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