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