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