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