<commit_before>/*-
 * Copyright (c) 1998,1999,2000,2001 <NAME>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer,
 *    without modification, immediately at the beginning of the file.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * $FreeBSD$
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/ata.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/bio.h>
#include <sys/bus.h>
#include <sys/disklabel.h>
#include <sys/devicestat.h>
#include <sys/cdio.h>
#include <sys/cdrio.h>
#include <sys/dvdio.h>
#include <sys/fcntl.h>
#include <sys/conf.h>
#include <sys/ctype.h>
#include <dev/ata/ata-all.h>
#include <dev/ata/atapi-all.h>
#include <dev/ata/atapi-cd.h>

/* device structures */
static d_open_t		acdopen;
static d_close_t	acdclose;
static d_ioctl_t	acdioctl;
static d_strategy_t	acdstrategy;
static struct cdevsw acd_cdevsw = {
	/* open */	acdopen,
	/* close */	acdclose,
	/* read */	physread,
	/* write */	physwrite,
	/* ioctl */	acdioctl,
	/* poll */	nopoll,
	/* mmap */	nommap,
	/* strategy */	acdstrategy,
	/* name */	"acd",
	/* maj */	117,
	/* dump */	nodump,
	/* psize */	nopsize,
	/* flags */	D_DISK | D_TRACKCLOSE,
};

/* prototypes */
static struct acd_softc *acd_init_lun(struct atapi_softc *, struct devstat *);
static void acd_make_dev(struct acd_softc *);
static void acd_describe(struct acd_softc *);
static void lba2msf(u_int32_t, u_int8_t *, u_int8_t *, u_int8_t *);
static u_int32_t msf2lba(u_int8_t, u_int8_t, u_int8_t);
static int acd_done(struct atapi_request *);
static void acd_read_toc(struct acd_softc *);
static int acd_play(struct acd_softc *, int, int);
static int acd_setchan(struct acd_softc *, u_int8_t, u_int8_t, u_int8_t, u_int8_t);
static void acd_select_slot(struct acd_softc *);
static int acd_open_disk(struct acd_softc *);
static int acd_close_disk(struct acd_softc *, int);
static int acd_open_track(struct acd_softc *, struct cdr_track *);
static int acd_close_track(struct acd_softc *);
static int acd_read_track_info(struct acd_softc *, int32_t, struct acd_track_info *);
static int acd_get_progress(struct acd_softc *, int *);
static int acd_report_key(struct acd_softc *, struct dvd_authinfo *);
static int acd_send_key(struct acd_softc *, struct dvd_authinfo *);
static int acd_read_structure(struct acd_softc *, struct dvd_struct *);
static int acd_eject(struct acd_softc *, int);
static int acd_blank(struct acd_softc *, int);
static int acd_prevent_allow(struct acd_softc *, int);
static int acd_start_stop(struct acd_softc *, int);
static int acd_pause_resume(struct acd_softc *, int);
static int acd_mode_sense(struct acd_softc *, int, caddr_t, int);
static int acd_mode_select(struct acd_softc *, caddr_t, int);
static int acd_set_speed(struct acd_softc *, int);
static void acd_get_cap(struct acd_softc *);

/* internal vars */
static u_int32_t acd_lun_map = 0;
static MALLOC_DEFINE(M_ACD, "ACD driver", "ATAPI CD driver buffers");

int
acdattach(struct atapi_softc *atp)
{
    struct acd_softc *cdp;
    struct changer *chp;
    char name[16];
    static int acd_cdev_done = 0;

    if (!acd_cdev_done) {
	cdevsw_add(&acd_cdevsw);
	acd_cdev_done++;
    }

    if ((cdp = acd_init_lun(atp, NULL)) == NULL) {
	ata_printf(atp->controller, atp->unit, "acd: out of memory\n");
	return -1;
    }

    sprintf(name, "acd%d", cdp->lun);
    ata_set_name(atp->controller, atp->unit, name);
    acd_get_cap(cdp);

    /* if this is a changer device, allocate the neeeded lun's */
    if (cdp->cap.mech == MST_MECH_CHANGER) {
	int8_t ccb[16] = { ATAPI_MECH_STATUS,
			   0, 0, 0, 0, 0, 0, 0, 
			   sizeof(struct changer)>>8, sizeof(struct changer),
			   0, 0, 0, 0, 0, 0 };

	chp = malloc(sizeof(struct changer), M_ACD, M_NOWAIT | M_ZERO);
	if (chp == NULL) {
	    ata_printf(atp->controller, atp->unit, "out of memory\n");
	    free(cdp, M_ACD);
	    return -1;
	}
	if (!atapi_queue_cmd(cdp->atp, ccb, (caddr_t)chp, 
			     sizeof(struct changer),
			     ATPR_F_READ, 60, NULL, NULL)) {
	    struct acd_softc *tmpcdp = cdp;
	    struct acd_softc **cdparr;
	    int count;

	    chp->table_length = htons(chp->table_length);
	    if (!(cdparr = malloc(sizeof(struct acd_softc) * chp->slots,
				 M_ACD, M_NOWAIT))) {
		ata_printf(atp->controller, atp->unit, "out of memory\n");
		free(chp, M_ACD);
		free(cdp, M_ACD);
		return -1;
	    }
	    for (count = 0; count < chp->slots; count++) {
		if (count > 0) {
		    tmpcdp = acd_init_lun(atp, cdp->stats);
		    if (!tmpcdp) {
			ata_printf(atp->controller,atp->unit,"out of memory\n");
			break;
		    }
		}
		cdparr[count] = tmpcdp;
		tmpcdp->driver = cdparr;
		tmpcdp->slot = count;
		tmpcdp->changer_info = chp;
	        acd_make_dev(tmpcdp);
	    }
	    sprintf(name, "acd%d-%d", cdp->lun, 
		    cdp->lun + cdp->changer_info->slots - 1);
	    ata_free_name(atp->controller, atp->unit);
	    ata_set_name(atp->controller, atp->unit, name);
	    devstat_add_entry(cdp->stats, name, tmpcdp->lun, DEV_BSIZE,
			      DEVSTAT_NO_ORDERED_TAGS,
			      DEVSTAT_TYPE_CDROM | DEVSTAT_TYPE_IF_IDE,
			      DEVSTAT_PRIORITY_CD);
	}
    }
    else {
	acd_make_dev(cdp);
	devstat_add_entry(cdp->stats, "acd", cdp->lun, DEV_BSIZE,
			  DEVSTAT_NO_ORDERED_TAGS,
			  DEVSTAT_TYPE_CDROM | DEVSTAT_TYPE_IF_IDE,
			  DEVSTAT_PRIORITY_CD);
    }
    cdp->atp->driver = cdp;
    acd_describe(cdp);
    return 0;
}

void
acddetach(struct atapi_softc *atp)
{   
    struct acd_softc *cdp = atp->driver;
    struct acd_devlist *entry;
    struct bio *bp;
    int subdev;
    
    if (cdp->changer_info) {
	for (subdev = 0; subdev < cdp->changer_info->slots; subdev++) {
	    if (cdp->driver[subdev] == cdp)
		continue;
	    while ((bp = bioq_first(&cdp->driver[subdev]->queue))) {
        	biofinish(bp, NULL, ENXIO);
	    }
	    destroy_dev(cdp->driver[subdev]->dev1);
	    destroy_dev(cdp->driver[subdev]->dev2);
	    while ((entry = TAILQ_FIRST(&cdp->driver[subdev]->dev_list))) {
		destroy_dev(entry->dev);
		TAILQ_REMOVE(&cdp->driver[subdev]->dev_list, entry, chain);
		free(entry, M_ACD);
	    }
	    devstat_remove_entry(cdp->driver[subdev]->stats);
	    free(cdp->driver[subdev]->stats, M_ACD);
	    ata_free_lun(&acd_lun_map, cdp->driver[subdev]->lun);
	    free(cdp->driver[subdev], M_ACD);
	}
	free(cdp->driver, M_ACD);
	free(cdp->changer_info, M_ACD);
    }
    while ((bp = bioq_first(&cdp->queue))) {
        biofinish(bp, NULL, ENXIO);
    }
    destroy_dev(cdp->dev1);
    destroy_dev(cdp->dev2);
    while ((entry = TAILQ_FIRST(&cdp->dev_list))) {
	destroy_dev(entry->dev);
	TAILQ_REMOVE(&cdp->dev_list, entry, chain);
	free(entry, M_ACD);
    }
    devstat_remove_entry(cdp->stats);
    free(cdp->stats, M_ACD);
    ata_free_name(atp->controller, atp->unit);
    ata_free_lun(&acd_lun_map, cdp->lun);
    free(cdp, M_ACD);
}

static struct acd_softc *
acd_init_lun(struct atapi_softc *atp, struct devstat *stats)
{
    struct acd_softc *cdp;

    if (!(cdp = malloc(sizeof(struct acd_softc), M_ACD, M_NOWAIT | M_ZERO)))
	return NULL;
    TAILQ_INIT(&cdp->dev_list);
    bioq_init(&cdp->queue);
    cdp->atp = atp;
    cdp->lun = ata_get_lun(&acd_lun_map);
    cdp->block_size = 2048;
    cdp->slot = -1;
    cdp->changer_info = NULL;
    if (stats == NULL) {
	if (!(cdp->stats = malloc(sizeof(struct devstat), M_ACD,
				  M_NOWAIT | M_ZERO))) {
	    free(cdp, M_ACD);
	    return NULL;
	}
    }
    else
	cdp->stats = stats;
    return cdp;
}

static void
acd_make_dev(struct acd_softc *cdp)
{
    dev_t dev;

    dev = make_dev(&acd_cdevsw, dkmakeminor(cdp->lun, 0, 0),
		   UID_ROOT, GID_OPERATOR, 0644, "acd%da", cdp->lun);
    dev->si_drv1 = cdp;
    dev->si_iosize_max = 252 * DEV_BSIZE;
    dev->si_bsize_phys = 2048; /* XXX SOS */
    cdp->dev1 = dev;
    dev = make_dev(&acd_cdevsw, dkmakeminor(cdp->lun, 0, RAW_PART),
		   UID_ROOT, GID_OPERATOR, 0644, "acd%dc", cdp->lun);
    dev->si_drv1 = cdp;
    dev->si_iosize_max = 252 * DEV_BSIZE;
    dev->si_bsize_phys = 2048; /* XXX SOS */
    cdp->dev2 = dev;
    cdp->atp->flags |= ATAPI_F_MEDIA_CHANGED;
}

