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