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