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