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