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