static void 
acd_describe(struct acd_softc *cdp)
{
    int comma = 0;
    char *mechanism;

    if (bootverbose) {
	ata_printf(cdp->atp->controller, cdp->atp->unit,
		   "<%.40s/%.8s> %s drive at ata%d as %s\n",
		   ATA_PARAM(cdp->atp->controller, cdp->atp->unit)->model,
		   ATA_PARAM(cdp->atp->controller, cdp->atp->unit)->revision,
		   (cdp->cap.write_dvdr) ? "DVD-R" : 
		    (cdp->cap.write_dvdram) ? "DVD-RAM" : 
		     (cdp->cap.write_cdrw) ? "CD-RW" :
		      (cdp->cap.write_cdr) ? "CD-R" : 
		       (cdp->cap.read_dvdrom) ? "DVD-ROM" : "CDROM",
		   device_get_unit(cdp->atp->controller->dev),
		   (cdp->atp->unit == ATA_MASTER) ? "master" : "slave");

	ata_printf(cdp->atp->controller, cdp->atp->unit, "%s", "");
	if (cdp->cap.cur_read_speed) {
	    printf("read %dKB/s", cdp->cap.cur_read_speed * 1000 / 1024);
	    if (cdp->cap.max_read_speed) 
		printf(" (%dKB/s)", cdp->cap.max_read_speed * 1000 / 1024);
	    if ((cdp->cap.cur_write_speed) &&
		(cdp->cap.write_cdr || cdp->cap.write_cdrw || 
		 cdp->cap.write_dvdr || cdp->cap.write_dvdram)) {
		printf(" write %dKB/s", cdp->cap.cur_write_speed * 1000 / 1024);
		if (cdp->cap.max_write_speed)
		    printf(" (%dKB/s)", cdp->cap.max_write_speed * 1000 / 1024);
	    }
	    comma = 1;
	}
	if (cdp->cap.buf_size) {
	    printf("%s %dKB buffer", comma ? "," : "", cdp->cap.buf_size);
	    comma = 1;
	}
	printf("%s %s\n", 
	       comma ? "," : "", ata_mode2str(
		cdp->atp->controller->mode[ATA_DEV(cdp->atp->unit)]));

	ata_printf(cdp->atp->controller, cdp->atp->unit, "Reads:");
	comma = 0;
	if (cdp->cap.read_cdr) {
	    printf(" CD-R"); comma = 1;
	}
	if (cdp->cap.read_cdrw) {
	    printf("%s CD-RW", comma ? "," : ""); comma = 1;
	}
	if (cdp->cap.cd_da) {
	    if (cdp->cap.cd_da_stream)
	    printf("%s CD-DA stream", comma ? "," : "");
	    else
	    printf("%s CD-DA", comma ? "," : "");
	    comma = 1;
	}
	if (cdp->cap.read_dvdrom) {
	    printf("%s DVD-ROM", comma ? "," : ""); comma = 1;
	}
	if (cdp->cap.read_dvdr) {
	    printf("%s DVD-R", comma ? "," : ""); comma = 1;
	}
	if (cdp->cap.read_dvdram) {
	    printf("%s DVD-RAM", comma ? "," : ""); comma = 1;
	}
	if (cdp->cap.read_packet)
	    printf("%s packet", comma ? "," : "");

	printf("\n");
	ata_printf(cdp->atp->controller, cdp->atp->unit, "Writes:");
	if (cdp->cap.write_cdr || cdp->cap.write_cdrw || 
	    cdp->cap.write_dvdr || cdp->cap.write_dvdram) {
	    comma = 0;
	    if (cdp->cap.write_cdr) {
		printf(" CD-R" ); comma = 1;
	    }
	    if (cdp->cap.write_cdrw) {
		printf("%s CD-RW", comma ? "," : ""); comma = 1;
	    }
	    if (cdp->cap.write_dvdr) {
		printf("%s DVD-R", comma ? "," : ""); comma = 1;
	    }
	    if (cdp->cap.write_dvdram) {
		printf("%s DVD-RAM", comma ? "," : ""); comma = 1; 
	    }
	    if (cdp->cap.test_write) {
		printf("%s test write", comma ? "," : ""); comma = 1;
	    }
	    if (cdp->cap.burnproof)
		printf("%s burnproof", comma ? "," : "");
	}
	printf("\n");
	if (cdp->cap.audio_play) {
	    ata_printf(cdp->atp->controller, cdp->atp->unit, "Audio: ");
	    if (cdp->cap.audio_play)
		printf("play");
	    if (cdp->cap.max_vol_levels)
		printf(", %d volume levels", cdp->cap.max_vol_levels);
	    printf("\n");
	}
	ata_printf(cdp->atp->controller, cdp->atp->unit, "Mechanism: ");
	switch (cdp->cap.mech) {
	case MST_MECH_CADDY:
	    mechanism = "caddy"; break;
	case MST_MECH_TRAY:
	    mechanism = "tray"; break;
	case MST_MECH_POPUP:
	    mechanism = "popup"; break;
	case MST_MECH_CHANGER:
	    mechanism = "changer"; break;
	case MST_MECH_CARTRIDGE:
	    mechanism = "cartridge"; break;
	default:
	    mechanism = 0; break;
	}
	if (mechanism)
	    printf("%s%s", cdp->cap.eject ? "ejectable " : "", mechanism);
	else if (cdp->cap.eject)
	    printf("ejectable");

	if (cdp->cap.mech != MST_MECH_CHANGER) {
	    ata_printf(cdp->atp->controller, cdp->atp->unit, "Medium: ");
	    switch (cdp->cap.medium_type & MST_TYPE_MASK_HIGH) {
	    case MST_CDROM:
		printf("CD-ROM "); break;
	    case MST_CDR:
		printf("CD-R "); break;
	    case MST_CDRW:
		printf("CD-RW "); break;
	    case MST_DOOR_OPEN:
		printf("door open"); break;
	    case MST_NO_DISC:
		printf("no/blank disc"); break;
	    case MST_FMT_ERROR:
		printf("medium format error"); break;
	    }
	    if ((cdp->cap.medium_type & MST_TYPE_MASK_HIGH)<MST_TYPE_MASK_HIGH){
		switch (cdp->cap.medium_type & MST_TYPE_MASK_LOW) {
		case MST_DATA_120:
		    printf("120mm data disc"); break;
		case MST_AUDIO_120:
		    printf("120mm audio disc"); break;
		case MST_COMB_120:
		    printf("120mm data/audio disc"); break;
		case MST_PHOTO_120:
		    printf("120mm photo disc"); break;
		case MST_DATA_80:
		    printf("80mm data disc"); break;
		case MST_AUDIO_80:
		    printf("80mm audio disc"); break;
		case MST_COMB_80:
		    printf("80mm data/audio disc"); break;
		case MST_PHOTO_80:
		    printf("80mm photo disc"); break;
		case MST_FMT_NONE:
		    switch (cdp->cap.medium_type & MST_TYPE_MASK_HIGH) {
		    case MST_CDROM:
			printf("unknown"); break;
		    case MST_CDR:
		    case MST_CDRW:
			printf("blank"); break;
		    }
		    break;
		default:
		    printf("unknown (0x%x)", cdp->cap.medium_type); break;
		}
	    }
	}
	if (cdp->cap.lock)
	    printf(cdp->cap.locked ? ", locked" : ", unlocked");
	if (cdp->cap.prevent)
	    printf(", lock protected");
	printf("\n");
    }
    else {
	char chg[32];

	bzero(chg, sizeof(chg));
	if (cdp->changer_info)
	    sprintf(chg, " with %d CD changer", cdp->changer_info->slots);

	ata_printf(cdp->atp->controller, cdp->atp->unit,
		   "%s%s <%.40s> at ata%d-%s %s\n",
		   (cdp->cap.write_dvdr) ? "DVD-R" : 
		    (cdp->cap.write_dvdram) ? "DVD-RAM" : 
		     (cdp->cap.write_cdrw) ? "CD-RW" :
		      (cdp->cap.write_cdr) ? "CD-R" : 
		       (cdp->cap.read_dvdrom) ? "DVD-ROM" : "CDROM",
		   chg, ATA_PARAM(cdp->atp->controller, cdp->atp->unit)->model,
		   device_get_unit(cdp->atp->controller->dev),
		   (cdp->atp->unit == ATA_MASTER) ? "master" : "slave",
		   ata_mode2str(cdp->atp->controller->
				mode[ATA_DEV(cdp->atp->unit)])
	       );
    }
}

static __inline void 
lba2msf(u_int32_t lba, u_int8_t *m, u_int8_t *s, u_int8_t *f)
{
    lba += 150;
    lba &= 0xffffff;
    *m = lba / (60 * 75);
    lba %= (60 * 75);
    *s = lba / 75;
    *f = lba % 75;
}

static __inline u_int32_t 
msf2lba(u_int8_t m, u_int8_t s, u_int8_t f)
{
    return (m * 60 + s) * 75 + f - 150;
}

static int
acdopen(dev_t dev, int flags, int fmt, struct proc *p)
{
    struct acd_softc *cdp = dev->si_drv1;
    
    if (!cdp)
	return ENXIO;

    if (flags & FWRITE) {
	if (count_dev(dev) > 1)
	    return EBUSY;
    }
    if (count_dev(dev) == 1) {
	if (cdp->changer_info && cdp->slot != cdp->changer_info->current_slot) {
	    acd_select_slot(cdp);
	    tsleep(&cdp->changer_info, PRIBIO, "acdopn", 0);
	}
	acd_prevent_allow(cdp, 1);
	cdp->flags |= F_LOCKED;
	acd_read_toc(cdp);
    }
    return 0;
}

