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