xref: /dragonfly/sys/dev/disk/mmcsd/mmcsd.c (revision 277350a0)
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 	struct thread *td;
85 	struct bio_queue_head bio_queue;
86 	daddr_t eblock, eend;	/* Range remaining after the last erase. */
87 	int running;
88 	int suspend;
89 };
90 
91 /* bus entry points */
92 static int mmcsd_probe(device_t dev);
93 static int mmcsd_attach(device_t dev);
94 static int mmcsd_detach(device_t dev);
95 
96 /* disk routines */
97 static d_open_t mmcsd_open;
98 static d_close_t mmcsd_close;
99 static d_strategy_t mmcsd_strategy;
100 static d_dump_t mmcsd_dump;
101 
102 static void mmcsd_task(void *arg);
103 
104 static const char *mmcsd_card_name(device_t dev);
105 static int mmcsd_bus_bit_width(device_t dev);
106 
107 #define MMCSD_LOCK(_sc)		lockmgr(&(_sc)->sc_lock, LK_EXCLUSIVE)
108 #define	MMCSD_UNLOCK(_sc)	lockmgr(&(_sc)->sc_lock, LK_RELEASE)
109 #define MMCSD_LOCK_INIT(_sc)	lockinit(&(_sc)->sc_lock, "mmcsd", 0, LK_CANRECURSE)
110 #define MMCSD_LOCK_DESTROY(_sc)	lockuninit(&(_sc)->sc_lock);
111 #define MMCSD_ASSERT_LOCKED(_sc) KKASSERT(lockstatus(&(_sc)->sc_lock, curthread) != 0);
112 #define MMCSD_ASSERT_UNLOCKED(_sc) KKASSERT(lockstatus(&(_sc)->sc_lock, curthread) == 0);
113 
114 static struct dev_ops mmcsd_ops = {
115 	{ "mmcsd", 0, D_DISK },
116 	.d_open = mmcsd_open,
117 	.d_close = mmcsd_close,
118 	.d_strategy = mmcsd_strategy,
119 	.d_dump = mmcsd_dump,
120 };
121 
122 static int
123 mmcsd_probe(device_t dev)
124 {
125 
126 	device_quiet(dev);
127 	device_set_desc(dev, "MMC/SD Memory Card");
128 	return (0);
129 }
130 
131 static int
132 mmcsd_attach(device_t dev)
133 {
134 	struct mmcsd_softc *sc;
135 	struct disk_info info;
136 	cdev_t dsk;
137 	intmax_t mb;
138 	char unit;
139 	int sector_size;
140 
141 	sc = device_get_softc(dev);
142 	sc->dev = dev;
143 	MMCSD_LOCK_INIT(sc);
144 
145 	sector_size = mmc_get_sector_size(dev);
146 	devstat_add_entry(&sc->device_stats, "mmcsd", device_get_unit(dev),
147 	    sector_size, DEVSTAT_NO_ORDERED_TAGS,
148 	    DEVSTAT_TYPE_DIRECT | DEVSTAT_TYPE_IF_OTHER,
149 	    DEVSTAT_PRIORITY_DISK);
150 
151 	dsk = disk_create(device_get_unit(dev), &sc->disk, &mmcsd_ops);
152 	dsk->si_drv1 = sc;
153 	sc->dev_t = dsk;
154 
155 	dsk->si_iosize_max = 4*1024*1024;	/* Maximum defined SD card AU size. */
156 
157 	bzero(&info, sizeof(info));
158 	info.d_media_blksize = sector_size;
159 	info.d_media_blocks = mmc_get_media_size(dev);
160 	disk_setdiskinfo(&sc->disk, &info);
161 
162 	/*
163 	 * Display in most natural units.  There's no cards < 1MB.
164 	 * The SD standard goes to 2GiB, but the data format supports
165 	 * up to 4GiB and some card makers push it up to this limit.
166 	 * The SDHC standard only goes to 32GiB (the data format in
167 	 * SDHC is good to 2TiB however, which isn't too ugly at
168 	 * 2048GiBm, so we note it in passing here and don't add the
169 	 * code to print TiB).
170 	 */
171 	mb = (info.d_media_blksize * info.d_media_blocks) >> 20;	/* 1MiB == 1 << 20 */
172 	unit = 'M';
173 	if (mb >= 10240) {		/* 1GiB = 1024 MiB */
174 		unit = 'G';
175 		mb /= 1024;
176 	}
177 	device_printf(dev, "%ju%cB <%s Memory Card>%s at %s %dMHz/%dbit\n",
178 	    mb, unit, mmcsd_card_name(dev),
179 	    mmc_get_read_only(dev) ? " (read-only)" : "",
180 	    device_get_nameunit(device_get_parent(dev)),
181 	    mmc_get_tran_speed(dev) / 1000000, mmcsd_bus_bit_width(dev));
182 
183 	bioq_init(&sc->bio_queue);
184 
185 	sc->running = 1;
186 	sc->suspend = 0;
187 	sc->eblock = sc->eend = 0;
188 	kthread_create(mmcsd_task, sc, &sc->td, "mmc/sd card task");
189 
190 	return (0);
191 }
192 
193 static int
194 mmcsd_detach(device_t dev)
195 {
196 	struct mmcsd_softc *sc = device_get_softc(dev);
197 	struct buf *q_bp;
198 	struct bio *q_bio;
199 
200 	MMCSD_LOCK(sc);
201 	sc->suspend = 0;
202 	if (sc->running > 0) {
203 		/* kill thread */
204 		sc->running = 0;
205 		wakeup(sc);
206 		/* wait for thread to finish. */
207 		while (sc->running != -1)
208 			lksleep(sc, &sc->sc_lock, 0, "detach", 0);
209 	}
210 	MMCSD_UNLOCK(sc);
211 
212 	/* Flush the request queue.
213 	 *
214 	 * XXX: Return all queued I/O with ENXIO. Is this correct?
215 	 */
216 	while ((q_bio = bioq_takefirst(&sc->bio_queue)) != NULL) {
217 		q_bp = q_bio->bio_buf;
218 		q_bp->b_resid = q_bp->b_bcount;
219 		q_bp->b_error = ENXIO;
220 		q_bp->b_flags |= B_ERROR;
221 		biodone(q_bio);
222 	}
223 
224 	/* kill disk */
225 	disk_destroy(&sc->disk);
226 	devstat_remove_entry(&sc->device_stats);
227 
228 	MMCSD_LOCK_DESTROY(sc);
229 
230 	return (0);
231 }
232 
233 static int
234 mmcsd_suspend(device_t dev)
235 {
236 	struct mmcsd_softc *sc = device_get_softc(dev);
237 
238 	MMCSD_LOCK(sc);
239 	sc->suspend = 1;
240 	if (sc->running > 0) {
241 		/* kill thread */
242 		sc->running = 0;
243 		wakeup(sc);
244 		/* wait for thread to finish. */
245 		while (sc->running != -1)
246 			lksleep(sc, &sc->sc_lock, 0, "detach", 0);
247 	}
248 	MMCSD_UNLOCK(sc);
249 	return (0);
250 }
251 
252 static int
253 mmcsd_resume(device_t dev)
254 {
255 	struct mmcsd_softc *sc = device_get_softc(dev);
256 
257 	MMCSD_LOCK(sc);
258 	sc->suspend = 0;
259 	if (sc->running <= 0) {
260 		sc->running = 1;
261 		MMCSD_UNLOCK(sc);
262 		kthread_create(mmcsd_task, sc, &sc->td, "mmc/sd card task");
263 	} else
264 		MMCSD_UNLOCK(sc);
265 	return (0);
266 }
267 
268 static int
269 mmcsd_open(struct dev_open_args *ap)
270 {
271 	return (0);
272 }
273 
274 static int
275 mmcsd_close(struct dev_close_args *ap)
276 {
277 	return (0);
278 }
279 
280 static int
281 mmcsd_strategy(struct dev_strategy_args *ap)
282 {
283 	struct mmcsd_softc *sc;
284 	struct bio *bio = ap->a_bio;
285 	struct buf *bp = bio->bio_buf;
286 
287 	sc = (struct mmcsd_softc *)ap->a_head.a_dev->si_drv1;
288 	MMCSD_LOCK(sc);
289 	if (sc->running > 0 || sc->suspend > 0) {
290 		bioqdisksort(&sc->bio_queue, bio);
291 		devstat_start_transaction(&sc->device_stats);
292 		MMCSD_UNLOCK(sc);
293 		wakeup(sc);
294 	} else {
295 		MMCSD_UNLOCK(sc);
296 		bp->b_error = ENXIO;
297 		bp->b_flags |= B_ERROR;
298 		bp->b_resid = bp->b_bcount;
299 		biodone(bio);
300 	}
301 	return (0);
302 }
303 
304 static daddr_t
305 mmcsd_rw(struct mmcsd_softc *sc, struct bio *bio)
306 {
307 	daddr_t block, end;
308 	struct mmc_command cmd;
309 	struct mmc_command stop;
310 	struct mmc_request req;
311 	struct mmc_data data;
312 	device_t dev = sc->dev;
313 	int sz = sc->disk.d_info.d_media_blksize;
314 	struct buf *bp = bio->bio_buf;
315 
316 	block = bio->bio_offset / sz;
317 	end = block + (bp->b_bcount / sz);
318 	while (block < end) {
319 		char *vaddr = bp->b_data +
320 		    (block - (bio->bio_offset / sz)) * sz;
321 		int numblocks = min(end - block, mmc_get_max_data(dev));
322 		memset(&req, 0, sizeof(req));
323 		memset(&cmd, 0, sizeof(cmd));
324 		memset(&stop, 0, sizeof(stop));
325 		req.cmd = &cmd;
326 		cmd.data = &data;
327 		if (bp->b_cmd == BUF_CMD_READ) {
328 			if (numblocks > 1)
329 				cmd.opcode = MMC_READ_MULTIPLE_BLOCK;
330 			else
331 				cmd.opcode = MMC_READ_SINGLE_BLOCK;
332 		} else {
333 			if (numblocks > 1)
334 				cmd.opcode = MMC_WRITE_MULTIPLE_BLOCK;
335 			else
336 				cmd.opcode = MMC_WRITE_BLOCK;
337 		}
338 		cmd.arg = block;
339 		if (!mmc_get_high_cap(dev))
340 			cmd.arg <<= 9;
341 		cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
342 		data.data = vaddr;
343 		data.mrq = &req;
344 		if (bp->b_cmd == BUF_CMD_READ)
345 			data.flags = MMC_DATA_READ;
346 		else
347 			data.flags = MMC_DATA_WRITE;
348 		data.len = numblocks * sz;
349 		if (numblocks > 1) {
350 			data.flags |= MMC_DATA_MULTI;
351 			stop.opcode = MMC_STOP_TRANSMISSION;
352 			stop.arg = 0;
353 			stop.flags = MMC_RSP_R1B | MMC_CMD_AC;
354 			req.stop = &stop;
355 		}
356 //		kprintf("Len %d  %lld-%lld flags %#x sz %d\n",
357 //		    (int)data.len, (long long)block, (long long)end, data.flags, sz);
358 		MMCBUS_WAIT_FOR_REQUEST(device_get_parent(dev), dev,
359 		    &req);
360 		if (req.cmd->error != MMC_ERR_NONE)
361 			break;
362 		block += numblocks;
363 	}
364 	return (block);
365 }
366 
367 static daddr_t
368 mmcsd_delete(struct mmcsd_softc *sc, struct bio *bio)
369 {
370 	daddr_t block, end, start, stop;
371 	struct mmc_command cmd;
372 	struct mmc_request req;
373 	device_t dev = sc->dev;
374 	int sz = sc->disk.d_info.d_media_blksize;
375 	int erase_sector;
376 	struct buf *bp = bio->bio_buf;
377 
378 	block = bio->bio_offset / sz;
379 	end = block + (bp->b_bcount / sz);
380 	/* Coalesce with part remaining from previous request. */
381 	if (block > sc->eblock && block <= sc->eend)
382 		block = sc->eblock;
383 	if (end >= sc->eblock && end < sc->eend)
384 		end = sc->eend;
385 	/* Safe round to the erase sector boundaries. */
386 	erase_sector = mmc_get_erase_sector(dev);
387 	start = block + erase_sector - 1;	 /* Round up. */
388 	start -= start % erase_sector;
389 	stop = end;				/* Round down. */
390 	stop -= end % erase_sector;
391 	/* We can't erase area smaller then sector, store it for later. */
392 	if (start >= stop) {
393 		sc->eblock = block;
394 		sc->eend = end;
395 		return (end);
396 	}
397 
398 	/* Set erase start position. */
399 	memset(&req, 0, sizeof(req));
400 	memset(&cmd, 0, sizeof(cmd));
401 	req.cmd = &cmd;
402 	if (mmc_get_card_type(dev) == mode_sd)
403 		cmd.opcode = SD_ERASE_WR_BLK_START;
404 	else
405 		cmd.opcode = MMC_ERASE_GROUP_START;
406 	cmd.arg = start;
407 	if (!mmc_get_high_cap(dev))
408 		cmd.arg <<= 9;
409 	cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
410 	MMCBUS_WAIT_FOR_REQUEST(device_get_parent(dev), dev,
411 	    &req);
412 	if (req.cmd->error != MMC_ERR_NONE) {
413 	    kprintf("erase err1: %d\n", req.cmd->error);
414 	    return (block);
415 	}
416 	/* Set erase stop position. */
417 	memset(&req, 0, sizeof(req));
418 	memset(&cmd, 0, sizeof(cmd));
419 	req.cmd = &cmd;
420 	if (mmc_get_card_type(dev) == mode_sd)
421 		cmd.opcode = SD_ERASE_WR_BLK_END;
422 	else
423 		cmd.opcode = MMC_ERASE_GROUP_END;
424 	cmd.arg = stop;
425 	if (!mmc_get_high_cap(dev))
426 		cmd.arg <<= 9;
427 	cmd.arg--;
428 	cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
429 	MMCBUS_WAIT_FOR_REQUEST(device_get_parent(dev), dev,
430 	    &req);
431 	if (req.cmd->error != MMC_ERR_NONE) {
432 	    kprintf("erase err2: %d\n", req.cmd->error);
433 	    return (block);
434 	}
435 	/* Erase range. */
436 	memset(&req, 0, sizeof(req));
437 	memset(&cmd, 0, sizeof(cmd));
438 	req.cmd = &cmd;
439 	cmd.opcode = MMC_ERASE;
440 	cmd.arg = 0;
441 	cmd.flags = MMC_RSP_R1B | MMC_CMD_AC;
442 	MMCBUS_WAIT_FOR_REQUEST(device_get_parent(dev), dev,
443 	    &req);
444 	if (req.cmd->error != MMC_ERR_NONE) {
445 	    kprintf("erase err3 %d\n", req.cmd->error);
446 	    return (block);
447 	}
448 	/* Store one of remaining parts for the next call. */
449 	if ((bio->bio_offset / sz) >= sc->eblock || block == start) {
450 		sc->eblock = stop;	/* Predict next forward. */
451 		sc->eend = end;
452 	} else {
453 		sc->eblock = block;	/* Predict next backward. */
454 		sc->eend = start;
455 	}
456 	return (end);
457 }
458 
459 static int
460 mmcsd_dump(struct dev_dump_args *ap)
461 {
462 #if 0
463 	cdev_t cdev = ap->a_head.a_dev;
464 	struct mmcsd_softc *sc = (struct mmcsd_softc *)cdev->si_drv1;
465 	device_t dev = sc->dev;
466 	struct bio bp;
467 	daddr_t block, end;
468 	int length = ap->a_length;
469 
470 	/* length zero is special and really means flush buffers to media */
471 	if (!length)
472 		return (0);
473 
474 	bzero(&bp, sizeof(struct bio));
475 	bp.bio_driver_info = cdev;
476 	bp.bio_pblkno = offset / sc->disk->d_sectorsize;
477 	bp.bio_bcount = length;
478 	bp.bio_data = virtual;
479 	bp.bio_cmd = BIO_WRITE;
480 	end = bp.bio_pblkno + bp.bio_bcount / sc->disk.d_info.d_media_blksize;
481 	MMCBUS_ACQUIRE_BUS(device_get_parent(dev), dev);
482 	block = mmcsd_rw(sc, &bp);
483 	MMCBUS_RELEASE_BUS(device_get_parent(dev), dev);
484 	return ((end < block) ? EIO : 0);
485 #endif
486 	return EIO;
487 }
488 
489 static void
490 mmcsd_task(void *arg)
491 {
492 	struct mmcsd_softc *sc = (struct mmcsd_softc*)arg;
493 	struct bio *bio;
494 	struct buf *bp;
495 	int sz;
496 	daddr_t block, end;
497 	device_t dev;
498 
499 	get_mplock();
500 	dev = sc->dev;
501 
502 	while (1) {
503 		MMCSD_LOCK(sc);
504 		do {
505 			if (sc->running == 0)
506 				goto out;
507 			bio = bioq_takefirst(&sc->bio_queue);
508 			if (bio == NULL)
509 				lksleep(sc, &sc->sc_lock, 0, "jobqueue", 0);
510 		} while (bio == NULL);
511 		bp = bio->bio_buf;
512 		MMCSD_UNLOCK(sc);
513 		if (bp->b_cmd != BUF_CMD_READ && mmc_get_read_only(dev)) {
514 			bp->b_error = EROFS;
515 			bp->b_resid = bp->b_bcount;
516 			bp->b_flags |= B_ERROR;
517 			devstat_end_transaction_buf(&sc->device_stats, bp);
518 			biodone(bio);
519 			continue;
520 		}
521 		MMCBUS_ACQUIRE_BUS(device_get_parent(dev), dev);
522 		sz = sc->disk.d_info.d_media_blksize;
523 		block = bio->bio_offset / sz;
524 		end = block + (bp->b_bcount / sz);
525 		if (bp->b_cmd == BUF_CMD_READ ||
526 		    bp->b_cmd == BUF_CMD_WRITE) {
527 			/* Access to the remaining erase block obsoletes it. */
528 			if (block < sc->eend && end > sc->eblock)
529 				sc->eblock = sc->eend = 0;
530 			block = mmcsd_rw(sc, bio);
531 		} else if (bp->b_cmd == BUF_CMD_FREEBLKS) {
532 			block = mmcsd_delete(sc, bio);
533 		}
534 		MMCBUS_RELEASE_BUS(device_get_parent(dev), dev);
535 		if (block < end) {
536 			bp->b_error = EIO;
537 			bp->b_resid = (end - block) * sz;
538 			bp->b_flags |= B_ERROR;
539 		}
540 		devstat_end_transaction_buf(&sc->device_stats, bp);
541 		biodone(bio);
542 	}
543 out:
544 	/* tell parent we're done */
545 	sc->running = -1;
546 	MMCSD_UNLOCK(sc);
547 	wakeup(sc);
548 
549 	rel_mplock();
550 }
551 
552 static const char *
553 mmcsd_card_name(device_t dev)
554 {
555 	if (mmc_get_card_type(dev) == mode_mmc)
556 		return ("MMC");
557 	if (mmc_get_high_cap(dev))
558 		return ("SDHC");
559 	return ("SD");
560 }
561 
562 static int
563 mmcsd_bus_bit_width(device_t dev)
564 {
565 	if (mmc_get_bus_width(dev) == bus_width_1)
566 		return (1);
567 	if (mmc_get_bus_width(dev) == bus_width_4)
568 		return (4);
569 	return (8);
570 }
571 
572 static device_method_t mmcsd_methods[] = {
573 	DEVMETHOD(device_probe, mmcsd_probe),
574 	DEVMETHOD(device_attach, mmcsd_attach),
575 	DEVMETHOD(device_detach, mmcsd_detach),
576 	DEVMETHOD(device_suspend, mmcsd_suspend),
577 	DEVMETHOD(device_resume, mmcsd_resume),
578 	DEVMETHOD_END
579 };
580 
581 static driver_t mmcsd_driver = {
582 	"mmcsd",
583 	mmcsd_methods,
584 	sizeof(struct mmcsd_softc),
585 };
586 static devclass_t mmcsd_devclass;
587 
588 DRIVER_MODULE(mmcsd, mmc, mmcsd_driver, mmcsd_devclass, NULL, NULL);
589