xref: /dragonfly/sys/dev/disk/mmcsd/mmcsd.c (revision b58f1e66)
1 /*-
2  * Copyright (c) 2006 Bernd Walter.  All rights reserved.
3  * Copyright (c) 2006 M. Warner Losh.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  *
25  * Portions of this software may have been developed with reference to
26  * the SD Simplified Specification.  The following disclaimer may apply:
27  *
28  * The following conditions apply to the release of the simplified
29  * specification ("Simplified Specification") by the SD Card Association and
30  * the SD Group. The Simplified Specification is a subset of the complete SD
31  * Specification which is owned by the SD Card Association and the SD
32  * Group. This Simplified Specification is provided on a non-confidential
33  * basis subject to the disclaimers below. Any implementation of the
34  * Simplified Specification may require a license from the SD Card
35  * Association, SD Group, SD-3C LLC or other third parties.
36  *
37  * Disclaimers:
38  *
39  * The information contained in the Simplified Specification is presented only
40  * as a standard specification for SD Cards and SD Host/Ancillary products and
41  * is provided "AS-IS" without any representations or warranties of any
42  * kind. No responsibility is assumed by the SD Group, SD-3C LLC or the SD
43  * Card Association for any damages, any infringements of patents or other
44  * right of the SD Group, SD-3C LLC, the SD Card Association or any third
45  * parties, which may result from its use. No license is granted by
46  * implication, estoppel or otherwise under any patent or other rights of the
47  * SD Group, SD-3C LLC, the SD Card Association or any third party. Nothing
48  * herein shall be construed as an obligation by the SD Group, the SD-3C LLC
49  * or the SD Card Association to disclose or distribute any technical
50  * information, know-how or other confidential information to any third party.
51  *
52  * $FreeBSD: src/sys/dev/mmc/mmcsd.c,v 1.20 2009/02/17 19:17:25 mav Exp $
53  */
54 
55 #include <sys/param.h>
56 #include <sys/systm.h>
57 #include <sys/buf.h>
58 #include <sys/bus.h>
59 #include <sys/conf.h>
60 #include <sys/disk.h>
61 #include <sys/device.h>
62 #include <sys/devicestat.h>
63 #include <sys/kernel.h>
64 #include <sys/kthread.h>
65 #include <sys/lock.h>
66 #include <sys/malloc.h>
67 #include <sys/module.h>
68 #include <sys/spinlock.h>
69 
70 #include <sys/buf2.h>
71 #include <sys/mplock2.h>
72 
73 #include <bus/mmc/mmcvar.h>
74 #include <bus/mmc/mmcreg.h>
75 
76 #include "mmcbus_if.h"
77 
78 struct mmcsd_softc {
79 	device_t dev;
80 	cdev_t dev_t;
81 	struct lock sc_lock;
82 	struct disk disk;
83 	struct devstat device_stats;
84 	int unit;
85 	struct thread *td;
86 	struct bio_queue_head bio_queue;
87 	daddr_t eblock, eend;	/* Range remaining after the last erase. */
88 	int running;
89 	int suspend;
90 };
91 
92 /* bus entry points */
93 static int mmcsd_probe(device_t dev);
94 static int mmcsd_attach(device_t dev);
95 static int mmcsd_detach(device_t dev);
96 
97 /* disk routines */
98 static d_open_t mmcsd_open;
99 static d_close_t mmcsd_close;
100 static d_strategy_t mmcsd_strategy;
101 static d_dump_t mmcsd_dump;
102 
103 static void mmcsd_task(void *arg);
104 
105 static const char *mmcsd_card_name(device_t dev);
106 static int mmcsd_bus_bit_width(device_t dev);
107 
108 #define MMCSD_LOCK(_sc)		lockmgr(&(_sc)->sc_lock, LK_EXCLUSIVE)
109 #define	MMCSD_UNLOCK(_sc)	lockmgr(&(_sc)->sc_lock, LK_RELEASE)
110 #define MMCSD_LOCK_INIT(_sc)	lockinit(&(_sc)->sc_lock, "mmcsd", 0, LK_CANRECURSE)
111 #define MMCSD_LOCK_DESTROY(_sc)	lockuninit(&(_sc)->sc_lock);
112 #define MMCSD_ASSERT_LOCKED(_sc) KKASSERT(lockstatus(&(_sc)->sc_lock, curthread) != 0);
113 #define MMCSD_ASSERT_UNLOCKED(_sc) KKASSERT(lockstatus(&(_sc)->sc_lock, curthread) == 0);
114 
115 static struct dev_ops mmcsd_ops = {
116 	{ "mmcsd", 0, D_DISK },
117 	.d_open = mmcsd_open,
118 	.d_close = mmcsd_close,
119 	.d_strategy = mmcsd_strategy,
120 	.d_dump = mmcsd_dump,
121 };
122 
123 static int
124 mmcsd_probe(device_t dev)
125 {
126 
127 	device_quiet(dev);
128 	device_set_desc(dev, "MMC/SD Memory Card");
129 	return (0);
130 }
131 
132 static int
133 mmcsd_attach(device_t dev)
134 {
135 	struct mmcsd_softc *sc;
136 	struct disk_info info;
137 	cdev_t dsk;
138 	intmax_t mb;
139 	char unit;
140 	int sector_size;
141 
142 	sc = device_get_softc(dev);
143 	sc->dev = dev;
144 	MMCSD_LOCK_INIT(sc);
145 
146 	sector_size = mmc_get_sector_size(dev);
147 	devstat_add_entry(&sc->device_stats, "mmcsd", device_get_unit(dev),
148 	    sector_size, DEVSTAT_NO_ORDERED_TAGS,
149 	    DEVSTAT_TYPE_DIRECT | DEVSTAT_TYPE_IF_OTHER,
150 	    DEVSTAT_PRIORITY_DISK);
151 
152 	dsk = disk_create(sc->unit, &sc->disk, &mmcsd_ops);
153 	dsk->si_drv1 = sc;
154 	sc->dev_t = dsk;
155 
156 	dsk->si_iosize_max = 4*1024*1024;	/* Maximum defined SD card AU size. */
157 
158 	bzero(&info, sizeof(info));
159 	info.d_media_blksize = sector_size;
160 	info.d_media_blocks = mmc_get_media_size(dev);
161 	disk_setdiskinfo(&sc->disk, &info);
162 
163 	/*
164 	 * Display in most natural units.  There's no cards < 1MB.
165 	 * The SD standard goes to 2GiB, but the data format supports
166 	 * up to 4GiB and some card makers push it up to this limit.
167 	 * The SDHC standard only goes to 32GiB (the data format in
168 	 * SDHC is good to 2TiB however, which isn't too ugly at
169 	 * 2048GiBm, so we note it in passing here and don't add the
170 	 * code to print TiB).
171 	 */
172 	mb = (info.d_media_blksize * info.d_media_blocks) >> 20;	/* 1MiB == 1 << 20 */
173 	unit = 'M';
174 	if (mb >= 10240) {		/* 1GiB = 1024 MiB */
175 		unit = 'G';
176 		mb /= 1024;
177 	}
178 	device_printf(dev, "%ju%cB <%s Memory Card>%s at %s %dMHz/%dbit\n",
179 	    mb, unit, mmcsd_card_name(dev),
180 	    mmc_get_read_only(dev) ? " (read-only)" : "",
181 	    device_get_nameunit(device_get_parent(dev)),
182 	    mmc_get_tran_speed(dev) / 1000000, mmcsd_bus_bit_width(dev));
183 
184 	bioq_init(&sc->bio_queue);
185 
186 	sc->running = 1;
187 	sc->suspend = 0;
188 	sc->eblock = sc->eend = 0;
189 	kthread_create(mmcsd_task, sc, &sc->td, "mmc/sd card task");
190 
191 	return (0);
192 }
193 
194 static int
195 mmcsd_detach(device_t dev)
196 {
197 	struct mmcsd_softc *sc = device_get_softc(dev);
198 	struct buf *q_bp;
199 	struct bio *q_bio;
200 
201 	MMCSD_LOCK(sc);
202 	sc->suspend = 0;
203 	if (sc->running > 0) {
204 		/* kill thread */
205 		sc->running = 0;
206 		wakeup(sc);
207 		/* wait for thread to finish. */
208 		while (sc->running != -1)
209 			lksleep(sc, &sc->sc_lock, 0, "detach", 0);
210 	}
211 	MMCSD_UNLOCK(sc);
212 
213 	/* Flush the request queue.
214 	 *
215 	 * XXX: Return all queued I/O with ENXIO. Is this correct?
216 	 */
217 	while ((q_bio = bioq_first(&sc->bio_queue)) != NULL){
218 		bioq_remove(&sc->bio_queue, q_bio);
219 		q_bp = q_bio->bio_buf;
220 		q_bp->b_resid = q_bp->b_bcount;
221 		q_bp->b_error = ENXIO;
222 		q_bp->b_flags |= B_ERROR;
223 		biodone(q_bio);
224 	}
225 
226 	/* kill disk */
227 	disk_destroy(&sc->disk);
228 	devstat_remove_entry(&sc->device_stats);
229 
230 	MMCSD_LOCK_DESTROY(sc);
231 
232 	return (0);
233 }
234 
235 static int
236 mmcsd_suspend(device_t dev)
237 {
238 	struct mmcsd_softc *sc = device_get_softc(dev);
239 
240 	MMCSD_LOCK(sc);
241 	sc->suspend = 1;
242 	if (sc->running > 0) {
243 		/* kill thread */
244 		sc->running = 0;
245 		wakeup(sc);
246 		/* wait for thread to finish. */
247 		while (sc->running != -1)
248 			lksleep(sc, &sc->sc_lock, 0, "detach", 0);
249 	}
250 	MMCSD_UNLOCK(sc);
251 	return (0);
252 }
253 
254 static int
255 mmcsd_resume(device_t dev)
256 {
257 	struct mmcsd_softc *sc = device_get_softc(dev);
258 
259 	MMCSD_LOCK(sc);
260 	sc->suspend = 0;
261 	if (sc->running <= 0) {
262 		sc->running = 1;
263 		MMCSD_UNLOCK(sc);
264 		kthread_create(mmcsd_task, sc, &sc->td, "mmc/sd card task");
265 	} else
266 		MMCSD_UNLOCK(sc);
267 	return (0);
268 }
269 
270 static int
271 mmcsd_open(struct dev_open_args *ap)
272 {
273 	return (0);
274 }
275 
276 static int
277 mmcsd_close(struct dev_close_args *ap)
278 {
279 	return (0);
280 }
281 
282 static int
283 mmcsd_strategy(struct dev_strategy_args *ap)
284 {
285 	struct mmcsd_softc *sc;
286 	struct bio *bio = ap->a_bio;
287 	struct buf *bp = bio->bio_buf;
288 
289 	sc = (struct mmcsd_softc *)ap->a_head.a_dev->si_drv1;
290 	MMCSD_LOCK(sc);
291 	if (sc->running > 0 || sc->suspend > 0) {
292 		bioqdisksort(&sc->bio_queue, bio);
293 		devstat_start_transaction(&sc->device_stats);
294 		MMCSD_UNLOCK(sc);
295 		wakeup(sc);
296 	} else {
297 		MMCSD_UNLOCK(sc);
298 		bp->b_error = ENXIO;
299 		bp->b_flags |= B_ERROR;
300 		bp->b_resid = bp->b_bcount;
301 		biodone(bio);
302 	}
303 	return (0);
304 }
305 
306 static daddr_t
307 mmcsd_rw(struct mmcsd_softc *sc, struct bio *bio)
308 {
309 	daddr_t block, end;
310 	struct mmc_command cmd;
311 	struct mmc_command stop;
312 	struct mmc_request req;
313 	struct mmc_data data;
314 	device_t dev = sc->dev;
315 	int sz = sc->disk.d_info.d_media_blksize;
316 	struct buf *bp = bio->bio_buf;
317 
318 	block = bio->bio_offset / sz;
319 	end = block + (bp->b_bcount / sz);
320 	while (block < end) {
321 		char *vaddr = bp->b_data +
322 		    (block - (bio->bio_offset / sz)) * sz;
323 		int numblocks = min(end - block, mmc_get_max_data(dev));
324 		memset(&req, 0, sizeof(req));
325 		memset(&cmd, 0, sizeof(cmd));
326 		memset(&stop, 0, sizeof(stop));
327 		req.cmd = &cmd;
328 		cmd.data = &data;
329 		if (bp->b_cmd == BUF_CMD_READ) {
330 			if (numblocks > 1)
331 				cmd.opcode = MMC_READ_MULTIPLE_BLOCK;
332 			else
333 				cmd.opcode = MMC_READ_SINGLE_BLOCK;
334 		} else {
335 			if (numblocks > 1)
336 				cmd.opcode = MMC_WRITE_MULTIPLE_BLOCK;
337 			else
338 				cmd.opcode = MMC_WRITE_BLOCK;
339 		}
340 		cmd.arg = block;
341 		if (!mmc_get_high_cap(dev))
342 			cmd.arg <<= 9;
343 		cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
344 		data.data = vaddr;
345 		data.mrq = &req;
346 		if (bp->b_cmd == BUF_CMD_READ)
347 			data.flags = MMC_DATA_READ;
348 		else
349 			data.flags = MMC_DATA_WRITE;
350 		data.len = numblocks * sz;
351 		if (numblocks > 1) {
352 			data.flags |= MMC_DATA_MULTI;
353 			stop.opcode = MMC_STOP_TRANSMISSION;
354 			stop.arg = 0;
355 			stop.flags = MMC_RSP_R1B | MMC_CMD_AC;
356 			req.stop = &stop;
357 		}
358 //		kprintf("Len %d  %lld-%lld flags %#x sz %d\n",
359 //		    (int)data.len, (long long)block, (long long)end, data.flags, sz);
360 		MMCBUS_WAIT_FOR_REQUEST(device_get_parent(dev), dev,
361 		    &req);
362 		if (req.cmd->error != MMC_ERR_NONE)
363 			break;
364 		block += numblocks;
365 	}
366 	return (block);
367 }
368 
369 static daddr_t
370 mmcsd_delete(struct mmcsd_softc *sc, struct bio *bio)
371 {
372 	daddr_t block, end, start, stop;
373 	struct mmc_command cmd;
374 	struct mmc_request req;
375 	device_t dev = sc->dev;
376 	int sz = sc->disk.d_info.d_media_blksize;
377 	int erase_sector;
378 	struct buf *bp = bio->bio_buf;
379 
380 	block = bio->bio_offset / sz;
381 	end = block + (bp->b_bcount / sz);
382 	/* Coalesce with part remaining from previous request. */
383 	if (block > sc->eblock && block <= sc->eend)
384 		block = sc->eblock;
385 	if (end >= sc->eblock && end < sc->eend)
386 		end = sc->eend;
387 	/* Safe round to the erase sector boundaries. */
388 	erase_sector = mmc_get_erase_sector(dev);
389 	start = block + erase_sector - 1;	 /* Round up. */
390 	start -= start % erase_sector;
391 	stop = end;				/* Round down. */
392 	stop -= end % erase_sector;
393 	/* We can't erase area smaller then sector, store it for later. */
394 	if (start >= stop) {
395 		sc->eblock = block;
396 		sc->eend = end;
397 		return (end);
398 	}
399 
400 	/* Set erase start position. */
401 	memset(&req, 0, sizeof(req));
402 	memset(&cmd, 0, sizeof(cmd));
403 	req.cmd = &cmd;
404 	if (mmc_get_card_type(dev) == mode_sd)
405 		cmd.opcode = SD_ERASE_WR_BLK_START;
406 	else
407 		cmd.opcode = MMC_ERASE_GROUP_START;
408 	cmd.arg = start;
409 	if (!mmc_get_high_cap(dev))
410 		cmd.arg <<= 9;
411 	cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
412 	MMCBUS_WAIT_FOR_REQUEST(device_get_parent(dev), dev,
413 	    &req);
414 	if (req.cmd->error != MMC_ERR_NONE) {
415 	    kprintf("erase err1: %d\n", req.cmd->error);
416 	    return (block);
417 	}
418 	/* Set erase stop position. */
419 	memset(&req, 0, sizeof(req));
420 	memset(&cmd, 0, sizeof(cmd));
421 	req.cmd = &cmd;
422 	if (mmc_get_card_type(dev) == mode_sd)
423 		cmd.opcode = SD_ERASE_WR_BLK_END;
424 	else
425 		cmd.opcode = MMC_ERASE_GROUP_END;
426 	cmd.arg = stop;
427 	if (!mmc_get_high_cap(dev))
428 		cmd.arg <<= 9;
429 	cmd.arg--;
430 	cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
431 	MMCBUS_WAIT_FOR_REQUEST(device_get_parent(dev), dev,
432 	    &req);
433 	if (req.cmd->error != MMC_ERR_NONE) {
434 	    kprintf("erase err2: %d\n", req.cmd->error);
435 	    return (block);
436 	}
437 	/* Erase range. */
438 	memset(&req, 0, sizeof(req));
439 	memset(&cmd, 0, sizeof(cmd));
440 	req.cmd = &cmd;
441 	cmd.opcode = MMC_ERASE;
442 	cmd.arg = 0;
443 	cmd.flags = MMC_RSP_R1B | MMC_CMD_AC;
444 	MMCBUS_WAIT_FOR_REQUEST(device_get_parent(dev), dev,
445 	    &req);
446 	if (req.cmd->error != MMC_ERR_NONE) {
447 	    kprintf("erase err3 %d\n", req.cmd->error);
448 	    return (block);
449 	}
450 	/* Store one of remaining parts for the next call. */
451 	if ((bio->bio_offset / sz) >= sc->eblock || block == start) {
452 		sc->eblock = stop;	/* Predict next forward. */
453 		sc->eend = end;
454 	} else {
455 		sc->eblock = block;	/* Predict next backward. */
456 		sc->eend = start;
457 	}
458 	return (end);
459 }
460 
461 static int
462 mmcsd_dump(struct dev_dump_args *ap)
463 {
464 #if 0
465 	cdev_t cdev = ap->a_head.a_dev;
466 	struct mmcsd_softc *sc = (struct mmcsd_softc *)cdev->si_drv1;
467 	device_t dev = sc->dev;
468 	struct bio bp;
469 	daddr_t block, end;
470 	int length = ap->a_length;
471 
472 	/* length zero is special and really means flush buffers to media */
473 	if (!length)
474 		return (0);
475 
476 	bzero(&bp, sizeof(struct bio));
477 	bp.bio_driver_info = cdev;
478 	bp.bio_pblkno = offset / sc->disk->d_sectorsize;
479 	bp.bio_bcount = length;
480 	bp.bio_data = virtual;
481 	bp.bio_cmd = BIO_WRITE;
482 	end = bp.bio_pblkno + bp.bio_bcount / sc->disk.d_info.d_media_blksize;
483 	MMCBUS_ACQUIRE_BUS(device_get_parent(dev), dev);
484 	block = mmcsd_rw(sc, &bp);
485 	MMCBUS_RELEASE_BUS(device_get_parent(dev), dev);
486 	return ((end < block) ? EIO : 0);
487 #endif
488 	return EIO;
489 }
490 
491 static void
492 mmcsd_task(void *arg)
493 {
494 	struct mmcsd_softc *sc = (struct mmcsd_softc*)arg;
495 	struct bio *bio;
496 	struct buf *bp;
497 	int sz;
498 	daddr_t block, end;
499 	device_t dev;
500 
501 	get_mplock();
502 	dev = sc->dev;
503 
504 	while (1) {
505 		MMCSD_LOCK(sc);
506 		do {
507 			if (sc->running == 0)
508 				goto out;
509 			bio = bioq_takefirst(&sc->bio_queue);
510 			if (bio == NULL)
511 				lksleep(sc, &sc->sc_lock, 0, "jobqueue", 0);
512 		} while (bio == NULL);
513 		bp = bio->bio_buf;
514 		MMCSD_UNLOCK(sc);
515 		if (bp->b_cmd != BUF_CMD_READ && mmc_get_read_only(dev)) {
516 			bp->b_error = EROFS;
517 			bp->b_resid = bp->b_bcount;
518 			bp->b_flags |= B_ERROR;
519 			devstat_end_transaction_buf(&sc->device_stats, bp);
520 			biodone(bio);
521 			continue;
522 		}
523 		MMCBUS_ACQUIRE_BUS(device_get_parent(dev), dev);
524 		sz = sc->disk.d_info.d_media_blksize;
525 		block = bio->bio_offset / sz;
526 		end = block + (bp->b_bcount / sz);
527 		if (bp->b_cmd == BUF_CMD_READ ||
528 		    bp->b_cmd == BUF_CMD_WRITE) {
529 			/* Access to the remaining erase block obsoletes it. */
530 			if (block < sc->eend && end > sc->eblock)
531 				sc->eblock = sc->eend = 0;
532 			block = mmcsd_rw(sc, bio);
533 		} else if (bp->b_cmd == BUF_CMD_FREEBLKS) {
534 			block = mmcsd_delete(sc, bio);
535 		}
536 		MMCBUS_RELEASE_BUS(device_get_parent(dev), dev);
537 		if (block < end) {
538 			bp->b_error = EIO;
539 			bp->b_resid = (end - block) * sz;
540 			bp->b_flags |= B_ERROR;
541 		}
542 		devstat_end_transaction_buf(&sc->device_stats, bp);
543 		biodone(bio);
544 	}
545 out:
546 	/* tell parent we're done */
547 	sc->running = -1;
548 	MMCSD_UNLOCK(sc);
549 	wakeup(sc);
550 
551 	rel_mplock();
552 }
553 
554 static const char *
555 mmcsd_card_name(device_t dev)
556 {
557 	if (mmc_get_card_type(dev) == mode_mmc)
558 		return ("MMC");
559 	if (mmc_get_high_cap(dev))
560 		return ("SDHC");
561 	return ("SD");
562 }
563 
564 static int
565 mmcsd_bus_bit_width(device_t dev)
566 {
567 	if (mmc_get_bus_width(dev) == bus_width_1)
568 		return (1);
569 	if (mmc_get_bus_width(dev) == bus_width_4)
570 		return (4);
571 	return (8);
572 }
573 
574 static device_method_t mmcsd_methods[] = {
575 	DEVMETHOD(device_probe, mmcsd_probe),
576 	DEVMETHOD(device_attach, mmcsd_attach),
577 	DEVMETHOD(device_detach, mmcsd_detach),
578 	DEVMETHOD(device_suspend, mmcsd_suspend),
579 	DEVMETHOD(device_resume, mmcsd_resume),
580 	{0, 0},
581 };
582 
583 static driver_t mmcsd_driver = {
584 	"mmcsd",
585 	mmcsd_methods,
586 	sizeof(struct mmcsd_softc),
587 };
588 static devclass_t mmcsd_devclass;
589 
590 DRIVER_MODULE(mmcsd, mmc, mmcsd_driver, mmcsd_devclass, 0, 0);
591