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