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