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