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