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