xref: /netbsd-src/sys/dev/scsipi/cd.c (revision 08c81a9c2dc8c7300e893321eb65c0925d60871c)
1 /*	$NetBSD: cd.c,v 1.167 2002/09/18 01:46:23 chs 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.167 2002/09/18 01:46:23 chs 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, 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 %d\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 	    bounds_check_with_label(bp, lp,
589 	    (cd->flags & (CDF_WLABEL|CDF_LABELLING)) != 0) <= 0)
590 		goto done;
591 
592 	/*
593 	 * Now convert the block number to absolute and put it in
594 	 * terms of the device's logical block size.
595 	 */
596 	blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE);
597 	if (CDPART(bp->b_dev) != RAW_PART)
598 		blkno += lp->d_partitions[CDPART(bp->b_dev)].p_offset;
599 
600 	bp->b_rawblkno = blkno;
601 
602 	/*
603 	 * If the disklabel sector size does not match the device
604 	 * sector size we may need to do some extra work.
605 	 */
606 	if (lp->d_secsize != cd->params.blksize) {
607 
608 		/*
609 		 * If the xfer is not a multiple of the device block size
610 		 * or it is not block aligned, we need to bounce it.
611 		 */
612 		if ((bp->b_bcount % cd->params.blksize) != 0 ||
613 			((blkno * lp->d_secsize) % cd->params.blksize) != 0) {
614 			struct buf *nbp;
615 			void *bounce = NULL;
616 			long count;
617 
618 			if ((bp->b_flags & B_READ) == 0) {
619 
620 				/* XXXX We don't support bouncing writes. */
621 				bp->b_error = EACCES;
622 				goto bad;
623 			}
624 			count = ((blkno * lp->d_secsize) % cd->params.blksize);
625 			/* XXX Store starting offset in bp->b_rawblkno */
626 			bp->b_rawblkno = count;
627 
628 			count += bp->b_bcount;
629 			count = roundup(count, cd->params.blksize);
630 
631 			blkno = ((blkno * lp->d_secsize) / cd->params.blksize);
632 			s = splbio();
633 			nbp = pool_get(&bufpool, PR_NOWAIT);
634 			splx(s);
635 			if (!nbp) {
636 				/* No memory -- fail the iop. */
637 				bp->b_error = ENOMEM;
638 				goto bad;
639 			}
640 			bounce = malloc(count, M_DEVBUF, M_NOWAIT);
641 			if (!bounce) {
642 				/* No memory -- fail the iop. */
643 				s = splbio();
644 				pool_put(&bufpool, nbp);
645 				splx(s);
646 				bp->b_error = ENOMEM;
647 				goto bad;
648 			}
649 
650 			/* Set up the IOP to the bounce buffer. */
651 			nbp->b_error = 0;
652 			nbp->b_proc = bp->b_proc;
653 			nbp->b_vp = NULLVP;
654 
655 			nbp->b_bcount = count;
656 			nbp->b_bufsize = count;
657 			nbp->b_data = bounce;
658 
659 			LIST_INIT(&nbp->b_dep);
660 			nbp->b_rawblkno = blkno;
661 
662 			/* We need to do a read-modify-write operation */
663 			nbp->b_flags = bp->b_flags | B_READ | B_CALL;
664 			nbp->b_iodone = cdbounce;
665 
666 			/* Put ptr to orig buf in b_private and use new buf */
667 			nbp->b_private = bp;
668 			bp = nbp;
669 
670 		} else {
671 			/* Xfer is aligned -- just adjust the start block */
672 			bp->b_rawblkno = (blkno * lp->d_secsize) /
673 				cd->params.blksize;
674 		}
675 	}
676 	s = splbio();
677 
678 	/*
679 	 * Place it in the queue of disk activities for this disk.
680 	 *
681 	 * XXX Only do disksort() if the current operating mode does not
682 	 * XXX include tagged queueing.
683 	 */
684 	BUFQ_PUT(&cd->buf_queue, bp);
685 
686 	/*
687 	 * Tell the device to get going on the transfer if it's
688 	 * not doing anything, otherwise just wait for completion
689 	 */
690 	cdstart(cd->sc_periph);
691 
692 	splx(s);
693 	return;
694 
695 bad:
696 	bp->b_flags |= B_ERROR;
697 done:
698 	/*
699 	 * Correctly set the buf to indicate a completed xfer
700 	 */
701 	bp->b_resid = bp->b_bcount;
702 	biodone(bp);
703 }
704 
705 /*
706  * cdstart looks to see if there is a buf waiting for the device
707  * and that the device is not already busy. If both are true,
708  * It deques the buf and creates a scsi command to perform the
709  * transfer in the buf. The transfer request will call scsipi_done
710  * on completion, which will in turn call this routine again
711  * so that the next queued transfer is performed.
712  * The bufs are queued by the strategy routine (cdstrategy)
713  *
714  * This routine is also called after other non-queued requests
715  * have been made of the scsi driver, to ensure that the queue
716  * continues to be drained.
717  *
718  * must be called at the correct (highish) spl level
719  * cdstart() is called at splbio from cdstrategy and scsipi_done
720  */
721 void
722 cdstart(periph)
723 	struct scsipi_periph *periph;
724 {
725 	struct cd_softc *cd = (void *)periph->periph_dev;
726 	struct buf *bp = 0;
727 	struct scsipi_rw_big cmd_big;
728 #if NCD_SCSIBUS > 0
729 	struct scsi_rw cmd_small;
730 #endif
731 	struct scsipi_generic *cmdp;
732 	int flags, nblks, cmdlen, error;
733 
734 	SC_DEBUG(periph, SCSIPI_DB2, ("cdstart "));
735 	/*
736 	 * Check if the device has room for another command
737 	 */
738 	while (periph->periph_active < periph->periph_openings) {
739 		/*
740 		 * there is excess capacity, but a special waits
741 		 * It'll need the adapter as soon as we clear out of the
742 		 * way and let it run (user level wait).
743 		 */
744 		if (periph->periph_flags & PERIPH_WAITING) {
745 			periph->periph_flags &= ~PERIPH_WAITING;
746 			wakeup((caddr_t)periph);
747 			return;
748 		}
749 
750 		/*
751 		 * See if there is a buf with work for us to do..
752 		 */
753 		if ((bp = BUFQ_GET(&cd->buf_queue)) == NULL)
754 			return;
755 
756 		/*
757 		 * If the device has become invalid, abort all the
758 		 * reads and writes until all files have been closed and
759 		 * re-opened
760 		 */
761 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
762 			bp->b_error = EIO;
763 			bp->b_flags |= B_ERROR;
764 			bp->b_resid = bp->b_bcount;
765 			biodone(bp);
766 			continue;
767 		}
768 
769 		/*
770 		 * We have a buf, now we should make a command.
771 		 */
772 
773 		nblks = howmany(bp->b_bcount, cd->params.blksize);
774 
775 #if NCD_SCSIBUS > 0
776 		/*
777 		 *  Fill out the scsi command.  If the transfer will
778 		 *  fit in a "small" cdb, use it.
779 		 */
780 		if (((bp->b_rawblkno & 0x1fffff) == bp->b_rawblkno) &&
781 		    ((nblks & 0xff) == nblks) &&
782 		    !(periph->periph_quirks & PQUIRK_ONLYBIG) &&
783 		    scsipi_periph_bustype(periph) == SCSIPI_BUSTYPE_SCSI) {
784 			/*
785 			 * We can fit in a small cdb.
786 			 */
787 			memset(&cmd_small, 0, sizeof(cmd_small));
788 			cmd_small.opcode = (bp->b_flags & B_READ) ?
789 			    SCSI_READ_COMMAND : SCSI_WRITE_COMMAND;
790 			_lto3b(bp->b_rawblkno, cmd_small.addr);
791 			cmd_small.length = nblks & 0xff;
792 			cmdlen = sizeof(cmd_small);
793 			cmdp = (struct scsipi_generic *)&cmd_small;
794 		} else
795 #endif
796 		{
797 			/*
798 			 * Need a large cdb.
799 			 */
800 			memset(&cmd_big, 0, sizeof(cmd_big));
801 			cmd_big.opcode = (bp->b_flags & B_READ) ?
802 			    READ_BIG : WRITE_BIG;
803 			_lto4b(bp->b_rawblkno, cmd_big.addr);
804 			_lto2b(nblks, cmd_big.length);
805 			cmdlen = sizeof(cmd_big);
806 			cmdp = (struct scsipi_generic *)&cmd_big;
807 		}
808 
809 		/* Instrumentation. */
810 		disk_busy(&cd->sc_dk);
811 
812 		/*
813 		 * Figure out what flags to use.
814 		 */
815 		flags = XS_CTL_NOSLEEP|XS_CTL_ASYNC|XS_CTL_SIMPLE_TAG;
816 		if (bp->b_flags & B_READ)
817 			flags |= XS_CTL_DATA_IN;
818 		else
819 			flags |= XS_CTL_DATA_OUT;
820 
821 		/*
822 		 * Call the routine that chats with the adapter.
823 		 * Note: we cannot sleep as we may be an interrupt
824 		 */
825 		error = scsipi_command(periph, cmdp, cmdlen,
826 		    (u_char *)bp->b_data, bp->b_bcount,
827 		    CDRETRIES, 30000, bp, flags);
828 		if (error) {
829 			disk_unbusy(&cd->sc_dk, 0);
830 			printf("%s: not queued, error %d\n",
831 			    cd->sc_dev.dv_xname, error);
832 		}
833 	}
834 }
835 
836 void
837 cddone(xs)
838 	struct scsipi_xfer *xs;
839 {
840 	struct cd_softc *cd = (void *)xs->xs_periph->periph_dev;
841 
842 	if (xs->bp != NULL) {
843 		disk_unbusy(&cd->sc_dk, xs->bp->b_bcount - xs->bp->b_resid);
844 #if NRND > 0
845 		rnd_add_uint32(&cd->rnd_source, xs->bp->b_rawblkno);
846 #endif
847 	}
848 }
849 
850 void
851 cdbounce(bp)
852 	struct buf *bp;
853 {
854 	struct buf *obp = (struct buf *)bp->b_private;
855 
856 	if (bp->b_flags & B_ERROR) {
857 		/* EEK propagate the error and free the memory */
858 		goto done;
859 	}
860 	if (obp->b_flags & B_READ) {
861 		/* Copy data to the final destination and free the buf. */
862 		memcpy(obp->b_data, bp->b_data+obp->b_rawblkno,
863 			obp->b_bcount);
864 	} else {
865 		/*
866 		 * XXXX This is a CD-ROM -- READ ONLY -- why do we bother with
867 		 * XXXX any of this write stuff?
868 		 */
869 		if (bp->b_flags & B_READ) {
870 			struct cd_softc *cd = cd_cd.cd_devs[CDUNIT(bp->b_dev)];
871 			struct buf *nbp;
872 			int s;
873 
874 			/* Read part of RMW complete. */
875 			memcpy(bp->b_data+obp->b_rawblkno, obp->b_data,
876 				obp->b_bcount);
877 
878 			s = splbio();
879 
880 			/* We need to alloc a new buf. */
881 			nbp = pool_get(&bufpool, PR_NOWAIT);
882 			if (!nbp) {
883 				splx(s);
884 				/* No buf available. */
885 				bp->b_flags |= B_ERROR;
886 				bp->b_error = ENOMEM;
887 				bp->b_resid = bp->b_bcount;
888 			}
889 
890 			/* Set up the IOP to the bounce buffer. */
891 			nbp->b_error = 0;
892 			nbp->b_proc = bp->b_proc;
893 			nbp->b_vp = NULLVP;
894 
895 			nbp->b_bcount = bp->b_bcount;
896 			nbp->b_bufsize = bp->b_bufsize;
897 			nbp->b_data = bp->b_data;
898 
899 			LIST_INIT(&nbp->b_dep);
900 			nbp->b_rawblkno = bp->b_rawblkno;
901 
902 			/* We need to do a read-modify-write operation */
903 			nbp->b_flags = obp->b_flags | B_CALL;
904 			nbp->b_iodone = cdbounce;
905 
906 			/* Put ptr to orig buf in b_private and use new buf */
907 			nbp->b_private = obp;
908 
909 			/*
910 			 * Place it in the queue of disk activities for this
911 			 * disk.
912 			 *
913 			 * XXX Only do disksort() if the current operating mode
914 			 * XXX does not include tagged queueing.
915 			 */
916 			BUFQ_PUT(&cd->buf_queue, nbp);
917 
918 			/*
919 			 * Tell the device to get going on the transfer if it's
920 			 * not doing anything, otherwise just wait for
921 			 * completion
922 			 */
923 			cdstart(cd->sc_periph);
924 
925 			splx(s);
926 			return;
927 
928 		}
929 	}
930 done:
931 	obp->b_flags |= (bp->b_flags&(B_EINTR|B_ERROR));
932 	obp->b_error = bp->b_error;
933 	obp->b_resid = bp->b_resid;
934 	free(bp->b_data, M_DEVBUF);
935 	biodone(obp);
936 }
937 
938 int cd_interpret_sense(xs)
939 	struct scsipi_xfer *xs;
940 {
941 	struct scsipi_periph *periph = xs->xs_periph;
942 	struct scsipi_sense_data *sense = &xs->sense.scsi_sense;
943 	int retval = EJUSTRETURN;
944 
945 	/*
946 	 * If it isn't a extended or extended/deferred error, let
947 	 * the generic code handle it.
948 	 */
949 	if ((sense->error_code & SSD_ERRCODE) != 0x70 &&
950 	    (sense->error_code & SSD_ERRCODE) != 0x71) {	/* DEFERRED */
951 		return (retval);
952 	}
953 
954 	/*
955 	 * If we got a "Unit not ready" (SKEY_NOT_READY) and "Logical Unit
956 	 * Is In The Process of Becoming Ready" (Sense code 0x04,0x01), then
957 	 * wait a bit for the drive to spin up
958 	 */
959 
960 	if ((sense->flags & SSD_KEY) == SKEY_NOT_READY &&
961 	    sense->add_sense_code == 0x4 &&
962 	    sense->add_sense_code_qual == 0x01)	{
963 		/*
964 		 * Sleep for 5 seconds to wait for the drive to spin up
965 		 */
966 
967 		SC_DEBUG(periph, SCSIPI_DB1, ("Waiting 5 sec for CD "
968 						"spinup\n"));
969 		if (!callout_active(&periph->periph_callout))
970 			scsipi_periph_freeze(periph, 1);
971 		callout_reset(&periph->periph_callout,
972 		    5 * hz, scsipi_periph_timed_thaw, periph);
973 		retval = ERESTART;
974 	}
975 	return (retval);
976 }
977 
978 void
979 cdminphys(bp)
980 	struct buf *bp;
981 {
982 	struct cd_softc *cd = cd_cd.cd_devs[CDUNIT(bp->b_dev)];
983 	long max;
984 
985 	/*
986 	 * If the device is ancient, we want to make sure that
987 	 * the transfer fits into a 6-byte cdb.
988 	 *
989 	 * XXX Note that the SCSI-I spec says that 256-block transfers
990 	 * are allowed in a 6-byte read/write, and are specified
991 	 * by settng the "length" to 0.  However, we're conservative
992 	 * here, allowing only 255-block transfers in case an
993 	 * ancient device gets confused by length == 0.  A length of 0
994 	 * in a 10-byte read/write actually means 0 blocks.
995 	 */
996 	if (cd->flags & CDF_ANCIENT) {
997 		max = cd->sc_dk.dk_label->d_secsize * 0xff;
998 
999 		if (bp->b_bcount > max)
1000 			bp->b_bcount = max;
1001 	}
1002 
1003 	(*cd->sc_periph->periph_channel->chan_adapter->adapt_minphys)(bp);
1004 }
1005 
1006 int
1007 cdread(dev, uio, ioflag)
1008 	dev_t dev;
1009 	struct uio *uio;
1010 	int ioflag;
1011 {
1012 
1013 	return (physio(cdstrategy, NULL, dev, B_READ, cdminphys, uio));
1014 }
1015 
1016 int
1017 cdwrite(dev, uio, ioflag)
1018 	dev_t dev;
1019 	struct uio *uio;
1020 	int ioflag;
1021 {
1022 
1023 	return (physio(cdstrategy, NULL, dev, B_WRITE, cdminphys, uio));
1024 }
1025 
1026 /*
1027  * conversion between minute-seconde-frame and logical block adress
1028  * adresses format
1029  */
1030 void
1031 lba2msf (lba, m, s, f)
1032 	u_long lba;
1033 	u_char *m, *s, *f;
1034 {
1035 	u_long tmp;
1036 
1037 	tmp = lba + CD_BLOCK_OFFSET;	/* offset of first logical frame */
1038 	tmp &= 0xffffff;		/* negative lbas use only 24 bits */
1039 	*m = tmp / (CD_SECS * CD_FRAMES);
1040 	tmp %= (CD_SECS * CD_FRAMES);
1041 	*s = tmp / CD_FRAMES;
1042 	*f = tmp % CD_FRAMES;
1043 }
1044 
1045 u_long
1046 msf2lba (m, s, f)
1047 	u_char m, s, f;
1048 {
1049 
1050 	return ((((m * CD_SECS) + s) * CD_FRAMES + f) - CD_BLOCK_OFFSET);
1051 }
1052 
1053 int
1054 cdreadmsaddr(cd, addr)
1055 	struct cd_softc *cd;
1056 	int *addr;
1057 {
1058 	struct scsipi_periph *periph = cd->sc_periph;
1059 	int error;
1060 	struct cd_toc toc;
1061 	struct cd_toc_entry *cte;
1062 
1063 	error = cd_read_toc(cd, 0, 0, &toc,
1064 	    sizeof(struct ioc_toc_header) + sizeof(struct cd_toc_entry),
1065 	    XS_CTL_DATA_ONSTACK,
1066 	    0x40 /* control word for "get MS info" */);
1067 
1068 	if (error)
1069 		return (error);
1070 
1071 	cte = &toc.entries[0];
1072 	if (periph->periph_quirks & PQUIRK_LITTLETOC) {
1073 		cte->addr.lba = le32toh(cte->addr.lba);
1074 		toc.header.len = le16toh(toc.header.len);
1075 	} else {
1076 		cte->addr.lba = be32toh(cte->addr.lba);
1077 		toc.header.len = be16toh(toc.header.len);
1078 	}
1079 
1080 	*addr = (toc.header.len >= 10 && cte->track > 1) ?
1081 		cte->addr.lba : 0;
1082 	return 0;
1083 }
1084 
1085 /*
1086  * Perform special action on behalf of the user.
1087  * Knows about the internals of this device
1088  */
1089 int
1090 cdioctl(dev, cmd, addr, flag, p)
1091 	dev_t dev;
1092 	u_long cmd;
1093 	caddr_t addr;
1094 	int flag;
1095 	struct proc *p;
1096 {
1097 	struct cd_softc *cd = cd_cd.cd_devs[CDUNIT(dev)];
1098 	struct scsipi_periph *periph = cd->sc_periph;
1099 	int part = CDPART(dev);
1100 	int error;
1101 #ifdef __HAVE_OLD_DISKLABEL
1102 	struct disklabel newlabel;
1103 #endif
1104 
1105 	SC_DEBUG(cd->sc_periph, SCSIPI_DB2, ("cdioctl 0x%lx ", cmd));
1106 
1107 	/*
1108 	 * If the device is not valid, some IOCTLs can still be
1109 	 * handled on the raw partition. Check this here.
1110 	 */
1111 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
1112 		switch (cmd) {
1113 		case DIOCWLABEL:
1114 		case DIOCLOCK:
1115 		case ODIOCEJECT:
1116 		case DIOCEJECT:
1117 		case SCIOCIDENTIFY:
1118 		case OSCIOCIDENTIFY:
1119 		case SCIOCCOMMAND:
1120 		case SCIOCDEBUG:
1121 		case CDIOCGETVOL:
1122 		case CDIOCSETVOL:
1123 		case CDIOCSETMONO:
1124 		case CDIOCSETSTEREO:
1125 		case CDIOCSETMUTE:
1126 		case CDIOCSETLEFT:
1127 		case CDIOCSETRIGHT:
1128 		case CDIOCCLOSE:
1129 		case CDIOCEJECT:
1130 		case CDIOCALLOW:
1131 		case CDIOCPREVENT:
1132 		case CDIOCSETDEBUG:
1133 		case CDIOCCLRDEBUG:
1134 		case CDIOCRESET:
1135 		case SCIOCRESET:
1136 		case CDIOCLOADUNLOAD:
1137 		case DVD_AUTH:
1138 		case DVD_READ_STRUCT:
1139 			if (part == RAW_PART)
1140 				break;
1141 		/* FALLTHROUGH */
1142 		default:
1143 			if ((periph->periph_flags & PERIPH_OPEN) == 0)
1144 				return (ENODEV);
1145 			else
1146 				return (EIO);
1147 		}
1148 	}
1149 
1150 	switch (cmd) {
1151 	case DIOCGDINFO:
1152 		*(struct disklabel *)addr = *(cd->sc_dk.dk_label);
1153 		return (0);
1154 #ifdef __HAVE_OLD_DISKLABEL
1155 	case ODIOCGDINFO:
1156 		newlabel = *(cd->sc_dk.dk_label);
1157 		if (newlabel.d_npartitions > OLDMAXPARTITIONS)
1158 			return ENOTTY;
1159 		memcpy(addr, &newlabel, sizeof (struct olddisklabel));
1160 		return (0);
1161 #endif
1162 
1163 	case DIOCGPART:
1164 		((struct partinfo *)addr)->disklab = cd->sc_dk.dk_label;
1165 		((struct partinfo *)addr)->part =
1166 		    &cd->sc_dk.dk_label->d_partitions[part];
1167 		return (0);
1168 
1169 	case DIOCWDINFO:
1170 	case DIOCSDINFO:
1171 #ifdef __HAVE_OLD_DISKLABEL
1172 	case ODIOCWDINFO:
1173 	case ODIOCSDINFO:
1174 #endif
1175 	{
1176 		struct disklabel *lp;
1177 
1178 #ifdef __HAVE_OLD_DISKLABEL
1179 		if (cmd == ODIOCSDINFO || cmd == ODIOCWDINFO) {
1180 			memset(&newlabel, 0, sizeof newlabel);
1181 			memcpy(&newlabel, addr, sizeof (struct olddisklabel));
1182 			lp = &newlabel;
1183 		} else
1184 #endif
1185 		lp = (struct disklabel *)addr;
1186 
1187 		if ((flag & FWRITE) == 0)
1188 			return (EBADF);
1189 
1190 		if ((error = cdlock(cd)) != 0)
1191 			return (error);
1192 		cd->flags |= CDF_LABELLING;
1193 
1194 		error = setdisklabel(cd->sc_dk.dk_label,
1195 		    lp, /*cd->sc_dk.dk_openmask : */0,
1196 		    cd->sc_dk.dk_cpulabel);
1197 		if (error == 0) {
1198 			/* XXX ? */
1199 		}
1200 
1201 		cd->flags &= ~CDF_LABELLING;
1202 		cdunlock(cd);
1203 		return (error);
1204 	}
1205 
1206 	case DIOCWLABEL:
1207 		return (EBADF);
1208 
1209 	case DIOCGDEFLABEL:
1210 		cdgetdefaultlabel(cd, (struct disklabel *)addr);
1211 		return (0);
1212 
1213 #ifdef __HAVE_OLD_DISKLABEL
1214 	case ODIOCGDEFLABEL:
1215 		cdgetdefaultlabel(cd, &newlabel);
1216 		if (newlabel.d_npartitions > OLDMAXPARTITIONS)
1217 			return ENOTTY;
1218 		memcpy(addr, &newlabel, sizeof (struct olddisklabel));
1219 		return (0);
1220 #endif
1221 
1222 	case CDIOCPLAYTRACKS: {
1223 		struct ioc_play_track *args = (struct ioc_play_track *)addr;
1224 
1225 		if ((error = (*cd->sc_ops->cdo_set_pa_immed)(cd, 0)) != 0)
1226 			return (error);
1227 		return (cd_play_tracks(cd, args->start_track,
1228 		    args->start_index, args->end_track, args->end_index));
1229 	}
1230 	case CDIOCPLAYMSF: {
1231 		struct ioc_play_msf *args = (struct ioc_play_msf *)addr;
1232 
1233 		if ((error = (*cd->sc_ops->cdo_set_pa_immed)(cd, 0)) != 0)
1234 			return (error);
1235 		return (cd_play_msf(cd, args->start_m, args->start_s,
1236 		    args->start_f, args->end_m, args->end_s, args->end_f));
1237 	}
1238 	case CDIOCPLAYBLOCKS: {
1239 		struct ioc_play_blocks *args = (struct ioc_play_blocks *)addr;
1240 
1241 		if ((error = (*cd->sc_ops->cdo_set_pa_immed)(cd, 0)) != 0)
1242 			return (error);
1243 		return (cd_play(cd, args->blk, args->len));
1244 	}
1245 	case CDIOCREADSUBCHANNEL: {
1246 		struct ioc_read_subchannel *args =
1247 		    (struct ioc_read_subchannel *)addr;
1248 		struct cd_sub_channel_info data;
1249 		int len = args->data_len;
1250 
1251 		if (len > sizeof(data) ||
1252 		    len < sizeof(struct cd_sub_channel_header))
1253 			return (EINVAL);
1254 		error = cd_read_subchannel(cd, args->address_format,
1255 		    args->data_format, args->track, &data, len,
1256 		    XS_CTL_DATA_ONSTACK);
1257 		if (error)
1258 			return (error);
1259 		len = min(len, _2btol(data.header.data_len) +
1260 		    sizeof(struct cd_sub_channel_header));
1261 		return (copyout(&data, args->data, len));
1262 	}
1263 	case CDIOREADTOCHEADER: {
1264 		struct ioc_toc_header th;
1265 
1266 		if ((error = cd_read_toc(cd, 0, 0, &th, sizeof(th),
1267 		    XS_CTL_DATA_ONSTACK, 0)) != 0)
1268 			return (error);
1269 		if (cd->sc_periph->periph_quirks & PQUIRK_LITTLETOC)
1270 			th.len = le16toh(th.len);
1271 		else
1272 			th.len = be16toh(th.len);
1273 		memcpy(addr, &th, sizeof(th));
1274 		return (0);
1275 	}
1276 	case CDIOREADTOCENTRYS: {
1277 		struct cd_toc toc;
1278 		struct ioc_read_toc_entry *te =
1279 		    (struct ioc_read_toc_entry *)addr;
1280 		struct ioc_toc_header *th;
1281 		struct cd_toc_entry *cte;
1282 		int len = te->data_len;
1283 		int ntracks;
1284 
1285 		th = &toc.header;
1286 
1287 		if (len > sizeof(toc.entries) ||
1288 		    len < sizeof(struct cd_toc_entry))
1289 			return (EINVAL);
1290 		error = cd_read_toc(cd, te->address_format, te->starting_track,
1291 		    &toc, len + sizeof(struct ioc_toc_header),
1292 		    XS_CTL_DATA_ONSTACK, 0);
1293 		if (error)
1294 			return (error);
1295 		if (te->address_format == CD_LBA_FORMAT)
1296 			for (ntracks =
1297 			    th->ending_track - th->starting_track + 1;
1298 			    ntracks >= 0; ntracks--) {
1299 				cte = &toc.entries[ntracks];
1300 				cte->addr_type = CD_LBA_FORMAT;
1301 				if (periph->periph_quirks & PQUIRK_LITTLETOC)
1302 					cte->addr.lba = le32toh(cte->addr.lba);
1303 				else
1304 					cte->addr.lba = be32toh(cte->addr.lba);
1305 			}
1306 		if (periph->periph_quirks & PQUIRK_LITTLETOC)
1307 			th->len = le16toh(th->len);
1308 		else
1309 			th->len = be16toh(th->len);
1310 		len = min(len, th->len - (sizeof(th->starting_track) +
1311 		    sizeof(th->ending_track)));
1312 		return (copyout(toc.entries, te->data, len));
1313 	}
1314 	case CDIOREADMSADDR: {
1315 		int sessno = *(int*)addr;
1316 
1317 		if (sessno != 0)
1318 			return (EINVAL);
1319 
1320 		return (cdreadmsaddr(cd, (int*)addr));
1321 	}
1322 	case CDIOCSETPATCH: {
1323 		struct ioc_patch *arg = (struct ioc_patch *)addr;
1324 
1325 		return ((*cd->sc_ops->cdo_setchan)(cd, arg->patch[0],
1326 		    arg->patch[1], arg->patch[2], arg->patch[3], 0));
1327 	}
1328 	case CDIOCGETVOL: {
1329 		struct ioc_vol *arg = (struct ioc_vol *)addr;
1330 
1331 		return ((*cd->sc_ops->cdo_getvol)(cd, arg, 0));
1332 	}
1333 	case CDIOCSETVOL: {
1334 		struct ioc_vol *arg = (struct ioc_vol *)addr;
1335 
1336 		return ((*cd->sc_ops->cdo_setvol)(cd, arg, 0));
1337 	}
1338 
1339 	case CDIOCSETMONO:
1340 		return ((*cd->sc_ops->cdo_setchan)(cd, BOTH_CHANNEL,
1341 		    BOTH_CHANNEL, MUTE_CHANNEL, MUTE_CHANNEL, 0));
1342 
1343 	case CDIOCSETSTEREO:
1344 		return ((*cd->sc_ops->cdo_setchan)(cd, LEFT_CHANNEL,
1345 		    RIGHT_CHANNEL, MUTE_CHANNEL, MUTE_CHANNEL, 0));
1346 
1347 	case CDIOCSETMUTE:
1348 		return ((*cd->sc_ops->cdo_setchan)(cd, MUTE_CHANNEL,
1349 		    MUTE_CHANNEL, MUTE_CHANNEL, MUTE_CHANNEL, 0));
1350 
1351 	case CDIOCSETLEFT:
1352 		return ((*cd->sc_ops->cdo_setchan)(cd, LEFT_CHANNEL,
1353 		    LEFT_CHANNEL, MUTE_CHANNEL, MUTE_CHANNEL, 0));
1354 
1355 	case CDIOCSETRIGHT:
1356 		return ((*cd->sc_ops->cdo_setchan)(cd, RIGHT_CHANNEL,
1357 		    RIGHT_CHANNEL, MUTE_CHANNEL, MUTE_CHANNEL, 0));
1358 
1359 	case CDIOCRESUME:
1360 		return (cd_pause(cd, PA_RESUME));
1361 	case CDIOCPAUSE:
1362 		return (cd_pause(cd, PA_PAUSE));
1363 	case CDIOCSTART:
1364 		return (scsipi_start(periph, SSS_START, 0));
1365 	case CDIOCSTOP:
1366 		return (scsipi_start(periph, SSS_STOP, 0));
1367 	case CDIOCCLOSE:
1368 		return (scsipi_start(periph, SSS_START|SSS_LOEJ,
1369 		    XS_CTL_IGNORE_NOT_READY | XS_CTL_IGNORE_MEDIA_CHANGE));
1370 	case DIOCEJECT:
1371 		if (*(int *)addr == 0) {
1372 			/*
1373 			 * Don't force eject: check that we are the only
1374 			 * partition open. If so, unlock it.
1375 			 */
1376 			if ((cd->sc_dk.dk_openmask & ~(1 << part)) == 0 &&
1377 			    cd->sc_dk.dk_bopenmask + cd->sc_dk.dk_copenmask ==
1378 			    cd->sc_dk.dk_openmask) {
1379 				error = scsipi_prevent(periph, PR_ALLOW,
1380 				    XS_CTL_IGNORE_NOT_READY);
1381 				if (error)
1382 					return (error);
1383 			} else {
1384 				return (EBUSY);
1385 			}
1386 		}
1387 		/* FALLTHROUGH */
1388 	case CDIOCEJECT: /* FALLTHROUGH */
1389 	case ODIOCEJECT:
1390 		return (scsipi_start(periph, SSS_STOP|SSS_LOEJ, 0));
1391 	case CDIOCALLOW:
1392 		return (scsipi_prevent(periph, PR_ALLOW, 0));
1393 	case CDIOCPREVENT:
1394 		return (scsipi_prevent(periph, PR_PREVENT, 0));
1395 	case DIOCLOCK:
1396 		return (scsipi_prevent(periph,
1397 		    (*(int *)addr) ? PR_PREVENT : PR_ALLOW, 0));
1398 	case CDIOCSETDEBUG:
1399 		cd->sc_periph->periph_dbflags |= (SCSIPI_DB1 | SCSIPI_DB2);
1400 		return (0);
1401 	case CDIOCCLRDEBUG:
1402 		cd->sc_periph->periph_dbflags &= ~(SCSIPI_DB1 | SCSIPI_DB2);
1403 		return (0);
1404 	case CDIOCRESET:
1405 	case SCIOCRESET:
1406 		return (cd_reset(cd));
1407 	case CDIOCLOADUNLOAD: {
1408 		struct ioc_load_unload *args = (struct ioc_load_unload *)addr;
1409 
1410 		return ((*cd->sc_ops->cdo_load_unload)(cd, args->options,
1411 			args->slot));
1412 	case DVD_AUTH:
1413 		return (dvd_auth(cd, (dvd_authinfo *)addr));
1414 	case DVD_READ_STRUCT:
1415 		return (dvd_read_struct(cd, (dvd_struct *)addr));
1416 	}
1417 
1418 	default:
1419 		if (part != RAW_PART)
1420 			return (ENOTTY);
1421 		return (scsipi_do_ioctl(periph, dev, cmd, addr, flag, p));
1422 	}
1423 
1424 #ifdef DIAGNOSTIC
1425 	panic("cdioctl: impossible");
1426 #endif
1427 }
1428 
1429 void
1430 cdgetdefaultlabel(cd, lp)
1431 	struct cd_softc *cd;
1432 	struct disklabel *lp;
1433 {
1434 	int lastsession;
1435 
1436 	memset(lp, 0, sizeof(struct disklabel));
1437 
1438 	lp->d_secsize = cd->params.blksize;
1439 	lp->d_ntracks = 1;
1440 	lp->d_nsectors = 100;
1441 	lp->d_ncylinders = (cd->params.disksize / 100) + 1;
1442 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
1443 
1444 	switch (scsipi_periph_bustype(cd->sc_periph)) {
1445 #if NCD_SCSIBUS > 0
1446 	case SCSIPI_BUSTYPE_SCSI:
1447 		lp->d_type = DTYPE_SCSI;
1448 		break;
1449 #endif
1450 #if NCD_ATAPIBUS > 0
1451 	case SCSIPI_BUSTYPE_ATAPI:
1452 		lp->d_type = DTYPE_ATAPI;
1453 		break;
1454 #endif
1455 	}
1456 	strncpy(lp->d_typename, cd->name, 16);
1457 	strncpy(lp->d_packname, "fictitious", 16);
1458 	lp->d_secperunit = cd->params.disksize;
1459 	lp->d_rpm = 300;
1460 	lp->d_interleave = 1;
1461 	lp->d_flags = D_REMOVABLE;
1462 
1463 	if (cdreadmsaddr(cd, &lastsession) != 0)
1464 		lastsession = 0;
1465 
1466 	lp->d_partitions[0].p_offset = 0;
1467 #ifdef notyet /* have to fix bounds_check_with_label() first */
1468 	lp->d_partitions[0].p_size = lp->d_secperunit;
1469 #else
1470 	lp->d_partitions[0].p_size =
1471 	    lp->d_secperunit * (lp->d_secsize / DEV_BSIZE);
1472 #endif
1473 	lp->d_partitions[0].p_cdsession = lastsession;
1474 	lp->d_partitions[0].p_fstype = FS_ISO9660;
1475 	lp->d_partitions[RAW_PART].p_offset = 0;
1476 #ifdef notyet
1477 	lp->d_partitions[RAW_PART].p_size = lp->d_secperunit;
1478 #else
1479 	lp->d_partitions[RAW_PART].p_size =
1480 	    lp->d_secperunit * (lp->d_secsize / DEV_BSIZE);
1481 #endif
1482 	lp->d_partitions[RAW_PART].p_fstype = FS_ISO9660;
1483 	lp->d_npartitions = RAW_PART + 1;
1484 
1485 	lp->d_magic = DISKMAGIC;
1486 	lp->d_magic2 = DISKMAGIC;
1487 	lp->d_checksum = dkcksum(lp);
1488 }
1489 
1490 /*
1491  * Load the label information on the named device
1492  * Actually fabricate a disklabel
1493  *
1494  * EVENTUALLY take information about different
1495  * data tracks from the TOC and put it in the disklabel
1496  */
1497 void
1498 cdgetdisklabel(cd)
1499 	struct cd_softc *cd;
1500 {
1501 	struct disklabel *lp = cd->sc_dk.dk_label;
1502 	char *errstring;
1503 
1504 	memset(cd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
1505 
1506 	cdgetdefaultlabel(cd, lp);
1507 
1508 	/*
1509 	 * Call the generic disklabel extraction routine
1510 	 */
1511 	errstring = readdisklabel(MAKECDDEV(0, cd->sc_dev.dv_unit, RAW_PART),
1512 	    cdstrategy, lp, cd->sc_dk.dk_cpulabel);
1513 	if (errstring) {
1514 		printf("%s: %s\n", cd->sc_dev.dv_xname, errstring);
1515 		goto error;
1516 	}
1517 	return;
1518 
1519 error:
1520 	/* Reset to default label -- should print a warning */
1521 	memset(cd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
1522 
1523 	cdgetdefaultlabel(cd, lp);
1524 }
1525 
1526 /*
1527  * Find out from the device what it's capacity is
1528  */
1529 u_long
1530 cd_size(cd, flags)
1531 	struct cd_softc *cd;
1532 	int flags;
1533 {
1534 	struct scsipi_read_cd_cap_data rdcap;
1535 	struct scsipi_read_cd_capacity scsipi_cmd;
1536 	int blksize;
1537 	u_long size;
1538 
1539 	if (cd->sc_periph->periph_quirks & PQUIRK_NOCAPACITY) {
1540 		/*
1541 		 * the drive doesn't support the READ_CD_CAPACITY command
1542 		 * use a fake size
1543 		 */
1544 		cd->params.blksize = 2048;
1545 		cd->params.disksize = 400000;
1546 		return (400000);
1547 	}
1548 
1549 	/*
1550 	 * make up a scsi command and ask the scsi driver to do
1551 	 * it for you.
1552 	 */
1553 	memset(&scsipi_cmd, 0, sizeof(scsipi_cmd));
1554 	scsipi_cmd.opcode = READ_CD_CAPACITY;
1555 
1556 	/*
1557 	 * If the command works, interpret the result as a 4 byte
1558 	 * number of blocks and a blocksize
1559 	 */
1560 	if (scsipi_command(cd->sc_periph,
1561 	    (struct scsipi_generic *)&scsipi_cmd, sizeof(scsipi_cmd),
1562 	    (u_char *)&rdcap, sizeof(rdcap), CDRETRIES, 30000, NULL,
1563 	    flags | XS_CTL_DATA_IN | XS_CTL_DATA_IN) != 0)
1564 		return (0);
1565 
1566 	blksize = _4btol(rdcap.length);
1567 	if ((blksize < 512) || ((blksize & 511) != 0))
1568 		blksize = 2048;	/* some drives lie ! */
1569 	cd->params.blksize = blksize;
1570 
1571 	size = _4btol(rdcap.addr) + 1;
1572 	if (size < 100)
1573 		size = 400000;	/* ditto */
1574 	cd->params.disksize = size;
1575 
1576 	SC_DEBUG(cd->sc_periph, SCSIPI_DB2,
1577 	    ("cd_size: %d %ld\n", blksize, size));
1578 	return (size);
1579 }
1580 
1581 /*
1582  * Get scsi driver to send a "start playing" command
1583  */
1584 int
1585 cd_play(cd, blkno, nblks)
1586 	struct cd_softc *cd;
1587 	int blkno, nblks;
1588 {
1589 	struct scsipi_play scsipi_cmd;
1590 
1591 	memset(&scsipi_cmd, 0, sizeof(scsipi_cmd));
1592 	scsipi_cmd.opcode = PLAY;
1593 	_lto4b(blkno, scsipi_cmd.blk_addr);
1594 	_lto2b(nblks, scsipi_cmd.xfer_len);
1595 	return (scsipi_command(cd->sc_periph,
1596 	    (struct scsipi_generic *)&scsipi_cmd, sizeof(scsipi_cmd),
1597 	    0, 0, CDRETRIES, 30000, NULL, 0));
1598 }
1599 
1600 /*
1601  * Get scsi driver to send a "start playing" command
1602  */
1603 int
1604 cd_play_tracks(cd, strack, sindex, etrack, eindex)
1605 	struct cd_softc *cd;
1606 	int strack, sindex, etrack, eindex;
1607 {
1608 	struct cd_toc toc;
1609 	int error;
1610 
1611 	if (!etrack)
1612 		return (EIO);
1613 	if (strack > etrack)
1614 		return (EINVAL);
1615 
1616 	if ((error = cd_load_toc(cd, &toc, XS_CTL_DATA_ONSTACK)) != 0)
1617 		return (error);
1618 
1619 	if (++etrack > (toc.header.ending_track+1))
1620 		etrack = toc.header.ending_track+1;
1621 
1622 	strack -= toc.header.starting_track;
1623 	etrack -= toc.header.starting_track;
1624 	if (strack < 0)
1625 		return (EINVAL);
1626 
1627 	return (cd_play_msf(cd, toc.entries[strack].addr.msf.minute,
1628 	    toc.entries[strack].addr.msf.second,
1629 	    toc.entries[strack].addr.msf.frame,
1630 	    toc.entries[etrack].addr.msf.minute,
1631 	    toc.entries[etrack].addr.msf.second,
1632 	    toc.entries[etrack].addr.msf.frame));
1633 }
1634 
1635 /*
1636  * Get scsi driver to send a "play msf" command
1637  */
1638 int
1639 cd_play_msf(cd, startm, starts, startf, endm, ends, endf)
1640 	struct cd_softc *cd;
1641 	int startm, starts, startf, endm, ends, endf;
1642 {
1643 	struct scsipi_play_msf scsipi_cmd;
1644 
1645 	memset(&scsipi_cmd, 0, sizeof(scsipi_cmd));
1646 	scsipi_cmd.opcode = PLAY_MSF;
1647 	scsipi_cmd.start_m = startm;
1648 	scsipi_cmd.start_s = starts;
1649 	scsipi_cmd.start_f = startf;
1650 	scsipi_cmd.end_m = endm;
1651 	scsipi_cmd.end_s = ends;
1652 	scsipi_cmd.end_f = endf;
1653 	return (scsipi_command(cd->sc_periph,
1654 	    (struct scsipi_generic *)&scsipi_cmd, sizeof(scsipi_cmd),
1655 	    0, 0, CDRETRIES, 30000, NULL, 0));
1656 }
1657 
1658 /*
1659  * Get scsi driver to send a "start up" command
1660  */
1661 int
1662 cd_pause(cd, go)
1663 	struct cd_softc *cd;
1664 	int go;
1665 {
1666 	struct scsipi_pause scsipi_cmd;
1667 
1668 	memset(&scsipi_cmd, 0, sizeof(scsipi_cmd));
1669 	scsipi_cmd.opcode = PAUSE;
1670 	scsipi_cmd.resume = go & 0xff;
1671 	return (scsipi_command(cd->sc_periph,
1672 	    (struct scsipi_generic *)&scsipi_cmd, sizeof(scsipi_cmd),
1673 	    0, 0, CDRETRIES, 30000, NULL, 0));
1674 }
1675 
1676 /*
1677  * Get scsi driver to send a "RESET" command
1678  */
1679 int
1680 cd_reset(cd)
1681 	struct cd_softc *cd;
1682 {
1683 
1684 	return (scsipi_command(cd->sc_periph, 0, 0, 0, 0,
1685 	    CDRETRIES, 30000, NULL, XS_CTL_RESET));
1686 }
1687 
1688 /*
1689  * Read subchannel
1690  */
1691 int
1692 cd_read_subchannel(cd, mode, format, track, data, len, flags)
1693 	struct cd_softc *cd;
1694 	int mode, format, track, len;
1695 	struct cd_sub_channel_info *data;
1696 	int flags;
1697 {
1698 	struct scsipi_read_subchannel scsipi_cmd;
1699 
1700 	memset(&scsipi_cmd, 0, sizeof(scsipi_cmd));
1701 	scsipi_cmd.opcode = READ_SUBCHANNEL;
1702 	if (mode == CD_MSF_FORMAT)
1703 		scsipi_cmd.byte2 |= CD_MSF;
1704 	scsipi_cmd.byte3 = SRS_SUBQ;
1705 	scsipi_cmd.subchan_format = format;
1706 	scsipi_cmd.track = track;
1707 	_lto2b(len, scsipi_cmd.data_len);
1708 	return (scsipi_command(cd->sc_periph,
1709 	    (struct scsipi_generic *)&scsipi_cmd,
1710 	    sizeof(struct scsipi_read_subchannel), (u_char *)data, len,
1711 	    CDRETRIES, 30000, NULL, flags | XS_CTL_DATA_IN | XS_CTL_SILENT));
1712 }
1713 
1714 /*
1715  * Read table of contents
1716  */
1717 int
1718 cd_read_toc(cd, mode, start, data, len, flags, control)
1719 	struct cd_softc *cd;
1720 	int mode, start, len, control;
1721 	void *data;
1722 	int flags;
1723 {
1724 	struct scsipi_read_toc scsipi_cmd;
1725 	int ntoc;
1726 
1727 	memset(&scsipi_cmd, 0, sizeof(scsipi_cmd));
1728 #if 0
1729 	if (len != sizeof(struct ioc_toc_header))
1730 		ntoc = ((len) - sizeof(struct ioc_toc_header)) /
1731 		    sizeof(struct cd_toc_entry);
1732 	else
1733 #endif
1734 	ntoc = len;
1735 	scsipi_cmd.opcode = READ_TOC;
1736 	if (mode == CD_MSF_FORMAT)
1737 		scsipi_cmd.byte2 |= CD_MSF;
1738 	scsipi_cmd.from_track = start;
1739 	_lto2b(ntoc, scsipi_cmd.data_len);
1740 	scsipi_cmd.control = control;
1741 	return (scsipi_command(cd->sc_periph,
1742 	    (struct scsipi_generic *)&scsipi_cmd,
1743 	    sizeof(struct scsipi_read_toc), (u_char *)data, len, CDRETRIES,
1744 	    30000, NULL, flags | XS_CTL_DATA_IN));
1745 }
1746 
1747 int
1748 cd_load_toc(cd, toc, flags)
1749 	struct cd_softc *cd;
1750 	struct cd_toc *toc;
1751 	int flags;
1752 {
1753 	int ntracks, len, error;
1754 
1755 	if ((error = cd_read_toc(cd, 0, 0, toc, sizeof(toc->header),
1756 	    flags, 0)) != 0)
1757 		return (error);
1758 
1759 	ntracks = toc->header.ending_track - toc->header.starting_track + 1;
1760 	len = (ntracks + 1) * sizeof(struct cd_toc_entry) +
1761 	    sizeof(toc->header);
1762 	if ((error = cd_read_toc(cd, CD_MSF_FORMAT, 0, toc, len,
1763 	    flags, 0)) != 0)
1764 		return (error);
1765 	return (0);
1766 }
1767 
1768 /*
1769  * Get the scsi driver to send a full inquiry to the device and use the
1770  * results to fill out the disk parameter structure.
1771  */
1772 int
1773 cd_get_parms(cd, flags)
1774 	struct cd_softc *cd;
1775 	int flags;
1776 {
1777 
1778 	/*
1779 	 * give a number of sectors so that sec * trks * cyls
1780 	 * is <= disk_size
1781 	 */
1782 	if (cd_size(cd, flags) == 0)
1783 		return (ENXIO);
1784 	return (0);
1785 }
1786 
1787 int
1788 cdsize(dev)
1789 	dev_t dev;
1790 {
1791 
1792 	/* CD-ROMs are read-only. */
1793 	return (-1);
1794 }
1795 
1796 int
1797 cddump(dev, blkno, va, size)
1798 	dev_t dev;
1799 	daddr_t blkno;
1800 	caddr_t va;
1801 	size_t size;
1802 {
1803 
1804 	/* Not implemented. */
1805 	return (ENXIO);
1806 }
1807 
1808 #define	dvd_copy_key(dst, src)		memcpy((dst), (src), sizeof(dvd_key))
1809 #define	dvd_copy_challenge(dst, src)	memcpy((dst), (src), sizeof(dvd_challenge))
1810 
1811 int
1812 dvd_auth(cd, a)
1813 	struct cd_softc *cd;
1814 	dvd_authinfo *a;
1815 {
1816 	struct scsipi_generic cmd;
1817 	u_int8_t buf[20];
1818 	int error;
1819 
1820 	memset(cmd.bytes, 0, 15);
1821 	memset(buf, 0, sizeof(buf));
1822 
1823 	switch (a->type) {
1824 	case DVD_LU_SEND_AGID:
1825 		cmd.opcode = GPCMD_REPORT_KEY;
1826 		cmd.bytes[8] = 8;
1827 		cmd.bytes[9] = 0 | (0 << 6);
1828 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 8,
1829 		    CDRETRIES, 30000, NULL,
1830 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
1831 		if (error)
1832 			return (error);
1833 		a->lsa.agid = buf[7] >> 6;
1834 		return (0);
1835 
1836 	case DVD_LU_SEND_CHALLENGE:
1837 		cmd.opcode = GPCMD_REPORT_KEY;
1838 		cmd.bytes[8] = 16;
1839 		cmd.bytes[9] = 1 | (a->lsc.agid << 6);
1840 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 16,
1841 		    CDRETRIES, 30000, NULL,
1842 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
1843 		if (error)
1844 			return (error);
1845 		dvd_copy_challenge(a->lsc.chal, &buf[4]);
1846 		return (0);
1847 
1848 	case DVD_LU_SEND_KEY1:
1849 		cmd.opcode = GPCMD_REPORT_KEY;
1850 		cmd.bytes[8] = 12;
1851 		cmd.bytes[9] = 2 | (a->lsk.agid << 6);
1852 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 12,
1853 		    CDRETRIES, 30000, NULL,
1854 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
1855 		if (error)
1856 			return (error);
1857 		dvd_copy_key(a->lsk.key, &buf[4]);
1858 		return (0);
1859 
1860 	case DVD_LU_SEND_TITLE_KEY:
1861 		cmd.opcode = GPCMD_REPORT_KEY;
1862 		_lto4b(a->lstk.lba, &cmd.bytes[1]);
1863 		cmd.bytes[8] = 12;
1864 		cmd.bytes[9] = 4 | (a->lstk.agid << 6);
1865 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 12,
1866 		    CDRETRIES, 30000, NULL,
1867 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
1868 		if (error)
1869 			return (error);
1870 		a->lstk.cpm = (buf[4] >> 7) & 1;
1871 		a->lstk.cp_sec = (buf[4] >> 6) & 1;
1872 		a->lstk.cgms = (buf[4] >> 4) & 3;
1873 		dvd_copy_key(a->lstk.title_key, &buf[5]);
1874 		return (0);
1875 
1876 	case DVD_LU_SEND_ASF:
1877 		cmd.opcode = GPCMD_REPORT_KEY;
1878 		cmd.bytes[8] = 8;
1879 		cmd.bytes[9] = 5 | (a->lsasf.agid << 6);
1880 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 8,
1881 		    CDRETRIES, 30000, NULL,
1882 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
1883 		if (error)
1884 			return (error);
1885 		a->lsasf.asf = buf[7] & 1;
1886 		return (0);
1887 
1888 	case DVD_HOST_SEND_CHALLENGE:
1889 		cmd.opcode = GPCMD_SEND_KEY;
1890 		cmd.bytes[8] = 16;
1891 		cmd.bytes[9] = 1 | (a->hsc.agid << 6);
1892 		buf[1] = 14;
1893 		dvd_copy_challenge(&buf[4], a->hsc.chal);
1894 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 16,
1895 		    CDRETRIES, 30000, NULL,
1896 		    XS_CTL_DATA_OUT|XS_CTL_DATA_ONSTACK);
1897 		if (error)
1898 			return (error);
1899 		a->type = DVD_LU_SEND_KEY1;
1900 		return (0);
1901 
1902 	case DVD_HOST_SEND_KEY2:
1903 		cmd.opcode = GPCMD_SEND_KEY;
1904 		cmd.bytes[8] = 12;
1905 		cmd.bytes[9] = 3 | (a->hsk.agid << 6);
1906 		buf[1] = 10;
1907 		dvd_copy_key(&buf[4], a->hsk.key);
1908 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 12,
1909 		    CDRETRIES, 30000, NULL,
1910 		    XS_CTL_DATA_OUT|XS_CTL_DATA_ONSTACK);
1911 		if (error) {
1912 			a->type = DVD_AUTH_FAILURE;
1913 			return (error);
1914 		}
1915 		a->type = DVD_AUTH_ESTABLISHED;
1916 		return (0);
1917 
1918 	case DVD_INVALIDATE_AGID:
1919 		cmd.opcode = GPCMD_REPORT_KEY;
1920 		cmd.bytes[9] = 0x3f | (a->lsa.agid << 6);
1921 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 16,
1922 		    CDRETRIES, 30000, NULL, 0);
1923 		if (error)
1924 			return (error);
1925 		return (0);
1926 
1927 	case DVD_LU_SEND_RPC_STATE:
1928 		cmd.opcode = GPCMD_REPORT_KEY;
1929 		cmd.bytes[8] = 8;
1930 		cmd.bytes[9] = 8 | (0 << 6);
1931 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 8,
1932 		    CDRETRIES, 30000, NULL,
1933 		    XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
1934 		if (error)
1935 			return (error);
1936 		a->lrpcs.type = (buf[8] >> 6) & 3;
1937 		a->lrpcs.vra = (buf[8] >> 3) & 7;
1938 		a->lrpcs.ucca = (buf[8]) & 7;
1939 		a->lrpcs.region_mask = buf[9];
1940 		a->lrpcs.rpc_scheme = buf[10];
1941 		return (0);
1942 
1943 	case DVD_HOST_SEND_RPC_STATE:
1944 		cmd.opcode = GPCMD_SEND_KEY;
1945 		cmd.bytes[8] = 8;
1946 		cmd.bytes[9] = 6 | (0 << 6);
1947 		buf[1] = 6;
1948 		buf[4] = a->hrpcs.pdrc;
1949 		error = scsipi_command(cd->sc_periph, &cmd, 12, buf, 8,
1950 		    CDRETRIES, 30000, NULL,
1951 		    XS_CTL_DATA_OUT|XS_CTL_DATA_ONSTACK);
1952 		if (error)
1953 			return (error);
1954 		return (0);
1955 
1956 	default:
1957 		return (ENOTTY);
1958 	}
1959 }
1960 
1961 int
1962 dvd_read_physical(cd, s)
1963 	struct cd_softc *cd;
1964 	dvd_struct *s;
1965 {
1966 	struct scsipi_generic cmd;
1967 	u_int8_t buf[4 + 4 * 20], *bufp;
1968 	int error;
1969 	struct dvd_layer *layer;
1970 	int i;
1971 
1972 	memset(cmd.bytes, 0, 15);
1973 	memset(buf, 0, sizeof(buf));
1974 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
1975 	cmd.bytes[6] = s->type;
1976 	_lto2b(sizeof(buf), &cmd.bytes[7]);
1977 
1978 	cmd.bytes[5] = s->physical.layer_num;
1979 	error = scsipi_command(cd->sc_periph, &cmd, 12, buf, sizeof(buf),
1980 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
1981 	if (error)
1982 		return (error);
1983 	for (i = 0, bufp = &buf[4], layer = &s->physical.layer[0]; i < 4;
1984 	     i++, bufp += 20, layer++) {
1985 		memset(layer, 0, sizeof(*layer));
1986                 layer->book_version = bufp[0] & 0xf;
1987                 layer->book_type = bufp[0] >> 4;
1988                 layer->min_rate = bufp[1] & 0xf;
1989                 layer->disc_size = bufp[1] >> 4;
1990                 layer->layer_type = bufp[2] & 0xf;
1991                 layer->track_path = (bufp[2] >> 4) & 1;
1992                 layer->nlayers = (bufp[2] >> 5) & 3;
1993                 layer->track_density = bufp[3] & 0xf;
1994                 layer->linear_density = bufp[3] >> 4;
1995                 layer->start_sector = _4btol(&bufp[4]);
1996                 layer->end_sector = _4btol(&bufp[8]);
1997                 layer->end_sector_l0 = _4btol(&bufp[12]);
1998                 layer->bca = bufp[16] >> 7;
1999 	}
2000 	return (0);
2001 }
2002 
2003 int
2004 dvd_read_copyright(cd, s)
2005 	struct cd_softc *cd;
2006 	dvd_struct *s;
2007 {
2008 	struct scsipi_generic cmd;
2009 	u_int8_t buf[8];
2010 	int error;
2011 
2012 	memset(cmd.bytes, 0, 15);
2013 	memset(buf, 0, sizeof(buf));
2014 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2015 	cmd.bytes[6] = s->type;
2016 	_lto2b(sizeof(buf), &cmd.bytes[7]);
2017 
2018 	cmd.bytes[5] = s->copyright.layer_num;
2019 	error = scsipi_command(cd->sc_periph, &cmd, 12, buf, sizeof(buf),
2020 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2021 	if (error)
2022 		return (error);
2023 	s->copyright.cpst = buf[4];
2024 	s->copyright.rmi = buf[5];
2025 	return (0);
2026 }
2027 
2028 int
2029 dvd_read_disckey(cd, s)
2030 	struct cd_softc *cd;
2031 	dvd_struct *s;
2032 {
2033 	struct scsipi_generic cmd;
2034 	u_int8_t buf[4 + 2048];
2035 	int error;
2036 
2037 	memset(cmd.bytes, 0, 15);
2038 	memset(buf, 0, sizeof(buf));
2039 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2040 	cmd.bytes[6] = s->type;
2041 	_lto2b(sizeof(buf), &cmd.bytes[7]);
2042 
2043 	cmd.bytes[9] = s->disckey.agid << 6;
2044 	error = scsipi_command(cd->sc_periph, &cmd, 12, buf, sizeof(buf),
2045 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2046 	if (error)
2047 		return (error);
2048 	memcpy(s->disckey.value, &buf[4], 2048);
2049 	return (0);
2050 }
2051 
2052 int
2053 dvd_read_bca(cd, s)
2054 	struct cd_softc *cd;
2055 	dvd_struct *s;
2056 {
2057 	struct scsipi_generic cmd;
2058 	u_int8_t buf[4 + 188];
2059 	int error;
2060 
2061 	memset(cmd.bytes, 0, 15);
2062 	memset(buf, 0, sizeof(buf));
2063 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2064 	cmd.bytes[6] = s->type;
2065 	_lto2b(sizeof(buf), &cmd.bytes[7]);
2066 
2067 	error = scsipi_command(cd->sc_periph, &cmd, 12, buf, sizeof(buf),
2068 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2069 	if (error)
2070 		return (error);
2071 	s->bca.len = _2btol(&buf[0]);
2072 	if (s->bca.len < 12 || s->bca.len > 188)
2073 		return (EIO);
2074 	memcpy(s->bca.value, &buf[4], s->bca.len);
2075 	return (0);
2076 }
2077 
2078 int
2079 dvd_read_manufact(cd, s)
2080 	struct cd_softc *cd;
2081 	dvd_struct *s;
2082 {
2083 	struct scsipi_generic cmd;
2084 	u_int8_t buf[4 + 2048];
2085 	int error;
2086 
2087 	memset(cmd.bytes, 0, 15);
2088 	memset(buf, 0, sizeof(buf));
2089 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2090 	cmd.bytes[6] = s->type;
2091 	_lto2b(sizeof(buf), &cmd.bytes[7]);
2092 
2093 	error = scsipi_command(cd->sc_periph, &cmd, 12, buf, sizeof(buf),
2094 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN|XS_CTL_DATA_ONSTACK);
2095 	if (error)
2096 		return (error);
2097 	s->manufact.len = _2btol(&buf[0]);
2098 	if (s->manufact.len < 0 || s->manufact.len > 2048)
2099 		return (EIO);
2100 	memcpy(s->manufact.value, &buf[4], s->manufact.len);
2101 	return (0);
2102 }
2103 
2104 int
2105 dvd_read_struct(cd, s)
2106 	struct cd_softc *cd;
2107 	dvd_struct *s;
2108 {
2109 
2110 	switch (s->type) {
2111 	case DVD_STRUCT_PHYSICAL:
2112 		return (dvd_read_physical(cd, s));
2113 	case DVD_STRUCT_COPYRIGHT:
2114 		return (dvd_read_copyright(cd, s));
2115 	case DVD_STRUCT_DISCKEY:
2116 		return (dvd_read_disckey(cd, s));
2117 	case DVD_STRUCT_BCA:
2118 		return (dvd_read_bca(cd, s));
2119 	case DVD_STRUCT_MANUFACT:
2120 		return (dvd_read_manufact(cd, s));
2121 	default:
2122 		return (EINVAL);
2123 	}
2124 }
2125