]> git.sur5r.net Git - openocd/blob - src/flash/nor/stm32f2x.c
stm32f2x.c: Add STM32F74x handling.
[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, 0x30, 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                                                                         /* busy: */
525                 0xE6, 0x68,                                     /* ldr          r6, [r4, #STM32_FLASH_SR_OFFSET] */
526                 0x16, 0xF4, 0x80, 0x3F,         /* tst          r6, #0x10000 */
527                 0xFB, 0xD1,                                     /* bne          busy */
528                 0x16, 0xF0, 0xF0, 0x0F,         /* tst          r6, #0xf0 */
529                 0x07, 0xD1,                                     /* bne          error */
530
531                 0x8F, 0x42,                                     /* cmp          r7, r1 */
532                 0x28, 0xBF,                                     /* it           cs */
533                 0x00, 0xF1, 0x08, 0x07,         /* addcs        r7, r0, #8 */
534                 0x47, 0x60,                                     /* str          r7, [r0, #4] */
535                 0x01, 0x3B,                                     /* subs         r3, r3, #1 */
536                 0x13, 0xB1,                                     /* cbz          r3, exit */
537                 0xE1, 0xE7,                                     /* b            wait_fifo */
538                                                                         /* error: */
539                 0x00, 0x21,                                     /* movs         r1, #0 */
540                 0x41, 0x60,                                     /* str          r1, [r0, #4] */
541                                                                         /* exit: */
542                 0x30, 0x46,                                     /* mov          r0, r6 */
543                 0x00, 0xBE,                                     /* bkpt         #0x00 */
544
545                 /* <STM32_PROG16>: */
546                 0x01, 0x01, 0x00, 0x00,         /* .word        0x00000101 */
547         };
548
549         if (target_alloc_working_area(target, sizeof(stm32x_flash_write_code),
550                         &write_algorithm) != ERROR_OK) {
551                 LOG_WARNING("no working area available, can't do block memory writes");
552                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
553         };
554
555         retval = target_write_buffer(target, write_algorithm->address,
556                         sizeof(stm32x_flash_write_code),
557                         stm32x_flash_write_code);
558         if (retval != ERROR_OK)
559                 return retval;
560
561         /* memory buffer */
562         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) {
563                 buffer_size /= 2;
564                 if (buffer_size <= 256) {
565                         /* we already allocated the writing code, but failed to get a
566                          * buffer, free the algorithm */
567                         target_free_working_area(target, write_algorithm);
568
569                         LOG_WARNING("no large enough working area available, can't do block memory writes");
570                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
571                 }
572         };
573
574         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
575         armv7m_info.core_mode = ARM_MODE_THREAD;
576
577         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT);         /* buffer start, status (out) */
578         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);            /* buffer end */
579         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);            /* target address */
580         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);            /* count (halfword-16bit) */
581         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);            /* flash base */
582
583         buf_set_u32(reg_params[0].value, 0, 32, source->address);
584         buf_set_u32(reg_params[1].value, 0, 32, source->address + source->size);
585         buf_set_u32(reg_params[2].value, 0, 32, address);
586         buf_set_u32(reg_params[3].value, 0, 32, count);
587         buf_set_u32(reg_params[4].value, 0, 32, STM32_FLASH_BASE);
588
589         retval = target_run_flash_async_algorithm(target, buffer, count, 2,
590                         0, NULL,
591                         5, reg_params,
592                         source->address, source->size,
593                         write_algorithm->address, 0,
594                         &armv7m_info);
595
596         if (retval == ERROR_FLASH_OPERATION_FAILED) {
597                 LOG_ERROR("error executing stm32x flash write algorithm");
598
599                 uint32_t error = buf_get_u32(reg_params[0].value, 0, 32) & FLASH_ERROR;
600
601                 if (error & FLASH_WRPERR)
602                         LOG_ERROR("flash memory write protected");
603
604                 if (error != 0) {
605                         LOG_ERROR("flash write failed = %08" PRIx32, error);
606                         /* Clear but report errors */
607                         target_write_u32(target, STM32_FLASH_SR, error);
608                         retval = ERROR_FAIL;
609                 }
610         }
611
612         target_free_working_area(target, source);
613         target_free_working_area(target, write_algorithm);
614
615         destroy_reg_param(&reg_params[0]);
616         destroy_reg_param(&reg_params[1]);
617         destroy_reg_param(&reg_params[2]);
618         destroy_reg_param(&reg_params[3]);
619         destroy_reg_param(&reg_params[4]);
620
621         return retval;
622 }
623
624 static int stm32x_write(struct flash_bank *bank, const uint8_t *buffer,
625                 uint32_t offset, uint32_t count)
626 {
627         struct target *target = bank->target;
628         uint32_t words_remaining = (count / 2);
629         uint32_t bytes_remaining = (count & 0x00000001);
630         uint32_t address = bank->base + offset;
631         uint32_t bytes_written = 0;
632         int retval;
633
634         if (bank->target->state != TARGET_HALTED) {
635                 LOG_ERROR("Target not halted");
636                 return ERROR_TARGET_NOT_HALTED;
637         }
638
639         if (offset & 0x1) {
640                 LOG_WARNING("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
641                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
642         }
643
644         retval = stm32x_unlock_reg(target);
645         if (retval != ERROR_OK)
646                 return retval;
647
648         /* multiple half words (2-byte) to be programmed? */
649         if (words_remaining > 0) {
650                 /* try using a block write */
651                 retval = stm32x_write_block(bank, buffer, offset, words_remaining);
652                 if (retval != ERROR_OK) {
653                         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
654                                 /* if block write failed (no sufficient working area),
655                                  * we use normal (slow) single dword accesses */
656                                 LOG_WARNING("couldn't use block writes, falling back to single memory accesses");
657                         }
658                 } else {
659                         buffer += words_remaining * 2;
660                         address += words_remaining * 2;
661                         words_remaining = 0;
662                 }
663         }
664
665         if ((retval != ERROR_OK) && (retval != ERROR_TARGET_RESOURCE_NOT_AVAILABLE))
666                 return retval;
667
668         /*
669         Standard programming
670         The Flash memory programming sequence is as follows:
671         1. Check that no main Flash memory operation is ongoing by checking the BSY bit in the
672           FLASH_SR register.
673         2. Set the PG bit in the FLASH_CR register
674         3. Perform the data write operation(s) to the desired memory address (inside main
675           memory block or OTP area):
676         â€“ â€“ Half-word access in case of x16 parallelism
677         â€“ Word access in case of x32 parallelism
678         â€“
679         4.
680         Byte access in case of x8 parallelism
681         Double word access in case of x64 parallelism
682         Wait for the BSY bit to be cleared
683         */
684         while (words_remaining > 0) {
685                 uint16_t value;
686                 memcpy(&value, buffer + bytes_written, sizeof(uint16_t));
687
688                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
689                                 FLASH_PG | FLASH_PSIZE_16);
690                 if (retval != ERROR_OK)
691                         return retval;
692
693                 retval = target_write_u16(target, address, value);
694                 if (retval != ERROR_OK)
695                         return retval;
696
697                 retval = stm32x_wait_status_busy(bank, FLASH_WRITE_TIMEOUT);
698                 if (retval != ERROR_OK)
699                         return retval;
700
701                 bytes_written += 2;
702                 words_remaining--;
703                 address += 2;
704         }
705
706         if (bytes_remaining) {
707                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
708                                 FLASH_PG | FLASH_PSIZE_8);
709                 if (retval != ERROR_OK)
710                         return retval;
711                 retval = target_write_u8(target, address, buffer[bytes_written]);
712                 if (retval != ERROR_OK)
713                         return retval;
714
715                 retval = stm32x_wait_status_busy(bank, FLASH_WRITE_TIMEOUT);
716                 if (retval != ERROR_OK)
717                         return retval;
718         }
719
720         return target_write_u32(target, STM32_FLASH_CR, FLASH_LOCK);
721 }
722
723 static void setup_sector(struct flash_bank *bank, int start, int num, int size)
724 {
725         for (int i = start; i < (start + num) ; i++) {
726                 assert(i < bank->num_sectors);
727                 bank->sectors[i].offset = bank->size;
728                 bank->sectors[i].size = size;
729                 bank->size += bank->sectors[i].size;
730         }
731 }
732
733 static int stm32x_get_device_id(struct flash_bank *bank, uint32_t *device_id)
734 {
735         /* this checks for a stm32f4x errata issue where a
736          * stm32f2x DBGMCU_IDCODE is incorrectly returned.
737          * If the issue is detected target is forced to stm32f4x Rev A.
738          * Only effects Rev A silicon */
739
740         struct target *target = bank->target;
741         uint32_t cpuid;
742
743         /* read stm32 device id register */
744         int retval = target_read_u32(target, 0xE0042000, device_id);
745         if (retval != ERROR_OK)
746                 return retval;
747
748         if ((*device_id & 0xfff) == 0x411) {
749                 /* read CPUID reg to check core type */
750                 retval = target_read_u32(target, 0xE000ED00, &cpuid);
751                 if (retval != ERROR_OK)
752                         return retval;
753
754                 /* check for cortex_m4 */
755                 if (((cpuid >> 4) & 0xFFF) == 0xC24) {
756                         *device_id &= ~((0xFFFF << 16) | 0xfff);
757                         *device_id |= (0x1000 << 16) | 0x413;
758                         LOG_INFO("stm32f4x errata detected - fixing incorrect MCU_IDCODE");
759                 }
760         }
761         return retval;
762 }
763
764 static int stm32x_probe(struct flash_bank *bank)
765 {
766         struct target *target = bank->target;
767         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
768         int i;
769         uint16_t flash_size_in_kb;
770         uint32_t flash_size_reg = 0x1FFF7A22;
771         uint16_t max_sector_size_in_kb = 128;
772         uint16_t max_flash_size_in_kb;
773         uint32_t device_id;
774         uint32_t base_address = 0x08000000;
775
776         stm32x_info->probed = 0;
777         stm32x_info->has_large_mem = false;
778
779         /* read stm32 device id register */
780         int retval = stm32x_get_device_id(bank, &device_id);
781         if (retval != ERROR_OK)
782                 return retval;
783         LOG_INFO("device id = 0x%08" PRIx32 "", device_id);
784
785         /* set max flash size depending on family */
786         switch (device_id & 0xfff) {
787         case 0x411:
788         case 0x413:
789                 max_flash_size_in_kb = 1024;
790                 break;
791         case 0x419:
792                 max_flash_size_in_kb = 2048;
793                 break;
794         case 0x423:
795                 max_flash_size_in_kb = 256;
796                 break;
797         case 0x431:
798         case 0x433:
799         case 0x421:
800                 max_flash_size_in_kb = 512;
801                 break;
802         case 0x449:
803                 max_flash_size_in_kb = 1024;
804                 max_sector_size_in_kb = 256;
805                 flash_size_reg = 0x1FF0F442;
806                 break;
807         default:
808                 LOG_WARNING("Cannot identify target as a STM32 family.");
809                 return ERROR_FAIL;
810         }
811
812         /* get flash size from target. */
813         retval = target_read_u16(target, flash_size_reg, &flash_size_in_kb);
814
815         /* failed reading flash size or flash size invalid (early silicon),
816          * default to max target family */
817         if (retval != ERROR_OK || flash_size_in_kb == 0xffff || flash_size_in_kb == 0) {
818                 LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming %dk flash",
819                         max_flash_size_in_kb);
820                 flash_size_in_kb = max_flash_size_in_kb;
821         }
822
823         /* if the user sets the size manually then ignore the probed value
824          * this allows us to work around devices that have a invalid flash size register value */
825         if (stm32x_info->user_bank_size) {
826                 LOG_INFO("ignoring flash probed value, using configured bank size");
827                 flash_size_in_kb = stm32x_info->user_bank_size / 1024;
828         }
829
830         LOG_INFO("flash size = %dkbytes", flash_size_in_kb);
831
832         /* did we assign flash size? */
833         assert(flash_size_in_kb != 0xffff);
834
835         /* calculate numbers of pages */
836         int num_pages = (flash_size_in_kb / max_sector_size_in_kb) + 4;
837
838         /* Devices with > 1024 kiByte always are dual-banked */
839         if (flash_size_in_kb > 1024)
840                 stm32x_info->has_large_mem = true;
841
842         /* F42x/43x 1024 kiByte devices have a dual bank option */
843         if ((device_id & 0xfff) == 0x419 && (flash_size_in_kb == 1024)) {
844                 uint32_t optiondata;
845                 retval = target_read_u32(target, STM32_FLASH_OPTCR, &optiondata);
846                 if (retval != ERROR_OK) {
847                         LOG_DEBUG("unable to read option bytes");
848                         return retval;
849                 }
850                 if (optiondata & (1 << OPT_DB1M)) {
851                         stm32x_info->has_large_mem = true;
852                         LOG_INFO("Dual Bank 1024 kiB STM32F42x/43x found");
853                 }
854         }
855
856         /* check for dual-banked devices */
857         if (stm32x_info->has_large_mem)
858                 num_pages += 4;
859
860         /* check that calculation result makes sense */
861         assert(num_pages > 0);
862
863         if (bank->sectors) {
864                 free(bank->sectors);
865                 bank->sectors = NULL;
866         }
867
868         bank->base = base_address;
869         bank->num_sectors = num_pages;
870         bank->sectors = malloc(sizeof(struct flash_sector) * num_pages);
871         bank->size = 0;
872
873         /* fixed memory */
874         setup_sector(bank, 0, 4, (max_sector_size_in_kb / 8) * 1024);
875         setup_sector(bank, 4, 1, (max_sector_size_in_kb / 2) * 1024);
876
877         if (stm32x_info->has_large_mem) {
878                 if (flash_size_in_kb == 1024) {
879                         setup_sector(bank,  5, 3, 128 * 1024);
880                         setup_sector(bank, 12, 4,  16 * 1024);
881                         setup_sector(bank, 16, 1,  64 * 1024);
882                         setup_sector(bank, 17, 3, 128 * 1024);
883                 } else {
884                         setup_sector(bank,  5, 7, 128 * 1024);
885                         setup_sector(bank, 12, 4,  16 * 1024);
886                         setup_sector(bank, 16, 1,  64 * 1024);
887                         setup_sector(bank, 17, 7, 128 * 1024);
888                 }
889         } else {
890                 setup_sector(bank, 4 + 1, MIN(12, num_pages) - 5,
891                                          max_sector_size_in_kb * 1024);
892         }
893         for (i = 0; i < num_pages; i++) {
894                 bank->sectors[i].is_erased = -1;
895                 bank->sectors[i].is_protected = 0;
896         }
897
898         stm32x_info->probed = 1;
899
900         return ERROR_OK;
901 }
902
903 static int stm32x_auto_probe(struct flash_bank *bank)
904 {
905         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
906         if (stm32x_info->probed)
907                 return ERROR_OK;
908         return stm32x_probe(bank);
909 }
910
911 static int get_stm32x_info(struct flash_bank *bank, char *buf, int buf_size)
912 {
913         uint32_t dbgmcu_idcode;
914
915         /* read stm32 device id register */
916         int retval = stm32x_get_device_id(bank, &dbgmcu_idcode);
917         if (retval != ERROR_OK)
918                 return retval;
919
920         uint16_t device_id = dbgmcu_idcode & 0xfff;
921         uint16_t rev_id = dbgmcu_idcode >> 16;
922         const char *device_str;
923         const char *rev_str = NULL;
924
925         switch (device_id) {
926         case 0x411:
927                 device_str = "STM32F2xx";
928
929                 switch (rev_id) {
930                 case 0x1000:
931                         rev_str = "A";
932                         break;
933
934                 case 0x2000:
935                         rev_str = "B";
936                         break;
937
938                 case 0x1001:
939                         rev_str = "Z";
940                         break;
941
942                 case 0x2001:
943                         rev_str = "Y";
944                         break;
945
946                 case 0x2003:
947                         rev_str = "X";
948                         break;
949                 }
950                 break;
951
952         case 0x413:
953         case 0x419:
954                 device_str = "STM32F4xx";
955
956                 switch (rev_id) {
957                 case 0x1000:
958                         rev_str = "A";
959                         break;
960
961                 case 0x1001:
962                         rev_str = "Z";
963                         break;
964
965                 case 0x1003:
966                         rev_str = "Y";
967                         break;
968
969                 case 0x1007:
970                         rev_str = "1";
971                         break;
972
973                 case 0x2001:
974                         rev_str = "3";
975                         break;
976                 }
977                 break;
978         case 0x421:
979                 device_str = "STM32F446";
980
981                 switch (rev_id) {
982                 case 0x1000:
983                         rev_str = "A";
984                         break;
985                 }
986                 break;
987         case 0x423:
988         case 0x431:
989         case 0x433:
990                 device_str = "STM32F4xx (Low Power)";
991
992                 switch (rev_id) {
993                 case 0x1000:
994                         rev_str = "A";
995                         break;
996
997                 case 0x1001:
998                         rev_str = "Z";
999                         break;
1000                 }
1001                 break;
1002
1003         case 0x449:
1004                 device_str = "STM32F7[4|5]x";
1005
1006                 switch (rev_id) {
1007                 case 0x1000:
1008                         rev_str = "A";
1009                         break;
1010
1011                 case 0x1001:
1012                         rev_str = "Z";
1013                         break;
1014                 }
1015                 break;
1016
1017         default:
1018                 snprintf(buf, buf_size, "Cannot identify target as a STM32F2/4/7\n");
1019                 return ERROR_FAIL;
1020         }
1021
1022         if (rev_str != NULL)
1023                 snprintf(buf, buf_size, "%s - Rev: %s", device_str, rev_str);
1024         else
1025                 snprintf(buf, buf_size, "%s - Rev: unknown (0x%04x)", device_str, rev_id);
1026
1027         return ERROR_OK;
1028 }
1029
1030 COMMAND_HANDLER(stm32x_handle_lock_command)
1031 {
1032         struct target *target = NULL;
1033         struct stm32x_flash_bank *stm32x_info = NULL;
1034
1035         if (CMD_ARGC < 1)
1036                 return ERROR_COMMAND_SYNTAX_ERROR;
1037
1038         struct flash_bank *bank;
1039         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1040         if (ERROR_OK != retval)
1041                 return retval;
1042
1043         stm32x_info = bank->driver_priv;
1044         target = bank->target;
1045
1046         if (target->state != TARGET_HALTED) {
1047                 LOG_ERROR("Target not halted");
1048                 return ERROR_TARGET_NOT_HALTED;
1049         }
1050
1051         if (stm32x_read_options(bank) != ERROR_OK) {
1052                 command_print(CMD_CTX, "%s failed to read options", bank->driver->name);
1053                 return ERROR_OK;
1054         }
1055
1056         /* set readout protection */
1057         stm32x_info->option_bytes.RDP = 0;
1058
1059         if (stm32x_write_options(bank) != ERROR_OK) {
1060                 command_print(CMD_CTX, "%s failed to lock device", bank->driver->name);
1061                 return ERROR_OK;
1062         }
1063
1064         command_print(CMD_CTX, "%s locked", bank->driver->name);
1065
1066         return ERROR_OK;
1067 }
1068
1069 COMMAND_HANDLER(stm32x_handle_unlock_command)
1070 {
1071         struct target *target = NULL;
1072         struct stm32x_flash_bank *stm32x_info = NULL;
1073
1074         if (CMD_ARGC < 1)
1075                 return ERROR_COMMAND_SYNTAX_ERROR;
1076
1077         struct flash_bank *bank;
1078         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1079         if (ERROR_OK != retval)
1080                 return retval;
1081
1082         stm32x_info = bank->driver_priv;
1083         target = bank->target;
1084
1085         if (target->state != TARGET_HALTED) {
1086                 LOG_ERROR("Target not halted");
1087                 return ERROR_TARGET_NOT_HALTED;
1088         }
1089
1090         if (stm32x_read_options(bank) != ERROR_OK) {
1091                 command_print(CMD_CTX, "%s failed to read options", bank->driver->name);
1092                 return ERROR_OK;
1093         }
1094
1095         /* clear readout protection and complementary option bytes
1096          * this will also force a device unlock if set */
1097         stm32x_info->option_bytes.RDP = 0xAA;
1098
1099         if (stm32x_write_options(bank) != ERROR_OK) {
1100                 command_print(CMD_CTX, "%s failed to unlock device", bank->driver->name);
1101                 return ERROR_OK;
1102         }
1103
1104         command_print(CMD_CTX, "%s unlocked.\n"
1105                         "INFO: a reset or power cycle is required "
1106                         "for the new settings to take effect.", bank->driver->name);
1107
1108         return ERROR_OK;
1109 }
1110
1111 static int stm32x_mass_erase(struct flash_bank *bank)
1112 {
1113         int retval;
1114         struct target *target = bank->target;
1115         struct stm32x_flash_bank *stm32x_info = NULL;
1116
1117         if (target->state != TARGET_HALTED) {
1118                 LOG_ERROR("Target not halted");
1119                 return ERROR_TARGET_NOT_HALTED;
1120         }
1121
1122         stm32x_info = bank->driver_priv;
1123
1124         retval = stm32x_unlock_reg(target);
1125         if (retval != ERROR_OK)
1126                 return retval;
1127
1128         /* mass erase flash memory */
1129         if (stm32x_info->has_large_mem)
1130                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_MER | FLASH_MER1);
1131         else
1132                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_MER);
1133         if (retval != ERROR_OK)
1134                 return retval;
1135         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
1136                 FLASH_MER | FLASH_STRT);
1137         if (retval != ERROR_OK)
1138                 return retval;
1139
1140         retval = stm32x_wait_status_busy(bank, 30000);
1141         if (retval != ERROR_OK)
1142                 return retval;
1143
1144         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
1145         if (retval != ERROR_OK)
1146                 return retval;
1147
1148         return ERROR_OK;
1149 }
1150
1151 COMMAND_HANDLER(stm32x_handle_mass_erase_command)
1152 {
1153         int i;
1154
1155         if (CMD_ARGC < 1) {
1156                 command_print(CMD_CTX, "stm32x mass_erase <bank>");
1157                 return ERROR_COMMAND_SYNTAX_ERROR;
1158         }
1159
1160         struct flash_bank *bank;
1161         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1162         if (ERROR_OK != retval)
1163                 return retval;
1164
1165         retval = stm32x_mass_erase(bank);
1166         if (retval == ERROR_OK) {
1167                 /* set all sectors as erased */
1168                 for (i = 0; i < bank->num_sectors; i++)
1169                         bank->sectors[i].is_erased = 1;
1170
1171                 command_print(CMD_CTX, "stm32x mass erase complete");
1172         } else {
1173                 command_print(CMD_CTX, "stm32x mass erase failed");
1174         }
1175
1176         return retval;
1177 }
1178
1179 static const struct command_registration stm32x_exec_command_handlers[] = {
1180         {
1181                 .name = "lock",
1182                 .handler = stm32x_handle_lock_command,
1183                 .mode = COMMAND_EXEC,
1184                 .usage = "bank_id",
1185                 .help = "Lock entire flash device.",
1186         },
1187         {
1188                 .name = "unlock",
1189                 .handler = stm32x_handle_unlock_command,
1190                 .mode = COMMAND_EXEC,
1191                 .usage = "bank_id",
1192                 .help = "Unlock entire protected flash device.",
1193         },
1194         {
1195                 .name = "mass_erase",
1196                 .handler = stm32x_handle_mass_erase_command,
1197                 .mode = COMMAND_EXEC,
1198                 .usage = "bank_id",
1199                 .help = "Erase entire flash device.",
1200         },
1201         COMMAND_REGISTRATION_DONE
1202 };
1203
1204 static const struct command_registration stm32x_command_handlers[] = {
1205         {
1206                 .name = "stm32f2x",
1207                 .mode = COMMAND_ANY,
1208                 .help = "stm32f2x flash command group",
1209                 .usage = "",
1210                 .chain = stm32x_exec_command_handlers,
1211         },
1212         COMMAND_REGISTRATION_DONE
1213 };
1214
1215 struct flash_driver stm32f2x_flash = {
1216         .name = "stm32f2x",
1217         .commands = stm32x_command_handlers,
1218         .flash_bank_command = stm32x_flash_bank_command,
1219         .erase = stm32x_erase,
1220         .protect = stm32x_protect,
1221         .write = stm32x_write,
1222         .read = default_flash_read,
1223         .probe = stm32x_probe,
1224         .auto_probe = stm32x_auto_probe,
1225         .erase_check = default_flash_blank_check,
1226         .protect_check = stm32x_protect_check,
1227         .info = get_stm32x_info,
1228 };