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