STM32L: Added flash driver and target
[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 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29
30 #include "imp.h"
31 #include <helper/binarybuffer.h>
32 #include <target/algorithm.h>
33 #include <target/armv7m.h>
34
35 /* stm32lx flash register locations */
36
37 #define FLASH_BASE              0x40023C00
38 #define FLASH_ACR               0x40023C00
39 #define FLASH_PECR              0x40023C04
40 #define FLASH_PDKEYR    0x40023C08
41 #define FLASH_PEKEYR    0x40023C0C
42 #define FLASH_PRGKEYR   0x40023C10
43 #define FLASH_OPTKEYR   0x40023C14
44 #define FLASH_SR                0x40023C18
45 #define FLASH_OBR               0x40023C1C
46 #define FLASH_WRPR              0x40023C20
47
48 /* FLASH_ACR bites */
49 #define FLASH_ACR__LATENCY              (1<<0)
50 #define FLASH_ACR__PRFTEN               (1<<1)
51 #define FLASH_ACR__ACC64                (1<<2)
52 #define FLASH_ACR__SLEEP_PD             (1<<3)
53 #define FLASH_ACR__RUN_PD               (1<<4)
54
55 /* FLASH_PECR bits */
56 #define FLASH_PECR__PELOCK              (1<<0)
57 #define FLASH_PECR__PRGLOCK             (1<<1)
58 #define FLASH_PECR__OPTLOCK             (1<<2)
59 #define FLASH_PECR__PROG                (1<<3)
60 #define FLASH_PECR__DATA                (1<<4)
61 #define FLASH_PECR__FTDW                (1<<8)
62 #define FLASH_PECR__ERASE               (1<<9)
63 #define FLASH_PECR__FPRG                (1<<10)
64 #define FLASH_PECR__EOPIE               (1<<16)
65 #define FLASH_PECR__ERRIE               (1<<17)
66 #define FLASH_PECR__OBL_LAUNCH  (1<<18)
67
68 /* FLASH_SR bits */
69 #define FLASH_SR__BSY           (1<<0)
70 #define FLASH_SR__EOP           (1<<1)
71 #define FLASH_SR__ENDHV         (1<<2)
72 #define FLASH_SR__READY         (1<<3)
73 #define FLASH_SR__WRPERR        (1<<8)
74 #define FLASH_SR__PGAERR        (1<<9)
75 #define FLASH_SR__SIZERR        (1<<10)
76 #define FLASH_SR__OPTVERR       (1<<11)
77
78 /* Unlock keys */
79 #define PEKEY1                  0x89ABCDEF
80 #define PEKEY2                  0x02030405
81 #define PRGKEY1                 0x8C9DAEBF
82 #define PRGKEY2                 0x13141516
83 #define OPTKEY1                 0xFBEAD9C8
84 #define OPTKEY2                 0x24252627
85
86 /* other registers */
87 #define DBGMCU_IDCODE   0xE0042000
88 #define F_SIZE                  0x1FF8004C
89
90 /* Constants */
91 #define FLASH_PAGE_SIZE 256
92 #define FLASH_SECTOR_SIZE 4096
93 #define FLASH_PAGES_PER_SECTOR 16
94 #define FLASH_BANK0_ADDRESS 0x08000000
95
96 /* stm32lx option byte register location */
97 #define OB_RDP                  0x1FF80000
98 #define OB_USER                 0x1FF80004
99 #define OB_WRP0_1               0x1FF80008
100 #define OB_WRP2_3               0x1FF8000C
101
102 /* OB_RDP values */
103 #define OB_RDP__LEVEL0  0xFF5500AA
104 #define OB_RDP__LEVEL1  0xFFFF0000
105
106 /* stm32lx RCC register locations */
107 #define RCC_CR          0x40023800
108 #define RCC_ICSCR       0x40023804
109 #define RCC_CFGR        0x40023808
110
111 /* RCC_ICSCR bits */
112 #define RCC_ICSCR__MSIRANGE_MASK        (7<<13)
113
114 static int stm32lx_unlock_program_memory(struct flash_bank *bank);
115 static int stm32lx_lock_program_memory(struct flash_bank *bank);
116 static int stm32lx_enable_write_half_page(struct flash_bank *bank);
117 static int stm32lx_erase_sector(struct flash_bank *bank, int sector);
118 static int stm32lx_wait_until_bsy_clear(struct flash_bank *bank);
119
120 struct stm32lx_flash_bank
121 {
122         struct working_area *write_algorithm;
123         int probed;
124 };
125
126 /* flash bank stm32lx <base> <size> 0 0 <target#>
127  */
128 FLASH_BANK_COMMAND_HANDLER(stm32lx_flash_bank_command)
129 {
130         struct stm32lx_flash_bank *stm32lx_info;
131         if (CMD_ARGC < 6)
132         {
133                 LOG_ERROR("incomplete flash_bank stm32lx configuration");
134                 return ERROR_FLASH_BANK_INVALID;
135         }
136
137         // Create the bank structure
138         stm32lx_info = malloc(sizeof(struct stm32lx_flash_bank));
139
140         // Check allocation
141         if (stm32lx_info == NULL)
142         {
143                 LOG_ERROR("failed to allocate bank structure");
144                 return ERROR_FAIL;
145         }
146
147         bank->driver_priv = stm32lx_info;
148
149         stm32lx_info->write_algorithm = NULL;
150         stm32lx_info->probed = 0;
151
152         return ERROR_OK;
153 }
154
155 static int stm32lx_protect_check(struct flash_bank *bank)
156 {
157         int retval;
158         struct target *target = bank->target;
159
160         uint32_t wrpr;
161
162         if (target->state != TARGET_HALTED)
163         {
164                 LOG_ERROR("Target not halted");
165                 return ERROR_TARGET_NOT_HALTED;
166         }
167
168         /*
169          * Read the WRPR word, and check each bit (corresponding to each
170          * flash sector
171          */
172         retval = target_read_u32(target, FLASH_WRPR, &wrpr);
173         if (retval != ERROR_OK)
174                 return retval;
175
176         for (int i = 0; i < 32; i++)
177         {
178                 if (wrpr & (1 << i))
179                 {
180                         bank->sectors[i].is_protected = 1;
181                 }
182                 else
183                 {
184                         bank->sectors[i].is_protected = 0;
185                 }
186         }
187         return ERROR_OK;
188 }
189
190 static int stm32lx_erase(struct flash_bank *bank, int first, int last)
191 {
192         int retval;
193
194         /*
195          * It could be possible to do a mass erase if all sectors must be
196          * erased, but it is not implemented yet.
197          */
198
199         if (bank->target->state != TARGET_HALTED)
200         {
201                 LOG_ERROR("Target not halted");
202                 return ERROR_TARGET_NOT_HALTED;
203         }
204
205         /*
206          * Loop over the selected sectors and erase them
207          */
208         for (int i = first; i <= last; i++)
209         {
210                 retval = stm32lx_erase_sector(bank, i);
211                 if (retval != ERROR_OK)
212                         return retval;
213                 bank->sectors[i].is_erased = 1;
214         }
215         return ERROR_OK;
216 }
217
218 static int stm32lx_protect(struct flash_bank *bank, int set, int first,
219                 int last)
220 {
221         LOG_WARNING("protection of the STM32L flash is not implemented");
222         return ERROR_OK;
223 }
224
225 static int stm32lx_write_half_pages(struct flash_bank *bank, uint8_t *buffer,
226                 uint32_t offset, uint32_t count)
227 {
228         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
229         struct target *target = bank->target;
230         uint32_t buffer_size = 4096 * 4;
231         struct working_area *source;
232         uint32_t address = bank->base + offset;
233
234         struct reg_param reg_params[5];
235         struct armv7m_algorithm armv7m_info;
236
237         int retval = ERROR_OK;
238         uint32_t reg32;
239
240         /* see contib/loaders/flash/stm32lx.s for src */
241
242         static const uint16_t stm32lx_flash_write_code_16[] =
243         {
244         //      00000000 <write_word-0x4>:
245                         0x2300, // 0:   2300            movs    r3, #0
246                         0xe004, // 2:   e004            b.n     e <test_done>
247
248                         //      00000004 <write_word>:
249                         0xf851, 0xcb04, // 4:   f851 cb04       ldr.w   ip, [r1], #4
250                         0xf840, 0xcb04, // 8:   f840 cb04       str.w   ip, [r0], #4
251                         0x3301, // c:   3301            adds    r3, #1
252
253                         //      0000000e <test_done>:
254                         0x4293, // e:   4293            cmp     r3, r2
255                         0xd3f8, // 10:  d3f8            bcc.n   4 <write_word>
256                         0xbe00, // 12:  be00            bkpt    0x0000
257
258                         };
259
260         // Flip endian
261         uint8_t stm32lx_flash_write_code[sizeof(stm32lx_flash_write_code_16)];
262         for (unsigned int i = 0; i < sizeof(stm32lx_flash_write_code_16) / 2; i++)
263         {
264                 stm32lx_flash_write_code[i * 2 + 0] = stm32lx_flash_write_code_16[i]
265                                 & 0xff;
266                 stm32lx_flash_write_code[i * 2 + 1] = (stm32lx_flash_write_code_16[i]
267                                 >> 8) & 0xff;
268         }
269         // Check if there is an even number of half pages (128bytes)
270         if (count % 128)
271         {
272                 LOG_ERROR("there should be an even number "
273                                 "of half pages = 128 bytes (count = %" PRIi32 " bytes)", count);
274                 return ERROR_FAIL;
275         }
276
277         // Allocate working area
278         reg32 = sizeof(stm32lx_flash_write_code);
279         // Add bytes to make 4byte aligned
280         reg32 += (4 - (reg32 % 4)) % 4;
281         retval = target_alloc_working_area(target, reg32,
282                         &stm32lx_info->write_algorithm);
283         if (retval != ERROR_OK)
284                 return retval;
285
286         // Write the flashing code
287         retval = target_write_buffer(target,
288                         stm32lx_info->write_algorithm->address,
289                         sizeof(stm32lx_flash_write_code),
290                         (uint8_t*) stm32lx_flash_write_code);
291         if (retval != ERROR_OK)
292         {
293                 target_free_working_area(target, stm32lx_info->write_algorithm);
294                 return retval;
295         }
296
297         // Allocate half pages memory
298         while (target_alloc_working_area_try(target, buffer_size, &source)
299                         != ERROR_OK)
300         {
301                 if (buffer_size > 1024)
302                         buffer_size -= 1024;
303                 else
304                         buffer_size /= 2;
305
306                 if (buffer_size <= 256)
307                 {
308                         /* if we already allocated the writing code, but failed to get a
309                          * buffer, free the algorithm */
310                         if (stm32lx_info->write_algorithm)
311                                 target_free_working_area(target, stm32lx_info->write_algorithm);
312
313                         LOG_WARNING("no large enough working area available, can't do block memory writes");
314                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
315                 }
316         }
317         LOG_DEBUG("allocated working area for data (%" PRIx32 " bytes)", buffer_size);
318
319         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
320         armv7m_info.core_mode = ARMV7M_MODE_ANY;
321         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
322         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
323         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
324         init_reg_param(&reg_params[3], "r3", 32, PARAM_IN_OUT);
325         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);
326
327         // Enable half-page write
328         retval = stm32lx_enable_write_half_page(bank);
329         if (retval != ERROR_OK)
330         {
331
332                 target_free_working_area(target, source);
333                 target_free_working_area(target, stm32lx_info->write_algorithm);
334
335                 destroy_reg_param(&reg_params[0]);
336                 destroy_reg_param(&reg_params[1]);
337                 destroy_reg_param(&reg_params[2]);
338                 destroy_reg_param(&reg_params[3]);
339
340                 return retval;
341         }
342
343         // Loop while there are bytes to write
344         while (count > 0)
345         {
346                 uint32_t this_count;
347                 this_count = (count > buffer_size) ? buffer_size : count;
348
349                 // Write the next half pages
350                 retval = target_write_buffer(target, source->address, this_count,
351                                 buffer);
352                 if (retval != ERROR_OK)
353                         break;
354
355                 // 4: Store useful information in the registers
356                 // the destination address of the copy (R0)
357                 buf_set_u32(reg_params[0].value, 0, 32, address);
358                 // The source address of the copy (R1)
359                 buf_set_u32(reg_params[1].value, 0, 32, source->address);
360                 // The length of the copy (R2)
361                 buf_set_u32(reg_params[2].value, 0, 32, this_count / 4);
362
363                 // 5: Execute the bunch of code
364                 retval = target_run_algorithm(target, 0, NULL, sizeof(reg_params)
365                                 / sizeof(*reg_params), reg_params,
366                                 stm32lx_info->write_algorithm->address, 0, 20000, &armv7m_info);
367                 if (retval != ERROR_OK)
368                         break;
369
370                 // 6: Wait while busy
371                 retval = stm32lx_wait_until_bsy_clear(bank);
372                 if (retval != ERROR_OK)
373                         break;
374
375                 buffer += this_count;
376                 address += this_count;
377                 count -= this_count;
378         }
379
380         if (retval == ERROR_OK)
381                 retval = stm32lx_lock_program_memory(bank);
382
383         target_free_working_area(target, source);
384         target_free_working_area(target, stm32lx_info->write_algorithm);
385
386         destroy_reg_param(&reg_params[0]);
387         destroy_reg_param(&reg_params[1]);
388         destroy_reg_param(&reg_params[2]);
389         destroy_reg_param(&reg_params[3]);
390
391         return retval;
392 }
393 static int stm32lx_write(struct flash_bank *bank, uint8_t *buffer,
394                 uint32_t offset, uint32_t count)
395 {
396         struct target *target = bank->target;
397
398         uint32_t halfpages_number;
399         uint32_t words_remaining;
400         uint32_t bytes_remaining;
401         uint32_t address = bank->base + offset;
402         uint32_t bytes_written = 0;
403         int retval;
404
405         if (bank->target->state != TARGET_HALTED)
406         {
407                 LOG_ERROR("Target not halted");
408                 return ERROR_TARGET_NOT_HALTED;
409         }
410
411         if (offset & 0x1)
412         {
413                 LOG_ERROR("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
414                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
415         }
416
417         // Check if there are some full half pages
418         if (((offset % 128) == 0) && (count >= 128))
419         {
420                 halfpages_number = count / 128;
421                 words_remaining = (count - 128 * halfpages_number) / 4;
422                 bytes_remaining = (count & 0x3);
423         }
424         else
425         {
426                 halfpages_number = 0;
427                 words_remaining = (count / 4);
428                 bytes_remaining = (count & 0x3);
429         }
430
431         if (halfpages_number)
432         {
433                 retval = stm32lx_write_half_pages(bank, buffer, offset, 128
434                                 * halfpages_number);
435                 if (retval != ERROR_OK)
436                         return ERROR_FAIL;
437         }
438
439         bytes_written = 128 * halfpages_number;
440
441         retval = stm32lx_unlock_program_memory(bank);
442         if (retval != ERROR_OK)
443                 return retval;
444
445         while (words_remaining > 0)
446         {
447                 uint32_t value;
448                 uint8_t* p = buffer + bytes_written;
449
450                 // Prepare the word, Little endian conversion
451                 value = p[0] + (p[1] << 8) + (p[2] << 16) + (p[3] << 24);
452
453                 retval = target_write_u32(target, address, value);
454                 if (retval != ERROR_OK)
455                         return retval;
456
457                 bytes_written += 4;
458                 words_remaining--;
459                 address += 4;
460
461                 retval = stm32lx_wait_until_bsy_clear(bank);
462                 if (retval != ERROR_OK)
463                         return retval;
464         }
465
466         if (bytes_remaining)
467         {
468                 uint32_t value = 0;
469                 for (int i = 0; i < 4; i++)
470                 {
471                         if (bytes_remaining)
472                         {
473                                 value += (buffer[i] << (8 * i));
474                                 bytes_remaining--;
475                         }
476                 }
477
478                 retval = target_write_u32(target, address, value);
479                 if (retval != ERROR_OK)
480                         return retval;
481
482                 retval = stm32lx_wait_until_bsy_clear(bank);
483                 if (retval != ERROR_OK)
484                         return retval;
485         }
486
487         retval = stm32lx_lock_program_memory(bank);
488         if (retval != ERROR_OK)
489                 return retval;
490
491         return ERROR_OK;
492 }
493
494 static int stm32lx_probe(struct flash_bank *bank)
495 {
496         struct target *target = bank->target;
497         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
498         int i;
499         uint16_t flash_size;
500         uint32_t device_id;
501         uint32_t reg32;
502
503         stm32lx_info->probed = 0;
504
505         /* read stm32 device id register */
506         int retval = target_read_u32(target, DBGMCU_IDCODE, &device_id);
507         if (retval != ERROR_OK)
508                 return retval;
509
510         LOG_DEBUG("device id = 0x%08" PRIx32 "", device_id);
511
512         if ((device_id & 0x7ff) != 0x416)
513         {
514                 LOG_WARNING("Cannot identify target as a STM32L family.");
515                 return ERROR_FAIL;
516         }
517
518         // Read the RDP byte and check if it is 0xAA
519         uint8_t rdp;
520         retval = target_read_u32(target, FLASH_OBR, &reg32);
521         if (retval != ERROR_OK)
522                 return retval;
523         rdp = reg32 & 0xFF;
524         if (rdp != 0xAA)
525         {
526                 /*
527                  * Unlocking the option byte is done by unlocking the PECR, then
528                  * by writing the 2 option byte keys to OPTKEYR
529                  */
530
531                 /* To unlock the PECR write the 2 PEKEY to the PEKEYR register */
532                 retval = target_write_u32(target, FLASH_PEKEYR, PEKEY1);
533                 if (retval != ERROR_OK)
534                         return retval;
535
536                 retval = target_write_u32(target, FLASH_PEKEYR, PEKEY2);
537                 if (retval != ERROR_OK)
538                         return retval;
539
540                 /* Make sure it worked */
541                 retval = target_read_u32(target, FLASH_PECR, &reg32);
542                 if (retval != ERROR_OK)
543                         return retval;
544
545                 if (reg32 & FLASH_PECR__PELOCK)
546                         return ERROR_FLASH_OPERATION_FAILED;
547
548                 retval = target_write_u32(target, FLASH_OPTKEYR, OPTKEY1);
549                 if (retval != ERROR_OK)
550                         return retval;
551                 retval = target_write_u32(target, FLASH_OPTKEYR, OPTKEY2);
552                 if (retval != ERROR_OK)
553                         return retval;
554
555                 retval = target_read_u32(target, FLASH_PECR, &reg32);
556                 if (retval != ERROR_OK)
557                         return retval;
558
559                 if (reg32 & FLASH_PECR__OPTLOCK)
560                 {
561                         LOG_ERROR("OPTLOCK is not cleared");
562                         return ERROR_FLASH_OPERATION_FAILED;
563                 }
564
565                 // Then, write RDP to 0x00 to set level 1
566                 reg32 = ((~0xAA) << 16) | (0xAA);
567                 retval = target_write_u32(target, OB_RDP, reg32);
568                 if (retval != ERROR_OK)
569                         return retval;
570
571                 // Set Automatic update of the option byte, by setting OBL_LAUNCH in FLASH_PECR
572                 reg32 = FLASH_PECR__OBL_LAUNCH;
573                 retval = target_write_u32(target, FLASH_PECR, reg32);
574                 if (retval != ERROR_OK)
575                         return retval;
576         }
577
578         /* get flash size from target. */
579         retval = target_read_u16(target, F_SIZE, &flash_size);
580         if (retval != ERROR_OK)
581                 return retval;
582
583         /* check for valid flash size */
584         if (flash_size == 0xffff)
585         {
586                 /* number of sectors incorrect on revA */
587                 LOG_ERROR("STM32 flash size failed, probe inaccurate");
588                 return ERROR_FAIL;
589         }
590
591         /* STM32L - we have 32 sectors, 16 pages per sector -> 512 pages
592          * 16 pages for a protection area */
593
594         /* calculate numbers of sectors (4kB per sector) */
595         int num_sectors = (flash_size * 1024) / FLASH_SECTOR_SIZE;
596         LOG_INFO("flash size = %dkbytes", flash_size);
597
598         if (bank->sectors)
599         {
600                 free(bank->sectors);
601                 bank->sectors = NULL;
602         }
603
604         bank->base = FLASH_BANK0_ADDRESS;
605         bank->size = flash_size * 1024;
606         bank->num_sectors = num_sectors;
607         bank->sectors = malloc(sizeof(struct flash_sector) * num_sectors);
608         if (bank->sectors == NULL)
609         {
610                 LOG_ERROR("failed to allocate bank sectors");
611                 return ERROR_FAIL;
612         }
613
614         for (i = 0; i < num_sectors; i++)
615         {
616                 bank->sectors[i].offset = i * FLASH_SECTOR_SIZE;
617                 bank->sectors[i].size = FLASH_SECTOR_SIZE;
618                 bank->sectors[i].is_erased = -1;
619                 bank->sectors[i].is_protected = 1;
620         }
621
622         stm32lx_info->probed = 1;
623
624         return ERROR_OK;
625 }
626
627 static int stm32lx_auto_probe(struct flash_bank *bank)
628 {
629         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
630
631         if (stm32lx_info->probed)
632         {
633                 return ERROR_OK;
634         }
635
636         return stm32lx_probe(bank);
637 }
638
639 static int stm32lx_erase_check(struct flash_bank *bank)
640 {
641         struct target *target = bank->target;
642         const int buffer_size = 4096;
643         int i;
644         uint32_t nBytes;
645         int retval = ERROR_OK;
646
647         if (bank->target->state != TARGET_HALTED)
648         {
649                 LOG_ERROR("Target not halted");
650                 return ERROR_TARGET_NOT_HALTED;
651         }
652
653         uint8_t *buffer = malloc(buffer_size);
654         if (buffer == NULL)
655         {
656                 LOG_ERROR("failed to allocate read buffer");
657                 return ERROR_FAIL;
658         }
659
660         for (i = 0; i < bank->num_sectors; i++)
661         {
662                 uint32_t j;
663                 bank->sectors[i].is_erased = 1;
664
665                 // Loop chunk by chunk over the sector
666                 for (j = 0; j < bank->sectors[i].size; j += buffer_size)
667                 {
668                         uint32_t chunk;
669                         chunk = buffer_size;
670                         if (chunk > (j - bank->sectors[i].size))
671                         {
672                                 chunk = (j - bank->sectors[i].size);
673                         }
674
675                         retval = target_read_memory(target, bank->base
676                                         + bank->sectors[i].offset + j, 4, chunk / 4, buffer);
677                         if (retval != ERROR_OK)
678                                 break;
679
680                         for (nBytes = 0; nBytes < chunk; nBytes++)
681                         {
682                                 if (buffer[nBytes] != 0x00)
683                                 {
684                                         bank->sectors[i].is_erased = 0;
685                                         break;
686                                 }
687                         }
688                 }
689                 if (retval != ERROR_OK)
690                 {
691                         break;
692                 }
693         }
694         free(buffer);
695
696         return retval;
697 }
698 static int stm32lx_get_info(struct flash_bank *bank, char *buf, int buf_size)
699 {
700         // This method must return a string displaying information about the bank
701
702         struct target *target = bank->target;
703         uint32_t device_id;
704         int printed;
705
706         /* read stm32 device id register */
707         int retval = target_read_u32(target, DBGMCU_IDCODE, &device_id);
708         if (retval != ERROR_OK)
709                 return retval;
710
711         if ((device_id & 0x7ff) == 0x416)
712         {
713                 printed = snprintf(buf, buf_size, "stm32lx - Rev: ");
714                 buf += printed;
715                 buf_size -= printed;
716
717                 switch (device_id >> 16)
718                 {
719                         case 0x1000:
720                                 snprintf(buf, buf_size, "A");
721                                 break;
722
723                         case 0x1008:
724                                 snprintf(buf, buf_size, "Y");
725                                 break;
726                         default:
727                                 snprintf(buf, buf_size, "unknown");
728                                 break;
729                 }
730         }
731         else
732         {
733                 snprintf(buf, buf_size, "Cannot identify target as a stm32lx");
734                 return ERROR_FAIL;
735         }
736
737         return ERROR_OK;
738 }
739
740 static const struct command_registration stm32lx_exec_command_handlers[] =
741 {
742         COMMAND_REGISTRATION_DONE
743 };
744
745 static const struct command_registration stm32lx_command_handlers[] =
746 {
747         {
748                 .name = "stm32lx",
749                 .mode = COMMAND_ANY,
750                 .help = "stm32lx flash command group",
751                 .chain = stm32lx_exec_command_handlers,
752         },
753         COMMAND_REGISTRATION_DONE
754 };
755
756 struct flash_driver stm32lx_flash =
757 {
758                 .name = "stm32lx",
759                 .commands = stm32lx_command_handlers,
760                 .flash_bank_command = stm32lx_flash_bank_command,
761                 .erase = stm32lx_erase,
762                 .protect = stm32lx_protect,
763                 .write = stm32lx_write,
764                 .read = default_flash_read,
765                 .probe = stm32lx_probe,
766                 .auto_probe = stm32lx_auto_probe,
767                 .erase_check = stm32lx_erase_check,
768                 .protect_check = stm32lx_protect_check,
769                 .info = stm32lx_get_info,
770 };
771
772 // Static methods implementation
773
774 static int stm32lx_unlock_program_memory(struct flash_bank *bank)
775 {
776         struct target *target = bank->target;
777         int retval;
778         uint32_t reg32;
779
780         /*
781          * Unlocking the program memory is done by unlocking the PECR,
782          * then by writing the 2 PRGKEY to the PRGKEYR register
783          */
784
785         /* To unlock the PECR write the 2 PEKEY to the PEKEYR register */
786         retval = target_write_u32(target, FLASH_PEKEYR, PEKEY1);
787         if (retval != ERROR_OK)
788                 return retval;
789
790         retval = target_write_u32(target, FLASH_PEKEYR, PEKEY2);
791         if (retval != ERROR_OK)
792                 return retval;
793
794         /* Make sure it worked */
795         retval = target_read_u32(target, FLASH_PECR, &reg32);
796         if (retval != ERROR_OK)
797                 return retval;
798
799         if (reg32 & FLASH_PECR__PELOCK)
800         {
801                 LOG_ERROR("PELOCK is not cleared :(");
802                 return ERROR_FLASH_OPERATION_FAILED;
803         }
804
805         retval = target_write_u32(target, FLASH_PRGKEYR, PRGKEY1);
806         if (retval != ERROR_OK)
807                 return retval;
808         retval = target_write_u32(target, FLASH_PRGKEYR, PRGKEY2);
809         if (retval != ERROR_OK)
810                 return retval;
811
812         /* Make sure it worked */
813         retval = target_read_u32(target, FLASH_PECR, &reg32);
814         if (retval != ERROR_OK)
815                 return retval;
816
817         if (reg32 & FLASH_PECR__PRGLOCK)
818         {
819                 LOG_ERROR("PRGLOCK is not cleared :(");
820                 return ERROR_FLASH_OPERATION_FAILED;
821         }
822         return ERROR_OK;
823 }
824
825 static int stm32lx_enable_write_half_page(struct flash_bank *bank)
826 {
827         struct target *target = bank->target;
828         int retval;
829         uint32_t reg32;
830
831         /**
832          * Unlock the program memory, then set the FPRG bit in the PECR register.
833          */
834         retval = stm32lx_unlock_program_memory(bank);
835         if (retval != ERROR_OK)
836                 return retval;
837
838         retval = target_read_u32(target, FLASH_PECR, &reg32);
839         if (retval != ERROR_OK)
840                 return retval;
841
842         reg32 |= FLASH_PECR__FPRG;
843         retval = target_write_u32(target, FLASH_PECR, reg32);
844         if (retval != ERROR_OK)
845                 return retval;
846
847         retval = target_read_u32(target, FLASH_PECR, &reg32);
848         if (retval != ERROR_OK)
849                 return retval;
850
851         reg32 |= FLASH_PECR__PROG;
852         retval = target_write_u32(target, FLASH_PECR, reg32);
853
854         return retval;
855 }
856
857 static int stm32lx_lock_program_memory(struct flash_bank *bank)
858 {
859         struct target *target = bank->target;
860         int retval;
861         uint32_t reg32;
862
863         /* To lock the program memory, simply set the lock bit and lock PECR */
864
865         retval = target_read_u32(target, FLASH_PECR, &reg32);
866         if (retval != ERROR_OK)
867                 return retval;
868
869         reg32 |= FLASH_PECR__PRGLOCK;
870         retval = target_write_u32(target, FLASH_PECR, reg32);
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__PELOCK;
879         retval = target_write_u32(target, FLASH_PECR, reg32);
880         if (retval != ERROR_OK)
881                 return retval;
882
883         return ERROR_OK;
884 }
885
886 static int stm32lx_erase_sector(struct flash_bank *bank, int sector)
887 {
888         struct target *target = bank->target;
889         int retval;
890         uint32_t reg32;
891
892         /*
893          * To erase a sector (i.e. FLASH_PAGES_PER_SECTOR pages),
894          * first unlock the memory, loop over the pages of this sector
895          * and write 0x0 to its first word.
896          */
897
898         retval = stm32lx_unlock_program_memory(bank);
899         if (retval != ERROR_OK)
900                 return retval;
901
902         for (int page = 0; page < FLASH_PAGES_PER_SECTOR; page++)
903         {
904                 reg32 = FLASH_PECR__PROG | FLASH_PECR__ERASE;
905                 retval = target_write_u32(target, FLASH_PECR, reg32);
906                 if (retval != ERROR_OK)
907                         return retval;
908
909                 retval = stm32lx_wait_until_bsy_clear(bank);
910                 if (retval != ERROR_OK)
911                         return retval;
912
913                 uint32_t addr = bank->base + bank->sectors[sector].offset + (page
914                                 * FLASH_PAGE_SIZE);
915                 retval = target_write_u32(target, addr, 0x0);
916                 if (retval != ERROR_OK)
917                         return retval;
918
919                 retval = stm32lx_wait_until_bsy_clear(bank);
920                 if (retval != ERROR_OK)
921                         return retval;
922         }
923
924         retval = stm32lx_lock_program_memory(bank);
925         if (retval != ERROR_OK)
926                 return retval;
927
928         return ERROR_OK;
929 }
930
931 static int stm32lx_wait_until_bsy_clear(struct flash_bank *bank)
932 {
933         struct target *target = bank->target;
934         uint32_t status;
935         int retval = ERROR_OK;
936         int timeout = 100;
937
938         /* wait for busy to clear */
939         for (;;)
940         {
941                 retval = target_read_u32(target, FLASH_SR, &status);
942                 if (retval != ERROR_OK)
943                         return retval;
944
945                 if ((status & FLASH_SR__BSY) == 0)
946                 {
947                         break;
948                 }
949                 if (timeout-- <= 0)
950                 {
951                         LOG_ERROR("timed out waiting for flash");
952                         return ERROR_FAIL;
953                 }
954                 alive_sleep(1);
955         }
956
957         if (status & FLASH_SR__WRPERR)
958         {
959                 LOG_ERROR("access denied / write protected");
960                 retval = ERROR_FAIL;
961         }
962
963         if (status & FLASH_SR__PGAERR)
964         {
965                 LOG_ERROR("invalid program address");
966                 retval = ERROR_FAIL;
967         }
968
969         return retval;
970 }