]> git.sur5r.net Git - openocd/blob - src/flash/nor/stm32f2x.c
flash: stm32f2x incorrectly using 512 as max family size
[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 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29
30 #include "imp.h"
31 #include <helper/binarybuffer.h>
32 #include <target/algorithm.h>
33 #include <target/armv7m.h>
34
35 /* Regarding performance:
36  *
37  * Short story - it might be best to leave the performance at
38  * current levels.
39  *
40  * You may see a jump in speed if you change to using
41  * 32bit words for the block programming.
42  *
43  * Its a shame you cannot use the double word as its
44  * even faster - but you require external VPP for that mode.
45  *
46  * Having said all that 16bit writes give us the widest vdd
47  * operating range, so may be worth adding a note to that effect.
48  *
49  */
50
51 /* Danger!!!! The STM32F1x and STM32F2x series actually have
52  * quite different flash controllers.
53  *
54  * What's more scary is that the names of the registers and their
55  * addresses are the same, but the actual bits and what they do are
56  * can be very different.
57  *
58  * To reduce testing complexity and dangers of regressions,
59  * a seperate file is used for stm32fx2x.
60  *
61  * 1mByte part with 4 x 16, 1 x 64, 7 x 128kBytes sectors
62  *
63  * What's the protection page size???
64  *
65  * Tested with STM3220F-EVAL board.
66  *
67  * STM32F21xx series for reference.
68  *
69  * RM0033
70  * http://www.st.com/internet/mcu/product/250192.jsp
71  *
72  * PM0059
73  * www.st.com/internet/com/TECHNICAL_RESOURCES/TECHNICAL_LITERATURE/PROGRAMMING_MANUAL/CD00233952.pdf
74  *
75  * STM32F1x series - notice that this code was copy, pasted and knocked
76  * into a stm32f2x driver, so in case something has been converted or
77  * bugs haven't been fixed, here are the original manuals:
78  *
79  * RM0008 - Reference manual
80  *
81  * RM0042, the Flash programming manual for low-, medium- high-density and
82  * connectivity line STM32F10x devices
83  *
84  * PM0068, the Flash programming manual for XL-density STM32F10x devices.
85  *
86  */
87
88  // Erase time can be as high as 1000ms, 10x this and it's toast...
89 #define FLASH_ERASE_TIMEOUT 10000
90 #define FLASH_WRITE_TIMEOUT 5
91
92
93 #define STM32_FLASH_BASE        0x40023c00
94 #define STM32_FLASH_ACR         0x40023c00
95 #define STM32_FLASH_KEYR        0x40023c04
96 #define STM32_FLASH_OPTKEYR     0x40023c08
97 #define STM32_FLASH_SR          0x40023c0C
98 #define STM32_FLASH_CR          0x40023c10
99 #define STM32_FLASH_OPTCR       0x40023c14
100 #define STM32_FLASH_OBR         0x40023c1C
101
102
103
104 /* option byte location */
105
106 #define STM32_OB_RDP            0x1FFFF800
107 #define STM32_OB_USER           0x1FFFF802
108 #define STM32_OB_DATA0          0x1FFFF804
109 #define STM32_OB_DATA1          0x1FFFF806
110 #define STM32_OB_WRP0           0x1FFFF808
111 #define STM32_OB_WRP1           0x1FFFF80A
112 #define STM32_OB_WRP2           0x1FFFF80C
113 #define STM32_OB_WRP3           0x1FFFF80E
114
115 /* FLASH_CR register bits */
116
117 #define FLASH_PG                (1 << 0)
118 #define FLASH_SER               (1 << 1)
119 #define FLASH_MER               (1 << 2)
120 #define FLASH_STRT              (1 << 16)
121 #define FLASH_PSIZE_8   (0 << 8)
122 #define FLASH_PSIZE_16  (1 << 8)
123 #define FLASH_PSIZE_32  (2 << 8)
124 #define FLASH_PSIZE_64  (3 << 8)
125 #define FLASH_SNB(a)    ((a) << 3)
126 #define FLASH_LOCK              (1 << 31)
127
128 /* FLASH_SR register bits */
129
130 #define FLASH_BSY               (1 << 16)
131 #define FLASH_PGSERR    (1 << 7) // Programming sequence error
132 #define FLASH_PGPERR    (1 << 6) // Programming parallelism error
133 #define FLASH_PGAERR    (1 << 5) // Programming alignment error
134 #define FLASH_WRPERR    (1 << 4) // Write protection error
135 #define FLASH_OPERR             (1 << 1) // Operation error
136
137 #define FLASH_ERROR (FLASH_PGSERR | FLASH_PGPERR | FLASH_PGAERR| FLASH_WRPERR| FLASH_OPERR)
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
148 /* register unlock keys */
149
150 #define KEY1                    0x45670123
151 #define KEY2                    0xCDEF89AB
152
153 struct stm32x_flash_bank
154 {
155         struct working_area *write_algorithm;
156         int probed;
157 };
158
159
160 /* flash bank stm32x <base> <size> 0 0 <target#>
161  */
162 FLASH_BANK_COMMAND_HANDLER(stm32x_flash_bank_command)
163 {
164         struct stm32x_flash_bank *stm32x_info;
165
166         if (CMD_ARGC < 6)
167         {
168                 return ERROR_COMMAND_SYNTAX_ERROR;
169         }
170
171         stm32x_info = malloc(sizeof(struct stm32x_flash_bank));
172         bank->driver_priv = stm32x_info;
173
174         stm32x_info->write_algorithm = NULL;
175         stm32x_info->probed = 0;
176
177         return ERROR_OK;
178 }
179
180 static inline int stm32x_get_flash_reg(struct flash_bank *bank, uint32_t reg)
181 {
182         return reg;
183 }
184
185 static inline int stm32x_get_flash_status(struct flash_bank *bank, uint32_t *status)
186 {
187         struct target *target = bank->target;
188         return target_read_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR), status);
189 }
190
191 static int stm32x_wait_status_busy(struct flash_bank *bank, int timeout)
192 {
193         struct target *target = bank->target;
194         uint32_t status;
195         int retval = ERROR_OK;
196
197         /* wait for busy to clear */
198         for (;;)
199         {
200                 retval = stm32x_get_flash_status(bank, &status);
201                 if (retval != ERROR_OK)
202                         return retval;
203                 LOG_DEBUG("status: 0x%" PRIx32 "", status);
204                 if ((status & FLASH_BSY) == 0)
205                         break;
206                 if (timeout-- <= 0)
207                 {
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         {
217                 LOG_ERROR("stm32x device protected");
218                 retval = ERROR_FAIL;
219         }
220
221         /* Clear but report errors */
222         if (status & FLASH_ERROR)
223         {
224                 /* If this operation fails, we ignore it and report the original
225                  * retval
226                  */
227                 target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR),
228                                 status & FLASH_ERROR);
229         }
230         return retval;
231 }
232
233 static int stm32x_unlock_reg(struct target *target)
234 {
235         uint32_t ctrl;
236
237         /* first check if not already unlocked
238          * otherwise writing on STM32_FLASH_KEYR will fail
239          */
240         int retval = target_read_u32(target, STM32_FLASH_CR, &ctrl);
241         if (retval != ERROR_OK)
242                 return retval;
243
244         if ((ctrl & FLASH_LOCK) == 0)
245                 return ERROR_OK;
246
247         /* unlock flash registers */
248         retval = target_write_u32(target, STM32_FLASH_KEYR, KEY1);
249         if (retval != ERROR_OK)
250                 return retval;
251
252         retval = target_write_u32(target, STM32_FLASH_KEYR, KEY2);
253         if (retval != ERROR_OK)
254                 return retval;
255
256         retval = target_read_u32(target, STM32_FLASH_CR, &ctrl);
257         if (retval != ERROR_OK)
258                 return retval;
259
260         if (ctrl & FLASH_LOCK) {
261                 LOG_ERROR("flash not unlocked STM32_FLASH_CR: %x", ctrl);
262                 return ERROR_TARGET_FAILURE;
263         }
264
265         return ERROR_OK;
266 }
267
268 static int stm32x_protect_check(struct flash_bank *bank)
269 {
270         return ERROR_OK;
271 }
272
273 static int stm32x_erase(struct flash_bank *bank, int first, int last)
274 {
275         struct target *target = bank->target;
276         int i;
277
278         if (bank->target->state != TARGET_HALTED)
279         {
280                 LOG_ERROR("Target not halted");
281                 return ERROR_TARGET_NOT_HALTED;
282         }
283
284         int retval;
285         retval = stm32x_unlock_reg(target);
286         if (retval != ERROR_OK)
287                 return retval;
288
289         /*
290         Sector Erase
291         To erase a sector, follow the procedure below:
292         1. Check that no Flash memory operation is ongoing by checking the BSY bit in the
293           FLASH_SR register
294         2. Set the SER bit and select the sector (out of the 12 sectors in the main memory block)
295           you wish to erase (SNB) in the FLASH_CR register
296         3. Set the STRT bit in the FLASH_CR register
297         4. Wait for the BSY bit to be cleared
298          */
299
300         for (i = first; i <= last; i++)
301         {
302                 retval = target_write_u32(target,
303                                 stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_SER | FLASH_SNB(i) | FLASH_STRT);
304                 if (retval != ERROR_OK)
305                         return retval;
306
307                 retval = stm32x_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
308                 if (retval != ERROR_OK)
309                         return retval;
310
311                 bank->sectors[i].is_erased = 1;
312         }
313
314         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
315         if (retval != ERROR_OK)
316                 return retval;
317
318         return ERROR_OK;
319 }
320
321 static int stm32x_protect(struct flash_bank *bank, int set, int first, int last)
322 {
323         return ERROR_OK;
324 }
325
326 static int stm32x_write_block(struct flash_bank *bank, uint8_t *buffer,
327                 uint32_t offset, uint32_t count)
328 {
329         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
330         struct target *target = bank->target;
331         uint32_t buffer_size = 16384;
332         struct working_area *source;
333         uint32_t address = bank->base + offset;
334         struct reg_param reg_params[5];
335         struct armv7m_algorithm armv7m_info;
336         int retval = ERROR_OK;
337
338         /* see contrib/loaders/flash/stm32f2x.S for src */
339
340         static const uint16_t stm32x_flash_write_code_16[] = {
341                 /* 00000000 <write>: */
342                 0x4b07,                         /* ldr          r3, [pc, #28] (20 <STM32_PROG16>) */
343                 0x6123,                         /* str          r3, [r4, #16] */
344                 0xf830, 0x3b02,         /* ldrh.w       r3, [r0], #2 */
345                 0xf821, 0x3b02,         /* strh.w       r3, [r1], #2 */
346
347                 /* 0000000c <busy>: */
348                 0x68e3,                         /* ldr          r3, [r4, #12] */
349                 0xf413, 0x3f80,         /* tst.w        r3, #65536      ; 0x10000 */
350                 0xd0fb,                         /* beq.n        c <busy> */
351                 0xf013, 0x0ff0,         /* tst.w        r3, #240        ; 0xf0 */
352                 0xd101,                         /* bne.n        1e <exit> */
353                 0x3a01,                         /* subs         r2, #1 */
354                 0xd1f0,                         /* bne.n        0 <write> */
355                                                         /* 0000001e <exit>: */
356                 0xbe00,                         /* bkpt         0x0000 */
357
358                 /* 00000020 <STM32_PROG16>: */
359                 0x0101, 0x0000,         /* .word        0x00000101 */
360         };
361
362         /* Flip endian */
363         uint8_t stm32x_flash_write_code[sizeof(stm32x_flash_write_code_16)*2];
364         for (unsigned i = 0; i < sizeof(stm32x_flash_write_code_16) / 2; i++)
365         {
366                 stm32x_flash_write_code[i*2 + 0] = stm32x_flash_write_code_16[i] & 0xff;
367                 stm32x_flash_write_code[i*2 + 1] = (stm32x_flash_write_code_16[i] >> 8) & 0xff;
368         }
369
370         if (target_alloc_working_area(target, sizeof(stm32x_flash_write_code),
371                         &stm32x_info->write_algorithm) != ERROR_OK)
372         {
373                 LOG_WARNING("no working area available, can't do block memory writes");
374                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
375         };
376
377         if ((retval = target_write_buffer(target, stm32x_info->write_algorithm->address,
378                         sizeof(stm32x_flash_write_code),
379                         (uint8_t*)stm32x_flash_write_code)) != ERROR_OK)
380                 return retval;
381
382         /* memory buffer */
383         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK)
384         {
385                 buffer_size /= 2;
386                 if (buffer_size <= 256)
387                 {
388                         /* if we already allocated the writing code, but failed to get a
389                          * buffer, free the algorithm */
390                         if (stm32x_info->write_algorithm)
391                                 target_free_working_area(target, stm32x_info->write_algorithm);
392
393                         LOG_WARNING("no large enough working area available, can't do block memory writes");
394                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
395                 }
396         };
397
398         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
399         armv7m_info.core_mode = ARMV7M_MODE_ANY;
400
401         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
402         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
403         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
404         init_reg_param(&reg_params[3], "r3", 32, PARAM_IN_OUT);
405         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);
406
407         while (count > 0)
408         {
409                 uint32_t thisrun_count = (count > (buffer_size / 2)) ?
410                                 (buffer_size / 2) : count;
411
412                 if ((retval = target_write_buffer(target, source->address,
413                                 thisrun_count * 2, buffer)) != ERROR_OK)
414                         break;
415
416                 buf_set_u32(reg_params[0].value, 0, 32, source->address);
417                 buf_set_u32(reg_params[1].value, 0, 32, address);
418                 buf_set_u32(reg_params[2].value, 0, 32, thisrun_count);
419                 // R3 is a return value only
420                 buf_set_u32(reg_params[4].value, 0, 32, STM32_FLASH_BASE);
421
422                 if ((retval = target_run_algorithm(target, 0, NULL,
423                                 sizeof(reg_params) / sizeof(*reg_params),
424                                 reg_params,
425                                 stm32x_info->write_algorithm->address,
426                                 0,
427                                 10000, &armv7m_info)) != ERROR_OK)
428                 {
429                         LOG_ERROR("error executing stm32x flash write algorithm");
430                         break;
431                 }
432
433                 uint32_t error = buf_get_u32(reg_params[3].value, 0, 32) & FLASH_ERROR;
434
435                 if (error & FLASH_WRPERR)
436                 {
437                         LOG_ERROR("flash memory write protected");
438                 }
439
440                 if (error != 0)
441                 {
442                         LOG_ERROR("flash write failed = %08x", error);
443                         /* Clear but report errors */
444                         target_write_u32(target, STM32_FLASH_SR, error);
445                         retval = ERROR_FAIL;
446                         break;
447                 }
448
449                 buffer += thisrun_count * 2;
450                 address += thisrun_count * 2;
451                 count -= thisrun_count;
452         }
453
454         target_free_working_area(target, source);
455         target_free_working_area(target, stm32x_info->write_algorithm);
456
457         destroy_reg_param(&reg_params[0]);
458         destroy_reg_param(&reg_params[1]);
459         destroy_reg_param(&reg_params[2]);
460         destroy_reg_param(&reg_params[3]);
461         destroy_reg_param(&reg_params[4]);
462
463         return retval;
464 }
465
466 static int stm32x_write(struct flash_bank *bank, uint8_t *buffer,
467                 uint32_t offset, uint32_t count)
468 {
469         struct target *target = bank->target;
470         uint32_t words_remaining = (count / 2);
471         uint32_t bytes_remaining = (count & 0x00000001);
472         uint32_t address = bank->base + offset;
473         uint32_t bytes_written = 0;
474         int retval;
475
476         if (bank->target->state != TARGET_HALTED)
477         {
478                 LOG_ERROR("Target not halted");
479                 return ERROR_TARGET_NOT_HALTED;
480         }
481
482         if (offset & 0x1)
483         {
484                 LOG_WARNING("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
485                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
486         }
487
488         retval = stm32x_unlock_reg(target);
489         if (retval != ERROR_OK)
490                 return retval;
491
492         /* multiple half words (2-byte) to be programmed? */
493         if (words_remaining > 0)
494         {
495                 /* try using a block write */
496                 if ((retval = stm32x_write_block(bank, buffer, offset, words_remaining)) != ERROR_OK)
497                 {
498                         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
499                         {
500                                 /* if block write failed (no sufficient working area),
501                                  * we use normal (slow) single dword accesses */
502                                 LOG_WARNING("couldn't use block writes, falling back to single memory accesses");
503                         }
504                 }
505                 else
506                 {
507                         buffer += words_remaining * 2;
508                         address += words_remaining * 2;
509                         words_remaining = 0;
510                 }
511         }
512
513         if ((retval != ERROR_OK) && (retval != ERROR_TARGET_RESOURCE_NOT_AVAILABLE))
514                 return retval;
515
516         /*
517         Standard programming
518         The Flash memory programming sequence is as follows:
519         1. Check that no main Flash memory operation is ongoing by checking the BSY bit in the
520           FLASH_SR register.
521         2. Set the PG bit in the FLASH_CR register
522         3. Perform the data write operation(s) to the desired memory address (inside main
523           memory block or OTP area):
524         â€“ â€“ Half-word access in case of x16 parallelism
525         â€“ Word access in case of x32 parallelism
526         â€“
527         4.
528         Byte access in case of x8 parallelism
529         Double word access in case of x64 parallelism
530         Wait for the BSY bit to be cleared
531         */
532         while (words_remaining > 0)
533         {
534                 uint16_t value;
535                 memcpy(&value, buffer + bytes_written, sizeof(uint16_t));
536
537                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
538                                 FLASH_PG | FLASH_PSIZE_16);
539                 if (retval != ERROR_OK)
540                         return retval;
541
542                 retval = target_write_u16(target, address, value);
543                 if (retval != ERROR_OK)
544                         return retval;
545
546                 retval = stm32x_wait_status_busy(bank, FLASH_WRITE_TIMEOUT);
547                 if (retval != ERROR_OK)
548                         return retval;
549
550                 bytes_written += 2;
551                 words_remaining--;
552                 address += 2;
553         }
554
555         if (bytes_remaining)
556         {
557                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
558                                 FLASH_PG | FLASH_PSIZE_8);
559                 if (retval != ERROR_OK)
560                         return retval;
561                 retval = target_write_u8(target, address, buffer[bytes_written]);
562                 if (retval != ERROR_OK)
563                         return retval;
564
565                 retval = stm32x_wait_status_busy(bank, FLASH_WRITE_TIMEOUT);
566                 if (retval != ERROR_OK)
567                         return retval;
568         }
569
570         return target_write_u32(target, STM32_FLASH_CR, FLASH_LOCK);
571 }
572
573 static void setup_sector(struct flash_bank *bank, int start, int num, int size)
574 {
575         for (int i = start; i < (start + num) ; i++)
576         {
577                 bank->sectors[i].offset = bank->size;
578                 bank->sectors[i].size = size;
579                 bank->size += bank->sectors[i].size;
580         }
581 }
582
583 static int stm32x_get_device_id(struct flash_bank *bank, uint32_t *device_id)
584 {
585         /* this checks for a stm32f4x errata issue where a
586          * stm32f2x DBGMCU_IDCODE is incorrectly returned.
587          * If the issue is detected target is forced to stm32f4x Rev A.
588          * Only effects Rev A silicon */
589
590         struct target *target = bank->target;
591         uint32_t cpuid;
592
593         /* read stm32 device id register */
594         int retval = target_read_u32(target, 0xE0042000, device_id);
595         if (retval != ERROR_OK)
596                 return retval;
597
598         if ((*device_id & DEV_ID_MASK) == 0x411) {
599                 /* read CPUID reg to check core type */
600                 retval = target_read_u32(target, 0xE000ED00, &cpuid);
601                 if (retval != ERROR_OK)
602                         return retval;
603
604                 /* check for cortex_m4 */
605                 if (((cpuid >> 4) & 0xFFF) == 0xC24) {
606                         *device_id &= ~((0xFFFF << 16) | DEV_ID_MASK);
607                         *device_id |= (0x1000 << 16) | 0x413;
608                         LOG_INFO("stm32f4x errata detected - fixing incorrect MCU_IDCODE");
609                 }
610         }
611         return retval;
612 }
613
614 static int stm32x_probe(struct flash_bank *bank)
615 {
616         struct target *target = bank->target;
617         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
618         int i;
619         uint16_t flash_size_in_kb;
620         uint32_t device_id;
621         uint32_t base_address = 0x08000000;
622
623         stm32x_info->probed = 0;
624
625         /* read stm32 device id register */
626         int retval = stm32x_get_device_id(bank, &device_id);
627         if (retval != ERROR_OK)
628                 return retval;
629         LOG_INFO("device id = 0x%08" PRIx32 "", device_id);
630
631         /* get flash size from target. */
632         retval = target_read_u16(target, 0x1FFF7A10, &flash_size_in_kb);
633         if (retval != ERROR_OK) {
634                 LOG_WARNING("failed reading flash size, default to max target family");
635                 /* failed reading flash size, default to max target family */
636                 flash_size_in_kb = 0xffff;
637         }
638
639         if ((device_id & 0xfff) == 0x411) {
640                 /* check for early silicon */
641                 if (flash_size_in_kb == 0xffff) {
642                         /* number of sectors may be incorrrect on early silicon */
643                         LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming 1024k flash");
644                         flash_size_in_kb = 1024;
645                 }
646         } else if ((device_id & 0xfff) == 0x413) {
647                 /* check for early silicon */
648                 if (flash_size_in_kb == 0xffff) {
649                         /* number of sectors may be incorrrect on early silicon */
650                         LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming 1024k flash");
651                         flash_size_in_kb = 1024;
652                 }
653         } else {
654                 LOG_WARNING("Cannot identify target as a STM32 family.");
655                 return ERROR_FAIL;
656         }
657
658         LOG_INFO("flash size = %dkbytes", flash_size_in_kb);
659
660         /* did we assign flash size? */
661         assert(flash_size_in_kb != 0xffff);
662
663         /* calculate numbers of pages */
664         int num_pages = (flash_size_in_kb / 128) + 4;
665
666         /* check that calculation result makes sense */
667         assert(num_pages > 0);
668
669         if (bank->sectors) {
670                 free(bank->sectors);
671                 bank->sectors = NULL;
672         }
673
674         bank->base = base_address;
675         bank->num_sectors = num_pages;
676         bank->sectors = malloc(sizeof(struct flash_sector) * num_pages);
677         bank->size = 0;
678
679         /* fixed memory */
680         setup_sector(bank, 0, 4, 16 * 1024);
681         setup_sector(bank, 4, 1, 64 * 1024);
682
683         /* dynamic memory */
684         setup_sector(bank, 4 + 1, num_pages - 5, 128 * 1024);
685
686         for (i = 0; i < num_pages; i++) {
687                 bank->sectors[i].is_erased = -1;
688                 bank->sectors[i].is_protected = 0;
689         }
690
691         stm32x_info->probed = 1;
692
693         return ERROR_OK;
694 }
695
696 static int stm32x_auto_probe(struct flash_bank *bank)
697 {
698         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
699         if (stm32x_info->probed)
700                 return ERROR_OK;
701         return stm32x_probe(bank);
702 }
703
704 static int get_stm32x_info(struct flash_bank *bank, char *buf, int buf_size)
705 {
706         uint32_t device_id;
707         int printed;
708
709         /* read stm32 device id register */
710         int retval = stm32x_get_device_id(bank, &device_id);
711         if (retval != ERROR_OK)
712                 return retval;
713
714         if ((device_id & 0xfff) == 0x411) {
715                 printed = snprintf(buf, buf_size, "stm32f2x - Rev: ");
716                 buf += printed;
717                 buf_size -= printed;
718
719                 switch (device_id >> 16) {
720                         case 0x1000:
721                                 snprintf(buf, buf_size, "A");
722                                 break;
723
724                         case 0x2000:
725                                 snprintf(buf, buf_size, "B");
726                                 break;
727
728                         case 0x1001:
729                                 snprintf(buf, buf_size, "Z");
730                                 break;
731
732                         case 0x2001:
733                                 snprintf(buf, buf_size, "Y");
734                                 break;
735
736                         default:
737                                 snprintf(buf, buf_size, "unknown");
738                                 break;
739                 }
740         } else if ((device_id & 0xfff) == 0x413) {
741                 printed = snprintf(buf, buf_size, "stm32f4x - Rev: ");
742                 buf += printed;
743                 buf_size -= printed;
744
745                 switch (device_id >> 16) {
746                         case 0x1000:
747                                 snprintf(buf, buf_size, "A");
748                                 break;
749
750                         case 0x1001:
751                                 snprintf(buf, buf_size, "Z");
752                                 break;
753
754                         default:
755                                 snprintf(buf, buf_size, "unknown");
756                                 break;
757                 }
758         } else {
759                 snprintf(buf, buf_size, "Cannot identify target as a stm32x\n");
760                 return ERROR_FAIL;
761         }
762
763         return ERROR_OK;
764 }
765
766 static int stm32x_mass_erase(struct flash_bank *bank)
767 {
768         int retval;
769         struct target *target = bank->target;
770
771         if (target->state != TARGET_HALTED) {
772                 LOG_ERROR("Target not halted");
773                 return ERROR_TARGET_NOT_HALTED;
774         }
775
776         retval = stm32x_unlock_reg(target);
777         if (retval != ERROR_OK)
778                 return retval;
779
780         /* mass erase flash memory */
781         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_MER);
782         if (retval != ERROR_OK)
783                 return retval;
784         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
785                 FLASH_MER | FLASH_STRT);
786         if (retval != ERROR_OK)
787                 return retval;
788
789         retval = stm32x_wait_status_busy(bank, 30000);
790         if (retval != ERROR_OK)
791                 return retval;
792
793         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
794         if (retval != ERROR_OK)
795                 return retval;
796
797         return ERROR_OK;
798 }
799
800 COMMAND_HANDLER(stm32x_handle_mass_erase_command)
801 {
802         int i;
803
804         if (CMD_ARGC < 1) {
805                 command_print(CMD_CTX, "stm32x mass_erase <bank>");
806                 return ERROR_COMMAND_SYNTAX_ERROR;
807         }
808
809         struct flash_bank *bank;
810         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
811         if (ERROR_OK != retval)
812                 return retval;
813
814         retval = stm32x_mass_erase(bank);
815         if (retval == ERROR_OK) {
816                 /* set all sectors as erased */
817                 for (i = 0; i < bank->num_sectors; i++)
818                         bank->sectors[i].is_erased = 1;
819
820                 command_print(CMD_CTX, "stm32x mass erase complete");
821         } else {
822                 command_print(CMD_CTX, "stm32x mass erase failed");
823         }
824
825         return retval;
826 }
827
828 static const struct command_registration stm32x_exec_command_handlers[] = {
829         {
830                 .name = "mass_erase",
831                 .handler = stm32x_handle_mass_erase_command,
832                 .mode = COMMAND_EXEC,
833                 .usage = "bank_id",
834                 .help = "Erase entire flash device.",
835         },
836         COMMAND_REGISTRATION_DONE
837 };
838
839 static const struct command_registration stm32x_command_handlers[] = {
840         {
841                 .name = "stm32f2x",
842                 .mode = COMMAND_ANY,
843                 .help = "stm32f2x flash command group",
844                 .usage = "",
845                 .chain = stm32x_exec_command_handlers,
846         },
847         COMMAND_REGISTRATION_DONE
848 };
849
850 struct flash_driver stm32f2x_flash = {
851         .name = "stm32f2x",
852         .commands = stm32x_command_handlers,
853         .flash_bank_command = stm32x_flash_bank_command,
854         .erase = stm32x_erase,
855         .protect = stm32x_protect,
856         .write = stm32x_write,
857         .read = default_flash_read,
858         .probe = stm32x_probe,
859         .auto_probe = stm32x_auto_probe,
860         .erase_check = default_flash_mem_blank_check,
861         .protect_check = stm32x_protect_check,
862         .info = get_stm32x_info,
863 };