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