]> git.sur5r.net Git - openocd/blob - src/flash/nor/stm32f1x.c
flash: use correct device_id mask
[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                         0x35, 0xf8, 0x02, 0x6b, /* ldrh         r6, [r5], #2 */
647                         0x24, 0xf8, 0x02, 0x6b, /* strh         r6, [r4], #2 */
648                 /* busy: */
649                         0xc6, 0x68,             /* ldr          r6, [r0, #STM32_FLASH_SR_OFFSET] */
650                         0x16, 0xf0, 0x01, 0x0f, /* tst          r6, #1 */
651                         0xfb, 0xd1,             /* bne          busy */
652                         0x16, 0xf0, 0x14, 0x0f, /* tst          r6, #0x14 */
653                         0x07, 0xd1,             /* bne          error */
654                         0x9d, 0x42,             /* cmp          r5, r3 */
655                         0x28, 0xbf,             /* it           cs */
656                         0x02, 0xf1, 0x08, 0x05, /* addcs        r5, r2, #8 */
657                         0x55, 0x60,             /* str          r5, [r2, #4] */
658                         0x01, 0x39,             /* subs         r1, r1, #1 */
659                         0x19, 0xb1,             /* cbz          r1, exit */
660                         0xe4, 0xe7,             /* b            wait_fifo */
661                 /* error: */
662                         0x00, 0x20,             /* movs         r0, #0 */
663                         0xc2, 0xf8,     0x02, 0x00, /* str      r0, [r2, #2] */
664                 /* exit: */
665                         0x30, 0x46,             /* mov          r0, r6 */
666                         0x00, 0xbe,             /* bkpt         #0 */
667         };
668
669         /* flash write code */
670         if (target_alloc_working_area(target, sizeof(stm32x_flash_write_code),
671                         &stm32x_info->write_algorithm) != ERROR_OK)
672         {
673                 LOG_WARNING("no working area available, can't do block memory writes");
674                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
675         };
676
677         if ((retval = target_write_buffer(target, stm32x_info->write_algorithm->address,
678                         sizeof(stm32x_flash_write_code),
679                         (uint8_t*)stm32x_flash_write_code)) != ERROR_OK)
680                 return retval;
681
682         /* memory buffer */
683         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK)
684         {
685                 buffer_size /= 2;
686                 buffer_size &= ~3UL; // Make sure it's 4 byte aligned
687                 if (buffer_size <= 256)
688                 {
689                         /* if we already allocated the writing code, but failed to get a
690                          * buffer, free the algorithm */
691                         if (stm32x_info->write_algorithm)
692                                 target_free_working_area(target, stm32x_info->write_algorithm);
693
694                         LOG_WARNING("no large enough working area available, can't do block memory writes");
695                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
696                 }
697         };
698
699         /* Set up working area. First word is write pointer, second word is read pointer,
700          * rest is fifo data area. */
701         uint32_t wp_addr = source->address;
702         uint32_t rp_addr = source->address + 4;
703         uint32_t fifo_start_addr = source->address + 8;
704         uint32_t fifo_end_addr = source->address + source->size;
705
706         uint32_t wp = fifo_start_addr;
707         uint32_t rp = fifo_start_addr;
708
709         retval = target_write_u32(target, wp_addr, wp);
710         if (retval != ERROR_OK)
711                 return retval;
712         retval = target_write_u32(target, rp_addr, rp);
713         if (retval != ERROR_OK)
714                 return retval;
715
716         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT); /* flash base (in), status (out) */
717         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);    /* count (halfword-16bit) */
718         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);    /* buffer start */
719         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);    /* buffer end */
720         init_reg_param(&reg_params[4], "r4", 32, PARAM_IN_OUT); /* target address */
721
722         buf_set_u32(reg_params[0].value, 0, 32, stm32x_info->register_base);
723         buf_set_u32(reg_params[1].value, 0, 32, count);
724         buf_set_u32(reg_params[2].value, 0, 32, source->address);
725         buf_set_u32(reg_params[3].value, 0, 32, source->address + source->size);
726         buf_set_u32(reg_params[4].value, 0, 32, address);
727
728         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
729         armv7m_info.core_mode = ARMV7M_MODE_ANY;
730
731         /* Start up algorithm on target and let it idle while writing the first chunk */
732         if ((retval = target_start_algorithm(target, 0, NULL, 5, reg_params,
733                         stm32x_info->write_algorithm->address,
734                         0,
735                         &armv7m_info)) != ERROR_OK)
736         {
737                 LOG_ERROR("error starting stm32x flash write algorithm");
738                 goto cleanup;
739         }
740
741         while (count > 0)
742         {
743                 retval = target_read_u32(target, rp_addr, &rp);
744                 if (retval != ERROR_OK)
745                 {
746                         LOG_ERROR("failed to get read pointer");
747                         break;
748                 }
749
750                 LOG_DEBUG("count 0x%"PRIx32" wp 0x%"PRIx32" rp 0x%"PRIx32, count, wp, rp);
751
752                 if (rp == 0)
753                 {
754                         LOG_ERROR("flash write algorithm aborted by target");
755                         retval = ERROR_FLASH_OPERATION_FAILED;
756                         break;
757                 }
758
759                 if ((rp & 1) || rp < fifo_start_addr || rp >= fifo_end_addr)
760                 {
761                         LOG_ERROR("corrupted fifo read pointer 0x%"PRIx32, rp);
762                         break;
763                 }
764
765                 /* Count the number of bytes available in the fifo without
766                  * crossing the wrap around. Make sure to not fill it completely,
767                  * because that would make wp == rp and that's the empty condition. */
768                 uint32_t thisrun_bytes;
769                 if (rp > wp)
770                         thisrun_bytes = rp - wp - 2;
771                 else if (rp > fifo_start_addr)
772                         thisrun_bytes = fifo_end_addr - wp;
773                 else
774                         thisrun_bytes = fifo_end_addr - wp - 2;
775
776                 if (thisrun_bytes == 0)
777                 {
778                         /* Throttle polling a bit if transfer is (much) faster than flash
779                          * programming. The exact delay shouldn't matter as long as it's
780                          * less than buffer size / flash speed. This is very unlikely to
781                          * run when using high latency connections such as USB. */
782                         alive_sleep(10);
783                         continue;
784                 }
785
786                 /* Limit to the amount of data we actually want to write */
787                 if (thisrun_bytes > count * 2)
788                         thisrun_bytes = count * 2;
789
790                 /* Write data to fifo */
791                 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
792                 if (retval != ERROR_OK)
793                         break;
794
795                 /* Update counters and wrap write pointer */
796                 buffer += thisrun_bytes;
797                 count -= thisrun_bytes / 2;
798                 wp += thisrun_bytes;
799                 if (wp >= fifo_end_addr)
800                         wp = fifo_start_addr;
801
802                 /* Store updated write pointer to target */
803                 retval = target_write_u32(target, wp_addr, wp);
804                 if (retval != ERROR_OK)
805                         break;
806         }
807
808         if (retval != ERROR_OK)
809         {
810                 /* abort flash write algorithm on target */
811                 target_write_u32(target, wp_addr, 0);
812         }
813
814         int retval2;
815         if ((retval2 = target_wait_algorithm(target, 0, NULL, 5, reg_params,
816                         0,
817                         10000,
818                         &armv7m_info)) != ERROR_OK)
819         {
820                 LOG_ERROR("error waiting for stm32x flash write algorithm");
821                 retval = retval2;
822         }
823
824         if (retval == ERROR_FLASH_OPERATION_FAILED)
825         {
826                 LOG_ERROR("flash write failed at address 0x%"PRIx32,
827                                 buf_get_u32(reg_params[4].value, 0, 32));
828
829                 if (buf_get_u32(reg_params[0].value, 0, 32) & FLASH_PGERR)
830                 {
831                         LOG_ERROR("flash memory not erased before writing");
832                         /* Clear but report errors */
833                         target_write_u32(target, STM32_FLASH_SR_B0, FLASH_PGERR);
834                 }
835
836                 if (buf_get_u32(reg_params[0].value, 0, 32) & FLASH_WRPRTERR)
837                 {
838                         LOG_ERROR("flash memory write protected");
839                         /* Clear but report errors */
840                         target_write_u32(target, STM32_FLASH_SR_B0, FLASH_WRPRTERR);
841                 }
842         }
843
844 cleanup:
845         target_free_working_area(target, source);
846         target_free_working_area(target, stm32x_info->write_algorithm);
847
848         destroy_reg_param(&reg_params[0]);
849         destroy_reg_param(&reg_params[1]);
850         destroy_reg_param(&reg_params[2]);
851         destroy_reg_param(&reg_params[3]);
852         destroy_reg_param(&reg_params[4]);
853
854         return retval;
855 }
856
857 static int stm32x_write(struct flash_bank *bank, uint8_t *buffer,
858                 uint32_t offset, uint32_t count)
859 {
860         struct target *target = bank->target;
861         uint32_t words_remaining = (count / 2);
862         uint32_t bytes_remaining = (count & 0x00000001);
863         uint32_t address = bank->base + offset;
864         uint32_t bytes_written = 0;
865         int retval;
866
867         if (bank->target->state != TARGET_HALTED)
868         {
869                 LOG_ERROR("Target not halted");
870                 return ERROR_TARGET_NOT_HALTED;
871         }
872
873         if (offset & 0x1)
874         {
875                 LOG_WARNING("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
876                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
877         }
878
879         /* unlock flash registers */
880         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_KEYR), KEY1);
881         if (retval != ERROR_OK)
882                 return retval;
883         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_KEYR), KEY2);
884         if (retval != ERROR_OK)
885                 return retval;
886
887         /* multiple half words (2-byte) to be programmed? */
888         if (words_remaining > 0)
889         {
890                 /* try using a block write */
891                 if ((retval = stm32x_write_block(bank, buffer, offset, words_remaining)) != ERROR_OK)
892                 {
893                         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
894                         {
895                                 /* if block write failed (no sufficient working area),
896                                  * we use normal (slow) single dword accesses */
897                                 LOG_WARNING("couldn't use block writes, falling back to single memory accesses");
898                         }
899                 }
900                 else
901                 {
902                         buffer += words_remaining * 2;
903                         address += words_remaining * 2;
904                         words_remaining = 0;
905                 }
906         }
907
908         if ((retval != ERROR_OK) && (retval != ERROR_TARGET_RESOURCE_NOT_AVAILABLE))
909                 return retval;
910
911         while (words_remaining > 0)
912         {
913                 uint16_t value;
914                 memcpy(&value, buffer + bytes_written, sizeof(uint16_t));
915
916                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_PG);
917                 if (retval != ERROR_OK)
918                         return retval;
919                 retval = target_write_u16(target, address, value);
920                 if (retval != ERROR_OK)
921                         return retval;
922
923                 retval = stm32x_wait_status_busy(bank, 5);
924                 if (retval != ERROR_OK)
925                         return retval;
926
927                 bytes_written += 2;
928                 words_remaining--;
929                 address += 2;
930         }
931
932         if (bytes_remaining)
933         {
934                 uint16_t value = 0xffff;
935                 memcpy(&value, buffer + bytes_written, bytes_remaining);
936
937                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_PG);
938                 if (retval != ERROR_OK)
939                         return retval;
940                 retval = target_write_u16(target, address, value);
941                 if (retval != ERROR_OK)
942                         return retval;
943
944                 retval = stm32x_wait_status_busy(bank, 5);
945                 if (retval != ERROR_OK)
946                         return retval;
947         }
948
949         return target_write_u32(target, STM32_FLASH_CR_B0, FLASH_LOCK);
950 }
951
952 static int stm32x_probe(struct flash_bank *bank)
953 {
954         struct target *target = bank->target;
955         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
956         int i;
957         uint16_t flash_size_in_kb;
958         uint32_t device_id;
959         int page_size;
960         uint32_t base_address = 0x08000000;
961
962         stm32x_info->probed = 0;
963         stm32x_info->register_base = FLASH_REG_BASE_B0;
964
965         /* read stm32 device id register */
966         int retval = target_read_u32(target, 0xE0042000, &device_id);
967         if (retval != ERROR_OK)
968                 return retval;
969         LOG_INFO("device id = 0x%08" PRIx32 "", device_id);
970
971         /* get flash size from target. */
972         retval = target_read_u16(target, 0x1FFFF7E0, &flash_size_in_kb);
973         if (retval != ERROR_OK)
974         {
975                 LOG_WARNING("failed reading flash size, default to max target family");
976                 /* failed reading flash size, default to max target family */
977                 flash_size_in_kb = 0xffff;
978         }
979
980         if ((device_id & 0xfff) == 0x410) {
981                 /* medium density - we have 1k pages
982                  * 4 pages for a protection area */
983                 page_size = 1024;
984                 stm32x_info->ppage_size = 4;
985
986                 /* check for early silicon */
987                 if (flash_size_in_kb == 0xffff)
988                 {
989                         /* number of sectors incorrect on revA */
990                         LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming 128k flash");
991                         flash_size_in_kb = 128;
992                 }
993         } else if ((device_id & 0xfff) == 0x412) {
994                 /* low density - we have 1k pages
995                  * 4 pages for a protection area */
996                 page_size = 1024;
997                 stm32x_info->ppage_size = 4;
998
999                 /* check for early silicon */
1000                 if (flash_size_in_kb == 0xffff)
1001                 {
1002                         /* number of sectors incorrect on revA */
1003                         LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming 32k flash");
1004                         flash_size_in_kb = 32;
1005                 }
1006         } else if ((device_id & 0xfff) == 0x414) {
1007                 /* high density - we have 2k pages
1008                  * 2 pages for a protection area */
1009                 page_size = 2048;
1010                 stm32x_info->ppage_size = 2;
1011
1012                 /* check for early silicon */
1013                 if (flash_size_in_kb == 0xffff)
1014                 {
1015                         /* number of sectors incorrect on revZ */
1016                         LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming 512k flash");
1017                         flash_size_in_kb = 512;
1018                 }
1019         } else if ((device_id & 0xfff) == 0x418) {
1020                 /* connectivity line density - we have 2k pages
1021                  * 2 pages for a protection area */
1022                 page_size = 2048;
1023                 stm32x_info->ppage_size = 2;
1024
1025                 /* check for early silicon */
1026                 if (flash_size_in_kb == 0xffff)
1027                 {
1028                         /* number of sectors incorrect on revZ */
1029                         LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming 256k flash");
1030                         flash_size_in_kb = 256;
1031                 }
1032         } else if ((device_id & 0xfff) == 0x420) {
1033                 /* value line density - we have 1k pages
1034                  * 4 pages for a protection area */
1035                 page_size = 1024;
1036                 stm32x_info->ppage_size = 4;
1037
1038                 /* check for early silicon */
1039                 if (flash_size_in_kb == 0xffff)
1040                 {
1041                         /* number of sectors may be incorrrect on early silicon */
1042                         LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming 128k flash");
1043                         flash_size_in_kb = 128;
1044                 }
1045         } else if ((device_id & 0xfff) == 0x428) {
1046                 /* value line High density - we have 2k pages
1047                  * 4 pages for a protection area */
1048                 page_size = 2048;
1049                 stm32x_info->ppage_size = 4;
1050
1051                 /* check for early silicon */
1052                 if (flash_size_in_kb == 0xffff)
1053                 {
1054                         /* number of sectors may be incorrrect on early silicon */
1055                         LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming 128k flash");
1056                         flash_size_in_kb = 128;
1057                 }
1058         } else if ((device_id & 0xfff) == 0x430) {
1059                 /* xl line density - we have 2k pages
1060                  * 2 pages for a protection area */
1061                 page_size = 2048;
1062                 stm32x_info->ppage_size = 2;
1063                 stm32x_info->has_dual_banks = true;
1064
1065                 /* check for early silicon */
1066                 if (flash_size_in_kb == 0xffff)
1067                 {
1068                         /* number of sectors may be incorrrect on early silicon */
1069                         LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming 1024k flash");
1070                         flash_size_in_kb = 1024;
1071                 }
1072
1073                 /* split reported size into matching bank */
1074                 if (bank->base != 0x08080000)
1075                 {
1076                         /* bank 0 will be fixed 512k */
1077                         flash_size_in_kb = 512;
1078                 }
1079                 else
1080                 {
1081                         flash_size_in_kb -= 512;
1082                         /* bank1 also uses a register offset */
1083                         stm32x_info->register_base = FLASH_REG_BASE_B1;
1084                         base_address = 0x08080000;
1085                 }
1086         }
1087         else
1088         {
1089                 LOG_WARNING("Cannot identify target as a STM32 family.");
1090                 return ERROR_FAIL;
1091         }
1092
1093         LOG_INFO("flash size = %dkbytes", flash_size_in_kb);
1094
1095         /* did we assign flash size? */
1096         assert(flash_size_in_kb != 0xffff);
1097
1098         /* calculate numbers of pages */
1099         int num_pages = flash_size_in_kb * 1024 / page_size;
1100
1101         /* check that calculation result makes sense */
1102         assert(num_pages > 0);
1103
1104         if (bank->sectors)
1105         {
1106                 free(bank->sectors);
1107                 bank->sectors = NULL;
1108         }
1109
1110         bank->base = base_address;
1111         bank->size = (num_pages * page_size);
1112         bank->num_sectors = num_pages;
1113         bank->sectors = malloc(sizeof(struct flash_sector) * num_pages);
1114
1115         for (i = 0; i < num_pages; i++)
1116         {
1117                 bank->sectors[i].offset = i * page_size;
1118                 bank->sectors[i].size = page_size;
1119                 bank->sectors[i].is_erased = -1;
1120                 bank->sectors[i].is_protected = 1;
1121         }
1122
1123         stm32x_info->probed = 1;
1124
1125         return ERROR_OK;
1126 }
1127
1128 static int stm32x_auto_probe(struct flash_bank *bank)
1129 {
1130         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
1131         if (stm32x_info->probed)
1132                 return ERROR_OK;
1133         return stm32x_probe(bank);
1134 }
1135
1136 #if 0
1137 COMMAND_HANDLER(stm32x_handle_part_id_command)
1138 {
1139         return ERROR_OK;
1140 }
1141 #endif
1142
1143 static int get_stm32x_info(struct flash_bank *bank, char *buf, int buf_size)
1144 {
1145         struct target *target = bank->target;
1146         uint32_t device_id;
1147         int printed;
1148
1149         /* read stm32 device id register */
1150         int retval = target_read_u32(target, 0xE0042000, &device_id);
1151         if (retval != ERROR_OK)
1152                 return retval;
1153
1154         if ((device_id & 0xfff) == 0x410) {
1155                 printed = snprintf(buf, buf_size, "stm32x (Medium Density) - Rev: ");
1156                 buf += printed;
1157                 buf_size -= printed;
1158
1159                 switch (device_id >> 16)
1160                 {
1161                         case 0x0000:
1162                                 snprintf(buf, buf_size, "A");
1163                                 break;
1164
1165                         case 0x2000:
1166                                 snprintf(buf, buf_size, "B");
1167                                 break;
1168
1169                         case 0x2001:
1170                                 snprintf(buf, buf_size, "Z");
1171                                 break;
1172
1173                         case 0x2003:
1174                                 snprintf(buf, buf_size, "Y");
1175                                 break;
1176
1177                         default:
1178                                 snprintf(buf, buf_size, "unknown");
1179                                 break;
1180                 }
1181         } else if ((device_id & 0xfff) == 0x412) {
1182                 printed = snprintf(buf, buf_size, "stm32x (Low Density) - Rev: ");
1183                 buf += printed;
1184                 buf_size -= printed;
1185
1186                 switch (device_id >> 16)
1187                 {
1188                         case 0x1000:
1189                                 snprintf(buf, buf_size, "A");
1190                                 break;
1191
1192                         default:
1193                                 snprintf(buf, buf_size, "unknown");
1194                                 break;
1195                 }
1196         } else if ((device_id & 0xfff) == 0x414) {
1197                 printed = snprintf(buf, buf_size, "stm32x (High Density) - Rev: ");
1198                 buf += printed;
1199                 buf_size -= printed;
1200
1201                 switch (device_id >> 16)
1202                 {
1203                         case 0x1000:
1204                                 snprintf(buf, buf_size, "A");
1205                                 break;
1206
1207                         case 0x1001:
1208                                 snprintf(buf, buf_size, "Z");
1209                                 break;
1210
1211                         default:
1212                                 snprintf(buf, buf_size, "unknown");
1213                                 break;
1214                 }
1215         } else if ((device_id & 0xfff) == 0x418) {
1216                 printed = snprintf(buf, buf_size, "stm32x (Connectivity) - Rev: ");
1217                 buf += printed;
1218                 buf_size -= printed;
1219
1220                 switch (device_id >> 16)
1221                 {
1222                         case 0x1000:
1223                                 snprintf(buf, buf_size, "A");
1224                                 break;
1225
1226                         case 0x1001:
1227                                 snprintf(buf, buf_size, "Z");
1228                                 break;
1229
1230                         default:
1231                                 snprintf(buf, buf_size, "unknown");
1232                                 break;
1233                 }
1234         } else if ((device_id & 0xfff) == 0x420) {
1235                 printed = snprintf(buf, buf_size, "stm32x (Value) - Rev: ");
1236                 buf += printed;
1237                 buf_size -= printed;
1238
1239                 switch (device_id >> 16)
1240                 {
1241                         case 0x1000:
1242                                 snprintf(buf, buf_size, "A");
1243                                 break;
1244
1245                         case 0x1001:
1246                                 snprintf(buf, buf_size, "Z");
1247                                 break;
1248
1249                         default:
1250                                 snprintf(buf, buf_size, "unknown");
1251                                 break;
1252                 }
1253         } else if ((device_id & 0xfff) == 0x428) {
1254                 printed = snprintf(buf, buf_size, "stm32x (Value HD) - Rev: ");
1255                 buf += printed;
1256                 buf_size -= printed;
1257
1258                 switch (device_id >> 16)
1259                 {
1260                         case 0x1000:
1261                                 snprintf(buf, buf_size, "A");
1262                                 break;
1263
1264                         case 0x1001:
1265                                 snprintf(buf, buf_size, "Z");
1266                                 break;
1267
1268                         default:
1269                                 snprintf(buf, buf_size, "unknown");
1270                                 break;
1271                 }
1272         } else if ((device_id & 0xfff) == 0x430) {
1273                 printed = snprintf(buf, buf_size, "stm32x (XL) - Rev: ");
1274                 buf += printed;
1275                 buf_size -= printed;
1276
1277                 switch (device_id >> 16)
1278                 {
1279                         case 0x1000:
1280                                 snprintf(buf, buf_size, "A");
1281                                 break;
1282
1283                         default:
1284                                 snprintf(buf, buf_size, "unknown");
1285                                 break;
1286                 }
1287         }
1288         else
1289         {
1290                 snprintf(buf, buf_size, "Cannot identify target as a stm32x\n");
1291                 return ERROR_FAIL;
1292         }
1293
1294         return ERROR_OK;
1295 }
1296
1297 COMMAND_HANDLER(stm32x_handle_lock_command)
1298 {
1299         struct target *target = NULL;
1300         struct stm32x_flash_bank *stm32x_info = NULL;
1301
1302         if (CMD_ARGC < 1)
1303         {
1304                 return ERROR_COMMAND_SYNTAX_ERROR;
1305         }
1306
1307         struct flash_bank *bank;
1308         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1309         if (ERROR_OK != retval)
1310                 return retval;
1311
1312         stm32x_info = bank->driver_priv;
1313
1314         target = bank->target;
1315
1316         if (target->state != TARGET_HALTED)
1317         {
1318                 LOG_ERROR("Target not halted");
1319                 return ERROR_TARGET_NOT_HALTED;
1320         }
1321
1322         retval = stm32x_check_operation_supported(bank);
1323         if (ERROR_OK != retval)
1324                 return retval;
1325
1326         if (stm32x_erase_options(bank) != ERROR_OK)
1327         {
1328                 command_print(CMD_CTX, "stm32x failed to erase options");
1329                 return ERROR_OK;
1330         }
1331
1332         /* set readout protection */
1333         stm32x_info->option_bytes.RDP = 0;
1334
1335         if (stm32x_write_options(bank) != ERROR_OK)
1336         {
1337                 command_print(CMD_CTX, "stm32x failed to lock device");
1338                 return ERROR_OK;
1339         }
1340
1341         command_print(CMD_CTX, "stm32x locked");
1342
1343         return ERROR_OK;
1344 }
1345
1346 COMMAND_HANDLER(stm32x_handle_unlock_command)
1347 {
1348         struct target *target = NULL;
1349
1350         if (CMD_ARGC < 1)
1351         {
1352                 return ERROR_COMMAND_SYNTAX_ERROR;
1353         }
1354
1355         struct flash_bank *bank;
1356         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1357         if (ERROR_OK != retval)
1358                 return retval;
1359
1360         target = bank->target;
1361
1362         if (target->state != TARGET_HALTED)
1363         {
1364                 LOG_ERROR("Target not halted");
1365                 return ERROR_TARGET_NOT_HALTED;
1366         }
1367
1368         retval = stm32x_check_operation_supported(bank);
1369         if (ERROR_OK != retval)
1370                 return retval;
1371
1372         if (stm32x_erase_options(bank) != ERROR_OK)
1373         {
1374                 command_print(CMD_CTX, "stm32x failed to unlock device");
1375                 return ERROR_OK;
1376         }
1377
1378         if (stm32x_write_options(bank) != ERROR_OK)
1379         {
1380                 command_print(CMD_CTX, "stm32x failed to lock device");
1381                 return ERROR_OK;
1382         }
1383
1384         command_print(CMD_CTX, "stm32x unlocked.\n"
1385                         "INFO: a reset or power cycle is required "
1386                         "for the new settings to take effect.");
1387
1388         return ERROR_OK;
1389 }
1390
1391 COMMAND_HANDLER(stm32x_handle_options_read_command)
1392 {
1393         uint32_t optionbyte;
1394         struct target *target = NULL;
1395         struct stm32x_flash_bank *stm32x_info = NULL;
1396
1397         if (CMD_ARGC < 1)
1398         {
1399                 return ERROR_COMMAND_SYNTAX_ERROR;
1400         }
1401
1402         struct flash_bank *bank;
1403         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1404         if (ERROR_OK != retval)
1405                 return retval;
1406
1407         stm32x_info = bank->driver_priv;
1408
1409         target = bank->target;
1410
1411         if (target->state != TARGET_HALTED)
1412         {
1413                 LOG_ERROR("Target not halted");
1414                 return ERROR_TARGET_NOT_HALTED;
1415         }
1416
1417         retval = stm32x_check_operation_supported(bank);
1418         if (ERROR_OK != retval)
1419                 return retval;
1420
1421         retval = target_read_u32(target, STM32_FLASH_OBR_B0, &optionbyte);
1422         if (retval != ERROR_OK)
1423                 return retval;
1424         command_print(CMD_CTX, "Option Byte: 0x%" PRIx32 "", optionbyte);
1425
1426         if (buf_get_u32((uint8_t*)&optionbyte, OPT_ERROR, 1))
1427                 command_print(CMD_CTX, "Option Byte Complement Error");
1428
1429         if (buf_get_u32((uint8_t*)&optionbyte, OPT_READOUT, 1))
1430                 command_print(CMD_CTX, "Readout Protection On");
1431         else
1432                 command_print(CMD_CTX, "Readout Protection Off");
1433
1434         if (buf_get_u32((uint8_t*)&optionbyte, OPT_RDWDGSW, 1))
1435                 command_print(CMD_CTX, "Software Watchdog");
1436         else
1437                 command_print(CMD_CTX, "Hardware Watchdog");
1438
1439         if (buf_get_u32((uint8_t*)&optionbyte, OPT_RDRSTSTOP, 1))
1440                 command_print(CMD_CTX, "Stop: No reset generated");
1441         else
1442                 command_print(CMD_CTX, "Stop: Reset generated");
1443
1444         if (buf_get_u32((uint8_t*)&optionbyte, OPT_RDRSTSTDBY, 1))
1445                 command_print(CMD_CTX, "Standby: No reset generated");
1446         else
1447                 command_print(CMD_CTX, "Standby: Reset generated");
1448
1449         if (stm32x_info->has_dual_banks)
1450         {
1451                 if (buf_get_u32((uint8_t*)&optionbyte, OPT_BFB2, 1))
1452                         command_print(CMD_CTX, "Boot: Bank 0");
1453                 else
1454                         command_print(CMD_CTX, "Boot: Bank 1");
1455         }
1456
1457         return ERROR_OK;
1458 }
1459
1460 COMMAND_HANDLER(stm32x_handle_options_write_command)
1461 {
1462         struct target *target = NULL;
1463         struct stm32x_flash_bank *stm32x_info = NULL;
1464         uint16_t optionbyte = 0xF8;
1465
1466         if (CMD_ARGC < 4)
1467         {
1468                 return ERROR_COMMAND_SYNTAX_ERROR;
1469         }
1470
1471         struct flash_bank *bank;
1472         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1473         if (ERROR_OK != retval)
1474                 return retval;
1475
1476         stm32x_info = bank->driver_priv;
1477
1478         target = bank->target;
1479
1480         if (target->state != TARGET_HALTED)
1481         {
1482                 LOG_ERROR("Target not halted");
1483                 return ERROR_TARGET_NOT_HALTED;
1484         }
1485
1486         retval = stm32x_check_operation_supported(bank);
1487         if (ERROR_OK != retval)
1488                 return retval;
1489
1490         /* REVISIT: ignores some options which we will display...
1491          * and doesn't insist on the specified syntax.
1492          */
1493
1494         /* OPT_RDWDGSW */
1495         if (strcmp(CMD_ARGV[1], "SWWDG") == 0)
1496         {
1497                 optionbyte |= (1 << 0);
1498         }
1499         else    /* REVISIT must be "HWWDG" then ... */
1500         {
1501                 optionbyte &= ~(1 << 0);
1502         }
1503
1504         /* OPT_RDRSTSTOP */
1505         if (strcmp(CMD_ARGV[2], "NORSTSTOP") == 0)
1506         {
1507                 optionbyte |= (1 << 1);
1508         }
1509         else    /* REVISIT must be "RSTSTNDBY" then ... */
1510         {
1511                 optionbyte &= ~(1 << 1);
1512         }
1513
1514         /* OPT_RDRSTSTDBY */
1515         if (strcmp(CMD_ARGV[3], "NORSTSTNDBY") == 0)
1516         {
1517                 optionbyte |= (1 << 2);
1518         }
1519         else    /* REVISIT must be "RSTSTOP" then ... */
1520         {
1521                 optionbyte &= ~(1 << 2);
1522         }
1523
1524         if (CMD_ARGC > 4 && stm32x_info->has_dual_banks)
1525         {
1526                 /* OPT_BFB2 */
1527                 if (strcmp(CMD_ARGV[4], "BOOT0") == 0)
1528                 {
1529                         optionbyte |= (1 << 3);
1530                 }
1531                 else
1532                 {
1533                         optionbyte &= ~(1 << 3);
1534                 }
1535         }
1536
1537         if (stm32x_erase_options(bank) != ERROR_OK)
1538         {
1539                 command_print(CMD_CTX, "stm32x failed to erase options");
1540                 return ERROR_OK;
1541         }
1542
1543         stm32x_info->option_bytes.user_options = optionbyte;
1544
1545         if (stm32x_write_options(bank) != ERROR_OK)
1546         {
1547                 command_print(CMD_CTX, "stm32x failed to write options");
1548                 return ERROR_OK;
1549         }
1550
1551         command_print(CMD_CTX, "stm32x write options complete.\n"
1552                                 "INFO: a reset or power cycle is required "
1553                                 "for the new settings to take effect.");
1554
1555         return ERROR_OK;
1556 }
1557
1558 static int stm32x_mass_erase(struct flash_bank *bank)
1559 {
1560         struct target *target = bank->target;
1561
1562         if (target->state != TARGET_HALTED)
1563         {
1564                 LOG_ERROR("Target not halted");
1565                 return ERROR_TARGET_NOT_HALTED;
1566         }
1567
1568         /* unlock option flash registers */
1569         int retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_KEYR), KEY1);
1570         if (retval != ERROR_OK)
1571                 return retval;
1572         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_KEYR), KEY2);
1573         if (retval != ERROR_OK)
1574                 return retval;
1575
1576         /* mass erase flash memory */
1577         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_MER);
1578         if (retval != ERROR_OK)
1579                 return retval;
1580         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_MER | FLASH_STRT);
1581         if (retval != ERROR_OK)
1582                 return retval;
1583
1584         retval = stm32x_wait_status_busy(bank, 100);
1585         if (retval != ERROR_OK)
1586                 return retval;
1587
1588         retval = target_write_u32(target, stm32x_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
1589         if (retval != ERROR_OK)
1590                 return retval;
1591
1592         return ERROR_OK;
1593 }
1594
1595 COMMAND_HANDLER(stm32x_handle_mass_erase_command)
1596 {
1597         int i;
1598
1599         if (CMD_ARGC < 1)
1600         {
1601                 return ERROR_COMMAND_SYNTAX_ERROR;
1602         }
1603
1604         struct flash_bank *bank;
1605         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1606         if (ERROR_OK != retval)
1607                 return retval;
1608
1609         retval = stm32x_mass_erase(bank);
1610         if (retval == ERROR_OK)
1611         {
1612                 /* set all sectors as erased */
1613                 for (i = 0; i < bank->num_sectors; i++)
1614                 {
1615                         bank->sectors[i].is_erased = 1;
1616                 }
1617
1618                 command_print(CMD_CTX, "stm32x mass erase complete");
1619         }
1620         else
1621         {
1622                 command_print(CMD_CTX, "stm32x mass erase failed");
1623         }
1624
1625         return retval;
1626 }
1627
1628 static const struct command_registration stm32x_exec_command_handlers[] = {
1629         {
1630                 .name = "lock",
1631                 .handler = stm32x_handle_lock_command,
1632                 .mode = COMMAND_EXEC,
1633                 .usage = "bank_id",
1634                 .help = "Lock entire flash device.",
1635         },
1636         {
1637                 .name = "unlock",
1638                 .handler = stm32x_handle_unlock_command,
1639                 .mode = COMMAND_EXEC,
1640                 .usage = "bank_id",
1641                 .help = "Unlock entire protected flash device.",
1642         },
1643         {
1644                 .name = "mass_erase",
1645                 .handler = stm32x_handle_mass_erase_command,
1646                 .mode = COMMAND_EXEC,
1647                 .usage = "bank_id",
1648                 .help = "Erase entire flash device.",
1649         },
1650         {
1651                 .name = "options_read",
1652                 .handler = stm32x_handle_options_read_command,
1653                 .mode = COMMAND_EXEC,
1654                 .usage = "bank_id",
1655                 .help = "Read and display device option byte.",
1656         },
1657         {
1658                 .name = "options_write",
1659                 .handler = stm32x_handle_options_write_command,
1660                 .mode = COMMAND_EXEC,
1661                 .usage = "bank_id ('SWWDG'|'HWWDG') "
1662                         "('RSTSTNDBY'|'NORSTSTNDBY') "
1663                         "('RSTSTOP'|'NORSTSTOP')",
1664                 .help = "Replace bits in device option byte.",
1665         },
1666         COMMAND_REGISTRATION_DONE
1667 };
1668
1669 static const struct command_registration stm32x_command_handlers[] = {
1670         {
1671                 .name = "stm32f1x",
1672                 .mode = COMMAND_ANY,
1673                 .help = "stm32f1x flash command group",
1674                 .chain = stm32x_exec_command_handlers,
1675         },
1676         COMMAND_REGISTRATION_DONE
1677 };
1678
1679 struct flash_driver stm32f1x_flash = {
1680         .name = "stm32f1x",
1681         .commands = stm32x_command_handlers,
1682         .flash_bank_command = stm32x_flash_bank_command,
1683         .erase = stm32x_erase,
1684         .protect = stm32x_protect,
1685         .write = stm32x_write,
1686         .read = default_flash_read,
1687         .probe = stm32x_probe,
1688         .auto_probe = stm32x_auto_probe,
1689         .erase_check = default_flash_mem_blank_check,
1690         .protect_check = stm32x_protect_check,
1691         .info = get_stm32x_info,
1692 };