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