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