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