static int 
acdclose(dev_t dev, int flags, int fmt, struct proc *p)
{
    struct acd_softc *cdp = dev->si_drv1;
    
    if (!cdp)
	return ENXIO;

    if (count_dev(dev) == 1) {
	if (cdp->changer_info && cdp->slot != cdp->changer_info->current_slot) {
	    acd_select_slot(cdp);
	    tsleep(&cdp->changer_info, PRIBIO, "acdclo", 0);
	}
	acd_prevent_allow(cdp, 0);
	cdp->flags &= ~F_LOCKED;
    }
    return 0;
}

static int 
acdioctl(dev_t dev, u_long cmd, caddr_t addr, int flags, struct proc *p)
{
    struct acd_softc *cdp = dev->si_drv1;
    int error = 0;

    if (!cdp)
	return ENXIO;

    if (cdp->changer_info && cdp->slot != cdp->changer_info->current_slot) {
	acd_select_slot(cdp);
	tsleep(&cdp->changer_info, PRIBIO, "acdctl", 0);
    }
    if (cdp->atp->flags & ATAPI_F_MEDIA_CHANGED)
	switch (cmd) {
	case CDIOCRESET:
	    atapi_test_ready(cdp->atp);
	    break;
	   
	default:
	    acd_read_toc(cdp);
	    acd_prevent_allow(cdp, 1);
	    cdp->flags |= F_LOCKED;
	    break;
	}
    switch (cmd) {

    case CDIOCRESUME:
	error = acd_pause_resume(cdp, 1);
	break;

    case CDIOCPAUSE:
	error = acd_pause_resume(cdp, 0);
	break;

    case CDIOCSTART:
	error = acd_start_stop(cdp, 1);
	break;

    case CDIOCSTOP:
	error = acd_start_stop(cdp, 0);
	break;

    case CDIOCALLOW:
	error = acd_prevent_allow(cdp, 0);
	cdp->flags &= ~F_LOCKED;
	break;

    case CDIOCPREVENT:
	error = acd_prevent_allow(cdp, 1);
	cdp->flags |= F_LOCKED;
	break;

    case CDIOCRESET:
	error = suser(p);
	if (error)
	    break;
	error = atapi_test_ready(cdp->atp);
	break;

    case CDIOCEJECT:
	if (count_dev(dev) > 1) {
	    error = EBUSY;
	    break;
	}
	error = acd_eject(cdp, 0);
	break;

    case CDIOCCLOSE:
	if (count_dev(dev) > 1)
	    break;
	error = acd_eject(cdp, 1);
	break;

    case CDIOREADTOCHEADER:
	if (!cdp->toc.hdr.ending_track) {
	    error = EIO;
	    break;
	}
	bcopy(&cdp->toc.hdr, addr, sizeof(cdp->toc.hdr));
	break;

    case CDIOREADTOCENTRYS:
	{
	    struct ioc_read_toc_entry *te = (struct ioc_read_toc_entry *)addr;
	    struct toc *toc = &cdp->toc;
	    struct toc buf;
	    int starting_track = te->starting_track;
	    int len;

	    if (!cdp->toc.hdr.ending_track) {
		error = EIO;
		break;
	    }

	    if (te->data_len < sizeof(toc->tab[0]) || 
		(te->data_len % sizeof(toc->tab[0])) != 0 || 
		(te->address_format != CD_MSF_FORMAT &&
		te->address_format != CD_LBA_FORMAT)) {
		error = EINVAL;
		break;
	    }

	    if (!starting_track)
		starting_track = toc->hdr.starting_track;
	    else if (starting_track == 170) 
		starting_track = toc->hdr.ending_track + 1;
	    else if (starting_track < toc->hdr.starting_track ||
		     starting_track > toc->hdr.ending_track + 1) {
		error = EINVAL;
		break;
	    }

	    len = ((toc->hdr.ending_track + 1 - starting_track) + 1) *
		  sizeof(toc->tab[0]);
	    if (te->data_len < len)
		len = te->data_len;
	    if (len > sizeof(toc->tab)) {
		error = EINVAL;
		break;
	    }

	    if (te->address_format == CD_MSF_FORMAT) {
		struct cd_toc_entry *entry;

		buf = cdp->toc;
		toc = &buf;
		entry = toc->tab + (toc->hdr.ending_track + 1 -
			toc->hdr.starting_track) + 1;
		while (--entry >= toc->tab)
		    lba2msf(ntohl(entry->addr.lba), &entry->addr.msf.minute,
			    &entry->addr.msf.second, &entry->addr.msf.frame);
	    }
	    error = copyout(toc->tab + starting_track - toc->hdr.starting_track,
			    te->data, len);
	    break;
	}
    case CDIOREADTOCENTRY:
	{
	    struct ioc_read_toc_single_entry *te =
		(struct ioc_read_toc_single_entry *)addr;
	    struct toc *toc = &cdp->toc;
	    struct toc buf;
	    u_char track = te->track;

	    if (!cdp->toc.hdr.ending_track) {
		error = EIO;
		break;
	    }

	    if (te->address_format != CD_MSF_FORMAT && 
		te->address_format != CD_LBA_FORMAT) {
		error = EINVAL;
		break;
	    }

	    if (!track)
		track = toc->hdr.starting_track;
	    else if (track == 170)
		track = toc->hdr.ending_track + 1;
	    else if (track < toc->hdr.starting_track ||
		     track > toc->hdr.ending_track + 1) {
		error = EINVAL;
		break;
	    }

	    if (te->address_format == CD_MSF_FORMAT) {
		struct cd_toc_entry *entry;

		buf = cdp->toc;
		toc = &buf;
		entry = toc->tab + (track - toc->hdr.starting_track);
		lba2msf(ntohl(entry->addr.lba), &entry->addr.msf.minute,
			&entry->addr.msf.second, &entry->addr.msf.frame);
	    }
	    bcopy(toc->tab + track - toc->hdr.starting_track,
		  &te->entry, sizeof(struct cd_toc_entry));
	}
	break;

    case CDIOCREADSUBCHANNEL:
	{
	    struct ioc_read_subchannel *args =
		(struct ioc_read_subchannel *)addr;
	    struct cd_sub_channel_info data;
	    int len = args->data_len;
	    int32_t abslba, rellba;
	    int8_t ccb[16] = { ATAPI_READ_SUBCHANNEL, 0, 0x40, 1, 0, 0, 0,
			       sizeof(cdp->subchan)>>8, sizeof(cdp->subchan),
			       0, 0, 0, 0, 0, 0, 0 };

	    if (len > sizeof(data) ||
		len < sizeof(struct cd_sub_channel_header)) {
		error = EINVAL;
		break;
	    }

	    if ((error = atapi_queue_cmd(cdp->atp, ccb, (caddr_t)&cdp->subchan, 
					 sizeof(cdp->subchan), ATPR_F_READ, 10,
					 NULL, NULL))) {
		break;
	    }
	    abslba = cdp->subchan.abslba;
	    rellba = cdp->subchan.rellba;
	    if (args->address_format == CD_MSF_FORMAT) {
		lba2msf(ntohl(abslba),
		    &data.what.position.absaddr.msf.minute,
		    &data.what.position.absaddr.msf.second,
		    &data.what.position.absaddr.msf.frame);
		lba2msf(ntohl(rellba),
		    &data.what.position.reladdr.msf.minute,
		    &data.what.position.reladdr.msf.second,
		    &data.what.position.reladdr.msf.frame);
	    } else {
		data.what.position.absaddr.lba = abslba;
		data.what.position.reladdr.lba = rellba;
	    }
	    data.header.audio_status = cdp->subchan.audio_status;
	    data.what.position.control = cdp->subchan.control & 0xf;
	    data.what.position.addr_type = cdp->subchan.control >> 4;
	    data.what.position.track_number = cdp->subchan.track;
	    data.what.position.index_number = cdp->subchan.indx;
	    error = copyout(&data, args->data, len);
	    break;
	}

    case CDIOCPLAYMSF:
	{
	    struct ioc_play_msf *args = (struct ioc_play_msf *)addr;

	    error = 
		acd_play(cdp, 
			 msf2lba(args->start_m, args->start_s, args->start_f),
			 msf2lba(args->end_m, args->end_s, args->end_f));
	    break;
	}

    case CDIOCPLAYBLOCKS:
	{
	    struct ioc_play_blocks *args = (struct ioc_play_blocks *)addr;

	    error = acd_play(cdp, args->blk, args->blk + args->len);
	    break;
	}

    case CDIOCPLAYTRACKS:
	{
	    struct ioc_play_track *args = (struct ioc_play_track *)addr;
	    int t1, t2;

	    if (!cdp->toc.hdr.ending_track) {
		error = EIO;
		break;
	    }
	    if (args->end_track < cdp->toc.hdr.ending_track + 1)
		++args->end_track;
	    if (args->end_track > cdp->toc.hdr.ending_track + 1)
		args->end_track = cdp->toc.hdr.ending_track + 1;
	    t1 = args->start_track - cdp->toc.hdr.starting_track;
	    t2 = args->end_track - cdp->toc.hdr.starting_track;
	    if (t1 < 0 || t2 < 0 ||
		t1 > (cdp->toc.hdr.ending_track-cdp->toc.hdr.starting_track)) {
		error = EINVAL;
		break;
	    }
	    error = acd_play(cdp, ntohl(cdp->toc.tab[t1].addr.lba),
			     ntohl(cdp->toc.tab[t2].addr.lba));
	    break;
	}

    case CDIOCREADAUDIO:
	{
	    struct ioc_read_audio *args = (struct ioc_read_audio *)addr;
	    int32_t lba;
	    caddr_t buffer, ubuf = args->buffer;
	    int8_t ccb[16];
	    int frames;

	    if (!cdp->toc.hdr.ending_track) {
		error = EIO;
		break;
	    }
		
	    if ((frames = args->nframes) < 0) {
		error = EINVAL;
		break;
	    }

	    if (args->address_format == CD_LBA_FORMAT)
		lba = args->address.lba;
	    else if (args->address_format == CD_MSF_FORMAT)
		lba = msf2lba(args->address.msf.minute,
			     args->address.msf.second,
			     args->address.msf.frame);
	    else {
		error = EINVAL;
		break;
	    }

#ifndef CD_BUFFER_BLOCKS
#define CD_BUFFER_BLOCKS 13
#endif
	    if (!(buffer = malloc(CD_BUFFER_BLOCKS * 2352, M_ACD, M_NOWAIT))){
		error = ENOMEM;
		break;
	    }
	    bzero(ccb, sizeof(ccb));
	    while (frames > 0) {
		int8_t blocks;
		int size;

		blocks = (frames>CD_BUFFER_BLOCKS) ? CD_BUFFER_BLOCKS : frames;
		size = blocks * 2352;

		ccb[0] = ATAPI_READ_CD;
		ccb[1] = 4;
		ccb[2] = lba>>24;
		ccb[3] = lba>>16;
		ccb[4] = lba>>8;
		ccb[5] = lba;
		ccb[8] = blocks;
		ccb[9] = 0xf0;
		if ((error = atapi_queue_cmd(cdp->atp, ccb, buffer, size, 
					     ATPR_F_READ, 30, NULL,NULL)))
		    break;

		if ((error = copyout(buffer, ubuf, size)))
		    break;
		    
		ubuf += size;
		frames -= blocks;
		lba += blocks;
	    }
	    free(buffer, M_ACD);
	    if (args->address_format == CD_LBA_FORMAT)
		args->address.lba = lba;
	    else if (args->address_format == CD_MSF_FORMAT)
		lba2msf(lba, &args->address.msf.minute,
			     &args->address.msf.second,
			     &args->address.msf.frame);
	    break;
	}

    case CDIOCGETVOL:
	{
	    struct ioc_vol *arg = (struct ioc_vol *)addr;

	    if ((error = acd_mode_sense(cdp, ATAPI_CDROM_AUDIO_PAGE,
					(caddr_t)&cdp->au, sizeof(cdp->au))))
		break;

	    if (cdp->au.page_code != ATAPI_CDROM_AUDIO_PAGE) {
		error = EIO;
		break;
	    }
	    arg->vol[0] = cdp->au.port[0].volume;
	    arg->vol[1] = cdp->au.port[1].volume;
	    arg->vol[2] = cdp->au.port[2].volume;
	    arg->vol[3] = cdp->au.port[3].volume;
	    break;
	}

    case CDIOCSETVOL:
	{
	    struct ioc_vol *arg = (struct ioc_vol *)addr;

	    if ((error = acd_mode_sense(cdp, ATAPI_CDROM_AUDIO_PAGE,
					(caddr_t)&cdp->au, sizeof(cdp->au))))
		break;
	    if (cdp->au.page_code != ATAPI_CDROM_AUDIO_PAGE) {
		error = EIO;
		break;
	    }
	    if ((error = acd_mode_sense(cdp, ATAPI_CDROM_AUDIO_PAGE_MASK,
					(caddr_t)&cdp->aumask,
					sizeof(cdp->aumask))))
		break;
	    cdp->au.data_length = 0;
	    cdp->au.port[0].channels = CHANNEL_0;
	    cdp->au.port[1].channels = CHANNEL_1;
	    cdp->au.port[0].volume = arg->vol[0] & cdp->aumask.port[0].volume;
	    cdp->au.port[1].volume = arg->vol[1] & cdp->aumask.port[1].volume;
	    cdp->au.port[2].volume = arg->vol[2] & cdp->aumask.port[2].volume;
	    cdp->au.port[3].volume = arg->vol[3] & cdp->aumask.port[3].volume;
	    error =  acd_mode_select(cdp, (caddr_t)&cdp->au, sizeof(cdp->au));
	    break;
	}
    case CDIOCSETPATCH:
	{
	    struct ioc_patch *arg = (struct ioc_patch *)addr;

	    error = acd_setchan(cdp, arg->patch[0], arg->patch[1],
				arg->patch[2], arg->patch[3]);
	    break;
	}

    case CDIOCSETMONO:
	error = acd_setchan(cdp, CHANNEL_0|CHANNEL_1, CHANNEL_0|CHANNEL_1, 0,0);
	break;

    case CDIOCSETSTEREO:
	error = acd_setchan(cdp, CHANNEL_0, CHANNEL_1, 0, 0);
	break;

    case CDIOCSETMUTE:
	error = acd_setchan(cdp, 0, 0, 0, 0);
	break;

    case CDIOCSETLEFT:
	error = acd_setchan(cdp, CHANNEL_0, CHANNEL_0, 0, 0);
	break;

    case CDIOCSETRIGHT:
	error = acd_setchan(cdp, CHANNEL_1, CHANNEL_1, 0, 0);
	break;

    case CDRIOCBLANK:
	error = acd_blank(cdp, (*(int *)addr));
	break;

    case CDRIOCNEXTWRITEABLEADDR:
	{
	    struct acd_track_info track_info;

	    if ((error = acd_read_track_info(cdp, 0xff, &track_info)))
		break;

	    if (!track_info.nwa_valid) {
		error = EINVAL;
		break;
	    }
	    *(int*)addr = track_info.next_writeable_addr;
	}
	break;
 
    case CDRIOCOPENDISK:
	error = acd_open_disk(cdp);
	break;

    case CDRIOCOPENTRACK:
	error = acd_open_track(cdp, (struct cdr_track *)addr);
	break;

    case CDRIOCCLOSETRACK:
	error = acd_close_track(cdp);
	break;

    case CDRIOCCLOSEDISK:
	error = acd_close_disk(cdp, (*(int *)addr));
	break;

    case CDRIOCWRITESPEED:
	error = acd_set_speed(cdp, (*(int *)addr));
	break;

    case CDRIOCGETBLOCKSIZE:
	*(int *)addr = cdp->block_size;
	break;

    case CDRIOCSETBLOCKSIZE:
	cdp->block_size = *(int *)addr;
	break;

    case CDRIOCGETPROGRESS:
        error = acd_get_progress(cdp, (int *)addr);
	break;

    case DVDIOCREPORTKEY:
	if (!cdp->cap.read_dvdrom)
	    error = EINVAL;
	else
	    error = acd_report_key(cdp, (struct dvd_authinfo *)addr);
	break;

    case DVDIOCSENDKEY:
	if (!cdp->cap.read_dvdrom)
	    error = EINVAL;
	else
	    error = acd_send_key(cdp, (struct dvd_authinfo *)addr);
	break;

    case DVDIOCREADSTRUCTURE:
	if (!cdp->cap.read_dvdrom)
	    error = EINVAL;
	else
	    error = acd_read_structure(cdp, (struct dvd_struct *)addr);
	break;

    case DIOCGDINFO:
	*(struct disklabel *)addr = cdp->disklabel;
	break;

    case DIOCWDINFO:
    case DIOCSDINFO:
	if ((flags & FWRITE) == 0)
	    error = EBADF;
	else
	    error = setdisklabel(&cdp->disklabel, (struct disklabel *)addr, 0);
	break;

    case DIOCWLABEL:
	error = EBADF;
	break;

    case DIOCGPART:
	((struct partinfo *)addr)->disklab = &cdp->disklabel;
	((struct partinfo *)addr)->part = &cdp->disklabel.d_partitions[0];
	break;

    default:
	error = ENOTTY;
    }
    return error;
}

