flash/nor: add support for Nuvoton NPCX series flash
[fw/openocd] / src / flash / nor / stmqspi.c
1 /***************************************************************************
2  *   Copyright (C) 2016 - 2019 by Andreas Bolsch                           *
3  *   andreas.bolsch@mni.thm.de                                             *
4  *                                                                         *
5  *   Copyright (C) 2010 by Antonio Borneo                                  *
6  *   borneo.antonio@gmail.com                                              *
7  *                                                                         *
8  *   This program is free software; you can redistribute it and/or modify  *
9  *   it under the terms of the GNU General Public License as published by  *
10  *   the Free Software Foundation; either version 2 of the License, or     *
11  *   (at your option) any later version.                                   *
12  *                                                                         *
13  *   This program is distributed in the hope that it will be useful,       *
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
16  *   GNU General Public License for more details.                          *
17  *                                                                         *
18  *   You should have received a copy of the GNU General Public License     *
19  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
20  ***************************************************************************/
21
22 /* STM QuadSPI (QSPI) and OctoSPI (OCTOSPI) controller are SPI bus controllers
23  * specifically designed for SPI memories.
24  * Two working modes are available:
25  * - indirect mode: the SPI is controlled by SW. Any custom commands can be sent
26  *   on the bus.
27  * - memory mapped mode: the SPI is under QSPI/OCTOSPI control. Memory content
28  *   is directly accessible in CPU memory space. CPU can read and execute from
29  *   memory (but not write to) */
30
31 /* ATTENTION:
32  * To have flash mapped in CPU memory space, the QSPI/OCTOSPI controller
33  * has to be in "memory mapped mode". This requires following constraints:
34  * 1) The command "reset init" has to initialize QSPI/OCTOSPI controller and put
35  *    it in memory mapped mode;
36  * 2) every command in this file has to return to prompt in memory mapped mode. */
37
38 #ifdef HAVE_CONFIG_H
39 #include "config.h"
40 #endif
41
42 #include "imp.h"
43 #include <helper/bits.h>
44 #include <helper/time_support.h>
45 #include <target/algorithm.h>
46 #include <target/armv7m.h>
47 #include <target/image.h>
48 #include "stmqspi.h"
49 #include "sfdp.h"
50
51 /* deprecated */
52 #undef SPIFLASH_READ
53 #undef SPIFLASH_PAGE_PROGRAM
54
55 /* saved mode settings */
56 #define QSPI_MODE (stmqspi_info->saved_ccr & \
57         (0xF0000000U | QSPI_DCYC_MASK | QSPI_4LINE_MODE | QSPI_ALTB_MODE | QSPI_ADDR4))
58
59 /* saved read mode settings but indirect read instead of memory mapped
60  * in particular, use the dummy cycle setting from this saved setting */
61 #define QSPI_CCR_READ (QSPI_READ_MODE | (stmqspi_info->saved_ccr & \
62         (0xF0000000U | QSPI_DCYC_MASK | QSPI_4LINE_MODE | QSPI_ALTB_MODE | QSPI_ADDR4 | 0xFF)))
63
64 /* QSPI_CCR for various other commands, these never use dummy cycles nor alternate bytes */
65 #define QSPI_CCR_READ_STATUS \
66         ((QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ADDR & QSPI_NO_ALTB) | \
67         (QSPI_READ_MODE | SPIFLASH_READ_STATUS))
68
69 #define QSPI_CCR_READ_ID \
70         ((QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ADDR & QSPI_NO_ALTB) | \
71         (QSPI_READ_MODE | SPIFLASH_READ_ID))
72
73 #define QSPI_CCR_READ_MID \
74         ((QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ADDR & QSPI_NO_ALTB) | \
75         (QSPI_READ_MODE | SPIFLASH_READ_MID))
76
77 /* always use 3-byte addresses for read SFDP */
78 #define QSPI_CCR_READ_SFDP \
79         ((QSPI_MODE & ~QSPI_DCYC_MASK & ~QSPI_ADDR4 & QSPI_NO_ALTB) | \
80         (QSPI_READ_MODE | QSPI_ADDR3 | SPIFLASH_READ_SFDP))
81
82 #define QSPI_CCR_WRITE_ENABLE \
83         ((QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ADDR & QSPI_NO_ALTB & QSPI_NO_DATA) | \
84         (QSPI_WRITE_MODE | SPIFLASH_WRITE_ENABLE))
85
86 #define QSPI_CCR_SECTOR_ERASE \
87         ((QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ALTB & QSPI_NO_DATA) | \
88         (QSPI_WRITE_MODE | stmqspi_info->dev.erase_cmd))
89
90 #define QSPI_CCR_MASS_ERASE \
91         ((QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ADDR & QSPI_NO_ALTB & QSPI_NO_DATA) | \
92         (QSPI_WRITE_MODE | stmqspi_info->dev.chip_erase_cmd))
93
94 #define QSPI_CCR_PAGE_PROG \
95         ((QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ALTB) | \
96         (QSPI_WRITE_MODE | stmqspi_info->dev.pprog_cmd))
97
98 /* saved mode settings */
99 #define OCTOSPI_MODE (stmqspi_info->saved_cr & 0xCFFFFFFF)
100
101 #define OPI_MODE ((stmqspi_info->saved_ccr & OCTOSPI_ISIZE_MASK) != 0)
102
103 #define OCTOSPI_MODE_CCR (stmqspi_info->saved_ccr & \
104         (0xF0000000U | OCTOSPI_8LINE_MODE | OCTOSPI_ALTB_MODE | OCTOSPI_ADDR4))
105
106 /* use saved ccr for read */
107 #define OCTOSPI_CCR_READ OCTOSPI_MODE_CCR
108
109 /* OCTOSPI_CCR for various other commands, these never use alternate bytes      *
110  * for READ_STATUS and READ_ID, 4-byte address 0                                                        *
111  * 4 dummy cycles must sent in OPI mode when DQS is disabled. However, when     *
112  * DQS is enabled, some STM32 devices need at least 6 dummy cycles for          *
113  * proper operation, but otherwise the actual number has no effect!                     *
114  * E.g. RM0432 Rev. 7 is incorrect regarding this: L4R9 works well with 4       *
115  * dummy clocks whereas L4P5 not at all.                                                                        *
116  */
117 #define OPI_DUMMY \
118         ((stmqspi_info->saved_ccr & OCTOSPI_DQSEN) ? 6U : 4U)
119
120 #define OCTOSPI_CCR_READ_STATUS \
121         ((OCTOSPI_MODE_CCR & OCTOSPI_NO_DDTR & \
122         (OPI_MODE ? ~0U : OCTOSPI_NO_ADDR) & OCTOSPI_NO_ALTB))
123
124 #define OCTOSPI_CCR_READ_ID \
125         ((OCTOSPI_MODE_CCR & OCTOSPI_NO_DDTR & \
126         (OPI_MODE ? ~0U : OCTOSPI_NO_ADDR) & OCTOSPI_NO_ALTB))
127
128 #define OCTOSPI_CCR_READ_MID OCTOSPI_CCR_READ_ID
129
130 /* 4-byte address in octo mode, else 3-byte address for read SFDP */
131 #define OCTOSPI_CCR_READ_SFDP(len) \
132         ((OCTOSPI_MODE_CCR & OCTOSPI_NO_DDTR & ~OCTOSPI_ADDR4 & OCTOSPI_NO_ALTB) | \
133         (((len) < 4) ? OCTOSPI_ADDR3 : OCTOSPI_ADDR4))
134
135 #define OCTOSPI_CCR_WRITE_ENABLE \
136         ((OCTOSPI_MODE_CCR & OCTOSPI_NO_ADDR & OCTOSPI_NO_ALTB & OCTOSPI_NO_DATA))
137
138 #define OCTOSPI_CCR_SECTOR_ERASE \
139         ((OCTOSPI_MODE_CCR & OCTOSPI_NO_ALTB & OCTOSPI_NO_DATA))
140
141 #define OCTOSPI_CCR_MASS_ERASE \
142         ((OCTOSPI_MODE_CCR & OCTOSPI_NO_ADDR & OCTOSPI_NO_ALTB & OCTOSPI_NO_DATA))
143
144 #define OCTOSPI_CCR_PAGE_PROG \
145         ((OCTOSPI_MODE_CCR & QSPI_NO_ALTB))
146
147 #define SPI_ADSIZE (((stmqspi_info->saved_ccr >> SPI_ADSIZE_POS) & 0x3) + 1)
148
149 #define OPI_CMD(cmd) ((OPI_MODE ? ((((uint16_t)(cmd)) << 8) | (~(cmd) & 0xFFU)) : (cmd)))
150
151 /* convert uint32_t into 4 uint8_t in little endian byte order */
152 static inline uint32_t h_to_le_32(uint32_t val)
153 {
154         uint32_t result;
155
156         h_u32_to_le((uint8_t *)&result, val);
157         return result;
158 }
159
160 /* Timeout in ms */
161 #define SPI_CMD_TIMEOUT                 (100)
162 #define SPI_PROBE_TIMEOUT               (100)
163 #define SPI_MAX_TIMEOUT                 (2000)
164 #define SPI_MASS_ERASE_TIMEOUT  (400000)
165
166 struct sector_info {
167         uint32_t offset;
168         uint32_t size;
169         uint32_t result;
170 };
171
172 struct stmqspi_flash_bank {
173         bool probed;
174         char devname[32];
175         bool octo;
176         struct flash_device dev;
177         uint32_t io_base;
178         uint32_t saved_cr;      /* in particular FSEL, DFM bit mask in QUADSPI_CR *AND* OCTOSPI_CR */
179         uint32_t saved_ccr; /* different meaning for QUADSPI and OCTOSPI */
180         uint32_t saved_tcr;     /* only for OCTOSPI */
181         uint32_t saved_ir;      /* only for OCTOSPI */
182         unsigned int sfdp_dummy1;       /* number of dummy bytes for SFDP read for flash1 and octo */
183         unsigned int sfdp_dummy2;       /* number of dummy bytes for SFDP read for flash2 */
184 };
185
186 static inline int octospi_cmd(struct flash_bank *bank, uint32_t mode,
187                 uint32_t ccr, uint32_t ir)
188 {
189         struct target *target = bank->target;
190         const struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
191         const uint32_t io_base = stmqspi_info->io_base;
192
193         int retval = target_write_u32(target, io_base + OCTOSPI_CR,
194                 OCTOSPI_MODE | mode);
195
196         if (retval != ERROR_OK)
197                 return retval;
198
199         retval = target_write_u32(target, io_base + OCTOSPI_TCR,
200                 (stmqspi_info->saved_tcr & ~OCTOSPI_DCYC_MASK) |
201                 ((OPI_MODE && (mode == OCTOSPI_READ_MODE)) ?
202                 (OPI_DUMMY << OCTOSPI_DCYC_POS) : 0));
203
204         if (retval != ERROR_OK)
205                 return retval;
206
207         retval = target_write_u32(target, io_base + OCTOSPI_CCR, ccr);
208
209         if (retval != ERROR_OK)
210                 return retval;
211
212         return target_write_u32(target, io_base + OCTOSPI_IR, OPI_CMD(ir));
213 }
214
215 FLASH_BANK_COMMAND_HANDLER(stmqspi_flash_bank_command)
216 {
217         struct stmqspi_flash_bank *stmqspi_info;
218         uint32_t io_base;
219
220         LOG_DEBUG("%s", __func__);
221
222         if (CMD_ARGC < 7)
223                 return ERROR_COMMAND_SYNTAX_ERROR;
224
225         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[6], io_base);
226
227         stmqspi_info = malloc(sizeof(struct stmqspi_flash_bank));
228         if (!stmqspi_info) {
229                 LOG_ERROR("not enough memory");
230                 return ERROR_FAIL;
231         }
232
233         bank->driver_priv = stmqspi_info;
234         stmqspi_info->sfdp_dummy1 = 0;
235         stmqspi_info->sfdp_dummy2 = 0;
236         stmqspi_info->probed = false;
237         stmqspi_info->io_base = io_base;
238
239         return ERROR_OK;
240 }
241
242 /* Poll busy flag */
243 /* timeout in ms */
244 static int poll_busy(struct flash_bank *bank, int timeout)
245 {
246         struct target *target = bank->target;
247         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
248         uint32_t io_base = stmqspi_info->io_base;
249         long long endtime;
250
251         endtime = timeval_ms() + timeout;
252         do {
253                 uint32_t spi_sr;
254                 int retval = target_read_u32(target, io_base + SPI_SR, &spi_sr);
255
256                 if (retval != ERROR_OK)
257                         return retval;
258
259                 if ((spi_sr & BIT(SPI_BUSY)) == 0) {
260                         /* Clear transmit finished flag */
261                         return target_write_u32(target, io_base + SPI_FCR, BIT(SPI_TCF));
262                 } else
263                         LOG_DEBUG("busy: 0x%08X", spi_sr);
264                 alive_sleep(1);
265         } while (timeval_ms() < endtime);
266
267         LOG_ERROR("Timeout while polling BUSY");
268         return ERROR_FLASH_OPERATION_FAILED;
269 }
270
271 static int stmqspi_abort(struct flash_bank *bank)
272 {
273         struct target *target = bank->target;
274         const struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
275         const uint32_t io_base = stmqspi_info->io_base;
276         uint32_t cr;
277
278         int retval = target_read_u32(target, io_base + SPI_CR, &cr);
279
280         if (retval != ERROR_OK)
281                 cr = 0;
282
283         return target_write_u32(target, io_base + SPI_CR, cr | BIT(SPI_ABORT));
284 }
285
286 /* Set to memory-mapped mode, e.g. after an error */
287 static int set_mm_mode(struct flash_bank *bank)
288 {
289         struct target *target = bank->target;
290         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
291         uint32_t io_base = stmqspi_info->io_base;
292         int retval;
293
294         /* Reset Address register bits 0 and 1, see various errata sheets */
295         retval = target_write_u32(target, io_base + SPI_AR, 0x0);
296         if (retval != ERROR_OK)
297                 return retval;
298
299         /* Abort any previous operation */
300         retval = stmqspi_abort(bank);
301         if (retval != ERROR_OK)
302                 return retval;
303
304         /* Wait for busy to be cleared */
305         retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
306         if (retval != ERROR_OK)
307                 return retval;
308
309         /* Finally switch to memory mapped mode */
310         if (IS_OCTOSPI) {
311                 retval = target_write_u32(target, io_base + OCTOSPI_CR,
312                         OCTOSPI_MODE | OCTOSPI_MM_MODE);
313                 if (retval == ERROR_OK)
314                         retval = target_write_u32(target, io_base + OCTOSPI_CCR,
315                                 stmqspi_info->saved_ccr);
316                 if (retval == ERROR_OK)
317                         retval = target_write_u32(target, io_base + OCTOSPI_TCR,
318                                 stmqspi_info->saved_tcr);
319                 if (retval == ERROR_OK)
320                         retval = target_write_u32(target, io_base + OCTOSPI_IR,
321                                 stmqspi_info->saved_ir);
322         } else {
323                 retval = target_write_u32(target, io_base + QSPI_CR,
324                         stmqspi_info->saved_cr);
325                 if (retval == ERROR_OK)
326                         retval = target_write_u32(target, io_base + QSPI_CCR,
327                                 stmqspi_info->saved_ccr);
328         }
329         return retval;
330 }
331
332 /* Read the status register of the external SPI flash chip(s). */
333 static int read_status_reg(struct flash_bank *bank, uint16_t *status)
334 {
335         struct target *target = bank->target;
336         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
337         uint32_t io_base = stmqspi_info->io_base;
338         uint8_t data;
339         int count, retval;
340
341         /* Abort any previous operation */
342         retval = stmqspi_abort(bank);
343         if (retval != ERROR_OK)
344                 return retval;
345
346         /* Wait for busy to be cleared */
347         retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
348         if (retval != ERROR_OK)
349                 goto err;
350
351         /* Read always two (for DTR mode) bytes per chip */
352         count = 2;
353         retval = target_write_u32(target, io_base + SPI_DLR,
354                 ((stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? 2 * count : count) - 1);
355         if (retval != ERROR_OK)
356                 goto err;
357
358         /* Read status */
359         if (IS_OCTOSPI) {
360                 retval = octospi_cmd(bank, OCTOSPI_READ_MODE, OCTOSPI_CCR_READ_STATUS,
361                         SPIFLASH_READ_STATUS);
362                 if (OPI_MODE) {
363                         /* Dummy address 0, only required for 8-line mode */
364                         retval = target_write_u32(target, io_base + SPI_AR, 0);
365                         if (retval != ERROR_OK)
366                                 goto err;
367                 }
368         } else
369                 retval = target_write_u32(target, io_base + QSPI_CCR, QSPI_CCR_READ_STATUS);
370         if (retval != ERROR_OK)
371                 goto err;
372
373         *status = 0;
374
375         /* for debugging only */
376         uint32_t dummy;
377         (void)target_read_u32(target, io_base + SPI_SR, &dummy);
378
379         for ( ; count > 0; --count) {
380                 if ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH)))
381                         != BIT(SPI_FSEL_FLASH)) {
382                         /* get status of flash 1 in dual mode or flash 1 only mode */
383                         retval = target_read_u8(target, io_base + SPI_DR, &data);
384                         if (retval != ERROR_OK)
385                                 goto err;
386                         *status |= data;
387                 }
388
389                 if ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH))) != 0) {
390                         /* get status of flash 2 in dual mode or flash 2 only mode */
391                         retval = target_read_u8(target, io_base + SPI_DR, &data);
392                         if (retval != ERROR_OK)
393                                 goto err;
394                         *status |= ((uint16_t)data) << 8;
395                 }
396         }
397
398         LOG_DEBUG("flash status regs: 0x%04" PRIx16, *status);
399
400 err:
401         return retval;
402 }
403
404 /* check for WIP (write in progress) bit(s) in status register(s) */
405 /* timeout in ms */
406 static int wait_till_ready(struct flash_bank *bank, int timeout)
407 {
408         uint16_t status;
409         int retval;
410         long long endtime;
411
412         endtime = timeval_ms() + timeout;
413         do {
414                 /* Read flash status register(s) */
415                 retval = read_status_reg(bank, &status);
416                 if (retval != ERROR_OK)
417                         return retval;
418
419                 if ((status & ((SPIFLASH_BSY_BIT << 8) | SPIFLASH_BSY_BIT)) == 0)
420                         return retval;
421                 alive_sleep(25);
422         } while (timeval_ms() < endtime);
423
424         LOG_ERROR("timeout");
425         return ERROR_FLASH_OPERATION_FAILED;
426 }
427
428 /* Send "write enable" command to SPI flash chip(s). */
429 static int qspi_write_enable(struct flash_bank *bank)
430 {
431         struct target *target = bank->target;
432         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
433         uint32_t io_base = stmqspi_info->io_base;
434         uint16_t status;
435         int retval;
436
437         /* Abort any previous operation */
438         retval = stmqspi_abort(bank);
439         if (retval != ERROR_OK)
440                 return retval;
441
442         /* Wait for busy to be cleared */
443         retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
444         if (retval != ERROR_OK)
445                 goto err;
446
447         /* Send write enable command */
448         if (IS_OCTOSPI) {
449                 retval = octospi_cmd(bank, OCTOSPI_WRITE_MODE, OCTOSPI_CCR_WRITE_ENABLE,
450                         SPIFLASH_WRITE_ENABLE);
451                 if (OPI_MODE) {
452                         /* Dummy address 0, only required for 8-line mode */
453                         retval = target_write_u32(target, io_base + SPI_AR, 0);
454                         if (retval != ERROR_OK)
455                                 goto err;
456                 }
457         } else
458                 retval = target_write_u32(target, io_base + QSPI_CCR, QSPI_CCR_WRITE_ENABLE);
459         if (retval != ERROR_OK)
460                 goto err;
461
462
463         /* Wait for transmit of command completed */
464         poll_busy(bank, SPI_CMD_TIMEOUT);
465         if (retval != ERROR_OK)
466                 goto err;
467
468         /* Read flash status register */
469         retval = read_status_reg(bank, &status);
470         if (retval != ERROR_OK)
471                 goto err;
472
473         /* Check write enabled for flash 1 */
474         if ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH)))
475                 != BIT(SPI_FSEL_FLASH))
476                 if ((status & (SPIFLASH_WE_BIT | SPIFLASH_BSY_BIT)) != SPIFLASH_WE_BIT) {
477                         LOG_ERROR("Cannot write enable flash1. Status=0x%02x",
478                                 status & 0xFFU);
479                         return ERROR_FLASH_OPERATION_FAILED;
480                 }
481
482         /* Check write enabled for flash 2 */
483         status >>= 8;
484         if ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH))) != 0)
485                 if ((status & (SPIFLASH_WE_BIT | SPIFLASH_BSY_BIT)) != SPIFLASH_WE_BIT) {
486                         LOG_ERROR("Cannot write enable flash2. Status=0x%02x",
487                                 status & 0xFFU);
488                         return ERROR_FLASH_OPERATION_FAILED;
489                 }
490
491 err:
492         return retval;
493 }
494
495 COMMAND_HANDLER(stmqspi_handle_mass_erase_command)
496 {
497         struct target *target = NULL;
498         struct flash_bank *bank;
499         struct stmqspi_flash_bank *stmqspi_info;
500         struct duration bench;
501         uint32_t io_base;
502         uint16_t status;
503         unsigned int sector;
504         int retval;
505
506         LOG_DEBUG("%s", __func__);
507
508         if (CMD_ARGC != 1)
509                 return ERROR_COMMAND_SYNTAX_ERROR;
510
511         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
512         if (retval != ERROR_OK)
513                 return retval;
514
515         stmqspi_info = bank->driver_priv;
516         target = bank->target;
517
518         if (target->state != TARGET_HALTED) {
519                 LOG_ERROR("Target not halted");
520                 return ERROR_TARGET_NOT_HALTED;
521         }
522
523         if (!(stmqspi_info->probed)) {
524                 LOG_ERROR("Flash bank not probed");
525                 return ERROR_FLASH_BANK_NOT_PROBED;
526         }
527
528         if (stmqspi_info->dev.chip_erase_cmd == 0x00) {
529                 LOG_ERROR("Mass erase not available for this device");
530                 return ERROR_FLASH_OPER_UNSUPPORTED;
531         }
532
533         for (sector = 0; sector < bank->num_sectors; sector++) {
534                 if (bank->sectors[sector].is_protected) {
535                         LOG_ERROR("Flash sector %u protected", sector);
536                         return ERROR_FLASH_PROTECTED;
537                 }
538         }
539
540         io_base = stmqspi_info->io_base;
541         duration_start(&bench);
542
543         retval = qspi_write_enable(bank);
544         if (retval != ERROR_OK)
545                 goto err;
546
547         /* Send Mass Erase command */
548         if (IS_OCTOSPI)
549                 retval = octospi_cmd(bank, OCTOSPI_WRITE_MODE, OCTOSPI_CCR_MASS_ERASE,
550                         stmqspi_info->dev.chip_erase_cmd);
551         else
552                 retval = target_write_u32(target, io_base + QSPI_CCR, QSPI_CCR_MASS_ERASE);
553         if (retval != ERROR_OK)
554                 goto err;
555
556         /* Wait for transmit of command completed */
557         poll_busy(bank, SPI_CMD_TIMEOUT);
558         if (retval != ERROR_OK)
559                 goto err;
560
561         /* Read flash status register(s) */
562         retval = read_status_reg(bank, &status);
563         if (retval != ERROR_OK)
564                 goto err;
565
566         /* Check for command in progress for flash 1 */
567         if (((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH)))
568                 != BIT(SPI_FSEL_FLASH)) && ((status & SPIFLASH_BSY_BIT) == 0) &&
569                 ((status & SPIFLASH_WE_BIT) != 0)) {
570                 LOG_ERROR("Mass erase command not accepted by flash1. Status=0x%02x",
571                         status & 0xFFU);
572                 retval = ERROR_FLASH_OPERATION_FAILED;
573                 goto err;
574         }
575
576         /* Check for command in progress for flash 2 */
577         status >>= 8;
578         if (((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH))) != 0) &&
579                 ((status & SPIFLASH_BSY_BIT) == 0) &&
580                 ((status & SPIFLASH_WE_BIT) != 0)) {
581                 LOG_ERROR("Mass erase command not accepted by flash2. Status=0x%02x",
582                         status & 0xFFU);
583                 retval = ERROR_FLASH_OPERATION_FAILED;
584                 goto err;
585         }
586
587         /* Poll WIP for end of self timed Sector Erase cycle */
588         retval = wait_till_ready(bank, SPI_MASS_ERASE_TIMEOUT);
589
590         duration_measure(&bench);
591         if (retval == ERROR_OK)
592                 command_print(CMD, "stmqspi mass erase completed in %fs (%0.3f KiB/s)",
593                         duration_elapsed(&bench),
594                         duration_kbps(&bench, bank->size));
595         else
596                 command_print(CMD, "stmqspi mass erase not completed even after %fs",
597                         duration_elapsed(&bench));
598
599 err:
600         /* Switch to memory mapped mode before return to prompt */
601         set_mm_mode(bank);
602
603         return retval;
604 }
605
606 static int log2u(uint32_t word)
607 {
608         int result;
609
610         for (result = 0; (unsigned int) result < sizeof(uint32_t) * CHAR_BIT; result++)
611                 if (word == BIT(result))
612                         return result;
613
614         return -1;
615 }
616
617 COMMAND_HANDLER(stmqspi_handle_set)
618 {
619         struct flash_bank *bank = NULL;
620         struct target *target = NULL;
621         struct stmqspi_flash_bank *stmqspi_info = NULL;
622         struct flash_sector *sectors = NULL;
623         uint32_t io_base;
624         unsigned int index = 0, dual, fsize;
625         int retval;
626
627         LOG_DEBUG("%s", __func__);
628
629         dual = (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? 1 : 0;
630
631         /* chip_erase_cmd, sectorsize and erase_cmd are optional */
632         if ((CMD_ARGC < 7) || (CMD_ARGC > 10))
633                 return ERROR_COMMAND_SYNTAX_ERROR;
634
635         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, index++, &bank);
636         if (retval != ERROR_OK)
637                 return retval;
638
639         target = bank->target;
640         stmqspi_info = bank->driver_priv;
641
642         /* invalidate all old info */
643         if (stmqspi_info->probed)
644                 free(bank->sectors);
645         bank->size = 0;
646         bank->num_sectors = 0;
647         bank->sectors = NULL;
648         stmqspi_info->sfdp_dummy1 = 0;
649         stmqspi_info->sfdp_dummy2 = 0;
650         stmqspi_info->probed = false;
651         memset(&stmqspi_info->dev, 0, sizeof(stmqspi_info->dev));
652         stmqspi_info->dev.name = "unknown";
653
654         strncpy(stmqspi_info->devname, CMD_ARGV[index++], sizeof(stmqspi_info->devname) - 1);
655         stmqspi_info->devname[sizeof(stmqspi_info->devname) - 1] = '\0';
656
657         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[index++], stmqspi_info->dev.size_in_bytes);
658         if (log2u(stmqspi_info->dev.size_in_bytes) < 8) {
659                 command_print(CMD, "stmqspi: device size must be 2^n with n >= 8");
660                 return ERROR_COMMAND_SYNTAX_ERROR;
661         }
662
663         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[index++], stmqspi_info->dev.pagesize);
664         if (stmqspi_info->dev.pagesize > stmqspi_info->dev.size_in_bytes ||
665                 (log2u(stmqspi_info->dev.pagesize) < 0)) {
666                 command_print(CMD, "stmqspi: page size must be 2^n and <= device size");
667                 return ERROR_COMMAND_SYNTAX_ERROR;
668         }
669
670         COMMAND_PARSE_NUMBER(u8, CMD_ARGV[index++], stmqspi_info->dev.read_cmd);
671         if ((stmqspi_info->dev.read_cmd != 0x03) &&
672                 (stmqspi_info->dev.read_cmd != 0x13)) {
673                 command_print(CMD, "stmqspi: only 0x03/0x13 READ cmd allowed");
674                 return ERROR_COMMAND_SYNTAX_ERROR;
675         }
676
677         COMMAND_PARSE_NUMBER(u8, CMD_ARGV[index++], stmqspi_info->dev.qread_cmd);
678         if ((stmqspi_info->dev.qread_cmd != 0x00) &&
679                 (stmqspi_info->dev.qread_cmd != 0x0B) &&
680                 (stmqspi_info->dev.qread_cmd != 0x0C) &&
681                 (stmqspi_info->dev.qread_cmd != 0x3B) &&
682                 (stmqspi_info->dev.qread_cmd != 0x3C) &&
683                 (stmqspi_info->dev.qread_cmd != 0x6B) &&
684                 (stmqspi_info->dev.qread_cmd != 0x6C) &&
685                 (stmqspi_info->dev.qread_cmd != 0xBB) &&
686                 (stmqspi_info->dev.qread_cmd != 0xBC) &&
687                 (stmqspi_info->dev.qread_cmd != 0xEB) &&
688                 (stmqspi_info->dev.qread_cmd != 0xEC) &&
689                 (stmqspi_info->dev.qread_cmd != 0xEE)) {
690                 command_print(CMD, "stmqspi: only 0x0B/0x0C/0x3B/0x3C/"
691                         "0x6B/0x6C/0xBB/0xBC/0xEB/0xEC/0xEE QREAD allowed");
692                 return ERROR_COMMAND_SYNTAX_ERROR;
693         }
694
695         COMMAND_PARSE_NUMBER(u8, CMD_ARGV[index++], stmqspi_info->dev.pprog_cmd);
696         if ((stmqspi_info->dev.pprog_cmd != 0x02) &&
697                 (stmqspi_info->dev.pprog_cmd != 0x12) &&
698                 (stmqspi_info->dev.pprog_cmd != 0x32)) {
699                 command_print(CMD, "stmqspi: only 0x02/0x12/0x32 PPRG cmd allowed");
700                 return ERROR_COMMAND_SYNTAX_ERROR;
701         }
702
703         if (index < CMD_ARGC)
704                 COMMAND_PARSE_NUMBER(u8, CMD_ARGV[index++], stmqspi_info->dev.chip_erase_cmd);
705         else
706                 stmqspi_info->dev.chip_erase_cmd = 0x00;
707
708         if (index < CMD_ARGC) {
709                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[index++], stmqspi_info->dev.sectorsize);
710                 if ((stmqspi_info->dev.sectorsize > stmqspi_info->dev.size_in_bytes) ||
711                         (stmqspi_info->dev.sectorsize < stmqspi_info->dev.pagesize) ||
712                         (log2u(stmqspi_info->dev.sectorsize) < 0)) {
713                         command_print(CMD, "stmqspi: sector size must be 2^n and <= device size");
714                         return ERROR_COMMAND_SYNTAX_ERROR;
715                 }
716
717                 if (index < CMD_ARGC)
718                         COMMAND_PARSE_NUMBER(u8, CMD_ARGV[index++], stmqspi_info->dev.erase_cmd);
719                 else
720                         return ERROR_COMMAND_SYNTAX_ERROR;
721         } else {
722                 /* no sector size / sector erase cmd given, treat whole bank as a single sector */
723                 stmqspi_info->dev.erase_cmd = 0x00;
724                 stmqspi_info->dev.sectorsize = stmqspi_info->dev.size_in_bytes;
725         }
726
727         /* set correct size value */
728         bank->size = stmqspi_info->dev.size_in_bytes << dual;
729
730         io_base = stmqspi_info->io_base;
731
732         uint32_t dcr;
733         retval = target_read_u32(target, io_base + SPI_DCR, &dcr);
734
735         if (retval != ERROR_OK)
736                 return retval;
737
738         fsize = (dcr >> SPI_FSIZE_POS) & (BIT(SPI_FSIZE_LEN) - 1);
739
740         LOG_DEBUG("FSIZE = 0x%04x", fsize);
741         if (bank->size == BIT(fsize + 1))
742                 LOG_DEBUG("FSIZE in DCR(1) matches actual capacity. Beware of silicon bug in H7, L4+, MP1.");
743         else if (bank->size == BIT(fsize + 0))
744                 LOG_DEBUG("FSIZE in DCR(1) is off by one regarding actual capacity. Fix for silicon bug?");
745         else
746                 LOG_ERROR("FSIZE in DCR(1) doesn't match actual capacity.");
747
748         /* create and fill sectors array */
749         bank->num_sectors =
750                 stmqspi_info->dev.size_in_bytes / stmqspi_info->dev.sectorsize;
751         sectors = malloc(sizeof(struct flash_sector) * bank->num_sectors);
752         if (!sectors) {
753                 LOG_ERROR("not enough memory");
754                 return ERROR_FAIL;
755         }
756
757         for (unsigned int sector = 0; sector < bank->num_sectors; sector++) {
758                 sectors[sector].offset = sector * (stmqspi_info->dev.sectorsize << dual);
759                 sectors[sector].size = (stmqspi_info->dev.sectorsize << dual);
760                 sectors[sector].is_erased = -1;
761                 sectors[sector].is_protected = 0;
762         }
763
764         bank->sectors = sectors;
765         stmqspi_info->dev.name = stmqspi_info->devname;
766         if (stmqspi_info->dev.size_in_bytes / 4096)
767                 LOG_INFO("flash \'%s\' id = unknown\nchip size = %" PRIu32 "kbytes,"
768                         " bank size = %" PRIu32 "kbytes", stmqspi_info->dev.name,
769                         stmqspi_info->dev.size_in_bytes / 1024,
770                         (stmqspi_info->dev.size_in_bytes / 1024) << dual);
771         else
772                 LOG_INFO("flash \'%s\' id = unknown\nchip size = %" PRIu32 "bytes,"
773                         " bank size = %" PRIu32 "bytes", stmqspi_info->dev.name,
774                         stmqspi_info->dev.size_in_bytes,
775                         stmqspi_info->dev.size_in_bytes << dual);
776
777         stmqspi_info->probed = true;
778
779         return ERROR_OK;
780 }
781
782 COMMAND_HANDLER(stmqspi_handle_cmd)
783 {
784         struct target *target = NULL;
785         struct flash_bank *bank;
786         struct stmqspi_flash_bank *stmqspi_info = NULL;
787         uint32_t io_base, addr;
788         uint8_t num_write, num_read, cmd_byte, data;
789         unsigned int count;
790         const int max = 21;
791         char temp[4], output[(2 + max + 256) * 3 + 8];
792         int retval;
793
794         LOG_DEBUG("%s", __func__);
795
796         if (CMD_ARGC < 3)
797                 return ERROR_COMMAND_SYNTAX_ERROR;
798
799         num_write = CMD_ARGC - 2;
800         if (num_write > max) {
801                 LOG_ERROR("at most %d bytes may be sent", max);
802                 return ERROR_COMMAND_SYNTAX_ERROR;
803         }
804
805         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
806         if (retval != ERROR_OK)
807                 return retval;
808
809         target = bank->target;
810         stmqspi_info = bank->driver_priv;
811         io_base = stmqspi_info->io_base;
812
813         if (target->state != TARGET_HALTED) {
814                 LOG_ERROR("Target not halted");
815                 return ERROR_TARGET_NOT_HALTED;
816         }
817
818         COMMAND_PARSE_NUMBER(u8, CMD_ARGV[1], num_read);
819         COMMAND_PARSE_NUMBER(u8, CMD_ARGV[2], cmd_byte);
820
821         if (num_read == 0) {
822                 /* nothing to read, then one command byte and for dual flash
823                  * an *even* number of data bytes to follow */
824                 if (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) {
825                         if ((num_write & 1) == 0) {
826                                 LOG_ERROR("number of data bytes to write must be even in dual mode");
827                                 return ERROR_COMMAND_SYNTAX_ERROR;
828                         }
829                 }
830         } else {
831                 /* read mode, one command byte and up to four following address bytes */
832                 if (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) {
833                         if ((num_read & 1) != 0) {
834                                 LOG_ERROR("number of bytes to read must be even in dual mode");
835                                 return ERROR_COMMAND_SYNTAX_ERROR;
836                         }
837                 }
838                 if ((num_write < 1) || (num_write > 5)) {
839                         LOG_ERROR("one cmd and up to four addr bytes must be send when reading");
840                         return ERROR_COMMAND_SYNTAX_ERROR;
841                 }
842         }
843
844         /* Abort any previous operation */
845         retval = stmqspi_abort(bank);
846         if (retval != ERROR_OK)
847                 return retval;
848
849         /* Wait for busy to be cleared */
850         retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
851         if (retval != ERROR_OK)
852                 return retval;
853
854         /* send command byte */
855         snprintf(output, sizeof(output), "spi: %02x ", cmd_byte);
856         if (num_read == 0) {
857                 /* write, send cmd byte */
858                 retval = target_write_u32(target, io_base + SPI_DLR, ((uint32_t)num_write) - 2);
859                 if (retval != ERROR_OK)
860                         goto err;
861
862                 if (IS_OCTOSPI)
863                         retval = octospi_cmd(bank, OCTOSPI_WRITE_MODE,
864                                 (OCTOSPI_MODE_CCR & OCTOSPI_NO_ALTB & OCTOSPI_NO_ADDR &
865                                 ((num_write == 1) ? OCTOSPI_NO_DATA : ~0U)), cmd_byte);
866                 else
867                         retval = target_write_u32(target, io_base + QSPI_CCR,
868                                 (QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ALTB & QSPI_NO_ADDR &
869                                 ((num_write == 1) ? QSPI_NO_DATA : ~0U)) |
870                                 (QSPI_WRITE_MODE | cmd_byte));
871                 if (retval != ERROR_OK)
872                         goto err;
873
874                 /* send additional data bytes */
875                 for (count = 3; count < CMD_ARGC; count++) {
876                         COMMAND_PARSE_NUMBER(u8, CMD_ARGV[count], data);
877                         snprintf(temp, sizeof(temp), "%02" PRIx8 " ", data);
878                         retval = target_write_u8(target, io_base + SPI_DR, data);
879                         if (retval != ERROR_OK)
880                                 goto err;
881                         strncat(output, temp, sizeof(output) - strlen(output) - 1);
882                 }
883                 strncat(output, "-> ", sizeof(output) - strlen(output) - 1);
884         } else {
885                 /* read, pack additional bytes into address */
886                 addr = 0;
887                 for (count = 3; count < CMD_ARGC; count++) {
888                         COMMAND_PARSE_NUMBER(u8, CMD_ARGV[count], data);
889                         snprintf(temp, sizeof(temp), "%02" PRIx8 " ", data);
890                         addr = (addr << 8) | data;
891                         strncat(output, temp, sizeof(output) - strlen(output) - 1);
892                 }
893                 strncat(output, "-> ", sizeof(output) - strlen(output) - 1);
894
895                 /* send cmd byte, if ADMODE indicates no address, this already triggers command */
896                 retval = target_write_u32(target, io_base + SPI_DLR, ((uint32_t)num_read) - 1);
897                 if (retval != ERROR_OK)
898                         goto err;
899                 if (IS_OCTOSPI)
900                         retval = octospi_cmd(bank, OCTOSPI_READ_MODE,
901                                 (OCTOSPI_MODE_CCR & OCTOSPI_NO_DDTR & OCTOSPI_NO_ALTB & ~OCTOSPI_ADDR4 &
902                                         ((num_write == 1) ? OCTOSPI_NO_ADDR : ~0U)) |
903                                 (((num_write - 2) & 0x3U) << SPI_ADSIZE_POS), cmd_byte);
904                 else
905                         retval = target_write_u32(target, io_base + QSPI_CCR,
906                                 (QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ALTB & ~QSPI_ADDR4 &
907                                         ((num_write == 1) ? QSPI_NO_ADDR : ~0U)) |
908                                 ((QSPI_READ_MODE | (((num_write - 2) & 0x3U) << SPI_ADSIZE_POS) | cmd_byte)));
909                 if (retval != ERROR_OK)
910                         goto err;
911
912                 if (num_write > 1) {
913                         /* if ADMODE indicates address required, only the write to AR triggers command */
914                         retval = target_write_u32(target, io_base + SPI_AR, addr);
915                         if (retval != ERROR_OK)
916                                 goto err;
917                 }
918
919                 /* read response bytes */
920                 for ( ; num_read > 0; num_read--) {
921                         retval = target_read_u8(target, io_base + SPI_DR, &data);
922                         if (retval != ERROR_OK)
923                                 goto err;
924                         snprintf(temp, sizeof(temp), "%02" PRIx8 " ", data);
925                         strncat(output, temp, sizeof(output) - strlen(output) - 1);
926                 }
927         }
928         command_print(CMD, "%s", output);
929
930 err:
931         /* Switch to memory mapped mode before return to prompt */
932         set_mm_mode(bank);
933
934         return retval;
935 }
936
937 static int qspi_erase_sector(struct flash_bank *bank, unsigned int sector)
938 {
939         struct target *target = bank->target;
940         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
941         uint32_t io_base = stmqspi_info->io_base;
942         uint16_t status;
943         int retval;
944
945         retval = qspi_write_enable(bank);
946         if (retval != ERROR_OK)
947                 goto err;
948
949         /* Send Sector Erase command */
950         if (IS_OCTOSPI)
951                 retval = octospi_cmd(bank, OCTOSPI_WRITE_MODE, OCTOSPI_CCR_SECTOR_ERASE,
952                         stmqspi_info->dev.erase_cmd);
953         else
954                 retval = target_write_u32(target, io_base + QSPI_CCR, QSPI_CCR_SECTOR_ERASE);
955         if (retval != ERROR_OK)
956                 goto err;
957
958         /* Address is sector offset, this write initiates command transmission */
959         retval = target_write_u32(target, io_base + SPI_AR, bank->sectors[sector].offset);
960         if (retval != ERROR_OK)
961                 goto err;
962
963         /* Wait for transmit of command completed */
964         poll_busy(bank, SPI_CMD_TIMEOUT);
965         if (retval != ERROR_OK)
966                 goto err;
967
968         /* Read flash status register(s) */
969         retval = read_status_reg(bank, &status);
970         if (retval != ERROR_OK)
971                 goto err;
972
973         LOG_DEBUG("erase status regs: 0x%04" PRIx16, status);
974
975         /* Check for command in progress for flash 1 */
976         /* If BSY and WE are already cleared the erase did probably complete already */
977         if (((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH)))
978                 != BIT(SPI_FSEL_FLASH)) && ((status & SPIFLASH_BSY_BIT) == 0) &&
979                 ((status & SPIFLASH_WE_BIT) != 0)) {
980                 LOG_ERROR("Sector erase command not accepted by flash1. Status=0x%02x",
981                         status & 0xFFU);
982                 retval = ERROR_FLASH_OPERATION_FAILED;
983                 goto err;
984         }
985
986         /* Check for command in progress for flash 2 */
987         /* If BSY and WE are already cleared the erase did probably complete already */
988         status >>= 8;
989         if (((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH))) != 0) &&
990                 ((status & SPIFLASH_BSY_BIT) == 0) &&
991                 ((status & SPIFLASH_WE_BIT) != 0)) {
992                 LOG_ERROR("Sector erase command not accepted by flash2. Status=0x%02x",
993                         status & 0xFFU);
994                 retval = ERROR_FLASH_OPERATION_FAILED;
995                 goto err;
996         }
997
998         /* Erase takes a long time, so some sort of progress message is a good idea */
999         LOG_DEBUG("erasing sector %4u", sector);
1000
1001         /* Poll WIP for end of self timed Sector Erase cycle */
1002         retval = wait_till_ready(bank, SPI_MAX_TIMEOUT);
1003
1004 err:
1005         return retval;
1006 }
1007
1008 static int stmqspi_erase(struct flash_bank *bank, unsigned int first, unsigned int last)
1009 {
1010         struct target *target = bank->target;
1011         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
1012         unsigned int sector;
1013         int retval = ERROR_OK;
1014
1015         LOG_DEBUG("%s: from sector %u to sector %u", __func__, first, last);
1016
1017         if (target->state != TARGET_HALTED) {
1018                 LOG_ERROR("Target not halted");
1019                 return ERROR_TARGET_NOT_HALTED;
1020         }
1021
1022         if (!(stmqspi_info->probed)) {
1023                 LOG_ERROR("Flash bank not probed");
1024                 return ERROR_FLASH_BANK_NOT_PROBED;
1025         }
1026
1027         if (stmqspi_info->dev.erase_cmd == 0x00) {
1028                 LOG_ERROR("Sector erase not available for this device");
1029                 return ERROR_FLASH_OPER_UNSUPPORTED;
1030         }
1031
1032         if ((last < first) || (last >= bank->num_sectors)) {
1033                 LOG_ERROR("Flash sector invalid");
1034                 return ERROR_FLASH_SECTOR_INVALID;
1035         }
1036
1037         for (sector = first; sector <= last; sector++) {
1038                 if (bank->sectors[sector].is_protected) {
1039                         LOG_ERROR("Flash sector %u protected", sector);
1040                         return ERROR_FLASH_PROTECTED;
1041                 }
1042         }
1043
1044         for (sector = first; sector <= last; sector++) {
1045                 retval = qspi_erase_sector(bank, sector);
1046                 if (retval != ERROR_OK)
1047                         break;
1048                 alive_sleep(10);
1049                 keep_alive();
1050         }
1051
1052         if (retval != ERROR_OK)
1053                 LOG_ERROR("Flash sector_erase failed on sector %u", sector);
1054
1055         /* Switch to memory mapped mode before return to prompt */
1056         set_mm_mode(bank);
1057
1058         return retval;
1059 }
1060
1061 static int stmqspi_protect(struct flash_bank *bank, int set,
1062         unsigned int first, unsigned int last)
1063 {
1064         unsigned int sector;
1065
1066         for (sector = first; sector <= last; sector++)
1067                 bank->sectors[sector].is_protected = set;
1068
1069         if (set)
1070                 LOG_WARNING("setting soft protection only, not related to flash's hardware write protection");
1071
1072         return ERROR_OK;
1073 }
1074
1075 /* Check whether flash is blank */
1076 static int stmqspi_blank_check(struct flash_bank *bank)
1077 {
1078         struct target *target = bank->target;
1079         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
1080         struct duration bench;
1081         struct reg_param reg_params[2];
1082         struct armv7m_algorithm armv7m_info;
1083         struct working_area *algorithm;
1084         const uint8_t *code;
1085         struct sector_info erase_check_info;
1086         uint32_t codesize, maxsize, result, exit_point;
1087         unsigned int count, index, num_sectors, sector;
1088         int retval;
1089         const uint32_t erased = 0x00FF;
1090
1091         if (target->state != TARGET_HALTED) {
1092                 LOG_ERROR("Target not halted");
1093                 return ERROR_TARGET_NOT_HALTED;
1094         }
1095
1096         if (!(stmqspi_info->probed)) {
1097                 LOG_ERROR("Flash bank not probed");
1098                 return ERROR_FLASH_BANK_NOT_PROBED;
1099         }
1100
1101         /* Abort any previous operation */
1102         retval = stmqspi_abort(bank);
1103         if (retval != ERROR_OK)
1104                 return retval;
1105
1106         /* Wait for busy to be cleared */
1107         retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
1108         if (retval != ERROR_OK)
1109                 return retval;
1110
1111         /* see contrib/loaders/flash/stmqspi/stmqspi_erase_check.S for src */
1112         static const uint8_t stmqspi_erase_check_code[] = {
1113                 #include "../../../contrib/loaders/flash/stmqspi/stmqspi_erase_check.inc"
1114         };
1115
1116         /* see contrib/loaders/flash/stmqspi/stmoctospi_erase_check.S for src */
1117         static const uint8_t stmoctospi_erase_check_code[] = {
1118                 #include "../../../contrib/loaders/flash/stmqspi/stmoctospi_erase_check.inc"
1119         };
1120
1121         if (IS_OCTOSPI) {
1122                 code = stmoctospi_erase_check_code;
1123                 codesize = sizeof(stmoctospi_erase_check_code);
1124         } else {
1125                 code = stmqspi_erase_check_code;
1126                 codesize = sizeof(stmqspi_erase_check_code);
1127         }
1128
1129         /* This will overlay the last 4 words of stmqspi/stmoctospi_erase_check_code in target */
1130         /* for read use the saved settings (memory mapped mode) but indirect read mode */
1131         uint32_t ccr_buffer[][4] = {
1132                 /* cr  (not used for QSPI)                      *
1133                  * ccr (for both QSPI and OCTOSPI)      *
1134                  * tcr (not used for QSPI)                      *
1135                  * ir  (not used for QSPI)                      */
1136                 {
1137                         h_to_le_32(OCTOSPI_MODE | OCTOSPI_READ_MODE),
1138                         h_to_le_32(IS_OCTOSPI ? OCTOSPI_CCR_READ : QSPI_CCR_READ),
1139                         h_to_le_32(stmqspi_info->saved_tcr),
1140                         h_to_le_32(stmqspi_info->saved_ir),
1141                 },
1142         };
1143
1144         maxsize = target_get_working_area_avail(target);
1145         if (maxsize < codesize + sizeof(erase_check_info)) {
1146                 LOG_ERROR("Not enough working area, can't do QSPI blank check");
1147                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1148         }
1149
1150         num_sectors = (maxsize - codesize) / sizeof(erase_check_info);
1151         num_sectors = (bank->num_sectors < num_sectors) ? bank->num_sectors : num_sectors;
1152
1153         if (target_alloc_working_area_try(target,
1154                         codesize + num_sectors * sizeof(erase_check_info), &algorithm) != ERROR_OK) {
1155                 LOG_ERROR("allocating working area failed");
1156                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1157         };
1158
1159         /* prepare blank check code, excluding ccr_buffer */
1160         retval = target_write_buffer(target, algorithm->address,
1161                 codesize - sizeof(ccr_buffer), code);
1162         if (retval != ERROR_OK)
1163                 goto err;
1164
1165         /* prepare QSPI/OCTOSPI_CCR register values */
1166         retval = target_write_buffer(target, algorithm->address
1167                 + codesize - sizeof(ccr_buffer),
1168                 sizeof(ccr_buffer), (uint8_t *)ccr_buffer);
1169         if (retval != ERROR_OK)
1170                 goto err;
1171
1172         duration_start(&bench);
1173
1174         /* after breakpoint instruction (halfword), one nop (halfword) and
1175          * port_buffer till end of code */
1176         exit_point = algorithm->address + codesize - sizeof(uint32_t) - sizeof(ccr_buffer);
1177
1178         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);    /* sector count */
1179         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);    /* QSPI/OCTOSPI io_base */
1180
1181         sector = 0;
1182         while (sector < bank->num_sectors) {
1183                 /* at most num_sectors sectors to handle in one run */
1184                 count = bank->num_sectors - sector;
1185                 if (count > num_sectors)
1186                         count = num_sectors;
1187
1188                 for (index = 0; index < count; index++) {
1189                         erase_check_info.offset = h_to_le_32(bank->sectors[sector + index].offset);
1190                         erase_check_info.size = h_to_le_32(bank->sectors[sector + index].size);
1191                         erase_check_info.result = h_to_le_32(erased);
1192
1193                         retval = target_write_buffer(target, algorithm->address
1194                                 + codesize + index * sizeof(erase_check_info),
1195                                         sizeof(erase_check_info), (uint8_t *)&erase_check_info);
1196                         if (retval != ERROR_OK)
1197                                 goto err;
1198                 }
1199
1200                 buf_set_u32(reg_params[0].value, 0, 32, count);
1201                 buf_set_u32(reg_params[1].value, 0, 32, stmqspi_info->io_base);
1202
1203                 armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
1204                 armv7m_info.core_mode = ARM_MODE_THREAD;
1205
1206                 LOG_DEBUG("checking sectors %u to %u", sector, sector + count - 1);
1207                 /* check a block of sectors */
1208                 retval = target_run_algorithm(target,
1209                         0, NULL,
1210                         ARRAY_SIZE(reg_params), reg_params,
1211                         algorithm->address, exit_point,
1212                         count * ((bank->sectors[sector].size >> 6) + 1) + 1000,
1213                         &armv7m_info);
1214                 if (retval != ERROR_OK)
1215                         break;
1216
1217                 for (index = 0; index < count; index++) {
1218                         retval = target_read_buffer(target, algorithm->address
1219                                 + codesize + index * sizeof(erase_check_info),
1220                                         sizeof(erase_check_info), (uint8_t *)&erase_check_info);
1221                         if (retval != ERROR_OK)
1222                                 goto err;
1223
1224                         if ((erase_check_info.offset != h_to_le_32(bank->sectors[sector + index].offset)) ||
1225                                 (erase_check_info.size != 0)) {
1226                                 LOG_ERROR("corrupted blank check info");
1227                                 goto err;
1228                         }
1229
1230                         /* we need le_32_to_h, but that's the same as h_to_le_32 */
1231                         result = h_to_le_32(erase_check_info.result);
1232                         bank->sectors[sector + index].is_erased = ((result & 0xFF) == 0xFF);
1233                         LOG_DEBUG("Flash sector %u checked: 0x%04x", sector + index, result & 0xFFFFU);
1234                 }
1235                 keep_alive();
1236                 sector += count;
1237         }
1238
1239         destroy_reg_param(&reg_params[0]);
1240         destroy_reg_param(&reg_params[1]);
1241
1242         duration_measure(&bench);
1243         LOG_INFO("stmqspi blank checked in %fs (%0.3f KiB/s)", duration_elapsed(&bench),
1244                 duration_kbps(&bench, bank->size));
1245
1246 err:
1247         target_free_working_area(target, algorithm);
1248
1249         /* Switch to memory mapped mode before return to prompt */
1250         set_mm_mode(bank);
1251
1252         return retval;
1253 }
1254
1255 /* Verify checksum */
1256 static int qspi_verify(struct flash_bank *bank, uint8_t *buffer,
1257         uint32_t offset, uint32_t count)
1258 {
1259         struct target *target = bank->target;
1260         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
1261         struct reg_param reg_params[4];
1262         struct armv7m_algorithm armv7m_info;
1263         struct working_area *algorithm;
1264         const uint8_t *code;
1265         uint32_t pagesize, codesize, crc32, result, exit_point;
1266         int retval;
1267
1268         /* see contrib/loaders/flash/stmqspi/stmqspi_crc32.S for src */
1269         static const uint8_t stmqspi_crc32_code[] = {
1270                 #include "../../../contrib/loaders/flash/stmqspi/stmqspi_crc32.inc"
1271         };
1272
1273         /* see contrib/loaders/flash/stmqspi/stmoctospi_crc32.S for src */
1274         static const uint8_t stmoctospi_crc32_code[] = {
1275                 #include "../../../contrib/loaders/flash/stmqspi/stmoctospi_crc32.inc"
1276         };
1277
1278         if (IS_OCTOSPI) {
1279                 code = stmoctospi_crc32_code;
1280                 codesize = sizeof(stmoctospi_crc32_code);
1281         } else {
1282                 code = stmqspi_crc32_code;
1283                 codesize = sizeof(stmqspi_crc32_code);
1284         }
1285
1286         /* block size doesn't matter that much here */
1287         pagesize = stmqspi_info->dev.sectorsize;
1288         if (pagesize == 0)
1289                 pagesize = stmqspi_info->dev.pagesize;
1290         if (pagesize == 0)
1291                 pagesize = SPIFLASH_DEF_PAGESIZE;
1292
1293         /* adjust size according to dual flash mode */
1294         pagesize = (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? pagesize << 1 : pagesize;
1295
1296         /* This will overlay the last 4 words of stmqspi/stmoctospi_crc32_code in target */
1297         /* for read use the saved settings (memory mapped mode) but indirect read mode */
1298         uint32_t ccr_buffer[][4] = {
1299                 /* cr  (not used for QSPI)                      *
1300                  * ccr (for both QSPI and OCTOSPI)      *
1301                  * tcr (not used for QSPI)                      *
1302                  * ir  (not used for QSPI)                      */
1303                 {
1304                         h_to_le_32(OCTOSPI_MODE | OCTOSPI_READ_MODE),
1305                         h_to_le_32(IS_OCTOSPI ? OCTOSPI_CCR_READ : QSPI_CCR_READ),
1306                         h_to_le_32(stmqspi_info->saved_tcr),
1307                         h_to_le_32(stmqspi_info->saved_ir),
1308                 },
1309         };
1310
1311         if (target_alloc_working_area_try(target, codesize, &algorithm) != ERROR_OK) {
1312                 LOG_ERROR("Not enough working area, can't do QSPI verify");
1313                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1314         };
1315
1316         /* prepare verify code, excluding ccr_buffer */
1317         retval = target_write_buffer(target, algorithm->address,
1318                 codesize - sizeof(ccr_buffer), code);
1319         if (retval != ERROR_OK)
1320                 goto err;
1321
1322         /* prepare QSPI/OCTOSPI_CCR register values */
1323         retval = target_write_buffer(target, algorithm->address
1324                 + codesize - sizeof(ccr_buffer),
1325                 sizeof(ccr_buffer), (uint8_t *)ccr_buffer);
1326         if (retval != ERROR_OK)
1327                 goto err;
1328
1329         /* after breakpoint instruction (halfword), one nop (halfword) and
1330          * port_buffer till end of code */
1331         exit_point = algorithm->address + codesize - sizeof(uint32_t) - sizeof(ccr_buffer);
1332
1333         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT); /* count (in), crc32 (out) */
1334         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);    /* pagesize */
1335         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);    /* offset into flash address */
1336         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);    /* QSPI/OCTOSPI io_base */
1337
1338         buf_set_u32(reg_params[0].value, 0, 32, count);
1339         buf_set_u32(reg_params[1].value, 0, 32, pagesize);
1340         buf_set_u32(reg_params[2].value, 0, 32, offset);
1341         buf_set_u32(reg_params[3].value, 0, 32, stmqspi_info->io_base);
1342
1343
1344         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
1345         armv7m_info.core_mode = ARM_MODE_THREAD;
1346
1347         retval = target_run_algorithm(target,
1348                 0, NULL,
1349                 ARRAY_SIZE(reg_params), reg_params,
1350                 algorithm->address, exit_point,
1351                 (count >> 5) + 1000,
1352                 &armv7m_info);
1353         keep_alive();
1354
1355         image_calculate_checksum(buffer, count, &crc32);
1356
1357         if (retval == ERROR_OK) {
1358                 result = buf_get_u32(reg_params[0].value, 0, 32);
1359                 LOG_DEBUG("addr " TARGET_ADDR_FMT ", len 0x%08" PRIx32 ", crc 0x%08" PRIx32 " 0x%08" PRIx32,
1360                         offset + bank->base, count, ~crc32, result);
1361                 if (~crc32 != result)
1362                         retval = ERROR_FAIL;
1363         }
1364
1365         destroy_reg_param(&reg_params[0]);
1366         destroy_reg_param(&reg_params[1]);
1367         destroy_reg_param(&reg_params[2]);
1368         destroy_reg_param(&reg_params[3]);
1369
1370 err:
1371         target_free_working_area(target, algorithm);
1372
1373         /* Switch to memory mapped mode before return to prompt */
1374         set_mm_mode(bank);
1375
1376         return retval;
1377 }
1378
1379 static int qspi_read_write_block(struct flash_bank *bank, uint8_t *buffer,
1380         uint32_t offset, uint32_t count, bool write)
1381 {
1382         struct target *target = bank->target;
1383         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
1384         uint32_t io_base = stmqspi_info->io_base;
1385         struct reg_param reg_params[6];
1386         struct armv7m_algorithm armv7m_info;
1387         struct working_area *algorithm;
1388         uint32_t pagesize, fifo_start, fifosize, remaining;
1389         uint32_t maxsize, codesize, exit_point;
1390         const uint8_t *code = NULL;
1391         unsigned int dual;
1392         int retval;
1393
1394         LOG_DEBUG("%s: offset=0x%08" PRIx32 " len=0x%08" PRIx32,
1395                 __func__, offset, count);
1396
1397         dual = (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? 1 : 0;
1398
1399         /* see contrib/loaders/flash/stmqspi/stmqspi_read.S for src */
1400         static const uint8_t stmqspi_read_code[] = {
1401 #include "../../../contrib/loaders/flash/stmqspi/stmqspi_read.inc"
1402         };
1403
1404         /* see contrib/loaders/flash/stmqspi/stmoctospi_read.S for src */
1405         static const uint8_t stmoctospi_read_code[] = {
1406 #include "../../../contrib/loaders/flash/stmqspi/stmoctospi_read.inc"
1407         };
1408
1409         /* see contrib/loaders/flash/stmqspi/stmqspi_write.S for src */
1410         static const uint8_t stmqspi_write_code[] = {
1411 #include "../../../contrib/loaders/flash/stmqspi/stmqspi_write.inc"
1412         };
1413
1414         /* see contrib/loaders/flash/stmqspi/stmoctospi_write.S for src */
1415         static const uint8_t stmoctospi_write_code[] = {
1416 #include "../../../contrib/loaders/flash/stmqspi/stmoctospi_write.inc"
1417         };
1418
1419         /* This will overlay the last 12 words of stmqspi/stmoctospi_read/write_code in target */
1420         /* for read use the saved settings (memory mapped mode) but indirect read mode */
1421         uint32_t ccr_buffer[][4] = {
1422                 /* cr  (not used for QSPI)                      *
1423                  * ccr (for both QSPI and OCTOSPI)      *
1424                  * tcr (not used for QSPI)                      *
1425                  * ir  (not used for QSPI)                      */
1426                 {
1427                         h_to_le_32(OCTOSPI_MODE | OCTOSPI_READ_MODE),
1428                         h_to_le_32(IS_OCTOSPI ? OCTOSPI_CCR_READ_STATUS : QSPI_CCR_READ_STATUS),
1429                         h_to_le_32((stmqspi_info->saved_tcr & ~OCTOSPI_DCYC_MASK) |
1430                                                 (OPI_MODE ? (OPI_DUMMY << OCTOSPI_DCYC_POS) : 0)),
1431                         h_to_le_32(OPI_CMD(SPIFLASH_READ_STATUS)),
1432                 },
1433                 {
1434                         h_to_le_32(OCTOSPI_MODE | OCTOSPI_WRITE_MODE),
1435                         h_to_le_32(IS_OCTOSPI ? OCTOSPI_CCR_WRITE_ENABLE : QSPI_CCR_WRITE_ENABLE),
1436                         h_to_le_32(stmqspi_info->saved_tcr & ~OCTOSPI_DCYC_MASK),
1437                         h_to_le_32(OPI_CMD(SPIFLASH_WRITE_ENABLE)),
1438                 },
1439                 {
1440                         h_to_le_32(OCTOSPI_MODE | (write ? OCTOSPI_WRITE_MODE : OCTOSPI_READ_MODE)),
1441                         h_to_le_32(write ? (IS_OCTOSPI ? OCTOSPI_CCR_PAGE_PROG : QSPI_CCR_PAGE_PROG) :
1442                                 (IS_OCTOSPI ? OCTOSPI_CCR_READ : QSPI_CCR_READ)),
1443                         h_to_le_32(write ? (stmqspi_info->saved_tcr & ~OCTOSPI_DCYC_MASK) :
1444                                 stmqspi_info->saved_tcr),
1445                         h_to_le_32(write ? OPI_CMD(stmqspi_info->dev.pprog_cmd) : stmqspi_info->saved_ir),
1446                 },
1447         };
1448
1449         /* force reasonable defaults */
1450         fifosize = stmqspi_info->dev.sectorsize ?
1451                 stmqspi_info->dev.sectorsize : stmqspi_info->dev.size_in_bytes;
1452
1453         if (write) {
1454                 if (IS_OCTOSPI) {
1455                         code = stmoctospi_write_code;
1456                         codesize = sizeof(stmoctospi_write_code);
1457                 } else {
1458                         code = stmqspi_write_code;
1459                         codesize = sizeof(stmqspi_write_code);
1460                 }
1461         } else {
1462                 if (IS_OCTOSPI) {
1463                         code = stmoctospi_read_code;
1464                         codesize = sizeof(stmoctospi_read_code);
1465                 } else {
1466                         code = stmqspi_read_code;
1467                         codesize = sizeof(stmqspi_read_code);
1468                 }
1469         }
1470
1471         /* for write, pagesize must be taken into account */
1472         /* for read, the page size doesn't matter that much */
1473         pagesize = stmqspi_info->dev.pagesize;
1474         if (pagesize == 0)
1475                 pagesize = (fifosize <= SPIFLASH_DEF_PAGESIZE) ?
1476                         fifosize : SPIFLASH_DEF_PAGESIZE;
1477
1478         /* adjust sizes according to dual flash mode */
1479         pagesize <<= dual;
1480         fifosize <<= dual;
1481
1482         /* memory buffer, we assume sectorsize to be a power of 2 times pagesize */
1483         maxsize = target_get_working_area_avail(target);
1484         if (maxsize < codesize + 2 * sizeof(uint32_t) + pagesize) {
1485                 LOG_ERROR("not enough working area, can't do QSPI page reads/writes");
1486                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1487         }
1488
1489         /* fifo size at most sector size, and multiple of page size */
1490         maxsize -= (codesize + 2 * sizeof(uint32_t));
1491         fifosize = ((maxsize < fifosize) ? maxsize : fifosize) & ~(pagesize - 1);
1492
1493         if (target_alloc_working_area_try(target,
1494                 codesize + 2 * sizeof(uint32_t) + fifosize, &algorithm) != ERROR_OK) {
1495                 LOG_ERROR("allocating working area failed");
1496                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1497         };
1498
1499         /* prepare flash write code, excluding ccr_buffer */
1500         retval = target_write_buffer(target, algorithm->address,
1501                 codesize - sizeof(ccr_buffer), code);
1502         if (retval != ERROR_OK)
1503                 goto err;
1504
1505         /* prepare QSPI/OCTOSPI_CCR register values */
1506         retval = target_write_buffer(target, algorithm->address
1507                 + codesize - sizeof(ccr_buffer),
1508                 sizeof(ccr_buffer), (uint8_t *)ccr_buffer);
1509         if (retval != ERROR_OK)
1510                 goto err;
1511
1512         /* target buffer starts right after flash_write_code, i.e.
1513          * wp and rp are implicitly included in buffer!!! */
1514         fifo_start = algorithm->address + codesize + 2 * sizeof(uint32_t);
1515
1516         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT); /* count (in), status (out) */
1517         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);    /* pagesize */
1518         init_reg_param(&reg_params[2], "r2", 32, PARAM_IN_OUT); /* offset into flash address */
1519         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);    /* QSPI/OCTOSPI io_base */
1520         init_reg_param(&reg_params[4], "r8", 32, PARAM_OUT);    /* fifo start */
1521         init_reg_param(&reg_params[5], "r9", 32, PARAM_OUT);    /* fifo end + 1 */
1522
1523         buf_set_u32(reg_params[0].value, 0, 32, count);
1524         buf_set_u32(reg_params[1].value, 0, 32, pagesize);
1525         buf_set_u32(reg_params[2].value, 0, 32, offset);
1526         buf_set_u32(reg_params[3].value, 0, 32, io_base);
1527         buf_set_u32(reg_params[4].value, 0, 32, fifo_start);
1528         buf_set_u32(reg_params[5].value, 0, 32, fifo_start + fifosize);
1529
1530         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
1531         armv7m_info.core_mode = ARM_MODE_THREAD;
1532
1533         /* after breakpoint instruction (halfword), one nop (halfword) and
1534          * ccr_buffer follow till end of code */
1535         exit_point = algorithm->address + codesize
1536                 - (sizeof(ccr_buffer) + sizeof(uint32_t));
1537
1538         if (write) {
1539                 retval = target_run_flash_async_algorithm(target, buffer, count, 1,
1540                                 0, NULL,
1541                                 ARRAY_SIZE(reg_params), reg_params,
1542                                 algorithm->address + codesize,
1543                                 fifosize + 2 * sizeof(uint32_t),
1544                                 algorithm->address, exit_point,
1545                                 &armv7m_info);
1546         } else {
1547                 retval = target_run_read_async_algorithm(target, buffer, count, 1,
1548                                 0, NULL,
1549                                 ARRAY_SIZE(reg_params), reg_params,
1550                                 algorithm->address + codesize,
1551                                 fifosize + 2 * sizeof(uint32_t),
1552                                 algorithm->address, exit_point,
1553                                 &armv7m_info);
1554         }
1555
1556         remaining = buf_get_u32(reg_params[0].value, 0, 32);
1557         if ((retval == ERROR_OK) && remaining)
1558                 retval = ERROR_FLASH_OPERATION_FAILED;
1559
1560         if (retval != ERROR_OK) {
1561                 offset = buf_get_u32(reg_params[2].value, 0, 32);
1562                 LOG_ERROR("flash %s failed at address 0x%" PRIx32 ", remaining 0x%" PRIx32,
1563                         write ? "write" : "read", offset, remaining);
1564         }
1565
1566         destroy_reg_param(&reg_params[0]);
1567         destroy_reg_param(&reg_params[1]);
1568         destroy_reg_param(&reg_params[2]);
1569         destroy_reg_param(&reg_params[3]);
1570         destroy_reg_param(&reg_params[4]);
1571         destroy_reg_param(&reg_params[5]);
1572
1573 err:
1574         target_free_working_area(target, algorithm);
1575
1576         /* Switch to memory mapped mode before return to prompt */
1577         set_mm_mode(bank);
1578
1579         return retval;
1580 }
1581
1582 static int stmqspi_read(struct flash_bank *bank, uint8_t *buffer,
1583         uint32_t offset, uint32_t count)
1584 {
1585         struct target *target = bank->target;
1586         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
1587         int retval;
1588
1589         LOG_DEBUG("%s: offset=0x%08" PRIx32 " count=0x%08" PRIx32,
1590                 __func__, offset, count);
1591
1592         if (target->state != TARGET_HALTED) {
1593                 LOG_ERROR("Target not halted");
1594                 return ERROR_TARGET_NOT_HALTED;
1595         }
1596
1597         if (!(stmqspi_info->probed)) {
1598                 LOG_ERROR("Flash bank not probed");
1599                 return ERROR_FLASH_BANK_NOT_PROBED;
1600         }
1601
1602         if (offset + count > bank->size) {
1603                 LOG_WARNING("Read beyond end of flash. Extra data to be ignored.");
1604                 count = bank->size - offset;
1605         }
1606
1607         /* Abort any previous operation */
1608         retval = stmqspi_abort(bank);
1609         if (retval != ERROR_OK)
1610                 return retval;
1611
1612         /* Wait for busy to be cleared */
1613         retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
1614         if (retval != ERROR_OK)
1615                 return retval;
1616
1617         return qspi_read_write_block(bank, buffer, offset, count, false);
1618 }
1619
1620 static int stmqspi_write(struct flash_bank *bank, const uint8_t *buffer,
1621         uint32_t offset, uint32_t count)
1622 {
1623         struct target *target = bank->target;
1624         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
1625         unsigned int dual, sector;
1626         bool octal_dtr;
1627         int retval;
1628
1629         LOG_DEBUG("%s: offset=0x%08" PRIx32 " count=0x%08" PRIx32,
1630                 __func__, offset, count);
1631
1632         dual = (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? 1 : 0;
1633         octal_dtr = IS_OCTOSPI && (stmqspi_info->saved_ccr & BIT(OCTOSPI_DDTR));
1634
1635         if (target->state != TARGET_HALTED) {
1636                 LOG_ERROR("Target not halted");
1637                 return ERROR_TARGET_NOT_HALTED;
1638         }
1639
1640         if (!(stmqspi_info->probed)) {
1641                 LOG_ERROR("Flash bank not probed");
1642                 return ERROR_FLASH_BANK_NOT_PROBED;
1643         }
1644
1645         if (offset + count > bank->size) {
1646                 LOG_WARNING("Write beyond end of flash. Extra data discarded.");
1647                 count = bank->size - offset;
1648         }
1649
1650         /* Check sector protection */
1651         for (sector = 0; sector < bank->num_sectors; sector++) {
1652                 /* Start offset in or before this sector? */
1653                 /* End offset in or behind this sector? */
1654                 if ((offset < (bank->sectors[sector].offset + bank->sectors[sector].size)) &&
1655                         ((offset + count - 1) >= bank->sectors[sector].offset) &&
1656                         bank->sectors[sector].is_protected) {
1657                         LOG_ERROR("Flash sector %u protected", sector);
1658                         return ERROR_FLASH_PROTECTED;
1659                 }
1660         }
1661
1662         if ((dual || octal_dtr) && ((offset & 1) != 0 || (count & 1) != 0)) {
1663                 LOG_ERROR("In dual-QSPI and octal-DTR modes writes must be two byte aligned: "
1664                         "%s: address=0x%08" PRIx32 " len=0x%08" PRIx32, __func__, offset, count);
1665                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
1666         }
1667
1668         /* Abort any previous operation */
1669         retval = stmqspi_abort(bank);
1670         if (retval != ERROR_OK)
1671                 return retval;
1672
1673         /* Wait for busy to be cleared */
1674         retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
1675         if (retval != ERROR_OK)
1676                 return retval;
1677
1678         return qspi_read_write_block(bank, (uint8_t *)buffer, offset, count, true);
1679 }
1680
1681 static int stmqspi_verify(struct flash_bank *bank, const uint8_t *buffer,
1682         uint32_t offset, uint32_t count)
1683 {
1684         struct target *target = bank->target;
1685         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
1686         unsigned int dual;
1687         bool octal_dtr;
1688         int retval;
1689
1690         LOG_DEBUG("%s: offset=0x%08" PRIx32 " count=0x%08" PRIx32,
1691                 __func__, offset, count);
1692
1693         dual = (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? 1 : 0;
1694         octal_dtr = IS_OCTOSPI && (stmqspi_info->saved_ccr & BIT(OCTOSPI_DDTR));
1695
1696         if (target->state != TARGET_HALTED) {
1697                 LOG_ERROR("Target not halted");
1698                 return ERROR_TARGET_NOT_HALTED;
1699         }
1700
1701         if (!(stmqspi_info->probed)) {
1702                 LOG_ERROR("Flash bank not probed");
1703                 return ERROR_FLASH_BANK_NOT_PROBED;
1704         }
1705
1706         if (offset + count > bank->size) {
1707                 LOG_WARNING("Verify beyond end of flash. Extra data ignored.");
1708                 count = bank->size - offset;
1709         }
1710
1711         if ((dual || octal_dtr) && ((offset & 1) != 0 || (count & 1) != 0)) {
1712                 LOG_ERROR("In dual-QSPI and octal-DTR modes reads must be two byte aligned: "
1713                         "%s: address=0x%08" PRIx32 " len=0x%08" PRIx32, __func__, offset, count);
1714                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
1715         }
1716
1717         /* Abort any previous operation */
1718         retval = stmqspi_abort(bank);
1719         if (retval != ERROR_OK)
1720                 return retval;
1721
1722         /* Wait for busy to be cleared */
1723         retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
1724         if (retval != ERROR_OK)
1725                 return retval;
1726
1727         return qspi_verify(bank, (uint8_t *)buffer, offset, count);
1728 }
1729
1730 /* Find appropriate dummy setting, in particular octo mode */
1731 static int find_sfdp_dummy(struct flash_bank *bank, int len)
1732 {
1733         struct target *target = bank->target;
1734         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
1735         uint32_t io_base = stmqspi_info->io_base;
1736         uint8_t data;
1737         unsigned int dual, count;
1738         bool flash1 = !(stmqspi_info->saved_cr & BIT(SPI_FSEL_FLASH));
1739         int retval;
1740         const unsigned int max_bytes = 64;
1741
1742         dual = (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? 1 : 0;
1743
1744         LOG_DEBUG("%s: len=%d, dual=%u, flash1=%d",
1745                 __func__, len, dual, flash1);
1746
1747         /* Abort any previous operation */
1748         retval = target_write_u32(target, io_base + SPI_CR,
1749                 stmqspi_info->saved_cr | BIT(SPI_ABORT));
1750         if (retval != ERROR_OK)
1751                 goto err;
1752
1753         /* Wait for busy to be cleared */
1754         retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
1755         if (retval != ERROR_OK)
1756                 goto err;
1757
1758         /* Switch to saved_cr (had to be set accordingly before this call) */
1759         retval = target_write_u32(target, io_base + SPI_CR, stmqspi_info->saved_cr);
1760         if (retval != ERROR_OK)
1761                 goto err;
1762
1763         /* Read at most that many bytes */
1764         retval = target_write_u32(target, io_base + SPI_DLR, (max_bytes << dual) - 1);
1765         if (retval != ERROR_OK)
1766                 return retval;
1767
1768         /* Read SFDP block */
1769         if (IS_OCTOSPI)
1770                 retval = octospi_cmd(bank, OCTOSPI_READ_MODE,
1771                         OCTOSPI_CCR_READ_SFDP(len), SPIFLASH_READ_SFDP);
1772         else
1773                 retval = target_write_u32(target, io_base + QSPI_CCR, QSPI_CCR_READ_SFDP);
1774         if (retval != ERROR_OK)
1775                 goto err;
1776
1777         /* Read from start of sfdp block */
1778         retval = target_write_u32(target, io_base + SPI_AR, 0);
1779         if (retval != ERROR_OK)
1780                 goto err;
1781
1782         for (count = 0 ; count < max_bytes; count++) {
1783                 if ((dual != 0) && !flash1) {
1784                         /* discard even byte in dual flash-mode if flash2 */
1785                         retval = target_read_u8(target, io_base + SPI_DR, &data);
1786                         if (retval != ERROR_OK)
1787                                 goto err;
1788                 }
1789
1790                 retval = target_read_u8(target, io_base + SPI_DR, &data);
1791                 if (retval != ERROR_OK)
1792                         goto err;
1793
1794                 if (data == 0x53) {
1795                         LOG_DEBUG("start of SFDP header for flash%c after %u dummy bytes",
1796                                 flash1 ? '1' : '2', count);
1797                         if (flash1)
1798                                 stmqspi_info->sfdp_dummy1 = count;
1799                         else
1800                                 stmqspi_info->sfdp_dummy2 = count;
1801                         return ERROR_OK;
1802                 }
1803
1804                 if ((dual != 0) && flash1) {
1805                         /* discard odd byte in dual flash-mode if flash1 */
1806                         retval = target_read_u8(target, io_base + SPI_DR, &data);
1807                         if (retval != ERROR_OK)
1808                                 goto err;
1809                 }
1810         }
1811
1812         retval = ERROR_FAIL;
1813         LOG_DEBUG("no start of SFDP header even after %u dummy bytes", count);
1814
1815 err:
1816         /* Abort operation */
1817         retval = stmqspi_abort(bank);
1818
1819         return retval;
1820 }
1821
1822 /* Read SFDP parameter block */
1823 static int read_sfdp_block(struct flash_bank *bank, uint32_t addr,
1824         uint32_t words, uint32_t *buffer)
1825 {
1826         struct target *target = bank->target;
1827         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
1828         uint32_t io_base = stmqspi_info->io_base;
1829         bool flash1 = !(stmqspi_info->saved_cr & BIT(SPI_FSEL_FLASH));
1830         unsigned int dual, count, len, *dummy;
1831         int retval;
1832
1833         dual = (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? 1 : 0;
1834
1835         if (IS_OCTOSPI && (((stmqspi_info->saved_ccr >> SPI_DMODE_POS) & 0x7) > 3)) {
1836                 /* in OCTO mode 4-byte address and (yet) unknown number of dummy clocks */
1837                 len = 4;
1838
1839                 /* in octo mode, use sfdp_dummy1 only */
1840                 dummy = &stmqspi_info->sfdp_dummy1;
1841                 if (*dummy == 0) {
1842                         retval = find_sfdp_dummy(bank, len);
1843                         if (retval != ERROR_OK)
1844                                 return retval;
1845                 }
1846         } else {
1847                 /* in all other modes 3-byte-address and 8(?) dummy clocks */
1848                 len = 3;
1849
1850                 /* use sfdp_dummy1/2 according to currently selected flash */
1851                 dummy = (stmqspi_info->saved_cr & BIT(SPI_FSEL_FLASH)) ?
1852                         &stmqspi_info->sfdp_dummy2 : &stmqspi_info->sfdp_dummy1;
1853
1854                 /* according to SFDP standard, there should always be 8 dummy *CLOCKS*
1855                  * giving 1, 2 or 4 dummy *BYTES*, however, this is apparently not
1856                  * always implemented correctly, so determine the number of dummy bytes
1857                  * dynamically */
1858                 if (*dummy == 0) {
1859                         retval = find_sfdp_dummy(bank, len);
1860                         if (retval != ERROR_OK)
1861                                 return retval;
1862                 }
1863         }
1864
1865         LOG_DEBUG("%s: addr=0x%08" PRIx32 " words=0x%08" PRIx32 " dummy=%u",
1866                 __func__, addr, words, *dummy);
1867
1868         /* Abort any previous operation */
1869         retval = target_write_u32(target, io_base + SPI_CR,
1870                 stmqspi_info->saved_cr | BIT(SPI_ABORT));
1871         if (retval != ERROR_OK)
1872                 goto err;
1873
1874         /* Wait for busy to be cleared */
1875         retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
1876         if (retval != ERROR_OK)
1877                 goto err;
1878
1879         /* Switch to one flash only */
1880         retval = target_write_u32(target, io_base + SPI_CR, stmqspi_info->saved_cr);
1881         if (retval != ERROR_OK)
1882                 goto err;
1883
1884         /* Read that many words plus dummy bytes */
1885         retval = target_write_u32(target, io_base + SPI_DLR,
1886                 ((*dummy + words * sizeof(uint32_t)) << dual) - 1);
1887         if (retval != ERROR_OK)
1888                 goto err;
1889
1890         /* Read SFDP block */
1891         if (IS_OCTOSPI)
1892                 retval = octospi_cmd(bank, OCTOSPI_READ_MODE,
1893                         OCTOSPI_CCR_READ_SFDP(len), SPIFLASH_READ_SFDP);
1894         else
1895                 retval = target_write_u32(target, io_base + QSPI_CCR, QSPI_CCR_READ_SFDP);
1896         if (retval != ERROR_OK)
1897                 goto err;
1898
1899         retval = target_write_u32(target, io_base + SPI_AR, addr << dual);
1900         if (retval != ERROR_OK)
1901                 goto err;
1902
1903         /* dummy clocks */
1904         for (count = *dummy << dual; count > 0; --count) {
1905                 retval = target_read_u8(target, io_base + SPI_DR, (uint8_t *)buffer);
1906                 if (retval != ERROR_OK)
1907                         goto err;
1908         }
1909
1910         for ( ; words > 0; words--) {
1911                 if (dual != 0) {
1912                         uint32_t word1, word2;
1913
1914                         retval = target_read_u32(target, io_base + SPI_DR, &word1);
1915                         if (retval != ERROR_OK)
1916                                 goto err;
1917                         retval = target_read_u32(target, io_base + SPI_DR, &word2);
1918                         if (retval != ERROR_OK)
1919                                 goto err;
1920
1921                         if (!flash1) {
1922                                 /* shift odd numbered bytes into even numbered ones */
1923                                 word1 >>= 8;
1924                                 word2 >>= 8;
1925                         }
1926
1927                         /* pack even numbered bytes into one word */
1928                         *buffer = (word1 & 0xFFU) | ((word1 & 0xFF0000U) >> 8) |
1929                                 ((word2 & 0xFFU) << 16) | ((word2 & 0xFF0000U) << 8);
1930
1931
1932                 } else {
1933                         retval = target_read_u32(target, io_base + SPI_DR, buffer);
1934                         if (retval != ERROR_OK)
1935                                 goto err;
1936                 }
1937                 LOG_DEBUG("raw SFDP data 0x%08" PRIx32, *buffer);
1938
1939                 /* endian correction, sfdp data is always le uint32_t based */
1940                 *buffer = le_to_h_u32((uint8_t *)buffer);
1941                 buffer++;
1942         }
1943
1944 err:
1945         return retval;
1946 }
1947
1948 /* Return ID of flash device(s) */
1949 /* On exit, indirect mode is kept */
1950 static int read_flash_id(struct flash_bank *bank, uint32_t *id1, uint32_t *id2)
1951 {
1952         struct target *target = bank->target;
1953         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
1954         uint32_t io_base = stmqspi_info->io_base;
1955         uint8_t byte;
1956         unsigned int type, count, len1, len2;
1957         int retval = ERROR_OK;
1958
1959         /* invalidate both ids */
1960         *id1 = 0;
1961         *id2 = 0;
1962
1963         if (target->state != TARGET_HALTED) {
1964                 LOG_ERROR("Target not halted");
1965                 return ERROR_TARGET_NOT_HALTED;
1966         }
1967
1968         /* SPIFLASH_READ_MID causes device in octal mode to go berserk, so don't use in this case */
1969         for (type = (IS_OCTOSPI && OPI_MODE) ? 1 : 0; type < 2 ; type++) {
1970                 /* Abort any previous operation */
1971                 retval = stmqspi_abort(bank);
1972                 if (retval != ERROR_OK)
1973                         goto err;
1974
1975                 /* Poll WIP */
1976                 retval = wait_till_ready(bank, SPI_PROBE_TIMEOUT);
1977                 if (retval != ERROR_OK)
1978                         goto err;
1979
1980                 /* Wait for busy to be cleared */
1981                 retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
1982                 if (retval != ERROR_OK)
1983                         goto err;
1984
1985                 /* Read at most 16 bytes per chip */
1986                 count = 16;
1987                 retval = target_write_u32(target, io_base + SPI_DLR,
1988                         (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH) ? count * 2 : count) - 1);
1989                 if (retval != ERROR_OK)
1990                         goto err;
1991
1992                 /* Read id: one particular flash chip (N25Q128) switches back to SPI mode when receiving
1993                  * SPI_FLASH_READ_ID in QPI mode, hence try SPIFLASH_READ_MID first */
1994                 switch (type) {
1995                         case 0:
1996                                 if (IS_OCTOSPI)
1997                                         retval = octospi_cmd(bank, OCTOSPI_READ_MODE,
1998                                                 OCTOSPI_CCR_READ_MID, SPIFLASH_READ_MID);
1999                                 else
2000                                         retval = target_write_u32(target, io_base + QSPI_CCR, QSPI_CCR_READ_MID);
2001                                 break;
2002
2003                         case 1:
2004                                 if (IS_OCTOSPI)
2005                                         retval = octospi_cmd(bank, OCTOSPI_READ_MODE,
2006                                                 OCTOSPI_CCR_READ_ID, SPIFLASH_READ_ID);
2007                                 else
2008                                         retval = target_write_u32(target, io_base + QSPI_CCR, QSPI_CCR_READ_ID);
2009                                 break;
2010
2011                         default:
2012                                 return ERROR_FAIL;
2013                 }
2014
2015                 if (retval != ERROR_OK)
2016                         goto err;
2017
2018                 /* Dummy address 0, only required for 8-line mode */
2019                 if (IS_OCTOSPI && OPI_MODE) {
2020                         retval = target_write_u32(target, io_base + SPI_AR, 0);
2021                         if (retval != ERROR_OK)
2022                                 goto err;
2023                 }
2024
2025                 /* for debugging only */
2026                 uint32_t dummy;
2027                 (void)target_read_u32(target, io_base + SPI_SR, &dummy);
2028
2029                 /* Read ID from Data Register */
2030                 for (len1 = 0, len2 = 0; count > 0; --count) {
2031                         if ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) |
2032                                 BIT(SPI_FSEL_FLASH))) != BIT(SPI_FSEL_FLASH)) {
2033                                 retval = target_read_u8(target, io_base + SPI_DR, &byte);
2034                                 if (retval != ERROR_OK)
2035                                         goto err;
2036                                 /* collect 3 bytes without continuation codes */
2037                                 if ((byte != 0x7F) && (len1 < 3)) {
2038                                         *id1 = (*id1 >> 8) | ((uint32_t)byte) << 16;
2039                                         len1++;
2040                                 }
2041                         }
2042                         if ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) |
2043                                 BIT(SPI_FSEL_FLASH))) != 0) {
2044                                 retval = target_read_u8(target, io_base + SPI_DR, &byte);
2045                                 if (retval != ERROR_OK)
2046                                         goto err;
2047                                 /* collect 3 bytes without continuation codes */
2048                                 if ((byte != 0x7F) && (len2 < 3)) {
2049                                         *id2 = (*id2 >> 8) | ((uint32_t)byte) << 16;
2050                                         len2++;
2051                                 }
2052                         }
2053                 }
2054
2055                 if (((*id1 != 0x000000) && (*id1 != 0xFFFFFF)) ||
2056                         ((*id2 != 0x000000) && (*id2 != 0xFFFFFF)))
2057                         break;
2058         }
2059
2060         if ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) |
2061                 BIT(SPI_FSEL_FLASH))) != BIT(SPI_FSEL_FLASH)) {
2062                 if ((*id1 == 0x000000) || (*id1 == 0xFFFFFF)) {
2063                         /* no id retrieved, so id must be set manually */
2064                         LOG_INFO("No id from flash1");
2065                         retval = ERROR_FLASH_BANK_NOT_PROBED;
2066                 }
2067         }
2068
2069         if ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH))) != 0) {
2070                 if ((*id2 == 0x000000) || (*id2 == 0xFFFFFF)) {
2071                         /* no id retrieved, so id must be set manually */
2072                         LOG_INFO("No id from flash2");
2073                         retval = ERROR_FLASH_BANK_NOT_PROBED;
2074                 }
2075         }
2076
2077 err:
2078         return retval;
2079 }
2080
2081 static int stmqspi_probe(struct flash_bank *bank)
2082 {
2083         struct target *target = bank->target;
2084         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
2085         struct flash_sector *sectors = NULL;
2086         uint32_t io_base = stmqspi_info->io_base;
2087         uint32_t id1 = 0, id2 = 0, data = 0;
2088         const struct flash_device *p;
2089         const uint32_t magic = 0xAEF1510E;
2090         unsigned int dual, fsize;
2091         bool octal_dtr;
2092         int retval;
2093
2094         if (stmqspi_info->probed) {
2095                 bank->size = 0;
2096                 bank->num_sectors = 0;
2097                 free(bank->sectors);
2098                 bank->sectors = NULL;
2099                 memset(&stmqspi_info->dev, 0, sizeof(stmqspi_info->dev));
2100                 stmqspi_info->sfdp_dummy1 = 0;
2101                 stmqspi_info->sfdp_dummy2 = 0;
2102                 stmqspi_info->probed = false;
2103         }
2104
2105         /* Abort any previous operation */
2106         retval = stmqspi_abort(bank);
2107         if (retval != ERROR_OK)
2108                 return retval;
2109
2110         /* Wait for busy to be cleared */
2111         retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
2112         if (retval != ERROR_OK)
2113                 return retval;
2114
2115         /* check whether QSPI_ABR is writeable and readback returns the value written */
2116         retval = target_write_u32(target, io_base + QSPI_ABR, magic);
2117         if (retval == ERROR_OK) {
2118                 retval = target_read_u32(target, io_base + QSPI_ABR, &data);
2119                 retval = target_write_u32(target, io_base + QSPI_ABR, 0);
2120         }
2121
2122         if (data == magic) {
2123                 LOG_DEBUG("QSPI_ABR register present");
2124                 stmqspi_info->octo = false;
2125         } else {
2126                 uint32_t magic_id;
2127
2128                 retval = target_read_u32(target, io_base + OCTOSPI_MAGIC, &magic_id);
2129
2130                 if (retval == ERROR_OK && magic_id == OCTO_MAGIC_ID) {
2131                         LOG_DEBUG("OCTOSPI_MAGIC present");
2132                         stmqspi_info->octo = true;
2133                 } else {
2134                         LOG_ERROR("No QSPI, no OCTOSPI at 0x%08" PRIx32, io_base);
2135                         stmqspi_info->probed = false;
2136                         stmqspi_info->dev.name = "none";
2137                         return ERROR_FAIL;
2138                 }
2139         }
2140
2141         /* save current FSEL and DFM bits in QSPI/OCTOSPI_CR, current QSPI/OCTOSPI_CCR value */
2142         retval = target_read_u32(target, io_base + SPI_CR, &stmqspi_info->saved_cr);
2143         if (retval == ERROR_OK)
2144                 retval = target_read_u32(target, io_base + SPI_CCR, &stmqspi_info->saved_ccr);
2145
2146         if (IS_OCTOSPI) {
2147                 uint32_t dcr1;
2148
2149                 retval = target_read_u32(target, io_base + OCTOSPI_DCR1, &dcr1);
2150
2151                 if (retval == ERROR_OK)
2152                         retval = target_read_u32(target, io_base + OCTOSPI_TCR,
2153                                 &stmqspi_info->saved_tcr);
2154
2155                 if (retval == ERROR_OK)
2156                         retval = target_read_u32(target, io_base + OCTOSPI_IR,
2157                                 &stmqspi_info->saved_ir);
2158
2159                 if (retval != ERROR_OK) {
2160                         LOG_ERROR("No OCTOSPI at io_base 0x%08" PRIx32, io_base);
2161                         stmqspi_info->probed = false;
2162                         stmqspi_info->dev.name = "none";
2163                         return ERROR_FAIL;
2164                 }
2165
2166                 const uint32_t mtyp = (dcr1 & OCTOSPI_MTYP_MASK) >> OCTOSPI_MTYP_POS;
2167
2168                 if ((mtyp != 0x0) && (mtyp != 0x1)) {
2169                         LOG_ERROR("Only regular SPI protocol supported in OCTOSPI");
2170                         stmqspi_info->probed = false;
2171                         stmqspi_info->dev.name = "none";
2172                         return ERROR_FAIL;
2173                 }
2174
2175                 LOG_DEBUG("OCTOSPI at 0x%08" PRIx64 ", io_base at 0x%08" PRIx32 ", OCTOSPI_CR 0x%08"
2176                         PRIx32 ", OCTOSPI_CCR 0x%08" PRIx32 ", %d-byte addr", bank->base, io_base,
2177                         stmqspi_info->saved_cr, stmqspi_info->saved_ccr, SPI_ADSIZE);
2178         } else {
2179                 if (retval == ERROR_OK) {
2180                         LOG_DEBUG("QSPI at 0x%08" PRIx64 ", io_base at 0x%08" PRIx32 ", QSPI_CR 0x%08"
2181                                 PRIx32 ", QSPI_CCR 0x%08" PRIx32 ", %d-byte addr", bank->base, io_base,
2182                                 stmqspi_info->saved_cr, stmqspi_info->saved_ccr, SPI_ADSIZE);
2183                                 if (stmqspi_info->saved_ccr & (1U << QSPI_DDRM))
2184                                         LOG_WARNING("DDR mode is untested and suffers from some silicon bugs");
2185                 } else {
2186                         LOG_ERROR("No QSPI at io_base 0x%08" PRIx32, io_base);
2187                         stmqspi_info->probed = false;
2188                         stmqspi_info->dev.name = "none";
2189                         return ERROR_FAIL;
2190                 }
2191         }
2192
2193         dual = (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? 1 : 0;
2194         octal_dtr = IS_OCTOSPI && (stmqspi_info->saved_ccr & BIT(OCTOSPI_DDTR));
2195         if (dual || octal_dtr)
2196                 bank->write_start_alignment = bank->write_end_alignment = 2;
2197         else
2198                 bank->write_start_alignment = bank->write_end_alignment = 1;
2199
2200         /* read and decode flash ID; returns in indirect mode */
2201         retval = read_flash_id(bank, &id1, &id2);
2202         LOG_DEBUG("id1 0x%06" PRIx32 ", id2 0x%06" PRIx32, id1, id2);
2203         if (retval == ERROR_FLASH_BANK_NOT_PROBED) {
2204                 /* no id retrieved, so id must be set manually */
2205                 LOG_INFO("No id - set flash parameters manually");
2206                 retval = ERROR_OK;
2207                 goto err;
2208         }
2209
2210         if (retval != ERROR_OK)
2211                 goto err;
2212
2213         /* identify flash1 */
2214         for (p = flash_devices; id1 && p->name ; p++) {
2215                 if (p->device_id == id1) {
2216                         memcpy(&stmqspi_info->dev, p, sizeof(stmqspi_info->dev));
2217                         if (p->size_in_bytes / 4096)
2218                                 LOG_INFO("flash1 \'%s\' id = 0x%06" PRIx32 " size = %" PRIu32
2219                                         "kbytes", p->name, id1, p->size_in_bytes / 1024);
2220                         else
2221                                 LOG_INFO("flash1 \'%s\' id = 0x%06" PRIx32 " size = %" PRIu32
2222                                         "bytes", p->name, id1, p->size_in_bytes);
2223                         break;
2224                 }
2225         }
2226
2227         if (id1 && !p->name) {
2228                 /* chip not been identified by id, then try SFDP */
2229                 struct flash_device temp;
2230                 uint32_t saved_cr = stmqspi_info->saved_cr;
2231
2232                 /* select flash1 */
2233                 stmqspi_info->saved_cr = stmqspi_info->saved_cr & ~BIT(SPI_FSEL_FLASH);
2234                 retval = spi_sfdp(bank, &temp, &read_sfdp_block);
2235
2236                 /* restore saved_cr */
2237                 stmqspi_info->saved_cr = saved_cr;
2238
2239                 if (retval == ERROR_OK) {
2240                         LOG_INFO("flash1 \'%s\' id = 0x%06" PRIx32 " size = %" PRIu32
2241                                 "kbytes", temp.name, id1, temp.size_in_bytes / 1024);
2242                         /* save info and retrieved *good* id as spi_sfdp clears all info */
2243                         memcpy(&stmqspi_info->dev, &temp, sizeof(stmqspi_info->dev));
2244                         stmqspi_info->dev.device_id = id1;
2245                 } else {
2246                         /* even not identified by SFDP, then give up */
2247                         LOG_WARNING("Unknown flash1 device id = 0x%06" PRIx32
2248                                 " - set flash parameters manually", id1);
2249                         retval = ERROR_OK;
2250                         goto err;
2251                 }
2252         }
2253
2254         /* identify flash2 */
2255         for (p = flash_devices; id2 && p->name ; p++) {
2256                 if (p->device_id == id2) {
2257                         if (p->size_in_bytes / 4096)
2258                                 LOG_INFO("flash2 \'%s\' id = 0x%06" PRIx32 " size = %" PRIu32
2259                                         "kbytes", p->name, id2, p->size_in_bytes / 1024);
2260                         else
2261                                 LOG_INFO("flash2 \'%s\' id = 0x%06" PRIx32 " size = %" PRIu32
2262                                         "bytes", p->name, id2, p->size_in_bytes);
2263
2264                         if (!id1)
2265                                 memcpy(&stmqspi_info->dev, p, sizeof(stmqspi_info->dev));
2266                         else {
2267                                 if ((stmqspi_info->dev.read_cmd != p->read_cmd) ||
2268                                         (stmqspi_info->dev.qread_cmd != p->qread_cmd) ||
2269                                         (stmqspi_info->dev.pprog_cmd != p->pprog_cmd) ||
2270                                         (stmqspi_info->dev.erase_cmd != p->erase_cmd) ||
2271                                         (stmqspi_info->dev.chip_erase_cmd != p->chip_erase_cmd) ||
2272                                         (stmqspi_info->dev.sectorsize != p->sectorsize) ||
2273                                         (stmqspi_info->dev.size_in_bytes != p->size_in_bytes)) {
2274                                         LOG_ERROR("Incompatible flash1/flash2 devices");
2275                                         goto err;
2276                                 }
2277                                 /* page size is optional in SFDP, so accept smallest value */
2278                                 if (p->pagesize < stmqspi_info->dev.pagesize)
2279                                         stmqspi_info->dev.pagesize = p->pagesize;
2280                         }
2281                         break;
2282                 }
2283         }
2284
2285         if (id2 && !p->name) {
2286                 /* chip not been identified by id, then try SFDP */
2287                 struct flash_device temp;
2288                 uint32_t saved_cr = stmqspi_info->saved_cr;
2289
2290                 /* select flash2 */
2291                 stmqspi_info->saved_cr = stmqspi_info->saved_cr | BIT(SPI_FSEL_FLASH);
2292                 retval = spi_sfdp(bank, &temp, &read_sfdp_block);
2293
2294                 /* restore saved_cr */
2295                 stmqspi_info->saved_cr = saved_cr;
2296
2297                 if (retval == ERROR_OK)
2298                         LOG_INFO("flash2 \'%s\' id = 0x%06" PRIx32 " size = %" PRIu32
2299                                 "kbytes", temp.name, id2, temp.size_in_bytes / 1024);
2300                 else {
2301                         /* even not identified by SFDP, then give up */
2302                         LOG_WARNING("Unknown flash2 device id = 0x%06" PRIx32
2303                                 " - set flash parameters manually", id2);
2304                         retval = ERROR_OK;
2305                         goto err;
2306                 }
2307
2308                 if (!id1)
2309                         memcpy(&stmqspi_info->dev, &temp, sizeof(stmqspi_info->dev));
2310                 else {
2311                         if ((stmqspi_info->dev.read_cmd != temp.read_cmd) ||
2312                                 (stmqspi_info->dev.qread_cmd != temp.qread_cmd) ||
2313                                 (stmqspi_info->dev.pprog_cmd != temp.pprog_cmd) ||
2314                                 (stmqspi_info->dev.erase_cmd != temp.erase_cmd) ||
2315                                 (stmqspi_info->dev.chip_erase_cmd != temp.chip_erase_cmd) ||
2316                                 (stmqspi_info->dev.sectorsize != temp.sectorsize) ||
2317                                 (stmqspi_info->dev.size_in_bytes != temp.size_in_bytes)) {
2318                                 LOG_ERROR("Incompatible flash1/flash2 devices");
2319                                 goto err;
2320                         }
2321                         /* page size is optional in SFDP, so accept smallest value */
2322                         if (temp.pagesize < stmqspi_info->dev.pagesize)
2323                                 stmqspi_info->dev.pagesize = temp.pagesize;
2324                 }
2325         }
2326
2327         /* Set correct size value */
2328         bank->size = stmqspi_info->dev.size_in_bytes << dual;
2329
2330         uint32_t dcr;
2331         retval = target_read_u32(target, io_base + SPI_DCR, &dcr);
2332
2333         if (retval != ERROR_OK)
2334                 goto err;
2335
2336         fsize = (dcr >> SPI_FSIZE_POS) & (BIT(SPI_FSIZE_LEN) - 1);
2337
2338         LOG_DEBUG("FSIZE = 0x%04x", fsize);
2339         if (bank->size == BIT((fsize + 1)))
2340                 LOG_DEBUG("FSIZE in DCR(1) matches actual capacity. Beware of silicon bug in H7, L4+, MP1.");
2341         else if (bank->size == BIT((fsize + 0)))
2342                 LOG_DEBUG("FSIZE in DCR(1) is off by one regarding actual capacity. Fix for silicon bug?");
2343         else
2344                 LOG_ERROR("FSIZE in DCR(1) doesn't match actual capacity.");
2345
2346         /* if no sectors, then treat whole flash as single sector */
2347         if (stmqspi_info->dev.sectorsize == 0)
2348                 stmqspi_info->dev.sectorsize = stmqspi_info->dev.size_in_bytes;
2349         /* if no page_size, then use sectorsize as page_size */
2350         if (stmqspi_info->dev.pagesize == 0)
2351                 stmqspi_info->dev.pagesize = stmqspi_info->dev.sectorsize;
2352
2353         /* create and fill sectors array */
2354         bank->num_sectors = stmqspi_info->dev.size_in_bytes / stmqspi_info->dev.sectorsize;
2355         sectors = malloc(sizeof(struct flash_sector) * bank->num_sectors);
2356         if (!sectors) {
2357                 LOG_ERROR("not enough memory");
2358                 retval = ERROR_FAIL;
2359                 goto err;
2360         }
2361
2362         for (unsigned int sector = 0; sector < bank->num_sectors; sector++) {
2363                 sectors[sector].offset = sector * (stmqspi_info->dev.sectorsize << dual);
2364                 sectors[sector].size = (stmqspi_info->dev.sectorsize << dual);
2365                 sectors[sector].is_erased = -1;
2366                 sectors[sector].is_protected = 0;
2367         }
2368
2369         bank->sectors = sectors;
2370         stmqspi_info->probed = true;
2371
2372 err:
2373         /* Switch to memory mapped mode before return to prompt */
2374         set_mm_mode(bank);
2375
2376         return retval;
2377 }
2378
2379 static int stmqspi_auto_probe(struct flash_bank *bank)
2380 {
2381         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
2382
2383         if (stmqspi_info->probed)
2384                 return ERROR_OK;
2385         stmqspi_probe(bank);
2386         return ERROR_OK;
2387 }
2388
2389 static int stmqspi_protect_check(struct flash_bank *bank)
2390 {
2391         /* Nothing to do. Protection is only handled in SW. */
2392         return ERROR_OK;
2393 }
2394
2395 static int get_stmqspi_info(struct flash_bank *bank, struct command_invocation *cmd)
2396 {
2397         struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
2398
2399         if (!(stmqspi_info->probed)) {
2400                 command_print_sameline(cmd, "\nQSPI flash bank not probed yet\n");
2401                 return ERROR_FLASH_BANK_NOT_PROBED;
2402         }
2403
2404         command_print_sameline(cmd, "flash%s%s \'%s\', device id = 0x%06" PRIx32
2405                         ", flash size = %" PRIu32 "%sbytes\n(page size = %" PRIu32
2406                         ", read = 0x%02" PRIx8 ", qread = 0x%02" PRIx8
2407                         ", pprog = 0x%02" PRIx8 ", mass_erase = 0x%02" PRIx8
2408                         ", sector size = %" PRIu32 "%sbytes, sector_erase = 0x%02" PRIx8 ")",
2409                         ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) |
2410                         BIT(SPI_FSEL_FLASH))) != BIT(SPI_FSEL_FLASH)) ? "1" : "",
2411                         ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) |
2412                         BIT(SPI_FSEL_FLASH))) != 0) ? "2" : "",
2413                         stmqspi_info->dev.name, stmqspi_info->dev.device_id,
2414                         bank->size / 4096 ? bank->size / 1024 : bank->size,
2415                         bank->size / 4096 ? "k" : "", stmqspi_info->dev.pagesize,
2416                         stmqspi_info->dev.read_cmd, stmqspi_info->dev.qread_cmd,
2417                         stmqspi_info->dev.pprog_cmd, stmqspi_info->dev.chip_erase_cmd,
2418                         stmqspi_info->dev.sectorsize / 4096 ?
2419                                 stmqspi_info->dev.sectorsize / 1024 : stmqspi_info->dev.sectorsize,
2420                         stmqspi_info->dev.sectorsize / 4096 ? "k" : "",
2421                         stmqspi_info->dev.erase_cmd);
2422
2423         return ERROR_OK;
2424 }
2425
2426 static const struct command_registration stmqspi_exec_command_handlers[] = {
2427         {
2428                 .name = "mass_erase",
2429                 .handler = stmqspi_handle_mass_erase_command,
2430                 .mode = COMMAND_EXEC,
2431                 .usage = "bank_id",
2432                 .help = "Mass erase entire flash device.",
2433         },
2434         {
2435                 .name = "set",
2436                 .handler = stmqspi_handle_set,
2437                 .mode = COMMAND_EXEC,
2438                 .usage = "bank_id name chip_size page_size read_cmd qread_cmd pprg_cmd "
2439                         "[ mass_erase_cmd ] [ sector_size sector_erase_cmd ]",
2440                 .help = "Set params of single flash chip",
2441         },
2442         {
2443                 .name = "cmd",
2444                 .handler = stmqspi_handle_cmd,
2445                 .mode = COMMAND_EXEC,
2446                 .usage = "bank_id num_resp cmd_byte ...",
2447                 .help = "Send low-level command cmd_byte and following bytes or read num_resp.",
2448         },
2449         COMMAND_REGISTRATION_DONE
2450 };
2451
2452 static const struct command_registration stmqspi_command_handlers[] = {
2453         {
2454                 .name = "stmqspi",
2455                 .mode = COMMAND_ANY,
2456                 .help = "stmqspi flash command group",
2457                 .usage = "",
2458                 .chain = stmqspi_exec_command_handlers,
2459         },
2460         COMMAND_REGISTRATION_DONE
2461 };
2462
2463 struct flash_driver stmqspi_flash = {
2464         .name = "stmqspi",
2465         .commands = stmqspi_command_handlers,
2466         .flash_bank_command = stmqspi_flash_bank_command,
2467         .erase = stmqspi_erase,
2468         .protect = stmqspi_protect,
2469         .write = stmqspi_write,
2470         .read = stmqspi_read,
2471         .verify = stmqspi_verify,
2472         .probe = stmqspi_probe,
2473         .auto_probe = stmqspi_auto_probe,
2474         .erase_check = stmqspi_blank_check,
2475         .protect_check = stmqspi_protect_check,
2476         .info = get_stmqspi_info,
2477         .free_driver_priv = default_flash_free_driver_priv,
2478 };