]> git.sur5r.net Git - openocd/blob - src/flash/nor/stm32lx.c
flash/nor/stm32l: unify waiting for busy flag functions
[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  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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 #include <target/cortex_m.h>
36
37 /* stm32lx flash register locations */
38
39 #define FLASH_ACR               0x00
40 #define FLASH_PECR              0x04
41 #define FLASH_PDKEYR    0x08
42 #define FLASH_PEKEYR    0x0C
43 #define FLASH_PRGKEYR   0x10
44 #define FLASH_OPTKEYR   0x14
45 #define FLASH_SR                0x18
46 #define FLASH_OBR               0x1C
47 #define FLASH_WRPR              0x20
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 DBGMCU_IDCODE_L0        0x40015800
90
91 /* Constants */
92 #define FLASH_SECTOR_SIZE 4096
93 #define FLASH_BANK0_ADDRESS 0x08000000
94
95 /* option bytes */
96 #define OPTION_BYTES_ADDRESS 0x1FF80000
97
98 #define OPTION_BYTE_0_PR1 0xFFFF0000
99 #define OPTION_BYTE_0_PR0 0xFF5500AA
100
101 static int stm32lx_unlock_program_memory(struct flash_bank *bank);
102 static int stm32lx_lock_program_memory(struct flash_bank *bank);
103 static int stm32lx_enable_write_half_page(struct flash_bank *bank);
104 static int stm32lx_erase_sector(struct flash_bank *bank, int sector);
105 static int stm32lx_wait_until_bsy_clear(struct flash_bank *bank);
106 static int stm32lx_mass_erase(struct flash_bank *bank);
107 static int stm32lx_wait_until_bsy_clear_timeout(struct flash_bank *bank, int timeout);
108
109 struct stm32lx_rev {
110         uint16_t rev;
111         const char *str;
112 };
113
114 struct stm32lx_part_info {
115         uint16_t id;
116         const char *device_str;
117         const struct stm32lx_rev *revs;
118         size_t num_revs;
119         unsigned int page_size;
120         unsigned int pages_per_sector;
121         uint16_t max_flash_size_kb;
122         uint16_t first_bank_size_kb; /* used when has_dual_banks is true */
123         bool has_dual_banks;
124
125         uint32_t flash_base;    /* Flash controller registers location */
126         uint32_t fsize_base;    /* Location of FSIZE register */
127 };
128
129 struct stm32lx_flash_bank {
130         int probed;
131         uint32_t idcode;
132         uint32_t user_bank_size;
133         uint32_t flash_base;
134
135         const struct stm32lx_part_info *part_info;
136 };
137
138 static const struct stm32lx_rev stm32_416_revs[] = {
139         { 0x1000, "A" }, { 0x1008, "Y" }, { 0x1018, "X" }, { 0x1038, "W" },
140         { 0x1078, "V" },
141 };
142 static const struct stm32lx_rev stm32_417_revs[] = {
143         { 0x1000, "A" }, { 0x1008, "Z" },
144 };
145 static const struct stm32lx_rev stm32_427_revs[] = {
146         { 0x1018, "A" },
147 };
148 static const struct stm32lx_rev stm32_436_revs[] = {
149         { 0x1000, "A" }, { 0x1008, "Z" }, { 0x1018, "Y" },
150 };
151
152 static const struct stm32lx_part_info stm32lx_parts[] = {
153         {
154                 .id                                     = 0x416,
155                 .revs                           = stm32_416_revs,
156                 .num_revs                       = ARRAY_SIZE(stm32_416_revs),
157                 .device_str                     = "STM32L1xx (Low/Medium Density)",
158                 .page_size                      = 256,
159                 .pages_per_sector       = 16,
160                 .max_flash_size_kb      = 128,
161                 .has_dual_banks         = false,
162                 .flash_base                     = 0x40023C00,
163                 .fsize_base                     = 0x1FF8004C,
164         },
165         {
166                 .id                                     = 0x417,
167                 .revs                           = stm32_417_revs,
168                 .num_revs                       = ARRAY_SIZE(stm32_417_revs),
169                 .device_str                     = "STM32L0xx",
170                 .page_size                      = 128,
171                 .pages_per_sector       = 32,
172                 .max_flash_size_kb      = 64,
173                 .has_dual_banks         = false,
174                 .flash_base                     = 0x40022000,
175                 .fsize_base                     = 0x1FF8007C,
176         },
177         {
178                 .id                                     = 0x427,
179                 .revs                           = stm32_427_revs,
180                 .num_revs                       = ARRAY_SIZE(stm32_427_revs),
181                 .device_str                     = "STM32L1xx (Medium+ Density)",
182                 .page_size                      = 256,
183                 .pages_per_sector       = 16,
184                 .max_flash_size_kb      = 256,
185                 .first_bank_size_kb     = 192,
186                 .has_dual_banks         = true,
187                 .flash_base                     = 0x40023C00,
188                 .fsize_base                     = 0x1FF800CC,
189         },
190         {
191                 .id                                     = 0x436,
192                 .revs                           = stm32_436_revs,
193                 .num_revs                       = ARRAY_SIZE(stm32_436_revs),
194                 .device_str                     = "STM32L1xx (Medium+/High Density)",
195                 .page_size                      = 256,
196                 .pages_per_sector       = 16,
197                 .max_flash_size_kb      = 384,
198                 .first_bank_size_kb     = 192,
199                 .has_dual_banks         = true,
200                 .flash_base                     = 0x40023C00,
201                 .fsize_base                     = 0x1FF800CC,
202         },
203         {
204                 .id                                     = 0x437,
205                 .device_str                     = "STM32L1xx (Medium+/High Density)",
206                 .page_size                      = 256,
207                 .pages_per_sector       = 16,
208                 .max_flash_size_kb      = 512,
209                 .first_bank_size_kb     = 256,
210                 .has_dual_banks         = true,
211                 .flash_base                     = 0x40023C00,
212                 .fsize_base                     = 0x1FF800CC,
213         },
214 };
215
216 /* flash bank stm32lx <base> <size> 0 0 <target#>
217  */
218 FLASH_BANK_COMMAND_HANDLER(stm32lx_flash_bank_command)
219 {
220         struct stm32lx_flash_bank *stm32lx_info;
221         if (CMD_ARGC < 6)
222                 return ERROR_COMMAND_SYNTAX_ERROR;
223
224         /* Create the bank structure */
225         stm32lx_info = calloc(1, sizeof(*stm32lx_info));
226
227         /* Check allocation */
228         if (stm32lx_info == NULL) {
229                 LOG_ERROR("failed to allocate bank structure");
230                 return ERROR_FAIL;
231         }
232
233         bank->driver_priv = stm32lx_info;
234
235         stm32lx_info->probed = 0;
236         stm32lx_info->user_bank_size = bank->size;
237
238         /* the stm32l erased value is 0x00 */
239         bank->default_padded_value = 0x00;
240
241         return ERROR_OK;
242 }
243
244 COMMAND_HANDLER(stm32lx_handle_mass_erase_command)
245 {
246         int i;
247
248         if (CMD_ARGC < 1)
249                 return ERROR_COMMAND_SYNTAX_ERROR;
250
251         struct flash_bank *bank;
252         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
253         if (ERROR_OK != retval)
254                 return retval;
255
256         retval = stm32lx_mass_erase(bank);
257         if (retval == ERROR_OK) {
258                 /* set all sectors as erased */
259                 for (i = 0; i < bank->num_sectors; i++)
260                         bank->sectors[i].is_erased = 1;
261
262                 command_print(CMD_CTX, "stm32lx mass erase complete");
263         } else {
264                 command_print(CMD_CTX, "stm32lx mass erase failed");
265         }
266
267         return retval;
268 }
269
270 static int stm32lx_protect_check(struct flash_bank *bank)
271 {
272         int retval;
273         struct target *target = bank->target;
274         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
275
276         uint32_t wrpr;
277
278         /*
279          * Read the WRPR word, and check each bit (corresponding to each
280          * flash sector
281          */
282         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_WRPR,
283                         &wrpr);
284         if (retval != ERROR_OK)
285                 return retval;
286
287         for (int i = 0; i < bank->num_sectors; i++) {
288                 if (wrpr & (1 << i))
289                         bank->sectors[i].is_protected = 1;
290                 else
291                         bank->sectors[i].is_protected = 0;
292         }
293         return ERROR_OK;
294 }
295
296 static int stm32lx_erase(struct flash_bank *bank, int first, int last)
297 {
298         int retval;
299
300         /*
301          * It could be possible to do a mass erase if all sectors must be
302          * erased, but it is not implemented yet.
303          */
304
305         if (bank->target->state != TARGET_HALTED) {
306                 LOG_ERROR("Target not halted");
307                 return ERROR_TARGET_NOT_HALTED;
308         }
309
310         if ((first == 0) && (last == (bank->num_sectors - 1)))
311                 return stm32lx_mass_erase(bank);
312
313         /*
314          * Loop over the selected sectors and erase them
315          */
316         for (int i = first; i <= last; i++) {
317                 retval = stm32lx_erase_sector(bank, i);
318                 if (retval != ERROR_OK)
319                         return retval;
320                 bank->sectors[i].is_erased = 1;
321         }
322         return ERROR_OK;
323 }
324
325 static int stm32lx_protect(struct flash_bank *bank, int set, int first,
326                 int last)
327 {
328         LOG_WARNING("protection of the STM32L flash is not implemented");
329         return ERROR_OK;
330 }
331
332 static int stm32lx_write_half_pages(struct flash_bank *bank, const uint8_t *buffer,
333                 uint32_t offset, uint32_t count)
334 {
335         struct target *target = bank->target;
336         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
337
338         uint32_t hp_nb = stm32lx_info->part_info->page_size / 2;
339         uint32_t buffer_size = 16384;
340         struct working_area *write_algorithm;
341         struct working_area *source;
342         uint32_t address = bank->base + offset;
343
344         struct reg_param reg_params[3];
345         struct armv7m_algorithm armv7m_info;
346
347         int retval = ERROR_OK;
348
349         /* see contib/loaders/flash/stm32lx.S for src */
350
351         static const uint8_t stm32lx_flash_write_code[] = {
352                 /* write_word: */
353                 0x00, 0x23,             /* movs r3, #0 */
354                 0x04, 0xe0,             /* b test_done */
355
356                 /* write_word: */
357                 0x51, 0xf8, 0x04, 0xcb, /* ldr ip, [r1], #4 */
358                 0x40, 0xf8, 0x04, 0xcb, /* str ip, [r0], #4 */
359                 0x01, 0x33,             /* adds r3, #1 */
360
361                 /* test_done: */
362                 0x93, 0x42,             /* cmp r3, r2 */
363                 0xf8, 0xd3,             /* bcc write_word */
364                 0x00, 0xbe,             /* bkpt 0 */
365         };
366
367         /* Make sure we're performing a half-page aligned write. */
368         if (count % hp_nb) {
369                 LOG_ERROR("The byte count must be %" PRIu32 "B-aligned but count is %" PRIi32 "B)", hp_nb, count);
370                 return ERROR_FAIL;
371         }
372
373         /* flash write code */
374         if (target_alloc_working_area(target, sizeof(stm32lx_flash_write_code),
375                         &write_algorithm) != ERROR_OK) {
376                 LOG_DEBUG("no working area for block memory writes");
377                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
378         };
379
380         /* Write the flashing code */
381         retval = target_write_buffer(target,
382                         write_algorithm->address,
383                         sizeof(stm32lx_flash_write_code),
384                         stm32lx_flash_write_code);
385         if (retval != ERROR_OK) {
386                 target_free_working_area(target, write_algorithm);
387                 return retval;
388         }
389
390         /* Allocate half pages memory */
391         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) {
392                 if (buffer_size > 1024)
393                         buffer_size -= 1024;
394                 else
395                         buffer_size /= 2;
396
397                 if (buffer_size <= stm32lx_info->part_info->page_size) {
398                         /* we already allocated the writing code, but failed to get a
399                          * buffer, free the algorithm */
400                         target_free_working_area(target, write_algorithm);
401
402                         LOG_WARNING("no large enough working area available, can't do block memory writes");
403                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
404                 }
405         }
406
407         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
408         armv7m_info.core_mode = ARM_MODE_THREAD;
409         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
410         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
411         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
412
413         /* Enable half-page write */
414         retval = stm32lx_enable_write_half_page(bank);
415         if (retval != ERROR_OK) {
416                 target_free_working_area(target, source);
417                 target_free_working_area(target, write_algorithm);
418
419                 destroy_reg_param(&reg_params[0]);
420                 destroy_reg_param(&reg_params[1]);
421                 destroy_reg_param(&reg_params[2]);
422                 return retval;
423         }
424
425         struct armv7m_common *armv7m = target_to_armv7m(target);
426         if (armv7m == NULL) {
427
428                 /* something is very wrong if armv7m is NULL */
429                 LOG_ERROR("unable to get armv7m target");
430                 return retval;
431         }
432
433         /* save any DEMCR flags and configure target to catch any Hard Faults */
434         uint32_t demcr_save = armv7m->demcr;
435         armv7m->demcr = VC_HARDERR;
436
437         /* Loop while there are bytes to write */
438         while (count > 0) {
439                 uint32_t this_count;
440                 this_count = (count > buffer_size) ? buffer_size : count;
441
442                 /* Write the next half pages */
443                 retval = target_write_buffer(target, source->address, this_count, buffer);
444                 if (retval != ERROR_OK)
445                         break;
446
447                 /* 4: Store useful information in the registers */
448                 /* the destination address of the copy (R0) */
449                 buf_set_u32(reg_params[0].value, 0, 32, address);
450                 /* The source address of the copy (R1) */
451                 buf_set_u32(reg_params[1].value, 0, 32, source->address);
452                 /* The length of the copy (R2) */
453                 buf_set_u32(reg_params[2].value, 0, 32, this_count / 4);
454
455                 /* 5: Execute the bunch of code */
456                 retval = target_run_algorithm(target, 0, NULL, sizeof(reg_params)
457                                 / sizeof(*reg_params), reg_params,
458                                 write_algorithm->address, 0, 10000, &armv7m_info);
459                 if (retval != ERROR_OK)
460                         break;
461
462                 /* check for Hard Fault */
463                 if (armv7m->exception_number == 3)
464                         break;
465
466                 /* 6: Wait while busy */
467                 retval = stm32lx_wait_until_bsy_clear(bank);
468                 if (retval != ERROR_OK)
469                         break;
470
471                 buffer += this_count;
472                 address += this_count;
473                 count -= this_count;
474         }
475
476         /* restore previous flags */
477         armv7m->demcr = demcr_save;
478
479         if (armv7m->exception_number == 3) {
480
481                 /* the stm32l15x devices seem to have an issue when blank.
482                  * if a ram loader is executed on a blank device it will
483                  * Hard Fault, this issue does not happen for a already programmed device.
484                  * A related issue is described in the stm32l151xx errata (Doc ID 17721 Rev 6 - 2.1.3).
485                  * The workaround of handling the Hard Fault exception does work, but makes the
486                  * loader more complicated, as a compromise we manually write the pages, programming time
487                  * is reduced by 50% using this slower method.
488                  */
489
490                 LOG_WARNING("couldn't use loader, falling back to page memory writes");
491
492                 while (count > 0) {
493                         uint32_t this_count;
494                         this_count = (count > hp_nb) ? hp_nb : count;
495
496                         /* Write the next half pages */
497                         retval = target_write_buffer(target, address, this_count, buffer);
498                         if (retval != ERROR_OK)
499                                 break;
500
501                         /* Wait while busy */
502                         retval = stm32lx_wait_until_bsy_clear(bank);
503                         if (retval != ERROR_OK)
504                                 break;
505
506                         buffer += this_count;
507                         address += this_count;
508                         count -= this_count;
509                 }
510         }
511
512         if (retval == ERROR_OK)
513                 retval = stm32lx_lock_program_memory(bank);
514
515         target_free_working_area(target, source);
516         target_free_working_area(target, write_algorithm);
517
518         destroy_reg_param(&reg_params[0]);
519         destroy_reg_param(&reg_params[1]);
520         destroy_reg_param(&reg_params[2]);
521
522         return retval;
523 }
524
525 static int stm32lx_write(struct flash_bank *bank, const uint8_t *buffer,
526                 uint32_t offset, uint32_t count)
527 {
528         struct target *target = bank->target;
529         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
530
531         uint32_t hp_nb = stm32lx_info->part_info->page_size / 2;
532         uint32_t halfpages_number;
533         uint32_t bytes_remaining = 0;
534         uint32_t address = bank->base + offset;
535         uint32_t bytes_written = 0;
536         int retval, retval2;
537
538         if (bank->target->state != TARGET_HALTED) {
539                 LOG_ERROR("Target not halted");
540                 return ERROR_TARGET_NOT_HALTED;
541         }
542
543         if (offset & 0x3) {
544                 LOG_ERROR("offset 0x%" PRIx32 " breaks required 4-byte alignment", offset);
545                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
546         }
547
548         retval = stm32lx_unlock_program_memory(bank);
549         if (retval != ERROR_OK)
550                 return retval;
551
552         /* first we need to write any unaligned head bytes upto
553          * the next 128 byte page */
554
555         if (offset % hp_nb)
556                 bytes_remaining = MIN(count, hp_nb - (offset % hp_nb));
557
558         while (bytes_remaining > 0) {
559                 uint8_t value[4] = {0xff, 0xff, 0xff, 0xff};
560
561                 /* copy remaining bytes into the write buffer */
562                 uint32_t bytes_to_write = MIN(4, bytes_remaining);
563                 memcpy(value, buffer + bytes_written, bytes_to_write);
564
565                 retval = target_write_buffer(target, address, 4, value);
566                 if (retval != ERROR_OK)
567                         goto reset_pg_and_lock;
568
569                 bytes_written += bytes_to_write;
570                 bytes_remaining -= bytes_to_write;
571                 address += 4;
572
573                 retval = stm32lx_wait_until_bsy_clear(bank);
574                 if (retval != ERROR_OK)
575                         goto reset_pg_and_lock;
576         }
577
578         offset += bytes_written;
579         count -= bytes_written;
580
581         /* this should always pass this check here */
582         assert((offset % hp_nb) == 0);
583
584         /* calculate half pages */
585         halfpages_number = count / hp_nb;
586
587         if (halfpages_number) {
588                 retval = stm32lx_write_half_pages(bank, buffer + bytes_written, offset, hp_nb * halfpages_number);
589                 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
590                         /* attempt slow memory writes */
591                         LOG_WARNING("couldn't use block writes, falling back to single memory accesses");
592                         halfpages_number = 0;
593                 } else {
594                         if (retval != ERROR_OK)
595                                 return ERROR_FAIL;
596                 }
597         }
598
599         /* write any remaining bytes */
600         uint32_t page_bytes_written = hp_nb * halfpages_number;
601         bytes_written += page_bytes_written;
602         address += page_bytes_written;
603         bytes_remaining = count - page_bytes_written;
604
605         retval = stm32lx_unlock_program_memory(bank);
606         if (retval != ERROR_OK)
607                 return retval;
608
609         while (bytes_remaining > 0) {
610                 uint8_t value[4] = {0xff, 0xff, 0xff, 0xff};
611
612                 /* copy remaining bytes into the write buffer */
613                 uint32_t bytes_to_write = MIN(4, bytes_remaining);
614                 memcpy(value, buffer + bytes_written, bytes_to_write);
615
616                 retval = target_write_buffer(target, address, 4, value);
617                 if (retval != ERROR_OK)
618                         goto reset_pg_and_lock;
619
620                 bytes_written += bytes_to_write;
621                 bytes_remaining -= bytes_to_write;
622                 address += 4;
623
624                 retval = stm32lx_wait_until_bsy_clear(bank);
625                 if (retval != ERROR_OK)
626                         goto reset_pg_and_lock;
627         }
628
629 reset_pg_and_lock:
630         retval2 = stm32lx_lock_program_memory(bank);
631         if (retval == ERROR_OK)
632                 retval = retval2;
633
634         return retval;
635 }
636
637 static int stm32lx_read_id_code(struct target *target, uint32_t *id)
638 {
639         /* read stm32 device id register */
640         int retval = target_read_u32(target, DBGMCU_IDCODE, id);
641         if (retval != ERROR_OK)
642                 return retval;
643
644         /* STM32L0 parts will have 0 there, try reading the L0's location for
645          * DBG_IDCODE in case this is an L0 part. */
646         if (*id == 0)
647                 retval = target_read_u32(target, DBGMCU_IDCODE_L0, id);
648
649         return retval;
650 }
651
652 static int stm32lx_probe(struct flash_bank *bank)
653 {
654         struct target *target = bank->target;
655         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
656         int i;
657         uint16_t flash_size_in_kb;
658         uint32_t device_id;
659         uint32_t base_address = FLASH_BANK0_ADDRESS;
660         uint32_t second_bank_base;
661
662         stm32lx_info->probed = 0;
663         stm32lx_info->part_info = NULL;
664
665         int retval = stm32lx_read_id_code(bank->target, &device_id);
666         if (retval != ERROR_OK)
667                 return retval;
668
669         stm32lx_info->idcode = device_id;
670
671         LOG_DEBUG("device id = 0x%08" PRIx32 "", device_id);
672
673         for (unsigned int n = 0; n < ARRAY_SIZE(stm32lx_parts); n++) {
674                 if ((device_id & 0xfff) == stm32lx_parts[n].id)
675                         stm32lx_info->part_info = &stm32lx_parts[n];
676         }
677
678         if (!stm32lx_info->part_info) {
679                 LOG_WARNING("Cannot identify target as a STM32L family.");
680                 return ERROR_FAIL;
681         }
682
683         stm32lx_info->flash_base = stm32lx_info->part_info->flash_base;
684
685         /* Get the flash size from target. */
686         retval = target_read_u16(target, stm32lx_info->part_info->fsize_base,
687                         &flash_size_in_kb);
688
689         /* 0x436 devices report their flash size as a 0 or 1 code indicating 384K
690          * or 256K, respectively.  Please see RM0038 r8 or newer and refer to
691          * section 30.1.1. */
692         if (retval == ERROR_OK && (device_id & 0xfff) == 0x436) {
693                 if (flash_size_in_kb == 0)
694                         flash_size_in_kb = 384;
695                 else if (flash_size_in_kb == 1)
696                         flash_size_in_kb = 256;
697         }
698
699         /* Failed reading flash size or flash size invalid (early silicon),
700          * default to max target family */
701         if (retval != ERROR_OK || flash_size_in_kb == 0xffff || flash_size_in_kb == 0) {
702                 LOG_WARNING("STM32L flash size failed, probe inaccurate - assuming %dk flash",
703                         stm32lx_info->part_info->max_flash_size_kb);
704                 flash_size_in_kb = stm32lx_info->part_info->max_flash_size_kb;
705         } else if (flash_size_in_kb > stm32lx_info->part_info->max_flash_size_kb) {
706                 LOG_WARNING("STM32L probed flash size assumed incorrect since FLASH_SIZE=%dk > %dk, - assuming %dk flash",
707                         flash_size_in_kb, stm32lx_info->part_info->max_flash_size_kb,
708                         stm32lx_info->part_info->max_flash_size_kb);
709                 flash_size_in_kb = stm32lx_info->part_info->max_flash_size_kb;
710         }
711
712         if (stm32lx_info->part_info->has_dual_banks) {
713                 /* Use the configured base address to determine if this is the first or second flash bank.
714                  * Verify that the base address is reasonably correct and determine the flash bank size
715                  */
716                 second_bank_base = base_address +
717                         stm32lx_info->part_info->first_bank_size_kb * 1024;
718                 if (bank->base == second_bank_base) {
719                         /* This is the second bank  */
720                         base_address = second_bank_base;
721                         flash_size_in_kb = flash_size_in_kb -
722                                 stm32lx_info->part_info->first_bank_size_kb;
723                 } else if (bank->base == 0 || bank->base == base_address) {
724                         /* This is the first bank */
725                         flash_size_in_kb = stm32lx_info->part_info->first_bank_size_kb;
726                 } else {
727                         LOG_WARNING("STM32L flash bank base address config is incorrect."
728                                     " 0x%" PRIx32 " but should rather be 0x%" PRIx32 " or 0x%" PRIx32,
729                                                 bank->base, base_address, second_bank_base);
730                         return ERROR_FAIL;
731                 }
732                 LOG_INFO("STM32L flash has dual banks. Bank (%d) size is %dkb, base address is 0x%" PRIx32,
733                                 bank->bank_number, flash_size_in_kb, base_address);
734         } else {
735                 LOG_INFO("STM32L flash size is %dkb, base address is 0x%" PRIx32, flash_size_in_kb, base_address);
736         }
737
738         /* if the user sets the size manually then ignore the probed value
739          * this allows us to work around devices that have a invalid flash size register value */
740         if (stm32lx_info->user_bank_size) {
741                 flash_size_in_kb = stm32lx_info->user_bank_size / 1024;
742                 LOG_INFO("ignoring flash probed value, using configured bank size: %dkbytes", flash_size_in_kb);
743         }
744
745         /* calculate numbers of sectors (4kB per sector) */
746         int num_sectors = (flash_size_in_kb * 1024) / FLASH_SECTOR_SIZE;
747
748         if (bank->sectors) {
749                 free(bank->sectors);
750                 bank->sectors = NULL;
751         }
752
753         bank->size = flash_size_in_kb * 1024;
754         bank->base = base_address;
755         bank->num_sectors = num_sectors;
756         bank->sectors = malloc(sizeof(struct flash_sector) * num_sectors);
757         if (bank->sectors == NULL) {
758                 LOG_ERROR("failed to allocate bank sectors");
759                 return ERROR_FAIL;
760         }
761
762         for (i = 0; i < num_sectors; i++) {
763                 bank->sectors[i].offset = i * FLASH_SECTOR_SIZE;
764                 bank->sectors[i].size = FLASH_SECTOR_SIZE;
765                 bank->sectors[i].is_erased = -1;
766                 bank->sectors[i].is_protected = 1;
767         }
768
769         stm32lx_info->probed = 1;
770
771         return ERROR_OK;
772 }
773
774 static int stm32lx_auto_probe(struct flash_bank *bank)
775 {
776         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
777
778         if (stm32lx_info->probed)
779                 return ERROR_OK;
780
781         return stm32lx_probe(bank);
782 }
783
784 static int stm32lx_erase_check(struct flash_bank *bank)
785 {
786         struct target *target = bank->target;
787         const int buffer_size = 4096;
788         int i;
789         uint32_t nBytes;
790         int retval = ERROR_OK;
791
792         if (bank->target->state != TARGET_HALTED) {
793                 LOG_ERROR("Target not halted");
794                 return ERROR_TARGET_NOT_HALTED;
795         }
796
797         uint8_t *buffer = malloc(buffer_size);
798         if (buffer == NULL) {
799                 LOG_ERROR("failed to allocate read buffer");
800                 return ERROR_FAIL;
801         }
802
803         for (i = 0; i < bank->num_sectors; i++) {
804                 uint32_t j;
805                 bank->sectors[i].is_erased = 1;
806
807                 /* Loop chunk by chunk over the sector */
808                 for (j = 0; j < bank->sectors[i].size; j += buffer_size) {
809                         uint32_t chunk;
810                         chunk = buffer_size;
811                         if (chunk > (j - bank->sectors[i].size))
812                                 chunk = (j - bank->sectors[i].size);
813
814                         retval = target_read_memory(target, bank->base
815                                         + bank->sectors[i].offset + j, 4, chunk / 4, buffer);
816                         if (retval != ERROR_OK)
817                                 break;
818
819                         for (nBytes = 0; nBytes < chunk; nBytes++) {
820                                 if (buffer[nBytes] != 0x00) {
821                                         bank->sectors[i].is_erased = 0;
822                                         break;
823                                 }
824                         }
825                 }
826                 if (retval != ERROR_OK)
827                         break;
828         }
829         free(buffer);
830
831         return retval;
832 }
833
834 /* This method must return a string displaying information about the bank */
835 static int stm32lx_get_info(struct flash_bank *bank, char *buf, int buf_size)
836 {
837         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
838
839         if (!stm32lx_info->probed) {
840                 int retval = stm32lx_probe(bank);
841                 if (retval != ERROR_OK) {
842                         snprintf(buf, buf_size,
843                                 "Unable to find bank information.");
844                         return retval;
845                 }
846         }
847
848         const struct stm32lx_part_info *info = stm32lx_info->part_info;
849
850         if (info) {
851                 const char *rev_str = NULL;
852                 uint16_t rev_id = stm32lx_info->idcode >> 16;
853
854                 for (unsigned int i = 0; i < info->num_revs; i++)
855                         if (rev_id == info->revs[i].rev)
856                                 rev_str = info->revs[i].str;
857
858                 if (rev_str != NULL) {
859                         snprintf(buf, buf_size,
860                                 "%s - Rev: %s",
861                                 stm32lx_info->part_info->device_str, rev_str);
862                 } else {
863                         snprintf(buf, buf_size,
864                                 "%s - Rev: unknown (0x%04x)",
865                                 stm32lx_info->part_info->device_str, rev_id);
866                 }
867
868                 return ERROR_OK;
869         } else {
870                 snprintf(buf, buf_size, "Cannot identify target as a STM32Lx");
871
872                 return ERROR_FAIL;
873         }
874 }
875
876 static const struct command_registration stm32lx_exec_command_handlers[] = {
877         {
878                 .name = "mass_erase",
879                 .handler = stm32lx_handle_mass_erase_command,
880                 .mode = COMMAND_EXEC,
881                 .usage = "bank_id",
882                 .help = "Erase entire flash device. including available EEPROM",
883         },
884         COMMAND_REGISTRATION_DONE
885 };
886
887 static const struct command_registration stm32lx_command_handlers[] = {
888         {
889                 .name = "stm32lx",
890                 .mode = COMMAND_ANY,
891                 .help = "stm32lx flash command group",
892                 .usage = "",
893                 .chain = stm32lx_exec_command_handlers,
894         },
895         COMMAND_REGISTRATION_DONE
896 };
897
898 struct flash_driver stm32lx_flash = {
899                 .name = "stm32lx",
900                 .commands = stm32lx_command_handlers,
901                 .flash_bank_command = stm32lx_flash_bank_command,
902                 .erase = stm32lx_erase,
903                 .protect = stm32lx_protect,
904                 .write = stm32lx_write,
905                 .read = default_flash_read,
906                 .probe = stm32lx_probe,
907                 .auto_probe = stm32lx_auto_probe,
908                 .erase_check = stm32lx_erase_check,
909                 .protect_check = stm32lx_protect_check,
910                 .info = stm32lx_get_info,
911 };
912
913 /* Static methods implementation */
914 static int stm32lx_unlock_program_memory(struct flash_bank *bank)
915 {
916         struct target *target = bank->target;
917         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
918         int retval;
919         uint32_t reg32;
920
921         /*
922          * Unlocking the program memory is done by unlocking the PECR,
923          * then by writing the 2 PRGKEY to the PRGKEYR register
924          */
925
926         /* check flash is not already unlocked */
927         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
928                         &reg32);
929         if (retval != ERROR_OK)
930                 return retval;
931
932         if ((reg32 & FLASH_PECR__PRGLOCK) == 0)
933                 return ERROR_OK;
934
935         /* To unlock the PECR write the 2 PEKEY to the PEKEYR register */
936         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PEKEYR,
937                         PEKEY1);
938         if (retval != ERROR_OK)
939                 return retval;
940
941         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PEKEYR,
942                         PEKEY2);
943         if (retval != ERROR_OK)
944                 return retval;
945
946         /* Make sure it worked */
947         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
948                         &reg32);
949         if (retval != ERROR_OK)
950                 return retval;
951
952         if (reg32 & FLASH_PECR__PELOCK) {
953                 LOG_ERROR("PELOCK is not cleared :(");
954                 return ERROR_FLASH_OPERATION_FAILED;
955         }
956
957         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PRGKEYR,
958                         PRGKEY1);
959         if (retval != ERROR_OK)
960                 return retval;
961         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PRGKEYR,
962                         PRGKEY2);
963         if (retval != ERROR_OK)
964                 return retval;
965
966         /* Make sure it worked */
967         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
968                         &reg32);
969         if (retval != ERROR_OK)
970                 return retval;
971
972         if (reg32 & FLASH_PECR__PRGLOCK) {
973                 LOG_ERROR("PRGLOCK is not cleared :(");
974                 return ERROR_FLASH_OPERATION_FAILED;
975         }
976
977         return ERROR_OK;
978 }
979
980 static int stm32lx_enable_write_half_page(struct flash_bank *bank)
981 {
982         struct target *target = bank->target;
983         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
984         int retval;
985         uint32_t reg32;
986
987         /**
988          * Unlock the program memory, then set the FPRG bit in the PECR register.
989          */
990         retval = stm32lx_unlock_program_memory(bank);
991         if (retval != ERROR_OK)
992                 return retval;
993
994         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
995                         &reg32);
996         if (retval != ERROR_OK)
997                 return retval;
998
999         reg32 |= FLASH_PECR__FPRG;
1000         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1001                         reg32);
1002         if (retval != ERROR_OK)
1003                 return retval;
1004
1005         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1006                         &reg32);
1007         if (retval != ERROR_OK)
1008                 return retval;
1009
1010         reg32 |= FLASH_PECR__PROG;
1011         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1012                         reg32);
1013
1014         return retval;
1015 }
1016
1017 static int stm32lx_lock_program_memory(struct flash_bank *bank)
1018 {
1019         struct target *target = bank->target;
1020         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1021         int retval;
1022         uint32_t reg32;
1023
1024         /* To lock the program memory, simply set the lock bit and lock PECR */
1025
1026         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1027                         &reg32);
1028         if (retval != ERROR_OK)
1029                 return retval;
1030
1031         reg32 |= FLASH_PECR__PRGLOCK;
1032         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1033                         reg32);
1034         if (retval != ERROR_OK)
1035                 return retval;
1036
1037         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1038                         &reg32);
1039         if (retval != ERROR_OK)
1040                 return retval;
1041
1042         reg32 |= FLASH_PECR__PELOCK;
1043         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1044                         reg32);
1045         if (retval != ERROR_OK)
1046                 return retval;
1047
1048         return ERROR_OK;
1049 }
1050
1051 static int stm32lx_erase_sector(struct flash_bank *bank, int sector)
1052 {
1053         struct target *target = bank->target;
1054         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1055         int retval;
1056         uint32_t reg32;
1057
1058         /*
1059          * To erase a sector (i.e. stm32lx_info->part_info.pages_per_sector pages),
1060          * first unlock the memory, loop over the pages of this sector
1061          * and write 0x0 to its first word.
1062          */
1063
1064         retval = stm32lx_unlock_program_memory(bank);
1065         if (retval != ERROR_OK)
1066                 return retval;
1067
1068         for (int page = 0; page < (int)stm32lx_info->part_info->pages_per_sector;
1069                         page++) {
1070                 reg32 = FLASH_PECR__PROG | FLASH_PECR__ERASE;
1071                 retval = target_write_u32(target,
1072                                 stm32lx_info->flash_base + FLASH_PECR, reg32);
1073                 if (retval != ERROR_OK)
1074                         return retval;
1075
1076                 retval = stm32lx_wait_until_bsy_clear(bank);
1077                 if (retval != ERROR_OK)
1078                         return retval;
1079
1080                 uint32_t addr = bank->base + bank->sectors[sector].offset + (page
1081                                 * stm32lx_info->part_info->page_size);
1082                 retval = target_write_u32(target, addr, 0x0);
1083                 if (retval != ERROR_OK)
1084                         return retval;
1085
1086                 retval = stm32lx_wait_until_bsy_clear(bank);
1087                 if (retval != ERROR_OK)
1088                         return retval;
1089         }
1090
1091         retval = stm32lx_lock_program_memory(bank);
1092         if (retval != ERROR_OK)
1093                 return retval;
1094
1095         return ERROR_OK;
1096 }
1097
1098 static inline int stm32lx_get_flash_status(struct flash_bank *bank, uint32_t *status)
1099 {
1100         struct target *target = bank->target;
1101         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1102
1103         return target_read_u32(target, stm32lx_info->flash_base + FLASH_SR, status);
1104 }
1105
1106 static int stm32lx_wait_until_bsy_clear(struct flash_bank *bank)
1107 {
1108         return stm32lx_wait_until_bsy_clear_timeout(bank, 100);
1109 }
1110
1111 static int stm32lx_unlock_options_bytes(struct flash_bank *bank)
1112 {
1113         struct target *target = bank->target;
1114         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1115         int retval;
1116         uint32_t reg32;
1117
1118         /*
1119         * Unlocking the options bytes is done by unlocking the PECR,
1120         * then by writing the 2 FLASH_PEKEYR to the FLASH_OPTKEYR register
1121         */
1122
1123         /* check flash is not already unlocked */
1124         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR, &reg32);
1125         if (retval != ERROR_OK)
1126                 return retval;
1127
1128         if ((reg32 & FLASH_PECR__OPTLOCK) == 0)
1129                 return ERROR_OK;
1130
1131         if ((reg32 & FLASH_PECR__PELOCK) != 0) {
1132
1133                 retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PEKEYR, PEKEY1);
1134                 if (retval != ERROR_OK)
1135                         return retval;
1136
1137                 retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PEKEYR, PEKEY2);
1138                 if (retval != ERROR_OK)
1139                         return retval;
1140         }
1141
1142         /* To unlock the PECR write the 2 OPTKEY to the FLASH_OPTKEYR register */
1143         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_OPTKEYR, OPTKEY1);
1144         if (retval != ERROR_OK)
1145                 return retval;
1146
1147         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_OPTKEYR, OPTKEY2);
1148         if (retval != ERROR_OK)
1149                 return retval;
1150
1151         return ERROR_OK;
1152 }
1153
1154 static int stm32lx_wait_until_bsy_clear_timeout(struct flash_bank *bank, int timeout)
1155 {
1156         struct target *target = bank->target;
1157         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1158         uint32_t status;
1159         int retval = ERROR_OK;
1160
1161         /* wait for busy to clear */
1162         for (;;) {
1163                 retval = stm32lx_get_flash_status(bank, &status);
1164                 if (retval != ERROR_OK)
1165                         return retval;
1166
1167                 LOG_DEBUG("status: 0x%" PRIx32 "", status);
1168                 if ((status & FLASH_SR__BSY) == 0)
1169                         break;
1170
1171                 if (timeout-- <= 0) {
1172                         LOG_ERROR("timed out waiting for flash");
1173                         return ERROR_FAIL;
1174                 }
1175                 alive_sleep(1);
1176         }
1177
1178         if (status & FLASH_SR__WRPERR) {
1179                 LOG_ERROR("access denied / write protected");
1180                 retval = ERROR_FAIL;
1181         }
1182
1183         if (status & FLASH_SR__PGAERR) {
1184                 LOG_ERROR("invalid program address");
1185                 retval = ERROR_FAIL;
1186         }
1187
1188         /* Clear but report errors */
1189         if (status & FLASH_SR__OPTVERR) {
1190                 /* If this operation fails, we ignore it and report the original retval */
1191                 target_write_u32(target, stm32lx_info->flash_base + FLASH_SR, status & FLASH_SR__OPTVERR);
1192         }
1193
1194         return retval;
1195 }
1196
1197 static int stm32lx_obl_launch(struct flash_bank *bank)
1198 {
1199         struct target *target = bank->target;
1200         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1201         int retval;
1202
1203         /* This will fail as the target gets immediately rebooted */
1204         target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1205                          FLASH_PECR__OBL_LAUNCH);
1206
1207         size_t tries = 10;
1208         do {
1209                 target_halt(target);
1210                 retval = target_poll(target);
1211         } while (--tries > 0 &&
1212                  (retval != ERROR_OK || target->state != TARGET_HALTED));
1213
1214         return tries ? ERROR_OK : ERROR_FAIL;
1215 }
1216
1217 static int stm32lx_mass_erase(struct flash_bank *bank)
1218 {
1219         int retval;
1220         struct target *target = bank->target;
1221         struct stm32lx_flash_bank *stm32lx_info = NULL;
1222         uint32_t reg32;
1223
1224         if (target->state != TARGET_HALTED) {
1225                 LOG_ERROR("Target not halted");
1226                 return ERROR_TARGET_NOT_HALTED;
1227         }
1228
1229         stm32lx_info = bank->driver_priv;
1230
1231         retval = stm32lx_unlock_options_bytes(bank);
1232         if (retval != ERROR_OK)
1233                 return retval;
1234
1235         /* mass erase flash memory */
1236         /* set the RDP protection level to 1 */
1237         retval = target_write_u32(target, OPTION_BYTES_ADDRESS, OPTION_BYTE_0_PR1);
1238         if (retval != ERROR_OK)
1239                 return retval;
1240
1241         retval = stm32lx_obl_launch(bank);
1242         if (retval != ERROR_OK)
1243                 return retval;
1244
1245         retval = stm32lx_unlock_options_bytes(bank);
1246         if (retval != ERROR_OK)
1247                 return retval;
1248
1249         /* set the RDP protection level to 0 */
1250         retval = target_write_u32(target, OPTION_BYTES_ADDRESS, OPTION_BYTE_0_PR0);
1251         if (retval != ERROR_OK)
1252                 return retval;
1253
1254         retval = stm32lx_wait_until_bsy_clear_timeout(bank, 30000);
1255         if (retval != ERROR_OK)
1256                 return retval;
1257
1258         retval = stm32lx_obl_launch(bank);
1259         if (retval != ERROR_OK)
1260                 return retval;
1261
1262         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR, &reg32);
1263         if (retval != ERROR_OK)
1264                 return retval;
1265
1266         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR, reg32 | FLASH_PECR__OPTLOCK);
1267         if (retval != ERROR_OK)
1268                 return retval;
1269
1270         return ERROR_OK;
1271 }