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