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