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