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