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