xref: /dragonfly/sys/bus/cam/scsi/scsi_cd.c (revision 49781055)
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.20 2006/02/17 19:17:42 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 			scsi_read_write(&start_ccb->csio,
1548 					/*retries*/4,
1549 					/* cbfcnp */ cddone,
1550 					(bp->b_flags & B_ORDERED) != 0 ?
1551 					    MSG_ORDERED_Q_TAG :
1552 					    MSG_SIMPLE_Q_TAG,
1553 					/* read */bp->b_flags & B_READ,
1554 					/* byte2 */ 0,
1555 					/* minimum_cmd_size */ 10,
1556 					/* lba */ bio->bio_blkno,
1557 					bp->b_bcount / softc->params.blksize,
1558 					/* data_ptr */ bp->b_data,
1559 					/* dxfer_len */ bp->b_bcount,
1560 					/* sense_len */ SSD_FULL_SIZE,
1561 					/* timeout */ 30000);
1562 			start_ccb->ccb_h.ccb_state = CD_CCB_BUFFER_IO;
1563 
1564 
1565 			/*
1566 			 * Block out any asyncronous callbacks
1567 			 * while we touch the pending ccb list.
1568 			 */
1569 			LIST_INSERT_HEAD(&softc->pending_ccbs,
1570 					 &start_ccb->ccb_h, periph_links.le);
1571 
1572 			/* We expect a unit attention from this device */
1573 			if ((softc->flags & CD_FLAG_RETRY_UA) != 0) {
1574 				start_ccb->ccb_h.ccb_state |= CD_CCB_RETRY_UA;
1575 				softc->flags &= ~CD_FLAG_RETRY_UA;
1576 			}
1577 
1578 			start_ccb->ccb_h.ccb_bio = bio;
1579 			bio = bioq_first(&softc->bio_queue);
1580 			crit_exit();
1581 
1582 			xpt_action(start_ccb);
1583 		}
1584 		if (bio != NULL) {
1585 			/* Have more work to do, so ensure we stay scheduled */
1586 			xpt_schedule(periph, /* XXX priority */1);
1587 		}
1588 		break;
1589 	}
1590 	case CD_STATE_PROBE:
1591 	{
1592 
1593 		rcap = malloc(sizeof(*rcap), M_TEMP, M_INTWAIT);
1594 		csio = &start_ccb->csio;
1595 		scsi_read_capacity(csio,
1596 				   /*retries*/1,
1597 				   cddone,
1598 				   MSG_SIMPLE_Q_TAG,
1599 				   rcap,
1600 				   SSD_FULL_SIZE,
1601 				   /*timeout*/20000);
1602 		start_ccb->ccb_h.ccb_bio = NULL;
1603 		start_ccb->ccb_h.ccb_state = CD_CCB_PROBE;
1604 		xpt_action(start_ccb);
1605 		break;
1606 	}
1607 	}
1608 }
1609 
1610 static void
1611 cddone(struct cam_periph *periph, union ccb *done_ccb)
1612 {
1613 	struct cd_softc *softc;
1614 	struct ccb_scsiio *csio;
1615 
1616 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cddone\n"));
1617 
1618 	softc = (struct cd_softc *)periph->softc;
1619 	csio = &done_ccb->csio;
1620 
1621 	switch (csio->ccb_h.ccb_state & CD_CCB_TYPE_MASK) {
1622 	case CD_CCB_BUFFER_IO:
1623 	{
1624 		struct buf	*bp;
1625 		struct bio	*bio;
1626 		int		error;
1627 
1628 		bio = (struct bio *)done_ccb->ccb_h.ccb_bio;
1629 		bp = bio->bio_buf;
1630 		error = 0;
1631 
1632 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1633 			int sf;
1634 
1635 			if ((done_ccb->ccb_h.ccb_state & CD_CCB_RETRY_UA) != 0)
1636 				sf = SF_RETRY_UA;
1637 			else
1638 				sf = 0;
1639 
1640 			/* Retry selection timeouts */
1641 			sf |= SF_RETRY_SELTO;
1642 
1643 			if ((error = cderror(done_ccb, 0, sf)) == ERESTART) {
1644 				/*
1645 				 * A retry was scheuled, so
1646 				 * just return.
1647 				 */
1648 				return;
1649 			}
1650 		}
1651 
1652 		if (error != 0) {
1653 			struct bio *q_bio;
1654 			struct buf *q_bp;
1655 
1656 			xpt_print_path(periph->path);
1657 			printf("cddone: got error %#x back\n", error);
1658 			crit_enter();
1659 			while ((q_bio = bioq_first(&softc->bio_queue)) != NULL) {
1660 				bioq_remove(&softc->bio_queue, q_bio);
1661 				q_bp = q_bio->bio_buf;
1662 				q_bp->b_resid = q_bp->b_bcount;
1663 				q_bp->b_error = EIO;
1664 				q_bp->b_flags |= B_ERROR;
1665 				biodone(q_bio);
1666 			}
1667 			crit_exit();
1668 			bp->b_resid = bp->b_bcount;
1669 			bp->b_error = error;
1670 			bp->b_flags |= B_ERROR;
1671 			cam_release_devq(done_ccb->ccb_h.path,
1672 					 /*relsim_flags*/0,
1673 					 /*reduction*/0,
1674 					 /*timeout*/0,
1675 					 /*getcount_only*/0);
1676 
1677 		} else {
1678 			bp->b_resid = csio->resid;
1679 			bp->b_error = 0;
1680 			if (bp->b_resid != 0) {
1681 				/* Short transfer ??? */
1682 				bp->b_flags |= B_ERROR;
1683 			}
1684 		}
1685 
1686 		/*
1687 		 * Block out any asyncronous callbacks
1688 		 * while we touch the pending ccb list.
1689 		 */
1690 		crit_enter();
1691 		LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
1692 		crit_exit();
1693 
1694 		if (softc->flags & CD_FLAG_CHANGER)
1695 			cdchangerschedule(softc);
1696 
1697 		devstat_end_transaction_buf(&softc->device_stats, bp);
1698 		biodone(bio);
1699 		break;
1700 	}
1701 	case CD_CCB_PROBE:
1702 	{
1703 		struct	   scsi_read_capacity_data *rdcap;
1704 		char	   announce_buf[120]; /*
1705 					       * Currently (9/30/97) the
1706 					       * longest possible announce
1707 					       * buffer is 108 bytes, for the
1708 					       * first error case below.
1709 					       * That is 39 bytes for the
1710 					       * basic string, 16 bytes for the
1711 					       * biggest sense key (hardware
1712 					       * error), 52 bytes for the
1713 					       * text of the largest sense
1714 					       * qualifier valid for a CDROM,
1715 					       * (0x72, 0x03 or 0x04,
1716 					       * 0x03), and one byte for the
1717 					       * null terminating character.
1718 					       * To allow for longer strings,
1719 					       * the announce buffer is 120
1720 					       * bytes.
1721 					       */
1722 		struct	   cd_params *cdp;
1723 
1724 		cdp = &softc->params;
1725 
1726 		rdcap = (struct scsi_read_capacity_data *)csio->data_ptr;
1727 
1728 		cdp->disksize = scsi_4btoul (rdcap->addr) + 1;
1729 		cdp->blksize = scsi_4btoul (rdcap->length);
1730 
1731 		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1732 
1733 			snprintf(announce_buf, sizeof(announce_buf),
1734 				"cd present [%lu x %lu byte records]",
1735 				cdp->disksize, (u_long)cdp->blksize);
1736 
1737 		} else {
1738 			int	error;
1739 			/*
1740 			 * Retry any UNIT ATTENTION type errors.  They
1741 			 * are expected at boot.
1742 			 */
1743 			error = cderror(done_ccb, 0, SF_RETRY_UA |
1744 					SF_NO_PRINT | SF_RETRY_SELTO);
1745 			if (error == ERESTART) {
1746 				/*
1747 				 * A retry was scheuled, so
1748 				 * just return.
1749 				 */
1750 				return;
1751 			} else if (error != 0) {
1752 
1753 				struct scsi_sense_data *sense;
1754 				int asc, ascq;
1755 				int sense_key, error_code;
1756 				int have_sense;
1757 				cam_status status;
1758 				struct ccb_getdev cgd;
1759 
1760 				/* Don't wedge this device's queue */
1761 				cam_release_devq(done_ccb->ccb_h.path,
1762 						 /*relsim_flags*/0,
1763 						 /*reduction*/0,
1764 						 /*timeout*/0,
1765 						 /*getcount_only*/0);
1766 
1767 				status = done_ccb->ccb_h.status;
1768 
1769 				xpt_setup_ccb(&cgd.ccb_h,
1770 					      done_ccb->ccb_h.path,
1771 					      /* priority */ 1);
1772 				cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1773 				xpt_action((union ccb *)&cgd);
1774 
1775 				if (((csio->ccb_h.flags & CAM_SENSE_PHYS) != 0)
1776 				 || ((csio->ccb_h.flags & CAM_SENSE_PTR) != 0)
1777 				 || ((status & CAM_AUTOSNS_VALID) == 0))
1778 					have_sense = FALSE;
1779 				else
1780 					have_sense = TRUE;
1781 
1782 				if (have_sense) {
1783 					sense = &csio->sense_data;
1784 					scsi_extract_sense(sense, &error_code,
1785 							   &sense_key,
1786 							   &asc, &ascq);
1787 				}
1788 				/*
1789 				 * Attach to anything that claims to be a
1790 				 * CDROM or WORM device, as long as it
1791 				 * doesn't return a "Logical unit not
1792 				 * supported" (0x25) error.
1793 				 */
1794 				if ((have_sense) && (asc != 0x25)
1795 				 && (error_code == SSD_CURRENT_ERROR))
1796 					snprintf(announce_buf,
1797 					    sizeof(announce_buf),
1798 						"Attempt to query device "
1799 						"size failed: %s, %s",
1800 						scsi_sense_key_text[sense_key],
1801 						scsi_sense_desc(asc,ascq,
1802 								&cgd.inq_data));
1803 				else if ((have_sense == 0)
1804 				      && ((status & CAM_STATUS_MASK) ==
1805 					   CAM_SCSI_STATUS_ERROR)
1806 				      && (csio->scsi_status ==
1807 					  SCSI_STATUS_BUSY)) {
1808 					snprintf(announce_buf,
1809 					    sizeof(announce_buf),
1810 					    "Attempt to query device "
1811 					    "size failed: SCSI status: BUSY");
1812 				} else if (SID_TYPE(&cgd.inq_data) == T_CDROM) {
1813 					/*
1814 					 * We only print out an error for
1815 					 * CDROM type devices.  For WORM
1816 					 * devices, we don't print out an
1817 					 * error since a few WORM devices
1818 					 * don't support CDROM commands.
1819 					 * If we have sense information, go
1820 					 * ahead and print it out.
1821 					 * Otherwise, just say that we
1822 					 * couldn't attach.
1823 					 */
1824 
1825 					/*
1826 					 * Just print out the error, not
1827 					 * the full probe message, when we
1828 					 * don't attach.
1829 					 */
1830 					if (have_sense)
1831 						scsi_sense_print(
1832 							&done_ccb->csio);
1833 					else {
1834 						xpt_print_path(periph->path);
1835 						printf("got CAM status %#x\n",
1836 						       done_ccb->ccb_h.status);
1837 					}
1838 					xpt_print_path(periph->path);
1839 					printf("fatal error, failed"
1840 					       " to attach to device\n");
1841 
1842 					/*
1843 					 * Invalidate this peripheral.
1844 					 */
1845 					cam_periph_invalidate(periph);
1846 
1847 					announce_buf[0] = '\0';
1848 				} else {
1849 
1850 					/*
1851 					 * Invalidate this peripheral.
1852 					 */
1853 					cam_periph_invalidate(periph);
1854 					announce_buf[0] = '\0';
1855 				}
1856 			}
1857 		}
1858 		free(rdcap, M_TEMP);
1859 		if (announce_buf[0] != '\0') {
1860 			xpt_announce_periph(periph, announce_buf);
1861 			if (softc->flags & CD_FLAG_CHANGER)
1862 				cdchangerschedule(softc);
1863 			/*
1864 			 * Create our sysctl variables, now that we know
1865 			 * we have successfully attached.
1866 			 */
1867 			taskqueue_enqueue(taskqueue_thread[mycpuid],
1868 			    &softc->sysctl_task);
1869 		}
1870 		softc->state = CD_STATE_NORMAL;
1871 		/*
1872 		 * Since our peripheral may be invalidated by an error
1873 		 * above or an external event, we must release our CCB
1874 		 * before releasing the probe lock on the peripheral.
1875 		 * The peripheral will only go away once the last lock
1876 		 * is removed, and we need it around for the CCB release
1877 		 * operation.
1878 		 */
1879 		xpt_release_ccb(done_ccb);
1880 		cam_periph_unlock(periph);
1881 		return;
1882 	}
1883 	case CD_CCB_WAITING:
1884 	{
1885 		/* Caller will release the CCB */
1886 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1887 			  ("trying to wakeup ccbwait\n"));
1888 
1889 		wakeup(&done_ccb->ccb_h.cbfcnp);
1890 		return;
1891 	}
1892 	default:
1893 		break;
1894 	}
1895 	xpt_release_ccb(done_ccb);
1896 }
1897 
1898 static union cd_pages *
1899 cdgetpage(struct cd_mode_params *mode_params)
1900 {
1901 	union cd_pages *page;
1902 
1903 	if (mode_params->cdb_size == 10)
1904 		page = (union cd_pages *)find_mode_page_10(
1905 			(struct scsi_mode_header_10 *)mode_params->mode_buf);
1906 	else
1907 		page = (union cd_pages *)find_mode_page_6(
1908 			(struct scsi_mode_header_6 *)mode_params->mode_buf);
1909 
1910 	return (page);
1911 }
1912 
1913 static int
1914 cdgetpagesize(int page_num)
1915 {
1916 	int i;
1917 
1918 	for (i = 0; i < (sizeof(cd_page_size_table)/
1919 	    sizeof(cd_page_size_table[0])); i++) {
1920 		if (cd_page_size_table[i].page == page_num)
1921 			return (cd_page_size_table[i].page_size);
1922 	}
1923 	return (-1);
1924 }
1925 
1926 static int
1927 cdioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
1928 {
1929 
1930 	struct 	cam_periph *periph;
1931 	struct	cd_softc *softc;
1932 	int	error, unit;
1933 
1934 	unit = dkunit(dev);
1935 
1936 	periph = cam_extend_get(cdperiphs, unit);
1937 	if (periph == NULL)
1938 		return(ENXIO);
1939 
1940 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdioctl\n"));
1941 
1942 	softc = (struct cd_softc *)periph->softc;
1943 
1944 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1945 		  ("trying to do ioctl %#lx\n", cmd));
1946 
1947 	error = cam_periph_lock(periph, PCATCH);
1948 
1949 	if (error != 0)
1950 		return(error);
1951 
1952 	/*
1953 	 * If we don't have media loaded, check for it.  If still don't
1954 	 * have media loaded, we can only do a load or eject.
1955 	 */
1956 	if (((softc->flags & CD_FLAG_VALID_MEDIA) == 0)
1957 	    && ((cmd != CDIOCCLOSE)
1958 	    && (cmd != CDIOCEJECT))) {
1959 		error = cdcheckmedia(periph);
1960 		if (error != 0) {
1961 			cam_periph_unlock(periph);
1962 			return (error);
1963 		}
1964 	}
1965 
1966 	switch (cmd) {
1967 
1968 	case CDIOCPLAYTRACKS:
1969 		{
1970 			struct ioc_play_track *args
1971 			    = (struct ioc_play_track *) addr;
1972 			struct cd_mode_params params;
1973 			union cd_pages *page;
1974 
1975 			params.alloc_len = sizeof(union cd_mode_data_6_10);
1976 			params.mode_buf = malloc(params.alloc_len, M_TEMP,
1977 						 M_WAITOK | M_ZERO);
1978 
1979 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1980 				  ("trying to do CDIOCPLAYTRACKS\n"));
1981 
1982 			error = cdgetmode(periph, &params, AUDIO_PAGE);
1983 			if (error) {
1984 				free(params.mode_buf, M_TEMP);
1985 				break;
1986 			}
1987 			page = cdgetpage(&params);
1988 
1989 			page->audio.flags &= ~CD_PA_SOTC;
1990 			page->audio.flags |= CD_PA_IMMED;
1991 			error = cdsetmode(periph, &params);
1992 			free(params.mode_buf, M_TEMP);
1993 			if (error)
1994 				break;
1995 
1996 			/*
1997 			 * This was originally implemented with the PLAY
1998 			 * AUDIO TRACK INDEX command, but that command was
1999 			 * deprecated after SCSI-2.  Most (all?) SCSI CDROM
2000 			 * drives support it but ATAPI and ATAPI-derivative
2001 			 * drives don't seem to support it.  So we keep a
2002 			 * cache of the table of contents and translate
2003 			 * track numbers to MSF format.
2004 			 */
2005 			if (softc->flags & CD_FLAG_VALID_TOC) {
2006 				union msf_lba *sentry, *eentry;
2007 				int st, et;
2008 
2009 				if (args->end_track <
2010 				    softc->toc.header.ending_track + 1)
2011 					args->end_track++;
2012 				if (args->end_track >
2013 				    softc->toc.header.ending_track + 1)
2014 					args->end_track =
2015 					    softc->toc.header.ending_track + 1;
2016 				st = args->start_track -
2017 					softc->toc.header.starting_track;
2018 				et = args->end_track -
2019 					softc->toc.header.starting_track;
2020 				if ((st < 0)
2021 				 || (et < 0)
2022 			 	 || (st > (softc->toc.header.ending_track -
2023 				     softc->toc.header.starting_track))) {
2024 					error = EINVAL;
2025 					break;
2026 				}
2027 				sentry = &softc->toc.entries[st].addr;
2028 				eentry = &softc->toc.entries[et].addr;
2029 				error = cdplaymsf(periph,
2030 						  sentry->msf.minute,
2031 						  sentry->msf.second,
2032 						  sentry->msf.frame,
2033 						  eentry->msf.minute,
2034 						  eentry->msf.second,
2035 						  eentry->msf.frame);
2036 			} else {
2037 				/*
2038 				 * If we don't have a valid TOC, try the
2039 				 * play track index command.  It is part of
2040 				 * the SCSI-2 spec, but was removed in the
2041 				 * MMC specs.  ATAPI and ATAPI-derived
2042 				 * drives don't support it.
2043 				 */
2044 				if (softc->quirks & CD_Q_BCD_TRACKS) {
2045 					args->start_track =
2046 						bin2bcd(args->start_track);
2047 					args->end_track =
2048 						bin2bcd(args->end_track);
2049 				}
2050 				error = cdplaytracks(periph,
2051 						     args->start_track,
2052 						     args->start_index,
2053 						     args->end_track,
2054 						     args->end_index);
2055 			}
2056 		}
2057 		break;
2058 	case CDIOCPLAYMSF:
2059 		{
2060 			struct ioc_play_msf *args
2061 				= (struct ioc_play_msf *) addr;
2062 			struct cd_mode_params params;
2063 			union cd_pages *page;
2064 
2065 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2066 			params.mode_buf = malloc(params.alloc_len, M_TEMP,
2067 						 M_WAITOK | M_ZERO);
2068 
2069 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2070 				  ("trying to do CDIOCPLAYMSF\n"));
2071 
2072 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2073 			if (error) {
2074 				free(params.mode_buf, M_TEMP);
2075 				break;
2076 			}
2077 			page = cdgetpage(&params);
2078 
2079 			page->audio.flags &= ~CD_PA_SOTC;
2080 			page->audio.flags |= CD_PA_IMMED;
2081 			error = cdsetmode(periph, &params);
2082 			free(params.mode_buf, M_TEMP);
2083 			if (error)
2084 				break;
2085 			error = cdplaymsf(periph,
2086 					  args->start_m,
2087 					  args->start_s,
2088 					  args->start_f,
2089 					  args->end_m,
2090 					  args->end_s,
2091 					  args->end_f);
2092 		}
2093 		break;
2094 	case CDIOCPLAYBLOCKS:
2095 		{
2096 			struct ioc_play_blocks *args
2097 				= (struct ioc_play_blocks *) addr;
2098 			struct cd_mode_params params;
2099 			union cd_pages *page;
2100 
2101 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2102 				  ("trying to do CDIOCPLAYBLOCKS\n"));
2103 
2104 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2105 			params.mode_buf = malloc(params.alloc_len, M_TEMP,
2106 						 M_WAITOK | M_ZERO);
2107 
2108 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2109 			if (error) {
2110 				free(params.mode_buf, M_TEMP);
2111 				break;
2112 			}
2113 			page = cdgetpage(&params);
2114 
2115 			page->audio.flags &= ~CD_PA_SOTC;
2116 			page->audio.flags |= CD_PA_IMMED;
2117 			error = cdsetmode(periph, &params);
2118 			free(params.mode_buf, M_TEMP);
2119 			if (error)
2120 				break;
2121 			error = cdplay(periph, args->blk, args->len);
2122 		}
2123 		break;
2124 	case CDIOCREADSUBCHANNEL:
2125 		{
2126 			struct ioc_read_subchannel *args
2127 				= (struct ioc_read_subchannel *) addr;
2128 			struct cd_sub_channel_info *data;
2129 			u_int32_t len = args->data_len;
2130 
2131 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2132 				  ("trying to do CDIOCREADSUBCHANNEL\n"));
2133 
2134 			data = malloc(sizeof(struct cd_sub_channel_info),
2135 				      M_TEMP, M_WAITOK);
2136 
2137 			if ((len > sizeof(struct cd_sub_channel_info)) ||
2138 			    (len < sizeof(struct cd_sub_channel_header))) {
2139 				printf(
2140 					"scsi_cd: cdioctl: "
2141 					"cdioreadsubchannel: error, len=%d\n",
2142 					len);
2143 				error = EINVAL;
2144 				free(data, M_TEMP);
2145 				break;
2146 			}
2147 
2148 			if (softc->quirks & CD_Q_BCD_TRACKS)
2149 				args->track = bin2bcd(args->track);
2150 
2151 			error = cdreadsubchannel(periph, args->address_format,
2152 				args->data_format, args->track, data, len);
2153 
2154 			if (error) {
2155 				free(data, M_TEMP);
2156 	 			break;
2157 			}
2158 			if (softc->quirks & CD_Q_BCD_TRACKS)
2159 				data->what.track_info.track_number =
2160 				    bcd2bin(data->what.track_info.track_number);
2161 			len = min(len, ((data->header.data_len[0] << 8) +
2162 				data->header.data_len[1] +
2163 				sizeof(struct cd_sub_channel_header)));
2164 			if (copyout(data, args->data, len) != 0) {
2165 				error = EFAULT;
2166 			}
2167 			free(data, M_TEMP);
2168 		}
2169 		break;
2170 
2171 	case CDIOREADTOCHEADER:
2172 		{
2173 			struct ioc_toc_header *th;
2174 
2175 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2176 				  ("trying to do CDIOREADTOCHEADER\n"));
2177 
2178 			th = malloc(sizeof(struct ioc_toc_header), M_TEMP,
2179 				    M_WAITOK);
2180 			error = cdreadtoc(periph, 0, 0, (u_int8_t *)th,
2181 				          sizeof (*th), /*sense_flags*/0);
2182 			if (error) {
2183 				free(th, M_TEMP);
2184 				break;
2185 			}
2186 			if (softc->quirks & CD_Q_BCD_TRACKS) {
2187 				/* we are going to have to convert the BCD
2188 				 * encoding on the cd to what is expected
2189 				 */
2190 				th->starting_track =
2191 					bcd2bin(th->starting_track);
2192 				th->ending_track = bcd2bin(th->ending_track);
2193 			}
2194 			th->len = ntohs(th->len);
2195 			bcopy(th, addr, sizeof(*th));
2196 			free(th, M_TEMP);
2197 		}
2198 		break;
2199 	case CDIOREADTOCENTRYS:
2200 		{
2201 			struct cd_tocdata *data;
2202 			struct cd_toc_single *lead;
2203 			struct ioc_read_toc_entry *te =
2204 				(struct ioc_read_toc_entry *) addr;
2205 			struct ioc_toc_header *th;
2206 			u_int32_t len, readlen, idx, num;
2207 			u_int32_t starting_track = te->starting_track;
2208 
2209 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2210 				  ("trying to do CDIOREADTOCENTRYS\n"));
2211 
2212 			data = malloc(sizeof(*data), M_TEMP, M_WAITOK);
2213 			lead = malloc(sizeof(*lead), M_TEMP, M_WAITOK);
2214 
2215 			if (te->data_len < sizeof(struct cd_toc_entry)
2216 			 || (te->data_len % sizeof(struct cd_toc_entry)) != 0
2217 			 || (te->address_format != CD_MSF_FORMAT
2218 			  && te->address_format != CD_LBA_FORMAT)) {
2219 				error = EINVAL;
2220 				printf("scsi_cd: error in readtocentries, "
2221 				       "returning EINVAL\n");
2222 				free(data, M_TEMP);
2223 				free(lead, M_TEMP);
2224 				break;
2225 			}
2226 
2227 			th = &data->header;
2228 			error = cdreadtoc(periph, 0, 0, (u_int8_t *)th,
2229 					  sizeof (*th), /*sense_flags*/0);
2230 			if (error) {
2231 				free(data, M_TEMP);
2232 				free(lead, M_TEMP);
2233 				break;
2234 			}
2235 
2236 			if (softc->quirks & CD_Q_BCD_TRACKS) {
2237 				/* we are going to have to convert the BCD
2238 				 * encoding on the cd to what is expected
2239 				 */
2240 				th->starting_track =
2241 				    bcd2bin(th->starting_track);
2242 				th->ending_track = bcd2bin(th->ending_track);
2243 			}
2244 
2245 			if (starting_track == 0)
2246 				starting_track = th->starting_track;
2247 			else if (starting_track == LEADOUT)
2248 				starting_track = th->ending_track + 1;
2249 			else if (starting_track < th->starting_track ||
2250 				 starting_track > th->ending_track + 1) {
2251 				printf("scsi_cd: error in readtocentries, "
2252 				       "returning EINVAL\n");
2253 				free(data, M_TEMP);
2254 				free(lead, M_TEMP);
2255 				error = EINVAL;
2256 				break;
2257 			}
2258 
2259 			/* calculate reading length without leadout entry */
2260 			readlen = (th->ending_track - starting_track + 1) *
2261 				  sizeof(struct cd_toc_entry);
2262 
2263 			/* and with leadout entry */
2264 			len = readlen + sizeof(struct cd_toc_entry);
2265 			if (te->data_len < len) {
2266 				len = te->data_len;
2267 				if (readlen > len)
2268 					readlen = len;
2269 			}
2270 			if (len > sizeof(data->entries)) {
2271 				printf("scsi_cd: error in readtocentries, "
2272 				       "returning EINVAL\n");
2273 				error = EINVAL;
2274 				free(data, M_TEMP);
2275 				free(lead, M_TEMP);
2276 				break;
2277 			}
2278 			num = len / sizeof(struct cd_toc_entry);
2279 
2280 			if (readlen > 0) {
2281 				error = cdreadtoc(periph, te->address_format,
2282 						  starting_track,
2283 						  (u_int8_t *)data,
2284 						  readlen + sizeof (*th),
2285 						  /*sense_flags*/0);
2286 				if (error) {
2287 					free(data, M_TEMP);
2288 					free(lead, M_TEMP);
2289 					break;
2290 				}
2291 			}
2292 
2293 			/* make leadout entry if needed */
2294 			idx = starting_track + num - 1;
2295 			if (softc->quirks & CD_Q_BCD_TRACKS)
2296 				th->ending_track = bcd2bin(th->ending_track);
2297 			if (idx == th->ending_track + 1) {
2298 				error = cdreadtoc(periph, te->address_format,
2299 						  LEADOUT, (u_int8_t *)lead,
2300 						  sizeof(*lead),
2301 						  /*sense_flags*/0);
2302 				if (error) {
2303 					free(data, M_TEMP);
2304 					free(lead, M_TEMP);
2305 					break;
2306 				}
2307 				data->entries[idx - starting_track] =
2308 					lead->entry;
2309 			}
2310 			if (softc->quirks & CD_Q_BCD_TRACKS) {
2311 				for (idx = 0; idx < num - 1; idx++) {
2312 					data->entries[idx].track =
2313 					    bcd2bin(data->entries[idx].track);
2314 				}
2315 			}
2316 
2317 			error = copyout(data->entries, te->data, len);
2318 			free(data, M_TEMP);
2319 			free(lead, M_TEMP);
2320 		}
2321 		break;
2322 	case CDIOREADTOCENTRY:
2323 		{
2324 			struct cd_toc_single *data;
2325 			struct ioc_read_toc_single_entry *te =
2326 				(struct ioc_read_toc_single_entry *) addr;
2327 			struct ioc_toc_header *th;
2328 			u_int32_t track;
2329 
2330 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2331 				  ("trying to do CDIOREADTOCENTRY\n"));
2332 
2333 			data = malloc(sizeof(*data), M_TEMP, M_WAITOK);
2334 
2335 			if (te->address_format != CD_MSF_FORMAT
2336 			    && te->address_format != CD_LBA_FORMAT) {
2337 				printf("error in readtocentry, "
2338 				       " returning EINVAL\n");
2339 				free(data, M_TEMP);
2340 				error = EINVAL;
2341 				break;
2342 			}
2343 
2344 			th = &data->header;
2345 			error = cdreadtoc(periph, 0, 0, (u_int8_t *)th,
2346 					  sizeof (*th), /*sense_flags*/0);
2347 			if (error) {
2348 				free(data, M_TEMP);
2349 				break;
2350 			}
2351 
2352 			if (softc->quirks & CD_Q_BCD_TRACKS) {
2353 				/* we are going to have to convert the BCD
2354 				 * encoding on the cd to what is expected
2355 				 */
2356 				th->starting_track =
2357 				    bcd2bin(th->starting_track);
2358 				th->ending_track = bcd2bin(th->ending_track);
2359 			}
2360 			track = te->track;
2361 			if (track == 0)
2362 				track = th->starting_track;
2363 			else if (track == LEADOUT)
2364 				/* OK */;
2365 			else if (track < th->starting_track ||
2366 				 track > th->ending_track + 1) {
2367 				printf("error in readtocentry, "
2368 				       " returning EINVAL\n");
2369 				free(data, M_TEMP);
2370 				error = EINVAL;
2371 				break;
2372 			}
2373 
2374 			error = cdreadtoc(periph, te->address_format, track,
2375 					  (u_int8_t *)data, sizeof(*data),
2376 					  /*sense_flags*/0);
2377 			if (error) {
2378 				free(data, M_TEMP);
2379 				break;
2380 			}
2381 
2382 			if (softc->quirks & CD_Q_BCD_TRACKS)
2383 				data->entry.track = bcd2bin(data->entry.track);
2384 			bcopy(&data->entry, &te->entry,
2385 			      sizeof(struct cd_toc_entry));
2386 			free(data, M_TEMP);
2387 		}
2388 		break;
2389 	case CDIOCSETPATCH:
2390 		{
2391 			struct ioc_patch *arg = (struct ioc_patch *)addr;
2392 			struct cd_mode_params params;
2393 			union cd_pages *page;
2394 
2395 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2396 				  ("trying to do CDIOCSETPATCH\n"));
2397 
2398 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2399 			params.mode_buf = malloc(params.alloc_len, M_TEMP,
2400 						 M_WAITOK | M_ZERO);
2401 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2402 			if (error) {
2403 				free(params.mode_buf, M_TEMP);
2404 				break;
2405 			}
2406 			page = cdgetpage(&params);
2407 
2408 			page->audio.port[LEFT_PORT].channels =
2409 				arg->patch[0];
2410 			page->audio.port[RIGHT_PORT].channels =
2411 				arg->patch[1];
2412 			page->audio.port[2].channels = arg->patch[2];
2413 			page->audio.port[3].channels = arg->patch[3];
2414 			error = cdsetmode(periph, &params);
2415 			free(params.mode_buf, M_TEMP);
2416 		}
2417 		break;
2418 	case CDIOCGETVOL:
2419 		{
2420 			struct ioc_vol *arg = (struct ioc_vol *) addr;
2421 			struct cd_mode_params params;
2422 			union cd_pages *page;
2423 
2424 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2425 				  ("trying to do CDIOCGETVOL\n"));
2426 
2427 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2428 			params.mode_buf = malloc(params.alloc_len, M_TEMP,
2429 						 M_WAITOK | M_ZERO);
2430 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2431 			if (error) {
2432 				free(params.mode_buf, M_TEMP);
2433 				break;
2434 			}
2435 			page = cdgetpage(&params);
2436 
2437 			arg->vol[LEFT_PORT] =
2438 				page->audio.port[LEFT_PORT].volume;
2439 			arg->vol[RIGHT_PORT] =
2440 				page->audio.port[RIGHT_PORT].volume;
2441 			arg->vol[2] = page->audio.port[2].volume;
2442 			arg->vol[3] = page->audio.port[3].volume;
2443 			free(params.mode_buf, M_TEMP);
2444 		}
2445 		break;
2446 	case CDIOCSETVOL:
2447 		{
2448 			struct ioc_vol *arg = (struct ioc_vol *) addr;
2449 			struct cd_mode_params params;
2450 			union cd_pages *page;
2451 
2452 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2453 				  ("trying to do CDIOCSETVOL\n"));
2454 
2455 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2456 			params.mode_buf = malloc(params.alloc_len, M_TEMP,
2457 						 M_WAITOK | M_ZERO);
2458 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2459 			if (error) {
2460 				free(params.mode_buf, M_TEMP);
2461 				break;
2462 			}
2463 			page = cdgetpage(&params);
2464 
2465 			page->audio.port[LEFT_PORT].channels = CHANNEL_0;
2466 			page->audio.port[LEFT_PORT].volume =
2467 				arg->vol[LEFT_PORT];
2468 			page->audio.port[RIGHT_PORT].channels = CHANNEL_1;
2469 			page->audio.port[RIGHT_PORT].volume =
2470 				arg->vol[RIGHT_PORT];
2471 			page->audio.port[2].volume = arg->vol[2];
2472 			page->audio.port[3].volume = arg->vol[3];
2473 			error = cdsetmode(periph, &params);
2474 			free(params.mode_buf, M_TEMP);
2475 		}
2476 		break;
2477 	case CDIOCSETMONO:
2478 		{
2479 			struct cd_mode_params params;
2480 			union cd_pages *page;
2481 
2482 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2483 				  ("trying to do CDIOCSETMONO\n"));
2484 
2485 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2486 			params.mode_buf = malloc(params.alloc_len, M_TEMP,
2487 						 M_WAITOK | M_ZERO);
2488 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2489 			if (error) {
2490 				free(params.mode_buf, M_TEMP);
2491 				break;
2492 			}
2493 			page = cdgetpage(&params);
2494 
2495 			page->audio.port[LEFT_PORT].channels =
2496 				LEFT_CHANNEL | RIGHT_CHANNEL;
2497 			page->audio.port[RIGHT_PORT].channels =
2498 				LEFT_CHANNEL | RIGHT_CHANNEL;
2499 			page->audio.port[2].channels = 0;
2500 			page->audio.port[3].channels = 0;
2501 			error = cdsetmode(periph, &params);
2502 			free(params.mode_buf, M_TEMP);
2503 		}
2504 		break;
2505 	case CDIOCSETSTEREO:
2506 		{
2507 			struct cd_mode_params params;
2508 			union cd_pages *page;
2509 
2510 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2511 				  ("trying to do CDIOCSETSTEREO\n"));
2512 
2513 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2514 			params.mode_buf = malloc(params.alloc_len, M_TEMP,
2515 						 M_WAITOK | M_ZERO);
2516 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2517 			if (error) {
2518 				free(params.mode_buf, M_TEMP);
2519 				break;
2520 			}
2521 			page = cdgetpage(&params);
2522 
2523 			page->audio.port[LEFT_PORT].channels =
2524 				LEFT_CHANNEL;
2525 			page->audio.port[RIGHT_PORT].channels =
2526 				RIGHT_CHANNEL;
2527 			page->audio.port[2].channels = 0;
2528 			page->audio.port[3].channels = 0;
2529 			error = cdsetmode(periph, &params);
2530 			free(params.mode_buf, M_TEMP);
2531 		}
2532 		break;
2533 	case CDIOCSETMUTE:
2534 		{
2535 			struct cd_mode_params params;
2536 			union cd_pages *page;
2537 
2538 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2539 				  ("trying to do CDIOCSETMUTE\n"));
2540 
2541 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2542 			params.mode_buf = malloc(params.alloc_len, M_TEMP,
2543 						 M_WAITOK | M_ZERO);
2544 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2545 			if (error) {
2546 				free(&params, M_TEMP);
2547 				break;
2548 			}
2549 			page = cdgetpage(&params);
2550 
2551 			page->audio.port[LEFT_PORT].channels = 0;
2552 			page->audio.port[RIGHT_PORT].channels = 0;
2553 			page->audio.port[2].channels = 0;
2554 			page->audio.port[3].channels = 0;
2555 			error = cdsetmode(periph, &params);
2556 			free(params.mode_buf, M_TEMP);
2557 		}
2558 		break;
2559 	case CDIOCSETLEFT:
2560 		{
2561 			struct cd_mode_params params;
2562 			union cd_pages *page;
2563 
2564 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2565 				  ("trying to do CDIOCSETLEFT\n"));
2566 
2567 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2568 			params.mode_buf = malloc(params.alloc_len, M_TEMP,
2569 						 M_WAITOK | M_ZERO);
2570 
2571 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2572 			if (error) {
2573 				free(params.mode_buf, M_TEMP);
2574 				break;
2575 			}
2576 			page = cdgetpage(&params);
2577 
2578 			page->audio.port[LEFT_PORT].channels = LEFT_CHANNEL;
2579 			page->audio.port[RIGHT_PORT].channels = LEFT_CHANNEL;
2580 			page->audio.port[2].channels = 0;
2581 			page->audio.port[3].channels = 0;
2582 			error = cdsetmode(periph, &params);
2583 			free(params.mode_buf, M_TEMP);
2584 		}
2585 		break;
2586 	case CDIOCSETRIGHT:
2587 		{
2588 			struct cd_mode_params params;
2589 			union cd_pages *page;
2590 
2591 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2592 				  ("trying to do CDIOCSETRIGHT\n"));
2593 
2594 			params.alloc_len = sizeof(union cd_mode_data_6_10);
2595 			params.mode_buf = malloc(params.alloc_len, M_TEMP,
2596 						 M_WAITOK | M_ZERO);
2597 
2598 			error = cdgetmode(periph, &params, AUDIO_PAGE);
2599 			if (error) {
2600 				free(params.mode_buf, M_TEMP);
2601 				break;
2602 			}
2603 			page = cdgetpage(&params);
2604 
2605 			page->audio.port[LEFT_PORT].channels = RIGHT_CHANNEL;
2606 			page->audio.port[RIGHT_PORT].channels = RIGHT_CHANNEL;
2607 			page->audio.port[2].channels = 0;
2608 			page->audio.port[3].channels = 0;
2609 			error = cdsetmode(periph, &params);
2610 			free(params.mode_buf, M_TEMP);
2611 		}
2612 		break;
2613 	case CDIOCRESUME:
2614 		error = cdpause(periph, 1);
2615 		break;
2616 	case CDIOCPAUSE:
2617 		error = cdpause(periph, 0);
2618 		break;
2619 	case CDIOCSTART:
2620 		error = cdstartunit(periph, 0);
2621 		break;
2622 	case CDIOCCLOSE:
2623 		error = cdstartunit(periph, 1);
2624 
2625 #ifdef notyet
2626 		if (error != 0)
2627 			break;
2628 
2629 		/*
2630 		 * The user successfully closed the tray, run
2631 		 * cdcheckmedia() again so we can re-sync the disklabel
2632 		 * information.
2633 		 */
2634 		cdcheckmedia(periph);
2635 #endif /* notyet */
2636 		break;
2637 	case CDIOCSTOP:
2638 		error = cdstopunit(periph, 0);
2639 		break;
2640 	case CDIOCEJECT:
2641 		error = cdstopunit(periph, 1);
2642 
2643 #ifdef notyet
2644 		if (error != 0)
2645 			break;
2646 
2647 		/*
2648 		 * Since we've successfully ejected the media, run
2649 		 * cdcheckmedia() again so we re-sync the disklabel
2650 		 * information.
2651 		 */
2652 		cdcheckmedia(periph);
2653 #endif /* notyet */
2654 		break;
2655 	case CDIOCALLOW:
2656 		cdprevent(periph, PR_ALLOW);
2657 		break;
2658 	case CDIOCPREVENT:
2659 		cdprevent(periph, PR_PREVENT);
2660 		break;
2661 	case CDIOCSETDEBUG:
2662 		/* sc_link->flags |= (SDEV_DB1 | SDEV_DB2); */
2663 		error = ENOTTY;
2664 		break;
2665 	case CDIOCCLRDEBUG:
2666 		/* sc_link->flags &= ~(SDEV_DB1 | SDEV_DB2); */
2667 		error = ENOTTY;
2668 		break;
2669 	case CDIOCRESET:
2670 		/* return (cd_reset(periph)); */
2671 		error = ENOTTY;
2672 		break;
2673 	case CDRIOCREADSPEED:
2674 		error = cdsetspeed(periph, *(u_int32_t *)addr, CDR_MAX_SPEED);
2675 		break;
2676 	case CDRIOCWRITESPEED:
2677 		error = cdsetspeed(periph, CDR_MAX_SPEED, *(u_int32_t *)addr);
2678 		break;
2679 	case DVDIOCSENDKEY:
2680 	case DVDIOCREPORTKEY: {
2681 		struct dvd_authinfo *authinfo;
2682 
2683 		authinfo = (struct dvd_authinfo *)addr;
2684 
2685 		if (cmd == DVDIOCREPORTKEY)
2686 			error = cdreportkey(periph, authinfo);
2687 		else
2688 			error = cdsendkey(periph, authinfo);
2689 		break;
2690 	}
2691 	case DVDIOCREADSTRUCTURE: {
2692 		struct dvd_struct *dvdstruct;
2693 
2694 		dvdstruct = (struct dvd_struct *)addr;
2695 
2696 		error = cdreaddvdstructure(periph, dvdstruct);
2697 
2698 		break;
2699 	}
2700 	default:
2701 		error = cam_periph_ioctl(periph, cmd, addr, cderror);
2702 		break;
2703 	}
2704 
2705 	cam_periph_unlock(periph);
2706 
2707 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdioctl\n"));
2708 
2709 	return (error);
2710 }
2711 
2712 static void
2713 cdprevent(struct cam_periph *periph, int action)
2714 {
2715 	union	ccb *ccb;
2716 	struct	cd_softc *softc;
2717 	int	error;
2718 
2719 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdprevent\n"));
2720 
2721 	softc = (struct cd_softc *)periph->softc;
2722 
2723 	if (((action == PR_ALLOW)
2724 	  && (softc->flags & CD_FLAG_DISC_LOCKED) == 0)
2725 	 || ((action == PR_PREVENT)
2726 	  && (softc->flags & CD_FLAG_DISC_LOCKED) != 0)) {
2727 		return;
2728 	}
2729 
2730 	ccb = cdgetccb(periph, /* priority */ 1);
2731 
2732 	scsi_prevent(&ccb->csio,
2733 		     /*retries*/ 1,
2734 		     cddone,
2735 		     MSG_SIMPLE_Q_TAG,
2736 		     action,
2737 		     SSD_FULL_SIZE,
2738 		     /* timeout */60000);
2739 
2740 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2741 			/*sense_flags*/SF_RETRY_UA|SF_NO_PRINT|SF_RETRY_SELTO);
2742 
2743 	xpt_release_ccb(ccb);
2744 
2745 	if (error == 0) {
2746 		if (action == PR_ALLOW)
2747 			softc->flags &= ~CD_FLAG_DISC_LOCKED;
2748 		else
2749 			softc->flags |= CD_FLAG_DISC_LOCKED;
2750 	}
2751 }
2752 
2753 int
2754 cdcheckmedia(struct cam_periph *periph)
2755 {
2756 	struct cd_softc *softc;
2757 	struct ioc_toc_header *toch;
2758 	struct cd_toc_single leadout;
2759 	struct ccb_getdev cgd;
2760 	u_int32_t size, toclen;
2761 	int error, num_entries, cdindex;
2762 	int first_track_audio;
2763 	struct disklabel *label;
2764 
2765 	softc = (struct cd_softc *)periph->softc;
2766 
2767 	first_track_audio = -1;
2768 	error = 0;
2769 
2770 	cdprevent(periph, PR_PREVENT);
2771 
2772 	/*
2773 	 * Build prototype label for whole disk.
2774 	 * Should take information about different data tracks from the
2775 	 * TOC and put it in the partition table.
2776 	 */
2777 	label = &softc->disk.d_label;
2778 	bzero(label, sizeof(*label));
2779 	label->d_type = DTYPE_SCSI;
2780 
2781 	/*
2782 	 * Grab the inquiry data to get the vendor and product names.
2783 	 * Put them in the typename and packname for the label.
2784 	 */
2785 	xpt_setup_ccb(&cgd.ccb_h, periph->path, /*priority*/ 1);
2786 	cgd.ccb_h.func_code = XPT_GDEV_TYPE;
2787 	xpt_action((union ccb *)&cgd);
2788 
2789 	strncpy(label->d_typename, cgd.inq_data.vendor,
2790 		min(SID_VENDOR_SIZE, sizeof(label->d_typename)));
2791 	strncpy(label->d_packname, cgd.inq_data.product,
2792 		min(SID_PRODUCT_SIZE, sizeof(label->d_packname)));
2793 
2794 	label->d_flags = D_REMOVABLE;
2795 	/*
2796 	 * Make partition 'a' cover the whole disk.  This is a temporary
2797 	 * compatibility hack.  The 'a' partition should not exist, so
2798 	 * the slice code won't create it.  The slice code will make
2799 	 * partition (RAW_PART + 'a') cover the whole disk and fill in
2800 	 * some more defaults.
2801 	 */
2802 	label->d_partitions[0].p_size = label->d_secperunit;
2803 	label->d_partitions[0].p_fstype = FS_OTHER;
2804 
2805 	/*
2806 	 * Default to not reading the disklabel off the disk, until we can
2807 	 * verify that we have media, that we have a table of contents, and
2808 	 * that the first track is a data track (which could theoretically
2809 	 * contain a disklabel).
2810 	 */
2811 	softc->disk.d_dsflags &= ~DSO_COMPATLABEL;
2812 	softc->disk.d_dsflags |= DSO_NOLABELS;
2813 
2814 	/*
2815 	 * Clear the valid media and TOC flags until we've verified that we
2816 	 * have both.
2817 	 */
2818 	softc->flags &= ~(CD_FLAG_VALID_MEDIA|CD_FLAG_VALID_TOC);
2819 
2820 	/*
2821 	 * Get the disc size and block size.  If we can't get it, we don't
2822 	 * have media, most likely.
2823 	 */
2824 	if ((error = cdsize(periph, &size)) != 0) {
2825 		/*
2826 		 * Set a bogus sector size, so the slice code won't try to
2827 		 * divide by 0 and panic the kernel.
2828 		 */
2829 		label->d_secsize = 2048;
2830 
2831 		label->d_secperunit = 0;
2832 
2833 		/*
2834 		 * XXX KDM is this a good idea?  Seems to cause more
2835 		 * problems.
2836 		 */
2837 		if (softc->flags & CD_FLAG_OPEN) {
2838 			int force;
2839 
2840 			force = 1;
2841 
2842 			/*
2843 			 * We don't bother checking the return value here,
2844 			 * since we already have an error...
2845 			 */
2846 			dsioctl(softc->disk.d_cdev, DIOCSYNCSLICEINFO,
2847 				/*data*/(caddr_t)&force, /*flags*/ 0,
2848 				&softc->disk.d_slice);
2849 		}
2850 
2851 		/*
2852 		 * Tell devstat(9) we don't have a blocksize.
2853 		 */
2854 		softc->device_stats.flags |= DEVSTAT_BS_UNAVAILABLE;
2855 
2856 		cdprevent(periph, PR_ALLOW);
2857 
2858 		return (error);
2859 	} else {
2860 
2861 		label->d_secsize = softc->params.blksize;
2862 		label->d_secperunit = softc->params.disksize;
2863 
2864 		/*
2865 		 * Force a re-sync of slice information, like the blocksize,
2866 		 * now that we know it.  It isn't pretty...but according to
2867 		 * Bruce Evans, this is probably the best way to do it in
2868 		 * -stable.  We only do this if we're already open, and
2869 		 * therefore dsopen() has already run.  If CD_FLAG_OPEN
2870 		 * isn't set, this isn't necessary.
2871 		 */
2872 		if (softc->flags & CD_FLAG_OPEN) {
2873 			int force;
2874 
2875 			force = 1;
2876 
2877 			error = dsioctl(softc->disk.d_cdev, DIOCSYNCSLICEINFO,
2878 					/*data*/(caddr_t)&force, /*flags*/ 0,
2879 					&softc->disk.d_slice);
2880 			if (error != 0) {
2881 				/*
2882 				 * Set a bogus sector size, so the slice code
2883 				 * won't try to divide by 0 and panic the
2884 				 * kernel.
2885 				 */
2886 				label->d_secsize = 2048;
2887 
2888 				label->d_secperunit = 0;
2889 
2890 				/*
2891 				 * Tell devstat(9) we don't have a blocksize.
2892 				 */
2893 				softc->device_stats.flags |=
2894 					DEVSTAT_BS_UNAVAILABLE;
2895 
2896 				cdprevent(periph, PR_ALLOW);
2897 			}
2898 		}
2899 
2900 		/*
2901 		 * We unconditionally (re)set the blocksize each time the
2902 		 * CD device is opened.  This is because the CD can change,
2903 		 * and therefore the blocksize might change.
2904 		 * XXX problems here if some slice or partition is still
2905 		 * open with the old size?
2906 		 */
2907 		if ((softc->device_stats.flags & DEVSTAT_BS_UNAVAILABLE) != 0)
2908 			softc->device_stats.flags &= ~DEVSTAT_BS_UNAVAILABLE;
2909 		softc->device_stats.block_size = softc->params.blksize;
2910 
2911 		softc->flags |= CD_FLAG_VALID_MEDIA;
2912 	}
2913 
2914 	/*
2915 	 * Now we check the table of contents.  This (currently) is only
2916 	 * used for the CDIOCPLAYTRACKS ioctl.  It may be used later to do
2917 	 * things like present a separate entry in /dev for each track,
2918 	 * like that acd(4) driver does.
2919 	 */
2920 	bzero(&softc->toc, sizeof(softc->toc));
2921 	toch = &softc->toc.header;
2922 
2923 	/*
2924 	 * We will get errors here for media that doesn't have a table of
2925 	 * contents.  According to the MMC-3 spec: "When a Read TOC/PMA/ATIP
2926 	 * command is presented for a DDCD/CD-R/RW media, where the first TOC
2927 	 * has not been recorded (no complete session) and the Format codes
2928 	 * 0000b, 0001b, or 0010b are specified, this command shall be rejected
2929 	 * with an INVALID FIELD IN CDB.  Devices that are not capable of
2930 	 * reading an incomplete session on DDC/CD-R/RW media shall report
2931 	 * CANNOT READ MEDIUM - INCOMPATIBLE FORMAT."
2932 	 *
2933 	 * So this isn't fatal if we can't read the table of contents, it
2934 	 * just means that the user won't be able to issue the play tracks
2935 	 * ioctl, and likely lots of other stuff won't work either.  They
2936 	 * need to burn the CD before we can do a whole lot with it.  So
2937 	 * we don't print anything here if we get an error back.
2938 	 */
2939 	error = cdreadtoc(periph, 0, 0, (u_int8_t *)toch, sizeof(*toch),
2940 			  SF_NO_PRINT);
2941 	/*
2942 	 * Errors in reading the table of contents aren't fatal, we just
2943 	 * won't have a valid table of contents cached.
2944 	 */
2945 	if (error != 0) {
2946 		error = 0;
2947 		bzero(&softc->toc, sizeof(softc->toc));
2948 		goto bailout;
2949 	}
2950 
2951 	if (softc->quirks & CD_Q_BCD_TRACKS) {
2952 		toch->starting_track = bcd2bin(toch->starting_track);
2953 		toch->ending_track = bcd2bin(toch->ending_track);
2954 	}
2955 
2956 	/* Number of TOC entries, plus leadout */
2957 	num_entries = (toch->ending_track - toch->starting_track) + 2;
2958 
2959 	if (num_entries <= 0)
2960 		goto bailout;
2961 
2962 	toclen = num_entries * sizeof(struct cd_toc_entry);
2963 
2964 	error = cdreadtoc(periph, CD_MSF_FORMAT, toch->starting_track,
2965 			  (u_int8_t *)&softc->toc, toclen + sizeof(*toch),
2966 			  SF_NO_PRINT);
2967 	if (error != 0) {
2968 		error = 0;
2969 		bzero(&softc->toc, sizeof(softc->toc));
2970 		goto bailout;
2971 	}
2972 
2973 	if (softc->quirks & CD_Q_BCD_TRACKS) {
2974 		toch->starting_track = bcd2bin(toch->starting_track);
2975 		toch->ending_track = bcd2bin(toch->ending_track);
2976 	}
2977 	toch->len = scsi_2btoul((uint8_t *)&toch->len);
2978 
2979 	/*
2980 	 * XXX KDM is this necessary?  Probably only if the drive doesn't
2981 	 * return leadout information with the table of contents.
2982 	 */
2983 	cdindex = toch->starting_track + num_entries -1;
2984 	if (cdindex == toch->ending_track + 1) {
2985 
2986 		error = cdreadtoc(periph, CD_MSF_FORMAT, LEADOUT,
2987 				  (u_int8_t *)&leadout, sizeof(leadout),
2988 				  SF_NO_PRINT);
2989 		if (error != 0) {
2990 			error = 0;
2991 			goto bailout;
2992 		}
2993 		softc->toc.entries[cdindex - toch->starting_track] =
2994 			leadout.entry;
2995 	}
2996 	if (softc->quirks & CD_Q_BCD_TRACKS) {
2997 		for (cdindex = 0; cdindex < (num_entries - 1); cdindex++) {
2998 			softc->toc.entries[cdindex].track =
2999 				bcd2bin(softc->toc.entries[cdindex].track);
3000 		}
3001 	}
3002 
3003 	/*
3004 	 * Run through the TOC entries, find the first entry and determine
3005 	 * whether it is an audio or data track.
3006 	 */
3007 	for (cdindex = 0; cdindex < (num_entries - 1); cdindex++) {
3008 		if (softc->toc.entries[cdindex].track == toch->starting_track) {
3009 			if (softc->toc.entries[cdindex].control & 0x04)
3010 				first_track_audio = 0;
3011 			else
3012 				first_track_audio = 1;
3013 			break;
3014 		}
3015 	}
3016 
3017 	/*
3018 	 * If first_track_audio is non-zero, we either have an error (e.g.
3019 	 * couldn't find the starting track) or the first track is an audio
3020 	 * track.  If first_track_audio is 0, the first track is a data
3021 	 * track that could have a disklabel.  Attempt to read the
3022 	 * disklabel off the media, just in case the user put one there.
3023 	 */
3024 	if (first_track_audio == 0) {
3025 		softc->disk.d_dsflags |= DSO_COMPATLABEL;
3026 		softc->disk.d_dsflags &= ~DSO_NOLABELS;
3027 	}
3028 	softc->flags |= CD_FLAG_VALID_TOC;
3029 
3030 bailout:
3031 	return (error);
3032 }
3033 
3034 static int
3035 cdsize(struct cam_periph *periph, u_int32_t *size)
3036 {
3037 	struct cd_softc *softc;
3038 	union ccb *ccb;
3039 	struct scsi_read_capacity_data *rcap_buf;
3040 	int error;
3041 
3042 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdsize\n"));
3043 
3044 	softc = (struct cd_softc *)periph->softc;
3045 
3046 	ccb = cdgetccb(periph, /* priority */ 1);
3047 
3048 	rcap_buf = malloc(sizeof(struct scsi_read_capacity_data),
3049 			  M_TEMP, M_INTWAIT | M_ZERO);
3050 
3051 	scsi_read_capacity(&ccb->csio,
3052 			   /*retries*/ 1,
3053 			   cddone,
3054 			   MSG_SIMPLE_Q_TAG,
3055 			   rcap_buf,
3056 			   SSD_FULL_SIZE,
3057 			   /* timeout */20000);
3058 
3059 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3060 			 /*sense_flags*/SF_RETRY_UA|SF_NO_PRINT|SF_RETRY_SELTO);
3061 
3062 	xpt_release_ccb(ccb);
3063 
3064 	softc->params.disksize = scsi_4btoul(rcap_buf->addr) + 1;
3065 	softc->params.blksize  = scsi_4btoul(rcap_buf->length);
3066 	/*
3067 	 * SCSI-3 mandates that the reported blocksize shall be 2048.
3068 	 * Older drives sometimes report funny values, trim it down to
3069 	 * 2048, or other parts of the kernel will get confused.
3070 	 *
3071 	 * XXX we leave drives alone that might report 512 bytes, as
3072 	 * well as drives reporting more weird sizes like perhaps 4K.
3073 	 */
3074 	if (softc->params.blksize > 2048 && softc->params.blksize <= 2352)
3075 		softc->params.blksize = 2048;
3076 
3077 	free(rcap_buf, M_TEMP);
3078 	*size = softc->params.disksize;
3079 
3080 	return (error);
3081 
3082 }
3083 
3084 static int
3085 cd6byteworkaround(union ccb *ccb)
3086 {
3087 	u_int8_t *cdb;
3088 	struct cam_periph *periph;
3089 	struct cd_softc *softc;
3090 	struct cd_mode_params *params;
3091 	int frozen, found;
3092 
3093 	periph = xpt_path_periph(ccb->ccb_h.path);
3094 	softc = (struct cd_softc *)periph->softc;
3095 
3096 	cdb = ccb->csio.cdb_io.cdb_bytes;
3097 
3098 	if ((ccb->ccb_h.flags & CAM_CDB_POINTER)
3099 	 || ((cdb[0] != MODE_SENSE_6)
3100 	  && (cdb[0] != MODE_SELECT_6)))
3101 		return (0);
3102 
3103 	/*
3104 	 * Because there is no convenient place to stash the overall
3105 	 * cd_mode_params structure pointer, we have to grab it like this.
3106 	 * This means that ALL MODE_SENSE and MODE_SELECT requests in the
3107 	 * cd(4) driver MUST go through cdgetmode() and cdsetmode()!
3108 	 *
3109 	 * XXX It would be nice if, at some point, we could increase the
3110 	 * number of available peripheral private pointers.  Both pointers
3111 	 * are currently used in most every peripheral driver.
3112 	 */
3113 	found = 0;
3114 
3115 	STAILQ_FOREACH(params, &softc->mode_queue, links) {
3116 		if (params->mode_buf == ccb->csio.data_ptr) {
3117 			found = 1;
3118 			break;
3119 		}
3120 	}
3121 
3122 	/*
3123 	 * This shouldn't happen.  All mode sense and mode select
3124 	 * operations in the cd(4) driver MUST go through cdgetmode() and
3125 	 * cdsetmode()!
3126 	 */
3127 	if (found == 0) {
3128 		xpt_print_path(periph->path);
3129 		printf("mode buffer not found in mode queue!\n");
3130 		return (0);
3131 	}
3132 
3133 	params->cdb_size = 10;
3134 	softc->minimum_command_size = 10;
3135 	xpt_print_path(ccb->ccb_h.path);
3136 	printf("%s(6) failed, increasing minimum CDB size to 10 bytes\n",
3137 	       (cdb[0] == MODE_SENSE_6) ? "MODE_SENSE" : "MODE_SELECT");
3138 
3139 	if (cdb[0] == MODE_SENSE_6) {
3140 		struct scsi_mode_sense_10 ms10;
3141 		struct scsi_mode_sense_6 *ms6;
3142 		int len;
3143 
3144 		ms6 = (struct scsi_mode_sense_6 *)cdb;
3145 
3146 		bzero(&ms10, sizeof(ms10));
3147  		ms10.opcode = MODE_SENSE_10;
3148  		ms10.byte2 = ms6->byte2;
3149  		ms10.page = ms6->page;
3150 
3151 		/*
3152 		 * 10 byte mode header, block descriptor,
3153 		 * sizeof(union cd_pages)
3154 		 */
3155 		len = sizeof(struct cd_mode_data_10);
3156 		ccb->csio.dxfer_len = len;
3157 
3158 		scsi_ulto2b(len, ms10.length);
3159 		ms10.control = ms6->control;
3160 		bcopy(&ms10, cdb, 10);
3161 		ccb->csio.cdb_len = 10;
3162 	} else {
3163 		struct scsi_mode_select_10 ms10;
3164 		struct scsi_mode_select_6 *ms6;
3165 		struct scsi_mode_header_6 *header6;
3166 		struct scsi_mode_header_10 *header10;
3167 		struct scsi_mode_page_header *page_header;
3168 		int blk_desc_len, page_num, page_size, len;
3169 
3170 		ms6 = (struct scsi_mode_select_6 *)cdb;
3171 
3172 		bzero(&ms10, sizeof(ms10));
3173 		ms10.opcode = MODE_SELECT_10;
3174 		ms10.byte2 = ms6->byte2;
3175 
3176 		header6 = (struct scsi_mode_header_6 *)params->mode_buf;
3177 		header10 = (struct scsi_mode_header_10 *)params->mode_buf;
3178 
3179 		page_header = find_mode_page_6(header6);
3180 		page_num = page_header->page_code;
3181 
3182 		blk_desc_len = header6->blk_desc_len;
3183 
3184 		page_size = cdgetpagesize(page_num);
3185 
3186 		if (page_size != (page_header->page_length +
3187 		    sizeof(*page_header)))
3188 			page_size = page_header->page_length +
3189 				sizeof(*page_header);
3190 
3191 		len = sizeof(*header10) + blk_desc_len + page_size;
3192 
3193 		len = min(params->alloc_len, len);
3194 
3195 		/*
3196 		 * Since the 6 byte parameter header is shorter than the 10
3197 		 * byte parameter header, we need to copy the actual mode
3198 		 * page data, and the block descriptor, if any, so things wind
3199 		 * up in the right place.  The regions will overlap, but
3200 		 * bcopy() does the right thing.
3201 		 */
3202 		bcopy(params->mode_buf + sizeof(*header6),
3203 		      params->mode_buf + sizeof(*header10),
3204 		      len - sizeof(*header10));
3205 
3206 		/* Make sure these fields are set correctly. */
3207 		scsi_ulto2b(0, header10->data_length);
3208 		header10->medium_type = 0;
3209 		scsi_ulto2b(blk_desc_len, header10->blk_desc_len);
3210 
3211 		ccb->csio.dxfer_len = len;
3212 
3213 		scsi_ulto2b(len, ms10.length);
3214 		ms10.control = ms6->control;
3215 		bcopy(&ms10, cdb, 10);
3216 		ccb->csio.cdb_len = 10;
3217 	}
3218 
3219 	frozen = (ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
3220 	ccb->ccb_h.status = CAM_REQUEUE_REQ;
3221 	xpt_action(ccb);
3222 	if (frozen) {
3223 		cam_release_devq(ccb->ccb_h.path,
3224 				 /*relsim_flags*/0,
3225 				 /*openings*/0,
3226 				 /*timeout*/0,
3227 				 /*getcount_only*/0);
3228 	}
3229 
3230 	return (ERESTART);
3231 }
3232 
3233 static int
3234 cderror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
3235 {
3236 	struct cd_softc *softc;
3237 	struct cam_periph *periph;
3238 	int error;
3239 
3240 	periph = xpt_path_periph(ccb->ccb_h.path);
3241 	softc = (struct cd_softc *)periph->softc;
3242 
3243 	error = 0;
3244 
3245 	/*
3246 	 * We use a status of CAM_REQ_INVALID as shorthand -- if a 6 byte
3247 	 * CDB comes back with this particular error, try transforming it
3248 	 * into the 10 byte version.
3249 	 */
3250 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INVALID) {
3251 		error = cd6byteworkaround(ccb);
3252 	} else if (((ccb->ccb_h.status & CAM_STATUS_MASK) ==
3253 		     CAM_SCSI_STATUS_ERROR)
3254 	 && (ccb->ccb_h.status & CAM_AUTOSNS_VALID)
3255 	 && (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND)
3256 	 && ((ccb->ccb_h.flags & CAM_SENSE_PHYS) == 0)
3257 	 && ((ccb->ccb_h.flags & CAM_SENSE_PTR) == 0)) {
3258 		int sense_key, error_code, asc, ascq;
3259 
3260  		scsi_extract_sense(&ccb->csio.sense_data,
3261 				   &error_code, &sense_key, &asc, &ascq);
3262 		if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
3263  			error = cd6byteworkaround(ccb);
3264 	}
3265 
3266 	if (error == ERESTART)
3267 		return (error);
3268 
3269 	/*
3270 	 * XXX
3271 	 * Until we have a better way of doing pack validation,
3272 	 * don't treat UAs as errors.
3273 	 */
3274 	sense_flags |= SF_RETRY_UA;
3275 	return (cam_periph_error(ccb, cam_flags, sense_flags,
3276 				 &softc->saved_ccb));
3277 }
3278 
3279 /*
3280  * Read table of contents
3281  */
3282 static int
3283 cdreadtoc(struct cam_periph *periph, u_int32_t mode, u_int32_t start,
3284 	  u_int8_t *data, u_int32_t len, u_int32_t sense_flags)
3285 {
3286 	struct scsi_read_toc *scsi_cmd;
3287 	u_int32_t ntoc;
3288         struct ccb_scsiio *csio;
3289 	union ccb *ccb;
3290 	int error;
3291 
3292 	ntoc = len;
3293 	error = 0;
3294 
3295 	ccb = cdgetccb(periph, /* priority */ 1);
3296 
3297 	csio = &ccb->csio;
3298 
3299 	cam_fill_csio(csio,
3300 		      /* retries */ 1,
3301 		      /* cbfcnp */ cddone,
3302 		      /* flags */ CAM_DIR_IN,
3303 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3304 		      /* data_ptr */ data,
3305 		      /* dxfer_len */ len,
3306 		      /* sense_len */ SSD_FULL_SIZE,
3307 		      sizeof(struct scsi_read_toc),
3308  		      /* timeout */ 50000);
3309 
3310 	scsi_cmd = (struct scsi_read_toc *)&csio->cdb_io.cdb_bytes;
3311 	bzero (scsi_cmd, sizeof(*scsi_cmd));
3312 
3313 	if (mode == CD_MSF_FORMAT)
3314 		scsi_cmd->byte2 |= CD_MSF;
3315 	scsi_cmd->from_track = start;
3316 	/* scsi_ulto2b(ntoc, (u_int8_t *)scsi_cmd->data_len); */
3317 	scsi_cmd->data_len[0] = (ntoc) >> 8;
3318 	scsi_cmd->data_len[1] = (ntoc) & 0xff;
3319 
3320 	scsi_cmd->op_code = READ_TOC;
3321 
3322 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3323 			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO |
3324 			 sense_flags);
3325 
3326 	xpt_release_ccb(ccb);
3327 
3328 	return(error);
3329 }
3330 
3331 static int
3332 cdreadsubchannel(struct cam_periph *periph, u_int32_t mode,
3333 		 u_int32_t format, int track,
3334 		 struct cd_sub_channel_info *data, u_int32_t len)
3335 {
3336 	struct scsi_read_subchannel *scsi_cmd;
3337         struct ccb_scsiio *csio;
3338 	union ccb *ccb;
3339 	int error;
3340 
3341 	error = 0;
3342 
3343 	ccb = cdgetccb(periph, /* priority */ 1);
3344 
3345 	csio = &ccb->csio;
3346 
3347 	cam_fill_csio(csio,
3348 		      /* retries */ 1,
3349 		      /* cbfcnp */ cddone,
3350 		      /* flags */ CAM_DIR_IN,
3351 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3352 		      /* data_ptr */ (u_int8_t *)data,
3353 		      /* dxfer_len */ len,
3354 		      /* sense_len */ SSD_FULL_SIZE,
3355 		      sizeof(struct scsi_read_subchannel),
3356  		      /* timeout */ 50000);
3357 
3358 	scsi_cmd = (struct scsi_read_subchannel *)&csio->cdb_io.cdb_bytes;
3359 	bzero (scsi_cmd, sizeof(*scsi_cmd));
3360 
3361 	scsi_cmd->op_code = READ_SUBCHANNEL;
3362 	if (mode == CD_MSF_FORMAT)
3363 		scsi_cmd->byte1 |= CD_MSF;
3364 	scsi_cmd->byte2 = SRS_SUBQ;
3365 	scsi_cmd->subchan_format = format;
3366 	scsi_cmd->track = track;
3367 	scsi_ulto2b(len, (u_int8_t *)scsi_cmd->data_len);
3368 	scsi_cmd->control = 0;
3369 
3370 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3371 			 /*sense_flags*/SF_RETRY_UA|SF_RETRY_SELTO);
3372 
3373 	xpt_release_ccb(ccb);
3374 
3375 	return(error);
3376 }
3377 
3378 /*
3379  * All MODE_SENSE requests in the cd(4) driver MUST go through this
3380  * routine.  See comments in cd6byteworkaround() for details.
3381  */
3382 static int
3383 cdgetmode(struct cam_periph *periph, struct cd_mode_params *data,
3384 	  u_int32_t page)
3385 {
3386 	struct ccb_scsiio *csio;
3387 	struct cd_softc *softc;
3388 	union ccb *ccb;
3389 	int param_len;
3390 	int error;
3391 
3392 	softc = (struct cd_softc *)periph->softc;
3393 
3394 	ccb = cdgetccb(periph, /* priority */ 1);
3395 
3396 	csio = &ccb->csio;
3397 
3398 	data->cdb_size = softc->minimum_command_size;
3399 	if (data->cdb_size < 10)
3400 		param_len = sizeof(struct cd_mode_data);
3401 	else
3402 		param_len = sizeof(struct cd_mode_data_10);
3403 
3404 	/* Don't say we've got more room than we actually allocated */
3405 	param_len = min(param_len, data->alloc_len);
3406 
3407 	scsi_mode_sense_len(csio,
3408 			    /* retries */ 1,
3409 			    /* cbfcnp */ cddone,
3410 			    /* tag_action */ MSG_SIMPLE_Q_TAG,
3411 			    /* dbd */ 0,
3412 			    /* page_code */ SMS_PAGE_CTRL_CURRENT,
3413 			    /* page */ page,
3414 			    /* param_buf */ data->mode_buf,
3415 			    /* param_len */ param_len,
3416 			    /* minimum_cmd_size */ softc->minimum_command_size,
3417 			    /* sense_len */ SSD_FULL_SIZE,
3418 			    /* timeout */ 50000);
3419 
3420 	/*
3421 	 * It would be nice not to have to do this, but there's no
3422 	 * available pointer in the CCB that would allow us to stuff the
3423 	 * mode params structure in there and retrieve it in
3424 	 * cd6byteworkaround(), so we can set the cdb size.  The cdb size
3425 	 * lets the caller know what CDB size we ended up using, so they
3426 	 * can find the actual mode page offset.
3427 	 */
3428 	STAILQ_INSERT_TAIL(&softc->mode_queue, data, links);
3429 
3430 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3431 			 /*sense_flags*/SF_RETRY_UA|SF_RETRY_SELTO);
3432 
3433 	xpt_release_ccb(ccb);
3434 
3435 	STAILQ_REMOVE(&softc->mode_queue, data, cd_mode_params, links);
3436 
3437 	/*
3438 	 * This is a bit of belt-and-suspenders checking, but if we run
3439 	 * into a situation where the target sends back multiple block
3440 	 * descriptors, we might not have enough space in the buffer to
3441 	 * see the whole mode page.  Better to return an error than
3442 	 * potentially access memory beyond our malloced region.
3443 	 */
3444 	if (error == 0) {
3445 		u_int32_t data_len;
3446 
3447 		if (data->cdb_size == 10) {
3448 			struct scsi_mode_header_10 *hdr10;
3449 
3450 			hdr10 = (struct scsi_mode_header_10 *)data->mode_buf;
3451 			data_len = scsi_2btoul(hdr10->data_length);
3452 			data_len += sizeof(hdr10->data_length);
3453 		} else {
3454 			struct scsi_mode_header_6 *hdr6;
3455 
3456 			hdr6 = (struct scsi_mode_header_6 *)data->mode_buf;
3457 			data_len = hdr6->data_length;
3458 			data_len += sizeof(hdr6->data_length);
3459 		}
3460 
3461 		/*
3462 		 * Complain if there is more mode data available than we
3463 		 * allocated space for.  This could potentially happen if
3464 		 * we miscalculated the page length for some reason, if the
3465 		 * drive returns multiple block descriptors, or if it sets
3466 		 * the data length incorrectly.
3467 		 */
3468 		if (data_len > data->alloc_len) {
3469 			xpt_print_path(periph->path);
3470 			printf("allocated modepage %d length %d < returned "
3471 			       "length %d\n", page, data->alloc_len, data_len);
3472 
3473 			error = ENOSPC;
3474 		}
3475 	}
3476 	return (error);
3477 }
3478 
3479 /*
3480  * All MODE_SELECT requests in the cd(4) driver MUST go through this
3481  * routine.  See comments in cd6byteworkaround() for details.
3482  */
3483 static int
3484 cdsetmode(struct cam_periph *periph, struct cd_mode_params *data)
3485 {
3486 	struct ccb_scsiio *csio;
3487 	struct cd_softc *softc;
3488 	union ccb *ccb;
3489 	int cdb_size, param_len;
3490 	int error;
3491 
3492 	softc = (struct cd_softc *)periph->softc;
3493 
3494 	ccb = cdgetccb(periph, /* priority */ 1);
3495 
3496 	csio = &ccb->csio;
3497 
3498 	error = 0;
3499 
3500 	/*
3501 	 * If the data is formatted for the 10 byte version of the mode
3502 	 * select parameter list, we need to use the 10 byte CDB.
3503 	 * Otherwise, we use whatever the stored minimum command size.
3504 	 */
3505 	if (data->cdb_size == 10)
3506 		cdb_size = data->cdb_size;
3507 	else
3508 		cdb_size = softc->minimum_command_size;
3509 
3510 	if (cdb_size >= 10) {
3511 		struct scsi_mode_header_10 *mode_header;
3512 		u_int32_t data_len;
3513 
3514 		mode_header = (struct scsi_mode_header_10 *)data->mode_buf;
3515 
3516 		data_len = scsi_2btoul(mode_header->data_length);
3517 
3518 		scsi_ulto2b(0, mode_header->data_length);
3519 		/*
3520 		 * SONY drives do not allow a mode select with a medium_type
3521 		 * value that has just been returned by a mode sense; use a
3522 		 * medium_type of 0 (Default) instead.
3523 		 */
3524 		mode_header->medium_type = 0;
3525 
3526 		/*
3527 		 * Pass back whatever the drive passed to us, plus the size
3528 		 * of the data length field.
3529 		 */
3530 		param_len = data_len + sizeof(mode_header->data_length);
3531 
3532 	} else {
3533 		struct scsi_mode_header_6 *mode_header;
3534 
3535 		mode_header = (struct scsi_mode_header_6 *)data->mode_buf;
3536 
3537 		param_len = mode_header->data_length + 1;
3538 
3539 		mode_header->data_length = 0;
3540 		/*
3541 		 * SONY drives do not allow a mode select with a medium_type
3542 		 * value that has just been returned by a mode sense; use a
3543 		 * medium_type of 0 (Default) instead.
3544 		 */
3545 		mode_header->medium_type = 0;
3546 	}
3547 
3548 	/* Don't say we've got more room than we actually allocated */
3549 	param_len = min(param_len, data->alloc_len);
3550 
3551 	scsi_mode_select_len(csio,
3552 			     /* retries */ 1,
3553 			     /* cbfcnp */ cddone,
3554 			     /* tag_action */ MSG_SIMPLE_Q_TAG,
3555 			     /* scsi_page_fmt */ 1,
3556 			     /* save_pages */ 0,
3557 			     /* param_buf */ data->mode_buf,
3558 			     /* param_len */ param_len,
3559 			     /* minimum_cmd_size */ cdb_size,
3560 			     /* sense_len */ SSD_FULL_SIZE,
3561 			     /* timeout */ 50000);
3562 
3563 	/* See comments in cdgetmode() and cd6byteworkaround(). */
3564 	STAILQ_INSERT_TAIL(&softc->mode_queue, data, links);
3565 
3566 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3567 			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3568 
3569 	xpt_release_ccb(ccb);
3570 
3571 	STAILQ_REMOVE(&softc->mode_queue, data, cd_mode_params, links);
3572 
3573 	return (error);
3574 }
3575 
3576 
3577 
3578 static int
3579 cdplay(struct cam_periph *periph, u_int32_t blk, u_int32_t len)
3580 {
3581 	struct ccb_scsiio *csio;
3582 	union ccb *ccb;
3583 	int error;
3584 	u_int8_t cdb_len;
3585 
3586 	error = 0;
3587 	ccb = cdgetccb(periph, /* priority */ 1);
3588 	csio = &ccb->csio;
3589 	/*
3590 	 * Use the smallest possible command to perform the operation.
3591 	 */
3592 	if ((len & 0xffff0000) == 0) {
3593 		/*
3594 		 * We can fit in a 10 byte cdb.
3595 		 */
3596 		struct scsi_play_10 *scsi_cmd;
3597 
3598 		scsi_cmd = (struct scsi_play_10 *)&csio->cdb_io.cdb_bytes;
3599 		bzero (scsi_cmd, sizeof(*scsi_cmd));
3600 		scsi_cmd->op_code = PLAY_10;
3601 		scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
3602 		scsi_ulto2b(len, (u_int8_t *)scsi_cmd->xfer_len);
3603 		cdb_len = sizeof(*scsi_cmd);
3604 	} else  {
3605 		struct scsi_play_12 *scsi_cmd;
3606 
3607 		scsi_cmd = (struct scsi_play_12 *)&csio->cdb_io.cdb_bytes;
3608 		bzero (scsi_cmd, sizeof(*scsi_cmd));
3609 		scsi_cmd->op_code = PLAY_12;
3610 		scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
3611 		scsi_ulto4b(len, (u_int8_t *)scsi_cmd->xfer_len);
3612 		cdb_len = sizeof(*scsi_cmd);
3613 	}
3614 	cam_fill_csio(csio,
3615 		      /*retries*/2,
3616 		      cddone,
3617 		      /*flags*/CAM_DIR_NONE,
3618 		      MSG_SIMPLE_Q_TAG,
3619 		      /*dataptr*/NULL,
3620 		      /*datalen*/0,
3621 		      /*sense_len*/SSD_FULL_SIZE,
3622 		      cdb_len,
3623 		      /*timeout*/50 * 1000);
3624 
3625 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3626 			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3627 
3628 	xpt_release_ccb(ccb);
3629 
3630 	return(error);
3631 }
3632 
3633 static int
3634 cdplaymsf(struct cam_periph *periph, u_int32_t startm, u_int32_t starts,
3635 	  u_int32_t startf, u_int32_t endm, u_int32_t ends, u_int32_t endf)
3636 {
3637 	struct scsi_play_msf *scsi_cmd;
3638         struct ccb_scsiio *csio;
3639 	union ccb *ccb;
3640 	int error;
3641 
3642 	error = 0;
3643 
3644 	ccb = cdgetccb(periph, /* priority */ 1);
3645 
3646 	csio = &ccb->csio;
3647 
3648 	cam_fill_csio(csio,
3649 		      /* retries */ 1,
3650 		      /* cbfcnp */ cddone,
3651 		      /* flags */ CAM_DIR_NONE,
3652 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3653 		      /* data_ptr */ NULL,
3654 		      /* dxfer_len */ 0,
3655 		      /* sense_len */ SSD_FULL_SIZE,
3656 		      sizeof(struct scsi_play_msf),
3657  		      /* timeout */ 50000);
3658 
3659 	scsi_cmd = (struct scsi_play_msf *)&csio->cdb_io.cdb_bytes;
3660 	bzero (scsi_cmd, sizeof(*scsi_cmd));
3661 
3662         scsi_cmd->op_code = PLAY_MSF;
3663         scsi_cmd->start_m = startm;
3664         scsi_cmd->start_s = starts;
3665         scsi_cmd->start_f = startf;
3666         scsi_cmd->end_m = endm;
3667         scsi_cmd->end_s = ends;
3668         scsi_cmd->end_f = endf;
3669 
3670 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3671 			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3672 
3673 	xpt_release_ccb(ccb);
3674 
3675 	return(error);
3676 }
3677 
3678 
3679 static int
3680 cdplaytracks(struct cam_periph *periph, u_int32_t strack, u_int32_t sindex,
3681 	     u_int32_t etrack, u_int32_t eindex)
3682 {
3683 	struct scsi_play_track *scsi_cmd;
3684         struct ccb_scsiio *csio;
3685 	union ccb *ccb;
3686 	int error;
3687 
3688 	error = 0;
3689 
3690 	ccb = cdgetccb(periph, /* priority */ 1);
3691 
3692 	csio = &ccb->csio;
3693 
3694 	cam_fill_csio(csio,
3695 		      /* retries */ 1,
3696 		      /* cbfcnp */ cddone,
3697 		      /* flags */ CAM_DIR_NONE,
3698 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3699 		      /* data_ptr */ NULL,
3700 		      /* dxfer_len */ 0,
3701 		      /* sense_len */ SSD_FULL_SIZE,
3702 		      sizeof(struct scsi_play_track),
3703  		      /* timeout */ 50000);
3704 
3705 	scsi_cmd = (struct scsi_play_track *)&csio->cdb_io.cdb_bytes;
3706 	bzero (scsi_cmd, sizeof(*scsi_cmd));
3707 
3708         scsi_cmd->op_code = PLAY_TRACK;
3709         scsi_cmd->start_track = strack;
3710         scsi_cmd->start_index = sindex;
3711         scsi_cmd->end_track = etrack;
3712         scsi_cmd->end_index = eindex;
3713 
3714 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3715 			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3716 
3717 	xpt_release_ccb(ccb);
3718 
3719 	return(error);
3720 }
3721 
3722 static int
3723 cdpause(struct cam_periph *periph, u_int32_t go)
3724 {
3725 	struct scsi_pause *scsi_cmd;
3726         struct ccb_scsiio *csio;
3727 	union ccb *ccb;
3728 	int error;
3729 
3730 	error = 0;
3731 
3732 	ccb = cdgetccb(periph, /* priority */ 1);
3733 
3734 	csio = &ccb->csio;
3735 
3736 	cam_fill_csio(csio,
3737 		      /* retries */ 1,
3738 		      /* cbfcnp */ cddone,
3739 		      /* flags */ CAM_DIR_NONE,
3740 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3741 		      /* data_ptr */ NULL,
3742 		      /* dxfer_len */ 0,
3743 		      /* sense_len */ SSD_FULL_SIZE,
3744 		      sizeof(struct scsi_pause),
3745  		      /* timeout */ 50000);
3746 
3747 	scsi_cmd = (struct scsi_pause *)&csio->cdb_io.cdb_bytes;
3748 	bzero (scsi_cmd, sizeof(*scsi_cmd));
3749 
3750         scsi_cmd->op_code = PAUSE;
3751 	scsi_cmd->resume = go;
3752 
3753 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3754 			 /*sense_flags*/SF_RETRY_UA |SF_RETRY_SELTO);
3755 
3756 	xpt_release_ccb(ccb);
3757 
3758 	return(error);
3759 }
3760 
3761 static int
3762 cdstartunit(struct cam_periph *periph, int load)
3763 {
3764 	union ccb *ccb;
3765 	int error;
3766 
3767 	error = 0;
3768 
3769 	ccb = cdgetccb(periph, /* priority */ 1);
3770 
3771 	scsi_start_stop(&ccb->csio,
3772 			/* retries */ 1,
3773 			/* cbfcnp */ cddone,
3774 			/* tag_action */ MSG_SIMPLE_Q_TAG,
3775 			/* start */ TRUE,
3776 			/* load_eject */ load,
3777 			/* immediate */ FALSE,
3778 			/* sense_len */ SSD_FULL_SIZE,
3779 			/* timeout */ 50000);
3780 
3781 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3782 			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3783 
3784 	xpt_release_ccb(ccb);
3785 
3786 	return(error);
3787 }
3788 
3789 static int
3790 cdstopunit(struct cam_periph *periph, u_int32_t eject)
3791 {
3792 	union ccb *ccb;
3793 	int error;
3794 
3795 	error = 0;
3796 
3797 	ccb = cdgetccb(periph, /* priority */ 1);
3798 
3799 	scsi_start_stop(&ccb->csio,
3800 			/* retries */ 1,
3801 			/* cbfcnp */ cddone,
3802 			/* tag_action */ MSG_SIMPLE_Q_TAG,
3803 			/* start */ FALSE,
3804 			/* load_eject */ eject,
3805 			/* immediate */ FALSE,
3806 			/* sense_len */ SSD_FULL_SIZE,
3807 			/* timeout */ 50000);
3808 
3809 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3810 			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3811 
3812 	xpt_release_ccb(ccb);
3813 
3814 	return(error);
3815 }
3816 
3817 static int
3818 cdsetspeed(struct cam_periph *periph, u_int32_t rdspeed, u_int32_t wrspeed)
3819 {
3820 	struct scsi_set_speed *scsi_cmd;
3821 	struct ccb_scsiio *csio;
3822 	union ccb *ccb;
3823 	int error;
3824 
3825 	error = 0;
3826 	ccb = cdgetccb(periph, /* priority */ 1);
3827 	csio = &ccb->csio;
3828 
3829 	/* Preserve old behavior: units in multiples of CDROM speed */
3830 	if (rdspeed < 177)
3831 		rdspeed *= 177;
3832 	if (wrspeed < 177)
3833 		wrspeed *= 177;
3834 
3835 	cam_fill_csio(csio,
3836 		      /* retries */ 1,
3837 		      /* cbfcnp */ cddone,
3838 		      /* flags */ CAM_DIR_NONE,
3839 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3840 		      /* data_ptr */ NULL,
3841 		      /* dxfer_len */ 0,
3842 		      /* sense_len */ SSD_FULL_SIZE,
3843 		      sizeof(struct scsi_set_speed),
3844  		      /* timeout */ 50000);
3845 
3846 	scsi_cmd = (struct scsi_set_speed *)&csio->cdb_io.cdb_bytes;
3847 	bzero(scsi_cmd, sizeof(*scsi_cmd));
3848 
3849 	scsi_cmd->opcode = SET_CD_SPEED;
3850 	scsi_ulto2b(rdspeed, scsi_cmd->readspeed);
3851 	scsi_ulto2b(wrspeed, scsi_cmd->writespeed);
3852 
3853 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3854 			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3855 
3856 	xpt_release_ccb(ccb);
3857 
3858 	return(error);
3859 }
3860 
3861 static int
3862 cdreportkey(struct cam_periph *periph, struct dvd_authinfo *authinfo)
3863 {
3864 	union ccb *ccb;
3865 	u_int8_t *databuf;
3866 	u_int32_t lba;
3867 	int error;
3868 	int length;
3869 
3870 	error = 0;
3871 	databuf = NULL;
3872 	lba = 0;
3873 
3874 	ccb = cdgetccb(periph, /* priority */ 1);
3875 
3876 	switch (authinfo->format) {
3877 	case DVD_REPORT_AGID:
3878 		length = sizeof(struct scsi_report_key_data_agid);
3879 		break;
3880 	case DVD_REPORT_CHALLENGE:
3881 		length = sizeof(struct scsi_report_key_data_challenge);
3882 		break;
3883 	case DVD_REPORT_KEY1:
3884 		length = sizeof(struct scsi_report_key_data_key1_key2);
3885 		break;
3886 	case DVD_REPORT_TITLE_KEY:
3887 		length = sizeof(struct scsi_report_key_data_title);
3888 		/* The lba field is only set for the title key */
3889 		lba = authinfo->lba;
3890 		break;
3891 	case DVD_REPORT_ASF:
3892 		length = sizeof(struct scsi_report_key_data_asf);
3893 		break;
3894 	case DVD_REPORT_RPC:
3895 		length = sizeof(struct scsi_report_key_data_rpc);
3896 		break;
3897 	case DVD_INVALIDATE_AGID:
3898 		length = 0;
3899 		break;
3900 	default:
3901 		error = EINVAL;
3902 		goto bailout;
3903 		break; /* NOTREACHED */
3904 	}
3905 
3906 	if (length != 0) {
3907 		databuf = malloc(length, M_DEVBUF, M_INTWAIT | M_ZERO);
3908 	} else {
3909 		databuf = NULL;
3910 	}
3911 
3912 
3913 	scsi_report_key(&ccb->csio,
3914 			/* retries */ 1,
3915 			/* cbfcnp */ cddone,
3916 			/* tag_action */ MSG_SIMPLE_Q_TAG,
3917 			/* lba */ lba,
3918 			/* agid */ authinfo->agid,
3919 			/* key_format */ authinfo->format,
3920 			/* data_ptr */ databuf,
3921 			/* dxfer_len */ length,
3922 			/* sense_len */ SSD_FULL_SIZE,
3923 			/* timeout */ 50000);
3924 
3925 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3926 			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3927 
3928 	if (error != 0)
3929 		goto bailout;
3930 
3931 	if (ccb->csio.resid != 0) {
3932 		xpt_print_path(periph->path);
3933 		printf("warning, residual for report key command is %d\n",
3934 		       ccb->csio.resid);
3935 	}
3936 
3937 	switch(authinfo->format) {
3938 	case DVD_REPORT_AGID: {
3939 		struct scsi_report_key_data_agid *agid_data;
3940 
3941 		agid_data = (struct scsi_report_key_data_agid *)databuf;
3942 
3943 		authinfo->agid = (agid_data->agid & RKD_AGID_MASK) >>
3944 			RKD_AGID_SHIFT;
3945 		break;
3946 	}
3947 	case DVD_REPORT_CHALLENGE: {
3948 		struct scsi_report_key_data_challenge *chal_data;
3949 
3950 		chal_data = (struct scsi_report_key_data_challenge *)databuf;
3951 
3952 		bcopy(chal_data->challenge_key, authinfo->keychal,
3953 		      min(sizeof(chal_data->challenge_key),
3954 		          sizeof(authinfo->keychal)));
3955 		break;
3956 	}
3957 	case DVD_REPORT_KEY1: {
3958 		struct scsi_report_key_data_key1_key2 *key1_data;
3959 
3960 		key1_data = (struct scsi_report_key_data_key1_key2 *)databuf;
3961 
3962 		bcopy(key1_data->key1, authinfo->keychal,
3963 		      min(sizeof(key1_data->key1), sizeof(authinfo->keychal)));
3964 		break;
3965 	}
3966 	case DVD_REPORT_TITLE_KEY: {
3967 		struct scsi_report_key_data_title *title_data;
3968 
3969 		title_data = (struct scsi_report_key_data_title *)databuf;
3970 
3971 		authinfo->cpm = (title_data->byte0 & RKD_TITLE_CPM) >>
3972 			RKD_TITLE_CPM_SHIFT;
3973 		authinfo->cp_sec = (title_data->byte0 & RKD_TITLE_CP_SEC) >>
3974 			RKD_TITLE_CP_SEC_SHIFT;
3975 		authinfo->cgms = (title_data->byte0 & RKD_TITLE_CMGS_MASK) >>
3976 			RKD_TITLE_CMGS_SHIFT;
3977 		bcopy(title_data->title_key, authinfo->keychal,
3978 		      min(sizeof(title_data->title_key),
3979 			  sizeof(authinfo->keychal)));
3980 		break;
3981 	}
3982 	case DVD_REPORT_ASF: {
3983 		struct scsi_report_key_data_asf *asf_data;
3984 
3985 		asf_data = (struct scsi_report_key_data_asf *)databuf;
3986 
3987 		authinfo->asf = asf_data->success & RKD_ASF_SUCCESS;
3988 		break;
3989 	}
3990 	case DVD_REPORT_RPC: {
3991 		struct scsi_report_key_data_rpc *rpc_data;
3992 
3993 		rpc_data = (struct scsi_report_key_data_rpc *)databuf;
3994 
3995 		authinfo->reg_type = (rpc_data->byte4 & RKD_RPC_TYPE_MASK) >>
3996 			RKD_RPC_TYPE_SHIFT;
3997 		authinfo->vend_rsts =
3998 			(rpc_data->byte4 & RKD_RPC_VENDOR_RESET_MASK) >>
3999 			RKD_RPC_VENDOR_RESET_SHIFT;
4000 		authinfo->user_rsts = rpc_data->byte4 & RKD_RPC_USER_RESET_MASK;
4001 		authinfo->region = rpc_data->region_mask;
4002 		authinfo->rpc_scheme = rpc_data->rpc_scheme1;
4003 		break;
4004 	}
4005 	case DVD_INVALIDATE_AGID:
4006 		break;
4007 	default:
4008 		/* This should be impossible, since we checked above */
4009 		error = EINVAL;
4010 		goto bailout;
4011 		break; /* NOTREACHED */
4012 	}
4013 bailout:
4014 	if (databuf != NULL)
4015 		free(databuf, M_DEVBUF);
4016 
4017 	xpt_release_ccb(ccb);
4018 
4019 	return(error);
4020 }
4021 
4022 static int
4023 cdsendkey(struct cam_periph *periph, struct dvd_authinfo *authinfo)
4024 {
4025 	union ccb *ccb;
4026 	u_int8_t *databuf;
4027 	int length;
4028 	int error;
4029 
4030 	error = 0;
4031 	databuf = NULL;
4032 
4033 	ccb = cdgetccb(periph, /* priority */ 1);
4034 
4035 	switch(authinfo->format) {
4036 	case DVD_SEND_CHALLENGE: {
4037 		struct scsi_report_key_data_challenge *challenge_data;
4038 
4039 		length = sizeof(*challenge_data);
4040 
4041 		challenge_data = malloc(length, M_DEVBUF, M_INTWAIT | M_ZERO);
4042 
4043 		databuf = (u_int8_t *)challenge_data;
4044 
4045 		scsi_ulto2b(length - sizeof(challenge_data->data_len),
4046 			    challenge_data->data_len);
4047 
4048 		bcopy(authinfo->keychal, challenge_data->challenge_key,
4049 		      min(sizeof(authinfo->keychal),
4050 			  sizeof(challenge_data->challenge_key)));
4051 		break;
4052 	}
4053 	case DVD_SEND_KEY2: {
4054 		struct scsi_report_key_data_key1_key2 *key2_data;
4055 
4056 		length = sizeof(*key2_data);
4057 
4058 		key2_data = malloc(length, M_DEVBUF, M_INTWAIT | M_ZERO);
4059 
4060 		databuf = (u_int8_t *)key2_data;
4061 
4062 		scsi_ulto2b(length - sizeof(key2_data->data_len),
4063 			    key2_data->data_len);
4064 
4065 		bcopy(authinfo->keychal, key2_data->key1,
4066 		      min(sizeof(authinfo->keychal), sizeof(key2_data->key1)));
4067 
4068 		break;
4069 	}
4070 	case DVD_SEND_RPC: {
4071 		struct scsi_send_key_data_rpc *rpc_data;
4072 
4073 		length = sizeof(*rpc_data);
4074 
4075 		rpc_data = malloc(length, M_DEVBUF, M_INTWAIT | M_ZERO);
4076 
4077 		databuf = (u_int8_t *)rpc_data;
4078 
4079 		scsi_ulto2b(length - sizeof(rpc_data->data_len),
4080 			    rpc_data->data_len);
4081 
4082 		rpc_data->region_code = authinfo->region;
4083 		break;
4084 	}
4085 	default:
4086 		error = EINVAL;
4087 		goto bailout;
4088 		break; /* NOTREACHED */
4089 	}
4090 
4091 	scsi_send_key(&ccb->csio,
4092 		      /* retries */ 1,
4093 		      /* cbfcnp */ cddone,
4094 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
4095 		      /* agid */ authinfo->agid,
4096 		      /* key_format */ authinfo->format,
4097 		      /* data_ptr */ databuf,
4098 		      /* dxfer_len */ length,
4099 		      /* sense_len */ SSD_FULL_SIZE,
4100 		      /* timeout */ 50000);
4101 
4102 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
4103 			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
4104 
4105 bailout:
4106 
4107 	if (databuf != NULL)
4108 		free(databuf, M_DEVBUF);
4109 
4110 	xpt_release_ccb(ccb);
4111 
4112 	return(error);
4113 }
4114 
4115 static int
4116 cdreaddvdstructure(struct cam_periph *periph, struct dvd_struct *dvdstruct)
4117 {
4118 	union ccb *ccb;
4119 	u_int8_t *databuf;
4120 	u_int32_t address;
4121 	int error;
4122 	int length;
4123 
4124 	error = 0;
4125 	databuf = NULL;
4126 	/* The address is reserved for many of the formats */
4127 	address = 0;
4128 
4129 	ccb = cdgetccb(periph, /* priority */ 1);
4130 
4131 	switch(dvdstruct->format) {
4132 	case DVD_STRUCT_PHYSICAL:
4133 		length = sizeof(struct scsi_read_dvd_struct_data_physical);
4134 		break;
4135 	case DVD_STRUCT_COPYRIGHT:
4136 		length = sizeof(struct scsi_read_dvd_struct_data_copyright);
4137 		break;
4138 	case DVD_STRUCT_DISCKEY:
4139 		length = sizeof(struct scsi_read_dvd_struct_data_disc_key);
4140 		break;
4141 	case DVD_STRUCT_BCA:
4142 		length = sizeof(struct scsi_read_dvd_struct_data_bca);
4143 		break;
4144 	case DVD_STRUCT_MANUFACT:
4145 		length = sizeof(struct scsi_read_dvd_struct_data_manufacturer);
4146 		break;
4147 	case DVD_STRUCT_CMI:
4148 		error = ENODEV;
4149 		goto bailout;
4150 #ifdef notyet
4151 		length = sizeof(struct scsi_read_dvd_struct_data_copy_manage);
4152 		address = dvdstruct->address;
4153 #endif
4154 		break; /* NOTREACHED */
4155 	case DVD_STRUCT_PROTDISCID:
4156 		length = sizeof(struct scsi_read_dvd_struct_data_prot_discid);
4157 		break;
4158 	case DVD_STRUCT_DISCKEYBLOCK:
4159 		length = sizeof(struct scsi_read_dvd_struct_data_disc_key_blk);
4160 		break;
4161 	case DVD_STRUCT_DDS:
4162 		length = sizeof(struct scsi_read_dvd_struct_data_dds);
4163 		break;
4164 	case DVD_STRUCT_MEDIUM_STAT:
4165 		length = sizeof(struct scsi_read_dvd_struct_data_medium_status);
4166 		break;
4167 	case DVD_STRUCT_SPARE_AREA:
4168 		length = sizeof(struct scsi_read_dvd_struct_data_spare_area);
4169 		break;
4170 	case DVD_STRUCT_RMD_LAST:
4171 		error = ENODEV;
4172 		goto bailout;
4173 #ifdef notyet
4174 		length = sizeof(struct scsi_read_dvd_struct_data_rmd_borderout);
4175 		address = dvdstruct->address;
4176 #endif
4177 		break; /* NOTREACHED */
4178 	case DVD_STRUCT_RMD_RMA:
4179 		error = ENODEV;
4180 		goto bailout;
4181 #ifdef notyet
4182 		length = sizeof(struct scsi_read_dvd_struct_data_rmd);
4183 		address = dvdstruct->address;
4184 #endif
4185 		break; /* NOTREACHED */
4186 	case DVD_STRUCT_PRERECORDED:
4187 		length = sizeof(struct scsi_read_dvd_struct_data_leadin);
4188 		break;
4189 	case DVD_STRUCT_UNIQUEID:
4190 		length = sizeof(struct scsi_read_dvd_struct_data_disc_id);
4191 		break;
4192 	case DVD_STRUCT_DCB:
4193 		error = ENODEV;
4194 		goto bailout;
4195 #ifdef notyet
4196 		length = sizeof(struct scsi_read_dvd_struct_data_dcb);
4197 		address = dvdstruct->address;
4198 #endif
4199 		break; /* NOTREACHED */
4200 	case DVD_STRUCT_LIST:
4201 		/*
4202 		 * This is the maximum allocation length for the READ DVD
4203 		 * STRUCTURE command.  There's nothing in the MMC3 spec
4204 		 * that indicates a limit in the amount of data that can
4205 		 * be returned from this call, other than the limits
4206 		 * imposed by the 2-byte length variables.
4207 		 */
4208 		length = 65535;
4209 		break;
4210 	default:
4211 		error = EINVAL;
4212 		goto bailout;
4213 		break; /* NOTREACHED */
4214 	}
4215 
4216 	if (length != 0) {
4217 		databuf = malloc(length, M_DEVBUF, M_INTWAIT | M_ZERO);
4218 	} else {
4219 		databuf = NULL;
4220 	}
4221 
4222 	scsi_read_dvd_structure(&ccb->csio,
4223 				/* retries */ 1,
4224 				/* cbfcnp */ cddone,
4225 				/* tag_action */ MSG_SIMPLE_Q_TAG,
4226 				/* lba */ address,
4227 				/* layer_number */ dvdstruct->layer_num,
4228 				/* key_format */ dvdstruct->format,
4229 				/* agid */ dvdstruct->agid,
4230 				/* data_ptr */ databuf,
4231 				/* dxfer_len */ length,
4232 				/* sense_len */ SSD_FULL_SIZE,
4233 				/* timeout */ 50000);
4234 
4235 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
4236 			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
4237 
4238 	if (error != 0)
4239 		goto bailout;
4240 
4241 	switch(dvdstruct->format) {
4242 	case DVD_STRUCT_PHYSICAL: {
4243 		struct scsi_read_dvd_struct_data_layer_desc *inlayer;
4244 		struct dvd_layer *outlayer;
4245 		struct scsi_read_dvd_struct_data_physical *phys_data;
4246 
4247 		phys_data =
4248 			(struct scsi_read_dvd_struct_data_physical *)databuf;
4249 		inlayer = &phys_data->layer_desc;
4250 		outlayer = (struct dvd_layer *)&dvdstruct->data;
4251 
4252 		dvdstruct->length = sizeof(*inlayer);
4253 
4254 		outlayer->book_type = (inlayer->book_type_version &
4255 			RDSD_BOOK_TYPE_MASK) >> RDSD_BOOK_TYPE_SHIFT;
4256 		outlayer->book_version = (inlayer->book_type_version &
4257 			RDSD_BOOK_VERSION_MASK);
4258 		outlayer->disc_size = (inlayer->disc_size_max_rate &
4259 			RDSD_DISC_SIZE_MASK) >> RDSD_DISC_SIZE_SHIFT;
4260 		outlayer->max_rate = (inlayer->disc_size_max_rate &
4261 			RDSD_MAX_RATE_MASK);
4262 		outlayer->nlayers = (inlayer->layer_info &
4263 			RDSD_NUM_LAYERS_MASK) >> RDSD_NUM_LAYERS_SHIFT;
4264 		outlayer->track_path = (inlayer->layer_info &
4265 			RDSD_TRACK_PATH_MASK) >> RDSD_TRACK_PATH_SHIFT;
4266 		outlayer->layer_type = (inlayer->layer_info &
4267 			RDSD_LAYER_TYPE_MASK);
4268 		outlayer->linear_density = (inlayer->density &
4269 			RDSD_LIN_DENSITY_MASK) >> RDSD_LIN_DENSITY_SHIFT;
4270 		outlayer->track_density = (inlayer->density &
4271 			RDSD_TRACK_DENSITY_MASK);
4272 		outlayer->bca = (inlayer->bca & RDSD_BCA_MASK) >>
4273 			RDSD_BCA_SHIFT;
4274 		outlayer->start_sector = scsi_3btoul(inlayer->main_data_start);
4275 		outlayer->end_sector = scsi_3btoul(inlayer->main_data_end);
4276 		outlayer->end_sector_l0 =
4277 			scsi_3btoul(inlayer->end_sector_layer0);
4278 		break;
4279 	}
4280 	case DVD_STRUCT_COPYRIGHT: {
4281 		struct scsi_read_dvd_struct_data_copyright *copy_data;
4282 
4283 		copy_data = (struct scsi_read_dvd_struct_data_copyright *)
4284 			databuf;
4285 
4286 		dvdstruct->cpst = copy_data->cps_type;
4287 		dvdstruct->rmi = copy_data->region_info;
4288 		dvdstruct->length = 0;
4289 
4290 		break;
4291 	}
4292 	default:
4293 		/*
4294 		 * Tell the user what the overall length is, no matter
4295 		 * what we can actually fit in the data buffer.
4296 		 */
4297 		dvdstruct->length = length - ccb->csio.resid -
4298 			sizeof(struct scsi_read_dvd_struct_data_header);
4299 
4300 		/*
4301 		 * But only actually copy out the smaller of what we read
4302 		 * in or what the structure can take.
4303 		 */
4304 		bcopy(databuf + sizeof(struct scsi_read_dvd_struct_data_header),
4305 		      dvdstruct->data,
4306 		      min(sizeof(dvdstruct->data), dvdstruct->length));
4307 		break;
4308 	}
4309 bailout:
4310 
4311 	if (databuf != NULL)
4312 		free(databuf, M_DEVBUF);
4313 
4314 	xpt_release_ccb(ccb);
4315 
4316 	return(error);
4317 }
4318 
4319 void
4320 scsi_report_key(struct ccb_scsiio *csio, u_int32_t retries,
4321 		void (*cbfcnp)(struct cam_periph *, union ccb *),
4322 		u_int8_t tag_action, u_int32_t lba, u_int8_t agid,
4323 		u_int8_t key_format, u_int8_t *data_ptr, u_int32_t dxfer_len,
4324 		u_int8_t sense_len, u_int32_t timeout)
4325 {
4326 	struct scsi_report_key *scsi_cmd;
4327 
4328 	scsi_cmd = (struct scsi_report_key *)&csio->cdb_io.cdb_bytes;
4329 	bzero(scsi_cmd, sizeof(*scsi_cmd));
4330 	scsi_cmd->opcode = REPORT_KEY;
4331 	scsi_ulto4b(lba, scsi_cmd->lba);
4332 	scsi_ulto2b(dxfer_len, scsi_cmd->alloc_len);
4333 	scsi_cmd->agid_keyformat = (agid << RK_KF_AGID_SHIFT) |
4334 		(key_format & RK_KF_KEYFORMAT_MASK);
4335 
4336 	cam_fill_csio(csio,
4337 		      retries,
4338 		      cbfcnp,
4339 		      /*flags*/ (dxfer_len == 0) ? CAM_DIR_NONE : CAM_DIR_IN,
4340 		      tag_action,
4341 		      /*data_ptr*/ data_ptr,
4342 		      /*dxfer_len*/ dxfer_len,
4343 		      sense_len,
4344 		      sizeof(*scsi_cmd),
4345 		      timeout);
4346 }
4347 
4348 void
4349 scsi_send_key(struct ccb_scsiio *csio, u_int32_t retries,
4350 	      void (*cbfcnp)(struct cam_periph *, union ccb *),
4351 	      u_int8_t tag_action, u_int8_t agid, u_int8_t key_format,
4352 	      u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
4353 	      u_int32_t timeout)
4354 {
4355 	struct scsi_send_key *scsi_cmd;
4356 
4357 	scsi_cmd = (struct scsi_send_key *)&csio->cdb_io.cdb_bytes;
4358 	bzero(scsi_cmd, sizeof(*scsi_cmd));
4359 	scsi_cmd->opcode = SEND_KEY;
4360 
4361 	scsi_ulto2b(dxfer_len, scsi_cmd->param_len);
4362 	scsi_cmd->agid_keyformat = (agid << RK_KF_AGID_SHIFT) |
4363 		(key_format & RK_KF_KEYFORMAT_MASK);
4364 
4365 	cam_fill_csio(csio,
4366 		      retries,
4367 		      cbfcnp,
4368 		      /*flags*/ CAM_DIR_OUT,
4369 		      tag_action,
4370 		      /*data_ptr*/ data_ptr,
4371 		      /*dxfer_len*/ dxfer_len,
4372 		      sense_len,
4373 		      sizeof(*scsi_cmd),
4374 		      timeout);
4375 }
4376 
4377 
4378 void
4379 scsi_read_dvd_structure(struct ccb_scsiio *csio, u_int32_t retries,
4380 			void (*cbfcnp)(struct cam_periph *, union ccb *),
4381 			u_int8_t tag_action, u_int32_t address,
4382 			u_int8_t layer_number, u_int8_t format, u_int8_t agid,
4383 			u_int8_t *data_ptr, u_int32_t dxfer_len,
4384 			u_int8_t sense_len, u_int32_t timeout)
4385 {
4386 	struct scsi_read_dvd_structure *scsi_cmd;
4387 
4388 	scsi_cmd = (struct scsi_read_dvd_structure *)&csio->cdb_io.cdb_bytes;
4389 	bzero(scsi_cmd, sizeof(*scsi_cmd));
4390 	scsi_cmd->opcode = READ_DVD_STRUCTURE;
4391 
4392 	scsi_ulto4b(address, scsi_cmd->address);
4393 	scsi_cmd->layer_number = layer_number;
4394 	scsi_cmd->format = format;
4395 	scsi_ulto2b(dxfer_len, scsi_cmd->alloc_len);
4396 	/* The AGID is the top two bits of this byte */
4397 	scsi_cmd->agid = agid << 6;
4398 
4399 	cam_fill_csio(csio,
4400 		      retries,
4401 		      cbfcnp,
4402 		      /*flags*/ CAM_DIR_IN,
4403 		      tag_action,
4404 		      /*data_ptr*/ data_ptr,
4405 		      /*dxfer_len*/ dxfer_len,
4406 		      sense_len,
4407 		      sizeof(*scsi_cmd),
4408 		      timeout);
4409 }
4410