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