flash/stm32l4x: introduce 'stm32l4x trustzone [enable|disable]' command
[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 };
213
214 enum stm32_bank_id {
215         STM32_BANK1,
216         STM32_BANK2,
217         STM32_ALL_BANKS
218 };
219
220 struct stm32l4_wrp {
221         enum stm32l4_flash_reg_index reg_idx;
222         uint32_t value;
223         bool used;
224         int first;
225         int last;
226         int offset;
227 };
228
229 /* human readable list of families this drivers supports (sorted alphabetically) */
230 static const char *device_families = "STM32G0/G4/L4/L4+/L5/WB/WL";
231
232 static const struct stm32l4_rev stm32_415_revs[] = {
233         { 0x1000, "1" }, { 0x1001, "2" }, { 0x1003, "3" }, { 0x1007, "4" }
234 };
235
236 static const struct stm32l4_rev stm32_435_revs[] = {
237         { 0x1000, "A" }, { 0x1001, "Z" }, { 0x2001, "Y" },
238 };
239
240 static const struct stm32l4_rev stm32_460_revs[] = {
241         { 0x1000, "A/Z" } /* A and Z, no typo in RM! */, { 0x2000, "B" },
242 };
243
244 static const struct stm32l4_rev stm32_461_revs[] = {
245         { 0x1000, "A" }, { 0x2000, "B" },
246 };
247
248 static const struct stm32l4_rev stm32_462_revs[] = {
249         { 0x1000, "A" }, { 0x1001, "Z" }, { 0x2001, "Y" },
250 };
251
252 static const struct stm32l4_rev stm32_464_revs[] = {
253         { 0x1000, "A" }, { 0x1001, "Z" }, { 0x2001, "Y" },
254 };
255
256 static const struct stm32l4_rev stm32_466_revs[] = {
257         { 0x1000, "A" }, { 0x1001, "Z" }, { 0x2000, "B" },
258 };
259
260 static const struct stm32l4_rev stm32_468_revs[] = {
261         { 0x1000, "A" }, { 0x2000, "B" }, { 0x2001, "Z" },
262 };
263
264 static const struct stm32l4_rev stm32_469_revs[] = {
265         { 0x1000, "A" }, { 0x2000, "B" }, { 0x2001, "Z" },
266 };
267
268 static const struct stm32l4_rev stm32_470_revs[] = {
269         { 0x1000, "A" }, { 0x1001, "Z" }, { 0x1003, "Y" }, { 0x100F, "W" },
270 };
271
272 static const struct stm32l4_rev stm32_471_revs[] = {
273         { 0x1001, "Z" },
274 };
275
276 static const struct stm32l4_rev stm32_472_revs[] = {
277         { 0x1000, "A" }, { 0x2000, "B" },
278 };
279
280 static const struct stm32l4_rev stm32_479_revs[] = {
281         { 0x1000, "A" },
282 };
283
284 static const struct stm32l4_rev stm32_495_revs[] = {
285         { 0x2001, "2.1" },
286 };
287
288 static const struct stm32l4_rev stm32_496_revs[] = {
289         { 0x1000, "A" },
290 };
291
292 static const struct stm32l4_rev stm32_497_revs[] = {
293         { 0x1000, "1.0" },
294 };
295
296 static const struct stm32l4_part_info stm32l4_parts[] = {
297         {
298           .id                    = 0x415,
299           .revs                  = stm32_415_revs,
300           .num_revs              = ARRAY_SIZE(stm32_415_revs),
301           .device_str            = "STM32L47/L48xx",
302           .max_flash_size_kb     = 1024,
303           .flags                 = F_HAS_DUAL_BANK,
304           .flash_regs_base       = 0x40022000,
305           .default_flash_regs    = stm32l4_flash_regs,
306           .fsize_addr            = 0x1FFF75E0,
307           .otp_base              = 0x1FFF7000,
308           .otp_size              = 1024,
309         },
310         {
311           .id                    = 0x435,
312           .revs                  = stm32_435_revs,
313           .num_revs              = ARRAY_SIZE(stm32_435_revs),
314           .device_str            = "STM32L43/L44xx",
315           .max_flash_size_kb     = 256,
316           .flags                 = F_NONE,
317           .flash_regs_base       = 0x40022000,
318           .default_flash_regs    = stm32l4_flash_regs,
319           .fsize_addr            = 0x1FFF75E0,
320           .otp_base              = 0x1FFF7000,
321           .otp_size              = 1024,
322         },
323         {
324           .id                    = 0x460,
325           .revs                  = stm32_460_revs,
326           .num_revs              = ARRAY_SIZE(stm32_460_revs),
327           .device_str            = "STM32G07/G08xx",
328           .max_flash_size_kb     = 128,
329           .flags                 = F_NONE,
330           .flash_regs_base       = 0x40022000,
331           .default_flash_regs    = stm32l4_flash_regs,
332           .fsize_addr            = 0x1FFF75E0,
333           .otp_base              = 0x1FFF7000,
334           .otp_size              = 1024,
335         },
336         {
337           .id                    = 0x461,
338           .revs                  = stm32_461_revs,
339           .num_revs              = ARRAY_SIZE(stm32_461_revs),
340           .device_str            = "STM32L49/L4Axx",
341           .max_flash_size_kb     = 1024,
342           .flags                 = F_HAS_DUAL_BANK,
343           .flash_regs_base       = 0x40022000,
344           .default_flash_regs    = stm32l4_flash_regs,
345           .fsize_addr            = 0x1FFF75E0,
346           .otp_base              = 0x1FFF7000,
347           .otp_size              = 1024,
348         },
349         {
350           .id                    = 0x462,
351           .revs                  = stm32_462_revs,
352           .num_revs              = ARRAY_SIZE(stm32_462_revs),
353           .device_str            = "STM32L45/L46xx",
354           .max_flash_size_kb     = 512,
355           .flags                 = F_NONE,
356           .flash_regs_base       = 0x40022000,
357           .default_flash_regs    = stm32l4_flash_regs,
358           .fsize_addr            = 0x1FFF75E0,
359           .otp_base              = 0x1FFF7000,
360           .otp_size              = 1024,
361         },
362         {
363           .id                    = 0x464,
364           .revs                  = stm32_464_revs,
365           .num_revs              = ARRAY_SIZE(stm32_464_revs),
366           .device_str            = "STM32L41/L42xx",
367           .max_flash_size_kb     = 128,
368           .flags                 = F_NONE,
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                    = 0x466,
377           .revs                  = stm32_466_revs,
378           .num_revs              = ARRAY_SIZE(stm32_466_revs),
379           .device_str            = "STM32G03/G04xx",
380           .max_flash_size_kb     = 64,
381           .flags                 = F_NONE,
382           .flash_regs_base       = 0x40022000,
383           .default_flash_regs    = stm32l4_flash_regs,
384           .fsize_addr            = 0x1FFF75E0,
385           .otp_base              = 0x1FFF7000,
386           .otp_size              = 1024,
387         },
388         {
389           .id                    = 0x468,
390           .revs                  = stm32_468_revs,
391           .num_revs              = ARRAY_SIZE(stm32_468_revs),
392           .device_str            = "STM32G43/G44xx",
393           .max_flash_size_kb     = 128,
394           .flags                 = F_NONE,
395           .flash_regs_base       = 0x40022000,
396           .default_flash_regs    = stm32l4_flash_regs,
397           .fsize_addr            = 0x1FFF75E0,
398           .otp_base              = 0x1FFF7000,
399           .otp_size              = 1024,
400         },
401         {
402           .id                    = 0x469,
403           .revs                  = stm32_469_revs,
404           .num_revs              = ARRAY_SIZE(stm32_469_revs),
405           .device_str            = "STM32G47/G48xx",
406           .max_flash_size_kb     = 512,
407           .flags                 = F_HAS_DUAL_BANK | F_USE_ALL_WRPXX,
408           .flash_regs_base       = 0x40022000,
409           .default_flash_regs    = stm32l4_flash_regs,
410           .fsize_addr            = 0x1FFF75E0,
411           .otp_base              = 0x1FFF7000,
412           .otp_size              = 1024,
413         },
414         {
415           .id                    = 0x470,
416           .revs                  = stm32_470_revs,
417           .num_revs              = ARRAY_SIZE(stm32_470_revs),
418           .device_str            = "STM32L4R/L4Sxx",
419           .max_flash_size_kb     = 2048,
420           .flags                 = F_HAS_DUAL_BANK | F_USE_ALL_WRPXX,
421           .flash_regs_base       = 0x40022000,
422           .default_flash_regs    = stm32l4_flash_regs,
423           .fsize_addr            = 0x1FFF75E0,
424           .otp_base              = 0x1FFF7000,
425           .otp_size              = 1024,
426         },
427         {
428           .id                    = 0x471,
429           .revs                  = stm32_471_revs,
430           .num_revs              = ARRAY_SIZE(stm32_471_revs),
431           .device_str            = "STM32L4P5/L4Q5x",
432           .max_flash_size_kb     = 1024,
433           .flags                 = F_HAS_DUAL_BANK | F_USE_ALL_WRPXX,
434           .flash_regs_base       = 0x40022000,
435           .default_flash_regs    = stm32l4_flash_regs,
436           .fsize_addr            = 0x1FFF75E0,
437           .otp_base              = 0x1FFF7000,
438           .otp_size              = 1024,
439         },
440         {
441           .id                    = 0x472,
442           .revs                  = stm32_472_revs,
443           .num_revs              = ARRAY_SIZE(stm32_472_revs),
444           .device_str            = "STM32L55/L56xx",
445           .max_flash_size_kb     = 512,
446           .flags                 = F_HAS_DUAL_BANK | F_USE_ALL_WRPXX | F_HAS_TZ,
447           .flash_regs_base       = 0x40022000,
448           .default_flash_regs    = stm32l5_ns_flash_regs,
449           .fsize_addr            = 0x0BFA05E0,
450           .otp_base              = 0x0BFA0000,
451           .otp_size              = 512,
452         },
453         {
454           .id                    = 0x479,
455           .revs                  = stm32_479_revs,
456           .num_revs              = ARRAY_SIZE(stm32_479_revs),
457           .device_str            = "STM32G49/G4Axx",
458           .max_flash_size_kb     = 512,
459           .flags                 = F_NONE,
460           .flash_regs_base       = 0x40022000,
461           .default_flash_regs    = stm32l4_flash_regs,
462           .fsize_addr            = 0x1FFF75E0,
463           .otp_base              = 0x1FFF7000,
464           .otp_size              = 1024,
465         },
466         {
467           .id                    = 0x495,
468           .revs                  = stm32_495_revs,
469           .num_revs              = ARRAY_SIZE(stm32_495_revs),
470           .device_str            = "STM32WB5x",
471           .max_flash_size_kb     = 1024,
472           .flags                 = F_NONE,
473           .flash_regs_base       = 0x58004000,
474           .default_flash_regs    = stm32l4_flash_regs,
475           .fsize_addr            = 0x1FFF75E0,
476           .otp_base              = 0x1FFF7000,
477           .otp_size              = 1024,
478         },
479         {
480           .id                    = 0x496,
481           .revs                  = stm32_496_revs,
482           .num_revs              = ARRAY_SIZE(stm32_496_revs),
483           .device_str            = "STM32WB3x",
484           .max_flash_size_kb     = 512,
485           .flags                 = F_NONE,
486           .flash_regs_base       = 0x58004000,
487           .default_flash_regs    = stm32l4_flash_regs,
488           .fsize_addr            = 0x1FFF75E0,
489           .otp_base              = 0x1FFF7000,
490           .otp_size              = 1024,
491         },
492         {
493           .id                    = 0x497,
494           .revs                  = stm32_497_revs,
495           .num_revs              = ARRAY_SIZE(stm32_497_revs),
496           .device_str            = "STM32WLEx",
497           .max_flash_size_kb     = 256,
498           .flags                 = F_NONE,
499           .flash_regs_base       = 0x58004000,
500           .default_flash_regs    = stm32l4_flash_regs,
501           .fsize_addr            = 0x1FFF75E0,
502           .otp_base              = 0x1FFF7000,
503           .otp_size              = 1024,
504         },
505 };
506
507 /* flash bank stm32l4x <base> <size> 0 0 <target#> */
508 FLASH_BANK_COMMAND_HANDLER(stm32l4_flash_bank_command)
509 {
510         struct stm32l4_flash_bank *stm32l4_info;
511
512         if (CMD_ARGC < 6)
513                 return ERROR_COMMAND_SYNTAX_ERROR;
514
515         /* fix-up bank base address: 0 is used for normal flash memory */
516         if (bank->base == 0)
517                 bank->base = STM32_FLASH_BANK_BASE;
518
519         stm32l4_info = calloc(1, sizeof(struct stm32l4_flash_bank));
520         if (!stm32l4_info)
521                 return ERROR_FAIL; /* Checkme: What better error to use?*/
522         bank->driver_priv = stm32l4_info;
523
524         /* The flash write must be aligned to a double word (8-bytes) boundary.
525          * Ask the flash infrastructure to ensure required alignment */
526         bank->write_start_alignment = bank->write_end_alignment = 8;
527
528         stm32l4_info->probed = false;
529         stm32l4_info->otp_enabled = false;
530         stm32l4_info->user_bank_size = bank->size;
531
532         return ERROR_OK;
533 }
534
535 /* bitmap helper extension */
536 struct range {
537         unsigned int start;
538         unsigned int end;
539 };
540
541 static void bitmap_to_ranges(unsigned long *bitmap, unsigned int nbits,
542                 struct range *ranges, unsigned int *ranges_count) {
543         *ranges_count = 0;
544         bool last_bit = 0, cur_bit;
545         for (unsigned int i = 0; i < nbits; i++) {
546                 cur_bit = test_bit(i, bitmap);
547
548                 if (cur_bit && !last_bit) {
549                         (*ranges_count)++;
550                         ranges[*ranges_count - 1].start = i;
551                         ranges[*ranges_count - 1].end = i;
552                 } else if (cur_bit && last_bit) {
553                         /* update (increment) the end this range */
554                         ranges[*ranges_count - 1].end = i;
555                 }
556
557                 last_bit = cur_bit;
558         }
559 }
560
561 static inline int range_print_one(struct range *range, char *str)
562 {
563         if (range->start == range->end)
564                 return sprintf(str, "[%d]", range->start);
565
566         return sprintf(str, "[%d,%d]", range->start, range->end);
567 }
568
569 static char *range_print_alloc(struct range *ranges, unsigned int ranges_count)
570 {
571         /* each range will be printed like the following: [start,end]
572          * start and end, both are unsigned int, an unsigned int takes 10 characters max
573          * plus 3 characters for '[', ',' and ']'
574          * thus means each range can take maximum 23 character
575          * after each range we add a ' ' as separator and finally we need the '\0'
576          * if the ranges_count is zero we reserve one char for '\0' to return an empty string */
577         char *str = calloc(1, ranges_count * (24 * sizeof(char)) + 1);
578         char *ptr = str;
579
580         for (unsigned int i = 0; i < ranges_count; i++) {
581                 ptr += range_print_one(&(ranges[i]), ptr);
582
583                 if (i < ranges_count - 1)
584                         *(ptr++) = ' ';
585         }
586
587         return str;
588 }
589
590 /* end of bitmap helper extension */
591
592 static inline bool stm32l4_is_otp(struct flash_bank *bank)
593 {
594         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
595         return bank->base == stm32l4_info->part_info->otp_base;
596 }
597
598 static int stm32l4_otp_enable(struct flash_bank *bank, bool enable)
599 {
600         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
601
602         if (!stm32l4_is_otp(bank))
603                 return ERROR_FAIL;
604
605         char *op_str = enable ? "enabled" : "disabled";
606
607         LOG_INFO("OTP memory (bank #%d) is %s%s for write commands",
608                         bank->bank_number,
609                         stm32l4_info->otp_enabled == enable ? "already " : "",
610                         op_str);
611
612         stm32l4_info->otp_enabled = enable;
613
614         return ERROR_OK;
615 }
616
617 static inline bool stm32l4_otp_is_enabled(struct flash_bank *bank)
618 {
619         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
620         return stm32l4_info->otp_enabled;
621 }
622
623 static void stm32l4_sync_rdp_tzen(struct flash_bank *bank, uint32_t optr_value)
624 {
625         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
626
627         bool tzen = false;
628
629         if (stm32l4_info->part_info->flags & F_HAS_TZ)
630                 tzen = (optr_value & FLASH_TZEN) != 0;
631
632         uint32_t rdp = optr_value & FLASH_RDP_MASK;
633
634         /* for devices without TrustZone:
635          *   RDP level 0 and 2 values are to 0xAA and 0xCC
636          *   Any other value corresponds to RDP level 1
637          * for devices with TrusZone:
638          *   RDP level 0 and 2 values are 0xAA and 0xCC
639          *   RDP level 0.5 value is 0x55 only if TZEN = 1
640          *   Any other value corresponds to RDP level 1, including 0x55 if TZEN = 0
641          */
642
643         if (rdp != RDP_LEVEL_0 && rdp != RDP_LEVEL_2) {
644                 if (!tzen || (tzen && rdp != RDP_LEVEL_0_5))
645                         rdp = RDP_LEVEL_1;
646         }
647
648         stm32l4_info->tzen = tzen;
649         stm32l4_info->rdp = rdp;
650 }
651
652 static inline uint32_t stm32l4_get_flash_reg(struct flash_bank *bank, uint32_t reg_offset)
653 {
654         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
655         return stm32l4_info->part_info->flash_regs_base + reg_offset;
656 }
657
658 static inline uint32_t stm32l4_get_flash_reg_by_index(struct flash_bank *bank,
659         enum stm32l4_flash_reg_index reg_index)
660 {
661         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
662         return stm32l4_get_flash_reg(bank, stm32l4_info->flash_regs[reg_index]);
663 }
664
665 static inline int stm32l4_read_flash_reg(struct flash_bank *bank, uint32_t reg_offset, uint32_t *value)
666 {
667         return target_read_u32(bank->target, stm32l4_get_flash_reg(bank, reg_offset), value);
668 }
669
670 static inline int stm32l4_read_flash_reg_by_index(struct flash_bank *bank,
671         enum stm32l4_flash_reg_index reg_index, uint32_t *value)
672 {
673         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
674         return stm32l4_read_flash_reg(bank, stm32l4_info->flash_regs[reg_index], value);
675 }
676
677 static inline int stm32l4_write_flash_reg(struct flash_bank *bank, uint32_t reg_offset, uint32_t value)
678 {
679         return target_write_u32(bank->target, stm32l4_get_flash_reg(bank, reg_offset), value);
680 }
681
682 static inline int stm32l4_write_flash_reg_by_index(struct flash_bank *bank,
683         enum stm32l4_flash_reg_index reg_index, uint32_t value)
684 {
685         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
686         return stm32l4_write_flash_reg(bank, stm32l4_info->flash_regs[reg_index], value);
687 }
688
689 static int stm32l4_wait_status_busy(struct flash_bank *bank, int timeout)
690 {
691         uint32_t status;
692         int retval = ERROR_OK;
693
694         /* wait for busy to clear */
695         for (;;) {
696                 retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_SR_INDEX, &status);
697                 if (retval != ERROR_OK)
698                         return retval;
699                 LOG_DEBUG("status: 0x%" PRIx32 "", status);
700                 if ((status & FLASH_BSY) == 0)
701                         break;
702                 if (timeout-- <= 0) {
703                         LOG_ERROR("timed out waiting for flash");
704                         return ERROR_FAIL;
705                 }
706                 alive_sleep(1);
707         }
708
709         if (status & FLASH_WRPERR) {
710                 LOG_ERROR("stm32x device protected");
711                 retval = ERROR_FAIL;
712         }
713
714         /* Clear but report errors */
715         if (status & FLASH_ERROR) {
716                 if (retval == ERROR_OK)
717                         retval = ERROR_FAIL;
718                 /* If this operation fails, we ignore it and report the original
719                  * retval
720                  */
721                 stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_SR_INDEX, status & FLASH_ERROR);
722         }
723
724         return retval;
725 }
726
727 static int stm32l4_unlock_reg(struct flash_bank *bank)
728 {
729         uint32_t ctrl;
730
731         /* first check if not already unlocked
732          * otherwise writing on STM32_FLASH_KEYR will fail
733          */
734         int retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, &ctrl);
735         if (retval != ERROR_OK)
736                 return retval;
737
738         if ((ctrl & FLASH_LOCK) == 0)
739                 return ERROR_OK;
740
741         /* unlock flash registers */
742         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_KEYR_INDEX, KEY1);
743         if (retval != ERROR_OK)
744                 return retval;
745
746         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_KEYR_INDEX, KEY2);
747         if (retval != ERROR_OK)
748                 return retval;
749
750         retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, &ctrl);
751         if (retval != ERROR_OK)
752                 return retval;
753
754         if (ctrl & FLASH_LOCK) {
755                 LOG_ERROR("flash not unlocked STM32_FLASH_CR: %" PRIx32, ctrl);
756                 return ERROR_TARGET_FAILURE;
757         }
758
759         return ERROR_OK;
760 }
761
762 static int stm32l4_unlock_option_reg(struct flash_bank *bank)
763 {
764         uint32_t ctrl;
765
766         int retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, &ctrl);
767         if (retval != ERROR_OK)
768                 return retval;
769
770         if ((ctrl & FLASH_OPTLOCK) == 0)
771                 return ERROR_OK;
772
773         /* unlock option registers */
774         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_OPTKEYR_INDEX, OPTKEY1);
775         if (retval != ERROR_OK)
776                 return retval;
777
778         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_OPTKEYR_INDEX, OPTKEY2);
779         if (retval != ERROR_OK)
780                 return retval;
781
782         retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, &ctrl);
783         if (retval != ERROR_OK)
784                 return retval;
785
786         if (ctrl & FLASH_OPTLOCK) {
787                 LOG_ERROR("options not unlocked STM32_FLASH_CR: %" PRIx32, ctrl);
788                 return ERROR_TARGET_FAILURE;
789         }
790
791         return ERROR_OK;
792 }
793
794 static int stm32l4_perform_obl_launch(struct flash_bank *bank)
795 {
796         int retval, retval2;
797
798         retval = stm32l4_unlock_reg(bank);
799         if (retval != ERROR_OK)
800                 goto err_lock;
801
802         retval = stm32l4_unlock_option_reg(bank);
803         if (retval != ERROR_OK)
804                 goto err_lock;
805
806         /* Set OBL_LAUNCH bit in CR -> system reset and option bytes reload,
807          * but the RMs explicitly do *NOT* list this as power-on reset cause, and:
808          * "Note: If the read protection is set while the debugger is still
809          * connected through JTAG/SWD, apply a POR (power-on reset) instead of a system reset."
810          */
811
812         /* "Setting OBL_LAUNCH generates a reset so the option byte loading is performed under system reset" */
813         /* Due to this reset ST-Link reports an SWD_DP_ERROR, despite the write was successful,
814          * then just ignore the returned value */
815         stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_OBL_LAUNCH);
816
817         /* Need to re-probe after change */
818         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
819         stm32l4_info->probed = false;
820
821 err_lock:
822         retval2 = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_LOCK | FLASH_OPTLOCK);
823
824         if (retval != ERROR_OK)
825                 return retval;
826
827         return retval2;
828 }
829
830 static int stm32l4_write_option(struct flash_bank *bank, uint32_t reg_offset,
831         uint32_t value, uint32_t mask)
832 {
833         uint32_t optiondata;
834         int retval, retval2;
835
836         retval = stm32l4_read_flash_reg(bank, reg_offset, &optiondata);
837         if (retval != ERROR_OK)
838                 return retval;
839
840         retval = stm32l4_unlock_reg(bank);
841         if (retval != ERROR_OK)
842                 goto err_lock;
843
844         retval = stm32l4_unlock_option_reg(bank);
845         if (retval != ERROR_OK)
846                 goto err_lock;
847
848         optiondata = (optiondata & ~mask) | (value & mask);
849
850         retval = stm32l4_write_flash_reg(bank, reg_offset, optiondata);
851         if (retval != ERROR_OK)
852                 goto err_lock;
853
854         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_OPTSTRT);
855         if (retval != ERROR_OK)
856                 goto err_lock;
857
858         retval = stm32l4_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
859
860 err_lock:
861         retval2 = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_LOCK | FLASH_OPTLOCK);
862
863         if (retval != ERROR_OK)
864                 return retval;
865
866         return retval2;
867 }
868
869 static int stm32l4_get_one_wrpxy(struct flash_bank *bank, struct stm32l4_wrp *wrpxy,
870                 enum stm32l4_flash_reg_index reg_idx, int offset)
871 {
872         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
873         int ret;
874
875         wrpxy->reg_idx = reg_idx;
876         wrpxy->offset = offset;
877
878         ret = stm32l4_read_flash_reg_by_index(bank, wrpxy->reg_idx , &wrpxy->value);
879         if (ret != ERROR_OK)
880                 return ret;
881
882         wrpxy->first = (wrpxy->value & stm32l4_info->wrpxxr_mask) + wrpxy->offset;
883         wrpxy->last = ((wrpxy->value >> 16) & stm32l4_info->wrpxxr_mask) + wrpxy->offset;
884         wrpxy->used = wrpxy->first <= wrpxy->last;
885
886         return ERROR_OK;
887 }
888
889 static int stm32l4_get_all_wrpxy(struct flash_bank *bank, enum stm32_bank_id dev_bank_id,
890                 struct stm32l4_wrp *wrpxy, unsigned int *n_wrp)
891 {
892         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
893         int ret;
894
895         *n_wrp = 0;
896
897         /* for single bank devices there is 2 WRP regions.
898          * for dual bank devices there is 2 WRP regions per bank,
899          *   if configured as single bank only 2 WRP are usable
900          *   except for STM32L4R/S/P/Q, G4 cat3, L5 ... all 4 WRP are usable
901          * note: this should be revised, if a device will have the SWAP banks option
902          */
903
904         int wrp2y_sectors_offset = -1; /* -1 : unused */
905
906         /* if bank_id is BANK1 or ALL_BANKS */
907         if (dev_bank_id != STM32_BANK2) {
908                 /* get FLASH_WRP1AR */
909                 ret = stm32l4_get_one_wrpxy(bank, &wrpxy[(*n_wrp)++], STM32_FLASH_WRP1AR_INDEX, 0);
910                 if (ret != ERROR_OK)
911                         return ret;
912
913                 /* get WRP1BR */
914                 ret = stm32l4_get_one_wrpxy(bank, &wrpxy[(*n_wrp)++], STM32_FLASH_WRP1BR_INDEX, 0);
915                 if (ret != ERROR_OK)
916                         return ret;
917
918                 /* for some devices (like STM32L4R/S) in single-bank mode, the 4 WRPxx are usable */
919                 if ((stm32l4_info->part_info->flags & F_USE_ALL_WRPXX) && !stm32l4_info->dual_bank_mode)
920                         wrp2y_sectors_offset = 0;
921         }
922
923         /* if bank_id is BANK2 or ALL_BANKS */
924         if (dev_bank_id != STM32_BANK1 && stm32l4_info->dual_bank_mode)
925                 wrp2y_sectors_offset = stm32l4_info->bank1_sectors;
926
927         if (wrp2y_sectors_offset > -1) {
928                 /* get WRP2AR */
929                 ret = stm32l4_get_one_wrpxy(bank, &wrpxy[(*n_wrp)++], STM32_FLASH_WRP2AR_INDEX, wrp2y_sectors_offset);
930                 if (ret != ERROR_OK)
931                         return ret;
932
933                 /* get WRP2BR */
934                 ret = stm32l4_get_one_wrpxy(bank, &wrpxy[(*n_wrp)++], STM32_FLASH_WRP2BR_INDEX, wrp2y_sectors_offset);
935                 if (ret != ERROR_OK)
936                         return ret;
937         }
938
939         return ERROR_OK;
940 }
941
942 static int stm32l4_write_one_wrpxy(struct flash_bank *bank, struct stm32l4_wrp *wrpxy)
943 {
944         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
945
946         int wrp_start = wrpxy->first - wrpxy->offset;
947         int wrp_end = wrpxy->last - wrpxy->offset;
948
949         uint32_t wrp_value = (wrp_start & stm32l4_info->wrpxxr_mask) | ((wrp_end & stm32l4_info->wrpxxr_mask) << 16);
950
951         return stm32l4_write_option(bank, stm32l4_info->flash_regs[wrpxy->reg_idx], wrp_value, 0xffffffff);
952 }
953
954 static int stm32l4_write_all_wrpxy(struct flash_bank *bank, struct stm32l4_wrp *wrpxy, unsigned int n_wrp)
955 {
956         int ret;
957
958         for (unsigned int i = 0; i < n_wrp; i++) {
959                 ret = stm32l4_write_one_wrpxy(bank, &wrpxy[i]);
960                 if (ret != ERROR_OK)
961                         return ret;
962         }
963
964         return ERROR_OK;
965 }
966
967 static int stm32l4_protect_check(struct flash_bank *bank)
968 {
969         unsigned int n_wrp;
970         struct stm32l4_wrp wrpxy[4];
971
972         int ret = stm32l4_get_all_wrpxy(bank, STM32_ALL_BANKS, wrpxy, &n_wrp);
973         if (ret != ERROR_OK)
974                 return ret;
975
976         /* initialize all sectors as unprotected */
977         for (unsigned int i = 0; i < bank->num_sectors; i++)
978                 bank->sectors[i].is_protected = 0;
979
980         /* now check WRPxy and mark the protected sectors */
981         for (unsigned int i = 0; i < n_wrp; i++) {
982                 if (wrpxy[i].used) {
983                         for (int s = wrpxy[i].first; s <= wrpxy[i].last; s++)
984                                 bank->sectors[s].is_protected = 1;
985                 }
986         }
987
988         return ERROR_OK;
989 }
990
991 static int stm32l4_erase(struct flash_bank *bank, unsigned int first,
992                 unsigned int last)
993 {
994         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
995         int retval, retval2;
996
997         assert((first <= last) && (last < bank->num_sectors));
998
999         if (stm32l4_is_otp(bank)) {
1000                 LOG_ERROR("cannot erase OTP memory");
1001                 return ERROR_FLASH_OPER_UNSUPPORTED;
1002         }
1003
1004         if (bank->target->state != TARGET_HALTED) {
1005                 LOG_ERROR("Target not halted");
1006                 return ERROR_TARGET_NOT_HALTED;
1007         }
1008
1009         retval = stm32l4_unlock_reg(bank);
1010         if (retval != ERROR_OK)
1011                 goto err_lock;
1012
1013         /*
1014         Sector Erase
1015         To erase a sector, follow the procedure below:
1016         1. Check that no Flash memory operation is ongoing by
1017            checking the BSY bit in the FLASH_SR register
1018         2. Set the PER bit and select the page and bank
1019            you wish to erase in the FLASH_CR register
1020         3. Set the STRT bit in the FLASH_CR register
1021         4. Wait for the BSY bit to be cleared
1022          */
1023
1024         for (unsigned int i = first; i <= last; i++) {
1025                 uint32_t erase_flags;
1026                 erase_flags = FLASH_PER | FLASH_STRT;
1027
1028                 if (i >= stm32l4_info->bank1_sectors) {
1029                         uint8_t snb;
1030                         snb = i - stm32l4_info->bank1_sectors;
1031                         erase_flags |= snb << FLASH_PAGE_SHIFT | FLASH_CR_BKER;
1032                 } else
1033                         erase_flags |= i << FLASH_PAGE_SHIFT;
1034                 retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, erase_flags);
1035                 if (retval != ERROR_OK)
1036                         break;
1037
1038                 retval = stm32l4_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
1039                 if (retval != ERROR_OK)
1040                         break;
1041         }
1042
1043 err_lock:
1044         retval2 = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_LOCK);
1045
1046         if (retval != ERROR_OK)
1047                 return retval;
1048
1049         return retval2;
1050 }
1051
1052 static int stm32l4_protect(struct flash_bank *bank, int set, unsigned int first, unsigned int last)
1053 {
1054         struct target *target = bank->target;
1055         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1056         int ret = ERROR_OK;
1057         unsigned int i;
1058
1059         if (stm32l4_is_otp(bank)) {
1060                 LOG_ERROR("cannot protect/unprotect OTP memory");
1061                 return ERROR_FLASH_OPER_UNSUPPORTED;
1062         }
1063
1064         if (target->state != TARGET_HALTED) {
1065                 LOG_ERROR("Target not halted");
1066                 return ERROR_TARGET_NOT_HALTED;
1067         }
1068
1069         /* the requested sectors could be located into bank1 and/or bank2 */
1070         bool use_bank2 = false;
1071         if (last >= stm32l4_info->bank1_sectors) {
1072                 if (first < stm32l4_info->bank1_sectors) {
1073                         /* the requested sectors for (un)protection are shared between
1074                          * bank 1 and 2, then split the operation */
1075
1076                         /*  1- deal with bank 1 sectors */
1077                         LOG_DEBUG("The requested sectors for %s are shared between bank 1 and 2",
1078                                         set ? "protection" : "unprotection");
1079                         ret = stm32l4_protect(bank, set, first, stm32l4_info->bank1_sectors - 1);
1080                         if (ret != ERROR_OK)
1081                                 return ret;
1082
1083                         /*  2- then continue with bank 2 sectors */
1084                         first = stm32l4_info->bank1_sectors;
1085                 }
1086
1087                 use_bank2 = true;
1088         }
1089
1090         /* refresh the sectors' protection */
1091         ret = stm32l4_protect_check(bank);
1092         if (ret != ERROR_OK)
1093                 return ret;
1094
1095         /* check if the desired protection is already configured */
1096         for (i = first; i <= last; i++) {
1097                 if (bank->sectors[i].is_protected != set)
1098                         break;
1099                 else if (i == last) {
1100                         LOG_INFO("The specified sectors are already %s", set ? "protected" : "unprotected");
1101                         return ERROR_OK;
1102                 }
1103         }
1104
1105         /* all sectors from first to last (or part of them) could have different
1106          * protection other than the requested */
1107         unsigned int n_wrp;
1108         struct stm32l4_wrp wrpxy[4];
1109
1110         ret = stm32l4_get_all_wrpxy(bank, use_bank2 ? STM32_BANK2 : STM32_BANK1, wrpxy, &n_wrp);
1111         if (ret != ERROR_OK)
1112                 return ret;
1113
1114         /* use bitmap and range helpers to optimize the WRP usage */
1115         DECLARE_BITMAP(pages, bank->num_sectors);
1116         bitmap_zero(pages, bank->num_sectors);
1117
1118         for (i = 0; i < n_wrp; i++) {
1119                 if (wrpxy[i].used) {
1120                         for (int p = wrpxy[i].first; p <= wrpxy[i].last; p++)
1121                                 set_bit(p, pages);
1122                 }
1123         }
1124
1125         /* we have at most 'n_wrp' WRP areas
1126          * add one range if the user is trying to protect a fifth range */
1127         struct range ranges[n_wrp + 1];
1128         unsigned int ranges_count = 0;
1129
1130         bitmap_to_ranges(pages, bank->num_sectors, ranges, &ranges_count);
1131
1132         /* pretty-print the currently protected ranges */
1133         if (ranges_count > 0) {
1134                 char *ranges_str = range_print_alloc(ranges, ranges_count);
1135                 LOG_DEBUG("current protected areas: %s", ranges_str);
1136                 free(ranges_str);
1137         } else
1138                 LOG_DEBUG("current protected areas: none");
1139
1140         if (set) { /* flash protect */
1141                 for (i = first; i <= last; i++)
1142                         set_bit(i, pages);
1143         } else { /* flash unprotect */
1144                 for (i = first; i <= last; i++)
1145                         clear_bit(i, pages);
1146         }
1147
1148         /* check the ranges_count after the user request */
1149         bitmap_to_ranges(pages, bank->num_sectors, ranges, &ranges_count);
1150
1151         /* pretty-print the requested areas for protection */
1152         if (ranges_count > 0) {
1153                 char *ranges_str = range_print_alloc(ranges, ranges_count);
1154                 LOG_DEBUG("requested areas for protection: %s", ranges_str);
1155                 free(ranges_str);
1156         } else
1157                 LOG_DEBUG("requested areas for protection: none");
1158
1159         if (ranges_count > n_wrp) {
1160                 LOG_ERROR("cannot set the requested protection "
1161                                 "(only %u write protection areas are available)" , n_wrp);
1162                 return ERROR_FAIL;
1163         }
1164
1165         /* re-init all WRPxy as disabled (first > last)*/
1166         for (i = 0; i < n_wrp; i++) {
1167                 wrpxy[i].first = wrpxy[i].offset + 1;
1168                 wrpxy[i].last = wrpxy[i].offset;
1169         }
1170
1171         /* then configure WRPxy areas */
1172         for (i = 0; i < ranges_count; i++) {
1173                 wrpxy[i].first = ranges[i].start;
1174                 wrpxy[i].last = ranges[i].end;
1175         }
1176
1177         /* finally write WRPxy registers */
1178         return stm32l4_write_all_wrpxy(bank, wrpxy, n_wrp);
1179 }
1180
1181 /* Count is in double-words */
1182 static int stm32l4_write_block(struct flash_bank *bank, const uint8_t *buffer,
1183         uint32_t offset, uint32_t count)
1184 {
1185         struct target *target = bank->target;
1186         uint32_t buffer_size;
1187         struct working_area *write_algorithm;
1188         struct working_area *source;
1189         uint32_t address = bank->base + offset;
1190         struct reg_param reg_params[6];
1191         struct armv7m_algorithm armv7m_info;
1192         int retval = ERROR_OK;
1193
1194         static const uint8_t stm32l4_flash_write_code[] = {
1195 #include "../../../contrib/loaders/flash/stm32/stm32l4x.inc"
1196         };
1197
1198         if (target_alloc_working_area(target, sizeof(stm32l4_flash_write_code),
1199                         &write_algorithm) != ERROR_OK) {
1200                 LOG_WARNING("no working area available, can't do block memory writes");
1201                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1202         }
1203
1204         retval = target_write_buffer(target, write_algorithm->address,
1205                         sizeof(stm32l4_flash_write_code),
1206                         stm32l4_flash_write_code);
1207         if (retval != ERROR_OK) {
1208                 target_free_working_area(target, write_algorithm);
1209                 return retval;
1210         }
1211
1212         /* memory buffer, size *must* be multiple of dword plus one dword for rp and one for wp */
1213         buffer_size = target_get_working_area_avail(target) & ~(2 * sizeof(uint32_t) - 1);
1214         if (buffer_size < 256) {
1215                 LOG_WARNING("large enough working area not available, can't do block memory writes");
1216                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1217         } else if (buffer_size > 16384) {
1218                 /* probably won't benefit from more than 16k ... */
1219                 buffer_size = 16384;
1220         }
1221
1222         if (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) {
1223                 LOG_ERROR("allocating working area failed");
1224                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1225         }
1226
1227         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
1228         armv7m_info.core_mode = ARM_MODE_THREAD;
1229
1230         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT); /* buffer start, status (out) */
1231         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);    /* buffer end */
1232         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);    /* target address */
1233         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);    /* count (double word-64bit) */
1234         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);    /* flash status register */
1235         init_reg_param(&reg_params[5], "r5", 32, PARAM_OUT);    /* flash control register */
1236
1237         buf_set_u32(reg_params[0].value, 0, 32, source->address);
1238         buf_set_u32(reg_params[1].value, 0, 32, source->address + source->size);
1239         buf_set_u32(reg_params[2].value, 0, 32, address);
1240         buf_set_u32(reg_params[3].value, 0, 32, count);
1241         buf_set_u32(reg_params[4].value, 0, 32, stm32l4_get_flash_reg_by_index(bank, STM32_FLASH_SR_INDEX));
1242         buf_set_u32(reg_params[5].value, 0, 32, stm32l4_get_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX));
1243
1244         retval = target_run_flash_async_algorithm(target, buffer, count, 8,
1245                         0, NULL,
1246                         ARRAY_SIZE(reg_params), reg_params,
1247                         source->address, source->size,
1248                         write_algorithm->address, 0,
1249                         &armv7m_info);
1250
1251         if (retval == ERROR_FLASH_OPERATION_FAILED) {
1252                 LOG_ERROR("error executing stm32l4 flash write algorithm");
1253
1254                 uint32_t error = buf_get_u32(reg_params[0].value, 0, 32) & FLASH_ERROR;
1255
1256                 if (error & FLASH_WRPERR)
1257                         LOG_ERROR("flash memory write protected");
1258
1259                 if (error != 0) {
1260                         LOG_ERROR("flash write failed = %08" PRIx32, error);
1261                         /* Clear but report errors */
1262                         stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_SR_INDEX, error);
1263                         retval = ERROR_FAIL;
1264                 }
1265         }
1266
1267         target_free_working_area(target, source);
1268         target_free_working_area(target, write_algorithm);
1269
1270         destroy_reg_param(&reg_params[0]);
1271         destroy_reg_param(&reg_params[1]);
1272         destroy_reg_param(&reg_params[2]);
1273         destroy_reg_param(&reg_params[3]);
1274         destroy_reg_param(&reg_params[4]);
1275         destroy_reg_param(&reg_params[5]);
1276
1277         return retval;
1278 }
1279
1280 static int stm32l4_write(struct flash_bank *bank, const uint8_t *buffer,
1281         uint32_t offset, uint32_t count)
1282 {
1283         int retval = ERROR_OK, retval2;
1284
1285         if (stm32l4_is_otp(bank) && !stm32l4_otp_is_enabled(bank)) {
1286                 LOG_ERROR("OTP memory is disabled for write commands");
1287                 return ERROR_FAIL;
1288         }
1289
1290         if (bank->target->state != TARGET_HALTED) {
1291                 LOG_ERROR("Target not halted");
1292                 return ERROR_TARGET_NOT_HALTED;
1293         }
1294
1295         /* The flash write must be aligned to a double word (8-bytes) boundary.
1296          * The flash infrastructure ensures it, do just a security check */
1297         assert(offset % 8 == 0);
1298         assert(count % 8 == 0);
1299
1300         /* STM32G4xxx Cat. 3 devices may have gaps between banks, check whether
1301          * data to be written does not go into a gap:
1302          * suppose buffer is fully contained in bank from sector 0 to sector
1303          * num->sectors - 1 and sectors are ordered according to offset
1304          */
1305         struct flash_sector *head = &bank->sectors[0];
1306         struct flash_sector *tail = &bank->sectors[bank->num_sectors - 1];
1307
1308         while ((head < tail) && (offset >= (head + 1)->offset)) {
1309                 /* buffer does not intersect head nor gap behind head */
1310                 head++;
1311         }
1312
1313         while ((head < tail) && (offset + count <= (tail - 1)->offset + (tail - 1)->size)) {
1314                 /* buffer does not intersect tail nor gap before tail */
1315                 --tail;
1316         }
1317
1318         LOG_DEBUG("data: 0x%08" PRIx32 " - 0x%08" PRIx32 ", sectors: 0x%08" PRIx32 " - 0x%08" PRIx32,
1319                 offset, offset + count - 1, head->offset, tail->offset + tail->size - 1);
1320
1321         /* Now check that there is no gap from head to tail, this should work
1322          * even for multiple or non-symmetric gaps
1323          */
1324         while (head < tail) {
1325                 if (head->offset + head->size != (head + 1)->offset) {
1326                         LOG_ERROR("write into gap from " TARGET_ADDR_FMT " to " TARGET_ADDR_FMT,
1327                                 bank->base + head->offset + head->size,
1328                                 bank->base + (head + 1)->offset - 1);
1329                         retval = ERROR_FLASH_DST_OUT_OF_BANK;
1330                 }
1331                 head++;
1332         }
1333
1334         if (retval != ERROR_OK)
1335                 return retval;
1336
1337         retval = stm32l4_unlock_reg(bank);
1338         if (retval != ERROR_OK)
1339                 goto err_lock;
1340
1341         retval = stm32l4_write_block(bank, buffer, offset, count / 8);
1342
1343 err_lock:
1344         retval2 = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_LOCK);
1345
1346         if (retval != ERROR_OK) {
1347                 LOG_ERROR("block write failed");
1348                 return retval;
1349         }
1350         return retval2;
1351 }
1352
1353 static int stm32l4_read_idcode(struct flash_bank *bank, uint32_t *id)
1354 {
1355         int retval;
1356
1357         /* try reading possible IDCODE registers, in the following order */
1358         uint32_t dbgmcu_idcode[] = {DBGMCU_IDCODE_L4_G4, DBGMCU_IDCODE_G0, DBGMCU_IDCODE_L5};
1359
1360         for (unsigned int i = 0; i < ARRAY_SIZE(dbgmcu_idcode); i++) {
1361                 retval = target_read_u32(bank->target, dbgmcu_idcode[i], id);
1362                 if ((retval == ERROR_OK) && ((*id & 0xfff) != 0) && ((*id & 0xfff) != 0xfff))
1363                         return ERROR_OK;
1364         }
1365
1366         LOG_ERROR("can't get the device id");
1367         return (retval == ERROR_OK) ? ERROR_FAIL : retval;
1368 }
1369
1370 static const char *get_stm32l4_rev_str(struct flash_bank *bank)
1371 {
1372         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1373         const struct stm32l4_part_info *part_info = stm32l4_info->part_info;
1374         assert(part_info);
1375
1376         const uint16_t rev_id = stm32l4_info->idcode >> 16;
1377         for (unsigned int i = 0; i < part_info->num_revs; i++) {
1378                 if (rev_id == part_info->revs[i].rev)
1379                         return part_info->revs[i].str;
1380         }
1381         return "'unknown'";
1382 }
1383
1384 static const char *get_stm32l4_bank_type_str(struct flash_bank *bank)
1385 {
1386         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1387         assert(stm32l4_info->part_info);
1388         return stm32l4_is_otp(bank) ? "OTP" :
1389                         stm32l4_info->dual_bank_mode ? "Flash dual" :
1390                         "Flash single";
1391 }
1392
1393 static int stm32l4_probe(struct flash_bank *bank)
1394 {
1395         struct target *target = bank->target;
1396         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1397         const struct stm32l4_part_info *part_info;
1398         uint16_t flash_size_kb = 0xffff;
1399         uint32_t options;
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, &options);
1433         if (retval != ERROR_OK)
1434                 return retval;
1435
1436         stm32l4_sync_rdp_tzen(bank, options);
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 || (options & 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 (options & 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 && (options & BIT(22))) ||
1569                         (!use_dbank_bit && (options & 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 && (options & BIT(22))) ||
1586                         (!use_dbank_bit && (options & 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                 return ERROR_OK;
1665
1666         return stm32l4_probe(bank);
1667 }
1668
1669 static int get_stm32l4_info(struct flash_bank *bank, struct command_invocation *cmd)
1670 {
1671         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1672         const struct stm32l4_part_info *part_info = stm32l4_info->part_info;
1673
1674         if (part_info) {
1675                 const uint16_t rev_id = stm32l4_info->idcode >> 16;
1676                 command_print_sameline(cmd, "%s - Rev %s : 0x%04x", part_info->device_str,
1677                                 get_stm32l4_rev_str(bank), rev_id);
1678                 if (stm32l4_info->probed)
1679                         command_print_sameline(cmd, " - %s-bank", get_stm32l4_bank_type_str(bank));
1680         } else {
1681                 command_print_sameline(cmd, "Cannot identify target as an %s device", device_families);
1682         }
1683
1684         return ERROR_OK;
1685 }
1686
1687 static int stm32l4_mass_erase(struct flash_bank *bank)
1688 {
1689         int retval, retval2;
1690         struct target *target = bank->target;
1691         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1692
1693         if (stm32l4_is_otp(bank)) {
1694                 LOG_ERROR("cannot erase OTP memory");
1695                 return ERROR_FLASH_OPER_UNSUPPORTED;
1696         }
1697
1698         uint32_t action = FLASH_MER1;
1699
1700         if (stm32l4_info->part_info->flags & F_HAS_DUAL_BANK)
1701                 action |= FLASH_MER2;
1702
1703         if (target->state != TARGET_HALTED) {
1704                 LOG_ERROR("Target not halted");
1705                 return ERROR_TARGET_NOT_HALTED;
1706         }
1707
1708         retval = stm32l4_unlock_reg(bank);
1709         if (retval != ERROR_OK)
1710                 goto err_lock;
1711
1712         /* mass erase flash memory */
1713         retval = stm32l4_wait_status_busy(bank, FLASH_ERASE_TIMEOUT / 10);
1714         if (retval != ERROR_OK)
1715                 goto err_lock;
1716
1717         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, action);
1718         if (retval != ERROR_OK)
1719                 goto err_lock;
1720
1721         retval = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, action | FLASH_STRT);
1722         if (retval != ERROR_OK)
1723                 goto err_lock;
1724
1725         retval = stm32l4_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
1726
1727 err_lock:
1728         retval2 = stm32l4_write_flash_reg_by_index(bank, STM32_FLASH_CR_INDEX, FLASH_LOCK);
1729
1730         if (retval != ERROR_OK)
1731                 return retval;
1732
1733         return retval2;
1734 }
1735
1736 COMMAND_HANDLER(stm32l4_handle_mass_erase_command)
1737 {
1738         if (CMD_ARGC < 1) {
1739                 command_print(CMD, "stm32l4x mass_erase <STM32L4 bank>");
1740                 return ERROR_COMMAND_SYNTAX_ERROR;
1741         }
1742
1743         struct flash_bank *bank;
1744         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1745         if (retval != ERROR_OK)
1746                 return retval;
1747
1748         retval = stm32l4_mass_erase(bank);
1749         if (retval == ERROR_OK)
1750                 command_print(CMD, "stm32l4x mass erase complete");
1751         else
1752                 command_print(CMD, "stm32l4x mass erase failed");
1753
1754         return retval;
1755 }
1756
1757 COMMAND_HANDLER(stm32l4_handle_option_read_command)
1758 {
1759         if (CMD_ARGC < 2) {
1760                 command_print(CMD, "stm32l4x option_read <STM32L4 bank> <option_reg offset>");
1761                 return ERROR_COMMAND_SYNTAX_ERROR;
1762         }
1763
1764         struct flash_bank *bank;
1765         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1766         if (retval != ERROR_OK)
1767                 return retval;
1768
1769         uint32_t reg_offset, reg_addr;
1770         uint32_t value = 0;
1771
1772         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], reg_offset);
1773         reg_addr = stm32l4_get_flash_reg(bank, reg_offset);
1774
1775         retval = stm32l4_read_flash_reg(bank, reg_offset, &value);
1776         if (retval != ERROR_OK)
1777                 return retval;
1778
1779         command_print(CMD, "Option Register: <0x%" PRIx32 "> = 0x%" PRIx32 "", reg_addr, value);
1780
1781         return retval;
1782 }
1783
1784 COMMAND_HANDLER(stm32l4_handle_option_write_command)
1785 {
1786         if (CMD_ARGC < 3) {
1787                 command_print(CMD, "stm32l4x option_write <STM32L4 bank> <option_reg offset> <value> [mask]");
1788                 return ERROR_COMMAND_SYNTAX_ERROR;
1789         }
1790
1791         struct flash_bank *bank;
1792         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1793         if (retval != ERROR_OK)
1794                 return retval;
1795
1796         uint32_t reg_offset;
1797         uint32_t value = 0;
1798         uint32_t mask = 0xFFFFFFFF;
1799
1800         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], reg_offset);
1801         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], value);
1802
1803         if (CMD_ARGC > 3)
1804                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], mask);
1805
1806         command_print(CMD, "%s Option written.\n"
1807                                 "INFO: a reset or power cycle is required "
1808                                 "for the new settings to take effect.", bank->driver->name);
1809
1810         retval = stm32l4_write_option(bank, reg_offset, value, mask);
1811         return retval;
1812 }
1813
1814 COMMAND_HANDLER(stm32l4_handle_trustzone_command)
1815 {
1816         if (CMD_ARGC < 1 || CMD_ARGC > 2)
1817                 return ERROR_COMMAND_SYNTAX_ERROR;
1818
1819         struct flash_bank *bank;
1820         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1821         if (retval != ERROR_OK)
1822                 return retval;
1823
1824         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1825         if (!(stm32l4_info->part_info->flags & F_HAS_TZ)) {
1826                 LOG_ERROR("This device does not have a TrustZone");
1827                 return ERROR_FAIL;
1828         }
1829
1830         uint32_t optr;
1831         retval = stm32l4_read_flash_reg_by_index(bank, STM32_FLASH_OPTR_INDEX, &optr);
1832         if (retval != ERROR_OK)
1833                 return retval;
1834
1835         stm32l4_sync_rdp_tzen(bank, optr);
1836
1837         if (CMD_ARGC == 1) {
1838                 /* only display the TZEN value */
1839                 LOG_INFO("Global TrustZone Security is %s", stm32l4_info->tzen ? "enabled" : "disabled");
1840                 return ERROR_OK;
1841         }
1842
1843         bool new_tzen;
1844         COMMAND_PARSE_ENABLE(CMD_ARGV[1], new_tzen);
1845
1846         if (new_tzen == stm32l4_info->tzen) {
1847                 LOG_INFO("The requested TZEN is already programmed");
1848                 return ERROR_OK;
1849         }
1850
1851         if (new_tzen) {
1852                 if (stm32l4_info->rdp != RDP_LEVEL_0) {
1853                         LOG_ERROR("TZEN can be set only when RDP level is 0");
1854                         return ERROR_FAIL;
1855                 }
1856                 retval = stm32l4_write_option(bank, stm32l4_info->flash_regs[STM32_FLASH_OPTR_INDEX],
1857                                 FLASH_TZEN, FLASH_TZEN);
1858         } else {
1859                 /* Deactivation of TZEN (from 1 to 0) is only possible when the RDP is
1860                  * changing to level 0 (from level 1 to level 0 or from level 0.5 to level 0). */
1861                 if (stm32l4_info->rdp != RDP_LEVEL_1 && stm32l4_info->rdp != RDP_LEVEL_0_5) {
1862                         LOG_ERROR("Deactivation of TZEN is only possible when the RDP is changing to level 0");
1863                         return ERROR_FAIL;
1864                 }
1865
1866                 retval = stm32l4_write_option(bank, stm32l4_info->flash_regs[STM32_FLASH_OPTR_INDEX],
1867                                 RDP_LEVEL_0, FLASH_RDP_MASK | FLASH_TZEN);
1868         }
1869
1870         if (retval != ERROR_OK)
1871                 return retval;
1872
1873         return stm32l4_perform_obl_launch(bank);
1874 }
1875
1876 COMMAND_HANDLER(stm32l4_handle_option_load_command)
1877 {
1878         if (CMD_ARGC != 1)
1879                 return ERROR_COMMAND_SYNTAX_ERROR;
1880
1881         struct flash_bank *bank;
1882         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1883         if (retval != ERROR_OK)
1884                 return retval;
1885
1886         retval = stm32l4_perform_obl_launch(bank);
1887         if (retval != ERROR_OK) {
1888                 command_print(CMD, "stm32l4x option load failed");
1889                 return retval;
1890         }
1891
1892
1893         command_print(CMD, "stm32l4x option load completed. Power-on reset might be required");
1894
1895         return ERROR_OK;
1896 }
1897
1898 COMMAND_HANDLER(stm32l4_handle_lock_command)
1899 {
1900         struct target *target = NULL;
1901
1902         if (CMD_ARGC < 1)
1903                 return ERROR_COMMAND_SYNTAX_ERROR;
1904
1905         struct flash_bank *bank;
1906         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1907         if (retval != ERROR_OK)
1908                 return retval;
1909
1910         if (stm32l4_is_otp(bank)) {
1911                 LOG_ERROR("cannot lock/unlock OTP memory");
1912                 return ERROR_FLASH_OPER_UNSUPPORTED;
1913         }
1914
1915         target = bank->target;
1916
1917         if (target->state != TARGET_HALTED) {
1918                 LOG_ERROR("Target not halted");
1919                 return ERROR_TARGET_NOT_HALTED;
1920         }
1921
1922         /* set readout protection level 1 by erasing the RDP option byte */
1923         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1924         if (stm32l4_write_option(bank, stm32l4_info->flash_regs[STM32_FLASH_OPTR_INDEX],
1925                         RDP_LEVEL_1, FLASH_RDP_MASK) != ERROR_OK) {
1926                 command_print(CMD, "%s failed to lock device", bank->driver->name);
1927                 return ERROR_OK;
1928         }
1929
1930         return ERROR_OK;
1931 }
1932
1933 COMMAND_HANDLER(stm32l4_handle_unlock_command)
1934 {
1935         struct target *target = NULL;
1936
1937         if (CMD_ARGC < 1)
1938                 return ERROR_COMMAND_SYNTAX_ERROR;
1939
1940         struct flash_bank *bank;
1941         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1942         if (retval != ERROR_OK)
1943                 return retval;
1944
1945         if (stm32l4_is_otp(bank)) {
1946                 LOG_ERROR("cannot lock/unlock OTP memory");
1947                 return ERROR_FLASH_OPER_UNSUPPORTED;
1948         }
1949
1950         target = bank->target;
1951
1952         if (target->state != TARGET_HALTED) {
1953                 LOG_ERROR("Target not halted");
1954                 return ERROR_TARGET_NOT_HALTED;
1955         }
1956
1957         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1958         if (stm32l4_write_option(bank, stm32l4_info->flash_regs[STM32_FLASH_OPTR_INDEX],
1959                         RDP_LEVEL_0, FLASH_RDP_MASK) != ERROR_OK) {
1960                 command_print(CMD, "%s failed to unlock device", bank->driver->name);
1961                 return ERROR_OK;
1962         }
1963
1964         return ERROR_OK;
1965 }
1966
1967 COMMAND_HANDLER(stm32l4_handle_wrp_info_command)
1968 {
1969         if (CMD_ARGC < 1 || CMD_ARGC > 2)
1970                 return ERROR_COMMAND_SYNTAX_ERROR;
1971
1972         struct flash_bank *bank;
1973         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1974         if (retval != ERROR_OK)
1975                 return retval;
1976
1977         if (stm32l4_is_otp(bank)) {
1978                 LOG_ERROR("OTP memory does not have write protection areas");
1979                 return ERROR_FLASH_OPER_UNSUPPORTED;
1980         }
1981
1982         struct stm32l4_flash_bank *stm32l4_info = bank->driver_priv;
1983         enum stm32_bank_id dev_bank_id = STM32_ALL_BANKS;
1984         if (CMD_ARGC == 2) {
1985                 if (strcmp(CMD_ARGV[1], "bank1") == 0)
1986                         dev_bank_id = STM32_BANK1;
1987                 else if (strcmp(CMD_ARGV[1], "bank2") == 0)
1988                         dev_bank_id = STM32_BANK2;
1989                 else
1990                         return ERROR_COMMAND_ARGUMENT_INVALID;
1991         }
1992
1993         if (dev_bank_id == STM32_BANK2) {
1994                 if (!(stm32l4_info->part_info->flags & F_HAS_DUAL_BANK)) {
1995                         LOG_ERROR("this device has no second bank");
1996                         return ERROR_FAIL;
1997                 } else if (!stm32l4_info->dual_bank_mode) {
1998                         LOG_ERROR("this device is configured in single bank mode");
1999                         return ERROR_FAIL;
2000                 }
2001         }
2002
2003         int ret;
2004         unsigned int n_wrp, i;
2005         struct stm32l4_wrp wrpxy[4];
2006
2007         ret = stm32l4_get_all_wrpxy(bank, dev_bank_id, wrpxy, &n_wrp);
2008         if (ret != ERROR_OK)
2009                 return ret;
2010
2011         /* use bitmap and range helpers to better describe protected areas */
2012         DECLARE_BITMAP(pages, bank->num_sectors);
2013         bitmap_zero(pages, bank->num_sectors);
2014
2015         for (i = 0; i < n_wrp; i++) {
2016                 if (wrpxy[i].used) {
2017                         for (int p = wrpxy[i].first; p <= wrpxy[i].last; p++)
2018                                 set_bit(p, pages);
2019                 }
2020         }
2021
2022         /* we have at most 'n_wrp' WRP areas */
2023         struct range ranges[n_wrp];
2024         unsigned int ranges_count = 0;
2025
2026         bitmap_to_ranges(pages, bank->num_sectors, ranges, &ranges_count);
2027
2028         if (ranges_count > 0) {
2029                 /* pretty-print the protected ranges */
2030                 char *ranges_str = range_print_alloc(ranges, ranges_count);
2031                 command_print(CMD, "protected areas: %s", ranges_str);
2032                 free(ranges_str);
2033         } else
2034                 command_print(CMD, "no protected areas");
2035
2036         return ERROR_OK;
2037 }
2038
2039 COMMAND_HANDLER(stm32l4_handle_otp_command)
2040 {
2041         if (CMD_ARGC < 2)
2042                 return ERROR_COMMAND_SYNTAX_ERROR;
2043
2044         struct flash_bank *bank;
2045         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
2046         if (retval != ERROR_OK)
2047                 return retval;
2048
2049         if (!stm32l4_is_otp(bank)) {
2050                 command_print(CMD, "the specified bank is not an OTP memory");
2051                 return ERROR_FAIL;
2052         }
2053         if (strcmp(CMD_ARGV[1], "enable") == 0)
2054                 stm32l4_otp_enable(bank, true);
2055         else if (strcmp(CMD_ARGV[1], "disable") == 0)
2056                 stm32l4_otp_enable(bank, false);
2057         else if (strcmp(CMD_ARGV[1], "show") == 0)
2058                 command_print(CMD, "OTP memory bank #%d is %s for write commands.",
2059                                 bank->bank_number, stm32l4_otp_is_enabled(bank) ? "enabled" : "disabled");
2060         else
2061                 return ERROR_COMMAND_SYNTAX_ERROR;
2062
2063         return ERROR_OK;
2064 }
2065
2066 static const struct command_registration stm32l4_exec_command_handlers[] = {
2067         {
2068                 .name = "lock",
2069                 .handler = stm32l4_handle_lock_command,
2070                 .mode = COMMAND_EXEC,
2071                 .usage = "bank_id",
2072                 .help = "Lock entire flash device.",
2073         },
2074         {
2075                 .name = "unlock",
2076                 .handler = stm32l4_handle_unlock_command,
2077                 .mode = COMMAND_EXEC,
2078                 .usage = "bank_id",
2079                 .help = "Unlock entire protected flash device.",
2080         },
2081         {
2082                 .name = "mass_erase",
2083                 .handler = stm32l4_handle_mass_erase_command,
2084                 .mode = COMMAND_EXEC,
2085                 .usage = "bank_id",
2086                 .help = "Erase entire flash device.",
2087         },
2088         {
2089                 .name = "option_read",
2090                 .handler = stm32l4_handle_option_read_command,
2091                 .mode = COMMAND_EXEC,
2092                 .usage = "bank_id reg_offset",
2093                 .help = "Read & Display device option bytes.",
2094         },
2095         {
2096                 .name = "option_write",
2097                 .handler = stm32l4_handle_option_write_command,
2098                 .mode = COMMAND_EXEC,
2099                 .usage = "bank_id reg_offset value mask",
2100                 .help = "Write device option bit fields with provided value.",
2101         },
2102         {
2103                 .name = "trustzone",
2104                 .handler = stm32l4_handle_trustzone_command,
2105                 .mode = COMMAND_EXEC,
2106                 .usage = "<bank_id> [enable|disable]",
2107                 .help = "Configure TrustZone security",
2108         },
2109         {
2110                 .name = "wrp_info",
2111                 .handler = stm32l4_handle_wrp_info_command,
2112                 .mode = COMMAND_EXEC,
2113                 .usage = "bank_id [bank1|bank2]",
2114                 .help = "list the protected areas using WRP",
2115         },
2116         {
2117                 .name = "option_load",
2118                 .handler = stm32l4_handle_option_load_command,
2119                 .mode = COMMAND_EXEC,
2120                 .usage = "bank_id",
2121                 .help = "Force re-load of device options (will cause device reset).",
2122         },
2123         {
2124                 .name = "otp",
2125                 .handler = stm32l4_handle_otp_command,
2126                 .mode = COMMAND_EXEC,
2127                 .usage = "<bank_id> <enable|disable|show>",
2128                 .help = "OTP (One Time Programmable) memory write enable/disable",
2129         },
2130         COMMAND_REGISTRATION_DONE
2131 };
2132
2133 static const struct command_registration stm32l4_command_handlers[] = {
2134         {
2135                 .name = "stm32l4x",
2136                 .mode = COMMAND_ANY,
2137                 .help = "stm32l4x flash command group",
2138                 .usage = "",
2139                 .chain = stm32l4_exec_command_handlers,
2140         },
2141         COMMAND_REGISTRATION_DONE
2142 };
2143
2144 const struct flash_driver stm32l4x_flash = {
2145         .name = "stm32l4x",
2146         .commands = stm32l4_command_handlers,
2147         .flash_bank_command = stm32l4_flash_bank_command,
2148         .erase = stm32l4_erase,
2149         .protect = stm32l4_protect,
2150         .write = stm32l4_write,
2151         .read = default_flash_read,
2152         .probe = stm32l4_probe,
2153         .auto_probe = stm32l4_auto_probe,
2154         .erase_check = default_flash_blank_check,
2155         .protect_check = stm32l4_protect_check,
2156         .info = get_stm32l4_info,
2157         .free_driver_priv = default_flash_free_driver_priv,
2158 };