]> git.sur5r.net Git - openocd/blob - src/flash/nor/stm32f2x.c
flash/stm32f2x: add stm32f7 revision Z identification
[openocd] / src / flash / nor / stm32f2x.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 Ã˜yvind Harboe                                      *
9  *   oyvind.harboe@zylin.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, see <http://www.gnu.org/licenses/>. *
23  ***************************************************************************/
24
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #endif
28
29 #include "imp.h"
30 #include <helper/binarybuffer.h>
31 #include <target/algorithm.h>
32 #include <target/armv7m.h>
33
34 /* Regarding performance:
35  *
36  * Short story - it might be best to leave the performance at
37  * current levels.
38  *
39  * You may see a jump in speed if you change to using
40  * 32bit words for the block programming.
41  *
42  * Its a shame you cannot use the double word as its
43  * even faster - but you require external VPP for that mode.
44  *
45  * Having said all that 16bit writes give us the widest vdd
46  * operating range, so may be worth adding a note to that effect.
47  *
48  */
49
50 /* Danger!!!! The STM32F1x and STM32F2x series actually have
51  * quite different flash controllers.
52  *
53  * What's more scary is that the names of the registers and their
54  * addresses are the same, but the actual bits and what they do are
55  * can be very different.
56  *
57  * To reduce testing complexity and dangers of regressions,
58  * a seperate file is used for stm32fx2x.
59  *
60  * Sector sizes in kiBytes:
61  * 1 MiByte part with 4 x 16, 1 x 64, 7 x 128.
62  * 1.5 MiByte part with 4 x 16, 1 x 64, 11 x 128.
63  * 2 MiByte part with 4 x 16, 1 x 64, 7 x 128, 4 x 16, 1 x 64, 7 x 128.
64  * 1 MiByte STM32F42x/43x part with DB1M Option set:
65  *                    4 x 16, 1 x 64, 3 x 128, 4 x 16, 1 x 64, 3 x 128.
66  *
67  * STM32F7[2|3]
68  * 512 kiByte part with 4 x 16, 1 x 64, 3 x 128.
69  *
70  * STM32F7[4|5]
71  * 1 MiByte part with 4 x 32, 1 x 128, 3 x 256.
72  *
73  * STM32F7[6|7]
74  * 1 MiByte part in single bank mode with 4 x 32, 1 x 128, 3 x 256.
75  * 1 MiByte part in dual-bank mode two banks with 4 x 16, 1 x 64, 3 x 128 each.
76  * 2 MiByte part in single-bank mode with 4 x 32, 1 x 128, 7 x 256.
77  * 2 MiByte part in dual-bank mode two banks with 4 x 16, 1 x 64, 7 x 128 each.
78  *
79  * Protection size is sector size.
80  *
81  * Tested with STM3220F-EVAL board.
82  *
83  * STM32F4xx series for reference.
84  *
85  * RM0090
86  * http://www.st.com/web/en/resource/technical/document/reference_manual/DM00031020.pdf
87  *
88  * PM0059
89  * www.st.com/internet/com/TECHNICAL_RESOURCES/TECHNICAL_LITERATURE/
90  * PROGRAMMING_MANUAL/CD00233952.pdf
91  *
92  * STM32F7xx series for reference.
93  *
94  * RM0385
95  * http://www.st.com/web/en/resource/technical/document/reference_manual/DM00124865.pdf
96  *
97  * RM0410
98  * http://www.st.com/resource/en/reference_manual/dm00224583.pdf
99  *
100  * RM0430
101  * http://www.st.com/resource/en/reference_manual/dm00305666.pdf
102  *
103  * RM0431
104  * http://www.st.com/resource/en/reference_manual/dm00305990.pdf
105  *
106  * STM32F1x series - notice that this code was copy, pasted and knocked
107  * into a stm32f2x driver, so in case something has been converted or
108  * bugs haven't been fixed, here are the original manuals:
109  *
110  * RM0008 - Reference manual
111  *
112  * RM0042, the Flash programming manual for low-, medium- high-density and
113  * connectivity line STM32F10x devices
114  *
115  * PM0068, the Flash programming manual for XL-density STM32F10x devices.
116  *
117  */
118
119 /* Erase time can be as high as 1000ms, 10x this and it's toast... */
120 #define FLASH_ERASE_TIMEOUT 10000
121 #define FLASH_WRITE_TIMEOUT 5
122
123 /* Mass erase time can be as high as 32 s in x8 mode. */
124 #define FLASH_MASS_ERASE_TIMEOUT 33000
125
126 #define STM32_FLASH_BASE    0x40023c00
127 #define STM32_FLASH_ACR     0x40023c00
128 #define STM32_FLASH_KEYR    0x40023c04
129 #define STM32_FLASH_OPTKEYR 0x40023c08
130 #define STM32_FLASH_SR      0x40023c0C
131 #define STM32_FLASH_CR      0x40023c10
132 #define STM32_FLASH_OPTCR   0x40023c14
133 #define STM32_FLASH_OPTCR1  0x40023c18
134 #define STM32_FLASH_OPTCR2  0x40023c1c
135
136 /* FLASH_CR register bits */
137 #define FLASH_PG       (1 << 0)
138 #define FLASH_SER      (1 << 1)
139 #define FLASH_MER      (1 << 2)         /* MER/MER1 for f76x/77x */
140 #define FLASH_MER1     (1 << 15)        /* MER2 for f76x/77x, confusing ... */
141 #define FLASH_STRT     (1 << 16)
142 #define FLASH_PSIZE_8  (0 << 8)
143 #define FLASH_PSIZE_16 (1 << 8)
144 #define FLASH_PSIZE_32 (2 << 8)
145 #define FLASH_PSIZE_64 (3 << 8)
146 /* The sector number encoding is not straight binary for dual bank flash. */
147 #define FLASH_SNB(a)   ((a) << 3)
148 #define FLASH_LOCK     (1 << 31)
149
150 /* FLASH_SR register bits */
151 #define FLASH_BSY      (1 << 16)
152 #define FLASH_PGSERR   (1 << 7) /* Programming sequence error */
153 #define FLASH_PGPERR   (1 << 6) /* Programming parallelism error */
154 #define FLASH_PGAERR   (1 << 5) /* Programming alignment error */
155 #define FLASH_WRPERR   (1 << 4) /* Write protection error */
156 #define FLASH_OPERR    (1 << 1) /* Operation error */
157
158 #define FLASH_ERROR (FLASH_PGSERR | FLASH_PGPERR | FLASH_PGAERR | FLASH_WRPERR | FLASH_OPERR)
159
160 /* STM32_FLASH_OPTCR register bits */
161 #define OPTCR_LOCK     (1 << 0)
162 #define OPTCR_START    (1 << 1)
163 #define OPTCR_NDBANK   (1 << 29)        /* not dual bank mode */
164 #define OPTCR_DB1M     (1 << 30)        /* 1 MiB devices dual flash bank option */
165 #define OPTCR_SPRMOD   (1 << 31)        /* switches PCROPi/nWPRi interpretation */
166
167 /* STM32_FLASH_OPTCR2 register bits */
168 #define OPTCR2_PCROP_RDP        (1 << 31)       /* erase PCROP zone when decreasing RDP */
169
170 /* register unlock keys */
171 #define KEY1           0x45670123
172 #define KEY2           0xCDEF89AB
173
174 /* option register unlock key */
175 #define OPTKEY1        0x08192A3B
176 #define OPTKEY2        0x4C5D6E7F
177
178 struct stm32x_options {
179         uint8_t RDP;
180         uint16_t user_options;  /* bit 0-7 usual options, bit 8-11 extra options */
181         uint32_t protection;
182         uint32_t boot_addr;
183         uint32_t optcr2_pcrop;
184 };
185
186 struct stm32x_flash_bank {
187         struct stm32x_options option_bytes;
188         int probed;
189         bool has_large_mem;             /* F42x/43x/469/479/7xx in dual bank mode */
190         bool has_extra_options; /* F42x/43x/469/479/7xx */
191         bool has_boot_addr;     /* F7xx */
192         bool has_optcr2_pcrop;  /* F72x/73x */
193         int protection_bits;    /* F413/423 */
194         uint32_t user_bank_size;
195 };
196
197 /* flash bank stm32x <base> <size> 0 0 <target#>
198  */
199 FLASH_BANK_COMMAND_HANDLER(stm32x_flash_bank_command)
200 {
201         struct stm32x_flash_bank *stm32x_info;
202
203         if (CMD_ARGC < 6)
204                 return ERROR_COMMAND_SYNTAX_ERROR;
205
206         stm32x_info = malloc(sizeof(struct stm32x_flash_bank));
207         bank->driver_priv = stm32x_info;
208
209         stm32x_info->probed = 0;
210         stm32x_info->user_bank_size = bank->size;
211
212         return ERROR_OK;
213 }
214
215 static inline int stm32x_get_flash_reg(struct flash_bank *bank, uint32_t reg)
216 {
217         return reg;
218 }
219
220 static inline int stm32x_get_flash_status(struct flash_bank *bank, uint32_t *status)
221 {
222         struct target *target = bank->target;
223         return target_read_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR), status);
224 }
225
226 static int stm32x_wait_status_busy(struct flash_bank *bank, int timeout)
227 {
228         struct target *target = bank->target;
229         uint32_t status;
230         int retval = ERROR_OK;
231
232         /* wait for busy to clear */
233         for (;;) {
234                 retval = stm32x_get_flash_status(bank, &status);
235                 if (retval != ERROR_OK)
236                         return retval;
237                 LOG_DEBUG("status: 0x%" PRIx32 "", status);
238                 if ((status & FLASH_BSY) == 0)
239                         break;
240                 if (timeout-- <= 0) {
241                         LOG_ERROR("timed out waiting for flash");
242                         return ERROR_FAIL;
243                 }
244                 alive_sleep(1);
245         }
246
247
248         if (status & FLASH_WRPERR) {
249                 LOG_ERROR("stm32x device protected");
250                 retval = ERROR_FAIL;
251         }
252
253         /* Clear but report errors */
254         if (status & FLASH_ERROR) {
255                 if (retval == ERROR_OK)
256                         retval = ERROR_FAIL;
257                 /* If this operation fails, we ignore it and report the original
258                  * retval
259                  */
260                 target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR),
261                                 status & FLASH_ERROR);
262         }
263         return retval;
264 }
265
266 static int stm32x_unlock_reg(struct target *target)
267 {
268         uint32_t ctrl;
269
270         /* first check if not already unlocked
271          * otherwise writing on STM32_FLASH_KEYR will fail
272          */
273         int retval = target_read_u32(target, STM32_FLASH_CR, &ctrl);
274         if (retval != ERROR_OK)
275                 return retval;
276
277         if ((ctrl & FLASH_LOCK) == 0)
278                 return ERROR_OK;
279
280         /* unlock flash registers */
281         retval = target_write_u32(target, STM32_FLASH_KEYR, KEY1);
282         if (retval != ERROR_OK)
283                 return retval;
284
285         retval = target_write_u32(target, STM32_FLASH_KEYR, KEY2);
286         if (retval != ERROR_OK)
287                 return retval;
288
289         retval = target_read_u32(target, STM32_FLASH_CR, &ctrl);
290         if (retval != ERROR_OK)
291                 return retval;
292
293         if (ctrl & FLASH_LOCK) {
294                 LOG_ERROR("flash not unlocked STM32_FLASH_CR: %" PRIx32, ctrl);
295                 return ERROR_TARGET_FAILURE;
296         }
297
298         return ERROR_OK;
299 }
300
301 static int stm32x_unlock_option_reg(struct target *target)
302 {
303         uint32_t ctrl;
304
305         int retval = target_read_u32(target, STM32_FLASH_OPTCR, &ctrl);
306         if (retval != ERROR_OK)
307                 return retval;
308
309         if ((ctrl & OPTCR_LOCK) == 0)
310                 return ERROR_OK;
311
312         /* unlock option registers */
313         retval = target_write_u32(target, STM32_FLASH_OPTKEYR, OPTKEY1);
314         if (retval != ERROR_OK)
315                 return retval;
316
317         retval = target_write_u32(target, STM32_FLASH_OPTKEYR, OPTKEY2);
318         if (retval != ERROR_OK)
319                 return retval;
320
321         retval = target_read_u32(target, STM32_FLASH_OPTCR, &ctrl);
322         if (retval != ERROR_OK)
323                 return retval;
324
325         if (ctrl & OPTCR_LOCK) {
326                 LOG_ERROR("options not unlocked STM32_FLASH_OPTCR: %" PRIx32, ctrl);
327                 return ERROR_TARGET_FAILURE;
328         }
329
330         return ERROR_OK;
331 }
332
333 static int stm32x_read_options(struct flash_bank *bank)
334 {
335         uint32_t optiondata;
336         struct stm32x_flash_bank *stm32x_info = NULL;
337         struct target *target = bank->target;
338
339         stm32x_info = bank->driver_priv;
340
341         /* read current option bytes */
342         int retval = target_read_u32(target, STM32_FLASH_OPTCR, &optiondata);
343         if (retval != ERROR_OK)
344                 return retval;
345
346     /* caution: F2 implements 5 bits (WDG_SW only)
347      * whereas F7 6 bits (IWDG_SW and WWDG_SW) in user_options */
348         stm32x_info->option_bytes.user_options = optiondata & 0xfc;
349         stm32x_info->option_bytes.RDP = (optiondata >> 8) & 0xff;
350         stm32x_info->option_bytes.protection =
351                 (optiondata >> 16) & (~(0xffff << stm32x_info->protection_bits) & 0xffff);
352
353         if (stm32x_info->has_extra_options) {
354                 /* F42x/43x/469/479 and 7xx have up to 4 bits of extra options */
355                 stm32x_info->option_bytes.user_options |= (optiondata >> 20) &
356                         ((0xf00 << (stm32x_info->protection_bits - 12)) & 0xf00);
357         }
358
359         if (stm32x_info->has_large_mem || stm32x_info->has_boot_addr) {
360                 retval = target_read_u32(target, STM32_FLASH_OPTCR1, &optiondata);
361                 if (retval != ERROR_OK)
362                         return retval;
363
364                 /* FLASH_OPTCR1 has quite diffent meanings ... */
365                 if (stm32x_info->has_boot_addr) {
366                         /* for F7xx it contains boot0 and boot1 */
367                         stm32x_info->option_bytes.boot_addr = optiondata;
368                 } else {
369                         /* for F42x/43x/469/479 it contains 12 additional protection bits */
370                         stm32x_info->option_bytes.protection |= (optiondata >> 4) & 0x00fff000;
371                 }
372         }
373
374         if (stm32x_info->has_optcr2_pcrop) {
375                 retval = target_read_u32(target, STM32_FLASH_OPTCR2, &optiondata);
376                 if (retval != ERROR_OK)
377                         return retval;
378
379                 stm32x_info->option_bytes.optcr2_pcrop = optiondata;
380                 if (stm32x_info->has_optcr2_pcrop &&
381                         (stm32x_info->option_bytes.optcr2_pcrop & ~OPTCR2_PCROP_RDP)) {
382                         LOG_INFO("PCROP Engaged");
383                 }
384         } else {
385                 stm32x_info->option_bytes.optcr2_pcrop = 0x0;
386         }
387
388         if (stm32x_info->option_bytes.RDP != 0xAA)
389                 LOG_INFO("Device Security Bit Set");
390
391         return ERROR_OK;
392 }
393
394 static int stm32x_write_options(struct flash_bank *bank)
395 {
396         struct stm32x_flash_bank *stm32x_info = NULL;
397         struct target *target = bank->target;
398         uint32_t optiondata, optiondata2;
399
400         stm32x_info = bank->driver_priv;
401
402         int retval = stm32x_unlock_option_reg(target);
403         if (retval != ERROR_OK)
404                 return retval;
405
406         /* rebuild option data */
407         optiondata = stm32x_info->option_bytes.user_options & 0xfc;
408         optiondata |= stm32x_info->option_bytes.RDP << 8;
409         optiondata |= (stm32x_info->option_bytes.protection &
410                 (~(0xffff << stm32x_info->protection_bits))) << 16;
411
412         if (stm32x_info->has_extra_options) {
413                 /* F42x/43x/469/479 and 7xx have up to 4 bits of extra options */
414                 optiondata |= (stm32x_info->option_bytes.user_options &
415                         ((0xf00 << (stm32x_info->protection_bits - 12)) & 0xf00)) << 20;
416         }
417
418         if (stm32x_info->has_large_mem || stm32x_info->has_boot_addr) {
419                 if (stm32x_info->has_boot_addr) {
420                         /* F7xx uses FLASH_OPTCR1 for boot0 and boot1 ... */
421                         optiondata2 = stm32x_info->option_bytes.boot_addr;
422                 } else {
423                         /* F42x/43x/469/479 uses FLASH_OPTCR1 for additional protection bits */
424                         optiondata2 = (stm32x_info->option_bytes.protection & 0x00fff000) << 4;
425                 }
426
427                 retval = target_write_u32(target, STM32_FLASH_OPTCR1, optiondata2);
428                 if (retval != ERROR_OK)
429                         return retval;
430         }
431
432         /* program extra pcrop register */
433         if (stm32x_info->has_optcr2_pcrop) {
434                 retval = target_write_u32(target, STM32_FLASH_OPTCR2,
435                         stm32x_info->option_bytes.optcr2_pcrop);
436                 if (retval != ERROR_OK)
437                         return retval;
438         }
439
440         /* program options */
441         retval = target_write_u32(target, STM32_FLASH_OPTCR, optiondata);
442         if (retval != ERROR_OK)
443                 return retval;
444
445         /* start programming cycle */
446         retval = target_write_u32(target, STM32_FLASH_OPTCR, optiondata | OPTCR_START);
447         if (retval != ERROR_OK)
448                 return retval;
449
450         /* wait for completion, this might trigger a security erase and take a while */
451         retval = stm32x_wait_status_busy(bank, FLASH_MASS_ERASE_TIMEOUT);
452         if (retval != ERROR_OK)
453                 return retval;
454
455         /* relock registers */
456         retval = target_write_u32(target, STM32_FLASH_OPTCR, optiondata | OPTCR_LOCK);
457         if (retval != ERROR_OK)
458                 return retval;
459
460         return ERROR_OK;
461 }
462
463 static int stm32x_protect_check(struct flash_bank *bank)
464 {
465         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
466         struct flash_sector *prot_blocks;
467         int num_prot_blocks;
468
469         /* read write protection settings */
470         int retval = stm32x_read_options(bank);
471         if (retval != ERROR_OK) {
472                 LOG_DEBUG("unable to read option bytes");
473                 return retval;
474         }
475
476         if (bank->prot_blocks) {
477                 num_prot_blocks = bank->num_prot_blocks;
478                 prot_blocks = bank->prot_blocks;
479         } else {
480                 num_prot_blocks = bank->num_sectors;
481                 prot_blocks = bank->sectors;
482         }
483
484         for (int i = 0; i < num_prot_blocks; i++)
485                 prot_blocks[i].is_protected =
486                         ~(stm32x_info->option_bytes.protection >> i) & 1;
487
488         return ERROR_OK;
489 }
490
491 static int stm32x_erase(struct flash_bank *bank, int first, int last)
492 {
493         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
494         struct target *target = bank->target;
495         int i;
496
497         assert((0 <= first) && (first <= last) && (last < bank->num_sectors));
498
499         if (bank->target->state != TARGET_HALTED) {
500                 LOG_ERROR("Target not halted");
501                 return ERROR_TARGET_NOT_HALTED;
502         }
503
504         int retval;
505         retval = stm32x_unlock_reg(target);
506         if (retval != ERROR_OK)
507                 return retval;
508
509         /*
510         Sector Erase
511         To erase a sector, follow the procedure below:
512         1. Check that no Flash memory operation is ongoing by checking the BSY bit in the
513           FLASH_SR register
514         2. Set the SER bit and select the sector
515           you wish to erase (SNB) in the FLASH_CR register
516         3. Set the STRT bit in the FLASH_CR register
517         4. Wait for the BSY bit to be cleared
518          */
519
520         for (i = first; i <= last; i++) {
521                 int snb;
522                 if (stm32x_info->has_large_mem && i >= 12)
523                         snb = (i - 12) | 0x10;
524                 else
525                         snb = i;
526
527                 retval = target_write_u32(target,
528                                 stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_SER | FLASH_SNB(snb) | FLASH_STRT);
529                 if (retval != ERROR_OK)
530                         return retval;
531
532                 retval = stm32x_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
533                 if (retval != ERROR_OK)
534                         return retval;
535
536                 bank->sectors[i].is_erased = 1;
537         }
538
539         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
540         if (retval != ERROR_OK)
541                 return retval;
542
543         return ERROR_OK;
544 }
545
546 static int stm32x_protect(struct flash_bank *bank, int set, int first, int last)
547 {
548         struct target *target = bank->target;
549         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
550
551         if (target->state != TARGET_HALTED) {
552                 LOG_ERROR("Target not halted");
553                 return ERROR_TARGET_NOT_HALTED;
554         }
555
556         /* read protection settings */
557         int retval = stm32x_read_options(bank);
558         if (retval != ERROR_OK) {
559                 LOG_DEBUG("unable to read option bytes");
560                 return retval;
561         }
562
563         for (int i = first; i <= last; i++) {
564                 if (set)
565                         stm32x_info->option_bytes.protection &= ~(1 << i);
566                 else
567                         stm32x_info->option_bytes.protection |= (1 << i);
568         }
569
570         retval = stm32x_write_options(bank);
571         if (retval != ERROR_OK)
572                 return retval;
573
574         return ERROR_OK;
575 }
576
577 static int stm32x_write_block(struct flash_bank *bank, const uint8_t *buffer,
578                 uint32_t offset, uint32_t count)
579 {
580         struct target *target = bank->target;
581         uint32_t buffer_size = 16384;
582         struct working_area *write_algorithm;
583         struct working_area *source;
584         uint32_t address = bank->base + offset;
585         struct reg_param reg_params[5];
586         struct armv7m_algorithm armv7m_info;
587         int retval = ERROR_OK;
588
589         static const uint8_t stm32x_flash_write_code[] = {
590 #include "../../../contrib/loaders/flash/stm32/stm32f2x.inc"
591         };
592
593         if (target_alloc_working_area(target, sizeof(stm32x_flash_write_code),
594                         &write_algorithm) != ERROR_OK) {
595                 LOG_WARNING("no working area available, can't do block memory writes");
596                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
597         }
598
599         retval = target_write_buffer(target, write_algorithm->address,
600                         sizeof(stm32x_flash_write_code),
601                         stm32x_flash_write_code);
602         if (retval != ERROR_OK) {
603                 target_free_working_area(target, write_algorithm);
604                 return retval;
605         }
606
607         /* memory buffer */
608         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) {
609                 buffer_size /= 2;
610                 if (buffer_size <= 256) {
611                         /* we already allocated the writing code, but failed to get a
612                          * buffer, free the algorithm */
613                         target_free_working_area(target, write_algorithm);
614
615                         LOG_WARNING("no large enough working area available, can't do block memory writes");
616                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
617                 }
618         }
619
620         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
621         armv7m_info.core_mode = ARM_MODE_THREAD;
622
623         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT);         /* buffer start, status (out) */
624         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);            /* buffer end */
625         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);            /* target address */
626         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);            /* count (halfword-16bit) */
627         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);            /* flash base */
628
629         buf_set_u32(reg_params[0].value, 0, 32, source->address);
630         buf_set_u32(reg_params[1].value, 0, 32, source->address + source->size);
631         buf_set_u32(reg_params[2].value, 0, 32, address);
632         buf_set_u32(reg_params[3].value, 0, 32, count);
633         buf_set_u32(reg_params[4].value, 0, 32, STM32_FLASH_BASE);
634
635         retval = target_run_flash_async_algorithm(target, buffer, count, 2,
636                         0, NULL,
637                         5, reg_params,
638                         source->address, source->size,
639                         write_algorithm->address, 0,
640                         &armv7m_info);
641
642         if (retval == ERROR_FLASH_OPERATION_FAILED) {
643                 LOG_ERROR("error executing stm32x flash write algorithm");
644
645                 uint32_t error = buf_get_u32(reg_params[0].value, 0, 32) & FLASH_ERROR;
646
647                 if (error & FLASH_WRPERR)
648                         LOG_ERROR("flash memory write protected");
649
650                 if (error != 0) {
651                         LOG_ERROR("flash write failed = %08" PRIx32, error);
652                         /* Clear but report errors */
653                         target_write_u32(target, STM32_FLASH_SR, error);
654                         retval = ERROR_FAIL;
655                 }
656         }
657
658         target_free_working_area(target, source);
659         target_free_working_area(target, write_algorithm);
660
661         destroy_reg_param(&reg_params[0]);
662         destroy_reg_param(&reg_params[1]);
663         destroy_reg_param(&reg_params[2]);
664         destroy_reg_param(&reg_params[3]);
665         destroy_reg_param(&reg_params[4]);
666
667         return retval;
668 }
669
670 static int stm32x_write(struct flash_bank *bank, const uint8_t *buffer,
671                 uint32_t offset, uint32_t count)
672 {
673         struct target *target = bank->target;
674         uint32_t words_remaining = (count / 2);
675         uint32_t bytes_remaining = (count & 0x00000001);
676         uint32_t address = bank->base + offset;
677         uint32_t bytes_written = 0;
678         int retval;
679
680         if (bank->target->state != TARGET_HALTED) {
681                 LOG_ERROR("Target not halted");
682                 return ERROR_TARGET_NOT_HALTED;
683         }
684
685         if (offset & 0x1) {
686                 LOG_WARNING("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
687                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
688         }
689
690         retval = stm32x_unlock_reg(target);
691         if (retval != ERROR_OK)
692                 return retval;
693
694         /* multiple half words (2-byte) to be programmed? */
695         if (words_remaining > 0) {
696                 /* try using a block write */
697                 retval = stm32x_write_block(bank, buffer, offset, words_remaining);
698                 if (retval != ERROR_OK) {
699                         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
700                                 /* if block write failed (no sufficient working area),
701                                  * we use normal (slow) single dword accesses */
702                                 LOG_WARNING("couldn't use block writes, falling back to single memory accesses");
703                         }
704                 } else {
705                         buffer += words_remaining * 2;
706                         address += words_remaining * 2;
707                         words_remaining = 0;
708                 }
709         }
710
711         if ((retval != ERROR_OK) && (retval != ERROR_TARGET_RESOURCE_NOT_AVAILABLE))
712                 return retval;
713
714         /*
715         Standard programming
716         The Flash memory programming sequence is as follows:
717         1. Check that no main Flash memory operation is ongoing by checking the BSY bit in the
718           FLASH_SR register.
719         2. Set the PG bit in the FLASH_CR register
720         3. Perform the data write operation(s) to the desired memory address (inside main
721           memory block or OTP area):
722         â€“ â€“ Half-word access in case of x16 parallelism
723         â€“ Word access in case of x32 parallelism
724         â€“
725         4.
726         Byte access in case of x8 parallelism
727         Double word access in case of x64 parallelism
728         Wait for the BSY bit to be cleared
729         */
730         while (words_remaining > 0) {
731                 uint16_t value;
732                 memcpy(&value, buffer + bytes_written, sizeof(uint16_t));
733
734                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
735                                 FLASH_PG | FLASH_PSIZE_16);
736                 if (retval != ERROR_OK)
737                         return retval;
738
739                 retval = target_write_u16(target, address, value);
740                 if (retval != ERROR_OK)
741                         return retval;
742
743                 retval = stm32x_wait_status_busy(bank, FLASH_WRITE_TIMEOUT);
744                 if (retval != ERROR_OK)
745                         return retval;
746
747                 bytes_written += 2;
748                 words_remaining--;
749                 address += 2;
750         }
751
752         if (bytes_remaining) {
753                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
754                                 FLASH_PG | FLASH_PSIZE_8);
755                 if (retval != ERROR_OK)
756                         return retval;
757                 retval = target_write_u8(target, address, buffer[bytes_written]);
758                 if (retval != ERROR_OK)
759                         return retval;
760
761                 retval = stm32x_wait_status_busy(bank, FLASH_WRITE_TIMEOUT);
762                 if (retval != ERROR_OK)
763                         return retval;
764         }
765
766         return target_write_u32(target, STM32_FLASH_CR, FLASH_LOCK);
767 }
768
769 static int setup_sector(struct flash_bank *bank, int start, int num, int size)
770 {
771
772         for (int i = start; i < (start + num) ; i++) {
773                 assert(i < bank->num_sectors);
774                 bank->sectors[i].offset = bank->size;
775                 bank->sectors[i].size = size;
776                 bank->size += bank->sectors[i].size;
777             LOG_DEBUG("sector %d: %dkBytes", i, size >> 10);
778         }
779
780         return start + num;
781 }
782
783 static void setup_bank(struct flash_bank *bank, int start,
784         uint16_t flash_size_in_kb, uint16_t max_sector_size_in_kb)
785 {
786         int remain;
787
788         start = setup_sector(bank, start, 4, (max_sector_size_in_kb / 8) * 1024);
789         start = setup_sector(bank, start, 1, (max_sector_size_in_kb / 2) * 1024);
790
791         /* remaining sectors all of size max_sector_size_in_kb */
792         remain = (flash_size_in_kb / max_sector_size_in_kb) - 1;
793         start = setup_sector(bank, start, remain, max_sector_size_in_kb * 1024);
794 }
795
796 static int stm32x_get_device_id(struct flash_bank *bank, uint32_t *device_id)
797 {
798         /* this checks for a stm32f4x errata issue where a
799          * stm32f2x DBGMCU_IDCODE is incorrectly returned.
800          * If the issue is detected target is forced to stm32f4x Rev A.
801          * Only effects Rev A silicon */
802
803         struct target *target = bank->target;
804         uint32_t cpuid;
805
806         /* read stm32 device id register */
807         int retval = target_read_u32(target, 0xE0042000, device_id);
808         if (retval != ERROR_OK)
809                 return retval;
810
811         if ((*device_id & 0xfff) == 0x411) {
812                 /* read CPUID reg to check core type */
813                 retval = target_read_u32(target, 0xE000ED00, &cpuid);
814                 if (retval != ERROR_OK)
815                         return retval;
816
817                 /* check for cortex_m4 */
818                 if (((cpuid >> 4) & 0xFFF) == 0xC24) {
819                         *device_id &= ~((0xFFFF << 16) | 0xfff);
820                         *device_id |= (0x1000 << 16) | 0x413;
821                         LOG_INFO("stm32f4x errata detected - fixing incorrect MCU_IDCODE");
822                 }
823         }
824         return retval;
825 }
826
827 static int stm32x_probe(struct flash_bank *bank)
828 {
829         struct target *target = bank->target;
830         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
831         int i, num_prot_blocks;
832         uint16_t flash_size_in_kb;
833         uint32_t flash_size_reg = 0x1FFF7A22;
834         uint16_t max_sector_size_in_kb = 128;
835         uint16_t max_flash_size_in_kb;
836         uint32_t device_id;
837         uint32_t base_address = 0x08000000;
838
839         stm32x_info->probed = 0;
840         stm32x_info->has_large_mem = false;
841         stm32x_info->has_boot_addr = false;
842         stm32x_info->has_extra_options = false;
843         stm32x_info->has_optcr2_pcrop = false;
844         stm32x_info->protection_bits = 12;              /* max. number of nWRPi bits (in FLASH_OPTCR !!!) */
845         num_prot_blocks = 0;
846
847         if (bank->sectors) {
848                 free(bank->sectors);
849                 bank->num_sectors = 0;
850                 bank->sectors = NULL;
851         }
852
853         if (bank->prot_blocks) {
854                 free(bank->prot_blocks);
855                 bank->num_prot_blocks = 0;
856                 bank->prot_blocks = NULL;
857         }
858
859         /* read stm32 device id register */
860         int retval = stm32x_get_device_id(bank, &device_id);
861         if (retval != ERROR_OK)
862                 return retval;
863         LOG_INFO("device id = 0x%08" PRIx32 "", device_id);
864         device_id &= 0xfff;             /* only bits 0-11 are used further on */
865
866         /* set max flash size depending on family, id taken from AN2606 */
867         switch (device_id) {
868         case 0x411: /* F20x/21x */
869         case 0x413: /* F40x/41x */
870                 max_flash_size_in_kb = 1024;
871                 break;
872
873         case 0x419: /* F42x/43x */
874         case 0x434: /* F469/479 */
875                 stm32x_info->has_extra_options = true;
876                 max_flash_size_in_kb = 2048;
877                 break;
878
879         case 0x423:     /* F401xB/C */
880                 max_flash_size_in_kb = 256;
881                 break;
882
883         case 0x421:     /* F446 */
884         case 0x431: /* F411 */
885         case 0x433: /* F401xD/E */
886         case 0x441: /* F412 */
887                 max_flash_size_in_kb = 512;
888                 break;
889
890         case 0x458: /* F410 */
891                 max_flash_size_in_kb = 128;
892                 break;
893
894         case 0x449:     /* F74x/75x */
895                 max_flash_size_in_kb = 1024;
896                 max_sector_size_in_kb = 256;
897                 flash_size_reg = 0x1FF0F442;
898                 stm32x_info->has_extra_options = true;
899                 stm32x_info->has_boot_addr = true;
900                 break;
901
902         case 0x451:     /* F76x/77x */
903                 max_flash_size_in_kb = 2048;
904                 max_sector_size_in_kb = 256;
905                 flash_size_reg = 0x1FF0F442;
906                 stm32x_info->has_extra_options = true;
907                 stm32x_info->has_boot_addr = true;
908                 break;
909
910         case 0x452:     /* F72x/73x */
911                 max_flash_size_in_kb = 512;
912                 flash_size_reg = 0x1FF07A22;    /* yes, 0x1FF*0*7A22, not 0x1FF*F*7A22 */
913                 stm32x_info->has_extra_options = true;
914                 stm32x_info->has_boot_addr = true;
915                 stm32x_info->has_optcr2_pcrop = true;
916                 break;
917
918         case 0x463:     /* F413x/423x */
919                 max_flash_size_in_kb = 1536;
920                 stm32x_info->has_extra_options = true;
921                 stm32x_info->protection_bits = 15;
922                 num_prot_blocks = 15;
923                 break;
924
925         default:
926                 LOG_WARNING("Cannot identify target as a STM32 family.");
927                 return ERROR_FAIL;
928         }
929
930         /* get flash size from target. */
931         retval = target_read_u16(target, flash_size_reg, &flash_size_in_kb);
932
933         /* failed reading flash size or flash size invalid (early silicon),
934          * default to max target family */
935         if (retval != ERROR_OK || flash_size_in_kb == 0xffff || flash_size_in_kb == 0) {
936                 LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming %dk flash",
937                         max_flash_size_in_kb);
938                 flash_size_in_kb = max_flash_size_in_kb;
939         }
940
941         /* if the user sets the size manually then ignore the probed value
942          * this allows us to work around devices that have a invalid flash size register value */
943         if (stm32x_info->user_bank_size) {
944                 LOG_INFO("ignoring flash probed value, using configured bank size");
945                 flash_size_in_kb = stm32x_info->user_bank_size / 1024;
946         }
947
948         LOG_INFO("flash size = %dkbytes", flash_size_in_kb);
949
950         /* did we assign flash size? */
951         assert(flash_size_in_kb != 0xffff);
952
953         /* F42x/43x/469/479 1024 kiByte devices have a dual bank option */
954         if ((device_id == 0x419) || (device_id == 0x434)) {
955                 uint32_t optiondata;
956                 retval = target_read_u32(target, STM32_FLASH_OPTCR, &optiondata);
957                 if (retval != ERROR_OK) {
958                         LOG_DEBUG("unable to read option bytes");
959                         return retval;
960                 }
961                 if ((flash_size_in_kb > 1024) || (optiondata & OPTCR_DB1M)) {
962                         stm32x_info->has_large_mem = true;
963                         LOG_INFO("Dual Bank %d kiB STM32F42x/43x/469/479 found", flash_size_in_kb);
964                 } else {
965                         stm32x_info->has_large_mem = false;
966                         LOG_INFO("Single Bank %d kiB STM32F42x/43x/469/479 found", flash_size_in_kb);
967                 }
968         }
969
970         /* F76x/77x devices have a dual bank option */
971         if (device_id == 0x451) {
972                 uint32_t optiondata;
973                 retval = target_read_u32(target, STM32_FLASH_OPTCR, &optiondata);
974                 if (retval != ERROR_OK) {
975                         LOG_DEBUG("unable to read option bytes");
976                         return retval;
977                 }
978                 if (optiondata & OPTCR_NDBANK) {
979                         stm32x_info->has_large_mem = false;
980                         LOG_INFO("Single Bank %d kiB STM32F76x/77x found", flash_size_in_kb);
981                 } else {
982                         stm32x_info->has_large_mem = true;
983                         max_sector_size_in_kb >>= 1; /* sector size divided by 2 in dual-bank mode */
984                         LOG_INFO("Dual Bank %d kiB STM32F76x/77x found", flash_size_in_kb);
985                 }
986         }
987
988         /* calculate numbers of pages */
989         int num_pages = flash_size_in_kb / max_sector_size_in_kb
990                 + (stm32x_info->has_large_mem ? 8 : 4);
991
992         bank->base = base_address;
993         bank->num_sectors = num_pages;
994         bank->sectors = malloc(sizeof(struct flash_sector) * num_pages);
995         for (i = 0; i < num_pages; i++) {
996                 bank->sectors[i].is_erased = -1;
997                 bank->sectors[i].is_protected = 0;
998         }
999         bank->size = 0;
1000         LOG_DEBUG("allocated %d sectors", num_pages);
1001
1002         /* F76x/77x in dual bank mode */
1003         if ((device_id == 0x451) && stm32x_info->has_large_mem)
1004                 num_prot_blocks = num_pages >> 1;
1005
1006         if (num_prot_blocks) {
1007                 bank->prot_blocks = malloc(sizeof(struct flash_sector) * num_prot_blocks);
1008                 for (i = 0; i < num_prot_blocks; i++)
1009                         bank->prot_blocks[i].is_protected = 0;
1010                 LOG_DEBUG("allocated %d prot blocks", num_prot_blocks);
1011         }
1012
1013         if (stm32x_info->has_large_mem) {
1014                 /* dual-bank */
1015                 setup_bank(bank, 0, flash_size_in_kb >> 1, max_sector_size_in_kb);
1016                 setup_bank(bank, num_pages >> 1, flash_size_in_kb >> 1,
1017                         max_sector_size_in_kb);
1018
1019                 /* F767x/F77x in dual mode, one protection bit refers to two adjacent sectors */
1020                 if (device_id == 0x451) {
1021                         for (i = 0; i < num_prot_blocks; i++) {
1022                                 bank->prot_blocks[i].offset = bank->sectors[i << 1].offset;
1023                                 bank->prot_blocks[i].size = bank->sectors[i << 1].size
1024                                                 + bank->sectors[(i << 1) + 1].size;
1025                         }
1026                 }
1027         } else {
1028                 /* single-bank */
1029                 setup_bank(bank, 0, flash_size_in_kb, max_sector_size_in_kb);
1030
1031                 /* F413/F423, sectors 14 and 15 share one common protection bit */
1032                 if (device_id == 0x463) {
1033                         for (i = 0; i < num_prot_blocks; i++) {
1034                                 bank->prot_blocks[i].offset = bank->sectors[i].offset;
1035                                 bank->prot_blocks[i].size = bank->sectors[i].size;
1036                         }
1037                         bank->prot_blocks[num_prot_blocks - 1].size <<= 1;
1038                 }
1039         }
1040         bank->num_prot_blocks = num_prot_blocks;
1041         assert((bank->size >> 10) == flash_size_in_kb);
1042
1043         stm32x_info->probed = 1;
1044         return ERROR_OK;
1045 }
1046
1047 static int stm32x_auto_probe(struct flash_bank *bank)
1048 {
1049         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
1050         if (stm32x_info->probed)
1051                 return ERROR_OK;
1052         return stm32x_probe(bank);
1053 }
1054
1055 static int get_stm32x_info(struct flash_bank *bank, char *buf, int buf_size)
1056 {
1057         uint32_t dbgmcu_idcode;
1058
1059         /* read stm32 device id register */
1060         int retval = stm32x_get_device_id(bank, &dbgmcu_idcode);
1061         if (retval != ERROR_OK)
1062                 return retval;
1063
1064         uint16_t device_id = dbgmcu_idcode & 0xfff;
1065         uint16_t rev_id = dbgmcu_idcode >> 16;
1066         const char *device_str;
1067         const char *rev_str = NULL;
1068
1069         switch (device_id) {
1070         case 0x411:
1071                 device_str = "STM32F2xx";
1072
1073                 switch (rev_id) {
1074                 case 0x1000:
1075                         rev_str = "A";
1076                         break;
1077
1078                 case 0x2000:
1079                         rev_str = "B";
1080                         break;
1081
1082                 case 0x1001:
1083                         rev_str = "Z";
1084                         break;
1085
1086                 case 0x2001:
1087                         rev_str = "Y";
1088                         break;
1089
1090                 case 0x2003:
1091                         rev_str = "X";
1092                         break;
1093
1094                 case 0x2007:
1095                         rev_str = "1";
1096                         break;
1097
1098                 case 0x200F:
1099                         rev_str = "V";
1100                         break;
1101
1102                 case 0x201F:
1103                         rev_str = "2";
1104                         break;
1105                 }
1106                 break;
1107
1108         case 0x413:
1109         case 0x419:
1110         case 0x434:
1111                 device_str = "STM32F4xx";
1112
1113                 switch (rev_id) {
1114                 case 0x1000:
1115                         rev_str = "A";
1116                         break;
1117
1118                 case 0x1001:
1119                         rev_str = "Z";
1120                         break;
1121
1122                 case 0x1003:
1123                         rev_str = "Y";
1124                         break;
1125
1126                 case 0x1007:
1127                         rev_str = "1";
1128                         break;
1129
1130                 case 0x2001:
1131                         rev_str = "3";
1132                         break;
1133                 }
1134                 break;
1135
1136         case 0x421:
1137                 device_str = "STM32F446";
1138
1139                 switch (rev_id) {
1140                 case 0x1000:
1141                         rev_str = "A";
1142                         break;
1143                 }
1144                 break;
1145
1146         case 0x423:
1147         case 0x431:
1148         case 0x433:
1149         case 0x458:
1150         case 0x441:
1151                 device_str = "STM32F4xx (Low Power)";
1152
1153                 switch (rev_id) {
1154                 case 0x1000:
1155                         rev_str = "A";
1156                         break;
1157
1158                 case 0x1001:
1159                         rev_str = "Z";
1160                         break;
1161
1162                 case 0x2000:
1163                         rev_str = "B";
1164                         break;
1165
1166                 case 0x3000:
1167                         rev_str = "C";
1168                         break;
1169                 }
1170                 break;
1171
1172         case 0x449:
1173                 device_str = "STM32F7[4|5]x";
1174
1175                 switch (rev_id) {
1176                 case 0x1000:
1177                         rev_str = "A";
1178                         break;
1179
1180                 case 0x1001:
1181                         rev_str = "Z";
1182                         break;
1183                 }
1184                 break;
1185
1186         case 0x451:
1187                 device_str = "STM32F7[6|7]x";
1188
1189                 switch (rev_id) {
1190                 case 0x1000:
1191                         rev_str = "A";
1192                         break;
1193                 case 0x1001:
1194                         rev_str = "Z";
1195                         break;
1196                 }
1197                 break;
1198
1199         case 0x452:
1200                 device_str = "STM32F7[2|3]x";
1201
1202                 switch (rev_id) {
1203                 case 0x1000:
1204                         rev_str = "A";
1205                         break;
1206                 }
1207                 break;
1208
1209         case 0x463:
1210                 device_str = "STM32F4[1|2]3";
1211
1212                 switch (rev_id) {
1213                 case 0x1000:
1214                         rev_str = "A";
1215                         break;
1216                 }
1217                 break;
1218
1219         default:
1220                 snprintf(buf, buf_size, "Cannot identify target as a STM32F2/4/7\n");
1221                 return ERROR_FAIL;
1222         }
1223
1224         if (rev_str != NULL)
1225                 snprintf(buf, buf_size, "%s - Rev: %s", device_str, rev_str);
1226         else
1227                 snprintf(buf, buf_size, "%s - Rev: unknown (0x%04x)", device_str, rev_id);
1228
1229         return ERROR_OK;
1230 }
1231
1232 COMMAND_HANDLER(stm32x_handle_lock_command)
1233 {
1234         struct target *target = NULL;
1235         struct stm32x_flash_bank *stm32x_info = NULL;
1236
1237         if (CMD_ARGC < 1)
1238                 return ERROR_COMMAND_SYNTAX_ERROR;
1239
1240         struct flash_bank *bank;
1241         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1242         if (ERROR_OK != retval)
1243                 return retval;
1244
1245         stm32x_info = bank->driver_priv;
1246         target = bank->target;
1247
1248         if (target->state != TARGET_HALTED) {
1249                 LOG_INFO("Target not halted");
1250                 /* return ERROR_TARGET_NOT_HALTED; */
1251         }
1252
1253         if (stm32x_read_options(bank) != ERROR_OK) {
1254                 command_print(CMD_CTX, "%s failed to read options", bank->driver->name);
1255                 return ERROR_OK;
1256         }
1257
1258         /* set readout protection */
1259         stm32x_info->option_bytes.RDP = 0;
1260
1261         if (stm32x_write_options(bank) != ERROR_OK) {
1262                 command_print(CMD_CTX, "%s failed to lock device", bank->driver->name);
1263                 return ERROR_OK;
1264         }
1265
1266         command_print(CMD_CTX, "%s locked", bank->driver->name);
1267
1268         return ERROR_OK;
1269 }
1270
1271 COMMAND_HANDLER(stm32x_handle_unlock_command)
1272 {
1273         struct target *target = NULL;
1274         struct stm32x_flash_bank *stm32x_info = NULL;
1275
1276         if (CMD_ARGC < 1)
1277                 return ERROR_COMMAND_SYNTAX_ERROR;
1278
1279         struct flash_bank *bank;
1280         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1281         if (ERROR_OK != retval)
1282                 return retval;
1283
1284         stm32x_info = bank->driver_priv;
1285         target = bank->target;
1286
1287         if (target->state != TARGET_HALTED) {
1288                 LOG_INFO("Target not halted");
1289                 /* return ERROR_TARGET_NOT_HALTED; */
1290         }
1291
1292         if (stm32x_read_options(bank) != ERROR_OK) {
1293                 command_print(CMD_CTX, "%s failed to read options", bank->driver->name);
1294                 return ERROR_OK;
1295         }
1296
1297         /* clear readout protection and complementary option bytes
1298          * this will also force a device unlock if set */
1299         stm32x_info->option_bytes.RDP = 0xAA;
1300         if (stm32x_info->has_optcr2_pcrop) {
1301                 stm32x_info->option_bytes.optcr2_pcrop = OPTCR2_PCROP_RDP | (~1U << bank->num_sectors);
1302         }
1303
1304         if (stm32x_write_options(bank) != ERROR_OK) {
1305                 command_print(CMD_CTX, "%s failed to unlock device", bank->driver->name);
1306                 return ERROR_OK;
1307         }
1308
1309         command_print(CMD_CTX, "%s unlocked.\n"
1310                         "INFO: a reset or power cycle is required "
1311                         "for the new settings to take effect.", bank->driver->name);
1312
1313         return ERROR_OK;
1314 }
1315
1316 static int stm32x_mass_erase(struct flash_bank *bank)
1317 {
1318         int retval;
1319         uint32_t flash_mer;
1320         struct target *target = bank->target;
1321         struct stm32x_flash_bank *stm32x_info = NULL;
1322
1323         if (target->state != TARGET_HALTED) {
1324                 LOG_ERROR("Target not halted");
1325                 return ERROR_TARGET_NOT_HALTED;
1326         }
1327
1328         stm32x_info = bank->driver_priv;
1329
1330         retval = stm32x_unlock_reg(target);
1331         if (retval != ERROR_OK)
1332                 return retval;
1333
1334         /* mass erase flash memory */
1335         if (stm32x_info->has_large_mem)
1336                 flash_mer = FLASH_MER | FLASH_MER1;
1337         else
1338                 flash_mer = FLASH_MER;
1339
1340         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), flash_mer);
1341         if (retval != ERROR_OK)
1342                 return retval;
1343         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
1344                 flash_mer | FLASH_STRT);
1345         if (retval != ERROR_OK)
1346                 return retval;
1347
1348         retval = stm32x_wait_status_busy(bank, FLASH_MASS_ERASE_TIMEOUT);
1349         if (retval != ERROR_OK)
1350                 return retval;
1351
1352         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
1353         if (retval != ERROR_OK)
1354                 return retval;
1355
1356         return ERROR_OK;
1357 }
1358
1359 COMMAND_HANDLER(stm32x_handle_mass_erase_command)
1360 {
1361         int i;
1362
1363         if (CMD_ARGC < 1) {
1364                 command_print(CMD_CTX, "stm32x mass_erase <bank>");
1365                 return ERROR_COMMAND_SYNTAX_ERROR;
1366         }
1367
1368         struct flash_bank *bank;
1369         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1370         if (ERROR_OK != retval)
1371                 return retval;
1372
1373         retval = stm32x_mass_erase(bank);
1374         if (retval == ERROR_OK) {
1375                 /* set all sectors as erased */
1376                 for (i = 0; i < bank->num_sectors; i++)
1377                         bank->sectors[i].is_erased = 1;
1378
1379                 command_print(CMD_CTX, "stm32x mass erase complete");
1380         } else {
1381                 command_print(CMD_CTX, "stm32x mass erase failed");
1382         }
1383
1384         return retval;
1385 }
1386
1387 COMMAND_HANDLER(stm32f2x_handle_options_read_command)
1388 {
1389         int retval;
1390         struct flash_bank *bank;
1391         struct stm32x_flash_bank *stm32x_info = NULL;
1392
1393         if (CMD_ARGC != 1) {
1394                 command_print(CMD_CTX, "stm32f2x options_read <bank>");
1395                 return ERROR_COMMAND_SYNTAX_ERROR;
1396         }
1397
1398         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1399         if (ERROR_OK != retval)
1400                 return retval;
1401
1402         retval = stm32x_read_options(bank);
1403         if (ERROR_OK != retval)
1404                 return retval;
1405
1406         stm32x_info = bank->driver_priv;
1407         if (stm32x_info->has_extra_options) {
1408                 if (stm32x_info->has_boot_addr) {
1409                         uint32_t boot_addr = stm32x_info->option_bytes.boot_addr;
1410
1411                         command_print(CMD_CTX, "stm32f2x user_options 0x%03X,"
1412                                 " boot_add0 0x%04X, boot_add1 0x%04X",
1413                                 stm32x_info->option_bytes.user_options,
1414                                 boot_addr & 0xffff, (boot_addr & 0xffff0000) >> 16);
1415                         if (stm32x_info->has_optcr2_pcrop) {
1416                                 command_print(CMD_CTX, "stm32f2x optcr2_pcrop 0x%08X",
1417                                                 stm32x_info->option_bytes.optcr2_pcrop);
1418                         }
1419                 } else {
1420                         command_print(CMD_CTX, "stm32f2x user_options 0x%03X",
1421                                 stm32x_info->option_bytes.user_options);
1422                 }
1423         } else {
1424                 command_print(CMD_CTX, "stm32f2x user_options 0x%02X",
1425                         stm32x_info->option_bytes.user_options);
1426
1427         }
1428
1429         return retval;
1430 }
1431
1432 COMMAND_HANDLER(stm32f2x_handle_options_write_command)
1433 {
1434         int retval;
1435         struct flash_bank *bank;
1436         struct stm32x_flash_bank *stm32x_info = NULL;
1437         uint16_t user_options, boot_addr0, boot_addr1, options_mask;
1438
1439         if (CMD_ARGC < 1) {
1440                 command_print(CMD_CTX, "stm32f2x options_write <bank> ...");
1441                 return ERROR_COMMAND_SYNTAX_ERROR;
1442         }
1443
1444         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1445         if (ERROR_OK != retval)
1446                 return retval;
1447
1448         retval = stm32x_read_options(bank);
1449         if (ERROR_OK != retval)
1450                 return retval;
1451
1452         stm32x_info = bank->driver_priv;
1453         if (stm32x_info->has_boot_addr) {
1454                 if (CMD_ARGC != 4) {
1455                         command_print(CMD_CTX, "stm32f2x options_write <bank> <user_options>"
1456                                 " <boot_addr0> <boot_addr1>");
1457                         return ERROR_COMMAND_SYNTAX_ERROR;
1458                 }
1459                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[2], boot_addr0);
1460                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[3], boot_addr1);
1461                 stm32x_info->option_bytes.boot_addr = boot_addr0 | (((uint32_t) boot_addr1) << 16);
1462         } else {
1463                 if (CMD_ARGC != 2) {
1464                         command_print(CMD_CTX, "stm32f2x options_write <bank> <user_options>");
1465                         return ERROR_COMMAND_SYNTAX_ERROR;
1466                 }
1467         }
1468
1469         COMMAND_PARSE_NUMBER(u16, CMD_ARGV[1], user_options);
1470         options_mask = !stm32x_info->has_extra_options ? ~0xfc :
1471                 ~(((0xf00 << (stm32x_info->protection_bits - 12)) | 0xff) & 0xffc);
1472         if (user_options & options_mask) {
1473                 command_print(CMD_CTX, "stm32f2x invalid user_options");
1474                 return ERROR_COMMAND_ARGUMENT_INVALID;
1475         }
1476
1477         stm32x_info->option_bytes.user_options = user_options;
1478
1479         if (stm32x_write_options(bank) != ERROR_OK) {
1480                 command_print(CMD_CTX, "stm32f2x failed to write options");
1481                 return ERROR_OK;
1482         }
1483
1484         /* switching between single- and dual-bank modes requires re-probe */
1485         /* ... and reprogramming of whole flash */
1486         stm32x_info->probed = 0;
1487
1488         command_print(CMD_CTX, "stm32f2x write options complete.\n"
1489                                 "INFO: a reset or power cycle is required "
1490                                 "for the new settings to take effect.");
1491         return retval;
1492 }
1493
1494 COMMAND_HANDLER(stm32f2x_handle_optcr2_write_command)
1495 {
1496         int retval;
1497         struct flash_bank *bank;
1498         struct stm32x_flash_bank *stm32x_info = NULL;
1499         uint32_t optcr2_pcrop;
1500
1501         if (CMD_ARGC != 2) {
1502                 command_print(CMD_CTX, "stm32f2x optcr2_write <bank> <optcr2_value>");
1503                 return ERROR_COMMAND_SYNTAX_ERROR;
1504         }
1505
1506         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1507         if (ERROR_OK != retval)
1508                 return retval;
1509
1510         stm32x_info = bank->driver_priv;
1511         if (!stm32x_info->has_optcr2_pcrop) {
1512                 command_print(CMD_CTX, "no optcr2 register");
1513                 return ERROR_COMMAND_ARGUMENT_INVALID;
1514         }
1515
1516         command_print(CMD_CTX, "INFO: To disable PCROP, set PCROP_RDP"
1517                                 " with PCROPi bits STILL SET, then\nlock device and"
1518                                 " finally unlock it. Clears PCROP and mass erases flash.");
1519
1520         retval = stm32x_read_options(bank);
1521         if (ERROR_OK != retval)
1522                 return retval;
1523
1524         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], optcr2_pcrop);
1525         stm32x_info->option_bytes.optcr2_pcrop = optcr2_pcrop;
1526
1527         if (stm32x_write_options(bank) != ERROR_OK) {
1528                 command_print(CMD_CTX, "stm32f2x failed to write options");
1529                 return ERROR_OK;
1530         }
1531
1532         command_print(CMD_CTX, "stm32f2x optcr2_write complete.");
1533         return retval;
1534 }
1535
1536 static const struct command_registration stm32x_exec_command_handlers[] = {
1537         {
1538                 .name = "lock",
1539                 .handler = stm32x_handle_lock_command,
1540                 .mode = COMMAND_EXEC,
1541                 .usage = "bank_id",
1542                 .help = "Lock entire flash device.",
1543         },
1544         {
1545                 .name = "unlock",
1546                 .handler = stm32x_handle_unlock_command,
1547                 .mode = COMMAND_EXEC,
1548                 .usage = "bank_id",
1549                 .help = "Unlock entire protected flash device.",
1550         },
1551         {
1552                 .name = "mass_erase",
1553                 .handler = stm32x_handle_mass_erase_command,
1554                 .mode = COMMAND_EXEC,
1555                 .usage = "bank_id",
1556                 .help = "Erase entire flash device.",
1557         },
1558         {
1559                 .name = "options_read",
1560                 .handler = stm32f2x_handle_options_read_command,
1561                 .mode = COMMAND_EXEC,
1562                 .usage = "bank_id",
1563                 .help = "Read and display device option bytes.",
1564         },
1565         {
1566                 .name = "options_write",
1567                 .handler = stm32f2x_handle_options_write_command,
1568                 .mode = COMMAND_EXEC,
1569                 .usage = "bank_id user_options [ boot_add0 boot_add1 ]",
1570                 .help = "Write option bytes",
1571         },
1572         {
1573                 .name = "optcr2_write",
1574                 .handler = stm32f2x_handle_optcr2_write_command,
1575                 .mode = COMMAND_EXEC,
1576                 .usage = "bank_id optcr2",
1577                 .help = "Write optcr2 word",
1578         },
1579
1580         COMMAND_REGISTRATION_DONE
1581 };
1582
1583 static const struct command_registration stm32x_command_handlers[] = {
1584         {
1585                 .name = "stm32f2x",
1586                 .mode = COMMAND_ANY,
1587                 .help = "stm32f2x flash command group",
1588                 .usage = "",
1589                 .chain = stm32x_exec_command_handlers,
1590         },
1591         COMMAND_REGISTRATION_DONE
1592 };
1593
1594 struct flash_driver stm32f2x_flash = {
1595         .name = "stm32f2x",
1596         .commands = stm32x_command_handlers,
1597         .flash_bank_command = stm32x_flash_bank_command,
1598         .erase = stm32x_erase,
1599         .protect = stm32x_protect,
1600         .write = stm32x_write,
1601         .read = default_flash_read,
1602         .probe = stm32x_probe,
1603         .auto_probe = stm32x_auto_probe,
1604         .erase_check = default_flash_blank_check,
1605         .protect_check = stm32x_protect_check,
1606         .info = get_stm32x_info,
1607         .free_driver_priv = default_flash_free_driver_priv,
1608 };