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