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