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