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