scsi_cd.c revision 72119
1/*
2 * Copyright (c) 1997 Justin T. Gibbs.
3 * Copyright (c) 1997, 1998, 1999, 2000, 2001 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 72119 2001-02-07 07:05:59Z peter $
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/bio.h>
55#include <sys/conf.h>
56#include <sys/disk.h>
57#include <sys/malloc.h>
58#include <sys/cdio.h>
59#include <sys/dvdio.h>
60#include <sys/devicestat.h>
61#include <sys/sysctl.h>
62
63#include <cam/cam.h>
64#include <cam/cam_ccb.h>
65#include <cam/cam_extend.h>
66#include <cam/cam_periph.h>
67#include <cam/cam_xpt_periph.h>
68#include <cam/cam_queue.h>
69
70#include <cam/scsi/scsi_message.h>
71#include <cam/scsi/scsi_da.h>
72#include <cam/scsi/scsi_cd.h>
73
74#define LEADOUT         0xaa            /* leadout toc entry */
75
76struct cd_params {
77	u_int32_t blksize;
78	u_long    disksize;
79};
80
81typedef enum {
82	CD_Q_NONE	= 0x00,
83	CD_Q_NO_TOUCH	= 0x01,
84	CD_Q_BCD_TRACKS	= 0x02,
85	CD_Q_NO_CHANGER	= 0x04,
86	CD_Q_CHANGER	= 0x08
87} cd_quirks;
88
89typedef enum {
90	CD_FLAG_INVALID		= 0x001,
91	CD_FLAG_NEW_DISC	= 0x002,
92	CD_FLAG_DISC_LOCKED	= 0x004,
93	CD_FLAG_DISC_REMOVABLE	= 0x008,
94	CD_FLAG_TAGGED_QUEUING	= 0x010,
95	CD_FLAG_CHANGER		= 0x040,
96	CD_FLAG_ACTIVE		= 0x080,
97	CD_FLAG_SCHED_ON_COMP	= 0x100,
98	CD_FLAG_RETRY_UA	= 0x200
99} cd_flags;
100
101typedef enum {
102	CD_CCB_PROBE		= 0x01,
103	CD_CCB_BUFFER_IO	= 0x02,
104	CD_CCB_WAITING		= 0x03,
105	CD_CCB_TYPE_MASK	= 0x0F,
106	CD_CCB_RETRY_UA		= 0x10
107} cd_ccb_state;
108
109typedef enum {
110	CHANGER_TIMEOUT_SCHED		= 0x01,
111	CHANGER_SHORT_TMOUT_SCHED	= 0x02,
112	CHANGER_MANUAL_CALL		= 0x04,
113	CHANGER_NEED_TIMEOUT		= 0x08
114} cd_changer_flags;
115
116#define ccb_state ppriv_field0
117#define ccb_bp ppriv_ptr1
118
119typedef enum {
120	CD_STATE_PROBE,
121	CD_STATE_NORMAL
122} cd_state;
123
124struct cd_softc {
125	cam_pinfo		pinfo;
126	cd_state		state;
127	volatile cd_flags	flags;
128	struct bio_queue_head	bio_queue;
129	LIST_HEAD(, ccb_hdr)	pending_ccbs;
130	struct cd_params	params;
131	struct disk	 	disk;
132	union ccb		saved_ccb;
133	cd_quirks		quirks;
134	struct devstat		device_stats;
135	STAILQ_ENTRY(cd_softc)	changer_links;
136	struct cdchanger	*changer;
137	int			bufs_left;
138	struct cam_periph	*periph;
139};
140
141struct cd_quirk_entry {
142	struct scsi_inquiry_pattern inq_pat;
143	cd_quirks quirks;
144};
145
146/*
147 * These quirk entries aren't strictly necessary.  Basically, what they do
148 * is tell cdregister() up front that a device is a changer.  Otherwise, it
149 * will figure that fact out once it sees a LUN on the device that is
150 * greater than 0.  If it is known up front that a device is a changer, all
151 * I/O to the device will go through the changer scheduling routines, as
152 * opposed to the "normal" CD code.
153 */
154static struct cd_quirk_entry cd_quirk_table[] =
155{
156	{
157		{ T_CDROM, SIP_MEDIA_REMOVABLE, "NRC", "MBR-7", "*"},
158		 /*quirks*/ CD_Q_CHANGER
159	},
160	{
161		{ T_CDROM, SIP_MEDIA_REMOVABLE, "PIONEER", "CD-ROM DRM*",
162		  "*"}, /* quirks */ CD_Q_CHANGER
163	},
164	{
165		{ T_CDROM, SIP_MEDIA_REMOVABLE, "NAKAMICH", "MJ-*", "*"},
166		 /* quirks */ CD_Q_CHANGER
167	},
168	{
169		{ T_CDROM, SIP_MEDIA_REMOVABLE, "CHINON", "CD-ROM CDS-535","*"},
170		/* quirks */ CD_Q_BCD_TRACKS
171	}
172};
173
174#ifndef MIN
175#define MIN(x,y) ((x<y) ? x : y)
176#endif
177
178#define CD_CDEV_MAJOR 15
179#define CD_BDEV_MAJOR 6
180
181static	d_open_t	cdopen;
182static	d_close_t	cdclose;
183static	d_ioctl_t	cdioctl;
184static	d_strategy_t	cdstrategy;
185
186static	periph_init_t	cdinit;
187static	periph_ctor_t	cdregister;
188static	periph_dtor_t	cdcleanup;
189static	periph_start_t	cdstart;
190static	periph_oninv_t	cdoninvalidate;
191static	void		cdasync(void *callback_arg, u_int32_t code,
192				struct cam_path *path, void *arg);
193static	void		cdshorttimeout(void *arg);
194static	void		cdschedule(struct cam_periph *periph, int priority);
195static	void		cdrunchangerqueue(void *arg);
196static	void		cdchangerschedule(struct cd_softc *softc);
197static	int		cdrunccb(union ccb *ccb,
198				 int (*error_routine)(union ccb *ccb,
199						      u_int32_t cam_flags,
200						      u_int32_t sense_flags),
201				 u_int32_t cam_flags, u_int32_t sense_flags);
202static union	ccb 	*cdgetccb(struct cam_periph *periph,
203				  u_int32_t priority);
204static	void		cddone(struct cam_periph *periph,
205			       union ccb *start_ccb);
206static	int		cderror(union ccb *ccb, u_int32_t cam_flags,
207				u_int32_t sense_flags);
208static	void		cdprevent(struct cam_periph *periph, int action);
209static	int		cdsize(dev_t dev, u_int32_t *size);
210static	int		cdfirsttrackisdata(struct cam_periph *periph);
211static	int		cdreadtoc(struct cam_periph *periph, u_int32_t mode,
212				  u_int32_t start, struct cd_toc_entry *data,
213				  u_int32_t len);
214static	int		cdgetmode(struct cam_periph *periph,
215				  struct cd_mode_data *data, u_int32_t page);
216static	int		cdsetmode(struct cam_periph *periph,
217				  struct cd_mode_data *data);
218static	int		cdplay(struct cam_periph *periph, u_int32_t blk,
219			       u_int32_t len);
220static	int		cdreadsubchannel(struct cam_periph *periph,
221					 u_int32_t mode, u_int32_t format,
222					 int track,
223					 struct cd_sub_channel_info *data,
224					 u_int32_t len);
225static	int		cdplaymsf(struct cam_periph *periph, u_int32_t startm,
226				  u_int32_t starts, u_int32_t startf,
227				  u_int32_t endm, u_int32_t ends,
228				  u_int32_t endf);
229static	int		cdplaytracks(struct cam_periph *periph,
230				     u_int32_t strack, u_int32_t sindex,
231				     u_int32_t etrack, u_int32_t eindex);
232static	int		cdpause(struct cam_periph *periph, u_int32_t go);
233static	int		cdstopunit(struct cam_periph *periph, u_int32_t eject);
234static	int		cdstartunit(struct cam_periph *periph);
235static	int		cdreportkey(struct cam_periph *periph,
236				    struct dvd_authinfo *authinfo);
237static	int		cdsendkey(struct cam_periph *periph,
238				  struct dvd_authinfo *authinfo);
239static	int		cdreaddvdstructure(struct cam_periph *periph,
240					   struct dvd_struct *dvdstruct);
241
242static struct periph_driver cddriver =
243{
244	cdinit, "cd",
245	TAILQ_HEAD_INITIALIZER(cddriver.units), /* generation */ 0
246};
247
248PERIPHDRIVER_DECLARE(cd, cddriver);
249
250/* For 2.2-stable support */
251#ifndef D_DISK
252#define D_DISK 0
253#endif
254static struct cdevsw cd_cdevsw = {
255	/* open */	cdopen,
256	/* close */	cdclose,
257	/* read */	physread,
258	/* write */	physwrite,
259	/* ioctl */	cdioctl,
260	/* poll */	nopoll,
261	/* mmap */	nommap,
262	/* strategy */	cdstrategy,
263	/* name */	"cd",
264	/* maj */	CD_CDEV_MAJOR,
265	/* dump */	nodump,
266	/* psize */	nopsize,
267	/* flags */	D_DISK,
268	/* bmaj */	CD_BDEV_MAJOR
269};
270static struct cdevsw cddisk_cdevsw;
271
272static struct extend_array *cdperiphs;
273static int num_changers;
274
275#ifndef CHANGER_MIN_BUSY_SECONDS
276#define CHANGER_MIN_BUSY_SECONDS	5
277#endif
278#ifndef CHANGER_MAX_BUSY_SECONDS
279#define CHANGER_MAX_BUSY_SECONDS	15
280#endif
281
282static int changer_min_busy_seconds = CHANGER_MIN_BUSY_SECONDS;
283static int changer_max_busy_seconds = CHANGER_MAX_BUSY_SECONDS;
284
285/*
286 * XXX KDM this CAM node should be moved if we ever get more CAM sysctl
287 * variables.
288 */
289SYSCTL_NODE(_kern, OID_AUTO, cam, CTLFLAG_RD, 0, "CAM Subsystem");
290SYSCTL_NODE(_kern_cam, OID_AUTO, cd, CTLFLAG_RD, 0, "CAM CDROM driver");
291SYSCTL_NODE(_kern_cam_cd, OID_AUTO, changer, CTLFLAG_RD, 0, "CD Changer");
292SYSCTL_INT(_kern_cam_cd_changer, OID_AUTO, min_busy_seconds, CTLFLAG_RW,
293	   &changer_min_busy_seconds, 0, "Minimum changer scheduling quantum");
294SYSCTL_INT(_kern_cam_cd_changer, OID_AUTO, max_busy_seconds, CTLFLAG_RW,
295	   &changer_max_busy_seconds, 0, "Maximum changer scheduling quantum");
296
297struct cdchanger {
298	path_id_t			 path_id;
299	target_id_t			 target_id;
300	int				 num_devices;
301	struct camq			 devq;
302	struct timeval			 start_time;
303	struct cd_softc			 *cur_device;
304	struct callout_handle		 short_handle;
305	struct callout_handle		 long_handle;
306	volatile cd_changer_flags	 flags;
307	STAILQ_ENTRY(cdchanger)		 changer_links;
308	STAILQ_HEAD(chdevlist, cd_softc) chluns;
309};
310
311static STAILQ_HEAD(changerlist, cdchanger) changerq;
312
313void
314cdinit(void)
315{
316	cam_status status;
317	struct cam_path *path;
318
319	/*
320	 * Create our extend array for storing the devices we attach to.
321	 */
322	cdperiphs = cam_extend_new();
323	if (cdperiphs == NULL) {
324		printf("cd: Failed to alloc extend array!\n");
325		return;
326	}
327
328	/*
329	 * Install a global async callback.  This callback will
330	 * receive async callbacks like "new device found".
331	 */
332	status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
333				 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
334
335	if (status == CAM_REQ_CMP) {
336		struct ccb_setasync csa;
337
338                xpt_setup_ccb(&csa.ccb_h, path, /*priority*/5);
339                csa.ccb_h.func_code = XPT_SASYNC_CB;
340                csa.event_enable = AC_FOUND_DEVICE;
341                csa.callback = cdasync;
342                csa.callback_arg = NULL;
343                xpt_action((union ccb *)&csa);
344		status = csa.ccb_h.status;
345                xpt_free_path(path);
346        }
347
348	if (status != CAM_REQ_CMP) {
349		printf("cd: Failed to attach master async callback "
350		       "due to status 0x%x!\n", status);
351	}
352}
353
354static void
355cdoninvalidate(struct cam_periph *periph)
356{
357	int s;
358	struct cd_softc *softc;
359	struct bio *q_bp;
360	struct ccb_setasync csa;
361
362	softc = (struct cd_softc *)periph->softc;
363
364	/*
365	 * De-register any async callbacks.
366	 */
367	xpt_setup_ccb(&csa.ccb_h, periph->path,
368		      /* priority */ 5);
369	csa.ccb_h.func_code = XPT_SASYNC_CB;
370	csa.event_enable = 0;
371	csa.callback = cdasync;
372	csa.callback_arg = periph;
373	xpt_action((union ccb *)&csa);
374
375	softc->flags |= CD_FLAG_INVALID;
376
377	/*
378	 * Although the oninvalidate() routines are always called at
379	 * splsoftcam, we need to be at splbio() here to keep the buffer
380	 * queue from being modified while we traverse it.
381	 */
382	s = splbio();
383
384	/*
385	 * Return all queued I/O with ENXIO.
386	 * XXX Handle any transactions queued to the card
387	 *     with XPT_ABORT_CCB.
388	 */
389	while ((q_bp = bioq_first(&softc->bio_queue)) != NULL){
390		bioq_remove(&softc->bio_queue, q_bp);
391		q_bp->bio_resid = q_bp->bio_bcount;
392		q_bp->bio_error = ENXIO;
393		q_bp->bio_flags |= BIO_ERROR;
394		biodone(q_bp);
395	}
396	splx(s);
397
398	/*
399	 * If this device is part of a changer, and it was scheduled
400	 * to run, remove it from the run queue since we just nuked
401	 * all of its scheduled I/O.
402	 */
403	if ((softc->flags & CD_FLAG_CHANGER)
404	 && (softc->pinfo.index != CAM_UNQUEUED_INDEX))
405		camq_remove(&softc->changer->devq, softc->pinfo.index);
406
407	xpt_print_path(periph->path);
408	printf("lost device\n");
409}
410
411static void
412cdcleanup(struct cam_periph *periph)
413{
414	struct cd_softc *softc;
415	int s;
416
417	softc = (struct cd_softc *)periph->softc;
418
419	xpt_print_path(periph->path);
420	printf("removing device entry\n");
421
422	s = splsoftcam();
423	/*
424	 * In the queued, non-active case, the device in question
425	 * has already been removed from the changer run queue.  Since this
426	 * device is active, we need to de-activate it, and schedule
427	 * another device to run.  (if there is another one to run)
428	 */
429	if ((softc->flags & CD_FLAG_CHANGER)
430	 && (softc->flags & CD_FLAG_ACTIVE)) {
431
432		/*
433		 * The purpose of the short timeout is soley to determine
434		 * whether the current device has finished or not.  Well,
435		 * since we're removing the active device, we know that it
436		 * is finished.  So, get rid of the short timeout.
437		 * Otherwise, if we're in the time period before the short
438		 * timeout fires, and there are no other devices in the
439		 * queue to run, there won't be any other device put in the
440		 * active slot.  i.e., when we call cdrunchangerqueue()
441		 * below, it won't do anything.  Then, when the short
442		 * timeout fires, it'll look at the "current device", which
443		 * we are free below, and possibly panic the kernel on a
444		 * bogus pointer reference.
445		 *
446		 * The long timeout doesn't really matter, since we
447		 * decrement the qfrozen_cnt to indicate that there is
448		 * nothing in the active slot now.  Therefore, there won't
449		 * be any bogus pointer references there.
450		 */
451		if (softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
452			untimeout(cdshorttimeout, softc->changer,
453				  softc->changer->short_handle);
454			softc->changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
455		}
456		softc->changer->devq.qfrozen_cnt--;
457		softc->changer->flags |= CHANGER_MANUAL_CALL;
458		cdrunchangerqueue(softc->changer);
459	}
460
461	/*
462	 * If we're removing the last device on the changer, go ahead and
463	 * remove the changer device structure.
464	 */
465	if ((softc->flags & CD_FLAG_CHANGER)
466	 && (--softc->changer->num_devices == 0)) {
467
468		/*
469		 * Theoretically, there shouldn't be any timeouts left, but
470		 * I'm not completely sure that that will be the case.  So,
471		 * it won't hurt to check and see if there are any left.
472		 */
473		if (softc->changer->flags & CHANGER_TIMEOUT_SCHED) {
474			untimeout(cdrunchangerqueue, softc->changer,
475				  softc->changer->long_handle);
476			softc->changer->flags &= ~CHANGER_TIMEOUT_SCHED;
477		}
478
479		if (softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
480			untimeout(cdshorttimeout, softc->changer,
481				  softc->changer->short_handle);
482			softc->changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
483		}
484
485		STAILQ_REMOVE(&changerq, softc->changer, cdchanger,
486			      changer_links);
487		xpt_print_path(periph->path);
488		printf("removing changer entry\n");
489		free(softc->changer, M_DEVBUF);
490		num_changers--;
491	}
492	devstat_remove_entry(&softc->device_stats);
493	cam_extend_release(cdperiphs, periph->unit_number);
494	free(softc, M_DEVBUF);
495	splx(s);
496}
497
498static void
499cdasync(void *callback_arg, u_int32_t code,
500	struct cam_path *path, void *arg)
501{
502	struct cam_periph *periph;
503
504	periph = (struct cam_periph *)callback_arg;
505	switch (code) {
506	case AC_FOUND_DEVICE:
507	{
508		struct ccb_getdev *cgd;
509		cam_status status;
510
511		cgd = (struct ccb_getdev *)arg;
512
513		if (SID_TYPE(&cgd->inq_data) != T_CDROM
514		    && SID_TYPE(&cgd->inq_data) != 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_SENT_BDR:
536	case AC_BUS_RESET:
537	{
538		struct cd_softc *softc;
539		struct ccb_hdr *ccbh;
540		int s;
541
542		softc = (struct cd_softc *)periph->softc;
543		s = splsoftcam();
544		/*
545		 * Don't fail on the expected unit attention
546		 * that will occur.
547		 */
548		softc->flags |= CD_FLAG_RETRY_UA;
549		LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
550			ccbh->ccb_state |= CD_CCB_RETRY_UA;
551		splx(s);
552		/* FALLTHROUGH */
553	}
554	default:
555		cam_periph_async(periph, code, path, arg);
556		break;
557	}
558}
559
560static cam_status
561cdregister(struct cam_periph *periph, void *arg)
562{
563	struct cd_softc *softc;
564	struct ccb_setasync csa;
565	struct ccb_getdev *cgd;
566	caddr_t match;
567
568	cgd = (struct ccb_getdev *)arg;
569	if (periph == NULL) {
570		printf("cdregister: periph was NULL!!\n");
571		return(CAM_REQ_CMP_ERR);
572	}
573	if (cgd == NULL) {
574		printf("cdregister: no getdev CCB, can't register device\n");
575		return(CAM_REQ_CMP_ERR);
576	}
577
578	softc = (struct cd_softc *)malloc(sizeof(*softc),M_DEVBUF,M_NOWAIT);
579
580	if (softc == NULL) {
581		printf("cdregister: Unable to probe new device. "
582		       "Unable to allocate softc\n");
583		return(CAM_REQ_CMP_ERR);
584	}
585
586	bzero(softc, sizeof(*softc));
587	LIST_INIT(&softc->pending_ccbs);
588	softc->state = CD_STATE_PROBE;
589	bioq_init(&softc->bio_queue);
590	if (SID_IS_REMOVABLE(&cgd->inq_data))
591		softc->flags |= CD_FLAG_DISC_REMOVABLE;
592	if ((cgd->inq_data.flags & SID_CmdQue) != 0)
593		softc->flags |= CD_FLAG_TAGGED_QUEUING;
594
595	periph->softc = softc;
596	softc->periph = periph;
597
598	cam_extend_set(cdperiphs, periph->unit_number, periph);
599
600	/*
601	 * See if this device has any quirks.
602	 */
603	match = cam_quirkmatch((caddr_t)&cgd->inq_data,
604			       (caddr_t)cd_quirk_table,
605			       sizeof(cd_quirk_table)/sizeof(*cd_quirk_table),
606			       sizeof(*cd_quirk_table), scsi_inquiry_match);
607
608	if (match != NULL)
609		softc->quirks = ((struct cd_quirk_entry *)match)->quirks;
610	else
611		softc->quirks = CD_Q_NONE;
612
613	/*
614	 * We need to register the statistics structure for this device,
615	 * but we don't have the blocksize yet for it.  So, we register
616	 * the structure and indicate that we don't have the blocksize
617	 * yet.  Unlike other SCSI peripheral drivers, we explicitly set
618	 * the device type here to be CDROM, rather than just ORing in
619	 * the device type.  This is because this driver can attach to either
620	 * CDROM or WORM devices, and we want this peripheral driver to
621	 * show up in the devstat list as a CD peripheral driver, not a
622	 * WORM peripheral driver.  WORM drives will also have the WORM
623	 * driver attached to them.
624	 */
625	devstat_add_entry(&softc->device_stats, "cd",
626			  periph->unit_number, 0,
627	  		  DEVSTAT_BS_UNAVAILABLE,
628			  DEVSTAT_TYPE_CDROM | DEVSTAT_TYPE_IF_SCSI,
629			  DEVSTAT_PRIORITY_CD);
630	disk_create(periph->unit_number, &softc->disk,
631		    DSO_ONESLICE | DSO_COMPATLABEL,
632		    &cd_cdevsw, &cddisk_cdevsw);
633
634	/*
635	 * Add an async callback so that we get
636	 * notified if this device goes away.
637	 */
638	xpt_setup_ccb(&csa.ccb_h, periph->path,
639		      /* priority */ 5);
640	csa.ccb_h.func_code = XPT_SASYNC_CB;
641	csa.event_enable = AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE;
642	csa.callback = cdasync;
643	csa.callback_arg = periph;
644	xpt_action((union ccb *)&csa);
645
646	/*
647	 * If the target lun is greater than 0, we most likely have a CD
648	 * changer device.  Check the quirk entries as well, though, just
649	 * in case someone has a CD tower with one lun per drive or
650	 * something like that.  Also, if we know up front that a
651	 * particular device is a changer, we can mark it as such starting
652	 * with lun 0, instead of lun 1.  It shouldn't be necessary to have
653	 * a quirk entry to define something as a changer, however.
654	 */
655	if (((cgd->ccb_h.target_lun > 0)
656	  && ((softc->quirks & CD_Q_NO_CHANGER) == 0))
657	 || ((softc->quirks & CD_Q_CHANGER) != 0)) {
658		struct cdchanger *nchanger;
659		struct cam_periph *nperiph;
660		struct cam_path *path;
661		cam_status status;
662		int found;
663
664		/* Set the changer flag in the current device's softc */
665		softc->flags |= CD_FLAG_CHANGER;
666
667		if (num_changers == 0)
668			STAILQ_INIT(&changerq);
669
670		/*
671		 * Now, look around for an existing changer device with the
672		 * same path and target ID as the current device.
673		 */
674		for (found = 0,
675		     nchanger = (struct cdchanger *)STAILQ_FIRST(&changerq);
676		     nchanger != NULL;
677		     nchanger = STAILQ_NEXT(nchanger, changer_links)){
678			if ((nchanger->path_id == cgd->ccb_h.path_id)
679			 && (nchanger->target_id == cgd->ccb_h.target_id)) {
680				found = 1;
681				break;
682			}
683		}
684
685		/*
686		 * If we found a matching entry, just add this device to
687		 * the list of devices on this changer.
688		 */
689		if (found == 1) {
690			struct chdevlist *chlunhead;
691
692			chlunhead = &nchanger->chluns;
693
694			/*
695			 * XXX KDM look at consolidating this code with the
696			 * code below in a separate function.
697			 */
698
699			/*
700			 * Create a path with lun id 0, and see if we can
701			 * find a matching device
702			 */
703			status = xpt_create_path(&path, /*periph*/ periph,
704						 cgd->ccb_h.path_id,
705						 cgd->ccb_h.target_id, 0);
706
707			if ((status == CAM_REQ_CMP)
708			 && ((nperiph = cam_periph_find(path, "cd")) != NULL)){
709				struct cd_softc *nsoftc;
710
711				nsoftc = (struct cd_softc *)nperiph->softc;
712
713				if ((nsoftc->flags & CD_FLAG_CHANGER) == 0){
714					nsoftc->flags |= CD_FLAG_CHANGER;
715					nchanger->num_devices++;
716					if (camq_resize(&nchanger->devq,
717					   nchanger->num_devices)!=CAM_REQ_CMP){
718						printf("cdregister: "
719						       "camq_resize "
720						       "failed, changer "
721						       "support may "
722						       "be messed up\n");
723					}
724					nsoftc->changer = nchanger;
725					nsoftc->pinfo.index =CAM_UNQUEUED_INDEX;
726
727					STAILQ_INSERT_TAIL(&nchanger->chluns,
728							  nsoftc,changer_links);
729				}
730				xpt_free_path(path);
731			} else if (status == CAM_REQ_CMP)
732				xpt_free_path(path);
733			else {
734				printf("cdregister: unable to allocate path\n"
735				       "cdregister: changer support may be "
736				       "broken\n");
737			}
738
739			nchanger->num_devices++;
740
741			softc->changer = nchanger;
742			softc->pinfo.index = CAM_UNQUEUED_INDEX;
743
744			if (camq_resize(&nchanger->devq,
745			    nchanger->num_devices) != CAM_REQ_CMP) {
746				printf("cdregister: camq_resize "
747				       "failed, changer support may "
748				       "be messed up\n");
749			}
750
751			STAILQ_INSERT_TAIL(chlunhead, softc, changer_links);
752		}
753		/*
754		 * In this case, we don't already have an entry for this
755		 * particular changer, so we need to create one, add it to
756		 * the queue, and queue this device on the list for this
757		 * changer.  Before we queue this device, however, we need
758		 * to search for lun id 0 on this target, and add it to the
759		 * queue first, if it exists.  (and if it hasn't already
760		 * been marked as part of the changer.)
761		 */
762		else {
763			nchanger = malloc(sizeof(struct cdchanger),
764				M_DEVBUF, M_NOWAIT);
765
766			if (nchanger == NULL) {
767				softc->flags &= ~CD_FLAG_CHANGER;
768				printf("cdregister: unable to malloc "
769				       "changer structure\ncdregister: "
770				       "changer support disabled\n");
771
772				/*
773				 * Yes, gotos can be gross but in this case
774				 * I think it's justified..
775				 */
776				goto cdregisterexit;
777			}
778
779			/* zero the structure */
780			bzero(nchanger, sizeof(struct cdchanger));
781
782			if (camq_init(&nchanger->devq, 1) != 0) {
783				softc->flags &= ~CD_FLAG_CHANGER;
784				printf("cdregister: changer support "
785				       "disabled\n");
786				goto cdregisterexit;
787			}
788
789			num_changers++;
790
791			nchanger->path_id = cgd->ccb_h.path_id;
792			nchanger->target_id = cgd->ccb_h.target_id;
793
794			/* this is superfluous, but it makes things clearer */
795			nchanger->num_devices = 0;
796
797			STAILQ_INIT(&nchanger->chluns);
798
799			STAILQ_INSERT_TAIL(&changerq, nchanger,
800					   changer_links);
801
802			/*
803			 * Create a path with lun id 0, and see if we can
804			 * find a matching device
805			 */
806			status = xpt_create_path(&path, /*periph*/ periph,
807						 cgd->ccb_h.path_id,
808						 cgd->ccb_h.target_id, 0);
809
810			/*
811			 * If we were able to allocate the path, and if we
812			 * find a matching device and it isn't already
813			 * marked as part of a changer, then we add it to
814			 * the current changer.
815			 */
816			if ((status == CAM_REQ_CMP)
817			 && ((nperiph = cam_periph_find(path, "cd")) != NULL)
818			 && ((((struct cd_softc *)periph->softc)->flags &
819			       CD_FLAG_CHANGER) == 0)) {
820				struct cd_softc *nsoftc;
821
822				nsoftc = (struct cd_softc *)nperiph->softc;
823
824				nsoftc->flags |= CD_FLAG_CHANGER;
825				nchanger->num_devices++;
826				if (camq_resize(&nchanger->devq,
827				    nchanger->num_devices) != CAM_REQ_CMP) {
828					printf("cdregister: camq_resize "
829					       "failed, changer support may "
830					       "be messed up\n");
831				}
832				nsoftc->changer = nchanger;
833				nsoftc->pinfo.index = CAM_UNQUEUED_INDEX;
834
835				STAILQ_INSERT_TAIL(&nchanger->chluns,
836						   nsoftc, changer_links);
837				xpt_free_path(path);
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 (cam_periph_acquire(periph) != CAM_REQ_CMP)
910		return(ENXIO);
911
912	cdprevent(periph, PR_PREVENT);
913
914	/* find out the size */
915	if ((error = cdsize(dev, &size)) != 0) {
916		cdprevent(periph, PR_ALLOW);
917		cam_periph_unlock(periph);
918		cam_periph_release(periph);
919		return(error);
920	}
921
922	/*
923	 * If we get a non-zero return, revert back to not reading the
924	 * label off the disk.  The first track is likely audio, which
925	 * won't have a disklabel.
926	 */
927	if ((error = cdfirsttrackisdata(periph)) != 0) {
928		softc->disk.d_dsflags &= ~DSO_COMPATLABEL;
929		softc->disk.d_dsflags |= DSO_NOLABELS;
930		error = 0;
931	}
932
933	/*
934	 * Build prototype label for whole disk.
935	 * Should take information about different data tracks from the
936	 * TOC and put it in the partition table.
937	 */
938	label = &softc->disk.d_label;
939	bzero(label, sizeof(*label));
940	label->d_type = DTYPE_SCSI;
941
942	/*
943	 * Grab the inquiry data to get the vendor and product names.
944	 * Put them in the typename and packname for the label.
945	 */
946	xpt_setup_ccb(&cgd.ccb_h, periph->path, /*priority*/ 1);
947	cgd.ccb_h.func_code = XPT_GDEV_TYPE;
948	xpt_action((union ccb *)&cgd);
949
950	strncpy(label->d_typename, cgd.inq_data.vendor,
951		min(SID_VENDOR_SIZE, sizeof(label->d_typename)));
952	strncpy(label->d_packname, cgd.inq_data.product,
953		min(SID_PRODUCT_SIZE, sizeof(label->d_packname)));
954
955	label->d_secsize = softc->params.blksize;
956	label->d_secperunit = softc->params.disksize;
957	label->d_flags = D_REMOVABLE;
958	/*
959	 * Make partition 'a' cover the whole disk.  This is a temporary
960	 * compatibility hack.  The 'a' partition should not exist, so
961	 * the slice code won't create it.  The slice code will make
962	 * partition (RAW_PART + 'a') cover the whole disk and fill in
963	 * some more defaults.
964	 */
965	label->d_partitions[0].p_size = label->d_secperunit;
966	label->d_partitions[0].p_fstype = FS_OTHER;
967
968	/*
969	 * We unconditionally (re)set the blocksize each time the
970	 * CD device is opened.  This is because the CD can change,
971	 * and therefore the blocksize might change.
972	 * XXX problems here if some slice or partition is still
973	 * open with the old size?
974	 */
975	if ((softc->device_stats.flags & DEVSTAT_BS_UNAVAILABLE) != 0)
976		softc->device_stats.flags &= ~DEVSTAT_BS_UNAVAILABLE;
977	softc->device_stats.block_size = softc->params.blksize;
978
979	cam_periph_unlock(periph);
980
981	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdopen\n"));
982
983	return (error);
984}
985
986static int
987cdclose(dev_t dev, int flag, int fmt, struct proc *p)
988{
989	struct 	cam_periph *periph;
990	struct	cd_softc *softc;
991	int	unit, error;
992
993	unit = dkunit(dev);
994	periph = cam_extend_get(cdperiphs, unit);
995	if (periph == NULL)
996		return (ENXIO);
997
998	softc = (struct cd_softc *)periph->softc;
999
1000	if ((error = cam_periph_lock(periph, PRIBIO)) != 0)
1001		return (error);
1002
1003	if ((softc->flags & CD_FLAG_DISC_REMOVABLE) != 0)
1004		cdprevent(periph, PR_ALLOW);
1005
1006	/*
1007	 * Unconditionally set the dsopen() flags back to their default
1008	 * state.
1009	 */
1010	softc->disk.d_dsflags &= ~DSO_NOLABELS;
1011	softc->disk.d_dsflags |= DSO_COMPATLABEL;
1012
1013	/*
1014	 * Since we're closing this CD, mark the blocksize as unavailable.
1015	 * It will be marked as available whence the CD is opened again.
1016	 */
1017	softc->device_stats.flags |= DEVSTAT_BS_UNAVAILABLE;
1018
1019	cam_periph_unlock(periph);
1020	cam_periph_release(periph);
1021
1022	return (0);
1023}
1024
1025static void
1026cdshorttimeout(void *arg)
1027{
1028	struct cdchanger *changer;
1029	int s;
1030
1031	s = splsoftcam();
1032
1033	changer = (struct cdchanger *)arg;
1034
1035	/* Always clear the short timeout flag, since that's what we're in */
1036	changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
1037
1038	/*
1039	 * Check to see if there is any more pending or outstanding I/O for
1040	 * this device.  If not, move it out of the active slot.
1041	 */
1042	if ((bioq_first(&changer->cur_device->bio_queue) == NULL)
1043	 && (changer->cur_device->device_stats.busy_count == 0)) {
1044		changer->flags |= CHANGER_MANUAL_CALL;
1045		cdrunchangerqueue(changer);
1046	}
1047
1048	splx(s);
1049}
1050
1051/*
1052 * This is a wrapper for xpt_schedule.  It only applies to changers.
1053 */
1054static void
1055cdschedule(struct cam_periph *periph, int priority)
1056{
1057	struct cd_softc *softc;
1058	int s;
1059
1060	s = splsoftcam();
1061
1062	softc = (struct cd_softc *)periph->softc;
1063
1064	/*
1065	 * If this device isn't currently queued, and if it isn't
1066	 * the active device, then we queue this device and run the
1067	 * changer queue if there is no timeout scheduled to do it.
1068	 * If this device is the active device, just schedule it
1069	 * to run again.  If this device is queued, there should be
1070	 * a timeout in place already that will make sure it runs.
1071	 */
1072	if ((softc->pinfo.index == CAM_UNQUEUED_INDEX)
1073	 && ((softc->flags & CD_FLAG_ACTIVE) == 0)) {
1074		/*
1075		 * We don't do anything with the priority here.
1076		 * This is strictly a fifo queue.
1077		 */
1078		softc->pinfo.priority = 1;
1079		softc->pinfo.generation = ++softc->changer->devq.generation;
1080		camq_insert(&softc->changer->devq, (cam_pinfo *)softc);
1081
1082		/*
1083		 * Since we just put a device in the changer queue,
1084		 * check and see if there is a timeout scheduled for
1085		 * this changer.  If so, let the timeout handle
1086		 * switching this device into the active slot.  If
1087		 * not, manually call the timeout routine to
1088		 * bootstrap things.
1089		 */
1090		if (((softc->changer->flags & CHANGER_TIMEOUT_SCHED)==0)
1091		 && ((softc->changer->flags & CHANGER_NEED_TIMEOUT)==0)
1092		 && ((softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED)==0)){
1093			softc->changer->flags |= CHANGER_MANUAL_CALL;
1094			cdrunchangerqueue(softc->changer);
1095		}
1096	} else if ((softc->flags & CD_FLAG_ACTIVE)
1097		&& ((softc->flags & CD_FLAG_SCHED_ON_COMP) == 0))
1098		xpt_schedule(periph, priority);
1099
1100	splx(s);
1101
1102}
1103
1104static void
1105cdrunchangerqueue(void *arg)
1106{
1107	struct cd_softc *softc;
1108	struct cdchanger *changer;
1109	int called_from_timeout;
1110	int s;
1111
1112	s = splsoftcam();
1113
1114	changer = (struct cdchanger *)arg;
1115
1116	/*
1117	 * If we have NOT been called from cdstrategy() or cddone(), and
1118	 * instead from a timeout routine, go ahead and clear the
1119	 * timeout flag.
1120	 */
1121	if ((changer->flags & CHANGER_MANUAL_CALL) == 0) {
1122		changer->flags &= ~CHANGER_TIMEOUT_SCHED;
1123		called_from_timeout = 1;
1124	} else
1125		called_from_timeout = 0;
1126
1127	/* Always clear the manual call flag */
1128	changer->flags &= ~CHANGER_MANUAL_CALL;
1129
1130	/* nothing to do if the queue is empty */
1131	if (changer->devq.entries <= 0) {
1132		splx(s);
1133		return;
1134	}
1135
1136	/*
1137	 * If the changer queue is frozen, that means we have an active
1138	 * device.
1139	 */
1140	if (changer->devq.qfrozen_cnt > 0) {
1141
1142		if (changer->cur_device->device_stats.busy_count > 0) {
1143			changer->cur_device->flags |= CD_FLAG_SCHED_ON_COMP;
1144			changer->cur_device->bufs_left =
1145				changer->cur_device->device_stats.busy_count;
1146			if (called_from_timeout) {
1147				changer->long_handle =
1148					timeout(cdrunchangerqueue, changer,
1149				        changer_max_busy_seconds * hz);
1150				changer->flags |= CHANGER_TIMEOUT_SCHED;
1151			}
1152			splx(s);
1153			return;
1154		}
1155
1156		/*
1157		 * We always need to reset the frozen count and clear the
1158		 * active flag.
1159		 */
1160		changer->devq.qfrozen_cnt--;
1161		changer->cur_device->flags &= ~CD_FLAG_ACTIVE;
1162		changer->cur_device->flags &= ~CD_FLAG_SCHED_ON_COMP;
1163
1164		/*
1165		 * Check to see whether the current device has any I/O left
1166		 * to do.  If so, requeue it at the end of the queue.  If
1167		 * not, there is no need to requeue it.
1168		 */
1169		if (bioq_first(&changer->cur_device->bio_queue) != NULL) {
1170
1171			changer->cur_device->pinfo.generation =
1172				++changer->devq.generation;
1173			camq_insert(&changer->devq,
1174				(cam_pinfo *)changer->cur_device);
1175		}
1176	}
1177
1178	softc = (struct cd_softc *)camq_remove(&changer->devq, CAMQ_HEAD);
1179
1180	changer->cur_device = softc;
1181
1182	changer->devq.qfrozen_cnt++;
1183	softc->flags |= CD_FLAG_ACTIVE;
1184
1185	/* Just in case this device is waiting */
1186	wakeup(&softc->changer);
1187	xpt_schedule(softc->periph, /*priority*/ 1);
1188
1189	/*
1190	 * Get rid of any pending timeouts, and set a flag to schedule new
1191	 * ones so this device gets its full time quantum.
1192	 */
1193	if (changer->flags & CHANGER_TIMEOUT_SCHED) {
1194		untimeout(cdrunchangerqueue, changer, changer->long_handle);
1195		changer->flags &= ~CHANGER_TIMEOUT_SCHED;
1196	}
1197
1198	if (changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
1199		untimeout(cdshorttimeout, changer, changer->short_handle);
1200		changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
1201	}
1202
1203	/*
1204	 * We need to schedule timeouts, but we only do this after the
1205	 * first transaction has completed.  This eliminates the changer
1206	 * switch time.
1207	 */
1208	changer->flags |= CHANGER_NEED_TIMEOUT;
1209
1210	splx(s);
1211}
1212
1213static void
1214cdchangerschedule(struct cd_softc *softc)
1215{
1216	struct cdchanger *changer;
1217	int s;
1218
1219	s = splsoftcam();
1220
1221	changer = softc->changer;
1222
1223	/*
1224	 * If this is a changer, and this is the current device,
1225	 * and this device has at least the minimum time quantum to
1226	 * run, see if we can switch it out.
1227	 */
1228	if ((softc->flags & CD_FLAG_ACTIVE)
1229	 && ((changer->flags & CHANGER_SHORT_TMOUT_SCHED) == 0)
1230	 && ((changer->flags & CHANGER_NEED_TIMEOUT) == 0)) {
1231		/*
1232		 * We try three things here.  The first is that we
1233		 * check to see whether the schedule on completion
1234		 * flag is set.  If it is, we decrement the number
1235		 * of buffers left, and if it's zero, we reschedule.
1236		 * Next, we check to see whether the pending buffer
1237		 * queue is empty and whether there are no
1238		 * outstanding transactions.  If so, we reschedule.
1239		 * Next, we see if the pending buffer queue is empty.
1240		 * If it is, we set the number of buffers left to
1241		 * the current active buffer count and set the
1242		 * schedule on complete flag.
1243		 */
1244		if (softc->flags & CD_FLAG_SCHED_ON_COMP) {
1245		 	if (--softc->bufs_left == 0) {
1246				softc->changer->flags |=
1247					CHANGER_MANUAL_CALL;
1248				softc->flags &= ~CD_FLAG_SCHED_ON_COMP;
1249				cdrunchangerqueue(softc->changer);
1250			}
1251		} else if ((bioq_first(&softc->bio_queue) == NULL)
1252		        && (softc->device_stats.busy_count == 0)) {
1253			softc->changer->flags |= CHANGER_MANUAL_CALL;
1254			cdrunchangerqueue(softc->changer);
1255		}
1256	} else if ((softc->changer->flags & CHANGER_NEED_TIMEOUT)
1257		&& (softc->flags & CD_FLAG_ACTIVE)) {
1258
1259		/*
1260		 * Now that the first transaction to this
1261		 * particular device has completed, we can go ahead
1262		 * and schedule our timeouts.
1263		 */
1264		if ((changer->flags & CHANGER_TIMEOUT_SCHED) == 0) {
1265			changer->long_handle =
1266			    timeout(cdrunchangerqueue, changer,
1267				    changer_max_busy_seconds * hz);
1268			changer->flags |= CHANGER_TIMEOUT_SCHED;
1269		} else
1270			printf("cdchangerschedule: already have a long"
1271			       " timeout!\n");
1272
1273		if ((changer->flags & CHANGER_SHORT_TMOUT_SCHED) == 0) {
1274			changer->short_handle =
1275			    timeout(cdshorttimeout, changer,
1276				    changer_min_busy_seconds * hz);
1277			changer->flags |= CHANGER_SHORT_TMOUT_SCHED;
1278		} else
1279			printf("cdchangerschedule: already have a short "
1280			       "timeout!\n");
1281
1282		/*
1283		 * We just scheduled timeouts, no need to schedule
1284		 * more.
1285		 */
1286		changer->flags &= ~CHANGER_NEED_TIMEOUT;
1287
1288	}
1289	splx(s);
1290}
1291
1292static int
1293cdrunccb(union ccb *ccb, int (*error_routine)(union ccb *ccb,
1294					      u_int32_t cam_flags,
1295					      u_int32_t sense_flags),
1296	 u_int32_t cam_flags, u_int32_t sense_flags)
1297{
1298	struct cd_softc *softc;
1299	struct cam_periph *periph;
1300	int error;
1301
1302	periph = xpt_path_periph(ccb->ccb_h.path);
1303	softc = (struct cd_softc *)periph->softc;
1304
1305	error = cam_periph_runccb(ccb, error_routine, cam_flags, sense_flags,
1306				  &softc->device_stats);
1307
1308	if (softc->flags & CD_FLAG_CHANGER)
1309		cdchangerschedule(softc);
1310
1311	return(error);
1312}
1313
1314static union ccb *
1315cdgetccb(struct cam_periph *periph, u_int32_t priority)
1316{
1317	struct cd_softc *softc;
1318	int s;
1319
1320	softc = (struct cd_softc *)periph->softc;
1321
1322	if (softc->flags & CD_FLAG_CHANGER) {
1323
1324		s = splsoftcam();
1325
1326		/*
1327		 * This should work the first time this device is woken up,
1328		 * but just in case it doesn't, we use a while loop.
1329		 */
1330		while ((softc->flags & CD_FLAG_ACTIVE) == 0) {
1331			/*
1332			 * If this changer isn't already queued, queue it up.
1333			 */
1334			if (softc->pinfo.index == CAM_UNQUEUED_INDEX) {
1335				softc->pinfo.priority = 1;
1336				softc->pinfo.generation =
1337					++softc->changer->devq.generation;
1338				camq_insert(&softc->changer->devq,
1339					    (cam_pinfo *)softc);
1340			}
1341			if (((softc->changer->flags & CHANGER_TIMEOUT_SCHED)==0)
1342			 && ((softc->changer->flags & CHANGER_NEED_TIMEOUT)==0)
1343			 && ((softc->changer->flags
1344			      & CHANGER_SHORT_TMOUT_SCHED)==0)) {
1345				softc->changer->flags |= CHANGER_MANUAL_CALL;
1346				cdrunchangerqueue(softc->changer);
1347			} else
1348				tsleep(&softc->changer, PRIBIO, "cgticb", 0);
1349		}
1350		splx(s);
1351	}
1352	return(cam_periph_getccb(periph, priority));
1353}
1354
1355
1356/*
1357 * Actually translate the requested transfer into one the physical driver
1358 * can understand.  The transfer is described by a buf and will include
1359 * only one physical transfer.
1360 */
1361static void
1362cdstrategy(struct bio *bp)
1363{
1364	struct cam_periph *periph;
1365	struct cd_softc *softc;
1366	u_int  unit, part;
1367	int    s;
1368
1369	unit = dkunit(bp->bio_dev);
1370	part = dkpart(bp->bio_dev);
1371	periph = cam_extend_get(cdperiphs, unit);
1372	if (periph == NULL) {
1373		bp->bio_error = ENXIO;
1374		goto bad;
1375	}
1376
1377	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdstrategy\n"));
1378
1379	softc = (struct cd_softc *)periph->softc;
1380
1381	/*
1382	 * Mask interrupts so that the pack cannot be invalidated until
1383	 * after we are in the queue.  Otherwise, we might not properly
1384	 * clean up one of the buffers.
1385	 */
1386	s = splbio();
1387
1388	/*
1389	 * If the device has been made invalid, error out
1390	 */
1391	if ((softc->flags & CD_FLAG_INVALID)) {
1392		splx(s);
1393		bp->bio_error = ENXIO;
1394		goto bad;
1395	}
1396
1397	/*
1398	 * Place it in the queue of disk activities for this disk
1399	 */
1400	bioqdisksort(&softc->bio_queue, bp);
1401
1402	splx(s);
1403
1404	/*
1405	 * Schedule ourselves for performing the work.  We do things
1406	 * differently for changers.
1407	 */
1408	if ((softc->flags & CD_FLAG_CHANGER) == 0)
1409		xpt_schedule(periph, /* XXX priority */1);
1410	else
1411		cdschedule(periph, /* priority */ 1);
1412
1413	return;
1414bad:
1415	bp->bio_flags |= BIO_ERROR;
1416	/*
1417	 * Correctly set the buf to indicate a completed xfer
1418	 */
1419	bp->bio_resid = bp->bio_bcount;
1420	biodone(bp);
1421	return;
1422}
1423
1424static void
1425cdstart(struct cam_periph *periph, union ccb *start_ccb)
1426{
1427	struct cd_softc *softc;
1428	struct bio *bp;
1429	struct ccb_scsiio *csio;
1430	struct scsi_read_capacity_data *rcap;
1431	int s;
1432
1433	softc = (struct cd_softc *)periph->softc;
1434
1435	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdstart\n"));
1436
1437	switch (softc->state) {
1438	case CD_STATE_NORMAL:
1439	{
1440		int oldspl;
1441
1442		s = splbio();
1443		bp = bioq_first(&softc->bio_queue);
1444		if (periph->immediate_priority <= periph->pinfo.priority) {
1445			start_ccb->ccb_h.ccb_state = CD_CCB_WAITING;
1446
1447			SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1448					  periph_links.sle);
1449			periph->immediate_priority = CAM_PRIORITY_NONE;
1450			splx(s);
1451			wakeup(&periph->ccb_list);
1452		} else if (bp == NULL) {
1453			splx(s);
1454			xpt_release_ccb(start_ccb);
1455		} else {
1456			bioq_remove(&softc->bio_queue, bp);
1457
1458			devstat_start_transaction(&softc->device_stats);
1459
1460			scsi_read_write(&start_ccb->csio,
1461					/*retries*/4,
1462					/* cbfcnp */ cddone,
1463					(bp->bio_flags & BIO_ORDERED) != 0 ?
1464					    MSG_ORDERED_Q_TAG :
1465					    MSG_SIMPLE_Q_TAG,
1466					/* read */bp->bio_cmd == BIO_READ,
1467					/* byte2 */ 0,
1468					/* minimum_cmd_size */ 10,
1469					/* lba */ bp->bio_pblkno,
1470					bp->bio_bcount / softc->params.blksize,
1471					/* data_ptr */ bp->bio_data,
1472					/* dxfer_len */ bp->bio_bcount,
1473					/* sense_len */ SSD_FULL_SIZE,
1474					/* timeout */ 30000);
1475			start_ccb->ccb_h.ccb_state = CD_CCB_BUFFER_IO;
1476
1477
1478			/*
1479			 * Block out any asyncronous callbacks
1480			 * while we touch the pending ccb list.
1481			 */
1482			oldspl = splcam();
1483			LIST_INSERT_HEAD(&softc->pending_ccbs,
1484					 &start_ccb->ccb_h, periph_links.le);
1485			splx(oldspl);
1486
1487			/* We expect a unit attention from this device */
1488			if ((softc->flags & CD_FLAG_RETRY_UA) != 0) {
1489				start_ccb->ccb_h.ccb_state |= CD_CCB_RETRY_UA;
1490				softc->flags &= ~CD_FLAG_RETRY_UA;
1491			}
1492
1493			start_ccb->ccb_h.ccb_bp = bp;
1494			bp = bioq_first(&softc->bio_queue);
1495			splx(s);
1496
1497			xpt_action(start_ccb);
1498		}
1499		if (bp != NULL) {
1500			/* Have more work to do, so ensure we stay scheduled */
1501			xpt_schedule(periph, /* XXX priority */1);
1502		}
1503		break;
1504	}
1505	case CD_STATE_PROBE:
1506	{
1507
1508		rcap = (struct scsi_read_capacity_data *)malloc(sizeof(*rcap),
1509								M_TEMP,
1510								M_NOWAIT);
1511		if (rcap == NULL) {
1512			xpt_print_path(periph->path);
1513			printf("cdstart: Couldn't malloc read_capacity data\n");
1514			/* cd_free_periph??? */
1515			break;
1516		}
1517		csio = &start_ccb->csio;
1518		scsi_read_capacity(csio,
1519				   /*retries*/1,
1520				   cddone,
1521				   MSG_SIMPLE_Q_TAG,
1522				   rcap,
1523				   SSD_FULL_SIZE,
1524				   /*timeout*/20000);
1525		start_ccb->ccb_h.ccb_bp = NULL;
1526		start_ccb->ccb_h.ccb_state = CD_CCB_PROBE;
1527		xpt_action(start_ccb);
1528		break;
1529	}
1530	}
1531}
1532
1533static void
1534cddone(struct cam_periph *periph, union ccb *done_ccb)
1535{
1536	struct cd_softc *softc;
1537	struct ccb_scsiio *csio;
1538
1539	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cddone\n"));
1540
1541	softc = (struct cd_softc *)periph->softc;
1542	csio = &done_ccb->csio;
1543
1544	switch (csio->ccb_h.ccb_state & CD_CCB_TYPE_MASK) {
1545	case CD_CCB_BUFFER_IO:
1546	{
1547		struct bio	*bp;
1548		int		error;
1549		int		oldspl;
1550
1551		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
1552		error = 0;
1553
1554		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1555			int sf;
1556
1557			if ((done_ccb->ccb_h.ccb_state & CD_CCB_RETRY_UA) != 0)
1558				sf = SF_RETRY_UA;
1559			else
1560				sf = 0;
1561
1562			/* Retry selection timeouts */
1563			sf |= SF_RETRY_SELTO;
1564
1565			if ((error = cderror(done_ccb, 0, sf)) == ERESTART) {
1566				/*
1567				 * A retry was scheuled, so
1568				 * just return.
1569				 */
1570				return;
1571			}
1572		}
1573
1574		if (error != 0) {
1575			int s;
1576			struct bio *q_bp;
1577
1578			xpt_print_path(periph->path);
1579			printf("cddone: got error %#x back\n", error);
1580			s = splbio();
1581			while ((q_bp = bioq_first(&softc->bio_queue)) != NULL) {
1582				bioq_remove(&softc->bio_queue, q_bp);
1583				q_bp->bio_resid = q_bp->bio_bcount;
1584				q_bp->bio_error = EIO;
1585				q_bp->bio_flags |= BIO_ERROR;
1586				biodone(q_bp);
1587			}
1588			splx(s);
1589			bp->bio_resid = bp->bio_bcount;
1590			bp->bio_error = error;
1591			bp->bio_flags |= BIO_ERROR;
1592			cam_release_devq(done_ccb->ccb_h.path,
1593					 /*relsim_flags*/0,
1594					 /*reduction*/0,
1595					 /*timeout*/0,
1596					 /*getcount_only*/0);
1597
1598		} else {
1599			bp->bio_resid = csio->resid;
1600			bp->bio_error = 0;
1601			if (bp->bio_resid != 0) {
1602				/* Short transfer ??? */
1603				bp->bio_flags |= BIO_ERROR;
1604			}
1605		}
1606
1607		/*
1608		 * Block out any asyncronous callbacks
1609		 * while we touch the pending ccb list.
1610		 */
1611		oldspl = splcam();
1612		LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
1613		splx(oldspl);
1614
1615		if (softc->flags & CD_FLAG_CHANGER)
1616			cdchangerschedule(softc);
1617
1618		devstat_end_transaction_bio(&softc->device_stats, bp);
1619		biodone(bp);
1620		break;
1621	}
1622	case CD_CCB_PROBE:
1623	{
1624		struct	   scsi_read_capacity_data *rdcap;
1625		char	   announce_buf[120]; /*
1626					       * Currently (9/30/97) the
1627					       * longest possible announce
1628					       * buffer is 108 bytes, for the
1629					       * first error case below.
1630					       * That is 39 bytes for the
1631					       * basic string, 16 bytes for the
1632					       * biggest sense key (hardware
1633					       * error), 52 bytes for the
1634					       * text of the largest sense
1635					       * qualifier valid for a CDROM,
1636					       * (0x72, 0x03 or 0x04,
1637					       * 0x03), and one byte for the
1638					       * null terminating character.
1639					       * To allow for longer strings,
1640					       * the announce buffer is 120
1641					       * bytes.
1642					       */
1643		struct	   cd_params *cdp;
1644
1645		cdp = &softc->params;
1646
1647		rdcap = (struct scsi_read_capacity_data *)csio->data_ptr;
1648
1649		cdp->disksize = scsi_4btoul (rdcap->addr) + 1;
1650		cdp->blksize = scsi_4btoul (rdcap->length);
1651
1652		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1653
1654			snprintf(announce_buf, sizeof(announce_buf),
1655				"cd present [%lu x %lu byte records]",
1656				cdp->disksize, (u_long)cdp->blksize);
1657
1658		} else {
1659			int	error;
1660			/*
1661			 * Retry any UNIT ATTENTION type errors.  They
1662			 * are expected at boot.
1663			 */
1664			error = cderror(done_ccb, 0, SF_RETRY_UA |
1665					SF_NO_PRINT | SF_RETRY_SELTO);
1666			if (error == ERESTART) {
1667				/*
1668				 * A retry was scheuled, so
1669				 * just return.
1670				 */
1671				return;
1672			} else if (error != 0) {
1673
1674				struct scsi_sense_data *sense;
1675				int asc, ascq;
1676				int sense_key, error_code;
1677				int have_sense;
1678				cam_status status;
1679				struct ccb_getdev cgd;
1680
1681				/* Don't wedge this device's queue */
1682				cam_release_devq(done_ccb->ccb_h.path,
1683						 /*relsim_flags*/0,
1684						 /*reduction*/0,
1685						 /*timeout*/0,
1686						 /*getcount_only*/0);
1687
1688				status = done_ccb->ccb_h.status;
1689
1690				xpt_setup_ccb(&cgd.ccb_h,
1691					      done_ccb->ccb_h.path,
1692					      /* priority */ 1);
1693				cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1694				xpt_action((union ccb *)&cgd);
1695
1696				if (((csio->ccb_h.flags & CAM_SENSE_PHYS) != 0)
1697				 || ((csio->ccb_h.flags & CAM_SENSE_PTR) != 0)
1698				 || ((status & CAM_AUTOSNS_VALID) == 0))
1699					have_sense = FALSE;
1700				else
1701					have_sense = TRUE;
1702
1703				if (have_sense) {
1704					sense = &csio->sense_data;
1705					scsi_extract_sense(sense, &error_code,
1706							   &sense_key,
1707							   &asc, &ascq);
1708				}
1709				/*
1710				 * Attach to anything that claims to be a
1711				 * CDROM or WORM device, as long as it
1712				 * doesn't return a "Logical unit not
1713				 * supported" (0x25) error.
1714				 */
1715				if ((have_sense) && (asc != 0x25)
1716				 && (error_code == SSD_CURRENT_ERROR))
1717					snprintf(announce_buf,
1718					    sizeof(announce_buf),
1719						"Attempt to query device "
1720						"size failed: %s, %s",
1721						scsi_sense_key_text[sense_key],
1722						scsi_sense_desc(asc,ascq,
1723								&cgd.inq_data));
1724				else if (SID_TYPE(&cgd.inq_data) == T_CDROM) {
1725					/*
1726					 * We only print out an error for
1727					 * CDROM type devices.  For WORM
1728					 * devices, we don't print out an
1729					 * error since a few WORM devices
1730					 * don't support CDROM commands.
1731					 * If we have sense information, go
1732					 * ahead and print it out.
1733					 * Otherwise, just say that we
1734					 * couldn't attach.
1735					 */
1736
1737					/*
1738					 * Just print out the error, not
1739					 * the full probe message, when we
1740					 * don't attach.
1741					 */
1742					if (have_sense)
1743						scsi_sense_print(
1744							&done_ccb->csio);
1745					else {
1746						xpt_print_path(periph->path);
1747						printf("got CAM status %#x\n",
1748						       done_ccb->ccb_h.status);
1749					}
1750					xpt_print_path(periph->path);
1751					printf("fatal error, failed"
1752					       " to attach to device\n");
1753
1754					/*
1755					 * Invalidate this peripheral.
1756					 */
1757					cam_periph_invalidate(periph);
1758
1759					announce_buf[0] = '\0';
1760				} else {
1761
1762					/*
1763					 * Invalidate this peripheral.
1764					 */
1765					cam_periph_invalidate(periph);
1766					announce_buf[0] = '\0';
1767				}
1768			}
1769		}
1770		free(rdcap, M_TEMP);
1771		if (announce_buf[0] != '\0') {
1772			xpt_announce_periph(periph, announce_buf);
1773			if (softc->flags & CD_FLAG_CHANGER)
1774				cdchangerschedule(softc);
1775		}
1776		softc->state = CD_STATE_NORMAL;
1777		/*
1778		 * Since our peripheral may be invalidated by an error
1779		 * above or an external event, we must release our CCB
1780		 * before releasing the probe lock on the peripheral.
1781		 * The peripheral will only go away once the last lock
1782		 * is removed, and we need it around for the CCB release
1783		 * operation.
1784		 */
1785		xpt_release_ccb(done_ccb);
1786		cam_periph_unlock(periph);
1787		return;
1788	}
1789	case CD_CCB_WAITING:
1790	{
1791		/* Caller will release the CCB */
1792		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1793			  ("trying to wakeup ccbwait\n"));
1794
1795		wakeup(&done_ccb->ccb_h.cbfcnp);
1796		return;
1797	}
1798	default:
1799		break;
1800	}
1801	xpt_release_ccb(done_ccb);
1802}
1803
1804static int
1805cdioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
1806{
1807
1808	struct 	cam_periph *periph;
1809	struct	cd_softc *softc;
1810	int	error, unit;
1811
1812	unit = dkunit(dev);
1813
1814	periph = cam_extend_get(cdperiphs, unit);
1815	if (periph == NULL)
1816		return(ENXIO);
1817
1818	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdioctl\n"));
1819
1820	softc = (struct cd_softc *)periph->softc;
1821
1822	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1823		  ("trying to do ioctl %#lx\n", cmd));
1824
1825	error = cam_periph_lock(periph, PRIBIO | PCATCH);
1826
1827	if (error != 0)
1828		return(error);
1829
1830	switch (cmd) {
1831
1832	case CDIOCPLAYTRACKS:
1833		{
1834			struct ioc_play_track *args
1835			    = (struct ioc_play_track *) addr;
1836			struct cd_mode_data *data;
1837
1838			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
1839				      M_WAITOK);
1840
1841			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1842				  ("trying to do CDIOCPLAYTRACKS\n"));
1843
1844			error = cdgetmode(periph, data, AUDIO_PAGE);
1845			if (error) {
1846				free(data, M_TEMP);
1847				break;
1848			}
1849			data->page.audio.flags &= ~CD_PA_SOTC;
1850			data->page.audio.flags |= CD_PA_IMMED;
1851			error = cdsetmode(periph, data);
1852			free(data, M_TEMP);
1853			if (error)
1854				break;
1855			if (softc->quirks & CD_Q_BCD_TRACKS) {
1856				args->start_track = bin2bcd(args->start_track);
1857				args->end_track = bin2bcd(args->end_track);
1858			}
1859			error = cdplaytracks(periph,
1860					     args->start_track,
1861					     args->start_index,
1862					     args->end_track,
1863					     args->end_index);
1864		}
1865		break;
1866	case CDIOCPLAYMSF:
1867		{
1868			struct ioc_play_msf *args
1869				= (struct ioc_play_msf *) addr;
1870			struct cd_mode_data *data;
1871
1872			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
1873				      M_WAITOK);
1874
1875			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1876				  ("trying to do CDIOCPLAYMSF\n"));
1877
1878			error = cdgetmode(periph, data, AUDIO_PAGE);
1879			if (error) {
1880				free(data, M_TEMP);
1881				break;
1882			}
1883			data->page.audio.flags &= ~CD_PA_SOTC;
1884			data->page.audio.flags |= CD_PA_IMMED;
1885			error = cdsetmode(periph, data);
1886			free(data, M_TEMP);
1887			if (error)
1888				break;
1889			error = cdplaymsf(periph,
1890					  args->start_m,
1891					  args->start_s,
1892					  args->start_f,
1893					  args->end_m,
1894					  args->end_s,
1895					  args->end_f);
1896		}
1897		break;
1898	case CDIOCPLAYBLOCKS:
1899		{
1900			struct ioc_play_blocks *args
1901				= (struct ioc_play_blocks *) addr;
1902			struct cd_mode_data *data;
1903
1904			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1905				  ("trying to do CDIOCPLAYBLOCKS\n"));
1906
1907			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
1908				      M_WAITOK);
1909
1910			error = cdgetmode(periph, data, AUDIO_PAGE);
1911			if (error) {
1912				free(data, M_TEMP);
1913				break;
1914			}
1915			data->page.audio.flags &= ~CD_PA_SOTC;
1916			data->page.audio.flags |= CD_PA_IMMED;
1917			error = cdsetmode(periph, data);
1918			free(data, M_TEMP);
1919			if (error)
1920				break;
1921			error = cdplay(periph, args->blk, args->len);
1922		}
1923		break;
1924	case CDIOCREADSUBCHANNEL:
1925		{
1926			struct ioc_read_subchannel *args
1927				= (struct ioc_read_subchannel *) addr;
1928			struct cd_sub_channel_info *data;
1929			u_int32_t len = args->data_len;
1930
1931			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1932				  ("trying to do CDIOCREADSUBCHANNEL\n"));
1933
1934			data = malloc(sizeof(struct cd_sub_channel_info),
1935				      M_TEMP, M_WAITOK);
1936
1937			if ((len > sizeof(struct cd_sub_channel_info)) ||
1938			    (len < sizeof(struct cd_sub_channel_header))) {
1939				printf(
1940					"scsi_cd: cdioctl: "
1941					"cdioreadsubchannel: error, len=%d\n",
1942					len);
1943				error = EINVAL;
1944				free(data, M_TEMP);
1945				break;
1946			}
1947
1948			if (softc->quirks & CD_Q_BCD_TRACKS)
1949				args->track = bin2bcd(args->track);
1950
1951			error = cdreadsubchannel(periph, args->address_format,
1952				args->data_format, args->track, data, len);
1953
1954			if (error) {
1955				free(data, M_TEMP);
1956	 			break;
1957			}
1958			if (softc->quirks & CD_Q_BCD_TRACKS)
1959				data->what.track_info.track_number =
1960				    bcd2bin(data->what.track_info.track_number);
1961			len = min(len, ((data->header.data_len[0] << 8) +
1962				data->header.data_len[1] +
1963				sizeof(struct cd_sub_channel_header)));
1964			if (copyout(data, args->data, len) != 0) {
1965				error = EFAULT;
1966			}
1967			free(data, M_TEMP);
1968		}
1969		break;
1970
1971	case CDIOREADTOCHEADER:
1972		{
1973			struct ioc_toc_header *th;
1974
1975			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1976				  ("trying to do CDIOREADTOCHEADER\n"));
1977
1978			th = malloc(sizeof(struct ioc_toc_header), M_TEMP,
1979				    M_WAITOK);
1980			error = cdreadtoc(periph, 0, 0,
1981					  (struct cd_toc_entry *)th,
1982				          sizeof (*th));
1983			if (error) {
1984				free(th, M_TEMP);
1985				break;
1986			}
1987			if (softc->quirks & CD_Q_BCD_TRACKS) {
1988				/* we are going to have to convert the BCD
1989				 * encoding on the cd to what is expected
1990				 */
1991				th->starting_track =
1992					bcd2bin(th->starting_track);
1993				th->ending_track = bcd2bin(th->ending_track);
1994			}
1995			NTOHS(th->len);
1996			bcopy(th, addr, sizeof(*th));
1997			free(th, M_TEMP);
1998		}
1999		break;
2000	case CDIOREADTOCENTRYS:
2001		{
2002			typedef struct {
2003				struct ioc_toc_header header;
2004				struct cd_toc_entry entries[100];
2005			} data_t;
2006			typedef struct {
2007				struct ioc_toc_header header;
2008				struct cd_toc_entry entry;
2009			} lead_t;
2010
2011			data_t *data;
2012			lead_t *lead;
2013			struct ioc_read_toc_entry *te =
2014				(struct ioc_read_toc_entry *) addr;
2015			struct ioc_toc_header *th;
2016			u_int32_t len, readlen, idx, num;
2017			u_int32_t starting_track = te->starting_track;
2018
2019			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2020				  ("trying to do CDIOREADTOCENTRYS\n"));
2021
2022			data = malloc(sizeof(data_t), M_TEMP, M_WAITOK);
2023			lead = malloc(sizeof(lead_t), M_TEMP, M_WAITOK);
2024
2025			if (te->data_len < sizeof(struct cd_toc_entry)
2026			 || (te->data_len % sizeof(struct cd_toc_entry)) != 0
2027			 || (te->address_format != CD_MSF_FORMAT
2028			  && te->address_format != CD_LBA_FORMAT)) {
2029				error = EINVAL;
2030				printf("scsi_cd: error in readtocentries, "
2031				       "returning EINVAL\n");
2032				free(data, M_TEMP);
2033				free(lead, M_TEMP);
2034				break;
2035			}
2036
2037			th = &data->header;
2038			error = cdreadtoc(periph, 0, 0,
2039					  (struct cd_toc_entry *)th,
2040					  sizeof (*th));
2041			if (error) {
2042				free(data, M_TEMP);
2043				free(lead, M_TEMP);
2044				break;
2045			}
2046
2047			if (softc->quirks & CD_Q_BCD_TRACKS) {
2048				/* we are going to have to convert the BCD
2049				 * encoding on the cd to what is expected
2050				 */
2051				th->starting_track =
2052				    bcd2bin(th->starting_track);
2053				th->ending_track = bcd2bin(th->ending_track);
2054			}
2055
2056			if (starting_track == 0)
2057				starting_track = th->starting_track;
2058			else if (starting_track == LEADOUT)
2059				starting_track = th->ending_track + 1;
2060			else if (starting_track < th->starting_track ||
2061				 starting_track > th->ending_track + 1) {
2062				printf("scsi_cd: error in readtocentries, "
2063				       "returning EINVAL\n");
2064				free(data, M_TEMP);
2065				free(lead, M_TEMP);
2066				error = EINVAL;
2067				break;
2068			}
2069
2070			/* calculate reading length without leadout entry */
2071			readlen = (th->ending_track - starting_track + 1) *
2072				  sizeof(struct cd_toc_entry);
2073
2074			/* and with leadout entry */
2075			len = readlen + sizeof(struct cd_toc_entry);
2076			if (te->data_len < len) {
2077				len = te->data_len;
2078				if (readlen > len)
2079					readlen = len;
2080			}
2081			if (len > sizeof(data->entries)) {
2082				printf("scsi_cd: error in readtocentries, "
2083				       "returning EINVAL\n");
2084				error = EINVAL;
2085				free(data, M_TEMP);
2086				free(lead, M_TEMP);
2087				break;
2088			}
2089			num = len / sizeof(struct cd_toc_entry);
2090
2091			if (readlen > 0) {
2092				error = cdreadtoc(periph, te->address_format,
2093						  starting_track,
2094						  (struct cd_toc_entry *)data,
2095						  readlen + sizeof (*th));
2096				if (error) {
2097					free(data, M_TEMP);
2098					free(lead, M_TEMP);
2099					break;
2100				}
2101			}
2102
2103			/* make leadout entry if needed */
2104			idx = starting_track + num - 1;
2105			if (softc->quirks & CD_Q_BCD_TRACKS)
2106				th->ending_track = bcd2bin(th->ending_track);
2107			if (idx == th->ending_track + 1) {
2108				error = cdreadtoc(periph, te->address_format,
2109						  LEADOUT,
2110						  (struct cd_toc_entry *)lead,
2111						  sizeof(*lead));
2112				if (error) {
2113					free(data, M_TEMP);
2114					free(lead, M_TEMP);
2115					break;
2116				}
2117				data->entries[idx - starting_track] =
2118					lead->entry;
2119			}
2120			if (softc->quirks & CD_Q_BCD_TRACKS) {
2121				for (idx = 0; idx < num - 1; idx++) {
2122					data->entries[idx].track =
2123					    bcd2bin(data->entries[idx].track);
2124				}
2125			}
2126
2127			error = copyout(data->entries, te->data, len);
2128			free(data, M_TEMP);
2129			free(lead, M_TEMP);
2130		}
2131		break;
2132	case CDIOREADTOCENTRY:
2133		{
2134			/* yeah yeah, this is ugly */
2135			typedef struct {
2136				struct ioc_toc_header header;
2137				struct cd_toc_entry entry;
2138			} data_t;
2139
2140			data_t *data;
2141			struct ioc_read_toc_single_entry *te =
2142				(struct ioc_read_toc_single_entry *) addr;
2143			struct ioc_toc_header *th;
2144			u_int32_t track;
2145
2146			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2147				  ("trying to do CDIOREADTOCENTRY\n"));
2148
2149			data = malloc(sizeof(data_t), M_TEMP, M_WAITOK);
2150
2151			if (te->address_format != CD_MSF_FORMAT
2152			    && te->address_format != CD_LBA_FORMAT) {
2153				printf("error in readtocentry, "
2154				       " returning EINVAL\n");
2155				free(data, M_TEMP);
2156				error = EINVAL;
2157				break;
2158			}
2159
2160			th = &data->header;
2161			error = cdreadtoc(periph, 0, 0,
2162					  (struct cd_toc_entry *)th,
2163					  sizeof (*th));
2164			if (error) {
2165				free(data, M_TEMP);
2166				break;
2167			}
2168
2169			if (softc->quirks & CD_Q_BCD_TRACKS) {
2170				/* we are going to have to convert the BCD
2171				 * encoding on the cd to what is expected
2172				 */
2173				th->starting_track =
2174				    bcd2bin(th->starting_track);
2175				th->ending_track = bcd2bin(th->ending_track);
2176			}
2177			track = te->track;
2178			if (track == 0)
2179				track = th->starting_track;
2180			else if (track == LEADOUT)
2181				/* OK */;
2182			else if (track < th->starting_track ||
2183				 track > th->ending_track + 1) {
2184				printf("error in readtocentry, "
2185				       " returning EINVAL\n");
2186				free(data, M_TEMP);
2187				error = EINVAL;
2188				break;
2189			}
2190
2191			error = cdreadtoc(periph, te->address_format, track,
2192					  (struct cd_toc_entry *)data,
2193					  sizeof(data_t));
2194			if (error) {
2195				free(data, M_TEMP);
2196				break;
2197			}
2198
2199			if (softc->quirks & CD_Q_BCD_TRACKS)
2200				data->entry.track = bcd2bin(data->entry.track);
2201			bcopy(&data->entry, &te->entry,
2202			      sizeof(struct cd_toc_entry));
2203			free(data, M_TEMP);
2204		}
2205		break;
2206	case CDIOCSETPATCH:
2207		{
2208			struct ioc_patch *arg = (struct ioc_patch *) addr;
2209			struct cd_mode_data *data;
2210
2211			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2212				  ("trying to do CDIOCSETPATCH\n"));
2213
2214			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2215				      M_WAITOK);
2216			error = cdgetmode(periph, data, AUDIO_PAGE);
2217			if (error) {
2218				free(data, M_TEMP);
2219				break;
2220			}
2221			data->page.audio.port[LEFT_PORT].channels =
2222				arg->patch[0];
2223			data->page.audio.port[RIGHT_PORT].channels =
2224				arg->patch[1];
2225			data->page.audio.port[2].channels = arg->patch[2];
2226			data->page.audio.port[3].channels = arg->patch[3];
2227			error = cdsetmode(periph, data);
2228			free(data, M_TEMP);
2229		}
2230		break;
2231	case CDIOCGETVOL:
2232		{
2233			struct ioc_vol *arg = (struct ioc_vol *) addr;
2234			struct cd_mode_data *data;
2235
2236			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2237				  ("trying to do CDIOCGETVOL\n"));
2238
2239			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2240				      M_WAITOK);
2241			error = cdgetmode(periph, data, AUDIO_PAGE);
2242			if (error) {
2243				free(data, M_TEMP);
2244				break;
2245			}
2246			arg->vol[LEFT_PORT] =
2247				data->page.audio.port[LEFT_PORT].volume;
2248			arg->vol[RIGHT_PORT] =
2249				data->page.audio.port[RIGHT_PORT].volume;
2250			arg->vol[2] = data->page.audio.port[2].volume;
2251			arg->vol[3] = data->page.audio.port[3].volume;
2252			free(data, M_TEMP);
2253		}
2254		break;
2255	case CDIOCSETVOL:
2256		{
2257			struct ioc_vol *arg = (struct ioc_vol *) addr;
2258			struct cd_mode_data *data;
2259
2260			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2261				  ("trying to do CDIOCSETVOL\n"));
2262
2263			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2264				      M_WAITOK);
2265			error = cdgetmode(periph, data, AUDIO_PAGE);
2266			if (error) {
2267				free(data, M_TEMP);
2268				break;
2269			}
2270			data->page.audio.port[LEFT_PORT].channels = CHANNEL_0;
2271			data->page.audio.port[LEFT_PORT].volume =
2272				arg->vol[LEFT_PORT];
2273			data->page.audio.port[RIGHT_PORT].channels = CHANNEL_1;
2274			data->page.audio.port[RIGHT_PORT].volume =
2275				arg->vol[RIGHT_PORT];
2276			data->page.audio.port[2].volume = arg->vol[2];
2277			data->page.audio.port[3].volume = arg->vol[3];
2278			error = cdsetmode(periph, data);
2279			free(data, M_TEMP);
2280		}
2281		break;
2282	case CDIOCSETMONO:
2283		{
2284			struct cd_mode_data *data;
2285
2286			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2287				  ("trying to do CDIOCSETMONO\n"));
2288
2289			data = malloc(sizeof(struct cd_mode_data),
2290				      M_TEMP, M_WAITOK);
2291			error = cdgetmode(periph, data, AUDIO_PAGE);
2292			if (error) {
2293				free(data, M_TEMP);
2294				break;
2295			}
2296			data->page.audio.port[LEFT_PORT].channels =
2297				LEFT_CHANNEL | RIGHT_CHANNEL;
2298			data->page.audio.port[RIGHT_PORT].channels =
2299				LEFT_CHANNEL | RIGHT_CHANNEL;
2300			data->page.audio.port[2].channels = 0;
2301			data->page.audio.port[3].channels = 0;
2302			error = cdsetmode(periph, data);
2303			free(data, M_TEMP);
2304		}
2305		break;
2306	case CDIOCSETSTEREO:
2307		{
2308			struct cd_mode_data *data;
2309
2310			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2311				  ("trying to do CDIOCSETSTEREO\n"));
2312
2313			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2314				      M_WAITOK);
2315			error = cdgetmode(periph, data, AUDIO_PAGE);
2316			if (error) {
2317				free(data, M_TEMP);
2318				break;
2319			}
2320			data->page.audio.port[LEFT_PORT].channels =
2321				LEFT_CHANNEL;
2322			data->page.audio.port[RIGHT_PORT].channels =
2323				RIGHT_CHANNEL;
2324			data->page.audio.port[2].channels = 0;
2325			data->page.audio.port[3].channels = 0;
2326			error = cdsetmode(periph, data);
2327			free(data, M_TEMP);
2328		}
2329		break;
2330	case CDIOCSETMUTE:
2331		{
2332			struct cd_mode_data *data;
2333
2334			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2335				  ("trying to do CDIOCSETMUTE\n"));
2336
2337			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2338				      M_WAITOK);
2339			error = cdgetmode(periph, data, AUDIO_PAGE);
2340			if (error) {
2341				free(data, M_TEMP);
2342				break;
2343			}
2344			data->page.audio.port[LEFT_PORT].channels = 0;
2345			data->page.audio.port[RIGHT_PORT].channels = 0;
2346			data->page.audio.port[2].channels = 0;
2347			data->page.audio.port[3].channels = 0;
2348			error = cdsetmode(periph, data);
2349			free(data, M_TEMP);
2350		}
2351		break;
2352	case CDIOCSETLEFT:
2353		{
2354			struct cd_mode_data *data;
2355
2356			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2357				  ("trying to do CDIOCSETLEFT\n"));
2358
2359			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2360				      M_WAITOK);
2361			error = cdgetmode(periph, data, AUDIO_PAGE);
2362			if (error) {
2363				free(data, M_TEMP);
2364				break;
2365			}
2366			data->page.audio.port[LEFT_PORT].channels =
2367				LEFT_CHANNEL;
2368			data->page.audio.port[RIGHT_PORT].channels =
2369				LEFT_CHANNEL;
2370			data->page.audio.port[2].channels = 0;
2371			data->page.audio.port[3].channels = 0;
2372			error = cdsetmode(periph, data);
2373			free(data, M_TEMP);
2374		}
2375		break;
2376	case CDIOCSETRIGHT:
2377		{
2378			struct cd_mode_data *data;
2379
2380			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2381				  ("trying to do CDIOCSETRIGHT\n"));
2382
2383			data = malloc(sizeof(struct cd_mode_data), M_TEMP,
2384				      M_WAITOK);
2385			error = cdgetmode(periph, data, AUDIO_PAGE);
2386			if (error) {
2387				free(data, M_TEMP);
2388				break;
2389			}
2390			data->page.audio.port[LEFT_PORT].channels =
2391				RIGHT_CHANNEL;
2392			data->page.audio.port[RIGHT_PORT].channels =
2393				RIGHT_CHANNEL;
2394			data->page.audio.port[2].channels = 0;
2395			data->page.audio.port[3].channels = 0;
2396			error = cdsetmode(periph, data);
2397			free(data, M_TEMP);
2398		}
2399		break;
2400	case CDIOCRESUME:
2401		error = cdpause(periph, 1);
2402		break;
2403	case CDIOCPAUSE:
2404		error = cdpause(periph, 0);
2405		break;
2406	case CDIOCSTART:
2407		error = cdstartunit(periph);
2408		break;
2409	case CDIOCSTOP:
2410		error = cdstopunit(periph, 0);
2411		break;
2412	case CDIOCEJECT:
2413		error = cdstopunit(periph, 1);
2414		break;
2415	case CDIOCALLOW:
2416		cdprevent(periph, PR_ALLOW);
2417		break;
2418	case CDIOCPREVENT:
2419		cdprevent(periph, PR_PREVENT);
2420		break;
2421	case CDIOCSETDEBUG:
2422		/* sc_link->flags |= (SDEV_DB1 | SDEV_DB2); */
2423		error = ENOTTY;
2424		break;
2425	case CDIOCCLRDEBUG:
2426		/* sc_link->flags &= ~(SDEV_DB1 | SDEV_DB2); */
2427		error = ENOTTY;
2428		break;
2429	case CDIOCRESET:
2430		/* return (cd_reset(periph)); */
2431		error = ENOTTY;
2432		break;
2433	case DVDIOCSENDKEY:
2434	case DVDIOCREPORTKEY: {
2435		struct dvd_authinfo *authinfo;
2436
2437		authinfo = (struct dvd_authinfo *)addr;
2438
2439		if (cmd == DVDIOCREPORTKEY)
2440			error = cdreportkey(periph, authinfo);
2441		else
2442			error = cdsendkey(periph, authinfo);
2443		break;
2444	}
2445	case DVDIOCREADSTRUCTURE: {
2446		struct dvd_struct *dvdstruct;
2447
2448		dvdstruct = (struct dvd_struct *)addr;
2449
2450		error = cdreaddvdstructure(periph, dvdstruct);
2451
2452		break;
2453	}
2454	default:
2455		error = cam_periph_ioctl(periph, cmd, addr, cderror);
2456		break;
2457	}
2458
2459	cam_periph_unlock(periph);
2460
2461	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdioctl\n"));
2462
2463	return (error);
2464}
2465
2466static void
2467cdprevent(struct cam_periph *periph, int action)
2468{
2469	union	ccb *ccb;
2470	struct	cd_softc *softc;
2471	int	error;
2472
2473	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdprevent\n"));
2474
2475	softc = (struct cd_softc *)periph->softc;
2476
2477	if (((action == PR_ALLOW)
2478	  && (softc->flags & CD_FLAG_DISC_LOCKED) == 0)
2479	 || ((action == PR_PREVENT)
2480	  && (softc->flags & CD_FLAG_DISC_LOCKED) != 0)) {
2481		return;
2482	}
2483
2484	ccb = cdgetccb(periph, /* priority */ 1);
2485
2486	scsi_prevent(&ccb->csio,
2487		     /*retries*/ 1,
2488		     cddone,
2489		     MSG_SIMPLE_Q_TAG,
2490		     action,
2491		     SSD_FULL_SIZE,
2492		     /* timeout */60000);
2493
2494	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2495			/*sense_flags*/SF_RETRY_UA|SF_NO_PRINT|SF_RETRY_SELTO);
2496
2497	xpt_release_ccb(ccb);
2498
2499	if (error == 0) {
2500		if (action == PR_ALLOW)
2501			softc->flags &= ~CD_FLAG_DISC_LOCKED;
2502		else
2503			softc->flags |= CD_FLAG_DISC_LOCKED;
2504	}
2505}
2506
2507static int
2508cdsize(dev_t dev, u_int32_t *size)
2509{
2510	struct cam_periph *periph;
2511	struct cd_softc *softc;
2512	union ccb *ccb;
2513	struct scsi_read_capacity_data *rcap_buf;
2514	int error;
2515
2516	periph = cam_extend_get(cdperiphs, dkunit(dev));
2517
2518	if (periph == NULL)
2519		return (ENXIO);
2520
2521	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdsize\n"));
2522
2523	softc = (struct cd_softc *)periph->softc;
2524
2525	ccb = cdgetccb(periph, /* priority */ 1);
2526
2527	rcap_buf = malloc(sizeof(struct scsi_read_capacity_data),
2528			  M_TEMP, M_WAITOK);
2529
2530	scsi_read_capacity(&ccb->csio,
2531			   /*retries*/ 1,
2532			   cddone,
2533			   MSG_SIMPLE_Q_TAG,
2534			   rcap_buf,
2535			   SSD_FULL_SIZE,
2536			   /* timeout */20000);
2537
2538	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2539			 /*sense_flags*/SF_RETRY_UA|SF_NO_PRINT|SF_RETRY_SELTO);
2540
2541	xpt_release_ccb(ccb);
2542
2543	softc->params.disksize = scsi_4btoul(rcap_buf->addr) + 1;
2544	softc->params.blksize  = scsi_4btoul(rcap_buf->length);
2545	/*
2546	 * SCSI-3 mandates that the reported blocksize shall be 2048.
2547	 * Older drives sometimes report funny values, trim it down to
2548	 * 2048, or other parts of the kernel will get confused.
2549	 *
2550	 * XXX we leave drives alone that might report 512 bytes, as
2551	 * well as drives reporting more weird sizes like perhaps 4K.
2552	 */
2553	if (softc->params.blksize > 2048 && softc->params.blksize <= 2352)
2554		softc->params.blksize = 2048;
2555
2556	free(rcap_buf, M_TEMP);
2557	*size = softc->params.disksize;
2558
2559	return (error);
2560
2561}
2562
2563/*
2564 * The idea here is to try to figure out whether the first track is data or
2565 * audio.  If it is data, we can at least attempt to read a disklabel off
2566 * the first sector of the disk.  If it is audio, there won't be a
2567 * disklabel.
2568 *
2569 * This routine returns 0 if the first track is data, and non-zero if there
2570 * is an error or the first track is audio.  (If either non-zero case, we
2571 * should not attempt to read the disklabel.)
2572 */
2573static int
2574cdfirsttrackisdata(struct cam_periph *periph)
2575{
2576	struct cdtocdata {
2577		struct ioc_toc_header header;
2578		struct cd_toc_entry entries[100];
2579	};
2580	struct cd_softc *softc;
2581	struct ioc_toc_header *th;
2582	struct cdtocdata *data;
2583	int num_entries, i;
2584	int error, first_track_audio;
2585
2586	error = 0;
2587	first_track_audio = -1;
2588
2589	softc = (struct cd_softc *)periph->softc;
2590
2591	data = malloc(sizeof(struct cdtocdata), M_TEMP, M_WAITOK);
2592
2593	th = &data->header;
2594	error = cdreadtoc(periph, 0, 0, (struct cd_toc_entry *)data,
2595			  sizeof(*data));
2596
2597	if (error)
2598		goto bailout;
2599
2600	if (softc->quirks & CD_Q_BCD_TRACKS) {
2601		/* we are going to have to convert the BCD
2602		 * encoding on the cd to what is expected
2603		 */
2604		th->starting_track =
2605		    bcd2bin(th->starting_track);
2606		th->ending_track = bcd2bin(th->ending_track);
2607	}
2608	th->len = scsi_2btoul((u_int8_t *)&th->len);
2609
2610	if ((th->len - 2) > 0)
2611		num_entries = (th->len - 2) / sizeof(struct cd_toc_entry);
2612	else
2613		num_entries = 0;
2614
2615	for (i = 0; i < num_entries; i++) {
2616		if (data->entries[i].track == th->starting_track) {
2617			if (data->entries[i].control & 0x4)
2618				first_track_audio = 0;
2619			else
2620				first_track_audio = 1;
2621			break;
2622		}
2623	}
2624
2625	if (first_track_audio == -1)
2626		error = ENOENT;
2627	else if (first_track_audio == 1)
2628		error = EINVAL;
2629	else
2630		error = 0;
2631bailout:
2632	free(data, M_TEMP);
2633
2634	return(error);
2635}
2636
2637static int
2638cderror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
2639{
2640	struct cd_softc *softc;
2641	struct cam_periph *periph;
2642
2643	periph = xpt_path_periph(ccb->ccb_h.path);
2644	softc = (struct cd_softc *)periph->softc;
2645
2646	/*
2647	 * XXX
2648	 * Until we have a better way of doing pack validation,
2649	 * don't treat UAs as errors.
2650	 */
2651	sense_flags |= SF_RETRY_UA;
2652	return (cam_periph_error(ccb, cam_flags, sense_flags,
2653				 &softc->saved_ccb));
2654}
2655
2656/*
2657 * Read table of contents
2658 */
2659static int
2660cdreadtoc(struct cam_periph *periph, u_int32_t mode, u_int32_t start,
2661	    struct cd_toc_entry *data, u_int32_t len)
2662{
2663	struct scsi_read_toc *scsi_cmd;
2664	u_int32_t ntoc;
2665        struct ccb_scsiio *csio;
2666	union ccb *ccb;
2667	int error;
2668
2669	ntoc = len;
2670	error = 0;
2671
2672	ccb = cdgetccb(periph, /* priority */ 1);
2673
2674	csio = &ccb->csio;
2675
2676	cam_fill_csio(csio,
2677		      /* retries */ 1,
2678		      /* cbfcnp */ cddone,
2679		      /* flags */ CAM_DIR_IN,
2680		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2681		      /* data_ptr */ (u_int8_t *)data,
2682		      /* dxfer_len */ len,
2683		      /* sense_len */ SSD_FULL_SIZE,
2684		      sizeof(struct scsi_read_toc),
2685 		      /* timeout */ 50000);
2686
2687	scsi_cmd = (struct scsi_read_toc *)&csio->cdb_io.cdb_bytes;
2688	bzero (scsi_cmd, sizeof(*scsi_cmd));
2689
2690	if (mode == CD_MSF_FORMAT)
2691		scsi_cmd->byte2 |= CD_MSF;
2692	scsi_cmd->from_track = start;
2693	/* scsi_ulto2b(ntoc, (u_int8_t *)scsi_cmd->data_len); */
2694	scsi_cmd->data_len[0] = (ntoc) >> 8;
2695	scsi_cmd->data_len[1] = (ntoc) & 0xff;
2696
2697	scsi_cmd->op_code = READ_TOC;
2698
2699	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2700			 /*sense_flags*/SF_RETRY_UA|SF_RETRY_SELTO);
2701
2702	xpt_release_ccb(ccb);
2703
2704	return(error);
2705}
2706
2707static int
2708cdreadsubchannel(struct cam_periph *periph, u_int32_t mode,
2709		 u_int32_t format, int track,
2710		 struct cd_sub_channel_info *data, u_int32_t len)
2711{
2712	struct scsi_read_subchannel *scsi_cmd;
2713        struct ccb_scsiio *csio;
2714	union ccb *ccb;
2715	int error;
2716
2717	error = 0;
2718
2719	ccb = cdgetccb(periph, /* priority */ 1);
2720
2721	csio = &ccb->csio;
2722
2723	cam_fill_csio(csio,
2724		      /* retries */ 1,
2725		      /* cbfcnp */ cddone,
2726		      /* flags */ CAM_DIR_IN,
2727		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2728		      /* data_ptr */ (u_int8_t *)data,
2729		      /* dxfer_len */ len,
2730		      /* sense_len */ SSD_FULL_SIZE,
2731		      sizeof(struct scsi_read_subchannel),
2732 		      /* timeout */ 50000);
2733
2734	scsi_cmd = (struct scsi_read_subchannel *)&csio->cdb_io.cdb_bytes;
2735	bzero (scsi_cmd, sizeof(*scsi_cmd));
2736
2737	scsi_cmd->op_code = READ_SUBCHANNEL;
2738	if (mode == CD_MSF_FORMAT)
2739		scsi_cmd->byte1 |= CD_MSF;
2740	scsi_cmd->byte2 = SRS_SUBQ;
2741	scsi_cmd->subchan_format = format;
2742	scsi_cmd->track = track;
2743	scsi_ulto2b(len, (u_int8_t *)scsi_cmd->data_len);
2744	scsi_cmd->control = 0;
2745
2746	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2747			 /*sense_flags*/SF_RETRY_UA|SF_RETRY_SELTO);
2748
2749	xpt_release_ccb(ccb);
2750
2751	return(error);
2752}
2753
2754
2755static int
2756cdgetmode(struct cam_periph *periph, struct cd_mode_data *data, u_int32_t page)
2757{
2758	struct scsi_mode_sense_6 *scsi_cmd;
2759        struct ccb_scsiio *csio;
2760	union ccb *ccb;
2761	int error;
2762
2763	ccb = cdgetccb(periph, /* priority */ 1);
2764
2765	csio = &ccb->csio;
2766
2767	bzero(data, sizeof(*data));
2768	cam_fill_csio(csio,
2769		      /* retries */ 1,
2770		      /* cbfcnp */ cddone,
2771		      /* flags */ CAM_DIR_IN,
2772		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2773		      /* data_ptr */ (u_int8_t *)data,
2774		      /* dxfer_len */ sizeof(*data),
2775		      /* sense_len */ SSD_FULL_SIZE,
2776		      sizeof(struct scsi_mode_sense_6),
2777 		      /* timeout */ 50000);
2778
2779	scsi_cmd = (struct scsi_mode_sense_6 *)&csio->cdb_io.cdb_bytes;
2780	bzero (scsi_cmd, sizeof(*scsi_cmd));
2781
2782	scsi_cmd->page = page;
2783	scsi_cmd->length = sizeof(*data) & 0xff;
2784	scsi_cmd->opcode = MODE_SENSE;
2785
2786	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2787			 /*sense_flags*/SF_RETRY_UA|SF_RETRY_SELTO);
2788
2789	xpt_release_ccb(ccb);
2790
2791	return(error);
2792}
2793
2794static int
2795cdsetmode(struct cam_periph *periph, struct cd_mode_data *data)
2796{
2797	struct scsi_mode_select_6 *scsi_cmd;
2798        struct ccb_scsiio *csio;
2799	union ccb *ccb;
2800	int error;
2801
2802	ccb = cdgetccb(periph, /* priority */ 1);
2803
2804	csio = &ccb->csio;
2805
2806	error = 0;
2807
2808	cam_fill_csio(csio,
2809		      /* retries */ 1,
2810		      /* cbfcnp */ cddone,
2811		      /* flags */ CAM_DIR_OUT,
2812		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2813		      /* data_ptr */ (u_int8_t *)data,
2814		      /* dxfer_len */ sizeof(*data),
2815		      /* sense_len */ SSD_FULL_SIZE,
2816		      sizeof(struct scsi_mode_select_6),
2817 		      /* timeout */ 50000);
2818
2819	scsi_cmd = (struct scsi_mode_select_6 *)&csio->cdb_io.cdb_bytes;
2820
2821	bzero(scsi_cmd, sizeof(*scsi_cmd));
2822	scsi_cmd->opcode = MODE_SELECT;
2823	scsi_cmd->byte2 |= SMS_PF;
2824	scsi_cmd->length = sizeof(*data) & 0xff;
2825	data->header.data_length = 0;
2826	/*
2827	 * SONY drives do not allow a mode select with a medium_type
2828	 * value that has just been returned by a mode sense; use a
2829	 * medium_type of 0 (Default) instead.
2830	 */
2831	data->header.medium_type = 0;
2832
2833	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2834			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
2835
2836	xpt_release_ccb(ccb);
2837
2838	return(error);
2839}
2840
2841
2842static int
2843cdplay(struct cam_periph *periph, u_int32_t blk, u_int32_t len)
2844{
2845	struct ccb_scsiio *csio;
2846	union ccb *ccb;
2847	int error;
2848	u_int8_t cdb_len;
2849
2850	error = 0;
2851	ccb = cdgetccb(periph, /* priority */ 1);
2852	csio = &ccb->csio;
2853	/*
2854	 * Use the smallest possible command to perform the operation.
2855	 */
2856	if ((len & 0xffff0000) == 0) {
2857		/*
2858		 * We can fit in a 10 byte cdb.
2859		 */
2860		struct scsi_play_10 *scsi_cmd;
2861
2862		scsi_cmd = (struct scsi_play_10 *)&csio->cdb_io.cdb_bytes;
2863		bzero (scsi_cmd, sizeof(*scsi_cmd));
2864		scsi_cmd->op_code = PLAY_10;
2865		scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
2866		scsi_ulto2b(len, (u_int8_t *)scsi_cmd->xfer_len);
2867		cdb_len = sizeof(*scsi_cmd);
2868	} else  {
2869		struct scsi_play_12 *scsi_cmd;
2870
2871		scsi_cmd = (struct scsi_play_12 *)&csio->cdb_io.cdb_bytes;
2872		bzero (scsi_cmd, sizeof(*scsi_cmd));
2873		scsi_cmd->op_code = PLAY_12;
2874		scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
2875		scsi_ulto4b(len, (u_int8_t *)scsi_cmd->xfer_len);
2876		cdb_len = sizeof(*scsi_cmd);
2877	}
2878	cam_fill_csio(csio,
2879		      /*retries*/2,
2880		      cddone,
2881		      /*flags*/CAM_DIR_NONE,
2882		      MSG_SIMPLE_Q_TAG,
2883		      /*dataptr*/NULL,
2884		      /*datalen*/0,
2885		      /*sense_len*/SSD_FULL_SIZE,
2886		      cdb_len,
2887		      /*timeout*/50 * 1000);
2888
2889	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2890			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
2891
2892	xpt_release_ccb(ccb);
2893
2894	return(error);
2895}
2896
2897static int
2898cdplaymsf(struct cam_periph *periph, u_int32_t startm, u_int32_t starts,
2899	  u_int32_t startf, u_int32_t endm, u_int32_t ends, u_int32_t endf)
2900{
2901	struct scsi_play_msf *scsi_cmd;
2902        struct ccb_scsiio *csio;
2903	union ccb *ccb;
2904	int error;
2905
2906	error = 0;
2907
2908	ccb = cdgetccb(periph, /* priority */ 1);
2909
2910	csio = &ccb->csio;
2911
2912	cam_fill_csio(csio,
2913		      /* retries */ 1,
2914		      /* cbfcnp */ cddone,
2915		      /* flags */ CAM_DIR_NONE,
2916		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2917		      /* data_ptr */ NULL,
2918		      /* dxfer_len */ 0,
2919		      /* sense_len */ SSD_FULL_SIZE,
2920		      sizeof(struct scsi_play_msf),
2921 		      /* timeout */ 50000);
2922
2923	scsi_cmd = (struct scsi_play_msf *)&csio->cdb_io.cdb_bytes;
2924	bzero (scsi_cmd, sizeof(*scsi_cmd));
2925
2926        scsi_cmd->op_code = PLAY_MSF;
2927        scsi_cmd->start_m = startm;
2928        scsi_cmd->start_s = starts;
2929        scsi_cmd->start_f = startf;
2930        scsi_cmd->end_m = endm;
2931        scsi_cmd->end_s = ends;
2932        scsi_cmd->end_f = endf;
2933
2934	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2935			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
2936
2937	xpt_release_ccb(ccb);
2938
2939	return(error);
2940}
2941
2942
2943static int
2944cdplaytracks(struct cam_periph *periph, u_int32_t strack, u_int32_t sindex,
2945	     u_int32_t etrack, u_int32_t eindex)
2946{
2947	struct scsi_play_track *scsi_cmd;
2948        struct ccb_scsiio *csio;
2949	union ccb *ccb;
2950	int error;
2951
2952	error = 0;
2953
2954	ccb = cdgetccb(periph, /* priority */ 1);
2955
2956	csio = &ccb->csio;
2957
2958	cam_fill_csio(csio,
2959		      /* retries */ 1,
2960		      /* cbfcnp */ cddone,
2961		      /* flags */ CAM_DIR_NONE,
2962		      /* tag_action */ MSG_SIMPLE_Q_TAG,
2963		      /* data_ptr */ NULL,
2964		      /* dxfer_len */ 0,
2965		      /* sense_len */ SSD_FULL_SIZE,
2966		      sizeof(struct scsi_play_track),
2967 		      /* timeout */ 50000);
2968
2969	scsi_cmd = (struct scsi_play_track *)&csio->cdb_io.cdb_bytes;
2970	bzero (scsi_cmd, sizeof(*scsi_cmd));
2971
2972        scsi_cmd->op_code = PLAY_TRACK;
2973        scsi_cmd->start_track = strack;
2974        scsi_cmd->start_index = sindex;
2975        scsi_cmd->end_track = etrack;
2976        scsi_cmd->end_index = eindex;
2977
2978	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2979			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
2980
2981	xpt_release_ccb(ccb);
2982
2983	return(error);
2984}
2985
2986static int
2987cdpause(struct cam_periph *periph, u_int32_t go)
2988{
2989	struct scsi_pause *scsi_cmd;
2990        struct ccb_scsiio *csio;
2991	union ccb *ccb;
2992	int error;
2993
2994	error = 0;
2995
2996	ccb = cdgetccb(periph, /* priority */ 1);
2997
2998	csio = &ccb->csio;
2999
3000	cam_fill_csio(csio,
3001		      /* retries */ 1,
3002		      /* cbfcnp */ cddone,
3003		      /* flags */ CAM_DIR_NONE,
3004		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3005		      /* data_ptr */ NULL,
3006		      /* dxfer_len */ 0,
3007		      /* sense_len */ SSD_FULL_SIZE,
3008		      sizeof(struct scsi_pause),
3009 		      /* timeout */ 50000);
3010
3011	scsi_cmd = (struct scsi_pause *)&csio->cdb_io.cdb_bytes;
3012	bzero (scsi_cmd, sizeof(*scsi_cmd));
3013
3014        scsi_cmd->op_code = PAUSE;
3015	scsi_cmd->resume = go;
3016
3017	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3018			 /*sense_flags*/SF_RETRY_UA |SF_RETRY_SELTO);
3019
3020	xpt_release_ccb(ccb);
3021
3022	return(error);
3023}
3024
3025static int
3026cdstartunit(struct cam_periph *periph)
3027{
3028	union ccb *ccb;
3029	int error;
3030
3031	error = 0;
3032
3033	ccb = cdgetccb(periph, /* priority */ 1);
3034
3035	scsi_start_stop(&ccb->csio,
3036			/* retries */ 1,
3037			/* cbfcnp */ cddone,
3038			/* tag_action */ MSG_SIMPLE_Q_TAG,
3039			/* start */ TRUE,
3040			/* load_eject */ FALSE,
3041			/* immediate */ FALSE,
3042			/* sense_len */ SSD_FULL_SIZE,
3043			/* timeout */ 50000);
3044
3045	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3046			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3047
3048	xpt_release_ccb(ccb);
3049
3050	return(error);
3051}
3052
3053static int
3054cdstopunit(struct cam_periph *periph, u_int32_t eject)
3055{
3056	union ccb *ccb;
3057	int error;
3058
3059	error = 0;
3060
3061	ccb = cdgetccb(periph, /* priority */ 1);
3062
3063	scsi_start_stop(&ccb->csio,
3064			/* retries */ 1,
3065			/* cbfcnp */ cddone,
3066			/* tag_action */ MSG_SIMPLE_Q_TAG,
3067			/* start */ FALSE,
3068			/* load_eject */ eject,
3069			/* immediate */ FALSE,
3070			/* sense_len */ SSD_FULL_SIZE,
3071			/* timeout */ 50000);
3072
3073	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3074			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3075
3076	xpt_release_ccb(ccb);
3077
3078	return(error);
3079}
3080
3081static int
3082cdreportkey(struct cam_periph *periph, struct dvd_authinfo *authinfo)
3083{
3084	union ccb *ccb;
3085	u_int8_t *databuf;
3086	u_int32_t lba;
3087	int error;
3088	int length;
3089
3090	error = 0;
3091	databuf = NULL;
3092	lba = 0;
3093
3094	ccb = cdgetccb(periph, /* priority */ 1);
3095
3096	switch (authinfo->format) {
3097	case DVD_REPORT_AGID:
3098		length = sizeof(struct scsi_report_key_data_agid);
3099		break;
3100	case DVD_REPORT_CHALLENGE:
3101		length = sizeof(struct scsi_report_key_data_challenge);
3102		break;
3103	case DVD_REPORT_KEY1:
3104		length = sizeof(struct scsi_report_key_data_key1_key2);
3105		break;
3106	case DVD_REPORT_TITLE_KEY:
3107		length = sizeof(struct scsi_report_key_data_title);
3108		/* The lba field is only set for the title key */
3109		lba = authinfo->lba;
3110		break;
3111	case DVD_REPORT_ASF:
3112		length = sizeof(struct scsi_report_key_data_asf);
3113		break;
3114	case DVD_REPORT_RPC:
3115		length = sizeof(struct scsi_report_key_data_rpc);
3116		break;
3117	case DVD_INVALIDATE_AGID:
3118		length = 0;
3119		break;
3120	default:
3121		error = EINVAL;
3122		goto bailout;
3123		break; /* NOTREACHED */
3124	}
3125
3126	if (length != 0) {
3127		databuf = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3128	} else
3129		databuf = NULL;
3130
3131
3132	scsi_report_key(&ccb->csio,
3133			/* retries */ 1,
3134			/* cbfcnp */ cddone,
3135			/* tag_action */ MSG_SIMPLE_Q_TAG,
3136			/* lba */ lba,
3137			/* agid */ authinfo->agid,
3138			/* key_format */ authinfo->format,
3139			/* data_ptr */ databuf,
3140			/* dxfer_len */ length,
3141			/* sense_len */ SSD_FULL_SIZE,
3142			/* timeout */ 50000);
3143
3144	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3145			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3146
3147	if (error != 0)
3148		goto bailout;
3149
3150	if (ccb->csio.resid != 0) {
3151		xpt_print_path(periph->path);
3152		printf("warning, residual for report key command is %d\n",
3153		       ccb->csio.resid);
3154	}
3155
3156	switch(authinfo->format) {
3157	case DVD_REPORT_AGID: {
3158		struct scsi_report_key_data_agid *agid_data;
3159
3160		agid_data = (struct scsi_report_key_data_agid *)databuf;
3161
3162		authinfo->agid = (agid_data->agid & RKD_AGID_MASK) >>
3163			RKD_AGID_SHIFT;
3164		break;
3165	}
3166	case DVD_REPORT_CHALLENGE: {
3167		struct scsi_report_key_data_challenge *chal_data;
3168
3169		chal_data = (struct scsi_report_key_data_challenge *)databuf;
3170
3171		bcopy(chal_data->challenge_key, authinfo->keychal,
3172		      min(sizeof(chal_data->challenge_key),
3173		          sizeof(authinfo->keychal)));
3174		break;
3175	}
3176	case DVD_REPORT_KEY1: {
3177		struct scsi_report_key_data_key1_key2 *key1_data;
3178
3179		key1_data = (struct scsi_report_key_data_key1_key2 *)databuf;
3180
3181		bcopy(key1_data->key1, authinfo->keychal,
3182		      min(sizeof(key1_data->key1), sizeof(authinfo->keychal)));
3183		break;
3184	}
3185	case DVD_REPORT_TITLE_KEY: {
3186		struct scsi_report_key_data_title *title_data;
3187
3188		title_data = (struct scsi_report_key_data_title *)databuf;
3189
3190		authinfo->cpm = (title_data->byte0 & RKD_TITLE_CPM) >>
3191			RKD_TITLE_CPM_SHIFT;
3192		authinfo->cp_sec = (title_data->byte0 & RKD_TITLE_CP_SEC) >>
3193			RKD_TITLE_CP_SEC_SHIFT;
3194		authinfo->cgms = (title_data->byte0 & RKD_TITLE_CMGS_MASK) >>
3195			RKD_TITLE_CMGS_SHIFT;
3196		bcopy(title_data->title_key, authinfo->keychal,
3197		      min(sizeof(title_data->title_key),
3198			  sizeof(authinfo->keychal)));
3199		break;
3200	}
3201	case DVD_REPORT_ASF: {
3202		struct scsi_report_key_data_asf *asf_data;
3203
3204		asf_data = (struct scsi_report_key_data_asf *)databuf;
3205
3206		authinfo->asf = asf_data->success & RKD_ASF_SUCCESS;
3207		break;
3208	}
3209	case DVD_REPORT_RPC: {
3210		struct scsi_report_key_data_rpc *rpc_data;
3211
3212		rpc_data = (struct scsi_report_key_data_rpc *)databuf;
3213
3214		authinfo->reg_type = (rpc_data->byte4 & RKD_RPC_TYPE_MASK) >>
3215			RKD_RPC_TYPE_SHIFT;
3216		authinfo->vend_rsts =
3217			(rpc_data->byte4 & RKD_RPC_VENDOR_RESET_MASK) >>
3218			RKD_RPC_VENDOR_RESET_SHIFT;
3219		authinfo->user_rsts = rpc_data->byte4 & RKD_RPC_USER_RESET_MASK;
3220		authinfo->region = rpc_data->region_mask;
3221		authinfo->rpc_scheme = rpc_data->rpc_scheme1;
3222		break;
3223	}
3224	case DVD_INVALIDATE_AGID:
3225		break;
3226	default:
3227		/* This should be impossible, since we checked above */
3228		error = EINVAL;
3229		goto bailout;
3230		break; /* NOTREACHED */
3231	}
3232bailout:
3233	if (databuf != NULL)
3234		free(databuf, M_DEVBUF);
3235
3236	xpt_release_ccb(ccb);
3237
3238	return(error);
3239}
3240
3241static int
3242cdsendkey(struct cam_periph *periph, struct dvd_authinfo *authinfo)
3243{
3244	union ccb *ccb;
3245	u_int8_t *databuf;
3246	int length;
3247	int error;
3248
3249	error = 0;
3250	databuf = NULL;
3251
3252	ccb = cdgetccb(periph, /* priority */ 1);
3253
3254	switch(authinfo->format) {
3255	case DVD_SEND_CHALLENGE: {
3256		struct scsi_report_key_data_challenge *challenge_data;
3257
3258		length = sizeof(*challenge_data);
3259
3260		challenge_data = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3261
3262		databuf = (u_int8_t *)challenge_data;
3263
3264		scsi_ulto2b(length - sizeof(challenge_data->data_len),
3265			    challenge_data->data_len);
3266
3267		bcopy(authinfo->keychal, challenge_data->challenge_key,
3268		      min(sizeof(authinfo->keychal),
3269			  sizeof(challenge_data->challenge_key)));
3270		break;
3271	}
3272	case DVD_SEND_KEY2: {
3273		struct scsi_report_key_data_key1_key2 *key2_data;
3274
3275		length = sizeof(*key2_data);
3276
3277		key2_data = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3278
3279		databuf = (u_int8_t *)key2_data;
3280
3281		scsi_ulto2b(length - sizeof(key2_data->data_len),
3282			    key2_data->data_len);
3283
3284		bcopy(authinfo->keychal, key2_data->key1,
3285		      min(sizeof(authinfo->keychal), sizeof(key2_data->key1)));
3286
3287		break;
3288	}
3289	case DVD_SEND_RPC: {
3290		struct scsi_send_key_data_rpc *rpc_data;
3291
3292		length = sizeof(*rpc_data);
3293
3294		rpc_data = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3295
3296		databuf = (u_int8_t *)rpc_data;
3297
3298		scsi_ulto2b(length - sizeof(rpc_data->data_len),
3299			    rpc_data->data_len);
3300
3301		rpc_data->region_code = authinfo->region;
3302		break;
3303	}
3304	default:
3305		error = EINVAL;
3306		goto bailout;
3307		break; /* NOTREACHED */
3308	}
3309
3310	scsi_send_key(&ccb->csio,
3311		      /* retries */ 1,
3312		      /* cbfcnp */ cddone,
3313		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3314		      /* agid */ authinfo->agid,
3315		      /* key_format */ authinfo->format,
3316		      /* data_ptr */ databuf,
3317		      /* dxfer_len */ length,
3318		      /* sense_len */ SSD_FULL_SIZE,
3319		      /* timeout */ 50000);
3320
3321	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3322			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3323
3324bailout:
3325
3326	if (databuf != NULL)
3327		free(databuf, M_DEVBUF);
3328
3329	xpt_release_ccb(ccb);
3330
3331	return(error);
3332}
3333
3334static int
3335cdreaddvdstructure(struct cam_periph *periph, struct dvd_struct *dvdstruct)
3336{
3337	union ccb *ccb;
3338	u_int8_t *databuf;
3339	u_int32_t address;
3340	int error;
3341	int length;
3342
3343	error = 0;
3344	databuf = NULL;
3345	/* The address is reserved for many of the formats */
3346	address = 0;
3347
3348	ccb = cdgetccb(periph, /* priority */ 1);
3349
3350	switch(dvdstruct->format) {
3351	case DVD_STRUCT_PHYSICAL:
3352		length = sizeof(struct scsi_read_dvd_struct_data_physical);
3353		break;
3354	case DVD_STRUCT_COPYRIGHT:
3355		length = sizeof(struct scsi_read_dvd_struct_data_copyright);
3356		break;
3357	case DVD_STRUCT_DISCKEY:
3358		length = sizeof(struct scsi_read_dvd_struct_data_disc_key);
3359		break;
3360	case DVD_STRUCT_BCA:
3361		length = sizeof(struct scsi_read_dvd_struct_data_bca);
3362		break;
3363	case DVD_STRUCT_MANUFACT:
3364		length = sizeof(struct scsi_read_dvd_struct_data_manufacturer);
3365		break;
3366	case DVD_STRUCT_CMI:
3367		error = ENODEV;
3368		goto bailout;
3369#ifdef notyet
3370		length = sizeof(struct scsi_read_dvd_struct_data_copy_manage);
3371		address = dvdstruct->address;
3372#endif
3373		break; /* NOTREACHED */
3374	case DVD_STRUCT_PROTDISCID:
3375		length = sizeof(struct scsi_read_dvd_struct_data_prot_discid);
3376		break;
3377	case DVD_STRUCT_DISCKEYBLOCK:
3378		length = sizeof(struct scsi_read_dvd_struct_data_disc_key_blk);
3379		break;
3380	case DVD_STRUCT_DDS:
3381		length = sizeof(struct scsi_read_dvd_struct_data_dds);
3382		break;
3383	case DVD_STRUCT_MEDIUM_STAT:
3384		length = sizeof(struct scsi_read_dvd_struct_data_medium_status);
3385		break;
3386	case DVD_STRUCT_SPARE_AREA:
3387		length = sizeof(struct scsi_read_dvd_struct_data_spare_area);
3388		break;
3389	case DVD_STRUCT_RMD_LAST:
3390		error = ENODEV;
3391		goto bailout;
3392#ifdef notyet
3393		length = sizeof(struct scsi_read_dvd_struct_data_rmd_borderout);
3394		address = dvdstruct->address;
3395#endif
3396		break; /* NOTREACHED */
3397	case DVD_STRUCT_RMD_RMA:
3398		error = ENODEV;
3399		goto bailout;
3400#ifdef notyet
3401		length = sizeof(struct scsi_read_dvd_struct_data_rmd);
3402		address = dvdstruct->address;
3403#endif
3404		break; /* NOTREACHED */
3405	case DVD_STRUCT_PRERECORDED:
3406		length = sizeof(struct scsi_read_dvd_struct_data_leadin);
3407		break;
3408	case DVD_STRUCT_UNIQUEID:
3409		length = sizeof(struct scsi_read_dvd_struct_data_disc_id);
3410		break;
3411	case DVD_STRUCT_DCB:
3412		error = ENODEV;
3413		goto bailout;
3414#ifdef notyet
3415		length = sizeof(struct scsi_read_dvd_struct_data_dcb);
3416		address = dvdstruct->address;
3417#endif
3418		break; /* NOTREACHED */
3419	case DVD_STRUCT_LIST:
3420		/*
3421		 * This is the maximum allocation length for the READ DVD
3422		 * STRUCTURE command.  There's nothing in the MMC3 spec
3423		 * that indicates a limit in the amount of data that can
3424		 * be returned from this call, other than the limits
3425		 * imposed by the 2-byte length variables.
3426		 */
3427		length = 65535;
3428		break;
3429	default:
3430		error = EINVAL;
3431		goto bailout;
3432		break; /* NOTREACHED */
3433	}
3434
3435	if (length != 0) {
3436		databuf = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3437	} else
3438		databuf = NULL;
3439
3440	scsi_read_dvd_structure(&ccb->csio,
3441				/* retries */ 1,
3442				/* cbfcnp */ cddone,
3443				/* tag_action */ MSG_SIMPLE_Q_TAG,
3444				/* lba */ address,
3445				/* layer_number */ dvdstruct->layer_num,
3446				/* key_format */ dvdstruct->format,
3447				/* agid */ dvdstruct->agid,
3448				/* data_ptr */ databuf,
3449				/* dxfer_len */ length,
3450				/* sense_len */ SSD_FULL_SIZE,
3451				/* timeout */ 50000);
3452
3453	error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3454			 /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3455
3456	if (error != 0)
3457		goto bailout;
3458
3459	switch(dvdstruct->format) {
3460	case DVD_STRUCT_PHYSICAL: {
3461		struct scsi_read_dvd_struct_data_layer_desc *inlayer;
3462		struct dvd_layer *outlayer;
3463		struct scsi_read_dvd_struct_data_physical *phys_data;
3464
3465		phys_data =
3466			(struct scsi_read_dvd_struct_data_physical *)databuf;
3467		inlayer = &phys_data->layer_desc;
3468		outlayer = (struct dvd_layer *)&dvdstruct->data;
3469
3470		dvdstruct->length = sizeof(*inlayer);
3471
3472		outlayer->book_type = (inlayer->book_type_version &
3473			RDSD_BOOK_TYPE_MASK) >> RDSD_BOOK_TYPE_SHIFT;
3474		outlayer->book_version = (inlayer->book_type_version &
3475			RDSD_BOOK_VERSION_MASK);
3476		outlayer->disc_size = (inlayer->disc_size_max_rate &
3477			RDSD_DISC_SIZE_MASK) >> RDSD_DISC_SIZE_SHIFT;
3478		outlayer->max_rate = (inlayer->disc_size_max_rate &
3479			RDSD_MAX_RATE_MASK);
3480		outlayer->nlayers = (inlayer->layer_info &
3481			RDSD_NUM_LAYERS_MASK) >> RDSD_NUM_LAYERS_SHIFT;
3482		outlayer->track_path = (inlayer->layer_info &
3483			RDSD_TRACK_PATH_MASK) >> RDSD_TRACK_PATH_SHIFT;
3484		outlayer->layer_type = (inlayer->layer_info &
3485			RDSD_LAYER_TYPE_MASK);
3486		outlayer->linear_density = (inlayer->density &
3487			RDSD_LIN_DENSITY_MASK) >> RDSD_LIN_DENSITY_SHIFT;
3488		outlayer->track_density = (inlayer->density &
3489			RDSD_TRACK_DENSITY_MASK);
3490		outlayer->bca = (inlayer->bca & RDSD_BCA_MASK) >>
3491			RDSD_BCA_SHIFT;
3492		outlayer->start_sector = scsi_3btoul(inlayer->main_data_start);
3493		outlayer->end_sector = scsi_3btoul(inlayer->main_data_end);
3494		outlayer->end_sector_l0 =
3495			scsi_3btoul(inlayer->end_sector_layer0);
3496		break;
3497	}
3498	case DVD_STRUCT_COPYRIGHT: {
3499		struct scsi_read_dvd_struct_data_copyright *copy_data;
3500
3501		copy_data = (struct scsi_read_dvd_struct_data_copyright *)
3502			databuf;
3503
3504		dvdstruct->cpst = copy_data->cps_type;
3505		dvdstruct->rmi = copy_data->region_info;
3506		dvdstruct->length = 0;
3507
3508		break;
3509	}
3510	default:
3511		/*
3512		 * Tell the user what the overall length is, no matter
3513		 * what we can actually fit in the data buffer.
3514		 */
3515		dvdstruct->length = length - ccb->csio.resid -
3516			sizeof(struct scsi_read_dvd_struct_data_header);
3517
3518		/*
3519		 * But only actually copy out the smaller of what we read
3520		 * in or what the structure can take.
3521		 */
3522		bcopy(databuf + sizeof(struct scsi_read_dvd_struct_data_header),
3523		      dvdstruct->data,
3524		      min(sizeof(dvdstruct->data), dvdstruct->length));
3525		break;
3526	}
3527bailout:
3528
3529	if (databuf != NULL)
3530		free(databuf, M_DEVBUF);
3531
3532	xpt_release_ccb(ccb);
3533
3534	return(error);
3535}
3536
3537void
3538scsi_report_key(struct ccb_scsiio *csio, u_int32_t retries,
3539		void (*cbfcnp)(struct cam_periph *, union ccb *),
3540		u_int8_t tag_action, u_int32_t lba, u_int8_t agid,
3541		u_int8_t key_format, u_int8_t *data_ptr, u_int32_t dxfer_len,
3542		u_int8_t sense_len, u_int32_t timeout)
3543{
3544	struct scsi_report_key *scsi_cmd;
3545
3546	scsi_cmd = (struct scsi_report_key *)&csio->cdb_io.cdb_bytes;
3547	bzero(scsi_cmd, sizeof(*scsi_cmd));
3548	scsi_cmd->opcode = REPORT_KEY;
3549	scsi_ulto4b(lba, scsi_cmd->lba);
3550	scsi_ulto2b(dxfer_len, scsi_cmd->alloc_len);
3551	scsi_cmd->agid_keyformat = (agid << RK_KF_AGID_SHIFT) |
3552		(key_format & RK_KF_KEYFORMAT_MASK);
3553
3554	cam_fill_csio(csio,
3555		      retries,
3556		      cbfcnp,
3557		      /*flags*/ (dxfer_len == 0) ? CAM_DIR_NONE : CAM_DIR_IN,
3558		      tag_action,
3559		      /*data_ptr*/ data_ptr,
3560		      /*dxfer_len*/ dxfer_len,
3561		      sense_len,
3562		      sizeof(*scsi_cmd),
3563		      timeout);
3564}
3565
3566void
3567scsi_send_key(struct ccb_scsiio *csio, u_int32_t retries,
3568	      void (*cbfcnp)(struct cam_periph *, union ccb *),
3569	      u_int8_t tag_action, u_int8_t agid, u_int8_t key_format,
3570	      u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
3571	      u_int32_t timeout)
3572{
3573	struct scsi_send_key *scsi_cmd;
3574
3575	scsi_cmd = (struct scsi_send_key *)&csio->cdb_io.cdb_bytes;
3576	bzero(scsi_cmd, sizeof(*scsi_cmd));
3577	scsi_cmd->opcode = SEND_KEY;
3578
3579	scsi_ulto2b(dxfer_len, scsi_cmd->param_len);
3580	scsi_cmd->agid_keyformat = (agid << RK_KF_AGID_SHIFT) |
3581		(key_format & RK_KF_KEYFORMAT_MASK);
3582
3583	cam_fill_csio(csio,
3584		      retries,
3585		      cbfcnp,
3586		      /*flags*/ CAM_DIR_OUT,
3587		      tag_action,
3588		      /*data_ptr*/ data_ptr,
3589		      /*dxfer_len*/ dxfer_len,
3590		      sense_len,
3591		      sizeof(*scsi_cmd),
3592		      timeout);
3593}
3594
3595
3596void
3597scsi_read_dvd_structure(struct ccb_scsiio *csio, u_int32_t retries,
3598			void (*cbfcnp)(struct cam_periph *, union ccb *),
3599			u_int8_t tag_action, u_int32_t address,
3600			u_int8_t layer_number, u_int8_t format, u_int8_t agid,
3601			u_int8_t *data_ptr, u_int32_t dxfer_len,
3602			u_int8_t sense_len, u_int32_t timeout)
3603{
3604	struct scsi_read_dvd_structure *scsi_cmd;
3605
3606	scsi_cmd = (struct scsi_read_dvd_structure *)&csio->cdb_io.cdb_bytes;
3607	bzero(scsi_cmd, sizeof(*scsi_cmd));
3608	scsi_cmd->opcode = READ_DVD_STRUCTURE;
3609
3610	scsi_ulto4b(address, scsi_cmd->address);
3611	scsi_cmd->layer_number = layer_number;
3612	scsi_cmd->format = format;
3613	scsi_ulto2b(dxfer_len, scsi_cmd->alloc_len);
3614	/* The AGID is the top two bits of this byte */
3615	scsi_cmd->agid = agid << 6;
3616
3617	cam_fill_csio(csio,
3618		      retries,
3619		      cbfcnp,
3620		      /*flags*/ CAM_DIR_IN,
3621		      tag_action,
3622		      /*data_ptr*/ data_ptr,
3623		      /*dxfer_len*/ dxfer_len,
3624		      sense_len,
3625		      sizeof(*scsi_cmd),
3626		      timeout);
3627}
3628