2407977f1110cd8a3804605f7e8e22f26efdc7ec
[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  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, 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_OBR         0x40023c1C
102
103 /* option byte location */
104
105 #define STM32_OB_RDP            0x1FFFF800
106 #define STM32_OB_USER           0x1FFFF802
107 #define STM32_OB_DATA0          0x1FFFF804
108 #define STM32_OB_DATA1          0x1FFFF806
109 #define STM32_OB_WRP0           0x1FFFF808
110 #define STM32_OB_WRP1           0x1FFFF80A
111 #define STM32_OB_WRP2           0x1FFFF80C
112 #define STM32_OB_WRP3           0x1FFFF80E
113
114 /* FLASH_CR register bits */
115
116 #define FLASH_PG                (1 << 0)
117 #define FLASH_SER               (1 << 1)
118 #define FLASH_MER               (1 << 2)
119 #define FLASH_STRT              (1 << 16)
120 #define FLASH_PSIZE_8   (0 << 8)
121 #define FLASH_PSIZE_16  (1 << 8)
122 #define FLASH_PSIZE_32  (2 << 8)
123 #define FLASH_PSIZE_64  (3 << 8)
124 #define FLASH_SNB(a)    ((a) << 3)
125 #define FLASH_LOCK              (1 << 31)
126
127 /* FLASH_SR register bits */
128
129 #define FLASH_BSY               (1 << 16)
130 #define FLASH_PGSERR    (1 << 7) /* Programming sequence error */
131 #define FLASH_PGPERR    (1 << 6) /* Programming parallelism error */
132 #define FLASH_PGAERR    (1 << 5) /* Programming alignment error */
133 #define FLASH_WRPERR    (1 << 4) /* Write protection error */
134 #define FLASH_OPERR             (1 << 1) /* Operation error */
135
136 #define FLASH_ERROR (FLASH_PGSERR | FLASH_PGPERR | FLASH_PGAERR | FLASH_WRPERR | FLASH_OPERR)
137
138 /* STM32_FLASH_OBR bit definitions (reading) */
139
140 #define OPT_ERROR               0
141 #define OPT_READOUT             1
142 #define OPT_RDWDGSW             2
143 #define OPT_RDRSTSTOP   3
144 #define OPT_RDRSTSTDBY  4
145 #define OPT_BFB2                5       /* dual flash bank only */
146
147 /* register unlock keys */
148
149 #define KEY1                    0x45670123
150 #define KEY2                    0xCDEF89AB
151
152 struct stm32x_flash_bank {
153         struct working_area *write_algorithm;
154         int probed;
155 };
156
157
158 /* flash bank stm32x <base> <size> 0 0 <target#>
159  */
160 FLASH_BANK_COMMAND_HANDLER(stm32x_flash_bank_command)
161 {
162         struct stm32x_flash_bank *stm32x_info;
163
164         if (CMD_ARGC < 6)
165                 return ERROR_COMMAND_SYNTAX_ERROR;
166
167         stm32x_info = malloc(sizeof(struct stm32x_flash_bank));
168         bank->driver_priv = stm32x_info;
169
170         stm32x_info->write_algorithm = NULL;
171         stm32x_info->probed = 0;
172
173         return ERROR_OK;
174 }
175
176 static inline int stm32x_get_flash_reg(struct flash_bank *bank, uint32_t reg)
177 {
178         return reg;
179 }
180
181 static inline int stm32x_get_flash_status(struct flash_bank *bank, uint32_t *status)
182 {
183         struct target *target = bank->target;
184         return target_read_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR), status);
185 }
186
187 static int stm32x_wait_status_busy(struct flash_bank *bank, int timeout)
188 {
189         struct target *target = bank->target;
190         uint32_t status;
191         int retval = ERROR_OK;
192
193         /* wait for busy to clear */
194         for (;;) {
195                 retval = stm32x_get_flash_status(bank, &status);
196                 if (retval != ERROR_OK)
197                         return retval;
198                 LOG_DEBUG("status: 0x%" PRIx32 "", status);
199                 if ((status & FLASH_BSY) == 0)
200                         break;
201                 if (timeout-- <= 0) {
202                         LOG_ERROR("timed out waiting for flash");
203                         return ERROR_FAIL;
204                 }
205                 alive_sleep(1);
206         }
207
208
209         if (status & FLASH_WRPERR) {
210                 LOG_ERROR("stm32x device protected");
211                 retval = ERROR_FAIL;
212         }
213
214         /* Clear but report errors */
215         if (status & FLASH_ERROR) {
216                 /* If this operation fails, we ignore it and report the original
217                  * retval
218                  */
219                 target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR),
220                                 status & FLASH_ERROR);
221         }
222         return retval;
223 }
224
225 static int stm32x_unlock_reg(struct target *target)
226 {
227         uint32_t ctrl;
228
229         /* first check if not already unlocked
230          * otherwise writing on STM32_FLASH_KEYR will fail
231          */
232         int retval = target_read_u32(target, STM32_FLASH_CR, &ctrl);
233         if (retval != ERROR_OK)
234                 return retval;
235
236         if ((ctrl & FLASH_LOCK) == 0)
237                 return ERROR_OK;
238
239         /* unlock flash registers */
240         retval = target_write_u32(target, STM32_FLASH_KEYR, KEY1);
241         if (retval != ERROR_OK)
242                 return retval;
243
244         retval = target_write_u32(target, STM32_FLASH_KEYR, KEY2);
245         if (retval != ERROR_OK)
246                 return retval;
247
248         retval = target_read_u32(target, STM32_FLASH_CR, &ctrl);
249         if (retval != ERROR_OK)
250                 return retval;
251
252         if (ctrl & FLASH_LOCK) {
253                 LOG_ERROR("flash not unlocked STM32_FLASH_CR: %x", ctrl);
254                 return ERROR_TARGET_FAILURE;
255         }
256
257         return ERROR_OK;
258 }
259
260 static int stm32x_protect_check(struct flash_bank *bank)
261 {
262         return ERROR_OK;
263 }
264
265 static int stm32x_erase(struct flash_bank *bank, int first, int last)
266 {
267         struct target *target = bank->target;
268         int i;
269
270         if (bank->target->state != TARGET_HALTED) {
271                 LOG_ERROR("Target not halted");
272                 return ERROR_TARGET_NOT_HALTED;
273         }
274
275         int retval;
276         retval = stm32x_unlock_reg(target);
277         if (retval != ERROR_OK)
278                 return retval;
279
280         /*
281         Sector Erase
282         To erase a sector, follow the procedure below:
283         1. Check that no Flash memory operation is ongoing by checking the BSY bit in the
284           FLASH_SR register
285         2. Set the SER bit and select the sector (out of the 12 sectors in the main memory block)
286           you wish to erase (SNB) in the FLASH_CR register
287         3. Set the STRT bit in the FLASH_CR register
288         4. Wait for the BSY bit to be cleared
289          */
290
291         for (i = first; i <= last; i++) {
292                 retval = target_write_u32(target,
293                                 stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_SER | FLASH_SNB(i) | FLASH_STRT);
294                 if (retval != ERROR_OK)
295                         return retval;
296
297                 retval = stm32x_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
298                 if (retval != ERROR_OK)
299                         return retval;
300
301                 bank->sectors[i].is_erased = 1;
302         }
303
304         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
305         if (retval != ERROR_OK)
306                 return retval;
307
308         return ERROR_OK;
309 }
310
311 static int stm32x_protect(struct flash_bank *bank, int set, int first, int last)
312 {
313         return ERROR_OK;
314 }
315
316 static int stm32x_write_block(struct flash_bank *bank, uint8_t *buffer,
317                 uint32_t offset, uint32_t count)
318 {
319         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
320         struct target *target = bank->target;
321         uint32_t buffer_size = 16384;
322         struct working_area *source;
323         uint32_t address = bank->base + offset;
324         struct reg_param reg_params[5];
325         struct armv7m_algorithm armv7m_info;
326         int retval = ERROR_OK;
327
328         /* see contrib/loaders/flash/stm32f2x.S for src */
329
330         static const uint8_t stm32x_flash_write_code[] = {
331                                                                         /* wait_fifo: */
332                 0xD0, 0xF8, 0x00, 0x80,         /* ldr          r8, [r0, #0] */
333                 0xB8, 0xF1, 0x00, 0x0F,         /* cmp          r8, #0 */
334                 0x1A, 0xD0,                                     /* beq          exit */
335                 0x47, 0x68,                                     /* ldr          r7, [r0, #4] */
336                 0x47, 0x45,                                     /* cmp          r7, r8 */
337                 0xF7, 0xD0,                                     /* beq          wait_fifo */
338
339                 0xDF, 0xF8, 0x30, 0x60,         /* ldr          r6, STM32_PROG16 */
340                 0x26, 0x61,                                     /* str          r6, [r4, #STM32_FLASH_CR_OFFSET] */
341                 0x37, 0xF8, 0x02, 0x6B,         /* ldrh         r6, [r7], #0x02 */
342                 0x22, 0xF8, 0x02, 0x6B,         /* strh         r6, [r2], #0x02 */
343                                                                         /* busy: */
344                 0xE6, 0x68,                                     /* ldr          r6, [r4, #STM32_FLASH_SR_OFFSET] */
345                 0x16, 0xF4, 0x80, 0x3F,         /* tst          r6, #0x10000 */
346                 0xFB, 0xD1,                                     /* bne          busy */
347                 0x16, 0xF0, 0xF0, 0x0F,         /* tst          r6, #0xf0 */
348                 0x07, 0xD1,                                     /* bne          error */
349
350                 0x8F, 0x42,                                     /* cmp          r7, r1 */
351                 0x28, 0xBF,                                     /* it           cs */
352                 0x00, 0xF1, 0x08, 0x07,         /* addcs        r7, r0, #8 */
353                 0x47, 0x60,                                     /* str          r7, [r0, #4] */
354                 0x01, 0x3B,                                     /* subs         r3, r3, #1 */
355                 0x13, 0xB1,                                     /* cbz          r3, exit */
356                 0xE1, 0xE7,                                     /* b            wait_fifo */
357                                                                         /* error: */
358                 0x00, 0x21,                                     /* movs         r1, #0 */
359                 0x41, 0x60,                                     /* str          r1, [r0, #4] */
360                                                                         /* exit: */
361                 0x30, 0x46,                                     /* mov          r0, r6 */
362                 0x00, 0xBE,                                     /* bkpt         #0x00 */
363
364                 /* <STM32_PROG16>: */
365                 0x01, 0x01, 0x00, 0x00,         /* .word        0x00000101 */
366         };
367
368         if (target_alloc_working_area(target, sizeof(stm32x_flash_write_code),
369                         &stm32x_info->write_algorithm) != ERROR_OK) {
370                 LOG_WARNING("no working area available, can't do block memory writes");
371                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
372         };
373
374         retval = target_write_buffer(target, stm32x_info->write_algorithm->address,
375                         sizeof(stm32x_flash_write_code),
376                         (uint8_t *)stm32x_flash_write_code);
377         if (retval != ERROR_OK)
378                 return retval;
379
380         /* memory buffer */
381         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) {
382                 buffer_size /= 2;
383                 if (buffer_size <= 256) {
384                         /* if we already allocated the writing code, but failed to get a
385                          * buffer, free the algorithm */
386                         if (stm32x_info->write_algorithm)
387                                 target_free_working_area(target, stm32x_info->write_algorithm);
388
389                         LOG_WARNING("no large enough working area available, can't do block memory writes");
390                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
391                 }
392         };
393
394         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
395         armv7m_info.core_mode = ARMV7M_MODE_ANY;
396
397         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT);         /* buffer start, status (out) */
398         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);            /* buffer end */
399         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);            /* target address */
400         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);            /* count (halfword-16bit) */
401         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);            /* flash base */
402
403         buf_set_u32(reg_params[0].value, 0, 32, source->address);
404         buf_set_u32(reg_params[1].value, 0, 32, source->address + source->size);
405         buf_set_u32(reg_params[2].value, 0, 32, address);
406         buf_set_u32(reg_params[3].value, 0, 32, count);
407         buf_set_u32(reg_params[4].value, 0, 32, STM32_FLASH_BASE);
408
409         retval = target_run_flash_async_algorithm(target, buffer, count, 2,
410                         0, NULL,
411                         5, reg_params,
412                         source->address, source->size,
413                         stm32x_info->write_algorithm->address, 0,
414                         &armv7m_info);
415
416         if (retval == ERROR_FLASH_OPERATION_FAILED) {
417                 LOG_ERROR("error executing stm32x flash write algorithm");
418
419                 uint32_t error = buf_get_u32(reg_params[0].value, 0, 32) & FLASH_ERROR;
420
421                 if (error & FLASH_WRPERR)
422                         LOG_ERROR("flash memory write protected");
423
424                 if (error != 0) {
425                         LOG_ERROR("flash write failed = %08x", error);
426                         /* Clear but report errors */
427                         target_write_u32(target, STM32_FLASH_SR, error);
428                         retval = ERROR_FAIL;
429                 }
430         }
431
432         target_free_working_area(target, source);
433         target_free_working_area(target, stm32x_info->write_algorithm);
434
435         destroy_reg_param(&reg_params[0]);
436         destroy_reg_param(&reg_params[1]);
437         destroy_reg_param(&reg_params[2]);
438         destroy_reg_param(&reg_params[3]);
439         destroy_reg_param(&reg_params[4]);
440
441         return retval;
442 }
443
444 static int stm32x_write(struct flash_bank *bank, uint8_t *buffer,
445                 uint32_t offset, uint32_t count)
446 {
447         struct target *target = bank->target;
448         uint32_t words_remaining = (count / 2);
449         uint32_t bytes_remaining = (count & 0x00000001);
450         uint32_t address = bank->base + offset;
451         uint32_t bytes_written = 0;
452         int retval;
453
454         if (bank->target->state != TARGET_HALTED) {
455                 LOG_ERROR("Target not halted");
456                 return ERROR_TARGET_NOT_HALTED;
457         }
458
459         if (offset & 0x1) {
460                 LOG_WARNING("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
461                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
462         }
463
464         retval = stm32x_unlock_reg(target);
465         if (retval != ERROR_OK)
466                 return retval;
467
468         /* multiple half words (2-byte) to be programmed? */
469         if (words_remaining > 0) {
470                 /* try using a block write */
471                 retval = stm32x_write_block(bank, buffer, offset, words_remaining);
472                 if (retval != ERROR_OK) {
473                         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
474                                 /* if block write failed (no sufficient working area),
475                                  * we use normal (slow) single dword accesses */
476                                 LOG_WARNING("couldn't use block writes, falling back to single memory accesses");
477                         }
478                 } else {
479                         buffer += words_remaining * 2;
480                         address += words_remaining * 2;
481                         words_remaining = 0;
482                 }
483         }
484
485         if ((retval != ERROR_OK) && (retval != ERROR_TARGET_RESOURCE_NOT_AVAILABLE))
486                 return retval;
487
488         /*
489         Standard programming
490         The Flash memory programming sequence is as follows:
491         1. Check that no main Flash memory operation is ongoing by checking the BSY bit in the
492           FLASH_SR register.
493         2. Set the PG bit in the FLASH_CR register
494         3. Perform the data write operation(s) to the desired memory address (inside main
495           memory block or OTP area):
496         â€“ â€“ Half-word access in case of x16 parallelism
497         â€“ Word access in case of x32 parallelism
498         â€“
499         4.
500         Byte access in case of x8 parallelism
501         Double word access in case of x64 parallelism
502         Wait for the BSY bit to be cleared
503         */
504         while (words_remaining > 0) {
505                 uint16_t value;
506                 memcpy(&value, buffer + bytes_written, sizeof(uint16_t));
507
508                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
509                                 FLASH_PG | FLASH_PSIZE_16);
510                 if (retval != ERROR_OK)
511                         return retval;
512
513                 retval = target_write_u16(target, address, value);
514                 if (retval != ERROR_OK)
515                         return retval;
516
517                 retval = stm32x_wait_status_busy(bank, FLASH_WRITE_TIMEOUT);
518                 if (retval != ERROR_OK)
519                         return retval;
520
521                 bytes_written += 2;
522                 words_remaining--;
523                 address += 2;
524         }
525
526         if (bytes_remaining) {
527                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
528                                 FLASH_PG | FLASH_PSIZE_8);
529                 if (retval != ERROR_OK)
530                         return retval;
531                 retval = target_write_u8(target, address, buffer[bytes_written]);
532                 if (retval != ERROR_OK)
533                         return retval;
534
535                 retval = stm32x_wait_status_busy(bank, FLASH_WRITE_TIMEOUT);
536                 if (retval != ERROR_OK)
537                         return retval;
538         }
539
540         return target_write_u32(target, STM32_FLASH_CR, FLASH_LOCK);
541 }
542
543 static void setup_sector(struct flash_bank *bank, int start, int num, int size)
544 {
545         for (int i = start; i < (start + num) ; i++) {
546                 bank->sectors[i].offset = bank->size;
547                 bank->sectors[i].size = size;
548                 bank->size += bank->sectors[i].size;
549         }
550 }
551
552 static int stm32x_get_device_id(struct flash_bank *bank, uint32_t *device_id)
553 {
554         /* this checks for a stm32f4x errata issue where a
555          * stm32f2x DBGMCU_IDCODE is incorrectly returned.
556          * If the issue is detected target is forced to stm32f4x Rev A.
557          * Only effects Rev A silicon */
558
559         struct target *target = bank->target;
560         uint32_t cpuid;
561
562         /* read stm32 device id register */
563         int retval = target_read_u32(target, 0xE0042000, device_id);
564         if (retval != ERROR_OK)
565                 return retval;
566
567         if ((*device_id & 0xfff) == 0x411) {
568                 /* read CPUID reg to check core type */
569                 retval = target_read_u32(target, 0xE000ED00, &cpuid);
570                 if (retval != ERROR_OK)
571                         return retval;
572
573                 /* check for cortex_m4 */
574                 if (((cpuid >> 4) & 0xFFF) == 0xC24) {
575                         *device_id &= ~((0xFFFF << 16) | 0xfff);
576                         *device_id |= (0x1000 << 16) | 0x413;
577                         LOG_INFO("stm32f4x errata detected - fixing incorrect MCU_IDCODE");
578                 }
579         }
580         return retval;
581 }
582
583 static int stm32x_probe(struct flash_bank *bank)
584 {
585         struct target *target = bank->target;
586         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
587         int i;
588         uint16_t flash_size_in_kb;
589         uint16_t max_flash_size_in_kb;
590         uint32_t device_id;
591         uint32_t base_address = 0x08000000;
592
593         stm32x_info->probed = 0;
594
595         /* read stm32 device id register */
596         int retval = stm32x_get_device_id(bank, &device_id);
597         if (retval != ERROR_OK)
598                 return retval;
599         LOG_INFO("device id = 0x%08" PRIx32 "", device_id);
600
601         /* set max flash size depending on family */
602         switch (device_id & 0xfff) {
603         case 0x411:
604         case 0x413:
605                 max_flash_size_in_kb = 1024;
606                 break;
607         default:
608                 LOG_WARNING("Cannot identify target as a STM32 family.");
609                 return ERROR_FAIL;
610         }
611
612         /* get flash size from target. */
613         retval = target_read_u16(target, 0x1FFF7A22, &flash_size_in_kb);
614
615         /* failed reading flash size or flash size invalid (early silicon),
616          * default to max target family */
617         if (retval != ERROR_OK || flash_size_in_kb == 0xffff || flash_size_in_kb == 0) {
618                 LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming %dk flash",
619                         max_flash_size_in_kb);
620                 flash_size_in_kb = max_flash_size_in_kb;
621         }
622
623         LOG_INFO("flash size = %dkbytes", flash_size_in_kb);
624
625         /* did we assign flash size? */
626         assert(flash_size_in_kb != 0xffff);
627
628         /* calculate numbers of pages */
629         int num_pages = (flash_size_in_kb / 128) + 4;
630
631         /* check that calculation result makes sense */
632         assert(num_pages > 0);
633
634         if (bank->sectors) {
635                 free(bank->sectors);
636                 bank->sectors = NULL;
637         }
638
639         bank->base = base_address;
640         bank->num_sectors = num_pages;
641         bank->sectors = malloc(sizeof(struct flash_sector) * num_pages);
642         bank->size = 0;
643
644         /* fixed memory */
645         setup_sector(bank, 0, 4, 16 * 1024);
646         setup_sector(bank, 4, 1, 64 * 1024);
647
648         /* dynamic memory */
649         setup_sector(bank, 4 + 1, num_pages - 5, 128 * 1024);
650
651         for (i = 0; i < num_pages; i++) {
652                 bank->sectors[i].is_erased = -1;
653                 bank->sectors[i].is_protected = 0;
654         }
655
656         stm32x_info->probed = 1;
657
658         return ERROR_OK;
659 }
660
661 static int stm32x_auto_probe(struct flash_bank *bank)
662 {
663         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
664         if (stm32x_info->probed)
665                 return ERROR_OK;
666         return stm32x_probe(bank);
667 }
668
669 static int get_stm32x_info(struct flash_bank *bank, char *buf, int buf_size)
670 {
671         uint32_t device_id;
672         int printed;
673
674         /* read stm32 device id register */
675         int retval = stm32x_get_device_id(bank, &device_id);
676         if (retval != ERROR_OK)
677                 return retval;
678
679         if ((device_id & 0xfff) == 0x411) {
680                 printed = snprintf(buf, buf_size, "stm32f2x - Rev: ");
681                 buf += printed;
682                 buf_size -= printed;
683
684                 switch (device_id >> 16) {
685                         case 0x1000:
686                                 snprintf(buf, buf_size, "A");
687                                 break;
688
689                         case 0x2000:
690                                 snprintf(buf, buf_size, "B");
691                                 break;
692
693                         case 0x1001:
694                                 snprintf(buf, buf_size, "Z");
695                                 break;
696
697                         case 0x2001:
698                                 snprintf(buf, buf_size, "Y");
699                                 break;
700
701                         default:
702                                 snprintf(buf, buf_size, "unknown");
703                                 break;
704                 }
705         } else if ((device_id & 0xfff) == 0x413) {
706                 printed = snprintf(buf, buf_size, "stm32f4x - Rev: ");
707                 buf += printed;
708                 buf_size -= printed;
709
710                 switch (device_id >> 16) {
711                         case 0x1000:
712                                 snprintf(buf, buf_size, "A");
713                                 break;
714
715                         case 0x1001:
716                                 snprintf(buf, buf_size, "Z");
717                                 break;
718
719                         default:
720                                 snprintf(buf, buf_size, "unknown");
721                                 break;
722                 }
723         } else {
724                 snprintf(buf, buf_size, "Cannot identify target as a stm32x\n");
725                 return ERROR_FAIL;
726         }
727
728         return ERROR_OK;
729 }
730
731 static int stm32x_mass_erase(struct flash_bank *bank)
732 {
733         int retval;
734         struct target *target = bank->target;
735
736         if (target->state != TARGET_HALTED) {
737                 LOG_ERROR("Target not halted");
738                 return ERROR_TARGET_NOT_HALTED;
739         }
740
741         retval = stm32x_unlock_reg(target);
742         if (retval != ERROR_OK)
743                 return retval;
744
745         /* mass erase flash memory */
746         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_MER);
747         if (retval != ERROR_OK)
748                 return retval;
749         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
750                 FLASH_MER | FLASH_STRT);
751         if (retval != ERROR_OK)
752                 return retval;
753
754         retval = stm32x_wait_status_busy(bank, 30000);
755         if (retval != ERROR_OK)
756                 return retval;
757
758         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
759         if (retval != ERROR_OK)
760                 return retval;
761
762         return ERROR_OK;
763 }
764
765 COMMAND_HANDLER(stm32x_handle_mass_erase_command)
766 {
767         int i;
768
769         if (CMD_ARGC < 1) {
770                 command_print(CMD_CTX, "stm32x mass_erase <bank>");
771                 return ERROR_COMMAND_SYNTAX_ERROR;
772         }
773
774         struct flash_bank *bank;
775         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
776         if (ERROR_OK != retval)
777                 return retval;
778
779         retval = stm32x_mass_erase(bank);
780         if (retval == ERROR_OK) {
781                 /* set all sectors as erased */
782                 for (i = 0; i < bank->num_sectors; i++)
783                         bank->sectors[i].is_erased = 1;
784
785                 command_print(CMD_CTX, "stm32x mass erase complete");
786         } else {
787                 command_print(CMD_CTX, "stm32x mass erase failed");
788         }
789
790         return retval;
791 }
792
793 static const struct command_registration stm32x_exec_command_handlers[] = {
794         {
795                 .name = "mass_erase",
796                 .handler = stm32x_handle_mass_erase_command,
797                 .mode = COMMAND_EXEC,
798                 .usage = "bank_id",
799                 .help = "Erase entire flash device.",
800         },
801         COMMAND_REGISTRATION_DONE
802 };
803
804 static const struct command_registration stm32x_command_handlers[] = {
805         {
806                 .name = "stm32f2x",
807                 .mode = COMMAND_ANY,
808                 .help = "stm32f2x flash command group",
809                 .usage = "",
810                 .chain = stm32x_exec_command_handlers,
811         },
812         COMMAND_REGISTRATION_DONE
813 };
814
815 struct flash_driver stm32f2x_flash = {
816         .name = "stm32f2x",
817         .commands = stm32x_command_handlers,
818         .flash_bank_command = stm32x_flash_bank_command,
819         .erase = stm32x_erase,
820         .protect = stm32x_protect,
821         .write = stm32x_write,
822         .read = default_flash_read,
823         .probe = stm32x_probe,
824         .auto_probe = stm32x_auto_probe,
825         .erase_check = default_flash_blank_check,
826         .protect_check = stm32x_protect_check,
827         .info = get_stm32x_info,
828 };