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