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