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