ca8a3b81de6f5fcc889feb9e5e4e519dc7c2e0d2
[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  *   Copyright (C) 2019 by Tarek Bochkati for STMicroelectronics           *
6  *   tarek.bouchkati@gmail.com                                             *
7  *                                                                         *
8  *   This program is free software; you can redistribute it and/or modify  *
9  *   it under the terms of the GNU General Public License as published by  *
10  *   the Free Software Foundation; either version 2 of the License, or     *
11  *   (at your option) any later version.                                   *
12  *                                                                         *
13  *   This program is distributed in the hope that it will be useful,       *
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
16  *   GNU General Public License for more details.                          *
17  *                                                                         *
18  *   You should have received a copy of the GNU General Public License     *
19  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
20  ***************************************************************************/
21
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25
26 #include "imp.h"
27 #include <helper/binarybuffer.h>
28 #include <target/algorithm.h>
29 #include <target/armv7m.h>
30 #include "bits.h"
31 #include "stm32l4x.h"
32
33 /* STM32L4xxx series for reference.
34  *
35  * RM0351 (STM32L4x5/STM32L4x6)
36  * http://www.st.com/resource/en/reference_manual/dm00083560.pdf
37  *
38  * RM0394 (STM32L43x/44x/45x/46x)
39  * http://www.st.com/resource/en/reference_manual/dm00151940.pdf
40  *
41  * RM0432 (STM32L4R/4Sxx)
42  * http://www.st.com/resource/en/reference_manual/dm00310109.pdf
43  *
44  * STM32L476RG Datasheet (for erase timing)
45  * http://www.st.com/resource/en/datasheet/stm32l476rg.pdf
46  *
47  * The RM0351 devices have normally two banks, but on 512 and 256 kiB devices
48  * an option byte is available to map all sectors to the first bank.
49  * Both STM32 banks are treated as one OpenOCD bank, as other STM32 devices
50  * handlers do!
51  *
52  * RM0394 devices have a single bank only.
53  *
54  * RM0432 devices have single and dual bank operating modes.
55  *  - for STM32L4R/Sxx the FLASH size is 2Mbyte or 1Mbyte.
56  *  - for STM32L4P/Q5x the FLASH size is 1Mbyte or 512Kbyte.
57  * Bank page (sector) size is 4Kbyte (dual mode) or 8Kbyte (single mode).
58  *
59  * Bank mode is controlled by two different bits in option bytes register.
60  *  - for STM32L4R/Sxx
61  *    In 2M FLASH devices bit 22 (DBANK) controls Dual Bank mode.
62  *    In 1M FLASH devices bit 21 (DB1M) controls Dual Bank mode.
63  *  - for STM32L4P5/Q5x
64  *    In 1M FLASH devices bit 22 (DBANK) controls Dual Bank mode.
65  *    In 512K FLASH devices bit 21 (DB512K) controls Dual Bank mode.
66  *
67  */
68
69 /* STM32WBxxx series for reference.
70  *
71  * RM0434 (STM32WB55)
72  * http://www.st.com/resource/en/reference_manual/dm00318631.pdf
73  *
74  * RM0471 (STM32WB50)
75  * http://www.st.com/resource/en/reference_manual/dm00622834.pdf
76  */
77
78 /* STM32WLxxx series for reference.
79  *
80  * RM0461 (STM32WLEx)
81  * http://www.st.com/resource/en/reference_manual/dm00530369.pdf
82  */
83
84 /* STM32G0xxx series for reference.
85  *
86  * RM0444 (STM32G0x1)
87  * http://www.st.com/resource/en/reference_manual/dm00371828.pdf
88  *
89  * RM0454 (STM32G0x0)
90  * http://www.st.com/resource/en/reference_manual/dm00463896.pdf
91  */
92
93 /* STM32G4xxx series for reference.
94  *
95  * RM0440 (STM32G43x/44x/47x/48x/49x/4Ax)
96  * http://www.st.com/resource/en/reference_manual/dm00355726.pdf
97  *
98  * Cat. 2 devices have single bank only, page size is 2kByte.
99  *
100  * Cat. 3 devices have single and dual bank operating modes,
101  * Page size is 2kByte (dual mode) or 4kByte (single mode).
102  *
103  * Bank mode is controlled by bit 22 (DBANK) in option bytes register.
104  * Both banks are treated as a single OpenOCD bank.
105  *
106  * Cat. 4 devices have single bank only, page size is 2kByte.
107  */
108
109 /* Erase time can be as high as 25ms, 10x this and assume it's toast... */
110
111 #define FLASH_ERASE_TIMEOUT 250
112
113 enum stm32l4_flash_reg_index {
114         STM32_FLASH_ACR_INDEX,
115         STM32_FLASH_KEYR_INDEX,
116         STM32_FLASH_OPTKEYR_INDEX,
117         STM32_FLASH_SR_INDEX,
118         STM32_FLASH_CR_INDEX,
119         STM32_FLASH_OPTR_INDEX,
120         STM32_FLASH_WRP1AR_INDEX,
121         STM32_FLASH_WRP1BR_INDEX,
122         STM32_FLASH_WRP2AR_INDEX,
123         STM32_FLASH_WRP2BR_INDEX,
124         STM32_FLASH_REG_INDEX_NUM,
125 };
126
127 static const uint32_t stm32l4_flash_regs[STM32_FLASH_REG_INDEX_NUM] = {
128         [STM32_FLASH_ACR_INDEX]      = 0x000,
129         [STM32_FLASH_KEYR_INDEX]     = 0x008,
130         [STM32_FLASH_OPTKEYR_INDEX]  = 0x00C,
131         [STM32_FLASH_SR_INDEX]       = 0x010,
132         [STM32_FLASH_CR_INDEX]       = 0x014,
133         [STM32_FLASH_OPTR_INDEX]     = 0x020,
134         [STM32_FLASH_WRP1AR_INDEX]   = 0x02C,
135         [STM32_FLASH_WRP1BR_INDEX]   = 0x030,
136         [STM32_FLASH_WRP2AR_INDEX]   = 0x04C,
137         [STM32_FLASH_WRP2BR_INDEX]   = 0x050,
138 };
139
140 struct stm32l4_rev {
141         const uint16_t rev;
142         const char *str;
143 };
144
145 struct stm32l4_part_info {
146         uint16_t id;
147         const char *device_str;
148         const struct stm32l4_rev *revs;
149         const size_t num_revs;
150         const uint16_t max_flash_size_kb;
151         const bool has_dual_bank;
152         const uint32_t flash_regs_base;
153         const uint32_t *default_flash_regs;
154         const uint32_t fsize_addr;
155 };
156
157 struct stm32l4_flash_bank {
158         bool probed;
159         uint32_t idcode;
160         unsigned int bank1_sectors;
161         bool dual_bank_mode;
162         int hole_sectors;
163         uint32_t user_bank_size;
164         uint32_t wrpxxr_mask;
165         const struct stm32l4_part_info *part_info;
166         const uint32_t *flash_regs;
167 };
168
169 /* human readable list of families this drivers supports (sorted alphabetically) */
170 static const char *device_families = "STM32G0/G4/L4/L4+/WB/WL";
171
172 static const struct stm32l4_rev stm32_415_revs[] = {
173         { 0x1000, "1" }, { 0x1001, "2" }, { 0x1003, "3" }, { 0x1007, "4" }
174 };
175
176 static const struct stm32l4_rev stm32_435_revs[] = {
177         { 0x1000, "A" }, { 0x1001, "Z" }, { 0x2001, "Y" },
178 };
179
180 static const struct stm32l4_rev stm32_460_revs[] = {
181         { 0x1000, "A/Z" } /* A and Z, no typo in RM! */, { 0x2000, "B" },
182 };
183
184 static const struct stm32l4_rev stm32_461_revs[] = {
185         { 0x1000, "A" }, { 0x2000, "B" },
186 };
187
188 static const struct stm32l4_rev stm32_462_revs[] = {
189         { 0x1000, "A" }, { 0x1001, "Z" }, { 0x2001, "Y" },
190 };
191
192 static const struct stm32l4_rev stm32_464_revs[] = {
193         { 0x1000, "A" }, { 0x1001, "Z" }, { 0x2001, "Y" },
194 };
195
196 static const struct stm32l4_rev stm32_466_revs[] = {
197         { 0x1000, "A" }, { 0x1001, "Z" }, { 0x2000, "B" },
198 };
199
200 static const struct stm32l4_rev stm32_468_revs[] = {
201         { 0x1000, "A" }, { 0x2000, "B" }, { 0x2001, "Z" },
202 };
203
204 static const struct stm32l4_rev stm32_469_revs[] = {
205         { 0x1000, "A" }, { 0x2000, "B" }, { 0x2001, "Z" },
206 };
207
208 static const struct stm32l4_rev stm32_470_revs[] = {
209         { 0x1000, "A" }, { 0x1001, "Z" }, { 0x1003, "Y" }, { 0x100F, "W" },
210 };
211
212 static const struct stm32l4_rev stm32_471_revs[] = {
213         { 0x1001, "Z" },
214 };
215
216 static const struct stm32l4_rev stm32_479_revs[] = {
217         { 0x1000, "A" },
218 };
219
220 static const struct stm32l4_rev stm32_495_revs[] = {
221         { 0x2001, "2.1" },
222 };
223
224 static const struct stm32l4_rev stm32_496_revs[] = {
225         { 0x1000, "A" },
226 };
227
228 static const struct stm32l4_rev stm32_497_revs[] = {
229         { 0x1000, "1.0" },
230 };
231
232 static const struct stm32l4_part_info stm32l4_parts[] = {
233         {
234           .id                    = 0x415,
235           .revs                  = stm32_415_revs,
236           .num_revs              = ARRAY_SIZE(stm32_415_revs),
237           .device_str            = "STM32L47/L48xx",
238           .max_flash_size_kb     = 1024,
239           .has_dual_bank         = true,
240           .flash_regs_base       = 0x40022000,
241           .default_flash_regs    = stm32l4_flash_regs,
242           .fsize_addr            = 0x1FFF75E0,
243         },
244         {
245           .id                    = 0x435,
246           .revs                  = stm32_435_revs,
247           .num_revs              = ARRAY_SIZE(stm32_435_revs),
248           .device_str            = "STM32L43/L44xx",
249           .max_flash_size_kb     = 256,
250           .has_dual_bank         = false,
251           .flash_regs_base       = 0x40022000,
252           .default_flash_regs    = stm32l4_flash_regs,
253           .fsize_addr            = 0x1FFF75E0,
254         },
255         {
256           .id                    = 0x460,
257           .revs                  = stm32_460_revs,
258           .num_revs              = ARRAY_SIZE(stm32_460_revs),
259           .device_str            = "STM32G07/G08xx",
260           .max_flash_size_kb     = 128,
261           .has_dual_bank         = false,
262           .flash_regs_base       = 0x40022000,
263           .default_flash_regs    = stm32l4_flash_regs,
264           .fsize_addr            = 0x1FFF75E0,
265         },
266         {
267           .id                    = 0x461,
268           .revs                  = stm32_461_revs,
269           .num_revs              = ARRAY_SIZE(stm32_461_revs),
270           .device_str            = "STM32L49/L4Axx",
271           .max_flash_size_kb     = 1024,
272           .has_dual_bank         = true,
273           .flash_regs_base       = 0x40022000,
274           .default_flash_regs    = stm32l4_flash_regs,
275           .fsize_addr            = 0x1FFF75E0,
276         },
277         {
278           .id                    = 0x462,
279           .revs                  = stm32_462_revs,
280           .num_revs              = ARRAY_SIZE(stm32_462_revs),
281           .device_str            = "STM32L45/L46xx",
282           .max_flash_size_kb     = 512,
283           .has_dual_bank         = false,
284           .flash_regs_base       = 0x40022000,
285           .default_flash_regs    = stm32l4_flash_regs,
286           .fsize_addr            = 0x1FFF75E0,
287         },
288         {
289           .id                    = 0x464,
290           .revs                  = stm32_464_revs,
291           .num_revs              = ARRAY_SIZE(stm32_464_revs),
292           .device_str            = "STM32L41/L42xx",
293           .max_flash_size_kb     = 128,
294           .has_dual_bank         = false,
295           .flash_regs_base       = 0x40022000,
296           .default_flash_regs    = stm32l4_flash_regs,
297           .fsize_addr            = 0x1FFF75E0,
298         },
299         {
300           .id                    = 0x466,
301           .revs                  = stm32_466_revs,
302           .num_revs              = ARRAY_SIZE(stm32_466_revs),
303           .device_str            = "STM32G03/G04xx",
304           .max_flash_size_kb     = 64,
305           .has_dual_bank         = false,
306           .flash_regs_base       = 0x40022000,
307           .default_flash_regs    = stm32l4_flash_regs,
308           .fsize_addr            = 0x1FFF75E0,
309         },
310         {
311           .id                    = 0x468,
312           .revs                  = stm32_468_revs,
313           .num_revs              = ARRAY_SIZE(stm32_468_revs),
314           .device_str            = "STM32G43/G44xx",
315           .max_flash_size_kb     = 128,
316           .has_dual_bank         = false,
317           .flash_regs_base       = 0x40022000,
318           .default_flash_regs    = stm32l4_flash_regs,
319           .fsize_addr            = 0x1FFF75E0,
320         },
321         {
322           .id                    = 0x469,
323           .revs                  = stm32_469_revs,
324           .num_revs              = ARRAY_SIZE(stm32_469_revs),
325           .device_str            = "STM32G47/G48xx",
326           .max_flash_size_kb     = 512,
327           .has_dual_bank         = true,
328           .flash_regs_base       = 0x40022000,
329           .default_flash_regs    = stm32l4_flash_regs,
330           .fsize_addr            = 0x1FFF75E0,
331         },
332         {
333           .id                    = 0x470,
334           .revs                  = stm32_470_revs,
335           .num_revs              = ARRAY_SIZE(stm32_470_revs),
336           .device_str            = "STM32L4R/L4Sxx",
337           .max_flash_size_kb     = 2048,
338           .has_dual_bank         = true,
339           .flash_regs_base       = 0x40022000,
340           .default_flash_regs    = stm32l4_flash_regs,
341           .fsize_addr            = 0x1FFF75E0,
342         },
343         {
344           .id                    = 0x471,
345           .revs                  = stm32_471_revs,
346           .num_revs              = ARRAY_SIZE(stm32_471_revs),
347           .device_str            = "STM32L4P5/L4Q5x",
348           .max_flash_size_kb     = 1024,
349           .has_dual_bank         = true,
350           .flash_regs_base       = 0x40022000,
351           .default_flash_regs    = stm32l4_flash_regs,
352           .fsize_addr            = 0x1FFF75E0,
353         },
354         {
355           .id                    = 0x479,
356           .revs                  = stm32_479_revs,
357           .num_revs              = ARRAY_SIZE(stm32_479_revs),
358           .device_str            = "STM32G49/G4Axx",
359           .max_flash_size_kb     = 512,
360           .has_dual_bank         = false,
361           .flash_regs_base       = 0x40022000,
362           .default_flash_regs    = stm32l4_flash_regs,
363           .fsize_addr            = 0x1FFF75E0,
364         },
365         {
366           .id                    = 0x495,
367           .revs                  = stm32_495_revs,
368           .num_revs              = ARRAY_SIZE(stm32_495_revs),
369           .device_str            = "STM32WB5x",
370           .max_flash_size_kb     = 1024,
371           .has_dual_bank         = false,
372           .flash_regs_base       = 0x58004000,
373           .default_flash_regs    = stm32l4_flash_regs,
374           .fsize_addr            = 0x1FFF75E0,
375         },
376         {
377           .id                    = 0x496,
378           .revs                  = stm32_496_revs,
379           .num_revs              = ARRAY_SIZE(stm32_496_revs),
380           .device_str            = "STM32WB3x",
381           .max_flash_size_kb     = 512,
382           .has_dual_bank         = false,
383           .flash_regs_base       = 0x58004000,
384           .default_flash_regs    = stm32l4_flash_regs,
385           .fsize_addr            = 0x1FFF75E0,
386         },
387         {
388           .id                    = 0x497,
389           .revs                  = stm32_497_revs,
390           .num_revs              = ARRAY_SIZE(stm32_497_revs),
391           .device_str            = "STM32WLEx",
392           .max_flash_size_kb     = 256,
393           .has_dual_bank         = false,
394           .flash_regs_base       = 0x58004000,
395           .default_flash_regs    = stm32l4_flash_regs,
396           .fsize_addr            = 0x1FFF75E0,
397         },
398 };
399
400 /* flash bank stm32l4x <base> <size> 0 0 <target#> */
401 FLASH_BANK_COMMAND_HANDLER(stm32l4_flash_bank_command)
402 {
403         struct stm32l4_flash_bank *stm32l4_info;
404
405         if (CMD_ARGC < 6)
406                 return ERROR_COMMAND_SYNTAX_ERROR;
407
408         stm32l4_info = malloc(sizeof(struct stm32l4_flash_bank));
409         if (!stm32l4_info)
410                 return ERROR_FAIL; /* Checkme: What better error to use?*/
411         bank->driver_priv = stm32l4_info;
412
413         /* The flash write must be aligned to a double word (8-bytes) boundary.
414          * Ask the flash infrastructure to ensure required alignment */
415         bank->write_start_alignment = bank->write_end_alignment = 8;
416
417         stm32l4_info->probed = false;
418         stm32l4_info->user_bank_size = bank->size;
419
420         return ERROR_OK;
421 }
422
423 static inline uint32_t stm32l4_get_flash_reg(struct flash_bank *bank, uint32_t reg_offset)
424 {
425         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
426         return stm32l4_info->part_info->flash_regs_base + reg_offset;
427 }
428
429 static inline uint32_t stm32l4_get_flash_reg_by_index(struct flash_bank *bank,
430         enum stm32l4_flash_reg_index reg_index)
431 {
432         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
433         return stm32l4_get_flash_reg(bank, stm32l4_info->flash_regs[reg_index]);
434 }
435
436 static inline int stm32l4_read_flash_reg(struct flash_bank *bank, uint32_t reg_offset, uint32_t *value)
437 {
438         return target_read_u32(bank->target, stm32l4_get_flash_reg(bank, reg_offset), value);
439 }
440
441 static inline int stm32l4_read_flash_reg_by_index(struct flash_bank *bank,
442         enum stm32l4_flash_reg_index reg_index, uint32_t *value)
443 {
444         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
445         return stm32l4_read_flash_reg(bank, stm32l4_info->flash_regs[reg_index], value);
446 }
447
448 static inline int stm32l4_write_flash_reg(struct flash_bank *bank, uint32_t reg_offset, uint32_t value)
449 {
450         return target_write_u32(bank->target, stm32l4_get_flash_reg(bank, reg_offset), value);
451 }
452
453 static inline int stm32l4_write_flash_reg_by_index(struct flash_bank *bank,
454         enum stm32l4_flash_reg_index reg_index, uint32_t value)
455 {
456         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
457         return stm32l4_write_flash_reg(bank, stm32l4_info->flash_regs[reg_index], value);
458 }
459
460 static int stm32l4_wait_status_busy(struct flash_bank *bank, int timeout)
461 {
462         uint32_t status;
463         int retval = ERROR_OK;
464
465         /* wait for busy to clear */
466         for (;;) {
467                 retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_SR_INDEX, &status);
468                 if (retval != ERROR_OK)
469                         return retval;
470                 LOG_DEBUG("status: 0x%" PRIx32 "", status);
471                 if ((status & FLASH_BSY) == 0)
472                         break;
473                 if (timeout-- <= 0) {
474                         LOG_ERROR("timed out waiting for flash");
475                         return ERROR_FAIL;
476                 }
477                 alive_sleep(1);
478         }
479
480
481         if (status & FLASH_WRPERR) {
482                 LOG_ERROR("stm32x device protected");
483                 retval = ERROR_FAIL;
484         }
485
486         /* Clear but report errors */
487         if (status & FLASH_ERROR) {
488                 if (retval == ERROR_OK)
489                         retval = ERROR_FAIL;
490                 /* If this operation fails, we ignore it and report the original
491                  * retval
492                  */
493                 stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_SR_INDEX, status & FLASH_ERROR);
494         }
495
496         return retval;
497 }
498
499 static int stm32l4_unlock_reg(struct flash_bank *bank)
500 {
501         uint32_t ctrl;
502
503         /* first check if not already unlocked
504          * otherwise writing on STM32_FLASH_KEYR will fail
505          */
506         int retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, &ctrl);
507         if (retval != ERROR_OK)
508                 return retval;
509
510         if ((ctrl & FLASH_LOCK) == 0)
511                 return ERROR_OK;
512
513         /* unlock flash registers */
514         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_KEYR_INDEX, KEY1);
515         if (retval != ERROR_OK)
516                 return retval;
517
518         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_KEYR_INDEX, KEY2);
519         if (retval != ERROR_OK)
520                 return retval;
521
522         retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, &ctrl);
523         if (retval != ERROR_OK)
524                 return retval;
525
526         if (ctrl & FLASH_LOCK) {
527                 LOG_ERROR("flash not unlocked STM32_FLASH_CR: %" PRIx32, ctrl);
528                 return ERROR_TARGET_FAILURE;
529         }
530
531         return ERROR_OK;
532 }
533
534 static int stm32l4_unlock_option_reg(struct flash_bank *bank)
535 {
536         uint32_t ctrl;
537
538         int retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, &ctrl);
539         if (retval != ERROR_OK)
540                 return retval;
541
542         if ((ctrl & FLASH_OPTLOCK) == 0)
543                 return ERROR_OK;
544
545         /* unlock option registers */
546         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_OPTKEYR_INDEX, OPTKEY1);
547         if (retval != ERROR_OK)
548                 return retval;
549
550         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_OPTKEYR_INDEX, OPTKEY2);
551         if (retval != ERROR_OK)
552                 return retval;
553
554         retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, &ctrl);
555         if (retval != ERROR_OK)
556                 return retval;
557
558         if (ctrl & FLASH_OPTLOCK) {
559                 LOG_ERROR("options not unlocked STM32_FLASH_CR: %" PRIx32, ctrl);
560                 return ERROR_TARGET_FAILURE;
561         }
562
563         return ERROR_OK;
564 }
565
566 static int stm32l4_write_option(struct flash_bank *bank, uint32_t reg_offset,
567         uint32_t value, uint32_t mask)
568 {
569         uint32_t optiondata;
570         int retval, retval2;
571
572         retval = stm32l4_read_flash_reg(bank, reg_offset, &optiondata);
573         if (retval != ERROR_OK)
574                 return retval;
575
576         retval = stm32l4_unlock_reg(bank);
577         if (retval != ERROR_OK)
578                 goto err_lock;
579
580         retval = stm32l4_unlock_option_reg(bank);
581         if (retval != ERROR_OK)
582                 goto err_lock;
583
584         optiondata = (optiondata & ~mask) | (value & mask);
585
586         retval = stm32l4_write_flash_reg(bank, reg_offset, optiondata);
587         if (retval != ERROR_OK)
588                 goto err_lock;
589
590         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_OPTSTRT);
591         if (retval != ERROR_OK)
592                 goto err_lock;
593
594         retval = stm32l4_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
595
596 err_lock:
597         retval2 = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_LOCK | FLASH_OPTLOCK);
598
599         if (retval != ERROR_OK)
600                 return retval;
601
602         return retval2;
603 }
604
605 static int stm32l4_protect_check(struct flash_bank *bank)
606 {
607         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
608
609         uint32_t wrp1ar, wrp1br, wrp2ar, wrp2br;
610         stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_WRP1AR_INDEX, &wrp1ar);
611         stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_WRP1BR_INDEX, &wrp1br);
612         if (stm32l4_info->part_info->has_dual_bank) {
613                 stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_WRP2AR_INDEX, &wrp2ar);
614                 stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_WRP2BR_INDEX, &wrp2br);
615         } else {
616                 /* prevent uninitialized errors */
617                 wrp2ar = 0;
618                 wrp2br = 0;
619         }
620
621         const uint8_t wrp1a_start = wrp1ar & stm32l4_info->wrpxxr_mask;
622         const uint8_t wrp1a_end = (wrp1ar >> 16) & stm32l4_info->wrpxxr_mask;
623         const uint8_t wrp1b_start = wrp1br & stm32l4_info->wrpxxr_mask;
624         const uint8_t wrp1b_end = (wrp1br >> 16) & stm32l4_info->wrpxxr_mask;
625         const uint8_t wrp2a_start = wrp2ar & stm32l4_info->wrpxxr_mask;
626         const uint8_t wrp2a_end = (wrp2ar >> 16) & stm32l4_info->wrpxxr_mask;
627         const uint8_t wrp2b_start = wrp2br & stm32l4_info->wrpxxr_mask;
628         const uint8_t wrp2b_end = (wrp2br >> 16) & stm32l4_info->wrpxxr_mask;
629
630         for (unsigned int i = 0; i < bank->num_sectors; i++) {
631                 if (i < stm32l4_info->bank1_sectors) {
632                         if (((i >= wrp1a_start) &&
633                                  (i <= wrp1a_end)) ||
634                                 ((i >= wrp1b_start) &&
635                                  (i <= wrp1b_end)))
636                                 bank->sectors[i].is_protected = 1;
637                         else
638                                 bank->sectors[i].is_protected = 0;
639                 } else {
640                         assert(stm32l4_info->part_info->has_dual_bank == true);
641                         uint8_t snb;
642                         snb = i - stm32l4_info->bank1_sectors;
643                         if (((snb >= wrp2a_start) &&
644                                  (snb <= wrp2a_end)) ||
645                                 ((snb >= wrp2b_start) &&
646                                  (snb <= wrp2b_end)))
647                                 bank->sectors[i].is_protected = 1;
648                         else
649                                 bank->sectors[i].is_protected = 0;
650                 }
651         }
652         return ERROR_OK;
653 }
654
655 static int stm32l4_erase(struct flash_bank *bank, unsigned int first,
656                 unsigned int last)
657 {
658         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
659         int retval, retval2;
660
661         assert((first <= last) && (last < bank->num_sectors));
662
663         if (bank->target->state != TARGET_HALTED) {
664                 LOG_ERROR("Target not halted");
665                 return ERROR_TARGET_NOT_HALTED;
666         }
667
668         retval = stm32l4_unlock_reg(bank);
669         if (retval != ERROR_OK)
670                 goto err_lock;
671
672         /*
673         Sector Erase
674         To erase a sector, follow the procedure below:
675         1. Check that no Flash memory operation is ongoing by
676            checking the BSY bit in the FLASH_SR register
677         2. Set the PER bit and select the page and bank
678            you wish to erase in the FLASH_CR register
679         3. Set the STRT bit in the FLASH_CR register
680         4. Wait for the BSY bit to be cleared
681          */
682
683         for (unsigned int i = first; i <= last; i++) {
684                 uint32_t erase_flags;
685                 erase_flags = FLASH_PER | FLASH_STRT;
686
687                 if (i >= stm32l4_info->bank1_sectors) {
688                         uint8_t snb;
689                         snb = i - stm32l4_info->bank1_sectors;
690                         erase_flags |= snb << FLASH_PAGE_SHIFT | FLASH_CR_BKER;
691                 } else
692                         erase_flags |= i << FLASH_PAGE_SHIFT;
693                 retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, erase_flags);
694                 if (retval != ERROR_OK)
695                         break;
696
697                 retval = stm32l4_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
698                 if (retval != ERROR_OK)
699                         break;
700
701                 bank->sectors[i].is_erased = 1;
702         }
703
704 err_lock:
705         retval2 = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_LOCK);
706
707         if (retval != ERROR_OK)
708                 return retval;
709
710         return retval2;
711 }
712
713 static int stm32l4_protect(struct flash_bank *bank, int set, unsigned int first,
714                 unsigned int last)
715 {
716         struct target *target = bank->target;
717         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
718
719         if (target->state != TARGET_HALTED) {
720                 LOG_ERROR("Target not halted");
721                 return ERROR_TARGET_NOT_HALTED;
722         }
723
724         int ret = ERROR_OK;
725         /* Bank 2 */
726         uint32_t reg_value = 0xFF; /* Default to bank un-protected */
727         if (last >= stm32l4_info->bank1_sectors) {
728                 if (set == 1) {
729                         uint8_t begin = first > stm32l4_info->bank1_sectors ? first : 0x00;
730                         reg_value = ((last & 0xFF) << 16) | begin;
731                 }
732
733                 ret = stm32l4_write_option(bank, stm32l4_info->flash_regs[STM32_FLASH_WRP2AR_INDEX], reg_value, 0xffffffff);
734         }
735         /* Bank 1 */
736         reg_value = 0xFF; /* Default to bank un-protected */
737         if (first < stm32l4_info->bank1_sectors) {
738                 if (set == 1) {
739                         uint8_t end = last >= stm32l4_info->bank1_sectors ? 0xFF : last;
740                         reg_value = (end << 16) | (first & 0xFF);
741                 }
742
743                 ret = stm32l4_write_option(bank, stm32l4_info->flash_regs[STM32_FLASH_WRP1AR_INDEX], reg_value, 0xffffffff);
744         }
745
746         return ret;
747 }
748
749 /* Count is in double-words */
750 static int stm32l4_write_block(struct flash_bank *bank, const uint8_t *buffer,
751         uint32_t offset, uint32_t count)
752 {
753         struct target *target = bank->target;
754         uint32_t buffer_size;
755         struct working_area *write_algorithm;
756         struct working_area *source;
757         uint32_t address = bank->base + offset;
758         struct reg_param reg_params[6];
759         struct armv7m_algorithm armv7m_info;
760         int retval = ERROR_OK;
761
762         static const uint8_t stm32l4_flash_write_code[] = {
763 #include "../../../contrib/loaders/flash/stm32/stm32l4x.inc"
764         };
765
766         if (target_alloc_working_area(target, sizeof(stm32l4_flash_write_code),
767                         &write_algorithm) != ERROR_OK) {
768                 LOG_WARNING("no working area available, can't do block memory writes");
769                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
770         }
771
772         retval = target_write_buffer(target, write_algorithm->address,
773                         sizeof(stm32l4_flash_write_code),
774                         stm32l4_flash_write_code);
775         if (retval != ERROR_OK) {
776                 target_free_working_area(target, write_algorithm);
777                 return retval;
778         }
779
780         /* memory buffer, size *must* be multiple of dword plus one dword for rp and one for wp */
781         buffer_size = target_get_working_area_avail(target) & ~(2 * sizeof(uint32_t) - 1);
782         if (buffer_size < 256) {
783                 LOG_WARNING("large enough working area not available, can't do block memory writes");
784                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
785         } else if (buffer_size > 16384) {
786                 /* probably won't benefit from more than 16k ... */
787                 buffer_size = 16384;
788         }
789
790         if (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) {
791                 LOG_ERROR("allocating working area failed");
792                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
793         }
794
795         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
796         armv7m_info.core_mode = ARM_MODE_THREAD;
797
798         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT); /* buffer start, status (out) */
799         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);    /* buffer end */
800         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);    /* target address */
801         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);    /* count (double word-64bit) */
802         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);    /* flash status register */
803         init_reg_param(&reg_params[5], "r5", 32, PARAM_OUT);    /* flash control register */
804
805         buf_set_u32(reg_params[0].value, 0, 32, source->address);
806         buf_set_u32(reg_params[1].value, 0, 32, source->address + source->size);
807         buf_set_u32(reg_params[2].value, 0, 32, address);
808         buf_set_u32(reg_params[3].value, 0, 32, count);
809         buf_set_u32(reg_params[4].value, 0, 32, stm32l4_get_flash_reg_by_index(bank, STM32_FLASH_SR_INDEX));
810         buf_set_u32(reg_params[5].value, 0, 32, stm32l4_get_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX));
811
812         retval = target_run_flash_async_algorithm(target, buffer, count, 8,
813                         0, NULL,
814                         ARRAY_SIZE(reg_params), reg_params,
815                         source->address, source->size,
816                         write_algorithm->address, 0,
817                         &armv7m_info);
818
819         if (retval == ERROR_FLASH_OPERATION_FAILED) {
820                 LOG_ERROR("error executing stm32l4 flash write algorithm");
821
822                 uint32_t error = buf_get_u32(reg_params[0].value, 0, 32) & FLASH_ERROR;
823
824                 if (error & FLASH_WRPERR)
825                         LOG_ERROR("flash memory write protected");
826
827                 if (error != 0) {
828                         LOG_ERROR("flash write failed = %08" PRIx32, error);
829                         /* Clear but report errors */
830                         stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_SR_INDEX, error);
831                         retval = ERROR_FAIL;
832                 }
833         }
834
835         target_free_working_area(target, source);
836         target_free_working_area(target, write_algorithm);
837
838         destroy_reg_param(&reg_params[0]);
839         destroy_reg_param(&reg_params[1]);
840         destroy_reg_param(&reg_params[2]);
841         destroy_reg_param(&reg_params[3]);
842         destroy_reg_param(&reg_params[4]);
843         destroy_reg_param(&reg_params[5]);
844
845         return retval;
846 }
847
848 static int stm32l4_write(struct flash_bank *bank, const uint8_t *buffer,
849         uint32_t offset, uint32_t count)
850 {
851         int retval = ERROR_OK, retval2;
852
853         if (bank->target->state != TARGET_HALTED) {
854                 LOG_ERROR("Target not halted");
855                 return ERROR_TARGET_NOT_HALTED;
856         }
857
858         /* The flash write must be aligned to a double word (8-bytes) boundary.
859          * The flash infrastructure ensures it, do just a security check */
860         assert(offset % 8 == 0);
861         assert(count % 8 == 0);
862
863         /* STM32G4xxx Cat. 3 devices may have gaps between banks, check whether
864          * data to be written does not go into a gap:
865          * suppose buffer is fully contained in bank from sector 0 to sector
866          * num->sectors - 1 and sectors are ordered according to offset
867          */
868         struct flash_sector *head = &bank->sectors[0];
869         struct flash_sector *tail = &bank->sectors[bank->num_sectors - 1];
870
871         while ((head < tail) && (offset >= (head + 1)->offset)) {
872                 /* buffer does not intersect head nor gap behind head */
873                 head++;
874         }
875
876         while ((head < tail) && (offset + count <= (tail - 1)->offset + (tail - 1)->size)) {
877                 /* buffer does not intersect tail nor gap before tail */
878                 --tail;
879         }
880
881         LOG_DEBUG("data: 0x%08" PRIx32 " - 0x%08" PRIx32 ", sectors: 0x%08" PRIx32 " - 0x%08" PRIx32,
882                 offset, offset + count - 1, head->offset, tail->offset + tail->size - 1);
883
884         /* Now check that there is no gap from head to tail, this should work
885          * even for multiple or non-symmetric gaps
886          */
887         while (head < tail) {
888                 if (head->offset + head->size != (head + 1)->offset) {
889                         LOG_ERROR("write into gap from " TARGET_ADDR_FMT " to " TARGET_ADDR_FMT,
890                                 bank->base + head->offset + head->size,
891                                 bank->base + (head + 1)->offset - 1);
892                         retval = ERROR_FLASH_DST_OUT_OF_BANK;
893                 }
894                 head++;
895         }
896
897         if (retval != ERROR_OK)
898                 return retval;
899
900         retval = stm32l4_unlock_reg(bank);
901         if (retval != ERROR_OK)
902                 goto err_lock;
903
904         retval = stm32l4_write_block(bank, buffer, offset, count / 8);
905
906 err_lock:
907         retval2 = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_LOCK);
908
909         if (retval != ERROR_OK) {
910                 LOG_ERROR("block write failed");
911                 return retval;
912         }
913         return retval2;
914 }
915
916 static int stm32l4_read_idcode(struct flash_bank *bank, uint32_t *id)
917 {
918         int retval;
919
920         /* try stm32l4/l4+/wb/g4 id register first, then stm32g0 id register */
921         retval = target_read_u32(bank->target, DBGMCU_IDCODE_L4_G4, id);
922         if ((retval != ERROR_OK) || ((*id & 0xfff) == 0) || ((*id & 0xfff) == 0xfff)) {
923                 retval = target_read_u32(bank->target, DBGMCU_IDCODE_G0, id);
924                 if ((retval != ERROR_OK) || ((*id & 0xfff) == 0) || ((*id & 0xfff) == 0xfff)) {
925                         LOG_ERROR("can't get device id");
926                         return (retval == ERROR_OK) ? ERROR_FAIL : retval;
927                 }
928         }
929
930         return retval;
931 }
932
933 static int stm32l4_probe(struct flash_bank *bank)
934 {
935         struct target *target = bank->target;
936         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
937         const struct stm32l4_part_info *part_info;
938         uint16_t flash_size_kb = 0xffff;
939         uint32_t device_id;
940         uint32_t options;
941
942         stm32l4_info->probed = false;
943
944         /* read stm32 device id registers */
945         int retval = stm32l4_read_idcode(bank, &stm32l4_info->idcode);
946         if (retval != ERROR_OK)
947                 return retval;
948
949         device_id = stm32l4_info->idcode & 0xFFF;
950
951         for (unsigned int n = 0; n < ARRAY_SIZE(stm32l4_parts); n++) {
952                 if (device_id == stm32l4_parts[n].id)
953                         stm32l4_info->part_info = &stm32l4_parts[n];
954         }
955
956         if (!stm32l4_info->part_info) {
957                 LOG_WARNING("Cannot identify target as an %s family device.", device_families);
958                 return ERROR_FAIL;
959         }
960
961         part_info = stm32l4_info->part_info;
962         stm32l4_info->flash_regs = stm32l4_info->part_info->default_flash_regs;
963
964         char device_info[1024];
965         retval = bank->driver->info(bank, device_info, sizeof(device_info));
966         if (retval != ERROR_OK)
967                 return retval;
968
969         LOG_INFO("device idcode = 0x%08" PRIx32 " (%s)", stm32l4_info->idcode, device_info);
970
971         /* get flash size from target. */
972         retval = target_read_u16(target, part_info->fsize_addr, &flash_size_kb);
973
974         /* failed reading flash size or flash size invalid (early silicon),
975          * default to max target family */
976         if (retval != ERROR_OK || flash_size_kb == 0xffff || flash_size_kb == 0
977                         || flash_size_kb > part_info->max_flash_size_kb) {
978                 LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming %dk flash",
979                         part_info->max_flash_size_kb);
980                 flash_size_kb = part_info->max_flash_size_kb;
981         }
982
983         /* if the user sets the size manually then ignore the probed value
984          * this allows us to work around devices that have a invalid flash size register value */
985         if (stm32l4_info->user_bank_size) {
986                 LOG_WARNING("overriding size register by configured bank size - MAY CAUSE TROUBLE");
987                 flash_size_kb = stm32l4_info->user_bank_size / 1024;
988         }
989
990         LOG_INFO("flash size = %dkbytes", flash_size_kb);
991
992         /* did we assign a flash size? */
993         assert((flash_size_kb != 0xffff) && flash_size_kb);
994
995         /* read flash option register */
996         retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_OPTR_INDEX, &options);
997         if (retval != ERROR_OK)
998                 return retval;
999
1000         stm32l4_info->bank1_sectors = 0;
1001         stm32l4_info->hole_sectors = 0;
1002
1003         int num_pages = 0;
1004         int page_size_kb = 0;
1005
1006         stm32l4_info->dual_bank_mode = false;
1007
1008         switch (device_id) {
1009         case 0x415: /* STM32L47/L48xx */
1010         case 0x461: /* STM32L49/L4Axx */
1011                 /* if flash size is max (1M) the device is always dual bank
1012                  * 0x415: has variants with 512K
1013                  * 0x461: has variants with 512 and 256
1014                  * for these variants:
1015                  *   if DUAL_BANK = 0 -> single bank
1016                  *   else -> dual bank without gap
1017                  * note: the page size is invariant
1018                  */
1019                 page_size_kb = 2;
1020                 num_pages = flash_size_kb / page_size_kb;
1021                 stm32l4_info->bank1_sectors = num_pages;
1022
1023                 /* check DUAL_BANK bit[21] if the flash is less than 1M */
1024                 if (flash_size_kb == 1024 || (options & BIT(21))) {
1025                         stm32l4_info->dual_bank_mode = true;
1026                         stm32l4_info->bank1_sectors = num_pages / 2;
1027                 }
1028                 break;
1029         case 0x435: /* STM32L43/L44xx */
1030         case 0x460: /* STM32G07/G08xx */
1031         case 0x462: /* STM32L45/L46xx */
1032         case 0x464: /* STM32L41/L42xx */
1033         case 0x466: /* STM32G03/G04xx */
1034         case 0x468: /* STM32G43/G44xx */
1035         case 0x479: /* STM32G49/G4Axx */
1036         case 0x497: /* STM32WLEx */
1037                 /* single bank flash */
1038                 page_size_kb = 2;
1039                 num_pages = flash_size_kb / page_size_kb;
1040                 stm32l4_info->bank1_sectors = num_pages;
1041                 break;
1042         case 0x469: /* STM32G47/G48xx */
1043                 /* STM32G47/8 can be single/dual bank:
1044                  *   if DUAL_BANK = 0 -> single bank
1045                  *   else -> dual bank WITH gap
1046                  */
1047                 page_size_kb = 4;
1048                 num_pages = flash_size_kb / page_size_kb;
1049                 stm32l4_info->bank1_sectors = num_pages;
1050                 if (options & BIT(22)) {
1051                         stm32l4_info->dual_bank_mode = true;
1052                         page_size_kb = 2;
1053                         num_pages = flash_size_kb / page_size_kb;
1054                         stm32l4_info->bank1_sectors = num_pages / 2;
1055
1056                         /* for devices with trimmed flash, there is a gap between both banks */
1057                         stm32l4_info->hole_sectors =
1058                                 (part_info->max_flash_size_kb - flash_size_kb) / (2 * page_size_kb);
1059                 }
1060                 break;
1061         case 0x470: /* STM32L4R/L4Sxx */
1062         case 0x471: /* STM32L4P5/L4Q5x */
1063                 /* STM32L4R/S can be single/dual bank:
1064                  *   if size = 2M check DBANK bit(22)
1065                  *   if size = 1M check DB1M bit(21)
1066                  * STM32L4P/Q can be single/dual bank
1067                  *   if size = 1M check DBANK bit(22)
1068                  *   if size = 512K check DB512K bit(21)
1069                  */
1070                 page_size_kb = 8;
1071                 num_pages = flash_size_kb / page_size_kb;
1072                 stm32l4_info->bank1_sectors = num_pages;
1073                 const bool use_dbank_bit = flash_size_kb == part_info->max_flash_size_kb;
1074                 if ((use_dbank_bit && (options & BIT(22))) ||
1075                         (!use_dbank_bit && (options & BIT(21)))) {
1076                         stm32l4_info->dual_bank_mode = true;
1077                         page_size_kb = 4;
1078                         num_pages = flash_size_kb / page_size_kb;
1079                         stm32l4_info->bank1_sectors = num_pages / 2;
1080                 }
1081                 break;
1082         case 0x495: /* STM32WB5x */
1083         case 0x496: /* STM32WB3x */
1084                 /* single bank flash */
1085                 page_size_kb = 4;
1086                 num_pages = flash_size_kb / page_size_kb;
1087                 stm32l4_info->bank1_sectors = num_pages;
1088                 break;
1089         default:
1090                 LOG_ERROR("unsupported device");
1091                 return ERROR_FAIL;
1092         }
1093
1094         LOG_INFO("flash mode : %s-bank", stm32l4_info->dual_bank_mode ? "dual" : "single");
1095
1096         const int gap_size_kb = stm32l4_info->hole_sectors * page_size_kb;
1097
1098         if (gap_size_kb != 0) {
1099                 LOG_INFO("gap detected from 0x%08x to 0x%08x",
1100                         STM32_FLASH_BANK_BASE + stm32l4_info->bank1_sectors
1101                                 * page_size_kb * 1024,
1102                         STM32_FLASH_BANK_BASE + (stm32l4_info->bank1_sectors
1103                                 * page_size_kb + gap_size_kb) * 1024 - 1);
1104         }
1105
1106         /* number of significant bits in WRPxxR differs per device,
1107          * always right adjusted, on some devices non-implemented
1108          * bits read as '0', on others as '1' ...
1109          * notably G4 Cat. 2 implement only 6 bits, contradicting the RM
1110          */
1111
1112         /* use *max_flash_size* instead of actual size as the trimmed versions
1113          * certainly use the same number of bits
1114          * max_flash_size is always power of two, so max_pages too
1115          */
1116         uint32_t max_pages = stm32l4_info->part_info->max_flash_size_kb / page_size_kb;
1117         assert((max_pages & (max_pages - 1)) == 0);
1118
1119         /* in dual bank mode number of pages is doubled, but extra bit is bank selection */
1120         stm32l4_info->wrpxxr_mask = ((max_pages >> (stm32l4_info->dual_bank_mode ? 1 : 0)) - 1);
1121         assert((stm32l4_info->wrpxxr_mask & 0xFFFF0000) == 0);
1122         LOG_DEBUG("WRPxxR mask 0x%04" PRIx16, (uint16_t)stm32l4_info->wrpxxr_mask);
1123
1124         free(bank->sectors);
1125
1126         bank->size = (flash_size_kb + gap_size_kb) * 1024;
1127         bank->base = STM32_FLASH_BANK_BASE;
1128         bank->num_sectors = num_pages;
1129         bank->sectors = malloc(sizeof(struct flash_sector) * bank->num_sectors);
1130         if (bank->sectors == NULL) {
1131                 LOG_ERROR("failed to allocate bank sectors");
1132                 return ERROR_FAIL;
1133         }
1134
1135         for (unsigned int i = 0; i < bank->num_sectors; i++) {
1136                 bank->sectors[i].offset = i * page_size_kb * 1024;
1137                 /* in dual bank configuration, if there is a gap between banks
1138                  * we fix up the sector offset to consider this gap */
1139                 if (i >= stm32l4_info->bank1_sectors && stm32l4_info->hole_sectors)
1140                         bank->sectors[i].offset += gap_size_kb * 1024;
1141                 bank->sectors[i].size = page_size_kb * 1024;
1142                 bank->sectors[i].is_erased = -1;
1143                 bank->sectors[i].is_protected = 1;
1144         }
1145
1146         stm32l4_info->probed = true;
1147         return ERROR_OK;
1148 }
1149
1150 static int stm32l4_auto_probe(struct flash_bank *bank)
1151 {
1152         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1153         if (stm32l4_info->probed)
1154                 return ERROR_OK;
1155
1156         return stm32l4_probe(bank);
1157 }
1158
1159 static int get_stm32l4_info(struct flash_bank *bank, char *buf, int buf_size)
1160 {
1161         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1162         const struct stm32l4_part_info *part_info = stm32l4_info->part_info;
1163
1164         if (part_info) {
1165                 const char *rev_str = NULL;
1166                 uint16_t rev_id = stm32l4_info->idcode >> 16;
1167                 for (unsigned int i = 0; i < part_info->num_revs; i++) {
1168                         if (rev_id == part_info->revs[i].rev) {
1169                                 rev_str = part_info->revs[i].str;
1170
1171                                 if (rev_str != NULL) {
1172                                         snprintf(buf, buf_size, "%s - Rev: %s%s",
1173                                                 part_info->device_str, rev_str, stm32l4_info->probed ?
1174                                                         (stm32l4_info->dual_bank_mode ? " dual-bank" : " single-bank") : "");
1175                                         return ERROR_OK;
1176                                 }
1177                         }
1178                 }
1179
1180                 snprintf(buf, buf_size, "%s - Rev: unknown (0x%04x)%s",
1181                         part_info->device_str, rev_id, stm32l4_info->probed ?
1182                                 (stm32l4_info->dual_bank_mode ? " dual-bank" : " single-bank") : "");
1183                 return ERROR_OK;
1184         } else {
1185                 snprintf(buf, buf_size, "Cannot identify target as an %s device", device_families);
1186                 return ERROR_FAIL;
1187         }
1188
1189         return ERROR_OK;
1190 }
1191
1192 static int stm32l4_mass_erase(struct flash_bank *bank)
1193 {
1194         int retval, retval2;
1195         struct target *target = bank->target;
1196         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1197
1198         uint32_t action = FLASH_MER1;
1199
1200         if (stm32l4_info->part_info->has_dual_bank)
1201                 action |= FLASH_MER2;
1202
1203         if (target->state != TARGET_HALTED) {
1204                 LOG_ERROR("Target not halted");
1205                 return ERROR_TARGET_NOT_HALTED;
1206         }
1207
1208         retval = stm32l4_unlock_reg(bank);
1209         if (retval != ERROR_OK)
1210                 goto err_lock;
1211
1212         /* mass erase flash memory */
1213         retval = stm32l4_wait_status_busy(bank, FLASH_ERASE_TIMEOUT / 10);
1214         if (retval != ERROR_OK)
1215                 goto err_lock;
1216
1217         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, action);
1218         if (retval != ERROR_OK)
1219                 goto err_lock;
1220
1221         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, action | FLASH_STRT);
1222         if (retval != ERROR_OK)
1223                 goto err_lock;
1224
1225         retval = stm32l4_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
1226
1227 err_lock:
1228         retval2 = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_LOCK);
1229
1230         if (retval != ERROR_OK)
1231                 return retval;
1232
1233         return retval2;
1234 }
1235
1236 COMMAND_HANDLER(stm32l4_handle_mass_erase_command)
1237 {
1238         if (CMD_ARGC < 1) {
1239                 command_print(CMD, "stm32l4x mass_erase <STM32L4 bank>");
1240                 return ERROR_COMMAND_SYNTAX_ERROR;
1241         }
1242
1243         struct flash_bank *bank;
1244         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1245         if (ERROR_OK != retval)
1246                 return retval;
1247
1248         retval = stm32l4_mass_erase(bank);
1249         if (retval == ERROR_OK) {
1250                 /* set all sectors as erased */
1251                 for (unsigned int i = 0; i < bank->num_sectors; i++)
1252                         bank->sectors[i].is_erased = 1;
1253
1254                 command_print(CMD, "stm32l4x mass erase complete");
1255         } else {
1256                 command_print(CMD, "stm32l4x mass erase failed");
1257         }
1258
1259         return retval;
1260 }
1261
1262 COMMAND_HANDLER(stm32l4_handle_option_read_command)
1263 {
1264         if (CMD_ARGC < 2) {
1265                 command_print(CMD, "stm32l4x option_read <STM32L4 bank> <option_reg offset>");
1266                 return ERROR_COMMAND_SYNTAX_ERROR;
1267         }
1268
1269         struct flash_bank *bank;
1270         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1271         if (ERROR_OK != retval)
1272                 return retval;
1273
1274         uint32_t reg_offset, reg_addr;
1275         uint32_t value = 0;
1276
1277         reg_offset = strtoul(CMD_ARGV[1], NULL, 16);
1278         reg_addr = stm32l4_get_flash_reg(bank, reg_offset);
1279
1280         retval = stm32l4_read_flash_reg(bank, reg_offset, &value);
1281         if (ERROR_OK != retval)
1282                 return retval;
1283
1284         command_print(CMD, "Option Register: <0x%" PRIx32 "> = 0x%" PRIx32 "", reg_addr, value);
1285
1286         return retval;
1287 }
1288
1289 COMMAND_HANDLER(stm32l4_handle_option_write_command)
1290 {
1291         if (CMD_ARGC < 3) {
1292                 command_print(CMD, "stm32l4x option_write <STM32L4 bank> <option_reg offset> <value> [mask]");
1293                 return ERROR_COMMAND_SYNTAX_ERROR;
1294         }
1295
1296         struct flash_bank *bank;
1297         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1298         if (ERROR_OK != retval)
1299                 return retval;
1300
1301         uint32_t reg_offset;
1302         uint32_t value = 0;
1303         uint32_t mask = 0xFFFFFFFF;
1304
1305         reg_offset = strtoul(CMD_ARGV[1], NULL, 16);
1306         value = strtoul(CMD_ARGV[2], NULL, 16);
1307         if (CMD_ARGC > 3)
1308                 mask = strtoul(CMD_ARGV[3], NULL, 16);
1309
1310         command_print(CMD, "%s Option written.\n"
1311                                 "INFO: a reset or power cycle is required "
1312                                 "for the new settings to take effect.", bank->driver->name);
1313
1314         retval = stm32l4_write_option(bank, reg_offset, value, mask);
1315         return retval;
1316 }
1317
1318 COMMAND_HANDLER(stm32l4_handle_option_load_command)
1319 {
1320         if (CMD_ARGC != 1)
1321                 return ERROR_COMMAND_SYNTAX_ERROR;
1322
1323         struct flash_bank *bank;
1324         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1325         if (ERROR_OK != retval)
1326                 return retval;
1327
1328         retval = stm32l4_unlock_reg(bank);
1329         if (ERROR_OK != retval)
1330                 return retval;
1331
1332         retval = stm32l4_unlock_option_reg(bank);
1333         if (ERROR_OK != retval)
1334                 return retval;
1335
1336         /* Set OBL_LAUNCH bit in CR -> system reset and option bytes reload,
1337          * but the RMs explicitly do *NOT* list this as power-on reset cause, and:
1338          * "Note: If the read protection is set while the debugger is still
1339          * connected through JTAG/SWD, apply a POR (power-on reset) instead of a system reset."
1340          */
1341         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_OBL_LAUNCH);
1342
1343         command_print(CMD, "stm32l4x option load completed. Power-on reset might be required");
1344
1345         /* Need to re-probe after change */
1346         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1347         stm32l4_info->probed = false;
1348
1349         return retval;
1350 }
1351
1352 COMMAND_HANDLER(stm32l4_handle_lock_command)
1353 {
1354         struct target *target = NULL;
1355
1356         if (CMD_ARGC < 1)
1357                 return ERROR_COMMAND_SYNTAX_ERROR;
1358
1359         struct flash_bank *bank;
1360         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1361         if (ERROR_OK != retval)
1362                 return retval;
1363
1364         target = bank->target;
1365
1366         if (target->state != TARGET_HALTED) {
1367                 LOG_ERROR("Target not halted");
1368                 return ERROR_TARGET_NOT_HALTED;
1369         }
1370
1371         /* set readout protection level 1 by erasing the RDP option byte */
1372         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1373         if (stm32l4_write_option(bank, stm32l4_info->flash_regs[STM32_FLASH_OPTR_INDEX], 0, 0x000000FF) != ERROR_OK) {
1374                 command_print(CMD, "%s failed to lock device", bank->driver->name);
1375                 return ERROR_OK;
1376         }
1377
1378         return ERROR_OK;
1379 }
1380
1381 COMMAND_HANDLER(stm32l4_handle_unlock_command)
1382 {
1383         struct target *target = NULL;
1384
1385         if (CMD_ARGC < 1)
1386                 return ERROR_COMMAND_SYNTAX_ERROR;
1387
1388         struct flash_bank *bank;
1389         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1390         if (ERROR_OK != retval)
1391                 return retval;
1392
1393         target = bank->target;
1394
1395         if (target->state != TARGET_HALTED) {
1396                 LOG_ERROR("Target not halted");
1397                 return ERROR_TARGET_NOT_HALTED;
1398         }
1399
1400         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1401         if (stm32l4_write_option(bank, stm32l4_info->flash_regs[STM32_FLASH_OPTR_INDEX],
1402                         RDP_LEVEL_0, 0x000000FF) != ERROR_OK) {
1403                 command_print(CMD, "%s failed to unlock device", bank->driver->name);
1404                 return ERROR_OK;
1405         }
1406
1407         return ERROR_OK;
1408 }
1409
1410 static const struct command_registration stm32l4_exec_command_handlers[] = {
1411         {
1412                 .name = "lock",
1413                 .handler = stm32l4_handle_lock_command,
1414                 .mode = COMMAND_EXEC,
1415                 .usage = "bank_id",
1416                 .help = "Lock entire flash device.",
1417         },
1418         {
1419                 .name = "unlock",
1420                 .handler = stm32l4_handle_unlock_command,
1421                 .mode = COMMAND_EXEC,
1422                 .usage = "bank_id",
1423                 .help = "Unlock entire protected flash device.",
1424         },
1425         {
1426                 .name = "mass_erase",
1427                 .handler = stm32l4_handle_mass_erase_command,
1428                 .mode = COMMAND_EXEC,
1429                 .usage = "bank_id",
1430                 .help = "Erase entire flash device.",
1431         },
1432         {
1433                 .name = "option_read",
1434                 .handler = stm32l4_handle_option_read_command,
1435                 .mode = COMMAND_EXEC,
1436                 .usage = "bank_id reg_offset",
1437                 .help = "Read & Display device option bytes.",
1438         },
1439         {
1440                 .name = "option_write",
1441                 .handler = stm32l4_handle_option_write_command,
1442                 .mode = COMMAND_EXEC,
1443                 .usage = "bank_id reg_offset value mask",
1444                 .help = "Write device option bit fields with provided value.",
1445         },
1446         {
1447                 .name = "option_load",
1448                 .handler = stm32l4_handle_option_load_command,
1449                 .mode = COMMAND_EXEC,
1450                 .usage = "bank_id",
1451                 .help = "Force re-load of device options (will cause device reset).",
1452         },
1453         COMMAND_REGISTRATION_DONE
1454 };
1455
1456 static const struct command_registration stm32l4_command_handlers[] = {
1457         {
1458                 .name = "stm32l4x",
1459                 .mode = COMMAND_ANY,
1460                 .help = "stm32l4x flash command group",
1461                 .usage = "",
1462                 .chain = stm32l4_exec_command_handlers,
1463         },
1464         COMMAND_REGISTRATION_DONE
1465 };
1466
1467 const struct flash_driver stm32l4x_flash = {
1468         .name = "stm32l4x",
1469         .commands = stm32l4_command_handlers,
1470         .flash_bank_command = stm32l4_flash_bank_command,
1471         .erase = stm32l4_erase,
1472         .protect = stm32l4_protect,
1473         .write = stm32l4_write,
1474         .read = default_flash_read,
1475         .probe = stm32l4_probe,
1476         .auto_probe = stm32l4_auto_probe,
1477         .erase_check = default_flash_blank_check,
1478         .protect_check = stm32l4_protect_check,
1479         .info = get_stm32l4_info,
1480         .free_driver_priv = default_flash_free_driver_priv,
1481 };