scsi_cd.c revision 186882
1171095Ssam/*-
2171095Ssam * Copyright (c) 1997 Justin T. Gibbs.
3171095Ssam * Copyright (c) 1997, 1998, 1999, 2000, 2001, 2002, 2003 Kenneth D. Merry.
4171095Ssam * All rights reserved.
5171095Ssam *
6171095Ssam * Redistribution and use in source and binary forms, with or without
7171095Ssam * modification, are permitted provided that the following conditions
8171095Ssam * are met:
9171095Ssam * 1. Redistributions of source code must retain the above copyright
10171095Ssam *    notice, this list of conditions, and the following disclaimer,
11171095Ssam *    without modification, immediately at the beginning of the file.
12171095Ssam * 2. The name of the author may not be used to endorse or promote products
13171095Ssam *    derived from this software without specific prior written permission.
14171095Ssam *
15171095Ssam * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16171095Ssam * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17171095Ssam * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18171095Ssam * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
19171095Ssam * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20171095Ssam * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21171095Ssam * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22171095Ssam * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23171095Ssam * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24171095Ssam * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25171095Ssam * SUCH DAMAGE.
26171095Ssam */
27171095Ssam
28171095Ssam/*-
29171095Ssam * Portions of this driver taken from the original FreeBSD cd driver.
30171095Ssam * Written by Julian Elischer (julian@tfs.com)
31171095Ssam * for TRW Financial Systems for use under the MACH(2.5) operating system.
32171095Ssam *
33171095Ssam * TRW Financial Systems, in accordance with their agreement with Carnegie
34171095Ssam * Mellon University, makes this software available to CMU to distribute
35171095Ssam * or use in any manner that they see fit as long as this message is kept with
36173139Srwatson * the software. For this reason TFS also grants any other persons or
37171095Ssam * organisations permission to use or modify this software.
38171095Ssam *
39173139Srwatson * TFS supplies this software to be publicly redistributed
40171095Ssam * on the understanding that TFS is not responsible for the correct
41173139Srwatson * functioning of this software in any circumstances.
42173139Srwatson *
43171095Ssam * Ported to run under 386BSD by Julian Elischer (julian@tfs.com) Sept 1992
44173139Srwatson *
45173139Srwatson *      from: cd.c,v 1.83 1997/05/04 15:24:22 joerg Exp $
46171095Ssam */
47171095Ssam
48173139Srwatson#include <sys/cdefs.h>
49171095Ssam__FBSDID("$FreeBSD: head/sys/cam/scsi/scsi_cd.c 186882 2009-01-08 00:45:47Z imp $");
50171095Ssam
51173139Srwatson#include "opt_cd.h"
52171095Ssam
53171095Ssam#include <sys/param.h>
54173139Srwatson#include <sys/systm.h>
55171095Ssam#include <sys/kernel.h>
56173139Srwatson#include <sys/bio.h>
57173139Srwatson#include <sys/conf.h>
58173139Srwatson#include <sys/disk.h>
59171095Ssam#include <sys/malloc.h>
60171095Ssam#include <sys/cdio.h>
61173139Srwatson#include <sys/cdrio.h>
62171095Ssam#include <sys/dvdio.h>
63171095Ssam#include <sys/devicestat.h>
64173139Srwatson#include <sys/sysctl.h>
65173139Srwatson#include <sys/taskqueue.h>
66171095Ssam#include <geom/geom_disk.h>
67173139Srwatson
68173139Srwatson#include <cam/cam.h>
69171095Ssam#include <cam/cam_ccb.h>
70171095Ssam#include <cam/cam_periph.h>
71173139Srwatson#include <cam/cam_xpt_periph.h>
72171095Ssam#include <cam/cam_queue.h>
73171095Ssam#include <cam/cam_sim.h>
74173139Srwatson
75171095Ssam#include <cam/scsi/scsi_message.h>
76171095Ssam#include <cam/scsi/scsi_da.h>
77171095Ssam#include <cam/scsi/scsi_cd.h>
78171095Ssam
79171095Ssam#define LEADOUT         0xaa            /* leadout toc entry */
80173139Srwatson
81171095Ssamstruct cd_params {
82171095Ssam	u_int32_t blksize;
83173139Srwatson	u_long    disksize;
84171095Ssam};
85171095Ssam
86171095Ssamtypedef enum {
87171095Ssam	CD_Q_NONE		= 0x00,
88	CD_Q_NO_TOUCH		= 0x01,
89	CD_Q_BCD_TRACKS		= 0x02,
90	CD_Q_NO_CHANGER		= 0x04,
91	CD_Q_CHANGER		= 0x08,
92	CD_Q_10_BYTE_ONLY	= 0x10
93} cd_quirks;
94
95typedef enum {
96	CD_FLAG_INVALID		= 0x0001,
97	CD_FLAG_NEW_DISC	= 0x0002,
98	CD_FLAG_DISC_LOCKED	= 0x0004,
99	CD_FLAG_DISC_REMOVABLE	= 0x0008,
100	CD_FLAG_TAGGED_QUEUING	= 0x0010,
101	CD_FLAG_CHANGER		= 0x0040,
102	CD_FLAG_ACTIVE		= 0x0080,
103	CD_FLAG_SCHED_ON_COMP	= 0x0100,
104	CD_FLAG_RETRY_UA	= 0x0200,
105	CD_FLAG_VALID_MEDIA	= 0x0400,
106	CD_FLAG_VALID_TOC	= 0x0800,
107	CD_FLAG_SCTX_INIT	= 0x1000,
108	CD_FLAG_OPEN		= 0x2000
109} cd_flags;
110
111typedef enum {
112	CD_CCB_PROBE		= 0x01,
113	CD_CCB_BUFFER_IO	= 0x02,
114	CD_CCB_WAITING		= 0x03,
115	CD_CCB_TYPE_MASK	= 0x0F,
116	CD_CCB_RETRY_UA		= 0x10
117} cd_ccb_state;
118
119typedef enum {
120	CHANGER_TIMEOUT_SCHED		= 0x01,
121	CHANGER_SHORT_TMOUT_SCHED	= 0x02,
122	CHANGER_MANUAL_CALL		= 0x04,
123	CHANGER_NEED_TIMEOUT		= 0x08
124} cd_changer_flags;
125
126#define ccb_state ppriv_field0
127#define ccb_bp ppriv_ptr1
128
129struct cd_tocdata {
130	struct ioc_toc_header header;
131	struct cd_toc_entry entries[100];
132};
133
134struct cd_toc_single {
135	struct ioc_toc_header header;
136	struct cd_toc_entry entry;
137};
138
139typedef enum {
140	CD_STATE_PROBE,
141	CD_STATE_NORMAL
142} cd_state;
143
144struct cd_softc {
145	cam_pinfo		pinfo;
146	cd_state		state;
147	volatile cd_flags	flags;
148	struct bio_queue_head	bio_queue;
149	LIST_HEAD(, ccb_hdr)	pending_ccbs;
150	struct cd_params	params;
151	union ccb		saved_ccb;
152	cd_quirks		quirks;
153	STAILQ_ENTRY(cd_softc)	changer_links;
154	struct cdchanger	*changer;
155	int			bufs_left;
156	struct cam_periph	*periph;
157	int			minimum_command_size;
158	int			outstanding_cmds;
159	struct task		sysctl_task;
160	struct sysctl_ctx_list	sysctl_ctx;
161	struct sysctl_oid	*sysctl_tree;
162	STAILQ_HEAD(, cd_mode_params)	mode_queue;
163	struct cd_tocdata	toc;
164	struct disk		*disk;
165};
166
167struct cd_page_sizes {
168	int page;
169	int page_size;
170};
171
172static struct cd_page_sizes cd_page_size_table[] =
173{
174	{ AUDIO_PAGE, sizeof(struct cd_audio_page)}
175};
176
177struct cd_quirk_entry {
178	struct scsi_inquiry_pattern inq_pat;
179	cd_quirks quirks;
180};
181
182/*
183 * The changer quirk entries aren't strictly necessary.  Basically, what
184 * they do is tell cdregister() up front that a device is a changer.
185 * Otherwise, it will figure that fact out once it sees a LUN on the device
186 * that is greater than 0.  If it is known up front that a device is a changer,
187 * all I/O to the device will go through the changer scheduling routines, as
188 * opposed to the "normal" CD code.
189 *
190 * NOTE ON 10_BYTE_ONLY quirks:  Any 10_BYTE_ONLY quirks MUST be because
191 * your device hangs when it gets a 10 byte command.  Adding a quirk just
192 * to get rid of the informative diagnostic message is not acceptable.  All
193 * 10_BYTE_ONLY quirks must be documented in full in a PR (which should be
194 * referenced in a comment along with the quirk) , and must be approved by
195 * ken@FreeBSD.org.  Any quirks added that don't adhere to this policy may
196 * be removed until the submitter can explain why they are needed.
197 * 10_BYTE_ONLY quirks will be removed (as they will no longer be necessary)
198 * when the CAM_NEW_TRAN_CODE work is done.
199 */
200static struct cd_quirk_entry cd_quirk_table[] =
201{
202	{
203		{ T_CDROM, SIP_MEDIA_REMOVABLE, "NRC", "MBR-7", "*"},
204		 /*quirks*/ CD_Q_CHANGER
205	},
206	{
207		{ T_CDROM, SIP_MEDIA_REMOVABLE, "PIONEER", "CD-ROM DRM*",
208		  "*"}, /* quirks */ CD_Q_CHANGER
209	},
210	{
211		{ T_CDROM, SIP_MEDIA_REMOVABLE, "NAKAMICH", "MJ-*", "*"},
212		 /* quirks */ CD_Q_CHANGER
213	},
214	{
215		{ T_CDROM, SIP_MEDIA_REMOVABLE, "CHINON", "CD-ROM CDS-535","*"},
216		/* quirks */ CD_Q_BCD_TRACKS
217	}
218};
219
220static	disk_open_t	cdopen;
221static	disk_close_t	cdclose;
222static	disk_ioctl_t	cdioctl;
223static	disk_strategy_t	cdstrategy;
224
225static	periph_init_t	cdinit;
226static	periph_ctor_t	cdregister;
227static	periph_dtor_t	cdcleanup;
228static	periph_start_t	cdstart;
229static	periph_oninv_t	cdoninvalidate;
230static	void		cdasync(void *callback_arg, u_int32_t code,
231				struct cam_path *path, void *arg);
232static	int		cdcmdsizesysctl(SYSCTL_HANDLER_ARGS);
233static	void		cdshorttimeout(void *arg);
234static	void		cdschedule(struct cam_periph *periph, int priority);
235static	void		cdrunchangerqueue(void *arg);
236static	void		cdchangerschedule(struct cd_softc *softc);
237static	int		cdrunccb(union ccb *ccb,
238				 int (*error_routine)(union ccb *ccb,
239						      u_int32_t cam_flags,
240						      u_int32_t sense_flags),
241				 u_int32_t cam_flags, u_int32_t sense_flags);
242static	union ccb 	*cdgetccb(struct cam_periph *periph,
243				  u_int32_t priority);
244static	void		cddone(struct cam_periph *periph,
245			       union ccb *start_ccb);
246static	union cd_pages	*cdgetpage(struct cd_mode_params *mode_params);
247static	int		cdgetpagesize(int page_num);
248static	void		cdprevent(struct cam_periph *periph, int action);
249static	int		cdcheckmedia(struct cam_periph *periph);
250static	int		cdsize(struct cam_periph *periph, u_int32_t *size);
251static	int		cd6byteworkaround(union ccb *ccb);
252static	int		cderror(union ccb *ccb, u_int32_t cam_flags,
253				u_int32_t sense_flags);
254static	int		cdreadtoc(struct cam_periph *periph, u_int32_t mode,
255				  u_int32_t start, u_int8_t *data,
256				  u_int32_t len, u_int32_t sense_flags);
257static	int		cdgetmode(struct cam_periph *periph,
258				  struct cd_mode_params *data, u_int32_t page);
259static	int		cdsetmode(struct cam_periph *periph,
260				  struct cd_mode_params *data);
261static	int		cdplay(struct cam_periph *periph, u_int32_t blk,
262			       u_int32_t len);
263static	int		cdreadsubchannel(struct cam_periph *periph,
264					 u_int32_t mode, u_int32_t format,
265					 int track,
266					 struct cd_sub_channel_info *data,
267					 u_int32_t len);
268static	int		cdplaymsf(struct cam_periph *periph, u_int32_t startm,
269				  u_int32_t starts, u_int32_t startf,
270				  u_int32_t endm, u_int32_t ends,
271				  u_int32_t endf);
272static	int		cdplaytracks(struct cam_periph *periph,
273				     u_int32_t strack, u_int32_t sindex,
274				     u_int32_t etrack, u_int32_t eindex);
275static	int		cdpause(struct cam_periph *periph, u_int32_t go);
276static	int		cdstopunit(struct cam_periph *periph, u_int32_t eject);
277static	int		cdstartunit(struct cam_periph *periph, int load);
278static	int		cdsetspeed(struct cam_periph *periph,
279				   u_int32_t rdspeed, u_int32_t wrspeed);
280static	int		cdreportkey(struct cam_periph *periph,
281				    struct dvd_authinfo *authinfo);
282static	int		cdsendkey(struct cam_periph *periph,
283				  struct dvd_authinfo *authinfo);
284static	int		cdreaddvdstructure(struct cam_periph *periph,
285					   struct dvd_struct *dvdstruct);
286
287static struct periph_driver cddriver =
288{
289	cdinit, "cd",
290	TAILQ_HEAD_INITIALIZER(cddriver.units), /* generation */ 0
291};
292
293PERIPHDRIVER_DECLARE(cd, cddriver);
294
295#ifndef	CD_DEFAULT_RETRY
296#define	CD_DEFAULT_RETRY	4
297#endif
298#ifndef CHANGER_MIN_BUSY_SECONDS
299#define CHANGER_MIN_BUSY_SECONDS	5
300#endif
301#ifndef CHANGER_MAX_BUSY_SECONDS
302#define CHANGER_MAX_BUSY_SECONDS	15
303#endif
304
305static int cd_retry_count = CD_DEFAULT_RETRY;
306static int changer_min_busy_seconds = CHANGER_MIN_BUSY_SECONDS;
307static int changer_max_busy_seconds = CHANGER_MAX_BUSY_SECONDS;
308
309SYSCTL_NODE(_kern_cam, OID_AUTO, cd, CTLFLAG_RD, 0, "CAM CDROM driver");
310SYSCTL_NODE(_kern_cam_cd, OID_AUTO, changer, CTLFLAG_RD, 0, "CD Changer");
311SYSCTL_INT(_kern_cam_cd, OID_AUTO, retry_count, CTLFLAG_RW,
312           &cd_retry_count, 0, "Normal I/O retry count");
313TUNABLE_INT("kern.cam.cd.retry_count", &cd_retry_count);
314SYSCTL_INT(_kern_cam_cd_changer, OID_AUTO, min_busy_seconds, CTLFLAG_RW,
315	   &changer_min_busy_seconds, 0, "Minimum changer scheduling quantum");
316TUNABLE_INT("kern.cam.cd.changer.min_busy_seconds", &changer_min_busy_seconds);
317SYSCTL_INT(_kern_cam_cd_changer, OID_AUTO, max_busy_seconds, CTLFLAG_RW,
318	   &changer_max_busy_seconds, 0, "Maximum changer scheduling quantum");
319TUNABLE_INT("kern.cam.cd.changer.max_busy_seconds", &changer_max_busy_seconds);
320
321struct cdchanger {
322	path_id_t			 path_id;
323	target_id_t			 target_id;
324	int				 num_devices;
325	struct camq			 devq;
326	struct timeval			 start_time;
327	struct cd_softc			 *cur_device;
328	struct callout			 short_handle;
329	struct callout			 long_handle;
330	volatile cd_changer_flags	 flags;
331	STAILQ_ENTRY(cdchanger)		 changer_links;
332	STAILQ_HEAD(chdevlist, cd_softc) chluns;
333};
334
335static struct mtx changerq_mtx;
336static STAILQ_HEAD(changerlist, cdchanger) changerq;
337static int num_changers;
338
339MALLOC_DEFINE(M_SCSICD, "scsi_cd", "scsi_cd buffers");
340
341static void
342cdinit(void)
343{
344	cam_status status;
345
346	mtx_init(&changerq_mtx, "cdchangerq", "SCSI CD Changer List", MTX_DEF);
347	STAILQ_INIT(&changerq);
348
349	/*
350	 * Install a global async callback.  This callback will
351	 * receive async callbacks like "new device found".
352	 */
353	status = xpt_register_async(AC_FOUND_DEVICE, cdasync, NULL, NULL);
354
355	if (status != CAM_REQ_CMP) {
356		printf("cd: Failed to attach master async callback "
357		       "due to status 0x%x!\n", status);
358	}
359}
360
361static void
362cdoninvalidate(struct cam_periph *periph)
363{
364	struct cd_softc *softc;
365
366	softc = (struct cd_softc *)periph->softc;
367
368	/*
369	 * De-register any async callbacks.
370	 */
371	xpt_register_async(0, cdasync, periph, periph->path);
372
373	softc->flags |= CD_FLAG_INVALID;
374
375	/*
376	 * Return all queued I/O with ENXIO.
377	 * XXX Handle any transactions queued to the card
378	 *     with XPT_ABORT_CCB.
379	 */
380	bioq_flush(&softc->bio_queue, NULL, ENXIO);
381
382	/*
383	 * If this device is part of a changer, and it was scheduled
384	 * to run, remove it from the run queue since we just nuked
385	 * all of its scheduled I/O.
386	 */
387	if ((softc->flags & CD_FLAG_CHANGER)
388	 && (softc->pinfo.index != CAM_UNQUEUED_INDEX))
389		camq_remove(&softc->changer->devq, softc->pinfo.index);
390
391	disk_gone(softc->disk);
392	xpt_print(periph->path, "lost device\n");
393}
394
395static void
396cdcleanup(struct cam_periph *periph)
397{
398	struct cd_softc *softc;
399
400	softc = (struct cd_softc *)periph->softc;
401
402	xpt_print(periph->path, "removing device entry\n");
403
404	if ((softc->flags & CD_FLAG_SCTX_INIT) != 0
405	    && sysctl_ctx_free(&softc->sysctl_ctx) != 0) {
406		xpt_print(periph->path, "can't remove sysctl context\n");
407	}
408
409	/*
410	 * In the queued, non-active case, the device in question
411	 * has already been removed from the changer run queue.  Since this
412	 * device is active, we need to de-activate it, and schedule
413	 * another device to run.  (if there is another one to run)
414	 */
415	if ((softc->flags & CD_FLAG_CHANGER)
416	 && (softc->flags & CD_FLAG_ACTIVE)) {
417
418		/*
419		 * The purpose of the short timeout is soley to determine
420		 * whether the current device has finished or not.  Well,
421		 * since we're removing the active device, we know that it
422		 * is finished.  So, get rid of the short timeout.
423		 * Otherwise, if we're in the time period before the short
424		 * timeout fires, and there are no other devices in the
425		 * queue to run, there won't be any other device put in the
426		 * active slot.  i.e., when we call cdrunchangerqueue()
427		 * below, it won't do anything.  Then, when the short
428		 * timeout fires, it'll look at the "current device", which
429		 * we are free below, and possibly panic the kernel on a
430		 * bogus pointer reference.
431		 *
432		 * The long timeout doesn't really matter, since we
433		 * decrement the qfrozen_cnt to indicate that there is
434		 * nothing in the active slot now.  Therefore, there won't
435		 * be any bogus pointer references there.
436		 */
437		if (softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
438			callout_stop(&softc->changer->short_handle);
439			softc->changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
440		}
441		softc->changer->devq.qfrozen_cnt--;
442		softc->changer->flags |= CHANGER_MANUAL_CALL;
443		cdrunchangerqueue(softc->changer);
444	}
445
446	/*
447	 * If we're removing the last device on the changer, go ahead and
448	 * remove the changer device structure.
449	 */
450	if ((softc->flags & CD_FLAG_CHANGER)
451	 && (--softc->changer->num_devices == 0)) {
452
453		/*
454		 * Theoretically, there shouldn't be any timeouts left, but
455		 * I'm not completely sure that that will be the case.  So,
456		 * it won't hurt to check and see if there are any left.
457		 */
458		if (softc->changer->flags & CHANGER_TIMEOUT_SCHED) {
459			callout_stop(&softc->changer->long_handle);
460			softc->changer->flags &= ~CHANGER_TIMEOUT_SCHED;
461		}
462
463		if (softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
464			callout_stop(&softc->changer->short_handle);
465			softc->changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
466		}
467
468		mtx_lock(&changerq_mtx);
469		STAILQ_REMOVE(&changerq, softc->changer, cdchanger,
470			      changer_links);
471		num_changers--;
472		mtx_unlock(&changerq_mtx);
473		xpt_print(periph->path, "removing changer entry\n");
474		free(softc->changer, M_DEVBUF);
475	}
476	cam_periph_unlock(periph);
477	disk_destroy(softc->disk);
478	cam_periph_lock(periph);
479	free(softc, M_DEVBUF);
480}
481
482static void
483cdasync(void *callback_arg, u_int32_t code,
484	struct cam_path *path, void *arg)
485{
486	struct cam_periph *periph;
487
488	periph = (struct cam_periph *)callback_arg;
489	switch (code) {
490	case AC_FOUND_DEVICE:
491	{
492		struct ccb_getdev *cgd;
493		cam_status status;
494
495		cgd = (struct ccb_getdev *)arg;
496		if (cgd == NULL)
497			break;
498
499		if (SID_TYPE(&cgd->inq_data) != T_CDROM
500		    && SID_TYPE(&cgd->inq_data) != T_WORM)
501			break;
502
503		/*
504		 * Allocate a peripheral instance for
505		 * this device and start the probe
506		 * process.
507		 */
508		status = cam_periph_alloc(cdregister, cdoninvalidate,
509					  cdcleanup, cdstart,
510					  "cd", CAM_PERIPH_BIO,
511					  cgd->ccb_h.path, cdasync,
512					  AC_FOUND_DEVICE, cgd);
513
514		if (status != CAM_REQ_CMP
515		 && status != CAM_REQ_INPROG)
516			printf("cdasync: Unable to attach new device "
517			       "due to status 0x%x\n", status);
518
519		break;
520	}
521	case AC_SENT_BDR:
522	case AC_BUS_RESET:
523	{
524		struct cd_softc *softc;
525		struct ccb_hdr *ccbh;
526
527		softc = (struct cd_softc *)periph->softc;
528		/*
529		 * Don't fail on the expected unit attention
530		 * that will occur.
531		 */
532		softc->flags |= CD_FLAG_RETRY_UA;
533		LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
534			ccbh->ccb_state |= CD_CCB_RETRY_UA;
535		/* FALLTHROUGH */
536	}
537	default:
538		cam_periph_async(periph, code, path, arg);
539		break;
540	}
541}
542
543static void
544cdsysctlinit(void *context, int pending)
545{
546	struct cam_periph *periph;
547	struct cd_softc *softc;
548	char tmpstr[80], tmpstr2[80];
549
550	periph = (struct cam_periph *)context;
551	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
552		return;
553
554	softc = (struct cd_softc *)periph->softc;
555	snprintf(tmpstr, sizeof(tmpstr), "CAM CD unit %d", periph->unit_number);
556	snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
557
558	mtx_lock(&Giant);
559
560	sysctl_ctx_init(&softc->sysctl_ctx);
561	softc->flags |= CD_FLAG_SCTX_INIT;
562	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
563		SYSCTL_STATIC_CHILDREN(_kern_cam_cd), OID_AUTO,
564		tmpstr2, CTLFLAG_RD, 0, tmpstr);
565
566	if (softc->sysctl_tree == NULL) {
567		printf("cdsysctlinit: unable to allocate sysctl tree\n");
568		mtx_unlock(&Giant);
569		cam_periph_release(periph);
570		return;
571	}
572
573	/*
574	 * Now register the sysctl handler, so the user can the value on
575	 * the fly.
576	 */
577	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
578		OID_AUTO, "minimum_cmd_size", CTLTYPE_INT | CTLFLAG_RW,
579		&softc->minimum_command_size, 0, cdcmdsizesysctl, "I",
580		"Minimum CDB size");
581
582	mtx_unlock(&Giant);
583	cam_periph_release(periph);
584}
585
586/*
587 * We have a handler function for this so we can check the values when the
588 * user sets them, instead of every time we look at them.
589 */
590static int
591cdcmdsizesysctl(SYSCTL_HANDLER_ARGS)
592{
593	int error, value;
594
595	value = *(int *)arg1;
596
597	error = sysctl_handle_int(oidp, &value, 0, req);
598
599	if ((error != 0)
600	 || (req->newptr == NULL))
601		return (error);
602
603	/*
604	 * The only real values we can have here are 6 or 10.  I don't
605	 * really forsee having 12 be an option at any time in the future.
606	 * So if the user sets something less than or equal to 6, we'll set
607	 * it to 6.  If he sets something greater than 6, we'll set it to 10.
608	 *
609	 * I suppose we could just return an error here for the wrong values,
610	 * but I don't think it's necessary to do so, as long as we can
611	 * determine the user's intent without too much trouble.
612	 */
613	if (value < 6)
614		value = 6;
615	else if (value > 6)
616		value = 10;
617
618	*(int *)arg1 = value;
619
620	return (0);
621}
622
623static cam_status
624cdregister(struct cam_periph *periph, void *arg)
625{
626	struct cd_softc *softc;
627	struct ccb_pathinq cpi;
628	struct ccb_getdev *cgd;
629	char tmpstr[80];
630	caddr_t match;
631
632	cgd = (struct ccb_getdev *)arg;
633	if (periph == NULL) {
634		printf("cdregister: periph was NULL!!\n");
635		return(CAM_REQ_CMP_ERR);
636	}
637	if (cgd == NULL) {
638		printf("cdregister: no getdev CCB, can't register device\n");
639		return(CAM_REQ_CMP_ERR);
640	}
641
642	softc = (struct cd_softc *)malloc(sizeof(*softc),M_DEVBUF,M_NOWAIT);
643
644	if (softc == NULL) {
645		printf("cdregister: Unable to probe new device. "
646		       "Unable to allocate softc\n");
647		return(CAM_REQ_CMP_ERR);
648	}
649
650	bzero(softc, sizeof(*softc));
651	LIST_INIT(&softc->pending_ccbs);
652	STAILQ_INIT(&softc->mode_queue);
653	softc->state = CD_STATE_PROBE;
654	bioq_init(&softc->bio_queue);
655	if (SID_IS_REMOVABLE(&cgd->inq_data))
656		softc->flags |= CD_FLAG_DISC_REMOVABLE;
657	if ((cgd->inq_data.flags & SID_CmdQue) != 0)
658		softc->flags |= CD_FLAG_TAGGED_QUEUING;
659
660	periph->softc = softc;
661	softc->periph = periph;
662
663	/*
664	 * See if this device has any quirks.
665	 */
666	match = cam_quirkmatch((caddr_t)&cgd->inq_data,
667			       (caddr_t)cd_quirk_table,
668			       sizeof(cd_quirk_table)/sizeof(*cd_quirk_table),
669			       sizeof(*cd_quirk_table), scsi_inquiry_match);
670
671	if (match != NULL)
672		softc->quirks = ((struct cd_quirk_entry *)match)->quirks;
673	else
674		softc->quirks = CD_Q_NONE;
675
676	/* Check if the SIM does not want 6 byte commands */
677	xpt_setup_ccb(&cpi.ccb_h, periph->path, /*priority*/1);
678	cpi.ccb_h.func_code = XPT_PATH_INQ;
679	xpt_action((union ccb *)&cpi);
680	if (cpi.ccb_h.status == CAM_REQ_CMP && (cpi.hba_misc & PIM_NO_6_BYTE))
681		softc->quirks |= CD_Q_10_BYTE_ONLY;
682
683	TASK_INIT(&softc->sysctl_task, 0, cdsysctlinit, periph);
684
685	/* The default is 6 byte commands, unless quirked otherwise */
686	if (softc->quirks & CD_Q_10_BYTE_ONLY)
687		softc->minimum_command_size = 10;
688	else
689		softc->minimum_command_size = 6;
690
691	/*
692	 * Load the user's default, if any.
693	 */
694	snprintf(tmpstr, sizeof(tmpstr), "kern.cam.cd.%d.minimum_cmd_size",
695		 periph->unit_number);
696	TUNABLE_INT_FETCH(tmpstr, &softc->minimum_command_size);
697
698	/* 6 and 10 are the only permissible values here. */
699	if (softc->minimum_command_size < 6)
700		softc->minimum_command_size = 6;
701	else if (softc->minimum_command_size > 6)
702		softc->minimum_command_size = 10;
703
704	/*
705	 * We need to register the statistics structure for this device,
706	 * but we don't have the blocksize yet for it.  So, we register
707	 * the structure and indicate that we don't have the blocksize
708	 * yet.  Unlike other SCSI peripheral drivers, we explicitly set
709	 * the device type here to be CDROM, rather than just ORing in
710	 * the device type.  This is because this driver can attach to either
711	 * CDROM or WORM devices, and we want this peripheral driver to
712	 * show up in the devstat list as a CD peripheral driver, not a
713	 * WORM peripheral driver.  WORM drives will also have the WORM
714	 * driver attached to them.
715	 */
716	cam_periph_unlock(periph);
717	softc->disk = disk_alloc();
718	softc->disk->d_devstat = devstat_new_entry("cd",
719			  periph->unit_number, 0,
720	  		  DEVSTAT_BS_UNAVAILABLE,
721			  DEVSTAT_TYPE_CDROM | DEVSTAT_TYPE_IF_SCSI,
722			  DEVSTAT_PRIORITY_CD);
723	softc->disk->d_open = cdopen;
724	softc->disk->d_close = cdclose;
725	softc->disk->d_strategy = cdstrategy;
726	softc->disk->d_ioctl = cdioctl;
727	softc->disk->d_name = "cd";
728	softc->disk->d_unit = periph->unit_number;
729	softc->disk->d_drv1 = periph;
730	softc->disk->d_flags = 0;
731	disk_create(softc->disk, DISK_VERSION);
732	cam_periph_lock(periph);
733
734	/*
735	 * Add an async callback so that we get
736	 * notified if this device goes away.
737	 */
738	xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE,
739			   cdasync, periph, periph->path);
740
741	/*
742	 * If the target lun is greater than 0, we most likely have a CD
743	 * changer device.  Check the quirk entries as well, though, just
744	 * in case someone has a CD tower with one lun per drive or
745	 * something like that.  Also, if we know up front that a
746	 * particular device is a changer, we can mark it as such starting
747	 * with lun 0, instead of lun 1.  It shouldn't be necessary to have
748	 * a quirk entry to define something as a changer, however.
749	 */
750	if (((cgd->ccb_h.target_lun > 0)
751	  && ((softc->quirks & CD_Q_NO_CHANGER) == 0))
752	 || ((softc->quirks & CD_Q_CHANGER) != 0)) {
753		struct cdchanger *nchanger;
754		struct cam_periph *nperiph;
755		struct cam_path *path;
756		cam_status status;
757		int found;
758
759		/* Set the changer flag in the current device's softc */
760		softc->flags |= CD_FLAG_CHANGER;
761
762		/*
763		 * Now, look around for an existing changer device with the
764		 * same path and target ID as the current device.
765		 */
766		mtx_lock(&changerq_mtx);
767		for (found = 0,
768		     nchanger = (struct cdchanger *)STAILQ_FIRST(&changerq);
769		     nchanger != NULL;
770		     nchanger = STAILQ_NEXT(nchanger, changer_links)){
771			if ((nchanger->path_id == cgd->ccb_h.path_id)
772			 && (nchanger->target_id == cgd->ccb_h.target_id)) {
773				found = 1;
774				break;
775			}
776		}
777		mtx_unlock(&changerq_mtx);
778
779		/*
780		 * If we found a matching entry, just add this device to
781		 * the list of devices on this changer.
782		 */
783		if (found == 1) {
784			struct chdevlist *chlunhead;
785
786			chlunhead = &nchanger->chluns;
787
788			/*
789			 * XXX KDM look at consolidating this code with the
790			 * code below in a separate function.
791			 */
792
793			/*
794			 * Create a path with lun id 0, and see if we can
795			 * find a matching device
796			 */
797			status = xpt_create_path(&path, /*periph*/ periph,
798						 cgd->ccb_h.path_id,
799						 cgd->ccb_h.target_id, 0);
800
801			if ((status == CAM_REQ_CMP)
802			 && ((nperiph = cam_periph_find(path, "cd")) != NULL)){
803				struct cd_softc *nsoftc;
804
805				nsoftc = (struct cd_softc *)nperiph->softc;
806
807				if ((nsoftc->flags & CD_FLAG_CHANGER) == 0){
808					nsoftc->flags |= CD_FLAG_CHANGER;
809					nchanger->num_devices++;
810					if (camq_resize(&nchanger->devq,
811					   nchanger->num_devices)!=CAM_REQ_CMP){
812						printf("cdregister: "
813						       "camq_resize "
814						       "failed, changer "
815						       "support may "
816						       "be messed up\n");
817					}
818					nsoftc->changer = nchanger;
819					nsoftc->pinfo.index =CAM_UNQUEUED_INDEX;
820
821					STAILQ_INSERT_TAIL(&nchanger->chluns,
822							  nsoftc,changer_links);
823				}
824				xpt_free_path(path);
825			} else if (status == CAM_REQ_CMP)
826				xpt_free_path(path);
827			else {
828				printf("cdregister: unable to allocate path\n"
829				       "cdregister: changer support may be "
830				       "broken\n");
831			}
832
833			nchanger->num_devices++;
834
835			softc->changer = nchanger;
836			softc->pinfo.index = CAM_UNQUEUED_INDEX;
837
838			if (camq_resize(&nchanger->devq,
839			    nchanger->num_devices) != CAM_REQ_CMP) {
840				printf("cdregister: camq_resize "
841				       "failed, changer support may "
842				       "be messed up\n");
843			}
844
845			STAILQ_INSERT_TAIL(chlunhead, softc, changer_links);
846		}
847		/*
848		 * In this case, we don't already have an entry for this
849		 * particular changer, so we need to create one, add it to
850		 * the queue, and queue this device on the list for this
851		 * changer.  Before we queue this device, however, we need
852		 * to search for lun id 0 on this target, and add it to the
853		 * queue first, if it exists.  (and if it hasn't already
854		 * been marked as part of the changer.)
855		 */
856		else {
857			nchanger = malloc(sizeof(struct cdchanger),
858				M_DEVBUF, M_NOWAIT);
859
860			if (nchanger == NULL) {
861				softc->flags &= ~CD_FLAG_CHANGER;
862				printf("cdregister: unable to malloc "
863				       "changer structure\ncdregister: "
864				       "changer support disabled\n");
865
866				/*
867				 * Yes, gotos can be gross but in this case
868				 * I think it's justified..
869				 */
870				goto cdregisterexit;
871			}
872
873			/* zero the structure */
874			bzero(nchanger, sizeof(struct cdchanger));
875
876			if (camq_init(&nchanger->devq, 1) != 0) {
877				softc->flags &= ~CD_FLAG_CHANGER;
878				printf("cdregister: changer support "
879				       "disabled\n");
880				goto cdregisterexit;
881			}
882
883			nchanger->path_id = cgd->ccb_h.path_id;
884			nchanger->target_id = cgd->ccb_h.target_id;
885
886			/* this is superfluous, but it makes things clearer */
887			nchanger->num_devices = 0;
888
889			STAILQ_INIT(&nchanger->chluns);
890
891			callout_init_mtx(&nchanger->long_handle,
892			    periph->sim->mtx, 0);
893			callout_init_mtx(&nchanger->short_handle,
894			    periph->sim->mtx, 0);
895
896			mtx_lock(&changerq_mtx);
897			num_changers++;
898			STAILQ_INSERT_TAIL(&changerq, nchanger,
899					   changer_links);
900			mtx_unlock(&changerq_mtx);
901
902			/*
903			 * Create a path with lun id 0, and see if we can
904			 * find a matching device
905			 */
906			status = xpt_create_path(&path, /*periph*/ periph,
907						 cgd->ccb_h.path_id,
908						 cgd->ccb_h.target_id, 0);
909
910			/*
911			 * If we were able to allocate the path, and if we
912			 * find a matching device and it isn't already
913			 * marked as part of a changer, then we add it to
914			 * the current changer.
915			 */
916			if ((status == CAM_REQ_CMP)
917			 && ((nperiph = cam_periph_find(path, "cd")) != NULL)
918			 && ((((struct cd_softc *)periph->softc)->flags &
919			       CD_FLAG_CHANGER) == 0)) {
920				struct cd_softc *nsoftc;
921
922				nsoftc = (struct cd_softc *)nperiph->softc;
923
924				nsoftc->flags |= CD_FLAG_CHANGER;
925				nchanger->num_devices++;
926				if (camq_resize(&nchanger->devq,
927				    nchanger->num_devices) != CAM_REQ_CMP) {
928					printf("cdregister: camq_resize "
929					       "failed, changer support may "
930					       "be messed up\n");
931				}
932				nsoftc->changer = nchanger;
933				nsoftc->pinfo.index = CAM_UNQUEUED_INDEX;
934
935				STAILQ_INSERT_TAIL(&nchanger->chluns,
936						   nsoftc, changer_links);
937				xpt_free_path(path);
938			} else if (status == CAM_REQ_CMP)
939				xpt_free_path(path);
940			else {
941				printf("cdregister: unable to allocate path\n"
942				       "cdregister: changer support may be "
943				       "broken\n");
944			}
945
946			softc->changer = nchanger;
947			softc->pinfo.index = CAM_UNQUEUED_INDEX;
948			nchanger->num_devices++;
949			if (camq_resize(&nchanger->devq,
950			    nchanger->num_devices) != CAM_REQ_CMP) {
951				printf("cdregister: camq_resize "
952				       "failed, changer support may "
953				       "be messed up\n");
954			}
955			STAILQ_INSERT_TAIL(&nchanger->chluns, softc,
956					   changer_links);
957		}
958	}
959
960cdregisterexit:
961
962	/*
963	 * Refcount and block open attempts until we are setup
964	 * Can't block
965	 */
966	(void)cam_periph_hold(periph, PRIBIO);
967
968	if ((softc->flags & CD_FLAG_CHANGER) == 0)
969		xpt_schedule(periph, /*priority*/5);
970	else
971		cdschedule(periph, /*priority*/ 5);
972
973	return(CAM_REQ_CMP);
974}
975
976static int
977cdopen(struct disk *dp)
978{
979	struct cam_periph *periph;
980	struct cd_softc *softc;
981	int error;
982
983	periph = (struct cam_periph *)dp->d_drv1;
984	if (periph == NULL)
985		return (ENXIO);
986
987	softc = (struct cd_softc *)periph->softc;
988
989	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
990		return(ENXIO);
991
992	cam_periph_lock(periph);
993
994	if (softc->flags & CD_FLAG_INVALID) {
995		cam_periph_unlock(periph);
996		cam_periph_release(periph);
997		return(ENXIO);
998	}
999
1000	if ((error = cam_periph_hold(periph, PRIBIO | PCATCH)) != 0) {
1001		cam_periph_unlock(periph);
1002		cam_periph_release(periph);
1003		return (error);
1004	}
1005
1006	/*
1007	 * Check for media, and set the appropriate flags.  We don't bail
1008	 * if we don't have media, but then we don't allow anything but the
1009	 * CDIOCEJECT/CDIOCCLOSE ioctls if there is no media.
1010	 */
1011	cdcheckmedia(periph);
1012
1013	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdopen\n"));
1014	cam_periph_unhold(periph);
1015
1016	/* Closes aren't symmetrical with opens, so fix up the refcounting. */
1017	if ((softc->flags & CD_FLAG_OPEN) == 0) {
1018		softc->flags |= CD_FLAG_OPEN;
1019		cam_periph_unlock(periph);
1020	} else {
1021		cam_periph_unlock(periph);
1022		cam_periph_release(periph);
1023	}
1024
1025	return (0);
1026}
1027
1028static int
1029cdclose(struct disk *dp)
1030{
1031	struct 	cam_periph *periph;
1032	struct	cd_softc *softc;
1033
1034	periph = (struct cam_periph *)dp->d_drv1;
1035	if (periph == NULL)
1036		return (ENXIO);
1037
1038	softc = (struct cd_softc *)periph->softc;
1039
1040	cam_periph_lock(periph);
1041	cam_periph_hold(periph, PRIBIO);
1042
1043	if ((softc->flags & CD_FLAG_DISC_REMOVABLE) != 0)
1044		cdprevent(periph, PR_ALLOW);
1045
1046	/*
1047	 * Since we're closing this CD, mark the blocksize as unavailable.
1048	 * It will be marked as available when the CD is opened again.
1049	 */
1050	softc->disk->d_devstat->flags |= DEVSTAT_BS_UNAVAILABLE;
1051
1052	/*
1053	 * We'll check the media and toc again at the next open().
1054	 */
1055	softc->flags &= ~(CD_FLAG_VALID_MEDIA|CD_FLAG_VALID_TOC|CD_FLAG_OPEN);
1056
1057	cam_periph_unhold(periph);
1058	cam_periph_unlock(periph);
1059	cam_periph_release(periph);
1060
1061	return (0);
1062}
1063
1064static void
1065cdshorttimeout(void *arg)
1066{
1067	struct cdchanger *changer;
1068
1069	changer = (struct cdchanger *)arg;
1070
1071	/* Always clear the short timeout flag, since that's what we're in */
1072	changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
1073
1074	/*
1075	 * Check to see if there is any more pending or outstanding I/O for
1076	 * this device.  If not, move it out of the active slot.
1077	 */
1078	if ((bioq_first(&changer->cur_device->bio_queue) == NULL)
1079	 && (changer->cur_device->outstanding_cmds == 0)) {
1080		changer->flags |= CHANGER_MANUAL_CALL;
1081		cdrunchangerqueue(changer);
1082	}
1083}
1084
1085/*
1086 * This is a wrapper for xpt_schedule.  It only applies to changers.
1087 */
1088static void
1089cdschedule(struct cam_periph *periph, int priority)
1090{
1091	struct cd_softc *softc;
1092
1093	softc = (struct cd_softc *)periph->softc;
1094
1095	/*
1096	 * If this device isn't currently queued, and if it isn't
1097	 * the active device, then we queue this device and run the
1098	 * changer queue if there is no timeout scheduled to do it.
1099	 * If this device is the active device, just schedule it
1100	 * to run again.  If this device is queued, there should be
1101	 * a timeout in place already that will make sure it runs.
1102	 */
1103	if ((softc->pinfo.index == CAM_UNQUEUED_INDEX)
1104	 && ((softc->flags & CD_FLAG_ACTIVE) == 0)) {
1105		/*
1106		 * We don't do anything with the priority here.
1107		 * This is strictly a fifo queue.
1108		 */
1109		softc->pinfo.priority = 1;
1110		softc->pinfo.generation = ++softc->changer->devq.generation;
1111		camq_insert(&softc->changer->devq, (cam_pinfo *)softc);
1112
1113		/*
1114		 * Since we just put a device in the changer queue,
1115		 * check and see if there is a timeout scheduled for
1116		 * this changer.  If so, let the timeout handle
1117		 * switching this device into the active slot.  If
1118		 * not, manually call the timeout routine to
1119		 * bootstrap things.
1120		 */
1121		if (((softc->changer->flags & CHANGER_TIMEOUT_SCHED)==0)
1122		 && ((softc->changer->flags & CHANGER_NEED_TIMEOUT)==0)
1123		 && ((softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED)==0)){
1124			softc->changer->flags |= CHANGER_MANUAL_CALL;
1125			cdrunchangerqueue(softc->changer);
1126		}
1127	} else if ((softc->flags & CD_FLAG_ACTIVE)
1128		&& ((softc->flags & CD_FLAG_SCHED_ON_COMP) == 0))
1129		xpt_schedule(periph, priority);
1130}
1131
1132static void
1133cdrunchangerqueue(void *arg)
1134{
1135	struct cd_softc *softc;
1136	struct cdchanger *changer;
1137	int called_from_timeout;
1138
1139	changer = (struct cdchanger *)arg;
1140
1141	/*
1142	 * If we have NOT been called from cdstrategy() or cddone(), and
1143	 * instead from a timeout routine, go ahead and clear the
1144	 * timeout flag.
1145	 */
1146	if ((changer->flags & CHANGER_MANUAL_CALL) == 0) {
1147		changer->flags &= ~CHANGER_TIMEOUT_SCHED;
1148		called_from_timeout = 1;
1149	} else
1150		called_from_timeout = 0;
1151
1152	/* Always clear the manual call flag */
1153	changer->flags &= ~CHANGER_MANUAL_CALL;
1154
1155	/* nothing to do if the queue is empty */
1156	if (changer->devq.entries <= 0) {
1157		return;
1158	}
1159
1160	/*
1161	 * If the changer queue is frozen, that means we have an active
1162	 * device.
1163	 */
1164	if (changer->devq.qfrozen_cnt > 0) {
1165
1166		/*
1167		 * We always need to reset the frozen count and clear the
1168		 * active flag.
1169		 */
1170		changer->devq.qfrozen_cnt--;
1171		changer->cur_device->flags &= ~CD_FLAG_ACTIVE;
1172		changer->cur_device->flags &= ~CD_FLAG_SCHED_ON_COMP;
1173
1174		if (changer->cur_device->outstanding_cmds > 0) {
1175			changer->cur_device->flags |= CD_FLAG_SCHED_ON_COMP;
1176			changer->cur_device->bufs_left =
1177				changer->cur_device->outstanding_cmds;
1178			if (called_from_timeout) {
1179				callout_reset(&changer->long_handle,
1180			            changer_max_busy_seconds * hz,
1181				    cdrunchangerqueue, changer);
1182				changer->flags |= CHANGER_TIMEOUT_SCHED;
1183			}
1184			return;
1185		}
1186
1187		/*
1188		 * Check to see whether the current device has any I/O left
1189		 * to do.  If so, requeue it at the end of the queue.  If
1190		 * not, there is no need to requeue it.
1191		 */
1192		if (bioq_first(&changer->cur_device->bio_queue) != NULL) {
1193
1194			changer->cur_device->pinfo.generation =
1195				++changer->devq.generation;
1196			camq_insert(&changer->devq,
1197				(cam_pinfo *)changer->cur_device);
1198		}
1199	}
1200
1201	softc = (struct cd_softc *)camq_remove(&changer->devq, CAMQ_HEAD);
1202
1203	changer->cur_device = softc;
1204
1205	changer->devq.qfrozen_cnt++;
1206	softc->flags |= CD_FLAG_ACTIVE;
1207
1208	/* Just in case this device is waiting */
1209	wakeup(&softc->changer);
1210	xpt_schedule(softc->periph, /*priority*/ 1);
1211
1212	/*
1213	 * Get rid of any pending timeouts, and set a flag to schedule new
1214	 * ones so this device gets its full time quantum.
1215	 */
1216	if (changer->flags & CHANGER_TIMEOUT_SCHED) {
1217		callout_stop(&changer->long_handle);
1218		changer->flags &= ~CHANGER_TIMEOUT_SCHED;
1219	}
1220
1221	if (changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
1222		callout_stop(&changer->short_handle);
1223		changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
1224	}
1225
1226	/*
1227	 * We need to schedule timeouts, but we only do this after the
1228	 * first transaction has completed.  This eliminates the changer
1229	 * switch time.
1230	 */
1231	changer->flags |= CHANGER_NEED_TIMEOUT;
1232}
1233
1234static void
1235cdchangerschedule(struct cd_softc *softc)
1236{
1237	struct cdchanger *changer;
1238
1239	changer = softc->changer;
1240
1241	/*
1242	 * If this is a changer, and this is the current device,
1243	 * and this device has at least the minimum time quantum to
1244	 * run, see if we can switch it out.
1245	 */
1246	if ((softc->flags & CD_FLAG_ACTIVE)
1247	 && ((changer->flags & CHANGER_SHORT_TMOUT_SCHED) == 0)
1248	 && ((changer->flags & CHANGER_NEED_TIMEOUT) == 0)) {
1249		/*
1250		 * We try three things here.  The first is that we
1251		 * check to see whether the schedule on completion
1252		 * flag is set.  If it is, we decrement the number
1253		 * of buffers left, and if it's zero, we reschedule.
1254		 * Next, we check to see whether the pending buffer
1255		 * queue is empty and whether there are no
1256		 * outstanding transactions.  If so, we reschedule.
1257		 * Next, we see if the pending buffer queue is empty.
1258		 * If it is, we set the number of buffers left to
1259		 * the current active buffer count and set the
1260		 * schedule on complete flag.
1261		 */
1262		if (softc->flags & CD_FLAG_SCHED_ON_COMP) {
1263		 	if (--softc->bufs_left == 0) {
1264				softc->changer->flags |=
1265					CHANGER_MANUAL_CALL;
1266				softc->flags &= ~CD_FLAG_SCHED_ON_COMP;
1267				cdrunchangerqueue(softc->changer);
1268			}
1269		} else if ((bioq_first(&softc->bio_queue) == NULL)
1270		        && (softc->outstanding_cmds == 0)) {
1271			softc->changer->flags |= CHANGER_MANUAL_CALL;
1272			cdrunchangerqueue(softc->changer);
1273		}
1274	} else if ((softc->changer->flags & CHANGER_NEED_TIMEOUT)
1275		&& (softc->flags & CD_FLAG_ACTIVE)) {
1276
1277		/*
1278		 * Now that the first transaction to this
1279		 * particular device has completed, we can go ahead
1280		 * and schedule our timeouts.
1281		 */
1282		if ((changer->flags & CHANGER_TIMEOUT_SCHED) == 0) {
1283			callout_reset(&changer->long_handle,
1284			    changer_max_busy_seconds * hz,
1285			    cdrunchangerqueue, changer);
1286			changer->flags |= CHANGER_TIMEOUT_SCHED;
1287		} else
1288			printf("cdchangerschedule: already have a long"
1289			       " timeout!\n");
1290
1291		if ((changer->flags & CHANGER_SHORT_TMOUT_SCHED) == 0) {
1292			callout_reset(&changer->short_handle,
1293			    changer_min_busy_seconds * hz,
1294			    cdshorttimeout, changer);
1295			changer->flags |= CHANGER_SHORT_TMOUT_SCHED;
1296		} else
1297			printf("cdchangerschedule: already have a short "
1298			       "timeout!\n");
1299
1300		/*
1301		 * We just scheduled timeouts, no need to schedule
1302		 * more.
1303		 */
1304		changer->flags &= ~CHANGER_NEED_TIMEOUT;
1305
1306	}
1307}
1308
1309static int
1310cdrunccb(union ccb *ccb, int (*error_routine)(union ccb *ccb,
1311					      u_int32_t cam_flags,
1312					      u_int32_t sense_flags),
1313	 u_int32_t cam_flags, u_int32_t sense_flags)
1314{
1315	struct cd_softc *softc;
1316	struct cam_periph *periph;
1317	int error;
1318
1319	periph = xpt_path_periph(ccb->ccb_h.path);
1320	softc = (struct cd_softc *)periph->softc;
1321
1322	error = cam_periph_runccb(ccb, error_routine, cam_flags, sense_flags,
1323				  softc->disk->d_devstat);
1324
1325	if (softc->flags & CD_FLAG_CHANGER)
1326		cdchangerschedule(softc);
1327
1328	return(error);
1329}
1330
1331static union ccb *
1332cdgetccb(struct cam_periph *periph, u_int32_t priority)
1333{
1334	struct cd_softc *softc;
1335
1336	softc = (struct cd_softc *)periph->softc;
1337
1338	if (softc->flags & CD_FLAG_CHANGER) {
1339		/*
1340		 * This should work the first time this device is woken up,
1341		 * but just in case it doesn't, we use a while loop.
1342		 */
1343		while ((softc->flags & CD_FLAG_ACTIVE) == 0) {
1344			/*
1345			 * If this changer isn't already queued, queue it up.
1346			 */
1347			if (softc->pinfo.index == CAM_UNQUEUED_INDEX) {
1348				softc->pinfo.priority = 1;
1349				softc->pinfo.generation =
1350					++softc->changer->devq.generation;
1351				camq_insert(&softc->changer->devq,
1352					    (cam_pinfo *)softc);
1353			}
1354			if (((softc->changer->flags & CHANGER_TIMEOUT_SCHED)==0)
1355			 && ((softc->changer->flags & CHANGER_NEED_TIMEOUT)==0)
1356			 && ((softc->changer->flags
1357			      & CHANGER_SHORT_TMOUT_SCHED)==0)) {
1358				softc->changer->flags |= CHANGER_MANUAL_CALL;
1359				cdrunchangerqueue(softc->changer);
1360			} else
1361				msleep(&softc->changer, periph->sim->mtx,
1362				    PRIBIO, "cgticb", 0);
1363		}
1364	}
1365	return(cam_periph_getccb(periph, priority));
1366}
1367
1368
1369/*
1370 * Actually translate the requested transfer into one the physical driver
1371 * can understand.  The transfer is described by a buf and will include
1372 * only one physical transfer.
1373 */
1374static void
1375cdstrategy(struct bio *bp)
1376{
1377	struct cam_periph *periph;
1378	struct cd_softc *softc;
1379
1380	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1381	if (periph == NULL) {
1382		biofinish(bp, NULL, ENXIO);
1383		return;
1384	}
1385
1386	cam_periph_lock(periph);
1387	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdstrategy\n"));
1388
1389	softc = (struct cd_softc *)periph->softc;
1390
1391	/*
1392	 * If the device has been made invalid, error out
1393	 */
1394	if ((softc->flags & CD_FLAG_INVALID)) {
1395		cam_periph_unlock(periph);
1396		biofinish(bp, NULL, ENXIO);
1397		return;
1398	}
1399
1400        /*
1401	 * If we don't have valid media, look for it before trying to
1402	 * schedule the I/O.
1403	 */
1404	if ((softc->flags & CD_FLAG_VALID_MEDIA) == 0) {
1405		int error;
1406
1407		error = cdcheckmedia(periph);
1408		if (error != 0) {
1409			cam_periph_unlock(periph);
1410			biofinish(bp, NULL, error);
1411			return;
1412		}
1413	}
1414
1415	/*
1416	 * Place it in the queue of disk activities for this disk
1417	 */
1418	bioq_disksort(&softc->bio_queue, bp);
1419
1420	/*
1421	 * Schedule ourselves for performing the work.  We do things
1422	 * differently for changers.
1423	 */
1424	if ((softc->flags & CD_FLAG_CHANGER) == 0)
1425		xpt_schedule(periph, /* XXX priority */1);
1426	else
1427		cdschedule(periph, /* priority */ 1);
1428
1429	cam_periph_unlock(periph);
1430	return;
1431}
1432
1433static void
1434cdstart(struct cam_periph *periph, union ccb *start_ccb)
1435{
1436	struct cd_softc *softc;
1437	struct bio *bp;
1438	struct ccb_scsiio *csio;
1439	struct scsi_read_capacity_data *rcap;
1440
1441	softc = (struct cd_softc *)periph->softc;
1442
1443	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdstart\n"));
1444
1445	switch (softc->state) {
1446	case CD_STATE_NORMAL:
1447	{
1448		bp = bioq_first(&softc->bio_queue);
1449		if (periph->immediate_priority <= periph->pinfo.priority) {
1450			start_ccb->ccb_h.ccb_state = CD_CCB_WAITING;
1451
1452			SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1453					  periph_links.sle);
1454			periph->immediate_priority = CAM_PRIORITY_NONE;
1455			wakeup(&periph->ccb_list);
1456		} else if (bp == NULL) {
1457			xpt_release_ccb(start_ccb);
1458		} else {
1459			bioq_remove(&softc->bio_queue, bp);
1460
1461			devstat_start_transaction_bio(softc->disk->d_devstat, bp);
1462
1463			scsi_read_write(&start_ccb->csio,
1464					/*retries*/cd_retry_count,
1465					/* cbfcnp */ cddone,
1466					MSG_SIMPLE_Q_TAG,
1467					/* read */bp->bio_cmd == BIO_READ,
1468					/* byte2 */ 0,
1469					/* minimum_cmd_size */ 10,
1470					/* lba */ bp->bio_offset /
1471					  softc->params.blksize,
1472					bp->bio_bcount / softc->params.blksize,
1473					/* data_ptr */ bp->bio_data,
1474					/* dxfer_len */ bp->bio_bcount,
1475					/* sense_len */ SSD_FULL_SIZE,
1476					/* timeout */ 30000);
1477			start_ccb->ccb_h.ccb_state = CD_CCB_BUFFER_IO;
1478
1479
1480			LIST_INSERT_HEAD(&softc->pending_ccbs,
1481					 &start_ccb->ccb_h, periph_links.le);
1482			softc->outstanding_cmds++;
1483
1484			/* We expect a unit attention from this device */
1485			if ((softc->flags & CD_FLAG_RETRY_UA) != 0) {
1486				start_ccb->ccb_h.ccb_state |= CD_CCB_RETRY_UA;
1487				softc->flags &= ~CD_FLAG_RETRY_UA;
1488			}
1489
1490			start_ccb->ccb_h.ccb_bp = bp;
1491			bp = bioq_first(&softc->bio_queue);
1492
1493			xpt_action(start_ccb);
1494		}
1495		if (bp != NULL) {
1496			/* Have more work to do, so ensure we stay scheduled */
1497			xpt_schedule(periph, /* XXX priority */1);
1498		}
1499		break;
1500	}
1501	case CD_STATE_PROBE:
1502	{
1503
1504		rcap = (struct scsi_read_capacity_data *)malloc(sizeof(*rcap),
1505								M_SCSICD,
1506								M_NOWAIT);
1507		if (rcap == NULL) {
1508			xpt_print(periph->path,
1509			    "cdstart: Couldn't malloc read_capacity data\n");
1510			/* cd_free_periph??? */
1511			break;
1512		}
1513		csio = &start_ccb->csio;
1514		scsi_read_capacity(csio,
1515				   /*retries*/1,
1516				   cddone,
1517				   MSG_SIMPLE_Q_TAG,
1518				   rcap,
1519				   SSD_FULL_SIZE,
1520				   /*timeout*/20000);
1521		start_ccb->ccb_h.ccb_bp = NULL;
1522		start_ccb->ccb_h.ccb_state = CD_CCB_PROBE;
1523		xpt_action(start_ccb);
1524		break;
1525	}
1526	}
1527}
1528
1529static void
1530cddone(struct cam_periph *periph, union ccb *done_ccb)
1531{
1532	struct cd_softc *softc;
1533	struct ccb_scsiio *csio;
1534
1535	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cddone\n"));
1536
1537	softc = (struct cd_softc *)periph->softc;
1538	csio = &done_ccb->csio;
1539
1540	switch (csio->ccb_h.ccb_state & CD_CCB_TYPE_MASK) {
1541	case CD_CCB_BUFFER_IO:
1542	{
1543		struct bio	*bp;
1544		int		error;
1545
1546		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
1547		error = 0;
1548
1549		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1550			int sf;
1551
1552			if ((done_ccb->ccb_h.ccb_state & CD_CCB_RETRY_UA) != 0)
1553				sf = SF_RETRY_UA;
1554			else
1555				sf = 0;
1556
1557			error = cderror(done_ccb, CAM_RETRY_SELTO, sf);
1558			if (error == ERESTART) {
1559				/*
1560				 * A retry was scheuled, so
1561				 * just return.
1562				 */
1563				return;
1564			}
1565		}
1566
1567		if (error != 0) {
1568			xpt_print(periph->path,
1569			    "cddone: got error %#x back\n", error);
1570			bioq_flush(&softc->bio_queue, NULL, EIO);
1571			bp->bio_resid = bp->bio_bcount;
1572			bp->bio_error = error;
1573			bp->bio_flags |= BIO_ERROR;
1574			cam_release_devq(done_ccb->ccb_h.path,
1575					 /*relsim_flags*/0,
1576					 /*reduction*/0,
1577					 /*timeout*/0,
1578					 /*getcount_only*/0);
1579
1580		} else {
1581			bp->bio_resid = csio->resid;
1582			bp->bio_error = 0;
1583			if (bp->bio_resid != 0) {
1584				/*
1585				 * Short transfer ???
1586				 * XXX: not sure this is correct for partial
1587				 * transfers at EOM
1588				 */
1589				bp->bio_flags |= BIO_ERROR;
1590			}
1591		}
1592
1593		LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
1594		softc->outstanding_cmds--;
1595
1596		if (softc->flags & CD_FLAG_CHANGER)
1597			cdchangerschedule(softc);
1598
1599		biofinish(bp, NULL, 0);
1600		break;
1601	}
1602	case CD_CCB_PROBE:
1603	{
1604		struct	   scsi_read_capacity_data *rdcap;
1605		char	   announce_buf[120]; /*
1606					       * Currently (9/30/97) the
1607					       * longest possible announce
1608					       * buffer is 108 bytes, for the
1609					       * first error case below.
1610					       * That is 39 bytes for the
1611					       * basic string, 16 bytes for the
1612					       * biggest sense key (hardware
1613					       * error), 52 bytes for the
1614					       * text of the largest sense
1615					       * qualifier valid for a CDROM,
1616					       * (0x72, 0x03 or 0x04,
1617					       * 0x03), and one byte for the
1618					       * null terminating character.
1619					       * To allow for longer strings,
1620					       * the announce buffer is 120
1621					       * bytes.
1622					       */
1623		struct	   cd_params *cdp;
1624
1625		cdp = &softc->params;
1626
1627		rdcap = (struct scsi_read_capacity_data *)csio->data_ptr;
1628
1629		cdp->disksize = scsi_4btoul (rdcap->addr) + 1;
1630		cdp->blksize = scsi_4btoul (rdcap->length);
1631
1632		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1633
1634			snprintf(announce_buf, sizeof(announce_buf),
1635				"cd present [%lu x %lu byte records]",
1636				cdp->disksize, (u_long)cdp->blksize);
1637
1638		} else {
1639			int	error;
1640			/*
1641			 * Retry any UNIT ATTENTION type errors.  They
1642			 * are expected at boot.
1643			 */
1644			error = cderror(done_ccb, CAM_RETRY_SELTO,
1645					SF_RETRY_UA | SF_NO_PRINT);
1646			if (error == ERESTART) {
1647				/*
1648				 * A retry was scheuled, so
1649				 * just return.
1650				 */
1651				return;
1652			} else if (error != 0) {
1653
1654				struct scsi_sense_data *sense;
1655				int asc, ascq;
1656				int sense_key, error_code;
1657				int have_sense;
1658				cam_status status;
1659				struct ccb_getdev cgd;
1660
1661				/* Don't wedge this device's queue */
1662				cam_release_devq(done_ccb->ccb_h.path,
1663						 /*relsim_flags*/0,
1664						 /*reduction*/0,
1665						 /*timeout*/0,
1666						 /*getcount_only*/0);
1667
1668				status = done_ccb->ccb_h.status;
1669
1670				xpt_setup_ccb(&cgd.ccb_h,
1671					      done_ccb->ccb_h.path,
1672					      /* priority */ 1);
1673				cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1674				xpt_action((union ccb *)&cgd);
1675
1676				if (((csio->ccb_h.flags & CAM_SENSE_PHYS) != 0)
1677				 || ((csio->ccb_h.flags & CAM_SENSE_PTR) != 0)
1678				 || ((status & CAM_AUTOSNS_VALID) == 0))
1679					have_sense = FALSE;
1680				else
1681					have_sense = TRUE;
1682
1683				if (have_sense) {
1684					sense = &csio->sense_data;
1685					scsi_extract_sense(sense, &error_code,
1686							   &sense_key,
1687							   &asc, &ascq);
1688				}
1689				/*
1690				 * Attach to anything that claims to be a
1691				 * CDROM or WORM device, as long as it
1692				 * doesn't return a "Logical unit not
1693				 * supported" (0x25) error.
1694				 */
1695				if ((have_sense) && (asc != 0x25)
1696				 && (error_code == SSD_CURRENT_ERROR)) {
1697					const char *sense_key_desc;
1698					const char *asc_desc;
1699
1700					scsi_sense_desc(sense_key, asc, ascq,
1701							&cgd.inq_data,
1702							&sense_key_desc,
1703							&asc_desc);
1704					snprintf(announce_buf,
1705					    sizeof(announce_buf),
1706						"Attempt to query device "
1707						"size failed: %s, %s",
1708						sense_key_desc,
1709						asc_desc);
1710 				} else if ((have_sense == 0)
1711 				      && ((status & CAM_STATUS_MASK) ==
1712 					   CAM_SCSI_STATUS_ERROR)
1713 				      && (csio->scsi_status ==
1714 					  SCSI_STATUS_BUSY)) {
1715 					snprintf(announce_buf,
1716 					    sizeof(announce_buf),
1717 					    "Attempt to query device "
1718 					    "size failed: SCSI Status: %s",
1719					    scsi_status_string(csio));
1720				} else if (SID_TYPE(&cgd.inq_data) == T_CDROM) {
1721					/*
1722					 * We only print out an error for
1723					 * CDROM type devices.  For WORM
1724					 * devices, we don't print out an
1725					 * error since a few WORM devices
1726					 * don't support CDROM commands.
1727					 * If we have sense information, go
1728					 * ahead and print it out.
1729					 * Otherwise, just say that we
1730					 * couldn't attach.
1731					 */
1732
1733					/*
1734					 * Just print out the error, not
1735					 * the full probe message, when we
1736					 * don't attach.
1737					 */
1738					if (have_sense)
1739						scsi_sense_print(
1740							&done_ccb->csio);
1741					else {
1742						xpt_print(periph->path,
1743						    "got CAM status %#x\n",
1744						    done_ccb->ccb_h.status);
1745					}
1746					xpt_print(periph->path, "fatal error, "
1747					    "failed to attach to device\n");
1748					/*
1749					 * Invalidate this peripheral.
1750					 */
1751					cam_periph_invalidate(periph);
1752
1753					announce_buf[0] = '\0';
1754				} else {
1755
1756					/*
1757					 * Invalidate this peripheral.
1758					 */
1759					cam_periph_invalidate(periph);
1760					announce_buf[0] = '\0';
1761				}
1762			}
1763		}
1764		free(rdcap, M_SCSICD);
1765		if (announce_buf[0] != '\0') {
1766			xpt_announce_periph(periph, announce_buf);
1767			if (softc->flags & CD_FLAG_CHANGER)
1768				cdchangerschedule(softc);
1769			/*
1770			 * Create our sysctl variables, now that we know
1771			 * we have successfully attached.
1772			 */
1773			taskqueue_enqueue(taskqueue_thread,&softc->sysctl_task);
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_unhold(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 union cd_pages *
1804cdgetpage(struct cd_mode_params *mode_params)
1805{
1806	union cd_pages *page;
1807
1808	if (mode_params->cdb_size == 10)
1809		page = (union cd_pages *)find_mode_page_10(
1810			(struct scsi_mode_header_10 *)mode_params->mode_buf);
1811	else
1812		page = (union cd_pages *)find_mode_page_6(
1813			(struct scsi_mode_header_6 *)mode_params->mode_buf);
1814
1815	return (page);
1816}
1817
1818static int
1819cdgetpagesize(int page_num)
1820{
1821	int i;
1822
1823	for (i = 0; i < (sizeof(cd_page_size_table)/
1824	     sizeof(cd_page_size_table[0])); i++) {
1825		if (cd_page_size_table[i].page == page_num)
1826			return (cd_page_size_table[i].page_size);
1827	}
1828
1829	return (-1);
1830}
1831
1832static int
1833cdioctl(struct disk *dp, u_long cmd, void *addr, int flag, struct thread *td)
1834{
1835
1836	struct 	cam_periph *periph;
1837	struct	cd_softc *softc;
1838	int	nocopyout, error = 0;
1839
1840	periph = (struct cam_periph *)dp->d_drv1;
1841	if (periph == NULL)
1842		return(ENXIO);
1843
1844	cam_periph_lock(periph);
1845	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdioctl\n"));
1846
1847	softc = (struct cd_softc *)periph->softc;
1848
1849	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1850		  ("trying to do ioctl %#lx\n", cmd));
1851
1852	if ((error = cam_periph_hold(periph, PRIBIO | PCATCH)) != 0) {
1853		cam_periph_unlock(periph);
1854		cam_periph_release(periph);
1855		return (error);
1856	}
1857
1858	/*
1859	 * If we don't have media loaded, check for it.  If still don't
1860	 * have media loaded, we can only do a load or eject.
1861	 *
1862	 * We only care whether media is loaded if this is a cd-specific ioctl
1863	 * (thus the IOCGROUP check below).  Note that this will break if
1864	 * anyone adds any ioctls into the switch statement below that don't
1865	 * have their ioctl group set to 'c'.
1866	 */
1867	if (((softc->flags & CD_FLAG_VALID_MEDIA) == 0)
1868	 && ((cmd != CDIOCCLOSE)
1869	  && (cmd != CDIOCEJECT))
1870	 && (IOCGROUP(cmd) == 'c')) {
1871		error = cdcheckmedia(periph);
1872		if (error != 0) {
1873			cam_periph_unhold(periph);
1874			cam_periph_unlock(periph);
1875			return (error);
1876		}
1877	}
1878	/*
1879	 * Drop the lock here so later mallocs can use WAITOK.  The periph
1880	 * is essentially locked still with the cam_periph_hold call above.
1881	 */
1882	cam_periph_unlock(periph);
1883
1884	nocopyout = 0;
1885	switch (cmd) {
1886
1887	case CDIOCPLAYTRACKS:
1888		{
1889			struct ioc_play_track *args
1890			    = (struct ioc_play_track *) addr;
1891			struct cd_mode_params params;
1892			union cd_pages *page;
1893
1894			params.alloc_len = sizeof(union cd_mode_data_6_10);
1895			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
1896						 M_WAITOK | M_ZERO);
1897
1898			cam_periph_lock(periph);
1899			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1900				  ("trying to do CDIOCPLAYTRACKS\n"));
1901
1902			error = cdgetmode(periph, &params, AUDIO_PAGE);
1903			if (error) {
1904				free(params.mode_buf, M_SCSICD);
1905				cam_periph_unlock(periph);
1906				break;
1907			}
1908			page = cdgetpage(&params);
1909
1910			page->audio.flags &= ~CD_PA_SOTC;
1911			page->audio.flags |= CD_PA_IMMED;
1912			error = cdsetmode(periph, &params);
1913			free(params.mode_buf, M_SCSICD);
1914			if (error) {
1915				cam_periph_unlock(periph);
1916				break;
1917			}
1918
1919			/*
1920			 * This was originally implemented with the PLAY
1921			 * AUDIO TRACK INDEX command, but that command was
1922			 * deprecated after SCSI-2.  Most (all?) SCSI CDROM
1923			 * drives support it but ATAPI and ATAPI-derivative
1924			 * drives don't seem to support it.  So we keep a
1925			 * cache of the table of contents and translate
1926			 * track numbers to MSF format.
1927			 */
1928			if (softc->flags & CD_FLAG_VALID_TOC) {
1929				union msf_lba *sentry, *eentry;
1930				int st, et;
1931
1932				if (args->end_track <
1933				    softc->toc.header.ending_track + 1)
1934					args->end_track++;
1935				if (args->end_track >
1936				    softc->toc.header.ending_track + 1)
1937					args->end_track =
1938					    softc->toc.header.ending_track + 1;
1939				st = args->start_track -
1940					softc->toc.header.starting_track;
1941				et = args->end_track -
1942					softc->toc.header.starting_track;
1943				if ((st < 0)
1944				 || (et < 0)
1945			 	 || (st > (softc->toc.header.ending_track -
1946				     softc->toc.header.starting_track))) {
1947					error = EINVAL;
1948					break;
1949				}
1950				sentry = &softc->toc.entries[st].addr;
1951				eentry = &softc->toc.entries[et].addr;
1952				error = cdplaymsf(periph,
1953						  sentry->msf.minute,
1954						  sentry->msf.second,
1955						  sentry->msf.frame,
1956						  eentry->msf.minute,
1957						  eentry->msf.second,
1958						  eentry->msf.frame);
1959			} else {
1960				/*
1961				 * If we don't have a valid TOC, try the
1962				 * play track index command.  It is part of
1963				 * the SCSI-2 spec, but was removed in the
1964				 * MMC specs.  ATAPI and ATAPI-derived
1965				 * drives don't support it.
1966				 */
1967				if (softc->quirks & CD_Q_BCD_TRACKS) {
1968					args->start_track =
1969						bin2bcd(args->start_track);
1970					args->end_track =
1971						bin2bcd(args->end_track);
1972				}
1973				error = cdplaytracks(periph,
1974						     args->start_track,
1975						     args->start_index,
1976						     args->end_track,
1977						     args->end_index);
1978			}
1979			cam_periph_unlock(periph);
1980		}
1981		break;
1982	case CDIOCPLAYMSF:
1983		{
1984			struct ioc_play_msf *args
1985				= (struct ioc_play_msf *) addr;
1986			struct cd_mode_params params;
1987			union cd_pages *page;
1988
1989			params.alloc_len = sizeof(union cd_mode_data_6_10);
1990			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
1991						 M_WAITOK | M_ZERO);
1992
1993			cam_periph_lock(periph);
1994			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1995				  ("trying to do CDIOCPLAYMSF\n"));
1996
1997			error = cdgetmode(periph, &params, AUDIO_PAGE);
1998			if (error) {
1999				free(params.mode_buf, M_SCSICD);
2000				cam_periph_unlock(periph);
2001				break;
2002			}
2003			page = cdgetpage(&params);
2004
2005			page->audio.flags &= ~CD_PA_SOTC;
2006			page->audio.flags |= CD_PA_IMMED;
2007			error = cdsetmode(periph, &params);
2008			free(params.mode_buf, M_SCSICD);
2009			if (error) {
2010				cam_periph_unlock(periph);
2011				break;
2012			}
2013			error = cdplaymsf(periph,
2014					  args->start_m,
2015					  args->start_s,
2016					  args->start_f,
2017					  args->end_m,
2018					  args->end_s,
2019					  args->end_f);
2020			cam_periph_unlock(periph);
2021		}
2022		break;
2023	case CDIOCPLAYBLOCKS:
2024		{
2025			struct ioc_play_blocks *args
2026				= (struct ioc_play_blocks *) addr;
2027			struct cd_mode_params params;
2028			union cd_pages *page;
2029
2030			params.alloc_len = sizeof(union cd_mode_data_6_10);
2031			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2032						 M_WAITOK | M_ZERO);
2033
2034			cam_periph_lock(periph);
2035			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2036				  ("trying to do CDIOCPLAYBLOCKS\n"));
2037
2038
2039			error = cdgetmode(periph, &params, AUDIO_PAGE);
2040			if (error) {
2041				free(params.mode_buf, M_SCSICD);
2042				cam_periph_unlock(periph);
2043				break;
2044			}
2045			page = cdgetpage(&params);
2046
2047			page->audio.flags &= ~CD_PA_SOTC;
2048			page->audio.flags |= CD_PA_IMMED;
2049			error = cdsetmode(periph, &params);
2050			free(params.mode_buf, M_SCSICD);
2051			if (error) {
2052				cam_periph_unlock(periph);
2053				break;
2054			}
2055			error = cdplay(periph, args->blk, args->len);
2056			cam_periph_unlock(periph);
2057		}
2058		break;
2059	case CDIOCREADSUBCHANNEL_SYSSPACE:
2060		nocopyout = 1;
2061		/* Fallthrough */
2062	case CDIOCREADSUBCHANNEL:
2063		{
2064			struct ioc_read_subchannel *args
2065				= (struct ioc_read_subchannel *) addr;
2066			struct cd_sub_channel_info *data;
2067			u_int32_t len = args->data_len;
2068
2069			data = malloc(sizeof(struct cd_sub_channel_info),
2070				      M_SCSICD, M_WAITOK);
2071
2072			cam_periph_lock(periph);
2073			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2074				  ("trying to do CDIOCREADSUBCHANNEL\n"));
2075
2076			if ((len > sizeof(struct cd_sub_channel_info)) ||
2077			    (len < sizeof(struct cd_sub_channel_header))) {
2078				printf(
2079					"scsi_cd: cdioctl: "
2080					"cdioreadsubchannel: error, len=%d\n",
2081					len);
2082				error = EINVAL;
2083				free(data, M_SCSICD);
2084				cam_periph_unlock(periph);
2085				break;
2086			}
2087
2088			if (softc->quirks & CD_Q_BCD_TRACKS)
2089				args->track = bin2bcd(args->track);
2090
2091			error = cdreadsubchannel(periph, args->address_format,
2092				args->data_format, args->track, data, len);
2093
2094			if (error) {
2095				free(data, M_SCSICD);
2096				cam_periph_unlock(periph);
2097	 			break;
2098			}
2099			if (softc->quirks & CD_Q_BCD_TRACKS)
2100				data->what.track_info.track_number =
2101				    bcd2bin(data->what.track_info.track_number);
2102			len = min(len, ((data->header.data_len[0] << 8) +
2103				data->header.data_len[1] +
2104				sizeof(struct cd_sub_channel_header)));
2105			cam_periph_unlock(periph);
2106			if (nocopyout == 0) {
2107				if (copyout(data, args->data, len) != 0) {
2108					error = EFAULT;
2109				}
2110			} else {
2111				bcopy(data, args->data, len);
2112			}
2113			free(data, M_SCSICD);
2114		}
2115		break;
2116
2117	case CDIOREADTOCHEADER:
2118		{
2119			struct ioc_toc_header *th;
2120
2121			th = malloc(sizeof(struct ioc_toc_header), M_SCSICD,
2122				    M_WAITOK);
2123
2124			cam_periph_lock(periph);
2125			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2126				  ("trying to do CDIOREADTOCHEADER\n"));
2127
2128			error = cdreadtoc(periph, 0, 0, (u_int8_t *)th,
2129				          sizeof (*th), /*sense_flags*/0);
2130			if (error) {
2131				free(th, M_SCSICD);
2132				cam_periph_unlock(periph);
2133				break;
2134			}
2135			if (softc->quirks & CD_Q_BCD_TRACKS) {
2136				/* we are going to have to convert the BCD
2137				 * encoding on the cd to what is expected
2138				 */
2139				th->starting_track =
2140					bcd2bin(th->starting_track);
2141				th->ending_track = bcd2bin(th->ending_track);
2142			}
2143			th->len = ntohs(th->len);
2144			bcopy(th, addr, sizeof(*th));
2145			free(th, M_SCSICD);
2146			cam_periph_unlock(periph);
2147		}
2148		break;
2149	case CDIOREADTOCENTRYS:
2150		{
2151			struct cd_tocdata *data;
2152			struct cd_toc_single *lead;
2153			struct ioc_read_toc_entry *te =
2154				(struct ioc_read_toc_entry *) addr;
2155			struct ioc_toc_header *th;
2156			u_int32_t len, readlen, idx, num;
2157			u_int32_t starting_track = te->starting_track;
2158
2159			data = malloc(sizeof(*data), M_SCSICD, M_WAITOK);
2160			lead = malloc(sizeof(*lead), M_SCSICD, M_WAITOK);
2161
2162			cam_periph_lock(periph);
2163			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2164				  ("trying to do CDIOREADTOCENTRYS\n"));
2165
2166			if (te->data_len < sizeof(struct cd_toc_entry)
2167			 || (te->data_len % sizeof(struct cd_toc_entry)) != 0
2168			 || (te->address_format != CD_MSF_FORMAT
2169			  && te->address_format != CD_LBA_FORMAT)) {
2170				error = EINVAL;
2171				printf("scsi_cd: error in readtocentries, "
2172				       "returning EINVAL\n");
2173				free(data, M_SCSICD);
2174				free(lead, M_SCSICD);
2175				cam_periph_unlock(periph);
2176				break;
2177			}
2178
2179			th = &data->header;
2180			error = cdreadtoc(periph, 0, 0, (u_int8_t *)th,
2181					  sizeof (*th), /*sense_flags*/0);
2182			if (error) {
2183				free(data, M_SCSICD);
2184				free(lead, M_SCSICD);
2185				cam_periph_unlock(periph);
2186				break;
2187			}
2188
2189			if (softc->quirks & CD_Q_BCD_TRACKS) {
2190				/* we are going to have to convert the BCD
2191				 * encoding on the cd to what is expected
2192				 */
2193				th->starting_track =
2194				    bcd2bin(th->starting_track);
2195				th->ending_track = bcd2bin(th->ending_track);
2196			}
2197
2198			if (starting_track == 0)
2199				starting_track = th->starting_track;
2200			else if (starting_track == LEADOUT)
2201				starting_track = th->ending_track + 1;
2202			else if (starting_track < th->starting_track ||
2203				 starting_track > th->ending_track + 1) {
2204				printf("scsi_cd: error in readtocentries, "
2205				       "returning EINVAL\n");
2206				free(data, M_SCSICD);
2207				free(lead, M_SCSICD);
2208				cam_periph_unlock(periph);
2209				error = EINVAL;
2210				break;
2211			}
2212
2213			/* calculate reading length without leadout entry */
2214			readlen = (th->ending_track - starting_track + 1) *
2215				  sizeof(struct cd_toc_entry);
2216
2217			/* and with leadout entry */
2218			len = readlen + sizeof(struct cd_toc_entry);
2219			if (te->data_len < len) {
2220				len = te->data_len;
2221				if (readlen > len)
2222					readlen = len;
2223			}
2224			if (len > sizeof(data->entries)) {
2225				printf("scsi_cd: error in readtocentries, "
2226				       "returning EINVAL\n");
2227				error = EINVAL;
2228				free(data, M_SCSICD);
2229				free(lead, M_SCSICD);
2230				cam_periph_unlock(periph);
2231				break;
2232			}
2233			num = len / sizeof(struct cd_toc_entry);
2234
2235			if (readlen > 0) {
2236				error = cdreadtoc(periph, te->address_format,
2237						  starting_track,
2238						  (u_int8_t *)data,
2239						  readlen + sizeof (*th),
2240						  /*sense_flags*/0);
2241				if (error) {
2242					free(data, M_SCSICD);
2243					free(lead, M_SCSICD);
2244					cam_periph_unlock(periph);
2245					break;
2246				}
2247			}
2248
2249			/* make leadout entry if needed */
2250			idx = starting_track + num - 1;
2251			if (softc->quirks & CD_Q_BCD_TRACKS)
2252				th->ending_track = bcd2bin(th->ending_track);
2253			if (idx == th->ending_track + 1) {
2254				error = cdreadtoc(periph, te->address_format,
2255						  LEADOUT, (u_int8_t *)lead,
2256						  sizeof(*lead),
2257						  /*sense_flags*/0);
2258				if (error) {
2259					free(data, M_SCSICD);
2260					free(lead, M_SCSICD);
2261					cam_periph_unlock(periph);
2262					break;
2263				}
2264				data->entries[idx - starting_track] =
2265					lead->entry;
2266			}
2267			if (softc->quirks & CD_Q_BCD_TRACKS) {
2268				for (idx = 0; idx < num - 1; idx++) {
2269					data->entries[idx].track =
2270					    bcd2bin(data->entries[idx].track);
2271				}
2272			}
2273
2274			cam_periph_unlock(periph);
2275			error = copyout(data->entries, te->data, len);
2276			free(data, M_SCSICD);
2277			free(lead, M_SCSICD);
2278		}
2279		break;
2280	case CDIOREADTOCENTRY:
2281		{
2282			struct cd_toc_single *data;
2283			struct ioc_read_toc_single_entry *te =
2284				(struct ioc_read_toc_single_entry *) addr;
2285			struct ioc_toc_header *th;
2286			u_int32_t track;
2287
2288			data = malloc(sizeof(*data), M_SCSICD, M_WAITOK);
2289
2290			cam_periph_lock(periph);
2291			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2292				  ("trying to do CDIOREADTOCENTRY\n"));
2293
2294			if (te->address_format != CD_MSF_FORMAT
2295			    && te->address_format != CD_LBA_FORMAT) {
2296				printf("error in readtocentry, "
2297				       " returning EINVAL\n");
2298				free(data, M_SCSICD);
2299				error = EINVAL;
2300				cam_periph_unlock(periph);
2301				break;
2302			}
2303
2304			th = &data->header;
2305			error = cdreadtoc(periph, 0, 0, (u_int8_t *)th,
2306					  sizeof (*th), /*sense_flags*/0);
2307			if (error) {
2308				free(data, M_SCSICD);
2309				cam_periph_unlock(periph);
2310				break;
2311			}
2312
2313			if (softc->quirks & CD_Q_BCD_TRACKS) {
2314				/* we are going to have to convert the BCD
2315				 * encoding on the cd to what is expected
2316				 */
2317				th->starting_track =
2318				    bcd2bin(th->starting_track);
2319				th->ending_track = bcd2bin(th->ending_track);
2320			}
2321			track = te->track;
2322			if (track == 0)
2323				track = th->starting_track;
2324			else if (track == LEADOUT)
2325				/* OK */;
2326			else if (track < th->starting_track ||
2327				 track > th->ending_track + 1) {
2328				printf("error in readtocentry, "
2329				       " returning EINVAL\n");
2330				free(data, M_SCSICD);
2331				error = EINVAL;
2332				cam_periph_unlock(periph);
2333				break;
2334			}
2335
2336			error = cdreadtoc(periph, te->address_format, track,
2337					  (u_int8_t *)data, sizeof(*data),
2338					  /*sense_flags*/0);
2339			if (error) {
2340				free(data, M_SCSICD);
2341				cam_periph_unlock(periph);
2342				break;
2343			}
2344
2345			if (softc->quirks & CD_Q_BCD_TRACKS)
2346				data->entry.track = bcd2bin(data->entry.track);
2347			bcopy(&data->entry, &te->entry,
2348			      sizeof(struct cd_toc_entry));
2349			free(data, M_SCSICD);
2350			cam_periph_unlock(periph);
2351		}
2352		break;
2353	case CDIOCSETPATCH:
2354		{
2355			struct ioc_patch *arg = (struct ioc_patch *)addr;
2356			struct cd_mode_params params;
2357			union cd_pages *page;
2358
2359			params.alloc_len = sizeof(union cd_mode_data_6_10);
2360			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2361						 M_WAITOK | M_ZERO);
2362
2363			cam_periph_lock(periph);
2364			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2365				  ("trying to do CDIOCSETPATCH\n"));
2366
2367			error = cdgetmode(periph, &params, AUDIO_PAGE);
2368			if (error) {
2369				free(params.mode_buf, M_SCSICD);
2370				cam_periph_unlock(periph);
2371				break;
2372			}
2373			page = cdgetpage(&params);
2374
2375			page->audio.port[LEFT_PORT].channels =
2376				arg->patch[0];
2377			page->audio.port[RIGHT_PORT].channels =
2378				arg->patch[1];
2379			page->audio.port[2].channels = arg->patch[2];
2380			page->audio.port[3].channels = arg->patch[3];
2381			error = cdsetmode(periph, &params);
2382			free(params.mode_buf, M_SCSICD);
2383			cam_periph_unlock(periph);
2384		}
2385		break;
2386	case CDIOCGETVOL:
2387		{
2388			struct ioc_vol *arg = (struct ioc_vol *) addr;
2389			struct cd_mode_params params;
2390			union cd_pages *page;
2391
2392			params.alloc_len = sizeof(union cd_mode_data_6_10);
2393			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2394						 M_WAITOK | M_ZERO);
2395
2396			cam_periph_lock(periph);
2397			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2398				  ("trying to do CDIOCGETVOL\n"));
2399
2400			error = cdgetmode(periph, &params, AUDIO_PAGE);
2401			if (error) {
2402				free(params.mode_buf, M_SCSICD);
2403				cam_periph_unlock(periph);
2404				break;
2405			}
2406			page = cdgetpage(&params);
2407
2408			arg->vol[LEFT_PORT] =
2409				page->audio.port[LEFT_PORT].volume;
2410			arg->vol[RIGHT_PORT] =
2411				page->audio.port[RIGHT_PORT].volume;
2412			arg->vol[2] = page->audio.port[2].volume;
2413			arg->vol[3] = page->audio.port[3].volume;
2414			free(params.mode_buf, M_SCSICD);
2415			cam_periph_unlock(periph);
2416		}
2417		break;
2418	case CDIOCSETVOL:
2419		{
2420			struct ioc_vol *arg = (struct ioc_vol *) addr;
2421			struct cd_mode_params params;
2422			union cd_pages *page;
2423
2424			params.alloc_len = sizeof(union cd_mode_data_6_10);
2425			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2426						 M_WAITOK | M_ZERO);
2427
2428			cam_periph_lock(periph);
2429			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2430				  ("trying to do CDIOCSETVOL\n"));
2431
2432			error = cdgetmode(periph, &params, AUDIO_PAGE);
2433			if (error) {
2434				free(params.mode_buf, M_SCSICD);
2435				cam_periph_unlock(periph);
2436				break;
2437			}
2438			page = cdgetpage(&params);
2439
2440			page->audio.port[LEFT_PORT].channels = CHANNEL_0;
2441			page->audio.port[LEFT_PORT].volume =
2442				arg->vol[LEFT_PORT];
2443			page->audio.port[RIGHT_PORT].channels = CHANNEL_1;
2444			page->audio.port[RIGHT_PORT].volume =
2445				arg->vol[RIGHT_PORT];
2446			page->audio.port[2].volume = arg->vol[2];
2447			page->audio.port[3].volume = arg->vol[3];
2448			error = cdsetmode(periph, &params);
2449			cam_periph_unlock(periph);
2450			free(params.mode_buf, M_SCSICD);
2451		}
2452		break;
2453	case CDIOCSETMONO:
2454		{
2455			struct cd_mode_params params;
2456			union cd_pages *page;
2457
2458			params.alloc_len = sizeof(union cd_mode_data_6_10);
2459			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2460						 M_WAITOK | M_ZERO);
2461
2462			cam_periph_lock(periph);
2463			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2464				  ("trying to do CDIOCSETMONO\n"));
2465
2466			error = cdgetmode(periph, &params, AUDIO_PAGE);
2467			if (error) {
2468				free(params.mode_buf, M_SCSICD);
2469				cam_periph_unlock(periph);
2470				break;
2471			}
2472			page = cdgetpage(&params);
2473
2474			page->audio.port[LEFT_PORT].channels =
2475				LEFT_CHANNEL | RIGHT_CHANNEL;
2476			page->audio.port[RIGHT_PORT].channels =
2477				LEFT_CHANNEL | RIGHT_CHANNEL;
2478			page->audio.port[2].channels = 0;
2479			page->audio.port[3].channels = 0;
2480			error = cdsetmode(periph, &params);
2481			cam_periph_unlock(periph);
2482			free(params.mode_buf, M_SCSICD);
2483		}
2484		break;
2485	case CDIOCSETSTEREO:
2486		{
2487			struct cd_mode_params params;
2488			union cd_pages *page;
2489
2490			params.alloc_len = sizeof(union cd_mode_data_6_10);
2491			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2492						 M_WAITOK | M_ZERO);
2493
2494			cam_periph_lock(periph);
2495			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2496				  ("trying to do CDIOCSETSTEREO\n"));
2497
2498			error = cdgetmode(periph, &params, AUDIO_PAGE);
2499			if (error) {
2500				free(params.mode_buf, M_SCSICD);
2501				cam_periph_unlock(periph);
2502				break;
2503			}
2504			page = cdgetpage(&params);
2505
2506			page->audio.port[LEFT_PORT].channels =
2507				LEFT_CHANNEL;
2508			page->audio.port[RIGHT_PORT].channels =
2509				RIGHT_CHANNEL;
2510			page->audio.port[2].channels = 0;
2511			page->audio.port[3].channels = 0;
2512			error = cdsetmode(periph, &params);
2513			free(params.mode_buf, M_SCSICD);
2514			cam_periph_unlock(periph);
2515		}
2516		break;
2517	case CDIOCSETMUTE:
2518		{
2519			struct cd_mode_params params;
2520			union cd_pages *page;
2521
2522			params.alloc_len = sizeof(union cd_mode_data_6_10);
2523			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2524						 M_WAITOK | M_ZERO);
2525
2526			cam_periph_lock(periph);
2527			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2528				  ("trying to do CDIOCSETMUTE\n"));
2529
2530			error = cdgetmode(periph, &params, AUDIO_PAGE);
2531			if (error) {
2532				free(&params, M_SCSICD);
2533				cam_periph_unlock(periph);
2534				break;
2535			}
2536			page = cdgetpage(&params);
2537
2538			page->audio.port[LEFT_PORT].channels = 0;
2539			page->audio.port[RIGHT_PORT].channels = 0;
2540			page->audio.port[2].channels = 0;
2541			page->audio.port[3].channels = 0;
2542			error = cdsetmode(periph, &params);
2543			free(params.mode_buf, M_SCSICD);
2544			cam_periph_unlock(periph);
2545		}
2546		break;
2547	case CDIOCSETLEFT:
2548		{
2549			struct cd_mode_params params;
2550			union cd_pages *page;
2551
2552			params.alloc_len = sizeof(union cd_mode_data_6_10);
2553			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2554						 M_WAITOK | M_ZERO);
2555
2556			cam_periph_lock(periph);
2557			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2558				  ("trying to do CDIOCSETLEFT\n"));
2559
2560			error = cdgetmode(periph, &params, AUDIO_PAGE);
2561			if (error) {
2562				free(params.mode_buf, M_SCSICD);
2563				cam_periph_unlock(periph);
2564				break;
2565			}
2566			page = cdgetpage(&params);
2567
2568			page->audio.port[LEFT_PORT].channels = LEFT_CHANNEL;
2569			page->audio.port[RIGHT_PORT].channels = LEFT_CHANNEL;
2570			page->audio.port[2].channels = 0;
2571			page->audio.port[3].channels = 0;
2572			error = cdsetmode(periph, &params);
2573			free(params.mode_buf, M_SCSICD);
2574			cam_periph_unlock(periph);
2575		}
2576		break;
2577	case CDIOCSETRIGHT:
2578		{
2579			struct cd_mode_params params;
2580			union cd_pages *page;
2581
2582			params.alloc_len = sizeof(union cd_mode_data_6_10);
2583			params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2584						 M_WAITOK | M_ZERO);
2585
2586			cam_periph_lock(periph);
2587			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2588				  ("trying to do CDIOCSETRIGHT\n"));
2589
2590			error = cdgetmode(periph, &params, AUDIO_PAGE);
2591			if (error) {
2592				free(params.mode_buf, M_SCSICD);
2593				cam_periph_unlock(periph);
2594				break;
2595			}
2596			page = cdgetpage(&params);
2597
2598			page->audio.port[LEFT_PORT].channels = RIGHT_CHANNEL;
2599			page->audio.port[RIGHT_PORT].channels = RIGHT_CHANNEL;
2600			page->audio.port[2].channels = 0;
2601			page->audio.port[3].channels = 0;
2602			error = cdsetmode(periph, &params);
2603			free(params.mode_buf, M_SCSICD);
2604			cam_periph_unlock(periph);
2605		}
2606		break;
2607	case CDIOCRESUME:
2608		cam_periph_lock(periph);
2609		error = cdpause(periph, 1);
2610		cam_periph_unlock(periph);
2611		break;
2612	case CDIOCPAUSE:
2613		cam_periph_lock(periph);
2614		error = cdpause(periph, 0);
2615		cam_periph_unlock(periph);
2616		break;
2617	case CDIOCSTART:
2618		cam_periph_lock(periph);
2619		error = cdstartunit(periph, 0);
2620		cam_periph_unlock(periph);
2621		break;
2622	case CDIOCCLOSE:
2623		cam_periph_lock(periph);
2624		error = cdstartunit(periph, 1);
2625		cam_periph_unlock(periph);
2626		break;
2627	case CDIOCSTOP:
2628		cam_periph_lock(periph);
2629		error = cdstopunit(periph, 0);
2630		cam_periph_unlock(periph);
2631		break;
2632	case CDIOCEJECT:
2633		cam_periph_lock(periph);
2634		error = cdstopunit(periph, 1);
2635		cam_periph_unlock(periph);
2636		break;
2637	case CDIOCALLOW:
2638		cam_periph_lock(periph);
2639		cdprevent(periph, PR_ALLOW);
2640		cam_periph_unlock(periph);
2641		break;
2642	case CDIOCPREVENT:
2643		cam_periph_lock(periph);
2644		cdprevent(periph, PR_PREVENT);
2645		cam_periph_unlock(periph);
2646		break;
2647	case CDIOCSETDEBUG:
2648		/* sc_link->flags |= (SDEV_DB1 | SDEV_DB2); */
2649		error = ENOTTY;
2650		break;
2651	case CDIOCCLRDEBUG:
2652		/* sc_link->flags &= ~(SDEV_DB1 | SDEV_DB2); */
2653		error = ENOTTY;
2654		break;
2655	case CDIOCRESET:
2656		/* return (cd_reset(periph)); */
2657		error = ENOTTY;
2658		break;
2659	case CDRIOCREADSPEED:
2660		cam_periph_lock(periph);
2661		error = cdsetspeed(periph, *(u_int32_t *)addr, CDR_MAX_SPEED);
2662		cam_periph_unlock(periph);
2663		break;
2664	case CDRIOCWRITESPEED:
2665		cam_periph_lock(periph);
2666		error = cdsetspeed(periph, CDR_MAX_SPEED, *(u_int32_t *)addr);
2667		cam_periph_unlock(periph);
2668		break;
2669	case DVDIOCSENDKEY:
2670	case DVDIOCREPORTKEY: {
2671		struct dvd_authinfo *authinfo;
2672
2673		authinfo = (struct dvd_authinfo *)addr;
2674
2675		cam_periph_lock(periph);
2676		if (cmd == DVDIOCREPORTKEY)
2677			error = cdreportkey(periph, authinfo);
2678		else
2679			error = cdsendkey(periph, authinfo);
2680		cam_periph_unlock(periph);
2681		break;
2682		}
2683	case DVDIOCREADSTRUCTURE: {
2684		struct dvd_struct *dvdstruct;
2685
2686		dvdstruct = (struct dvd_struct *)addr;
2687
2688		cam_periph_lock(periph);
2689		error = cdreaddvdstructure(periph, dvdstruct);
2690		cam_periph_unlock(periph);
2691
2692		break;
2693	}
2694	default:
2695		cam_periph_lock(periph);
2696		error = cam_periph_ioctl(periph, cmd, addr, cderror);
2697		cam_periph_unlock(periph);
2698		break;
2699	}
2700
2701	cam_periph_lock(periph);
2702	cam_periph_unhold(periph);
2703
2704	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdioctl\n"));
2705	if (error && bootverbose) {
2706		printf("scsi_cd.c::ioctl cmd=%08lx error=%d\n", cmd, error);
2707	}
2708	cam_periph_unlock(periph);
2709
2710	return (error);
2711}
2712
2713static void
2714cdprevent(struct cam_periph *periph, int action)
2715{
2716	union	ccb *ccb;
2717	struct	cd_softc *softc;
2718	int	error;
2719
2720	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdprevent\n"));
2721
2722	softc = (struct cd_softc *)periph->softc;
2723
2724	if (((action == PR_ALLOW)
2725	  && (softc->flags & CD_FLAG_DISC_LOCKED) == 0)
2726	 || ((action == PR_PREVENT)
2727	  && (softc->flags & CD_FLAG_DISC_LOCKED) != 0)) {
2728		return;
2729	}
2730
2731	ccb = cdgetccb(periph, /* priority */ 1);
2732
2733	scsi_prevent(&ccb->csio,
2734		     /*retries*/ 1,
2735		     cddone,
2736		     MSG_SIMPLE_Q_TAG,
2737		     action,
2738		     SSD_FULL_SIZE,
2739		     /* timeout */60000);
2740
2741	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2742			/*sense_flags*/SF_RETRY_UA|SF_NO_PRINT);
2743
2744	xpt_release_ccb(ccb);
2745
2746	if (error == 0) {
2747		if (action == PR_ALLOW)
2748			softc->flags &= ~CD_FLAG_DISC_LOCKED;
2749		else
2750			softc->flags |= CD_FLAG_DISC_LOCKED;
2751	}
2752}
2753
2754/*
2755 * XXX: the disk media and sector size is only really able to change
2756 * XXX: while the device is closed.
2757 */
2758static int
2759cdcheckmedia(struct cam_periph *periph)
2760{
2761	struct cd_softc *softc;
2762	struct ioc_toc_header *toch;
2763	struct cd_toc_single leadout;
2764	u_int32_t size, toclen;
2765	int error, num_entries, cdindex;
2766
2767	softc = (struct cd_softc *)periph->softc;
2768
2769	cdprevent(periph, PR_PREVENT);
2770	softc->disk->d_maxsize = DFLTPHYS;
2771	softc->disk->d_sectorsize = 2048;
2772	softc->disk->d_mediasize = 0;
2773
2774	/*
2775	 * Get the disc size and block size.  If we can't get it, we don't
2776	 * have media, most likely.
2777	 */
2778	if ((error = cdsize(periph, &size)) != 0) {
2779		softc->flags &= ~(CD_FLAG_VALID_MEDIA|CD_FLAG_VALID_TOC);
2780		cdprevent(periph, PR_ALLOW);
2781		return (error);
2782	} else
2783		softc->flags |= CD_FLAG_VALID_MEDIA;
2784
2785	/*
2786	 * Now we check the table of contents.  This (currently) is only
2787	 * used for the CDIOCPLAYTRACKS ioctl.  It may be used later to do
2788	 * things like present a separate entry in /dev for each track,
2789	 * like that acd(4) driver does.
2790	 */
2791	bzero(&softc->toc, sizeof(softc->toc));
2792	toch = &softc->toc.header;
2793	/*
2794	 * We will get errors here for media that doesn't have a table of
2795	 * contents.  According to the MMC-3 spec: "When a Read TOC/PMA/ATIP
2796	 * command is presented for a DDCD/CD-R/RW media, where the first TOC
2797	 * has not been recorded (no complete session) and the Format codes
2798	 * 0000b, 0001b, or 0010b are specified, this command shall be rejected
2799	 * with an INVALID FIELD IN CDB.  Devices that are not capable of
2800	 * reading an incomplete session on DDC/CD-R/RW media shall report
2801	 * CANNOT READ MEDIUM - INCOMPATIBLE FORMAT."
2802	 *
2803	 * So this isn't fatal if we can't read the table of contents, it
2804	 * just means that the user won't be able to issue the play tracks
2805	 * ioctl, and likely lots of other stuff won't work either.  They
2806	 * need to burn the CD before we can do a whole lot with it.  So
2807	 * we don't print anything here if we get an error back.
2808	 */
2809	error = cdreadtoc(periph, 0, 0, (u_int8_t *)toch, sizeof(*toch),
2810			  SF_NO_PRINT);
2811	/*
2812	 * Errors in reading the table of contents aren't fatal, we just
2813	 * won't have a valid table of contents cached.
2814	 */
2815	if (error != 0) {
2816		error = 0;
2817		bzero(&softc->toc, sizeof(softc->toc));
2818		goto bailout;
2819	}
2820
2821	if (softc->quirks & CD_Q_BCD_TRACKS) {
2822		toch->starting_track = bcd2bin(toch->starting_track);
2823		toch->ending_track = bcd2bin(toch->ending_track);
2824	}
2825
2826	/* Number of TOC entries, plus leadout */
2827	num_entries = (toch->ending_track - toch->starting_track) + 2;
2828
2829	if (num_entries <= 0)
2830		goto bailout;
2831
2832	toclen = num_entries * sizeof(struct cd_toc_entry);
2833
2834	error = cdreadtoc(periph, CD_MSF_FORMAT, toch->starting_track,
2835			  (u_int8_t *)&softc->toc, toclen + sizeof(*toch),
2836			  SF_NO_PRINT);
2837	if (error != 0) {
2838		error = 0;
2839		bzero(&softc->toc, sizeof(softc->toc));
2840		goto bailout;
2841	}
2842
2843	if (softc->quirks & CD_Q_BCD_TRACKS) {
2844		toch->starting_track = bcd2bin(toch->starting_track);
2845		toch->ending_track = bcd2bin(toch->ending_track);
2846	}
2847	/*
2848	 * XXX KDM is this necessary?  Probably only if the drive doesn't
2849	 * return leadout information with the table of contents.
2850	 */
2851	cdindex = toch->starting_track + num_entries -1;
2852	if (cdindex == toch->ending_track + 1) {
2853
2854		error = cdreadtoc(periph, CD_MSF_FORMAT, LEADOUT,
2855				  (u_int8_t *)&leadout, sizeof(leadout),
2856				  SF_NO_PRINT);
2857		if (error != 0) {
2858			error = 0;
2859			goto bailout;
2860		}
2861		softc->toc.entries[cdindex - toch->starting_track] =
2862			leadout.entry;
2863	}
2864	if (softc->quirks & CD_Q_BCD_TRACKS) {
2865		for (cdindex = 0; cdindex < num_entries - 1; cdindex++) {
2866			softc->toc.entries[cdindex].track =
2867				bcd2bin(softc->toc.entries[cdindex].track);
2868		}
2869	}
2870
2871	softc->flags |= CD_FLAG_VALID_TOC;
2872	softc->disk->d_maxsize = DFLTPHYS;
2873	softc->disk->d_sectorsize = softc->params.blksize;
2874	softc->disk->d_mediasize =
2875	    (off_t)softc->params.blksize * softc->params.disksize;
2876
2877bailout:
2878
2879	/*
2880	 * We unconditionally (re)set the blocksize each time the
2881	 * CD device is opened.  This is because the CD can change,
2882	 * and therefore the blocksize might change.
2883	 * XXX problems here if some slice or partition is still
2884	 * open with the old size?
2885	 */
2886	if ((softc->disk->d_devstat->flags & DEVSTAT_BS_UNAVAILABLE) != 0)
2887		softc->disk->d_devstat->flags &= ~DEVSTAT_BS_UNAVAILABLE;
2888	softc->disk->d_devstat->block_size = softc->params.blksize;
2889
2890	return (error);
2891}
2892
2893static int
2894cdsize(struct cam_periph *periph, u_int32_t *size)
2895{
2896	struct cd_softc *softc;
2897	union ccb *ccb;
2898	struct scsi_read_capacity_data *rcap_buf;
2899	int error;
2900
2901	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdsize\n"));
2902
2903	softc = (struct cd_softc *)periph->softc;
2904
2905	ccb = cdgetccb(periph, /* priority */ 1);
2906
2907	/* XXX Should be M_WAITOK */
2908	rcap_buf = malloc(sizeof(struct scsi_read_capacity_data),
2909			  M_SCSICD, M_NOWAIT);
2910	if (rcap_buf == NULL)
2911		return (ENOMEM);
2912
2913	scsi_read_capacity(&ccb->csio,
2914			   /*retries*/ 1,
2915			   cddone,
2916			   MSG_SIMPLE_Q_TAG,
2917			   rcap_buf,
2918			   SSD_FULL_SIZE,
2919			   /* timeout */20000);
2920
2921	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2922			 /*sense_flags*/SF_RETRY_UA|SF_NO_PRINT);
2923
2924	xpt_release_ccb(ccb);
2925
2926	softc->params.disksize = scsi_4btoul(rcap_buf->addr) + 1;
2927	softc->params.blksize  = scsi_4btoul(rcap_buf->length);
2928	/*
2929	 * SCSI-3 mandates that the reported blocksize shall be 2048.
2930	 * Older drives sometimes report funny values, trim it down to
2931	 * 2048, or other parts of the kernel will get confused.
2932	 *
2933	 * XXX we leave drives alone that might report 512 bytes, as
2934	 * well as drives reporting more weird sizes like perhaps 4K.
2935	 */
2936	if (softc->params.blksize > 2048 && softc->params.blksize <= 2352)
2937		softc->params.blksize = 2048;
2938
2939	free(rcap_buf, M_SCSICD);
2940	*size = softc->params.disksize;
2941
2942	return (error);
2943
2944}
2945
2946static int
2947cd6byteworkaround(union ccb *ccb)
2948{
2949	u_int8_t *cdb;
2950	struct cam_periph *periph;
2951	struct cd_softc *softc;
2952	struct cd_mode_params *params;
2953	int frozen, found;
2954
2955	periph = xpt_path_periph(ccb->ccb_h.path);
2956	softc = (struct cd_softc *)periph->softc;
2957
2958	cdb = ccb->csio.cdb_io.cdb_bytes;
2959
2960	if ((ccb->ccb_h.flags & CAM_CDB_POINTER)
2961	 || ((cdb[0] != MODE_SENSE_6)
2962	  && (cdb[0] != MODE_SELECT_6)))
2963		return (0);
2964
2965	/*
2966	 * Because there is no convenient place to stash the overall
2967	 * cd_mode_params structure pointer, we have to grab it like this.
2968	 * This means that ALL MODE_SENSE and MODE_SELECT requests in the
2969	 * cd(4) driver MUST go through cdgetmode() and cdsetmode()!
2970	 *
2971	 * XXX It would be nice if, at some point, we could increase the
2972	 * number of available peripheral private pointers.  Both pointers
2973	 * are currently used in most every peripheral driver.
2974	 */
2975	found = 0;
2976
2977	STAILQ_FOREACH(params, &softc->mode_queue, links) {
2978		if (params->mode_buf == ccb->csio.data_ptr) {
2979			found = 1;
2980			break;
2981		}
2982	}
2983
2984	/*
2985	 * This shouldn't happen.  All mode sense and mode select
2986	 * operations in the cd(4) driver MUST go through cdgetmode() and
2987	 * cdsetmode()!
2988	 */
2989	if (found == 0) {
2990		xpt_print(periph->path,
2991		    "mode buffer not found in mode queue!\n");
2992		return (0);
2993	}
2994
2995	params->cdb_size = 10;
2996	softc->minimum_command_size = 10;
2997	xpt_print(ccb->ccb_h.path,
2998	    "%s(6) failed, increasing minimum CDB size to 10 bytes\n",
2999	    (cdb[0] == MODE_SENSE_6) ? "MODE_SENSE" : "MODE_SELECT");
3000
3001	if (cdb[0] == MODE_SENSE_6) {
3002		struct scsi_mode_sense_10 ms10;
3003		struct scsi_mode_sense_6 *ms6;
3004		int len;
3005
3006		ms6 = (struct scsi_mode_sense_6 *)cdb;
3007
3008		bzero(&ms10, sizeof(ms10));
3009 		ms10.opcode = MODE_SENSE_10;
3010 		ms10.byte2 = ms6->byte2;
3011 		ms10.page = ms6->page;
3012
3013		/*
3014		 * 10 byte mode header, block descriptor,
3015		 * sizeof(union cd_pages)
3016		 */
3017		len = sizeof(struct cd_mode_data_10);
3018		ccb->csio.dxfer_len = len;
3019
3020		scsi_ulto2b(len, ms10.length);
3021		ms10.control = ms6->control;
3022		bcopy(&ms10, cdb, 10);
3023		ccb->csio.cdb_len = 10;
3024	} else {
3025		struct scsi_mode_select_10 ms10;
3026		struct scsi_mode_select_6 *ms6;
3027		struct scsi_mode_header_6 *header6;
3028		struct scsi_mode_header_10 *header10;
3029		struct scsi_mode_page_header *page_header;
3030		int blk_desc_len, page_num, page_size, len;
3031
3032		ms6 = (struct scsi_mode_select_6 *)cdb;
3033
3034		bzero(&ms10, sizeof(ms10));
3035		ms10.opcode = MODE_SELECT_10;
3036		ms10.byte2 = ms6->byte2;
3037
3038		header6 = (struct scsi_mode_header_6 *)params->mode_buf;
3039		header10 = (struct scsi_mode_header_10 *)params->mode_buf;
3040
3041		page_header = find_mode_page_6(header6);
3042		page_num = page_header->page_code;
3043
3044		blk_desc_len = header6->blk_desc_len;
3045
3046		page_size = cdgetpagesize(page_num);
3047
3048		if (page_size != (page_header->page_length +
3049		    sizeof(*page_header)))
3050			page_size = page_header->page_length +
3051				sizeof(*page_header);
3052
3053		len = sizeof(*header10) + blk_desc_len + page_size;
3054
3055		len = min(params->alloc_len, len);
3056
3057		/*
3058		 * Since the 6 byte parameter header is shorter than the 10
3059		 * byte parameter header, we need to copy the actual mode
3060		 * page data, and the block descriptor, if any, so things wind
3061		 * up in the right place.  The regions will overlap, but
3062		 * bcopy() does the right thing.
3063		 */
3064		bcopy(params->mode_buf + sizeof(*header6),
3065		      params->mode_buf + sizeof(*header10),
3066		      len - sizeof(*header10));
3067
3068		/* Make sure these fields are set correctly. */
3069		scsi_ulto2b(0, header10->data_length);
3070		header10->medium_type = 0;
3071		scsi_ulto2b(blk_desc_len, header10->blk_desc_len);
3072
3073		ccb->csio.dxfer_len = len;
3074
3075		scsi_ulto2b(len, ms10.length);
3076		ms10.control = ms6->control;
3077		bcopy(&ms10, cdb, 10);
3078		ccb->csio.cdb_len = 10;
3079	}
3080
3081	frozen = (ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
3082	ccb->ccb_h.status = CAM_REQUEUE_REQ;
3083	xpt_action(ccb);
3084	if (frozen) {
3085		cam_release_devq(ccb->ccb_h.path,
3086				 /*relsim_flags*/0,
3087				 /*openings*/0,
3088				 /*timeout*/0,
3089				 /*getcount_only*/0);
3090	}
3091
3092	return (ERESTART);
3093}
3094
3095static int
3096cderror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
3097{
3098	struct cd_softc *softc;
3099	struct cam_periph *periph;
3100	int error;
3101
3102	periph = xpt_path_periph(ccb->ccb_h.path);
3103	softc = (struct cd_softc *)periph->softc;
3104
3105	error = 0;
3106
3107	/*
3108	 * We use a status of CAM_REQ_INVALID as shorthand -- if a 6 byte
3109	 * CDB comes back with this particular error, try transforming it
3110	 * into the 10 byte version.
3111	 */
3112	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INVALID) {
3113		error = cd6byteworkaround(ccb);
3114	} else if (((ccb->ccb_h.status & CAM_STATUS_MASK) ==
3115		     CAM_SCSI_STATUS_ERROR)
3116	 && (ccb->ccb_h.status & CAM_AUTOSNS_VALID)
3117	 && (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND)
3118	 && ((ccb->ccb_h.flags & CAM_SENSE_PHYS) == 0)
3119	 && ((ccb->ccb_h.flags & CAM_SENSE_PTR) == 0)) {
3120		int sense_key, error_code, asc, ascq;
3121
3122 		scsi_extract_sense(&ccb->csio.sense_data,
3123				   &error_code, &sense_key, &asc, &ascq);
3124		if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
3125 			error = cd6byteworkaround(ccb);
3126	}
3127
3128	if (error == ERESTART)
3129		return (error);
3130
3131	/*
3132	 * XXX
3133	 * Until we have a better way of doing pack validation,
3134	 * don't treat UAs as errors.
3135	 */
3136	sense_flags |= SF_RETRY_UA;
3137	return (cam_periph_error(ccb, cam_flags, sense_flags,
3138				 &softc->saved_ccb));
3139}
3140
3141/*
3142 * Read table of contents
3143 */
3144static int
3145cdreadtoc(struct cam_periph *periph, u_int32_t mode, u_int32_t start,
3146	  u_int8_t *data, u_int32_t len, u_int32_t sense_flags)
3147{
3148	struct scsi_read_toc *scsi_cmd;
3149	u_int32_t ntoc;
3150        struct ccb_scsiio *csio;
3151	union ccb *ccb;
3152	int error;
3153
3154	ntoc = len;
3155	error = 0;
3156
3157	ccb = cdgetccb(periph, /* priority */ 1);
3158
3159	csio = &ccb->csio;
3160
3161	cam_fill_csio(csio,
3162		      /* retries */ 1,
3163		      /* cbfcnp */ cddone,
3164		      /* flags */ CAM_DIR_IN,
3165		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3166		      /* data_ptr */ data,
3167		      /* dxfer_len */ len,
3168		      /* sense_len */ SSD_FULL_SIZE,
3169		      sizeof(struct scsi_read_toc),
3170 		      /* timeout */ 50000);
3171
3172	scsi_cmd = (struct scsi_read_toc *)&csio->cdb_io.cdb_bytes;
3173	bzero (scsi_cmd, sizeof(*scsi_cmd));
3174
3175	if (mode == CD_MSF_FORMAT)
3176		scsi_cmd->byte2 |= CD_MSF;
3177	scsi_cmd->from_track = start;
3178	/* scsi_ulto2b(ntoc, (u_int8_t *)scsi_cmd->data_len); */
3179	scsi_cmd->data_len[0] = (ntoc) >> 8;
3180	scsi_cmd->data_len[1] = (ntoc) & 0xff;
3181
3182	scsi_cmd->op_code = READ_TOC;
3183
3184	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3185			 /*sense_flags*/SF_RETRY_UA | sense_flags);
3186
3187	xpt_release_ccb(ccb);
3188
3189	return(error);
3190}
3191
3192static int
3193cdreadsubchannel(struct cam_periph *periph, u_int32_t mode,
3194		 u_int32_t format, int track,
3195		 struct cd_sub_channel_info *data, u_int32_t len)
3196{
3197	struct scsi_read_subchannel *scsi_cmd;
3198        struct ccb_scsiio *csio;
3199	union ccb *ccb;
3200	int error;
3201
3202	error = 0;
3203
3204	ccb = cdgetccb(periph, /* priority */ 1);
3205
3206	csio = &ccb->csio;
3207
3208	cam_fill_csio(csio,
3209		      /* retries */ 1,
3210		      /* cbfcnp */ cddone,
3211		      /* flags */ CAM_DIR_IN,
3212		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3213		      /* data_ptr */ (u_int8_t *)data,
3214		      /* dxfer_len */ len,
3215		      /* sense_len */ SSD_FULL_SIZE,
3216		      sizeof(struct scsi_read_subchannel),
3217 		      /* timeout */ 50000);
3218
3219	scsi_cmd = (struct scsi_read_subchannel *)&csio->cdb_io.cdb_bytes;
3220	bzero (scsi_cmd, sizeof(*scsi_cmd));
3221
3222	scsi_cmd->op_code = READ_SUBCHANNEL;
3223	if (mode == CD_MSF_FORMAT)
3224		scsi_cmd->byte1 |= CD_MSF;
3225	scsi_cmd->byte2 = SRS_SUBQ;
3226	scsi_cmd->subchan_format = format;
3227	scsi_cmd->track = track;
3228	scsi_ulto2b(len, (u_int8_t *)scsi_cmd->data_len);
3229	scsi_cmd->control = 0;
3230
3231	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3232			 /*sense_flags*/SF_RETRY_UA);
3233
3234	xpt_release_ccb(ccb);
3235
3236	return(error);
3237}
3238
3239
3240/*
3241 * All MODE_SENSE requests in the cd(4) driver MUST go through this
3242 * routine.  See comments in cd6byteworkaround() for details.
3243 */
3244static int
3245cdgetmode(struct cam_periph *periph, struct cd_mode_params *data,
3246	  u_int32_t page)
3247{
3248	struct ccb_scsiio *csio;
3249	struct cd_softc *softc;
3250	union ccb *ccb;
3251	int param_len;
3252	int error;
3253
3254	softc = (struct cd_softc *)periph->softc;
3255
3256	ccb = cdgetccb(periph, /* priority */ 1);
3257
3258	csio = &ccb->csio;
3259
3260	data->cdb_size = softc->minimum_command_size;
3261	if (data->cdb_size < 10)
3262		param_len = sizeof(struct cd_mode_data);
3263	else
3264		param_len = sizeof(struct cd_mode_data_10);
3265
3266	/* Don't say we've got more room than we actually allocated */
3267	param_len = min(param_len, data->alloc_len);
3268
3269	scsi_mode_sense_len(csio,
3270			    /* retries */ 1,
3271			    /* cbfcnp */ cddone,
3272			    /* tag_action */ MSG_SIMPLE_Q_TAG,
3273			    /* dbd */ 0,
3274			    /* page_code */ SMS_PAGE_CTRL_CURRENT,
3275			    /* page */ page,
3276			    /* param_buf */ data->mode_buf,
3277			    /* param_len */ param_len,
3278			    /* minimum_cmd_size */ softc->minimum_command_size,
3279			    /* sense_len */ SSD_FULL_SIZE,
3280			    /* timeout */ 50000);
3281
3282	/*
3283	 * It would be nice not to have to do this, but there's no
3284	 * available pointer in the CCB that would allow us to stuff the
3285	 * mode params structure in there and retrieve it in
3286	 * cd6byteworkaround(), so we can set the cdb size.  The cdb size
3287	 * lets the caller know what CDB size we ended up using, so they
3288	 * can find the actual mode page offset.
3289	 */
3290	STAILQ_INSERT_TAIL(&softc->mode_queue, data, links);
3291
3292	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3293			 /*sense_flags*/SF_RETRY_UA);
3294
3295	xpt_release_ccb(ccb);
3296
3297	STAILQ_REMOVE(&softc->mode_queue, data, cd_mode_params, links);
3298
3299	/*
3300	 * This is a bit of belt-and-suspenders checking, but if we run
3301	 * into a situation where the target sends back multiple block
3302	 * descriptors, we might not have enough space in the buffer to
3303	 * see the whole mode page.  Better to return an error than
3304	 * potentially access memory beyond our malloced region.
3305	 */
3306	if (error == 0) {
3307		u_int32_t data_len;
3308
3309		if (data->cdb_size == 10) {
3310			struct scsi_mode_header_10 *hdr10;
3311
3312			hdr10 = (struct scsi_mode_header_10 *)data->mode_buf;
3313			data_len = scsi_2btoul(hdr10->data_length);
3314			data_len += sizeof(hdr10->data_length);
3315		} else {
3316			struct scsi_mode_header_6 *hdr6;
3317
3318			hdr6 = (struct scsi_mode_header_6 *)data->mode_buf;
3319			data_len = hdr6->data_length;
3320			data_len += sizeof(hdr6->data_length);
3321		}
3322
3323		/*
3324		 * Complain if there is more mode data available than we
3325		 * allocated space for.  This could potentially happen if
3326		 * we miscalculated the page length for some reason, if the
3327		 * drive returns multiple block descriptors, or if it sets
3328		 * the data length incorrectly.
3329		 */
3330		if (data_len > data->alloc_len) {
3331			xpt_print(periph->path, "allocated modepage %d length "
3332			    "%d < returned length %d\n", page, data->alloc_len,
3333			    data_len);
3334			error = ENOSPC;
3335		}
3336	}
3337	return (error);
3338}
3339
3340/*
3341 * All MODE_SELECT requests in the cd(4) driver MUST go through this
3342 * routine.  See comments in cd6byteworkaround() for details.
3343 */
3344static int
3345cdsetmode(struct cam_periph *periph, struct cd_mode_params *data)
3346{
3347	struct ccb_scsiio *csio;
3348	struct cd_softc *softc;
3349	union ccb *ccb;
3350	int cdb_size, param_len;
3351	int error;
3352
3353	softc = (struct cd_softc *)periph->softc;
3354
3355	ccb = cdgetccb(periph, /* priority */ 1);
3356
3357	csio = &ccb->csio;
3358
3359	error = 0;
3360
3361	/*
3362	 * If the data is formatted for the 10 byte version of the mode
3363	 * select parameter list, we need to use the 10 byte CDB.
3364	 * Otherwise, we use whatever the stored minimum command size.
3365	 */
3366	if (data->cdb_size == 10)
3367		cdb_size = data->cdb_size;
3368	else
3369		cdb_size = softc->minimum_command_size;
3370
3371	if (cdb_size >= 10) {
3372		struct scsi_mode_header_10 *mode_header;
3373		u_int32_t data_len;
3374
3375		mode_header = (struct scsi_mode_header_10 *)data->mode_buf;
3376
3377		data_len = scsi_2btoul(mode_header->data_length);
3378
3379		scsi_ulto2b(0, mode_header->data_length);
3380		/*
3381		 * SONY drives do not allow a mode select with a medium_type
3382		 * value that has just been returned by a mode sense; use a
3383		 * medium_type of 0 (Default) instead.
3384		 */
3385		mode_header->medium_type = 0;
3386
3387		/*
3388		 * Pass back whatever the drive passed to us, plus the size
3389		 * of the data length field.
3390		 */
3391		param_len = data_len + sizeof(mode_header->data_length);
3392
3393	} else {
3394		struct scsi_mode_header_6 *mode_header;
3395
3396		mode_header = (struct scsi_mode_header_6 *)data->mode_buf;
3397
3398		param_len = mode_header->data_length + 1;
3399
3400		mode_header->data_length = 0;
3401		/*
3402		 * SONY drives do not allow a mode select with a medium_type
3403		 * value that has just been returned by a mode sense; use a
3404		 * medium_type of 0 (Default) instead.
3405		 */
3406		mode_header->medium_type = 0;
3407	}
3408
3409	/* Don't say we've got more room than we actually allocated */
3410	param_len = min(param_len, data->alloc_len);
3411
3412	scsi_mode_select_len(csio,
3413			     /* retries */ 1,
3414			     /* cbfcnp */ cddone,
3415			     /* tag_action */ MSG_SIMPLE_Q_TAG,
3416			     /* scsi_page_fmt */ 1,
3417			     /* save_pages */ 0,
3418			     /* param_buf */ data->mode_buf,
3419			     /* param_len */ param_len,
3420			     /* minimum_cmd_size */ cdb_size,
3421			     /* sense_len */ SSD_FULL_SIZE,
3422			     /* timeout */ 50000);
3423
3424	/* See comments in cdgetmode() and cd6byteworkaround(). */
3425	STAILQ_INSERT_TAIL(&softc->mode_queue, data, links);
3426
3427	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3428			 /*sense_flags*/SF_RETRY_UA);
3429
3430	xpt_release_ccb(ccb);
3431
3432	STAILQ_REMOVE(&softc->mode_queue, data, cd_mode_params, links);
3433
3434	return (error);
3435}
3436
3437
3438static int
3439cdplay(struct cam_periph *periph, u_int32_t blk, u_int32_t len)
3440{
3441	struct ccb_scsiio *csio;
3442	union ccb *ccb;
3443	int error;
3444	u_int8_t cdb_len;
3445
3446	error = 0;
3447	ccb = cdgetccb(periph, /* priority */ 1);
3448	csio = &ccb->csio;
3449	/*
3450	 * Use the smallest possible command to perform the operation.
3451	 */
3452	if ((len & 0xffff0000) == 0) {
3453		/*
3454		 * We can fit in a 10 byte cdb.
3455		 */
3456		struct scsi_play_10 *scsi_cmd;
3457
3458		scsi_cmd = (struct scsi_play_10 *)&csio->cdb_io.cdb_bytes;
3459		bzero (scsi_cmd, sizeof(*scsi_cmd));
3460		scsi_cmd->op_code = PLAY_10;
3461		scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
3462		scsi_ulto2b(len, (u_int8_t *)scsi_cmd->xfer_len);
3463		cdb_len = sizeof(*scsi_cmd);
3464	} else  {
3465		struct scsi_play_12 *scsi_cmd;
3466
3467		scsi_cmd = (struct scsi_play_12 *)&csio->cdb_io.cdb_bytes;
3468		bzero (scsi_cmd, sizeof(*scsi_cmd));
3469		scsi_cmd->op_code = PLAY_12;
3470		scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
3471		scsi_ulto4b(len, (u_int8_t *)scsi_cmd->xfer_len);
3472		cdb_len = sizeof(*scsi_cmd);
3473	}
3474	cam_fill_csio(csio,
3475		      /*retries*/2,
3476		      cddone,
3477		      /*flags*/CAM_DIR_NONE,
3478		      MSG_SIMPLE_Q_TAG,
3479		      /*dataptr*/NULL,
3480		      /*datalen*/0,
3481		      /*sense_len*/SSD_FULL_SIZE,
3482		      cdb_len,
3483		      /*timeout*/50 * 1000);
3484
3485	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3486			 /*sense_flags*/SF_RETRY_UA);
3487
3488	xpt_release_ccb(ccb);
3489
3490	return(error);
3491}
3492
3493static int
3494cdplaymsf(struct cam_periph *periph, u_int32_t startm, u_int32_t starts,
3495	  u_int32_t startf, u_int32_t endm, u_int32_t ends, u_int32_t endf)
3496{
3497	struct scsi_play_msf *scsi_cmd;
3498        struct ccb_scsiio *csio;
3499	union ccb *ccb;
3500	int error;
3501
3502	error = 0;
3503
3504	ccb = cdgetccb(periph, /* priority */ 1);
3505
3506	csio = &ccb->csio;
3507
3508	cam_fill_csio(csio,
3509		      /* retries */ 1,
3510		      /* cbfcnp */ cddone,
3511		      /* flags */ CAM_DIR_NONE,
3512		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3513		      /* data_ptr */ NULL,
3514		      /* dxfer_len */ 0,
3515		      /* sense_len */ SSD_FULL_SIZE,
3516		      sizeof(struct scsi_play_msf),
3517 		      /* timeout */ 50000);
3518
3519	scsi_cmd = (struct scsi_play_msf *)&csio->cdb_io.cdb_bytes;
3520	bzero (scsi_cmd, sizeof(*scsi_cmd));
3521
3522        scsi_cmd->op_code = PLAY_MSF;
3523        scsi_cmd->start_m = startm;
3524        scsi_cmd->start_s = starts;
3525        scsi_cmd->start_f = startf;
3526        scsi_cmd->end_m = endm;
3527        scsi_cmd->end_s = ends;
3528        scsi_cmd->end_f = endf;
3529
3530	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3531			 /*sense_flags*/SF_RETRY_UA);
3532
3533	xpt_release_ccb(ccb);
3534
3535	return(error);
3536}
3537
3538
3539static int
3540cdplaytracks(struct cam_periph *periph, u_int32_t strack, u_int32_t sindex,
3541	     u_int32_t etrack, u_int32_t eindex)
3542{
3543	struct scsi_play_track *scsi_cmd;
3544        struct ccb_scsiio *csio;
3545	union ccb *ccb;
3546	int error;
3547
3548	error = 0;
3549
3550	ccb = cdgetccb(periph, /* priority */ 1);
3551
3552	csio = &ccb->csio;
3553
3554	cam_fill_csio(csio,
3555		      /* retries */ 1,
3556		      /* cbfcnp */ cddone,
3557		      /* flags */ CAM_DIR_NONE,
3558		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3559		      /* data_ptr */ NULL,
3560		      /* dxfer_len */ 0,
3561		      /* sense_len */ SSD_FULL_SIZE,
3562		      sizeof(struct scsi_play_track),
3563 		      /* timeout */ 50000);
3564
3565	scsi_cmd = (struct scsi_play_track *)&csio->cdb_io.cdb_bytes;
3566	bzero (scsi_cmd, sizeof(*scsi_cmd));
3567
3568        scsi_cmd->op_code = PLAY_TRACK;
3569        scsi_cmd->start_track = strack;
3570        scsi_cmd->start_index = sindex;
3571        scsi_cmd->end_track = etrack;
3572        scsi_cmd->end_index = eindex;
3573
3574	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3575			 /*sense_flags*/SF_RETRY_UA);
3576
3577	xpt_release_ccb(ccb);
3578
3579	return(error);
3580}
3581
3582static int
3583cdpause(struct cam_periph *periph, u_int32_t go)
3584{
3585	struct scsi_pause *scsi_cmd;
3586        struct ccb_scsiio *csio;
3587	union ccb *ccb;
3588	int error;
3589
3590	error = 0;
3591
3592	ccb = cdgetccb(periph, /* priority */ 1);
3593
3594	csio = &ccb->csio;
3595
3596	cam_fill_csio(csio,
3597		      /* retries */ 1,
3598		      /* cbfcnp */ cddone,
3599		      /* flags */ CAM_DIR_NONE,
3600		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3601		      /* data_ptr */ NULL,
3602		      /* dxfer_len */ 0,
3603		      /* sense_len */ SSD_FULL_SIZE,
3604		      sizeof(struct scsi_pause),
3605 		      /* timeout */ 50000);
3606
3607	scsi_cmd = (struct scsi_pause *)&csio->cdb_io.cdb_bytes;
3608	bzero (scsi_cmd, sizeof(*scsi_cmd));
3609
3610        scsi_cmd->op_code = PAUSE;
3611	scsi_cmd->resume = go;
3612
3613	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3614			 /*sense_flags*/SF_RETRY_UA);
3615
3616	xpt_release_ccb(ccb);
3617
3618	return(error);
3619}
3620
3621static int
3622cdstartunit(struct cam_periph *periph, int load)
3623{
3624	union ccb *ccb;
3625	int error;
3626
3627	error = 0;
3628
3629	ccb = cdgetccb(periph, /* priority */ 1);
3630
3631	scsi_start_stop(&ccb->csio,
3632			/* retries */ 1,
3633			/* cbfcnp */ cddone,
3634			/* tag_action */ MSG_SIMPLE_Q_TAG,
3635			/* start */ TRUE,
3636			/* load_eject */ load,
3637			/* immediate */ FALSE,
3638			/* sense_len */ SSD_FULL_SIZE,
3639			/* timeout */ 50000);
3640
3641	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3642			 /*sense_flags*/SF_RETRY_UA);
3643
3644	xpt_release_ccb(ccb);
3645
3646	return(error);
3647}
3648
3649static int
3650cdstopunit(struct cam_periph *periph, u_int32_t eject)
3651{
3652	union ccb *ccb;
3653	int error;
3654
3655	error = 0;
3656
3657	ccb = cdgetccb(periph, /* priority */ 1);
3658
3659	scsi_start_stop(&ccb->csio,
3660			/* retries */ 1,
3661			/* cbfcnp */ cddone,
3662			/* tag_action */ MSG_SIMPLE_Q_TAG,
3663			/* start */ FALSE,
3664			/* load_eject */ eject,
3665			/* immediate */ FALSE,
3666			/* sense_len */ SSD_FULL_SIZE,
3667			/* timeout */ 50000);
3668
3669	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3670			 /*sense_flags*/SF_RETRY_UA);
3671
3672	xpt_release_ccb(ccb);
3673
3674	return(error);
3675}
3676
3677static int
3678cdsetspeed(struct cam_periph *periph, u_int32_t rdspeed, u_int32_t wrspeed)
3679{
3680	struct scsi_set_speed *scsi_cmd;
3681	struct ccb_scsiio *csio;
3682	union ccb *ccb;
3683	int error;
3684
3685	error = 0;
3686	ccb = cdgetccb(periph, /* priority */ 1);
3687	csio = &ccb->csio;
3688
3689	/* Preserve old behavior: units in multiples of CDROM speed */
3690	if (rdspeed < 177)
3691		rdspeed *= 177;
3692	if (wrspeed < 177)
3693		wrspeed *= 177;
3694
3695	cam_fill_csio(csio,
3696		      /* retries */ 1,
3697		      /* cbfcnp */ cddone,
3698		      /* flags */ CAM_DIR_NONE,
3699		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3700		      /* data_ptr */ NULL,
3701		      /* dxfer_len */ 0,
3702		      /* sense_len */ SSD_FULL_SIZE,
3703		      sizeof(struct scsi_set_speed),
3704 		      /* timeout */ 50000);
3705
3706	scsi_cmd = (struct scsi_set_speed *)&csio->cdb_io.cdb_bytes;
3707	bzero(scsi_cmd, sizeof(*scsi_cmd));
3708
3709	scsi_cmd->opcode = SET_CD_SPEED;
3710	scsi_ulto2b(rdspeed, scsi_cmd->readspeed);
3711	scsi_ulto2b(wrspeed, scsi_cmd->writespeed);
3712
3713	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3714			 /*sense_flags*/SF_RETRY_UA);
3715
3716	xpt_release_ccb(ccb);
3717
3718	return(error);
3719}
3720
3721static int
3722cdreportkey(struct cam_periph *periph, struct dvd_authinfo *authinfo)
3723{
3724	union ccb *ccb;
3725	u_int8_t *databuf;
3726	u_int32_t lba;
3727	int error;
3728	int length;
3729
3730	error = 0;
3731	databuf = NULL;
3732	lba = 0;
3733
3734	ccb = cdgetccb(periph, /* priority */ 1);
3735
3736	switch (authinfo->format) {
3737	case DVD_REPORT_AGID:
3738		length = sizeof(struct scsi_report_key_data_agid);
3739		break;
3740	case DVD_REPORT_CHALLENGE:
3741		length = sizeof(struct scsi_report_key_data_challenge);
3742		break;
3743	case DVD_REPORT_KEY1:
3744		length = sizeof(struct scsi_report_key_data_key1_key2);
3745		break;
3746	case DVD_REPORT_TITLE_KEY:
3747		length = sizeof(struct scsi_report_key_data_title);
3748		/* The lba field is only set for the title key */
3749		lba = authinfo->lba;
3750		break;
3751	case DVD_REPORT_ASF:
3752		length = sizeof(struct scsi_report_key_data_asf);
3753		break;
3754	case DVD_REPORT_RPC:
3755		length = sizeof(struct scsi_report_key_data_rpc);
3756		break;
3757	case DVD_INVALIDATE_AGID:
3758		length = 0;
3759		break;
3760	default:
3761		error = EINVAL;
3762		goto bailout;
3763		break; /* NOTREACHED */
3764	}
3765
3766	if (length != 0) {
3767		databuf = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3768	} else
3769		databuf = NULL;
3770
3771
3772	scsi_report_key(&ccb->csio,
3773			/* retries */ 1,
3774			/* cbfcnp */ cddone,
3775			/* tag_action */ MSG_SIMPLE_Q_TAG,
3776			/* lba */ lba,
3777			/* agid */ authinfo->agid,
3778			/* key_format */ authinfo->format,
3779			/* data_ptr */ databuf,
3780			/* dxfer_len */ length,
3781			/* sense_len */ SSD_FULL_SIZE,
3782			/* timeout */ 50000);
3783
3784	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3785			 /*sense_flags*/SF_RETRY_UA);
3786
3787	if (error != 0)
3788		goto bailout;
3789
3790	if (ccb->csio.resid != 0) {
3791		xpt_print(periph->path, "warning, residual for report key "
3792		    "command is %d\n", ccb->csio.resid);
3793	}
3794
3795	switch(authinfo->format) {
3796	case DVD_REPORT_AGID: {
3797		struct scsi_report_key_data_agid *agid_data;
3798
3799		agid_data = (struct scsi_report_key_data_agid *)databuf;
3800
3801		authinfo->agid = (agid_data->agid & RKD_AGID_MASK) >>
3802			RKD_AGID_SHIFT;
3803		break;
3804	}
3805	case DVD_REPORT_CHALLENGE: {
3806		struct scsi_report_key_data_challenge *chal_data;
3807
3808		chal_data = (struct scsi_report_key_data_challenge *)databuf;
3809
3810		bcopy(chal_data->challenge_key, authinfo->keychal,
3811		      min(sizeof(chal_data->challenge_key),
3812		          sizeof(authinfo->keychal)));
3813		break;
3814	}
3815	case DVD_REPORT_KEY1: {
3816		struct scsi_report_key_data_key1_key2 *key1_data;
3817
3818		key1_data = (struct scsi_report_key_data_key1_key2 *)databuf;
3819
3820		bcopy(key1_data->key1, authinfo->keychal,
3821		      min(sizeof(key1_data->key1), sizeof(authinfo->keychal)));
3822		break;
3823	}
3824	case DVD_REPORT_TITLE_KEY: {
3825		struct scsi_report_key_data_title *title_data;
3826
3827		title_data = (struct scsi_report_key_data_title *)databuf;
3828
3829		authinfo->cpm = (title_data->byte0 & RKD_TITLE_CPM) >>
3830			RKD_TITLE_CPM_SHIFT;
3831		authinfo->cp_sec = (title_data->byte0 & RKD_TITLE_CP_SEC) >>
3832			RKD_TITLE_CP_SEC_SHIFT;
3833		authinfo->cgms = (title_data->byte0 & RKD_TITLE_CMGS_MASK) >>
3834			RKD_TITLE_CMGS_SHIFT;
3835		bcopy(title_data->title_key, authinfo->keychal,
3836		      min(sizeof(title_data->title_key),
3837			  sizeof(authinfo->keychal)));
3838		break;
3839	}
3840	case DVD_REPORT_ASF: {
3841		struct scsi_report_key_data_asf *asf_data;
3842
3843		asf_data = (struct scsi_report_key_data_asf *)databuf;
3844
3845		authinfo->asf = asf_data->success & RKD_ASF_SUCCESS;
3846		break;
3847	}
3848	case DVD_REPORT_RPC: {
3849		struct scsi_report_key_data_rpc *rpc_data;
3850
3851		rpc_data = (struct scsi_report_key_data_rpc *)databuf;
3852
3853		authinfo->reg_type = (rpc_data->byte4 & RKD_RPC_TYPE_MASK) >>
3854			RKD_RPC_TYPE_SHIFT;
3855		authinfo->vend_rsts =
3856			(rpc_data->byte4 & RKD_RPC_VENDOR_RESET_MASK) >>
3857			RKD_RPC_VENDOR_RESET_SHIFT;
3858		authinfo->user_rsts = rpc_data->byte4 & RKD_RPC_USER_RESET_MASK;
3859		authinfo->region = rpc_data->region_mask;
3860		authinfo->rpc_scheme = rpc_data->rpc_scheme1;
3861		break;
3862	}
3863	case DVD_INVALIDATE_AGID:
3864		break;
3865	default:
3866		/* This should be impossible, since we checked above */
3867		error = EINVAL;
3868		goto bailout;
3869		break; /* NOTREACHED */
3870	}
3871bailout:
3872	if (databuf != NULL)
3873		free(databuf, M_DEVBUF);
3874
3875	xpt_release_ccb(ccb);
3876
3877	return(error);
3878}
3879
3880static int
3881cdsendkey(struct cam_periph *periph, struct dvd_authinfo *authinfo)
3882{
3883	union ccb *ccb;
3884	u_int8_t *databuf;
3885	int length;
3886	int error;
3887
3888	error = 0;
3889	databuf = NULL;
3890
3891	ccb = cdgetccb(periph, /* priority */ 1);
3892
3893	switch(authinfo->format) {
3894	case DVD_SEND_CHALLENGE: {
3895		struct scsi_report_key_data_challenge *challenge_data;
3896
3897		length = sizeof(*challenge_data);
3898
3899		challenge_data = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3900
3901		databuf = (u_int8_t *)challenge_data;
3902
3903		scsi_ulto2b(length - sizeof(challenge_data->data_len),
3904			    challenge_data->data_len);
3905
3906		bcopy(authinfo->keychal, challenge_data->challenge_key,
3907		      min(sizeof(authinfo->keychal),
3908			  sizeof(challenge_data->challenge_key)));
3909		break;
3910	}
3911	case DVD_SEND_KEY2: {
3912		struct scsi_report_key_data_key1_key2 *key2_data;
3913
3914		length = sizeof(*key2_data);
3915
3916		key2_data = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3917
3918		databuf = (u_int8_t *)key2_data;
3919
3920		scsi_ulto2b(length - sizeof(key2_data->data_len),
3921			    key2_data->data_len);
3922
3923		bcopy(authinfo->keychal, key2_data->key1,
3924		      min(sizeof(authinfo->keychal), sizeof(key2_data->key1)));
3925
3926		break;
3927	}
3928	case DVD_SEND_RPC: {
3929		struct scsi_send_key_data_rpc *rpc_data;
3930
3931		length = sizeof(*rpc_data);
3932
3933		rpc_data = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3934
3935		databuf = (u_int8_t *)rpc_data;
3936
3937		scsi_ulto2b(length - sizeof(rpc_data->data_len),
3938			    rpc_data->data_len);
3939
3940		rpc_data->region_code = authinfo->region;
3941		break;
3942	}
3943	default:
3944		error = EINVAL;
3945		goto bailout;
3946		break; /* NOTREACHED */
3947	}
3948
3949	scsi_send_key(&ccb->csio,
3950		      /* retries */ 1,
3951		      /* cbfcnp */ cddone,
3952		      /* tag_action */ MSG_SIMPLE_Q_TAG,
3953		      /* agid */ authinfo->agid,
3954		      /* key_format */ authinfo->format,
3955		      /* data_ptr */ databuf,
3956		      /* dxfer_len */ length,
3957		      /* sense_len */ SSD_FULL_SIZE,
3958		      /* timeout */ 50000);
3959
3960	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3961			 /*sense_flags*/SF_RETRY_UA);
3962
3963bailout:
3964
3965	if (databuf != NULL)
3966		free(databuf, M_DEVBUF);
3967
3968	xpt_release_ccb(ccb);
3969
3970	return(error);
3971}
3972
3973static int
3974cdreaddvdstructure(struct cam_periph *periph, struct dvd_struct *dvdstruct)
3975{
3976	union ccb *ccb;
3977	u_int8_t *databuf;
3978	u_int32_t address;
3979	int error;
3980	int length;
3981
3982	error = 0;
3983	databuf = NULL;
3984	/* The address is reserved for many of the formats */
3985	address = 0;
3986
3987	ccb = cdgetccb(periph, /* priority */ 1);
3988
3989	switch(dvdstruct->format) {
3990	case DVD_STRUCT_PHYSICAL:
3991		length = sizeof(struct scsi_read_dvd_struct_data_physical);
3992		break;
3993	case DVD_STRUCT_COPYRIGHT:
3994		length = sizeof(struct scsi_read_dvd_struct_data_copyright);
3995		break;
3996	case DVD_STRUCT_DISCKEY:
3997		length = sizeof(struct scsi_read_dvd_struct_data_disc_key);
3998		break;
3999	case DVD_STRUCT_BCA:
4000		length = sizeof(struct scsi_read_dvd_struct_data_bca);
4001		break;
4002	case DVD_STRUCT_MANUFACT:
4003		length = sizeof(struct scsi_read_dvd_struct_data_manufacturer);
4004		break;
4005	case DVD_STRUCT_CMI:
4006		error = ENODEV;
4007		goto bailout;
4008#ifdef notyet
4009		length = sizeof(struct scsi_read_dvd_struct_data_copy_manage);
4010		address = dvdstruct->address;
4011#endif
4012		break; /* NOTREACHED */
4013	case DVD_STRUCT_PROTDISCID:
4014		length = sizeof(struct scsi_read_dvd_struct_data_prot_discid);
4015		break;
4016	case DVD_STRUCT_DISCKEYBLOCK:
4017		length = sizeof(struct scsi_read_dvd_struct_data_disc_key_blk);
4018		break;
4019	case DVD_STRUCT_DDS:
4020		length = sizeof(struct scsi_read_dvd_struct_data_dds);
4021		break;
4022	case DVD_STRUCT_MEDIUM_STAT:
4023		length = sizeof(struct scsi_read_dvd_struct_data_medium_status);
4024		break;
4025	case DVD_STRUCT_SPARE_AREA:
4026		length = sizeof(struct scsi_read_dvd_struct_data_spare_area);
4027		break;
4028	case DVD_STRUCT_RMD_LAST:
4029		error = ENODEV;
4030		goto bailout;
4031#ifdef notyet
4032		length = sizeof(struct scsi_read_dvd_struct_data_rmd_borderout);
4033		address = dvdstruct->address;
4034#endif
4035		break; /* NOTREACHED */
4036	case DVD_STRUCT_RMD_RMA:
4037		error = ENODEV;
4038		goto bailout;
4039#ifdef notyet
4040		length = sizeof(struct scsi_read_dvd_struct_data_rmd);
4041		address = dvdstruct->address;
4042#endif
4043		break; /* NOTREACHED */
4044	case DVD_STRUCT_PRERECORDED:
4045		length = sizeof(struct scsi_read_dvd_struct_data_leadin);
4046		break;
4047	case DVD_STRUCT_UNIQUEID:
4048		length = sizeof(struct scsi_read_dvd_struct_data_disc_id);
4049		break;
4050	case DVD_STRUCT_DCB:
4051		error = ENODEV;
4052		goto bailout;
4053#ifdef notyet
4054		length = sizeof(struct scsi_read_dvd_struct_data_dcb);
4055		address = dvdstruct->address;
4056#endif
4057		break; /* NOTREACHED */
4058	case DVD_STRUCT_LIST:
4059		/*
4060		 * This is the maximum allocation length for the READ DVD
4061		 * STRUCTURE command.  There's nothing in the MMC3 spec
4062		 * that indicates a limit in the amount of data that can
4063		 * be returned from this call, other than the limits
4064		 * imposed by the 2-byte length variables.
4065		 */
4066		length = 65535;
4067		break;
4068	default:
4069		error = EINVAL;
4070		goto bailout;
4071		break; /* NOTREACHED */
4072	}
4073
4074	if (length != 0) {
4075		databuf = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
4076	} else
4077		databuf = NULL;
4078
4079	scsi_read_dvd_structure(&ccb->csio,
4080				/* retries */ 1,
4081				/* cbfcnp */ cddone,
4082				/* tag_action */ MSG_SIMPLE_Q_TAG,
4083				/* lba */ address,
4084				/* layer_number */ dvdstruct->layer_num,
4085				/* key_format */ dvdstruct->format,
4086				/* agid */ dvdstruct->agid,
4087				/* data_ptr */ databuf,
4088				/* dxfer_len */ length,
4089				/* sense_len */ SSD_FULL_SIZE,
4090				/* timeout */ 50000);
4091
4092	error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
4093			 /*sense_flags*/SF_RETRY_UA);
4094
4095	if (error != 0)
4096		goto bailout;
4097
4098	switch(dvdstruct->format) {
4099	case DVD_STRUCT_PHYSICAL: {
4100		struct scsi_read_dvd_struct_data_layer_desc *inlayer;
4101		struct dvd_layer *outlayer;
4102		struct scsi_read_dvd_struct_data_physical *phys_data;
4103
4104		phys_data =
4105			(struct scsi_read_dvd_struct_data_physical *)databuf;
4106		inlayer = &phys_data->layer_desc;
4107		outlayer = (struct dvd_layer *)&dvdstruct->data;
4108
4109		dvdstruct->length = sizeof(*inlayer);
4110
4111		outlayer->book_type = (inlayer->book_type_version &
4112			RDSD_BOOK_TYPE_MASK) >> RDSD_BOOK_TYPE_SHIFT;
4113		outlayer->book_version = (inlayer->book_type_version &
4114			RDSD_BOOK_VERSION_MASK);
4115		outlayer->disc_size = (inlayer->disc_size_max_rate &
4116			RDSD_DISC_SIZE_MASK) >> RDSD_DISC_SIZE_SHIFT;
4117		outlayer->max_rate = (inlayer->disc_size_max_rate &
4118			RDSD_MAX_RATE_MASK);
4119		outlayer->nlayers = (inlayer->layer_info &
4120			RDSD_NUM_LAYERS_MASK) >> RDSD_NUM_LAYERS_SHIFT;
4121		outlayer->track_path = (inlayer->layer_info &
4122			RDSD_TRACK_PATH_MASK) >> RDSD_TRACK_PATH_SHIFT;
4123		outlayer->layer_type = (inlayer->layer_info &
4124			RDSD_LAYER_TYPE_MASK);
4125		outlayer->linear_density = (inlayer->density &
4126			RDSD_LIN_DENSITY_MASK) >> RDSD_LIN_DENSITY_SHIFT;
4127		outlayer->track_density = (inlayer->density &
4128			RDSD_TRACK_DENSITY_MASK);
4129		outlayer->bca = (inlayer->bca & RDSD_BCA_MASK) >>
4130			RDSD_BCA_SHIFT;
4131		outlayer->start_sector = scsi_3btoul(inlayer->main_data_start);
4132		outlayer->end_sector = scsi_3btoul(inlayer->main_data_end);
4133		outlayer->end_sector_l0 =
4134			scsi_3btoul(inlayer->end_sector_layer0);
4135		break;
4136	}
4137	case DVD_STRUCT_COPYRIGHT: {
4138		struct scsi_read_dvd_struct_data_copyright *copy_data;
4139
4140		copy_data = (struct scsi_read_dvd_struct_data_copyright *)
4141			databuf;
4142
4143		dvdstruct->cpst = copy_data->cps_type;
4144		dvdstruct->rmi = copy_data->region_info;
4145		dvdstruct->length = 0;
4146
4147		break;
4148	}
4149	default:
4150		/*
4151		 * Tell the user what the overall length is, no matter
4152		 * what we can actually fit in the data buffer.
4153		 */
4154		dvdstruct->length = length - ccb->csio.resid -
4155			sizeof(struct scsi_read_dvd_struct_data_header);
4156
4157		/*
4158		 * But only actually copy out the smaller of what we read
4159		 * in or what the structure can take.
4160		 */
4161		bcopy(databuf + sizeof(struct scsi_read_dvd_struct_data_header),
4162		      dvdstruct->data,
4163		      min(sizeof(dvdstruct->data), dvdstruct->length));
4164		break;
4165	}
4166bailout:
4167
4168	if (databuf != NULL)
4169		free(databuf, M_DEVBUF);
4170
4171	xpt_release_ccb(ccb);
4172
4173	return(error);
4174}
4175
4176void
4177scsi_report_key(struct ccb_scsiio *csio, u_int32_t retries,
4178		void (*cbfcnp)(struct cam_periph *, union ccb *),
4179		u_int8_t tag_action, u_int32_t lba, u_int8_t agid,
4180		u_int8_t key_format, u_int8_t *data_ptr, u_int32_t dxfer_len,
4181		u_int8_t sense_len, u_int32_t timeout)
4182{
4183	struct scsi_report_key *scsi_cmd;
4184
4185	scsi_cmd = (struct scsi_report_key *)&csio->cdb_io.cdb_bytes;
4186	bzero(scsi_cmd, sizeof(*scsi_cmd));
4187	scsi_cmd->opcode = REPORT_KEY;
4188	scsi_ulto4b(lba, scsi_cmd->lba);
4189	scsi_ulto2b(dxfer_len, scsi_cmd->alloc_len);
4190	scsi_cmd->agid_keyformat = (agid << RK_KF_AGID_SHIFT) |
4191		(key_format & RK_KF_KEYFORMAT_MASK);
4192
4193	cam_fill_csio(csio,
4194		      retries,
4195		      cbfcnp,
4196		      /*flags*/ (dxfer_len == 0) ? CAM_DIR_NONE : CAM_DIR_IN,
4197		      tag_action,
4198		      /*data_ptr*/ data_ptr,
4199		      /*dxfer_len*/ dxfer_len,
4200		      sense_len,
4201		      sizeof(*scsi_cmd),
4202		      timeout);
4203}
4204
4205void
4206scsi_send_key(struct ccb_scsiio *csio, u_int32_t retries,
4207	      void (*cbfcnp)(struct cam_periph *, union ccb *),
4208	      u_int8_t tag_action, u_int8_t agid, u_int8_t key_format,
4209	      u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
4210	      u_int32_t timeout)
4211{
4212	struct scsi_send_key *scsi_cmd;
4213
4214	scsi_cmd = (struct scsi_send_key *)&csio->cdb_io.cdb_bytes;
4215	bzero(scsi_cmd, sizeof(*scsi_cmd));
4216	scsi_cmd->opcode = SEND_KEY;
4217
4218	scsi_ulto2b(dxfer_len, scsi_cmd->param_len);
4219	scsi_cmd->agid_keyformat = (agid << RK_KF_AGID_SHIFT) |
4220		(key_format & RK_KF_KEYFORMAT_MASK);
4221
4222	cam_fill_csio(csio,
4223		      retries,
4224		      cbfcnp,
4225		      /*flags*/ CAM_DIR_OUT,
4226		      tag_action,
4227		      /*data_ptr*/ data_ptr,
4228		      /*dxfer_len*/ dxfer_len,
4229		      sense_len,
4230		      sizeof(*scsi_cmd),
4231		      timeout);
4232}
4233
4234
4235void
4236scsi_read_dvd_structure(struct ccb_scsiio *csio, u_int32_t retries,
4237			void (*cbfcnp)(struct cam_periph *, union ccb *),
4238			u_int8_t tag_action, u_int32_t address,
4239			u_int8_t layer_number, u_int8_t format, u_int8_t agid,
4240			u_int8_t *data_ptr, u_int32_t dxfer_len,
4241			u_int8_t sense_len, u_int32_t timeout)
4242{
4243	struct scsi_read_dvd_structure *scsi_cmd;
4244
4245	scsi_cmd = (struct scsi_read_dvd_structure *)&csio->cdb_io.cdb_bytes;
4246	bzero(scsi_cmd, sizeof(*scsi_cmd));
4247	scsi_cmd->opcode = READ_DVD_STRUCTURE;
4248
4249	scsi_ulto4b(address, scsi_cmd->address);
4250	scsi_cmd->layer_number = layer_number;
4251	scsi_cmd->format = format;
4252	scsi_ulto2b(dxfer_len, scsi_cmd->alloc_len);
4253	/* The AGID is the top two bits of this byte */
4254	scsi_cmd->agid = agid << 6;
4255
4256	cam_fill_csio(csio,
4257		      retries,
4258		      cbfcnp,
4259		      /*flags*/ CAM_DIR_IN,
4260		      tag_action,
4261		      /*data_ptr*/ data_ptr,
4262		      /*dxfer_len*/ dxfer_len,
4263		      sense_len,
4264		      sizeof(*scsi_cmd),
4265		      timeout);
4266}
4267