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