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