89ba75dad8a34c2cd656cc9b430969c2cf9084e7
[fw/openocd] / src / flash / nor / stm32h7x.c
1 /***************************************************************************
2  *   Copyright (C) 2017 by STMicroelectronics                              *
3  *                                                                         *
4  *   This program is free software; you can redistribute it and/or modify  *
5  *   it under the terms of the GNU General Public License as published by  *
6  *   the Free Software Foundation; either version 2 of the License, or     *
7  *   (at your option) any later version.                                   *
8  *                                                                         *
9  *   This program is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU General Public License for more details.                          *
13  *                                                                         *
14  *   You should have received a copy of the GNU General Public License     *
15  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
16  ***************************************************************************/
17 #ifdef HAVE_CONFIG_H
18 #include "config.h"
19 #endif
20
21 #include "imp.h"
22 #include <helper/binarybuffer.h>
23 #include <target/algorithm.h>
24 #include <target/armv7m.h>
25
26
27 /* Erase time can be as high as 1000ms, 10x this and it's toast... */
28 #define FLASH_ERASE_TIMEOUT 10000
29 #define FLASH_WRITE_TIMEOUT 5
30
31 /* RM 433 */
32 /* Same Flash registers for both banks, */
33 /* access depends on Flash Base address */
34 #define FLASH_ACR       0x00
35 #define FLASH_KEYR      0x04
36 #define FLASH_OPTKEYR   0x08
37 #define FLASH_CR        0x0C
38 #define FLASH_SR        0x10
39 #define FLASH_CCR       0x14
40 #define FLASH_OPTCR     0x18
41 #define FLASH_OPTSR_CUR 0x1C
42 #define FLASH_OPTSR_PRG 0x20
43 #define FLASH_OPTCCR    0x24
44 #define FLASH_WPSN_CUR  0x38
45 #define FLASH_WPSN_PRG  0x3C
46
47
48 /* FLASH_CR register bits */
49 #define FLASH_LOCK     (1 << 0)
50 #define FLASH_PG       (1 << 1)
51 #define FLASH_SER      (1 << 2)
52 #define FLASH_BER      (1 << 3)
53 #define FLASH_PSIZE_8  (0 << 4)
54 #define FLASH_PSIZE_16 (1 << 4)
55 #define FLASH_PSIZE_32 (2 << 4)
56 #define FLASH_PSIZE_64 (3 << 4)
57 #define FLASH_FW       (1 << 6)
58 #define FLASH_START    (1 << 7)
59
60 /* FLASH_SR register bits */
61 #define FLASH_BSY      (1 << 0)  /* Operation in progress */
62 #define FLASH_QW       (1 << 2)  /* Operation queue in progress */
63 #define FLASH_WRPERR   (1 << 17) /* Write protection error */
64 #define FLASH_PGSERR   (1 << 18) /* Programming sequence error */
65 #define FLASH_STRBERR  (1 << 19) /* Strobe error */
66 #define FLASH_INCERR   (1 << 21) /* Inconsistency error */
67 #define FLASH_OPERR    (1 << 22) /* Operation error */
68 #define FLASH_RDPERR   (1 << 23) /* Read Protection error */
69 #define FLASH_RDSERR   (1 << 24) /* Secure Protection error */
70 #define FLASH_SNECCERR (1 << 25) /* Single ECC error */
71 #define FLASH_DBECCERR (1 << 26) /* Double ECC error */
72
73 #define FLASH_ERROR (FLASH_WRPERR | FLASH_PGSERR | FLASH_STRBERR | FLASH_INCERR | FLASH_OPERR | \
74                                          FLASH_RDPERR | FLASH_RDSERR | FLASH_SNECCERR | FLASH_DBECCERR)
75
76 /* FLASH_OPTCR register bits */
77 #define OPT_LOCK       (1 << 0)
78 #define OPT_START      (1 << 1)
79
80 /* FLASH_OPTSR register bits */
81 #define OPT_BSY        (1 << 0)
82 #define OPT_RDP_POS    8
83 #define OPT_RDP_MASK   (0xff << OPT_RDP_POS)
84 #define OPT_OPTCHANGEERR (1 << 30)
85
86 /* FLASH_OPTCCR register bits */
87 #define OPT_CLR_OPTCHANGEERR (1 << 30)
88
89 /* register unlock keys */
90 #define KEY1           0x45670123
91 #define KEY2           0xCDEF89AB
92
93 /* option register unlock key */
94 #define OPTKEY1        0x08192A3B
95 #define OPTKEY2        0x4C5D6E7F
96
97 #define DBGMCU_IDCODE_REGISTER  0x5C001000
98 #define FLASH_BANK0_ADDRESS     0x08000000
99 #define FLASH_BANK1_ADDRESS     0x08100000
100 #define FLASH_REG_BASE_B0       0x52002000
101 #define FLASH_REG_BASE_B1       0x52002100
102
103 struct stm32h7x_rev {
104         uint16_t rev;
105         const char *str;
106 };
107
108 /* stm32h7x_part_info permits the store each device information and specificities.
109  * the default unit is byte unless the suffix '_kb' is used. */
110
111 struct stm32h7x_part_info {
112         uint16_t id;
113         const char *device_str;
114         const struct stm32h7x_rev *revs;
115         size_t num_revs;
116         unsigned int page_size_kb;
117         unsigned int block_size;    /* flash write word size in bytes */
118         uint16_t max_flash_size_kb;
119         bool has_dual_bank;
120         uint16_t max_bank_size_kb;  /* Used when has_dual_bank is true */
121         uint32_t fsize_addr;        /* Location of FSIZE register */
122         uint32_t wps_group_size;    /* write protection group sectors' count */
123         uint32_t wps_mask;
124         /* function to compute flash_cr register values */
125         uint32_t (*compute_flash_cr)(uint32_t cmd, int snb);
126 };
127
128 struct stm32h7x_flash_bank {
129         bool probed;
130         uint32_t idcode;
131         uint32_t user_bank_size;
132         uint32_t flash_regs_base;    /* Address of flash reg controller */
133         const struct stm32h7x_part_info *part_info;
134 };
135
136 enum stm32h7x_opt_rdp {
137         OPT_RDP_L0 = 0xaa,
138         OPT_RDP_L1 = 0x00,
139         OPT_RDP_L2 = 0xcc
140 };
141
142 static const struct stm32h7x_rev stm32_450_revs[] = {
143         { 0x1000, "A" }, { 0x1001, "Z" }, { 0x1003, "Y" }, { 0x2001, "X"  }, { 0x2003, "V"  },
144 };
145
146 static const struct stm32h7x_rev stm32_480_revs[] = {
147         { 0x1000, "A"},
148 };
149
150 static const struct stm32h7x_rev stm32_483_revs[] = {
151         { 0x1000, "A" }, { 0x1001, "Z" },
152 };
153
154 static uint32_t stm32x_compute_flash_cr_450_483(uint32_t cmd, int snb)
155 {
156         return cmd | (snb << 8);
157 }
158
159 static uint32_t stm32x_compute_flash_cr_480(uint32_t cmd, int snb)
160 {
161         /* save FW and START bits, to be right shifted by 2 bits later */
162         const uint32_t tmp = cmd & (FLASH_FW | FLASH_START);
163
164         /* mask parallelism (ignored), FW and START bits */
165         cmd &= ~(FLASH_PSIZE_64 | FLASH_FW | FLASH_START);
166
167         return cmd | (tmp >> 2) | (snb << 6);
168 }
169
170 static const struct stm32h7x_part_info stm32h7x_parts[] = {
171         {
172         .id                                     = 0x450,
173         .revs                           = stm32_450_revs,
174         .num_revs                       = ARRAY_SIZE(stm32_450_revs),
175         .device_str                     = "STM32H74x/75x",
176         .page_size_kb           = 128,
177         .block_size                     = 32,
178         .max_flash_size_kb      = 2048,
179         .max_bank_size_kb       = 1024,
180         .has_dual_bank          = true,
181         .fsize_addr                     = 0x1FF1E880,
182         .wps_group_size         = 1,
183         .wps_mask                       = 0xFF,
184         .compute_flash_cr       = stm32x_compute_flash_cr_450_483,
185         },
186         {
187         .id                                     = 0x480,
188         .revs                           = stm32_480_revs,
189         .num_revs                       = ARRAY_SIZE(stm32_480_revs),
190         .device_str                     = "STM32H7Ax/7Bx",
191         .page_size_kb           = 8,
192         .block_size                     = 16,
193         .max_flash_size_kb      = 2048,
194         .max_bank_size_kb       = 1024,
195         .has_dual_bank          = true,
196         .fsize_addr                     = 0x08FFF80C,
197         .wps_group_size         = 4,
198         .wps_mask                       = 0xFFFFFFFF,
199         .compute_flash_cr       = stm32x_compute_flash_cr_480,
200         },
201         {
202         .id                                     = 0x483,
203         .revs                           = stm32_483_revs,
204         .num_revs                       = ARRAY_SIZE(stm32_483_revs),
205         .device_str                     = "STM32H72x/73x",
206         .page_size_kb           = 128,
207         .block_size                     = 32,
208         .max_flash_size_kb      = 1024,
209         .max_bank_size_kb       = 1024,
210         .has_dual_bank          = false,
211         .fsize_addr                     = 0x1FF1E880,
212         .wps_group_size         = 1,
213         .wps_mask                       = 0xFF,
214         .compute_flash_cr   = stm32x_compute_flash_cr_450_483,
215         },
216 };
217
218 /* flash bank stm32x <base> <size> 0 0 <target#> */
219
220 FLASH_BANK_COMMAND_HANDLER(stm32x_flash_bank_command)
221 {
222         struct stm32h7x_flash_bank *stm32x_info;
223
224         if (CMD_ARGC < 6)
225                 return ERROR_COMMAND_SYNTAX_ERROR;
226
227         stm32x_info = malloc(sizeof(struct stm32h7x_flash_bank));
228         bank->driver_priv = stm32x_info;
229
230         stm32x_info->probed = false;
231         stm32x_info->user_bank_size = bank->size;
232
233         return ERROR_OK;
234 }
235
236 static inline uint32_t stm32x_get_flash_reg(struct flash_bank *bank, uint32_t reg_offset)
237 {
238         struct stm32h7x_flash_bank *stm32x_info = bank->driver_priv;
239         return reg_offset + stm32x_info->flash_regs_base;
240 }
241
242 static inline int stm32x_read_flash_reg(struct flash_bank *bank, uint32_t reg_offset, uint32_t *value)
243 {
244         uint32_t reg_addr = stm32x_get_flash_reg(bank, reg_offset);
245         int retval = target_read_u32(bank->target, reg_addr, value);
246
247         if (retval != ERROR_OK)
248                 LOG_ERROR("error while reading from address 0x%" PRIx32, reg_addr);
249
250         return retval;
251 }
252
253 static inline int stm32x_write_flash_reg(struct flash_bank *bank, uint32_t reg_offset, uint32_t value)
254 {
255         uint32_t reg_addr = stm32x_get_flash_reg(bank, reg_offset);
256         int retval = target_write_u32(bank->target, reg_addr, value);
257
258         if (retval != ERROR_OK)
259                 LOG_ERROR("error while writing to address 0x%" PRIx32, reg_addr);
260
261         return retval;
262 }
263
264 static inline int stm32x_get_flash_status(struct flash_bank *bank, uint32_t *status)
265 {
266         return stm32x_read_flash_reg(bank, FLASH_SR, status);
267 }
268
269 static int stm32x_wait_flash_op_queue(struct flash_bank *bank, int timeout)
270 {
271         uint32_t status;
272         int retval;
273
274         /* wait for flash operations completion */
275         for (;;) {
276                 retval = stm32x_get_flash_status(bank, &status);
277                 if (retval != ERROR_OK)
278                         return retval;
279
280                 if ((status & FLASH_QW) == 0)
281                         break;
282
283                 if (timeout-- <= 0) {
284                         LOG_ERROR("wait_flash_op_queue, time out expired, status: 0x%" PRIx32, status);
285                         return ERROR_FAIL;
286                 }
287                 alive_sleep(1);
288         }
289
290         if (status & FLASH_WRPERR) {
291                 LOG_ERROR("wait_flash_op_queue, WRPERR detected");
292                 retval = ERROR_FAIL;
293         }
294
295         /* Clear error + EOP flags but report errors */
296         if (status & FLASH_ERROR) {
297                 if (retval == ERROR_OK)
298                         retval = ERROR_FAIL;
299                 /* If this operation fails, we ignore it and report the original retval */
300                 stm32x_write_flash_reg(bank, FLASH_CCR, status);
301         }
302         return retval;
303 }
304
305 static int stm32x_unlock_reg(struct flash_bank *bank)
306 {
307         uint32_t ctrl;
308
309         /* first check if not already unlocked
310          * otherwise writing on FLASH_KEYR will fail
311          */
312         int retval = stm32x_read_flash_reg(bank, FLASH_CR, &ctrl);
313         if (retval != ERROR_OK)
314                 return retval;
315
316         if ((ctrl & FLASH_LOCK) == 0)
317                 return ERROR_OK;
318
319         /* unlock flash registers for bank */
320         retval = stm32x_write_flash_reg(bank, FLASH_KEYR, KEY1);
321         if (retval != ERROR_OK)
322                 return retval;
323
324         retval = stm32x_write_flash_reg(bank, FLASH_KEYR, KEY2);
325         if (retval != ERROR_OK)
326                 return retval;
327
328         retval = stm32x_read_flash_reg(bank, FLASH_CR, &ctrl);
329         if (retval != ERROR_OK)
330                 return retval;
331
332         if (ctrl & FLASH_LOCK) {
333                 LOG_ERROR("flash not unlocked STM32_FLASH_CRx: 0x%" PRIx32, ctrl);
334                 return ERROR_TARGET_FAILURE;
335         }
336         return ERROR_OK;
337 }
338
339 static int stm32x_unlock_option_reg(struct flash_bank *bank)
340 {
341         uint32_t ctrl;
342
343         int retval = stm32x_read_flash_reg(bank, FLASH_OPTCR, &ctrl);
344         if (retval != ERROR_OK)
345                 return retval;
346
347         if ((ctrl & OPT_LOCK) == 0)
348                 return ERROR_OK;
349
350         /* unlock option registers */
351         retval = stm32x_write_flash_reg(bank, FLASH_OPTKEYR, OPTKEY1);
352         if (retval != ERROR_OK)
353                 return retval;
354
355         retval = stm32x_write_flash_reg(bank, FLASH_OPTKEYR, OPTKEY2);
356         if (retval != ERROR_OK)
357                 return retval;
358
359         retval = stm32x_read_flash_reg(bank, FLASH_OPTCR, &ctrl);
360         if (retval != ERROR_OK)
361                 return retval;
362
363         if (ctrl & OPT_LOCK) {
364                 LOG_ERROR("options not unlocked STM32_FLASH_OPTCR: 0x%" PRIx32, ctrl);
365                 return ERROR_TARGET_FAILURE;
366         }
367
368         return ERROR_OK;
369 }
370
371 static inline int stm32x_lock_reg(struct flash_bank *bank)
372 {
373         return stm32x_write_flash_reg(bank, FLASH_CR, FLASH_LOCK);
374 }
375
376 static inline int stm32x_lock_option_reg(struct flash_bank *bank)
377 {
378         return stm32x_write_flash_reg(bank, FLASH_OPTCR, OPT_LOCK);
379 }
380
381 static int stm32x_write_option(struct flash_bank *bank, uint32_t reg_offset, uint32_t value)
382 {
383         int retval, retval2;
384
385         /* unlock option bytes for modification */
386         retval = stm32x_unlock_option_reg(bank);
387         if (retval != ERROR_OK)
388                 goto flash_options_lock;
389
390         /* write option bytes */
391         retval = stm32x_write_flash_reg(bank, reg_offset, value);
392         if (retval != ERROR_OK)
393                 goto flash_options_lock;
394
395         /* Remove OPT error flag before programming */
396         retval = stm32x_write_flash_reg(bank, FLASH_OPTCCR, OPT_CLR_OPTCHANGEERR);
397         if (retval != ERROR_OK)
398                 goto flash_options_lock;
399
400         /* start programming cycle */
401         retval = stm32x_write_flash_reg(bank, FLASH_OPTCR, OPT_START);
402         if (retval != ERROR_OK)
403                 goto flash_options_lock;
404
405         /* wait for completion */
406         int timeout = FLASH_ERASE_TIMEOUT;
407         uint32_t status;
408         for (;;) {
409                 retval = stm32x_read_flash_reg(bank, FLASH_OPTSR_CUR, &status);
410                 if (retval != ERROR_OK) {
411                         LOG_ERROR("stm32x_options_program: failed to read FLASH_OPTSR_CUR");
412                         goto flash_options_lock;
413                 }
414                 if ((status & OPT_BSY) == 0)
415                         break;
416
417                 if (timeout-- <= 0) {
418                         LOG_ERROR("waiting for OBL launch, time out expired, OPTSR: 0x%" PRIx32, status);
419                         retval = ERROR_FAIL;
420                         goto flash_options_lock;
421                 }
422                 alive_sleep(1);
423         }
424
425         /* check for failure */
426         if (status & OPT_OPTCHANGEERR) {
427                 LOG_ERROR("error changing option bytes (OPTCHANGEERR=1)");
428                 retval = ERROR_FLASH_OPERATION_FAILED;
429         }
430
431 flash_options_lock:
432         retval2 = stm32x_lock_option_reg(bank);
433         if (retval2 != ERROR_OK)
434                 LOG_ERROR("error during the lock of flash options");
435
436         return (retval == ERROR_OK) ? retval2 : retval;
437 }
438
439 static int stm32x_modify_option(struct flash_bank *bank, uint32_t reg_offset, uint32_t value, uint32_t mask)
440 {
441         uint32_t data;
442
443         int retval = stm32x_read_flash_reg(bank, reg_offset, &data);
444         if (retval != ERROR_OK)
445                 return retval;
446
447         data = (data & ~mask) | (value & mask);
448
449         return stm32x_write_option(bank, reg_offset, data);
450 }
451
452 static int stm32x_protect_check(struct flash_bank *bank)
453 {
454         uint32_t protection;
455
456         /* read 'write protection' settings */
457         int retval = stm32x_read_flash_reg(bank, FLASH_WPSN_CUR, &protection);
458         if (retval != ERROR_OK) {
459                 LOG_DEBUG("unable to read WPSN_CUR register");
460                 return retval;
461         }
462
463         for (unsigned int i = 0; i < bank->num_prot_blocks; i++)
464                 bank->prot_blocks[i].is_protected = protection & (1 << i) ? 0 : 1;
465
466         return ERROR_OK;
467 }
468
469 static int stm32x_erase(struct flash_bank *bank, unsigned int first,
470                 unsigned int last)
471 {
472         struct stm32h7x_flash_bank *stm32x_info = bank->driver_priv;
473         int retval, retval2;
474
475         assert(first < bank->num_sectors);
476         assert(last < bank->num_sectors);
477
478         if (bank->target->state != TARGET_HALTED)
479                 return ERROR_TARGET_NOT_HALTED;
480
481         retval = stm32x_unlock_reg(bank);
482         if (retval != ERROR_OK)
483                 goto flash_lock;
484
485         /*
486         Sector Erase
487         To erase a sector, follow the procedure below:
488         1. Check that no Flash memory operation is ongoing by checking the QW bit in the
489           FLASH_SR register
490         2. Set the SER bit and select the sector
491           you wish to erase (SNB) in the FLASH_CR register
492         3. Set the STRT bit in the FLASH_CR register
493         4. Wait for flash operations completion
494          */
495         for (unsigned int i = first; i <= last; i++) {
496                 LOG_DEBUG("erase sector %u", i);
497                 retval = stm32x_write_flash_reg(bank, FLASH_CR,
498                                 stm32x_info->part_info->compute_flash_cr(FLASH_SER | FLASH_PSIZE_64, i));
499                 if (retval != ERROR_OK) {
500                         LOG_ERROR("Error erase sector %u", i);
501                         goto flash_lock;
502                 }
503                 retval = stm32x_write_flash_reg(bank, FLASH_CR,
504                                 stm32x_info->part_info->compute_flash_cr(FLASH_SER | FLASH_PSIZE_64 | FLASH_START, i));
505                 if (retval != ERROR_OK) {
506                         LOG_ERROR("Error erase sector %u", i);
507                         goto flash_lock;
508                 }
509                 retval = stm32x_wait_flash_op_queue(bank, FLASH_ERASE_TIMEOUT);
510
511                 if (retval != ERROR_OK) {
512                         LOG_ERROR("erase time-out or operation error sector %u", i);
513                         goto flash_lock;
514                 }
515         }
516
517 flash_lock:
518         retval2 = stm32x_lock_reg(bank);
519         if (retval2 != ERROR_OK)
520                 LOG_ERROR("error during the lock of flash");
521
522         return (retval == ERROR_OK) ? retval2 : retval;
523 }
524
525 static int stm32x_protect(struct flash_bank *bank, int set, unsigned int first,
526                 unsigned int last)
527 {
528         struct target *target = bank->target;
529         uint32_t protection;
530
531         if (target->state != TARGET_HALTED) {
532                 LOG_ERROR("Target not halted");
533                 return ERROR_TARGET_NOT_HALTED;
534         }
535
536         /* read 'write protection' settings */
537         int retval = stm32x_read_flash_reg(bank, FLASH_WPSN_CUR, &protection);
538         if (retval != ERROR_OK) {
539                 LOG_DEBUG("unable to read WPSN_CUR register");
540                 return retval;
541         }
542
543         for (unsigned int i = first; i <= last; i++) {
544                 if (set)
545                         protection &= ~(1 << i);
546                 else
547                         protection |= (1 << i);
548         }
549
550         /* apply WRPSN mask */
551         protection &= 0xff;
552
553         LOG_DEBUG("stm32x_protect, option_bytes written WPSN 0x%" PRIx32, protection);
554
555         /* apply new option value */
556         return stm32x_write_option(bank, FLASH_WPSN_PRG, protection);
557 }
558
559 static int stm32x_write_block(struct flash_bank *bank, const uint8_t *buffer,
560                 uint32_t offset, uint32_t count)
561 {
562         struct target *target = bank->target;
563         struct stm32h7x_flash_bank *stm32x_info = bank->driver_priv;
564         /*
565          * If the size of the data part of the buffer is not a multiple of .block_size, we get
566          * "corrupted fifo read" pointer in target_run_flash_async_algorithm()
567          */
568         uint32_t data_size = 512 * stm32x_info->part_info->block_size;
569         uint32_t buffer_size = 8 + data_size;
570         struct working_area *write_algorithm;
571         struct working_area *source;
572         uint32_t address = bank->base + offset;
573         struct reg_param reg_params[6];
574         struct armv7m_algorithm armv7m_info;
575         int retval = ERROR_OK;
576
577         static const uint8_t stm32x_flash_write_code[] = {
578 #include "../../../contrib/loaders/flash/stm32/stm32h7x.inc"
579         };
580
581         if (target_alloc_working_area(target, sizeof(stm32x_flash_write_code),
582                         &write_algorithm) != ERROR_OK) {
583                 LOG_WARNING("no working area available, can't do block memory writes");
584                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
585         }
586
587         retval = target_write_buffer(target, write_algorithm->address,
588                         sizeof(stm32x_flash_write_code),
589                         stm32x_flash_write_code);
590         if (retval != ERROR_OK) {
591                 target_free_working_area(target, write_algorithm);
592                 return retval;
593         }
594
595         /* memory buffer */
596         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) {
597                 data_size /= 2;
598                 buffer_size = 8 + data_size;
599                 if (data_size <= 256) {
600                         /* we already allocated the writing code, but failed to get a
601                          * buffer, free the algorithm */
602                         target_free_working_area(target, write_algorithm);
603
604                         LOG_WARNING("no large enough working area available, can't do block memory writes");
605                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
606                 }
607         }
608
609         LOG_DEBUG("target_alloc_working_area_try : buffer_size -> 0x%" PRIx32, buffer_size);
610
611         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
612         armv7m_info.core_mode = ARM_MODE_THREAD;
613
614         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT);         /* buffer start, status (out) */
615         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);            /* buffer end */
616         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);            /* target address */
617         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);            /* count of words (word size = .block_size (bytes) */
618         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);            /* word size in bytes */
619         init_reg_param(&reg_params[5], "r5", 32, PARAM_OUT);            /* flash reg base */
620
621         buf_set_u32(reg_params[0].value, 0, 32, source->address);
622         buf_set_u32(reg_params[1].value, 0, 32, source->address + source->size);
623         buf_set_u32(reg_params[2].value, 0, 32, address);
624         buf_set_u32(reg_params[3].value, 0, 32, count);
625         buf_set_u32(reg_params[4].value, 0, 32, stm32x_info->part_info->block_size);
626         buf_set_u32(reg_params[5].value, 0, 32, stm32x_info->flash_regs_base);
627
628         retval = target_run_flash_async_algorithm(target,
629                                                   buffer,
630                                                   count,
631                                                   stm32x_info->part_info->block_size,
632                                                   0, NULL,
633                                                   ARRAY_SIZE(reg_params), reg_params,
634                                                   source->address, source->size,
635                                                   write_algorithm->address, 0,
636                                                   &armv7m_info);
637
638         if (retval == ERROR_FLASH_OPERATION_FAILED) {
639                 LOG_ERROR("error executing stm32h7x flash write algorithm");
640
641                 uint32_t flash_sr = buf_get_u32(reg_params[0].value, 0, 32);
642
643                 if (flash_sr & FLASH_WRPERR)
644                         LOG_ERROR("flash memory write protected");
645
646                 if ((flash_sr & FLASH_ERROR) != 0) {
647                         LOG_ERROR("flash write failed, FLASH_SR = 0x%08" PRIx32, flash_sr);
648                         /* Clear error + EOP flags but report errors */
649                         stm32x_write_flash_reg(bank, FLASH_CCR, flash_sr);
650                         retval = ERROR_FAIL;
651                 }
652         }
653
654         target_free_working_area(target, source);
655         target_free_working_area(target, write_algorithm);
656
657         destroy_reg_param(&reg_params[0]);
658         destroy_reg_param(&reg_params[1]);
659         destroy_reg_param(&reg_params[2]);
660         destroy_reg_param(&reg_params[3]);
661         destroy_reg_param(&reg_params[4]);
662         destroy_reg_param(&reg_params[5]);
663         return retval;
664 }
665
666 static int stm32x_write(struct flash_bank *bank, const uint8_t *buffer,
667                 uint32_t offset, uint32_t count)
668 {
669         struct target *target = bank->target;
670         struct stm32h7x_flash_bank *stm32x_info = bank->driver_priv;
671         uint32_t address = bank->base + offset;
672         int retval, retval2;
673
674         if (bank->target->state != TARGET_HALTED) {
675                 LOG_ERROR("Target not halted");
676                 return ERROR_TARGET_NOT_HALTED;
677         }
678
679         /* should be enforced via bank->write_start_alignment */
680         assert(!(offset % stm32x_info->part_info->block_size));
681
682         /* should be enforced via bank->write_end_alignment */
683         assert(!(count % stm32x_info->part_info->block_size));
684
685         retval = stm32x_unlock_reg(bank);
686         if (retval != ERROR_OK)
687                 goto flash_lock;
688
689         uint32_t blocks_remaining = count / stm32x_info->part_info->block_size;
690
691         /* multiple words (n * .block_size) to be programmed in block */
692         if (blocks_remaining) {
693                 retval = stm32x_write_block(bank, buffer, offset, blocks_remaining);
694                 if (retval != ERROR_OK) {
695                         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
696                                 /* if block write failed (no sufficient working area),
697                                  * we use normal (slow) dword accesses */
698                                 LOG_WARNING("couldn't use block writes, falling back to single memory accesses");
699                         }
700                 } else {
701                         buffer += blocks_remaining * stm32x_info->part_info->block_size;
702                         address += blocks_remaining * stm32x_info->part_info->block_size;
703                         blocks_remaining = 0;
704                 }
705                 if ((retval != ERROR_OK) && (retval != ERROR_TARGET_RESOURCE_NOT_AVAILABLE))
706                         goto flash_lock;
707         }
708
709         /*
710         Standard programming
711         The Flash memory programming sequence is as follows:
712         1. Check that no main Flash memory operation is ongoing by checking the QW bit in the
713            FLASH_SR register.
714         2. Set the PG bit in the FLASH_CR register
715         3. 8 x Word access (or Force Write FW)
716         4. Wait for flash operations completion
717         */
718         while (blocks_remaining > 0) {
719                 retval = stm32x_write_flash_reg(bank, FLASH_CR,
720                                 stm32x_info->part_info->compute_flash_cr(FLASH_PG | FLASH_PSIZE_64, 0));
721                 if (retval != ERROR_OK)
722                         goto flash_lock;
723
724                 retval = target_write_buffer(target, address, stm32x_info->part_info->block_size, buffer);
725                 if (retval != ERROR_OK)
726                         goto flash_lock;
727
728                 retval = stm32x_wait_flash_op_queue(bank, FLASH_WRITE_TIMEOUT);
729                 if (retval != ERROR_OK)
730                         goto flash_lock;
731
732                 buffer += stm32x_info->part_info->block_size;
733                 address += stm32x_info->part_info->block_size;
734                 blocks_remaining--;
735         }
736
737 flash_lock:
738         retval2 = stm32x_lock_reg(bank);
739         if (retval2 != ERROR_OK)
740                 LOG_ERROR("error during the lock of flash");
741
742         return (retval == ERROR_OK) ? retval2 : retval;
743 }
744
745 static int stm32x_read_id_code(struct flash_bank *bank, uint32_t *id)
746 {
747         /* read stm32 device id register */
748         int retval = target_read_u32(bank->target, DBGMCU_IDCODE_REGISTER, id);
749         if (retval != ERROR_OK)
750                 return retval;
751         return ERROR_OK;
752 }
753
754 static int stm32x_probe(struct flash_bank *bank)
755 {
756         struct target *target = bank->target;
757         struct stm32h7x_flash_bank *stm32x_info = bank->driver_priv;
758         uint16_t flash_size_in_kb;
759         uint32_t device_id;
760
761         stm32x_info->probed = false;
762         stm32x_info->part_info = NULL;
763
764         int retval = stm32x_read_id_code(bank, &stm32x_info->idcode);
765         if (retval != ERROR_OK)
766                 return retval;
767
768         LOG_DEBUG("device id = 0x%08" PRIx32, stm32x_info->idcode);
769
770         device_id = stm32x_info->idcode & 0xfff;
771
772         for (unsigned int n = 0; n < ARRAY_SIZE(stm32h7x_parts); n++) {
773                 if (device_id == stm32h7x_parts[n].id)
774                         stm32x_info->part_info = &stm32h7x_parts[n];
775         }
776         if (!stm32x_info->part_info) {
777                 LOG_WARNING("Cannot identify target as a STM32H7xx family.");
778                 return ERROR_FAIL;
779         } else {
780                 LOG_INFO("Device: %s", stm32x_info->part_info->device_str);
781         }
782
783         /* update the address of controller */
784         if (bank->base == FLASH_BANK0_ADDRESS)
785                 stm32x_info->flash_regs_base = FLASH_REG_BASE_B0;
786         else if (bank->base == FLASH_BANK1_ADDRESS)
787                 stm32x_info->flash_regs_base = FLASH_REG_BASE_B1;
788         else {
789                 LOG_WARNING("Flash register base not defined for bank %u", bank->bank_number);
790                 return ERROR_FAIL;
791         }
792         LOG_DEBUG("flash_regs_base: 0x%" PRIx32, stm32x_info->flash_regs_base);
793
794         /* get flash size from target */
795         retval = target_read_u16(target, stm32x_info->part_info->fsize_addr, &flash_size_in_kb);
796         if (retval != ERROR_OK) {
797                 /* read error when device has invalid value, set max flash size */
798                 flash_size_in_kb = stm32x_info->part_info->max_flash_size_kb;
799         } else
800                 LOG_INFO("flash size probed value %" PRIu16, flash_size_in_kb);
801
802
803
804
805         /* setup bank size */
806         const uint32_t bank1_base = FLASH_BANK0_ADDRESS;
807         const uint32_t bank2_base = bank1_base + stm32x_info->part_info->max_bank_size_kb * 1024;
808         bool has_dual_bank = stm32x_info->part_info->has_dual_bank;
809
810         switch (device_id) {
811         case 0x450:
812         case 0x480:
813                 /* For STM32H74x/75x and STM32H7Ax/Bx
814                  *  - STM32H7xxxI devices contains dual bank, 1 Mbyte each
815                  *  - STM32H7xxxG devices contains dual bank, 512 Kbyte each
816                  *  - STM32H7xxxB devices contains single bank, 128 Kbyte
817                  *  - the second bank starts always from 0x08100000
818                  */
819                 if (flash_size_in_kb == 128)
820                         has_dual_bank = false;
821                 else
822                         /* flash size is 2M or 1M */
823                         flash_size_in_kb /= 2;
824                 break;
825         case 0x483:
826                 break;
827         default:
828                 LOG_ERROR("unsupported device");
829                 return ERROR_FAIL;
830         }
831
832         if (has_dual_bank) {
833                 LOG_INFO("STM32H7 flash has dual banks");
834                 if (bank->base != bank1_base && bank->base != bank2_base) {
835                         LOG_ERROR("STM32H7 flash bank base address config is incorrect. "
836                                         TARGET_ADDR_FMT " but should rather be 0x%" PRIx32 " or 0x%" PRIx32,
837                                         bank->base, bank1_base, bank2_base);
838                         return ERROR_FAIL;
839                 }
840         } else {
841                 LOG_INFO("STM32H7 flash has a single bank");
842                 if (bank->base == bank2_base) {
843                         LOG_ERROR("this device has a single bank only");
844                         return ERROR_FAIL;
845                 } else if (bank->base != bank1_base) {
846                         LOG_ERROR("STM32H7 flash bank base address config is incorrect. "
847                                         TARGET_ADDR_FMT " but should be 0x%" PRIx32,
848                                         bank->base, bank1_base);
849                         return ERROR_FAIL;
850                 }
851         }
852
853         LOG_INFO("Bank (%u) size is %" PRIu16 " kb, base address is " TARGET_ADDR_FMT,
854                 bank->bank_number, flash_size_in_kb, bank->base);
855
856         /* if the user sets the size manually then ignore the probed value
857          * this allows us to work around devices that have an invalid flash size register value */
858         if (stm32x_info->user_bank_size) {
859                 LOG_INFO("ignoring flash probed value, using configured bank size");
860                 flash_size_in_kb = stm32x_info->user_bank_size / 1024;
861         } else if (flash_size_in_kb == 0xffff) {
862                 /* die flash size */
863                 flash_size_in_kb = stm32x_info->part_info->max_flash_size_kb;
864         }
865
866         /* did we assign flash size? */
867         assert(flash_size_in_kb != 0xffff);
868         bank->size = flash_size_in_kb * 1024;
869         bank->write_start_alignment = stm32x_info->part_info->block_size;
870         bank->write_end_alignment = stm32x_info->part_info->block_size;
871
872         /* setup sectors */
873         bank->num_sectors = flash_size_in_kb / stm32x_info->part_info->page_size_kb;
874         assert(bank->num_sectors > 0);
875
876         free(bank->sectors);
877
878         bank->sectors = alloc_block_array(0, stm32x_info->part_info->page_size_kb * 1024,
879                         bank->num_sectors);
880
881         if (!bank->sectors) {
882                 LOG_ERROR("failed to allocate bank sectors");
883                 return ERROR_FAIL;
884         }
885
886         /* setup protection blocks */
887         const uint32_t wpsn = stm32x_info->part_info->wps_group_size;
888         assert(bank->num_sectors % wpsn == 0);
889
890         bank->num_prot_blocks = bank->num_sectors / wpsn;
891         assert(bank->num_prot_blocks > 0);
892
893         free(bank->prot_blocks);
894
895         bank->prot_blocks = alloc_block_array(0, stm32x_info->part_info->page_size_kb * wpsn * 1024,
896                         bank->num_prot_blocks);
897
898         if (!bank->prot_blocks) {
899                 LOG_ERROR("failed to allocate bank prot_block");
900                 return ERROR_FAIL;
901         }
902
903         stm32x_info->probed = true;
904         return ERROR_OK;
905 }
906
907 static int stm32x_auto_probe(struct flash_bank *bank)
908 {
909         struct stm32h7x_flash_bank *stm32x_info = bank->driver_priv;
910
911         if (stm32x_info->probed)
912                 return ERROR_OK;
913
914         return stm32x_probe(bank);
915 }
916
917 /* This method must return a string displaying information about the bank */
918 static int stm32x_get_info(struct flash_bank *bank, struct command_invocation *cmd)
919 {
920         struct stm32h7x_flash_bank *stm32x_info = bank->driver_priv;
921         const struct stm32h7x_part_info *info = stm32x_info->part_info;
922
923         if (!stm32x_info->probed) {
924                 int retval = stm32x_probe(bank);
925                 if (retval != ERROR_OK) {
926                         command_print_sameline(cmd, "Unable to find bank information.");
927                         return retval;
928                 }
929         }
930
931         if (info) {
932                 const char *rev_str = NULL;
933                 uint16_t rev_id = stm32x_info->idcode >> 16;
934
935                 for (unsigned int i = 0; i < info->num_revs; i++)
936                         if (rev_id == info->revs[i].rev)
937                                 rev_str = info->revs[i].str;
938
939                 if (rev_str) {
940                         command_print_sameline(cmd, "%s - Rev: %s",
941                                 stm32x_info->part_info->device_str, rev_str);
942                 } else {
943                         command_print_sameline(cmd,
944                                  "%s - Rev: unknown (0x%04" PRIx16 ")",
945                                 stm32x_info->part_info->device_str, rev_id);
946                 }
947         } else {
948                 command_print_sameline(cmd, "Cannot identify target as a STM32H7x");
949                 return ERROR_FAIL;
950         }
951         return ERROR_OK;
952 }
953
954 static int stm32x_set_rdp(struct flash_bank *bank, enum stm32h7x_opt_rdp new_rdp)
955 {
956         struct target *target = bank->target;
957         uint32_t optsr, cur_rdp;
958         int retval;
959
960         if (target->state != TARGET_HALTED) {
961                 LOG_ERROR("Target not halted");
962                 return ERROR_TARGET_NOT_HALTED;
963         }
964
965         retval = stm32x_read_flash_reg(bank, FLASH_OPTSR_PRG, &optsr);
966
967         if (retval != ERROR_OK) {
968                 LOG_DEBUG("unable to read FLASH_OPTSR_PRG register");
969                 return retval;
970         }
971
972         /* get current RDP, and check if there is a change */
973         cur_rdp = (optsr & OPT_RDP_MASK) >> OPT_RDP_POS;
974         if (new_rdp == cur_rdp) {
975                 LOG_INFO("the requested RDP value is already programmed");
976                 return ERROR_OK;
977         }
978
979         switch (new_rdp) {
980         case OPT_RDP_L0:
981                 LOG_WARNING("unlocking the entire flash device");
982                 break;
983         case OPT_RDP_L1:
984                 LOG_WARNING("locking the entire flash device");
985                 break;
986         case OPT_RDP_L2:
987                 LOG_WARNING("locking the entire flash device, irreversible");
988                 break;
989         }
990
991         /* apply new RDP */
992         optsr = (optsr & ~OPT_RDP_MASK) | (new_rdp << OPT_RDP_POS);
993
994         /* apply new option value */
995         return stm32x_write_option(bank, FLASH_OPTSR_PRG, optsr);
996 }
997
998 COMMAND_HANDLER(stm32x_handle_lock_command)
999 {
1000         if (CMD_ARGC < 1)
1001                 return ERROR_COMMAND_SYNTAX_ERROR;
1002
1003         struct flash_bank *bank;
1004         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1005         if (retval != ERROR_OK)
1006                 return retval;
1007
1008         retval = stm32x_set_rdp(bank, OPT_RDP_L1);
1009
1010         if (retval != ERROR_OK)
1011                 command_print(CMD, "%s failed to lock device", bank->driver->name);
1012         else
1013                 command_print(CMD, "%s locked", bank->driver->name);
1014
1015         return retval;
1016 }
1017
1018 COMMAND_HANDLER(stm32x_handle_unlock_command)
1019 {
1020         if (CMD_ARGC < 1)
1021                 return ERROR_COMMAND_SYNTAX_ERROR;
1022
1023         struct flash_bank *bank;
1024         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1025         if (retval != ERROR_OK)
1026                 return retval;
1027
1028         retval = stm32x_set_rdp(bank, OPT_RDP_L0);
1029
1030         if (retval != ERROR_OK)
1031                 command_print(CMD, "%s failed to unlock device", bank->driver->name);
1032         else
1033                 command_print(CMD, "%s unlocked", bank->driver->name);
1034
1035         return retval;
1036 }
1037
1038 static int stm32x_mass_erase(struct flash_bank *bank)
1039 {
1040         int retval, retval2;
1041         struct target *target = bank->target;
1042         struct stm32h7x_flash_bank *stm32x_info = bank->driver_priv;
1043
1044         if (target->state != TARGET_HALTED) {
1045                 LOG_ERROR("Target not halted");
1046                 return ERROR_TARGET_NOT_HALTED;
1047         }
1048
1049         retval = stm32x_unlock_reg(bank);
1050         if (retval != ERROR_OK)
1051                 goto flash_lock;
1052
1053         /* mass erase flash memory bank */
1054         retval = stm32x_write_flash_reg(bank, FLASH_CR,
1055                         stm32x_info->part_info->compute_flash_cr(FLASH_BER | FLASH_PSIZE_64, 0));
1056         if (retval != ERROR_OK)
1057                 goto flash_lock;
1058
1059         retval = stm32x_write_flash_reg(bank, FLASH_CR,
1060                         stm32x_info->part_info->compute_flash_cr(FLASH_BER | FLASH_PSIZE_64 | FLASH_START, 0));
1061         if (retval != ERROR_OK)
1062                 goto flash_lock;
1063
1064         retval = stm32x_wait_flash_op_queue(bank, 30000);
1065         if (retval != ERROR_OK)
1066                 goto flash_lock;
1067
1068 flash_lock:
1069         retval2 = stm32x_lock_reg(bank);
1070         if (retval2 != ERROR_OK)
1071                 LOG_ERROR("error during the lock of flash");
1072
1073         return (retval == ERROR_OK) ? retval2 : retval;
1074 }
1075
1076 COMMAND_HANDLER(stm32x_handle_mass_erase_command)
1077 {
1078         if (CMD_ARGC < 1) {
1079                 command_print(CMD, "stm32h7x mass_erase <bank>");
1080                 return ERROR_COMMAND_SYNTAX_ERROR;
1081         }
1082
1083         struct flash_bank *bank;
1084         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1085         if (retval != ERROR_OK)
1086                 return retval;
1087
1088         retval = stm32x_mass_erase(bank);
1089         if (retval == ERROR_OK)
1090                 command_print(CMD, "stm32h7x mass erase complete");
1091         else
1092                 command_print(CMD, "stm32h7x mass erase failed");
1093
1094         return retval;
1095 }
1096
1097 COMMAND_HANDLER(stm32x_handle_option_read_command)
1098 {
1099         if (CMD_ARGC < 2) {
1100                 command_print(CMD, "stm32h7x option_read <bank> <option_reg offset>");
1101                 return ERROR_COMMAND_SYNTAX_ERROR;
1102         }
1103
1104         struct flash_bank *bank;
1105         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1106         if (retval != ERROR_OK)
1107                 return retval;
1108
1109         uint32_t reg_offset, value;
1110
1111         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], reg_offset);
1112         retval = stm32x_read_flash_reg(bank, reg_offset, &value);
1113         if (retval != ERROR_OK)
1114                 return retval;
1115
1116         command_print(CMD, "Option Register: <0x%" PRIx32 "> = 0x%" PRIx32,
1117                         stm32x_get_flash_reg(bank, reg_offset), value);
1118
1119         return retval;
1120 }
1121
1122 COMMAND_HANDLER(stm32x_handle_option_write_command)
1123 {
1124         if (CMD_ARGC < 3) {
1125                 command_print(CMD, "stm32h7x option_write <bank> <option_reg offset> <value> [mask]");
1126                 return ERROR_COMMAND_SYNTAX_ERROR;
1127         }
1128
1129         struct flash_bank *bank;
1130         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1131         if (retval != ERROR_OK)
1132                 return retval;
1133
1134         uint32_t reg_offset, value, mask = 0xffffffff;
1135
1136         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], reg_offset);
1137         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], value);
1138         if (CMD_ARGC > 3)
1139                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], mask);
1140
1141         return stm32x_modify_option(bank, reg_offset, value, mask);
1142 }
1143
1144 static const struct command_registration stm32x_exec_command_handlers[] = {
1145         {
1146                 .name = "lock",
1147                 .handler = stm32x_handle_lock_command,
1148                 .mode = COMMAND_EXEC,
1149                 .usage = "bank_id",
1150                 .help = "Lock entire flash device.",
1151         },
1152         {
1153                 .name = "unlock",
1154                 .handler = stm32x_handle_unlock_command,
1155                 .mode = COMMAND_EXEC,
1156                 .usage = "bank_id",
1157                 .help = "Unlock entire protected flash device.",
1158         },
1159         {
1160                 .name = "mass_erase",
1161                 .handler = stm32x_handle_mass_erase_command,
1162                 .mode = COMMAND_EXEC,
1163                 .usage = "bank_id",
1164                 .help = "Erase entire flash device.",
1165         },
1166         {
1167                 .name = "option_read",
1168                 .handler = stm32x_handle_option_read_command,
1169                 .mode = COMMAND_EXEC,
1170                 .usage = "bank_id reg_offset",
1171                 .help = "Read and display device option bytes.",
1172         },
1173         {
1174                 .name = "option_write",
1175                 .handler = stm32x_handle_option_write_command,
1176                 .mode = COMMAND_EXEC,
1177                 .usage = "bank_id reg_offset value [mask]",
1178                 .help = "Write device option bit fields with provided value.",
1179         },
1180         COMMAND_REGISTRATION_DONE
1181 };
1182
1183 static const struct command_registration stm32x_command_handlers[] = {
1184         {
1185                 .name = "stm32h7x",
1186                 .mode = COMMAND_ANY,
1187                 .help = "stm32h7x flash command group",
1188                 .usage = "",
1189                 .chain = stm32x_exec_command_handlers,
1190         },
1191         COMMAND_REGISTRATION_DONE
1192 };
1193
1194 const struct flash_driver stm32h7x_flash = {
1195         .name = "stm32h7x",
1196         .commands = stm32x_command_handlers,
1197         .flash_bank_command = stm32x_flash_bank_command,
1198         .erase = stm32x_erase,
1199         .protect = stm32x_protect,
1200         .write = stm32x_write,
1201         .read = default_flash_read,
1202         .probe = stm32x_probe,
1203         .auto_probe = stm32x_auto_probe,
1204         .erase_check = default_flash_blank_check,
1205         .protect_check = stm32x_protect_check,
1206         .info = stm32x_get_info,
1207         .free_driver_priv = default_flash_free_driver_priv,
1208 };