openocd: use unique name for struct command_registration
[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/cortex_m.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 separate 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         unsigned 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 different 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         unsigned 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 (unsigned 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
654         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
655         if (retval != ERROR_OK)
656                 return retval;
657
658         return ERROR_OK;
659 }
660
661 static int stm32x_protect(struct flash_bank *bank, int set, unsigned int first,
662                 unsigned int last)
663 {
664         struct target *target = bank->target;
665         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
666
667         if (target->state != TARGET_HALTED) {
668                 LOG_ERROR("Target not halted");
669                 return ERROR_TARGET_NOT_HALTED;
670         }
671
672         if (stm32x_is_otp(bank)) {
673                 if (!set)
674                         return ERROR_COMMAND_ARGUMENT_INVALID;
675
676                 return stm32x_otp_protect(bank, first, last);
677         }
678
679         /* read protection settings */
680         int retval = stm32x_read_options(bank);
681         if (retval != ERROR_OK) {
682                 LOG_DEBUG("unable to read option bytes");
683                 return retval;
684         }
685
686         for (unsigned int i = first; i <= last; i++) {
687                 if (set)
688                         stm32x_info->option_bytes.protection &= ~(1 << i);
689                 else
690                         stm32x_info->option_bytes.protection |= (1 << i);
691         }
692
693         retval = stm32x_write_options(bank);
694         if (retval != ERROR_OK)
695                 return retval;
696
697         return ERROR_OK;
698 }
699
700 static int stm32x_write_block(struct flash_bank *bank, const uint8_t *buffer,
701                 uint32_t offset, uint32_t count)
702 {
703         struct target *target = bank->target;
704         uint32_t buffer_size = 16384;
705         struct working_area *write_algorithm;
706         struct working_area *source;
707         uint32_t address = bank->base + offset;
708         struct reg_param reg_params[5];
709         struct armv7m_algorithm armv7m_info;
710         int retval = ERROR_OK;
711
712         static const uint8_t stm32x_flash_write_code[] = {
713 #include "../../../contrib/loaders/flash/stm32/stm32f2x.inc"
714         };
715
716         if (stm32x_is_otp(bank) && !stm32x_is_otp_unlocked(bank)) {
717                 LOG_ERROR("OTP memory bank is disabled for write commands.");
718                 return ERROR_FAIL;
719         }
720
721         if (target_alloc_working_area(target, sizeof(stm32x_flash_write_code),
722                         &write_algorithm) != ERROR_OK) {
723                 LOG_WARNING("no working area available, can't do block memory writes");
724                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
725         }
726
727         retval = target_write_buffer(target, write_algorithm->address,
728                         sizeof(stm32x_flash_write_code),
729                         stm32x_flash_write_code);
730         if (retval != ERROR_OK) {
731                 target_free_working_area(target, write_algorithm);
732                 return retval;
733         }
734
735         /* memory buffer */
736         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) {
737                 buffer_size /= 2;
738                 if (buffer_size <= 256) {
739                         /* we already allocated the writing code, but failed to get a
740                          * buffer, free the algorithm */
741                         target_free_working_area(target, write_algorithm);
742
743                         LOG_WARNING("no large enough working area available, can't do block memory writes");
744                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
745                 }
746         }
747
748         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
749         armv7m_info.core_mode = ARM_MODE_THREAD;
750
751         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT);         /* buffer start, status (out) */
752         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);            /* buffer end */
753         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);            /* target address */
754         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);            /* count (halfword-16bit) */
755         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);            /* flash base */
756
757         buf_set_u32(reg_params[0].value, 0, 32, source->address);
758         buf_set_u32(reg_params[1].value, 0, 32, source->address + source->size);
759         buf_set_u32(reg_params[2].value, 0, 32, address);
760         buf_set_u32(reg_params[3].value, 0, 32, count);
761         buf_set_u32(reg_params[4].value, 0, 32, STM32_FLASH_BASE);
762
763         retval = target_run_flash_async_algorithm(target, buffer, count, 2,
764                         0, NULL,
765                         5, reg_params,
766                         source->address, source->size,
767                         write_algorithm->address, 0,
768                         &armv7m_info);
769
770         if (retval == ERROR_FLASH_OPERATION_FAILED) {
771                 LOG_ERROR("error executing stm32x flash write algorithm");
772
773                 uint32_t error = buf_get_u32(reg_params[0].value, 0, 32) & FLASH_ERROR;
774
775                 if (error & FLASH_WRPERR)
776                         LOG_ERROR("flash memory write protected");
777
778                 if (error != 0) {
779                         LOG_ERROR("flash write failed = 0x%08" PRIx32, error);
780                         /* Clear but report errors */
781                         target_write_u32(target, STM32_FLASH_SR, error);
782                         retval = ERROR_FAIL;
783                 }
784         }
785
786         target_free_working_area(target, source);
787         target_free_working_area(target, write_algorithm);
788
789         destroy_reg_param(&reg_params[0]);
790         destroy_reg_param(&reg_params[1]);
791         destroy_reg_param(&reg_params[2]);
792         destroy_reg_param(&reg_params[3]);
793         destroy_reg_param(&reg_params[4]);
794
795         return retval;
796 }
797
798 static int stm32x_write(struct flash_bank *bank, const uint8_t *buffer,
799                 uint32_t offset, uint32_t count)
800 {
801         struct target *target = bank->target;
802         uint32_t words_remaining = (count / 2);
803         uint32_t bytes_remaining = (count & 0x00000001);
804         uint32_t address = bank->base + offset;
805         uint32_t bytes_written = 0;
806         int retval;
807
808         if (bank->target->state != TARGET_HALTED) {
809                 LOG_ERROR("Target not halted");
810                 return ERROR_TARGET_NOT_HALTED;
811         }
812
813         if (offset & 0x1) {
814                 LOG_WARNING("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
815                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
816         }
817
818         retval = stm32x_unlock_reg(target);
819         if (retval != ERROR_OK)
820                 return retval;
821
822         /* multiple half words (2-byte) to be programmed? */
823         if (words_remaining > 0) {
824                 /* try using a block write */
825                 retval = stm32x_write_block(bank, buffer, offset, words_remaining);
826                 if (retval != ERROR_OK) {
827                         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
828                                 /* if block write failed (no sufficient working area),
829                                  * we use normal (slow) single dword accesses */
830                                 LOG_WARNING("couldn't use block writes, falling back to single memory accesses");
831                         }
832                 } else {
833                         buffer += words_remaining * 2;
834                         address += words_remaining * 2;
835                         words_remaining = 0;
836                 }
837         }
838
839         if ((retval != ERROR_OK) && (retval != ERROR_TARGET_RESOURCE_NOT_AVAILABLE))
840                 return retval;
841
842         /*
843         Standard programming
844         The Flash memory programming sequence is as follows:
845         1. Check that no main Flash memory operation is ongoing by checking the BSY bit in the
846           FLASH_SR register.
847         2. Set the PG bit in the FLASH_CR register
848         3. Perform the data write operation(s) to the desired memory address (inside main
849           memory block or OTP area):
850         â€“ â€“ Half-word access in case of x16 parallelism
851         â€“ Word access in case of x32 parallelism
852         â€“
853         4.
854         Byte access in case of x8 parallelism
855         Double word access in case of x64 parallelism
856         Wait for the BSY bit to be cleared
857         */
858         while (words_remaining > 0) {
859                 uint16_t value;
860                 memcpy(&value, buffer + bytes_written, sizeof(uint16_t));
861
862                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
863                                 FLASH_PG | FLASH_PSIZE_16);
864                 if (retval != ERROR_OK)
865                         return retval;
866
867                 retval = target_write_u16(target, address, value);
868                 if (retval != ERROR_OK)
869                         return retval;
870
871                 retval = stm32x_wait_status_busy(bank, FLASH_WRITE_TIMEOUT);
872                 if (retval != ERROR_OK)
873                         return retval;
874
875                 bytes_written += 2;
876                 words_remaining--;
877                 address += 2;
878         }
879
880         if (bytes_remaining) {
881                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
882                                 FLASH_PG | FLASH_PSIZE_8);
883                 if (retval != ERROR_OK)
884                         return retval;
885                 retval = target_write_u8(target, address, buffer[bytes_written]);
886                 if (retval != ERROR_OK)
887                         return retval;
888
889                 retval = stm32x_wait_status_busy(bank, FLASH_WRITE_TIMEOUT);
890                 if (retval != ERROR_OK)
891                         return retval;
892         }
893
894         return target_write_u32(target, STM32_FLASH_CR, FLASH_LOCK);
895 }
896
897 static void setup_sector(struct flash_bank *bank, unsigned int i,
898                 unsigned int size)
899 {
900         assert(i < bank->num_sectors);
901         bank->sectors[i].offset = bank->size;
902         bank->sectors[i].size = size;
903         bank->size += bank->sectors[i].size;
904         LOG_DEBUG("sector %u: %ukBytes", i, size >> 10);
905 }
906
907 static uint16_t sector_size_in_kb(unsigned int i, uint16_t max_sector_size_in_kb)
908 {
909         if (i < 4)
910                 return max_sector_size_in_kb / 8;
911         if (i == 4)
912                 return max_sector_size_in_kb / 2;
913         return max_sector_size_in_kb;
914 }
915
916 static unsigned int calculate_number_of_sectors(struct flash_bank *bank,
917                 uint16_t flash_size_in_kb,
918                 uint16_t max_sector_size_in_kb)
919 {
920         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
921         uint16_t remaining_flash_size_in_kb = flash_size_in_kb;
922         unsigned int nr_sectors;
923
924         /* Dual Bank Flash has two identically-arranged banks of sectors. */
925         if (stm32x_info->has_large_mem)
926                 remaining_flash_size_in_kb /= 2;
927
928         for (nr_sectors = 0; remaining_flash_size_in_kb > 0; nr_sectors++) {
929                 uint16_t size_in_kb = sector_size_in_kb(nr_sectors, max_sector_size_in_kb);
930                 if (size_in_kb > remaining_flash_size_in_kb) {
931                         LOG_INFO("%s Bank %" PRIu16 " kiB final sector clipped to %" PRIu16 " kiB",
932                                  stm32x_info->has_large_mem ? "Dual" : "Single",
933                                  flash_size_in_kb, remaining_flash_size_in_kb);
934                         remaining_flash_size_in_kb = 0;
935                 } else {
936                         remaining_flash_size_in_kb -= size_in_kb;
937                 }
938         }
939
940         return stm32x_info->has_large_mem ? nr_sectors*2 : nr_sectors;
941 }
942
943 static void setup_bank(struct flash_bank *bank, unsigned int start,
944         uint16_t flash_size_in_kb, uint16_t max_sector_size_in_kb)
945 {
946         uint16_t remaining_flash_size_in_kb = flash_size_in_kb;
947         unsigned int sector_index = 0;
948         while (remaining_flash_size_in_kb > 0) {
949                 uint16_t size_in_kb = sector_size_in_kb(sector_index, max_sector_size_in_kb);
950                 if (size_in_kb > remaining_flash_size_in_kb) {
951                         /* Clip last sector. Already warned in
952                          * calculate_number_of_sectors. */
953                         size_in_kb = remaining_flash_size_in_kb;
954                 }
955                 setup_sector(bank, start + sector_index, size_in_kb * 1024);
956                 remaining_flash_size_in_kb -= size_in_kb;
957                 sector_index++;
958         }
959 }
960
961 static int stm32x_get_device_id(struct flash_bank *bank, uint32_t *device_id)
962 {
963         /* this checks for a stm32f4x errata issue where a
964          * stm32f2x DBGMCU_IDCODE is incorrectly returned.
965          * If the issue is detected target is forced to stm32f4x Rev A.
966          * Only effects Rev A silicon */
967
968         struct target *target = bank->target;
969         struct cortex_m_common *cortex_m = target_to_cm(target);
970
971         /* read stm32 device id register */
972         int retval = target_read_u32(target, 0xE0042000, device_id);
973         if (retval != ERROR_OK)
974                 return retval;
975
976         if ((*device_id & 0xfff) == 0x411 && cortex_m->core_info->partno == CORTEX_M4_PARTNO) {
977                 *device_id &= ~((0xFFFF << 16) | 0xfff);
978                 *device_id |= (0x1000 << 16) | 0x413;
979                 LOG_INFO("stm32f4x errata detected - fixing incorrect MCU_IDCODE");
980         }
981         return retval;
982 }
983
984 static int stm32x_probe(struct flash_bank *bank)
985 {
986         struct target *target = bank->target;
987         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
988         unsigned int num_prot_blocks, num_sectors;
989         uint16_t flash_size_in_kb;
990         uint16_t otp_size_in_b;
991         uint16_t otp_sector_size;
992         uint32_t flash_size_reg = 0x1FFF7A22;
993         uint16_t max_sector_size_in_kb = 128;
994         uint16_t max_flash_size_in_kb;
995         uint32_t device_id;
996         uint32_t base_address = 0x08000000;
997
998         stm32x_info->probed = false;
999         stm32x_info->has_large_mem = false;
1000         stm32x_info->has_boot_addr = false;
1001         stm32x_info->has_extra_options = false;
1002         stm32x_info->has_optcr2_pcrop = false;
1003         stm32x_info->protection_bits = 12;              /* max. number of nWRPi bits (in FLASH_OPTCR !!!) */
1004         num_prot_blocks = 0;
1005
1006         free(bank->sectors);
1007         bank->num_sectors = 0;
1008         bank->sectors = NULL;
1009
1010         free(bank->prot_blocks);
1011         bank->num_prot_blocks = 0;
1012         bank->prot_blocks = NULL;
1013
1014         /* if explicitly called out as OTP bank, short circuit probe */
1015         if (stm32x_is_otp(bank)) {
1016                 if (stm32x_otp_is_f7(bank)) {
1017                         otp_size_in_b = STM32F7_OTP_SIZE;
1018                         otp_sector_size = STM32F7_OTP_SECTOR_SIZE;
1019                 } else {
1020                         otp_size_in_b = STM32F2_OTP_SIZE;
1021                         otp_sector_size = STM32F2_OTP_SECTOR_SIZE;
1022                 }
1023
1024                 num_sectors = otp_size_in_b / otp_sector_size;
1025                 LOG_INFO("flash size = %" PRIu16 " bytes", otp_size_in_b);
1026
1027                 assert(num_sectors > 0);
1028
1029                 bank->num_sectors = num_sectors;
1030                 bank->sectors = calloc(sizeof(struct flash_sector), num_sectors);
1031
1032                 if (stm32x_otp_is_f7(bank))
1033                         bank->size = STM32F7_OTP_SIZE;
1034                 else
1035                         bank->size = STM32F2_OTP_SIZE;
1036
1037                 for (unsigned int i = 0; i < num_sectors; i++) {
1038                         bank->sectors[i].offset = i * otp_sector_size;
1039                         bank->sectors[i].size = otp_sector_size;
1040                         bank->sectors[i].is_erased = 1;
1041                         bank->sectors[i].is_protected = 0;
1042                 }
1043
1044                 stm32x_info->probed = true;
1045                 return ERROR_OK;
1046         }
1047
1048         /* read stm32 device id register */
1049         int retval = stm32x_get_device_id(bank, &device_id);
1050         if (retval != ERROR_OK)
1051                 return retval;
1052         LOG_INFO("device id = 0x%08" PRIx32, device_id);
1053         device_id &= 0xfff;             /* only bits 0-11 are used further on */
1054
1055         /* set max flash size depending on family, id taken from AN2606 */
1056         switch (device_id) {
1057         case 0x411: /* F20x/21x */
1058         case 0x413: /* F40x/41x */
1059                 max_flash_size_in_kb = 1024;
1060                 break;
1061
1062         case 0x419: /* F42x/43x */
1063         case 0x434: /* F469/479 */
1064                 stm32x_info->has_extra_options = true;
1065                 max_flash_size_in_kb = 2048;
1066                 break;
1067
1068         case 0x423:     /* F401xB/C */
1069                 max_flash_size_in_kb = 256;
1070                 break;
1071
1072         case 0x421:     /* F446 */
1073         case 0x431: /* F411 */
1074         case 0x433: /* F401xD/E */
1075         case 0x441: /* F412 */
1076                 max_flash_size_in_kb = 512;
1077                 break;
1078
1079         case 0x458: /* F410 */
1080                 max_flash_size_in_kb = 128;
1081                 break;
1082
1083         case 0x449:     /* F74x/75x */
1084                 max_flash_size_in_kb = 1024;
1085                 max_sector_size_in_kb = 256;
1086                 flash_size_reg = 0x1FF0F442;
1087                 stm32x_info->has_extra_options = true;
1088                 stm32x_info->has_boot_addr = true;
1089                 break;
1090
1091         case 0x451:     /* F76x/77x */
1092                 max_flash_size_in_kb = 2048;
1093                 max_sector_size_in_kb = 256;
1094                 flash_size_reg = 0x1FF0F442;
1095                 stm32x_info->has_extra_options = true;
1096                 stm32x_info->has_boot_addr = true;
1097                 break;
1098
1099         case 0x452:     /* F72x/73x */
1100                 max_flash_size_in_kb = 512;
1101                 flash_size_reg = 0x1FF07A22;    /* yes, 0x1FF*0*7A22, not 0x1FF*F*7A22 */
1102                 stm32x_info->has_extra_options = true;
1103                 stm32x_info->has_boot_addr = true;
1104                 stm32x_info->has_optcr2_pcrop = true;
1105                 break;
1106
1107         case 0x463:     /* F413x/423x */
1108                 max_flash_size_in_kb = 1536;
1109                 stm32x_info->has_extra_options = true;
1110                 stm32x_info->protection_bits = 15;
1111                 num_prot_blocks = 15;
1112                 break;
1113
1114         default:
1115                 LOG_WARNING("Cannot identify target as a STM32 family.");
1116                 return ERROR_FAIL;
1117         }
1118
1119         /* get flash size from target. */
1120         retval = target_read_u16(target, flash_size_reg, &flash_size_in_kb);
1121
1122         /* failed reading flash size or flash size invalid (early silicon),
1123          * default to max target family */
1124         if (retval != ERROR_OK || flash_size_in_kb == 0xffff || flash_size_in_kb == 0) {
1125                 LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming %" PRIu16 "k flash",
1126                         max_flash_size_in_kb);
1127                 flash_size_in_kb = max_flash_size_in_kb;
1128         }
1129
1130         /* if the user sets the size manually then ignore the probed value
1131          * this allows us to work around devices that have a invalid flash size register value */
1132         if (stm32x_info->user_bank_size) {
1133                 LOG_INFO("ignoring flash probed value, using configured bank size");
1134                 flash_size_in_kb = stm32x_info->user_bank_size / 1024;
1135         }
1136
1137         LOG_INFO("flash size = %" PRIu16 " kbytes", flash_size_in_kb);
1138
1139         /* did we assign flash size? */
1140         assert(flash_size_in_kb != 0xffff);
1141
1142         /* F42x/43x/469/479 1024 kiByte devices have a dual bank option */
1143         if ((device_id == 0x419) || (device_id == 0x434)) {
1144                 uint32_t optiondata;
1145                 retval = target_read_u32(target, STM32_FLASH_OPTCR, &optiondata);
1146                 if (retval != ERROR_OK) {
1147                         LOG_DEBUG("unable to read option bytes");
1148                         return retval;
1149                 }
1150                 if ((flash_size_in_kb > 1024) || (optiondata & OPTCR_DB1M)) {
1151                         stm32x_info->has_large_mem = true;
1152                         LOG_INFO("Dual Bank %" PRIu16 " kiB STM32F42x/43x/469/479 found", flash_size_in_kb);
1153                 } else {
1154                         stm32x_info->has_large_mem = false;
1155                         LOG_INFO("Single Bank %" PRIu16 " kiB STM32F42x/43x/469/479 found", flash_size_in_kb);
1156                 }
1157         }
1158
1159         /* F76x/77x devices have a dual bank option */
1160         if (device_id == 0x451) {
1161                 uint32_t optiondata;
1162                 retval = target_read_u32(target, STM32_FLASH_OPTCR, &optiondata);
1163                 if (retval != ERROR_OK) {
1164                         LOG_DEBUG("unable to read option bytes");
1165                         return retval;
1166                 }
1167                 if (optiondata & OPTCR_NDBANK) {
1168                         stm32x_info->has_large_mem = false;
1169                         LOG_INFO("Single Bank %" PRIu16 " kiB STM32F76x/77x found", flash_size_in_kb);
1170                 } else {
1171                         stm32x_info->has_large_mem = true;
1172                         max_sector_size_in_kb >>= 1; /* sector size divided by 2 in dual-bank mode */
1173                         LOG_INFO("Dual Bank %" PRIu16 " kiB STM32F76x/77x found", flash_size_in_kb);
1174                 }
1175         }
1176
1177         /* calculate numbers of pages */
1178         unsigned int num_pages = calculate_number_of_sectors(
1179                         bank, flash_size_in_kb, max_sector_size_in_kb);
1180
1181         bank->base = base_address;
1182         bank->num_sectors = num_pages;
1183         bank->sectors = calloc(num_pages, sizeof(struct flash_sector));
1184         for (unsigned int i = 0; i < num_pages; i++) {
1185                 bank->sectors[i].is_erased = -1;
1186                 bank->sectors[i].is_protected = 0;
1187         }
1188         bank->size = 0;
1189         LOG_DEBUG("allocated %u sectors", num_pages);
1190
1191         /* F76x/77x in dual bank mode */
1192         if ((device_id == 0x451) && stm32x_info->has_large_mem)
1193                 num_prot_blocks = num_pages >> 1;
1194
1195         if (num_prot_blocks) {
1196                 bank->prot_blocks = malloc(sizeof(struct flash_sector) * num_prot_blocks);
1197                 for (unsigned int i = 0; i < num_prot_blocks; i++)
1198                         bank->prot_blocks[i].is_protected = 0;
1199                 LOG_DEBUG("allocated %u prot blocks", num_prot_blocks);
1200         }
1201
1202         if (stm32x_info->has_large_mem) {
1203                 /* dual-bank */
1204                 setup_bank(bank, 0, flash_size_in_kb >> 1, max_sector_size_in_kb);
1205                 setup_bank(bank, num_pages >> 1, flash_size_in_kb >> 1,
1206                         max_sector_size_in_kb);
1207
1208                 /* F767x/F77x in dual mode, one protection bit refers to two adjacent sectors */
1209                 if (device_id == 0x451) {
1210                         for (unsigned int i = 0; i < num_prot_blocks; i++) {
1211                                 bank->prot_blocks[i].offset = bank->sectors[i << 1].offset;
1212                                 bank->prot_blocks[i].size = bank->sectors[i << 1].size
1213                                                 + bank->sectors[(i << 1) + 1].size;
1214                         }
1215                 }
1216         } else {
1217                 /* single-bank */
1218                 setup_bank(bank, 0, flash_size_in_kb, max_sector_size_in_kb);
1219
1220                 /* F413/F423, sectors 14 and 15 share one common protection bit */
1221                 if (device_id == 0x463) {
1222                         for (unsigned int i = 0; i < num_prot_blocks; i++) {
1223                                 bank->prot_blocks[i].offset = bank->sectors[i].offset;
1224                                 bank->prot_blocks[i].size = bank->sectors[i].size;
1225                         }
1226                         bank->prot_blocks[num_prot_blocks - 1].size <<= 1;
1227                 }
1228         }
1229         bank->num_prot_blocks = num_prot_blocks;
1230         assert((bank->size >> 10) == flash_size_in_kb);
1231
1232         stm32x_info->probed = true;
1233         return ERROR_OK;
1234 }
1235
1236 static int stm32x_auto_probe(struct flash_bank *bank)
1237 {
1238         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
1239         if (stm32x_info->probed)
1240                 return ERROR_OK;
1241         return stm32x_probe(bank);
1242 }
1243
1244 static int get_stm32x_info(struct flash_bank *bank, struct command_invocation *cmd)
1245 {
1246         uint32_t dbgmcu_idcode;
1247
1248         /* read stm32 device id register */
1249         int retval = stm32x_get_device_id(bank, &dbgmcu_idcode);
1250         if (retval != ERROR_OK)
1251                 return retval;
1252
1253         uint16_t device_id = dbgmcu_idcode & 0xfff;
1254         uint16_t rev_id = dbgmcu_idcode >> 16;
1255         const char *device_str;
1256         const char *rev_str = NULL;
1257
1258         switch (device_id) {
1259         case 0x411:
1260                 device_str = "STM32F2xx";
1261
1262                 switch (rev_id) {
1263                 case 0x1000:
1264                         rev_str = "A";
1265                         break;
1266
1267                 case 0x2000:
1268                         rev_str = "B";
1269                         break;
1270
1271                 case 0x1001:
1272                         rev_str = "Z";
1273                         break;
1274
1275                 case 0x2001:
1276                         rev_str = "Y";
1277                         break;
1278
1279                 case 0x2003:
1280                         rev_str = "X";
1281                         break;
1282
1283                 case 0x2007:
1284                         rev_str = "1";
1285                         break;
1286
1287                 case 0x200F:
1288                         rev_str = "V";
1289                         break;
1290
1291                 case 0x201F:
1292                         rev_str = "2";
1293                         break;
1294                 }
1295                 break;
1296
1297         case 0x413:
1298         case 0x419:
1299         case 0x434:
1300                 device_str = "STM32F4xx";
1301
1302                 switch (rev_id) {
1303                 case 0x1000:
1304                         rev_str = "A";
1305                         break;
1306
1307                 case 0x1001:
1308                         rev_str = "Z";
1309                         break;
1310
1311                 case 0x1003:
1312                         rev_str = "Y";
1313                         break;
1314
1315                 case 0x1007:
1316                         rev_str = "1";
1317                         break;
1318
1319                 case 0x2001:
1320                         rev_str = "3";
1321                         break;
1322                 }
1323                 break;
1324
1325         case 0x421:
1326                 device_str = "STM32F446";
1327
1328                 switch (rev_id) {
1329                 case 0x1000:
1330                         rev_str = "A";
1331                         break;
1332                 }
1333                 break;
1334
1335         case 0x423:
1336         case 0x431:
1337         case 0x433:
1338         case 0x458:
1339         case 0x441:
1340                 device_str = "STM32F4xx (Low Power)";
1341
1342                 switch (rev_id) {
1343                 case 0x1000:
1344                         rev_str = "A";
1345                         break;
1346
1347                 case 0x1001:
1348                         rev_str = "Z";
1349                         break;
1350
1351                 case 0x2000:
1352                         rev_str = "B";
1353                         break;
1354
1355                 case 0x3000:
1356                         rev_str = "C";
1357                         break;
1358                 }
1359                 break;
1360
1361         case 0x449:
1362                 device_str = "STM32F7[4|5]x";
1363
1364                 switch (rev_id) {
1365                 case 0x1000:
1366                         rev_str = "A";
1367                         break;
1368
1369                 case 0x1001:
1370                         rev_str = "Z";
1371                         break;
1372                 }
1373                 break;
1374
1375         case 0x451:
1376                 device_str = "STM32F7[6|7]x";
1377
1378                 switch (rev_id) {
1379                 case 0x1000:
1380                         rev_str = "A";
1381                         break;
1382                 case 0x1001:
1383                         rev_str = "Z";
1384                         break;
1385                 }
1386                 break;
1387
1388         case 0x452:
1389                 device_str = "STM32F7[2|3]x";
1390
1391                 switch (rev_id) {
1392                 case 0x1000:
1393                         rev_str = "A";
1394                         break;
1395                 }
1396                 break;
1397
1398         case 0x463:
1399                 device_str = "STM32F4[1|2]3";
1400
1401                 switch (rev_id) {
1402                 case 0x1000:
1403                         rev_str = "A";
1404                         break;
1405                 }
1406                 break;
1407
1408         default:
1409                 command_print_sameline(cmd, "Cannot identify target as a STM32F2/4/7\n");
1410                 return ERROR_FAIL;
1411         }
1412
1413         if (rev_str)
1414                 command_print_sameline(cmd, "%s - Rev: %s", device_str, rev_str);
1415         else
1416                 command_print_sameline(cmd, "%s - Rev: unknown (0x%04" PRIx16 ")", device_str, rev_id);
1417
1418         return ERROR_OK;
1419 }
1420
1421 COMMAND_HANDLER(stm32x_handle_lock_command)
1422 {
1423         struct target *target = NULL;
1424         struct stm32x_flash_bank *stm32x_info = NULL;
1425
1426         if (CMD_ARGC < 1)
1427                 return ERROR_COMMAND_SYNTAX_ERROR;
1428
1429         struct flash_bank *bank;
1430         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1431         if (retval != ERROR_OK)
1432                 return retval;
1433
1434         stm32x_info = bank->driver_priv;
1435         target = bank->target;
1436
1437         if (target->state != TARGET_HALTED) {
1438                 LOG_INFO("Target not halted");
1439                 /* return ERROR_TARGET_NOT_HALTED; */
1440         }
1441
1442         if (stm32x_read_options(bank) != ERROR_OK) {
1443                 command_print(CMD, "%s failed to read options", bank->driver->name);
1444                 return ERROR_OK;
1445         }
1446
1447         /* set readout protection */
1448         stm32x_info->option_bytes.RDP = 0;
1449
1450         if (stm32x_write_options(bank) != ERROR_OK) {
1451                 command_print(CMD, "%s failed to lock device", bank->driver->name);
1452                 return ERROR_OK;
1453         }
1454
1455         command_print(CMD, "%s locked", bank->driver->name);
1456
1457         return ERROR_OK;
1458 }
1459
1460 COMMAND_HANDLER(stm32x_handle_unlock_command)
1461 {
1462         struct target *target = NULL;
1463         struct stm32x_flash_bank *stm32x_info = NULL;
1464
1465         if (CMD_ARGC < 1)
1466                 return ERROR_COMMAND_SYNTAX_ERROR;
1467
1468         struct flash_bank *bank;
1469         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1470         if (retval != ERROR_OK)
1471                 return retval;
1472
1473         stm32x_info = bank->driver_priv;
1474         target = bank->target;
1475
1476         if (target->state != TARGET_HALTED) {
1477                 LOG_INFO("Target not halted");
1478                 /* return ERROR_TARGET_NOT_HALTED; */
1479         }
1480
1481         if (stm32x_read_options(bank) != ERROR_OK) {
1482                 command_print(CMD, "%s failed to read options", bank->driver->name);
1483                 return ERROR_OK;
1484         }
1485
1486         /* clear readout protection and complementary option bytes
1487          * this will also force a device unlock if set */
1488         stm32x_info->option_bytes.RDP = 0xAA;
1489         if (stm32x_info->has_optcr2_pcrop) {
1490                 stm32x_info->option_bytes.optcr2_pcrop = OPTCR2_PCROP_RDP | (~1U << bank->num_sectors);
1491         }
1492
1493         if (stm32x_write_options(bank) != ERROR_OK) {
1494                 command_print(CMD, "%s failed to unlock device", bank->driver->name);
1495                 return ERROR_OK;
1496         }
1497
1498         command_print(CMD, "%s unlocked.\n"
1499                         "INFO: a reset or power cycle is required "
1500                         "for the new settings to take effect.", bank->driver->name);
1501
1502         return ERROR_OK;
1503 }
1504
1505 static int stm32x_mass_erase(struct flash_bank *bank)
1506 {
1507         int retval;
1508         uint32_t flash_mer;
1509         struct target *target = bank->target;
1510         struct stm32x_flash_bank *stm32x_info = NULL;
1511
1512         if (target->state != TARGET_HALTED) {
1513                 LOG_ERROR("Target not halted");
1514                 return ERROR_TARGET_NOT_HALTED;
1515         }
1516
1517         stm32x_info = bank->driver_priv;
1518
1519         retval = stm32x_unlock_reg(target);
1520         if (retval != ERROR_OK)
1521                 return retval;
1522
1523         /* mass erase flash memory */
1524         if (stm32x_info->has_large_mem)
1525                 flash_mer = FLASH_MER | FLASH_MER1;
1526         else
1527                 flash_mer = FLASH_MER;
1528
1529         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), flash_mer);
1530         if (retval != ERROR_OK)
1531                 return retval;
1532         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
1533                 flash_mer | FLASH_STRT);
1534         if (retval != ERROR_OK)
1535                 return retval;
1536
1537         retval = stm32x_wait_status_busy(bank, FLASH_MASS_ERASE_TIMEOUT);
1538         if (retval != ERROR_OK)
1539                 return retval;
1540
1541         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
1542         if (retval != ERROR_OK)
1543                 return retval;
1544
1545         return ERROR_OK;
1546 }
1547
1548 COMMAND_HANDLER(stm32x_handle_mass_erase_command)
1549 {
1550         if (CMD_ARGC < 1) {
1551                 command_print(CMD, "stm32x mass_erase <bank>");
1552                 return ERROR_COMMAND_SYNTAX_ERROR;
1553         }
1554
1555         struct flash_bank *bank;
1556         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1557         if (retval != ERROR_OK)
1558                 return retval;
1559
1560         retval = stm32x_mass_erase(bank);
1561         if (retval == ERROR_OK) {
1562                 command_print(CMD, "stm32x mass erase complete");
1563         } else {
1564                 command_print(CMD, "stm32x mass erase failed");
1565         }
1566
1567         return retval;
1568 }
1569
1570 COMMAND_HANDLER(stm32f2x_handle_options_read_command)
1571 {
1572         int retval;
1573         struct flash_bank *bank;
1574         struct stm32x_flash_bank *stm32x_info = NULL;
1575
1576         if (CMD_ARGC != 1) {
1577                 command_print(CMD, "stm32f2x options_read <bank>");
1578                 return ERROR_COMMAND_SYNTAX_ERROR;
1579         }
1580
1581         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1582         if (retval != ERROR_OK)
1583                 return retval;
1584
1585         retval = stm32x_read_options(bank);
1586         if (retval != ERROR_OK)
1587                 return retval;
1588
1589         stm32x_info = bank->driver_priv;
1590         if (stm32x_info->has_extra_options) {
1591                 if (stm32x_info->has_boot_addr) {
1592                         uint32_t boot_addr = stm32x_info->option_bytes.boot_addr;
1593
1594                         command_print(CMD, "stm32f2x user_options 0x%03" PRIX16 ","
1595                                 " boot_add0 0x%04" PRIX32 ", boot_add1 0x%04" PRIX32,
1596                                 stm32x_info->option_bytes.user_options,
1597                                 boot_addr & 0xffff, (boot_addr & 0xffff0000) >> 16);
1598                         if (stm32x_info->has_optcr2_pcrop) {
1599                                 command_print(CMD, "stm32f2x optcr2_pcrop 0x%08" PRIX32,
1600                                                 stm32x_info->option_bytes.optcr2_pcrop);
1601                         }
1602                 } else {
1603                         command_print(CMD, "stm32f2x user_options 0x%03" PRIX16,
1604                                 stm32x_info->option_bytes.user_options);
1605                 }
1606         } else {
1607                 command_print(CMD, "stm32f2x user_options 0x%02" PRIX16,
1608                         stm32x_info->option_bytes.user_options);
1609
1610         }
1611
1612         return retval;
1613 }
1614
1615 COMMAND_HANDLER(stm32f2x_handle_options_write_command)
1616 {
1617         int retval;
1618         struct flash_bank *bank;
1619         struct stm32x_flash_bank *stm32x_info = NULL;
1620         uint16_t user_options, boot_addr0, boot_addr1, options_mask;
1621
1622         if (CMD_ARGC < 1) {
1623                 command_print(CMD, "stm32f2x options_write <bank> ...");
1624                 return ERROR_COMMAND_SYNTAX_ERROR;
1625         }
1626
1627         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1628         if (retval != ERROR_OK)
1629                 return retval;
1630
1631         retval = stm32x_read_options(bank);
1632         if (retval != ERROR_OK)
1633                 return retval;
1634
1635         stm32x_info = bank->driver_priv;
1636         if (stm32x_info->has_boot_addr) {
1637                 if (CMD_ARGC != 4) {
1638                         command_print(CMD, "stm32f2x options_write <bank> <user_options>"
1639                                 " <boot_addr0> <boot_addr1>");
1640                         return ERROR_COMMAND_SYNTAX_ERROR;
1641                 }
1642                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[2], boot_addr0);
1643                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[3], boot_addr1);
1644                 stm32x_info->option_bytes.boot_addr = boot_addr0 | (((uint32_t) boot_addr1) << 16);
1645         } else {
1646                 if (CMD_ARGC != 2) {
1647                         command_print(CMD, "stm32f2x options_write <bank> <user_options>");
1648                         return ERROR_COMMAND_SYNTAX_ERROR;
1649                 }
1650         }
1651
1652         COMMAND_PARSE_NUMBER(u16, CMD_ARGV[1], user_options);
1653         options_mask = !stm32x_info->has_extra_options ? ~0xfc :
1654                 ~(((0xf00 << (stm32x_info->protection_bits - 12)) | 0xff) & 0xffc);
1655         if (user_options & options_mask) {
1656                 command_print(CMD, "stm32f2x invalid user_options");
1657                 return ERROR_COMMAND_ARGUMENT_INVALID;
1658         }
1659
1660         stm32x_info->option_bytes.user_options = user_options;
1661
1662         if (stm32x_write_options(bank) != ERROR_OK) {
1663                 command_print(CMD, "stm32f2x failed to write options");
1664                 return ERROR_OK;
1665         }
1666
1667         /* switching between single- and dual-bank modes requires re-probe */
1668         /* ... and reprogramming of whole flash */
1669         stm32x_info->probed = false;
1670
1671         command_print(CMD, "stm32f2x write options complete.\n"
1672                                 "INFO: a reset or power cycle is required "
1673                                 "for the new settings to take effect.");
1674         return retval;
1675 }
1676
1677 COMMAND_HANDLER(stm32f2x_handle_optcr2_write_command)
1678 {
1679         int retval;
1680         struct flash_bank *bank;
1681         struct stm32x_flash_bank *stm32x_info = NULL;
1682         uint32_t optcr2_pcrop;
1683
1684         if (CMD_ARGC != 2) {
1685                 command_print(CMD, "stm32f2x optcr2_write <bank> <optcr2_value>");
1686                 return ERROR_COMMAND_SYNTAX_ERROR;
1687         }
1688
1689         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1690         if (retval != ERROR_OK)
1691                 return retval;
1692
1693         stm32x_info = bank->driver_priv;
1694         if (!stm32x_info->has_optcr2_pcrop) {
1695                 command_print(CMD, "no optcr2 register");
1696                 return ERROR_COMMAND_ARGUMENT_INVALID;
1697         }
1698
1699         command_print(CMD, "INFO: To disable PCROP, set PCROP_RDP"
1700                                 " with PCROPi bits STILL SET, then\nlock device and"
1701                                 " finally unlock it. Clears PCROP and mass erases flash.");
1702
1703         retval = stm32x_read_options(bank);
1704         if (retval != ERROR_OK)
1705                 return retval;
1706
1707         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], optcr2_pcrop);
1708         stm32x_info->option_bytes.optcr2_pcrop = optcr2_pcrop;
1709
1710         if (stm32x_write_options(bank) != ERROR_OK) {
1711                 command_print(CMD, "stm32f2x failed to write options");
1712                 return ERROR_OK;
1713         }
1714
1715         command_print(CMD, "stm32f2x optcr2_write complete.");
1716         return retval;
1717 }
1718
1719 COMMAND_HANDLER(stm32x_handle_otp_command)
1720 {
1721         if (CMD_ARGC < 2) {
1722                 command_print(CMD, "stm32x otp <bank> (enable|disable|show)");
1723                 return ERROR_COMMAND_SYNTAX_ERROR;
1724         }
1725
1726         struct flash_bank *bank;
1727         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1728         if (retval != ERROR_OK)
1729                 return retval;
1730         if (stm32x_is_otp(bank)) {
1731                 if (strcmp(CMD_ARGV[1], "enable") == 0) {
1732                         stm32x_otp_enable(bank);
1733                 } else if (strcmp(CMD_ARGV[1], "disable") == 0) {
1734                         stm32x_otp_disable(bank);
1735                 } else if (strcmp(CMD_ARGV[1], "show") == 0) {
1736                         command_print(CMD,
1737                                 "OTP memory bank #%u is %s for write commands.",
1738                                 bank->bank_number,
1739                                 stm32x_is_otp_unlocked(bank) ? "enabled" : "disabled");
1740                 } else {
1741                         return ERROR_COMMAND_SYNTAX_ERROR;
1742                 }
1743         } else {
1744                 command_print(CMD, "Failed: not an OTP bank.");
1745         }
1746
1747         return retval;
1748 }
1749
1750 static const struct command_registration stm32f2x_exec_command_handlers[] = {
1751         {
1752                 .name = "lock",
1753                 .handler = stm32x_handle_lock_command,
1754                 .mode = COMMAND_EXEC,
1755                 .usage = "bank_id",
1756                 .help = "Lock entire flash device.",
1757         },
1758         {
1759                 .name = "unlock",
1760                 .handler = stm32x_handle_unlock_command,
1761                 .mode = COMMAND_EXEC,
1762                 .usage = "bank_id",
1763                 .help = "Unlock entire protected flash device.",
1764         },
1765         {
1766                 .name = "mass_erase",
1767                 .handler = stm32x_handle_mass_erase_command,
1768                 .mode = COMMAND_EXEC,
1769                 .usage = "bank_id",
1770                 .help = "Erase entire flash device.",
1771         },
1772         {
1773                 .name = "options_read",
1774                 .handler = stm32f2x_handle_options_read_command,
1775                 .mode = COMMAND_EXEC,
1776                 .usage = "bank_id",
1777                 .help = "Read and display device option bytes.",
1778         },
1779         {
1780                 .name = "options_write",
1781                 .handler = stm32f2x_handle_options_write_command,
1782                 .mode = COMMAND_EXEC,
1783                 .usage = "bank_id user_options [ boot_add0 boot_add1 ]",
1784                 .help = "Write option bytes",
1785         },
1786         {
1787                 .name = "optcr2_write",
1788                 .handler = stm32f2x_handle_optcr2_write_command,
1789                 .mode = COMMAND_EXEC,
1790                 .usage = "bank_id optcr2",
1791                 .help = "Write optcr2 word",
1792         },
1793         {
1794                 .name = "otp",
1795                 .handler = stm32x_handle_otp_command,
1796                 .mode = COMMAND_EXEC,
1797                 .usage = "bank_id",
1798                 .help = "OTP (One Time Programmable) memory write enable/disable.",
1799         },
1800         COMMAND_REGISTRATION_DONE
1801 };
1802
1803 static const struct command_registration stm32f2x_command_handlers[] = {
1804         {
1805                 .name = "stm32f2x",
1806                 .mode = COMMAND_ANY,
1807                 .help = "stm32f2x flash command group",
1808                 .usage = "",
1809                 .chain = stm32f2x_exec_command_handlers,
1810         },
1811         COMMAND_REGISTRATION_DONE
1812 };
1813
1814 const struct flash_driver stm32f2x_flash = {
1815         .name = "stm32f2x",
1816         .commands = stm32f2x_command_handlers,
1817         .flash_bank_command = stm32x_flash_bank_command,
1818         .erase = stm32x_erase,
1819         .protect = stm32x_protect,
1820         .write = stm32x_write,
1821         .read = default_flash_read,
1822         .probe = stm32x_probe,
1823         .auto_probe = stm32x_auto_probe,
1824         .erase_check = default_flash_blank_check,
1825         .protect_check = stm32x_protect_check,
1826         .info = get_stm32x_info,
1827         .free_driver_priv = default_flash_free_driver_priv,
1828 };