flash: use lowercase for C variables
[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 const char *get_stm32l4_rev_str(struct flash_bank *bank)
1336 {
1337         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1338         const struct stm32l4_part_info *part_info = stm32l4_info->part_info;
1339         assert(part_info);
1340
1341         const uint16_t rev_id = stm32l4_info->idcode >> 16;
1342         for (unsigned int i = 0; i < part_info->num_revs; i++) {
1343                 if (rev_id == part_info->revs[i].rev)
1344                         return part_info->revs[i].str;
1345         }
1346         return "'unknown'";
1347 }
1348
1349 static const char *get_stm32l4_bank_type_str(struct flash_bank *bank)
1350 {
1351         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1352         assert(stm32l4_info->part_info);
1353         return stm32l4_is_otp(bank) ? "OTP" :
1354                         stm32l4_info->dual_bank_mode ? "Flash dual" :
1355                         "Flash single";
1356 }
1357
1358 static int stm32l4_probe(struct flash_bank *bank)
1359 {
1360         struct target *target = bank->target;
1361         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1362         const struct stm32l4_part_info *part_info;
1363         uint16_t flash_size_kb = 0xffff;
1364         uint32_t options;
1365
1366         stm32l4_info->probed = false;
1367
1368         /* read stm32 device id registers */
1369         int retval = stm32l4_read_idcode(bank, &stm32l4_info->idcode);
1370         if (retval != ERROR_OK)
1371                 return retval;
1372
1373         const uint32_t device_id = stm32l4_info->idcode & 0xFFF;
1374
1375         for (unsigned int n = 0; n < ARRAY_SIZE(stm32l4_parts); n++) {
1376                 if (device_id == stm32l4_parts[n].id) {
1377                         stm32l4_info->part_info = &stm32l4_parts[n];
1378                         break;
1379                 }
1380         }
1381
1382         if (!stm32l4_info->part_info) {
1383                 LOG_WARNING("Cannot identify target as an %s family device.", device_families);
1384                 return ERROR_FAIL;
1385         }
1386
1387         part_info = stm32l4_info->part_info;
1388         const char *rev_str = get_stm32l4_rev_str(bank);
1389         const uint16_t rev_id = stm32l4_info->idcode >> 16;
1390
1391         LOG_INFO("device idcode = 0x%08" PRIx32 " (%s - Rev %s : 0x%04x - %s-bank)",
1392                         stm32l4_info->idcode, part_info->device_str, rev_str, rev_id,
1393                         get_stm32l4_bank_type_str(bank));
1394
1395         stm32l4_info->flash_regs = stm32l4_info->part_info->default_flash_regs;
1396
1397         /* read flash option register */
1398         retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_OPTR_INDEX, &options);
1399         if (retval != ERROR_OK)
1400                 return retval;
1401
1402         stm32l4_sync_rdp_tzen(bank, options);
1403
1404         if (part_info->flags & F_HAS_TZ)
1405                 LOG_INFO("TZEN = %d : TrustZone %s by option bytes",
1406                                 stm32l4_info->tzen,
1407                                 stm32l4_info->tzen ? "enabled" : "disabled");
1408
1409         LOG_INFO("RDP level %s (0x%02X)",
1410                         stm32l4_info->rdp == RDP_LEVEL_0 ? "0" : stm32l4_info->rdp == RDP_LEVEL_0_5 ? "0.5" : "1",
1411                         stm32l4_info->rdp);
1412
1413         if (stm32l4_is_otp(bank)) {
1414                 bank->size = part_info->otp_size;
1415
1416                 LOG_INFO("OTP size is %d bytes, base address is " TARGET_ADDR_FMT, bank->size, bank->base);
1417
1418                 /* OTP memory is considered as one sector */
1419                 free(bank->sectors);
1420                 bank->num_sectors = 1;
1421                 bank->sectors = alloc_block_array(0, part_info->otp_size, 1);
1422
1423                 if (!bank->sectors) {
1424                         LOG_ERROR("failed to allocate bank sectors");
1425                         return ERROR_FAIL;
1426                 }
1427
1428                 stm32l4_info->probed = true;
1429                 return ERROR_OK;
1430         } else if (bank->base != STM32_FLASH_BANK_BASE) {
1431                 LOG_ERROR("invalid bank base address");
1432                 return ERROR_FAIL;
1433         }
1434
1435         /* get flash size from target. */
1436         retval = target_read_u16(target, part_info->fsize_addr, &flash_size_kb);
1437
1438         /* failed reading flash size or flash size invalid (early silicon),
1439          * default to max target family */
1440         if (retval != ERROR_OK || flash_size_kb == 0xffff || flash_size_kb == 0
1441                         || flash_size_kb > part_info->max_flash_size_kb) {
1442                 LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming %dk flash",
1443                         part_info->max_flash_size_kb);
1444                 flash_size_kb = part_info->max_flash_size_kb;
1445         }
1446
1447         /* if the user sets the size manually then ignore the probed value
1448          * this allows us to work around devices that have a invalid flash size register value */
1449         if (stm32l4_info->user_bank_size) {
1450                 LOG_WARNING("overriding size register by configured bank size - MAY CAUSE TROUBLE");
1451                 flash_size_kb = stm32l4_info->user_bank_size / 1024;
1452         }
1453
1454         LOG_INFO("flash size = %dkbytes", flash_size_kb);
1455
1456         /* did we assign a flash size? */
1457         assert((flash_size_kb != 0xffff) && flash_size_kb);
1458
1459         stm32l4_info->bank1_sectors = 0;
1460         stm32l4_info->hole_sectors = 0;
1461
1462         int num_pages = 0;
1463         int page_size_kb = 0;
1464
1465         stm32l4_info->dual_bank_mode = false;
1466         bool use_dbank_bit = false;
1467
1468         switch (device_id) {
1469         case 0x415: /* STM32L47/L48xx */
1470         case 0x461: /* STM32L49/L4Axx */
1471                 /* if flash size is max (1M) the device is always dual bank
1472                  * 0x415: has variants with 512K
1473                  * 0x461: has variants with 512 and 256
1474                  * for these variants:
1475                  *   if DUAL_BANK = 0 -> single bank
1476                  *   else -> dual bank without gap
1477                  * note: the page size is invariant
1478                  */
1479                 page_size_kb = 2;
1480                 num_pages = flash_size_kb / page_size_kb;
1481                 stm32l4_info->bank1_sectors = num_pages;
1482
1483                 /* check DUAL_BANK bit[21] if the flash is less than 1M */
1484                 if (flash_size_kb == 1024 || (options & BIT(21))) {
1485                         stm32l4_info->dual_bank_mode = true;
1486                         stm32l4_info->bank1_sectors = num_pages / 2;
1487                 }
1488                 break;
1489         case 0x435: /* STM32L43/L44xx */
1490         case 0x460: /* STM32G07/G08xx */
1491         case 0x462: /* STM32L45/L46xx */
1492         case 0x464: /* STM32L41/L42xx */
1493         case 0x466: /* STM32G03/G04xx */
1494         case 0x468: /* STM32G43/G44xx */
1495         case 0x479: /* STM32G49/G4Axx */
1496         case 0x497: /* STM32WLEx */
1497                 /* single bank flash */
1498                 page_size_kb = 2;
1499                 num_pages = flash_size_kb / page_size_kb;
1500                 stm32l4_info->bank1_sectors = num_pages;
1501                 break;
1502         case 0x469: /* STM32G47/G48xx */
1503                 /* STM32G47/8 can be single/dual bank:
1504                  *   if DUAL_BANK = 0 -> single bank
1505                  *   else -> dual bank WITH gap
1506                  */
1507                 page_size_kb = 4;
1508                 num_pages = flash_size_kb / page_size_kb;
1509                 stm32l4_info->bank1_sectors = num_pages;
1510                 if (options & BIT(22)) {
1511                         stm32l4_info->dual_bank_mode = true;
1512                         page_size_kb = 2;
1513                         num_pages = flash_size_kb / page_size_kb;
1514                         stm32l4_info->bank1_sectors = num_pages / 2;
1515
1516                         /* for devices with trimmed flash, there is a gap between both banks */
1517                         stm32l4_info->hole_sectors =
1518                                 (part_info->max_flash_size_kb - flash_size_kb) / (2 * page_size_kb);
1519                 }
1520                 break;
1521         case 0x470: /* STM32L4R/L4Sxx */
1522         case 0x471: /* STM32L4P5/L4Q5x */
1523                 /* STM32L4R/S can be single/dual bank:
1524                  *   if size = 2M check DBANK bit(22)
1525                  *   if size = 1M check DB1M bit(21)
1526                  * STM32L4P/Q can be single/dual bank
1527                  *   if size = 1M check DBANK bit(22)
1528                  *   if size = 512K check DB512K bit(21)
1529                  */
1530                 page_size_kb = 8;
1531                 num_pages = flash_size_kb / page_size_kb;
1532                 stm32l4_info->bank1_sectors = num_pages;
1533                 use_dbank_bit = flash_size_kb == part_info->max_flash_size_kb;
1534                 if ((use_dbank_bit && (options & BIT(22))) ||
1535                         (!use_dbank_bit && (options & BIT(21)))) {
1536                         stm32l4_info->dual_bank_mode = true;
1537                         page_size_kb = 4;
1538                         num_pages = flash_size_kb / page_size_kb;
1539                         stm32l4_info->bank1_sectors = num_pages / 2;
1540                 }
1541                 break;
1542         case 0x472: /* STM32L55/L56xx */
1543                 /* STM32L55/L56xx can be single/dual bank:
1544                  *   if size = 512K check DBANK bit(22)
1545                  *   if size = 256K check DB256K bit(21)
1546                  */
1547                 page_size_kb = 4;
1548                 num_pages = flash_size_kb / page_size_kb;
1549                 stm32l4_info->bank1_sectors = num_pages;
1550                 use_dbank_bit = flash_size_kb == part_info->max_flash_size_kb;
1551                 if ((use_dbank_bit && (options & BIT(22))) ||
1552                         (!use_dbank_bit && (options & BIT(21)))) {
1553                         stm32l4_info->dual_bank_mode = true;
1554                         page_size_kb = 2;
1555                         num_pages = flash_size_kb / page_size_kb;
1556                         stm32l4_info->bank1_sectors = num_pages / 2;
1557                 }
1558                 break;
1559         case 0x495: /* STM32WB5x */
1560         case 0x496: /* STM32WB3x */
1561                 /* single bank flash */
1562                 page_size_kb = 4;
1563                 num_pages = flash_size_kb / page_size_kb;
1564                 stm32l4_info->bank1_sectors = num_pages;
1565                 break;
1566         default:
1567                 LOG_ERROR("unsupported device");
1568                 return ERROR_FAIL;
1569         }
1570
1571         LOG_INFO("flash mode : %s-bank", stm32l4_info->dual_bank_mode ? "dual" : "single");
1572
1573         const int gap_size_kb = stm32l4_info->hole_sectors * page_size_kb;
1574
1575         if (gap_size_kb != 0) {
1576                 LOG_INFO("gap detected from 0x%08x to 0x%08x",
1577                         STM32_FLASH_BANK_BASE + stm32l4_info->bank1_sectors
1578                                 * page_size_kb * 1024,
1579                         STM32_FLASH_BANK_BASE + (stm32l4_info->bank1_sectors
1580                                 * page_size_kb + gap_size_kb) * 1024 - 1);
1581         }
1582
1583         /* number of significant bits in WRPxxR differs per device,
1584          * always right adjusted, on some devices non-implemented
1585          * bits read as '0', on others as '1' ...
1586          * notably G4 Cat. 2 implement only 6 bits, contradicting the RM
1587          */
1588
1589         /* use *max_flash_size* instead of actual size as the trimmed versions
1590          * certainly use the same number of bits
1591          * max_flash_size is always power of two, so max_pages too
1592          */
1593         uint32_t max_pages = stm32l4_info->part_info->max_flash_size_kb / page_size_kb;
1594         assert((max_pages & (max_pages - 1)) == 0);
1595
1596         /* in dual bank mode number of pages is doubled, but extra bit is bank selection */
1597         stm32l4_info->wrpxxr_mask = ((max_pages >> (stm32l4_info->dual_bank_mode ? 1 : 0)) - 1);
1598         assert((stm32l4_info->wrpxxr_mask & 0xFFFF0000) == 0);
1599         LOG_DEBUG("WRPxxR mask 0x%04" PRIx16, (uint16_t)stm32l4_info->wrpxxr_mask);
1600
1601         free(bank->sectors);
1602
1603         bank->size = (flash_size_kb + gap_size_kb) * 1024;
1604         bank->num_sectors = num_pages;
1605         bank->sectors = malloc(sizeof(struct flash_sector) * bank->num_sectors);
1606         if (bank->sectors == NULL) {
1607                 LOG_ERROR("failed to allocate bank sectors");
1608                 return ERROR_FAIL;
1609         }
1610
1611         for (unsigned int i = 0; i < bank->num_sectors; i++) {
1612                 bank->sectors[i].offset = i * page_size_kb * 1024;
1613                 /* in dual bank configuration, if there is a gap between banks
1614                  * we fix up the sector offset to consider this gap */
1615                 if (i >= stm32l4_info->bank1_sectors && stm32l4_info->hole_sectors)
1616                         bank->sectors[i].offset += gap_size_kb * 1024;
1617                 bank->sectors[i].size = page_size_kb * 1024;
1618                 bank->sectors[i].is_erased = -1;
1619                 bank->sectors[i].is_protected = 1;
1620         }
1621
1622         stm32l4_info->probed = true;
1623         return ERROR_OK;
1624 }
1625
1626 static int stm32l4_auto_probe(struct flash_bank *bank)
1627 {
1628         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1629         if (stm32l4_info->probed)
1630                 return ERROR_OK;
1631
1632         return stm32l4_probe(bank);
1633 }
1634
1635 static int get_stm32l4_info(struct flash_bank *bank, struct command_invocation *cmd)
1636 {
1637         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1638         const struct stm32l4_part_info *part_info = stm32l4_info->part_info;
1639
1640         if (part_info) {
1641                 const uint16_t rev_id = stm32l4_info->idcode >> 16;
1642                 command_print_sameline(cmd, "%s - Rev %s : 0x%04x", part_info->device_str,
1643                                 get_stm32l4_rev_str(bank), rev_id);
1644                 if (stm32l4_info->probed)
1645                         command_print_sameline(cmd, " - %s-bank", get_stm32l4_bank_type_str(bank));
1646         } else {
1647                 command_print_sameline(cmd, "Cannot identify target as an %s device", device_families);
1648         }
1649
1650         return ERROR_OK;
1651 }
1652
1653 static int stm32l4_mass_erase(struct flash_bank *bank)
1654 {
1655         int retval, retval2;
1656         struct target *target = bank->target;
1657         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1658
1659         if (stm32l4_is_otp(bank)) {
1660                 LOG_ERROR("cannot erase OTP memory");
1661                 return ERROR_FLASH_OPER_UNSUPPORTED;
1662         }
1663
1664         uint32_t action = FLASH_MER1;
1665
1666         if (stm32l4_info->part_info->flags & F_HAS_DUAL_BANK)
1667                 action |= FLASH_MER2;
1668
1669         if (target->state != TARGET_HALTED) {
1670                 LOG_ERROR("Target not halted");
1671                 return ERROR_TARGET_NOT_HALTED;
1672         }
1673
1674         retval = stm32l4_unlock_reg(bank);
1675         if (retval != ERROR_OK)
1676                 goto err_lock;
1677
1678         /* mass erase flash memory */
1679         retval = stm32l4_wait_status_busy(bank, FLASH_ERASE_TIMEOUT / 10);
1680         if (retval != ERROR_OK)
1681                 goto err_lock;
1682
1683         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, action);
1684         if (retval != ERROR_OK)
1685                 goto err_lock;
1686
1687         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, action | FLASH_STRT);
1688         if (retval != ERROR_OK)
1689                 goto err_lock;
1690
1691         retval = stm32l4_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
1692
1693 err_lock:
1694         retval2 = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_LOCK);
1695
1696         if (retval != ERROR_OK)
1697                 return retval;
1698
1699         return retval2;
1700 }
1701
1702 COMMAND_HANDLER(stm32l4_handle_mass_erase_command)
1703 {
1704         if (CMD_ARGC < 1) {
1705                 command_print(CMD, "stm32l4x mass_erase <STM32L4 bank>");
1706                 return ERROR_COMMAND_SYNTAX_ERROR;
1707         }
1708
1709         struct flash_bank *bank;
1710         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1711         if (ERROR_OK != retval)
1712                 return retval;
1713
1714         retval = stm32l4_mass_erase(bank);
1715         if (retval == ERROR_OK) {
1716                 /* set all sectors as erased */
1717                 for (unsigned int i = 0; i < bank->num_sectors; i++)
1718                         bank->sectors[i].is_erased = 1;
1719
1720                 command_print(CMD, "stm32l4x mass erase complete");
1721         } else {
1722                 command_print(CMD, "stm32l4x mass erase failed");
1723         }
1724
1725         return retval;
1726 }
1727
1728 COMMAND_HANDLER(stm32l4_handle_option_read_command)
1729 {
1730         if (CMD_ARGC < 2) {
1731                 command_print(CMD, "stm32l4x option_read <STM32L4 bank> <option_reg offset>");
1732                 return ERROR_COMMAND_SYNTAX_ERROR;
1733         }
1734
1735         struct flash_bank *bank;
1736         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1737         if (ERROR_OK != retval)
1738                 return retval;
1739
1740         uint32_t reg_offset, reg_addr;
1741         uint32_t value = 0;
1742
1743         reg_offset = strtoul(CMD_ARGV[1], NULL, 16);
1744         reg_addr = stm32l4_get_flash_reg(bank, reg_offset);
1745
1746         retval = stm32l4_read_flash_reg(bank, reg_offset, &value);
1747         if (ERROR_OK != retval)
1748                 return retval;
1749
1750         command_print(CMD, "Option Register: <0x%" PRIx32 "> = 0x%" PRIx32 "", reg_addr, value);
1751
1752         return retval;
1753 }
1754
1755 COMMAND_HANDLER(stm32l4_handle_option_write_command)
1756 {
1757         if (CMD_ARGC < 3) {
1758                 command_print(CMD, "stm32l4x option_write <STM32L4 bank> <option_reg offset> <value> [mask]");
1759                 return ERROR_COMMAND_SYNTAX_ERROR;
1760         }
1761
1762         struct flash_bank *bank;
1763         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1764         if (ERROR_OK != retval)
1765                 return retval;
1766
1767         uint32_t reg_offset;
1768         uint32_t value = 0;
1769         uint32_t mask = 0xFFFFFFFF;
1770
1771         reg_offset = strtoul(CMD_ARGV[1], NULL, 16);
1772         value = strtoul(CMD_ARGV[2], NULL, 16);
1773         if (CMD_ARGC > 3)
1774                 mask = strtoul(CMD_ARGV[3], NULL, 16);
1775
1776         command_print(CMD, "%s Option written.\n"
1777                                 "INFO: a reset or power cycle is required "
1778                                 "for the new settings to take effect.", bank->driver->name);
1779
1780         retval = stm32l4_write_option(bank, reg_offset, value, mask);
1781         return retval;
1782 }
1783
1784 COMMAND_HANDLER(stm32l4_handle_option_load_command)
1785 {
1786         if (CMD_ARGC != 1)
1787                 return ERROR_COMMAND_SYNTAX_ERROR;
1788
1789         struct flash_bank *bank;
1790         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1791         if (ERROR_OK != retval)
1792                 return retval;
1793
1794         retval = stm32l4_unlock_reg(bank);
1795         if (ERROR_OK != retval)
1796                 return retval;
1797
1798         retval = stm32l4_unlock_option_reg(bank);
1799         if (ERROR_OK != retval)
1800                 return retval;
1801
1802         /* Set OBL_LAUNCH bit in CR -> system reset and option bytes reload,
1803          * but the RMs explicitly do *NOT* list this as power-on reset cause, and:
1804          * "Note: If the read protection is set while the debugger is still
1805          * connected through JTAG/SWD, apply a POR (power-on reset) instead of a system reset."
1806          */
1807         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_OBL_LAUNCH);
1808
1809         command_print(CMD, "stm32l4x option load completed. Power-on reset might be required");
1810
1811         /* Need to re-probe after change */
1812         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1813         stm32l4_info->probed = false;
1814
1815         return retval;
1816 }
1817
1818 COMMAND_HANDLER(stm32l4_handle_lock_command)
1819 {
1820         struct target *target = NULL;
1821
1822         if (CMD_ARGC < 1)
1823                 return ERROR_COMMAND_SYNTAX_ERROR;
1824
1825         struct flash_bank *bank;
1826         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1827         if (ERROR_OK != retval)
1828                 return retval;
1829
1830         if (stm32l4_is_otp(bank)) {
1831                 LOG_ERROR("cannot lock/unlock OTP memory");
1832                 return ERROR_FLASH_OPER_UNSUPPORTED;
1833         }
1834
1835         target = bank->target;
1836
1837         if (target->state != TARGET_HALTED) {
1838                 LOG_ERROR("Target not halted");
1839                 return ERROR_TARGET_NOT_HALTED;
1840         }
1841
1842         /* set readout protection level 1 by erasing the RDP option byte */
1843         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1844         if (stm32l4_write_option(bank, stm32l4_info->flash_regs[STM32_FLASH_OPTR_INDEX],
1845                         RDP_LEVEL_1, FLASH_RDP_MASK) != ERROR_OK) {
1846                 command_print(CMD, "%s failed to lock device", bank->driver->name);
1847                 return ERROR_OK;
1848         }
1849
1850         return ERROR_OK;
1851 }
1852
1853 COMMAND_HANDLER(stm32l4_handle_unlock_command)
1854 {
1855         struct target *target = NULL;
1856
1857         if (CMD_ARGC < 1)
1858                 return ERROR_COMMAND_SYNTAX_ERROR;
1859
1860         struct flash_bank *bank;
1861         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1862         if (ERROR_OK != retval)
1863                 return retval;
1864
1865         if (stm32l4_is_otp(bank)) {
1866                 LOG_ERROR("cannot lock/unlock OTP memory");
1867                 return ERROR_FLASH_OPER_UNSUPPORTED;
1868         }
1869
1870         target = bank->target;
1871
1872         if (target->state != TARGET_HALTED) {
1873                 LOG_ERROR("Target not halted");
1874                 return ERROR_TARGET_NOT_HALTED;
1875         }
1876
1877         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1878         if (stm32l4_write_option(bank, stm32l4_info->flash_regs[STM32_FLASH_OPTR_INDEX],
1879                         RDP_LEVEL_0, FLASH_RDP_MASK) != ERROR_OK) {
1880                 command_print(CMD, "%s failed to unlock device", bank->driver->name);
1881                 return ERROR_OK;
1882         }
1883
1884         return ERROR_OK;
1885 }
1886
1887 COMMAND_HANDLER(stm32l4_handle_wrp_info_command)
1888 {
1889         if (CMD_ARGC < 1 || CMD_ARGC > 2)
1890                 return ERROR_COMMAND_SYNTAX_ERROR;
1891
1892         struct flash_bank *bank;
1893         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1894         if (ERROR_OK != retval)
1895                 return retval;
1896
1897         if (stm32l4_is_otp(bank)) {
1898                 LOG_ERROR("OTP memory does not have write protection areas");
1899                 return ERROR_FLASH_OPER_UNSUPPORTED;
1900         }
1901
1902         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1903         enum stm32_bank_id dev_bank_id = STM32_ALL_BANKS;
1904         if (CMD_ARGC == 2) {
1905                 if (strcmp(CMD_ARGV[1], "bank1") == 0)
1906                         dev_bank_id = STM32_BANK1;
1907                 else if (strcmp(CMD_ARGV[1], "bank2") == 0)
1908                         dev_bank_id = STM32_BANK2;
1909                 else
1910                         return ERROR_COMMAND_ARGUMENT_INVALID;
1911         }
1912
1913         if (dev_bank_id == STM32_BANK2) {
1914                 if (!(stm32l4_info->part_info->flags & F_HAS_DUAL_BANK)) {
1915                         LOG_ERROR("this device has no second bank");
1916                         return ERROR_FAIL;
1917                 } else if (!stm32l4_info->dual_bank_mode) {
1918                         LOG_ERROR("this device is configured in single bank mode");
1919                         return ERROR_FAIL;
1920                 }
1921         }
1922
1923         int ret;
1924         unsigned int n_wrp, i;
1925         struct stm32l4_wrp wrpxy[4];
1926
1927         ret = stm32l4_get_all_wrpxy(bank, dev_bank_id, wrpxy, &n_wrp);
1928         if (ret != ERROR_OK)
1929                 return ret;
1930
1931         /* use bitmap and range helpers to better describe protected areas */
1932         DECLARE_BITMAP(pages, bank->num_sectors);
1933         bitmap_zero(pages, bank->num_sectors);
1934
1935         for (i = 0; i < n_wrp; i++) {
1936                 if (wrpxy[i].used) {
1937                         for (int p = wrpxy[i].first; p <= wrpxy[i].last; p++)
1938                                 set_bit(p, pages);
1939                 }
1940         }
1941
1942         /* we have at most 'n_wrp' WRP areas */
1943         struct range ranges[n_wrp];
1944         unsigned int ranges_count = 0;
1945
1946         bitmap_to_ranges(pages, bank->num_sectors, ranges, &ranges_count);
1947
1948         if (ranges_count > 0) {
1949                 /* pretty-print the protected ranges */
1950                 char *ranges_str = range_print_alloc(ranges, ranges_count);
1951                 command_print(CMD, "protected areas: %s", ranges_str);
1952                 free(ranges_str);
1953         } else
1954                 command_print(CMD, "no protected areas");
1955
1956         return ERROR_OK;
1957 }
1958
1959 COMMAND_HANDLER(stm32l4_handle_otp_command)
1960 {
1961         if (CMD_ARGC < 2)
1962                 return ERROR_COMMAND_SYNTAX_ERROR;
1963
1964         struct flash_bank *bank;
1965         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1966         if (ERROR_OK != retval)
1967                 return retval;
1968
1969         if (!stm32l4_is_otp(bank)) {
1970                 command_print(CMD, "the specified bank is not an OTP memory");
1971                 return ERROR_FAIL;
1972         }
1973         if (strcmp(CMD_ARGV[1], "enable") == 0)
1974                 stm32l4_otp_enable(bank, true);
1975         else if (strcmp(CMD_ARGV[1], "disable") == 0)
1976                 stm32l4_otp_enable(bank, false);
1977         else if (strcmp(CMD_ARGV[1], "show") == 0)
1978                 command_print(CMD, "OTP memory bank #%d is %s for write commands.",
1979                                 bank->bank_number, stm32l4_otp_is_enabled(bank) ? "enabled" : "disabled");
1980         else
1981                 return ERROR_COMMAND_SYNTAX_ERROR;
1982
1983         return ERROR_OK;
1984 }
1985
1986 static const struct command_registration stm32l4_exec_command_handlers[] = {
1987         {
1988                 .name = "lock",
1989                 .handler = stm32l4_handle_lock_command,
1990                 .mode = COMMAND_EXEC,
1991                 .usage = "bank_id",
1992                 .help = "Lock entire flash device.",
1993         },
1994         {
1995                 .name = "unlock",
1996                 .handler = stm32l4_handle_unlock_command,
1997                 .mode = COMMAND_EXEC,
1998                 .usage = "bank_id",
1999                 .help = "Unlock entire protected flash device.",
2000         },
2001         {
2002                 .name = "mass_erase",
2003                 .handler = stm32l4_handle_mass_erase_command,
2004                 .mode = COMMAND_EXEC,
2005                 .usage = "bank_id",
2006                 .help = "Erase entire flash device.",
2007         },
2008         {
2009                 .name = "option_read",
2010                 .handler = stm32l4_handle_option_read_command,
2011                 .mode = COMMAND_EXEC,
2012                 .usage = "bank_id reg_offset",
2013                 .help = "Read & Display device option bytes.",
2014         },
2015         {
2016                 .name = "option_write",
2017                 .handler = stm32l4_handle_option_write_command,
2018                 .mode = COMMAND_EXEC,
2019                 .usage = "bank_id reg_offset value mask",
2020                 .help = "Write device option bit fields with provided value.",
2021         },
2022         {
2023                 .name = "wrp_info",
2024                 .handler = stm32l4_handle_wrp_info_command,
2025                 .mode = COMMAND_EXEC,
2026                 .usage = "bank_id [bank1|bank2]",
2027                 .help = "list the protected areas using WRP",
2028         },
2029         {
2030                 .name = "option_load",
2031                 .handler = stm32l4_handle_option_load_command,
2032                 .mode = COMMAND_EXEC,
2033                 .usage = "bank_id",
2034                 .help = "Force re-load of device options (will cause device reset).",
2035         },
2036         {
2037                 .name = "otp",
2038                 .handler = stm32l4_handle_otp_command,
2039                 .mode = COMMAND_EXEC,
2040                 .usage = "<bank_id> <enable|disable|show>",
2041                 .help = "OTP (One Time Programmable) memory write enable/disable",
2042         },
2043         COMMAND_REGISTRATION_DONE
2044 };
2045
2046 static const struct command_registration stm32l4_command_handlers[] = {
2047         {
2048                 .name = "stm32l4x",
2049                 .mode = COMMAND_ANY,
2050                 .help = "stm32l4x flash command group",
2051                 .usage = "",
2052                 .chain = stm32l4_exec_command_handlers,
2053         },
2054         COMMAND_REGISTRATION_DONE
2055 };
2056
2057 const struct flash_driver stm32l4x_flash = {
2058         .name = "stm32l4x",
2059         .commands = stm32l4_command_handlers,
2060         .flash_bank_command = stm32l4_flash_bank_command,
2061         .erase = stm32l4_erase,
2062         .protect = stm32l4_protect,
2063         .write = stm32l4_write,
2064         .read = default_flash_read,
2065         .probe = stm32l4_probe,
2066         .auto_probe = stm32l4_auto_probe,
2067         .erase_check = default_flash_blank_check,
2068         .protect_check = stm32l4_protect_check,
2069         .info = get_stm32l4_info,
2070         .free_driver_priv = default_flash_free_driver_priv,
2071 };