scsi_cd.c revision 42017
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.10 1998/12/04 22:54:43 archie 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);
202union	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		softc->state = CD_STATE_NORMAL;
1819		if (softc->flags & CD_FLAG_CHANGER)
1820			cdchangerschedule(softc);
1821		cam_periph_unlock(periph);
1822
1823		break;
1824	}
1825	case CD_CCB_WAITING:
1826	{
1827		/* Caller will release the CCB */
1828		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1829			  ("trying to wakeup ccbwait\n"));
1830
1831		wakeup(&done_ccb->ccb_h.cbfcnp);
1832		return;
1833	}
1834	}
1835	xpt_release_ccb(done_ccb);
1836}
1837
1838static int
1839cdioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
1840{
1841
1842	struct 	cam_periph *periph;
1843	struct	cd_softc *softc;
1844	int	error, unit;
1845
1846	unit = dkunit(dev);
1847
1848	periph = cam_extend_get(cdperiphs, unit);
1849	if (periph == NULL)
1850		return(ENXIO);
1851
1852	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdioctl\n"));
1853
1854	softc = (struct cd_softc *)periph->softc;
1855
1856	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1857		  ("trying to do ioctl %#lx\n", cmd));
1858
1859	error = cam_periph_lock(periph, PRIBIO | PCATCH);
1860
1861	if (error != 0)
1862		return(error);
1863
1864	switch (cmd) {
1865
1866	case CDIOCPLAYTRACKS:
1867		{
1868			struct ioc_play_track *args
1869			    = (struct ioc_play_track *) addr;
1870			struct cd_mode_data *data;
1871
1872			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
1873				      M_WAITOK);
1874
1875			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1876				  ("trying to do CDIOCPLAYTRACKS\n"));
1877
1878			error = cdgetmode(periph, data, AUDIO_PAGE);
1879			if (error) {
1880				free(data, M_TEMP);
1881				break;
1882			}
1883			data->page.audio.flags &= ~CD_PA_SOTC;
1884			data->page.audio.flags |= CD_PA_IMMED;
1885			error = cdsetmode(periph, data);
1886			free(data, M_TEMP);
1887			if (error)
1888				break;
1889			if (softc->quirks & CD_Q_BCD_TRACKS) {
1890				args->start_track = bin2bcd(args->start_track);
1891				args->end_track = bin2bcd(args->end_track);
1892			}
1893			error = cdplaytracks(periph,
1894					     args->start_track,
1895					     args->start_index,
1896					     args->end_track,
1897					     args->end_index);
1898		}
1899		break;
1900	case CDIOCPLAYMSF:
1901		{
1902			struct ioc_play_msf *args
1903				= (struct ioc_play_msf *) addr;
1904			struct cd_mode_data *data;
1905
1906			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
1907				      M_WAITOK);
1908
1909			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1910				  ("trying to do CDIOCPLAYMSF\n"));
1911
1912			error = cdgetmode(periph, data, AUDIO_PAGE);
1913			if (error) {
1914				free(data, M_TEMP);
1915				break;
1916			}
1917			data->page.audio.flags &= ~CD_PA_SOTC;
1918			data->page.audio.flags |= CD_PA_IMMED;
1919			error = cdsetmode(periph, data);
1920			free(data, M_TEMP);
1921			if (error)
1922				break;
1923			error = cdplaymsf(periph,
1924					  args->start_m,
1925					  args->start_s,
1926					  args->start_f,
1927					  args->end_m,
1928					  args->end_s,
1929					  args->end_f);
1930		}
1931		break;
1932	case CDIOCPLAYBLOCKS:
1933		{
1934			struct ioc_play_blocks *args
1935				= (struct ioc_play_blocks *) addr;
1936			struct cd_mode_data *data;
1937
1938			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1939				  ("trying to do CDIOCPLAYBLOCKS\n"));
1940
1941			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
1942				      M_WAITOK);
1943
1944			error = cdgetmode(periph, data, AUDIO_PAGE);
1945			if (error) {
1946				free(data, M_TEMP);
1947				break;
1948			}
1949			data->page.audio.flags &= ~CD_PA_SOTC;
1950			data->page.audio.flags |= CD_PA_IMMED;
1951			error = cdsetmode(periph, data);
1952			free(data, M_TEMP);
1953			if (error)
1954				break;
1955			error = cdplay(periph, args->blk, args->len);
1956		}
1957		break;
1958	case CDIOCREADSUBCHANNEL:
1959		{
1960			struct ioc_read_subchannel *args
1961				= (struct ioc_read_subchannel *) addr;
1962			struct cd_sub_channel_info *data;
1963			u_int32_t len = args->data_len;
1964
1965			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1966				  ("trying to do CDIOCREADSUBCHANNEL\n"));
1967
1968			data = malloc(sizeof(struct cd_sub_channel_info),
1969				      M_TEMP, M_WAITOK);
1970
1971			if ((len > sizeof(struct cd_sub_channel_info)) ||
1972			    (len < sizeof(struct cd_sub_channel_header))) {
1973				printf(
1974					"scsi_cd: cdioctl: "
1975					"cdioreadsubchannel: error, len=%d\n",
1976					len);
1977				error = EINVAL;
1978				free(data, M_TEMP);
1979				break;
1980			}
1981
1982			if (softc->quirks & CD_Q_BCD_TRACKS)
1983				args->track = bin2bcd(args->track);
1984
1985			error = cdreadsubchannel(periph, args->address_format,
1986				args->data_format, args->track, data, len);
1987
1988			if (error) {
1989				free(data, M_TEMP);
1990	 			break;
1991			}
1992			if (softc->quirks & CD_Q_BCD_TRACKS)
1993				data->what.track_info.track_number =
1994				    bcd2bin(data->what.track_info.track_number);
1995			len = min(len, ((data->header.data_len[0] << 8) +
1996				data->header.data_len[1] +
1997				sizeof(struct cd_sub_channel_header)));
1998			if (copyout(data, args->data, len) != 0) {
1999				error = EFAULT;
2000			}
2001			free(data, M_TEMP);
2002		}
2003		break;
2004
2005	case CDIOREADTOCHEADER:
2006		{
2007			struct ioc_toc_header *th;
2008
2009			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2010				  ("trying to do CDIOREADTOCHEADER\n"));
2011
2012			th = malloc(sizeof(struct ioc_toc_header), M_TEMP,
2013				    M_WAITOK);
2014			error = cdreadtoc(periph, 0, 0,
2015					  (struct cd_toc_entry *)th,
2016				          sizeof (*th));
2017			if (error) {
2018				free(th, M_TEMP);
2019				break;
2020			}
2021			if (softc->quirks & CD_Q_BCD_TRACKS) {
2022				/* we are going to have to convert the BCD
2023				 * encoding on the cd to what is expected
2024				 */
2025				th->starting_track =
2026					bcd2bin(th->starting_track);
2027				th->ending_track = bcd2bin(th->ending_track);
2028			}
2029			NTOHS(th->len);
2030			bcopy(th, addr, sizeof(*th));
2031			free(th, M_TEMP);
2032		}
2033		break;
2034	case CDIOREADTOCENTRYS:
2035		{
2036			typedef struct {
2037				struct ioc_toc_header header;
2038				struct cd_toc_entry entries[100];
2039			} data_t;
2040			typedef struct {
2041				struct ioc_toc_header header;
2042				struct cd_toc_entry entry;
2043			} lead_t;
2044
2045			data_t *data;
2046			lead_t *lead;
2047			struct ioc_read_toc_entry *te =
2048				(struct ioc_read_toc_entry *) addr;
2049			struct ioc_toc_header *th;
2050			u_int32_t len, readlen, idx, num;
2051			u_int32_t starting_track = te->starting_track;
2052
2053			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2054				  ("trying to do CDIOREADTOCENTRYS\n"));
2055
2056			data = malloc(sizeof(data_t), M_TEMP, M_WAITOK);
2057			lead = malloc(sizeof(lead_t), M_TEMP, M_WAITOK);
2058
2059			if (te->data_len < sizeof(struct cd_toc_entry)
2060			 || (te->data_len % sizeof(struct cd_toc_entry)) != 0
2061			 || (te->address_format != CD_MSF_FORMAT
2062			  && te->address_format != CD_LBA_FORMAT)) {
2063				error = EINVAL;
2064				printf("scsi_cd: error in readtocentries, "
2065				       "returning EINVAL\n");
2066				free(data, M_TEMP);
2067				free(lead, M_TEMP);
2068				break;
2069			}
2070
2071			th = &data->header;
2072			error = cdreadtoc(periph, 0, 0,
2073					  (struct cd_toc_entry *)th,
2074					  sizeof (*th));
2075			if (error) {
2076				free(data, M_TEMP);
2077				free(lead, M_TEMP);
2078				break;
2079			}
2080
2081			if (softc->quirks & CD_Q_BCD_TRACKS) {
2082				/* we are going to have to convert the BCD
2083				 * encoding on the cd to what is expected
2084				 */
2085				th->starting_track =
2086				    bcd2bin(th->starting_track);
2087				th->ending_track = bcd2bin(th->ending_track);
2088			}
2089
2090			if (starting_track == 0)
2091				starting_track = th->starting_track;
2092			else if (starting_track == LEADOUT)
2093				starting_track = th->ending_track + 1;
2094			else if (starting_track < th->starting_track ||
2095				 starting_track > th->ending_track + 1) {
2096				printf("scsi_cd: error in readtocentries, "
2097				       "returning EINVAL\n");
2098				free(data, M_TEMP);
2099				free(lead, M_TEMP);
2100				error = EINVAL;
2101				break;
2102			}
2103
2104			/* calculate reading length without leadout entry */
2105			readlen = (th->ending_track - starting_track + 1) *
2106				  sizeof(struct cd_toc_entry);
2107
2108			/* and with leadout entry */
2109			len = readlen + sizeof(struct cd_toc_entry);
2110			if (te->data_len < len) {
2111				len = te->data_len;
2112				if (readlen > len)
2113					readlen = len;
2114			}
2115			if (len > sizeof(data->entries)) {
2116				printf("scsi_cd: error in readtocentries, "
2117				       "returning EINVAL\n");
2118				error = EINVAL;
2119				free(data, M_TEMP);
2120				free(lead, M_TEMP);
2121				break;
2122			}
2123			num = len / sizeof(struct cd_toc_entry);
2124
2125			if (readlen > 0) {
2126				error = cdreadtoc(periph, te->address_format,
2127						  starting_track,
2128						  (struct cd_toc_entry *)data,
2129						  readlen + sizeof (*th));
2130				if (error) {
2131					free(data, M_TEMP);
2132					free(lead, M_TEMP);
2133					break;
2134				}
2135			}
2136
2137			/* make leadout entry if needed */
2138			idx = starting_track + num - 1;
2139			if (softc->quirks & CD_Q_BCD_TRACKS)
2140				th->ending_track = bcd2bin(th->ending_track);
2141			if (idx == th->ending_track + 1) {
2142				error = cdreadtoc(periph, te->address_format,
2143						  LEADOUT,
2144						  (struct cd_toc_entry *)lead,
2145						  sizeof(*lead));
2146				if (error) {
2147					free(data, M_TEMP);
2148					free(lead, M_TEMP);
2149					break;
2150				}
2151				data->entries[idx - starting_track] =
2152					lead->entry;
2153			}
2154			if (softc->quirks & CD_Q_BCD_TRACKS) {
2155				for (idx = 0; idx < num - 1; idx++) {
2156					data->entries[idx].track =
2157					    bcd2bin(data->entries[idx].track);
2158				}
2159			}
2160
2161			error = copyout(data->entries, te->data, len);
2162			free(data, M_TEMP);
2163			free(lead, M_TEMP);
2164		}
2165		break;
2166	case CDIOREADTOCENTRY:
2167		{
2168			/* yeah yeah, this is ugly */
2169			typedef struct {
2170				struct ioc_toc_header header;
2171				struct cd_toc_entry entry;
2172			} data_t;
2173
2174			data_t *data;
2175			struct ioc_read_toc_single_entry *te =
2176				(struct ioc_read_toc_single_entry *) addr;
2177			struct ioc_toc_header *th;
2178			u_int32_t track;
2179
2180			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2181				  ("trying to do CDIOREADTOCENTRY\n"));
2182
2183			data = malloc(sizeof(data_t), M_TEMP, M_WAITOK);
2184
2185			if (te->address_format != CD_MSF_FORMAT
2186			    && te->address_format != CD_LBA_FORMAT) {
2187				printf("error in readtocentry, "
2188				       " returning EINVAL\n");
2189				free(data, M_TEMP);
2190				error = EINVAL;
2191				break;
2192			}
2193
2194			th = &data->header;
2195			error = cdreadtoc(periph, 0, 0,
2196					  (struct cd_toc_entry *)th,
2197					  sizeof (*th));
2198			if (error) {
2199				free(data, M_TEMP);
2200				break;
2201			}
2202
2203			if (softc->quirks & CD_Q_BCD_TRACKS) {
2204				/* we are going to have to convert the BCD
2205				 * encoding on the cd to what is expected
2206				 */
2207				th->starting_track =
2208				    bcd2bin(th->starting_track);
2209				th->ending_track = bcd2bin(th->ending_track);
2210			}
2211			track = te->track;
2212			if (track == 0)
2213				track = th->starting_track;
2214			else if (track == LEADOUT)
2215				/* OK */;
2216			else if (track < th->starting_track ||
2217				 track > th->ending_track + 1) {
2218				printf("error in readtocentry, "
2219				       " returning EINVAL\n");
2220				free(data, M_TEMP);
2221				error = EINVAL;
2222				break;
2223			}
2224
2225			error = cdreadtoc(periph, te->address_format, track,
2226					  (struct cd_toc_entry *)data,
2227					  sizeof(data_t));
2228			if (error) {
2229				free(data, M_TEMP);
2230				break;
2231			}
2232
2233			if (softc->quirks & CD_Q_BCD_TRACKS)
2234				data->entry.track = bcd2bin(data->entry.track);
2235			bcopy(&data->entry, &te->entry,
2236			      sizeof(struct cd_toc_entry));
2237			free(data, M_TEMP);
2238		}
2239		break;
2240	case CDIOCSETPATCH:
2241		{
2242			struct ioc_patch *arg = (struct ioc_patch *) addr;
2243			struct cd_mode_data *data;
2244
2245			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2246				  ("trying to do CDIOCSETPATCH\n"));
2247
2248			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2249				      M_WAITOK);
2250			error = cdgetmode(periph, data, AUDIO_PAGE);
2251			if (error) {
2252				free(data, M_TEMP);
2253				break;
2254			}
2255			data->page.audio.port[LEFT_PORT].channels =
2256				arg->patch[0];
2257			data->page.audio.port[RIGHT_PORT].channels =
2258				arg->patch[1];
2259			data->page.audio.port[2].channels = arg->patch[2];
2260			data->page.audio.port[3].channels = arg->patch[3];
2261			error = cdsetmode(periph, data);
2262			free(data, M_TEMP);
2263		}
2264		break;
2265	case CDIOCGETVOL:
2266		{
2267			struct ioc_vol *arg = (struct ioc_vol *) addr;
2268			struct cd_mode_data *data;
2269
2270			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2271				  ("trying to do CDIOCGETVOL\n"));
2272
2273			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2274				      M_WAITOK);
2275			error = cdgetmode(periph, data, AUDIO_PAGE);
2276			if (error) {
2277				free(data, M_TEMP);
2278				break;
2279			}
2280			arg->vol[LEFT_PORT] =
2281				data->page.audio.port[LEFT_PORT].volume;
2282			arg->vol[RIGHT_PORT] =
2283				data->page.audio.port[RIGHT_PORT].volume;
2284			arg->vol[2] = data->page.audio.port[2].volume;
2285			arg->vol[3] = data->page.audio.port[3].volume;
2286			free(data, M_TEMP);
2287		}
2288		break;
2289	case CDIOCSETVOL:
2290		{
2291			struct ioc_vol *arg = (struct ioc_vol *) addr;
2292			struct cd_mode_data *data;
2293
2294			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2295				  ("trying to do CDIOCSETVOL\n"));
2296
2297			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2298				      M_WAITOK);
2299			error = cdgetmode(periph, data, AUDIO_PAGE);
2300			if (error) {
2301				free(data, M_TEMP);
2302				break;
2303			}
2304			data->page.audio.port[LEFT_PORT].channels = CHANNEL_0;
2305			data->page.audio.port[LEFT_PORT].volume =
2306				arg->vol[LEFT_PORT];
2307			data->page.audio.port[RIGHT_PORT].channels = CHANNEL_1;
2308			data->page.audio.port[RIGHT_PORT].volume =
2309				arg->vol[RIGHT_PORT];
2310			data->page.audio.port[2].volume = arg->vol[2];
2311			data->page.audio.port[3].volume = arg->vol[3];
2312			error = cdsetmode(periph, data);
2313			free(data, M_TEMP);
2314		}
2315		break;
2316	case CDIOCSETMONO:
2317		{
2318			struct cd_mode_data *data;
2319
2320			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2321				  ("trying to do CDIOCSETMONO\n"));
2322
2323			data = malloc(sizeof(struct cd_mode_data),
2324				      M_TEMP, M_WAITOK);
2325			error = cdgetmode(periph, data, AUDIO_PAGE);
2326			if (error) {
2327				free(data, M_TEMP);
2328				break;
2329			}
2330			data->page.audio.port[LEFT_PORT].channels =
2331				LEFT_CHANNEL | RIGHT_CHANNEL;
2332			data->page.audio.port[RIGHT_PORT].channels =
2333				LEFT_CHANNEL | RIGHT_CHANNEL;
2334			data->page.audio.port[2].channels = 0;
2335			data->page.audio.port[3].channels = 0;
2336			error = cdsetmode(periph, data);
2337			free(data, M_TEMP);
2338		}
2339		break;
2340	case CDIOCSETSTEREO:
2341		{
2342			struct cd_mode_data *data;
2343
2344			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2345				  ("trying to do CDIOCSETSTEREO\n"));
2346
2347			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2348				      M_WAITOK);
2349			error = cdgetmode(periph, data, AUDIO_PAGE);
2350			if (error) {
2351				free(data, M_TEMP);
2352				break;
2353			}
2354			data->page.audio.port[LEFT_PORT].channels =
2355				LEFT_CHANNEL;
2356			data->page.audio.port[RIGHT_PORT].channels =
2357				RIGHT_CHANNEL;
2358			data->page.audio.port[2].channels = 0;
2359			data->page.audio.port[3].channels = 0;
2360			error = cdsetmode(periph, data);
2361			free(data, M_TEMP);
2362		}
2363		break;
2364	case CDIOCSETMUTE:
2365		{
2366			struct cd_mode_data *data;
2367
2368			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2369				  ("trying to do CDIOCSETMUTE\n"));
2370
2371			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2372				      M_WAITOK);
2373			error = cdgetmode(periph, data, AUDIO_PAGE);
2374			if (error) {
2375				free(data, M_TEMP);
2376				break;
2377			}
2378			data->page.audio.port[LEFT_PORT].channels = 0;
2379			data->page.audio.port[RIGHT_PORT].channels = 0;
2380			data->page.audio.port[2].channels = 0;
2381			data->page.audio.port[3].channels = 0;
2382			error = cdsetmode(periph, data);
2383			free(data, M_TEMP);
2384		}
2385		break;
2386	case CDIOCSETLEFT:
2387		{
2388			struct cd_mode_data *data;
2389
2390			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2391				  ("trying to do CDIOCSETLEFT\n"));
2392
2393			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2394				      M_WAITOK);
2395			error = cdgetmode(periph, data, AUDIO_PAGE);
2396			if (error) {
2397				free(data, M_TEMP);
2398				break;
2399			}
2400			data->page.audio.port[LEFT_PORT].channels =
2401				LEFT_CHANNEL;
2402			data->page.audio.port[RIGHT_PORT].channels =
2403				LEFT_CHANNEL;
2404			data->page.audio.port[2].channels = 0;
2405			data->page.audio.port[3].channels = 0;
2406			error = cdsetmode(periph, data);
2407			free(data, M_TEMP);
2408		}
2409		break;
2410	case CDIOCSETRIGHT:
2411		{
2412			struct cd_mode_data *data;
2413
2414			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2415				  ("trying to do CDIOCSETRIGHT\n"));
2416
2417			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2418				      M_WAITOK);
2419			error = cdgetmode(periph, data, AUDIO_PAGE);
2420			if (error) {
2421				free(data, M_TEMP);
2422				break;
2423			}
2424			data->page.audio.port[LEFT_PORT].channels =
2425				RIGHT_CHANNEL;
2426			data->page.audio.port[RIGHT_PORT].channels =
2427				RIGHT_CHANNEL;
2428			data->page.audio.port[2].channels = 0;
2429			data->page.audio.port[3].channels = 0;
2430			error = cdsetmode(periph, data);
2431			free(data, M_TEMP);
2432		}
2433		break;
2434	case CDIOCRESUME:
2435		error = cdpause(periph, 1);
2436		break;
2437	case CDIOCPAUSE:
2438		error = cdpause(periph, 0);
2439		break;
2440	case CDIOCSTART:
2441		error = cdstartunit(periph);
2442		break;
2443	case CDIOCSTOP:
2444		error = cdstopunit(periph, 0);
2445		break;
2446	case CDIOCEJECT:
2447		error = cdstopunit(periph, 1);
2448		break;
2449	case CDIOCALLOW:
2450		cdprevent(periph, PR_ALLOW);
2451		break;
2452	case CDIOCPREVENT:
2453		cdprevent(periph, PR_PREVENT);
2454		break;
2455	case CDIOCSETDEBUG:
2456		/* sc_link->flags |= (SDEV_DB1 | SDEV_DB2); */
2457		error = ENOTTY;
2458		break;
2459	case CDIOCCLRDEBUG:
2460		/* sc_link->flags &= ~(SDEV_DB1 | SDEV_DB2); */
2461		error = ENOTTY;
2462		break;
2463	case CDIOCRESET:
2464		/* return (cd_reset(periph)); */
2465		error = ENOTTY;
2466		break;
2467	default:
2468		if (cmd == DIOCSBAD) {
2469			error = EINVAL;	/* XXX */
2470			break;
2471		}
2472
2473		/*
2474		 * Check to see whether we've got a disk-type ioctl.  If we
2475		 * don't, dsioctl will pass back an error code of ENOIOCTL.
2476		 */
2477		error = dsioctl("cd", dev, cmd, addr, flag, &softc->cd_slices,
2478				cdstrategy, (ds_setgeom_t *)NULL);
2479
2480		if (error != ENOIOCTL)
2481			break;
2482
2483		error = cam_periph_ioctl(periph, cmd, addr, cderror);
2484		break;
2485	}
2486
2487	cam_periph_unlock(periph);
2488
2489	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdioctl\n"));
2490
2491	return (error);
2492}
2493
2494static void
2495cdprevent(struct cam_periph *periph, int action)
2496{
2497	union	ccb *ccb;
2498	struct	cd_softc *softc;
2499	int	error;
2500
2501	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdprevent\n"));
2502
2503	softc = (struct cd_softc *)periph->softc;
2504
2505	if (((action == PR_ALLOW)
2506	  && (softc->flags & CD_FLAG_DISC_LOCKED) == 0)
2507	 || ((action == PR_PREVENT)
2508	  && (softc->flags & CD_FLAG_DISC_LOCKED) != 0)) {
2509		return;
2510	}
2511
2512	ccb = cdgetccb(periph, /* priority */ 1);
2513
2514	scsi_prevent(&ccb->csio,
2515		     /*retries*/ 1,
2516		     cddone,
2517		     MSG_SIMPLE_Q_TAG,
2518		     action,
2519		     SSD_FULL_SIZE,
2520		     /* timeout */60000);
2521
2522	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2523				  /*sense_flags*/SF_RETRY_UA|SF_NO_PRINT);
2524
2525	xpt_release_ccb(ccb);
2526
2527	if (error == 0) {
2528		if (action == PR_ALLOW)
2529			softc->flags &= ~CD_FLAG_DISC_LOCKED;
2530		else
2531			softc->flags |= CD_FLAG_DISC_LOCKED;
2532	}
2533}
2534
2535static int
2536cdsize(dev_t dev, u_int32_t *size)
2537{
2538	struct cam_periph *periph;
2539	struct cd_softc *softc;
2540	union ccb *ccb;
2541	struct scsi_read_capacity_data *rcap_buf;
2542	int error;
2543
2544	periph = cam_extend_get(cdperiphs, dkunit(dev));
2545
2546	if (periph == NULL)
2547		return (ENXIO);
2548
2549	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdsize\n"));
2550
2551	softc = (struct cd_softc *)periph->softc;
2552
2553	ccb = cdgetccb(periph, /* priority */ 1);
2554
2555	rcap_buf = malloc(sizeof(struct scsi_read_capacity_data),
2556			  M_TEMP, M_WAITOK);
2557
2558	scsi_read_capacity(&ccb->csio,
2559			   /*retries*/ 1,
2560			   cddone,
2561			   MSG_SIMPLE_Q_TAG,
2562			   rcap_buf,
2563			   SSD_FULL_SIZE,
2564			   /* timeout */20000);
2565
2566	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2567				  /*sense_flags*/SF_RETRY_UA|SF_NO_PRINT);
2568
2569	xpt_release_ccb(ccb);
2570
2571	softc->params.disksize = scsi_4btoul(rcap_buf->addr) + 1;
2572	softc->params.blksize  = scsi_4btoul(rcap_buf->length);
2573
2574	free(rcap_buf, M_TEMP);
2575	*size = softc->params.disksize;
2576
2577	return (error);
2578
2579}
2580
2581static int
2582cderror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
2583{
2584	struct cd_softc *softc;
2585	struct cam_periph *periph;
2586
2587	periph = xpt_path_periph(ccb->ccb_h.path);
2588	softc = (struct cd_softc *)periph->softc;
2589
2590	/*
2591	 * XXX
2592	 * Until we have a better way of doing pack validation,
2593	 * don't treat UAs as errors.
2594	 */
2595	sense_flags |= SF_RETRY_UA;
2596	return (cam_periph_error(ccb, cam_flags, sense_flags,
2597				 &softc->saved_ccb));
2598}
2599
2600/*
2601 * Read table of contents
2602 */
2603static int
2604cdreadtoc(struct cam_periph *periph, u_int32_t mode, u_int32_t start,
2605	    struct cd_toc_entry *data, u_int32_t len)
2606{
2607	struct scsi_read_toc *scsi_cmd;
2608	u_int32_t ntoc;
2609        struct ccb_scsiio *csio;
2610	union ccb *ccb;
2611	int error;
2612
2613	ntoc = len;
2614	error = 0;
2615
2616	ccb = cdgetccb(periph, /* priority */ 1);
2617
2618	csio = &ccb->csio;
2619
2620	cam_fill_csio(csio,
2621		      /* retries */ 1,
2622		      /* cbfcnp */ cddone,
2623		      /* flags */ CAM_DIR_IN,
2624		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2625		      /* data_ptr */ (u_int8_t *)data,
2626		      /* dxfer_len */ len,
2627		      /* sense_len */ SSD_FULL_SIZE,
2628		      sizeof(struct scsi_read_toc),
2629 		      /* timeout */ 50000);
2630
2631	scsi_cmd = (struct scsi_read_toc *)&csio->cdb_io.cdb_bytes;
2632	bzero (scsi_cmd, sizeof(*scsi_cmd));
2633
2634	if (mode == CD_MSF_FORMAT)
2635		scsi_cmd->byte2 |= CD_MSF;
2636	scsi_cmd->from_track = start;
2637	/* scsi_ulto2b(ntoc, (u_int8_t *)scsi_cmd->data_len); */
2638	scsi_cmd->data_len[0] = (ntoc) >> 8;
2639	scsi_cmd->data_len[1] = (ntoc) & 0xff;
2640
2641	scsi_cmd->op_code = READ_TOC;
2642
2643	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2644				  /*sense_flags*/SF_RETRY_UA);
2645
2646	xpt_release_ccb(ccb);
2647
2648	return(error);
2649}
2650
2651static int
2652cdreadsubchannel(struct cam_periph *periph, u_int32_t mode,
2653		 u_int32_t format, int track,
2654		 struct cd_sub_channel_info *data, u_int32_t len)
2655{
2656	struct scsi_read_subchannel *scsi_cmd;
2657        struct ccb_scsiio *csio;
2658	union ccb *ccb;
2659	int error;
2660
2661	error = 0;
2662
2663	ccb = cdgetccb(periph, /* priority */ 1);
2664
2665	csio = &ccb->csio;
2666
2667	cam_fill_csio(csio,
2668		      /* retries */ 1,
2669		      /* cbfcnp */ cddone,
2670		      /* flags */ CAM_DIR_IN,
2671		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2672		      /* data_ptr */ (u_int8_t *)data,
2673		      /* dxfer_len */ len,
2674		      /* sense_len */ SSD_FULL_SIZE,
2675		      sizeof(struct scsi_read_subchannel),
2676 		      /* timeout */ 50000);
2677
2678	scsi_cmd = (struct scsi_read_subchannel *)&csio->cdb_io.cdb_bytes;
2679	bzero (scsi_cmd, sizeof(*scsi_cmd));
2680
2681	scsi_cmd->op_code = READ_SUBCHANNEL;
2682	if (mode == CD_MSF_FORMAT)
2683		scsi_cmd->byte1 |= CD_MSF;
2684	scsi_cmd->byte2 = SRS_SUBQ;
2685	scsi_cmd->subchan_format = format;
2686	scsi_cmd->track = track;
2687	scsi_ulto2b(len, (u_int8_t *)scsi_cmd->data_len);
2688	scsi_cmd->control = 0;
2689
2690	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2691				  /*sense_flags*/SF_RETRY_UA);
2692
2693	xpt_release_ccb(ccb);
2694
2695	return(error);
2696}
2697
2698
2699static int
2700cdgetmode(struct cam_periph *periph, struct cd_mode_data *data, u_int32_t page)
2701{
2702	struct scsi_mode_sense_6 *scsi_cmd;
2703        struct ccb_scsiio *csio;
2704	union ccb *ccb;
2705	int error;
2706
2707	ccb = cdgetccb(periph, /* priority */ 1);
2708
2709	csio = &ccb->csio;
2710
2711	bzero(data, sizeof(*data));
2712	cam_fill_csio(csio,
2713		      /* retries */ 1,
2714		      /* cbfcnp */ cddone,
2715		      /* flags */ CAM_DIR_IN,
2716		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2717		      /* data_ptr */ (u_int8_t *)data,
2718		      /* dxfer_len */ sizeof(*data),
2719		      /* sense_len */ SSD_FULL_SIZE,
2720		      sizeof(struct scsi_mode_sense_6),
2721 		      /* timeout */ 50000);
2722
2723	scsi_cmd = (struct scsi_mode_sense_6 *)&csio->cdb_io.cdb_bytes;
2724	bzero (scsi_cmd, sizeof(*scsi_cmd));
2725
2726	scsi_cmd->page = page;
2727	scsi_cmd->length = sizeof(*data) & 0xff;
2728	scsi_cmd->opcode = MODE_SENSE;
2729
2730	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2731				  /*sense_flags*/SF_RETRY_UA);
2732
2733	xpt_release_ccb(ccb);
2734
2735	return(error);
2736}
2737
2738static int
2739cdsetmode(struct cam_periph *periph, struct cd_mode_data *data)
2740{
2741	struct scsi_mode_select_6 *scsi_cmd;
2742        struct ccb_scsiio *csio;
2743	union ccb *ccb;
2744	int error;
2745
2746	ccb = cdgetccb(periph, /* priority */ 1);
2747
2748	csio = &ccb->csio;
2749
2750	error = 0;
2751
2752	cam_fill_csio(csio,
2753		      /* retries */ 1,
2754		      /* cbfcnp */ cddone,
2755		      /* flags */ CAM_DIR_OUT,
2756		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2757		      /* data_ptr */ (u_int8_t *)data,
2758		      /* dxfer_len */ sizeof(*data),
2759		      /* sense_len */ SSD_FULL_SIZE,
2760		      sizeof(struct scsi_mode_select_6),
2761 		      /* timeout */ 50000);
2762
2763	scsi_cmd = (struct scsi_mode_select_6 *)&csio->cdb_io.cdb_bytes;
2764
2765	bzero(scsi_cmd, sizeof(*scsi_cmd));
2766	scsi_cmd->opcode = MODE_SELECT;
2767	scsi_cmd->byte2 |= SMS_PF;
2768	scsi_cmd->length = sizeof(*data) & 0xff;
2769	data->header.data_length = 0;
2770	/*
2771	 * SONY drives do not allow a mode select with a medium_type
2772	 * value that has just been returned by a mode sense; use a
2773	 * medium_type of 0 (Default) instead.
2774	 */
2775	data->header.medium_type = 0;
2776
2777	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2778				  /*sense_flags*/SF_RETRY_UA);
2779
2780	xpt_release_ccb(ccb);
2781
2782	return(error);
2783}
2784
2785
2786static int
2787cdplay(struct cam_periph *periph, u_int32_t blk, u_int32_t len)
2788{
2789	struct ccb_scsiio *csio;
2790	union ccb *ccb;
2791	int error;
2792	u_int8_t cdb_len;
2793
2794	error = 0;
2795	ccb = cdgetccb(periph, /* priority */ 1);
2796	csio = &ccb->csio;
2797	/*
2798	 * Use the smallest possible command to perform the operation.
2799	 */
2800	if ((len & 0xffff0000) == 0) {
2801		/*
2802		 * We can fit in a 10 byte cdb.
2803		 */
2804		struct scsi_play_10 *scsi_cmd;
2805
2806		scsi_cmd = (struct scsi_play_10 *)&csio->cdb_io.cdb_bytes;
2807		bzero (scsi_cmd, sizeof(*scsi_cmd));
2808		scsi_cmd->op_code = PLAY_10;
2809		scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
2810		scsi_ulto2b(len, (u_int8_t *)scsi_cmd->xfer_len);
2811		cdb_len = sizeof(*scsi_cmd);
2812	} else  {
2813		struct scsi_play_12 *scsi_cmd;
2814
2815		scsi_cmd = (struct scsi_play_12 *)&csio->cdb_io.cdb_bytes;
2816		bzero (scsi_cmd, sizeof(*scsi_cmd));
2817		scsi_cmd->op_code = PLAY_12;
2818		scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
2819		scsi_ulto4b(len, (u_int8_t *)scsi_cmd->xfer_len);
2820		cdb_len = sizeof(*scsi_cmd);
2821	}
2822	cam_fill_csio(csio,
2823		      /*retries*/2,
2824		      cddone,
2825		      /*flags*/CAM_DIR_NONE,
2826		      MSG_SIMPLE_Q_TAG,
2827		      /*dataptr*/NULL,
2828		      /*datalen*/0,
2829		      /*sense_len*/SSD_FULL_SIZE,
2830		      cdb_len,
2831		      /*timeout*/50 * 1000);
2832
2833	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2834			 /*sense_flags*/SF_RETRY_UA);
2835
2836	xpt_release_ccb(ccb);
2837
2838	return(error);
2839}
2840
2841static int
2842cdplaymsf(struct cam_periph *periph, u_int32_t startm, u_int32_t starts,
2843	  u_int32_t startf, u_int32_t endm, u_int32_t ends, u_int32_t endf)
2844{
2845	struct scsi_play_msf *scsi_cmd;
2846        struct ccb_scsiio *csio;
2847	union ccb *ccb;
2848	int error;
2849
2850	error = 0;
2851
2852	ccb = cdgetccb(periph, /* priority */ 1);
2853
2854	csio = &ccb->csio;
2855
2856	cam_fill_csio(csio,
2857		      /* retries */ 1,
2858		      /* cbfcnp */ cddone,
2859		      /* flags */ CAM_DIR_NONE,
2860		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2861		      /* data_ptr */ NULL,
2862		      /* dxfer_len */ 0,
2863		      /* sense_len */ SSD_FULL_SIZE,
2864		      sizeof(struct scsi_play_msf),
2865 		      /* timeout */ 50000);
2866
2867	scsi_cmd = (struct scsi_play_msf *)&csio->cdb_io.cdb_bytes;
2868	bzero (scsi_cmd, sizeof(*scsi_cmd));
2869
2870        scsi_cmd->op_code = PLAY_MSF;
2871        scsi_cmd->start_m = startm;
2872        scsi_cmd->start_s = starts;
2873        scsi_cmd->start_f = startf;
2874        scsi_cmd->end_m = endm;
2875        scsi_cmd->end_s = ends;
2876        scsi_cmd->end_f = endf;
2877
2878	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2879				  /*sense_flags*/SF_RETRY_UA);
2880
2881	xpt_release_ccb(ccb);
2882
2883	return(error);
2884}
2885
2886
2887static int
2888cdplaytracks(struct cam_periph *periph, u_int32_t strack, u_int32_t sindex,
2889	     u_int32_t etrack, u_int32_t eindex)
2890{
2891	struct scsi_play_track *scsi_cmd;
2892        struct ccb_scsiio *csio;
2893	union ccb *ccb;
2894	int error;
2895
2896	error = 0;
2897
2898	ccb = cdgetccb(periph, /* priority */ 1);
2899
2900	csio = &ccb->csio;
2901
2902	cam_fill_csio(csio,
2903		      /* retries */ 1,
2904		      /* cbfcnp */ cddone,
2905		      /* flags */ CAM_DIR_NONE,
2906		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2907		      /* data_ptr */ NULL,
2908		      /* dxfer_len */ 0,
2909		      /* sense_len */ SSD_FULL_SIZE,
2910		      sizeof(struct scsi_play_track),
2911 		      /* timeout */ 50000);
2912
2913	scsi_cmd = (struct scsi_play_track *)&csio->cdb_io.cdb_bytes;
2914	bzero (scsi_cmd, sizeof(*scsi_cmd));
2915
2916        scsi_cmd->op_code = PLAY_TRACK;
2917        scsi_cmd->start_track = strack;
2918        scsi_cmd->start_index = sindex;
2919        scsi_cmd->end_track = etrack;
2920        scsi_cmd->end_index = eindex;
2921
2922	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2923				  /*sense_flags*/SF_RETRY_UA);
2924
2925	xpt_release_ccb(ccb);
2926
2927	return(error);
2928}
2929
2930static int
2931cdpause(struct cam_periph *periph, u_int32_t go)
2932{
2933	struct scsi_pause *scsi_cmd;
2934        struct ccb_scsiio *csio;
2935	union ccb *ccb;
2936	int error;
2937
2938	error = 0;
2939
2940	ccb = cdgetccb(periph, /* priority */ 1);
2941
2942	csio = &ccb->csio;
2943
2944	cam_fill_csio(csio,
2945		      /* retries */ 1,
2946		      /* cbfcnp */ cddone,
2947		      /* flags */ CAM_DIR_NONE,
2948		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2949		      /* data_ptr */ NULL,
2950		      /* dxfer_len */ 0,
2951		      /* sense_len */ SSD_FULL_SIZE,
2952		      sizeof(struct scsi_pause),
2953 		      /* timeout */ 50000);
2954
2955	scsi_cmd = (struct scsi_pause *)&csio->cdb_io.cdb_bytes;
2956	bzero (scsi_cmd, sizeof(*scsi_cmd));
2957
2958        scsi_cmd->op_code = PAUSE;
2959	scsi_cmd->resume = go;
2960
2961	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2962				  /*sense_flags*/SF_RETRY_UA);
2963
2964	xpt_release_ccb(ccb);
2965
2966	return(error);
2967}
2968
2969static int
2970cdstartunit(struct cam_periph *periph)
2971{
2972	union ccb *ccb;
2973	int error;
2974
2975	error = 0;
2976
2977	ccb = cdgetccb(periph, /* priority */ 1);
2978
2979	scsi_start_stop(&ccb->csio,
2980			/* retries */ 1,
2981			/* cbfcnp */ cddone,
2982			/* tag_action */ MSG_SIMPLE_Q_TAG,
2983			/* start */ TRUE,
2984			/* load_eject */ TRUE,
2985			/* immediate */ FALSE,
2986			/* sense_len */ SSD_FULL_SIZE,
2987			/* timeout */ 50000);
2988
2989	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2990				  /*sense_flags*/SF_RETRY_UA);
2991
2992	xpt_release_ccb(ccb);
2993
2994	return(error);
2995}
2996
2997static int
2998cdstopunit(struct cam_periph *periph, u_int32_t eject)
2999{
3000	union ccb *ccb;
3001	int error;
3002
3003	error = 0;
3004
3005	ccb = cdgetccb(periph, /* priority */ 1);
3006
3007	scsi_start_stop(&ccb->csio,
3008			/* retries */ 1,
3009			/* cbfcnp */ cddone,
3010			/* tag_action */ MSG_SIMPLE_Q_TAG,
3011			/* start */ FALSE,
3012			/* load_eject */ eject,
3013			/* immediate */ FALSE,
3014			/* sense_len */ SSD_FULL_SIZE,
3015			/* timeout */ 50000);
3016
3017	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3018				  /*sense_flags*/SF_RETRY_UA);
3019
3020	xpt_release_ccb(ccb);
3021
3022	return(error);
3023}
3024