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