stm32f2x: Fix left shift of negative value
[fw/openocd] / src / flash / nor / stm32f2x.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2008 by Spencer Oliver                                  *
6  *   spen@spen-soft.co.uk                                                  *
7  *                                                                         *
8  *   Copyright (C) 2011 Ã˜yvind Harboe                                      *
9  *   oyvind.harboe@zylin.com                                               *
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU General Public License as published by  *
13  *   the Free Software Foundation; either version 2 of the License, or     *
14  *   (at your option) any later version.                                   *
15  *                                                                         *
16  *   This program is distributed in the hope that it will be useful,       *
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
19  *   GNU General Public License for more details.                          *
20  *                                                                         *
21  *   You should have received a copy of the GNU General Public License     *
22  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
23  ***************************************************************************/
24
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #endif
28
29 #include "imp.h"
30 #include <helper/binarybuffer.h>
31 #include <target/algorithm.h>
32 #include <target/armv7m.h>
33
34 /* Regarding performance:
35  *
36  * Short story - it might be best to leave the performance at
37  * current levels.
38  *
39  * You may see a jump in speed if you change to using
40  * 32bit words for the block programming.
41  *
42  * Its a shame you cannot use the double word as its
43  * even faster - but you require external VPP for that mode.
44  *
45  * Having said all that 16bit writes give us the widest vdd
46  * operating range, so may be worth adding a note to that effect.
47  *
48  */
49
50 /* Danger!!!! The STM32F1x and STM32F2x series actually have
51  * quite different flash controllers.
52  *
53  * What's more scary is that the names of the registers and their
54  * addresses are the same, but the actual bits and what they do are
55  * can be very different.
56  *
57  * To reduce testing complexity and dangers of regressions,
58  * a seperate file is used for stm32fx2x.
59  *
60  * Sector sizes in kiBytes:
61  * 1 MiByte part with 4 x 16, 1 x 64, 7 x 128.
62  * 1.5 MiByte part with 4 x 16, 1 x 64, 11 x 128.
63  * 2 MiByte part with 4 x 16, 1 x 64, 7 x 128, 4 x 16, 1 x 64, 7 x 128.
64  * 1 MiByte STM32F42x/43x part with DB1M Option set:
65  *                    4 x 16, 1 x 64, 3 x 128, 4 x 16, 1 x 64, 3 x 128.
66  *
67  * STM32F7[2|3]
68  * 512 kiByte part with 4 x 16, 1 x 64, 3 x 128.
69  *
70  * STM32F7[4|5]
71  * 1 MiByte part with 4 x 32, 1 x 128, 3 x 256.
72  *
73  * STM32F7[6|7]
74  * 1 MiByte part in single bank mode with 4 x 32, 1 x 128, 3 x 256.
75  * 1 MiByte part in dual-bank mode two banks with 4 x 16, 1 x 64, 3 x 128 each.
76  * 2 MiByte part in single-bank mode with 4 x 32, 1 x 128, 7 x 256.
77  * 2 MiByte part in dual-bank mode two banks with 4 x 16, 1 x 64, 7 x 128 each.
78  *
79  * Protection size is sector size.
80  *
81  * Tested with STM3220F-EVAL board.
82  *
83  * STM32F4xx series for reference.
84  *
85  * RM0090
86  * http://www.st.com/web/en/resource/technical/document/reference_manual/DM00031020.pdf
87  *
88  * PM0059
89  * www.st.com/internet/com/TECHNICAL_RESOURCES/TECHNICAL_LITERATURE/
90  * PROGRAMMING_MANUAL/CD00233952.pdf
91  *
92  * STM32F7xx series for reference.
93  *
94  * RM0385
95  * http://www.st.com/web/en/resource/technical/document/reference_manual/DM00124865.pdf
96  *
97  * RM0410
98  * http://www.st.com/resource/en/reference_manual/dm00224583.pdf
99  *
100  * RM0430
101  * http://www.st.com/resource/en/reference_manual/dm00305666.pdf
102  *
103  * RM0431
104  * http://www.st.com/resource/en/reference_manual/dm00305990.pdf
105  *
106  * STM32F1x series - notice that this code was copy, pasted and knocked
107  * into a stm32f2x driver, so in case something has been converted or
108  * bugs haven't been fixed, here are the original manuals:
109  *
110  * RM0008 - Reference manual
111  *
112  * RM0042, the Flash programming manual for low-, medium- high-density and
113  * connectivity line STM32F10x devices
114  *
115  * PM0068, the Flash programming manual for XL-density STM32F10x devices.
116  *
117  */
118
119 /* Erase time can be as high as 1000ms, 10x this and it's toast... */
120 #define FLASH_ERASE_TIMEOUT 10000
121 #define FLASH_WRITE_TIMEOUT 5
122
123 /* Mass erase time can be as high as 32 s in x8 mode. */
124 #define FLASH_MASS_ERASE_TIMEOUT 33000
125
126 #define 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 << 1;
1051                         }
1052                 }
1053         } else {
1054                 /* single-bank */
1055                 setup_bank(bank, 0, flash_size_in_kb, max_sector_size_in_kb);
1056
1057                 /* F413/F423, sectors 14 and 15 share one common protection bit */
1058                 if (device_id == 0x463) {
1059                         for (i = 0; i < num_prot_blocks; i++) {
1060                                 bank->prot_blocks[i].offset = bank->sectors[i].offset;
1061                                 bank->prot_blocks[i].size = bank->sectors[i].size;
1062                         }
1063                         bank->prot_blocks[num_prot_blocks - 1].size <<= 1;
1064                 }
1065         }
1066         bank->num_prot_blocks = num_prot_blocks;
1067         assert((bank->size >> 10) == flash_size_in_kb);
1068
1069         stm32x_info->probed = 1;
1070         return ERROR_OK;
1071 }
1072
1073 static int stm32x_auto_probe(struct flash_bank *bank)
1074 {
1075         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
1076         if (stm32x_info->probed)
1077                 return ERROR_OK;
1078         return stm32x_probe(bank);
1079 }
1080
1081 static int get_stm32x_info(struct flash_bank *bank, char *buf, int buf_size)
1082 {
1083         uint32_t dbgmcu_idcode;
1084
1085         /* read stm32 device id register */
1086         int retval = stm32x_get_device_id(bank, &dbgmcu_idcode);
1087         if (retval != ERROR_OK)
1088                 return retval;
1089
1090         uint16_t device_id = dbgmcu_idcode & 0xfff;
1091         uint16_t rev_id = dbgmcu_idcode >> 16;
1092         const char *device_str;
1093         const char *rev_str = NULL;
1094
1095         switch (device_id) {
1096         case 0x411:
1097                 device_str = "STM32F2xx";
1098
1099                 switch (rev_id) {
1100                 case 0x1000:
1101                         rev_str = "A";
1102                         break;
1103
1104                 case 0x2000:
1105                         rev_str = "B";
1106                         break;
1107
1108                 case 0x1001:
1109                         rev_str = "Z";
1110                         break;
1111
1112                 case 0x2001:
1113                         rev_str = "Y";
1114                         break;
1115
1116                 case 0x2003:
1117                         rev_str = "X";
1118                         break;
1119
1120                 case 0x2007:
1121                         rev_str = "1";
1122                         break;
1123
1124                 case 0x200F:
1125                         rev_str = "V";
1126                         break;
1127
1128                 case 0x201F:
1129                         rev_str = "2";
1130                         break;
1131                 }
1132                 break;
1133
1134         case 0x413:
1135         case 0x419:
1136         case 0x434:
1137                 device_str = "STM32F4xx";
1138
1139                 switch (rev_id) {
1140                 case 0x1000:
1141                         rev_str = "A";
1142                         break;
1143
1144                 case 0x1001:
1145                         rev_str = "Z";
1146                         break;
1147
1148                 case 0x1003:
1149                         rev_str = "Y";
1150                         break;
1151
1152                 case 0x1007:
1153                         rev_str = "1";
1154                         break;
1155
1156                 case 0x2001:
1157                         rev_str = "3";
1158                         break;
1159                 }
1160                 break;
1161
1162         case 0x421:
1163                 device_str = "STM32F446";
1164
1165                 switch (rev_id) {
1166                 case 0x1000:
1167                         rev_str = "A";
1168                         break;
1169                 }
1170                 break;
1171
1172         case 0x423:
1173         case 0x431:
1174         case 0x433:
1175         case 0x458:
1176         case 0x441:
1177                 device_str = "STM32F4xx (Low Power)";
1178
1179                 switch (rev_id) {
1180                 case 0x1000:
1181                         rev_str = "A";
1182                         break;
1183
1184                 case 0x1001:
1185                         rev_str = "Z";
1186                         break;
1187
1188                 case 0x2000:
1189                         rev_str = "B";
1190                         break;
1191
1192                 case 0x3000:
1193                         rev_str = "C";
1194                         break;
1195                 }
1196                 break;
1197
1198         case 0x449:
1199                 device_str = "STM32F7[4|5]x";
1200
1201                 switch (rev_id) {
1202                 case 0x1000:
1203                         rev_str = "A";
1204                         break;
1205
1206                 case 0x1001:
1207                         rev_str = "Z";
1208                         break;
1209                 }
1210                 break;
1211
1212         case 0x451:
1213                 device_str = "STM32F7[6|7]x";
1214
1215                 switch (rev_id) {
1216                 case 0x1000:
1217                         rev_str = "A";
1218                         break;
1219                 }
1220                 break;
1221
1222         case 0x452:
1223                 device_str = "STM32F7[2|3]x";
1224
1225                 switch (rev_id) {
1226                 case 0x1000:
1227                         rev_str = "A";
1228                         break;
1229                 }
1230                 break;
1231
1232         case 0x463:
1233                 device_str = "STM32F4[1|2]3";
1234
1235                 switch (rev_id) {
1236                 case 0x1000:
1237                         rev_str = "A";
1238                         break;
1239                 }
1240                 break;
1241
1242         default:
1243                 snprintf(buf, buf_size, "Cannot identify target as a STM32F2/4/7\n");
1244                 return ERROR_FAIL;
1245         }
1246
1247         if (rev_str != NULL)
1248                 snprintf(buf, buf_size, "%s - Rev: %s", device_str, rev_str);
1249         else
1250                 snprintf(buf, buf_size, "%s - Rev: unknown (0x%04x)", device_str, rev_id);
1251
1252         return ERROR_OK;
1253 }
1254
1255 COMMAND_HANDLER(stm32x_handle_lock_command)
1256 {
1257         struct target *target = NULL;
1258         struct stm32x_flash_bank *stm32x_info = NULL;
1259
1260         if (CMD_ARGC < 1)
1261                 return ERROR_COMMAND_SYNTAX_ERROR;
1262
1263         struct flash_bank *bank;
1264         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1265         if (ERROR_OK != retval)
1266                 return retval;
1267
1268         stm32x_info = bank->driver_priv;
1269         target = bank->target;
1270
1271         if (target->state != TARGET_HALTED) {
1272                 LOG_INFO("Target not halted");
1273                 /* return ERROR_TARGET_NOT_HALTED; */
1274         }
1275
1276         if (stm32x_read_options(bank) != ERROR_OK) {
1277                 command_print(CMD_CTX, "%s failed to read options", bank->driver->name);
1278                 return ERROR_OK;
1279         }
1280
1281         /* set readout protection */
1282         stm32x_info->option_bytes.RDP = 0;
1283
1284         if (stm32x_write_options(bank) != ERROR_OK) {
1285                 command_print(CMD_CTX, "%s failed to lock device", bank->driver->name);
1286                 return ERROR_OK;
1287         }
1288
1289         command_print(CMD_CTX, "%s locked", bank->driver->name);
1290
1291         return ERROR_OK;
1292 }
1293
1294 COMMAND_HANDLER(stm32x_handle_unlock_command)
1295 {
1296         struct target *target = NULL;
1297         struct stm32x_flash_bank *stm32x_info = NULL;
1298
1299         if (CMD_ARGC < 1)
1300                 return ERROR_COMMAND_SYNTAX_ERROR;
1301
1302         struct flash_bank *bank;
1303         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1304         if (ERROR_OK != retval)
1305                 return retval;
1306
1307         stm32x_info = bank->driver_priv;
1308         target = bank->target;
1309
1310         if (target->state != TARGET_HALTED) {
1311                 LOG_INFO("Target not halted");
1312                 /* return ERROR_TARGET_NOT_HALTED; */
1313         }
1314
1315         if (stm32x_read_options(bank) != ERROR_OK) {
1316                 command_print(CMD_CTX, "%s failed to read options", bank->driver->name);
1317                 return ERROR_OK;
1318         }
1319
1320         /* clear readout protection and complementary option bytes
1321          * this will also force a device unlock if set */
1322         stm32x_info->option_bytes.RDP = 0xAA;
1323         if (stm32x_info->has_optcr2_pcrop) {
1324                 stm32x_info->option_bytes.optcr2_pcrop = OPTCR2_PCROP_RDP | (~1U << bank->num_sectors);
1325         }
1326
1327         if (stm32x_write_options(bank) != ERROR_OK) {
1328                 command_print(CMD_CTX, "%s failed to unlock device", bank->driver->name);
1329                 return ERROR_OK;
1330         }
1331
1332         command_print(CMD_CTX, "%s unlocked.\n"
1333                         "INFO: a reset or power cycle is required "
1334                         "for the new settings to take effect.", bank->driver->name);
1335
1336         return ERROR_OK;
1337 }
1338
1339 static int stm32x_mass_erase(struct flash_bank *bank)
1340 {
1341         int retval;
1342         uint32_t flash_mer;
1343         struct target *target = bank->target;
1344         struct stm32x_flash_bank *stm32x_info = NULL;
1345
1346         if (target->state != TARGET_HALTED) {
1347                 LOG_ERROR("Target not halted");
1348                 return ERROR_TARGET_NOT_HALTED;
1349         }
1350
1351         stm32x_info = bank->driver_priv;
1352
1353         retval = stm32x_unlock_reg(target);
1354         if (retval != ERROR_OK)
1355                 return retval;
1356
1357         /* mass erase flash memory */
1358         if (stm32x_info->has_large_mem)
1359                 flash_mer = FLASH_MER | FLASH_MER1;
1360         else
1361                 flash_mer = FLASH_MER;
1362
1363         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), flash_mer);
1364         if (retval != ERROR_OK)
1365                 return retval;
1366         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
1367                 flash_mer | FLASH_STRT);
1368         if (retval != ERROR_OK)
1369                 return retval;
1370
1371         retval = stm32x_wait_status_busy(bank, FLASH_MASS_ERASE_TIMEOUT);
1372         if (retval != ERROR_OK)
1373                 return retval;
1374
1375         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
1376         if (retval != ERROR_OK)
1377                 return retval;
1378
1379         return ERROR_OK;
1380 }
1381
1382 COMMAND_HANDLER(stm32x_handle_mass_erase_command)
1383 {
1384         int i;
1385
1386         if (CMD_ARGC < 1) {
1387                 command_print(CMD_CTX, "stm32x mass_erase <bank>");
1388                 return ERROR_COMMAND_SYNTAX_ERROR;
1389         }
1390
1391         struct flash_bank *bank;
1392         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1393         if (ERROR_OK != retval)
1394                 return retval;
1395
1396         retval = stm32x_mass_erase(bank);
1397         if (retval == ERROR_OK) {
1398                 /* set all sectors as erased */
1399                 for (i = 0; i < bank->num_sectors; i++)
1400                         bank->sectors[i].is_erased = 1;
1401
1402                 command_print(CMD_CTX, "stm32x mass erase complete");
1403         } else {
1404                 command_print(CMD_CTX, "stm32x mass erase failed");
1405         }
1406
1407         return retval;
1408 }
1409
1410 COMMAND_HANDLER(stm32f2x_handle_options_read_command)
1411 {
1412         int retval;
1413         struct flash_bank *bank;
1414         struct stm32x_flash_bank *stm32x_info = NULL;
1415
1416         if (CMD_ARGC != 1) {
1417                 command_print(CMD_CTX, "stm32f2x options_read <bank>");
1418                 return ERROR_COMMAND_SYNTAX_ERROR;
1419         }
1420
1421         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1422         if (ERROR_OK != retval)
1423                 return retval;
1424
1425         retval = stm32x_read_options(bank);
1426         if (ERROR_OK != retval)
1427                 return retval;
1428
1429         stm32x_info = bank->driver_priv;
1430         if (stm32x_info->has_extra_options) {
1431                 if (stm32x_info->has_boot_addr) {
1432                         uint32_t boot_addr = stm32x_info->option_bytes.boot_addr;
1433
1434                         command_print(CMD_CTX, "stm32f2x user_options 0x%03X,"
1435                                 " boot_add0 0x%04X, boot_add1 0x%04X",
1436                                 stm32x_info->option_bytes.user_options,
1437                                 boot_addr & 0xffff, (boot_addr & 0xffff0000) >> 16);
1438                         if (stm32x_info->has_optcr2_pcrop) {
1439                                 command_print(CMD_CTX, "stm32f2x optcr2_pcrop 0x%08X",
1440                                                 stm32x_info->option_bytes.optcr2_pcrop);
1441                         }
1442                 } else {
1443                         command_print(CMD_CTX, "stm32f2x user_options 0x%03X",
1444                                 stm32x_info->option_bytes.user_options);
1445                 }
1446         } else {
1447                 command_print(CMD_CTX, "stm32f2x user_options 0x%02X",
1448                         stm32x_info->option_bytes.user_options);
1449
1450         }
1451
1452         return retval;
1453 }
1454
1455 COMMAND_HANDLER(stm32f2x_handle_options_write_command)
1456 {
1457         int retval;
1458         struct flash_bank *bank;
1459         struct stm32x_flash_bank *stm32x_info = NULL;
1460         uint16_t user_options, boot_addr0, boot_addr1, options_mask;
1461
1462         if (CMD_ARGC < 1) {
1463                 command_print(CMD_CTX, "stm32f2x options_write <bank> ...");
1464                 return ERROR_COMMAND_SYNTAX_ERROR;
1465         }
1466
1467         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1468         if (ERROR_OK != retval)
1469                 return retval;
1470
1471         retval = stm32x_read_options(bank);
1472         if (ERROR_OK != retval)
1473                 return retval;
1474
1475         stm32x_info = bank->driver_priv;
1476         if (stm32x_info->has_boot_addr) {
1477                 if (CMD_ARGC != 4) {
1478                         command_print(CMD_CTX, "stm32f2x options_write <bank> <user_options>"
1479                                 " <boot_addr0> <boot_addr1>");
1480                         return ERROR_COMMAND_SYNTAX_ERROR;
1481                 }
1482                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[2], boot_addr0);
1483                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[3], boot_addr1);
1484                 stm32x_info->option_bytes.boot_addr = boot_addr0 | (((uint32_t) boot_addr1) << 16);
1485         } else {
1486                 if (CMD_ARGC != 2) {
1487                         command_print(CMD_CTX, "stm32f2x options_write <bank> <user_options>");
1488                         return ERROR_COMMAND_SYNTAX_ERROR;
1489                 }
1490         }
1491
1492         COMMAND_PARSE_NUMBER(u16, CMD_ARGV[1], user_options);
1493         options_mask = !stm32x_info->has_extra_options ? ~0xfc :
1494                 ~(((0xf00 << (stm32x_info->protection_bits - 12)) | 0xff) & 0xffc);
1495         if (user_options & options_mask) {
1496                 command_print(CMD_CTX, "stm32f2x invalid user_options");
1497                 return ERROR_COMMAND_ARGUMENT_INVALID;
1498         }
1499
1500         stm32x_info->option_bytes.user_options = user_options;
1501
1502         if (stm32x_write_options(bank) != ERROR_OK) {
1503                 command_print(CMD_CTX, "stm32f2x failed to write options");
1504                 return ERROR_OK;
1505         }
1506
1507         /* switching between single- and dual-bank modes requires re-probe */
1508         /* ... and reprogramming of whole flash */
1509         stm32x_info->probed = 0;
1510
1511         command_print(CMD_CTX, "stm32f2x write options complete.\n"
1512                                 "INFO: a reset or power cycle is required "
1513                                 "for the new settings to take effect.");
1514         return retval;
1515 }
1516
1517 COMMAND_HANDLER(stm32f2x_handle_optcr2_write_command)
1518 {
1519         int retval;
1520         struct flash_bank *bank;
1521         struct stm32x_flash_bank *stm32x_info = NULL;
1522         uint32_t optcr2_pcrop;
1523
1524         if (CMD_ARGC != 2) {
1525                 command_print(CMD_CTX, "stm32f2x optcr2_write <bank> <optcr2_value>");
1526                 return ERROR_COMMAND_SYNTAX_ERROR;
1527         }
1528
1529         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1530         if (ERROR_OK != retval)
1531                 return retval;
1532
1533         stm32x_info = bank->driver_priv;
1534         if (!stm32x_info->has_optcr2_pcrop) {
1535                 command_print(CMD_CTX, "no optcr2 register");
1536                 return ERROR_COMMAND_ARGUMENT_INVALID;
1537         }
1538
1539         command_print(CMD_CTX, "INFO: To disable PCROP, set PCROP_RDP"
1540                                 " with PCROPi bits STILL SET, then\nlock device and"
1541                                 " finally unlock it. Clears PCROP and mass erases flash.");
1542
1543         retval = stm32x_read_options(bank);
1544         if (ERROR_OK != retval)
1545                 return retval;
1546
1547         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], optcr2_pcrop);
1548         stm32x_info->option_bytes.optcr2_pcrop = optcr2_pcrop;
1549
1550         if (stm32x_write_options(bank) != ERROR_OK) {
1551                 command_print(CMD_CTX, "stm32f2x failed to write options");
1552                 return ERROR_OK;
1553         }
1554
1555         command_print(CMD_CTX, "stm32f2x optcr2_write complete.");
1556         return retval;
1557 }
1558
1559 static const struct command_registration stm32x_exec_command_handlers[] = {
1560         {
1561                 .name = "lock",
1562                 .handler = stm32x_handle_lock_command,
1563                 .mode = COMMAND_EXEC,
1564                 .usage = "bank_id",
1565                 .help = "Lock entire flash device.",
1566         },
1567         {
1568                 .name = "unlock",
1569                 .handler = stm32x_handle_unlock_command,
1570                 .mode = COMMAND_EXEC,
1571                 .usage = "bank_id",
1572                 .help = "Unlock entire protected flash device.",
1573         },
1574         {
1575                 .name = "mass_erase",
1576                 .handler = stm32x_handle_mass_erase_command,
1577                 .mode = COMMAND_EXEC,
1578                 .usage = "bank_id",
1579                 .help = "Erase entire flash device.",
1580         },
1581         {
1582                 .name = "options_read",
1583                 .handler = stm32f2x_handle_options_read_command,
1584                 .mode = COMMAND_EXEC,
1585                 .usage = "bank_id",
1586                 .help = "Read and display device option bytes.",
1587         },
1588         {
1589                 .name = "options_write",
1590                 .handler = stm32f2x_handle_options_write_command,
1591                 .mode = COMMAND_EXEC,
1592                 .usage = "bank_id user_options [ boot_add0 boot_add1 ]",
1593                 .help = "Write option bytes",
1594         },
1595         {
1596                 .name = "optcr2_write",
1597                 .handler = stm32f2x_handle_optcr2_write_command,
1598                 .mode = COMMAND_EXEC,
1599                 .usage = "bank_id optcr2",
1600                 .help = "Write optcr2 word",
1601         },
1602
1603         COMMAND_REGISTRATION_DONE
1604 };
1605
1606 static const struct command_registration stm32x_command_handlers[] = {
1607         {
1608                 .name = "stm32f2x",
1609                 .mode = COMMAND_ANY,
1610                 .help = "stm32f2x flash command group",
1611                 .usage = "",
1612                 .chain = stm32x_exec_command_handlers,
1613         },
1614         COMMAND_REGISTRATION_DONE
1615 };
1616
1617 struct flash_driver stm32f2x_flash = {
1618         .name = "stm32f2x",
1619         .commands = stm32x_command_handlers,
1620         .flash_bank_command = stm32x_flash_bank_command,
1621         .erase = stm32x_erase,
1622         .protect = stm32x_protect,
1623         .write = stm32x_write,
1624         .read = default_flash_read,
1625         .probe = stm32x_probe,
1626         .auto_probe = stm32x_auto_probe,
1627         .erase_check = default_flash_blank_check,
1628         .protect_check = stm32x_protect_check,
1629         .info = get_stm32x_info,
1630 };