Home | History | Annotate | Line # | Download | only in spi
spiflash.c revision 1.14
      1 /* $NetBSD: spiflash.c,v 1.14 2014/07/25 08:02:20 dholland Exp $ */
      2 
      3 /*-
      4  * Copyright (c) 2006 Urbana-Champaign Independent Media Center.
      5  * Copyright (c) 2006 Garrett D'Amore.
      6  * All rights reserved.
      7  *
      8  * Portions of this code were written by Garrett D'Amore for the
      9  * Champaign-Urbana Community Wireless Network Project.
     10  *
     11  * Redistribution and use in source and binary forms, with or
     12  * without modification, are permitted provided that the following
     13  * conditions are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above
     17  *    copyright notice, this list of conditions and the following
     18  *    disclaimer in the documentation and/or other materials provided
     19  *    with the distribution.
     20  * 3. All advertising materials mentioning features or use of this
     21  *    software must display the following acknowledgements:
     22  *      This product includes software developed by the Urbana-Champaign
     23  *      Independent Media Center.
     24  *	This product includes software developed by Garrett D'Amore.
     25  * 4. Urbana-Champaign Independent Media Center's name and Garrett
     26  *    D'Amore's name may not be used to endorse or promote products
     27  *    derived from this software without specific prior written permission.
     28  *
     29  * THIS SOFTWARE IS PROVIDED BY THE URBANA-CHAMPAIGN INDEPENDENT
     30  * MEDIA CENTER AND GARRETT D'AMORE ``AS IS'' AND ANY EXPRESS OR
     31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
     32  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE URBANA-CHAMPAIGN INDEPENDENT
     34  * MEDIA CENTER OR GARRETT D'AMORE BE LIABLE FOR ANY DIRECT, INDIRECT,
     35  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     36  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     37  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
     38  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
     39  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     40  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
     41  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     42  */
     43 
     44 #include <sys/cdefs.h>
     45 __KERNEL_RCSID(0, "$NetBSD: spiflash.c,v 1.14 2014/07/25 08:02:20 dholland Exp $");
     46 
     47 #include <sys/param.h>
     48 #include <sys/conf.h>
     49 #include <sys/proc.h>
     50 #include <sys/systm.h>
     51 #include <sys/device.h>
     52 #include <sys/kernel.h>
     53 #include <sys/file.h>
     54 #include <sys/ioctl.h>
     55 #include <sys/disk.h>
     56 #include <sys/disklabel.h>
     57 #include <sys/buf.h>
     58 #include <sys/bufq.h>
     59 #include <sys/uio.h>
     60 #include <sys/kthread.h>
     61 #include <sys/malloc.h>
     62 #include <sys/errno.h>
     63 
     64 #include <dev/spi/spivar.h>
     65 #include <dev/spi/spiflash.h>
     66 
     67 /*
     68  * This is an MI block driver for SPI flash devices.  It could probably be
     69  * converted to some more generic framework, if someone wanted to create one
     70  * for NOR flashes.  Note that some flashes have the ability to handle
     71  * interrupts.
     72  */
     73 
     74 struct spiflash_softc {
     75 	struct disk		sc_dk;
     76 
     77 	struct spiflash_hw_if	sc_hw;
     78 	void			*sc_cookie;
     79 
     80 	const char		*sc_name;
     81 	struct spi_handle	*sc_handle;
     82 	int			sc_device_size;
     83 	int			sc_write_size;
     84 	int			sc_erase_size;
     85 	int			sc_read_size;
     86 	int			sc_device_blks;
     87 
     88 	struct bufq_state	*sc_waitq;
     89 	struct bufq_state	*sc_workq;
     90 	struct bufq_state	*sc_doneq;
     91 	lwp_t			*sc_thread;
     92 };
     93 
     94 #define	sc_getname	sc_hw.sf_getname
     95 #define	sc_gethandle	sc_hw.sf_gethandle
     96 #define	sc_getsize	sc_hw.sf_getsize
     97 #define	sc_getflags	sc_hw.sf_getflags
     98 #define	sc_erase	sc_hw.sf_erase
     99 #define	sc_write	sc_hw.sf_write
    100 #define	sc_read		sc_hw.sf_read
    101 #define	sc_getstatus	sc_hw.sf_getstatus
    102 #define	sc_setstatus	sc_hw.sf_setstatus
    103 
    104 struct spiflash_attach_args {
    105 	const struct spiflash_hw_if	*hw;
    106 	void				*cookie;
    107 };
    108 
    109 #define	STATIC
    110 STATIC int spiflash_match(device_t , cfdata_t , void *);
    111 STATIC void spiflash_attach(device_t , device_t , void *);
    112 STATIC int spiflash_print(void *, const char *);
    113 STATIC int spiflash_common_erase(spiflash_handle_t, size_t, size_t);
    114 STATIC int spiflash_common_write(spiflash_handle_t, size_t, size_t,
    115     const uint8_t *);
    116 STATIC int spiflash_common_read(spiflash_handle_t, size_t, size_t, uint8_t *);
    117 STATIC void spiflash_process_done(spiflash_handle_t, int);
    118 STATIC void spiflash_process_read(spiflash_handle_t);
    119 STATIC void spiflash_process_write(spiflash_handle_t);
    120 STATIC void spiflash_thread(void *);
    121 STATIC int spiflash_nsectors(spiflash_handle_t, struct buf *);
    122 STATIC int spiflash_nsectors(spiflash_handle_t, struct buf *);
    123 STATIC int spiflash_sector(spiflash_handle_t, struct buf *);
    124 
    125 CFATTACH_DECL_NEW(spiflash, sizeof(struct spiflash_softc),
    126 	      spiflash_match, spiflash_attach, NULL, NULL);
    127 
    128 #ifdef	SPIFLASH_DEBUG
    129 #define	DPRINTF(x)	do { printf x; } while (0/*CONSTCOND*/)
    130 #else
    131 #define	DPRINTF(x)	do {  } while (0/*CONSTCOND*/)
    132 #endif
    133 
    134 extern struct cfdriver spiflash_cd;
    135 
    136 dev_type_open(spiflash_open);
    137 dev_type_close(spiflash_close);
    138 dev_type_read(spiflash_read);
    139 dev_type_write(spiflash_write);
    140 dev_type_ioctl(spiflash_ioctl);
    141 dev_type_strategy(spiflash_strategy);
    142 
    143 const struct bdevsw spiflash_bdevsw = {
    144 	.d_open = spiflash_open,
    145 	.d_close = spiflash_close,
    146 	.d_strategy = spiflash_strategy,
    147 	.d_ioctl = spiflash_ioctl,
    148 	.d_dump = nodump,
    149 	.d_psize = nosize,
    150 	.d_discard = nodiscard,
    151 	.d_flag = D_DISK,
    152 };
    153 
    154 const struct cdevsw spiflash_cdevsw = {
    155 	.d_open = spiflash_open,
    156 	.d_close = spiflash_close,
    157 	.d_read = spiflash_read,
    158 	.d_write = spiflash_write,
    159 	.d_ioctl = spiflash_ioctl,
    160 	.d_stop = nostop,
    161 	.d_tty = notty,
    162 	.d_poll = nopoll,
    163 	.d_mmap = nommap,
    164 	.d_kqfilter = nokqfilter,
    165 	.d_flag = D_DISK,
    166 };
    167 
    168 static struct dkdriver spiflash_dkdriver = { spiflash_strategy, NULL };
    169 
    170 spiflash_handle_t
    171 spiflash_attach_mi(const struct spiflash_hw_if *hw, void *cookie,
    172     device_t dev)
    173 {
    174 	struct spiflash_attach_args sfa;
    175 	sfa.hw = hw;
    176 	sfa.cookie = cookie;
    177 
    178 	return (spiflash_handle_t)config_found(dev, &sfa, spiflash_print);
    179 }
    180 
    181 int
    182 spiflash_print(void *aux, const char *pnp)
    183 {
    184 	if (pnp != NULL)
    185 		printf("spiflash at %s\n", pnp);
    186 
    187 	return UNCONF;
    188 }
    189 
    190 int
    191 spiflash_match(device_t parent, cfdata_t cf, void *aux)
    192 {
    193 
    194 	return 1;
    195 }
    196 
    197 void
    198 spiflash_attach(device_t parent, device_t self, void *aux)
    199 {
    200 	struct spiflash_softc *sc = device_private(self);
    201 	struct spiflash_attach_args *sfa = aux;
    202 	void *cookie = sfa->cookie;
    203 
    204 	sc->sc_hw = *sfa->hw;
    205 	sc->sc_cookie = cookie;
    206 	sc->sc_name = sc->sc_getname(cookie);
    207 	sc->sc_handle = sc->sc_gethandle(cookie);
    208 	sc->sc_device_size = sc->sc_getsize(cookie, SPIFLASH_SIZE_DEVICE);
    209 	sc->sc_erase_size = sc->sc_getsize(cookie, SPIFLASH_SIZE_ERASE);
    210 	sc->sc_write_size = sc->sc_getsize(cookie, SPIFLASH_SIZE_WRITE);
    211 	sc->sc_read_size = sc->sc_getsize(cookie, SPIFLASH_SIZE_READ);
    212 	sc->sc_device_blks = sc->sc_device_size / DEV_BSIZE;
    213 
    214 	if (sc->sc_read == NULL)
    215 		sc->sc_read = spiflash_common_read;
    216 	if (sc->sc_write == NULL)
    217 		sc->sc_write = spiflash_common_write;
    218 	if (sc->sc_erase == NULL)
    219 		sc->sc_erase = spiflash_common_erase;
    220 
    221 	aprint_naive(": SPI flash\n");
    222 	aprint_normal(": %s SPI flash\n", sc->sc_name);
    223 	/* XXX: note that this has to change for boot-sectored flash */
    224 	aprint_normal_dev(self, "%d KB, %d sectors of %d KB each\n",
    225 	    sc->sc_device_size / 1024,
    226 	    sc->sc_device_size / sc->sc_erase_size,
    227 	    sc->sc_erase_size / 1024);
    228 
    229 	/* first-come first-served strategy works best for us */
    230 	bufq_alloc(&sc->sc_waitq, "fcfs", BUFQ_SORT_RAWBLOCK);
    231 	bufq_alloc(&sc->sc_workq, "fcfs", BUFQ_SORT_RAWBLOCK);
    232 	bufq_alloc(&sc->sc_doneq, "fcfs", BUFQ_SORT_RAWBLOCK);
    233 
    234 	sc->sc_dk.dk_driver = &spiflash_dkdriver;
    235 	sc->sc_dk.dk_name = device_xname(self);
    236 
    237 	disk_attach(&sc->sc_dk);
    238 
    239 	/* arrange to allocate the kthread */
    240 	kthread_create(PRI_NONE, 0, NULL, spiflash_thread, sc,
    241 	    &sc->sc_thread, "spiflash");
    242 }
    243 
    244 int
    245 spiflash_open(dev_t dev, int flags, int mode, struct lwp *l)
    246 {
    247 	spiflash_handle_t sc;
    248 
    249 	sc = device_lookup_private(&spiflash_cd, DISKUNIT(dev));
    250 	if (sc == NULL)
    251 		return ENXIO;
    252 
    253 	/*
    254 	 * XXX: We need to handle partitions here.  The problem is
    255 	 * that it isn't entirely clear to me how to deal with this.
    256 	 * There are devices that could be used "in the raw" with a
    257 	 * NetBSD label, but then you get into devices that have other
    258 	 * kinds of data on them -- some have VxWorks data, some have
    259 	 * RedBoot data, and some have other contraints -- for example
    260 	 * some devices might have a portion that is read-only,
    261 	 * whereas others might have a portion that is read-write.
    262 	 *
    263 	 * For now we just permit access to the entire device.
    264 	 */
    265 	return 0;
    266 }
    267 
    268 int
    269 spiflash_close(dev_t dev, int flags, int mode, struct lwp *l)
    270 {
    271 	spiflash_handle_t sc;
    272 
    273 	sc = device_lookup_private(&spiflash_cd, DISKUNIT(dev));
    274 	if (sc == NULL)
    275 		return ENXIO;
    276 
    277 	return 0;
    278 }
    279 
    280 int
    281 spiflash_read(dev_t dev, struct uio *uio, int ioflag)
    282 {
    283 
    284 	return physio(spiflash_strategy, NULL, dev, B_READ, minphys, uio);
    285 }
    286 
    287 int
    288 spiflash_write(dev_t dev, struct uio *uio, int ioflag)
    289 {
    290 
    291 	return physio(spiflash_strategy, NULL, dev, B_WRITE, minphys, uio);
    292 }
    293 
    294 int
    295 spiflash_ioctl(dev_t dev, u_long cmd, void *data, int flags, struct lwp *l)
    296 {
    297 	spiflash_handle_t sc;
    298 
    299 	sc = device_lookup_private(&spiflash_cd, DISKUNIT(dev));
    300 	if (sc == NULL)
    301 		return ENXIO;
    302 
    303 	return EINVAL;
    304 }
    305 
    306 void
    307 spiflash_strategy(struct buf *bp)
    308 {
    309 	spiflash_handle_t sc;
    310 	int	s;
    311 
    312 	sc = device_lookup_private(&spiflash_cd, DISKUNIT(bp->b_dev));
    313 	if (sc == NULL) {
    314 		bp->b_error = ENXIO;
    315 		biodone(bp);
    316 		return;
    317 	}
    318 
    319 	if (((bp->b_bcount % sc->sc_write_size) != 0) ||
    320 	    (bp->b_blkno < 0)) {
    321 		bp->b_error = EINVAL;
    322 		biodone(bp);
    323 		return;
    324 	}
    325 
    326 	/* no work? */
    327 	if (bp->b_bcount == 0) {
    328 		biodone(bp);
    329 		return;
    330 	}
    331 
    332 	if (bounds_check_with_mediasize(bp, DEV_BSIZE,
    333 		sc->sc_device_blks) <= 0) {
    334 		biodone(bp);
    335 		return;
    336 	}
    337 
    338 	bp->b_resid = bp->b_bcount;
    339 
    340 	/* all ready, hand off to thread for async processing */
    341 	s = splbio();
    342 	bufq_put(sc->sc_waitq, bp);
    343 	wakeup(&sc->sc_thread);
    344 	splx(s);
    345 }
    346 
    347 void
    348 spiflash_process_done(spiflash_handle_t sc, int err)
    349 {
    350 	struct buf	*bp;
    351 	int		cnt = 0;
    352 	int		flag = 0;
    353 
    354 	while ((bp = bufq_get(sc->sc_doneq)) != NULL) {
    355 		flag = bp->b_flags & B_READ;
    356 		if ((bp->b_error = err) == 0)
    357 			bp->b_resid = 0;
    358 		cnt += bp->b_bcount - bp->b_resid;
    359 		biodone(bp);
    360 	}
    361 	disk_unbusy(&sc->sc_dk, cnt, flag);
    362 }
    363 
    364 void
    365 spiflash_process_read(spiflash_handle_t sc)
    366 {
    367 	struct buf	*bp;
    368 	int		err = 0;
    369 
    370 	disk_busy(&sc->sc_dk);
    371 	while ((bp = bufq_get(sc->sc_workq)) != NULL) {
    372 		size_t addr = bp->b_blkno * DEV_BSIZE;
    373 		uint8_t *data = bp->b_data;
    374 		int cnt = bp->b_resid;
    375 
    376 		bufq_put(sc->sc_doneq, bp);
    377 
    378 		DPRINTF(("read from addr %x, cnt %d\n", (unsigned)addr, cnt));
    379 
    380 		if ((err = sc->sc_read(sc, addr, cnt, data)) != 0) {
    381 			/* error occurred, fail all pending workq bufs */
    382 			bufq_move(sc->sc_doneq, sc->sc_workq);
    383 			break;
    384 		}
    385 
    386 		bp->b_resid -= cnt;
    387 		data += cnt;
    388 		addr += cnt;
    389 	}
    390 	spiflash_process_done(sc, err);
    391 }
    392 
    393 void
    394 spiflash_process_write(spiflash_handle_t sc)
    395 {
    396 	int	len;
    397 	size_t	base;
    398 	daddr_t	blkno;
    399 	uint8_t	*save;
    400 	int	err = 0, neederase = 0;
    401 	struct buf *bp;
    402 
    403 	/*
    404 	 * due to other considerations, we are guaranteed that
    405 	 * we will only have multiple buffers if they are all in
    406 	 * the same erase sector.  Therefore we never need to look
    407 	 * beyond the first block to determine how much data we need
    408 	 * to save.
    409 	 */
    410 
    411 	bp = bufq_peek(sc->sc_workq);
    412 	len = spiflash_nsectors(sc, bp)  * sc->sc_erase_size;
    413 	blkno = bp->b_blkno;
    414 	base = (blkno * DEV_BSIZE) & ~ (sc->sc_erase_size - 1);
    415 
    416 	/* get ourself a scratch buffer */
    417 	save = malloc(len, M_DEVBUF, M_WAITOK);
    418 
    419 	disk_busy(&sc->sc_dk);
    420 	/* read in as much of the data as we need */
    421 	DPRINTF(("reading in %d bytes\n", len));
    422 	if ((err = sc->sc_read(sc, base, len, save)) != 0) {
    423 		bufq_move(sc->sc_doneq, sc->sc_workq);
    424 		spiflash_process_done(sc, err);
    425 		return;
    426 	}
    427 
    428 	/*
    429 	 * now coalesce the writes into the save area, but also
    430 	 * check to see if we need to do an erase
    431 	 */
    432 	while ((bp = bufq_get(sc->sc_workq)) != NULL) {
    433 		uint8_t	*data, *dst;
    434 		int resid = bp->b_resid;
    435 
    436 		DPRINTF(("coalesce write, blkno %x, count %d, resid %d\n",
    437 			    (unsigned)bp->b_blkno, bp->b_bcount, resid));
    438 
    439 		data = bp->b_data;
    440 		dst = save + (bp->b_blkno * DEV_BSIZE) - base;
    441 
    442 		/*
    443 		 * NOR flash bits.  We can clear a bit, but we cannot
    444 		 * set a bit, without erasing.  This should help reduce
    445 		 * unnecessary erases.
    446 		 */
    447 		while (resid) {
    448 			if ((*data) & ~(*dst))
    449 				neederase = 1;
    450 			*dst++ = *data++;
    451 			resid--;
    452 		}
    453 
    454 		bufq_put(sc->sc_doneq, bp);
    455 	}
    456 
    457 	/*
    458 	 * do the erase, if we need to.
    459 	 */
    460 	if (neederase) {
    461 		DPRINTF(("erasing from %zx - %zx\n", base, base + len));
    462 		if ((err = sc->sc_erase(sc, base, len)) != 0) {
    463 			spiflash_process_done(sc, err);
    464 			return;
    465 		}
    466 	}
    467 
    468 	/*
    469 	 * now write our save area, and finish up.
    470 	 */
    471 	DPRINTF(("flashing %d bytes to %zx from %p\n", len, base, save));
    472 	err = sc->sc_write(sc, base, len, save);
    473 	spiflash_process_done(sc, err);
    474 }
    475 
    476 
    477 int
    478 spiflash_nsectors(spiflash_handle_t sc, struct buf *bp)
    479 {
    480 	unsigned	addr, sector;
    481 
    482 	addr = bp->b_blkno * DEV_BSIZE;
    483 	sector = addr / sc->sc_erase_size;
    484 
    485 	addr += bp->b_bcount;
    486 	addr--;
    487 	return (((addr / sc->sc_erase_size)  - sector) + 1);
    488 }
    489 
    490 int
    491 spiflash_sector(spiflash_handle_t sc, struct buf *bp)
    492 {
    493 	unsigned	addr, sector;
    494 
    495 	addr = bp->b_blkno * DEV_BSIZE;
    496 	sector = addr / sc->sc_erase_size;
    497 
    498 	/* if it spans multiple blocks, error it */
    499 	addr += bp->b_bcount;
    500 	addr--;
    501 	if (sector != (addr / sc->sc_erase_size))
    502 		return -1;
    503 
    504 	return sector;
    505 }
    506 
    507 void
    508 spiflash_thread(void *arg)
    509 {
    510 	spiflash_handle_t sc = arg;
    511 	struct buf	*bp;
    512 	int		sector;
    513 
    514 	(void)splbio();
    515 	for (;;) {
    516 		if ((bp = bufq_get(sc->sc_waitq)) == NULL) {
    517 			tsleep(&sc->sc_thread, PRIBIO, "spiflash_thread", 0);
    518 			continue;
    519 		}
    520 
    521 		bufq_put(sc->sc_workq, bp);
    522 
    523 		if (bp->b_flags & B_READ) {
    524 			/* just do the read */
    525 			spiflash_process_read(sc);
    526 			continue;
    527 		}
    528 
    529 		/*
    530 		 * Because writing a flash filesystem is particularly
    531 		 * painful, involving erase, modify, write, we prefer
    532 		 * to coalesce writes to the same sector together.
    533 		 */
    534 
    535 		sector = spiflash_sector(sc, bp);
    536 
    537 		/*
    538 		 * if the write spans multiple sectors, skip
    539 		 * coalescing.  (It would be nice if we could break
    540 		 * these up.  minphys is honored for read/write, but
    541 		 * not necessarily for bread.)
    542 		 */
    543 		if (sector < 0)
    544 			goto dowrite;
    545 
    546 		while ((bp = bufq_peek(sc->sc_waitq)) != NULL) {
    547 			/* can't deal with read requests! */
    548 			if (bp->b_flags & B_READ)
    549 				break;
    550 
    551 			/* is it for the same sector? */
    552 			if (spiflash_sector(sc, bp) != sector)
    553 				break;
    554 
    555 			bp = bufq_get(sc->sc_waitq);
    556 			bufq_put(sc->sc_workq, bp);
    557 		}
    558 
    559 	dowrite:
    560 		spiflash_process_write(sc);
    561 	}
    562 }
    563 /*
    564  * SPI flash common implementation.
    565  */
    566 
    567 /*
    568  * Most devices take on the order of 1 second for each block that they
    569  * delete.
    570  */
    571 int
    572 spiflash_common_erase(spiflash_handle_t sc, size_t start, size_t size)
    573 {
    574 	int		rv;
    575 
    576 	if ((start % sc->sc_erase_size) || (size % sc->sc_erase_size))
    577 		return EINVAL;
    578 
    579 	/* the second test is to test against wrap */
    580 	if ((start > sc->sc_device_size) ||
    581 	    ((start + size) > sc->sc_device_size))
    582 		return EINVAL;
    583 
    584 	/*
    585 	 * XXX: check protection status?  Requires master table mapping
    586 	 * sectors to status bits, and so forth.
    587 	 */
    588 
    589 	while (size) {
    590 		if ((rv = spiflash_write_enable(sc)) != 0) {
    591 			spiflash_write_disable(sc);
    592 			return rv;
    593 		}
    594 		if ((rv = spiflash_cmd(sc, SPIFLASH_CMD_ERASE, 3, start, 0,
    595 			 NULL, NULL)) != 0) {
    596 			spiflash_write_disable(sc);
    597 			return rv;
    598 		}
    599 
    600 		/*
    601 		 * The devices I have all say typical for sector erase
    602 		 * is ~1sec.  We check ten times that often.  (There
    603 		 * is no way to interrupt on this.)
    604 		 */
    605 		if ((rv = spiflash_wait(sc, hz / 10)) != 0)
    606 			return rv;
    607 
    608 		start += sc->sc_erase_size;
    609 		size -= sc->sc_erase_size;
    610 
    611 		/* NB: according to the docs I have, the write enable
    612 		 * is automatically cleared upon completion of an erase
    613 		 * command, so there is no need to explicitly disable it.
    614 		 */
    615 	}
    616 
    617 	return 0;
    618 }
    619 
    620 int
    621 spiflash_common_write(spiflash_handle_t sc, size_t start, size_t size,
    622     const uint8_t *data)
    623 {
    624 	int		rv;
    625 
    626 	if ((start % sc->sc_write_size) || (size % sc->sc_write_size))
    627 		return EINVAL;
    628 
    629 	while (size) {
    630 		int cnt;
    631 
    632 		if ((rv = spiflash_write_enable(sc)) != 0) {
    633 			spiflash_write_disable(sc);
    634 			return rv;
    635 		}
    636 
    637 		cnt = min(size, sc->sc_write_size);
    638 		if ((rv = spiflash_cmd(sc, SPIFLASH_CMD_PROGRAM, 3, start,
    639 			 cnt, data, NULL)) != 0) {
    640 			spiflash_write_disable(sc);
    641 			return rv;
    642 		}
    643 
    644 		/*
    645 		 * It seems that most devices can write bits fairly
    646 		 * quickly.  For example, one part I have access to
    647 		 * takes ~5msec to process the entire 256 byte page.
    648 		 * Probably this should be modified to cope with
    649 		 * device-specific timing, and maybe also take into
    650 		 * account systems with higher values of HZ (which
    651 		 * could benefit from sleeping.)
    652 		 */
    653 		if ((rv = spiflash_wait(sc, 0)) != 0)
    654 			return rv;
    655 
    656 		data += cnt;
    657 		start += cnt;
    658 		size -= cnt;
    659 	}
    660 
    661 	return 0;
    662 }
    663 
    664 int
    665 spiflash_common_read(spiflash_handle_t sc, size_t start, size_t size,
    666     uint8_t *data)
    667 {
    668 	int		rv;
    669 
    670 	while (size) {
    671 		int cnt;
    672 
    673 		if (sc->sc_read_size > 0)
    674 			cnt = min(size, sc->sc_read_size);
    675 		else
    676 			cnt = size;
    677 
    678 		if ((rv = spiflash_cmd(sc, SPIFLASH_CMD_READ, 3, start,
    679 			 cnt, NULL, data)) != 0) {
    680 			return rv;
    681 		}
    682 
    683 		start += cnt;
    684 		size -= cnt;
    685 	}
    686 
    687 	return 0;
    688 }
    689 
    690 /* read status register */
    691 int
    692 spiflash_read_status(spiflash_handle_t sc, uint8_t *sr)
    693 {
    694 
    695 	return spiflash_cmd(sc, SPIFLASH_CMD_RDSR, 0, 0, 1, NULL, sr);
    696 }
    697 
    698 int
    699 spiflash_write_enable(spiflash_handle_t sc)
    700 {
    701 
    702 	return spiflash_cmd(sc, SPIFLASH_CMD_WREN, 0, 0, 0, NULL, NULL);
    703 }
    704 
    705 int
    706 spiflash_write_disable(spiflash_handle_t sc)
    707 {
    708 
    709 	return spiflash_cmd(sc, SPIFLASH_CMD_WRDI, 0, 0, 0, NULL, NULL);
    710 }
    711 
    712 int
    713 spiflash_cmd(spiflash_handle_t sc, uint8_t cmd,
    714     size_t addrlen, uint32_t addr,
    715     size_t cnt, const uint8_t *wdata, uint8_t *rdata)
    716 {
    717 	struct spi_transfer	trans;
    718 	struct spi_chunk	chunk1, chunk2;
    719 	char buf[4];
    720 	int i;
    721 
    722 	buf[0] = cmd;
    723 
    724 	if (addrlen > 3)
    725 		return EINVAL;
    726 
    727 	for (i = addrlen; i > 0; i--) {
    728 		buf[i] = addr & 0xff;
    729 		addr >>= 8;
    730 	}
    731 	spi_transfer_init(&trans);
    732 	spi_chunk_init(&chunk1, addrlen + 1, buf, NULL);
    733 	spi_transfer_add(&trans, &chunk1);
    734 	if (cnt) {
    735 		spi_chunk_init(&chunk2, cnt, wdata, rdata);
    736 		spi_transfer_add(&trans, &chunk2);
    737 	}
    738 
    739 	spi_transfer(sc->sc_handle, &trans);
    740 	spi_wait(&trans);
    741 
    742 	if (trans.st_flags & SPI_F_ERROR)
    743 		return trans.st_errno;
    744 	return 0;
    745 }
    746 
    747 int
    748 spiflash_wait(spiflash_handle_t sc, int tmo)
    749 {
    750 	int	rv;
    751 	uint8_t	sr;
    752 
    753 	for (;;) {
    754 		if ((rv = spiflash_read_status(sc, &sr)) != 0)
    755 			return rv;
    756 
    757 		if ((sr & SPIFLASH_SR_BUSY) == 0)
    758 			break;
    759 		/*
    760 		 * The devices I have all say typical for sector
    761 		 * erase is ~1sec.  We check time times that often.
    762 		 * (There is no way to interrupt on this.)
    763 		 */
    764 		if (tmo)
    765 			tsleep(&sr, PWAIT, "spiflash_wait", tmo);
    766 	}
    767 	return 0;
    768 }
    769