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