xref: /netbsd-src/sys/dev/scsipi/cd.c (revision a30f264f2a5f410ffefcc55600a9238b3a0c935c)
1 /*	$NetBSD: cd.c,v 1.234 2005/12/21 13:11:27 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  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *        This product includes software developed by the NetBSD
21  *        Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 /*
40  * Originally written by Julian Elischer (julian@tfs.com)
41  * for TRW Financial Systems for use under the MACH(2.5) operating system.
42  *
43  * TRW Financial Systems, in accordance with their agreement with Carnegie
44  * Mellon University, makes this software available to CMU to distribute
45  * or use in any manner that they see fit as long as this message is kept with
46  * the software. For this reason TFS also grants any other persons or
47  * organisations permission to use or modify this software.
48  *
49  * TFS supplies this software to be publicly redistributed
50  * on the understanding that TFS is not responsible for the correct
51  * functioning of this software in any circumstances.
52  *
53  * Ported to run under 386BSD by Julian Elischer (julian@tfs.com) Sept 1992
54  */
55 
56 #include <sys/cdefs.h>
57 __KERNEL_RCSID(0, "$NetBSD: cd.c,v 1.234 2005/12/21 13:11:27 reinoud Exp $");
58 
59 #include "rnd.h"
60 
61 #include <sys/param.h>
62 #include <sys/systm.h>
63 #include <sys/kernel.h>
64 #include <sys/file.h>
65 #include <sys/stat.h>
66 #include <sys/ioctl.h>
67 #include <sys/buf.h>
68 #include <sys/bufq.h>
69 #include <sys/uio.h>
70 #include <sys/malloc.h>
71 #include <sys/errno.h>
72 #include <sys/device.h>
73 #include <sys/disklabel.h>
74 #include <sys/disk.h>
75 #include <sys/cdio.h>
76 #include <sys/dvdio.h>
77 #include <sys/scsiio.h>
78 #include <sys/proc.h>
79 #include <sys/conf.h>
80 #include <sys/vnode.h>
81 #if NRND > 0
82 #include <sys/rnd.h>
83 #endif
84 
85 #include <dev/scsipi/scsi_spc.h>
86 #include <dev/scsipi/scsipi_all.h>
87 #include <dev/scsipi/scsipi_cd.h>
88 #include <dev/scsipi/scsipi_disk.h>	/* rw_big and start_stop come */
89 #include <dev/scsipi/scsi_all.h>
90 					/* from there */
91 #include <dev/scsipi/scsi_disk.h>	/* rw comes from there */
92 #include <dev/scsipi/scsipiconf.h>
93 #include <dev/scsipi/scsipi_base.h>
94 #include <dev/scsipi/cdvar.h>
95 
96 #define	CDUNIT(z)			DISKUNIT(z)
97 #define	CDPART(z)			DISKPART(z)
98 #define	CDMINOR(unit, part)		DISKMINOR(unit, part)
99 #define	MAKECDDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)
100 
101 #define MAXTRACK	99
102 #define CD_BLOCK_OFFSET	150
103 #define CD_FRAMES	75
104 #define CD_SECS		60
105 
106 #define CD_TOC_FORM	0	/* formatted TOC, exposed to userland     */
107 #define CD_TOC_MSINFO	1	/* multi-session info			  */
108 #define CD_TOC_RAW	2	/* raw TOC as on disc, unprocessed	  */
109 #define CD_TOC_PMA	3	/* PMA, used as intermediate (rare use)   */
110 #define CD_TOC_ATIP	4	/* pressed space of recordable		  */
111 #define CD_TOC_CDTEXT	5	/* special CD-TEXT, rarely used		  */
112 
113 struct cd_formatted_toc {
114 	struct ioc_toc_header header;
115 	struct cd_toc_entry entries[MAXTRACK+1]; /* One extra for the */
116 						 /* leadout */
117 };
118 
119 static void	cdstart(struct scsipi_periph *);
120 static void	cdrestart(void *);
121 static void	cdminphys(struct buf *);
122 static void	cdgetdefaultlabel(struct cd_softc *, struct disklabel *);
123 static void	cdgetdisklabel(struct cd_softc *);
124 static void	cddone(struct scsipi_xfer *, int);
125 static void	cdbounce(struct buf *);
126 static int	cd_interpret_sense(struct scsipi_xfer *);
127 static u_long	cd_size(struct cd_softc *, int);
128 static int	cd_play(struct cd_softc *, int, int);
129 static int	cd_play_tracks(struct cd_softc *, int, int, int, int);
130 static int	cd_play_msf(struct cd_softc *, int, int, int, int, int, int);
131 static int	cd_pause(struct cd_softc *, int);
132 static int	cd_reset(struct cd_softc *);
133 static int	cd_read_subchannel(struct cd_softc *, int, int, int,
134 		    struct cd_sub_channel_info *, int, int);
135 static int	cd_read_toc(struct cd_softc *, int, int, int, void *, int, int, int);
136 static int	cd_get_parms(struct cd_softc *, int);
137 static int	cd_load_toc(struct cd_softc *, int, struct cd_formatted_toc *, int);
138 static int	cdreadmsaddr(struct cd_softc *, int *);
139 
140 static int	dvd_auth(struct cd_softc *, dvd_authinfo *);
141 static int	dvd_read_physical(struct cd_softc *, dvd_struct *);
142 static int	dvd_read_copyright(struct cd_softc *, dvd_struct *);
143 static int	dvd_read_disckey(struct cd_softc *, dvd_struct *);
144 static int	dvd_read_bca(struct cd_softc *, dvd_struct *);
145 static int	dvd_read_manufact(struct cd_softc *, dvd_struct *);
146 static int	dvd_read_struct(struct cd_softc *, dvd_struct *);
147 
148 static int	cd_mode_sense(struct cd_softc *, u_int8_t, void *, size_t, int,
149 		    int, int *);
150 static int	cd_mode_select(struct cd_softc *, u_int8_t, void *, size_t,
151 		    int, int);
152 static int	cd_setchan(struct cd_softc *, int, int, int, int, int);
153 static int	cd_getvol(struct cd_softc *, struct ioc_vol *, int);
154 static int	cd_setvol(struct cd_softc *, const struct ioc_vol *, int);
155 static int	cd_set_pa_immed(struct cd_softc *, int);
156 static int	cd_load_unload(struct cd_softc *, struct ioc_load_unload *);
157 static int	cd_setblksize(struct cd_softc *);
158 
159 static int	cdmatch(struct device *, struct cfdata *, void *);
160 static void	cdattach(struct device *, struct device *, void *);
161 static int	cdactivate(struct device *, enum devact);
162 static int	cddetach(struct device *, int);
163 
164 CFATTACH_DECL(cd, sizeof(struct cd_softc), cdmatch, cdattach, cddetach,
165     cdactivate);
166 
167 extern struct cfdriver cd_cd;
168 
169 static const struct scsipi_inquiry_pattern cd_patterns[] = {
170 	{T_CDROM, T_REMOV,
171 	 "",         "",                 ""},
172 	{T_WORM, T_REMOV,
173 	 "",         "",                 ""},
174 #if 0
175 	{T_CDROM, T_REMOV, /* more luns */
176 	 "PIONEER ", "CD-ROM DRM-600  ", ""},
177 #endif
178 	{T_DIRECT, T_REMOV,
179 	 "NEC                 CD-ROM DRIVE:260", "", ""},
180 };
181 
182 static dev_type_open(cdopen);
183 static dev_type_close(cdclose);
184 static dev_type_read(cdread);
185 static dev_type_write(cdwrite);
186 static dev_type_ioctl(cdioctl);
187 static dev_type_strategy(cdstrategy);
188 static dev_type_dump(cddump);
189 static dev_type_size(cdsize);
190 
191 const struct bdevsw cd_bdevsw = {
192 	cdopen, cdclose, cdstrategy, cdioctl, cddump, cdsize, D_DISK
193 };
194 
195 const struct cdevsw cd_cdevsw = {
196 	cdopen, cdclose, cdread, cdwrite, cdioctl,
197 	nostop, notty, nopoll, nommap, nokqfilter, D_DISK
198 };
199 
200 static struct dkdriver cddkdriver = { cdstrategy };
201 
202 static const struct scsipi_periphsw cd_switch = {
203 	cd_interpret_sense,	/* use our error handler first */
204 	cdstart,		/* we have a queue, which is started by this */
205 	NULL,			/* we do not have an async handler */
206 	cddone,			/* deal with stats at interrupt time */
207 };
208 
209 /*
210  * The routine called by the low level scsi routine when it discovers
211  * A device suitable for this driver
212  */
213 static int
214 cdmatch(struct device *parent, struct cfdata *match, void *aux)
215 {
216 	struct scsipibus_attach_args *sa = aux;
217 	int priority;
218 
219 	(void)scsipi_inqmatch(&sa->sa_inqbuf,
220 	    cd_patterns, sizeof(cd_patterns) / sizeof(cd_patterns[0]),
221 	    sizeof(cd_patterns[0]), &priority);
222 
223 	return (priority);
224 }
225 
226 static void
227 cdattach(struct device *parent, struct device *self, void *aux)
228 {
229 	struct cd_softc *cd = (void *)self;
230 	struct scsipibus_attach_args *sa = aux;
231 	struct scsipi_periph *periph = sa->sa_periph;
232 
233 	SC_DEBUG(periph, SCSIPI_DB2, ("cdattach: "));
234 
235 	lockinit(&cd->sc_lock, PRIBIO | PCATCH, "cdlock", 0, 0);
236 
237 	if (scsipi_periph_bustype(sa->sa_periph) == SCSIPI_BUSTYPE_SCSI &&
238 	    periph->periph_version == 0)
239 		cd->flags |= CDF_ANCIENT;
240 
241 	bufq_alloc(&cd->buf_queue, "disksort", BUFQ_SORT_RAWBLOCK);
242 
243 	callout_init(&cd->sc_callout);
244 
245 	/*
246 	 * Store information needed to contact our base driver
247 	 */
248 	cd->sc_periph = periph;
249 
250 	periph->periph_dev = &cd->sc_dev;
251 	periph->periph_switch = &cd_switch;
252 
253 	/*
254 	 * Increase our openings to the maximum-per-periph
255 	 * supported by the adapter.  This will either be
256 	 * clamped down or grown by the adapter if necessary.
257 	 */
258 	periph->periph_openings =
259 	    SCSIPI_CHAN_MAX_PERIPH(periph->periph_channel);
260 	periph->periph_flags |= PERIPH_GROW_OPENINGS;
261 
262 	/*
263 	 * Initialize and attach the disk structure.
264 	 */
265   	cd->sc_dk.dk_driver = &cddkdriver;
266 	cd->sc_dk.dk_name = cd->sc_dev.dv_xname;
267 	disk_attach(&cd->sc_dk);
268 
269 	printf("\n");
270 
271 #if NRND > 0
272 	rnd_attach_source(&cd->rnd_source, cd->sc_dev.dv_xname,
273 			  RND_TYPE_DISK, 0);
274 #endif
275 }
276 
277 static int
278 cdactivate(struct device *self, enum devact act)
279 {
280 	int rv = 0;
281 
282 	switch (act) {
283 	case DVACT_ACTIVATE:
284 		rv = EOPNOTSUPP;
285 		break;
286 
287 	case DVACT_DEACTIVATE:
288 		/*
289 		 * Nothing to do; we key off the device's DVF_ACTIVE.
290 		 */
291 		break;
292 	}
293 	return (rv);
294 }
295 
296 static int
297 cddetach(struct device *self, int flags)
298 {
299 	struct cd_softc *cd = (struct cd_softc *) self;
300 	int s, bmaj, cmaj, i, mn;
301 
302 	/* locate the major number */
303 	bmaj = bdevsw_lookup_major(&cd_bdevsw);
304 	cmaj = cdevsw_lookup_major(&cd_cdevsw);
305 
306 	/* Nuke the vnodes for any open instances */
307 	for (i = 0; i < MAXPARTITIONS; i++) {
308 		mn = CDMINOR(self->dv_unit, i);
309 		vdevgone(bmaj, mn, mn, VBLK);
310 		vdevgone(cmaj, mn, mn, VCHR);
311 	}
312 
313 	/* kill any pending restart */
314 	callout_stop(&cd->sc_callout);
315 
316 	s = splbio();
317 
318 	/* Kill off any queued buffers. */
319 	bufq_drain(cd->buf_queue);
320 
321 	bufq_free(cd->buf_queue);
322 
323 	/* Kill off any pending commands. */
324 	scsipi_kill_pending(cd->sc_periph);
325 
326 	splx(s);
327 
328 	lockmgr(&cd->sc_lock, LK_DRAIN, 0);
329 
330 	/* Detach from the disk list. */
331 	disk_detach(&cd->sc_dk);
332 
333 #if 0
334 	/* Get rid of the shutdown hook. */
335 	if (cd->sc_sdhook != NULL)
336 		shutdownhook_disestablish(cd->sc_sdhook);
337 #endif
338 
339 #if NRND > 0
340 	/* Unhook the entropy source. */
341 	rnd_detach_source(&cd->rnd_source);
342 #endif
343 
344 	return (0);
345 }
346 
347 /*
348  * open the device. Make sure the partition info is a up-to-date as can be.
349  */
350 static int
351 cdopen(dev_t dev, int flag, int fmt, struct lwp *l)
352 {
353 	struct cd_softc *cd;
354 	struct scsipi_periph *periph;
355 	struct scsipi_adapter *adapt;
356 	int unit, part;
357 	int error;
358 	int rawpart;
359 
360 	unit = CDUNIT(dev);
361 	if (unit >= cd_cd.cd_ndevs)
362 		return (ENXIO);
363 	cd = cd_cd.cd_devs[unit];
364 	if (cd == NULL)
365 		return (ENXIO);
366 
367 	periph = cd->sc_periph;
368 	adapt = periph->periph_channel->chan_adapter;
369 	part = CDPART(dev);
370 
371 	SC_DEBUG(periph, SCSIPI_DB1,
372 	    ("cdopen: dev=0x%x (unit %d (of %d), partition %d)\n", dev, unit,
373 	    cd_cd.cd_ndevs, CDPART(dev)));
374 
375 	/*
376 	 * If this is the first open of this device, add a reference
377 	 * to the adapter.
378 	 */
379 	if (cd->sc_dk.dk_openmask == 0 &&
380 	    (error = scsipi_adapter_addref(adapt)) != 0)
381 		return (error);
382 
383 	if ((error = lockmgr(&cd->sc_lock, LK_EXCLUSIVE, NULL)) != 0)
384 		goto bad4;
385 
386 	rawpart = (part == RAW_PART && fmt == S_IFCHR);
387 	if ((periph->periph_flags & PERIPH_OPEN) != 0) {
388 		/*
389 		 * If any partition is open, but the disk has been invalidated,
390 		 * disallow further opens.
391 		 */
392 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0 &&
393 			!rawpart) {
394 			error = EIO;
395 			goto bad3;
396 		}
397 	} else {
398 		int silent;
399 
400 		if (rawpart)
401 			silent = XS_CTL_SILENT;
402 		else
403 			silent = 0;
404 
405 		/* Check that it is still responding and ok. */
406 		error = scsipi_test_unit_ready(periph,
407 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE |
408 		    silent);
409 
410 		/*
411 		 * Start the pack spinning if necessary. Always allow the
412 		 * raw parition to be opened, for raw IOCTLs. Data transfers
413 		 * will check for SDEV_MEDIA_LOADED.
414 		 */
415 		if (error == EIO) {
416 			int error2;
417 
418 			error2 = scsipi_start(periph, SSS_START, silent);
419 			switch (error2) {
420 			case 0:
421 				error = 0;
422 				break;
423 			case EIO:
424 			case EINVAL:
425 				break;
426 			default:
427 				error = error2;
428 				break;
429 			}
430 		}
431 		if (error) {
432 			if (rawpart)
433 				goto out;
434 			goto bad3;
435 		}
436 
437 		periph->periph_flags |= PERIPH_OPEN;
438 
439 		/* Lock the pack in. */
440 		error = scsipi_prevent(periph, SPAMR_PREVENT_DT,
441 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE);
442 		SC_DEBUG(periph, SCSIPI_DB1,
443 		    ("cdopen: scsipi_prevent, error=%d\n", error));
444 		if (error) {
445 			if (rawpart)
446 				goto out;
447 			goto bad;
448 		}
449 
450 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
451 			/* Load the physical device parameters. */
452 			if (cd_get_parms(cd, 0) != 0) {
453 				if (rawpart)
454 					goto out;
455 				error = ENXIO;
456 				goto bad;
457 			}
458 			periph->periph_flags |= PERIPH_MEDIA_LOADED;
459 			SC_DEBUG(periph, SCSIPI_DB3, ("Params loaded "));
460 
461 			/* Fabricate a disk label. */
462 			cdgetdisklabel(cd);
463 			SC_DEBUG(periph, SCSIPI_DB3, ("Disklabel fabricated "));
464 		}
465 	}
466 
467 	/* Check that the partition exists. */
468 	if (part != RAW_PART &&
469 	    (part >= cd->sc_dk.dk_label->d_npartitions ||
470 	    cd->sc_dk.dk_label->d_partitions[part].p_fstype == FS_UNUSED)) {
471 		error = ENXIO;
472 		goto bad;
473 	}
474 
475 out:	/* Insure only one open at a time. */
476 	switch (fmt) {
477 	case S_IFCHR:
478 		cd->sc_dk.dk_copenmask |= (1 << part);
479 		break;
480 	case S_IFBLK:
481 		cd->sc_dk.dk_bopenmask |= (1 << part);
482 		break;
483 	}
484 	cd->sc_dk.dk_openmask =
485 	    cd->sc_dk.dk_copenmask | cd->sc_dk.dk_bopenmask;
486 
487 	SC_DEBUG(periph, SCSIPI_DB3, ("open complete\n"));
488 	lockmgr(&cd->sc_lock, LK_RELEASE, NULL);
489 	return (0);
490 
491 	periph->periph_flags &= ~PERIPH_MEDIA_LOADED;
492 
493 bad:
494 	if (cd->sc_dk.dk_openmask == 0) {
495 		scsipi_prevent(periph, SPAMR_ALLOW,
496 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE);
497 		periph->periph_flags &= ~PERIPH_OPEN;
498 	}
499 
500 bad3:
501 	lockmgr(&cd->sc_lock, LK_RELEASE, NULL);
502 bad4:
503 	if (cd->sc_dk.dk_openmask == 0)
504 		scsipi_adapter_delref(adapt);
505 	return (error);
506 }
507 
508 /*
509  * close the device.. only called if we are the LAST
510  * occurence of an open device
511  */
512 static int
513 cdclose(dev_t dev, int flag, int fmt, struct lwp *l)
514 {
515 	struct cd_softc *cd = cd_cd.cd_devs[CDUNIT(dev)];
516 	struct scsipi_periph *periph = cd->sc_periph;
517 	struct scsipi_adapter *adapt = periph->periph_channel->chan_adapter;
518 	int part = CDPART(dev);
519 	int error;
520 
521 	if ((error = lockmgr(&cd->sc_lock, LK_EXCLUSIVE, NULL)) != 0)
522 		return (error);
523 
524 	switch (fmt) {
525 	case S_IFCHR:
526 		cd->sc_dk.dk_copenmask &= ~(1 << part);
527 		break;
528 	case S_IFBLK:
529 		cd->sc_dk.dk_bopenmask &= ~(1 << part);
530 		break;
531 	}
532 	cd->sc_dk.dk_openmask =
533 	    cd->sc_dk.dk_copenmask | cd->sc_dk.dk_bopenmask;
534 
535 	if (cd->sc_dk.dk_openmask == 0) {
536 		scsipi_wait_drain(periph);
537 
538 		scsipi_prevent(periph, SPAMR_ALLOW,
539 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE |
540 		    XS_CTL_IGNORE_NOT_READY);
541 		periph->periph_flags &= ~PERIPH_OPEN;
542 
543 		scsipi_wait_drain(periph);
544 
545 		scsipi_adapter_delref(adapt);
546 	}
547 
548 	lockmgr(&cd->sc_lock, LK_RELEASE, NULL);
549 	return (0);
550 }
551 
552 /*
553  * Actually translate the requested transfer into one the physical driver can
554  * understand.  The transfer is described by a buf and will include only one
555  * physical transfer.
556  */
557 static void
558 cdstrategy(struct buf *bp)
559 {
560 	struct cd_softc *cd = cd_cd.cd_devs[CDUNIT(bp->b_dev)];
561 	struct disklabel *lp;
562 	struct scsipi_periph *periph = cd->sc_periph;
563 	daddr_t blkno;
564 	int s;
565 
566 	SC_DEBUG(cd->sc_periph, SCSIPI_DB2, ("cdstrategy "));
567 	SC_DEBUG(cd->sc_periph, SCSIPI_DB1,
568 	    ("%d bytes @ blk %" PRId64 "\n", bp->b_bcount, bp->b_blkno));
569 	/*
570 	 * If the device has been made invalid, error out
571 	 * maybe the media changed
572 	 */
573 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
574 		if (periph->periph_flags & PERIPH_OPEN)
575 			bp->b_error = EIO;
576 		else
577 			bp->b_error = ENODEV;
578 		goto bad;
579 	}
580 
581 	lp = cd->sc_dk.dk_label;
582 
583 	/*
584 	 * The transfer must be a whole number of blocks, offset must not
585 	 * be negative.
586 	 */
587 	if ((bp->b_bcount % lp->d_secsize) != 0 ||
588 	    bp->b_blkno < 0 ) {
589 		bp->b_error = EINVAL;
590 		goto bad;
591 	}
592 	/*
593 	 * If it's a null transfer, return immediately
594 	 */
595 	if (bp->b_bcount == 0)
596 		goto done;
597 
598 	/*
599 	 * Do bounds checking, adjust transfer. if error, process.
600 	 * If end of partition, just return.
601 	 */
602 	if (CDPART(bp->b_dev) == RAW_PART) {
603 		if (bounds_check_with_mediasize(bp, DEV_BSIZE,
604 		    cd->params.disksize512) <= 0)
605 			goto done;
606 	} else {
607 		if (bounds_check_with_label(&cd->sc_dk, bp,
608 		    (cd->flags & (CDF_WLABEL|CDF_LABELLING)) != 0) <= 0)
609 			goto done;
610 	}
611 
612 	/*
613 	 * Now convert the block number to absolute and put it in
614 	 * terms of the device's logical block size.
615 	 */
616 	blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE);
617 	if (CDPART(bp->b_dev) != RAW_PART)
618 		blkno += lp->d_partitions[CDPART(bp->b_dev)].p_offset;
619 
620 	bp->b_rawblkno = blkno;
621 
622 	/*
623 	 * If the disklabel sector size does not match the device
624 	 * sector size we may need to do some extra work.
625 	 */
626 	if (lp->d_secsize != cd->params.blksize) {
627 
628 		/*
629 		 * If the xfer is not a multiple of the device block size
630 		 * or it is not block aligned, we need to bounce it.
631 		 */
632 		if ((bp->b_bcount % cd->params.blksize) != 0 ||
633 			((blkno * lp->d_secsize) % cd->params.blksize) != 0) {
634 			struct buf *nbp;
635 			void *bounce = NULL;
636 			long count;
637 
638 			if ((bp->b_flags & B_READ) == 0) {
639 
640 				/* XXXX We don't support bouncing writes. */
641 				bp->b_error = EACCES;
642 				goto bad;
643 			}
644 			count = ((blkno * lp->d_secsize) % cd->params.blksize);
645 			/* XXX Store starting offset in bp->b_rawblkno */
646 			bp->b_rawblkno = count;
647 
648 			count += bp->b_bcount;
649 			count = roundup(count, cd->params.blksize);
650 
651 			blkno = ((blkno * lp->d_secsize) / cd->params.blksize);
652 			s = splbio();
653 			nbp = pool_get(&bufpool, PR_NOWAIT);
654 			splx(s);
655 			if (!nbp) {
656 				/* No memory -- fail the iop. */
657 				bp->b_error = ENOMEM;
658 				goto bad;
659 			}
660 			bounce = malloc(count, M_DEVBUF, M_NOWAIT);
661 			if (!bounce) {
662 				/* No memory -- fail the iop. */
663 				s = splbio();
664 				pool_put(&bufpool, nbp);
665 				splx(s);
666 				bp->b_error = ENOMEM;
667 				goto bad;
668 			}
669 
670 			/* Set up the IOP to the bounce buffer. */
671 			BUF_INIT(nbp);
672 			nbp->b_error = 0;
673 			nbp->b_proc = bp->b_proc;
674 			nbp->b_vp = NULLVP;
675 
676 			nbp->b_bcount = count;
677 			nbp->b_bufsize = count;
678 			nbp->b_data = bounce;
679 
680 			nbp->b_rawblkno = blkno;
681 
682 			/* We need to do a read-modify-write operation */
683 			nbp->b_flags = bp->b_flags | B_READ | B_CALL;
684 			nbp->b_iodone = cdbounce;
685 
686 			/* Put ptr to orig buf in b_private and use new buf */
687 			nbp->b_private = bp;
688 
689 			BIO_COPYPRIO(nbp, bp);
690 
691 			bp = nbp;
692 
693 		} else {
694 			/* Xfer is aligned -- just adjust the start block */
695 			bp->b_rawblkno = (blkno * lp->d_secsize) /
696 				cd->params.blksize;
697 		}
698 	}
699 	s = splbio();
700 
701 	/*
702 	 * Place it in the queue of disk activities for this disk.
703 	 *
704 	 * XXX Only do disksort() if the current operating mode does not
705 	 * XXX include tagged queueing.
706 	 */
707 	BUFQ_PUT(cd->buf_queue, bp);
708 
709 	/*
710 	 * Tell the device to get going on the transfer if it's
711 	 * not doing anything, otherwise just wait for completion
712 	 */
713 	cdstart(cd->sc_periph);
714 
715 	splx(s);
716 	return;
717 
718 bad:
719 	bp->b_flags |= B_ERROR;
720 done:
721 	/*
722 	 * Correctly set the buf to indicate a completed xfer
723 	 */
724 	bp->b_resid = bp->b_bcount;
725 	biodone(bp);
726 }
727 
728 /*
729  * cdstart looks to see if there is a buf waiting for the device
730  * and that the device is not already busy. If both are true,
731  * It deques the buf and creates a scsi command to perform the
732  * transfer in the buf. The transfer request will call scsipi_done
733  * on completion, which will in turn call this routine again
734  * so that the next queued transfer is performed.
735  * The bufs are queued by the strategy routine (cdstrategy)
736  *
737  * This routine is also called after other non-queued requests
738  * have been made of the scsi driver, to ensure that the queue
739  * continues to be drained.
740  *
741  * must be called at the correct (highish) spl level
742  * cdstart() is called at splbio from cdstrategy, cdrestart and scsipi_done
743  */
744 static void
745 cdstart(struct scsipi_periph *periph)
746 {
747 	struct cd_softc *cd = (void *)periph->periph_dev;
748 	struct buf *bp = 0;
749 	struct scsipi_rw_10 cmd_big;
750 	struct scsi_rw_6 cmd_small;
751 	struct scsipi_generic *cmdp;
752 	struct scsipi_xfer *xs;
753 	int flags, nblks, cmdlen, error;
754 
755 	SC_DEBUG(periph, SCSIPI_DB2, ("cdstart "));
756 	/*
757 	 * Check if the device has room for another command
758 	 */
759 	while (periph->periph_active < periph->periph_openings) {
760 		/*
761 		 * there is excess capacity, but a special waits
762 		 * It'll need the adapter as soon as we clear out of the
763 		 * way and let it run (user level wait).
764 		 */
765 		if (periph->periph_flags & PERIPH_WAITING) {
766 			periph->periph_flags &= ~PERIPH_WAITING;
767 			wakeup((caddr_t)periph);
768 			return;
769 		}
770 
771 		/*
772 		 * If the device has become invalid, abort all the
773 		 * reads and writes until all files have been closed and
774 		 * re-opened
775 		 */
776 		if (__predict_false(
777 		    (periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)) {
778 			if ((bp = BUFQ_GET(cd->buf_queue)) != NULL) {
779 				bp->b_error = EIO;
780 				bp->b_flags |= B_ERROR;
781 				bp->b_resid = bp->b_bcount;
782 				biodone(bp);
783 				continue;
784 			} else {
785 				return;
786 			}
787 		}
788 
789 		/*
790 		 * See if there is a buf with work for us to do..
791 		 */
792 		if ((bp = BUFQ_PEEK(cd->buf_queue)) == NULL)
793 			return;
794 
795 		/*
796 		 * We have a buf, now we should make a command.
797 		 */
798 
799 		nblks = howmany(bp->b_bcount, cd->params.blksize);
800 
801 		/*
802 		 *  Fill out the scsi command.  If the transfer will
803 		 *  fit in a "small" cdb, use it.
804 		 */
805 		if (((bp->b_rawblkno & 0x1fffff) == bp->b_rawblkno) &&
806 		    ((nblks & 0xff) == nblks) &&
807 		    !(periph->periph_quirks & PQUIRK_ONLYBIG)) {
808 			/*
809 			 * We can fit in a small cdb.
810 			 */
811 			memset(&cmd_small, 0, sizeof(cmd_small));
812 			cmd_small.opcode = (bp->b_flags & B_READ) ?
813 			    SCSI_READ_6_COMMAND : SCSI_WRITE_6_COMMAND;
814 			_lto3b(bp->b_rawblkno, cmd_small.addr);
815 			cmd_small.length = nblks & 0xff;
816 			cmdlen = sizeof(cmd_small);
817 			cmdp = (struct scsipi_generic *)&cmd_small;
818 		} else {
819 			/*
820 			 * Need a large cdb.
821 			 */
822 			memset(&cmd_big, 0, sizeof(cmd_big));
823 			cmd_big.opcode = (bp->b_flags & B_READ) ?
824 			    READ_10 : WRITE_10;
825 			_lto4b(bp->b_rawblkno, cmd_big.addr);
826 			_lto2b(nblks, cmd_big.length);
827 			cmdlen = sizeof(cmd_big);
828 			cmdp = (struct scsipi_generic *)&cmd_big;
829 		}
830 
831 		/* Instrumentation. */
832 		disk_busy(&cd->sc_dk);
833 
834 		/*
835 		 * Figure out what flags to use.
836 		 */
837 		flags = XS_CTL_NOSLEEP|XS_CTL_ASYNC|XS_CTL_SIMPLE_TAG;
838 		if (bp->b_flags & B_READ)
839 			flags |= XS_CTL_DATA_IN;
840 		else
841 			flags |= XS_CTL_DATA_OUT;
842 
843 		/*
844 		 * Call the routine that chats with the adapter.
845 		 * Note: we cannot sleep as we may be an interrupt
846 		 */
847 		xs = scsipi_make_xs(periph, cmdp, cmdlen,
848 		    (u_char *)bp->b_data, bp->b_bcount,
849 		    CDRETRIES, 30000, bp, flags);
850 		if (__predict_false(xs == NULL)) {
851 			/*
852 			 * out of memory. Keep this buffer in the queue, and
853 			 * retry later.
854 			 */
855 			callout_reset(&cd->sc_callout, hz / 2, cdrestart,
856 			    periph);
857 			return;
858 		}
859 		/*
860 		 * need to dequeue the buffer before queuing the command,
861 		 * because cdstart may be called recursively from the
862 		 * HBA driver
863 		 */
864 #ifdef DIAGNOSTIC
865 		if (BUFQ_GET(cd->buf_queue) != bp)
866 			panic("cdstart(): dequeued wrong buf");
867 #else
868 		BUFQ_GET(cd->buf_queue);
869 #endif
870 		error = scsipi_execute_xs(xs);
871 		/* with a scsipi_xfer preallocated, scsipi_command can't fail */
872 		KASSERT(error == 0);
873 	}
874 }
875 
876 static void
877 cdrestart(void *v)
878 {
879 	int s = splbio();
880 	cdstart((struct scsipi_periph *)v);
881 	splx(s);
882 }
883 
884 static void
885 cddone(struct scsipi_xfer *xs, int error)
886 {
887 	struct cd_softc *cd = (void *)xs->xs_periph->periph_dev;
888 	struct buf *bp = xs->bp;
889 
890 	if (bp) {
891 		bp->b_error = error;
892 		bp->b_resid = xs->resid;
893 		if (error)
894 			bp->b_flags |= B_ERROR;
895 
896 		disk_unbusy(&cd->sc_dk, bp->b_bcount - bp->b_resid,
897 		    (bp->b_flags & B_READ));
898 #if NRND > 0
899 		rnd_add_uint32(&cd->rnd_source, bp->b_rawblkno);
900 #endif
901 
902 		biodone(bp);
903 	}
904 }
905 
906 static void
907 cdbounce(struct buf *bp)
908 {
909 	struct buf *obp = (struct buf *)bp->b_private;
910 
911 	if (bp->b_flags & B_ERROR) {
912 		/* EEK propagate the error and free the memory */
913 		goto done;
914 	}
915 	if (obp->b_flags & B_READ) {
916 		/* Copy data to the final destination and free the buf. */
917 		memcpy(obp->b_data, bp->b_data+obp->b_rawblkno,
918 			obp->b_bcount);
919 	} else {
920 		/*
921 		 * XXXX This is a CD-ROM -- READ ONLY -- why do we bother with
922 		 * XXXX any of this write stuff?
923 		 */
924 		if (bp->b_flags & B_READ) {
925 			struct cd_softc *cd = cd_cd.cd_devs[CDUNIT(bp->b_dev)];
926 			struct buf *nbp;
927 			int s;
928 
929 			/* Read part of RMW complete. */
930 			memcpy(bp->b_data+obp->b_rawblkno, obp->b_data,
931 				obp->b_bcount);
932 
933 			s = splbio();
934 
935 			/* We need to alloc a new buf. */
936 			nbp = pool_get(&bufpool, PR_NOWAIT);
937 			if (!nbp) {
938 				splx(s);
939 				/* No buf available. */
940 				bp->b_flags |= B_ERROR;
941 				bp->b_error = ENOMEM;
942 				bp->b_resid = bp->b_bcount;
943 			}
944 
945 			/* Set up the IOP to the bounce buffer. */
946 			BUF_INIT(nbp);
947 			nbp->b_error = 0;
948 			nbp->b_proc = bp->b_proc;
949 			nbp->b_vp = NULLVP;
950 
951 			nbp->b_bcount = bp->b_bcount;
952 			nbp->b_bufsize = bp->b_bufsize;
953 			nbp->b_data = bp->b_data;
954 
955 			nbp->b_rawblkno = bp->b_rawblkno;
956 
957 			/* We need to do a read-modify-write operation */
958 			nbp->b_flags = obp->b_flags | B_CALL;
959 			nbp->b_iodone = cdbounce;
960 
961 			/* Put ptr to orig buf in b_private and use new buf */
962 			nbp->b_private = obp;
963 
964 			/*
965 			 * Place it in the queue of disk activities for this
966 			 * disk.
967 			 *
968 			 * XXX Only do disksort() if the current operating mode
969 			 * XXX does not include tagged queueing.
970 			 */
971 			BUFQ_PUT(cd->buf_queue, nbp);
972 
973 			/*
974 			 * Tell the device to get going on the transfer if it's
975 			 * not doing anything, otherwise just wait for
976 			 * completion
977 			 */
978 			cdstart(cd->sc_periph);
979 
980 			splx(s);
981 			return;
982 
983 		}
984 	}
985 done:
986 	obp->b_flags |= (bp->b_flags&(B_EINTR|B_ERROR));
987 	obp->b_error = bp->b_error;
988 	obp->b_resid = bp->b_resid;
989 	free(bp->b_data, M_DEVBUF);
990 	biodone(obp);
991 }
992 
993 static int
994 cd_interpret_sense(struct scsipi_xfer *xs)
995 {
996 	struct scsipi_periph *periph = xs->xs_periph;
997 	struct scsi_sense_data *sense = &xs->sense.scsi_sense;
998 	int retval = EJUSTRETURN;
999 
1000 	/*
1001 	 * If it isn't a extended or extended/deferred error, let
1002 	 * the generic code handle it.
1003 	 */
1004 	if (SSD_RCODE(sense->response_code) != SSD_RCODE_CURRENT &&
1005 	    SSD_RCODE(sense->response_code) != SSD_RCODE_DEFERRED)
1006 		return (retval);
1007 
1008 	/*
1009 	 * If we got a "Unit not ready" (SKEY_NOT_READY) and "Logical Unit
1010 	 * Is In The Process of Becoming Ready" (Sense code 0x04,0x01), then
1011 	 * wait a bit for the drive to spin up
1012 	 */
1013 
1014 	if (SSD_SENSE_KEY(sense->flags) == SKEY_NOT_READY &&
1015 	    sense->asc == 0x4 &&
1016 	    sense->ascq == 0x01)	{
1017 		/*
1018 		 * Sleep for 5 seconds to wait for the drive to spin up
1019 		 */
1020 
1021 		SC_DEBUG(periph, SCSIPI_DB1, ("Waiting 5 sec for CD "
1022 						"spinup\n"));
1023 		if (!callout_pending(&periph->periph_callout))
1024 			scsipi_periph_freeze(periph, 1);
1025 		callout_reset(&periph->periph_callout,
1026 		    5 * hz, scsipi_periph_timed_thaw, periph);
1027 		retval = ERESTART;
1028 	}
1029 	return (retval);
1030 }
1031 
1032 static void
1033 cdminphys(struct buf *bp)
1034 {
1035 	struct cd_softc *cd = cd_cd.cd_devs[CDUNIT(bp->b_dev)];
1036 	long xmax;
1037 
1038 	/*
1039 	 * If the device is ancient, we want to make sure that
1040 	 * the transfer fits into a 6-byte cdb.
1041 	 *
1042 	 * XXX Note that the SCSI-I spec says that 256-block transfers
1043 	 * are allowed in a 6-byte read/write, and are specified
1044 	 * by settng the "length" to 0.  However, we're conservative
1045 	 * here, allowing only 255-block transfers in case an
1046 	 * ancient device gets confused by length == 0.  A length of 0
1047 	 * in a 10-byte read/write actually means 0 blocks.
1048 	 */
1049 	if (cd->flags & CDF_ANCIENT) {
1050 		xmax = cd->sc_dk.dk_label->d_secsize * 0xff;
1051 
1052 		if (bp->b_bcount > xmax)
1053 			bp->b_bcount = xmax;
1054 	}
1055 
1056 	(*cd->sc_periph->periph_channel->chan_adapter->adapt_minphys)(bp);
1057 }
1058 
1059 static int
1060 cdread(dev_t dev, struct uio *uio, int ioflag)
1061 {
1062 
1063 	return (physio(cdstrategy, NULL, dev, B_READ, cdminphys, uio));
1064 }
1065 
1066 static int
1067 cdwrite(dev_t dev, struct uio *uio, int ioflag)
1068 {
1069 
1070 	return (physio(cdstrategy, NULL, dev, B_WRITE, cdminphys, uio));
1071 }
1072 
1073 #if 0	/* XXX Not used */
1074 /*
1075  * conversion between minute-seconde-frame and logical block address
1076  * addresses format
1077  */
1078 static void
1079 lba2msf(u_long lba, u_char *m, u_char *s, u_char *f)
1080 {
1081 	u_long tmp;
1082 
1083 	tmp = lba + CD_BLOCK_OFFSET;	/* offset of first logical frame */
1084 	tmp &= 0xffffff;		/* negative lbas use only 24 bits */
1085 	*m = tmp / (CD_SECS * CD_FRAMES);
1086 	tmp %= (CD_SECS * CD_FRAMES);
1087 	*s = tmp / CD_FRAMES;
1088 	*f = tmp % CD_FRAMES;
1089 }
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 #endif /* XXX Not used */
1105 
1106 static int
1107 cdreadmsaddr(struct cd_softc *cd, int *addr)
1108 {
1109 	struct scsipi_periph *periph = cd->sc_periph;
1110 	int error;
1111 	struct cd_formatted_toc toc;
1112 	struct cd_toc_entry *cte;
1113 
1114 	error = cd_read_toc(cd, CD_TOC_FORM, 0, 0, &toc,
1115 	    sizeof(struct ioc_toc_header) + sizeof(struct cd_toc_entry),
1116 	    XS_CTL_DATA_ONSTACK,
1117 	    0x40 /* control word for "get MS info" */);
1118 
1119 	if (error)
1120 		return (error);
1121 
1122 	cte = &toc.entries[0];
1123 	if (periph->periph_quirks & PQUIRK_LITTLETOC) {
1124 		cte->addr.lba = le32toh(cte->addr.lba);
1125 		toc.header.len = le16toh(toc.header.len);
1126 	} else {
1127 		cte->addr.lba = be32toh(cte->addr.lba);
1128 		toc.header.len = be16toh(toc.header.len);
1129 	}
1130 
1131 	*addr = (toc.header.len >= 10 && cte->track > 1) ?
1132 		cte->addr.lba : 0;
1133 	return 0;
1134 }
1135 
1136 /* synchronise caches code from sd.c, move to scsipi_ioctl.c ? */
1137 static int
1138 cdcachesync(struct scsipi_periph *periph, int flags) {
1139 	struct scsi_synchronize_cache_10 cmd;
1140 
1141 	/*
1142 	 * Issue a SYNCHRONIZE CACHE. MMC devices have to issue with address 0
1143 	 * and length 0 as it can't synchronise parts of the disc per spec.
1144 	 * We ignore ILLEGAL REQUEST in the event that the command is not
1145 	 * supported by the device, and poll for completion so that we know
1146 	 * that the cache has actually been flushed.
1147 	 *
1148 	 * XXX should we handle the PQUIRK_NOSYNCCACHE ?
1149 	 */
1150 
1151 	memset(&cmd, 0, sizeof(cmd));
1152 	cmd.opcode = SCSI_SYNCHRONIZE_CACHE_10;
1153 
1154 	return (scsipi_command(periph, (void *)&cmd, sizeof(cmd), 0, 0,
1155 	    CDRETRIES, 30000, NULL, flags | XS_CTL_IGNORE_ILLEGAL_REQUEST));
1156 }
1157 
1158 /*
1159  * Perform special action on behalf of the user.
1160  * Knows about the internals of this device
1161  */
1162 static int
1163 cdioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct lwp *l)
1164 {
1165 	struct cd_softc *cd = cd_cd.cd_devs[CDUNIT(dev)];
1166 	struct scsipi_periph *periph = cd->sc_periph;
1167 	int part = CDPART(dev);
1168 	int error = 0;
1169 #ifdef __HAVE_OLD_DISKLABEL
1170 	struct disklabel *newlabel = NULL;
1171 #endif
1172 
1173 	SC_DEBUG(cd->sc_periph, SCSIPI_DB2, ("cdioctl 0x%lx ", cmd));
1174 
1175 	/*
1176 	 * If the device is not valid, some IOCTLs can still be
1177 	 * handled on the raw partition. Check this here.
1178 	 */
1179 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
1180 		switch (cmd) {
1181 		case DIOCWLABEL:
1182 		case DIOCLOCK:
1183 		case ODIOCEJECT:
1184 		case DIOCEJECT:
1185 		case DIOCCACHESYNC:
1186 		case SCIOCIDENTIFY:
1187 		case OSCIOCIDENTIFY:
1188 		case SCIOCCOMMAND:
1189 		case SCIOCDEBUG:
1190 		case CDIOCGETVOL:
1191 		case CDIOCSETVOL:
1192 		case CDIOCSETMONO:
1193 		case CDIOCSETSTEREO:
1194 		case CDIOCSETMUTE:
1195 		case CDIOCSETLEFT:
1196 		case CDIOCSETRIGHT:
1197 		case CDIOCCLOSE:
1198 		case CDIOCEJECT:
1199 		case CDIOCALLOW:
1200 		case CDIOCPREVENT:
1201 		case CDIOCSETDEBUG:
1202 		case CDIOCCLRDEBUG:
1203 		case CDIOCRESET:
1204 		case SCIOCRESET:
1205 		case CDIOCLOADUNLOAD:
1206 		case DVD_AUTH:
1207 		case DVD_READ_STRUCT:
1208 			if (part == RAW_PART)
1209 				break;
1210 		/* FALLTHROUGH */
1211 		default:
1212 			if ((periph->periph_flags & PERIPH_OPEN) == 0)
1213 				return (ENODEV);
1214 			else
1215 				return (EIO);
1216 		}
1217 	}
1218 
1219 	switch (cmd) {
1220 	case DIOCGDINFO:
1221 		*(struct disklabel *)addr = *(cd->sc_dk.dk_label);
1222 		return (0);
1223 #ifdef __HAVE_OLD_DISKLABEL
1224 	case ODIOCGDINFO:
1225 		newlabel = malloc(sizeof (*newlabel), M_TEMP, M_WAITOK);
1226 		if (newlabel == NULL)
1227 			return (EIO);
1228 		memcpy(newlabel, cd->sc_dk.dk_label, sizeof (*newlabel));
1229 		if (newlabel->d_npartitions > OLDMAXPARTITIONS)
1230 			error = ENOTTY;
1231 		else
1232 			memcpy(addr, newlabel, sizeof (struct olddisklabel));
1233 		free(newlabel, M_TEMP);
1234 		return error;
1235 #endif
1236 
1237 	case DIOCGPART:
1238 		((struct partinfo *)addr)->disklab = cd->sc_dk.dk_label;
1239 		((struct partinfo *)addr)->part =
1240 		    &cd->sc_dk.dk_label->d_partitions[part];
1241 		return (0);
1242 
1243 	case DIOCWDINFO:
1244 	case DIOCSDINFO:
1245 #ifdef __HAVE_OLD_DISKLABEL
1246 	case ODIOCWDINFO:
1247 	case ODIOCSDINFO:
1248 #endif
1249 	{
1250 		struct disklabel *lp;
1251 
1252 		if ((flag & FWRITE) == 0)
1253 			return (EBADF);
1254 
1255 #ifdef __HAVE_OLD_DISKLABEL
1256 		if (cmd == ODIOCSDINFO || cmd == ODIOCWDINFO) {
1257 			newlabel = malloc(sizeof (*newlabel), M_TEMP, M_WAITOK);
1258 			if (newlabel == NULL)
1259 				return (EIO);
1260 			memset(newlabel, 0, sizeof newlabel);
1261 			memcpy(newlabel, addr, sizeof (struct olddisklabel));
1262 			lp = newlabel;
1263 		} else
1264 #endif
1265 		lp = (struct disklabel *)addr;
1266 
1267 		if ((error = lockmgr(&cd->sc_lock, LK_EXCLUSIVE, NULL)) != 0)
1268 			goto bad;
1269 		cd->flags |= CDF_LABELLING;
1270 
1271 		error = setdisklabel(cd->sc_dk.dk_label,
1272 		    lp, /*cd->sc_dk.dk_openmask : */0,
1273 		    cd->sc_dk.dk_cpulabel);
1274 		if (error == 0) {
1275 			/* XXX ? */
1276 		}
1277 
1278 		cd->flags &= ~CDF_LABELLING;
1279 		lockmgr(&cd->sc_lock, LK_RELEASE, NULL);
1280 bad:
1281 #ifdef __HAVE_OLD_DISKLABEL
1282 		if (newlabel != NULL)
1283 			free(newlabel, M_TEMP);
1284 #endif
1285 		return (error);
1286 	}
1287 
1288 	case DIOCWLABEL:
1289 		return (EBADF);
1290 
1291 	case DIOCGDEFLABEL:
1292 		cdgetdefaultlabel(cd, (struct disklabel *)addr);
1293 		return (0);
1294 
1295 #ifdef __HAVE_OLD_DISKLABEL
1296 	case ODIOCGDEFLABEL:
1297 		newlabel = malloc(sizeof (*newlabel), M_TEMP, M_WAITOK);
1298 		if (newlabel == NULL)
1299 			return (EIO);
1300 		cdgetdefaultlabel(cd, newlabel);
1301 		if (newlabel->d_npartitions > OLDMAXPARTITIONS)
1302 			error = ENOTTY;
1303 		else
1304 			memcpy(addr, newlabel, sizeof (struct olddisklabel));
1305 		free(newlabel, M_TEMP);
1306 		return error;
1307 #endif
1308 
1309 	case CDIOCPLAYTRACKS: {
1310 		/* PLAY_MSF command */
1311 		struct ioc_play_track *args = (struct ioc_play_track *)addr;
1312 
1313 		if ((error = cd_set_pa_immed(cd, 0)) != 0)
1314 			return (error);
1315 		return (cd_play_tracks(cd, args->start_track,
1316 		    args->start_index, args->end_track, args->end_index));
1317 	}
1318 	case CDIOCPLAYMSF: {
1319 		/* PLAY_MSF command */
1320 		struct ioc_play_msf *args = (struct ioc_play_msf *)addr;
1321 
1322 		if ((error = cd_set_pa_immed(cd, 0)) != 0)
1323 			return (error);
1324 		return (cd_play_msf(cd, args->start_m, args->start_s,
1325 		    args->start_f, args->end_m, args->end_s, args->end_f));
1326 	}
1327 	case CDIOCPLAYBLOCKS: {
1328 		/* PLAY command */
1329 		struct ioc_play_blocks *args = (struct ioc_play_blocks *)addr;
1330 
1331 		if ((error = cd_set_pa_immed(cd, 0)) != 0)
1332 			return (error);
1333 		return (cd_play(cd, args->blk, args->len));
1334 	}
1335 	case CDIOCREADSUBCHANNEL: {
1336 		/* READ_SUBCHANNEL command */
1337 		struct ioc_read_subchannel *args =
1338 		    (struct ioc_read_subchannel *)addr;
1339 		struct cd_sub_channel_info data;
1340 		u_int len = args->data_len;
1341 
1342 		if (len > sizeof(data) ||
1343 		    len < sizeof(struct cd_sub_channel_header))
1344 			return (EINVAL);
1345 		error = cd_read_subchannel(cd, args->address_format,
1346 		    args->data_format, args->track, &data, len,
1347 		    XS_CTL_DATA_ONSTACK);
1348 		if (error)
1349 			return (error);
1350 		len = min(len, _2btol(data.header.data_len) +
1351 		    sizeof(struct cd_sub_channel_header));
1352 		return (copyout(&data, args->data, len));
1353 	}
1354 	case CDIOREADTOCHEADER: {
1355 		/* READ TOC format 0 command, static header */
1356 		struct ioc_toc_header th;
1357 
1358 		if ((error = cd_read_toc(cd, CD_TOC_FORM, 0, 0, &th, sizeof(th),
1359 		    XS_CTL_DATA_ONSTACK, 0)) != 0)
1360 			return (error);
1361 		if (cd->sc_periph->periph_quirks & PQUIRK_LITTLETOC)
1362 			th.len = le16toh(th.len);
1363 		else
1364 			th.len = be16toh(th.len);
1365 		memcpy(addr, &th, sizeof(th));
1366 		return (0);
1367 	}
1368 	case CDIOREADTOCENTRYS: {
1369 		/* READ TOC format 0 command, entries */
1370 		struct cd_formatted_toc toc;
1371 		struct ioc_read_toc_entry *te =
1372 		    (struct ioc_read_toc_entry *)addr;
1373 		struct ioc_toc_header *th;
1374 		struct cd_toc_entry *cte;
1375 		u_int len = te->data_len;
1376 		int ntracks;
1377 
1378 		th = &toc.header;
1379 
1380 		if (len > sizeof(toc.entries) ||
1381 		    len < sizeof(struct cd_toc_entry))
1382 			return (EINVAL);
1383 		error = cd_read_toc(cd, CD_TOC_FORM, te->address_format,
1384 		    te->starting_track, &toc,
1385 		    len + sizeof(struct ioc_toc_header),
1386 		    XS_CTL_DATA_ONSTACK, 0);
1387 		if (error)
1388 			return (error);
1389 		if (te->address_format == CD_LBA_FORMAT)
1390 			for (ntracks =
1391 			    th->ending_track - th->starting_track + 1;
1392 			    ntracks >= 0; ntracks--) {
1393 				cte = &toc.entries[ntracks];
1394 				cte->addr_type = CD_LBA_FORMAT;
1395 				if (periph->periph_quirks & PQUIRK_LITTLETOC)
1396 					cte->addr.lba = le32toh(cte->addr.lba);
1397 				else
1398 					cte->addr.lba = be32toh(cte->addr.lba);
1399 			}
1400 		if (periph->periph_quirks & PQUIRK_LITTLETOC)
1401 			th->len = le16toh(th->len);
1402 		else
1403 			th->len = be16toh(th->len);
1404 		len = min(len, th->len - (sizeof(th->starting_track) +
1405 		    sizeof(th->ending_track)));
1406 		return (copyout(toc.entries, te->data, len));
1407 	}
1408 	case CDIOREADMSADDR: {
1409 		/* READ TOC format 0 command, length of first track only */
1410 		int sessno = *(int*)addr;
1411 
1412 		if (sessno != 0)
1413 			return (EINVAL);
1414 
1415 		return (cdreadmsaddr(cd, (int*)addr));
1416 	}
1417 	case CDIOCSETPATCH: {
1418 		struct ioc_patch *arg = (struct ioc_patch *)addr;
1419 
1420 		return (cd_setchan(cd, arg->patch[0], arg->patch[1],
1421 		    arg->patch[2], arg->patch[3], 0));
1422 	}
1423 	case CDIOCGETVOL: {
1424 		/* MODE SENSE command (AUDIO page) */
1425 		struct ioc_vol *arg = (struct ioc_vol *)addr;
1426 
1427 		return (cd_getvol(cd, arg, 0));
1428 	}
1429 	case CDIOCSETVOL: {
1430 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1431 		struct ioc_vol *arg = (struct ioc_vol *)addr;
1432 
1433 		return (cd_setvol(cd, arg, 0));
1434 	}
1435 	case CDIOCSETMONO:
1436 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1437 		return (cd_setchan(cd, BOTH_CHANNEL, BOTH_CHANNEL,
1438 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1439 
1440 	case CDIOCSETSTEREO:
1441 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1442 		return (cd_setchan(cd, LEFT_CHANNEL, RIGHT_CHANNEL,
1443 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1444 
1445 	case CDIOCSETMUTE:
1446 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1447 		return (cd_setchan(cd, MUTE_CHANNEL, MUTE_CHANNEL,
1448 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1449 
1450 	case CDIOCSETLEFT:
1451 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1452 		return (cd_setchan(cd, LEFT_CHANNEL, LEFT_CHANNEL,
1453 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1454 
1455 	case CDIOCSETRIGHT:
1456 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1457 		return (cd_setchan(cd, RIGHT_CHANNEL, RIGHT_CHANNEL,
1458 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1459 
1460 	case CDIOCRESUME:
1461 		/* PAUSE command */
1462 		return (cd_pause(cd, PA_RESUME));
1463 	case CDIOCPAUSE:
1464 		/* PAUSE command */
1465 		return (cd_pause(cd, PA_PAUSE));
1466 	case CDIOCSTART:
1467 		return (scsipi_start(periph, SSS_START, 0));
1468 	case CDIOCSTOP:
1469 		return (scsipi_start(periph, SSS_STOP, 0));
1470 	case CDIOCCLOSE:
1471 		return (scsipi_start(periph, SSS_START|SSS_LOEJ,
1472 		    XS_CTL_IGNORE_NOT_READY | XS_CTL_IGNORE_MEDIA_CHANGE));
1473 	case DIOCEJECT:
1474 		if (*(int *)addr == 0) {
1475 			/*
1476 			 * Don't force eject: check that we are the only
1477 			 * partition open. If so, unlock it.
1478 			 */
1479 			if ((cd->sc_dk.dk_openmask & ~(1 << part)) == 0 &&
1480 			    cd->sc_dk.dk_bopenmask + cd->sc_dk.dk_copenmask ==
1481 			    cd->sc_dk.dk_openmask) {
1482 				error = scsipi_prevent(periph, SPAMR_ALLOW,
1483 				    XS_CTL_IGNORE_NOT_READY);
1484 				if (error)
1485 					return (error);
1486 			} else {
1487 				return (EBUSY);
1488 			}
1489 		}
1490 		/* FALLTHROUGH */
1491 	case CDIOCEJECT: /* FALLTHROUGH */
1492 	case ODIOCEJECT:
1493 		return (scsipi_start(periph, SSS_STOP|SSS_LOEJ, 0));
1494 	case DIOCCACHESYNC:
1495 		/* SYNCHRONISE CACHES command */
1496 		return (cdcachesync(periph, 0));
1497 	case CDIOCALLOW:
1498 		return (scsipi_prevent(periph, SPAMR_ALLOW, 0));
1499 	case CDIOCPREVENT:
1500 		return (scsipi_prevent(periph, SPAMR_PREVENT_DT, 0));
1501 	case DIOCLOCK:
1502 		return (scsipi_prevent(periph,
1503 		    (*(int *)addr) ? SPAMR_PREVENT_DT : SPAMR_ALLOW, 0));
1504 	case CDIOCSETDEBUG:
1505 		cd->sc_periph->periph_dbflags |= (SCSIPI_DB1 | SCSIPI_DB2);
1506 		return (0);
1507 	case CDIOCCLRDEBUG:
1508 		cd->sc_periph->periph_dbflags &= ~(SCSIPI_DB1 | SCSIPI_DB2);
1509 		return (0);
1510 	case CDIOCRESET:
1511 	case SCIOCRESET:
1512 		return (cd_reset(cd));
1513 	case CDIOCLOADUNLOAD:
1514 		/* LOAD_UNLOAD command */
1515 		return (cd_load_unload(cd, (struct ioc_load_unload *)addr));
1516 	case DVD_AUTH:
1517 		/* GPCMD_REPORT_KEY or GPCMD_SEND_KEY command */
1518 		return (dvd_auth(cd, (dvd_authinfo *)addr));
1519 	case DVD_READ_STRUCT:
1520 		/* GPCMD_READ_DVD_STRUCTURE command */
1521 		return (dvd_read_struct(cd, (dvd_struct *)addr));
1522 	default:
1523 		if (part != RAW_PART)
1524 			return (ENOTTY);
1525 		return (scsipi_do_ioctl(periph, dev, cmd, addr, flag, l));
1526 	}
1527 
1528 #ifdef DIAGNOSTIC
1529 	panic("cdioctl: impossible");
1530 #endif
1531 }
1532 
1533 static void
1534 cdgetdefaultlabel(struct cd_softc *cd, struct disklabel *lp)
1535 {
1536 	int lastsession;
1537 
1538 	memset(lp, 0, sizeof(struct disklabel));
1539 
1540 	lp->d_secsize = cd->params.blksize;
1541 	lp->d_ntracks = 1;
1542 	lp->d_nsectors = 100;
1543 	lp->d_ncylinders = (cd->params.disksize / 100) + 1;
1544 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
1545 
1546 	switch (scsipi_periph_bustype(cd->sc_periph)) {
1547 	case SCSIPI_BUSTYPE_SCSI:
1548 		lp->d_type = DTYPE_SCSI;
1549 		break;
1550 	case SCSIPI_BUSTYPE_ATAPI:
1551 		lp->d_type = DTYPE_ATAPI;
1552 		break;
1553 	}
1554 	/*
1555 	 * XXX
1556 	 * We could probe the mode pages to figure out what kind of disc it is.
1557 	 * Is this worthwhile?
1558 	 */
1559 	strncpy(lp->d_typename, "mydisc", 16);
1560 	strncpy(lp->d_packname, "fictitious", 16);
1561 	lp->d_secperunit = cd->params.disksize;
1562 	lp->d_rpm = 300;
1563 	lp->d_interleave = 1;
1564 	lp->d_flags = D_REMOVABLE;
1565 
1566 	if (cdreadmsaddr(cd, &lastsession) != 0)
1567 		lastsession = 0;
1568 
1569 	lp->d_partitions[0].p_offset = 0;
1570 #ifdef notyet /* have to fix bounds_check_with_label() first */
1571 	lp->d_partitions[0].p_size = lp->d_secperunit;
1572 #else
1573 	lp->d_partitions[0].p_size =
1574 	    lp->d_secperunit * (lp->d_secsize / DEV_BSIZE);
1575 #endif
1576 	lp->d_partitions[0].p_cdsession = lastsession;
1577 	lp->d_partitions[0].p_fstype = FS_ISO9660;
1578 	lp->d_partitions[RAW_PART].p_offset = 0;
1579 #ifdef notyet
1580 	lp->d_partitions[RAW_PART].p_size = lp->d_secperunit;
1581 #else
1582 	lp->d_partitions[RAW_PART].p_size =
1583 	    lp->d_secperunit * (lp->d_secsize / DEV_BSIZE);
1584 #endif
1585 	lp->d_partitions[RAW_PART].p_fstype = FS_ISO9660;
1586 	lp->d_npartitions = RAW_PART + 1;
1587 
1588 	lp->d_magic = DISKMAGIC;
1589 	lp->d_magic2 = DISKMAGIC;
1590 	lp->d_checksum = dkcksum(lp);
1591 }
1592 
1593 /*
1594  * Load the label information on the named device
1595  * Actually fabricate a disklabel
1596  *
1597  * EVENTUALLY take information about different
1598  * data tracks from the TOC and put it in the disklabel
1599  */
1600 static void
1601 cdgetdisklabel(struct cd_softc *cd)
1602 {
1603 	struct disklabel *lp = cd->sc_dk.dk_label;
1604 	const char *errstring;
1605 
1606 	memset(cd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
1607 
1608 	cdgetdefaultlabel(cd, lp);
1609 
1610 	/*
1611 	 * Call the generic disklabel extraction routine
1612 	 */
1613 	errstring = readdisklabel(MAKECDDEV(0, cd->sc_dev.dv_unit, RAW_PART),
1614 	    cdstrategy, lp, cd->sc_dk.dk_cpulabel);
1615 
1616 	/* if all went OK, we are passed a NULL error string */
1617 	if (errstring == NULL)
1618 		return;
1619 
1620 	/* Reset to default label -- after printing error and the warning */
1621 	printf("%s: %s\n", cd->sc_dev.dv_xname, errstring);
1622 	memset(cd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
1623 	cdgetdefaultlabel(cd, lp);
1624 }
1625 
1626 /*
1627  * Reading a discs total capacity is aparently a very difficult issue for the
1628  * SCSI standardisation group. Every disc type seems to have its own
1629  * (re)invented size request method and modifiers. The failsafe way of
1630  * determining the total (max) capacity i.e. not the recorded capacity but the
1631  * total maximum capacity is to request the info on the last track and
1632  * calucate the total size.
1633  *
1634  * For ROM drives, we go for the CD recorded capacity. For recordable devices
1635  * we count.
1636  */
1637 static int
1638 read_cd_capacity(struct scsipi_periph *periph, int *blksize, u_long *size)
1639 {
1640 	struct scsipi_read_cd_capacity    cap_cmd;
1641 	struct scsipi_read_cd_cap_data    cap;
1642 	struct scsipi_read_discinfo       di_cmd;
1643 	struct scsipi_read_discinfo_data  di;
1644 	struct scsipi_read_trackinfo      ti_cmd;
1645 	struct scsipi_read_trackinfo_data ti;
1646 	uint32_t track_start, track_size;
1647 	int error, flags, msb, lsb, last_track;
1648 
1649 	/* if the device doesn't grog capacity, return the dummies */
1650 	if (periph->periph_quirks & PQUIRK_NOCAPACITY)
1651 		return 0;
1652 
1653 	/* first try read CD capacity for blksize and recorded size */
1654 	/* issue the cd capacity request */
1655 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK;
1656 	memset(&cap_cmd, 0, sizeof(cap_cmd));
1657 	cap_cmd.opcode = READ_CD_CAPACITY;
1658 
1659 	error = scsipi_command(periph,
1660 	    (void *) &cap_cmd, sizeof(cap_cmd),
1661 	    (void *) &cap,     sizeof(cap),
1662 	    CDRETRIES, 30000, NULL, flags);
1663 	if (error)
1664 		return error;
1665 
1666 	/* retrieve values and sanity check them */
1667 	*blksize = _4btol(cap.length);
1668 	*size    = _4btol(cap.addr);
1669 
1670 	/* blksize is 2048 for CD, but some drives give gibberish */
1671 	if ((*blksize < 512) || ((*blksize & 511) != 0))
1672 		*blksize = 2048;	/* some drives lie ! */
1673 
1674 	/* recordables have READ_DISCINFO implemented */
1675 	flags = XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK | XS_CTL_SILENT;
1676 	memset(&di_cmd, 0, sizeof(di_cmd));
1677 	di_cmd.opcode = READ_DISCINFO;
1678 	_lto2b(sizeof(di), di_cmd.data_len);
1679 
1680 	error = scsipi_command(periph,
1681 	    (void *) &di_cmd,  sizeof(di_cmd),
1682 	    (void *) &di,      sizeof(di),
1683 	    CDRETRIES, 30000, NULL, flags);
1684 	if (error == 0) {
1685 		msb = di.last_track_last_session_msb;
1686 		lsb = di.last_track_last_session_lsb;
1687 		last_track = (msb << 8) | lsb;
1688 
1689 		/* request info on last track */
1690 		memset(&ti_cmd, 0, sizeof(ti_cmd));
1691 		ti_cmd.opcode = READ_TRACKINFO;
1692 		ti_cmd.addr_type = 1;			/* on tracknr */
1693 		_lto4b(last_track, ti_cmd.address);	/* tracknr    */
1694 		_lto2b(sizeof(ti), ti_cmd.data_len);
1695 
1696 		error = scsipi_command(periph,
1697 		    (void *) &ti_cmd,  sizeof(ti_cmd),
1698 		    (void *) &ti,      sizeof(ti),
1699 		    CDRETRIES, 30000, NULL, flags);
1700 		if (error == 0) {
1701 			track_start = _4btol(ti.track_start);
1702 			track_size  = _4btol(ti.track_size);
1703 
1704 			*size = track_start + track_size;
1705 		};
1706 	};
1707 
1708 	/* sanity check for size */
1709 	if (*size < 100)
1710 		*size = 400000;
1711 
1712 	return 0;
1713 }
1714 
1715 /*
1716  * Find out from the device what it's capacity is
1717  */
1718 static u_long
1719 cd_size(struct cd_softc *cd, int flags)
1720 {
1721 	int blksize;
1722 	u_long size;
1723 	int error;
1724 
1725 	/* set up fake values */
1726 	blksize = 2048;
1727 	size    = 400000;
1728 
1729 	/* if this function bounces with an error return fake value */
1730 	error = read_cd_capacity(cd->sc_periph, &blksize, &size);
1731 	if (error)
1732 		return size;
1733 
1734 	if (blksize != 2048) {
1735 		if (cd_setblksize(cd) == 0)
1736 			blksize = 2048;
1737 	}
1738 	cd->params.blksize     = blksize;
1739 	cd->params.disksize    = size-1;   /* disklabel is exclusive */
1740 	cd->params.disksize512 = ((u_int64_t)cd->params.disksize * blksize) / DEV_BSIZE;
1741 
1742 	SC_DEBUG(cd->sc_periph, SCSIPI_DB2,
1743 	    ("cd_size: %d %ld\n", blksize, size));
1744 
1745 	return size;
1746 }
1747 
1748 /*
1749  * Get scsi driver to send a "start playing" command
1750  */
1751 static int
1752 cd_play(struct cd_softc *cd, int blkno, int nblks)
1753 {
1754 	struct scsipi_play cmd;
1755 
1756 	memset(&cmd, 0, sizeof(cmd));
1757 	cmd.opcode = PLAY;
1758 	_lto4b(blkno, cmd.blk_addr);
1759 	_lto2b(nblks, cmd.xfer_len);
1760 
1761 	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
1762 	    CDRETRIES, 30000, NULL, 0));
1763 }
1764 
1765 /*
1766  * Get scsi driver to send a "start playing" command
1767  */
1768 static int
1769 cd_play_tracks(struct cd_softc *cd, int strack, int sindex, int etrack,
1770     int eindex)
1771 {
1772 	struct cd_formatted_toc toc;
1773 	int error;
1774 
1775 	if (!etrack)
1776 		return (EIO);
1777 	if (strack > etrack)
1778 		return (EINVAL);
1779 
1780 	error = cd_load_toc(cd, CD_TOC_FORM, &toc, XS_CTL_DATA_ONSTACK);
1781 	if (error)
1782 		return (error);
1783 
1784 	if (++etrack > (toc.header.ending_track+1))
1785 		etrack = toc.header.ending_track+1;
1786 
1787 	strack -= toc.header.starting_track;
1788 	etrack -= toc.header.starting_track;
1789 	if (strack < 0)
1790 		return (EINVAL);
1791 
1792 	return (cd_play_msf(cd, toc.entries[strack].addr.msf.minute,
1793 	    toc.entries[strack].addr.msf.second,
1794 	    toc.entries[strack].addr.msf.frame,
1795 	    toc.entries[etrack].addr.msf.minute,
1796 	    toc.entries[etrack].addr.msf.second,
1797 	    toc.entries[etrack].addr.msf.frame));
1798 }
1799 
1800 /*
1801  * Get scsi driver to send a "play msf" command
1802  */
1803 static int
1804 cd_play_msf(struct cd_softc *cd, int startm, int starts, int startf, int endm,
1805     int ends, int endf)
1806 {
1807 	struct scsipi_play_msf cmd;
1808 
1809 	memset(&cmd, 0, sizeof(cmd));
1810 	cmd.opcode = PLAY_MSF;
1811 	cmd.start_m = startm;
1812 	cmd.start_s = starts;
1813 	cmd.start_f = startf;
1814 	cmd.end_m = endm;
1815 	cmd.end_s = ends;
1816 	cmd.end_f = endf;
1817 
1818 	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
1819 	    CDRETRIES, 30000, NULL, 0));
1820 }
1821 
1822 /*
1823  * Get scsi driver to send a "start up" command
1824  */
1825 static int
1826 cd_pause(struct cd_softc *cd, int go)
1827 {
1828 	struct scsipi_pause cmd;
1829 
1830 	memset(&cmd, 0, sizeof(cmd));
1831 	cmd.opcode = PAUSE;
1832 	cmd.resume = go & 0xff;
1833 
1834 	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
1835 	    CDRETRIES, 30000, NULL, 0));
1836 }
1837 
1838 /*
1839  * Get scsi driver to send a "RESET" command
1840  */
1841 static int
1842 cd_reset(struct cd_softc *cd)
1843 {
1844 
1845 	return (scsipi_command(cd->sc_periph, 0, 0, 0, 0,
1846 	    CDRETRIES, 30000, NULL, XS_CTL_RESET));
1847 }
1848 
1849 /*
1850  * Read subchannel
1851  */
1852 static int
1853 cd_read_subchannel(struct cd_softc *cd, int mode, int format, int track,
1854     struct cd_sub_channel_info *data, int len, int flags)
1855 {
1856 	struct scsipi_read_subchannel cmd;
1857 
1858 	memset(&cmd, 0, sizeof(cmd));
1859 	cmd.opcode = READ_SUBCHANNEL;
1860 	if (mode == CD_MSF_FORMAT)
1861 		cmd.byte2 |= CD_MSF;
1862 	cmd.byte3 = SRS_SUBQ;
1863 	cmd.subchan_format = format;
1864 	cmd.track = track;
1865 	_lto2b(len, cmd.data_len);
1866 
1867 	return (scsipi_command(cd->sc_periph,
1868 	    (void *)&cmd, sizeof(struct scsipi_read_subchannel),
1869 	    (void *)data, len,
1870 	    CDRETRIES, 30000, NULL, flags | XS_CTL_DATA_IN | XS_CTL_SILENT));
1871 }
1872 
1873 /*
1874  * Read table of contents
1875  */
1876 static int
1877 cd_read_toc(struct cd_softc *cd, int respf, int mode, int start, void *data, int len,
1878     int flags, int control)
1879 {
1880 	struct scsipi_read_toc cmd;
1881 	int ntoc;
1882 
1883 	memset(&cmd, 0, sizeof(cmd));
1884 #if 0
1885 	if (len != sizeof(struct ioc_toc_header))
1886 		ntoc = ((len) - sizeof(struct ioc_toc_header)) /
1887 		    sizeof(struct cd_toc_entry);
1888 	else
1889 #endif
1890 	ntoc = len;
1891 	cmd.opcode = READ_TOC;
1892 	if (mode == CD_MSF_FORMAT)
1893 		cmd.addr_mode |= CD_MSF;
1894 	cmd.resp_format = respf;
1895 	cmd.from_track = start;
1896 	_lto2b(ntoc, cmd.data_len);
1897 	cmd.control = control;
1898 
1899 	return (scsipi_command(cd->sc_periph,
1900 	    (void *)&cmd, sizeof(cmd), (void *)data, len, CDRETRIES,
1901 	    30000, NULL, flags | XS_CTL_DATA_IN));
1902 }
1903 
1904 static int
1905 cd_load_toc(struct cd_softc *cd, int respf, struct cd_formatted_toc *toc, int flags)
1906 {
1907 	int ntracks, len, error;
1908 
1909 	if ((error = cd_read_toc(cd, respf, 0, 0, toc, sizeof(toc->header),
1910 	    flags, 0)) != 0)
1911 		return (error);
1912 
1913 	ntracks = toc->header.ending_track - toc->header.starting_track + 1;
1914 	len = (ntracks + 1) * sizeof(struct cd_toc_entry) +
1915 	    sizeof(toc->header);
1916 	if ((error = cd_read_toc(cd, respf, CD_MSF_FORMAT, 0, toc, len,
1917 	    flags, 0)) != 0)
1918 		return (error);
1919 	return (0);
1920 }
1921 
1922 /*
1923  * Get the scsi driver to send a full inquiry to the device and use the
1924  * results to fill out the disk parameter structure.
1925  */
1926 static int
1927 cd_get_parms(struct cd_softc *cd, int flags)
1928 {
1929 
1930 	/*
1931 	 * give a number of sectors so that sec * trks * cyls
1932 	 * is <= disk_size
1933 	 */
1934 	if (cd_size(cd, flags) == 0)
1935 		return (ENXIO);
1936 	return (0);
1937 }
1938 
1939 static int
1940 cdsize(dev_t dev)
1941 {
1942 
1943 	/* CD-ROMs are read-only. */
1944 	return (-1);
1945 }
1946 
1947 static int
1948 cddump(dev_t dev, daddr_t blkno, caddr_t va, size_t size)
1949 {
1950 
1951 	/* Not implemented. */
1952 	return (ENXIO);
1953 }
1954 
1955 #define	dvd_copy_key(dst, src)		memcpy((dst), (src), sizeof(dvd_key))
1956 #define	dvd_copy_challenge(dst, src)	memcpy((dst), (src), sizeof(dvd_challenge))
1957 
1958 static int
1959 dvd_auth(struct cd_softc *cd, dvd_authinfo *a)
1960 {
1961 	struct scsipi_generic cmd;
1962 	u_int8_t bf[20];
1963 	int error;
1964 
1965 	memset(cmd.bytes, 0, 15);
1966 	memset(bf, 0, sizeof(bf));
1967 
1968 	switch (a->type) {
1969 	case DVD_LU_SEND_AGID:
1970 		cmd.opcode = GPCMD_REPORT_KEY;
1971 		cmd.bytes[8] = 8;
1972 		cmd.bytes[9] = 0 | (0 << 6);
1973 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
1974 		    CDRETRIES, 30000, NULL,
1975 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
1976 		if (error)
1977 			return (error);
1978 		a->lsa.agid = bf[7] >> 6;
1979 		return (0);
1980 
1981 	case DVD_LU_SEND_CHALLENGE:
1982 		cmd.opcode = GPCMD_REPORT_KEY;
1983 		cmd.bytes[8] = 16;
1984 		cmd.bytes[9] = 1 | (a->lsc.agid << 6);
1985 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 16,
1986 		    CDRETRIES, 30000, NULL,
1987 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
1988 		if (error)
1989 			return (error);
1990 		dvd_copy_challenge(a->lsc.chal, &bf[4]);
1991 		return (0);
1992 
1993 	case DVD_LU_SEND_KEY1:
1994 		cmd.opcode = GPCMD_REPORT_KEY;
1995 		cmd.bytes[8] = 12;
1996 		cmd.bytes[9] = 2 | (a->lsk.agid << 6);
1997 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 12,
1998 		    CDRETRIES, 30000, NULL,
1999 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2000 		if (error)
2001 			return (error);
2002 		dvd_copy_key(a->lsk.key, &bf[4]);
2003 		return (0);
2004 
2005 	case DVD_LU_SEND_TITLE_KEY:
2006 		cmd.opcode = GPCMD_REPORT_KEY;
2007 		_lto4b(a->lstk.lba, &cmd.bytes[1]);
2008 		cmd.bytes[8] = 12;
2009 		cmd.bytes[9] = 4 | (a->lstk.agid << 6);
2010 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 12,
2011 		    CDRETRIES, 30000, NULL,
2012 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2013 		if (error)
2014 			return (error);
2015 		a->lstk.cpm = (bf[4] >> 7) & 1;
2016 		a->lstk.cp_sec = (bf[4] >> 6) & 1;
2017 		a->lstk.cgms = (bf[4] >> 4) & 3;
2018 		dvd_copy_key(a->lstk.title_key, &bf[5]);
2019 		return (0);
2020 
2021 	case DVD_LU_SEND_ASF:
2022 		cmd.opcode = GPCMD_REPORT_KEY;
2023 		cmd.bytes[8] = 8;
2024 		cmd.bytes[9] = 5 | (a->lsasf.agid << 6);
2025 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
2026 		    CDRETRIES, 30000, NULL,
2027 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2028 		if (error)
2029 			return (error);
2030 		a->lsasf.asf = bf[7] & 1;
2031 		return (0);
2032 
2033 	case DVD_HOST_SEND_CHALLENGE:
2034 		cmd.opcode = GPCMD_SEND_KEY;
2035 		cmd.bytes[8] = 16;
2036 		cmd.bytes[9] = 1 | (a->hsc.agid << 6);
2037 		bf[1] = 14;
2038 		dvd_copy_challenge(&bf[4], a->hsc.chal);
2039 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 16,
2040 		    CDRETRIES, 30000, NULL,
2041 		    XS_CTL_DATA_OUT|XS_CTL_DATA_ONSTACK);
2042 		if (error)
2043 			return (error);
2044 		a->type = DVD_LU_SEND_KEY1;
2045 		return (0);
2046 
2047 	case DVD_HOST_SEND_KEY2:
2048 		cmd.opcode = GPCMD_SEND_KEY;
2049 		cmd.bytes[8] = 12;
2050 		cmd.bytes[9] = 3 | (a->hsk.agid << 6);
2051 		bf[1] = 10;
2052 		dvd_copy_key(&bf[4], a->hsk.key);
2053 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 12,
2054 		    CDRETRIES, 30000, NULL,
2055 		    XS_CTL_DATA_OUT|XS_CTL_DATA_ONSTACK);
2056 		if (error) {
2057 			a->type = DVD_AUTH_FAILURE;
2058 			return (error);
2059 		}
2060 		a->type = DVD_AUTH_ESTABLISHED;
2061 		return (0);
2062 
2063 	case DVD_INVALIDATE_AGID:
2064 		cmd.opcode = GPCMD_REPORT_KEY;
2065 		cmd.bytes[9] = 0x3f | (a->lsa.agid << 6);
2066 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 16,
2067 		    CDRETRIES, 30000, NULL, 0);
2068 		if (error)
2069 			return (error);
2070 		return (0);
2071 
2072 	case DVD_LU_SEND_RPC_STATE:
2073 		cmd.opcode = GPCMD_REPORT_KEY;
2074 		cmd.bytes[8] = 8;
2075 		cmd.bytes[9] = 8 | (0 << 6);
2076 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
2077 		    CDRETRIES, 30000, NULL,
2078 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2079 		if (error)
2080 			return (error);
2081 		a->lrpcs.type = (bf[4] >> 6) & 3;
2082 		a->lrpcs.vra = (bf[4] >> 3) & 7;
2083 		a->lrpcs.ucca = (bf[4]) & 7;
2084 		a->lrpcs.region_mask = bf[5];
2085 		a->lrpcs.rpc_scheme = bf[6];
2086 		return (0);
2087 
2088 	case DVD_HOST_SEND_RPC_STATE:
2089 		cmd.opcode = GPCMD_SEND_KEY;
2090 		cmd.bytes[8] = 8;
2091 		cmd.bytes[9] = 6 | (0 << 6);
2092 		bf[1] = 6;
2093 		bf[4] = a->hrpcs.pdrc;
2094 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
2095 		    CDRETRIES, 30000, NULL,
2096 		    XS_CTL_DATA_OUT|XS_CTL_DATA_ONSTACK);
2097 		if (error)
2098 			return (error);
2099 		return (0);
2100 
2101 	default:
2102 		return (ENOTTY);
2103 	}
2104 }
2105 
2106 static int
2107 dvd_read_physical(struct cd_softc *cd, dvd_struct *s)
2108 {
2109 	struct scsipi_generic cmd;
2110 	u_int8_t bf[4 + 4 * 20], *bufp;
2111 	int error;
2112 	struct dvd_layer *layer;
2113 	int i;
2114 
2115 	memset(cmd.bytes, 0, 15);
2116 	memset(bf, 0, sizeof(bf));
2117 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2118 	cmd.bytes[6] = s->type;
2119 	_lto2b(sizeof(bf), &cmd.bytes[7]);
2120 
2121 	cmd.bytes[5] = s->physical.layer_num;
2122 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, sizeof(bf),
2123 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2124 	if (error)
2125 		return (error);
2126 	for (i = 0, bufp = &bf[4], layer = &s->physical.layer[0]; i < 4;
2127 	     i++, bufp += 20, layer++) {
2128 		memset(layer, 0, sizeof(*layer));
2129                 layer->book_version = bufp[0] & 0xf;
2130                 layer->book_type = bufp[0] >> 4;
2131                 layer->min_rate = bufp[1] & 0xf;
2132                 layer->disc_size = bufp[1] >> 4;
2133                 layer->layer_type = bufp[2] & 0xf;
2134                 layer->track_path = (bufp[2] >> 4) & 1;
2135                 layer->nlayers = (bufp[2] >> 5) & 3;
2136                 layer->track_density = bufp[3] & 0xf;
2137                 layer->linear_density = bufp[3] >> 4;
2138                 layer->start_sector = _4btol(&bufp[4]);
2139                 layer->end_sector = _4btol(&bufp[8]);
2140                 layer->end_sector_l0 = _4btol(&bufp[12]);
2141                 layer->bca = bufp[16] >> 7;
2142 	}
2143 	return (0);
2144 }
2145 
2146 static int
2147 dvd_read_copyright(struct cd_softc *cd, dvd_struct *s)
2148 {
2149 	struct scsipi_generic cmd;
2150 	u_int8_t bf[8];
2151 	int error;
2152 
2153 	memset(cmd.bytes, 0, 15);
2154 	memset(bf, 0, sizeof(bf));
2155 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2156 	cmd.bytes[6] = s->type;
2157 	_lto2b(sizeof(bf), &cmd.bytes[7]);
2158 
2159 	cmd.bytes[5] = s->copyright.layer_num;
2160 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, sizeof(bf),
2161 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2162 	if (error)
2163 		return (error);
2164 	s->copyright.cpst = bf[4];
2165 	s->copyright.rmi = bf[5];
2166 	return (0);
2167 }
2168 
2169 static int
2170 dvd_read_disckey(struct cd_softc *cd, dvd_struct *s)
2171 {
2172 	struct scsipi_generic cmd;
2173 	u_int8_t *bf;
2174 	int error;
2175 
2176 	bf = malloc(4 + 2048, M_TEMP, M_WAITOK|M_ZERO);
2177 	if (bf == NULL)
2178 		return EIO;
2179 	memset(cmd.bytes, 0, 15);
2180 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2181 	cmd.bytes[6] = s->type;
2182 	_lto2b(4 + 2048, &cmd.bytes[7]);
2183 
2184 	cmd.bytes[9] = s->disckey.agid << 6;
2185 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 4 + 2048,
2186 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2187 	if (error == 0)
2188 		memcpy(s->disckey.value, &bf[4], 2048);
2189 	free(bf, M_TEMP);
2190 	return error;
2191 }
2192 
2193 static int
2194 dvd_read_bca(struct cd_softc *cd, dvd_struct *s)
2195 {
2196 	struct scsipi_generic cmd;
2197 	u_int8_t bf[4 + 188];
2198 	int error;
2199 
2200 	memset(cmd.bytes, 0, 15);
2201 	memset(bf, 0, sizeof(bf));
2202 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2203 	cmd.bytes[6] = s->type;
2204 	_lto2b(sizeof(bf), &cmd.bytes[7]);
2205 
2206 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, sizeof(bf),
2207 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2208 	if (error)
2209 		return (error);
2210 	s->bca.len = _2btol(&bf[0]);
2211 	if (s->bca.len < 12 || s->bca.len > 188)
2212 		return (EIO);
2213 	memcpy(s->bca.value, &bf[4], s->bca.len);
2214 	return (0);
2215 }
2216 
2217 static int
2218 dvd_read_manufact(struct cd_softc *cd, dvd_struct *s)
2219 {
2220 	struct scsipi_generic cmd;
2221 	u_int8_t *bf;
2222 	int error;
2223 
2224 	bf = malloc(4 + 2048, M_TEMP, M_WAITOK|M_ZERO);
2225 	if (bf == NULL)
2226 		return (EIO);
2227 	memset(cmd.bytes, 0, 15);
2228 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2229 	cmd.bytes[6] = s->type;
2230 	_lto2b(4 + 2048, &cmd.bytes[7]);
2231 
2232 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 4 + 2048,
2233 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2234 	if (error == 0) {
2235 		s->manufact.len = _2btol(&bf[0]);
2236 		if (s->manufact.len >= 0 && s->manufact.len <= 2048)
2237 			memcpy(s->manufact.value, &bf[4], s->manufact.len);
2238 		else
2239 			error = EIO;
2240 	}
2241 	free(bf, M_TEMP);
2242 	return error;
2243 }
2244 
2245 static int
2246 dvd_read_struct(struct cd_softc *cd, dvd_struct *s)
2247 {
2248 
2249 	switch (s->type) {
2250 	case DVD_STRUCT_PHYSICAL:
2251 		return (dvd_read_physical(cd, s));
2252 	case DVD_STRUCT_COPYRIGHT:
2253 		return (dvd_read_copyright(cd, s));
2254 	case DVD_STRUCT_DISCKEY:
2255 		return (dvd_read_disckey(cd, s));
2256 	case DVD_STRUCT_BCA:
2257 		return (dvd_read_bca(cd, s));
2258 	case DVD_STRUCT_MANUFACT:
2259 		return (dvd_read_manufact(cd, s));
2260 	default:
2261 		return (EINVAL);
2262 	}
2263 }
2264 
2265 static int
2266 cd_mode_sense(struct cd_softc *cd, u_int8_t byte2, void *sense, size_t size,
2267     int page, int flags, int *big)
2268 {
2269 
2270 	if (cd->sc_periph->periph_quirks & PQUIRK_ONLYBIG) {
2271 		*big = 1;
2272 		return scsipi_mode_sense_big(cd->sc_periph, byte2, page, sense,
2273 		    size + sizeof(struct scsi_mode_parameter_header_10),
2274 		    flags | XS_CTL_DATA_ONSTACK, CDRETRIES, 20000);
2275 	} else {
2276 		*big = 0;
2277 		return scsipi_mode_sense(cd->sc_periph, byte2, page, sense,
2278 		    size + sizeof(struct scsi_mode_parameter_header_6),
2279 		    flags | XS_CTL_DATA_ONSTACK, CDRETRIES, 20000);
2280 	}
2281 }
2282 
2283 static int
2284 cd_mode_select(struct cd_softc *cd, u_int8_t byte2, void *sense, size_t size,
2285     int flags, int big)
2286 {
2287 
2288 	if (big) {
2289 		struct scsi_mode_parameter_header_10 *header = sense;
2290 
2291 		_lto2b(0, header->data_length);
2292 		return scsipi_mode_select_big(cd->sc_periph, byte2, sense,
2293 		    size + sizeof(struct scsi_mode_parameter_header_10),
2294 		    flags | XS_CTL_DATA_ONSTACK, CDRETRIES, 20000);
2295 	} else {
2296 		struct scsi_mode_parameter_header_6 *header = sense;
2297 
2298 		header->data_length = 0;
2299 		return scsipi_mode_select(cd->sc_periph, byte2, sense,
2300 		    size + sizeof(struct scsi_mode_parameter_header_6),
2301 		    flags | XS_CTL_DATA_ONSTACK, CDRETRIES, 20000);
2302 	}
2303 }
2304 
2305 static int
2306 cd_set_pa_immed(struct cd_softc *cd, int flags)
2307 {
2308 	struct {
2309 		union {
2310 			struct scsi_mode_parameter_header_6 small;
2311 			struct scsi_mode_parameter_header_10 big;
2312 		} header;
2313 		struct cd_audio_page page;
2314 	} data;
2315 	int error;
2316 	uint8_t oflags;
2317 	int big, byte2;
2318 	struct cd_audio_page *page;
2319 
2320 	byte2 = SMS_DBD;
2321 try_again:
2322 	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
2323 	    AUDIO_PAGE, flags, &big)) != 0) {
2324 		if (byte2 == SMS_DBD) {
2325 			/* Device may not understand DBD; retry without */
2326 			byte2 = 0;
2327 			goto try_again;
2328 		}
2329 		return (error);
2330 	}
2331 
2332 	if (big)
2333 		page = (void *)((u_long)&data.header.big +
2334 				sizeof data.header.big +
2335 				_2btol(data.header.big.blk_desc_len));
2336 	else
2337 		page = (void *)((u_long)&data.header.small +
2338 				sizeof data.header.small +
2339 				data.header.small.blk_desc_len);
2340 
2341 	oflags = page->flags;
2342 	page->flags &= ~CD_PA_SOTC;
2343 	page->flags |= CD_PA_IMMED;
2344 	if (oflags == page->flags)
2345 		return (0);
2346 
2347 	return (cd_mode_select(cd, SMS_PF, &data,
2348 	    sizeof(struct scsi_mode_page_header) + page->pg_length,
2349 	    flags, big));
2350 }
2351 
2352 static int
2353 cd_setchan(struct cd_softc *cd, int p0, int p1, int p2, int p3, int flags)
2354 {
2355 	struct {
2356 		union {
2357 			struct scsi_mode_parameter_header_6 small;
2358 			struct scsi_mode_parameter_header_10 big;
2359 		} header;
2360 		struct cd_audio_page page;
2361 	} data;
2362 	int error;
2363 	int big, byte2;
2364 	struct cd_audio_page *page;
2365 
2366 	byte2 = SMS_DBD;
2367 try_again:
2368 	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
2369 	    AUDIO_PAGE, flags, &big)) != 0) {
2370 		if (byte2 == SMS_DBD) {
2371 			/* Device may not understand DBD; retry without */
2372 			byte2 = 0;
2373 			goto try_again;
2374 		}
2375 		return (error);
2376 	}
2377 
2378 	if (big)
2379 		page = (void *)((u_long)&data.header.big +
2380 				sizeof data.header.big +
2381 				_2btol(data.header.big.blk_desc_len));
2382 	else
2383 		page = (void *)((u_long)&data.header.small +
2384 				sizeof data.header.small +
2385 				data.header.small.blk_desc_len);
2386 
2387 	page->port[0].channels = p0;
2388 	page->port[1].channels = p1;
2389 	page->port[2].channels = p2;
2390 	page->port[3].channels = p3;
2391 
2392 	return (cd_mode_select(cd, SMS_PF, &data,
2393 	    sizeof(struct scsi_mode_page_header) + page->pg_length,
2394 	    flags, big));
2395 }
2396 
2397 static int
2398 cd_getvol(struct cd_softc *cd, struct ioc_vol *arg, int flags)
2399 {
2400 	struct {
2401 		union {
2402 			struct scsi_mode_parameter_header_6 small;
2403 			struct scsi_mode_parameter_header_10 big;
2404 		} header;
2405 		struct cd_audio_page page;
2406 	} data;
2407 	int error;
2408 	int big, byte2;
2409 	struct cd_audio_page *page;
2410 
2411 	byte2 = SMS_DBD;
2412 try_again:
2413 	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
2414 	    AUDIO_PAGE, flags, &big)) != 0) {
2415 		if (byte2 == SMS_DBD) {
2416 			/* Device may not understand DBD; retry without */
2417 			byte2 = 0;
2418 			goto try_again;
2419 		}
2420 		return (error);
2421 	}
2422 
2423 	if (big)
2424 		page = (void *)((u_long)&data.header.big +
2425 				sizeof data.header.big +
2426 				_2btol(data.header.big.blk_desc_len));
2427 	else
2428 		page = (void *)((u_long)&data.header.small +
2429 				sizeof data.header.small +
2430 				data.header.small.blk_desc_len);
2431 
2432 	arg->vol[0] = page->port[0].volume;
2433 	arg->vol[1] = page->port[1].volume;
2434 	arg->vol[2] = page->port[2].volume;
2435 	arg->vol[3] = page->port[3].volume;
2436 
2437 	return (0);
2438 }
2439 
2440 static int
2441 cd_setvol(struct cd_softc *cd, const struct ioc_vol *arg, int flags)
2442 {
2443 	struct {
2444 		union {
2445 			struct scsi_mode_parameter_header_6 small;
2446 			struct scsi_mode_parameter_header_10 big;
2447 		} header;
2448 		struct cd_audio_page page;
2449 	} data, mask;
2450 	int error;
2451 	int big, byte2;
2452 	struct cd_audio_page *page, *page2;
2453 
2454 	byte2 = SMS_DBD;
2455 try_again:
2456 	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
2457 	    AUDIO_PAGE, flags, &big)) != 0) {
2458 		if (byte2 == SMS_DBD) {
2459 			/* Device may not understand DBD; retry without */
2460 			byte2 = 0;
2461 			goto try_again;
2462 		}
2463 		return (error);
2464 	}
2465 	if ((error = cd_mode_sense(cd, byte2, &mask, sizeof(mask.page),
2466 	    AUDIO_PAGE|SMS_PCTRL_CHANGEABLE, flags, &big)) != 0)
2467 		return (error);
2468 
2469 	if (big) {
2470 		page = (void *)((u_long)&data.header.big +
2471 				sizeof data.header.big +
2472 				_2btol(data.header.big.blk_desc_len));
2473 		page2 = (void *)((u_long)&mask.header.big +
2474 				sizeof mask.header.big +
2475 				_2btol(mask.header.big.blk_desc_len));
2476 	} else {
2477 		page = (void *)((u_long)&data.header.small +
2478 				sizeof data.header.small +
2479 				data.header.small.blk_desc_len);
2480 		page2 = (void *)((u_long)&mask.header.small +
2481 				sizeof mask.header.small +
2482 				mask.header.small.blk_desc_len);
2483 	}
2484 
2485 	page->port[0].volume = arg->vol[0] & page2->port[0].volume;
2486 	page->port[1].volume = arg->vol[1] & page2->port[1].volume;
2487 	page->port[2].volume = arg->vol[2] & page2->port[2].volume;
2488 	page->port[3].volume = arg->vol[3] & page2->port[3].volume;
2489 
2490 	page->port[0].channels = CHANNEL_0;
2491 	page->port[1].channels = CHANNEL_1;
2492 
2493 	return (cd_mode_select(cd, SMS_PF, &data,
2494 	    sizeof(struct scsi_mode_page_header) + page->pg_length,
2495 	    flags, big));
2496 }
2497 
2498 static int
2499 cd_load_unload(struct cd_softc *cd, struct ioc_load_unload *args)
2500 {
2501 	struct scsipi_load_unload cmd;
2502 
2503 	memset(&cmd, 0, sizeof(cmd));
2504 	cmd.opcode = LOAD_UNLOAD;
2505 	cmd.options = args->options;    /* ioctl uses MMC values */
2506 	cmd.slot = args->slot;
2507 
2508 	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
2509 	    CDRETRIES, 200000, NULL, 0));
2510 }
2511 
2512 static int
2513 cd_setblksize(struct cd_softc *cd)
2514 {
2515 	struct {
2516 		union {
2517 			struct scsi_mode_parameter_header_6 small;
2518 			struct scsi_mode_parameter_header_10 big;
2519 		} header;
2520 		struct scsi_general_block_descriptor blk_desc;
2521 	} data;
2522 	int error;
2523 	int big, bsize;
2524 	struct scsi_general_block_descriptor *bdesc;
2525 
2526 	if ((error = cd_mode_sense(cd, 0, &data, sizeof(data.blk_desc), 0, 0,
2527 	    &big)) != 0)
2528 		return (error);
2529 
2530 	if (big) {
2531 		bdesc = (void *)(&data.header.big + 1);
2532 		bsize = _2btol(data.header.big.blk_desc_len);
2533 	} else {
2534 		bdesc = (void *)(&data.header.small + 1);
2535 		bsize = data.header.small.blk_desc_len;
2536 	}
2537 
2538 	if (bsize == 0) {
2539 printf("cd_setblksize: trying to change bsize, but no blk_desc\n");
2540 		return (EINVAL);
2541 	}
2542 	if (_3btol(bdesc->blklen) == 2048) {
2543 printf("cd_setblksize: trying to change bsize, but blk_desc is correct\n");
2544 		return (EINVAL);
2545 	}
2546 
2547 	_lto3b(2048, bdesc->blklen);
2548 
2549 	return (cd_mode_select(cd, SMS_PF, &data, sizeof(data.blk_desc), 0,
2550 	    big));
2551 }
2552 
2553