862e43aae4348a7f4e15966781805553250479a7
[fw/openocd] / src / flash / nor / sh_qspi.c
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * SH QSPI (Quad SPI) driver
4  * Copyright (C) 2019 Marek Vasut <marek.vasut@gmail.com>
5  *
6  * Based on U-Boot SH QSPI driver
7  * Copyright (C) 2013 Renesas Electronics Corporation
8  * Copyright (C) 2013 Nobuhiro Iwamatsu <nobuhiro.iwamatsu.yj@renesas.com>
9  */
10
11 #ifdef HAVE_CONFIG_H
12 #include "config.h"
13 #endif
14
15 #include "imp.h"
16 #include "spi.h"
17 #include <helper/binarybuffer.h>
18 #include <helper/bits.h>
19 #include <helper/time_support.h>
20 #include <helper/types.h>
21 #include <jtag/jtag.h>
22 #include <target/algorithm.h>
23 #include <target/arm.h>
24 #include <target/arm_opcodes.h>
25 #include <target/target.h>
26
27 /* SH QSPI register bit masks <REG>_<BIT> */
28 #define SPCR_MSTR       0x08
29 #define SPCR_SPE        0x40
30 #define SPSR_SPRFF      0x80
31 #define SPSR_SPTEF      0x20
32 #define SPPCR_IO3FV     0x04
33 #define SPPCR_IO2FV     0x02
34 #define SPPCR_IO1FV     0x01
35 #define SPBDCR_RXBC0    BIT(0)
36 #define SPCMD_SCKDEN    BIT(15)
37 #define SPCMD_SLNDEN    BIT(14)
38 #define SPCMD_SPNDEN    BIT(13)
39 #define SPCMD_SSLKP     BIT(7)
40 #define SPCMD_BRDV0     BIT(2)
41 #define SPCMD_INIT1     (SPCMD_SCKDEN | SPCMD_SLNDEN | \
42                         SPCMD_SPNDEN | SPCMD_SSLKP | \
43                         SPCMD_BRDV0)
44 #define SPCMD_INIT2     (SPCMD_SPNDEN | SPCMD_SSLKP | \
45                         SPCMD_BRDV0)
46 #define SPBFCR_TXRST    BIT(7)
47 #define SPBFCR_RXRST    BIT(6)
48 #define SPBFCR_TXTRG    0x30
49 #define SPBFCR_RXTRG    0x07
50
51 /* SH QSPI register set */
52 #define SH_QSPI_SPCR            0x00
53 #define SH_QSPI_SSLP            0x01
54 #define SH_QSPI_SPPCR           0x02
55 #define SH_QSPI_SPSR            0x03
56 #define SH_QSPI_SPDR            0x04
57 #define SH_QSPI_SPSCR           0x08
58 #define SH_QSPI_SPSSR           0x09
59 #define SH_QSPI_SPBR            0x0a
60 #define SH_QSPI_SPDCR           0x0b
61 #define SH_QSPI_SPCKD           0x0c
62 #define SH_QSPI_SSLND           0x0d
63 #define SH_QSPI_SPND            0x0e
64 #define SH_QSPI_DUMMY0          0x0f
65 #define SH_QSPI_SPCMD0          0x10
66 #define SH_QSPI_SPCMD1          0x12
67 #define SH_QSPI_SPCMD2          0x14
68 #define SH_QSPI_SPCMD3          0x16
69 #define SH_QSPI_SPBFCR          0x18
70 #define SH_QSPI_DUMMY1          0x19
71 #define SH_QSPI_SPBDCR          0x1a
72 #define SH_QSPI_SPBMUL0         0x1c
73 #define SH_QSPI_SPBMUL1         0x20
74 #define SH_QSPI_SPBMUL2         0x24
75 #define SH_QSPI_SPBMUL3         0x28
76
77 struct sh_qspi_flash_bank {
78         const struct flash_device *dev;
79         uint32_t                io_base;
80         int                     probed;
81         struct working_area     *io_algorithm;
82         struct working_area     *source;
83         unsigned int            buffer_size;
84 };
85
86 struct sh_qspi_target {
87         char            *name;
88         uint32_t        tap_idcode;
89         uint32_t        io_base;
90 };
91
92 static const struct sh_qspi_target target_devices[] = {
93         /* name,        tap_idcode,     io_base */
94         { "SH QSPI",    0x4ba00477,     0xe6b10000 },
95         { NULL,         0,              0 }
96 };
97
98 static int sh_qspi_init(struct flash_bank *bank)
99 {
100         struct target *target = bank->target;
101         struct sh_qspi_flash_bank *info = bank->driver_priv;
102         uint8_t val;
103         int ret;
104
105         /* QSPI initialize */
106         /* Set master mode only */
107         ret = target_write_u8(target, info->io_base + SH_QSPI_SPCR, SPCR_MSTR);
108         if (ret != ERROR_OK)
109                 return ret;
110
111         /* Set SSL signal level */
112         ret = target_write_u8(target, info->io_base + SH_QSPI_SSLP, 0x00);
113         if (ret != ERROR_OK)
114                 return ret;
115
116         /* Set MOSI signal value when transfer is in idle state */
117         ret = target_write_u8(target, info->io_base + SH_QSPI_SPPCR,
118                               SPPCR_IO3FV | SPPCR_IO2FV);
119         if (ret != ERROR_OK)
120                 return ret;
121
122         /* Set bit rate. See 58.3.8 Quad Serial Peripheral Interface */
123         ret = target_write_u8(target, info->io_base + SH_QSPI_SPBR, 0x01);
124         if (ret != ERROR_OK)
125                 return ret;
126
127         /* Disable Dummy Data Transmission */
128         ret = target_write_u8(target, info->io_base + SH_QSPI_SPDCR, 0x00);
129         if (ret != ERROR_OK)
130                 return ret;
131
132         /* Set clock delay value */
133         ret = target_write_u8(target, info->io_base + SH_QSPI_SPCKD, 0x00);
134         if (ret != ERROR_OK)
135                 return ret;
136
137         /* Set SSL negation delay value */
138         ret = target_write_u8(target, info->io_base + SH_QSPI_SSLND, 0x00);
139         if (ret != ERROR_OK)
140                 return ret;
141
142         /* Set next-access delay value */
143         ret = target_write_u8(target, info->io_base + SH_QSPI_SPND, 0x00);
144         if (ret != ERROR_OK)
145                 return ret;
146
147         /* Set equence command */
148         ret = target_write_u16(target, info->io_base + SH_QSPI_SPCMD0,
149                                SPCMD_INIT2);
150         if (ret != ERROR_OK)
151                 return ret;
152
153         /* Reset transfer and receive Buffer */
154         ret = target_read_u8(target, info->io_base + SH_QSPI_SPBFCR, &val);
155         if (ret != ERROR_OK)
156                 return ret;
157
158         val |= SPBFCR_TXRST | SPBFCR_RXRST;
159
160         ret = target_write_u8(target, info->io_base + SH_QSPI_SPBFCR, val);
161         if (ret != ERROR_OK)
162                 return ret;
163
164         /* Clear transfer and receive Buffer control bit */
165         ret = target_read_u8(target, info->io_base + SH_QSPI_SPBFCR, &val);
166         if (ret != ERROR_OK)
167                 return ret;
168
169         val &= ~(SPBFCR_TXRST | SPBFCR_RXRST);
170
171         ret = target_write_u8(target, info->io_base + SH_QSPI_SPBFCR, val);
172         if (ret != ERROR_OK)
173                 return ret;
174
175         /* Set equence control method. Use equence0 only */
176         ret = target_write_u8(target, info->io_base + SH_QSPI_SPSCR, 0x00);
177         if (ret != ERROR_OK)
178                 return ret;
179
180         /* Enable SPI function */
181         ret = target_read_u8(target, info->io_base + SH_QSPI_SPCR, &val);
182         if (ret != ERROR_OK)
183                 return ret;
184
185         val |= SPCR_SPE;
186
187         return target_write_u8(target, info->io_base + SH_QSPI_SPCR, val);
188 }
189
190 static int sh_qspi_cs_activate(struct flash_bank *bank)
191 {
192         struct target *target = bank->target;
193         struct sh_qspi_flash_bank *info = bank->driver_priv;
194         uint8_t val;
195         int ret;
196
197         /* Set master mode only */
198         ret = target_write_u8(target, info->io_base + SH_QSPI_SPCR, SPCR_MSTR);
199         if (ret != ERROR_OK)
200                 return ret;
201
202         /* Set command */
203         ret = target_write_u16(target, info->io_base + SH_QSPI_SPCMD0,
204                                SPCMD_INIT1);
205         if (ret != ERROR_OK)
206                 return ret;
207
208         /* Reset transfer and receive Buffer */
209         ret = target_read_u8(target, info->io_base + SH_QSPI_SPBFCR, &val);
210         if (ret != ERROR_OK)
211                 return ret;
212
213         val |= SPBFCR_TXRST | SPBFCR_RXRST;
214
215         ret = target_write_u8(target, info->io_base + SH_QSPI_SPBFCR, val);
216         if (ret != ERROR_OK)
217                 return ret;
218
219         /* Clear transfer and receive Buffer control bit */
220         ret = target_read_u8(target, info->io_base + SH_QSPI_SPBFCR, &val);
221         if (ret != ERROR_OK)
222                 return ret;
223
224         val &= ~(SPBFCR_TXRST | SPBFCR_RXRST);
225
226         ret = target_write_u8(target, info->io_base + SH_QSPI_SPBFCR, val);
227         if (ret != ERROR_OK)
228                 return ret;
229
230         /* Set equence control method. Use equence0 only */
231         ret = target_write_u8(target, info->io_base + SH_QSPI_SPSCR, 0x00);
232         if (ret != ERROR_OK)
233                 return ret;
234
235         /* Enable SPI function */
236         ret = target_read_u8(target, info->io_base + SH_QSPI_SPCR, &val);
237         if (ret != ERROR_OK)
238                 return ret;
239
240         val |= SPCR_SPE;
241
242         return target_write_u8(target, info->io_base + SH_QSPI_SPCR, val);
243 }
244
245 static int sh_qspi_cs_deactivate(struct flash_bank *bank)
246 {
247         struct target *target = bank->target;
248         struct sh_qspi_flash_bank *info = bank->driver_priv;
249         uint8_t val;
250         int ret;
251
252         /* Disable SPI Function */
253         ret = target_read_u8(target, info->io_base + SH_QSPI_SPCR, &val);
254         if (ret != ERROR_OK)
255                 return ret;
256
257         val &= ~SPCR_SPE;
258
259         return target_write_u8(target, info->io_base + SH_QSPI_SPCR, val);
260 }
261
262 static int sh_qspi_wait_for_bit(struct flash_bank *bank, uint8_t reg,
263                                 uint32_t mask, bool set,
264                                 unsigned long timeout)
265 {
266         struct target *target = bank->target;
267         struct sh_qspi_flash_bank *info = bank->driver_priv;
268         long long endtime;
269         uint8_t val;
270         int ret;
271
272         endtime = timeval_ms() + timeout;
273         do {
274                 ret = target_read_u8(target, info->io_base + reg, &val);
275                 if (ret != ERROR_OK)
276                         return ret;
277
278                 if (!set)
279                         val = ~val;
280
281                 if ((val & mask) == mask)
282                         return ERROR_OK;
283
284                 alive_sleep(1);
285         } while (timeval_ms() < endtime);
286
287         LOG_ERROR("timeout");
288         return ERROR_TIMEOUT_REACHED;
289 }
290
291 static int sh_qspi_xfer_common(struct flash_bank *bank,
292                                const uint8_t *dout, unsigned int outlen,
293                                uint8_t *din, unsigned int inlen,
294                                bool xfer_start, bool xfer_end)
295 {
296         struct target *target = bank->target;
297         struct sh_qspi_flash_bank *info = bank->driver_priv;
298         uint8_t tdata, rdata;
299         uint8_t val;
300         unsigned int nbyte = outlen + inlen;
301         int ret = 0;
302
303         if (xfer_start) {
304                 ret = sh_qspi_cs_activate(bank);
305                 if (ret != ERROR_OK)
306                         return ret;
307
308                 ret = target_write_u32(target, info->io_base + SH_QSPI_SPBMUL0,
309                                        nbyte);
310                 if (ret != ERROR_OK)
311                         return ret;
312
313                 ret = target_read_u8(target, info->io_base + SH_QSPI_SPBFCR,
314                                      &val);
315                 if (ret != ERROR_OK)
316                         return ret;
317
318                 val &= ~(SPBFCR_TXTRG | SPBFCR_RXTRG);
319
320                 ret = target_write_u8(target, info->io_base + SH_QSPI_SPBFCR,
321                                       val);
322                 if (ret != ERROR_OK)
323                         return ret;
324         }
325
326         while (nbyte > 0) {
327                 ret = sh_qspi_wait_for_bit(bank, SH_QSPI_SPSR, SPSR_SPTEF,
328                                                 true, 1000);
329                 if (ret != ERROR_OK)
330                         return ret;
331
332                 tdata = outlen ? *dout++ : 0;
333                 ret = target_write_u8(target, info->io_base + SH_QSPI_SPDR,
334                                       tdata);
335                 if (ret != ERROR_OK)
336                         return ret;
337
338                 ret = sh_qspi_wait_for_bit(bank, SH_QSPI_SPSR, SPSR_SPRFF,
339                                                 true, 1000);
340                 if (ret != ERROR_OK)
341                         return ret;
342
343                 ret = target_read_u8(target, info->io_base + SH_QSPI_SPDR,
344                                      &rdata);
345                 if (ret != ERROR_OK)
346                         return ret;
347                 if (!outlen && inlen) {
348                         *din++ = rdata;
349                         inlen--;
350                 }
351
352                 if (outlen)
353                         outlen--;
354
355                 nbyte--;
356         }
357
358         if (xfer_end)
359                 return sh_qspi_cs_deactivate(bank);
360         else
361                 return ERROR_OK;
362 }
363
364 /* Send "write enable" command to SPI flash chip. */
365 static int sh_qspi_write_enable(struct flash_bank *bank)
366 {
367         uint8_t dout = SPIFLASH_WRITE_ENABLE;
368
369         return sh_qspi_xfer_common(bank, &dout, 1, NULL, 0, 1, 1);
370 }
371
372 /* Read the status register of the external SPI flash chip. */
373 static int read_status_reg(struct flash_bank *bank, uint32_t *status)
374 {
375         uint8_t dout = SPIFLASH_READ_STATUS;
376         uint8_t din;
377         int ret;
378
379         ret = sh_qspi_xfer_common(bank, &dout, 1, &din, 1, 1, 1);
380         if (ret != ERROR_OK)
381                 return ret;
382
383         *status = din & 0xff;
384
385         return ERROR_OK;
386 }
387
388 /* check for WIP (write in progress) bit in status register */
389 /* timeout in ms */
390 static int wait_till_ready(struct flash_bank *bank, int timeout)
391 {
392         long long endtime;
393         uint32_t status;
394         int ret;
395
396         endtime = timeval_ms() + timeout;
397         do {
398                 /* read flash status register */
399                 ret = read_status_reg(bank, &status);
400                 if (ret != ERROR_OK)
401                         return ret;
402
403                 if ((status & SPIFLASH_BSY_BIT) == 0)
404                         return ERROR_OK;
405                 alive_sleep(1);
406         } while (timeval_ms() < endtime);
407
408         LOG_ERROR("timeout");
409         return ERROR_TIMEOUT_REACHED;
410 }
411
412 static int sh_qspi_erase_sector(struct flash_bank *bank, int sector)
413 {
414         struct sh_qspi_flash_bank *info = bank->driver_priv;
415         bool addr4b = info->dev->size_in_bytes > (1UL << 24);
416         uint32_t address = (sector * info->dev->sectorsize) <<
417                            (addr4b ? 0 : 8);
418         uint8_t dout[5] = {
419                 info->dev->erase_cmd,
420                 (address >> 24) & 0xff, (address >> 16) & 0xff,
421                 (address >> 8) & 0xff, (address >> 0) & 0xff
422         };
423         unsigned int doutlen = addr4b ? 5 : 4;
424         int ret;
425
426         /* Write Enable */
427         ret = sh_qspi_write_enable(bank);
428         if (ret != ERROR_OK)
429                 return ret;
430
431         /* Erase */
432         ret = sh_qspi_xfer_common(bank, dout, doutlen, NULL, 0, 1, 1);
433         if (ret != ERROR_OK)
434                 return ret;
435
436         /* Poll status register */
437         return wait_till_ready(bank, 3000);
438 }
439
440 static int sh_qspi_erase(struct flash_bank *bank, int first, int last)
441 {
442         struct target *target = bank->target;
443         struct sh_qspi_flash_bank *info = bank->driver_priv;
444         int retval = ERROR_OK;
445         int sector;
446
447         LOG_DEBUG("%s: from sector %d to sector %d", __func__, first, last);
448
449         if (target->state != TARGET_HALTED) {
450                 LOG_ERROR("Target not halted");
451                 return ERROR_TARGET_NOT_HALTED;
452         }
453
454         if ((first < 0) || (last < first) || (last >= bank->num_sectors)) {
455                 LOG_ERROR("Flash sector invalid");
456                 return ERROR_FLASH_SECTOR_INVALID;
457         }
458
459         if (!info->probed) {
460                 LOG_ERROR("Flash bank not probed");
461                 return ERROR_FLASH_BANK_NOT_PROBED;
462         }
463
464         if (info->dev->erase_cmd == 0x00)
465                 return ERROR_FLASH_OPER_UNSUPPORTED;
466
467         for (sector = first; sector <= last; sector++) {
468                 if (bank->sectors[sector].is_protected) {
469                         LOG_ERROR("Flash sector %d protected", sector);
470                         return ERROR_FAIL;
471                 }
472         }
473
474         for (sector = first; sector <= last; sector++) {
475                 retval = sh_qspi_erase_sector(bank, sector);
476                 if (retval != ERROR_OK)
477                         break;
478                 keep_alive();
479         }
480
481         return retval;
482 }
483
484 static int sh_qspi_write(struct flash_bank *bank, const uint8_t *buffer,
485                        uint32_t offset, uint32_t count)
486 {
487         struct target *target = bank->target;
488         struct sh_qspi_flash_bank *info = bank->driver_priv;
489         struct reg_param reg_params[4];
490         struct arm_algorithm arm_algo;
491         uint32_t io_base = (uint32_t)(info->io_base);
492         uint32_t src_base = (uint32_t)(info->source->address);
493         uint32_t chunk;
494         bool addr4b = !!(info->dev->size_in_bytes > (1UL << 24));
495         int ret = ERROR_OK;
496         int sector;
497
498         LOG_DEBUG("%s: offset=0x%08" PRIx32 " count=0x%08" PRIx32,
499                   __func__, offset, count);
500
501         if (target->state != TARGET_HALTED) {
502                 LOG_ERROR("Target not halted");
503                 return ERROR_TARGET_NOT_HALTED;
504         }
505
506         if (offset + count > bank->size) {
507                 LOG_WARNING("Write pasts end of flash. Extra data discarded.");
508                 count = bank->size - offset;
509         }
510
511         if (offset & 0xff) {
512                 LOG_ERROR("sh_qspi_write_page: unaligned write address: %08x",
513                           offset);
514                 return ERROR_FAIL;
515         }
516
517         /* Check sector protection */
518         for (sector = 0; sector < bank->num_sectors; sector++) {
519                 /* Start offset in or before this sector? */
520                 /* End offset in or behind this sector? */
521                 struct flash_sector *bs = &bank->sectors[sector];
522
523                 if ((offset < (bs->offset + bs->size)) &&
524                     ((offset + count - 1) >= bs->offset) &&
525                     bs->is_protected) {
526                         LOG_ERROR("Flash sector %d protected", sector);
527                         return ERROR_FAIL;
528                 }
529         }
530
531         LOG_DEBUG("%s: offset=0x%08" PRIx32 " count=0x%08" PRIx32,
532                   __func__, offset, count);
533
534         if (target->state != TARGET_HALTED) {
535                 LOG_ERROR("Target not halted");
536                 return ERROR_TARGET_NOT_HALTED;
537         }
538
539         if (offset + count > bank->size) {
540                 LOG_WARNING("Reads past end of flash. Extra data discarded.");
541                 count = bank->size - offset;
542         }
543
544         arm_algo.common_magic = ARM_COMMON_MAGIC;
545         arm_algo.core_mode = ARM_MODE_SVC;
546         arm_algo.core_state = ARM_STATE_ARM;
547
548         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
549         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
550         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
551         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);
552
553         while (count > 0) {
554                 chunk = (count > info->buffer_size) ?
555                         info->buffer_size : count;
556
557                 target_write_buffer(target, info->source->address,
558                                     chunk, buffer);
559
560                 buf_set_u32(reg_params[0].value, 0, 32, io_base);
561                 buf_set_u32(reg_params[1].value, 0, 32, src_base);
562                 buf_set_u32(reg_params[2].value, 0, 32,
563                                 (1 << 31) | (addr4b << 30) |
564                                 (info->dev->pprog_cmd << 20) | chunk);
565                 buf_set_u32(reg_params[3].value, 0, 32, offset);
566
567                 ret = target_run_algorithm(target, 0, NULL, 4, reg_params,
568                                 info->io_algorithm->address,
569                                 0, 10000, &arm_algo);
570                 if (ret != ERROR_OK) {
571                         LOG_ERROR("error executing SH QSPI flash IO algorithm");
572                         ret = ERROR_FLASH_OPERATION_FAILED;
573                         break;
574                 }
575
576                 buffer += chunk;
577                 offset += chunk;
578                 count -= chunk;
579         }
580
581         destroy_reg_param(&reg_params[0]);
582         destroy_reg_param(&reg_params[1]);
583         destroy_reg_param(&reg_params[2]);
584         destroy_reg_param(&reg_params[3]);
585
586         return ret;
587 }
588
589 static int sh_qspi_read(struct flash_bank *bank, uint8_t *buffer,
590                         uint32_t offset, uint32_t count)
591 {
592         struct target *target = bank->target;
593         struct sh_qspi_flash_bank *info = bank->driver_priv;
594         struct reg_param reg_params[4];
595         struct arm_algorithm arm_algo;
596         uint32_t io_base = (uint32_t)(info->io_base);
597         uint32_t src_base = (uint32_t)(info->source->address);
598         uint32_t chunk;
599         bool addr4b = !!(info->dev->size_in_bytes > (1UL << 24));
600         int ret = ERROR_OK;
601
602         LOG_DEBUG("%s: offset=0x%08" PRIx32 " count=0x%08" PRIx32,
603                   __func__, offset, count);
604
605         if (target->state != TARGET_HALTED) {
606                 LOG_ERROR("Target not halted");
607                 return ERROR_TARGET_NOT_HALTED;
608         }
609
610         if (offset + count > bank->size) {
611                 LOG_WARNING("Reads past end of flash. Extra data discarded.");
612                 count = bank->size - offset;
613         }
614
615         arm_algo.common_magic = ARM_COMMON_MAGIC;
616         arm_algo.core_mode = ARM_MODE_SVC;
617         arm_algo.core_state = ARM_STATE_ARM;
618
619         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
620         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
621         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
622         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);
623
624         while (count > 0) {
625                 chunk = (count > info->buffer_size) ?
626                         info->buffer_size : count;
627
628                 buf_set_u32(reg_params[0].value, 0, 32, io_base);
629                 buf_set_u32(reg_params[1].value, 0, 32, src_base);
630                 buf_set_u32(reg_params[2].value, 0, 32,
631                                 (addr4b << 30) | (info->dev->read_cmd << 20) |
632                                 chunk);
633                 buf_set_u32(reg_params[3].value, 0, 32, offset);
634
635                 ret = target_run_algorithm(target, 0, NULL, 4, reg_params,
636                                 info->io_algorithm->address,
637                                 0, 10000, &arm_algo);
638                 if (ret != ERROR_OK) {
639                         LOG_ERROR("error executing SH QSPI flash IO algorithm");
640                         ret = ERROR_FLASH_OPERATION_FAILED;
641                         break;
642                 }
643
644                 target_read_buffer(target, info->source->address,
645                                    chunk, buffer);
646
647                 buffer += chunk;
648                 offset += chunk;
649                 count -= chunk;
650         }
651
652         destroy_reg_param(&reg_params[0]);
653         destroy_reg_param(&reg_params[1]);
654         destroy_reg_param(&reg_params[2]);
655         destroy_reg_param(&reg_params[3]);
656
657         return ret;
658 }
659
660 /* Return ID of flash device */
661 static int read_flash_id(struct flash_bank *bank, uint32_t *id)
662 {
663         struct target *target = bank->target;
664         uint8_t dout = SPIFLASH_READ_ID;
665         uint8_t din[3] = { 0, 0, 0 };
666         int ret;
667
668         if (target->state != TARGET_HALTED) {
669                 LOG_ERROR("Target not halted");
670                 return ERROR_TARGET_NOT_HALTED;
671         }
672
673         ret = sh_qspi_xfer_common(bank, &dout, 1, din, 3, 1, 1);
674         if (ret != ERROR_OK)
675                 return ret;
676
677         *id = (din[0] << 0) | (din[1] << 8) | (din[2] << 16);
678
679         if (*id == 0xffffff) {
680                 LOG_ERROR("No SPI flash found");
681                 return ERROR_FAIL;
682         }
683
684         return ERROR_OK;
685 }
686
687 static int sh_qspi_protect(struct flash_bank *bank, int set,
688                          int first, int last)
689 {
690         int sector;
691
692         for (sector = first; sector <= last; sector++)
693                 bank->sectors[sector].is_protected = set;
694
695         return ERROR_OK;
696 }
697
698 static int sh_qspi_upload_helper(struct flash_bank *bank)
699 {
700         struct target *target = bank->target;
701         struct sh_qspi_flash_bank *info = bank->driver_priv;
702
703         /* see contrib/loaders/flash/sh_qspi.s for src */
704         static const uint8_t sh_qspi_io_code[] = {
705 #include "../../../contrib/loaders/flash/sh_qspi/sh_qspi.inc"
706         };
707         int ret;
708
709         if (info->source)
710                 target_free_working_area(target, info->source);
711         if (info->io_algorithm)
712                 target_free_working_area(target, info->io_algorithm);
713
714         /* flash write code */
715         if (target_alloc_working_area(target, sizeof(sh_qspi_io_code),
716                         &info->io_algorithm) != ERROR_OK) {
717                 LOG_WARNING("no working area available, can't do block memory writes");
718                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
719         }
720
721         target_write_buffer(target, info->io_algorithm->address,
722                             sizeof(sh_qspi_io_code), sh_qspi_io_code);
723
724         /*
725          * Try to allocate as big work area buffer as possible, start
726          * with 32 kiB and count down. If there is less than 256 Bytes
727          * of work area available, abort.
728          */
729         info->buffer_size = 32768;
730         while (true) {
731                 ret = target_alloc_working_area_try(target, info->buffer_size,
732                                                     &info->source);
733                 if (ret == ERROR_OK)
734                         return ret;
735
736                 info->buffer_size /= 2;
737                 if (info->buffer_size <= 256) {
738                         target_free_working_area(target, info->io_algorithm);
739
740                         LOG_WARNING("no large enough working area available, can't do block memory writes");
741                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
742                 }
743         }
744
745         return ERROR_OK;
746 }
747
748 static int sh_qspi_probe(struct flash_bank *bank)
749 {
750         struct target *target = bank->target;
751         struct sh_qspi_flash_bank *info = bank->driver_priv;
752         struct flash_sector *sectors;
753         uint32_t id = 0; /* silence uninitialized warning */
754         uint32_t sectorsize;
755         const struct sh_qspi_target *target_device;
756         int ret;
757
758         if (info->probed)
759                 free(bank->sectors);
760
761         info->probed = 0;
762
763         for (target_device = target_devices; target_device->name;
764                 ++target_device)
765                 if (target_device->tap_idcode == target->tap->idcode)
766                         break;
767         if (!target_device->name) {
768                 LOG_ERROR("Device ID 0x%" PRIx32 " is not known",
769                           target->tap->idcode);
770                 return ERROR_FAIL;
771         }
772
773         info->io_base = target_device->io_base;
774
775         LOG_DEBUG("Found device %s at address " TARGET_ADDR_FMT,
776                   target_device->name, bank->base);
777
778         ret = sh_qspi_upload_helper(bank);
779         if (ret != ERROR_OK)
780                 return ret;
781
782         ret = sh_qspi_init(bank);
783         if (ret != ERROR_OK)
784                 return ret;
785
786         ret = read_flash_id(bank, &id);
787         if (ret != ERROR_OK)
788                 return ret;
789
790         info->dev = NULL;
791         for (const struct flash_device *p = flash_devices; p->name; p++)
792                 if (p->device_id == id) {
793                         info->dev = p;
794                         break;
795                 }
796
797         if (!info->dev) {
798                 LOG_ERROR("Unknown flash device (ID 0x%08" PRIx32 ")", id);
799                 return ERROR_FAIL;
800         }
801
802         LOG_INFO("Found flash device \'%s\' (ID 0x%08" PRIx32 ")",
803                  info->dev->name, info->dev->device_id);
804
805         /* Set correct size value */
806         bank->size = info->dev->size_in_bytes;
807         if (bank->size <= (1UL << 16))
808                 LOG_WARNING("device needs 2-byte addresses - not implemented");
809
810         /* if no sectors, treat whole bank as single sector */
811         sectorsize = info->dev->sectorsize ?
812                      info->dev->sectorsize :
813                      info->dev->size_in_bytes;
814
815         /* create and fill sectors array */
816         bank->num_sectors = info->dev->size_in_bytes / sectorsize;
817         sectors = calloc(1, sizeof(*sectors) * bank->num_sectors);
818         if (!sectors) {
819                 LOG_ERROR("not enough memory");
820                 return ERROR_FAIL;
821         }
822
823         for (int sector = 0; sector < bank->num_sectors; sector++) {
824                 sectors[sector].offset = sector * sectorsize;
825                 sectors[sector].size = sectorsize;
826                 sectors[sector].is_erased = 0;
827                 sectors[sector].is_protected = 0;
828         }
829
830         bank->sectors = sectors;
831         info->probed = 1;
832         return ERROR_OK;
833 }
834
835 static int sh_qspi_auto_probe(struct flash_bank *bank)
836 {
837         struct sh_qspi_flash_bank *info = bank->driver_priv;
838
839         if (info->probed)
840                 return ERROR_OK;
841
842         return sh_qspi_probe(bank);
843 }
844
845 static int sh_qspi_flash_blank_check(struct flash_bank *bank)
846 {
847         /* Not implemented */
848         return ERROR_OK;
849 }
850
851 static int sh_qspi_protect_check(struct flash_bank *bank)
852 {
853         /* Not implemented */
854         return ERROR_OK;
855 }
856
857 static int sh_qspi_get_info(struct flash_bank *bank, char *buf, int buf_size)
858 {
859         struct sh_qspi_flash_bank *info = bank->driver_priv;
860
861         if (!info->probed) {
862                 snprintf(buf, buf_size,
863                          "\nSH QSPI flash bank not probed yet\n");
864                 return ERROR_OK;
865         }
866
867         snprintf(buf, buf_size, "\nSH QSPI flash information:\n"
868                 "  Device \'%s\' (ID 0x%08" PRIx32 ")\n",
869                 info->dev->name, info->dev->device_id);
870
871         return ERROR_OK;
872 }
873
874 FLASH_BANK_COMMAND_HANDLER(sh_qspi_flash_bank_command)
875 {
876         struct sh_qspi_flash_bank *info;
877
878         LOG_DEBUG("%s", __func__);
879
880         if (CMD_ARGC < 6 || CMD_ARGC > 7)
881                 return ERROR_COMMAND_SYNTAX_ERROR;
882
883         if ((CMD_ARGC == 7) && strcmp(CMD_ARGV[6], "cs0")) {
884                 LOG_ERROR("Unknown arg: %s", CMD_ARGV[6]);
885                 return ERROR_COMMAND_SYNTAX_ERROR;
886         }
887
888         info = calloc(1, sizeof(struct sh_qspi_flash_bank));
889         if (!info) {
890                 LOG_ERROR("not enough memory");
891                 return ERROR_FAIL;
892         }
893
894         bank->driver_priv = info;
895
896         return ERROR_OK;
897 }
898
899 const struct flash_driver sh_qspi_flash = {
900         .name                   = "sh_qspi",
901         .flash_bank_command     = sh_qspi_flash_bank_command,
902         .erase                  = sh_qspi_erase,
903         .protect                = sh_qspi_protect,
904         .write                  = sh_qspi_write,
905         .read                   = sh_qspi_read,
906         .probe                  = sh_qspi_probe,
907         .auto_probe             = sh_qspi_auto_probe,
908         .erase_check            = sh_qspi_flash_blank_check,
909         .protect_check          = sh_qspi_protect_check,
910         .info                   = sh_qspi_get_info,
911         .free_driver_priv       = default_flash_free_driver_priv,
912 };