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