xref: /freebsd/sys/dev/mmc/mmcsd.c (revision 9162f64b58d01ec01481d60b6cdc06ffd8e8c7fc)
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 
53 #include <sys/cdefs.h>
54 __FBSDID("$FreeBSD$");
55 
56 #include <sys/param.h>
57 #include <sys/systm.h>
58 #include <sys/bio.h>
59 #include <sys/bus.h>
60 #include <sys/conf.h>
61 #include <sys/kernel.h>
62 #include <sys/kthread.h>
63 #include <sys/lock.h>
64 #include <sys/malloc.h>
65 #include <sys/module.h>
66 #include <sys/mutex.h>
67 #include <geom/geom_disk.h>
68 
69 #include <dev/mmc/mmcvar.h>
70 #include <dev/mmc/mmcreg.h>
71 
72 #include "mmcbus_if.h"
73 
74 struct mmcsd_softc {
75 	device_t dev;
76 	struct mtx sc_mtx;
77 	struct disk *disk;
78 	struct proc *p;
79 	struct bio_queue_head bio_queue;
80 	daddr_t eblock, eend;	/* Range remaining after the last erase. */
81 	int running;
82 	int suspend;
83 };
84 
85 /* bus entry points */
86 static int mmcsd_probe(device_t dev);
87 static int mmcsd_attach(device_t dev);
88 static int mmcsd_detach(device_t dev);
89 
90 /* disk routines */
91 static int mmcsd_open(struct disk *dp);
92 static int mmcsd_close(struct disk *dp);
93 static void mmcsd_strategy(struct bio *bp);
94 static void mmcsd_task(void *arg);
95 
96 static const char *mmcsd_card_name(device_t dev);
97 static int mmcsd_bus_bit_width(device_t dev);
98 
99 #define MMCSD_LOCK(_sc)		mtx_lock(&(_sc)->sc_mtx)
100 #define	MMCSD_UNLOCK(_sc)	mtx_unlock(&(_sc)->sc_mtx)
101 #define MMCSD_LOCK_INIT(_sc) \
102 	mtx_init(&_sc->sc_mtx, device_get_nameunit(_sc->dev), \
103 	    "mmcsd", MTX_DEF)
104 #define MMCSD_LOCK_DESTROY(_sc)	mtx_destroy(&_sc->sc_mtx);
105 #define MMCSD_ASSERT_LOCKED(_sc) mtx_assert(&_sc->sc_mtx, MA_OWNED);
106 #define MMCSD_ASSERT_UNLOCKED(_sc) mtx_assert(&_sc->sc_mtx, MA_NOTOWNED);
107 
108 static int
109 mmcsd_probe(device_t dev)
110 {
111 
112 	device_quiet(dev);
113 	device_set_desc(dev, "MMC/SD Memory Card");
114 	return (0);
115 }
116 
117 static int
118 mmcsd_attach(device_t dev)
119 {
120 	struct mmcsd_softc *sc;
121 	struct disk *d;
122 	intmax_t mb;
123 	char unit;
124 
125 	sc = device_get_softc(dev);
126 	sc->dev = dev;
127 	MMCSD_LOCK_INIT(sc);
128 
129 	d = sc->disk = disk_alloc();
130 	d->d_open = mmcsd_open;
131 	d->d_close = mmcsd_close;
132 	d->d_strategy = mmcsd_strategy;
133 	// d->d_dump = mmcsd_dump;	Need polling mmc layer
134 	d->d_name = "mmcsd";
135 	d->d_drv1 = sc;
136 	d->d_maxsize = 4*1024*1024;	/* Maximum defined SD card AU size. */
137 	d->d_sectorsize = mmc_get_sector_size(dev);
138 	d->d_mediasize = mmc_get_media_size(dev) * d->d_sectorsize;
139 	d->d_stripeoffset = 0;
140 	d->d_stripesize = mmc_get_erase_sector(dev) * d->d_sectorsize;
141 	d->d_unit = device_get_unit(dev);
142 	d->d_flags = DISKFLAG_CANDELETE;
143 	/*
144 	 * Display in most natural units.  There's no cards < 1MB.
145 	 * The SD standard goes to 2GiB, but the data format supports
146 	 * up to 4GiB and some card makers push it up to this limit.
147 	 * The SDHC standard only goes to 32GiB (the data format in
148 	 * SDHC is good to 2TiB however, which isn't too ugly at
149 	 * 2048GiBm, so we note it in passing here and don't add the
150 	 * code to print TiB).
151 	 */
152 	mb = d->d_mediasize >> 20;	/* 1MiB == 1 << 20 */
153 	unit = 'M';
154 	if (mb >= 10240) {		/* 1GiB = 1024 MiB */
155 		unit = 'G';
156 		mb /= 1024;
157 	}
158 	device_printf(dev, "%ju%cB <%s Memory Card>%s at %s %dMHz/%dbit\n",
159 	    mb, unit, mmcsd_card_name(dev),
160 	    mmc_get_read_only(dev) ? " (read-only)" : "",
161 	    device_get_nameunit(device_get_parent(dev)),
162 	    mmc_get_tran_speed(dev) / 1000000, mmcsd_bus_bit_width(dev));
163 	disk_create(d, DISK_VERSION);
164 	bioq_init(&sc->bio_queue);
165 
166 	sc->running = 1;
167 	sc->suspend = 0;
168 	sc->eblock = sc->eend = 0;
169 	kproc_create(&mmcsd_task, sc, &sc->p, 0, 0, "task: mmc/sd card");
170 
171 	return (0);
172 }
173 
174 static int
175 mmcsd_detach(device_t dev)
176 {
177 	struct mmcsd_softc *sc = device_get_softc(dev);
178 
179 	MMCSD_LOCK(sc);
180 	sc->suspend = 0;
181 	if (sc->running > 0) {
182 		/* kill thread */
183 		sc->running = 0;
184 		wakeup(sc);
185 		/* wait for thread to finish. */
186 		while (sc->running != -1)
187 			msleep(sc, &sc->sc_mtx, 0, "detach", 0);
188 	}
189 	MMCSD_UNLOCK(sc);
190 
191 	/* Flush the request queue. */
192 	bioq_flush(&sc->bio_queue, NULL, ENXIO);
193 	/* kill disk */
194 	disk_destroy(sc->disk);
195 
196 	MMCSD_LOCK_DESTROY(sc);
197 
198 	return (0);
199 }
200 
201 static int
202 mmcsd_suspend(device_t dev)
203 {
204 	struct mmcsd_softc *sc = device_get_softc(dev);
205 
206 	MMCSD_LOCK(sc);
207 	sc->suspend = 1;
208 	if (sc->running > 0) {
209 		/* kill thread */
210 		sc->running = 0;
211 		wakeup(sc);
212 		/* wait for thread to finish. */
213 		while (sc->running != -1)
214 			msleep(sc, &sc->sc_mtx, 0, "detach", 0);
215 	}
216 	MMCSD_UNLOCK(sc);
217 	return (0);
218 }
219 
220 static int
221 mmcsd_resume(device_t dev)
222 {
223 	struct mmcsd_softc *sc = device_get_softc(dev);
224 
225 	MMCSD_LOCK(sc);
226 	sc->suspend = 0;
227 	if (sc->running <= 0) {
228 		sc->running = 1;
229 		MMCSD_UNLOCK(sc);
230 		kproc_create(&mmcsd_task, sc, &sc->p, 0, 0, "task: mmc/sd card");
231 	} else
232 		MMCSD_UNLOCK(sc);
233 	return (0);
234 }
235 
236 static int
237 mmcsd_open(struct disk *dp)
238 {
239 	return (0);
240 }
241 
242 static int
243 mmcsd_close(struct disk *dp)
244 {
245 	return (0);
246 }
247 
248 static void
249 mmcsd_strategy(struct bio *bp)
250 {
251 	struct mmcsd_softc *sc;
252 
253 	sc = (struct mmcsd_softc *)bp->bio_disk->d_drv1;
254 	MMCSD_LOCK(sc);
255 	if (sc->running > 0 || sc->suspend > 0) {
256 		bioq_disksort(&sc->bio_queue, bp);
257 		MMCSD_UNLOCK(sc);
258 		wakeup(sc);
259 	} else {
260 		MMCSD_UNLOCK(sc);
261 		biofinish(bp, NULL, ENXIO);
262 	}
263 }
264 
265 static daddr_t
266 mmcsd_rw(struct mmcsd_softc *sc, struct bio *bp)
267 {
268 	daddr_t block, end;
269 	struct mmc_command cmd;
270 	struct mmc_command stop;
271 	struct mmc_request req;
272 	struct mmc_data data;
273 	device_t dev = sc->dev;
274 	int sz = sc->disk->d_sectorsize;
275 
276 	block = bp->bio_pblkno;
277 	end = bp->bio_pblkno + (bp->bio_bcount / sz);
278 	while (block < end) {
279 		char *vaddr = bp->bio_data +
280 		    (block - bp->bio_pblkno) * sz;
281 		int numblocks = min(end - block, mmc_get_max_data(dev));
282 		memset(&req, 0, sizeof(req));
283     		memset(&cmd, 0, sizeof(cmd));
284 		memset(&stop, 0, sizeof(stop));
285 		req.cmd = &cmd;
286 		cmd.data = &data;
287 		if (bp->bio_cmd == BIO_READ) {
288 			if (numblocks > 1)
289 				cmd.opcode = MMC_READ_MULTIPLE_BLOCK;
290 			else
291 				cmd.opcode = MMC_READ_SINGLE_BLOCK;
292 		} else {
293 			if (numblocks > 1)
294 				cmd.opcode = MMC_WRITE_MULTIPLE_BLOCK;
295 			else
296 				cmd.opcode = MMC_WRITE_BLOCK;
297 		}
298 		cmd.arg = block;
299 		if (!mmc_get_high_cap(dev))
300 			cmd.arg <<= 9;
301 		cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
302 		data.data = vaddr;
303 		data.mrq = &req;
304 		if (bp->bio_cmd == BIO_READ)
305 			data.flags = MMC_DATA_READ;
306 		else
307 			data.flags = MMC_DATA_WRITE;
308 		data.len = numblocks * sz;
309 		if (numblocks > 1) {
310 			data.flags |= MMC_DATA_MULTI;
311 			stop.opcode = MMC_STOP_TRANSMISSION;
312 			stop.arg = 0;
313 			stop.flags = MMC_RSP_R1B | MMC_CMD_AC;
314 			req.stop = &stop;
315 		}
316 //		printf("Len %d  %lld-%lld flags %#x sz %d\n",
317 //		    (int)data.len, (long long)block, (long long)end, data.flags, sz);
318 		MMCBUS_WAIT_FOR_REQUEST(device_get_parent(dev), dev,
319 		    &req);
320 		if (req.cmd->error != MMC_ERR_NONE)
321 			break;
322 		block += numblocks;
323 	}
324 	return (block);
325 }
326 
327 static daddr_t
328 mmcsd_delete(struct mmcsd_softc *sc, struct bio *bp)
329 {
330 	daddr_t block, end, start, stop;
331 	struct mmc_command cmd;
332 	struct mmc_request req;
333 	device_t dev = sc->dev;
334 	int sz = sc->disk->d_sectorsize;
335 	int erase_sector;
336 
337 	block = bp->bio_pblkno;
338 	end = bp->bio_pblkno + (bp->bio_bcount / sz);
339 	/* Coalesce with part remaining from previous request. */
340 	if (block > sc->eblock && block <= sc->eend)
341 		block = sc->eblock;
342 	if (end >= sc->eblock && end < sc->eend)
343 		end = sc->eend;
344 	/* Safe round to the erase sector boundaries. */
345 	erase_sector = mmc_get_erase_sector(dev);
346 	start = block + erase_sector - 1;	 /* Round up. */
347 	start -= start % erase_sector;
348 	stop = end;				/* Round down. */
349 	stop -= end % erase_sector;
350 	/* We can't erase area smaller then sector, store it for later. */
351 	if (start >= stop) {
352 		sc->eblock = block;
353 		sc->eend = end;
354 		return (end);
355 	}
356 
357 	/* Set erase start position. */
358 	memset(&req, 0, sizeof(req));
359 	memset(&cmd, 0, sizeof(cmd));
360 	req.cmd = &cmd;
361 	if (mmc_get_card_type(dev) == mode_sd)
362 		cmd.opcode = SD_ERASE_WR_BLK_START;
363 	else
364 		cmd.opcode = MMC_ERASE_GROUP_START;
365 	cmd.arg = start;
366 	if (!mmc_get_high_cap(dev))
367 		cmd.arg <<= 9;
368 	cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
369 	MMCBUS_WAIT_FOR_REQUEST(device_get_parent(dev), dev,
370 	    &req);
371 	if (req.cmd->error != MMC_ERR_NONE) {
372 	    printf("erase err1: %d\n", req.cmd->error);
373 	    return (block);
374 	}
375 	/* Set erase stop position. */
376 	memset(&req, 0, sizeof(req));
377 	memset(&cmd, 0, sizeof(cmd));
378 	req.cmd = &cmd;
379 	if (mmc_get_card_type(dev) == mode_sd)
380 		cmd.opcode = SD_ERASE_WR_BLK_END;
381 	else
382 		cmd.opcode = MMC_ERASE_GROUP_END;
383 	cmd.arg = stop;
384 	if (!mmc_get_high_cap(dev))
385 		cmd.arg <<= 9;
386 	cmd.arg--;
387 	cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
388 	MMCBUS_WAIT_FOR_REQUEST(device_get_parent(dev), dev,
389 	    &req);
390 	if (req.cmd->error != MMC_ERR_NONE) {
391 	    printf("erase err2: %d\n", req.cmd->error);
392 	    return (block);
393 	}
394 	/* Erase range. */
395 	memset(&req, 0, sizeof(req));
396 	memset(&cmd, 0, sizeof(cmd));
397 	req.cmd = &cmd;
398 	cmd.opcode = MMC_ERASE;
399 	cmd.arg = 0;
400 	cmd.flags = MMC_RSP_R1B | MMC_CMD_AC;
401 	MMCBUS_WAIT_FOR_REQUEST(device_get_parent(dev), dev,
402 	    &req);
403 	if (req.cmd->error != MMC_ERR_NONE) {
404 	    printf("erase err3 %d\n", req.cmd->error);
405 	    return (block);
406 	}
407 	/* Store one of remaining parts for the next call. */
408 	if (bp->bio_pblkno >= sc->eblock || block == start) {
409 		sc->eblock = stop;	/* Predict next forward. */
410 		sc->eend = end;
411 	} else {
412 		sc->eblock = block;	/* Predict next backward. */
413 		sc->eend = start;
414 	}
415 	return (end);
416 }
417 
418 static void
419 mmcsd_task(void *arg)
420 {
421 	struct mmcsd_softc *sc = (struct mmcsd_softc*)arg;
422 	struct bio *bp;
423 	int sz;
424 	daddr_t block, end;
425 	device_t dev;
426 
427 	dev = sc->dev;
428 	while (1) {
429 		MMCSD_LOCK(sc);
430 		do {
431 			if (sc->running == 0)
432 				goto out;
433 			bp = bioq_takefirst(&sc->bio_queue);
434 			if (bp == NULL)
435 				msleep(sc, &sc->sc_mtx, PRIBIO, "jobqueue", 0);
436 		} while (bp == NULL);
437 		MMCSD_UNLOCK(sc);
438 		if (bp->bio_cmd != BIO_READ && mmc_get_read_only(dev)) {
439 			bp->bio_error = EROFS;
440 			bp->bio_resid = bp->bio_bcount;
441 			bp->bio_flags |= BIO_ERROR;
442 			biodone(bp);
443 			continue;
444 		}
445 		MMCBUS_ACQUIRE_BUS(device_get_parent(dev), dev);
446 		sz = sc->disk->d_sectorsize;
447 		block = bp->bio_pblkno;
448 		end = bp->bio_pblkno + (bp->bio_bcount / sz);
449 		if (bp->bio_cmd == BIO_READ || bp->bio_cmd == BIO_WRITE) {
450 			/* Access to the remaining erase block obsoletes it. */
451 			if (block < sc->eend && end > sc->eblock)
452 				sc->eblock = sc->eend = 0;
453 			block = mmcsd_rw(sc, bp);
454 		} else if (bp->bio_cmd == BIO_DELETE) {
455 			block = mmcsd_delete(sc, bp);
456 		}
457 		MMCBUS_RELEASE_BUS(device_get_parent(dev), dev);
458 		if (block < end) {
459 			bp->bio_error = EIO;
460 			bp->bio_resid = (end - block) * sz;
461 			bp->bio_flags |= BIO_ERROR;
462 		}
463 		biodone(bp);
464 	}
465 out:
466 	/* tell parent we're done */
467 	sc->running = -1;
468 	MMCSD_UNLOCK(sc);
469 	wakeup(sc);
470 
471 	kproc_exit(0);
472 }
473 
474 static const char *
475 mmcsd_card_name(device_t dev)
476 {
477 	if (mmc_get_card_type(dev) == mode_mmc)
478 		return ("MMC");
479 	if (mmc_get_high_cap(dev))
480 		return ("SDHC");
481 	return ("SD");
482 }
483 
484 static int
485 mmcsd_bus_bit_width(device_t dev)
486 {
487 	if (mmc_get_bus_width(dev) == bus_width_1)
488 		return (1);
489 	if (mmc_get_bus_width(dev) == bus_width_4)
490 		return (4);
491 	return (8);
492 }
493 
494 static device_method_t mmcsd_methods[] = {
495 	DEVMETHOD(device_probe, mmcsd_probe),
496 	DEVMETHOD(device_attach, mmcsd_attach),
497 	DEVMETHOD(device_detach, mmcsd_detach),
498 	DEVMETHOD(device_suspend, mmcsd_suspend),
499 	DEVMETHOD(device_resume, mmcsd_resume),
500 	{0, 0},
501 };
502 
503 static driver_t mmcsd_driver = {
504 	"mmcsd",
505 	mmcsd_methods,
506 	sizeof(struct mmcsd_softc),
507 };
508 static devclass_t mmcsd_devclass;
509 
510 DRIVER_MODULE(mmcsd, mmc, mmcsd_driver, mmcsd_devclass, 0, 0);
511