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