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