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