Remove FSF address from GPL notices
[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  * 2 MiByte part with 4 x 16, 1 x 64, 7 x 128, 4 x 16, 1 x 64, 7 x 128.
63  * 1 MiByte STM32F42x/43x part with DB1M Option set:
64  *                    4 x 16, 1 x 64, 3 x 128, 4 x 16, 1 x 64, 3 x 128.
65  *
66  * STM32F7
67  * 1 MiByte part with 4 x 32, 1 x 128, 3 x 256.
68  *
69  * Protection size is sector size.
70  *
71  * Tested with STM3220F-EVAL board.
72  *
73  * STM32F4xx series for reference.
74  *
75  * RM0090
76  * http://www.st.com/web/en/resource/technical/document/reference_manual/DM00031020.pdf
77  *
78  * PM0059
79  * www.st.com/internet/com/TECHNICAL_RESOURCES/TECHNICAL_LITERATURE/
80  * PROGRAMMING_MANUAL/CD00233952.pdf
81  *
82  * STM32F7xx series for reference.
83  *
84  * RM0385
85  * http://www.st.com/web/en/resource/technical/document/reference_manual/DM00124865.pdf
86  *
87  * STM32F1x series - notice that this code was copy, pasted and knocked
88  * into a stm32f2x driver, so in case something has been converted or
89  * bugs haven't been fixed, here are the original manuals:
90  *
91  * RM0008 - Reference manual
92  *
93  * RM0042, the Flash programming manual for low-, medium- high-density and
94  * connectivity line STM32F10x devices
95  *
96  * PM0068, the Flash programming manual for XL-density STM32F10x devices.
97  *
98  */
99
100 /* Erase time can be as high as 1000ms, 10x this and it's toast... */
101 #define FLASH_ERASE_TIMEOUT 10000
102 #define FLASH_WRITE_TIMEOUT 5
103
104 #define STM32_FLASH_BASE    0x40023c00
105 #define STM32_FLASH_ACR     0x40023c00
106 #define STM32_FLASH_KEYR    0x40023c04
107 #define STM32_FLASH_OPTKEYR 0x40023c08
108 #define STM32_FLASH_SR      0x40023c0C
109 #define STM32_FLASH_CR      0x40023c10
110 #define STM32_FLASH_OPTCR   0x40023c14
111 #define STM32_FLASH_OPTCR1  0x40023c18
112
113 /* FLASH_CR register bits */
114
115 #define FLASH_PG       (1 << 0)
116 #define FLASH_SER      (1 << 1)
117 #define FLASH_MER      (1 << 2)
118 #define FLASH_MER1     (1 << 15)
119 #define FLASH_STRT     (1 << 16)
120 #define FLASH_PSIZE_8  (0 << 8)
121 #define FLASH_PSIZE_16 (1 << 8)
122 #define FLASH_PSIZE_32 (2 << 8)
123 #define FLASH_PSIZE_64 (3 << 8)
124 /* The sector number encoding is not straight binary for dual bank flash.
125  * Warning: evaluates the argument multiple times */
126 #define FLASH_SNB(a)   ((((a) >= 12) ? 0x10 | ((a) - 12) : (a)) << 3)
127 #define FLASH_LOCK     (1 << 31)
128
129 /* FLASH_SR register bits */
130
131 #define FLASH_BSY      (1 << 16)
132 #define FLASH_PGSERR   (1 << 7) /* Programming sequence error */
133 #define FLASH_PGPERR   (1 << 6) /* Programming parallelism error */
134 #define FLASH_PGAERR   (1 << 5) /* Programming alignment error */
135 #define FLASH_WRPERR   (1 << 4) /* Write protection error */
136 #define FLASH_OPERR    (1 << 1) /* Operation error */
137
138 #define FLASH_ERROR (FLASH_PGSERR | FLASH_PGPERR | FLASH_PGAERR | FLASH_WRPERR | FLASH_OPERR)
139
140 /* STM32_FLASH_OPTCR register bits */
141
142 #define OPT_LOCK      (1 << 0)
143 #define OPT_START     (1 << 1)
144
145 /* STM32_FLASH_OBR bit definitions (reading) */
146
147 #define OPT_ERROR      0
148 #define OPT_READOUT    1
149 #define OPT_RDWDGSW    2
150 #define OPT_RDRSTSTOP  3
151 #define OPT_RDRSTSTDBY 4
152 #define OPT_BFB2       5        /* dual flash bank only */
153 #define OPT_DB1M       14       /* 1 MiB devices dual flash bank option */
154
155 /* register unlock keys */
156
157 #define KEY1           0x45670123
158 #define KEY2           0xCDEF89AB
159
160 /* option register unlock key */
161 #define OPTKEY1        0x08192A3B
162 #define OPTKEY2        0x4C5D6E7F
163
164 struct stm32x_options {
165         uint8_t RDP;
166         uint8_t user_options;
167         uint32_t protection;
168 };
169
170 struct stm32x_flash_bank {
171         struct stm32x_options option_bytes;
172         int probed;
173         bool has_large_mem;             /* stm32f42x/stm32f43x family */
174         uint32_t user_bank_size;
175 };
176
177 /* flash bank stm32x <base> <size> 0 0 <target#>
178  */
179 FLASH_BANK_COMMAND_HANDLER(stm32x_flash_bank_command)
180 {
181         struct stm32x_flash_bank *stm32x_info;
182
183         if (CMD_ARGC < 6)
184                 return ERROR_COMMAND_SYNTAX_ERROR;
185
186         stm32x_info = malloc(sizeof(struct stm32x_flash_bank));
187         bank->driver_priv = stm32x_info;
188
189         stm32x_info->probed = 0;
190         stm32x_info->user_bank_size = bank->size;
191
192         return ERROR_OK;
193 }
194
195 static inline int stm32x_get_flash_reg(struct flash_bank *bank, uint32_t reg)
196 {
197         return reg;
198 }
199
200 static inline int stm32x_get_flash_status(struct flash_bank *bank, uint32_t *status)
201 {
202         struct target *target = bank->target;
203         return target_read_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR), status);
204 }
205
206 static int stm32x_wait_status_busy(struct flash_bank *bank, int timeout)
207 {
208         struct target *target = bank->target;
209         uint32_t status;
210         int retval = ERROR_OK;
211
212         /* wait for busy to clear */
213         for (;;) {
214                 retval = stm32x_get_flash_status(bank, &status);
215                 if (retval != ERROR_OK)
216                         return retval;
217                 LOG_DEBUG("status: 0x%" PRIx32 "", status);
218                 if ((status & FLASH_BSY) == 0)
219                         break;
220                 if (timeout-- <= 0) {
221                         LOG_ERROR("timed out waiting for flash");
222                         return ERROR_FAIL;
223                 }
224                 alive_sleep(1);
225         }
226
227
228         if (status & FLASH_WRPERR) {
229                 LOG_ERROR("stm32x device protected");
230                 retval = ERROR_FAIL;
231         }
232
233         /* Clear but report errors */
234         if (status & FLASH_ERROR) {
235                 /* If this operation fails, we ignore it and report the original
236                  * retval
237                  */
238                 target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR),
239                                 status & FLASH_ERROR);
240         }
241         return retval;
242 }
243
244 static int stm32x_unlock_reg(struct target *target)
245 {
246         uint32_t ctrl;
247
248         /* first check if not already unlocked
249          * otherwise writing on STM32_FLASH_KEYR will fail
250          */
251         int retval = target_read_u32(target, STM32_FLASH_CR, &ctrl);
252         if (retval != ERROR_OK)
253                 return retval;
254
255         if ((ctrl & FLASH_LOCK) == 0)
256                 return ERROR_OK;
257
258         /* unlock flash registers */
259         retval = target_write_u32(target, STM32_FLASH_KEYR, KEY1);
260         if (retval != ERROR_OK)
261                 return retval;
262
263         retval = target_write_u32(target, STM32_FLASH_KEYR, KEY2);
264         if (retval != ERROR_OK)
265                 return retval;
266
267         retval = target_read_u32(target, STM32_FLASH_CR, &ctrl);
268         if (retval != ERROR_OK)
269                 return retval;
270
271         if (ctrl & FLASH_LOCK) {
272                 LOG_ERROR("flash not unlocked STM32_FLASH_CR: %" PRIx32, ctrl);
273                 return ERROR_TARGET_FAILURE;
274         }
275
276         return ERROR_OK;
277 }
278
279 static int stm32x_unlock_option_reg(struct target *target)
280 {
281         uint32_t ctrl;
282
283         int retval = target_read_u32(target, STM32_FLASH_OPTCR, &ctrl);
284         if (retval != ERROR_OK)
285                 return retval;
286
287         if ((ctrl & OPT_LOCK) == 0)
288                 return ERROR_OK;
289
290         /* unlock option registers */
291         retval = target_write_u32(target, STM32_FLASH_OPTKEYR, OPTKEY1);
292         if (retval != ERROR_OK)
293                 return retval;
294
295         retval = target_write_u32(target, STM32_FLASH_OPTKEYR, OPTKEY2);
296         if (retval != ERROR_OK)
297                 return retval;
298
299         retval = target_read_u32(target, STM32_FLASH_OPTCR, &ctrl);
300         if (retval != ERROR_OK)
301                 return retval;
302
303         if (ctrl & OPT_LOCK) {
304                 LOG_ERROR("options not unlocked STM32_FLASH_OPTCR: %" PRIx32, ctrl);
305                 return ERROR_TARGET_FAILURE;
306         }
307
308         return ERROR_OK;
309 }
310
311 static int stm32x_read_options(struct flash_bank *bank)
312 {
313         uint32_t optiondata;
314         struct stm32x_flash_bank *stm32x_info = NULL;
315         struct target *target = bank->target;
316
317         stm32x_info = bank->driver_priv;
318
319         /* read current option bytes */
320         int retval = target_read_u32(target, STM32_FLASH_OPTCR, &optiondata);
321         if (retval != ERROR_OK)
322                 return retval;
323
324         stm32x_info->option_bytes.user_options = optiondata & 0xec;
325         stm32x_info->option_bytes.RDP = (optiondata >> 8) & 0xff;
326         stm32x_info->option_bytes.protection = (optiondata >> 16) & 0xfff;
327
328         if (stm32x_info->has_large_mem) {
329
330                 retval = target_read_u32(target, STM32_FLASH_OPTCR1, &optiondata);
331                 if (retval != ERROR_OK)
332                         return retval;
333
334                 /* append protection bits */
335                 stm32x_info->option_bytes.protection |= (optiondata >> 4) & 0x00fff000;
336         }
337
338         if (stm32x_info->option_bytes.RDP != 0xAA)
339                 LOG_INFO("Device Security Bit Set");
340
341         return ERROR_OK;
342 }
343
344 static int stm32x_write_options(struct flash_bank *bank)
345 {
346         struct stm32x_flash_bank *stm32x_info = NULL;
347         struct target *target = bank->target;
348         uint32_t optiondata;
349
350         stm32x_info = bank->driver_priv;
351
352         int retval = stm32x_unlock_option_reg(target);
353         if (retval != ERROR_OK)
354                 return retval;
355
356         /* rebuild option data */
357         optiondata = stm32x_info->option_bytes.user_options;
358         optiondata |= stm32x_info->option_bytes.RDP << 8;
359         optiondata |= (stm32x_info->option_bytes.protection & 0x0fff) << 16;
360
361         /* program options */
362         retval = target_write_u32(target, STM32_FLASH_OPTCR, optiondata);
363         if (retval != ERROR_OK)
364                 return retval;
365
366         if (stm32x_info->has_large_mem) {
367
368                 uint32_t optiondata2 = 0;
369                 optiondata2 |= (stm32x_info->option_bytes.protection & 0x00fff000) << 4;
370                 retval = target_write_u32(target, STM32_FLASH_OPTCR1, optiondata2);
371                 if (retval != ERROR_OK)
372                         return retval;
373         }
374
375         /* start programming cycle */
376         retval = target_write_u32(target, STM32_FLASH_OPTCR, optiondata | OPT_START);
377         if (retval != ERROR_OK)
378                 return retval;
379
380         /* wait for completion */
381         retval = stm32x_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
382         if (retval != ERROR_OK)
383                 return retval;
384
385         /* relock registers */
386         retval = target_write_u32(target, STM32_FLASH_OPTCR, optiondata | OPT_LOCK);
387         if (retval != ERROR_OK)
388                 return retval;
389
390         return ERROR_OK;
391 }
392
393 static int stm32x_protect_check(struct flash_bank *bank)
394 {
395         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
396
397         /* read write protection settings */
398         int retval = stm32x_read_options(bank);
399         if (retval != ERROR_OK) {
400                 LOG_DEBUG("unable to read option bytes");
401                 return retval;
402         }
403
404         for (int i = 0; i < bank->num_sectors; i++) {
405                 if (stm32x_info->option_bytes.protection & (1 << i))
406                         bank->sectors[i].is_protected = 0;
407                 else
408                         bank->sectors[i].is_protected = 1;
409         }
410
411         return ERROR_OK;
412 }
413
414 static int stm32x_erase(struct flash_bank *bank, int first, int last)
415 {
416         struct target *target = bank->target;
417         int i;
418
419         assert(first < bank->num_sectors);
420         assert(last < bank->num_sectors);
421
422         if (bank->target->state != TARGET_HALTED) {
423                 LOG_ERROR("Target not halted");
424                 return ERROR_TARGET_NOT_HALTED;
425         }
426
427         int retval;
428         retval = stm32x_unlock_reg(target);
429         if (retval != ERROR_OK)
430                 return retval;
431
432         /*
433         Sector Erase
434         To erase a sector, follow the procedure below:
435         1. Check that no Flash memory operation is ongoing by checking the BSY bit in the
436           FLASH_SR register
437         2. Set the SER bit and select the sector
438           you wish to erase (SNB) in the FLASH_CR register
439         3. Set the STRT bit in the FLASH_CR register
440         4. Wait for the BSY bit to be cleared
441          */
442
443         for (i = first; i <= last; i++) {
444                 retval = target_write_u32(target,
445                                 stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_SER | FLASH_SNB(i) | FLASH_STRT);
446                 if (retval != ERROR_OK)
447                         return retval;
448
449                 retval = stm32x_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
450                 if (retval != ERROR_OK)
451                         return retval;
452
453                 bank->sectors[i].is_erased = 1;
454         }
455
456         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
457         if (retval != ERROR_OK)
458                 return retval;
459
460         return ERROR_OK;
461 }
462
463 static int stm32x_protect(struct flash_bank *bank, int set, int first, int last)
464 {
465         struct target *target = bank->target;
466         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
467
468         if (target->state != TARGET_HALTED) {
469                 LOG_ERROR("Target not halted");
470                 return ERROR_TARGET_NOT_HALTED;
471         }
472
473         /* read protection settings */
474         int retval = stm32x_read_options(bank);
475         if (retval != ERROR_OK) {
476                 LOG_DEBUG("unable to read option bytes");
477                 return retval;
478         }
479
480         for (int i = first; i <= last; i++) {
481
482                 if (set)
483                         stm32x_info->option_bytes.protection &= ~(1 << i);
484                 else
485                         stm32x_info->option_bytes.protection |= (1 << i);
486         }
487
488         retval = stm32x_write_options(bank);
489         if (retval != ERROR_OK)
490                 return retval;
491
492         return ERROR_OK;
493 }
494
495 static int stm32x_write_block(struct flash_bank *bank, const uint8_t *buffer,
496                 uint32_t offset, uint32_t count)
497 {
498         struct target *target = bank->target;
499         uint32_t buffer_size = 16384;
500         struct working_area *write_algorithm;
501         struct working_area *source;
502         uint32_t address = bank->base + offset;
503         struct reg_param reg_params[5];
504         struct armv7m_algorithm armv7m_info;
505         int retval = ERROR_OK;
506
507         /* see contrib/loaders/flash/stm32f2x.S for src */
508
509         static const uint8_t stm32x_flash_write_code[] = {
510                                                                         /* wait_fifo: */
511                 0xD0, 0xF8, 0x00, 0x80,         /* ldr          r8, [r0, #0] */
512                 0xB8, 0xF1, 0x00, 0x0F,         /* cmp          r8, #0 */
513                 0x1A, 0xD0,                                     /* beq          exit */
514                 0x47, 0x68,                                     /* ldr          r7, [r0, #4] */
515                 0x47, 0x45,                                     /* cmp          r7, r8 */
516                 0xF7, 0xD0,                                     /* beq          wait_fifo */
517
518                 0xDF, 0xF8, 0x34, 0x60,         /* ldr          r6, STM32_PROG16 */
519                 0x26, 0x61,                                     /* str          r6, [r4, #STM32_FLASH_CR_OFFSET] */
520                 0x37, 0xF8, 0x02, 0x6B,         /* ldrh         r6, [r7], #0x02 */
521                 0x22, 0xF8, 0x02, 0x6B,         /* strh         r6, [r2], #0x02 */
522                 0xBF, 0xF3, 0x4F, 0x8F,         /* dsb          sy */
523                                                                         /* busy: */
524                 0xE6, 0x68,                                     /* ldr          r6, [r4, #STM32_FLASH_SR_OFFSET] */
525                 0x16, 0xF4, 0x80, 0x3F,         /* tst          r6, #0x10000 */
526                 0xFB, 0xD1,                                     /* bne          busy */
527                 0x16, 0xF0, 0xF0, 0x0F,         /* tst          r6, #0xf0 */
528                 0x07, 0xD1,                                     /* bne          error */
529
530                 0x8F, 0x42,                                     /* cmp          r7, r1 */
531                 0x28, 0xBF,                                     /* it           cs */
532                 0x00, 0xF1, 0x08, 0x07,         /* addcs        r7, r0, #8 */
533                 0x47, 0x60,                                     /* str          r7, [r0, #4] */
534                 0x01, 0x3B,                                     /* subs         r3, r3, #1 */
535                 0x13, 0xB1,                                     /* cbz          r3, exit */
536                 0xDF, 0xE7,                                     /* b            wait_fifo */
537                                                                         /* error: */
538                 0x00, 0x21,                                     /* movs         r1, #0 */
539                 0x41, 0x60,                                     /* str          r1, [r0, #4] */
540                                                                         /* exit: */
541                 0x30, 0x46,                                     /* mov          r0, r6 */
542                 0x00, 0xBE,                                     /* bkpt         #0x00 */
543
544                 /* <STM32_PROG16>: */
545                 0x01, 0x01, 0x00, 0x00,         /* .word        0x00000101 */
546         };
547
548         if (target_alloc_working_area(target, sizeof(stm32x_flash_write_code),
549                         &write_algorithm) != ERROR_OK) {
550                 LOG_WARNING("no working area available, can't do block memory writes");
551                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
552         }
553
554         retval = target_write_buffer(target, write_algorithm->address,
555                         sizeof(stm32x_flash_write_code),
556                         stm32x_flash_write_code);
557         if (retval != ERROR_OK)
558                 return retval;
559
560         /* memory buffer */
561         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) {
562                 buffer_size /= 2;
563                 if (buffer_size <= 256) {
564                         /* we already allocated the writing code, but failed to get a
565                          * buffer, free the algorithm */
566                         target_free_working_area(target, write_algorithm);
567
568                         LOG_WARNING("no large enough working area available, can't do block memory writes");
569                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
570                 }
571         }
572
573         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
574         armv7m_info.core_mode = ARM_MODE_THREAD;
575
576         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT);         /* buffer start, status (out) */
577         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);            /* buffer end */
578         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);            /* target address */
579         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);            /* count (halfword-16bit) */
580         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);            /* flash base */
581
582         buf_set_u32(reg_params[0].value, 0, 32, source->address);
583         buf_set_u32(reg_params[1].value, 0, 32, source->address + source->size);
584         buf_set_u32(reg_params[2].value, 0, 32, address);
585         buf_set_u32(reg_params[3].value, 0, 32, count);
586         buf_set_u32(reg_params[4].value, 0, 32, STM32_FLASH_BASE);
587
588         retval = target_run_flash_async_algorithm(target, buffer, count, 2,
589                         0, NULL,
590                         5, reg_params,
591                         source->address, source->size,
592                         write_algorithm->address, 0,
593                         &armv7m_info);
594
595         if (retval == ERROR_FLASH_OPERATION_FAILED) {
596                 LOG_ERROR("error executing stm32x flash write algorithm");
597
598                 uint32_t error = buf_get_u32(reg_params[0].value, 0, 32) & FLASH_ERROR;
599
600                 if (error & FLASH_WRPERR)
601                         LOG_ERROR("flash memory write protected");
602
603                 if (error != 0) {
604                         LOG_ERROR("flash write failed = %08" PRIx32, error);
605                         /* Clear but report errors */
606                         target_write_u32(target, STM32_FLASH_SR, error);
607                         retval = ERROR_FAIL;
608                 }
609         }
610
611         target_free_working_area(target, source);
612         target_free_working_area(target, write_algorithm);
613
614         destroy_reg_param(&reg_params[0]);
615         destroy_reg_param(&reg_params[1]);
616         destroy_reg_param(&reg_params[2]);
617         destroy_reg_param(&reg_params[3]);
618         destroy_reg_param(&reg_params[4]);
619
620         return retval;
621 }
622
623 static int stm32x_write(struct flash_bank *bank, const uint8_t *buffer,
624                 uint32_t offset, uint32_t count)
625 {
626         struct target *target = bank->target;
627         uint32_t words_remaining = (count / 2);
628         uint32_t bytes_remaining = (count & 0x00000001);
629         uint32_t address = bank->base + offset;
630         uint32_t bytes_written = 0;
631         int retval;
632
633         if (bank->target->state != TARGET_HALTED) {
634                 LOG_ERROR("Target not halted");
635                 return ERROR_TARGET_NOT_HALTED;
636         }
637
638         if (offset & 0x1) {
639                 LOG_WARNING("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
640                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
641         }
642
643         retval = stm32x_unlock_reg(target);
644         if (retval != ERROR_OK)
645                 return retval;
646
647         /* multiple half words (2-byte) to be programmed? */
648         if (words_remaining > 0) {
649                 /* try using a block write */
650                 retval = stm32x_write_block(bank, buffer, offset, words_remaining);
651                 if (retval != ERROR_OK) {
652                         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
653                                 /* if block write failed (no sufficient working area),
654                                  * we use normal (slow) single dword accesses */
655                                 LOG_WARNING("couldn't use block writes, falling back to single memory accesses");
656                         }
657                 } else {
658                         buffer += words_remaining * 2;
659                         address += words_remaining * 2;
660                         words_remaining = 0;
661                 }
662         }
663
664         if ((retval != ERROR_OK) && (retval != ERROR_TARGET_RESOURCE_NOT_AVAILABLE))
665                 return retval;
666
667         /*
668         Standard programming
669         The Flash memory programming sequence is as follows:
670         1. Check that no main Flash memory operation is ongoing by checking the BSY bit in the
671           FLASH_SR register.
672         2. Set the PG bit in the FLASH_CR register
673         3. Perform the data write operation(s) to the desired memory address (inside main
674           memory block or OTP area):
675         â€“ â€“ Half-word access in case of x16 parallelism
676         â€“ Word access in case of x32 parallelism
677         â€“
678         4.
679         Byte access in case of x8 parallelism
680         Double word access in case of x64 parallelism
681         Wait for the BSY bit to be cleared
682         */
683         while (words_remaining > 0) {
684                 uint16_t value;
685                 memcpy(&value, buffer + bytes_written, sizeof(uint16_t));
686
687                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
688                                 FLASH_PG | FLASH_PSIZE_16);
689                 if (retval != ERROR_OK)
690                         return retval;
691
692                 retval = target_write_u16(target, address, value);
693                 if (retval != ERROR_OK)
694                         return retval;
695
696                 retval = stm32x_wait_status_busy(bank, FLASH_WRITE_TIMEOUT);
697                 if (retval != ERROR_OK)
698                         return retval;
699
700                 bytes_written += 2;
701                 words_remaining--;
702                 address += 2;
703         }
704
705         if (bytes_remaining) {
706                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
707                                 FLASH_PG | FLASH_PSIZE_8);
708                 if (retval != ERROR_OK)
709                         return retval;
710                 retval = target_write_u8(target, address, buffer[bytes_written]);
711                 if (retval != ERROR_OK)
712                         return retval;
713
714                 retval = stm32x_wait_status_busy(bank, FLASH_WRITE_TIMEOUT);
715                 if (retval != ERROR_OK)
716                         return retval;
717         }
718
719         return target_write_u32(target, STM32_FLASH_CR, FLASH_LOCK);
720 }
721
722 static void setup_sector(struct flash_bank *bank, int start, int num, int size)
723 {
724         for (int i = start; i < (start + num) ; i++) {
725                 assert(i < bank->num_sectors);
726                 bank->sectors[i].offset = bank->size;
727                 bank->sectors[i].size = size;
728                 bank->size += bank->sectors[i].size;
729         }
730 }
731
732 static int stm32x_get_device_id(struct flash_bank *bank, uint32_t *device_id)
733 {
734         /* this checks for a stm32f4x errata issue where a
735          * stm32f2x DBGMCU_IDCODE is incorrectly returned.
736          * If the issue is detected target is forced to stm32f4x Rev A.
737          * Only effects Rev A silicon */
738
739         struct target *target = bank->target;
740         uint32_t cpuid;
741
742         /* read stm32 device id register */
743         int retval = target_read_u32(target, 0xE0042000, device_id);
744         if (retval != ERROR_OK)
745                 return retval;
746
747         if ((*device_id & 0xfff) == 0x411) {
748                 /* read CPUID reg to check core type */
749                 retval = target_read_u32(target, 0xE000ED00, &cpuid);
750                 if (retval != ERROR_OK)
751                         return retval;
752
753                 /* check for cortex_m4 */
754                 if (((cpuid >> 4) & 0xFFF) == 0xC24) {
755                         *device_id &= ~((0xFFFF << 16) | 0xfff);
756                         *device_id |= (0x1000 << 16) | 0x413;
757                         LOG_INFO("stm32f4x errata detected - fixing incorrect MCU_IDCODE");
758                 }
759         }
760         return retval;
761 }
762
763 static int stm32x_probe(struct flash_bank *bank)
764 {
765         struct target *target = bank->target;
766         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
767         int i;
768         uint16_t flash_size_in_kb;
769         uint32_t flash_size_reg = 0x1FFF7A22;
770         uint16_t max_sector_size_in_kb = 128;
771         uint16_t max_flash_size_in_kb;
772         uint32_t device_id;
773         uint32_t base_address = 0x08000000;
774
775         stm32x_info->probed = 0;
776         stm32x_info->has_large_mem = false;
777
778         /* read stm32 device id register */
779         int retval = stm32x_get_device_id(bank, &device_id);
780         if (retval != ERROR_OK)
781                 return retval;
782         LOG_INFO("device id = 0x%08" PRIx32 "", device_id);
783
784         /* set max flash size depending on family */
785         switch (device_id & 0xfff) {
786         case 0x411:
787         case 0x413:
788         case 0x441:
789                 max_flash_size_in_kb = 1024;
790                 break;
791         case 0x419:
792         case 0x434:
793                 max_flash_size_in_kb = 2048;
794                 break;
795         case 0x423:
796                 max_flash_size_in_kb = 256;
797                 break;
798         case 0x431:
799         case 0x433:
800         case 0x421:
801                 max_flash_size_in_kb = 512;
802                 break;
803         case 0x458:
804                 max_flash_size_in_kb = 128;
805                 break;
806         case 0x449:
807                 max_flash_size_in_kb = 1024;
808                 max_sector_size_in_kb = 256;
809                 flash_size_reg = 0x1FF0F442;
810                 break;
811         default:
812                 LOG_WARNING("Cannot identify target as a STM32 family.");
813                 return ERROR_FAIL;
814         }
815
816         /* get flash size from target. */
817         retval = target_read_u16(target, flash_size_reg, &flash_size_in_kb);
818
819         /* failed reading flash size or flash size invalid (early silicon),
820          * default to max target family */
821         if (retval != ERROR_OK || flash_size_in_kb == 0xffff || flash_size_in_kb == 0) {
822                 LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming %dk flash",
823                         max_flash_size_in_kb);
824                 flash_size_in_kb = max_flash_size_in_kb;
825         }
826
827         /* if the user sets the size manually then ignore the probed value
828          * this allows us to work around devices that have a invalid flash size register value */
829         if (stm32x_info->user_bank_size) {
830                 LOG_INFO("ignoring flash probed value, using configured bank size");
831                 flash_size_in_kb = stm32x_info->user_bank_size / 1024;
832         }
833
834         LOG_INFO("flash size = %dkbytes", flash_size_in_kb);
835
836         /* did we assign flash size? */
837         assert(flash_size_in_kb != 0xffff);
838
839         /* calculate numbers of pages */
840         int num_pages = (flash_size_in_kb / max_sector_size_in_kb) + 4;
841
842         /* Devices with > 1024 kiByte always are dual-banked */
843         if (flash_size_in_kb > 1024)
844                 stm32x_info->has_large_mem = true;
845
846         /* F42x/43x 1024 kiByte devices have a dual bank option */
847         if ((device_id & 0xfff) == 0x419 && (flash_size_in_kb == 1024)) {
848                 uint32_t optiondata;
849                 retval = target_read_u32(target, STM32_FLASH_OPTCR, &optiondata);
850                 if (retval != ERROR_OK) {
851                         LOG_DEBUG("unable to read option bytes");
852                         return retval;
853                 }
854                 if (optiondata & (1 << OPT_DB1M)) {
855                         stm32x_info->has_large_mem = true;
856                         LOG_INFO("Dual Bank 1024 kiB STM32F42x/43x found");
857                 }
858         }
859
860         /* check for dual-banked devices */
861         if (stm32x_info->has_large_mem)
862                 num_pages += 4;
863
864         /* check that calculation result makes sense */
865         assert(num_pages > 0);
866
867         if (bank->sectors) {
868                 free(bank->sectors);
869                 bank->sectors = NULL;
870         }
871
872         bank->base = base_address;
873         bank->num_sectors = num_pages;
874         bank->sectors = malloc(sizeof(struct flash_sector) * num_pages);
875         bank->size = 0;
876
877         /* fixed memory */
878         setup_sector(bank, 0, 4, (max_sector_size_in_kb / 8) * 1024);
879         setup_sector(bank, 4, 1, (max_sector_size_in_kb / 2) * 1024);
880
881         if (stm32x_info->has_large_mem) {
882                 if (flash_size_in_kb == 1024) {
883                         setup_sector(bank,  5, 3, 128 * 1024);
884                         setup_sector(bank, 12, 4,  16 * 1024);
885                         setup_sector(bank, 16, 1,  64 * 1024);
886                         setup_sector(bank, 17, 3, 128 * 1024);
887                 } else {
888                         setup_sector(bank,  5, 7, 128 * 1024);
889                         setup_sector(bank, 12, 4,  16 * 1024);
890                         setup_sector(bank, 16, 1,  64 * 1024);
891                         setup_sector(bank, 17, 7, 128 * 1024);
892                 }
893         } else {
894                 setup_sector(bank, 4 + 1, MIN(12, num_pages) - 5,
895                                          max_sector_size_in_kb * 1024);
896         }
897         for (i = 0; i < num_pages; i++) {
898                 bank->sectors[i].is_erased = -1;
899                 bank->sectors[i].is_protected = 0;
900         }
901
902         stm32x_info->probed = 1;
903
904         return ERROR_OK;
905 }
906
907 static int stm32x_auto_probe(struct flash_bank *bank)
908 {
909         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
910         if (stm32x_info->probed)
911                 return ERROR_OK;
912         return stm32x_probe(bank);
913 }
914
915 static int get_stm32x_info(struct flash_bank *bank, char *buf, int buf_size)
916 {
917         uint32_t dbgmcu_idcode;
918
919         /* read stm32 device id register */
920         int retval = stm32x_get_device_id(bank, &dbgmcu_idcode);
921         if (retval != ERROR_OK)
922                 return retval;
923
924         uint16_t device_id = dbgmcu_idcode & 0xfff;
925         uint16_t rev_id = dbgmcu_idcode >> 16;
926         const char *device_str;
927         const char *rev_str = NULL;
928
929         switch (device_id) {
930         case 0x411:
931                 device_str = "STM32F2xx";
932
933                 switch (rev_id) {
934                 case 0x1000:
935                         rev_str = "A";
936                         break;
937
938                 case 0x2000:
939                         rev_str = "B";
940                         break;
941
942                 case 0x1001:
943                         rev_str = "Z";
944                         break;
945
946                 case 0x2001:
947                         rev_str = "Y";
948                         break;
949
950                 case 0x2003:
951                         rev_str = "X";
952                         break;
953                 }
954                 break;
955
956         case 0x413:
957         case 0x419:
958                 device_str = "STM32F4xx";
959
960                 switch (rev_id) {
961                 case 0x1000:
962                         rev_str = "A";
963                         break;
964
965                 case 0x1001:
966                         rev_str = "Z";
967                         break;
968
969                 case 0x1003:
970                         rev_str = "Y";
971                         break;
972
973                 case 0x1007:
974                         rev_str = "1";
975                         break;
976
977                 case 0x2001:
978                         rev_str = "3";
979                         break;
980                 }
981                 break;
982         case 0x421:
983                 device_str = "STM32F446";
984
985                 switch (rev_id) {
986                 case 0x1000:
987                         rev_str = "A";
988                         break;
989                 }
990                 break;
991         case 0x423:
992         case 0x431:
993         case 0x433:
994         case 0x458:
995         case 0x441:
996                 device_str = "STM32F4xx (Low Power)";
997
998                 switch (rev_id) {
999                 case 0x1000:
1000                         rev_str = "A";
1001                         break;
1002
1003                 case 0x1001:
1004                         rev_str = "Z";
1005                         break;
1006                 }
1007                 break;
1008
1009         case 0x449:
1010                 device_str = "STM32F7[4|5]x";
1011
1012                 switch (rev_id) {
1013                 case 0x1000:
1014                         rev_str = "A";
1015                         break;
1016
1017                 case 0x1001:
1018                         rev_str = "Z";
1019                         break;
1020                 }
1021                 break;
1022         case 0x434:
1023                 device_str = "STM32F46x/F47x";
1024
1025                 switch (rev_id) {
1026                 case 0x1000:
1027                         rev_str = "A";
1028                         break;
1029                 }
1030                 break;
1031
1032         default:
1033                 snprintf(buf, buf_size, "Cannot identify target as a STM32F2/4/7\n");
1034                 return ERROR_FAIL;
1035         }
1036
1037         if (rev_str != NULL)
1038                 snprintf(buf, buf_size, "%s - Rev: %s", device_str, rev_str);
1039         else
1040                 snprintf(buf, buf_size, "%s - Rev: unknown (0x%04x)", device_str, rev_id);
1041
1042         return ERROR_OK;
1043 }
1044
1045 COMMAND_HANDLER(stm32x_handle_lock_command)
1046 {
1047         struct target *target = NULL;
1048         struct stm32x_flash_bank *stm32x_info = NULL;
1049
1050         if (CMD_ARGC < 1)
1051                 return ERROR_COMMAND_SYNTAX_ERROR;
1052
1053         struct flash_bank *bank;
1054         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1055         if (ERROR_OK != retval)
1056                 return retval;
1057
1058         stm32x_info = bank->driver_priv;
1059         target = bank->target;
1060
1061         if (target->state != TARGET_HALTED) {
1062                 LOG_ERROR("Target not halted");
1063                 return ERROR_TARGET_NOT_HALTED;
1064         }
1065
1066         if (stm32x_read_options(bank) != ERROR_OK) {
1067                 command_print(CMD_CTX, "%s failed to read options", bank->driver->name);
1068                 return ERROR_OK;
1069         }
1070
1071         /* set readout protection */
1072         stm32x_info->option_bytes.RDP = 0;
1073
1074         if (stm32x_write_options(bank) != ERROR_OK) {
1075                 command_print(CMD_CTX, "%s failed to lock device", bank->driver->name);
1076                 return ERROR_OK;
1077         }
1078
1079         command_print(CMD_CTX, "%s locked", bank->driver->name);
1080
1081         return ERROR_OK;
1082 }
1083
1084 COMMAND_HANDLER(stm32x_handle_unlock_command)
1085 {
1086         struct target *target = NULL;
1087         struct stm32x_flash_bank *stm32x_info = NULL;
1088
1089         if (CMD_ARGC < 1)
1090                 return ERROR_COMMAND_SYNTAX_ERROR;
1091
1092         struct flash_bank *bank;
1093         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1094         if (ERROR_OK != retval)
1095                 return retval;
1096
1097         stm32x_info = bank->driver_priv;
1098         target = bank->target;
1099
1100         if (target->state != TARGET_HALTED) {
1101                 LOG_ERROR("Target not halted");
1102                 return ERROR_TARGET_NOT_HALTED;
1103         }
1104
1105         if (stm32x_read_options(bank) != ERROR_OK) {
1106                 command_print(CMD_CTX, "%s failed to read options", bank->driver->name);
1107                 return ERROR_OK;
1108         }
1109
1110         /* clear readout protection and complementary option bytes
1111          * this will also force a device unlock if set */
1112         stm32x_info->option_bytes.RDP = 0xAA;
1113
1114         if (stm32x_write_options(bank) != ERROR_OK) {
1115                 command_print(CMD_CTX, "%s failed to unlock device", bank->driver->name);
1116                 return ERROR_OK;
1117         }
1118
1119         command_print(CMD_CTX, "%s unlocked.\n"
1120                         "INFO: a reset or power cycle is required "
1121                         "for the new settings to take effect.", bank->driver->name);
1122
1123         return ERROR_OK;
1124 }
1125
1126 static int stm32x_mass_erase(struct flash_bank *bank)
1127 {
1128         int retval;
1129         uint32_t flash_mer;
1130         struct target *target = bank->target;
1131         struct stm32x_flash_bank *stm32x_info = NULL;
1132
1133         if (target->state != TARGET_HALTED) {
1134                 LOG_ERROR("Target not halted");
1135                 return ERROR_TARGET_NOT_HALTED;
1136         }
1137
1138         stm32x_info = bank->driver_priv;
1139
1140         retval = stm32x_unlock_reg(target);
1141         if (retval != ERROR_OK)
1142                 return retval;
1143
1144         /* mass erase flash memory */
1145         if (stm32x_info->has_large_mem)
1146                 flash_mer = FLASH_MER | FLASH_MER1;
1147         else
1148                 flash_mer = FLASH_MER;
1149         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), flash_mer);
1150         if (retval != ERROR_OK)
1151                 return retval;
1152         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
1153                 flash_mer | FLASH_STRT);
1154         if (retval != ERROR_OK)
1155                 return retval;
1156
1157         retval = stm32x_wait_status_busy(bank, 30000);
1158         if (retval != ERROR_OK)
1159                 return retval;
1160
1161         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
1162         if (retval != ERROR_OK)
1163                 return retval;
1164
1165         return ERROR_OK;
1166 }
1167
1168 COMMAND_HANDLER(stm32x_handle_mass_erase_command)
1169 {
1170         int i;
1171
1172         if (CMD_ARGC < 1) {
1173                 command_print(CMD_CTX, "stm32x mass_erase <bank>");
1174                 return ERROR_COMMAND_SYNTAX_ERROR;
1175         }
1176
1177         struct flash_bank *bank;
1178         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1179         if (ERROR_OK != retval)
1180                 return retval;
1181
1182         retval = stm32x_mass_erase(bank);
1183         if (retval == ERROR_OK) {
1184                 /* set all sectors as erased */
1185                 for (i = 0; i < bank->num_sectors; i++)
1186                         bank->sectors[i].is_erased = 1;
1187
1188                 command_print(CMD_CTX, "stm32x mass erase complete");
1189         } else {
1190                 command_print(CMD_CTX, "stm32x mass erase failed");
1191         }
1192
1193         return retval;
1194 }
1195
1196 static const struct command_registration stm32x_exec_command_handlers[] = {
1197         {
1198                 .name = "lock",
1199                 .handler = stm32x_handle_lock_command,
1200                 .mode = COMMAND_EXEC,
1201                 .usage = "bank_id",
1202                 .help = "Lock entire flash device.",
1203         },
1204         {
1205                 .name = "unlock",
1206                 .handler = stm32x_handle_unlock_command,
1207                 .mode = COMMAND_EXEC,
1208                 .usage = "bank_id",
1209                 .help = "Unlock entire protected flash device.",
1210         },
1211         {
1212                 .name = "mass_erase",
1213                 .handler = stm32x_handle_mass_erase_command,
1214                 .mode = COMMAND_EXEC,
1215                 .usage = "bank_id",
1216                 .help = "Erase entire flash device.",
1217         },
1218         COMMAND_REGISTRATION_DONE
1219 };
1220
1221 static const struct command_registration stm32x_command_handlers[] = {
1222         {
1223                 .name = "stm32f2x",
1224                 .mode = COMMAND_ANY,
1225                 .help = "stm32f2x flash command group",
1226                 .usage = "",
1227                 .chain = stm32x_exec_command_handlers,
1228         },
1229         COMMAND_REGISTRATION_DONE
1230 };
1231
1232 struct flash_driver stm32f2x_flash = {
1233         .name = "stm32f2x",
1234         .commands = stm32x_command_handlers,
1235         .flash_bank_command = stm32x_flash_bank_command,
1236         .erase = stm32x_erase,
1237         .protect = stm32x_protect,
1238         .write = stm32x_write,
1239         .read = default_flash_read,
1240         .probe = stm32x_probe,
1241         .auto_probe = stm32x_auto_probe,
1242         .erase_check = default_flash_blank_check,
1243         .protect_check = stm32x_protect_check,
1244         .info = get_stm32x_info,
1245 };