static void 
acdstrategy(struct bio *bp)
{
    struct acd_softc *cdp = bp->bio_dev->si_drv1;
    int s;

    if (cdp->atp->flags & ATAPI_F_DETACHING) {
	biofinish(bp, NULL, ENXIO);
	return;
    }

    /* if it's a null transfer, return immediatly. */
    if (bp->bio_bcount == 0) {
	bp->bio_resid = 0;
	biodone(bp);
	return;
    }
    
    bp->bio_pblkno = bp->bio_blkno;
    bp->bio_resid = bp->bio_bcount;

    s = splbio();
    bioqdisksort(&cdp->queue, bp);
    ata_start(cdp->atp->controller);
    splx(s);
}

void 
acd_start(struct atapi_softc *atp)
{
    struct acd_softc *cdp = atp->driver;
    struct bio *bp = bioq_first(&cdp->queue);
    u_int32_t lba, lastlba, count;
    int8_t ccb[16];
    int track, blocksize;

    if (cdp->changer_info) {
	int i;

	cdp = cdp->driver[cdp->changer_info->current_slot];
	bp = bioq_first(&cdp->queue);

	/* check for work pending on any other slot */
	for (i = 0; i < cdp->changer_info->slots; i++) {
	    if (i == cdp->changer_info->current_slot)
		continue;
	    if (bioq_first(&(cdp->driver[i]->queue))) {
	        if (!bp || time_second > (cdp->timestamp + 10)) {
		    acd_select_slot(cdp->driver[i]);
		    return;
		}
	    }
	}
    }
    if (!bp)
	return;
    bioq_remove(&cdp->queue, bp);

    /* reject all queued entries if media changed */
    if (cdp->atp->flags & ATAPI_F_MEDIA_CHANGED) {
	biofinish(bp, NULL, EIO);
	return;
    }

    bzero(ccb, sizeof(ccb));

    lba = bp->bio_offset / cdp->block_size;
    track = (bp->bio_dev->si_udev & 0x00ff0000) >> 16;

    if (track) {
	blocksize = (cdp->toc.tab[track - 1].control & 4) ? 2048 : 2352;
	lastlba = ntohl(cdp->toc.tab[track].addr.lba);
	lba += ntohl(cdp->toc.tab[track - 1].addr.lba);
    }
    else {
	blocksize = cdp->block_size;
	lastlba = cdp->disk_size;
    }

    count = (bp->bio_bcount + (blocksize - 1)) / blocksize;

    if (bp->bio_cmd == BIO_READ) {
	/* if transfer goes beyond range adjust it to be within limits */
	if (lba + count > lastlba) {
	    /* if we are entirely beyond EOM return EOF */
	    if ((count = lastlba - lba) <= 0) {
		bp->bio_resid = bp->bio_bcount;
		biodone(bp);
		return;
	    }
	}
	switch (blocksize) {
	case 2048:
	    ccb[0] = ATAPI_READ_BIG;
	    break;

	case 2352: <commit_msg>Disallow ATAPI CD transfers that are not a multiple of the device block size (previously, the transfer size would be rounded up to a multiple of the block size, which would overflow the buffer). This fixes panics when doing things like trying to mount audio CD's.<commit_after>/*-
 * Copyright (c) 1998,1999,2000,2001 <NAME>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer,
 *    without modification, immediately at the beginning of the file.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * $FreeBSD$
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/ata.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/bio.h>
#include <sys/bus.h>
#include <sys/disklabel.h>
#include <sys/devicestat.h>
#include <sys/cdio.h>
#include <sys/cdrio.h>
#include <sys/dvdio.h>
#include <sys/fcntl.h>
#include <sys/conf.h>
#include <sys/ctype.h>
#include <dev/ata/ata-all.h>
#include <dev/ata/atapi-all.h>
#include <dev/ata/atapi-cd.h>

/* device structures */
static d_open_t		acdopen;
static d_close_t	acdclose;
static d_ioctl_t	acdioctl;
static d_strategy_t	acdstrategy;
static struct cdevsw acd_cdevsw = {
	/* open */	acdopen,
	/* close */	acdclose,
	/* read */	physread,
	/* write */	physwrite,
	/* ioctl */	acdioctl,
	/* poll */	nopoll,
	/* mmap */	nommap,
	/* strategy */	acdstrategy,
	/* name */	"acd",
	/* maj */	117,
	/* dump */	nodump,
	/* psize */	nopsize,
	/* flags */	D_DISK | D_TRACKCLOSE,
};

/* prototypes */
static struct acd_softc *acd_init_lun(struct atapi_softc *, struct devstat *);
static void acd_make_dev(struct acd_softc *);
static void acd_describe(struct acd_softc *);
static void lba2msf(u_int32_t, u_int8_t *, u_int8_t *, u_int8_t *);
static u_int32_t msf2lba(u_int8_t, u_int8_t, u_int8_t);
static int acd_done(struct atapi_request *);
static void acd_read_toc(struct acd_softc *);
static int acd_play(struct acd_softc *, int, int);
static int acd_setchan(struct acd_softc *, u_int8_t, u_int8_t, u_int8_t, u_int8_t);
static void acd_select_slot(struct acd_softc *);
static int acd_open_disk(struct acd_softc *);
static int acd_close_disk(struct acd_softc *, int);
static int acd_open_track(struct acd_softc *, struct cdr_track *);
static int acd_close_track(struct acd_softc *);
static int acd_read_track_info(struct acd_softc *, int32_t, struct acd_track_info *);
static int acd_get_progress(struct acd_softc *, int *);
static int acd_report_key(struct acd_softc *, struct dvd_authinfo *);
static int acd_send_key(struct acd_softc *, struct dvd_authinfo *);
static int acd_read_structure(struct acd_softc *, struct dvd_struct *);
static int acd_eject(struct acd_softc *, int);
static int acd_blank(struct acd_softc *, int);
static int acd_prevent_allow(struct acd_softc *, int);
static int acd_start_stop(struct acd_softc *, int);
static int acd_pause_resume(struct acd_softc *, int);
static int acd_mode_sense(struct acd_softc *, int, caddr_t, int);
static int acd_mode_select(struct acd_softc *, caddr_t, int);
static int acd_set_speed(struct acd_softc *, int);
static void acd_get_cap(struct acd_softc *);

/* internal vars */
static u_int32_t acd_lun_map = 0;
static MALLOC_DEFINE(M_ACD, "ACD driver", "ATAPI CD driver buffers");

int
acdattach(struct atapi_softc *atp)
{
    struct acd_softc *cdp;
    struct changer *chp;
    char name[16];
    static int acd_cdev_done = 0;

    if (!acd_cdev_done) {
	cdevsw_add(&acd_cdevsw);
	acd_cdev_done++;
    }

    if ((cdp = acd_init_lun(atp, NULL)) == NULL) {
	ata_printf(atp->controller, atp->unit, "acd: out of memory\n");
	return -1;
    }

    sprintf(name, "acd%d", cdp->lun);
    ata_set_name(atp->controller, atp->unit, name);
    acd_get_cap(cdp);

    /* if this is a changer device, allocate the neeeded lun's */
    if (cdp->cap.mech == MST_MECH_CHANGER) {
	int8_t ccb[16] = { ATAPI_MECH_STATUS,
			   0, 0, 0, 0, 0, 0, 0, 
			   sizeof(struct changer)>>8, sizeof(struct changer),
			   0, 0, 0, 0, 0, 0 };

	chp = malloc(sizeof(struct changer), M_ACD, M_NOWAIT | M_ZERO);
	if (chp == NULL) {
	    ata_printf(atp->controller, atp->unit, "out of memory\n");
	    free(cdp, M_ACD);
	    return -1;
	}
	if (!atapi_queue_cmd(cdp->atp, ccb, (caddr_t)chp, 
			     sizeof(struct changer),
			     ATPR_F_READ, 60, NULL, NULL)) {
	    struct acd_softc *tmpcdp = cdp;
	    struct acd_softc **cdparr;
	    int count;

	    chp->table_length = htons(chp->table_length);
	    if (!(cdparr = malloc(sizeof(struct acd_softc) * chp->slots,
				 M_ACD, M_NOWAIT))) {
		ata_printf(atp->controller, atp->unit, "out of memory\n");
		free(chp, M_ACD);
		free(cdp, M_ACD);
		return -1;
	    }
	    for (count = 0; count < chp->slots; count++) {
		if (count > 0) {
		    tmpcdp = acd_init_lun(atp, cdp->stats);
		    if (!tmpcdp) {
			ata_printf(atp->controller,atp->unit,"out of memory\n");
			break;
		    }
		}
		cdparr[count] = tmpcdp;
		tmpcdp->driver = cdparr;
		tmpcdp->slot = count;
		tmpcdp->changer_info = chp;
	        acd_make_dev(tmpcdp);
	    }
	    sprintf(name, "acd%d-%d", cdp->lun, 
		    cdp->lun + cdp->changer_info->slots - 1);
	    ata_free_name(atp->controller, atp->unit);
	    ata_set_name(atp->controller, atp->unit, name);
	    devstat_add_entry(cdp->stats, name, tmpcdp->lun, DEV_BSIZE,
			      DEVSTAT_NO_ORDERED_TAGS,
			      DEVSTAT_TYPE_CDROM | DEVSTAT_TYPE_IF_IDE,
			      DEVSTAT_PRIORITY_CD);
	}
    }
    else {
	acd_make_dev(cdp);
	devstat_add_entry(cdp->stats, "acd", cdp->lun, DEV_BSIZE,
			  DEVSTAT_NO_ORDERED_TAGS,
			  DEVSTAT_TYPE_CDROM | DEVSTAT_TYPE_IF_IDE,
			  DEVSTAT_PRIORITY_CD);
    }
    cdp->atp->driver = cdp;
    acd_describe(cdp);
    return 0;
}

void
acddetach(struct atapi_softc *atp)
{   
    struct acd_softc *cdp = atp->driver;
    struct acd_devlist *entry;
    struct bio *bp;
    int subdev;
    
    if (cdp->changer_info) {
	for (subdev = 0; subdev < cdp->changer_info->slots; subdev++) {
	    if (cdp->driver[subdev] == cdp)
		continue;
	    while ((bp = bioq_first(&cdp->driver[subdev]->queue))) {
        	biofinish(bp, NULL, ENXIO);
	    }
	    destroy_dev(cdp->driver[subdev]->dev1);
	    destroy_dev(cdp->driver[subdev]->dev2);
	    while ((entry = TAILQ_FIRST(&cdp->driver[subdev]->dev_list))) {
		destroy_dev(entry->dev);
		TAILQ_REMOVE(&cdp->driver[subdev]->dev_list, entry, chain);
		free(entry, M_ACD);
	    }
	    devstat_remove_entry(cdp->driver[subdev]->stats);
	    free(cdp->driver[subdev]->stats, M_ACD);
	    ata_free_lun(&acd_lun_map, cdp->driver[subdev]->lun);
	    free(cdp->driver[subdev], M_ACD);
	}
	free(cdp->driver, M_ACD);
	free(cdp->changer_info, M_ACD);
    }
    while ((bp = bioq_first(&cdp->queue))) {
        biofinish(bp, NULL, ENXIO);
    }
    destroy_dev(cdp->dev1);
    destroy_dev(cdp->dev2);
    while ((entry = TAILQ_FIRST(&cdp->dev_list))) {
	destroy_dev(entry->dev);
	TAILQ_REMOVE(&cdp->dev_list, entry, chain);
	free(entry, M_ACD);
    }
    devstat_remove_entry(cdp->stats);
    free(cdp->stats, M_ACD);
    ata_free_name(atp->controller, atp->unit);
    ata_free_lun(&acd_lun_map, cdp->lun);
    free(cdp, M_ACD);
}

static struct acd_softc *
acd_init_lun(struct atapi_softc *atp, struct devstat *stats)
{
    struct acd_softc *cdp;

    if (!(cdp = malloc(sizeof(struct acd_softc), M_ACD, M_NOWAIT | M_ZERO)))
	return NULL;
    TAILQ_INIT(&cdp->dev_list);
    bioq_init(&cdp->queue);
    cdp->atp = atp;
    cdp->lun = ata_get_lun(&acd_lun_map);
    cdp->block_size = 2048;
    cdp->slot = -1;
    cdp->changer_info = NULL;
    if (stats == NULL) {
	if (!(cdp->stats = malloc(sizeof(struct devstat), M_ACD,
				  M_NOWAIT | M_ZERO))) {
	    free(cdp, M_ACD);
	    return NULL;
	}
    }
    else
	cdp->stats = stats;
    return cdp;
}

static void
acd_make_dev(struct acd_softc *cdp)
{
    dev_t dev;

    dev = make_dev(&acd_cdevsw, dkmakeminor(cdp->lun, 0, 0),
		   UID_ROOT, GID_OPERATOR, 0644, "acd%da", cdp->lun);
    dev->si_drv1 = cdp;
    dev->si_iosize_max = 252 * DEV_BSIZE;
    dev->si_bsize_phys = 2048; /* XXX SOS */
    cdp->dev1 = dev;
    dev = make_dev(&acd_cdevsw, dkmakeminor(cdp->lun, 0, RAW_PART),
		   UID_ROOT, GID_OPERATOR, 0644, "acd%dc", cdp->lun);
    dev->si_drv1 = cdp;
    dev->si_iosize_max = 252 * DEV_BSIZE;
    dev->si_bsize_phys = 2048; /* XXX SOS */
    cdp->dev2 = dev;
    cdp->atp->flags |= ATAPI_F_MEDIA_CHANGED;
}

static void 
acd_describe(struct acd_softc *cdp)
{
    int comma = 0;
    char *mechanism;

    if (bootverbose) {
	ata_printf(cdp->atp->controller, cdp->atp->unit,
		   "<%.40s/%.8s> %s drive at ata%d as %s\n",
		   ATA_PARAM(cdp->atp->controller, cdp->atp->unit)->model,
		   ATA_PARAM(cdp->atp->controller, cdp->atp->unit)->revision,
		   (cdp->cap.write_dvdr) ? "DVD-R" : 
		    (cdp->cap.write_dvdram) ? "DVD-RAM" : 
		     (cdp->cap.write_cdrw) ? "CD-RW" :
		      (cdp->cap.write_cdr) ? "CD-R" : 
		       (cdp->cap.read_dvdrom) ? "DVD-ROM" : "CDROM",
		   device_get_unit(cdp->atp->controller->dev),
		   (cdp->atp->unit == ATA_MASTER) ? "master" : "slave");

	ata_printf(cdp->atp->controller, cdp->atp->unit, "%s", "");
	if (cdp->cap.cur_read_speed) {
	    printf("read %dKB/s", cdp->cap.cur_read_speed * 1000 / 1024);
	    if (cdp->cap.max_read_speed) 
		printf(" (%dKB/s)", cdp->cap.max_read_speed * 1000 / 1024);
	    if ((cdp->cap.cur_write_speed) &&
		(cdp->cap.write_cdr || cdp->cap.write_cdrw || 
		 cdp->cap.write_dvdr || cdp->cap.write_dvdram)) {
		printf(" write %dKB/s", cdp->cap.cur_write_speed * 1000 / 1024);
		if (cdp->cap.max_write_speed)
		    printf(" (%dKB/s)", cdp->cap.max_write_speed * 1000 / 1024);
	    }
	    comma = 1;
	}
	if (cdp->cap.buf_size) {
	    printf("%s %dKB buffer", comma ? "," : "", cdp->cap.buf_size);
	    comma = 1;
	}
	printf("%s %s\n", 
	       comma ? "," : "", ata_mode2str(
		cdp->atp->controller->mode[ATA_DEV(cdp->atp->unit)]));

	ata_printf(cdp->atp->controller, cdp->atp->unit, "Reads:");
	comma = 0;
	if (cdp->cap.read_cdr) {
	    printf(" CD-R"); comma = 1;
	}
	if (cdp->cap.read_cdrw) {
	    printf("%s CD-RW", comma ? "," : ""); comma = 1;
	}
	if (cdp->cap.cd_da) {
	    if (cdp->cap.cd_da_stream)
	    printf("%s CD-DA stream", comma ? "," : "");
	    else
	    printf("%s CD-DA", comma ? "," : "");
	    comma = 1;
	}
	if (cdp->cap.read_dvdrom) {
	    printf("%s DVD-ROM", comma ? "," : ""); comma = 1;
	}
	if (cdp->cap.read_dvdr) {
	    printf("%s DVD-R", comma ? "," : ""); comma = 1;
	}
	if (cdp->cap.read_dvdram) {
	    printf("%s DVD-RAM", comma ? "," : ""); comma = 1;
	}
	if (cdp->cap.read_packet)
	    printf("%s packet", comma ? "," : "");

	printf("\n");
	ata_printf(cdp->atp->controller, cdp->atp->unit, "Writes:");
	if (cdp->cap.write_cdr || cdp->cap.write_cdrw || 
	    cdp->cap.write_dvdr || cdp->cap.write_dvdram) {
	    comma = 0;
	    if (cdp->cap.write_cdr) {
		printf(" CD-R" ); comma = 1;
	    }
	    if (cdp->cap.write_cdrw) {
		printf("%s CD-RW", comma ? "," : ""); comma = 1;
	    }
	    if (cdp->cap.write_dvdr) {
		printf("%s DVD-R", comma ? "," : ""); comma = 1;
	    }
	    if (cdp->cap.write_dvdram) {
		printf("%s DVD-RAM", comma ? "," : ""); comma = 1; 
	    }
	    if (cdp->cap.test_write) {
		printf("%s test write", comma ? "," : ""); comma = 1;
	    }
	    if (cdp->cap.burnproof)
		printf("%s burnproof", comma ? "," : "");
	}
	printf("\n");
	if (cdp->cap.audio_play) {
	    ata_printf(cdp->atp->controller, cdp->atp->unit, "Audio: ");
	    if (cdp->cap.audio_play)
		printf("play");
	    if (cdp->cap.max_vol_levels)
		printf(", %d volume levels", cdp->cap.max_vol_levels);
	    printf("\n");
	}
	ata_printf(cdp->atp->controller, cdp->atp->unit, "Mechanism: ");
	switch (cdp->cap.mech) {
	case MST_MECH_CADDY:
	    mechanism = "caddy"; break;
	case MST_MECH_TRAY:
	    mechanism = "tray"; break;
	case MST_MECH_POPUP:
	    mechanism = "popup"; break;
	case MST_MECH_CHANGER:
	    mechanism = "changer"; break;
	case MST_MECH_CARTRIDGE:
	    mechanism = "cartridge"; break;
	default:
	    mechanism = 0; break;
	}
	if (mechanism)
	    printf("%s%s", cdp->cap.eject ? "ejectable " : "", mechanism);
	else if (cdp->cap.eject)
	    printf("ejectable");

	if (cdp->cap.mech != MST_MECH_CHANGER) {
	    ata_printf(cdp->atp->controller, cdp->atp->unit, "Medium: ");
	    switch (cdp->cap.medium_type & MST_TYPE_MASK_HIGH) {
	    case MST_CDROM:
		printf("CD-ROM "); break;
	    case MST_CDR:
		printf("CD-R "); break;
	    case MST_CDRW:
		printf("CD-RW "); break;
	    case MST_DOOR_OPEN:
		printf("door open"); break;
	    case MST_NO_DISC:
		printf("no/blank disc"); break;
	    case MST_FMT_ERROR:
		printf("medium format error"); break;
	    }
	    if ((cdp->cap.medium_type & MST_TYPE_MASK_HIGH)<MST_TYPE_MASK_HIGH){
		switch (cdp->cap.medium_type & MST_TYPE_MASK_LOW) {
		case MST_DATA_120:
		    printf("120mm data disc"); break;
		case MST_AUDIO_120:
		    printf("120mm audio disc"); break;
		case MST_COMB_120:
		    printf("120mm data/audio disc"); break;
		case MST_PHOTO_120:
		    printf("120mm photo disc"); break;
		case MST_DATA_80:
		    printf("80mm data disc"); break;
		case MST_AUDIO_80:
		    printf("80mm audio disc"); break;
		case MST_COMB_80:
		    printf("80mm data/audio disc"); break;
		case MST_PHOTO_80:
		    printf("80mm photo disc"); break;
		case MST_FMT_NONE:
		    switch (cdp->cap.medium_type & MST_TYPE_MASK_HIGH) {
		    case MST_CDROM:
			printf("unknown"); break;
		    case MST_CDR:
		    case MST_CDRW:
			printf("blank"); break;
		    }
		    break;
		default:
		    printf("unknown (0x%x)", cdp->cap.medium_type); break;
		}
	    }
	}
	if (cdp->cap.lock)
	    printf(cdp->cap.locked ? ", locked" : ", unlocked");
	if (cdp->cap.prevent)
	    printf(", lock protected");
	printf("\n");
    }
    else {
	char chg[32];

	bzero(chg, sizeof(chg));
	if (cdp->changer_info)
	    sprintf(chg, " with %d CD changer", cdp->changer_info->slots);

	ata_printf(cdp->atp->controller, cdp->atp->unit,
		   "%s%s <%.40s> at ata%d-%s %s\n",
		   (cdp->cap.write_dvdr) ? "DVD-R" : 
		    (cdp->cap.write_dvdram) ? "DVD-RAM" : 
		     (cdp->cap.write_cdrw) ? "CD-RW" :
		      (cdp->cap.write_cdr) ? "CD-R" : 
		       (cdp->cap.read_dvdrom) ? "DVD-ROM" : "CDROM",
		   chg, ATA_PARAM(cdp->atp->controller, cdp->atp->unit)->model,
		   device_get_unit(cdp->atp->controller->dev),
		   (cdp->atp->unit == ATA_MASTER) ? "master" : "slave",
		   ata_mode2str(cdp->atp->controller->
				mode[ATA_DEV(cdp->atp->unit)])
	       );
    }
}

static __inline void 
lba2msf(u_int32_t lba, u_int8_t *m, u_int8_t *s, u_int8_t *f)
{
    lba += 150;
    lba &= 0xffffff;
    *m = lba / (60 * 75);
    lba %= (60 * 75);
    *s = lba / 75;
    *f = lba % 75;
}

static __inline u_int32_t 
msf2lba(u_int8_t m, u_int8_t s, u_int8_t f)
{
    return (m * 60 + s) * 75 + f - 150;
}

static int
acdopen(dev_t dev, int flags, int fmt, struct proc *p)
{
    struct acd_softc *cdp = dev->si_drv1;
    
    if (!cdp)
	return ENXIO;

    if (flags & FWRITE) {
	if (count_dev(dev) > 1)
	    return EBUSY;
    }
    if (count_dev(dev) == 1) {
	if (cdp->changer_info && cdp->slot != cdp->changer_info->current_slot) {
	    acd_select_slot(cdp);
	    tsleep(&cdp->changer_info, PRIBIO, "acdopn", 0);
	}
	acd_prevent_allow(cdp, 1);
	cdp->flags |= F_LOCKED;
	acd_read_toc(cdp);
    }
    return 0;
}

static int 
acdclose(dev_t dev, int flags, int fmt, struct proc *p)
{
    struct acd_softc *cdp = dev->si_drv1;
    
    if (!cdp)
	return ENXIO;

    if (count_dev(dev) == 1) {
	if (cdp->changer_info && cdp->slot != cdp->changer_info->current_slot) {
	    acd_select_slot(cdp);
	    tsleep(&cdp->changer_info, PRIBIO, "acdclo", 0);
	}
	acd_prevent_allow(cdp, 0);
	cdp->flags &= ~F_LOCKED;
    }
    return 0;
}

static int 
acdioctl(dev_t dev, u_long cmd, caddr_t addr, int flags, struct proc *p)
{
    struct acd_softc *cdp = dev->si_drv1;
    int error = 0;

    if (!cdp)
	return ENXIO;

    if (cdp->changer_info && cdp->slot != cdp->changer_info->current_slot) {
	acd_select_slot(cdp);
	tsleep(&cdp->changer_info, PRIBIO, "acdctl", 0);
    }
    if (cdp->atp->flags & ATAPI_F_MEDIA_CHANGED)
	switch (cmd) {
	case CDIOCRESET:
	    atapi_test_ready(cdp->atp);
	    break;
	   
	default:
	    acd_read_toc(cdp);
	    acd_prevent_allow(cdp, 1);
	    cdp->flags |= F_LOCKED;
	    break;
	}
    switch (cmd) {

    case CDIOCRESUME:
	error = acd_pause_resume(cdp, 1);
	break;

    case CDIOCPAUSE:
	error = acd_pause_resume(cdp, 0);
	break;

    case CDIOCSTART:
	error = acd_start_stop(cdp, 1);
	break;

    case CDIOCSTOP:
	error = acd_start_stop(cdp, 0);
	break;

    case CDIOCALLOW:
	error = acd_prevent_allow(cdp, 0);
	cdp->flags &= ~F_LOCKED;
	break;

    case CDIOCPREVENT:
	error = acd_prevent_allow(cdp, 1);
	cdp->flags |= F_LOCKED;
	break;

    case CDIOCRESET:
	error = suser(p);
	if (error)
	    break;
	error = atapi_test_ready(cdp->atp);
	break;

    case CDIOCEJECT:
	if (count_dev(dev) > 1) {
	    error = EBUSY;
	    break;
	}
	error = acd_eject(cdp, 0);
	break;

    case CDIOCCLOSE:
	if (count_dev(dev) > 1)
	    break;
	error = acd_eject(cdp, 1);
	break;

    case CDIOREADTOCHEADER:
	if (!cdp->toc.hdr.ending_track) {
	    error = EIO;
	    break;
	}
	bcopy(&cdp->toc.hdr, addr, sizeof(cdp->toc.hdr));
	break;

    case CDIOREADTOCENTRYS:
	{
	    struct ioc_read_toc_entry *te = (struct ioc_read_toc_entry *)addr;
	    struct toc *toc = &cdp->toc;
	    struct toc buf;
	    int starting_track = te->starting_track;
	    int len;

	    if (!cdp->toc.hdr.ending_track) {
		error = EIO;
		break;
	    }

	    if (te->data_len < sizeof(toc->tab[0]) || 
		(te->data_len % sizeof(toc->tab[0])) != 0 || 
		(te->address_format != CD_MSF_FORMAT &&
		te->address_format != CD_LBA_FORMAT)) {
		error = EINVAL;
		break;
	    }

	    if (!starting_track)
		starting_track = toc->hdr.starting_track;
	    else if (starting_track == 170) 
		starting_track = toc->hdr.ending_track + 1;
	    else if (starting_track < toc->hdr.starting_track ||
		     starting_track > toc->hdr.ending_track + 1) {
		error = EINVAL;
		break;
	    }

	    len = ((toc->hdr.ending_track + 1 - starting_track) + 1) *
		  sizeof(toc->tab[0]);
	    if (te->data_len < len)
		len = te->data_len;
	    if (len > sizeof(toc->tab)) {
		error = EINVAL;
		break;
	    }

	    if (te->address_format == CD_MSF_FORMAT) {
		struct cd_toc_entry *entry;

		buf = cdp->toc;
		toc = &buf;
		entry = toc->tab + (toc->hdr.ending_track + 1 -
			toc->hdr.starting_track) + 1;
		while (--entry >= toc->tab)
		    lba2msf(ntohl(entry->addr.lba), &entry->addr.msf.minute,
			    &entry->addr.msf.second, &entry->addr.msf.frame);
	    }
	    error = copyout(toc->tab + starting_track - toc->hdr.starting_track,
			    te->data, len);
	    break;
	}
    case CDIOREADTOCENTRY:
	{
	    struct ioc_read_toc_single_entry *te =
		(struct ioc_read_toc_single_entry *)addr;
	    struct toc *toc = &cdp->toc;
	    struct toc buf;
	    u_char track = te->track;

	    if (!cdp->toc.hdr.ending_track) {
		error = EIO;
		break;
	    }

	    if (te->address_format != CD_MSF_FORMAT && 
		te->address_format != CD_LBA_FORMAT) {
		error = EINVAL;
		break;
	    }

	    if (!track)
		track = toc->hdr.starting_track;
	    else if (track == 170)
		track = toc->hdr.ending_track + 1;
	    else if (track < toc->hdr.starting_track ||
		     track > toc->hdr.ending_track + 1) {
		error = EINVAL;
		break;
	    }

	    if (te->address_format == CD_MSF_FORMAT) {
		struct cd_toc_entry *entry;

		buf = cdp->toc;
		toc = &buf;
		entry = toc->tab + (track - toc->hdr.starting_track);
		lba2msf(ntohl(entry->addr.lba), &entry->addr.msf.minute,
			&entry->addr.msf.second, &entry->addr.msf.frame);
	    }
	    bcopy(toc->tab + track - toc->hdr.starting_track,
		  &te->entry, sizeof(struct cd_toc_entry));
	}
	break;

    case CDIOCREADSUBCHANNEL:
	{
	    struct ioc_read_subchannel *args =
		(struct ioc_read_subchannel *)addr;
	    struct cd_sub_channel_info data;
	    int len = args->data_len;
	    int32_t abslba, rellba;
	    int8_t ccb[16] = { ATAPI_READ_SUBCHANNEL, 0, 0x40, 1, 0, 0, 0,
			       sizeof(cdp->subchan)>>8, sizeof(cdp->subchan),
			       0, 0, 0, 0, 0, 0, 0 };

	    if (len > sizeof(data) ||
		len < sizeof(struct cd_sub_channel_header)) {
		error = EINVAL;
		break;
	    }

	    if ((error = atapi_queue_cmd(cdp->atp, ccb, (caddr_t)&cdp->subchan, 
					 sizeof(cdp->subchan), ATPR_F_READ, 10,
					 NULL, NULL))) {
		break;
	    }
	    abslba = cdp->subchan.abslba;
	    rellba = cdp->subchan.rellba;
	    if (args->address_format == CD_MSF_FORMAT) {
		lba2msf(ntohl(abslba),
		    &data.what.position.absaddr.msf.minute,
		    &data.what.position.absaddr.msf.second,
		    &data.what.position.absaddr.msf.frame);
		lba2msf(ntohl(rellba),
		    &data.what.position.reladdr.msf.minute,
		    &data.what.position.reladdr.msf.second,
		    &data.what.position.reladdr.msf.frame);
	    } else {
		data.what.position.absaddr.lba = abslba;
		data.what.position.reladdr.lba = rellba;
	    }
	    data.header.audio_status = cdp->subchan.audio_status;
	    data.what.position.control = cdp->subchan.control & 0xf;
	    data.what.position.addr_type = cdp->subchan.control >> 4;
	    data.what.position.track_number = cdp->subchan.track;
	    data.what.position.index_number = cdp->subchan.indx;
	    error = copyout(&data, args->data, len);
	    break;
	}

    case CDIOCPLAYMSF:
	{
	    struct ioc_play_msf *args = (struct ioc_play_msf *)addr;

	    error = 
		acd_play(cdp, 
			 msf2lba(args->start_m, args->start_s, args->start_f),
			 msf2lba(args->end_m, args->end_s, args->end_f));
	    break;
	}

    case CDIOCPLAYBLOCKS:
	{
	    struct ioc_play_blocks *args = (struct ioc_play_blocks *)addr;

	    error = acd_play(cdp, args->blk, args->blk + args->len);
	    break;
	}

    case CDIOCPLAYTRACKS:
	{
	    struct ioc_play_track *args = (struct ioc_play_track *)addr;
	    int t1, t2;

	    if (!cdp->toc.hdr.ending_track) {
		error = EIO;
		break;
	    }
	    if (args->end_track < cdp->toc.hdr.ending_track + 1)
		++args->end_track;
	    if (args->end_track > cdp->toc.hdr.ending_track + 1)
		args->end_track = cdp->toc.hdr.ending_track + 1;
	    t1 = args->start_track - cdp->toc.hdr.starting_track;
	    t2 = args->end_track - cdp->toc.hdr.starting_track;
	    if (t1 < 0 || t2 < 0 ||
		t1 > (cdp->toc.hdr.ending_track-cdp->toc.hdr.starting_track)) {
		error = EINVAL;
		break;
	    }
	    error = acd_play(cdp, ntohl(cdp->toc.tab[t1].addr.lba),
			     ntohl(cdp->toc.tab[t2].addr.lba));
	    break;
	}

    case CDIOCREADAUDIO:
	{
	    struct ioc_read_audio *args = (struct ioc_read_audio *)addr;
	    int32_t lba;
	    caddr_t buffer, ubuf = args->buffer;
	    int8_t ccb[16];
	    int frames;

	    if (!cdp->toc.hdr.ending_track) {
		error = EIO;
		break;
	    }
		
	    if ((frames = args->nframes) < 0) {
		error = EINVAL;
		break;
	    }

	    if (args->address_format == CD_LBA_FORMAT)
		lba = args->address.lba;
	    else if (args->address_format == CD_MSF_FORMAT)
		lba = msf2lba(args->address.msf.minute,
			     args->address.msf.second,
			     args->address.msf.frame);
	    else {
		error = EINVAL;
		break;
	    }

#ifndef CD_BUFFER_BLOCKS
#define CD_BUFFER_BLOCKS 13
#endif
	    if (!(buffer = malloc(CD_BUFFER_BLOCKS * 2352, M_ACD, M_NOWAIT))){
		error = ENOMEM;
		break;
	    }
	    bzero(ccb, sizeof(ccb));
	    while (frames > 0) {
		int8_t blocks;
		int size;

		blocks = (frames>CD_BUFFER_BLOCKS) ? CD_BUFFER_BLOCKS : frames;
		size = blocks * 2352;

		ccb[0] = ATAPI_READ_CD;
		ccb[1] = 4;
		ccb[2] = lba>>24;
		ccb[3] = lba>>16;
		ccb[4] = lba>>8;
		ccb[5] = lba;
		ccb[8] = blocks;
		ccb[9] = 0xf0;
		if ((error = atapi_queue_cmd(cdp->atp, ccb, buffer, size, 
					     ATPR_F_READ, 30, NULL,NULL)))
		    break;

		if ((error = copyout(buffer, ubuf, size)))
		    break;
		    
		ubuf += size;
		frames -= blocks;
		lba += blocks;
	    }
	    free(buffer, M_ACD);
	    if (args->address_format == CD_LBA_FORMAT)
		args->address.lba = lba;
	    else if (args->address_format == CD_MSF_FORMAT)
		lba2msf(lba, &args->address.msf.minute,
			     &args->address.msf.second,
			     &args->address.msf.frame);
	    break;
	}

    case CDIOCGETVOL:
	{
	    struct ioc_vol *arg = (struct ioc_vol *)addr;

	    if ((error = acd_mode_sense(cdp, ATAPI_CDROM_AUDIO_PAGE,
					(caddr_t)&cdp->au, sizeof(cdp->au))))
		break;

	    if (cdp->au.page_code != ATAPI_CDROM_AUDIO_PAGE) {
		error = EIO;
		break;
	    }
	    arg->vol[0] = cdp->au.port[0].volume;
	    arg->vol[1] = cdp->au.port[1].volume;
	    arg->vol[2] = cdp->au.port[2].volume;
	    arg->vol[3] = cdp->au.port[3].volume;
	    break;
	}

    case CDIOCSETVOL:
	{
	    struct ioc_vol *arg = (struct ioc_vol *)addr;

	    if ((error = acd_mode_sense(cdp, ATAPI_CDROM_AUDIO_PAGE,
					(caddr_t)&cdp->au, sizeof(cdp->au))))
		break;
	    if (cdp->au.page_code != ATAPI_CDROM_AUDIO_PAGE) {
		error = EIO;
		break;
	    }
	    if ((error = acd_mode_sense(cdp, ATAPI_CDROM_AUDIO_PAGE_MASK,
					(caddr_t)&cdp->aumask,
					sizeof(cdp->aumask))))
		break;
	    cdp->au.data_length = 0;
	    cdp->au.port[0].channels = CHANNEL_0;
	    cdp->au.port[1].channels = CHANNEL_1;
	    cdp->au.port[0].volume = arg->vol[0] & cdp->aumask.port[0].volume;
	    cdp->au.port[1].volume = arg->vol[1] & cdp->aumask.port[1].volume;
	    cdp->au.port[2].volume = arg->vol[2] & cdp->aumask.port[2].volume;
	    cdp->au.port[3].volume = arg->vol[3] & cdp->aumask.port[3].volume;
	    error =  acd_mode_select(cdp, (caddr_t)&cdp->au, sizeof(cdp->au));
	    break;
	}
    case CDIOCSETPATCH:
	{
	    struct ioc_patch *arg = (struct ioc_patch *)addr;

	    error = acd_setchan(cdp, arg->patch[0], arg->patch[1],
				arg->patch[2], arg->patch[3]);
	    break;
	}

    case CDIOCSETMONO:
	error = acd_setchan(cdp, CHANNEL_0|CHANNEL_1, CHANNEL_0|CHANNEL_1, 0,0);
	break;

    case CDIOCSETSTEREO:
	error = acd_setchan(cdp, CHANNEL_0, CHANNEL_1, 0, 0);
	break;

    case CDIOCSETMUTE:
	error = acd_setchan(cdp, 0, 0, 0, 0);
	break;

    case CDIOCSETLEFT:
	error = acd_setchan(cdp, CHANNEL_0, CHANNEL_0, 0, 0);
	break;

    case CDIOCSETRIGHT:
	error = acd_setchan(cdp, CHANNEL_1, CHANNEL_1, 0, 0);
	break;

    case CDRIOCBLANK:
	error = acd_blank(cdp, (*(int *)addr));
	break;

    case CDRIOCNEXTWRITEABLEADDR:
	{
	    struct acd_track_info track_info;

	    if ((error = acd_read_track_info(cdp, 0xff, &track_info)))
		break;

	    if (!track_info.nwa_valid) {
		error = EINVAL;
		break;
	    }
	    *(int*)addr = track_info.next_writeable_addr;
	}
	break;
 
    case CDRIOCOPENDISK:
	error = acd_open_disk(cdp);
	break;

    case CDRIOCOPENTRACK:
	error = acd_open_track(cdp, (struct cdr_track *)addr);
	break;

    case CDRIOCCLOSETRACK:
	error = acd_close_track(cdp);
	break;

    case CDRIOCCLOSEDISK:
	error = acd_close_disk(cdp, (*(int *)addr));
	break;

    case CDRIOCWRITESPEED:
	error = acd_set_speed(cdp, (*(int *)addr));
	break;

    case CDRIOCGETBLOCKSIZE:
	*(int *)addr = cdp->block_size;
	break;

    case CDRIOCSETBLOCKSIZE:
	cdp->block_size = *(int *)addr;
	break;

    case CDRIOCGETPROGRESS:
        error = acd_get_progress(cdp, (int *)addr);
	break;

    case DVDIOCREPORTKEY:
	if (!cdp->cap.read_dvdrom)
	    error = EINVAL;
	else
	    error = acd_report_key(cdp, (struct dvd_authinfo *)addr);
	break;

    case DVDIOCSENDKEY:
	if (!cdp->cap.read_dvdrom)
	    error = EINVAL;
	else
	    error = acd_send_key(cdp, (struct dvd_authinfo *)addr);
	break;

    case DVDIOCREADSTRUCTURE:
	if (!cdp->cap.read_dvdrom)
	    error = EINVAL;
	else
	    error = acd_read_structure(cdp, (struct dvd_struct *)addr);
	break;

    case DIOCGDINFO:
	*(struct disklabel *)addr = cdp->disklabel;
	break;

    case DIOCWDINFO:
    case DIOCSDINFO:
	if ((flags & FWRITE) == 0)
	    error = EBADF;
	else
	    error = setdisklabel(&cdp->disklabel, (struct disklabel *)addr, 0);
	break;

    case DIOCWLABEL:
	error = EBADF;
	break;

    case DIOCGPART:
	((struct partinfo *)addr)->disklab = &cdp->disklabel;
	((struct partinfo *)addr)->part = &cdp->disklabel.d_partitions[0];
	break;

    default:
	error = ENOTTY;
    }
    return error;
}

static void 
acdstrategy(struct bio *bp)
{
    struct acd_softc *cdp = bp->bio_dev->si_drv1;
    int s;

    if (cdp->atp->flags & ATAPI_F_DETACHING) {
	biofinish(bp, NULL, ENXIO);
	return;
    }

    /* if it's a null transfer, return immediatly. */
    if (bp->bio_bcount == 0) {
	bp->bio_resid = 0;
	biodone(bp);
	return;
    }
    
    bp->bio_pblkno = bp->bio_blkno;
    bp->bio_resid = bp->bio_bcount;

    s = splbio();
    bioqdisksort(&cdp->queue, bp);
    ata_start(cdp->atp->controller);
    splx(s);
}

void 
acd_start(struct atapi_softc *atp)
{
    struct acd_softc *cdp = atp->driver;
    struct bio *bp = bioq_first(&cdp->queue);
    u_int32_t lba, lastlba, count;
    int8_t ccb[16];
    int track, blocksize;

    if (cdp->changer_info) {
	int i;

	cdp = cdp->driver[cdp->changer_info->current_slot];
	bp = bioq_first(&cdp->queue);

	/* check for work pending on any other slot */
	for (i = 0; i < cdp->changer_info->slots; i++) {
	    if (i == cdp->changer_info->current_slot)
		continue;
	    if (bioq_first(&(cdp->driver[i]->queue))) {
	        if (!bp || time_second > (cdp->timestamp + 10)) {
		    acd_select_slot(cdp->driver[i]);
		    return;
		}
	    }
	}
    }
    if (!bp)
	return;
    bioq_remove(&cdp->queue, bp);

    /* reject all queued entries if media changed */
    if (cdp->atp->flags & ATAPI_F_MEDIA_CHANGED) {
	biofinish(bp, NULL, EIO);
	return;
    }

    bzero(ccb, sizeof(ccb));

    lba = bp->bio_offset / cdp->block_size;
    track = (bp->bio_dev->si_udev & 0x00ff0000) >> 16;

    if (track) {
	blocksize = (cdp->toc.tab[track - 1].control & 4) ? 2048 : 2352;
	lastlba = ntohl(cdp->toc.tab[track].addr.lba);
	lba += ntohl(cdp->toc.tab[track - 1].addr.lba);
    }
    else {
	blocksize = cdp->block_size;
	lastlba = cdp->disk_size;
    }

    if (bp->bio_bcount % blocksize != 0) {
	biofinish(bp, NULL, EINVAL);
	return;
    }
    count = bp->bio_bcount / blocksize;

    if (bp->bio_cmd == BIO_READ) {
	/* if transfer goes beyond range adjust it to be within limits */
	if (lba + count > lastlba) {
	    /* if we are entirely beyond EOM return EOF */
	    if ((count = lastlba - lba) <= 0) {
		bp->bio_resid = bp->bio_bcount;
		biodone(bp);
		return;
	    }
	}
	switch (blocksize) {
	case 2048:
	    ccb[0] = ATAPI_READ_BIG;
	    break;

	case 2352: 
{'fraction_non_alphanumeric': 0.15661459993624482, 'fraction_numerical': 0.01491871214536181, 'mean_word_length': 3.1539327330508473, 'pattern_counts': {'":': 0, '<': 73, '<?xml version=': 0, '>': 1006, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4786857', 'n_tokens_mistral': 28144, 'n_tokens_neox': 25689, 'n_words': 5073}