xref: /netbsd-src/sys/dev/scsipi/cd.c (revision 11a6dbe72840351315e0652b2fc6663628c84cad)
1 /*	$NetBSD: cd.c,v 1.274 2008/04/28 20:23:57 martin Exp $	*/
2 
3 /*-
4  * Copyright (c) 1998, 2001, 2003, 2004, 2005 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Charles M. Hannum.
9  *
10  * MMC discinfo/trackinfo contributed to the NetBSD Foundation by Reinoud
11  * Zandijk.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 /*
36  * Originally written by Julian Elischer (julian@tfs.com)
37  * for TRW Financial Systems for use under the MACH(2.5) operating system.
38  *
39  * TRW Financial Systems, in accordance with their agreement with Carnegie
40  * Mellon University, makes this software available to CMU to distribute
41  * or use in any manner that they see fit as long as this message is kept with
42  * the software. For this reason TFS also grants any other persons or
43  * organisations permission to use or modify this software.
44  *
45  * TFS supplies this software to be publicly redistributed
46  * on the understanding that TFS is not responsible for the correct
47  * functioning of this software in any circumstances.
48  *
49  * Ported to run under 386BSD by Julian Elischer (julian@tfs.com) Sept 1992
50  */
51 
52 #include <sys/cdefs.h>
53 __KERNEL_RCSID(0, "$NetBSD: cd.c,v 1.274 2008/04/28 20:23:57 martin Exp $");
54 
55 #include "rnd.h"
56 
57 #include <sys/param.h>
58 #include <sys/systm.h>
59 #include <sys/kernel.h>
60 #include <sys/file.h>
61 #include <sys/stat.h>
62 #include <sys/ioctl.h>
63 #include <sys/buf.h>
64 #include <sys/bufq.h>
65 #include <sys/uio.h>
66 #include <sys/malloc.h>
67 #include <sys/errno.h>
68 #include <sys/device.h>
69 #include <sys/disklabel.h>
70 #include <sys/disk.h>
71 #include <sys/cdio.h>
72 #include <sys/dvdio.h>
73 #include <sys/scsiio.h>
74 #include <sys/proc.h>
75 #include <sys/conf.h>
76 #include <sys/vnode.h>
77 #if NRND > 0
78 #include <sys/rnd.h>
79 #endif
80 
81 #include <dev/scsipi/scsi_spc.h>
82 #include <dev/scsipi/scsipi_all.h>
83 #include <dev/scsipi/scsipi_cd.h>
84 #include <dev/scsipi/scsipi_disk.h>	/* rw_big and start_stop come */
85 #include <dev/scsipi/scsi_all.h>
86 					/* from there */
87 #include <dev/scsipi/scsi_disk.h>	/* rw comes from there */
88 #include <dev/scsipi/scsipiconf.h>
89 #include <dev/scsipi/scsipi_base.h>
90 #include <dev/scsipi/cdvar.h>
91 
92 #define	CDUNIT(z)			DISKUNIT(z)
93 #define	CDPART(z)			DISKPART(z)
94 #define	CDMINOR(unit, part)		DISKMINOR(unit, part)
95 #define	MAKECDDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)
96 
97 #define MAXTRACK	99
98 #define CD_BLOCK_OFFSET	150
99 #define CD_FRAMES	75
100 #define CD_SECS		60
101 
102 #define CD_TOC_FORM	0	/* formatted TOC, exposed to userland     */
103 #define CD_TOC_MSINFO	1	/* multi-session info			  */
104 #define CD_TOC_RAW	2	/* raw TOC as on disc, unprocessed	  */
105 #define CD_TOC_PMA	3	/* PMA, used as intermediate (rare use)   */
106 #define CD_TOC_ATIP	4	/* pressed space of recordable		  */
107 #define CD_TOC_CDTEXT	5	/* special CD-TEXT, rarely used		  */
108 
109 struct cd_formatted_toc {
110 	struct ioc_toc_header header;
111 	struct cd_toc_entry entries[MAXTRACK+1]; /* One extra for the */
112 						 /* leadout */
113 };
114 
115 struct cdbounce {
116 	struct buf     *obp;			/* original buf */
117 	int		doff;			/* byte offset in orig. buf */
118 	int		soff;			/* byte offset in bounce buf */
119 	int		resid;			/* residual i/o in orig. buf */
120 	int		bcount;			/* actual obp bytes in bounce */
121 };
122 
123 static void	cdstart(struct scsipi_periph *);
124 static void	cdrestart(void *);
125 static void	cdminphys(struct buf *);
126 static void	cdgetdefaultlabel(struct cd_softc *, struct cd_formatted_toc *,
127 		    struct disklabel *);
128 static void	cdgetdisklabel(struct cd_softc *);
129 static void	cddone(struct scsipi_xfer *, int);
130 static void	cdbounce(struct buf *);
131 static int	cd_interpret_sense(struct scsipi_xfer *);
132 static u_long	cd_size(struct cd_softc *, int);
133 static int	cd_play(struct cd_softc *, int, int);
134 static int	cd_play_tracks(struct cd_softc *, struct cd_formatted_toc *,
135 		    int, int, int, int);
136 static int	cd_play_msf(struct cd_softc *, int, int, int, int, int, int);
137 static int	cd_pause(struct cd_softc *, int);
138 static int	cd_reset(struct cd_softc *);
139 static int	cd_read_subchannel(struct cd_softc *, int, int, int,
140 		    struct cd_sub_channel_info *, int, int);
141 static int	cd_read_toc(struct cd_softc *, int, int, int,
142 		    struct cd_formatted_toc *, int, int, int);
143 static int	cd_get_parms(struct cd_softc *, int);
144 static int	cd_load_toc(struct cd_softc *, int, struct cd_formatted_toc *, int);
145 static int	cdreadmsaddr(struct cd_softc *, struct cd_formatted_toc *,int *);
146 
147 static int	dvd_auth(struct cd_softc *, dvd_authinfo *);
148 static int	dvd_read_physical(struct cd_softc *, dvd_struct *);
149 static int	dvd_read_copyright(struct cd_softc *, dvd_struct *);
150 static int	dvd_read_disckey(struct cd_softc *, dvd_struct *);
151 static int	dvd_read_bca(struct cd_softc *, dvd_struct *);
152 static int	dvd_read_manufact(struct cd_softc *, dvd_struct *);
153 static int	dvd_read_struct(struct cd_softc *, dvd_struct *);
154 
155 static int	cd_mode_sense(struct cd_softc *, u_int8_t, void *, size_t, int,
156 		    int, int *);
157 static int	cd_mode_select(struct cd_softc *, u_int8_t, void *, size_t,
158 		    int, int);
159 static int	cd_setchan(struct cd_softc *, int, int, int, int, int);
160 static int	cd_getvol(struct cd_softc *, struct ioc_vol *, int);
161 static int	cd_setvol(struct cd_softc *, const struct ioc_vol *, int);
162 static int	cd_set_pa_immed(struct cd_softc *, int);
163 static int	cd_load_unload(struct cd_softc *, struct ioc_load_unload *);
164 static int	cd_setblksize(struct cd_softc *);
165 
166 static int	cdmatch(device_t, cfdata_t, void *);
167 static void	cdattach(device_t, device_t, void *);
168 static int	cdactivate(device_t, enum devact);
169 static int	cddetach(device_t, int);
170 
171 static int	mmc_getdiscinfo(struct scsipi_periph *, struct mmc_discinfo *);
172 static int	mmc_gettrackinfo(struct scsipi_periph *, struct mmc_trackinfo *);
173 
174 CFATTACH_DECL_NEW(cd, sizeof(struct cd_softc), cdmatch, cdattach, cddetach,
175     cdactivate);
176 
177 extern struct cfdriver cd_cd;
178 
179 static const struct scsipi_inquiry_pattern cd_patterns[] = {
180 	{T_CDROM, T_REMOV,
181 	 "",         "",                 ""},
182 	{T_WORM, T_REMOV,
183 	 "",         "",                 ""},
184 #if 0
185 	{T_CDROM, T_REMOV, /* more luns */
186 	 "PIONEER ", "CD-ROM DRM-600  ", ""},
187 #endif
188 	{T_DIRECT, T_REMOV,
189 	 "NEC                 CD-ROM DRIVE:260", "", ""},
190 };
191 
192 static dev_type_open(cdopen);
193 static dev_type_close(cdclose);
194 static dev_type_read(cdread);
195 static dev_type_write(cdwrite);
196 static dev_type_ioctl(cdioctl);
197 static dev_type_strategy(cdstrategy);
198 static dev_type_dump(cddump);
199 static dev_type_size(cdsize);
200 
201 const struct bdevsw cd_bdevsw = {
202 	cdopen, cdclose, cdstrategy, cdioctl, cddump, cdsize, D_DISK
203 };
204 
205 const struct cdevsw cd_cdevsw = {
206 	cdopen, cdclose, cdread, cdwrite, cdioctl,
207 	nostop, notty, nopoll, nommap, nokqfilter, D_DISK
208 };
209 
210 static struct dkdriver cddkdriver = { cdstrategy, NULL };
211 
212 static const struct scsipi_periphsw cd_switch = {
213 	cd_interpret_sense,	/* use our error handler first */
214 	cdstart,		/* we have a queue, which is started by this */
215 	NULL,			/* we do not have an async handler */
216 	cddone,			/* deal with stats at interrupt time */
217 };
218 
219 /*
220  * The routine called by the low level scsi routine when it discovers
221  * A device suitable for this driver
222  */
223 static int
224 cdmatch(device_t parent, cfdata_t match, void *aux)
225 {
226 	struct scsipibus_attach_args *sa = aux;
227 	int priority;
228 
229 	(void)scsipi_inqmatch(&sa->sa_inqbuf,
230 	    cd_patterns, sizeof(cd_patterns) / sizeof(cd_patterns[0]),
231 	    sizeof(cd_patterns[0]), &priority);
232 
233 	return (priority);
234 }
235 
236 static void
237 cdattach(device_t parent, device_t self, void *aux)
238 {
239 	struct cd_softc *cd = device_private(self);
240 	struct scsipibus_attach_args *sa = aux;
241 	struct scsipi_periph *periph = sa->sa_periph;
242 
243 	SC_DEBUG(periph, SCSIPI_DB2, ("cdattach: "));
244 
245 	cd->sc_dev = self;
246 
247 	mutex_init(&cd->sc_lock, MUTEX_DEFAULT, IPL_NONE);
248 
249 	if (scsipi_periph_bustype(sa->sa_periph) == SCSIPI_BUSTYPE_SCSI &&
250 	    periph->periph_version == 0)
251 		cd->flags |= CDF_ANCIENT;
252 
253 	bufq_alloc(&cd->buf_queue, "disksort", BUFQ_SORT_RAWBLOCK);
254 
255 	callout_init(&cd->sc_callout, 0);
256 
257 	/*
258 	 * Store information needed to contact our base driver
259 	 */
260 	cd->sc_periph = periph;
261 
262 	periph->periph_dev = cd->sc_dev;
263 	periph->periph_switch = &cd_switch;
264 
265 	/*
266 	 * Increase our openings to the maximum-per-periph
267 	 * supported by the adapter.  This will either be
268 	 * clamped down or grown by the adapter if necessary.
269 	 */
270 	periph->periph_openings =
271 	    SCSIPI_CHAN_MAX_PERIPH(periph->periph_channel);
272 	periph->periph_flags |= PERIPH_GROW_OPENINGS;
273 
274 	/*
275 	 * Initialize and attach the disk structure.
276 	 */
277 	disk_init(&cd->sc_dk, device_xname(cd->sc_dev), &cddkdriver);
278 	disk_attach(&cd->sc_dk);
279 
280 	printf("\n");
281 
282 #if NRND > 0
283 	rnd_attach_source(&cd->rnd_source, device_xname(cd->sc_dev),
284 			  RND_TYPE_DISK, 0);
285 #endif
286 
287 	if (!pmf_device_register(self, NULL, NULL))
288 		aprint_error_dev(self, "couldn't establish power handler\n");
289 }
290 
291 static int
292 cdactivate(device_t self, enum devact act)
293 {
294 	int rv = 0;
295 
296 	switch (act) {
297 	case DVACT_ACTIVATE:
298 		rv = EOPNOTSUPP;
299 		break;
300 
301 	case DVACT_DEACTIVATE:
302 		/*
303 		 * Nothing to do; we key off the device's DVF_ACTIVE.
304 		 */
305 		break;
306 	}
307 	return (rv);
308 }
309 
310 static int
311 cddetach(device_t self, int flags)
312 {
313 	struct cd_softc *cd = device_private(self);
314 	int s, bmaj, cmaj, i, mn;
315 
316 	/* locate the major number */
317 	bmaj = bdevsw_lookup_major(&cd_bdevsw);
318 	cmaj = cdevsw_lookup_major(&cd_cdevsw);
319 	/* Nuke the vnodes for any open instances */
320 	for (i = 0; i < MAXPARTITIONS; i++) {
321 		mn = CDMINOR(device_unit(self), i);
322 		vdevgone(bmaj, mn, mn, VBLK);
323 		vdevgone(cmaj, mn, mn, VCHR);
324 	}
325 
326 	/* kill any pending restart */
327 	callout_stop(&cd->sc_callout);
328 
329 	s = splbio();
330 
331 	/* Kill off any queued buffers. */
332 	bufq_drain(cd->buf_queue);
333 
334 	bufq_free(cd->buf_queue);
335 
336 	/* Kill off any pending commands. */
337 	scsipi_kill_pending(cd->sc_periph);
338 
339 	splx(s);
340 
341 	mutex_destroy(&cd->sc_lock);
342 
343 	/* Detach from the disk list. */
344 	disk_detach(&cd->sc_dk);
345 	disk_destroy(&cd->sc_dk);
346 
347 #if 0
348 	/* Get rid of the shutdown hook. */
349 	if (cd->sc_sdhook != NULL)
350 		shutdownhook_disestablish(cd->sc_sdhook);
351 #endif
352 
353 #if NRND > 0
354 	/* Unhook the entropy source. */
355 	rnd_detach_source(&cd->rnd_source);
356 #endif
357 
358 	return (0);
359 }
360 
361 /*
362  * open the device. Make sure the partition info is a up-to-date as can be.
363  */
364 static int
365 cdopen(dev_t dev, int flag, int fmt, struct lwp *l)
366 {
367 	struct cd_softc *cd;
368 	struct scsipi_periph *periph;
369 	struct scsipi_adapter *adapt;
370 	int part;
371 	int error;
372 	int rawpart;
373 
374 	cd = device_lookup_private(&cd_cd, CDUNIT(dev));
375 	if (cd == NULL)
376 		return (ENXIO);
377 
378 	periph = cd->sc_periph;
379 	adapt = periph->periph_channel->chan_adapter;
380 	part = CDPART(dev);
381 
382 	SC_DEBUG(periph, SCSIPI_DB1,
383 	    ("cdopen: dev=0x%x (unit %d (of %d), partition %d)\n", dev,
384 	    CDUNIT(dev), cd_cd.cd_ndevs, CDPART(dev)));
385 
386 	/*
387 	 * If this is the first open of this device, add a reference
388 	 * to the adapter.
389 	 */
390 	if (cd->sc_dk.dk_openmask == 0 &&
391 	    (error = scsipi_adapter_addref(adapt)) != 0)
392 		return (error);
393 
394 	mutex_enter(&cd->sc_lock);
395 
396 	rawpart = (part == RAW_PART && fmt == S_IFCHR);
397 	if ((periph->periph_flags & PERIPH_OPEN) != 0) {
398 		/*
399 		 * If any partition is open, but the disk has been invalidated,
400 		 * disallow further opens.
401 		 */
402 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0 &&
403 			!rawpart) {
404 			error = EIO;
405 			goto bad3;
406 		}
407 	} else {
408 		int silent;
409 
410 		if (rawpart)
411 			silent = XS_CTL_SILENT;
412 		else
413 			silent = 0;
414 
415 		/* Check that it is still responding and ok. */
416 		error = scsipi_test_unit_ready(periph,
417 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE |
418 		    silent);
419 
420 		/*
421 		 * Start the pack spinning if necessary. Always allow the
422 		 * raw parition to be opened, for raw IOCTLs. Data transfers
423 		 * will check for SDEV_MEDIA_LOADED.
424 		 */
425 		if (error == EIO) {
426 			int error2;
427 
428 			error2 = scsipi_start(periph, SSS_START, silent);
429 			switch (error2) {
430 			case 0:
431 				error = 0;
432 				break;
433 			case EIO:
434 			case EINVAL:
435 				break;
436 			default:
437 				error = error2;
438 				break;
439 			}
440 		}
441 		if (error) {
442 			if (rawpart)
443 				goto out;
444 			goto bad3;
445 		}
446 
447 		periph->periph_flags |= PERIPH_OPEN;
448 
449 		/* Lock the pack in. */
450 		error = scsipi_prevent(periph, SPAMR_PREVENT_DT,
451 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE);
452 		SC_DEBUG(periph, SCSIPI_DB1,
453 		    ("cdopen: scsipi_prevent, error=%d\n", error));
454 		if (error) {
455 			if (rawpart)
456 				goto out;
457 			goto bad;
458 		}
459 
460 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
461 			/* Load the physical device parameters. */
462 			if (cd_get_parms(cd, 0) != 0) {
463 				if (rawpart)
464 					goto out;
465 				error = ENXIO;
466 				goto bad;
467 			}
468 			periph->periph_flags |= PERIPH_MEDIA_LOADED;
469 			SC_DEBUG(periph, SCSIPI_DB3, ("Params loaded "));
470 
471 			/* Fabricate a disk label. */
472 			cdgetdisklabel(cd);
473 			SC_DEBUG(periph, SCSIPI_DB3, ("Disklabel fabricated "));
474 		}
475 	}
476 
477 	/* Check that the partition exists. */
478 	if (part != RAW_PART &&
479 	    (part >= cd->sc_dk.dk_label->d_npartitions ||
480 	    cd->sc_dk.dk_label->d_partitions[part].p_fstype == FS_UNUSED)) {
481 		error = ENXIO;
482 		goto bad;
483 	}
484 
485 out:	/* Insure only one open at a time. */
486 	switch (fmt) {
487 	case S_IFCHR:
488 		cd->sc_dk.dk_copenmask |= (1 << part);
489 		break;
490 	case S_IFBLK:
491 		cd->sc_dk.dk_bopenmask |= (1 << part);
492 		break;
493 	}
494 	cd->sc_dk.dk_openmask =
495 	    cd->sc_dk.dk_copenmask | cd->sc_dk.dk_bopenmask;
496 
497 	SC_DEBUG(periph, SCSIPI_DB3, ("open complete\n"));
498 	mutex_exit(&cd->sc_lock);
499 	return (0);
500 
501 	periph->periph_flags &= ~PERIPH_MEDIA_LOADED;
502 
503 bad:
504 	if (cd->sc_dk.dk_openmask == 0) {
505 		scsipi_prevent(periph, SPAMR_ALLOW,
506 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE);
507 		periph->periph_flags &= ~PERIPH_OPEN;
508 	}
509 
510 bad3:
511 	mutex_exit(&cd->sc_lock);
512 	if (cd->sc_dk.dk_openmask == 0)
513 		scsipi_adapter_delref(adapt);
514 	return (error);
515 }
516 
517 /*
518  * close the device.. only called if we are the LAST
519  * occurence of an open device
520  */
521 static int
522 cdclose(dev_t dev, int flag, int fmt, struct lwp *l)
523 {
524 	struct cd_softc *cd = device_lookup_private(&cd_cd, CDUNIT(dev));
525 	struct scsipi_periph *periph = cd->sc_periph;
526 	struct scsipi_adapter *adapt = periph->periph_channel->chan_adapter;
527 	int part = CDPART(dev);
528 
529 	mutex_enter(&cd->sc_lock);
530 
531 	switch (fmt) {
532 	case S_IFCHR:
533 		cd->sc_dk.dk_copenmask &= ~(1 << part);
534 		break;
535 	case S_IFBLK:
536 		cd->sc_dk.dk_bopenmask &= ~(1 << part);
537 		break;
538 	}
539 	cd->sc_dk.dk_openmask =
540 	    cd->sc_dk.dk_copenmask | cd->sc_dk.dk_bopenmask;
541 
542 	if (cd->sc_dk.dk_openmask == 0) {
543 		scsipi_wait_drain(periph);
544 
545 		scsipi_prevent(periph, SPAMR_ALLOW,
546 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE |
547 		    XS_CTL_IGNORE_NOT_READY);
548 		periph->periph_flags &= ~PERIPH_OPEN;
549 
550 		scsipi_wait_drain(periph);
551 
552 		scsipi_adapter_delref(adapt);
553 	}
554 
555 	mutex_exit(&cd->sc_lock);
556 	return (0);
557 }
558 
559 /*
560  * Actually translate the requested transfer into one the physical driver can
561  * understand.  The transfer is described by a buf and will include only one
562  * physical transfer.
563  */
564 static void
565 cdstrategy(struct buf *bp)
566 {
567 	struct cd_softc *cd = device_lookup_private(&cd_cd,CDUNIT(bp->b_dev));
568 	struct disklabel *lp;
569 	struct scsipi_periph *periph = cd->sc_periph;
570 	daddr_t blkno;
571 	int s;
572 
573 	SC_DEBUG(cd->sc_periph, SCSIPI_DB2, ("cdstrategy "));
574 	SC_DEBUG(cd->sc_periph, SCSIPI_DB1,
575 	    ("%d bytes @ blk %" PRId64 "\n", bp->b_bcount, bp->b_blkno));
576 	/*
577 	 * If the device has been made invalid, error out
578 	 * maybe the media changed
579 	 */
580 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
581 		if (periph->periph_flags & PERIPH_OPEN)
582 			bp->b_error = EIO;
583 		else
584 			bp->b_error = ENODEV;
585 		goto done;
586 	}
587 
588 	lp = cd->sc_dk.dk_label;
589 
590 	/*
591 	 * The transfer must be a whole number of blocks, offset must not
592 	 * be negative.
593 	 */
594 	if ((bp->b_bcount % lp->d_secsize) != 0 ||
595 	    bp->b_blkno < 0 ) {
596 		bp->b_error = EINVAL;
597 		goto done;
598 	}
599 	/*
600 	 * If it's a null transfer, return immediately
601 	 */
602 	if (bp->b_bcount == 0)
603 		goto done;
604 
605 	/*
606 	 * Do bounds checking, adjust transfer. if error, process.
607 	 * If end of partition, just return.
608 	 */
609 	if (CDPART(bp->b_dev) == RAW_PART) {
610 		if (bounds_check_with_mediasize(bp, DEV_BSIZE,
611 		    cd->params.disksize512) <= 0)
612 			goto done;
613 	} else {
614 		if (bounds_check_with_label(&cd->sc_dk, bp,
615 		    (cd->flags & (CDF_WLABEL|CDF_LABELLING)) != 0) <= 0)
616 			goto done;
617 	}
618 
619 	/*
620 	 * Now convert the block number to absolute and put it in
621 	 * terms of the device's logical block size.
622 	 */
623 	blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE);
624 	if (CDPART(bp->b_dev) != RAW_PART)
625 		blkno += lp->d_partitions[CDPART(bp->b_dev)].p_offset;
626 
627 	bp->b_rawblkno = blkno;
628 
629 	/*
630 	 * If the disklabel sector size does not match the device
631 	 * sector size we may need to do some extra work.
632 	 */
633 	if (lp->d_secsize != cd->params.blksize) {
634 
635 		/*
636 		 * If the xfer is not a multiple of the device block size
637 		 * or it is not block aligned, we need to bounce it.
638 		 */
639 		if ((bp->b_bcount % cd->params.blksize) != 0 ||
640 			((blkno * lp->d_secsize) % cd->params.blksize) != 0) {
641 			struct cdbounce *bounce;
642 			struct buf *nbp;
643 			long count;
644 
645 			if ((bp->b_flags & B_READ) == 0) {
646 
647 				/* XXXX We don't support bouncing writes. */
648 				bp->b_error = EACCES;
649 				goto done;
650 			}
651 
652 			bounce = malloc(sizeof(*bounce), M_DEVBUF, M_NOWAIT);
653 			if (!bounce) {
654 				/* No memory -- fail the iop. */
655 				bp->b_error = ENOMEM;
656 				goto done;
657 			}
658 
659 			bounce->obp = bp;
660 			bounce->resid = bp->b_bcount;
661 			bounce->doff = 0;
662 			count = ((blkno * lp->d_secsize) % cd->params.blksize);
663 			bounce->soff = count;
664 			count += bp->b_bcount;
665 			count = roundup(count, cd->params.blksize);
666 			bounce->bcount = bounce->resid;
667 			if (count > MAXPHYS) {
668 				bounce->bcount = MAXPHYS - bounce->soff;
669 				count = MAXPHYS;
670 			}
671 
672 			blkno = ((blkno * lp->d_secsize) / cd->params.blksize);
673 			nbp = getiobuf(false, NULL);
674 			if (!nbp) {
675 				/* No memory -- fail the iop. */
676 				free(bounce, M_DEVBUF);
677 				bp->b_error = ENOMEM;
678 				goto done;
679 			}
680 			nbp->b_data = malloc(count, M_DEVBUF, M_NOWAIT);
681 			if (!nbp->b_data) {
682 				/* No memory -- fail the iop. */
683 				free(bounce, M_DEVBUF);
684 				putiobuf(nbp);
685 				bp->b_error = ENOMEM;
686 				goto done;
687 			}
688 
689 			/* Set up the IOP to the bounce buffer. */
690 			nbp->b_error = 0;
691 			nbp->b_proc = bp->b_proc;
692 			nbp->b_bcount = count;
693 			nbp->b_bufsize = count;
694 			nbp->b_rawblkno = blkno;
695 			nbp->b_flags = bp->b_flags | B_READ;
696 			nbp->b_oflags = bp->b_oflags;
697 			nbp->b_cflags = bp->b_cflags;
698 			nbp->b_iodone = cdbounce;
699 
700 			/* store bounce state in b_private and use new buf */
701 			nbp->b_private = bounce;
702 
703 			BIO_COPYPRIO(nbp, bp);
704 
705 			bp = nbp;
706 
707 		} else {
708 			/* Xfer is aligned -- just adjust the start block */
709 			bp->b_rawblkno = (blkno * lp->d_secsize) /
710 				cd->params.blksize;
711 		}
712 	}
713 	s = splbio();
714 
715 	/*
716 	 * Place it in the queue of disk activities for this disk.
717 	 *
718 	 * XXX Only do disksort() if the current operating mode does not
719 	 * XXX include tagged queueing.
720 	 */
721 	BUFQ_PUT(cd->buf_queue, bp);
722 
723 	/*
724 	 * Tell the device to get going on the transfer if it's
725 	 * not doing anything, otherwise just wait for completion
726 	 */
727 	cdstart(cd->sc_periph);
728 
729 	splx(s);
730 	return;
731 
732 done:
733 	/*
734 	 * Correctly set the buf to indicate a completed xfer
735 	 */
736 	bp->b_resid = bp->b_bcount;
737 	biodone(bp);
738 }
739 
740 /*
741  * cdstart looks to see if there is a buf waiting for the device
742  * and that the device is not already busy. If both are true,
743  * It deques the buf and creates a scsi command to perform the
744  * transfer in the buf. The transfer request will call scsipi_done
745  * on completion, which will in turn call this routine again
746  * so that the next queued transfer is performed.
747  * The bufs are queued by the strategy routine (cdstrategy)
748  *
749  * This routine is also called after other non-queued requests
750  * have been made of the scsi driver, to ensure that the queue
751  * continues to be drained.
752  *
753  * must be called at the correct (highish) spl level
754  * cdstart() is called at splbio from cdstrategy, cdrestart and scsipi_done
755  */
756 static void
757 cdstart(struct scsipi_periph *periph)
758 {
759 	struct cd_softc *cd = device_private(periph->periph_dev);
760 	struct buf *bp = 0;
761 	struct scsipi_rw_10 cmd_big;
762 	struct scsi_rw_6 cmd_small;
763 	struct scsipi_generic *cmdp;
764 	struct scsipi_xfer *xs;
765 	int flags, nblks, cmdlen, error;
766 
767 	SC_DEBUG(periph, SCSIPI_DB2, ("cdstart "));
768 	/*
769 	 * Check if the device has room for another command
770 	 */
771 	while (periph->periph_active < periph->periph_openings) {
772 		/*
773 		 * there is excess capacity, but a special waits
774 		 * It'll need the adapter as soon as we clear out of the
775 		 * way and let it run (user level wait).
776 		 */
777 		if (periph->periph_flags & PERIPH_WAITING) {
778 			periph->periph_flags &= ~PERIPH_WAITING;
779 			wakeup((void *)periph);
780 			return;
781 		}
782 
783 		/*
784 		 * If the device has become invalid, abort all the
785 		 * reads and writes until all files have been closed and
786 		 * re-opened
787 		 */
788 		if (__predict_false(
789 		    (periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)) {
790 			if ((bp = BUFQ_GET(cd->buf_queue)) != NULL) {
791 				bp->b_error = EIO;
792 				bp->b_resid = bp->b_bcount;
793 				biodone(bp);
794 				continue;
795 			} else {
796 				return;
797 			}
798 		}
799 
800 		/*
801 		 * See if there is a buf with work for us to do..
802 		 */
803 		if ((bp = BUFQ_PEEK(cd->buf_queue)) == NULL)
804 			return;
805 
806 		/*
807 		 * We have a buf, now we should make a command.
808 		 */
809 
810 		nblks = howmany(bp->b_bcount, cd->params.blksize);
811 
812 		/*
813 		 *  Fill out the scsi command.  If the transfer will
814 		 *  fit in a "small" cdb, use it.
815 		 */
816 		if (((bp->b_rawblkno & 0x1fffff) == bp->b_rawblkno) &&
817 		    ((nblks & 0xff) == nblks) &&
818 		    !(periph->periph_quirks & PQUIRK_ONLYBIG)) {
819 			/*
820 			 * We can fit in a small cdb.
821 			 */
822 			memset(&cmd_small, 0, sizeof(cmd_small));
823 			cmd_small.opcode = (bp->b_flags & B_READ) ?
824 			    SCSI_READ_6_COMMAND : SCSI_WRITE_6_COMMAND;
825 			_lto3b(bp->b_rawblkno, cmd_small.addr);
826 			cmd_small.length = nblks & 0xff;
827 			cmdlen = sizeof(cmd_small);
828 			cmdp = (struct scsipi_generic *)&cmd_small;
829 		} else {
830 			/*
831 			 * Need a large cdb.
832 			 */
833 			memset(&cmd_big, 0, sizeof(cmd_big));
834 			cmd_big.opcode = (bp->b_flags & B_READ) ?
835 			    READ_10 : WRITE_10;
836 			_lto4b(bp->b_rawblkno, cmd_big.addr);
837 			_lto2b(nblks, cmd_big.length);
838 			cmdlen = sizeof(cmd_big);
839 			cmdp = (struct scsipi_generic *)&cmd_big;
840 		}
841 
842 		/* Instrumentation. */
843 		disk_busy(&cd->sc_dk);
844 
845 		/*
846 		 * Figure out what flags to use.
847 		 */
848 		flags = XS_CTL_NOSLEEP|XS_CTL_ASYNC|XS_CTL_SIMPLE_TAG;
849 		if (bp->b_flags & B_READ)
850 			flags |= XS_CTL_DATA_IN;
851 		else
852 			flags |= XS_CTL_DATA_OUT;
853 
854 		/*
855 		 * Call the routine that chats with the adapter.
856 		 * Note: we cannot sleep as we may be an interrupt
857 		 */
858 		xs = scsipi_make_xs(periph, cmdp, cmdlen,
859 		    (u_char *)bp->b_data, bp->b_bcount,
860 		    CDRETRIES, 30000, bp, flags);
861 		if (__predict_false(xs == NULL)) {
862 			/*
863 			 * out of memory. Keep this buffer in the queue, and
864 			 * retry later.
865 			 */
866 			callout_reset(&cd->sc_callout, hz / 2, cdrestart,
867 			    periph);
868 			return;
869 		}
870 		/*
871 		 * need to dequeue the buffer before queuing the command,
872 		 * because cdstart may be called recursively from the
873 		 * HBA driver
874 		 */
875 #ifdef DIAGNOSTIC
876 		if (BUFQ_GET(cd->buf_queue) != bp)
877 			panic("cdstart(): dequeued wrong buf");
878 #else
879 		BUFQ_GET(cd->buf_queue);
880 #endif
881 		error = scsipi_execute_xs(xs);
882 		/* with a scsipi_xfer preallocated, scsipi_command can't fail */
883 		KASSERT(error == 0);
884 	}
885 }
886 
887 static void
888 cdrestart(void *v)
889 {
890 	int s = splbio();
891 	cdstart((struct scsipi_periph *)v);
892 	splx(s);
893 }
894 
895 static void
896 cddone(struct scsipi_xfer *xs, int error)
897 {
898 	struct cd_softc *cd = device_private(xs->xs_periph->periph_dev);
899 	struct buf *bp = xs->bp;
900 
901 	if (bp) {
902 		/* note, bp->b_resid is NOT initialised */
903 		bp->b_error = error;
904 		bp->b_resid = xs->resid;
905 		if (error) {
906 			/* on a read/write error bp->b_resid is zero, so fix */
907 			bp->b_resid = bp->b_bcount;
908 		}
909 
910 		disk_unbusy(&cd->sc_dk, bp->b_bcount - bp->b_resid,
911 		    (bp->b_flags & B_READ));
912 #if NRND > 0
913 		rnd_add_uint32(&cd->rnd_source, bp->b_rawblkno);
914 #endif
915 
916 		biodone(bp);
917 	}
918 }
919 
920 static void
921 cdbounce(struct buf *bp)
922 {
923 	struct cdbounce *bounce = (struct cdbounce *)bp->b_private;
924 	struct buf *obp = bounce->obp;
925 	struct cd_softc *cd =
926 	    device_private(cd_cd.cd_devs[CDUNIT(obp->b_dev)]);
927 	struct disklabel *lp = cd->sc_dk.dk_label;
928 
929 	if (bp->b_error != 0) {
930 		/* EEK propagate the error and free the memory */
931 		goto done;
932 	}
933 
934 	KASSERT(obp->b_flags & B_READ);
935 
936 	/* copy bounce buffer to final destination */
937 	memcpy((char *)obp->b_data + bounce->doff,
938 	    (char *)bp->b_data + bounce->soff, bounce->bcount);
939 
940 	/* check if we need more I/O, i.e. bounce put us over MAXPHYS */
941 	KASSERT(bounce->resid >= bounce->bcount);
942 	bounce->resid -= bounce->bcount;
943 	if (bounce->resid > 0) {
944 		struct buf *nbp;
945 		daddr_t blkno;
946 		long count;
947 		int s;
948 
949 		blkno = obp->b_rawblkno +
950 		    ((obp->b_bcount - bounce->resid) / lp->d_secsize);
951 		count = ((blkno * lp->d_secsize) % cd->params.blksize);
952 		blkno = (blkno * lp->d_secsize) / cd->params.blksize;
953 		bounce->soff = count;
954 		bounce->doff += bounce->bcount;
955 		count += bounce->resid;
956 		count = roundup(count, cd->params.blksize);
957 		bounce->bcount = bounce->resid;
958 		if (count > MAXPHYS) {
959 			bounce->bcount = MAXPHYS - bounce->soff;
960 			count = MAXPHYS;
961 		}
962 
963 		nbp = getiobuf(false, NULL);
964 		if (!nbp) {
965 			/* No memory -- fail the iop. */
966 			bp->b_error = ENOMEM;
967 			goto done;
968 		}
969 
970 		/* Set up the IOP to the bounce buffer. */
971 		nbp->b_error = 0;
972 		nbp->b_proc = obp->b_proc;
973 		nbp->b_bcount = count;
974 		nbp->b_bufsize = count;
975 		nbp->b_data = bp->b_data;
976 		nbp->b_rawblkno = blkno;
977 		nbp->b_flags = obp->b_flags | B_READ;
978 		nbp->b_oflags = obp->b_oflags;
979 		nbp->b_cflags = obp->b_cflags;
980 		nbp->b_iodone = cdbounce;
981 
982 		/* store bounce state in b_private and use new buf */
983 		nbp->b_private = bounce;
984 
985 		BIO_COPYPRIO(nbp, obp);
986 
987 		bp->b_data = NULL;
988 		putiobuf(bp);
989 
990 		/* enqueue the request and return */
991 		s = splbio();
992 		BUFQ_PUT(cd->buf_queue, nbp);
993 		cdstart(cd->sc_periph);
994 		splx(s);
995 
996 		return;
997 	}
998 
999 done:
1000 	obp->b_error = bp->b_error;
1001 	obp->b_resid = bp->b_resid;
1002 	free(bp->b_data, M_DEVBUF);
1003 	free(bounce, M_DEVBUF);
1004 	bp->b_data = NULL;
1005 	putiobuf(bp);
1006 	biodone(obp);
1007 }
1008 
1009 static int
1010 cd_interpret_sense(struct scsipi_xfer *xs)
1011 {
1012 	struct scsipi_periph *periph = xs->xs_periph;
1013 	struct scsi_sense_data *sense = &xs->sense.scsi_sense;
1014 	int retval = EJUSTRETURN;
1015 
1016 	/*
1017 	 * If it isn't a extended or extended/deferred error, let
1018 	 * the generic code handle it.
1019 	 */
1020 	if (SSD_RCODE(sense->response_code) != SSD_RCODE_CURRENT &&
1021 	    SSD_RCODE(sense->response_code) != SSD_RCODE_DEFERRED)
1022 		return (retval);
1023 
1024 	/*
1025 	 * If we got a "Unit not ready" (SKEY_NOT_READY) and "Logical Unit
1026 	 * Is In The Process of Becoming Ready" (Sense code 0x04,0x01), then
1027 	 * wait a bit for the drive to spin up
1028 	 */
1029 
1030 	if (SSD_SENSE_KEY(sense->flags) == SKEY_NOT_READY &&
1031 	    sense->asc == 0x4 &&
1032 	    sense->ascq == 0x01)	{
1033 		/*
1034 		 * Sleep for 5 seconds to wait for the drive to spin up
1035 		 */
1036 
1037 		SC_DEBUG(periph, SCSIPI_DB1, ("Waiting 5 sec for CD "
1038 						"spinup\n"));
1039 		if (!callout_pending(&periph->periph_callout))
1040 			scsipi_periph_freeze(periph, 1);
1041 		callout_reset(&periph->periph_callout,
1042 		    5 * hz, scsipi_periph_timed_thaw, periph);
1043 		retval = ERESTART;
1044 	}
1045 
1046 	/*
1047 	 * If we got a "Unit not ready" (SKEY_NOT_READY) and "Long write in
1048 	 * progress" (Sense code 0x04, 0x08), then wait for the specified
1049 	 * time
1050 	 */
1051 
1052 	if ((SSD_SENSE_KEY(sense->flags) == SKEY_NOT_READY) &&
1053 	    (sense->asc == 0x04) && (sense->ascq == 0x08)) {
1054 		/*
1055 		 * long write in process; we could listen to the delay; but it
1056 		 * looks like the skey data is not always returned.
1057 		 */
1058 		/* cd_delay = _2btol(sense->sks.sks_bytes); */
1059 
1060 		/* wait for a second and get going again */
1061 		if (!callout_pending(&periph->periph_callout))
1062 			scsipi_periph_freeze(periph, 1);
1063 		callout_reset(&periph->periph_callout,
1064 		    1 * hz, scsipi_periph_timed_thaw, periph);
1065 		retval = ERESTART;
1066 	}
1067 
1068 	return (retval);
1069 }
1070 
1071 static void
1072 cdminphys(struct buf *bp)
1073 {
1074 	struct cd_softc *cd = device_lookup_private(&cd_cd, CDUNIT(bp->b_dev));
1075 	long xmax;
1076 
1077 	/*
1078 	 * If the device is ancient, we want to make sure that
1079 	 * the transfer fits into a 6-byte cdb.
1080 	 *
1081 	 * XXX Note that the SCSI-I spec says that 256-block transfers
1082 	 * are allowed in a 6-byte read/write, and are specified
1083 	 * by settng the "length" to 0.  However, we're conservative
1084 	 * here, allowing only 255-block transfers in case an
1085 	 * ancient device gets confused by length == 0.  A length of 0
1086 	 * in a 10-byte read/write actually means 0 blocks.
1087 	 */
1088 	if (cd->flags & CDF_ANCIENT) {
1089 		xmax = cd->sc_dk.dk_label->d_secsize * 0xff;
1090 
1091 		if (bp->b_bcount > xmax)
1092 			bp->b_bcount = xmax;
1093 	}
1094 
1095 	(*cd->sc_periph->periph_channel->chan_adapter->adapt_minphys)(bp);
1096 }
1097 
1098 static int
1099 cdread(dev_t dev, struct uio *uio, int ioflag)
1100 {
1101 	return (physio(cdstrategy, NULL, dev, B_READ, cdminphys, uio));
1102 }
1103 
1104 static int
1105 cdwrite(dev_t dev, struct uio *uio, int ioflag)
1106 {
1107 	return (physio(cdstrategy, NULL, dev, B_WRITE, cdminphys, uio));
1108 }
1109 
1110 #if 0	/* XXX Not used */
1111 /*
1112  * conversion between minute-seconde-frame and logical block address
1113  * addresses format
1114  */
1115 static void
1116 lba2msf(u_long lba, u_char *m, u_char *s, u_char *f)
1117 {
1118 	u_long tmp;
1119 
1120 	tmp = lba + CD_BLOCK_OFFSET;	/* offset of first logical frame */
1121 	tmp &= 0xffffff;		/* negative lbas use only 24 bits */
1122 	*m = tmp / (CD_SECS * CD_FRAMES);
1123 	tmp %= (CD_SECS * CD_FRAMES);
1124 	*s = tmp / CD_FRAMES;
1125 	*f = tmp % CD_FRAMES;
1126 }
1127 #endif /* XXX Not used */
1128 
1129 /*
1130  * Convert an hour:minute:second:frame address to a logical block adres. In
1131  * theory the number of secs/minute and number of frames/second could be
1132  * configured differently in the device  as could the block offset but in
1133  * practice these values are rock solid and most drives don't even allow
1134  * theses values to be changed.
1135  */
1136 static uint32_t
1137 hmsf2lba(uint8_t h, uint8_t m, uint8_t s, uint8_t f)
1138 {
1139 	return (((((uint32_t) h * 60 + m) * CD_SECS) + s) * CD_FRAMES + f)
1140 		- CD_BLOCK_OFFSET;
1141 }
1142 
1143 static int
1144 cdreadmsaddr(struct cd_softc *cd, struct cd_formatted_toc *toc, int *addr)
1145 {
1146 	struct scsipi_periph *periph = cd->sc_periph;
1147 	int error;
1148 	struct cd_toc_entry *cte;
1149 
1150 	error = cd_read_toc(cd, CD_TOC_FORM, 0, 0, toc,
1151 	    sizeof(struct ioc_toc_header) + sizeof(struct cd_toc_entry),
1152 	    XS_CTL_DATA_ONSTACK,
1153 	    0x40 /* control word for "get MS info" */);
1154 
1155 	if (error)
1156 		return (error);
1157 
1158 	cte = &toc->entries[0];
1159 	if (periph->periph_quirks & PQUIRK_LITTLETOC) {
1160 		cte->addr.lba = le32toh(cte->addr.lba);
1161 		toc->header.len = le16toh(toc->header.len);
1162 	} else {
1163 		cte->addr.lba = be32toh(cte->addr.lba);
1164 		toc->header.len = be16toh(toc->header.len);
1165 	}
1166 
1167 	*addr = (toc->header.len >= 10 && cte->track > 1) ?
1168 		cte->addr.lba : 0;
1169 	return 0;
1170 }
1171 
1172 /* synchronise caches code from sd.c, move to scsipi_ioctl.c ? */
1173 static int
1174 cdcachesync(struct scsipi_periph *periph, int flags) {
1175 	struct scsi_synchronize_cache_10 cmd;
1176 
1177 	/*
1178 	 * Issue a SYNCHRONIZE CACHE. MMC devices have to issue with address 0
1179 	 * and length 0 as it can't synchronise parts of the disc per spec.
1180 	 * We ignore ILLEGAL REQUEST in the event that the command is not
1181 	 * supported by the device, and poll for completion so that we know
1182 	 * that the cache has actually been flushed.
1183 	 *
1184 	 * XXX should we handle the PQUIRK_NOSYNCCACHE ?
1185 	 */
1186 
1187 	memset(&cmd, 0, sizeof(cmd));
1188 	cmd.opcode = SCSI_SYNCHRONIZE_CACHE_10;
1189 
1190 	return (scsipi_command(periph, (void *)&cmd, sizeof(cmd), 0, 0,
1191 	    CDRETRIES, 30000, NULL, flags | XS_CTL_IGNORE_ILLEGAL_REQUEST));
1192 }
1193 
1194 static int
1195 do_cdioreadentries(struct cd_softc *cd, struct ioc_read_toc_entry *te,
1196     struct cd_formatted_toc *toc)
1197 {
1198 	/* READ TOC format 0 command, entries */
1199 	struct ioc_toc_header *th;
1200 	struct cd_toc_entry *cte;
1201 	u_int len = te->data_len;
1202 	int ntracks;
1203 	int error;
1204 
1205 	th = &toc->header;
1206 
1207 	if (len > sizeof(toc->entries) ||
1208 	    len < sizeof(toc->entries[0]))
1209 		return (EINVAL);
1210 	error = cd_read_toc(cd, CD_TOC_FORM, te->address_format,
1211 	    te->starting_track, toc,
1212 	    sizeof(toc->header) + len,
1213 	    XS_CTL_DATA_ONSTACK, 0);
1214 	if (error)
1215 		return (error);
1216 	if (te->address_format == CD_LBA_FORMAT)
1217 		for (ntracks =
1218 		    th->ending_track - th->starting_track + 1;
1219 		    ntracks >= 0; ntracks--) {
1220 			cte = &toc->entries[ntracks];
1221 			cte->addr_type = CD_LBA_FORMAT;
1222 			if (cd->sc_periph->periph_quirks & PQUIRK_LITTLETOC)
1223 				cte->addr.lba = le32toh(cte->addr.lba);
1224 			else
1225 				cte->addr.lba = be32toh(cte->addr.lba);
1226 		}
1227 	if (cd->sc_periph->periph_quirks & PQUIRK_LITTLETOC)
1228 		th->len = le16toh(th->len);
1229 	else
1230 		th->len = be16toh(th->len);
1231 	return 0;
1232 }
1233 
1234 /*
1235  * Perform special action on behalf of the user.
1236  * Knows about the internals of this device
1237  */
1238 static int
1239 cdioctl(dev_t dev, u_long cmd, void *addr, int flag, struct lwp *l)
1240 {
1241 	struct cd_softc *cd = device_lookup_private(&cd_cd, CDUNIT(dev));
1242 	struct scsipi_periph *periph = cd->sc_periph;
1243 	struct cd_formatted_toc toc;
1244 	int part = CDPART(dev);
1245 	int error = 0;
1246 	int s;
1247 #ifdef __HAVE_OLD_DISKLABEL
1248 	struct disklabel *newlabel = NULL;
1249 #endif
1250 
1251 	SC_DEBUG(cd->sc_periph, SCSIPI_DB2, ("cdioctl 0x%lx ", cmd));
1252 
1253 	/*
1254 	 * If the device is not valid, some IOCTLs can still be
1255 	 * handled on the raw partition. Check this here.
1256 	 */
1257 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
1258 		switch (cmd) {
1259 		case DIOCWLABEL:
1260 		case DIOCLOCK:
1261 		case ODIOCEJECT:
1262 		case DIOCEJECT:
1263 		case DIOCCACHESYNC:
1264 		case SCIOCIDENTIFY:
1265 		case OSCIOCIDENTIFY:
1266 		case SCIOCCOMMAND:
1267 		case SCIOCDEBUG:
1268 		case CDIOCGETVOL:
1269 		case CDIOCSETVOL:
1270 		case CDIOCSETMONO:
1271 		case CDIOCSETSTEREO:
1272 		case CDIOCSETMUTE:
1273 		case CDIOCSETLEFT:
1274 		case CDIOCSETRIGHT:
1275 		case CDIOCCLOSE:
1276 		case CDIOCEJECT:
1277 		case CDIOCALLOW:
1278 		case CDIOCPREVENT:
1279 		case CDIOCSETDEBUG:
1280 		case CDIOCCLRDEBUG:
1281 		case CDIOCRESET:
1282 		case SCIOCRESET:
1283 		case CDIOCLOADUNLOAD:
1284 		case DVD_AUTH:
1285 		case DVD_READ_STRUCT:
1286 		case DIOCGSTRATEGY:
1287 		case DIOCSSTRATEGY:
1288 			if (part == RAW_PART)
1289 				break;
1290 		/* FALLTHROUGH */
1291 		default:
1292 			if ((periph->periph_flags & PERIPH_OPEN) == 0)
1293 				return (ENODEV);
1294 			else
1295 				return (EIO);
1296 		}
1297 	}
1298 
1299 	switch (cmd) {
1300 	case DIOCGDINFO:
1301 		*(struct disklabel *)addr = *(cd->sc_dk.dk_label);
1302 		return (0);
1303 #ifdef __HAVE_OLD_DISKLABEL
1304 	case ODIOCGDINFO:
1305 		newlabel = malloc(sizeof (*newlabel), M_TEMP, M_WAITOK);
1306 		if (newlabel == NULL)
1307 			return (EIO);
1308 		memcpy(newlabel, cd->sc_dk.dk_label, sizeof (*newlabel));
1309 		if (newlabel->d_npartitions > OLDMAXPARTITIONS)
1310 			error = ENOTTY;
1311 		else
1312 			memcpy(addr, newlabel, sizeof (struct olddisklabel));
1313 		free(newlabel, M_TEMP);
1314 		return error;
1315 #endif
1316 
1317 	case DIOCGPART:
1318 		((struct partinfo *)addr)->disklab = cd->sc_dk.dk_label;
1319 		((struct partinfo *)addr)->part =
1320 		    &cd->sc_dk.dk_label->d_partitions[part];
1321 		return (0);
1322 
1323 	case DIOCWDINFO:
1324 	case DIOCSDINFO:
1325 #ifdef __HAVE_OLD_DISKLABEL
1326 	case ODIOCWDINFO:
1327 	case ODIOCSDINFO:
1328 #endif
1329 	{
1330 		struct disklabel *lp;
1331 
1332 		if ((flag & FWRITE) == 0)
1333 			return (EBADF);
1334 
1335 #ifdef __HAVE_OLD_DISKLABEL
1336 		if (cmd == ODIOCSDINFO || cmd == ODIOCWDINFO) {
1337 			newlabel = malloc(sizeof (*newlabel), M_TEMP, M_WAITOK);
1338 			if (newlabel == NULL)
1339 				return (EIO);
1340 			memset(newlabel, 0, sizeof newlabel);
1341 			memcpy(newlabel, addr, sizeof (struct olddisklabel));
1342 			lp = newlabel;
1343 		} else
1344 #endif
1345 		lp = addr;
1346 
1347 		mutex_enter(&cd->sc_lock);
1348 		cd->flags |= CDF_LABELLING;
1349 
1350 		error = setdisklabel(cd->sc_dk.dk_label,
1351 		    lp, /*cd->sc_dk.dk_openmask : */0,
1352 		    cd->sc_dk.dk_cpulabel);
1353 		if (error == 0) {
1354 			/* XXX ? */
1355 		}
1356 
1357 		cd->flags &= ~CDF_LABELLING;
1358 		mutex_exit(&cd->sc_lock);
1359 #ifdef __HAVE_OLD_DISKLABEL
1360 		if (newlabel != NULL)
1361 			free(newlabel, M_TEMP);
1362 #endif
1363 		return (error);
1364 	}
1365 
1366 	case DIOCWLABEL:
1367 		return (EBADF);
1368 
1369 	case DIOCGDEFLABEL:
1370 		cdgetdefaultlabel(cd, &toc, addr);
1371 		return (0);
1372 
1373 #ifdef __HAVE_OLD_DISKLABEL
1374 	case ODIOCGDEFLABEL:
1375 		newlabel = malloc(sizeof (*newlabel), M_TEMP, M_WAITOK);
1376 		if (newlabel == NULL)
1377 			return (EIO);
1378 		cdgetdefaultlabel(cd, &toc, newlabel);
1379 		if (newlabel->d_npartitions > OLDMAXPARTITIONS)
1380 			error = ENOTTY;
1381 		else
1382 			memcpy(addr, newlabel, sizeof (struct olddisklabel));
1383 		free(newlabel, M_TEMP);
1384 		return error;
1385 #endif
1386 
1387 	case CDIOCPLAYTRACKS: {
1388 		/* PLAY_MSF command */
1389 		struct ioc_play_track *args = addr;
1390 
1391 		if ((error = cd_set_pa_immed(cd, 0)) != 0)
1392 			return (error);
1393 		return (cd_play_tracks(cd, &toc, args->start_track,
1394 		    args->start_index, args->end_track, args->end_index));
1395 	}
1396 	case CDIOCPLAYMSF: {
1397 		/* PLAY_MSF command */
1398 		struct ioc_play_msf *args = addr;
1399 
1400 		if ((error = cd_set_pa_immed(cd, 0)) != 0)
1401 			return (error);
1402 		return (cd_play_msf(cd, args->start_m, args->start_s,
1403 		    args->start_f, args->end_m, args->end_s, args->end_f));
1404 	}
1405 	case CDIOCPLAYBLOCKS: {
1406 		/* PLAY command */
1407 		struct ioc_play_blocks *args = addr;
1408 
1409 		if ((error = cd_set_pa_immed(cd, 0)) != 0)
1410 			return (error);
1411 		return (cd_play(cd, args->blk, args->len));
1412 	}
1413 	case CDIOCREADSUBCHANNEL: {
1414 		/* READ_SUBCHANNEL command */
1415 		struct ioc_read_subchannel *args = addr;
1416 		struct cd_sub_channel_info data;
1417 		u_int len = args->data_len;
1418 
1419 		if (len > sizeof(data) ||
1420 		    len < sizeof(struct cd_sub_channel_header))
1421 			return (EINVAL);
1422 		error = cd_read_subchannel(cd, args->address_format,
1423 		    args->data_format, args->track, &data, len,
1424 		    XS_CTL_DATA_ONSTACK);
1425 		if (error)
1426 			return (error);
1427 		len = min(len, _2btol(data.header.data_len) +
1428 		    sizeof(struct cd_sub_channel_header));
1429 		return (copyout(&data, args->data, len));
1430 	}
1431 	case CDIOCREADSUBCHANNEL_BUF: {
1432 		/* As CDIOCREADSUBCHANNEL, but without a 2nd buffer area */
1433 		struct ioc_read_subchannel_buf *args = addr;
1434 		if (args->req.data_len != sizeof args->info)
1435 			return EINVAL;
1436 		return cd_read_subchannel(cd, args->req.address_format,
1437 		    args->req.data_format, args->req.track, &args->info,
1438 		    sizeof args->info, XS_CTL_DATA_ONSTACK);
1439 	}
1440 	case CDIOREADTOCHEADER: {
1441 		/* READ TOC format 0 command, static header */
1442 		if ((error = cd_read_toc(cd, CD_TOC_FORM, 0, 0,
1443 		    &toc, sizeof(toc.header),
1444 		    XS_CTL_DATA_ONSTACK, 0)) != 0)
1445 			return (error);
1446 		if (cd->sc_periph->periph_quirks & PQUIRK_LITTLETOC)
1447 			toc.header.len = le16toh(toc.header.len);
1448 		else
1449 			toc.header.len = be16toh(toc.header.len);
1450 		memcpy(addr, &toc.header, sizeof(toc.header));
1451 		return (0);
1452 	}
1453 	case CDIOREADTOCENTRYS: {
1454 		struct ioc_read_toc_entry *te = addr;
1455 		error = do_cdioreadentries(cd, te, &toc);
1456 		if (error != 0)
1457 			return error;
1458 		return copyout(toc.entries, te->data, min(te->data_len,
1459 		    toc.header.len - (sizeof(toc.header.starting_track)
1460 			+ sizeof(toc.header.ending_track))));
1461 	}
1462 	case CDIOREADTOCENTRIES_BUF: {
1463 		struct ioc_read_toc_entry_buf *te = addr;
1464 		error = do_cdioreadentries(cd, &te->req, &toc);
1465 		if (error != 0)
1466 			return error;
1467 		memcpy(te->entry, toc.entries, min(te->req.data_len,
1468 		    toc.header.len - (sizeof(toc.header.starting_track)
1469 			+ sizeof(toc.header.ending_track))));
1470 		return 0;
1471 	}
1472 	case CDIOREADMSADDR: {
1473 		/* READ TOC format 0 command, length of first track only */
1474 		int sessno = *(int*)addr;
1475 
1476 		if (sessno != 0)
1477 			return (EINVAL);
1478 
1479 		return (cdreadmsaddr(cd, &toc, addr));
1480 	}
1481 	case CDIOCSETPATCH: {
1482 		struct ioc_patch *arg = addr;
1483 
1484 		return (cd_setchan(cd, arg->patch[0], arg->patch[1],
1485 		    arg->patch[2], arg->patch[3], 0));
1486 	}
1487 	case CDIOCGETVOL: {
1488 		/* MODE SENSE command (AUDIO page) */
1489 		struct ioc_vol *arg = addr;
1490 
1491 		return (cd_getvol(cd, arg, 0));
1492 	}
1493 	case CDIOCSETVOL: {
1494 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1495 		struct ioc_vol *arg = addr;
1496 
1497 		return (cd_setvol(cd, arg, 0));
1498 	}
1499 	case CDIOCSETMONO:
1500 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1501 		return (cd_setchan(cd, BOTH_CHANNEL, BOTH_CHANNEL,
1502 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1503 
1504 	case CDIOCSETSTEREO:
1505 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1506 		return (cd_setchan(cd, LEFT_CHANNEL, RIGHT_CHANNEL,
1507 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1508 
1509 	case CDIOCSETMUTE:
1510 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1511 		return (cd_setchan(cd, MUTE_CHANNEL, MUTE_CHANNEL,
1512 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1513 
1514 	case CDIOCSETLEFT:
1515 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1516 		return (cd_setchan(cd, LEFT_CHANNEL, LEFT_CHANNEL,
1517 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1518 
1519 	case CDIOCSETRIGHT:
1520 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1521 		return (cd_setchan(cd, RIGHT_CHANNEL, RIGHT_CHANNEL,
1522 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1523 
1524 	case CDIOCRESUME:
1525 		/* PAUSE command */
1526 		return (cd_pause(cd, PA_RESUME));
1527 	case CDIOCPAUSE:
1528 		/* PAUSE command */
1529 		return (cd_pause(cd, PA_PAUSE));
1530 	case CDIOCSTART:
1531 		return (scsipi_start(periph, SSS_START, 0));
1532 	case CDIOCSTOP:
1533 		return (scsipi_start(periph, SSS_STOP, 0));
1534 	case CDIOCCLOSE:
1535 		return (scsipi_start(periph, SSS_START|SSS_LOEJ,
1536 		    XS_CTL_IGNORE_NOT_READY | XS_CTL_IGNORE_MEDIA_CHANGE));
1537 	case DIOCEJECT:
1538 		if (*(int *)addr == 0) {
1539 			/*
1540 			 * Don't force eject: check that we are the only
1541 			 * partition open. If so, unlock it.
1542 			 */
1543 			if ((cd->sc_dk.dk_openmask & ~(1 << part)) == 0 &&
1544 			    cd->sc_dk.dk_bopenmask + cd->sc_dk.dk_copenmask ==
1545 			    cd->sc_dk.dk_openmask) {
1546 				error = scsipi_prevent(periph, SPAMR_ALLOW,
1547 				    XS_CTL_IGNORE_NOT_READY);
1548 				if (error)
1549 					return (error);
1550 			} else {
1551 				return (EBUSY);
1552 			}
1553 		}
1554 		/* FALLTHROUGH */
1555 	case CDIOCEJECT: /* FALLTHROUGH */
1556 	case ODIOCEJECT:
1557 		return (scsipi_start(periph, SSS_STOP|SSS_LOEJ, 0));
1558 	case DIOCCACHESYNC:
1559 		/* SYNCHRONISE CACHES command */
1560 		return (cdcachesync(periph, 0));
1561 	case CDIOCALLOW:
1562 		return (scsipi_prevent(periph, SPAMR_ALLOW, 0));
1563 	case CDIOCPREVENT:
1564 		return (scsipi_prevent(periph, SPAMR_PREVENT_DT, 0));
1565 	case DIOCLOCK:
1566 		return (scsipi_prevent(periph,
1567 		    (*(int *)addr) ? SPAMR_PREVENT_DT : SPAMR_ALLOW, 0));
1568 	case CDIOCSETDEBUG:
1569 		cd->sc_periph->periph_dbflags |= (SCSIPI_DB1 | SCSIPI_DB2);
1570 		return (0);
1571 	case CDIOCCLRDEBUG:
1572 		cd->sc_periph->periph_dbflags &= ~(SCSIPI_DB1 | SCSIPI_DB2);
1573 		return (0);
1574 	case CDIOCRESET:
1575 	case SCIOCRESET:
1576 		return (cd_reset(cd));
1577 	case CDIOCLOADUNLOAD:
1578 		/* LOAD_UNLOAD command */
1579 		return (cd_load_unload(cd, addr));
1580 	case DVD_AUTH:
1581 		/* GPCMD_REPORT_KEY or GPCMD_SEND_KEY command */
1582 		return (dvd_auth(cd, addr));
1583 	case DVD_READ_STRUCT:
1584 		/* GPCMD_READ_DVD_STRUCTURE command */
1585 		return (dvd_read_struct(cd, addr));
1586 	case MMCGETDISCINFO:
1587 		/*
1588 		 * GET_CONFIGURATION, READ_DISCINFO, READ_TRACKINFO,
1589 		 * (READ_TOCf2, READ_CD_CAPACITY and GET_CONFIGURATION) commands
1590 		 */
1591 		return mmc_getdiscinfo(periph, (struct mmc_discinfo *) addr);
1592 	case MMCGETTRACKINFO:
1593 		/* READ TOCf2, READ_CD_CAPACITY and READ_TRACKINFO commands */
1594 		return mmc_gettrackinfo(periph, (struct mmc_trackinfo *) addr);
1595 	case DIOCGSTRATEGY:
1596 	    {
1597 		struct disk_strategy *dks = addr;
1598 
1599 		s = splbio();
1600 		strlcpy(dks->dks_name, bufq_getstrategyname(cd->buf_queue),
1601 		    sizeof(dks->dks_name));
1602 		splx(s);
1603 		dks->dks_paramlen = 0;
1604 
1605 		return 0;
1606 	    }
1607 	case DIOCSSTRATEGY:
1608 	    {
1609 		struct disk_strategy *dks = addr;
1610 		struct bufq_state *new;
1611 		struct bufq_state *old;
1612 
1613 		if ((flag & FWRITE) == 0) {
1614 			return EBADF;
1615 		}
1616 		if (dks->dks_param != NULL) {
1617 			return EINVAL;
1618 		}
1619 		dks->dks_name[sizeof(dks->dks_name) - 1] = 0; /* ensure term */
1620 		error = bufq_alloc(&new, dks->dks_name,
1621 		    BUFQ_EXACT|BUFQ_SORT_RAWBLOCK);
1622 		if (error) {
1623 			return error;
1624 		}
1625 		s = splbio();
1626 		old = cd->buf_queue;
1627 		bufq_move(new, old);
1628 		cd->buf_queue = new;
1629 		splx(s);
1630 		bufq_free(old);
1631 
1632 		return 0;
1633 	    }
1634 	default:
1635 		if (part != RAW_PART)
1636 			return (ENOTTY);
1637 		return (scsipi_do_ioctl(periph, dev, cmd, addr, flag, l));
1638 	}
1639 
1640 #ifdef DIAGNOSTIC
1641 	panic("cdioctl: impossible");
1642 #endif
1643 }
1644 
1645 static void
1646 cdgetdefaultlabel(struct cd_softc *cd, struct cd_formatted_toc *toc,
1647     struct disklabel *lp)
1648 {
1649 	int lastsession;
1650 
1651 	memset(lp, 0, sizeof(struct disklabel));
1652 
1653 	lp->d_secsize = cd->params.blksize;
1654 	lp->d_ntracks = 1;
1655 	lp->d_nsectors = 100;
1656 	lp->d_ncylinders = (cd->params.disksize / 100) + 1;
1657 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
1658 
1659 	switch (scsipi_periph_bustype(cd->sc_periph)) {
1660 	case SCSIPI_BUSTYPE_SCSI:
1661 		lp->d_type = DTYPE_SCSI;
1662 		break;
1663 	case SCSIPI_BUSTYPE_ATAPI:
1664 		lp->d_type = DTYPE_ATAPI;
1665 		break;
1666 	}
1667 	/*
1668 	 * XXX
1669 	 * We could probe the mode pages to figure out what kind of disc it is.
1670 	 * Is this worthwhile?
1671 	 */
1672 	strncpy(lp->d_typename, "mydisc", 16);
1673 	strncpy(lp->d_packname, "fictitious", 16);
1674 	lp->d_secperunit = cd->params.disksize;
1675 	lp->d_rpm = 300;
1676 	lp->d_interleave = 1;
1677 	lp->d_flags = D_REMOVABLE;
1678 
1679 	if (cdreadmsaddr(cd, toc, &lastsession) != 0)
1680 		lastsession = 0;
1681 
1682 	lp->d_partitions[0].p_offset = 0;
1683 	lp->d_partitions[0].p_size = lp->d_secperunit;
1684 	lp->d_partitions[0].p_cdsession = lastsession;
1685 	lp->d_partitions[0].p_fstype = FS_ISO9660;
1686 	lp->d_partitions[RAW_PART].p_offset = 0;
1687 	lp->d_partitions[RAW_PART].p_size = lp->d_secperunit;
1688 	lp->d_partitions[RAW_PART].p_fstype = FS_ISO9660;
1689 	lp->d_npartitions = RAW_PART + 1;
1690 
1691 	lp->d_magic = DISKMAGIC;
1692 	lp->d_magic2 = DISKMAGIC;
1693 	lp->d_checksum = dkcksum(lp);
1694 }
1695 
1696 /*
1697  * Load the label information on the named device
1698  * Actually fabricate a disklabel
1699  *
1700  * EVENTUALLY take information about different
1701  * data tracks from the TOC and put it in the disklabel
1702  */
1703 static void
1704 cdgetdisklabel(struct cd_softc *cd)
1705 {
1706 	struct disklabel *lp = cd->sc_dk.dk_label;
1707 	struct cd_formatted_toc toc;
1708 	const char *errstring;
1709 
1710 	memset(cd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
1711 
1712 	cdgetdefaultlabel(cd, &toc, lp);
1713 
1714 	/*
1715 	 * Call the generic disklabel extraction routine
1716 	 */
1717 	errstring = readdisklabel(MAKECDDEV(0, device_unit(cd->sc_dev),
1718 	    RAW_PART), cdstrategy, lp, cd->sc_dk.dk_cpulabel);
1719 
1720 	/* if all went OK, we are passed a NULL error string */
1721 	if (errstring == NULL)
1722 		return;
1723 
1724 	/* Reset to default label -- after printing error and the warning */
1725 	aprint_error_dev(cd->sc_dev, "%s\n", errstring);
1726 	memset(cd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
1727 	cdgetdefaultlabel(cd, &toc, lp);
1728 }
1729 
1730 /*
1731  * Reading a discs total capacity is aparently a very difficult issue for the
1732  * SCSI standardisation group. Every disc type seems to have its own
1733  * (re)invented size request method and modifiers. The failsafe way of
1734  * determining the total (max) capacity i.e. not the recorded capacity but the
1735  * total maximum capacity is to request the info on the last track and
1736  * calucate the total size.
1737  *
1738  * For ROM drives, we go for the CD recorded capacity. For recordable devices
1739  * we count.
1740  */
1741 static int
1742 read_cd_capacity(struct scsipi_periph *periph, u_int *blksize, u_long *size)
1743 {
1744 	struct scsipi_read_cd_capacity    cap_cmd;
1745 	struct scsipi_read_cd_cap_data    cap;
1746 	struct scsipi_read_discinfo       di_cmd;
1747 	struct scsipi_read_discinfo_data  di;
1748 	struct scsipi_read_trackinfo      ti_cmd;
1749 	struct scsipi_read_trackinfo_data ti;
1750 	uint32_t track_start, track_size;
1751 	int error, flags, msb, lsb, last_track;
1752 
1753 	/* if the device doesn't grog capacity, return the dummies */
1754 	if (periph->periph_quirks & PQUIRK_NOCAPACITY)
1755 		return 0;
1756 
1757 	/* first try read CD capacity for blksize and recorded size */
1758 	/* issue the cd capacity request */
1759 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK;
1760 	memset(&cap_cmd, 0, sizeof(cap_cmd));
1761 	cap_cmd.opcode = READ_CD_CAPACITY;
1762 
1763 	error = scsipi_command(periph,
1764 	    (void *) &cap_cmd, sizeof(cap_cmd),
1765 	    (void *) &cap,     sizeof(cap),
1766 	    CDRETRIES, 30000, NULL, flags);
1767 	if (error)
1768 		return error;
1769 
1770 	/* retrieve values and sanity check them */
1771 	*blksize = _4btol(cap.length);
1772 	*size    = _4btol(cap.addr);
1773 
1774 	/* blksize is 2048 for CD, but some drives give gibberish */
1775 	if ((*blksize < 512) || ((*blksize & 511) != 0))
1776 		*blksize = 2048;	/* some drives lie ! */
1777 
1778 	/* recordables have READ_DISCINFO implemented */
1779 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK | XS_CTL_SILENT;
1780 	memset(&di_cmd, 0, sizeof(di_cmd));
1781 	di_cmd.opcode = READ_DISCINFO;
1782 	_lto2b(READ_DISCINFO_BIGSIZE, di_cmd.data_len);
1783 
1784 	error = scsipi_command(periph,
1785 	    (void *) &di_cmd,  sizeof(di_cmd),
1786 	    (void *) &di,      READ_DISCINFO_BIGSIZE,
1787 	    CDRETRIES, 30000, NULL, flags);
1788 	if (error == 0) {
1789 		msb = di.last_track_last_session_msb;
1790 		lsb = di.last_track_last_session_lsb;
1791 		last_track = (msb << 8) | lsb;
1792 
1793 		/* request info on last track */
1794 		memset(&ti_cmd, 0, sizeof(ti_cmd));
1795 		ti_cmd.opcode = READ_TRACKINFO;
1796 		ti_cmd.addr_type = 1;			/* on tracknr */
1797 		_lto4b(last_track, ti_cmd.address);	/* tracknr    */
1798 		_lto2b(sizeof(ti), ti_cmd.data_len);
1799 
1800 		error = scsipi_command(periph,
1801 		    (void *) &ti_cmd,  sizeof(ti_cmd),
1802 		    (void *) &ti,      sizeof(ti),
1803 		    CDRETRIES, 30000, NULL, flags);
1804 		if (error == 0) {
1805 			track_start = _4btol(ti.track_start);
1806 			track_size  = _4btol(ti.track_size);
1807 
1808 			/* overwrite only with a sane value */
1809 			if (track_start + track_size >= 100)
1810 				*size = track_start + track_size;
1811 		}
1812 	}
1813 
1814 	/* sanity check for size */
1815 	if (*size < 100)
1816 		*size = 400000;
1817 
1818 	return 0;
1819 }
1820 
1821 /*
1822  * Find out from the device what it's capacity is
1823  */
1824 static u_long
1825 cd_size(struct cd_softc *cd, int flags)
1826 {
1827 	u_int blksize;
1828 	u_long size;
1829 	int error;
1830 
1831 	/* set up fake values */
1832 	blksize = 2048;
1833 	size    = 400000;
1834 
1835 	/* if this function bounces with an error return fake value */
1836 	error = read_cd_capacity(cd->sc_periph, &blksize, &size);
1837 	if (error)
1838 		return size;
1839 
1840 	if (blksize != 2048) {
1841 		if (cd_setblksize(cd) == 0)
1842 			blksize = 2048;
1843 	}
1844 	cd->params.blksize     = blksize;
1845 	cd->params.disksize    = size;
1846 	cd->params.disksize512 = ((u_int64_t)cd->params.disksize * blksize) / DEV_BSIZE;
1847 
1848 	SC_DEBUG(cd->sc_periph, SCSIPI_DB2,
1849 	    ("cd_size: %u %lu\n", blksize, size));
1850 
1851 	return size;
1852 }
1853 
1854 /*
1855  * Get scsi driver to send a "start playing" command
1856  */
1857 static int
1858 cd_play(struct cd_softc *cd, int blkno, int nblks)
1859 {
1860 	struct scsipi_play cmd;
1861 
1862 	memset(&cmd, 0, sizeof(cmd));
1863 	cmd.opcode = PLAY;
1864 	_lto4b(blkno, cmd.blk_addr);
1865 	_lto2b(nblks, cmd.xfer_len);
1866 
1867 	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
1868 	    CDRETRIES, 30000, NULL, 0));
1869 }
1870 
1871 /*
1872  * Get scsi driver to send a "start playing" command
1873  */
1874 static int
1875 cd_play_tracks(struct cd_softc *cd, struct cd_formatted_toc *toc, int strack,
1876     int sindex, int etrack, int eindex)
1877 {
1878 	int error;
1879 
1880 	if (!etrack)
1881 		return (EIO);
1882 	if (strack > etrack)
1883 		return (EINVAL);
1884 
1885 	error = cd_load_toc(cd, CD_TOC_FORM, toc, XS_CTL_DATA_ONSTACK);
1886 	if (error)
1887 		return (error);
1888 
1889 	if (++etrack > (toc->header.ending_track+1))
1890 		etrack = toc->header.ending_track+1;
1891 
1892 	strack -= toc->header.starting_track;
1893 	etrack -= toc->header.starting_track;
1894 	if (strack < 0)
1895 		return (EINVAL);
1896 
1897 	return (cd_play_msf(cd, toc->entries[strack].addr.msf.minute,
1898 	    toc->entries[strack].addr.msf.second,
1899 	    toc->entries[strack].addr.msf.frame,
1900 	    toc->entries[etrack].addr.msf.minute,
1901 	    toc->entries[etrack].addr.msf.second,
1902 	    toc->entries[etrack].addr.msf.frame));
1903 }
1904 
1905 /*
1906  * Get scsi driver to send a "play msf" command
1907  */
1908 static int
1909 cd_play_msf(struct cd_softc *cd, int startm, int starts, int startf, int endm,
1910     int ends, int endf)
1911 {
1912 	struct scsipi_play_msf cmd;
1913 
1914 	memset(&cmd, 0, sizeof(cmd));
1915 	cmd.opcode = PLAY_MSF;
1916 	cmd.start_m = startm;
1917 	cmd.start_s = starts;
1918 	cmd.start_f = startf;
1919 	cmd.end_m = endm;
1920 	cmd.end_s = ends;
1921 	cmd.end_f = endf;
1922 
1923 	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
1924 	    CDRETRIES, 30000, NULL, 0));
1925 }
1926 
1927 /*
1928  * Get scsi driver to send a "start up" command
1929  */
1930 static int
1931 cd_pause(struct cd_softc *cd, int go)
1932 {
1933 	struct scsipi_pause cmd;
1934 
1935 	memset(&cmd, 0, sizeof(cmd));
1936 	cmd.opcode = PAUSE;
1937 	cmd.resume = go & 0xff;
1938 
1939 	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
1940 	    CDRETRIES, 30000, NULL, 0));
1941 }
1942 
1943 /*
1944  * Get scsi driver to send a "RESET" command
1945  */
1946 static int
1947 cd_reset(struct cd_softc *cd)
1948 {
1949 
1950 	return (scsipi_command(cd->sc_periph, 0, 0, 0, 0,
1951 	    CDRETRIES, 30000, NULL, XS_CTL_RESET));
1952 }
1953 
1954 /*
1955  * Read subchannel
1956  */
1957 static int
1958 cd_read_subchannel(struct cd_softc *cd, int mode, int format, int track,
1959     struct cd_sub_channel_info *data, int len, int flags)
1960 {
1961 	struct scsipi_read_subchannel cmd;
1962 
1963 	memset(&cmd, 0, sizeof(cmd));
1964 	cmd.opcode = READ_SUBCHANNEL;
1965 	if (mode == CD_MSF_FORMAT)
1966 		cmd.byte2 |= CD_MSF;
1967 	cmd.byte3 = SRS_SUBQ;
1968 	cmd.subchan_format = format;
1969 	cmd.track = track;
1970 	_lto2b(len, cmd.data_len);
1971 
1972 	return (scsipi_command(cd->sc_periph,
1973 	    (void *)&cmd, sizeof(struct scsipi_read_subchannel),
1974 	    (void *)data, len,
1975 	    CDRETRIES, 30000, NULL, flags | XS_CTL_DATA_IN | XS_CTL_SILENT));
1976 }
1977 
1978 /*
1979  * Read table of contents
1980  */
1981 static int
1982 cd_read_toc(struct cd_softc *cd, int respf, int mode, int start,
1983     struct cd_formatted_toc *toc, int len, int flags, int control)
1984 {
1985 	struct scsipi_read_toc cmd;
1986 	int ntoc;
1987 
1988 	memset(&cmd, 0, sizeof(cmd));
1989 #if 0
1990 	if (len != sizeof(struct ioc_toc_header))
1991 		ntoc = ((len) - sizeof(struct ioc_toc_header)) /
1992 		    sizeof(struct cd_toc_entry);
1993 	else
1994 #endif
1995 	ntoc = len;
1996 	cmd.opcode = READ_TOC;
1997 	if (mode == CD_MSF_FORMAT)
1998 		cmd.addr_mode |= CD_MSF;
1999 	cmd.resp_format = respf;
2000 	cmd.from_track = start;
2001 	_lto2b(ntoc, cmd.data_len);
2002 	cmd.control = control;
2003 
2004 	return (scsipi_command(cd->sc_periph,
2005 	    (void *)&cmd, sizeof(cmd), (void *)toc, len, CDRETRIES,
2006 	    30000, NULL, flags | XS_CTL_DATA_IN));
2007 }
2008 
2009 static int
2010 cd_load_toc(struct cd_softc *cd, int respf, struct cd_formatted_toc *toc, int flags)
2011 {
2012 	int ntracks, len, error;
2013 
2014 	if ((error = cd_read_toc(cd, respf, 0, 0, toc, sizeof(toc->header),
2015 	    flags, 0)) != 0)
2016 		return (error);
2017 
2018 	ntracks = toc->header.ending_track - toc->header.starting_track + 1;
2019 	len = (ntracks + 1) * sizeof(struct cd_toc_entry) +
2020 	    sizeof(toc->header);
2021 	if ((error = cd_read_toc(cd, respf, CD_MSF_FORMAT, 0, toc, len,
2022 	    flags, 0)) != 0)
2023 		return (error);
2024 	return (0);
2025 }
2026 
2027 /*
2028  * Get the scsi driver to send a full inquiry to the device and use the
2029  * results to fill out the disk parameter structure.
2030  */
2031 static int
2032 cd_get_parms(struct cd_softc *cd, int flags)
2033 {
2034 
2035 	/*
2036 	 * give a number of sectors so that sec * trks * cyls
2037 	 * is <= disk_size
2038 	 */
2039 	if (cd_size(cd, flags) == 0)
2040 		return (ENXIO);
2041 	disk_blocksize(&cd->sc_dk, cd->params.blksize);
2042 	return (0);
2043 }
2044 
2045 static int
2046 cdsize(dev_t dev)
2047 {
2048 
2049 	/* CD-ROMs are read-only. */
2050 	return (-1);
2051 }
2052 
2053 static int
2054 cddump(dev_t dev, daddr_t blkno, void *va, size_t size)
2055 {
2056 
2057 	/* Not implemented. */
2058 	return (ENXIO);
2059 }
2060 
2061 #define	dvd_copy_key(dst, src)		memcpy((dst), (src), sizeof(dvd_key))
2062 #define	dvd_copy_challenge(dst, src)	memcpy((dst), (src), sizeof(dvd_challenge))
2063 
2064 static int
2065 dvd_auth(struct cd_softc *cd, dvd_authinfo *a)
2066 {
2067 	struct scsipi_generic cmd;
2068 	u_int8_t bf[20];
2069 	int error;
2070 
2071 	memset(cmd.bytes, 0, 15);
2072 	memset(bf, 0, sizeof(bf));
2073 
2074 	switch (a->type) {
2075 	case DVD_LU_SEND_AGID:
2076 		cmd.opcode = GPCMD_REPORT_KEY;
2077 		cmd.bytes[8] = 8;
2078 		cmd.bytes[9] = 0 | (0 << 6);
2079 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
2080 		    CDRETRIES, 30000, NULL,
2081 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2082 		if (error)
2083 			return (error);
2084 		a->lsa.agid = bf[7] >> 6;
2085 		return (0);
2086 
2087 	case DVD_LU_SEND_CHALLENGE:
2088 		cmd.opcode = GPCMD_REPORT_KEY;
2089 		cmd.bytes[8] = 16;
2090 		cmd.bytes[9] = 1 | (a->lsc.agid << 6);
2091 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 16,
2092 		    CDRETRIES, 30000, NULL,
2093 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2094 		if (error)
2095 			return (error);
2096 		dvd_copy_challenge(a->lsc.chal, &bf[4]);
2097 		return (0);
2098 
2099 	case DVD_LU_SEND_KEY1:
2100 		cmd.opcode = GPCMD_REPORT_KEY;
2101 		cmd.bytes[8] = 12;
2102 		cmd.bytes[9] = 2 | (a->lsk.agid << 6);
2103 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 12,
2104 		    CDRETRIES, 30000, NULL,
2105 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2106 		if (error)
2107 			return (error);
2108 		dvd_copy_key(a->lsk.key, &bf[4]);
2109 		return (0);
2110 
2111 	case DVD_LU_SEND_TITLE_KEY:
2112 		cmd.opcode = GPCMD_REPORT_KEY;
2113 		_lto4b(a->lstk.lba, &cmd.bytes[1]);
2114 		cmd.bytes[8] = 12;
2115 		cmd.bytes[9] = 4 | (a->lstk.agid << 6);
2116 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 12,
2117 		    CDRETRIES, 30000, NULL,
2118 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2119 		if (error)
2120 			return (error);
2121 		a->lstk.cpm = (bf[4] >> 7) & 1;
2122 		a->lstk.cp_sec = (bf[4] >> 6) & 1;
2123 		a->lstk.cgms = (bf[4] >> 4) & 3;
2124 		dvd_copy_key(a->lstk.title_key, &bf[5]);
2125 		return (0);
2126 
2127 	case DVD_LU_SEND_ASF:
2128 		cmd.opcode = GPCMD_REPORT_KEY;
2129 		cmd.bytes[8] = 8;
2130 		cmd.bytes[9] = 5 | (a->lsasf.agid << 6);
2131 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
2132 		    CDRETRIES, 30000, NULL,
2133 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2134 		if (error)
2135 			return (error);
2136 		a->lsasf.asf = bf[7] & 1;
2137 		return (0);
2138 
2139 	case DVD_HOST_SEND_CHALLENGE:
2140 		cmd.opcode = GPCMD_SEND_KEY;
2141 		cmd.bytes[8] = 16;
2142 		cmd.bytes[9] = 1 | (a->hsc.agid << 6);
2143 		bf[1] = 14;
2144 		dvd_copy_challenge(&bf[4], a->hsc.chal);
2145 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 16,
2146 		    CDRETRIES, 30000, NULL,
2147 		    XS_CTL_DATA_OUT|XS_CTL_DATA_ONSTACK);
2148 		if (error)
2149 			return (error);
2150 		a->type = DVD_LU_SEND_KEY1;
2151 		return (0);
2152 
2153 	case DVD_HOST_SEND_KEY2:
2154 		cmd.opcode = GPCMD_SEND_KEY;
2155 		cmd.bytes[8] = 12;
2156 		cmd.bytes[9] = 3 | (a->hsk.agid << 6);
2157 		bf[1] = 10;
2158 		dvd_copy_key(&bf[4], a->hsk.key);
2159 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 12,
2160 		    CDRETRIES, 30000, NULL,
2161 		    XS_CTL_DATA_OUT|XS_CTL_DATA_ONSTACK);
2162 		if (error) {
2163 			a->type = DVD_AUTH_FAILURE;
2164 			return (error);
2165 		}
2166 		a->type = DVD_AUTH_ESTABLISHED;
2167 		return (0);
2168 
2169 	case DVD_INVALIDATE_AGID:
2170 		cmd.opcode = GPCMD_REPORT_KEY;
2171 		cmd.bytes[9] = 0x3f | (a->lsa.agid << 6);
2172 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 16,
2173 		    CDRETRIES, 30000, NULL, 0);
2174 		if (error)
2175 			return (error);
2176 		return (0);
2177 
2178 	case DVD_LU_SEND_RPC_STATE:
2179 		cmd.opcode = GPCMD_REPORT_KEY;
2180 		cmd.bytes[8] = 8;
2181 		cmd.bytes[9] = 8 | (0 << 6);
2182 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
2183 		    CDRETRIES, 30000, NULL,
2184 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2185 		if (error)
2186 			return (error);
2187 		a->lrpcs.type = (bf[4] >> 6) & 3;
2188 		a->lrpcs.vra = (bf[4] >> 3) & 7;
2189 		a->lrpcs.ucca = (bf[4]) & 7;
2190 		a->lrpcs.region_mask = bf[5];
2191 		a->lrpcs.rpc_scheme = bf[6];
2192 		return (0);
2193 
2194 	case DVD_HOST_SEND_RPC_STATE:
2195 		cmd.opcode = GPCMD_SEND_KEY;
2196 		cmd.bytes[8] = 8;
2197 		cmd.bytes[9] = 6 | (0 << 6);
2198 		bf[1] = 6;
2199 		bf[4] = a->hrpcs.pdrc;
2200 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
2201 		    CDRETRIES, 30000, NULL,
2202 		    XS_CTL_DATA_OUT|XS_CTL_DATA_ONSTACK);
2203 		if (error)
2204 			return (error);
2205 		return (0);
2206 
2207 	default:
2208 		return (ENOTTY);
2209 	}
2210 }
2211 
2212 static int
2213 dvd_read_physical(struct cd_softc *cd, dvd_struct *s)
2214 {
2215 	struct scsipi_generic cmd;
2216 	u_int8_t bf[4 + 4 * 20], *bufp;
2217 	int error;
2218 	struct dvd_layer *layer;
2219 	int i;
2220 
2221 	memset(cmd.bytes, 0, 15);
2222 	memset(bf, 0, sizeof(bf));
2223 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2224 	cmd.bytes[6] = s->type;
2225 	_lto2b(sizeof(bf), &cmd.bytes[7]);
2226 
2227 	cmd.bytes[5] = s->physical.layer_num;
2228 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, sizeof(bf),
2229 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2230 	if (error)
2231 		return (error);
2232 	for (i = 0, bufp = &bf[4], layer = &s->physical.layer[0]; i < 4;
2233 	     i++, bufp += 20, layer++) {
2234 		memset(layer, 0, sizeof(*layer));
2235                 layer->book_version = bufp[0] & 0xf;
2236                 layer->book_type = bufp[0] >> 4;
2237                 layer->min_rate = bufp[1] & 0xf;
2238                 layer->disc_size = bufp[1] >> 4;
2239                 layer->layer_type = bufp[2] & 0xf;
2240                 layer->track_path = (bufp[2] >> 4) & 1;
2241                 layer->nlayers = (bufp[2] >> 5) & 3;
2242                 layer->track_density = bufp[3] & 0xf;
2243                 layer->linear_density = bufp[3] >> 4;
2244                 layer->start_sector = _4btol(&bufp[4]);
2245                 layer->end_sector = _4btol(&bufp[8]);
2246                 layer->end_sector_l0 = _4btol(&bufp[12]);
2247                 layer->bca = bufp[16] >> 7;
2248 	}
2249 	return (0);
2250 }
2251 
2252 static int
2253 dvd_read_copyright(struct cd_softc *cd, dvd_struct *s)
2254 {
2255 	struct scsipi_generic cmd;
2256 	u_int8_t bf[8];
2257 	int error;
2258 
2259 	memset(cmd.bytes, 0, 15);
2260 	memset(bf, 0, sizeof(bf));
2261 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2262 	cmd.bytes[6] = s->type;
2263 	_lto2b(sizeof(bf), &cmd.bytes[7]);
2264 
2265 	cmd.bytes[5] = s->copyright.layer_num;
2266 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, sizeof(bf),
2267 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2268 	if (error)
2269 		return (error);
2270 	s->copyright.cpst = bf[4];
2271 	s->copyright.rmi = bf[5];
2272 	return (0);
2273 }
2274 
2275 static int
2276 dvd_read_disckey(struct cd_softc *cd, dvd_struct *s)
2277 {
2278 	struct scsipi_generic cmd;
2279 	u_int8_t *bf;
2280 	int error;
2281 
2282 	bf = malloc(4 + 2048, M_TEMP, M_WAITOK|M_ZERO);
2283 	if (bf == NULL)
2284 		return EIO;
2285 	memset(cmd.bytes, 0, 15);
2286 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2287 	cmd.bytes[6] = s->type;
2288 	_lto2b(4 + 2048, &cmd.bytes[7]);
2289 
2290 	cmd.bytes[9] = s->disckey.agid << 6;
2291 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 4 + 2048,
2292 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2293 	if (error == 0)
2294 		memcpy(s->disckey.value, &bf[4], 2048);
2295 	free(bf, M_TEMP);
2296 	return error;
2297 }
2298 
2299 static int
2300 dvd_read_bca(struct cd_softc *cd, dvd_struct *s)
2301 {
2302 	struct scsipi_generic cmd;
2303 	u_int8_t bf[4 + 188];
2304 	int error;
2305 
2306 	memset(cmd.bytes, 0, 15);
2307 	memset(bf, 0, sizeof(bf));
2308 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2309 	cmd.bytes[6] = s->type;
2310 	_lto2b(sizeof(bf), &cmd.bytes[7]);
2311 
2312 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, sizeof(bf),
2313 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2314 	if (error)
2315 		return (error);
2316 	s->bca.len = _2btol(&bf[0]);
2317 	if (s->bca.len < 12 || s->bca.len > 188)
2318 		return (EIO);
2319 	memcpy(s->bca.value, &bf[4], s->bca.len);
2320 	return (0);
2321 }
2322 
2323 static int
2324 dvd_read_manufact(struct cd_softc *cd, dvd_struct *s)
2325 {
2326 	struct scsipi_generic cmd;
2327 	u_int8_t *bf;
2328 	int error;
2329 
2330 	bf = malloc(4 + 2048, M_TEMP, M_WAITOK|M_ZERO);
2331 	if (bf == NULL)
2332 		return (EIO);
2333 	memset(cmd.bytes, 0, 15);
2334 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2335 	cmd.bytes[6] = s->type;
2336 	_lto2b(4 + 2048, &cmd.bytes[7]);
2337 
2338 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 4 + 2048,
2339 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2340 	if (error == 0) {
2341 		s->manufact.len = _2btol(&bf[0]);
2342 		if (s->manufact.len >= 0 && s->manufact.len <= 2048)
2343 			memcpy(s->manufact.value, &bf[4], s->manufact.len);
2344 		else
2345 			error = EIO;
2346 	}
2347 	free(bf, M_TEMP);
2348 	return error;
2349 }
2350 
2351 static int
2352 dvd_read_struct(struct cd_softc *cd, dvd_struct *s)
2353 {
2354 
2355 	switch (s->type) {
2356 	case DVD_STRUCT_PHYSICAL:
2357 		return (dvd_read_physical(cd, s));
2358 	case DVD_STRUCT_COPYRIGHT:
2359 		return (dvd_read_copyright(cd, s));
2360 	case DVD_STRUCT_DISCKEY:
2361 		return (dvd_read_disckey(cd, s));
2362 	case DVD_STRUCT_BCA:
2363 		return (dvd_read_bca(cd, s));
2364 	case DVD_STRUCT_MANUFACT:
2365 		return (dvd_read_manufact(cd, s));
2366 	default:
2367 		return (EINVAL);
2368 	}
2369 }
2370 
2371 static int
2372 cd_mode_sense(struct cd_softc *cd, u_int8_t byte2, void *sense, size_t size,
2373     int page, int flags, int *big)
2374 {
2375 
2376 	if (cd->sc_periph->periph_quirks & PQUIRK_ONLYBIG) {
2377 		*big = 1;
2378 		return scsipi_mode_sense_big(cd->sc_periph, byte2, page, sense,
2379 		    size + sizeof(struct scsi_mode_parameter_header_10),
2380 		    flags | XS_CTL_DATA_ONSTACK, CDRETRIES, 20000);
2381 	} else {
2382 		*big = 0;
2383 		return scsipi_mode_sense(cd->sc_periph, byte2, page, sense,
2384 		    size + sizeof(struct scsi_mode_parameter_header_6),
2385 		    flags | XS_CTL_DATA_ONSTACK, CDRETRIES, 20000);
2386 	}
2387 }
2388 
2389 static int
2390 cd_mode_select(struct cd_softc *cd, u_int8_t byte2, void *sense, size_t size,
2391     int flags, int big)
2392 {
2393 
2394 	if (big) {
2395 		struct scsi_mode_parameter_header_10 *header = sense;
2396 
2397 		_lto2b(0, header->data_length);
2398 		return scsipi_mode_select_big(cd->sc_periph, byte2, sense,
2399 		    size + sizeof(struct scsi_mode_parameter_header_10),
2400 		    flags | XS_CTL_DATA_ONSTACK, CDRETRIES, 20000);
2401 	} else {
2402 		struct scsi_mode_parameter_header_6 *header = sense;
2403 
2404 		header->data_length = 0;
2405 		return scsipi_mode_select(cd->sc_periph, byte2, sense,
2406 		    size + sizeof(struct scsi_mode_parameter_header_6),
2407 		    flags | XS_CTL_DATA_ONSTACK, CDRETRIES, 20000);
2408 	}
2409 }
2410 
2411 static int
2412 cd_set_pa_immed(struct cd_softc *cd, int flags)
2413 {
2414 	struct {
2415 		union {
2416 			struct scsi_mode_parameter_header_6 small;
2417 			struct scsi_mode_parameter_header_10 big;
2418 		} header;
2419 		struct cd_audio_page page;
2420 	} data;
2421 	int error;
2422 	uint8_t oflags;
2423 	int big, byte2;
2424 	struct cd_audio_page *page;
2425 
2426 	byte2 = SMS_DBD;
2427 try_again:
2428 	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
2429 	    AUDIO_PAGE, flags, &big)) != 0) {
2430 		if (byte2 == SMS_DBD) {
2431 			/* Device may not understand DBD; retry without */
2432 			byte2 = 0;
2433 			goto try_again;
2434 		}
2435 		return (error);
2436 	}
2437 
2438 	if (big)
2439 		page = (void *)((u_long)&data.header.big +
2440 				sizeof data.header.big +
2441 				_2btol(data.header.big.blk_desc_len));
2442 	else
2443 		page = (void *)((u_long)&data.header.small +
2444 				sizeof data.header.small +
2445 				data.header.small.blk_desc_len);
2446 
2447 	oflags = page->flags;
2448 	page->flags &= ~CD_PA_SOTC;
2449 	page->flags |= CD_PA_IMMED;
2450 	if (oflags == page->flags)
2451 		return (0);
2452 
2453 	return (cd_mode_select(cd, SMS_PF, &data,
2454 	    sizeof(struct scsi_mode_page_header) + page->pg_length,
2455 	    flags, big));
2456 }
2457 
2458 static int
2459 cd_setchan(struct cd_softc *cd, int p0, int p1, int p2, int p3, int flags)
2460 {
2461 	struct {
2462 		union {
2463 			struct scsi_mode_parameter_header_6 small;
2464 			struct scsi_mode_parameter_header_10 big;
2465 		} header;
2466 		struct cd_audio_page page;
2467 	} data;
2468 	int error;
2469 	int big, byte2;
2470 	struct cd_audio_page *page;
2471 
2472 	byte2 = SMS_DBD;
2473 try_again:
2474 	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
2475 	    AUDIO_PAGE, flags, &big)) != 0) {
2476 		if (byte2 == SMS_DBD) {
2477 			/* Device may not understand DBD; retry without */
2478 			byte2 = 0;
2479 			goto try_again;
2480 		}
2481 		return (error);
2482 	}
2483 
2484 	if (big)
2485 		page = (void *)((u_long)&data.header.big +
2486 				sizeof data.header.big +
2487 				_2btol(data.header.big.blk_desc_len));
2488 	else
2489 		page = (void *)((u_long)&data.header.small +
2490 				sizeof data.header.small +
2491 				data.header.small.blk_desc_len);
2492 
2493 	page->port[0].channels = p0;
2494 	page->port[1].channels = p1;
2495 	page->port[2].channels = p2;
2496 	page->port[3].channels = p3;
2497 
2498 	return (cd_mode_select(cd, SMS_PF, &data,
2499 	    sizeof(struct scsi_mode_page_header) + page->pg_length,
2500 	    flags, big));
2501 }
2502 
2503 static int
2504 cd_getvol(struct cd_softc *cd, struct ioc_vol *arg, int flags)
2505 {
2506 	struct {
2507 		union {
2508 			struct scsi_mode_parameter_header_6 small;
2509 			struct scsi_mode_parameter_header_10 big;
2510 		} header;
2511 		struct cd_audio_page page;
2512 	} data;
2513 	int error;
2514 	int big, byte2;
2515 	struct cd_audio_page *page;
2516 
2517 	byte2 = SMS_DBD;
2518 try_again:
2519 	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
2520 	    AUDIO_PAGE, flags, &big)) != 0) {
2521 		if (byte2 == SMS_DBD) {
2522 			/* Device may not understand DBD; retry without */
2523 			byte2 = 0;
2524 			goto try_again;
2525 		}
2526 		return (error);
2527 	}
2528 
2529 	if (big)
2530 		page = (void *)((u_long)&data.header.big +
2531 				sizeof data.header.big +
2532 				_2btol(data.header.big.blk_desc_len));
2533 	else
2534 		page = (void *)((u_long)&data.header.small +
2535 				sizeof data.header.small +
2536 				data.header.small.blk_desc_len);
2537 
2538 	arg->vol[0] = page->port[0].volume;
2539 	arg->vol[1] = page->port[1].volume;
2540 	arg->vol[2] = page->port[2].volume;
2541 	arg->vol[3] = page->port[3].volume;
2542 
2543 	return (0);
2544 }
2545 
2546 static int
2547 cd_setvol(struct cd_softc *cd, const struct ioc_vol *arg, int flags)
2548 {
2549 	struct {
2550 		union {
2551 			struct scsi_mode_parameter_header_6 small;
2552 			struct scsi_mode_parameter_header_10 big;
2553 		} header;
2554 		struct cd_audio_page page;
2555 	} data, mask;
2556 	int error;
2557 	int big, byte2;
2558 	struct cd_audio_page *page, *page2;
2559 
2560 	byte2 = SMS_DBD;
2561 try_again:
2562 	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
2563 	    AUDIO_PAGE, flags, &big)) != 0) {
2564 		if (byte2 == SMS_DBD) {
2565 			/* Device may not understand DBD; retry without */
2566 			byte2 = 0;
2567 			goto try_again;
2568 		}
2569 		return (error);
2570 	}
2571 	if ((error = cd_mode_sense(cd, byte2, &mask, sizeof(mask.page),
2572 	    AUDIO_PAGE|SMS_PCTRL_CHANGEABLE, flags, &big)) != 0)
2573 		return (error);
2574 
2575 	if (big) {
2576 		page = (void *)((u_long)&data.header.big +
2577 				sizeof data.header.big +
2578 				_2btol(data.header.big.blk_desc_len));
2579 		page2 = (void *)((u_long)&mask.header.big +
2580 				sizeof mask.header.big +
2581 				_2btol(mask.header.big.blk_desc_len));
2582 	} else {
2583 		page = (void *)((u_long)&data.header.small +
2584 				sizeof data.header.small +
2585 				data.header.small.blk_desc_len);
2586 		page2 = (void *)((u_long)&mask.header.small +
2587 				sizeof mask.header.small +
2588 				mask.header.small.blk_desc_len);
2589 	}
2590 
2591 	page->port[0].volume = arg->vol[0] & page2->port[0].volume;
2592 	page->port[1].volume = arg->vol[1] & page2->port[1].volume;
2593 	page->port[2].volume = arg->vol[2] & page2->port[2].volume;
2594 	page->port[3].volume = arg->vol[3] & page2->port[3].volume;
2595 
2596 	page->port[0].channels = CHANNEL_0;
2597 	page->port[1].channels = CHANNEL_1;
2598 
2599 	return (cd_mode_select(cd, SMS_PF, &data,
2600 	    sizeof(struct scsi_mode_page_header) + page->pg_length,
2601 	    flags, big));
2602 }
2603 
2604 static int
2605 cd_load_unload(struct cd_softc *cd, struct ioc_load_unload *args)
2606 {
2607 	struct scsipi_load_unload cmd;
2608 
2609 	memset(&cmd, 0, sizeof(cmd));
2610 	cmd.opcode = LOAD_UNLOAD;
2611 	cmd.options = args->options;    /* ioctl uses MMC values */
2612 	cmd.slot = args->slot;
2613 
2614 	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
2615 	    CDRETRIES, 200000, NULL, 0));
2616 }
2617 
2618 static int
2619 cd_setblksize(struct cd_softc *cd)
2620 {
2621 	struct {
2622 		union {
2623 			struct scsi_mode_parameter_header_6 small;
2624 			struct scsi_mode_parameter_header_10 big;
2625 		} header;
2626 		struct scsi_general_block_descriptor blk_desc;
2627 	} data;
2628 	int error;
2629 	int big, bsize;
2630 	struct scsi_general_block_descriptor *bdesc;
2631 
2632 	if ((error = cd_mode_sense(cd, 0, &data, sizeof(data.blk_desc), 0, 0,
2633 	    &big)) != 0)
2634 		return (error);
2635 
2636 	if (big) {
2637 		bdesc = (void *)(&data.header.big + 1);
2638 		bsize = _2btol(data.header.big.blk_desc_len);
2639 	} else {
2640 		bdesc = (void *)(&data.header.small + 1);
2641 		bsize = data.header.small.blk_desc_len;
2642 	}
2643 
2644 	if (bsize == 0) {
2645 printf("cd_setblksize: trying to change bsize, but no blk_desc\n");
2646 		return (EINVAL);
2647 	}
2648 	if (_3btol(bdesc->blklen) == 2048) {
2649 printf("cd_setblksize: trying to change bsize, but blk_desc is correct\n");
2650 		return (EINVAL);
2651 	}
2652 
2653 	_lto3b(2048, bdesc->blklen);
2654 
2655 	return (cd_mode_select(cd, SMS_PF, &data, sizeof(data.blk_desc), 0,
2656 	    big));
2657 }
2658 
2659 
2660 static int
2661 mmc_profile2class(uint16_t mmc_profile)
2662 {
2663 	switch (mmc_profile) {
2664 	case 0x01 : /* SCSI discs */
2665 	case 0x02 :
2666 		/* this can't happen really, cd.c wouldn't have matched */
2667 		return MMC_CLASS_DISC;
2668 	case 0x03 : /* Magneto Optical with sector erase */
2669 	case 0x04 : /* Magneto Optical write once        */
2670 	case 0x05 : /* Advance Storage Magneto Optical   */
2671 		return MMC_CLASS_MO;
2672 	case 0x00 : /* Unknown MMC profile, can also be CD-ROM */
2673 	case 0x08 : /* CD-ROM  */
2674 	case 0x09 : /* CD-R    */
2675 	case 0x0a : /* CD-RW   */
2676 		return MMC_CLASS_CD;
2677 	case 0x10 : /* DVD-ROM */
2678 	case 0x11 : /* DVD-R   */
2679 	case 0x12 : /* DVD-RAM */
2680 	case 0x13 : /* DVD-RW restricted overwrite */
2681 	case 0x14 : /* DVD-RW sequential */
2682 	case 0x1a : /* DVD+RW  */
2683 	case 0x1b : /* DVD+R   */
2684 	case 0x2a : /* DVD+RW Dual layer */
2685 	case 0x2b : /* DVD+R Dual layer */
2686 	case 0x50 : /* HD DVD-ROM */
2687 	case 0x51 : /* HD DVD-R   */
2688 	case 0x52 : /* HD DVD-RW; DVD-RAM like */
2689 		return MMC_CLASS_DVD;
2690 	case 0x40 : /* BD-ROM  */
2691 	case 0x41 : /* BD-R Sequential recording (SRM) */
2692 	case 0x42 : /* BD-R Ramdom Recording (RRM) */
2693 	case 0x43 : /* BD-RE */
2694 		return MMC_CLASS_BD;
2695 	}
2696 	return MMC_CLASS_UNKN;
2697 }
2698 
2699 
2700 /*
2701  * Drive/media combination is reflected in a series of features that can
2702  * either be current or dormant. We try to make sense out of them to create a
2703  * set of easy to use flags that abstract the device/media capabilities.
2704  */
2705 
2706 static void
2707 mmc_process_feature(struct mmc_discinfo *mmc_discinfo,
2708 		    uint16_t feature, int cur, uint8_t *rpos)
2709 {
2710 	uint32_t blockingnr;
2711 	uint64_t flags;
2712 
2713 	if (cur == 1) {
2714 		flags = mmc_discinfo->mmc_cur;
2715 	} else {
2716 		flags = mmc_discinfo->mmc_cap;
2717 	}
2718 
2719 	switch (feature) {
2720 	case 0x0010 :	/* random readable feature */
2721 		blockingnr  =  rpos[5] | (rpos[4] << 8);
2722 		if (blockingnr > 1)
2723 			flags |= MMC_CAP_PACKET;
2724 
2725 		/* RW error page */
2726 		break;
2727 	case 0x0020 :	/* random writable feature */
2728 		flags |= MMC_CAP_RECORDABLE;
2729 		flags |= MMC_CAP_REWRITABLE;
2730 		blockingnr  =  rpos[9] | (rpos[8] << 8);
2731 		if (blockingnr > 1)
2732 			flags |= MMC_CAP_PACKET;
2733 		break;
2734 	case 0x0021 :	/* incremental streaming write feature */
2735 		flags |= MMC_CAP_RECORDABLE;
2736 		flags |= MMC_CAP_SEQUENTIAL;
2737 		if (cur)
2738 			mmc_discinfo->link_block_penalty = rpos[4];
2739 		if (rpos[2] & 1)
2740 			flags |= MMC_CAP_ZEROLINKBLK;
2741 		break;
2742 	case 0x0022 : 	/* (obsolete) erase support feature */
2743 		flags |= MMC_CAP_RECORDABLE;
2744 		flags |= MMC_CAP_ERASABLE;
2745 		break;
2746 	case 0x0023 :	/* formatting media support feature */
2747 		flags |= MMC_CAP_RECORDABLE;
2748 		flags |= MMC_CAP_FORMATTABLE;
2749 		break;
2750 	case 0x0024 :	/* hardware assised defect management feature */
2751 		flags |= MMC_CAP_HW_DEFECTFREE;
2752 		break;
2753 	case 0x0025 : 	/* write once */
2754 		flags |= MMC_CAP_RECORDABLE;
2755 		break;
2756 	case 0x0026 :	/* restricted overwrite feature */
2757 		flags |= MMC_CAP_RECORDABLE;
2758 		flags |= MMC_CAP_REWRITABLE;
2759 		flags |= MMC_CAP_STRICTOVERWRITE;
2760 		break;
2761 	case 0x0028 :	/* MRW formatted media support feature */
2762 		flags |= MMC_CAP_MRW;
2763 		break;
2764 	case 0x002b :	/* DVD+R read (and opt. write) support */
2765 		flags |= MMC_CAP_SEQUENTIAL;
2766 		if (rpos[0] & 1) /* write support */
2767 			flags |= MMC_CAP_RECORDABLE;
2768 		break;
2769 	case 0x002c :	/* rigid restricted overwrite feature */
2770 		flags |= MMC_CAP_RECORDABLE;
2771 		flags |= MMC_CAP_REWRITABLE;
2772 		flags |= MMC_CAP_STRICTOVERWRITE;
2773 		if (rpos[0] & 1) /* blank bit */
2774 			flags |= MMC_CAP_BLANKABLE;
2775 		break;
2776 	case 0x002d :	/* track at once recording feature */
2777 		flags |= MMC_CAP_RECORDABLE;
2778 		flags |= MMC_CAP_SEQUENTIAL;
2779 		break;
2780 	case 0x002f :	/* DVD-R/-RW write feature */
2781 		flags |= MMC_CAP_RECORDABLE;
2782 		if (rpos[0] & 2) /* DVD-RW bit */
2783 			flags |= MMC_CAP_BLANKABLE;
2784 		break;
2785 	case 0x0038 :	/* BD-R SRM with pseudo overwrite */
2786 		flags |= MMC_CAP_PSEUDOOVERWRITE;
2787 		break;
2788 	default :
2789 		/* ignore */
2790 		break;
2791 	}
2792 
2793 	if (cur == 1) {
2794 		mmc_discinfo->mmc_cur = flags;
2795 	} else {
2796 		mmc_discinfo->mmc_cap = flags;
2797 	}
2798 }
2799 
2800 static int
2801 mmc_getdiscinfo_cdrom(struct scsipi_periph *periph,
2802 		      struct mmc_discinfo *mmc_discinfo)
2803 {
2804 	struct scsipi_read_toc      gtoc_cmd;
2805 	struct scsipi_toc_header   *toc_hdr;
2806 	struct scsipi_toc_msinfo   *toc_msinfo;
2807 	const uint32_t buffer_size = 1024;
2808 	uint32_t req_size;
2809 	uint8_t  *buffer;
2810 	int error, flags;
2811 
2812 	buffer = malloc(buffer_size, M_TEMP, M_WAITOK);
2813 	/*
2814 	 * Fabricate mmc_discinfo for CD-ROM. Some values are really `dont
2815 	 * care' but others might be of interest to programs.
2816 	 */
2817 
2818 	mmc_discinfo->disc_state	 = MMC_STATE_FULL;
2819 	mmc_discinfo->last_session_state = MMC_STATE_FULL;
2820 	mmc_discinfo->bg_format_state    = MMC_BGFSTATE_COMPLETED;
2821 	mmc_discinfo->link_block_penalty = 7;	/* not relevant */
2822 
2823 	/* get number of sessions and first tracknr in last session */
2824 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK;
2825 	bzero(&gtoc_cmd, sizeof(gtoc_cmd));
2826 	gtoc_cmd.opcode      = READ_TOC;
2827 	gtoc_cmd.addr_mode   = CD_MSF;		/* not relevant        */
2828 	gtoc_cmd.resp_format = CD_TOC_MSINFO;	/* multisession info   */
2829 	gtoc_cmd.from_track  = 0;		/* reserved, must be 0 */
2830 	req_size = sizeof(*toc_hdr) + sizeof(*toc_msinfo);
2831 	_lto2b(req_size, gtoc_cmd.data_len);
2832 
2833 	error = scsipi_command(periph,
2834 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
2835 		(void *)buffer,    req_size,
2836 		CDRETRIES, 30000, NULL, flags);
2837 	if (error)
2838 		goto out;
2839 	toc_hdr    = (struct scsipi_toc_header *)  buffer;
2840 	toc_msinfo = (struct scsipi_toc_msinfo *) (buffer + 4);
2841 	mmc_discinfo->num_sessions = toc_hdr->last - toc_hdr->first + 1;
2842 	mmc_discinfo->first_track  = toc_hdr->first;
2843 	mmc_discinfo->first_track_last_session = toc_msinfo->tracknr;
2844 
2845 	/* get last track of last session */
2846 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK;
2847 	gtoc_cmd.resp_format  = CD_TOC_FORM;	/* formatted toc */
2848 	req_size = sizeof(*toc_hdr);
2849 	_lto2b(req_size, gtoc_cmd.data_len);
2850 
2851 	error = scsipi_command(periph,
2852 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
2853 		(void *)buffer,    req_size,
2854 		CDRETRIES, 30000, NULL, flags);
2855 	if (error)
2856 		goto out;
2857 	toc_hdr    = (struct scsipi_toc_header *) buffer;
2858 	mmc_discinfo->last_track_last_session = toc_hdr->last;
2859 	mmc_discinfo->num_tracks = toc_hdr->last - toc_hdr->first + 1;
2860 
2861 	/* TODO how to handle disc_barcode and disc_id */
2862 	/* done */
2863 
2864 out:
2865 	free(buffer, M_TEMP);
2866 	return error;
2867 }
2868 
2869 static int
2870 mmc_getdiscinfo_dvdrom(struct scsipi_periph *periph,
2871 		       struct mmc_discinfo *mmc_discinfo)
2872 {
2873 	struct scsipi_read_toc   gtoc_cmd;
2874 	struct scsipi_toc_header toc_hdr;
2875 	uint32_t req_size;
2876 	int error, flags;
2877 
2878 	/*
2879 	 * Fabricate mmc_discinfo for DVD-ROM. Some values are really `dont
2880 	 * care' but others might be of interest to programs.
2881 	 */
2882 
2883 	mmc_discinfo->disc_state	 = MMC_STATE_FULL;
2884 	mmc_discinfo->last_session_state = MMC_STATE_FULL;
2885 	mmc_discinfo->bg_format_state    = MMC_BGFSTATE_COMPLETED;
2886 	mmc_discinfo->link_block_penalty = 16;	/* not relevant */
2887 
2888 	/* get number of sessions and first tracknr in last session */
2889 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK;
2890 	bzero(&gtoc_cmd, sizeof(gtoc_cmd));
2891 	gtoc_cmd.opcode      = READ_TOC;
2892 	gtoc_cmd.addr_mode   = 0;		/* LBA                 */
2893 	gtoc_cmd.resp_format = CD_TOC_FORM;	/* multisession info   */
2894 	gtoc_cmd.from_track  = 1;		/* first track         */
2895 	req_size = sizeof(toc_hdr);
2896 	_lto2b(req_size, gtoc_cmd.data_len);
2897 
2898 	error = scsipi_command(periph,
2899 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
2900 		(void *)&toc_hdr,  req_size,
2901 		CDRETRIES, 30000, NULL, flags);
2902 	if (error)
2903 		return error;
2904 
2905 	/* DVD-ROM squashes the track/session space */
2906 	mmc_discinfo->num_sessions = toc_hdr.last - toc_hdr.first + 1;
2907 	mmc_discinfo->num_tracks   = mmc_discinfo->num_sessions;
2908 	mmc_discinfo->first_track  = toc_hdr.first;
2909 	mmc_discinfo->first_track_last_session = toc_hdr.last;
2910 	mmc_discinfo->last_track_last_session  = toc_hdr.last;
2911 
2912 	/* TODO how to handle disc_barcode and disc_id */
2913 	/* done */
2914 	return 0;
2915 }
2916 
2917 static int
2918 mmc_getdiscinfo(struct scsipi_periph *periph,
2919 		struct mmc_discinfo *mmc_discinfo)
2920 {
2921 	struct scsipi_get_configuration   gc_cmd;
2922 	struct scsipi_get_conf_data      *gc;
2923 	struct scsipi_get_conf_feature   *gcf;
2924 	struct scsipi_read_discinfo       di_cmd;
2925 	struct scsipi_read_discinfo_data  di;
2926 	const uint32_t buffer_size = 1024;
2927 	uint32_t feat_tbl_len, pos;
2928 	u_long   last_lba;
2929 	uint8_t  *buffer, *fpos;
2930 	int feature, last_feature, features_len, feature_cur, feature_len;
2931 	int lsb, msb, error, flags;
2932 
2933 	feat_tbl_len = buffer_size;
2934 
2935 	buffer = malloc(buffer_size, M_TEMP, M_WAITOK);
2936 
2937 	/* initialise structure */
2938 	memset(mmc_discinfo, 0, sizeof(struct mmc_discinfo));
2939 	mmc_discinfo->mmc_profile = 0x00;	/* unknown */
2940 	mmc_discinfo->mmc_class   = MMC_CLASS_UNKN;
2941 	mmc_discinfo->mmc_cur     = 0;
2942 	mmc_discinfo->mmc_cap     = 0;
2943 	mmc_discinfo->link_block_penalty = 0;
2944 
2945 	/* determine mmc profile and class */
2946 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK;
2947 	memset(&gc_cmd, 0, sizeof(gc_cmd));
2948 	gc_cmd.opcode = GET_CONFIGURATION;
2949 	_lto2b(GET_CONF_NO_FEATURES_LEN, gc_cmd.data_len);
2950 
2951 	gc = (struct scsipi_get_conf_data *) buffer;
2952 
2953 	error = scsipi_command(periph,
2954 		(void *)&gc_cmd, sizeof(gc_cmd),
2955 		(void *) gc,     GET_CONF_NO_FEATURES_LEN,
2956 		CDRETRIES, 30000, NULL, flags);
2957 	if (error)
2958 		goto out;
2959 
2960 	mmc_discinfo->mmc_profile = _2btol(gc->mmc_profile);
2961 	mmc_discinfo->mmc_class = mmc_profile2class(mmc_discinfo->mmc_profile);
2962 
2963 	/* assume 2048 sector size unless told otherwise */
2964 	mmc_discinfo->sector_size = 2048;
2965 	error = read_cd_capacity(periph, &mmc_discinfo->sector_size, &last_lba);
2966 	if (error)
2967 		goto out;
2968 
2969 	mmc_discinfo->last_possible_lba = (uint32_t) last_lba - 1;
2970 
2971 	/* Read in all features to determine device capabilities */
2972 	last_feature = feature = 0;
2973 	do {
2974 		/* determine mmc profile and class */
2975 		flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK;
2976 		memset(&gc_cmd, 0, sizeof(gc_cmd));
2977 		gc_cmd.opcode = GET_CONFIGURATION;
2978 		_lto2b(last_feature, gc_cmd.start_at_feature);
2979 		_lto2b(feat_tbl_len, gc_cmd.data_len);
2980 
2981 		error = scsipi_command(periph,
2982 			(void *)&gc_cmd, sizeof(gc_cmd),
2983 			(void *) gc,     feat_tbl_len,
2984 			CDRETRIES, 30000, NULL, flags);
2985 		if (error) {
2986 			/* ieeek... break out of loop... i dunno what to do */
2987 			break;
2988 		}
2989 
2990 		features_len = _4btol(gc->data_len);
2991 
2992 		pos  = 0;
2993 		fpos = &gc->feature_desc[0];
2994 		while (pos < features_len - 4) {
2995 			gcf = (struct scsipi_get_conf_feature *) fpos;
2996 
2997 			feature     = _2btol(gcf->featurecode);
2998 			feature_cur = gcf->flags & 1;
2999 			feature_len = gcf->additional_length;
3000 
3001 			mmc_process_feature(mmc_discinfo,
3002 					    feature, feature_cur,
3003 					    gcf->feature_dependent);
3004 
3005 			last_feature = MAX(last_feature, feature);
3006 #ifdef DIAGNOSTIC
3007 			/* assert((feature_len & 3) == 0); */
3008 			if ((feature_len & 3) != 0) {
3009 				printf("feature %d having length %d\n",
3010 					feature, feature_len);
3011 			}
3012 #endif
3013 
3014 			pos  += 4 + feature_len;
3015 			fpos += 4 + feature_len;
3016 		}
3017 		/* unlikely to ever grow past our 1kb buffer */
3018 	} while (features_len >= 0xffff);
3019 
3020 #ifdef DEBUG
3021 	printf("CD mmc %d, mmc_cur 0x%"PRIx64", mmc_cap 0x%"PRIx64"\n",
3022 		mmc_discinfo->mmc_profile,
3023 	 	mmc_discinfo->mmc_cur, mmc_discinfo->mmc_cap);
3024 #endif
3025 
3026 	/* read in disc state and number of sessions and tracks */
3027 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK | XS_CTL_SILENT;
3028 	memset(&di_cmd, 0, sizeof(di_cmd));
3029 	di_cmd.opcode = READ_DISCINFO;
3030 	di_cmd.data_len[1] = READ_DISCINFO_BIGSIZE;
3031 
3032 	error = scsipi_command(periph,
3033 		(void *)&di_cmd, sizeof(di_cmd),
3034 		(void *)&di,     READ_DISCINFO_BIGSIZE,
3035 		CDRETRIES, 30000, NULL, flags);
3036 
3037 	if (error) {
3038 		/* discinfo call failed, emulate for cd-rom/dvd-rom */
3039 		if (mmc_discinfo->mmc_profile == 0x08) /* CD-ROM */
3040 			return mmc_getdiscinfo_cdrom(periph, mmc_discinfo);
3041 		if (mmc_discinfo->mmc_profile == 0x10) /* DVD-ROM */
3042 			return mmc_getdiscinfo_dvdrom(periph, mmc_discinfo);
3043 		/* CD/DVD drive is violating specs */
3044 		error = EIO;
3045 		goto out;
3046 	}
3047 
3048 	/* call went OK */
3049 	mmc_discinfo->disc_state         =  di.disc_state & 3;
3050 	mmc_discinfo->last_session_state = (di.disc_state >> 2) & 3;
3051 	mmc_discinfo->bg_format_state    = (di.disc_state2 & 3);
3052 
3053 	lsb = di.num_sessions_lsb;
3054 	msb = di.num_sessions_msb;
3055 	mmc_discinfo->num_sessions = lsb | (msb << 8);
3056 
3057 	mmc_discinfo->first_track = di.first_track;
3058 	lsb = di.first_track_last_session_lsb;
3059 	msb = di.first_track_last_session_msb;
3060 	mmc_discinfo->first_track_last_session = lsb | (msb << 8);
3061 	lsb = di.last_track_last_session_lsb;
3062 	msb = di.last_track_last_session_msb;
3063 	mmc_discinfo->last_track_last_session  = lsb | (msb << 8);
3064 
3065 	mmc_discinfo->num_tracks = mmc_discinfo->last_track_last_session -
3066 		mmc_discinfo->first_track + 1;
3067 
3068 	/* set misc. flags and parameters from this disc info */
3069 	if (di.disc_state  &  16)
3070 		mmc_discinfo->mmc_cur |= MMC_CAP_BLANKABLE;
3071 
3072 	if (di.disc_state2 & 128) {
3073 		mmc_discinfo->disc_id = _4btol(di.discid);
3074 		mmc_discinfo->disc_flags |= MMC_DFLAGS_DISCIDVALID;
3075 	}
3076 	if (di.disc_state2 &  64) {
3077 		mmc_discinfo->disc_barcode = _8btol(di.disc_bar_code);
3078 		mmc_discinfo->disc_flags |= MMC_DFLAGS_BARCODEVALID;
3079 	}
3080 	if (di.disc_state2 &  32)
3081 		mmc_discinfo->disc_flags |= MMC_DFLAGS_UNRESTRICTED;
3082 
3083 	if (di.disc_state2 &  16) {
3084 		mmc_discinfo->application_code = di.application_code;
3085 		mmc_discinfo->disc_flags |= MMC_DFLAGS_APPCODEVALID;
3086 	}
3087 
3088 	/* done */
3089 
3090 out:
3091 	free(buffer, M_TEMP);
3092 	return error;
3093 }
3094 
3095 static int
3096 mmc_gettrackinfo_cdrom(struct scsipi_periph *periph,
3097 		       struct mmc_trackinfo *trackinfo)
3098 {
3099 	struct scsipi_read_toc            gtoc_cmd;
3100 	struct scsipi_toc_header         *toc_hdr;
3101 	struct scsipi_toc_rawtoc         *rawtoc;
3102 	uint32_t track_start, track_end, track_size;
3103 	uint32_t last_recorded, next_writable;
3104 	uint32_t lba, next_track_start, lead_out;
3105 	const uint32_t buffer_size = 4 * 1024;	/* worst case TOC estimate */
3106 	uint8_t *buffer;
3107 	uint8_t track_sessionnr, last_tracknr, sessionnr, adr, tno, point;
3108 	uint8_t tmin, tsec, tframe, pmin, psec, pframe;
3109 	int size, req_size;
3110 	int error, flags;
3111 
3112 	buffer = malloc(buffer_size, M_TEMP, M_WAITOK);
3113 
3114 	/*
3115 	 * Emulate read trackinfo for CD-ROM using the raw-TOC.
3116 	 *
3117 	 * Not all information is present and this presents a problem.  Track
3118 	 * starts are known for each track but other values are deducted.
3119 	 *
3120 	 * For a complete overview of `magic' values used here, see the
3121 	 * SCSI/ATAPI MMC documentation. Note that the `magic' values have no
3122 	 * names, they are specified as numbers.
3123 	 */
3124 
3125 	/* get raw toc to process, first header to check size */
3126 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK | XS_CTL_SILENT;
3127 	bzero(&gtoc_cmd, sizeof(gtoc_cmd));
3128 	gtoc_cmd.opcode      = READ_TOC;
3129 	gtoc_cmd.addr_mode   = CD_MSF;		/* not relevant     */
3130 	gtoc_cmd.resp_format = CD_TOC_RAW;	/* raw toc          */
3131 	gtoc_cmd.from_track  = 1;		/* first session    */
3132 	req_size = sizeof(*toc_hdr);
3133 	_lto2b(req_size, gtoc_cmd.data_len);
3134 
3135 	error = scsipi_command(periph,
3136 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
3137 		(void *)buffer,    req_size,
3138 		CDRETRIES, 30000, NULL, flags);
3139 	if (error)
3140 		goto out;
3141 	toc_hdr = (struct scsipi_toc_header *) buffer;
3142 	if (_2btol(toc_hdr->length) > buffer_size - 2) {
3143 #ifdef DIAGNOSTIC
3144 		printf("increase buffersize in mmc_readtrackinfo_cdrom\n");
3145 #endif
3146 		error = ENOBUFS;
3147 		goto out;
3148 	}
3149 
3150 	/* read in complete raw toc */
3151 	req_size = _2btol(toc_hdr->length);
3152 	_lto2b(req_size, gtoc_cmd.data_len);
3153 
3154 	error = scsipi_command(periph,
3155 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
3156 		(void *)buffer,    req_size,
3157 		CDRETRIES, 30000, NULL, flags);
3158 	if (error)
3159 		goto out;
3160 
3161 	toc_hdr = (struct scsipi_toc_header *) buffer;
3162 	rawtoc  = (struct scsipi_toc_rawtoc *) (buffer + 4);
3163 
3164 	track_start      = 0;
3165 	track_end        = 0;
3166 	track_size       = 0;
3167 	last_recorded    = 0;
3168 	next_writable    = 0;
3169 	flags            = 0;
3170 
3171 	last_tracknr     = 1;
3172 	next_track_start = 0;
3173 	track_sessionnr  = MAXTRACK;	/* by definition */
3174 	lead_out         = 0;
3175 
3176 	size = req_size - sizeof(struct scsipi_toc_header) + 1;
3177 	while (size > 0) {
3178 		/* get track start and session end */
3179 		tno       = rawtoc->tno;
3180 		sessionnr = rawtoc->sessionnr;
3181 		adr       = rawtoc->adrcontrol >> 4;
3182 		point     = rawtoc->point;
3183 		tmin      = rawtoc->min;
3184 		tsec      = rawtoc->sec;
3185 		tframe    = rawtoc->frame;
3186 		pmin      = rawtoc->pmin;
3187 		psec      = rawtoc->psec;
3188 		pframe    = rawtoc->pframe;
3189 
3190 		if (tno == 0 && sessionnr && adr == 1) {
3191 			lba = hmsf2lba(0, pmin, psec, pframe);
3192 			if (point == trackinfo->tracknr) {
3193 				track_start = lba;
3194 				track_sessionnr = sessionnr;
3195 			}
3196 			if (point == trackinfo->tracknr + 1) {
3197 				/* estimate size */
3198 				track_size = lba - track_start;
3199 				next_track_start = lba;
3200 			}
3201 			if (point == 0xa2) {
3202 				lead_out = lba;
3203 			}
3204 			if (point <= 0x63) {
3205 				/* CD's ok, DVD are glued */
3206 				last_tracknr = point;
3207 			}
3208 			if (sessionnr == track_sessionnr) {
3209 				last_recorded = lead_out;
3210 			}
3211 		}
3212 		if (tno == 0 && sessionnr && adr == 5) {
3213 			lba = hmsf2lba(0, tmin, tsec, tframe);
3214 			if (sessionnr == track_sessionnr) {
3215 				next_writable = lba;
3216 			}
3217 		}
3218 
3219 		rawtoc++;
3220 		size -= sizeof(struct scsipi_toc_rawtoc);
3221 	}
3222 
3223 	/* process found values; some voodoo */
3224 	/* if no tracksize tracknr is the last of the disc */
3225 	if ((track_size == 0) && last_recorded) {
3226 		track_size = last_recorded - track_start;
3227 	}
3228 	/* if last_recorded < tracksize, tracksize is overestimated */
3229 	if (last_recorded) {
3230 		if (last_recorded - track_start <= track_size) {
3231 			track_size = last_recorded - track_start;
3232 			flags |= MMC_TRACKINFO_LRA_VALID;
3233 		}
3234 	}
3235 	/* check if its a the last track of the sector */
3236 	if (next_writable) {
3237 		if (next_track_start > next_writable)
3238 			flags |= MMC_TRACKINFO_NWA_VALID;
3239 	}
3240 
3241 	/* no flag set -> no values */
3242 	if ((flags & MMC_TRACKINFO_LRA_VALID) == 0)
3243 		last_recorded = 0;
3244 	if ((flags & MMC_TRACKINFO_NWA_VALID) == 0)
3245 		next_writable = 0;
3246 
3247 	/* fill in */
3248 	/* trackinfo->tracknr preserved */
3249 	trackinfo->sessionnr  = track_sessionnr;
3250 	trackinfo->track_mode = 7;	/* data, incremental  */
3251 	trackinfo->data_mode  = 8;	/* 2048 bytes mode1   */
3252 
3253 	trackinfo->flags = flags;
3254 	trackinfo->track_start   = track_start;
3255 	trackinfo->next_writable = next_writable;
3256 	trackinfo->free_blocks   = 0;
3257 	trackinfo->packet_size   = 1;
3258 	trackinfo->track_size    = track_size;
3259 	trackinfo->last_recorded = last_recorded;
3260 
3261 out:
3262 	free(buffer, M_TEMP);
3263 	return error;
3264 
3265 }
3266 
3267 static int
3268 mmc_gettrackinfo_dvdrom(struct scsipi_periph *periph,
3269 			struct mmc_trackinfo *trackinfo)
3270 {
3271 	struct scsipi_read_toc            gtoc_cmd;
3272 	struct scsipi_toc_header         *toc_hdr;
3273 	struct scsipi_toc_formatted      *toc;
3274 	uint32_t tracknr, track_start, track_size;
3275 	uint32_t lba, lead_out;
3276 	const uint32_t buffer_size = 4 * 1024;	/* worst case TOC estimate */
3277 	uint8_t *buffer;
3278 	uint8_t last_tracknr;
3279 	int size, req_size;
3280 	int error, flags;
3281 
3282 
3283 	buffer = malloc(buffer_size, M_TEMP, M_WAITOK);
3284 	/*
3285 	 * Emulate read trackinfo for DVD-ROM. We can't use the raw-TOC as the
3286 	 * CD-ROM emulation uses since the specification tells us that no such
3287 	 * thing is defined for DVD's. The reason for this is due to the large
3288 	 * number of tracks and that would clash with the `magic' values. This
3289 	 * suxs.
3290 	 *
3291 	 * Not all information is present and this presents a problem.
3292 	 * Track starts are known for each track but other values are
3293 	 * deducted.
3294 	 */
3295 
3296 	/* get formatted toc to process, first header to check size */
3297 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK | XS_CTL_SILENT;
3298 	bzero(&gtoc_cmd, sizeof(gtoc_cmd));
3299 	gtoc_cmd.opcode      = READ_TOC;
3300 	gtoc_cmd.addr_mode   = 0;		/* lba's please     */
3301 	gtoc_cmd.resp_format = CD_TOC_FORM;	/* formatted toc    */
3302 	gtoc_cmd.from_track  = 1;		/* first track      */
3303 	req_size = sizeof(*toc_hdr);
3304 	_lto2b(req_size, gtoc_cmd.data_len);
3305 
3306 	error = scsipi_command(periph,
3307 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
3308 		(void *)buffer,    req_size,
3309 		CDRETRIES, 30000, NULL, flags);
3310 	if (error)
3311 		goto out;
3312 	toc_hdr = (struct scsipi_toc_header *) buffer;
3313 	if (_2btol(toc_hdr->length) > buffer_size - 2) {
3314 #ifdef DIAGNOSTIC
3315 		printf("incease buffersize in mmc_readtrackinfo_dvdrom\n");
3316 #endif
3317 		error = ENOBUFS;
3318 		goto out;
3319 	}
3320 
3321 	/* read in complete formatted toc */
3322 	req_size = _2btol(toc_hdr->length);
3323 	_lto2b(req_size, gtoc_cmd.data_len);
3324 
3325 	error = scsipi_command(periph,
3326 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
3327 		(void *)buffer,    req_size,
3328 		CDRETRIES, 30000, NULL, flags);
3329 	if (error)
3330 		goto out;
3331 
3332 	toc_hdr = (struct scsipi_toc_header *)     buffer;
3333 	toc     = (struct scsipi_toc_formatted *) (buffer + 4);
3334 
3335 	/* as in read disc info, all sessions are converted to tracks      */
3336 	/* track 1..  -> offsets, sizes can be (rougly) estimated (16 ECC) */
3337 	/* last track -> we got the size from the lead-out                 */
3338 
3339 	tracknr      = 0;
3340 	last_tracknr = toc_hdr->last;
3341 	track_start  = 0;
3342 	track_size   = 0;
3343 	lead_out     = 0;
3344 
3345 	size = req_size - sizeof(struct scsipi_toc_header) + 1;
3346 	while (size > 0) {
3347 		/* remember, DVD-ROM: tracknr == sessionnr */
3348 		lba     = _4btol(toc->msf_lba);
3349 		tracknr = toc->tracknr;
3350 		if (trackinfo->tracknr == tracknr) {
3351 			track_start = lba;
3352 		}
3353 		if (trackinfo->tracknr == tracknr+1) {
3354 			track_size  = lba - track_start;
3355 			track_size -= 16;	/* link block ? */
3356 		}
3357 		if (tracknr == 0xAA) {
3358 			lead_out = lba;
3359 		}
3360 		toc++;
3361 		size -= sizeof(struct scsipi_toc_formatted);
3362 	}
3363 	if (trackinfo->tracknr == last_tracknr) {
3364 		track_size = lead_out - track_start;
3365 	}
3366 
3367 	/* fill in */
3368 	/* trackinfo->tracknr preserved */
3369 	trackinfo->sessionnr  = trackinfo->tracknr;
3370 	trackinfo->track_mode = 0;	/* unknown */
3371 	trackinfo->data_mode  = 8;	/* 2048 bytes mode1   */
3372 
3373 	trackinfo->flags         = 0;
3374 	trackinfo->track_start   = track_start;
3375 	trackinfo->next_writable = 0;
3376 	trackinfo->free_blocks   = 0;
3377 	trackinfo->packet_size   = 16;	/* standard length 16 blocks ECC */
3378 	trackinfo->track_size    = track_size;
3379 	trackinfo->last_recorded = 0;
3380 
3381 out:
3382 	free(buffer, M_TEMP);
3383 	return error;
3384 }
3385 
3386 static int
3387 mmc_gettrackinfo(struct scsipi_periph *periph,
3388 		 struct mmc_trackinfo *trackinfo)
3389 {
3390 	struct scsipi_read_trackinfo      ti_cmd;
3391 	struct scsipi_read_trackinfo_data ti;
3392 	struct scsipi_get_configuration   gc_cmd;
3393 	struct scsipi_get_conf_data       gc;
3394 	int error, flags;
3395 	int mmc_profile;
3396 
3397 	/* set up SCSI call with track number from trackinfo.tracknr */
3398 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK | XS_CTL_SILENT;
3399 	memset(&ti_cmd, 0, sizeof(ti_cmd));
3400 	ti_cmd.opcode    = READ_TRACKINFO;
3401 	ti_cmd.addr_type = READ_TRACKINFO_ADDR_TRACK;
3402 	ti_cmd.data_len[1] = READ_TRACKINFO_RETURNSIZE;
3403 
3404 	/* trackinfo.tracknr contains number of tracks to query */
3405 	_lto4b(trackinfo->tracknr, ti_cmd.address);
3406 	error = scsipi_command(periph,
3407 		(void *)&ti_cmd, sizeof(ti_cmd),
3408 		(void *)&ti,     READ_TRACKINFO_RETURNSIZE,
3409 		CDRETRIES, 30000, NULL, flags);
3410 
3411 	if (error) {
3412 		/* trackinfo call failed, emulate for cd-rom/dvd-rom */
3413 		/* first determine mmc profile */
3414 		flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK;
3415 		memset(&gc_cmd, 0, sizeof(gc_cmd));
3416 		gc_cmd.opcode = GET_CONFIGURATION;
3417 		_lto2b(GET_CONF_NO_FEATURES_LEN, gc_cmd.data_len);
3418 
3419 		error = scsipi_command(periph,
3420 			(void *)&gc_cmd, sizeof(gc_cmd),
3421 			(void *)&gc,     GET_CONF_NO_FEATURES_LEN,
3422 			CDRETRIES, 30000, NULL, flags);
3423 		if (error)
3424 			return error;
3425 		mmc_profile = _2btol(gc.mmc_profile);
3426 
3427 		/* choose emulation */
3428 		if (mmc_profile == 0x08) /* CD-ROM */
3429 			return mmc_gettrackinfo_cdrom(periph, trackinfo);
3430 		if (mmc_profile == 0x10) /* DVD-ROM */
3431 			return mmc_gettrackinfo_dvdrom(periph, trackinfo);
3432 		/* CD/DVD drive is violating specs */
3433 		return EIO;
3434 	}
3435 
3436 	/* (re)initialise structure */
3437 	memset(trackinfo, 0, sizeof(struct mmc_trackinfo));
3438 
3439 	/* account for short returns screwing up track and session msb */
3440 	if ((ti.data_len[1] | (ti.data_len[0] << 8)) <= 32) {
3441 		ti.track_msb   = 0;
3442 		ti.session_msb = 0;
3443 	}
3444 
3445 	trackinfo->tracknr    = ti.track_lsb   | (ti.track_msb   << 8);
3446 	trackinfo->sessionnr  = ti.session_lsb | (ti.session_msb << 8);
3447 	trackinfo->track_mode = ti.track_info_1 & 0xf;
3448 	trackinfo->data_mode  = ti.track_info_2 & 0xf;
3449 
3450 	flags = 0;
3451 	if (ti.track_info_1 & 0x10)
3452 		flags |= MMC_TRACKINFO_COPY;
3453 	if (ti.track_info_1 & 0x20)
3454 		flags |= MMC_TRACKINFO_DAMAGED;
3455 	if (ti.track_info_2 & 0x10)
3456 		flags |= MMC_TRACKINFO_FIXED_PACKET;
3457 	if (ti.track_info_2 & 0x20)
3458 		flags |= MMC_TRACKINFO_INCREMENTAL;
3459 	if (ti.track_info_2 & 0x40)
3460 		flags |= MMC_TRACKINFO_BLANK;
3461 	if (ti.track_info_2 & 0x80)
3462 		flags |= MMC_TRACKINFO_RESERVED;
3463 	if (ti.data_valid   & 0x01)
3464 		flags |= MMC_TRACKINFO_NWA_VALID;
3465 	if (ti.data_valid   & 0x02)
3466 		flags |= MMC_TRACKINFO_LRA_VALID;
3467 
3468 	trackinfo->flags = flags;
3469 	trackinfo->track_start    = _4btol(ti.track_start);
3470 	trackinfo->next_writable  = _4btol(ti.next_writable);
3471 	trackinfo->free_blocks    = _4btol(ti.free_blocks);
3472 	trackinfo->packet_size    = _4btol(ti.packet_size);
3473 	trackinfo->track_size     = _4btol(ti.track_size);
3474 	trackinfo->last_recorded  = _4btol(ti.last_recorded);
3475 
3476 	return 0;
3477 }
3478