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