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