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