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