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