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