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