]> git.sur5r.net Git - openocd/blob - src/flash/nor/stm32f2x.c
c285847fc49a9d9c163a98b0f36209b9550eb349
[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         case 0x441:
791                 max_flash_size_in_kb = 1024;
792                 break;
793         case 0x419:
794         case 0x434:
795                 max_flash_size_in_kb = 2048;
796                 break;
797         case 0x423:
798                 max_flash_size_in_kb = 256;
799                 break;
800         case 0x431:
801         case 0x433:
802         case 0x421:
803                 max_flash_size_in_kb = 512;
804                 break;
805         case 0x458:
806                 max_flash_size_in_kb = 128;
807                 break;
808         case 0x449:
809                 max_flash_size_in_kb = 1024;
810                 max_sector_size_in_kb = 256;
811                 flash_size_reg = 0x1FF0F442;
812                 break;
813         default:
814                 LOG_WARNING("Cannot identify target as a STM32 family.");
815                 return ERROR_FAIL;
816         }
817
818         /* get flash size from target. */
819         retval = target_read_u16(target, flash_size_reg, &flash_size_in_kb);
820
821         /* failed reading flash size or flash size invalid (early silicon),
822          * default to max target family */
823         if (retval != ERROR_OK || flash_size_in_kb == 0xffff || flash_size_in_kb == 0) {
824                 LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming %dk flash",
825                         max_flash_size_in_kb);
826                 flash_size_in_kb = max_flash_size_in_kb;
827         }
828
829         /* if the user sets the size manually then ignore the probed value
830          * this allows us to work around devices that have a invalid flash size register value */
831         if (stm32x_info->user_bank_size) {
832                 LOG_INFO("ignoring flash probed value, using configured bank size");
833                 flash_size_in_kb = stm32x_info->user_bank_size / 1024;
834         }
835
836         LOG_INFO("flash size = %dkbytes", flash_size_in_kb);
837
838         /* did we assign flash size? */
839         assert(flash_size_in_kb != 0xffff);
840
841         /* calculate numbers of pages */
842         int num_pages = (flash_size_in_kb / max_sector_size_in_kb) + 4;
843
844         /* Devices with > 1024 kiByte always are dual-banked */
845         if (flash_size_in_kb > 1024)
846                 stm32x_info->has_large_mem = true;
847
848         /* F42x/43x 1024 kiByte devices have a dual bank option */
849         if ((device_id & 0xfff) == 0x419 && (flash_size_in_kb == 1024)) {
850                 uint32_t optiondata;
851                 retval = target_read_u32(target, STM32_FLASH_OPTCR, &optiondata);
852                 if (retval != ERROR_OK) {
853                         LOG_DEBUG("unable to read option bytes");
854                         return retval;
855                 }
856                 if (optiondata & (1 << OPT_DB1M)) {
857                         stm32x_info->has_large_mem = true;
858                         LOG_INFO("Dual Bank 1024 kiB STM32F42x/43x found");
859                 }
860         }
861
862         /* check for dual-banked devices */
863         if (stm32x_info->has_large_mem)
864                 num_pages += 4;
865
866         /* check that calculation result makes sense */
867         assert(num_pages > 0);
868
869         if (bank->sectors) {
870                 free(bank->sectors);
871                 bank->sectors = NULL;
872         }
873
874         bank->base = base_address;
875         bank->num_sectors = num_pages;
876         bank->sectors = malloc(sizeof(struct flash_sector) * num_pages);
877         bank->size = 0;
878
879         /* fixed memory */
880         setup_sector(bank, 0, 4, (max_sector_size_in_kb / 8) * 1024);
881         setup_sector(bank, 4, 1, (max_sector_size_in_kb / 2) * 1024);
882
883         if (stm32x_info->has_large_mem) {
884                 if (flash_size_in_kb == 1024) {
885                         setup_sector(bank,  5, 3, 128 * 1024);
886                         setup_sector(bank, 12, 4,  16 * 1024);
887                         setup_sector(bank, 16, 1,  64 * 1024);
888                         setup_sector(bank, 17, 3, 128 * 1024);
889                 } else {
890                         setup_sector(bank,  5, 7, 128 * 1024);
891                         setup_sector(bank, 12, 4,  16 * 1024);
892                         setup_sector(bank, 16, 1,  64 * 1024);
893                         setup_sector(bank, 17, 7, 128 * 1024);
894                 }
895         } else {
896                 setup_sector(bank, 4 + 1, MIN(12, num_pages) - 5,
897                                          max_sector_size_in_kb * 1024);
898         }
899         for (i = 0; i < num_pages; i++) {
900                 bank->sectors[i].is_erased = -1;
901                 bank->sectors[i].is_protected = 0;
902         }
903
904         stm32x_info->probed = 1;
905
906         return ERROR_OK;
907 }
908
909 static int stm32x_auto_probe(struct flash_bank *bank)
910 {
911         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
912         if (stm32x_info->probed)
913                 return ERROR_OK;
914         return stm32x_probe(bank);
915 }
916
917 static int get_stm32x_info(struct flash_bank *bank, char *buf, int buf_size)
918 {
919         uint32_t dbgmcu_idcode;
920
921         /* read stm32 device id register */
922         int retval = stm32x_get_device_id(bank, &dbgmcu_idcode);
923         if (retval != ERROR_OK)
924                 return retval;
925
926         uint16_t device_id = dbgmcu_idcode & 0xfff;
927         uint16_t rev_id = dbgmcu_idcode >> 16;
928         const char *device_str;
929         const char *rev_str = NULL;
930
931         switch (device_id) {
932         case 0x411:
933                 device_str = "STM32F2xx";
934
935                 switch (rev_id) {
936                 case 0x1000:
937                         rev_str = "A";
938                         break;
939
940                 case 0x2000:
941                         rev_str = "B";
942                         break;
943
944                 case 0x1001:
945                         rev_str = "Z";
946                         break;
947
948                 case 0x2001:
949                         rev_str = "Y";
950                         break;
951
952                 case 0x2003:
953                         rev_str = "X";
954                         break;
955                 }
956                 break;
957
958         case 0x413:
959         case 0x419:
960                 device_str = "STM32F4xx";
961
962                 switch (rev_id) {
963                 case 0x1000:
964                         rev_str = "A";
965                         break;
966
967                 case 0x1001:
968                         rev_str = "Z";
969                         break;
970
971                 case 0x1003:
972                         rev_str = "Y";
973                         break;
974
975                 case 0x1007:
976                         rev_str = "1";
977                         break;
978
979                 case 0x2001:
980                         rev_str = "3";
981                         break;
982                 }
983                 break;
984         case 0x421:
985                 device_str = "STM32F446";
986
987                 switch (rev_id) {
988                 case 0x1000:
989                         rev_str = "A";
990                         break;
991                 }
992                 break;
993         case 0x423:
994         case 0x431:
995         case 0x433:
996         case 0x458:
997         case 0x441:
998                 device_str = "STM32F4xx (Low Power)";
999
1000                 switch (rev_id) {
1001                 case 0x1000:
1002                         rev_str = "A";
1003                         break;
1004
1005                 case 0x1001:
1006                         rev_str = "Z";
1007                         break;
1008                 }
1009                 break;
1010
1011         case 0x449:
1012                 device_str = "STM32F7[4|5]x";
1013
1014                 switch (rev_id) {
1015                 case 0x1000:
1016                         rev_str = "A";
1017                         break;
1018
1019                 case 0x1001:
1020                         rev_str = "Z";
1021                         break;
1022                 }
1023                 break;
1024         case 0x434:
1025                 device_str = "STM32F46x/F47x";
1026
1027                 switch (rev_id) {
1028                 case 0x1000:
1029                         rev_str = "A";
1030                         break;
1031                 }
1032                 break;
1033
1034         default:
1035                 snprintf(buf, buf_size, "Cannot identify target as a STM32F2/4/7\n");
1036                 return ERROR_FAIL;
1037         }
1038
1039         if (rev_str != NULL)
1040                 snprintf(buf, buf_size, "%s - Rev: %s", device_str, rev_str);
1041         else
1042                 snprintf(buf, buf_size, "%s - Rev: unknown (0x%04x)", device_str, rev_id);
1043
1044         return ERROR_OK;
1045 }
1046
1047 COMMAND_HANDLER(stm32x_handle_lock_command)
1048 {
1049         struct target *target = NULL;
1050         struct stm32x_flash_bank *stm32x_info = NULL;
1051
1052         if (CMD_ARGC < 1)
1053                 return ERROR_COMMAND_SYNTAX_ERROR;
1054
1055         struct flash_bank *bank;
1056         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1057         if (ERROR_OK != retval)
1058                 return retval;
1059
1060         stm32x_info = bank->driver_priv;
1061         target = bank->target;
1062
1063         if (target->state != TARGET_HALTED) {
1064                 LOG_ERROR("Target not halted");
1065                 return ERROR_TARGET_NOT_HALTED;
1066         }
1067
1068         if (stm32x_read_options(bank) != ERROR_OK) {
1069                 command_print(CMD_CTX, "%s failed to read options", bank->driver->name);
1070                 return ERROR_OK;
1071         }
1072
1073         /* set readout protection */
1074         stm32x_info->option_bytes.RDP = 0;
1075
1076         if (stm32x_write_options(bank) != ERROR_OK) {
1077                 command_print(CMD_CTX, "%s failed to lock device", bank->driver->name);
1078                 return ERROR_OK;
1079         }
1080
1081         command_print(CMD_CTX, "%s locked", bank->driver->name);
1082
1083         return ERROR_OK;
1084 }
1085
1086 COMMAND_HANDLER(stm32x_handle_unlock_command)
1087 {
1088         struct target *target = NULL;
1089         struct stm32x_flash_bank *stm32x_info = NULL;
1090
1091         if (CMD_ARGC < 1)
1092                 return ERROR_COMMAND_SYNTAX_ERROR;
1093
1094         struct flash_bank *bank;
1095         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1096         if (ERROR_OK != retval)
1097                 return retval;
1098
1099         stm32x_info = bank->driver_priv;
1100         target = bank->target;
1101
1102         if (target->state != TARGET_HALTED) {
1103                 LOG_ERROR("Target not halted");
1104                 return ERROR_TARGET_NOT_HALTED;
1105         }
1106
1107         if (stm32x_read_options(bank) != ERROR_OK) {
1108                 command_print(CMD_CTX, "%s failed to read options", bank->driver->name);
1109                 return ERROR_OK;
1110         }
1111
1112         /* clear readout protection and complementary option bytes
1113          * this will also force a device unlock if set */
1114         stm32x_info->option_bytes.RDP = 0xAA;
1115
1116         if (stm32x_write_options(bank) != ERROR_OK) {
1117                 command_print(CMD_CTX, "%s failed to unlock device", bank->driver->name);
1118                 return ERROR_OK;
1119         }
1120
1121         command_print(CMD_CTX, "%s unlocked.\n"
1122                         "INFO: a reset or power cycle is required "
1123                         "for the new settings to take effect.", bank->driver->name);
1124
1125         return ERROR_OK;
1126 }
1127
1128 static int stm32x_mass_erase(struct flash_bank *bank)
1129 {
1130         int retval;
1131         uint32_t flash_mer;
1132         struct target *target = bank->target;
1133         struct stm32x_flash_bank *stm32x_info = NULL;
1134
1135         if (target->state != TARGET_HALTED) {
1136                 LOG_ERROR("Target not halted");
1137                 return ERROR_TARGET_NOT_HALTED;
1138         }
1139
1140         stm32x_info = bank->driver_priv;
1141
1142         retval = stm32x_unlock_reg(target);
1143         if (retval != ERROR_OK)
1144                 return retval;
1145
1146         /* mass erase flash memory */
1147         if (stm32x_info->has_large_mem)
1148                 flash_mer = FLASH_MER | FLASH_MER1;
1149         else
1150                 flash_mer = FLASH_MER;
1151         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), flash_mer);
1152         if (retval != ERROR_OK)
1153                 return retval;
1154         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
1155                 flash_mer | FLASH_STRT);
1156         if (retval != ERROR_OK)
1157                 return retval;
1158
1159         retval = stm32x_wait_status_busy(bank, 30000);
1160         if (retval != ERROR_OK)
1161                 return retval;
1162
1163         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
1164         if (retval != ERROR_OK)
1165                 return retval;
1166
1167         return ERROR_OK;
1168 }
1169
1170 COMMAND_HANDLER(stm32x_handle_mass_erase_command)
1171 {
1172         int i;
1173
1174         if (CMD_ARGC < 1) {
1175                 command_print(CMD_CTX, "stm32x mass_erase <bank>");
1176                 return ERROR_COMMAND_SYNTAX_ERROR;
1177         }
1178
1179         struct flash_bank *bank;
1180         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1181         if (ERROR_OK != retval)
1182                 return retval;
1183
1184         retval = stm32x_mass_erase(bank);
1185         if (retval == ERROR_OK) {
1186                 /* set all sectors as erased */
1187                 for (i = 0; i < bank->num_sectors; i++)
1188                         bank->sectors[i].is_erased = 1;
1189
1190                 command_print(CMD_CTX, "stm32x mass erase complete");
1191         } else {
1192                 command_print(CMD_CTX, "stm32x mass erase failed");
1193         }
1194
1195         return retval;
1196 }
1197
1198 static const struct command_registration stm32x_exec_command_handlers[] = {
1199         {
1200                 .name = "lock",
1201                 .handler = stm32x_handle_lock_command,
1202                 .mode = COMMAND_EXEC,
1203                 .usage = "bank_id",
1204                 .help = "Lock entire flash device.",
1205         },
1206         {
1207                 .name = "unlock",
1208                 .handler = stm32x_handle_unlock_command,
1209                 .mode = COMMAND_EXEC,
1210                 .usage = "bank_id",
1211                 .help = "Unlock entire protected flash device.",
1212         },
1213         {
1214                 .name = "mass_erase",
1215                 .handler = stm32x_handle_mass_erase_command,
1216                 .mode = COMMAND_EXEC,
1217                 .usage = "bank_id",
1218                 .help = "Erase entire flash device.",
1219         },
1220         COMMAND_REGISTRATION_DONE
1221 };
1222
1223 static const struct command_registration stm32x_command_handlers[] = {
1224         {
1225                 .name = "stm32f2x",
1226                 .mode = COMMAND_ANY,
1227                 .help = "stm32f2x flash command group",
1228                 .usage = "",
1229                 .chain = stm32x_exec_command_handlers,
1230         },
1231         COMMAND_REGISTRATION_DONE
1232 };
1233
1234 struct flash_driver stm32f2x_flash = {
1235         .name = "stm32f2x",
1236         .commands = stm32x_command_handlers,
1237         .flash_bank_command = stm32x_flash_bank_command,
1238         .erase = stm32x_erase,
1239         .protect = stm32x_protect,
1240         .write = stm32x_write,
1241         .read = default_flash_read,
1242         .probe = stm32x_probe,
1243         .auto_probe = stm32x_auto_probe,
1244         .erase_check = default_flash_blank_check,
1245         .protect_check = stm32x_protect_check,
1246         .info = get_stm32x_info,
1247 };