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