f077fe548137b196bbe17428e3080cb4a5238ebb
[fw/openocd] / src / flash / nor / stm32f1x.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2008 by Spencer Oliver                                  *
6  *   spen@spen-soft.co.uk                                                  *
7  *                                                                         *
8  *   Copyright (C) 2011 by Andreas Fritiofson                              *
9  *   andreas.fritiofson@gmail.com                                          *
10  *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU General Public License as published by  *
13  *   the Free Software Foundation; either version 2 of the License, or     *
14  *   (at your option) any later version.                                   *
15  *                                                                         *
16  *   This program is distributed in the hope that it will be useful,       *
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
19  *   GNU General Public License for more details.                          *
20  *                                                                         *
21  *   You should have received a copy of the GNU General Public License     *
22  *   along with this program; if not, write to the                         *
23  *   Free Software Foundation, Inc.,                                       *
24  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
25  ***************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include "imp.h"
32 #include <helper/binarybuffer.h>
33 #include <target/algorithm.h>
34 #include <target/armv7m.h>
35
36 /* stm32x register locations */
37
38 #define FLASH_REG_BASE_B0 0x40022000
39 #define FLASH_REG_BASE_B1 0x40022040
40
41 #define STM32_FLASH_ACR     0x00
42 #define STM32_FLASH_KEYR    0x04
43 #define STM32_FLASH_OPTKEYR 0x08
44 #define STM32_FLASH_SR      0x0C
45 #define STM32_FLASH_CR      0x10
46 #define STM32_FLASH_AR      0x14
47 #define STM32_FLASH_OBR     0x1C
48 #define STM32_FLASH_WRPR    0x20
49
50 /* TODO: Check if code using these really should be hard coded to bank 0.
51  * There are valid cases, on dual flash devices the protection of the
52  * second bank is done on the bank0 reg's. */
53 #define STM32_FLASH_ACR_B0     0x40022000
54 #define STM32_FLASH_KEYR_B0    0x40022004
55 #define STM32_FLASH_OPTKEYR_B0 0x40022008
56 #define STM32_FLASH_SR_B0      0x4002200C
57 #define STM32_FLASH_CR_B0      0x40022010
58 #define STM32_FLASH_AR_B0      0x40022014
59 #define STM32_FLASH_OBR_B0     0x4002201C
60 #define STM32_FLASH_WRPR_B0    0x40022020
61
62 /* option byte location */
63
64 #define STM32_OB_RDP            0x1FFFF800
65 #define STM32_OB_USER           0x1FFFF802
66 #define STM32_OB_DATA0          0x1FFFF804
67 #define STM32_OB_DATA1          0x1FFFF806
68 #define STM32_OB_WRP0           0x1FFFF808
69 #define STM32_OB_WRP1           0x1FFFF80A
70 #define STM32_OB_WRP2           0x1FFFF80C
71 #define STM32_OB_WRP3           0x1FFFF80E
72
73 /* FLASH_CR register bits */
74
75 #define FLASH_PG                (1 << 0)
76 #define FLASH_PER               (1 << 1)
77 #define FLASH_MER               (1 << 2)
78 #define FLASH_OPTPG             (1 << 4)
79 #define FLASH_OPTER             (1 << 5)
80 #define FLASH_STRT              (1 << 6)
81 #define FLASH_LOCK              (1 << 7)
82 #define FLASH_OPTWRE    (1 << 9)
83
84 /* FLASH_SR register bits */
85
86 #define FLASH_BSY               (1 << 0)
87 #define FLASH_PGERR             (1 << 2)
88 #define FLASH_WRPRTERR  (1 << 4)
89 #define FLASH_EOP               (1 << 5)
90
91 /* STM32_FLASH_OBR bit definitions (reading) */
92
93 #define OPT_ERROR               0
94 #define OPT_READOUT             1
95 #define OPT_RDWDGSW             2
96 #define OPT_RDRSTSTOP   3
97 #define OPT_RDRSTSTDBY  4
98 #define OPT_BFB2                5       /* dual flash bank only */
99
100 /* register unlock keys */
101
102 #define KEY1                    0x45670123
103 #define KEY2                    0xCDEF89AB
104
105 struct stm32x_options {
106         uint16_t RDP;
107         uint16_t user_options;
108         uint16_t protection[4];
109 };
110
111 struct stm32x_flash_bank {
112         struct stm32x_options option_bytes;
113         struct working_area *write_algorithm;
114         int ppage_size;
115         int probed;
116
117         bool has_dual_banks;
118         /* used to access dual flash bank stm32xl */
119         uint32_t register_base;
120 };
121
122 static int stm32x_mass_erase(struct flash_bank *bank);
123 static int stm32x_get_device_id(struct flash_bank *bank, uint32_t *device_id);
124
125 /* flash bank stm32x <base> <size> 0 0 <target#>
126  */
127 FLASH_BANK_COMMAND_HANDLER(stm32x_flash_bank_command)
128 {
129         struct stm32x_flash_bank *stm32x_info;
130
131         if (CMD_ARGC < 6)
132                 return ERROR_COMMAND_SYNTAX_ERROR;
133
134         stm32x_info = malloc(sizeof(struct stm32x_flash_bank));
135
136         bank->driver_priv = stm32x_info;
137         stm32x_info->write_algorithm = NULL;
138         stm32x_info->probed = 0;
139         stm32x_info->has_dual_banks = false;
140         stm32x_info->register_base = FLASH_REG_BASE_B0;
141
142         return ERROR_OK;
143 }
144
145 static inline int stm32x_get_flash_reg(struct flash_bank *bank, uint32_t reg)
146 {
147         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
148         return reg + stm32x_info->register_base;
149 }
150
151 static inline int stm32x_get_flash_status(struct flash_bank *bank, uint32_t *status)
152 {
153         struct target *target = bank->target;
154         return target_read_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR), status);
155 }
156
157 static int stm32x_wait_status_busy(struct flash_bank *bank, int timeout)
158 {
159         struct target *target = bank->target;
160         uint32_t status;
161         int retval = ERROR_OK;
162
163         /* wait for busy to clear */
164         for (;;) {
165                 retval = stm32x_get_flash_status(bank, &status);
166                 if (retval != ERROR_OK)
167                         return retval;
168                 LOG_DEBUG("status: 0x%" PRIx32 "", status);
169                 if ((status & FLASH_BSY) == 0)
170                         break;
171                 if (timeout-- <= 0) {
172                         LOG_ERROR("timed out waiting for flash");
173                         return ERROR_FAIL;
174                 }
175                 alive_sleep(1);
176         }
177
178         if (status & FLASH_WRPRTERR) {
179                 LOG_ERROR("stm32x device protected");
180                 retval = ERROR_FAIL;
181         }
182
183         if (status & FLASH_PGERR) {
184                 LOG_ERROR("stm32x device programming failed");
185                 retval = ERROR_FAIL;
186         }
187
188         /* Clear but report errors */
189         if (status & (FLASH_WRPRTERR | FLASH_PGERR)) {
190                 /* If this operation fails, we ignore it and report the original
191                  * retval
192                  */
193                 target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR),
194                                 FLASH_WRPRTERR | FLASH_PGERR);
195         }
196         return retval;
197 }
198
199 int stm32x_check_operation_supported(struct flash_bank *bank)
200 {
201         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
202
203         /* if we have a dual flash bank device then
204          * we need to perform option byte stuff on bank0 only */
205         if (stm32x_info->register_base != FLASH_REG_BASE_B0) {
206                 LOG_ERROR("Option Byte Operation's must use bank0");
207                 return ERROR_FLASH_OPERATION_FAILED;
208         }
209
210         return ERROR_OK;
211 }
212
213 static int stm32x_read_options(struct flash_bank *bank)
214 {
215         uint32_t optiondata;
216         struct stm32x_flash_bank *stm32x_info = NULL;
217         struct target *target = bank->target;
218
219         stm32x_info = bank->driver_priv;
220
221         /* read current option bytes */
222         int retval = target_read_u32(target, STM32_FLASH_OBR_B0, &optiondata);
223         if (retval != ERROR_OK)
224                 return retval;
225
226         stm32x_info->option_bytes.user_options = (uint16_t)0xFFF8 | ((optiondata >> 2) & 0x07);
227         stm32x_info->option_bytes.RDP = (optiondata & (1 << OPT_READOUT)) ? 0xFFFF : 0x5AA5;
228
229         if (optiondata & (1 << OPT_READOUT))
230                 LOG_INFO("Device Security Bit Set");
231
232         /* each bit refers to a 4bank protection */
233         retval = target_read_u32(target, STM32_FLASH_WRPR_B0, &optiondata);
234         if (retval != ERROR_OK)
235                 return retval;
236
237         stm32x_info->option_bytes.protection[0] = (uint16_t)optiondata;
238         stm32x_info->option_bytes.protection[1] = (uint16_t)(optiondata >> 8);
239         stm32x_info->option_bytes.protection[2] = (uint16_t)(optiondata >> 16);
240         stm32x_info->option_bytes.protection[3] = (uint16_t)(optiondata >> 24);
241
242         return ERROR_OK;
243 }
244
245 static int stm32x_erase_options(struct flash_bank *bank)
246 {
247         struct stm32x_flash_bank *stm32x_info = NULL;
248         struct target *target = bank->target;
249
250         stm32x_info = bank->driver_priv;
251
252         /* stlink is currently does not support 16bit
253          * read/writes. so we cannot write option bytes */
254         struct armv7m_common *armv7m = target_to_armv7m(target);
255         if (armv7m && armv7m->stlink) {
256                 LOG_ERROR("Option bytes currently unsupported for stlink");
257                 return ERROR_FAIL;
258         }
259
260         /* read current options */
261         stm32x_read_options(bank);
262
263         /* unlock flash registers */
264         int retval = target_write_u32(target, STM32_FLASH_KEYR_B0, KEY1);
265         if (retval != ERROR_OK)
266                 return retval;
267
268         retval = target_write_u32(target, STM32_FLASH_KEYR_B0, KEY2);
269         if (retval != ERROR_OK)
270                 return retval;
271
272         /* unlock option flash registers */
273         retval = target_write_u32(target, STM32_FLASH_OPTKEYR_B0, KEY1);
274         if (retval != ERROR_OK)
275                 return retval;
276         retval = target_write_u32(target, STM32_FLASH_OPTKEYR_B0, KEY2);
277         if (retval != ERROR_OK)
278                 return retval;
279
280         /* erase option bytes */
281         retval = target_write_u32(target, STM32_FLASH_CR_B0, FLASH_OPTER | FLASH_OPTWRE);
282         if (retval != ERROR_OK)
283                 return retval;
284         retval = target_write_u32(target, STM32_FLASH_CR_B0, FLASH_OPTER | FLASH_STRT | FLASH_OPTWRE);
285         if (retval != ERROR_OK)
286                 return retval;
287
288         retval = stm32x_wait_status_busy(bank, 10);
289         if (retval != ERROR_OK)
290                 return retval;
291
292         /* clear readout protection and complementary option bytes
293          * this will also force a device unlock if set */
294         stm32x_info->option_bytes.RDP = 0x5AA5;
295
296         return ERROR_OK;
297 }
298
299 static int stm32x_write_options(struct flash_bank *bank)
300 {
301         struct stm32x_flash_bank *stm32x_info = NULL;
302         struct target *target = bank->target;
303
304         stm32x_info = bank->driver_priv;
305
306         /* unlock flash registers */
307         int retval = target_write_u32(target, STM32_FLASH_KEYR_B0, KEY1);
308         if (retval != ERROR_OK)
309                 return retval;
310         retval = target_write_u32(target, STM32_FLASH_KEYR_B0, KEY2);
311         if (retval != ERROR_OK)
312                 return retval;
313
314         /* unlock option flash registers */
315         retval = target_write_u32(target, STM32_FLASH_OPTKEYR_B0, KEY1);
316         if (retval != ERROR_OK)
317                 return retval;
318         retval = target_write_u32(target, STM32_FLASH_OPTKEYR_B0, KEY2);
319         if (retval != ERROR_OK)
320                 return retval;
321
322         /* program option bytes */
323         retval = target_write_u32(target, STM32_FLASH_CR_B0, FLASH_OPTPG | FLASH_OPTWRE);
324         if (retval != ERROR_OK)
325                 return retval;
326
327         /* write user option byte */
328         retval = target_write_u16(target, STM32_OB_USER, stm32x_info->option_bytes.user_options);
329         if (retval != ERROR_OK)
330                 return retval;
331
332         retval = stm32x_wait_status_busy(bank, 10);
333         if (retval != ERROR_OK)
334                 return retval;
335
336         /* write protection byte 1 */
337         retval = target_write_u16(target, STM32_OB_WRP0, stm32x_info->option_bytes.protection[0]);
338         if (retval != ERROR_OK)
339                 return retval;
340
341         retval = stm32x_wait_status_busy(bank, 10);
342         if (retval != ERROR_OK)
343                 return retval;
344
345         /* write protection byte 2 */
346         retval = target_write_u16(target, STM32_OB_WRP1, stm32x_info->option_bytes.protection[1]);
347         if (retval != ERROR_OK)
348                 return retval;
349
350         retval = stm32x_wait_status_busy(bank, 10);
351         if (retval != ERROR_OK)
352                 return retval;
353
354         /* write protection byte 3 */
355         retval = target_write_u16(target, STM32_OB_WRP2, stm32x_info->option_bytes.protection[2]);
356         if (retval != ERROR_OK)
357                 return retval;
358
359         retval = stm32x_wait_status_busy(bank, 10);
360         if (retval != ERROR_OK)
361                 return retval;
362
363         /* write protection byte 4 */
364         retval = target_write_u16(target, STM32_OB_WRP3, stm32x_info->option_bytes.protection[3]);
365         if (retval != ERROR_OK)
366                 return retval;
367
368         retval = stm32x_wait_status_busy(bank, 10);
369         if (retval != ERROR_OK)
370                 return retval;
371
372         /* write readout protection bit */
373         retval = target_write_u16(target, STM32_OB_RDP, stm32x_info->option_bytes.RDP);
374         if (retval != ERROR_OK)
375                 return retval;
376
377         retval = stm32x_wait_status_busy(bank, 10);
378         if (retval != ERROR_OK)
379                 return retval;
380
381         retval = target_write_u32(target, STM32_FLASH_CR_B0, FLASH_LOCK);
382         if (retval != ERROR_OK)
383                 return retval;
384
385         return ERROR_OK;
386 }
387
388 static int stm32x_protect_check(struct flash_bank *bank)
389 {
390         struct target *target = bank->target;
391         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
392
393         uint32_t protection;
394         int i, s;
395         int num_bits;
396         int set;
397
398         if (target->state != TARGET_HALTED) {
399                 LOG_ERROR("Target not halted");
400                 return ERROR_TARGET_NOT_HALTED;
401         }
402
403         int retval = stm32x_check_operation_supported(bank);
404         if (ERROR_OK != retval)
405                 return retval;
406
407         /* medium density - each bit refers to a 4bank protection
408          * high density - each bit refers to a 2bank protection */
409         retval = target_read_u32(target, STM32_FLASH_WRPR_B0, &protection);
410         if (retval != ERROR_OK)
411                 return retval;
412
413         /* medium density - each protection bit is for 4 * 1K pages
414          * high density - each protection bit is for 2 * 2K pages */
415         num_bits = (bank->num_sectors / stm32x_info->ppage_size);
416
417         if (stm32x_info->ppage_size == 2) {
418                 /* high density flash/connectivity line protection */
419
420                 set = 1;
421
422                 if (protection & (1 << 31))
423                         set = 0;
424
425                 /* bit 31 controls sector 62 - 255 protection for high density
426                  * bit 31 controls sector 62 - 127 protection for connectivity line */
427                 for (s = 62; s < bank->num_sectors; s++)
428                         bank->sectors[s].is_protected = set;
429
430                 if (bank->num_sectors > 61)
431                         num_bits = 31;
432
433                 for (i = 0; i < num_bits; i++) {
434                         set = 1;
435
436                         if (protection & (1 << i))
437                                 set = 0;
438
439                         for (s = 0; s < stm32x_info->ppage_size; s++)
440                                 bank->sectors[(i * stm32x_info->ppage_size) + s].is_protected = set;
441                 }
442         } else {
443                 /* low/medium density flash protection */
444                 for (i = 0; i < num_bits; i++) {
445                         set = 1;
446
447                         if (protection & (1 << i))
448                                 set = 0;
449
450                         for (s = 0; s < stm32x_info->ppage_size; s++)
451                                 bank->sectors[(i * stm32x_info->ppage_size) + s].is_protected = set;
452                 }
453         }
454
455         return ERROR_OK;
456 }
457
458 static int stm32x_erase(struct flash_bank *bank, int first, int last)
459 {
460         struct target *target = bank->target;
461         int i;
462
463         if (bank->target->state != TARGET_HALTED) {
464                 LOG_ERROR("Target not halted");
465                 return ERROR_TARGET_NOT_HALTED;
466         }
467
468         if ((first == 0) && (last == (bank->num_sectors - 1)))
469                 return stm32x_mass_erase(bank);
470
471         /* unlock flash registers */
472         int retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_KEYR), KEY1);
473         if (retval != ERROR_OK)
474                 return retval;
475         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_KEYR), KEY2);
476         if (retval != ERROR_OK)
477                 return retval;
478
479         for (i = first; i <= last; i++) {
480                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_PER);
481                 if (retval != ERROR_OK)
482                         return retval;
483                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_AR),
484                                 bank->base + bank->sectors[i].offset);
485                 if (retval != ERROR_OK)
486                         return retval;
487                 retval = target_write_u32(target,
488                                 stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_PER | FLASH_STRT);
489                 if (retval != ERROR_OK)
490                         return retval;
491
492                 retval = stm32x_wait_status_busy(bank, 100);
493                 if (retval != ERROR_OK)
494                         return retval;
495
496                 bank->sectors[i].is_erased = 1;
497         }
498
499         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
500         if (retval != ERROR_OK)
501                 return retval;
502
503         return ERROR_OK;
504 }
505
506 static int stm32x_protect(struct flash_bank *bank, int set, int first, int last)
507 {
508         struct stm32x_flash_bank *stm32x_info = NULL;
509         struct target *target = bank->target;
510         uint16_t prot_reg[4] = {0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF};
511         int i, reg, bit;
512         int status;
513         uint32_t protection;
514
515         stm32x_info = bank->driver_priv;
516
517         if (target->state != TARGET_HALTED) {
518                 LOG_ERROR("Target not halted");
519                 return ERROR_TARGET_NOT_HALTED;
520         }
521
522         int retval = stm32x_check_operation_supported(bank);
523         if (ERROR_OK != retval)
524                 return retval;
525
526         if ((first % stm32x_info->ppage_size) != 0) {
527                 LOG_WARNING("aligned start protect sector to a %d sector boundary",
528                                 stm32x_info->ppage_size);
529                 first = first - (first % stm32x_info->ppage_size);
530         }
531         if (((last + 1) % stm32x_info->ppage_size) != 0) {
532                 LOG_WARNING("aligned end protect sector to a %d sector boundary",
533                                 stm32x_info->ppage_size);
534                 last++;
535                 last = last - (last % stm32x_info->ppage_size);
536                 last--;
537         }
538
539         /* medium density - each bit refers to a 4bank protection
540          * high density - each bit refers to a 2bank protection */
541         retval = target_read_u32(target, STM32_FLASH_WRPR_B0, &protection);
542         if (retval != ERROR_OK)
543                 return retval;
544
545         prot_reg[0] = (uint16_t)protection;
546         prot_reg[1] = (uint16_t)(protection >> 8);
547         prot_reg[2] = (uint16_t)(protection >> 16);
548         prot_reg[3] = (uint16_t)(protection >> 24);
549
550         if (stm32x_info->ppage_size == 2) {
551                 /* high density flash */
552
553                 /* bit 7 controls sector 62 - 255 protection */
554                 if (last > 61) {
555                         if (set)
556                                 prot_reg[3] &= ~(1 << 7);
557                         else
558                                 prot_reg[3] |= (1 << 7);
559                 }
560
561                 if (first > 61)
562                         first = 62;
563                 if (last > 61)
564                         last = 61;
565
566                 for (i = first; i <= last; i++) {
567                         reg = (i / stm32x_info->ppage_size) / 8;
568                         bit = (i / stm32x_info->ppage_size) - (reg * 8);
569
570                         if (set)
571                                 prot_reg[reg] &= ~(1 << bit);
572                         else
573                                 prot_reg[reg] |= (1 << bit);
574                 }
575         } else {
576                 /* medium density flash */
577                 for (i = first; i <= last; i++) {
578                         reg = (i / stm32x_info->ppage_size) / 8;
579                         bit = (i / stm32x_info->ppage_size) - (reg * 8);
580
581                         if (set)
582                                 prot_reg[reg] &= ~(1 << bit);
583                         else
584                                 prot_reg[reg] |= (1 << bit);
585                 }
586         }
587
588         status = stm32x_erase_options(bank);
589         if (status != ERROR_OK)
590                 return status;
591
592         stm32x_info->option_bytes.protection[0] = prot_reg[0];
593         stm32x_info->option_bytes.protection[1] = prot_reg[1];
594         stm32x_info->option_bytes.protection[2] = prot_reg[2];
595         stm32x_info->option_bytes.protection[3] = prot_reg[3];
596
597         return stm32x_write_options(bank);
598 }
599
600 static int stm32x_write_block(struct flash_bank *bank, uint8_t *buffer,
601                 uint32_t offset, uint32_t count)
602 {
603         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
604         struct target *target = bank->target;
605         uint32_t buffer_size = 16384;
606         struct working_area *source;
607         uint32_t address = bank->base + offset;
608         struct reg_param reg_params[5];
609         struct armv7m_algorithm armv7m_info;
610         int retval = ERROR_OK;
611
612         /* see contrib/loaders/flash/stm32f1x.S for src */
613
614         static const uint8_t stm32x_flash_write_code[] = {
615                 /* #define STM32_FLASH_SR_OFFSET 0x0C */
616                 /* wait_fifo: */
617                         0x16, 0x68,   /* ldr   r6, [r2, #0] */
618                         0x00, 0x2e,   /* cmp   r6, #0 */
619                         0x18, 0xd0,   /* beq   exit */
620                         0x55, 0x68,   /* ldr   r5, [r2, #4] */
621                         0xb5, 0x42,   /* cmp   r5, r6 */
622                         0xf9, 0xd0,   /* beq   wait_fifo */
623                         0x2e, 0x88,   /* ldrh  r6, [r5, #0] */
624                         0x26, 0x80,   /* strh  r6, [r4, #0] */
625                         0x02, 0x35,   /* adds  r5, #2 */
626                         0x02, 0x34,   /* adds  r4, #2 */
627                 /* busy: */
628                         0xc6, 0x68,   /* ldr   r6, [r0, #STM32_FLASH_SR_OFFSET] */
629                         0x01, 0x27,   /* movs  r7, #1 */
630                         0x3e, 0x42,   /* tst   r6, r7 */
631                         0xfb, 0xd1,   /* bne   busy */
632                         0x14, 0x27,   /* movs  r7, #0x14 */
633                         0x3e, 0x42,   /* tst   r6, r7 */
634                         0x08, 0xd1,   /* bne   error */
635                         0x9d, 0x42,   /* cmp   r5, r3 */
636                         0x01, 0xd3,   /* bcc   no_wrap */
637                         0x15, 0x46,   /* mov   r5, r2 */
638                         0x08, 0x35,   /* adds  r5, #8 */
639                 /* no_wrap: */
640                         0x55, 0x60,   /* str   r5, [r2, #4] */
641                         0x01, 0x39,   /* subs  r1, r1, #1 */
642                         0x00, 0x29,   /* cmp   r1, #0 */
643                         0x02, 0xd0,   /* beq   exit */
644                         0xe5, 0xe7,   /* b     wait_fifo */
645                 /* error: */
646                         0x00, 0x20,   /* movs  r0, #0 */
647                         0x50, 0x60,   /* str   r0, [r2, #4] */
648                 /* exit: */
649                         0x30, 0x46,   /* mov   r0, r6 */
650                         0x00, 0xbe,   /* bkpt  #0 */
651         };
652
653         /* flash write code */
654         if (target_alloc_working_area(target, sizeof(stm32x_flash_write_code),
655                         &stm32x_info->write_algorithm) != ERROR_OK) {
656                 LOG_WARNING("no working area available, can't do block memory writes");
657                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
658         };
659
660         retval = target_write_buffer(target, stm32x_info->write_algorithm->address,
661                         sizeof(stm32x_flash_write_code), (uint8_t *)stm32x_flash_write_code);
662         if (retval != ERROR_OK)
663                 return retval;
664
665         /* memory buffer */
666         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) {
667                 buffer_size /= 2;
668                 buffer_size &= ~3UL; /* Make sure it's 4 byte aligned */
669                 if (buffer_size <= 256) {
670                         /* if we already allocated the writing code, but failed to get a
671                          * buffer, free the algorithm */
672                         if (stm32x_info->write_algorithm)
673                                 target_free_working_area(target, stm32x_info->write_algorithm);
674
675                         LOG_WARNING("no large enough working area available, can't do block memory writes");
676                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
677                 }
678         };
679
680         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT); /* flash base (in), status (out) */
681         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);    /* count (halfword-16bit) */
682         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);    /* buffer start */
683         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);    /* buffer end */
684         init_reg_param(&reg_params[4], "r4", 32, PARAM_IN_OUT); /* target address */
685
686         buf_set_u32(reg_params[0].value, 0, 32, stm32x_info->register_base);
687         buf_set_u32(reg_params[1].value, 0, 32, count);
688         buf_set_u32(reg_params[2].value, 0, 32, source->address);
689         buf_set_u32(reg_params[3].value, 0, 32, source->address + source->size);
690         buf_set_u32(reg_params[4].value, 0, 32, address);
691
692         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
693         armv7m_info.core_mode = ARMV7M_MODE_ANY;
694
695         retval = target_run_flash_async_algorithm(target, buffer, count, 2,
696                         0, NULL,
697                         5, reg_params,
698                         source->address, source->size,
699                         stm32x_info->write_algorithm->address, 0,
700                         &armv7m_info);
701
702         if (retval == ERROR_FLASH_OPERATION_FAILED) {
703                 LOG_ERROR("flash write failed at address 0x%"PRIx32,
704                                 buf_get_u32(reg_params[4].value, 0, 32));
705
706                 if (buf_get_u32(reg_params[0].value, 0, 32) & FLASH_PGERR) {
707                         LOG_ERROR("flash memory not erased before writing");
708                         /* Clear but report errors */
709                         target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR), FLASH_PGERR);
710                 }
711
712                 if (buf_get_u32(reg_params[0].value, 0, 32) & FLASH_WRPRTERR) {
713                         LOG_ERROR("flash memory write protected");
714                         /* Clear but report errors */
715                         target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR), FLASH_WRPRTERR);
716                 }
717         }
718
719         target_free_working_area(target, source);
720         target_free_working_area(target, stm32x_info->write_algorithm);
721
722         destroy_reg_param(&reg_params[0]);
723         destroy_reg_param(&reg_params[1]);
724         destroy_reg_param(&reg_params[2]);
725         destroy_reg_param(&reg_params[3]);
726         destroy_reg_param(&reg_params[4]);
727
728         return retval;
729 }
730
731 static int stm32x_write(struct flash_bank *bank, uint8_t *buffer,
732                 uint32_t offset, uint32_t count)
733 {
734         struct target *target = bank->target;
735         uint8_t *new_buffer = NULL;
736
737         if (bank->target->state != TARGET_HALTED) {
738                 LOG_ERROR("Target not halted");
739                 return ERROR_TARGET_NOT_HALTED;
740         }
741
742         if (offset & 0x1) {
743                 LOG_ERROR("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
744                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
745         }
746
747         /* If there's an odd number of bytes, the data has to be padded. Duplicate
748          * the buffer and use the normal code path with a single block write since
749          * it's probably cheaper than to special case the last odd write using
750          * discrete accesses. */
751         if (count & 1) {
752                 new_buffer = malloc(count + 1);
753                 if (new_buffer == NULL) {
754                         LOG_ERROR("odd number of bytes to write and no memory for padding buffer");
755                         return ERROR_FAIL;
756                 }
757                 LOG_INFO("odd number of bytes to write, padding with 0xff");
758                 buffer = memcpy(new_buffer, buffer, count);
759                 buffer[count++] = 0xff;
760         }
761
762         uint32_t words_remaining = count / 2;
763         int retval, retval2;
764
765         /* unlock flash registers */
766         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_KEYR), KEY1);
767         if (retval != ERROR_OK)
768                 goto cleanup;
769         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_KEYR), KEY2);
770         if (retval != ERROR_OK)
771                 goto cleanup;
772
773         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_PG);
774         if (retval != ERROR_OK)
775                 goto cleanup;
776
777         /* try using a block write */
778         retval = stm32x_write_block(bank, buffer, offset, words_remaining);
779
780         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
781                 /* if block write failed (no sufficient working area),
782                  * we use normal (slow) single halfword accesses */
783                 LOG_WARNING("couldn't use block writes, falling back to single memory accesses");
784
785                 while (words_remaining > 0) {
786                         uint16_t value;
787                         memcpy(&value, buffer, sizeof(uint16_t));
788
789                         retval = target_write_u16(target, bank->base + offset, value);
790                         if (retval != ERROR_OK)
791                                 goto reset_pg_and_lock;
792
793                         retval = stm32x_wait_status_busy(bank, 5);
794                         if (retval != ERROR_OK)
795                                 goto reset_pg_and_lock;
796
797                         words_remaining--;
798                         buffer += 2;
799                         offset += 2;
800                 }
801         }
802
803 reset_pg_and_lock:
804         retval2 = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
805         if (retval == ERROR_OK)
806                 retval = retval2;
807
808 cleanup:
809         if (new_buffer)
810                 free(new_buffer);
811
812         return retval;
813 }
814
815 static int stm32x_get_device_id(struct flash_bank *bank, uint32_t *device_id)
816 {
817         /* This check the device CPUID core register to detect
818          * the M0 from the M3 devices. */
819
820         struct target *target = bank->target;
821         uint32_t cpuid, device_id_register = 0;
822
823         /* Get the CPUID from the ARM Core
824          * http://infocenter.arm.com/help/topic/com.arm.doc.ddi0432c/DDI0432C_cortex_m0_r0p0_trm.pdf 4.2.1 */
825         int retval = target_read_u32(target, 0xE000ED00, &cpuid);
826         if (retval != ERROR_OK)
827                 return retval;
828
829         if (((cpuid >> 4) & 0xFFF) == 0xC20) {
830                 /* 0xC20 is M0 devices */
831                 device_id_register = 0x40015800;
832         } else if (((cpuid >> 4) & 0xFFF) == 0xC23) {
833                 /* 0xC23 is M3 devices */
834                 device_id_register = 0xE0042000;
835         } else if (((cpuid >> 4) & 0xFFF) == 0xC24) {
836                 /* 0xC24 is M4 devices */
837                 device_id_register = 0xE0042000;
838         } else {
839                 LOG_ERROR("Cannot identify target as a stm32x");
840                 return ERROR_FAIL;
841         }
842
843         /* read stm32 device id register */
844         retval = target_read_u32(target, device_id_register, device_id);
845         if (retval != ERROR_OK)
846                 return retval;
847
848         return retval;
849 }
850
851 static int stm32x_get_flash_size(struct flash_bank *bank, uint16_t *flash_size_in_kb)
852 {
853         struct target *target = bank->target;
854         uint32_t cpuid, flash_size_reg;
855
856         int retval = target_read_u32(target, 0xE000ED00, &cpuid);
857         if (retval != ERROR_OK)
858                 return retval;
859
860         if (((cpuid >> 4) & 0xFFF) == 0xC20) {
861                 /* 0xC20 is M0 devices */
862                 flash_size_reg = 0x1FFFF7CC;
863         } else if (((cpuid >> 4) & 0xFFF) == 0xC23) {
864                 /* 0xC23 is M3 devices */
865                 flash_size_reg = 0x1FFFF7E0;
866         } else if (((cpuid >> 4) & 0xFFF) == 0xC24) {
867                 /* 0xC24 is M4 devices */
868                 flash_size_reg = 0x1FFFF7CC;
869         } else {
870                 LOG_ERROR("Cannot identify target as a stm32x");
871                 return ERROR_FAIL;
872         }
873
874         retval = target_read_u16(target, flash_size_reg, flash_size_in_kb);
875         if (retval != ERROR_OK)
876                 return retval;
877
878         return retval;
879 }
880
881 static int stm32x_probe(struct flash_bank *bank)
882 {
883         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
884         int i;
885         uint16_t flash_size_in_kb;
886         uint16_t max_flash_size_in_kb;
887         uint32_t device_id;
888         int page_size;
889         uint32_t base_address = 0x08000000;
890
891         stm32x_info->probed = 0;
892         stm32x_info->register_base = FLASH_REG_BASE_B0;
893
894         /* read stm32 device id register */
895         int retval = stm32x_get_device_id(bank, &device_id);
896         if (retval != ERROR_OK)
897                 return retval;
898
899         LOG_INFO("device id = 0x%08" PRIx32 "", device_id);
900
901         /* set page size, protection granularity and max flash size depending on family */
902         switch (device_id & 0xfff) {
903         case 0x410: /* medium density */
904                 page_size = 1024;
905                 stm32x_info->ppage_size = 4;
906                 max_flash_size_in_kb = 128;
907                 break;
908         case 0x412: /* low density */
909                 page_size = 1024;
910                 stm32x_info->ppage_size = 4;
911                 max_flash_size_in_kb = 32;
912                 break;
913         case 0x414: /* high density */
914                 page_size = 2048;
915                 stm32x_info->ppage_size = 2;
916                 max_flash_size_in_kb = 512;
917                 break;
918         case 0x418: /* connectivity line density */
919                 page_size = 2048;
920                 stm32x_info->ppage_size = 2;
921                 max_flash_size_in_kb = 256;
922                 break;
923         case 0x420: /* value line density */
924                 page_size = 1024;
925                 stm32x_info->ppage_size = 4;
926                 max_flash_size_in_kb = 128;
927                 break;
928         case 0x422: /* stm32f30x */
929                 page_size = 2048;
930                 stm32x_info->ppage_size = 2;
931                 max_flash_size_in_kb = 256;
932                 break;
933         case 0x428: /* value line High density */
934                 page_size = 2048;
935                 stm32x_info->ppage_size = 4;
936                 max_flash_size_in_kb = 128;
937                 break;
938         case 0x430: /* xl line density (dual flash banks) */
939                 page_size = 2048;
940                 stm32x_info->ppage_size = 2;
941                 max_flash_size_in_kb = 1024;
942                 stm32x_info->has_dual_banks = true;
943                 break;
944         case 0x432: /* stm32f37x */
945                 page_size = 2048;
946                 stm32x_info->ppage_size = 2;
947                 max_flash_size_in_kb = 256;
948                 break;
949         case 0x440: /* stm32f0x */
950                 page_size = 1024;
951                 stm32x_info->ppage_size = 4;
952                 max_flash_size_in_kb = 64;
953                 break;
954         default:
955                 LOG_WARNING("Cannot identify target as a STM32 family.");
956                 return ERROR_FAIL;
957         }
958
959         /* get flash size from target. */
960         retval = stm32x_get_flash_size(bank, &flash_size_in_kb);
961
962         /* failed reading flash size or flash size invalid (early silicon),
963          * default to max target family */
964         if (retval != ERROR_OK || flash_size_in_kb == 0xffff || flash_size_in_kb == 0) {
965                 LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming %dk flash",
966                         max_flash_size_in_kb);
967                 flash_size_in_kb = max_flash_size_in_kb;
968         }
969
970         if (stm32x_info->has_dual_banks) {
971                 /* split reported size into matching bank */
972                 if (bank->base != 0x08080000) {
973                         /* bank 0 will be fixed 512k */
974                         flash_size_in_kb = 512;
975                 } else {
976                         flash_size_in_kb -= 512;
977                         /* bank1 also uses a register offset */
978                         stm32x_info->register_base = FLASH_REG_BASE_B1;
979                         base_address = 0x08080000;
980                 }
981         }
982
983         LOG_INFO("flash size = %dkbytes", flash_size_in_kb);
984
985         /* did we assign flash size? */
986         assert(flash_size_in_kb != 0xffff);
987
988         /* calculate numbers of pages */
989         int num_pages = flash_size_in_kb * 1024 / page_size;
990
991         /* check that calculation result makes sense */
992         assert(num_pages > 0);
993
994         if (bank->sectors) {
995                 free(bank->sectors);
996                 bank->sectors = NULL;
997         }
998
999         bank->base = base_address;
1000         bank->size = (num_pages * page_size);
1001         bank->num_sectors = num_pages;
1002         bank->sectors = malloc(sizeof(struct flash_sector) * num_pages);
1003
1004         for (i = 0; i < num_pages; i++) {
1005                 bank->sectors[i].offset = i * page_size;
1006                 bank->sectors[i].size = page_size;
1007                 bank->sectors[i].is_erased = -1;
1008                 bank->sectors[i].is_protected = 1;
1009         }
1010
1011         stm32x_info->probed = 1;
1012
1013         return ERROR_OK;
1014 }
1015
1016 static int stm32x_auto_probe(struct flash_bank *bank)
1017 {
1018         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
1019         if (stm32x_info->probed)
1020                 return ERROR_OK;
1021         return stm32x_probe(bank);
1022 }
1023
1024 #if 0
1025 COMMAND_HANDLER(stm32x_handle_part_id_command)
1026 {
1027         return ERROR_OK;
1028 }
1029 #endif
1030
1031 static int get_stm32x_info(struct flash_bank *bank, char *buf, int buf_size)
1032 {
1033         uint32_t device_id;
1034         int printed;
1035
1036                 /* read stm32 device id register */
1037         int retval = stm32x_get_device_id(bank, &device_id);
1038         if (retval != ERROR_OK)
1039                 return retval;
1040
1041         if ((device_id & 0xfff) == 0x410) {
1042                 printed = snprintf(buf, buf_size, "stm32x (Medium Density) - Rev: ");
1043                 buf += printed;
1044                 buf_size -= printed;
1045
1046                 switch (device_id >> 16) {
1047                         case 0x0000:
1048                                 snprintf(buf, buf_size, "A");
1049                                 break;
1050
1051                         case 0x2000:
1052                                 snprintf(buf, buf_size, "B");
1053                                 break;
1054
1055                         case 0x2001:
1056                                 snprintf(buf, buf_size, "Z");
1057                                 break;
1058
1059                         case 0x2003:
1060                                 snprintf(buf, buf_size, "Y");
1061                                 break;
1062
1063                         default:
1064                                 snprintf(buf, buf_size, "unknown");
1065                                 break;
1066                 }
1067         } else if ((device_id & 0xfff) == 0x412) {
1068                 printed = snprintf(buf, buf_size, "stm32x (Low Density) - Rev: ");
1069                 buf += printed;
1070                 buf_size -= printed;
1071
1072                 switch (device_id >> 16) {
1073                         case 0x1000:
1074                                 snprintf(buf, buf_size, "A");
1075                                 break;
1076
1077                         default:
1078                                 snprintf(buf, buf_size, "unknown");
1079                                 break;
1080                 }
1081         } else if ((device_id & 0xfff) == 0x414) {
1082                 printed = snprintf(buf, buf_size, "stm32x (High Density) - Rev: ");
1083                 buf += printed;
1084                 buf_size -= printed;
1085
1086                 switch (device_id >> 16) {
1087                         case 0x1000:
1088                                 snprintf(buf, buf_size, "A");
1089                                 break;
1090
1091                         case 0x1001:
1092                                 snprintf(buf, buf_size, "Z");
1093                                 break;
1094
1095                         default:
1096                                 snprintf(buf, buf_size, "unknown");
1097                                 break;
1098                 }
1099         } else if ((device_id & 0xfff) == 0x418) {
1100                 printed = snprintf(buf, buf_size, "stm32x (Connectivity) - Rev: ");
1101                 buf += printed;
1102                 buf_size -= printed;
1103
1104                 switch (device_id >> 16) {
1105                         case 0x1000:
1106                                 snprintf(buf, buf_size, "A");
1107                                 break;
1108
1109                         case 0x1001:
1110                                 snprintf(buf, buf_size, "Z");
1111                                 break;
1112
1113                         default:
1114                                 snprintf(buf, buf_size, "unknown");
1115                                 break;
1116                 }
1117         } else if ((device_id & 0xfff) == 0x420) {
1118                 printed = snprintf(buf, buf_size, "stm32x (Value) - Rev: ");
1119                 buf += printed;
1120                 buf_size -= printed;
1121
1122                 switch (device_id >> 16) {
1123                         case 0x1000:
1124                                 snprintf(buf, buf_size, "A");
1125                                 break;
1126
1127                         case 0x1001:
1128                                 snprintf(buf, buf_size, "Z");
1129                                 break;
1130
1131                         default:
1132                                 snprintf(buf, buf_size, "unknown");
1133                                 break;
1134                 }
1135         } else if ((device_id & 0xfff) == 0x422) {
1136                 printed = snprintf(buf, buf_size, "stm32f30x - Rev: ");
1137                 buf += printed;
1138                 buf_size -= printed;
1139
1140                 switch (device_id >> 16) {
1141                         case 0x1000:
1142                                 snprintf(buf, buf_size, "1.0");
1143                                 break;
1144
1145                         default:
1146                                 snprintf(buf, buf_size, "unknown");
1147                                 break;
1148                 }
1149         } else if ((device_id & 0xfff) == 0x428) {
1150                 printed = snprintf(buf, buf_size, "stm32x (Value HD) - Rev: ");
1151                 buf += printed;
1152                 buf_size -= printed;
1153
1154                 switch (device_id >> 16) {
1155                         case 0x1000:
1156                                 snprintf(buf, buf_size, "A");
1157                                 break;
1158
1159                         case 0x1001:
1160                                 snprintf(buf, buf_size, "Z");
1161                                 break;
1162
1163                         default:
1164                                 snprintf(buf, buf_size, "unknown");
1165                                 break;
1166                 }
1167         } else if ((device_id & 0xfff) == 0x430) {
1168                 printed = snprintf(buf, buf_size, "stm32x (XL) - Rev: ");
1169                 buf += printed;
1170                 buf_size -= printed;
1171
1172                 switch (device_id >> 16) {
1173                         case 0x1000:
1174                                 snprintf(buf, buf_size, "A");
1175                                 break;
1176
1177                         default:
1178                                 snprintf(buf, buf_size, "unknown");
1179                                 break;
1180                 }
1181         } else if ((device_id & 0xfff) == 0x432) {
1182                 printed = snprintf(buf, buf_size, "stm32f37x - Rev: ");
1183                 buf += printed;
1184                 buf_size -= printed;
1185
1186                 switch (device_id >> 16) {
1187                         case 0x1000:
1188                                 snprintf(buf, buf_size, "1.0");
1189                                 break;
1190
1191                         default:
1192                                 snprintf(buf, buf_size, "unknown");
1193                                 break;
1194                 }
1195         } else if ((device_id & 0xfff) == 0x440) {
1196                 printed = snprintf(buf, buf_size, "stm32f0x - Rev: ");
1197                 buf += printed;
1198                 buf_size -= printed;
1199
1200                 switch (device_id >> 16) {
1201                         case 0x1000:
1202                                 snprintf(buf, buf_size, "1.0");
1203                                 break;
1204
1205                         case 0x2000:
1206                                 snprintf(buf, buf_size, "2.0");
1207                                 break;
1208
1209                         default:
1210                                 snprintf(buf, buf_size, "unknown");
1211                                 break;
1212                 }
1213         } else {
1214                 snprintf(buf, buf_size, "Cannot identify target as a stm32x\n");
1215                 return ERROR_FAIL;
1216         }
1217
1218         return ERROR_OK;
1219 }
1220
1221 COMMAND_HANDLER(stm32x_handle_lock_command)
1222 {
1223         struct target *target = NULL;
1224         struct stm32x_flash_bank *stm32x_info = NULL;
1225
1226         if (CMD_ARGC < 1)
1227                 return ERROR_COMMAND_SYNTAX_ERROR;
1228
1229         struct flash_bank *bank;
1230         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1231         if (ERROR_OK != retval)
1232                 return retval;
1233
1234         stm32x_info = bank->driver_priv;
1235
1236         target = bank->target;
1237
1238         if (target->state != TARGET_HALTED) {
1239                 LOG_ERROR("Target not halted");
1240                 return ERROR_TARGET_NOT_HALTED;
1241         }
1242
1243         retval = stm32x_check_operation_supported(bank);
1244         if (ERROR_OK != retval)
1245                 return retval;
1246
1247         if (stm32x_erase_options(bank) != ERROR_OK) {
1248                 command_print(CMD_CTX, "stm32x failed to erase options");
1249                 return ERROR_OK;
1250         }
1251
1252         /* set readout protection */
1253         stm32x_info->option_bytes.RDP = 0;
1254
1255         if (stm32x_write_options(bank) != ERROR_OK) {
1256                 command_print(CMD_CTX, "stm32x failed to lock device");
1257                 return ERROR_OK;
1258         }
1259
1260         command_print(CMD_CTX, "stm32x locked");
1261
1262         return ERROR_OK;
1263 }
1264
1265 COMMAND_HANDLER(stm32x_handle_unlock_command)
1266 {
1267         struct target *target = NULL;
1268
1269         if (CMD_ARGC < 1)
1270                 return ERROR_COMMAND_SYNTAX_ERROR;
1271
1272         struct flash_bank *bank;
1273         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1274         if (ERROR_OK != retval)
1275                 return retval;
1276
1277         target = bank->target;
1278
1279         if (target->state != TARGET_HALTED) {
1280                 LOG_ERROR("Target not halted");
1281                 return ERROR_TARGET_NOT_HALTED;
1282         }
1283
1284         retval = stm32x_check_operation_supported(bank);
1285         if (ERROR_OK != retval)
1286                 return retval;
1287
1288         if (stm32x_erase_options(bank) != ERROR_OK) {
1289                 command_print(CMD_CTX, "stm32x failed to unlock device");
1290                 return ERROR_OK;
1291         }
1292
1293         if (stm32x_write_options(bank) != ERROR_OK) {
1294                 command_print(CMD_CTX, "stm32x failed to lock device");
1295                 return ERROR_OK;
1296         }
1297
1298         command_print(CMD_CTX, "stm32x unlocked.\n"
1299                         "INFO: a reset or power cycle is required "
1300                         "for the new settings to take effect.");
1301
1302         return ERROR_OK;
1303 }
1304
1305 COMMAND_HANDLER(stm32x_handle_options_read_command)
1306 {
1307         uint32_t optionbyte;
1308         struct target *target = NULL;
1309         struct stm32x_flash_bank *stm32x_info = NULL;
1310
1311         if (CMD_ARGC < 1)
1312                 return ERROR_COMMAND_SYNTAX_ERROR;
1313
1314         struct flash_bank *bank;
1315         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1316         if (ERROR_OK != retval)
1317                 return retval;
1318
1319         stm32x_info = bank->driver_priv;
1320
1321         target = bank->target;
1322
1323         if (target->state != TARGET_HALTED) {
1324                 LOG_ERROR("Target not halted");
1325                 return ERROR_TARGET_NOT_HALTED;
1326         }
1327
1328         retval = stm32x_check_operation_supported(bank);
1329         if (ERROR_OK != retval)
1330                 return retval;
1331
1332         retval = target_read_u32(target, STM32_FLASH_OBR_B0, &optionbyte);
1333         if (retval != ERROR_OK)
1334                 return retval;
1335         command_print(CMD_CTX, "Option Byte: 0x%" PRIx32 "", optionbyte);
1336
1337         if (buf_get_u32((uint8_t *)&optionbyte, OPT_ERROR, 1))
1338                 command_print(CMD_CTX, "Option Byte Complement Error");
1339
1340         if (buf_get_u32((uint8_t *)&optionbyte, OPT_READOUT, 1))
1341                 command_print(CMD_CTX, "Readout Protection On");
1342         else
1343                 command_print(CMD_CTX, "Readout Protection Off");
1344
1345         if (buf_get_u32((uint8_t *)&optionbyte, OPT_RDWDGSW, 1))
1346                 command_print(CMD_CTX, "Software Watchdog");
1347         else
1348                 command_print(CMD_CTX, "Hardware Watchdog");
1349
1350         if (buf_get_u32((uint8_t *)&optionbyte, OPT_RDRSTSTOP, 1))
1351                 command_print(CMD_CTX, "Stop: No reset generated");
1352         else
1353                 command_print(CMD_CTX, "Stop: Reset generated");
1354
1355         if (buf_get_u32((uint8_t *)&optionbyte, OPT_RDRSTSTDBY, 1))
1356                 command_print(CMD_CTX, "Standby: No reset generated");
1357         else
1358                 command_print(CMD_CTX, "Standby: Reset generated");
1359
1360         if (stm32x_info->has_dual_banks) {
1361                 if (buf_get_u32((uint8_t *)&optionbyte, OPT_BFB2, 1))
1362                         command_print(CMD_CTX, "Boot: Bank 0");
1363                 else
1364                         command_print(CMD_CTX, "Boot: Bank 1");
1365         }
1366
1367         return ERROR_OK;
1368 }
1369
1370 COMMAND_HANDLER(stm32x_handle_options_write_command)
1371 {
1372         struct target *target = NULL;
1373         struct stm32x_flash_bank *stm32x_info = NULL;
1374         uint16_t optionbyte = 0xF8;
1375
1376         if (CMD_ARGC < 4)
1377                 return ERROR_COMMAND_SYNTAX_ERROR;
1378
1379         struct flash_bank *bank;
1380         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1381         if (ERROR_OK != retval)
1382                 return retval;
1383
1384         stm32x_info = bank->driver_priv;
1385
1386         target = bank->target;
1387
1388         if (target->state != TARGET_HALTED) {
1389                 LOG_ERROR("Target not halted");
1390                 return ERROR_TARGET_NOT_HALTED;
1391         }
1392
1393         retval = stm32x_check_operation_supported(bank);
1394         if (ERROR_OK != retval)
1395                 return retval;
1396
1397         /* REVISIT: ignores some options which we will display...
1398          * and doesn't insist on the specified syntax.
1399          */
1400
1401         /* OPT_RDWDGSW */
1402         if (strcmp(CMD_ARGV[1], "SWWDG") == 0)
1403                 optionbyte |= (1 << 0);
1404         else    /* REVISIT must be "HWWDG" then ... */
1405                 optionbyte &= ~(1 << 0);
1406
1407         /* OPT_RDRSTSTOP */
1408         if (strcmp(CMD_ARGV[2], "NORSTSTOP") == 0)
1409                 optionbyte |= (1 << 1);
1410         else    /* REVISIT must be "RSTSTNDBY" then ... */
1411                 optionbyte &= ~(1 << 1);
1412
1413         /* OPT_RDRSTSTDBY */
1414         if (strcmp(CMD_ARGV[3], "NORSTSTNDBY") == 0)
1415                 optionbyte |= (1 << 2);
1416         else    /* REVISIT must be "RSTSTOP" then ... */
1417                 optionbyte &= ~(1 << 2);
1418
1419         if (CMD_ARGC > 4 && stm32x_info->has_dual_banks) {
1420                 /* OPT_BFB2 */
1421                 if (strcmp(CMD_ARGV[4], "BOOT0") == 0)
1422                         optionbyte |= (1 << 3);
1423                 else
1424                         optionbyte &= ~(1 << 3);
1425         }
1426
1427         if (stm32x_erase_options(bank) != ERROR_OK) {
1428                 command_print(CMD_CTX, "stm32x failed to erase options");
1429                 return ERROR_OK;
1430         }
1431
1432         stm32x_info->option_bytes.user_options = optionbyte;
1433
1434         if (stm32x_write_options(bank) != ERROR_OK) {
1435                 command_print(CMD_CTX, "stm32x failed to write options");
1436                 return ERROR_OK;
1437         }
1438
1439         command_print(CMD_CTX, "stm32x write options complete.\n"
1440                                 "INFO: a reset or power cycle is required "
1441                                 "for the new settings to take effect.");
1442
1443         return ERROR_OK;
1444 }
1445
1446 static int stm32x_mass_erase(struct flash_bank *bank)
1447 {
1448         struct target *target = bank->target;
1449
1450         if (target->state != TARGET_HALTED) {
1451                 LOG_ERROR("Target not halted");
1452                 return ERROR_TARGET_NOT_HALTED;
1453         }
1454
1455         /* unlock option flash registers */
1456         int retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_KEYR), KEY1);
1457         if (retval != ERROR_OK)
1458                 return retval;
1459         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_KEYR), KEY2);
1460         if (retval != ERROR_OK)
1461                 return retval;
1462
1463         /* mass erase flash memory */
1464         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_MER);
1465         if (retval != ERROR_OK)
1466                 return retval;
1467         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
1468                         FLASH_MER | FLASH_STRT);
1469         if (retval != ERROR_OK)
1470                 return retval;
1471
1472         retval = stm32x_wait_status_busy(bank, 100);
1473         if (retval != ERROR_OK)
1474                 return retval;
1475
1476         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
1477         if (retval != ERROR_OK)
1478                 return retval;
1479
1480         return ERROR_OK;
1481 }
1482
1483 COMMAND_HANDLER(stm32x_handle_mass_erase_command)
1484 {
1485         int i;
1486
1487         if (CMD_ARGC < 1)
1488                 return ERROR_COMMAND_SYNTAX_ERROR;
1489
1490         struct flash_bank *bank;
1491         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1492         if (ERROR_OK != retval)
1493                 return retval;
1494
1495         retval = stm32x_mass_erase(bank);
1496         if (retval == ERROR_OK) {
1497                 /* set all sectors as erased */
1498                 for (i = 0; i < bank->num_sectors; i++)
1499                         bank->sectors[i].is_erased = 1;
1500
1501                 command_print(CMD_CTX, "stm32x mass erase complete");
1502         } else
1503                 command_print(CMD_CTX, "stm32x mass erase failed");
1504
1505         return retval;
1506 }
1507
1508 static const struct command_registration stm32x_exec_command_handlers[] = {
1509         {
1510                 .name = "lock",
1511                 .handler = stm32x_handle_lock_command,
1512                 .mode = COMMAND_EXEC,
1513                 .usage = "bank_id",
1514                 .help = "Lock entire flash device.",
1515         },
1516         {
1517                 .name = "unlock",
1518                 .handler = stm32x_handle_unlock_command,
1519                 .mode = COMMAND_EXEC,
1520                 .usage = "bank_id",
1521                 .help = "Unlock entire protected flash device.",
1522         },
1523         {
1524                 .name = "mass_erase",
1525                 .handler = stm32x_handle_mass_erase_command,
1526                 .mode = COMMAND_EXEC,
1527                 .usage = "bank_id",
1528                 .help = "Erase entire flash device.",
1529         },
1530         {
1531                 .name = "options_read",
1532                 .handler = stm32x_handle_options_read_command,
1533                 .mode = COMMAND_EXEC,
1534                 .usage = "bank_id",
1535                 .help = "Read and display device option byte.",
1536         },
1537         {
1538                 .name = "options_write",
1539                 .handler = stm32x_handle_options_write_command,
1540                 .mode = COMMAND_EXEC,
1541                 .usage = "bank_id ('SWWDG'|'HWWDG') "
1542                         "('RSTSTNDBY'|'NORSTSTNDBY') "
1543                         "('RSTSTOP'|'NORSTSTOP')",
1544                 .help = "Replace bits in device option byte.",
1545         },
1546         COMMAND_REGISTRATION_DONE
1547 };
1548
1549 static const struct command_registration stm32x_command_handlers[] = {
1550         {
1551                 .name = "stm32f1x",
1552                 .mode = COMMAND_ANY,
1553                 .help = "stm32f1x flash command group",
1554                 .usage = "",
1555                 .chain = stm32x_exec_command_handlers,
1556         },
1557         COMMAND_REGISTRATION_DONE
1558 };
1559
1560 struct flash_driver stm32f1x_flash = {
1561         .name = "stm32f1x",
1562         .commands = stm32x_command_handlers,
1563         .flash_bank_command = stm32x_flash_bank_command,
1564         .erase = stm32x_erase,
1565         .protect = stm32x_protect,
1566         .write = stm32x_write,
1567         .read = default_flash_read,
1568         .probe = stm32x_probe,
1569         .auto_probe = stm32x_auto_probe,
1570         .erase_check = default_flash_blank_check,
1571         .protect_check = stm32x_protect_check,
1572         .info = get_stm32x_info,
1573 };