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