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