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