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