flash/nor/at91samd: add SAM R30 family
[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) /* Increment 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 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, FLASH_REG_BASE_B0 + 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, FLASH_REG_BASE_B0 + FLASH_OPTKEYR, OPTKEY1);
278         if (retval != ERROR_OK)
279                 return retval;
280
281         retval = target_write_u32(target, FLASH_REG_BASE_B0 + FLASH_OPTKEYR, OPTKEY2);
282         if (retval != ERROR_OK)
283                 return retval;
284
285         retval = target_read_u32(target, FLASH_REG_BASE_B0 + 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 = NULL;
313         struct target *target = bank->target;
314
315         stm32x_info = bank->driver_priv;
316
317         /* read current option bytes */
318         int retval = target_read_u32(target, FLASH_REG_BASE_B0 + FLASH_OPTCUR, &optiondata);
319         if (retval != ERROR_OK)
320                 return retval;
321
322         /* decode option data */
323         stm32x_info->option_bytes.user_options = optiondata & 0xfc;
324         stm32x_info->option_bytes.RDP = (optiondata >> 8) & 0xff;
325         stm32x_info->option_bytes.user2_options = (optiondata >> 16) & 0xff;
326         stm32x_info->option_bytes.user3_options = (optiondata >> 24) & 0x83;
327
328         if (optiondata & IWDG1_HW)
329                 stm32x_info->option_bytes.independent_watchdog_selection = 1;
330         else
331                 stm32x_info->option_bytes.independent_watchdog_selection = 0;
332
333         if (stm32x_info->option_bytes.RDP != 0xAA)
334                 LOG_INFO("Device Security Bit Set");
335
336         /* read current WPSN option bytes */
337         retval = target_read_u32(target, FLASH_REG_BASE_B0 + FLASH_WPSNCUR, &optiondata);
338         if (retval != ERROR_OK)
339                 return retval;
340         stm32x_info->option_bytes.protection = optiondata & 0xff;
341
342         /* read current WPSN2 option bytes */
343         retval = target_read_u32(target, FLASH_REG_BASE_B1 + FLASH_WPSNCUR, &optiondata);
344         if (retval != ERROR_OK)
345                 return retval;
346         stm32x_info->option_bytes.protection2 = optiondata & 0xff;
347
348         return ERROR_OK;
349 }
350
351 static int stm32x_write_options(struct flash_bank *bank)
352 {
353         struct stm32h7x_flash_bank *stm32x_info = NULL;
354         struct target *target = bank->target;
355         uint32_t optiondata;
356
357         stm32x_info = bank->driver_priv;
358
359         int retval = stm32x_unlock_option_reg(bank);
360         if (retval != ERROR_OK)
361                 return retval;
362
363         /* rebuild option data */
364         optiondata = stm32x_info->option_bytes.user_options;
365         optiondata |= (stm32x_info->option_bytes.RDP << 8);
366         optiondata |= (stm32x_info->option_bytes.user2_options & 0xff) << 16;
367         optiondata |= (stm32x_info->option_bytes.user3_options & 0x83) << 24;
368
369         if (stm32x_info->option_bytes.independent_watchdog_selection)
370                 optiondata |= IWDG1_HW;
371         else
372                 optiondata &= ~IWDG1_HW;
373
374         /* program options */
375         retval = target_write_u32(target, FLASH_REG_BASE_B0 + FLASH_OPTPRG, optiondata);
376                 if (retval != ERROR_OK)
377                         return retval;
378
379         optiondata = stm32x_info->option_bytes.protection & 0xff;
380         /* Program protection WPSNPRG */
381         retval = target_write_u32(target, FLASH_REG_BASE_B0 + FLASH_WPSNPRG, optiondata);
382                 if (retval != ERROR_OK)
383                         return retval;
384
385         optiondata = stm32x_info->option_bytes.protection2 & 0xff;
386         /* Program protection WPSNPRG2 */
387         retval = target_write_u32(target, FLASH_REG_BASE_B1 + FLASH_WPSNPRG, optiondata);
388                 if (retval != ERROR_OK)
389                         return retval;
390
391         optiondata = 0x40000000;
392         /* Remove OPT error flag before programming */
393         retval = target_write_u32(target, FLASH_REG_BASE_B0 + FLASH_OPTCCR, optiondata);
394                 if (retval != ERROR_OK)
395                         return retval;
396
397         /* start programming cycle */
398         retval = target_write_u32(target, FLASH_REG_BASE_B0 + FLASH_OPTCR, OPT_START);
399         if (retval != ERROR_OK)
400                 return retval;
401
402         /* wait for completion */
403         int timeout = FLASH_ERASE_TIMEOUT;
404         for (;;) {
405                 uint32_t status;
406                 retval = target_read_u32(target, FLASH_REG_BASE_B0 + FLASH_SR, &status);
407                 if (retval != ERROR_OK) {
408                         LOG_INFO("stm32x_write_options: wait_status_busy : error");
409                         return retval;
410                 }
411                 if ((status & FLASH_BSY) == 0)
412                         break;
413
414                 if (timeout-- <= 0) {
415                         LOG_INFO("wait_status_busy, time out expired, status: 0x%" PRIx32 "", status);
416                         return ERROR_FAIL;
417                 }
418                 alive_sleep(1);
419         }
420
421         /* relock option registers */
422         retval = target_write_u32(target, FLASH_REG_BASE_B0 + FLASH_OPTCR, OPT_LOCK);
423         if (retval != ERROR_OK)
424                 return retval;
425
426         return ERROR_OK;
427 }
428
429 static int stm32x_protect_check(struct flash_bank *bank)
430 {
431         struct stm32h7x_flash_bank *stm32x_info = bank->driver_priv;
432
433         /* read 'write protection' settings */
434         int retval = stm32x_read_options(bank);
435         if (retval != ERROR_OK) {
436                 LOG_DEBUG("unable to read option bytes");
437                 return retval;
438         }
439
440         for (int i = 0; i < bank->num_sectors; i++) {
441                 if (stm32x_info->flash_base == FLASH_REG_BASE_B0) {
442                         if (stm32x_info->option_bytes.protection & (1 << i))
443                                 bank->sectors[i].is_protected = 0;
444                         else
445                                 bank->sectors[i].is_protected = 1;
446                 } else {
447                         if (stm32x_info->option_bytes.protection2 & (1 << i))
448                                 bank->sectors[i].is_protected = 0;
449                         else
450                                 bank->sectors[i].is_protected = 1;
451                 }
452         }
453         return ERROR_OK;
454 }
455
456 static int stm32x_erase(struct flash_bank *bank, int first, int last)
457 {
458         struct target *target = bank->target;
459         int retval;
460
461         assert(first < bank->num_sectors);
462         assert(last < bank->num_sectors);
463
464         if (bank->target->state != TARGET_HALTED)
465                 return ERROR_TARGET_NOT_HALTED;
466
467         retval = stm32x_unlock_reg(bank);
468         if (retval != ERROR_OK)
469                 return retval;
470
471         /*
472         Sector Erase
473         To erase a sector, follow the procedure below:
474         1. Check that no Flash memory operation is ongoing by checking the BSY bit in the
475           FLASH_SR register
476         2. Set the SER bit and select the sector
477           you wish to erase (SNB) in the FLASH_CR register
478         3. Set the STRT bit in the FLASH_CR register
479         4. Wait for the BSY bit to be cleared
480          */
481         for (int i = first; i <= last; i++) {
482                 LOG_DEBUG("erase sector %d", i);
483                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, FLASH_CR),
484                                 FLASH_SER | FLASH_SNB(i) | FLASH_PSIZE_64);
485                 if (retval != ERROR_OK) {
486                         LOG_ERROR("Error erase sector %d", i);
487                         return retval;
488                 }
489                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, FLASH_CR),
490                                 FLASH_SER | FLASH_SNB(i) | FLASH_PSIZE_64 | FLASH_START);
491                 if (retval != ERROR_OK) {
492                         LOG_ERROR("Error erase sector %d", i);
493                         return retval;
494                 }
495                 retval = stm32x_wait_status_busy(bank, FLASH_ERASE_TIMEOUT);
496
497                 if (retval != ERROR_OK) {
498                         LOG_ERROR("erase time-out error sector %d", i);
499                         return retval;
500                 }
501                 bank->sectors[i].is_erased = 1;
502         }
503
504         retval = stm32x_lock_reg(bank);
505         if (retval != ERROR_OK) {
506                 LOG_ERROR("error during the lock of flash");
507                 return retval;
508         }
509
510         return ERROR_OK;
511 }
512
513 static int stm32x_protect(struct flash_bank *bank, int set, int first, int last)
514 {
515         struct target *target = bank->target;
516         struct stm32h7x_flash_bank *stm32x_info = bank->driver_priv;
517
518         if (target->state != TARGET_HALTED) {
519                 LOG_ERROR("Target not halted");
520                 return ERROR_TARGET_NOT_HALTED;
521         }
522         /* read protection settings */
523         int retval = stm32x_read_options(bank);
524         if (retval != ERROR_OK) {
525                 LOG_DEBUG("unable to read option bytes");
526                 return retval;
527         }
528
529         for (int i = first; i <= last; i++) {
530                 if (stm32x_info->flash_base == FLASH_REG_BASE_B0) {
531                         if (set)
532                                 stm32x_info->option_bytes.protection &= ~(1 << i);
533                         else
534                                 stm32x_info->option_bytes.protection |= (1 << i);
535                 } else {
536                         if (set)
537                                 stm32x_info->option_bytes.protection2 &= ~(1 << i);
538                         else
539                                 stm32x_info->option_bytes.protection2 |= (1 << i);
540                 }
541         }
542
543         LOG_INFO("stm32x_protect, option_bytes written WRP1 0x%x , WRP2 0x%x",
544           (stm32x_info->option_bytes.protection & 0xff), (stm32x_info->option_bytes.protection2 & 0xff));
545
546         retval = stm32x_write_options(bank);
547         if (retval != ERROR_OK)
548                 return retval;
549
550         return ERROR_OK;
551 }
552
553 static int stm32x_write_block(struct flash_bank *bank, const uint8_t *buffer,
554                 uint32_t offset, uint32_t count)
555 {
556         struct target *target = bank->target;
557         /*
558          * If the size of the data part of the buffer is not a multiple of FLASH_BLOCK_SIZE, we get
559          * "corrupted fifo read" pointer in target_run_flash_async_algorithm()
560          */
561         uint32_t data_size = 512 * FLASH_BLOCK_SIZE;    /* 16384 */
562         uint32_t buffer_size = 8 + data_size;
563         struct working_area *write_algorithm;
564         struct working_area *source;
565         uint32_t address = bank->base + offset;
566         struct reg_param reg_params[5];
567         struct armv7m_algorithm armv7m_info;
568         struct stm32h7x_flash_bank *stm32x_info = bank->driver_priv;
569         int retval = ERROR_OK;
570
571         /* see contrib/loaders/flash/smt32h7x.S for src */
572         static const uint8_t stm32x_flash_write_code[] = {
573                                                                 /* <code>: */
574                 0x45, 0x68,                             /*              ldr             r5, [r0, #4] */
575                                                                 /* <wait_fifo>: */
576                 0x06, 0x68,                             /*              ldr             r6, [r0, #0] */
577                 0x26, 0xb3,                             /*              cbz             r6, <exit> */
578                 0x76, 0x1b,                             /*              subs    r6, r6, r5 */
579                 0x42, 0xbf,                             /*              ittt    mi */
580                 0x76, 0x18,                             /*              addmi   r6, r6, r1 */
581                 0x36, 0x1a,                             /*              submi   r6, r6, r0 */
582                 0x08, 0x3e,                             /*              submi   r6, #8 */
583                 0x20, 0x2e,                             /*              cmp             r6, #32 */
584                 0xf6, 0xd3,                             /*              bcc.n   <wait_fifo> */
585                 0x4f, 0xf0, 0x32, 0x06, /*              mov.w   r6, #STM32_PROG */
586                 0xe6, 0x60,                             /*              str             r6, [r4, #STM32_FLASH_CR_OFFSET] */
587                 0x4f, 0xf0, 0x08, 0x07, /*              mov.w   r7, #8 */
588                                                                 /* <write_flash>: */
589                 0x55, 0xf8, 0x04, 0x6b, /*              ldr.w   r6, [r5], #4 */
590                 0x42, 0xf8, 0x04, 0x6b, /*              str.w   r6, [r2], #4 */
591                 0xbf, 0xf3, 0x4f, 0x8f, /*              dsb             sy */
592                 0x8d, 0x42,                             /*              cmp             r5, r1 */
593                 0x28, 0xbf,                             /*              it              cs */
594                 0x00, 0xf1, 0x08, 0x05, /*              addcs.w r5, r0, #8 */
595                 0x01, 0x3f,                             /*              subs    r7, #1 */
596                 0xf3, 0xd1,                             /*              bne.n   <write_flash> */
597                                                                 /* <busy>: */
598                 0x26, 0x69,                             /*              ldr             r6, [r4, #STM32_FLASH_SR_OFFSET] */
599                 0x16, 0xf0, 0x01, 0x0f, /*              tst.w   r6, #STM32_SR_BUSY_MASK */
600                 0xfb, 0xd1,                             /*              bne.n   <busy> */
601                 0x05, 0x4f,                             /*              ldr             r7, [pc, #20] ; (<stm32_sr_error_mask>) */
602                 0x3e, 0x42,                             /*              tst             r6, r7 */
603                 0x03, 0xd1,                             /*              bne.n   <error> */
604                 0x45, 0x60,                             /*              str             r5, [r0, #4] */
605                 0x01, 0x3b,                             /*              subs    r3, #1 */
606                 0xdb, 0xd1,                             /*              bne.n   <wait_fifo> */
607                 0x01, 0xe0,                             /*              b.n             <exit> */
608                                                                 /* <error>: */
609                 0x00, 0x27,                             /*              movs    r7, #0 */
610                 0x47, 0x60,                             /*              str             r7, [r0, #4] */
611                                                                 /* <exit>: */
612                 0x30, 0x46,                             /*              mov             r0, r6 */
613                 0x00, 0xbe,                             /*              bkpt    0x0000 */
614                                                                 /* <stm32_sr_error_mask>: */
615                 0x00, 0x00, 0xee, 0x03  /*              .word   0x03ee0000 ; (STM32_SR_ERROR_MASK) */
616         };
617
618         if (target_alloc_working_area(target, sizeof(stm32x_flash_write_code),
619                         &write_algorithm) != ERROR_OK) {
620                 LOG_WARNING("no working area available, can't do block memory writes");
621                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
622         }
623
624         retval = target_write_buffer(target, write_algorithm->address,
625                         sizeof(stm32x_flash_write_code),
626                         stm32x_flash_write_code);
627         if (retval != ERROR_OK)
628                 return retval;
629
630         /* memory buffer */
631         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) {
632                 data_size /= 2;
633                 buffer_size = 8 + data_size;
634                 if (data_size <= 256) {
635                         /* we already allocated the writing code, but failed to get a
636                          * buffer, free the algorithm */
637                         target_free_working_area(target, write_algorithm);
638
639                         LOG_WARNING("no large enough working area available, can't do block memory writes");
640                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
641                 }
642         }
643
644         LOG_DEBUG("target_alloc_working_area_try : buffer_size -> 0x%x", buffer_size);
645
646         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
647         armv7m_info.core_mode = ARM_MODE_THREAD;
648
649         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT);         /* buffer start, status (out) */
650         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);            /* buffer end */
651         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);            /* target address */
652         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);            /* count (word-256 bits) */
653         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);            /* flash reg base */
654
655         buf_set_u32(reg_params[0].value, 0, 32, source->address);
656         buf_set_u32(reg_params[1].value, 0, 32, source->address + source->size);
657         buf_set_u32(reg_params[2].value, 0, 32, address);
658         buf_set_u32(reg_params[3].value, 0, 32, count);
659         buf_set_u32(reg_params[4].value, 0, 32, stm32x_info->flash_base);
660
661         retval = target_run_flash_async_algorithm(target,
662                                                   buffer,
663                                                   count,
664                                                   FLASH_BLOCK_SIZE,
665                                                   0, NULL,
666                                                   5, reg_params,
667                                                   source->address, source->size,
668                                                   write_algorithm->address, 0,
669                                                   &armv7m_info);
670
671         if (retval == ERROR_FLASH_OPERATION_FAILED) {
672                 LOG_INFO("error executing stm32h7x flash write algorithm");
673
674                 uint32_t flash_sr = buf_get_u32(reg_params[0].value, 0, 32);
675
676                 if (flash_sr & FLASH_WRPERR)
677                         LOG_ERROR("flash memory write protected");
678
679                 if ((flash_sr & FLASH_ERROR) != 0) {
680                         LOG_ERROR("flash write failed, FLASH_SR = %08" PRIx32, flash_sr);
681                         /* Clear error + EOP flags but report errors */
682                         target_write_u32(target, stm32x_get_flash_reg(bank, FLASH_CCR), flash_sr);
683                         retval = ERROR_FAIL;
684                 }
685         }
686
687         target_free_working_area(target, source);
688         target_free_working_area(target, write_algorithm);
689
690         destroy_reg_param(&reg_params[0]);
691         destroy_reg_param(&reg_params[1]);
692         destroy_reg_param(&reg_params[2]);
693         destroy_reg_param(&reg_params[3]);
694         destroy_reg_param(&reg_params[4]);
695         return retval;
696 }
697
698 static int stm32x_write(struct flash_bank *bank, const uint8_t *buffer,
699                 uint32_t offset, uint32_t count)
700 {
701         struct target *target = bank->target;
702         uint32_t address = bank->base + offset;
703         int retval, retval2;
704
705         if (bank->target->state != TARGET_HALTED) {
706                 LOG_ERROR("Target not halted");
707                 return ERROR_TARGET_NOT_HALTED;
708         }
709
710         if (offset % FLASH_BLOCK_SIZE) {
711                 LOG_WARNING("offset 0x%" PRIx32 " breaks required 32-byte alignment", offset);
712                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
713         }
714
715         retval = stm32x_unlock_reg(bank);
716         if (retval != ERROR_OK)
717                 return retval;
718
719         uint32_t blocks_remaining = count / FLASH_BLOCK_SIZE;
720         uint32_t bytes_remaining = count % FLASH_BLOCK_SIZE;
721
722         /* multiple words (32-bytes) to be programmed in block */
723         if (blocks_remaining) {
724                 retval = stm32x_write_block(bank, buffer, offset, blocks_remaining);
725                 if (retval != ERROR_OK) {
726                         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
727                                 /* if block write failed (no sufficient working area),
728                                  * we use normal (slow) dword accesses */
729                                 LOG_WARNING("couldn't use block writes, falling back to single memory accesses");
730                         }
731                 } else {
732                         buffer += blocks_remaining * FLASH_BLOCK_SIZE;
733                         address += blocks_remaining * FLASH_BLOCK_SIZE;
734                         blocks_remaining = 0;
735                 }
736                 if ((retval != ERROR_OK) && (retval != ERROR_TARGET_RESOURCE_NOT_AVAILABLE))
737                         goto flash_lock;
738         }
739
740         /*
741         Standard programming
742         The Flash memory programming sequence is as follows:
743         1. Check that no main Flash memory operation is ongoing by checking the BSY bit in the
744            FLASH_SR register.
745         2. Set the PG bit in the FLASH_CR register
746         3. 8 x Word access (or Force Write FW)
747         4. Wait for the BSY bit to be cleared
748         */
749         while (blocks_remaining > 0) {
750                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, FLASH_CR), FLASH_PG | FLASH_PSIZE_64);
751                 if (retval != ERROR_OK)
752                         goto flash_lock;
753
754                 retval = target_write_buffer(target, address, FLASH_BLOCK_SIZE, buffer);
755                 if (retval != ERROR_OK)
756                         goto flash_lock;
757
758                 retval = stm32x_wait_status_busy(bank, FLASH_WRITE_TIMEOUT);
759                 if (retval != ERROR_OK)
760                         goto flash_lock;
761
762                 buffer += FLASH_BLOCK_SIZE;
763                 address += FLASH_BLOCK_SIZE;
764                 blocks_remaining--;
765         }
766
767         if (bytes_remaining) {
768                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, FLASH_CR), FLASH_PG | FLASH_PSIZE_64);
769                 if (retval != ERROR_OK)
770                         goto flash_lock;
771
772                 retval = target_write_buffer(target, address, bytes_remaining, buffer);
773                 if (retval != ERROR_OK)
774                         goto flash_lock;
775
776                 /* Force Write buffer of FLASH_BLOCK_SIZE = 32 bytes */
777                 retval = target_write_u32(target, stm32x_get_flash_reg(bank, FLASH_CR), FLASH_PG | FLASH_PSIZE_64 | FLASH_FW);
778                 if (retval != ERROR_OK)
779                         goto flash_lock;
780
781                 retval = stm32x_wait_status_busy(bank, FLASH_WRITE_TIMEOUT);
782                 if (retval != ERROR_OK)
783                         goto flash_lock;
784         }
785
786 flash_lock:
787         retval2 = stm32x_lock_reg(bank);
788         if (retval2 != ERROR_OK)
789                 LOG_ERROR("error during the lock of flash");
790
791         if (retval == ERROR_OK)
792                 retval = retval2;
793
794         return retval;
795 }
796
797 static void setup_sector(struct flash_bank *bank, int start, int num, int size)
798 {
799         for (int i = start; i < (start + num) ; i++) {
800                 assert(i < bank->num_sectors);
801                 bank->sectors[i].offset = bank->size;
802                 bank->sectors[i].size = size;
803                 bank->size += bank->sectors[i].size;
804         }
805 }
806
807 static int stm32x_read_id_code(struct flash_bank *bank, uint32_t *id)
808 {
809         /* read stm32 device id register */
810         int retval = target_read_u32(bank->target, DBGMCU_IDCODE_REGISTER, id);
811         if (retval != ERROR_OK)
812                 return retval;
813         return ERROR_OK;
814 }
815
816 static int stm32x_probe(struct flash_bank *bank)
817 {
818         struct target *target = bank->target;
819         struct stm32h7x_flash_bank *stm32x_info = bank->driver_priv;
820         int i;
821         uint16_t flash_size_in_kb;
822         uint32_t device_id;
823         uint32_t base_address = FLASH_BANK0_ADDRESS;
824         uint32_t second_bank_base;
825
826         stm32x_info->probed = 0;
827         stm32x_info->part_info = NULL;
828
829         int retval = stm32x_read_id_code(bank, &stm32x_info->idcode);
830         if (retval != ERROR_OK)
831                 return retval;
832
833         LOG_DEBUG("device id = 0x%08" PRIx32 "", stm32x_info->idcode);
834
835         device_id = stm32x_info->idcode & 0xfff;
836
837         for (unsigned int n = 0; n < ARRAY_SIZE(stm32h7x_parts); n++) {
838                 if (device_id == stm32h7x_parts[n].id)
839                         stm32x_info->part_info = &stm32h7x_parts[n];
840         }
841         if (!stm32x_info->part_info) {
842                 LOG_WARNING("Cannot identify target as a STM32H7xx family.");
843                 return ERROR_FAIL;
844         } else {
845                 LOG_INFO("Device: %s", stm32x_info->part_info->device_str);
846         }
847
848         /* update the address of controller from data base */
849         stm32x_info->flash_base = stm32x_info->part_info->flash_base;
850
851         /* get flash size from target */
852         retval = target_read_u16(target, stm32x_info->part_info->fsize_base, &flash_size_in_kb);
853         if (retval != ERROR_OK) {
854                 /* read error when device has invalid value, set max flash size */
855                 flash_size_in_kb = stm32x_info->part_info->max_flash_size_kb;
856         } else
857                 LOG_INFO("flash size probed value %d", flash_size_in_kb);
858
859         /* Lower flash size devices are single bank */
860         if (stm32x_info->part_info->has_dual_bank && (flash_size_in_kb > stm32x_info->part_info->first_bank_size_kb)) {
861                 /* Use the configured base address to determine if this is the first or second flash bank.
862                  * Verify that the base address is reasonably correct and determine the flash bank size
863                  */
864                 second_bank_base = base_address + stm32x_info->part_info->first_bank_size_kb * 1024;
865                 if (bank->base == second_bank_base) {
866                         /* This is the second bank  */
867                         base_address = second_bank_base;
868                         flash_size_in_kb = flash_size_in_kb - stm32x_info->part_info->first_bank_size_kb;
869                         /* bank1 also uses a register offset */
870                         stm32x_info->flash_base = FLASH_REG_BASE_B1;
871                 } else if (bank->base == base_address) {
872                         /* This is the first bank */
873                         flash_size_in_kb = stm32x_info->part_info->first_bank_size_kb;
874                 } else {
875                         LOG_WARNING("STM32H flash bank base address config is incorrect."
876                                     " 0x%" PRIx32 " but should rather be 0x%" PRIx32 " or 0x%" PRIx32,
877                                         bank->base, base_address, second_bank_base);
878                         return ERROR_FAIL;
879                 }
880                 LOG_INFO("STM32H flash has dual banks. Bank (%d) size is %dkb, base address is 0x%" PRIx32,
881                                 bank->bank_number, flash_size_in_kb, base_address);
882         } else {
883                 LOG_INFO("STM32H flash size is %dkb, base address is 0x%" PRIx32, flash_size_in_kb, base_address);
884         }
885
886         /* if the user sets the size manually then ignore the probed value
887          * this allows us to work around devices that have an invalid flash size register value */
888         if (stm32x_info->user_bank_size) {
889                 LOG_INFO("ignoring flash probed value, using configured bank size");
890                 flash_size_in_kb = stm32x_info->user_bank_size / 1024;
891         } else if (flash_size_in_kb == 0xffff) {
892                 /* die flash size */
893                 flash_size_in_kb = stm32x_info->part_info->max_flash_size_kb;
894         }
895
896         /* did we assign flash size? */
897         assert(flash_size_in_kb != 0xffff);
898
899         /* calculate numbers of pages */
900         int num_pages = flash_size_in_kb / stm32x_info->part_info->page_size;
901
902         /* check that calculation result makes sense */
903         assert(num_pages > 0);
904
905         if (bank->sectors) {
906                 free(bank->sectors);
907                 bank->sectors = NULL;
908         }
909
910         bank->base = base_address;
911         bank->num_sectors = num_pages;
912         bank->sectors = malloc(sizeof(struct flash_sector) * num_pages);
913         if (bank->sectors == NULL) {
914                 LOG_ERROR("failed to allocate bank sectors");
915                 return ERROR_FAIL;
916         }
917         bank->size = 0;
918
919         /* fixed memory */
920         setup_sector(bank, 0, num_pages, stm32x_info->part_info->page_size * 1024);
921
922         for (i = 0; i < num_pages; i++) {
923                 bank->sectors[i].is_erased = -1;
924                 bank->sectors[i].is_protected = 0;
925         }
926
927         stm32x_info->probed = 1;
928         return ERROR_OK;
929 }
930
931 static int stm32x_auto_probe(struct flash_bank *bank)
932 {
933         struct stm32h7x_flash_bank *stm32x_info = bank->driver_priv;
934
935         if (stm32x_info->probed)
936                 return ERROR_OK;
937
938         return stm32x_probe(bank);
939 }
940
941 /* This method must return a string displaying information about the bank */
942 static int stm32x_get_info(struct flash_bank *bank, char *buf, int buf_size)
943 {
944         struct stm32h7x_flash_bank *stm32x_info = bank->driver_priv;
945         const struct stm32h7x_part_info *info = stm32x_info->part_info;
946
947         if (!stm32x_info->probed) {
948                 int retval = stm32x_probe(bank);
949                 if (retval != ERROR_OK) {
950                         snprintf(buf, buf_size, "Unable to find bank information.");
951                         return retval;
952                 }
953         }
954
955         if (info) {
956                 const char *rev_str = NULL;
957                 uint16_t rev_id = stm32x_info->idcode >> 16;
958
959                 for (unsigned int i = 0; i < info->num_revs; i++)
960                         if (rev_id == info->revs[i].rev)
961                                 rev_str = info->revs[i].str;
962
963                 if (rev_str != NULL) {
964                         snprintf(buf, buf_size, "%s - Rev: %s",
965                                 stm32x_info->part_info->device_str, rev_str);
966                 } else {
967                         snprintf(buf, buf_size,
968                                  "%s - Rev: unknown (0x%04x)",
969                                 stm32x_info->part_info->device_str, rev_id);
970                 }
971         } else {
972           snprintf(buf, buf_size, "Cannot identify target as a STM32H7x");
973           return ERROR_FAIL;
974         }
975         return ERROR_OK;
976 }
977
978 COMMAND_HANDLER(stm32x_handle_lock_command)
979 {
980         struct target *target = NULL;
981         struct stm32h7x_flash_bank *stm32x_info = NULL;
982
983         if (CMD_ARGC < 1)
984                 return ERROR_COMMAND_SYNTAX_ERROR;
985
986         struct flash_bank *bank;
987         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
988         if (ERROR_OK != retval)
989                 return retval;
990
991         stm32x_info = bank->driver_priv;
992         target = bank->target;
993
994         /* if we have a dual flash bank device then
995          * we need to perform option byte lock on bank0 only */
996         if (stm32x_info->flash_base != FLASH_REG_BASE_B0) {
997                 LOG_ERROR("Option Byte Lock Operation must use bank0");
998                 return ERROR_FLASH_OPERATION_FAILED;
999         }
1000
1001         if (target->state != TARGET_HALTED) {
1002                 LOG_ERROR("Target not halted");
1003                 return ERROR_TARGET_NOT_HALTED;
1004         }
1005
1006         if (stm32x_read_options(bank) != ERROR_OK) {
1007                 command_print(CMD_CTX, "%s failed to read options",
1008                               bank->driver->name);
1009                 return ERROR_OK;
1010         }
1011         /* set readout protection */
1012         stm32x_info->option_bytes.RDP = 0;
1013
1014         if (stm32x_write_options(bank) != ERROR_OK) {
1015                 command_print(CMD_CTX, "%s failed to lock device",
1016                               bank->driver->name);
1017                 return ERROR_OK;
1018         }
1019         command_print(CMD_CTX, "%s locked", bank->driver->name);
1020
1021         return ERROR_OK;
1022 }
1023
1024 COMMAND_HANDLER(stm32x_handle_unlock_command)
1025 {
1026         struct target *target = NULL;
1027         struct stm32h7x_flash_bank *stm32x_info = NULL;
1028
1029         if (CMD_ARGC < 1)
1030                 return ERROR_COMMAND_SYNTAX_ERROR;
1031
1032         struct flash_bank *bank;
1033         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1034         if (ERROR_OK != retval)
1035                 return retval;
1036
1037         stm32x_info = bank->driver_priv;
1038         target = bank->target;
1039
1040         /* if we have a dual flash bank device then
1041          * we need to perform option byte unlock on bank0 only */
1042         if (stm32x_info->flash_base != FLASH_REG_BASE_B0) {
1043                 LOG_ERROR("Option Byte Unlock Operation must use bank0");
1044                 return ERROR_FLASH_OPERATION_FAILED;
1045         }
1046
1047         if (target->state != TARGET_HALTED) {
1048                 LOG_ERROR("Target not halted");
1049                 return ERROR_TARGET_NOT_HALTED;
1050         }
1051
1052         if (stm32x_read_options(bank) != ERROR_OK) {
1053                 command_print(CMD_CTX, "%s failed to read options", bank->driver->name);
1054                 return ERROR_OK;
1055         }
1056
1057         /* clear readout protection option byte
1058          * this will also force a device unlock if set */
1059         stm32x_info->option_bytes.RDP = 0xAA;
1060
1061         if (stm32x_write_options(bank) != ERROR_OK) {
1062                 command_print(CMD_CTX, "%s failed to unlock device", bank->driver->name);
1063                 return ERROR_OK;
1064         }
1065         command_print(CMD_CTX, "%s unlocked.\n", bank->driver->name);
1066
1067         return ERROR_OK;
1068 }
1069
1070 static int stm32x_mass_erase(struct flash_bank *bank)
1071 {
1072         int retval;
1073         struct target *target = bank->target;
1074
1075         if (target->state != TARGET_HALTED) {
1076                 LOG_ERROR("Target not halted");
1077                 return ERROR_TARGET_NOT_HALTED;
1078         }
1079
1080         retval = stm32x_unlock_reg(bank);
1081         if (retval != ERROR_OK)
1082                 return retval;
1083
1084         /* mass erase flash memory bank */
1085         retval = target_write_u32(target, stm32x_get_flash_reg(bank, FLASH_CR), FLASH_BER_CMD | FLASH_PSIZE_64);
1086         if (retval != ERROR_OK)
1087                 return retval;
1088
1089         retval = target_write_u32(target, stm32x_get_flash_reg(bank, FLASH_CR),
1090                                                           FLASH_BER_CMD | FLASH_PSIZE_64 | FLASH_START);
1091         if (retval != ERROR_OK)
1092                 return retval;
1093
1094         retval = stm32x_wait_status_busy(bank, 30000);
1095         if (retval != ERROR_OK)
1096                 return retval;
1097
1098         retval = stm32x_lock_reg(bank);
1099         if (retval != ERROR_OK) {
1100                 LOG_ERROR("error during the lock of flash");
1101                 return retval;
1102         }
1103         return ERROR_OK;
1104 }
1105
1106 COMMAND_HANDLER(stm32x_handle_mass_erase_command)
1107 {
1108         int i;
1109
1110         if (CMD_ARGC < 1) {
1111                 command_print(CMD_CTX, "stm32h7x mass_erase <bank>");
1112                 return ERROR_COMMAND_SYNTAX_ERROR;
1113         }
1114
1115         struct flash_bank *bank;
1116         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1117         if (ERROR_OK != retval)
1118                 return retval;
1119
1120         retval = stm32x_mass_erase(bank);
1121         if (retval == ERROR_OK) {
1122                 /* set all sectors as erased */
1123                 for (i = 0; i < bank->num_sectors; i++)
1124                         bank->sectors[i].is_erased = 1;
1125
1126                 command_print(CMD_CTX, "stm32h7x mass erase complete");
1127         } else {
1128                 command_print(CMD_CTX, "stm32h7x mass erase failed");
1129         }
1130
1131         return retval;
1132 }
1133
1134 static const struct command_registration stm32x_exec_command_handlers[] = {
1135         {
1136                 .name = "lock",
1137                 .handler = stm32x_handle_lock_command,
1138                 .mode = COMMAND_EXEC,
1139                 .usage = "bank_id",
1140                 .help = "Lock entire flash device.",
1141         },
1142         {
1143                 .name = "unlock",
1144                 .handler = stm32x_handle_unlock_command,
1145                 .mode = COMMAND_EXEC,
1146                 .usage = "bank_id",
1147                 .help = "Unlock entire protected flash device.",
1148         },
1149         {
1150                 .name = "mass_erase",
1151                 .handler = stm32x_handle_mass_erase_command,
1152                 .mode = COMMAND_EXEC,
1153                 .usage = "bank_id",
1154                 .help = "Erase entire flash device.",
1155         },
1156         COMMAND_REGISTRATION_DONE
1157 };
1158
1159 static const struct command_registration stm32x_command_handlers[] = {
1160         {
1161                 .name = "stm32h7x",
1162                 .mode = COMMAND_ANY,
1163                 .help = "stm32h7x flash command group",
1164                 .usage = "",
1165                 .chain = stm32x_exec_command_handlers,
1166         },
1167         COMMAND_REGISTRATION_DONE
1168 };
1169
1170 struct flash_driver stm32h7x_flash = {
1171         .name = "stm32h7x",
1172         .commands = stm32x_command_handlers,
1173         .flash_bank_command = stm32x_flash_bank_command,
1174         .erase = stm32x_erase,
1175         .protect = stm32x_protect,
1176         .write = stm32x_write,
1177         .read = default_flash_read,
1178         .probe = stm32x_probe,
1179         .auto_probe = stm32x_auto_probe,
1180         .erase_check = default_flash_blank_check,
1181         .protect_check = stm32x_protect_check,
1182         .info = stm32x_get_info,
1183 };