xref: /freebsd/sys/dev/flash/at45d.c (revision d0b2dbfa)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2011-2012 Ian Lepore All rights reserved.
5  * Copyright (c) 2012 Marius Strobl <marius@FreeBSD.org> All rights reserved.
6  * Copyright (c) 2006 M. Warner Losh <imp@FreeBSD.org>
7 
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/bio.h>
33 #include <sys/bus.h>
34 #include <sys/conf.h>
35 #include <sys/endian.h>
36 #include <sys/kernel.h>
37 #include <sys/kthread.h>
38 #include <sys/lock.h>
39 #include <sys/mbuf.h>
40 #include <sys/malloc.h>
41 #include <sys/module.h>
42 #include <sys/mutex.h>
43 #include <geom/geom_disk.h>
44 
45 #include <dev/spibus/spi.h>
46 #include "spibus_if.h"
47 
48 #include "opt_platform.h"
49 
50 #ifdef FDT
51 #include <dev/fdt/fdt_common.h>
52 #include <dev/ofw/ofw_bus_subr.h>
53 #include <dev/ofw/openfirm.h>
54 
55 static struct ofw_compat_data compat_data[] = {
56 	{ "atmel,at45",		1 },
57 	{ "atmel,dataflash",	1 },
58 	{ NULL,			0 },
59 };
60 #endif
61 
62 /* This is the information returned by the MANUFACTURER_ID command. */
63 struct at45d_mfg_info {
64 	uint32_t	jedec_id; /* Mfg ID, DevId1, DevId2, ExtLen */
65 	uint16_t	ext_id;   /* ExtId1, ExtId2 */
66 };
67 
68 /*
69  * This is an entry in our table of metadata describing the chips.  We match on
70  * both jedec id and extended id info returned by the MANUFACTURER_ID command.
71  */
72 struct at45d_flash_ident
73 {
74 	const char	*name;
75 	uint32_t	jedec;
76 	uint16_t	extid;
77 	uint16_t	extmask;
78 	uint16_t	pagecount;
79 	uint16_t	pageoffset;
80 	uint16_t	pagesize;
81 	uint16_t	pagesize2n;
82 };
83 
84 struct at45d_softc
85 {
86 	struct bio_queue_head	bio_queue;
87 	struct mtx		sc_mtx;
88 	struct disk		*disk;
89 	struct proc		*p;
90 	device_t		dev;
91 	u_int			taskstate;
92 	uint16_t		pagecount;
93 	uint16_t		pageoffset;
94 	uint16_t		pagesize;
95 	void			*dummybuf;
96 };
97 
98 #define	TSTATE_STOPPED	0
99 #define	TSTATE_STOPPING	1
100 #define	TSTATE_RUNNING	2
101 
102 #define	AT45D_LOCK(_sc)			mtx_lock(&(_sc)->sc_mtx)
103 #define	AT45D_UNLOCK(_sc)		mtx_unlock(&(_sc)->sc_mtx)
104 #define	AT45D_LOCK_INIT(_sc) \
105 	mtx_init(&_sc->sc_mtx, device_get_nameunit(_sc->dev), \
106 	    "at45d", MTX_DEF)
107 #define	AT45D_LOCK_DESTROY(_sc)		mtx_destroy(&_sc->sc_mtx);
108 #define	AT45D_ASSERT_LOCKED(_sc)	mtx_assert(&_sc->sc_mtx, MA_OWNED);
109 #define	AT45D_ASSERT_UNLOCKED(_sc)	mtx_assert(&_sc->sc_mtx, MA_NOTOWNED);
110 
111 /* bus entry points */
112 static device_attach_t at45d_attach;
113 static device_detach_t at45d_detach;
114 static device_probe_t at45d_probe;
115 
116 /* disk routines */
117 static int at45d_close(struct disk *dp);
118 static int at45d_open(struct disk *dp);
119 static int at45d_getattr(struct bio *bp);
120 static void at45d_strategy(struct bio *bp);
121 static void at45d_task(void *arg);
122 
123 /* helper routines */
124 static void at45d_delayed_attach(void *xsc);
125 static int at45d_get_mfg_info(device_t dev, struct at45d_mfg_info *resp);
126 static int at45d_get_status(device_t dev, uint8_t *status);
127 static int at45d_wait_ready(device_t dev, uint8_t *status);
128 
129 #define	PAGE_TO_BUFFER_TRANSFER		0x53
130 #define	PAGE_TO_BUFFER_COMPARE		0x60
131 #define	PROGRAM_THROUGH_BUFFER		0x82
132 #define	MANUFACTURER_ID			0x9f
133 #define	STATUS_REGISTER_READ		0xd7
134 #define	CONTINUOUS_ARRAY_READ		0xe8
135 
136 #define	STATUS_READY			(1u << 7)
137 #define	STATUS_CMPFAIL			(1u << 6)
138 #define	STATUS_PAGE2N			(1u << 0)
139 
140 /*
141  * Metadata for supported chips.
142  *
143  * The jedec id in this table includes the extended id length byte.  A match is
144  * based on both jedec id and extended id matching.  The chip's extended id (not
145  * present in most chips) is ANDed with ExtMask and the result is compared to
146  * ExtId.  If a chip only returns 1 ext id byte it will be in the upper 8 bits
147  * of ExtId in this table.
148  *
149  * A sectorsize2n != 0 is used to indicate that a device optionally supports
150  * 2^N byte pages.  If support for the latter is enabled, the sector offset
151  * has to be reduced by one.
152  */
153 static const struct at45d_flash_ident at45d_flash_devices[] = {
154 	/* Part Name    Jedec ID    ExtId   ExtMask PgCnt Offs PgSz PgSz2n */
155 	{ "AT45DB011B", 0x1f220000, 0x0000, 0x0000,   512,  9,  264,  256 },
156 	{ "AT45DB021B", 0x1f230000, 0x0000, 0x0000,  1024,  9,  264,  256 },
157 	{ "AT45DB041x", 0x1f240000, 0x0000, 0x0000,  2028,  9,  264,  256 },
158 	{ "AT45DB081B", 0x1f250000, 0x0000, 0x0000,  4096,  9,  264,  256 },
159 	{ "AT45DB161x", 0x1f260000, 0x0000, 0x0000,  4096, 10,  528,  512 },
160 	{ "AT45DB321x", 0x1f270000, 0x0000, 0x0000,  8192, 10,  528,    0 },
161 	{ "AT45DB321x", 0x1f270100, 0x0000, 0x0000,  8192, 10,  528,  512 },
162 	{ "AT45DB641E", 0x1f280001, 0x0000, 0xff00, 32768,  9,  264,  256 },
163 	{ "AT45DB642x", 0x1f280000, 0x0000, 0x0000,  8192, 11, 1056, 1024 },
164 };
165 
166 static int
167 at45d_get_status(device_t dev, uint8_t *status)
168 {
169 	uint8_t rxBuf[8], txBuf[8];
170 	struct spi_command cmd;
171 	int err;
172 
173 	memset(&cmd, 0, sizeof(cmd));
174 	memset(txBuf, 0, sizeof(txBuf));
175 	memset(rxBuf, 0, sizeof(rxBuf));
176 
177 	txBuf[0] = STATUS_REGISTER_READ;
178 	cmd.tx_cmd = txBuf;
179 	cmd.rx_cmd = rxBuf;
180 	cmd.rx_cmd_sz = cmd.tx_cmd_sz = 2;
181 	err = SPIBUS_TRANSFER(device_get_parent(dev), dev, &cmd);
182 	*status = rxBuf[1];
183 	return (err);
184 }
185 
186 static int
187 at45d_get_mfg_info(device_t dev, struct at45d_mfg_info *resp)
188 {
189 	uint8_t rxBuf[8], txBuf[8];
190 	struct spi_command cmd;
191 	int err;
192 
193 	memset(&cmd, 0, sizeof(cmd));
194 	memset(txBuf, 0, sizeof(txBuf));
195 	memset(rxBuf, 0, sizeof(rxBuf));
196 
197 	txBuf[0] = MANUFACTURER_ID;
198 	cmd.tx_cmd = &txBuf;
199 	cmd.rx_cmd = &rxBuf;
200 	cmd.tx_cmd_sz = cmd.rx_cmd_sz = 7;
201 	err = SPIBUS_TRANSFER(device_get_parent(dev), dev, &cmd);
202 	if (err)
203 		return (err);
204 
205 	resp->jedec_id = be32dec(rxBuf + 1);
206 	resp->ext_id   = be16dec(rxBuf + 5);
207 
208 	return (0);
209 }
210 
211 static int
212 at45d_wait_ready(device_t dev, uint8_t *status)
213 {
214 	struct timeval now, tout;
215 	int err;
216 
217 	getmicrouptime(&tout);
218 	tout.tv_sec += 3;
219 	do {
220 		getmicrouptime(&now);
221 		if (now.tv_sec > tout.tv_sec)
222 			err = ETIMEDOUT;
223 		else
224 			err = at45d_get_status(dev, status);
225 	} while (err == 0 && !(*status & STATUS_READY));
226 	return (err);
227 }
228 
229 static int
230 at45d_probe(device_t dev)
231 {
232 	int rv;
233 
234 #ifdef FDT
235 	if (!ofw_bus_status_okay(dev))
236 		return (ENXIO);
237 
238 	if (ofw_bus_search_compatible(dev, compat_data)->ocd_data == 0)
239 		return (ENXIO);
240 
241 	rv = BUS_PROBE_DEFAULT;
242 #else
243 	rv = BUS_PROBE_NOWILDCARD;
244 #endif
245 
246 	device_set_desc(dev, "AT45D Flash Family");
247 	return (rv);
248 }
249 
250 static int
251 at45d_attach(device_t dev)
252 {
253 	struct at45d_softc *sc;
254 
255 	sc = device_get_softc(dev);
256 	sc->dev = dev;
257 	AT45D_LOCK_INIT(sc);
258 
259 	config_intrhook_oneshot(at45d_delayed_attach, sc);
260 	return (0);
261 }
262 
263 static int
264 at45d_detach(device_t dev)
265 {
266 	struct at45d_softc *sc;
267 	int err;
268 
269 	sc = device_get_softc(dev);
270 	err = 0;
271 
272 	AT45D_LOCK(sc);
273 	if (sc->taskstate == TSTATE_RUNNING) {
274 		sc->taskstate = TSTATE_STOPPING;
275 		wakeup(sc);
276 		while (err == 0 && sc->taskstate != TSTATE_STOPPED) {
277 			err = msleep(sc, &sc->sc_mtx, 0, "at45dt", hz * 3);
278 			if (err != 0) {
279 				sc->taskstate = TSTATE_RUNNING;
280 				device_printf(sc->dev,
281 				    "Failed to stop queue task\n");
282 			}
283 		}
284 	}
285 	AT45D_UNLOCK(sc);
286 
287 	if (err == 0 && sc->taskstate == TSTATE_STOPPED) {
288 		if (sc->disk) {
289 			disk_destroy(sc->disk);
290 			bioq_flush(&sc->bio_queue, NULL, ENXIO);
291 			free(sc->dummybuf, M_DEVBUF);
292 		}
293 		AT45D_LOCK_DESTROY(sc);
294 	}
295 	return (err);
296 }
297 
298 static void
299 at45d_delayed_attach(void *xsc)
300 {
301 	struct at45d_softc *sc;
302 	struct at45d_mfg_info mfginfo;
303 	const struct at45d_flash_ident *ident;
304 	u_int i;
305 	int sectorsize;
306 	uint32_t jedec;
307 	uint16_t pagesize;
308 	uint8_t status;
309 
310 	sc = xsc;
311 	ident = NULL;
312 	jedec = 0;
313 
314 	if (at45d_wait_ready(sc->dev, &status) != 0) {
315 		device_printf(sc->dev, "Error waiting for device-ready.\n");
316 		return;
317 	}
318 	if (at45d_get_mfg_info(sc->dev, &mfginfo) != 0) {
319 		device_printf(sc->dev, "Failed to get ID.\n");
320 		return;
321 	}
322 	for (i = 0; i < nitems(at45d_flash_devices); i++) {
323 		ident = &at45d_flash_devices[i];
324 		if (mfginfo.jedec_id == ident->jedec &&
325 		    (mfginfo.ext_id & ident->extmask) == ident->extid) {
326 			break;
327 		}
328 	}
329 	if (i == nitems(at45d_flash_devices)) {
330 		device_printf(sc->dev, "JEDEC 0x%x not in list.\n", jedec);
331 		return;
332 	}
333 
334 	sc->pagecount = ident->pagecount;
335 	sc->pageoffset = ident->pageoffset;
336 	if (ident->pagesize2n != 0 && (status & STATUS_PAGE2N)) {
337 		sc->pageoffset -= 1;
338 		pagesize = ident->pagesize2n;
339 	} else
340 		pagesize = ident->pagesize;
341 	sc->pagesize = pagesize;
342 
343 	/*
344 	 * By default we set up a disk with a sector size that matches the
345 	 * device page size.  If there is a device hint or fdt property
346 	 * requesting a different size, use that, as long as it is a multiple of
347 	 * the device page size).
348 	 */
349 	sectorsize = pagesize;
350 #ifdef FDT
351 	{
352 		pcell_t size;
353 		if (OF_getencprop(ofw_bus_get_node(sc->dev),
354 		    "freebsd,sectorsize", &size, sizeof(size)) > 0)
355 			sectorsize = size;
356 	}
357 #endif
358 	resource_int_value(device_get_name(sc->dev), device_get_unit(sc->dev),
359 	    "sectorsize", &sectorsize);
360 
361 	if ((sectorsize % pagesize) != 0) {
362 		device_printf(sc->dev, "Invalid sectorsize %d, "
363 		    "must be a multiple of %d\n", sectorsize, pagesize);
364 		return;
365 	}
366 
367 	sc->dummybuf = malloc(pagesize, M_DEVBUF, M_WAITOK | M_ZERO);
368 
369 	sc->disk = disk_alloc();
370 	sc->disk->d_open = at45d_open;
371 	sc->disk->d_close = at45d_close;
372 	sc->disk->d_strategy = at45d_strategy;
373 	sc->disk->d_getattr = at45d_getattr;
374 	sc->disk->d_name = "flash/at45d";
375 	sc->disk->d_drv1 = sc;
376 	sc->disk->d_maxsize = DFLTPHYS;
377 	sc->disk->d_sectorsize = sectorsize;
378 	sc->disk->d_mediasize = pagesize * ident->pagecount;
379 	sc->disk->d_unit = device_get_unit(sc->dev);
380 	disk_create(sc->disk, DISK_VERSION);
381 	bioq_init(&sc->bio_queue);
382 	kproc_create(&at45d_task, sc, &sc->p, 0, 0, "task: at45d flash");
383 	sc->taskstate = TSTATE_RUNNING;
384 	device_printf(sc->dev,
385 	    "%s, %d bytes per page, %d pages; %d KBytes; disk sector size %d\n",
386 	    ident->name, pagesize, ident->pagecount,
387 	    (pagesize * ident->pagecount) / 1024, sectorsize);
388 }
389 
390 static int
391 at45d_open(struct disk *dp)
392 {
393 
394 	return (0);
395 }
396 
397 static int
398 at45d_close(struct disk *dp)
399 {
400 
401 	return (0);
402 }
403 
404 static int
405 at45d_getattr(struct bio *bp)
406 {
407 	struct at45d_softc *sc;
408 
409 	/*
410 	 * This function exists to support geom_flashmap and fdt_slicer.
411 	 */
412 
413 	if (bp->bio_disk == NULL || bp->bio_disk->d_drv1 == NULL)
414 		return (ENXIO);
415 	if (strcmp(bp->bio_attribute, "SPI::device") != 0)
416 		return (-1);
417 	sc = bp->bio_disk->d_drv1;
418 	if (bp->bio_length != sizeof(sc->dev))
419 		return (EFAULT);
420 	bcopy(&sc->dev, bp->bio_data, sizeof(sc->dev));
421 	return (0);
422 }
423 
424 static void
425 at45d_strategy(struct bio *bp)
426 {
427 	struct at45d_softc *sc;
428 
429 	sc = (struct at45d_softc *)bp->bio_disk->d_drv1;
430 	AT45D_LOCK(sc);
431 	bioq_disksort(&sc->bio_queue, bp);
432 	wakeup(sc);
433 	AT45D_UNLOCK(sc);
434 }
435 
436 static void
437 at45d_task(void *arg)
438 {
439 	uint8_t rxBuf[8], txBuf[8];
440 	struct at45d_softc *sc;
441 	struct bio *bp;
442 	struct spi_command cmd;
443 	device_t dev, pdev;
444 	caddr_t buf;
445 	u_long len, resid;
446 	u_int addr, berr, err, offset, page;
447 	uint8_t status;
448 
449 	sc = (struct at45d_softc*)arg;
450 	dev = sc->dev;
451 	pdev = device_get_parent(dev);
452 	memset(&cmd, 0, sizeof(cmd));
453 	memset(txBuf, 0, sizeof(txBuf));
454 	memset(rxBuf, 0, sizeof(rxBuf));
455 	cmd.tx_cmd = txBuf;
456 	cmd.rx_cmd = rxBuf;
457 
458 	for (;;) {
459 		AT45D_LOCK(sc);
460 		do {
461 			if (sc->taskstate == TSTATE_STOPPING) {
462 				sc->taskstate = TSTATE_STOPPED;
463 				AT45D_UNLOCK(sc);
464 				wakeup(sc);
465 				kproc_exit(0);
466 			}
467 			bp = bioq_takefirst(&sc->bio_queue);
468 			if (bp == NULL)
469 				msleep(sc, &sc->sc_mtx, PRIBIO, "at45dq", 0);
470 		} while (bp == NULL);
471 		AT45D_UNLOCK(sc);
472 
473 		berr = 0;
474 		buf = bp->bio_data;
475 		len = resid = bp->bio_bcount;
476 		page = bp->bio_offset / sc->pagesize;
477 		offset = bp->bio_offset % sc->pagesize;
478 
479 		switch (bp->bio_cmd) {
480 		case BIO_READ:
481 			txBuf[0] = CONTINUOUS_ARRAY_READ;
482 			cmd.tx_cmd_sz = cmd.rx_cmd_sz = 8;
483 			cmd.tx_data = sc->dummybuf;
484 			cmd.rx_data = buf;
485 			break;
486 		case BIO_WRITE:
487 			cmd.tx_cmd_sz = cmd.rx_cmd_sz = 4;
488 			cmd.tx_data = buf;
489 			cmd.rx_data = sc->dummybuf;
490 			if (resid + offset > sc->pagesize)
491 				len = sc->pagesize - offset;
492 			break;
493 		default:
494 			berr = EOPNOTSUPP;
495 			goto out;
496 		}
497 
498 		/*
499 		 * NB: for BIO_READ, this loop is only traversed once.
500 		 */
501 		while (resid > 0) {
502 			if (page > sc->pagecount) {
503 				berr = EINVAL;
504 				goto out;
505 			}
506 			addr = page << sc->pageoffset;
507 			if (bp->bio_cmd == BIO_WRITE) {
508 				/*
509 				 * If writing less than a full page, transfer
510 				 * the existing page to the buffer, so that our
511 				 * PROGRAM_THROUGH_BUFFER below will preserve
512 				 * the parts of the page we're not writing.
513 				 */
514 				if (len != sc->pagesize) {
515 					txBuf[0] = PAGE_TO_BUFFER_TRANSFER;
516 					txBuf[1] = ((addr >> 16) & 0xff);
517 					txBuf[2] = ((addr >> 8) & 0xff);
518 					txBuf[3] = 0;
519 					cmd.tx_data_sz = cmd.rx_data_sz = 0;
520 					err = SPIBUS_TRANSFER(pdev, dev, &cmd);
521 					if (err == 0)
522 						err = at45d_wait_ready(dev,
523 						    &status);
524 					if (err != 0) {
525 						berr = EIO;
526 						goto out;
527 					}
528 				}
529 				txBuf[0] = PROGRAM_THROUGH_BUFFER;
530 			}
531 
532 			addr += offset;
533 			txBuf[1] = ((addr >> 16) & 0xff);
534 			txBuf[2] = ((addr >> 8) & 0xff);
535 			txBuf[3] = (addr & 0xff);
536 			cmd.tx_data_sz = cmd.rx_data_sz = len;
537 			err = SPIBUS_TRANSFER(pdev, dev, &cmd);
538 			if (err == 0 && bp->bio_cmd != BIO_READ)
539 				err = at45d_wait_ready(dev, &status);
540 			if (err != 0) {
541 				berr = EIO;
542 				goto out;
543 			}
544 			if (bp->bio_cmd == BIO_WRITE) {
545 				addr = page << sc->pageoffset;
546 				txBuf[0] = PAGE_TO_BUFFER_COMPARE;
547 				txBuf[1] = ((addr >> 16) & 0xff);
548 				txBuf[2] = ((addr >> 8) & 0xff);
549 				txBuf[3] = 0;
550 				cmd.tx_data_sz = cmd.rx_data_sz = 0;
551 				err = SPIBUS_TRANSFER(pdev, dev, &cmd);
552 				if (err == 0)
553 					err = at45d_wait_ready(dev, &status);
554 				if (err != 0 || (status & STATUS_CMPFAIL)) {
555 					device_printf(dev, "comparing page "
556 					    "%d failed (status=0x%x)\n", page,
557 					    status);
558 					berr = EIO;
559 					goto out;
560 				}
561 			}
562 			page++;
563 			buf += len;
564 			offset = 0;
565 			resid -= len;
566 			if (resid > sc->pagesize)
567 				len = sc->pagesize;
568 			else
569 				len = resid;
570 			if (bp->bio_cmd == BIO_READ)
571 				cmd.rx_data = buf;
572 			else
573 				cmd.tx_data = buf;
574 		}
575  out:
576 		if (berr != 0) {
577 			bp->bio_flags |= BIO_ERROR;
578 			bp->bio_error = berr;
579 		}
580 		bp->bio_resid = resid;
581 		biodone(bp);
582 	}
583 }
584 
585 static device_method_t at45d_methods[] = {
586 	/* Device interface */
587 	DEVMETHOD(device_probe,		at45d_probe),
588 	DEVMETHOD(device_attach,	at45d_attach),
589 	DEVMETHOD(device_detach,	at45d_detach),
590 
591 	DEVMETHOD_END
592 };
593 
594 static driver_t at45d_driver = {
595 	"at45d",
596 	at45d_methods,
597 	sizeof(struct at45d_softc),
598 };
599 
600 DRIVER_MODULE(at45d, spibus, at45d_driver, NULL, NULL);
601 MODULE_DEPEND(at45d, spibus, 1, 1, 1);
602 #ifdef FDT
603 MODULE_DEPEND(at45d, fdt_slicer, 1, 1, 1);
604 SPIBUS_FDT_PNP_INFO(compat_data);
605 #endif
606 
607