stm32x: allow flash probe on a running target
[fw/openocd] / src / flash / nor / stm32x.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  *   This program is free software; you can redistribute it and/or modify  *
9  *   it under the terms of the GNU General Public License as published by  *
10  *   the Free Software Foundation; either version 2 of the License, or     *
11  *   (at your option) any later version.                                   *
12  *                                                                         *
13  *   This program is distributed in the hope that it will be useful,       *
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
16  *   GNU General Public License for more details.                          *
17  *                                                                         *
18  *   You should have received a copy of the GNU General Public License     *
19  *   along with this program; if not, write to the                         *
20  *   Free Software Foundation, Inc.,                                       *
21  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
22  ***************************************************************************/
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include "imp.h"
28 #include "stm32x.h"
29 #include <helper/binarybuffer.h>
30 #include <target/algorithm.h>
31 #include <target/armv7m.h>
32
33
34 static int stm32x_mass_erase(struct flash_bank *bank);
35
36 /* flash bank stm32x <base> <size> 0 0 <target#>
37  */
38 FLASH_BANK_COMMAND_HANDLER(stm32x_flash_bank_command)
39 {
40         struct stm32x_flash_bank *stm32x_info;
41
42         if (CMD_ARGC < 6)
43         {
44                 LOG_WARNING("incomplete flash_bank stm32x configuration");
45                 return ERROR_FLASH_BANK_INVALID;
46         }
47
48         stm32x_info = malloc(sizeof(struct stm32x_flash_bank));
49         bank->driver_priv = stm32x_info;
50
51         stm32x_info->write_algorithm = NULL;
52         stm32x_info->probed = 0;
53
54         return ERROR_OK;
55 }
56
57 static uint32_t stm32x_get_flash_status(struct flash_bank *bank)
58 {
59         struct target *target = bank->target;
60         uint32_t status;
61
62         target_read_u32(target, STM32_FLASH_SR, &status);
63
64         return status;
65 }
66
67 static uint32_t stm32x_wait_status_busy(struct flash_bank *bank, int timeout)
68 {
69         struct target *target = bank->target;
70         uint32_t status;
71
72         /* wait for busy to clear */
73         while (((status = stm32x_get_flash_status(bank)) & FLASH_BSY) && (timeout-- > 0))
74         {
75                 LOG_DEBUG("status: 0x%" PRIx32 "", status);
76                 alive_sleep(1);
77         }
78         /* Clear but report errors */
79         if (status & (FLASH_WRPRTERR | FLASH_PGERR))
80         {
81                 target_write_u32(target, STM32_FLASH_SR, FLASH_WRPRTERR | FLASH_PGERR);
82         }
83         return status;
84 }
85
86 static int stm32x_read_options(struct flash_bank *bank)
87 {
88         uint32_t optiondata;
89         struct stm32x_flash_bank *stm32x_info = NULL;
90         struct target *target = bank->target;
91
92         stm32x_info = bank->driver_priv;
93
94         /* read current option bytes */
95         target_read_u32(target, STM32_FLASH_OBR, &optiondata);
96
97         stm32x_info->option_bytes.user_options = (uint16_t)0xFFF8 | ((optiondata >> 2) & 0x07);
98         stm32x_info->option_bytes.RDP = (optiondata & (1 << OPT_READOUT)) ? 0xFFFF : 0x5AA5;
99
100         if (optiondata & (1 << OPT_READOUT))
101                 LOG_INFO("Device Security Bit Set");
102
103         /* each bit refers to a 4bank protection */
104         target_read_u32(target, STM32_FLASH_WRPR, &optiondata);
105
106         stm32x_info->option_bytes.protection[0] = (uint16_t)optiondata;
107         stm32x_info->option_bytes.protection[1] = (uint16_t)(optiondata >> 8);
108         stm32x_info->option_bytes.protection[2] = (uint16_t)(optiondata >> 16);
109         stm32x_info->option_bytes.protection[3] = (uint16_t)(optiondata >> 24);
110
111         return ERROR_OK;
112 }
113
114 static int stm32x_erase_options(struct flash_bank *bank)
115 {
116         struct stm32x_flash_bank *stm32x_info = NULL;
117         struct target *target = bank->target;
118         uint32_t status;
119
120         stm32x_info = bank->driver_priv;
121
122         /* read current options */
123         stm32x_read_options(bank);
124
125         /* unlock flash registers */
126         target_write_u32(target, STM32_FLASH_KEYR, KEY1);
127         target_write_u32(target, STM32_FLASH_KEYR, KEY2);
128
129         /* unlock option flash registers */
130         target_write_u32(target, STM32_FLASH_OPTKEYR, KEY1);
131         target_write_u32(target, STM32_FLASH_OPTKEYR, KEY2);
132
133         /* erase option bytes */
134         target_write_u32(target, STM32_FLASH_CR, FLASH_OPTER | FLASH_OPTWRE);
135         target_write_u32(target, STM32_FLASH_CR, FLASH_OPTER | FLASH_STRT | FLASH_OPTWRE);
136
137         status = stm32x_wait_status_busy(bank, 10);
138
139         if (status & FLASH_WRPRTERR)
140                 return ERROR_FLASH_OPERATION_FAILED;
141         if (status & FLASH_PGERR)
142                 return ERROR_FLASH_OPERATION_FAILED;
143
144         /* clear readout protection and complementary option bytes
145          * this will also force a device unlock if set */
146         stm32x_info->option_bytes.RDP = 0x5AA5;
147
148         return ERROR_OK;
149 }
150
151 static int stm32x_write_options(struct flash_bank *bank)
152 {
153         struct stm32x_flash_bank *stm32x_info = NULL;
154         struct target *target = bank->target;
155         uint32_t status;
156
157         stm32x_info = bank->driver_priv;
158
159         /* unlock flash registers */
160         target_write_u32(target, STM32_FLASH_KEYR, KEY1);
161         target_write_u32(target, STM32_FLASH_KEYR, KEY2);
162
163         /* unlock option flash registers */
164         target_write_u32(target, STM32_FLASH_OPTKEYR, KEY1);
165         target_write_u32(target, STM32_FLASH_OPTKEYR, KEY2);
166
167         /* program option bytes */
168         target_write_u32(target, STM32_FLASH_CR, FLASH_OPTPG | FLASH_OPTWRE);
169
170         /* write user option byte */
171         target_write_u16(target, STM32_OB_USER, stm32x_info->option_bytes.user_options);
172
173         status = stm32x_wait_status_busy(bank, 10);
174
175         if (status & FLASH_WRPRTERR)
176                 return ERROR_FLASH_OPERATION_FAILED;
177         if (status & FLASH_PGERR)
178                 return ERROR_FLASH_OPERATION_FAILED;
179
180         /* write protection byte 1 */
181         target_write_u16(target, STM32_OB_WRP0, stm32x_info->option_bytes.protection[0]);
182
183         status = stm32x_wait_status_busy(bank, 10);
184
185         if (status & FLASH_WRPRTERR)
186                 return ERROR_FLASH_OPERATION_FAILED;
187         if (status & FLASH_PGERR)
188                 return ERROR_FLASH_OPERATION_FAILED;
189
190         /* write protection byte 2 */
191         target_write_u16(target, STM32_OB_WRP1, stm32x_info->option_bytes.protection[1]);
192
193         status = stm32x_wait_status_busy(bank, 10);
194
195         if (status & FLASH_WRPRTERR)
196                 return ERROR_FLASH_OPERATION_FAILED;
197         if (status & FLASH_PGERR)
198                 return ERROR_FLASH_OPERATION_FAILED;
199
200         /* write protection byte 3 */
201         target_write_u16(target, STM32_OB_WRP2, stm32x_info->option_bytes.protection[2]);
202
203         status = stm32x_wait_status_busy(bank, 10);
204
205         if (status & FLASH_WRPRTERR)
206                 return ERROR_FLASH_OPERATION_FAILED;
207         if (status & FLASH_PGERR)
208                 return ERROR_FLASH_OPERATION_FAILED;
209
210         /* write protection byte 4 */
211         target_write_u16(target, STM32_OB_WRP3, stm32x_info->option_bytes.protection[3]);
212
213         status = stm32x_wait_status_busy(bank, 10);
214
215         if (status & FLASH_WRPRTERR)
216                 return ERROR_FLASH_OPERATION_FAILED;
217         if (status & FLASH_PGERR)
218                 return ERROR_FLASH_OPERATION_FAILED;
219
220         /* write readout protection bit */
221         target_write_u16(target, STM32_OB_RDP, stm32x_info->option_bytes.RDP);
222
223         status = stm32x_wait_status_busy(bank, 10);
224
225         if (status & FLASH_WRPRTERR)
226                 return ERROR_FLASH_OPERATION_FAILED;
227         if (status & FLASH_PGERR)
228                 return ERROR_FLASH_OPERATION_FAILED;
229
230         target_write_u32(target, STM32_FLASH_CR, FLASH_LOCK);
231
232         return ERROR_OK;
233 }
234
235 static int stm32x_protect_check(struct flash_bank *bank)
236 {
237         struct target *target = bank->target;
238         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
239
240         uint32_t protection;
241         int i, s;
242         int num_bits;
243         int set;
244
245         if (target->state != TARGET_HALTED)
246         {
247                 LOG_ERROR("Target not halted");
248                 return ERROR_TARGET_NOT_HALTED;
249         }
250
251         /* medium density - each bit refers to a 4bank protection
252          * high density - each bit refers to a 2bank protection */
253         target_read_u32(target, STM32_FLASH_WRPR, &protection);
254
255         /* medium density - each protection bit is for 4 * 1K pages
256          * high density - each protection bit is for 2 * 2K pages */
257         num_bits = (bank->num_sectors / stm32x_info->ppage_size);
258
259         if (stm32x_info->ppage_size == 2)
260         {
261                 /* high density flash/connectivity line protection */
262
263                 set = 1;
264
265                 if (protection & (1 << 31))
266                         set = 0;
267
268                 /* bit 31 controls sector 62 - 255 protection for high density
269                  * bit 31 controls sector 62 - 127 protection for connectivity line */
270                 for (s = 62; s < bank->num_sectors; s++)
271                 {
272                         bank->sectors[s].is_protected = set;
273                 }
274
275                 if (bank->num_sectors > 61)
276                         num_bits = 31;
277
278                 for (i = 0; i < num_bits; i++)
279                 {
280                         set = 1;
281
282                         if (protection & (1 << i))
283                                 set = 0;
284
285                         for (s = 0; s < stm32x_info->ppage_size; s++)
286                                 bank->sectors[(i * stm32x_info->ppage_size) + s].is_protected = set;
287                 }
288         }
289         else
290         {
291                 /* low/medium density flash protection */
292                 for (i = 0; i < num_bits; i++)
293                 {
294                         set = 1;
295
296                         if (protection & (1 << i))
297                                 set = 0;
298
299                         for (s = 0; s < stm32x_info->ppage_size; s++)
300                                 bank->sectors[(i * stm32x_info->ppage_size) + s].is_protected = set;
301                 }
302         }
303
304         return ERROR_OK;
305 }
306
307 static int stm32x_erase(struct flash_bank *bank, int first, int last)
308 {
309         struct target *target = bank->target;
310         int i;
311         uint32_t status;
312
313         if (bank->target->state != TARGET_HALTED)
314         {
315                 LOG_ERROR("Target not halted");
316                 return ERROR_TARGET_NOT_HALTED;
317         }
318
319         if ((first == 0) && (last == (bank->num_sectors - 1)))
320         {
321                 return stm32x_mass_erase(bank);
322         }
323
324         /* unlock flash registers */
325         target_write_u32(target, STM32_FLASH_KEYR, KEY1);
326         target_write_u32(target, STM32_FLASH_KEYR, KEY2);
327
328         for (i = first; i <= last; i++)
329         {
330                 target_write_u32(target, STM32_FLASH_CR, FLASH_PER);
331                 target_write_u32(target, STM32_FLASH_AR, bank->base + bank->sectors[i].offset);
332                 target_write_u32(target, STM32_FLASH_CR, FLASH_PER | FLASH_STRT);
333
334                 status = stm32x_wait_status_busy(bank, 10);
335
336                 if (status & FLASH_WRPRTERR)
337                         return ERROR_FLASH_OPERATION_FAILED;
338                 if (status & FLASH_PGERR)
339                         return ERROR_FLASH_OPERATION_FAILED;
340                 bank->sectors[i].is_erased = 1;
341         }
342
343         target_write_u32(target, STM32_FLASH_CR, FLASH_LOCK);
344
345         return ERROR_OK;
346 }
347
348 static int stm32x_protect(struct flash_bank *bank, int set, int first, int last)
349 {
350         struct stm32x_flash_bank *stm32x_info = NULL;
351         struct target *target = bank->target;
352         uint16_t prot_reg[4] = {0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF};
353         int i, reg, bit;
354         int status;
355         uint32_t protection;
356
357         stm32x_info = bank->driver_priv;
358
359         if (target->state != TARGET_HALTED)
360         {
361                 LOG_ERROR("Target not halted");
362                 return ERROR_TARGET_NOT_HALTED;
363         }
364
365         if ((first && (first % stm32x_info->ppage_size)) || ((last + 1) &&
366                         (last + 1) % stm32x_info->ppage_size))
367         {
368                 LOG_WARNING("Error: start and end sectors must be on a %d sector boundary",
369                                 stm32x_info->ppage_size);
370                 return ERROR_FLASH_SECTOR_INVALID;
371         }
372
373         /* medium density - each bit refers to a 4bank protection
374          * high density - each bit refers to a 2bank protection */
375         target_read_u32(target, STM32_FLASH_WRPR, &protection);
376
377         prot_reg[0] = (uint16_t)protection;
378         prot_reg[1] = (uint16_t)(protection >> 8);
379         prot_reg[2] = (uint16_t)(protection >> 16);
380         prot_reg[3] = (uint16_t)(protection >> 24);
381
382         if (stm32x_info->ppage_size == 2)
383         {
384                 /* high density flash */
385
386                 /* bit 7 controls sector 62 - 255 protection */
387                 if (last > 61)
388                 {
389                         if (set)
390                                 prot_reg[3] &= ~(1 << 7);
391                         else
392                                 prot_reg[3] |= (1 << 7);
393                 }
394
395                 if (first > 61)
396                         first = 62;
397                 if (last > 61)
398                         last = 61;
399
400                 for (i = first; i <= last; i++)
401                 {
402                         reg = (i / stm32x_info->ppage_size) / 8;
403                         bit = (i / stm32x_info->ppage_size) - (reg * 8);
404
405                         if (set)
406                                 prot_reg[reg] &= ~(1 << bit);
407                         else
408                                 prot_reg[reg] |= (1 << bit);
409                 }
410         }
411         else
412         {
413                 /* medium density flash */
414                 for (i = first; i <= last; i++)
415                 {
416                         reg = (i / stm32x_info->ppage_size) / 8;
417                         bit = (i / stm32x_info->ppage_size) - (reg * 8);
418
419                         if (set)
420                                 prot_reg[reg] &= ~(1 << bit);
421                         else
422                                 prot_reg[reg] |= (1 << bit);
423                 }
424         }
425
426         if ((status = stm32x_erase_options(bank)) != ERROR_OK)
427                 return status;
428
429         stm32x_info->option_bytes.protection[0] = prot_reg[0];
430         stm32x_info->option_bytes.protection[1] = prot_reg[1];
431         stm32x_info->option_bytes.protection[2] = prot_reg[2];
432         stm32x_info->option_bytes.protection[3] = prot_reg[3];
433
434         return stm32x_write_options(bank);
435 }
436
437 static int stm32x_write_block(struct flash_bank *bank, uint8_t *buffer,
438                 uint32_t offset, uint32_t count)
439 {
440         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
441         struct target *target = bank->target;
442         uint32_t buffer_size = 16384;
443         struct working_area *source;
444         uint32_t address = bank->base + offset;
445         struct reg_param reg_params[4];
446         struct armv7m_algorithm armv7m_info;
447         int retval = ERROR_OK;
448
449         static const uint8_t stm32x_flash_write_code[] = {
450                                                                         /* write: */
451                 0xDF, 0xF8, 0x24, 0x40,         /* ldr  r4, STM32_FLASH_CR */
452                 0x09, 0x4D,                                     /* ldr  r5, STM32_FLASH_SR */
453                 0x4F, 0xF0, 0x01, 0x03,         /* mov  r3, #1 */
454                 0x23, 0x60,                                     /* str  r3, [r4, #0] */
455                 0x30, 0xF8, 0x02, 0x3B,         /* ldrh r3, [r0], #2 */
456                 0x21, 0xF8, 0x02, 0x3B,         /* strh r3, [r1], #2 */
457                                                                         /* busy: */
458                 0x2B, 0x68,                                     /* ldr  r3, [r5, #0] */
459                 0x13, 0xF0, 0x01, 0x0F,         /* tst  r3, #0x01 */
460                 0xFB, 0xD0,                                     /* beq  busy */
461                 0x13, 0xF0, 0x14, 0x0F,         /* tst  r3, #0x14 */
462                 0x01, 0xD1,                                     /* bne  exit */
463                 0x01, 0x3A,                                     /* subs r2, r2, #1 */
464                 0xED, 0xD1,                                     /* bne  write */
465                 0x00, 0xBE,                             /* bkpt #0 */
466                 0x10, 0x20, 0x02, 0x40,         /* STM32_FLASH_CR:      .word 0x40022010 */
467                 0x0C, 0x20, 0x02, 0x40          /* STM32_FLASH_SR:      .word 0x4002200C */
468         };
469
470         /* flash write code */
471         if (target_alloc_working_area(target, sizeof(stm32x_flash_write_code),
472                         &stm32x_info->write_algorithm) != ERROR_OK)
473         {
474                 LOG_WARNING("no working area available, can't do block memory writes");
475                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
476         };
477
478         if ((retval = target_write_buffer(target, stm32x_info->write_algorithm->address,
479                         sizeof(stm32x_flash_write_code),
480                         (uint8_t*)stm32x_flash_write_code)) != ERROR_OK)
481                 return retval;
482
483         /* memory buffer */
484         while (target_alloc_working_area(target, buffer_size, &source) != ERROR_OK)
485         {
486                 buffer_size /= 2;
487                 if (buffer_size <= 256)
488                 {
489                         /* if we already allocated the writing code, but failed to get a
490                          * buffer, free the algorithm */
491                         if (stm32x_info->write_algorithm)
492                                 target_free_working_area(target, stm32x_info->write_algorithm);
493
494                         LOG_WARNING("no large enough working area available, can't do block memory writes");
495                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
496                 }
497         };
498
499         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
500         armv7m_info.core_mode = ARMV7M_MODE_ANY;
501
502         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
503         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
504         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
505         init_reg_param(&reg_params[3], "r3", 32, PARAM_IN);
506
507         while (count > 0)
508         {
509                 uint32_t thisrun_count = (count > (buffer_size / 2)) ?
510                                 (buffer_size / 2) : count;
511
512                 if ((retval = target_write_buffer(target, source->address,
513                                 thisrun_count * 2, buffer)) != ERROR_OK)
514                         break;
515
516                 buf_set_u32(reg_params[0].value, 0, 32, source->address);
517                 buf_set_u32(reg_params[1].value, 0, 32, address);
518                 buf_set_u32(reg_params[2].value, 0, 32, thisrun_count);
519
520                 if ((retval = target_run_algorithm(target, 0, NULL, 4, reg_params,
521                                 stm32x_info->write_algorithm->address,
522                                 stm32x_info->write_algorithm->address + (sizeof(stm32x_flash_write_code) - 10),
523                                 10000, &armv7m_info)) != ERROR_OK)
524                 {
525                         LOG_ERROR("error executing stm32x flash write algorithm");
526                         retval = ERROR_FLASH_OPERATION_FAILED;
527                         break;
528                 }
529
530                 if (buf_get_u32(reg_params[3].value, 0, 32) & FLASH_PGERR)
531                 {
532                         LOG_ERROR("flash memory not erased before writing");
533                         /* Clear but report errors */
534                         target_write_u32(target, STM32_FLASH_SR, FLASH_PGERR);
535                         retval = ERROR_FLASH_OPERATION_FAILED;
536                         break;
537                 }
538
539                 if (buf_get_u32(reg_params[3].value, 0, 32) & FLASH_WRPRTERR)
540                 {
541                         LOG_ERROR("flash memory write protected");
542                         /* Clear but report errors */
543                         target_write_u32(target, STM32_FLASH_SR, FLASH_WRPRTERR);
544                         retval = ERROR_FLASH_OPERATION_FAILED;
545                         break;
546                 }
547
548                 buffer += thisrun_count * 2;
549                 address += thisrun_count * 2;
550                 count -= thisrun_count;
551         }
552
553         target_free_working_area(target, source);
554         target_free_working_area(target, stm32x_info->write_algorithm);
555
556         destroy_reg_param(&reg_params[0]);
557         destroy_reg_param(&reg_params[1]);
558         destroy_reg_param(&reg_params[2]);
559         destroy_reg_param(&reg_params[3]);
560
561         return retval;
562 }
563
564 static int stm32x_write(struct flash_bank *bank, uint8_t *buffer,
565                 uint32_t offset, uint32_t count)
566 {
567         struct target *target = bank->target;
568         uint32_t words_remaining = (count / 2);
569         uint32_t bytes_remaining = (count & 0x00000001);
570         uint32_t address = bank->base + offset;
571         uint32_t bytes_written = 0;
572         uint8_t status;
573         int retval;
574
575         if (bank->target->state != TARGET_HALTED)
576         {
577                 LOG_ERROR("Target not halted");
578                 return ERROR_TARGET_NOT_HALTED;
579         }
580
581         if (offset & 0x1)
582         {
583                 LOG_WARNING("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
584                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
585         }
586
587         /* unlock flash registers */
588         target_write_u32(target, STM32_FLASH_KEYR, KEY1);
589         target_write_u32(target, STM32_FLASH_KEYR, KEY2);
590
591         /* multiple half words (2-byte) to be programmed? */
592         if (words_remaining > 0)
593         {
594                 /* try using a block write */
595                 if ((retval = stm32x_write_block(bank, buffer, offset, words_remaining)) != ERROR_OK)
596                 {
597                         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
598                         {
599                                 /* if block write failed (no sufficient working area),
600                                  * we use normal (slow) single dword accesses */
601                                 LOG_WARNING("couldn't use block writes, falling back to single memory accesses");
602                         }
603                         else if (retval == ERROR_FLASH_OPERATION_FAILED)
604                         {
605                                 LOG_ERROR("flash writing failed with error code: 0x%x", retval);
606                                 return ERROR_FLASH_OPERATION_FAILED;
607                         }
608                 }
609                 else
610                 {
611                         buffer += words_remaining * 2;
612                         address += words_remaining * 2;
613                         words_remaining = 0;
614                 }
615         }
616
617         while (words_remaining > 0)
618         {
619                 uint16_t value;
620                 memcpy(&value, buffer + bytes_written, sizeof(uint16_t));
621
622                 target_write_u32(target, STM32_FLASH_CR, FLASH_PG);
623                 target_write_u16(target, address, value);
624
625                 status = stm32x_wait_status_busy(bank, 5);
626
627                 if (status & FLASH_WRPRTERR)
628                 {
629                         LOG_ERROR("flash memory not erased before writing");
630                         return ERROR_FLASH_OPERATION_FAILED;
631                 }
632                 if (status & FLASH_PGERR)
633                 {
634                         LOG_ERROR("flash memory write protected");
635                         return ERROR_FLASH_OPERATION_FAILED;
636                 }
637
638                 bytes_written += 2;
639                 words_remaining--;
640                 address += 2;
641         }
642
643         if (bytes_remaining)
644         {
645                 uint16_t value = 0xffff;
646                 memcpy(&value, buffer + bytes_written, bytes_remaining);
647
648                 target_write_u32(target, STM32_FLASH_CR, FLASH_PG);
649                 target_write_u16(target, address, value);
650
651                 status = stm32x_wait_status_busy(bank, 5);
652
653                 if (status & FLASH_WRPRTERR)
654                 {
655                         LOG_ERROR("flash memory not erased before writing");
656                         return ERROR_FLASH_OPERATION_FAILED;
657                 }
658                 if (status & FLASH_PGERR)
659                 {
660                         LOG_ERROR("flash memory write protected");
661                         return ERROR_FLASH_OPERATION_FAILED;
662                 }
663         }
664
665         target_write_u32(target, STM32_FLASH_CR, FLASH_LOCK);
666
667         return ERROR_OK;
668 }
669
670 static int stm32x_probe(struct flash_bank *bank)
671 {
672         struct target *target = bank->target;
673         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
674         int i;
675         uint16_t num_pages;
676         uint32_t device_id;
677         int page_size;
678
679         stm32x_info->probed = 0;
680
681         /* read stm32 device id register */
682         target_read_u32(target, 0xE0042000, &device_id);
683         LOG_INFO("device id = 0x%08" PRIx32 "", device_id);
684
685         /* get flash size from target */
686         if (target_read_u16(target, 0x1FFFF7E0, &num_pages) != ERROR_OK)
687         {
688                 /* failed reading flash size, default to max target family */
689                 num_pages = 0xffff;
690         }
691
692         if ((device_id & 0x7ff) == 0x410)
693         {
694                 /* medium density - we have 1k pages
695                  * 4 pages for a protection area */
696                 page_size = 1024;
697                 stm32x_info->ppage_size = 4;
698
699                 /* check for early silicon */
700                 if (num_pages == 0xffff)
701                 {
702                         /* number of sectors incorrect on revA */
703                         LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming 128k flash");
704                         num_pages = 128;
705                 }
706         }
707         else if ((device_id & 0x7ff) == 0x412)
708         {
709                 /* low density - we have 1k pages
710                  * 4 pages for a protection area */
711                 page_size = 1024;
712                 stm32x_info->ppage_size = 4;
713
714                 /* check for early silicon */
715                 if (num_pages == 0xffff)
716                 {
717                         /* number of sectors incorrect on revA */
718                         LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming 32k flash");
719                         num_pages = 32;
720                 }
721         }
722         else if ((device_id & 0x7ff) == 0x414)
723         {
724                 /* high density - we have 2k pages
725                  * 2 pages for a protection area */
726                 page_size = 2048;
727                 stm32x_info->ppage_size = 2;
728
729                 /* check for early silicon */
730                 if (num_pages == 0xffff)
731                 {
732                         /* number of sectors incorrect on revZ */
733                         LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming 512k flash");
734                         num_pages = 512;
735                 }
736         }
737         else if ((device_id & 0x7ff) == 0x418)
738         {
739                 /* connectivity line density - we have 2k pages
740                  * 2 pages for a protection area */
741                 page_size = 2048;
742                 stm32x_info->ppage_size = 2;
743
744                 /* check for early silicon */
745                 if (num_pages == 0xffff)
746                 {
747                         /* number of sectors incorrect on revZ */
748                         LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming 256k flash");
749                         num_pages = 256;
750                 }
751         }
752         else if ((device_id & 0x7ff) == 0x420)
753         {
754                 /* value line density - we have 1k pages
755                  * 4 pages for a protection area */
756                 page_size = 1024;
757                 stm32x_info->ppage_size = 4;
758
759                 /* check for early silicon */
760                 if (num_pages == 0xffff)
761                 {
762                         /* number of sectors may be incorrrect on early silicon */
763                         LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming 128k flash");
764                         num_pages = 128;
765                 }
766         }
767         else
768         {
769                 LOG_WARNING("Cannot identify target as a STM32 family.");
770                 return ERROR_FLASH_OPERATION_FAILED;
771         }
772
773         LOG_INFO("flash size = %dkbytes", num_pages);
774
775         /* calculate numbers of pages */
776         num_pages /= (page_size / 1024);
777
778         bank->base = 0x08000000;
779         bank->size = (num_pages * page_size);
780         bank->num_sectors = num_pages;
781         bank->sectors = malloc(sizeof(struct flash_sector) * num_pages);
782
783         for (i = 0; i < num_pages; i++)
784         {
785                 bank->sectors[i].offset = i * page_size;
786                 bank->sectors[i].size = page_size;
787                 bank->sectors[i].is_erased = -1;
788                 bank->sectors[i].is_protected = 1;
789         }
790
791         stm32x_info->probed = 1;
792
793         return ERROR_OK;
794 }
795
796 static int stm32x_auto_probe(struct flash_bank *bank)
797 {
798         struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
799         if (stm32x_info->probed)
800                 return ERROR_OK;
801         return stm32x_probe(bank);
802 }
803
804 #if 0
805 COMMAND_HANDLER(stm32x_handle_part_id_command)
806 {
807         return ERROR_OK;
808 }
809 #endif
810
811 static int stm32x_info(struct flash_bank *bank, char *buf, int buf_size)
812 {
813         struct target *target = bank->target;
814         uint32_t device_id;
815         int printed;
816
817         /* read stm32 device id register */
818         target_read_u32(target, 0xE0042000, &device_id);
819
820         if ((device_id & 0x7ff) == 0x410)
821         {
822                 printed = snprintf(buf, buf_size, "stm32x (Medium Density) - Rev: ");
823                 buf += printed;
824                 buf_size -= printed;
825
826                 switch (device_id >> 16)
827                 {
828                         case 0x0000:
829                                 snprintf(buf, buf_size, "A");
830                                 break;
831
832                         case 0x2000:
833                                 snprintf(buf, buf_size, "B");
834                                 break;
835
836                         case 0x2001:
837                                 snprintf(buf, buf_size, "Z");
838                                 break;
839
840                         case 0x2003:
841                                 snprintf(buf, buf_size, "Y");
842                                 break;
843
844                         default:
845                                 snprintf(buf, buf_size, "unknown");
846                                 break;
847                 }
848         }
849         else if ((device_id & 0x7ff) == 0x412)
850         {
851                 printed = snprintf(buf, buf_size, "stm32x (Low Density) - Rev: ");
852                 buf += printed;
853                 buf_size -= printed;
854
855                 switch (device_id >> 16)
856                 {
857                         case 0x1000:
858                                 snprintf(buf, buf_size, "A");
859                                 break;
860
861                         default:
862                                 snprintf(buf, buf_size, "unknown");
863                                 break;
864                 }
865         }
866         else if ((device_id & 0x7ff) == 0x414)
867         {
868                 printed = snprintf(buf, buf_size, "stm32x (High Density) - Rev: ");
869                 buf += printed;
870                 buf_size -= printed;
871
872                 switch (device_id >> 16)
873                 {
874                         case 0x1000:
875                                 snprintf(buf, buf_size, "A");
876                                 break;
877
878                         case 0x1001:
879                                 snprintf(buf, buf_size, "Z");
880                                 break;
881
882                         default:
883                                 snprintf(buf, buf_size, "unknown");
884                                 break;
885                 }
886         }
887         else if ((device_id & 0x7ff) == 0x418)
888         {
889                 printed = snprintf(buf, buf_size, "stm32x (Connectivity) - Rev: ");
890                 buf += printed;
891                 buf_size -= printed;
892
893                 switch (device_id >> 16)
894                 {
895                         case 0x1000:
896                                 snprintf(buf, buf_size, "A");
897                                 break;
898
899                         case 0x1001:
900                                 snprintf(buf, buf_size, "Z");
901                                 break;
902
903                         default:
904                                 snprintf(buf, buf_size, "unknown");
905                                 break;
906                 }
907         }
908         else if ((device_id & 0x7ff) == 0x420)
909         {
910                 printed = snprintf(buf, buf_size, "stm32x (Value) - Rev: ");
911                 buf += printed;
912                 buf_size -= printed;
913
914                 switch (device_id >> 16)
915                 {
916                         case 0x1000:
917                                 snprintf(buf, buf_size, "A");
918                                 break;
919
920                         case 0x1001:
921                                 snprintf(buf, buf_size, "Z");
922                                 break;
923
924                         default:
925                                 snprintf(buf, buf_size, "unknown");
926                                 break;
927                 }
928         }
929         else
930         {
931                 snprintf(buf, buf_size, "Cannot identify target as a stm32x\n");
932                 return ERROR_FLASH_OPERATION_FAILED;
933         }
934
935         return ERROR_OK;
936 }
937
938 COMMAND_HANDLER(stm32x_handle_lock_command)
939 {
940         struct target *target = NULL;
941         struct stm32x_flash_bank *stm32x_info = NULL;
942
943         if (CMD_ARGC < 1)
944         {
945                 command_print(CMD_CTX, "stm32x lock <bank>");
946                 return ERROR_OK;
947         }
948
949         struct flash_bank *bank;
950         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
951         if (ERROR_OK != retval)
952                 return retval;
953
954         stm32x_info = bank->driver_priv;
955
956         target = bank->target;
957
958         if (target->state != TARGET_HALTED)
959         {
960                 LOG_ERROR("Target not halted");
961                 return ERROR_TARGET_NOT_HALTED;
962         }
963
964         if (stm32x_erase_options(bank) != ERROR_OK)
965         {
966                 command_print(CMD_CTX, "stm32x failed to erase options");
967                 return ERROR_OK;
968         }
969
970         /* set readout protection */
971         stm32x_info->option_bytes.RDP = 0;
972
973         if (stm32x_write_options(bank) != ERROR_OK)
974         {
975                 command_print(CMD_CTX, "stm32x failed to lock device");
976                 return ERROR_OK;
977         }
978
979         command_print(CMD_CTX, "stm32x locked");
980
981         return ERROR_OK;
982 }
983
984 COMMAND_HANDLER(stm32x_handle_unlock_command)
985 {
986         struct target *target = NULL;
987         struct stm32x_flash_bank *stm32x_info = NULL;
988
989         if (CMD_ARGC < 1)
990         {
991                 command_print(CMD_CTX, "stm32x unlock <bank>");
992                 return ERROR_OK;
993         }
994
995         struct flash_bank *bank;
996         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
997         if (ERROR_OK != retval)
998                 return retval;
999
1000         stm32x_info = bank->driver_priv;
1001
1002         target = bank->target;
1003
1004         if (target->state != TARGET_HALTED)
1005         {
1006                 LOG_ERROR("Target not halted");
1007                 return ERROR_TARGET_NOT_HALTED;
1008         }
1009
1010         if (stm32x_erase_options(bank) != ERROR_OK)
1011         {
1012                 command_print(CMD_CTX, "stm32x failed to unlock device");
1013                 return ERROR_OK;
1014         }
1015
1016         if (stm32x_write_options(bank) != ERROR_OK)
1017         {
1018                 command_print(CMD_CTX, "stm32x failed to lock device");
1019                 return ERROR_OK;
1020         }
1021
1022         command_print(CMD_CTX, "stm32x unlocked.\n"
1023                         "INFO: a reset or power cycle is required "
1024                         "for the new settings to take effect.");
1025
1026         return ERROR_OK;
1027 }
1028
1029 COMMAND_HANDLER(stm32x_handle_options_read_command)
1030 {
1031         uint32_t optionbyte;
1032         struct target *target = NULL;
1033         struct stm32x_flash_bank *stm32x_info = NULL;
1034
1035         if (CMD_ARGC < 1)
1036         {
1037                 command_print(CMD_CTX, "stm32x options_read <bank>");
1038                 return ERROR_OK;
1039         }
1040
1041         struct flash_bank *bank;
1042         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1043         if (ERROR_OK != retval)
1044                 return retval;
1045
1046         stm32x_info = bank->driver_priv;
1047
1048         target = bank->target;
1049
1050         if (target->state != TARGET_HALTED)
1051         {
1052                 LOG_ERROR("Target not halted");
1053                 return ERROR_TARGET_NOT_HALTED;
1054         }
1055
1056         target_read_u32(target, STM32_FLASH_OBR, &optionbyte);
1057         command_print(CMD_CTX, "Option Byte: 0x%" PRIx32 "", optionbyte);
1058
1059         if (buf_get_u32((uint8_t*)&optionbyte, OPT_ERROR, 1))
1060                 command_print(CMD_CTX, "Option Byte Complement Error");
1061
1062         if (buf_get_u32((uint8_t*)&optionbyte, OPT_READOUT, 1))
1063                 command_print(CMD_CTX, "Readout Protection On");
1064         else
1065                 command_print(CMD_CTX, "Readout Protection Off");
1066
1067         if (buf_get_u32((uint8_t*)&optionbyte, OPT_RDWDGSW, 1))
1068                 command_print(CMD_CTX, "Software Watchdog");
1069         else
1070                 command_print(CMD_CTX, "Hardware Watchdog");
1071
1072         if (buf_get_u32((uint8_t*)&optionbyte, OPT_RDRSTSTOP, 1))
1073                 command_print(CMD_CTX, "Stop: No reset generated");
1074         else
1075                 command_print(CMD_CTX, "Stop: Reset generated");
1076
1077         if (buf_get_u32((uint8_t*)&optionbyte, OPT_RDRSTSTDBY, 1))
1078                 command_print(CMD_CTX, "Standby: No reset generated");
1079         else
1080                 command_print(CMD_CTX, "Standby: Reset generated");
1081
1082         return ERROR_OK;
1083 }
1084
1085 COMMAND_HANDLER(stm32x_handle_options_write_command)
1086 {
1087         struct target *target = NULL;
1088         struct stm32x_flash_bank *stm32x_info = NULL;
1089         uint16_t optionbyte = 0xF8;
1090
1091         if (CMD_ARGC < 4)
1092         {
1093                 command_print(CMD_CTX, "stm32x options_write <bank> <SWWDG | HWWDG> <RSTSTNDBY | NORSTSTNDBY> <RSTSTOP | NORSTSTOP>");
1094                 return ERROR_OK;
1095         }
1096
1097         struct flash_bank *bank;
1098         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1099         if (ERROR_OK != retval)
1100                 return retval;
1101
1102         stm32x_info = bank->driver_priv;
1103
1104         target = bank->target;
1105
1106         if (target->state != TARGET_HALTED)
1107         {
1108                 LOG_ERROR("Target not halted");
1109                 return ERROR_TARGET_NOT_HALTED;
1110         }
1111
1112         /* REVISIT: ignores some options which we will display...
1113          * and doesn't insist on the specified syntax.
1114          */
1115
1116         /* OPT_RDWDGSW */
1117         if (strcmp(CMD_ARGV[1], "SWWDG") == 0)
1118         {
1119                 optionbyte |= (1 << 0);
1120         }
1121         else    /* REVISIT must be "HWWDG" then ... */
1122         {
1123                 optionbyte &= ~(1 << 0);
1124         }
1125
1126         /* OPT_RDRSTSTDBY */
1127         if (strcmp(CMD_ARGV[2], "NORSTSTNDBY") == 0)
1128         {
1129                 optionbyte |= (1 << 1);
1130         }
1131         else    /* REVISIT must be "RSTSTNDBY" then ... */
1132         {
1133                 optionbyte &= ~(1 << 1);
1134         }
1135
1136         /* OPT_RDRSTSTOP */
1137         if (strcmp(CMD_ARGV[3], "NORSTSTOP") == 0)
1138         {
1139                 optionbyte |= (1 << 2);
1140         }
1141         else    /* REVISIT must be "RSTSTOP" then ... */
1142         {
1143                 optionbyte &= ~(1 << 2);
1144         }
1145
1146         if (stm32x_erase_options(bank) != ERROR_OK)
1147         {
1148                 command_print(CMD_CTX, "stm32x failed to erase options");
1149                 return ERROR_OK;
1150         }
1151
1152         stm32x_info->option_bytes.user_options = optionbyte;
1153
1154         if (stm32x_write_options(bank) != ERROR_OK)
1155         {
1156                 command_print(CMD_CTX, "stm32x failed to write options");
1157                 return ERROR_OK;
1158         }
1159
1160         command_print(CMD_CTX, "stm32x write options complete.\n"
1161                                 "INFO: a reset or power cycle is required "
1162                                 "for the new settings to take effect.");
1163
1164         return ERROR_OK;
1165 }
1166
1167 static int stm32x_mass_erase(struct flash_bank *bank)
1168 {
1169         struct target *target = bank->target;
1170         uint32_t status;
1171
1172         if (target->state != TARGET_HALTED)
1173         {
1174                 LOG_ERROR("Target not halted");
1175                 return ERROR_TARGET_NOT_HALTED;
1176         }
1177
1178         /* unlock option flash registers */
1179         target_write_u32(target, STM32_FLASH_KEYR, KEY1);
1180         target_write_u32(target, STM32_FLASH_KEYR, KEY2);
1181
1182         /* mass erase flash memory */
1183         target_write_u32(target, STM32_FLASH_CR, FLASH_MER);
1184         target_write_u32(target, STM32_FLASH_CR, FLASH_MER | FLASH_STRT);
1185
1186         status = stm32x_wait_status_busy(bank, 10);
1187
1188         target_write_u32(target, STM32_FLASH_CR, FLASH_LOCK);
1189
1190         if (status & FLASH_WRPRTERR)
1191         {
1192                 LOG_ERROR("stm32x device protected");
1193                 return ERROR_OK;
1194         }
1195
1196         if (status & FLASH_PGERR)
1197         {
1198                 LOG_ERROR("stm32x device programming failed");
1199                 return ERROR_OK;
1200         }
1201
1202         return ERROR_OK;
1203 }
1204
1205 COMMAND_HANDLER(stm32x_handle_mass_erase_command)
1206 {
1207         int i;
1208
1209         if (CMD_ARGC < 1)
1210         {
1211                 command_print(CMD_CTX, "stm32x mass_erase <bank>");
1212                 return ERROR_OK;
1213         }
1214
1215         struct flash_bank *bank;
1216         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1217         if (ERROR_OK != retval)
1218                 return retval;
1219
1220         if (stm32x_mass_erase(bank) == ERROR_OK)
1221         {
1222                 /* set all sectors as erased */
1223                 for (i = 0; i < bank->num_sectors; i++)
1224                 {
1225                         bank->sectors[i].is_erased = 1;
1226                 }
1227
1228                 command_print(CMD_CTX, "stm32x mass erase complete");
1229         }
1230         else
1231         {
1232                 command_print(CMD_CTX, "stm32x mass erase failed");
1233         }
1234
1235         return ERROR_OK;
1236 }
1237
1238 static const struct command_registration stm32x_exec_command_handlers[] = {
1239         {
1240                 .name = "lock",
1241                 .handler = stm32x_handle_lock_command,
1242                 .mode = COMMAND_EXEC,
1243                 .usage = "bank_id",
1244                 .help = "Lock entire flash device.",
1245         },
1246         {
1247                 .name = "unlock",
1248                 .handler = stm32x_handle_unlock_command,
1249                 .mode = COMMAND_EXEC,
1250                 .usage = "bank_id",
1251                 .help = "Unlock entire protected flash device.",
1252         },
1253         {
1254                 .name = "mass_erase",
1255                 .handler = stm32x_handle_mass_erase_command,
1256                 .mode = COMMAND_EXEC,
1257                 .usage = "bank_id",
1258                 .help = "Erase entire flash device.",
1259         },
1260         {
1261                 .name = "options_read",
1262                 .handler = stm32x_handle_options_read_command,
1263                 .mode = COMMAND_EXEC,
1264                 .usage = "bank_id",
1265                 .help = "Read and display device option byte.",
1266         },
1267         {
1268                 .name = "options_write",
1269                 .handler = stm32x_handle_options_write_command,
1270                 .mode = COMMAND_EXEC,
1271                 .usage = "bank_id ('SWWDG'|'HWWDG') "
1272                         "('RSTSTNDBY'|'NORSTSTNDBY') "
1273                         "('RSTSTOP'|'NORSTSTOP')",
1274                 .help = "Replace bits in device option byte.",
1275         },
1276         COMMAND_REGISTRATION_DONE
1277 };
1278
1279 static const struct command_registration stm32x_command_handlers[] = {
1280         {
1281                 .name = "stm32x",
1282                 .mode = COMMAND_ANY,
1283                 .help = "stm32x flash command group",
1284                 .chain = stm32x_exec_command_handlers,
1285         },
1286         COMMAND_REGISTRATION_DONE
1287 };
1288
1289 struct flash_driver stm32x_flash = {
1290         .name = "stm32x",
1291         .commands = stm32x_command_handlers,
1292         .flash_bank_command = stm32x_flash_bank_command,
1293         .erase = stm32x_erase,
1294         .protect = stm32x_protect,
1295         .write = stm32x_write,
1296         .probe = stm32x_probe,
1297         .auto_probe = stm32x_auto_probe,
1298         .erase_check = default_flash_mem_blank_check,
1299         .protect_check = stm32x_protect_check,
1300         .info = stm32x_info,
1301 };