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