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