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