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