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