STM32L: Validate flash writes
[fw/openocd] / src / flash / nor / stm32lx.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 Clement Burin des Roziers                       *
9  *   clement.burin-des-roziers@hikob.com                                   *
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU General Public License as published by  *
13  *   the Free Software Foundation; either version 2 of the License, or     *
14  *   (at your option) any later version.                                   *
15  *                                                                         *
16  *   This program is distributed in the hope that it will be useful,       *
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
19  *   GNU General Public License for more details.                          *
20  *                                                                         *
21  *   You should have received a copy of the GNU General Public License     *
22  *   along with this program; if not, write to the                         *
23  *   Free Software Foundation, Inc.,                                       *
24  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
25  ***************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include "imp.h"
32 #include <helper/binarybuffer.h>
33 #include <target/algorithm.h>
34 #include <target/armv7m.h>
35
36 /* stm32lx flash register locations */
37
38 #define FLASH_BASE              0x40023C00
39 #define FLASH_ACR               0x40023C00
40 #define FLASH_PECR              0x40023C04
41 #define FLASH_PDKEYR    0x40023C08
42 #define FLASH_PEKEYR    0x40023C0C
43 #define FLASH_PRGKEYR   0x40023C10
44 #define FLASH_OPTKEYR   0x40023C14
45 #define FLASH_SR                0x40023C18
46 #define FLASH_OBR               0x40023C1C
47 #define FLASH_WRPR              0x40023C20
48
49 /* FLASH_ACR bites */
50 #define FLASH_ACR__LATENCY              (1<<0)
51 #define FLASH_ACR__PRFTEN               (1<<1)
52 #define FLASH_ACR__ACC64                (1<<2)
53 #define FLASH_ACR__SLEEP_PD             (1<<3)
54 #define FLASH_ACR__RUN_PD               (1<<4)
55
56 /* FLASH_PECR bits */
57 #define FLASH_PECR__PELOCK              (1<<0)
58 #define FLASH_PECR__PRGLOCK             (1<<1)
59 #define FLASH_PECR__OPTLOCK             (1<<2)
60 #define FLASH_PECR__PROG                (1<<3)
61 #define FLASH_PECR__DATA                (1<<4)
62 #define FLASH_PECR__FTDW                (1<<8)
63 #define FLASH_PECR__ERASE               (1<<9)
64 #define FLASH_PECR__FPRG                (1<<10)
65 #define FLASH_PECR__EOPIE               (1<<16)
66 #define FLASH_PECR__ERRIE               (1<<17)
67 #define FLASH_PECR__OBL_LAUNCH  (1<<18)
68
69 /* FLASH_SR bits */
70 #define FLASH_SR__BSY           (1<<0)
71 #define FLASH_SR__EOP           (1<<1)
72 #define FLASH_SR__ENDHV         (1<<2)
73 #define FLASH_SR__READY         (1<<3)
74 #define FLASH_SR__WRPERR        (1<<8)
75 #define FLASH_SR__PGAERR        (1<<9)
76 #define FLASH_SR__SIZERR        (1<<10)
77 #define FLASH_SR__OPTVERR       (1<<11)
78
79 /* Unlock keys */
80 #define PEKEY1                  0x89ABCDEF
81 #define PEKEY2                  0x02030405
82 #define PRGKEY1                 0x8C9DAEBF
83 #define PRGKEY2                 0x13141516
84 #define OPTKEY1                 0xFBEAD9C8
85 #define OPTKEY2                 0x24252627
86
87 /* other registers */
88 #define DBGMCU_IDCODE   0xE0042000
89 #define F_SIZE                  0x1FF8004C
90
91 /* Constants */
92 #define FLASH_PAGE_SIZE 256
93 #define FLASH_SECTOR_SIZE 4096
94 #define FLASH_PAGES_PER_SECTOR 16
95 #define FLASH_BANK0_ADDRESS 0x08000000
96
97 /* stm32lx option byte register location */
98 #define OB_RDP                  0x1FF80000
99 #define OB_USER                 0x1FF80004
100 #define OB_WRP0_1               0x1FF80008
101 #define OB_WRP2_3               0x1FF8000C
102
103 /* OB_RDP values */
104 #define OB_RDP__LEVEL0  0xFF5500AA
105 #define OB_RDP__LEVEL1  0xFFFF0000
106
107 /* stm32lx RCC register locations */
108 #define RCC_CR          0x40023800
109 #define RCC_ICSCR       0x40023804
110 #define RCC_CFGR        0x40023808
111
112 /* RCC_ICSCR bits */
113 #define RCC_ICSCR__MSIRANGE_MASK        (7<<13)
114
115 static int stm32lx_unlock_program_memory(struct flash_bank *bank);
116 static int stm32lx_lock_program_memory(struct flash_bank *bank);
117 static int stm32lx_enable_write_half_page(struct flash_bank *bank);
118 static int stm32lx_erase_sector(struct flash_bank *bank, int sector);
119 static int stm32lx_wait_until_bsy_clear(struct flash_bank *bank);
120
121 struct stm32lx_flash_bank {
122         int probed;
123 };
124
125 /* flash bank stm32lx <base> <size> 0 0 <target#>
126  */
127 FLASH_BANK_COMMAND_HANDLER(stm32lx_flash_bank_command)
128 {
129         struct stm32lx_flash_bank *stm32lx_info;
130         if (CMD_ARGC < 6)
131                 return ERROR_COMMAND_SYNTAX_ERROR;
132
133         /* Create the bank structure */
134         stm32lx_info = malloc(sizeof(struct stm32lx_flash_bank));
135
136         /* Check allocation */
137         if (stm32lx_info == NULL) {
138                 LOG_ERROR("failed to allocate bank structure");
139                 return ERROR_FAIL;
140         }
141
142         bank->driver_priv = stm32lx_info;
143
144         stm32lx_info->probed = 0;
145
146         return ERROR_OK;
147 }
148
149 static int stm32lx_protect_check(struct flash_bank *bank)
150 {
151         int retval;
152         struct target *target = bank->target;
153
154         uint32_t wrpr;
155
156         if (target->state != TARGET_HALTED) {
157                 LOG_ERROR("Target not halted");
158                 return ERROR_TARGET_NOT_HALTED;
159         }
160
161         /*
162          * Read the WRPR word, and check each bit (corresponding to each
163          * flash sector
164          */
165         retval = target_read_u32(target, FLASH_WRPR, &wrpr);
166         if (retval != ERROR_OK)
167                 return retval;
168
169         for (int i = 0; i < 32; i++) {
170                 if (wrpr & (1 << i))
171                         bank->sectors[i].is_protected = 1;
172                 else
173                         bank->sectors[i].is_protected = 0;
174         }
175         return ERROR_OK;
176 }
177
178 static int stm32lx_erase(struct flash_bank *bank, int first, int last)
179 {
180         int retval;
181
182         /*
183          * It could be possible to do a mass erase if all sectors must be
184          * erased, but it is not implemented yet.
185          */
186
187         if (bank->target->state != TARGET_HALTED) {
188                 LOG_ERROR("Target not halted");
189                 return ERROR_TARGET_NOT_HALTED;
190         }
191
192         /*
193          * Loop over the selected sectors and erase them
194          */
195         for (int i = first; i <= last; i++) {
196                 retval = stm32lx_erase_sector(bank, i);
197                 if (retval != ERROR_OK)
198                         return retval;
199                 bank->sectors[i].is_erased = 1;
200         }
201         return ERROR_OK;
202 }
203
204 static int stm32lx_protect(struct flash_bank *bank, int set, int first,
205                 int last)
206 {
207         LOG_WARNING("protection of the STM32L flash is not implemented");
208         return ERROR_OK;
209 }
210
211 static int stm32lx_write_half_pages(struct flash_bank *bank, uint8_t *buffer,
212                 uint32_t offset, uint32_t count)
213 {
214         struct target *target = bank->target;
215         uint32_t buffer_size = 4096 * 4;
216         struct working_area *write_algorithm;
217         struct working_area *source;
218         uint32_t address = bank->base + offset;
219
220         struct reg_param reg_params[5];
221         struct armv7m_algorithm armv7m_info;
222
223         int retval = ERROR_OK;
224         uint32_t reg32;
225
226         /* see contib/loaders/flash/stm32lx.s for src */
227
228         static const uint16_t stm32lx_flash_write_code_16[] = {
229         /*      00000000 <write_word-0x4>: */
230                         0x2300, /* 0:   2300            movs    r3, #0 */
231                         0xe004, /* 2:   e004            b.n     e <test_done> */
232
233                         /*      00000004 <write_word>: */
234                         0xf851, 0xcb04, /* 4:   f851 cb04       ldr.w   ip, [r1], #4 */
235                         0xf840, 0xcb04, /* 8:   f840 cb04       str.w   ip, [r0], #4 */
236                         0x3301, /* c:   3301            adds    r3, #1 */
237
238                         /*      0000000e <test_done>: */
239                         0x4293, /* e:   4293            cmp     r3, r2 */
240                         0xd3f8, /* 10:  d3f8            bcc.n   4 <write_word> */
241                         0xbe00, /* 12:  be00            bkpt    0x0000 */
242
243                         };
244
245         /* Flip endian */
246         uint8_t stm32lx_flash_write_code[sizeof(stm32lx_flash_write_code_16)];
247         for (unsigned int i = 0; i < sizeof(stm32lx_flash_write_code_16) / 2; i++) {
248                 stm32lx_flash_write_code[i * 2 + 0] = stm32lx_flash_write_code_16[i]
249                                 & 0xff;
250                 stm32lx_flash_write_code[i * 2 + 1] = (stm32lx_flash_write_code_16[i]
251                                 >> 8) & 0xff;
252         }
253         /* Check if there is an even number of half pages (128bytes) */
254         if (count % 128) {
255                 LOG_ERROR("there should be an even number "
256                                 "of half pages = 128 bytes (count = %" PRIi32 " bytes)", count);
257                 return ERROR_FAIL;
258         }
259
260         /* Allocate working area */
261         reg32 = sizeof(stm32lx_flash_write_code);
262         /* Add bytes to make 4byte aligned */
263         reg32 += (4 - (reg32 % 4)) % 4;
264         retval = target_alloc_working_area(target, reg32,
265                         &write_algorithm);
266         if (retval != ERROR_OK)
267                 return retval;
268
269         /* Write the flashing code */
270         retval = target_write_buffer(target,
271                         write_algorithm->address,
272                         sizeof(stm32lx_flash_write_code),
273                         (uint8_t *)stm32lx_flash_write_code);
274         if (retval != ERROR_OK) {
275                 target_free_working_area(target, write_algorithm);
276                 return retval;
277         }
278
279         /* Allocate half pages memory */
280         while (target_alloc_working_area_try(target, buffer_size, &source)
281                         != ERROR_OK) {
282                 if (buffer_size > 1024)
283                         buffer_size -= 1024;
284                 else
285                         buffer_size /= 2;
286
287                 if (buffer_size <= 256) {
288                         /* we already allocated the writing code, but failed to get a
289                          * buffer, free the algorithm */
290                         target_free_working_area(target, write_algorithm);
291
292                         LOG_WARNING("no large enough working area available, can't do block memory writes");
293                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
294                 }
295         }
296         LOG_DEBUG("allocated working area for data (%" PRIx32 " bytes)", buffer_size);
297
298         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
299         armv7m_info.core_mode = ARMV7M_MODE_ANY;
300         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
301         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
302         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
303         init_reg_param(&reg_params[3], "r3", 32, PARAM_IN_OUT);
304         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);
305
306         /* Enable half-page write */
307         retval = stm32lx_enable_write_half_page(bank);
308         if (retval != ERROR_OK) {
309                 target_free_working_area(target, source);
310                 target_free_working_area(target, write_algorithm);
311
312                 destroy_reg_param(&reg_params[0]);
313                 destroy_reg_param(&reg_params[1]);
314                 destroy_reg_param(&reg_params[2]);
315                 destroy_reg_param(&reg_params[3]);
316                 return retval;
317         }
318
319         /* Loop while there are bytes to write */
320         while (count > 0) {
321                 uint32_t this_count;
322                 this_count = (count > buffer_size) ? buffer_size : count;
323
324                 /* Write the next half pages */
325                 retval = target_write_buffer(target, source->address, this_count,
326                                 buffer);
327                 if (retval != ERROR_OK)
328                         break;
329
330                 /* 4: Store useful information in the registers */
331                 /* the destination address of the copy (R0) */
332                 buf_set_u32(reg_params[0].value, 0, 32, address);
333                 /* The source address of the copy (R1) */
334                 buf_set_u32(reg_params[1].value, 0, 32, source->address);
335                 /* The length of the copy (R2) */
336                 buf_set_u32(reg_params[2].value, 0, 32, this_count / 4);
337
338                 /* 5: Execute the bunch of code */
339                 retval = target_run_algorithm(target, 0, NULL, sizeof(reg_params)
340                                 / sizeof(*reg_params), reg_params,
341                                 write_algorithm->address, 0, 20000, &armv7m_info);
342                 if (retval != ERROR_OK)
343                         break;
344
345                 /* 6: Wait while busy */
346                 retval = stm32lx_wait_until_bsy_clear(bank);
347                 if (retval != ERROR_OK)
348                         break;
349
350                 buffer += this_count;
351                 address += this_count;
352                 count -= this_count;
353         }
354
355         if (retval == ERROR_OK)
356                 retval = stm32lx_lock_program_memory(bank);
357
358         target_free_working_area(target, source);
359         target_free_working_area(target, write_algorithm);
360
361         destroy_reg_param(&reg_params[0]);
362         destroy_reg_param(&reg_params[1]);
363         destroy_reg_param(&reg_params[2]);
364         destroy_reg_param(&reg_params[3]);
365
366         return retval;
367 }
368 static int stm32lx_write(struct flash_bank *bank, uint8_t *buffer,
369                 uint32_t offset, uint32_t count)
370 {
371         struct target *target = bank->target;
372
373         uint32_t halfpages_number;
374         uint32_t words_remaining;
375         uint32_t bytes_remaining;
376         uint32_t address = bank->base + offset;
377         uint32_t bytes_written = 0;
378         int retval;
379
380         uint8_t  *start = buffer;
381         uint32_t start_address = address;
382         uint32_t start_count = count;
383         uint8_t  *validate;
384         uint32_t check;
385
386         if (bank->target->state != TARGET_HALTED) {
387                 LOG_ERROR("Target not halted");
388                 return ERROR_TARGET_NOT_HALTED;
389         }
390
391         if (offset & 0x1) {
392                 LOG_ERROR("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
393                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
394         }
395
396         /* Check if there are some full half pages */
397         if (((offset % 128) == 0) && (count >= 128)) {
398                 halfpages_number = count / 128;
399                 words_remaining = (count - 128 * halfpages_number) / 4;
400                 bytes_remaining = (count & 0x3);
401         } else {
402                 halfpages_number = 0;
403                 words_remaining = (count / 4);
404                 bytes_remaining = (count & 0x3);
405         }
406
407         if (halfpages_number) {
408                 retval = stm32lx_write_half_pages(bank, buffer, offset, 128
409                                 * halfpages_number);
410                 if (retval != ERROR_OK)
411                         return ERROR_FAIL;
412         }
413
414         bytes_written = 128 * halfpages_number;
415         address += bytes_written;
416
417         retval = stm32lx_unlock_program_memory(bank);
418         if (retval != ERROR_OK)
419                 return retval;
420
421         while (words_remaining > 0) {
422                 uint32_t value;
423                 uint8_t *p = buffer + bytes_written;
424
425                 /* Prepare the word, Little endian conversion */
426                 value = p[0] + (p[1] << 8) + (p[2] << 16) + (p[3] << 24);
427
428                 retval = target_write_u32(target, address, value);
429                 if (retval != ERROR_OK)
430                         return retval;
431
432                 bytes_written += 4;
433                 words_remaining--;
434                 address += 4;
435
436                 retval = stm32lx_wait_until_bsy_clear(bank);
437                 if (retval != ERROR_OK)
438                         return retval;
439         }
440
441         if (bytes_remaining) {
442                 uint8_t last_word[4] = {0xff, 0xff, 0xff, 0xff};
443
444                 /* copy the last remaining bytes into the write buffer */
445                 memcpy(last_word, buffer+bytes_written, bytes_remaining);
446
447                 retval = target_write_buffer(target, address, 4, last_word);
448                 if (retval != ERROR_OK)
449                         return retval;
450
451                 retval = stm32lx_wait_until_bsy_clear(bank);
452                 if (retval != ERROR_OK)
453                         return retval;
454         }
455
456         retval = stm32lx_lock_program_memory(bank);
457         if (retval != ERROR_OK)
458                 return retval;
459
460         validate = malloc (start_count);
461
462         retval = target_read_buffer(target, start_address, start_count, validate);
463         if (retval != ERROR_OK) {
464                 free (validate);
465                 return retval;
466         }
467
468         for (check = 0; check < start_count; check++) {
469                 if (validate[check] != start[check]) {
470                         LOG_ERROR ("flash corrupted at 0x%08x (%02x != %02x)\n",
471                                    start_address + check, start[check], validate[check]);
472                         retval = ERROR_FAIL;
473                         break;
474                 }
475         }
476
477         free (validate);
478
479         return retval;
480 }
481
482 static int stm32lx_probe(struct flash_bank *bank)
483 {
484         struct target *target = bank->target;
485         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
486         int i;
487         uint16_t flash_size_in_kb;
488         uint16_t max_flash_size_in_kb;
489         uint32_t device_id;
490
491         stm32lx_info->probed = 0;
492
493         /* read stm32 device id register */
494         int retval = target_read_u32(target, DBGMCU_IDCODE, &device_id);
495         if (retval != ERROR_OK)
496                 return retval;
497
498         LOG_DEBUG("device id = 0x%08" PRIx32 "", device_id);
499
500         /* set max flash size depending on family */
501         switch (device_id & 0xfff) {
502         case 0x416:
503                 max_flash_size_in_kb = 128;
504                 break;
505         case 0x436:
506                 max_flash_size_in_kb = 384;
507                 break;
508         default:
509                 LOG_WARNING("Cannot identify target as a STM32L family.");
510                 return ERROR_FAIL;
511         }
512
513         /* get flash size from target. */
514         retval = target_read_u16(target, F_SIZE, &flash_size_in_kb);
515
516         /* failed reading flash size or flash size invalid (early silicon),
517          * default to max target family */
518         if (retval != ERROR_OK || flash_size_in_kb == 0xffff || flash_size_in_kb == 0) {
519                 LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming %dk flash",
520                         max_flash_size_in_kb);
521                 flash_size_in_kb = max_flash_size_in_kb;
522         }
523
524         /* STM32L - we have 32 sectors, 16 pages per sector -> 512 pages
525          * 16 pages for a protection area */
526
527         /* calculate numbers of sectors (4kB per sector) */
528         int num_sectors = (flash_size_in_kb * 1024) / FLASH_SECTOR_SIZE;
529         LOG_INFO("flash size = %dkbytes", flash_size_in_kb);
530
531         if (bank->sectors) {
532                 free(bank->sectors);
533                 bank->sectors = NULL;
534         }
535
536         bank->base = FLASH_BANK0_ADDRESS;
537         bank->size = flash_size_in_kb * 1024;
538         bank->num_sectors = num_sectors;
539         bank->sectors = malloc(sizeof(struct flash_sector) * num_sectors);
540         if (bank->sectors == NULL) {
541                 LOG_ERROR("failed to allocate bank sectors");
542                 return ERROR_FAIL;
543         }
544
545         for (i = 0; i < num_sectors; i++) {
546                 bank->sectors[i].offset = i * FLASH_SECTOR_SIZE;
547                 bank->sectors[i].size = FLASH_SECTOR_SIZE;
548                 bank->sectors[i].is_erased = -1;
549                 bank->sectors[i].is_protected = 1;
550         }
551
552         stm32lx_info->probed = 1;
553
554         return ERROR_OK;
555 }
556
557 static int stm32lx_auto_probe(struct flash_bank *bank)
558 {
559         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
560
561         if (stm32lx_info->probed)
562                 return ERROR_OK;
563
564         return stm32lx_probe(bank);
565 }
566
567 static int stm32lx_erase_check(struct flash_bank *bank)
568 {
569         struct target *target = bank->target;
570         const int buffer_size = 4096;
571         int i;
572         uint32_t nBytes;
573         int retval = ERROR_OK;
574
575         if (bank->target->state != TARGET_HALTED) {
576                 LOG_ERROR("Target not halted");
577                 return ERROR_TARGET_NOT_HALTED;
578         }
579
580         uint8_t *buffer = malloc(buffer_size);
581         if (buffer == NULL) {
582                 LOG_ERROR("failed to allocate read buffer");
583                 return ERROR_FAIL;
584         }
585
586         for (i = 0; i < bank->num_sectors; i++) {
587                 uint32_t j;
588                 bank->sectors[i].is_erased = 1;
589
590                 /* Loop chunk by chunk over the sector */
591                 for (j = 0; j < bank->sectors[i].size; j += buffer_size) {
592                         uint32_t chunk;
593                         chunk = buffer_size;
594                         if (chunk > (j - bank->sectors[i].size))
595                                 chunk = (j - bank->sectors[i].size);
596
597                         retval = target_read_memory(target, bank->base
598                                         + bank->sectors[i].offset + j, 4, chunk / 4, buffer);
599                         if (retval != ERROR_OK)
600                                 break;
601
602                         for (nBytes = 0; nBytes < chunk; nBytes++) {
603                                 if (buffer[nBytes] != 0x00) {
604                                         bank->sectors[i].is_erased = 0;
605                                         break;
606                                 }
607                         }
608                 }
609                 if (retval != ERROR_OK)
610                         break;
611         }
612         free(buffer);
613
614         return retval;
615 }
616
617 static int stm32lx_get_info(struct flash_bank *bank, char *buf, int buf_size)
618 {
619         /* This method must return a string displaying information about the bank */
620
621         struct target *target = bank->target;
622         uint32_t device_id;
623         int printed;
624
625         /* read stm32 device id register */
626         int retval = target_read_u32(target, DBGMCU_IDCODE, &device_id);
627         if (retval != ERROR_OK)
628                 return retval;
629
630         if ((device_id & 0xfff) == 0x416) {
631                 printed = snprintf(buf, buf_size, "stm32lx - Rev: ");
632                 buf += printed;
633                 buf_size -= printed;
634
635                 switch (device_id >> 16) {
636                         case 0x1000:
637                                 snprintf(buf, buf_size, "A");
638                                 break;
639
640                         case 0x1008:
641                                 snprintf(buf, buf_size, "Y");
642                                 break;
643
644                         case 0x1018:
645                                 snprintf(buf, buf_size, "X");
646                                 break;
647
648                         case 0x1038:
649                                 snprintf(buf, buf_size, "W");
650                                 break;
651
652                         case 0x1078:
653                                 snprintf(buf, buf_size, "V");
654                                 break;
655
656                         default:
657                                 snprintf(buf, buf_size, "unknown");
658                                 break;
659                 }
660         } else if ((device_id & 0xfff) == 0x436) {
661                 printed = snprintf(buf, buf_size, "stm32lx (HD) - Rev: ");
662                 buf += printed;
663                 buf_size -= printed;
664
665                 switch (device_id >> 16) {
666                         case 0x1000:
667                                 snprintf(buf, buf_size, "A");
668                                 break;
669
670                         case 0x1008:
671                                 snprintf(buf, buf_size, "Z");
672                                 break;
673
674                         default:
675                                 snprintf(buf, buf_size, "unknown");
676                                 break;
677                 }
678         } else {
679                 snprintf(buf, buf_size, "Cannot identify target as a stm32lx");
680                 return ERROR_FAIL;
681         }
682
683         return ERROR_OK;
684 }
685
686 static const struct command_registration stm32lx_exec_command_handlers[] = {
687         COMMAND_REGISTRATION_DONE
688 };
689
690 static const struct command_registration stm32lx_command_handlers[] = {
691         {
692                 .name = "stm32lx",
693                 .mode = COMMAND_ANY,
694                 .help = "stm32lx flash command group",
695                 .usage = "",
696                 .chain = stm32lx_exec_command_handlers,
697         },
698         COMMAND_REGISTRATION_DONE
699 };
700
701 struct flash_driver stm32lx_flash = {
702                 .name = "stm32lx",
703                 .commands = stm32lx_command_handlers,
704                 .flash_bank_command = stm32lx_flash_bank_command,
705                 .erase = stm32lx_erase,
706                 .protect = stm32lx_protect,
707                 .write = stm32lx_write,
708                 .read = default_flash_read,
709                 .probe = stm32lx_probe,
710                 .auto_probe = stm32lx_auto_probe,
711                 .erase_check = stm32lx_erase_check,
712                 .protect_check = stm32lx_protect_check,
713                 .info = stm32lx_get_info,
714 };
715
716 /* Static methods implementation */
717 static int stm32lx_unlock_program_memory(struct flash_bank *bank)
718 {
719         struct target *target = bank->target;
720         int retval;
721         uint32_t reg32;
722
723         /*
724          * Unlocking the program memory is done by unlocking the PECR,
725          * then by writing the 2 PRGKEY to the PRGKEYR register
726          */
727
728         /* To unlock the PECR write the 2 PEKEY to the PEKEYR register */
729         retval = target_write_u32(target, FLASH_PEKEYR, PEKEY1);
730         if (retval != ERROR_OK)
731                 return retval;
732
733         retval = target_write_u32(target, FLASH_PEKEYR, PEKEY2);
734         if (retval != ERROR_OK)
735                 return retval;
736
737         /* Make sure it worked */
738         retval = target_read_u32(target, FLASH_PECR, &reg32);
739         if (retval != ERROR_OK)
740                 return retval;
741
742         if (reg32 & FLASH_PECR__PELOCK) {
743                 LOG_ERROR("PELOCK is not cleared :(");
744                 return ERROR_FLASH_OPERATION_FAILED;
745         }
746
747         retval = target_write_u32(target, FLASH_PRGKEYR, PRGKEY1);
748         if (retval != ERROR_OK)
749                 return retval;
750         retval = target_write_u32(target, FLASH_PRGKEYR, PRGKEY2);
751         if (retval != ERROR_OK)
752                 return retval;
753
754         /* Make sure it worked */
755         retval = target_read_u32(target, FLASH_PECR, &reg32);
756         if (retval != ERROR_OK)
757                 return retval;
758
759         if (reg32 & FLASH_PECR__PRGLOCK) {
760                 LOG_ERROR("PRGLOCK is not cleared :(");
761                 return ERROR_FLASH_OPERATION_FAILED;
762         }
763         return ERROR_OK;
764 }
765
766 static int stm32lx_enable_write_half_page(struct flash_bank *bank)
767 {
768         struct target *target = bank->target;
769         int retval;
770         uint32_t reg32;
771
772         /**
773          * Unlock the program memory, then set the FPRG bit in the PECR register.
774          */
775         retval = stm32lx_unlock_program_memory(bank);
776         if (retval != ERROR_OK)
777                 return retval;
778
779         retval = target_read_u32(target, FLASH_PECR, &reg32);
780         if (retval != ERROR_OK)
781                 return retval;
782
783         reg32 |= FLASH_PECR__FPRG;
784         retval = target_write_u32(target, FLASH_PECR, reg32);
785         if (retval != ERROR_OK)
786                 return retval;
787
788         retval = target_read_u32(target, FLASH_PECR, &reg32);
789         if (retval != ERROR_OK)
790                 return retval;
791
792         reg32 |= FLASH_PECR__PROG;
793         retval = target_write_u32(target, FLASH_PECR, reg32);
794
795         return retval;
796 }
797
798 static int stm32lx_lock_program_memory(struct flash_bank *bank)
799 {
800         struct target *target = bank->target;
801         int retval;
802         uint32_t reg32;
803
804         /* To lock the program memory, simply set the lock bit and lock PECR */
805
806         retval = target_read_u32(target, FLASH_PECR, &reg32);
807         if (retval != ERROR_OK)
808                 return retval;
809
810         reg32 |= FLASH_PECR__PRGLOCK;
811         retval = target_write_u32(target, FLASH_PECR, reg32);
812         if (retval != ERROR_OK)
813                 return retval;
814
815         retval = target_read_u32(target, FLASH_PECR, &reg32);
816         if (retval != ERROR_OK)
817                 return retval;
818
819         reg32 |= FLASH_PECR__PELOCK;
820         retval = target_write_u32(target, FLASH_PECR, reg32);
821         if (retval != ERROR_OK)
822                 return retval;
823
824         return ERROR_OK;
825 }
826
827 static int stm32lx_erase_sector(struct flash_bank *bank, int sector)
828 {
829         struct target *target = bank->target;
830         int retval;
831         uint32_t reg32;
832
833         /*
834          * To erase a sector (i.e. FLASH_PAGES_PER_SECTOR pages),
835          * first unlock the memory, loop over the pages of this sector
836          * and write 0x0 to its first word.
837          */
838
839         retval = stm32lx_unlock_program_memory(bank);
840         if (retval != ERROR_OK)
841                 return retval;
842
843         for (int page = 0; page < FLASH_PAGES_PER_SECTOR; page++) {
844                 reg32 = FLASH_PECR__PROG | FLASH_PECR__ERASE;
845                 retval = target_write_u32(target, FLASH_PECR, reg32);
846                 if (retval != ERROR_OK)
847                         return retval;
848
849                 retval = stm32lx_wait_until_bsy_clear(bank);
850                 if (retval != ERROR_OK)
851                         return retval;
852
853                 uint32_t addr = bank->base + bank->sectors[sector].offset + (page
854                                 * FLASH_PAGE_SIZE);
855                 retval = target_write_u32(target, addr, 0x0);
856                 if (retval != ERROR_OK)
857                         return retval;
858
859                 retval = stm32lx_wait_until_bsy_clear(bank);
860                 if (retval != ERROR_OK)
861                         return retval;
862         }
863
864         retval = stm32lx_lock_program_memory(bank);
865         if (retval != ERROR_OK)
866                 return retval;
867
868         return ERROR_OK;
869 }
870
871 static int stm32lx_wait_until_bsy_clear(struct flash_bank *bank)
872 {
873         struct target *target = bank->target;
874         uint32_t status;
875         int retval = ERROR_OK;
876         int timeout = 100;
877
878         /* wait for busy to clear */
879         for (;;) {
880                 retval = target_read_u32(target, FLASH_SR, &status);
881                 if (retval != ERROR_OK)
882                         return retval;
883
884                 if ((status & FLASH_SR__BSY) == 0)
885                         break;
886                 if (timeout-- <= 0) {
887                         LOG_ERROR("timed out waiting for flash");
888                         return ERROR_FAIL;
889                 }
890                 alive_sleep(1);
891         }
892
893         if (status & FLASH_SR__WRPERR) {
894                 LOG_ERROR("access denied / write protected");
895                 retval = ERROR_FAIL;
896         }
897
898         if (status & FLASH_SR__PGAERR) {
899                 LOG_ERROR("invalid program address");
900                 retval = ERROR_FAIL;
901         }
902
903         return retval;
904 }