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