flash/stm32l4x: STM32L5 support programming when TZEN=1 and RDP=0x55
[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/align.h>
28 #include <helper/binarybuffer.h>
29 #include <target/algorithm.h>
30 #include <target/armv7m.h>
31 #include "bits.h"
32 #include "stm32l4x.h"
33
34 /* STM32L4xxx series for reference.
35  *
36  * RM0351 (STM32L4x5/STM32L4x6)
37  * http://www.st.com/resource/en/reference_manual/dm00083560.pdf
38  *
39  * RM0394 (STM32L43x/44x/45x/46x)
40  * http://www.st.com/resource/en/reference_manual/dm00151940.pdf
41  *
42  * RM0432 (STM32L4R/4Sxx)
43  * http://www.st.com/resource/en/reference_manual/dm00310109.pdf
44  *
45  * STM32L476RG Datasheet (for erase timing)
46  * http://www.st.com/resource/en/datasheet/stm32l476rg.pdf
47  *
48  * The RM0351 devices have normally two banks, but on 512 and 256 kiB devices
49  * an option byte is available to map all sectors to the first bank.
50  * Both STM32 banks are treated as one OpenOCD bank, as other STM32 devices
51  * handlers do!
52  *
53  * RM0394 devices have a single bank only.
54  *
55  * RM0432 devices have single and dual bank operating modes.
56  *  - for STM32L4R/Sxx the FLASH size is 2Mbyte or 1Mbyte.
57  *  - for STM32L4P/Q5x the FLASH size is 1Mbyte or 512Kbyte.
58  * Bank page (sector) size is 4Kbyte (dual mode) or 8Kbyte (single mode).
59  *
60  * Bank mode is controlled by two different bits in option bytes register.
61  *  - for STM32L4R/Sxx
62  *    In 2M FLASH devices bit 22 (DBANK) controls Dual Bank mode.
63  *    In 1M FLASH devices bit 21 (DB1M) controls Dual Bank mode.
64  *  - for STM32L4P5/Q5x
65  *    In 1M FLASH devices bit 22 (DBANK) controls Dual Bank mode.
66  *    In 512K FLASH devices bit 21 (DB512K) controls Dual Bank mode.
67  *
68  */
69
70 /* STM32WBxxx series for reference.
71  *
72  * RM0434 (STM32WB55)
73  * http://www.st.com/resource/en/reference_manual/dm00318631.pdf
74  *
75  * RM0471 (STM32WB50)
76  * http://www.st.com/resource/en/reference_manual/dm00622834.pdf
77  */
78
79 /* STM32WLxxx series for reference.
80  *
81  * RM0461 (STM32WLEx)
82  * http://www.st.com/resource/en/reference_manual/dm00530369.pdf
83  */
84
85 /* STM32G0xxx series for reference.
86  *
87  * RM0444 (STM32G0x1)
88  * http://www.st.com/resource/en/reference_manual/dm00371828.pdf
89  *
90  * RM0454 (STM32G0x0)
91  * http://www.st.com/resource/en/reference_manual/dm00463896.pdf
92  */
93
94 /* STM32G4xxx series for reference.
95  *
96  * RM0440 (STM32G43x/44x/47x/48x/49x/4Ax)
97  * http://www.st.com/resource/en/reference_manual/dm00355726.pdf
98  *
99  * Cat. 2 devices have single bank only, page size is 2kByte.
100  *
101  * Cat. 3 devices have single and dual bank operating modes,
102  * Page size is 2kByte (dual mode) or 4kByte (single mode).
103  *
104  * Bank mode is controlled by bit 22 (DBANK) in option bytes register.
105  * Both banks are treated as a single OpenOCD bank.
106  *
107  * Cat. 4 devices have single bank only, page size is 2kByte.
108  */
109
110 /* STM32L5xxx series for reference.
111  *
112  * RM0428 (STM32L552xx/STM32L562xx)
113  * http://www.st.com/resource/en/reference_manual/dm00346336.pdf
114  */
115
116 /* Erase time can be as high as 25ms, 10x this and assume it's toast... */
117
118 #define FLASH_ERASE_TIMEOUT 250
119
120
121 /* relevant STM32L4 flags ****************************************************/
122 #define F_NONE              0
123 /* this flag indicates if the device flash is with dual bank architecture */
124 #define F_HAS_DUAL_BANK     BIT(0)
125 /* this flags is used for dual bank devices only, it indicates if the
126  * 4 WRPxx are usable if the device is configured in single-bank mode */
127 #define F_USE_ALL_WRPXX     BIT(1)
128 /* this flag indicates if the device embeds a TrustZone security feature */
129 #define F_HAS_TZ            BIT(2)
130 /* this flag indicates if the device has the same flash registers as STM32L5 */
131 #define F_HAS_L5_FLASH_REGS BIT(3)
132 /* end of STM32L4 flags ******************************************************/
133
134
135 enum stm32l4_flash_reg_index {
136         STM32_FLASH_ACR_INDEX,
137         STM32_FLASH_KEYR_INDEX,
138         STM32_FLASH_OPTKEYR_INDEX,
139         STM32_FLASH_SR_INDEX,
140         STM32_FLASH_CR_INDEX,
141         STM32_FLASH_OPTR_INDEX,
142         STM32_FLASH_WRP1AR_INDEX,
143         STM32_FLASH_WRP1BR_INDEX,
144         STM32_FLASH_WRP2AR_INDEX,
145         STM32_FLASH_WRP2BR_INDEX,
146         STM32_FLASH_REG_INDEX_NUM,
147 };
148
149 enum stm32l4_rdp {
150         RDP_LEVEL_0   = 0xAA,
151         RDP_LEVEL_0_5 = 0x55, /* for devices with TrustZone enabled */
152         RDP_LEVEL_1   = 0x00,
153         RDP_LEVEL_2   = 0xCC
154 };
155
156 static const uint32_t stm32l4_flash_regs[STM32_FLASH_REG_INDEX_NUM] = {
157         [STM32_FLASH_ACR_INDEX]      = 0x000,
158         [STM32_FLASH_KEYR_INDEX]     = 0x008,
159         [STM32_FLASH_OPTKEYR_INDEX]  = 0x00C,
160         [STM32_FLASH_SR_INDEX]       = 0x010,
161         [STM32_FLASH_CR_INDEX]       = 0x014,
162         [STM32_FLASH_OPTR_INDEX]     = 0x020,
163         [STM32_FLASH_WRP1AR_INDEX]   = 0x02C,
164         [STM32_FLASH_WRP1BR_INDEX]   = 0x030,
165         [STM32_FLASH_WRP2AR_INDEX]   = 0x04C,
166         [STM32_FLASH_WRP2BR_INDEX]   = 0x050,
167 };
168
169 static const uint32_t stm32l5_ns_flash_regs[STM32_FLASH_REG_INDEX_NUM] = {
170         [STM32_FLASH_ACR_INDEX]      = 0x000,
171         [STM32_FLASH_KEYR_INDEX]     = 0x008, /* NSKEYR */
172         [STM32_FLASH_OPTKEYR_INDEX]  = 0x010,
173         [STM32_FLASH_SR_INDEX]       = 0x020, /* NSSR */
174         [STM32_FLASH_CR_INDEX]       = 0x028, /* NSCR */
175         [STM32_FLASH_OPTR_INDEX]     = 0x040,
176         [STM32_FLASH_WRP1AR_INDEX]   = 0x058,
177         [STM32_FLASH_WRP1BR_INDEX]   = 0x05C,
178         [STM32_FLASH_WRP2AR_INDEX]   = 0x068,
179         [STM32_FLASH_WRP2BR_INDEX]   = 0x06C,
180 };
181
182 static const uint32_t stm32l5_s_flash_regs[STM32_FLASH_REG_INDEX_NUM] = {
183         [STM32_FLASH_ACR_INDEX]      = 0x000,
184         [STM32_FLASH_KEYR_INDEX]     = 0x00C, /* SECKEYR */
185         [STM32_FLASH_OPTKEYR_INDEX]  = 0x010,
186         [STM32_FLASH_SR_INDEX]       = 0x024, /* SECSR */
187         [STM32_FLASH_CR_INDEX]       = 0x02C, /* SECCR */
188         [STM32_FLASH_OPTR_INDEX]     = 0x040,
189         [STM32_FLASH_WRP1AR_INDEX]   = 0x058,
190         [STM32_FLASH_WRP1BR_INDEX]   = 0x05C,
191         [STM32_FLASH_WRP2AR_INDEX]   = 0x068,
192         [STM32_FLASH_WRP2BR_INDEX]   = 0x06C,
193 };
194
195 struct stm32l4_rev {
196         const uint16_t rev;
197         const char *str;
198 };
199
200 struct stm32l4_part_info {
201         uint16_t id;
202         const char *device_str;
203         const struct stm32l4_rev *revs;
204         const size_t num_revs;
205         const uint16_t max_flash_size_kb;
206         const uint32_t flags; /* one bit per feature, see STM32L4 flags: macros F_XXX */
207         const uint32_t flash_regs_base;
208         const uint32_t *default_flash_regs;
209         const uint32_t fsize_addr;
210         const uint32_t otp_base;
211         const uint32_t otp_size;
212 };
213
214 struct stm32l4_flash_bank {
215         bool probed;
216         uint32_t idcode;
217         unsigned int bank1_sectors;
218         bool dual_bank_mode;
219         int hole_sectors;
220         uint32_t user_bank_size;
221         uint32_t wrpxxr_mask;
222         const struct stm32l4_part_info *part_info;
223         uint32_t flash_regs_base;
224         const uint32_t *flash_regs;
225         bool otp_enabled;
226         enum stm32l4_rdp rdp;
227         bool tzen;
228         uint32_t optr;
229 };
230
231 enum stm32_bank_id {
232         STM32_BANK1,
233         STM32_BANK2,
234         STM32_ALL_BANKS
235 };
236
237 struct stm32l4_wrp {
238         enum stm32l4_flash_reg_index reg_idx;
239         uint32_t value;
240         bool used;
241         int first;
242         int last;
243         int offset;
244 };
245
246 /* human readable list of families this drivers supports (sorted alphabetically) */
247 static const char *device_families = "STM32G0/G4/L4/L4+/L5/WB/WL";
248
249 static const struct stm32l4_rev stm32_415_revs[] = {
250         { 0x1000, "1" }, { 0x1001, "2" }, { 0x1003, "3" }, { 0x1007, "4" }
251 };
252
253 static const struct stm32l4_rev stm32_435_revs[] = {
254         { 0x1000, "A" }, { 0x1001, "Z" }, { 0x2001, "Y" },
255 };
256
257 static const struct stm32l4_rev stm32_460_revs[] = {
258         { 0x1000, "A/Z" } /* A and Z, no typo in RM! */, { 0x2000, "B" },
259 };
260
261 static const struct stm32l4_rev stm32_461_revs[] = {
262         { 0x1000, "A" }, { 0x2000, "B" },
263 };
264
265 static const struct stm32l4_rev stm32_462_revs[] = {
266         { 0x1000, "A" }, { 0x1001, "Z" }, { 0x2001, "Y" },
267 };
268
269 static const struct stm32l4_rev stm32_464_revs[] = {
270         { 0x1000, "A" }, { 0x1001, "Z" }, { 0x2001, "Y" },
271 };
272
273 static const struct stm32l4_rev stm32_466_revs[] = {
274         { 0x1000, "A" }, { 0x1001, "Z" }, { 0x2000, "B" },
275 };
276
277 static const struct stm32l4_rev stm32_468_revs[] = {
278         { 0x1000, "A" }, { 0x2000, "B" }, { 0x2001, "Z" },
279 };
280
281 static const struct stm32l4_rev stm32_469_revs[] = {
282         { 0x1000, "A" }, { 0x2000, "B" }, { 0x2001, "Z" },
283 };
284
285 static const struct stm32l4_rev stm32_470_revs[] = {
286         { 0x1000, "A" }, { 0x1001, "Z" }, { 0x1003, "Y" }, { 0x100F, "W" },
287 };
288
289 static const struct stm32l4_rev stm32_471_revs[] = {
290         { 0x1001, "Z" },
291 };
292
293 static const struct stm32l4_rev stm32_472_revs[] = {
294         { 0x1000, "A" }, { 0x2000, "B" },
295 };
296
297 static const struct stm32l4_rev stm32_479_revs[] = {
298         { 0x1000, "A" },
299 };
300
301 static const struct stm32l4_rev stm32_495_revs[] = {
302         { 0x2001, "2.1" },
303 };
304
305 static const struct stm32l4_rev stm32_496_revs[] = {
306         { 0x1000, "A" },
307 };
308
309 static const struct stm32l4_rev stm32_497_revs[] = {
310         { 0x1000, "1.0" },
311 };
312
313 static const struct stm32l4_part_info stm32l4_parts[] = {
314         {
315           .id                    = 0x415,
316           .revs                  = stm32_415_revs,
317           .num_revs              = ARRAY_SIZE(stm32_415_revs),
318           .device_str            = "STM32L47/L48xx",
319           .max_flash_size_kb     = 1024,
320           .flags                 = F_HAS_DUAL_BANK,
321           .flash_regs_base       = 0x40022000,
322           .default_flash_regs    = stm32l4_flash_regs,
323           .fsize_addr            = 0x1FFF75E0,
324           .otp_base              = 0x1FFF7000,
325           .otp_size              = 1024,
326         },
327         {
328           .id                    = 0x435,
329           .revs                  = stm32_435_revs,
330           .num_revs              = ARRAY_SIZE(stm32_435_revs),
331           .device_str            = "STM32L43/L44xx",
332           .max_flash_size_kb     = 256,
333           .flags                 = F_NONE,
334           .flash_regs_base       = 0x40022000,
335           .default_flash_regs    = stm32l4_flash_regs,
336           .fsize_addr            = 0x1FFF75E0,
337           .otp_base              = 0x1FFF7000,
338           .otp_size              = 1024,
339         },
340         {
341           .id                    = 0x460,
342           .revs                  = stm32_460_revs,
343           .num_revs              = ARRAY_SIZE(stm32_460_revs),
344           .device_str            = "STM32G07/G08xx",
345           .max_flash_size_kb     = 128,
346           .flags                 = F_NONE,
347           .flash_regs_base       = 0x40022000,
348           .default_flash_regs    = stm32l4_flash_regs,
349           .fsize_addr            = 0x1FFF75E0,
350           .otp_base              = 0x1FFF7000,
351           .otp_size              = 1024,
352         },
353         {
354           .id                    = 0x461,
355           .revs                  = stm32_461_revs,
356           .num_revs              = ARRAY_SIZE(stm32_461_revs),
357           .device_str            = "STM32L49/L4Axx",
358           .max_flash_size_kb     = 1024,
359           .flags                 = F_HAS_DUAL_BANK,
360           .flash_regs_base       = 0x40022000,
361           .default_flash_regs    = stm32l4_flash_regs,
362           .fsize_addr            = 0x1FFF75E0,
363           .otp_base              = 0x1FFF7000,
364           .otp_size              = 1024,
365         },
366         {
367           .id                    = 0x462,
368           .revs                  = stm32_462_revs,
369           .num_revs              = ARRAY_SIZE(stm32_462_revs),
370           .device_str            = "STM32L45/L46xx",
371           .max_flash_size_kb     = 512,
372           .flags                 = F_NONE,
373           .flash_regs_base       = 0x40022000,
374           .default_flash_regs    = stm32l4_flash_regs,
375           .fsize_addr            = 0x1FFF75E0,
376           .otp_base              = 0x1FFF7000,
377           .otp_size              = 1024,
378         },
379         {
380           .id                    = 0x464,
381           .revs                  = stm32_464_revs,
382           .num_revs              = ARRAY_SIZE(stm32_464_revs),
383           .device_str            = "STM32L41/L42xx",
384           .max_flash_size_kb     = 128,
385           .flags                 = F_NONE,
386           .flash_regs_base       = 0x40022000,
387           .default_flash_regs    = stm32l4_flash_regs,
388           .fsize_addr            = 0x1FFF75E0,
389           .otp_base              = 0x1FFF7000,
390           .otp_size              = 1024,
391         },
392         {
393           .id                    = 0x466,
394           .revs                  = stm32_466_revs,
395           .num_revs              = ARRAY_SIZE(stm32_466_revs),
396           .device_str            = "STM32G03/G04xx",
397           .max_flash_size_kb     = 64,
398           .flags                 = F_NONE,
399           .flash_regs_base       = 0x40022000,
400           .default_flash_regs    = stm32l4_flash_regs,
401           .fsize_addr            = 0x1FFF75E0,
402           .otp_base              = 0x1FFF7000,
403           .otp_size              = 1024,
404         },
405         {
406           .id                    = 0x468,
407           .revs                  = stm32_468_revs,
408           .num_revs              = ARRAY_SIZE(stm32_468_revs),
409           .device_str            = "STM32G43/G44xx",
410           .max_flash_size_kb     = 128,
411           .flags                 = F_NONE,
412           .flash_regs_base       = 0x40022000,
413           .default_flash_regs    = stm32l4_flash_regs,
414           .fsize_addr            = 0x1FFF75E0,
415           .otp_base              = 0x1FFF7000,
416           .otp_size              = 1024,
417         },
418         {
419           .id                    = 0x469,
420           .revs                  = stm32_469_revs,
421           .num_revs              = ARRAY_SIZE(stm32_469_revs),
422           .device_str            = "STM32G47/G48xx",
423           .max_flash_size_kb     = 512,
424           .flags                 = F_HAS_DUAL_BANK | F_USE_ALL_WRPXX,
425           .flash_regs_base       = 0x40022000,
426           .default_flash_regs    = stm32l4_flash_regs,
427           .fsize_addr            = 0x1FFF75E0,
428           .otp_base              = 0x1FFF7000,
429           .otp_size              = 1024,
430         },
431         {
432           .id                    = 0x470,
433           .revs                  = stm32_470_revs,
434           .num_revs              = ARRAY_SIZE(stm32_470_revs),
435           .device_str            = "STM32L4R/L4Sxx",
436           .max_flash_size_kb     = 2048,
437           .flags                 = F_HAS_DUAL_BANK | F_USE_ALL_WRPXX,
438           .flash_regs_base       = 0x40022000,
439           .default_flash_regs    = stm32l4_flash_regs,
440           .fsize_addr            = 0x1FFF75E0,
441           .otp_base              = 0x1FFF7000,
442           .otp_size              = 1024,
443         },
444         {
445           .id                    = 0x471,
446           .revs                  = stm32_471_revs,
447           .num_revs              = ARRAY_SIZE(stm32_471_revs),
448           .device_str            = "STM32L4P5/L4Q5x",
449           .max_flash_size_kb     = 1024,
450           .flags                 = F_HAS_DUAL_BANK | F_USE_ALL_WRPXX,
451           .flash_regs_base       = 0x40022000,
452           .default_flash_regs    = stm32l4_flash_regs,
453           .fsize_addr            = 0x1FFF75E0,
454           .otp_base              = 0x1FFF7000,
455           .otp_size              = 1024,
456         },
457         {
458           .id                    = 0x472,
459           .revs                  = stm32_472_revs,
460           .num_revs              = ARRAY_SIZE(stm32_472_revs),
461           .device_str            = "STM32L55/L56xx",
462           .max_flash_size_kb     = 512,
463           .flags                 = F_HAS_DUAL_BANK | F_USE_ALL_WRPXX | F_HAS_TZ | F_HAS_L5_FLASH_REGS,
464           .flash_regs_base       = 0x40022000,
465           .default_flash_regs    = stm32l5_ns_flash_regs,
466           .fsize_addr            = 0x0BFA05E0,
467           .otp_base              = 0x0BFA0000,
468           .otp_size              = 512,
469         },
470         {
471           .id                    = 0x479,
472           .revs                  = stm32_479_revs,
473           .num_revs              = ARRAY_SIZE(stm32_479_revs),
474           .device_str            = "STM32G49/G4Axx",
475           .max_flash_size_kb     = 512,
476           .flags                 = F_NONE,
477           .flash_regs_base       = 0x40022000,
478           .default_flash_regs    = stm32l4_flash_regs,
479           .fsize_addr            = 0x1FFF75E0,
480           .otp_base              = 0x1FFF7000,
481           .otp_size              = 1024,
482         },
483         {
484           .id                    = 0x495,
485           .revs                  = stm32_495_revs,
486           .num_revs              = ARRAY_SIZE(stm32_495_revs),
487           .device_str            = "STM32WB5x",
488           .max_flash_size_kb     = 1024,
489           .flags                 = F_NONE,
490           .flash_regs_base       = 0x58004000,
491           .default_flash_regs    = stm32l4_flash_regs,
492           .fsize_addr            = 0x1FFF75E0,
493           .otp_base              = 0x1FFF7000,
494           .otp_size              = 1024,
495         },
496         {
497           .id                    = 0x496,
498           .revs                  = stm32_496_revs,
499           .num_revs              = ARRAY_SIZE(stm32_496_revs),
500           .device_str            = "STM32WB3x",
501           .max_flash_size_kb     = 512,
502           .flags                 = F_NONE,
503           .flash_regs_base       = 0x58004000,
504           .default_flash_regs    = stm32l4_flash_regs,
505           .fsize_addr            = 0x1FFF75E0,
506           .otp_base              = 0x1FFF7000,
507           .otp_size              = 1024,
508         },
509         {
510           .id                    = 0x497,
511           .revs                  = stm32_497_revs,
512           .num_revs              = ARRAY_SIZE(stm32_497_revs),
513           .device_str            = "STM32WLEx",
514           .max_flash_size_kb     = 256,
515           .flags                 = F_NONE,
516           .flash_regs_base       = 0x58004000,
517           .default_flash_regs    = stm32l4_flash_regs,
518           .fsize_addr            = 0x1FFF75E0,
519           .otp_base              = 0x1FFF7000,
520           .otp_size              = 1024,
521         },
522 };
523
524 /* flash bank stm32l4x <base> <size> 0 0 <target#> */
525 FLASH_BANK_COMMAND_HANDLER(stm32l4_flash_bank_command)
526 {
527         struct stm32l4_flash_bank *stm32l4_info;
528
529         if (CMD_ARGC < 6)
530                 return ERROR_COMMAND_SYNTAX_ERROR;
531
532         /* fix-up bank base address: 0 is used for normal flash memory */
533         if (bank->base == 0)
534                 bank->base = STM32_FLASH_BANK_BASE;
535
536         stm32l4_info = calloc(1, sizeof(struct stm32l4_flash_bank));
537         if (!stm32l4_info)
538                 return ERROR_FAIL; /* Checkme: What better error to use?*/
539         bank->driver_priv = stm32l4_info;
540
541         /* The flash write must be aligned to a double word (8-bytes) boundary.
542          * Ask the flash infrastructure to ensure required alignment */
543         bank->write_start_alignment = bank->write_end_alignment = 8;
544
545         stm32l4_info->probed = false;
546         stm32l4_info->otp_enabled = false;
547         stm32l4_info->user_bank_size = bank->size;
548
549         return ERROR_OK;
550 }
551
552 /* bitmap helper extension */
553 struct range {
554         unsigned int start;
555         unsigned int end;
556 };
557
558 static void bitmap_to_ranges(unsigned long *bitmap, unsigned int nbits,
559                 struct range *ranges, unsigned int *ranges_count) {
560         *ranges_count = 0;
561         bool last_bit = 0, cur_bit;
562         for (unsigned int i = 0; i < nbits; i++) {
563                 cur_bit = test_bit(i, bitmap);
564
565                 if (cur_bit && !last_bit) {
566                         (*ranges_count)++;
567                         ranges[*ranges_count - 1].start = i;
568                         ranges[*ranges_count - 1].end = i;
569                 } else if (cur_bit && last_bit) {
570                         /* update (increment) the end this range */
571                         ranges[*ranges_count - 1].end = i;
572                 }
573
574                 last_bit = cur_bit;
575         }
576 }
577
578 static inline int range_print_one(struct range *range, char *str)
579 {
580         if (range->start == range->end)
581                 return sprintf(str, "[%d]", range->start);
582
583         return sprintf(str, "[%d,%d]", range->start, range->end);
584 }
585
586 static char *range_print_alloc(struct range *ranges, unsigned int ranges_count)
587 {
588         /* each range will be printed like the following: [start,end]
589          * start and end, both are unsigned int, an unsigned int takes 10 characters max
590          * plus 3 characters for '[', ',' and ']'
591          * thus means each range can take maximum 23 character
592          * after each range we add a ' ' as separator and finally we need the '\0'
593          * if the ranges_count is zero we reserve one char for '\0' to return an empty string */
594         char *str = calloc(1, ranges_count * (24 * sizeof(char)) + 1);
595         char *ptr = str;
596
597         for (unsigned int i = 0; i < ranges_count; i++) {
598                 ptr += range_print_one(&(ranges[i]), ptr);
599
600                 if (i < ranges_count - 1)
601                         *(ptr++) = ' ';
602         }
603
604         return str;
605 }
606
607 /* end of bitmap helper extension */
608
609 static inline bool stm32l4_is_otp(struct flash_bank *bank)
610 {
611         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
612         return bank->base == stm32l4_info->part_info->otp_base;
613 }
614
615 static int stm32l4_otp_enable(struct flash_bank *bank, bool enable)
616 {
617         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
618
619         if (!stm32l4_is_otp(bank))
620                 return ERROR_FAIL;
621
622         char *op_str = enable ? "enabled" : "disabled";
623
624         LOG_INFO("OTP memory (bank #%d) is %s%s for write commands",
625                         bank->bank_number,
626                         stm32l4_info->otp_enabled == enable ? "already " : "",
627                         op_str);
628
629         stm32l4_info->otp_enabled = enable;
630
631         return ERROR_OK;
632 }
633
634 static inline bool stm32l4_otp_is_enabled(struct flash_bank *bank)
635 {
636         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
637         return stm32l4_info->otp_enabled;
638 }
639
640 static void stm32l4_sync_rdp_tzen(struct flash_bank *bank)
641 {
642         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
643
644         bool tzen = false;
645
646         if (stm32l4_info->part_info->flags & F_HAS_TZ)
647                 tzen = (stm32l4_info->optr & FLASH_TZEN) != 0;
648
649         uint32_t rdp = stm32l4_info->optr & FLASH_RDP_MASK;
650
651         /* for devices without TrustZone:
652          *   RDP level 0 and 2 values are to 0xAA and 0xCC
653          *   Any other value corresponds to RDP level 1
654          * for devices with TrusZone:
655          *   RDP level 0 and 2 values are 0xAA and 0xCC
656          *   RDP level 0.5 value is 0x55 only if TZEN = 1
657          *   Any other value corresponds to RDP level 1, including 0x55 if TZEN = 0
658          */
659
660         if (rdp != RDP_LEVEL_0 && rdp != RDP_LEVEL_2) {
661                 if (!tzen || (tzen && rdp != RDP_LEVEL_0_5))
662                         rdp = RDP_LEVEL_1;
663         }
664
665         stm32l4_info->tzen = tzen;
666         stm32l4_info->rdp = rdp;
667 }
668
669 static inline uint32_t stm32l4_get_flash_reg(struct flash_bank *bank, uint32_t reg_offset)
670 {
671         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
672         return stm32l4_info->flash_regs_base + reg_offset;
673 }
674
675 static inline uint32_t stm32l4_get_flash_reg_by_index(struct flash_bank *bank,
676         enum stm32l4_flash_reg_index reg_index)
677 {
678         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
679         return stm32l4_get_flash_reg(bank, stm32l4_info->flash_regs[reg_index]);
680 }
681
682 static inline int stm32l4_read_flash_reg(struct flash_bank *bank, uint32_t reg_offset, uint32_t *value)
683 {
684         return target_read_u32(bank->target, stm32l4_get_flash_reg(bank, reg_offset), value);
685 }
686
687 static inline int stm32l4_read_flash_reg_by_index(struct flash_bank *bank,
688         enum stm32l4_flash_reg_index reg_index, uint32_t *value)
689 {
690         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
691         return stm32l4_read_flash_reg(bank, stm32l4_info->flash_regs[reg_index], value);
692 }
693
694 static inline int stm32l4_write_flash_reg(struct flash_bank *bank, uint32_t reg_offset, uint32_t value)
695 {
696         return target_write_u32(bank->target, stm32l4_get_flash_reg(bank, reg_offset), value);
697 }
698
699 static inline int stm32l4_write_flash_reg_by_index(struct flash_bank *bank,
700         enum stm32l4_flash_reg_index reg_index, uint32_t value)
701 {
702         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
703         return stm32l4_write_flash_reg(bank, stm32l4_info->flash_regs[reg_index], value);
704 }
705
706 static int stm32l4_wait_status_busy(struct flash_bank *bank, int timeout)
707 {
708         uint32_t status;
709         int retval = ERROR_OK;
710
711         /* wait for busy to clear */
712         for (;;) {
713                 retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_SR_INDEX, &status);
714                 if (retval != ERROR_OK)
715                         return retval;
716                 LOG_DEBUG("status: 0x%" PRIx32 "", status);
717                 if ((status & FLASH_BSY) == 0)
718                         break;
719                 if (timeout-- <= 0) {
720                         LOG_ERROR("timed out waiting for flash");
721                         return ERROR_FAIL;
722                 }
723                 alive_sleep(1);
724         }
725
726         if (status & FLASH_WRPERR) {
727                 LOG_ERROR("stm32x device protected");
728                 retval = ERROR_FAIL;
729         }
730
731         /* Clear but report errors */
732         if (status & FLASH_ERROR) {
733                 if (retval == ERROR_OK)
734                         retval = ERROR_FAIL;
735                 /* If this operation fails, we ignore it and report the original
736                  * retval
737                  */
738                 stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_SR_INDEX, status & FLASH_ERROR);
739         }
740
741         return retval;
742 }
743
744 /** set all FLASH_SECBB registers to the same value */
745 static int stm32l4_set_secbb(struct flash_bank *bank, uint32_t value)
746 {
747         /* This function should be used only with device with TrustZone, do just a security check */
748         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
749         assert(stm32l4_info->part_info->flags & F_HAS_TZ);
750
751         /* based on RM0438 Rev6 for STM32L5x devices:
752          * to modify a page block-based security attribution, it is recommended to
753          *  1- check that no flash operation is ongoing on the related page
754          *  2- add ISB instruction after modifying the page security attribute in SECBBxRy
755          *     this step is not need in case of JTAG direct access
756          */
757         int retval = stm32l4_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
758         if (retval != ERROR_OK)
759                 return retval;
760
761         /* write SECBBxRy registers */
762         LOG_DEBUG("setting secure block-based areas registers (SECBBxRy) to 0x%08x", value);
763
764         const uint8_t secbb_regs[] = {
765                         FLASH_SECBB1(1), FLASH_SECBB1(2), FLASH_SECBB1(3), FLASH_SECBB1(4), /* bank 1 SECBB register offsets */
766                         FLASH_SECBB2(1), FLASH_SECBB2(2), FLASH_SECBB2(3), FLASH_SECBB2(4)  /* bank 2 SECBB register offsets */
767         };
768
769
770         unsigned int num_secbb_regs = ARRAY_SIZE(secbb_regs);
771
772         /* in single bank mode, it's useless to modify FLASH_SECBB2Rx registers
773          * then consider only the first half of secbb_regs
774          */
775         if (!stm32l4_info->dual_bank_mode)
776                 num_secbb_regs /= 2;
777
778         for (unsigned int i = 0; i < num_secbb_regs; i++) {
779                 retval = stm32l4_write_flash_reg(bank, secbb_regs[i], value);
780                 if (retval != ERROR_OK)
781                         return retval;
782         }
783
784         return ERROR_OK;
785 }
786
787 static int stm32l4_unlock_reg(struct flash_bank *bank)
788 {
789         uint32_t ctrl;
790
791         /* first check if not already unlocked
792          * otherwise writing on STM32_FLASH_KEYR will fail
793          */
794         int retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, &ctrl);
795         if (retval != ERROR_OK)
796                 return retval;
797
798         if ((ctrl & FLASH_LOCK) == 0)
799                 return ERROR_OK;
800
801         /* unlock flash registers */
802         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_KEYR_INDEX, KEY1);
803         if (retval != ERROR_OK)
804                 return retval;
805
806         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_KEYR_INDEX, KEY2);
807         if (retval != ERROR_OK)
808                 return retval;
809
810         retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, &ctrl);
811         if (retval != ERROR_OK)
812                 return retval;
813
814         if (ctrl & FLASH_LOCK) {
815                 LOG_ERROR("flash not unlocked STM32_FLASH_CR: %" PRIx32, ctrl);
816                 return ERROR_TARGET_FAILURE;
817         }
818
819         return ERROR_OK;
820 }
821
822 static int stm32l4_unlock_option_reg(struct flash_bank *bank)
823 {
824         uint32_t ctrl;
825
826         int retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, &ctrl);
827         if (retval != ERROR_OK)
828                 return retval;
829
830         if ((ctrl & FLASH_OPTLOCK) == 0)
831                 return ERROR_OK;
832
833         /* unlock option registers */
834         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_OPTKEYR_INDEX, OPTKEY1);
835         if (retval != ERROR_OK)
836                 return retval;
837
838         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_OPTKEYR_INDEX, OPTKEY2);
839         if (retval != ERROR_OK)
840                 return retval;
841
842         retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, &ctrl);
843         if (retval != ERROR_OK)
844                 return retval;
845
846         if (ctrl & FLASH_OPTLOCK) {
847                 LOG_ERROR("options not unlocked STM32_FLASH_CR: %" PRIx32, ctrl);
848                 return ERROR_TARGET_FAILURE;
849         }
850
851         return ERROR_OK;
852 }
853
854 static int stm32l4_perform_obl_launch(struct flash_bank *bank)
855 {
856         int retval, retval2;
857
858         retval = stm32l4_unlock_reg(bank);
859         if (retval != ERROR_OK)
860                 goto err_lock;
861
862         retval = stm32l4_unlock_option_reg(bank);
863         if (retval != ERROR_OK)
864                 goto err_lock;
865
866         /* Set OBL_LAUNCH bit in CR -> system reset and option bytes reload,
867          * but the RMs explicitly do *NOT* list this as power-on reset cause, and:
868          * "Note: If the read protection is set while the debugger is still
869          * connected through JTAG/SWD, apply a POR (power-on reset) instead of a system reset."
870          */
871
872         /* "Setting OBL_LAUNCH generates a reset so the option byte loading is performed under system reset" */
873         /* Due to this reset ST-Link reports an SWD_DP_ERROR, despite the write was successful,
874          * then just ignore the returned value */
875         stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_OBL_LAUNCH);
876
877         /* Need to re-probe after change */
878         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
879         stm32l4_info->probed = false;
880
881 err_lock:
882         retval2 = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_LOCK | FLASH_OPTLOCK);
883
884         if (retval != ERROR_OK)
885                 return retval;
886
887         return retval2;
888 }
889
890 static int stm32l4_write_option(struct flash_bank *bank, uint32_t reg_offset,
891         uint32_t value, uint32_t mask)
892 {
893         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
894         uint32_t optiondata;
895         int retval, retval2;
896
897         retval = stm32l4_read_flash_reg(bank, reg_offset, &optiondata);
898         if (retval != ERROR_OK)
899                 return retval;
900
901         /* for STM32L5 and similar devices, use always non-secure
902          * registers for option bytes programming */
903         const uint32_t *saved_flash_regs = stm32l4_info->flash_regs;
904         if (stm32l4_info->part_info->flags & F_HAS_L5_FLASH_REGS)
905                 stm32l4_info->flash_regs = stm32l5_ns_flash_regs;
906
907         retval = stm32l4_unlock_reg(bank);
908         if (retval != ERROR_OK)
909                 goto err_lock;
910
911         retval = stm32l4_unlock_option_reg(bank);
912         if (retval != ERROR_OK)
913                 goto err_lock;
914
915         optiondata = (optiondata & ~mask) | (value & mask);
916
917         retval = stm32l4_write_flash_reg(bank, reg_offset, optiondata);
918         if (retval != ERROR_OK)
919                 goto err_lock;
920
921         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_OPTSTRT);
922         if (retval != ERROR_OK)
923                 goto err_lock;
924
925         retval = stm32l4_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
926
927 err_lock:
928         retval2 = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_LOCK | FLASH_OPTLOCK);
929         stm32l4_info->flash_regs = saved_flash_regs;
930
931         if (retval != ERROR_OK)
932                 return retval;
933
934         return retval2;
935 }
936
937 static int stm32l4_get_one_wrpxy(struct flash_bank *bank, struct stm32l4_wrp *wrpxy,
938                 enum stm32l4_flash_reg_index reg_idx, int offset)
939 {
940         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
941         int ret;
942
943         wrpxy->reg_idx = reg_idx;
944         wrpxy->offset = offset;
945
946         ret = stm32l4_read_flash_reg_by_index(bank, wrpxy->reg_idx , &wrpxy->value);
947         if (ret != ERROR_OK)
948                 return ret;
949
950         wrpxy->first = (wrpxy->value & stm32l4_info->wrpxxr_mask) + wrpxy->offset;
951         wrpxy->last = ((wrpxy->value >> 16) & stm32l4_info->wrpxxr_mask) + wrpxy->offset;
952         wrpxy->used = wrpxy->first <= wrpxy->last;
953
954         return ERROR_OK;
955 }
956
957 static int stm32l4_get_all_wrpxy(struct flash_bank *bank, enum stm32_bank_id dev_bank_id,
958                 struct stm32l4_wrp *wrpxy, unsigned int *n_wrp)
959 {
960         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
961         int ret;
962
963         *n_wrp = 0;
964
965         /* for single bank devices there is 2 WRP regions.
966          * for dual bank devices there is 2 WRP regions per bank,
967          *   if configured as single bank only 2 WRP are usable
968          *   except for STM32L4R/S/P/Q, G4 cat3, L5 ... all 4 WRP are usable
969          * note: this should be revised, if a device will have the SWAP banks option
970          */
971
972         int wrp2y_sectors_offset = -1; /* -1 : unused */
973
974         /* if bank_id is BANK1 or ALL_BANKS */
975         if (dev_bank_id != STM32_BANK2) {
976                 /* get FLASH_WRP1AR */
977                 ret = stm32l4_get_one_wrpxy(bank, &wrpxy[(*n_wrp)++], STM32_FLASH_WRP1AR_INDEX, 0);
978                 if (ret != ERROR_OK)
979                         return ret;
980
981                 /* get WRP1BR */
982                 ret = stm32l4_get_one_wrpxy(bank, &wrpxy[(*n_wrp)++], STM32_FLASH_WRP1BR_INDEX, 0);
983                 if (ret != ERROR_OK)
984                         return ret;
985
986                 /* for some devices (like STM32L4R/S) in single-bank mode, the 4 WRPxx are usable */
987                 if ((stm32l4_info->part_info->flags & F_USE_ALL_WRPXX) && !stm32l4_info->dual_bank_mode)
988                         wrp2y_sectors_offset = 0;
989         }
990
991         /* if bank_id is BANK2 or ALL_BANKS */
992         if (dev_bank_id != STM32_BANK1 && stm32l4_info->dual_bank_mode)
993                 wrp2y_sectors_offset = stm32l4_info->bank1_sectors;
994
995         if (wrp2y_sectors_offset > -1) {
996                 /* get WRP2AR */
997                 ret = stm32l4_get_one_wrpxy(bank, &wrpxy[(*n_wrp)++], STM32_FLASH_WRP2AR_INDEX, wrp2y_sectors_offset);
998                 if (ret != ERROR_OK)
999                         return ret;
1000
1001                 /* get WRP2BR */
1002                 ret = stm32l4_get_one_wrpxy(bank, &wrpxy[(*n_wrp)++], STM32_FLASH_WRP2BR_INDEX, wrp2y_sectors_offset);
1003                 if (ret != ERROR_OK)
1004                         return ret;
1005         }
1006
1007         return ERROR_OK;
1008 }
1009
1010 static int stm32l4_write_one_wrpxy(struct flash_bank *bank, struct stm32l4_wrp *wrpxy)
1011 {
1012         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1013
1014         int wrp_start = wrpxy->first - wrpxy->offset;
1015         int wrp_end = wrpxy->last - wrpxy->offset;
1016
1017         uint32_t wrp_value = (wrp_start & stm32l4_info->wrpxxr_mask) | ((wrp_end & stm32l4_info->wrpxxr_mask) << 16);
1018
1019         return stm32l4_write_option(bank, stm32l4_info->flash_regs[wrpxy->reg_idx], wrp_value, 0xffffffff);
1020 }
1021
1022 static int stm32l4_write_all_wrpxy(struct flash_bank *bank, struct stm32l4_wrp *wrpxy, unsigned int n_wrp)
1023 {
1024         int ret;
1025
1026         for (unsigned int i = 0; i < n_wrp; i++) {
1027                 ret = stm32l4_write_one_wrpxy(bank, &wrpxy[i]);
1028                 if (ret != ERROR_OK)
1029                         return ret;
1030         }
1031
1032         return ERROR_OK;
1033 }
1034
1035 static int stm32l4_protect_check(struct flash_bank *bank)
1036 {
1037         unsigned int n_wrp;
1038         struct stm32l4_wrp wrpxy[4];
1039
1040         int ret = stm32l4_get_all_wrpxy(bank, STM32_ALL_BANKS, wrpxy, &n_wrp);
1041         if (ret != ERROR_OK)
1042                 return ret;
1043
1044         /* initialize all sectors as unprotected */
1045         for (unsigned int i = 0; i < bank->num_sectors; i++)
1046                 bank->sectors[i].is_protected = 0;
1047
1048         /* now check WRPxy and mark the protected sectors */
1049         for (unsigned int i = 0; i < n_wrp; i++) {
1050                 if (wrpxy[i].used) {
1051                         for (int s = wrpxy[i].first; s <= wrpxy[i].last; s++)
1052                                 bank->sectors[s].is_protected = 1;
1053                 }
1054         }
1055
1056         return ERROR_OK;
1057 }
1058
1059 static int stm32l4_erase(struct flash_bank *bank, unsigned int first,
1060                 unsigned int last)
1061 {
1062         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1063         int retval, retval2;
1064
1065         assert((first <= last) && (last < bank->num_sectors));
1066
1067         if (stm32l4_is_otp(bank)) {
1068                 LOG_ERROR("cannot erase OTP memory");
1069                 return ERROR_FLASH_OPER_UNSUPPORTED;
1070         }
1071
1072         if (bank->target->state != TARGET_HALTED) {
1073                 LOG_ERROR("Target not halted");
1074                 return ERROR_TARGET_NOT_HALTED;
1075         }
1076
1077         if (stm32l4_info->tzen && (stm32l4_info->rdp == RDP_LEVEL_0)) {
1078                 /* set all FLASH pages as secure */
1079                 retval = stm32l4_set_secbb(bank, FLASH_SECBB_SECURE);
1080                 if (retval != ERROR_OK) {
1081                         /* restore all FLASH pages as non-secure */
1082                         stm32l4_set_secbb(bank, FLASH_SECBB_NON_SECURE); /* ignore the return value */
1083                         return retval;
1084                 }
1085         }
1086
1087         retval = stm32l4_unlock_reg(bank);
1088         if (retval != ERROR_OK)
1089                 goto err_lock;
1090
1091         /*
1092         Sector Erase
1093         To erase a sector, follow the procedure below:
1094         1. Check that no Flash memory operation is ongoing by
1095            checking the BSY bit in the FLASH_SR register
1096         2. Set the PER bit and select the page and bank
1097            you wish to erase in the FLASH_CR register
1098         3. Set the STRT bit in the FLASH_CR register
1099         4. Wait for the BSY bit to be cleared
1100          */
1101
1102         for (unsigned int i = first; i <= last; i++) {
1103                 uint32_t erase_flags;
1104                 erase_flags = FLASH_PER | FLASH_STRT;
1105
1106                 if (i >= stm32l4_info->bank1_sectors) {
1107                         uint8_t snb;
1108                         snb = i - stm32l4_info->bank1_sectors;
1109                         erase_flags |= snb << FLASH_PAGE_SHIFT | FLASH_CR_BKER;
1110                 } else
1111                         erase_flags |= i << FLASH_PAGE_SHIFT;
1112                 retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, erase_flags);
1113                 if (retval != ERROR_OK)
1114                         break;
1115
1116                 retval = stm32l4_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
1117                 if (retval != ERROR_OK)
1118                         break;
1119         }
1120
1121 err_lock:
1122         retval2 = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_LOCK);
1123
1124         if (stm32l4_info->tzen && (stm32l4_info->rdp == RDP_LEVEL_0)) {
1125                 /* restore all FLASH pages as non-secure */
1126                 int retval3 = stm32l4_set_secbb(bank, FLASH_SECBB_NON_SECURE);
1127                 if (retval3 != ERROR_OK)
1128                         return retval3;
1129         }
1130
1131         if (retval != ERROR_OK)
1132                 return retval;
1133
1134         return retval2;
1135 }
1136
1137 static int stm32l4_protect(struct flash_bank *bank, int set, unsigned int first, unsigned int last)
1138 {
1139         struct target *target = bank->target;
1140         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1141         int ret = ERROR_OK;
1142         unsigned int i;
1143
1144         if (stm32l4_is_otp(bank)) {
1145                 LOG_ERROR("cannot protect/unprotect OTP memory");
1146                 return ERROR_FLASH_OPER_UNSUPPORTED;
1147         }
1148
1149         if (target->state != TARGET_HALTED) {
1150                 LOG_ERROR("Target not halted");
1151                 return ERROR_TARGET_NOT_HALTED;
1152         }
1153
1154         /* the requested sectors could be located into bank1 and/or bank2 */
1155         bool use_bank2 = false;
1156         if (last >= stm32l4_info->bank1_sectors) {
1157                 if (first < stm32l4_info->bank1_sectors) {
1158                         /* the requested sectors for (un)protection are shared between
1159                          * bank 1 and 2, then split the operation */
1160
1161                         /*  1- deal with bank 1 sectors */
1162                         LOG_DEBUG("The requested sectors for %s are shared between bank 1 and 2",
1163                                         set ? "protection" : "unprotection");
1164                         ret = stm32l4_protect(bank, set, first, stm32l4_info->bank1_sectors - 1);
1165                         if (ret != ERROR_OK)
1166                                 return ret;
1167
1168                         /*  2- then continue with bank 2 sectors */
1169                         first = stm32l4_info->bank1_sectors;
1170                 }
1171
1172                 use_bank2 = true;
1173         }
1174
1175         /* refresh the sectors' protection */
1176         ret = stm32l4_protect_check(bank);
1177         if (ret != ERROR_OK)
1178                 return ret;
1179
1180         /* check if the desired protection is already configured */
1181         for (i = first; i <= last; i++) {
1182                 if (bank->sectors[i].is_protected != set)
1183                         break;
1184                 else if (i == last) {
1185                         LOG_INFO("The specified sectors are already %s", set ? "protected" : "unprotected");
1186                         return ERROR_OK;
1187                 }
1188         }
1189
1190         /* all sectors from first to last (or part of them) could have different
1191          * protection other than the requested */
1192         unsigned int n_wrp;
1193         struct stm32l4_wrp wrpxy[4];
1194
1195         ret = stm32l4_get_all_wrpxy(bank, use_bank2 ? STM32_BANK2 : STM32_BANK1, wrpxy, &n_wrp);
1196         if (ret != ERROR_OK)
1197                 return ret;
1198
1199         /* use bitmap and range helpers to optimize the WRP usage */
1200         DECLARE_BITMAP(pages, bank->num_sectors);
1201         bitmap_zero(pages, bank->num_sectors);
1202
1203         for (i = 0; i < n_wrp; i++) {
1204                 if (wrpxy[i].used) {
1205                         for (int p = wrpxy[i].first; p <= wrpxy[i].last; p++)
1206                                 set_bit(p, pages);
1207                 }
1208         }
1209
1210         /* we have at most 'n_wrp' WRP areas
1211          * add one range if the user is trying to protect a fifth range */
1212         struct range ranges[n_wrp + 1];
1213         unsigned int ranges_count = 0;
1214
1215         bitmap_to_ranges(pages, bank->num_sectors, ranges, &ranges_count);
1216
1217         /* pretty-print the currently protected ranges */
1218         if (ranges_count > 0) {
1219                 char *ranges_str = range_print_alloc(ranges, ranges_count);
1220                 LOG_DEBUG("current protected areas: %s", ranges_str);
1221                 free(ranges_str);
1222         } else
1223                 LOG_DEBUG("current protected areas: none");
1224
1225         if (set) { /* flash protect */
1226                 for (i = first; i <= last; i++)
1227                         set_bit(i, pages);
1228         } else { /* flash unprotect */
1229                 for (i = first; i <= last; i++)
1230                         clear_bit(i, pages);
1231         }
1232
1233         /* check the ranges_count after the user request */
1234         bitmap_to_ranges(pages, bank->num_sectors, ranges, &ranges_count);
1235
1236         /* pretty-print the requested areas for protection */
1237         if (ranges_count > 0) {
1238                 char *ranges_str = range_print_alloc(ranges, ranges_count);
1239                 LOG_DEBUG("requested areas for protection: %s", ranges_str);
1240                 free(ranges_str);
1241         } else
1242                 LOG_DEBUG("requested areas for protection: none");
1243
1244         if (ranges_count > n_wrp) {
1245                 LOG_ERROR("cannot set the requested protection "
1246                                 "(only %u write protection areas are available)" , n_wrp);
1247                 return ERROR_FAIL;
1248         }
1249
1250         /* re-init all WRPxy as disabled (first > last)*/
1251         for (i = 0; i < n_wrp; i++) {
1252                 wrpxy[i].first = wrpxy[i].offset + 1;
1253                 wrpxy[i].last = wrpxy[i].offset;
1254         }
1255
1256         /* then configure WRPxy areas */
1257         for (i = 0; i < ranges_count; i++) {
1258                 wrpxy[i].first = ranges[i].start;
1259                 wrpxy[i].last = ranges[i].end;
1260         }
1261
1262         /* finally write WRPxy registers */
1263         return stm32l4_write_all_wrpxy(bank, wrpxy, n_wrp);
1264 }
1265
1266 /* Count is in double-words */
1267 static int stm32l4_write_block(struct flash_bank *bank, const uint8_t *buffer,
1268         uint32_t offset, uint32_t count)
1269 {
1270         struct target *target = bank->target;
1271         uint32_t buffer_size;
1272         struct working_area *write_algorithm;
1273         struct working_area *source;
1274         uint32_t address = bank->base + offset;
1275         struct reg_param reg_params[6];
1276         struct armv7m_algorithm armv7m_info;
1277         int retval = ERROR_OK;
1278
1279         static const uint8_t stm32l4_flash_write_code[] = {
1280 #include "../../../contrib/loaders/flash/stm32/stm32l4x.inc"
1281         };
1282
1283         if (target_alloc_working_area(target, sizeof(stm32l4_flash_write_code),
1284                         &write_algorithm) != ERROR_OK) {
1285                 LOG_WARNING("no working area available, can't do block memory writes");
1286                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1287         }
1288
1289         retval = target_write_buffer(target, write_algorithm->address,
1290                         sizeof(stm32l4_flash_write_code),
1291                         stm32l4_flash_write_code);
1292         if (retval != ERROR_OK) {
1293                 target_free_working_area(target, write_algorithm);
1294                 return retval;
1295         }
1296
1297         /* memory buffer, size *must* be multiple of dword plus one dword for rp and one for wp */
1298         buffer_size = target_get_working_area_avail(target) & ~(2 * sizeof(uint32_t) - 1);
1299         if (buffer_size < 256) {
1300                 LOG_WARNING("large enough working area not available, can't do block memory writes");
1301                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1302         } else if (buffer_size > 16384) {
1303                 /* probably won't benefit from more than 16k ... */
1304                 buffer_size = 16384;
1305         }
1306
1307         if (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) {
1308                 LOG_ERROR("allocating working area failed");
1309                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1310         }
1311
1312         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
1313         armv7m_info.core_mode = ARM_MODE_THREAD;
1314
1315         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT); /* buffer start, status (out) */
1316         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);    /* buffer end */
1317         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);    /* target address */
1318         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);    /* count (double word-64bit) */
1319         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);    /* flash status register */
1320         init_reg_param(&reg_params[5], "r5", 32, PARAM_OUT);    /* flash control register */
1321
1322         buf_set_u32(reg_params[0].value, 0, 32, source->address);
1323         buf_set_u32(reg_params[1].value, 0, 32, source->address + source->size);
1324         buf_set_u32(reg_params[2].value, 0, 32, address);
1325         buf_set_u32(reg_params[3].value, 0, 32, count);
1326         buf_set_u32(reg_params[4].value, 0, 32, stm32l4_get_flash_reg_by_index(bank, STM32_FLASH_SR_INDEX));
1327         buf_set_u32(reg_params[5].value, 0, 32, stm32l4_get_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX));
1328
1329         retval = target_run_flash_async_algorithm(target, buffer, count, 8,
1330                         0, NULL,
1331                         ARRAY_SIZE(reg_params), reg_params,
1332                         source->address, source->size,
1333                         write_algorithm->address, 0,
1334                         &armv7m_info);
1335
1336         if (retval == ERROR_FLASH_OPERATION_FAILED) {
1337                 LOG_ERROR("error executing stm32l4 flash write algorithm");
1338
1339                 uint32_t error = buf_get_u32(reg_params[0].value, 0, 32) & FLASH_ERROR;
1340
1341                 if (error & FLASH_WRPERR)
1342                         LOG_ERROR("flash memory write protected");
1343
1344                 if (error != 0) {
1345                         LOG_ERROR("flash write failed = %08" PRIx32, error);
1346                         /* Clear but report errors */
1347                         stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_SR_INDEX, error);
1348                         retval = ERROR_FAIL;
1349                 }
1350         }
1351
1352         target_free_working_area(target, source);
1353         target_free_working_area(target, write_algorithm);
1354
1355         destroy_reg_param(&reg_params[0]);
1356         destroy_reg_param(&reg_params[1]);
1357         destroy_reg_param(&reg_params[2]);
1358         destroy_reg_param(&reg_params[3]);
1359         destroy_reg_param(&reg_params[4]);
1360         destroy_reg_param(&reg_params[5]);
1361
1362         return retval;
1363 }
1364
1365 static int stm32l4_write(struct flash_bank *bank, const uint8_t *buffer,
1366         uint32_t offset, uint32_t count)
1367 {
1368         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1369         int retval = ERROR_OK, retval2;
1370
1371         if (stm32l4_is_otp(bank) && !stm32l4_otp_is_enabled(bank)) {
1372                 LOG_ERROR("OTP memory is disabled for write commands");
1373                 return ERROR_FAIL;
1374         }
1375
1376         if (bank->target->state != TARGET_HALTED) {
1377                 LOG_ERROR("Target not halted");
1378                 return ERROR_TARGET_NOT_HALTED;
1379         }
1380
1381         /* The flash write must be aligned to a double word (8-bytes) boundary.
1382          * The flash infrastructure ensures it, do just a security check */
1383         assert(offset % 8 == 0);
1384         assert(count % 8 == 0);
1385
1386         /* STM32G4xxx Cat. 3 devices may have gaps between banks, check whether
1387          * data to be written does not go into a gap:
1388          * suppose buffer is fully contained in bank from sector 0 to sector
1389          * num->sectors - 1 and sectors are ordered according to offset
1390          */
1391         struct flash_sector *head = &bank->sectors[0];
1392         struct flash_sector *tail = &bank->sectors[bank->num_sectors - 1];
1393
1394         while ((head < tail) && (offset >= (head + 1)->offset)) {
1395                 /* buffer does not intersect head nor gap behind head */
1396                 head++;
1397         }
1398
1399         while ((head < tail) && (offset + count <= (tail - 1)->offset + (tail - 1)->size)) {
1400                 /* buffer does not intersect tail nor gap before tail */
1401                 --tail;
1402         }
1403
1404         LOG_DEBUG("data: 0x%08" PRIx32 " - 0x%08" PRIx32 ", sectors: 0x%08" PRIx32 " - 0x%08" PRIx32,
1405                 offset, offset + count - 1, head->offset, tail->offset + tail->size - 1);
1406
1407         /* Now check that there is no gap from head to tail, this should work
1408          * even for multiple or non-symmetric gaps
1409          */
1410         while (head < tail) {
1411                 if (head->offset + head->size != (head + 1)->offset) {
1412                         LOG_ERROR("write into gap from " TARGET_ADDR_FMT " to " TARGET_ADDR_FMT,
1413                                 bank->base + head->offset + head->size,
1414                                 bank->base + (head + 1)->offset - 1);
1415                         retval = ERROR_FLASH_DST_OUT_OF_BANK;
1416                 }
1417                 head++;
1418         }
1419
1420         if (retval != ERROR_OK)
1421                 return retval;
1422
1423         if (stm32l4_info->tzen && (stm32l4_info->rdp == RDP_LEVEL_0)) {
1424                 /* set all FLASH pages as secure */
1425                 retval = stm32l4_set_secbb(bank, FLASH_SECBB_SECURE);
1426                 if (retval != ERROR_OK) {
1427                         /* restore all FLASH pages as non-secure */
1428                         stm32l4_set_secbb(bank, FLASH_SECBB_NON_SECURE); /* ignore the return value */
1429                         return retval;
1430                 }
1431         }
1432
1433         retval = stm32l4_unlock_reg(bank);
1434         if (retval != ERROR_OK)
1435                 goto err_lock;
1436
1437         /* For TrustZone enabled devices, when TZEN is set and RDP level is 0.5,
1438          * the debug is possible only in non-secure state.
1439          * Thus means the flashloader will run in non-secure mode,
1440          * and the workarea need to be in non-secure RAM */
1441         if (stm32l4_info->tzen && (stm32l4_info->rdp == RDP_LEVEL_0_5))
1442                 LOG_INFO("RDP level is 0.5, the work-area should reside in non-secure RAM");
1443
1444         retval = stm32l4_write_block(bank, buffer, offset, count / 8);
1445
1446 err_lock:
1447         retval2 = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_LOCK);
1448
1449         if (stm32l4_info->tzen && (stm32l4_info->rdp == RDP_LEVEL_0)) {
1450                 /* restore all FLASH pages as non-secure */
1451                 int retval3 = stm32l4_set_secbb(bank, FLASH_SECBB_NON_SECURE);
1452                 if (retval3 != ERROR_OK)
1453                         return retval3;
1454         }
1455
1456         if (retval != ERROR_OK) {
1457                 LOG_ERROR("block write failed");
1458                 return retval;
1459         }
1460         return retval2;
1461 }
1462
1463 static int stm32l4_read_idcode(struct flash_bank *bank, uint32_t *id)
1464 {
1465         int retval;
1466
1467         /* try reading possible IDCODE registers, in the following order */
1468         uint32_t dbgmcu_idcode[] = {DBGMCU_IDCODE_L4_G4, DBGMCU_IDCODE_G0, DBGMCU_IDCODE_L5};
1469
1470         for (unsigned int i = 0; i < ARRAY_SIZE(dbgmcu_idcode); i++) {
1471                 retval = target_read_u32(bank->target, dbgmcu_idcode[i], id);
1472                 if ((retval == ERROR_OK) && ((*id & 0xfff) != 0) && ((*id & 0xfff) != 0xfff))
1473                         return ERROR_OK;
1474         }
1475
1476         LOG_ERROR("can't get the device id");
1477         return (retval == ERROR_OK) ? ERROR_FAIL : retval;
1478 }
1479
1480 static const char *get_stm32l4_rev_str(struct flash_bank *bank)
1481 {
1482         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1483         const struct stm32l4_part_info *part_info = stm32l4_info->part_info;
1484         assert(part_info);
1485
1486         const uint16_t rev_id = stm32l4_info->idcode >> 16;
1487         for (unsigned int i = 0; i < part_info->num_revs; i++) {
1488                 if (rev_id == part_info->revs[i].rev)
1489                         return part_info->revs[i].str;
1490         }
1491         return "'unknown'";
1492 }
1493
1494 static const char *get_stm32l4_bank_type_str(struct flash_bank *bank)
1495 {
1496         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1497         assert(stm32l4_info->part_info);
1498         return stm32l4_is_otp(bank) ? "OTP" :
1499                         stm32l4_info->dual_bank_mode ? "Flash dual" :
1500                         "Flash single";
1501 }
1502
1503 static int stm32l4_probe(struct flash_bank *bank)
1504 {
1505         struct target *target = bank->target;
1506         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1507         const struct stm32l4_part_info *part_info;
1508         uint16_t flash_size_kb = 0xffff;
1509
1510         stm32l4_info->probed = false;
1511
1512         /* read stm32 device id registers */
1513         int retval = stm32l4_read_idcode(bank, &stm32l4_info->idcode);
1514         if (retval != ERROR_OK)
1515                 return retval;
1516
1517         const uint32_t device_id = stm32l4_info->idcode & 0xFFF;
1518
1519         for (unsigned int n = 0; n < ARRAY_SIZE(stm32l4_parts); n++) {
1520                 if (device_id == stm32l4_parts[n].id) {
1521                         stm32l4_info->part_info = &stm32l4_parts[n];
1522                         break;
1523                 }
1524         }
1525
1526         if (!stm32l4_info->part_info) {
1527                 LOG_WARNING("Cannot identify target as an %s family device.", device_families);
1528                 return ERROR_FAIL;
1529         }
1530
1531         part_info = stm32l4_info->part_info;
1532         const char *rev_str = get_stm32l4_rev_str(bank);
1533         const uint16_t rev_id = stm32l4_info->idcode >> 16;
1534
1535         LOG_INFO("device idcode = 0x%08" PRIx32 " (%s - Rev %s : 0x%04x)",
1536                         stm32l4_info->idcode, part_info->device_str, rev_str, rev_id);
1537
1538         stm32l4_info->flash_regs_base = stm32l4_info->part_info->flash_regs_base;
1539         stm32l4_info->flash_regs = stm32l4_info->part_info->default_flash_regs;
1540
1541         /* read flash option register */
1542         retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_OPTR_INDEX, &stm32l4_info->optr);
1543         if (retval != ERROR_OK)
1544                 return retval;
1545
1546         stm32l4_sync_rdp_tzen(bank);
1547
1548         if (part_info->flags & F_HAS_TZ)
1549                 LOG_INFO("TZEN = %d : TrustZone %s by option bytes",
1550                                 stm32l4_info->tzen,
1551                                 stm32l4_info->tzen ? "enabled" : "disabled");
1552
1553         LOG_INFO("RDP level %s (0x%02X)",
1554                         stm32l4_info->rdp == RDP_LEVEL_0 ? "0" : stm32l4_info->rdp == RDP_LEVEL_0_5 ? "0.5" : "1",
1555                         stm32l4_info->rdp);
1556
1557         if (stm32l4_is_otp(bank)) {
1558                 bank->size = part_info->otp_size;
1559
1560                 LOG_INFO("OTP size is %d bytes, base address is " TARGET_ADDR_FMT, bank->size, bank->base);
1561
1562                 /* OTP memory is considered as one sector */
1563                 free(bank->sectors);
1564                 bank->num_sectors = 1;
1565                 bank->sectors = alloc_block_array(0, part_info->otp_size, 1);
1566
1567                 if (!bank->sectors) {
1568                         LOG_ERROR("failed to allocate bank sectors");
1569                         return ERROR_FAIL;
1570                 }
1571
1572                 stm32l4_info->probed = true;
1573                 return ERROR_OK;
1574         } else if (bank->base != STM32_FLASH_BANK_BASE && bank->base != STM32_FLASH_S_BANK_BASE) {
1575                 LOG_ERROR("invalid bank base address");
1576                 return ERROR_FAIL;
1577         }
1578
1579         /* get flash size from target. */
1580         retval = target_read_u16(target, part_info->fsize_addr, &flash_size_kb);
1581
1582         /* failed reading flash size or flash size invalid (early silicon),
1583          * default to max target family */
1584         if (retval != ERROR_OK || flash_size_kb == 0xffff || flash_size_kb == 0
1585                         || flash_size_kb > part_info->max_flash_size_kb) {
1586                 LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming %dk flash",
1587                         part_info->max_flash_size_kb);
1588                 flash_size_kb = part_info->max_flash_size_kb;
1589         }
1590
1591         /* if the user sets the size manually then ignore the probed value
1592          * this allows us to work around devices that have a invalid flash size register value */
1593         if (stm32l4_info->user_bank_size) {
1594                 LOG_WARNING("overriding size register by configured bank size - MAY CAUSE TROUBLE");
1595                 flash_size_kb = stm32l4_info->user_bank_size / 1024;
1596         }
1597
1598         LOG_INFO("flash size = %dkbytes", flash_size_kb);
1599
1600         /* did we assign a flash size? */
1601         assert((flash_size_kb != 0xffff) && flash_size_kb);
1602
1603         stm32l4_info->bank1_sectors = 0;
1604         stm32l4_info->hole_sectors = 0;
1605
1606         int num_pages = 0;
1607         int page_size_kb = 0;
1608
1609         stm32l4_info->dual_bank_mode = false;
1610         bool use_dbank_bit = false;
1611
1612         switch (device_id) {
1613         case 0x415: /* STM32L47/L48xx */
1614         case 0x461: /* STM32L49/L4Axx */
1615                 /* if flash size is max (1M) the device is always dual bank
1616                  * 0x415: has variants with 512K
1617                  * 0x461: has variants with 512 and 256
1618                  * for these variants:
1619                  *   if DUAL_BANK = 0 -> single bank
1620                  *   else -> dual bank without gap
1621                  * note: the page size is invariant
1622                  */
1623                 page_size_kb = 2;
1624                 num_pages = flash_size_kb / page_size_kb;
1625                 stm32l4_info->bank1_sectors = num_pages;
1626
1627                 /* check DUAL_BANK bit[21] if the flash is less than 1M */
1628                 if (flash_size_kb == 1024 || (stm32l4_info->optr & BIT(21))) {
1629                         stm32l4_info->dual_bank_mode = true;
1630                         stm32l4_info->bank1_sectors = num_pages / 2;
1631                 }
1632                 break;
1633         case 0x435: /* STM32L43/L44xx */
1634         case 0x460: /* STM32G07/G08xx */
1635         case 0x462: /* STM32L45/L46xx */
1636         case 0x464: /* STM32L41/L42xx */
1637         case 0x466: /* STM32G03/G04xx */
1638         case 0x468: /* STM32G43/G44xx */
1639         case 0x479: /* STM32G49/G4Axx */
1640         case 0x497: /* STM32WLEx */
1641                 /* single bank flash */
1642                 page_size_kb = 2;
1643                 num_pages = flash_size_kb / page_size_kb;
1644                 stm32l4_info->bank1_sectors = num_pages;
1645                 break;
1646         case 0x469: /* STM32G47/G48xx */
1647                 /* STM32G47/8 can be single/dual bank:
1648                  *   if DUAL_BANK = 0 -> single bank
1649                  *   else -> dual bank WITH gap
1650                  */
1651                 page_size_kb = 4;
1652                 num_pages = flash_size_kb / page_size_kb;
1653                 stm32l4_info->bank1_sectors = num_pages;
1654                 if (stm32l4_info->optr & BIT(22)) {
1655                         stm32l4_info->dual_bank_mode = true;
1656                         page_size_kb = 2;
1657                         num_pages = flash_size_kb / page_size_kb;
1658                         stm32l4_info->bank1_sectors = num_pages / 2;
1659
1660                         /* for devices with trimmed flash, there is a gap between both banks */
1661                         stm32l4_info->hole_sectors =
1662                                 (part_info->max_flash_size_kb - flash_size_kb) / (2 * page_size_kb);
1663                 }
1664                 break;
1665         case 0x470: /* STM32L4R/L4Sxx */
1666         case 0x471: /* STM32L4P5/L4Q5x */
1667                 /* STM32L4R/S can be single/dual bank:
1668                  *   if size = 2M check DBANK bit(22)
1669                  *   if size = 1M check DB1M bit(21)
1670                  * STM32L4P/Q can be single/dual bank
1671                  *   if size = 1M check DBANK bit(22)
1672                  *   if size = 512K check DB512K bit(21)
1673                  */
1674                 page_size_kb = 8;
1675                 num_pages = flash_size_kb / page_size_kb;
1676                 stm32l4_info->bank1_sectors = num_pages;
1677                 use_dbank_bit = flash_size_kb == part_info->max_flash_size_kb;
1678                 if ((use_dbank_bit && (stm32l4_info->optr & BIT(22))) ||
1679                         (!use_dbank_bit && (stm32l4_info->optr & BIT(21)))) {
1680                         stm32l4_info->dual_bank_mode = true;
1681                         page_size_kb = 4;
1682                         num_pages = flash_size_kb / page_size_kb;
1683                         stm32l4_info->bank1_sectors = num_pages / 2;
1684                 }
1685                 break;
1686         case 0x472: /* STM32L55/L56xx */
1687                 /* STM32L55/L56xx can be single/dual bank:
1688                  *   if size = 512K check DBANK bit(22)
1689                  *   if size = 256K check DB256K bit(21)
1690                  */
1691                 page_size_kb = 4;
1692                 num_pages = flash_size_kb / page_size_kb;
1693                 stm32l4_info->bank1_sectors = num_pages;
1694                 use_dbank_bit = flash_size_kb == part_info->max_flash_size_kb;
1695                 if ((use_dbank_bit && (stm32l4_info->optr & BIT(22))) ||
1696                         (!use_dbank_bit && (stm32l4_info->optr & BIT(21)))) {
1697                         stm32l4_info->dual_bank_mode = true;
1698                         page_size_kb = 2;
1699                         num_pages = flash_size_kb / page_size_kb;
1700                         stm32l4_info->bank1_sectors = num_pages / 2;
1701                 }
1702
1703                 /**
1704                  * by default use the non-secure registers,
1705                  * switch secure registers if TZ is enabled and RDP is LEVEL_0
1706                  */
1707                 if (stm32l4_info->tzen && (stm32l4_info->rdp == RDP_LEVEL_0)) {
1708                         stm32l4_info->flash_regs_base |= 0x10000000;
1709                         stm32l4_info->flash_regs = stm32l5_s_flash_regs;
1710                 }
1711                 break;
1712         case 0x495: /* STM32WB5x */
1713         case 0x496: /* STM32WB3x */
1714                 /* single bank flash */
1715                 page_size_kb = 4;
1716                 num_pages = flash_size_kb / page_size_kb;
1717                 stm32l4_info->bank1_sectors = num_pages;
1718                 break;
1719         default:
1720                 LOG_ERROR("unsupported device");
1721                 return ERROR_FAIL;
1722         }
1723
1724         LOG_INFO("flash mode : %s-bank", stm32l4_info->dual_bank_mode ? "dual" : "single");
1725
1726         const int gap_size_kb = stm32l4_info->hole_sectors * page_size_kb;
1727
1728         if (gap_size_kb != 0) {
1729                 LOG_INFO("gap detected from 0x%08x to 0x%08x",
1730                         STM32_FLASH_BANK_BASE + stm32l4_info->bank1_sectors
1731                                 * page_size_kb * 1024,
1732                         STM32_FLASH_BANK_BASE + (stm32l4_info->bank1_sectors
1733                                 * page_size_kb + gap_size_kb) * 1024 - 1);
1734         }
1735
1736         /* number of significant bits in WRPxxR differs per device,
1737          * always right adjusted, on some devices non-implemented
1738          * bits read as '0', on others as '1' ...
1739          * notably G4 Cat. 2 implement only 6 bits, contradicting the RM
1740          */
1741
1742         /* use *max_flash_size* instead of actual size as the trimmed versions
1743          * certainly use the same number of bits
1744          * max_flash_size is always power of two, so max_pages too
1745          */
1746         uint32_t max_pages = stm32l4_info->part_info->max_flash_size_kb / page_size_kb;
1747         assert(IS_PWR_OF_2(max_pages));
1748
1749         /* in dual bank mode number of pages is doubled, but extra bit is bank selection */
1750         stm32l4_info->wrpxxr_mask = ((max_pages >> (stm32l4_info->dual_bank_mode ? 1 : 0)) - 1);
1751         assert((stm32l4_info->wrpxxr_mask & 0xFFFF0000) == 0);
1752         LOG_DEBUG("WRPxxR mask 0x%04" PRIx16, (uint16_t)stm32l4_info->wrpxxr_mask);
1753
1754         free(bank->sectors);
1755
1756         bank->size = (flash_size_kb + gap_size_kb) * 1024;
1757         bank->num_sectors = num_pages;
1758         bank->sectors = malloc(sizeof(struct flash_sector) * bank->num_sectors);
1759         if (!bank->sectors) {
1760                 LOG_ERROR("failed to allocate bank sectors");
1761                 return ERROR_FAIL;
1762         }
1763
1764         for (unsigned int i = 0; i < bank->num_sectors; i++) {
1765                 bank->sectors[i].offset = i * page_size_kb * 1024;
1766                 /* in dual bank configuration, if there is a gap between banks
1767                  * we fix up the sector offset to consider this gap */
1768                 if (i >= stm32l4_info->bank1_sectors && stm32l4_info->hole_sectors)
1769                         bank->sectors[i].offset += gap_size_kb * 1024;
1770                 bank->sectors[i].size = page_size_kb * 1024;
1771                 bank->sectors[i].is_erased = -1;
1772                 bank->sectors[i].is_protected = 1;
1773         }
1774
1775         stm32l4_info->probed = true;
1776         return ERROR_OK;
1777 }
1778
1779 static int stm32l4_auto_probe(struct flash_bank *bank)
1780 {
1781         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1782         if (stm32l4_info->probed) {
1783                 uint32_t optr_cur;
1784
1785                 /* read flash option register and re-probe if optr value is changed */
1786                 int retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_OPTR_INDEX, &optr_cur);
1787                 if (retval != ERROR_OK)
1788                         return retval;
1789
1790                 if (stm32l4_info->optr == optr_cur)
1791                         return ERROR_OK;
1792         }
1793
1794         return stm32l4_probe(bank);
1795 }
1796
1797 static int get_stm32l4_info(struct flash_bank *bank, struct command_invocation *cmd)
1798 {
1799         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1800         const struct stm32l4_part_info *part_info = stm32l4_info->part_info;
1801
1802         if (part_info) {
1803                 const uint16_t rev_id = stm32l4_info->idcode >> 16;
1804                 command_print_sameline(cmd, "%s - Rev %s : 0x%04x", part_info->device_str,
1805                                 get_stm32l4_rev_str(bank), rev_id);
1806                 if (stm32l4_info->probed)
1807                         command_print_sameline(cmd, " - %s-bank", get_stm32l4_bank_type_str(bank));
1808         } else {
1809                 command_print_sameline(cmd, "Cannot identify target as an %s device", device_families);
1810         }
1811
1812         return ERROR_OK;
1813 }
1814
1815 static int stm32l4_mass_erase(struct flash_bank *bank)
1816 {
1817         int retval, retval2;
1818         struct target *target = bank->target;
1819         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1820
1821         if (stm32l4_is_otp(bank)) {
1822                 LOG_ERROR("cannot erase OTP memory");
1823                 return ERROR_FLASH_OPER_UNSUPPORTED;
1824         }
1825
1826         uint32_t action = FLASH_MER1;
1827
1828         if (stm32l4_info->part_info->flags & F_HAS_DUAL_BANK)
1829                 action |= FLASH_MER2;
1830
1831         if (target->state != TARGET_HALTED) {
1832                 LOG_ERROR("Target not halted");
1833                 return ERROR_TARGET_NOT_HALTED;
1834         }
1835
1836         if (stm32l4_info->tzen && (stm32l4_info->rdp == RDP_LEVEL_0)) {
1837                 /* set all FLASH pages as secure */
1838                 retval = stm32l4_set_secbb(bank, FLASH_SECBB_SECURE);
1839                 if (retval != ERROR_OK) {
1840                         /* restore all FLASH pages as non-secure */
1841                         stm32l4_set_secbb(bank, FLASH_SECBB_NON_SECURE); /* ignore the return value */
1842                         return retval;
1843                 }
1844         }
1845
1846         retval = stm32l4_unlock_reg(bank);
1847         if (retval != ERROR_OK)
1848                 goto err_lock;
1849
1850         /* mass erase flash memory */
1851         retval = stm32l4_wait_status_busy(bank, FLASH_ERASE_TIMEOUT / 10);
1852         if (retval != ERROR_OK)
1853                 goto err_lock;
1854
1855         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, action);
1856         if (retval != ERROR_OK)
1857                 goto err_lock;
1858
1859         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, action | FLASH_STRT);
1860         if (retval != ERROR_OK)
1861                 goto err_lock;
1862
1863         retval = stm32l4_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
1864
1865 err_lock:
1866         retval2 = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_LOCK);
1867
1868         if (stm32l4_info->tzen && (stm32l4_info->rdp == RDP_LEVEL_0)) {
1869                 /* restore all FLASH pages as non-secure */
1870                 int retval3 = stm32l4_set_secbb(bank, FLASH_SECBB_NON_SECURE);
1871                 if (retval3 != ERROR_OK)
1872                         return retval3;
1873         }
1874
1875         if (retval != ERROR_OK)
1876                 return retval;
1877
1878         return retval2;
1879 }
1880
1881 COMMAND_HANDLER(stm32l4_handle_mass_erase_command)
1882 {
1883         if (CMD_ARGC < 1) {
1884                 command_print(CMD, "stm32l4x mass_erase <STM32L4 bank>");
1885                 return ERROR_COMMAND_SYNTAX_ERROR;
1886         }
1887
1888         struct flash_bank *bank;
1889         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1890         if (retval != ERROR_OK)
1891                 return retval;
1892
1893         retval = stm32l4_mass_erase(bank);
1894         if (retval == ERROR_OK)
1895                 command_print(CMD, "stm32l4x mass erase complete");
1896         else
1897                 command_print(CMD, "stm32l4x mass erase failed");
1898
1899         return retval;
1900 }
1901
1902 COMMAND_HANDLER(stm32l4_handle_option_read_command)
1903 {
1904         if (CMD_ARGC < 2) {
1905                 command_print(CMD, "stm32l4x option_read <STM32L4 bank> <option_reg offset>");
1906                 return ERROR_COMMAND_SYNTAX_ERROR;
1907         }
1908
1909         struct flash_bank *bank;
1910         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1911         if (retval != ERROR_OK)
1912                 return retval;
1913
1914         uint32_t reg_offset, reg_addr;
1915         uint32_t value = 0;
1916
1917         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], reg_offset);
1918         reg_addr = stm32l4_get_flash_reg(bank, reg_offset);
1919
1920         retval = stm32l4_read_flash_reg(bank, reg_offset, &value);
1921         if (retval != ERROR_OK)
1922                 return retval;
1923
1924         command_print(CMD, "Option Register: <0x%" PRIx32 "> = 0x%" PRIx32 "", reg_addr, value);
1925
1926         return retval;
1927 }
1928
1929 COMMAND_HANDLER(stm32l4_handle_option_write_command)
1930 {
1931         if (CMD_ARGC < 3) {
1932                 command_print(CMD, "stm32l4x option_write <STM32L4 bank> <option_reg offset> <value> [mask]");
1933                 return ERROR_COMMAND_SYNTAX_ERROR;
1934         }
1935
1936         struct flash_bank *bank;
1937         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1938         if (retval != ERROR_OK)
1939                 return retval;
1940
1941         uint32_t reg_offset;
1942         uint32_t value = 0;
1943         uint32_t mask = 0xFFFFFFFF;
1944
1945         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], reg_offset);
1946         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], value);
1947
1948         if (CMD_ARGC > 3)
1949                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], mask);
1950
1951         command_print(CMD, "%s Option written.\n"
1952                                 "INFO: a reset or power cycle is required "
1953                                 "for the new settings to take effect.", bank->driver->name);
1954
1955         retval = stm32l4_write_option(bank, reg_offset, value, mask);
1956         return retval;
1957 }
1958
1959 COMMAND_HANDLER(stm32l4_handle_trustzone_command)
1960 {
1961         if (CMD_ARGC < 1 || CMD_ARGC > 2)
1962                 return ERROR_COMMAND_SYNTAX_ERROR;
1963
1964         struct flash_bank *bank;
1965         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1966         if (retval != ERROR_OK)
1967                 return retval;
1968
1969         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1970         if (!(stm32l4_info->part_info->flags & F_HAS_TZ)) {
1971                 LOG_ERROR("This device does not have a TrustZone");
1972                 return ERROR_FAIL;
1973         }
1974
1975         retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_OPTR_INDEX, &stm32l4_info->optr);
1976         if (retval != ERROR_OK)
1977                 return retval;
1978
1979         stm32l4_sync_rdp_tzen(bank);
1980
1981         if (CMD_ARGC == 1) {
1982                 /* only display the TZEN value */
1983                 LOG_INFO("Global TrustZone Security is %s", stm32l4_info->tzen ? "enabled" : "disabled");
1984                 return ERROR_OK;
1985         }
1986
1987         bool new_tzen;
1988         COMMAND_PARSE_ENABLE(CMD_ARGV[1], new_tzen);
1989
1990         if (new_tzen == stm32l4_info->tzen) {
1991                 LOG_INFO("The requested TZEN is already programmed");
1992                 return ERROR_OK;
1993         }
1994
1995         if (new_tzen) {
1996                 if (stm32l4_info->rdp != RDP_LEVEL_0) {
1997                         LOG_ERROR("TZEN can be set only when RDP level is 0");
1998                         return ERROR_FAIL;
1999                 }
2000                 retval = stm32l4_write_option(bank, stm32l4_info->flash_regs[STM32_FLASH_OPTR_INDEX],
2001                                 FLASH_TZEN, FLASH_TZEN);
2002         } else {
2003                 /* Deactivation of TZEN (from 1 to 0) is only possible when the RDP is
2004                  * changing to level 0 (from level 1 to level 0 or from level 0.5 to level 0). */
2005                 if (stm32l4_info->rdp != RDP_LEVEL_1 && stm32l4_info->rdp != RDP_LEVEL_0_5) {
2006                         LOG_ERROR("Deactivation of TZEN is only possible when the RDP is changing to level 0");
2007                         return ERROR_FAIL;
2008                 }
2009
2010                 retval = stm32l4_write_option(bank, stm32l4_info->flash_regs[STM32_FLASH_OPTR_INDEX],
2011                                 RDP_LEVEL_0, FLASH_RDP_MASK | FLASH_TZEN);
2012         }
2013
2014         if (retval != ERROR_OK)
2015                 return retval;
2016
2017         return stm32l4_perform_obl_launch(bank);
2018 }
2019
2020 COMMAND_HANDLER(stm32l4_handle_option_load_command)
2021 {
2022         if (CMD_ARGC != 1)
2023                 return ERROR_COMMAND_SYNTAX_ERROR;
2024
2025         struct flash_bank *bank;
2026         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
2027         if (retval != ERROR_OK)
2028                 return retval;
2029
2030         retval = stm32l4_perform_obl_launch(bank);
2031         if (retval != ERROR_OK) {
2032                 command_print(CMD, "stm32l4x option load failed");
2033                 return retval;
2034         }
2035
2036
2037         command_print(CMD, "stm32l4x option load completed. Power-on reset might be required");
2038
2039         return ERROR_OK;
2040 }
2041
2042 COMMAND_HANDLER(stm32l4_handle_lock_command)
2043 {
2044         struct target *target = NULL;
2045
2046         if (CMD_ARGC < 1)
2047                 return ERROR_COMMAND_SYNTAX_ERROR;
2048
2049         struct flash_bank *bank;
2050         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
2051         if (retval != ERROR_OK)
2052                 return retval;
2053
2054         if (stm32l4_is_otp(bank)) {
2055                 LOG_ERROR("cannot lock/unlock OTP memory");
2056                 return ERROR_FLASH_OPER_UNSUPPORTED;
2057         }
2058
2059         target = bank->target;
2060
2061         if (target->state != TARGET_HALTED) {
2062                 LOG_ERROR("Target not halted");
2063                 return ERROR_TARGET_NOT_HALTED;
2064         }
2065
2066         /* set readout protection level 1 by erasing the RDP option byte */
2067         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
2068         if (stm32l4_write_option(bank, stm32l4_info->flash_regs[STM32_FLASH_OPTR_INDEX],
2069                         RDP_LEVEL_1, FLASH_RDP_MASK) != ERROR_OK) {
2070                 command_print(CMD, "%s failed to lock device", bank->driver->name);
2071                 return ERROR_OK;
2072         }
2073
2074         return ERROR_OK;
2075 }
2076
2077 COMMAND_HANDLER(stm32l4_handle_unlock_command)
2078 {
2079         struct target *target = NULL;
2080
2081         if (CMD_ARGC < 1)
2082                 return ERROR_COMMAND_SYNTAX_ERROR;
2083
2084         struct flash_bank *bank;
2085         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
2086         if (retval != ERROR_OK)
2087                 return retval;
2088
2089         if (stm32l4_is_otp(bank)) {
2090                 LOG_ERROR("cannot lock/unlock OTP memory");
2091                 return ERROR_FLASH_OPER_UNSUPPORTED;
2092         }
2093
2094         target = bank->target;
2095
2096         if (target->state != TARGET_HALTED) {
2097                 LOG_ERROR("Target not halted");
2098                 return ERROR_TARGET_NOT_HALTED;
2099         }
2100
2101         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
2102         if (stm32l4_write_option(bank, stm32l4_info->flash_regs[STM32_FLASH_OPTR_INDEX],
2103                         RDP_LEVEL_0, FLASH_RDP_MASK) != ERROR_OK) {
2104                 command_print(CMD, "%s failed to unlock device", bank->driver->name);
2105                 return ERROR_OK;
2106         }
2107
2108         return ERROR_OK;
2109 }
2110
2111 COMMAND_HANDLER(stm32l4_handle_wrp_info_command)
2112 {
2113         if (CMD_ARGC < 1 || CMD_ARGC > 2)
2114                 return ERROR_COMMAND_SYNTAX_ERROR;
2115
2116         struct flash_bank *bank;
2117         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
2118         if (retval != ERROR_OK)
2119                 return retval;
2120
2121         if (stm32l4_is_otp(bank)) {
2122                 LOG_ERROR("OTP memory does not have write protection areas");
2123                 return ERROR_FLASH_OPER_UNSUPPORTED;
2124         }
2125
2126         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
2127         enum stm32_bank_id dev_bank_id = STM32_ALL_BANKS;
2128         if (CMD_ARGC == 2) {
2129                 if (strcmp(CMD_ARGV[1], "bank1") == 0)
2130                         dev_bank_id = STM32_BANK1;
2131                 else if (strcmp(CMD_ARGV[1], "bank2") == 0)
2132                         dev_bank_id = STM32_BANK2;
2133                 else
2134                         return ERROR_COMMAND_ARGUMENT_INVALID;
2135         }
2136
2137         if (dev_bank_id == STM32_BANK2) {
2138                 if (!(stm32l4_info->part_info->flags & F_HAS_DUAL_BANK)) {
2139                         LOG_ERROR("this device has no second bank");
2140                         return ERROR_FAIL;
2141                 } else if (!stm32l4_info->dual_bank_mode) {
2142                         LOG_ERROR("this device is configured in single bank mode");
2143                         return ERROR_FAIL;
2144                 }
2145         }
2146
2147         int ret;
2148         unsigned int n_wrp, i;
2149         struct stm32l4_wrp wrpxy[4];
2150
2151         ret = stm32l4_get_all_wrpxy(bank, dev_bank_id, wrpxy, &n_wrp);
2152         if (ret != ERROR_OK)
2153                 return ret;
2154
2155         /* use bitmap and range helpers to better describe protected areas */
2156         DECLARE_BITMAP(pages, bank->num_sectors);
2157         bitmap_zero(pages, bank->num_sectors);
2158
2159         for (i = 0; i < n_wrp; i++) {
2160                 if (wrpxy[i].used) {
2161                         for (int p = wrpxy[i].first; p <= wrpxy[i].last; p++)
2162                                 set_bit(p, pages);
2163                 }
2164         }
2165
2166         /* we have at most 'n_wrp' WRP areas */
2167         struct range ranges[n_wrp];
2168         unsigned int ranges_count = 0;
2169
2170         bitmap_to_ranges(pages, bank->num_sectors, ranges, &ranges_count);
2171
2172         if (ranges_count > 0) {
2173                 /* pretty-print the protected ranges */
2174                 char *ranges_str = range_print_alloc(ranges, ranges_count);
2175                 command_print(CMD, "protected areas: %s", ranges_str);
2176                 free(ranges_str);
2177         } else
2178                 command_print(CMD, "no protected areas");
2179
2180         return ERROR_OK;
2181 }
2182
2183 COMMAND_HANDLER(stm32l4_handle_otp_command)
2184 {
2185         if (CMD_ARGC < 2)
2186                 return ERROR_COMMAND_SYNTAX_ERROR;
2187
2188         struct flash_bank *bank;
2189         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
2190         if (retval != ERROR_OK)
2191                 return retval;
2192
2193         if (!stm32l4_is_otp(bank)) {
2194                 command_print(CMD, "the specified bank is not an OTP memory");
2195                 return ERROR_FAIL;
2196         }
2197         if (strcmp(CMD_ARGV[1], "enable") == 0)
2198                 stm32l4_otp_enable(bank, true);
2199         else if (strcmp(CMD_ARGV[1], "disable") == 0)
2200                 stm32l4_otp_enable(bank, false);
2201         else if (strcmp(CMD_ARGV[1], "show") == 0)
2202                 command_print(CMD, "OTP memory bank #%d is %s for write commands.",
2203                                 bank->bank_number, stm32l4_otp_is_enabled(bank) ? "enabled" : "disabled");
2204         else
2205                 return ERROR_COMMAND_SYNTAX_ERROR;
2206
2207         return ERROR_OK;
2208 }
2209
2210 static const struct command_registration stm32l4_exec_command_handlers[] = {
2211         {
2212                 .name = "lock",
2213                 .handler = stm32l4_handle_lock_command,
2214                 .mode = COMMAND_EXEC,
2215                 .usage = "bank_id",
2216                 .help = "Lock entire flash device.",
2217         },
2218         {
2219                 .name = "unlock",
2220                 .handler = stm32l4_handle_unlock_command,
2221                 .mode = COMMAND_EXEC,
2222                 .usage = "bank_id",
2223                 .help = "Unlock entire protected flash device.",
2224         },
2225         {
2226                 .name = "mass_erase",
2227                 .handler = stm32l4_handle_mass_erase_command,
2228                 .mode = COMMAND_EXEC,
2229                 .usage = "bank_id",
2230                 .help = "Erase entire flash device.",
2231         },
2232         {
2233                 .name = "option_read",
2234                 .handler = stm32l4_handle_option_read_command,
2235                 .mode = COMMAND_EXEC,
2236                 .usage = "bank_id reg_offset",
2237                 .help = "Read & Display device option bytes.",
2238         },
2239         {
2240                 .name = "option_write",
2241                 .handler = stm32l4_handle_option_write_command,
2242                 .mode = COMMAND_EXEC,
2243                 .usage = "bank_id reg_offset value mask",
2244                 .help = "Write device option bit fields with provided value.",
2245         },
2246         {
2247                 .name = "trustzone",
2248                 .handler = stm32l4_handle_trustzone_command,
2249                 .mode = COMMAND_EXEC,
2250                 .usage = "<bank_id> [enable|disable]",
2251                 .help = "Configure TrustZone security",
2252         },
2253         {
2254                 .name = "wrp_info",
2255                 .handler = stm32l4_handle_wrp_info_command,
2256                 .mode = COMMAND_EXEC,
2257                 .usage = "bank_id [bank1|bank2]",
2258                 .help = "list the protected areas using WRP",
2259         },
2260         {
2261                 .name = "option_load",
2262                 .handler = stm32l4_handle_option_load_command,
2263                 .mode = COMMAND_EXEC,
2264                 .usage = "bank_id",
2265                 .help = "Force re-load of device options (will cause device reset).",
2266         },
2267         {
2268                 .name = "otp",
2269                 .handler = stm32l4_handle_otp_command,
2270                 .mode = COMMAND_EXEC,
2271                 .usage = "<bank_id> <enable|disable|show>",
2272                 .help = "OTP (One Time Programmable) memory write enable/disable",
2273         },
2274         COMMAND_REGISTRATION_DONE
2275 };
2276
2277 static const struct command_registration stm32l4_command_handlers[] = {
2278         {
2279                 .name = "stm32l4x",
2280                 .mode = COMMAND_ANY,
2281                 .help = "stm32l4x flash command group",
2282                 .usage = "",
2283                 .chain = stm32l4_exec_command_handlers,
2284         },
2285         COMMAND_REGISTRATION_DONE
2286 };
2287
2288 const struct flash_driver stm32l4x_flash = {
2289         .name = "stm32l4x",
2290         .commands = stm32l4_command_handlers,
2291         .flash_bank_command = stm32l4_flash_bank_command,
2292         .erase = stm32l4_erase,
2293         .protect = stm32l4_protect,
2294         .write = stm32l4_write,
2295         .read = default_flash_read,
2296         .probe = stm32l4_probe,
2297         .auto_probe = stm32l4_auto_probe,
2298         .erase_check = default_flash_blank_check,
2299         .protect_check = stm32l4_protect_check,
2300         .info = get_stm32l4_info,
2301         .free_driver_priv = default_flash_free_driver_priv,
2302 };