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