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