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