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