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