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