xref: /netbsd-src/sys/dev/scsipi/cd.c (revision 001c68bd94f75ce9270b69227c4199fbf34ee396)
1 /*	$NetBSD: cd.c,v 1.185 2003/06/29 22:30:37 fvdl Exp $	*/
2 
3 /*-
4  * Copyright (c) 1998, 2001 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.185 2003/06/29 22:30:37 fvdl 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/uio.h>
69 #include <sys/malloc.h>
70 #include <sys/errno.h>
71 #include <sys/device.h>
72 #include <sys/disklabel.h>
73 #include <sys/disk.h>
74 #include <sys/cdio.h>
75 #include <sys/dvdio.h>
76 #include <sys/scsiio.h>
77 #include <sys/proc.h>
78 #include <sys/conf.h>
79 #include <sys/vnode.h>
80 #if NRND > 0
81 #include <sys/rnd.h>
82 #endif
83 
84 #include <dev/scsipi/scsipi_all.h>
85 #include <dev/scsipi/scsipi_cd.h>
86 #include <dev/scsipi/scsipi_disk.h>	/* rw_big and start_stop come */
87 					/* from there */
88 #include <dev/scsipi/scsi_disk.h>	/* rw comes from there */
89 #include <dev/scsipi/scsipiconf.h>
90 #include <dev/scsipi/cdvar.h>
91 
92 #include "cd.h"		/* NCD_SCSIBUS and NCD_ATAPIBUS come from here */
93 
94 #define	CDUNIT(z)			DISKUNIT(z)
95 #define	CDPART(z)			DISKPART(z)
96 #define	CDMINOR(unit, part)		DISKMINOR(unit, part)
97 #define	MAKECDDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)
98 
99 #define MAXTRACK	99
100 #define CD_BLOCK_OFFSET	150
101 #define CD_FRAMES	75
102 #define CD_SECS		60
103 
104 struct cd_toc {
105 	struct ioc_toc_header header;
106 	struct cd_toc_entry entries[MAXTRACK+1]; /* One extra for the */
107 						 /* leadout */
108 };
109 
110 int	cdlock __P((struct cd_softc *));
111 void	cdunlock __P((struct cd_softc *));
112 void	cdstart __P((struct scsipi_periph *));
113 void	cdminphys __P((struct buf *));
114 void	cdgetdefaultlabel __P((struct cd_softc *, struct disklabel *));
115 void	cdgetdisklabel __P((struct cd_softc *));
116 void	cddone __P((struct scsipi_xfer *));
117 void	cdbounce __P((struct buf *));
118 int	cd_interpret_sense __P((struct scsipi_xfer *));
119 u_long	cd_size __P((struct cd_softc *, int));
120 void	lba2msf __P((u_long, u_char *, u_char *, u_char *));
121 u_long	msf2lba __P((u_char, u_char, u_char));
122 int	cd_play __P((struct cd_softc *, int, int));
123 int	cd_play_tracks __P((struct cd_softc *, int, int, int, int));
124 int	cd_play_msf __P((struct cd_softc *, int, int, int, int, int, int));
125 int	cd_pause __P((struct cd_softc *, int));
126 int	cd_reset __P((struct cd_softc *));
127 int	cd_read_subchannel __P((struct cd_softc *, int, int, int,
128 	    struct cd_sub_channel_info *, int, int));
129 int	cd_read_toc __P((struct cd_softc *, int, int, void *, int, int, int));
130 int	cd_get_parms __P((struct cd_softc *, int));
131 int	cd_load_toc __P((struct cd_softc *, struct cd_toc *, int));
132 int	cdreadmsaddr __P((struct cd_softc *, int *));
133 int	dvd_auth __P((struct cd_softc *, dvd_authinfo *));
134 int	dvd_read_physical __P((struct cd_softc *, dvd_struct *));
135 int	dvd_read_copyright __P((struct cd_softc *, dvd_struct *));
136 int	dvd_read_disckey __P((struct cd_softc *, dvd_struct *));
137 int	dvd_read_bca __P((struct cd_softc *, dvd_struct *));
138 int	dvd_read_manufact __P((struct cd_softc *, dvd_struct *));
139 int	dvd_read_struct __P((struct cd_softc *, dvd_struct *));
140 
141 extern struct cfdriver cd_cd;
142 
143 dev_type_open(cdopen);
144 dev_type_close(cdclose);
145 dev_type_read(cdread);
146 dev_type_write(cdwrite);
147 dev_type_ioctl(cdioctl);
148 dev_type_strategy(cdstrategy);
149 dev_type_dump(cddump);
150 dev_type_size(cdsize);
151 
152 const struct bdevsw cd_bdevsw = {
153 	cdopen, cdclose, cdstrategy, cdioctl, cddump, cdsize, D_DISK
154 };
155 
156 const struct cdevsw cd_cdevsw = {
157 	cdopen, cdclose, cdread, cdwrite, cdioctl,
158 	nostop, notty, nopoll, nommap, nokqfilter, D_DISK
159 };
160 
161 struct dkdriver cddkdriver = { cdstrategy };
162 
163 const struct scsipi_periphsw cd_switch = {
164 	cd_interpret_sense,	/* use our error handler first */
165 	cdstart,		/* we have a queue, which is started by this */
166 	NULL,			/* we do not have an async handler */
167 	cddone,			/* deal with stats at interrupt time */
168 };
169 
170 /*
171  * The routine called by the low level scsi routine when it discovers
172  * A device suitable for this driver
173  */
174 void
175 cdattach(parent, cd, periph, ops)
176 	struct device *parent;
177 	struct cd_softc *cd;
178 	struct scsipi_periph *periph;
179 	const struct cd_ops *ops;
180 {
181 	SC_DEBUG(periph, SCSIPI_DB2, ("cdattach: "));
182 
183 	bufq_alloc(&cd->buf_queue, BUFQ_DISKSORT|BUFQ_SORT_RAWBLOCK);
184 
185 	/*
186 	 * Store information needed to contact our base driver
187 	 */
188 	cd->sc_periph = periph;
189 	cd->sc_ops = ops;
190 
191 	periph->periph_dev = &cd->sc_dev;
192 	periph->periph_switch = &cd_switch;
193 
194 	/*
195 	 * Increase our openings to the maximum-per-periph
196 	 * supported by the adapter.  This will either be
197 	 * clamped down or grown by the adapter if necessary.
198 	 */
199 	periph->periph_openings =
200 	    SCSIPI_CHAN_MAX_PERIPH(periph->periph_channel);
201 	periph->periph_flags |= PERIPH_GROW_OPENINGS;
202 
203 	/*
204 	 * Initialize and attach the disk structure.
205 	 */
206   	cd->sc_dk.dk_driver = &cddkdriver;
207 	cd->sc_dk.dk_name = cd->sc_dev.dv_xname;
208 	disk_attach(&cd->sc_dk);
209 
210 	printf("\n");
211 
212 #if NRND > 0
213 	rnd_attach_source(&cd->rnd_source, cd->sc_dev.dv_xname,
214 			  RND_TYPE_DISK, 0);
215 #endif
216 }
217 
218 int
219 cdactivate(self, act)
220 	struct device *self;
221 	enum devact act;
222 {
223 	int rv = 0;
224 
225 	switch (act) {
226 	case DVACT_ACTIVATE:
227 		rv = EOPNOTSUPP;
228 		break;
229 
230 	case DVACT_DEACTIVATE:
231 		/*
232 		 * Nothing to do; we key off the device's DVF_ACTIVE.
233 		 */
234 		break;
235 	}
236 	return (rv);
237 }
238 
239 int
240 cddetach(self, flags)
241 	struct device *self;
242 	int flags;
243 {
244 	struct cd_softc *cd = (struct cd_softc *) self;
245 	struct buf *bp;
246 	int s, bmaj, cmaj, i, mn;
247 
248 	/* locate the major number */
249 	bmaj = bdevsw_lookup_major(&cd_bdevsw);
250 	cmaj = cdevsw_lookup_major(&cd_cdevsw);
251 
252 	s = splbio();
253 
254 	/* Kill off any queued buffers. */
255 	while ((bp = BUFQ_GET(&cd->buf_queue)) != NULL) {
256 		bp->b_error = EIO;
257 		bp->b_flags |= B_ERROR;
258 		bp->b_resid = bp->b_bcount;
259 		biodone(bp);
260 	}
261 
262 	bufq_free(&cd->buf_queue);
263 
264 	/* Kill off any pending commands. */
265 	scsipi_kill_pending(cd->sc_periph);
266 
267 	splx(s);
268 
269 	/* Nuke the vnodes for any open instances */
270 	for (i = 0; i < MAXPARTITIONS; i++) {
271 		mn = CDMINOR(self->dv_unit, i);
272 		vdevgone(bmaj, mn, mn, VBLK);
273 		vdevgone(cmaj, mn, mn, VCHR);
274 	}
275 
276 	/* Detach from the disk list. */
277 	disk_detach(&cd->sc_dk);
278 
279 #if 0
280 	/* Get rid of the shutdown hook. */
281 	if (cd->sc_sdhook != NULL)
282 		shutdownhook_disestablish(cd->sc_sdhook);
283 #endif
284 
285 #if NRND > 0
286 	/* Unhook the entropy source. */
287 	rnd_detach_source(&cd->rnd_source);
288 #endif
289 
290 	return (0);
291 }
292 
293 /*
294  * Wait interruptibly for an exclusive lock.
295  *
296  * XXX
297  * Several drivers do this; it should be abstracted and made MP-safe.
298  */
299 int
300 cdlock(cd)
301 	struct cd_softc *cd;
302 {
303 	int error;
304 
305 	while ((cd->flags & CDF_LOCKED) != 0) {
306 		cd->flags |= CDF_WANTED;
307 		if ((error = tsleep(cd, PRIBIO | PCATCH, "cdlck", 0)) != 0)
308 			return (error);
309 	}
310 	cd->flags |= CDF_LOCKED;
311 	return (0);
312 }
313 
314 /*
315  * Unlock and wake up any waiters.
316  */
317 void
318 cdunlock(cd)
319 	struct cd_softc *cd;
320 {
321 
322 	cd->flags &= ~CDF_LOCKED;
323 	if ((cd->flags & CDF_WANTED) != 0) {
324 		cd->flags &= ~CDF_WANTED;
325 		wakeup(cd);
326 	}
327 }
328 
329 /*
330  * open the device. Make sure the partition info is a up-to-date as can be.
331  */
332 int
333 cdopen(dev, flag, fmt, p)
334 	dev_t dev;
335 	int flag, fmt;
336 	struct proc *p;
337 {
338 	struct cd_softc *cd;
339 	struct scsipi_periph *periph;
340 	struct scsipi_adapter *adapt;
341 	struct cd_sub_channel_info data;
342 	int unit, part;
343 	int error;
344 
345 	unit = CDUNIT(dev);
346 	if (unit >= cd_cd.cd_ndevs)
347 		return (ENXIO);
348 	cd = cd_cd.cd_devs[unit];
349 	if (cd == NULL)
350 		return (ENXIO);
351 
352 	periph = cd->sc_periph;
353 	adapt = periph->periph_channel->chan_adapter;
354 	part = CDPART(dev);
355 
356 	SC_DEBUG(periph, SCSIPI_DB1,
357 	    ("cdopen: dev=0x%x (unit %d (of %d), partition %d)\n", dev, unit,
358 	    cd_cd.cd_ndevs, CDPART(dev)));
359 
360 	/*
361 	 * If this is the first open of this device, add a reference
362 	 * to the adapter.
363 	 */
364 	if (cd->sc_dk.dk_openmask == 0 &&
365 	    (error = scsipi_adapter_addref(adapt)) != 0)
366 		return (error);
367 
368 	if ((error = cdlock(cd)) != 0)
369 		goto bad4;
370 
371 	if ((periph->periph_flags & PERIPH_OPEN) != 0) {
372 		/*
373 		 * If any partition is open, but the disk has been invalidated,
374 		 * disallow further opens.
375 		 */
376 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0 &&
377 			(part != RAW_PART || fmt != S_IFCHR )) {
378 			error = EIO;
379 			goto bad3;
380 		}
381 	} else {
382 		/* Check that it is still responding and ok. */
383 		error = scsipi_test_unit_ready(periph,
384 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE |
385 		    XS_CTL_SILENT_NODEV);
386 		SC_DEBUG(periph, SCSIPI_DB1,
387 		    ("cdopen: scsipi_test_unit_ready, error=%d\n", error));
388 		if (error) {
389 			if (part != RAW_PART || fmt != S_IFCHR)
390 				goto bad3;
391 			else
392 				goto out;
393 		}
394 
395 		/* Don't try to start the unit if audio is playing. */
396 		error = cd_read_subchannel(cd, CD_LBA_FORMAT,
397 		    CD_CURRENT_POSITION, 0, &data, sizeof(data),
398 		    XS_CTL_DATA_ONSTACK);
399 		if ((data.header.audio_status != CD_AS_PLAY_IN_PROGRESS &&
400 		    data.header.audio_status != CD_AS_PLAY_PAUSED) || error) {
401 			/*
402 			 * Start the pack spinning if necessary. Always
403 			 * allow the raw parition to be opened, for raw
404 			 * IOCTLs. Data transfers will check for
405 			 * SDEV_MEDIA_LOADED.
406 			 */
407 			error = scsipi_start(periph, SSS_START,
408 			    XS_CTL_IGNORE_ILLEGAL_REQUEST |
409 			    XS_CTL_IGNORE_MEDIA_CHANGE |
410 			    XS_CTL_SILENT);
411 			SC_DEBUG(periph, SCSIPI_DB1,
412 			    ("cdopen: scsipi_start, error=%d\n", error));
413 			if (error) {
414 				if (part != RAW_PART || fmt != S_IFCHR)
415 					goto bad3;
416 				else
417 					goto out;
418 			}
419 		}
420 
421 		periph->periph_flags |= PERIPH_OPEN;
422 
423 		/* Lock the pack in. */
424 		error = scsipi_prevent(periph, PR_PREVENT,
425 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE);
426 		SC_DEBUG(periph, SCSIPI_DB1,
427 		    ("cdopen: scsipi_prevent, error=%d\n", error));
428 		if (error)
429 			goto bad;
430 
431 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
432 			periph->periph_flags |= PERIPH_MEDIA_LOADED;
433 
434 			/* Load the physical device parameters. */
435 			if (cd_get_parms(cd, 0) != 0) {
436 				error = ENXIO;
437 				goto bad2;
438 			}
439 			SC_DEBUG(periph, SCSIPI_DB3, ("Params loaded "));
440 
441 			/* Fabricate a disk label. */
442 			cdgetdisklabel(cd);
443 			SC_DEBUG(periph, SCSIPI_DB3, ("Disklabel fabricated "));
444 		}
445 	}
446 
447 	/* Check that the partition exists. */
448 	if (part != RAW_PART &&
449 	    (part >= cd->sc_dk.dk_label->d_npartitions ||
450 	    cd->sc_dk.dk_label->d_partitions[part].p_fstype == FS_UNUSED)) {
451 		error = ENXIO;
452 		goto bad;
453 	}
454 
455 out:	/* Insure only one open at a time. */
456 	switch (fmt) {
457 	case S_IFCHR:
458 		cd->sc_dk.dk_copenmask |= (1 << part);
459 		break;
460 	case S_IFBLK:
461 		cd->sc_dk.dk_bopenmask |= (1 << part);
462 		break;
463 	}
464 	cd->sc_dk.dk_openmask =
465 	    cd->sc_dk.dk_copenmask | cd->sc_dk.dk_bopenmask;
466 
467 	SC_DEBUG(periph, SCSIPI_DB3, ("open complete\n"));
468 	cdunlock(cd);
469 	return (0);
470 
471 bad2:
472 	periph->periph_flags &= ~PERIPH_MEDIA_LOADED;
473 
474 bad:
475 	if (cd->sc_dk.dk_openmask == 0) {
476 		scsipi_prevent(periph, PR_ALLOW,
477 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE);
478 		periph->periph_flags &= ~PERIPH_OPEN;
479 	}
480 
481 bad3:
482 	cdunlock(cd);
483 bad4:
484 	if (cd->sc_dk.dk_openmask == 0)
485 		scsipi_adapter_delref(adapt);
486 	return (error);
487 }
488 
489 /*
490  * close the device.. only called if we are the LAST
491  * occurence of an open device
492  */
493 int
494 cdclose(dev, flag, fmt, p)
495 	dev_t dev;
496 	int flag, fmt;
497 	struct proc *p;
498 {
499 	struct cd_softc *cd = cd_cd.cd_devs[CDUNIT(dev)];
500 	struct scsipi_periph *periph = cd->sc_periph;
501 	struct scsipi_adapter *adapt = periph->periph_channel->chan_adapter;
502 	int part = CDPART(dev);
503 	int error;
504 
505 	if ((error = cdlock(cd)) != 0)
506 		return (error);
507 
508 	switch (fmt) {
509 	case S_IFCHR:
510 		cd->sc_dk.dk_copenmask &= ~(1 << part);
511 		break;
512 	case S_IFBLK:
513 		cd->sc_dk.dk_bopenmask &= ~(1 << part);
514 		break;
515 	}
516 	cd->sc_dk.dk_openmask =
517 	    cd->sc_dk.dk_copenmask | cd->sc_dk.dk_bopenmask;
518 
519 	if (cd->sc_dk.dk_openmask == 0) {
520 		scsipi_wait_drain(periph);
521 
522 		scsipi_prevent(periph, PR_ALLOW,
523 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE |
524 		    XS_CTL_IGNORE_NOT_READY);
525 		periph->periph_flags &= ~PERIPH_OPEN;
526 
527 		scsipi_wait_drain(periph);
528 
529 		scsipi_adapter_delref(adapt);
530 	}
531 
532 	cdunlock(cd);
533 	return (0);
534 }
535 
536 /*
537  * Actually translate the requested transfer into one the physical driver can
538  * understand.  The transfer is described by a buf and will include only one
539  * physical transfer.
540  */
541 void
542 cdstrategy(bp)
543 	struct buf *bp;
544 {
545 	struct cd_softc *cd = cd_cd.cd_devs[CDUNIT(bp->b_dev)];
546 	struct disklabel *lp;
547 	struct scsipi_periph *periph = cd->sc_periph;
548 	daddr_t blkno;
549 	int s;
550 
551 	SC_DEBUG(cd->sc_periph, SCSIPI_DB2, ("cdstrategy "));
552 	SC_DEBUG(cd->sc_periph, SCSIPI_DB1,
553 	    ("%ld bytes @ blk %" PRId64 "\n", bp->b_bcount, bp->b_blkno));
554 	/*
555 	 * If the device has been made invalid, error out
556 	 * maybe the media changed
557 	 */
558 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
559 		if (periph->periph_flags & PERIPH_OPEN)
560 			bp->b_error = EIO;
561 		else
562 			bp->b_error = ENODEV;
563 		goto bad;
564 	}
565 
566 	lp = cd->sc_dk.dk_label;
567 
568 	/*
569 	 * The transfer must be a whole number of blocks, offset must not
570 	 * be negative.
571 	 */
572 	if ((bp->b_bcount % lp->d_secsize) != 0 ||
573 	    bp->b_blkno < 0 ) {
574 		bp->b_error = EINVAL;
575 		goto bad;
576 	}
577 	/*
578 	 * If it's a null transfer, return immediately
579 	 */
580 	if (bp->b_bcount == 0)
581 		goto done;
582 
583 	/*
584 	 * Do bounds checking, adjust transfer. if error, process.
585 	 * If end of partition, just return.
586 	 */
587 	if (CDPART(bp->b_dev) == RAW_PART) {
588 		if (bounds_check_with_mediasize(bp, DEV_BSIZE,
589 		    cd->params.disksize512) <= 0)
590 			goto done;
591 	} else {
592 		if (bounds_check_with_label(&cd->sc_dk, bp,
593 		    (cd->flags & (CDF_WLABEL|CDF_LABELLING)) != 0) <= 0)
594 			goto done;
595 	}
596 
597 	/*
598 	 * Now convert the block number to absolute and put it in
599 	 * terms of the device's logical block size.
600 	 */
601 	blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE);
602 	if (CDPART(bp->b_dev) != RAW_PART)
603 		blkno += lp->d_partitions[CDPART(bp->b_dev)].p_offset;
604 
605 	bp->b_rawblkno = blkno;
606 
607 	/*
608 	 * If the disklabel sector size does not match the device
609 	 * sector size we may need to do some extra work.
610 	 */
611 	if (lp->d_secsize != cd->params.blksize) {
612 
613 		/*
614 		 * If the xfer is not a multiple of the device block size
615 		 * or it is not block aligned, we need to bounce it.
616 		 */
617 		if ((bp->b_bcount % cd->params.blksize) != 0 ||
618 			((blkno * lp->d_secsize) % cd->params.blksize) != 0) {
619 			struct buf *nbp;
620 			void *bounce = NULL;
621 			long count;
622 
623 			if ((bp->b_flags & B_READ) == 0) {
624 
625 				/* XXXX We don't support bouncing writes. */
626 				bp->b_error = EACCES;
627 				goto bad;
628 			}
629 			count = ((blkno * lp->d_secsize) % cd->params.blksize);
630 			/* XXX Store starting offset in bp->b_rawblkno */
631 			bp->b_rawblkno = count;
632 
633 			count += bp->b_bcount;
634 			count = roundup(count, cd->params.blksize);
635 
636 			blkno = ((blkno * lp->d_secsize) / cd->params.blksize);
637 			s = splbio();
638 			nbp = pool_get(&bufpool, PR_NOWAIT);
639 			splx(s);
640 			if (!nbp) {
641 				/* No memory -- fail the iop. */
642 				bp->b_error = ENOMEM;
643 				goto bad;
644 			}
645 			bounce = malloc(count, M_DEVBUF, M_NOWAIT);
646 			if (!bounce) {
647 				/* No memory -- fail the iop. */
648 				s = splbio();
649 				pool_put(&bufpool, nbp);
650 				splx(s);
651 				bp->b_error = ENOMEM;
652 				goto bad;
653 			}
654 
655 			/* Set up the IOP to the bounce buffer. */
656 			BUF_INIT(nbp);
657 			nbp->b_error = 0;
658 			nbp->b_proc = bp->b_proc;
659 			nbp->b_vp = NULLVP;
660 
661 			nbp->b_bcount = count;
662 			nbp->b_bufsize = count;
663 			nbp->b_data = bounce;
664 
665 			nbp->b_rawblkno = blkno;
666 
667 			/* We need to do a read-modify-write operation */
668 			nbp->b_flags = bp->b_flags | B_READ | B_CALL;
669 			nbp->b_iodone = cdbounce;
670 
671 			/* Put ptr to orig buf in b_private and use new buf */
672 			nbp->b_private = bp;
673 			bp = nbp;
674 
675 		} else {
676 			/* Xfer is aligned -- just adjust the start block */
677 			bp->b_rawblkno = (blkno * lp->d_secsize) /
678 				cd->params.blksize;
679 		}
680 	}
681 	s = splbio();
682 
683 	/*
684 	 * Place it in the queue of disk activities for this disk.
685 	 *
686 	 * XXX Only do disksort() if the current operating mode does not
687 	 * XXX include tagged queueing.
688 	 */
689 	BUFQ_PUT(&cd->buf_queue, bp);
690 
691 	/*
692 	 * Tell the device to get going on the transfer if it's
693 	 * not doing anything, otherwise just wait for completion
694 	 */
695 	cdstart(cd->sc_periph);
696 
697 	splx(s);
698 	return;
699 
700 bad:
701 	bp->b_flags |= B_ERROR;
702 done:
703 	/*
704 	 * Correctly set the buf to indicate a completed xfer
705 	 */
706 	bp->b_resid = bp->b_bcount;
707 	biodone(bp);
708 }
709 
710 /*
711  * cdstart looks to see if there is a buf waiting for the device
712  * and that the device is not already busy. If both are true,
713  * It deques the buf and creates a scsi command to perform the
714  * transfer in the buf. The transfer request will call scsipi_done
715  * on completion, which will in turn call this routine again
716  * so that the next queued transfer is performed.
717  * The bufs are queued by the strategy routine (cdstrategy)
718  *
719  * This routine is also called after other non-queued requests
720  * have been made of the scsi driver, to ensure that the queue
721  * continues to be drained.
722  *
723  * must be called at the correct (highish) spl level
724  * cdstart() is called at splbio from cdstrategy and scsipi_done
725  */
726 void
727 cdstart(periph)
728 	struct scsipi_periph *periph;
729 {
730 	struct cd_softc *cd = (void *)periph->periph_dev;
731 	struct buf *bp = 0;
732 	struct scsipi_rw_big cmd_big;
733 #if NCD_SCSIBUS > 0
734 	struct scsi_rw cmd_small;
735 #endif
736 	struct scsipi_generic *cmdp;
737 	int flags, nblks, cmdlen, error;
738 
739 	SC_DEBUG(periph, SCSIPI_DB2, ("cdstart "));
740 	/*
741 	 * Check if the device has room for another command
742 	 */
743 	while (periph->periph_active < periph->periph_openings) {
744 		/*
745 		 * there is excess capacity, but a special waits
746 		 * It'll need the adapter as soon as we clear out of the
747 		 * way and let it run (user level wait).
748 		 */
749 		if (periph->periph_flags & PERIPH_WAITING) {
750 			periph->periph_flags &= ~PERIPH_WAITING;
751 			wakeup((caddr_t)periph);
752 			return;
753 		}
754 
755 		/*
756 		 * See if there is a buf with work for us to do..
757 		 */
758 		if ((bp = BUFQ_GET(&cd->buf_queue)) == NULL)
759 			return;
760 
761 		/*
762 		 * If the device has become invalid, abort all the
763 		 * reads and writes until all files have been closed and
764 		 * re-opened
765 		 */
766 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
767 			bp->b_error = EIO;
768 			bp->b_flags |= B_ERROR;
769 			bp->b_resid = bp->b_bcount;
770 			biodone(bp);
771 			continue;
772 		}
773 
774 		/*
775 		 * We have a buf, now we should make a command.
776 		 */
777 
778 		nblks = howmany(bp->b_bcount, cd->params.blksize);
779 
780 #if NCD_SCSIBUS > 0
781 		/*
782 		 *  Fill out the scsi command.  If the transfer will
783 		 *  fit in a "small" cdb, use it.
784 		 */
785 		if (((bp->b_rawblkno & 0x1fffff) == bp->b_rawblkno) &&
786 		    ((nblks & 0xff) == nblks) &&
787 		    !(periph->periph_quirks & PQUIRK_ONLYBIG) &&
788 		    scsipi_periph_bustype(periph) == SCSIPI_BUSTYPE_SCSI) {
789 			/*
790 			 * We can fit in a small cdb.
791 			 */
792 			memset(&cmd_small, 0, sizeof(cmd_small));
793 			cmd_small.opcode = (bp->b_flags & B_READ) ?
794 			    SCSI_READ_COMMAND : SCSI_WRITE_COMMAND;
795 			_lto3b(bp->b_rawblkno, cmd_small.addr);
796 			cmd_small.length = nblks & 0xff;
797 			cmdlen = sizeof(cmd_small);
798 			cmdp = (struct scsipi_generic *)&cmd_small;
799 		} else
800 #endif
801 		{
802 			/*
803 			 * Need a large cdb.
804 			 */
805 			memset(&cmd_big, 0, sizeof(cmd_big));
806 			cmd_big.opcode = (bp->b_flags & B_READ) ?
807 			    READ_BIG : WRITE_BIG;
808 			_lto4b(bp->b_rawblkno, cmd_big.addr);
809 			_lto2b(nblks, cmd_big.length);
810 			cmdlen = sizeof(cmd_big);
811 			cmdp = (struct scsipi_generic *)&cmd_big;
812 		}
813 
814 		/* Instrumentation. */
815 		disk_busy(&cd->sc_dk);
816 
817 		/*
818 		 * Figure out what flags to use.
819 		 */
820 		flags = XS_CTL_NOSLEEP|XS_CTL_ASYNC|XS_CTL_SIMPLE_TAG;
821 		if (bp->b_flags & B_READ)
822 			flags |= XS_CTL_DATA_IN;
823 		else
824 			flags |= XS_CTL_DATA_OUT;
825 
826 		/*
827 		 * Call the routine that chats with the adapter.
828 		 * Note: we cannot sleep as we may be an interrupt
829 		 */
830 		error = scsipi_command(periph, cmdp, cmdlen,
831 		    (u_char *)bp->b_data, bp->b_bcount,
832 		    CDRETRIES, 30000, bp, flags);
833 		if (error) {
834 			disk_unbusy(&cd->sc_dk, 0, 0);
835 			printf("%s: not queued, error %d\n",
836 			    cd->sc_dev.dv_xname, error);
837 		}
838 	}
839 }
840 
841 void
842 cddone(xs)
843 	struct scsipi_xfer *xs;
844 {
845 	struct cd_softc *cd = (void *)xs->xs_periph->periph_dev;
846 
847 	if (xs->bp != NULL) {
848 		disk_unbusy(&cd->sc_dk, xs->bp->b_bcount - xs->bp->b_resid,
849 		    (xs->bp->b_flags & B_READ));
850 #if NRND > 0
851 		rnd_add_uint32(&cd->rnd_source, xs->bp->b_rawblkno);
852 #endif
853 	}
854 }
855 
856 void
857 cdbounce(bp)
858 	struct buf *bp;
859 {
860 	struct buf *obp = (struct buf *)bp->b_private;
861 
862 	if (bp->b_flags & B_ERROR) {
863 		/* EEK propagate the error and free the memory */
864 		goto done;
865 	}
866 	if (obp->b_flags & B_READ) {
867 		/* Copy data to the final destination and free the buf. */
868 		memcpy(obp->b_data, bp->b_data+obp->b_rawblkno,
869 			obp->b_bcount);
870 	} else {
871 		/*
872 		 * XXXX This is a CD-ROM -- READ ONLY -- why do we bother with
873 		 * XXXX any of this write stuff?
874 		 */
875 		if (bp->b_flags & B_READ) {
876 			struct cd_softc *cd = cd_cd.cd_devs[CDUNIT(bp->b_dev)];
877 			struct buf *nbp;
878 			int s;
879 
880 			/* Read part of RMW complete. */
881 			memcpy(bp->b_data+obp->b_rawblkno, obp->b_data,
882 				obp->b_bcount);
883 
884 			s = splbio();
885 
886 			/* We need to alloc a new buf. */
887 			nbp = pool_get(&bufpool, PR_NOWAIT);
888 			if (!nbp) {
889 				splx(s);
890 				/* No buf available. */
891 				bp->b_flags |= B_ERROR;
892 				bp->b_error = ENOMEM;
893 				bp->b_resid = bp->b_bcount;
894 			}
895 
896 			/* Set up the IOP to the bounce buffer. */
897 			BUF_INIT(nbp);
898 			nbp->b_error = 0;
899 			nbp->b_proc = bp->b_proc;
900 			nbp->b_vp = NULLVP;
901 
902 			nbp->b_bcount = bp->b_bcount;
903 			nbp->b_bufsize = bp->b_bufsize;
904 			nbp->b_data = bp->b_data;
905 
906 			nbp->b_rawblkno = bp->b_rawblkno;
907 
908 			/* We need to do a read-modify-write operation */
909 			nbp->b_flags = obp->b_flags | B_CALL;
910 			nbp->b_iodone = cdbounce;
911 
912 			/* Put ptr to orig buf in b_private and use new buf */
913 			nbp->b_private = obp;
914 
915 			/*
916 			 * Place it in the queue of disk activities for this
917 			 * disk.
918 			 *
919 			 * XXX Only do disksort() if the current operating mode
920 			 * XXX does not include tagged queueing.
921 			 */
922 			BUFQ_PUT(&cd->buf_queue, nbp);
923 
924 			/*
925 			 * Tell the device to get going on the transfer if it's
926 			 * not doing anything, otherwise just wait for
927 			 * completion
928 			 */
929 			cdstart(cd->sc_periph);
930 
931 			splx(s);
932 			return;
933 
934 		}
935 	}
936 done:
937 	obp->b_flags |= (bp->b_flags&(B_EINTR|B_ERROR));
938 	obp->b_error = bp->b_error;
939 	obp->b_resid = bp->b_resid;
940 	free(bp->b_data, M_DEVBUF);
941 	biodone(obp);
942 }
943 
944 int cd_interpret_sense(xs)
945 	struct scsipi_xfer *xs;
946 {
947 	struct scsipi_periph *periph = xs->xs_periph;
948 	struct scsipi_sense_data *sense = &xs->sense.scsi_sense;
949 	int retval = EJUSTRETURN;
950 
951 	/*
952 	 * If it isn't a extended or extended/deferred error, let
953 	 * the generic code handle it.
954 	 */
955 	if ((sense->error_code & SSD_ERRCODE) != 0x70 &&
956 	    (sense->error_code & SSD_ERRCODE) != 0x71) {	/* DEFERRED */
957 		return (retval);
958 	}
959 
960 	/*
961 	 * If we got a "Unit not ready" (SKEY_NOT_READY) and "Logical Unit
962 	 * Is In The Process of Becoming Ready" (Sense code 0x04,0x01), then
963 	 * wait a bit for the drive to spin up
964 	 */
965 
966 	if ((sense->flags & SSD_KEY) == SKEY_NOT_READY &&
967 	    sense->add_sense_code == 0x4 &&
968 	    sense->add_sense_code_qual == 0x01)	{
969 		/*
970 		 * Sleep for 5 seconds to wait for the drive to spin up
971 		 */
972 
973 		SC_DEBUG(periph, SCSIPI_DB1, ("Waiting 5 sec for CD "
974 						"spinup\n"));
975 		if (!callout_pending(&periph->periph_callout))
976 			scsipi_periph_freeze(periph, 1);
977 		callout_reset(&periph->periph_callout,
978 		    5 * hz, scsipi_periph_timed_thaw, periph);
979 		retval = ERESTART;
980 	}
981 	return (retval);
982 }
983 
984 void
985 cdminphys(bp)
986 	struct buf *bp;
987 {
988 	struct cd_softc *cd = cd_cd.cd_devs[CDUNIT(bp->b_dev)];
989 	long max;
990 
991 	/*
992 	 * If the device is ancient, we want to make sure that
993 	 * the transfer fits into a 6-byte cdb.
994 	 *
995 	 * XXX Note that the SCSI-I spec says that 256-block transfers
996 	 * are allowed in a 6-byte read/write, and are specified
997 	 * by settng the "length" to 0.  However, we're conservative
998 	 * here, allowing only 255-block transfers in case an
999 	 * ancient device gets confused by length == 0.  A length of 0
1000 	 * in a 10-byte read/write actually means 0 blocks.
1001 	 */
1002 	if (cd->flags & CDF_ANCIENT) {
1003 		max = cd->sc_dk.dk_label->d_secsize * 0xff;
1004 
1005 		if (bp->b_bcount > max)
1006 			bp->b_bcount = max;
1007 	}
1008 
1009 	(*cd->sc_periph->periph_channel->chan_adapter->adapt_minphys)(bp);
1010 }
1011 
1012 int
1013 cdread(dev, uio, ioflag)
1014 	dev_t dev;
1015 	struct uio *uio;
1016 	int ioflag;
1017 {
1018 
1019 	return (physio(cdstrategy, NULL, dev, B_READ, cdminphys, uio));
1020 }
1021 
1022 int
1023 cdwrite(dev, uio, ioflag)
1024 	dev_t dev;
1025 	struct uio *uio;
1026 	int ioflag;
1027 {
1028 
1029 	return (physio(cdstrategy, NULL, dev, B_WRITE, cdminphys, uio));
1030 }
1031 
1032 /*
1033  * conversion between minute-seconde-frame and logical block adress
1034  * adresses format
1035  */
1036 void
1037 lba2msf (lba, m, s, f)
1038 	u_long lba;
1039 	u_char *m, *s, *f;
1040 {
1041 	u_long tmp;
1042 
1043 	tmp = lba + CD_BLOCK_OFFSET;	/* offset of first logical frame */
1044 	tmp &= 0xffffff;		/* negative lbas use only 24 bits */
1045 	*m = tmp / (CD_SECS * CD_FRAMES);
1046 	tmp %= (CD_SECS * CD_FRAMES);
1047 	*s = tmp / CD_FRAMES;
1048 	*f = tmp % CD_FRAMES;
1049 }
1050 
1051 u_long
1052 msf2lba (m, s, f)
1053 	u_char m, s, f;
1054 {
1055 
1056 	return ((((m * CD_SECS) + s) * CD_FRAMES + f) - CD_BLOCK_OFFSET);
1057 }
1058 
1059 int
1060 cdreadmsaddr(cd, addr)
1061 	struct cd_softc *cd;
1062 	int *addr;
1063 {
1064 	struct scsipi_periph *periph = cd->sc_periph;
1065 	int error;
1066 	struct cd_toc toc;
1067 	struct cd_toc_entry *cte;
1068 
1069 	error = cd_read_toc(cd, 0, 0, &toc,
1070 	    sizeof(struct ioc_toc_header) + sizeof(struct cd_toc_entry),
1071 	    XS_CTL_DATA_ONSTACK,
1072 	    0x40 /* control word for "get MS info" */);
1073 
1074 	if (error)
1075 		return (error);
1076 
1077 	cte = &toc.entries[0];
1078 	if (periph->periph_quirks & PQUIRK_LITTLETOC) {
1079 		cte->addr.lba = le32toh(cte->addr.lba);
1080 		toc.header.len = le16toh(toc.header.len);
1081 	} else {
1082 		cte->addr.lba = be32toh(cte->addr.lba);
1083 		toc.header.len = be16toh(toc.header.len);
1084 	}
1085 
1086 	*addr = (toc.header.len >= 10 && cte->track > 1) ?
1087 		cte->addr.lba : 0;
1088 	return 0;
1089 }
1090 
1091 /*
1092  * Perform special action on behalf of the user.
1093  * Knows about the internals of this device
1094  */
1095 int
1096 cdioctl(dev, cmd, addr, flag, p)
1097 	dev_t dev;
1098 	u_long cmd;
1099 	caddr_t addr;
1100 	int flag;
1101 	struct proc *p;
1102 {
1103 	struct cd_softc *cd = cd_cd.cd_devs[CDUNIT(dev)];
1104 	struct scsipi_periph *periph = cd->sc_periph;
1105 	int part = CDPART(dev);
1106 	int error = 0;
1107 #ifdef __HAVE_OLD_DISKLABEL
1108 	struct disklabel *newlabel = NULL;
1109 #endif
1110 
1111 	SC_DEBUG(cd->sc_periph, SCSIPI_DB2, ("cdioctl 0x%lx ", cmd));
1112 
1113 	/*
1114 	 * If the device is not valid, some IOCTLs can still be
1115 	 * handled on the raw partition. Check this here.
1116 	 */
1117 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
1118 		switch (cmd) {
1119 		case DIOCWLABEL:
1120 		case DIOCLOCK:
1121 		case ODIOCEJECT:
1122 		case DIOCEJECT:
1123 		case SCIOCIDENTIFY:
1124 		case OSCIOCIDENTIFY:
1125 		case SCIOCCOMMAND:
1126 		case SCIOCDEBUG:
1127 		case CDIOCGETVOL:
1128 		case CDIOCSETVOL:
1129 		case CDIOCSETMONO:
1130 		case CDIOCSETSTEREO:
1131 		case CDIOCSETMUTE:
1132 		case CDIOCSETLEFT:
1133 		case CDIOCSETRIGHT:
1134 		case CDIOCCLOSE:
1135 		case CDIOCEJECT:
1136 		case CDIOCALLOW:
1137 		case CDIOCPREVENT:
1138 		case CDIOCSETDEBUG:
1139 		case CDIOCCLRDEBUG:
1140 		case CDIOCRESET:
1141 		case SCIOCRESET:
1142 		case CDIOCLOADUNLOAD:
1143 		case DVD_AUTH:
1144 		case DVD_READ_STRUCT:
1145 			if (part == RAW_PART)
1146 				break;
1147 		/* FALLTHROUGH */
1148 		default:
1149 			if ((periph->periph_flags & PERIPH_OPEN) == 0)
1150 				return (ENODEV);
1151 			else
1152 				return (EIO);
1153 		}
1154 	}
1155 
1156 	switch (cmd) {
1157 	case DIOCGDINFO:
1158 		*(struct disklabel *)addr = *(cd->sc_dk.dk_label);
1159 		return (0);
1160 #ifdef __HAVE_OLD_DISKLABEL
1161 	case ODIOCGDINFO:
1162 		newlabel = malloc(sizeof (*newlabel), M_TEMP, M_WAITOK);
1163 		if (newlabel == NULL)
1164 			return (EIO);
1165 		memcpy(newlabel, cd->sc_dk.dk_label, sizeof (*newlabel));
1166 		if (newlabel->d_npartitions > OLDMAXPARTITIONS)
1167 			error = ENOTTY;
1168 		else
1169 			memcpy(addr, newlabel, sizeof (struct olddisklabel));
1170 		free(newlabel, M_TEMP);
1171 		return error;
1172 #endif
1173 
1174 	case DIOCGPART:
1175 		((struct partinfo *)addr)->disklab = cd->sc_dk.dk_label;
1176 		((struct partinfo *)addr)->part =
1177 		    &cd->sc_dk.dk_label->d_partitions[part];
1178 		return (0);
1179 
1180 	case DIOCWDINFO:
1181 	case DIOCSDINFO:
1182 #ifdef __HAVE_OLD_DISKLABEL
1183 	case ODIOCWDINFO:
1184 	case ODIOCSDINFO:
1185 #endif
1186 	{
1187 		struct disklabel *lp;
1188 
1189 		if ((flag & FWRITE) == 0)
1190 			return (EBADF);
1191 
1192 #ifdef __HAVE_OLD_DISKLABEL
1193 		if (cmd == ODIOCSDINFO || cmd == ODIOCWDINFO) {
1194 			newlabel = malloc(sizeof (*newlabel), M_TEMP, M_WAITOK);
1195 			if (newlabel == NULL)
1196 				return (EIO);
1197 			memset(newlabel, 0, sizeof newlabel);
1198 			memcpy(newlabel, addr, sizeof (struct olddisklabel));
1199 			lp = newlabel;
1200 		} else
1201 #endif
1202 		lp = (struct disklabel *)addr;
1203 
1204 		if ((error = cdlock(cd)) != 0)
1205 			goto bad;
1206 		cd->flags |= CDF_LABELLING;
1207 
1208 		error = setdisklabel(cd->sc_dk.dk_label,
1209 		    lp, /*cd->sc_dk.dk_openmask : */0,
1210 		    cd->sc_dk.dk_cpulabel);
1211 		if (error == 0) {
1212 			/* XXX ? */
1213 		}
1214 
1215 		cd->flags &= ~CDF_LABELLING;
1216 		cdunlock(cd);
1217 bad:
1218 #ifdef __HAVE_OLD_DISKLABEL
1219 		if (newlabel != NULL)
1220 			free(newlabel, M_TEMP);
1221 #endif
1222 		return (error);
1223 	}
1224 
1225 	case DIOCWLABEL:
1226 		return (EBADF);
1227 
1228 	case DIOCGDEFLABEL:
1229 		cdgetdefaultlabel(cd, (struct disklabel *)addr);
1230 		return (0);
1231 
1232 #ifdef __HAVE_OLD_DISKLABEL
1233 	case ODIOCGDEFLABEL:
1234 		newlabel = malloc(sizeof (*newlabel), M_TEMP, M_WAITOK);
1235 		if (newlabel == NULL)
1236 			return (EIO);
1237 		cdgetdefaultlabel(cd, newlabel);
1238 		if (newlabel->d_npartitions > OLDMAXPARTITIONS)
1239 			error = ENOTTY;
1240 		else
1241 			memcpy(addr, newlabel, sizeof (struct olddisklabel));
1242 		free(newlabel, M_TEMP);
1243 		return error;
1244 #endif
1245 
1246 	case CDIOCPLAYTRACKS: {
1247 		struct ioc_play_track *args = (struct ioc_play_track *)addr;
1248 
1249 		if ((error = (*cd->sc_ops->cdo_set_pa_immed)(cd, 0)) != 0)
1250 			return (error);
1251 		return (cd_play_tracks(cd, args->start_track,
1252 		    args->start_index, args->end_track, args->end_index));
1253 	}
1254 	case CDIOCPLAYMSF: {
1255 		struct ioc_play_msf *args = (struct ioc_play_msf *)addr;
1256 
1257 		if ((error = (*cd->sc_ops->cdo_set_pa_immed)(cd, 0)) != 0)
1258 			return (error);
1259 		return (cd_play_msf(cd, args->start_m, args->start_s,
1260 		    args->start_f, args->end_m, args->end_s, args->end_f));
1261 	}
1262 	case CDIOCPLAYBLOCKS: {
1263 		struct ioc_play_blocks *args = (struct ioc_play_blocks *)addr;
1264 
1265 		if ((error = (*cd->sc_ops->cdo_set_pa_immed)(cd, 0)) != 0)
1266 			return (error);
1267 		return (cd_play(cd, args->blk, args->len));
1268 	}
1269 	case CDIOCREADSUBCHANNEL: {
1270 		struct ioc_read_subchannel *args =
1271 		    (struct ioc_read_subchannel *)addr;
1272 		struct cd_sub_channel_info data;
1273 		u_int len = args->data_len;
1274 
1275 		if (len > sizeof(data) ||
1276 		    len < sizeof(struct cd_sub_channel_header))
1277 			return (EINVAL);
1278 		error = cd_read_subchannel(cd, args->address_format,
1279 		    args->data_format, args->track, &data, len,
1280 		    XS_CTL_DATA_ONSTACK);
1281 		if (error)
1282 			return (error);
1283 		len = min(len, _2btol(data.header.data_len) +
1284 		    sizeof(struct cd_sub_channel_header));
1285 		return (copyout(&data, args->data, len));
1286 	}
1287 	case CDIOREADTOCHEADER: {
1288 		struct ioc_toc_header th;
1289 
1290 		if ((error = cd_read_toc(cd, 0, 0, &th, sizeof(th),
1291 		    XS_CTL_DATA_ONSTACK, 0)) != 0)
1292 			return (error);
1293 		if (cd->sc_periph->periph_quirks & PQUIRK_LITTLETOC)
1294 			th.len = le16toh(th.len);
1295 		else
1296 			th.len = be16toh(th.len);
1297 		memcpy(addr, &th, sizeof(th));
1298 		return (0);
1299 	}
1300 	case CDIOREADTOCENTRYS: {
1301 		struct cd_toc toc;
1302 		struct ioc_read_toc_entry *te =
1303 		    (struct ioc_read_toc_entry *)addr;
1304 		struct ioc_toc_header *th;
1305 		struct cd_toc_entry *cte;
1306 		u_int len = te->data_len;
1307 		int ntracks;
1308 
1309 		th = &toc.header;
1310 
1311 		if (len > sizeof(toc.entries) ||
1312 		    len < sizeof(struct cd_toc_entry))
1313 			return (EINVAL);
1314 		error = cd_read_toc(cd, te->address_format, te->starting_track,
1315 		    &toc, len + sizeof(struct ioc_toc_header),
1316 		    XS_CTL_DATA_ONSTACK, 0);
1317 		if (error)
1318 			return (error);
1319 		if (te->address_format == CD_LBA_FORMAT)
1320 			for (ntracks =
1321 			    th->ending_track - th->starting_track + 1;
1322 			    ntracks >= 0; ntracks--) {
1323 				cte = &toc.entries[ntracks];
1324 				cte->addr_type = CD_LBA_FORMAT;
1325 				if (periph->periph_quirks & PQUIRK_LITTLETOC)
1326 					cte->addr.lba = le32toh(cte->addr.lba);
1327 				else
1328 					cte->addr.lba = be32toh(cte->addr.lba);
1329 			}
1330 		if (periph->periph_quirks & PQUIRK_LITTLETOC)
1331 			th->len = le16toh(th->len);
1332 		else
1333 			th->len = be16toh(th->len);
1334 		len = min(len, th->len - (sizeof(th->starting_track) +
1335 		    sizeof(th->ending_track)));
1336 		return (copyout(toc.entries, te->data, len));
1337 	}
1338 	case CDIOREADMSADDR: {
1339 		int sessno = *(int*)addr;
1340 
1341 		if (sessno != 0)
1342 			return (EINVAL);
1343 
1344 		return (cdreadmsaddr(cd, (int*)addr));
1345 	}
1346 	case CDIOCSETPATCH: {
1347 		struct ioc_patch *arg = (struct ioc_patch *)addr;
1348 
1349 		return ((*cd->sc_ops->cdo_setchan)(cd, arg->patch[0],
1350 		    arg->patch[1], arg->patch[2], arg->patch[3], 0));
1351 	}
1352 	case CDIOCGETVOL: {
1353 		struct ioc_vol *arg = (struct ioc_vol *)addr;
1354 
1355 		return ((*cd->sc_ops->cdo_getvol)(cd, arg, 0));
1356 	}
1357 	case CDIOCSETVOL: {
1358 		struct ioc_vol *arg = (struct ioc_vol *)addr;
1359 
1360 		return ((*cd->sc_ops->cdo_setvol)(cd, arg, 0));
1361 	}
1362 
1363 	case CDIOCSETMONO:
1364 		return ((*cd->sc_ops->cdo_setchan)(cd, BOTH_CHANNEL,
1365 		    BOTH_CHANNEL, MUTE_CHANNEL, MUTE_CHANNEL, 0));
1366 
1367 	case CDIOCSETSTEREO:
1368 		return ((*cd->sc_ops->cdo_setchan)(cd, LEFT_CHANNEL,
1369 		    RIGHT_CHANNEL, MUTE_CHANNEL, MUTE_CHANNEL, 0));
1370 
1371 	case CDIOCSETMUTE:
1372 		return ((*cd->sc_ops->cdo_setchan)(cd, MUTE_CHANNEL,
1373 		    MUTE_CHANNEL, MUTE_CHANNEL, MUTE_CHANNEL, 0));
1374 
1375 	case CDIOCSETLEFT:
1376 		return ((*cd->sc_ops->cdo_setchan)(cd, LEFT_CHANNEL,
1377 		    LEFT_CHANNEL, MUTE_CHANNEL, MUTE_CHANNEL, 0));
1378 
1379 	case CDIOCSETRIGHT:
1380 		return ((*cd->sc_ops->cdo_setchan)(cd, RIGHT_CHANNEL,
1381 		    RIGHT_CHANNEL, MUTE_CHANNEL, MUTE_CHANNEL, 0));
1382 
1383 	case CDIOCRESUME:
1384 		return (cd_pause(cd, PA_RESUME));
1385 	case CDIOCPAUSE:
1386 		return (cd_pause(cd, PA_PAUSE));
1387 	case CDIOCSTART:
1388 		return (scsipi_start(periph, SSS_START, 0));
1389 	case CDIOCSTOP:
1390 		return (scsipi_start(periph, SSS_STOP, 0));
1391 	case CDIOCCLOSE:
1392 		return (scsipi_start(periph, SSS_START|SSS_LOEJ,
1393 		    XS_CTL_IGNORE_NOT_READY | XS_CTL_IGNORE_MEDIA_CHANGE));
1394 	case DIOCEJECT:
1395 		if (*(int *)addr == 0) {
1396 			/*
1397 			 * Don't force eject: check that we are the only
1398 			 * partition open. If so, unlock it.
1399 			 */
1400 			if ((cd->sc_dk.dk_openmask & ~(1 << part)) == 0 &&
1401 			    cd->sc_dk.dk_bopenmask + cd->sc_dk.dk_copenmask ==
1402 			    cd->sc_dk.dk_openmask) {
1403 				error = scsipi_prevent(periph, PR_ALLOW,
1404 				    XS_CTL_IGNORE_NOT_READY);
1405 				if (error)
1406 					return (error);
1407 			} else {
1408 				return (EBUSY);
1409 			}
1410 		}
1411 		/* FALLTHROUGH */
1412 	case CDIOCEJECT: /* FALLTHROUGH */
1413 	case ODIOCEJECT:
1414 		return (scsipi_start(periph, SSS_STOP|SSS_LOEJ, 0));
1415 	case CDIOCALLOW:
1416 		return (scsipi_prevent(periph, PR_ALLOW, 0));
1417 	case CDIOCPREVENT:
1418 		return (scsipi_prevent(periph, PR_PREVENT, 0));
1419 	case DIOCLOCK:
1420 		return (scsipi_prevent(periph,
1421 		    (*(int *)addr) ? PR_PREVENT : PR_ALLOW, 0));
1422 	case CDIOCSETDEBUG:
1423 		cd->sc_periph->periph_dbflags |= (SCSIPI_DB1 | SCSIPI_DB2);
1424 		return (0);
1425 	case CDIOCCLRDEBUG:
1426 		cd->sc_periph->periph_dbflags &= ~(SCSIPI_DB1 | SCSIPI_DB2);
1427 		return (0);
1428 	case CDIOCRESET:
1429 	case SCIOCRESET:
1430 		return (cd_reset(cd));
1431 	case CDIOCLOADUNLOAD: {
1432 		struct ioc_load_unload *args = (struct ioc_load_unload *)addr;
1433 
1434 		return ((*cd->sc_ops->cdo_load_unload)(cd, args->options,
1435 			args->slot));
1436 	case DVD_AUTH:
1437 		return (dvd_auth(cd, (dvd_authinfo *)addr));
1438 	case DVD_READ_STRUCT:
1439 		return (dvd_read_struct(cd, (dvd_struct *)addr));
1440 	}
1441 
1442 	default:
1443 		if (part != RAW_PART)
1444 			return (ENOTTY);
1445 		return (scsipi_do_ioctl(periph, dev, cmd, addr, flag, p));
1446 	}
1447 
1448 #ifdef DIAGNOSTIC
1449 	panic("cdioctl: impossible");
1450 #endif
1451 }
1452 
1453 void
1454 cdgetdefaultlabel(cd, lp)
1455 	struct cd_softc *cd;
1456 	struct disklabel *lp;
1457 {
1458 	int lastsession;
1459 
1460 	memset(lp, 0, sizeof(struct disklabel));
1461 
1462 	lp->d_secsize = cd->params.blksize;
1463 	lp->d_ntracks = 1;
1464 	lp->d_nsectors = 100;
1465 	lp->d_ncylinders = (cd->params.disksize / 100) + 1;
1466 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
1467 
1468 	switch (scsipi_periph_bustype(cd->sc_periph)) {
1469 #if NCD_SCSIBUS > 0
1470 	case SCSIPI_BUSTYPE_SCSI:
1471 		lp->d_type = DTYPE_SCSI;
1472 		break;
1473 #endif
1474 #if NCD_ATAPIBUS > 0
1475 	case SCSIPI_BUSTYPE_ATAPI:
1476 		lp->d_type = DTYPE_ATAPI;
1477 		break;
1478 #endif
1479 	}
1480 	strncpy(lp->d_typename, cd->name, 16);
1481 	strncpy(lp->d_packname, "fictitious", 16);
1482 	lp->d_secperunit = cd->params.disksize;
1483 	lp->d_rpm = 300;
1484 	lp->d_interleave = 1;
1485 	lp->d_flags = D_REMOVABLE;
1486 
1487 	if (cdreadmsaddr(cd, &lastsession) != 0)
1488 		lastsession = 0;
1489 
1490 	lp->d_partitions[0].p_offset = 0;
1491 #ifdef notyet /* have to fix bounds_check_with_label() first */
1492 	lp->d_partitions[0].p_size = lp->d_secperunit;
1493 #else
1494 	lp->d_partitions[0].p_size =
1495 	    lp->d_secperunit * (lp->d_secsize / DEV_BSIZE);
1496 #endif
1497 	lp->d_partitions[0].p_cdsession = lastsession;
1498 	lp->d_partitions[0].p_fstype = FS_ISO9660;
1499 	lp->d_partitions[RAW_PART].p_offset = 0;
1500 #ifdef notyet
1501 	lp->d_partitions[RAW_PART].p_size = lp->d_secperunit;
1502 #else
1503 	lp->d_partitions[RAW_PART].p_size =
1504 	    lp->d_secperunit * (lp->d_secsize / DEV_BSIZE);
1505 #endif
1506 	lp->d_partitions[RAW_PART].p_fstype = FS_ISO9660;
1507 	lp->d_npartitions = RAW_PART + 1;
1508 
1509 	lp->d_magic = DISKMAGIC;
1510 	lp->d_magic2 = DISKMAGIC;
1511 	lp->d_checksum = dkcksum(lp);
1512 }
1513 
1514 /*
1515  * Load the label information on the named device
1516  * Actually fabricate a disklabel
1517  *
1518  * EVENTUALLY take information about different
1519  * data tracks from the TOC and put it in the disklabel
1520  */
1521 void
1522 cdgetdisklabel(cd)
1523 	struct cd_softc *cd;
1524 {
1525 	struct disklabel *lp = cd->sc_dk.dk_label;
1526 	const char *errstring;
1527 
1528 	memset(cd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
1529 
1530 	cdgetdefaultlabel(cd, lp);
1531 
1532 	/*
1533 	 * Call the generic disklabel extraction routine
1534 	 */
1535 	errstring = readdisklabel(MAKECDDEV(0, cd->sc_dev.dv_unit, RAW_PART),
1536 	    cdstrategy, lp, cd->sc_dk.dk_cpulabel);
1537 	if (errstring) {
1538 		printf("%s: %s\n", cd->sc_dev.dv_xname, errstring);
1539 		goto error;
1540 	}
1541 	return;
1542 
1543 error:
1544 	/* Reset to default label -- should print a warning */
1545 	memset(cd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
1546 
1547 	cdgetdefaultlabel(cd, lp);
1548 }
1549 
1550 /*
1551  * Find out from the device what it's capacity is
1552  */
1553 u_long
1554 cd_size(cd, flags)
1555 	struct cd_softc *cd;
1556 	int flags;
1557 {
1558 	struct scsipi_read_cd_cap_data rdcap;
1559 	struct scsipi_read_cd_capacity scsipi_cmd;
1560 	int blksize;
1561 	u_long size;
1562 
1563 	if (cd->sc_periph->periph_quirks & PQUIRK_NOCAPACITY) {
1564 		/*
1565 		 * the drive doesn't support the READ_CD_CAPACITY command
1566 		 * use a fake size
1567 		 */
1568 		cd->params.blksize = 2048;
1569 		cd->params.disksize = 400000;
1570 		cd->params.disksize512 = 1600000;
1571 		return (400000);
1572 	}
1573 
1574 	/*
1575 	 * make up a scsi command and ask the scsi driver to do
1576 	 * it for you.
1577 	 */
1578 	memset(&scsipi_cmd, 0, sizeof(scsipi_cmd));
1579 	scsipi_cmd.opcode = READ_CD_CAPACITY;
1580 
1581 	/*
1582 	 * If the command works, interpret the result as a 4 byte
1583 	 * number of blocks and a blocksize
1584 	 */
1585 	if (scsipi_command(cd->sc_periph,
1586 	    (struct scsipi_generic *)&scsipi_cmd, sizeof(scsipi_cmd),
1587 	    (u_char *)&rdcap, sizeof(rdcap), CDRETRIES, 30000, NULL,
1588 	    flags | XS_CTL_DATA_IN | XS_CTL_DATA_IN) != 0)
1589 		return (0);
1590 
1591 	blksize = _4btol(rdcap.length);
1592 	if ((blksize < 512) || ((blksize & 511) != 0))
1593 		blksize = 2048;	/* some drives lie ! */
1594 	cd->params.blksize = blksize;
1595 
1596 	size = _4btol(rdcap.addr) + 1;
1597 	if (size < 100)
1598 		size = 400000;	/* ditto */
1599 	cd->params.disksize = size;
1600 	cd->params.disksize512 = (cd->params.disksize * blksize) / DEV_BSIZE;
1601 
1602 	SC_DEBUG(cd->sc_periph, SCSIPI_DB2,
1603 	    ("cd_size: %d %ld\n", blksize, size));
1604 	return (size);
1605 }
1606 
1607 /*
1608  * Get scsi driver to send a "start playing" command
1609  */
1610 int
1611 cd_play(cd, blkno, nblks)
1612 	struct cd_softc *cd;
1613 	int blkno, nblks;
1614 {
1615 	struct scsipi_play scsipi_cmd;
1616 
1617 	memset(&scsipi_cmd, 0, sizeof(scsipi_cmd));
1618 	scsipi_cmd.opcode = PLAY;
1619 	_lto4b(blkno, scsipi_cmd.blk_addr);
1620 	_lto2b(nblks, scsipi_cmd.xfer_len);
1621 	return (scsipi_command(cd->sc_periph,
1622 	    (struct scsipi_generic *)&scsipi_cmd, sizeof(scsipi_cmd),
1623 	    0, 0, CDRETRIES, 30000, NULL, 0));
1624 }
1625 
1626 /*
1627  * Get scsi driver to send a "start playing" command
1628  */
1629 int
1630 cd_play_tracks(cd, strack, sindex, etrack, eindex)
1631 	struct cd_softc *cd;
1632 	int strack, sindex, etrack, eindex;
1633 {
1634 	struct cd_toc toc;
1635 	int error;
1636 
1637 	if (!etrack)
1638 		return (EIO);
1639 	if (strack > etrack)
1640 		return (EINVAL);
1641 
1642 	if ((error = cd_load_toc(cd, &toc, XS_CTL_DATA_ONSTACK)) != 0)
1643 		return (error);
1644 
1645 	if (++etrack > (toc.header.ending_track+1))
1646 		etrack = toc.header.ending_track+1;
1647 
1648 	strack -= toc.header.starting_track;
1649 	etrack -= toc.header.starting_track;
1650 	if (strack < 0)
1651 		return (EINVAL);
1652 
1653 	return (cd_play_msf(cd, toc.entries[strack].addr.msf.minute,
1654 	    toc.entries[strack].addr.msf.second,
1655 	    toc.entries[strack].addr.msf.frame,
1656 	    toc.entries[etrack].addr.msf.minute,
1657 	    toc.entries[etrack].addr.msf.second,
1658 	    toc.entries[etrack].addr.msf.frame));
1659 }
1660 
1661 /*
1662  * Get scsi driver to send a "play msf" command
1663  */
1664 int
1665 cd_play_msf(cd, startm, starts, startf, endm, ends, endf)
1666 	struct cd_softc *cd;
1667 	int startm, starts, startf, endm, ends, endf;
1668 {
1669 	struct scsipi_play_msf scsipi_cmd;
1670 
1671 	memset(&scsipi_cmd, 0, sizeof(scsipi_cmd));
1672 	scsipi_cmd.opcode = PLAY_MSF;
1673 	scsipi_cmd.start_m = startm;
1674 	scsipi_cmd.start_s = starts;
1675 	scsipi_cmd.start_f = startf;
1676 	scsipi_cmd.end_m = endm;
1677 	scsipi_cmd.end_s = ends;
1678 	scsipi_cmd.end_f = endf;
1679 	return (scsipi_command(cd->sc_periph,
1680 	    (struct scsipi_generic *)&scsipi_cmd, sizeof(scsipi_cmd),
1681 	    0, 0, CDRETRIES, 30000, NULL, 0));
1682 }
1683 
1684 /*
1685  * Get scsi driver to send a "start up" command
1686  */
1687 int
1688 cd_pause(cd, go)
1689 	struct cd_softc *cd;
1690 	int go;
1691 {
1692 	struct scsipi_pause scsipi_cmd;
1693 
1694 	memset(&scsipi_cmd, 0, sizeof(scsipi_cmd));
1695 	scsipi_cmd.opcode = PAUSE;
1696 	scsipi_cmd.resume = go & 0xff;
1697 	return (scsipi_command(cd->sc_periph,
1698 	    (struct scsipi_generic *)&scsipi_cmd, sizeof(scsipi_cmd),
1699 	    0, 0, CDRETRIES, 30000, NULL, 0));
1700 }
1701 
1702 /*
1703  * Get scsi driver to send a "RESET" command
1704  */
1705 int
1706 cd_reset(cd)
1707 	struct cd_softc *cd;
1708 {
1709 
1710 	return (scsipi_command(cd->sc_periph, 0, 0, 0, 0,
1711 	    CDRETRIES, 30000, NULL, XS_CTL_RESET));
1712 }
1713 
1714 /*
1715  * Read subchannel
1716  */
1717 int
1718 cd_read_subchannel(cd, mode, format, track, data, len, flags)
1719 	struct cd_softc *cd;
1720 	int mode, format, track, len;
1721 	struct cd_sub_channel_info *data;
1722 	int flags;
1723 {
1724 	struct scsipi_read_subchannel scsipi_cmd;
1725 
1726 	memset(&scsipi_cmd, 0, sizeof(scsipi_cmd));
1727 	scsipi_cmd.opcode = READ_SUBCHANNEL;
1728 	if (mode == CD_MSF_FORMAT)
1729 		scsipi_cmd.byte2 |= CD_MSF;
1730 	scsipi_cmd.byte3 = SRS_SUBQ;
1731 	scsipi_cmd.subchan_format = format;
1732 	scsipi_cmd.track = track;
1733 	_lto2b(len, scsipi_cmd.data_len);
1734 	return (scsipi_command(cd->sc_periph,
1735 	    (struct scsipi_generic *)&scsipi_cmd,
1736 	    sizeof(struct scsipi_read_subchannel), (u_char *)data, len,
1737 	    CDRETRIES, 30000, NULL, flags | XS_CTL_DATA_IN | XS_CTL_SILENT));
1738 }
1739 
1740 /*
1741  * Read table of contents
1742  */
1743 int
1744 cd_read_toc(cd, mode, start, data, len, flags, control)
1745 	struct cd_softc *cd;
1746 	int mode, start, len, control;
1747 	void *data;
1748 	int flags;
1749 {
1750 	struct scsipi_read_toc scsipi_cmd;
1751 	int ntoc;
1752 
1753 	memset(&scsipi_cmd, 0, sizeof(scsipi_cmd));
1754 #if 0
1755 	if (len != sizeof(struct ioc_toc_header))
1756 		ntoc = ((len) - sizeof(struct ioc_toc_header)) /
1757 		    sizeof(struct cd_toc_entry);
1758 	else
1759 #endif
1760 	ntoc = len;
1761 	scsipi_cmd.opcode = READ_TOC;
1762 	if (mode == CD_MSF_FORMAT)
1763 		scsipi_cmd.byte2 |= CD_MSF;
1764 	scsipi_cmd.from_track = start;
1765 	_lto2b(ntoc, scsipi_cmd.data_len);
1766 	scsipi_cmd.control = control;
1767 	return (scsipi_command(cd->sc_periph,
1768 	    (struct scsipi_generic *)&scsipi_cmd,
1769 	    sizeof(struct scsipi_read_toc), (u_char *)data, len, CDRETRIES,
1770 	    30000, NULL, flags | XS_CTL_DATA_IN));
1771 }
1772 
1773 int
1774 cd_load_toc(cd, toc, flags)
1775 	struct cd_softc *cd;
1776 	struct cd_toc *toc;
1777 	int flags;
1778 {
1779 	int ntracks, len, error;
1780 
1781 	if ((error = cd_read_toc(cd, 0, 0, toc, sizeof(toc->header),
1782 	    flags, 0)) != 0)
1783 		return (error);
1784 
1785 	ntracks = toc->header.ending_track - toc->header.starting_track + 1;
1786 	len = (ntracks + 1) * sizeof(struct cd_toc_entry) +
1787 	    sizeof(toc->header);
1788 	if ((error = cd_read_toc(cd, CD_MSF_FORMAT, 0, toc, len,
1789 	    flags, 0)) != 0)
1790 		return (error);
1791 	return (0);
1792 }
1793 
1794 /*
1795  * Get the scsi driver to send a full inquiry to the device and use the
1796  * results to fill out the disk parameter structure.
1797  */
1798 int
1799 cd_get_parms(cd, flags)
1800 	struct cd_softc *cd;
1801 	int flags;
1802 {
1803 
1804 	/*
1805 	 * give a number of sectors so that sec * trks * cyls
1806 	 * is <= disk_size
1807 	 */
1808 	if (cd_size(cd, flags) == 0)
1809 		return (ENXIO);
1810 	return (0);
1811 }
1812 
1813 int
1814 cdsize(dev)
1815 	dev_t dev;
1816 {
1817 
1818 	/* CD-ROMs are read-only. */
1819 	return (-1);
1820 }
1821 
1822 int
1823 cddump(dev, blkno, va, size)
1824 	dev_t dev;
1825 	daddr_t blkno;
1826 	caddr_t va;
1827 	size_t size;
1828 {
1829 
1830 	/* Not implemented. */
1831 	return (ENXIO);
1832 }
1833 
1834 #define	dvd_copy_key(dst, src)		memcpy((dst), (src), sizeof(dvd_key))
1835 #define	dvd_copy_challenge(dst, src)	memcpy((dst), (src), sizeof(dvd_challenge))
1836 
1837 int
1838 dvd_auth(cd, a)
1839 	struct cd_softc *cd;
1840 	dvd_authinfo *a;
1841 {
1842 	struct scsipi_generic cmd;
1843 	u_int8_t buf[20];
1844 	int error;
1845 
1846 	memset(cmd.bytes, 0, 15);
1847 	memset(buf, 0, sizeof(buf));
1848 
1849 	switch (a->type) {
1850 	case DVD_LU_SEND_AGID:
1851 		cmd.opcode = GPCMD_REPORT_KEY;
1852 		cmd.bytes[8] = 8;
1853 		cmd.bytes[9] = 0 | (0 << 6);
1854 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 8,
1855 		    CDRETRIES, 30000, NULL,
1856 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
1857 		if (error)
1858 			return (error);
1859 		a->lsa.agid = buf[7] >> 6;
1860 		return (0);
1861 
1862 	case DVD_LU_SEND_CHALLENGE:
1863 		cmd.opcode = GPCMD_REPORT_KEY;
1864 		cmd.bytes[8] = 16;
1865 		cmd.bytes[9] = 1 | (a->lsc.agid << 6);
1866 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 16,
1867 		    CDRETRIES, 30000, NULL,
1868 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
1869 		if (error)
1870 			return (error);
1871 		dvd_copy_challenge(a->lsc.chal, &buf[4]);
1872 		return (0);
1873 
1874 	case DVD_LU_SEND_KEY1:
1875 		cmd.opcode = GPCMD_REPORT_KEY;
1876 		cmd.bytes[8] = 12;
1877 		cmd.bytes[9] = 2 | (a->lsk.agid << 6);
1878 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 12,
1879 		    CDRETRIES, 30000, NULL,
1880 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
1881 		if (error)
1882 			return (error);
1883 		dvd_copy_key(a->lsk.key, &buf[4]);
1884 		return (0);
1885 
1886 	case DVD_LU_SEND_TITLE_KEY:
1887 		cmd.opcode = GPCMD_REPORT_KEY;
1888 		_lto4b(a->lstk.lba, &cmd.bytes[1]);
1889 		cmd.bytes[8] = 12;
1890 		cmd.bytes[9] = 4 | (a->lstk.agid << 6);
1891 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 12,
1892 		    CDRETRIES, 30000, NULL,
1893 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
1894 		if (error)
1895 			return (error);
1896 		a->lstk.cpm = (buf[4] >> 7) & 1;
1897 		a->lstk.cp_sec = (buf[4] >> 6) & 1;
1898 		a->lstk.cgms = (buf[4] >> 4) & 3;
1899 		dvd_copy_key(a->lstk.title_key, &buf[5]);
1900 		return (0);
1901 
1902 	case DVD_LU_SEND_ASF:
1903 		cmd.opcode = GPCMD_REPORT_KEY;
1904 		cmd.bytes[8] = 8;
1905 		cmd.bytes[9] = 5 | (a->lsasf.agid << 6);
1906 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 8,
1907 		    CDRETRIES, 30000, NULL,
1908 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
1909 		if (error)
1910 			return (error);
1911 		a->lsasf.asf = buf[7] & 1;
1912 		return (0);
1913 
1914 	case DVD_HOST_SEND_CHALLENGE:
1915 		cmd.opcode = GPCMD_SEND_KEY;
1916 		cmd.bytes[8] = 16;
1917 		cmd.bytes[9] = 1 | (a->hsc.agid << 6);
1918 		buf[1] = 14;
1919 		dvd_copy_challenge(&buf[4], a->hsc.chal);
1920 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 16,
1921 		    CDRETRIES, 30000, NULL,
1922 		    XS_CTL_DATA_OUT|XS_CTL_DATA_ONSTACK);
1923 		if (error)
1924 			return (error);
1925 		a->type = DVD_LU_SEND_KEY1;
1926 		return (0);
1927 
1928 	case DVD_HOST_SEND_KEY2:
1929 		cmd.opcode = GPCMD_SEND_KEY;
1930 		cmd.bytes[8] = 12;
1931 		cmd.bytes[9] = 3 | (a->hsk.agid << 6);
1932 		buf[1] = 10;
1933 		dvd_copy_key(&buf[4], a->hsk.key);
1934 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 12,
1935 		    CDRETRIES, 30000, NULL,
1936 		    XS_CTL_DATA_OUT|XS_CTL_DATA_ONSTACK);
1937 		if (error) {
1938 			a->type = DVD_AUTH_FAILURE;
1939 			return (error);
1940 		}
1941 		a->type = DVD_AUTH_ESTABLISHED;
1942 		return (0);
1943 
1944 	case DVD_INVALIDATE_AGID:
1945 		cmd.opcode = GPCMD_REPORT_KEY;
1946 		cmd.bytes[9] = 0x3f | (a->lsa.agid << 6);
1947 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 16,
1948 		    CDRETRIES, 30000, NULL, 0);
1949 		if (error)
1950 			return (error);
1951 		return (0);
1952 
1953 	case DVD_LU_SEND_RPC_STATE:
1954 		cmd.opcode = GPCMD_REPORT_KEY;
1955 		cmd.bytes[8] = 8;
1956 		cmd.bytes[9] = 8 | (0 << 6);
1957 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 8,
1958 		    CDRETRIES, 30000, NULL,
1959 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
1960 		if (error)
1961 			return (error);
1962 		a->lrpcs.type = (buf[4] >> 6) & 3;
1963 		a->lrpcs.vra = (buf[4] >> 3) & 7;
1964 		a->lrpcs.ucca = (buf[4]) & 7;
1965 		a->lrpcs.region_mask = buf[5];
1966 		a->lrpcs.rpc_scheme = buf[6];
1967 		return (0);
1968 
1969 	case DVD_HOST_SEND_RPC_STATE:
1970 		cmd.opcode = GPCMD_SEND_KEY;
1971 		cmd.bytes[8] = 8;
1972 		cmd.bytes[9] = 6 | (0 << 6);
1973 		buf[1] = 6;
1974 		buf[4] = a->hrpcs.pdrc;
1975 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 8,
1976 		    CDRETRIES, 30000, NULL,
1977 		    XS_CTL_DATA_OUT|XS_CTL_DATA_ONSTACK);
1978 		if (error)
1979 			return (error);
1980 		return (0);
1981 
1982 	default:
1983 		return (ENOTTY);
1984 	}
1985 }
1986 
1987 int
1988 dvd_read_physical(cd, s)
1989 	struct cd_softc *cd;
1990 	dvd_struct *s;
1991 {
1992 	struct scsipi_generic cmd;
1993 	u_int8_t buf[4 + 4 * 20], *bufp;
1994 	int error;
1995 	struct dvd_layer *layer;
1996 	int i;
1997 
1998 	memset(cmd.bytes, 0, 15);
1999 	memset(buf, 0, sizeof(buf));
2000 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2001 	cmd.bytes[6] = s->type;
2002 	_lto2b(sizeof(buf), &cmd.bytes[7]);
2003 
2004 	cmd.bytes[5] = s->physical.layer_num;
2005 	error = scsipi_command(cd->sc_periph, &cmd, 12, buf, sizeof(buf),
2006 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2007 	if (error)
2008 		return (error);
2009 	for (i = 0, bufp = &buf[4], layer = &s->physical.layer[0]; i < 4;
2010 	     i++, bufp += 20, layer++) {
2011 		memset(layer, 0, sizeof(*layer));
2012                 layer->book_version = bufp[0] & 0xf;
2013                 layer->book_type = bufp[0] >> 4;
2014                 layer->min_rate = bufp[1] & 0xf;
2015                 layer->disc_size = bufp[1] >> 4;
2016                 layer->layer_type = bufp[2] & 0xf;
2017                 layer->track_path = (bufp[2] >> 4) & 1;
2018                 layer->nlayers = (bufp[2] >> 5) & 3;
2019                 layer->track_density = bufp[3] & 0xf;
2020                 layer->linear_density = bufp[3] >> 4;
2021                 layer->start_sector = _4btol(&bufp[4]);
2022                 layer->end_sector = _4btol(&bufp[8]);
2023                 layer->end_sector_l0 = _4btol(&bufp[12]);
2024                 layer->bca = bufp[16] >> 7;
2025 	}
2026 	return (0);
2027 }
2028 
2029 int
2030 dvd_read_copyright(cd, s)
2031 	struct cd_softc *cd;
2032 	dvd_struct *s;
2033 {
2034 	struct scsipi_generic cmd;
2035 	u_int8_t buf[8];
2036 	int error;
2037 
2038 	memset(cmd.bytes, 0, 15);
2039 	memset(buf, 0, sizeof(buf));
2040 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2041 	cmd.bytes[6] = s->type;
2042 	_lto2b(sizeof(buf), &cmd.bytes[7]);
2043 
2044 	cmd.bytes[5] = s->copyright.layer_num;
2045 	error = scsipi_command(cd->sc_periph, &cmd, 12, buf, sizeof(buf),
2046 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2047 	if (error)
2048 		return (error);
2049 	s->copyright.cpst = buf[4];
2050 	s->copyright.rmi = buf[5];
2051 	return (0);
2052 }
2053 
2054 int
2055 dvd_read_disckey(cd, s)
2056 	struct cd_softc *cd;
2057 	dvd_struct *s;
2058 {
2059 	struct scsipi_generic cmd;
2060 	u_int8_t *buf;
2061 	int error;
2062 
2063 	buf = malloc(4 + 2048, M_TEMP, M_WAITOK|M_ZERO);
2064 	if (buf == NULL)
2065 		return EIO;
2066 	memset(cmd.bytes, 0, 15);
2067 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2068 	cmd.bytes[6] = s->type;
2069 	_lto2b(4 + 2048, &cmd.bytes[7]);
2070 
2071 	cmd.bytes[9] = s->disckey.agid << 6;
2072 	error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 4 + 2048,
2073 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2074 	if (error == 0)
2075 		memcpy(s->disckey.value, &buf[4], 2048);
2076 	free(buf, M_TEMP);
2077 	return error;
2078 }
2079 
2080 int
2081 dvd_read_bca(cd, s)
2082 	struct cd_softc *cd;
2083 	dvd_struct *s;
2084 {
2085 	struct scsipi_generic cmd;
2086 	u_int8_t buf[4 + 188];
2087 	int error;
2088 
2089 	memset(cmd.bytes, 0, 15);
2090 	memset(buf, 0, sizeof(buf));
2091 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2092 	cmd.bytes[6] = s->type;
2093 	_lto2b(sizeof(buf), &cmd.bytes[7]);
2094 
2095 	error = scsipi_command(cd->sc_periph, &cmd, 12, buf, sizeof(buf),
2096 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2097 	if (error)
2098 		return (error);
2099 	s->bca.len = _2btol(&buf[0]);
2100 	if (s->bca.len < 12 || s->bca.len > 188)
2101 		return (EIO);
2102 	memcpy(s->bca.value, &buf[4], s->bca.len);
2103 	return (0);
2104 }
2105 
2106 int
2107 dvd_read_manufact(cd, s)
2108 	struct cd_softc *cd;
2109 	dvd_struct *s;
2110 {
2111 	struct scsipi_generic cmd;
2112 	u_int8_t *buf;
2113 	int error;
2114 
2115 	buf = malloc(4 + 2048, M_TEMP, M_WAITOK|M_ZERO);
2116 	if (buf == NULL)
2117 		return (EIO);
2118 	memset(cmd.bytes, 0, 15);
2119 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2120 	cmd.bytes[6] = s->type;
2121 	_lto2b(4 + 2048, &cmd.bytes[7]);
2122 
2123 	error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 4 + 2048,
2124 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2125 	if (error == 0) {
2126 		s->manufact.len = _2btol(&buf[0]);
2127 		if (s->manufact.len >= 0 && s->manufact.len <= 2048)
2128 			memcpy(s->manufact.value, &buf[4], s->manufact.len);
2129 		else
2130 			error = EIO;
2131 	}
2132 	free(buf, M_TEMP);
2133 	return error;
2134 }
2135 
2136 int
2137 dvd_read_struct(cd, s)
2138 	struct cd_softc *cd;
2139 	dvd_struct *s;
2140 {
2141 
2142 	switch (s->type) {
2143 	case DVD_STRUCT_PHYSICAL:
2144 		return (dvd_read_physical(cd, s));
2145 	case DVD_STRUCT_COPYRIGHT:
2146 		return (dvd_read_copyright(cd, s));
2147 	case DVD_STRUCT_DISCKEY:
2148 		return (dvd_read_disckey(cd, s));
2149 	case DVD_STRUCT_BCA:
2150 		return (dvd_read_bca(cd, s));
2151 	case DVD_STRUCT_MANUFACT:
2152 		return (dvd_read_manufact(cd, s));
2153 	default:
2154 		return (EINVAL);
2155 	}
2156 }
2157