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