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