9d093607fd1f315964732c39db44ca8f149f7365
[fw/openocd] / src / flash / nor / stm32f1x.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 by Andreas Fritiofson                              *
9  *   andreas.fritiofson@gmail.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 /* stm32x register locations */
37
38 #define FLASH_REG_BASE_B0 0x40022000
39 #define FLASH_REG_BASE_B1 0x40022040
40
41 #define STM32_FLASH_ACR     0x00
42 #define STM32_FLASH_KEYR    0x04
43 #define STM32_FLASH_OPTKEYR 0x08
44 #define STM32_FLASH_SR      0x0C
45 #define STM32_FLASH_CR      0x10
46 #define STM32_FLASH_AR      0x14
47 #define STM32_FLASH_OBR     0x1C
48 #define STM32_FLASH_WRPR    0x20
49
50 /* TODO: Check if code using these really should be hard coded to bank 0.
51  * There are valid cases, on dual flash devices the protection of the
52  * second bank is done on the bank0 reg's. */
53 #define STM32_FLASH_ACR_B0     0x40022000
54 #define STM32_FLASH_KEYR_B0    0x40022004
55 #define STM32_FLASH_OPTKEYR_B0 0x40022008
56 #define STM32_FLASH_SR_B0      0x4002200C
57 #define STM32_FLASH_CR_B0      0x40022010
58 #define STM32_FLASH_AR_B0      0x40022014
59 #define STM32_FLASH_OBR_B0     0x4002201C
60 #define STM32_FLASH_WRPR_B0    0x40022020
61
62 /* option byte location */
63
64 #define STM32_OB_RDP            0x1FFFF800
65 #define STM32_OB_USER           0x1FFFF802
66 #define STM32_OB_DATA0          0x1FFFF804
67 #define STM32_OB_DATA1          0x1FFFF806
68 #define STM32_OB_WRP0           0x1FFFF808
69 #define STM32_OB_WRP1           0x1FFFF80A
70 #define STM32_OB_WRP2           0x1FFFF80C
71 #define STM32_OB_WRP3           0x1FFFF80E
72
73 /* FLASH_CR register bits */
74
75 #define FLASH_PG                (1 << 0)
76 #define FLASH_PER               (1 << 1)
77 #define FLASH_MER               (1 << 2)
78 #define FLASH_OPTPG             (1 << 4)
79 #define FLASH_OPTER             (1 << 5)
80 #define FLASH_STRT              (1 << 6)
81 #define FLASH_LOCK              (1 << 7)
82 #define FLASH_OPTWRE    (1 << 9)
83
84 /* FLASH_SR register bits */
85
86 #define FLASH_BSY               (1 << 0)
87 #define FLASH_PGERR             (1 << 2)
88 #define FLASH_WRPRTERR  (1 << 4)
89 #define FLASH_EOP               (1 << 5)
90
91 /* STM32_FLASH_OBR bit definitions (reading) */
92
93 #define OPT_ERROR               0
94 #define OPT_READOUT             1
95 #define OPT_RDWDGSW             2
96 #define OPT_RDRSTSTOP   3
97 #define OPT_RDRSTSTDBY  4
98 #define OPT_BFB2                5       /* dual flash bank only */
99
100 /* register unlock keys */
101
102 #define KEY1                    0x45670123
103 #define KEY2                    0xCDEF89AB
104
105 struct stm32x_options {
106         uint16_t RDP;
107         uint16_t user_options;
108         uint16_t protection[4];
109 };
110
111 struct stm32x_flash_bank {
112         struct stm32x_options option_bytes;
113         int ppage_size;
114         int probed;
115
116         bool has_dual_banks;
117         /* used to access dual flash bank stm32xl */
118         uint32_t register_base;
119 };
120
121 static int stm32x_mass_erase(struct flash_bank *bank);
122 static int stm32x_get_device_id(struct flash_bank *bank, uint32_t *device_id);
123
124 /* flash bank stm32x <base> <size> 0 0 <target#>
125  */
126 FLASH_BANK_COMMAND_HANDLER(stm32x_flash_bank_command)
127 {
128         struct stm32x_flash_bank *stm32x_info;
129
130         if (CMD_ARGC < 6)
131                 return ERROR_COMMAND_SYNTAX_ERROR;
132
133         stm32x_info = malloc(sizeof(struct stm32x_flash_bank));
134
135         bank->driver_priv = stm32x_info;
136         stm32x_info->probed = 0;
137         stm32x_info->has_dual_banks = false;
138         stm32x_info->register_base = FLASH_REG_BASE_B0;
139
140         return ERROR_OK;
141 }
142
143 static inline int stm32x_get_flash_reg(struct flash_bank *bank, uint32_t reg)
144 {
145         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
146         return reg + stm32x_info->register_base;
147 }
148
149 static inline int stm32x_get_flash_status(struct flash_bank *bank, uint32_t *status)
150 {
151         struct target *target = bank->target;
152         return target_read_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR), status);
153 }
154
155 static int stm32x_wait_status_busy(struct flash_bank *bank, int timeout)
156 {
157         struct target *target = bank->target;
158         uint32_t status;
159         int retval = ERROR_OK;
160
161         /* wait for busy to clear */
162         for (;;) {
163                 retval = stm32x_get_flash_status(bank, &status);
164                 if (retval != ERROR_OK)
165                         return retval;
166                 LOG_DEBUG("status: 0x%" PRIx32 "", status);
167                 if ((status & FLASH_BSY) == 0)
168                         break;
169                 if (timeout-- <= 0) {
170                         LOG_ERROR("timed out waiting for flash");
171                         return ERROR_FAIL;
172                 }
173                 alive_sleep(1);
174         }
175
176         if (status & FLASH_WRPRTERR) {
177                 LOG_ERROR("stm32x device protected");
178                 retval = ERROR_FAIL;
179         }
180
181         if (status & FLASH_PGERR) {
182                 LOG_ERROR("stm32x device programming failed");
183                 retval = ERROR_FAIL;
184         }
185
186         /* Clear but report errors */
187         if (status & (FLASH_WRPRTERR | FLASH_PGERR)) {
188                 /* If this operation fails, we ignore it and report the original
189                  * retval
190                  */
191                 target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR),
192                                 FLASH_WRPRTERR | FLASH_PGERR);
193         }
194         return retval;
195 }
196
197 int stm32x_check_operation_supported(struct flash_bank *bank)
198 {
199         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
200
201         /* if we have a dual flash bank device then
202          * we need to perform option byte stuff on bank0 only */
203         if (stm32x_info->register_base != FLASH_REG_BASE_B0) {
204                 LOG_ERROR("Option Byte Operation's must use bank0");
205                 return ERROR_FLASH_OPERATION_FAILED;
206         }
207
208         return ERROR_OK;
209 }
210
211 static int stm32x_read_options(struct flash_bank *bank)
212 {
213         uint32_t optiondata;
214         struct stm32x_flash_bank *stm32x_info = NULL;
215         struct target *target = bank->target;
216
217         stm32x_info = bank->driver_priv;
218
219         /* read current option bytes */
220         int retval = target_read_u32(target, STM32_FLASH_OBR_B0, &optiondata);
221         if (retval != ERROR_OK)
222                 return retval;
223
224         stm32x_info->option_bytes.user_options = (uint16_t)0xFFF8 | ((optiondata >> 2) & 0x07);
225         stm32x_info->option_bytes.RDP = (optiondata & (1 << OPT_READOUT)) ? 0xFFFF : 0x5AA5;
226
227         if (optiondata & (1 << OPT_READOUT))
228                 LOG_INFO("Device Security Bit Set");
229
230         /* each bit refers to a 4bank protection */
231         retval = target_read_u32(target, STM32_FLASH_WRPR_B0, &optiondata);
232         if (retval != ERROR_OK)
233                 return retval;
234
235         stm32x_info->option_bytes.protection[0] = (uint16_t)optiondata;
236         stm32x_info->option_bytes.protection[1] = (uint16_t)(optiondata >> 8);
237         stm32x_info->option_bytes.protection[2] = (uint16_t)(optiondata >> 16);
238         stm32x_info->option_bytes.protection[3] = (uint16_t)(optiondata >> 24);
239
240         return ERROR_OK;
241 }
242
243 static int stm32x_erase_options(struct flash_bank *bank)
244 {
245         struct stm32x_flash_bank *stm32x_info = NULL;
246         struct target *target = bank->target;
247
248         stm32x_info = bank->driver_priv;
249
250         /* stlink is currently does not support 16bit
251          * read/writes. so we cannot write option bytes */
252         struct armv7m_common *armv7m = target_to_armv7m(target);
253         if (armv7m && armv7m->stlink) {
254                 LOG_ERROR("Option bytes currently unsupported for stlink");
255                 return ERROR_FAIL;
256         }
257
258         /* read current options */
259         stm32x_read_options(bank);
260
261         /* unlock flash registers */
262         int retval = target_write_u32(target, STM32_FLASH_KEYR_B0, KEY1);
263         if (retval != ERROR_OK)
264                 return retval;
265
266         retval = target_write_u32(target, STM32_FLASH_KEYR_B0, KEY2);
267         if (retval != ERROR_OK)
268                 return retval;
269
270         /* unlock option flash registers */
271         retval = target_write_u32(target, STM32_FLASH_OPTKEYR_B0, KEY1);
272         if (retval != ERROR_OK)
273                 return retval;
274         retval = target_write_u32(target, STM32_FLASH_OPTKEYR_B0, KEY2);
275         if (retval != ERROR_OK)
276                 return retval;
277
278         /* erase option bytes */
279         retval = target_write_u32(target, STM32_FLASH_CR_B0, FLASH_OPTER | FLASH_OPTWRE);
280         if (retval != ERROR_OK)
281                 return retval;
282         retval = target_write_u32(target, STM32_FLASH_CR_B0, FLASH_OPTER | FLASH_STRT | FLASH_OPTWRE);
283         if (retval != ERROR_OK)
284                 return retval;
285
286         retval = stm32x_wait_status_busy(bank, 10);
287         if (retval != ERROR_OK)
288                 return retval;
289
290         /* clear readout protection and complementary option bytes
291          * this will also force a device unlock if set */
292         stm32x_info->option_bytes.RDP = 0x5AA5;
293
294         return ERROR_OK;
295 }
296
297 static int stm32x_write_options(struct flash_bank *bank)
298 {
299         struct stm32x_flash_bank *stm32x_info = NULL;
300         struct target *target = bank->target;
301
302         stm32x_info = bank->driver_priv;
303
304         /* unlock flash registers */
305         int retval = target_write_u32(target, STM32_FLASH_KEYR_B0, KEY1);
306         if (retval != ERROR_OK)
307                 return retval;
308         retval = target_write_u32(target, STM32_FLASH_KEYR_B0, KEY2);
309         if (retval != ERROR_OK)
310                 return retval;
311
312         /* unlock option flash registers */
313         retval = target_write_u32(target, STM32_FLASH_OPTKEYR_B0, KEY1);
314         if (retval != ERROR_OK)
315                 return retval;
316         retval = target_write_u32(target, STM32_FLASH_OPTKEYR_B0, KEY2);
317         if (retval != ERROR_OK)
318                 return retval;
319
320         /* program option bytes */
321         retval = target_write_u32(target, STM32_FLASH_CR_B0, FLASH_OPTPG | FLASH_OPTWRE);
322         if (retval != ERROR_OK)
323                 return retval;
324
325         /* write user option byte */
326         retval = target_write_u16(target, STM32_OB_USER, stm32x_info->option_bytes.user_options);
327         if (retval != ERROR_OK)
328                 return retval;
329
330         retval = stm32x_wait_status_busy(bank, 10);
331         if (retval != ERROR_OK)
332                 return retval;
333
334         /* write protection byte 1 */
335         retval = target_write_u16(target, STM32_OB_WRP0, stm32x_info->option_bytes.protection[0]);
336         if (retval != ERROR_OK)
337                 return retval;
338
339         retval = stm32x_wait_status_busy(bank, 10);
340         if (retval != ERROR_OK)
341                 return retval;
342
343         /* write protection byte 2 */
344         retval = target_write_u16(target, STM32_OB_WRP1, stm32x_info->option_bytes.protection[1]);
345         if (retval != ERROR_OK)
346                 return retval;
347
348         retval = stm32x_wait_status_busy(bank, 10);
349         if (retval != ERROR_OK)
350                 return retval;
351
352         /* write protection byte 3 */
353         retval = target_write_u16(target, STM32_OB_WRP2, stm32x_info->option_bytes.protection[2]);
354         if (retval != ERROR_OK)
355                 return retval;
356
357         retval = stm32x_wait_status_busy(bank, 10);
358         if (retval != ERROR_OK)
359                 return retval;
360
361         /* write protection byte 4 */
362         retval = target_write_u16(target, STM32_OB_WRP3, stm32x_info->option_bytes.protection[3]);
363         if (retval != ERROR_OK)
364                 return retval;
365
366         retval = stm32x_wait_status_busy(bank, 10);
367         if (retval != ERROR_OK)
368                 return retval;
369
370         /* write readout protection bit */
371         retval = target_write_u16(target, STM32_OB_RDP, stm32x_info->option_bytes.RDP);
372         if (retval != ERROR_OK)
373                 return retval;
374
375         retval = stm32x_wait_status_busy(bank, 10);
376         if (retval != ERROR_OK)
377                 return retval;
378
379         retval = target_write_u32(target, STM32_FLASH_CR_B0, FLASH_LOCK);
380         if (retval != ERROR_OK)
381                 return retval;
382
383         return ERROR_OK;
384 }
385
386 static int stm32x_protect_check(struct flash_bank *bank)
387 {
388         struct target *target = bank->target;
389         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
390
391         uint32_t protection;
392         int i, s;
393         int num_bits;
394         int set;
395
396         if (target->state != TARGET_HALTED) {
397                 LOG_ERROR("Target not halted");
398                 return ERROR_TARGET_NOT_HALTED;
399         }
400
401         int retval = stm32x_check_operation_supported(bank);
402         if (ERROR_OK != retval)
403                 return retval;
404
405         /* medium density - each bit refers to a 4bank protection
406          * high density - each bit refers to a 2bank protection */
407         retval = target_read_u32(target, STM32_FLASH_WRPR_B0, &protection);
408         if (retval != ERROR_OK)
409                 return retval;
410
411         /* medium density - each protection bit is for 4 * 1K pages
412          * high density - each protection bit is for 2 * 2K pages */
413         num_bits = (bank->num_sectors / stm32x_info->ppage_size);
414
415         if (stm32x_info->ppage_size == 2) {
416                 /* high density flash/connectivity line protection */
417
418                 set = 1;
419
420                 if (protection & (1 << 31))
421                         set = 0;
422
423                 /* bit 31 controls sector 62 - 255 protection for high density
424                  * bit 31 controls sector 62 - 127 protection for connectivity line */
425                 for (s = 62; s < bank->num_sectors; s++)
426                         bank->sectors[s].is_protected = set;
427
428                 if (bank->num_sectors > 61)
429                         num_bits = 31;
430
431                 for (i = 0; i < num_bits; i++) {
432                         set = 1;
433
434                         if (protection & (1 << i))
435                                 set = 0;
436
437                         for (s = 0; s < stm32x_info->ppage_size; s++)
438                                 bank->sectors[(i * stm32x_info->ppage_size) + s].is_protected = set;
439                 }
440         } else {
441                 /* low/medium density flash protection */
442                 for (i = 0; i < num_bits; i++) {
443                         set = 1;
444
445                         if (protection & (1 << i))
446                                 set = 0;
447
448                         for (s = 0; s < stm32x_info->ppage_size; s++)
449                                 bank->sectors[(i * stm32x_info->ppage_size) + s].is_protected = set;
450                 }
451         }
452
453         return ERROR_OK;
454 }
455
456 static int stm32x_erase(struct flash_bank *bank, int first, int last)
457 {
458         struct target *target = bank->target;
459         int i;
460
461         if (bank->target->state != TARGET_HALTED) {
462                 LOG_ERROR("Target not halted");
463                 return ERROR_TARGET_NOT_HALTED;
464         }
465
466         if ((first == 0) && (last == (bank->num_sectors - 1)))
467                 return stm32x_mass_erase(bank);
468
469         /* unlock flash registers */
470         int retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_KEYR), KEY1);
471         if (retval != ERROR_OK)
472                 return retval;
473         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_KEYR), KEY2);
474         if (retval != ERROR_OK)
475                 return retval;
476
477         for (i = first; i <= last; i++) {
478                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_PER);
479                 if (retval != ERROR_OK)
480                         return retval;
481                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_AR),
482                                 bank->base + bank->sectors[i].offset);
483                 if (retval != ERROR_OK)
484                         return retval;
485                 retval = target_write_u32(target,
486                                 stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_PER | FLASH_STRT);
487                 if (retval != ERROR_OK)
488                         return retval;
489
490                 retval = stm32x_wait_status_busy(bank, 100);
491                 if (retval != ERROR_OK)
492                         return retval;
493
494                 bank->sectors[i].is_erased = 1;
495         }
496
497         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
498         if (retval != ERROR_OK)
499                 return retval;
500
501         return ERROR_OK;
502 }
503
504 static int stm32x_protect(struct flash_bank *bank, int set, int first, int last)
505 {
506         struct stm32x_flash_bank *stm32x_info = NULL;
507         struct target *target = bank->target;
508         uint16_t prot_reg[4] = {0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF};
509         int i, reg, bit;
510         int status;
511         uint32_t protection;
512
513         stm32x_info = bank->driver_priv;
514
515         if (target->state != TARGET_HALTED) {
516                 LOG_ERROR("Target not halted");
517                 return ERROR_TARGET_NOT_HALTED;
518         }
519
520         int retval = stm32x_check_operation_supported(bank);
521         if (ERROR_OK != retval)
522                 return retval;
523
524         if ((first % stm32x_info->ppage_size) != 0) {
525                 LOG_WARNING("aligned start protect sector to a %d sector boundary",
526                                 stm32x_info->ppage_size);
527                 first = first - (first % stm32x_info->ppage_size);
528         }
529         if (((last + 1) % stm32x_info->ppage_size) != 0) {
530                 LOG_WARNING("aligned end protect sector to a %d sector boundary",
531                                 stm32x_info->ppage_size);
532                 last++;
533                 last = last - (last % stm32x_info->ppage_size);
534                 last--;
535         }
536
537         /* medium density - each bit refers to a 4bank protection
538          * high density - each bit refers to a 2bank protection */
539         retval = target_read_u32(target, STM32_FLASH_WRPR_B0, &protection);
540         if (retval != ERROR_OK)
541                 return retval;
542
543         prot_reg[0] = (uint16_t)protection;
544         prot_reg[1] = (uint16_t)(protection >> 8);
545         prot_reg[2] = (uint16_t)(protection >> 16);
546         prot_reg[3] = (uint16_t)(protection >> 24);
547
548         if (stm32x_info->ppage_size == 2) {
549                 /* high density flash */
550
551                 /* bit 7 controls sector 62 - 255 protection */
552                 if (last > 61) {
553                         if (set)
554                                 prot_reg[3] &= ~(1 << 7);
555                         else
556                                 prot_reg[3] |= (1 << 7);
557                 }
558
559                 if (first > 61)
560                         first = 62;
561                 if (last > 61)
562                         last = 61;
563
564                 for (i = first; i <= last; i++) {
565                         reg = (i / stm32x_info->ppage_size) / 8;
566                         bit = (i / stm32x_info->ppage_size) - (reg * 8);
567
568                         if (set)
569                                 prot_reg[reg] &= ~(1 << bit);
570                         else
571                                 prot_reg[reg] |= (1 << bit);
572                 }
573         } else {
574                 /* medium density flash */
575                 for (i = first; i <= last; i++) {
576                         reg = (i / stm32x_info->ppage_size) / 8;
577                         bit = (i / stm32x_info->ppage_size) - (reg * 8);
578
579                         if (set)
580                                 prot_reg[reg] &= ~(1 << bit);
581                         else
582                                 prot_reg[reg] |= (1 << bit);
583                 }
584         }
585
586         status = stm32x_erase_options(bank);
587         if (status != ERROR_OK)
588                 return status;
589
590         stm32x_info->option_bytes.protection[0] = prot_reg[0];
591         stm32x_info->option_bytes.protection[1] = prot_reg[1];
592         stm32x_info->option_bytes.protection[2] = prot_reg[2];
593         stm32x_info->option_bytes.protection[3] = prot_reg[3];
594
595         return stm32x_write_options(bank);
596 }
597
598 static int stm32x_write_block(struct flash_bank *bank, uint8_t *buffer,
599                 uint32_t offset, uint32_t count)
600 {
601         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
602         struct target *target = bank->target;
603         uint32_t buffer_size = 16384;
604         struct working_area *write_algorithm;
605         struct working_area *source;
606         uint32_t address = bank->base + offset;
607         struct reg_param reg_params[5];
608         struct armv7m_algorithm armv7m_info;
609         int retval = ERROR_OK;
610
611         /* see contrib/loaders/flash/stm32f1x.S for src */
612
613         static const uint8_t stm32x_flash_write_code[] = {
614                 /* #define STM32_FLASH_SR_OFFSET 0x0C */
615                 /* wait_fifo: */
616                         0x16, 0x68,   /* ldr   r6, [r2, #0] */
617                         0x00, 0x2e,   /* cmp   r6, #0 */
618                         0x18, 0xd0,   /* beq   exit */
619                         0x55, 0x68,   /* ldr   r5, [r2, #4] */
620                         0xb5, 0x42,   /* cmp   r5, r6 */
621                         0xf9, 0xd0,   /* beq   wait_fifo */
622                         0x2e, 0x88,   /* ldrh  r6, [r5, #0] */
623                         0x26, 0x80,   /* strh  r6, [r4, #0] */
624                         0x02, 0x35,   /* adds  r5, #2 */
625                         0x02, 0x34,   /* adds  r4, #2 */
626                 /* busy: */
627                         0xc6, 0x68,   /* ldr   r6, [r0, #STM32_FLASH_SR_OFFSET] */
628                         0x01, 0x27,   /* movs  r7, #1 */
629                         0x3e, 0x42,   /* tst   r6, r7 */
630                         0xfb, 0xd1,   /* bne   busy */
631                         0x14, 0x27,   /* movs  r7, #0x14 */
632                         0x3e, 0x42,   /* tst   r6, r7 */
633                         0x08, 0xd1,   /* bne   error */
634                         0x9d, 0x42,   /* cmp   r5, r3 */
635                         0x01, 0xd3,   /* bcc   no_wrap */
636                         0x15, 0x46,   /* mov   r5, r2 */
637                         0x08, 0x35,   /* adds  r5, #8 */
638                 /* no_wrap: */
639                         0x55, 0x60,   /* str   r5, [r2, #4] */
640                         0x01, 0x39,   /* subs  r1, r1, #1 */
641                         0x00, 0x29,   /* cmp   r1, #0 */
642                         0x02, 0xd0,   /* beq   exit */
643                         0xe5, 0xe7,   /* b     wait_fifo */
644                 /* error: */
645                         0x00, 0x20,   /* movs  r0, #0 */
646                         0x50, 0x60,   /* str   r0, [r2, #4] */
647                 /* exit: */
648                         0x30, 0x46,   /* mov   r0, r6 */
649                         0x00, 0xbe,   /* bkpt  #0 */
650         };
651
652         /* flash write code */
653         if (target_alloc_working_area(target, sizeof(stm32x_flash_write_code),
654                         &write_algorithm) != ERROR_OK) {
655                 LOG_WARNING("no working area available, can't do block memory writes");
656                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
657         };
658
659         retval = target_write_buffer(target, write_algorithm->address,
660                         sizeof(stm32x_flash_write_code), (uint8_t *)stm32x_flash_write_code);
661         if (retval != ERROR_OK)
662                 return retval;
663
664         /* memory buffer */
665         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) {
666                 buffer_size /= 2;
667                 buffer_size &= ~3UL; /* Make sure it's 4 byte aligned */
668                 if (buffer_size <= 256) {
669                         /* we already allocated the writing code, but failed to get a
670                          * buffer, free the algorithm */
671                         target_free_working_area(target, write_algorithm);
672
673                         LOG_WARNING("no large enough working area available, can't do block memory writes");
674                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
675                 }
676         };
677
678         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT); /* flash base (in), status (out) */
679         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);    /* count (halfword-16bit) */
680         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);    /* buffer start */
681         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);    /* buffer end */
682         init_reg_param(&reg_params[4], "r4", 32, PARAM_IN_OUT); /* target address */
683
684         buf_set_u32(reg_params[0].value, 0, 32, stm32x_info->register_base);
685         buf_set_u32(reg_params[1].value, 0, 32, count);
686         buf_set_u32(reg_params[2].value, 0, 32, source->address);
687         buf_set_u32(reg_params[3].value, 0, 32, source->address + source->size);
688         buf_set_u32(reg_params[4].value, 0, 32, address);
689
690         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
691         armv7m_info.core_mode = ARMV7M_MODE_ANY;
692
693         retval = target_run_flash_async_algorithm(target, buffer, count, 2,
694                         0, NULL,
695                         5, reg_params,
696                         source->address, source->size,
697                         write_algorithm->address, 0,
698                         &armv7m_info);
699
700         if (retval == ERROR_FLASH_OPERATION_FAILED) {
701                 LOG_ERROR("flash write failed at address 0x%"PRIx32,
702                                 buf_get_u32(reg_params[4].value, 0, 32));
703
704                 if (buf_get_u32(reg_params[0].value, 0, 32) & FLASH_PGERR) {
705                         LOG_ERROR("flash memory not erased before writing");
706                         /* Clear but report errors */
707                         target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR), FLASH_PGERR);
708                 }
709
710                 if (buf_get_u32(reg_params[0].value, 0, 32) & FLASH_WRPRTERR) {
711                         LOG_ERROR("flash memory write protected");
712                         /* Clear but report errors */
713                         target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_SR), FLASH_WRPRTERR);
714                 }
715         }
716
717         target_free_working_area(target, source);
718         target_free_working_area(target, write_algorithm);
719
720         destroy_reg_param(&reg_params[0]);
721         destroy_reg_param(&reg_params[1]);
722         destroy_reg_param(&reg_params[2]);
723         destroy_reg_param(&reg_params[3]);
724         destroy_reg_param(&reg_params[4]);
725
726         return retval;
727 }
728
729 static int stm32x_write(struct flash_bank *bank, uint8_t *buffer,
730                 uint32_t offset, uint32_t count)
731 {
732         struct target *target = bank->target;
733         uint8_t *new_buffer = NULL;
734
735         if (bank->target->state != TARGET_HALTED) {
736                 LOG_ERROR("Target not halted");
737                 return ERROR_TARGET_NOT_HALTED;
738         }
739
740         if (offset & 0x1) {
741                 LOG_ERROR("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
742                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
743         }
744
745         /* If there's an odd number of bytes, the data has to be padded. Duplicate
746          * the buffer and use the normal code path with a single block write since
747          * it's probably cheaper than to special case the last odd write using
748          * discrete accesses. */
749         if (count & 1) {
750                 new_buffer = malloc(count + 1);
751                 if (new_buffer == NULL) {
752                         LOG_ERROR("odd number of bytes to write and no memory for padding buffer");
753                         return ERROR_FAIL;
754                 }
755                 LOG_INFO("odd number of bytes to write, padding with 0xff");
756                 buffer = memcpy(new_buffer, buffer, count);
757                 buffer[count++] = 0xff;
758         }
759
760         uint32_t words_remaining = count / 2;
761         int retval, retval2;
762
763         /* unlock flash registers */
764         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_KEYR), KEY1);
765         if (retval != ERROR_OK)
766                 goto cleanup;
767         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_KEYR), KEY2);
768         if (retval != ERROR_OK)
769                 goto cleanup;
770
771         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_PG);
772         if (retval != ERROR_OK)
773                 goto cleanup;
774
775         /* try using a block write */
776         retval = stm32x_write_block(bank, buffer, offset, words_remaining);
777
778         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
779                 /* if block write failed (no sufficient working area),
780                  * we use normal (slow) single halfword accesses */
781                 LOG_WARNING("couldn't use block writes, falling back to single memory accesses");
782
783                 while (words_remaining > 0) {
784                         uint16_t value;
785                         memcpy(&value, buffer, sizeof(uint16_t));
786
787                         retval = target_write_u16(target, bank->base + offset, value);
788                         if (retval != ERROR_OK)
789                                 goto reset_pg_and_lock;
790
791                         retval = stm32x_wait_status_busy(bank, 5);
792                         if (retval != ERROR_OK)
793                                 goto reset_pg_and_lock;
794
795                         words_remaining--;
796                         buffer += 2;
797                         offset += 2;
798                 }
799         }
800
801 reset_pg_and_lock:
802         retval2 = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
803         if (retval == ERROR_OK)
804                 retval = retval2;
805
806 cleanup:
807         if (new_buffer)
808                 free(new_buffer);
809
810         return retval;
811 }
812
813 static int stm32x_get_device_id(struct flash_bank *bank, uint32_t *device_id)
814 {
815         /* This check the device CPUID core register to detect
816          * the M0 from the M3 devices. */
817
818         struct target *target = bank->target;
819         uint32_t cpuid, device_id_register = 0;
820
821         /* Get the CPUID from the ARM Core
822          * http://infocenter.arm.com/help/topic/com.arm.doc.ddi0432c/DDI0432C_cortex_m0_r0p0_trm.pdf 4.2.1 */
823         int retval = target_read_u32(target, 0xE000ED00, &cpuid);
824         if (retval != ERROR_OK)
825                 return retval;
826
827         if (((cpuid >> 4) & 0xFFF) == 0xC20) {
828                 /* 0xC20 is M0 devices */
829                 device_id_register = 0x40015800;
830         } else if (((cpuid >> 4) & 0xFFF) == 0xC23) {
831                 /* 0xC23 is M3 devices */
832                 device_id_register = 0xE0042000;
833         } else if (((cpuid >> 4) & 0xFFF) == 0xC24) {
834                 /* 0xC24 is M4 devices */
835                 device_id_register = 0xE0042000;
836         } else {
837                 LOG_ERROR("Cannot identify target as a stm32x");
838                 return ERROR_FAIL;
839         }
840
841         /* read stm32 device id register */
842         retval = target_read_u32(target, device_id_register, device_id);
843         if (retval != ERROR_OK)
844                 return retval;
845
846         return retval;
847 }
848
849 static int stm32x_get_flash_size(struct flash_bank *bank, uint16_t *flash_size_in_kb)
850 {
851         struct target *target = bank->target;
852         uint32_t cpuid, flash_size_reg;
853
854         int retval = target_read_u32(target, 0xE000ED00, &cpuid);
855         if (retval != ERROR_OK)
856                 return retval;
857
858         if (((cpuid >> 4) & 0xFFF) == 0xC20) {
859                 /* 0xC20 is M0 devices */
860                 flash_size_reg = 0x1FFFF7CC;
861         } else if (((cpuid >> 4) & 0xFFF) == 0xC23) {
862                 /* 0xC23 is M3 devices */
863                 flash_size_reg = 0x1FFFF7E0;
864         } else if (((cpuid >> 4) & 0xFFF) == 0xC24) {
865                 /* 0xC24 is M4 devices */
866                 flash_size_reg = 0x1FFFF7CC;
867         } else {
868                 LOG_ERROR("Cannot identify target as a stm32x");
869                 return ERROR_FAIL;
870         }
871
872         retval = target_read_u16(target, flash_size_reg, flash_size_in_kb);
873         if (retval != ERROR_OK)
874                 return retval;
875
876         return retval;
877 }
878
879 static int stm32x_probe(struct flash_bank *bank)
880 {
881         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
882         int i;
883         uint16_t flash_size_in_kb;
884         uint16_t max_flash_size_in_kb;
885         uint32_t device_id;
886         int page_size;
887         uint32_t base_address = 0x08000000;
888
889         stm32x_info->probed = 0;
890         stm32x_info->register_base = FLASH_REG_BASE_B0;
891
892         /* read stm32 device id register */
893         int retval = stm32x_get_device_id(bank, &device_id);
894         if (retval != ERROR_OK)
895                 return retval;
896
897         LOG_INFO("device id = 0x%08" PRIx32 "", device_id);
898
899         /* set page size, protection granularity and max flash size depending on family */
900         switch (device_id & 0xfff) {
901         case 0x410: /* medium density */
902                 page_size = 1024;
903                 stm32x_info->ppage_size = 4;
904                 max_flash_size_in_kb = 128;
905                 break;
906         case 0x412: /* low density */
907                 page_size = 1024;
908                 stm32x_info->ppage_size = 4;
909                 max_flash_size_in_kb = 32;
910                 break;
911         case 0x414: /* high density */
912                 page_size = 2048;
913                 stm32x_info->ppage_size = 2;
914                 max_flash_size_in_kb = 512;
915                 break;
916         case 0x418: /* connectivity line density */
917                 page_size = 2048;
918                 stm32x_info->ppage_size = 2;
919                 max_flash_size_in_kb = 256;
920                 break;
921         case 0x420: /* value line density */
922                 page_size = 1024;
923                 stm32x_info->ppage_size = 4;
924                 max_flash_size_in_kb = 128;
925                 break;
926         case 0x422: /* stm32f30x */
927                 page_size = 2048;
928                 stm32x_info->ppage_size = 2;
929                 max_flash_size_in_kb = 256;
930                 break;
931         case 0x428: /* value line High density */
932                 page_size = 2048;
933                 stm32x_info->ppage_size = 4;
934                 max_flash_size_in_kb = 128;
935                 break;
936         case 0x430: /* xl line density (dual flash banks) */
937                 page_size = 2048;
938                 stm32x_info->ppage_size = 2;
939                 max_flash_size_in_kb = 1024;
940                 stm32x_info->has_dual_banks = true;
941                 break;
942         case 0x432: /* stm32f37x */
943                 page_size = 2048;
944                 stm32x_info->ppage_size = 2;
945                 max_flash_size_in_kb = 256;
946                 break;
947         case 0x440: /* stm32f0x */
948                 page_size = 1024;
949                 stm32x_info->ppage_size = 4;
950                 max_flash_size_in_kb = 64;
951                 break;
952         default:
953                 LOG_WARNING("Cannot identify target as a STM32 family.");
954                 return ERROR_FAIL;
955         }
956
957         /* get flash size from target. */
958         retval = stm32x_get_flash_size(bank, &flash_size_in_kb);
959
960         /* failed reading flash size or flash size invalid (early silicon),
961          * default to max target family */
962         if (retval != ERROR_OK || flash_size_in_kb == 0xffff || flash_size_in_kb == 0) {
963                 LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming %dk flash",
964                         max_flash_size_in_kb);
965                 flash_size_in_kb = max_flash_size_in_kb;
966         }
967
968         if (stm32x_info->has_dual_banks) {
969                 /* split reported size into matching bank */
970                 if (bank->base != 0x08080000) {
971                         /* bank 0 will be fixed 512k */
972                         flash_size_in_kb = 512;
973                 } else {
974                         flash_size_in_kb -= 512;
975                         /* bank1 also uses a register offset */
976                         stm32x_info->register_base = FLASH_REG_BASE_B1;
977                         base_address = 0x08080000;
978                 }
979         }
980
981         LOG_INFO("flash size = %dkbytes", flash_size_in_kb);
982
983         /* did we assign flash size? */
984         assert(flash_size_in_kb != 0xffff);
985
986         /* calculate numbers of pages */
987         int num_pages = flash_size_in_kb * 1024 / page_size;
988
989         /* check that calculation result makes sense */
990         assert(num_pages > 0);
991
992         if (bank->sectors) {
993                 free(bank->sectors);
994                 bank->sectors = NULL;
995         }
996
997         bank->base = base_address;
998         bank->size = (num_pages * page_size);
999         bank->num_sectors = num_pages;
1000         bank->sectors = malloc(sizeof(struct flash_sector) * num_pages);
1001
1002         for (i = 0; i < num_pages; i++) {
1003                 bank->sectors[i].offset = i * page_size;
1004                 bank->sectors[i].size = page_size;
1005                 bank->sectors[i].is_erased = -1;
1006                 bank->sectors[i].is_protected = 1;
1007         }
1008
1009         stm32x_info->probed = 1;
1010
1011         return ERROR_OK;
1012 }
1013
1014 static int stm32x_auto_probe(struct flash_bank *bank)
1015 {
1016         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
1017         if (stm32x_info->probed)
1018                 return ERROR_OK;
1019         return stm32x_probe(bank);
1020 }
1021
1022 #if 0
1023 COMMAND_HANDLER(stm32x_handle_part_id_command)
1024 {
1025         return ERROR_OK;
1026 }
1027 #endif
1028
1029 static int get_stm32x_info(struct flash_bank *bank, char *buf, int buf_size)
1030 {
1031         uint32_t device_id;
1032         int printed;
1033
1034                 /* read stm32 device id register */
1035         int retval = stm32x_get_device_id(bank, &device_id);
1036         if (retval != ERROR_OK)
1037                 return retval;
1038
1039         if ((device_id & 0xfff) == 0x410) {
1040                 printed = snprintf(buf, buf_size, "stm32x (Medium Density) - Rev: ");
1041                 buf += printed;
1042                 buf_size -= printed;
1043
1044                 switch (device_id >> 16) {
1045                         case 0x0000:
1046                                 snprintf(buf, buf_size, "A");
1047                                 break;
1048
1049                         case 0x2000:
1050                                 snprintf(buf, buf_size, "B");
1051                                 break;
1052
1053                         case 0x2001:
1054                                 snprintf(buf, buf_size, "Z");
1055                                 break;
1056
1057                         case 0x2003:
1058                                 snprintf(buf, buf_size, "Y");
1059                                 break;
1060
1061                         default:
1062                                 snprintf(buf, buf_size, "unknown");
1063                                 break;
1064                 }
1065         } else if ((device_id & 0xfff) == 0x412) {
1066                 printed = snprintf(buf, buf_size, "stm32x (Low Density) - Rev: ");
1067                 buf += printed;
1068                 buf_size -= printed;
1069
1070                 switch (device_id >> 16) {
1071                         case 0x1000:
1072                                 snprintf(buf, buf_size, "A");
1073                                 break;
1074
1075                         default:
1076                                 snprintf(buf, buf_size, "unknown");
1077                                 break;
1078                 }
1079         } else if ((device_id & 0xfff) == 0x414) {
1080                 printed = snprintf(buf, buf_size, "stm32x (High Density) - Rev: ");
1081                 buf += printed;
1082                 buf_size -= printed;
1083
1084                 switch (device_id >> 16) {
1085                         case 0x1000:
1086                                 snprintf(buf, buf_size, "A");
1087                                 break;
1088
1089                         case 0x1001:
1090                                 snprintf(buf, buf_size, "Z");
1091                                 break;
1092
1093                         default:
1094                                 snprintf(buf, buf_size, "unknown");
1095                                 break;
1096                 }
1097         } else if ((device_id & 0xfff) == 0x418) {
1098                 printed = snprintf(buf, buf_size, "stm32x (Connectivity) - Rev: ");
1099                 buf += printed;
1100                 buf_size -= printed;
1101
1102                 switch (device_id >> 16) {
1103                         case 0x1000:
1104                                 snprintf(buf, buf_size, "A");
1105                                 break;
1106
1107                         case 0x1001:
1108                                 snprintf(buf, buf_size, "Z");
1109                                 break;
1110
1111                         default:
1112                                 snprintf(buf, buf_size, "unknown");
1113                                 break;
1114                 }
1115         } else if ((device_id & 0xfff) == 0x420) {
1116                 printed = snprintf(buf, buf_size, "stm32x (Value) - Rev: ");
1117                 buf += printed;
1118                 buf_size -= printed;
1119
1120                 switch (device_id >> 16) {
1121                         case 0x1000:
1122                                 snprintf(buf, buf_size, "A");
1123                                 break;
1124
1125                         case 0x1001:
1126                                 snprintf(buf, buf_size, "Z");
1127                                 break;
1128
1129                         default:
1130                                 snprintf(buf, buf_size, "unknown");
1131                                 break;
1132                 }
1133         } else if ((device_id & 0xfff) == 0x422) {
1134                 printed = snprintf(buf, buf_size, "stm32f30x - Rev: ");
1135                 buf += printed;
1136                 buf_size -= printed;
1137
1138                 switch (device_id >> 16) {
1139                         case 0x1000:
1140                                 snprintf(buf, buf_size, "1.0");
1141                                 break;
1142
1143                         case 0x2000:
1144                                 snprintf(buf, buf_size, "2.0");
1145                                 break;
1146
1147                         default:
1148                                 snprintf(buf, buf_size, "unknown");
1149                                 break;
1150                 }
1151         } else if ((device_id & 0xfff) == 0x428) {
1152                 printed = snprintf(buf, buf_size, "stm32x (Value HD) - Rev: ");
1153                 buf += printed;
1154                 buf_size -= printed;
1155
1156                 switch (device_id >> 16) {
1157                         case 0x1000:
1158                                 snprintf(buf, buf_size, "A");
1159                                 break;
1160
1161                         case 0x1001:
1162                                 snprintf(buf, buf_size, "Z");
1163                                 break;
1164
1165                         default:
1166                                 snprintf(buf, buf_size, "unknown");
1167                                 break;
1168                 }
1169         } else if ((device_id & 0xfff) == 0x430) {
1170                 printed = snprintf(buf, buf_size, "stm32x (XL) - Rev: ");
1171                 buf += printed;
1172                 buf_size -= printed;
1173
1174                 switch (device_id >> 16) {
1175                         case 0x1000:
1176                                 snprintf(buf, buf_size, "A");
1177                                 break;
1178
1179                         default:
1180                                 snprintf(buf, buf_size, "unknown");
1181                                 break;
1182                 }
1183         } else if ((device_id & 0xfff) == 0x432) {
1184                 printed = snprintf(buf, buf_size, "stm32f37x - Rev: ");
1185                 buf += printed;
1186                 buf_size -= printed;
1187
1188                 switch (device_id >> 16) {
1189                         case 0x1000:
1190                                 snprintf(buf, buf_size, "1.0");
1191                                 break;
1192
1193                         case 0x2000:
1194                                 snprintf(buf, buf_size, "2.0");
1195                                 break;
1196
1197                         default:
1198                                 snprintf(buf, buf_size, "unknown");
1199                                 break;
1200                 }
1201         } else if ((device_id & 0xfff) == 0x440) {
1202                 printed = snprintf(buf, buf_size, "stm32f0x - Rev: ");
1203                 buf += printed;
1204                 buf_size -= printed;
1205
1206                 switch (device_id >> 16) {
1207                         case 0x1000:
1208                                 snprintf(buf, buf_size, "1.0");
1209                                 break;
1210
1211                         case 0x2000:
1212                                 snprintf(buf, buf_size, "2.0");
1213                                 break;
1214
1215                         default:
1216                                 snprintf(buf, buf_size, "unknown");
1217                                 break;
1218                 }
1219         } else {
1220                 snprintf(buf, buf_size, "Cannot identify target as a stm32x\n");
1221                 return ERROR_FAIL;
1222         }
1223
1224         return ERROR_OK;
1225 }
1226
1227 COMMAND_HANDLER(stm32x_handle_lock_command)
1228 {
1229         struct target *target = NULL;
1230         struct stm32x_flash_bank *stm32x_info = NULL;
1231
1232         if (CMD_ARGC < 1)
1233                 return ERROR_COMMAND_SYNTAX_ERROR;
1234
1235         struct flash_bank *bank;
1236         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1237         if (ERROR_OK != retval)
1238                 return retval;
1239
1240         stm32x_info = bank->driver_priv;
1241
1242         target = bank->target;
1243
1244         if (target->state != TARGET_HALTED) {
1245                 LOG_ERROR("Target not halted");
1246                 return ERROR_TARGET_NOT_HALTED;
1247         }
1248
1249         retval = stm32x_check_operation_supported(bank);
1250         if (ERROR_OK != retval)
1251                 return retval;
1252
1253         if (stm32x_erase_options(bank) != ERROR_OK) {
1254                 command_print(CMD_CTX, "stm32x failed to erase options");
1255                 return ERROR_OK;
1256         }
1257
1258         /* set readout protection */
1259         stm32x_info->option_bytes.RDP = 0;
1260
1261         if (stm32x_write_options(bank) != ERROR_OK) {
1262                 command_print(CMD_CTX, "stm32x failed to lock device");
1263                 return ERROR_OK;
1264         }
1265
1266         command_print(CMD_CTX, "stm32x locked");
1267
1268         return ERROR_OK;
1269 }
1270
1271 COMMAND_HANDLER(stm32x_handle_unlock_command)
1272 {
1273         struct target *target = NULL;
1274
1275         if (CMD_ARGC < 1)
1276                 return ERROR_COMMAND_SYNTAX_ERROR;
1277
1278         struct flash_bank *bank;
1279         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1280         if (ERROR_OK != retval)
1281                 return retval;
1282
1283         target = bank->target;
1284
1285         if (target->state != TARGET_HALTED) {
1286                 LOG_ERROR("Target not halted");
1287                 return ERROR_TARGET_NOT_HALTED;
1288         }
1289
1290         retval = stm32x_check_operation_supported(bank);
1291         if (ERROR_OK != retval)
1292                 return retval;
1293
1294         if (stm32x_erase_options(bank) != ERROR_OK) {
1295                 command_print(CMD_CTX, "stm32x failed to unlock device");
1296                 return ERROR_OK;
1297         }
1298
1299         if (stm32x_write_options(bank) != ERROR_OK) {
1300                 command_print(CMD_CTX, "stm32x failed to lock device");
1301                 return ERROR_OK;
1302         }
1303
1304         command_print(CMD_CTX, "stm32x unlocked.\n"
1305                         "INFO: a reset or power cycle is required "
1306                         "for the new settings to take effect.");
1307
1308         return ERROR_OK;
1309 }
1310
1311 COMMAND_HANDLER(stm32x_handle_options_read_command)
1312 {
1313         uint32_t optionbyte;
1314         struct target *target = NULL;
1315         struct stm32x_flash_bank *stm32x_info = NULL;
1316
1317         if (CMD_ARGC < 1)
1318                 return ERROR_COMMAND_SYNTAX_ERROR;
1319
1320         struct flash_bank *bank;
1321         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1322         if (ERROR_OK != retval)
1323                 return retval;
1324
1325         stm32x_info = bank->driver_priv;
1326
1327         target = bank->target;
1328
1329         if (target->state != TARGET_HALTED) {
1330                 LOG_ERROR("Target not halted");
1331                 return ERROR_TARGET_NOT_HALTED;
1332         }
1333
1334         retval = stm32x_check_operation_supported(bank);
1335         if (ERROR_OK != retval)
1336                 return retval;
1337
1338         retval = target_read_u32(target, STM32_FLASH_OBR_B0, &optionbyte);
1339         if (retval != ERROR_OK)
1340                 return retval;
1341         command_print(CMD_CTX, "Option Byte: 0x%" PRIx32 "", optionbyte);
1342
1343         if (buf_get_u32((uint8_t *)&optionbyte, OPT_ERROR, 1))
1344                 command_print(CMD_CTX, "Option Byte Complement Error");
1345
1346         if (buf_get_u32((uint8_t *)&optionbyte, OPT_READOUT, 1))
1347                 command_print(CMD_CTX, "Readout Protection On");
1348         else
1349                 command_print(CMD_CTX, "Readout Protection Off");
1350
1351         if (buf_get_u32((uint8_t *)&optionbyte, OPT_RDWDGSW, 1))
1352                 command_print(CMD_CTX, "Software Watchdog");
1353         else
1354                 command_print(CMD_CTX, "Hardware Watchdog");
1355
1356         if (buf_get_u32((uint8_t *)&optionbyte, OPT_RDRSTSTOP, 1))
1357                 command_print(CMD_CTX, "Stop: No reset generated");
1358         else
1359                 command_print(CMD_CTX, "Stop: Reset generated");
1360
1361         if (buf_get_u32((uint8_t *)&optionbyte, OPT_RDRSTSTDBY, 1))
1362                 command_print(CMD_CTX, "Standby: No reset generated");
1363         else
1364                 command_print(CMD_CTX, "Standby: Reset generated");
1365
1366         if (stm32x_info->has_dual_banks) {
1367                 if (buf_get_u32((uint8_t *)&optionbyte, OPT_BFB2, 1))
1368                         command_print(CMD_CTX, "Boot: Bank 0");
1369                 else
1370                         command_print(CMD_CTX, "Boot: Bank 1");
1371         }
1372
1373         return ERROR_OK;
1374 }
1375
1376 COMMAND_HANDLER(stm32x_handle_options_write_command)
1377 {
1378         struct target *target = NULL;
1379         struct stm32x_flash_bank *stm32x_info = NULL;
1380         uint16_t optionbyte = 0xF8;
1381
1382         if (CMD_ARGC < 4)
1383                 return ERROR_COMMAND_SYNTAX_ERROR;
1384
1385         struct flash_bank *bank;
1386         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1387         if (ERROR_OK != retval)
1388                 return retval;
1389
1390         stm32x_info = bank->driver_priv;
1391
1392         target = bank->target;
1393
1394         if (target->state != TARGET_HALTED) {
1395                 LOG_ERROR("Target not halted");
1396                 return ERROR_TARGET_NOT_HALTED;
1397         }
1398
1399         retval = stm32x_check_operation_supported(bank);
1400         if (ERROR_OK != retval)
1401                 return retval;
1402
1403         /* REVISIT: ignores some options which we will display...
1404          * and doesn't insist on the specified syntax.
1405          */
1406
1407         /* OPT_RDWDGSW */
1408         if (strcmp(CMD_ARGV[1], "SWWDG") == 0)
1409                 optionbyte |= (1 << 0);
1410         else    /* REVISIT must be "HWWDG" then ... */
1411                 optionbyte &= ~(1 << 0);
1412
1413         /* OPT_RDRSTSTOP */
1414         if (strcmp(CMD_ARGV[2], "NORSTSTOP") == 0)
1415                 optionbyte |= (1 << 1);
1416         else    /* REVISIT must be "RSTSTNDBY" then ... */
1417                 optionbyte &= ~(1 << 1);
1418
1419         /* OPT_RDRSTSTDBY */
1420         if (strcmp(CMD_ARGV[3], "NORSTSTNDBY") == 0)
1421                 optionbyte |= (1 << 2);
1422         else    /* REVISIT must be "RSTSTOP" then ... */
1423                 optionbyte &= ~(1 << 2);
1424
1425         if (CMD_ARGC > 4 && stm32x_info->has_dual_banks) {
1426                 /* OPT_BFB2 */
1427                 if (strcmp(CMD_ARGV[4], "BOOT0") == 0)
1428                         optionbyte |= (1 << 3);
1429                 else
1430                         optionbyte &= ~(1 << 3);
1431         }
1432
1433         if (stm32x_erase_options(bank) != ERROR_OK) {
1434                 command_print(CMD_CTX, "stm32x failed to erase options");
1435                 return ERROR_OK;
1436         }
1437
1438         stm32x_info->option_bytes.user_options = optionbyte;
1439
1440         if (stm32x_write_options(bank) != ERROR_OK) {
1441                 command_print(CMD_CTX, "stm32x failed to write options");
1442                 return ERROR_OK;
1443         }
1444
1445         command_print(CMD_CTX, "stm32x write options complete.\n"
1446                                 "INFO: a reset or power cycle is required "
1447                                 "for the new settings to take effect.");
1448
1449         return ERROR_OK;
1450 }
1451
1452 static int stm32x_mass_erase(struct flash_bank *bank)
1453 {
1454         struct target *target = bank->target;
1455
1456         if (target->state != TARGET_HALTED) {
1457                 LOG_ERROR("Target not halted");
1458                 return ERROR_TARGET_NOT_HALTED;
1459         }
1460
1461         /* unlock option flash registers */
1462         int retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_KEYR), KEY1);
1463         if (retval != ERROR_OK)
1464                 return retval;
1465         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_KEYR), KEY2);
1466         if (retval != ERROR_OK)
1467                 return retval;
1468
1469         /* mass erase flash memory */
1470         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_MER);
1471         if (retval != ERROR_OK)
1472                 return retval;
1473         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR),
1474                         FLASH_MER | FLASH_STRT);
1475         if (retval != ERROR_OK)
1476                 return retval;
1477
1478         retval = stm32x_wait_status_busy(bank, 100);
1479         if (retval != ERROR_OK)
1480                 return retval;
1481
1482         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
1483         if (retval != ERROR_OK)
1484                 return retval;
1485
1486         return ERROR_OK;
1487 }
1488
1489 COMMAND_HANDLER(stm32x_handle_mass_erase_command)
1490 {
1491         int i;
1492
1493         if (CMD_ARGC < 1)
1494                 return ERROR_COMMAND_SYNTAX_ERROR;
1495
1496         struct flash_bank *bank;
1497         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1498         if (ERROR_OK != retval)
1499                 return retval;
1500
1501         retval = stm32x_mass_erase(bank);
1502         if (retval == ERROR_OK) {
1503                 /* set all sectors as erased */
1504                 for (i = 0; i < bank->num_sectors; i++)
1505                         bank->sectors[i].is_erased = 1;
1506
1507                 command_print(CMD_CTX, "stm32x mass erase complete");
1508         } else
1509                 command_print(CMD_CTX, "stm32x mass erase failed");
1510
1511         return retval;
1512 }
1513
1514 static const struct command_registration stm32x_exec_command_handlers[] = {
1515         {
1516                 .name = "lock",
1517                 .handler = stm32x_handle_lock_command,
1518                 .mode = COMMAND_EXEC,
1519                 .usage = "bank_id",
1520                 .help = "Lock entire flash device.",
1521         },
1522         {
1523                 .name = "unlock",
1524                 .handler = stm32x_handle_unlock_command,
1525                 .mode = COMMAND_EXEC,
1526                 .usage = "bank_id",
1527                 .help = "Unlock entire protected flash device.",
1528         },
1529         {
1530                 .name = "mass_erase",
1531                 .handler = stm32x_handle_mass_erase_command,
1532                 .mode = COMMAND_EXEC,
1533                 .usage = "bank_id",
1534                 .help = "Erase entire flash device.",
1535         },
1536         {
1537                 .name = "options_read",
1538                 .handler = stm32x_handle_options_read_command,
1539                 .mode = COMMAND_EXEC,
1540                 .usage = "bank_id",
1541                 .help = "Read and display device option byte.",
1542         },
1543         {
1544                 .name = "options_write",
1545                 .handler = stm32x_handle_options_write_command,
1546                 .mode = COMMAND_EXEC,
1547                 .usage = "bank_id ('SWWDG'|'HWWDG') "
1548                         "('RSTSTNDBY'|'NORSTSTNDBY') "
1549                         "('RSTSTOP'|'NORSTSTOP')",
1550                 .help = "Replace bits in device option byte.",
1551         },
1552         COMMAND_REGISTRATION_DONE
1553 };
1554
1555 static const struct command_registration stm32x_command_handlers[] = {
1556         {
1557                 .name = "stm32f1x",
1558                 .mode = COMMAND_ANY,
1559                 .help = "stm32f1x flash command group",
1560                 .usage = "",
1561                 .chain = stm32x_exec_command_handlers,
1562         },
1563         COMMAND_REGISTRATION_DONE
1564 };
1565
1566 struct flash_driver stm32f1x_flash = {
1567         .name = "stm32f1x",
1568         .commands = stm32x_command_handlers,
1569         .flash_bank_command = stm32x_flash_bank_command,
1570         .erase = stm32x_erase,
1571         .protect = stm32x_protect,
1572         .write = stm32x_write,
1573         .read = default_flash_read,
1574         .probe = stm32x_probe,
1575         .auto_probe = stm32x_auto_probe,
1576         .erase_check = default_flash_blank_check,
1577         .protect_check = stm32x_protect_check,
1578         .info = get_stm32x_info,
1579 };