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