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