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