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