scsi_cd.c revision 45845
1/*
2 * Copyright (c) 1997 Justin T. Gibbs.
3 * Copyright (c) 1997, 1998, 1999 Kenneth D. Merry.
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions, and the following disclaimer,
11 *    without modification, immediately at the beginning of the file.
12 * 2. The name of the author may not be used to endorse or promote products
13 *    derived from this software without specific prior written permission.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
19 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 *
27 *      $Id: scsi_cd.c,v 1.16 1999/04/07 22:57:54 gibbs 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			  DEVSTAT_PRIORITY_CD);
636
637	/*
638	 * Add an async callback so that we get
639	 * notified if this device goes away.
640	 */
641	xpt_setup_ccb(&csa.ccb_h, periph->path,
642		      /* priority */ 5);
643	csa.ccb_h.func_code = XPT_SASYNC_CB;
644	csa.event_enable = AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE;
645	csa.callback = cdasync;
646	csa.callback_arg = periph;
647	xpt_action((union ccb *)&csa);
648
649	/*
650	 * If the target lun is greater than 0, we most likely have a CD
651	 * changer device.  Check the quirk entries as well, though, just
652	 * in case someone has a CD tower with one lun per drive or
653	 * something like that.  Also, if we know up front that a
654	 * particular device is a changer, we can mark it as such starting
655	 * with lun 0, instead of lun 1.  It shouldn't be necessary to have
656	 * a quirk entry to define something as a changer, however.
657	 */
658	if (((cgd->ccb_h.target_lun > 0)
659	  && ((softc->quirks & CD_Q_NO_CHANGER) == 0))
660	 || ((softc->quirks & CD_Q_CHANGER) != 0)) {
661		struct cdchanger *nchanger;
662		struct cam_periph *nperiph;
663		struct cam_path *path;
664		cam_status status;
665		int found;
666
667		/* Set the changer flag in the current device's softc */
668		softc->flags |= CD_FLAG_CHANGER;
669
670		if (num_changers == 0)
671			STAILQ_INIT(&changerq);
672
673		/*
674		 * Now, look around for an existing changer device with the
675		 * same path and target ID as the current device.
676		 */
677		for (found = 0,
678		     nchanger = (struct cdchanger *)STAILQ_FIRST(&changerq);
679		     nchanger != NULL;
680		     nchanger = STAILQ_NEXT(nchanger, changer_links)){
681			if ((nchanger->path_id == cgd->ccb_h.path_id)
682			 && (nchanger->target_id == cgd->ccb_h.target_id)) {
683				found = 1;
684				break;
685			}
686		}
687
688		/*
689		 * If we found a matching entry, just add this device to
690		 * the list of devices on this changer.
691		 */
692		if (found == 1) {
693			struct chdevlist *chlunhead;
694
695			chlunhead = &nchanger->chluns;
696
697			/*
698			 * XXX KDM look at consolidating this code with the
699			 * code below in a separate function.
700			 */
701
702			/*
703			 * Create a path with lun id 0, and see if we can
704			 * find a matching device
705			 */
706			status = xpt_create_path(&path, /*periph*/ periph,
707						 cgd->ccb_h.path_id,
708						 cgd->ccb_h.target_id, 0);
709
710			if ((status == CAM_REQ_CMP)
711			 && ((nperiph = cam_periph_find(path, "cd")) != NULL)){
712				struct cd_softc *nsoftc;
713
714				nsoftc = (struct cd_softc *)nperiph->softc;
715
716				if ((nsoftc->flags & CD_FLAG_CHANGER) == 0){
717					nsoftc->flags |= CD_FLAG_CHANGER;
718					nchanger->num_devices++;
719					if (camq_resize(&nchanger->devq,
720					   nchanger->num_devices)!=CAM_REQ_CMP){
721						printf("cdregister: "
722						       "camq_resize "
723						       "failed, changer "
724						       "support may "
725						       "be messed up\n");
726					}
727					nsoftc->changer = nchanger;
728					nsoftc->pinfo.index =CAM_UNQUEUED_INDEX;
729
730					STAILQ_INSERT_TAIL(&nchanger->chluns,
731							  nsoftc,changer_links);
732				}
733			} else if (status == CAM_REQ_CMP)
734				xpt_free_path(path);
735			else {
736				printf("cdregister: unable to allocate path\n"
737				       "cdregister: changer support may be "
738				       "broken\n");
739			}
740
741			nchanger->num_devices++;
742
743			softc->changer = nchanger;
744			softc->pinfo.index = CAM_UNQUEUED_INDEX;
745
746			if (camq_resize(&nchanger->devq,
747			    nchanger->num_devices) != CAM_REQ_CMP) {
748				printf("cdregister: camq_resize "
749				       "failed, changer support may "
750				       "be messed up\n");
751			}
752
753			STAILQ_INSERT_TAIL(chlunhead, softc, changer_links);
754		}
755		/*
756		 * In this case, we don't already have an entry for this
757		 * particular changer, so we need to create one, add it to
758		 * the queue, and queue this device on the list for this
759		 * changer.  Before we queue this device, however, we need
760		 * to search for lun id 0 on this target, and add it to the
761		 * queue first, if it exists.  (and if it hasn't already
762		 * been marked as part of the changer.)
763		 */
764		else {
765			nchanger = malloc(sizeof(struct cdchanger),
766				M_DEVBUF, M_NOWAIT);
767
768			if (nchanger == NULL) {
769				softc->flags &= ~CD_FLAG_CHANGER;
770				printf("cdregister: unable to malloc "
771				       "changer structure\ncdregister: "
772				       "changer support disabled\n");
773
774				/*
775				 * Yes, gotos can be gross but in this case
776				 * I think it's justified..
777				 */
778				goto cdregisterexit;
779			}
780
781			/* zero the structure */
782			bzero(nchanger, sizeof(struct cdchanger));
783
784			if (camq_init(&nchanger->devq, 1) != 0) {
785				softc->flags &= ~CD_FLAG_CHANGER;
786				printf("cdregister: changer support "
787				       "disabled\n");
788				goto cdregisterexit;
789			}
790
791			num_changers++;
792
793			nchanger->path_id = cgd->ccb_h.path_id;
794			nchanger->target_id = cgd->ccb_h.target_id;
795
796			/* this is superfluous, but it makes things clearer */
797			nchanger->num_devices = 0;
798
799			STAILQ_INIT(&nchanger->chluns);
800
801			STAILQ_INSERT_TAIL(&changerq, nchanger,
802					   changer_links);
803
804			/*
805			 * Create a path with lun id 0, and see if we can
806			 * find a matching device
807			 */
808			status = xpt_create_path(&path, /*periph*/ periph,
809						 cgd->ccb_h.path_id,
810						 cgd->ccb_h.target_id, 0);
811
812			/*
813			 * If we were able to allocate the path, and if we
814			 * find a matching device and it isn't already
815			 * marked as part of a changer, then we add it to
816			 * the current changer.
817			 */
818			if ((status == CAM_REQ_CMP)
819			 && ((nperiph = cam_periph_find(path, "cd")) != NULL)
820			 && ((((struct cd_softc *)periph->softc)->flags &
821			       CD_FLAG_CHANGER) == 0)) {
822				struct cd_softc *nsoftc;
823
824				nsoftc = (struct cd_softc *)nperiph->softc;
825
826				nsoftc->flags |= CD_FLAG_CHANGER;
827				nchanger->num_devices++;
828				if (camq_resize(&nchanger->devq,
829				    nchanger->num_devices) != CAM_REQ_CMP) {
830					printf("cdregister: camq_resize "
831					       "failed, changer support may "
832					       "be messed up\n");
833				}
834				nsoftc->changer = nchanger;
835				nsoftc->pinfo.index = CAM_UNQUEUED_INDEX;
836
837				STAILQ_INSERT_TAIL(&nchanger->chluns,
838						   nsoftc, changer_links);
839			} else if (status == CAM_REQ_CMP)
840				xpt_free_path(path);
841			else {
842				printf("cdregister: unable to allocate path\n"
843				       "cdregister: changer support may be "
844				       "broken\n");
845			}
846
847			softc->changer = nchanger;
848			softc->pinfo.index = CAM_UNQUEUED_INDEX;
849			nchanger->num_devices++;
850			if (camq_resize(&nchanger->devq,
851			    nchanger->num_devices) != CAM_REQ_CMP) {
852				printf("cdregister: camq_resize "
853				       "failed, changer support may "
854				       "be messed up\n");
855			}
856			STAILQ_INSERT_TAIL(&nchanger->chluns, softc,
857					   changer_links);
858		}
859	}
860
861cdregisterexit:
862
863	/* Lock this peripheral until we are setup */
864	/* Can't block */
865	cam_periph_lock(periph, PRIBIO);
866
867	if ((softc->flags & CD_FLAG_CHANGER) == 0)
868		xpt_schedule(periph, /*priority*/5);
869	else
870		cdschedule(periph, /*priority*/ 5);
871
872	return(CAM_REQ_CMP);
873}
874
875static int
876cdopen(dev_t dev, int flags, int fmt, struct proc *p)
877{
878	struct disklabel label;
879	struct cam_periph *periph;
880	struct cd_softc *softc;
881	struct ccb_getdev cgd;
882	u_int32_t size;
883	int unit, error;
884	int s;
885
886	unit = dkunit(dev);
887	periph = cam_extend_get(cdperiphs, unit);
888
889	if (periph == NULL)
890		return (ENXIO);
891
892	softc = (struct cd_softc *)periph->softc;
893
894	/*
895	 * Grab splsoftcam and hold it until we lock the peripheral.
896	 */
897	s = splsoftcam();
898	if (softc->flags & CD_FLAG_INVALID) {
899		splx(s);
900		return(ENXIO);
901	}
902
903	if ((error = cam_periph_lock(periph, PRIBIO | PCATCH)) != 0) {
904		splx(s);
905		return (error);
906	}
907
908	splx(s);
909
910	if ((softc->flags & CD_FLAG_OPEN) == 0) {
911		if (cam_periph_acquire(periph) != CAM_REQ_CMP)
912			return(ENXIO);
913		softc->flags |= CD_FLAG_OPEN;
914
915		cdprevent(periph, PR_PREVENT);
916	}
917
918	/* find out the size */
919	if ((error = cdsize(dev, &size)) != 0) {
920		if (dsisopen(softc->cd_slices) == 0) {
921			cdprevent(periph, PR_ALLOW);
922			softc->flags &= ~CD_FLAG_OPEN;
923		}
924		cam_periph_unlock(periph);
925
926		if ((softc->flags & CD_FLAG_OPEN) == 0)
927			cam_periph_release(periph);
928
929		return(error);
930	}
931
932	/*
933	 * Build prototype label for whole disk.
934	 * Should take information about different data tracks from the
935	 * TOC and put it in the partition table.
936	 */
937	bzero(&label, sizeof(label));
938	label.d_type = DTYPE_SCSI;
939
940	/*
941	 * Grab the inquiry data to get the vendor and product names.
942	 * Put them in the typename and packname for the label.
943	 */
944	xpt_setup_ccb(&cgd.ccb_h, periph->path, /*priority*/ 1);
945	cgd.ccb_h.func_code = XPT_GDEV_TYPE;
946	xpt_action((union ccb *)&cgd);
947
948	strncpy(label.d_typename, cgd.inq_data.vendor,
949		min(SID_VENDOR_SIZE, sizeof(label.d_typename)));
950	strncpy(label.d_packname, cgd.inq_data.product,
951		min(SID_PRODUCT_SIZE, sizeof(label.d_packname)));
952
953	label.d_secsize = softc->params.blksize;
954	label.d_secperunit = softc->params.disksize;
955	label.d_flags = D_REMOVABLE;
956	/*
957	 * Make partition 'a' cover the whole disk.  This is a temporary
958	 * compatibility hack.  The 'a' partition should not exist, so
959	 * the slice code won't create it.  The slice code will make
960	 * partition (RAW_PART + 'a') cover the whole disk and fill in
961	 * some more defaults.
962	 */
963	label.d_partitions[0].p_size = label.d_secperunit;
964	label.d_partitions[0].p_fstype = FS_OTHER;
965
966	/* Initialize slice tables. */
967	error = dsopen("cd", dev, fmt, DSO_NOLABELS | DSO_ONESLICE,
968		       &softc->cd_slices, &label, cdstrategy1,
969		       (ds_setgeom_t *)NULL, &cd_cdevsw);
970
971	if (error == 0) {
972		/*
973		 * We unconditionally (re)set the blocksize each time the
974		 * CD device is opened.  This is because the CD can change,
975		 * and therefore the blocksize might change.
976		 * XXX problems here if some slice or partition is still
977		 * open with the old size?
978		 */
979		if ((softc->device_stats.flags & DEVSTAT_BS_UNAVAILABLE) != 0)
980			softc->device_stats.flags &= ~DEVSTAT_BS_UNAVAILABLE;
981		softc->device_stats.block_size = softc->params.blksize;
982	} else {
983		if ((dsisopen(softc->cd_slices) == 0)
984		 && ((softc->flags & CD_FLAG_DISC_REMOVABLE) != 0))
985			cdprevent(periph, PR_ALLOW);
986	}
987
988	cam_periph_unlock(periph);
989
990	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdopen\n"));
991
992	return (error);
993}
994
995static int
996cdclose(dev_t dev, int flag, int fmt, struct proc *p)
997{
998	struct 	cam_periph *periph;
999	struct	cd_softc *softc;
1000	int	unit, error;
1001
1002	unit = dkunit(dev);
1003	periph = cam_extend_get(cdperiphs, unit);
1004	if (periph == NULL)
1005		return (ENXIO);
1006
1007	softc = (struct cd_softc *)periph->softc;
1008
1009	if ((error = cam_periph_lock(periph, PRIBIO)) != 0)
1010		return (error);
1011
1012	dsclose(dev, fmt, softc->cd_slices);
1013	if (dsisopen(softc->cd_slices)) {
1014		cam_periph_unlock(periph);
1015		return (0);
1016	}
1017
1018	if ((softc->flags & CD_FLAG_DISC_REMOVABLE) != 0)
1019		cdprevent(periph, PR_ALLOW);
1020
1021	/*
1022	 * Since we're closing this CD, mark the blocksize as unavailable.
1023	 * It will be marked as available whence the CD is opened again.
1024	 */
1025	softc->device_stats.flags |= DEVSTAT_BS_UNAVAILABLE;
1026
1027	softc->flags &= ~CD_FLAG_OPEN;
1028	cam_periph_unlock(periph);
1029	cam_periph_release(periph);
1030
1031	return (0);
1032}
1033
1034static int
1035cdread(dev_t dev, struct uio *uio, int ioflag)
1036{
1037	return(physio(cdstrategy, NULL, dev, 1, minphys, uio));
1038}
1039
1040static void
1041cdshorttimeout(void *arg)
1042{
1043	struct cdchanger *changer;
1044	int s;
1045
1046	s = splsoftcam();
1047
1048	changer = (struct cdchanger *)arg;
1049
1050	/* Always clear the short timeout flag, since that's what we're in */
1051	changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
1052
1053	/*
1054	 * Check to see if there is any more pending or outstanding I/O for
1055	 * this device.  If not, move it out of the active slot.
1056	 */
1057	if ((bufq_first(&changer->cur_device->buf_queue) == NULL)
1058	 && (changer->cur_device->device_stats.busy_count == 0)) {
1059		changer->flags |= CHANGER_MANUAL_CALL;
1060		cdrunchangerqueue(changer);
1061	}
1062
1063	splx(s);
1064}
1065
1066/*
1067 * This is a wrapper for xpt_schedule.  It only applies to changers.
1068 */
1069static void
1070cdschedule(struct cam_periph *periph, int priority)
1071{
1072	struct cd_softc *softc;
1073	int s;
1074
1075	s = splsoftcam();
1076
1077	softc = (struct cd_softc *)periph->softc;
1078
1079	/*
1080	 * If this device isn't currently queued, and if it isn't
1081	 * the active device, then we queue this device and run the
1082	 * changer queue if there is no timeout scheduled to do it.
1083	 * If this device is the active device, just schedule it
1084	 * to run again.  If this device is queued, there should be
1085	 * a timeout in place already that will make sure it runs.
1086	 */
1087	if ((softc->pinfo.index == CAM_UNQUEUED_INDEX)
1088	 && ((softc->flags & CD_FLAG_ACTIVE) == 0)) {
1089		/*
1090		 * We don't do anything with the priority here.
1091		 * This is strictly a fifo queue.
1092		 */
1093		softc->pinfo.priority = 1;
1094		softc->pinfo.generation = ++softc->changer->devq.generation;
1095		camq_insert(&softc->changer->devq, (cam_pinfo *)softc);
1096
1097		/*
1098		 * Since we just put a device in the changer queue,
1099		 * check and see if there is a timeout scheduled for
1100		 * this changer.  If so, let the timeout handle
1101		 * switching this device into the active slot.  If
1102		 * not, manually call the timeout routine to
1103		 * bootstrap things.
1104		 */
1105		if (((softc->changer->flags & CHANGER_TIMEOUT_SCHED)==0)
1106		 &&((softc->changer->flags & CHANGER_NEED_TIMEOUT)==0)){
1107			softc->changer->flags |= CHANGER_MANUAL_CALL;
1108			cdrunchangerqueue(softc->changer);
1109		}
1110	} else if ((softc->flags & CD_FLAG_ACTIVE)
1111		&& ((softc->flags & CD_FLAG_SCHED_ON_COMP) == 0))
1112		xpt_schedule(periph, priority);
1113
1114	splx(s);
1115
1116}
1117
1118static void
1119cdrunchangerqueue(void *arg)
1120{
1121	struct cd_softc *softc;
1122	struct cdchanger *changer;
1123	int called_from_timeout;
1124	int s;
1125
1126	s = splsoftcam();
1127
1128	changer = (struct cdchanger *)arg;
1129
1130	/*
1131	 * If we have NOT been called from cdstrategy() or cddone(), and
1132	 * instead from a timeout routine, go ahead and clear the
1133	 * timeout flag.
1134	 */
1135	if ((changer->flags & CHANGER_MANUAL_CALL) == 0) {
1136		changer->flags &= ~CHANGER_TIMEOUT_SCHED;
1137		called_from_timeout = 1;
1138	} else
1139		called_from_timeout = 0;
1140
1141	/* Always clear the manual call flag */
1142	changer->flags &= ~CHANGER_MANUAL_CALL;
1143
1144	/* nothing to do if the queue is empty */
1145	if (changer->devq.entries <= 0) {
1146		splx(s);
1147		return;
1148	}
1149
1150	/*
1151	 * If the changer queue is frozen, that means we have an active
1152	 * device.
1153	 */
1154	if (changer->devq.qfrozen_cnt > 0) {
1155
1156		if (changer->cur_device->device_stats.busy_count > 0) {
1157			changer->cur_device->flags |= CD_FLAG_SCHED_ON_COMP;
1158			changer->cur_device->bufs_left =
1159				changer->cur_device->device_stats.busy_count;
1160			if (called_from_timeout) {
1161				changer->long_handle =
1162					timeout(cdrunchangerqueue, changer,
1163				        changer_max_busy_seconds * hz);
1164				changer->flags |= CHANGER_TIMEOUT_SCHED;
1165			}
1166			splx(s);
1167			return;
1168		}
1169
1170		/*
1171		 * We always need to reset the frozen count and clear the
1172		 * active flag.
1173		 */
1174		changer->devq.qfrozen_cnt--;
1175		changer->cur_device->flags &= ~CD_FLAG_ACTIVE;
1176		changer->cur_device->flags &= ~CD_FLAG_SCHED_ON_COMP;
1177
1178		/*
1179		 * Check to see whether the current device has any I/O left
1180		 * to do.  If so, requeue it at the end of the queue.  If
1181		 * not, there is no need to requeue it.
1182		 */
1183		if (bufq_first(&changer->cur_device->buf_queue) != NULL) {
1184
1185			changer->cur_device->pinfo.generation =
1186				++changer->devq.generation;
1187			camq_insert(&changer->devq,
1188				(cam_pinfo *)changer->cur_device);
1189		}
1190	}
1191
1192	softc = (struct cd_softc *)camq_remove(&changer->devq, CAMQ_HEAD);
1193
1194	changer->cur_device = softc;
1195
1196	changer->devq.qfrozen_cnt++;
1197	softc->flags |= CD_FLAG_ACTIVE;
1198
1199	/* Just in case this device is waiting */
1200	wakeup(&softc->changer);
1201	xpt_schedule(softc->periph, /*priority*/ 1);
1202
1203	/*
1204	 * Get rid of any pending timeouts, and set a flag to schedule new
1205	 * ones so this device gets its full time quantum.
1206	 */
1207	if (changer->flags & CHANGER_TIMEOUT_SCHED) {
1208		untimeout(cdrunchangerqueue, changer, changer->long_handle);
1209		changer->flags &= ~CHANGER_TIMEOUT_SCHED;
1210	}
1211
1212	if (changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
1213		untimeout(cdshorttimeout, changer, changer->short_handle);
1214		changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
1215	}
1216
1217	/*
1218	 * We need to schedule timeouts, but we only do this after the
1219	 * first transaction has completed.  This eliminates the changer
1220	 * switch time.
1221	 */
1222	changer->flags |= CHANGER_NEED_TIMEOUT;
1223
1224	splx(s);
1225}
1226
1227static void
1228cdchangerschedule(struct cd_softc *softc)
1229{
1230	struct cdchanger *changer;
1231	int s;
1232
1233	s = splsoftcam();
1234
1235	changer = softc->changer;
1236
1237	/*
1238	 * If this is a changer, and this is the current device,
1239	 * and this device has at least the minimum time quantum to
1240	 * run, see if we can switch it out.
1241	 */
1242	if ((softc->flags & CD_FLAG_ACTIVE)
1243	 && ((changer->flags & CHANGER_SHORT_TMOUT_SCHED) == 0)
1244	 && ((changer->flags & CHANGER_NEED_TIMEOUT) == 0)) {
1245		/*
1246		 * We try three things here.  The first is that we
1247		 * check to see whether the schedule on completion
1248		 * flag is set.  If it is, we decrement the number
1249		 * of buffers left, and if it's zero, we reschedule.
1250		 * Next, we check to see whether the pending buffer
1251		 * queue is empty and whether there are no
1252		 * outstanding transactions.  If so, we reschedule.
1253		 * Next, we see if the pending buffer queue is empty.
1254		 * If it is, we set the number of buffers left to
1255		 * the current active buffer count and set the
1256		 * schedule on complete flag.
1257		 */
1258		if (softc->flags & CD_FLAG_SCHED_ON_COMP) {
1259		 	if (--softc->bufs_left == 0) {
1260				softc->changer->flags |=
1261					CHANGER_MANUAL_CALL;
1262				softc->flags &= ~CD_FLAG_SCHED_ON_COMP;
1263				cdrunchangerqueue(softc->changer);
1264			}
1265		} else if ((bufq_first(&softc->buf_queue) == NULL)
1266		        && (softc->device_stats.busy_count == 0)) {
1267			softc->changer->flags |= CHANGER_MANUAL_CALL;
1268			cdrunchangerqueue(softc->changer);
1269		}
1270	} else if ((softc->changer->flags & CHANGER_NEED_TIMEOUT)
1271		&& (softc->flags & CD_FLAG_ACTIVE)) {
1272
1273		/*
1274		 * Now that the first transaction to this
1275		 * particular device has completed, we can go ahead
1276		 * and schedule our timeouts.
1277		 */
1278		if ((changer->flags & CHANGER_TIMEOUT_SCHED) == 0) {
1279			changer->long_handle =
1280			    timeout(cdrunchangerqueue, changer,
1281				    changer_max_busy_seconds * hz);
1282			changer->flags |= CHANGER_TIMEOUT_SCHED;
1283		} else
1284			printf("cdchangerschedule: already have a long"
1285			       " timeout!\n");
1286
1287		if ((changer->flags & CHANGER_SHORT_TMOUT_SCHED) == 0) {
1288			changer->short_handle =
1289			    timeout(cdshorttimeout, changer,
1290				    changer_min_busy_seconds * hz);
1291			changer->flags |= CHANGER_SHORT_TMOUT_SCHED;
1292		} else
1293			printf("cdchangerschedule: already have a short "
1294			       "timeout!\n");
1295
1296		/*
1297		 * We just scheduled timeouts, no need to schedule
1298		 * more.
1299		 */
1300		changer->flags &= ~CHANGER_NEED_TIMEOUT;
1301
1302	}
1303	splx(s);
1304}
1305
1306static int
1307cdrunccb(union ccb *ccb, int (*error_routine)(union ccb *ccb,
1308					      u_int32_t cam_flags,
1309					      u_int32_t sense_flags),
1310	 u_int32_t cam_flags, u_int32_t sense_flags)
1311{
1312	struct cd_softc *softc;
1313	struct cam_periph *periph;
1314	int error;
1315
1316	periph = xpt_path_periph(ccb->ccb_h.path);
1317	softc = (struct cd_softc *)periph->softc;
1318
1319	error = cam_periph_runccb(ccb, error_routine, cam_flags, sense_flags,
1320				  &softc->device_stats);
1321
1322	if (softc->flags & CD_FLAG_CHANGER)
1323		cdchangerschedule(softc);
1324
1325	return(error);
1326}
1327
1328static union ccb *
1329cdgetccb(struct cam_periph *periph, u_int32_t priority)
1330{
1331	struct cd_softc *softc;
1332	int s;
1333
1334	softc = (struct cd_softc *)periph->softc;
1335
1336	if (softc->flags & CD_FLAG_CHANGER) {
1337
1338		s = splsoftcam();
1339
1340		/*
1341		 * This should work the first time this device is woken up,
1342		 * but just in case it doesn't, we use a while loop.
1343		 */
1344		while ((((volatile cd_flags)softc->flags) & CD_FLAG_ACTIVE)==0){
1345			/*
1346			 * If this changer isn't already queued, queue it up.
1347			 */
1348			if (softc->pinfo.index == CAM_UNQUEUED_INDEX) {
1349				softc->pinfo.priority = 1;
1350				softc->pinfo.generation =
1351					++softc->changer->devq.generation;
1352				camq_insert(&softc->changer->devq,
1353					    (cam_pinfo *)softc);
1354			}
1355			if (((((volatile cd_changer_flags)softc->changer->flags)
1356				& CHANGER_TIMEOUT_SCHED)==0)
1357			 &&((((volatile cd_changer_flags)softc->changer->flags)
1358				& CHANGER_NEED_TIMEOUT)==0)){
1359				softc->changer->flags |= CHANGER_MANUAL_CALL;
1360				cdrunchangerqueue(softc->changer);
1361			} else
1362				tsleep(&softc->changer, PRIBIO, "cgticb", 0);
1363		}
1364		splx(s);
1365	}
1366	return(cam_periph_getccb(periph, priority));
1367}
1368
1369
1370/*
1371 * Actually translate the requested transfer into one the physical driver
1372 * can understand.  The transfer is described by a buf and will include
1373 * only one physical transfer.
1374 */
1375static void
1376cdstrategy(struct buf *bp)
1377{
1378	struct cam_periph *periph;
1379	struct cd_softc *softc;
1380	u_int  unit, part;
1381	int    s;
1382
1383	unit = dkunit(bp->b_dev);
1384	part = dkpart(bp->b_dev);
1385	periph = cam_extend_get(cdperiphs, unit);
1386	if (periph == NULL) {
1387		bp->b_error = ENXIO;
1388		goto bad;
1389	}
1390
1391	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdstrategy\n"));
1392
1393	softc = (struct cd_softc *)periph->softc;
1394
1395	/*
1396	 * Do bounds checking, adjust transfer, and set b_pbklno.
1397	 */
1398	if (dscheck(bp, softc->cd_slices) <= 0)
1399		goto done;
1400
1401	/*
1402	 * Mask interrupts so that the pack cannot be invalidated until
1403	 * after we are in the queue.  Otherwise, we might not properly
1404	 * clean up one of the buffers.
1405	 */
1406	s = splbio();
1407
1408	/*
1409	 * If the device has been made invalid, error out
1410	 */
1411	if ((softc->flags & CD_FLAG_INVALID)) {
1412		splx(s);
1413		bp->b_error = ENXIO;
1414		goto bad;
1415	}
1416
1417	/*
1418	 * Place it in the queue of disk activities for this disk
1419	 */
1420	bufqdisksort(&softc->buf_queue, bp);
1421
1422	splx(s);
1423
1424	/*
1425	 * Schedule ourselves for performing the work.  We do things
1426	 * differently for changers.
1427	 */
1428	if ((softc->flags & CD_FLAG_CHANGER) == 0)
1429		xpt_schedule(periph, /* XXX priority */1);
1430	else
1431		cdschedule(periph, /* priority */ 1);
1432
1433	return;
1434bad:
1435	bp->b_flags |= B_ERROR;
1436done:
1437	/*
1438	 * Correctly set the buf to indicate a completed xfer
1439	 */
1440	bp->b_resid = bp->b_bcount;
1441	biodone(bp);
1442	return;
1443}
1444
1445static void
1446cdstrategy1(struct buf *bp)
1447{
1448	/*
1449	 * XXX - do something to make cdstrategy() but not this block while
1450	 * we're doing dsopen() and dsioctl().
1451	 */
1452	cdstrategy(bp);
1453}
1454
1455static void
1456cdstart(struct cam_periph *periph, union ccb *start_ccb)
1457{
1458	struct cd_softc *softc;
1459	struct buf *bp;
1460	struct ccb_scsiio *csio;
1461	struct scsi_read_capacity_data *rcap;
1462	int s;
1463
1464	softc = (struct cd_softc *)periph->softc;
1465
1466	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdstart\n"));
1467
1468	switch (softc->state) {
1469	case CD_STATE_NORMAL:
1470	{
1471		int oldspl;
1472
1473		s = splbio();
1474		bp = bufq_first(&softc->buf_queue);
1475		if (periph->immediate_priority <= periph->pinfo.priority) {
1476			start_ccb->ccb_h.ccb_state = CD_CCB_WAITING;
1477
1478			SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1479					  periph_links.sle);
1480			periph->immediate_priority = CAM_PRIORITY_NONE;
1481			splx(s);
1482			wakeup(&periph->ccb_list);
1483		} else if (bp == NULL) {
1484			splx(s);
1485			xpt_release_ccb(start_ccb);
1486		} else {
1487			bufq_remove(&softc->buf_queue, bp);
1488
1489			devstat_start_transaction(&softc->device_stats);
1490
1491			scsi_read_write(&start_ccb->csio,
1492					/*retries*/4,
1493					/* cbfcnp */ cddone,
1494					(bp->b_flags & B_ORDERED) != 0 ?
1495					    MSG_ORDERED_Q_TAG :
1496					    MSG_SIMPLE_Q_TAG,
1497					/* read */bp->b_flags & B_READ,
1498					/* byte2 */ 0,
1499					/* minimum_cmd_size */ 10,
1500					/* lba */ bp->b_pblkno,
1501					bp->b_bcount / softc->params.blksize,
1502					/* data_ptr */ bp->b_data,
1503					/* dxfer_len */ bp->b_bcount,
1504					/* sense_len */ SSD_FULL_SIZE,
1505					/* timeout */ 30000);
1506			start_ccb->ccb_h.ccb_state = CD_CCB_BUFFER_IO;
1507
1508
1509			/*
1510			 * Block out any asyncronous callbacks
1511			 * while we touch the pending ccb list.
1512			 */
1513			oldspl = splcam();
1514			LIST_INSERT_HEAD(&softc->pending_ccbs,
1515					 &start_ccb->ccb_h, periph_links.le);
1516			splx(oldspl);
1517
1518			/* We expect a unit attention from this device */
1519			if ((softc->flags & CD_FLAG_RETRY_UA) != 0) {
1520				start_ccb->ccb_h.ccb_state |= CD_CCB_RETRY_UA;
1521				softc->flags &= ~CD_FLAG_RETRY_UA;
1522			}
1523
1524			start_ccb->ccb_h.ccb_bp = bp;
1525			bp = bufq_first(&softc->buf_queue);
1526			splx(s);
1527
1528			xpt_action(start_ccb);
1529		}
1530		if (bp != NULL) {
1531			/* Have more work to do, so ensure we stay scheduled */
1532			xpt_schedule(periph, /* XXX priority */1);
1533		}
1534		break;
1535	}
1536	case CD_STATE_PROBE:
1537	{
1538
1539		rcap = (struct scsi_read_capacity_data *)malloc(sizeof(*rcap),
1540								M_TEMP,
1541								M_NOWAIT);
1542		if (rcap == NULL) {
1543			xpt_print_path(periph->path);
1544			printf("cdstart: Couldn't malloc read_capacity data\n");
1545			/* cd_free_periph??? */
1546			break;
1547		}
1548		csio = &start_ccb->csio;
1549		scsi_read_capacity(csio,
1550				   /*retries*/1,
1551				   cddone,
1552				   MSG_SIMPLE_Q_TAG,
1553				   rcap,
1554				   SSD_FULL_SIZE,
1555				   /*timeout*/20000);
1556		start_ccb->ccb_h.ccb_bp = NULL;
1557		start_ccb->ccb_h.ccb_state = CD_CCB_PROBE;
1558		xpt_action(start_ccb);
1559		break;
1560	}
1561	}
1562}
1563
1564static void
1565cddone(struct cam_periph *periph, union ccb *done_ccb)
1566{
1567	struct cd_softc *softc;
1568	struct ccb_scsiio *csio;
1569
1570	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cddone\n"));
1571
1572	softc = (struct cd_softc *)periph->softc;
1573	csio = &done_ccb->csio;
1574
1575	switch (csio->ccb_h.ccb_state & CD_CCB_TYPE_MASK) {
1576	case CD_CCB_BUFFER_IO:
1577	{
1578		struct buf	*bp;
1579		int		error;
1580		int		oldspl;
1581
1582		bp = (struct buf *)done_ccb->ccb_h.ccb_bp;
1583		error = 0;
1584
1585		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1586			int sf;
1587
1588			if ((done_ccb->ccb_h.ccb_state & CD_CCB_RETRY_UA) != 0)
1589				sf = SF_RETRY_UA;
1590			else
1591				sf = 0;
1592
1593			if ((error = cderror(done_ccb, 0, sf)) == ERESTART) {
1594				/*
1595				 * A retry was scheuled, so
1596				 * just return.
1597				 */
1598				return;
1599			}
1600		}
1601
1602		if (error != 0) {
1603			int s;
1604			struct buf *q_bp;
1605
1606			xpt_print_path(periph->path);
1607			printf("cddone: got error %#x back\n", error);
1608			s = splbio();
1609			while ((q_bp = bufq_first(&softc->buf_queue)) != NULL) {
1610				bufq_remove(&softc->buf_queue, q_bp);
1611				q_bp->b_resid = q_bp->b_bcount;
1612				q_bp->b_error = EIO;
1613				q_bp->b_flags |= B_ERROR;
1614				biodone(q_bp);
1615			}
1616			splx(s);
1617			bp->b_resid = bp->b_bcount;
1618			bp->b_error = error;
1619			bp->b_flags |= B_ERROR;
1620			cam_release_devq(done_ccb->ccb_h.path,
1621					 /*relsim_flags*/0,
1622					 /*reduction*/0,
1623					 /*timeout*/0,
1624					 /*getcount_only*/0);
1625
1626		} else {
1627			bp->b_resid = csio->resid;
1628			bp->b_error = 0;
1629			if (bp->b_resid != 0) {
1630				/* Short transfer ??? */
1631				bp->b_flags |= B_ERROR;
1632			}
1633		}
1634
1635		/*
1636		 * Block out any asyncronous callbacks
1637		 * while we touch the pending ccb list.
1638		 */
1639		oldspl = splcam();
1640		LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
1641		splx(oldspl);
1642
1643		devstat_end_transaction(&softc->device_stats,
1644					bp->b_bcount - bp->b_resid,
1645					done_ccb->csio.tag_action & 0xf,
1646					(bp->b_flags & B_READ) ? DEVSTAT_READ
1647							       : DEVSTAT_WRITE);
1648
1649		if (softc->flags & CD_FLAG_CHANGER)
1650			cdchangerschedule(softc);
1651
1652		biodone(bp);
1653		break;
1654	}
1655	case CD_CCB_PROBE:
1656	{
1657		struct	   scsi_read_capacity_data *rdcap;
1658		char	   announce_buf[120]; /*
1659					       * Currently (9/30/97) the
1660					       * longest possible announce
1661					       * buffer is 108 bytes, for the
1662					       * first error case below.
1663					       * That is 39 bytes for the
1664					       * basic string, 16 bytes for the
1665					       * biggest sense key (hardware
1666					       * error), 52 bytes for the
1667					       * text of the largest sense
1668					       * qualifier valid for a CDROM,
1669					       * (0x72, 0x03 or 0x04,
1670					       * 0x03), and one byte for the
1671					       * null terminating character.
1672					       * To allow for longer strings,
1673					       * the announce buffer is 120
1674					       * bytes.
1675					       */
1676		struct	   cd_params *cdp;
1677
1678		cdp = &softc->params;
1679
1680		rdcap = (struct scsi_read_capacity_data *)csio->data_ptr;
1681
1682		cdp->disksize = scsi_4btoul (rdcap->addr) + 1;
1683		cdp->blksize = scsi_4btoul (rdcap->length);
1684
1685		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1686
1687			snprintf(announce_buf, sizeof(announce_buf),
1688				"cd present [%lu x %lu byte records]",
1689				cdp->disksize, (u_long)cdp->blksize);
1690
1691		} else {
1692			int	error;
1693			/*
1694			 * Retry any UNIT ATTENTION type errors.  They
1695			 * are expected at boot.
1696			 */
1697			error = cderror(done_ccb, 0, SF_RETRY_UA|SF_NO_PRINT);
1698			if (error == ERESTART) {
1699				/*
1700				 * A retry was scheuled, so
1701				 * just return.
1702				 */
1703				return;
1704			} else if (error != 0) {
1705
1706				struct scsi_sense_data *sense;
1707				int asc, ascq;
1708				int sense_key, error_code;
1709				int have_sense;
1710				cam_status status;
1711				struct ccb_getdev cgd;
1712
1713				/* Don't wedge this device's queue */
1714				cam_release_devq(done_ccb->ccb_h.path,
1715						 /*relsim_flags*/0,
1716						 /*reduction*/0,
1717						 /*timeout*/0,
1718						 /*getcount_only*/0);
1719
1720				status = done_ccb->ccb_h.status;
1721
1722				xpt_setup_ccb(&cgd.ccb_h,
1723					      done_ccb->ccb_h.path,
1724					      /* priority */ 1);
1725				cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1726				xpt_action((union ccb *)&cgd);
1727
1728				if (((csio->ccb_h.flags & CAM_SENSE_PHYS) != 0)
1729				 || ((csio->ccb_h.flags & CAM_SENSE_PTR) != 0)
1730				 || ((status & CAM_AUTOSNS_VALID) == 0))
1731					have_sense = FALSE;
1732				else
1733					have_sense = TRUE;
1734
1735				if (have_sense) {
1736					sense = &csio->sense_data;
1737					scsi_extract_sense(sense, &error_code,
1738							   &sense_key,
1739							   &asc, &ascq);
1740				}
1741				/*
1742				 * With CDROM devices, we expect 0x3a
1743				 * (Medium not present) errors, since not
1744				 * everyone leaves a CD in the drive.  Some
1745				 * broken Philips and HP WORM drives return
1746				 * 0x04,0x00 (logical unit not ready, cause
1747				 * not reportable), so we accept any "not
1748				 * ready" type errors as well.  If the error
1749				 * is anything else, though, we shouldn't
1750				 * attach.
1751				 */
1752				if ((have_sense)
1753				 && ((asc == 0x3a) || (asc == 0x04))
1754				 && (error_code == SSD_CURRENT_ERROR))
1755					snprintf(announce_buf,
1756					    sizeof(announce_buf),
1757						"Attempt to query device "
1758						"size failed: %s, %s",
1759						scsi_sense_key_text[sense_key],
1760						scsi_sense_desc(asc,ascq,
1761								&cgd.inq_data));
1762				else if (cgd.pd_type == T_CDROM) {
1763					/*
1764					 * We only print out an error for
1765					 * CDROM type devices.  For WORM
1766					 * devices, we don't print out an
1767					 * error since a few WORM devices
1768					 * don't support CDROM commands.
1769					 * If we have sense information, go
1770					 * ahead and print it out.
1771					 * Otherwise, just say that we
1772					 * couldn't attach.
1773					 */
1774
1775					/*
1776					 * Just print out the error, not
1777					 * the full probe message, when we
1778					 * don't attach.
1779					 */
1780					if (have_sense)
1781						scsi_sense_print(
1782							&done_ccb->csio);
1783					else {
1784						xpt_print_path(periph->path);
1785						printf("got CAM status %#x\n",
1786						       done_ccb->ccb_h.status);
1787					}
1788					xpt_print_path(periph->path);
1789					printf("fatal error, failed"
1790					       " to attach to device\n");
1791
1792					/*
1793					 * Invalidate this peripheral.
1794					 */
1795					cam_periph_invalidate(periph);
1796
1797					announce_buf[0] = '\0';
1798				} else {
1799
1800					/*
1801					 * Invalidate this peripheral.
1802					 */
1803					cam_periph_invalidate(periph);
1804					announce_buf[0] = '\0';
1805				}
1806			}
1807		}
1808		free(rdcap, M_TEMP);
1809		if (announce_buf[0] != '\0') {
1810			xpt_announce_periph(periph, announce_buf);
1811			if (softc->flags & CD_FLAG_CHANGER)
1812				cdchangerschedule(softc);
1813		}
1814		softc->state = CD_STATE_NORMAL;
1815		/*
1816		 * Since our peripheral may be invalidated by an error
1817		 * above or an external event, we must release our CCB
1818		 * before releasing the probe lock on the peripheral.
1819		 * The peripheral will only go away once the last lock
1820		 * is removed, and we need it around for the CCB release
1821		 * operation.
1822		 */
1823		xpt_release_ccb(done_ccb);
1824		cam_periph_unlock(periph);
1825		return;
1826	}
1827	case CD_CCB_WAITING:
1828	{
1829		/* Caller will release the CCB */
1830		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1831			  ("trying to wakeup ccbwait\n"));
1832
1833		wakeup(&done_ccb->ccb_h.cbfcnp);
1834		return;
1835	}
1836	default:
1837		break;
1838	}
1839	xpt_release_ccb(done_ccb);
1840}
1841
1842static int
1843cdioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
1844{
1845
1846	struct 	cam_periph *periph;
1847	struct	cd_softc *softc;
1848	int	error, unit;
1849
1850	unit = dkunit(dev);
1851
1852	periph = cam_extend_get(cdperiphs, unit);
1853	if (periph == NULL)
1854		return(ENXIO);
1855
1856	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdioctl\n"));
1857
1858	softc = (struct cd_softc *)periph->softc;
1859
1860	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1861		  ("trying to do ioctl %#lx\n", cmd));
1862
1863	error = cam_periph_lock(periph, PRIBIO | PCATCH);
1864
1865	if (error != 0)
1866		return(error);
1867
1868	switch (cmd) {
1869
1870	case CDIOCPLAYTRACKS:
1871		{
1872			struct ioc_play_track *args
1873			    = (struct ioc_play_track *) addr;
1874			struct cd_mode_data *data;
1875
1876			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
1877				      M_WAITOK);
1878
1879			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1880				  ("trying to do CDIOCPLAYTRACKS\n"));
1881
1882			error = cdgetmode(periph, data, AUDIO_PAGE);
1883			if (error) {
1884				free(data, M_TEMP);
1885				break;
1886			}
1887			data->page.audio.flags &= ~CD_PA_SOTC;
1888			data->page.audio.flags |= CD_PA_IMMED;
1889			error = cdsetmode(periph, data);
1890			free(data, M_TEMP);
1891			if (error)
1892				break;
1893			if (softc->quirks & CD_Q_BCD_TRACKS) {
1894				args->start_track = bin2bcd(args->start_track);
1895				args->end_track = bin2bcd(args->end_track);
1896			}
1897			error = cdplaytracks(periph,
1898					     args->start_track,
1899					     args->start_index,
1900					     args->end_track,
1901					     args->end_index);
1902		}
1903		break;
1904	case CDIOCPLAYMSF:
1905		{
1906			struct ioc_play_msf *args
1907				= (struct ioc_play_msf *) addr;
1908			struct cd_mode_data *data;
1909
1910			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
1911				      M_WAITOK);
1912
1913			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1914				  ("trying to do CDIOCPLAYMSF\n"));
1915
1916			error = cdgetmode(periph, data, AUDIO_PAGE);
1917			if (error) {
1918				free(data, M_TEMP);
1919				break;
1920			}
1921			data->page.audio.flags &= ~CD_PA_SOTC;
1922			data->page.audio.flags |= CD_PA_IMMED;
1923			error = cdsetmode(periph, data);
1924			free(data, M_TEMP);
1925			if (error)
1926				break;
1927			error = cdplaymsf(periph,
1928					  args->start_m,
1929					  args->start_s,
1930					  args->start_f,
1931					  args->end_m,
1932					  args->end_s,
1933					  args->end_f);
1934		}
1935		break;
1936	case CDIOCPLAYBLOCKS:
1937		{
1938			struct ioc_play_blocks *args
1939				= (struct ioc_play_blocks *) addr;
1940			struct cd_mode_data *data;
1941
1942			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1943				  ("trying to do CDIOCPLAYBLOCKS\n"));
1944
1945			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
1946				      M_WAITOK);
1947
1948			error = cdgetmode(periph, data, AUDIO_PAGE);
1949			if (error) {
1950				free(data, M_TEMP);
1951				break;
1952			}
1953			data->page.audio.flags &= ~CD_PA_SOTC;
1954			data->page.audio.flags |= CD_PA_IMMED;
1955			error = cdsetmode(periph, data);
1956			free(data, M_TEMP);
1957			if (error)
1958				break;
1959			error = cdplay(periph, args->blk, args->len);
1960		}
1961		break;
1962	case CDIOCREADSUBCHANNEL:
1963		{
1964			struct ioc_read_subchannel *args
1965				= (struct ioc_read_subchannel *) addr;
1966			struct cd_sub_channel_info *data;
1967			u_int32_t len = args->data_len;
1968
1969			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1970				  ("trying to do CDIOCREADSUBCHANNEL\n"));
1971
1972			data = malloc(sizeof(struct cd_sub_channel_info),
1973				      M_TEMP, M_WAITOK);
1974
1975			if ((len > sizeof(struct cd_sub_channel_info)) ||
1976			    (len < sizeof(struct cd_sub_channel_header))) {
1977				printf(
1978					"scsi_cd: cdioctl: "
1979					"cdioreadsubchannel: error, len=%d\n",
1980					len);
1981				error = EINVAL;
1982				free(data, M_TEMP);
1983				break;
1984			}
1985
1986			if (softc->quirks & CD_Q_BCD_TRACKS)
1987				args->track = bin2bcd(args->track);
1988
1989			error = cdreadsubchannel(periph, args->address_format,
1990				args->data_format, args->track, data, len);
1991
1992			if (error) {
1993				free(data, M_TEMP);
1994	 			break;
1995			}
1996			if (softc->quirks & CD_Q_BCD_TRACKS)
1997				data->what.track_info.track_number =
1998				    bcd2bin(data->what.track_info.track_number);
1999			len = min(len, ((data->header.data_len[0] << 8) +
2000				data->header.data_len[1] +
2001				sizeof(struct cd_sub_channel_header)));
2002			if (copyout(data, args->data, len) != 0) {
2003				error = EFAULT;
2004			}
2005			free(data, M_TEMP);
2006		}
2007		break;
2008
2009	case CDIOREADTOCHEADER:
2010		{
2011			struct ioc_toc_header *th;
2012
2013			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2014				  ("trying to do CDIOREADTOCHEADER\n"));
2015
2016			th = malloc(sizeof(struct ioc_toc_header), M_TEMP,
2017				    M_WAITOK);
2018			error = cdreadtoc(periph, 0, 0,
2019					  (struct cd_toc_entry *)th,
2020				          sizeof (*th));
2021			if (error) {
2022				free(th, M_TEMP);
2023				break;
2024			}
2025			if (softc->quirks & CD_Q_BCD_TRACKS) {
2026				/* we are going to have to convert the BCD
2027				 * encoding on the cd to what is expected
2028				 */
2029				th->starting_track =
2030					bcd2bin(th->starting_track);
2031				th->ending_track = bcd2bin(th->ending_track);
2032			}
2033			NTOHS(th->len);
2034			bcopy(th, addr, sizeof(*th));
2035			free(th, M_TEMP);
2036		}
2037		break;
2038	case CDIOREADTOCENTRYS:
2039		{
2040			typedef struct {
2041				struct ioc_toc_header header;
2042				struct cd_toc_entry entries[100];
2043			} data_t;
2044			typedef struct {
2045				struct ioc_toc_header header;
2046				struct cd_toc_entry entry;
2047			} lead_t;
2048
2049			data_t *data;
2050			lead_t *lead;
2051			struct ioc_read_toc_entry *te =
2052				(struct ioc_read_toc_entry *) addr;
2053			struct ioc_toc_header *th;
2054			u_int32_t len, readlen, idx, num;
2055			u_int32_t starting_track = te->starting_track;
2056
2057			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2058				  ("trying to do CDIOREADTOCENTRYS\n"));
2059
2060			data = malloc(sizeof(data_t), M_TEMP, M_WAITOK);
2061			lead = malloc(sizeof(lead_t), M_TEMP, M_WAITOK);
2062
2063			if (te->data_len < sizeof(struct cd_toc_entry)
2064			 || (te->data_len % sizeof(struct cd_toc_entry)) != 0
2065			 || (te->address_format != CD_MSF_FORMAT
2066			  && te->address_format != CD_LBA_FORMAT)) {
2067				error = EINVAL;
2068				printf("scsi_cd: error in readtocentries, "
2069				       "returning EINVAL\n");
2070				free(data, M_TEMP);
2071				free(lead, M_TEMP);
2072				break;
2073			}
2074
2075			th = &data->header;
2076			error = cdreadtoc(periph, 0, 0,
2077					  (struct cd_toc_entry *)th,
2078					  sizeof (*th));
2079			if (error) {
2080				free(data, M_TEMP);
2081				free(lead, M_TEMP);
2082				break;
2083			}
2084
2085			if (softc->quirks & CD_Q_BCD_TRACKS) {
2086				/* we are going to have to convert the BCD
2087				 * encoding on the cd to what is expected
2088				 */
2089				th->starting_track =
2090				    bcd2bin(th->starting_track);
2091				th->ending_track = bcd2bin(th->ending_track);
2092			}
2093
2094			if (starting_track == 0)
2095				starting_track = th->starting_track;
2096			else if (starting_track == LEADOUT)
2097				starting_track = th->ending_track + 1;
2098			else if (starting_track < th->starting_track ||
2099				 starting_track > th->ending_track + 1) {
2100				printf("scsi_cd: error in readtocentries, "
2101				       "returning EINVAL\n");
2102				free(data, M_TEMP);
2103				free(lead, M_TEMP);
2104				error = EINVAL;
2105				break;
2106			}
2107
2108			/* calculate reading length without leadout entry */
2109			readlen = (th->ending_track - starting_track + 1) *
2110				  sizeof(struct cd_toc_entry);
2111
2112			/* and with leadout entry */
2113			len = readlen + sizeof(struct cd_toc_entry);
2114			if (te->data_len < len) {
2115				len = te->data_len;
2116				if (readlen > len)
2117					readlen = len;
2118			}
2119			if (len > sizeof(data->entries)) {
2120				printf("scsi_cd: error in readtocentries, "
2121				       "returning EINVAL\n");
2122				error = EINVAL;
2123				free(data, M_TEMP);
2124				free(lead, M_TEMP);
2125				break;
2126			}
2127			num = len / sizeof(struct cd_toc_entry);
2128
2129			if (readlen > 0) {
2130				error = cdreadtoc(periph, te->address_format,
2131						  starting_track,
2132						  (struct cd_toc_entry *)data,
2133						  readlen + sizeof (*th));
2134				if (error) {
2135					free(data, M_TEMP);
2136					free(lead, M_TEMP);
2137					break;
2138				}
2139			}
2140
2141			/* make leadout entry if needed */
2142			idx = starting_track + num - 1;
2143			if (softc->quirks & CD_Q_BCD_TRACKS)
2144				th->ending_track = bcd2bin(th->ending_track);
2145			if (idx == th->ending_track + 1) {
2146				error = cdreadtoc(periph, te->address_format,
2147						  LEADOUT,
2148						  (struct cd_toc_entry *)lead,
2149						  sizeof(*lead));
2150				if (error) {
2151					free(data, M_TEMP);
2152					free(lead, M_TEMP);
2153					break;
2154				}
2155				data->entries[idx - starting_track] =
2156					lead->entry;
2157			}
2158			if (softc->quirks & CD_Q_BCD_TRACKS) {
2159				for (idx = 0; idx < num - 1; idx++) {
2160					data->entries[idx].track =
2161					    bcd2bin(data->entries[idx].track);
2162				}
2163			}
2164
2165			error = copyout(data->entries, te->data, len);
2166			free(data, M_TEMP);
2167			free(lead, M_TEMP);
2168		}
2169		break;
2170	case CDIOREADTOCENTRY:
2171		{
2172			/* yeah yeah, this is ugly */
2173			typedef struct {
2174				struct ioc_toc_header header;
2175				struct cd_toc_entry entry;
2176			} data_t;
2177
2178			data_t *data;
2179			struct ioc_read_toc_single_entry *te =
2180				(struct ioc_read_toc_single_entry *) addr;
2181			struct ioc_toc_header *th;
2182			u_int32_t track;
2183
2184			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2185				  ("trying to do CDIOREADTOCENTRY\n"));
2186
2187			data = malloc(sizeof(data_t), M_TEMP, M_WAITOK);
2188
2189			if (te->address_format != CD_MSF_FORMAT
2190			    && te->address_format != CD_LBA_FORMAT) {
2191				printf("error in readtocentry, "
2192				       " returning EINVAL\n");
2193				free(data, M_TEMP);
2194				error = EINVAL;
2195				break;
2196			}
2197
2198			th = &data->header;
2199			error = cdreadtoc(periph, 0, 0,
2200					  (struct cd_toc_entry *)th,
2201					  sizeof (*th));
2202			if (error) {
2203				free(data, M_TEMP);
2204				break;
2205			}
2206
2207			if (softc->quirks & CD_Q_BCD_TRACKS) {
2208				/* we are going to have to convert the BCD
2209				 * encoding on the cd to what is expected
2210				 */
2211				th->starting_track =
2212				    bcd2bin(th->starting_track);
2213				th->ending_track = bcd2bin(th->ending_track);
2214			}
2215			track = te->track;
2216			if (track == 0)
2217				track = th->starting_track;
2218			else if (track == LEADOUT)
2219				/* OK */;
2220			else if (track < th->starting_track ||
2221				 track > th->ending_track + 1) {
2222				printf("error in readtocentry, "
2223				       " returning EINVAL\n");
2224				free(data, M_TEMP);
2225				error = EINVAL;
2226				break;
2227			}
2228
2229			error = cdreadtoc(periph, te->address_format, track,
2230					  (struct cd_toc_entry *)data,
2231					  sizeof(data_t));
2232			if (error) {
2233				free(data, M_TEMP);
2234				break;
2235			}
2236
2237			if (softc->quirks & CD_Q_BCD_TRACKS)
2238				data->entry.track = bcd2bin(data->entry.track);
2239			bcopy(&data->entry, &te->entry,
2240			      sizeof(struct cd_toc_entry));
2241			free(data, M_TEMP);
2242		}
2243		break;
2244	case CDIOCSETPATCH:
2245		{
2246			struct ioc_patch *arg = (struct ioc_patch *) addr;
2247			struct cd_mode_data *data;
2248
2249			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2250				  ("trying to do CDIOCSETPATCH\n"));
2251
2252			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2253				      M_WAITOK);
2254			error = cdgetmode(periph, data, AUDIO_PAGE);
2255			if (error) {
2256				free(data, M_TEMP);
2257				break;
2258			}
2259			data->page.audio.port[LEFT_PORT].channels =
2260				arg->patch[0];
2261			data->page.audio.port[RIGHT_PORT].channels =
2262				arg->patch[1];
2263			data->page.audio.port[2].channels = arg->patch[2];
2264			data->page.audio.port[3].channels = arg->patch[3];
2265			error = cdsetmode(periph, data);
2266			free(data, M_TEMP);
2267		}
2268		break;
2269	case CDIOCGETVOL:
2270		{
2271			struct ioc_vol *arg = (struct ioc_vol *) addr;
2272			struct cd_mode_data *data;
2273
2274			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2275				  ("trying to do CDIOCGETVOL\n"));
2276
2277			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2278				      M_WAITOK);
2279			error = cdgetmode(periph, data, AUDIO_PAGE);
2280			if (error) {
2281				free(data, M_TEMP);
2282				break;
2283			}
2284			arg->vol[LEFT_PORT] =
2285				data->page.audio.port[LEFT_PORT].volume;
2286			arg->vol[RIGHT_PORT] =
2287				data->page.audio.port[RIGHT_PORT].volume;
2288			arg->vol[2] = data->page.audio.port[2].volume;
2289			arg->vol[3] = data->page.audio.port[3].volume;
2290			free(data, M_TEMP);
2291		}
2292		break;
2293	case CDIOCSETVOL:
2294		{
2295			struct ioc_vol *arg = (struct ioc_vol *) addr;
2296			struct cd_mode_data *data;
2297
2298			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2299				  ("trying to do CDIOCSETVOL\n"));
2300
2301			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2302				      M_WAITOK);
2303			error = cdgetmode(periph, data, AUDIO_PAGE);
2304			if (error) {
2305				free(data, M_TEMP);
2306				break;
2307			}
2308			data->page.audio.port[LEFT_PORT].channels = CHANNEL_0;
2309			data->page.audio.port[LEFT_PORT].volume =
2310				arg->vol[LEFT_PORT];
2311			data->page.audio.port[RIGHT_PORT].channels = CHANNEL_1;
2312			data->page.audio.port[RIGHT_PORT].volume =
2313				arg->vol[RIGHT_PORT];
2314			data->page.audio.port[2].volume = arg->vol[2];
2315			data->page.audio.port[3].volume = arg->vol[3];
2316			error = cdsetmode(periph, data);
2317			free(data, M_TEMP);
2318		}
2319		break;
2320	case CDIOCSETMONO:
2321		{
2322			struct cd_mode_data *data;
2323
2324			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2325				  ("trying to do CDIOCSETMONO\n"));
2326
2327			data = malloc(sizeof(struct cd_mode_data),
2328				      M_TEMP, M_WAITOK);
2329			error = cdgetmode(periph, data, AUDIO_PAGE);
2330			if (error) {
2331				free(data, M_TEMP);
2332				break;
2333			}
2334			data->page.audio.port[LEFT_PORT].channels =
2335				LEFT_CHANNEL | RIGHT_CHANNEL;
2336			data->page.audio.port[RIGHT_PORT].channels =
2337				LEFT_CHANNEL | RIGHT_CHANNEL;
2338			data->page.audio.port[2].channels = 0;
2339			data->page.audio.port[3].channels = 0;
2340			error = cdsetmode(periph, data);
2341			free(data, M_TEMP);
2342		}
2343		break;
2344	case CDIOCSETSTEREO:
2345		{
2346			struct cd_mode_data *data;
2347
2348			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2349				  ("trying to do CDIOCSETSTEREO\n"));
2350
2351			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2352				      M_WAITOK);
2353			error = cdgetmode(periph, data, AUDIO_PAGE);
2354			if (error) {
2355				free(data, M_TEMP);
2356				break;
2357			}
2358			data->page.audio.port[LEFT_PORT].channels =
2359				LEFT_CHANNEL;
2360			data->page.audio.port[RIGHT_PORT].channels =
2361				RIGHT_CHANNEL;
2362			data->page.audio.port[2].channels = 0;
2363			data->page.audio.port[3].channels = 0;
2364			error = cdsetmode(periph, data);
2365			free(data, M_TEMP);
2366		}
2367		break;
2368	case CDIOCSETMUTE:
2369		{
2370			struct cd_mode_data *data;
2371
2372			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2373				  ("trying to do CDIOCSETMUTE\n"));
2374
2375			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2376				      M_WAITOK);
2377			error = cdgetmode(periph, data, AUDIO_PAGE);
2378			if (error) {
2379				free(data, M_TEMP);
2380				break;
2381			}
2382			data->page.audio.port[LEFT_PORT].channels = 0;
2383			data->page.audio.port[RIGHT_PORT].channels = 0;
2384			data->page.audio.port[2].channels = 0;
2385			data->page.audio.port[3].channels = 0;
2386			error = cdsetmode(periph, data);
2387			free(data, M_TEMP);
2388		}
2389		break;
2390	case CDIOCSETLEFT:
2391		{
2392			struct cd_mode_data *data;
2393
2394			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2395				  ("trying to do CDIOCSETLEFT\n"));
2396
2397			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2398				      M_WAITOK);
2399			error = cdgetmode(periph, data, AUDIO_PAGE);
2400			if (error) {
2401				free(data, M_TEMP);
2402				break;
2403			}
2404			data->page.audio.port[LEFT_PORT].channels =
2405				LEFT_CHANNEL;
2406			data->page.audio.port[RIGHT_PORT].channels =
2407				LEFT_CHANNEL;
2408			data->page.audio.port[2].channels = 0;
2409			data->page.audio.port[3].channels = 0;
2410			error = cdsetmode(periph, data);
2411			free(data, M_TEMP);
2412		}
2413		break;
2414	case CDIOCSETRIGHT:
2415		{
2416			struct cd_mode_data *data;
2417
2418			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2419				  ("trying to do CDIOCSETRIGHT\n"));
2420
2421			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2422				      M_WAITOK);
2423			error = cdgetmode(periph, data, AUDIO_PAGE);
2424			if (error) {
2425				free(data, M_TEMP);
2426				break;
2427			}
2428			data->page.audio.port[LEFT_PORT].channels =
2429				RIGHT_CHANNEL;
2430			data->page.audio.port[RIGHT_PORT].channels =
2431				RIGHT_CHANNEL;
2432			data->page.audio.port[2].channels = 0;
2433			data->page.audio.port[3].channels = 0;
2434			error = cdsetmode(periph, data);
2435			free(data, M_TEMP);
2436		}
2437		break;
2438	case CDIOCRESUME:
2439		error = cdpause(periph, 1);
2440		break;
2441	case CDIOCPAUSE:
2442		error = cdpause(periph, 0);
2443		break;
2444	case CDIOCSTART:
2445		error = cdstartunit(periph);
2446		break;
2447	case CDIOCSTOP:
2448		error = cdstopunit(periph, 0);
2449		break;
2450	case CDIOCEJECT:
2451		error = cdstopunit(periph, 1);
2452		break;
2453	case CDIOCALLOW:
2454		cdprevent(periph, PR_ALLOW);
2455		break;
2456	case CDIOCPREVENT:
2457		cdprevent(periph, PR_PREVENT);
2458		break;
2459	case CDIOCSETDEBUG:
2460		/* sc_link->flags |= (SDEV_DB1 | SDEV_DB2); */
2461		error = ENOTTY;
2462		break;
2463	case CDIOCCLRDEBUG:
2464		/* sc_link->flags &= ~(SDEV_DB1 | SDEV_DB2); */
2465		error = ENOTTY;
2466		break;
2467	case CDIOCRESET:
2468		/* return (cd_reset(periph)); */
2469		error = ENOTTY;
2470		break;
2471	default:
2472		if (cmd == DIOCSBAD) {
2473			error = EINVAL;	/* XXX */
2474			break;
2475		}
2476
2477		/*
2478		 * Check to see whether we've got a disk-type ioctl.  If we
2479		 * don't, dsioctl will pass back an error code of ENOIOCTL.
2480		 */
2481		error = dsioctl("cd", dev, cmd, addr, flag, &softc->cd_slices,
2482				cdstrategy1, (ds_setgeom_t *)NULL);
2483
2484		if (error != ENOIOCTL)
2485			break;
2486
2487		error = cam_periph_ioctl(periph, cmd, addr, cderror);
2488		break;
2489	}
2490
2491	cam_periph_unlock(periph);
2492
2493	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdioctl\n"));
2494
2495	return (error);
2496}
2497
2498static void
2499cdprevent(struct cam_periph *periph, int action)
2500{
2501	union	ccb *ccb;
2502	struct	cd_softc *softc;
2503	int	error;
2504
2505	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdprevent\n"));
2506
2507	softc = (struct cd_softc *)periph->softc;
2508
2509	if (((action == PR_ALLOW)
2510	  && (softc->flags & CD_FLAG_DISC_LOCKED) == 0)
2511	 || ((action == PR_PREVENT)
2512	  && (softc->flags & CD_FLAG_DISC_LOCKED) != 0)) {
2513		return;
2514	}
2515
2516	ccb = cdgetccb(periph, /* priority */ 1);
2517
2518	scsi_prevent(&ccb->csio,
2519		     /*retries*/ 1,
2520		     cddone,
2521		     MSG_SIMPLE_Q_TAG,
2522		     action,
2523		     SSD_FULL_SIZE,
2524		     /* timeout */60000);
2525
2526	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2527				  /*sense_flags*/SF_RETRY_UA|SF_NO_PRINT);
2528
2529	xpt_release_ccb(ccb);
2530
2531	if (error == 0) {
2532		if (action == PR_ALLOW)
2533			softc->flags &= ~CD_FLAG_DISC_LOCKED;
2534		else
2535			softc->flags |= CD_FLAG_DISC_LOCKED;
2536	}
2537}
2538
2539static int
2540cdsize(dev_t dev, u_int32_t *size)
2541{
2542	struct cam_periph *periph;
2543	struct cd_softc *softc;
2544	union ccb *ccb;
2545	struct scsi_read_capacity_data *rcap_buf;
2546	int error;
2547
2548	periph = cam_extend_get(cdperiphs, dkunit(dev));
2549
2550	if (periph == NULL)
2551		return (ENXIO);
2552
2553	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdsize\n"));
2554
2555	softc = (struct cd_softc *)periph->softc;
2556
2557	ccb = cdgetccb(periph, /* priority */ 1);
2558
2559	rcap_buf = malloc(sizeof(struct scsi_read_capacity_data),
2560			  M_TEMP, M_WAITOK);
2561
2562	scsi_read_capacity(&ccb->csio,
2563			   /*retries*/ 1,
2564			   cddone,
2565			   MSG_SIMPLE_Q_TAG,
2566			   rcap_buf,
2567			   SSD_FULL_SIZE,
2568			   /* timeout */20000);
2569
2570	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2571				  /*sense_flags*/SF_RETRY_UA|SF_NO_PRINT);
2572
2573	xpt_release_ccb(ccb);
2574
2575	softc->params.disksize = scsi_4btoul(rcap_buf->addr) + 1;
2576	softc->params.blksize  = scsi_4btoul(rcap_buf->length);
2577
2578	free(rcap_buf, M_TEMP);
2579	*size = softc->params.disksize;
2580
2581	return (error);
2582
2583}
2584
2585static int
2586cderror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
2587{
2588	struct cd_softc *softc;
2589	struct cam_periph *periph;
2590
2591	periph = xpt_path_periph(ccb->ccb_h.path);
2592	softc = (struct cd_softc *)periph->softc;
2593
2594	/*
2595	 * XXX
2596	 * Until we have a better way of doing pack validation,
2597	 * don't treat UAs as errors.
2598	 */
2599	sense_flags |= SF_RETRY_UA;
2600	return (cam_periph_error(ccb, cam_flags, sense_flags,
2601				 &softc->saved_ccb));
2602}
2603
2604/*
2605 * Read table of contents
2606 */
2607static int
2608cdreadtoc(struct cam_periph *periph, u_int32_t mode, u_int32_t start,
2609	    struct cd_toc_entry *data, u_int32_t len)
2610{
2611	struct scsi_read_toc *scsi_cmd;
2612	u_int32_t ntoc;
2613        struct ccb_scsiio *csio;
2614	union ccb *ccb;
2615	int error;
2616
2617	ntoc = len;
2618	error = 0;
2619
2620	ccb = cdgetccb(periph, /* priority */ 1);
2621
2622	csio = &ccb->csio;
2623
2624	cam_fill_csio(csio,
2625		      /* retries */ 1,
2626		      /* cbfcnp */ cddone,
2627		      /* flags */ CAM_DIR_IN,
2628		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2629		      /* data_ptr */ (u_int8_t *)data,
2630		      /* dxfer_len */ len,
2631		      /* sense_len */ SSD_FULL_SIZE,
2632		      sizeof(struct scsi_read_toc),
2633 		      /* timeout */ 50000);
2634
2635	scsi_cmd = (struct scsi_read_toc *)&csio->cdb_io.cdb_bytes;
2636	bzero (scsi_cmd, sizeof(*scsi_cmd));
2637
2638	if (mode == CD_MSF_FORMAT)
2639		scsi_cmd->byte2 |= CD_MSF;
2640	scsi_cmd->from_track = start;
2641	/* scsi_ulto2b(ntoc, (u_int8_t *)scsi_cmd->data_len); */
2642	scsi_cmd->data_len[0] = (ntoc) >> 8;
2643	scsi_cmd->data_len[1] = (ntoc) & 0xff;
2644
2645	scsi_cmd->op_code = READ_TOC;
2646
2647	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2648				  /*sense_flags*/SF_RETRY_UA);
2649
2650	xpt_release_ccb(ccb);
2651
2652	return(error);
2653}
2654
2655static int
2656cdreadsubchannel(struct cam_periph *periph, u_int32_t mode,
2657		 u_int32_t format, int track,
2658		 struct cd_sub_channel_info *data, u_int32_t len)
2659{
2660	struct scsi_read_subchannel *scsi_cmd;
2661        struct ccb_scsiio *csio;
2662	union ccb *ccb;
2663	int error;
2664
2665	error = 0;
2666
2667	ccb = cdgetccb(periph, /* priority */ 1);
2668
2669	csio = &ccb->csio;
2670
2671	cam_fill_csio(csio,
2672		      /* retries */ 1,
2673		      /* cbfcnp */ cddone,
2674		      /* flags */ CAM_DIR_IN,
2675		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2676		      /* data_ptr */ (u_int8_t *)data,
2677		      /* dxfer_len */ len,
2678		      /* sense_len */ SSD_FULL_SIZE,
2679		      sizeof(struct scsi_read_subchannel),
2680 		      /* timeout */ 50000);
2681
2682	scsi_cmd = (struct scsi_read_subchannel *)&csio->cdb_io.cdb_bytes;
2683	bzero (scsi_cmd, sizeof(*scsi_cmd));
2684
2685	scsi_cmd->op_code = READ_SUBCHANNEL;
2686	if (mode == CD_MSF_FORMAT)
2687		scsi_cmd->byte1 |= CD_MSF;
2688	scsi_cmd->byte2 = SRS_SUBQ;
2689	scsi_cmd->subchan_format = format;
2690	scsi_cmd->track = track;
2691	scsi_ulto2b(len, (u_int8_t *)scsi_cmd->data_len);
2692	scsi_cmd->control = 0;
2693
2694	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2695				  /*sense_flags*/SF_RETRY_UA);
2696
2697	xpt_release_ccb(ccb);
2698
2699	return(error);
2700}
2701
2702
2703static int
2704cdgetmode(struct cam_periph *periph, struct cd_mode_data *data, u_int32_t page)
2705{
2706	struct scsi_mode_sense_6 *scsi_cmd;
2707        struct ccb_scsiio *csio;
2708	union ccb *ccb;
2709	int error;
2710
2711	ccb = cdgetccb(periph, /* priority */ 1);
2712
2713	csio = &ccb->csio;
2714
2715	bzero(data, sizeof(*data));
2716	cam_fill_csio(csio,
2717		      /* retries */ 1,
2718		      /* cbfcnp */ cddone,
2719		      /* flags */ CAM_DIR_IN,
2720		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2721		      /* data_ptr */ (u_int8_t *)data,
2722		      /* dxfer_len */ sizeof(*data),
2723		      /* sense_len */ SSD_FULL_SIZE,
2724		      sizeof(struct scsi_mode_sense_6),
2725 		      /* timeout */ 50000);
2726
2727	scsi_cmd = (struct scsi_mode_sense_6 *)&csio->cdb_io.cdb_bytes;
2728	bzero (scsi_cmd, sizeof(*scsi_cmd));
2729
2730	scsi_cmd->page = page;
2731	scsi_cmd->length = sizeof(*data) & 0xff;
2732	scsi_cmd->opcode = MODE_SENSE;
2733
2734	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2735				  /*sense_flags*/SF_RETRY_UA);
2736
2737	xpt_release_ccb(ccb);
2738
2739	return(error);
2740}
2741
2742static int
2743cdsetmode(struct cam_periph *periph, struct cd_mode_data *data)
2744{
2745	struct scsi_mode_select_6 *scsi_cmd;
2746        struct ccb_scsiio *csio;
2747	union ccb *ccb;
2748	int error;
2749
2750	ccb = cdgetccb(periph, /* priority */ 1);
2751
2752	csio = &ccb->csio;
2753
2754	error = 0;
2755
2756	cam_fill_csio(csio,
2757		      /* retries */ 1,
2758		      /* cbfcnp */ cddone,
2759		      /* flags */ CAM_DIR_OUT,
2760		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2761		      /* data_ptr */ (u_int8_t *)data,
2762		      /* dxfer_len */ sizeof(*data),
2763		      /* sense_len */ SSD_FULL_SIZE,
2764		      sizeof(struct scsi_mode_select_6),
2765 		      /* timeout */ 50000);
2766
2767	scsi_cmd = (struct scsi_mode_select_6 *)&csio->cdb_io.cdb_bytes;
2768
2769	bzero(scsi_cmd, sizeof(*scsi_cmd));
2770	scsi_cmd->opcode = MODE_SELECT;
2771	scsi_cmd->byte2 |= SMS_PF;
2772	scsi_cmd->length = sizeof(*data) & 0xff;
2773	data->header.data_length = 0;
2774	/*
2775	 * SONY drives do not allow a mode select with a medium_type
2776	 * value that has just been returned by a mode sense; use a
2777	 * medium_type of 0 (Default) instead.
2778	 */
2779	data->header.medium_type = 0;
2780
2781	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2782				  /*sense_flags*/SF_RETRY_UA);
2783
2784	xpt_release_ccb(ccb);
2785
2786	return(error);
2787}
2788
2789
2790static int
2791cdplay(struct cam_periph *periph, u_int32_t blk, u_int32_t len)
2792{
2793	struct ccb_scsiio *csio;
2794	union ccb *ccb;
2795	int error;
2796	u_int8_t cdb_len;
2797
2798	error = 0;
2799	ccb = cdgetccb(periph, /* priority */ 1);
2800	csio = &ccb->csio;
2801	/*
2802	 * Use the smallest possible command to perform the operation.
2803	 */
2804	if ((len & 0xffff0000) == 0) {
2805		/*
2806		 * We can fit in a 10 byte cdb.
2807		 */
2808		struct scsi_play_10 *scsi_cmd;
2809
2810		scsi_cmd = (struct scsi_play_10 *)&csio->cdb_io.cdb_bytes;
2811		bzero (scsi_cmd, sizeof(*scsi_cmd));
2812		scsi_cmd->op_code = PLAY_10;
2813		scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
2814		scsi_ulto2b(len, (u_int8_t *)scsi_cmd->xfer_len);
2815		cdb_len = sizeof(*scsi_cmd);
2816	} else  {
2817		struct scsi_play_12 *scsi_cmd;
2818
2819		scsi_cmd = (struct scsi_play_12 *)&csio->cdb_io.cdb_bytes;
2820		bzero (scsi_cmd, sizeof(*scsi_cmd));
2821		scsi_cmd->op_code = PLAY_12;
2822		scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
2823		scsi_ulto4b(len, (u_int8_t *)scsi_cmd->xfer_len);
2824		cdb_len = sizeof(*scsi_cmd);
2825	}
2826	cam_fill_csio(csio,
2827		      /*retries*/2,
2828		      cddone,
2829		      /*flags*/CAM_DIR_NONE,
2830		      MSG_SIMPLE_Q_TAG,
2831		      /*dataptr*/NULL,
2832		      /*datalen*/0,
2833		      /*sense_len*/SSD_FULL_SIZE,
2834		      cdb_len,
2835		      /*timeout*/50 * 1000);
2836
2837	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2838			 /*sense_flags*/SF_RETRY_UA);
2839
2840	xpt_release_ccb(ccb);
2841
2842	return(error);
2843}
2844
2845static int
2846cdplaymsf(struct cam_periph *periph, u_int32_t startm, u_int32_t starts,
2847	  u_int32_t startf, u_int32_t endm, u_int32_t ends, u_int32_t endf)
2848{
2849	struct scsi_play_msf *scsi_cmd;
2850        struct ccb_scsiio *csio;
2851	union ccb *ccb;
2852	int error;
2853
2854	error = 0;
2855
2856	ccb = cdgetccb(periph, /* priority */ 1);
2857
2858	csio = &ccb->csio;
2859
2860	cam_fill_csio(csio,
2861		      /* retries */ 1,
2862		      /* cbfcnp */ cddone,
2863		      /* flags */ CAM_DIR_NONE,
2864		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2865		      /* data_ptr */ NULL,
2866		      /* dxfer_len */ 0,
2867		      /* sense_len */ SSD_FULL_SIZE,
2868		      sizeof(struct scsi_play_msf),
2869 		      /* timeout */ 50000);
2870
2871	scsi_cmd = (struct scsi_play_msf *)&csio->cdb_io.cdb_bytes;
2872	bzero (scsi_cmd, sizeof(*scsi_cmd));
2873
2874        scsi_cmd->op_code = PLAY_MSF;
2875        scsi_cmd->start_m = startm;
2876        scsi_cmd->start_s = starts;
2877        scsi_cmd->start_f = startf;
2878        scsi_cmd->end_m = endm;
2879        scsi_cmd->end_s = ends;
2880        scsi_cmd->end_f = endf;
2881
2882	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2883				  /*sense_flags*/SF_RETRY_UA);
2884
2885	xpt_release_ccb(ccb);
2886
2887	return(error);
2888}
2889
2890
2891static int
2892cdplaytracks(struct cam_periph *periph, u_int32_t strack, u_int32_t sindex,
2893	     u_int32_t etrack, u_int32_t eindex)
2894{
2895	struct scsi_play_track *scsi_cmd;
2896        struct ccb_scsiio *csio;
2897	union ccb *ccb;
2898	int error;
2899
2900	error = 0;
2901
2902	ccb = cdgetccb(periph, /* priority */ 1);
2903
2904	csio = &ccb->csio;
2905
2906	cam_fill_csio(csio,
2907		      /* retries */ 1,
2908		      /* cbfcnp */ cddone,
2909		      /* flags */ CAM_DIR_NONE,
2910		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2911		      /* data_ptr */ NULL,
2912		      /* dxfer_len */ 0,
2913		      /* sense_len */ SSD_FULL_SIZE,
2914		      sizeof(struct scsi_play_track),
2915 		      /* timeout */ 50000);
2916
2917	scsi_cmd = (struct scsi_play_track *)&csio->cdb_io.cdb_bytes;
2918	bzero (scsi_cmd, sizeof(*scsi_cmd));
2919
2920        scsi_cmd->op_code = PLAY_TRACK;
2921        scsi_cmd->start_track = strack;
2922        scsi_cmd->start_index = sindex;
2923        scsi_cmd->end_track = etrack;
2924        scsi_cmd->end_index = eindex;
2925
2926	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2927				  /*sense_flags*/SF_RETRY_UA);
2928
2929	xpt_release_ccb(ccb);
2930
2931	return(error);
2932}
2933
2934static int
2935cdpause(struct cam_periph *periph, u_int32_t go)
2936{
2937	struct scsi_pause *scsi_cmd;
2938        struct ccb_scsiio *csio;
2939	union ccb *ccb;
2940	int error;
2941
2942	error = 0;
2943
2944	ccb = cdgetccb(periph, /* priority */ 1);
2945
2946	csio = &ccb->csio;
2947
2948	cam_fill_csio(csio,
2949		      /* retries */ 1,
2950		      /* cbfcnp */ cddone,
2951		      /* flags */ CAM_DIR_NONE,
2952		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2953		      /* data_ptr */ NULL,
2954		      /* dxfer_len */ 0,
2955		      /* sense_len */ SSD_FULL_SIZE,
2956		      sizeof(struct scsi_pause),
2957 		      /* timeout */ 50000);
2958
2959	scsi_cmd = (struct scsi_pause *)&csio->cdb_io.cdb_bytes;
2960	bzero (scsi_cmd, sizeof(*scsi_cmd));
2961
2962        scsi_cmd->op_code = PAUSE;
2963	scsi_cmd->resume = go;
2964
2965	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2966				  /*sense_flags*/SF_RETRY_UA);
2967
2968	xpt_release_ccb(ccb);
2969
2970	return(error);
2971}
2972
2973static int
2974cdstartunit(struct cam_periph *periph)
2975{
2976	union ccb *ccb;
2977	int error;
2978
2979	error = 0;
2980
2981	ccb = cdgetccb(periph, /* priority */ 1);
2982
2983	scsi_start_stop(&ccb->csio,
2984			/* retries */ 1,
2985			/* cbfcnp */ cddone,
2986			/* tag_action */ MSG_SIMPLE_Q_TAG,
2987			/* start */ TRUE,
2988			/* load_eject */ TRUE,
2989			/* immediate */ FALSE,
2990			/* sense_len */ SSD_FULL_SIZE,
2991			/* timeout */ 50000);
2992
2993	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2994				  /*sense_flags*/SF_RETRY_UA);
2995
2996	xpt_release_ccb(ccb);
2997
2998	return(error);
2999}
3000
3001static int
3002cdstopunit(struct cam_periph *periph, u_int32_t eject)
3003{
3004	union ccb *ccb;
3005	int error;
3006
3007	error = 0;
3008
3009	ccb = cdgetccb(periph, /* priority */ 1);
3010
3011	scsi_start_stop(&ccb->csio,
3012			/* retries */ 1,
3013			/* cbfcnp */ cddone,
3014			/* tag_action */ MSG_SIMPLE_Q_TAG,
3015			/* start */ FALSE,
3016			/* load_eject */ eject,
3017			/* immediate */ FALSE,
3018			/* sense_len */ SSD_FULL_SIZE,
3019			/* timeout */ 50000);
3020
3021	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3022				  /*sense_flags*/SF_RETRY_UA);
3023
3024	xpt_release_ccb(ccb);
3025
3026	return(error);
3027}
3028