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