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