xref: /netbsd-src/sys/dev/scsipi/cd.c (revision cd22f25e6f6d1cc1f197fe8c5468a80f51d1c4e1)
1 /*	$NetBSD: cd.c,v 1.277 2008/05/02 16:06:38 reinoud 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.277 2008/05/02 16:06:38 reinoud 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 == 0x04) && (sense->ascq == 0x01)) {
1032 		/*
1033 		 * Sleep for 5 seconds to wait for the drive to spin up
1034 		 */
1035 
1036 		SC_DEBUG(periph, SCSIPI_DB1, ("Waiting 5 sec for CD "
1037 						"spinup\n"));
1038 		if (!callout_pending(&periph->periph_callout))
1039 			scsipi_periph_freeze(periph, 1);
1040 		callout_reset(&periph->periph_callout,
1041 		    5 * hz, scsipi_periph_timed_thaw, periph);
1042 		retval = ERESTART;
1043 	}
1044 
1045 	/*
1046 	 * If we got a "Unit not ready" (SKEY_NOT_READY) and "Logical Unit Not
1047 	 * Ready, Operation In Progress" (Sense code 0x04, 0x07),
1048 	 * then wait for the specified time
1049 	 */
1050 
1051 	if ((SSD_SENSE_KEY(sense->flags) == SKEY_NOT_READY) &&
1052 	    (sense->asc == 0x04) && (sense->ascq == 0x07)) {
1053 		/*
1054 		 * we could listen to the delay; but it looks like the skey
1055 		 * data is not always returned.
1056 		 */
1057 		/* cd_delay = _2btol(sense->sks.sks_bytes); */
1058 
1059 		/* wait for a half second and get going again */
1060 		if (!callout_pending(&periph->periph_callout))
1061 			scsipi_periph_freeze(periph, 1);
1062 		callout_reset(&periph->periph_callout,
1063 		    hz/2, scsipi_periph_timed_thaw, periph);
1064 		retval = ERESTART;
1065 	}
1066 
1067 	/*
1068 	 * If we got a "Unit not ready" (SKEY_NOT_READY) and "Long write in
1069 	 * progress" (Sense code 0x04, 0x08), then wait for the specified
1070 	 * time
1071 	 */
1072 
1073 	if ((SSD_SENSE_KEY(sense->flags) == SKEY_NOT_READY) &&
1074 	    (sense->asc == 0x04) && (sense->ascq == 0x08)) {
1075 		/*
1076 		 * long write in process; we could listen to the delay; but it
1077 		 * looks like the skey data is not always returned.
1078 		 */
1079 		/* cd_delay = _2btol(sense->sks.sks_bytes); */
1080 
1081 		/* wait for a half second and get going again */
1082 		if (!callout_pending(&periph->periph_callout))
1083 			scsipi_periph_freeze(periph, 1);
1084 		callout_reset(&periph->periph_callout,
1085 		    hz/2, scsipi_periph_timed_thaw, periph);
1086 		retval = ERESTART;
1087 	}
1088 
1089 	return (retval);
1090 }
1091 
1092 static void
1093 cdminphys(struct buf *bp)
1094 {
1095 	struct cd_softc *cd = device_lookup_private(&cd_cd, CDUNIT(bp->b_dev));
1096 	long xmax;
1097 
1098 	/*
1099 	 * If the device is ancient, we want to make sure that
1100 	 * the transfer fits into a 6-byte cdb.
1101 	 *
1102 	 * XXX Note that the SCSI-I spec says that 256-block transfers
1103 	 * are allowed in a 6-byte read/write, and are specified
1104 	 * by settng the "length" to 0.  However, we're conservative
1105 	 * here, allowing only 255-block transfers in case an
1106 	 * ancient device gets confused by length == 0.  A length of 0
1107 	 * in a 10-byte read/write actually means 0 blocks.
1108 	 */
1109 	if (cd->flags & CDF_ANCIENT) {
1110 		xmax = cd->sc_dk.dk_label->d_secsize * 0xff;
1111 
1112 		if (bp->b_bcount > xmax)
1113 			bp->b_bcount = xmax;
1114 	}
1115 
1116 	(*cd->sc_periph->periph_channel->chan_adapter->adapt_minphys)(bp);
1117 }
1118 
1119 static int
1120 cdread(dev_t dev, struct uio *uio, int ioflag)
1121 {
1122 	return (physio(cdstrategy, NULL, dev, B_READ, cdminphys, uio));
1123 }
1124 
1125 static int
1126 cdwrite(dev_t dev, struct uio *uio, int ioflag)
1127 {
1128 	return (physio(cdstrategy, NULL, dev, B_WRITE, cdminphys, uio));
1129 }
1130 
1131 #if 0	/* XXX Not used */
1132 /*
1133  * conversion between minute-seconde-frame and logical block address
1134  * addresses format
1135  */
1136 static void
1137 lba2msf(u_long lba, u_char *m, u_char *s, u_char *f)
1138 {
1139 	u_long tmp;
1140 
1141 	tmp = lba + CD_BLOCK_OFFSET;	/* offset of first logical frame */
1142 	tmp &= 0xffffff;		/* negative lbas use only 24 bits */
1143 	*m = tmp / (CD_SECS * CD_FRAMES);
1144 	tmp %= (CD_SECS * CD_FRAMES);
1145 	*s = tmp / CD_FRAMES;
1146 	*f = tmp % CD_FRAMES;
1147 }
1148 #endif /* XXX Not used */
1149 
1150 /*
1151  * Convert an hour:minute:second:frame address to a logical block adres. In
1152  * theory the number of secs/minute and number of frames/second could be
1153  * configured differently in the device  as could the block offset but in
1154  * practice these values are rock solid and most drives don't even allow
1155  * theses values to be changed.
1156  */
1157 static uint32_t
1158 hmsf2lba(uint8_t h, uint8_t m, uint8_t s, uint8_t f)
1159 {
1160 	return (((((uint32_t) h * 60 + m) * CD_SECS) + s) * CD_FRAMES + f)
1161 		- CD_BLOCK_OFFSET;
1162 }
1163 
1164 static int
1165 cdreadmsaddr(struct cd_softc *cd, struct cd_formatted_toc *toc, int *addr)
1166 {
1167 	struct scsipi_periph *periph = cd->sc_periph;
1168 	int error;
1169 	struct cd_toc_entry *cte;
1170 
1171 	error = cd_read_toc(cd, CD_TOC_FORM, 0, 0, toc,
1172 	    sizeof(struct ioc_toc_header) + sizeof(struct cd_toc_entry),
1173 	    XS_CTL_DATA_ONSTACK,
1174 	    0x40 /* control word for "get MS info" */);
1175 
1176 	if (error)
1177 		return (error);
1178 
1179 	cte = &toc->entries[0];
1180 	if (periph->periph_quirks & PQUIRK_LITTLETOC) {
1181 		cte->addr.lba = le32toh(cte->addr.lba);
1182 		toc->header.len = le16toh(toc->header.len);
1183 	} else {
1184 		cte->addr.lba = be32toh(cte->addr.lba);
1185 		toc->header.len = be16toh(toc->header.len);
1186 	}
1187 
1188 	*addr = (toc->header.len >= 10 && cte->track > 1) ?
1189 		cte->addr.lba : 0;
1190 	return 0;
1191 }
1192 
1193 /* synchronise caches code from sd.c, move to scsipi_ioctl.c ? */
1194 static int
1195 cdcachesync(struct scsipi_periph *periph, int flags) {
1196 	struct scsi_synchronize_cache_10 cmd;
1197 
1198 	/*
1199 	 * Issue a SYNCHRONIZE CACHE. MMC devices have to issue with address 0
1200 	 * and length 0 as it can't synchronise parts of the disc per spec.
1201 	 * We ignore ILLEGAL REQUEST in the event that the command is not
1202 	 * supported by the device, and poll for completion so that we know
1203 	 * that the cache has actually been flushed.
1204 	 *
1205 	 * XXX should we handle the PQUIRK_NOSYNCCACHE ?
1206 	 */
1207 
1208 	memset(&cmd, 0, sizeof(cmd));
1209 	cmd.opcode = SCSI_SYNCHRONIZE_CACHE_10;
1210 
1211 	return (scsipi_command(periph, (void *)&cmd, sizeof(cmd), 0, 0,
1212 	    CDRETRIES, 30000, NULL, flags | XS_CTL_IGNORE_ILLEGAL_REQUEST));
1213 }
1214 
1215 static int
1216 do_cdioreadentries(struct cd_softc *cd, struct ioc_read_toc_entry *te,
1217     struct cd_formatted_toc *toc)
1218 {
1219 	/* READ TOC format 0 command, entries */
1220 	struct ioc_toc_header *th;
1221 	struct cd_toc_entry *cte;
1222 	u_int len = te->data_len;
1223 	int ntracks;
1224 	int error;
1225 
1226 	th = &toc->header;
1227 
1228 	if (len > sizeof(toc->entries) ||
1229 	    len < sizeof(toc->entries[0]))
1230 		return (EINVAL);
1231 	error = cd_read_toc(cd, CD_TOC_FORM, te->address_format,
1232 	    te->starting_track, toc,
1233 	    sizeof(toc->header) + len,
1234 	    XS_CTL_DATA_ONSTACK, 0);
1235 	if (error)
1236 		return (error);
1237 	if (te->address_format == CD_LBA_FORMAT)
1238 		for (ntracks =
1239 		    th->ending_track - th->starting_track + 1;
1240 		    ntracks >= 0; ntracks--) {
1241 			cte = &toc->entries[ntracks];
1242 			cte->addr_type = CD_LBA_FORMAT;
1243 			if (cd->sc_periph->periph_quirks & PQUIRK_LITTLETOC)
1244 				cte->addr.lba = le32toh(cte->addr.lba);
1245 			else
1246 				cte->addr.lba = be32toh(cte->addr.lba);
1247 		}
1248 	if (cd->sc_periph->periph_quirks & PQUIRK_LITTLETOC)
1249 		th->len = le16toh(th->len);
1250 	else
1251 		th->len = be16toh(th->len);
1252 	return 0;
1253 }
1254 
1255 /*
1256  * Perform special action on behalf of the user.
1257  * Knows about the internals of this device
1258  */
1259 static int
1260 cdioctl(dev_t dev, u_long cmd, void *addr, int flag, struct lwp *l)
1261 {
1262 	struct cd_softc *cd = device_lookup_private(&cd_cd, CDUNIT(dev));
1263 	struct scsipi_periph *periph = cd->sc_periph;
1264 	struct cd_formatted_toc toc;
1265 	int part = CDPART(dev);
1266 	int error = 0;
1267 	int s;
1268 #ifdef __HAVE_OLD_DISKLABEL
1269 	struct disklabel *newlabel = NULL;
1270 #endif
1271 
1272 	SC_DEBUG(cd->sc_periph, SCSIPI_DB2, ("cdioctl 0x%lx ", cmd));
1273 
1274 	/*
1275 	 * If the device is not valid, some IOCTLs can still be
1276 	 * handled on the raw partition. Check this here.
1277 	 */
1278 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
1279 		switch (cmd) {
1280 		case DIOCWLABEL:
1281 		case DIOCLOCK:
1282 		case ODIOCEJECT:
1283 		case DIOCEJECT:
1284 		case DIOCCACHESYNC:
1285 		case SCIOCIDENTIFY:
1286 		case OSCIOCIDENTIFY:
1287 		case SCIOCCOMMAND:
1288 		case SCIOCDEBUG:
1289 		case CDIOCGETVOL:
1290 		case CDIOCSETVOL:
1291 		case CDIOCSETMONO:
1292 		case CDIOCSETSTEREO:
1293 		case CDIOCSETMUTE:
1294 		case CDIOCSETLEFT:
1295 		case CDIOCSETRIGHT:
1296 		case CDIOCCLOSE:
1297 		case CDIOCEJECT:
1298 		case CDIOCALLOW:
1299 		case CDIOCPREVENT:
1300 		case CDIOCSETDEBUG:
1301 		case CDIOCCLRDEBUG:
1302 		case CDIOCRESET:
1303 		case SCIOCRESET:
1304 		case CDIOCLOADUNLOAD:
1305 		case DVD_AUTH:
1306 		case DVD_READ_STRUCT:
1307 		case DIOCGSTRATEGY:
1308 		case DIOCSSTRATEGY:
1309 			if (part == RAW_PART)
1310 				break;
1311 		/* FALLTHROUGH */
1312 		default:
1313 			if ((periph->periph_flags & PERIPH_OPEN) == 0)
1314 				return (ENODEV);
1315 			else
1316 				return (EIO);
1317 		}
1318 	}
1319 
1320 	switch (cmd) {
1321 	case DIOCGDINFO:
1322 		*(struct disklabel *)addr = *(cd->sc_dk.dk_label);
1323 		return (0);
1324 #ifdef __HAVE_OLD_DISKLABEL
1325 	case ODIOCGDINFO:
1326 		newlabel = malloc(sizeof (*newlabel), M_TEMP, M_WAITOK);
1327 		if (newlabel == NULL)
1328 			return (EIO);
1329 		memcpy(newlabel, cd->sc_dk.dk_label, sizeof (*newlabel));
1330 		if (newlabel->d_npartitions > OLDMAXPARTITIONS)
1331 			error = ENOTTY;
1332 		else
1333 			memcpy(addr, newlabel, sizeof (struct olddisklabel));
1334 		free(newlabel, M_TEMP);
1335 		return error;
1336 #endif
1337 
1338 	case DIOCGPART:
1339 		((struct partinfo *)addr)->disklab = cd->sc_dk.dk_label;
1340 		((struct partinfo *)addr)->part =
1341 		    &cd->sc_dk.dk_label->d_partitions[part];
1342 		return (0);
1343 
1344 	case DIOCWDINFO:
1345 	case DIOCSDINFO:
1346 #ifdef __HAVE_OLD_DISKLABEL
1347 	case ODIOCWDINFO:
1348 	case ODIOCSDINFO:
1349 #endif
1350 	{
1351 		struct disklabel *lp;
1352 
1353 		if ((flag & FWRITE) == 0)
1354 			return (EBADF);
1355 
1356 #ifdef __HAVE_OLD_DISKLABEL
1357 		if (cmd == ODIOCSDINFO || cmd == ODIOCWDINFO) {
1358 			newlabel = malloc(sizeof (*newlabel), M_TEMP, M_WAITOK);
1359 			if (newlabel == NULL)
1360 				return (EIO);
1361 			memset(newlabel, 0, sizeof newlabel);
1362 			memcpy(newlabel, addr, sizeof (struct olddisklabel));
1363 			lp = newlabel;
1364 		} else
1365 #endif
1366 		lp = addr;
1367 
1368 		mutex_enter(&cd->sc_lock);
1369 		cd->flags |= CDF_LABELLING;
1370 
1371 		error = setdisklabel(cd->sc_dk.dk_label,
1372 		    lp, /*cd->sc_dk.dk_openmask : */0,
1373 		    cd->sc_dk.dk_cpulabel);
1374 		if (error == 0) {
1375 			/* XXX ? */
1376 		}
1377 
1378 		cd->flags &= ~CDF_LABELLING;
1379 		mutex_exit(&cd->sc_lock);
1380 #ifdef __HAVE_OLD_DISKLABEL
1381 		if (newlabel != NULL)
1382 			free(newlabel, M_TEMP);
1383 #endif
1384 		return (error);
1385 	}
1386 
1387 	case DIOCWLABEL:
1388 		return (EBADF);
1389 
1390 	case DIOCGDEFLABEL:
1391 		cdgetdefaultlabel(cd, &toc, addr);
1392 		return (0);
1393 
1394 #ifdef __HAVE_OLD_DISKLABEL
1395 	case ODIOCGDEFLABEL:
1396 		newlabel = malloc(sizeof (*newlabel), M_TEMP, M_WAITOK);
1397 		if (newlabel == NULL)
1398 			return (EIO);
1399 		cdgetdefaultlabel(cd, &toc, newlabel);
1400 		if (newlabel->d_npartitions > OLDMAXPARTITIONS)
1401 			error = ENOTTY;
1402 		else
1403 			memcpy(addr, newlabel, sizeof (struct olddisklabel));
1404 		free(newlabel, M_TEMP);
1405 		return error;
1406 #endif
1407 
1408 	case CDIOCPLAYTRACKS: {
1409 		/* PLAY_MSF command */
1410 		struct ioc_play_track *args = addr;
1411 
1412 		if ((error = cd_set_pa_immed(cd, 0)) != 0)
1413 			return (error);
1414 		return (cd_play_tracks(cd, &toc, args->start_track,
1415 		    args->start_index, args->end_track, args->end_index));
1416 	}
1417 	case CDIOCPLAYMSF: {
1418 		/* PLAY_MSF command */
1419 		struct ioc_play_msf *args = addr;
1420 
1421 		if ((error = cd_set_pa_immed(cd, 0)) != 0)
1422 			return (error);
1423 		return (cd_play_msf(cd, args->start_m, args->start_s,
1424 		    args->start_f, args->end_m, args->end_s, args->end_f));
1425 	}
1426 	case CDIOCPLAYBLOCKS: {
1427 		/* PLAY command */
1428 		struct ioc_play_blocks *args = addr;
1429 
1430 		if ((error = cd_set_pa_immed(cd, 0)) != 0)
1431 			return (error);
1432 		return (cd_play(cd, args->blk, args->len));
1433 	}
1434 	case CDIOCREADSUBCHANNEL: {
1435 		/* READ_SUBCHANNEL command */
1436 		struct ioc_read_subchannel *args = addr;
1437 		struct cd_sub_channel_info data;
1438 		u_int len = args->data_len;
1439 
1440 		if (len > sizeof(data) ||
1441 		    len < sizeof(struct cd_sub_channel_header))
1442 			return (EINVAL);
1443 		error = cd_read_subchannel(cd, args->address_format,
1444 		    args->data_format, args->track, &data, len,
1445 		    XS_CTL_DATA_ONSTACK);
1446 		if (error)
1447 			return (error);
1448 		len = min(len, _2btol(data.header.data_len) +
1449 		    sizeof(struct cd_sub_channel_header));
1450 		return (copyout(&data, args->data, len));
1451 	}
1452 	case CDIOCREADSUBCHANNEL_BUF: {
1453 		/* As CDIOCREADSUBCHANNEL, but without a 2nd buffer area */
1454 		struct ioc_read_subchannel_buf *args = addr;
1455 		if (args->req.data_len != sizeof args->info)
1456 			return EINVAL;
1457 		return cd_read_subchannel(cd, args->req.address_format,
1458 		    args->req.data_format, args->req.track, &args->info,
1459 		    sizeof args->info, XS_CTL_DATA_ONSTACK);
1460 	}
1461 	case CDIOREADTOCHEADER: {
1462 		/* READ TOC format 0 command, static header */
1463 		if ((error = cd_read_toc(cd, CD_TOC_FORM, 0, 0,
1464 		    &toc, sizeof(toc.header),
1465 		    XS_CTL_DATA_ONSTACK, 0)) != 0)
1466 			return (error);
1467 		if (cd->sc_periph->periph_quirks & PQUIRK_LITTLETOC)
1468 			toc.header.len = le16toh(toc.header.len);
1469 		else
1470 			toc.header.len = be16toh(toc.header.len);
1471 		memcpy(addr, &toc.header, sizeof(toc.header));
1472 		return (0);
1473 	}
1474 	case CDIOREADTOCENTRYS: {
1475 		struct ioc_read_toc_entry *te = addr;
1476 		error = do_cdioreadentries(cd, te, &toc);
1477 		if (error != 0)
1478 			return error;
1479 		return copyout(toc.entries, te->data, min(te->data_len,
1480 		    toc.header.len - (sizeof(toc.header.starting_track)
1481 			+ sizeof(toc.header.ending_track))));
1482 	}
1483 	case CDIOREADTOCENTRIES_BUF: {
1484 		struct ioc_read_toc_entry_buf *te = addr;
1485 		error = do_cdioreadentries(cd, &te->req, &toc);
1486 		if (error != 0)
1487 			return error;
1488 		memcpy(te->entry, toc.entries, min(te->req.data_len,
1489 		    toc.header.len - (sizeof(toc.header.starting_track)
1490 			+ sizeof(toc.header.ending_track))));
1491 		return 0;
1492 	}
1493 	case CDIOREADMSADDR: {
1494 		/* READ TOC format 0 command, length of first track only */
1495 		int sessno = *(int*)addr;
1496 
1497 		if (sessno != 0)
1498 			return (EINVAL);
1499 
1500 		return (cdreadmsaddr(cd, &toc, addr));
1501 	}
1502 	case CDIOCSETPATCH: {
1503 		struct ioc_patch *arg = addr;
1504 
1505 		return (cd_setchan(cd, arg->patch[0], arg->patch[1],
1506 		    arg->patch[2], arg->patch[3], 0));
1507 	}
1508 	case CDIOCGETVOL: {
1509 		/* MODE SENSE command (AUDIO page) */
1510 		struct ioc_vol *arg = addr;
1511 
1512 		return (cd_getvol(cd, arg, 0));
1513 	}
1514 	case CDIOCSETVOL: {
1515 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1516 		struct ioc_vol *arg = addr;
1517 
1518 		return (cd_setvol(cd, arg, 0));
1519 	}
1520 	case CDIOCSETMONO:
1521 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1522 		return (cd_setchan(cd, BOTH_CHANNEL, BOTH_CHANNEL,
1523 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1524 
1525 	case CDIOCSETSTEREO:
1526 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1527 		return (cd_setchan(cd, LEFT_CHANNEL, RIGHT_CHANNEL,
1528 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1529 
1530 	case CDIOCSETMUTE:
1531 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1532 		return (cd_setchan(cd, MUTE_CHANNEL, MUTE_CHANNEL,
1533 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1534 
1535 	case CDIOCSETLEFT:
1536 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1537 		return (cd_setchan(cd, LEFT_CHANNEL, LEFT_CHANNEL,
1538 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1539 
1540 	case CDIOCSETRIGHT:
1541 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1542 		return (cd_setchan(cd, RIGHT_CHANNEL, RIGHT_CHANNEL,
1543 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1544 
1545 	case CDIOCRESUME:
1546 		/* PAUSE command */
1547 		return (cd_pause(cd, PA_RESUME));
1548 	case CDIOCPAUSE:
1549 		/* PAUSE command */
1550 		return (cd_pause(cd, PA_PAUSE));
1551 	case CDIOCSTART:
1552 		return (scsipi_start(periph, SSS_START, 0));
1553 	case CDIOCSTOP:
1554 		return (scsipi_start(periph, SSS_STOP, 0));
1555 	case CDIOCCLOSE:
1556 		return (scsipi_start(periph, SSS_START|SSS_LOEJ,
1557 		    XS_CTL_IGNORE_NOT_READY | XS_CTL_IGNORE_MEDIA_CHANGE));
1558 	case DIOCEJECT:
1559 		if (*(int *)addr == 0) {
1560 			/*
1561 			 * Don't force eject: check that we are the only
1562 			 * partition open. If so, unlock it.
1563 			 */
1564 			if ((cd->sc_dk.dk_openmask & ~(1 << part)) == 0 &&
1565 			    cd->sc_dk.dk_bopenmask + cd->sc_dk.dk_copenmask ==
1566 			    cd->sc_dk.dk_openmask) {
1567 				error = scsipi_prevent(periph, SPAMR_ALLOW,
1568 				    XS_CTL_IGNORE_NOT_READY);
1569 				if (error)
1570 					return (error);
1571 			} else {
1572 				return (EBUSY);
1573 			}
1574 		}
1575 		/* FALLTHROUGH */
1576 	case CDIOCEJECT: /* FALLTHROUGH */
1577 	case ODIOCEJECT:
1578 		return (scsipi_start(periph, SSS_STOP|SSS_LOEJ, 0));
1579 	case DIOCCACHESYNC:
1580 		/* SYNCHRONISE CACHES command */
1581 		return (cdcachesync(periph, 0));
1582 	case CDIOCALLOW:
1583 		return (scsipi_prevent(periph, SPAMR_ALLOW, 0));
1584 	case CDIOCPREVENT:
1585 		return (scsipi_prevent(periph, SPAMR_PREVENT_DT, 0));
1586 	case DIOCLOCK:
1587 		return (scsipi_prevent(periph,
1588 		    (*(int *)addr) ? SPAMR_PREVENT_DT : SPAMR_ALLOW, 0));
1589 	case CDIOCSETDEBUG:
1590 		cd->sc_periph->periph_dbflags |= (SCSIPI_DB1 | SCSIPI_DB2);
1591 		return (0);
1592 	case CDIOCCLRDEBUG:
1593 		cd->sc_periph->periph_dbflags &= ~(SCSIPI_DB1 | SCSIPI_DB2);
1594 		return (0);
1595 	case CDIOCRESET:
1596 	case SCIOCRESET:
1597 		return (cd_reset(cd));
1598 	case CDIOCLOADUNLOAD:
1599 		/* LOAD_UNLOAD command */
1600 		return (cd_load_unload(cd, addr));
1601 	case DVD_AUTH:
1602 		/* GPCMD_REPORT_KEY or GPCMD_SEND_KEY command */
1603 		return (dvd_auth(cd, addr));
1604 	case DVD_READ_STRUCT:
1605 		/* GPCMD_READ_DVD_STRUCTURE command */
1606 		return (dvd_read_struct(cd, addr));
1607 	case MMCGETDISCINFO:
1608 		/*
1609 		 * GET_CONFIGURATION, READ_DISCINFO, READ_TRACKINFO,
1610 		 * (READ_TOCf2, READ_CD_CAPACITY and GET_CONFIGURATION) commands
1611 		 */
1612 		return mmc_getdiscinfo(periph, (struct mmc_discinfo *) addr);
1613 	case MMCGETTRACKINFO:
1614 		/* READ TOCf2, READ_CD_CAPACITY and READ_TRACKINFO commands */
1615 		return mmc_gettrackinfo(periph, (struct mmc_trackinfo *) addr);
1616 	case DIOCGSTRATEGY:
1617 	    {
1618 		struct disk_strategy *dks = addr;
1619 
1620 		s = splbio();
1621 		strlcpy(dks->dks_name, bufq_getstrategyname(cd->buf_queue),
1622 		    sizeof(dks->dks_name));
1623 		splx(s);
1624 		dks->dks_paramlen = 0;
1625 
1626 		return 0;
1627 	    }
1628 	case DIOCSSTRATEGY:
1629 	    {
1630 		struct disk_strategy *dks = addr;
1631 		struct bufq_state *new;
1632 		struct bufq_state *old;
1633 
1634 		if ((flag & FWRITE) == 0) {
1635 			return EBADF;
1636 		}
1637 		if (dks->dks_param != NULL) {
1638 			return EINVAL;
1639 		}
1640 		dks->dks_name[sizeof(dks->dks_name) - 1] = 0; /* ensure term */
1641 		error = bufq_alloc(&new, dks->dks_name,
1642 		    BUFQ_EXACT|BUFQ_SORT_RAWBLOCK);
1643 		if (error) {
1644 			return error;
1645 		}
1646 		s = splbio();
1647 		old = cd->buf_queue;
1648 		bufq_move(new, old);
1649 		cd->buf_queue = new;
1650 		splx(s);
1651 		bufq_free(old);
1652 
1653 		return 0;
1654 	    }
1655 	default:
1656 		if (part != RAW_PART)
1657 			return (ENOTTY);
1658 		return (scsipi_do_ioctl(periph, dev, cmd, addr, flag, l));
1659 	}
1660 
1661 #ifdef DIAGNOSTIC
1662 	panic("cdioctl: impossible");
1663 #endif
1664 }
1665 
1666 static void
1667 cdgetdefaultlabel(struct cd_softc *cd, struct cd_formatted_toc *toc,
1668     struct disklabel *lp)
1669 {
1670 	int lastsession;
1671 
1672 	memset(lp, 0, sizeof(struct disklabel));
1673 
1674 	lp->d_secsize = cd->params.blksize;
1675 	lp->d_ntracks = 1;
1676 	lp->d_nsectors = 100;
1677 	lp->d_ncylinders = (cd->params.disksize / 100) + 1;
1678 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
1679 
1680 	switch (scsipi_periph_bustype(cd->sc_periph)) {
1681 	case SCSIPI_BUSTYPE_SCSI:
1682 		lp->d_type = DTYPE_SCSI;
1683 		break;
1684 	case SCSIPI_BUSTYPE_ATAPI:
1685 		lp->d_type = DTYPE_ATAPI;
1686 		break;
1687 	}
1688 	/*
1689 	 * XXX
1690 	 * We could probe the mode pages to figure out what kind of disc it is.
1691 	 * Is this worthwhile?
1692 	 */
1693 	strncpy(lp->d_typename, "mydisc", 16);
1694 	strncpy(lp->d_packname, "fictitious", 16);
1695 	lp->d_secperunit = cd->params.disksize;
1696 	lp->d_rpm = 300;
1697 	lp->d_interleave = 1;
1698 	lp->d_flags = D_REMOVABLE;
1699 
1700 	if (cdreadmsaddr(cd, toc, &lastsession) != 0)
1701 		lastsession = 0;
1702 
1703 	lp->d_partitions[0].p_offset = 0;
1704 	lp->d_partitions[0].p_size = lp->d_secperunit;
1705 	lp->d_partitions[0].p_cdsession = lastsession;
1706 	lp->d_partitions[0].p_fstype = FS_ISO9660;
1707 	lp->d_partitions[RAW_PART].p_offset = 0;
1708 	lp->d_partitions[RAW_PART].p_size = lp->d_secperunit;
1709 	lp->d_partitions[RAW_PART].p_fstype = FS_ISO9660;
1710 	lp->d_npartitions = RAW_PART + 1;
1711 
1712 	lp->d_magic = DISKMAGIC;
1713 	lp->d_magic2 = DISKMAGIC;
1714 	lp->d_checksum = dkcksum(lp);
1715 }
1716 
1717 /*
1718  * Load the label information on the named device
1719  * Actually fabricate a disklabel
1720  *
1721  * EVENTUALLY take information about different
1722  * data tracks from the TOC and put it in the disklabel
1723  */
1724 static void
1725 cdgetdisklabel(struct cd_softc *cd)
1726 {
1727 	struct disklabel *lp = cd->sc_dk.dk_label;
1728 	struct cd_formatted_toc toc;
1729 	const char *errstring;
1730 
1731 	memset(cd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
1732 
1733 	cdgetdefaultlabel(cd, &toc, lp);
1734 
1735 	/*
1736 	 * Call the generic disklabel extraction routine
1737 	 */
1738 	errstring = readdisklabel(MAKECDDEV(0, device_unit(cd->sc_dev),
1739 	    RAW_PART), cdstrategy, lp, cd->sc_dk.dk_cpulabel);
1740 
1741 	/* if all went OK, we are passed a NULL error string */
1742 	if (errstring == NULL)
1743 		return;
1744 
1745 	/* Reset to default label -- after printing error and the warning */
1746 	aprint_error_dev(cd->sc_dev, "%s\n", errstring);
1747 	memset(cd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
1748 	cdgetdefaultlabel(cd, &toc, lp);
1749 }
1750 
1751 /*
1752  * Reading a discs total capacity is aparently a very difficult issue for the
1753  * SCSI standardisation group. Every disc type seems to have its own
1754  * (re)invented size request method and modifiers. The failsafe way of
1755  * determining the total (max) capacity i.e. not the recorded capacity but the
1756  * total maximum capacity is to request the info on the last track and
1757  * calucate the total size.
1758  *
1759  * For ROM drives, we go for the CD recorded capacity. For recordable devices
1760  * we count.
1761  */
1762 static int
1763 read_cd_capacity(struct scsipi_periph *periph, u_int *blksize, u_long *size)
1764 {
1765 	struct scsipi_read_cd_capacity    cap_cmd;
1766 	struct scsipi_read_cd_cap_data    cap;
1767 	struct scsipi_read_discinfo       di_cmd;
1768 	struct scsipi_read_discinfo_data  di;
1769 	struct scsipi_read_trackinfo      ti_cmd;
1770 	struct scsipi_read_trackinfo_data ti;
1771 	uint32_t track_start, track_size;
1772 	int error, flags, msb, lsb, last_track;
1773 
1774 	/* if the device doesn't grog capacity, return the dummies */
1775 	if (periph->periph_quirks & PQUIRK_NOCAPACITY)
1776 		return 0;
1777 
1778 	/* first try read CD capacity for blksize and recorded size */
1779 	/* issue the cd capacity request */
1780 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK;
1781 	memset(&cap_cmd, 0, sizeof(cap_cmd));
1782 	cap_cmd.opcode = READ_CD_CAPACITY;
1783 
1784 	error = scsipi_command(periph,
1785 	    (void *) &cap_cmd, sizeof(cap_cmd),
1786 	    (void *) &cap,     sizeof(cap),
1787 	    CDRETRIES, 30000, NULL, flags);
1788 	if (error)
1789 		return error;
1790 
1791 	/* retrieve values and sanity check them */
1792 	*blksize = _4btol(cap.length);
1793 	*size    = _4btol(cap.addr);
1794 
1795 	/* blksize is 2048 for CD, but some drives give gibberish */
1796 	if ((*blksize < 512) || ((*blksize & 511) != 0))
1797 		*blksize = 2048;	/* some drives lie ! */
1798 
1799 	/* recordables have READ_DISCINFO implemented */
1800 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK | XS_CTL_SILENT;
1801 	memset(&di_cmd, 0, sizeof(di_cmd));
1802 	di_cmd.opcode = READ_DISCINFO;
1803 	_lto2b(READ_DISCINFO_BIGSIZE, di_cmd.data_len);
1804 
1805 	error = scsipi_command(periph,
1806 	    (void *) &di_cmd,  sizeof(di_cmd),
1807 	    (void *) &di,      READ_DISCINFO_BIGSIZE,
1808 	    CDRETRIES, 30000, NULL, flags);
1809 	if (error == 0) {
1810 		msb = di.last_track_last_session_msb;
1811 		lsb = di.last_track_last_session_lsb;
1812 		last_track = (msb << 8) | lsb;
1813 
1814 		/* request info on last track */
1815 		memset(&ti_cmd, 0, sizeof(ti_cmd));
1816 		ti_cmd.opcode = READ_TRACKINFO;
1817 		ti_cmd.addr_type = 1;			/* on tracknr */
1818 		_lto4b(last_track, ti_cmd.address);	/* tracknr    */
1819 		_lto2b(sizeof(ti), ti_cmd.data_len);
1820 
1821 		error = scsipi_command(periph,
1822 		    (void *) &ti_cmd,  sizeof(ti_cmd),
1823 		    (void *) &ti,      sizeof(ti),
1824 		    CDRETRIES, 30000, NULL, flags);
1825 		if (error == 0) {
1826 			track_start = _4btol(ti.track_start);
1827 			track_size  = _4btol(ti.track_size);
1828 
1829 			/* overwrite only with a sane value */
1830 			if (track_start + track_size >= 100)
1831 				*size = track_start + track_size;
1832 		}
1833 	}
1834 
1835 	/* sanity check for size */
1836 	if (*size < 100)
1837 		*size = 400000;
1838 
1839 	return 0;
1840 }
1841 
1842 /*
1843  * Find out from the device what it's capacity is
1844  */
1845 static u_long
1846 cd_size(struct cd_softc *cd, int flags)
1847 {
1848 	u_int blksize;
1849 	u_long size;
1850 	int error;
1851 
1852 	/* set up fake values */
1853 	blksize = 2048;
1854 	size    = 400000;
1855 
1856 	/* if this function bounces with an error return fake value */
1857 	error = read_cd_capacity(cd->sc_periph, &blksize, &size);
1858 	if (error)
1859 		return size;
1860 
1861 	if (blksize != 2048) {
1862 		if (cd_setblksize(cd) == 0)
1863 			blksize = 2048;
1864 	}
1865 	cd->params.blksize     = blksize;
1866 	cd->params.disksize    = size;
1867 	cd->params.disksize512 = ((u_int64_t)cd->params.disksize * blksize) / DEV_BSIZE;
1868 
1869 	SC_DEBUG(cd->sc_periph, SCSIPI_DB2,
1870 	    ("cd_size: %u %lu\n", blksize, size));
1871 
1872 	return size;
1873 }
1874 
1875 /*
1876  * Get scsi driver to send a "start playing" command
1877  */
1878 static int
1879 cd_play(struct cd_softc *cd, int blkno, int nblks)
1880 {
1881 	struct scsipi_play cmd;
1882 
1883 	memset(&cmd, 0, sizeof(cmd));
1884 	cmd.opcode = PLAY;
1885 	_lto4b(blkno, cmd.blk_addr);
1886 	_lto2b(nblks, cmd.xfer_len);
1887 
1888 	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
1889 	    CDRETRIES, 30000, NULL, 0));
1890 }
1891 
1892 /*
1893  * Get scsi driver to send a "start playing" command
1894  */
1895 static int
1896 cd_play_tracks(struct cd_softc *cd, struct cd_formatted_toc *toc, int strack,
1897     int sindex, int etrack, int eindex)
1898 {
1899 	int error;
1900 
1901 	if (!etrack)
1902 		return (EIO);
1903 	if (strack > etrack)
1904 		return (EINVAL);
1905 
1906 	error = cd_load_toc(cd, CD_TOC_FORM, toc, XS_CTL_DATA_ONSTACK);
1907 	if (error)
1908 		return (error);
1909 
1910 	if (++etrack > (toc->header.ending_track+1))
1911 		etrack = toc->header.ending_track+1;
1912 
1913 	strack -= toc->header.starting_track;
1914 	etrack -= toc->header.starting_track;
1915 	if (strack < 0)
1916 		return (EINVAL);
1917 
1918 	return (cd_play_msf(cd, toc->entries[strack].addr.msf.minute,
1919 	    toc->entries[strack].addr.msf.second,
1920 	    toc->entries[strack].addr.msf.frame,
1921 	    toc->entries[etrack].addr.msf.minute,
1922 	    toc->entries[etrack].addr.msf.second,
1923 	    toc->entries[etrack].addr.msf.frame));
1924 }
1925 
1926 /*
1927  * Get scsi driver to send a "play msf" command
1928  */
1929 static int
1930 cd_play_msf(struct cd_softc *cd, int startm, int starts, int startf, int endm,
1931     int ends, int endf)
1932 {
1933 	struct scsipi_play_msf cmd;
1934 
1935 	memset(&cmd, 0, sizeof(cmd));
1936 	cmd.opcode = PLAY_MSF;
1937 	cmd.start_m = startm;
1938 	cmd.start_s = starts;
1939 	cmd.start_f = startf;
1940 	cmd.end_m = endm;
1941 	cmd.end_s = ends;
1942 	cmd.end_f = endf;
1943 
1944 	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
1945 	    CDRETRIES, 30000, NULL, 0));
1946 }
1947 
1948 /*
1949  * Get scsi driver to send a "start up" command
1950  */
1951 static int
1952 cd_pause(struct cd_softc *cd, int go)
1953 {
1954 	struct scsipi_pause cmd;
1955 
1956 	memset(&cmd, 0, sizeof(cmd));
1957 	cmd.opcode = PAUSE;
1958 	cmd.resume = go & 0xff;
1959 
1960 	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
1961 	    CDRETRIES, 30000, NULL, 0));
1962 }
1963 
1964 /*
1965  * Get scsi driver to send a "RESET" command
1966  */
1967 static int
1968 cd_reset(struct cd_softc *cd)
1969 {
1970 
1971 	return (scsipi_command(cd->sc_periph, 0, 0, 0, 0,
1972 	    CDRETRIES, 30000, NULL, XS_CTL_RESET));
1973 }
1974 
1975 /*
1976  * Read subchannel
1977  */
1978 static int
1979 cd_read_subchannel(struct cd_softc *cd, int mode, int format, int track,
1980     struct cd_sub_channel_info *data, int len, int flags)
1981 {
1982 	struct scsipi_read_subchannel cmd;
1983 
1984 	memset(&cmd, 0, sizeof(cmd));
1985 	cmd.opcode = READ_SUBCHANNEL;
1986 	if (mode == CD_MSF_FORMAT)
1987 		cmd.byte2 |= CD_MSF;
1988 	cmd.byte3 = SRS_SUBQ;
1989 	cmd.subchan_format = format;
1990 	cmd.track = track;
1991 	_lto2b(len, cmd.data_len);
1992 
1993 	return (scsipi_command(cd->sc_periph,
1994 	    (void *)&cmd, sizeof(struct scsipi_read_subchannel),
1995 	    (void *)data, len,
1996 	    CDRETRIES, 30000, NULL, flags | XS_CTL_DATA_IN | XS_CTL_SILENT));
1997 }
1998 
1999 /*
2000  * Read table of contents
2001  */
2002 static int
2003 cd_read_toc(struct cd_softc *cd, int respf, int mode, int start,
2004     struct cd_formatted_toc *toc, int len, int flags, int control)
2005 {
2006 	struct scsipi_read_toc cmd;
2007 	int ntoc;
2008 
2009 	memset(&cmd, 0, sizeof(cmd));
2010 #if 0
2011 	if (len != sizeof(struct ioc_toc_header))
2012 		ntoc = ((len) - sizeof(struct ioc_toc_header)) /
2013 		    sizeof(struct cd_toc_entry);
2014 	else
2015 #endif
2016 	ntoc = len;
2017 	cmd.opcode = READ_TOC;
2018 	if (mode == CD_MSF_FORMAT)
2019 		cmd.addr_mode |= CD_MSF;
2020 	cmd.resp_format = respf;
2021 	cmd.from_track = start;
2022 	_lto2b(ntoc, cmd.data_len);
2023 	cmd.control = control;
2024 
2025 	return (scsipi_command(cd->sc_periph,
2026 	    (void *)&cmd, sizeof(cmd), (void *)toc, len, CDRETRIES,
2027 	    30000, NULL, flags | XS_CTL_DATA_IN));
2028 }
2029 
2030 static int
2031 cd_load_toc(struct cd_softc *cd, int respf, struct cd_formatted_toc *toc, int flags)
2032 {
2033 	int ntracks, len, error;
2034 
2035 	if ((error = cd_read_toc(cd, respf, 0, 0, toc, sizeof(toc->header),
2036 	    flags, 0)) != 0)
2037 		return (error);
2038 
2039 	ntracks = toc->header.ending_track - toc->header.starting_track + 1;
2040 	len = (ntracks + 1) * sizeof(struct cd_toc_entry) +
2041 	    sizeof(toc->header);
2042 	if ((error = cd_read_toc(cd, respf, CD_MSF_FORMAT, 0, toc, len,
2043 	    flags, 0)) != 0)
2044 		return (error);
2045 	return (0);
2046 }
2047 
2048 /*
2049  * Get the scsi driver to send a full inquiry to the device and use the
2050  * results to fill out the disk parameter structure.
2051  */
2052 static int
2053 cd_get_parms(struct cd_softc *cd, int flags)
2054 {
2055 
2056 	/*
2057 	 * give a number of sectors so that sec * trks * cyls
2058 	 * is <= disk_size
2059 	 */
2060 	if (cd_size(cd, flags) == 0)
2061 		return (ENXIO);
2062 	disk_blocksize(&cd->sc_dk, cd->params.blksize);
2063 	return (0);
2064 }
2065 
2066 static int
2067 cdsize(dev_t dev)
2068 {
2069 
2070 	/* CD-ROMs are read-only. */
2071 	return (-1);
2072 }
2073 
2074 static int
2075 cddump(dev_t dev, daddr_t blkno, void *va, size_t size)
2076 {
2077 
2078 	/* Not implemented. */
2079 	return (ENXIO);
2080 }
2081 
2082 #define	dvd_copy_key(dst, src)		memcpy((dst), (src), sizeof(dvd_key))
2083 #define	dvd_copy_challenge(dst, src)	memcpy((dst), (src), sizeof(dvd_challenge))
2084 
2085 static int
2086 dvd_auth(struct cd_softc *cd, dvd_authinfo *a)
2087 {
2088 	struct scsipi_generic cmd;
2089 	u_int8_t bf[20];
2090 	int error;
2091 
2092 	memset(cmd.bytes, 0, 15);
2093 	memset(bf, 0, sizeof(bf));
2094 
2095 	switch (a->type) {
2096 	case DVD_LU_SEND_AGID:
2097 		cmd.opcode = GPCMD_REPORT_KEY;
2098 		cmd.bytes[8] = 8;
2099 		cmd.bytes[9] = 0 | (0 << 6);
2100 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
2101 		    CDRETRIES, 30000, NULL,
2102 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2103 		if (error)
2104 			return (error);
2105 		a->lsa.agid = bf[7] >> 6;
2106 		return (0);
2107 
2108 	case DVD_LU_SEND_CHALLENGE:
2109 		cmd.opcode = GPCMD_REPORT_KEY;
2110 		cmd.bytes[8] = 16;
2111 		cmd.bytes[9] = 1 | (a->lsc.agid << 6);
2112 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 16,
2113 		    CDRETRIES, 30000, NULL,
2114 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2115 		if (error)
2116 			return (error);
2117 		dvd_copy_challenge(a->lsc.chal, &bf[4]);
2118 		return (0);
2119 
2120 	case DVD_LU_SEND_KEY1:
2121 		cmd.opcode = GPCMD_REPORT_KEY;
2122 		cmd.bytes[8] = 12;
2123 		cmd.bytes[9] = 2 | (a->lsk.agid << 6);
2124 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 12,
2125 		    CDRETRIES, 30000, NULL,
2126 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2127 		if (error)
2128 			return (error);
2129 		dvd_copy_key(a->lsk.key, &bf[4]);
2130 		return (0);
2131 
2132 	case DVD_LU_SEND_TITLE_KEY:
2133 		cmd.opcode = GPCMD_REPORT_KEY;
2134 		_lto4b(a->lstk.lba, &cmd.bytes[1]);
2135 		cmd.bytes[8] = 12;
2136 		cmd.bytes[9] = 4 | (a->lstk.agid << 6);
2137 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 12,
2138 		    CDRETRIES, 30000, NULL,
2139 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2140 		if (error)
2141 			return (error);
2142 		a->lstk.cpm = (bf[4] >> 7) & 1;
2143 		a->lstk.cp_sec = (bf[4] >> 6) & 1;
2144 		a->lstk.cgms = (bf[4] >> 4) & 3;
2145 		dvd_copy_key(a->lstk.title_key, &bf[5]);
2146 		return (0);
2147 
2148 	case DVD_LU_SEND_ASF:
2149 		cmd.opcode = GPCMD_REPORT_KEY;
2150 		cmd.bytes[8] = 8;
2151 		cmd.bytes[9] = 5 | (a->lsasf.agid << 6);
2152 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
2153 		    CDRETRIES, 30000, NULL,
2154 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2155 		if (error)
2156 			return (error);
2157 		a->lsasf.asf = bf[7] & 1;
2158 		return (0);
2159 
2160 	case DVD_HOST_SEND_CHALLENGE:
2161 		cmd.opcode = GPCMD_SEND_KEY;
2162 		cmd.bytes[8] = 16;
2163 		cmd.bytes[9] = 1 | (a->hsc.agid << 6);
2164 		bf[1] = 14;
2165 		dvd_copy_challenge(&bf[4], a->hsc.chal);
2166 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 16,
2167 		    CDRETRIES, 30000, NULL,
2168 		    XS_CTL_DATA_OUT|XS_CTL_DATA_ONSTACK);
2169 		if (error)
2170 			return (error);
2171 		a->type = DVD_LU_SEND_KEY1;
2172 		return (0);
2173 
2174 	case DVD_HOST_SEND_KEY2:
2175 		cmd.opcode = GPCMD_SEND_KEY;
2176 		cmd.bytes[8] = 12;
2177 		cmd.bytes[9] = 3 | (a->hsk.agid << 6);
2178 		bf[1] = 10;
2179 		dvd_copy_key(&bf[4], a->hsk.key);
2180 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 12,
2181 		    CDRETRIES, 30000, NULL,
2182 		    XS_CTL_DATA_OUT|XS_CTL_DATA_ONSTACK);
2183 		if (error) {
2184 			a->type = DVD_AUTH_FAILURE;
2185 			return (error);
2186 		}
2187 		a->type = DVD_AUTH_ESTABLISHED;
2188 		return (0);
2189 
2190 	case DVD_INVALIDATE_AGID:
2191 		cmd.opcode = GPCMD_REPORT_KEY;
2192 		cmd.bytes[9] = 0x3f | (a->lsa.agid << 6);
2193 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 16,
2194 		    CDRETRIES, 30000, NULL, 0);
2195 		if (error)
2196 			return (error);
2197 		return (0);
2198 
2199 	case DVD_LU_SEND_RPC_STATE:
2200 		cmd.opcode = GPCMD_REPORT_KEY;
2201 		cmd.bytes[8] = 8;
2202 		cmd.bytes[9] = 8 | (0 << 6);
2203 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
2204 		    CDRETRIES, 30000, NULL,
2205 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2206 		if (error)
2207 			return (error);
2208 		a->lrpcs.type = (bf[4] >> 6) & 3;
2209 		a->lrpcs.vra = (bf[4] >> 3) & 7;
2210 		a->lrpcs.ucca = (bf[4]) & 7;
2211 		a->lrpcs.region_mask = bf[5];
2212 		a->lrpcs.rpc_scheme = bf[6];
2213 		return (0);
2214 
2215 	case DVD_HOST_SEND_RPC_STATE:
2216 		cmd.opcode = GPCMD_SEND_KEY;
2217 		cmd.bytes[8] = 8;
2218 		cmd.bytes[9] = 6 | (0 << 6);
2219 		bf[1] = 6;
2220 		bf[4] = a->hrpcs.pdrc;
2221 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
2222 		    CDRETRIES, 30000, NULL,
2223 		    XS_CTL_DATA_OUT|XS_CTL_DATA_ONSTACK);
2224 		if (error)
2225 			return (error);
2226 		return (0);
2227 
2228 	default:
2229 		return (ENOTTY);
2230 	}
2231 }
2232 
2233 static int
2234 dvd_read_physical(struct cd_softc *cd, dvd_struct *s)
2235 {
2236 	struct scsipi_generic cmd;
2237 	u_int8_t bf[4 + 4 * 20], *bufp;
2238 	int error;
2239 	struct dvd_layer *layer;
2240 	int i;
2241 
2242 	memset(cmd.bytes, 0, 15);
2243 	memset(bf, 0, sizeof(bf));
2244 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2245 	cmd.bytes[6] = s->type;
2246 	_lto2b(sizeof(bf), &cmd.bytes[7]);
2247 
2248 	cmd.bytes[5] = s->physical.layer_num;
2249 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, sizeof(bf),
2250 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2251 	if (error)
2252 		return (error);
2253 	for (i = 0, bufp = &bf[4], layer = &s->physical.layer[0]; i < 4;
2254 	     i++, bufp += 20, layer++) {
2255 		memset(layer, 0, sizeof(*layer));
2256                 layer->book_version = bufp[0] & 0xf;
2257                 layer->book_type = bufp[0] >> 4;
2258                 layer->min_rate = bufp[1] & 0xf;
2259                 layer->disc_size = bufp[1] >> 4;
2260                 layer->layer_type = bufp[2] & 0xf;
2261                 layer->track_path = (bufp[2] >> 4) & 1;
2262                 layer->nlayers = (bufp[2] >> 5) & 3;
2263                 layer->track_density = bufp[3] & 0xf;
2264                 layer->linear_density = bufp[3] >> 4;
2265                 layer->start_sector = _4btol(&bufp[4]);
2266                 layer->end_sector = _4btol(&bufp[8]);
2267                 layer->end_sector_l0 = _4btol(&bufp[12]);
2268                 layer->bca = bufp[16] >> 7;
2269 	}
2270 	return (0);
2271 }
2272 
2273 static int
2274 dvd_read_copyright(struct cd_softc *cd, dvd_struct *s)
2275 {
2276 	struct scsipi_generic cmd;
2277 	u_int8_t bf[8];
2278 	int error;
2279 
2280 	memset(cmd.bytes, 0, 15);
2281 	memset(bf, 0, sizeof(bf));
2282 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2283 	cmd.bytes[6] = s->type;
2284 	_lto2b(sizeof(bf), &cmd.bytes[7]);
2285 
2286 	cmd.bytes[5] = s->copyright.layer_num;
2287 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, sizeof(bf),
2288 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2289 	if (error)
2290 		return (error);
2291 	s->copyright.cpst = bf[4];
2292 	s->copyright.rmi = bf[5];
2293 	return (0);
2294 }
2295 
2296 static int
2297 dvd_read_disckey(struct cd_softc *cd, dvd_struct *s)
2298 {
2299 	struct scsipi_generic cmd;
2300 	u_int8_t *bf;
2301 	int error;
2302 
2303 	bf = malloc(4 + 2048, M_TEMP, M_WAITOK|M_ZERO);
2304 	if (bf == NULL)
2305 		return EIO;
2306 	memset(cmd.bytes, 0, 15);
2307 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2308 	cmd.bytes[6] = s->type;
2309 	_lto2b(4 + 2048, &cmd.bytes[7]);
2310 
2311 	cmd.bytes[9] = s->disckey.agid << 6;
2312 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 4 + 2048,
2313 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2314 	if (error == 0)
2315 		memcpy(s->disckey.value, &bf[4], 2048);
2316 	free(bf, M_TEMP);
2317 	return error;
2318 }
2319 
2320 static int
2321 dvd_read_bca(struct cd_softc *cd, dvd_struct *s)
2322 {
2323 	struct scsipi_generic cmd;
2324 	u_int8_t bf[4 + 188];
2325 	int error;
2326 
2327 	memset(cmd.bytes, 0, 15);
2328 	memset(bf, 0, sizeof(bf));
2329 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2330 	cmd.bytes[6] = s->type;
2331 	_lto2b(sizeof(bf), &cmd.bytes[7]);
2332 
2333 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, sizeof(bf),
2334 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2335 	if (error)
2336 		return (error);
2337 	s->bca.len = _2btol(&bf[0]);
2338 	if (s->bca.len < 12 || s->bca.len > 188)
2339 		return (EIO);
2340 	memcpy(s->bca.value, &bf[4], s->bca.len);
2341 	return (0);
2342 }
2343 
2344 static int
2345 dvd_read_manufact(struct cd_softc *cd, dvd_struct *s)
2346 {
2347 	struct scsipi_generic cmd;
2348 	u_int8_t *bf;
2349 	int error;
2350 
2351 	bf = malloc(4 + 2048, M_TEMP, M_WAITOK|M_ZERO);
2352 	if (bf == NULL)
2353 		return (EIO);
2354 	memset(cmd.bytes, 0, 15);
2355 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2356 	cmd.bytes[6] = s->type;
2357 	_lto2b(4 + 2048, &cmd.bytes[7]);
2358 
2359 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 4 + 2048,
2360 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2361 	if (error == 0) {
2362 		s->manufact.len = _2btol(&bf[0]);
2363 		if (s->manufact.len >= 0 && s->manufact.len <= 2048)
2364 			memcpy(s->manufact.value, &bf[4], s->manufact.len);
2365 		else
2366 			error = EIO;
2367 	}
2368 	free(bf, M_TEMP);
2369 	return error;
2370 }
2371 
2372 static int
2373 dvd_read_struct(struct cd_softc *cd, dvd_struct *s)
2374 {
2375 
2376 	switch (s->type) {
2377 	case DVD_STRUCT_PHYSICAL:
2378 		return (dvd_read_physical(cd, s));
2379 	case DVD_STRUCT_COPYRIGHT:
2380 		return (dvd_read_copyright(cd, s));
2381 	case DVD_STRUCT_DISCKEY:
2382 		return (dvd_read_disckey(cd, s));
2383 	case DVD_STRUCT_BCA:
2384 		return (dvd_read_bca(cd, s));
2385 	case DVD_STRUCT_MANUFACT:
2386 		return (dvd_read_manufact(cd, s));
2387 	default:
2388 		return (EINVAL);
2389 	}
2390 }
2391 
2392 static int
2393 cd_mode_sense(struct cd_softc *cd, u_int8_t byte2, void *sense, size_t size,
2394     int page, int flags, int *big)
2395 {
2396 
2397 	if (cd->sc_periph->periph_quirks & PQUIRK_ONLYBIG) {
2398 		*big = 1;
2399 		return scsipi_mode_sense_big(cd->sc_periph, byte2, page, sense,
2400 		    size + sizeof(struct scsi_mode_parameter_header_10),
2401 		    flags | XS_CTL_DATA_ONSTACK, CDRETRIES, 20000);
2402 	} else {
2403 		*big = 0;
2404 		return scsipi_mode_sense(cd->sc_periph, byte2, page, sense,
2405 		    size + sizeof(struct scsi_mode_parameter_header_6),
2406 		    flags | XS_CTL_DATA_ONSTACK, CDRETRIES, 20000);
2407 	}
2408 }
2409 
2410 static int
2411 cd_mode_select(struct cd_softc *cd, u_int8_t byte2, void *sense, size_t size,
2412     int flags, int big)
2413 {
2414 
2415 	if (big) {
2416 		struct scsi_mode_parameter_header_10 *header = sense;
2417 
2418 		_lto2b(0, header->data_length);
2419 		return scsipi_mode_select_big(cd->sc_periph, byte2, sense,
2420 		    size + sizeof(struct scsi_mode_parameter_header_10),
2421 		    flags | XS_CTL_DATA_ONSTACK, CDRETRIES, 20000);
2422 	} else {
2423 		struct scsi_mode_parameter_header_6 *header = sense;
2424 
2425 		header->data_length = 0;
2426 		return scsipi_mode_select(cd->sc_periph, byte2, sense,
2427 		    size + sizeof(struct scsi_mode_parameter_header_6),
2428 		    flags | XS_CTL_DATA_ONSTACK, CDRETRIES, 20000);
2429 	}
2430 }
2431 
2432 static int
2433 cd_set_pa_immed(struct cd_softc *cd, int flags)
2434 {
2435 	struct {
2436 		union {
2437 			struct scsi_mode_parameter_header_6 small;
2438 			struct scsi_mode_parameter_header_10 big;
2439 		} header;
2440 		struct cd_audio_page page;
2441 	} data;
2442 	int error;
2443 	uint8_t oflags;
2444 	int big, byte2;
2445 	struct cd_audio_page *page;
2446 
2447 	byte2 = SMS_DBD;
2448 try_again:
2449 	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
2450 	    AUDIO_PAGE, flags, &big)) != 0) {
2451 		if (byte2 == SMS_DBD) {
2452 			/* Device may not understand DBD; retry without */
2453 			byte2 = 0;
2454 			goto try_again;
2455 		}
2456 		return (error);
2457 	}
2458 
2459 	if (big)
2460 		page = (void *)((u_long)&data.header.big +
2461 				sizeof data.header.big +
2462 				_2btol(data.header.big.blk_desc_len));
2463 	else
2464 		page = (void *)((u_long)&data.header.small +
2465 				sizeof data.header.small +
2466 				data.header.small.blk_desc_len);
2467 
2468 	oflags = page->flags;
2469 	page->flags &= ~CD_PA_SOTC;
2470 	page->flags |= CD_PA_IMMED;
2471 	if (oflags == page->flags)
2472 		return (0);
2473 
2474 	return (cd_mode_select(cd, SMS_PF, &data,
2475 	    sizeof(struct scsi_mode_page_header) + page->pg_length,
2476 	    flags, big));
2477 }
2478 
2479 static int
2480 cd_setchan(struct cd_softc *cd, int p0, int p1, int p2, int p3, int flags)
2481 {
2482 	struct {
2483 		union {
2484 			struct scsi_mode_parameter_header_6 small;
2485 			struct scsi_mode_parameter_header_10 big;
2486 		} header;
2487 		struct cd_audio_page page;
2488 	} data;
2489 	int error;
2490 	int big, byte2;
2491 	struct cd_audio_page *page;
2492 
2493 	byte2 = SMS_DBD;
2494 try_again:
2495 	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
2496 	    AUDIO_PAGE, flags, &big)) != 0) {
2497 		if (byte2 == SMS_DBD) {
2498 			/* Device may not understand DBD; retry without */
2499 			byte2 = 0;
2500 			goto try_again;
2501 		}
2502 		return (error);
2503 	}
2504 
2505 	if (big)
2506 		page = (void *)((u_long)&data.header.big +
2507 				sizeof data.header.big +
2508 				_2btol(data.header.big.blk_desc_len));
2509 	else
2510 		page = (void *)((u_long)&data.header.small +
2511 				sizeof data.header.small +
2512 				data.header.small.blk_desc_len);
2513 
2514 	page->port[0].channels = p0;
2515 	page->port[1].channels = p1;
2516 	page->port[2].channels = p2;
2517 	page->port[3].channels = p3;
2518 
2519 	return (cd_mode_select(cd, SMS_PF, &data,
2520 	    sizeof(struct scsi_mode_page_header) + page->pg_length,
2521 	    flags, big));
2522 }
2523 
2524 static int
2525 cd_getvol(struct cd_softc *cd, struct ioc_vol *arg, int flags)
2526 {
2527 	struct {
2528 		union {
2529 			struct scsi_mode_parameter_header_6 small;
2530 			struct scsi_mode_parameter_header_10 big;
2531 		} header;
2532 		struct cd_audio_page page;
2533 	} data;
2534 	int error;
2535 	int big, byte2;
2536 	struct cd_audio_page *page;
2537 
2538 	byte2 = SMS_DBD;
2539 try_again:
2540 	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
2541 	    AUDIO_PAGE, flags, &big)) != 0) {
2542 		if (byte2 == SMS_DBD) {
2543 			/* Device may not understand DBD; retry without */
2544 			byte2 = 0;
2545 			goto try_again;
2546 		}
2547 		return (error);
2548 	}
2549 
2550 	if (big)
2551 		page = (void *)((u_long)&data.header.big +
2552 				sizeof data.header.big +
2553 				_2btol(data.header.big.blk_desc_len));
2554 	else
2555 		page = (void *)((u_long)&data.header.small +
2556 				sizeof data.header.small +
2557 				data.header.small.blk_desc_len);
2558 
2559 	arg->vol[0] = page->port[0].volume;
2560 	arg->vol[1] = page->port[1].volume;
2561 	arg->vol[2] = page->port[2].volume;
2562 	arg->vol[3] = page->port[3].volume;
2563 
2564 	return (0);
2565 }
2566 
2567 static int
2568 cd_setvol(struct cd_softc *cd, const struct ioc_vol *arg, int flags)
2569 {
2570 	struct {
2571 		union {
2572 			struct scsi_mode_parameter_header_6 small;
2573 			struct scsi_mode_parameter_header_10 big;
2574 		} header;
2575 		struct cd_audio_page page;
2576 	} data, mask;
2577 	int error;
2578 	int big, byte2;
2579 	struct cd_audio_page *page, *page2;
2580 
2581 	byte2 = SMS_DBD;
2582 try_again:
2583 	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
2584 	    AUDIO_PAGE, flags, &big)) != 0) {
2585 		if (byte2 == SMS_DBD) {
2586 			/* Device may not understand DBD; retry without */
2587 			byte2 = 0;
2588 			goto try_again;
2589 		}
2590 		return (error);
2591 	}
2592 	if ((error = cd_mode_sense(cd, byte2, &mask, sizeof(mask.page),
2593 	    AUDIO_PAGE|SMS_PCTRL_CHANGEABLE, flags, &big)) != 0)
2594 		return (error);
2595 
2596 	if (big) {
2597 		page = (void *)((u_long)&data.header.big +
2598 				sizeof data.header.big +
2599 				_2btol(data.header.big.blk_desc_len));
2600 		page2 = (void *)((u_long)&mask.header.big +
2601 				sizeof mask.header.big +
2602 				_2btol(mask.header.big.blk_desc_len));
2603 	} else {
2604 		page = (void *)((u_long)&data.header.small +
2605 				sizeof data.header.small +
2606 				data.header.small.blk_desc_len);
2607 		page2 = (void *)((u_long)&mask.header.small +
2608 				sizeof mask.header.small +
2609 				mask.header.small.blk_desc_len);
2610 	}
2611 
2612 	page->port[0].volume = arg->vol[0] & page2->port[0].volume;
2613 	page->port[1].volume = arg->vol[1] & page2->port[1].volume;
2614 	page->port[2].volume = arg->vol[2] & page2->port[2].volume;
2615 	page->port[3].volume = arg->vol[3] & page2->port[3].volume;
2616 
2617 	page->port[0].channels = CHANNEL_0;
2618 	page->port[1].channels = CHANNEL_1;
2619 
2620 	return (cd_mode_select(cd, SMS_PF, &data,
2621 	    sizeof(struct scsi_mode_page_header) + page->pg_length,
2622 	    flags, big));
2623 }
2624 
2625 static int
2626 cd_load_unload(struct cd_softc *cd, struct ioc_load_unload *args)
2627 {
2628 	struct scsipi_load_unload cmd;
2629 
2630 	memset(&cmd, 0, sizeof(cmd));
2631 	cmd.opcode = LOAD_UNLOAD;
2632 	cmd.options = args->options;    /* ioctl uses MMC values */
2633 	cmd.slot = args->slot;
2634 
2635 	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
2636 	    CDRETRIES, 200000, NULL, 0));
2637 }
2638 
2639 static int
2640 cd_setblksize(struct cd_softc *cd)
2641 {
2642 	struct {
2643 		union {
2644 			struct scsi_mode_parameter_header_6 small;
2645 			struct scsi_mode_parameter_header_10 big;
2646 		} header;
2647 		struct scsi_general_block_descriptor blk_desc;
2648 	} data;
2649 	int error;
2650 	int big, bsize;
2651 	struct scsi_general_block_descriptor *bdesc;
2652 
2653 	if ((error = cd_mode_sense(cd, 0, &data, sizeof(data.blk_desc), 0, 0,
2654 	    &big)) != 0)
2655 		return (error);
2656 
2657 	if (big) {
2658 		bdesc = (void *)(&data.header.big + 1);
2659 		bsize = _2btol(data.header.big.blk_desc_len);
2660 	} else {
2661 		bdesc = (void *)(&data.header.small + 1);
2662 		bsize = data.header.small.blk_desc_len;
2663 	}
2664 
2665 	if (bsize == 0) {
2666 printf("cd_setblksize: trying to change bsize, but no blk_desc\n");
2667 		return (EINVAL);
2668 	}
2669 	if (_3btol(bdesc->blklen) == 2048) {
2670 printf("cd_setblksize: trying to change bsize, but blk_desc is correct\n");
2671 		return (EINVAL);
2672 	}
2673 
2674 	_lto3b(2048, bdesc->blklen);
2675 
2676 	return (cd_mode_select(cd, SMS_PF, &data, sizeof(data.blk_desc), 0,
2677 	    big));
2678 }
2679 
2680 
2681 static int
2682 mmc_profile2class(uint16_t mmc_profile)
2683 {
2684 	switch (mmc_profile) {
2685 	case 0x01 : /* SCSI discs */
2686 	case 0x02 :
2687 		/* this can't happen really, cd.c wouldn't have matched */
2688 		return MMC_CLASS_DISC;
2689 	case 0x03 : /* Magneto Optical with sector erase */
2690 	case 0x04 : /* Magneto Optical write once        */
2691 	case 0x05 : /* Advance Storage Magneto Optical   */
2692 		return MMC_CLASS_MO;
2693 	case 0x00 : /* Unknown MMC profile, can also be CD-ROM */
2694 	case 0x08 : /* CD-ROM  */
2695 	case 0x09 : /* CD-R    */
2696 	case 0x0a : /* CD-RW   */
2697 		return MMC_CLASS_CD;
2698 	case 0x10 : /* DVD-ROM */
2699 	case 0x11 : /* DVD-R   */
2700 	case 0x12 : /* DVD-RAM */
2701 	case 0x13 : /* DVD-RW restricted overwrite */
2702 	case 0x14 : /* DVD-RW sequential */
2703 	case 0x1a : /* DVD+RW  */
2704 	case 0x1b : /* DVD+R   */
2705 	case 0x2a : /* DVD+RW Dual layer */
2706 	case 0x2b : /* DVD+R Dual layer */
2707 	case 0x50 : /* HD DVD-ROM */
2708 	case 0x51 : /* HD DVD-R   */
2709 	case 0x52 : /* HD DVD-RW; DVD-RAM like */
2710 		return MMC_CLASS_DVD;
2711 	case 0x40 : /* BD-ROM  */
2712 	case 0x41 : /* BD-R Sequential recording (SRM) */
2713 	case 0x42 : /* BD-R Ramdom Recording (RRM) */
2714 	case 0x43 : /* BD-RE */
2715 		return MMC_CLASS_BD;
2716 	}
2717 	return MMC_CLASS_UNKN;
2718 }
2719 
2720 
2721 /*
2722  * Drive/media combination is reflected in a series of features that can
2723  * either be current or dormant. We try to make sense out of them to create a
2724  * set of easy to use flags that abstract the device/media capabilities.
2725  */
2726 
2727 static void
2728 mmc_process_feature(struct mmc_discinfo *mmc_discinfo,
2729 		    uint16_t feature, int cur, uint8_t *rpos)
2730 {
2731 	uint32_t blockingnr;
2732 	uint64_t flags;
2733 
2734 	if (cur == 1) {
2735 		flags = mmc_discinfo->mmc_cur;
2736 	} else {
2737 		flags = mmc_discinfo->mmc_cap;
2738 	}
2739 
2740 	switch (feature) {
2741 	case 0x0010 :	/* random readable feature */
2742 		blockingnr  =  rpos[5] | (rpos[4] << 8);
2743 		if (blockingnr > 1)
2744 			flags |= MMC_CAP_PACKET;
2745 
2746 		/* RW error page */
2747 		break;
2748 	case 0x0020 :	/* random writable feature */
2749 		flags |= MMC_CAP_RECORDABLE;
2750 		flags |= MMC_CAP_REWRITABLE;
2751 		blockingnr  =  rpos[9] | (rpos[8] << 8);
2752 		if (blockingnr > 1)
2753 			flags |= MMC_CAP_PACKET;
2754 		break;
2755 	case 0x0021 :	/* incremental streaming write feature */
2756 		flags |= MMC_CAP_RECORDABLE;
2757 		flags |= MMC_CAP_SEQUENTIAL;
2758 		if (cur)
2759 			mmc_discinfo->link_block_penalty = rpos[4];
2760 		if (rpos[2] & 1)
2761 			flags |= MMC_CAP_ZEROLINKBLK;
2762 		break;
2763 	case 0x0022 : 	/* (obsolete) erase support feature */
2764 		flags |= MMC_CAP_RECORDABLE;
2765 		flags |= MMC_CAP_ERASABLE;
2766 		break;
2767 	case 0x0023 :	/* formatting media support feature */
2768 		flags |= MMC_CAP_RECORDABLE;
2769 		flags |= MMC_CAP_FORMATTABLE;
2770 		break;
2771 	case 0x0024 :	/* hardware assised defect management feature */
2772 		flags |= MMC_CAP_HW_DEFECTFREE;
2773 		break;
2774 	case 0x0025 : 	/* write once */
2775 		flags |= MMC_CAP_RECORDABLE;
2776 		break;
2777 	case 0x0026 :	/* restricted overwrite feature */
2778 		flags |= MMC_CAP_RECORDABLE;
2779 		flags |= MMC_CAP_REWRITABLE;
2780 		flags |= MMC_CAP_STRICTOVERWRITE;
2781 		break;
2782 	case 0x0028 :	/* MRW formatted media support feature */
2783 		flags |= MMC_CAP_MRW;
2784 		break;
2785 	case 0x002b :	/* DVD+R read (and opt. write) support */
2786 		flags |= MMC_CAP_SEQUENTIAL;
2787 		if (rpos[0] & 1) /* write support */
2788 			flags |= MMC_CAP_RECORDABLE;
2789 		break;
2790 	case 0x002c :	/* rigid restricted overwrite feature */
2791 		flags |= MMC_CAP_RECORDABLE;
2792 		flags |= MMC_CAP_REWRITABLE;
2793 		flags |= MMC_CAP_STRICTOVERWRITE;
2794 		if (rpos[0] & 1) /* blank bit */
2795 			flags |= MMC_CAP_BLANKABLE;
2796 		break;
2797 	case 0x002d :	/* track at once recording feature */
2798 		flags |= MMC_CAP_RECORDABLE;
2799 		flags |= MMC_CAP_SEQUENTIAL;
2800 		break;
2801 	case 0x002f :	/* DVD-R/-RW write feature */
2802 		flags |= MMC_CAP_RECORDABLE;
2803 		if (rpos[0] & 2) /* DVD-RW bit */
2804 			flags |= MMC_CAP_BLANKABLE;
2805 		break;
2806 	case 0x0038 :	/* BD-R SRM with pseudo overwrite */
2807 		flags |= MMC_CAP_PSEUDOOVERWRITE;
2808 		break;
2809 	default :
2810 		/* ignore */
2811 		break;
2812 	}
2813 
2814 	if (cur == 1) {
2815 		mmc_discinfo->mmc_cur = flags;
2816 	} else {
2817 		mmc_discinfo->mmc_cap = flags;
2818 	}
2819 }
2820 
2821 static int
2822 mmc_getdiscinfo_cdrom(struct scsipi_periph *periph,
2823 		      struct mmc_discinfo *mmc_discinfo)
2824 {
2825 	struct scsipi_read_toc      gtoc_cmd;
2826 	struct scsipi_toc_header   *toc_hdr;
2827 	struct scsipi_toc_msinfo   *toc_msinfo;
2828 	const uint32_t buffer_size = 1024;
2829 	uint32_t req_size;
2830 	uint8_t  *buffer;
2831 	int error, flags;
2832 
2833 	buffer = malloc(buffer_size, M_TEMP, M_WAITOK);
2834 	/*
2835 	 * Fabricate mmc_discinfo for CD-ROM. Some values are really `dont
2836 	 * care' but others might be of interest to programs.
2837 	 */
2838 
2839 	mmc_discinfo->disc_state	 = MMC_STATE_FULL;
2840 	mmc_discinfo->last_session_state = MMC_STATE_FULL;
2841 	mmc_discinfo->bg_format_state    = MMC_BGFSTATE_COMPLETED;
2842 	mmc_discinfo->link_block_penalty = 7;	/* not relevant */
2843 
2844 	/* get number of sessions and first tracknr in last session */
2845 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK;
2846 	bzero(&gtoc_cmd, sizeof(gtoc_cmd));
2847 	gtoc_cmd.opcode      = READ_TOC;
2848 	gtoc_cmd.addr_mode   = CD_MSF;		/* not relevant        */
2849 	gtoc_cmd.resp_format = CD_TOC_MSINFO;	/* multisession info   */
2850 	gtoc_cmd.from_track  = 0;		/* reserved, must be 0 */
2851 	req_size = sizeof(*toc_hdr) + sizeof(*toc_msinfo);
2852 	_lto2b(req_size, gtoc_cmd.data_len);
2853 
2854 	error = scsipi_command(periph,
2855 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
2856 		(void *)buffer,    req_size,
2857 		CDRETRIES, 30000, NULL, flags);
2858 	if (error)
2859 		goto out;
2860 	toc_hdr    = (struct scsipi_toc_header *)  buffer;
2861 	toc_msinfo = (struct scsipi_toc_msinfo *) (buffer + 4);
2862 	mmc_discinfo->num_sessions = toc_hdr->last - toc_hdr->first + 1;
2863 	mmc_discinfo->first_track  = toc_hdr->first;
2864 	mmc_discinfo->first_track_last_session = toc_msinfo->tracknr;
2865 
2866 	/* get last track of last session */
2867 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK;
2868 	gtoc_cmd.resp_format  = CD_TOC_FORM;	/* formatted toc */
2869 	req_size = sizeof(*toc_hdr);
2870 	_lto2b(req_size, gtoc_cmd.data_len);
2871 
2872 	error = scsipi_command(periph,
2873 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
2874 		(void *)buffer,    req_size,
2875 		CDRETRIES, 30000, NULL, flags);
2876 	if (error)
2877 		goto out;
2878 	toc_hdr    = (struct scsipi_toc_header *) buffer;
2879 	mmc_discinfo->last_track_last_session = toc_hdr->last;
2880 	mmc_discinfo->num_tracks = toc_hdr->last - toc_hdr->first + 1;
2881 
2882 	/* TODO how to handle disc_barcode and disc_id */
2883 	/* done */
2884 
2885 out:
2886 	free(buffer, M_TEMP);
2887 	return error;
2888 }
2889 
2890 static int
2891 mmc_getdiscinfo_dvdrom(struct scsipi_periph *periph,
2892 		       struct mmc_discinfo *mmc_discinfo)
2893 {
2894 	struct scsipi_read_toc   gtoc_cmd;
2895 	struct scsipi_toc_header toc_hdr;
2896 	uint32_t req_size;
2897 	int error, flags;
2898 
2899 	/*
2900 	 * Fabricate mmc_discinfo for DVD-ROM. Some values are really `dont
2901 	 * care' but others might be of interest to programs.
2902 	 */
2903 
2904 	mmc_discinfo->disc_state	 = MMC_STATE_FULL;
2905 	mmc_discinfo->last_session_state = MMC_STATE_FULL;
2906 	mmc_discinfo->bg_format_state    = MMC_BGFSTATE_COMPLETED;
2907 	mmc_discinfo->link_block_penalty = 16;	/* not relevant */
2908 
2909 	/* get number of sessions and first tracknr in last session */
2910 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK;
2911 	bzero(&gtoc_cmd, sizeof(gtoc_cmd));
2912 	gtoc_cmd.opcode      = READ_TOC;
2913 	gtoc_cmd.addr_mode   = 0;		/* LBA                 */
2914 	gtoc_cmd.resp_format = CD_TOC_FORM;	/* multisession info   */
2915 	gtoc_cmd.from_track  = 1;		/* first track         */
2916 	req_size = sizeof(toc_hdr);
2917 	_lto2b(req_size, gtoc_cmd.data_len);
2918 
2919 	error = scsipi_command(periph,
2920 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
2921 		(void *)&toc_hdr,  req_size,
2922 		CDRETRIES, 30000, NULL, flags);
2923 	if (error)
2924 		return error;
2925 
2926 	/* DVD-ROM squashes the track/session space */
2927 	mmc_discinfo->num_sessions = toc_hdr.last - toc_hdr.first + 1;
2928 	mmc_discinfo->num_tracks   = mmc_discinfo->num_sessions;
2929 	mmc_discinfo->first_track  = toc_hdr.first;
2930 	mmc_discinfo->first_track_last_session = toc_hdr.last;
2931 	mmc_discinfo->last_track_last_session  = toc_hdr.last;
2932 
2933 	/* TODO how to handle disc_barcode and disc_id */
2934 	/* done */
2935 	return 0;
2936 }
2937 
2938 static int
2939 mmc_getdiscinfo(struct scsipi_periph *periph,
2940 		struct mmc_discinfo *mmc_discinfo)
2941 {
2942 	struct scsipi_get_configuration   gc_cmd;
2943 	struct scsipi_get_conf_data      *gc;
2944 	struct scsipi_get_conf_feature   *gcf;
2945 	struct scsipi_read_discinfo       di_cmd;
2946 	struct scsipi_read_discinfo_data  di;
2947 	const uint32_t buffer_size = 1024;
2948 	uint32_t feat_tbl_len, pos;
2949 	u_long   last_lba;
2950 	uint8_t  *buffer, *fpos;
2951 	int feature, last_feature, features_len, feature_cur, feature_len;
2952 	int lsb, msb, error, flags;
2953 
2954 	feat_tbl_len = buffer_size;
2955 
2956 	buffer = malloc(buffer_size, M_TEMP, M_WAITOK);
2957 
2958 	/* initialise structure */
2959 	memset(mmc_discinfo, 0, sizeof(struct mmc_discinfo));
2960 	mmc_discinfo->mmc_profile = 0x00;	/* unknown */
2961 	mmc_discinfo->mmc_class   = MMC_CLASS_UNKN;
2962 	mmc_discinfo->mmc_cur     = 0;
2963 	mmc_discinfo->mmc_cap     = 0;
2964 	mmc_discinfo->link_block_penalty = 0;
2965 
2966 	/* determine mmc profile and class */
2967 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK;
2968 	memset(&gc_cmd, 0, sizeof(gc_cmd));
2969 	gc_cmd.opcode = GET_CONFIGURATION;
2970 	_lto2b(GET_CONF_NO_FEATURES_LEN, gc_cmd.data_len);
2971 
2972 	gc = (struct scsipi_get_conf_data *) buffer;
2973 
2974 	error = scsipi_command(periph,
2975 		(void *)&gc_cmd, sizeof(gc_cmd),
2976 		(void *) gc,     GET_CONF_NO_FEATURES_LEN,
2977 		CDRETRIES, 30000, NULL, flags);
2978 	if (error)
2979 		goto out;
2980 
2981 	mmc_discinfo->mmc_profile = _2btol(gc->mmc_profile);
2982 	mmc_discinfo->mmc_class = mmc_profile2class(mmc_discinfo->mmc_profile);
2983 
2984 	/* assume 2048 sector size unless told otherwise */
2985 	mmc_discinfo->sector_size = 2048;
2986 	error = read_cd_capacity(periph, &mmc_discinfo->sector_size, &last_lba);
2987 	if (error)
2988 		goto out;
2989 
2990 	mmc_discinfo->last_possible_lba = (uint32_t) last_lba - 1;
2991 
2992 	/* Read in all features to determine device capabilities */
2993 	last_feature = feature = 0;
2994 	do {
2995 		/* determine mmc profile and class */
2996 		flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK;
2997 		memset(&gc_cmd, 0, sizeof(gc_cmd));
2998 		gc_cmd.opcode = GET_CONFIGURATION;
2999 		_lto2b(last_feature, gc_cmd.start_at_feature);
3000 		_lto2b(feat_tbl_len, gc_cmd.data_len);
3001 
3002 		error = scsipi_command(periph,
3003 			(void *)&gc_cmd, sizeof(gc_cmd),
3004 			(void *) gc,     feat_tbl_len,
3005 			CDRETRIES, 30000, NULL, flags);
3006 		if (error) {
3007 			/* ieeek... break out of loop... i dunno what to do */
3008 			break;
3009 		}
3010 
3011 		features_len = _4btol(gc->data_len);
3012 
3013 		pos  = 0;
3014 		fpos = &gc->feature_desc[0];
3015 		while (pos < features_len - 4) {
3016 			gcf = (struct scsipi_get_conf_feature *) fpos;
3017 
3018 			feature     = _2btol(gcf->featurecode);
3019 			feature_cur = gcf->flags & 1;
3020 			feature_len = gcf->additional_length;
3021 
3022 			mmc_process_feature(mmc_discinfo,
3023 					    feature, feature_cur,
3024 					    gcf->feature_dependent);
3025 
3026 			last_feature = MAX(last_feature, feature);
3027 #ifdef DIAGNOSTIC
3028 			/* assert((feature_len & 3) == 0); */
3029 			if ((feature_len & 3) != 0) {
3030 				printf("feature %d having length %d\n",
3031 					feature, feature_len);
3032 			}
3033 #endif
3034 
3035 			pos  += 4 + feature_len;
3036 			fpos += 4 + feature_len;
3037 		}
3038 		/* unlikely to ever grow past our 1kb buffer */
3039 	} while (features_len >= 0xffff);
3040 
3041 	/*
3042 	 * Fixup CD-RW drives that are on crack.
3043 	 *
3044 	 * Some drives report the capability to incrementally write
3045 	 * sequentially on CD-R(W) media...  nice, but this should not be
3046 	 * active for a fixed packet formatted CD-RW media. Other report the
3047 	 * ability of HW_DEFECTFREE even when the media is NOT MRW
3048 	 * formatted....
3049 	 */
3050 	if (mmc_discinfo->mmc_profile == 0x0a) {
3051 		if ((mmc_discinfo->mmc_cur & MMC_CAP_SEQUENTIAL) == 0)
3052 			mmc_discinfo->mmc_cur |= MMC_CAP_STRICTOVERWRITE;
3053 		if (mmc_discinfo->mmc_cur & MMC_CAP_STRICTOVERWRITE)
3054 			mmc_discinfo->mmc_cur &= ~MMC_CAP_SEQUENTIAL;
3055 		if (mmc_discinfo->mmc_cur & MMC_CAP_MRW) {
3056 			mmc_discinfo->mmc_cur &= ~MMC_CAP_SEQUENTIAL;
3057 			mmc_discinfo->mmc_cur &= ~MMC_CAP_STRICTOVERWRITE;
3058 		} else {
3059 			mmc_discinfo->mmc_cur &= ~MMC_CAP_HW_DEFECTFREE;
3060 		}
3061 	}
3062 	if (mmc_discinfo->mmc_profile == 0x09) {
3063 		mmc_discinfo->mmc_cur &= ~MMC_CAP_REWRITABLE;
3064 	}
3065 
3066 #ifdef DEBUG
3067 	printf("CD mmc %d, mmc_cur 0x%"PRIx64", mmc_cap 0x%"PRIx64"\n",
3068 		mmc_discinfo->mmc_profile,
3069 	 	mmc_discinfo->mmc_cur, mmc_discinfo->mmc_cap);
3070 #endif
3071 
3072 	/* read in disc state and number of sessions and tracks */
3073 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK | XS_CTL_SILENT;
3074 	memset(&di_cmd, 0, sizeof(di_cmd));
3075 	di_cmd.opcode = READ_DISCINFO;
3076 	di_cmd.data_len[1] = READ_DISCINFO_BIGSIZE;
3077 
3078 	error = scsipi_command(periph,
3079 		(void *)&di_cmd, sizeof(di_cmd),
3080 		(void *)&di,     READ_DISCINFO_BIGSIZE,
3081 		CDRETRIES, 30000, NULL, flags);
3082 
3083 	if (error) {
3084 		/* discinfo call failed, emulate for cd-rom/dvd-rom */
3085 		if (mmc_discinfo->mmc_profile == 0x08) /* CD-ROM */
3086 			return mmc_getdiscinfo_cdrom(periph, mmc_discinfo);
3087 		if (mmc_discinfo->mmc_profile == 0x10) /* DVD-ROM */
3088 			return mmc_getdiscinfo_dvdrom(periph, mmc_discinfo);
3089 		/* CD/DVD drive is violating specs */
3090 		error = EIO;
3091 		goto out;
3092 	}
3093 
3094 	/* call went OK */
3095 	mmc_discinfo->disc_state         =  di.disc_state & 3;
3096 	mmc_discinfo->last_session_state = (di.disc_state >> 2) & 3;
3097 	mmc_discinfo->bg_format_state    = (di.disc_state2 & 3);
3098 
3099 	lsb = di.num_sessions_lsb;
3100 	msb = di.num_sessions_msb;
3101 	mmc_discinfo->num_sessions = lsb | (msb << 8);
3102 
3103 	mmc_discinfo->first_track = di.first_track;
3104 	lsb = di.first_track_last_session_lsb;
3105 	msb = di.first_track_last_session_msb;
3106 	mmc_discinfo->first_track_last_session = lsb | (msb << 8);
3107 	lsb = di.last_track_last_session_lsb;
3108 	msb = di.last_track_last_session_msb;
3109 	mmc_discinfo->last_track_last_session  = lsb | (msb << 8);
3110 
3111 	mmc_discinfo->num_tracks = mmc_discinfo->last_track_last_session -
3112 		mmc_discinfo->first_track + 1;
3113 
3114 	/* set misc. flags and parameters from this disc info */
3115 	if (di.disc_state  &  16)
3116 		mmc_discinfo->mmc_cur |= MMC_CAP_BLANKABLE;
3117 
3118 	if (di.disc_state2 & 128) {
3119 		mmc_discinfo->disc_id = _4btol(di.discid);
3120 		mmc_discinfo->disc_flags |= MMC_DFLAGS_DISCIDVALID;
3121 	}
3122 	if (di.disc_state2 &  64) {
3123 		mmc_discinfo->disc_barcode = _8btol(di.disc_bar_code);
3124 		mmc_discinfo->disc_flags |= MMC_DFLAGS_BARCODEVALID;
3125 	}
3126 	if (di.disc_state2 &  32)
3127 		mmc_discinfo->disc_flags |= MMC_DFLAGS_UNRESTRICTED;
3128 
3129 	if (di.disc_state2 &  16) {
3130 		mmc_discinfo->application_code = di.application_code;
3131 		mmc_discinfo->disc_flags |= MMC_DFLAGS_APPCODEVALID;
3132 	}
3133 
3134 	/* done */
3135 
3136 out:
3137 	free(buffer, M_TEMP);
3138 	return error;
3139 }
3140 
3141 static int
3142 mmc_gettrackinfo_cdrom(struct scsipi_periph *periph,
3143 		       struct mmc_trackinfo *trackinfo)
3144 {
3145 	struct scsipi_read_toc            gtoc_cmd;
3146 	struct scsipi_toc_header         *toc_hdr;
3147 	struct scsipi_toc_rawtoc         *rawtoc;
3148 	uint32_t track_start, track_end, track_size;
3149 	uint32_t last_recorded, next_writable;
3150 	uint32_t lba, next_track_start, lead_out;
3151 	const uint32_t buffer_size = 4 * 1024;	/* worst case TOC estimate */
3152 	uint8_t *buffer;
3153 	uint8_t track_sessionnr, last_tracknr, sessionnr, adr, tno, point;
3154 	uint8_t tmin, tsec, tframe, pmin, psec, pframe;
3155 	int size, req_size;
3156 	int error, flags;
3157 
3158 	buffer = malloc(buffer_size, M_TEMP, M_WAITOK);
3159 
3160 	/*
3161 	 * Emulate read trackinfo for CD-ROM using the raw-TOC.
3162 	 *
3163 	 * Not all information is present and this presents a problem.  Track
3164 	 * starts are known for each track but other values are deducted.
3165 	 *
3166 	 * For a complete overview of `magic' values used here, see the
3167 	 * SCSI/ATAPI MMC documentation. Note that the `magic' values have no
3168 	 * names, they are specified as numbers.
3169 	 */
3170 
3171 	/* get raw toc to process, first header to check size */
3172 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK | XS_CTL_SILENT;
3173 	bzero(&gtoc_cmd, sizeof(gtoc_cmd));
3174 	gtoc_cmd.opcode      = READ_TOC;
3175 	gtoc_cmd.addr_mode   = CD_MSF;		/* not relevant     */
3176 	gtoc_cmd.resp_format = CD_TOC_RAW;	/* raw toc          */
3177 	gtoc_cmd.from_track  = 1;		/* first session    */
3178 	req_size = sizeof(*toc_hdr);
3179 	_lto2b(req_size, gtoc_cmd.data_len);
3180 
3181 	error = scsipi_command(periph,
3182 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
3183 		(void *)buffer,    req_size,
3184 		CDRETRIES, 30000, NULL, flags);
3185 	if (error)
3186 		goto out;
3187 	toc_hdr = (struct scsipi_toc_header *) buffer;
3188 	if (_2btol(toc_hdr->length) > buffer_size - 2) {
3189 #ifdef DIAGNOSTIC
3190 		printf("increase buffersize in mmc_readtrackinfo_cdrom\n");
3191 #endif
3192 		error = ENOBUFS;
3193 		goto out;
3194 	}
3195 
3196 	/* read in complete raw toc */
3197 	req_size = _2btol(toc_hdr->length);
3198 	_lto2b(req_size, gtoc_cmd.data_len);
3199 
3200 	error = scsipi_command(periph,
3201 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
3202 		(void *)buffer,    req_size,
3203 		CDRETRIES, 30000, NULL, flags);
3204 	if (error)
3205 		goto out;
3206 
3207 	toc_hdr = (struct scsipi_toc_header *) buffer;
3208 	rawtoc  = (struct scsipi_toc_rawtoc *) (buffer + 4);
3209 
3210 	track_start      = 0;
3211 	track_end        = 0;
3212 	track_size       = 0;
3213 	last_recorded    = 0;
3214 	next_writable    = 0;
3215 	flags            = 0;
3216 
3217 	last_tracknr     = 1;
3218 	next_track_start = 0;
3219 	track_sessionnr  = MAXTRACK;	/* by definition */
3220 	lead_out         = 0;
3221 
3222 	size = req_size - sizeof(struct scsipi_toc_header) + 1;
3223 	while (size > 0) {
3224 		/* get track start and session end */
3225 		tno       = rawtoc->tno;
3226 		sessionnr = rawtoc->sessionnr;
3227 		adr       = rawtoc->adrcontrol >> 4;
3228 		point     = rawtoc->point;
3229 		tmin      = rawtoc->min;
3230 		tsec      = rawtoc->sec;
3231 		tframe    = rawtoc->frame;
3232 		pmin      = rawtoc->pmin;
3233 		psec      = rawtoc->psec;
3234 		pframe    = rawtoc->pframe;
3235 
3236 		if (tno == 0 && sessionnr && adr == 1) {
3237 			lba = hmsf2lba(0, pmin, psec, pframe);
3238 			if (point == trackinfo->tracknr) {
3239 				track_start = lba;
3240 				track_sessionnr = sessionnr;
3241 			}
3242 			if (point == trackinfo->tracknr + 1) {
3243 				/* estimate size */
3244 				track_size = lba - track_start;
3245 				next_track_start = lba;
3246 			}
3247 			if (point == 0xa2) {
3248 				lead_out = lba;
3249 			}
3250 			if (point <= 0x63) {
3251 				/* CD's ok, DVD are glued */
3252 				last_tracknr = point;
3253 			}
3254 			if (sessionnr == track_sessionnr) {
3255 				last_recorded = lead_out;
3256 			}
3257 		}
3258 		if (tno == 0 && sessionnr && adr == 5) {
3259 			lba = hmsf2lba(0, tmin, tsec, tframe);
3260 			if (sessionnr == track_sessionnr) {
3261 				next_writable = lba;
3262 			}
3263 		}
3264 
3265 		rawtoc++;
3266 		size -= sizeof(struct scsipi_toc_rawtoc);
3267 	}
3268 
3269 	/* process found values; some voodoo */
3270 	/* if no tracksize tracknr is the last of the disc */
3271 	if ((track_size == 0) && last_recorded) {
3272 		track_size = last_recorded - track_start;
3273 	}
3274 	/* if last_recorded < tracksize, tracksize is overestimated */
3275 	if (last_recorded) {
3276 		if (last_recorded - track_start <= track_size) {
3277 			track_size = last_recorded - track_start;
3278 			flags |= MMC_TRACKINFO_LRA_VALID;
3279 		}
3280 	}
3281 	/* check if its a the last track of the sector */
3282 	if (next_writable) {
3283 		if (next_track_start > next_writable)
3284 			flags |= MMC_TRACKINFO_NWA_VALID;
3285 	}
3286 
3287 	/* no flag set -> no values */
3288 	if ((flags & MMC_TRACKINFO_LRA_VALID) == 0)
3289 		last_recorded = 0;
3290 	if ((flags & MMC_TRACKINFO_NWA_VALID) == 0)
3291 		next_writable = 0;
3292 
3293 	/* fill in */
3294 	/* trackinfo->tracknr preserved */
3295 	trackinfo->sessionnr  = track_sessionnr;
3296 	trackinfo->track_mode = 7;	/* data, incremental  */
3297 	trackinfo->data_mode  = 8;	/* 2048 bytes mode1   */
3298 
3299 	trackinfo->flags = flags;
3300 	trackinfo->track_start   = track_start;
3301 	trackinfo->next_writable = next_writable;
3302 	trackinfo->free_blocks   = 0;
3303 	trackinfo->packet_size   = 1;
3304 	trackinfo->track_size    = track_size;
3305 	trackinfo->last_recorded = last_recorded;
3306 
3307 out:
3308 	free(buffer, M_TEMP);
3309 	return error;
3310 
3311 }
3312 
3313 static int
3314 mmc_gettrackinfo_dvdrom(struct scsipi_periph *periph,
3315 			struct mmc_trackinfo *trackinfo)
3316 {
3317 	struct scsipi_read_toc            gtoc_cmd;
3318 	struct scsipi_toc_header         *toc_hdr;
3319 	struct scsipi_toc_formatted      *toc;
3320 	uint32_t tracknr, track_start, track_size;
3321 	uint32_t lba, lead_out;
3322 	const uint32_t buffer_size = 4 * 1024;	/* worst case TOC estimate */
3323 	uint8_t *buffer;
3324 	uint8_t last_tracknr;
3325 	int size, req_size;
3326 	int error, flags;
3327 
3328 
3329 	buffer = malloc(buffer_size, M_TEMP, M_WAITOK);
3330 	/*
3331 	 * Emulate read trackinfo for DVD-ROM. We can't use the raw-TOC as the
3332 	 * CD-ROM emulation uses since the specification tells us that no such
3333 	 * thing is defined for DVD's. The reason for this is due to the large
3334 	 * number of tracks and that would clash with the `magic' values. This
3335 	 * suxs.
3336 	 *
3337 	 * Not all information is present and this presents a problem.
3338 	 * Track starts are known for each track but other values are
3339 	 * deducted.
3340 	 */
3341 
3342 	/* get formatted toc to process, first header to check size */
3343 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK | XS_CTL_SILENT;
3344 	bzero(&gtoc_cmd, sizeof(gtoc_cmd));
3345 	gtoc_cmd.opcode      = READ_TOC;
3346 	gtoc_cmd.addr_mode   = 0;		/* lba's please     */
3347 	gtoc_cmd.resp_format = CD_TOC_FORM;	/* formatted toc    */
3348 	gtoc_cmd.from_track  = 1;		/* first track      */
3349 	req_size = sizeof(*toc_hdr);
3350 	_lto2b(req_size, gtoc_cmd.data_len);
3351 
3352 	error = scsipi_command(periph,
3353 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
3354 		(void *)buffer,    req_size,
3355 		CDRETRIES, 30000, NULL, flags);
3356 	if (error)
3357 		goto out;
3358 	toc_hdr = (struct scsipi_toc_header *) buffer;
3359 	if (_2btol(toc_hdr->length) > buffer_size - 2) {
3360 #ifdef DIAGNOSTIC
3361 		printf("incease buffersize in mmc_readtrackinfo_dvdrom\n");
3362 #endif
3363 		error = ENOBUFS;
3364 		goto out;
3365 	}
3366 
3367 	/* read in complete formatted toc */
3368 	req_size = _2btol(toc_hdr->length);
3369 	_lto2b(req_size, gtoc_cmd.data_len);
3370 
3371 	error = scsipi_command(periph,
3372 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
3373 		(void *)buffer,    req_size,
3374 		CDRETRIES, 30000, NULL, flags);
3375 	if (error)
3376 		goto out;
3377 
3378 	toc_hdr = (struct scsipi_toc_header *)     buffer;
3379 	toc     = (struct scsipi_toc_formatted *) (buffer + 4);
3380 
3381 	/* as in read disc info, all sessions are converted to tracks      */
3382 	/* track 1..  -> offsets, sizes can be (rougly) estimated (16 ECC) */
3383 	/* last track -> we got the size from the lead-out                 */
3384 
3385 	tracknr      = 0;
3386 	last_tracknr = toc_hdr->last;
3387 	track_start  = 0;
3388 	track_size   = 0;
3389 	lead_out     = 0;
3390 
3391 	size = req_size - sizeof(struct scsipi_toc_header) + 1;
3392 	while (size > 0) {
3393 		/* remember, DVD-ROM: tracknr == sessionnr */
3394 		lba     = _4btol(toc->msf_lba);
3395 		tracknr = toc->tracknr;
3396 		if (trackinfo->tracknr == tracknr) {
3397 			track_start = lba;
3398 		}
3399 		if (trackinfo->tracknr == tracknr+1) {
3400 			track_size  = lba - track_start;
3401 			track_size -= 16;	/* link block ? */
3402 		}
3403 		if (tracknr == 0xAA) {
3404 			lead_out = lba;
3405 		}
3406 		toc++;
3407 		size -= sizeof(struct scsipi_toc_formatted);
3408 	}
3409 	if (trackinfo->tracknr == last_tracknr) {
3410 		track_size = lead_out - track_start;
3411 	}
3412 
3413 	/* fill in */
3414 	/* trackinfo->tracknr preserved */
3415 	trackinfo->sessionnr  = trackinfo->tracknr;
3416 	trackinfo->track_mode = 0;	/* unknown */
3417 	trackinfo->data_mode  = 8;	/* 2048 bytes mode1   */
3418 
3419 	trackinfo->flags         = 0;
3420 	trackinfo->track_start   = track_start;
3421 	trackinfo->next_writable = 0;
3422 	trackinfo->free_blocks   = 0;
3423 	trackinfo->packet_size   = 16;	/* standard length 16 blocks ECC */
3424 	trackinfo->track_size    = track_size;
3425 	trackinfo->last_recorded = 0;
3426 
3427 out:
3428 	free(buffer, M_TEMP);
3429 	return error;
3430 }
3431 
3432 static int
3433 mmc_gettrackinfo(struct scsipi_periph *periph,
3434 		 struct mmc_trackinfo *trackinfo)
3435 {
3436 	struct scsipi_read_trackinfo      ti_cmd;
3437 	struct scsipi_read_trackinfo_data ti;
3438 	struct scsipi_get_configuration   gc_cmd;
3439 	struct scsipi_get_conf_data       gc;
3440 	int error, flags;
3441 	int mmc_profile;
3442 
3443 	/* set up SCSI call with track number from trackinfo.tracknr */
3444 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK | XS_CTL_SILENT;
3445 	memset(&ti_cmd, 0, sizeof(ti_cmd));
3446 	ti_cmd.opcode    = READ_TRACKINFO;
3447 	ti_cmd.addr_type = READ_TRACKINFO_ADDR_TRACK;
3448 	ti_cmd.data_len[1] = READ_TRACKINFO_RETURNSIZE;
3449 
3450 	/* trackinfo.tracknr contains number of tracks to query */
3451 	_lto4b(trackinfo->tracknr, ti_cmd.address);
3452 	error = scsipi_command(periph,
3453 		(void *)&ti_cmd, sizeof(ti_cmd),
3454 		(void *)&ti,     READ_TRACKINFO_RETURNSIZE,
3455 		CDRETRIES, 30000, NULL, flags);
3456 
3457 	if (error) {
3458 		/* trackinfo call failed, emulate for cd-rom/dvd-rom */
3459 		/* first determine mmc profile */
3460 		flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK;
3461 		memset(&gc_cmd, 0, sizeof(gc_cmd));
3462 		gc_cmd.opcode = GET_CONFIGURATION;
3463 		_lto2b(GET_CONF_NO_FEATURES_LEN, gc_cmd.data_len);
3464 
3465 		error = scsipi_command(periph,
3466 			(void *)&gc_cmd, sizeof(gc_cmd),
3467 			(void *)&gc,     GET_CONF_NO_FEATURES_LEN,
3468 			CDRETRIES, 30000, NULL, flags);
3469 		if (error)
3470 			return error;
3471 		mmc_profile = _2btol(gc.mmc_profile);
3472 
3473 		/* choose emulation */
3474 		if (mmc_profile == 0x08) /* CD-ROM */
3475 			return mmc_gettrackinfo_cdrom(periph, trackinfo);
3476 		if (mmc_profile == 0x10) /* DVD-ROM */
3477 			return mmc_gettrackinfo_dvdrom(periph, trackinfo);
3478 		/* CD/DVD drive is violating specs */
3479 		return EIO;
3480 	}
3481 
3482 	/* (re)initialise structure */
3483 	memset(trackinfo, 0, sizeof(struct mmc_trackinfo));
3484 
3485 	/* account for short returns screwing up track and session msb */
3486 	if ((ti.data_len[1] | (ti.data_len[0] << 8)) <= 32) {
3487 		ti.track_msb   = 0;
3488 		ti.session_msb = 0;
3489 	}
3490 
3491 	trackinfo->tracknr    = ti.track_lsb   | (ti.track_msb   << 8);
3492 	trackinfo->sessionnr  = ti.session_lsb | (ti.session_msb << 8);
3493 	trackinfo->track_mode = ti.track_info_1 & 0xf;
3494 	trackinfo->data_mode  = ti.track_info_2 & 0xf;
3495 
3496 	flags = 0;
3497 	if (ti.track_info_1 & 0x10)
3498 		flags |= MMC_TRACKINFO_COPY;
3499 	if (ti.track_info_1 & 0x20)
3500 		flags |= MMC_TRACKINFO_DAMAGED;
3501 	if (ti.track_info_2 & 0x10)
3502 		flags |= MMC_TRACKINFO_FIXED_PACKET;
3503 	if (ti.track_info_2 & 0x20)
3504 		flags |= MMC_TRACKINFO_INCREMENTAL;
3505 	if (ti.track_info_2 & 0x40)
3506 		flags |= MMC_TRACKINFO_BLANK;
3507 	if (ti.track_info_2 & 0x80)
3508 		flags |= MMC_TRACKINFO_RESERVED;
3509 	if (ti.data_valid   & 0x01)
3510 		flags |= MMC_TRACKINFO_NWA_VALID;
3511 	if (ti.data_valid   & 0x02)
3512 		flags |= MMC_TRACKINFO_LRA_VALID;
3513 	if ((trackinfo->track_mode & (3<<2)) == 4)		/* 01xxb */
3514 		flags |= MMC_TRACKINFO_DATA;
3515 	if ((trackinfo->track_mode & (1<<2)) == 0) {		/* x0xxb */
3516 		flags |= MMC_TRACKINFO_AUDIO;
3517 		if (trackinfo->track_mode & (1<<3))		/* 10xxb */
3518 			flags |= MMC_TRACKINFO_AUDIO_4CHAN;
3519 		if (trackinfo->track_mode & 1)			/* xxx1b */
3520 			flags |= MMC_TRACKINFO_PRE_EMPH;
3521 	}
3522 
3523 	trackinfo->flags = flags;
3524 	trackinfo->track_start    = _4btol(ti.track_start);
3525 	trackinfo->next_writable  = _4btol(ti.next_writable);
3526 	trackinfo->free_blocks    = _4btol(ti.free_blocks);
3527 	trackinfo->packet_size    = _4btol(ti.packet_size);
3528 	trackinfo->track_size     = _4btol(ti.track_size);
3529 	trackinfo->last_recorded  = _4btol(ti.last_recorded);
3530 
3531 	return 0;
3532 }
3533