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