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