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