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