xref: /freebsd/sys/cam/scsi/scsi_cd.c (revision 10b59a9b4add0320d52c15ce057dd697261e7dfc)
1 /*-
2  * Copyright (c) 1997 Justin T. Gibbs.
3  * Copyright (c) 1997, 1998, 1999, 2000, 2001, 2002, 2003 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 
28 /*-
29  * Portions of this driver taken from the original FreeBSD cd driver.
30  * Written by Julian Elischer (julian@tfs.com)
31  * for TRW Financial Systems for use under the MACH(2.5) operating system.
32  *
33  * TRW Financial Systems, in accordance with their agreement with Carnegie
34  * Mellon University, makes this software available to CMU to distribute
35  * or use in any manner that they see fit as long as this message is kept with
36  * the software. For this reason TFS also grants any other persons or
37  * organisations permission to use or modify this software.
38  *
39  * TFS supplies this software to be publicly redistributed
40  * on the understanding that TFS is not responsible for the correct
41  * functioning of this software in any circumstances.
42  *
43  * Ported to run under 386BSD by Julian Elischer (julian@tfs.com) Sept 1992
44  *
45  *      from: cd.c,v 1.83 1997/05/04 15:24:22 joerg Exp $
46  */
47 
48 #include <sys/cdefs.h>
49 __FBSDID("$FreeBSD$");
50 
51 #include "opt_cd.h"
52 
53 #include <sys/param.h>
54 #include <sys/systm.h>
55 #include <sys/kernel.h>
56 #include <sys/bio.h>
57 #include <sys/conf.h>
58 #include <sys/disk.h>
59 #include <sys/malloc.h>
60 #include <sys/cdio.h>
61 #include <sys/cdrio.h>
62 #include <sys/dvdio.h>
63 #include <sys/devicestat.h>
64 #include <sys/sysctl.h>
65 #include <sys/taskqueue.h>
66 #include <geom/geom_disk.h>
67 
68 #include <cam/cam.h>
69 #include <cam/cam_ccb.h>
70 #include <cam/cam_periph.h>
71 #include <cam/cam_xpt_periph.h>
72 #include <cam/cam_queue.h>
73 #include <cam/cam_sim.h>
74 
75 #include <cam/scsi/scsi_message.h>
76 #include <cam/scsi/scsi_da.h>
77 #include <cam/scsi/scsi_cd.h>
78 
79 #define LEADOUT         0xaa            /* leadout toc entry */
80 
81 struct cd_params {
82 	u_int32_t blksize;
83 	u_long    disksize;
84 };
85 
86 typedef enum {
87 	CD_Q_NONE		= 0x00,
88 	CD_Q_NO_TOUCH		= 0x01,
89 	CD_Q_BCD_TRACKS		= 0x02,
90 	CD_Q_NO_CHANGER		= 0x04,
91 	CD_Q_CHANGER		= 0x08,
92 	CD_Q_10_BYTE_ONLY	= 0x10
93 } cd_quirks;
94 
95 typedef enum {
96 	CD_FLAG_INVALID		= 0x0001,
97 	CD_FLAG_NEW_DISC	= 0x0002,
98 	CD_FLAG_DISC_LOCKED	= 0x0004,
99 	CD_FLAG_DISC_REMOVABLE	= 0x0008,
100 	CD_FLAG_TAGGED_QUEUING	= 0x0010,
101 	CD_FLAG_CHANGER		= 0x0040,
102 	CD_FLAG_ACTIVE		= 0x0080,
103 	CD_FLAG_SCHED_ON_COMP	= 0x0100,
104 	CD_FLAG_RETRY_UA	= 0x0200,
105 	CD_FLAG_VALID_MEDIA	= 0x0400,
106 	CD_FLAG_VALID_TOC	= 0x0800,
107 	CD_FLAG_SCTX_INIT	= 0x1000,
108 	CD_FLAG_OPEN		= 0x2000
109 } cd_flags;
110 
111 typedef enum {
112 	CD_CCB_PROBE		= 0x01,
113 	CD_CCB_BUFFER_IO	= 0x02,
114 	CD_CCB_WAITING		= 0x03,
115 	CD_CCB_TYPE_MASK	= 0x0F,
116 	CD_CCB_RETRY_UA		= 0x10
117 } cd_ccb_state;
118 
119 typedef enum {
120 	CHANGER_TIMEOUT_SCHED		= 0x01,
121 	CHANGER_SHORT_TMOUT_SCHED	= 0x02,
122 	CHANGER_MANUAL_CALL		= 0x04,
123 	CHANGER_NEED_TIMEOUT		= 0x08
124 } cd_changer_flags;
125 
126 #define ccb_state ppriv_field0
127 #define ccb_bp ppriv_ptr1
128 
129 struct cd_tocdata {
130 	struct ioc_toc_header header;
131 	struct cd_toc_entry entries[100];
132 };
133 
134 struct cd_toc_single {
135 	struct ioc_toc_header header;
136 	struct cd_toc_entry entry;
137 };
138 
139 typedef enum {
140 	CD_STATE_PROBE,
141 	CD_STATE_NORMAL
142 } cd_state;
143 
144 struct cd_softc {
145 	cam_pinfo		pinfo;
146 	cd_state		state;
147 	volatile cd_flags	flags;
148 	struct bio_queue_head	bio_queue;
149 	LIST_HEAD(, ccb_hdr)	pending_ccbs;
150 	struct cd_params	params;
151 	union ccb		saved_ccb;
152 	cd_quirks		quirks;
153 	STAILQ_ENTRY(cd_softc)	changer_links;
154 	struct cdchanger	*changer;
155 	int			bufs_left;
156 	struct cam_periph	*periph;
157 	int			minimum_command_size;
158 	int			outstanding_cmds;
159 	struct task		sysctl_task;
160 	struct sysctl_ctx_list	sysctl_ctx;
161 	struct sysctl_oid	*sysctl_tree;
162 	STAILQ_HEAD(, cd_mode_params)	mode_queue;
163 	struct cd_tocdata	toc;
164 	struct disk		*disk;
165 };
166 
167 struct cd_page_sizes {
168 	int page;
169 	int page_size;
170 };
171 
172 static struct cd_page_sizes cd_page_size_table[] =
173 {
174 	{ AUDIO_PAGE, sizeof(struct cd_audio_page)}
175 };
176 
177 struct cd_quirk_entry {
178 	struct scsi_inquiry_pattern inq_pat;
179 	cd_quirks quirks;
180 };
181 
182 /*
183  * The changer quirk entries aren't strictly necessary.  Basically, what
184  * they do is tell cdregister() up front that a device is a changer.
185  * Otherwise, it will figure that fact out once it sees a LUN on the device
186  * that is greater than 0.  If it is known up front that a device is a changer,
187  * all I/O to the device will go through the changer scheduling routines, as
188  * opposed to the "normal" CD code.
189  *
190  * NOTE ON 10_BYTE_ONLY quirks:  Any 10_BYTE_ONLY quirks MUST be because
191  * your device hangs when it gets a 10 byte command.  Adding a quirk just
192  * to get rid of the informative diagnostic message is not acceptable.  All
193  * 10_BYTE_ONLY quirks must be documented in full in a PR (which should be
194  * referenced in a comment along with the quirk) , and must be approved by
195  * ken@FreeBSD.org.  Any quirks added that don't adhere to this policy may
196  * be removed until the submitter can explain why they are needed.
197  * 10_BYTE_ONLY quirks will be removed (as they will no longer be necessary)
198  * when the CAM_NEW_TRAN_CODE work is done.
199  */
200 static struct cd_quirk_entry cd_quirk_table[] =
201 {
202 	{
203 		{ T_CDROM, SIP_MEDIA_REMOVABLE, "NRC", "MBR-7", "*"},
204 		 /*quirks*/ CD_Q_CHANGER
205 	},
206 	{
207 		{ T_CDROM, SIP_MEDIA_REMOVABLE, "PIONEER", "CD-ROM DRM*",
208 		  "*"}, /* quirks */ CD_Q_CHANGER
209 	},
210 	{
211 		{ T_CDROM, SIP_MEDIA_REMOVABLE, "NAKAMICH", "MJ-*", "*"},
212 		 /* quirks */ CD_Q_CHANGER
213 	},
214 	{
215 		{ T_CDROM, SIP_MEDIA_REMOVABLE, "CHINON", "CD-ROM CDS-535","*"},
216 		/* quirks */ CD_Q_BCD_TRACKS
217 	}
218 };
219 
220 static	disk_open_t	cdopen;
221 static	disk_close_t	cdclose;
222 static	disk_ioctl_t	cdioctl;
223 static	disk_strategy_t	cdstrategy;
224 
225 static	periph_init_t	cdinit;
226 static	periph_ctor_t	cdregister;
227 static	periph_dtor_t	cdcleanup;
228 static	periph_start_t	cdstart;
229 static	periph_oninv_t	cdoninvalidate;
230 static	void		cdasync(void *callback_arg, u_int32_t code,
231 				struct cam_path *path, void *arg);
232 static	int		cdcmdsizesysctl(SYSCTL_HANDLER_ARGS);
233 static	void		cdshorttimeout(void *arg);
234 static	void		cdschedule(struct cam_periph *periph, int priority);
235 static	void		cdrunchangerqueue(void *arg);
236 static	void		cdchangerschedule(struct cd_softc *softc);
237 static	int		cdrunccb(union ccb *ccb,
238 				 int (*error_routine)(union ccb *ccb,
239 						      u_int32_t cam_flags,
240 						      u_int32_t sense_flags),
241 				 u_int32_t cam_flags, u_int32_t sense_flags);
242 static	union ccb 	*cdgetccb(struct cam_periph *periph,
243 				  u_int32_t priority);
244 static	void		cddone(struct cam_periph *periph,
245 			       union ccb *start_ccb);
246 static	union cd_pages	*cdgetpage(struct cd_mode_params *mode_params);
247 static	int		cdgetpagesize(int page_num);
248 static	void		cdprevent(struct cam_periph *periph, int action);
249 static	int		cdcheckmedia(struct cam_periph *periph);
250 static	int		cdsize(struct cam_periph *periph, u_int32_t *size);
251 static	int		cd6byteworkaround(union ccb *ccb);
252 static	int		cderror(union ccb *ccb, u_int32_t cam_flags,
253 				u_int32_t sense_flags);
254 static	int		cdreadtoc(struct cam_periph *periph, u_int32_t mode,
255 				  u_int32_t start, u_int8_t *data,
256 				  u_int32_t len, u_int32_t sense_flags);
257 static	int		cdgetmode(struct cam_periph *periph,
258 				  struct cd_mode_params *data, u_int32_t page);
259 static	int		cdsetmode(struct cam_periph *periph,
260 				  struct cd_mode_params *data);
261 static	int		cdplay(struct cam_periph *periph, u_int32_t blk,
262 			       u_int32_t len);
263 static	int		cdreadsubchannel(struct cam_periph *periph,
264 					 u_int32_t mode, u_int32_t format,
265 					 int track,
266 					 struct cd_sub_channel_info *data,
267 					 u_int32_t len);
268 static	int		cdplaymsf(struct cam_periph *periph, u_int32_t startm,
269 				  u_int32_t starts, u_int32_t startf,
270 				  u_int32_t endm, u_int32_t ends,
271 				  u_int32_t endf);
272 static	int		cdplaytracks(struct cam_periph *periph,
273 				     u_int32_t strack, u_int32_t sindex,
274 				     u_int32_t etrack, u_int32_t eindex);
275 static	int		cdpause(struct cam_periph *periph, u_int32_t go);
276 static	int		cdstopunit(struct cam_periph *periph, u_int32_t eject);
277 static	int		cdstartunit(struct cam_periph *periph, int load);
278 static	int		cdsetspeed(struct cam_periph *periph,
279 				   u_int32_t rdspeed, u_int32_t wrspeed);
280 static	int		cdreportkey(struct cam_periph *periph,
281 				    struct dvd_authinfo *authinfo);
282 static	int		cdsendkey(struct cam_periph *periph,
283 				  struct dvd_authinfo *authinfo);
284 static	int		cdreaddvdstructure(struct cam_periph *periph,
285 					   struct dvd_struct *dvdstruct);
286 
287 static struct periph_driver cddriver =
288 {
289 	cdinit, "cd",
290 	TAILQ_HEAD_INITIALIZER(cddriver.units), /* generation */ 0
291 };
292 
293 PERIPHDRIVER_DECLARE(cd, cddriver);
294 
295 #ifndef	CD_DEFAULT_RETRY
296 #define	CD_DEFAULT_RETRY	4
297 #endif
298 #ifndef CHANGER_MIN_BUSY_SECONDS
299 #define CHANGER_MIN_BUSY_SECONDS	5
300 #endif
301 #ifndef CHANGER_MAX_BUSY_SECONDS
302 #define CHANGER_MAX_BUSY_SECONDS	15
303 #endif
304 
305 static int cd_retry_count = CD_DEFAULT_RETRY;
306 static int changer_min_busy_seconds = CHANGER_MIN_BUSY_SECONDS;
307 static int changer_max_busy_seconds = CHANGER_MAX_BUSY_SECONDS;
308 
309 static SYSCTL_NODE(_kern_cam, OID_AUTO, cd, CTLFLAG_RD, 0, "CAM CDROM driver");
310 static SYSCTL_NODE(_kern_cam_cd, OID_AUTO, changer, CTLFLAG_RD, 0,
311     "CD Changer");
312 SYSCTL_INT(_kern_cam_cd, OID_AUTO, retry_count, CTLFLAG_RW,
313            &cd_retry_count, 0, "Normal I/O retry count");
314 TUNABLE_INT("kern.cam.cd.retry_count", &cd_retry_count);
315 SYSCTL_INT(_kern_cam_cd_changer, OID_AUTO, min_busy_seconds, CTLFLAG_RW,
316 	   &changer_min_busy_seconds, 0, "Minimum changer scheduling quantum");
317 TUNABLE_INT("kern.cam.cd.changer.min_busy_seconds", &changer_min_busy_seconds);
318 SYSCTL_INT(_kern_cam_cd_changer, OID_AUTO, max_busy_seconds, CTLFLAG_RW,
319 	   &changer_max_busy_seconds, 0, "Maximum changer scheduling quantum");
320 TUNABLE_INT("kern.cam.cd.changer.max_busy_seconds", &changer_max_busy_seconds);
321 
322 struct cdchanger {
323 	path_id_t			 path_id;
324 	target_id_t			 target_id;
325 	int				 num_devices;
326 	struct camq			 devq;
327 	struct timeval			 start_time;
328 	struct cd_softc			 *cur_device;
329 	struct callout			 short_handle;
330 	struct callout			 long_handle;
331 	volatile cd_changer_flags	 flags;
332 	STAILQ_ENTRY(cdchanger)		 changer_links;
333 	STAILQ_HEAD(chdevlist, cd_softc) chluns;
334 };
335 
336 static struct mtx changerq_mtx;
337 static STAILQ_HEAD(changerlist, cdchanger) changerq;
338 static int num_changers;
339 
340 static MALLOC_DEFINE(M_SCSICD, "scsi_cd", "scsi_cd buffers");
341 
342 static void
343 cdinit(void)
344 {
345 	cam_status status;
346 
347 	mtx_init(&changerq_mtx, "cdchangerq", "SCSI CD Changer List", MTX_DEF);
348 	STAILQ_INIT(&changerq);
349 
350 	/*
351 	 * Install a global async callback.  This callback will
352 	 * receive async callbacks like "new device found".
353 	 */
354 	status = xpt_register_async(AC_FOUND_DEVICE, cdasync, NULL, NULL);
355 
356 	if (status != CAM_REQ_CMP) {
357 		printf("cd: Failed to attach master async callback "
358 		       "due to status 0x%x!\n", status);
359 	}
360 }
361 
362 static void
363 cdoninvalidate(struct cam_periph *periph)
364 {
365 	struct cd_softc *softc;
366 
367 	softc = (struct cd_softc *)periph->softc;
368 
369 	/*
370 	 * De-register any async callbacks.
371 	 */
372 	xpt_register_async(0, cdasync, periph, periph->path);
373 
374 	softc->flags |= CD_FLAG_INVALID;
375 
376 	/*
377 	 * Return all queued I/O with ENXIO.
378 	 * XXX Handle any transactions queued to the card
379 	 *     with XPT_ABORT_CCB.
380 	 */
381 	bioq_flush(&softc->bio_queue, NULL, ENXIO);
382 
383 	/*
384 	 * If this device is part of a changer, and it was scheduled
385 	 * to run, remove it from the run queue since we just nuked
386 	 * all of its scheduled I/O.
387 	 */
388 	if ((softc->flags & CD_FLAG_CHANGER)
389 	 && (softc->pinfo.index != CAM_UNQUEUED_INDEX))
390 		camq_remove(&softc->changer->devq, softc->pinfo.index);
391 
392 	disk_gone(softc->disk);
393 	xpt_print(periph->path, "lost device\n");
394 }
395 
396 static void
397 cdcleanup(struct cam_periph *periph)
398 {
399 	struct cd_softc *softc;
400 
401 	softc = (struct cd_softc *)periph->softc;
402 
403 	xpt_print(periph->path, "removing device entry\n");
404 
405 	/*
406 	 * In the queued, non-active case, the device in question
407 	 * has already been removed from the changer run queue.  Since this
408 	 * device is active, we need to de-activate it, and schedule
409 	 * another device to run.  (if there is another one to run)
410 	 */
411 	if ((softc->flags & CD_FLAG_CHANGER)
412 	 && (softc->flags & CD_FLAG_ACTIVE)) {
413 
414 		/*
415 		 * The purpose of the short timeout is soley to determine
416 		 * whether the current device has finished or not.  Well,
417 		 * since we're removing the active device, we know that it
418 		 * is finished.  So, get rid of the short timeout.
419 		 * Otherwise, if we're in the time period before the short
420 		 * timeout fires, and there are no other devices in the
421 		 * queue to run, there won't be any other device put in the
422 		 * active slot.  i.e., when we call cdrunchangerqueue()
423 		 * below, it won't do anything.  Then, when the short
424 		 * timeout fires, it'll look at the "current device", which
425 		 * we are free below, and possibly panic the kernel on a
426 		 * bogus pointer reference.
427 		 *
428 		 * The long timeout doesn't really matter, since we
429 		 * decrement the qfrozen_cnt to indicate that there is
430 		 * nothing in the active slot now.  Therefore, there won't
431 		 * be any bogus pointer references there.
432 		 */
433 		if (softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
434 			callout_stop(&softc->changer->short_handle);
435 			softc->changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
436 		}
437 		softc->changer->devq.qfrozen_cnt[0]--;
438 		softc->changer->flags |= CHANGER_MANUAL_CALL;
439 		cdrunchangerqueue(softc->changer);
440 	}
441 
442 	/*
443 	 * If we're removing the last device on the changer, go ahead and
444 	 * remove the changer device structure.
445 	 */
446 	if ((softc->flags & CD_FLAG_CHANGER)
447 	 && (--softc->changer->num_devices == 0)) {
448 
449 		/*
450 		 * Theoretically, there shouldn't be any timeouts left, but
451 		 * I'm not completely sure that that will be the case.  So,
452 		 * it won't hurt to check and see if there are any left.
453 		 */
454 		if (softc->changer->flags & CHANGER_TIMEOUT_SCHED) {
455 			callout_stop(&softc->changer->long_handle);
456 			softc->changer->flags &= ~CHANGER_TIMEOUT_SCHED;
457 		}
458 
459 		if (softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
460 			callout_stop(&softc->changer->short_handle);
461 			softc->changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
462 		}
463 
464 		mtx_lock(&changerq_mtx);
465 		STAILQ_REMOVE(&changerq, softc->changer, cdchanger,
466 			      changer_links);
467 		num_changers--;
468 		mtx_unlock(&changerq_mtx);
469 		xpt_print(periph->path, "removing changer entry\n");
470 		free(softc->changer, M_DEVBUF);
471 	}
472 	cam_periph_unlock(periph);
473 	if ((softc->flags & CD_FLAG_SCTX_INIT) != 0
474 	    && sysctl_ctx_free(&softc->sysctl_ctx) != 0) {
475 		xpt_print(periph->path, "can't remove sysctl context\n");
476 	}
477 
478 	disk_destroy(softc->disk);
479 	free(softc, M_DEVBUF);
480 	cam_periph_lock(periph);
481 }
482 
483 static void
484 cdasync(void *callback_arg, u_int32_t code,
485 	struct cam_path *path, void *arg)
486 {
487 	struct cam_periph *periph;
488 
489 	periph = (struct cam_periph *)callback_arg;
490 	switch (code) {
491 	case AC_FOUND_DEVICE:
492 	{
493 		struct ccb_getdev *cgd;
494 		cam_status status;
495 
496 		cgd = (struct ccb_getdev *)arg;
497 		if (cgd == NULL)
498 			break;
499 
500 		if (cgd->protocol != PROTO_SCSI)
501 			break;
502 
503 		if (SID_TYPE(&cgd->inq_data) != T_CDROM
504 		    && SID_TYPE(&cgd->inq_data) != T_WORM)
505 			break;
506 
507 		/*
508 		 * Allocate a peripheral instance for
509 		 * this device and start the probe
510 		 * process.
511 		 */
512 		status = cam_periph_alloc(cdregister, cdoninvalidate,
513 					  cdcleanup, cdstart,
514 					  "cd", CAM_PERIPH_BIO,
515 					  cgd->ccb_h.path, cdasync,
516 					  AC_FOUND_DEVICE, cgd);
517 
518 		if (status != CAM_REQ_CMP
519 		 && status != CAM_REQ_INPROG)
520 			printf("cdasync: Unable to attach new device "
521 			       "due to status 0x%x\n", status);
522 
523 		break;
524 	}
525 	case AC_SENT_BDR:
526 	case AC_BUS_RESET:
527 	{
528 		struct cd_softc *softc;
529 		struct ccb_hdr *ccbh;
530 
531 		softc = (struct cd_softc *)periph->softc;
532 		/*
533 		 * Don't fail on the expected unit attention
534 		 * that will occur.
535 		 */
536 		softc->flags |= CD_FLAG_RETRY_UA;
537 		LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
538 			ccbh->ccb_state |= CD_CCB_RETRY_UA;
539 		/* FALLTHROUGH */
540 	}
541 	default:
542 		cam_periph_async(periph, code, path, arg);
543 		break;
544 	}
545 }
546 
547 static void
548 cdsysctlinit(void *context, int pending)
549 {
550 	struct cam_periph *periph;
551 	struct cd_softc *softc;
552 	char tmpstr[80], tmpstr2[80];
553 
554 	periph = (struct cam_periph *)context;
555 	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
556 		return;
557 
558 	softc = (struct cd_softc *)periph->softc;
559 	snprintf(tmpstr, sizeof(tmpstr), "CAM CD unit %d", periph->unit_number);
560 	snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
561 
562 	sysctl_ctx_init(&softc->sysctl_ctx);
563 	softc->flags |= CD_FLAG_SCTX_INIT;
564 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
565 		SYSCTL_STATIC_CHILDREN(_kern_cam_cd), OID_AUTO,
566 		tmpstr2, CTLFLAG_RD, 0, tmpstr);
567 
568 	if (softc->sysctl_tree == NULL) {
569 		printf("cdsysctlinit: unable to allocate sysctl tree\n");
570 		cam_periph_release(periph);
571 		return;
572 	}
573 
574 	/*
575 	 * Now register the sysctl handler, so the user can the value on
576 	 * the fly.
577 	 */
578 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
579 		OID_AUTO, "minimum_cmd_size", CTLTYPE_INT | CTLFLAG_RW,
580 		&softc->minimum_command_size, 0, cdcmdsizesysctl, "I",
581 		"Minimum CDB size");
582 
583 	cam_periph_release(periph);
584 }
585 
586 /*
587  * We have a handler function for this so we can check the values when the
588  * user sets them, instead of every time we look at them.
589  */
590 static int
591 cdcmdsizesysctl(SYSCTL_HANDLER_ARGS)
592 {
593 	int error, value;
594 
595 	value = *(int *)arg1;
596 
597 	error = sysctl_handle_int(oidp, &value, 0, req);
598 
599 	if ((error != 0)
600 	 || (req->newptr == NULL))
601 		return (error);
602 
603 	/*
604 	 * The only real values we can have here are 6 or 10.  I don't
605 	 * really forsee having 12 be an option at any time in the future.
606 	 * So if the user sets something less than or equal to 6, we'll set
607 	 * it to 6.  If he sets something greater than 6, we'll set it to 10.
608 	 *
609 	 * I suppose we could just return an error here for the wrong values,
610 	 * but I don't think it's necessary to do so, as long as we can
611 	 * determine the user's intent without too much trouble.
612 	 */
613 	if (value < 6)
614 		value = 6;
615 	else if (value > 6)
616 		value = 10;
617 
618 	*(int *)arg1 = value;
619 
620 	return (0);
621 }
622 
623 static cam_status
624 cdregister(struct cam_periph *periph, void *arg)
625 {
626 	struct cd_softc *softc;
627 	struct ccb_pathinq cpi;
628 	struct ccb_getdev *cgd;
629 	char tmpstr[80];
630 	caddr_t match;
631 
632 	cgd = (struct ccb_getdev *)arg;
633 	if (periph == NULL) {
634 		printf("cdregister: periph was NULL!!\n");
635 		return(CAM_REQ_CMP_ERR);
636 	}
637 	if (cgd == NULL) {
638 		printf("cdregister: no getdev CCB, can't register device\n");
639 		return(CAM_REQ_CMP_ERR);
640 	}
641 
642 	softc = (struct cd_softc *)malloc(sizeof(*softc),M_DEVBUF,
643 	    M_NOWAIT | M_ZERO);
644 	if (softc == NULL) {
645 		printf("cdregister: Unable to probe new device. "
646 		       "Unable to allocate softc\n");
647 		return(CAM_REQ_CMP_ERR);
648 	}
649 
650 	LIST_INIT(&softc->pending_ccbs);
651 	STAILQ_INIT(&softc->mode_queue);
652 	softc->state = CD_STATE_PROBE;
653 	bioq_init(&softc->bio_queue);
654 	if (SID_IS_REMOVABLE(&cgd->inq_data))
655 		softc->flags |= CD_FLAG_DISC_REMOVABLE;
656 	if ((cgd->inq_data.flags & SID_CmdQue) != 0)
657 		softc->flags |= CD_FLAG_TAGGED_QUEUING;
658 
659 	periph->softc = softc;
660 	softc->periph = periph;
661 
662 	/*
663 	 * See if this device has any quirks.
664 	 */
665 	match = cam_quirkmatch((caddr_t)&cgd->inq_data,
666 			       (caddr_t)cd_quirk_table,
667 			       sizeof(cd_quirk_table)/sizeof(*cd_quirk_table),
668 			       sizeof(*cd_quirk_table), scsi_inquiry_match);
669 
670 	if (match != NULL)
671 		softc->quirks = ((struct cd_quirk_entry *)match)->quirks;
672 	else
673 		softc->quirks = CD_Q_NONE;
674 
675 	/* Check if the SIM does not want 6 byte commands */
676 	bzero(&cpi, sizeof(cpi));
677 	xpt_setup_ccb(&cpi.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
678 	cpi.ccb_h.func_code = XPT_PATH_INQ;
679 	xpt_action((union ccb *)&cpi);
680 	if (cpi.ccb_h.status == CAM_REQ_CMP && (cpi.hba_misc & PIM_NO_6_BYTE))
681 		softc->quirks |= CD_Q_10_BYTE_ONLY;
682 
683 	TASK_INIT(&softc->sysctl_task, 0, cdsysctlinit, periph);
684 
685 	/* The default is 6 byte commands, unless quirked otherwise */
686 	if (softc->quirks & CD_Q_10_BYTE_ONLY)
687 		softc->minimum_command_size = 10;
688 	else
689 		softc->minimum_command_size = 6;
690 
691 	/*
692 	 * Refcount and block open attempts until we are setup
693 	 * Can't block
694 	 */
695 	(void)cam_periph_hold(periph, PRIBIO);
696 	cam_periph_unlock(periph);
697 	/*
698 	 * Load the user's default, if any.
699 	 */
700 	snprintf(tmpstr, sizeof(tmpstr), "kern.cam.cd.%d.minimum_cmd_size",
701 		 periph->unit_number);
702 	TUNABLE_INT_FETCH(tmpstr, &softc->minimum_command_size);
703 
704 	/* 6 and 10 are the only permissible values here. */
705 	if (softc->minimum_command_size < 6)
706 		softc->minimum_command_size = 6;
707 	else if (softc->minimum_command_size > 6)
708 		softc->minimum_command_size = 10;
709 
710 	/*
711 	 * We need to register the statistics structure for this device,
712 	 * but we don't have the blocksize yet for it.  So, we register
713 	 * the structure and indicate that we don't have the blocksize
714 	 * yet.  Unlike other SCSI peripheral drivers, we explicitly set
715 	 * the device type here to be CDROM, rather than just ORing in
716 	 * the device type.  This is because this driver can attach to either
717 	 * CDROM or WORM devices, and we want this peripheral driver to
718 	 * show up in the devstat list as a CD peripheral driver, not a
719 	 * WORM peripheral driver.  WORM drives will also have the WORM
720 	 * driver attached to them.
721 	 */
722 	softc->disk = disk_alloc();
723 	softc->disk->d_devstat = devstat_new_entry("cd",
724 			  periph->unit_number, 0,
725 			  DEVSTAT_BS_UNAVAILABLE,
726 			  DEVSTAT_TYPE_CDROM |
727 			  XPORT_DEVSTAT_TYPE(cpi.transport),
728 			  DEVSTAT_PRIORITY_CD);
729 	softc->disk->d_open = cdopen;
730 	softc->disk->d_close = cdclose;
731 	softc->disk->d_strategy = cdstrategy;
732 	softc->disk->d_ioctl = cdioctl;
733 	softc->disk->d_name = "cd";
734 	cam_strvis(softc->disk->d_descr, cgd->inq_data.vendor,
735 	    sizeof(cgd->inq_data.vendor), sizeof(softc->disk->d_descr));
736 	strlcat(softc->disk->d_descr, " ", sizeof(softc->disk->d_descr));
737 	cam_strvis(&softc->disk->d_descr[strlen(softc->disk->d_descr)],
738 	    cgd->inq_data.product, sizeof(cgd->inq_data.product),
739 	    sizeof(softc->disk->d_descr) - strlen(softc->disk->d_descr));
740 	softc->disk->d_unit = periph->unit_number;
741 	softc->disk->d_drv1 = periph;
742 	if (cpi.maxio == 0)
743 		softc->disk->d_maxsize = DFLTPHYS;	/* traditional default */
744 	else if (cpi.maxio > MAXPHYS)
745 		softc->disk->d_maxsize = MAXPHYS;	/* for safety */
746 	else
747 		softc->disk->d_maxsize = cpi.maxio;
748 	softc->disk->d_flags = 0;
749 	softc->disk->d_hba_vendor = cpi.hba_vendor;
750 	softc->disk->d_hba_device = cpi.hba_device;
751 	softc->disk->d_hba_subvendor = cpi.hba_subvendor;
752 	softc->disk->d_hba_subdevice = cpi.hba_subdevice;
753 	disk_create(softc->disk, DISK_VERSION);
754 	cam_periph_lock(periph);
755 
756 	/*
757 	 * Add an async callback so that we get
758 	 * notified if this device goes away.
759 	 */
760 	xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE,
761 			   cdasync, periph, periph->path);
762 
763 	/*
764 	 * If the target lun is greater than 0, we most likely have a CD
765 	 * changer device.  Check the quirk entries as well, though, just
766 	 * in case someone has a CD tower with one lun per drive or
767 	 * something like that.  Also, if we know up front that a
768 	 * particular device is a changer, we can mark it as such starting
769 	 * with lun 0, instead of lun 1.  It shouldn't be necessary to have
770 	 * a quirk entry to define something as a changer, however.
771 	 */
772 	if (((cgd->ccb_h.target_lun > 0)
773 	  && ((softc->quirks & CD_Q_NO_CHANGER) == 0))
774 	 || ((softc->quirks & CD_Q_CHANGER) != 0)) {
775 		struct cdchanger *nchanger;
776 		struct cam_periph *nperiph;
777 		struct cam_path *path;
778 		cam_status status;
779 		int found;
780 
781 		/* Set the changer flag in the current device's softc */
782 		softc->flags |= CD_FLAG_CHANGER;
783 
784 		/*
785 		 * Now, look around for an existing changer device with the
786 		 * same path and target ID as the current device.
787 		 */
788 		mtx_lock(&changerq_mtx);
789 		for (found = 0,
790 		     nchanger = (struct cdchanger *)STAILQ_FIRST(&changerq);
791 		     nchanger != NULL;
792 		     nchanger = STAILQ_NEXT(nchanger, changer_links)){
793 			if ((nchanger->path_id == cgd->ccb_h.path_id)
794 			 && (nchanger->target_id == cgd->ccb_h.target_id)) {
795 				found = 1;
796 				break;
797 			}
798 		}
799 		mtx_unlock(&changerq_mtx);
800 
801 		/*
802 		 * If we found a matching entry, just add this device to
803 		 * the list of devices on this changer.
804 		 */
805 		if (found == 1) {
806 			struct chdevlist *chlunhead;
807 
808 			chlunhead = &nchanger->chluns;
809 
810 			/*
811 			 * XXX KDM look at consolidating this code with the
812 			 * code below in a separate function.
813 			 */
814 
815 			/*
816 			 * Create a path with lun id 0, and see if we can
817 			 * find a matching device
818 			 */
819 			status = xpt_create_path(&path, /*periph*/ periph,
820 						 cgd->ccb_h.path_id,
821 						 cgd->ccb_h.target_id, 0);
822 
823 			if ((status == CAM_REQ_CMP)
824 			 && ((nperiph = cam_periph_find(path, "cd")) != NULL)){
825 				struct cd_softc *nsoftc;
826 
827 				nsoftc = (struct cd_softc *)nperiph->softc;
828 
829 				if ((nsoftc->flags & CD_FLAG_CHANGER) == 0){
830 					nsoftc->flags |= CD_FLAG_CHANGER;
831 					nchanger->num_devices++;
832 					if (camq_resize(&nchanger->devq,
833 					   nchanger->num_devices)!=CAM_REQ_CMP){
834 						printf("cdregister: "
835 						       "camq_resize "
836 						       "failed, changer "
837 						       "support may "
838 						       "be messed up\n");
839 					}
840 					nsoftc->changer = nchanger;
841 					nsoftc->pinfo.index =CAM_UNQUEUED_INDEX;
842 
843 					STAILQ_INSERT_TAIL(&nchanger->chluns,
844 							  nsoftc,changer_links);
845 				}
846 				xpt_free_path(path);
847 			} else if (status == CAM_REQ_CMP)
848 				xpt_free_path(path);
849 			else {
850 				printf("cdregister: unable to allocate path\n"
851 				       "cdregister: changer support may be "
852 				       "broken\n");
853 			}
854 
855 			nchanger->num_devices++;
856 
857 			softc->changer = nchanger;
858 			softc->pinfo.index = CAM_UNQUEUED_INDEX;
859 
860 			if (camq_resize(&nchanger->devq,
861 			    nchanger->num_devices) != CAM_REQ_CMP) {
862 				printf("cdregister: camq_resize "
863 				       "failed, changer support may "
864 				       "be messed up\n");
865 			}
866 
867 			STAILQ_INSERT_TAIL(chlunhead, softc, changer_links);
868 		}
869 		/*
870 		 * In this case, we don't already have an entry for this
871 		 * particular changer, so we need to create one, add it to
872 		 * the queue, and queue this device on the list for this
873 		 * changer.  Before we queue this device, however, we need
874 		 * to search for lun id 0 on this target, and add it to the
875 		 * queue first, if it exists.  (and if it hasn't already
876 		 * been marked as part of the changer.)
877 		 */
878 		else {
879 			nchanger = malloc(sizeof(struct cdchanger),
880 				M_DEVBUF, M_NOWAIT | M_ZERO);
881 			if (nchanger == NULL) {
882 				softc->flags &= ~CD_FLAG_CHANGER;
883 				printf("cdregister: unable to malloc "
884 				       "changer structure\ncdregister: "
885 				       "changer support disabled\n");
886 
887 				/*
888 				 * Yes, gotos can be gross but in this case
889 				 * I think it's justified..
890 				 */
891 				goto cdregisterexit;
892 			}
893 			if (camq_init(&nchanger->devq, 1) != 0) {
894 				softc->flags &= ~CD_FLAG_CHANGER;
895 				printf("cdregister: changer support "
896 				       "disabled\n");
897 				goto cdregisterexit;
898 			}
899 
900 			nchanger->path_id = cgd->ccb_h.path_id;
901 			nchanger->target_id = cgd->ccb_h.target_id;
902 
903 			/* this is superfluous, but it makes things clearer */
904 			nchanger->num_devices = 0;
905 
906 			STAILQ_INIT(&nchanger->chluns);
907 
908 			callout_init_mtx(&nchanger->long_handle,
909 			    periph->sim->mtx, 0);
910 			callout_init_mtx(&nchanger->short_handle,
911 			    periph->sim->mtx, 0);
912 
913 			mtx_lock(&changerq_mtx);
914 			num_changers++;
915 			STAILQ_INSERT_TAIL(&changerq, nchanger,
916 					   changer_links);
917 			mtx_unlock(&changerq_mtx);
918 
919 			/*
920 			 * Create a path with lun id 0, and see if we can
921 			 * find a matching device
922 			 */
923 			status = xpt_create_path(&path, /*periph*/ periph,
924 						 cgd->ccb_h.path_id,
925 						 cgd->ccb_h.target_id, 0);
926 
927 			/*
928 			 * If we were able to allocate the path, and if we
929 			 * find a matching device and it isn't already
930 			 * marked as part of a changer, then we add it to
931 			 * the current changer.
932 			 */
933 			if ((status == CAM_REQ_CMP)
934 			 && ((nperiph = cam_periph_find(path, "cd")) != NULL)
935 			 && ((((struct cd_softc *)periph->softc)->flags &
936 			       CD_FLAG_CHANGER) == 0)) {
937 				struct cd_softc *nsoftc;
938 
939 				nsoftc = (struct cd_softc *)nperiph->softc;
940 
941 				nsoftc->flags |= CD_FLAG_CHANGER;
942 				nchanger->num_devices++;
943 				if (camq_resize(&nchanger->devq,
944 				    nchanger->num_devices) != CAM_REQ_CMP) {
945 					printf("cdregister: camq_resize "
946 					       "failed, changer support may "
947 					       "be messed up\n");
948 				}
949 				nsoftc->changer = nchanger;
950 				nsoftc->pinfo.index = CAM_UNQUEUED_INDEX;
951 
952 				STAILQ_INSERT_TAIL(&nchanger->chluns,
953 						   nsoftc, changer_links);
954 				xpt_free_path(path);
955 			} else if (status == CAM_REQ_CMP)
956 				xpt_free_path(path);
957 			else {
958 				printf("cdregister: unable to allocate path\n"
959 				       "cdregister: changer support may be "
960 				       "broken\n");
961 			}
962 
963 			softc->changer = nchanger;
964 			softc->pinfo.index = CAM_UNQUEUED_INDEX;
965 			nchanger->num_devices++;
966 			if (camq_resize(&nchanger->devq,
967 			    nchanger->num_devices) != CAM_REQ_CMP) {
968 				printf("cdregister: camq_resize "
969 				       "failed, changer support may "
970 				       "be messed up\n");
971 			}
972 			STAILQ_INSERT_TAIL(&nchanger->chluns, softc,
973 					   changer_links);
974 		}
975 	}
976 
977 cdregisterexit:
978 
979 	if ((softc->flags & CD_FLAG_CHANGER) == 0)
980 		xpt_schedule(periph, CAM_PRIORITY_DEV);
981 	else
982 		cdschedule(periph, CAM_PRIORITY_DEV);
983 
984 	return(CAM_REQ_CMP);
985 }
986 
987 static int
988 cdopen(struct disk *dp)
989 {
990 	struct cam_periph *periph;
991 	struct cd_softc *softc;
992 	int error;
993 
994 	periph = (struct cam_periph *)dp->d_drv1;
995 	if (periph == NULL)
996 		return (ENXIO);
997 
998 	softc = (struct cd_softc *)periph->softc;
999 
1000 	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
1001 		return(ENXIO);
1002 
1003 	cam_periph_lock(periph);
1004 
1005 	if (softc->flags & CD_FLAG_INVALID) {
1006 		cam_periph_unlock(periph);
1007 		cam_periph_release(periph);
1008 		return(ENXIO);
1009 	}
1010 
1011 	if ((error = cam_periph_hold(periph, PRIBIO | PCATCH)) != 0) {
1012 		cam_periph_unlock(periph);
1013 		cam_periph_release(periph);
1014 		return (error);
1015 	}
1016 
1017 	/*
1018 	 * Check for media, and set the appropriate flags.  We don't bail
1019 	 * if we don't have media, but then we don't allow anything but the
1020 	 * CDIOCEJECT/CDIOCCLOSE ioctls if there is no media.
1021 	 */
1022 	cdcheckmedia(periph);
1023 
1024 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdopen\n"));
1025 	cam_periph_unhold(periph);
1026 
1027 	/* Closes aren't symmetrical with opens, so fix up the refcounting. */
1028 	if ((softc->flags & CD_FLAG_OPEN) == 0) {
1029 		softc->flags |= CD_FLAG_OPEN;
1030 		cam_periph_unlock(periph);
1031 	} else {
1032 		cam_periph_unlock(periph);
1033 		cam_periph_release(periph);
1034 	}
1035 
1036 	return (0);
1037 }
1038 
1039 static int
1040 cdclose(struct disk *dp)
1041 {
1042 	struct 	cam_periph *periph;
1043 	struct	cd_softc *softc;
1044 
1045 	periph = (struct cam_periph *)dp->d_drv1;
1046 	if (periph == NULL)
1047 		return (ENXIO);
1048 
1049 	softc = (struct cd_softc *)periph->softc;
1050 
1051 	cam_periph_lock(periph);
1052 	cam_periph_hold(periph, PRIBIO);
1053 
1054 	if ((softc->flags & CD_FLAG_DISC_REMOVABLE) != 0)
1055 		cdprevent(periph, PR_ALLOW);
1056 
1057 	/*
1058 	 * Since we're closing this CD, mark the blocksize as unavailable.
1059 	 * It will be marked as available when the CD is opened again.
1060 	 */
1061 	softc->disk->d_devstat->flags |= DEVSTAT_BS_UNAVAILABLE;
1062 
1063 	/*
1064 	 * We'll check the media and toc again at the next open().
1065 	 */
1066 	softc->flags &= ~(CD_FLAG_VALID_MEDIA|CD_FLAG_VALID_TOC|CD_FLAG_OPEN);
1067 
1068 	cam_periph_unhold(periph);
1069 	cam_periph_unlock(periph);
1070 	cam_periph_release(periph);
1071 
1072 	return (0);
1073 }
1074 
1075 static void
1076 cdshorttimeout(void *arg)
1077 {
1078 	struct cdchanger *changer;
1079 
1080 	changer = (struct cdchanger *)arg;
1081 
1082 	/* Always clear the short timeout flag, since that's what we're in */
1083 	changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
1084 
1085 	/*
1086 	 * Check to see if there is any more pending or outstanding I/O for
1087 	 * this device.  If not, move it out of the active slot.
1088 	 */
1089 	if ((bioq_first(&changer->cur_device->bio_queue) == NULL)
1090 	 && (changer->cur_device->outstanding_cmds == 0)) {
1091 		changer->flags |= CHANGER_MANUAL_CALL;
1092 		cdrunchangerqueue(changer);
1093 	}
1094 }
1095 
1096 /*
1097  * This is a wrapper for xpt_schedule.  It only applies to changers.
1098  */
1099 static void
1100 cdschedule(struct cam_periph *periph, int priority)
1101 {
1102 	struct cd_softc *softc;
1103 
1104 	softc = (struct cd_softc *)periph->softc;
1105 
1106 	/*
1107 	 * If this device isn't currently queued, and if it isn't
1108 	 * the active device, then we queue this device and run the
1109 	 * changer queue if there is no timeout scheduled to do it.
1110 	 * If this device is the active device, just schedule it
1111 	 * to run again.  If this device is queued, there should be
1112 	 * a timeout in place already that will make sure it runs.
1113 	 */
1114 	if ((softc->pinfo.index == CAM_UNQUEUED_INDEX)
1115 	 && ((softc->flags & CD_FLAG_ACTIVE) == 0)) {
1116 		/*
1117 		 * We don't do anything with the priority here.
1118 		 * This is strictly a fifo queue.
1119 		 */
1120 		softc->pinfo.priority = CAM_PRIORITY_NORMAL;
1121 		softc->pinfo.generation = ++softc->changer->devq.generation;
1122 		camq_insert(&softc->changer->devq, (cam_pinfo *)softc);
1123 
1124 		/*
1125 		 * Since we just put a device in the changer queue,
1126 		 * check and see if there is a timeout scheduled for
1127 		 * this changer.  If so, let the timeout handle
1128 		 * switching this device into the active slot.  If
1129 		 * not, manually call the timeout routine to
1130 		 * bootstrap things.
1131 		 */
1132 		if (((softc->changer->flags & CHANGER_TIMEOUT_SCHED)==0)
1133 		 && ((softc->changer->flags & CHANGER_NEED_TIMEOUT)==0)
1134 		 && ((softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED)==0)){
1135 			softc->changer->flags |= CHANGER_MANUAL_CALL;
1136 			cdrunchangerqueue(softc->changer);
1137 		}
1138 	} else if ((softc->flags & CD_FLAG_ACTIVE)
1139 		&& ((softc->flags & CD_FLAG_SCHED_ON_COMP) == 0))
1140 		xpt_schedule(periph, priority);
1141 }
1142 
1143 static void
1144 cdrunchangerqueue(void *arg)
1145 {
1146 	struct cd_softc *softc;
1147 	struct cdchanger *changer;
1148 	int called_from_timeout;
1149 
1150 	changer = (struct cdchanger *)arg;
1151 
1152 	/*
1153 	 * If we have NOT been called from cdstrategy() or cddone(), and
1154 	 * instead from a timeout routine, go ahead and clear the
1155 	 * timeout flag.
1156 	 */
1157 	if ((changer->flags & CHANGER_MANUAL_CALL) == 0) {
1158 		changer->flags &= ~CHANGER_TIMEOUT_SCHED;
1159 		called_from_timeout = 1;
1160 	} else
1161 		called_from_timeout = 0;
1162 
1163 	/* Always clear the manual call flag */
1164 	changer->flags &= ~CHANGER_MANUAL_CALL;
1165 
1166 	/* nothing to do if the queue is empty */
1167 	if (changer->devq.entries <= 0) {
1168 		return;
1169 	}
1170 
1171 	/*
1172 	 * If the changer queue is frozen, that means we have an active
1173 	 * device.
1174 	 */
1175 	if (changer->devq.qfrozen_cnt[0] > 0) {
1176 
1177 		/*
1178 		 * We always need to reset the frozen count and clear the
1179 		 * active flag.
1180 		 */
1181 		changer->devq.qfrozen_cnt[0]--;
1182 		changer->cur_device->flags &= ~CD_FLAG_ACTIVE;
1183 		changer->cur_device->flags &= ~CD_FLAG_SCHED_ON_COMP;
1184 
1185 		if (changer->cur_device->outstanding_cmds > 0) {
1186 			changer->cur_device->flags |= CD_FLAG_SCHED_ON_COMP;
1187 			changer->cur_device->bufs_left =
1188 				changer->cur_device->outstanding_cmds;
1189 			if (called_from_timeout) {
1190 				callout_reset(&changer->long_handle,
1191 			            changer_max_busy_seconds * hz,
1192 				    cdrunchangerqueue, changer);
1193 				changer->flags |= CHANGER_TIMEOUT_SCHED;
1194 			}
1195 			return;
1196 		}
1197 
1198 		/*
1199 		 * Check to see whether the current device has any I/O left
1200 		 * to do.  If so, requeue it at the end of the queue.  If
1201 		 * not, there is no need to requeue it.
1202 		 */
1203 		if (bioq_first(&changer->cur_device->bio_queue) != NULL) {
1204 
1205 			changer->cur_device->pinfo.generation =
1206 				++changer->devq.generation;
1207 			camq_insert(&changer->devq,
1208 				(cam_pinfo *)changer->cur_device);
1209 		}
1210 	}
1211 
1212 	softc = (struct cd_softc *)camq_remove(&changer->devq, CAMQ_HEAD);
1213 
1214 	changer->cur_device = softc;
1215 
1216 	changer->devq.qfrozen_cnt[0]++;
1217 	softc->flags |= CD_FLAG_ACTIVE;
1218 
1219 	/* Just in case this device is waiting */
1220 	wakeup(&softc->changer);
1221 	xpt_schedule(softc->periph, CAM_PRIORITY_NORMAL);
1222 
1223 	/*
1224 	 * Get rid of any pending timeouts, and set a flag to schedule new
1225 	 * ones so this device gets its full time quantum.
1226 	 */
1227 	if (changer->flags & CHANGER_TIMEOUT_SCHED) {
1228 		callout_stop(&changer->long_handle);
1229 		changer->flags &= ~CHANGER_TIMEOUT_SCHED;
1230 	}
1231 
1232 	if (changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
1233 		callout_stop(&changer->short_handle);
1234 		changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
1235 	}
1236 
1237 	/*
1238 	 * We need to schedule timeouts, but we only do this after the
1239 	 * first transaction has completed.  This eliminates the changer
1240 	 * switch time.
1241 	 */
1242 	changer->flags |= CHANGER_NEED_TIMEOUT;
1243 }
1244 
1245 static void
1246 cdchangerschedule(struct cd_softc *softc)
1247 {
1248 	struct cdchanger *changer;
1249 
1250 	changer = softc->changer;
1251 
1252 	/*
1253 	 * If this is a changer, and this is the current device,
1254 	 * and this device has at least the minimum time quantum to
1255 	 * run, see if we can switch it out.
1256 	 */
1257 	if ((softc->flags & CD_FLAG_ACTIVE)
1258 	 && ((changer->flags & CHANGER_SHORT_TMOUT_SCHED) == 0)
1259 	 && ((changer->flags & CHANGER_NEED_TIMEOUT) == 0)) {
1260 		/*
1261 		 * We try three things here.  The first is that we
1262 		 * check to see whether the schedule on completion
1263 		 * flag is set.  If it is, we decrement the number
1264 		 * of buffers left, and if it's zero, we reschedule.
1265 		 * Next, we check to see whether the pending buffer
1266 		 * queue is empty and whether there are no
1267 		 * outstanding transactions.  If so, we reschedule.
1268 		 * Next, we see if the pending buffer queue is empty.
1269 		 * If it is, we set the number of buffers left to
1270 		 * the current active buffer count and set the
1271 		 * schedule on complete flag.
1272 		 */
1273 		if (softc->flags & CD_FLAG_SCHED_ON_COMP) {
1274 		 	if (--softc->bufs_left == 0) {
1275 				softc->changer->flags |=
1276 					CHANGER_MANUAL_CALL;
1277 				softc->flags &= ~CD_FLAG_SCHED_ON_COMP;
1278 				cdrunchangerqueue(softc->changer);
1279 			}
1280 		} else if ((bioq_first(&softc->bio_queue) == NULL)
1281 		        && (softc->outstanding_cmds == 0)) {
1282 			softc->changer->flags |= CHANGER_MANUAL_CALL;
1283 			cdrunchangerqueue(softc->changer);
1284 		}
1285 	} else if ((softc->changer->flags & CHANGER_NEED_TIMEOUT)
1286 		&& (softc->flags & CD_FLAG_ACTIVE)) {
1287 
1288 		/*
1289 		 * Now that the first transaction to this
1290 		 * particular device has completed, we can go ahead
1291 		 * and schedule our timeouts.
1292 		 */
1293 		if ((changer->flags & CHANGER_TIMEOUT_SCHED) == 0) {
1294 			callout_reset(&changer->long_handle,
1295 			    changer_max_busy_seconds * hz,
1296 			    cdrunchangerqueue, changer);
1297 			changer->flags |= CHANGER_TIMEOUT_SCHED;
1298 		} else
1299 			printf("cdchangerschedule: already have a long"
1300 			       " timeout!\n");
1301 
1302 		if ((changer->flags & CHANGER_SHORT_TMOUT_SCHED) == 0) {
1303 			callout_reset(&changer->short_handle,
1304 			    changer_min_busy_seconds * hz,
1305 			    cdshorttimeout, changer);
1306 			changer->flags |= CHANGER_SHORT_TMOUT_SCHED;
1307 		} else
1308 			printf("cdchangerschedule: already have a short "
1309 			       "timeout!\n");
1310 
1311 		/*
1312 		 * We just scheduled timeouts, no need to schedule
1313 		 * more.
1314 		 */
1315 		changer->flags &= ~CHANGER_NEED_TIMEOUT;
1316 
1317 	}
1318 }
1319 
1320 static int
1321 cdrunccb(union ccb *ccb, int (*error_routine)(union ccb *ccb,
1322 					      u_int32_t cam_flags,
1323 					      u_int32_t sense_flags),
1324 	 u_int32_t cam_flags, u_int32_t sense_flags)
1325 {
1326 	struct cd_softc *softc;
1327 	struct cam_periph *periph;
1328 	int error;
1329 
1330 	periph = xpt_path_periph(ccb->ccb_h.path);
1331 	softc = (struct cd_softc *)periph->softc;
1332 
1333 	error = cam_periph_runccb(ccb, error_routine, cam_flags, sense_flags,
1334 				  softc->disk->d_devstat);
1335 
1336 	if (softc->flags & CD_FLAG_CHANGER)
1337 		cdchangerschedule(softc);
1338 
1339 	return(error);
1340 }
1341 
1342 static union ccb *
1343 cdgetccb(struct cam_periph *periph, u_int32_t priority)
1344 {
1345 	struct cd_softc *softc;
1346 
1347 	softc = (struct cd_softc *)periph->softc;
1348 
1349 	if (softc->flags & CD_FLAG_CHANGER) {
1350 		/*
1351 		 * This should work the first time this device is woken up,
1352 		 * but just in case it doesn't, we use a while loop.
1353 		 */
1354 		while ((softc->flags & CD_FLAG_ACTIVE) == 0) {
1355 			/*
1356 			 * If this changer isn't already queued, queue it up.
1357 			 */
1358 			if (softc->pinfo.index == CAM_UNQUEUED_INDEX) {
1359 				softc->pinfo.priority = CAM_PRIORITY_NORMAL;
1360 				softc->pinfo.generation =
1361 					++softc->changer->devq.generation;
1362 				camq_insert(&softc->changer->devq,
1363 					    (cam_pinfo *)softc);
1364 			}
1365 			if (((softc->changer->flags & CHANGER_TIMEOUT_SCHED)==0)
1366 			 && ((softc->changer->flags & CHANGER_NEED_TIMEOUT)==0)
1367 			 && ((softc->changer->flags
1368 			      & CHANGER_SHORT_TMOUT_SCHED)==0)) {
1369 				softc->changer->flags |= CHANGER_MANUAL_CALL;
1370 				cdrunchangerqueue(softc->changer);
1371 			} else
1372 				msleep(&softc->changer, periph->sim->mtx,
1373 				    PRIBIO, "cgticb", 0);
1374 		}
1375 	}
1376 	return(cam_periph_getccb(periph, priority));
1377 }
1378 
1379 
1380 /*
1381  * Actually translate the requested transfer into one the physical driver
1382  * can understand.  The transfer is described by a buf and will include
1383  * only one physical transfer.
1384  */
1385 static void
1386 cdstrategy(struct bio *bp)
1387 {
1388 	struct cam_periph *periph;
1389 	struct cd_softc *softc;
1390 
1391 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1392 	if (periph == NULL) {
1393 		biofinish(bp, NULL, ENXIO);
1394 		return;
1395 	}
1396 
1397 	cam_periph_lock(periph);
1398 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdstrategy\n"));
1399 
1400 	softc = (struct cd_softc *)periph->softc;
1401 
1402 	/*
1403 	 * If the device has been made invalid, error out
1404 	 */
1405 	if ((softc->flags & CD_FLAG_INVALID)) {
1406 		cam_periph_unlock(periph);
1407 		biofinish(bp, NULL, ENXIO);
1408 		return;
1409 	}
1410 
1411         /*
1412 	 * If we don't have valid media, look for it before trying to
1413 	 * schedule the I/O.
1414 	 */
1415 	if ((softc->flags & CD_FLAG_VALID_MEDIA) == 0) {
1416 		int error;
1417 
1418 		error = cdcheckmedia(periph);
1419 		if (error != 0) {
1420 			cam_periph_unlock(periph);
1421 			biofinish(bp, NULL, error);
1422 			return;
1423 		}
1424 	}
1425 
1426 	/*
1427 	 * Place it in the queue of disk activities for this disk
1428 	 */
1429 	bioq_disksort(&softc->bio_queue, bp);
1430 
1431 	/*
1432 	 * Schedule ourselves for performing the work.  We do things
1433 	 * differently for changers.
1434 	 */
1435 	if ((softc->flags & CD_FLAG_CHANGER) == 0)
1436 		xpt_schedule(periph, CAM_PRIORITY_NORMAL);
1437 	else
1438 		cdschedule(periph, CAM_PRIORITY_NORMAL);
1439 
1440 	cam_periph_unlock(periph);
1441 	return;
1442 }
1443 
1444 static void
1445 cdstart(struct cam_periph *periph, union ccb *start_ccb)
1446 {
1447 	struct cd_softc *softc;
1448 	struct bio *bp;
1449 	struct ccb_scsiio *csio;
1450 	struct scsi_read_capacity_data *rcap;
1451 
1452 	softc = (struct cd_softc *)periph->softc;
1453 
1454 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdstart\n"));
1455 
1456 	switch (softc->state) {
1457 	case CD_STATE_NORMAL:
1458 	{
1459 		bp = bioq_first(&softc->bio_queue);
1460 		if (periph->immediate_priority <= periph->pinfo.priority) {
1461 			start_ccb->ccb_h.ccb_state = CD_CCB_WAITING;
1462 
1463 			SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1464 					  periph_links.sle);
1465 			periph->immediate_priority = CAM_PRIORITY_NONE;
1466 			wakeup(&periph->ccb_list);
1467 		} else if (bp == NULL) {
1468 			xpt_release_ccb(start_ccb);
1469 		} else {
1470 			bioq_remove(&softc->bio_queue, bp);
1471 
1472 			scsi_read_write(&start_ccb->csio,
1473 					/*retries*/ cd_retry_count,
1474 					/* cbfcnp */ cddone,
1475 					MSG_SIMPLE_Q_TAG,
1476 					/* read */bp->bio_cmd == BIO_READ,
1477 					/* byte2 */ 0,
1478 					/* minimum_cmd_size */ 10,
1479 					/* lba */ bp->bio_offset /
1480 					  softc->params.blksize,
1481 					bp->bio_bcount / softc->params.blksize,
1482 					/* data_ptr */ bp->bio_data,
1483 					/* dxfer_len */ bp->bio_bcount,
1484 					/* sense_len */ SSD_FULL_SIZE,
1485 					/* timeout */ 30000);
1486 			start_ccb->ccb_h.ccb_state = CD_CCB_BUFFER_IO;
1487 
1488 
1489 			LIST_INSERT_HEAD(&softc->pending_ccbs,
1490 					 &start_ccb->ccb_h, periph_links.le);
1491 			softc->outstanding_cmds++;
1492 
1493 			/* We expect a unit attention from this device */
1494 			if ((softc->flags & CD_FLAG_RETRY_UA) != 0) {
1495 				start_ccb->ccb_h.ccb_state |= CD_CCB_RETRY_UA;
1496 				softc->flags &= ~CD_FLAG_RETRY_UA;
1497 			}
1498 
1499 			start_ccb->ccb_h.ccb_bp = bp;
1500 			bp = bioq_first(&softc->bio_queue);
1501 
1502 			xpt_action(start_ccb);
1503 		}
1504 		if (bp != NULL) {
1505 			/* Have more work to do, so ensure we stay scheduled */
1506 			xpt_schedule(periph, CAM_PRIORITY_NORMAL);
1507 		}
1508 		break;
1509 	}
1510 	case CD_STATE_PROBE:
1511 	{
1512 
1513 		rcap = (struct scsi_read_capacity_data *)malloc(sizeof(*rcap),
1514 		    M_SCSICD, M_NOWAIT | M_ZERO);
1515 		if (rcap == NULL) {
1516 			xpt_print(periph->path,
1517 			    "cdstart: Couldn't malloc read_capacity data\n");
1518 			/* cd_free_periph??? */
1519 			break;
1520 		}
1521 		csio = &start_ccb->csio;
1522 		scsi_read_capacity(csio,
1523 				   /*retries*/ cd_retry_count,
1524 				   cddone,
1525 				   MSG_SIMPLE_Q_TAG,
1526 				   rcap,
1527 				   SSD_FULL_SIZE,
1528 				   /*timeout*/20000);
1529 		start_ccb->ccb_h.ccb_bp = NULL;
1530 		start_ccb->ccb_h.ccb_state = CD_CCB_PROBE;
1531 		xpt_action(start_ccb);
1532 		break;
1533 	}
1534 	}
1535 }
1536 
1537 static void
1538 cddone(struct cam_periph *periph, union ccb *done_ccb)
1539 {
1540 	struct cd_softc *softc;
1541 	struct ccb_scsiio *csio;
1542 
1543 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cddone\n"));
1544 
1545 	softc = (struct cd_softc *)periph->softc;
1546 	csio = &done_ccb->csio;
1547 
1548 	switch (csio->ccb_h.ccb_state & CD_CCB_TYPE_MASK) {
1549 	case CD_CCB_BUFFER_IO:
1550 	{
1551 		struct bio	*bp;
1552 		int		error;
1553 
1554 		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
1555 		error = 0;
1556 
1557 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1558 			int sf;
1559 
1560 			if ((done_ccb->ccb_h.ccb_state & CD_CCB_RETRY_UA) != 0)
1561 				sf = SF_RETRY_UA;
1562 			else
1563 				sf = 0;
1564 
1565 			error = cderror(done_ccb, CAM_RETRY_SELTO, sf);
1566 			if (error == ERESTART) {
1567 				/*
1568 				 * A retry was scheuled, so
1569 				 * just return.
1570 				 */
1571 				return;
1572 			}
1573 		}
1574 
1575 		if (error != 0) {
1576 			xpt_print(periph->path,
1577 			    "cddone: got error %#x back\n", error);
1578 			bioq_flush(&softc->bio_queue, NULL, EIO);
1579 			bp->bio_resid = bp->bio_bcount;
1580 			bp->bio_error = error;
1581 			bp->bio_flags |= BIO_ERROR;
1582 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1583 				cam_release_devq(done_ccb->ccb_h.path,
1584 					 /*relsim_flags*/0,
1585 					 /*reduction*/0,
1586 					 /*timeout*/0,
1587 					 /*getcount_only*/0);
1588 
1589 		} else {
1590 			bp->bio_resid = csio->resid;
1591 			bp->bio_error = 0;
1592 			if (bp->bio_resid != 0) {
1593 				/*
1594 				 * Short transfer ???
1595 				 * XXX: not sure this is correct for partial
1596 				 * transfers at EOM
1597 				 */
1598 				bp->bio_flags |= BIO_ERROR;
1599 			}
1600 		}
1601 
1602 		LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
1603 		softc->outstanding_cmds--;
1604 
1605 		if (softc->flags & CD_FLAG_CHANGER)
1606 			cdchangerschedule(softc);
1607 
1608 		biofinish(bp, NULL, 0);
1609 		break;
1610 	}
1611 	case CD_CCB_PROBE:
1612 	{
1613 		struct	   scsi_read_capacity_data *rdcap;
1614 		char	   announce_buf[120]; /*
1615 					       * Currently (9/30/97) the
1616 					       * longest possible announce
1617 					       * buffer is 108 bytes, for the
1618 					       * first error case below.
1619 					       * That is 39 bytes for the
1620 					       * basic string, 16 bytes for the
1621 					       * biggest sense key (hardware
1622 					       * error), 52 bytes for the
1623 					       * text of the largest sense
1624 					       * qualifier valid for a CDROM,
1625 					       * (0x72, 0x03 or 0x04,
1626 					       * 0x03), and one byte for the
1627 					       * null terminating character.
1628 					       * To allow for longer strings,
1629 					       * the announce buffer is 120
1630 					       * bytes.
1631 					       */
1632 		struct	   cd_params *cdp;
1633 
1634 		cdp = &softc->params;
1635 
1636 		rdcap = (struct scsi_read_capacity_data *)csio->data_ptr;
1637 
1638 		cdp->disksize = scsi_4btoul (rdcap->addr) + 1;
1639 		cdp->blksize = scsi_4btoul (rdcap->length);
1640 
1641 		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1642 
1643 			snprintf(announce_buf, sizeof(announce_buf),
1644 				"cd present [%lu x %lu byte records]",
1645 				cdp->disksize, (u_long)cdp->blksize);
1646 
1647 		} else {
1648 			int	error;
1649 			/*
1650 			 * Retry any UNIT ATTENTION type errors.  They
1651 			 * are expected at boot.
1652 			 */
1653 			error = cderror(done_ccb, CAM_RETRY_SELTO,
1654 					SF_RETRY_UA | SF_NO_PRINT);
1655 			if (error == ERESTART) {
1656 				/*
1657 				 * A retry was scheuled, so
1658 				 * just return.
1659 				 */
1660 				return;
1661 			} else if (error != 0) {
1662 
1663 				struct scsi_sense_data *sense;
1664 				int asc, ascq;
1665 				int sense_key, error_code;
1666 				int have_sense;
1667 				cam_status status;
1668 				struct ccb_getdev cgd;
1669 
1670 				/* Don't wedge this device's queue */
1671 				if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1672 					cam_release_devq(done_ccb->ccb_h.path,
1673 						 /*relsim_flags*/0,
1674 						 /*reduction*/0,
1675 						 /*timeout*/0,
1676 						 /*getcount_only*/0);
1677 
1678 				status = done_ccb->ccb_h.status;
1679 
1680 				xpt_setup_ccb(&cgd.ccb_h,
1681 					      done_ccb->ccb_h.path,
1682 					      CAM_PRIORITY_NORMAL);
1683 				cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1684 				xpt_action((union ccb *)&cgd);
1685 
1686 				if (((csio->ccb_h.flags & CAM_SENSE_PHYS) != 0)
1687 				 || ((csio->ccb_h.flags & CAM_SENSE_PTR) != 0)
1688 				 || ((status & CAM_AUTOSNS_VALID) == 0))
1689 					have_sense = FALSE;
1690 				else
1691 					have_sense = TRUE;
1692 
1693 				if (have_sense) {
1694 					sense = &csio->sense_data;
1695 					scsi_extract_sense_len(sense,
1696 					    csio->sense_len - csio->sense_resid,
1697 					    &error_code, &sense_key, &asc,
1698 					    &ascq, /*show_errors*/ 1);
1699 				}
1700 				/*
1701 				 * Attach to anything that claims to be a
1702 				 * CDROM or WORM device, as long as it
1703 				 * doesn't return a "Logical unit not
1704 				 * supported" (0x25) error.
1705 				 */
1706 				if ((have_sense) && (asc != 0x25)
1707 				 && (error_code == SSD_CURRENT_ERROR)) {
1708 					const char *sense_key_desc;
1709 					const char *asc_desc;
1710 
1711 					scsi_sense_desc(sense_key, asc, ascq,
1712 							&cgd.inq_data,
1713 							&sense_key_desc,
1714 							&asc_desc);
1715 					snprintf(announce_buf,
1716 					    sizeof(announce_buf),
1717 						"Attempt to query device "
1718 						"size failed: %s, %s",
1719 						sense_key_desc,
1720 						asc_desc);
1721  				} else if ((have_sense == 0)
1722  				      && ((status & CAM_STATUS_MASK) ==
1723  					   CAM_SCSI_STATUS_ERROR)
1724  				      && (csio->scsi_status ==
1725  					  SCSI_STATUS_BUSY)) {
1726  					snprintf(announce_buf,
1727  					    sizeof(announce_buf),
1728  					    "Attempt to query device "
1729  					    "size failed: SCSI Status: %s",
1730 					    scsi_status_string(csio));
1731 				} else if (SID_TYPE(&cgd.inq_data) == T_CDROM) {
1732 					/*
1733 					 * We only print out an error for
1734 					 * CDROM type devices.  For WORM
1735 					 * devices, we don't print out an
1736 					 * error since a few WORM devices
1737 					 * don't support CDROM commands.
1738 					 * If we have sense information, go
1739 					 * ahead and print it out.
1740 					 * Otherwise, just say that we
1741 					 * couldn't attach.
1742 					 */
1743 
1744 					/*
1745 					 * Just print out the error, not
1746 					 * the full probe message, when we
1747 					 * don't attach.
1748 					 */
1749 					if (have_sense)
1750 						scsi_sense_print(
1751 							&done_ccb->csio);
1752 					else {
1753 						xpt_print(periph->path,
1754 						    "got CAM status %#x\n",
1755 						    done_ccb->ccb_h.status);
1756 					}
1757 					xpt_print(periph->path, "fatal error, "
1758 					    "failed to attach to device\n");
1759 					/*
1760 					 * Invalidate this peripheral.
1761 					 */
1762 					cam_periph_invalidate(periph);
1763 
1764 					announce_buf[0] = '\0';
1765 				} else {
1766 
1767 					/*
1768 					 * Invalidate this peripheral.
1769 					 */
1770 					cam_periph_invalidate(periph);
1771 					announce_buf[0] = '\0';
1772 				}
1773 			}
1774 		}
1775 		free(rdcap, M_SCSICD);
1776 		if (announce_buf[0] != '\0') {
1777 			xpt_announce_periph(periph, announce_buf);
1778 			if (softc->flags & CD_FLAG_CHANGER)
1779 				cdchangerschedule(softc);
1780 			/*
1781 			 * Create our sysctl variables, now that we know
1782 			 * we have successfully attached.
1783 			 */
1784 			taskqueue_enqueue(taskqueue_thread,&softc->sysctl_task);
1785 		}
1786 		softc->state = CD_STATE_NORMAL;
1787 		/*
1788 		 * Since our peripheral may be invalidated by an error
1789 		 * above or an external event, we must release our CCB
1790 		 * before releasing the probe lock on the peripheral.
1791 		 * The peripheral will only go away once the last lock
1792 		 * is removed, and we need it around for the CCB release
1793 		 * operation.
1794 		 */
1795 		xpt_release_ccb(done_ccb);
1796 		cam_periph_unhold(periph);
1797 		return;
1798 	}
1799 	case CD_CCB_WAITING:
1800 	{
1801 		/* Caller will release the CCB */
1802 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1803 			  ("trying to wakeup ccbwait\n"));
1804 
1805 		wakeup(&done_ccb->ccb_h.cbfcnp);
1806 		return;
1807 	}
1808 	default:
1809 		break;
1810 	}
1811 	xpt_release_ccb(done_ccb);
1812 }
1813 
1814 static union cd_pages *
1815 cdgetpage(struct cd_mode_params *mode_params)
1816 {
1817 	union cd_pages *page;
1818 
1819 	if (mode_params->cdb_size == 10)
1820 		page = (union cd_pages *)find_mode_page_10(
1821 			(struct scsi_mode_header_10 *)mode_params->mode_buf);
1822 	else
1823 		page = (union cd_pages *)find_mode_page_6(
1824 			(struct scsi_mode_header_6 *)mode_params->mode_buf);
1825 
1826 	return (page);
1827 }
1828 
1829 static int
1830 cdgetpagesize(int page_num)
1831 {
1832 	int i;
1833 
1834 	for (i = 0; i < (sizeof(cd_page_size_table)/
1835 	     sizeof(cd_page_size_table[0])); i++) {
1836 		if (cd_page_size_table[i].page == page_num)
1837 			return (cd_page_size_table[i].page_size);
1838 	}
1839 
1840 	return (-1);
1841 }
1842 
1843 static int
1844 cdioctl(struct disk *dp, u_long cmd, void *addr, int flag, struct thread *td)
1845 {
1846 
1847 	struct 	cam_periph *periph;
1848 	struct	cd_softc *softc;
1849 	int	nocopyout, error = 0;
1850 
1851 	periph = (struct cam_periph *)dp->d_drv1;
1852 	if (periph == NULL)
1853 		return(ENXIO);
1854 
1855 	cam_periph_lock(periph);
1856 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdioctl\n"));
1857 
1858 	softc = (struct cd_softc *)periph->softc;
1859 
1860 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1861 		  ("trying to do ioctl %#lx\n", cmd));
1862 
1863 	if ((error = cam_periph_hold(periph, PRIBIO | PCATCH)) != 0) {
1864 		cam_periph_unlock(periph);
1865 		cam_periph_release(periph);
1866 		return (error);
1867 	}
1868 
1869 	/*
1870 	 * If we don't have media loaded, check for it.  If still don't
1871 	 * have media loaded, we can only do a load or eject.
1872 	 *
1873 	 * We only care whether media is loaded if this is a cd-specific ioctl
1874 	 * (thus the IOCGROUP check below).  Note that this will break if
1875 	 * anyone adds any ioctls into the switch statement below that don't
1876 	 * have their ioctl group set to 'c'.
1877 	 */
1878 	if (((softc->flags & CD_FLAG_VALID_MEDIA) == 0)
1879 	 && ((cmd != CDIOCCLOSE)
1880 	  && (cmd != CDIOCEJECT))
1881 	 && (IOCGROUP(cmd) == 'c')) {
1882 		error = cdcheckmedia(periph);
1883 		if (error != 0) {
1884 			cam_periph_unhold(periph);
1885 			cam_periph_unlock(periph);
1886 			return (error);
1887 		}
1888 	}
1889 	/*
1890 	 * Drop the lock here so later mallocs can use WAITOK.  The periph
1891 	 * is essentially locked still with the cam_periph_hold call above.
1892 	 */
1893 	cam_periph_unlock(periph);
1894 
1895 	nocopyout = 0;
1896 	switch (cmd) {
1897 
1898 	case CDIOCPLAYTRACKS:
1899 		{
1900 			struct ioc_play_track *args
1901 			    = (struct ioc_play_track *) addr;
1902 			struct cd_mode_params params;
1903 			union cd_pages *page;
1904 
1905 			params.alloc_len = sizeof(union cd_mode_data_6_10);
1906 			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
1907 						 M_WAITOK | M_ZERO);
1908 
1909 			cam_periph_lock(periph);
1910 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1911 				  ("trying to do CDIOCPLAYTRACKS\n"));
1912 
1913 			error = cdgetmode(periph, &params, AUDIO_PAGE);
1914 			if (error) {
1915 				free(params.mode_buf, M_SCSICD);
1916 				cam_periph_unlock(periph);
1917 				break;
1918 			}
1919 			page = cdgetpage(&params);
1920 
1921 			page->audio.flags &= ~CD_PA_SOTC;
1922 			page->audio.flags |= CD_PA_IMMED;
1923 			error = cdsetmode(periph, &params);
1924 			free(params.mode_buf, M_SCSICD);
1925 			if (error) {
1926 				cam_periph_unlock(periph);
1927 				break;
1928 			}
1929 
1930 			/*
1931 			 * This was originally implemented with the PLAY
1932 			 * AUDIO TRACK INDEX command, but that command was
1933 			 * deprecated after SCSI-2.  Most (all?) SCSI CDROM
1934 			 * drives support it but ATAPI and ATAPI-derivative
1935 			 * drives don't seem to support it.  So we keep a
1936 			 * cache of the table of contents and translate
1937 			 * track numbers to MSF format.
1938 			 */
1939 			if (softc->flags & CD_FLAG_VALID_TOC) {
1940 				union msf_lba *sentry, *eentry;
1941 				int st, et;
1942 
1943 				if (args->end_track <
1944 				    softc->toc.header.ending_track + 1)
1945 					args->end_track++;
1946 				if (args->end_track >
1947 				    softc->toc.header.ending_track + 1)
1948 					args->end_track =
1949 					    softc->toc.header.ending_track + 1;
1950 				st = args->start_track -
1951 					softc->toc.header.starting_track;
1952 				et = args->end_track -
1953 					softc->toc.header.starting_track;
1954 				if ((st < 0)
1955 				 || (et < 0)
1956 			 	 || (st > (softc->toc.header.ending_track -
1957 				     softc->toc.header.starting_track))) {
1958 					error = EINVAL;
1959 					break;
1960 				}
1961 				sentry = &softc->toc.entries[st].addr;
1962 				eentry = &softc->toc.entries[et].addr;
1963 				error = cdplaymsf(periph,
1964 						  sentry->msf.minute,
1965 						  sentry->msf.second,
1966 						  sentry->msf.frame,
1967 						  eentry->msf.minute,
1968 						  eentry->msf.second,
1969 						  eentry->msf.frame);
1970 			} else {
1971 				/*
1972 				 * If we don't have a valid TOC, try the
1973 				 * play track index command.  It is part of
1974 				 * the SCSI-2 spec, but was removed in the
1975 				 * MMC specs.  ATAPI and ATAPI-derived
1976 				 * drives don't support it.
1977 				 */
1978 				if (softc->quirks & CD_Q_BCD_TRACKS) {
1979 					args->start_track =
1980 						bin2bcd(args->start_track);
1981 					args->end_track =
1982 						bin2bcd(args->end_track);
1983 				}
1984 				error = cdplaytracks(periph,
1985 						     args->start_track,
1986 						     args->start_index,
1987 						     args->end_track,
1988 						     args->end_index);
1989 			}
1990 			cam_periph_unlock(periph);
1991 		}
1992 		break;
1993 	case CDIOCPLAYMSF:
1994 		{
1995 			struct ioc_play_msf *args
1996 				= (struct ioc_play_msf *) addr;
1997 			struct cd_mode_params params;
1998 			union cd_pages *page;
1999 
2000 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2001 			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2002 						 M_WAITOK | M_ZERO);
2003 
2004 			cam_periph_lock(periph);
2005 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2006 				  ("trying to do CDIOCPLAYMSF\n"));
2007 
2008 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2009 			if (error) {
2010 				free(params.mode_buf, M_SCSICD);
2011 				cam_periph_unlock(periph);
2012 				break;
2013 			}
2014 			page = cdgetpage(&params);
2015 
2016 			page->audio.flags &= ~CD_PA_SOTC;
2017 			page->audio.flags |= CD_PA_IMMED;
2018 			error = cdsetmode(periph, &params);
2019 			free(params.mode_buf, M_SCSICD);
2020 			if (error) {
2021 				cam_periph_unlock(periph);
2022 				break;
2023 			}
2024 			error = cdplaymsf(periph,
2025 					  args->start_m,
2026 					  args->start_s,
2027 					  args->start_f,
2028 					  args->end_m,
2029 					  args->end_s,
2030 					  args->end_f);
2031 			cam_periph_unlock(periph);
2032 		}
2033 		break;
2034 	case CDIOCPLAYBLOCKS:
2035 		{
2036 			struct ioc_play_blocks *args
2037 				= (struct ioc_play_blocks *) addr;
2038 			struct cd_mode_params params;
2039 			union cd_pages *page;
2040 
2041 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2042 			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2043 						 M_WAITOK | M_ZERO);
2044 
2045 			cam_periph_lock(periph);
2046 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2047 				  ("trying to do CDIOCPLAYBLOCKS\n"));
2048 
2049 
2050 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2051 			if (error) {
2052 				free(params.mode_buf, M_SCSICD);
2053 				cam_periph_unlock(periph);
2054 				break;
2055 			}
2056 			page = cdgetpage(&params);
2057 
2058 			page->audio.flags &= ~CD_PA_SOTC;
2059 			page->audio.flags |= CD_PA_IMMED;
2060 			error = cdsetmode(periph, &params);
2061 			free(params.mode_buf, M_SCSICD);
2062 			if (error) {
2063 				cam_periph_unlock(periph);
2064 				break;
2065 			}
2066 			error = cdplay(periph, args->blk, args->len);
2067 			cam_periph_unlock(periph);
2068 		}
2069 		break;
2070 	case CDIOCREADSUBCHANNEL_SYSSPACE:
2071 		nocopyout = 1;
2072 		/* Fallthrough */
2073 	case CDIOCREADSUBCHANNEL:
2074 		{
2075 			struct ioc_read_subchannel *args
2076 				= (struct ioc_read_subchannel *) addr;
2077 			struct cd_sub_channel_info *data;
2078 			u_int32_t len = args->data_len;
2079 
2080 			data = malloc(sizeof(struct cd_sub_channel_info),
2081 				      M_SCSICD, M_WAITOK | M_ZERO);
2082 
2083 			cam_periph_lock(periph);
2084 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2085 				  ("trying to do CDIOCREADSUBCHANNEL\n"));
2086 
2087 			if ((len > sizeof(struct cd_sub_channel_info)) ||
2088 			    (len < sizeof(struct cd_sub_channel_header))) {
2089 				printf(
2090 					"scsi_cd: cdioctl: "
2091 					"cdioreadsubchannel: error, len=%d\n",
2092 					len);
2093 				error = EINVAL;
2094 				free(data, M_SCSICD);
2095 				cam_periph_unlock(periph);
2096 				break;
2097 			}
2098 
2099 			if (softc->quirks & CD_Q_BCD_TRACKS)
2100 				args->track = bin2bcd(args->track);
2101 
2102 			error = cdreadsubchannel(periph, args->address_format,
2103 				args->data_format, args->track, data, len);
2104 
2105 			if (error) {
2106 				free(data, M_SCSICD);
2107 				cam_periph_unlock(periph);
2108 	 			break;
2109 			}
2110 			if (softc->quirks & CD_Q_BCD_TRACKS)
2111 				data->what.track_info.track_number =
2112 				    bcd2bin(data->what.track_info.track_number);
2113 			len = min(len, ((data->header.data_len[0] << 8) +
2114 				data->header.data_len[1] +
2115 				sizeof(struct cd_sub_channel_header)));
2116 			cam_periph_unlock(periph);
2117 			if (nocopyout == 0) {
2118 				if (copyout(data, args->data, len) != 0) {
2119 					error = EFAULT;
2120 				}
2121 			} else {
2122 				bcopy(data, args->data, len);
2123 			}
2124 			free(data, M_SCSICD);
2125 		}
2126 		break;
2127 
2128 	case CDIOREADTOCHEADER:
2129 		{
2130 			struct ioc_toc_header *th;
2131 
2132 			th = malloc(sizeof(struct ioc_toc_header), M_SCSICD,
2133 				    M_WAITOK | M_ZERO);
2134 
2135 			cam_periph_lock(periph);
2136 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2137 				  ("trying to do CDIOREADTOCHEADER\n"));
2138 
2139 			error = cdreadtoc(periph, 0, 0, (u_int8_t *)th,
2140 				          sizeof (*th), /*sense_flags*/SF_NO_PRINT);
2141 			if (error) {
2142 				free(th, M_SCSICD);
2143 				cam_periph_unlock(periph);
2144 				break;
2145 			}
2146 			if (softc->quirks & CD_Q_BCD_TRACKS) {
2147 				/* we are going to have to convert the BCD
2148 				 * encoding on the cd to what is expected
2149 				 */
2150 				th->starting_track =
2151 					bcd2bin(th->starting_track);
2152 				th->ending_track = bcd2bin(th->ending_track);
2153 			}
2154 			th->len = ntohs(th->len);
2155 			bcopy(th, addr, sizeof(*th));
2156 			free(th, M_SCSICD);
2157 			cam_periph_unlock(periph);
2158 		}
2159 		break;
2160 	case CDIOREADTOCENTRYS:
2161 		{
2162 			struct cd_tocdata *data;
2163 			struct cd_toc_single *lead;
2164 			struct ioc_read_toc_entry *te =
2165 				(struct ioc_read_toc_entry *) addr;
2166 			struct ioc_toc_header *th;
2167 			u_int32_t len, readlen, idx, num;
2168 			u_int32_t starting_track = te->starting_track;
2169 
2170 			data = malloc(sizeof(*data), M_SCSICD, M_WAITOK | M_ZERO);
2171 			lead = malloc(sizeof(*lead), M_SCSICD, M_WAITOK | M_ZERO);
2172 
2173 			cam_periph_lock(periph);
2174 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2175 				  ("trying to do CDIOREADTOCENTRYS\n"));
2176 
2177 			if (te->data_len < sizeof(struct cd_toc_entry)
2178 			 || (te->data_len % sizeof(struct cd_toc_entry)) != 0
2179 			 || (te->address_format != CD_MSF_FORMAT
2180 			  && te->address_format != CD_LBA_FORMAT)) {
2181 				error = EINVAL;
2182 				printf("scsi_cd: error in readtocentries, "
2183 				       "returning EINVAL\n");
2184 				free(data, M_SCSICD);
2185 				free(lead, M_SCSICD);
2186 				cam_periph_unlock(periph);
2187 				break;
2188 			}
2189 
2190 			th = &data->header;
2191 			error = cdreadtoc(periph, 0, 0, (u_int8_t *)th,
2192 					  sizeof (*th), /*sense_flags*/0);
2193 			if (error) {
2194 				free(data, M_SCSICD);
2195 				free(lead, M_SCSICD);
2196 				cam_periph_unlock(periph);
2197 				break;
2198 			}
2199 
2200 			if (softc->quirks & CD_Q_BCD_TRACKS) {
2201 				/* we are going to have to convert the BCD
2202 				 * encoding on the cd to what is expected
2203 				 */
2204 				th->starting_track =
2205 				    bcd2bin(th->starting_track);
2206 				th->ending_track = bcd2bin(th->ending_track);
2207 			}
2208 
2209 			if (starting_track == 0)
2210 				starting_track = th->starting_track;
2211 			else if (starting_track == LEADOUT)
2212 				starting_track = th->ending_track + 1;
2213 			else if (starting_track < th->starting_track ||
2214 				 starting_track > th->ending_track + 1) {
2215 				printf("scsi_cd: error in readtocentries, "
2216 				       "returning EINVAL\n");
2217 				free(data, M_SCSICD);
2218 				free(lead, M_SCSICD);
2219 				cam_periph_unlock(periph);
2220 				error = EINVAL;
2221 				break;
2222 			}
2223 
2224 			/* calculate reading length without leadout entry */
2225 			readlen = (th->ending_track - starting_track + 1) *
2226 				  sizeof(struct cd_toc_entry);
2227 
2228 			/* and with leadout entry */
2229 			len = readlen + sizeof(struct cd_toc_entry);
2230 			if (te->data_len < len) {
2231 				len = te->data_len;
2232 				if (readlen > len)
2233 					readlen = len;
2234 			}
2235 			if (len > sizeof(data->entries)) {
2236 				printf("scsi_cd: error in readtocentries, "
2237 				       "returning EINVAL\n");
2238 				error = EINVAL;
2239 				free(data, M_SCSICD);
2240 				free(lead, M_SCSICD);
2241 				cam_periph_unlock(periph);
2242 				break;
2243 			}
2244 			num = len / sizeof(struct cd_toc_entry);
2245 
2246 			if (readlen > 0) {
2247 				error = cdreadtoc(periph, te->address_format,
2248 						  starting_track,
2249 						  (u_int8_t *)data,
2250 						  readlen + sizeof (*th),
2251 						  /*sense_flags*/0);
2252 				if (error) {
2253 					free(data, M_SCSICD);
2254 					free(lead, M_SCSICD);
2255 					cam_periph_unlock(periph);
2256 					break;
2257 				}
2258 			}
2259 
2260 			/* make leadout entry if needed */
2261 			idx = starting_track + num - 1;
2262 			if (softc->quirks & CD_Q_BCD_TRACKS)
2263 				th->ending_track = bcd2bin(th->ending_track);
2264 			if (idx == th->ending_track + 1) {
2265 				error = cdreadtoc(periph, te->address_format,
2266 						  LEADOUT, (u_int8_t *)lead,
2267 						  sizeof(*lead),
2268 						  /*sense_flags*/0);
2269 				if (error) {
2270 					free(data, M_SCSICD);
2271 					free(lead, M_SCSICD);
2272 					cam_periph_unlock(periph);
2273 					break;
2274 				}
2275 				data->entries[idx - starting_track] =
2276 					lead->entry;
2277 			}
2278 			if (softc->quirks & CD_Q_BCD_TRACKS) {
2279 				for (idx = 0; idx < num - 1; idx++) {
2280 					data->entries[idx].track =
2281 					    bcd2bin(data->entries[idx].track);
2282 				}
2283 			}
2284 
2285 			cam_periph_unlock(periph);
2286 			error = copyout(data->entries, te->data, len);
2287 			free(data, M_SCSICD);
2288 			free(lead, M_SCSICD);
2289 		}
2290 		break;
2291 	case CDIOREADTOCENTRY:
2292 		{
2293 			struct cd_toc_single *data;
2294 			struct ioc_read_toc_single_entry *te =
2295 				(struct ioc_read_toc_single_entry *) addr;
2296 			struct ioc_toc_header *th;
2297 			u_int32_t track;
2298 
2299 			data = malloc(sizeof(*data), M_SCSICD, M_WAITOK | M_ZERO);
2300 
2301 			cam_periph_lock(periph);
2302 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2303 				  ("trying to do CDIOREADTOCENTRY\n"));
2304 
2305 			if (te->address_format != CD_MSF_FORMAT
2306 			    && te->address_format != CD_LBA_FORMAT) {
2307 				printf("error in readtocentry, "
2308 				       " returning EINVAL\n");
2309 				free(data, M_SCSICD);
2310 				error = EINVAL;
2311 				cam_periph_unlock(periph);
2312 				break;
2313 			}
2314 
2315 			th = &data->header;
2316 			error = cdreadtoc(periph, 0, 0, (u_int8_t *)th,
2317 					  sizeof (*th), /*sense_flags*/0);
2318 			if (error) {
2319 				free(data, M_SCSICD);
2320 				cam_periph_unlock(periph);
2321 				break;
2322 			}
2323 
2324 			if (softc->quirks & CD_Q_BCD_TRACKS) {
2325 				/* we are going to have to convert the BCD
2326 				 * encoding on the cd to what is expected
2327 				 */
2328 				th->starting_track =
2329 				    bcd2bin(th->starting_track);
2330 				th->ending_track = bcd2bin(th->ending_track);
2331 			}
2332 			track = te->track;
2333 			if (track == 0)
2334 				track = th->starting_track;
2335 			else if (track == LEADOUT)
2336 				/* OK */;
2337 			else if (track < th->starting_track ||
2338 				 track > th->ending_track + 1) {
2339 				printf("error in readtocentry, "
2340 				       " returning EINVAL\n");
2341 				free(data, M_SCSICD);
2342 				error = EINVAL;
2343 				cam_periph_unlock(periph);
2344 				break;
2345 			}
2346 
2347 			error = cdreadtoc(periph, te->address_format, track,
2348 					  (u_int8_t *)data, sizeof(*data),
2349 					  /*sense_flags*/0);
2350 			if (error) {
2351 				free(data, M_SCSICD);
2352 				cam_periph_unlock(periph);
2353 				break;
2354 			}
2355 
2356 			if (softc->quirks & CD_Q_BCD_TRACKS)
2357 				data->entry.track = bcd2bin(data->entry.track);
2358 			bcopy(&data->entry, &te->entry,
2359 			      sizeof(struct cd_toc_entry));
2360 			free(data, M_SCSICD);
2361 			cam_periph_unlock(periph);
2362 		}
2363 		break;
2364 	case CDIOCSETPATCH:
2365 		{
2366 			struct ioc_patch *arg = (struct ioc_patch *)addr;
2367 			struct cd_mode_params params;
2368 			union cd_pages *page;
2369 
2370 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2371 			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2372 						 M_WAITOK | M_ZERO);
2373 
2374 			cam_periph_lock(periph);
2375 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2376 				  ("trying to do CDIOCSETPATCH\n"));
2377 
2378 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2379 			if (error) {
2380 				free(params.mode_buf, M_SCSICD);
2381 				cam_periph_unlock(periph);
2382 				break;
2383 			}
2384 			page = cdgetpage(&params);
2385 
2386 			page->audio.port[LEFT_PORT].channels =
2387 				arg->patch[0];
2388 			page->audio.port[RIGHT_PORT].channels =
2389 				arg->patch[1];
2390 			page->audio.port[2].channels = arg->patch[2];
2391 			page->audio.port[3].channels = arg->patch[3];
2392 			error = cdsetmode(periph, &params);
2393 			free(params.mode_buf, M_SCSICD);
2394 			cam_periph_unlock(periph);
2395 		}
2396 		break;
2397 	case CDIOCGETVOL:
2398 		{
2399 			struct ioc_vol *arg = (struct ioc_vol *) addr;
2400 			struct cd_mode_params params;
2401 			union cd_pages *page;
2402 
2403 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2404 			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2405 						 M_WAITOK | M_ZERO);
2406 
2407 			cam_periph_lock(periph);
2408 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2409 				  ("trying to do CDIOCGETVOL\n"));
2410 
2411 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2412 			if (error) {
2413 				free(params.mode_buf, M_SCSICD);
2414 				cam_periph_unlock(periph);
2415 				break;
2416 			}
2417 			page = cdgetpage(&params);
2418 
2419 			arg->vol[LEFT_PORT] =
2420 				page->audio.port[LEFT_PORT].volume;
2421 			arg->vol[RIGHT_PORT] =
2422 				page->audio.port[RIGHT_PORT].volume;
2423 			arg->vol[2] = page->audio.port[2].volume;
2424 			arg->vol[3] = page->audio.port[3].volume;
2425 			free(params.mode_buf, M_SCSICD);
2426 			cam_periph_unlock(periph);
2427 		}
2428 		break;
2429 	case CDIOCSETVOL:
2430 		{
2431 			struct ioc_vol *arg = (struct ioc_vol *) addr;
2432 			struct cd_mode_params params;
2433 			union cd_pages *page;
2434 
2435 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2436 			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2437 						 M_WAITOK | M_ZERO);
2438 
2439 			cam_periph_lock(periph);
2440 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2441 				  ("trying to do CDIOCSETVOL\n"));
2442 
2443 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2444 			if (error) {
2445 				free(params.mode_buf, M_SCSICD);
2446 				cam_periph_unlock(periph);
2447 				break;
2448 			}
2449 			page = cdgetpage(&params);
2450 
2451 			page->audio.port[LEFT_PORT].channels = CHANNEL_0;
2452 			page->audio.port[LEFT_PORT].volume =
2453 				arg->vol[LEFT_PORT];
2454 			page->audio.port[RIGHT_PORT].channels = CHANNEL_1;
2455 			page->audio.port[RIGHT_PORT].volume =
2456 				arg->vol[RIGHT_PORT];
2457 			page->audio.port[2].volume = arg->vol[2];
2458 			page->audio.port[3].volume = arg->vol[3];
2459 			error = cdsetmode(periph, &params);
2460 			cam_periph_unlock(periph);
2461 			free(params.mode_buf, M_SCSICD);
2462 		}
2463 		break;
2464 	case CDIOCSETMONO:
2465 		{
2466 			struct cd_mode_params params;
2467 			union cd_pages *page;
2468 
2469 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2470 			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2471 						 M_WAITOK | M_ZERO);
2472 
2473 			cam_periph_lock(periph);
2474 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2475 				  ("trying to do CDIOCSETMONO\n"));
2476 
2477 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2478 			if (error) {
2479 				free(params.mode_buf, M_SCSICD);
2480 				cam_periph_unlock(periph);
2481 				break;
2482 			}
2483 			page = cdgetpage(&params);
2484 
2485 			page->audio.port[LEFT_PORT].channels =
2486 				LEFT_CHANNEL | RIGHT_CHANNEL;
2487 			page->audio.port[RIGHT_PORT].channels =
2488 				LEFT_CHANNEL | RIGHT_CHANNEL;
2489 			page->audio.port[2].channels = 0;
2490 			page->audio.port[3].channels = 0;
2491 			error = cdsetmode(periph, &params);
2492 			cam_periph_unlock(periph);
2493 			free(params.mode_buf, M_SCSICD);
2494 		}
2495 		break;
2496 	case CDIOCSETSTEREO:
2497 		{
2498 			struct cd_mode_params params;
2499 			union cd_pages *page;
2500 
2501 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2502 			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2503 						 M_WAITOK | M_ZERO);
2504 
2505 			cam_periph_lock(periph);
2506 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2507 				  ("trying to do CDIOCSETSTEREO\n"));
2508 
2509 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2510 			if (error) {
2511 				free(params.mode_buf, M_SCSICD);
2512 				cam_periph_unlock(periph);
2513 				break;
2514 			}
2515 			page = cdgetpage(&params);
2516 
2517 			page->audio.port[LEFT_PORT].channels =
2518 				LEFT_CHANNEL;
2519 			page->audio.port[RIGHT_PORT].channels =
2520 				RIGHT_CHANNEL;
2521 			page->audio.port[2].channels = 0;
2522 			page->audio.port[3].channels = 0;
2523 			error = cdsetmode(periph, &params);
2524 			free(params.mode_buf, M_SCSICD);
2525 			cam_periph_unlock(periph);
2526 		}
2527 		break;
2528 	case CDIOCSETMUTE:
2529 		{
2530 			struct cd_mode_params params;
2531 			union cd_pages *page;
2532 
2533 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2534 			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2535 						 M_WAITOK | M_ZERO);
2536 
2537 			cam_periph_lock(periph);
2538 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2539 				  ("trying to do CDIOCSETMUTE\n"));
2540 
2541 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2542 			if (error) {
2543 				free(params.mode_buf, M_SCSICD);
2544 				cam_periph_unlock(periph);
2545 				break;
2546 			}
2547 			page = cdgetpage(&params);
2548 
2549 			page->audio.port[LEFT_PORT].channels = 0;
2550 			page->audio.port[RIGHT_PORT].channels = 0;
2551 			page->audio.port[2].channels = 0;
2552 			page->audio.port[3].channels = 0;
2553 			error = cdsetmode(periph, &params);
2554 			free(params.mode_buf, M_SCSICD);
2555 			cam_periph_unlock(periph);
2556 		}
2557 		break;
2558 	case CDIOCSETLEFT:
2559 		{
2560 			struct cd_mode_params params;
2561 			union cd_pages *page;
2562 
2563 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2564 			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2565 						 M_WAITOK | M_ZERO);
2566 
2567 			cam_periph_lock(periph);
2568 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2569 				  ("trying to do CDIOCSETLEFT\n"));
2570 
2571 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2572 			if (error) {
2573 				free(params.mode_buf, M_SCSICD);
2574 				cam_periph_unlock(periph);
2575 				break;
2576 			}
2577 			page = cdgetpage(&params);
2578 
2579 			page->audio.port[LEFT_PORT].channels = LEFT_CHANNEL;
2580 			page->audio.port[RIGHT_PORT].channels = LEFT_CHANNEL;
2581 			page->audio.port[2].channels = 0;
2582 			page->audio.port[3].channels = 0;
2583 			error = cdsetmode(periph, &params);
2584 			free(params.mode_buf, M_SCSICD);
2585 			cam_periph_unlock(periph);
2586 		}
2587 		break;
2588 	case CDIOCSETRIGHT:
2589 		{
2590 			struct cd_mode_params params;
2591 			union cd_pages *page;
2592 
2593 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2594 			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2595 						 M_WAITOK | M_ZERO);
2596 
2597 			cam_periph_lock(periph);
2598 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2599 				  ("trying to do CDIOCSETRIGHT\n"));
2600 
2601 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2602 			if (error) {
2603 				free(params.mode_buf, M_SCSICD);
2604 				cam_periph_unlock(periph);
2605 				break;
2606 			}
2607 			page = cdgetpage(&params);
2608 
2609 			page->audio.port[LEFT_PORT].channels = RIGHT_CHANNEL;
2610 			page->audio.port[RIGHT_PORT].channels = RIGHT_CHANNEL;
2611 			page->audio.port[2].channels = 0;
2612 			page->audio.port[3].channels = 0;
2613 			error = cdsetmode(periph, &params);
2614 			free(params.mode_buf, M_SCSICD);
2615 			cam_periph_unlock(periph);
2616 		}
2617 		break;
2618 	case CDIOCRESUME:
2619 		cam_periph_lock(periph);
2620 		error = cdpause(periph, 1);
2621 		cam_periph_unlock(periph);
2622 		break;
2623 	case CDIOCPAUSE:
2624 		cam_periph_lock(periph);
2625 		error = cdpause(periph, 0);
2626 		cam_periph_unlock(periph);
2627 		break;
2628 	case CDIOCSTART:
2629 		cam_periph_lock(periph);
2630 		error = cdstartunit(periph, 0);
2631 		cam_periph_unlock(periph);
2632 		break;
2633 	case CDIOCCLOSE:
2634 		cam_periph_lock(periph);
2635 		error = cdstartunit(periph, 1);
2636 		cam_periph_unlock(periph);
2637 		break;
2638 	case CDIOCSTOP:
2639 		cam_periph_lock(periph);
2640 		error = cdstopunit(periph, 0);
2641 		cam_periph_unlock(periph);
2642 		break;
2643 	case CDIOCEJECT:
2644 		cam_periph_lock(periph);
2645 		error = cdstopunit(periph, 1);
2646 		cam_periph_unlock(periph);
2647 		break;
2648 	case CDIOCALLOW:
2649 		cam_periph_lock(periph);
2650 		cdprevent(periph, PR_ALLOW);
2651 		cam_periph_unlock(periph);
2652 		break;
2653 	case CDIOCPREVENT:
2654 		cam_periph_lock(periph);
2655 		cdprevent(periph, PR_PREVENT);
2656 		cam_periph_unlock(periph);
2657 		break;
2658 	case CDIOCSETDEBUG:
2659 		/* sc_link->flags |= (SDEV_DB1 | SDEV_DB2); */
2660 		error = ENOTTY;
2661 		break;
2662 	case CDIOCCLRDEBUG:
2663 		/* sc_link->flags &= ~(SDEV_DB1 | SDEV_DB2); */
2664 		error = ENOTTY;
2665 		break;
2666 	case CDIOCRESET:
2667 		/* return (cd_reset(periph)); */
2668 		error = ENOTTY;
2669 		break;
2670 	case CDRIOCREADSPEED:
2671 		cam_periph_lock(periph);
2672 		error = cdsetspeed(periph, *(u_int32_t *)addr, CDR_MAX_SPEED);
2673 		cam_periph_unlock(periph);
2674 		break;
2675 	case CDRIOCWRITESPEED:
2676 		cam_periph_lock(periph);
2677 		error = cdsetspeed(periph, CDR_MAX_SPEED, *(u_int32_t *)addr);
2678 		cam_periph_unlock(periph);
2679 		break;
2680 	case DVDIOCSENDKEY:
2681 	case DVDIOCREPORTKEY: {
2682 		struct dvd_authinfo *authinfo;
2683 
2684 		authinfo = (struct dvd_authinfo *)addr;
2685 
2686 		if (cmd == DVDIOCREPORTKEY)
2687 			error = cdreportkey(periph, authinfo);
2688 		else
2689 			error = cdsendkey(periph, authinfo);
2690 		break;
2691 		}
2692 	case DVDIOCREADSTRUCTURE: {
2693 		struct dvd_struct *dvdstruct;
2694 
2695 		dvdstruct = (struct dvd_struct *)addr;
2696 
2697 		error = cdreaddvdstructure(periph, dvdstruct);
2698 
2699 		break;
2700 	}
2701 	default:
2702 		cam_periph_lock(periph);
2703 		error = cam_periph_ioctl(periph, cmd, addr, cderror);
2704 		cam_periph_unlock(periph);
2705 		break;
2706 	}
2707 
2708 	cam_periph_lock(periph);
2709 	cam_periph_unhold(periph);
2710 
2711 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdioctl\n"));
2712 	if (error && bootverbose) {
2713 		printf("scsi_cd.c::ioctl cmd=%08lx error=%d\n", cmd, error);
2714 	}
2715 	cam_periph_unlock(periph);
2716 
2717 	return (error);
2718 }
2719 
2720 static void
2721 cdprevent(struct cam_periph *periph, int action)
2722 {
2723 	union	ccb *ccb;
2724 	struct	cd_softc *softc;
2725 	int	error;
2726 
2727 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdprevent\n"));
2728 
2729 	softc = (struct cd_softc *)periph->softc;
2730 
2731 	if (((action == PR_ALLOW)
2732 	  && (softc->flags & CD_FLAG_DISC_LOCKED) == 0)
2733 	 || ((action == PR_PREVENT)
2734 	  && (softc->flags & CD_FLAG_DISC_LOCKED) != 0)) {
2735 		return;
2736 	}
2737 
2738 	ccb = cdgetccb(periph, CAM_PRIORITY_NORMAL);
2739 
2740 	scsi_prevent(&ccb->csio,
2741 		     /*retries*/ cd_retry_count,
2742 		     cddone,
2743 		     MSG_SIMPLE_Q_TAG,
2744 		     action,
2745 		     SSD_FULL_SIZE,
2746 		     /* timeout */60000);
2747 
2748 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2749 			/*sense_flags*/SF_RETRY_UA|SF_NO_PRINT);
2750 
2751 	xpt_release_ccb(ccb);
2752 
2753 	if (error == 0) {
2754 		if (action == PR_ALLOW)
2755 			softc->flags &= ~CD_FLAG_DISC_LOCKED;
2756 		else
2757 			softc->flags |= CD_FLAG_DISC_LOCKED;
2758 	}
2759 }
2760 
2761 /*
2762  * XXX: the disk media and sector size is only really able to change
2763  * XXX: while the device is closed.
2764  */
2765 static int
2766 cdcheckmedia(struct cam_periph *periph)
2767 {
2768 	struct cd_softc *softc;
2769 	struct ioc_toc_header *toch;
2770 	struct cd_toc_single leadout;
2771 	u_int32_t size, toclen;
2772 	int error, num_entries, cdindex;
2773 
2774 	softc = (struct cd_softc *)periph->softc;
2775 
2776 	cdprevent(periph, PR_PREVENT);
2777 	softc->disk->d_sectorsize = 2048;
2778 	softc->disk->d_mediasize = 0;
2779 
2780 	/*
2781 	 * Get the disc size and block size.  If we can't get it, we don't
2782 	 * have media, most likely.
2783 	 */
2784 	if ((error = cdsize(periph, &size)) != 0) {
2785 		softc->flags &= ~(CD_FLAG_VALID_MEDIA|CD_FLAG_VALID_TOC);
2786 		cdprevent(periph, PR_ALLOW);
2787 		return (error);
2788 	} else {
2789 		softc->flags |= CD_FLAG_VALID_MEDIA;
2790 		softc->disk->d_sectorsize = softc->params.blksize;
2791 		softc->disk->d_mediasize =
2792 		    (off_t)softc->params.blksize * softc->params.disksize;
2793 	}
2794 
2795 	/*
2796 	 * Now we check the table of contents.  This (currently) is only
2797 	 * used for the CDIOCPLAYTRACKS ioctl.  It may be used later to do
2798 	 * things like present a separate entry in /dev for each track,
2799 	 * like that acd(4) driver does.
2800 	 */
2801 	bzero(&softc->toc, sizeof(softc->toc));
2802 	toch = &softc->toc.header;
2803 	/*
2804 	 * We will get errors here for media that doesn't have a table of
2805 	 * contents.  According to the MMC-3 spec: "When a Read TOC/PMA/ATIP
2806 	 * command is presented for a DDCD/CD-R/RW media, where the first TOC
2807 	 * has not been recorded (no complete session) and the Format codes
2808 	 * 0000b, 0001b, or 0010b are specified, this command shall be rejected
2809 	 * with an INVALID FIELD IN CDB.  Devices that are not capable of
2810 	 * reading an incomplete session on DDC/CD-R/RW media shall report
2811 	 * CANNOT READ MEDIUM - INCOMPATIBLE FORMAT."
2812 	 *
2813 	 * So this isn't fatal if we can't read the table of contents, it
2814 	 * just means that the user won't be able to issue the play tracks
2815 	 * ioctl, and likely lots of other stuff won't work either.  They
2816 	 * need to burn the CD before we can do a whole lot with it.  So
2817 	 * we don't print anything here if we get an error back.
2818 	 */
2819 	error = cdreadtoc(periph, 0, 0, (u_int8_t *)toch, sizeof(*toch),
2820 			  SF_NO_PRINT);
2821 	/*
2822 	 * Errors in reading the table of contents aren't fatal, we just
2823 	 * won't have a valid table of contents cached.
2824 	 */
2825 	if (error != 0) {
2826 		error = 0;
2827 		bzero(&softc->toc, sizeof(softc->toc));
2828 		goto bailout;
2829 	}
2830 
2831 	if (softc->quirks & CD_Q_BCD_TRACKS) {
2832 		toch->starting_track = bcd2bin(toch->starting_track);
2833 		toch->ending_track = bcd2bin(toch->ending_track);
2834 	}
2835 
2836 	/* Number of TOC entries, plus leadout */
2837 	num_entries = (toch->ending_track - toch->starting_track) + 2;
2838 
2839 	if (num_entries <= 0)
2840 		goto bailout;
2841 
2842 	toclen = num_entries * sizeof(struct cd_toc_entry);
2843 
2844 	error = cdreadtoc(periph, CD_MSF_FORMAT, toch->starting_track,
2845 			  (u_int8_t *)&softc->toc, toclen + sizeof(*toch),
2846 			  SF_NO_PRINT);
2847 	if (error != 0) {
2848 		error = 0;
2849 		bzero(&softc->toc, sizeof(softc->toc));
2850 		goto bailout;
2851 	}
2852 
2853 	if (softc->quirks & CD_Q_BCD_TRACKS) {
2854 		toch->starting_track = bcd2bin(toch->starting_track);
2855 		toch->ending_track = bcd2bin(toch->ending_track);
2856 	}
2857 	/*
2858 	 * XXX KDM is this necessary?  Probably only if the drive doesn't
2859 	 * return leadout information with the table of contents.
2860 	 */
2861 	cdindex = toch->starting_track + num_entries -1;
2862 	if (cdindex == toch->ending_track + 1) {
2863 
2864 		error = cdreadtoc(periph, CD_MSF_FORMAT, LEADOUT,
2865 				  (u_int8_t *)&leadout, sizeof(leadout),
2866 				  SF_NO_PRINT);
2867 		if (error != 0) {
2868 			error = 0;
2869 			goto bailout;
2870 		}
2871 		softc->toc.entries[cdindex - toch->starting_track] =
2872 			leadout.entry;
2873 	}
2874 	if (softc->quirks & CD_Q_BCD_TRACKS) {
2875 		for (cdindex = 0; cdindex < num_entries - 1; cdindex++) {
2876 			softc->toc.entries[cdindex].track =
2877 				bcd2bin(softc->toc.entries[cdindex].track);
2878 		}
2879 	}
2880 
2881 	softc->flags |= CD_FLAG_VALID_TOC;
2882 
2883 bailout:
2884 
2885 	/*
2886 	 * We unconditionally (re)set the blocksize each time the
2887 	 * CD device is opened.  This is because the CD can change,
2888 	 * and therefore the blocksize might change.
2889 	 * XXX problems here if some slice or partition is still
2890 	 * open with the old size?
2891 	 */
2892 	if ((softc->disk->d_devstat->flags & DEVSTAT_BS_UNAVAILABLE) != 0)
2893 		softc->disk->d_devstat->flags &= ~DEVSTAT_BS_UNAVAILABLE;
2894 	softc->disk->d_devstat->block_size = softc->params.blksize;
2895 
2896 	return (error);
2897 }
2898 
2899 static int
2900 cdsize(struct cam_periph *periph, u_int32_t *size)
2901 {
2902 	struct cd_softc *softc;
2903 	union ccb *ccb;
2904 	struct scsi_read_capacity_data *rcap_buf;
2905 	int error;
2906 
2907 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdsize\n"));
2908 
2909 	softc = (struct cd_softc *)periph->softc;
2910 
2911 	ccb = cdgetccb(periph, CAM_PRIORITY_NORMAL);
2912 
2913 	/* XXX Should be M_WAITOK */
2914 	rcap_buf = malloc(sizeof(struct scsi_read_capacity_data),
2915 			  M_SCSICD, M_NOWAIT | M_ZERO);
2916 	if (rcap_buf == NULL)
2917 		return (ENOMEM);
2918 
2919 	scsi_read_capacity(&ccb->csio,
2920 			   /*retries*/ cd_retry_count,
2921 			   cddone,
2922 			   MSG_SIMPLE_Q_TAG,
2923 			   rcap_buf,
2924 			   SSD_FULL_SIZE,
2925 			   /* timeout */20000);
2926 
2927 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2928 			 /*sense_flags*/SF_RETRY_UA|SF_NO_PRINT);
2929 
2930 	xpt_release_ccb(ccb);
2931 
2932 	softc->params.disksize = scsi_4btoul(rcap_buf->addr) + 1;
2933 	softc->params.blksize  = scsi_4btoul(rcap_buf->length);
2934 	/* Make sure we got at least some block size. */
2935 	if (error == 0 && softc->params.blksize == 0)
2936 		error = EIO;
2937 	/*
2938 	 * SCSI-3 mandates that the reported blocksize shall be 2048.
2939 	 * Older drives sometimes report funny values, trim it down to
2940 	 * 2048, or other parts of the kernel will get confused.
2941 	 *
2942 	 * XXX we leave drives alone that might report 512 bytes, as
2943 	 * well as drives reporting more weird sizes like perhaps 4K.
2944 	 */
2945 	if (softc->params.blksize > 2048 && softc->params.blksize <= 2352)
2946 		softc->params.blksize = 2048;
2947 
2948 	free(rcap_buf, M_SCSICD);
2949 	*size = softc->params.disksize;
2950 
2951 	return (error);
2952 
2953 }
2954 
2955 static int
2956 cd6byteworkaround(union ccb *ccb)
2957 {
2958 	u_int8_t *cdb;
2959 	struct cam_periph *periph;
2960 	struct cd_softc *softc;
2961 	struct cd_mode_params *params;
2962 	int frozen, found;
2963 
2964 	periph = xpt_path_periph(ccb->ccb_h.path);
2965 	softc = (struct cd_softc *)periph->softc;
2966 
2967 	cdb = ccb->csio.cdb_io.cdb_bytes;
2968 
2969 	if ((ccb->ccb_h.flags & CAM_CDB_POINTER)
2970 	 || ((cdb[0] != MODE_SENSE_6)
2971 	  && (cdb[0] != MODE_SELECT_6)))
2972 		return (0);
2973 
2974 	/*
2975 	 * Because there is no convenient place to stash the overall
2976 	 * cd_mode_params structure pointer, we have to grab it like this.
2977 	 * This means that ALL MODE_SENSE and MODE_SELECT requests in the
2978 	 * cd(4) driver MUST go through cdgetmode() and cdsetmode()!
2979 	 *
2980 	 * XXX It would be nice if, at some point, we could increase the
2981 	 * number of available peripheral private pointers.  Both pointers
2982 	 * are currently used in most every peripheral driver.
2983 	 */
2984 	found = 0;
2985 
2986 	STAILQ_FOREACH(params, &softc->mode_queue, links) {
2987 		if (params->mode_buf == ccb->csio.data_ptr) {
2988 			found = 1;
2989 			break;
2990 		}
2991 	}
2992 
2993 	/*
2994 	 * This shouldn't happen.  All mode sense and mode select
2995 	 * operations in the cd(4) driver MUST go through cdgetmode() and
2996 	 * cdsetmode()!
2997 	 */
2998 	if (found == 0) {
2999 		xpt_print(periph->path,
3000 		    "mode buffer not found in mode queue!\n");
3001 		return (0);
3002 	}
3003 
3004 	params->cdb_size = 10;
3005 	softc->minimum_command_size = 10;
3006 	xpt_print(ccb->ccb_h.path,
3007 	    "%s(6) failed, increasing minimum CDB size to 10 bytes\n",
3008 	    (cdb[0] == MODE_SENSE_6) ? "MODE_SENSE" : "MODE_SELECT");
3009 
3010 	if (cdb[0] == MODE_SENSE_6) {
3011 		struct scsi_mode_sense_10 ms10;
3012 		struct scsi_mode_sense_6 *ms6;
3013 		int len;
3014 
3015 		ms6 = (struct scsi_mode_sense_6 *)cdb;
3016 
3017 		bzero(&ms10, sizeof(ms10));
3018  		ms10.opcode = MODE_SENSE_10;
3019  		ms10.byte2 = ms6->byte2;
3020  		ms10.page = ms6->page;
3021 
3022 		/*
3023 		 * 10 byte mode header, block descriptor,
3024 		 * sizeof(union cd_pages)
3025 		 */
3026 		len = sizeof(struct cd_mode_data_10);
3027 		ccb->csio.dxfer_len = len;
3028 
3029 		scsi_ulto2b(len, ms10.length);
3030 		ms10.control = ms6->control;
3031 		bcopy(&ms10, cdb, 10);
3032 		ccb->csio.cdb_len = 10;
3033 	} else {
3034 		struct scsi_mode_select_10 ms10;
3035 		struct scsi_mode_select_6 *ms6;
3036 		struct scsi_mode_header_6 *header6;
3037 		struct scsi_mode_header_10 *header10;
3038 		struct scsi_mode_page_header *page_header;
3039 		int blk_desc_len, page_num, page_size, len;
3040 
3041 		ms6 = (struct scsi_mode_select_6 *)cdb;
3042 
3043 		bzero(&ms10, sizeof(ms10));
3044 		ms10.opcode = MODE_SELECT_10;
3045 		ms10.byte2 = ms6->byte2;
3046 
3047 		header6 = (struct scsi_mode_header_6 *)params->mode_buf;
3048 		header10 = (struct scsi_mode_header_10 *)params->mode_buf;
3049 
3050 		page_header = find_mode_page_6(header6);
3051 		page_num = page_header->page_code;
3052 
3053 		blk_desc_len = header6->blk_desc_len;
3054 
3055 		page_size = cdgetpagesize(page_num);
3056 
3057 		if (page_size != (page_header->page_length +
3058 		    sizeof(*page_header)))
3059 			page_size = page_header->page_length +
3060 				sizeof(*page_header);
3061 
3062 		len = sizeof(*header10) + blk_desc_len + page_size;
3063 
3064 		len = min(params->alloc_len, len);
3065 
3066 		/*
3067 		 * Since the 6 byte parameter header is shorter than the 10
3068 		 * byte parameter header, we need to copy the actual mode
3069 		 * page data, and the block descriptor, if any, so things wind
3070 		 * up in the right place.  The regions will overlap, but
3071 		 * bcopy() does the right thing.
3072 		 */
3073 		bcopy(params->mode_buf + sizeof(*header6),
3074 		      params->mode_buf + sizeof(*header10),
3075 		      len - sizeof(*header10));
3076 
3077 		/* Make sure these fields are set correctly. */
3078 		scsi_ulto2b(0, header10->data_length);
3079 		header10->medium_type = 0;
3080 		scsi_ulto2b(blk_desc_len, header10->blk_desc_len);
3081 
3082 		ccb->csio.dxfer_len = len;
3083 
3084 		scsi_ulto2b(len, ms10.length);
3085 		ms10.control = ms6->control;
3086 		bcopy(&ms10, cdb, 10);
3087 		ccb->csio.cdb_len = 10;
3088 	}
3089 
3090 	frozen = (ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
3091 	ccb->ccb_h.status = CAM_REQUEUE_REQ;
3092 	xpt_action(ccb);
3093 	if (frozen) {
3094 		cam_release_devq(ccb->ccb_h.path,
3095 				 /*relsim_flags*/0,
3096 				 /*openings*/0,
3097 				 /*timeout*/0,
3098 				 /*getcount_only*/0);
3099 	}
3100 
3101 	return (ERESTART);
3102 }
3103 
3104 static int
3105 cderror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
3106 {
3107 	struct cd_softc *softc;
3108 	struct cam_periph *periph;
3109 	int error;
3110 
3111 	periph = xpt_path_periph(ccb->ccb_h.path);
3112 	softc = (struct cd_softc *)periph->softc;
3113 
3114 	error = 0;
3115 
3116 	/*
3117 	 * We use a status of CAM_REQ_INVALID as shorthand -- if a 6 byte
3118 	 * CDB comes back with this particular error, try transforming it
3119 	 * into the 10 byte version.
3120 	 */
3121 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INVALID) {
3122 		error = cd6byteworkaround(ccb);
3123 	} else if (((ccb->ccb_h.status & CAM_STATUS_MASK) ==
3124 		     CAM_SCSI_STATUS_ERROR)
3125 	 && (ccb->ccb_h.status & CAM_AUTOSNS_VALID)
3126 	 && (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND)
3127 	 && ((ccb->ccb_h.flags & CAM_SENSE_PHYS) == 0)
3128 	 && ((ccb->ccb_h.flags & CAM_SENSE_PTR) == 0)) {
3129 		int sense_key, error_code, asc, ascq;
3130 
3131  		scsi_extract_sense_len(&ccb->csio.sense_data,
3132 		    ccb->csio.sense_len - ccb->csio.sense_resid, &error_code,
3133 		    &sense_key, &asc, &ascq, /*show_errors*/ 1);
3134 		if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
3135  			error = cd6byteworkaround(ccb);
3136 	}
3137 
3138 	if (error == ERESTART)
3139 		return (error);
3140 
3141 	/*
3142 	 * XXX
3143 	 * Until we have a better way of doing pack validation,
3144 	 * don't treat UAs as errors.
3145 	 */
3146 	sense_flags |= SF_RETRY_UA;
3147 	return (cam_periph_error(ccb, cam_flags, sense_flags,
3148 				 &softc->saved_ccb));
3149 }
3150 
3151 /*
3152  * Read table of contents
3153  */
3154 static int
3155 cdreadtoc(struct cam_periph *periph, u_int32_t mode, u_int32_t start,
3156 	  u_int8_t *data, u_int32_t len, u_int32_t sense_flags)
3157 {
3158 	struct scsi_read_toc *scsi_cmd;
3159 	u_int32_t ntoc;
3160         struct ccb_scsiio *csio;
3161 	union ccb *ccb;
3162 	int error;
3163 
3164 	ntoc = len;
3165 	error = 0;
3166 
3167 	ccb = cdgetccb(periph, CAM_PRIORITY_NORMAL);
3168 
3169 	csio = &ccb->csio;
3170 
3171 	cam_fill_csio(csio,
3172 		      /* retries */ cd_retry_count,
3173 		      /* cbfcnp */ cddone,
3174 		      /* flags */ CAM_DIR_IN,
3175 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3176 		      /* data_ptr */ data,
3177 		      /* dxfer_len */ len,
3178 		      /* sense_len */ SSD_FULL_SIZE,
3179 		      sizeof(struct scsi_read_toc),
3180  		      /* timeout */ 50000);
3181 
3182 	scsi_cmd = (struct scsi_read_toc *)&csio->cdb_io.cdb_bytes;
3183 	bzero (scsi_cmd, sizeof(*scsi_cmd));
3184 
3185 	if (mode == CD_MSF_FORMAT)
3186 		scsi_cmd->byte2 |= CD_MSF;
3187 	scsi_cmd->from_track = start;
3188 	/* scsi_ulto2b(ntoc, (u_int8_t *)scsi_cmd->data_len); */
3189 	scsi_cmd->data_len[0] = (ntoc) >> 8;
3190 	scsi_cmd->data_len[1] = (ntoc) & 0xff;
3191 
3192 	scsi_cmd->op_code = READ_TOC;
3193 
3194 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3195 			 /*sense_flags*/SF_RETRY_UA | sense_flags);
3196 
3197 	xpt_release_ccb(ccb);
3198 
3199 	return(error);
3200 }
3201 
3202 static int
3203 cdreadsubchannel(struct cam_periph *periph, u_int32_t mode,
3204 		 u_int32_t format, int track,
3205 		 struct cd_sub_channel_info *data, u_int32_t len)
3206 {
3207 	struct scsi_read_subchannel *scsi_cmd;
3208         struct ccb_scsiio *csio;
3209 	union ccb *ccb;
3210 	int error;
3211 
3212 	error = 0;
3213 
3214 	ccb = cdgetccb(periph, CAM_PRIORITY_NORMAL);
3215 
3216 	csio = &ccb->csio;
3217 
3218 	cam_fill_csio(csio,
3219 		      /* retries */ cd_retry_count,
3220 		      /* cbfcnp */ cddone,
3221 		      /* flags */ CAM_DIR_IN,
3222 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3223 		      /* data_ptr */ (u_int8_t *)data,
3224 		      /* dxfer_len */ len,
3225 		      /* sense_len */ SSD_FULL_SIZE,
3226 		      sizeof(struct scsi_read_subchannel),
3227  		      /* timeout */ 50000);
3228 
3229 	scsi_cmd = (struct scsi_read_subchannel *)&csio->cdb_io.cdb_bytes;
3230 	bzero (scsi_cmd, sizeof(*scsi_cmd));
3231 
3232 	scsi_cmd->op_code = READ_SUBCHANNEL;
3233 	if (mode == CD_MSF_FORMAT)
3234 		scsi_cmd->byte1 |= CD_MSF;
3235 	scsi_cmd->byte2 = SRS_SUBQ;
3236 	scsi_cmd->subchan_format = format;
3237 	scsi_cmd->track = track;
3238 	scsi_ulto2b(len, (u_int8_t *)scsi_cmd->data_len);
3239 	scsi_cmd->control = 0;
3240 
3241 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3242 			 /*sense_flags*/SF_RETRY_UA);
3243 
3244 	xpt_release_ccb(ccb);
3245 
3246 	return(error);
3247 }
3248 
3249 
3250 /*
3251  * All MODE_SENSE requests in the cd(4) driver MUST go through this
3252  * routine.  See comments in cd6byteworkaround() for details.
3253  */
3254 static int
3255 cdgetmode(struct cam_periph *periph, struct cd_mode_params *data,
3256 	  u_int32_t page)
3257 {
3258 	struct ccb_scsiio *csio;
3259 	struct cd_softc *softc;
3260 	union ccb *ccb;
3261 	int param_len;
3262 	int error;
3263 
3264 	softc = (struct cd_softc *)periph->softc;
3265 
3266 	ccb = cdgetccb(periph, CAM_PRIORITY_NORMAL);
3267 
3268 	csio = &ccb->csio;
3269 
3270 	data->cdb_size = softc->minimum_command_size;
3271 	if (data->cdb_size < 10)
3272 		param_len = sizeof(struct cd_mode_data);
3273 	else
3274 		param_len = sizeof(struct cd_mode_data_10);
3275 
3276 	/* Don't say we've got more room than we actually allocated */
3277 	param_len = min(param_len, data->alloc_len);
3278 
3279 	scsi_mode_sense_len(csio,
3280 			    /* retries */ cd_retry_count,
3281 			    /* cbfcnp */ cddone,
3282 			    /* tag_action */ MSG_SIMPLE_Q_TAG,
3283 			    /* dbd */ 0,
3284 			    /* page_code */ SMS_PAGE_CTRL_CURRENT,
3285 			    /* page */ page,
3286 			    /* param_buf */ data->mode_buf,
3287 			    /* param_len */ param_len,
3288 			    /* minimum_cmd_size */ softc->minimum_command_size,
3289 			    /* sense_len */ SSD_FULL_SIZE,
3290 			    /* timeout */ 50000);
3291 
3292 	/*
3293 	 * It would be nice not to have to do this, but there's no
3294 	 * available pointer in the CCB that would allow us to stuff the
3295 	 * mode params structure in there and retrieve it in
3296 	 * cd6byteworkaround(), so we can set the cdb size.  The cdb size
3297 	 * lets the caller know what CDB size we ended up using, so they
3298 	 * can find the actual mode page offset.
3299 	 */
3300 	STAILQ_INSERT_TAIL(&softc->mode_queue, data, links);
3301 
3302 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3303 			 /*sense_flags*/SF_RETRY_UA);
3304 
3305 	xpt_release_ccb(ccb);
3306 
3307 	STAILQ_REMOVE(&softc->mode_queue, data, cd_mode_params, links);
3308 
3309 	/*
3310 	 * This is a bit of belt-and-suspenders checking, but if we run
3311 	 * into a situation where the target sends back multiple block
3312 	 * descriptors, we might not have enough space in the buffer to
3313 	 * see the whole mode page.  Better to return an error than
3314 	 * potentially access memory beyond our malloced region.
3315 	 */
3316 	if (error == 0) {
3317 		u_int32_t data_len;
3318 
3319 		if (data->cdb_size == 10) {
3320 			struct scsi_mode_header_10 *hdr10;
3321 
3322 			hdr10 = (struct scsi_mode_header_10 *)data->mode_buf;
3323 			data_len = scsi_2btoul(hdr10->data_length);
3324 			data_len += sizeof(hdr10->data_length);
3325 		} else {
3326 			struct scsi_mode_header_6 *hdr6;
3327 
3328 			hdr6 = (struct scsi_mode_header_6 *)data->mode_buf;
3329 			data_len = hdr6->data_length;
3330 			data_len += sizeof(hdr6->data_length);
3331 		}
3332 
3333 		/*
3334 		 * Complain if there is more mode data available than we
3335 		 * allocated space for.  This could potentially happen if
3336 		 * we miscalculated the page length for some reason, if the
3337 		 * drive returns multiple block descriptors, or if it sets
3338 		 * the data length incorrectly.
3339 		 */
3340 		if (data_len > data->alloc_len) {
3341 			xpt_print(periph->path, "allocated modepage %d length "
3342 			    "%d < returned length %d\n", page, data->alloc_len,
3343 			    data_len);
3344 			error = ENOSPC;
3345 		}
3346 	}
3347 	return (error);
3348 }
3349 
3350 /*
3351  * All MODE_SELECT requests in the cd(4) driver MUST go through this
3352  * routine.  See comments in cd6byteworkaround() for details.
3353  */
3354 static int
3355 cdsetmode(struct cam_periph *periph, struct cd_mode_params *data)
3356 {
3357 	struct ccb_scsiio *csio;
3358 	struct cd_softc *softc;
3359 	union ccb *ccb;
3360 	int cdb_size, param_len;
3361 	int error;
3362 
3363 	softc = (struct cd_softc *)periph->softc;
3364 
3365 	ccb = cdgetccb(periph, CAM_PRIORITY_NORMAL);
3366 
3367 	csio = &ccb->csio;
3368 
3369 	error = 0;
3370 
3371 	/*
3372 	 * If the data is formatted for the 10 byte version of the mode
3373 	 * select parameter list, we need to use the 10 byte CDB.
3374 	 * Otherwise, we use whatever the stored minimum command size.
3375 	 */
3376 	if (data->cdb_size == 10)
3377 		cdb_size = data->cdb_size;
3378 	else
3379 		cdb_size = softc->minimum_command_size;
3380 
3381 	if (cdb_size >= 10) {
3382 		struct scsi_mode_header_10 *mode_header;
3383 		u_int32_t data_len;
3384 
3385 		mode_header = (struct scsi_mode_header_10 *)data->mode_buf;
3386 
3387 		data_len = scsi_2btoul(mode_header->data_length);
3388 
3389 		scsi_ulto2b(0, mode_header->data_length);
3390 		/*
3391 		 * SONY drives do not allow a mode select with a medium_type
3392 		 * value that has just been returned by a mode sense; use a
3393 		 * medium_type of 0 (Default) instead.
3394 		 */
3395 		mode_header->medium_type = 0;
3396 
3397 		/*
3398 		 * Pass back whatever the drive passed to us, plus the size
3399 		 * of the data length field.
3400 		 */
3401 		param_len = data_len + sizeof(mode_header->data_length);
3402 
3403 	} else {
3404 		struct scsi_mode_header_6 *mode_header;
3405 
3406 		mode_header = (struct scsi_mode_header_6 *)data->mode_buf;
3407 
3408 		param_len = mode_header->data_length + 1;
3409 
3410 		mode_header->data_length = 0;
3411 		/*
3412 		 * SONY drives do not allow a mode select with a medium_type
3413 		 * value that has just been returned by a mode sense; use a
3414 		 * medium_type of 0 (Default) instead.
3415 		 */
3416 		mode_header->medium_type = 0;
3417 	}
3418 
3419 	/* Don't say we've got more room than we actually allocated */
3420 	param_len = min(param_len, data->alloc_len);
3421 
3422 	scsi_mode_select_len(csio,
3423 			     /* retries */ cd_retry_count,
3424 			     /* cbfcnp */ cddone,
3425 			     /* tag_action */ MSG_SIMPLE_Q_TAG,
3426 			     /* scsi_page_fmt */ 1,
3427 			     /* save_pages */ 0,
3428 			     /* param_buf */ data->mode_buf,
3429 			     /* param_len */ param_len,
3430 			     /* minimum_cmd_size */ cdb_size,
3431 			     /* sense_len */ SSD_FULL_SIZE,
3432 			     /* timeout */ 50000);
3433 
3434 	/* See comments in cdgetmode() and cd6byteworkaround(). */
3435 	STAILQ_INSERT_TAIL(&softc->mode_queue, data, links);
3436 
3437 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3438 			 /*sense_flags*/SF_RETRY_UA);
3439 
3440 	xpt_release_ccb(ccb);
3441 
3442 	STAILQ_REMOVE(&softc->mode_queue, data, cd_mode_params, links);
3443 
3444 	return (error);
3445 }
3446 
3447 
3448 static int
3449 cdplay(struct cam_periph *periph, u_int32_t blk, u_int32_t len)
3450 {
3451 	struct ccb_scsiio *csio;
3452 	union ccb *ccb;
3453 	int error;
3454 	u_int8_t cdb_len;
3455 
3456 	error = 0;
3457 	ccb = cdgetccb(periph, CAM_PRIORITY_NORMAL);
3458 	csio = &ccb->csio;
3459 	/*
3460 	 * Use the smallest possible command to perform the operation.
3461 	 */
3462 	if ((len & 0xffff0000) == 0) {
3463 		/*
3464 		 * We can fit in a 10 byte cdb.
3465 		 */
3466 		struct scsi_play_10 *scsi_cmd;
3467 
3468 		scsi_cmd = (struct scsi_play_10 *)&csio->cdb_io.cdb_bytes;
3469 		bzero (scsi_cmd, sizeof(*scsi_cmd));
3470 		scsi_cmd->op_code = PLAY_10;
3471 		scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
3472 		scsi_ulto2b(len, (u_int8_t *)scsi_cmd->xfer_len);
3473 		cdb_len = sizeof(*scsi_cmd);
3474 	} else  {
3475 		struct scsi_play_12 *scsi_cmd;
3476 
3477 		scsi_cmd = (struct scsi_play_12 *)&csio->cdb_io.cdb_bytes;
3478 		bzero (scsi_cmd, sizeof(*scsi_cmd));
3479 		scsi_cmd->op_code = PLAY_12;
3480 		scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
3481 		scsi_ulto4b(len, (u_int8_t *)scsi_cmd->xfer_len);
3482 		cdb_len = sizeof(*scsi_cmd);
3483 	}
3484 	cam_fill_csio(csio,
3485 		      /*retries*/ cd_retry_count,
3486 		      cddone,
3487 		      /*flags*/CAM_DIR_NONE,
3488 		      MSG_SIMPLE_Q_TAG,
3489 		      /*dataptr*/NULL,
3490 		      /*datalen*/0,
3491 		      /*sense_len*/SSD_FULL_SIZE,
3492 		      cdb_len,
3493 		      /*timeout*/50 * 1000);
3494 
3495 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3496 			 /*sense_flags*/SF_RETRY_UA);
3497 
3498 	xpt_release_ccb(ccb);
3499 
3500 	return(error);
3501 }
3502 
3503 static int
3504 cdplaymsf(struct cam_periph *periph, u_int32_t startm, u_int32_t starts,
3505 	  u_int32_t startf, u_int32_t endm, u_int32_t ends, u_int32_t endf)
3506 {
3507 	struct scsi_play_msf *scsi_cmd;
3508         struct ccb_scsiio *csio;
3509 	union ccb *ccb;
3510 	int error;
3511 
3512 	error = 0;
3513 
3514 	ccb = cdgetccb(periph, CAM_PRIORITY_NORMAL);
3515 
3516 	csio = &ccb->csio;
3517 
3518 	cam_fill_csio(csio,
3519 		      /* retries */ cd_retry_count,
3520 		      /* cbfcnp */ cddone,
3521 		      /* flags */ CAM_DIR_NONE,
3522 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3523 		      /* data_ptr */ NULL,
3524 		      /* dxfer_len */ 0,
3525 		      /* sense_len */ SSD_FULL_SIZE,
3526 		      sizeof(struct scsi_play_msf),
3527  		      /* timeout */ 50000);
3528 
3529 	scsi_cmd = (struct scsi_play_msf *)&csio->cdb_io.cdb_bytes;
3530 	bzero (scsi_cmd, sizeof(*scsi_cmd));
3531 
3532         scsi_cmd->op_code = PLAY_MSF;
3533         scsi_cmd->start_m = startm;
3534         scsi_cmd->start_s = starts;
3535         scsi_cmd->start_f = startf;
3536         scsi_cmd->end_m = endm;
3537         scsi_cmd->end_s = ends;
3538         scsi_cmd->end_f = endf;
3539 
3540 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3541 			 /*sense_flags*/SF_RETRY_UA);
3542 
3543 	xpt_release_ccb(ccb);
3544 
3545 	return(error);
3546 }
3547 
3548 
3549 static int
3550 cdplaytracks(struct cam_periph *periph, u_int32_t strack, u_int32_t sindex,
3551 	     u_int32_t etrack, u_int32_t eindex)
3552 {
3553 	struct scsi_play_track *scsi_cmd;
3554         struct ccb_scsiio *csio;
3555 	union ccb *ccb;
3556 	int error;
3557 
3558 	error = 0;
3559 
3560 	ccb = cdgetccb(periph, CAM_PRIORITY_NORMAL);
3561 
3562 	csio = &ccb->csio;
3563 
3564 	cam_fill_csio(csio,
3565 		      /* retries */ cd_retry_count,
3566 		      /* cbfcnp */ cddone,
3567 		      /* flags */ CAM_DIR_NONE,
3568 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3569 		      /* data_ptr */ NULL,
3570 		      /* dxfer_len */ 0,
3571 		      /* sense_len */ SSD_FULL_SIZE,
3572 		      sizeof(struct scsi_play_track),
3573  		      /* timeout */ 50000);
3574 
3575 	scsi_cmd = (struct scsi_play_track *)&csio->cdb_io.cdb_bytes;
3576 	bzero (scsi_cmd, sizeof(*scsi_cmd));
3577 
3578         scsi_cmd->op_code = PLAY_TRACK;
3579         scsi_cmd->start_track = strack;
3580         scsi_cmd->start_index = sindex;
3581         scsi_cmd->end_track = etrack;
3582         scsi_cmd->end_index = eindex;
3583 
3584 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3585 			 /*sense_flags*/SF_RETRY_UA);
3586 
3587 	xpt_release_ccb(ccb);
3588 
3589 	return(error);
3590 }
3591 
3592 static int
3593 cdpause(struct cam_periph *periph, u_int32_t go)
3594 {
3595 	struct scsi_pause *scsi_cmd;
3596         struct ccb_scsiio *csio;
3597 	union ccb *ccb;
3598 	int error;
3599 
3600 	error = 0;
3601 
3602 	ccb = cdgetccb(periph, CAM_PRIORITY_NORMAL);
3603 
3604 	csio = &ccb->csio;
3605 
3606 	cam_fill_csio(csio,
3607 		      /* retries */ cd_retry_count,
3608 		      /* cbfcnp */ cddone,
3609 		      /* flags */ CAM_DIR_NONE,
3610 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3611 		      /* data_ptr */ NULL,
3612 		      /* dxfer_len */ 0,
3613 		      /* sense_len */ SSD_FULL_SIZE,
3614 		      sizeof(struct scsi_pause),
3615  		      /* timeout */ 50000);
3616 
3617 	scsi_cmd = (struct scsi_pause *)&csio->cdb_io.cdb_bytes;
3618 	bzero (scsi_cmd, sizeof(*scsi_cmd));
3619 
3620         scsi_cmd->op_code = PAUSE;
3621 	scsi_cmd->resume = go;
3622 
3623 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3624 			 /*sense_flags*/SF_RETRY_UA);
3625 
3626 	xpt_release_ccb(ccb);
3627 
3628 	return(error);
3629 }
3630 
3631 static int
3632 cdstartunit(struct cam_periph *periph, int load)
3633 {
3634 	union ccb *ccb;
3635 	int error;
3636 
3637 	error = 0;
3638 
3639 	ccb = cdgetccb(periph, CAM_PRIORITY_NORMAL);
3640 
3641 	scsi_start_stop(&ccb->csio,
3642 			/* retries */ cd_retry_count,
3643 			/* cbfcnp */ cddone,
3644 			/* tag_action */ MSG_SIMPLE_Q_TAG,
3645 			/* start */ TRUE,
3646 			/* load_eject */ load,
3647 			/* immediate */ FALSE,
3648 			/* sense_len */ SSD_FULL_SIZE,
3649 			/* timeout */ 50000);
3650 
3651 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3652 			 /*sense_flags*/SF_RETRY_UA);
3653 
3654 	xpt_release_ccb(ccb);
3655 
3656 	return(error);
3657 }
3658 
3659 static int
3660 cdstopunit(struct cam_periph *periph, u_int32_t eject)
3661 {
3662 	union ccb *ccb;
3663 	int error;
3664 
3665 	error = 0;
3666 
3667 	ccb = cdgetccb(periph, CAM_PRIORITY_NORMAL);
3668 
3669 	scsi_start_stop(&ccb->csio,
3670 			/* retries */ cd_retry_count,
3671 			/* cbfcnp */ cddone,
3672 			/* tag_action */ MSG_SIMPLE_Q_TAG,
3673 			/* start */ FALSE,
3674 			/* load_eject */ eject,
3675 			/* immediate */ FALSE,
3676 			/* sense_len */ SSD_FULL_SIZE,
3677 			/* timeout */ 50000);
3678 
3679 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3680 			 /*sense_flags*/SF_RETRY_UA);
3681 
3682 	xpt_release_ccb(ccb);
3683 
3684 	return(error);
3685 }
3686 
3687 static int
3688 cdsetspeed(struct cam_periph *periph, u_int32_t rdspeed, u_int32_t wrspeed)
3689 {
3690 	struct scsi_set_speed *scsi_cmd;
3691 	struct ccb_scsiio *csio;
3692 	union ccb *ccb;
3693 	int error;
3694 
3695 	error = 0;
3696 	ccb = cdgetccb(periph, CAM_PRIORITY_NORMAL);
3697 	csio = &ccb->csio;
3698 
3699 	/* Preserve old behavior: units in multiples of CDROM speed */
3700 	if (rdspeed < 177)
3701 		rdspeed *= 177;
3702 	if (wrspeed < 177)
3703 		wrspeed *= 177;
3704 
3705 	cam_fill_csio(csio,
3706 		      /* retries */ cd_retry_count,
3707 		      /* cbfcnp */ cddone,
3708 		      /* flags */ CAM_DIR_NONE,
3709 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3710 		      /* data_ptr */ NULL,
3711 		      /* dxfer_len */ 0,
3712 		      /* sense_len */ SSD_FULL_SIZE,
3713 		      sizeof(struct scsi_set_speed),
3714  		      /* timeout */ 50000);
3715 
3716 	scsi_cmd = (struct scsi_set_speed *)&csio->cdb_io.cdb_bytes;
3717 	bzero(scsi_cmd, sizeof(*scsi_cmd));
3718 
3719 	scsi_cmd->opcode = SET_CD_SPEED;
3720 	scsi_ulto2b(rdspeed, scsi_cmd->readspeed);
3721 	scsi_ulto2b(wrspeed, scsi_cmd->writespeed);
3722 
3723 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3724 			 /*sense_flags*/SF_RETRY_UA);
3725 
3726 	xpt_release_ccb(ccb);
3727 
3728 	return(error);
3729 }
3730 
3731 static int
3732 cdreportkey(struct cam_periph *periph, struct dvd_authinfo *authinfo)
3733 {
3734 	union ccb *ccb;
3735 	u_int8_t *databuf;
3736 	u_int32_t lba;
3737 	int error;
3738 	int length;
3739 
3740 	error = 0;
3741 	databuf = NULL;
3742 	lba = 0;
3743 
3744 	switch (authinfo->format) {
3745 	case DVD_REPORT_AGID:
3746 		length = sizeof(struct scsi_report_key_data_agid);
3747 		break;
3748 	case DVD_REPORT_CHALLENGE:
3749 		length = sizeof(struct scsi_report_key_data_challenge);
3750 		break;
3751 	case DVD_REPORT_KEY1:
3752 		length = sizeof(struct scsi_report_key_data_key1_key2);
3753 		break;
3754 	case DVD_REPORT_TITLE_KEY:
3755 		length = sizeof(struct scsi_report_key_data_title);
3756 		/* The lba field is only set for the title key */
3757 		lba = authinfo->lba;
3758 		break;
3759 	case DVD_REPORT_ASF:
3760 		length = sizeof(struct scsi_report_key_data_asf);
3761 		break;
3762 	case DVD_REPORT_RPC:
3763 		length = sizeof(struct scsi_report_key_data_rpc);
3764 		break;
3765 	case DVD_INVALIDATE_AGID:
3766 		length = 0;
3767 		break;
3768 	default:
3769 		return (EINVAL);
3770 	}
3771 
3772 	if (length != 0) {
3773 		databuf = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3774 	} else
3775 		databuf = NULL;
3776 
3777 	cam_periph_lock(periph);
3778 	ccb = cdgetccb(periph, CAM_PRIORITY_NORMAL);
3779 
3780 	scsi_report_key(&ccb->csio,
3781 			/* retries */ cd_retry_count,
3782 			/* cbfcnp */ cddone,
3783 			/* tag_action */ MSG_SIMPLE_Q_TAG,
3784 			/* lba */ lba,
3785 			/* agid */ authinfo->agid,
3786 			/* key_format */ authinfo->format,
3787 			/* data_ptr */ databuf,
3788 			/* dxfer_len */ length,
3789 			/* sense_len */ SSD_FULL_SIZE,
3790 			/* timeout */ 50000);
3791 
3792 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3793 			 /*sense_flags*/SF_RETRY_UA);
3794 
3795 	if (error != 0)
3796 		goto bailout;
3797 
3798 	if (ccb->csio.resid != 0) {
3799 		xpt_print(periph->path, "warning, residual for report key "
3800 		    "command is %d\n", ccb->csio.resid);
3801 	}
3802 
3803 	switch(authinfo->format) {
3804 	case DVD_REPORT_AGID: {
3805 		struct scsi_report_key_data_agid *agid_data;
3806 
3807 		agid_data = (struct scsi_report_key_data_agid *)databuf;
3808 
3809 		authinfo->agid = (agid_data->agid & RKD_AGID_MASK) >>
3810 			RKD_AGID_SHIFT;
3811 		break;
3812 	}
3813 	case DVD_REPORT_CHALLENGE: {
3814 		struct scsi_report_key_data_challenge *chal_data;
3815 
3816 		chal_data = (struct scsi_report_key_data_challenge *)databuf;
3817 
3818 		bcopy(chal_data->challenge_key, authinfo->keychal,
3819 		      min(sizeof(chal_data->challenge_key),
3820 		          sizeof(authinfo->keychal)));
3821 		break;
3822 	}
3823 	case DVD_REPORT_KEY1: {
3824 		struct scsi_report_key_data_key1_key2 *key1_data;
3825 
3826 		key1_data = (struct scsi_report_key_data_key1_key2 *)databuf;
3827 
3828 		bcopy(key1_data->key1, authinfo->keychal,
3829 		      min(sizeof(key1_data->key1), sizeof(authinfo->keychal)));
3830 		break;
3831 	}
3832 	case DVD_REPORT_TITLE_KEY: {
3833 		struct scsi_report_key_data_title *title_data;
3834 
3835 		title_data = (struct scsi_report_key_data_title *)databuf;
3836 
3837 		authinfo->cpm = (title_data->byte0 & RKD_TITLE_CPM) >>
3838 			RKD_TITLE_CPM_SHIFT;
3839 		authinfo->cp_sec = (title_data->byte0 & RKD_TITLE_CP_SEC) >>
3840 			RKD_TITLE_CP_SEC_SHIFT;
3841 		authinfo->cgms = (title_data->byte0 & RKD_TITLE_CMGS_MASK) >>
3842 			RKD_TITLE_CMGS_SHIFT;
3843 		bcopy(title_data->title_key, authinfo->keychal,
3844 		      min(sizeof(title_data->title_key),
3845 			  sizeof(authinfo->keychal)));
3846 		break;
3847 	}
3848 	case DVD_REPORT_ASF: {
3849 		struct scsi_report_key_data_asf *asf_data;
3850 
3851 		asf_data = (struct scsi_report_key_data_asf *)databuf;
3852 
3853 		authinfo->asf = asf_data->success & RKD_ASF_SUCCESS;
3854 		break;
3855 	}
3856 	case DVD_REPORT_RPC: {
3857 		struct scsi_report_key_data_rpc *rpc_data;
3858 
3859 		rpc_data = (struct scsi_report_key_data_rpc *)databuf;
3860 
3861 		authinfo->reg_type = (rpc_data->byte4 & RKD_RPC_TYPE_MASK) >>
3862 			RKD_RPC_TYPE_SHIFT;
3863 		authinfo->vend_rsts =
3864 			(rpc_data->byte4 & RKD_RPC_VENDOR_RESET_MASK) >>
3865 			RKD_RPC_VENDOR_RESET_SHIFT;
3866 		authinfo->user_rsts = rpc_data->byte4 & RKD_RPC_USER_RESET_MASK;
3867 		authinfo->region = rpc_data->region_mask;
3868 		authinfo->rpc_scheme = rpc_data->rpc_scheme1;
3869 		break;
3870 	}
3871 	case DVD_INVALIDATE_AGID:
3872 		break;
3873 	default:
3874 		/* This should be impossible, since we checked above */
3875 		error = EINVAL;
3876 		goto bailout;
3877 		break; /* NOTREACHED */
3878 	}
3879 
3880 bailout:
3881 	xpt_release_ccb(ccb);
3882 	cam_periph_unlock(periph);
3883 
3884 	if (databuf != NULL)
3885 		free(databuf, M_DEVBUF);
3886 
3887 	return(error);
3888 }
3889 
3890 static int
3891 cdsendkey(struct cam_periph *periph, struct dvd_authinfo *authinfo)
3892 {
3893 	union ccb *ccb;
3894 	u_int8_t *databuf;
3895 	int length;
3896 	int error;
3897 
3898 	error = 0;
3899 	databuf = NULL;
3900 
3901 	switch(authinfo->format) {
3902 	case DVD_SEND_CHALLENGE: {
3903 		struct scsi_report_key_data_challenge *challenge_data;
3904 
3905 		length = sizeof(*challenge_data);
3906 
3907 		challenge_data = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3908 
3909 		databuf = (u_int8_t *)challenge_data;
3910 
3911 		scsi_ulto2b(length - sizeof(challenge_data->data_len),
3912 			    challenge_data->data_len);
3913 
3914 		bcopy(authinfo->keychal, challenge_data->challenge_key,
3915 		      min(sizeof(authinfo->keychal),
3916 			  sizeof(challenge_data->challenge_key)));
3917 		break;
3918 	}
3919 	case DVD_SEND_KEY2: {
3920 		struct scsi_report_key_data_key1_key2 *key2_data;
3921 
3922 		length = sizeof(*key2_data);
3923 
3924 		key2_data = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3925 
3926 		databuf = (u_int8_t *)key2_data;
3927 
3928 		scsi_ulto2b(length - sizeof(key2_data->data_len),
3929 			    key2_data->data_len);
3930 
3931 		bcopy(authinfo->keychal, key2_data->key1,
3932 		      min(sizeof(authinfo->keychal), sizeof(key2_data->key1)));
3933 
3934 		break;
3935 	}
3936 	case DVD_SEND_RPC: {
3937 		struct scsi_send_key_data_rpc *rpc_data;
3938 
3939 		length = sizeof(*rpc_data);
3940 
3941 		rpc_data = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3942 
3943 		databuf = (u_int8_t *)rpc_data;
3944 
3945 		scsi_ulto2b(length - sizeof(rpc_data->data_len),
3946 			    rpc_data->data_len);
3947 
3948 		rpc_data->region_code = authinfo->region;
3949 		break;
3950 	}
3951 	default:
3952 		return (EINVAL);
3953 	}
3954 
3955 	cam_periph_lock(periph);
3956 	ccb = cdgetccb(periph, CAM_PRIORITY_NORMAL);
3957 
3958 	scsi_send_key(&ccb->csio,
3959 		      /* retries */ cd_retry_count,
3960 		      /* cbfcnp */ cddone,
3961 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3962 		      /* agid */ authinfo->agid,
3963 		      /* key_format */ authinfo->format,
3964 		      /* data_ptr */ databuf,
3965 		      /* dxfer_len */ length,
3966 		      /* sense_len */ SSD_FULL_SIZE,
3967 		      /* timeout */ 50000);
3968 
3969 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3970 			 /*sense_flags*/SF_RETRY_UA);
3971 
3972 	xpt_release_ccb(ccb);
3973 	cam_periph_unlock(periph);
3974 
3975 	if (databuf != NULL)
3976 		free(databuf, M_DEVBUF);
3977 
3978 	return(error);
3979 }
3980 
3981 static int
3982 cdreaddvdstructure(struct cam_periph *periph, struct dvd_struct *dvdstruct)
3983 {
3984 	union ccb *ccb;
3985 	u_int8_t *databuf;
3986 	u_int32_t address;
3987 	int error;
3988 	int length;
3989 
3990 	error = 0;
3991 	databuf = NULL;
3992 	/* The address is reserved for many of the formats */
3993 	address = 0;
3994 
3995 	switch(dvdstruct->format) {
3996 	case DVD_STRUCT_PHYSICAL:
3997 		length = sizeof(struct scsi_read_dvd_struct_data_physical);
3998 		break;
3999 	case DVD_STRUCT_COPYRIGHT:
4000 		length = sizeof(struct scsi_read_dvd_struct_data_copyright);
4001 		break;
4002 	case DVD_STRUCT_DISCKEY:
4003 		length = sizeof(struct scsi_read_dvd_struct_data_disc_key);
4004 		break;
4005 	case DVD_STRUCT_BCA:
4006 		length = sizeof(struct scsi_read_dvd_struct_data_bca);
4007 		break;
4008 	case DVD_STRUCT_MANUFACT:
4009 		length = sizeof(struct scsi_read_dvd_struct_data_manufacturer);
4010 		break;
4011 	case DVD_STRUCT_CMI:
4012 		return (ENODEV);
4013 	case DVD_STRUCT_PROTDISCID:
4014 		length = sizeof(struct scsi_read_dvd_struct_data_prot_discid);
4015 		break;
4016 	case DVD_STRUCT_DISCKEYBLOCK:
4017 		length = sizeof(struct scsi_read_dvd_struct_data_disc_key_blk);
4018 		break;
4019 	case DVD_STRUCT_DDS:
4020 		length = sizeof(struct scsi_read_dvd_struct_data_dds);
4021 		break;
4022 	case DVD_STRUCT_MEDIUM_STAT:
4023 		length = sizeof(struct scsi_read_dvd_struct_data_medium_status);
4024 		break;
4025 	case DVD_STRUCT_SPARE_AREA:
4026 		length = sizeof(struct scsi_read_dvd_struct_data_spare_area);
4027 		break;
4028 	case DVD_STRUCT_RMD_LAST:
4029 		return (ENODEV);
4030 	case DVD_STRUCT_RMD_RMA:
4031 		return (ENODEV);
4032 	case DVD_STRUCT_PRERECORDED:
4033 		length = sizeof(struct scsi_read_dvd_struct_data_leadin);
4034 		break;
4035 	case DVD_STRUCT_UNIQUEID:
4036 		length = sizeof(struct scsi_read_dvd_struct_data_disc_id);
4037 		break;
4038 	case DVD_STRUCT_DCB:
4039 		return (ENODEV);
4040 	case DVD_STRUCT_LIST:
4041 		/*
4042 		 * This is the maximum allocation length for the READ DVD
4043 		 * STRUCTURE command.  There's nothing in the MMC3 spec
4044 		 * that indicates a limit in the amount of data that can
4045 		 * be returned from this call, other than the limits
4046 		 * imposed by the 2-byte length variables.
4047 		 */
4048 		length = 65535;
4049 		break;
4050 	default:
4051 		return (EINVAL);
4052 	}
4053 
4054 	if (length != 0) {
4055 		databuf = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
4056 	} else
4057 		databuf = NULL;
4058 
4059 	cam_periph_lock(periph);
4060 	ccb = cdgetccb(periph, CAM_PRIORITY_NORMAL);
4061 
4062 	scsi_read_dvd_structure(&ccb->csio,
4063 				/* retries */ cd_retry_count,
4064 				/* cbfcnp */ cddone,
4065 				/* tag_action */ MSG_SIMPLE_Q_TAG,
4066 				/* lba */ address,
4067 				/* layer_number */ dvdstruct->layer_num,
4068 				/* key_format */ dvdstruct->format,
4069 				/* agid */ dvdstruct->agid,
4070 				/* data_ptr */ databuf,
4071 				/* dxfer_len */ length,
4072 				/* sense_len */ SSD_FULL_SIZE,
4073 				/* timeout */ 50000);
4074 
4075 	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
4076 			 /*sense_flags*/SF_RETRY_UA);
4077 
4078 	if (error != 0)
4079 		goto bailout;
4080 
4081 	switch(dvdstruct->format) {
4082 	case DVD_STRUCT_PHYSICAL: {
4083 		struct scsi_read_dvd_struct_data_layer_desc *inlayer;
4084 		struct dvd_layer *outlayer;
4085 		struct scsi_read_dvd_struct_data_physical *phys_data;
4086 
4087 		phys_data =
4088 			(struct scsi_read_dvd_struct_data_physical *)databuf;
4089 		inlayer = &phys_data->layer_desc;
4090 		outlayer = (struct dvd_layer *)&dvdstruct->data;
4091 
4092 		dvdstruct->length = sizeof(*inlayer);
4093 
4094 		outlayer->book_type = (inlayer->book_type_version &
4095 			RDSD_BOOK_TYPE_MASK) >> RDSD_BOOK_TYPE_SHIFT;
4096 		outlayer->book_version = (inlayer->book_type_version &
4097 			RDSD_BOOK_VERSION_MASK);
4098 		outlayer->disc_size = (inlayer->disc_size_max_rate &
4099 			RDSD_DISC_SIZE_MASK) >> RDSD_DISC_SIZE_SHIFT;
4100 		outlayer->max_rate = (inlayer->disc_size_max_rate &
4101 			RDSD_MAX_RATE_MASK);
4102 		outlayer->nlayers = (inlayer->layer_info &
4103 			RDSD_NUM_LAYERS_MASK) >> RDSD_NUM_LAYERS_SHIFT;
4104 		outlayer->track_path = (inlayer->layer_info &
4105 			RDSD_TRACK_PATH_MASK) >> RDSD_TRACK_PATH_SHIFT;
4106 		outlayer->layer_type = (inlayer->layer_info &
4107 			RDSD_LAYER_TYPE_MASK);
4108 		outlayer->linear_density = (inlayer->density &
4109 			RDSD_LIN_DENSITY_MASK) >> RDSD_LIN_DENSITY_SHIFT;
4110 		outlayer->track_density = (inlayer->density &
4111 			RDSD_TRACK_DENSITY_MASK);
4112 		outlayer->bca = (inlayer->bca & RDSD_BCA_MASK) >>
4113 			RDSD_BCA_SHIFT;
4114 		outlayer->start_sector = scsi_3btoul(inlayer->main_data_start);
4115 		outlayer->end_sector = scsi_3btoul(inlayer->main_data_end);
4116 		outlayer->end_sector_l0 =
4117 			scsi_3btoul(inlayer->end_sector_layer0);
4118 		break;
4119 	}
4120 	case DVD_STRUCT_COPYRIGHT: {
4121 		struct scsi_read_dvd_struct_data_copyright *copy_data;
4122 
4123 		copy_data = (struct scsi_read_dvd_struct_data_copyright *)
4124 			databuf;
4125 
4126 		dvdstruct->cpst = copy_data->cps_type;
4127 		dvdstruct->rmi = copy_data->region_info;
4128 		dvdstruct->length = 0;
4129 
4130 		break;
4131 	}
4132 	default:
4133 		/*
4134 		 * Tell the user what the overall length is, no matter
4135 		 * what we can actually fit in the data buffer.
4136 		 */
4137 		dvdstruct->length = length - ccb->csio.resid -
4138 			sizeof(struct scsi_read_dvd_struct_data_header);
4139 
4140 		/*
4141 		 * But only actually copy out the smaller of what we read
4142 		 * in or what the structure can take.
4143 		 */
4144 		bcopy(databuf + sizeof(struct scsi_read_dvd_struct_data_header),
4145 		      dvdstruct->data,
4146 		      min(sizeof(dvdstruct->data), dvdstruct->length));
4147 		break;
4148 	}
4149 
4150 bailout:
4151 	xpt_release_ccb(ccb);
4152 	cam_periph_unlock(periph);
4153 
4154 	if (databuf != NULL)
4155 		free(databuf, M_DEVBUF);
4156 
4157 	return(error);
4158 }
4159 
4160 void
4161 scsi_report_key(struct ccb_scsiio *csio, u_int32_t retries,
4162 		void (*cbfcnp)(struct cam_periph *, union ccb *),
4163 		u_int8_t tag_action, u_int32_t lba, u_int8_t agid,
4164 		u_int8_t key_format, u_int8_t *data_ptr, u_int32_t dxfer_len,
4165 		u_int8_t sense_len, u_int32_t timeout)
4166 {
4167 	struct scsi_report_key *scsi_cmd;
4168 
4169 	scsi_cmd = (struct scsi_report_key *)&csio->cdb_io.cdb_bytes;
4170 	bzero(scsi_cmd, sizeof(*scsi_cmd));
4171 	scsi_cmd->opcode = REPORT_KEY;
4172 	scsi_ulto4b(lba, scsi_cmd->lba);
4173 	scsi_ulto2b(dxfer_len, scsi_cmd->alloc_len);
4174 	scsi_cmd->agid_keyformat = (agid << RK_KF_AGID_SHIFT) |
4175 		(key_format & RK_KF_KEYFORMAT_MASK);
4176 
4177 	cam_fill_csio(csio,
4178 		      retries,
4179 		      cbfcnp,
4180 		      /*flags*/ (dxfer_len == 0) ? CAM_DIR_NONE : CAM_DIR_IN,
4181 		      tag_action,
4182 		      /*data_ptr*/ data_ptr,
4183 		      /*dxfer_len*/ dxfer_len,
4184 		      sense_len,
4185 		      sizeof(*scsi_cmd),
4186 		      timeout);
4187 }
4188 
4189 void
4190 scsi_send_key(struct ccb_scsiio *csio, u_int32_t retries,
4191 	      void (*cbfcnp)(struct cam_periph *, union ccb *),
4192 	      u_int8_t tag_action, u_int8_t agid, u_int8_t key_format,
4193 	      u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
4194 	      u_int32_t timeout)
4195 {
4196 	struct scsi_send_key *scsi_cmd;
4197 
4198 	scsi_cmd = (struct scsi_send_key *)&csio->cdb_io.cdb_bytes;
4199 	bzero(scsi_cmd, sizeof(*scsi_cmd));
4200 	scsi_cmd->opcode = SEND_KEY;
4201 
4202 	scsi_ulto2b(dxfer_len, scsi_cmd->param_len);
4203 	scsi_cmd->agid_keyformat = (agid << RK_KF_AGID_SHIFT) |
4204 		(key_format & RK_KF_KEYFORMAT_MASK);
4205 
4206 	cam_fill_csio(csio,
4207 		      retries,
4208 		      cbfcnp,
4209 		      /*flags*/ CAM_DIR_OUT,
4210 		      tag_action,
4211 		      /*data_ptr*/ data_ptr,
4212 		      /*dxfer_len*/ dxfer_len,
4213 		      sense_len,
4214 		      sizeof(*scsi_cmd),
4215 		      timeout);
4216 }
4217 
4218 
4219 void
4220 scsi_read_dvd_structure(struct ccb_scsiio *csio, u_int32_t retries,
4221 			void (*cbfcnp)(struct cam_periph *, union ccb *),
4222 			u_int8_t tag_action, u_int32_t address,
4223 			u_int8_t layer_number, u_int8_t format, u_int8_t agid,
4224 			u_int8_t *data_ptr, u_int32_t dxfer_len,
4225 			u_int8_t sense_len, u_int32_t timeout)
4226 {
4227 	struct scsi_read_dvd_structure *scsi_cmd;
4228 
4229 	scsi_cmd = (struct scsi_read_dvd_structure *)&csio->cdb_io.cdb_bytes;
4230 	bzero(scsi_cmd, sizeof(*scsi_cmd));
4231 	scsi_cmd->opcode = READ_DVD_STRUCTURE;
4232 
4233 	scsi_ulto4b(address, scsi_cmd->address);
4234 	scsi_cmd->layer_number = layer_number;
4235 	scsi_cmd->format = format;
4236 	scsi_ulto2b(dxfer_len, scsi_cmd->alloc_len);
4237 	/* The AGID is the top two bits of this byte */
4238 	scsi_cmd->agid = agid << 6;
4239 
4240 	cam_fill_csio(csio,
4241 		      retries,
4242 		      cbfcnp,
4243 		      /*flags*/ CAM_DIR_IN,
4244 		      tag_action,
4245 		      /*data_ptr*/ data_ptr,
4246 		      /*dxfer_len*/ dxfer_len,
4247 		      sense_len,
4248 		      sizeof(*scsi_cmd),
4249 		      timeout);
4250 }
4251