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