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