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