openocd: fix SPDX tag format for files .c
[fw/openocd] / src / flash / nor / ath79.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2
3 /***************************************************************************
4  *   Copyright (C) 2015 by Tobias Diedrich                                 *
5  *   <ranma+openwrt@tdiedrich.de>                                          *
6  *                                                                         *
7  *   based on the stmsmi code written by Antonio Borneo                    *
8  *   <borneo.antonio@gmail.com>                                            *
9  *                                                                         *
10  ***************************************************************************/
11 /*
12  * Driver for the Atheros AR7xxx/AR9xxx SPI flash interface.
13  *
14  * Since no SPI mode register is present, presumably only
15  * SPI "mode 3" (CPOL=1 and CPHA=1) is supported.
16  *
17  * The SPI interface supports up to 3 chip selects, however the SPI flash
18  * used for booting the system must be connected to CS0.
19  *
20  * On boot, the first 4MiB of flash space are memory-mapped into the
21  * area bf000000 - bfffffff (4 copies), so the MIPS bootstrap
22  * vector bfc00000 is mapped to the beginning of the flash.
23  *
24  * By writing a 1 to the REMAP_DISABLE bit in the SPI_CONTROL register,
25  * the full area of 16MiB is mapped.
26  *
27  * By writing a 0 to the SPI_FUNCTION_SELECT register (write-only dword
28  * register @bf000000), memory mapping is disabled and the SPI registers
29  * are exposed to the CPU instead:
30  * bf000000 SPI_FUNCTION_SELECT
31  * bf000004 SPI_CONTROL
32  * bf000008 SPI_IO_CONTROL
33  * bf00000c SPI_READ_DATA
34  *
35  * When not memory-mapped, the SPI interface is essentially bitbanged
36  * using SPI_CONTROL and SPI_IO_CONTROL with the only hardware-assistance
37  * being the 32bit read-only shift-register SPI_READ_DATA.
38  */
39
40 #ifdef HAVE_CONFIG_H
41 #include "config.h"
42 #endif
43
44 #include "imp.h"
45 #include "spi.h"
46 #include <jtag/jtag.h>
47 #include <helper/time_support.h>
48 #include <helper/types.h>
49 #include <target/mips32.h>
50 #include <target/mips32_pracc.h>
51 #include <target/target.h>
52
53 #define BITS_PER_BYTE 8
54
55 #define ATH79_REG_FS     0
56 #define ATH79_REG_CLOCK  4
57 #define ATH79_REG_WRITE  8
58 #define ATH79_REG_DATA  12
59
60 #define ATH79_SPI_CS_ALLHI 0x70000
61 #define ATH79_SPI_CS0_HI   0x10000
62 #define ATH79_SPI_CS1_HI   0x20000
63 #define ATH79_SPI_CS2_HI   0x40000
64 #define ATH79_SPI_CE_HI    0x00100
65 #define ATH79_SPI_DO_HI    0x00001
66
67 #define ATH79_XFER_FINAL   0x00000001
68 #define ATH79_XFER_PARTIAL 0x00000000
69
70 /* Timeout in ms */
71 #define ATH79_MAX_TIMEOUT  (3000)
72
73 struct ath79_spi_ctx {
74         uint8_t *page_buf;
75         int pre_deselect;
76         int post_deselect;
77 };
78
79 struct ath79_flash_bank {
80         bool probed;
81         int chipselect;
82         uint32_t io_base;
83         const struct flash_device *dev;
84         struct ath79_spi_ctx spi;
85 };
86
87 struct ath79_target {
88         char *name;
89         uint32_t tap_idcode;
90         uint32_t io_base;
91 };
92
93 static const struct ath79_target target_devices[] = {
94         /* name,   tap_idcode, io_base */
95         { "ATH79", 0x00000001, 0xbf000000 },
96         { NULL,    0,          0 }
97 };
98
99 static const uint32_t ath79_chipselects[] = {
100         (~ATH79_SPI_CS0_HI & ATH79_SPI_CS_ALLHI),
101         (~ATH79_SPI_CS1_HI & ATH79_SPI_CS_ALLHI),
102         (~ATH79_SPI_CS2_HI & ATH79_SPI_CS_ALLHI),
103 };
104
105 static void ath79_pracc_addn(struct pracc_queue_info *ctx,
106                              const uint32_t *instr,
107                              int n)
108 {
109         for (int i = 0; i < n; i++)
110                 pracc_add(ctx, 0, instr[i]);
111 }
112
113 static int ath79_spi_bitbang_codegen(struct ath79_flash_bank *ath79_info,
114                                      struct pracc_queue_info *ctx,
115                                      uint8_t *data, int len,
116                                      int partial_xfer)
117 {
118         uint32_t cs_high = ATH79_SPI_CS_ALLHI;
119         uint32_t cs_low = ath79_chipselects[ath79_info->chipselect];
120         uint32_t clock_high = cs_low | ATH79_SPI_CE_HI;
121         uint32_t clock_low = cs_low;
122         uint32_t pracc_out = 0;
123         uint32_t io_base = ath79_info->io_base;
124
125         const uint32_t preamble1[] = {
126                 /* $15 = MIPS32_PRACC_BASE_ADDR */
127                 MIPS32_LUI(0, 15, PRACC_UPPER_BASE_ADDR),
128                 /* $1 = io_base */
129                 MIPS32_LUI(0, 1, UPPER16(io_base)),
130         };
131         ath79_pracc_addn(ctx, preamble1, ARRAY_SIZE(preamble1));
132         if (ath79_info->spi.pre_deselect) {
133                 /* Clear deselect flag so we don't deselect again if
134                  * this is a partial xfer.
135                  */
136                 ath79_info->spi.pre_deselect = 0;
137                 const uint32_t pre_deselect[] = {
138                         /* [$1 + FS] = 1  (enable flash io register access) */
139                         MIPS32_LUI(0, 2, UPPER16(1)),
140                         MIPS32_ORI(0, 2, 2, LOWER16(1)),
141                         MIPS32_SW(0, 2, ATH79_REG_FS, 1),
142                         /* deselect flash just in case */
143                         /* $2 = SPI_CS_DIS */
144                         MIPS32_LUI(0, 2, UPPER16(cs_high)),
145                         MIPS32_ORI(0, 2, 2, LOWER16(cs_high)),
146                         /* [$1 + WRITE] = $2 */
147                         MIPS32_SW(0, 2, ATH79_REG_WRITE, 1),
148                 };
149                 ath79_pracc_addn(ctx, pre_deselect, ARRAY_SIZE(pre_deselect));
150         }
151         const uint32_t preamble2[] = {
152                 /* t0 = CLOCK_LOW + 0-bit */
153                 MIPS32_LUI(0, 8, UPPER16((clock_low + 0))),
154                 MIPS32_ORI(0, 8, 8, LOWER16((clock_low + 0))),
155                 /* t1 = CLOCK_LOW + 1-bit */
156                 MIPS32_LUI(0, 9, UPPER16((clock_low + 1))),
157                 MIPS32_ORI(0, 9, 9, LOWER16((clock_low + 1))),
158                 /* t2 = CLOCK_HIGH + 0-bit */
159                 MIPS32_LUI(0, 10, UPPER16((clock_high + 0))),
160                 MIPS32_ORI(0, 10, 10, LOWER16((clock_high + 0))),
161                 /* t3 = CLOCK_HIGH + 1-bit */
162                 MIPS32_LUI(0, 11, UPPER16((clock_high + 1))),
163                 MIPS32_ORI(0, 11, 11, LOWER16((clock_high + 1))),
164         };
165         ath79_pracc_addn(ctx, preamble2, ARRAY_SIZE(preamble2));
166
167         for (int i = 0; i < len; i++) {
168                 uint8_t x = data[i];
169
170                 /* Generate bitbang code for one byte, highest bit first .*/
171                 for (int j = BITS_PER_BYTE - 1; j >= 0; j--) {
172                         int bit = ((x >> j) & 1);
173
174                         if (bit) {
175                                 /* [$1 + WRITE] = t1 */
176                                 pracc_add(ctx, 0,
177                                           MIPS32_SW(0, 9, ATH79_REG_WRITE, 1));
178                                 /* [$1 + WRITE] = t3 */
179                                 pracc_add(ctx, 0,
180                                           MIPS32_SW(0, 11, ATH79_REG_WRITE, 1));
181                         } else {
182                                 /* [$1 + WRITE] = t0 */
183                                 pracc_add(ctx, 0,
184                                           MIPS32_SW(0, 8, ATH79_REG_WRITE, 1));
185                                 /* [$1 + WRITE] = t2 */
186                                 pracc_add(ctx, 0,
187                                           MIPS32_SW(0, 10, ATH79_REG_WRITE, 1));
188                         }
189                 }
190                 if (i % 4 == 3) {
191                         /* $3 = [$1 + DATA] */
192                         pracc_add(ctx, 0, MIPS32_LW(0, 3, ATH79_REG_DATA, 1));
193                         /* [OUTi] = $3 */
194                         pracc_add(ctx, MIPS32_PRACC_PARAM_OUT + pracc_out,
195                                   MIPS32_SW(0, 3, PRACC_OUT_OFFSET +
196                                  pracc_out, 15));
197                         pracc_out += 4;
198                 }
199         }
200         if (len & 3) { /* not a multiple of 4 bytes */
201                 /* $3 = [$1 + DATA] */
202                 pracc_add(ctx, 0, MIPS32_LW(0, 3, ATH79_REG_DATA, 1));
203                 /* [OUTi] = $3 */
204                 pracc_add(ctx, MIPS32_PRACC_PARAM_OUT + pracc_out,
205                           MIPS32_SW(0, 3, PRACC_OUT_OFFSET + pracc_out, 15));
206                 pracc_out += 4;
207         }
208
209         if (ath79_info->spi.post_deselect && !partial_xfer) {
210                 const uint32_t post_deselect[] = {
211                         /* $2 = SPI_CS_DIS */
212                         MIPS32_LUI(0, 2, UPPER16(cs_high)),
213                         MIPS32_ORI(0, 2, 2, LOWER16(cs_high)),
214                         /* [$1 + WRITE] = $2 */
215                         MIPS32_SW(0, 2, ATH79_REG_WRITE, 1),
216
217                         /* [$1 + FS] = 0  (disable flash io register access) */
218                         MIPS32_XORI(0, 2, 2, 0),
219                         MIPS32_SW(0, 2, ATH79_REG_FS, 1),
220                 };
221                 ath79_pracc_addn(ctx, post_deselect, ARRAY_SIZE(post_deselect));
222         }
223
224         /* common pracc epilogue */
225         /* jump to start */
226         pracc_add(ctx, 0, MIPS32_B(0, NEG16(ctx->code_count + 1)));
227         /* restore $15 from DeSave */
228         pracc_add(ctx, 0, MIPS32_MFC0(0, 15, 31, 0));
229
230         return pracc_out / 4;
231 }
232
233 static int ath79_spi_bitbang_chunk(struct flash_bank *bank,
234                                    uint8_t *data, int len, int *transferred)
235 {
236         struct target *target = bank->target;
237         struct ath79_flash_bank *ath79_info = bank->driver_priv;
238         struct mips32_common *mips32 = target_to_mips32(target);
239         struct mips_ejtag *ejtag_info = &mips32->ejtag_info;
240         int pracc_words;
241
242         /*
243          * These constants must match the worst case in the above code
244          * generator function ath79_spi_bitbang_codegen.
245          */
246         const int pracc_pre_post = 26;
247         const int pracc_loop_byte = 8 * 2 + 2;
248
249         struct pracc_queue_info ctx = {
250                 .ejtag_info = ejtag_info
251         };
252         int max_len = (PRACC_MAX_INSTRUCTIONS - pracc_pre_post) / pracc_loop_byte;
253         int to_xfer = len > max_len ? max_len : len;
254         int partial_xfer = len != to_xfer;
255         int padded_len = (to_xfer + 3) & ~3;
256         uint32_t *out = malloc(padded_len);
257
258         if (!out) {
259                 LOG_ERROR("not enough memory");
260                 return ERROR_FAIL;
261         }
262
263         *transferred = 0;
264         pracc_queue_init(&ctx);
265
266         LOG_DEBUG("ath79_spi_bitbang_bytes(%p, %08" PRIx32 ", %p, %d)",
267                   target, ath79_info->io_base, data, len);
268
269         LOG_DEBUG("max code %d => max len %d. to_xfer %d",
270                   PRACC_MAX_INSTRUCTIONS, max_len, to_xfer);
271
272         pracc_words = ath79_spi_bitbang_codegen(
273                 ath79_info, &ctx, data, to_xfer, partial_xfer);
274
275         LOG_DEBUG("Assembled %d instructions, %d stores",
276                   ctx.code_count, ctx.store_count);
277
278         ctx.retval = mips32_pracc_queue_exec(ejtag_info, &ctx, out, 1);
279         if (ctx.retval != ERROR_OK)
280                 goto exit;
281
282         if (to_xfer & 3) { /* Not a multiple of 4 bytes. */
283                 /*
284                  * Need to realign last word since we didn't shift the
285                  * full 32 bits.
286                  */
287                 int missed_bytes = 4 - (to_xfer & 3);
288
289                 out[pracc_words - 1] <<= BITS_PER_BYTE * missed_bytes;
290         }
291
292         /*
293          * pracc reads return uint32_t in host endianness, convert to
294          * target endianness.
295          * Since we know the ATH79 target is big endian and the SPI
296          * shift register has the bytes in highest to lowest bit order,
297          * this will ensure correct memory byte order regardless of host
298          * endianness.
299          */
300         target_buffer_set_u32_array(target, (uint8_t *)out, pracc_words, out);
301
302         if (LOG_LEVEL_IS(LOG_LVL_DEBUG)) {
303                 for (int i = 0; i < to_xfer; i++) {
304                         LOG_DEBUG("bitbang %02x => %02x",
305                                   data[i], ((uint8_t *)out)[i]);
306                 }
307         }
308         memcpy(data, out, to_xfer);
309         *transferred = to_xfer;
310
311 exit:
312         pracc_queue_free(&ctx);
313         free(out);
314         return ctx.retval;
315 }
316
317 static void ath79_spi_bitbang_prepare(struct flash_bank *bank)
318 {
319         struct ath79_flash_bank *ath79_info = bank->driver_priv;
320
321         ath79_info->spi.pre_deselect = 1;
322 }
323
324 static int ath79_spi_bitbang_bytes(struct flash_bank *bank,
325                                    uint8_t *data, int len, uint32_t flags)
326 {
327         struct ath79_flash_bank *ath79_info = bank->driver_priv;
328         int retval;
329         int transferred;
330
331         ath79_info->spi.post_deselect = !!(flags & ATH79_XFER_FINAL);
332
333         do {
334                 transferred = 0;
335                 retval = ath79_spi_bitbang_chunk(
336                         bank, data, len, &transferred);
337                 if (retval != ERROR_OK)
338                         return retval;
339
340                 data += transferred;
341                 len -= transferred;
342         } while (len > 0);
343
344         return ERROR_OK;
345 }
346
347 FLASH_BANK_COMMAND_HANDLER(ath79_flash_bank_command)
348 {
349         struct ath79_flash_bank *ath79_info;
350         int chipselect = 0;
351
352         LOG_DEBUG("%s", __func__);
353
354         if (CMD_ARGC < 6 || CMD_ARGC > 7)
355                 return ERROR_COMMAND_SYNTAX_ERROR;
356
357         if (CMD_ARGC == 7) {
358                 if (strcmp(CMD_ARGV[6], "cs0") == 0)
359                         chipselect = 0;  /* default */
360                 else if (strcmp(CMD_ARGV[6], "cs1") == 0)
361                         chipselect = 1;
362                 else if (strcmp(CMD_ARGV[6], "cs2") == 0)
363                         chipselect = 2;
364                 else {
365                         LOG_ERROR("Unknown arg: %s", CMD_ARGV[6]);
366                         return ERROR_COMMAND_SYNTAX_ERROR;
367                 }
368         }
369
370         ath79_info = calloc(1, sizeof(struct ath79_flash_bank));
371         if (!ath79_info) {
372                 LOG_ERROR("not enough memory");
373                 return ERROR_FAIL;
374         }
375
376         ath79_info->chipselect = chipselect;
377         bank->driver_priv = ath79_info;
378
379         return ERROR_OK;
380 }
381
382 /* Read the status register of the external SPI flash chip. */
383 static int read_status_reg(struct flash_bank *bank, uint32_t *status)
384 {
385         uint8_t spi_bytes[] = {SPIFLASH_READ_STATUS, 0};
386         int retval;
387
388         /* Send SPI command "read STATUS" */
389         ath79_spi_bitbang_prepare(bank);
390         retval = ath79_spi_bitbang_bytes(
391                 bank, spi_bytes, sizeof(spi_bytes),
392                 ATH79_XFER_FINAL);
393
394         *status = spi_bytes[1];
395
396         return retval;
397 }
398
399 /* check for WIP (write in progress) bit in status register */
400 /* timeout in ms */
401 static int wait_till_ready(struct flash_bank *bank, int timeout)
402 {
403         uint32_t status;
404         int retval;
405         long long endtime;
406
407         endtime = timeval_ms() + timeout;
408         do {
409                 /* read flash status register */
410                 retval = read_status_reg(bank, &status);
411                 if (retval != ERROR_OK)
412                         return retval;
413
414                 if ((status & SPIFLASH_BSY_BIT) == 0)
415                         return ERROR_OK;
416                 alive_sleep(1);
417         } while (timeval_ms() < endtime);
418
419         LOG_ERROR("timeout");
420         return ERROR_FAIL;
421 }
422
423 /* Send "write enable" command to SPI flash chip. */
424 static int ath79_write_enable(struct flash_bank *bank)
425 {
426         uint32_t status;
427         int retval;
428
429         uint8_t spi_bytes[] = {SPIFLASH_WRITE_ENABLE};
430
431         /* Send SPI command "write enable" */
432         ath79_spi_bitbang_prepare(bank);
433         retval = ath79_spi_bitbang_bytes(
434                 bank, spi_bytes, sizeof(spi_bytes),
435                 ATH79_XFER_FINAL);
436         if (retval != ERROR_OK)
437                 return retval;
438
439         /* read flash status register */
440         retval = read_status_reg(bank, &status);
441         if (retval != ERROR_OK)
442                 return retval;
443
444         /* Check write enabled */
445         if ((status & SPIFLASH_WE_BIT) == 0) {
446                 LOG_ERROR("Cannot enable write to flash. Status=0x%08" PRIx32,
447                           status);
448                 return ERROR_FAIL;
449         }
450
451         return ERROR_OK;
452 }
453
454 static int erase_command(struct flash_bank *bank, int sector)
455 {
456         struct ath79_flash_bank *ath79_info = bank->driver_priv;
457         uint32_t offset = bank->sectors[sector].offset;
458
459         uint8_t spi_bytes[] = {
460                 ath79_info->dev->erase_cmd,
461                 offset >> 16,
462                 offset >> 8,
463                 offset
464         };
465
466         /* bitbang command */
467         ath79_spi_bitbang_prepare(bank);
468         return ath79_spi_bitbang_bytes(
469                 bank, spi_bytes, sizeof(spi_bytes),
470                 ATH79_XFER_FINAL);
471 }
472
473 static int ath79_erase_sector(struct flash_bank *bank, int sector)
474 {
475         int retval = ath79_write_enable(bank);
476
477         if (retval != ERROR_OK)
478                 return retval;
479
480         /* send SPI command "block erase" */
481         retval = erase_command(bank, sector);
482         if (retval != ERROR_OK)
483                 return retval;
484
485         /* poll WIP for end of self timed Sector Erase cycle */
486         return wait_till_ready(bank, ATH79_MAX_TIMEOUT);
487 }
488
489 static int ath79_erase(struct flash_bank *bank, unsigned int first,
490                 unsigned int last)
491 {
492         struct target *target = bank->target;
493         struct ath79_flash_bank *ath79_info = bank->driver_priv;
494         int retval = ERROR_OK;
495
496         LOG_DEBUG("%s: from sector %u to sector %u", __func__, first, last);
497
498         if (target->state != TARGET_HALTED) {
499                 LOG_ERROR("Target not halted");
500                 return ERROR_TARGET_NOT_HALTED;
501         }
502
503         if ((last < first) || (last >= bank->num_sectors)) {
504                 LOG_ERROR("Flash sector invalid");
505                 return ERROR_FLASH_SECTOR_INVALID;
506         }
507
508         if (!ath79_info->probed) {
509                 LOG_ERROR("Flash bank not probed");
510                 return ERROR_FLASH_BANK_NOT_PROBED;
511         }
512
513         if (ath79_info->dev->erase_cmd == 0x00)
514                 return ERROR_FLASH_OPER_UNSUPPORTED;
515
516         for (unsigned sector = first; sector <= last; sector++) {
517                 if (bank->sectors[sector].is_protected) {
518                         LOG_ERROR("Flash sector %u protected", sector);
519                         return ERROR_FAIL;
520                 }
521         }
522
523         for (unsigned int sector = first; sector <= last; sector++) {
524                 retval = ath79_erase_sector(bank, sector);
525                 if (retval != ERROR_OK)
526                         break;
527                 keep_alive();
528         }
529
530         return retval;
531 }
532
533 static int ath79_protect(struct flash_bank *bank, int set, unsigned int first,
534                 unsigned int last)
535 {
536         for (unsigned int sector = first; sector <= last; sector++)
537                 bank->sectors[sector].is_protected = set;
538         return ERROR_OK;
539 }
540
541 static int ath79_write_page(struct flash_bank *bank, const uint8_t *buffer,
542                             uint32_t address, uint32_t len)
543 {
544         struct ath79_flash_bank *ath79_info = bank->driver_priv;
545         uint8_t spi_bytes[] = {
546                 SPIFLASH_PAGE_PROGRAM,
547                 address >> 16,
548                 address >> 8,
549                 address,
550         };
551         int retval;
552         uint32_t i, pagesize;
553
554         /* if no write pagesize, use reasonable default */
555         pagesize = ath79_info->dev->pagesize ?
556                 ath79_info->dev->pagesize : SPIFLASH_DEF_PAGESIZE;
557
558         if (address & 0xff) {
559                 LOG_ERROR("ath79_write_page: unaligned write address: %08" PRIx32,
560                           address);
561                 return ERROR_FAIL;
562         }
563         if (!ath79_info->spi.page_buf) {
564                 LOG_ERROR("ath79_write_page: page buffer not initialized");
565                 return ERROR_FAIL;
566         }
567         if (len > ath79_info->dev->pagesize) {
568                 LOG_ERROR("ath79_write_page: len bigger than page size %" PRIu32 ": %" PRIu32,
569                         pagesize, len);
570                 return ERROR_FAIL;
571         }
572
573         for (i = 0; i < len; i++) {
574                 if (buffer[i] != 0xff)
575                         break;
576         }
577         if (i == len)  /* all 0xff, no need to program. */
578                 return ERROR_OK;
579
580         LOG_INFO("writing %" PRIu32 " bytes to flash page @0x%08" PRIx32, len, address);
581
582         memcpy(ath79_info->spi.page_buf, buffer, len);
583
584         /* unlock writes */
585         retval = ath79_write_enable(bank);
586         if (retval != ERROR_OK)
587                 return retval;
588
589         /* bitbang command */
590         ath79_spi_bitbang_prepare(bank);
591         retval = ath79_spi_bitbang_bytes(
592                 bank, spi_bytes, sizeof(spi_bytes),
593                 ATH79_XFER_PARTIAL);
594         if (retval != ERROR_OK)
595                 return retval;
596
597         /* write data */
598         return ath79_spi_bitbang_bytes(
599                 bank, ath79_info->spi.page_buf, len,
600                 ATH79_XFER_FINAL);
601 }
602
603 static int ath79_write_buffer(struct flash_bank *bank, const uint8_t *buffer,
604                               uint32_t address, uint32_t len)
605 {
606         struct ath79_flash_bank *ath79_info = bank->driver_priv;
607         uint32_t page_size;
608         int retval;
609
610         LOG_DEBUG("%s: address=0x%08" PRIx32 " len=0x%08" PRIx32,
611                   __func__, address, len);
612
613         /* if no valid page_size, use reasonable default */
614         page_size = ath79_info->dev->pagesize ?
615                 ath79_info->dev->pagesize : SPIFLASH_DEF_PAGESIZE;
616
617         while (len > 0) {
618                 int page_len = len > page_size ? page_size : len;
619
620                 retval = ath79_write_page(
621                         bank, buffer, address, page_len);
622                 if (retval != ERROR_OK)
623                         return retval;
624
625                 buffer += page_size;
626                 address += page_size;
627                 len -= page_len;
628         }
629
630         return ERROR_OK;
631 }
632
633 static int ath79_write(struct flash_bank *bank, const uint8_t *buffer,
634                        uint32_t offset, uint32_t count)
635 {
636         struct target *target = bank->target;
637
638         LOG_DEBUG("%s: offset=0x%08" PRIx32 " count=0x%08" PRIx32,
639                   __func__, offset, count);
640
641         if (target->state != TARGET_HALTED) {
642                 LOG_ERROR("Target not halted");
643                 return ERROR_TARGET_NOT_HALTED;
644         }
645
646         if (offset + count > bank->size) {
647                 LOG_WARNING("Write pasts end of flash. Extra data discarded.");
648                 count = bank->size - offset;
649         }
650
651         /* Check sector protection */
652         for (unsigned int sector = 0; sector < bank->num_sectors; sector++) {
653                 /* Start offset in or before this sector? */
654                 /* End offset in or behind this sector? */
655                 struct flash_sector *bs = &bank->sectors[sector];
656
657                 if ((offset < (bs->offset + bs->size)) &&
658                     ((offset + count - 1) >= bs->offset) &&
659                     bs->is_protected) {
660                         LOG_ERROR("Flash sector %u protected", sector);
661                         return ERROR_FAIL;
662                 }
663         }
664
665         return ath79_write_buffer(bank, buffer, offset, count);
666 }
667
668 static int ath79_read_buffer(struct flash_bank *bank, uint8_t *buffer,
669                              uint32_t address, uint32_t len)
670 {
671         uint8_t spi_bytes[] = {
672                 SPIFLASH_READ,
673                 address >> 16,
674                 address >> 8,
675                 address,
676         };
677         int retval;
678
679         LOG_DEBUG("%s: address=0x%08" PRIx32 " len=0x%08" PRIx32,
680                   __func__, address, len);
681
682         if (address & 0xff) {
683                 LOG_ERROR("ath79_read_buffer: unaligned read address: %08" PRIx32,
684                           address);
685                 return ERROR_FAIL;
686         }
687
688         LOG_INFO("reading %" PRIu32 " bytes from flash @0x%08" PRIx32, len, address);
689
690         /* bitbang command */
691         ath79_spi_bitbang_prepare(bank);
692         retval = ath79_spi_bitbang_bytes(
693                 bank, spi_bytes, sizeof(spi_bytes), ATH79_XFER_PARTIAL);
694         if (retval != ERROR_OK)
695                 return retval;
696
697         /* read data */
698         return ath79_spi_bitbang_bytes(
699                 bank, buffer, len, ATH79_XFER_FINAL);
700 }
701
702 static int ath79_read(struct flash_bank *bank, uint8_t *buffer,
703                       uint32_t offset, uint32_t count)
704 {
705         struct target *target = bank->target;
706
707         LOG_DEBUG("%s: offset=0x%08" PRIx32 " count=0x%08" PRIx32,
708                   __func__, offset, count);
709
710         if (target->state != TARGET_HALTED) {
711                 LOG_ERROR("Target not halted");
712                 return ERROR_TARGET_NOT_HALTED;
713         }
714
715         if (offset + count > bank->size) {
716                 LOG_WARNING("Reads past end of flash. Extra data discarded.");
717                 count = bank->size - offset;
718         }
719
720         return ath79_read_buffer(bank, buffer, offset, count);
721 }
722
723 /* Return ID of flash device */
724 static int read_flash_id(struct flash_bank *bank, uint32_t *id)
725 {
726         struct target *target = bank->target;
727         int retval;
728         uint8_t spi_bytes[] = {SPIFLASH_READ_ID, 0, 0, 0};
729
730         if (target->state != TARGET_HALTED) {
731                 LOG_ERROR("Target not halted");
732                 return ERROR_TARGET_NOT_HALTED;
733         }
734
735         /* Send SPI command "read ID" */
736         ath79_spi_bitbang_prepare(bank);
737         retval = ath79_spi_bitbang_bytes(
738                 bank, spi_bytes, sizeof(spi_bytes), ATH79_XFER_FINAL);
739         if (retval != ERROR_OK)
740                 return retval;
741
742         *id = (spi_bytes[1] << 0)
743                 | (spi_bytes[2] << 8)
744                 | (spi_bytes[3] << 16);
745
746         if (*id == 0xffffff) {
747                 LOG_ERROR("No SPI flash found");
748                 return ERROR_FAIL;
749         }
750
751         return ERROR_OK;
752 }
753
754 static int ath79_probe(struct flash_bank *bank)
755 {
756         struct target *target = bank->target;
757         struct ath79_flash_bank *ath79_info = bank->driver_priv;
758         struct flash_sector *sectors;
759         uint32_t id = 0; /* silence uninitialized warning */
760         uint32_t pagesize, sectorsize;
761         const struct ath79_target *target_device;
762         int retval;
763
764         if (ath79_info->probed) {
765                 free(bank->sectors);
766                 free(ath79_info->spi.page_buf);
767         }
768         ath79_info->probed = false;
769
770         for (target_device = target_devices; target_device->name;
771                 ++target_device)
772                 if (target_device->tap_idcode == target->tap->idcode)
773                         break;
774         if (!target_device->name) {
775                 LOG_ERROR("Device ID 0x%" PRIx32 " is not known",
776                           target->tap->idcode);
777                 return ERROR_FAIL;
778         }
779
780         ath79_info->io_base = target_device->io_base;
781
782         LOG_DEBUG("Found device %s at address " TARGET_ADDR_FMT,
783                   target_device->name, bank->base);
784
785         retval = read_flash_id(bank, &id);
786         if (retval != ERROR_OK)
787                 return retval;
788
789         ath79_info->dev = NULL;
790         for (const struct flash_device *p = flash_devices; p->name; p++)
791                 if (p->device_id == id) {
792                         ath79_info->dev = p;
793                         break;
794                 }
795
796         if (!ath79_info->dev) {
797                 LOG_ERROR("Unknown flash device (ID 0x%08" PRIx32 ")", id);
798                 return ERROR_FAIL;
799         }
800
801         LOG_INFO("Found flash device \'%s\' (ID 0x%08" PRIx32 ")",
802                  ath79_info->dev->name, ath79_info->dev->device_id);
803
804         /* Set correct size value */
805         bank->size = ath79_info->dev->size_in_bytes;
806         if (bank->size <= (1UL << 16))
807                 LOG_WARNING("device needs 2-byte addresses - not implemented");
808         if (bank->size > (1UL << 24))
809                 LOG_WARNING("device needs paging or 4-byte addresses - not implemented");
810
811         /* if no sectors, treat whole bank as single sector */
812         sectorsize = ath79_info->dev->sectorsize ?
813                 ath79_info->dev->sectorsize : ath79_info->dev->size_in_bytes;
814
815         /* create and fill sectors array */
816         bank->num_sectors = ath79_info->dev->size_in_bytes / sectorsize;
817         sectors = calloc(1, sizeof(struct flash_sector) * bank->num_sectors);
818         if (!sectors) {
819                 LOG_ERROR("not enough memory");
820                 return ERROR_FAIL;
821         }
822
823         /* if no write pagesize, use reasonable default */
824         pagesize = ath79_info->dev->pagesize ? ath79_info->dev->pagesize : SPIFLASH_DEF_PAGESIZE;
825
826         ath79_info->spi.page_buf = malloc(pagesize);
827         if (!ath79_info->spi.page_buf) {
828                 LOG_ERROR("not enough memory");
829                 free(sectors);
830                 return ERROR_FAIL;
831         }
832
833         for (unsigned int sector = 0; sector < bank->num_sectors; sector++) {
834                 sectors[sector].offset = sector * sectorsize;
835                 sectors[sector].size = sectorsize;
836                 sectors[sector].is_erased = 0;
837                 sectors[sector].is_protected = 1;
838         }
839
840         bank->sectors = sectors;
841         ath79_info->probed = true;
842         return ERROR_OK;
843 }
844
845 static int ath79_auto_probe(struct flash_bank *bank)
846 {
847         struct ath79_flash_bank *ath79_info = bank->driver_priv;
848
849         if (ath79_info->probed)
850                 return ERROR_OK;
851         return ath79_probe(bank);
852 }
853
854 static int ath79_flash_blank_check(struct flash_bank *bank)
855 {
856         /* Not implemented */
857         return ERROR_OK;
858 }
859
860 static int ath79_protect_check(struct flash_bank *bank)
861 {
862         /* Not implemented */
863         return ERROR_OK;
864 }
865
866 static int get_ath79_info(struct flash_bank *bank, struct command_invocation *cmd)
867 {
868         struct ath79_flash_bank *ath79_info = bank->driver_priv;
869
870         if (!ath79_info->probed) {
871                 command_print_sameline(cmd, "\nATH79 flash bank not probed yet\n");
872                 return ERROR_OK;
873         }
874
875         command_print_sameline(cmd, "\nATH79 flash information:\n"
876                 "  Device \'%s\' (ID 0x%08" PRIx32 ")\n",
877                 ath79_info->dev->name, ath79_info->dev->device_id);
878
879         return ERROR_OK;
880 }
881
882 const struct flash_driver ath79_flash = {
883         .name = "ath79",
884         .flash_bank_command = ath79_flash_bank_command,
885         .erase = ath79_erase,
886         .protect = ath79_protect,
887         .write = ath79_write,
888         .read = ath79_read,
889         .probe = ath79_probe,
890         .auto_probe = ath79_auto_probe,
891         .erase_check = ath79_flash_blank_check,
892         .protect_check = ath79_protect_check,
893         .info = get_ath79_info,
894         .free_driver_priv = default_flash_free_driver_priv,
895 };