xref: /openbmc/u-boot/drivers/mtd/spi/sandbox.c (revision 55d39911)
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 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'\n",
133 		       dev->name);
134 		return -EINVAL;
135 	}
136 	debug("found at cs %d\n", cs);
137 
138 	if (!pdata->filename) {
139 		printf("Error: No filename available\n");
140 		return -EINVAL;
141 	}
142 	spec = strchr(pdata->device_name, ',');
143 	if (spec)
144 		spec++;
145 	else
146 		spec = pdata->device_name;
147 	idname_len = strlen(spec);
148 	debug("%s: device='%s'\n", __func__, spec);
149 
150 	for (data = spi_flash_ids; data->name; data++) {
151 		len = strlen(data->name);
152 		if (idname_len != len)
153 			continue;
154 		if (!strncasecmp(spec, data->name, len))
155 			break;
156 	}
157 	if (!data->name) {
158 		printf("%s: unknown flash '%*s'\n", __func__, (int)idname_len,
159 		       spec);
160 		ret = -EINVAL;
161 		goto error;
162 	}
163 
164 	if (sandbox_sf_0xff[0] == 0x00)
165 		memset(sandbox_sf_0xff, 0xff, sizeof(sandbox_sf_0xff));
166 
167 	sbsf->fd = os_open(pdata->filename, 02);
168 	if (sbsf->fd == -1) {
169 		printf("%s: unable to open file '%s'\n", __func__,
170 		       pdata->filename);
171 		ret = -EIO;
172 		goto error;
173 	}
174 
175 	sbsf->data = data;
176 	sbsf->cs = cs;
177 
178 	return 0;
179 
180  error:
181 	debug("%s: Got error %d\n", __func__, ret);
182 	return ret;
183 }
184 
185 static int sandbox_sf_remove(struct udevice *dev)
186 {
187 	struct sandbox_spi_flash *sbsf = dev_get_priv(dev);
188 
189 	os_close(sbsf->fd);
190 
191 	return 0;
192 }
193 
194 static void sandbox_sf_cs_activate(struct udevice *dev)
195 {
196 	struct sandbox_spi_flash *sbsf = dev_get_priv(dev);
197 
198 	log_content("sandbox_sf: CS activated; state is fresh!\n");
199 
200 	/* CS is asserted, so reset state */
201 	sbsf->off = 0;
202 	sbsf->addr_bytes = 0;
203 	sbsf->pad_addr_bytes = 0;
204 	sbsf->state = SF_CMD;
205 	sbsf->cmd = SF_CMD;
206 }
207 
208 static void sandbox_sf_cs_deactivate(struct udevice *dev)
209 {
210 	log_content("sandbox_sf: CS deactivated; cmd done processing!\n");
211 }
212 
213 /*
214  * There are times when the data lines are allowed to tristate.  What
215  * is actually sensed on the line depends on the hardware.  It could
216  * always be 0xFF/0x00 (if there are pull ups/downs), or things could
217  * float and so we'd get garbage back.  This func encapsulates that
218  * scenario so we can worry about the details here.
219  */
220 static void sandbox_spi_tristate(u8 *buf, uint len)
221 {
222 	/* XXX: make this into a user config option ? */
223 	memset(buf, 0xff, len);
224 }
225 
226 /* Figure out what command this stream is telling us to do */
227 static int sandbox_sf_process_cmd(struct sandbox_spi_flash *sbsf, const u8 *rx,
228 				  u8 *tx)
229 {
230 	enum sandbox_sf_state oldstate = sbsf->state;
231 
232 	/* We need to output a byte for the cmd byte we just ate */
233 	if (tx)
234 		sandbox_spi_tristate(tx, 1);
235 
236 	sbsf->cmd = rx[0];
237 	switch (sbsf->cmd) {
238 	case CMD_READ_ID:
239 		sbsf->state = SF_ID;
240 		sbsf->cmd = SF_ID;
241 		break;
242 	case CMD_READ_ARRAY_FAST:
243 		sbsf->pad_addr_bytes = 1;
244 	case CMD_READ_ARRAY_SLOW:
245 	case CMD_PAGE_PROGRAM:
246 		sbsf->state = SF_ADDR;
247 		break;
248 	case CMD_WRITE_DISABLE:
249 		debug(" write disabled\n");
250 		sbsf->status &= ~STAT_WEL;
251 		break;
252 	case CMD_READ_STATUS:
253 		sbsf->state = SF_READ_STATUS;
254 		break;
255 	case CMD_READ_STATUS1:
256 		sbsf->state = SF_READ_STATUS1;
257 		break;
258 	case CMD_WRITE_ENABLE:
259 		debug(" write enabled\n");
260 		sbsf->status |= STAT_WEL;
261 		break;
262 	case CMD_WRITE_STATUS:
263 		sbsf->state = SF_WRITE_STATUS;
264 		break;
265 	default: {
266 		int flags = sbsf->data->flags;
267 
268 		/* we only support erase here */
269 		if (sbsf->cmd == CMD_ERASE_CHIP) {
270 			sbsf->erase_size = sbsf->data->sector_size *
271 				sbsf->data->n_sectors;
272 		} else if (sbsf->cmd == CMD_ERASE_4K && (flags & SECT_4K)) {
273 			sbsf->erase_size = 4 << 10;
274 		} else if (sbsf->cmd == CMD_ERASE_64K && !(flags & SECT_4K)) {
275 			sbsf->erase_size = 64 << 10;
276 		} else {
277 			debug(" cmd unknown: %#x\n", sbsf->cmd);
278 			return -EIO;
279 		}
280 		sbsf->state = SF_ADDR;
281 		break;
282 	}
283 	}
284 
285 	if (oldstate != sbsf->state)
286 		log_content(" cmd: transition to %s state\n",
287 			    sandbox_sf_state_name(sbsf->state));
288 
289 	return 0;
290 }
291 
292 int sandbox_erase_part(struct sandbox_spi_flash *sbsf, int size)
293 {
294 	int todo;
295 	int ret;
296 
297 	while (size > 0) {
298 		todo = min(size, (int)sizeof(sandbox_sf_0xff));
299 		ret = os_write(sbsf->fd, sandbox_sf_0xff, todo);
300 		if (ret != todo)
301 			return ret;
302 		size -= todo;
303 	}
304 
305 	return 0;
306 }
307 
308 static int sandbox_sf_xfer(struct udevice *dev, unsigned int bitlen,
309 			   const void *rxp, void *txp, unsigned long flags)
310 {
311 	struct sandbox_spi_flash *sbsf = dev_get_priv(dev);
312 	const uint8_t *rx = rxp;
313 	uint8_t *tx = txp;
314 	uint cnt, pos = 0;
315 	int bytes = bitlen / 8;
316 	int ret;
317 
318 	log_content("sandbox_sf: state:%x(%s) bytes:%u\n", sbsf->state,
319 		    sandbox_sf_state_name(sbsf->state), bytes);
320 
321 	if ((flags & SPI_XFER_BEGIN))
322 		sandbox_sf_cs_activate(dev);
323 
324 	if (sbsf->state == SF_CMD) {
325 		/* Figure out the initial state */
326 		ret = sandbox_sf_process_cmd(sbsf, rx, tx);
327 		if (ret)
328 			return ret;
329 		++pos;
330 	}
331 
332 	/* Process the remaining data */
333 	while (pos < bytes) {
334 		switch (sbsf->state) {
335 		case SF_ID: {
336 			u8 id;
337 
338 			log_content(" id: off:%u tx:", sbsf->off);
339 			if (sbsf->off < IDCODE_LEN) {
340 				/* Extract correct byte from ID 0x00aabbcc */
341 				id = ((JEDEC_MFR(sbsf->data) << 16) |
342 					JEDEC_ID(sbsf->data)) >>
343 					(8 * (IDCODE_LEN - 1 - sbsf->off));
344 			} else {
345 				id = 0;
346 			}
347 			log_content("%d %02x\n", sbsf->off, id);
348 			tx[pos++] = id;
349 			++sbsf->off;
350 			break;
351 		}
352 		case SF_ADDR:
353 			log_content(" addr: bytes:%u rx:%02x ",
354 				    sbsf->addr_bytes, rx[pos]);
355 
356 			if (sbsf->addr_bytes++ < SF_ADDR_LEN)
357 				sbsf->off = (sbsf->off << 8) | rx[pos];
358 			log_content("addr:%06x\n", sbsf->off);
359 
360 			if (tx)
361 				sandbox_spi_tristate(&tx[pos], 1);
362 			pos++;
363 
364 			/* See if we're done processing */
365 			if (sbsf->addr_bytes <
366 					SF_ADDR_LEN + sbsf->pad_addr_bytes)
367 				break;
368 
369 			/* Next state! */
370 			if (os_lseek(sbsf->fd, sbsf->off, OS_SEEK_SET) < 0) {
371 				puts("sandbox_sf: os_lseek() failed");
372 				return -EIO;
373 			}
374 			switch (sbsf->cmd) {
375 			case CMD_READ_ARRAY_FAST:
376 			case CMD_READ_ARRAY_SLOW:
377 				sbsf->state = SF_READ;
378 				break;
379 			case CMD_PAGE_PROGRAM:
380 				sbsf->state = SF_WRITE;
381 				break;
382 			default:
383 				/* assume erase state ... */
384 				sbsf->state = SF_ERASE;
385 				goto case_sf_erase;
386 			}
387 			log_content(" cmd: transition to %s state\n",
388 				    sandbox_sf_state_name(sbsf->state));
389 			break;
390 		case SF_READ:
391 			/*
392 			 * XXX: need to handle exotic behavior:
393 			 *      - reading past end of device
394 			 */
395 
396 			cnt = bytes - pos;
397 			log_content(" tx: read(%u)\n", cnt);
398 			assert(tx);
399 			ret = os_read(sbsf->fd, tx + pos, cnt);
400 			if (ret < 0) {
401 				puts("sandbox_sf: os_read() failed\n");
402 				return -EIO;
403 			}
404 			pos += ret;
405 			break;
406 		case SF_READ_STATUS:
407 			log_content(" read status: %#x\n", sbsf->status);
408 			cnt = bytes - pos;
409 			memset(tx + pos, sbsf->status, cnt);
410 			pos += cnt;
411 			break;
412 		case SF_READ_STATUS1:
413 			log_content(" read status: %#x\n", sbsf->status);
414 			cnt = bytes - pos;
415 			memset(tx + pos, sbsf->status >> 8, cnt);
416 			pos += cnt;
417 			break;
418 		case SF_WRITE_STATUS:
419 			log_content(" write status: %#x (ignored)\n", rx[pos]);
420 			pos = bytes;
421 			break;
422 		case SF_WRITE:
423 			/*
424 			 * XXX: need to handle exotic behavior:
425 			 *      - unaligned addresses
426 			 *      - more than a page (256) worth of data
427 			 *      - reading past end of device
428 			 */
429 			if (!(sbsf->status & STAT_WEL)) {
430 				puts("sandbox_sf: write enable not set before write\n");
431 				goto done;
432 			}
433 
434 			cnt = bytes - pos;
435 			log_content(" rx: write(%u)\n", cnt);
436 			if (tx)
437 				sandbox_spi_tristate(&tx[pos], cnt);
438 			ret = os_write(sbsf->fd, rx + pos, cnt);
439 			if (ret < 0) {
440 				puts("sandbox_spi: os_write() failed\n");
441 				return -EIO;
442 			}
443 			pos += ret;
444 			sbsf->status &= ~STAT_WEL;
445 			break;
446 		case SF_ERASE:
447  case_sf_erase: {
448 			if (!(sbsf->status & STAT_WEL)) {
449 				puts("sandbox_sf: write enable not set before erase\n");
450 				goto done;
451 			}
452 
453 			/* verify address is aligned */
454 			if (sbsf->off & (sbsf->erase_size - 1)) {
455 				log_content(" sector erase: cmd:%#x needs align:%#x, but we got %#x\n",
456 					    sbsf->cmd, sbsf->erase_size,
457 					    sbsf->off);
458 				sbsf->status &= ~STAT_WEL;
459 				goto done;
460 			}
461 
462 			log_content(" sector erase addr: %u, size: %u\n",
463 				    sbsf->off, sbsf->erase_size);
464 
465 			cnt = bytes - pos;
466 			if (tx)
467 				sandbox_spi_tristate(&tx[pos], cnt);
468 			pos += cnt;
469 
470 			/*
471 			 * TODO(vapier@gentoo.org): latch WIP in status, and
472 			 * delay before clearing it ?
473 			 */
474 			ret = sandbox_erase_part(sbsf, sbsf->erase_size);
475 			sbsf->status &= ~STAT_WEL;
476 			if (ret) {
477 				log_content("sandbox_sf: Erase failed\n");
478 				goto done;
479 			}
480 			goto done;
481 		}
482 		default:
483 			log_content(" ??? no idea what to do ???\n");
484 			goto done;
485 		}
486 	}
487 
488  done:
489 	if (flags & SPI_XFER_END)
490 		sandbox_sf_cs_deactivate(dev);
491 	return pos == bytes ? 0 : -EIO;
492 }
493 
494 int sandbox_sf_ofdata_to_platdata(struct udevice *dev)
495 {
496 	struct sandbox_spi_flash_plat_data *pdata = dev_get_platdata(dev);
497 
498 	pdata->filename = dev_read_string(dev, "sandbox,filename");
499 	pdata->device_name = dev_read_string(dev, "compatible");
500 	if (!pdata->filename || !pdata->device_name) {
501 		debug("%s: Missing properties, filename=%s, device_name=%s\n",
502 		      __func__, pdata->filename, pdata->device_name);
503 		return -EINVAL;
504 	}
505 
506 	return 0;
507 }
508 
509 static const struct dm_spi_emul_ops sandbox_sf_emul_ops = {
510 	.xfer          = sandbox_sf_xfer,
511 };
512 
513 #ifdef CONFIG_SPI_FLASH
514 int sandbox_sf_bind_emul(struct sandbox_state *state, int busnum, int cs,
515 			 struct udevice *bus, ofnode node, const char *spec)
516 {
517 	struct udevice *emul;
518 	char name[20], *str;
519 	struct driver *drv;
520 	int ret;
521 
522 	/* now the emulator */
523 	strncpy(name, spec, sizeof(name) - 6);
524 	name[sizeof(name) - 6] = '\0';
525 	strcat(name, "-emul");
526 	drv = lists_driver_lookup_name("sandbox_sf_emul");
527 	if (!drv) {
528 		puts("Cannot find sandbox_sf_emul driver\n");
529 		return -ENOENT;
530 	}
531 	str = strdup(name);
532 	if (!str)
533 		return -ENOMEM;
534 	ret = device_bind_ofnode(bus, drv, str, NULL, node, &emul);
535 	if (ret) {
536 		free(str);
537 		printf("Cannot create emul device for spec '%s' (err=%d)\n",
538 		       spec, ret);
539 		return ret;
540 	}
541 	state->spi[busnum][cs].emul = emul;
542 
543 	return 0;
544 }
545 
546 void sandbox_sf_unbind_emul(struct sandbox_state *state, int busnum, int cs)
547 {
548 	struct udevice *dev;
549 
550 	dev = state->spi[busnum][cs].emul;
551 	device_remove(dev, DM_REMOVE_NORMAL);
552 	device_unbind(dev);
553 	state->spi[busnum][cs].emul = NULL;
554 }
555 
556 int sandbox_spi_get_emul(struct sandbox_state *state,
557 			 struct udevice *bus, struct udevice *slave,
558 			 struct udevice **emulp)
559 {
560 	struct sandbox_spi_info *info;
561 	int busnum = bus->seq;
562 	int cs = spi_chip_select(slave);
563 	int ret;
564 
565 	info = &state->spi[busnum][cs];
566 	if (!info->emul) {
567 		/* Use the same device tree node as the SPI flash device */
568 		debug("%s: busnum=%u, cs=%u: binding SPI flash emulation: ",
569 		      __func__, busnum, cs);
570 		ret = sandbox_sf_bind_emul(state, busnum, cs, bus,
571 					   dev_ofnode(slave), slave->name);
572 		if (ret) {
573 			debug("failed (err=%d)\n", ret);
574 			return ret;
575 		}
576 		debug("OK\n");
577 	}
578 	*emulp = info->emul;
579 
580 	return 0;
581 }
582 #endif
583 
584 static const struct udevice_id sandbox_sf_ids[] = {
585 	{ .compatible = "sandbox,spi-flash" },
586 	{ }
587 };
588 
589 U_BOOT_DRIVER(sandbox_sf_emul) = {
590 	.name		= "sandbox_sf_emul",
591 	.id		= UCLASS_SPI_EMUL,
592 	.of_match	= sandbox_sf_ids,
593 	.ofdata_to_platdata = sandbox_sf_ofdata_to_platdata,
594 	.probe		= sandbox_sf_probe,
595 	.remove		= sandbox_sf_remove,
596 	.priv_auto_alloc_size = sizeof(struct sandbox_spi_flash),
597 	.platdata_auto_alloc_size = sizeof(struct sandbox_spi_flash_plat_data),
598 	.ops		= &sandbox_sf_emul_ops,
599 };
600