xref: /freebsd/sys/cam/scsi/scsi_cd.c (revision 4cf49a43559ed9fdad601bdcccd2c55963008675)
1 /*
2  * Copyright (c) 1997 Justin T. Gibbs.
3  * Copyright (c) 1997, 1998, 1999 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/buf.h>
55 #include <sys/conf.h>
56 #include <sys/disk.h>
57 #include <sys/malloc.h>
58 #include <sys/cdio.h>
59 #include <sys/devicestat.h>
60 #include <sys/sysctl.h>
61 
62 #include <cam/cam.h>
63 #include <cam/cam_ccb.h>
64 #include <cam/cam_extend.h>
65 #include <cam/cam_periph.h>
66 #include <cam/cam_xpt_periph.h>
67 #include <cam/cam_queue.h>
68 
69 #include <cam/scsi/scsi_message.h>
70 #include <cam/scsi/scsi_da.h>
71 #include <cam/scsi/scsi_cd.h>
72 
73 #define LEADOUT         0xaa            /* leadout toc entry */
74 
75 struct cd_params {
76 	u_int32_t blksize;
77 	u_long    disksize;
78 };
79 
80 typedef enum {
81 	CD_Q_NONE	= 0x00,
82 	CD_Q_NO_TOUCH	= 0x01,
83 	CD_Q_BCD_TRACKS	= 0x02,
84 	CD_Q_NO_CHANGER	= 0x04,
85 	CD_Q_CHANGER	= 0x08
86 } cd_quirks;
87 
88 typedef enum {
89 	CD_FLAG_INVALID		= 0x001,
90 	CD_FLAG_NEW_DISC	= 0x002,
91 	CD_FLAG_DISC_LOCKED	= 0x004,
92 	CD_FLAG_DISC_REMOVABLE	= 0x008,
93 	CD_FLAG_TAGGED_QUEUING	= 0x010,
94 	CD_FLAG_CHANGER		= 0x040,
95 	CD_FLAG_ACTIVE		= 0x080,
96 	CD_FLAG_SCHED_ON_COMP	= 0x100,
97 	CD_FLAG_RETRY_UA	= 0x200
98 } cd_flags;
99 
100 typedef enum {
101 	CD_CCB_PROBE		= 0x01,
102 	CD_CCB_BUFFER_IO	= 0x02,
103 	CD_CCB_WAITING		= 0x03,
104 	CD_CCB_TYPE_MASK	= 0x0F,
105 	CD_CCB_RETRY_UA		= 0x10
106 } cd_ccb_state;
107 
108 typedef enum {
109 	CHANGER_TIMEOUT_SCHED		= 0x01,
110 	CHANGER_SHORT_TMOUT_SCHED	= 0x02,
111 	CHANGER_MANUAL_CALL		= 0x04,
112 	CHANGER_NEED_TIMEOUT		= 0x08
113 } cd_changer_flags;
114 
115 #define ccb_state ppriv_field0
116 #define ccb_bp ppriv_ptr1
117 
118 typedef enum {
119 	CD_STATE_PROBE,
120 	CD_STATE_NORMAL
121 } cd_state;
122 
123 struct cd_softc {
124 	cam_pinfo		pinfo;
125 	cd_state		state;
126 	volatile cd_flags	flags;
127 	struct buf_queue_head	buf_queue;
128 	LIST_HEAD(, ccb_hdr)	pending_ccbs;
129 	struct cd_params	params;
130 	struct disk	 	disk;
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 };
139 
140 struct cd_quirk_entry {
141 	struct scsi_inquiry_pattern inq_pat;
142 	cd_quirks quirks;
143 };
144 
145 /*
146  * These quirk entries aren't strictly necessary.  Basically, what they do
147  * is tell cdregister() up front that a device is a changer.  Otherwise, it
148  * will figure that fact out once it sees a LUN on the device that is
149  * greater than 0.  If it is known up front that a device is a changer, all
150  * I/O to the device will go through the changer scheduling routines, as
151  * opposed to the "normal" CD code.
152  */
153 static struct cd_quirk_entry cd_quirk_table[] =
154 {
155 	{
156 		{ T_CDROM, SIP_MEDIA_REMOVABLE, "NRC", "MBR-7", "*"},
157 		 /*quirks*/ CD_Q_CHANGER
158 	},
159 	{
160 		{ T_CDROM, SIP_MEDIA_REMOVABLE, "PIONEER", "CD-ROM DRM-604X",
161 		  "*"}, /* quirks */ CD_Q_CHANGER
162 	},
163 	{
164 		{ T_CDROM, SIP_MEDIA_REMOVABLE, "CHINON", "CD-ROM CDS-535","*"},
165 		/* quirks */ CD_Q_BCD_TRACKS
166 	}
167 };
168 
169 #ifndef MIN
170 #define MIN(x,y) ((x<y) ? x : y)
171 #endif
172 
173 #define CD_CDEV_MAJOR 15
174 #define CD_BDEV_MAJOR 6
175 
176 static	d_open_t	cdopen;
177 static	d_close_t	cdclose;
178 static	d_ioctl_t	cdioctl;
179 static	d_strategy_t	cdstrategy;
180 
181 static	periph_init_t	cdinit;
182 static	periph_ctor_t	cdregister;
183 static	periph_dtor_t	cdcleanup;
184 static	periph_start_t	cdstart;
185 static	periph_oninv_t	cdoninvalidate;
186 static	void		cdasync(void *callback_arg, u_int32_t code,
187 				struct cam_path *path, void *arg);
188 static	void		cdshorttimeout(void *arg);
189 static	void		cdschedule(struct cam_periph *periph, int priority);
190 static	void		cdrunchangerqueue(void *arg);
191 static	void		cdchangerschedule(struct cd_softc *softc);
192 static	int		cdrunccb(union ccb *ccb,
193 				 int (*error_routine)(union ccb *ccb,
194 						      u_int32_t cam_flags,
195 						      u_int32_t sense_flags),
196 				 u_int32_t cam_flags, u_int32_t sense_flags);
197 static union	ccb 	*cdgetccb(struct cam_periph *periph,
198 				  u_int32_t priority);
199 static	void		cddone(struct cam_periph *periph,
200 			       union ccb *start_ccb);
201 static	int		cderror(union ccb *ccb, u_int32_t cam_flags,
202 				u_int32_t sense_flags);
203 static	void		cdprevent(struct cam_periph *periph, int action);
204 static	int		cdsize(dev_t dev, u_int32_t *size);
205 static	int		cdreadtoc(struct cam_periph *periph, u_int32_t mode,
206 				  u_int32_t start, struct cd_toc_entry *data,
207 				  u_int32_t len);
208 static	int		cdgetmode(struct cam_periph *periph,
209 				  struct cd_mode_data *data, u_int32_t page);
210 static	int		cdsetmode(struct cam_periph *periph,
211 				  struct cd_mode_data *data);
212 static	int		cdplay(struct cam_periph *periph, u_int32_t blk,
213 			       u_int32_t len);
214 static	int		cdreadsubchannel(struct cam_periph *periph,
215 					 u_int32_t mode, u_int32_t format,
216 					 int track,
217 					 struct cd_sub_channel_info *data,
218 					 u_int32_t len);
219 static	int		cdplaymsf(struct cam_periph *periph, u_int32_t startm,
220 				  u_int32_t starts, u_int32_t startf,
221 				  u_int32_t endm, u_int32_t ends,
222 				  u_int32_t endf);
223 static	int		cdplaytracks(struct cam_periph *periph,
224 				     u_int32_t strack, u_int32_t sindex,
225 				     u_int32_t etrack, u_int32_t eindex);
226 static	int		cdpause(struct cam_periph *periph, u_int32_t go);
227 static	int		cdstopunit(struct cam_periph *periph, u_int32_t eject);
228 static	int		cdstartunit(struct cam_periph *periph);
229 
230 static struct periph_driver cddriver =
231 {
232 	cdinit, "cd",
233 	TAILQ_HEAD_INITIALIZER(cddriver.units), /* generation */ 0
234 };
235 
236 DATA_SET(periphdriver_set, cddriver);
237 
238 /* For 2.2-stable support */
239 #ifndef D_DISK
240 #define D_DISK 0
241 #endif
242 static struct cdevsw cd_cdevsw = {
243 	/* open */	cdopen,
244 	/* close */	cdclose,
245 	/* read */	physread,
246 	/* write */	nowrite,
247 	/* ioctl */	cdioctl,
248 	/* poll */	nopoll,
249 	/* mmap */	nommap,
250 	/* strategy */	cdstrategy,
251 	/* name */	"cd",
252 	/* maj */	CD_CDEV_MAJOR,
253 	/* dump */	nodump,
254 	/* psize */	nopsize,
255 	/* flags */	D_DISK,
256 	/* bmaj */	CD_BDEV_MAJOR
257 };
258 static struct cdevsw cddisk_cdevsw;
259 
260 static struct extend_array *cdperiphs;
261 static int num_changers;
262 
263 #ifndef CHANGER_MIN_BUSY_SECONDS
264 #define CHANGER_MIN_BUSY_SECONDS	5
265 #endif
266 #ifndef CHANGER_MAX_BUSY_SECONDS
267 #define CHANGER_MAX_BUSY_SECONDS	15
268 #endif
269 
270 static int changer_min_busy_seconds = CHANGER_MIN_BUSY_SECONDS;
271 static int changer_max_busy_seconds = CHANGER_MAX_BUSY_SECONDS;
272 
273 /*
274  * XXX KDM this CAM node should be moved if we ever get more CAM sysctl
275  * variables.
276  */
277 SYSCTL_NODE(_kern, OID_AUTO, cam, CTLFLAG_RD, 0, "CAM Subsystem");
278 SYSCTL_NODE(_kern_cam, OID_AUTO, cd, CTLFLAG_RD, 0, "CAM CDROM driver");
279 SYSCTL_NODE(_kern_cam_cd, OID_AUTO, changer, CTLFLAG_RD, 0, "CD Changer");
280 SYSCTL_INT(_kern_cam_cd_changer, OID_AUTO, min_busy_seconds, CTLFLAG_RW,
281 	   &changer_min_busy_seconds, 0, "Minimum changer scheduling quantum");
282 SYSCTL_INT(_kern_cam_cd_changer, OID_AUTO, max_busy_seconds, CTLFLAG_RW,
283 	   &changer_max_busy_seconds, 0, "Maximum changer scheduling quantum");
284 
285 struct cdchanger {
286 	path_id_t			 path_id;
287 	target_id_t			 target_id;
288 	int				 num_devices;
289 	struct camq			 devq;
290 	struct timeval			 start_time;
291 	struct cd_softc			 *cur_device;
292 	struct callout_handle		 short_handle;
293 	struct callout_handle		 long_handle;
294 	volatile cd_changer_flags	 flags;
295 	STAILQ_ENTRY(cdchanger)		 changer_links;
296 	STAILQ_HEAD(chdevlist, cd_softc) chluns;
297 };
298 
299 static STAILQ_HEAD(changerlist, cdchanger) changerq;
300 
301 void
302 cdinit(void)
303 {
304 	cam_status status;
305 	struct cam_path *path;
306 
307 	/*
308 	 * Create our extend array for storing the devices we attach to.
309 	 */
310 	cdperiphs = cam_extend_new();
311 	if (cdperiphs == NULL) {
312 		printf("cd: Failed to alloc extend array!\n");
313 		return;
314 	}
315 
316 	/*
317 	 * Install a global async callback.  This callback will
318 	 * receive async callbacks like "new device found".
319 	 */
320 	status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
321 				 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
322 
323 	if (status == CAM_REQ_CMP) {
324 		struct ccb_setasync csa;
325 
326                 xpt_setup_ccb(&csa.ccb_h, path, /*priority*/5);
327                 csa.ccb_h.func_code = XPT_SASYNC_CB;
328                 csa.event_enable = AC_FOUND_DEVICE;
329                 csa.callback = cdasync;
330                 csa.callback_arg = NULL;
331                 xpt_action((union ccb *)&csa);
332 		status = csa.ccb_h.status;
333                 xpt_free_path(path);
334         }
335 
336 	if (status != CAM_REQ_CMP) {
337 		printf("cd: Failed to attach master async callback "
338 		       "due to status 0x%x!\n", status);
339 	}
340 }
341 
342 static void
343 cdoninvalidate(struct cam_periph *periph)
344 {
345 	int s;
346 	struct cd_softc *softc;
347 	struct buf *q_bp;
348 	struct ccb_setasync csa;
349 
350 	softc = (struct cd_softc *)periph->softc;
351 
352 	/*
353 	 * De-register any async callbacks.
354 	 */
355 	xpt_setup_ccb(&csa.ccb_h, periph->path,
356 		      /* priority */ 5);
357 	csa.ccb_h.func_code = XPT_SASYNC_CB;
358 	csa.event_enable = 0;
359 	csa.callback = cdasync;
360 	csa.callback_arg = periph;
361 	xpt_action((union ccb *)&csa);
362 
363 	softc->flags |= CD_FLAG_INVALID;
364 
365 	/*
366 	 * Although the oninvalidate() routines are always called at
367 	 * splsoftcam, we need to be at splbio() here to keep the buffer
368 	 * queue from being modified while we traverse it.
369 	 */
370 	s = splbio();
371 
372 	/*
373 	 * Return all queued I/O with ENXIO.
374 	 * XXX Handle any transactions queued to the card
375 	 *     with XPT_ABORT_CCB.
376 	 */
377 	while ((q_bp = bufq_first(&softc->buf_queue)) != NULL){
378 		bufq_remove(&softc->buf_queue, q_bp);
379 		q_bp->b_resid = q_bp->b_bcount;
380 		q_bp->b_error = ENXIO;
381 		q_bp->b_flags |= B_ERROR;
382 		biodone(q_bp);
383 	}
384 	splx(s);
385 
386 	/*
387 	 * If this device is part of a changer, and it was scheduled
388 	 * to run, remove it from the run queue since we just nuked
389 	 * all of its scheduled I/O.
390 	 */
391 	if ((softc->flags & CD_FLAG_CHANGER)
392 	 && (softc->pinfo.index != CAM_UNQUEUED_INDEX))
393 		camq_remove(&softc->changer->devq, softc->pinfo.index);
394 
395 	xpt_print_path(periph->path);
396 	printf("lost device\n");
397 }
398 
399 static void
400 cdcleanup(struct cam_periph *periph)
401 {
402 	struct cd_softc *softc;
403 	int s;
404 
405 	softc = (struct cd_softc *)periph->softc;
406 
407 	xpt_print_path(periph->path);
408 	printf("removing device entry\n");
409 
410 	s = splsoftcam();
411 	/*
412 	 * In the queued, non-active case, the device in question
413 	 * has already been removed from the changer run queue.  Since this
414 	 * device is active, we need to de-activate it, and schedule
415 	 * another device to run.  (if there is another one to run)
416 	 */
417 	if ((softc->flags & CD_FLAG_CHANGER)
418 	 && (softc->flags & CD_FLAG_ACTIVE)) {
419 
420 		/*
421 		 * The purpose of the short timeout is soley to determine
422 		 * whether the current device has finished or not.  Well,
423 		 * since we're removing the active device, we know that it
424 		 * is finished.  So, get rid of the short timeout.
425 		 * Otherwise, if we're in the time period before the short
426 		 * timeout fires, and there are no other devices in the
427 		 * queue to run, there won't be any other device put in the
428 		 * active slot.  i.e., when we call cdrunchangerqueue()
429 		 * below, it won't do anything.  Then, when the short
430 		 * timeout fires, it'll look at the "current device", which
431 		 * we are free below, and possibly panic the kernel on a
432 		 * bogus pointer reference.
433 		 *
434 		 * The long timeout doesn't really matter, since we
435 		 * decrement the qfrozen_cnt to indicate that there is
436 		 * nothing in the active slot now.  Therefore, there won't
437 		 * be any bogus pointer references there.
438 		 */
439 		if (softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
440 			untimeout(cdshorttimeout, softc->changer,
441 				  softc->changer->short_handle);
442 			softc->changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
443 		}
444 		softc->changer->devq.qfrozen_cnt--;
445 		softc->changer->flags |= CHANGER_MANUAL_CALL;
446 		cdrunchangerqueue(softc->changer);
447 	}
448 
449 	/*
450 	 * If we're removing the last device on the changer, go ahead and
451 	 * remove the changer device structure.
452 	 */
453 	if ((softc->flags & CD_FLAG_CHANGER)
454 	 && (--softc->changer->num_devices == 0)) {
455 
456 		/*
457 		 * Theoretically, there shouldn't be any timeouts left, but
458 		 * I'm not completely sure that that will be the case.  So,
459 		 * it won't hurt to check and see if there are any left.
460 		 */
461 		if (softc->changer->flags & CHANGER_TIMEOUT_SCHED) {
462 			untimeout(cdrunchangerqueue, softc->changer,
463 				  softc->changer->long_handle);
464 			softc->changer->flags &= ~CHANGER_TIMEOUT_SCHED;
465 		}
466 
467 		if (softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
468 			untimeout(cdshorttimeout, softc->changer,
469 				  softc->changer->short_handle);
470 			softc->changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
471 		}
472 
473 		STAILQ_REMOVE(&changerq, softc->changer, cdchanger,
474 			      changer_links);
475 		xpt_print_path(periph->path);
476 		printf("removing changer entry\n");
477 		free(softc->changer, M_DEVBUF);
478 		num_changers--;
479 	}
480 	devstat_remove_entry(&softc->device_stats);
481 	cam_extend_release(cdperiphs, periph->unit_number);
482 	free(softc, M_DEVBUF);
483 	splx(s);
484 }
485 
486 static void
487 cdasync(void *callback_arg, u_int32_t code,
488 	struct cam_path *path, void *arg)
489 {
490 	struct cam_periph *periph;
491 
492 	periph = (struct cam_periph *)callback_arg;
493 	switch (code) {
494 	case AC_FOUND_DEVICE:
495 	{
496 		struct ccb_getdev *cgd;
497 		cam_status status;
498 
499 		cgd = (struct ccb_getdev *)arg;
500 
501 		if ((cgd->pd_type != T_CDROM) && (cgd->pd_type != T_WORM))
502 			break;
503 
504 		/*
505 		 * Allocate a peripheral instance for
506 		 * this device and start the probe
507 		 * process.
508 		 */
509 		status = cam_periph_alloc(cdregister, cdoninvalidate,
510 					  cdcleanup, cdstart,
511 					  "cd", CAM_PERIPH_BIO,
512 					  cgd->ccb_h.path, cdasync,
513 					  AC_FOUND_DEVICE, cgd);
514 
515 		if (status != CAM_REQ_CMP
516 		 && status != CAM_REQ_INPROG)
517 			printf("cdasync: Unable to attach new device "
518 			       "due to status 0x%x\n", status);
519 
520 		break;
521 	}
522 	case AC_SENT_BDR:
523 	case AC_BUS_RESET:
524 	{
525 		struct cd_softc *softc;
526 		struct ccb_hdr *ccbh;
527 		int s;
528 
529 		softc = (struct cd_softc *)periph->softc;
530 		s = splsoftcam();
531 		/*
532 		 * Don't fail on the expected unit attention
533 		 * that will occur.
534 		 */
535 		softc->flags |= CD_FLAG_RETRY_UA;
536 		for (ccbh = LIST_FIRST(&softc->pending_ccbs);
537 		     ccbh != NULL; ccbh = LIST_NEXT(ccbh, periph_links.le))
538 			ccbh->ccb_state |= CD_CCB_RETRY_UA;
539 		splx(s);
540 		/* FALLTHROUGH */
541 	}
542 	default:
543 		cam_periph_async(periph, code, path, arg);
544 		break;
545 	}
546 }
547 
548 static cam_status
549 cdregister(struct cam_periph *periph, void *arg)
550 {
551 	struct cd_softc *softc;
552 	struct ccb_setasync csa;
553 	struct ccb_getdev *cgd;
554 	caddr_t match;
555 
556 	cgd = (struct ccb_getdev *)arg;
557 	if (periph == NULL) {
558 		printf("cdregister: periph was NULL!!\n");
559 		return(CAM_REQ_CMP_ERR);
560 	}
561 	if (cgd == NULL) {
562 		printf("cdregister: no getdev CCB, can't register device\n");
563 		return(CAM_REQ_CMP_ERR);
564 	}
565 
566 	softc = (struct cd_softc *)malloc(sizeof(*softc),M_DEVBUF,M_NOWAIT);
567 
568 	if (softc == NULL) {
569 		printf("cdregister: Unable to probe new device. "
570 		       "Unable to allocate softc\n");
571 		return(CAM_REQ_CMP_ERR);
572 	}
573 
574 	bzero(softc, sizeof(*softc));
575 	LIST_INIT(&softc->pending_ccbs);
576 	softc->state = CD_STATE_PROBE;
577 	bufq_init(&softc->buf_queue);
578 	if (SID_IS_REMOVABLE(&cgd->inq_data))
579 		softc->flags |= CD_FLAG_DISC_REMOVABLE;
580 	if ((cgd->inq_data.flags & SID_CmdQue) != 0)
581 		softc->flags |= CD_FLAG_TAGGED_QUEUING;
582 
583 	periph->softc = softc;
584 	softc->periph = periph;
585 
586 	cam_extend_set(cdperiphs, periph->unit_number, periph);
587 
588 	/*
589 	 * See if this device has any quirks.
590 	 */
591 	match = cam_quirkmatch((caddr_t)&cgd->inq_data,
592 			       (caddr_t)cd_quirk_table,
593 			       sizeof(cd_quirk_table)/sizeof(*cd_quirk_table),
594 			       sizeof(*cd_quirk_table), scsi_inquiry_match);
595 
596 	if (match != NULL)
597 		softc->quirks = ((struct cd_quirk_entry *)match)->quirks;
598 	else
599 		softc->quirks = CD_Q_NONE;
600 
601 	/*
602 	 * We need to register the statistics structure for this device,
603 	 * but we don't have the blocksize yet for it.  So, we register
604 	 * the structure and indicate that we don't have the blocksize
605 	 * yet.  Unlike other SCSI peripheral drivers, we explicitly set
606 	 * the device type here to be CDROM, rather than just ORing in
607 	 * cgd->pd_type.  This is because this driver can attach to either
608 	 * CDROM or WORM devices, and we want this peripheral driver to
609 	 * show up in the devstat list as a CD peripheral driver, not a
610 	 * WORM peripheral driver.  WORM drives will also have the WORM
611 	 * driver attached to them.
612 	 */
613 	devstat_add_entry(&softc->device_stats, "cd",
614 			  periph->unit_number, 0,
615 	  		  DEVSTAT_BS_UNAVAILABLE,
616 			  DEVSTAT_TYPE_CDROM | DEVSTAT_TYPE_IF_SCSI,
617 			  DEVSTAT_PRIORITY_CD);
618 	disk_create(periph->unit_number, &softc->disk,
619 		    DSO_NOLABELS | DSO_ONESLICE,
620 		    &cd_cdevsw, &cddisk_cdevsw);
621 
622 	/*
623 	 * Add an async callback so that we get
624 	 * notified if this device goes away.
625 	 */
626 	xpt_setup_ccb(&csa.ccb_h, periph->path,
627 		      /* priority */ 5);
628 	csa.ccb_h.func_code = XPT_SASYNC_CB;
629 	csa.event_enable = AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE;
630 	csa.callback = cdasync;
631 	csa.callback_arg = periph;
632 	xpt_action((union ccb *)&csa);
633 
634 	/*
635 	 * If the target lun is greater than 0, we most likely have a CD
636 	 * changer device.  Check the quirk entries as well, though, just
637 	 * in case someone has a CD tower with one lun per drive or
638 	 * something like that.  Also, if we know up front that a
639 	 * particular device is a changer, we can mark it as such starting
640 	 * with lun 0, instead of lun 1.  It shouldn't be necessary to have
641 	 * a quirk entry to define something as a changer, however.
642 	 */
643 	if (((cgd->ccb_h.target_lun > 0)
644 	  && ((softc->quirks & CD_Q_NO_CHANGER) == 0))
645 	 || ((softc->quirks & CD_Q_CHANGER) != 0)) {
646 		struct cdchanger *nchanger;
647 		struct cam_periph *nperiph;
648 		struct cam_path *path;
649 		cam_status status;
650 		int found;
651 
652 		/* Set the changer flag in the current device's softc */
653 		softc->flags |= CD_FLAG_CHANGER;
654 
655 		if (num_changers == 0)
656 			STAILQ_INIT(&changerq);
657 
658 		/*
659 		 * Now, look around for an existing changer device with the
660 		 * same path and target ID as the current device.
661 		 */
662 		for (found = 0,
663 		     nchanger = (struct cdchanger *)STAILQ_FIRST(&changerq);
664 		     nchanger != NULL;
665 		     nchanger = STAILQ_NEXT(nchanger, changer_links)){
666 			if ((nchanger->path_id == cgd->ccb_h.path_id)
667 			 && (nchanger->target_id == cgd->ccb_h.target_id)) {
668 				found = 1;
669 				break;
670 			}
671 		}
672 
673 		/*
674 		 * If we found a matching entry, just add this device to
675 		 * the list of devices on this changer.
676 		 */
677 		if (found == 1) {
678 			struct chdevlist *chlunhead;
679 
680 			chlunhead = &nchanger->chluns;
681 
682 			/*
683 			 * XXX KDM look at consolidating this code with the
684 			 * code below in a separate function.
685 			 */
686 
687 			/*
688 			 * Create a path with lun id 0, and see if we can
689 			 * find a matching device
690 			 */
691 			status = xpt_create_path(&path, /*periph*/ periph,
692 						 cgd->ccb_h.path_id,
693 						 cgd->ccb_h.target_id, 0);
694 
695 			if ((status == CAM_REQ_CMP)
696 			 && ((nperiph = cam_periph_find(path, "cd")) != NULL)){
697 				struct cd_softc *nsoftc;
698 
699 				nsoftc = (struct cd_softc *)nperiph->softc;
700 
701 				if ((nsoftc->flags & CD_FLAG_CHANGER) == 0){
702 					nsoftc->flags |= CD_FLAG_CHANGER;
703 					nchanger->num_devices++;
704 					if (camq_resize(&nchanger->devq,
705 					   nchanger->num_devices)!=CAM_REQ_CMP){
706 						printf("cdregister: "
707 						       "camq_resize "
708 						       "failed, changer "
709 						       "support may "
710 						       "be messed up\n");
711 					}
712 					nsoftc->changer = nchanger;
713 					nsoftc->pinfo.index =CAM_UNQUEUED_INDEX;
714 
715 					STAILQ_INSERT_TAIL(&nchanger->chluns,
716 							  nsoftc,changer_links);
717 				}
718 			} else if (status == CAM_REQ_CMP)
719 				xpt_free_path(path);
720 			else {
721 				printf("cdregister: unable to allocate path\n"
722 				       "cdregister: changer support may be "
723 				       "broken\n");
724 			}
725 
726 			nchanger->num_devices++;
727 
728 			softc->changer = nchanger;
729 			softc->pinfo.index = CAM_UNQUEUED_INDEX;
730 
731 			if (camq_resize(&nchanger->devq,
732 			    nchanger->num_devices) != CAM_REQ_CMP) {
733 				printf("cdregister: camq_resize "
734 				       "failed, changer support may "
735 				       "be messed up\n");
736 			}
737 
738 			STAILQ_INSERT_TAIL(chlunhead, softc, changer_links);
739 		}
740 		/*
741 		 * In this case, we don't already have an entry for this
742 		 * particular changer, so we need to create one, add it to
743 		 * the queue, and queue this device on the list for this
744 		 * changer.  Before we queue this device, however, we need
745 		 * to search for lun id 0 on this target, and add it to the
746 		 * queue first, if it exists.  (and if it hasn't already
747 		 * been marked as part of the changer.)
748 		 */
749 		else {
750 			nchanger = malloc(sizeof(struct cdchanger),
751 				M_DEVBUF, M_NOWAIT);
752 
753 			if (nchanger == NULL) {
754 				softc->flags &= ~CD_FLAG_CHANGER;
755 				printf("cdregister: unable to malloc "
756 				       "changer structure\ncdregister: "
757 				       "changer support disabled\n");
758 
759 				/*
760 				 * Yes, gotos can be gross but in this case
761 				 * I think it's justified..
762 				 */
763 				goto cdregisterexit;
764 			}
765 
766 			/* zero the structure */
767 			bzero(nchanger, sizeof(struct cdchanger));
768 
769 			if (camq_init(&nchanger->devq, 1) != 0) {
770 				softc->flags &= ~CD_FLAG_CHANGER;
771 				printf("cdregister: changer support "
772 				       "disabled\n");
773 				goto cdregisterexit;
774 			}
775 
776 			num_changers++;
777 
778 			nchanger->path_id = cgd->ccb_h.path_id;
779 			nchanger->target_id = cgd->ccb_h.target_id;
780 
781 			/* this is superfluous, but it makes things clearer */
782 			nchanger->num_devices = 0;
783 
784 			STAILQ_INIT(&nchanger->chluns);
785 
786 			STAILQ_INSERT_TAIL(&changerq, nchanger,
787 					   changer_links);
788 
789 			/*
790 			 * Create a path with lun id 0, and see if we can
791 			 * find a matching device
792 			 */
793 			status = xpt_create_path(&path, /*periph*/ periph,
794 						 cgd->ccb_h.path_id,
795 						 cgd->ccb_h.target_id, 0);
796 
797 			/*
798 			 * If we were able to allocate the path, and if we
799 			 * find a matching device and it isn't already
800 			 * marked as part of a changer, then we add it to
801 			 * the current changer.
802 			 */
803 			if ((status == CAM_REQ_CMP)
804 			 && ((nperiph = cam_periph_find(path, "cd")) != NULL)
805 			 && ((((struct cd_softc *)periph->softc)->flags &
806 			       CD_FLAG_CHANGER) == 0)) {
807 				struct cd_softc *nsoftc;
808 
809 				nsoftc = (struct cd_softc *)nperiph->softc;
810 
811 				nsoftc->flags |= CD_FLAG_CHANGER;
812 				nchanger->num_devices++;
813 				if (camq_resize(&nchanger->devq,
814 				    nchanger->num_devices) != CAM_REQ_CMP) {
815 					printf("cdregister: camq_resize "
816 					       "failed, changer support may "
817 					       "be messed up\n");
818 				}
819 				nsoftc->changer = nchanger;
820 				nsoftc->pinfo.index = CAM_UNQUEUED_INDEX;
821 
822 				STAILQ_INSERT_TAIL(&nchanger->chluns,
823 						   nsoftc, changer_links);
824 			} else if (status == CAM_REQ_CMP)
825 				xpt_free_path(path);
826 			else {
827 				printf("cdregister: unable to allocate path\n"
828 				       "cdregister: changer support may be "
829 				       "broken\n");
830 			}
831 
832 			softc->changer = nchanger;
833 			softc->pinfo.index = CAM_UNQUEUED_INDEX;
834 			nchanger->num_devices++;
835 			if (camq_resize(&nchanger->devq,
836 			    nchanger->num_devices) != CAM_REQ_CMP) {
837 				printf("cdregister: camq_resize "
838 				       "failed, changer support may "
839 				       "be messed up\n");
840 			}
841 			STAILQ_INSERT_TAIL(&nchanger->chluns, softc,
842 					   changer_links);
843 		}
844 	}
845 
846 cdregisterexit:
847 
848 	/* Lock this peripheral until we are setup */
849 	/* Can't block */
850 	cam_periph_lock(periph, PRIBIO);
851 
852 	if ((softc->flags & CD_FLAG_CHANGER) == 0)
853 		xpt_schedule(periph, /*priority*/5);
854 	else
855 		cdschedule(periph, /*priority*/ 5);
856 
857 	return(CAM_REQ_CMP);
858 }
859 
860 static int
861 cdopen(dev_t dev, int flags, int fmt, struct proc *p)
862 {
863 	struct disklabel *label;
864 	struct cam_periph *periph;
865 	struct cd_softc *softc;
866 	struct ccb_getdev cgd;
867 	u_int32_t size;
868 	int unit, error;
869 	int s;
870 
871 	unit = dkunit(dev);
872 	periph = cam_extend_get(cdperiphs, unit);
873 
874 	if (periph == NULL)
875 		return (ENXIO);
876 
877 	softc = (struct cd_softc *)periph->softc;
878 
879 	/*
880 	 * Grab splsoftcam and hold it until we lock the peripheral.
881 	 */
882 	s = splsoftcam();
883 	if (softc->flags & CD_FLAG_INVALID) {
884 		splx(s);
885 		return(ENXIO);
886 	}
887 
888 	if ((error = cam_periph_lock(periph, PRIBIO | PCATCH)) != 0) {
889 		splx(s);
890 		return (error);
891 	}
892 
893 	splx(s);
894 
895 	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
896 		return(ENXIO);
897 
898 	cdprevent(periph, PR_PREVENT);
899 
900 	/* find out the size */
901 	if ((error = cdsize(dev, &size)) != 0) {
902 		cdprevent(periph, PR_ALLOW);
903 		cam_periph_unlock(periph);
904 		cam_periph_release(periph);
905 		return(error);
906 	}
907 
908 	/*
909 	 * Build prototype label for whole disk.
910 	 * Should take information about different data tracks from the
911 	 * TOC and put it in the partition table.
912 	 */
913 	label = &softc->disk.d_label;
914 	bzero(label, sizeof(*label));
915 	label->d_type = DTYPE_SCSI;
916 
917 	/*
918 	 * Grab the inquiry data to get the vendor and product names.
919 	 * Put them in the typename and packname for the label.
920 	 */
921 	xpt_setup_ccb(&cgd.ccb_h, periph->path, /*priority*/ 1);
922 	cgd.ccb_h.func_code = XPT_GDEV_TYPE;
923 	xpt_action((union ccb *)&cgd);
924 
925 	strncpy(label->d_typename, cgd.inq_data.vendor,
926 		min(SID_VENDOR_SIZE, sizeof(label->d_typename)));
927 	strncpy(label->d_packname, cgd.inq_data.product,
928 		min(SID_PRODUCT_SIZE, sizeof(label->d_packname)));
929 
930 	label->d_secsize = softc->params.blksize;
931 	label->d_secperunit = softc->params.disksize;
932 	label->d_flags = D_REMOVABLE;
933 	/*
934 	 * Make partition 'a' cover the whole disk.  This is a temporary
935 	 * compatibility hack.  The 'a' partition should not exist, so
936 	 * the slice code won't create it.  The slice code will make
937 	 * partition (RAW_PART + 'a') cover the whole disk and fill in
938 	 * some more defaults.
939 	 */
940 	label->d_partitions[0].p_size = label->d_secperunit;
941 	label->d_partitions[0].p_fstype = FS_OTHER;
942 
943 	/*
944 	 * We unconditionally (re)set the blocksize each time the
945 	 * CD device is opened.  This is because the CD can change,
946 	 * and therefore the blocksize might change.
947 	 * XXX problems here if some slice or partition is still
948 	 * open with the old size?
949 	 */
950 	if ((softc->device_stats.flags & DEVSTAT_BS_UNAVAILABLE) != 0)
951 		softc->device_stats.flags &= ~DEVSTAT_BS_UNAVAILABLE;
952 	softc->device_stats.block_size = softc->params.blksize;
953 
954 	cam_periph_unlock(periph);
955 
956 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdopen\n"));
957 
958 	return (error);
959 }
960 
961 static int
962 cdclose(dev_t dev, int flag, int fmt, struct proc *p)
963 {
964 	struct 	cam_periph *periph;
965 	struct	cd_softc *softc;
966 	int	unit, error;
967 
968 	unit = dkunit(dev);
969 	periph = cam_extend_get(cdperiphs, unit);
970 	if (periph == NULL)
971 		return (ENXIO);
972 
973 	softc = (struct cd_softc *)periph->softc;
974 
975 	if ((error = cam_periph_lock(periph, PRIBIO)) != 0)
976 		return (error);
977 
978 	if ((softc->flags & CD_FLAG_DISC_REMOVABLE) != 0)
979 		cdprevent(periph, PR_ALLOW);
980 
981 	/*
982 	 * Since we're closing this CD, mark the blocksize as unavailable.
983 	 * It will be marked as available whence the CD is opened again.
984 	 */
985 	softc->device_stats.flags |= DEVSTAT_BS_UNAVAILABLE;
986 
987 	cam_periph_unlock(periph);
988 	cam_periph_release(periph);
989 
990 	return (0);
991 }
992 
993 static void
994 cdshorttimeout(void *arg)
995 {
996 	struct cdchanger *changer;
997 	int s;
998 
999 	s = splsoftcam();
1000 
1001 	changer = (struct cdchanger *)arg;
1002 
1003 	/* Always clear the short timeout flag, since that's what we're in */
1004 	changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
1005 
1006 	/*
1007 	 * Check to see if there is any more pending or outstanding I/O for
1008 	 * this device.  If not, move it out of the active slot.
1009 	 */
1010 	if ((bufq_first(&changer->cur_device->buf_queue) == NULL)
1011 	 && (changer->cur_device->device_stats.busy_count == 0)) {
1012 		changer->flags |= CHANGER_MANUAL_CALL;
1013 		cdrunchangerqueue(changer);
1014 	}
1015 
1016 	splx(s);
1017 }
1018 
1019 /*
1020  * This is a wrapper for xpt_schedule.  It only applies to changers.
1021  */
1022 static void
1023 cdschedule(struct cam_periph *periph, int priority)
1024 {
1025 	struct cd_softc *softc;
1026 	int s;
1027 
1028 	s = splsoftcam();
1029 
1030 	softc = (struct cd_softc *)periph->softc;
1031 
1032 	/*
1033 	 * If this device isn't currently queued, and if it isn't
1034 	 * the active device, then we queue this device and run the
1035 	 * changer queue if there is no timeout scheduled to do it.
1036 	 * If this device is the active device, just schedule it
1037 	 * to run again.  If this device is queued, there should be
1038 	 * a timeout in place already that will make sure it runs.
1039 	 */
1040 	if ((softc->pinfo.index == CAM_UNQUEUED_INDEX)
1041 	 && ((softc->flags & CD_FLAG_ACTIVE) == 0)) {
1042 		/*
1043 		 * We don't do anything with the priority here.
1044 		 * This is strictly a fifo queue.
1045 		 */
1046 		softc->pinfo.priority = 1;
1047 		softc->pinfo.generation = ++softc->changer->devq.generation;
1048 		camq_insert(&softc->changer->devq, (cam_pinfo *)softc);
1049 
1050 		/*
1051 		 * Since we just put a device in the changer queue,
1052 		 * check and see if there is a timeout scheduled for
1053 		 * this changer.  If so, let the timeout handle
1054 		 * switching this device into the active slot.  If
1055 		 * not, manually call the timeout routine to
1056 		 * bootstrap things.
1057 		 */
1058 		if (((softc->changer->flags & CHANGER_TIMEOUT_SCHED)==0)
1059 		 && ((softc->changer->flags & CHANGER_NEED_TIMEOUT)==0)
1060 		 && ((softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED)==0)){
1061 			softc->changer->flags |= CHANGER_MANUAL_CALL;
1062 			cdrunchangerqueue(softc->changer);
1063 		}
1064 	} else if ((softc->flags & CD_FLAG_ACTIVE)
1065 		&& ((softc->flags & CD_FLAG_SCHED_ON_COMP) == 0))
1066 		xpt_schedule(periph, priority);
1067 
1068 	splx(s);
1069 
1070 }
1071 
1072 static void
1073 cdrunchangerqueue(void *arg)
1074 {
1075 	struct cd_softc *softc;
1076 	struct cdchanger *changer;
1077 	int called_from_timeout;
1078 	int s;
1079 
1080 	s = splsoftcam();
1081 
1082 	changer = (struct cdchanger *)arg;
1083 
1084 	/*
1085 	 * If we have NOT been called from cdstrategy() or cddone(), and
1086 	 * instead from a timeout routine, go ahead and clear the
1087 	 * timeout flag.
1088 	 */
1089 	if ((changer->flags & CHANGER_MANUAL_CALL) == 0) {
1090 		changer->flags &= ~CHANGER_TIMEOUT_SCHED;
1091 		called_from_timeout = 1;
1092 	} else
1093 		called_from_timeout = 0;
1094 
1095 	/* Always clear the manual call flag */
1096 	changer->flags &= ~CHANGER_MANUAL_CALL;
1097 
1098 	/* nothing to do if the queue is empty */
1099 	if (changer->devq.entries <= 0) {
1100 		splx(s);
1101 		return;
1102 	}
1103 
1104 	/*
1105 	 * If the changer queue is frozen, that means we have an active
1106 	 * device.
1107 	 */
1108 	if (changer->devq.qfrozen_cnt > 0) {
1109 
1110 		if (changer->cur_device->device_stats.busy_count > 0) {
1111 			changer->cur_device->flags |= CD_FLAG_SCHED_ON_COMP;
1112 			changer->cur_device->bufs_left =
1113 				changer->cur_device->device_stats.busy_count;
1114 			if (called_from_timeout) {
1115 				changer->long_handle =
1116 					timeout(cdrunchangerqueue, changer,
1117 				        changer_max_busy_seconds * hz);
1118 				changer->flags |= CHANGER_TIMEOUT_SCHED;
1119 			}
1120 			splx(s);
1121 			return;
1122 		}
1123 
1124 		/*
1125 		 * We always need to reset the frozen count and clear the
1126 		 * active flag.
1127 		 */
1128 		changer->devq.qfrozen_cnt--;
1129 		changer->cur_device->flags &= ~CD_FLAG_ACTIVE;
1130 		changer->cur_device->flags &= ~CD_FLAG_SCHED_ON_COMP;
1131 
1132 		/*
1133 		 * Check to see whether the current device has any I/O left
1134 		 * to do.  If so, requeue it at the end of the queue.  If
1135 		 * not, there is no need to requeue it.
1136 		 */
1137 		if (bufq_first(&changer->cur_device->buf_queue) != NULL) {
1138 
1139 			changer->cur_device->pinfo.generation =
1140 				++changer->devq.generation;
1141 			camq_insert(&changer->devq,
1142 				(cam_pinfo *)changer->cur_device);
1143 		}
1144 	}
1145 
1146 	softc = (struct cd_softc *)camq_remove(&changer->devq, CAMQ_HEAD);
1147 
1148 	changer->cur_device = softc;
1149 
1150 	changer->devq.qfrozen_cnt++;
1151 	softc->flags |= CD_FLAG_ACTIVE;
1152 
1153 	/* Just in case this device is waiting */
1154 	wakeup(&softc->changer);
1155 	xpt_schedule(softc->periph, /*priority*/ 1);
1156 
1157 	/*
1158 	 * Get rid of any pending timeouts, and set a flag to schedule new
1159 	 * ones so this device gets its full time quantum.
1160 	 */
1161 	if (changer->flags & CHANGER_TIMEOUT_SCHED) {
1162 		untimeout(cdrunchangerqueue, changer, changer->long_handle);
1163 		changer->flags &= ~CHANGER_TIMEOUT_SCHED;
1164 	}
1165 
1166 	if (changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
1167 		untimeout(cdshorttimeout, changer, changer->short_handle);
1168 		changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
1169 	}
1170 
1171 	/*
1172 	 * We need to schedule timeouts, but we only do this after the
1173 	 * first transaction has completed.  This eliminates the changer
1174 	 * switch time.
1175 	 */
1176 	changer->flags |= CHANGER_NEED_TIMEOUT;
1177 
1178 	splx(s);
1179 }
1180 
1181 static void
1182 cdchangerschedule(struct cd_softc *softc)
1183 {
1184 	struct cdchanger *changer;
1185 	int s;
1186 
1187 	s = splsoftcam();
1188 
1189 	changer = softc->changer;
1190 
1191 	/*
1192 	 * If this is a changer, and this is the current device,
1193 	 * and this device has at least the minimum time quantum to
1194 	 * run, see if we can switch it out.
1195 	 */
1196 	if ((softc->flags & CD_FLAG_ACTIVE)
1197 	 && ((changer->flags & CHANGER_SHORT_TMOUT_SCHED) == 0)
1198 	 && ((changer->flags & CHANGER_NEED_TIMEOUT) == 0)) {
1199 		/*
1200 		 * We try three things here.  The first is that we
1201 		 * check to see whether the schedule on completion
1202 		 * flag is set.  If it is, we decrement the number
1203 		 * of buffers left, and if it's zero, we reschedule.
1204 		 * Next, we check to see whether the pending buffer
1205 		 * queue is empty and whether there are no
1206 		 * outstanding transactions.  If so, we reschedule.
1207 		 * Next, we see if the pending buffer queue is empty.
1208 		 * If it is, we set the number of buffers left to
1209 		 * the current active buffer count and set the
1210 		 * schedule on complete flag.
1211 		 */
1212 		if (softc->flags & CD_FLAG_SCHED_ON_COMP) {
1213 		 	if (--softc->bufs_left == 0) {
1214 				softc->changer->flags |=
1215 					CHANGER_MANUAL_CALL;
1216 				softc->flags &= ~CD_FLAG_SCHED_ON_COMP;
1217 				cdrunchangerqueue(softc->changer);
1218 			}
1219 		} else if ((bufq_first(&softc->buf_queue) == NULL)
1220 		        && (softc->device_stats.busy_count == 0)) {
1221 			softc->changer->flags |= CHANGER_MANUAL_CALL;
1222 			cdrunchangerqueue(softc->changer);
1223 		}
1224 	} else if ((softc->changer->flags & CHANGER_NEED_TIMEOUT)
1225 		&& (softc->flags & CD_FLAG_ACTIVE)) {
1226 
1227 		/*
1228 		 * Now that the first transaction to this
1229 		 * particular device has completed, we can go ahead
1230 		 * and schedule our timeouts.
1231 		 */
1232 		if ((changer->flags & CHANGER_TIMEOUT_SCHED) == 0) {
1233 			changer->long_handle =
1234 			    timeout(cdrunchangerqueue, changer,
1235 				    changer_max_busy_seconds * hz);
1236 			changer->flags |= CHANGER_TIMEOUT_SCHED;
1237 		} else
1238 			printf("cdchangerschedule: already have a long"
1239 			       " timeout!\n");
1240 
1241 		if ((changer->flags & CHANGER_SHORT_TMOUT_SCHED) == 0) {
1242 			changer->short_handle =
1243 			    timeout(cdshorttimeout, changer,
1244 				    changer_min_busy_seconds * hz);
1245 			changer->flags |= CHANGER_SHORT_TMOUT_SCHED;
1246 		} else
1247 			printf("cdchangerschedule: already have a short "
1248 			       "timeout!\n");
1249 
1250 		/*
1251 		 * We just scheduled timeouts, no need to schedule
1252 		 * more.
1253 		 */
1254 		changer->flags &= ~CHANGER_NEED_TIMEOUT;
1255 
1256 	}
1257 	splx(s);
1258 }
1259 
1260 static int
1261 cdrunccb(union ccb *ccb, int (*error_routine)(union ccb *ccb,
1262 					      u_int32_t cam_flags,
1263 					      u_int32_t sense_flags),
1264 	 u_int32_t cam_flags, u_int32_t sense_flags)
1265 {
1266 	struct cd_softc *softc;
1267 	struct cam_periph *periph;
1268 	int error;
1269 
1270 	periph = xpt_path_periph(ccb->ccb_h.path);
1271 	softc = (struct cd_softc *)periph->softc;
1272 
1273 	error = cam_periph_runccb(ccb, error_routine, cam_flags, sense_flags,
1274 				  &softc->device_stats);
1275 
1276 	if (softc->flags & CD_FLAG_CHANGER)
1277 		cdchangerschedule(softc);
1278 
1279 	return(error);
1280 }
1281 
1282 static union ccb *
1283 cdgetccb(struct cam_periph *periph, u_int32_t priority)
1284 {
1285 	struct cd_softc *softc;
1286 	int s;
1287 
1288 	softc = (struct cd_softc *)periph->softc;
1289 
1290 	if (softc->flags & CD_FLAG_CHANGER) {
1291 
1292 		s = splsoftcam();
1293 
1294 		/*
1295 		 * This should work the first time this device is woken up,
1296 		 * but just in case it doesn't, we use a while loop.
1297 		 */
1298 		while ((softc->flags & CD_FLAG_ACTIVE) == 0) {
1299 			/*
1300 			 * If this changer isn't already queued, queue it up.
1301 			 */
1302 			if (softc->pinfo.index == CAM_UNQUEUED_INDEX) {
1303 				softc->pinfo.priority = 1;
1304 				softc->pinfo.generation =
1305 					++softc->changer->devq.generation;
1306 				camq_insert(&softc->changer->devq,
1307 					    (cam_pinfo *)softc);
1308 			}
1309 			if (((softc->changer->flags & CHANGER_TIMEOUT_SCHED)==0)
1310 			 && ((softc->changer->flags & CHANGER_NEED_TIMEOUT)==0)
1311 			 && ((softc->changer->flags
1312 			      & CHANGER_SHORT_TMOUT_SCHED)==0)) {
1313 				softc->changer->flags |= CHANGER_MANUAL_CALL;
1314 				cdrunchangerqueue(softc->changer);
1315 			} else
1316 				tsleep(&softc->changer, PRIBIO, "cgticb", 0);
1317 		}
1318 		splx(s);
1319 	}
1320 	return(cam_periph_getccb(periph, priority));
1321 }
1322 
1323 
1324 /*
1325  * Actually translate the requested transfer into one the physical driver
1326  * can understand.  The transfer is described by a buf and will include
1327  * only one physical transfer.
1328  */
1329 static void
1330 cdstrategy(struct buf *bp)
1331 {
1332 	struct cam_periph *periph;
1333 	struct cd_softc *softc;
1334 	u_int  unit, part;
1335 	int    s;
1336 
1337 	unit = dkunit(bp->b_dev);
1338 	part = dkpart(bp->b_dev);
1339 	periph = cam_extend_get(cdperiphs, unit);
1340 	if (periph == NULL) {
1341 		bp->b_error = ENXIO;
1342 		goto bad;
1343 	}
1344 
1345 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdstrategy\n"));
1346 
1347 	softc = (struct cd_softc *)periph->softc;
1348 
1349 	/*
1350 	 * Mask interrupts so that the pack cannot be invalidated until
1351 	 * after we are in the queue.  Otherwise, we might not properly
1352 	 * clean up one of the buffers.
1353 	 */
1354 	s = splbio();
1355 
1356 	/*
1357 	 * If the device has been made invalid, error out
1358 	 */
1359 	if ((softc->flags & CD_FLAG_INVALID)) {
1360 		splx(s);
1361 		bp->b_error = ENXIO;
1362 		goto bad;
1363 	}
1364 
1365 	/*
1366 	 * Place it in the queue of disk activities for this disk
1367 	 */
1368 	bufqdisksort(&softc->buf_queue, bp);
1369 
1370 	splx(s);
1371 
1372 	/*
1373 	 * Schedule ourselves for performing the work.  We do things
1374 	 * differently for changers.
1375 	 */
1376 	if ((softc->flags & CD_FLAG_CHANGER) == 0)
1377 		xpt_schedule(periph, /* XXX priority */1);
1378 	else
1379 		cdschedule(periph, /* priority */ 1);
1380 
1381 	return;
1382 bad:
1383 	bp->b_flags |= B_ERROR;
1384 	/*
1385 	 * Correctly set the buf to indicate a completed xfer
1386 	 */
1387 	bp->b_resid = bp->b_bcount;
1388 	biodone(bp);
1389 	return;
1390 }
1391 
1392 static void
1393 cdstart(struct cam_periph *periph, union ccb *start_ccb)
1394 {
1395 	struct cd_softc *softc;
1396 	struct buf *bp;
1397 	struct ccb_scsiio *csio;
1398 	struct scsi_read_capacity_data *rcap;
1399 	int s;
1400 
1401 	softc = (struct cd_softc *)periph->softc;
1402 
1403 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdstart\n"));
1404 
1405 	switch (softc->state) {
1406 	case CD_STATE_NORMAL:
1407 	{
1408 		int oldspl;
1409 
1410 		s = splbio();
1411 		bp = bufq_first(&softc->buf_queue);
1412 		if (periph->immediate_priority <= periph->pinfo.priority) {
1413 			start_ccb->ccb_h.ccb_state = CD_CCB_WAITING;
1414 
1415 			SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1416 					  periph_links.sle);
1417 			periph->immediate_priority = CAM_PRIORITY_NONE;
1418 			splx(s);
1419 			wakeup(&periph->ccb_list);
1420 		} else if (bp == NULL) {
1421 			splx(s);
1422 			xpt_release_ccb(start_ccb);
1423 		} else {
1424 			bufq_remove(&softc->buf_queue, bp);
1425 
1426 			devstat_start_transaction(&softc->device_stats);
1427 
1428 			scsi_read_write(&start_ccb->csio,
1429 					/*retries*/4,
1430 					/* cbfcnp */ cddone,
1431 					(bp->b_flags & B_ORDERED) != 0 ?
1432 					    MSG_ORDERED_Q_TAG :
1433 					    MSG_SIMPLE_Q_TAG,
1434 					/* read */bp->b_flags & B_READ,
1435 					/* byte2 */ 0,
1436 					/* minimum_cmd_size */ 10,
1437 					/* lba */ bp->b_pblkno,
1438 					bp->b_bcount / softc->params.blksize,
1439 					/* data_ptr */ bp->b_data,
1440 					/* dxfer_len */ bp->b_bcount,
1441 					/* sense_len */ SSD_FULL_SIZE,
1442 					/* timeout */ 30000);
1443 			start_ccb->ccb_h.ccb_state = CD_CCB_BUFFER_IO;
1444 
1445 
1446 			/*
1447 			 * Block out any asyncronous callbacks
1448 			 * while we touch the pending ccb list.
1449 			 */
1450 			oldspl = splcam();
1451 			LIST_INSERT_HEAD(&softc->pending_ccbs,
1452 					 &start_ccb->ccb_h, periph_links.le);
1453 			splx(oldspl);
1454 
1455 			/* We expect a unit attention from this device */
1456 			if ((softc->flags & CD_FLAG_RETRY_UA) != 0) {
1457 				start_ccb->ccb_h.ccb_state |= CD_CCB_RETRY_UA;
1458 				softc->flags &= ~CD_FLAG_RETRY_UA;
1459 			}
1460 
1461 			start_ccb->ccb_h.ccb_bp = bp;
1462 			bp = bufq_first(&softc->buf_queue);
1463 			splx(s);
1464 
1465 			xpt_action(start_ccb);
1466 		}
1467 		if (bp != NULL) {
1468 			/* Have more work to do, so ensure we stay scheduled */
1469 			xpt_schedule(periph, /* XXX priority */1);
1470 		}
1471 		break;
1472 	}
1473 	case CD_STATE_PROBE:
1474 	{
1475 
1476 		rcap = (struct scsi_read_capacity_data *)malloc(sizeof(*rcap),
1477 								M_TEMP,
1478 								M_NOWAIT);
1479 		if (rcap == NULL) {
1480 			xpt_print_path(periph->path);
1481 			printf("cdstart: Couldn't malloc read_capacity data\n");
1482 			/* cd_free_periph??? */
1483 			break;
1484 		}
1485 		csio = &start_ccb->csio;
1486 		scsi_read_capacity(csio,
1487 				   /*retries*/1,
1488 				   cddone,
1489 				   MSG_SIMPLE_Q_TAG,
1490 				   rcap,
1491 				   SSD_FULL_SIZE,
1492 				   /*timeout*/20000);
1493 		start_ccb->ccb_h.ccb_bp = NULL;
1494 		start_ccb->ccb_h.ccb_state = CD_CCB_PROBE;
1495 		xpt_action(start_ccb);
1496 		break;
1497 	}
1498 	}
1499 }
1500 
1501 static void
1502 cddone(struct cam_periph *periph, union ccb *done_ccb)
1503 {
1504 	struct cd_softc *softc;
1505 	struct ccb_scsiio *csio;
1506 
1507 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cddone\n"));
1508 
1509 	softc = (struct cd_softc *)periph->softc;
1510 	csio = &done_ccb->csio;
1511 
1512 	switch (csio->ccb_h.ccb_state & CD_CCB_TYPE_MASK) {
1513 	case CD_CCB_BUFFER_IO:
1514 	{
1515 		struct buf	*bp;
1516 		int		error;
1517 		int		oldspl;
1518 
1519 		bp = (struct buf *)done_ccb->ccb_h.ccb_bp;
1520 		error = 0;
1521 
1522 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1523 			int sf;
1524 
1525 			if ((done_ccb->ccb_h.ccb_state & CD_CCB_RETRY_UA) != 0)
1526 				sf = SF_RETRY_UA;
1527 			else
1528 				sf = 0;
1529 
1530 			/* Retry selection timeouts */
1531 			sf |= SF_RETRY_SELTO;
1532 
1533 			if ((error = cderror(done_ccb, 0, sf)) == ERESTART) {
1534 				/*
1535 				 * A retry was scheuled, so
1536 				 * just return.
1537 				 */
1538 				return;
1539 			}
1540 		}
1541 
1542 		if (error != 0) {
1543 			int s;
1544 			struct buf *q_bp;
1545 
1546 			xpt_print_path(periph->path);
1547 			printf("cddone: got error %#x back\n", error);
1548 			s = splbio();
1549 			while ((q_bp = bufq_first(&softc->buf_queue)) != NULL) {
1550 				bufq_remove(&softc->buf_queue, q_bp);
1551 				q_bp->b_resid = q_bp->b_bcount;
1552 				q_bp->b_error = EIO;
1553 				q_bp->b_flags |= B_ERROR;
1554 				biodone(q_bp);
1555 			}
1556 			splx(s);
1557 			bp->b_resid = bp->b_bcount;
1558 			bp->b_error = error;
1559 			bp->b_flags |= B_ERROR;
1560 			cam_release_devq(done_ccb->ccb_h.path,
1561 					 /*relsim_flags*/0,
1562 					 /*reduction*/0,
1563 					 /*timeout*/0,
1564 					 /*getcount_only*/0);
1565 
1566 		} else {
1567 			bp->b_resid = csio->resid;
1568 			bp->b_error = 0;
1569 			if (bp->b_resid != 0) {
1570 				/* Short transfer ??? */
1571 				bp->b_flags |= B_ERROR;
1572 			}
1573 		}
1574 
1575 		/*
1576 		 * Block out any asyncronous callbacks
1577 		 * while we touch the pending ccb list.
1578 		 */
1579 		oldspl = splcam();
1580 		LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
1581 		splx(oldspl);
1582 
1583 		if (softc->flags & CD_FLAG_CHANGER)
1584 			cdchangerschedule(softc);
1585 
1586 		devstat_end_transaction_buf(&softc->device_stats, bp);
1587 		biodone(bp);
1588 		break;
1589 	}
1590 	case CD_CCB_PROBE:
1591 	{
1592 		struct	   scsi_read_capacity_data *rdcap;
1593 		char	   announce_buf[120]; /*
1594 					       * Currently (9/30/97) the
1595 					       * longest possible announce
1596 					       * buffer is 108 bytes, for the
1597 					       * first error case below.
1598 					       * That is 39 bytes for the
1599 					       * basic string, 16 bytes for the
1600 					       * biggest sense key (hardware
1601 					       * error), 52 bytes for the
1602 					       * text of the largest sense
1603 					       * qualifier valid for a CDROM,
1604 					       * (0x72, 0x03 or 0x04,
1605 					       * 0x03), and one byte for the
1606 					       * null terminating character.
1607 					       * To allow for longer strings,
1608 					       * the announce buffer is 120
1609 					       * bytes.
1610 					       */
1611 		struct	   cd_params *cdp;
1612 
1613 		cdp = &softc->params;
1614 
1615 		rdcap = (struct scsi_read_capacity_data *)csio->data_ptr;
1616 
1617 		cdp->disksize = scsi_4btoul (rdcap->addr) + 1;
1618 		cdp->blksize = scsi_4btoul (rdcap->length);
1619 
1620 		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1621 
1622 			snprintf(announce_buf, sizeof(announce_buf),
1623 				"cd present [%lu x %lu byte records]",
1624 				cdp->disksize, (u_long)cdp->blksize);
1625 
1626 		} else {
1627 			int	error;
1628 			/*
1629 			 * Retry any UNIT ATTENTION type errors.  They
1630 			 * are expected at boot.
1631 			 */
1632 			error = cderror(done_ccb, 0, SF_RETRY_UA |
1633 					SF_NO_PRINT | SF_RETRY_SELTO);
1634 			if (error == ERESTART) {
1635 				/*
1636 				 * A retry was scheuled, so
1637 				 * just return.
1638 				 */
1639 				return;
1640 			} else if (error != 0) {
1641 
1642 				struct scsi_sense_data *sense;
1643 				int asc, ascq;
1644 				int sense_key, error_code;
1645 				int have_sense;
1646 				cam_status status;
1647 				struct ccb_getdev cgd;
1648 
1649 				/* Don't wedge this device's queue */
1650 				cam_release_devq(done_ccb->ccb_h.path,
1651 						 /*relsim_flags*/0,
1652 						 /*reduction*/0,
1653 						 /*timeout*/0,
1654 						 /*getcount_only*/0);
1655 
1656 				status = done_ccb->ccb_h.status;
1657 
1658 				xpt_setup_ccb(&cgd.ccb_h,
1659 					      done_ccb->ccb_h.path,
1660 					      /* priority */ 1);
1661 				cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1662 				xpt_action((union ccb *)&cgd);
1663 
1664 				if (((csio->ccb_h.flags & CAM_SENSE_PHYS) != 0)
1665 				 || ((csio->ccb_h.flags & CAM_SENSE_PTR) != 0)
1666 				 || ((status & CAM_AUTOSNS_VALID) == 0))
1667 					have_sense = FALSE;
1668 				else
1669 					have_sense = TRUE;
1670 
1671 				if (have_sense) {
1672 					sense = &csio->sense_data;
1673 					scsi_extract_sense(sense, &error_code,
1674 							   &sense_key,
1675 							   &asc, &ascq);
1676 				}
1677 				/*
1678 				 * Attach to anything that claims to be a
1679 				 * CDROM or WORM device, as long as it
1680 				 * doesn't return a "Logical unit not
1681 				 * supported" (0x25) error.
1682 				 */
1683 				if ((have_sense) && (asc != 0x25)
1684 				 && (error_code == SSD_CURRENT_ERROR))
1685 					snprintf(announce_buf,
1686 					    sizeof(announce_buf),
1687 						"Attempt to query device "
1688 						"size failed: %s, %s",
1689 						scsi_sense_key_text[sense_key],
1690 						scsi_sense_desc(asc,ascq,
1691 								&cgd.inq_data));
1692 				else if (cgd.pd_type == T_CDROM) {
1693 					/*
1694 					 * We only print out an error for
1695 					 * CDROM type devices.  For WORM
1696 					 * devices, we don't print out an
1697 					 * error since a few WORM devices
1698 					 * don't support CDROM commands.
1699 					 * If we have sense information, go
1700 					 * ahead and print it out.
1701 					 * Otherwise, just say that we
1702 					 * couldn't attach.
1703 					 */
1704 
1705 					/*
1706 					 * Just print out the error, not
1707 					 * the full probe message, when we
1708 					 * don't attach.
1709 					 */
1710 					if (have_sense)
1711 						scsi_sense_print(
1712 							&done_ccb->csio);
1713 					else {
1714 						xpt_print_path(periph->path);
1715 						printf("got CAM status %#x\n",
1716 						       done_ccb->ccb_h.status);
1717 					}
1718 					xpt_print_path(periph->path);
1719 					printf("fatal error, failed"
1720 					       " to attach to device\n");
1721 
1722 					/*
1723 					 * Invalidate this peripheral.
1724 					 */
1725 					cam_periph_invalidate(periph);
1726 
1727 					announce_buf[0] = '\0';
1728 				} else {
1729 
1730 					/*
1731 					 * Invalidate this peripheral.
1732 					 */
1733 					cam_periph_invalidate(periph);
1734 					announce_buf[0] = '\0';
1735 				}
1736 			}
1737 		}
1738 		free(rdcap, M_TEMP);
1739 		if (announce_buf[0] != '\0') {
1740 			xpt_announce_periph(periph, announce_buf);
1741 			if (softc->flags & CD_FLAG_CHANGER)
1742 				cdchangerschedule(softc);
1743 		}
1744 		softc->state = CD_STATE_NORMAL;
1745 		/*
1746 		 * Since our peripheral may be invalidated by an error
1747 		 * above or an external event, we must release our CCB
1748 		 * before releasing the probe lock on the peripheral.
1749 		 * The peripheral will only go away once the last lock
1750 		 * is removed, and we need it around for the CCB release
1751 		 * operation.
1752 		 */
1753 		xpt_release_ccb(done_ccb);
1754 		cam_periph_unlock(periph);
1755 		return;
1756 	}
1757 	case CD_CCB_WAITING:
1758 	{
1759 		/* Caller will release the CCB */
1760 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1761 			  ("trying to wakeup ccbwait\n"));
1762 
1763 		wakeup(&done_ccb->ccb_h.cbfcnp);
1764 		return;
1765 	}
1766 	default:
1767 		break;
1768 	}
1769 	xpt_release_ccb(done_ccb);
1770 }
1771 
1772 static int
1773 cdioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
1774 {
1775 
1776 	struct 	cam_periph *periph;
1777 	struct	cd_softc *softc;
1778 	int	error, unit;
1779 
1780 	unit = dkunit(dev);
1781 
1782 	periph = cam_extend_get(cdperiphs, unit);
1783 	if (periph == NULL)
1784 		return(ENXIO);
1785 
1786 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdioctl\n"));
1787 
1788 	softc = (struct cd_softc *)periph->softc;
1789 
1790 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1791 		  ("trying to do ioctl %#lx\n", cmd));
1792 
1793 	error = cam_periph_lock(periph, PRIBIO | PCATCH);
1794 
1795 	if (error != 0)
1796 		return(error);
1797 
1798 	switch (cmd) {
1799 
1800 	case CDIOCPLAYTRACKS:
1801 		{
1802 			struct ioc_play_track *args
1803 			    = (struct ioc_play_track *) addr;
1804 			struct cd_mode_data *data;
1805 
1806 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
1807 				      M_WAITOK);
1808 
1809 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1810 				  ("trying to do CDIOCPLAYTRACKS\n"));
1811 
1812 			error = cdgetmode(periph, data, AUDIO_PAGE);
1813 			if (error) {
1814 				free(data, M_TEMP);
1815 				break;
1816 			}
1817 			data->page.audio.flags &= ~CD_PA_SOTC;
1818 			data->page.audio.flags |= CD_PA_IMMED;
1819 			error = cdsetmode(periph, data);
1820 			free(data, M_TEMP);
1821 			if (error)
1822 				break;
1823 			if (softc->quirks & CD_Q_BCD_TRACKS) {
1824 				args->start_track = bin2bcd(args->start_track);
1825 				args->end_track = bin2bcd(args->end_track);
1826 			}
1827 			error = cdplaytracks(periph,
1828 					     args->start_track,
1829 					     args->start_index,
1830 					     args->end_track,
1831 					     args->end_index);
1832 		}
1833 		break;
1834 	case CDIOCPLAYMSF:
1835 		{
1836 			struct ioc_play_msf *args
1837 				= (struct ioc_play_msf *) addr;
1838 			struct cd_mode_data *data;
1839 
1840 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
1841 				      M_WAITOK);
1842 
1843 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1844 				  ("trying to do CDIOCPLAYMSF\n"));
1845 
1846 			error = cdgetmode(periph, data, AUDIO_PAGE);
1847 			if (error) {
1848 				free(data, M_TEMP);
1849 				break;
1850 			}
1851 			data->page.audio.flags &= ~CD_PA_SOTC;
1852 			data->page.audio.flags |= CD_PA_IMMED;
1853 			error = cdsetmode(periph, data);
1854 			free(data, M_TEMP);
1855 			if (error)
1856 				break;
1857 			error = cdplaymsf(periph,
1858 					  args->start_m,
1859 					  args->start_s,
1860 					  args->start_f,
1861 					  args->end_m,
1862 					  args->end_s,
1863 					  args->end_f);
1864 		}
1865 		break;
1866 	case CDIOCPLAYBLOCKS:
1867 		{
1868 			struct ioc_play_blocks *args
1869 				= (struct ioc_play_blocks *) addr;
1870 			struct cd_mode_data *data;
1871 
1872 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1873 				  ("trying to do CDIOCPLAYBLOCKS\n"));
1874 
1875 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
1876 				      M_WAITOK);
1877 
1878 			error = cdgetmode(periph, data, AUDIO_PAGE);
1879 			if (error) {
1880 				free(data, M_TEMP);
1881 				break;
1882 			}
1883 			data->page.audio.flags &= ~CD_PA_SOTC;
1884 			data->page.audio.flags |= CD_PA_IMMED;
1885 			error = cdsetmode(periph, data);
1886 			free(data, M_TEMP);
1887 			if (error)
1888 				break;
1889 			error = cdplay(periph, args->blk, args->len);
1890 		}
1891 		break;
1892 	case CDIOCREADSUBCHANNEL:
1893 		{
1894 			struct ioc_read_subchannel *args
1895 				= (struct ioc_read_subchannel *) addr;
1896 			struct cd_sub_channel_info *data;
1897 			u_int32_t len = args->data_len;
1898 
1899 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1900 				  ("trying to do CDIOCREADSUBCHANNEL\n"));
1901 
1902 			data = malloc(sizeof(struct cd_sub_channel_info),
1903 				      M_TEMP, M_WAITOK);
1904 
1905 			if ((len > sizeof(struct cd_sub_channel_info)) ||
1906 			    (len < sizeof(struct cd_sub_channel_header))) {
1907 				printf(
1908 					"scsi_cd: cdioctl: "
1909 					"cdioreadsubchannel: error, len=%d\n",
1910 					len);
1911 				error = EINVAL;
1912 				free(data, M_TEMP);
1913 				break;
1914 			}
1915 
1916 			if (softc->quirks & CD_Q_BCD_TRACKS)
1917 				args->track = bin2bcd(args->track);
1918 
1919 			error = cdreadsubchannel(periph, args->address_format,
1920 				args->data_format, args->track, data, len);
1921 
1922 			if (error) {
1923 				free(data, M_TEMP);
1924 	 			break;
1925 			}
1926 			if (softc->quirks & CD_Q_BCD_TRACKS)
1927 				data->what.track_info.track_number =
1928 				    bcd2bin(data->what.track_info.track_number);
1929 			len = min(len, ((data->header.data_len[0] << 8) +
1930 				data->header.data_len[1] +
1931 				sizeof(struct cd_sub_channel_header)));
1932 			if (copyout(data, args->data, len) != 0) {
1933 				error = EFAULT;
1934 			}
1935 			free(data, M_TEMP);
1936 		}
1937 		break;
1938 
1939 	case CDIOREADTOCHEADER:
1940 		{
1941 			struct ioc_toc_header *th;
1942 
1943 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1944 				  ("trying to do CDIOREADTOCHEADER\n"));
1945 
1946 			th = malloc(sizeof(struct ioc_toc_header), M_TEMP,
1947 				    M_WAITOK);
1948 			error = cdreadtoc(periph, 0, 0,
1949 					  (struct cd_toc_entry *)th,
1950 				          sizeof (*th));
1951 			if (error) {
1952 				free(th, M_TEMP);
1953 				break;
1954 			}
1955 			if (softc->quirks & CD_Q_BCD_TRACKS) {
1956 				/* we are going to have to convert the BCD
1957 				 * encoding on the cd to what is expected
1958 				 */
1959 				th->starting_track =
1960 					bcd2bin(th->starting_track);
1961 				th->ending_track = bcd2bin(th->ending_track);
1962 			}
1963 			NTOHS(th->len);
1964 			bcopy(th, addr, sizeof(*th));
1965 			free(th, M_TEMP);
1966 		}
1967 		break;
1968 	case CDIOREADTOCENTRYS:
1969 		{
1970 			typedef struct {
1971 				struct ioc_toc_header header;
1972 				struct cd_toc_entry entries[100];
1973 			} data_t;
1974 			typedef struct {
1975 				struct ioc_toc_header header;
1976 				struct cd_toc_entry entry;
1977 			} lead_t;
1978 
1979 			data_t *data;
1980 			lead_t *lead;
1981 			struct ioc_read_toc_entry *te =
1982 				(struct ioc_read_toc_entry *) addr;
1983 			struct ioc_toc_header *th;
1984 			u_int32_t len, readlen, idx, num;
1985 			u_int32_t starting_track = te->starting_track;
1986 
1987 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1988 				  ("trying to do CDIOREADTOCENTRYS\n"));
1989 
1990 			data = malloc(sizeof(data_t), M_TEMP, M_WAITOK);
1991 			lead = malloc(sizeof(lead_t), M_TEMP, M_WAITOK);
1992 
1993 			if (te->data_len < sizeof(struct cd_toc_entry)
1994 			 || (te->data_len % sizeof(struct cd_toc_entry)) != 0
1995 			 || (te->address_format != CD_MSF_FORMAT
1996 			  && te->address_format != CD_LBA_FORMAT)) {
1997 				error = EINVAL;
1998 				printf("scsi_cd: error in readtocentries, "
1999 				       "returning EINVAL\n");
2000 				free(data, M_TEMP);
2001 				free(lead, M_TEMP);
2002 				break;
2003 			}
2004 
2005 			th = &data->header;
2006 			error = cdreadtoc(periph, 0, 0,
2007 					  (struct cd_toc_entry *)th,
2008 					  sizeof (*th));
2009 			if (error) {
2010 				free(data, M_TEMP);
2011 				free(lead, M_TEMP);
2012 				break;
2013 			}
2014 
2015 			if (softc->quirks & CD_Q_BCD_TRACKS) {
2016 				/* we are going to have to convert the BCD
2017 				 * encoding on the cd to what is expected
2018 				 */
2019 				th->starting_track =
2020 				    bcd2bin(th->starting_track);
2021 				th->ending_track = bcd2bin(th->ending_track);
2022 			}
2023 
2024 			if (starting_track == 0)
2025 				starting_track = th->starting_track;
2026 			else if (starting_track == LEADOUT)
2027 				starting_track = th->ending_track + 1;
2028 			else if (starting_track < th->starting_track ||
2029 				 starting_track > th->ending_track + 1) {
2030 				printf("scsi_cd: error in readtocentries, "
2031 				       "returning EINVAL\n");
2032 				free(data, M_TEMP);
2033 				free(lead, M_TEMP);
2034 				error = EINVAL;
2035 				break;
2036 			}
2037 
2038 			/* calculate reading length without leadout entry */
2039 			readlen = (th->ending_track - starting_track + 1) *
2040 				  sizeof(struct cd_toc_entry);
2041 
2042 			/* and with leadout entry */
2043 			len = readlen + sizeof(struct cd_toc_entry);
2044 			if (te->data_len < len) {
2045 				len = te->data_len;
2046 				if (readlen > len)
2047 					readlen = len;
2048 			}
2049 			if (len > sizeof(data->entries)) {
2050 				printf("scsi_cd: error in readtocentries, "
2051 				       "returning EINVAL\n");
2052 				error = EINVAL;
2053 				free(data, M_TEMP);
2054 				free(lead, M_TEMP);
2055 				break;
2056 			}
2057 			num = len / sizeof(struct cd_toc_entry);
2058 
2059 			if (readlen > 0) {
2060 				error = cdreadtoc(periph, te->address_format,
2061 						  starting_track,
2062 						  (struct cd_toc_entry *)data,
2063 						  readlen + sizeof (*th));
2064 				if (error) {
2065 					free(data, M_TEMP);
2066 					free(lead, M_TEMP);
2067 					break;
2068 				}
2069 			}
2070 
2071 			/* make leadout entry if needed */
2072 			idx = starting_track + num - 1;
2073 			if (softc->quirks & CD_Q_BCD_TRACKS)
2074 				th->ending_track = bcd2bin(th->ending_track);
2075 			if (idx == th->ending_track + 1) {
2076 				error = cdreadtoc(periph, te->address_format,
2077 						  LEADOUT,
2078 						  (struct cd_toc_entry *)lead,
2079 						  sizeof(*lead));
2080 				if (error) {
2081 					free(data, M_TEMP);
2082 					free(lead, M_TEMP);
2083 					break;
2084 				}
2085 				data->entries[idx - starting_track] =
2086 					lead->entry;
2087 			}
2088 			if (softc->quirks & CD_Q_BCD_TRACKS) {
2089 				for (idx = 0; idx < num - 1; idx++) {
2090 					data->entries[idx].track =
2091 					    bcd2bin(data->entries[idx].track);
2092 				}
2093 			}
2094 
2095 			error = copyout(data->entries, te->data, len);
2096 			free(data, M_TEMP);
2097 			free(lead, M_TEMP);
2098 		}
2099 		break;
2100 	case CDIOREADTOCENTRY:
2101 		{
2102 			/* yeah yeah, this is ugly */
2103 			typedef struct {
2104 				struct ioc_toc_header header;
2105 				struct cd_toc_entry entry;
2106 			} data_t;
2107 
2108 			data_t *data;
2109 			struct ioc_read_toc_single_entry *te =
2110 				(struct ioc_read_toc_single_entry *) addr;
2111 			struct ioc_toc_header *th;
2112 			u_int32_t track;
2113 
2114 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2115 				  ("trying to do CDIOREADTOCENTRY\n"));
2116 
2117 			data = malloc(sizeof(data_t), M_TEMP, M_WAITOK);
2118 
2119 			if (te->address_format != CD_MSF_FORMAT
2120 			    && te->address_format != CD_LBA_FORMAT) {
2121 				printf("error in readtocentry, "
2122 				       " returning EINVAL\n");
2123 				free(data, M_TEMP);
2124 				error = EINVAL;
2125 				break;
2126 			}
2127 
2128 			th = &data->header;
2129 			error = cdreadtoc(periph, 0, 0,
2130 					  (struct cd_toc_entry *)th,
2131 					  sizeof (*th));
2132 			if (error) {
2133 				free(data, M_TEMP);
2134 				break;
2135 			}
2136 
2137 			if (softc->quirks & CD_Q_BCD_TRACKS) {
2138 				/* we are going to have to convert the BCD
2139 				 * encoding on the cd to what is expected
2140 				 */
2141 				th->starting_track =
2142 				    bcd2bin(th->starting_track);
2143 				th->ending_track = bcd2bin(th->ending_track);
2144 			}
2145 			track = te->track;
2146 			if (track == 0)
2147 				track = th->starting_track;
2148 			else if (track == LEADOUT)
2149 				/* OK */;
2150 			else if (track < th->starting_track ||
2151 				 track > th->ending_track + 1) {
2152 				printf("error in readtocentry, "
2153 				       " returning EINVAL\n");
2154 				free(data, M_TEMP);
2155 				error = EINVAL;
2156 				break;
2157 			}
2158 
2159 			error = cdreadtoc(periph, te->address_format, track,
2160 					  (struct cd_toc_entry *)data,
2161 					  sizeof(data_t));
2162 			if (error) {
2163 				free(data, M_TEMP);
2164 				break;
2165 			}
2166 
2167 			if (softc->quirks & CD_Q_BCD_TRACKS)
2168 				data->entry.track = bcd2bin(data->entry.track);
2169 			bcopy(&data->entry, &te->entry,
2170 			      sizeof(struct cd_toc_entry));
2171 			free(data, M_TEMP);
2172 		}
2173 		break;
2174 	case CDIOCSETPATCH:
2175 		{
2176 			struct ioc_patch *arg = (struct ioc_patch *) addr;
2177 			struct cd_mode_data *data;
2178 
2179 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2180 				  ("trying to do CDIOCSETPATCH\n"));
2181 
2182 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2183 				      M_WAITOK);
2184 			error = cdgetmode(periph, data, AUDIO_PAGE);
2185 			if (error) {
2186 				free(data, M_TEMP);
2187 				break;
2188 			}
2189 			data->page.audio.port[LEFT_PORT].channels =
2190 				arg->patch[0];
2191 			data->page.audio.port[RIGHT_PORT].channels =
2192 				arg->patch[1];
2193 			data->page.audio.port[2].channels = arg->patch[2];
2194 			data->page.audio.port[3].channels = arg->patch[3];
2195 			error = cdsetmode(periph, data);
2196 			free(data, M_TEMP);
2197 		}
2198 		break;
2199 	case CDIOCGETVOL:
2200 		{
2201 			struct ioc_vol *arg = (struct ioc_vol *) addr;
2202 			struct cd_mode_data *data;
2203 
2204 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2205 				  ("trying to do CDIOCGETVOL\n"));
2206 
2207 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2208 				      M_WAITOK);
2209 			error = cdgetmode(periph, data, AUDIO_PAGE);
2210 			if (error) {
2211 				free(data, M_TEMP);
2212 				break;
2213 			}
2214 			arg->vol[LEFT_PORT] =
2215 				data->page.audio.port[LEFT_PORT].volume;
2216 			arg->vol[RIGHT_PORT] =
2217 				data->page.audio.port[RIGHT_PORT].volume;
2218 			arg->vol[2] = data->page.audio.port[2].volume;
2219 			arg->vol[3] = data->page.audio.port[3].volume;
2220 			free(data, M_TEMP);
2221 		}
2222 		break;
2223 	case CDIOCSETVOL:
2224 		{
2225 			struct ioc_vol *arg = (struct ioc_vol *) addr;
2226 			struct cd_mode_data *data;
2227 
2228 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2229 				  ("trying to do CDIOCSETVOL\n"));
2230 
2231 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2232 				      M_WAITOK);
2233 			error = cdgetmode(periph, data, AUDIO_PAGE);
2234 			if (error) {
2235 				free(data, M_TEMP);
2236 				break;
2237 			}
2238 			data->page.audio.port[LEFT_PORT].channels = CHANNEL_0;
2239 			data->page.audio.port[LEFT_PORT].volume =
2240 				arg->vol[LEFT_PORT];
2241 			data->page.audio.port[RIGHT_PORT].channels = CHANNEL_1;
2242 			data->page.audio.port[RIGHT_PORT].volume =
2243 				arg->vol[RIGHT_PORT];
2244 			data->page.audio.port[2].volume = arg->vol[2];
2245 			data->page.audio.port[3].volume = arg->vol[3];
2246 			error = cdsetmode(periph, data);
2247 			free(data, M_TEMP);
2248 		}
2249 		break;
2250 	case CDIOCSETMONO:
2251 		{
2252 			struct cd_mode_data *data;
2253 
2254 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2255 				  ("trying to do CDIOCSETMONO\n"));
2256 
2257 			data = malloc(sizeof(struct cd_mode_data),
2258 				      M_TEMP, M_WAITOK);
2259 			error = cdgetmode(periph, data, AUDIO_PAGE);
2260 			if (error) {
2261 				free(data, M_TEMP);
2262 				break;
2263 			}
2264 			data->page.audio.port[LEFT_PORT].channels =
2265 				LEFT_CHANNEL | RIGHT_CHANNEL;
2266 			data->page.audio.port[RIGHT_PORT].channels =
2267 				LEFT_CHANNEL | RIGHT_CHANNEL;
2268 			data->page.audio.port[2].channels = 0;
2269 			data->page.audio.port[3].channels = 0;
2270 			error = cdsetmode(periph, data);
2271 			free(data, M_TEMP);
2272 		}
2273 		break;
2274 	case CDIOCSETSTEREO:
2275 		{
2276 			struct cd_mode_data *data;
2277 
2278 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2279 				  ("trying to do CDIOCSETSTEREO\n"));
2280 
2281 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2282 				      M_WAITOK);
2283 			error = cdgetmode(periph, data, AUDIO_PAGE);
2284 			if (error) {
2285 				free(data, M_TEMP);
2286 				break;
2287 			}
2288 			data->page.audio.port[LEFT_PORT].channels =
2289 				LEFT_CHANNEL;
2290 			data->page.audio.port[RIGHT_PORT].channels =
2291 				RIGHT_CHANNEL;
2292 			data->page.audio.port[2].channels = 0;
2293 			data->page.audio.port[3].channels = 0;
2294 			error = cdsetmode(periph, data);
2295 			free(data, M_TEMP);
2296 		}
2297 		break;
2298 	case CDIOCSETMUTE:
2299 		{
2300 			struct cd_mode_data *data;
2301 
2302 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2303 				  ("trying to do CDIOCSETMUTE\n"));
2304 
2305 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2306 				      M_WAITOK);
2307 			error = cdgetmode(periph, data, AUDIO_PAGE);
2308 			if (error) {
2309 				free(data, M_TEMP);
2310 				break;
2311 			}
2312 			data->page.audio.port[LEFT_PORT].channels = 0;
2313 			data->page.audio.port[RIGHT_PORT].channels = 0;
2314 			data->page.audio.port[2].channels = 0;
2315 			data->page.audio.port[3].channels = 0;
2316 			error = cdsetmode(periph, data);
2317 			free(data, M_TEMP);
2318 		}
2319 		break;
2320 	case CDIOCSETLEFT:
2321 		{
2322 			struct cd_mode_data *data;
2323 
2324 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2325 				  ("trying to do CDIOCSETLEFT\n"));
2326 
2327 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2328 				      M_WAITOK);
2329 			error = cdgetmode(periph, data, AUDIO_PAGE);
2330 			if (error) {
2331 				free(data, M_TEMP);
2332 				break;
2333 			}
2334 			data->page.audio.port[LEFT_PORT].channels =
2335 				LEFT_CHANNEL;
2336 			data->page.audio.port[RIGHT_PORT].channels =
2337 				LEFT_CHANNEL;
2338 			data->page.audio.port[2].channels = 0;
2339 			data->page.audio.port[3].channels = 0;
2340 			error = cdsetmode(periph, data);
2341 			free(data, M_TEMP);
2342 		}
2343 		break;
2344 	case CDIOCSETRIGHT:
2345 		{
2346 			struct cd_mode_data *data;
2347 
2348 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2349 				  ("trying to do CDIOCSETRIGHT\n"));
2350 
2351 			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2352 				      M_WAITOK);
2353 			error = cdgetmode(periph, data, AUDIO_PAGE);
2354 			if (error) {
2355 				free(data, M_TEMP);
2356 				break;
2357 			}
2358 			data->page.audio.port[LEFT_PORT].channels =
2359 				RIGHT_CHANNEL;
2360 			data->page.audio.port[RIGHT_PORT].channels =
2361 				RIGHT_CHANNEL;
2362 			data->page.audio.port[2].channels = 0;
2363 			data->page.audio.port[3].channels = 0;
2364 			error = cdsetmode(periph, data);
2365 			free(data, M_TEMP);
2366 		}
2367 		break;
2368 	case CDIOCRESUME:
2369 		error = cdpause(periph, 1);
2370 		break;
2371 	case CDIOCPAUSE:
2372 		error = cdpause(periph, 0);
2373 		break;
2374 	case CDIOCSTART:
2375 		error = cdstartunit(periph);
2376 		break;
2377 	case CDIOCSTOP:
2378 		error = cdstopunit(periph, 0);
2379 		break;
2380 	case CDIOCEJECT:
2381 		error = cdstopunit(periph, 1);
2382 		break;
2383 	case CDIOCALLOW:
2384 		cdprevent(periph, PR_ALLOW);
2385 		break;
2386 	case CDIOCPREVENT:
2387 		cdprevent(periph, PR_PREVENT);
2388 		break;
2389 	case CDIOCSETDEBUG:
2390 		/* sc_link->flags |= (SDEV_DB1 | SDEV_DB2); */
2391 		error = ENOTTY;
2392 		break;
2393 	case CDIOCCLRDEBUG:
2394 		/* sc_link->flags &= ~(SDEV_DB1 | SDEV_DB2); */
2395 		error = ENOTTY;
2396 		break;
2397 	case CDIOCRESET:
2398 		/* return (cd_reset(periph)); */
2399 		error = ENOTTY;
2400 		break;
2401 	default:
2402 		error = cam_periph_ioctl(periph, cmd, addr, cderror);
2403 		break;
2404 	}
2405 
2406 	cam_periph_unlock(periph);
2407 
2408 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdioctl\n"));
2409 
2410 	return (error);
2411 }
2412 
2413 static void
2414 cdprevent(struct cam_periph *periph, int action)
2415 {
2416 	union	ccb *ccb;
2417 	struct	cd_softc *softc;
2418 	int	error;
2419 
2420 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdprevent\n"));
2421 
2422 	softc = (struct cd_softc *)periph->softc;
2423 
2424 	if (((action == PR_ALLOW)
2425 	  && (softc->flags & CD_FLAG_DISC_LOCKED) == 0)
2426 	 || ((action == PR_PREVENT)
2427 	  && (softc->flags & CD_FLAG_DISC_LOCKED) != 0)) {
2428 		return;
2429 	}
2430 
2431 	ccb = cdgetccb(periph, /* priority */ 1);
2432 
2433 	scsi_prevent(&ccb->csio,
2434 		     /*retries*/ 1,
2435 		     cddone,
2436 		     MSG_SIMPLE_Q_TAG,
2437 		     action,
2438 		     SSD_FULL_SIZE,
2439 		     /* timeout */60000);
2440 
2441 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2442 			/*sense_flags*/SF_RETRY_UA|SF_NO_PRINT|SF_RETRY_SELTO);
2443 
2444 	xpt_release_ccb(ccb);
2445 
2446 	if (error == 0) {
2447 		if (action == PR_ALLOW)
2448 			softc->flags &= ~CD_FLAG_DISC_LOCKED;
2449 		else
2450 			softc->flags |= CD_FLAG_DISC_LOCKED;
2451 	}
2452 }
2453 
2454 static int
2455 cdsize(dev_t dev, u_int32_t *size)
2456 {
2457 	struct cam_periph *periph;
2458 	struct cd_softc *softc;
2459 	union ccb *ccb;
2460 	struct scsi_read_capacity_data *rcap_buf;
2461 	int error;
2462 
2463 	periph = cam_extend_get(cdperiphs, dkunit(dev));
2464 
2465 	if (periph == NULL)
2466 		return (ENXIO);
2467 
2468 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdsize\n"));
2469 
2470 	softc = (struct cd_softc *)periph->softc;
2471 
2472 	ccb = cdgetccb(periph, /* priority */ 1);
2473 
2474 	rcap_buf = malloc(sizeof(struct scsi_read_capacity_data),
2475 			  M_TEMP, M_WAITOK);
2476 
2477 	scsi_read_capacity(&ccb->csio,
2478 			   /*retries*/ 1,
2479 			   cddone,
2480 			   MSG_SIMPLE_Q_TAG,
2481 			   rcap_buf,
2482 			   SSD_FULL_SIZE,
2483 			   /* timeout */20000);
2484 
2485 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2486 			 /*sense_flags*/SF_RETRY_UA|SF_NO_PRINT|SF_RETRY_SELTO);
2487 
2488 	xpt_release_ccb(ccb);
2489 
2490 	softc->params.disksize = scsi_4btoul(rcap_buf->addr) + 1;
2491 	softc->params.blksize  = scsi_4btoul(rcap_buf->length);
2492 
2493 	free(rcap_buf, M_TEMP);
2494 	*size = softc->params.disksize;
2495 
2496 	return (error);
2497 
2498 }
2499 
2500 static int
2501 cderror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
2502 {
2503 	struct cd_softc *softc;
2504 	struct cam_periph *periph;
2505 
2506 	periph = xpt_path_periph(ccb->ccb_h.path);
2507 	softc = (struct cd_softc *)periph->softc;
2508 
2509 	/*
2510 	 * XXX
2511 	 * Until we have a better way of doing pack validation,
2512 	 * don't treat UAs as errors.
2513 	 */
2514 	sense_flags |= SF_RETRY_UA;
2515 	return (cam_periph_error(ccb, cam_flags, sense_flags,
2516 				 &softc->saved_ccb));
2517 }
2518 
2519 /*
2520  * Read table of contents
2521  */
2522 static int
2523 cdreadtoc(struct cam_periph *periph, u_int32_t mode, u_int32_t start,
2524 	    struct cd_toc_entry *data, u_int32_t len)
2525 {
2526 	struct scsi_read_toc *scsi_cmd;
2527 	u_int32_t ntoc;
2528         struct ccb_scsiio *csio;
2529 	union ccb *ccb;
2530 	int error;
2531 
2532 	ntoc = len;
2533 	error = 0;
2534 
2535 	ccb = cdgetccb(periph, /* priority */ 1);
2536 
2537 	csio = &ccb->csio;
2538 
2539 	cam_fill_csio(csio,
2540 		      /* retries */ 1,
2541 		      /* cbfcnp */ cddone,
2542 		      /* flags */ CAM_DIR_IN,
2543 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2544 		      /* data_ptr */ (u_int8_t *)data,
2545 		      /* dxfer_len */ len,
2546 		      /* sense_len */ SSD_FULL_SIZE,
2547 		      sizeof(struct scsi_read_toc),
2548  		      /* timeout */ 50000);
2549 
2550 	scsi_cmd = (struct scsi_read_toc *)&csio->cdb_io.cdb_bytes;
2551 	bzero (scsi_cmd, sizeof(*scsi_cmd));
2552 
2553 	if (mode == CD_MSF_FORMAT)
2554 		scsi_cmd->byte2 |= CD_MSF;
2555 	scsi_cmd->from_track = start;
2556 	/* scsi_ulto2b(ntoc, (u_int8_t *)scsi_cmd->data_len); */
2557 	scsi_cmd->data_len[0] = (ntoc) >> 8;
2558 	scsi_cmd->data_len[1] = (ntoc) & 0xff;
2559 
2560 	scsi_cmd->op_code = READ_TOC;
2561 
2562 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2563 			 /*sense_flags*/SF_RETRY_UA|SF_RETRY_SELTO);
2564 
2565 	xpt_release_ccb(ccb);
2566 
2567 	return(error);
2568 }
2569 
2570 static int
2571 cdreadsubchannel(struct cam_periph *periph, u_int32_t mode,
2572 		 u_int32_t format, int track,
2573 		 struct cd_sub_channel_info *data, u_int32_t len)
2574 {
2575 	struct scsi_read_subchannel *scsi_cmd;
2576         struct ccb_scsiio *csio;
2577 	union ccb *ccb;
2578 	int error;
2579 
2580 	error = 0;
2581 
2582 	ccb = cdgetccb(periph, /* priority */ 1);
2583 
2584 	csio = &ccb->csio;
2585 
2586 	cam_fill_csio(csio,
2587 		      /* retries */ 1,
2588 		      /* cbfcnp */ cddone,
2589 		      /* flags */ CAM_DIR_IN,
2590 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2591 		      /* data_ptr */ (u_int8_t *)data,
2592 		      /* dxfer_len */ len,
2593 		      /* sense_len */ SSD_FULL_SIZE,
2594 		      sizeof(struct scsi_read_subchannel),
2595  		      /* timeout */ 50000);
2596 
2597 	scsi_cmd = (struct scsi_read_subchannel *)&csio->cdb_io.cdb_bytes;
2598 	bzero (scsi_cmd, sizeof(*scsi_cmd));
2599 
2600 	scsi_cmd->op_code = READ_SUBCHANNEL;
2601 	if (mode == CD_MSF_FORMAT)
2602 		scsi_cmd->byte1 |= CD_MSF;
2603 	scsi_cmd->byte2 = SRS_SUBQ;
2604 	scsi_cmd->subchan_format = format;
2605 	scsi_cmd->track = track;
2606 	scsi_ulto2b(len, (u_int8_t *)scsi_cmd->data_len);
2607 	scsi_cmd->control = 0;
2608 
2609 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2610 			 /*sense_flags*/SF_RETRY_UA|SF_RETRY_SELTO);
2611 
2612 	xpt_release_ccb(ccb);
2613 
2614 	return(error);
2615 }
2616 
2617 
2618 static int
2619 cdgetmode(struct cam_periph *periph, struct cd_mode_data *data, u_int32_t page)
2620 {
2621 	struct scsi_mode_sense_6 *scsi_cmd;
2622         struct ccb_scsiio *csio;
2623 	union ccb *ccb;
2624 	int error;
2625 
2626 	ccb = cdgetccb(periph, /* priority */ 1);
2627 
2628 	csio = &ccb->csio;
2629 
2630 	bzero(data, sizeof(*data));
2631 	cam_fill_csio(csio,
2632 		      /* retries */ 1,
2633 		      /* cbfcnp */ cddone,
2634 		      /* flags */ CAM_DIR_IN,
2635 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2636 		      /* data_ptr */ (u_int8_t *)data,
2637 		      /* dxfer_len */ sizeof(*data),
2638 		      /* sense_len */ SSD_FULL_SIZE,
2639 		      sizeof(struct scsi_mode_sense_6),
2640  		      /* timeout */ 50000);
2641 
2642 	scsi_cmd = (struct scsi_mode_sense_6 *)&csio->cdb_io.cdb_bytes;
2643 	bzero (scsi_cmd, sizeof(*scsi_cmd));
2644 
2645 	scsi_cmd->page = page;
2646 	scsi_cmd->length = sizeof(*data) & 0xff;
2647 	scsi_cmd->opcode = MODE_SENSE;
2648 
2649 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2650 			 /*sense_flags*/SF_RETRY_UA|SF_RETRY_SELTO);
2651 
2652 	xpt_release_ccb(ccb);
2653 
2654 	return(error);
2655 }
2656 
2657 static int
2658 cdsetmode(struct cam_periph *periph, struct cd_mode_data *data)
2659 {
2660 	struct scsi_mode_select_6 *scsi_cmd;
2661         struct ccb_scsiio *csio;
2662 	union ccb *ccb;
2663 	int error;
2664 
2665 	ccb = cdgetccb(periph, /* priority */ 1);
2666 
2667 	csio = &ccb->csio;
2668 
2669 	error = 0;
2670 
2671 	cam_fill_csio(csio,
2672 		      /* retries */ 1,
2673 		      /* cbfcnp */ cddone,
2674 		      /* flags */ CAM_DIR_OUT,
2675 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2676 		      /* data_ptr */ (u_int8_t *)data,
2677 		      /* dxfer_len */ sizeof(*data),
2678 		      /* sense_len */ SSD_FULL_SIZE,
2679 		      sizeof(struct scsi_mode_select_6),
2680  		      /* timeout */ 50000);
2681 
2682 	scsi_cmd = (struct scsi_mode_select_6 *)&csio->cdb_io.cdb_bytes;
2683 
2684 	bzero(scsi_cmd, sizeof(*scsi_cmd));
2685 	scsi_cmd->opcode = MODE_SELECT;
2686 	scsi_cmd->byte2 |= SMS_PF;
2687 	scsi_cmd->length = sizeof(*data) & 0xff;
2688 	data->header.data_length = 0;
2689 	/*
2690 	 * SONY drives do not allow a mode select with a medium_type
2691 	 * value that has just been returned by a mode sense; use a
2692 	 * medium_type of 0 (Default) instead.
2693 	 */
2694 	data->header.medium_type = 0;
2695 
2696 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2697 			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
2698 
2699 	xpt_release_ccb(ccb);
2700 
2701 	return(error);
2702 }
2703 
2704 
2705 static int
2706 cdplay(struct cam_periph *periph, u_int32_t blk, u_int32_t len)
2707 {
2708 	struct ccb_scsiio *csio;
2709 	union ccb *ccb;
2710 	int error;
2711 	u_int8_t cdb_len;
2712 
2713 	error = 0;
2714 	ccb = cdgetccb(periph, /* priority */ 1);
2715 	csio = &ccb->csio;
2716 	/*
2717 	 * Use the smallest possible command to perform the operation.
2718 	 */
2719 	if ((len & 0xffff0000) == 0) {
2720 		/*
2721 		 * We can fit in a 10 byte cdb.
2722 		 */
2723 		struct scsi_play_10 *scsi_cmd;
2724 
2725 		scsi_cmd = (struct scsi_play_10 *)&csio->cdb_io.cdb_bytes;
2726 		bzero (scsi_cmd, sizeof(*scsi_cmd));
2727 		scsi_cmd->op_code = PLAY_10;
2728 		scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
2729 		scsi_ulto2b(len, (u_int8_t *)scsi_cmd->xfer_len);
2730 		cdb_len = sizeof(*scsi_cmd);
2731 	} else  {
2732 		struct scsi_play_12 *scsi_cmd;
2733 
2734 		scsi_cmd = (struct scsi_play_12 *)&csio->cdb_io.cdb_bytes;
2735 		bzero (scsi_cmd, sizeof(*scsi_cmd));
2736 		scsi_cmd->op_code = PLAY_12;
2737 		scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
2738 		scsi_ulto4b(len, (u_int8_t *)scsi_cmd->xfer_len);
2739 		cdb_len = sizeof(*scsi_cmd);
2740 	}
2741 	cam_fill_csio(csio,
2742 		      /*retries*/2,
2743 		      cddone,
2744 		      /*flags*/CAM_DIR_NONE,
2745 		      MSG_SIMPLE_Q_TAG,
2746 		      /*dataptr*/NULL,
2747 		      /*datalen*/0,
2748 		      /*sense_len*/SSD_FULL_SIZE,
2749 		      cdb_len,
2750 		      /*timeout*/50 * 1000);
2751 
2752 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2753 			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
2754 
2755 	xpt_release_ccb(ccb);
2756 
2757 	return(error);
2758 }
2759 
2760 static int
2761 cdplaymsf(struct cam_periph *periph, u_int32_t startm, u_int32_t starts,
2762 	  u_int32_t startf, u_int32_t endm, u_int32_t ends, u_int32_t endf)
2763 {
2764 	struct scsi_play_msf *scsi_cmd;
2765         struct ccb_scsiio *csio;
2766 	union ccb *ccb;
2767 	int error;
2768 
2769 	error = 0;
2770 
2771 	ccb = cdgetccb(periph, /* priority */ 1);
2772 
2773 	csio = &ccb->csio;
2774 
2775 	cam_fill_csio(csio,
2776 		      /* retries */ 1,
2777 		      /* cbfcnp */ cddone,
2778 		      /* flags */ CAM_DIR_NONE,
2779 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2780 		      /* data_ptr */ NULL,
2781 		      /* dxfer_len */ 0,
2782 		      /* sense_len */ SSD_FULL_SIZE,
2783 		      sizeof(struct scsi_play_msf),
2784  		      /* timeout */ 50000);
2785 
2786 	scsi_cmd = (struct scsi_play_msf *)&csio->cdb_io.cdb_bytes;
2787 	bzero (scsi_cmd, sizeof(*scsi_cmd));
2788 
2789         scsi_cmd->op_code = PLAY_MSF;
2790         scsi_cmd->start_m = startm;
2791         scsi_cmd->start_s = starts;
2792         scsi_cmd->start_f = startf;
2793         scsi_cmd->end_m = endm;
2794         scsi_cmd->end_s = ends;
2795         scsi_cmd->end_f = endf;
2796 
2797 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2798 			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
2799 
2800 	xpt_release_ccb(ccb);
2801 
2802 	return(error);
2803 }
2804 
2805 
2806 static int
2807 cdplaytracks(struct cam_periph *periph, u_int32_t strack, u_int32_t sindex,
2808 	     u_int32_t etrack, u_int32_t eindex)
2809 {
2810 	struct scsi_play_track *scsi_cmd;
2811         struct ccb_scsiio *csio;
2812 	union ccb *ccb;
2813 	int error;
2814 
2815 	error = 0;
2816 
2817 	ccb = cdgetccb(periph, /* priority */ 1);
2818 
2819 	csio = &ccb->csio;
2820 
2821 	cam_fill_csio(csio,
2822 		      /* retries */ 1,
2823 		      /* cbfcnp */ cddone,
2824 		      /* flags */ CAM_DIR_NONE,
2825 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2826 		      /* data_ptr */ NULL,
2827 		      /* dxfer_len */ 0,
2828 		      /* sense_len */ SSD_FULL_SIZE,
2829 		      sizeof(struct scsi_play_track),
2830  		      /* timeout */ 50000);
2831 
2832 	scsi_cmd = (struct scsi_play_track *)&csio->cdb_io.cdb_bytes;
2833 	bzero (scsi_cmd, sizeof(*scsi_cmd));
2834 
2835         scsi_cmd->op_code = PLAY_TRACK;
2836         scsi_cmd->start_track = strack;
2837         scsi_cmd->start_index = sindex;
2838         scsi_cmd->end_track = etrack;
2839         scsi_cmd->end_index = eindex;
2840 
2841 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2842 			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
2843 
2844 	xpt_release_ccb(ccb);
2845 
2846 	return(error);
2847 }
2848 
2849 static int
2850 cdpause(struct cam_periph *periph, u_int32_t go)
2851 {
2852 	struct scsi_pause *scsi_cmd;
2853         struct ccb_scsiio *csio;
2854 	union ccb *ccb;
2855 	int error;
2856 
2857 	error = 0;
2858 
2859 	ccb = cdgetccb(periph, /* priority */ 1);
2860 
2861 	csio = &ccb->csio;
2862 
2863 	cam_fill_csio(csio,
2864 		      /* retries */ 1,
2865 		      /* cbfcnp */ cddone,
2866 		      /* flags */ CAM_DIR_NONE,
2867 		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2868 		      /* data_ptr */ NULL,
2869 		      /* dxfer_len */ 0,
2870 		      /* sense_len */ SSD_FULL_SIZE,
2871 		      sizeof(struct scsi_pause),
2872  		      /* timeout */ 50000);
2873 
2874 	scsi_cmd = (struct scsi_pause *)&csio->cdb_io.cdb_bytes;
2875 	bzero (scsi_cmd, sizeof(*scsi_cmd));
2876 
2877         scsi_cmd->op_code = PAUSE;
2878 	scsi_cmd->resume = go;
2879 
2880 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2881 			 /*sense_flags*/SF_RETRY_UA |SF_RETRY_SELTO);
2882 
2883 	xpt_release_ccb(ccb);
2884 
2885 	return(error);
2886 }
2887 
2888 static int
2889 cdstartunit(struct cam_periph *periph)
2890 {
2891 	union ccb *ccb;
2892 	int error;
2893 
2894 	error = 0;
2895 
2896 	ccb = cdgetccb(periph, /* priority */ 1);
2897 
2898 	scsi_start_stop(&ccb->csio,
2899 			/* retries */ 1,
2900 			/* cbfcnp */ cddone,
2901 			/* tag_action */ MSG_SIMPLE_Q_TAG,
2902 			/* start */ TRUE,
2903 			/* load_eject */ TRUE,
2904 			/* immediate */ FALSE,
2905 			/* sense_len */ SSD_FULL_SIZE,
2906 			/* timeout */ 50000);
2907 
2908 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2909 			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
2910 
2911 	xpt_release_ccb(ccb);
2912 
2913 	return(error);
2914 }
2915 
2916 static int
2917 cdstopunit(struct cam_periph *periph, u_int32_t eject)
2918 {
2919 	union ccb *ccb;
2920 	int error;
2921 
2922 	error = 0;
2923 
2924 	ccb = cdgetccb(periph, /* priority */ 1);
2925 
2926 	scsi_start_stop(&ccb->csio,
2927 			/* retries */ 1,
2928 			/* cbfcnp */ cddone,
2929 			/* tag_action */ MSG_SIMPLE_Q_TAG,
2930 			/* start */ FALSE,
2931 			/* load_eject */ eject,
2932 			/* immediate */ FALSE,
2933 			/* sense_len */ SSD_FULL_SIZE,
2934 			/* timeout */ 50000);
2935 
2936 	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2937 			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
2938 
2939 	xpt_release_ccb(ccb);
2940 
2941 	return(error);
2942 }
2943