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