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