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