xref: /freebsd/sys/cam/scsi/scsi_cd.c (revision 5521ff5a4d1929056e7ffc982fac3341ca54df7c)
1 /*
2  * Copyright (c) 1997 Justin T. Gibbs.
3  * Copyright (c) 1997, 1998, 1999, 2000, 2001 Kenneth D. Merry.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions, and the following disclaimer,
11  *    without modification, immediately at the beginning of the file.
12  * 2. The name of the author may not be used to endorse or promote products
13  *    derived from this software without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
19  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $FreeBSD$
28  */
29 /*
30  * Portions of this driver taken from the original FreeBSD cd driver.
31  * Written by Julian Elischer (julian@tfs.com)
32  * for TRW Financial Systems for use under the MACH(2.5) operating system.
33  *
34  * TRW Financial Systems, in accordance with their agreement with Carnegie
35  * Mellon University, makes this software available to CMU to distribute
36  * or use in any manner that they see fit as long as this message is kept with
37  * the software. For this reason TFS also grants any other persons or
38  * organisations permission to use or modify this software.
39  *
40  * TFS supplies this software to be publicly redistributed
41  * on the understanding that TFS is not responsible for the correct
42  * functioning of this software in any circumstances.
43  *
44  * Ported to run under 386BSD by Julian Elischer (julian@tfs.com) Sept 1992
45  *
46  *      from: cd.c,v 1.83 1997/05/04 15:24:22 joerg Exp $
47  */
48 
49 #include "opt_cd.h"
50 
51 #include <sys/param.h>
52 #include <sys/systm.h>
53 #include <sys/kernel.h>
54 #include <sys/bio.h>
55 #include <sys/conf.h>
56 #include <sys/disk.h>
57 #include <sys/malloc.h>
58 #include <sys/cdio.h>
59 #include <sys/dvdio.h>
60 #include <sys/devicestat.h>
61 #include <sys/sysctl.h>
62 
63 #include <cam/cam.h>
64 #include <cam/cam_ccb.h>
65 #include <cam/cam_extend.h>
66 #include <cam/cam_periph.h>
67 #include <cam/cam_xpt_periph.h>
68 #include <cam/cam_queue.h>
69 
70 #include <cam/scsi/scsi_message.h>
71 #include <cam/scsi/scsi_da.h>
72 #include <cam/scsi/scsi_cd.h>
73 
74 #define LEADOUT         0xaa            /* leadout toc entry */
75 
76 struct cd_params {
77 	u_int32_t blksize;
78 	u_long    disksize;
79 };
80 
81 typedef enum {
82 	CD_Q_NONE	= 0x00,
83 	CD_Q_NO_TOUCH	= 0x01,
84 	CD_Q_BCD_TRACKS	= 0x02,
85 	CD_Q_NO_CHANGER	= 0x04,
86 	CD_Q_CHANGER	= 0x08
87 } cd_quirks;
88 
89 typedef enum {
90 	CD_FLAG_INVALID		= 0x001,
91 	CD_FLAG_NEW_DISC	= 0x002,
92 	CD_FLAG_DISC_LOCKED	= 0x004,
93 	CD_FLAG_DISC_REMOVABLE	= 0x008,
94 	CD_FLAG_TAGGED_QUEUING	= 0x010,
95 	CD_FLAG_CHANGER		= 0x040,
96 	CD_FLAG_ACTIVE		= 0x080,
97 	CD_FLAG_SCHED_ON_COMP	= 0x100,
98 	CD_FLAG_RETRY_UA	= 0x200
99 } cd_flags;
100 
101 typedef enum {
102 	CD_CCB_PROBE		= 0x01,
103 	CD_CCB_BUFFER_IO	= 0x02,
104 	CD_CCB_WAITING		= 0x03,
105 	CD_CCB_TYPE_MASK	= 0x0F,
106 	CD_CCB_RETRY_UA		= 0x10
107 } cd_ccb_state;
108 
109 typedef enum {
110 	CHANGER_TIMEOUT_SCHED		= 0x01,
111 	CHANGER_SHORT_TMOUT_SCHED	= 0x02,
112 	CHANGER_MANUAL_CALL		= 0x04,
113 	CHANGER_NEED_TIMEOUT		= 0x08
114 } cd_changer_flags;
115 
116 #define ccb_state ppriv_field0
117 #define ccb_bp ppriv_ptr1
118 
119 typedef enum {
120 	CD_STATE_PROBE,
121 	CD_STATE_NORMAL
122 } cd_state;
123 
124 struct cd_softc {
125 	cam_pinfo		pinfo;
126 	cd_state		state;
127 	volatile cd_flags	flags;
128 	struct bio_queue_head	bio_queue;
129 	LIST_HEAD(, ccb_hdr)	pending_ccbs;
130 	struct cd_params	params;
131 	struct disk	 	disk;
132 	union ccb		saved_ccb;
133 	cd_quirks		quirks;
134 	struct devstat		device_stats;
135 	STAILQ_ENTRY(cd_softc)	changer_links;
136 	struct cdchanger	*changer;
137 	int			bufs_left;
138 	struct cam_periph	*periph;
139 };
140 
141 struct cd_quirk_entry {
142 	struct scsi_inquiry_pattern inq_pat;
143 	cd_quirks quirks;
144 };
145 
146 /*
147  * These quirk entries aren't strictly necessary.  Basically, what they do
148  * is tell cdregister() up front that a device is a changer.  Otherwise, it
149  * will figure that fact out once it sees a LUN on the device that is
150  * greater than 0.  If it is known up front that a device is a changer, all
151  * I/O to the device will go through the changer scheduling routines, as
152  * opposed to the "normal" CD code.
153  */
154 static struct cd_quirk_entry cd_quirk_table[] =
155 {
156 	{
157 		{ T_CDROM, SIP_MEDIA_REMOVABLE, "NRC", "MBR-7", "*"},
158 		 /*quirks*/ CD_Q_CHANGER
159 	},
160 	{
161 		{ T_CDROM, SIP_MEDIA_REMOVABLE, "PIONEER", "CD-ROM DRM*",
162 		  "*"}, /* quirks */ CD_Q_CHANGER
163 	},
164 	{
165 		{ T_CDROM, SIP_MEDIA_REMOVABLE, "NAKAMICH", "MJ-*", "*"},
166 		 /* quirks */ CD_Q_CHANGER
167 	},
168 	{
169 		{ T_CDROM, SIP_MEDIA_REMOVABLE, "CHINON", "CD-ROM CDS-535","*"},
170 		/* quirks */ CD_Q_BCD_TRACKS
171 	}
172 };
173 
174 #ifndef MIN
175 #define MIN(x,y) ((x<y) ? x : y)
176 #endif
177 
178 #define CD_CDEV_MAJOR 15
179 
180 static	d_open_t	cdopen;
181 static	d_close_t	cdclose;
182 static	d_ioctl_t	cdioctl;
183 static	d_strategy_t	cdstrategy;
184 
185 static	periph_init_t	cdinit;
186 static	periph_ctor_t	cdregister;
187 static	periph_dtor_t	cdcleanup;
188 static	periph_start_t	cdstart;
189 static	periph_oninv_t	cdoninvalidate;
190 static	void		cdasync(void *callback_arg, u_int32_t code,
191 				struct cam_path *path, void *arg);
192 static	void		cdshorttimeout(void *arg);
193 static	void		cdschedule(struct cam_periph *periph, int priority);
194 static	void		cdrunchangerqueue(void *arg);
195 static	void		cdchangerschedule(struct cd_softc *softc);
196 static	int		cdrunccb(union ccb *ccb,
197 				 int (*error_routine)(union ccb *ccb,
198 						      u_int32_t cam_flags,
199 						      u_int32_t sense_flags),
200 				 u_int32_t cam_flags, u_int32_t sense_flags);
201 static union	ccb 	*cdgetccb(struct cam_periph *periph,
202 				  u_int32_t priority);
203 static	void		cddone(struct cam_periph *periph,
204 			       union ccb *start_ccb);
205 static	int		cderror(union ccb *ccb, u_int32_t cam_flags,
206 				u_int32_t sense_flags);
207 static	void		cdprevent(struct cam_periph *periph, int action);
208 static	int		cdsize(dev_t dev, u_int32_t *size);
209 static	int		cdfirsttrackisdata(struct cam_periph *periph);
210 static	int		cdreadtoc(struct cam_periph *periph, u_int32_t mode,
211 				  u_int32_t start, struct cd_toc_entry *data,
212 				  u_int32_t len);
213 static	int		cdgetmode(struct cam_periph *periph,
214 				  struct cd_mode_data *data, u_int32_t page);
215 static	int		cdsetmode(struct cam_periph *periph,
216 				  struct cd_mode_data *data);
217 static	int		cdplay(struct cam_periph *periph, u_int32_t blk,
218 			       u_int32_t len);
219 static	int		cdreadsubchannel(struct cam_periph *periph,
220 					 u_int32_t mode, u_int32_t format,
221 					 int track,
222 					 struct cd_sub_channel_info *data,
223 					 u_int32_t len);
224 static	int		cdplaymsf(struct cam_periph *periph, u_int32_t startm,
225 				  u_int32_t starts, u_int32_t startf,
226 				  u_int32_t endm, u_int32_t ends,
227 				  u_int32_t endf);
228 static	int		cdplaytracks(struct cam_periph *periph,
229 				     u_int32_t strack, u_int32_t sindex,
230 				     u_int32_t etrack, u_int32_t eindex);
231 static	int		cdpause(struct cam_periph *periph, u_int32_t go);
232 static	int		cdstopunit(struct cam_periph *periph, u_int32_t eject);
233 static	int		cdstartunit(struct cam_periph *periph);
234 static	int		cdreportkey(struct cam_periph *periph,
235 				    struct dvd_authinfo *authinfo);
236 static	int		cdsendkey(struct cam_periph *periph,
237 				  struct dvd_authinfo *authinfo);
238 static	int		cdreaddvdstructure(struct cam_periph *periph,
239 					   struct dvd_struct *dvdstruct);
240 
241 static struct periph_driver cddriver =
242 {
243 	cdinit, "cd",
244 	TAILQ_HEAD_INITIALIZER(cddriver.units), /* generation */ 0
245 };
246 
247 PERIPHDRIVER_DECLARE(cd, cddriver);
248 
249 /* For 2.2-stable support */
250 #ifndef D_DISK
251 #define D_DISK 0
252 #endif
253 static struct cdevsw cd_cdevsw = {
254 	/* open */	cdopen,
255 	/* close */	cdclose,
256 	/* read */	physread,
257 	/* write */	physwrite,
258 	/* ioctl */	cdioctl,
259 	/* poll */	nopoll,
260 	/* mmap */	nommap,
261 	/* strategy */	cdstrategy,
262 	/* name */	"cd",
263 	/* maj */	CD_CDEV_MAJOR,
264 	/* dump */	nodump,
265 	/* psize */	nopsize,
266 	/* flags */	D_DISK,
267 };
268 static struct cdevsw cddisk_cdevsw;
269 
270 static struct extend_array *cdperiphs;
271 static int num_changers;
272 
273 #ifndef CHANGER_MIN_BUSY_SECONDS
274 #define CHANGER_MIN_BUSY_SECONDS	5
275 #endif
276 #ifndef CHANGER_MAX_BUSY_SECONDS
277 #define CHANGER_MAX_BUSY_SECONDS	15
278 #endif
279 
280 static int changer_min_busy_seconds = CHANGER_MIN_BUSY_SECONDS;
281 static int changer_max_busy_seconds = CHANGER_MAX_BUSY_SECONDS;
282 
283 /*
284  * XXX KDM this CAM node should be moved if we ever get more CAM sysctl
285  * variables.
286  */
287 SYSCTL_NODE(_kern, OID_AUTO, cam, CTLFLAG_RD, 0, "CAM Subsystem");
288 SYSCTL_NODE(_kern_cam, OID_AUTO, cd, CTLFLAG_RD, 0, "CAM CDROM driver");
289 SYSCTL_NODE(_kern_cam_cd, OID_AUTO, changer, CTLFLAG_RD, 0, "CD Changer");
290 SYSCTL_INT(_kern_cam_cd_changer, OID_AUTO, min_busy_seconds, CTLFLAG_RW,
291 	   &changer_min_busy_seconds, 0, "Minimum changer scheduling quantum");
292 SYSCTL_INT(_kern_cam_cd_changer, OID_AUTO, max_busy_seconds, CTLFLAG_RW,
293 	   &changer_max_busy_seconds, 0, "Maximum changer scheduling quantum");
294 
295 struct cdchanger {
296 	path_id_t			 path_id;
297 	target_id_t			 target_id;
298 	int				 num_devices;
299 	struct camq			 devq;
300 	struct timeval			 start_time;
301 	struct cd_softc			 *cur_device;
302 	struct callout_handle		 short_handle;
303 	struct callout_handle		 long_handle;
304 	volatile cd_changer_flags	 flags;
305 	STAILQ_ENTRY(cdchanger)		 changer_links;
306 	STAILQ_HEAD(chdevlist, cd_softc) chluns;
307 };
308 
309 static STAILQ_HEAD(changerlist, cdchanger) changerq;
310 
311 void
312 cdinit(void)
313 {
314 	cam_status status;
315 	struct cam_path *path;
316 
317 	/*
318 	 * Create our extend array for storing the devices we attach to.
319 	 */
320 	cdperiphs = cam_extend_new();
321 	if (cdperiphs == NULL) {
322 		printf("cd: Failed to alloc extend array!\n");
323 		return;
324 	}
325 
326 	/*
327 	 * Install a global async callback.  This callback will
328 	 * receive async callbacks like "new device found".
329 	 */
330 	status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
331 				 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
332 
333 	if (status == CAM_REQ_CMP) {
334 		struct ccb_setasync csa;
335 
336                 xpt_setup_ccb(&csa.ccb_h, path, /*priority*/5);
337                 csa.ccb_h.func_code = XPT_SASYNC_CB;
338                 csa.event_enable = AC_FOUND_DEVICE;
339                 csa.callback = cdasync;
340                 csa.callback_arg = NULL;
341                 xpt_action((union ccb *)&csa);
342 		status = csa.ccb_h.status;
343                 xpt_free_path(path);
344         }
345 
346 	if (status != CAM_REQ_CMP) {
347 		printf("cd: Failed to attach master async callback "
348 		       "due to status 0x%x!\n", status);
349 	}
350 }
351 
352 static void
353 cdoninvalidate(struct cam_periph *periph)
354 {
355 	int s;
356 	struct cd_softc *softc;
357 	struct bio *q_bp;
358 	struct ccb_setasync csa;
359 
360 	softc = (struct cd_softc *)periph->softc;
361 
362 	/*
363 	 * De-register any async callbacks.
364 	 */
365 	xpt_setup_ccb(&csa.ccb_h, periph->path,
366 		      /* priority */ 5);
367 	csa.ccb_h.func_code = XPT_SASYNC_CB;
368 	csa.event_enable = 0;
369 	csa.callback = cdasync;
370 	csa.callback_arg = periph;
371 	xpt_action((union ccb *)&csa);
372 
373 	softc->flags |= CD_FLAG_INVALID;
374 
375 	/*
376 	 * Although the oninvalidate() routines are always called at
377 	 * splsoftcam, we need to be at splbio() here to keep the buffer
378 	 * queue from being modified while we traverse it.
379 	 */
380 	s = splbio();
381 
382 	/*
383 	 * Return all queued I/O with ENXIO.
384 	 * XXX Handle any transactions queued to the card
385 	 *     with XPT_ABORT_CCB.
386 	 */
387 	while ((q_bp = bioq_first(&softc->bio_queue)) != NULL){
388 		bioq_remove(&softc->bio_queue, q_bp);
389 		q_bp->bio_resid = q_bp->bio_bcount;
390 		biofinish(q_bp, NULL, ENXIO);
391 	}
392 	splx(s);
393 
394 	/*
395 	 * If this device is part of a changer, and it was scheduled
396 	 * to run, remove it from the run queue since we just nuked
397 	 * all of its scheduled I/O.
398 	 */
399 	if ((softc->flags & CD_FLAG_CHANGER)
400 	 && (softc->pinfo.index != CAM_UNQUEUED_INDEX))
401 		camq_remove(&softc->changer->devq, softc->pinfo.index);
402 
403 	xpt_print_path(periph->path);
404 	printf("lost device\n");
405 }
406 
407 static void
408 cdcleanup(struct cam_periph *periph)
409 {
410 	struct cd_softc *softc;
411 	int s;
412 
413 	softc = (struct cd_softc *)periph->softc;
414 
415 	xpt_print_path(periph->path);
416 	printf("removing device entry\n");
417 
418 	s = splsoftcam();
419 	/*
420 	 * In the queued, non-active case, the device in question
421 	 * has already been removed from the changer run queue.  Since this
422 	 * device is active, we need to de-activate it, and schedule
423 	 * another device to run.  (if there is another one to run)
424 	 */
425 	if ((softc->flags & CD_FLAG_CHANGER)
426 	 && (softc->flags & CD_FLAG_ACTIVE)) {
427 
428 		/*
429 		 * The purpose of the short timeout is soley to determine
430 		 * whether the current device has finished or not.  Well,
431 		 * since we're removing the active device, we know that it
432 		 * is finished.  So, get rid of the short timeout.
433 		 * Otherwise, if we're in the time period before the short
434 		 * timeout fires, and there are no other devices in the
435 		 * queue to run, there won't be any other device put in the
436 		 * active slot.  i.e., when we call cdrunchangerqueue()
437 		 * below, it won't do anything.  Then, when the short
438 		 * timeout fires, it'll look at the "current device", which
439 		 * we are free below, and possibly panic the kernel on a
440 		 * bogus pointer reference.
441 		 *
442 		 * The long timeout doesn't really matter, since we
443 		 * decrement the qfrozen_cnt to indicate that there is
444 		 * nothing in the active slot now.  Therefore, there won't
445 		 * be any bogus pointer references there.
446 		 */
447 		if (softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
448 			untimeout(cdshorttimeout, softc->changer,
449 				  softc->changer->short_handle);
450 			softc->changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
451 		}
452 		softc->changer->devq.qfrozen_cnt--;
453 		softc->changer->flags |= CHANGER_MANUAL_CALL;
454 		cdrunchangerqueue(softc->changer);
455 	}
456 
457 	/*
458 	 * If we're removing the last device on the changer, go ahead and
459 	 * remove the changer device structure.
460 	 */
461 	if ((softc->flags & CD_FLAG_CHANGER)
462 	 && (--softc->changer->num_devices == 0)) {
463 
464 		/*
465 		 * Theoretically, there shouldn't be any timeouts left, but
466 		 * I'm not completely sure that that will be the case.  So,
467 		 * it won't hurt to check and see if there are any left.
468 		 */
469 		if (softc->changer->flags & CHANGER_TIMEOUT_SCHED) {
470 			untimeout(cdrunchangerqueue, softc->changer,
471 				  softc->changer->long_handle);
472 			softc->changer->flags &= ~CHANGER_TIMEOUT_SCHED;
473 		}
474 
475 		if (softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
476 			untimeout(cdshorttimeout, softc->changer,
477 				  softc->changer->short_handle);
478 			softc->changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
479 		}
480 
481 		STAILQ_REMOVE(&changerq, softc->changer, cdchanger,
482 			      changer_links);
483 		xpt_print_path(periph->path);
484 		printf("removing changer entry\n");
485 		free(softc->changer, M_DEVBUF);
486 		num_changers--;
487 	}
488 	devstat_remove_entry(&softc->device_stats);
489 	cam_extend_release(cdperiphs, periph->unit_number);
490 	free(softc, M_DEVBUF);
491 	splx(s);
492 }
493 
494 static void
495 cdasync(void *callback_arg, u_int32_t code,
496 	struct cam_path *path, void *arg)
497 {
498 	struct cam_periph *periph;
499 
500 	periph = (struct cam_periph *)callback_arg;
501 	switch (code) {
502 	case AC_FOUND_DEVICE:
503 	{
504 		struct ccb_getdev *cgd;
505 		cam_status status;
506 
507 		cgd = (struct ccb_getdev *)arg;
508 		if (cgd == NULL)
509 			break;
510 
511 		if (SID_TYPE(&cgd->inq_data) != T_CDROM
512 		    && SID_TYPE(&cgd->inq_data) != T_WORM)
513 			break;
514 
515 		/*
516 		 * Allocate a peripheral instance for
517 		 * this device and start the probe
518 		 * process.
519 		 */
520 		status = cam_periph_alloc(cdregister, cdoninvalidate,
521 					  cdcleanup, cdstart,
522 					  "cd", CAM_PERIPH_BIO,
523 					  cgd->ccb_h.path, cdasync,
524 					  AC_FOUND_DEVICE, cgd);
525 
526 		if (status != CAM_REQ_CMP
527 		 && status != CAM_REQ_INPROG)
528 			printf("cdasync: Unable to attach new device "
529 			       "due to status 0x%x\n", status);
530 
531 		break;
532 	}
533 	case AC_SENT_BDR:
534 	case AC_BUS_RESET:
535 	{
536 		struct cd_softc *softc;
537 		struct ccb_hdr *ccbh;
538 		int s;
539 
540 		softc = (struct cd_softc *)periph->softc;
541 		s = splsoftcam();
542 		/*
543 		 * Don't fail on the expected unit attention
544 		 * that will occur.
545 		 */
546 		softc->flags |= CD_FLAG_RETRY_UA;
547 		LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
548 			ccbh->ccb_state |= CD_CCB_RETRY_UA;
549 		splx(s);
550 		/* FALLTHROUGH */
551 	}
552 	default:
553 		cam_periph_async(periph, code, path, arg);
554 		break;
555 	}
556 }
557 
558 static cam_status
559 cdregister(struct cam_periph *periph, void *arg)
560 {
561 	struct cd_softc *softc;
562 	struct ccb_setasync csa;
563 	struct ccb_getdev *cgd;
564 	caddr_t match;
565 
566 	cgd = (struct ccb_getdev *)arg;
567 	if (periph == NULL) {
568 		printf("cdregister: periph was NULL!!\n");
569 		return(CAM_REQ_CMP_ERR);
570 	}
571 	if (cgd == NULL) {
572 		printf("cdregister: no getdev CCB, can't register device\n");
573 		return(CAM_REQ_CMP_ERR);
574 	}
575 
576 	softc = (struct cd_softc *)malloc(sizeof(*softc),M_DEVBUF,M_NOWAIT);
577 
578 	if (softc == NULL) {
579 		printf("cdregister: Unable to probe new device. "
580 		       "Unable to allocate softc\n");
581 		return(CAM_REQ_CMP_ERR);
582 	}
583 
584 	bzero(softc, sizeof(*softc));
585 	LIST_INIT(&softc->pending_ccbs);
586 	softc->state = CD_STATE_PROBE;
587 	bioq_init(&softc->bio_queue);
588 	if (SID_IS_REMOVABLE(&cgd->inq_data))
589 		softc->flags |= CD_FLAG_DISC_REMOVABLE;
590 	if ((cgd->inq_data.flags & SID_CmdQue) != 0)
591 		softc->flags |= CD_FLAG_TAGGED_QUEUING;
592 
593 	periph->softc = softc;
594 	softc->periph = periph;
595 
596 	cam_extend_set(cdperiphs, periph->unit_number, periph);
597 
598 	/*
599 	 * See if this device has any quirks.
600 	 */
601 	match = cam_quirkmatch((caddr_t)&cgd->inq_data,
602 			       (caddr_t)cd_quirk_table,
603 			       sizeof(cd_quirk_table)/sizeof(*cd_quirk_table),
604 			       sizeof(*cd_quirk_table), scsi_inquiry_match);
605 
606 	if (match != NULL)
607 		softc->quirks = ((struct cd_quirk_entry *)match)->quirks;
608 	else
609 		softc->quirks = CD_Q_NONE;
610 
611 	/*
612 	 * We need to register the statistics structure for this device,
613 	 * but we don't have the blocksize yet for it.  So, we register
614 	 * the structure and indicate that we don't have the blocksize
615 	 * yet.  Unlike other SCSI peripheral drivers, we explicitly set
616 	 * the device type here to be CDROM, rather than just ORing in
617 	 * the device type.  This is because this driver can attach to either
618 	 * CDROM or WORM devices, and we want this peripheral driver to
619 	 * show up in the devstat list as a CD peripheral driver, not a
620 	 * WORM peripheral driver.  WORM drives will also have the WORM
621 	 * driver attached to them.
622 	 */
623 	devstat_add_entry(&softc->device_stats, "cd",
624 			  periph->unit_number, 0,
625 	  		  DEVSTAT_BS_UNAVAILABLE,
626 			  DEVSTAT_TYPE_CDROM | DEVSTAT_TYPE_IF_SCSI,
627 			  DEVSTAT_PRIORITY_CD);
628 	disk_create(periph->unit_number, &softc->disk,
629 		    DSO_ONESLICE | DSO_COMPATLABEL,
630 		    &cd_cdevsw, &cddisk_cdevsw);
631 
632 	/*
633 	 * Add an async callback so that we get
634 	 * notified if this device goes away.
635 	 */
636 	xpt_setup_ccb(&csa.ccb_h, periph->path,
637 		      /* priority */ 5);
638 	csa.ccb_h.func_code = XPT_SASYNC_CB;
639 	csa.event_enable = AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE;
640 	csa.callback = cdasync;
641 	csa.callback_arg = periph;
642 	xpt_action((union ccb *)&csa);
643 
644 	/*
645 	 * If the target lun is greater than 0, we most likely have a CD
646 	 * changer device.  Check the quirk entries as well, though, just
647 	 * in case someone has a CD tower with one lun per drive or
648 	 * something like that.  Also, if we know up front that a
649 	 * particular device is a changer, we can mark it as such starting
650 	 * with lun 0, instead of lun 1.  It shouldn't be necessary to have
651 	 * a quirk entry to define something as a changer, however.
652 	 */
653 	if (((cgd->ccb_h.target_lun > 0)
654 	  && ((softc->quirks & CD_Q_NO_CHANGER) == 0))
655 	 || ((softc->quirks & CD_Q_CHANGER) != 0)) {
656 		struct cdchanger *nchanger;
657 		struct cam_periph *nperiph;
658 		struct cam_path *path;
659 		cam_status status;
660 		int found;
661 
662 		/* Set the changer flag in the current device's softc */
663 		softc->flags |= CD_FLAG_CHANGER;
664 
665 		if (num_changers == 0)
666 			STAILQ_INIT(&changerq);
667 
668 		/*
669 		 * Now, look around for an existing changer device with the
670 		 * same path and target ID as the current device.
671 		 */
672 		for (found = 0,
673 		     nchanger = (struct cdchanger *)STAILQ_FIRST(&changerq);
674 		     nchanger != NULL;
675 		     nchanger = STAILQ_NEXT(nchanger, changer_links)){
676 			if ((nchanger->path_id == cgd->ccb_h.path_id)
677 			 && (nchanger->target_id == cgd->ccb_h.target_id)) {
678 				found = 1;
679 				break;
680 			}
681 		}
682 
683 		/*
684 		 * If we found a matching entry, just add this device to
685 		 * the list of devices on this changer.
686 		 */
687 		if (found == 1) {
688 			struct chdevlist *chlunhead;
689 
690 			chlunhead = &nchanger->chluns;
691 
692 			/*
693 			 * XXX KDM look at consolidating this code with the
694 			 * code below in a separate function.
695 			 */
696 
697 			/*
698 			 * Create a path with lun id 0, and see if we can
699 			 * find a matching device
700 			 */
701 			status = xpt_create_path(&path, /*periph*/ periph,
702 						 cgd->ccb_h.path_id,
703 						 cgd->ccb_h.target_id, 0);
704 
705 			if ((status == CAM_REQ_CMP)
706 			 && ((nperiph = cam_periph_find(path, "cd")) != NULL)){
707 				struct cd_softc *nsoftc;
708 
709 				nsoftc = (struct cd_softc *)nperiph->softc;
710 
711 				if ((nsoftc->flags & CD_FLAG_CHANGER) == 0){
712 					nsoftc->flags |= CD_FLAG_CHANGER;
713 					nchanger->num_devices++;
714 					if (camq_resize(&nchanger->devq,
715 					   nchanger->num_devices)!=CAM_REQ_CMP){
716 						printf("cdregister: "
717 						       "camq_resize "
718 						       "failed, changer "
719 						       "support may "
720 						       "be messed up\n");
721 					}
722 					nsoftc->changer = nchanger;
723 					nsoftc->pinfo.index =CAM_UNQUEUED_INDEX;
724 
725 					STAILQ_INSERT_TAIL(&nchanger->chluns,
726 							  nsoftc,changer_links);
727 				}
728 				xpt_free_path(path);
729 			} else if (status == CAM_REQ_CMP)
730 				xpt_free_path(path);
731 			else {
732 				printf("cdregister: unable to allocate path\n"
733 				       "cdregister: changer support may be "
734 				       "broken\n");
735 			}
736 
737 			nchanger->num_devices++;
738 
739 			softc->changer = nchanger;
740 			softc->pinfo.index = CAM_UNQUEUED_INDEX;
741 
742 			if (camq_resize(&nchanger->devq,
743 			    nchanger->num_devices) != CAM_REQ_CMP) {
744 				printf("cdregister: camq_resize "
745 				       "failed, changer support may "
746 				       "be messed up\n");
747 			}
748 
749 			STAILQ_INSERT_TAIL(chlunhead, softc, changer_links);
750 		}
751 		/*
752 		 * In this case, we don't already have an entry for this
753 		 * particular changer, so we need to create one, add it to
754 		 * the queue, and queue this device on the list for this
755 		 * changer.  Before we queue this device, however, we need
756 		 * to search for lun id 0 on this target, and add it to the
757 		 * queue first, if it exists.  (and if it hasn't already
758 		 * been marked as part of the changer.)
759 		 */
760 		else {
761 			nchanger = malloc(sizeof(struct cdchanger),
762 				M_DEVBUF, M_NOWAIT);
763 
764 			if (nchanger == NULL) {
765 				softc->flags &= ~CD_FLAG_CHANGER;
766 				printf("cdregister: unable to malloc "
767 				       "changer structure\ncdregister: "
768 				       "changer support disabled\n");
769 
770 				/*
771 				 * Yes, gotos can be gross but in this case
772 				 * I think it's justified..
773 				 */
774 				goto cdregisterexit;
775 			}
776 
777 			/* zero the structure */
778 			bzero(nchanger, sizeof(struct cdchanger));
779 
780 			if (camq_init(&nchanger->devq, 1) != 0) {
781 				softc->flags &= ~CD_FLAG_CHANGER;
782 				printf("cdregister: changer support "
783 				       "disabled\n");
784 				goto cdregisterexit;
785 			}
786 
787 			num_changers++;
788 
789 			nchanger->path_id = cgd->ccb_h.path_id;
790 			nchanger->target_id = cgd->ccb_h.target_id;
791 
792 			/* this is superfluous, but it makes things clearer */
793 			nchanger->num_devices = 0;
794 
795 			STAILQ_INIT(&nchanger->chluns);
796 
797 			STAILQ_INSERT_TAIL(&changerq, nchanger,
798 					   changer_links);
799 
800 			/*
801 			 * Create a path with lun id 0, and see if we can
802 			 * find a matching device
803 			 */
804 			status = xpt_create_path(&path, /*periph*/ periph,
805 						 cgd->ccb_h.path_id,
806 						 cgd->ccb_h.target_id, 0);
807 
808 			/*
809 			 * If we were able to allocate the path, and if we
810 			 * find a matching device and it isn't already
811 			 * marked as part of a changer, then we add it to
812 			 * the current changer.
813 			 */
814 			if ((status == CAM_REQ_CMP)
815 			 && ((nperiph = cam_periph_find(path, "cd")) != NULL)
816 			 && ((((struct cd_softc *)periph->softc)->flags &
817 			       CD_FLAG_CHANGER) == 0)) {
818 				struct cd_softc *nsoftc;
819 
820 				nsoftc = (struct cd_softc *)nperiph->softc;
821 
822 				nsoftc->flags |= CD_FLAG_CHANGER;
823 				nchanger->num_devices++;
824 				if (camq_resize(&nchanger->devq,
825 				    nchanger->num_devices) != CAM_REQ_CMP) {
826 					printf("cdregister: camq_resize "
827 					       "failed, changer support may "
828 					       "be messed up\n");
829 				}
830 				nsoftc->changer = nchanger;
831 				nsoftc->pinfo.index = CAM_UNQUEUED_INDEX;
832 
833 				STAILQ_INSERT_TAIL(&nchanger->chluns,
834 						   nsoftc, changer_links);
835 				xpt_free_path(path);
836 			} else if (status == CAM_REQ_CMP)
837 				xpt_free_path(path);
838 			else {
839 				printf("cdregister: unable to allocate path\n"
840 				       "cdregister: changer support may be "
841 				       "broken\n");
842 			}
843 
844 			softc->changer = nchanger;
845 			softc->pinfo.index = CAM_UNQUEUED_INDEX;
846 			nchanger->num_devices++;
847 			if (camq_resize(&nchanger->devq,
848 			    nchanger->num_devices) != CAM_REQ_CMP) {
849 				printf("cdregister: camq_resize "
850 				       "failed, changer support may "
851 				       "be messed up\n");
852 			}
853 			STAILQ_INSERT_TAIL(&nchanger->chluns, softc,
854 					   changer_links);
855 		}
856 	}
857 
858 cdregisterexit:
859 
860 	/* Lock this peripheral until we are setup */
861 	/* Can't block */
862 	cam_periph_lock(periph, PRIBIO);
863 
864 	if ((softc->flags & CD_FLAG_CHANGER) == 0)
865 		xpt_schedule(periph, /*priority*/5);
866 	else
867 		cdschedule(periph, /*priority*/ 5);
868 
869 	return(CAM_REQ_CMP);
870 }
871 
872 static int
873 cdopen(dev_t dev, int flags, int fmt, struct proc *p)
874 {
875 	struct disklabel *label;
876 	struct cam_periph *periph;
877 	struct cd_softc *softc;
878 	struct ccb_getdev cgd;
879 	u_int32_t size;
880 	int unit, error;
881 	int s;
882 
883 	unit = dkunit(dev);
884 	periph = cam_extend_get(cdperiphs, unit);
885 
886 	if (periph == NULL)
887 		return (ENXIO);
888 
889 	softc = (struct cd_softc *)periph->softc;
890 
891 	/*
892 	 * Grab splsoftcam and hold it until we lock the peripheral.
893 	 */
894 	s = splsoftcam();
895 	if (softc->flags & CD_FLAG_INVALID) {
896 		splx(s);
897 		return(ENXIO);
898 	}
899 
900 	if ((error = cam_periph_lock(periph, PRIBIO | PCATCH)) != 0) {
901 		splx(s);
902 		return (error);
903 	}
904 
905 	splx(s);
906 
907 	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
908 		return(ENXIO);
909 
910 	cdprevent(periph, PR_PREVENT);
911 
912 	/* find out the size */
913 	if ((error = cdsize(dev, &size)) != 0) {
914 		cdprevent(periph, PR_ALLOW);
915 		cam_periph_unlock(periph);
916 		cam_periph_release(periph);
917 		return(error);
918 	}
919 
920 	/*
921 	 * If we get a non-zero return, revert back to not reading the
922 	 * label off the disk.  The first track is likely audio, which
923 	 * won't have a disklabel.
924 	 */
925 	if ((error = cdfirsttrackisdata(periph)) != 0) {
926 		softc->disk.d_dsflags &= ~DSO_COMPATLABEL;
927 		softc->disk.d_dsflags |= DSO_NOLABELS;
928 		error = 0;
929 	}
930 
931 	/*
932 	 * Build prototype label for whole disk.
933 	 * Should take information about different data tracks from the
934 	 * TOC and put it in the partition table.
935 	 */
936 	label = &softc->disk.d_label;
937 	bzero(label, sizeof(*label));
938 	label->d_type = DTYPE_SCSI;
939 
940 	/*
941 	 * Grab the inquiry data to get the vendor and product names.
942 	 * Put them in the typename and packname for the label.
943 	 */
944 	xpt_setup_ccb(&cgd.ccb_h, periph->path, /*priority*/ 1);
945 	cgd.ccb_h.func_code = XPT_GDEV_TYPE;
946 	xpt_action((union ccb *)&cgd);
947 
948 	strncpy(label->d_typename, cgd.inq_data.vendor,
949 		min(SID_VENDOR_SIZE, sizeof(label->d_typename)));
950 	strncpy(label->d_packname, cgd.inq_data.product,
951 		min(SID_PRODUCT_SIZE, sizeof(label->d_packname)));
952 
953 	label->d_secsize = softc->params.blksize;
954 	label->d_secperunit = softc->params.disksize;
955 	label->d_flags = D_REMOVABLE;
956 	/*
957 	 * Make partition 'a' cover the whole disk.  This is a temporary
958 	 * compatibility hack.  The 'a' partition should not exist, so
959 	 * the slice code won't create it.  The slice code will make
960 	 * partition (RAW_PART + 'a') cover the whole disk and fill in
961 	 * some more defaults.
962 	 */
963 	label->d_partitions[0].p_size = label->d_secperunit;
964 	label->d_partitions[0].p_fstype = FS_OTHER;
965 
966 	/*
967 	 * We unconditionally (re)set the blocksize each time the
968 	 * CD device is opened.  This is because the CD can change,
969 	 * and therefore the blocksize might change.
970 	 * XXX problems here if some slice or partition is still
971 	 * open with the old size?
972 	 */
973 	if ((softc->device_stats.flags & DEVSTAT_BS_UNAVAILABLE) != 0)
974 		softc->device_stats.flags &= ~DEVSTAT_BS_UNAVAILABLE;
975 	softc->device_stats.block_size = softc->params.blksize;
976 
977 	cam_periph_unlock(periph);
978 
979 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdopen\n"));
980 
981 	return (error);
982 }
983 
984 static int
985 cdclose(dev_t dev, int flag, int fmt, struct proc *p)
986 {
987 	struct 	cam_periph *periph;
988 	struct	cd_softc *softc;
989 	int	unit, error;
990 
991 	unit = dkunit(dev);
992 	periph = cam_extend_get(cdperiphs, unit);
993 	if (periph == NULL)
994 		return (ENXIO);
995 
996 	softc = (struct cd_softc *)periph->softc;
997 
998 	if ((error = cam_periph_lock(periph, PRIBIO)) != 0)
999 		return (error);
1000 
1001 	if ((softc->flags & CD_FLAG_DISC_REMOVABLE) != 0)
1002 		cdprevent(periph, PR_ALLOW);
1003 
1004 	/*
1005 	 * Unconditionally set the dsopen() flags back to their default
1006 	 * state.
1007 	 */
1008 	softc->disk.d_dsflags &= ~DSO_NOLABELS;
1009 	softc->disk.d_dsflags |= DSO_COMPATLABEL;
1010 
1011 	/*
1012 	 * Since we're closing this CD, mark the blocksize as unavailable.
1013 	 * It will be marked as available whence the CD is opened again.
1014 	 */
1015 	softc->device_stats.flags |= DEVSTAT_BS_UNAVAILABLE;
1016 
1017 	cam_periph_unlock(periph);
1018 	cam_periph_release(periph);
1019 
1020 	return (0);
1021 }
1022 
1023 static void
1024 cdshorttimeout(void *arg)
1025 {
1026 	struct cdchanger *changer;
1027 	int s;
1028 
1029 	s = splsoftcam();
1030 
1031 	changer = (struct cdchanger *)arg;
1032 
1033 	/* Always clear the short timeout flag, since that's what we're in */
1034 	changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
1035 
1036 	/*
1037 	 * Check to see if there is any more pending or outstanding I/O for
1038 	 * this device.  If not, move it out of the active slot.
1039 	 */
1040 	if ((bioq_first(&changer->cur_device->bio_queue) == NULL)
1041 	 && (changer->cur_device->device_stats.busy_count == 0)) {
1042 		changer->flags |= CHANGER_MANUAL_CALL;
1043 		cdrunchangerqueue(changer);
1044 	}
1045 
1046 	splx(s);
1047 }
1048 
1049 /*
1050  * This is a wrapper for xpt_schedule.  It only applies to changers.
1051  */
1052 static void
1053 cdschedule(struct cam_periph *periph, int priority)
1054 {
1055 	struct cd_softc *softc;
1056 	int s;
1057 
1058 	s = splsoftcam();
1059 
1060 	softc = (struct cd_softc *)periph->softc;
1061 
1062 	/*
1063 	 * If this device isn't currently queued, and if it isn't
1064 	 * the active device, then we queue this device and run the
1065 	 * changer queue if there is no timeout scheduled to do it.
1066 	 * If this device is the active device, just schedule it
1067 	 * to run again.  If this device is queued, there should be
1068 	 * a timeout in place already that will make sure it runs.
1069 	 */
1070 	if ((softc->pinfo.index == CAM_UNQUEUED_INDEX)
1071 	 && ((softc->flags & CD_FLAG_ACTIVE) == 0)) {
1072 		/*
1073 		 * We don't do anything with the priority here.
1074 		 * This is strictly a fifo queue.
1075 		 */
1076 		softc->pinfo.priority = 1;
1077 		softc->pinfo.generation = ++softc->changer->devq.generation;
1078 		camq_insert(&softc->changer->devq, (cam_pinfo *)softc);
1079 
1080 		/*
1081 		 * Since we just put a device in the changer queue,
1082 		 * check and see if there is a timeout scheduled for
1083 		 * this changer.  If so, let the timeout handle
1084 		 * switching this device into the active slot.  If
1085 		 * not, manually call the timeout routine to
1086 		 * bootstrap things.
1087 		 */
1088 		if (((softc->changer->flags & CHANGER_TIMEOUT_SCHED)==0)
1089 		 && ((softc->changer->flags & CHANGER_NEED_TIMEOUT)==0)
1090 		 && ((softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED)==0)){
1091 			softc->changer->flags |= CHANGER_MANUAL_CALL;
1092 			cdrunchangerqueue(softc->changer);
1093 		}
1094 	} else if ((softc->flags & CD_FLAG_ACTIVE)
1095 		&& ((softc->flags & CD_FLAG_SCHED_ON_COMP) == 0))
1096 		xpt_schedule(periph, priority);
1097 
1098 	splx(s);
1099 
1100 }
1101 
1102 static void
1103 cdrunchangerqueue(void *arg)
1104 {
1105 	struct cd_softc *softc;
1106 	struct cdchanger *changer;
1107 	int called_from_timeout;
1108 	int s;
1109 
1110 	s = splsoftcam();
1111 
1112 	changer = (struct cdchanger *)arg;
1113 
1114 	/*
1115 	 * If we have NOT been called from cdstrategy() or cddone(), and
1116 	 * instead from a timeout routine, go ahead and clear the
1117 	 * timeout flag.
1118 	 */
1119 	if ((changer->flags & CHANGER_MANUAL_CALL) == 0) {
1120 		changer->flags &= ~CHANGER_TIMEOUT_SCHED;
1121 		called_from_timeout = 1;
1122 	} else
1123 		called_from_timeout = 0;
1124 
1125 	/* Always clear the manual call flag */
1126 	changer->flags &= ~CHANGER_MANUAL_CALL;
1127 
1128 	/* nothing to do if the queue is empty */
1129 	if (changer->devq.entries <= 0) {
1130 		splx(s);
1131 		return;
1132 	}
1133 
1134 	/*
1135 	 * If the changer queue is frozen, that means we have an active
1136 	 * device.
1137 	 */
1138 	if (changer->devq.qfrozen_cnt > 0) {
1139 
1140 		if (changer->cur_device->device_stats.busy_count > 0) {
1141 			changer->cur_device->flags |= CD_FLAG_SCHED_ON_COMP;
1142 			changer->cur_device->bufs_left =
1143 				changer->cur_device->device_stats.busy_count;
1144 			if (called_from_timeout) {
1145 				changer->long_handle =
1146 					timeout(cdrunchangerqueue, changer,
1147 				        changer_max_busy_seconds * hz);
1148 				changer->flags |= CHANGER_TIMEOUT_SCHED;
1149 			}
1150 			splx(s);
1151 			return;
1152 		}
1153 
1154 		/*
1155 		 * We always need to reset the frozen count and clear the
1156 		 * active flag.
1157 		 */
1158 		changer->devq.qfrozen_cnt--;
1159 		changer->cur_device->flags &= ~CD_FLAG_ACTIVE;
1160 		changer->cur_device->flags &= ~CD_FLAG_SCHED_ON_COMP;
1161 
1162 		/*
1163 		 * Check to see whether the current device has any I/O left
1164 		 * to do.  If so, requeue it at the end of the queue.  If
1165 		 * not, there is no need to requeue it.
1166 		 */
1167 		if (bioq_first(&changer->cur_device->bio_queue) != NULL) {
1168 
1169 			changer->cur_device->pinfo.generation =
1170 				++changer->devq.generation;
1171 			camq_insert(&changer->devq,
1172 				(cam_pinfo *)changer->cur_device);
1173 		}
1174 	}
1175 
1176 	softc = (struct cd_softc *)camq_remove(&changer->devq, CAMQ_HEAD);
1177 
1178 	changer->cur_device = softc;
1179 
1180 	changer->devq.qfrozen_cnt++;
1181 	softc->flags |= CD_FLAG_ACTIVE;
1182 
1183 	/* Just in case this device is waiting */
1184 	wakeup(&softc->changer);
1185 	xpt_schedule(softc->periph, /*priority*/ 1);
1186 
1187 	/*
1188 	 * Get rid of any pending timeouts, and set a flag to schedule new
1189 	 * ones so this device gets its full time quantum.
1190 	 */
1191 	if (changer->flags & CHANGER_TIMEOUT_SCHED) {
1192 		untimeout(cdrunchangerqueue, changer, changer->long_handle);
1193 		changer->flags &= ~CHANGER_TIMEOUT_SCHED;
1194 	}
1195 
1196 	if (changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
1197 		untimeout(cdshorttimeout, changer, changer->short_handle);
1198 		changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
1199 	}
1200 
1201 	/*
1202 	 * We need to schedule timeouts, but we only do this after the
1203 	 * first transaction has completed.  This eliminates the changer
1204 	 * switch time.
1205 	 */
1206 	changer->flags |= CHANGER_NEED_TIMEOUT;
1207 
1208 	splx(s);
1209 }
1210 
1211 static void
1212 cdchangerschedule(struct cd_softc *softc)
1213 {
1214 	struct cdchanger *changer;
1215 	int s;
1216 
1217 	s = splsoftcam();
1218 
1219 	changer = softc->changer;
1220 
1221 	/*
1222 	 * If this is a changer, and this is the current device,
1223 	 * and this device has at least the minimum time quantum to
1224 	 * run, see if we can switch it out.
1225 	 */
1226 	if ((softc->flags & CD_FLAG_ACTIVE)
1227 	 && ((changer->flags & CHANGER_SHORT_TMOUT_SCHED) == 0)
1228 	 && ((changer->flags & CHANGER_NEED_TIMEOUT) == 0)) {
1229 		/*
1230 		 * We try three things here.  The first is that we
1231 		 * check to see whether the schedule on completion
1232 		 * flag is set.  If it is, we decrement the number
1233 		 * of buffers left, and if it's zero, we reschedule.
1234 		 * Next, we check to see whether the pending buffer
1235 		 * queue is empty and whether there are no
1236 		 * outstanding transactions.  If so, we reschedule.
1237 		 * Next, we see if the pending buffer queue is empty.
1238 		 * If it is, we set the number of buffers left to
1239 		 * the current active buffer count and set the
1240 		 * schedule on complete flag.
1241 		 */
1242 		if (softc->flags & CD_FLAG_SCHED_ON_COMP) {
1243 		 	if (--softc->bufs_left == 0) {
1244 				softc->changer->flags |=
1245 					CHANGER_MANUAL_CALL;
1246 				softc->flags &= ~CD_FLAG_SCHED_ON_COMP;
1247 				cdrunchangerqueue(softc->changer);
1248 			}
1249 		} else if ((bioq_first(&softc->bio_queue) == NULL)
1250 		        && (softc->device_stats.busy_count == 0)) {
1251 			softc->changer->flags |= CHANGER_MANUAL_CALL;
1252 			cdrunchangerqueue(softc->changer);
1253 		}
1254 	} else if ((softc->changer->flags & CHANGER_NEED_TIMEOUT)
1255 		&& (softc->flags & CD_FLAG_ACTIVE)) {
1256 
1257 		/*
1258 		 * Now that the first transaction to this
1259 		 * particular device has completed, we can go ahead
1260 		 * and schedule our timeouts.
1261 		 */
1262 		if ((changer->flags & CHANGER_TIMEOUT_SCHED) == 0) {
1263 			changer->long_handle =
1264 			    timeout(cdrunchangerqueue, changer,
1265 				    changer_max_busy_seconds * hz);
1266 			changer->flags |= CHANGER_TIMEOUT_SCHED;
1267 		} else
1268 			printf("cdchangerschedule: already have a long"
1269 			       " timeout!\n");
1270 
1271 		if ((changer->flags & CHANGER_SHORT_TMOUT_SCHED) == 0) {
1272 			changer->short_handle =
1273 			    timeout(cdshorttimeout, changer,
1274 				    changer_min_busy_seconds * hz);
1275 			changer->flags |= CHANGER_SHORT_TMOUT_SCHED;
1276 		} else
1277 			printf("cdchangerschedule: already have a short "
1278 			       "timeout!\n");
1279 
1280 		/*
1281 		 * We just scheduled timeouts, no need to schedule
1282 		 * more.
1283 		 */
1284 		changer->flags &= ~CHANGER_NEED_TIMEOUT;
1285 
1286 	}
1287 	splx(s);
1288 }
1289 
1290 static int
1291 cdrunccb(union ccb *ccb, int (*error_routine)(union ccb *ccb,
1292 					      u_int32_t cam_flags,
1293 					      u_int32_t sense_flags),
1294 	 u_int32_t cam_flags, u_int32_t sense_flags)
1295 {
1296 	struct cd_softc *softc;
1297 	struct cam_periph *periph;
1298 	int error;
1299 
1300 	periph = xpt_path_periph(ccb->ccb_h.path);
1301 	softc = (struct cd_softc *)periph->softc;
1302 
1303 	error = cam_periph_runccb(ccb, error_routine, cam_flags, sense_flags,
1304 				  &softc->device_stats);
1305 
1306 	if (softc->flags & CD_FLAG_CHANGER)
1307 		cdchangerschedule(softc);
1308 
1309 	return(error);
1310 }
1311 
1312 static union ccb *
1313 cdgetccb(struct cam_periph *periph, u_int32_t priority)
1314 {
1315 	struct cd_softc *softc;
1316 	int s;
1317 
1318 	softc = (struct cd_softc *)periph->softc;
1319 
1320 	if (softc->flags & CD_FLAG_CHANGER) {
1321 
1322 		s = splsoftcam();
1323 
1324 		/*
1325 		 * This should work the first time this device is woken up,
1326 		 * but just in case it doesn't, we use a while loop.
1327 		 */
1328 		while ((softc->flags & CD_FLAG_ACTIVE) == 0) {
1329 			/*
1330 			 * If this changer isn't already queued, queue it up.
1331 			 */
1332 			if (softc->pinfo.index == CAM_UNQUEUED_INDEX) {
1333 				softc->pinfo.priority = 1;
1334 				softc->pinfo.generation =
1335 					++softc->changer->devq.generation;
1336 				camq_insert(&softc->changer->devq,
1337 					    (cam_pinfo *)softc);
1338 			}
1339 			if (((softc->changer->flags & CHANGER_TIMEOUT_SCHED)==0)
1340 			 && ((softc->changer->flags & CHANGER_NEED_TIMEOUT)==0)
1341 			 && ((softc->changer->flags
1342 			      & CHANGER_SHORT_TMOUT_SCHED)==0)) {
1343 				softc->changer->flags |= CHANGER_MANUAL_CALL;
1344 				cdrunchangerqueue(softc->changer);
1345 			} else
1346 				tsleep(&softc->changer, PRIBIO, "cgticb", 0);
1347 		}
1348 		splx(s);
1349 	}
1350 	return(cam_periph_getccb(periph, priority));
1351 }
1352 
1353 
1354 /*
1355  * Actually translate the requested transfer into one the physical driver
1356  * can understand.  The transfer is described by a buf and will include
1357  * only one physical transfer.
1358  */
1359 static void
1360 cdstrategy(struct bio *bp)
1361 {
1362 	struct cam_periph *periph;
1363 	struct cd_softc *softc;
1364 	u_int  unit, part;
1365 	int    s;
1366 
1367 	unit = dkunit(bp->bio_dev);
1368 	part = dkpart(bp->bio_dev);
1369 	periph = cam_extend_get(cdperiphs, unit);
1370 	if (periph == NULL) {
1371 		biofinish(bp, NULL, ENXIO);
1372 		return;
1373 	}
1374 
1375 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdstrategy\n"));
1376 
1377 	softc = (struct cd_softc *)periph->softc;
1378 
1379 	/*
1380 	 * Mask interrupts so that the pack cannot be invalidated until
1381 	 * after we are in the queue.  Otherwise, we might not properly
1382 	 * clean up one of the buffers.
1383 	 */
1384 	s = splbio();
1385 
1386 	/*
1387 	 * If the device has been made invalid, error out
1388 	 */
1389 	if ((softc->flags & CD_FLAG_INVALID)) {
1390 		splx(s);
1391 		biofinish(bp, NULL, ENXIO);
1392 		return;
1393 	}
1394 
1395 	/*
1396 	 * Place it in the queue of disk activities for this disk
1397 	 */
1398 	bioqdisksort(&softc->bio_queue, bp);
1399 
1400 	splx(s);
1401 
1402 	/*
1403 	 * Schedule ourselves for performing the work.  We do things
1404 	 * differently for changers.
1405 	 */
1406 	if ((softc->flags & CD_FLAG_CHANGER) == 0)
1407 		xpt_schedule(periph, /* XXX priority */1);
1408 	else
1409 		cdschedule(periph, /* priority */ 1);
1410 
1411 	return;
1412 }
1413 
1414 static void
1415 cdstart(struct cam_periph *periph, union ccb *start_ccb)
1416 {
1417 	struct cd_softc *softc;
1418 	struct bio *bp;
1419 	struct ccb_scsiio *csio;
1420 	struct scsi_read_capacity_data *rcap;
1421 	int s;
1422 
1423 	softc = (struct cd_softc *)periph->softc;
1424 
1425 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdstart\n"));
1426 
1427 	switch (softc->state) {
1428 	case CD_STATE_NORMAL:
1429 	{
1430 		int oldspl;
1431 
1432 		s = splbio();
1433 		bp = bioq_first(&softc->bio_queue);
1434 		if (periph->immediate_priority <= periph->pinfo.priority) {
1435 			start_ccb->ccb_h.ccb_state = CD_CCB_WAITING;
1436 
1437 			SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1438 					  periph_links.sle);
1439 			periph->immediate_priority = CAM_PRIORITY_NONE;
1440 			splx(s);
1441 			wakeup(&periph->ccb_list);
1442 		} else if (bp == NULL) {
1443 			splx(s);
1444 			xpt_release_ccb(start_ccb);
1445 		} else {
1446 			bioq_remove(&softc->bio_queue, bp);
1447 
1448 			devstat_start_transaction(&softc->device_stats);
1449 
1450 			scsi_read_write(&start_ccb->csio,
1451 					/*retries*/4,
1452 					/* cbfcnp */ cddone,
1453 					(bp->bio_flags & BIO_ORDERED) != 0 ?
1454 					    MSG_ORDERED_Q_TAG :
1455 					    MSG_SIMPLE_Q_TAG,
1456 					/* read */bp->bio_cmd == BIO_READ,
1457 					/* byte2 */ 0,
1458 					/* minimum_cmd_size */ 10,
1459 					/* lba */ bp->bio_pblkno,
1460 					bp->bio_bcount / softc->params.blksize,
1461 					/* data_ptr */ bp->bio_data,
1462 					/* dxfer_len */ bp->bio_bcount,
1463 					/* sense_len */ SSD_FULL_SIZE,
1464 					/* timeout */ 30000);
1465 			start_ccb->ccb_h.ccb_state = CD_CCB_BUFFER_IO;
1466 
1467 
1468 			/*
1469 			 * Block out any asyncronous callbacks
1470 			 * while we touch the pending ccb list.
1471 			 */
1472 			oldspl = splcam();
1473 			LIST_INSERT_HEAD(&softc->pending_ccbs,
1474 					 &start_ccb->ccb_h, periph_links.le);
1475 			splx(oldspl);
1476 
1477 			/* We expect a unit attention from this device */
1478 			if ((softc->flags & CD_FLAG_RETRY_UA) != 0) {
1479 				start_ccb->ccb_h.ccb_state |= CD_CCB_RETRY_UA;
1480 				softc->flags &= ~CD_FLAG_RETRY_UA;
1481 			}
1482 
1483 			start_ccb->ccb_h.ccb_bp = bp;
1484 			bp = bioq_first(&softc->bio_queue);
1485 			splx(s);
1486 
1487 			xpt_action(start_ccb);
1488 		}
1489 		if (bp != NULL) {
1490 			/* Have more work to do, so ensure we stay scheduled */
1491 			xpt_schedule(periph, /* XXX priority */1);
1492 		}
1493 		break;
1494 	}
1495 	case CD_STATE_PROBE:
1496 	{
1497 
1498 		rcap = (struct scsi_read_capacity_data *)malloc(sizeof(*rcap),
1499 								M_TEMP,
1500 								M_NOWAIT);
1501 		if (rcap == NULL) {
1502 			xpt_print_path(periph->path);
1503 			printf("cdstart: Couldn't malloc read_capacity data\n");
1504 			/* cd_free_periph??? */
1505 			break;
1506 		}
1507 		csio = &start_ccb->csio;
1508 		scsi_read_capacity(csio,
1509 				   /*retries*/1,
1510 				   cddone,
1511 				   MSG_SIMPLE_Q_TAG,
1512 				   rcap,
1513 				   SSD_FULL_SIZE,
1514 				   /*timeout*/20000);
1515 		start_ccb->ccb_h.ccb_bp = NULL;
1516 		start_ccb->ccb_h.ccb_state = CD_CCB_PROBE;
1517 		xpt_action(start_ccb);
1518 		break;
1519 	}
1520 	}
1521 }
1522 
1523 static void
1524 cddone(struct cam_periph *periph, union ccb *done_ccb)
1525 {
1526 	struct cd_softc *softc;
1527 	struct ccb_scsiio *csio;
1528 
1529 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cddone\n"));
1530 
1531 	softc = (struct cd_softc *)periph->softc;
1532 	csio = &done_ccb->csio;
1533 
1534 	switch (csio->ccb_h.ccb_state & CD_CCB_TYPE_MASK) {
1535 	case CD_CCB_BUFFER_IO:
1536 	{
1537 		struct bio	*bp;
1538 		int		error;
1539 		int		oldspl;
1540 
1541 		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
1542 		error = 0;
1543 
1544 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1545 			int sf;
1546 
1547 			if ((done_ccb->ccb_h.ccb_state & CD_CCB_RETRY_UA) != 0)
1548 				sf = SF_RETRY_UA;
1549 			else
1550 				sf = 0;
1551 
1552 			error = cderror(done_ccb, CAM_RETRY_SELTO, sf);
1553 			if (error == ERESTART) {
1554 				/*
1555 				 * A retry was scheuled, so
1556 				 * just return.
1557 				 */
1558 				return;
1559 			}
1560 		}
1561 
1562 		if (error != 0) {
1563 			int s;
1564 			struct bio *q_bp;
1565 
1566 			xpt_print_path(periph->path);
1567 			printf("cddone: got error %#x back\n", error);
1568 			s = splbio();
1569 			while ((q_bp = bioq_first(&softc->bio_queue)) != NULL) {
1570 				bioq_remove(&softc->bio_queue, q_bp);
1571 				q_bp->bio_resid = q_bp->bio_bcount;
1572 				biofinish(q_bp, NULL, EIO);
1573 			}
1574 			splx(s);
1575 			bp->bio_resid = bp->bio_bcount;
1576 			bp->bio_error = error;
1577 			bp->bio_flags |= BIO_ERROR;
1578 			cam_release_devq(done_ccb->ccb_h.path,
1579 					 /*relsim_flags*/0,
1580 					 /*reduction*/0,
1581 					 /*timeout*/0,
1582 					 /*getcount_only*/0);
1583 
1584 		} else {
1585 			bp->bio_resid = csio->resid;
1586 			bp->bio_error = 0;
1587 			if (bp->bio_resid != 0) {
1588 				/* Short transfer ??? */
1589 				bp->bio_flags |= BIO_ERROR;
1590 			}
1591 		}
1592 
1593 		/*
1594 		 * Block out any asyncronous callbacks
1595 		 * while we touch the pending ccb list.
1596 		 */
1597 		oldspl = splcam();
1598 		LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
1599 		splx(oldspl);
1600 
1601 		if (softc->flags & CD_FLAG_CHANGER)
1602 			cdchangerschedule(softc);
1603 
1604 		biofinish(bp, &softc->device_stats, 0);
1605 		break;
1606 	}
1607 	case CD_CCB_PROBE:
1608 	{
1609 		struct	   scsi_read_capacity_data *rdcap;
1610 		char	   announce_buf[120]; /*
1611 					       * Currently (9/30/97) the
1612 					       * longest possible announce
1613 					       * buffer is 108 bytes, for the
1614 					       * first error case below.
1615 					       * That is 39 bytes for the
1616 					       * basic string, 16 bytes for the
1617 					       * biggest sense key (hardware
1618 					       * error), 52 bytes for the
1619 					       * text of the largest sense
1620 					       * qualifier valid for a CDROM,
1621 					       * (0x72, 0x03 or 0x04,
1622 					       * 0x03), and one byte for the
1623 					       * null terminating character.
1624 					       * To allow for longer strings,
1625 					       * the announce buffer is 120
1626 					       * bytes.
1627 					       */
1628 		struct	   cd_params *cdp;
1629 
1630 		cdp = &softc->params;
1631 
1632 		rdcap = (struct scsi_read_capacity_data *)csio->data_ptr;
1633 
1634 		cdp->disksize = scsi_4btoul (rdcap->addr) + 1;
1635 		cdp->blksize = scsi_4btoul (rdcap->length);
1636 
1637 		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1638 
1639 			snprintf(announce_buf, sizeof(announce_buf),
1640 				"cd present [%lu x %lu byte records]",
1641 				cdp->disksize, (u_long)cdp->blksize);
1642 
1643 		} else {
1644 			int	error;
1645 			/*
1646 			 * Retry any UNIT ATTENTION type errors.  They
1647 			 * are expected at boot.
1648 			 */
1649 			error = cderror(done_ccb, CAM_RETRY_SELTO,
1650 					SF_RETRY_UA | SF_NO_PRINT);
1651 			if (error == ERESTART) {
1652 				/*
1653 				 * A retry was scheuled, so
1654 				 * just return.
1655 				 */
1656 				return;
1657 			} else if (error != 0) {
1658 
1659 				struct scsi_sense_data *sense;
1660 				int asc, ascq;
1661 				int sense_key, error_code;
1662 				int have_sense;
1663 				cam_status status;
1664 				struct ccb_getdev cgd;
1665 
1666 				/* Don't wedge this device's queue */
1667 				cam_release_devq(done_ccb->ccb_h.path,
1668 						 /*relsim_flags*/0,
1669 						 /*reduction*/0,
1670 						 /*timeout*/0,
1671 						 /*getcount_only*/0);
1672 
1673 				status = done_ccb->ccb_h.status;
1674 
1675 				xpt_setup_ccb(&cgd.ccb_h,
1676 					      done_ccb->ccb_h.path,
1677 					      /* priority */ 1);
1678 				cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1679 				xpt_action((union ccb *)&cgd);
1680 
1681 				if (((csio->ccb_h.flags & CAM_SENSE_PHYS) != 0)
1682 				 || ((csio->ccb_h.flags & CAM_SENSE_PTR) != 0)
1683 				 || ((status & CAM_AUTOSNS_VALID) == 0))
1684 					have_sense = FALSE;
1685 				else
1686 					have_sense = TRUE;
1687 
1688 				if (have_sense) {
1689 					sense = &csio->sense_data;
1690 					scsi_extract_sense(sense, &error_code,
1691 							   &sense_key,
1692 							   &asc, &ascq);
1693 				}
1694 				/*
1695 				 * Attach to anything that claims to be a
1696 				 * CDROM or WORM device, as long as it
1697 				 * doesn't return a "Logical unit not
1698 				 * supported" (0x25) error.
1699 				 */
1700 				if ((have_sense) && (asc != 0x25)
1701 				 && (error_code == SSD_CURRENT_ERROR)) {
1702 					const char *sense_key_desc;
1703 					const char *asc_desc;
1704 
1705 					scsi_sense_desc(sense_key, asc, ascq,
1706 							&cgd.inq_data,
1707 							&sense_key_desc,
1708 							&asc_desc);
1709 					snprintf(announce_buf,
1710 					    sizeof(announce_buf),
1711 						"Attempt to query device "
1712 						"size failed: %s, %s",
1713 						sense_key_desc,
1714 						asc_desc);
1715 				} else if (SID_TYPE(&cgd.inq_data) == T_CDROM) {
1716 					/*
1717 					 * We only print out an error for
1718 					 * CDROM type devices.  For WORM
1719 					 * devices, we don't print out an
1720 					 * error since a few WORM devices
1721 					 * don't support CDROM commands.
1722 					 * If we have sense information, go
1723 					 * ahead and print it out.
1724 					 * Otherwise, just say that we
1725 					 * couldn't attach.
1726 					 */
1727 
1728 					/*
1729 					 * Just print out the error, not
1730 					 * the full probe message, when we
1731 					 * don't attach.
1732 					 */
1733 					if (have_sense)
1734 						scsi_sense_print(
1735 							&done_ccb->csio);
1736 					else {
1737 						xpt_print_path(periph->path);
1738 						printf("got CAM status %#x\n",
1739 						       done_ccb->ccb_h.status);
1740 					}
1741 					xpt_print_path(periph->path);
1742 					printf("fatal error, failed"
1743 					       " to attach to device\n");
1744 
1745 					/*
1746 					 * Invalidate this peripheral.
1747 					 */
1748 					cam_periph_invalidate(periph);
1749 
1750 					announce_buf[0] = '\0';
1751 				} else {
1752 
1753 					/*
1754 					 * Invalidate this peripheral.
1755 					 */
1756 					cam_periph_invalidate(periph);
1757 					announce_buf[0] = '\0';
1758 				}
1759 			}
1760 		}
1761 		free(rdcap, M_TEMP);
1762 		if (announce_buf[0] != '\0') {
1763 			xpt_announce_periph(periph, announce_buf);
1764 			if (softc->flags & CD_FLAG_CHANGER)
1765 				cdchangerschedule(softc);
1766 		}
1767 		softc->state = CD_STATE_NORMAL;
1768 		/*
1769 		 * Since our peripheral may be invalidated by an error
1770 		 * above or an external event, we must release our CCB
1771 		 * before releasing the probe lock on the peripheral.
1772 		 * The peripheral will only go away once the last lock
1773 		 * is removed, and we need it around for the CCB release
1774 		 * operation.
1775 		 */
1776 		xpt_release_ccb(done_ccb);
1777 		cam_periph_unlock(periph);
1778 		return;
1779 	}
1780 	case CD_CCB_WAITING:
1781 	{
1782 		/* Caller will release the CCB */
1783 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1784 			  ("trying to wakeup ccbwait\n"));
1785 
1786 		wakeup(&done_ccb->ccb_h.cbfcnp);
1787 		return;
1788 	}
1789 	default:
1790 		break;
1791 	}
1792 	xpt_release_ccb(done_ccb);
1793 }
1794 
1795 static int
1796 cdioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
1797 {
1798 
1799 	struct 	cam_periph *periph;
1800 	struct	cd_softc *softc;
1801 	int	error, unit;
1802 
1803 	unit = dkunit(dev);
1804 
1805 	periph = cam_extend_get(cdperiphs, unit);
1806 	if (periph == NULL)
1807 		return(ENXIO);
1808 
1809 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdioctl\n"));
1810 
1811 	softc = (struct cd_softc *)periph->softc;
1812 
1813 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1814 		  ("trying to do ioctl %#lx\n", cmd));
1815 
1816 	error = cam_periph_lock(periph, PRIBIO | PCATCH);
1817 
1818 	if (error != 0)
1819 		return(error);
1820 
1821 	switch (cmd) {
1822 
1823 	case CDIOCPLAYTRACKS:
1824 		{
1825 			struct ioc_play_track *args
1826 			    = (struct ioc_play_track *) addr;
1827 			struct cd_mode_data *data;
1828 
1829 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
1830 				      M_WAITOK);
1831 
1832 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1833 				  ("trying to do CDIOCPLAYTRACKS\n"));
1834 
1835 			error = cdgetmode(periph, data, AUDIO_PAGE);
1836 			if (error) {
1837 				free(data, M_TEMP);
1838 				break;
1839 			}
1840 			data->page.audio.flags &= ~CD_PA_SOTC;
1841 			data->page.audio.flags |= CD_PA_IMMED;
1842 			error = cdsetmode(periph, data);
1843 			free(data, M_TEMP);
1844 			if (error)
1845 				break;
1846 			if (softc->quirks & CD_Q_BCD_TRACKS) {
1847 				args->start_track = bin2bcd(args->start_track);
1848 				args->end_track = bin2bcd(args->end_track);
1849 			}
1850 			error = cdplaytracks(periph,
1851 					     args->start_track,
1852 					     args->start_index,
1853 					     args->end_track,
1854 					     args->end_index);
1855 		}
1856 		break;
1857 	case CDIOCPLAYMSF:
1858 		{
1859 			struct ioc_play_msf *args
1860 				= (struct ioc_play_msf *) addr;
1861 			struct cd_mode_data *data;
1862 
1863 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
1864 				      M_WAITOK);
1865 
1866 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1867 				  ("trying to do CDIOCPLAYMSF\n"));
1868 
1869 			error = cdgetmode(periph, data, AUDIO_PAGE);
1870 			if (error) {
1871 				free(data, M_TEMP);
1872 				break;
1873 			}
1874 			data->page.audio.flags &= ~CD_PA_SOTC;
1875 			data->page.audio.flags |= CD_PA_IMMED;
1876 			error = cdsetmode(periph, data);
1877 			free(data, M_TEMP);
1878 			if (error)
1879 				break;
1880 			error = cdplaymsf(periph,
1881 					  args->start_m,
1882 					  args->start_s,
1883 					  args->start_f,
1884 					  args->end_m,
1885 					  args->end_s,
1886 					  args->end_f);
1887 		}
1888 		break;
1889 	case CDIOCPLAYBLOCKS:
1890 		{
1891 			struct ioc_play_blocks *args
1892 				= (struct ioc_play_blocks *) addr;
1893 			struct cd_mode_data *data;
1894 
1895 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1896 				  ("trying to do CDIOCPLAYBLOCKS\n"));
1897 
1898 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
1899 				      M_WAITOK);
1900 
1901 			error = cdgetmode(periph, data, AUDIO_PAGE);
1902 			if (error) {
1903 				free(data, M_TEMP);
1904 				break;
1905 			}
1906 			data->page.audio.flags &= ~CD_PA_SOTC;
1907 			data->page.audio.flags |= CD_PA_IMMED;
1908 			error = cdsetmode(periph, data);
1909 			free(data, M_TEMP);
1910 			if (error)
1911 				break;
1912 			error = cdplay(periph, args->blk, args->len);
1913 		}
1914 		break;
1915 	case CDIOCREADSUBCHANNEL:
1916 		{
1917 			struct ioc_read_subchannel *args
1918 				= (struct ioc_read_subchannel *) addr;
1919 			struct cd_sub_channel_info *data;
1920 			u_int32_t len = args->data_len;
1921 
1922 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1923 				  ("trying to do CDIOCREADSUBCHANNEL\n"));
1924 
1925 			data = malloc(sizeof(struct cd_sub_channel_info),
1926 				      M_TEMP, M_WAITOK);
1927 
1928 			if ((len > sizeof(struct cd_sub_channel_info)) ||
1929 			    (len < sizeof(struct cd_sub_channel_header))) {
1930 				printf(
1931 					"scsi_cd: cdioctl: "
1932 					"cdioreadsubchannel: error, len=%d\n",
1933 					len);
1934 				error = EINVAL;
1935 				free(data, M_TEMP);
1936 				break;
1937 			}
1938 
1939 			if (softc->quirks & CD_Q_BCD_TRACKS)
1940 				args->track = bin2bcd(args->track);
1941 
1942 			error = cdreadsubchannel(periph, args->address_format,
1943 				args->data_format, args->track, data, len);
1944 
1945 			if (error) {
1946 				free(data, M_TEMP);
1947 	 			break;
1948 			}
1949 			if (softc->quirks & CD_Q_BCD_TRACKS)
1950 				data->what.track_info.track_number =
1951 				    bcd2bin(data->what.track_info.track_number);
1952 			len = min(len, ((data->header.data_len[0] << 8) +
1953 				data->header.data_len[1] +
1954 				sizeof(struct cd_sub_channel_header)));
1955 			if (copyout(data, args->data, len) != 0) {
1956 				error = EFAULT;
1957 			}
1958 			free(data, M_TEMP);
1959 		}
1960 		break;
1961 
1962 	case CDIOREADTOCHEADER:
1963 		{
1964 			struct ioc_toc_header *th;
1965 
1966 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1967 				  ("trying to do CDIOREADTOCHEADER\n"));
1968 
1969 			th = malloc(sizeof(struct ioc_toc_header), M_TEMP,
1970 				    M_WAITOK);
1971 			error = cdreadtoc(periph, 0, 0,
1972 					  (struct cd_toc_entry *)th,
1973 				          sizeof (*th));
1974 			if (error) {
1975 				free(th, M_TEMP);
1976 				break;
1977 			}
1978 			if (softc->quirks & CD_Q_BCD_TRACKS) {
1979 				/* we are going to have to convert the BCD
1980 				 * encoding on the cd to what is expected
1981 				 */
1982 				th->starting_track =
1983 					bcd2bin(th->starting_track);
1984 				th->ending_track = bcd2bin(th->ending_track);
1985 			}
1986 			NTOHS(th->len);
1987 			bcopy(th, addr, sizeof(*th));
1988 			free(th, M_TEMP);
1989 		}
1990 		break;
1991 	case CDIOREADTOCENTRYS:
1992 		{
1993 			typedef struct {
1994 				struct ioc_toc_header header;
1995 				struct cd_toc_entry entries[100];
1996 			} data_t;
1997 			typedef struct {
1998 				struct ioc_toc_header header;
1999 				struct cd_toc_entry entry;
2000 			} lead_t;
2001 
2002 			data_t *data;
2003 			lead_t *lead;
2004 			struct ioc_read_toc_entry *te =
2005 				(struct ioc_read_toc_entry *) addr;
2006 			struct ioc_toc_header *th;
2007 			u_int32_t len, readlen, idx, num;
2008 			u_int32_t starting_track = te->starting_track;
2009 
2010 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2011 				  ("trying to do CDIOREADTOCENTRYS\n"));
2012 
2013 			data = malloc(sizeof(data_t), M_TEMP, M_WAITOK);
2014 			lead = malloc(sizeof(lead_t), M_TEMP, M_WAITOK);
2015 
2016 			if (te->data_len < sizeof(struct cd_toc_entry)
2017 			 || (te->data_len % sizeof(struct cd_toc_entry)) != 0
2018 			 || (te->address_format != CD_MSF_FORMAT
2019 			  && te->address_format != CD_LBA_FORMAT)) {
2020 				error = EINVAL;
2021 				printf("scsi_cd: error in readtocentries, "
2022 				       "returning EINVAL\n");
2023 				free(data, M_TEMP);
2024 				free(lead, M_TEMP);
2025 				break;
2026 			}
2027 
2028 			th = &data->header;
2029 			error = cdreadtoc(periph, 0, 0,
2030 					  (struct cd_toc_entry *)th,
2031 					  sizeof (*th));
2032 			if (error) {
2033 				free(data, M_TEMP);
2034 				free(lead, M_TEMP);
2035 				break;
2036 			}
2037 
2038 			if (softc->quirks & CD_Q_BCD_TRACKS) {
2039 				/* we are going to have to convert the BCD
2040 				 * encoding on the cd to what is expected
2041 				 */
2042 				th->starting_track =
2043 				    bcd2bin(th->starting_track);
2044 				th->ending_track = bcd2bin(th->ending_track);
2045 			}
2046 
2047 			if (starting_track == 0)
2048 				starting_track = th->starting_track;
2049 			else if (starting_track == LEADOUT)
2050 				starting_track = th->ending_track + 1;
2051 			else if (starting_track < th->starting_track ||
2052 				 starting_track > th->ending_track + 1) {
2053 				printf("scsi_cd: error in readtocentries, "
2054 				       "returning EINVAL\n");
2055 				free(data, M_TEMP);
2056 				free(lead, M_TEMP);
2057 				error = EINVAL;
2058 				break;
2059 			}
2060 
2061 			/* calculate reading length without leadout entry */
2062 			readlen = (th->ending_track - starting_track + 1) *
2063 				  sizeof(struct cd_toc_entry);
2064 
2065 			/* and with leadout entry */
2066 			len = readlen + sizeof(struct cd_toc_entry);
2067 			if (te->data_len < len) {
2068 				len = te->data_len;
2069 				if (readlen > len)
2070 					readlen = len;
2071 			}
2072 			if (len > sizeof(data->entries)) {
2073 				printf("scsi_cd: error in readtocentries, "
2074 				       "returning EINVAL\n");
2075 				error = EINVAL;
2076 				free(data, M_TEMP);
2077 				free(lead, M_TEMP);
2078 				break;
2079 			}
2080 			num = len / sizeof(struct cd_toc_entry);
2081 
2082 			if (readlen > 0) {
2083 				error = cdreadtoc(periph, te->address_format,
2084 						  starting_track,
2085 						  (struct cd_toc_entry *)data,
2086 						  readlen + sizeof (*th));
2087 				if (error) {
2088 					free(data, M_TEMP);
2089 					free(lead, M_TEMP);
2090 					break;
2091 				}
2092 			}
2093 
2094 			/* make leadout entry if needed */
2095 			idx = starting_track + num - 1;
2096 			if (softc->quirks & CD_Q_BCD_TRACKS)
2097 				th->ending_track = bcd2bin(th->ending_track);
2098 			if (idx == th->ending_track + 1) {
2099 				error = cdreadtoc(periph, te->address_format,
2100 						  LEADOUT,
2101 						  (struct cd_toc_entry *)lead,
2102 						  sizeof(*lead));
2103 				if (error) {
2104 					free(data, M_TEMP);
2105 					free(lead, M_TEMP);
2106 					break;
2107 				}
2108 				data->entries[idx - starting_track] =
2109 					lead->entry;
2110 			}
2111 			if (softc->quirks & CD_Q_BCD_TRACKS) {
2112 				for (idx = 0; idx < num - 1; idx++) {
2113 					data->entries[idx].track =
2114 					    bcd2bin(data->entries[idx].track);
2115 				}
2116 			}
2117 
2118 			error = copyout(data->entries, te->data, len);
2119 			free(data, M_TEMP);
2120 			free(lead, M_TEMP);
2121 		}
2122 		break;
2123 	case CDIOREADTOCENTRY:
2124 		{
2125 			/* yeah yeah, this is ugly */
2126 			typedef struct {
2127 				struct ioc_toc_header header;
2128 				struct cd_toc_entry entry;
2129 			} data_t;
2130 
2131 			data_t *data;
2132 			struct ioc_read_toc_single_entry *te =
2133 				(struct ioc_read_toc_single_entry *) addr;
2134 			struct ioc_toc_header *th;
2135 			u_int32_t track;
2136 
2137 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2138 				  ("trying to do CDIOREADTOCENTRY\n"));
2139 
2140 			data = malloc(sizeof(data_t), M_TEMP, M_WAITOK);
2141 
2142 			if (te->address_format != CD_MSF_FORMAT
2143 			    && te->address_format != CD_LBA_FORMAT) {
2144 				printf("error in readtocentry, "
2145 				       " returning EINVAL\n");
2146 				free(data, M_TEMP);
2147 				error = EINVAL;
2148 				break;
2149 			}
2150 
2151 			th = &data->header;
2152 			error = cdreadtoc(periph, 0, 0,
2153 					  (struct cd_toc_entry *)th,
2154 					  sizeof (*th));
2155 			if (error) {
2156 				free(data, M_TEMP);
2157 				break;
2158 			}
2159 
2160 			if (softc->quirks & CD_Q_BCD_TRACKS) {
2161 				/* we are going to have to convert the BCD
2162 				 * encoding on the cd to what is expected
2163 				 */
2164 				th->starting_track =
2165 				    bcd2bin(th->starting_track);
2166 				th->ending_track = bcd2bin(th->ending_track);
2167 			}
2168 			track = te->track;
2169 			if (track == 0)
2170 				track = th->starting_track;
2171 			else if (track == LEADOUT)
2172 				/* OK */;
2173 			else if (track < th->starting_track ||
2174 				 track > th->ending_track + 1) {
2175 				printf("error in readtocentry, "
2176 				       " returning EINVAL\n");
2177 				free(data, M_TEMP);
2178 				error = EINVAL;
2179 				break;
2180 			}
2181 
2182 			error = cdreadtoc(periph, te->address_format, track,
2183 					  (struct cd_toc_entry *)data,
2184 					  sizeof(data_t));
2185 			if (error) {
2186 				free(data, M_TEMP);
2187 				break;
2188 			}
2189 
2190 			if (softc->quirks & CD_Q_BCD_TRACKS)
2191 				data->entry.track = bcd2bin(data->entry.track);
2192 			bcopy(&data->entry, &te->entry,
2193 			      sizeof(struct cd_toc_entry));
2194 			free(data, M_TEMP);
2195 		}
2196 		break;
2197 	case CDIOCSETPATCH:
2198 		{
2199 			struct ioc_patch *arg = (struct ioc_patch *) addr;
2200 			struct cd_mode_data *data;
2201 
2202 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2203 				  ("trying to do CDIOCSETPATCH\n"));
2204 
2205 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2206 				      M_WAITOK);
2207 			error = cdgetmode(periph, data, AUDIO_PAGE);
2208 			if (error) {
2209 				free(data, M_TEMP);
2210 				break;
2211 			}
2212 			data->page.audio.port[LEFT_PORT].channels =
2213 				arg->patch[0];
2214 			data->page.audio.port[RIGHT_PORT].channels =
2215 				arg->patch[1];
2216 			data->page.audio.port[2].channels = arg->patch[2];
2217 			data->page.audio.port[3].channels = arg->patch[3];
2218 			error = cdsetmode(periph, data);
2219 			free(data, M_TEMP);
2220 		}
2221 		break;
2222 	case CDIOCGETVOL:
2223 		{
2224 			struct ioc_vol *arg = (struct ioc_vol *) addr;
2225 			struct cd_mode_data *data;
2226 
2227 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2228 				  ("trying to do CDIOCGETVOL\n"));
2229 
2230 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2231 				      M_WAITOK);
2232 			error = cdgetmode(periph, data, AUDIO_PAGE);
2233 			if (error) {
2234 				free(data, M_TEMP);
2235 				break;
2236 			}
2237 			arg->vol[LEFT_PORT] =
2238 				data->page.audio.port[LEFT_PORT].volume;
2239 			arg->vol[RIGHT_PORT] =
2240 				data->page.audio.port[RIGHT_PORT].volume;
2241 			arg->vol[2] = data->page.audio.port[2].volume;
2242 			arg->vol[3] = data->page.audio.port[3].volume;
2243 			free(data, M_TEMP);
2244 		}
2245 		break;
2246 	case CDIOCSETVOL:
2247 		{
2248 			struct ioc_vol *arg = (struct ioc_vol *) addr;
2249 			struct cd_mode_data *data;
2250 
2251 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2252 				  ("trying to do CDIOCSETVOL\n"));
2253 
2254 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2255 				      M_WAITOK);
2256 			error = cdgetmode(periph, data, AUDIO_PAGE);
2257 			if (error) {
2258 				free(data, M_TEMP);
2259 				break;
2260 			}
2261 			data->page.audio.port[LEFT_PORT].channels = CHANNEL_0;
2262 			data->page.audio.port[LEFT_PORT].volume =
2263 				arg->vol[LEFT_PORT];
2264 			data->page.audio.port[RIGHT_PORT].channels = CHANNEL_1;
2265 			data->page.audio.port[RIGHT_PORT].volume =
2266 				arg->vol[RIGHT_PORT];
2267 			data->page.audio.port[2].volume = arg->vol[2];
2268 			data->page.audio.port[3].volume = arg->vol[3];
2269 			error = cdsetmode(periph, data);
2270 			free(data, M_TEMP);
2271 		}
2272 		break;
2273 	case CDIOCSETMONO:
2274 		{
2275 			struct cd_mode_data *data;
2276 
2277 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2278 				  ("trying to do CDIOCSETMONO\n"));
2279 
2280 			data = malloc(sizeof(struct cd_mode_data),
2281 				      M_TEMP, M_WAITOK);
2282 			error = cdgetmode(periph, data, AUDIO_PAGE);
2283 			if (error) {
2284 				free(data, M_TEMP);
2285 				break;
2286 			}
2287 			data->page.audio.port[LEFT_PORT].channels =
2288 				LEFT_CHANNEL | RIGHT_CHANNEL;
2289 			data->page.audio.port[RIGHT_PORT].channels =
2290 				LEFT_CHANNEL | RIGHT_CHANNEL;
2291 			data->page.audio.port[2].channels = 0;
2292 			data->page.audio.port[3].channels = 0;
2293 			error = cdsetmode(periph, data);
2294 			free(data, M_TEMP);
2295 		}
2296 		break;
2297 	case CDIOCSETSTEREO:
2298 		{
2299 			struct cd_mode_data *data;
2300 
2301 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2302 				  ("trying to do CDIOCSETSTEREO\n"));
2303 
2304 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2305 				      M_WAITOK);
2306 			error = cdgetmode(periph, data, AUDIO_PAGE);
2307 			if (error) {
2308 				free(data, M_TEMP);
2309 				break;
2310 			}
2311 			data->page.audio.port[LEFT_PORT].channels =
2312 				LEFT_CHANNEL;
2313 			data->page.audio.port[RIGHT_PORT].channels =
2314 				RIGHT_CHANNEL;
2315 			data->page.audio.port[2].channels = 0;
2316 			data->page.audio.port[3].channels = 0;
2317 			error = cdsetmode(periph, data);
2318 			free(data, M_TEMP);
2319 		}
2320 		break;
2321 	case CDIOCSETMUTE:
2322 		{
2323 			struct cd_mode_data *data;
2324 
2325 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2326 				  ("trying to do CDIOCSETMUTE\n"));
2327 
2328 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2329 				      M_WAITOK);
2330 			error = cdgetmode(periph, data, AUDIO_PAGE);
2331 			if (error) {
2332 				free(data, M_TEMP);
2333 				break;
2334 			}
2335 			data->page.audio.port[LEFT_PORT].channels = 0;
2336 			data->page.audio.port[RIGHT_PORT].channels = 0;
2337 			data->page.audio.port[2].channels = 0;
2338 			data->page.audio.port[3].channels = 0;
2339 			error = cdsetmode(periph, data);
2340 			free(data, M_TEMP);
2341 		}
2342 		break;
2343 	case CDIOCSETLEFT:
2344 		{
2345 			struct cd_mode_data *data;
2346 
2347 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2348 				  ("trying to do CDIOCSETLEFT\n"));
2349 
2350 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2351 				      M_WAITOK);
2352 			error = cdgetmode(periph, data, AUDIO_PAGE);
2353 			if (error) {
2354 				free(data, M_TEMP);
2355 				break;
2356 			}
2357 			data->page.audio.port[LEFT_PORT].channels =
2358 				LEFT_CHANNEL;
2359 			data->page.audio.port[RIGHT_PORT].channels =
2360 				LEFT_CHANNEL;
2361 			data->page.audio.port[2].channels = 0;
2362 			data->page.audio.port[3].channels = 0;
2363 			error = cdsetmode(periph, data);
2364 			free(data, M_TEMP);
2365 		}
2366 		break;
2367 	case CDIOCSETRIGHT:
2368 		{
2369 			struct cd_mode_data *data;
2370 
2371 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2372 				  ("trying to do CDIOCSETRIGHT\n"));
2373 
2374 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2375 				      M_WAITOK);
2376 			error = cdgetmode(periph, data, AUDIO_PAGE);
2377 			if (error) {
2378 				free(data, M_TEMP);
2379 				break;
2380 			}
2381 			data->page.audio.port[LEFT_PORT].channels =
2382 				RIGHT_CHANNEL;
2383 			data->page.audio.port[RIGHT_PORT].channels =
2384 				RIGHT_CHANNEL;
2385 			data->page.audio.port[2].channels = 0;
2386 			data->page.audio.port[3].channels = 0;
2387 			error = cdsetmode(periph, data);
2388 			free(data, M_TEMP);
2389 		}
2390 		break;
2391 	case CDIOCRESUME:
2392 		error = cdpause(periph, 1);
2393 		break;
2394 	case CDIOCPAUSE:
2395 		error = cdpause(periph, 0);
2396 		break;
2397 	case CDIOCSTART:
2398 		error = cdstartunit(periph);
2399 		break;
2400 	case CDIOCSTOP:
2401 		error = cdstopunit(periph, 0);
2402 		break;
2403 	case CDIOCEJECT:
2404 		error = cdstopunit(periph, 1);
2405 		break;
2406 	case CDIOCALLOW:
2407 		cdprevent(periph, PR_ALLOW);
2408 		break;
2409 	case CDIOCPREVENT:
2410 		cdprevent(periph, PR_PREVENT);
2411 		break;
2412 	case CDIOCSETDEBUG:
2413 		/* sc_link->flags |= (SDEV_DB1 | SDEV_DB2); */
2414 		error = ENOTTY;
2415 		break;
2416 	case CDIOCCLRDEBUG:
2417 		/* sc_link->flags &= ~(SDEV_DB1 | SDEV_DB2); */
2418 		error = ENOTTY;
2419 		break;
2420 	case CDIOCRESET:
2421 		/* return (cd_reset(periph)); */
2422 		error = ENOTTY;
2423 		break;
2424 	case DVDIOCSENDKEY:
2425 	case DVDIOCREPORTKEY: {
2426 		struct dvd_authinfo *authinfo;
2427 
2428 		authinfo = (struct dvd_authinfo *)addr;
2429 
2430 		if (cmd == DVDIOCREPORTKEY)
2431 			error = cdreportkey(periph, authinfo);
2432 		else
2433 			error = cdsendkey(periph, authinfo);
2434 		break;
2435 	}
2436 	case DVDIOCREADSTRUCTURE: {
2437 		struct dvd_struct *dvdstruct;
2438 
2439 		dvdstruct = (struct dvd_struct *)addr;
2440 
2441 		error = cdreaddvdstructure(periph, dvdstruct);
2442 
2443 		break;
2444 	}
2445 	default:
2446 		error = cam_periph_ioctl(periph, cmd, addr, cderror);
2447 		break;
2448 	}
2449 
2450 	cam_periph_unlock(periph);
2451 
2452 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdioctl\n"));
2453 
2454 	return (error);
2455 }
2456 
2457 static void
2458 cdprevent(struct cam_periph *periph, int action)
2459 {
2460 	union	ccb *ccb;
2461 	struct	cd_softc *softc;
2462 	int	error;
2463 
2464 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdprevent\n"));
2465 
2466 	softc = (struct cd_softc *)periph->softc;
2467 
2468 	if (((action == PR_ALLOW)
2469 	  && (softc->flags & CD_FLAG_DISC_LOCKED) == 0)
2470 	 || ((action == PR_PREVENT)
2471 	  && (softc->flags & CD_FLAG_DISC_LOCKED) != 0)) {
2472 		return;
2473 	}
2474 
2475 	ccb = cdgetccb(periph, /* priority */ 1);
2476 
2477 	scsi_prevent(&ccb->csio,
2478 		     /*retries*/ 1,
2479 		     cddone,
2480 		     MSG_SIMPLE_Q_TAG,
2481 		     action,
2482 		     SSD_FULL_SIZE,
2483 		     /* timeout */60000);
2484 
2485 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2486 			/*sense_flags*/SF_RETRY_UA|SF_NO_PRINT);
2487 
2488 	xpt_release_ccb(ccb);
2489 
2490 	if (error == 0) {
2491 		if (action == PR_ALLOW)
2492 			softc->flags &= ~CD_FLAG_DISC_LOCKED;
2493 		else
2494 			softc->flags |= CD_FLAG_DISC_LOCKED;
2495 	}
2496 }
2497 
2498 static int
2499 cdsize(dev_t dev, u_int32_t *size)
2500 {
2501 	struct cam_periph *periph;
2502 	struct cd_softc *softc;
2503 	union ccb *ccb;
2504 	struct scsi_read_capacity_data *rcap_buf;
2505 	int error;
2506 
2507 	periph = cam_extend_get(cdperiphs, dkunit(dev));
2508 
2509 	if (periph == NULL)
2510 		return (ENXIO);
2511 
2512 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdsize\n"));
2513 
2514 	softc = (struct cd_softc *)periph->softc;
2515 
2516 	ccb = cdgetccb(periph, /* priority */ 1);
2517 
2518 	rcap_buf = malloc(sizeof(struct scsi_read_capacity_data),
2519 			  M_TEMP, M_WAITOK);
2520 
2521 	scsi_read_capacity(&ccb->csio,
2522 			   /*retries*/ 1,
2523 			   cddone,
2524 			   MSG_SIMPLE_Q_TAG,
2525 			   rcap_buf,
2526 			   SSD_FULL_SIZE,
2527 			   /* timeout */20000);
2528 
2529 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2530 			 /*sense_flags*/SF_RETRY_UA|SF_NO_PRINT);
2531 
2532 	xpt_release_ccb(ccb);
2533 
2534 	softc->params.disksize = scsi_4btoul(rcap_buf->addr) + 1;
2535 	softc->params.blksize  = scsi_4btoul(rcap_buf->length);
2536 	/*
2537 	 * SCSI-3 mandates that the reported blocksize shall be 2048.
2538 	 * Older drives sometimes report funny values, trim it down to
2539 	 * 2048, or other parts of the kernel will get confused.
2540 	 *
2541 	 * XXX we leave drives alone that might report 512 bytes, as
2542 	 * well as drives reporting more weird sizes like perhaps 4K.
2543 	 */
2544 	if (softc->params.blksize > 2048 && softc->params.blksize <= 2352)
2545 		softc->params.blksize = 2048;
2546 
2547 	free(rcap_buf, M_TEMP);
2548 	*size = softc->params.disksize;
2549 
2550 	return (error);
2551 
2552 }
2553 
2554 /*
2555  * The idea here is to try to figure out whether the first track is data or
2556  * audio.  If it is data, we can at least attempt to read a disklabel off
2557  * the first sector of the disk.  If it is audio, there won't be a
2558  * disklabel.
2559  *
2560  * This routine returns 0 if the first track is data, and non-zero if there
2561  * is an error or the first track is audio.  (If either non-zero case, we
2562  * should not attempt to read the disklabel.)
2563  */
2564 static int
2565 cdfirsttrackisdata(struct cam_periph *periph)
2566 {
2567 	struct cdtocdata {
2568 		struct ioc_toc_header header;
2569 		struct cd_toc_entry entries[100];
2570 	};
2571 	struct cd_softc *softc;
2572 	struct ioc_toc_header *th;
2573 	struct cdtocdata *data;
2574 	int num_entries, i;
2575 	int error, first_track_audio;
2576 
2577 	error = 0;
2578 	first_track_audio = -1;
2579 
2580 	softc = (struct cd_softc *)periph->softc;
2581 
2582 	data = malloc(sizeof(struct cdtocdata), M_TEMP, M_WAITOK);
2583 
2584 	th = &data->header;
2585 	error = cdreadtoc(periph, 0, 0, (struct cd_toc_entry *)data,
2586 			  sizeof(*data));
2587 
2588 	if (error)
2589 		goto bailout;
2590 
2591 	if (softc->quirks & CD_Q_BCD_TRACKS) {
2592 		/* we are going to have to convert the BCD
2593 		 * encoding on the cd to what is expected
2594 		 */
2595 		th->starting_track =
2596 		    bcd2bin(th->starting_track);
2597 		th->ending_track = bcd2bin(th->ending_track);
2598 	}
2599 	th->len = scsi_2btoul((u_int8_t *)&th->len);
2600 
2601 	if ((th->len - 2) > 0)
2602 		num_entries = (th->len - 2) / sizeof(struct cd_toc_entry);
2603 	else
2604 		num_entries = 0;
2605 
2606 	for (i = 0; i < num_entries; i++) {
2607 		if (data->entries[i].track == th->starting_track) {
2608 			if (data->entries[i].control & 0x4)
2609 				first_track_audio = 0;
2610 			else
2611 				first_track_audio = 1;
2612 			break;
2613 		}
2614 	}
2615 
2616 	if (first_track_audio == -1)
2617 		error = ENOENT;
2618 	else if (first_track_audio == 1)
2619 		error = EINVAL;
2620 	else
2621 		error = 0;
2622 bailout:
2623 	free(data, M_TEMP);
2624 
2625 	return(error);
2626 }
2627 
2628 static int
2629 cderror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
2630 {
2631 	struct cd_softc *softc;
2632 	struct cam_periph *periph;
2633 
2634 	periph = xpt_path_periph(ccb->ccb_h.path);
2635 	softc = (struct cd_softc *)periph->softc;
2636 
2637 	/*
2638 	 * XXX
2639 	 * Until we have a better way of doing pack validation,
2640 	 * don't treat UAs as errors.
2641 	 */
2642 	sense_flags |= SF_RETRY_UA;
2643 	return (cam_periph_error(ccb, cam_flags, sense_flags,
2644 				 &softc->saved_ccb));
2645 }
2646 
2647 /*
2648  * Read table of contents
2649  */
2650 static int
2651 cdreadtoc(struct cam_periph *periph, u_int32_t mode, u_int32_t start,
2652 	    struct cd_toc_entry *data, u_int32_t len)
2653 {
2654 	struct scsi_read_toc *scsi_cmd;
2655 	u_int32_t ntoc;
2656         struct ccb_scsiio *csio;
2657 	union ccb *ccb;
2658 	int error;
2659 
2660 	ntoc = len;
2661 	error = 0;
2662 
2663 	ccb = cdgetccb(periph, /* priority */ 1);
2664 
2665 	csio = &ccb->csio;
2666 
2667 	cam_fill_csio(csio,
2668 		      /* retries */ 1,
2669 		      /* cbfcnp */ cddone,
2670 		      /* flags */ CAM_DIR_IN,
2671 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2672 		      /* data_ptr */ (u_int8_t *)data,
2673 		      /* dxfer_len */ len,
2674 		      /* sense_len */ SSD_FULL_SIZE,
2675 		      sizeof(struct scsi_read_toc),
2676  		      /* timeout */ 50000);
2677 
2678 	scsi_cmd = (struct scsi_read_toc *)&csio->cdb_io.cdb_bytes;
2679 	bzero (scsi_cmd, sizeof(*scsi_cmd));
2680 
2681 	if (mode == CD_MSF_FORMAT)
2682 		scsi_cmd->byte2 |= CD_MSF;
2683 	scsi_cmd->from_track = start;
2684 	/* scsi_ulto2b(ntoc, (u_int8_t *)scsi_cmd->data_len); */
2685 	scsi_cmd->data_len[0] = (ntoc) >> 8;
2686 	scsi_cmd->data_len[1] = (ntoc) & 0xff;
2687 
2688 	scsi_cmd->op_code = READ_TOC;
2689 
2690 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2691 			 /*sense_flags*/SF_RETRY_UA);
2692 
2693 	xpt_release_ccb(ccb);
2694 
2695 	return(error);
2696 }
2697 
2698 static int
2699 cdreadsubchannel(struct cam_periph *periph, u_int32_t mode,
2700 		 u_int32_t format, int track,
2701 		 struct cd_sub_channel_info *data, u_int32_t len)
2702 {
2703 	struct scsi_read_subchannel *scsi_cmd;
2704         struct ccb_scsiio *csio;
2705 	union ccb *ccb;
2706 	int error;
2707 
2708 	error = 0;
2709 
2710 	ccb = cdgetccb(periph, /* priority */ 1);
2711 
2712 	csio = &ccb->csio;
2713 
2714 	cam_fill_csio(csio,
2715 		      /* retries */ 1,
2716 		      /* cbfcnp */ cddone,
2717 		      /* flags */ CAM_DIR_IN,
2718 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2719 		      /* data_ptr */ (u_int8_t *)data,
2720 		      /* dxfer_len */ len,
2721 		      /* sense_len */ SSD_FULL_SIZE,
2722 		      sizeof(struct scsi_read_subchannel),
2723  		      /* timeout */ 50000);
2724 
2725 	scsi_cmd = (struct scsi_read_subchannel *)&csio->cdb_io.cdb_bytes;
2726 	bzero (scsi_cmd, sizeof(*scsi_cmd));
2727 
2728 	scsi_cmd->op_code = READ_SUBCHANNEL;
2729 	if (mode == CD_MSF_FORMAT)
2730 		scsi_cmd->byte1 |= CD_MSF;
2731 	scsi_cmd->byte2 = SRS_SUBQ;
2732 	scsi_cmd->subchan_format = format;
2733 	scsi_cmd->track = track;
2734 	scsi_ulto2b(len, (u_int8_t *)scsi_cmd->data_len);
2735 	scsi_cmd->control = 0;
2736 
2737 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2738 			 /*sense_flags*/SF_RETRY_UA);
2739 
2740 	xpt_release_ccb(ccb);
2741 
2742 	return(error);
2743 }
2744 
2745 
2746 static int
2747 cdgetmode(struct cam_periph *periph, struct cd_mode_data *data, u_int32_t page)
2748 {
2749 	struct scsi_mode_sense_6 *scsi_cmd;
2750         struct ccb_scsiio *csio;
2751 	union ccb *ccb;
2752 	int error;
2753 
2754 	ccb = cdgetccb(periph, /* priority */ 1);
2755 
2756 	csio = &ccb->csio;
2757 
2758 	bzero(data, sizeof(*data));
2759 	cam_fill_csio(csio,
2760 		      /* retries */ 1,
2761 		      /* cbfcnp */ cddone,
2762 		      /* flags */ CAM_DIR_IN,
2763 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2764 		      /* data_ptr */ (u_int8_t *)data,
2765 		      /* dxfer_len */ sizeof(*data),
2766 		      /* sense_len */ SSD_FULL_SIZE,
2767 		      sizeof(struct scsi_mode_sense_6),
2768  		      /* timeout */ 50000);
2769 
2770 	scsi_cmd = (struct scsi_mode_sense_6 *)&csio->cdb_io.cdb_bytes;
2771 	bzero (scsi_cmd, sizeof(*scsi_cmd));
2772 
2773 	scsi_cmd->page = page;
2774 	scsi_cmd->length = sizeof(*data) & 0xff;
2775 	scsi_cmd->opcode = MODE_SENSE;
2776 
2777 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2778 			 /*sense_flags*/SF_RETRY_UA);
2779 
2780 	xpt_release_ccb(ccb);
2781 
2782 	return(error);
2783 }
2784 
2785 static int
2786 cdsetmode(struct cam_periph *periph, struct cd_mode_data *data)
2787 {
2788 	struct scsi_mode_select_6 *scsi_cmd;
2789         struct ccb_scsiio *csio;
2790 	union ccb *ccb;
2791 	int error;
2792 
2793 	ccb = cdgetccb(periph, /* priority */ 1);
2794 
2795 	csio = &ccb->csio;
2796 
2797 	error = 0;
2798 
2799 	cam_fill_csio(csio,
2800 		      /* retries */ 1,
2801 		      /* cbfcnp */ cddone,
2802 		      /* flags */ CAM_DIR_OUT,
2803 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2804 		      /* data_ptr */ (u_int8_t *)data,
2805 		      /* dxfer_len */ sizeof(*data),
2806 		      /* sense_len */ SSD_FULL_SIZE,
2807 		      sizeof(struct scsi_mode_select_6),
2808  		      /* timeout */ 50000);
2809 
2810 	scsi_cmd = (struct scsi_mode_select_6 *)&csio->cdb_io.cdb_bytes;
2811 
2812 	bzero(scsi_cmd, sizeof(*scsi_cmd));
2813 	scsi_cmd->opcode = MODE_SELECT;
2814 	scsi_cmd->byte2 |= SMS_PF;
2815 	scsi_cmd->length = sizeof(*data) & 0xff;
2816 	data->header.data_length = 0;
2817 	/*
2818 	 * SONY drives do not allow a mode select with a medium_type
2819 	 * value that has just been returned by a mode sense; use a
2820 	 * medium_type of 0 (Default) instead.
2821 	 */
2822 	data->header.medium_type = 0;
2823 
2824 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2825 			 /*sense_flags*/SF_RETRY_UA);
2826 
2827 	xpt_release_ccb(ccb);
2828 
2829 	return(error);
2830 }
2831 
2832 
2833 static int
2834 cdplay(struct cam_periph *periph, u_int32_t blk, u_int32_t len)
2835 {
2836 	struct ccb_scsiio *csio;
2837 	union ccb *ccb;
2838 	int error;
2839 	u_int8_t cdb_len;
2840 
2841 	error = 0;
2842 	ccb = cdgetccb(periph, /* priority */ 1);
2843 	csio = &ccb->csio;
2844 	/*
2845 	 * Use the smallest possible command to perform the operation.
2846 	 */
2847 	if ((len & 0xffff0000) == 0) {
2848 		/*
2849 		 * We can fit in a 10 byte cdb.
2850 		 */
2851 		struct scsi_play_10 *scsi_cmd;
2852 
2853 		scsi_cmd = (struct scsi_play_10 *)&csio->cdb_io.cdb_bytes;
2854 		bzero (scsi_cmd, sizeof(*scsi_cmd));
2855 		scsi_cmd->op_code = PLAY_10;
2856 		scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
2857 		scsi_ulto2b(len, (u_int8_t *)scsi_cmd->xfer_len);
2858 		cdb_len = sizeof(*scsi_cmd);
2859 	} else  {
2860 		struct scsi_play_12 *scsi_cmd;
2861 
2862 		scsi_cmd = (struct scsi_play_12 *)&csio->cdb_io.cdb_bytes;
2863 		bzero (scsi_cmd, sizeof(*scsi_cmd));
2864 		scsi_cmd->op_code = PLAY_12;
2865 		scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
2866 		scsi_ulto4b(len, (u_int8_t *)scsi_cmd->xfer_len);
2867 		cdb_len = sizeof(*scsi_cmd);
2868 	}
2869 	cam_fill_csio(csio,
2870 		      /*retries*/2,
2871 		      cddone,
2872 		      /*flags*/CAM_DIR_NONE,
2873 		      MSG_SIMPLE_Q_TAG,
2874 		      /*dataptr*/NULL,
2875 		      /*datalen*/0,
2876 		      /*sense_len*/SSD_FULL_SIZE,
2877 		      cdb_len,
2878 		      /*timeout*/50 * 1000);
2879 
2880 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2881 			 /*sense_flags*/SF_RETRY_UA);
2882 
2883 	xpt_release_ccb(ccb);
2884 
2885 	return(error);
2886 }
2887 
2888 static int
2889 cdplaymsf(struct cam_periph *periph, u_int32_t startm, u_int32_t starts,
2890 	  u_int32_t startf, u_int32_t endm, u_int32_t ends, u_int32_t endf)
2891 {
2892 	struct scsi_play_msf *scsi_cmd;
2893         struct ccb_scsiio *csio;
2894 	union ccb *ccb;
2895 	int error;
2896 
2897 	error = 0;
2898 
2899 	ccb = cdgetccb(periph, /* priority */ 1);
2900 
2901 	csio = &ccb->csio;
2902 
2903 	cam_fill_csio(csio,
2904 		      /* retries */ 1,
2905 		      /* cbfcnp */ cddone,
2906 		      /* flags */ CAM_DIR_NONE,
2907 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2908 		      /* data_ptr */ NULL,
2909 		      /* dxfer_len */ 0,
2910 		      /* sense_len */ SSD_FULL_SIZE,
2911 		      sizeof(struct scsi_play_msf),
2912  		      /* timeout */ 50000);
2913 
2914 	scsi_cmd = (struct scsi_play_msf *)&csio->cdb_io.cdb_bytes;
2915 	bzero (scsi_cmd, sizeof(*scsi_cmd));
2916 
2917         scsi_cmd->op_code = PLAY_MSF;
2918         scsi_cmd->start_m = startm;
2919         scsi_cmd->start_s = starts;
2920         scsi_cmd->start_f = startf;
2921         scsi_cmd->end_m = endm;
2922         scsi_cmd->end_s = ends;
2923         scsi_cmd->end_f = endf;
2924 
2925 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2926 			 /*sense_flags*/SF_RETRY_UA);
2927 
2928 	xpt_release_ccb(ccb);
2929 
2930 	return(error);
2931 }
2932 
2933 
2934 static int
2935 cdplaytracks(struct cam_periph *periph, u_int32_t strack, u_int32_t sindex,
2936 	     u_int32_t etrack, u_int32_t eindex)
2937 {
2938 	struct scsi_play_track *scsi_cmd;
2939         struct ccb_scsiio *csio;
2940 	union ccb *ccb;
2941 	int error;
2942 
2943 	error = 0;
2944 
2945 	ccb = cdgetccb(periph, /* priority */ 1);
2946 
2947 	csio = &ccb->csio;
2948 
2949 	cam_fill_csio(csio,
2950 		      /* retries */ 1,
2951 		      /* cbfcnp */ cddone,
2952 		      /* flags */ CAM_DIR_NONE,
2953 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2954 		      /* data_ptr */ NULL,
2955 		      /* dxfer_len */ 0,
2956 		      /* sense_len */ SSD_FULL_SIZE,
2957 		      sizeof(struct scsi_play_track),
2958  		      /* timeout */ 50000);
2959 
2960 	scsi_cmd = (struct scsi_play_track *)&csio->cdb_io.cdb_bytes;
2961 	bzero (scsi_cmd, sizeof(*scsi_cmd));
2962 
2963         scsi_cmd->op_code = PLAY_TRACK;
2964         scsi_cmd->start_track = strack;
2965         scsi_cmd->start_index = sindex;
2966         scsi_cmd->end_track = etrack;
2967         scsi_cmd->end_index = eindex;
2968 
2969 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2970 			 /*sense_flags*/SF_RETRY_UA);
2971 
2972 	xpt_release_ccb(ccb);
2973 
2974 	return(error);
2975 }
2976 
2977 static int
2978 cdpause(struct cam_periph *periph, u_int32_t go)
2979 {
2980 	struct scsi_pause *scsi_cmd;
2981         struct ccb_scsiio *csio;
2982 	union ccb *ccb;
2983 	int error;
2984 
2985 	error = 0;
2986 
2987 	ccb = cdgetccb(periph, /* priority */ 1);
2988 
2989 	csio = &ccb->csio;
2990 
2991 	cam_fill_csio(csio,
2992 		      /* retries */ 1,
2993 		      /* cbfcnp */ cddone,
2994 		      /* flags */ CAM_DIR_NONE,
2995 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2996 		      /* data_ptr */ NULL,
2997 		      /* dxfer_len */ 0,
2998 		      /* sense_len */ SSD_FULL_SIZE,
2999 		      sizeof(struct scsi_pause),
3000  		      /* timeout */ 50000);
3001 
3002 	scsi_cmd = (struct scsi_pause *)&csio->cdb_io.cdb_bytes;
3003 	bzero (scsi_cmd, sizeof(*scsi_cmd));
3004 
3005         scsi_cmd->op_code = PAUSE;
3006 	scsi_cmd->resume = go;
3007 
3008 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3009 			 /*sense_flags*/SF_RETRY_UA);
3010 
3011 	xpt_release_ccb(ccb);
3012 
3013 	return(error);
3014 }
3015 
3016 static int
3017 cdstartunit(struct cam_periph *periph)
3018 {
3019 	union ccb *ccb;
3020 	int error;
3021 
3022 	error = 0;
3023 
3024 	ccb = cdgetccb(periph, /* priority */ 1);
3025 
3026 	scsi_start_stop(&ccb->csio,
3027 			/* retries */ 1,
3028 			/* cbfcnp */ cddone,
3029 			/* tag_action */ MSG_SIMPLE_Q_TAG,
3030 			/* start */ TRUE,
3031 			/* load_eject */ FALSE,
3032 			/* immediate */ FALSE,
3033 			/* sense_len */ SSD_FULL_SIZE,
3034 			/* timeout */ 50000);
3035 
3036 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3037 			 /*sense_flags*/SF_RETRY_UA);
3038 
3039 	xpt_release_ccb(ccb);
3040 
3041 	return(error);
3042 }
3043 
3044 static int
3045 cdstopunit(struct cam_periph *periph, u_int32_t eject)
3046 {
3047 	union ccb *ccb;
3048 	int error;
3049 
3050 	error = 0;
3051 
3052 	ccb = cdgetccb(periph, /* priority */ 1);
3053 
3054 	scsi_start_stop(&ccb->csio,
3055 			/* retries */ 1,
3056 			/* cbfcnp */ cddone,
3057 			/* tag_action */ MSG_SIMPLE_Q_TAG,
3058 			/* start */ FALSE,
3059 			/* load_eject */ eject,
3060 			/* immediate */ FALSE,
3061 			/* sense_len */ SSD_FULL_SIZE,
3062 			/* timeout */ 50000);
3063 
3064 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3065 			 /*sense_flags*/SF_RETRY_UA);
3066 
3067 	xpt_release_ccb(ccb);
3068 
3069 	return(error);
3070 }
3071 
3072 static int
3073 cdreportkey(struct cam_periph *periph, struct dvd_authinfo *authinfo)
3074 {
3075 	union ccb *ccb;
3076 	u_int8_t *databuf;
3077 	u_int32_t lba;
3078 	int error;
3079 	int length;
3080 
3081 	error = 0;
3082 	databuf = NULL;
3083 	lba = 0;
3084 
3085 	ccb = cdgetccb(periph, /* priority */ 1);
3086 
3087 	switch (authinfo->format) {
3088 	case DVD_REPORT_AGID:
3089 		length = sizeof(struct scsi_report_key_data_agid);
3090 		break;
3091 	case DVD_REPORT_CHALLENGE:
3092 		length = sizeof(struct scsi_report_key_data_challenge);
3093 		break;
3094 	case DVD_REPORT_KEY1:
3095 		length = sizeof(struct scsi_report_key_data_key1_key2);
3096 		break;
3097 	case DVD_REPORT_TITLE_KEY:
3098 		length = sizeof(struct scsi_report_key_data_title);
3099 		/* The lba field is only set for the title key */
3100 		lba = authinfo->lba;
3101 		break;
3102 	case DVD_REPORT_ASF:
3103 		length = sizeof(struct scsi_report_key_data_asf);
3104 		break;
3105 	case DVD_REPORT_RPC:
3106 		length = sizeof(struct scsi_report_key_data_rpc);
3107 		break;
3108 	case DVD_INVALIDATE_AGID:
3109 		length = 0;
3110 		break;
3111 	default:
3112 		error = EINVAL;
3113 		goto bailout;
3114 		break; /* NOTREACHED */
3115 	}
3116 
3117 	if (length != 0) {
3118 		databuf = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3119 	} else
3120 		databuf = NULL;
3121 
3122 
3123 	scsi_report_key(&ccb->csio,
3124 			/* retries */ 1,
3125 			/* cbfcnp */ cddone,
3126 			/* tag_action */ MSG_SIMPLE_Q_TAG,
3127 			/* lba */ lba,
3128 			/* agid */ authinfo->agid,
3129 			/* key_format */ authinfo->format,
3130 			/* data_ptr */ databuf,
3131 			/* dxfer_len */ length,
3132 			/* sense_len */ SSD_FULL_SIZE,
3133 			/* timeout */ 50000);
3134 
3135 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3136 			 /*sense_flags*/SF_RETRY_UA);
3137 
3138 	if (error != 0)
3139 		goto bailout;
3140 
3141 	if (ccb->csio.resid != 0) {
3142 		xpt_print_path(periph->path);
3143 		printf("warning, residual for report key command is %d\n",
3144 		       ccb->csio.resid);
3145 	}
3146 
3147 	switch(authinfo->format) {
3148 	case DVD_REPORT_AGID: {
3149 		struct scsi_report_key_data_agid *agid_data;
3150 
3151 		agid_data = (struct scsi_report_key_data_agid *)databuf;
3152 
3153 		authinfo->agid = (agid_data->agid & RKD_AGID_MASK) >>
3154 			RKD_AGID_SHIFT;
3155 		break;
3156 	}
3157 	case DVD_REPORT_CHALLENGE: {
3158 		struct scsi_report_key_data_challenge *chal_data;
3159 
3160 		chal_data = (struct scsi_report_key_data_challenge *)databuf;
3161 
3162 		bcopy(chal_data->challenge_key, authinfo->keychal,
3163 		      min(sizeof(chal_data->challenge_key),
3164 		          sizeof(authinfo->keychal)));
3165 		break;
3166 	}
3167 	case DVD_REPORT_KEY1: {
3168 		struct scsi_report_key_data_key1_key2 *key1_data;
3169 
3170 		key1_data = (struct scsi_report_key_data_key1_key2 *)databuf;
3171 
3172 		bcopy(key1_data->key1, authinfo->keychal,
3173 		      min(sizeof(key1_data->key1), sizeof(authinfo->keychal)));
3174 		break;
3175 	}
3176 	case DVD_REPORT_TITLE_KEY: {
3177 		struct scsi_report_key_data_title *title_data;
3178 
3179 		title_data = (struct scsi_report_key_data_title *)databuf;
3180 
3181 		authinfo->cpm = (title_data->byte0 & RKD_TITLE_CPM) >>
3182 			RKD_TITLE_CPM_SHIFT;
3183 		authinfo->cp_sec = (title_data->byte0 & RKD_TITLE_CP_SEC) >>
3184 			RKD_TITLE_CP_SEC_SHIFT;
3185 		authinfo->cgms = (title_data->byte0 & RKD_TITLE_CMGS_MASK) >>
3186 			RKD_TITLE_CMGS_SHIFT;
3187 		bcopy(title_data->title_key, authinfo->keychal,
3188 		      min(sizeof(title_data->title_key),
3189 			  sizeof(authinfo->keychal)));
3190 		break;
3191 	}
3192 	case DVD_REPORT_ASF: {
3193 		struct scsi_report_key_data_asf *asf_data;
3194 
3195 		asf_data = (struct scsi_report_key_data_asf *)databuf;
3196 
3197 		authinfo->asf = asf_data->success & RKD_ASF_SUCCESS;
3198 		break;
3199 	}
3200 	case DVD_REPORT_RPC: {
3201 		struct scsi_report_key_data_rpc *rpc_data;
3202 
3203 		rpc_data = (struct scsi_report_key_data_rpc *)databuf;
3204 
3205 		authinfo->reg_type = (rpc_data->byte4 & RKD_RPC_TYPE_MASK) >>
3206 			RKD_RPC_TYPE_SHIFT;
3207 		authinfo->vend_rsts =
3208 			(rpc_data->byte4 & RKD_RPC_VENDOR_RESET_MASK) >>
3209 			RKD_RPC_VENDOR_RESET_SHIFT;
3210 		authinfo->user_rsts = rpc_data->byte4 & RKD_RPC_USER_RESET_MASK;
3211 		authinfo->region = rpc_data->region_mask;
3212 		authinfo->rpc_scheme = rpc_data->rpc_scheme1;
3213 		break;
3214 	}
3215 	case DVD_INVALIDATE_AGID:
3216 		break;
3217 	default:
3218 		/* This should be impossible, since we checked above */
3219 		error = EINVAL;
3220 		goto bailout;
3221 		break; /* NOTREACHED */
3222 	}
3223 bailout:
3224 	if (databuf != NULL)
3225 		free(databuf, M_DEVBUF);
3226 
3227 	xpt_release_ccb(ccb);
3228 
3229 	return(error);
3230 }
3231 
3232 static int
3233 cdsendkey(struct cam_periph *periph, struct dvd_authinfo *authinfo)
3234 {
3235 	union ccb *ccb;
3236 	u_int8_t *databuf;
3237 	int length;
3238 	int error;
3239 
3240 	error = 0;
3241 	databuf = NULL;
3242 
3243 	ccb = cdgetccb(periph, /* priority */ 1);
3244 
3245 	switch(authinfo->format) {
3246 	case DVD_SEND_CHALLENGE: {
3247 		struct scsi_report_key_data_challenge *challenge_data;
3248 
3249 		length = sizeof(*challenge_data);
3250 
3251 		challenge_data = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3252 
3253 		databuf = (u_int8_t *)challenge_data;
3254 
3255 		scsi_ulto2b(length - sizeof(challenge_data->data_len),
3256 			    challenge_data->data_len);
3257 
3258 		bcopy(authinfo->keychal, challenge_data->challenge_key,
3259 		      min(sizeof(authinfo->keychal),
3260 			  sizeof(challenge_data->challenge_key)));
3261 		break;
3262 	}
3263 	case DVD_SEND_KEY2: {
3264 		struct scsi_report_key_data_key1_key2 *key2_data;
3265 
3266 		length = sizeof(*key2_data);
3267 
3268 		key2_data = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3269 
3270 		databuf = (u_int8_t *)key2_data;
3271 
3272 		scsi_ulto2b(length - sizeof(key2_data->data_len),
3273 			    key2_data->data_len);
3274 
3275 		bcopy(authinfo->keychal, key2_data->key1,
3276 		      min(sizeof(authinfo->keychal), sizeof(key2_data->key1)));
3277 
3278 		break;
3279 	}
3280 	case DVD_SEND_RPC: {
3281 		struct scsi_send_key_data_rpc *rpc_data;
3282 
3283 		length = sizeof(*rpc_data);
3284 
3285 		rpc_data = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3286 
3287 		databuf = (u_int8_t *)rpc_data;
3288 
3289 		scsi_ulto2b(length - sizeof(rpc_data->data_len),
3290 			    rpc_data->data_len);
3291 
3292 		rpc_data->region_code = authinfo->region;
3293 		break;
3294 	}
3295 	default:
3296 		error = EINVAL;
3297 		goto bailout;
3298 		break; /* NOTREACHED */
3299 	}
3300 
3301 	scsi_send_key(&ccb->csio,
3302 		      /* retries */ 1,
3303 		      /* cbfcnp */ cddone,
3304 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3305 		      /* agid */ authinfo->agid,
3306 		      /* key_format */ authinfo->format,
3307 		      /* data_ptr */ databuf,
3308 		      /* dxfer_len */ length,
3309 		      /* sense_len */ SSD_FULL_SIZE,
3310 		      /* timeout */ 50000);
3311 
3312 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3313 			 /*sense_flags*/SF_RETRY_UA);
3314 
3315 bailout:
3316 
3317 	if (databuf != NULL)
3318 		free(databuf, M_DEVBUF);
3319 
3320 	xpt_release_ccb(ccb);
3321 
3322 	return(error);
3323 }
3324 
3325 static int
3326 cdreaddvdstructure(struct cam_periph *periph, struct dvd_struct *dvdstruct)
3327 {
3328 	union ccb *ccb;
3329 	u_int8_t *databuf;
3330 	u_int32_t address;
3331 	int error;
3332 	int length;
3333 
3334 	error = 0;
3335 	databuf = NULL;
3336 	/* The address is reserved for many of the formats */
3337 	address = 0;
3338 
3339 	ccb = cdgetccb(periph, /* priority */ 1);
3340 
3341 	switch(dvdstruct->format) {
3342 	case DVD_STRUCT_PHYSICAL:
3343 		length = sizeof(struct scsi_read_dvd_struct_data_physical);
3344 		break;
3345 	case DVD_STRUCT_COPYRIGHT:
3346 		length = sizeof(struct scsi_read_dvd_struct_data_copyright);
3347 		break;
3348 	case DVD_STRUCT_DISCKEY:
3349 		length = sizeof(struct scsi_read_dvd_struct_data_disc_key);
3350 		break;
3351 	case DVD_STRUCT_BCA:
3352 		length = sizeof(struct scsi_read_dvd_struct_data_bca);
3353 		break;
3354 	case DVD_STRUCT_MANUFACT:
3355 		length = sizeof(struct scsi_read_dvd_struct_data_manufacturer);
3356 		break;
3357 	case DVD_STRUCT_CMI:
3358 		error = ENODEV;
3359 		goto bailout;
3360 #ifdef notyet
3361 		length = sizeof(struct scsi_read_dvd_struct_data_copy_manage);
3362 		address = dvdstruct->address;
3363 #endif
3364 		break; /* NOTREACHED */
3365 	case DVD_STRUCT_PROTDISCID:
3366 		length = sizeof(struct scsi_read_dvd_struct_data_prot_discid);
3367 		break;
3368 	case DVD_STRUCT_DISCKEYBLOCK:
3369 		length = sizeof(struct scsi_read_dvd_struct_data_disc_key_blk);
3370 		break;
3371 	case DVD_STRUCT_DDS:
3372 		length = sizeof(struct scsi_read_dvd_struct_data_dds);
3373 		break;
3374 	case DVD_STRUCT_MEDIUM_STAT:
3375 		length = sizeof(struct scsi_read_dvd_struct_data_medium_status);
3376 		break;
3377 	case DVD_STRUCT_SPARE_AREA:
3378 		length = sizeof(struct scsi_read_dvd_struct_data_spare_area);
3379 		break;
3380 	case DVD_STRUCT_RMD_LAST:
3381 		error = ENODEV;
3382 		goto bailout;
3383 #ifdef notyet
3384 		length = sizeof(struct scsi_read_dvd_struct_data_rmd_borderout);
3385 		address = dvdstruct->address;
3386 #endif
3387 		break; /* NOTREACHED */
3388 	case DVD_STRUCT_RMD_RMA:
3389 		error = ENODEV;
3390 		goto bailout;
3391 #ifdef notyet
3392 		length = sizeof(struct scsi_read_dvd_struct_data_rmd);
3393 		address = dvdstruct->address;
3394 #endif
3395 		break; /* NOTREACHED */
3396 	case DVD_STRUCT_PRERECORDED:
3397 		length = sizeof(struct scsi_read_dvd_struct_data_leadin);
3398 		break;
3399 	case DVD_STRUCT_UNIQUEID:
3400 		length = sizeof(struct scsi_read_dvd_struct_data_disc_id);
3401 		break;
3402 	case DVD_STRUCT_DCB:
3403 		error = ENODEV;
3404 		goto bailout;
3405 #ifdef notyet
3406 		length = sizeof(struct scsi_read_dvd_struct_data_dcb);
3407 		address = dvdstruct->address;
3408 #endif
3409 		break; /* NOTREACHED */
3410 	case DVD_STRUCT_LIST:
3411 		/*
3412 		 * This is the maximum allocation length for the READ DVD
3413 		 * STRUCTURE command.  There's nothing in the MMC3 spec
3414 		 * that indicates a limit in the amount of data that can
3415 		 * be returned from this call, other than the limits
3416 		 * imposed by the 2-byte length variables.
3417 		 */
3418 		length = 65535;
3419 		break;
3420 	default:
3421 		error = EINVAL;
3422 		goto bailout;
3423 		break; /* NOTREACHED */
3424 	}
3425 
3426 	if (length != 0) {
3427 		databuf = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3428 	} else
3429 		databuf = NULL;
3430 
3431 	scsi_read_dvd_structure(&ccb->csio,
3432 				/* retries */ 1,
3433 				/* cbfcnp */ cddone,
3434 				/* tag_action */ MSG_SIMPLE_Q_TAG,
3435 				/* lba */ address,
3436 				/* layer_number */ dvdstruct->layer_num,
3437 				/* key_format */ dvdstruct->format,
3438 				/* agid */ dvdstruct->agid,
3439 				/* data_ptr */ databuf,
3440 				/* dxfer_len */ length,
3441 				/* sense_len */ SSD_FULL_SIZE,
3442 				/* timeout */ 50000);
3443 
3444 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3445 			 /*sense_flags*/SF_RETRY_UA);
3446 
3447 	if (error != 0)
3448 		goto bailout;
3449 
3450 	switch(dvdstruct->format) {
3451 	case DVD_STRUCT_PHYSICAL: {
3452 		struct scsi_read_dvd_struct_data_layer_desc *inlayer;
3453 		struct dvd_layer *outlayer;
3454 		struct scsi_read_dvd_struct_data_physical *phys_data;
3455 
3456 		phys_data =
3457 			(struct scsi_read_dvd_struct_data_physical *)databuf;
3458 		inlayer = &phys_data->layer_desc;
3459 		outlayer = (struct dvd_layer *)&dvdstruct->data;
3460 
3461 		dvdstruct->length = sizeof(*inlayer);
3462 
3463 		outlayer->book_type = (inlayer->book_type_version &
3464 			RDSD_BOOK_TYPE_MASK) >> RDSD_BOOK_TYPE_SHIFT;
3465 		outlayer->book_version = (inlayer->book_type_version &
3466 			RDSD_BOOK_VERSION_MASK);
3467 		outlayer->disc_size = (inlayer->disc_size_max_rate &
3468 			RDSD_DISC_SIZE_MASK) >> RDSD_DISC_SIZE_SHIFT;
3469 		outlayer->max_rate = (inlayer->disc_size_max_rate &
3470 			RDSD_MAX_RATE_MASK);
3471 		outlayer->nlayers = (inlayer->layer_info &
3472 			RDSD_NUM_LAYERS_MASK) >> RDSD_NUM_LAYERS_SHIFT;
3473 		outlayer->track_path = (inlayer->layer_info &
3474 			RDSD_TRACK_PATH_MASK) >> RDSD_TRACK_PATH_SHIFT;
3475 		outlayer->layer_type = (inlayer->layer_info &
3476 			RDSD_LAYER_TYPE_MASK);
3477 		outlayer->linear_density = (inlayer->density &
3478 			RDSD_LIN_DENSITY_MASK) >> RDSD_LIN_DENSITY_SHIFT;
3479 		outlayer->track_density = (inlayer->density &
3480 			RDSD_TRACK_DENSITY_MASK);
3481 		outlayer->bca = (inlayer->bca & RDSD_BCA_MASK) >>
3482 			RDSD_BCA_SHIFT;
3483 		outlayer->start_sector = scsi_3btoul(inlayer->main_data_start);
3484 		outlayer->end_sector = scsi_3btoul(inlayer->main_data_end);
3485 		outlayer->end_sector_l0 =
3486 			scsi_3btoul(inlayer->end_sector_layer0);
3487 		break;
3488 	}
3489 	case DVD_STRUCT_COPYRIGHT: {
3490 		struct scsi_read_dvd_struct_data_copyright *copy_data;
3491 
3492 		copy_data = (struct scsi_read_dvd_struct_data_copyright *)
3493 			databuf;
3494 
3495 		dvdstruct->cpst = copy_data->cps_type;
3496 		dvdstruct->rmi = copy_data->region_info;
3497 		dvdstruct->length = 0;
3498 
3499 		break;
3500 	}
3501 	default:
3502 		/*
3503 		 * Tell the user what the overall length is, no matter
3504 		 * what we can actually fit in the data buffer.
3505 		 */
3506 		dvdstruct->length = length - ccb->csio.resid -
3507 			sizeof(struct scsi_read_dvd_struct_data_header);
3508 
3509 		/*
3510 		 * But only actually copy out the smaller of what we read
3511 		 * in or what the structure can take.
3512 		 */
3513 		bcopy(databuf + sizeof(struct scsi_read_dvd_struct_data_header),
3514 		      dvdstruct->data,
3515 		      min(sizeof(dvdstruct->data), dvdstruct->length));
3516 		break;
3517 	}
3518 bailout:
3519 
3520 	if (databuf != NULL)
3521 		free(databuf, M_DEVBUF);
3522 
3523 	xpt_release_ccb(ccb);
3524 
3525 	return(error);
3526 }
3527 
3528 void
3529 scsi_report_key(struct ccb_scsiio *csio, u_int32_t retries,
3530 		void (*cbfcnp)(struct cam_periph *, union ccb *),
3531 		u_int8_t tag_action, u_int32_t lba, u_int8_t agid,
3532 		u_int8_t key_format, u_int8_t *data_ptr, u_int32_t dxfer_len,
3533 		u_int8_t sense_len, u_int32_t timeout)
3534 {
3535 	struct scsi_report_key *scsi_cmd;
3536 
3537 	scsi_cmd = (struct scsi_report_key *)&csio->cdb_io.cdb_bytes;
3538 	bzero(scsi_cmd, sizeof(*scsi_cmd));
3539 	scsi_cmd->opcode = REPORT_KEY;
3540 	scsi_ulto4b(lba, scsi_cmd->lba);
3541 	scsi_ulto2b(dxfer_len, scsi_cmd->alloc_len);
3542 	scsi_cmd->agid_keyformat = (agid << RK_KF_AGID_SHIFT) |
3543 		(key_format & RK_KF_KEYFORMAT_MASK);
3544 
3545 	cam_fill_csio(csio,
3546 		      retries,
3547 		      cbfcnp,
3548 		      /*flags*/ (dxfer_len == 0) ? CAM_DIR_NONE : CAM_DIR_IN,
3549 		      tag_action,
3550 		      /*data_ptr*/ data_ptr,
3551 		      /*dxfer_len*/ dxfer_len,
3552 		      sense_len,
3553 		      sizeof(*scsi_cmd),
3554 		      timeout);
3555 }
3556 
3557 void
3558 scsi_send_key(struct ccb_scsiio *csio, u_int32_t retries,
3559 	      void (*cbfcnp)(struct cam_periph *, union ccb *),
3560 	      u_int8_t tag_action, u_int8_t agid, u_int8_t key_format,
3561 	      u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
3562 	      u_int32_t timeout)
3563 {
3564 	struct scsi_send_key *scsi_cmd;
3565 
3566 	scsi_cmd = (struct scsi_send_key *)&csio->cdb_io.cdb_bytes;
3567 	bzero(scsi_cmd, sizeof(*scsi_cmd));
3568 	scsi_cmd->opcode = SEND_KEY;
3569 
3570 	scsi_ulto2b(dxfer_len, scsi_cmd->param_len);
3571 	scsi_cmd->agid_keyformat = (agid << RK_KF_AGID_SHIFT) |
3572 		(key_format & RK_KF_KEYFORMAT_MASK);
3573 
3574 	cam_fill_csio(csio,
3575 		      retries,
3576 		      cbfcnp,
3577 		      /*flags*/ CAM_DIR_OUT,
3578 		      tag_action,
3579 		      /*data_ptr*/ data_ptr,
3580 		      /*dxfer_len*/ dxfer_len,
3581 		      sense_len,
3582 		      sizeof(*scsi_cmd),
3583 		      timeout);
3584 }
3585 
3586 
3587 void
3588 scsi_read_dvd_structure(struct ccb_scsiio *csio, u_int32_t retries,
3589 			void (*cbfcnp)(struct cam_periph *, union ccb *),
3590 			u_int8_t tag_action, u_int32_t address,
3591 			u_int8_t layer_number, u_int8_t format, u_int8_t agid,
3592 			u_int8_t *data_ptr, u_int32_t dxfer_len,
3593 			u_int8_t sense_len, u_int32_t timeout)
3594 {
3595 	struct scsi_read_dvd_structure *scsi_cmd;
3596 
3597 	scsi_cmd = (struct scsi_read_dvd_structure *)&csio->cdb_io.cdb_bytes;
3598 	bzero(scsi_cmd, sizeof(*scsi_cmd));
3599 	scsi_cmd->opcode = READ_DVD_STRUCTURE;
3600 
3601 	scsi_ulto4b(address, scsi_cmd->address);
3602 	scsi_cmd->layer_number = layer_number;
3603 	scsi_cmd->format = format;
3604 	scsi_ulto2b(dxfer_len, scsi_cmd->alloc_len);
3605 	/* The AGID is the top two bits of this byte */
3606 	scsi_cmd->agid = agid << 6;
3607 
3608 	cam_fill_csio(csio,
3609 		      retries,
3610 		      cbfcnp,
3611 		      /*flags*/ CAM_DIR_IN,
3612 		      tag_action,
3613 		      /*data_ptr*/ data_ptr,
3614 		      /*dxfer_len*/ dxfer_len,
3615 		      sense_len,
3616 		      sizeof(*scsi_cmd),
3617 		      timeout);
3618 }
3619