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