xref: /netbsd-src/sys/dev/scsipi/cd.c (revision a7e090f70e491979434963c9a27df4020fe0a18b)
1 /*	$NetBSD: cd.c,v 1.301 2010/03/23 18:56:18 martin Exp $	*/
2 
3 /*-
4  * Copyright (c) 1998, 2001, 2003, 2004, 2005, 2008 The NetBSD Foundation,
5  * Inc.  All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Charles M. Hannum.
9  *
10  * MMC framework implemented and contributed to the NetBSD Foundation by
11  * Reinoud Zandijk.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 /*
36  * Originally written by Julian Elischer (julian@tfs.com)
37  * for TRW Financial Systems for use under the MACH(2.5) operating system.
38  *
39  * TRW Financial Systems, in accordance with their agreement with Carnegie
40  * Mellon University, makes this software available to CMU to distribute
41  * or use in any manner that they see fit as long as this message is kept with
42  * the software. For this reason TFS also grants any other persons or
43  * organisations permission to use or modify this software.
44  *
45  * TFS supplies this software to be publicly redistributed
46  * on the understanding that TFS is not responsible for the correct
47  * functioning of this software in any circumstances.
48  *
49  * Ported to run under 386BSD by Julian Elischer (julian@tfs.com) Sept 1992
50  */
51 
52 #include <sys/cdefs.h>
53 __KERNEL_RCSID(0, "$NetBSD: cd.c,v 1.301 2010/03/23 18:56:18 martin Exp $");
54 
55 #include "rnd.h"
56 
57 #include <sys/param.h>
58 #include <sys/systm.h>
59 #include <sys/kernel.h>
60 #include <sys/file.h>
61 #include <sys/stat.h>
62 #include <sys/ioctl.h>
63 #include <sys/buf.h>
64 #include <sys/bufq.h>
65 #include <sys/uio.h>
66 #include <sys/malloc.h>
67 #include <sys/errno.h>
68 #include <sys/device.h>
69 #include <sys/disklabel.h>
70 #include <sys/disk.h>
71 #include <sys/cdio.h>
72 #include <sys/dvdio.h>
73 #include <sys/scsiio.h>
74 #include <sys/proc.h>
75 #include <sys/conf.h>
76 #include <sys/vnode.h>
77 #if NRND > 0
78 #include <sys/rnd.h>
79 #endif
80 
81 #include <dev/scsipi/scsi_spc.h>
82 #include <dev/scsipi/scsipi_all.h>
83 #include <dev/scsipi/scsipi_cd.h>
84 #include <dev/scsipi/scsipi_disk.h>	/* rw_big and start_stop come */
85 #include <dev/scsipi/scsi_all.h>
86 					/* from there */
87 #include <dev/scsipi/scsi_disk.h>	/* rw comes from there */
88 #include <dev/scsipi/scsipiconf.h>
89 #include <dev/scsipi/scsipi_base.h>
90 #include <dev/scsipi/cdvar.h>
91 
92 #include <prop/proplib.h>
93 
94 #define	CDUNIT(z)			DISKUNIT(z)
95 #define	CDPART(z)			DISKPART(z)
96 #define	CDMINOR(unit, part)		DISKMINOR(unit, part)
97 #define	MAKECDDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)
98 
99 #define MAXTRACK	99
100 #define CD_BLOCK_OFFSET	150
101 #define CD_FRAMES	75
102 #define CD_SECS		60
103 
104 #define CD_TOC_FORM	0	/* formatted TOC, exposed to userland     */
105 #define CD_TOC_MSINFO	1	/* multi-session info			  */
106 #define CD_TOC_RAW	2	/* raw TOC as on disc, unprocessed	  */
107 #define CD_TOC_PMA	3	/* PMA, used as intermediate (rare use)   */
108 #define CD_TOC_ATIP	4	/* pressed space of recordable		  */
109 #define CD_TOC_CDTEXT	5	/* special CD-TEXT, rarely used		  */
110 
111 #define P5LEN	0x32
112 #define MS5LEN	(P5LEN + 8 + 2)
113 
114 struct cd_formatted_toc {
115 	struct ioc_toc_header header;
116 	struct cd_toc_entry entries[MAXTRACK+1]; /* One extra for the */
117 						 /* leadout */
118 };
119 
120 struct cdbounce {
121 	struct buf     *obp;			/* original buf */
122 	int		doff;			/* byte offset in orig. buf */
123 	int		soff;			/* byte offset in bounce buf */
124 	int		resid;			/* residual i/o in orig. buf */
125 	int		bcount;			/* actual obp bytes in bounce */
126 };
127 
128 static void	cdstart(struct scsipi_periph *);
129 static void	cdrestart(void *);
130 static void	cdminphys(struct buf *);
131 static void	cdgetdefaultlabel(struct cd_softc *, struct cd_formatted_toc *,
132 		    struct disklabel *);
133 static void	cdgetdisklabel(struct cd_softc *);
134 static void	cddone(struct scsipi_xfer *, int);
135 static void	cdbounce(struct buf *);
136 static int	cd_interpret_sense(struct scsipi_xfer *);
137 static u_long	cd_size(struct cd_softc *, int);
138 static int	cd_play(struct cd_softc *, int, int);
139 static int	cd_play_tracks(struct cd_softc *, struct cd_formatted_toc *,
140 		    int, int, int, int);
141 static int	cd_play_msf(struct cd_softc *, int, int, int, int, int, int);
142 static int	cd_pause(struct cd_softc *, int);
143 static int	cd_reset(struct cd_softc *);
144 static int	cd_read_subchannel(struct cd_softc *, int, int, int,
145 		    struct cd_sub_channel_info *, int, int);
146 static int	cd_read_toc(struct cd_softc *, int, int, int,
147 		    struct cd_formatted_toc *, int, int, int);
148 static int	cd_get_parms(struct cd_softc *, int);
149 static int	cd_load_toc(struct cd_softc *, int, struct cd_formatted_toc *, int);
150 static int	cdreadmsaddr(struct cd_softc *, struct cd_formatted_toc *,int *);
151 static int	cdcachesync(struct scsipi_periph *periph, int flags);
152 
153 static int	dvd_auth(struct cd_softc *, dvd_authinfo *);
154 static int	dvd_read_physical(struct cd_softc *, dvd_struct *);
155 static int	dvd_read_copyright(struct cd_softc *, dvd_struct *);
156 static int	dvd_read_disckey(struct cd_softc *, dvd_struct *);
157 static int	dvd_read_bca(struct cd_softc *, dvd_struct *);
158 static int	dvd_read_manufact(struct cd_softc *, dvd_struct *);
159 static int	dvd_read_struct(struct cd_softc *, dvd_struct *);
160 
161 static int	cd_mode_sense(struct cd_softc *, u_int8_t, void *, size_t, int,
162 		    int, int *);
163 static int	cd_mode_select(struct cd_softc *, u_int8_t, void *, size_t,
164 		    int, int);
165 static int	cd_setchan(struct cd_softc *, int, int, int, int, int);
166 static int	cd_getvol(struct cd_softc *, struct ioc_vol *, int);
167 static int	cd_setvol(struct cd_softc *, const struct ioc_vol *, int);
168 static int	cd_set_pa_immed(struct cd_softc *, int);
169 static int	cd_load_unload(struct cd_softc *, struct ioc_load_unload *);
170 static int	cd_setblksize(struct cd_softc *);
171 
172 static int	cdmatch(device_t, cfdata_t, void *);
173 static void	cdattach(device_t, device_t, void *);
174 static int	cddetach(device_t, int);
175 
176 static int	mmc_getdiscinfo(struct scsipi_periph *, struct mmc_discinfo *);
177 static int	mmc_gettrackinfo(struct scsipi_periph *, struct mmc_trackinfo *);
178 static int	mmc_do_op(struct scsipi_periph *, struct mmc_op *);
179 static int	mmc_setup_writeparams(struct scsipi_periph *, struct mmc_writeparams *);
180 
181 static void	cd_set_properties(struct cd_softc *);
182 
183 CFATTACH_DECL3_NEW(cd, sizeof(struct cd_softc), cdmatch, cdattach, cddetach,
184     NULL, NULL, NULL, DVF_DETACH_SHUTDOWN);
185 
186 extern struct cfdriver cd_cd;
187 
188 static const struct scsipi_inquiry_pattern cd_patterns[] = {
189 	{T_CDROM, T_REMOV,
190 	 "",         "",                 ""},
191 	{T_WORM, T_REMOV,
192 	 "",         "",                 ""},
193 #if 0
194 	{T_CDROM, T_REMOV, /* more luns */
195 	 "PIONEER ", "CD-ROM DRM-600  ", ""},
196 #endif
197 	{T_DIRECT, T_REMOV,
198 	 "NEC                 CD-ROM DRIVE:260", "", ""},
199 };
200 
201 static dev_type_open(cdopen);
202 static dev_type_close(cdclose);
203 static dev_type_read(cdread);
204 static dev_type_write(cdwrite);
205 static dev_type_ioctl(cdioctl);
206 static dev_type_strategy(cdstrategy);
207 static dev_type_dump(cddump);
208 static dev_type_size(cdsize);
209 
210 const struct bdevsw cd_bdevsw = {
211 	cdopen, cdclose, cdstrategy, cdioctl, cddump, cdsize, D_DISK
212 };
213 
214 const struct cdevsw cd_cdevsw = {
215 	cdopen, cdclose, cdread, cdwrite, cdioctl,
216 	nostop, notty, nopoll, nommap, nokqfilter, D_DISK
217 };
218 
219 static struct dkdriver cddkdriver = { cdstrategy, NULL };
220 
221 static const struct scsipi_periphsw cd_switch = {
222 	cd_interpret_sense,	/* use our error handler first */
223 	cdstart,		/* we have a queue, which is started by this */
224 	NULL,			/* we do not have an async handler */
225 	cddone,			/* deal with stats at interrupt time */
226 };
227 
228 /*
229  * The routine called by the low level scsi routine when it discovers
230  * A device suitable for this driver
231  */
232 static int
233 cdmatch(device_t parent, cfdata_t match, void *aux)
234 {
235 	struct scsipibus_attach_args *sa = aux;
236 	int priority;
237 
238 	(void)scsipi_inqmatch(&sa->sa_inqbuf,
239 	    cd_patterns, sizeof(cd_patterns) / sizeof(cd_patterns[0]),
240 	    sizeof(cd_patterns[0]), &priority);
241 
242 	return (priority);
243 }
244 
245 static void
246 cdattach(device_t parent, device_t self, void *aux)
247 {
248 	struct cd_softc *cd = device_private(self);
249 	struct scsipibus_attach_args *sa = aux;
250 	struct scsipi_periph *periph = sa->sa_periph;
251 
252 	SC_DEBUG(periph, SCSIPI_DB2, ("cdattach: "));
253 
254 	cd->sc_dev = self;
255 
256 	mutex_init(&cd->sc_lock, MUTEX_DEFAULT, IPL_NONE);
257 
258 	if (scsipi_periph_bustype(sa->sa_periph) == SCSIPI_BUSTYPE_SCSI &&
259 	    periph->periph_version == 0)
260 		cd->flags |= CDF_ANCIENT;
261 
262 	bufq_alloc(&cd->buf_queue, "disksort", BUFQ_SORT_RAWBLOCK);
263 
264 	callout_init(&cd->sc_callout, 0);
265 
266 	/*
267 	 * Store information needed to contact our base driver
268 	 */
269 	cd->sc_periph = periph;
270 
271 	periph->periph_dev = cd->sc_dev;
272 	periph->periph_switch = &cd_switch;
273 
274 	/*
275 	 * Increase our openings to the maximum-per-periph
276 	 * supported by the adapter.  This will either be
277 	 * clamped down or grown by the adapter if necessary.
278 	 */
279 	periph->periph_openings =
280 	    SCSIPI_CHAN_MAX_PERIPH(periph->periph_channel);
281 	periph->periph_flags |= PERIPH_GROW_OPENINGS;
282 
283 	/*
284 	 * Initialize and attach the disk structure.
285 	 */
286 	disk_init(&cd->sc_dk, device_xname(cd->sc_dev), &cddkdriver);
287 	disk_attach(&cd->sc_dk);
288 
289 	aprint_normal("\n");
290 	aprint_naive("\n");
291 
292 #if NRND > 0
293 	rnd_attach_source(&cd->rnd_source, device_xname(cd->sc_dev),
294 			  RND_TYPE_DISK, 0);
295 #endif
296 
297 	if (!pmf_device_register(self, NULL, NULL))
298 		aprint_error_dev(self, "couldn't establish power handler\n");
299 }
300 
301 static int
302 cddetach(device_t self, int flags)
303 {
304 	struct cd_softc *cd = device_private(self);
305 	int s, bmaj, cmaj, i, mn;
306 
307 	/* locate the major number */
308 	bmaj = bdevsw_lookup_major(&cd_bdevsw);
309 	cmaj = cdevsw_lookup_major(&cd_cdevsw);
310 	/* Nuke the vnodes for any open instances */
311 	for (i = 0; i < MAXPARTITIONS; i++) {
312 		mn = CDMINOR(device_unit(self), i);
313 		vdevgone(bmaj, mn, mn, VBLK);
314 		vdevgone(cmaj, mn, mn, VCHR);
315 	}
316 
317 	/* kill any pending restart */
318 	callout_stop(&cd->sc_callout);
319 
320 	s = splbio();
321 
322 	/* Kill off any queued buffers. */
323 	bufq_drain(cd->buf_queue);
324 
325 	bufq_free(cd->buf_queue);
326 
327 	/* Kill off any pending commands. */
328 	scsipi_kill_pending(cd->sc_periph);
329 
330 	splx(s);
331 
332 	mutex_destroy(&cd->sc_lock);
333 
334 	/* Detach from the disk list. */
335 	disk_detach(&cd->sc_dk);
336 	disk_destroy(&cd->sc_dk);
337 
338 #if NRND > 0
339 	/* Unhook the entropy source. */
340 	rnd_detach_source(&cd->rnd_source);
341 #endif
342 
343 	return (0);
344 }
345 
346 /*
347  * open the device. Make sure the partition info is a up-to-date as can be.
348  */
349 static int
350 cdopen(dev_t dev, int flag, int fmt, struct lwp *l)
351 {
352 	struct cd_softc *cd;
353 	struct scsipi_periph *periph;
354 	struct scsipi_adapter *adapt;
355 	int part;
356 	int error;
357 	int rawpart;
358 
359 	cd = device_lookup_private(&cd_cd, CDUNIT(dev));
360 	if (cd == NULL)
361 		return (ENXIO);
362 
363 	periph = cd->sc_periph;
364 	adapt = periph->periph_channel->chan_adapter;
365 	part = CDPART(dev);
366 
367 	SC_DEBUG(periph, SCSIPI_DB1,
368 	    ("cdopen: dev=0x%"PRIu64" (unit %"PRIu32" (of %d), partition %"PRId32")\n",dev,
369 	    CDUNIT(dev), cd_cd.cd_ndevs, CDPART(dev)));
370 
371 	/*
372 	 * If this is the first open of this device, add a reference
373 	 * to the adapter.
374 	 */
375 	if (cd->sc_dk.dk_openmask == 0 &&
376 	    (error = scsipi_adapter_addref(adapt)) != 0)
377 		return (error);
378 
379 	mutex_enter(&cd->sc_lock);
380 
381 	rawpart = (part == RAW_PART && fmt == S_IFCHR);
382 	if ((periph->periph_flags & PERIPH_OPEN) != 0) {
383 		/*
384 		 * If any partition is open, but the disk has been invalidated,
385 		 * disallow further opens.
386 		 */
387 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0 &&
388 			!rawpart) {
389 			error = EIO;
390 			goto bad3;
391 		}
392 	} else {
393 		int silent;
394 
395 		if (rawpart)
396 			silent = XS_CTL_SILENT;
397 		else
398 			silent = 0;
399 
400 		/* Check that it is still responding and ok. */
401 		error = scsipi_test_unit_ready(periph,
402 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE |
403 		    silent);
404 
405 		/*
406 		 * Start the pack spinning if necessary. Always allow the
407 		 * raw parition to be opened, for raw IOCTLs. Data transfers
408 		 * will check for SDEV_MEDIA_LOADED.
409 		 */
410 		if (error == EIO) {
411 			int error2;
412 
413 			error2 = scsipi_start(periph, SSS_START, silent);
414 			switch (error2) {
415 			case 0:
416 				error = 0;
417 				break;
418 			case EIO:
419 			case EINVAL:
420 				break;
421 			default:
422 				error = error2;
423 				break;
424 			}
425 		}
426 		if (error) {
427 			if (rawpart)
428 				goto out;
429 			goto bad3;
430 		}
431 
432 		periph->periph_flags |= PERIPH_OPEN;
433 
434 		/* Lock the pack in. */
435 		error = scsipi_prevent(periph, SPAMR_PREVENT_DT,
436 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE);
437 		SC_DEBUG(periph, SCSIPI_DB1,
438 		    ("cdopen: scsipi_prevent, error=%d\n", error));
439 		if (error) {
440 			if (rawpart)
441 				goto out;
442 			goto bad;
443 		}
444 
445 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
446 			/* Load the physical device parameters. */
447 			if (cd_get_parms(cd, 0) != 0) {
448 				if (rawpart)
449 					goto out;
450 				error = ENXIO;
451 				goto bad;
452 			}
453 			periph->periph_flags |= PERIPH_MEDIA_LOADED;
454 			SC_DEBUG(periph, SCSIPI_DB3, ("Params loaded "));
455 
456 			/* Fabricate a disk label. */
457 			cdgetdisklabel(cd);
458 			SC_DEBUG(periph, SCSIPI_DB3, ("Disklabel fabricated "));
459 
460 			cd_set_properties(cd);
461 		}
462 	}
463 
464 	/* Check that the partition exists. */
465 	if (part != RAW_PART &&
466 	    (part >= cd->sc_dk.dk_label->d_npartitions ||
467 	    cd->sc_dk.dk_label->d_partitions[part].p_fstype == FS_UNUSED)) {
468 		error = ENXIO;
469 		goto bad;
470 	}
471 
472 out:	/* Insure only one open at a time. */
473 	switch (fmt) {
474 	case S_IFCHR:
475 		cd->sc_dk.dk_copenmask |= (1 << part);
476 		break;
477 	case S_IFBLK:
478 		cd->sc_dk.dk_bopenmask |= (1 << part);
479 		break;
480 	}
481 	cd->sc_dk.dk_openmask =
482 	    cd->sc_dk.dk_copenmask | cd->sc_dk.dk_bopenmask;
483 
484 	SC_DEBUG(periph, SCSIPI_DB3, ("open complete\n"));
485 	mutex_exit(&cd->sc_lock);
486 	return (0);
487 
488 bad:
489 	if (cd->sc_dk.dk_openmask == 0) {
490 		scsipi_prevent(periph, SPAMR_ALLOW,
491 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE);
492 		periph->periph_flags &= ~PERIPH_OPEN;
493 	}
494 
495 bad3:
496 	mutex_exit(&cd->sc_lock);
497 	if (cd->sc_dk.dk_openmask == 0)
498 		scsipi_adapter_delref(adapt);
499 	return (error);
500 }
501 
502 /*
503  * close the device.. only called if we are the LAST
504  * occurence of an open device
505  */
506 static int
507 cdclose(dev_t dev, int flag, int fmt, struct lwp *l)
508 {
509 	struct cd_softc *cd = device_lookup_private(&cd_cd, CDUNIT(dev));
510 	struct scsipi_periph *periph = cd->sc_periph;
511 	struct scsipi_adapter *adapt = periph->periph_channel->chan_adapter;
512 	int part = CDPART(dev);
513 	int silent = 0;
514 
515 	if (part == RAW_PART && ((cd->sc_dk.dk_label->d_npartitions == 0) ||
516 	    (part < cd->sc_dk.dk_label->d_npartitions &&
517 	    cd->sc_dk.dk_label->d_partitions[part].p_fstype == FS_UNUSED)))
518 		silent = XS_CTL_SILENT;
519 
520 	mutex_enter(&cd->sc_lock);
521 
522 	switch (fmt) {
523 	case S_IFCHR:
524 		cd->sc_dk.dk_copenmask &= ~(1 << part);
525 		break;
526 	case S_IFBLK:
527 		cd->sc_dk.dk_bopenmask &= ~(1 << part);
528 		break;
529 	}
530 	cd->sc_dk.dk_openmask =
531 	    cd->sc_dk.dk_copenmask | cd->sc_dk.dk_bopenmask;
532 
533 	if (cd->sc_dk.dk_openmask == 0) {
534 		/* synchronise caches on last close */
535 		cdcachesync(periph, silent);
536 
537 		/* drain outstanding calls */
538 		scsipi_wait_drain(periph);
539 
540 		scsipi_prevent(periph, SPAMR_ALLOW,
541 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE |
542 		    XS_CTL_IGNORE_NOT_READY | silent);
543 		periph->periph_flags &= ~PERIPH_OPEN;
544 
545 		scsipi_wait_drain(periph);
546 
547 		scsipi_adapter_delref(adapt);
548 	}
549 
550 	mutex_exit(&cd->sc_lock);
551 	return (0);
552 }
553 
554 /*
555  * Actually translate the requested transfer into one the physical driver can
556  * understand.  The transfer is described by a buf and will include only one
557  * physical transfer.
558  */
559 static void
560 cdstrategy(struct buf *bp)
561 {
562 	struct cd_softc *cd = device_lookup_private(&cd_cd,CDUNIT(bp->b_dev));
563 	struct disklabel *lp;
564 	struct scsipi_periph *periph = cd->sc_periph;
565 	daddr_t blkno;
566 	int s;
567 
568 	SC_DEBUG(cd->sc_periph, SCSIPI_DB2, ("cdstrategy "));
569 	SC_DEBUG(cd->sc_periph, SCSIPI_DB1,
570 	    ("%d bytes @ blk %" PRId64 "\n", bp->b_bcount, bp->b_blkno));
571 	/*
572 	 * If the device has been made invalid, error out
573 	 * maybe the media changed
574 	 */
575 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
576 		if (periph->periph_flags & PERIPH_OPEN)
577 			bp->b_error = EIO;
578 		else
579 			bp->b_error = ENODEV;
580 		goto done;
581 	}
582 
583 	lp = cd->sc_dk.dk_label;
584 
585 	/*
586 	 * The transfer must be a whole number of blocks, offset must not
587 	 * be negative.
588 	 */
589 	if ((bp->b_bcount % lp->d_secsize) != 0 ||
590 	    bp->b_blkno < 0 ) {
591 		bp->b_error = EINVAL;
592 		goto done;
593 	}
594 	/*
595 	 * If it's a null transfer, return immediately
596 	 */
597 	if (bp->b_bcount == 0)
598 		goto done;
599 
600 	/*
601 	 * Do bounds checking, adjust transfer. if error, process.
602 	 * If end of partition, just return.
603 	 */
604 	if (CDPART(bp->b_dev) == RAW_PART) {
605 		if (bounds_check_with_mediasize(bp, DEV_BSIZE,
606 		    cd->params.disksize512) <= 0)
607 			goto done;
608 	} else {
609 		if (bounds_check_with_label(&cd->sc_dk, bp,
610 		    (cd->flags & (CDF_WLABEL|CDF_LABELLING)) != 0) <= 0)
611 			goto done;
612 	}
613 
614 	/*
615 	 * Now convert the block number to absolute and put it in
616 	 * terms of the device's logical block size.
617 	 */
618 	blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE);
619 	if (CDPART(bp->b_dev) != RAW_PART)
620 		blkno += lp->d_partitions[CDPART(bp->b_dev)].p_offset;
621 
622 	bp->b_rawblkno = blkno;
623 
624 	/*
625 	 * If the disklabel sector size does not match the device
626 	 * sector size we may need to do some extra work.
627 	 */
628 	if (lp->d_secsize != cd->params.blksize) {
629 
630 		/*
631 		 * If the xfer is not a multiple of the device block size
632 		 * or it is not block aligned, we need to bounce it.
633 		 */
634 		if ((bp->b_bcount % cd->params.blksize) != 0 ||
635 			((blkno * lp->d_secsize) % cd->params.blksize) != 0) {
636 			struct cdbounce *bounce;
637 			struct buf *nbp;
638 			long count;
639 
640 			if ((bp->b_flags & B_READ) == 0) {
641 
642 				/* XXXX We don't support bouncing writes. */
643 				bp->b_error = EACCES;
644 				goto done;
645 			}
646 
647 			bounce = malloc(sizeof(*bounce), M_DEVBUF, M_NOWAIT);
648 			if (!bounce) {
649 				/* No memory -- fail the iop. */
650 				bp->b_error = ENOMEM;
651 				goto done;
652 			}
653 
654 			bounce->obp = bp;
655 			bounce->resid = bp->b_bcount;
656 			bounce->doff = 0;
657 			count = ((blkno * lp->d_secsize) % cd->params.blksize);
658 			bounce->soff = count;
659 			count += bp->b_bcount;
660 			count = roundup(count, cd->params.blksize);
661 			bounce->bcount = bounce->resid;
662 			if (count > MAXPHYS) {
663 				bounce->bcount = MAXPHYS - bounce->soff;
664 				count = MAXPHYS;
665 			}
666 
667 			blkno = ((blkno * lp->d_secsize) / cd->params.blksize);
668 			nbp = getiobuf(NULL, false);
669 			if (!nbp) {
670 				/* No memory -- fail the iop. */
671 				free(bounce, M_DEVBUF);
672 				bp->b_error = ENOMEM;
673 				goto done;
674 			}
675 			nbp->b_data = malloc(count, M_DEVBUF, M_NOWAIT);
676 			if (!nbp->b_data) {
677 				/* No memory -- fail the iop. */
678 				free(bounce, M_DEVBUF);
679 				putiobuf(nbp);
680 				bp->b_error = ENOMEM;
681 				goto done;
682 			}
683 
684 			/* Set up the IOP to the bounce buffer. */
685 			nbp->b_error = 0;
686 			nbp->b_proc = bp->b_proc;
687 			nbp->b_bcount = count;
688 			nbp->b_bufsize = count;
689 			nbp->b_rawblkno = blkno;
690 			nbp->b_flags = bp->b_flags | B_READ;
691 			nbp->b_oflags = bp->b_oflags;
692 			nbp->b_cflags = bp->b_cflags;
693 			nbp->b_iodone = cdbounce;
694 
695 			/* store bounce state in b_private and use new buf */
696 			nbp->b_private = bounce;
697 
698 			BIO_COPYPRIO(nbp, bp);
699 
700 			bp = nbp;
701 
702 		} else {
703 			/* Xfer is aligned -- just adjust the start block */
704 			bp->b_rawblkno = (blkno * lp->d_secsize) /
705 				cd->params.blksize;
706 		}
707 	}
708 	s = splbio();
709 
710 	/*
711 	 * Place it in the queue of disk activities for this disk.
712 	 *
713 	 * XXX Only do disksort() if the current operating mode does not
714 	 * XXX include tagged queueing.
715 	 */
716 	bufq_put(cd->buf_queue, bp);
717 
718 	/*
719 	 * Tell the device to get going on the transfer if it's
720 	 * not doing anything, otherwise just wait for completion
721 	 */
722 	cdstart(cd->sc_periph);
723 
724 	splx(s);
725 	return;
726 
727 done:
728 	/*
729 	 * Correctly set the buf to indicate a completed xfer
730 	 */
731 	bp->b_resid = bp->b_bcount;
732 	biodone(bp);
733 }
734 
735 /*
736  * cdstart looks to see if there is a buf waiting for the device
737  * and that the device is not already busy. If both are true,
738  * It deques the buf and creates a scsi command to perform the
739  * transfer in the buf. The transfer request will call scsipi_done
740  * on completion, which will in turn call this routine again
741  * so that the next queued transfer is performed.
742  * The bufs are queued by the strategy routine (cdstrategy)
743  *
744  * This routine is also called after other non-queued requests
745  * have been made of the scsi driver, to ensure that the queue
746  * continues to be drained.
747  *
748  * must be called at the correct (highish) spl level
749  * cdstart() is called at splbio from cdstrategy, cdrestart and scsipi_done
750  */
751 static void
752 cdstart(struct scsipi_periph *periph)
753 {
754 	struct cd_softc *cd = device_private(periph->periph_dev);
755 	struct buf *bp = 0;
756 	struct scsipi_rw_10 cmd_big;
757 	struct scsi_rw_6 cmd_small;
758 	struct scsipi_generic *cmdp;
759 	struct scsipi_xfer *xs;
760 	int flags, nblks, cmdlen, error;
761 
762 	SC_DEBUG(periph, SCSIPI_DB2, ("cdstart "));
763 	/*
764 	 * Check if the device has room for another command
765 	 */
766 	while (periph->periph_active < periph->periph_openings) {
767 		/*
768 		 * there is excess capacity, but a special waits
769 		 * It'll need the adapter as soon as we clear out of the
770 		 * way and let it run (user level wait).
771 		 */
772 		if (periph->periph_flags & PERIPH_WAITING) {
773 			periph->periph_flags &= ~PERIPH_WAITING;
774 			wakeup((void *)periph);
775 			return;
776 		}
777 
778 		/*
779 		 * If the device has become invalid, abort all the
780 		 * reads and writes until all files have been closed and
781 		 * re-opened
782 		 */
783 		if (__predict_false(
784 		    (periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)) {
785 			if ((bp = bufq_get(cd->buf_queue)) != NULL) {
786 				bp->b_error = EIO;
787 				bp->b_resid = bp->b_bcount;
788 				biodone(bp);
789 				continue;
790 			} else {
791 				return;
792 			}
793 		}
794 
795 		/*
796 		 * See if there is a buf with work for us to do..
797 		 */
798 		if ((bp = bufq_peek(cd->buf_queue)) == NULL)
799 			return;
800 
801 		/*
802 		 * We have a buf, now we should make a command.
803 		 */
804 
805 		nblks = howmany(bp->b_bcount, cd->params.blksize);
806 
807 		/*
808 		 *  Fill out the scsi command.  If the transfer will
809 		 *  fit in a "small" cdb, use it.
810 		 */
811 		if (((bp->b_rawblkno & 0x1fffff) == bp->b_rawblkno) &&
812 		    ((nblks & 0xff) == nblks) &&
813 		    !(periph->periph_quirks & PQUIRK_ONLYBIG)) {
814 			/*
815 			 * We can fit in a small cdb.
816 			 */
817 			memset(&cmd_small, 0, sizeof(cmd_small));
818 			cmd_small.opcode = (bp->b_flags & B_READ) ?
819 			    SCSI_READ_6_COMMAND : SCSI_WRITE_6_COMMAND;
820 			_lto3b(bp->b_rawblkno, cmd_small.addr);
821 			cmd_small.length = nblks & 0xff;
822 			cmdlen = sizeof(cmd_small);
823 			cmdp = (struct scsipi_generic *)&cmd_small;
824 		} else {
825 			/*
826 			 * Need a large cdb.
827 			 */
828 			memset(&cmd_big, 0, sizeof(cmd_big));
829 			cmd_big.opcode = (bp->b_flags & B_READ) ?
830 			    READ_10 : WRITE_10;
831 			_lto4b(bp->b_rawblkno, cmd_big.addr);
832 			_lto2b(nblks, cmd_big.length);
833 			cmdlen = sizeof(cmd_big);
834 			cmdp = (struct scsipi_generic *)&cmd_big;
835 		}
836 
837 		/* Instrumentation. */
838 		disk_busy(&cd->sc_dk);
839 
840 		/*
841 		 * Figure out what flags to use.
842 		 */
843 		flags = XS_CTL_NOSLEEP|XS_CTL_ASYNC|XS_CTL_SIMPLE_TAG;
844 		if (bp->b_flags & B_READ)
845 			flags |= XS_CTL_DATA_IN;
846 		else
847 			flags |= XS_CTL_DATA_OUT;
848 
849 		/*
850 		 * Call the routine that chats with the adapter.
851 		 * Note: we cannot sleep as we may be an interrupt
852 		 */
853 		xs = scsipi_make_xs(periph, cmdp, cmdlen,
854 		    (u_char *)bp->b_data, bp->b_bcount,
855 		    CDRETRIES, 30000, bp, flags);
856 		if (__predict_false(xs == NULL)) {
857 			/*
858 			 * out of memory. Keep this buffer in the queue, and
859 			 * retry later.
860 			 */
861 			callout_reset(&cd->sc_callout, hz / 2, cdrestart,
862 			    periph);
863 			return;
864 		}
865 		/*
866 		 * need to dequeue the buffer before queuing the command,
867 		 * because cdstart may be called recursively from the
868 		 * HBA driver
869 		 */
870 #ifdef DIAGNOSTIC
871 		if (bufq_get(cd->buf_queue) != bp)
872 			panic("cdstart(): dequeued wrong buf");
873 #else
874 		bufq_get(cd->buf_queue);
875 #endif
876 		error = scsipi_execute_xs(xs);
877 		/* with a scsipi_xfer preallocated, scsipi_command can't fail */
878 		KASSERT(error == 0);
879 	}
880 }
881 
882 static void
883 cdrestart(void *v)
884 {
885 	int s = splbio();
886 	cdstart((struct scsipi_periph *)v);
887 	splx(s);
888 }
889 
890 static void
891 cddone(struct scsipi_xfer *xs, int error)
892 {
893 	struct cd_softc *cd = device_private(xs->xs_periph->periph_dev);
894 	struct buf *bp = xs->bp;
895 
896 	if (bp) {
897 		/* note, bp->b_resid is NOT initialised */
898 		bp->b_error = error;
899 		bp->b_resid = xs->resid;
900 		if (error) {
901 			/* on a read/write error bp->b_resid is zero, so fix */
902 			bp->b_resid = bp->b_bcount;
903 		}
904 
905 		disk_unbusy(&cd->sc_dk, bp->b_bcount - bp->b_resid,
906 		    (bp->b_flags & B_READ));
907 #if NRND > 0
908 		rnd_add_uint32(&cd->rnd_source, bp->b_rawblkno);
909 #endif
910 
911 		biodone(bp);
912 	}
913 }
914 
915 static void
916 cdbounce(struct buf *bp)
917 {
918 	struct cdbounce *bounce = (struct cdbounce *)bp->b_private;
919 	struct buf *obp = bounce->obp;
920 	struct cd_softc *cd =
921 	    device_lookup_private(&cd_cd, CDUNIT(obp->b_dev));
922 	struct disklabel *lp = cd->sc_dk.dk_label;
923 
924 	if (bp->b_error != 0) {
925 		/* EEK propagate the error and free the memory */
926 		goto done;
927 	}
928 
929 	KASSERT(obp->b_flags & B_READ);
930 
931 	/* copy bounce buffer to final destination */
932 	memcpy((char *)obp->b_data + bounce->doff,
933 	    (char *)bp->b_data + bounce->soff, bounce->bcount);
934 
935 	/* check if we need more I/O, i.e. bounce put us over MAXPHYS */
936 	KASSERT(bounce->resid >= bounce->bcount);
937 	bounce->resid -= bounce->bcount;
938 	if (bounce->resid > 0) {
939 		struct buf *nbp;
940 		daddr_t blkno;
941 		long count;
942 		int s;
943 
944 		blkno = obp->b_rawblkno +
945 		    ((obp->b_bcount - bounce->resid) / lp->d_secsize);
946 		count = ((blkno * lp->d_secsize) % cd->params.blksize);
947 		blkno = (blkno * lp->d_secsize) / cd->params.blksize;
948 		bounce->soff = count;
949 		bounce->doff += bounce->bcount;
950 		count += bounce->resid;
951 		count = roundup(count, cd->params.blksize);
952 		bounce->bcount = bounce->resid;
953 		if (count > MAXPHYS) {
954 			bounce->bcount = MAXPHYS - bounce->soff;
955 			count = MAXPHYS;
956 		}
957 
958 		nbp = getiobuf(NULL, false);
959 		if (!nbp) {
960 			/* No memory -- fail the iop. */
961 			bp->b_error = ENOMEM;
962 			goto done;
963 		}
964 
965 		/* Set up the IOP to the bounce buffer. */
966 		nbp->b_error = 0;
967 		nbp->b_proc = obp->b_proc;
968 		nbp->b_bcount = count;
969 		nbp->b_bufsize = count;
970 		nbp->b_data = bp->b_data;
971 		nbp->b_rawblkno = blkno;
972 		nbp->b_flags = obp->b_flags | B_READ;
973 		nbp->b_oflags = obp->b_oflags;
974 		nbp->b_cflags = obp->b_cflags;
975 		nbp->b_iodone = cdbounce;
976 
977 		/* store bounce state in b_private and use new buf */
978 		nbp->b_private = bounce;
979 
980 		BIO_COPYPRIO(nbp, obp);
981 
982 		bp->b_data = NULL;
983 		putiobuf(bp);
984 
985 		/* enqueue the request and return */
986 		s = splbio();
987 		bufq_put(cd->buf_queue, nbp);
988 		cdstart(cd->sc_periph);
989 		splx(s);
990 
991 		return;
992 	}
993 
994 done:
995 	obp->b_error = bp->b_error;
996 	obp->b_resid = bp->b_resid;
997 	free(bp->b_data, M_DEVBUF);
998 	free(bounce, M_DEVBUF);
999 	bp->b_data = NULL;
1000 	putiobuf(bp);
1001 	biodone(obp);
1002 }
1003 
1004 static int
1005 cd_interpret_sense(struct scsipi_xfer *xs)
1006 {
1007 	struct scsipi_periph *periph = xs->xs_periph;
1008 	struct scsi_sense_data *sense = &xs->sense.scsi_sense;
1009 	int retval = EJUSTRETURN;
1010 
1011 	/*
1012 	 * If it isn't a extended or extended/deferred error, let
1013 	 * the generic code handle it.
1014 	 */
1015 	if (SSD_RCODE(sense->response_code) != SSD_RCODE_CURRENT &&
1016 	    SSD_RCODE(sense->response_code) != SSD_RCODE_DEFERRED)
1017 		return (retval);
1018 
1019 	/*
1020 	 * If we got a "Unit not ready" (SKEY_NOT_READY) and "Logical Unit
1021 	 * Is In The Process of Becoming Ready" (Sense code 0x04,0x01), then
1022 	 * wait a bit for the drive to spin up
1023 	 */
1024 
1025 	if ((SSD_SENSE_KEY(sense->flags) == SKEY_NOT_READY) &&
1026 	    (sense->asc == 0x04) && (sense->ascq == 0x01)) {
1027 		/*
1028 		 * Sleep for 5 seconds to wait for the drive to spin up
1029 		 */
1030 
1031 		SC_DEBUG(periph, SCSIPI_DB1, ("Waiting 5 sec for CD "
1032 						"spinup\n"));
1033 		if (!callout_pending(&periph->periph_callout))
1034 			scsipi_periph_freeze(periph, 1);
1035 		callout_reset(&periph->periph_callout,
1036 		    5 * hz, scsipi_periph_timed_thaw, periph);
1037 		retval = ERESTART;
1038 	}
1039 
1040 	/*
1041 	 * If we got a "Unit not ready" (SKEY_NOT_READY) and "Logical Unit Not
1042 	 * Ready, Operation In Progress" (Sense code 0x04, 0x07),
1043 	 * then wait for the specified time
1044 	 */
1045 
1046 	if ((SSD_SENSE_KEY(sense->flags) == SKEY_NOT_READY) &&
1047 	    (sense->asc == 0x04) && (sense->ascq == 0x07)) {
1048 		/*
1049 		 * we could listen to the delay; but it looks like the skey
1050 		 * data is not always returned.
1051 		 */
1052 		/* cd_delay = _2btol(sense->sks.sks_bytes); */
1053 
1054 		/* wait for a half second and get going again */
1055 		if (!callout_pending(&periph->periph_callout))
1056 			scsipi_periph_freeze(periph, 1);
1057 		callout_reset(&periph->periph_callout,
1058 		    hz/2, scsipi_periph_timed_thaw, periph);
1059 		retval = ERESTART;
1060 	}
1061 
1062 	/*
1063 	 * If we got a "Unit not ready" (SKEY_NOT_READY) and "Long write in
1064 	 * progress" (Sense code 0x04, 0x08), then wait for the specified
1065 	 * time
1066 	 */
1067 
1068 	if ((SSD_SENSE_KEY(sense->flags) == SKEY_NOT_READY) &&
1069 	    (sense->asc == 0x04) && (sense->ascq == 0x08)) {
1070 		/*
1071 		 * long write in process; we could listen to the delay; but it
1072 		 * looks like the skey data is not always returned.
1073 		 */
1074 		/* cd_delay = _2btol(sense->sks.sks_bytes); */
1075 
1076 		/* wait for a half second and get going again */
1077 		if (!callout_pending(&periph->periph_callout))
1078 			scsipi_periph_freeze(periph, 1);
1079 		callout_reset(&periph->periph_callout,
1080 		    hz/2, scsipi_periph_timed_thaw, periph);
1081 		retval = ERESTART;
1082 	}
1083 
1084 	return (retval);
1085 }
1086 
1087 static void
1088 cdminphys(struct buf *bp)
1089 {
1090 	struct cd_softc *cd = device_lookup_private(&cd_cd, CDUNIT(bp->b_dev));
1091 	long xmax;
1092 
1093 	/*
1094 	 * If the device is ancient, we want to make sure that
1095 	 * the transfer fits into a 6-byte cdb.
1096 	 *
1097 	 * XXX Note that the SCSI-I spec says that 256-block transfers
1098 	 * are allowed in a 6-byte read/write, and are specified
1099 	 * by settng the "length" to 0.  However, we're conservative
1100 	 * here, allowing only 255-block transfers in case an
1101 	 * ancient device gets confused by length == 0.  A length of 0
1102 	 * in a 10-byte read/write actually means 0 blocks.
1103 	 */
1104 	if (cd->flags & CDF_ANCIENT) {
1105 		xmax = cd->sc_dk.dk_label->d_secsize * 0xff;
1106 
1107 		if (bp->b_bcount > xmax)
1108 			bp->b_bcount = xmax;
1109 	}
1110 
1111 	(*cd->sc_periph->periph_channel->chan_adapter->adapt_minphys)(bp);
1112 }
1113 
1114 static int
1115 cdread(dev_t dev, struct uio *uio, int ioflag)
1116 {
1117 	return (physio(cdstrategy, NULL, dev, B_READ, cdminphys, uio));
1118 }
1119 
1120 static int
1121 cdwrite(dev_t dev, struct uio *uio, int ioflag)
1122 {
1123 	return (physio(cdstrategy, NULL, dev, B_WRITE, cdminphys, uio));
1124 }
1125 
1126 #if 0	/* XXX Not used */
1127 /*
1128  * conversion between minute-seconde-frame and logical block address
1129  * addresses format
1130  */
1131 static void
1132 lba2msf(u_long lba, u_char *m, u_char *s, u_char *f)
1133 {
1134 	u_long tmp;
1135 
1136 	tmp = lba + CD_BLOCK_OFFSET;	/* offset of first logical frame */
1137 	tmp &= 0xffffff;		/* negative lbas use only 24 bits */
1138 	*m = tmp / (CD_SECS * CD_FRAMES);
1139 	tmp %= (CD_SECS * CD_FRAMES);
1140 	*s = tmp / CD_FRAMES;
1141 	*f = tmp % CD_FRAMES;
1142 }
1143 #endif /* XXX Not used */
1144 
1145 /*
1146  * Convert an hour:minute:second:frame address to a logical block adres. In
1147  * theory the number of secs/minute and number of frames/second could be
1148  * configured differently in the device  as could the block offset but in
1149  * practice these values are rock solid and most drives don't even allow
1150  * theses values to be changed.
1151  */
1152 static uint32_t
1153 hmsf2lba(uint8_t h, uint8_t m, uint8_t s, uint8_t f)
1154 {
1155 	return (((((uint32_t) h * 60 + m) * CD_SECS) + s) * CD_FRAMES + f)
1156 		- CD_BLOCK_OFFSET;
1157 }
1158 
1159 static int
1160 cdreadmsaddr(struct cd_softc *cd, struct cd_formatted_toc *toc, int *addr)
1161 {
1162 	struct scsipi_periph *periph = cd->sc_periph;
1163 	int error;
1164 	struct cd_toc_entry *cte;
1165 
1166 	error = cd_read_toc(cd, CD_TOC_FORM, 0, 0, toc,
1167 	    sizeof(struct ioc_toc_header) + sizeof(struct cd_toc_entry),
1168 	    0, 0x40 /* control word for "get MS info" */);
1169 
1170 	if (error)
1171 		return (error);
1172 
1173 	cte = &toc->entries[0];
1174 	if (periph->periph_quirks & PQUIRK_LITTLETOC) {
1175 		cte->addr.lba = le32toh(cte->addr.lba);
1176 		toc->header.len = le16toh(toc->header.len);
1177 	} else {
1178 		cte->addr.lba = be32toh(cte->addr.lba);
1179 		toc->header.len = be16toh(toc->header.len);
1180 	}
1181 
1182 	*addr = (toc->header.len >= 10 && cte->track > 1) ?
1183 		cte->addr.lba : 0;
1184 	return 0;
1185 }
1186 
1187 /* synchronise caches code from sd.c, move to scsipi_ioctl.c ? */
1188 static int
1189 cdcachesync(struct scsipi_periph *periph, int flags) {
1190 	struct scsi_synchronize_cache_10 cmd;
1191 
1192 	/*
1193 	 * Issue a SYNCHRONIZE CACHE. MMC devices have to issue with address 0
1194 	 * and length 0 as it can't synchronise parts of the disc per spec.
1195 	 * We ignore ILLEGAL REQUEST in the event that the command is not
1196 	 * supported by the device, and poll for completion so that we know
1197 	 * that the cache has actually been flushed.
1198 	 *
1199 	 * XXX should we handle the PQUIRK_NOSYNCCACHE ?
1200 	 */
1201 
1202 	memset(&cmd, 0, sizeof(cmd));
1203 	cmd.opcode = SCSI_SYNCHRONIZE_CACHE_10;
1204 
1205 	return (scsipi_command(periph, (void *)&cmd, sizeof(cmd), 0, 0,
1206 	    CDRETRIES, 30000, NULL, flags | XS_CTL_IGNORE_ILLEGAL_REQUEST));
1207 }
1208 
1209 static int
1210 do_cdioreadentries(struct cd_softc *cd, struct ioc_read_toc_entry *te,
1211     struct cd_formatted_toc *toc)
1212 {
1213 	/* READ TOC format 0 command, entries */
1214 	struct ioc_toc_header *th;
1215 	struct cd_toc_entry *cte;
1216 	u_int len = te->data_len;
1217 	int ntracks;
1218 	int error;
1219 
1220 	th = &toc->header;
1221 
1222 	if (len > sizeof(toc->entries) ||
1223 	    len < sizeof(toc->entries[0]))
1224 		return (EINVAL);
1225 	error = cd_read_toc(cd, CD_TOC_FORM, te->address_format,
1226 	    te->starting_track, toc,
1227 	    sizeof(toc->header) + len,
1228 	    0, 0);
1229 	if (error)
1230 		return (error);
1231 	if (te->address_format == CD_LBA_FORMAT)
1232 		for (ntracks =
1233 		    th->ending_track - th->starting_track + 1;
1234 		    ntracks >= 0; ntracks--) {
1235 			cte = &toc->entries[ntracks];
1236 			cte->addr_type = CD_LBA_FORMAT;
1237 			if (cd->sc_periph->periph_quirks & PQUIRK_LITTLETOC)
1238 				cte->addr.lba = le32toh(cte->addr.lba);
1239 			else
1240 				cte->addr.lba = be32toh(cte->addr.lba);
1241 		}
1242 	if (cd->sc_periph->periph_quirks & PQUIRK_LITTLETOC)
1243 		th->len = le16toh(th->len);
1244 	else
1245 		th->len = be16toh(th->len);
1246 	return 0;
1247 }
1248 
1249 /*
1250  * Perform special action on behalf of the user.
1251  * Knows about the internals of this device
1252  */
1253 static int
1254 cdioctl(dev_t dev, u_long cmd, void *addr, int flag, struct lwp *l)
1255 {
1256 	struct cd_softc *cd = device_lookup_private(&cd_cd, CDUNIT(dev));
1257 	struct scsipi_periph *periph = cd->sc_periph;
1258 	struct cd_formatted_toc toc;
1259 	int part = CDPART(dev);
1260 	int error = 0;
1261 	int s;
1262 #ifdef __HAVE_OLD_DISKLABEL
1263 	struct disklabel *newlabel = NULL;
1264 #endif
1265 
1266 	SC_DEBUG(cd->sc_periph, SCSIPI_DB2, ("cdioctl 0x%lx ", cmd));
1267 
1268 	/*
1269 	 * If the device is not valid, some IOCTLs can still be
1270 	 * handled on the raw partition. Check this here.
1271 	 */
1272 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
1273 		switch (cmd) {
1274 		case DIOCWLABEL:
1275 		case DIOCLOCK:
1276 		case ODIOCEJECT:
1277 		case DIOCEJECT:
1278 		case DIOCCACHESYNC:
1279 		case DIOCTUR:
1280 		case SCIOCIDENTIFY:
1281 		case OSCIOCIDENTIFY:
1282 		case SCIOCCOMMAND:
1283 		case SCIOCDEBUG:
1284 		case CDIOCGETVOL:
1285 		case CDIOCSETVOL:
1286 		case CDIOCSETMONO:
1287 		case CDIOCSETSTEREO:
1288 		case CDIOCSETMUTE:
1289 		case CDIOCSETLEFT:
1290 		case CDIOCSETRIGHT:
1291 		case CDIOCCLOSE:
1292 		case CDIOCEJECT:
1293 		case CDIOCALLOW:
1294 		case CDIOCPREVENT:
1295 		case CDIOCSETDEBUG:
1296 		case CDIOCCLRDEBUG:
1297 		case CDIOCRESET:
1298 		case SCIOCRESET:
1299 		case CDIOCLOADUNLOAD:
1300 		case DVD_AUTH:
1301 		case DVD_READ_STRUCT:
1302 		case DIOCGSTRATEGY:
1303 		case DIOCSSTRATEGY:
1304 			if (part == RAW_PART)
1305 				break;
1306 		/* FALLTHROUGH */
1307 		default:
1308 			if ((periph->periph_flags & PERIPH_OPEN) == 0)
1309 				return (ENODEV);
1310 			else
1311 				return (EIO);
1312 		}
1313 	}
1314 
1315 	error = disk_ioctl(&cd->sc_dk, cmd, addr, flag, l);
1316 	if (error != EPASSTHROUGH)
1317 		return (error);
1318 
1319 	switch (cmd) {
1320 	case DIOCGDINFO:
1321 		*(struct disklabel *)addr = *(cd->sc_dk.dk_label);
1322 		return (0);
1323 #ifdef __HAVE_OLD_DISKLABEL
1324 	case ODIOCGDINFO:
1325 		newlabel = malloc(sizeof (*newlabel), M_TEMP, M_WAITOK);
1326 		if (newlabel == NULL)
1327 			return (EIO);
1328 		memcpy(newlabel, cd->sc_dk.dk_label, sizeof (*newlabel));
1329 		if (newlabel->d_npartitions > OLDMAXPARTITIONS)
1330 			error = ENOTTY;
1331 		else
1332 			memcpy(addr, newlabel, sizeof (struct olddisklabel));
1333 		free(newlabel, M_TEMP);
1334 		return error;
1335 #endif
1336 
1337 	case DIOCGPART:
1338 		((struct partinfo *)addr)->disklab = cd->sc_dk.dk_label;
1339 		((struct partinfo *)addr)->part =
1340 		    &cd->sc_dk.dk_label->d_partitions[part];
1341 		return (0);
1342 
1343 	case DIOCWDINFO:
1344 	case DIOCSDINFO:
1345 #ifdef __HAVE_OLD_DISKLABEL
1346 	case ODIOCWDINFO:
1347 	case ODIOCSDINFO:
1348 #endif
1349 	{
1350 		struct disklabel *lp;
1351 
1352 		if ((flag & FWRITE) == 0)
1353 			return (EBADF);
1354 
1355 #ifdef __HAVE_OLD_DISKLABEL
1356 		if (cmd == ODIOCSDINFO || cmd == ODIOCWDINFO) {
1357 			newlabel = malloc(sizeof (*newlabel), M_TEMP, M_WAITOK);
1358 			if (newlabel == NULL)
1359 				return (EIO);
1360 			memset(newlabel, 0, sizeof newlabel);
1361 			memcpy(newlabel, addr, sizeof (struct olddisklabel));
1362 			lp = newlabel;
1363 		} else
1364 #endif
1365 		lp = addr;
1366 
1367 		mutex_enter(&cd->sc_lock);
1368 		cd->flags |= CDF_LABELLING;
1369 
1370 		error = setdisklabel(cd->sc_dk.dk_label,
1371 		    lp, /*cd->sc_dk.dk_openmask : */0,
1372 		    cd->sc_dk.dk_cpulabel);
1373 		if (error == 0) {
1374 			/* XXX ? */
1375 		}
1376 
1377 		cd->flags &= ~CDF_LABELLING;
1378 		mutex_exit(&cd->sc_lock);
1379 #ifdef __HAVE_OLD_DISKLABEL
1380 		if (newlabel != NULL)
1381 			free(newlabel, M_TEMP);
1382 #endif
1383 		return (error);
1384 	}
1385 
1386 	case DIOCWLABEL:
1387 		return (EBADF);
1388 
1389 	case DIOCGDEFLABEL:
1390 		cdgetdefaultlabel(cd, &toc, addr);
1391 		return (0);
1392 
1393 #ifdef __HAVE_OLD_DISKLABEL
1394 	case ODIOCGDEFLABEL:
1395 		newlabel = malloc(sizeof (*newlabel), M_TEMP, M_WAITOK);
1396 		if (newlabel == NULL)
1397 			return (EIO);
1398 		cdgetdefaultlabel(cd, &toc, newlabel);
1399 		if (newlabel->d_npartitions > OLDMAXPARTITIONS)
1400 			error = ENOTTY;
1401 		else
1402 			memcpy(addr, newlabel, sizeof (struct olddisklabel));
1403 		free(newlabel, M_TEMP);
1404 		return error;
1405 #endif
1406 
1407 	case DIOCTUR: {
1408 		/* test unit ready */
1409 		error = scsipi_test_unit_ready(cd->sc_periph, XS_CTL_SILENT);
1410 		*((int*)addr) = (error == 0);
1411 		if (error == ENODEV || error == EIO || error == 0)
1412 			return 0;
1413 		return error;
1414 	}
1415 
1416 	case CDIOCPLAYTRACKS: {
1417 		/* PLAY_MSF command */
1418 		struct ioc_play_track *args = addr;
1419 
1420 		if ((error = cd_set_pa_immed(cd, 0)) != 0)
1421 			return (error);
1422 		return (cd_play_tracks(cd, &toc, args->start_track,
1423 		    args->start_index, args->end_track, args->end_index));
1424 	}
1425 	case CDIOCPLAYMSF: {
1426 		/* PLAY_MSF command */
1427 		struct ioc_play_msf *args = addr;
1428 
1429 		if ((error = cd_set_pa_immed(cd, 0)) != 0)
1430 			return (error);
1431 		return (cd_play_msf(cd, args->start_m, args->start_s,
1432 		    args->start_f, args->end_m, args->end_s, args->end_f));
1433 	}
1434 	case CDIOCPLAYBLOCKS: {
1435 		/* PLAY command */
1436 		struct ioc_play_blocks *args = addr;
1437 
1438 		if ((error = cd_set_pa_immed(cd, 0)) != 0)
1439 			return (error);
1440 		return (cd_play(cd, args->blk, args->len));
1441 	}
1442 	case CDIOCREADSUBCHANNEL: {
1443 		/* READ_SUBCHANNEL command */
1444 		struct ioc_read_subchannel *args = addr;
1445 		struct cd_sub_channel_info data;
1446 		u_int len = args->data_len;
1447 
1448 		if (len > sizeof(data) ||
1449 		    len < sizeof(struct cd_sub_channel_header))
1450 			return (EINVAL);
1451 		error = cd_read_subchannel(cd, args->address_format,
1452 		    args->data_format, args->track, &data, len, 0);
1453 		if (error)
1454 			return (error);
1455 		len = min(len, _2btol(data.header.data_len) +
1456 		    sizeof(struct cd_sub_channel_header));
1457 		return (copyout(&data, args->data, len));
1458 	}
1459 	case CDIOCREADSUBCHANNEL_BUF: {
1460 		/* As CDIOCREADSUBCHANNEL, but without a 2nd buffer area */
1461 		struct ioc_read_subchannel_buf *args = addr;
1462 		if (args->req.data_len != sizeof args->info)
1463 			return EINVAL;
1464 		return cd_read_subchannel(cd, args->req.address_format,
1465 		    args->req.data_format, args->req.track, &args->info,
1466 		    sizeof(args->info), 0);
1467 	}
1468 	case CDIOREADTOCHEADER: {
1469 		/* READ TOC format 0 command, static header */
1470 		if ((error = cd_read_toc(cd, CD_TOC_FORM, 0, 0,
1471 		    &toc, sizeof(toc.header), 0, 0)) != 0)
1472 			return (error);
1473 		if (cd->sc_periph->periph_quirks & PQUIRK_LITTLETOC)
1474 			toc.header.len = le16toh(toc.header.len);
1475 		else
1476 			toc.header.len = be16toh(toc.header.len);
1477 		memcpy(addr, &toc.header, sizeof(toc.header));
1478 		return (0);
1479 	}
1480 	case CDIOREADTOCENTRYS: {
1481 		struct ioc_read_toc_entry *te = addr;
1482 		error = do_cdioreadentries(cd, te, &toc);
1483 		if (error != 0)
1484 			return error;
1485 		return copyout(toc.entries, te->data, min(te->data_len,
1486 		    toc.header.len - (sizeof(toc.header.starting_track)
1487 			+ sizeof(toc.header.ending_track))));
1488 	}
1489 	case CDIOREADTOCENTRIES_BUF: {
1490 		struct ioc_read_toc_entry_buf *te = addr;
1491 		error = do_cdioreadentries(cd, &te->req, &toc);
1492 		if (error != 0)
1493 			return error;
1494 		memcpy(te->entry, toc.entries, min(te->req.data_len,
1495 		    toc.header.len - (sizeof(toc.header.starting_track)
1496 			+ sizeof(toc.header.ending_track))));
1497 		return 0;
1498 	}
1499 	case CDIOREADMSADDR: {
1500 		/* READ TOC format 0 command, length of first track only */
1501 		int sessno = *(int*)addr;
1502 
1503 		if (sessno != 0)
1504 			return (EINVAL);
1505 
1506 		return (cdreadmsaddr(cd, &toc, addr));
1507 	}
1508 	case CDIOCSETPATCH: {
1509 		struct ioc_patch *arg = addr;
1510 
1511 		return (cd_setchan(cd, arg->patch[0], arg->patch[1],
1512 		    arg->patch[2], arg->patch[3], 0));
1513 	}
1514 	case CDIOCGETVOL: {
1515 		/* MODE SENSE command (AUDIO page) */
1516 		struct ioc_vol *arg = addr;
1517 
1518 		return (cd_getvol(cd, arg, 0));
1519 	}
1520 	case CDIOCSETVOL: {
1521 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1522 		struct ioc_vol *arg = addr;
1523 
1524 		return (cd_setvol(cd, arg, 0));
1525 	}
1526 	case CDIOCSETMONO:
1527 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1528 		return (cd_setchan(cd, BOTH_CHANNEL, BOTH_CHANNEL,
1529 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1530 
1531 	case CDIOCSETSTEREO:
1532 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1533 		return (cd_setchan(cd, LEFT_CHANNEL, RIGHT_CHANNEL,
1534 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1535 
1536 	case CDIOCSETMUTE:
1537 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1538 		return (cd_setchan(cd, MUTE_CHANNEL, MUTE_CHANNEL,
1539 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1540 
1541 	case CDIOCSETLEFT:
1542 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1543 		return (cd_setchan(cd, LEFT_CHANNEL, LEFT_CHANNEL,
1544 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1545 
1546 	case CDIOCSETRIGHT:
1547 		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
1548 		return (cd_setchan(cd, RIGHT_CHANNEL, RIGHT_CHANNEL,
1549 		    MUTE_CHANNEL, MUTE_CHANNEL, 0));
1550 
1551 	case CDIOCRESUME:
1552 		/* PAUSE command */
1553 		return (cd_pause(cd, PA_RESUME));
1554 	case CDIOCPAUSE:
1555 		/* PAUSE command */
1556 		return (cd_pause(cd, PA_PAUSE));
1557 	case CDIOCSTART:
1558 		return (scsipi_start(periph, SSS_START, 0));
1559 	case CDIOCSTOP:
1560 		return (scsipi_start(periph, SSS_STOP, 0));
1561 	case CDIOCCLOSE:
1562 		return (scsipi_start(periph, SSS_START|SSS_LOEJ,
1563 		    XS_CTL_IGNORE_NOT_READY | XS_CTL_IGNORE_MEDIA_CHANGE));
1564 	case DIOCEJECT:
1565 		if (*(int *)addr == 0) {
1566 			/*
1567 			 * Don't force eject: check that we are the only
1568 			 * partition open. If so, unlock it.
1569 			 */
1570 			if ((cd->sc_dk.dk_openmask & ~(1 << part)) == 0 &&
1571 			    cd->sc_dk.dk_bopenmask + cd->sc_dk.dk_copenmask ==
1572 			    cd->sc_dk.dk_openmask) {
1573 				error = scsipi_prevent(periph, SPAMR_ALLOW,
1574 				    XS_CTL_IGNORE_NOT_READY);
1575 				if (error)
1576 					return (error);
1577 			} else {
1578 				return (EBUSY);
1579 			}
1580 		}
1581 		/* FALLTHROUGH */
1582 	case CDIOCEJECT: /* FALLTHROUGH */
1583 	case ODIOCEJECT:
1584 		return (scsipi_start(periph, SSS_STOP|SSS_LOEJ, 0));
1585 	case DIOCCACHESYNC:
1586 		/* SYNCHRONISE CACHES command */
1587 		return (cdcachesync(periph, 0));
1588 	case CDIOCALLOW:
1589 		return (scsipi_prevent(periph, SPAMR_ALLOW, 0));
1590 	case CDIOCPREVENT:
1591 		return (scsipi_prevent(periph, SPAMR_PREVENT_DT, 0));
1592 	case DIOCLOCK:
1593 		return (scsipi_prevent(periph,
1594 		    (*(int *)addr) ? SPAMR_PREVENT_DT : SPAMR_ALLOW, 0));
1595 	case CDIOCSETDEBUG:
1596 		cd->sc_periph->periph_dbflags |= (SCSIPI_DB1 | SCSIPI_DB2);
1597 		return (0);
1598 	case CDIOCCLRDEBUG:
1599 		cd->sc_periph->periph_dbflags &= ~(SCSIPI_DB1 | SCSIPI_DB2);
1600 		return (0);
1601 	case CDIOCRESET:
1602 	case SCIOCRESET:
1603 		return (cd_reset(cd));
1604 	case CDIOCLOADUNLOAD:
1605 		/* LOAD_UNLOAD command */
1606 		return (cd_load_unload(cd, addr));
1607 	case DVD_AUTH:
1608 		/* GPCMD_REPORT_KEY or GPCMD_SEND_KEY command */
1609 		return (dvd_auth(cd, addr));
1610 	case DVD_READ_STRUCT:
1611 		/* GPCMD_READ_DVD_STRUCTURE command */
1612 		return (dvd_read_struct(cd, addr));
1613 	case MMCGETDISCINFO:
1614 		/*
1615 		 * GET_CONFIGURATION, READ_DISCINFO, READ_TRACKINFO,
1616 		 * (READ_TOCf2, READ_CD_CAPACITY and GET_CONFIGURATION) commands
1617 		 */
1618 		return mmc_getdiscinfo(periph, (struct mmc_discinfo *) addr);
1619 	case MMCGETTRACKINFO:
1620 		/* READ TOCf2, READ_CD_CAPACITY and READ_TRACKINFO commands */
1621 		return mmc_gettrackinfo(periph, (struct mmc_trackinfo *) addr);
1622 	case MMCOP:
1623 		/*
1624 		 * CLOSE TRACK/SESSION, RESERVE_TRACK, REPAIR_TRACK,
1625 		 * SYNCHRONISE_CACHE commands
1626 		 */
1627 		return mmc_do_op(periph, (struct mmc_op *) addr);
1628 	case MMCSETUPWRITEPARAMS :
1629 		/* MODE SENSE page 5, MODE_SELECT page 5 commands */
1630 		return mmc_setup_writeparams(periph, (struct mmc_writeparams *) addr);
1631 	case DIOCGSTRATEGY:
1632 	    {
1633 		struct disk_strategy *dks = addr;
1634 
1635 		s = splbio();
1636 		strlcpy(dks->dks_name, bufq_getstrategyname(cd->buf_queue),
1637 		    sizeof(dks->dks_name));
1638 		splx(s);
1639 		dks->dks_paramlen = 0;
1640 
1641 		return 0;
1642 	    }
1643 	case DIOCSSTRATEGY:
1644 	    {
1645 		struct disk_strategy *dks = addr;
1646 		struct bufq_state *new;
1647 		struct bufq_state *old;
1648 
1649 		if ((flag & FWRITE) == 0) {
1650 			return EBADF;
1651 		}
1652 		if (dks->dks_param != NULL) {
1653 			return EINVAL;
1654 		}
1655 		dks->dks_name[sizeof(dks->dks_name) - 1] = 0; /* ensure term */
1656 		error = bufq_alloc(&new, dks->dks_name,
1657 		    BUFQ_EXACT|BUFQ_SORT_RAWBLOCK);
1658 		if (error) {
1659 			return error;
1660 		}
1661 		s = splbio();
1662 		old = cd->buf_queue;
1663 		bufq_move(new, old);
1664 		cd->buf_queue = new;
1665 		splx(s);
1666 		bufq_free(old);
1667 
1668 		return 0;
1669 	    }
1670 	default:
1671 		if (part != RAW_PART)
1672 			return (ENOTTY);
1673 		return (scsipi_do_ioctl(periph, dev, cmd, addr, flag, l));
1674 	}
1675 
1676 #ifdef DIAGNOSTIC
1677 	panic("cdioctl: impossible");
1678 #endif
1679 }
1680 
1681 static void
1682 cdgetdefaultlabel(struct cd_softc *cd, struct cd_formatted_toc *toc,
1683     struct disklabel *lp)
1684 {
1685 	int lastsession;
1686 
1687 	memset(lp, 0, sizeof(struct disklabel));
1688 
1689 	lp->d_secsize = cd->params.blksize;
1690 	lp->d_ntracks = 1;
1691 	lp->d_nsectors = 100;
1692 	lp->d_ncylinders = (cd->params.disksize / 100) + 1;
1693 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
1694 
1695 	switch (scsipi_periph_bustype(cd->sc_periph)) {
1696 	case SCSIPI_BUSTYPE_SCSI:
1697 		lp->d_type = DTYPE_SCSI;
1698 		break;
1699 	case SCSIPI_BUSTYPE_ATAPI:
1700 		lp->d_type = DTYPE_ATAPI;
1701 		break;
1702 	}
1703 	/*
1704 	 * XXX
1705 	 * We could probe the mode pages to figure out what kind of disc it is.
1706 	 * Is this worthwhile?
1707 	 */
1708 	strncpy(lp->d_typename, "optical media", 16);
1709 	strncpy(lp->d_packname, "fictitious", 16);
1710 	lp->d_secperunit = cd->params.disksize;
1711 	lp->d_rpm = 300;
1712 	lp->d_interleave = 1;
1713 	lp->d_flags = D_REMOVABLE | D_SCSI_MMC;
1714 
1715 	if (cdreadmsaddr(cd, toc, &lastsession) != 0)
1716 		lastsession = 0;
1717 
1718 	lp->d_partitions[0].p_offset = 0;
1719 	lp->d_partitions[0].p_size = lp->d_secperunit;
1720 	lp->d_partitions[0].p_cdsession = lastsession;
1721 	lp->d_partitions[0].p_fstype = FS_ISO9660;
1722 
1723 	lp->d_partitions[RAW_PART].p_offset = 0;
1724 	lp->d_partitions[RAW_PART].p_size = lp->d_secperunit;
1725 	lp->d_partitions[RAW_PART].p_fstype = FS_UDF;
1726 
1727 	lp->d_npartitions = RAW_PART + 1;
1728 
1729 	lp->d_magic = DISKMAGIC;
1730 	lp->d_magic2 = DISKMAGIC;
1731 	lp->d_checksum = dkcksum(lp);
1732 }
1733 
1734 /*
1735  * Load the label information on the named device
1736  * Actually fabricate a disklabel
1737  *
1738  * EVENTUALLY take information about different
1739  * data tracks from the TOC and put it in the disklabel
1740  */
1741 static void
1742 cdgetdisklabel(struct cd_softc *cd)
1743 {
1744 	struct disklabel *lp = cd->sc_dk.dk_label;
1745 	struct cd_formatted_toc toc;
1746 	const char *errstring;
1747 	int bmajor;
1748 
1749 	memset(cd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
1750 
1751 	cdgetdefaultlabel(cd, &toc, lp);
1752 
1753 	/*
1754 	 * Call the generic disklabel extraction routine
1755 	 *
1756 	 * bmajor follows ata_raid code
1757 	 */
1758 	bmajor = devsw_name2blk(device_xname(cd->sc_dev), NULL, 0);
1759 	errstring = readdisklabel(MAKECDDEV(bmajor,
1760 	    device_unit(cd->sc_dev), RAW_PART),
1761 	    cdstrategy, lp, cd->sc_dk.dk_cpulabel);
1762 
1763 	/* if all went OK, we are passed a NULL error string */
1764 	if (errstring == NULL)
1765 		return;
1766 
1767 	/* Reset to default label -- after printing error and the warning */
1768 	aprint_error_dev(cd->sc_dev, "%s\n", errstring);
1769 	memset(cd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
1770 	cdgetdefaultlabel(cd, &toc, lp);
1771 }
1772 
1773 /*
1774  * Reading a discs total capacity is aparently a very difficult issue for the
1775  * SCSI standardisation group. Every disc type seems to have its own
1776  * (re)invented size request method and modifiers. The failsafe way of
1777  * determining the total (max) capacity i.e. not the recorded capacity but the
1778  * total maximum capacity is to request the info on the last track and
1779  * calucate the total size.
1780  *
1781  * For ROM drives, we go for the CD recorded capacity. For recordable devices
1782  * we count.
1783  */
1784 static int
1785 read_cd_capacity(struct scsipi_periph *periph, u_int *blksize, u_long *size)
1786 {
1787 	struct scsipi_read_cd_capacity    cap_cmd;
1788 	struct scsipi_read_cd_cap_data    cap;
1789 	struct scsipi_read_discinfo       di_cmd;
1790 	struct scsipi_read_discinfo_data  di;
1791 	struct scsipi_read_trackinfo      ti_cmd;
1792 	struct scsipi_read_trackinfo_data ti;
1793 	uint32_t track_start, track_size;
1794 	int error, flags, msb, lsb, last_track;
1795 
1796 	/* if the device doesn't grog capacity, return the dummies */
1797 	if (periph->periph_quirks & PQUIRK_NOCAPACITY)
1798 		return 0;
1799 
1800 	/* first try read CD capacity for blksize and recorded size */
1801 	/* issue the cd capacity request */
1802 	flags = XS_CTL_DATA_IN;
1803 	memset(&cap_cmd, 0, sizeof(cap_cmd));
1804 	cap_cmd.opcode = READ_CD_CAPACITY;
1805 
1806 	error = scsipi_command(periph,
1807 	    (void *) &cap_cmd, sizeof(cap_cmd),
1808 	    (void *) &cap,     sizeof(cap),
1809 	    CDRETRIES, 30000, NULL, flags);
1810 	if (error)
1811 		return error;
1812 
1813 	/* retrieve values and sanity check them */
1814 	*blksize = _4btol(cap.length);
1815 	*size    = _4btol(cap.addr);
1816 
1817 	/* blksize is 2048 for CD, but some drives give gibberish */
1818 	if ((*blksize < 512) || ((*blksize & 511) != 0))
1819 		*blksize = 2048;	/* some drives lie ! */
1820 
1821 	/* recordables have READ_DISCINFO implemented */
1822 	flags = XS_CTL_DATA_IN | XS_CTL_SILENT;
1823 	memset(&di_cmd, 0, sizeof(di_cmd));
1824 	di_cmd.opcode = READ_DISCINFO;
1825 	_lto2b(READ_DISCINFO_BIGSIZE, di_cmd.data_len);
1826 
1827 	error = scsipi_command(periph,
1828 	    (void *) &di_cmd,  sizeof(di_cmd),
1829 	    (void *) &di,      READ_DISCINFO_BIGSIZE,
1830 	    CDRETRIES, 30000, NULL, flags);
1831 	if (error == 0) {
1832 		msb = di.last_track_last_session_msb;
1833 		lsb = di.last_track_last_session_lsb;
1834 		last_track = (msb << 8) | lsb;
1835 
1836 		/* request info on last track */
1837 		memset(&ti_cmd, 0, sizeof(ti_cmd));
1838 		ti_cmd.opcode = READ_TRACKINFO;
1839 		ti_cmd.addr_type = 1;			/* on tracknr */
1840 		_lto4b(last_track, ti_cmd.address);	/* tracknr    */
1841 		_lto2b(sizeof(ti), ti_cmd.data_len);
1842 
1843 		error = scsipi_command(periph,
1844 		    (void *) &ti_cmd,  sizeof(ti_cmd),
1845 		    (void *) &ti,      sizeof(ti),
1846 		    CDRETRIES, 30000, NULL, flags);
1847 		if (error == 0) {
1848 			track_start = _4btol(ti.track_start);
1849 			track_size  = _4btol(ti.track_size);
1850 
1851 			/* overwrite only with a sane value */
1852 			if (track_start + track_size >= 100)
1853 				*size = track_start + track_size;
1854 		}
1855 	}
1856 
1857 	/* sanity check for size */
1858 	if (*size < 100)
1859 		*size = 400000;
1860 
1861 	return 0;
1862 }
1863 
1864 /*
1865  * Find out from the device what it's capacity is
1866  */
1867 static u_long
1868 cd_size(struct cd_softc *cd, int flags)
1869 {
1870 	u_int blksize;
1871 	u_long size;
1872 	int error;
1873 
1874 	/* set up fake values */
1875 	blksize = 2048;
1876 	size    = 400000;
1877 
1878 	/* if this function bounces with an error return fake value */
1879 	error = read_cd_capacity(cd->sc_periph, &blksize, &size);
1880 	if (error)
1881 		return size;
1882 
1883 	if (blksize != 2048) {
1884 		if (cd_setblksize(cd) == 0) {
1885 			blksize = 2048;
1886 			error = read_cd_capacity(cd->sc_periph,
1887 			    &blksize, &size);
1888 			if (error)
1889 				return size;
1890 		}
1891 	}
1892 	cd->params.blksize     = blksize;
1893 	cd->params.disksize    = size;
1894 	cd->params.disksize512 = ((u_int64_t)cd->params.disksize * blksize) / DEV_BSIZE;
1895 
1896 	SC_DEBUG(cd->sc_periph, SCSIPI_DB2,
1897 	    ("cd_size: %u %lu\n", blksize, size));
1898 
1899 	return size;
1900 }
1901 
1902 /*
1903  * Get scsi driver to send a "start playing" command
1904  */
1905 static int
1906 cd_play(struct cd_softc *cd, int blkno, int nblks)
1907 {
1908 	struct scsipi_play cmd;
1909 
1910 	memset(&cmd, 0, sizeof(cmd));
1911 	cmd.opcode = PLAY;
1912 	_lto4b(blkno, cmd.blk_addr);
1913 	_lto2b(nblks, cmd.xfer_len);
1914 
1915 	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
1916 	    CDRETRIES, 30000, NULL, 0));
1917 }
1918 
1919 /*
1920  * Get scsi driver to send a "start playing" command
1921  */
1922 static int
1923 cd_play_tracks(struct cd_softc *cd, struct cd_formatted_toc *toc, int strack,
1924     int sindex, int etrack, int eindex)
1925 {
1926 	int error;
1927 
1928 	if (!etrack)
1929 		return (EIO);
1930 	if (strack > etrack)
1931 		return (EINVAL);
1932 
1933 	error = cd_load_toc(cd, CD_TOC_FORM, toc, 0);
1934 	if (error)
1935 		return (error);
1936 
1937 	if (++etrack > (toc->header.ending_track+1))
1938 		etrack = toc->header.ending_track+1;
1939 
1940 	strack -= toc->header.starting_track;
1941 	etrack -= toc->header.starting_track;
1942 	if (strack < 0)
1943 		return (EINVAL);
1944 
1945 	return (cd_play_msf(cd, toc->entries[strack].addr.msf.minute,
1946 	    toc->entries[strack].addr.msf.second,
1947 	    toc->entries[strack].addr.msf.frame,
1948 	    toc->entries[etrack].addr.msf.minute,
1949 	    toc->entries[etrack].addr.msf.second,
1950 	    toc->entries[etrack].addr.msf.frame));
1951 }
1952 
1953 /*
1954  * Get scsi driver to send a "play msf" command
1955  */
1956 static int
1957 cd_play_msf(struct cd_softc *cd, int startm, int starts, int startf, int endm,
1958     int ends, int endf)
1959 {
1960 	struct scsipi_play_msf cmd;
1961 
1962 	memset(&cmd, 0, sizeof(cmd));
1963 	cmd.opcode = PLAY_MSF;
1964 	cmd.start_m = startm;
1965 	cmd.start_s = starts;
1966 	cmd.start_f = startf;
1967 	cmd.end_m = endm;
1968 	cmd.end_s = ends;
1969 	cmd.end_f = endf;
1970 
1971 	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
1972 	    CDRETRIES, 30000, NULL, 0));
1973 }
1974 
1975 /*
1976  * Get scsi driver to send a "start up" command
1977  */
1978 static int
1979 cd_pause(struct cd_softc *cd, int go)
1980 {
1981 	struct scsipi_pause cmd;
1982 
1983 	memset(&cmd, 0, sizeof(cmd));
1984 	cmd.opcode = PAUSE;
1985 	cmd.resume = go & 0xff;
1986 
1987 	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
1988 	    CDRETRIES, 30000, NULL, 0));
1989 }
1990 
1991 /*
1992  * Get scsi driver to send a "RESET" command
1993  */
1994 static int
1995 cd_reset(struct cd_softc *cd)
1996 {
1997 
1998 	return (scsipi_command(cd->sc_periph, 0, 0, 0, 0,
1999 	    CDRETRIES, 30000, NULL, XS_CTL_RESET));
2000 }
2001 
2002 /*
2003  * Read subchannel
2004  */
2005 static int
2006 cd_read_subchannel(struct cd_softc *cd, int mode, int format, int track,
2007     struct cd_sub_channel_info *data, int len, int flags)
2008 {
2009 	struct scsipi_read_subchannel cmd;
2010 
2011 	memset(&cmd, 0, sizeof(cmd));
2012 	cmd.opcode = READ_SUBCHANNEL;
2013 	if (mode == CD_MSF_FORMAT)
2014 		cmd.byte2 |= CD_MSF;
2015 	cmd.byte3 = SRS_SUBQ;
2016 	cmd.subchan_format = format;
2017 	cmd.track = track;
2018 	_lto2b(len, cmd.data_len);
2019 
2020 	return (scsipi_command(cd->sc_periph,
2021 	    (void *)&cmd, sizeof(struct scsipi_read_subchannel),
2022 	    (void *)data, len,
2023 	    CDRETRIES, 30000, NULL, flags | XS_CTL_DATA_IN | XS_CTL_SILENT));
2024 }
2025 
2026 /*
2027  * Read table of contents
2028  */
2029 static int
2030 cd_read_toc(struct cd_softc *cd, int respf, int mode, int start,
2031     struct cd_formatted_toc *toc, int len, int flags, int control)
2032 {
2033 	struct scsipi_read_toc cmd;
2034 	int ntoc;
2035 
2036 	memset(&cmd, 0, sizeof(cmd));
2037 #if 0
2038 	if (len != sizeof(struct ioc_toc_header))
2039 		ntoc = ((len) - sizeof(struct ioc_toc_header)) /
2040 		    sizeof(struct cd_toc_entry);
2041 	else
2042 #endif
2043 	ntoc = len;
2044 	cmd.opcode = READ_TOC;
2045 	if (mode == CD_MSF_FORMAT)
2046 		cmd.addr_mode |= CD_MSF;
2047 	cmd.resp_format = respf;
2048 	cmd.from_track = start;
2049 	_lto2b(ntoc, cmd.data_len);
2050 	cmd.control = control;
2051 
2052 	return (scsipi_command(cd->sc_periph,
2053 	    (void *)&cmd, sizeof(cmd), (void *)toc, len, CDRETRIES,
2054 	    30000, NULL, flags | XS_CTL_DATA_IN));
2055 }
2056 
2057 static int
2058 cd_load_toc(struct cd_softc *cd, int respf, struct cd_formatted_toc *toc, int flags)
2059 {
2060 	int ntracks, len, error;
2061 
2062 	if ((error = cd_read_toc(cd, respf, 0, 0, toc, sizeof(toc->header),
2063 	    flags, 0)) != 0)
2064 		return (error);
2065 
2066 	ntracks = toc->header.ending_track - toc->header.starting_track + 1;
2067 	len = (ntracks + 1) * sizeof(struct cd_toc_entry) +
2068 	    sizeof(toc->header);
2069 	if ((error = cd_read_toc(cd, respf, CD_MSF_FORMAT, 0, toc, len,
2070 	    flags, 0)) != 0)
2071 		return (error);
2072 	return (0);
2073 }
2074 
2075 /*
2076  * Get the scsi driver to send a full inquiry to the device and use the
2077  * results to fill out the disk parameter structure.
2078  */
2079 static int
2080 cd_get_parms(struct cd_softc *cd, int flags)
2081 {
2082 
2083 	/*
2084 	 * give a number of sectors so that sec * trks * cyls
2085 	 * is <= disk_size
2086 	 */
2087 	if (cd_size(cd, flags) == 0)
2088 		return (ENXIO);
2089 	disk_blocksize(&cd->sc_dk, cd->params.blksize);
2090 	return (0);
2091 }
2092 
2093 static int
2094 cdsize(dev_t dev)
2095 {
2096 
2097 	/* CD-ROMs are read-only. */
2098 	return (-1);
2099 }
2100 
2101 static int
2102 cddump(dev_t dev, daddr_t blkno, void *va, size_t size)
2103 {
2104 
2105 	/* Not implemented. */
2106 	return (ENXIO);
2107 }
2108 
2109 #define	dvd_copy_key(dst, src)		memcpy((dst), (src), sizeof(dvd_key))
2110 #define	dvd_copy_challenge(dst, src)	memcpy((dst), (src), sizeof(dvd_challenge))
2111 
2112 static int
2113 dvd_auth(struct cd_softc *cd, dvd_authinfo *a)
2114 {
2115 	struct scsipi_generic cmd;
2116 	u_int8_t bf[20];
2117 	int error;
2118 
2119 	memset(cmd.bytes, 0, 15);
2120 	memset(bf, 0, sizeof(bf));
2121 
2122 	switch (a->type) {
2123 	case DVD_LU_SEND_AGID:
2124 		cmd.opcode = GPCMD_REPORT_KEY;
2125 		cmd.bytes[8] = 8;
2126 		cmd.bytes[9] = 0 | (0 << 6);
2127 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
2128 		    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
2129 		if (error)
2130 			return (error);
2131 		a->lsa.agid = bf[7] >> 6;
2132 		return (0);
2133 
2134 	case DVD_LU_SEND_CHALLENGE:
2135 		cmd.opcode = GPCMD_REPORT_KEY;
2136 		cmd.bytes[8] = 16;
2137 		cmd.bytes[9] = 1 | (a->lsc.agid << 6);
2138 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 16,
2139 		    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
2140 		if (error)
2141 			return (error);
2142 		dvd_copy_challenge(a->lsc.chal, &bf[4]);
2143 		return (0);
2144 
2145 	case DVD_LU_SEND_KEY1:
2146 		cmd.opcode = GPCMD_REPORT_KEY;
2147 		cmd.bytes[8] = 12;
2148 		cmd.bytes[9] = 2 | (a->lsk.agid << 6);
2149 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 12,
2150 		    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
2151 		if (error)
2152 			return (error);
2153 		dvd_copy_key(a->lsk.key, &bf[4]);
2154 		return (0);
2155 
2156 	case DVD_LU_SEND_TITLE_KEY:
2157 		cmd.opcode = GPCMD_REPORT_KEY;
2158 		_lto4b(a->lstk.lba, &cmd.bytes[1]);
2159 		cmd.bytes[8] = 12;
2160 		cmd.bytes[9] = 4 | (a->lstk.agid << 6);
2161 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 12,
2162 		    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
2163 		if (error)
2164 			return (error);
2165 		a->lstk.cpm = (bf[4] >> 7) & 1;
2166 		a->lstk.cp_sec = (bf[4] >> 6) & 1;
2167 		a->lstk.cgms = (bf[4] >> 4) & 3;
2168 		dvd_copy_key(a->lstk.title_key, &bf[5]);
2169 		return (0);
2170 
2171 	case DVD_LU_SEND_ASF:
2172 		cmd.opcode = GPCMD_REPORT_KEY;
2173 		cmd.bytes[8] = 8;
2174 		cmd.bytes[9] = 5 | (a->lsasf.agid << 6);
2175 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
2176 		    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
2177 		if (error)
2178 			return (error);
2179 		a->lsasf.asf = bf[7] & 1;
2180 		return (0);
2181 
2182 	case DVD_HOST_SEND_CHALLENGE:
2183 		cmd.opcode = GPCMD_SEND_KEY;
2184 		cmd.bytes[8] = 16;
2185 		cmd.bytes[9] = 1 | (a->hsc.agid << 6);
2186 		bf[1] = 14;
2187 		dvd_copy_challenge(&bf[4], a->hsc.chal);
2188 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 16,
2189 		    CDRETRIES, 30000, NULL, XS_CTL_DATA_OUT);
2190 		if (error)
2191 			return (error);
2192 		a->type = DVD_LU_SEND_KEY1;
2193 		return (0);
2194 
2195 	case DVD_HOST_SEND_KEY2:
2196 		cmd.opcode = GPCMD_SEND_KEY;
2197 		cmd.bytes[8] = 12;
2198 		cmd.bytes[9] = 3 | (a->hsk.agid << 6);
2199 		bf[1] = 10;
2200 		dvd_copy_key(&bf[4], a->hsk.key);
2201 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 12,
2202 		    CDRETRIES, 30000, NULL, XS_CTL_DATA_OUT);
2203 		if (error) {
2204 			a->type = DVD_AUTH_FAILURE;
2205 			return (error);
2206 		}
2207 		a->type = DVD_AUTH_ESTABLISHED;
2208 		return (0);
2209 
2210 	case DVD_INVALIDATE_AGID:
2211 		cmd.opcode = GPCMD_REPORT_KEY;
2212 		cmd.bytes[9] = 0x3f | (a->lsa.agid << 6);
2213 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 16,
2214 		    CDRETRIES, 30000, NULL, 0);
2215 		if (error)
2216 			return (error);
2217 		return (0);
2218 
2219 	case DVD_LU_SEND_RPC_STATE:
2220 		cmd.opcode = GPCMD_REPORT_KEY;
2221 		cmd.bytes[8] = 8;
2222 		cmd.bytes[9] = 8 | (0 << 6);
2223 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
2224 		    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
2225 		if (error)
2226 			return (error);
2227 		a->lrpcs.type = (bf[4] >> 6) & 3;
2228 		a->lrpcs.vra = (bf[4] >> 3) & 7;
2229 		a->lrpcs.ucca = (bf[4]) & 7;
2230 		a->lrpcs.region_mask = bf[5];
2231 		a->lrpcs.rpc_scheme = bf[6];
2232 		return (0);
2233 
2234 	case DVD_HOST_SEND_RPC_STATE:
2235 		cmd.opcode = GPCMD_SEND_KEY;
2236 		cmd.bytes[8] = 8;
2237 		cmd.bytes[9] = 6 | (0 << 6);
2238 		bf[1] = 6;
2239 		bf[4] = a->hrpcs.pdrc;
2240 		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
2241 		    CDRETRIES, 30000, NULL, XS_CTL_DATA_OUT);
2242 		if (error)
2243 			return (error);
2244 		return (0);
2245 
2246 	default:
2247 		return (ENOTTY);
2248 	}
2249 }
2250 
2251 static int
2252 dvd_read_physical(struct cd_softc *cd, dvd_struct *s)
2253 {
2254 	struct scsipi_generic cmd;
2255 	u_int8_t bf[4 + 4 * 20], *bufp;
2256 	int error;
2257 	struct dvd_layer *layer;
2258 	int i;
2259 
2260 	memset(cmd.bytes, 0, 15);
2261 	memset(bf, 0, sizeof(bf));
2262 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2263 	cmd.bytes[6] = s->type;
2264 	_lto2b(sizeof(bf), &cmd.bytes[7]);
2265 
2266 	cmd.bytes[5] = s->physical.layer_num;
2267 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, sizeof(bf),
2268 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
2269 	if (error)
2270 		return (error);
2271 	for (i = 0, bufp = &bf[4], layer = &s->physical.layer[0]; i < 4;
2272 	     i++, bufp += 20, layer++) {
2273 		memset(layer, 0, sizeof(*layer));
2274                 layer->book_version = bufp[0] & 0xf;
2275                 layer->book_type = bufp[0] >> 4;
2276                 layer->min_rate = bufp[1] & 0xf;
2277                 layer->disc_size = bufp[1] >> 4;
2278                 layer->layer_type = bufp[2] & 0xf;
2279                 layer->track_path = (bufp[2] >> 4) & 1;
2280                 layer->nlayers = (bufp[2] >> 5) & 3;
2281                 layer->track_density = bufp[3] & 0xf;
2282                 layer->linear_density = bufp[3] >> 4;
2283                 layer->start_sector = _4btol(&bufp[4]);
2284                 layer->end_sector = _4btol(&bufp[8]);
2285                 layer->end_sector_l0 = _4btol(&bufp[12]);
2286                 layer->bca = bufp[16] >> 7;
2287 	}
2288 	return (0);
2289 }
2290 
2291 static int
2292 dvd_read_copyright(struct cd_softc *cd, dvd_struct *s)
2293 {
2294 	struct scsipi_generic cmd;
2295 	u_int8_t bf[8];
2296 	int error;
2297 
2298 	memset(cmd.bytes, 0, 15);
2299 	memset(bf, 0, sizeof(bf));
2300 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2301 	cmd.bytes[6] = s->type;
2302 	_lto2b(sizeof(bf), &cmd.bytes[7]);
2303 
2304 	cmd.bytes[5] = s->copyright.layer_num;
2305 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, sizeof(bf),
2306 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
2307 	if (error)
2308 		return (error);
2309 	s->copyright.cpst = bf[4];
2310 	s->copyright.rmi = bf[5];
2311 	return (0);
2312 }
2313 
2314 static int
2315 dvd_read_disckey(struct cd_softc *cd, dvd_struct *s)
2316 {
2317 	struct scsipi_generic cmd;
2318 	u_int8_t *bf;
2319 	int error;
2320 
2321 	bf = malloc(4 + 2048, M_TEMP, M_WAITOK|M_ZERO);
2322 	if (bf == NULL)
2323 		return EIO;
2324 	memset(cmd.bytes, 0, 15);
2325 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2326 	cmd.bytes[6] = s->type;
2327 	_lto2b(4 + 2048, &cmd.bytes[7]);
2328 
2329 	cmd.bytes[9] = s->disckey.agid << 6;
2330 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 4 + 2048,
2331 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
2332 	if (error == 0)
2333 		memcpy(s->disckey.value, &bf[4], 2048);
2334 	free(bf, M_TEMP);
2335 	return error;
2336 }
2337 
2338 static int
2339 dvd_read_bca(struct cd_softc *cd, dvd_struct *s)
2340 {
2341 	struct scsipi_generic cmd;
2342 	u_int8_t bf[4 + 188];
2343 	int error;
2344 
2345 	memset(cmd.bytes, 0, 15);
2346 	memset(bf, 0, sizeof(bf));
2347 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2348 	cmd.bytes[6] = s->type;
2349 	_lto2b(sizeof(bf), &cmd.bytes[7]);
2350 
2351 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, sizeof(bf),
2352 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
2353 	if (error)
2354 		return (error);
2355 	s->bca.len = _2btol(&bf[0]);
2356 	if (s->bca.len < 12 || s->bca.len > 188)
2357 		return (EIO);
2358 	memcpy(s->bca.value, &bf[4], s->bca.len);
2359 	return (0);
2360 }
2361 
2362 static int
2363 dvd_read_manufact(struct cd_softc *cd, dvd_struct *s)
2364 {
2365 	struct scsipi_generic cmd;
2366 	u_int8_t *bf;
2367 	int error;
2368 
2369 	bf = malloc(4 + 2048, M_TEMP, M_WAITOK|M_ZERO);
2370 	if (bf == NULL)
2371 		return (EIO);
2372 	memset(cmd.bytes, 0, 15);
2373 	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
2374 	cmd.bytes[6] = s->type;
2375 	_lto2b(4 + 2048, &cmd.bytes[7]);
2376 
2377 	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 4 + 2048,
2378 	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
2379 	if (error == 0) {
2380 		s->manufact.len = _2btol(&bf[0]);
2381 		if (s->manufact.len >= 0 && s->manufact.len <= 2048)
2382 			memcpy(s->manufact.value, &bf[4], s->manufact.len);
2383 		else
2384 			error = EIO;
2385 	}
2386 	free(bf, M_TEMP);
2387 	return error;
2388 }
2389 
2390 static int
2391 dvd_read_struct(struct cd_softc *cd, dvd_struct *s)
2392 {
2393 
2394 	switch (s->type) {
2395 	case DVD_STRUCT_PHYSICAL:
2396 		return (dvd_read_physical(cd, s));
2397 	case DVD_STRUCT_COPYRIGHT:
2398 		return (dvd_read_copyright(cd, s));
2399 	case DVD_STRUCT_DISCKEY:
2400 		return (dvd_read_disckey(cd, s));
2401 	case DVD_STRUCT_BCA:
2402 		return (dvd_read_bca(cd, s));
2403 	case DVD_STRUCT_MANUFACT:
2404 		return (dvd_read_manufact(cd, s));
2405 	default:
2406 		return (EINVAL);
2407 	}
2408 }
2409 
2410 static int
2411 cd_mode_sense(struct cd_softc *cd, u_int8_t byte2, void *sense, size_t size,
2412     int page, int flags, int *big)
2413 {
2414 
2415 	if (cd->sc_periph->periph_quirks & PQUIRK_ONLYBIG) {
2416 		*big = 1;
2417 		return scsipi_mode_sense_big(cd->sc_periph, byte2, page, sense,
2418 		    size + sizeof(struct scsi_mode_parameter_header_10),
2419 		    flags, CDRETRIES, 20000);
2420 	} else {
2421 		*big = 0;
2422 		return scsipi_mode_sense(cd->sc_periph, byte2, page, sense,
2423 		    size + sizeof(struct scsi_mode_parameter_header_6),
2424 		    flags, CDRETRIES, 20000);
2425 	}
2426 }
2427 
2428 static int
2429 cd_mode_select(struct cd_softc *cd, u_int8_t byte2, void *sense, size_t size,
2430     int flags, int big)
2431 {
2432 
2433 	if (big) {
2434 		struct scsi_mode_parameter_header_10 *header = sense;
2435 
2436 		_lto2b(0, header->data_length);
2437 		return scsipi_mode_select_big(cd->sc_periph, byte2, sense,
2438 		    size + sizeof(struct scsi_mode_parameter_header_10),
2439 		    flags, CDRETRIES, 20000);
2440 	} else {
2441 		struct scsi_mode_parameter_header_6 *header = sense;
2442 
2443 		header->data_length = 0;
2444 		return scsipi_mode_select(cd->sc_periph, byte2, sense,
2445 		    size + sizeof(struct scsi_mode_parameter_header_6),
2446 		    flags, CDRETRIES, 20000);
2447 	}
2448 }
2449 
2450 static int
2451 cd_set_pa_immed(struct cd_softc *cd, int flags)
2452 {
2453 	struct {
2454 		union {
2455 			struct scsi_mode_parameter_header_6 small;
2456 			struct scsi_mode_parameter_header_10 big;
2457 		} header;
2458 		struct cd_audio_page page;
2459 	} data;
2460 	int error;
2461 	uint8_t oflags;
2462 	int big, byte2;
2463 	struct cd_audio_page *page;
2464 
2465 	byte2 = SMS_DBD;
2466 try_again:
2467 	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
2468 	    AUDIO_PAGE, flags, &big)) != 0) {
2469 		if (byte2 == SMS_DBD) {
2470 			/* Device may not understand DBD; retry without */
2471 			byte2 = 0;
2472 			goto try_again;
2473 		}
2474 		return (error);
2475 	}
2476 
2477 	if (big)
2478 		page = (void *)((u_long)&data.header.big +
2479 				sizeof data.header.big +
2480 				_2btol(data.header.big.blk_desc_len));
2481 	else
2482 		page = (void *)((u_long)&data.header.small +
2483 				sizeof data.header.small +
2484 				data.header.small.blk_desc_len);
2485 
2486 	oflags = page->flags;
2487 	page->flags &= ~CD_PA_SOTC;
2488 	page->flags |= CD_PA_IMMED;
2489 	if (oflags == page->flags)
2490 		return (0);
2491 
2492 	return (cd_mode_select(cd, SMS_PF, &data,
2493 	    sizeof(struct scsi_mode_page_header) + page->pg_length,
2494 	    flags, big));
2495 }
2496 
2497 static int
2498 cd_setchan(struct cd_softc *cd, int p0, int p1, int p2, int p3, int flags)
2499 {
2500 	struct {
2501 		union {
2502 			struct scsi_mode_parameter_header_6 small;
2503 			struct scsi_mode_parameter_header_10 big;
2504 		} header;
2505 		struct cd_audio_page page;
2506 	} data;
2507 	int error;
2508 	int big, byte2;
2509 	struct cd_audio_page *page;
2510 
2511 	byte2 = SMS_DBD;
2512 try_again:
2513 	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
2514 	    AUDIO_PAGE, flags, &big)) != 0) {
2515 		if (byte2 == SMS_DBD) {
2516 			/* Device may not understand DBD; retry without */
2517 			byte2 = 0;
2518 			goto try_again;
2519 		}
2520 		return (error);
2521 	}
2522 
2523 	if (big)
2524 		page = (void *)((u_long)&data.header.big +
2525 				sizeof data.header.big +
2526 				_2btol(data.header.big.blk_desc_len));
2527 	else
2528 		page = (void *)((u_long)&data.header.small +
2529 				sizeof data.header.small +
2530 				data.header.small.blk_desc_len);
2531 
2532 	page->port[0].channels = p0;
2533 	page->port[1].channels = p1;
2534 	page->port[2].channels = p2;
2535 	page->port[3].channels = p3;
2536 
2537 	return (cd_mode_select(cd, SMS_PF, &data,
2538 	    sizeof(struct scsi_mode_page_header) + page->pg_length,
2539 	    flags, big));
2540 }
2541 
2542 static int
2543 cd_getvol(struct cd_softc *cd, struct ioc_vol *arg, int flags)
2544 {
2545 	struct {
2546 		union {
2547 			struct scsi_mode_parameter_header_6 small;
2548 			struct scsi_mode_parameter_header_10 big;
2549 		} header;
2550 		struct cd_audio_page page;
2551 	} data;
2552 	int error;
2553 	int big, byte2;
2554 	struct cd_audio_page *page;
2555 
2556 	byte2 = SMS_DBD;
2557 try_again:
2558 	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
2559 	    AUDIO_PAGE, flags, &big)) != 0) {
2560 		if (byte2 == SMS_DBD) {
2561 			/* Device may not understand DBD; retry without */
2562 			byte2 = 0;
2563 			goto try_again;
2564 		}
2565 		return (error);
2566 	}
2567 
2568 	if (big)
2569 		page = (void *)((u_long)&data.header.big +
2570 				sizeof data.header.big +
2571 				_2btol(data.header.big.blk_desc_len));
2572 	else
2573 		page = (void *)((u_long)&data.header.small +
2574 				sizeof data.header.small +
2575 				data.header.small.blk_desc_len);
2576 
2577 	arg->vol[0] = page->port[0].volume;
2578 	arg->vol[1] = page->port[1].volume;
2579 	arg->vol[2] = page->port[2].volume;
2580 	arg->vol[3] = page->port[3].volume;
2581 
2582 	return (0);
2583 }
2584 
2585 static int
2586 cd_setvol(struct cd_softc *cd, const struct ioc_vol *arg, int flags)
2587 {
2588 	struct {
2589 		union {
2590 			struct scsi_mode_parameter_header_6 small;
2591 			struct scsi_mode_parameter_header_10 big;
2592 		} header;
2593 		struct cd_audio_page page;
2594 	} data, mask;
2595 	int error;
2596 	int big, byte2;
2597 	struct cd_audio_page *page, *page2;
2598 
2599 	byte2 = SMS_DBD;
2600 try_again:
2601 	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
2602 	    AUDIO_PAGE, flags, &big)) != 0) {
2603 		if (byte2 == SMS_DBD) {
2604 			/* Device may not understand DBD; retry without */
2605 			byte2 = 0;
2606 			goto try_again;
2607 		}
2608 		return (error);
2609 	}
2610 	if ((error = cd_mode_sense(cd, byte2, &mask, sizeof(mask.page),
2611 	    AUDIO_PAGE|SMS_PCTRL_CHANGEABLE, flags, &big)) != 0)
2612 		return (error);
2613 
2614 	if (big) {
2615 		page = (void *)((u_long)&data.header.big +
2616 				sizeof data.header.big +
2617 				_2btol(data.header.big.blk_desc_len));
2618 		page2 = (void *)((u_long)&mask.header.big +
2619 				sizeof mask.header.big +
2620 				_2btol(mask.header.big.blk_desc_len));
2621 	} else {
2622 		page = (void *)((u_long)&data.header.small +
2623 				sizeof data.header.small +
2624 				data.header.small.blk_desc_len);
2625 		page2 = (void *)((u_long)&mask.header.small +
2626 				sizeof mask.header.small +
2627 				mask.header.small.blk_desc_len);
2628 	}
2629 
2630 	page->port[0].volume = arg->vol[0] & page2->port[0].volume;
2631 	page->port[1].volume = arg->vol[1] & page2->port[1].volume;
2632 	page->port[2].volume = arg->vol[2] & page2->port[2].volume;
2633 	page->port[3].volume = arg->vol[3] & page2->port[3].volume;
2634 
2635 	page->port[0].channels = CHANNEL_0;
2636 	page->port[1].channels = CHANNEL_1;
2637 
2638 	return (cd_mode_select(cd, SMS_PF, &data,
2639 	    sizeof(struct scsi_mode_page_header) + page->pg_length,
2640 	    flags, big));
2641 }
2642 
2643 static int
2644 cd_load_unload(struct cd_softc *cd, struct ioc_load_unload *args)
2645 {
2646 	struct scsipi_load_unload cmd;
2647 
2648 	memset(&cmd, 0, sizeof(cmd));
2649 	cmd.opcode = LOAD_UNLOAD;
2650 	cmd.options = args->options;    /* ioctl uses MMC values */
2651 	cmd.slot = args->slot;
2652 
2653 	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
2654 	    CDRETRIES, 200000, NULL, 0));
2655 }
2656 
2657 static int
2658 cd_setblksize(struct cd_softc *cd)
2659 {
2660 	struct {
2661 		union {
2662 			struct scsi_mode_parameter_header_6 small;
2663 			struct scsi_mode_parameter_header_10 big;
2664 		} header;
2665 		struct scsi_general_block_descriptor blk_desc;
2666 	} data;
2667 	int error;
2668 	int big, bsize;
2669 	struct scsi_general_block_descriptor *bdesc;
2670 
2671 	if ((error = cd_mode_sense(cd, 0, &data, sizeof(data.blk_desc), 0, 0,
2672 	    &big)) != 0)
2673 		return (error);
2674 
2675 	if (big) {
2676 		bdesc = (void *)(&data.header.big + 1);
2677 		bsize = _2btol(data.header.big.blk_desc_len);
2678 	} else {
2679 		bdesc = (void *)(&data.header.small + 1);
2680 		bsize = data.header.small.blk_desc_len;
2681 	}
2682 
2683 	if (bsize == 0) {
2684 printf("cd_setblksize: trying to change bsize, but no blk_desc\n");
2685 		return (EINVAL);
2686 	}
2687 	if (_3btol(bdesc->blklen) == 2048) {
2688 printf("cd_setblksize: trying to change bsize, but blk_desc is correct\n");
2689 		return (EINVAL);
2690 	}
2691 
2692 	_lto3b(2048, bdesc->blklen);
2693 
2694 	return (cd_mode_select(cd, SMS_PF, &data, sizeof(data.blk_desc), 0,
2695 	    big));
2696 }
2697 
2698 
2699 static int
2700 mmc_profile2class(uint16_t mmc_profile)
2701 {
2702 	switch (mmc_profile) {
2703 	case 0x01 : /* SCSI discs */
2704 	case 0x02 :
2705 		/* this can't happen really, cd.c wouldn't have matched */
2706 		return MMC_CLASS_DISC;
2707 	case 0x03 : /* Magneto Optical with sector erase */
2708 	case 0x04 : /* Magneto Optical write once        */
2709 	case 0x05 : /* Advance Storage Magneto Optical   */
2710 		return MMC_CLASS_MO;
2711 	case 0x00 : /* Unknown MMC profile, can also be CD-ROM */
2712 	case 0x08 : /* CD-ROM  */
2713 	case 0x09 : /* CD-R    */
2714 	case 0x0a : /* CD-RW   */
2715 		return MMC_CLASS_CD;
2716 	case 0x10 : /* DVD-ROM */
2717 	case 0x11 : /* DVD-R   */
2718 	case 0x12 : /* DVD-RAM */
2719 	case 0x13 : /* DVD-RW restricted overwrite */
2720 	case 0x14 : /* DVD-RW sequential */
2721 	case 0x1a : /* DVD+RW  */
2722 	case 0x1b : /* DVD+R   */
2723 	case 0x2a : /* DVD+RW Dual layer */
2724 	case 0x2b : /* DVD+R Dual layer */
2725 	case 0x50 : /* HD DVD-ROM */
2726 	case 0x51 : /* HD DVD-R   */
2727 	case 0x52 : /* HD DVD-RW; DVD-RAM like */
2728 		return MMC_CLASS_DVD;
2729 	case 0x40 : /* BD-ROM  */
2730 	case 0x41 : /* BD-R Sequential recording (SRM) */
2731 	case 0x42 : /* BD-R Ramdom Recording (RRM) */
2732 	case 0x43 : /* BD-RE */
2733 		return MMC_CLASS_BD;
2734 	}
2735 	return MMC_CLASS_UNKN;
2736 }
2737 
2738 
2739 /*
2740  * Drive/media combination is reflected in a series of features that can
2741  * either be current or dormant. We try to make sense out of them to create a
2742  * set of easy to use flags that abstract the device/media capabilities.
2743  */
2744 
2745 static void
2746 mmc_process_feature(struct mmc_discinfo *mmc_discinfo,
2747 		    uint16_t feature, int cur, uint8_t *rpos)
2748 {
2749 	uint32_t blockingnr;
2750 	uint64_t flags;
2751 
2752 	if (cur == 1) {
2753 		flags = mmc_discinfo->mmc_cur;
2754 	} else {
2755 		flags = mmc_discinfo->mmc_cap;
2756 	}
2757 
2758 	switch (feature) {
2759 	case 0x0010 :	/* random readable feature */
2760 		blockingnr  =  rpos[5] | (rpos[4] << 8);
2761 		if (blockingnr > 1)
2762 			flags |= MMC_CAP_PACKET;
2763 
2764 		/* RW error page */
2765 		break;
2766 	case 0x0020 :	/* random writable feature */
2767 		flags |= MMC_CAP_RECORDABLE;
2768 		flags |= MMC_CAP_REWRITABLE;
2769 		blockingnr  =  rpos[9] | (rpos[8] << 8);
2770 		if (blockingnr > 1)
2771 			flags |= MMC_CAP_PACKET;
2772 		break;
2773 	case 0x0021 :	/* incremental streaming write feature */
2774 		flags |= MMC_CAP_RECORDABLE;
2775 		flags |= MMC_CAP_SEQUENTIAL;
2776 		if (cur)
2777 			mmc_discinfo->link_block_penalty = rpos[4];
2778 		if (rpos[2] & 1)
2779 			flags |= MMC_CAP_ZEROLINKBLK;
2780 		break;
2781 	case 0x0022 : 	/* (obsolete) erase support feature */
2782 		flags |= MMC_CAP_RECORDABLE;
2783 		flags |= MMC_CAP_ERASABLE;
2784 		break;
2785 	case 0x0023 :	/* formatting media support feature */
2786 		flags |= MMC_CAP_RECORDABLE;
2787 		flags |= MMC_CAP_FORMATTABLE;
2788 		break;
2789 	case 0x0024 :	/* hardware assised defect management feature */
2790 		flags |= MMC_CAP_HW_DEFECTFREE;
2791 		break;
2792 	case 0x0025 : 	/* write once */
2793 		flags |= MMC_CAP_RECORDABLE;
2794 		break;
2795 	case 0x0026 :	/* restricted overwrite feature */
2796 		flags |= MMC_CAP_RECORDABLE;
2797 		flags |= MMC_CAP_REWRITABLE;
2798 		flags |= MMC_CAP_STRICTOVERWRITE;
2799 		break;
2800 	case 0x0028 :	/* MRW formatted media support feature */
2801 		flags |= MMC_CAP_MRW;
2802 		break;
2803 	case 0x002b :	/* DVD+R read (and opt. write) support */
2804 		flags |= MMC_CAP_SEQUENTIAL;
2805 		if (rpos[0] & 1) /* write support */
2806 			flags |= MMC_CAP_RECORDABLE;
2807 		break;
2808 	case 0x002c :	/* rigid restricted overwrite feature */
2809 		flags |= MMC_CAP_RECORDABLE;
2810 		flags |= MMC_CAP_REWRITABLE;
2811 		flags |= MMC_CAP_STRICTOVERWRITE;
2812 		if (rpos[0] & 1) /* blank bit */
2813 			flags |= MMC_CAP_BLANKABLE;
2814 		break;
2815 	case 0x002d :	/* track at once recording feature */
2816 		flags |= MMC_CAP_RECORDABLE;
2817 		flags |= MMC_CAP_SEQUENTIAL;
2818 		break;
2819 	case 0x002f :	/* DVD-R/-RW write feature */
2820 		flags |= MMC_CAP_RECORDABLE;
2821 		if (rpos[0] & 2) /* DVD-RW bit */
2822 			flags |= MMC_CAP_BLANKABLE;
2823 		break;
2824 	case 0x0038 :	/* BD-R SRM with pseudo overwrite */
2825 		flags |= MMC_CAP_PSEUDOOVERWRITE;
2826 		break;
2827 	default :
2828 		/* ignore */
2829 		break;
2830 	}
2831 
2832 	if (cur == 1) {
2833 		mmc_discinfo->mmc_cur = flags;
2834 	} else {
2835 		mmc_discinfo->mmc_cap = flags;
2836 	}
2837 }
2838 
2839 static int
2840 mmc_getdiscinfo_cdrom(struct scsipi_periph *periph,
2841 		      struct mmc_discinfo *mmc_discinfo)
2842 {
2843 	struct scsipi_read_toc      gtoc_cmd;
2844 	struct scsipi_toc_header   *toc_hdr;
2845 	struct scsipi_toc_msinfo   *toc_msinfo;
2846 	const uint32_t buffer_size = 1024;
2847 	uint32_t req_size;
2848 	uint8_t  *buffer;
2849 	int error, flags;
2850 
2851 	buffer = malloc(buffer_size, M_TEMP, M_WAITOK);
2852 	/*
2853 	 * Fabricate mmc_discinfo for CD-ROM. Some values are really `dont
2854 	 * care' but others might be of interest to programs.
2855 	 */
2856 
2857 	mmc_discinfo->disc_state	 = MMC_STATE_FULL;
2858 	mmc_discinfo->last_session_state = MMC_STATE_FULL;
2859 	mmc_discinfo->bg_format_state    = MMC_BGFSTATE_COMPLETED;
2860 	mmc_discinfo->link_block_penalty = 7;	/* not relevant */
2861 
2862 	/* get number of sessions and first tracknr in last session */
2863 	flags = XS_CTL_DATA_IN;
2864 	memset(&gtoc_cmd, 0, sizeof(gtoc_cmd));
2865 	gtoc_cmd.opcode      = READ_TOC;
2866 	gtoc_cmd.addr_mode   = CD_MSF;		/* not relevant        */
2867 	gtoc_cmd.resp_format = CD_TOC_MSINFO;	/* multisession info   */
2868 	gtoc_cmd.from_track  = 0;		/* reserved, must be 0 */
2869 	req_size = sizeof(*toc_hdr) + sizeof(*toc_msinfo);
2870 	_lto2b(req_size, gtoc_cmd.data_len);
2871 
2872 	error = scsipi_command(periph,
2873 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
2874 		(void *)buffer,    req_size,
2875 		CDRETRIES, 30000, NULL, flags);
2876 	if (error)
2877 		goto out;
2878 	toc_hdr    = (struct scsipi_toc_header *)  buffer;
2879 	toc_msinfo = (struct scsipi_toc_msinfo *) (buffer + 4);
2880 	mmc_discinfo->num_sessions = toc_hdr->last - toc_hdr->first + 1;
2881 	mmc_discinfo->first_track  = toc_hdr->first;
2882 	mmc_discinfo->first_track_last_session = toc_msinfo->tracknr;
2883 
2884 	/* get last track of last session */
2885 	flags = XS_CTL_DATA_IN;
2886 	gtoc_cmd.resp_format  = CD_TOC_FORM;	/* formatted toc */
2887 	req_size = sizeof(*toc_hdr);
2888 	_lto2b(req_size, gtoc_cmd.data_len);
2889 
2890 	error = scsipi_command(periph,
2891 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
2892 		(void *)buffer,    req_size,
2893 		CDRETRIES, 30000, NULL, flags);
2894 	if (error)
2895 		goto out;
2896 	toc_hdr    = (struct scsipi_toc_header *) buffer;
2897 	mmc_discinfo->last_track_last_session = toc_hdr->last;
2898 	mmc_discinfo->num_tracks = toc_hdr->last - toc_hdr->first + 1;
2899 
2900 	/* TODO how to handle disc_barcode and disc_id */
2901 	/* done */
2902 
2903 out:
2904 	free(buffer, M_TEMP);
2905 	return error;
2906 }
2907 
2908 static int
2909 mmc_getdiscinfo_dvdrom(struct scsipi_periph *periph,
2910 		       struct mmc_discinfo *mmc_discinfo)
2911 {
2912 	struct scsipi_read_toc   gtoc_cmd;
2913 	struct scsipi_toc_header toc_hdr;
2914 	uint32_t req_size;
2915 	int error, flags;
2916 
2917 	/*
2918 	 * Fabricate mmc_discinfo for DVD-ROM. Some values are really `dont
2919 	 * care' but others might be of interest to programs.
2920 	 */
2921 
2922 	mmc_discinfo->disc_state	 = MMC_STATE_FULL;
2923 	mmc_discinfo->last_session_state = MMC_STATE_FULL;
2924 	mmc_discinfo->bg_format_state    = MMC_BGFSTATE_COMPLETED;
2925 	mmc_discinfo->link_block_penalty = 16;	/* not relevant */
2926 
2927 	/* get number of sessions and first tracknr in last session */
2928 	flags = XS_CTL_DATA_IN;
2929 	memset(&gtoc_cmd, 0, sizeof(gtoc_cmd));
2930 	gtoc_cmd.opcode      = READ_TOC;
2931 	gtoc_cmd.addr_mode   = 0;		/* LBA                 */
2932 	gtoc_cmd.resp_format = CD_TOC_FORM;	/* multisession info   */
2933 	gtoc_cmd.from_track  = 1;		/* first track         */
2934 	req_size = sizeof(toc_hdr);
2935 	_lto2b(req_size, gtoc_cmd.data_len);
2936 
2937 	error = scsipi_command(periph,
2938 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
2939 		(void *)&toc_hdr,  req_size,
2940 		CDRETRIES, 30000, NULL, flags);
2941 	if (error)
2942 		return error;
2943 
2944 	/* DVD-ROM squashes the track/session space */
2945 	mmc_discinfo->num_sessions = toc_hdr.last - toc_hdr.first + 1;
2946 	mmc_discinfo->num_tracks   = mmc_discinfo->num_sessions;
2947 	mmc_discinfo->first_track  = toc_hdr.first;
2948 	mmc_discinfo->first_track_last_session = toc_hdr.last;
2949 	mmc_discinfo->last_track_last_session  = toc_hdr.last;
2950 
2951 	/* TODO how to handle disc_barcode and disc_id */
2952 	/* done */
2953 	return 0;
2954 }
2955 
2956 static int
2957 mmc_getdiscinfo(struct scsipi_periph *periph,
2958 		struct mmc_discinfo *mmc_discinfo)
2959 {
2960 	struct scsipi_get_configuration   gc_cmd;
2961 	struct scsipi_get_conf_data      *gc;
2962 	struct scsipi_get_conf_feature   *gcf;
2963 	struct scsipi_read_discinfo       di_cmd;
2964 	struct scsipi_read_discinfo_data  di;
2965 	const uint32_t buffer_size = 1024;
2966 	uint32_t feat_tbl_len, pos;
2967 	u_long   last_lba;
2968 	uint8_t  *buffer, *fpos;
2969 	int feature, last_feature, features_len, feature_cur, feature_len;
2970 	int lsb, msb, error, flags;
2971 
2972 	feat_tbl_len = buffer_size;
2973 
2974 	buffer = malloc(buffer_size, M_TEMP, M_WAITOK);
2975 
2976 	/* initialise structure */
2977 	memset(mmc_discinfo, 0, sizeof(struct mmc_discinfo));
2978 	mmc_discinfo->mmc_profile = 0x00;	/* unknown */
2979 	mmc_discinfo->mmc_class   = MMC_CLASS_UNKN;
2980 	mmc_discinfo->mmc_cur     = 0;
2981 	mmc_discinfo->mmc_cap     = 0;
2982 	mmc_discinfo->link_block_penalty = 0;
2983 
2984 	/* determine mmc profile and class */
2985 	flags = XS_CTL_DATA_IN;
2986 	memset(&gc_cmd, 0, sizeof(gc_cmd));
2987 	gc_cmd.opcode = GET_CONFIGURATION;
2988 	_lto2b(GET_CONF_NO_FEATURES_LEN, gc_cmd.data_len);
2989 
2990 	gc = (struct scsipi_get_conf_data *) buffer;
2991 
2992 	error = scsipi_command(periph,
2993 		(void *)&gc_cmd, sizeof(gc_cmd),
2994 		(void *) gc,     GET_CONF_NO_FEATURES_LEN,
2995 		CDRETRIES, 30000, NULL, flags);
2996 	if (error)
2997 		goto out;
2998 
2999 	mmc_discinfo->mmc_profile = _2btol(gc->mmc_profile);
3000 	mmc_discinfo->mmc_class = mmc_profile2class(mmc_discinfo->mmc_profile);
3001 
3002 	/* assume 2048 sector size unless told otherwise */
3003 	mmc_discinfo->sector_size = 2048;
3004 	error = read_cd_capacity(periph, &mmc_discinfo->sector_size, &last_lba);
3005 	if (error)
3006 		goto out;
3007 
3008 	mmc_discinfo->last_possible_lba = (uint32_t) last_lba - 1;
3009 
3010 	/* Read in all features to determine device capabilities */
3011 	last_feature = feature = 0;
3012 	do {
3013 		/* determine mmc profile and class */
3014 		flags = XS_CTL_DATA_IN;
3015 		memset(&gc_cmd, 0, sizeof(gc_cmd));
3016 		gc_cmd.opcode = GET_CONFIGURATION;
3017 		_lto2b(last_feature, gc_cmd.start_at_feature);
3018 		_lto2b(feat_tbl_len, gc_cmd.data_len);
3019 
3020 		error = scsipi_command(periph,
3021 			(void *)&gc_cmd, sizeof(gc_cmd),
3022 			(void *) gc,     feat_tbl_len,
3023 			CDRETRIES, 30000, NULL, flags);
3024 		if (error) {
3025 			/* ieeek... break out of loop... i dunno what to do */
3026 			break;
3027 		}
3028 
3029 		features_len = _4btol(gc->data_len);
3030 		if (features_len < 4)
3031 			break;
3032 
3033 		pos  = 0;
3034 		fpos = &gc->feature_desc[0];
3035 		while (pos < features_len - 4) {
3036 			gcf = (struct scsipi_get_conf_feature *) fpos;
3037 
3038 			feature     = _2btol(gcf->featurecode);
3039 			feature_cur = gcf->flags & 1;
3040 			feature_len = gcf->additional_length;
3041 
3042 			mmc_process_feature(mmc_discinfo,
3043 					    feature, feature_cur,
3044 					    gcf->feature_dependent);
3045 
3046 			last_feature = MAX(last_feature, feature);
3047 #ifdef DIAGNOSTIC
3048 			/* assert((feature_len & 3) == 0); */
3049 			if ((feature_len & 3) != 0) {
3050 				printf("feature %d having length %d\n",
3051 					feature, feature_len);
3052 			}
3053 #endif
3054 
3055 			pos  += 4 + feature_len;
3056 			fpos += 4 + feature_len;
3057 		}
3058 		/* unlikely to ever grow past our 1kb buffer */
3059 	} while (features_len >= 0xffff);
3060 
3061 	/*
3062 	 * Fixup CD-RW drives that are on crack.
3063 	 *
3064 	 * Some drives report the capability to incrementally write
3065 	 * sequentially on CD-R(W) media...  nice, but this should not be
3066 	 * active for a fixed packet formatted CD-RW media. Other report the
3067 	 * ability of HW_DEFECTFREE even when the media is NOT MRW
3068 	 * formatted....
3069 	 */
3070 	if (mmc_discinfo->mmc_profile == 0x0a) {
3071 		if ((mmc_discinfo->mmc_cur & MMC_CAP_SEQUENTIAL) == 0)
3072 			mmc_discinfo->mmc_cur |= MMC_CAP_STRICTOVERWRITE;
3073 		if (mmc_discinfo->mmc_cur & MMC_CAP_STRICTOVERWRITE)
3074 			mmc_discinfo->mmc_cur &= ~MMC_CAP_SEQUENTIAL;
3075 		if (mmc_discinfo->mmc_cur & MMC_CAP_MRW) {
3076 			mmc_discinfo->mmc_cur &= ~MMC_CAP_SEQUENTIAL;
3077 			mmc_discinfo->mmc_cur &= ~MMC_CAP_STRICTOVERWRITE;
3078 		} else {
3079 			mmc_discinfo->mmc_cur &= ~MMC_CAP_HW_DEFECTFREE;
3080 		}
3081 	}
3082 	if (mmc_discinfo->mmc_profile == 0x09) {
3083 		mmc_discinfo->mmc_cur &= ~MMC_CAP_REWRITABLE;
3084 	}
3085 
3086 #ifdef DEBUG
3087 	printf("CD mmc %d, mmc_cur 0x%"PRIx64", mmc_cap 0x%"PRIx64"\n",
3088 		mmc_discinfo->mmc_profile,
3089 	 	mmc_discinfo->mmc_cur, mmc_discinfo->mmc_cap);
3090 #endif
3091 
3092 	/* read in disc state and number of sessions and tracks */
3093 	flags = XS_CTL_DATA_IN | XS_CTL_SILENT;
3094 	memset(&di_cmd, 0, sizeof(di_cmd));
3095 	di_cmd.opcode = READ_DISCINFO;
3096 	di_cmd.data_len[1] = READ_DISCINFO_BIGSIZE;
3097 
3098 	error = scsipi_command(periph,
3099 		(void *)&di_cmd, sizeof(di_cmd),
3100 		(void *)&di,     READ_DISCINFO_BIGSIZE,
3101 		CDRETRIES, 30000, NULL, flags);
3102 
3103 	if (error) {
3104 		/* discinfo call failed, emulate for cd-rom/dvd-rom */
3105 		if (mmc_discinfo->mmc_profile == 0x08) /* CD-ROM */
3106 			return mmc_getdiscinfo_cdrom(periph, mmc_discinfo);
3107 		if (mmc_discinfo->mmc_profile == 0x10) /* DVD-ROM */
3108 			return mmc_getdiscinfo_dvdrom(periph, mmc_discinfo);
3109 		/* CD/DVD drive is violating specs */
3110 		error = EIO;
3111 		goto out;
3112 	}
3113 
3114 	/* call went OK */
3115 	mmc_discinfo->disc_state         =  di.disc_state & 3;
3116 	mmc_discinfo->last_session_state = (di.disc_state >> 2) & 3;
3117 	mmc_discinfo->bg_format_state    = (di.disc_state2 & 3);
3118 
3119 	lsb = di.num_sessions_lsb;
3120 	msb = di.num_sessions_msb;
3121 	mmc_discinfo->num_sessions = lsb | (msb << 8);
3122 
3123 	mmc_discinfo->first_track = di.first_track;
3124 	lsb = di.first_track_last_session_lsb;
3125 	msb = di.first_track_last_session_msb;
3126 	mmc_discinfo->first_track_last_session = lsb | (msb << 8);
3127 	lsb = di.last_track_last_session_lsb;
3128 	msb = di.last_track_last_session_msb;
3129 	mmc_discinfo->last_track_last_session  = lsb | (msb << 8);
3130 
3131 	mmc_discinfo->num_tracks = mmc_discinfo->last_track_last_session -
3132 		mmc_discinfo->first_track + 1;
3133 
3134 	/* set misc. flags and parameters from this disc info */
3135 	if (di.disc_state  &  16)
3136 		mmc_discinfo->mmc_cur |= MMC_CAP_BLANKABLE;
3137 
3138 	if (di.disc_state2 & 128) {
3139 		mmc_discinfo->disc_id = _4btol(di.discid);
3140 		mmc_discinfo->disc_flags |= MMC_DFLAGS_DISCIDVALID;
3141 	}
3142 	if (di.disc_state2 &  64) {
3143 		mmc_discinfo->disc_barcode = _8btol(di.disc_bar_code);
3144 		mmc_discinfo->disc_flags |= MMC_DFLAGS_BARCODEVALID;
3145 	}
3146 	if (di.disc_state2 &  32)
3147 		mmc_discinfo->disc_flags |= MMC_DFLAGS_UNRESTRICTED;
3148 
3149 	if (di.disc_state2 &  16) {
3150 		mmc_discinfo->application_code = di.application_code;
3151 		mmc_discinfo->disc_flags |= MMC_DFLAGS_APPCODEVALID;
3152 	}
3153 
3154 	/* done */
3155 
3156 out:
3157 	free(buffer, M_TEMP);
3158 	return error;
3159 }
3160 
3161 static int
3162 mmc_gettrackinfo_cdrom(struct scsipi_periph *periph,
3163 		       struct mmc_trackinfo *trackinfo)
3164 {
3165 	struct scsipi_read_toc            gtoc_cmd;
3166 	struct scsipi_toc_header         *toc_hdr;
3167 	struct scsipi_toc_rawtoc         *rawtoc;
3168 	uint32_t track_start, track_end, track_size;
3169 	uint32_t last_recorded, next_writable;
3170 	uint32_t lba, next_track_start, lead_out;
3171 	const uint32_t buffer_size = 4 * 1024;	/* worst case TOC estimate */
3172 	uint8_t *buffer;
3173 	uint8_t track_sessionnr, last_tracknr, sessionnr, adr, tno, point;
3174 	uint8_t control, tmin, tsec, tframe, pmin, psec, pframe;
3175 	int size, req_size;
3176 	int error, flags;
3177 
3178 	buffer = malloc(buffer_size, M_TEMP, M_WAITOK);
3179 
3180 	/*
3181 	 * Emulate read trackinfo for CD-ROM using the raw-TOC.
3182 	 *
3183 	 * Not all information is present and this presents a problem.  Track
3184 	 * starts are known for each track but other values are deducted.
3185 	 *
3186 	 * For a complete overview of `magic' values used here, see the
3187 	 * SCSI/ATAPI MMC documentation. Note that the `magic' values have no
3188 	 * names, they are specified as numbers.
3189 	 */
3190 
3191 	/* get raw toc to process, first header to check size */
3192 	flags = XS_CTL_DATA_IN | XS_CTL_SILENT;
3193 	memset(&gtoc_cmd, 0, sizeof(gtoc_cmd));
3194 	gtoc_cmd.opcode      = READ_TOC;
3195 	gtoc_cmd.addr_mode   = CD_MSF;		/* not relevant     */
3196 	gtoc_cmd.resp_format = CD_TOC_RAW;	/* raw toc          */
3197 	gtoc_cmd.from_track  = 1;		/* first session    */
3198 	req_size = sizeof(*toc_hdr);
3199 	_lto2b(req_size, gtoc_cmd.data_len);
3200 
3201 	error = scsipi_command(periph,
3202 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
3203 		(void *)buffer,    req_size,
3204 		CDRETRIES, 30000, NULL, flags);
3205 	if (error)
3206 		goto out;
3207 	toc_hdr = (struct scsipi_toc_header *) buffer;
3208 	if (_2btol(toc_hdr->length) > buffer_size - 2) {
3209 #ifdef DIAGNOSTIC
3210 		printf("increase buffersize in mmc_readtrackinfo_cdrom\n");
3211 #endif
3212 		error = ENOBUFS;
3213 		goto out;
3214 	}
3215 
3216 	/* read in complete raw toc */
3217 	req_size = _2btol(toc_hdr->length);
3218 	req_size = 2*((req_size + 1) / 2);	/* for ATAPI */
3219 	_lto2b(req_size, gtoc_cmd.data_len);
3220 
3221 	error = scsipi_command(periph,
3222 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
3223 		(void *)buffer,    req_size,
3224 		CDRETRIES, 30000, NULL, flags);
3225 	if (error)
3226 		goto out;
3227 
3228 	toc_hdr = (struct scsipi_toc_header *) buffer;
3229 	rawtoc  = (struct scsipi_toc_rawtoc *) (buffer + 4);
3230 
3231 	track_start      = 0;
3232 	track_end        = 0;
3233 	track_size       = 0;
3234 	last_recorded    = 0;
3235 	next_writable    = 0;
3236 	flags            = 0;
3237 
3238 	last_tracknr     = 1;
3239 	next_track_start = 0;
3240 	track_sessionnr  = MAXTRACK;	/* by definition */
3241 	lead_out         = 0;
3242 
3243 	size = req_size - sizeof(struct scsipi_toc_header) + 1;
3244 	while (size > 0) {
3245 		/* get track start and session end */
3246 		tno       = rawtoc->tno;
3247 		sessionnr = rawtoc->sessionnr;
3248 		adr       = rawtoc->adrcontrol >> 4;
3249 		control   = rawtoc->adrcontrol & 0xf;
3250 		point     = rawtoc->point;
3251 		tmin      = rawtoc->min;
3252 		tsec      = rawtoc->sec;
3253 		tframe    = rawtoc->frame;
3254 		pmin      = rawtoc->pmin;
3255 		psec      = rawtoc->psec;
3256 		pframe    = rawtoc->pframe;
3257 
3258 		if (tno == 0 && sessionnr && adr == 1) {
3259 			lba = hmsf2lba(0, pmin, psec, pframe);
3260 			if (point == trackinfo->tracknr) {
3261 				track_start = lba;
3262 				track_sessionnr = sessionnr;
3263 			}
3264 			if (point == trackinfo->tracknr + 1) {
3265 				/* estimate size */
3266 				track_size = lba - track_start;
3267 				next_track_start = lba;
3268 			}
3269 			if (point == 0xa2) {
3270 				lead_out = lba;
3271 			}
3272 			if (point <= 0x63) {
3273 				/* CD's ok, DVD are glued */
3274 				last_tracknr = point;
3275 			}
3276 			if (sessionnr == track_sessionnr) {
3277 				last_recorded = lead_out;
3278 			}
3279 		}
3280 		if (tno == 0 && sessionnr && adr == 5) {
3281 			lba = hmsf2lba(0, tmin, tsec, tframe);
3282 			if (sessionnr == track_sessionnr) {
3283 				next_writable = lba;
3284 			}
3285 		}
3286 
3287 		if ((control & (3<<2)) == 4)		/* 01xxb */
3288 			flags |= MMC_TRACKINFO_DATA;
3289 		if ((control & (1<<2)) == 0) {		/* x0xxb */
3290 			flags |= MMC_TRACKINFO_AUDIO;
3291 			if (control & 1)		/* xxx1b */
3292 				flags |= MMC_TRACKINFO_PRE_EMPH;
3293 		}
3294 
3295 		rawtoc++;
3296 		size -= sizeof(struct scsipi_toc_rawtoc);
3297 	}
3298 
3299 	/* process found values; some voodoo */
3300 	/* if no tracksize tracknr is the last of the disc */
3301 	if ((track_size == 0) && last_recorded) {
3302 		track_size = last_recorded - track_start;
3303 	}
3304 	/* if last_recorded < tracksize, tracksize is overestimated */
3305 	if (last_recorded) {
3306 		if (last_recorded - track_start <= track_size) {
3307 			track_size = last_recorded - track_start;
3308 			flags |= MMC_TRACKINFO_LRA_VALID;
3309 		}
3310 	}
3311 	/* check if its a the last track of the sector */
3312 	if (next_writable) {
3313 		if (next_track_start > next_writable)
3314 			flags |= MMC_TRACKINFO_NWA_VALID;
3315 	}
3316 
3317 	/* no flag set -> no values */
3318 	if ((flags & MMC_TRACKINFO_LRA_VALID) == 0)
3319 		last_recorded = 0;
3320 	if ((flags & MMC_TRACKINFO_NWA_VALID) == 0)
3321 		next_writable = 0;
3322 
3323 	/* fill in */
3324 	/* trackinfo->tracknr preserved */
3325 	trackinfo->sessionnr  = track_sessionnr;
3326 	trackinfo->track_mode = 7;	/* data, incremental  */
3327 	trackinfo->data_mode  = 8;	/* 2048 bytes mode1   */
3328 
3329 	trackinfo->flags = flags;
3330 	trackinfo->track_start   = track_start;
3331 	trackinfo->next_writable = next_writable;
3332 	trackinfo->free_blocks   = 0;
3333 	trackinfo->packet_size   = 1;
3334 	trackinfo->track_size    = track_size;
3335 	trackinfo->last_recorded = last_recorded;
3336 
3337 out:
3338 	free(buffer, M_TEMP);
3339 	return error;
3340 
3341 }
3342 
3343 static int
3344 mmc_gettrackinfo_dvdrom(struct scsipi_periph *periph,
3345 			struct mmc_trackinfo *trackinfo)
3346 {
3347 	struct scsipi_read_toc            gtoc_cmd;
3348 	struct scsipi_toc_header         *toc_hdr;
3349 	struct scsipi_toc_formatted      *toc;
3350 	uint32_t tracknr, track_start, track_size;
3351 	uint32_t lba, lead_out;
3352 	const uint32_t buffer_size = 4 * 1024;	/* worst case TOC estimate */
3353 	uint8_t *buffer;
3354 	uint8_t control, last_tracknr;
3355 	int size, req_size;
3356 	int error, flags;
3357 
3358 
3359 	buffer = malloc(buffer_size, M_TEMP, M_WAITOK);
3360 	/*
3361 	 * Emulate read trackinfo for DVD-ROM. We can't use the raw-TOC as the
3362 	 * CD-ROM emulation uses since the specification tells us that no such
3363 	 * thing is defined for DVD's. The reason for this is due to the large
3364 	 * number of tracks and that would clash with the `magic' values. This
3365 	 * suxs.
3366 	 *
3367 	 * Not all information is present and this presents a problem.
3368 	 * Track starts are known for each track but other values are
3369 	 * deducted.
3370 	 */
3371 
3372 	/* get formatted toc to process, first header to check size */
3373 	flags = XS_CTL_DATA_IN | XS_CTL_SILENT;
3374 	memset(&gtoc_cmd, 0, sizeof(gtoc_cmd));
3375 	gtoc_cmd.opcode      = READ_TOC;
3376 	gtoc_cmd.addr_mode   = 0;		/* lba's please     */
3377 	gtoc_cmd.resp_format = CD_TOC_FORM;	/* formatted toc    */
3378 	gtoc_cmd.from_track  = 1;		/* first track      */
3379 	req_size = sizeof(*toc_hdr);
3380 	_lto2b(req_size, gtoc_cmd.data_len);
3381 
3382 	error = scsipi_command(periph,
3383 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
3384 		(void *)buffer,    req_size,
3385 		CDRETRIES, 30000, NULL, flags);
3386 	if (error)
3387 		goto out;
3388 	toc_hdr = (struct scsipi_toc_header *) buffer;
3389 	if (_2btol(toc_hdr->length) > buffer_size - 2) {
3390 #ifdef DIAGNOSTIC
3391 		printf("incease buffersize in mmc_readtrackinfo_dvdrom\n");
3392 #endif
3393 		error = ENOBUFS;
3394 		goto out;
3395 	}
3396 
3397 	/* read in complete formatted toc */
3398 	req_size = _2btol(toc_hdr->length);
3399 	_lto2b(req_size, gtoc_cmd.data_len);
3400 
3401 	error = scsipi_command(periph,
3402 		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
3403 		(void *)buffer,    req_size,
3404 		CDRETRIES, 30000, NULL, flags);
3405 	if (error)
3406 		goto out;
3407 
3408 	toc_hdr = (struct scsipi_toc_header *)     buffer;
3409 	toc     = (struct scsipi_toc_formatted *) (buffer + 4);
3410 
3411 	/* as in read disc info, all sessions are converted to tracks      */
3412 	/* track 1..  -> offsets, sizes can be (rougly) estimated (16 ECC) */
3413 	/* last track -> we got the size from the lead-out                 */
3414 
3415 	tracknr      = 0;
3416 	last_tracknr = toc_hdr->last;
3417 	track_start  = 0;
3418 	track_size   = 0;
3419 	lead_out     = 0;
3420 	flags        = 0;
3421 
3422 	size = req_size - sizeof(struct scsipi_toc_header) + 1;
3423 	while (size > 0) {
3424 		/* remember, DVD-ROM: tracknr == sessionnr */
3425 		lba     = _4btol(toc->msf_lba);
3426 		tracknr = toc->tracknr;
3427 		control = toc->adrcontrol & 0xf;
3428 
3429 		if (trackinfo->tracknr == tracknr) {
3430 			track_start = lba;
3431 		}
3432 		if (trackinfo->tracknr == tracknr+1) {
3433 			track_size  = lba - track_start;
3434 			track_size -= 16;	/* link block ? */
3435 		}
3436 		if (tracknr == 0xAA) {
3437 			lead_out = lba;
3438 		}
3439 
3440 		if ((control & (3<<2)) == 4)		/* 01xxb */
3441 			flags |= MMC_TRACKINFO_DATA;
3442 		if ((control & (1<<2)) == 0) {		/* x0xxb */
3443 			flags |= MMC_TRACKINFO_AUDIO;
3444 			if (control & (1<<3))		/* 10xxb */
3445 				flags |= MMC_TRACKINFO_AUDIO_4CHAN;
3446 			if (control & 1)		/* xxx1b */
3447 				flags |= MMC_TRACKINFO_PRE_EMPH;
3448 		}
3449 
3450 		toc++;
3451 		size -= sizeof(struct scsipi_toc_formatted);
3452 	}
3453 	if (trackinfo->tracknr == last_tracknr) {
3454 		track_size = lead_out - track_start;
3455 	}
3456 
3457 	/* fill in */
3458 	/* trackinfo->tracknr preserved */
3459 	trackinfo->sessionnr  = trackinfo->tracknr;
3460 	trackinfo->track_mode = 0;	/* unknown */
3461 	trackinfo->data_mode  = 8;	/* 2048 bytes mode1   */
3462 
3463 	trackinfo->flags         = flags;
3464 	trackinfo->track_start   = track_start;
3465 	trackinfo->next_writable = 0;
3466 	trackinfo->free_blocks   = 0;
3467 	trackinfo->packet_size   = 16;	/* standard length 16 blocks ECC */
3468 	trackinfo->track_size    = track_size;
3469 	trackinfo->last_recorded = 0;
3470 
3471 out:
3472 	free(buffer, M_TEMP);
3473 	return error;
3474 }
3475 
3476 static int
3477 mmc_gettrackinfo(struct scsipi_periph *periph,
3478 		 struct mmc_trackinfo *trackinfo)
3479 {
3480 	struct scsipi_read_trackinfo      ti_cmd;
3481 	struct scsipi_read_trackinfo_data ti;
3482 	struct scsipi_get_configuration   gc_cmd;
3483 	struct scsipi_get_conf_data       gc;
3484 	int error, flags;
3485 	int mmc_profile;
3486 
3487 	/* set up SCSI call with track number from trackinfo.tracknr */
3488 	flags = XS_CTL_DATA_IN | XS_CTL_SILENT;
3489 	memset(&ti_cmd, 0, sizeof(ti_cmd));
3490 	ti_cmd.opcode    = READ_TRACKINFO;
3491 	ti_cmd.addr_type = READ_TRACKINFO_ADDR_TRACK;
3492 	ti_cmd.data_len[1] = READ_TRACKINFO_RETURNSIZE;
3493 
3494 	/* trackinfo.tracknr contains number of tracks to query */
3495 	_lto4b(trackinfo->tracknr, ti_cmd.address);
3496 	error = scsipi_command(periph,
3497 		(void *)&ti_cmd, sizeof(ti_cmd),
3498 		(void *)&ti,     READ_TRACKINFO_RETURNSIZE,
3499 		CDRETRIES, 30000, NULL, flags);
3500 
3501 	if (error) {
3502 		/* trackinfo call failed, emulate for cd-rom/dvd-rom */
3503 		/* first determine mmc profile */
3504 		flags = XS_CTL_DATA_IN;
3505 		memset(&gc_cmd, 0, sizeof(gc_cmd));
3506 		gc_cmd.opcode = GET_CONFIGURATION;
3507 		_lto2b(GET_CONF_NO_FEATURES_LEN, gc_cmd.data_len);
3508 
3509 		error = scsipi_command(periph,
3510 			(void *)&gc_cmd, sizeof(gc_cmd),
3511 			(void *)&gc,     GET_CONF_NO_FEATURES_LEN,
3512 			CDRETRIES, 30000, NULL, flags);
3513 		if (error)
3514 			return error;
3515 		mmc_profile = _2btol(gc.mmc_profile);
3516 
3517 		/* choose emulation */
3518 		if (mmc_profile == 0x08) /* CD-ROM */
3519 			return mmc_gettrackinfo_cdrom(periph, trackinfo);
3520 		if (mmc_profile == 0x10) /* DVD-ROM */
3521 			return mmc_gettrackinfo_dvdrom(periph, trackinfo);
3522 		/* CD/DVD drive is violating specs */
3523 		return EIO;
3524 	}
3525 
3526 	/* (re)initialise structure */
3527 	memset(trackinfo, 0, sizeof(struct mmc_trackinfo));
3528 
3529 	/* account for short returns screwing up track and session msb */
3530 	if ((ti.data_len[1] | (ti.data_len[0] << 8)) <= 32) {
3531 		ti.track_msb   = 0;
3532 		ti.session_msb = 0;
3533 	}
3534 
3535 	trackinfo->tracknr    = ti.track_lsb   | (ti.track_msb   << 8);
3536 	trackinfo->sessionnr  = ti.session_lsb | (ti.session_msb << 8);
3537 	trackinfo->track_mode = ti.track_info_1 & 0xf;
3538 	trackinfo->data_mode  = ti.track_info_2 & 0xf;
3539 
3540 	flags = 0;
3541 	if (ti.track_info_1 & 0x10)
3542 		flags |= MMC_TRACKINFO_COPY;
3543 	if (ti.track_info_1 & 0x20)
3544 		flags |= MMC_TRACKINFO_DAMAGED;
3545 	if (ti.track_info_2 & 0x10)
3546 		flags |= MMC_TRACKINFO_FIXED_PACKET;
3547 	if (ti.track_info_2 & 0x20)
3548 		flags |= MMC_TRACKINFO_INCREMENTAL;
3549 	if (ti.track_info_2 & 0x40)
3550 		flags |= MMC_TRACKINFO_BLANK;
3551 	if (ti.track_info_2 & 0x80)
3552 		flags |= MMC_TRACKINFO_RESERVED;
3553 	if (ti.data_valid   & 0x01)
3554 		flags |= MMC_TRACKINFO_NWA_VALID;
3555 	if (ti.data_valid   & 0x02)
3556 		flags |= MMC_TRACKINFO_LRA_VALID;
3557 	if ((trackinfo->track_mode & (3<<2)) == 4)		/* 01xxb */
3558 		flags |= MMC_TRACKINFO_DATA;
3559 	if ((trackinfo->track_mode & (1<<2)) == 0) {		/* x0xxb */
3560 		flags |= MMC_TRACKINFO_AUDIO;
3561 		if (trackinfo->track_mode & (1<<3))		/* 10xxb */
3562 			flags |= MMC_TRACKINFO_AUDIO_4CHAN;
3563 		if (trackinfo->track_mode & 1)			/* xxx1b */
3564 			flags |= MMC_TRACKINFO_PRE_EMPH;
3565 	}
3566 
3567 	trackinfo->flags = flags;
3568 	trackinfo->track_start    = _4btol(ti.track_start);
3569 	trackinfo->next_writable  = _4btol(ti.next_writable);
3570 	trackinfo->free_blocks    = _4btol(ti.free_blocks);
3571 	trackinfo->packet_size    = _4btol(ti.packet_size);
3572 	trackinfo->track_size     = _4btol(ti.track_size);
3573 	trackinfo->last_recorded  = _4btol(ti.last_recorded);
3574 
3575 	return 0;
3576 }
3577 
3578 static int
3579 mmc_doclose(struct scsipi_periph *periph, int param, int func) {
3580 	struct scsipi_close_tracksession close_cmd;
3581 	int error, flags;
3582 
3583 	/* set up SCSI call with track number */
3584 	flags = XS_CTL_DATA_OUT;
3585 	memset(&close_cmd, 0, sizeof(close_cmd));
3586 	close_cmd.opcode    = CLOSE_TRACKSESSION;
3587 	close_cmd.function  = func;
3588 	_lto2b(param, close_cmd.tracksessionnr);
3589 
3590 	error = scsipi_command(periph,
3591 		(void *) &close_cmd, sizeof(close_cmd),
3592 		NULL, 0,
3593 		CDRETRIES, 120000, NULL, flags);
3594 
3595 	return error;
3596 }
3597 
3598 static int
3599 mmc_do_closetrack(struct scsipi_periph *periph, struct mmc_op *mmc_op)
3600 {
3601 	int mmc_profile = mmc_op->mmc_profile;
3602 
3603 	switch (mmc_profile) {
3604 	case 0x12 : /* DVD-RAM */
3605 	case 0x1a : /* DVD+RW  */
3606 	case 0x2a : /* DVD+RW Dual layer */
3607 	case 0x42 : /* BD-R Ramdom Recording (RRM) */
3608 	case 0x43 : /* BD-RE */
3609 	case 0x52 : /* HD DVD-RW ; DVD-RAM like */
3610 		return EINVAL;
3611 	}
3612 
3613 	return mmc_doclose(periph, mmc_op->tracknr, 1);
3614 }
3615 
3616 static int
3617 mmc_do_close_or_finalise(struct scsipi_periph *periph, struct mmc_op *mmc_op)
3618 {
3619 	uint8_t blob[MS5LEN], *page5;
3620 	int mmc_profile = mmc_op->mmc_profile;
3621 	int func, close, flags;
3622 	int error;
3623 
3624 	close = (mmc_op->operation == MMC_OP_CLOSESESSION);
3625 
3626 	switch (mmc_profile) {
3627 	case 0x09 : /* CD-R       */
3628 	case 0x0a : /* CD-RW      */
3629 		/* Special case : need to update MS field in mode page 5 */
3630 		memset(blob, 0, sizeof(blob));
3631 		page5 = blob+8;
3632 
3633 		flags = XS_CTL_DATA_IN;
3634 		error = scsipi_mode_sense_big(periph, SMS_PF, 5,
3635 		    (void *)blob, sizeof(blob), flags, CDRETRIES, 20000);
3636 		if (error)
3637 			return error;
3638 
3639 		/* set multi session field when closing a session only */
3640 		page5[3] &= 63;
3641 		if (close)
3642 			page5[3] |= 3 << 6;
3643 
3644 		flags = XS_CTL_DATA_OUT;
3645 		error = scsipi_mode_select_big(periph, SMS_PF,
3646 		    (void *)blob, sizeof(blob), flags, CDRETRIES, 20000);
3647 		if (error)
3648 			return error;
3649 		/* and use funtion 2 */
3650 		func = 2;
3651 		break;
3652 	case 0x11 : /* DVD-R (DL) */
3653 	case 0x13 : /* DVD-RW restricted overwrite */
3654 	case 0x14 : /* DVD-RW sequential */
3655 		func = close ? 2 : 3;
3656 		break;
3657 	case 0x1b : /* DVD+R   */
3658 	case 0x2b : /* DVD+R Dual layer */
3659 	case 0x51 : /* HD DVD-R   */
3660 	case 0x41 : /* BD-R Sequential recording (SRM) */
3661 		func = close ? 2 : 6;
3662 		break;
3663 	case 0x12 : /* DVD-RAM */
3664 	case 0x1a : /* DVD+RW  */
3665 	case 0x2a : /* DVD+RW Dual layer */
3666 	case 0x42 : /* BD-R Ramdom Recording (RRM) */
3667 	case 0x43 : /* BD-RE */
3668 	case 0x52 : /* HD DVD-RW; DVD-RAM like */
3669 		return EINVAL;
3670 	default:
3671 		printf("MMC close/finalise passed wrong device type! (%d)\n",
3672 		    mmc_profile);
3673 		return EINVAL;
3674 	}
3675 
3676 	return mmc_doclose(periph, mmc_op->sessionnr, func);
3677 }
3678 
3679 static int
3680 mmc_do_reserve_track(struct scsipi_periph *periph, struct mmc_op *mmc_op)
3681 {
3682 	struct scsipi_reserve_track reserve_cmd;
3683 	uint32_t extent;
3684 	int error, flags;
3685 
3686 	/* TODO make mmc safeguards? */
3687 	extent = mmc_op->extent;
3688 	/* TODO min/max support? */
3689 
3690 	/* set up SCSI call with requested space */
3691 	flags = XS_CTL_DATA_OUT;
3692 	memset(&reserve_cmd, 0, sizeof(reserve_cmd));
3693 	reserve_cmd.opcode = RESERVE_TRACK;
3694 	_lto4b(extent, reserve_cmd.reservation_size);
3695 
3696 	error = scsipi_command(periph,
3697 		(void *) &reserve_cmd, sizeof(reserve_cmd),
3698 		NULL, 0,
3699 		CDRETRIES, 30000, NULL, flags);
3700 
3701 	return error;
3702 }
3703 
3704 static int
3705 mmc_do_reserve_track_nwa(struct scsipi_periph *periph, struct mmc_op *mmc_op)
3706 {
3707 	/* XXX assumes that NWA given is valid */
3708 	switch (mmc_op->mmc_profile) {
3709 	case 0x09 : /* CD-R       */
3710 		/* XXX unknown boundary checks XXX */
3711 		if (mmc_op->extent <= 152)
3712 			return EINVAL;
3713 		/* CD-R takes 152 sectors to close track */
3714 		mmc_op->extent -= 152;
3715 		return mmc_do_reserve_track(periph, mmc_op);
3716 	case 0x11 : /* DVD-R (DL) */
3717 	case 0x1b : /* DVD+R   */
3718 	case 0x2b : /* DVD+R Dual layer */
3719 		if (mmc_op->extent % 16)
3720 			return EINVAL;
3721 		/* upto one ECC block of 16 sectors lost */
3722 		mmc_op->extent -= 16;
3723 		return mmc_do_reserve_track(periph, mmc_op);
3724 	case 0x41 : /* BD-R Sequential recording (SRM) */
3725 	case 0x51 : /* HD DVD-R   */
3726 		if (mmc_op->extent % 32)
3727 			return EINVAL;
3728 		/* one ECC block of 32 sectors lost (AFAIK) */
3729 		mmc_op->extent -= 32;
3730 		return mmc_do_reserve_track(periph, mmc_op);
3731 	}
3732 
3733 	/* unknown behaviour or invalid disc type */
3734 	return EINVAL;
3735 }
3736 
3737 static int
3738 mmc_do_repair_track(struct scsipi_periph *periph, struct mmc_op *mmc_op)
3739 {
3740 	struct scsipi_repair_track repair_cmd;
3741 	int error, flags;
3742 
3743 	/* TODO make mmc safeguards? */
3744 
3745 	/* set up SCSI call with track number */
3746 	flags = XS_CTL_DATA_OUT;
3747 	memset(&repair_cmd, 0, sizeof(repair_cmd));
3748 	repair_cmd.opcode = REPAIR_TRACK;
3749 	_lto2b(mmc_op->tracknr, repair_cmd.tracknr);
3750 
3751 	error = scsipi_command(periph,
3752 		(void *) &repair_cmd, sizeof(repair_cmd),
3753 		NULL, 0,
3754 		CDRETRIES, 30000, NULL, flags);
3755 
3756 	return error;
3757 }
3758 
3759 static int
3760 mmc_do_op(struct scsipi_periph *periph, struct mmc_op *mmc_op)
3761 {
3762 	/* guard operation value */
3763 	if (mmc_op->operation < 1 || mmc_op->operation > MMC_OP_MAX)
3764 		return EINVAL;
3765 
3766 	/* synchronise cache is special since it doesn't rely on mmc_profile */
3767 	if (mmc_op->operation == MMC_OP_SYNCHRONISECACHE)
3768 		return cdcachesync(periph, 0);
3769 
3770 	/* zero mmc_profile means unknown disc so operations are not defined */
3771 	if (mmc_op->mmc_profile == 0) {
3772 #ifdef DEBUG
3773 		printf("mmc_do_op called with mmc_profile = 0\n");
3774 #endif
3775 		return EINVAL;
3776 	}
3777 
3778 	/* do the operations */
3779 	switch (mmc_op->operation) {
3780 	case MMC_OP_CLOSETRACK   :
3781 		return mmc_do_closetrack(periph, mmc_op);
3782 	case MMC_OP_CLOSESESSION :
3783 	case MMC_OP_FINALISEDISC :
3784 		return mmc_do_close_or_finalise(periph, mmc_op);
3785 	case MMC_OP_RESERVETRACK :
3786 		return mmc_do_reserve_track(periph, mmc_op);
3787 	case MMC_OP_RESERVETRACK_NWA :
3788 		return mmc_do_reserve_track_nwa(periph, mmc_op);
3789 	case MMC_OP_REPAIRTRACK  :
3790 		return mmc_do_repair_track(periph, mmc_op);
3791 	case MMC_OP_UNCLOSELASTSESSION :
3792 		/* TODO unclose last session support */
3793 		return EINVAL;
3794 	default :
3795 		printf("mmc_do_op: unhandled operation %d\n", mmc_op->operation);
3796 	}
3797 
3798 	return EINVAL;
3799 }
3800 
3801 static int
3802 mmc_setup_writeparams(struct scsipi_periph *periph,
3803 		      struct mmc_writeparams *mmc_writeparams)
3804 {
3805 	struct mmc_trackinfo trackinfo;
3806 	uint8_t blob[MS5LEN];
3807 	uint8_t *page5;
3808 	int flags, error;
3809 	int track_mode, data_mode;
3810 
3811 	/* setup mode page 5 for CD only */
3812 	if (mmc_writeparams->mmc_class != MMC_CLASS_CD)
3813 		return 0;
3814 
3815 	memset(blob, 0, sizeof(blob));
3816 	page5 = blob+8;
3817 
3818 	/* read mode page 5 (with header) */
3819 	flags = XS_CTL_DATA_IN;
3820 	error = scsipi_mode_sense_big(periph, SMS_PF, 5, (void *)blob,
3821 	    sizeof(blob), flags, CDRETRIES, 20000);
3822 	if (error)
3823 		return error;
3824 
3825 	/* set page length for reasurance */
3826 	page5[1] = P5LEN;	/* page length */
3827 
3828 	/* write type packet/incremental */
3829 	page5[2] &= 0xf0;
3830 
3831 	/* set specified mode parameters */
3832 	track_mode = mmc_writeparams->track_mode;
3833 	data_mode  = mmc_writeparams->data_mode;
3834 	if (track_mode <= 0 || track_mode > 15)
3835 		return EINVAL;
3836 	if (data_mode < 1 || data_mode > 2)
3837 		return EINVAL;
3838 
3839 	/* if a tracknr is passed, setup according to the track */
3840 	if (mmc_writeparams->tracknr > 0) {
3841 		trackinfo.tracknr = mmc_writeparams->tracknr;
3842 		error = mmc_gettrackinfo(periph, &trackinfo);
3843 		if (error)
3844 			return error;
3845 		if ((trackinfo.flags & MMC_TRACKINFO_BLANK) == 0) {
3846 			track_mode = trackinfo.track_mode;
3847 			data_mode  = trackinfo.data_mode;
3848 		}
3849 		mmc_writeparams->blockingnr = trackinfo.packet_size;
3850 	}
3851 
3852 	/* copy track mode and data mode from trackinfo */
3853 	page5[3] &= 16;		/* keep only `Copy' bit */
3854 	page5[3] |= (3 << 6) | track_mode;
3855 	page5[4] &= 0xf0;	/* wipe data block type */
3856 	if (data_mode == 1) {
3857 		/* select ISO mode 1 (CD only) */
3858 		page5[4] |= 8;
3859 		/* select session format normal disc (CD only) */
3860 		page5[8] = 0;
3861 	} else {
3862 		/* select ISO mode 2; XA form 1 (CD only) */
3863 		page5[4] |= 10;
3864 		/* select session format CD-ROM XA disc (CD only) */
3865 		page5[8] = 0x20;
3866 	}
3867 	if (mmc_writeparams->mmc_cur & MMC_CAP_SEQUENTIAL) {
3868 		if (mmc_writeparams->mmc_cur & MMC_CAP_ZEROLINKBLK) {
3869 			/* set BUFE buffer underrun protection */
3870 			page5[2] |= 1<<6;
3871 		}
3872 		/* allow for multi session */
3873 		page5[3] |= 3 << 6;
3874 	} else {
3875 		/* select fixed packets */
3876 		page5[3] |= 1<<5;
3877 		_lto4b(mmc_writeparams->blockingnr, &(page5[10]));
3878 	}
3879 
3880 	/* write out updated mode page 5 (with header) */
3881 	flags = XS_CTL_DATA_OUT;
3882 	error = scsipi_mode_select_big(periph, SMS_PF, (void *)blob,
3883 	    sizeof(blob), flags, CDRETRIES, 20000);
3884 	if (error)
3885 		return error;
3886 
3887 	return 0;
3888 }
3889 
3890 static void
3891 cd_set_properties(struct cd_softc *cd)
3892 {
3893 	prop_dictionary_t disk_info, odisk_info, geom;
3894 
3895 	disk_info = prop_dictionary_create();
3896 
3897 	geom = prop_dictionary_create();
3898 
3899 	prop_dictionary_set_uint64(geom, "sectors-per-unit",
3900 	    cd->params.disksize);
3901 
3902 	prop_dictionary_set_uint32(geom, "sector-size",
3903 	    cd->params.blksize);
3904 
3905 	prop_dictionary_set(disk_info, "geometry", geom);
3906 	prop_object_release(geom);
3907 
3908 	prop_dictionary_set(device_properties(cd->sc_dev),
3909 	    "disk-info", disk_info);
3910 
3911 	/*
3912 	 * Don't release disk_info here; we keep a reference to it.
3913 	 * disk_detach() will release it when we go away.
3914 	 */
3915 
3916 	odisk_info = cd->sc_dk.dk_info;
3917 	cd->sc_dk.dk_info = disk_info;
3918 	if (odisk_info)
3919 		prop_object_release(odisk_info);
3920 }
3921