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