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