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