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