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