Constify struct flash_driver instances
[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 #%d 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 #%d is is enabled for write commands.",
245                          bank->bank_number);
246                 stm32x_info->otp_unlocked = true;
247         } else {
248                 LOG_WARNING("OTP memory bank #%d 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: %" 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: %" 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 i, 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 (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, int first, int last)
542 {
543         struct target *target = bank->target;
544         uint32_t lock_base;
545         int i, retval;
546         uint8_t lock;
547
548         assert((0 <= first) && (first <= last) && (last < bank->num_sectors));
549
550         lock_base = stm32x_otp_is_f7(bank) ? STM32F7_OTP_LOCK_BASE
551                   : STM32F2_OTP_LOCK_BASE;
552
553         for (i = first; first <= last; i++) {
554                 retval = target_read_u8(target, lock_base + i, &lock);
555                 if (retval != ERROR_OK)
556                         return retval;
557                 if (lock)
558                         continue;
559
560                 lock = 0xff;
561                 retval = target_write_u8(target, lock_base + i, lock);
562                 if (retval != ERROR_OK)
563                         return retval;
564         }
565
566         return ERROR_OK;
567 }
568
569 static int stm32x_protect_check(struct flash_bank *bank)
570 {
571         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
572         struct flash_sector *prot_blocks;
573         int num_prot_blocks;
574         int retval;
575
576         /* if it's the OTP bank, look at the lock bits there */
577         if (stm32x_is_otp(bank))
578                 return stm32x_otp_read_protect(bank);
579
580         /* read write protection settings */
581         retval = stm32x_read_options(bank);
582         if (retval != ERROR_OK) {
583                 LOG_DEBUG("unable to read option bytes");
584                 return retval;
585         }
586
587         if (bank->prot_blocks) {
588                 num_prot_blocks = bank->num_prot_blocks;
589                 prot_blocks = bank->prot_blocks;
590         } else {
591                 num_prot_blocks = bank->num_sectors;
592                 prot_blocks = bank->sectors;
593         }
594
595         for (int i = 0; i < num_prot_blocks; i++)
596                 prot_blocks[i].is_protected =
597                         ~(stm32x_info->option_bytes.protection >> i) & 1;
598
599         return ERROR_OK;
600 }
601
602 static int stm32x_erase(struct flash_bank *bank, int first, int last)
603 {
604         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
605         struct target *target = bank->target;
606         int i;
607
608         if (stm32x_is_otp(bank)) {
609                 LOG_ERROR("Cannot erase OTP memory");
610                 return ERROR_FAIL;
611         }
612
613         assert((0 <= first) && (first <= last) && (last < bank->num_sectors));
614
615         if (bank->target->state != TARGET_HALTED) {
616                 LOG_ERROR("Target not halted");
617                 return ERROR_TARGET_NOT_HALTED;
618         }
619
620         int retval;
621         retval = stm32x_unlock_reg(target);
622         if (retval != ERROR_OK)
623                 return retval;
624
625         /*
626         Sector Erase
627         To erase a sector, follow the procedure below:
628         1. Check that no Flash memory operation is ongoing by checking the BSY bit in the
629           FLASH_SR register
630         2. Set the SER bit and select the sector
631           you wish to erase (SNB) in the FLASH_CR register
632         3. Set the STRT bit in the FLASH_CR register
633         4. Wait for the BSY bit to be cleared
634          */
635
636         for (i = first; i <= last; i++) {
637                 int snb;
638                 if (stm32x_info->has_large_mem && i >= 12)
639                         snb = (i - 12) | 0x10;
640                 else
641                         snb = i;
642
643                 retval = target_write_u32(target,
644                                 stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_SER | FLASH_SNB(snb) | FLASH_STRT);
645                 if (retval != ERROR_OK)
646                         return retval;
647
648                 retval = stm32x_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
649                 if (retval != ERROR_OK)
650                         return retval;
651
652                 bank->sectors[i].is_erased = 1;
653         }
654
655         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
656         if (retval != ERROR_OK)
657                 return retval;
658
659         return ERROR_OK;
660 }
661
662 static int stm32x_protect(struct flash_bank *bank, int set, int first, 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 (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 = %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 int setup_sector(struct flash_bank *bank, int start, int num, int size)
898 {
899
900         for (int i = start; i < (start + num) ; i++) {
901                 assert(i < bank->num_sectors);
902                 bank->sectors[i].offset = bank->size;
903                 bank->sectors[i].size = size;
904                 bank->size += bank->sectors[i].size;
905             LOG_DEBUG("sector %d: %d kBytes", i, size >> 10);
906         }
907
908         return start + num;
909 }
910
911 static void setup_bank(struct flash_bank *bank, int start,
912         uint16_t flash_size_in_kb, uint16_t max_sector_size_in_kb)
913 {
914         int remain;
915
916         start = setup_sector(bank, start, 4, (max_sector_size_in_kb / 8) * 1024);
917         start = setup_sector(bank, start, 1, (max_sector_size_in_kb / 2) * 1024);
918
919         /* remaining sectors all of size max_sector_size_in_kb */
920         remain = (flash_size_in_kb / max_sector_size_in_kb) - 1;
921         start = setup_sector(bank, start, remain, max_sector_size_in_kb * 1024);
922 }
923
924 static int stm32x_get_device_id(struct flash_bank *bank, uint32_t *device_id)
925 {
926         /* this checks for a stm32f4x errata issue where a
927          * stm32f2x DBGMCU_IDCODE is incorrectly returned.
928          * If the issue is detected target is forced to stm32f4x Rev A.
929          * Only effects Rev A silicon */
930
931         struct target *target = bank->target;
932         uint32_t cpuid;
933
934         /* read stm32 device id register */
935         int retval = target_read_u32(target, 0xE0042000, device_id);
936         if (retval != ERROR_OK)
937                 return retval;
938
939         if ((*device_id & 0xfff) == 0x411) {
940                 /* read CPUID reg to check core type */
941                 retval = target_read_u32(target, 0xE000ED00, &cpuid);
942                 if (retval != ERROR_OK)
943                         return retval;
944
945                 /* check for cortex_m4 */
946                 if (((cpuid >> 4) & 0xFFF) == 0xC24) {
947                         *device_id &= ~((0xFFFF << 16) | 0xfff);
948                         *device_id |= (0x1000 << 16) | 0x413;
949                         LOG_INFO("stm32f4x errata detected - fixing incorrect MCU_IDCODE");
950                 }
951         }
952         return retval;
953 }
954
955 static int stm32x_probe(struct flash_bank *bank)
956 {
957         struct target *target = bank->target;
958         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
959         int i, num_prot_blocks, num_sectors;
960         uint16_t flash_size_in_kb;
961         uint16_t otp_size_in_b;
962         uint16_t otp_sector_size;
963         uint32_t flash_size_reg = 0x1FFF7A22;
964         uint16_t max_sector_size_in_kb = 128;
965         uint16_t max_flash_size_in_kb;
966         uint32_t device_id;
967         uint32_t base_address = 0x08000000;
968
969         stm32x_info->probed = false;
970         stm32x_info->has_large_mem = false;
971         stm32x_info->has_boot_addr = false;
972         stm32x_info->has_extra_options = false;
973         stm32x_info->has_optcr2_pcrop = false;
974         stm32x_info->protection_bits = 12;              /* max. number of nWRPi bits (in FLASH_OPTCR !!!) */
975         num_prot_blocks = 0;
976
977         if (bank->sectors) {
978                 free(bank->sectors);
979                 bank->num_sectors = 0;
980                 bank->sectors = NULL;
981         }
982
983         if (bank->prot_blocks) {
984                 free(bank->prot_blocks);
985                 bank->num_prot_blocks = 0;
986                 bank->prot_blocks = NULL;
987         }
988
989         /* if explicitely called out as OTP bank, short circuit probe */
990         if (stm32x_is_otp(bank)) {
991                 if (stm32x_otp_is_f7(bank)) {
992                         otp_size_in_b = STM32F7_OTP_SIZE;
993                         otp_sector_size = STM32F7_OTP_SECTOR_SIZE;
994                 } else {
995                         otp_size_in_b = STM32F2_OTP_SIZE;
996                         otp_sector_size = STM32F2_OTP_SECTOR_SIZE;
997                 }
998
999                 num_sectors = otp_size_in_b / otp_sector_size;
1000                 LOG_INFO("flash size = %d bytes", otp_size_in_b);
1001
1002                 assert(num_sectors > 0);
1003
1004                 bank->num_sectors = num_sectors;
1005                 bank->sectors = calloc(sizeof(struct flash_sector), num_sectors);
1006
1007                 if (stm32x_otp_is_f7(bank))
1008                         bank->size = STM32F7_OTP_SIZE;
1009                 else
1010                         bank->size = STM32F2_OTP_SIZE;
1011
1012                 for (i = 0; i < num_sectors; i++) {
1013                         bank->sectors[i].offset = i * otp_sector_size;
1014                         bank->sectors[i].size = otp_sector_size;
1015                         bank->sectors[i].is_erased = 1;
1016                         bank->sectors[i].is_protected = 0;
1017                 }
1018
1019                 stm32x_info->probed = true;
1020                 return ERROR_OK;
1021         }
1022
1023         /* read stm32 device id register */
1024         int retval = stm32x_get_device_id(bank, &device_id);
1025         if (retval != ERROR_OK)
1026                 return retval;
1027         LOG_INFO("device id = 0x%08" PRIx32 "", device_id);
1028         device_id &= 0xfff;             /* only bits 0-11 are used further on */
1029
1030         /* set max flash size depending on family, id taken from AN2606 */
1031         switch (device_id) {
1032         case 0x411: /* F20x/21x */
1033         case 0x413: /* F40x/41x */
1034                 max_flash_size_in_kb = 1024;
1035                 break;
1036
1037         case 0x419: /* F42x/43x */
1038         case 0x434: /* F469/479 */
1039                 stm32x_info->has_extra_options = true;
1040                 max_flash_size_in_kb = 2048;
1041                 break;
1042
1043         case 0x423:     /* F401xB/C */
1044                 max_flash_size_in_kb = 256;
1045                 break;
1046
1047         case 0x421:     /* F446 */
1048         case 0x431: /* F411 */
1049         case 0x433: /* F401xD/E */
1050         case 0x441: /* F412 */
1051                 max_flash_size_in_kb = 512;
1052                 break;
1053
1054         case 0x458: /* F410 */
1055                 max_flash_size_in_kb = 128;
1056                 break;
1057
1058         case 0x449:     /* F74x/75x */
1059                 max_flash_size_in_kb = 1024;
1060                 max_sector_size_in_kb = 256;
1061                 flash_size_reg = 0x1FF0F442;
1062                 stm32x_info->has_extra_options = true;
1063                 stm32x_info->has_boot_addr = true;
1064                 break;
1065
1066         case 0x451:     /* F76x/77x */
1067                 max_flash_size_in_kb = 2048;
1068                 max_sector_size_in_kb = 256;
1069                 flash_size_reg = 0x1FF0F442;
1070                 stm32x_info->has_extra_options = true;
1071                 stm32x_info->has_boot_addr = true;
1072                 break;
1073
1074         case 0x452:     /* F72x/73x */
1075                 max_flash_size_in_kb = 512;
1076                 flash_size_reg = 0x1FF07A22;    /* yes, 0x1FF*0*7A22, not 0x1FF*F*7A22 */
1077                 stm32x_info->has_extra_options = true;
1078                 stm32x_info->has_boot_addr = true;
1079                 stm32x_info->has_optcr2_pcrop = true;
1080                 break;
1081
1082         case 0x463:     /* F413x/423x */
1083                 max_flash_size_in_kb = 1536;
1084                 stm32x_info->has_extra_options = true;
1085                 stm32x_info->protection_bits = 15;
1086                 num_prot_blocks = 15;
1087                 break;
1088
1089         default:
1090                 LOG_WARNING("Cannot identify target as a STM32 family.");
1091                 return ERROR_FAIL;
1092         }
1093
1094         /* get flash size from target. */
1095         retval = target_read_u16(target, flash_size_reg, &flash_size_in_kb);
1096
1097         /* failed reading flash size or flash size invalid (early silicon),
1098          * default to max target family */
1099         if (retval != ERROR_OK || flash_size_in_kb == 0xffff || flash_size_in_kb == 0) {
1100                 LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming %dk flash",
1101                         max_flash_size_in_kb);
1102                 flash_size_in_kb = max_flash_size_in_kb;
1103         }
1104
1105         /* if the user sets the size manually then ignore the probed value
1106          * this allows us to work around devices that have a invalid flash size register value */
1107         if (stm32x_info->user_bank_size) {
1108                 LOG_INFO("ignoring flash probed value, using configured bank size");
1109                 flash_size_in_kb = stm32x_info->user_bank_size / 1024;
1110         }
1111
1112         LOG_INFO("flash size = %d kbytes", flash_size_in_kb);
1113
1114         /* did we assign flash size? */
1115         assert(flash_size_in_kb != 0xffff);
1116
1117         /* F42x/43x/469/479 1024 kiByte devices have a dual bank option */
1118         if ((device_id == 0x419) || (device_id == 0x434)) {
1119                 uint32_t optiondata;
1120                 retval = target_read_u32(target, STM32_FLASH_OPTCR, &optiondata);
1121                 if (retval != ERROR_OK) {
1122                         LOG_DEBUG("unable to read option bytes");
1123                         return retval;
1124                 }
1125                 if ((flash_size_in_kb > 1024) || (optiondata & OPTCR_DB1M)) {
1126                         stm32x_info->has_large_mem = true;
1127                         LOG_INFO("Dual Bank %d kiB STM32F42x/43x/469/479 found", flash_size_in_kb);
1128                 } else {
1129                         stm32x_info->has_large_mem = false;
1130                         LOG_INFO("Single Bank %d kiB STM32F42x/43x/469/479 found", flash_size_in_kb);
1131                 }
1132         }
1133
1134         /* F76x/77x devices have a dual bank option */
1135         if (device_id == 0x451) {
1136                 uint32_t optiondata;
1137                 retval = target_read_u32(target, STM32_FLASH_OPTCR, &optiondata);
1138                 if (retval != ERROR_OK) {
1139                         LOG_DEBUG("unable to read option bytes");
1140                         return retval;
1141                 }
1142                 if (optiondata & OPTCR_NDBANK) {
1143                         stm32x_info->has_large_mem = false;
1144                         LOG_INFO("Single Bank %d kiB STM32F76x/77x found", flash_size_in_kb);
1145                 } else {
1146                         stm32x_info->has_large_mem = true;
1147                         max_sector_size_in_kb >>= 1; /* sector size divided by 2 in dual-bank mode */
1148                         LOG_INFO("Dual Bank %d kiB STM32F76x/77x found", flash_size_in_kb);
1149                 }
1150         }
1151
1152         /* calculate numbers of pages */
1153         int num_pages = flash_size_in_kb / max_sector_size_in_kb
1154                 + (stm32x_info->has_large_mem ? 8 : 4);
1155
1156         bank->base = base_address;
1157         bank->num_sectors = num_pages;
1158         bank->sectors = malloc(sizeof(struct flash_sector) * num_pages);
1159         for (i = 0; i < num_pages; i++) {
1160                 bank->sectors[i].is_erased = -1;
1161                 bank->sectors[i].is_protected = 0;
1162         }
1163         bank->size = 0;
1164         LOG_DEBUG("allocated %d sectors", num_pages);
1165
1166         /* F76x/77x in dual bank mode */
1167         if ((device_id == 0x451) && stm32x_info->has_large_mem)
1168                 num_prot_blocks = num_pages >> 1;
1169
1170         if (num_prot_blocks) {
1171                 bank->prot_blocks = malloc(sizeof(struct flash_sector) * num_prot_blocks);
1172                 for (i = 0; i < num_prot_blocks; i++)
1173                         bank->prot_blocks[i].is_protected = 0;
1174                 LOG_DEBUG("allocated %d prot blocks", num_prot_blocks);
1175         }
1176
1177         if (stm32x_info->has_large_mem) {
1178                 /* dual-bank */
1179                 setup_bank(bank, 0, flash_size_in_kb >> 1, max_sector_size_in_kb);
1180                 setup_bank(bank, num_pages >> 1, flash_size_in_kb >> 1,
1181                         max_sector_size_in_kb);
1182
1183                 /* F767x/F77x in dual mode, one protection bit refers to two adjacent sectors */
1184                 if (device_id == 0x451) {
1185                         for (i = 0; i < num_prot_blocks; i++) {
1186                                 bank->prot_blocks[i].offset = bank->sectors[i << 1].offset;
1187                                 bank->prot_blocks[i].size = bank->sectors[i << 1].size
1188                                                 + bank->sectors[(i << 1) + 1].size;
1189                         }
1190                 }
1191         } else {
1192                 /* single-bank */
1193                 setup_bank(bank, 0, flash_size_in_kb, max_sector_size_in_kb);
1194
1195                 /* F413/F423, sectors 14 and 15 share one common protection bit */
1196                 if (device_id == 0x463) {
1197                         for (i = 0; i < num_prot_blocks; i++) {
1198                                 bank->prot_blocks[i].offset = bank->sectors[i].offset;
1199                                 bank->prot_blocks[i].size = bank->sectors[i].size;
1200                         }
1201                         bank->prot_blocks[num_prot_blocks - 1].size <<= 1;
1202                 }
1203         }
1204         bank->num_prot_blocks = num_prot_blocks;
1205         assert((bank->size >> 10) == flash_size_in_kb);
1206
1207         stm32x_info->probed = true;
1208         return ERROR_OK;
1209 }
1210
1211 static int stm32x_auto_probe(struct flash_bank *bank)
1212 {
1213         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
1214         if (stm32x_info->probed)
1215                 return ERROR_OK;
1216         return stm32x_probe(bank);
1217 }
1218
1219 static int get_stm32x_info(struct flash_bank *bank, char *buf, int buf_size)
1220 {
1221         uint32_t dbgmcu_idcode;
1222
1223         /* read stm32 device id register */
1224         int retval = stm32x_get_device_id(bank, &dbgmcu_idcode);
1225         if (retval != ERROR_OK)
1226                 return retval;
1227
1228         uint16_t device_id = dbgmcu_idcode & 0xfff;
1229         uint16_t rev_id = dbgmcu_idcode >> 16;
1230         const char *device_str;
1231         const char *rev_str = NULL;
1232
1233         switch (device_id) {
1234         case 0x411:
1235                 device_str = "STM32F2xx";
1236
1237                 switch (rev_id) {
1238                 case 0x1000:
1239                         rev_str = "A";
1240                         break;
1241
1242                 case 0x2000:
1243                         rev_str = "B";
1244                         break;
1245
1246                 case 0x1001:
1247                         rev_str = "Z";
1248                         break;
1249
1250                 case 0x2001:
1251                         rev_str = "Y";
1252                         break;
1253
1254                 case 0x2003:
1255                         rev_str = "X";
1256                         break;
1257
1258                 case 0x2007:
1259                         rev_str = "1";
1260                         break;
1261
1262                 case 0x200F:
1263                         rev_str = "V";
1264                         break;
1265
1266                 case 0x201F:
1267                         rev_str = "2";
1268                         break;
1269                 }
1270                 break;
1271
1272         case 0x413:
1273         case 0x419:
1274         case 0x434:
1275                 device_str = "STM32F4xx";
1276
1277                 switch (rev_id) {
1278                 case 0x1000:
1279                         rev_str = "A";
1280                         break;
1281
1282                 case 0x1001:
1283                         rev_str = "Z";
1284                         break;
1285
1286                 case 0x1003:
1287                         rev_str = "Y";
1288                         break;
1289
1290                 case 0x1007:
1291                         rev_str = "1";
1292                         break;
1293
1294                 case 0x2001:
1295                         rev_str = "3";
1296                         break;
1297                 }
1298                 break;
1299
1300         case 0x421:
1301                 device_str = "STM32F446";
1302
1303                 switch (rev_id) {
1304                 case 0x1000:
1305                         rev_str = "A";
1306                         break;
1307                 }
1308                 break;
1309
1310         case 0x423:
1311         case 0x431:
1312         case 0x433:
1313         case 0x458:
1314         case 0x441:
1315                 device_str = "STM32F4xx (Low Power)";
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 0x2000:
1327                         rev_str = "B";
1328                         break;
1329
1330                 case 0x3000:
1331                         rev_str = "C";
1332                         break;
1333                 }
1334                 break;
1335
1336         case 0x449:
1337                 device_str = "STM32F7[4|5]x";
1338
1339                 switch (rev_id) {
1340                 case 0x1000:
1341                         rev_str = "A";
1342                         break;
1343
1344                 case 0x1001:
1345                         rev_str = "Z";
1346                         break;
1347                 }
1348                 break;
1349
1350         case 0x451:
1351                 device_str = "STM32F7[6|7]x";
1352
1353                 switch (rev_id) {
1354                 case 0x1000:
1355                         rev_str = "A";
1356                         break;
1357                 case 0x1001:
1358                         rev_str = "Z";
1359                         break;
1360                 }
1361                 break;
1362
1363         case 0x452:
1364                 device_str = "STM32F7[2|3]x";
1365
1366                 switch (rev_id) {
1367                 case 0x1000:
1368                         rev_str = "A";
1369                         break;
1370                 }
1371                 break;
1372
1373         case 0x463:
1374                 device_str = "STM32F4[1|2]3";
1375
1376                 switch (rev_id) {
1377                 case 0x1000:
1378                         rev_str = "A";
1379                         break;
1380                 }
1381                 break;
1382
1383         default:
1384                 snprintf(buf, buf_size, "Cannot identify target as a STM32F2/4/7\n");
1385                 return ERROR_FAIL;
1386         }
1387
1388         if (rev_str != NULL)
1389                 snprintf(buf, buf_size, "%s - Rev: %s", device_str, rev_str);
1390         else
1391                 snprintf(buf, buf_size, "%s - Rev: unknown (0x%04x)", device_str, rev_id);
1392
1393         return ERROR_OK;
1394 }
1395
1396 COMMAND_HANDLER(stm32x_handle_lock_command)
1397 {
1398         struct target *target = NULL;
1399         struct stm32x_flash_bank *stm32x_info = NULL;
1400
1401         if (CMD_ARGC < 1)
1402                 return ERROR_COMMAND_SYNTAX_ERROR;
1403
1404         struct flash_bank *bank;
1405         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1406         if (ERROR_OK != retval)
1407                 return retval;
1408
1409         stm32x_info = bank->driver_priv;
1410         target = bank->target;
1411
1412         if (target->state != TARGET_HALTED) {
1413                 LOG_INFO("Target not halted");
1414                 /* return ERROR_TARGET_NOT_HALTED; */
1415         }
1416
1417         if (stm32x_read_options(bank) != ERROR_OK) {
1418                 command_print(CMD_CTX, "%s failed to read options", bank->driver->name);
1419                 return ERROR_OK;
1420         }
1421
1422         /* set readout protection */
1423         stm32x_info->option_bytes.RDP = 0;
1424
1425         if (stm32x_write_options(bank) != ERROR_OK) {
1426                 command_print(CMD_CTX, "%s failed to lock device", bank->driver->name);
1427                 return ERROR_OK;
1428         }
1429
1430         command_print(CMD_CTX, "%s locked", bank->driver->name);
1431
1432         return ERROR_OK;
1433 }
1434
1435 COMMAND_HANDLER(stm32x_handle_unlock_command)
1436 {
1437         struct target *target = NULL;
1438         struct stm32x_flash_bank *stm32x_info = NULL;
1439
1440         if (CMD_ARGC < 1)
1441                 return ERROR_COMMAND_SYNTAX_ERROR;
1442
1443         struct flash_bank *bank;
1444         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1445         if (ERROR_OK != retval)
1446                 return retval;
1447
1448         stm32x_info = bank->driver_priv;
1449         target = bank->target;
1450
1451         if (target->state != TARGET_HALTED) {
1452                 LOG_INFO("Target not halted");
1453                 /* return ERROR_TARGET_NOT_HALTED; */
1454         }
1455
1456         if (stm32x_read_options(bank) != ERROR_OK) {
1457                 command_print(CMD_CTX, "%s failed to read options", bank->driver->name);
1458                 return ERROR_OK;
1459         }
1460
1461         /* clear readout protection and complementary option bytes
1462          * this will also force a device unlock if set */
1463         stm32x_info->option_bytes.RDP = 0xAA;
1464         if (stm32x_info->has_optcr2_pcrop) {
1465                 stm32x_info->option_bytes.optcr2_pcrop = OPTCR2_PCROP_RDP | (~1U << bank->num_sectors);
1466         }
1467
1468         if (stm32x_write_options(bank) != ERROR_OK) {
1469                 command_print(CMD_CTX, "%s failed to unlock device", bank->driver->name);
1470                 return ERROR_OK;
1471         }
1472
1473         command_print(CMD_CTX, "%s unlocked.\n"
1474                         "INFO: a reset or power cycle is required "
1475                         "for the new settings to take effect.", bank->driver->name);
1476
1477         return ERROR_OK;
1478 }
1479
1480 static int stm32x_mass_erase(struct flash_bank *bank)
1481 {
1482         int retval;
1483         uint32_t flash_mer;
1484         struct target *target = bank->target;
1485         struct stm32x_flash_bank *stm32x_info = NULL;
1486
1487         if (target->state != TARGET_HALTED) {
1488                 LOG_ERROR("Target not halted");
1489                 return ERROR_TARGET_NOT_HALTED;
1490         }
1491
1492         stm32x_info = bank->driver_priv;
1493
1494         retval = stm32x_unlock_reg(target);
1495         if (retval != ERROR_OK)
1496                 return retval;
1497
1498         /* mass erase flash memory */
1499         if (stm32x_info->has_large_mem)
1500                 flash_mer = FLASH_MER | FLASH_MER1;
1501         else
1502                 flash_mer = FLASH_MER;
1503
1504         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), flash_mer);
1505         if (retval != ERROR_OK)
1506                 return retval;
1507         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
1508                 flash_mer | FLASH_STRT);
1509         if (retval != ERROR_OK)
1510                 return retval;
1511
1512         retval = stm32x_wait_status_busy(bank, FLASH_MASS_ERASE_TIMEOUT);
1513         if (retval != ERROR_OK)
1514                 return retval;
1515
1516         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
1517         if (retval != ERROR_OK)
1518                 return retval;
1519
1520         return ERROR_OK;
1521 }
1522
1523 COMMAND_HANDLER(stm32x_handle_mass_erase_command)
1524 {
1525         int i;
1526
1527         if (CMD_ARGC < 1) {
1528                 command_print(CMD_CTX, "stm32x mass_erase <bank>");
1529                 return ERROR_COMMAND_SYNTAX_ERROR;
1530         }
1531
1532         struct flash_bank *bank;
1533         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1534         if (ERROR_OK != retval)
1535                 return retval;
1536
1537         retval = stm32x_mass_erase(bank);
1538         if (retval == ERROR_OK) {
1539                 /* set all sectors as erased */
1540                 for (i = 0; i < bank->num_sectors; i++)
1541                         bank->sectors[i].is_erased = 1;
1542
1543                 command_print(CMD_CTX, "stm32x mass erase complete");
1544         } else {
1545                 command_print(CMD_CTX, "stm32x mass erase failed");
1546         }
1547
1548         return retval;
1549 }
1550
1551 COMMAND_HANDLER(stm32f2x_handle_options_read_command)
1552 {
1553         int retval;
1554         struct flash_bank *bank;
1555         struct stm32x_flash_bank *stm32x_info = NULL;
1556
1557         if (CMD_ARGC != 1) {
1558                 command_print(CMD_CTX, "stm32f2x options_read <bank>");
1559                 return ERROR_COMMAND_SYNTAX_ERROR;
1560         }
1561
1562         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1563         if (ERROR_OK != retval)
1564                 return retval;
1565
1566         retval = stm32x_read_options(bank);
1567         if (ERROR_OK != retval)
1568                 return retval;
1569
1570         stm32x_info = bank->driver_priv;
1571         if (stm32x_info->has_extra_options) {
1572                 if (stm32x_info->has_boot_addr) {
1573                         uint32_t boot_addr = stm32x_info->option_bytes.boot_addr;
1574
1575                         command_print(CMD_CTX, "stm32f2x user_options 0x%03X,"
1576                                 " boot_add0 0x%04X, boot_add1 0x%04X",
1577                                 stm32x_info->option_bytes.user_options,
1578                                 boot_addr & 0xffff, (boot_addr & 0xffff0000) >> 16);
1579                         if (stm32x_info->has_optcr2_pcrop) {
1580                                 command_print(CMD_CTX, "stm32f2x optcr2_pcrop 0x%08X",
1581                                                 stm32x_info->option_bytes.optcr2_pcrop);
1582                         }
1583                 } else {
1584                         command_print(CMD_CTX, "stm32f2x user_options 0x%03X",
1585                                 stm32x_info->option_bytes.user_options);
1586                 }
1587         } else {
1588                 command_print(CMD_CTX, "stm32f2x user_options 0x%02X",
1589                         stm32x_info->option_bytes.user_options);
1590
1591         }
1592
1593         return retval;
1594 }
1595
1596 COMMAND_HANDLER(stm32f2x_handle_options_write_command)
1597 {
1598         int retval;
1599         struct flash_bank *bank;
1600         struct stm32x_flash_bank *stm32x_info = NULL;
1601         uint16_t user_options, boot_addr0, boot_addr1, options_mask;
1602
1603         if (CMD_ARGC < 1) {
1604                 command_print(CMD_CTX, "stm32f2x options_write <bank> ...");
1605                 return ERROR_COMMAND_SYNTAX_ERROR;
1606         }
1607
1608         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1609         if (ERROR_OK != retval)
1610                 return retval;
1611
1612         retval = stm32x_read_options(bank);
1613         if (ERROR_OK != retval)
1614                 return retval;
1615
1616         stm32x_info = bank->driver_priv;
1617         if (stm32x_info->has_boot_addr) {
1618                 if (CMD_ARGC != 4) {
1619                         command_print(CMD_CTX, "stm32f2x options_write <bank> <user_options>"
1620                                 " <boot_addr0> <boot_addr1>");
1621                         return ERROR_COMMAND_SYNTAX_ERROR;
1622                 }
1623                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[2], boot_addr0);
1624                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[3], boot_addr1);
1625                 stm32x_info->option_bytes.boot_addr = boot_addr0 | (((uint32_t) boot_addr1) << 16);
1626         } else {
1627                 if (CMD_ARGC != 2) {
1628                         command_print(CMD_CTX, "stm32f2x options_write <bank> <user_options>");
1629                         return ERROR_COMMAND_SYNTAX_ERROR;
1630                 }
1631         }
1632
1633         COMMAND_PARSE_NUMBER(u16, CMD_ARGV[1], user_options);
1634         options_mask = !stm32x_info->has_extra_options ? ~0xfc :
1635                 ~(((0xf00 << (stm32x_info->protection_bits - 12)) | 0xff) & 0xffc);
1636         if (user_options & options_mask) {
1637                 command_print(CMD_CTX, "stm32f2x invalid user_options");
1638                 return ERROR_COMMAND_ARGUMENT_INVALID;
1639         }
1640
1641         stm32x_info->option_bytes.user_options = user_options;
1642
1643         if (stm32x_write_options(bank) != ERROR_OK) {
1644                 command_print(CMD_CTX, "stm32f2x failed to write options");
1645                 return ERROR_OK;
1646         }
1647
1648         /* switching between single- and dual-bank modes requires re-probe */
1649         /* ... and reprogramming of whole flash */
1650         stm32x_info->probed = false;
1651
1652         command_print(CMD_CTX, "stm32f2x write options complete.\n"
1653                                 "INFO: a reset or power cycle is required "
1654                                 "for the new settings to take effect.");
1655         return retval;
1656 }
1657
1658 COMMAND_HANDLER(stm32f2x_handle_optcr2_write_command)
1659 {
1660         int retval;
1661         struct flash_bank *bank;
1662         struct stm32x_flash_bank *stm32x_info = NULL;
1663         uint32_t optcr2_pcrop;
1664
1665         if (CMD_ARGC != 2) {
1666                 command_print(CMD_CTX, "stm32f2x optcr2_write <bank> <optcr2_value>");
1667                 return ERROR_COMMAND_SYNTAX_ERROR;
1668         }
1669
1670         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1671         if (ERROR_OK != retval)
1672                 return retval;
1673
1674         stm32x_info = bank->driver_priv;
1675         if (!stm32x_info->has_optcr2_pcrop) {
1676                 command_print(CMD_CTX, "no optcr2 register");
1677                 return ERROR_COMMAND_ARGUMENT_INVALID;
1678         }
1679
1680         command_print(CMD_CTX, "INFO: To disable PCROP, set PCROP_RDP"
1681                                 " with PCROPi bits STILL SET, then\nlock device and"
1682                                 " finally unlock it. Clears PCROP and mass erases flash.");
1683
1684         retval = stm32x_read_options(bank);
1685         if (ERROR_OK != retval)
1686                 return retval;
1687
1688         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], optcr2_pcrop);
1689         stm32x_info->option_bytes.optcr2_pcrop = optcr2_pcrop;
1690
1691         if (stm32x_write_options(bank) != ERROR_OK) {
1692                 command_print(CMD_CTX, "stm32f2x failed to write options");
1693                 return ERROR_OK;
1694         }
1695
1696         command_print(CMD_CTX, "stm32f2x optcr2_write complete.");
1697         return retval;
1698 }
1699
1700 COMMAND_HANDLER(stm32x_handle_otp_command)
1701 {
1702         if (CMD_ARGC < 2) {
1703                 command_print(CMD_CTX, "stm32x otp <bank> (enable|disable|show)");
1704                 return ERROR_COMMAND_SYNTAX_ERROR;
1705         }
1706
1707         struct flash_bank *bank;
1708         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1709         if (ERROR_OK != retval)
1710                 return retval;
1711         if (stm32x_is_otp(bank)) {
1712                 if (strcmp(CMD_ARGV[1], "enable") == 0) {
1713                         stm32x_otp_enable(bank);
1714                 } else if (strcmp(CMD_ARGV[1], "disable") == 0) {
1715                         stm32x_otp_disable(bank);
1716                 } else if (strcmp(CMD_ARGV[1], "show") == 0) {
1717                         command_print(CMD_CTX,
1718                                 "OTP memory bank #%d is %s for write commands.",
1719                                 bank->bank_number,
1720                                 stm32x_is_otp_unlocked(bank) ? "enabled" : "disabled");
1721                 } else {
1722                         return ERROR_COMMAND_SYNTAX_ERROR;
1723                 }
1724         } else {
1725                 command_print(CMD_CTX, "Failed: not an OTP bank.");
1726         }
1727
1728         return retval;
1729 }
1730
1731 static const struct command_registration stm32x_exec_command_handlers[] = {
1732         {
1733                 .name = "lock",
1734                 .handler = stm32x_handle_lock_command,
1735                 .mode = COMMAND_EXEC,
1736                 .usage = "bank_id",
1737                 .help = "Lock entire flash device.",
1738         },
1739         {
1740                 .name = "unlock",
1741                 .handler = stm32x_handle_unlock_command,
1742                 .mode = COMMAND_EXEC,
1743                 .usage = "bank_id",
1744                 .help = "Unlock entire protected flash device.",
1745         },
1746         {
1747                 .name = "mass_erase",
1748                 .handler = stm32x_handle_mass_erase_command,
1749                 .mode = COMMAND_EXEC,
1750                 .usage = "bank_id",
1751                 .help = "Erase entire flash device.",
1752         },
1753         {
1754                 .name = "options_read",
1755                 .handler = stm32f2x_handle_options_read_command,
1756                 .mode = COMMAND_EXEC,
1757                 .usage = "bank_id",
1758                 .help = "Read and display device option bytes.",
1759         },
1760         {
1761                 .name = "options_write",
1762                 .handler = stm32f2x_handle_options_write_command,
1763                 .mode = COMMAND_EXEC,
1764                 .usage = "bank_id user_options [ boot_add0 boot_add1 ]",
1765                 .help = "Write option bytes",
1766         },
1767         {
1768                 .name = "optcr2_write",
1769                 .handler = stm32f2x_handle_optcr2_write_command,
1770                 .mode = COMMAND_EXEC,
1771                 .usage = "bank_id optcr2",
1772                 .help = "Write optcr2 word",
1773         },
1774         {
1775                 .name = "otp",
1776                 .handler = stm32x_handle_otp_command,
1777                 .mode = COMMAND_EXEC,
1778                 .usage = "bank_id",
1779                 .help = "OTP (One Time Programmable) memory write enable/disable.",
1780         },
1781         COMMAND_REGISTRATION_DONE
1782 };
1783
1784 static const struct command_registration stm32x_command_handlers[] = {
1785         {
1786                 .name = "stm32f2x",
1787                 .mode = COMMAND_ANY,
1788                 .help = "stm32f2x flash command group",
1789                 .usage = "",
1790                 .chain = stm32x_exec_command_handlers,
1791         },
1792         COMMAND_REGISTRATION_DONE
1793 };
1794
1795 const struct flash_driver stm32f2x_flash = {
1796         .name = "stm32f2x",
1797         .commands = stm32x_command_handlers,
1798         .flash_bank_command = stm32x_flash_bank_command,
1799         .erase = stm32x_erase,
1800         .protect = stm32x_protect,
1801         .write = stm32x_write,
1802         .read = default_flash_read,
1803         .probe = stm32x_probe,
1804         .auto_probe = stm32x_auto_probe,
1805         .erase_check = default_flash_blank_check,
1806         .protect_check = stm32x_protect_check,
1807         .info = get_stm32x_info,
1808         .free_driver_priv = default_flash_free_driver_priv,
1809 };