]> git.sur5r.net Git - openocd/blob - src/flash/nor/stm32l4x.c
flash/nor/stm32: Eliminate working area leak
[openocd] / src / flash / nor / stm32l4x.c
1 /***************************************************************************
2  *   Copyright (C) 2015 by Uwe Bonnes                                      *
3  *   bon@elektron.ikp.physik.tu-darmstadt.de                               *
4  *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
17  ***************************************************************************/
18
19 #ifdef HAVE_CONFIG_H
20 #include "config.h"
21 #endif
22
23 #include "imp.h"
24 #include <helper/binarybuffer.h>
25 #include <target/algorithm.h>
26 #include <target/armv7m.h>
27
28 /* STM32L4xxx series for reference.
29  *
30  * RM0351 (STM32L4x5/STM32L4x6)
31  * http://www.st.com/resource/en/reference_manual/dm00083560.pdf
32  *
33  * RM0394 (STM32L43x/44x/45x/46x)
34  * http://www.st.com/resource/en/reference_manual/dm00151940.pdf
35  *
36  * STM32L476RG Datasheet (for erase timing)
37  * http://www.st.com/resource/en/datasheet/stm32l476rg.pdf
38  *
39  * The RM0351 devices have normally two banks, but on 512 and 256 kiB devices
40  * an option byte is available to map all sectors to the first bank.
41  * Both STM32 banks are treated as one OpenOCD bank, as other STM32 devices
42  * handlers do!
43  *
44  * RM0394 devices have a single bank only.
45  *
46  */
47
48 /* Erase time can be as high as 25ms, 10x this and assume it's toast... */
49
50 #define FLASH_ERASE_TIMEOUT 250
51
52 #define STM32_FLASH_BASE    0x40022000
53 #define STM32_FLASH_ACR     0x40022000
54 #define STM32_FLASH_KEYR    0x40022008
55 #define STM32_FLASH_OPTKEYR 0x4002200c
56 #define STM32_FLASH_SR      0x40022010
57 #define STM32_FLASH_CR      0x40022014
58 #define STM32_FLASH_OPTR    0x40022020
59 #define STM32_FLASH_WRP1AR  0x4002202c
60 #define STM32_FLASH_WRP2AR  0x40022030
61 #define STM32_FLASH_WRP1BR  0x4002204c
62 #define STM32_FLASH_WRP2BR  0x40022050
63
64 /* FLASH_CR register bits */
65
66 #define FLASH_PG       (1 << 0)
67 #define FLASH_PER      (1 << 1)
68 #define FLASH_MER1     (1 << 2)
69 #define FLASH_PAGE_SHIFT     3
70 #define FLASH_CR_BKER  (1 << 11)
71 #define FLASH_MER2     (1 << 15)
72 #define FLASH_STRT     (1 << 16)
73 #define FLASH_EOPIE    (1 << 24)
74 #define FLASH_ERRIE    (1 << 25)
75 #define FLASH_OPTLOCK  (1 << 30)
76 #define FLASH_LOCK     (1 << 31)
77
78 /* FLASH_SR register bits */
79
80 #define FLASH_BSY      (1 << 16)
81 /* Fast programming not used => related errors not used*/
82 #define FLASH_PGSERR   (1 << 7) /* Programming sequence error */
83 #define FLASH_SIZERR   (1 << 6) /* Size  error */
84 #define FLASH_PGAERR   (1 << 5) /* Programming alignment error */
85 #define FLASH_WRPERR   (1 << 4) /* Write protection error */
86 #define FLASH_PROGERR  (1 << 3) /* Programming error */
87 #define FLASH_OPERR    (1 << 1) /* Operation error */
88 #define FLASH_EOP      (1 << 0) /* End of operation */
89
90 #define FLASH_ERROR (FLASH_PGSERR | FLASH_PGSERR | FLASH_PGAERR | FLASH_WRPERR | FLASH_OPERR)
91
92 /* STM32_FLASH_OBR bit definitions (reading) */
93
94 #define OPT_DUALBANK   21       /* dual flash bank only */
95
96 /* register unlock keys */
97
98 #define KEY1           0x45670123
99 #define KEY2           0xCDEF89AB
100
101 /* option register unlock key */
102 #define OPTKEY1        0x08192A3B
103 #define OPTKEY2        0x4C5D6E7F
104
105
106 /* other registers */
107 #define DBGMCU_IDCODE   0xE0042000
108 #define FLASH_SIZE_REG  0x1FFF75E0
109
110 struct stm32l4_options {
111         uint8_t RDP;
112         uint16_t bank_b_start;
113         uint8_t user_options;
114         uint8_t wpr1a_start;
115         uint8_t wpr1a_end;
116         uint8_t wpr1b_start;
117         uint8_t wpr1b_end;
118         uint8_t wpr2a_start;
119         uint8_t wpr2a_end;
120         uint8_t wpr2b_start;
121         uint8_t wpr2b_end;
122     /* Fixme: Handle PCROP */
123 };
124
125 struct stm32l4_flash_bank {
126         struct stm32l4_options option_bytes;
127         int probed;
128 };
129
130 /* flash bank stm32l4x <base> <size> 0 0 <target#>
131  */
132 FLASH_BANK_COMMAND_HANDLER(stm32l4_flash_bank_command)
133 {
134         struct stm32l4_flash_bank *stm32l4_info;
135
136         if (CMD_ARGC < 6)
137                 return ERROR_COMMAND_SYNTAX_ERROR;
138
139         stm32l4_info = malloc(sizeof(struct stm32l4_flash_bank));
140         if (!stm32l4_info)
141                 return ERROR_FAIL; /* Checkme: What better error to use?*/
142         bank->driver_priv = stm32l4_info;
143
144         stm32l4_info->probed = 0;
145
146         return ERROR_OK;
147 }
148
149 static inline int stm32l4_get_flash_reg(struct flash_bank *bank, uint32_t reg)
150 {
151         return reg;
152 }
153
154 static inline int stm32l4_get_flash_status(struct flash_bank *bank, uint32_t *status)
155 {
156         struct target *target = bank->target;
157         return target_read_u32(
158                 target, stm32l4_get_flash_reg(bank, STM32_FLASH_SR), status);
159 }
160
161 static int stm32l4_wait_status_busy(struct flash_bank *bank, int timeout)
162 {
163         struct target *target = bank->target;
164         uint32_t status;
165         int retval = ERROR_OK;
166
167         /* wait for busy to clear */
168         for (;;) {
169                 retval = stm32l4_get_flash_status(bank, &status);
170                 if (retval != ERROR_OK)
171                         return retval;
172                 LOG_DEBUG("status: 0x%" PRIx32 "", status);
173                 if ((status & FLASH_BSY) == 0)
174                         break;
175                 if (timeout-- <= 0) {
176                         LOG_ERROR("timed out waiting for flash");
177                         return ERROR_FAIL;
178                 }
179                 alive_sleep(1);
180         }
181
182
183         if (status & FLASH_WRPERR) {
184                 LOG_ERROR("stm32x device protected");
185                 retval = ERROR_FAIL;
186         }
187
188         /* Clear but report errors */
189         if (status & FLASH_ERROR) {
190                 if (retval == ERROR_OK)
191                         retval = ERROR_FAIL;
192                 /* If this operation fails, we ignore it and report the original
193                  * retval
194                  */
195                 target_write_u32(target, stm32l4_get_flash_reg(bank, STM32_FLASH_SR),
196                                 status & FLASH_ERROR);
197         }
198         return retval;
199 }
200
201 static int stm32l4_unlock_reg(struct target *target)
202 {
203         uint32_t ctrl;
204
205         /* first check if not already unlocked
206          * otherwise writing on STM32_FLASH_KEYR will fail
207          */
208         int retval = target_read_u32(target, STM32_FLASH_CR, &ctrl);
209         if (retval != ERROR_OK)
210                 return retval;
211
212         if ((ctrl & FLASH_LOCK) == 0)
213                 return ERROR_OK;
214
215         /* unlock flash registers */
216         retval = target_write_u32(target, STM32_FLASH_KEYR, KEY1);
217         if (retval != ERROR_OK)
218                 return retval;
219
220         retval = target_write_u32(target, STM32_FLASH_KEYR, KEY2);
221         if (retval != ERROR_OK)
222                 return retval;
223
224         retval = target_read_u32(target, STM32_FLASH_CR, &ctrl);
225         if (retval != ERROR_OK)
226                 return retval;
227
228         if (ctrl & FLASH_LOCK) {
229                 LOG_ERROR("flash not unlocked STM32_FLASH_CR: %" PRIx32, ctrl);
230                 return ERROR_TARGET_FAILURE;
231         }
232
233         return ERROR_OK;
234 }
235
236 static int stm32l4_unlock_option_reg(struct target *target)
237 {
238         uint32_t ctrl;
239
240         int retval = target_read_u32(target, STM32_FLASH_CR, &ctrl);
241         if (retval != ERROR_OK)
242                 return retval;
243
244         if ((ctrl & FLASH_OPTLOCK) == 0)
245                 return ERROR_OK;
246
247         /* unlock option registers */
248         retval = target_write_u32(target, STM32_FLASH_OPTKEYR, OPTKEY1);
249         if (retval != ERROR_OK)
250                 return retval;
251
252         retval = target_write_u32(target, STM32_FLASH_OPTKEYR, OPTKEY2);
253         if (retval != ERROR_OK)
254                 return retval;
255
256         retval = target_read_u32(target, STM32_FLASH_CR, &ctrl);
257         if (retval != ERROR_OK)
258                 return retval;
259
260         if (ctrl & FLASH_OPTLOCK) {
261                 LOG_ERROR("options not unlocked STM32_FLASH_CR: %" PRIx32, ctrl);
262                 return ERROR_TARGET_FAILURE;
263         }
264
265         return ERROR_OK;
266 }
267
268 static int stm32l4_read_options(struct flash_bank *bank)
269 {
270         uint32_t optiondata;
271         struct stm32l4_flash_bank *stm32l4_info = NULL;
272         struct target *target = bank->target;
273
274         stm32l4_info = bank->driver_priv;
275
276         /* read current option bytes */
277         int retval = target_read_u32(target, STM32_FLASH_OPTR, &optiondata);
278         if (retval != ERROR_OK)
279                 return retval;
280
281         stm32l4_info->option_bytes.user_options = (optiondata >> 8) & 0x3ffff;
282         stm32l4_info->option_bytes.RDP = optiondata & 0xff;
283
284         retval = target_read_u32(target, STM32_FLASH_WRP1AR, &optiondata);
285         if (retval != ERROR_OK)
286                 return retval;
287         stm32l4_info->option_bytes.wpr1a_start =  optiondata         & 0xff;
288         stm32l4_info->option_bytes.wpr1a_end   = (optiondata >> 16)  & 0xff;
289
290         retval = target_read_u32(target, STM32_FLASH_WRP2AR, &optiondata);
291         if (retval != ERROR_OK)
292                 return retval;
293         stm32l4_info->option_bytes.wpr2a_start =  optiondata         & 0xff;
294         stm32l4_info->option_bytes.wpr2a_end   = (optiondata >> 16)  & 0xff;
295
296         retval = target_read_u32(target, STM32_FLASH_WRP1BR, &optiondata);
297         if (retval != ERROR_OK)
298                 return retval;
299         stm32l4_info->option_bytes.wpr1b_start =  optiondata         & 0xff;
300         stm32l4_info->option_bytes.wpr1b_end   = (optiondata >> 16)  & 0xff;
301
302         retval = target_read_u32(target, STM32_FLASH_WRP2BR, &optiondata);
303         if (retval != ERROR_OK)
304                 return retval;
305         stm32l4_info->option_bytes.wpr2b_start =  optiondata         & 0xff;
306         stm32l4_info->option_bytes.wpr2b_end   = (optiondata >> 16)  & 0xff;
307
308         if (stm32l4_info->option_bytes.RDP != 0xAA)
309                 LOG_INFO("Device Security Bit Set");
310
311         return ERROR_OK;
312 }
313
314 static int stm32l4_write_options(struct flash_bank *bank)
315 {
316         struct stm32l4_flash_bank *stm32l4_info = NULL;
317         struct target *target = bank->target;
318         uint32_t optiondata;
319
320         stm32l4_info = bank->driver_priv;
321
322         (void) optiondata;
323         (void) stm32l4_info;
324
325         int retval = stm32l4_unlock_option_reg(target);
326         if (retval != ERROR_OK)
327                 return retval;
328         /* FIXME: Implement Option writing!*/
329         return ERROR_OK;
330 }
331
332 static int stm32l4_protect_check(struct flash_bank *bank)
333 {
334         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
335
336         /* read write protection settings */
337         int retval = stm32l4_read_options(bank);
338         if (retval != ERROR_OK) {
339                 LOG_DEBUG("unable to read option bytes");
340                 return retval;
341         }
342
343         for (int i = 0; i < bank->num_sectors; i++) {
344                 if (i < stm32l4_info->option_bytes.bank_b_start) {
345                         if (((i >= stm32l4_info->option_bytes.wpr1a_start) &&
346                                  (i <= stm32l4_info->option_bytes.wpr1a_end)) ||
347                                 ((i >= stm32l4_info->option_bytes.wpr2a_start) &&
348                                  (i <= stm32l4_info->option_bytes.wpr2a_end)))
349                                 bank->sectors[i].is_protected = 1;
350                         else
351                                 bank->sectors[i].is_protected = 0;
352                 } else {
353                         uint8_t snb;
354                         snb = i - stm32l4_info->option_bytes.bank_b_start + 256;
355                         if (((snb >= stm32l4_info->option_bytes.wpr1b_start) &&
356                                  (snb <= stm32l4_info->option_bytes.wpr1b_end)) ||
357                                 ((snb >= stm32l4_info->option_bytes.wpr2b_start) &&
358                                  (snb <= stm32l4_info->option_bytes.wpr2b_end)))
359                                 bank->sectors[i].is_protected = 1;
360                         else
361                                 bank->sectors[i].is_protected = 0;
362                 }
363         }
364         return ERROR_OK;
365 }
366
367 static int stm32l4_erase(struct flash_bank *bank, int first, int last)
368 {
369         struct target *target = bank->target;
370         int i;
371
372         assert(first < bank->num_sectors);
373         assert(last < bank->num_sectors);
374
375         if (bank->target->state != TARGET_HALTED) {
376                 LOG_ERROR("Target not halted");
377                 return ERROR_TARGET_NOT_HALTED;
378         }
379
380         int retval;
381         retval = stm32l4_unlock_reg(target);
382         if (retval != ERROR_OK)
383                 return retval;
384
385         /*
386         Sector Erase
387         To erase a sector, follow the procedure below:
388         1. Check that no Flash memory operation is ongoing by
389        checking the BSY bit in the FLASH_SR register
390         2. Set the PER bit and select the page and bank
391            you wish to erase  in the FLASH_CR register
392         3. Set the STRT bit in the FLASH_CR register
393         4. Wait for the BSY bit to be cleared
394          */
395         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
396
397         for (i = first; i <= last; i++) {
398                 uint32_t erase_flags;
399                 erase_flags = FLASH_PER | FLASH_STRT;
400
401                 if  (i >= stm32l4_info->option_bytes.bank_b_start) {
402                         uint8_t snb;
403                         snb = (i - stm32l4_info->option_bytes.bank_b_start) + 256;
404                         erase_flags |= snb << FLASH_PAGE_SHIFT | FLASH_CR_BKER;
405                 } else
406                         erase_flags |= i << FLASH_PAGE_SHIFT;
407                 retval = target_write_u32(target,
408                                 stm32l4_get_flash_reg(bank, STM32_FLASH_CR), erase_flags);
409                 if (retval != ERROR_OK)
410                         return retval;
411
412                 retval = stm32l4_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
413                 if (retval != ERROR_OK)
414                         return retval;
415
416                 bank->sectors[i].is_erased = 1;
417         }
418
419         retval = target_write_u32(
420                 target, stm32l4_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
421         if (retval != ERROR_OK)
422                 return retval;
423
424         return ERROR_OK;
425 }
426
427 static int stm32l4_protect(struct flash_bank *bank, int set, int first, int last)
428 {
429         struct target *target = bank->target;
430         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
431
432         if (target->state != TARGET_HALTED) {
433                 LOG_ERROR("Target not halted");
434                 return ERROR_TARGET_NOT_HALTED;
435         }
436
437         /* read protection settings */
438         int retval = stm32l4_read_options(bank);
439         if (retval != ERROR_OK) {
440                 LOG_DEBUG("unable to read option bytes");
441                 return retval;
442         }
443
444         (void)stm32l4_info;
445         /* FIXME: Write First and last in a valid WRPxx_start/end combo*/
446         retval = stm32l4_write_options(bank);
447         if (retval != ERROR_OK)
448                 return retval;
449
450         return ERROR_OK;
451 }
452
453 /* Count is in halfwords */
454 static int stm32l4_write_block(struct flash_bank *bank, const uint8_t *buffer,
455                 uint32_t offset, uint32_t count)
456 {
457         struct target *target = bank->target;
458         uint32_t buffer_size = 16384;
459         struct working_area *write_algorithm;
460         struct working_area *source;
461         uint32_t address = bank->base + offset;
462         struct reg_param reg_params[5];
463         struct armv7m_algorithm armv7m_info;
464         int retval = ERROR_OK;
465
466         static const uint8_t stm32l4_flash_write_code[] = {
467 #include "../../../contrib/loaders/flash/stm32/stm32l4x.inc"
468         };
469
470         if (target_alloc_working_area(target, sizeof(stm32l4_flash_write_code),
471                         &write_algorithm) != ERROR_OK) {
472                 LOG_WARNING("no working area available, can't do block memory writes");
473                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
474         }
475
476         retval = target_write_buffer(target, write_algorithm->address,
477                         sizeof(stm32l4_flash_write_code),
478                         stm32l4_flash_write_code);
479         if (retval != ERROR_OK) {
480                 target_free_working_area(target, write_algorithm);
481                 return retval;
482         }
483
484         /* memory buffer */
485         while (target_alloc_working_area_try(target, buffer_size, &source) !=
486                    ERROR_OK) {
487                 buffer_size /= 2;
488                 if (buffer_size <= 256) {
489                         /* we already allocated the writing code, but failed to get a
490                          * buffer, free the algorithm */
491                         target_free_working_area(target, write_algorithm);
492
493                         LOG_WARNING("no large enough working area available, can't do block memory writes");
494                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
495                 }
496         }
497
498         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
499         armv7m_info.core_mode = ARM_MODE_THREAD;
500
501         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT); /* buffer start, status (out) */
502         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);    /* buffer end */
503         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);    /* target address */
504         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);    /* count (double word-64bit) */
505         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);    /* flash base */
506
507         buf_set_u32(reg_params[0].value, 0, 32, source->address);
508         buf_set_u32(reg_params[1].value, 0, 32, source->address + source->size);
509         buf_set_u32(reg_params[2].value, 0, 32, address);
510         buf_set_u32(reg_params[3].value, 0, 32, count / 4);
511         buf_set_u32(reg_params[4].value, 0, 32, STM32_FLASH_BASE);
512
513         retval = target_run_flash_async_algorithm(target, buffer, count, 2,
514                         0, NULL,
515                         5, reg_params,
516                         source->address, source->size,
517                         write_algorithm->address, 0,
518                         &armv7m_info);
519
520         if (retval == ERROR_FLASH_OPERATION_FAILED) {
521                 LOG_ERROR("error executing stm32l4 flash write algorithm");
522
523                 uint32_t error = buf_get_u32(reg_params[0].value, 0, 32) & FLASH_ERROR;
524
525                 if (error & FLASH_WRPERR)
526                         LOG_ERROR("flash memory write protected");
527
528                 if (error != 0) {
529                         LOG_ERROR("flash write failed = %08" PRIx32, error);
530                         /* Clear but report errors */
531                         target_write_u32(target, STM32_FLASH_SR, error);
532                         retval = ERROR_FAIL;
533                 }
534         }
535
536         target_free_working_area(target, source);
537         target_free_working_area(target, write_algorithm);
538
539         destroy_reg_param(&reg_params[0]);
540         destroy_reg_param(&reg_params[1]);
541         destroy_reg_param(&reg_params[2]);
542         destroy_reg_param(&reg_params[3]);
543         destroy_reg_param(&reg_params[4]);
544
545         return retval;
546 }
547
548 static int stm32l4_write(struct flash_bank *bank, const uint8_t *buffer,
549                 uint32_t offset, uint32_t count)
550 {
551         struct target *target = bank->target;
552         int retval;
553
554         if (bank->target->state != TARGET_HALTED) {
555                 LOG_ERROR("Target not halted");
556                 return ERROR_TARGET_NOT_HALTED;
557         }
558
559         if (offset & 0x7) {
560                 LOG_WARNING("offset 0x%" PRIx32 " breaks required 8-byte alignment",
561                                         offset);
562                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
563         }
564
565         if (count & 0x7) {
566                 LOG_WARNING("Padding %d bytes to keep 8-byte write size",
567                                         count & 7);
568                 count = (count + 7) & ~7;
569                 /* This pads the write chunk with random bytes by overrunning the
570                  * write buffer. Padding with the erased pattern 0xff is purely
571                  * cosmetical, as 8-byte flash words are ECC secured and the first
572                  * write will program the ECC bits. A second write would need
573                  * to reprogramm these ECC bits.
574                  * But this can only be done after erase!
575                  */
576         }
577
578         retval = stm32l4_unlock_reg(target);
579         if (retval != ERROR_OK)
580                 return retval;
581
582         /* Only full double words (8-byte) can be programmed*/
583         retval = stm32l4_write_block(bank, buffer, offset, count / 2);
584         if (retval != ERROR_OK) {
585                 LOG_WARNING("block write failed");
586                 return retval;
587                 }
588
589         LOG_WARNING("block write succeeded");
590         return target_write_u32(target, STM32_FLASH_CR, FLASH_LOCK);
591 }
592
593 static int stm32l4_probe(struct flash_bank *bank)
594 {
595         struct target *target = bank->target;
596         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
597         int i;
598         uint16_t flash_size_in_kb = 0xffff;
599         uint16_t max_flash_size_in_kb;
600         uint32_t device_id;
601         uint32_t options;
602         uint32_t base_address = 0x08000000;
603
604         stm32l4_info->probed = 0;
605
606         /* read stm32 device id register */
607         int retval = target_read_u32(target, DBGMCU_IDCODE, &device_id);
608         if (retval != ERROR_OK)
609                 return retval;
610         LOG_INFO("device id = 0x%08" PRIx32 "", device_id);
611
612         /* set max flash size depending on family */
613         switch (device_id & 0xfff) {
614         case 0x461:
615         case 0x415:
616                 max_flash_size_in_kb = 1024;
617                 break;
618         case 0x462:
619                 max_flash_size_in_kb = 512;
620                 break;
621         case 0x435:
622                 max_flash_size_in_kb = 256;
623                 break;
624         default:
625                 LOG_WARNING("Cannot identify target as a STM32L4 family.");
626                 return ERROR_FAIL;
627         }
628
629         /* get flash size from target. */
630         retval = target_read_u16(target, FLASH_SIZE_REG, &flash_size_in_kb);
631
632         /* failed reading flash size or flash size invalid (early silicon),
633          * default to max target family */
634         if (retval != ERROR_OK || flash_size_in_kb == 0xffff || flash_size_in_kb == 0) {
635                 LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming %dk flash",
636                         max_flash_size_in_kb);
637                 flash_size_in_kb = max_flash_size_in_kb;
638         }
639
640         LOG_INFO("flash size = %dkbytes", flash_size_in_kb);
641
642         /* did we assign flash size? */
643         assert(flash_size_in_kb != 0xffff);
644
645         /* get options to for DUAL BANK. */
646         retval = target_read_u32(target, STM32_FLASH_OPTR, &options);
647
648         if (retval != ERROR_OK)
649                 return retval;
650
651         /* only devices with < 1024 kiB may be set to single bank dual banks */
652         if ((flash_size_in_kb == 1024) || !(options & OPT_DUALBANK))
653                 stm32l4_info->option_bytes.bank_b_start = 256;
654         else
655                 stm32l4_info->option_bytes.bank_b_start = flash_size_in_kb << 9;
656
657         /* did we assign flash size? */
658         assert((flash_size_in_kb != 0xffff) && flash_size_in_kb);
659
660         /* calculate numbers of pages */
661         int num_pages = flash_size_in_kb / 2;
662
663         /* check that calculation result makes sense */
664         assert(num_pages > 0);
665
666         if (bank->sectors) {
667                 free(bank->sectors);
668                 bank->sectors = NULL;
669         }
670
671         bank->base = base_address;
672         bank->size = num_pages * (1 << 11);
673         bank->num_sectors = num_pages;
674         bank->sectors = malloc(sizeof(struct flash_sector) * num_pages);
675         if (!bank->sectors)
676                 return ERROR_FAIL; /* Checkme: What better error to use?*/
677
678         for (i = 0; i < num_pages; i++) {
679                 bank->sectors[i].offset = i << 11;
680                 bank->sectors[i].size = 1 << 11;
681                 bank->sectors[i].is_erased = -1;
682                 bank->sectors[i].is_protected = 1;
683         }
684
685         stm32l4_info->probed = 1;
686
687         return ERROR_OK;
688 }
689
690 static int stm32l4_auto_probe(struct flash_bank *bank)
691 {
692         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
693         if (stm32l4_info->probed)
694                 return ERROR_OK;
695         return stm32l4_probe(bank);
696 }
697
698 static int get_stm32l4_info(struct flash_bank *bank, char *buf, int buf_size)
699 {
700         struct target *target = bank->target;
701         uint32_t dbgmcu_idcode;
702
703         /* read stm32 device id register */
704         int retval = target_read_u32(target, DBGMCU_IDCODE, &dbgmcu_idcode);
705         if (retval != ERROR_OK)
706                 return retval;
707
708         uint16_t device_id = dbgmcu_idcode & 0xfff;
709         uint8_t rev_id = dbgmcu_idcode >> 28;
710         uint8_t rev_minor = 0;
711         int i;
712
713         for (i = 16; i < 28; i++) {
714                 if (dbgmcu_idcode & (1 << i))
715                         rev_minor++;
716                 else
717                         break;
718         }
719
720         const char *device_str;
721
722         switch (device_id) {
723         case 0x461:
724                 device_str = "STM32L496/4A6";
725                 break;
726
727         case 0x415:
728                 device_str = "STM32L475/476/486";
729                 break;
730
731         case 0x462:
732                 device_str = "STM32L45x/46x";
733                 break;
734
735         case 0x435:
736                 device_str = "STM32L43x/44x";
737                 break;
738
739         default:
740                 snprintf(buf, buf_size, "Cannot identify target as a STM32L4\n");
741                 return ERROR_FAIL;
742         }
743
744         snprintf(buf, buf_size, "%s - Rev: %1d.%02d",
745                          device_str, rev_id, rev_minor);
746
747         return ERROR_OK;
748 }
749
750 COMMAND_HANDLER(stm32l4_handle_lock_command)
751 {
752         struct target *target = NULL;
753         struct stm32l4_flash_bank *stm32l4_info = NULL;
754
755         if (CMD_ARGC < 1)
756                 return ERROR_COMMAND_SYNTAX_ERROR;
757
758         struct flash_bank *bank;
759         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
760         if (ERROR_OK != retval)
761                 return retval;
762
763         stm32l4_info = bank->driver_priv;
764         target = bank->target;
765
766         if (target->state != TARGET_HALTED) {
767                 LOG_ERROR("Target not halted");
768                 return ERROR_TARGET_NOT_HALTED;
769         }
770
771         if (stm32l4_read_options(bank) != ERROR_OK) {
772                 command_print(CMD_CTX, "%s failed to read options",
773                                           bank->driver->name);
774                 return ERROR_OK;
775         }
776
777         /* set readout protection */
778         stm32l4_info->option_bytes.RDP = 0;
779
780         if (stm32l4_write_options(bank) != ERROR_OK) {
781                 command_print(CMD_CTX, "%s failed to lock device", bank->driver->name);
782                 return ERROR_OK;
783         }
784
785         command_print(CMD_CTX, "%s locked", bank->driver->name);
786
787         return ERROR_OK;
788 }
789
790 COMMAND_HANDLER(stm32l4_handle_unlock_command)
791 {
792         struct target *target = NULL;
793         struct stm32l4_flash_bank *stm32l4_info = NULL;
794
795         if (CMD_ARGC < 1)
796                 return ERROR_COMMAND_SYNTAX_ERROR;
797
798         struct flash_bank *bank;
799         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
800         if (ERROR_OK != retval)
801                 return retval;
802
803         stm32l4_info = bank->driver_priv;
804         target = bank->target;
805
806         if (target->state != TARGET_HALTED) {
807                 LOG_ERROR("Target not halted");
808                 return ERROR_TARGET_NOT_HALTED;
809         }
810
811         if (stm32l4_read_options(bank) != ERROR_OK) {
812                 command_print(CMD_CTX, "%s failed to read options", bank->driver->name);
813                 return ERROR_OK;
814         }
815
816         /* clear readout protection and complementary option bytes
817          * this will also force a device unlock if set */
818         stm32l4_info->option_bytes.RDP = 0xAA;
819
820         if (stm32l4_write_options(bank) != ERROR_OK) {
821                 command_print(CMD_CTX, "%s failed to unlock device",
822                                           bank->driver->name);
823                 return ERROR_OK;
824         }
825
826         command_print(CMD_CTX, "%s unlocked.\n"
827                         "INFO: a reset or power cycle is required "
828                         "for the new settings to take effect.", bank->driver->name);
829
830         return ERROR_OK;
831 }
832
833 static int stm32l4_mass_erase(struct flash_bank *bank, uint32_t action)
834 {
835         int retval;
836         struct target *target = bank->target;
837
838         if (target->state != TARGET_HALTED) {
839                 LOG_ERROR("Target not halted");
840                 return ERROR_TARGET_NOT_HALTED;
841         }
842
843         retval = stm32l4_unlock_reg(target);
844         if (retval != ERROR_OK)
845                 return retval;
846
847         /* mass erase flash memory */
848         retval = target_write_u32(
849                 target, stm32l4_get_flash_reg(bank, STM32_FLASH_CR), action);
850         if (retval != ERROR_OK)
851                 return retval;
852         retval = target_write_u32(
853                 target, stm32l4_get_flash_reg(bank, STM32_FLASH_CR),
854                 action | FLASH_STRT);
855         if (retval != ERROR_OK)
856                 return retval;
857
858         retval = stm32l4_wait_status_busy(bank,  FLASH_ERASE_TIMEOUT);
859         if (retval != ERROR_OK)
860                 return retval;
861
862         retval = target_write_u32(
863                 target, stm32l4_get_flash_reg(bank, STM32_FLASH_CR), FLASH_LOCK);
864         if (retval != ERROR_OK)
865                 return retval;
866
867         return ERROR_OK;
868 }
869
870 COMMAND_HANDLER(stm32l4_handle_mass_erase_command)
871 {
872         int i;
873         uint32_t action;
874
875         if (CMD_ARGC < 1) {
876                 command_print(CMD_CTX, "stm32x mass_erase <STM32L4 bank>");
877                 return ERROR_COMMAND_SYNTAX_ERROR;
878         }
879
880         struct flash_bank *bank;
881         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
882         if (ERROR_OK != retval)
883                 return retval;
884
885         action =  FLASH_MER1 |  FLASH_MER2;
886         retval = stm32l4_mass_erase(bank, action);
887         if (retval == ERROR_OK) {
888                 /* set all sectors as erased */
889                 for (i = 0; i < bank->num_sectors; i++)
890                         bank->sectors[i].is_erased = 1;
891
892                 command_print(CMD_CTX, "stm32x mass erase complete");
893         } else {
894                 command_print(CMD_CTX, "stm32x mass erase failed");
895         }
896
897         return retval;
898 }
899
900 static const struct command_registration stm32l4_exec_command_handlers[] = {
901         {
902                 .name = "lock",
903                 .handler = stm32l4_handle_lock_command,
904                 .mode = COMMAND_EXEC,
905                 .usage = "bank_id",
906                 .help = "Lock entire flash device.",
907         },
908         {
909                 .name = "unlock",
910                 .handler = stm32l4_handle_unlock_command,
911                 .mode = COMMAND_EXEC,
912                 .usage = "bank_id",
913                 .help = "Unlock entire protected flash device.",
914         },
915         {
916                 .name = "mass_erase",
917                 .handler = stm32l4_handle_mass_erase_command,
918                 .mode = COMMAND_EXEC,
919                 .usage = "bank_id",
920                 .help = "Erase entire flash device.",
921         },
922         COMMAND_REGISTRATION_DONE
923 };
924
925 static const struct command_registration stm32l4_command_handlers[] = {
926         {
927                 .name = "stm32l4x",
928                 .mode = COMMAND_ANY,
929                 .help = "stm32l4x flash command group",
930                 .usage = "",
931                 .chain = stm32l4_exec_command_handlers,
932         },
933         COMMAND_REGISTRATION_DONE
934 };
935
936 struct flash_driver stm32l4x_flash = {
937         .name = "stm32l4x",
938         .commands = stm32l4_command_handlers,
939         .flash_bank_command = stm32l4_flash_bank_command,
940         .erase = stm32l4_erase,
941         .protect = stm32l4_protect,
942         .write = stm32l4_write,
943         .read = default_flash_read,
944         .probe = stm32l4_probe,
945         .auto_probe = stm32l4_auto_probe,
946         .erase_check = default_flash_blank_check,
947         .protect_check = stm32l4_protect_check,
948         .info = get_stm32l4_info,
949         .free_driver_priv = default_flash_free_driver_priv,
950 };