src/flash/nor/stm32f2x: fix format strings
[fw/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 FLASH_BANK_BASE     0x80000000
127
128 #define STM32F2_OTP_SIZE 512
129 #define STM32F2_OTP_SECTOR_SIZE 32
130 #define STM32F2_OTP_BANK_BASE       0x1fff7800
131 #define STM32F2_OTP_LOCK_BASE       ((STM32F2_OTP_BANK_BASE) + (STM32F2_OTP_SIZE))
132
133 /* see RM0410 section 3.6 "One-time programmable bytes" */
134 #define STM32F7_OTP_SECTOR_SIZE 64
135 #define STM32F7_OTP_SIZE 1024
136 #define STM32F7_OTP_BANK_BASE       0x1ff0f000
137 #define STM32F7_OTP_LOCK_BASE       ((STM32F7_OTP_BANK_BASE) + (STM32F7_OTP_SIZE))
138
139 #define STM32_FLASH_BASE    0x40023c00
140 #define STM32_FLASH_ACR     0x40023c00
141 #define STM32_FLASH_KEYR    0x40023c04
142 #define STM32_FLASH_OPTKEYR 0x40023c08
143 #define STM32_FLASH_SR      0x40023c0C
144 #define STM32_FLASH_CR      0x40023c10
145 #define STM32_FLASH_OPTCR   0x40023c14
146 #define STM32_FLASH_OPTCR1  0x40023c18
147 #define STM32_FLASH_OPTCR2  0x40023c1c
148
149 /* FLASH_CR register bits */
150 #define FLASH_PG       (1 << 0)
151 #define FLASH_SER      (1 << 1)
152 #define FLASH_MER      (1 << 2)         /* MER/MER1 for f76x/77x */
153 #define FLASH_MER1     (1 << 15)        /* MER2 for f76x/77x, confusing ... */
154 #define FLASH_STRT     (1 << 16)
155 #define FLASH_PSIZE_8  (0 << 8)
156 #define FLASH_PSIZE_16 (1 << 8)
157 #define FLASH_PSIZE_32 (2 << 8)
158 #define FLASH_PSIZE_64 (3 << 8)
159 /* The sector number encoding is not straight binary for dual bank flash. */
160 #define FLASH_SNB(a)   ((a) << 3)
161 #define FLASH_LOCK     (1 << 31)
162
163 /* FLASH_SR register bits */
164 #define FLASH_BSY      (1 << 16)
165 #define FLASH_PGSERR   (1 << 7) /* Programming sequence error */
166 #define FLASH_PGPERR   (1 << 6) /* Programming parallelism error */
167 #define FLASH_PGAERR   (1 << 5) /* Programming alignment error */
168 #define FLASH_WRPERR   (1 << 4) /* Write protection error */
169 #define FLASH_OPERR    (1 << 1) /* Operation error */
170
171 #define FLASH_ERROR (FLASH_PGSERR | FLASH_PGPERR | FLASH_PGAERR | FLASH_WRPERR | FLASH_OPERR)
172
173 /* STM32_FLASH_OPTCR register bits */
174 #define OPTCR_LOCK     (1 << 0)
175 #define OPTCR_START    (1 << 1)
176 #define OPTCR_NDBANK   (1 << 29)        /* not dual bank mode */
177 #define OPTCR_DB1M     (1 << 30)        /* 1 MiB devices dual flash bank option */
178 #define OPTCR_SPRMOD   (1 << 31)        /* switches PCROPi/nWPRi interpretation */
179
180 /* STM32_FLASH_OPTCR2 register bits */
181 #define OPTCR2_PCROP_RDP        (1 << 31)       /* erase PCROP zone when decreasing RDP */
182
183 /* register unlock keys */
184 #define KEY1           0x45670123
185 #define KEY2           0xCDEF89AB
186
187 /* option register unlock key */
188 #define OPTKEY1        0x08192A3B
189 #define OPTKEY2        0x4C5D6E7F
190
191 struct stm32x_options {
192         uint8_t RDP;
193         uint16_t user_options;  /* bit 0-7 usual options, bit 8-11 extra options */
194         uint32_t protection;
195         uint32_t boot_addr;
196         uint32_t optcr2_pcrop;
197 };
198
199 struct stm32x_flash_bank {
200         struct stm32x_options option_bytes;
201         bool probed;
202         bool otp_unlocked;
203         bool has_large_mem;             /* F42x/43x/469/479/7xx in dual bank mode */
204         bool has_extra_options; /* F42x/43x/469/479/7xx */
205         bool has_boot_addr;     /* F7xx */
206         bool has_optcr2_pcrop;  /* F72x/73x */
207         int protection_bits;    /* F413/423 */
208         uint32_t user_bank_size;
209 };
210
211 static bool stm32x_is_otp(struct flash_bank *bank)
212 {
213         return bank->base == STM32F2_OTP_BANK_BASE ||
214                 bank->base == STM32F7_OTP_BANK_BASE;
215 }
216
217 static bool stm32x_otp_is_f7(struct flash_bank *bank)
218 {
219         return bank->base == STM32F7_OTP_BANK_BASE;
220 }
221
222 static int stm32x_is_otp_unlocked(struct flash_bank *bank)
223 {
224         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
225
226         return stm32x_info->otp_unlocked;
227 }
228
229 static int stm32x_otp_disable(struct flash_bank *bank)
230 {
231         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
232
233         LOG_INFO("OTP memory bank #%u is disabled for write commands.",
234                  bank->bank_number);
235         stm32x_info->otp_unlocked = false;
236         return ERROR_OK;
237 }
238
239 static int stm32x_otp_enable(struct flash_bank *bank)
240 {
241         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
242
243         if (!stm32x_info->otp_unlocked) {
244                 LOG_INFO("OTP memory bank #%u is is enabled for write commands.",
245                          bank->bank_number);
246                 stm32x_info->otp_unlocked = true;
247         } else {
248                 LOG_WARNING("OTP memory bank #%u is is already enabled for write commands.",
249                             bank->bank_number);
250         }
251         return ERROR_OK;
252 }
253
254 /* flash bank stm32x <base> <size> 0 0 <target#>
255  */
256 FLASH_BANK_COMMAND_HANDLER(stm32x_flash_bank_command)
257 {
258         struct stm32x_flash_bank *stm32x_info;
259
260         if (CMD_ARGC < 6)
261                 return ERROR_COMMAND_SYNTAX_ERROR;
262
263         stm32x_info = malloc(sizeof(struct stm32x_flash_bank));
264         bank->driver_priv = stm32x_info;
265
266         stm32x_info->probed = false;
267         stm32x_info->otp_unlocked = false;
268         stm32x_info->user_bank_size = bank->size;
269
270         return ERROR_OK;
271 }
272
273 static inline int stm32x_get_flash_reg(struct flash_bank *bank, uint32_t reg)
274 {
275         return reg;
276 }
277
278 static inline int stm32x_get_flash_status(struct flash_bank *bank, uint32_t *status)
279 {
280         struct target *target = bank->target;
281         return target_read_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR), status);
282 }
283
284 static int stm32x_wait_status_busy(struct flash_bank *bank, int timeout)
285 {
286         struct target *target = bank->target;
287         uint32_t status;
288         int retval = ERROR_OK;
289
290         /* wait for busy to clear */
291         for (;;) {
292                 retval = stm32x_get_flash_status(bank, &status);
293                 if (retval != ERROR_OK)
294                         return retval;
295                 LOG_DEBUG("status: 0x%" PRIx32, status);
296                 if ((status & FLASH_BSY) == 0)
297                         break;
298                 if (timeout-- <= 0) {
299                         LOG_ERROR("timed out waiting for flash");
300                         return ERROR_FAIL;
301                 }
302                 alive_sleep(1);
303         }
304
305
306         if (status & FLASH_WRPERR) {
307                 LOG_ERROR("stm32x device protected");
308                 retval = ERROR_FAIL;
309         }
310
311         /* Clear but report errors */
312         if (status & FLASH_ERROR) {
313                 if (retval == ERROR_OK)
314                         retval = ERROR_FAIL;
315                 /* If this operation fails, we ignore it and report the original
316                  * retval
317                  */
318                 target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR),
319                                 status & FLASH_ERROR);
320         }
321         return retval;
322 }
323
324 static int stm32x_unlock_reg(struct target *target)
325 {
326         uint32_t ctrl;
327
328         /* first check if not already unlocked
329          * otherwise writing on STM32_FLASH_KEYR will fail
330          */
331         int retval = target_read_u32(target, STM32_FLASH_CR, &ctrl);
332         if (retval != ERROR_OK)
333                 return retval;
334
335         if ((ctrl & FLASH_LOCK) == 0)
336                 return ERROR_OK;
337
338         /* unlock flash registers */
339         retval = target_write_u32(target, STM32_FLASH_KEYR, KEY1);
340         if (retval != ERROR_OK)
341                 return retval;
342
343         retval = target_write_u32(target, STM32_FLASH_KEYR, KEY2);
344         if (retval != ERROR_OK)
345                 return retval;
346
347         retval = target_read_u32(target, STM32_FLASH_CR, &ctrl);
348         if (retval != ERROR_OK)
349                 return retval;
350
351         if (ctrl & FLASH_LOCK) {
352                 LOG_ERROR("flash not unlocked STM32_FLASH_CR: 0x%" PRIx32, ctrl);
353                 return ERROR_TARGET_FAILURE;
354         }
355
356         return ERROR_OK;
357 }
358
359 static int stm32x_unlock_option_reg(struct target *target)
360 {
361         uint32_t ctrl;
362
363         int retval = target_read_u32(target, STM32_FLASH_OPTCR, &ctrl);
364         if (retval != ERROR_OK)
365                 return retval;
366
367         if ((ctrl & OPTCR_LOCK) == 0)
368                 return ERROR_OK;
369
370         /* unlock option registers */
371         retval = target_write_u32(target, STM32_FLASH_OPTKEYR, OPTKEY1);
372         if (retval != ERROR_OK)
373                 return retval;
374
375         retval = target_write_u32(target, STM32_FLASH_OPTKEYR, OPTKEY2);
376         if (retval != ERROR_OK)
377                 return retval;
378
379         retval = target_read_u32(target, STM32_FLASH_OPTCR, &ctrl);
380         if (retval != ERROR_OK)
381                 return retval;
382
383         if (ctrl & OPTCR_LOCK) {
384                 LOG_ERROR("options not unlocked STM32_FLASH_OPTCR: 0x%" PRIx32, ctrl);
385                 return ERROR_TARGET_FAILURE;
386         }
387
388         return ERROR_OK;
389 }
390
391 static int stm32x_read_options(struct flash_bank *bank)
392 {
393         uint32_t optiondata;
394         struct stm32x_flash_bank *stm32x_info = NULL;
395         struct target *target = bank->target;
396
397         stm32x_info = bank->driver_priv;
398
399         /* read current option bytes */
400         int retval = target_read_u32(target, STM32_FLASH_OPTCR, &optiondata);
401         if (retval != ERROR_OK)
402                 return retval;
403
404     /* caution: F2 implements 5 bits (WDG_SW only)
405      * whereas F7 6 bits (IWDG_SW and WWDG_SW) in user_options */
406         stm32x_info->option_bytes.user_options = optiondata & 0xfc;
407         stm32x_info->option_bytes.RDP = (optiondata >> 8) & 0xff;
408         stm32x_info->option_bytes.protection =
409                 (optiondata >> 16) & (~(0xffff << stm32x_info->protection_bits) & 0xffff);
410
411         if (stm32x_info->has_extra_options) {
412                 /* F42x/43x/469/479 and 7xx have up to 4 bits of extra options */
413                 stm32x_info->option_bytes.user_options |= (optiondata >> 20) &
414                         ((0xf00 << (stm32x_info->protection_bits - 12)) & 0xf00);
415         }
416
417         if (stm32x_info->has_large_mem || stm32x_info->has_boot_addr) {
418                 retval = target_read_u32(target, STM32_FLASH_OPTCR1, &optiondata);
419                 if (retval != ERROR_OK)
420                         return retval;
421
422                 /* FLASH_OPTCR1 has quite diffent meanings ... */
423                 if (stm32x_info->has_boot_addr) {
424                         /* for F7xx it contains boot0 and boot1 */
425                         stm32x_info->option_bytes.boot_addr = optiondata;
426                 } else {
427                         /* for F42x/43x/469/479 it contains 12 additional protection bits */
428                         stm32x_info->option_bytes.protection |= (optiondata >> 4) & 0x00fff000;
429                 }
430         }
431
432         if (stm32x_info->has_optcr2_pcrop) {
433                 retval = target_read_u32(target, STM32_FLASH_OPTCR2, &optiondata);
434                 if (retval != ERROR_OK)
435                         return retval;
436
437                 stm32x_info->option_bytes.optcr2_pcrop = optiondata;
438                 if (stm32x_info->has_optcr2_pcrop &&
439                         (stm32x_info->option_bytes.optcr2_pcrop & ~OPTCR2_PCROP_RDP)) {
440                         LOG_INFO("PCROP Engaged");
441                 }
442         } else {
443                 stm32x_info->option_bytes.optcr2_pcrop = 0x0;
444         }
445
446         if (stm32x_info->option_bytes.RDP != 0xAA)
447                 LOG_INFO("Device Security Bit Set");
448
449         return ERROR_OK;
450 }
451
452 static int stm32x_write_options(struct flash_bank *bank)
453 {
454         struct stm32x_flash_bank *stm32x_info = NULL;
455         struct target *target = bank->target;
456         uint32_t optiondata, optiondata2;
457
458         stm32x_info = bank->driver_priv;
459
460         int retval = stm32x_unlock_option_reg(target);
461         if (retval != ERROR_OK)
462                 return retval;
463
464         /* rebuild option data */
465         optiondata = stm32x_info->option_bytes.user_options & 0xfc;
466         optiondata |= stm32x_info->option_bytes.RDP << 8;
467         optiondata |= (stm32x_info->option_bytes.protection &
468                 (~(0xffff << stm32x_info->protection_bits))) << 16;
469
470         if (stm32x_info->has_extra_options) {
471                 /* F42x/43x/469/479 and 7xx have up to 4 bits of extra options */
472                 optiondata |= (stm32x_info->option_bytes.user_options &
473                         ((0xf00 << (stm32x_info->protection_bits - 12)) & 0xf00)) << 20;
474         }
475
476         if (stm32x_info->has_large_mem || stm32x_info->has_boot_addr) {
477                 if (stm32x_info->has_boot_addr) {
478                         /* F7xx uses FLASH_OPTCR1 for boot0 and boot1 ... */
479                         optiondata2 = stm32x_info->option_bytes.boot_addr;
480                 } else {
481                         /* F42x/43x/469/479 uses FLASH_OPTCR1 for additional protection bits */
482                         optiondata2 = (stm32x_info->option_bytes.protection & 0x00fff000) << 4;
483                 }
484
485                 retval = target_write_u32(target, STM32_FLASH_OPTCR1, optiondata2);
486                 if (retval != ERROR_OK)
487                         return retval;
488         }
489
490         /* program extra pcrop register */
491         if (stm32x_info->has_optcr2_pcrop) {
492                 retval = target_write_u32(target, STM32_FLASH_OPTCR2,
493                         stm32x_info->option_bytes.optcr2_pcrop);
494                 if (retval != ERROR_OK)
495                         return retval;
496         }
497
498         /* program options */
499         retval = target_write_u32(target, STM32_FLASH_OPTCR, optiondata);
500         if (retval != ERROR_OK)
501                 return retval;
502
503         /* start programming cycle */
504         retval = target_write_u32(target, STM32_FLASH_OPTCR, optiondata | OPTCR_START);
505         if (retval != ERROR_OK)
506                 return retval;
507
508         /* wait for completion, this might trigger a security erase and take a while */
509         retval = stm32x_wait_status_busy(bank, FLASH_MASS_ERASE_TIMEOUT);
510         if (retval != ERROR_OK)
511                 return retval;
512
513         /* relock registers */
514         retval = target_write_u32(target, STM32_FLASH_OPTCR, optiondata | OPTCR_LOCK);
515         if (retval != ERROR_OK)
516                 return retval;
517
518         return ERROR_OK;
519 }
520
521 static int stm32x_otp_read_protect(struct flash_bank *bank)
522 {
523         struct target *target = bank->target;
524         uint32_t lock_base;
525         int retval;
526         uint8_t lock;
527
528         lock_base = stm32x_otp_is_f7(bank) ? STM32F7_OTP_LOCK_BASE
529                   : STM32F2_OTP_LOCK_BASE;
530
531         for (unsigned int i = 0; i < bank->num_sectors; i++) {
532                 retval = target_read_u8(target, lock_base + i, &lock);
533                 if (retval != ERROR_OK)
534                         return retval;
535                 bank->sectors[i].is_protected = !lock;
536         }
537
538         return ERROR_OK;
539 }
540
541 static int stm32x_otp_protect(struct flash_bank *bank, unsigned int first,
542                 unsigned int last)
543 {
544         struct target *target = bank->target;
545         uint32_t lock_base;
546         int i, retval;
547         uint8_t lock;
548
549         assert((first <= last) && (last < bank->num_sectors));
550
551         lock_base = stm32x_otp_is_f7(bank) ? STM32F7_OTP_LOCK_BASE
552                   : STM32F2_OTP_LOCK_BASE;
553
554         for (i = first; first <= last; i++) {
555                 retval = target_read_u8(target, lock_base + i, &lock);
556                 if (retval != ERROR_OK)
557                         return retval;
558                 if (lock)
559                         continue;
560
561                 lock = 0xff;
562                 retval = target_write_u8(target, lock_base + i, lock);
563                 if (retval != ERROR_OK)
564                         return retval;
565         }
566
567         return ERROR_OK;
568 }
569
570 static int stm32x_protect_check(struct flash_bank *bank)
571 {
572         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
573         struct flash_sector *prot_blocks;
574         int num_prot_blocks;
575         int retval;
576
577         /* if it's the OTP bank, look at the lock bits there */
578         if (stm32x_is_otp(bank))
579                 return stm32x_otp_read_protect(bank);
580
581         /* read write protection settings */
582         retval = stm32x_read_options(bank);
583         if (retval != ERROR_OK) {
584                 LOG_DEBUG("unable to read option bytes");
585                 return retval;
586         }
587
588         if (bank->prot_blocks) {
589                 num_prot_blocks = bank->num_prot_blocks;
590                 prot_blocks = bank->prot_blocks;
591         } else {
592                 num_prot_blocks = bank->num_sectors;
593                 prot_blocks = bank->sectors;
594         }
595
596         for (int i = 0; i < num_prot_blocks; i++)
597                 prot_blocks[i].is_protected =
598                         ~(stm32x_info->option_bytes.protection >> i) & 1;
599
600         return ERROR_OK;
601 }
602
603 static int stm32x_erase(struct flash_bank *bank, unsigned int first,
604                 unsigned int last)
605 {
606         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
607         struct target *target = bank->target;
608
609         if (stm32x_is_otp(bank)) {
610                 LOG_ERROR("Cannot erase OTP memory");
611                 return ERROR_FAIL;
612         }
613
614         assert((first <= last) && (last < bank->num_sectors));
615
616         if (bank->target->state != TARGET_HALTED) {
617                 LOG_ERROR("Target not halted");
618                 return ERROR_TARGET_NOT_HALTED;
619         }
620
621         int retval;
622         retval = stm32x_unlock_reg(target);
623         if (retval != ERROR_OK)
624                 return retval;
625
626         /*
627         Sector Erase
628         To erase a sector, follow the procedure below:
629         1. Check that no Flash memory operation is ongoing by checking the BSY bit in the
630           FLASH_SR register
631         2. Set the SER bit and select the sector
632           you wish to erase (SNB) in the FLASH_CR register
633         3. Set the STRT bit in the FLASH_CR register
634         4. Wait for the BSY bit to be cleared
635          */
636
637         for (unsigned int i = first; i <= last; i++) {
638                 unsigned int snb;
639                 if (stm32x_info->has_large_mem && i >= 12)
640                         snb = (i - 12) | 0x10;
641                 else
642                         snb = i;
643
644                 retval = target_write_u32(target,
645                                 stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_SER | FLASH_SNB(snb) | FLASH_STRT);
646                 if (retval != ERROR_OK)
647                         return retval;
648
649                 retval = stm32x_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
650                 if (retval != ERROR_OK)
651                         return retval;
652
653                 bank->sectors[i].is_erased = 1;
654         }
655
656         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
657         if (retval != ERROR_OK)
658                 return retval;
659
660         return ERROR_OK;
661 }
662
663 static int stm32x_protect(struct flash_bank *bank, int set, unsigned int first,
664                 unsigned int last)
665 {
666         struct target *target = bank->target;
667         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
668
669         if (target->state != TARGET_HALTED) {
670                 LOG_ERROR("Target not halted");
671                 return ERROR_TARGET_NOT_HALTED;
672         }
673
674         if (stm32x_is_otp(bank)) {
675                 if (!set)
676                         return ERROR_COMMAND_ARGUMENT_INVALID;
677
678                 return stm32x_otp_protect(bank, first, last);
679         }
680
681         /* read protection settings */
682         int retval = stm32x_read_options(bank);
683         if (retval != ERROR_OK) {
684                 LOG_DEBUG("unable to read option bytes");
685                 return retval;
686         }
687
688         for (unsigned int i = first; i <= last; i++) {
689                 if (set)
690                         stm32x_info->option_bytes.protection &= ~(1 << i);
691                 else
692                         stm32x_info->option_bytes.protection |= (1 << i);
693         }
694
695         retval = stm32x_write_options(bank);
696         if (retval != ERROR_OK)
697                 return retval;
698
699         return ERROR_OK;
700 }
701
702 static int stm32x_write_block(struct flash_bank *bank, const uint8_t *buffer,
703                 uint32_t offset, uint32_t count)
704 {
705         struct target *target = bank->target;
706         uint32_t buffer_size = 16384;
707         struct working_area *write_algorithm;
708         struct working_area *source;
709         uint32_t address = bank->base + offset;
710         struct reg_param reg_params[5];
711         struct armv7m_algorithm armv7m_info;
712         int retval = ERROR_OK;
713
714         static const uint8_t stm32x_flash_write_code[] = {
715 #include "../../../contrib/loaders/flash/stm32/stm32f2x.inc"
716         };
717
718         if (stm32x_is_otp(bank) && !stm32x_is_otp_unlocked(bank)) {
719                 LOG_ERROR("OTP memory bank is disabled for write commands.");
720                 return ERROR_FAIL;
721         }
722
723         if (target_alloc_working_area(target, sizeof(stm32x_flash_write_code),
724                         &write_algorithm) != ERROR_OK) {
725                 LOG_WARNING("no working area available, can't do block memory writes");
726                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
727         }
728
729         retval = target_write_buffer(target, write_algorithm->address,
730                         sizeof(stm32x_flash_write_code),
731                         stm32x_flash_write_code);
732         if (retval != ERROR_OK) {
733                 target_free_working_area(target, write_algorithm);
734                 return retval;
735         }
736
737         /* memory buffer */
738         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) {
739                 buffer_size /= 2;
740                 if (buffer_size <= 256) {
741                         /* we already allocated the writing code, but failed to get a
742                          * buffer, free the algorithm */
743                         target_free_working_area(target, write_algorithm);
744
745                         LOG_WARNING("no large enough working area available, can't do block memory writes");
746                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
747                 }
748         }
749
750         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
751         armv7m_info.core_mode = ARM_MODE_THREAD;
752
753         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT);         /* buffer start, status (out) */
754         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);            /* buffer end */
755         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);            /* target address */
756         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);            /* count (halfword-16bit) */
757         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);            /* flash base */
758
759         buf_set_u32(reg_params[0].value, 0, 32, source->address);
760         buf_set_u32(reg_params[1].value, 0, 32, source->address + source->size);
761         buf_set_u32(reg_params[2].value, 0, 32, address);
762         buf_set_u32(reg_params[3].value, 0, 32, count);
763         buf_set_u32(reg_params[4].value, 0, 32, STM32_FLASH_BASE);
764
765         retval = target_run_flash_async_algorithm(target, buffer, count, 2,
766                         0, NULL,
767                         5, reg_params,
768                         source->address, source->size,
769                         write_algorithm->address, 0,
770                         &armv7m_info);
771
772         if (retval == ERROR_FLASH_OPERATION_FAILED) {
773                 LOG_ERROR("error executing stm32x flash write algorithm");
774
775                 uint32_t error = buf_get_u32(reg_params[0].value, 0, 32) & FLASH_ERROR;
776
777                 if (error & FLASH_WRPERR)
778                         LOG_ERROR("flash memory write protected");
779
780                 if (error != 0) {
781                         LOG_ERROR("flash write failed = 0x%08" PRIx32, error);
782                         /* Clear but report errors */
783                         target_write_u32(target, STM32_FLASH_SR, error);
784                         retval = ERROR_FAIL;
785                 }
786         }
787
788         target_free_working_area(target, source);
789         target_free_working_area(target, write_algorithm);
790
791         destroy_reg_param(&reg_params[0]);
792         destroy_reg_param(&reg_params[1]);
793         destroy_reg_param(&reg_params[2]);
794         destroy_reg_param(&reg_params[3]);
795         destroy_reg_param(&reg_params[4]);
796
797         return retval;
798 }
799
800 static int stm32x_write(struct flash_bank *bank, const uint8_t *buffer,
801                 uint32_t offset, uint32_t count)
802 {
803         struct target *target = bank->target;
804         uint32_t words_remaining = (count / 2);
805         uint32_t bytes_remaining = (count & 0x00000001);
806         uint32_t address = bank->base + offset;
807         uint32_t bytes_written = 0;
808         int retval;
809
810         if (bank->target->state != TARGET_HALTED) {
811                 LOG_ERROR("Target not halted");
812                 return ERROR_TARGET_NOT_HALTED;
813         }
814
815         if (offset & 0x1) {
816                 LOG_WARNING("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
817                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
818         }
819
820         retval = stm32x_unlock_reg(target);
821         if (retval != ERROR_OK)
822                 return retval;
823
824         /* multiple half words (2-byte) to be programmed? */
825         if (words_remaining > 0) {
826                 /* try using a block write */
827                 retval = stm32x_write_block(bank, buffer, offset, words_remaining);
828                 if (retval != ERROR_OK) {
829                         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
830                                 /* if block write failed (no sufficient working area),
831                                  * we use normal (slow) single dword accesses */
832                                 LOG_WARNING("couldn't use block writes, falling back to single memory accesses");
833                         }
834                 } else {
835                         buffer += words_remaining * 2;
836                         address += words_remaining * 2;
837                         words_remaining = 0;
838                 }
839         }
840
841         if ((retval != ERROR_OK) && (retval != ERROR_TARGET_RESOURCE_NOT_AVAILABLE))
842                 return retval;
843
844         /*
845         Standard programming
846         The Flash memory programming sequence is as follows:
847         1. Check that no main Flash memory operation is ongoing by checking the BSY bit in the
848           FLASH_SR register.
849         2. Set the PG bit in the FLASH_CR register
850         3. Perform the data write operation(s) to the desired memory address (inside main
851           memory block or OTP area):
852         â€“ â€“ Half-word access in case of x16 parallelism
853         â€“ Word access in case of x32 parallelism
854         â€“
855         4.
856         Byte access in case of x8 parallelism
857         Double word access in case of x64 parallelism
858         Wait for the BSY bit to be cleared
859         */
860         while (words_remaining > 0) {
861                 uint16_t value;
862                 memcpy(&value, buffer + bytes_written, sizeof(uint16_t));
863
864                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
865                                 FLASH_PG | FLASH_PSIZE_16);
866                 if (retval != ERROR_OK)
867                         return retval;
868
869                 retval = target_write_u16(target, address, value);
870                 if (retval != ERROR_OK)
871                         return retval;
872
873                 retval = stm32x_wait_status_busy(bank, FLASH_WRITE_TIMEOUT);
874                 if (retval != ERROR_OK)
875                         return retval;
876
877                 bytes_written += 2;
878                 words_remaining--;
879                 address += 2;
880         }
881
882         if (bytes_remaining) {
883                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
884                                 FLASH_PG | FLASH_PSIZE_8);
885                 if (retval != ERROR_OK)
886                         return retval;
887                 retval = target_write_u8(target, address, buffer[bytes_written]);
888                 if (retval != ERROR_OK)
889                         return retval;
890
891                 retval = stm32x_wait_status_busy(bank, FLASH_WRITE_TIMEOUT);
892                 if (retval != ERROR_OK)
893                         return retval;
894         }
895
896         return target_write_u32(target, STM32_FLASH_CR, FLASH_LOCK);
897 }
898
899 static void setup_sector(struct flash_bank *bank, unsigned int i,
900                 unsigned int size)
901 {
902         assert(i < bank->num_sectors);
903         bank->sectors[i].offset = bank->size;
904         bank->sectors[i].size = size;
905         bank->size += bank->sectors[i].size;
906         LOG_DEBUG("sector %u: %ukBytes", i, size >> 10);
907 }
908
909 static uint16_t sector_size_in_kb(int i, uint16_t max_sector_size_in_kb)
910 {
911         assert(i >= 0);
912         if (i < 4)
913                 return max_sector_size_in_kb / 8;
914         if (i == 4)
915                 return max_sector_size_in_kb / 2;
916         return max_sector_size_in_kb;
917 }
918
919 static int calculate_number_of_sectors(struct flash_bank *bank,
920                 uint16_t flash_size_in_kb,
921                 uint16_t max_sector_size_in_kb)
922 {
923         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
924         uint16_t remaining_flash_size_in_kb = flash_size_in_kb;
925         int nr_sectors;
926
927         /* Dual Bank Flash has two identically-arranged banks of sectors. */
928         if (stm32x_info->has_large_mem)
929                 remaining_flash_size_in_kb /= 2;
930
931         for (nr_sectors = 0; remaining_flash_size_in_kb > 0; nr_sectors++) {
932                 uint16_t size_in_kb = sector_size_in_kb(nr_sectors, max_sector_size_in_kb);
933                 if (size_in_kb > remaining_flash_size_in_kb) {
934                         LOG_INFO("%s Bank %" PRIu16 " kiB final sector clipped to %" PRIu16 " kiB",
935                                  stm32x_info->has_large_mem ? "Dual" : "Single",
936                                  flash_size_in_kb, remaining_flash_size_in_kb);
937                         remaining_flash_size_in_kb = 0;
938                 } else {
939                         remaining_flash_size_in_kb -= size_in_kb;
940                 }
941         }
942
943         return stm32x_info->has_large_mem ? nr_sectors*2 : nr_sectors;
944 }
945
946 static void setup_bank(struct flash_bank *bank, int start,
947         uint16_t flash_size_in_kb, uint16_t max_sector_size_in_kb)
948 {
949         uint16_t remaining_flash_size_in_kb = flash_size_in_kb;
950         int sector_index = 0;
951         while (remaining_flash_size_in_kb > 0) {
952                 uint16_t size_in_kb = sector_size_in_kb(sector_index, max_sector_size_in_kb);
953                 if (size_in_kb > remaining_flash_size_in_kb) {
954                         /* Clip last sector. Already warned in
955                          * calculate_number_of_sectors. */
956                         size_in_kb = remaining_flash_size_in_kb;
957                 }
958                 setup_sector(bank, start + sector_index, size_in_kb * 1024);
959                 remaining_flash_size_in_kb -= size_in_kb;
960                 sector_index++;
961         }
962 }
963
964 static int stm32x_get_device_id(struct flash_bank *bank, uint32_t *device_id)
965 {
966         /* this checks for a stm32f4x errata issue where a
967          * stm32f2x DBGMCU_IDCODE is incorrectly returned.
968          * If the issue is detected target is forced to stm32f4x Rev A.
969          * Only effects Rev A silicon */
970
971         struct target *target = bank->target;
972         uint32_t cpuid;
973
974         /* read stm32 device id register */
975         int retval = target_read_u32(target, 0xE0042000, device_id);
976         if (retval != ERROR_OK)
977                 return retval;
978
979         if ((*device_id & 0xfff) == 0x411) {
980                 /* read CPUID reg to check core type */
981                 retval = target_read_u32(target, 0xE000ED00, &cpuid);
982                 if (retval != ERROR_OK)
983                         return retval;
984
985                 /* check for cortex_m4 */
986                 if (((cpuid >> 4) & 0xFFF) == 0xC24) {
987                         *device_id &= ~((0xFFFF << 16) | 0xfff);
988                         *device_id |= (0x1000 << 16) | 0x413;
989                         LOG_INFO("stm32f4x errata detected - fixing incorrect MCU_IDCODE");
990                 }
991         }
992         return retval;
993 }
994
995 static int stm32x_probe(struct flash_bank *bank)
996 {
997         struct target *target = bank->target;
998         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
999         int i, num_prot_blocks, num_sectors;
1000         uint16_t flash_size_in_kb;
1001         uint16_t otp_size_in_b;
1002         uint16_t otp_sector_size;
1003         uint32_t flash_size_reg = 0x1FFF7A22;
1004         uint16_t max_sector_size_in_kb = 128;
1005         uint16_t max_flash_size_in_kb;
1006         uint32_t device_id;
1007         uint32_t base_address = 0x08000000;
1008
1009         stm32x_info->probed = false;
1010         stm32x_info->has_large_mem = false;
1011         stm32x_info->has_boot_addr = false;
1012         stm32x_info->has_extra_options = false;
1013         stm32x_info->has_optcr2_pcrop = false;
1014         stm32x_info->protection_bits = 12;              /* max. number of nWRPi bits (in FLASH_OPTCR !!!) */
1015         num_prot_blocks = 0;
1016
1017         if (bank->sectors) {
1018                 free(bank->sectors);
1019                 bank->num_sectors = 0;
1020                 bank->sectors = NULL;
1021         }
1022
1023         if (bank->prot_blocks) {
1024                 free(bank->prot_blocks);
1025                 bank->num_prot_blocks = 0;
1026                 bank->prot_blocks = NULL;
1027         }
1028
1029         /* if explicitely called out as OTP bank, short circuit probe */
1030         if (stm32x_is_otp(bank)) {
1031                 if (stm32x_otp_is_f7(bank)) {
1032                         otp_size_in_b = STM32F7_OTP_SIZE;
1033                         otp_sector_size = STM32F7_OTP_SECTOR_SIZE;
1034                 } else {
1035                         otp_size_in_b = STM32F2_OTP_SIZE;
1036                         otp_sector_size = STM32F2_OTP_SECTOR_SIZE;
1037                 }
1038
1039                 num_sectors = otp_size_in_b / otp_sector_size;
1040                 LOG_INFO("flash size = %" PRIu16 " bytes", otp_size_in_b);
1041
1042                 assert(num_sectors > 0);
1043
1044                 bank->num_sectors = num_sectors;
1045                 bank->sectors = calloc(sizeof(struct flash_sector), num_sectors);
1046
1047                 if (stm32x_otp_is_f7(bank))
1048                         bank->size = STM32F7_OTP_SIZE;
1049                 else
1050                         bank->size = STM32F2_OTP_SIZE;
1051
1052                 for (i = 0; i < num_sectors; i++) {
1053                         bank->sectors[i].offset = i * otp_sector_size;
1054                         bank->sectors[i].size = otp_sector_size;
1055                         bank->sectors[i].is_erased = 1;
1056                         bank->sectors[i].is_protected = 0;
1057                 }
1058
1059                 stm32x_info->probed = true;
1060                 return ERROR_OK;
1061         }
1062
1063         /* read stm32 device id register */
1064         int retval = stm32x_get_device_id(bank, &device_id);
1065         if (retval != ERROR_OK)
1066                 return retval;
1067         LOG_INFO("device id = 0x%08" PRIx32, device_id);
1068         device_id &= 0xfff;             /* only bits 0-11 are used further on */
1069
1070         /* set max flash size depending on family, id taken from AN2606 */
1071         switch (device_id) {
1072         case 0x411: /* F20x/21x */
1073         case 0x413: /* F40x/41x */
1074                 max_flash_size_in_kb = 1024;
1075                 break;
1076
1077         case 0x419: /* F42x/43x */
1078         case 0x434: /* F469/479 */
1079                 stm32x_info->has_extra_options = true;
1080                 max_flash_size_in_kb = 2048;
1081                 break;
1082
1083         case 0x423:     /* F401xB/C */
1084                 max_flash_size_in_kb = 256;
1085                 break;
1086
1087         case 0x421:     /* F446 */
1088         case 0x431: /* F411 */
1089         case 0x433: /* F401xD/E */
1090         case 0x441: /* F412 */
1091                 max_flash_size_in_kb = 512;
1092                 break;
1093
1094         case 0x458: /* F410 */
1095                 max_flash_size_in_kb = 128;
1096                 break;
1097
1098         case 0x449:     /* F74x/75x */
1099                 max_flash_size_in_kb = 1024;
1100                 max_sector_size_in_kb = 256;
1101                 flash_size_reg = 0x1FF0F442;
1102                 stm32x_info->has_extra_options = true;
1103                 stm32x_info->has_boot_addr = true;
1104                 break;
1105
1106         case 0x451:     /* F76x/77x */
1107                 max_flash_size_in_kb = 2048;
1108                 max_sector_size_in_kb = 256;
1109                 flash_size_reg = 0x1FF0F442;
1110                 stm32x_info->has_extra_options = true;
1111                 stm32x_info->has_boot_addr = true;
1112                 break;
1113
1114         case 0x452:     /* F72x/73x */
1115                 max_flash_size_in_kb = 512;
1116                 flash_size_reg = 0x1FF07A22;    /* yes, 0x1FF*0*7A22, not 0x1FF*F*7A22 */
1117                 stm32x_info->has_extra_options = true;
1118                 stm32x_info->has_boot_addr = true;
1119                 stm32x_info->has_optcr2_pcrop = true;
1120                 break;
1121
1122         case 0x463:     /* F413x/423x */
1123                 max_flash_size_in_kb = 1536;
1124                 stm32x_info->has_extra_options = true;
1125                 stm32x_info->protection_bits = 15;
1126                 num_prot_blocks = 15;
1127                 break;
1128
1129         default:
1130                 LOG_WARNING("Cannot identify target as a STM32 family.");
1131                 return ERROR_FAIL;
1132         }
1133
1134         /* get flash size from target. */
1135         retval = target_read_u16(target, flash_size_reg, &flash_size_in_kb);
1136
1137         /* failed reading flash size or flash size invalid (early silicon),
1138          * default to max target family */
1139         if (retval != ERROR_OK || flash_size_in_kb == 0xffff || flash_size_in_kb == 0) {
1140                 LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming %" PRIu16 "k flash",
1141                         max_flash_size_in_kb);
1142                 flash_size_in_kb = max_flash_size_in_kb;
1143         }
1144
1145         /* if the user sets the size manually then ignore the probed value
1146          * this allows us to work around devices that have a invalid flash size register value */
1147         if (stm32x_info->user_bank_size) {
1148                 LOG_INFO("ignoring flash probed value, using configured bank size");
1149                 flash_size_in_kb = stm32x_info->user_bank_size / 1024;
1150         }
1151
1152         LOG_INFO("flash size = %" PRIu16 " kbytes", flash_size_in_kb);
1153
1154         /* did we assign flash size? */
1155         assert(flash_size_in_kb != 0xffff);
1156
1157         /* F42x/43x/469/479 1024 kiByte devices have a dual bank option */
1158         if ((device_id == 0x419) || (device_id == 0x434)) {
1159                 uint32_t optiondata;
1160                 retval = target_read_u32(target, STM32_FLASH_OPTCR, &optiondata);
1161                 if (retval != ERROR_OK) {
1162                         LOG_DEBUG("unable to read option bytes");
1163                         return retval;
1164                 }
1165                 if ((flash_size_in_kb > 1024) || (optiondata & OPTCR_DB1M)) {
1166                         stm32x_info->has_large_mem = true;
1167                         LOG_INFO("Dual Bank %" PRIu16 " kiB STM32F42x/43x/469/479 found", flash_size_in_kb);
1168                 } else {
1169                         stm32x_info->has_large_mem = false;
1170                         LOG_INFO("Single Bank %" PRIu16 " kiB STM32F42x/43x/469/479 found", flash_size_in_kb);
1171                 }
1172         }
1173
1174         /* F76x/77x devices have a dual bank option */
1175         if (device_id == 0x451) {
1176                 uint32_t optiondata;
1177                 retval = target_read_u32(target, STM32_FLASH_OPTCR, &optiondata);
1178                 if (retval != ERROR_OK) {
1179                         LOG_DEBUG("unable to read option bytes");
1180                         return retval;
1181                 }
1182                 if (optiondata & OPTCR_NDBANK) {
1183                         stm32x_info->has_large_mem = false;
1184                         LOG_INFO("Single Bank %" PRIu16 " kiB STM32F76x/77x found", flash_size_in_kb);
1185                 } else {
1186                         stm32x_info->has_large_mem = true;
1187                         max_sector_size_in_kb >>= 1; /* sector size divided by 2 in dual-bank mode */
1188                         LOG_INFO("Dual Bank %" PRIu16 " kiB STM32F76x/77x found", flash_size_in_kb);
1189                 }
1190         }
1191
1192         /* calculate numbers of pages */
1193         int num_pages = calculate_number_of_sectors(
1194                         bank, flash_size_in_kb, max_sector_size_in_kb);
1195
1196         bank->base = base_address;
1197         bank->num_sectors = num_pages;
1198         bank->sectors = calloc(num_pages, sizeof(struct flash_sector));
1199         for (i = 0; i < num_pages; i++) {
1200                 bank->sectors[i].is_erased = -1;
1201                 bank->sectors[i].is_protected = 0;
1202         }
1203         bank->size = 0;
1204         LOG_DEBUG("allocated %d sectors", num_pages);
1205
1206         /* F76x/77x in dual bank mode */
1207         if ((device_id == 0x451) && stm32x_info->has_large_mem)
1208                 num_prot_blocks = num_pages >> 1;
1209
1210         if (num_prot_blocks) {
1211                 bank->prot_blocks = malloc(sizeof(struct flash_sector) * num_prot_blocks);
1212                 for (i = 0; i < num_prot_blocks; i++)
1213                         bank->prot_blocks[i].is_protected = 0;
1214                 LOG_DEBUG("allocated %d prot blocks", num_prot_blocks);
1215         }
1216
1217         if (stm32x_info->has_large_mem) {
1218                 /* dual-bank */
1219                 setup_bank(bank, 0, flash_size_in_kb >> 1, max_sector_size_in_kb);
1220                 setup_bank(bank, num_pages >> 1, flash_size_in_kb >> 1,
1221                         max_sector_size_in_kb);
1222
1223                 /* F767x/F77x in dual mode, one protection bit refers to two adjacent sectors */
1224                 if (device_id == 0x451) {
1225                         for (i = 0; i < num_prot_blocks; i++) {
1226                                 bank->prot_blocks[i].offset = bank->sectors[i << 1].offset;
1227                                 bank->prot_blocks[i].size = bank->sectors[i << 1].size
1228                                                 + bank->sectors[(i << 1) + 1].size;
1229                         }
1230                 }
1231         } else {
1232                 /* single-bank */
1233                 setup_bank(bank, 0, flash_size_in_kb, max_sector_size_in_kb);
1234
1235                 /* F413/F423, sectors 14 and 15 share one common protection bit */
1236                 if (device_id == 0x463) {
1237                         for (i = 0; i < num_prot_blocks; i++) {
1238                                 bank->prot_blocks[i].offset = bank->sectors[i].offset;
1239                                 bank->prot_blocks[i].size = bank->sectors[i].size;
1240                         }
1241                         bank->prot_blocks[num_prot_blocks - 1].size <<= 1;
1242                 }
1243         }
1244         bank->num_prot_blocks = num_prot_blocks;
1245         assert((bank->size >> 10) == flash_size_in_kb);
1246
1247         stm32x_info->probed = true;
1248         return ERROR_OK;
1249 }
1250
1251 static int stm32x_auto_probe(struct flash_bank *bank)
1252 {
1253         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
1254         if (stm32x_info->probed)
1255                 return ERROR_OK;
1256         return stm32x_probe(bank);
1257 }
1258
1259 static int get_stm32x_info(struct flash_bank *bank, char *buf, int buf_size)
1260 {
1261         uint32_t dbgmcu_idcode;
1262
1263         /* read stm32 device id register */
1264         int retval = stm32x_get_device_id(bank, &dbgmcu_idcode);
1265         if (retval != ERROR_OK)
1266                 return retval;
1267
1268         uint16_t device_id = dbgmcu_idcode & 0xfff;
1269         uint16_t rev_id = dbgmcu_idcode >> 16;
1270         const char *device_str;
1271         const char *rev_str = NULL;
1272
1273         switch (device_id) {
1274         case 0x411:
1275                 device_str = "STM32F2xx";
1276
1277                 switch (rev_id) {
1278                 case 0x1000:
1279                         rev_str = "A";
1280                         break;
1281
1282                 case 0x2000:
1283                         rev_str = "B";
1284                         break;
1285
1286                 case 0x1001:
1287                         rev_str = "Z";
1288                         break;
1289
1290                 case 0x2001:
1291                         rev_str = "Y";
1292                         break;
1293
1294                 case 0x2003:
1295                         rev_str = "X";
1296                         break;
1297
1298                 case 0x2007:
1299                         rev_str = "1";
1300                         break;
1301
1302                 case 0x200F:
1303                         rev_str = "V";
1304                         break;
1305
1306                 case 0x201F:
1307                         rev_str = "2";
1308                         break;
1309                 }
1310                 break;
1311
1312         case 0x413:
1313         case 0x419:
1314         case 0x434:
1315                 device_str = "STM32F4xx";
1316
1317                 switch (rev_id) {
1318                 case 0x1000:
1319                         rev_str = "A";
1320                         break;
1321
1322                 case 0x1001:
1323                         rev_str = "Z";
1324                         break;
1325
1326                 case 0x1003:
1327                         rev_str = "Y";
1328                         break;
1329
1330                 case 0x1007:
1331                         rev_str = "1";
1332                         break;
1333
1334                 case 0x2001:
1335                         rev_str = "3";
1336                         break;
1337                 }
1338                 break;
1339
1340         case 0x421:
1341                 device_str = "STM32F446";
1342
1343                 switch (rev_id) {
1344                 case 0x1000:
1345                         rev_str = "A";
1346                         break;
1347                 }
1348                 break;
1349
1350         case 0x423:
1351         case 0x431:
1352         case 0x433:
1353         case 0x458:
1354         case 0x441:
1355                 device_str = "STM32F4xx (Low Power)";
1356
1357                 switch (rev_id) {
1358                 case 0x1000:
1359                         rev_str = "A";
1360                         break;
1361
1362                 case 0x1001:
1363                         rev_str = "Z";
1364                         break;
1365
1366                 case 0x2000:
1367                         rev_str = "B";
1368                         break;
1369
1370                 case 0x3000:
1371                         rev_str = "C";
1372                         break;
1373                 }
1374                 break;
1375
1376         case 0x449:
1377                 device_str = "STM32F7[4|5]x";
1378
1379                 switch (rev_id) {
1380                 case 0x1000:
1381                         rev_str = "A";
1382                         break;
1383
1384                 case 0x1001:
1385                         rev_str = "Z";
1386                         break;
1387                 }
1388                 break;
1389
1390         case 0x451:
1391                 device_str = "STM32F7[6|7]x";
1392
1393                 switch (rev_id) {
1394                 case 0x1000:
1395                         rev_str = "A";
1396                         break;
1397                 case 0x1001:
1398                         rev_str = "Z";
1399                         break;
1400                 }
1401                 break;
1402
1403         case 0x452:
1404                 device_str = "STM32F7[2|3]x";
1405
1406                 switch (rev_id) {
1407                 case 0x1000:
1408                         rev_str = "A";
1409                         break;
1410                 }
1411                 break;
1412
1413         case 0x463:
1414                 device_str = "STM32F4[1|2]3";
1415
1416                 switch (rev_id) {
1417                 case 0x1000:
1418                         rev_str = "A";
1419                         break;
1420                 }
1421                 break;
1422
1423         default:
1424                 snprintf(buf, buf_size, "Cannot identify target as a STM32F2/4/7\n");
1425                 return ERROR_FAIL;
1426         }
1427
1428         if (rev_str != NULL)
1429                 snprintf(buf, buf_size, "%s - Rev: %s", device_str, rev_str);
1430         else
1431                 snprintf(buf, buf_size, "%s - Rev: unknown (0x%04" PRIx16 ")", device_str, rev_id);
1432
1433         return ERROR_OK;
1434 }
1435
1436 COMMAND_HANDLER(stm32x_handle_lock_command)
1437 {
1438         struct target *target = NULL;
1439         struct stm32x_flash_bank *stm32x_info = NULL;
1440
1441         if (CMD_ARGC < 1)
1442                 return ERROR_COMMAND_SYNTAX_ERROR;
1443
1444         struct flash_bank *bank;
1445         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1446         if (ERROR_OK != retval)
1447                 return retval;
1448
1449         stm32x_info = bank->driver_priv;
1450         target = bank->target;
1451
1452         if (target->state != TARGET_HALTED) {
1453                 LOG_INFO("Target not halted");
1454                 /* return ERROR_TARGET_NOT_HALTED; */
1455         }
1456
1457         if (stm32x_read_options(bank) != ERROR_OK) {
1458                 command_print(CMD, "%s failed to read options", bank->driver->name);
1459                 return ERROR_OK;
1460         }
1461
1462         /* set readout protection */
1463         stm32x_info->option_bytes.RDP = 0;
1464
1465         if (stm32x_write_options(bank) != ERROR_OK) {
1466                 command_print(CMD, "%s failed to lock device", bank->driver->name);
1467                 return ERROR_OK;
1468         }
1469
1470         command_print(CMD, "%s locked", bank->driver->name);
1471
1472         return ERROR_OK;
1473 }
1474
1475 COMMAND_HANDLER(stm32x_handle_unlock_command)
1476 {
1477         struct target *target = NULL;
1478         struct stm32x_flash_bank *stm32x_info = NULL;
1479
1480         if (CMD_ARGC < 1)
1481                 return ERROR_COMMAND_SYNTAX_ERROR;
1482
1483         struct flash_bank *bank;
1484         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1485         if (ERROR_OK != retval)
1486                 return retval;
1487
1488         stm32x_info = bank->driver_priv;
1489         target = bank->target;
1490
1491         if (target->state != TARGET_HALTED) {
1492                 LOG_INFO("Target not halted");
1493                 /* return ERROR_TARGET_NOT_HALTED; */
1494         }
1495
1496         if (stm32x_read_options(bank) != ERROR_OK) {
1497                 command_print(CMD, "%s failed to read options", bank->driver->name);
1498                 return ERROR_OK;
1499         }
1500
1501         /* clear readout protection and complementary option bytes
1502          * this will also force a device unlock if set */
1503         stm32x_info->option_bytes.RDP = 0xAA;
1504         if (stm32x_info->has_optcr2_pcrop) {
1505                 stm32x_info->option_bytes.optcr2_pcrop = OPTCR2_PCROP_RDP | (~1U << bank->num_sectors);
1506         }
1507
1508         if (stm32x_write_options(bank) != ERROR_OK) {
1509                 command_print(CMD, "%s failed to unlock device", bank->driver->name);
1510                 return ERROR_OK;
1511         }
1512
1513         command_print(CMD, "%s unlocked.\n"
1514                         "INFO: a reset or power cycle is required "
1515                         "for the new settings to take effect.", bank->driver->name);
1516
1517         return ERROR_OK;
1518 }
1519
1520 static int stm32x_mass_erase(struct flash_bank *bank)
1521 {
1522         int retval;
1523         uint32_t flash_mer;
1524         struct target *target = bank->target;
1525         struct stm32x_flash_bank *stm32x_info = NULL;
1526
1527         if (target->state != TARGET_HALTED) {
1528                 LOG_ERROR("Target not halted");
1529                 return ERROR_TARGET_NOT_HALTED;
1530         }
1531
1532         stm32x_info = bank->driver_priv;
1533
1534         retval = stm32x_unlock_reg(target);
1535         if (retval != ERROR_OK)
1536                 return retval;
1537
1538         /* mass erase flash memory */
1539         if (stm32x_info->has_large_mem)
1540                 flash_mer = FLASH_MER | FLASH_MER1;
1541         else
1542                 flash_mer = FLASH_MER;
1543
1544         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), flash_mer);
1545         if (retval != ERROR_OK)
1546                 return retval;
1547         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
1548                 flash_mer | FLASH_STRT);
1549         if (retval != ERROR_OK)
1550                 return retval;
1551
1552         retval = stm32x_wait_status_busy(bank, FLASH_MASS_ERASE_TIMEOUT);
1553         if (retval != ERROR_OK)
1554                 return retval;
1555
1556         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
1557         if (retval != ERROR_OK)
1558                 return retval;
1559
1560         return ERROR_OK;
1561 }
1562
1563 COMMAND_HANDLER(stm32x_handle_mass_erase_command)
1564 {
1565         if (CMD_ARGC < 1) {
1566                 command_print(CMD, "stm32x mass_erase <bank>");
1567                 return ERROR_COMMAND_SYNTAX_ERROR;
1568         }
1569
1570         struct flash_bank *bank;
1571         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1572         if (ERROR_OK != retval)
1573                 return retval;
1574
1575         retval = stm32x_mass_erase(bank);
1576         if (retval == ERROR_OK) {
1577                 /* set all sectors as erased */
1578                 for (unsigned int i = 0; i < bank->num_sectors; i++)
1579                         bank->sectors[i].is_erased = 1;
1580
1581                 command_print(CMD, "stm32x mass erase complete");
1582         } else {
1583                 command_print(CMD, "stm32x mass erase failed");
1584         }
1585
1586         return retval;
1587 }
1588
1589 COMMAND_HANDLER(stm32f2x_handle_options_read_command)
1590 {
1591         int retval;
1592         struct flash_bank *bank;
1593         struct stm32x_flash_bank *stm32x_info = NULL;
1594
1595         if (CMD_ARGC != 1) {
1596                 command_print(CMD, "stm32f2x options_read <bank>");
1597                 return ERROR_COMMAND_SYNTAX_ERROR;
1598         }
1599
1600         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1601         if (ERROR_OK != retval)
1602                 return retval;
1603
1604         retval = stm32x_read_options(bank);
1605         if (ERROR_OK != retval)
1606                 return retval;
1607
1608         stm32x_info = bank->driver_priv;
1609         if (stm32x_info->has_extra_options) {
1610                 if (stm32x_info->has_boot_addr) {
1611                         uint32_t boot_addr = stm32x_info->option_bytes.boot_addr;
1612
1613                         command_print(CMD, "stm32f2x user_options 0x%03" PRIX16 ","
1614                                 " boot_add0 0x%04" PRIX32 ", boot_add1 0x%04" PRIX32,
1615                                 stm32x_info->option_bytes.user_options,
1616                                 boot_addr & 0xffff, (boot_addr & 0xffff0000) >> 16);
1617                         if (stm32x_info->has_optcr2_pcrop) {
1618                                 command_print(CMD, "stm32f2x optcr2_pcrop 0x%08" PRIX32,
1619                                                 stm32x_info->option_bytes.optcr2_pcrop);
1620                         }
1621                 } else {
1622                         command_print(CMD, "stm32f2x user_options 0x%03" PRIX16,
1623                                 stm32x_info->option_bytes.user_options);
1624                 }
1625         } else {
1626                 command_print(CMD, "stm32f2x user_options 0x%02" PRIX16,
1627                         stm32x_info->option_bytes.user_options);
1628
1629         }
1630
1631         return retval;
1632 }
1633
1634 COMMAND_HANDLER(stm32f2x_handle_options_write_command)
1635 {
1636         int retval;
1637         struct flash_bank *bank;
1638         struct stm32x_flash_bank *stm32x_info = NULL;
1639         uint16_t user_options, boot_addr0, boot_addr1, options_mask;
1640
1641         if (CMD_ARGC < 1) {
1642                 command_print(CMD, "stm32f2x options_write <bank> ...");
1643                 return ERROR_COMMAND_SYNTAX_ERROR;
1644         }
1645
1646         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1647         if (ERROR_OK != retval)
1648                 return retval;
1649
1650         retval = stm32x_read_options(bank);
1651         if (ERROR_OK != retval)
1652                 return retval;
1653
1654         stm32x_info = bank->driver_priv;
1655         if (stm32x_info->has_boot_addr) {
1656                 if (CMD_ARGC != 4) {
1657                         command_print(CMD, "stm32f2x options_write <bank> <user_options>"
1658                                 " <boot_addr0> <boot_addr1>");
1659                         return ERROR_COMMAND_SYNTAX_ERROR;
1660                 }
1661                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[2], boot_addr0);
1662                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[3], boot_addr1);
1663                 stm32x_info->option_bytes.boot_addr = boot_addr0 | (((uint32_t) boot_addr1) << 16);
1664         } else {
1665                 if (CMD_ARGC != 2) {
1666                         command_print(CMD, "stm32f2x options_write <bank> <user_options>");
1667                         return ERROR_COMMAND_SYNTAX_ERROR;
1668                 }
1669         }
1670
1671         COMMAND_PARSE_NUMBER(u16, CMD_ARGV[1], user_options);
1672         options_mask = !stm32x_info->has_extra_options ? ~0xfc :
1673                 ~(((0xf00 << (stm32x_info->protection_bits - 12)) | 0xff) & 0xffc);
1674         if (user_options & options_mask) {
1675                 command_print(CMD, "stm32f2x invalid user_options");
1676                 return ERROR_COMMAND_ARGUMENT_INVALID;
1677         }
1678
1679         stm32x_info->option_bytes.user_options = user_options;
1680
1681         if (stm32x_write_options(bank) != ERROR_OK) {
1682                 command_print(CMD, "stm32f2x failed to write options");
1683                 return ERROR_OK;
1684         }
1685
1686         /* switching between single- and dual-bank modes requires re-probe */
1687         /* ... and reprogramming of whole flash */
1688         stm32x_info->probed = false;
1689
1690         command_print(CMD, "stm32f2x write options complete.\n"
1691                                 "INFO: a reset or power cycle is required "
1692                                 "for the new settings to take effect.");
1693         return retval;
1694 }
1695
1696 COMMAND_HANDLER(stm32f2x_handle_optcr2_write_command)
1697 {
1698         int retval;
1699         struct flash_bank *bank;
1700         struct stm32x_flash_bank *stm32x_info = NULL;
1701         uint32_t optcr2_pcrop;
1702
1703         if (CMD_ARGC != 2) {
1704                 command_print(CMD, "stm32f2x optcr2_write <bank> <optcr2_value>");
1705                 return ERROR_COMMAND_SYNTAX_ERROR;
1706         }
1707
1708         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1709         if (ERROR_OK != retval)
1710                 return retval;
1711
1712         stm32x_info = bank->driver_priv;
1713         if (!stm32x_info->has_optcr2_pcrop) {
1714                 command_print(CMD, "no optcr2 register");
1715                 return ERROR_COMMAND_ARGUMENT_INVALID;
1716         }
1717
1718         command_print(CMD, "INFO: To disable PCROP, set PCROP_RDP"
1719                                 " with PCROPi bits STILL SET, then\nlock device and"
1720                                 " finally unlock it. Clears PCROP and mass erases flash.");
1721
1722         retval = stm32x_read_options(bank);
1723         if (ERROR_OK != retval)
1724                 return retval;
1725
1726         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], optcr2_pcrop);
1727         stm32x_info->option_bytes.optcr2_pcrop = optcr2_pcrop;
1728
1729         if (stm32x_write_options(bank) != ERROR_OK) {
1730                 command_print(CMD, "stm32f2x failed to write options");
1731                 return ERROR_OK;
1732         }
1733
1734         command_print(CMD, "stm32f2x optcr2_write complete.");
1735         return retval;
1736 }
1737
1738 COMMAND_HANDLER(stm32x_handle_otp_command)
1739 {
1740         if (CMD_ARGC < 2) {
1741                 command_print(CMD, "stm32x otp <bank> (enable|disable|show)");
1742                 return ERROR_COMMAND_SYNTAX_ERROR;
1743         }
1744
1745         struct flash_bank *bank;
1746         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1747         if (ERROR_OK != retval)
1748                 return retval;
1749         if (stm32x_is_otp(bank)) {
1750                 if (strcmp(CMD_ARGV[1], "enable") == 0) {
1751                         stm32x_otp_enable(bank);
1752                 } else if (strcmp(CMD_ARGV[1], "disable") == 0) {
1753                         stm32x_otp_disable(bank);
1754                 } else if (strcmp(CMD_ARGV[1], "show") == 0) {
1755                         command_print(CMD,
1756                                 "OTP memory bank #%u is %s for write commands.",
1757                                 bank->bank_number,
1758                                 stm32x_is_otp_unlocked(bank) ? "enabled" : "disabled");
1759                 } else {
1760                         return ERROR_COMMAND_SYNTAX_ERROR;
1761                 }
1762         } else {
1763                 command_print(CMD, "Failed: not an OTP bank.");
1764         }
1765
1766         return retval;
1767 }
1768
1769 static const struct command_registration stm32x_exec_command_handlers[] = {
1770         {
1771                 .name = "lock",
1772                 .handler = stm32x_handle_lock_command,
1773                 .mode = COMMAND_EXEC,
1774                 .usage = "bank_id",
1775                 .help = "Lock entire flash device.",
1776         },
1777         {
1778                 .name = "unlock",
1779                 .handler = stm32x_handle_unlock_command,
1780                 .mode = COMMAND_EXEC,
1781                 .usage = "bank_id",
1782                 .help = "Unlock entire protected flash device.",
1783         },
1784         {
1785                 .name = "mass_erase",
1786                 .handler = stm32x_handle_mass_erase_command,
1787                 .mode = COMMAND_EXEC,
1788                 .usage = "bank_id",
1789                 .help = "Erase entire flash device.",
1790         },
1791         {
1792                 .name = "options_read",
1793                 .handler = stm32f2x_handle_options_read_command,
1794                 .mode = COMMAND_EXEC,
1795                 .usage = "bank_id",
1796                 .help = "Read and display device option bytes.",
1797         },
1798         {
1799                 .name = "options_write",
1800                 .handler = stm32f2x_handle_options_write_command,
1801                 .mode = COMMAND_EXEC,
1802                 .usage = "bank_id user_options [ boot_add0 boot_add1 ]",
1803                 .help = "Write option bytes",
1804         },
1805         {
1806                 .name = "optcr2_write",
1807                 .handler = stm32f2x_handle_optcr2_write_command,
1808                 .mode = COMMAND_EXEC,
1809                 .usage = "bank_id optcr2",
1810                 .help = "Write optcr2 word",
1811         },
1812         {
1813                 .name = "otp",
1814                 .handler = stm32x_handle_otp_command,
1815                 .mode = COMMAND_EXEC,
1816                 .usage = "bank_id",
1817                 .help = "OTP (One Time Programmable) memory write enable/disable.",
1818         },
1819         COMMAND_REGISTRATION_DONE
1820 };
1821
1822 static const struct command_registration stm32x_command_handlers[] = {
1823         {
1824                 .name = "stm32f2x",
1825                 .mode = COMMAND_ANY,
1826                 .help = "stm32f2x flash command group",
1827                 .usage = "",
1828                 .chain = stm32x_exec_command_handlers,
1829         },
1830         COMMAND_REGISTRATION_DONE
1831 };
1832
1833 const struct flash_driver stm32f2x_flash = {
1834         .name = "stm32f2x",
1835         .commands = stm32x_command_handlers,
1836         .flash_bank_command = stm32x_flash_bank_command,
1837         .erase = stm32x_erase,
1838         .protect = stm32x_protect,
1839         .write = stm32x_write,
1840         .read = default_flash_read,
1841         .probe = stm32x_probe,
1842         .auto_probe = stm32x_auto_probe,
1843         .erase_check = default_flash_blank_check,
1844         .protect_check = stm32x_protect_check,
1845         .info = get_stm32x_info,
1846         .free_driver_priv = default_flash_free_driver_priv,
1847 };