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