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