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