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