Merge branch 'master' of git://git.denx.de/u-boot-sunxi
[oweals/u-boot.git] / drivers / mtd / spi / sandbox.c
1 /*
2  * Simulate a SPI flash
3  *
4  * Copyright (c) 2011-2013 The Chromium OS Authors.
5  * See file CREDITS for list of people who contributed to this
6  * project.
7  *
8  * Licensed under the GPL-2 or later.
9  */
10
11 #include <common.h>
12 #include <dm.h>
13 #include <malloc.h>
14 #include <spi.h>
15 #include <os.h>
16
17 #include <spi_flash.h>
18 #include "sf_internal.h"
19
20 #include <asm/getopt.h>
21 #include <asm/spi.h>
22 #include <asm/state.h>
23 #include <dm/device-internal.h>
24 #include <dm/lists.h>
25 #include <dm/uclass-internal.h>
26
27 DECLARE_GLOBAL_DATA_PTR;
28
29 /*
30  * The different states that our SPI flash transitions between.
31  * We need to keep track of this across multiple xfer calls since
32  * the SPI bus could possibly call down into us multiple times.
33  */
34 enum sandbox_sf_state {
35         SF_CMD,   /* default state -- we're awaiting a command */
36         SF_ID,    /* read the flash's (jedec) ID code */
37         SF_ADDR,  /* processing the offset in the flash to read/etc... */
38         SF_READ,  /* reading data from the flash */
39         SF_WRITE, /* writing data to the flash, i.e. page programming */
40         SF_ERASE, /* erase the flash */
41         SF_READ_STATUS, /* read the flash's status register */
42         SF_READ_STATUS1, /* read the flash's status register upper 8 bits*/
43         SF_WRITE_STATUS, /* write the flash's status register */
44 };
45
46 static const char *sandbox_sf_state_name(enum sandbox_sf_state state)
47 {
48         static const char * const states[] = {
49                 "CMD", "ID", "ADDR", "READ", "WRITE", "ERASE", "READ_STATUS",
50                 "READ_STATUS1", "WRITE_STATUS",
51         };
52         return states[state];
53 }
54
55 /* Bits for the status register */
56 #define STAT_WIP        (1 << 0)
57 #define STAT_WEL        (1 << 1)
58
59 /* Assume all SPI flashes have 3 byte addresses since they do atm */
60 #define SF_ADDR_LEN     3
61
62 #define IDCODE_LEN 3
63
64 /* Used to quickly bulk erase backing store */
65 static u8 sandbox_sf_0xff[0x1000];
66
67 /* Internal state data for each SPI flash */
68 struct sandbox_spi_flash {
69         unsigned int cs;        /* Chip select we are attached to */
70         /*
71          * As we receive data over the SPI bus, our flash transitions
72          * between states.  For example, we start off in the SF_CMD
73          * state where the first byte tells us what operation to perform
74          * (such as read or write the flash).  But the operation itself
75          * can go through a few states such as first reading in the
76          * offset in the flash to perform the requested operation.
77          * Thus "state" stores the exact state that our machine is in
78          * while "cmd" stores the overall command we're processing.
79          */
80         enum sandbox_sf_state state;
81         uint cmd;
82         /* Erase size of current erase command */
83         uint erase_size;
84         /* Current position in the flash; used when reading/writing/etc... */
85         uint off;
86         /* How many address bytes we've consumed */
87         uint addr_bytes, pad_addr_bytes;
88         /* The current flash status (see STAT_XXX defines above) */
89         u16 status;
90         /* Data describing the flash we're emulating */
91         const struct spi_flash_params *data;
92         /* The file on disk to serv up data from */
93         int fd;
94 };
95
96 struct sandbox_spi_flash_plat_data {
97         const char *filename;
98         const char *device_name;
99         int bus;
100         int cs;
101 };
102
103 /**
104  * This is a very strange probe function. If it has platform data (which may
105  * have come from the device tree) then this function gets the filename and
106  * device type from there. Failing that it looks at the command line
107  * parameter.
108  */
109 static int sandbox_sf_probe(struct udevice *dev)
110 {
111         /* spec = idcode:file */
112         struct sandbox_spi_flash *sbsf = dev_get_priv(dev);
113         const char *file;
114         size_t len, idname_len;
115         const struct spi_flash_params *data;
116         struct sandbox_spi_flash_plat_data *pdata = dev_get_platdata(dev);
117         struct sandbox_state *state = state_get_current();
118         struct udevice *bus = dev->parent;
119         const char *spec = NULL;
120         int ret = 0;
121         int cs = -1;
122         int i;
123
124         debug("%s: bus %d, looking for emul=%p: ", __func__, bus->seq, dev);
125         if (bus->seq >= 0 && bus->seq < CONFIG_SANDBOX_SPI_MAX_BUS) {
126                 for (i = 0; i < CONFIG_SANDBOX_SPI_MAX_CS; i++) {
127                         if (state->spi[bus->seq][i].emul == dev)
128                                 cs = i;
129                 }
130         }
131         if (cs == -1) {
132                 printf("Error: Unknown chip select for device '%s'",
133                        dev->name);
134                 return -EINVAL;
135         }
136         debug("found at cs %d\n", cs);
137
138         if (!pdata->filename) {
139                 struct sandbox_state *state = state_get_current();
140
141                 assert(bus->seq != -1);
142                 if (bus->seq < CONFIG_SANDBOX_SPI_MAX_BUS)
143                         spec = state->spi[bus->seq][cs].spec;
144                 if (!spec) {
145                         ret = -ENOENT;
146                         goto error;
147                 }
148
149                 file = strchr(spec, ':');
150                 if (!file) {
151                         printf("sandbox_sf: unable to parse file\n");
152                         ret = -EINVAL;
153                         goto error;
154                 }
155                 idname_len = file - spec;
156                 pdata->filename = file + 1;
157                 pdata->device_name = spec;
158                 ++file;
159         } else {
160                 spec = strchr(pdata->device_name, ',');
161                 if (spec)
162                         spec++;
163                 else
164                         spec = pdata->device_name;
165                 idname_len = strlen(spec);
166         }
167         debug("%s: device='%s'\n", __func__, spec);
168
169         for (data = spi_flash_params_table; data->name; data++) {
170                 len = strlen(data->name);
171                 if (idname_len != len)
172                         continue;
173                 if (!strncasecmp(spec, data->name, len))
174                         break;
175         }
176         if (!data->name) {
177                 printf("sandbox_sf: unknown flash '%*s'\n", (int)idname_len,
178                        spec);
179                 ret = -EINVAL;
180                 goto error;
181         }
182
183         if (sandbox_sf_0xff[0] == 0x00)
184                 memset(sandbox_sf_0xff, 0xff, sizeof(sandbox_sf_0xff));
185
186         sbsf->fd = os_open(pdata->filename, 02);
187         if (sbsf->fd == -1) {
188                 free(sbsf);
189                 printf("sandbox_sf: unable to open file '%s'\n",
190                        pdata->filename);
191                 ret = -EIO;
192                 goto error;
193         }
194
195         sbsf->data = data;
196         sbsf->cs = cs;
197
198         return 0;
199
200  error:
201         debug("%s: Got error %d\n", __func__, ret);
202         return ret;
203 }
204
205 static int sandbox_sf_remove(struct udevice *dev)
206 {
207         struct sandbox_spi_flash *sbsf = dev_get_priv(dev);
208
209         os_close(sbsf->fd);
210
211         return 0;
212 }
213
214 static void sandbox_sf_cs_activate(struct udevice *dev)
215 {
216         struct sandbox_spi_flash *sbsf = dev_get_priv(dev);
217
218         debug("sandbox_sf: CS activated; state is fresh!\n");
219
220         /* CS is asserted, so reset state */
221         sbsf->off = 0;
222         sbsf->addr_bytes = 0;
223         sbsf->pad_addr_bytes = 0;
224         sbsf->state = SF_CMD;
225         sbsf->cmd = SF_CMD;
226 }
227
228 static void sandbox_sf_cs_deactivate(struct udevice *dev)
229 {
230         debug("sandbox_sf: CS deactivated; cmd done processing!\n");
231 }
232
233 /*
234  * There are times when the data lines are allowed to tristate.  What
235  * is actually sensed on the line depends on the hardware.  It could
236  * always be 0xFF/0x00 (if there are pull ups/downs), or things could
237  * float and so we'd get garbage back.  This func encapsulates that
238  * scenario so we can worry about the details here.
239  */
240 static void sandbox_spi_tristate(u8 *buf, uint len)
241 {
242         /* XXX: make this into a user config option ? */
243         memset(buf, 0xff, len);
244 }
245
246 /* Figure out what command this stream is telling us to do */
247 static int sandbox_sf_process_cmd(struct sandbox_spi_flash *sbsf, const u8 *rx,
248                                   u8 *tx)
249 {
250         enum sandbox_sf_state oldstate = sbsf->state;
251
252         /* We need to output a byte for the cmd byte we just ate */
253         if (tx)
254                 sandbox_spi_tristate(tx, 1);
255
256         sbsf->cmd = rx[0];
257         switch (sbsf->cmd) {
258         case CMD_READ_ID:
259                 sbsf->state = SF_ID;
260                 sbsf->cmd = SF_ID;
261                 break;
262         case CMD_READ_ARRAY_FAST:
263                 sbsf->pad_addr_bytes = 1;
264         case CMD_READ_ARRAY_SLOW:
265         case CMD_PAGE_PROGRAM:
266                 sbsf->state = SF_ADDR;
267                 break;
268         case CMD_WRITE_DISABLE:
269                 debug(" write disabled\n");
270                 sbsf->status &= ~STAT_WEL;
271                 break;
272         case CMD_READ_STATUS:
273                 sbsf->state = SF_READ_STATUS;
274                 break;
275         case CMD_READ_STATUS1:
276                 sbsf->state = SF_READ_STATUS1;
277                 break;
278         case CMD_WRITE_ENABLE:
279                 debug(" write enabled\n");
280                 sbsf->status |= STAT_WEL;
281                 break;
282         case CMD_WRITE_STATUS:
283                 sbsf->state = SF_WRITE_STATUS;
284                 break;
285         default: {
286                 int flags = sbsf->data->flags;
287
288                 /* we only support erase here */
289                 if (sbsf->cmd == CMD_ERASE_CHIP) {
290                         sbsf->erase_size = sbsf->data->sector_size *
291                                 sbsf->data->nr_sectors;
292                 } else if (sbsf->cmd == CMD_ERASE_4K && (flags & SECT_4K)) {
293                         sbsf->erase_size = 4 << 10;
294                 } else if (sbsf->cmd == CMD_ERASE_32K && (flags & SECT_32K)) {
295                         sbsf->erase_size = 32 << 10;
296                 } else if (sbsf->cmd == CMD_ERASE_64K &&
297                            !(flags & (SECT_4K | SECT_32K))) {
298                         sbsf->erase_size = 64 << 10;
299                 } else {
300                         debug(" cmd unknown: %#x\n", sbsf->cmd);
301                         return -EIO;
302                 }
303                 sbsf->state = SF_ADDR;
304                 break;
305         }
306         }
307
308         if (oldstate != sbsf->state)
309                 debug(" cmd: transition to %s state\n",
310                       sandbox_sf_state_name(sbsf->state));
311
312         return 0;
313 }
314
315 int sandbox_erase_part(struct sandbox_spi_flash *sbsf, int size)
316 {
317         int todo;
318         int ret;
319
320         while (size > 0) {
321                 todo = min(size, (int)sizeof(sandbox_sf_0xff));
322                 ret = os_write(sbsf->fd, sandbox_sf_0xff, todo);
323                 if (ret != todo)
324                         return ret;
325                 size -= todo;
326         }
327
328         return 0;
329 }
330
331 static int sandbox_sf_xfer(struct udevice *dev, unsigned int bitlen,
332                            const void *rxp, void *txp, unsigned long flags)
333 {
334         struct sandbox_spi_flash *sbsf = dev_get_priv(dev);
335         const uint8_t *rx = rxp;
336         uint8_t *tx = txp;
337         uint cnt, pos = 0;
338         int bytes = bitlen / 8;
339         int ret;
340
341         debug("sandbox_sf: state:%x(%s) bytes:%u\n", sbsf->state,
342               sandbox_sf_state_name(sbsf->state), bytes);
343
344         if ((flags & SPI_XFER_BEGIN))
345                 sandbox_sf_cs_activate(dev);
346
347         if (sbsf->state == SF_CMD) {
348                 /* Figure out the initial state */
349                 ret = sandbox_sf_process_cmd(sbsf, rx, tx);
350                 if (ret)
351                         return ret;
352                 ++pos;
353         }
354
355         /* Process the remaining data */
356         while (pos < bytes) {
357                 switch (sbsf->state) {
358                 case SF_ID: {
359                         u8 id;
360
361                         debug(" id: off:%u tx:", sbsf->off);
362                         if (sbsf->off < IDCODE_LEN) {
363                                 /* Extract correct byte from ID 0x00aabbcc */
364                                 id = sbsf->data->jedec >>
365                                         (8 * (IDCODE_LEN - 1 - sbsf->off));
366                         } else {
367                                 id = 0;
368                         }
369                         debug("%d %02x\n", sbsf->off, id);
370                         tx[pos++] = id;
371                         ++sbsf->off;
372                         break;
373                 }
374                 case SF_ADDR:
375                         debug(" addr: bytes:%u rx:%02x ", sbsf->addr_bytes,
376                               rx[pos]);
377
378                         if (sbsf->addr_bytes++ < SF_ADDR_LEN)
379                                 sbsf->off = (sbsf->off << 8) | rx[pos];
380                         debug("addr:%06x\n", sbsf->off);
381
382                         if (tx)
383                                 sandbox_spi_tristate(&tx[pos], 1);
384                         pos++;
385
386                         /* See if we're done processing */
387                         if (sbsf->addr_bytes <
388                                         SF_ADDR_LEN + sbsf->pad_addr_bytes)
389                                 break;
390
391                         /* Next state! */
392                         if (os_lseek(sbsf->fd, sbsf->off, OS_SEEK_SET) < 0) {
393                                 puts("sandbox_sf: os_lseek() failed");
394                                 return -EIO;
395                         }
396                         switch (sbsf->cmd) {
397                         case CMD_READ_ARRAY_FAST:
398                         case CMD_READ_ARRAY_SLOW:
399                                 sbsf->state = SF_READ;
400                                 break;
401                         case CMD_PAGE_PROGRAM:
402                                 sbsf->state = SF_WRITE;
403                                 break;
404                         default:
405                                 /* assume erase state ... */
406                                 sbsf->state = SF_ERASE;
407                                 goto case_sf_erase;
408                         }
409                         debug(" cmd: transition to %s state\n",
410                               sandbox_sf_state_name(sbsf->state));
411                         break;
412                 case SF_READ:
413                         /*
414                          * XXX: need to handle exotic behavior:
415                          *      - reading past end of device
416                          */
417
418                         cnt = bytes - pos;
419                         debug(" tx: read(%u)\n", cnt);
420                         assert(tx);
421                         ret = os_read(sbsf->fd, tx + pos, cnt);
422                         if (ret < 0) {
423                                 puts("sandbox_sf: os_read() failed\n");
424                                 return -EIO;
425                         }
426                         pos += ret;
427                         break;
428                 case SF_READ_STATUS:
429                         debug(" read status: %#x\n", sbsf->status);
430                         cnt = bytes - pos;
431                         memset(tx + pos, sbsf->status, cnt);
432                         pos += cnt;
433                         break;
434                 case SF_READ_STATUS1:
435                         debug(" read status: %#x\n", sbsf->status);
436                         cnt = bytes - pos;
437                         memset(tx + pos, sbsf->status >> 8, cnt);
438                         pos += cnt;
439                         break;
440                 case SF_WRITE_STATUS:
441                         debug(" write status: %#x (ignored)\n", rx[pos]);
442                         pos = bytes;
443                         break;
444                 case SF_WRITE:
445                         /*
446                          * XXX: need to handle exotic behavior:
447                          *      - unaligned addresses
448                          *      - more than a page (256) worth of data
449                          *      - reading past end of device
450                          */
451                         if (!(sbsf->status & STAT_WEL)) {
452                                 puts("sandbox_sf: write enable not set before write\n");
453                                 goto done;
454                         }
455
456                         cnt = bytes - pos;
457                         debug(" rx: write(%u)\n", cnt);
458                         if (tx)
459                                 sandbox_spi_tristate(&tx[pos], cnt);
460                         ret = os_write(sbsf->fd, rx + pos, cnt);
461                         if (ret < 0) {
462                                 puts("sandbox_spi: os_write() failed\n");
463                                 return -EIO;
464                         }
465                         pos += ret;
466                         sbsf->status &= ~STAT_WEL;
467                         break;
468                 case SF_ERASE:
469  case_sf_erase: {
470                         if (!(sbsf->status & STAT_WEL)) {
471                                 puts("sandbox_sf: write enable not set before erase\n");
472                                 goto done;
473                         }
474
475                         /* verify address is aligned */
476                         if (sbsf->off & (sbsf->erase_size - 1)) {
477                                 debug(" sector erase: cmd:%#x needs align:%#x, but we got %#x\n",
478                                       sbsf->cmd, sbsf->erase_size,
479                                       sbsf->off);
480                                 sbsf->status &= ~STAT_WEL;
481                                 goto done;
482                         }
483
484                         debug(" sector erase addr: %u, size: %u\n", sbsf->off,
485                               sbsf->erase_size);
486
487                         cnt = bytes - pos;
488                         if (tx)
489                                 sandbox_spi_tristate(&tx[pos], cnt);
490                         pos += cnt;
491
492                         /*
493                          * TODO(vapier@gentoo.org): latch WIP in status, and
494                          * delay before clearing it ?
495                          */
496                         ret = sandbox_erase_part(sbsf, sbsf->erase_size);
497                         sbsf->status &= ~STAT_WEL;
498                         if (ret) {
499                                 debug("sandbox_sf: Erase failed\n");
500                                 goto done;
501                         }
502                         goto done;
503                 }
504                 default:
505                         debug(" ??? no idea what to do ???\n");
506                         goto done;
507                 }
508         }
509
510  done:
511         if (flags & SPI_XFER_END)
512                 sandbox_sf_cs_deactivate(dev);
513         return pos == bytes ? 0 : -EIO;
514 }
515
516 int sandbox_sf_ofdata_to_platdata(struct udevice *dev)
517 {
518         struct sandbox_spi_flash_plat_data *pdata = dev_get_platdata(dev);
519         const void *blob = gd->fdt_blob;
520         int node = dev->of_offset;
521
522         pdata->filename = fdt_getprop(blob, node, "sandbox,filename", NULL);
523         pdata->device_name = fdt_getprop(blob, node, "compatible", NULL);
524         if (!pdata->filename || !pdata->device_name) {
525                 debug("%s: Missing properties, filename=%s, device_name=%s\n",
526                       __func__, pdata->filename, pdata->device_name);
527                 return -EINVAL;
528         }
529
530         return 0;
531 }
532
533 static const struct dm_spi_emul_ops sandbox_sf_emul_ops = {
534         .xfer          = sandbox_sf_xfer,
535 };
536
537 #ifdef CONFIG_SPI_FLASH
538 static int sandbox_cmdline_cb_spi_sf(struct sandbox_state *state,
539                                      const char *arg)
540 {
541         unsigned long bus, cs;
542         const char *spec = sandbox_spi_parse_spec(arg, &bus, &cs);
543
544         if (!spec)
545                 return 1;
546
547         /*
548          * It is safe to not make a copy of 'spec' because it comes from the
549          * command line.
550          *
551          * TODO(sjg@chromium.org): It would be nice if we could parse the
552          * spec here, but the problem is that no U-Boot init has been done
553          * yet. Perhaps we can figure something out.
554          */
555         state->spi[bus][cs].spec = spec;
556         return 0;
557 }
558 SANDBOX_CMDLINE_OPT(spi_sf, 1, "connect a SPI flash: <bus>:<cs>:<id>:<file>");
559
560 int sandbox_sf_bind_emul(struct sandbox_state *state, int busnum, int cs,
561                          struct udevice *bus, int of_offset, const char *spec)
562 {
563         struct udevice *emul;
564         char name[20], *str;
565         struct driver *drv;
566         int ret;
567
568         /* now the emulator */
569         strncpy(name, spec, sizeof(name) - 6);
570         name[sizeof(name) - 6] = '\0';
571         strcat(name, "-emul");
572         str = strdup(name);
573         if (!str)
574                 return -ENOMEM;
575         drv = lists_driver_lookup_name("sandbox_sf_emul");
576         if (!drv) {
577                 puts("Cannot find sandbox_sf_emul driver\n");
578                 return -ENOENT;
579         }
580         ret = device_bind(bus, drv, str, NULL, of_offset, &emul);
581         if (ret) {
582                 printf("Cannot create emul device for spec '%s' (err=%d)\n",
583                        spec, ret);
584                 return ret;
585         }
586         state->spi[busnum][cs].emul = emul;
587
588         return 0;
589 }
590
591 void sandbox_sf_unbind_emul(struct sandbox_state *state, int busnum, int cs)
592 {
593         struct udevice *dev;
594
595         dev = state->spi[busnum][cs].emul;
596         device_remove(dev);
597         device_unbind(dev);
598         state->spi[busnum][cs].emul = NULL;
599 }
600
601 static int sandbox_sf_bind_bus_cs(struct sandbox_state *state, int busnum,
602                                   int cs, const char *spec)
603 {
604         struct udevice *bus, *slave;
605         int ret;
606
607         ret = uclass_find_device_by_seq(UCLASS_SPI, busnum, true, &bus);
608         if (ret) {
609                 printf("Invalid bus %d for spec '%s' (err=%d)\n", busnum,
610                        spec, ret);
611                 return ret;
612         }
613         ret = spi_find_chip_select(bus, cs, &slave);
614         if (!ret) {
615                 printf("Chip select %d already exists for spec '%s'\n", cs,
616                        spec);
617                 return -EEXIST;
618         }
619
620         ret = device_bind_driver(bus, "spi_flash_std", spec, &slave);
621         if (ret)
622                 return ret;
623
624         return sandbox_sf_bind_emul(state, busnum, cs, bus, -1, spec);
625 }
626
627 int sandbox_spi_get_emul(struct sandbox_state *state,
628                          struct udevice *bus, struct udevice *slave,
629                          struct udevice **emulp)
630 {
631         struct sandbox_spi_info *info;
632         int busnum = bus->seq;
633         int cs = spi_chip_select(slave);
634         int ret;
635
636         info = &state->spi[busnum][cs];
637         if (!info->emul) {
638                 /* Use the same device tree node as the SPI flash device */
639                 debug("%s: busnum=%u, cs=%u: binding SPI flash emulation: ",
640                       __func__, busnum, cs);
641                 ret = sandbox_sf_bind_emul(state, busnum, cs, bus,
642                                            slave->of_offset, slave->name);
643                 if (ret) {
644                         debug("failed (err=%d)\n", ret);
645                         return ret;
646                 }
647                 debug("OK\n");
648         }
649         *emulp = info->emul;
650
651         return 0;
652 }
653
654 int dm_scan_other(bool pre_reloc_only)
655 {
656         struct sandbox_state *state = state_get_current();
657         int busnum, cs;
658
659         if (pre_reloc_only)
660                 return 0;
661         for (busnum = 0; busnum < CONFIG_SANDBOX_SPI_MAX_BUS; busnum++) {
662                 for (cs = 0; cs < CONFIG_SANDBOX_SPI_MAX_CS; cs++) {
663                         const char *spec = state->spi[busnum][cs].spec;
664                         int ret;
665
666                         if (spec) {
667                                 ret = sandbox_sf_bind_bus_cs(state, busnum,
668                                                              cs, spec);
669                                 if (ret) {
670                                         debug("%s: Bind failed for bus %d, cs %d\n",
671                                               __func__, busnum, cs);
672                                         return ret;
673                                 }
674                         }
675                 }
676         }
677
678         return 0;
679 }
680 #endif
681
682 static const struct udevice_id sandbox_sf_ids[] = {
683         { .compatible = "sandbox,spi-flash" },
684         { }
685 };
686
687 U_BOOT_DRIVER(sandbox_sf_emul) = {
688         .name           = "sandbox_sf_emul",
689         .id             = UCLASS_SPI_EMUL,
690         .of_match       = sandbox_sf_ids,
691         .ofdata_to_platdata = sandbox_sf_ofdata_to_platdata,
692         .probe          = sandbox_sf_probe,
693         .remove         = sandbox_sf_remove,
694         .priv_auto_alloc_size = sizeof(struct sandbox_spi_flash),
695         .platdata_auto_alloc_size = sizeof(struct sandbox_spi_flash_plat_data),
696         .ops            = &sandbox_sf_emul_ops,
697 };