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