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