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