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