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