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