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