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