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