code:
/*	$OpenBSD: asms.c,v 1.7 2008/04/25 16:37:44 xsa Exp $	*/
/*
 * Copyright (c) 2005 Xavier Santolaria <xsa@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * A driver for the Apple Sudden Motion Sensor based on notes from
 * http://johannes.sipsolutions.net/PowerBook/Apple_Motion_Sensor_Specification
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/sensors.h>

#include <dev/i2c/i2cvar.h>

/* ASMS Registers */
#define ASMS_REG_COMMAND	0x00
#define ASMS_REG_STATUS		0x01
#define ASMS_REG_RCONTROL1	0x02
#define ASMS_REG_RCONTROL2	0x03
#define ASMS_REG_RCONTROL3	0x04
#define ASMS_REG_RDATA1		0x05
#define ASMS_REG_RDATA2		0x06
#define ASMS_REG_DATA_X		0x20
#define ASMS_REG_DATA_Y		0x21
#define ASMS_REG_DATA_Z		0x22
#define ASMS_REG_SENS_LOW	0x26	/* init with 0x15 */
#define ASMS_REG_SENS_HIGH	0x27	/* init with 0x60 */
#define ASMS_REG_CONTROL_X	0x28	/* init with 0x08 */
#define ASMS_REG_CONTROL_Y	0x29	/* init with 0x0f */
#define ASMS_REG_CONTROL_Z	0x2a	/* init with 0x4f */
#define ASMS_REG_UNKNOWN1	0x2b	/* init with 0x14 */
#define ASMS_REG_VENDOR		0x2e
#define ASMS_CMD_READ_VER	0x01
#define ASMS_CMD_READ_MEM	0x02
#define ASMS_CMD_RESET		0x07
#define ASMS_CMD_START		0x08

/* Sensors */
#define ASMS_DATA_X		0
#define ASMS_DATA_Y		1
#define ASMS_DATA_Z		2
#define ASMS_NUM_SENSORS	3

struct asms_softc {
	struct device	sc_dev;
	i2c_tag_t	sc_tag;
	i2c_addr_t	sc_addr;

	struct ksensor	sc_sensor[ASMS_NUM_SENSORS];
	struct ksensordev sc_sensordev;
};

int	asms_match(struct device *, void *, void *);
void	asms_attach(struct device *, struct device *, void *);
void	asms_refresh(void *);

struct cfattach asms_ca = {
	sizeof(struct asms_softc), asms_match, asms_attach
};

struct cfdriver asms_cd = {
	NULL, "asms", DV_DULL
};

int
asms_match(struct device *parent, void *match, void *aux)
{
	struct i2c_attach_args *ia = aux;

	if (strcmp(ia->ia_name, "AAPL,accelerometer_1") == 0)
		return (1);
	return (0);
}

void
asms_attach(struct device *parent, struct device *self, void *aux)
{
	struct asms_softc *sc = (struct asms_softc *)self;
	struct i2c_attach_args *ia = aux;
	u_int8_t cmd, data, rev1, rev2, ver1, ver2;
	int i, vflag = 0;

	sc->sc_tag = ia->ia_tag;
	sc->sc_addr = ia ->ia_addr;

	iic_acquire_bus(sc->sc_tag, 0);

	cmd = ASMS_REG_COMMAND; data = ASMS_CMD_START;
	if (iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &data, sizeof data, 0)) {
		iic_release_bus(sc->sc_tag, 0);
		printf(": cannot write command register\n");
		return;
	}
	delay(10000);

	cmd = ASMS_REG_RCONTROL1; data = 0x02;
	if (iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &data, sizeof data, 0)) {
		iic_release_bus(sc->sc_tag, 0);
		printf(": cannot write read control register\n");
		return;
	}

	cmd = ASMS_REG_RCONTROL2; data = 0x85;
	if (iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &data, sizeof data, 0)) {
		iic_release_bus(sc->sc_tag, 0);
		printf(": cannot write read control register\n");
		return;
	}

	cmd = ASMS_REG_RCONTROL3; data = 0x01;
	if (iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &data, sizeof data, 0)) {
		iic_release_bus(sc->sc_tag, 0);
		printf(": cannot write read control register\n");
		return;
	}

	cmd = ASMS_REG_COMMAND; data = ASMS_CMD_READ_MEM;
	if (iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &data, sizeof data, 0)) {
		iic_release_bus(sc->sc_tag, 0);
		printf(": cannot write command register\n");
		return;
	}
	delay(10000);

	cmd = ASMS_REG_RDATA1;
	if (iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &rev1, sizeof rev1, 0)) {
		iic_release_bus(sc->sc_tag, 0);
		printf(": cannot read data register\n");
		return;
	}

	cmd = ASMS_REG_RDATA2;
	if (iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &rev2, sizeof rev2, 0)) {
		iic_release_bus(sc->sc_tag, 0);
		printf(": cannot read data register\n");
		return;
	}

	cmd = ASMS_REG_COMMAND; data = ASMS_CMD_READ_VER;
	if (iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &data, sizeof data, 0)) {
		iic_release_bus(sc->sc_tag, 0);
		printf(": cannot write command register\n");
		return;
	}
	delay(10000);

	cmd = ASMS_REG_RDATA1;
	if (iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &ver1, sizeof ver1, 0)) {
		iic_release_bus(sc->sc_tag, 0);
		printf(": cannot read data register\n");
		return;
	}

	cmd = ASMS_REG_RDATA2;
	if (iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &ver2, sizeof ver2, 0)) {
		iic_release_bus(sc->sc_tag, 0);
		printf(": cannot read data register\n");
		return;
	}

	cmd = ASMS_REG_VENDOR;
	if (iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &data, sizeof data, 0)) {
		iic_release_bus(sc->sc_tag, 0);
		printf(": cannot read vendor register\n");
		return;
	}
	if (data & 0x10)
		vflag = 1;

	cmd = ASMS_REG_SENS_LOW; data = 0x15;
	if (iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &data, sizeof data, 0)) {
		iic_release_bus(sc->sc_tag, 0);
		printf(": cannot write sensibility low register\n");
		return;
	}

	cmd = ASMS_REG_SENS_HIGH; data = 0x60;
	if (iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &data, sizeof data, 0)) {
		iic_release_bus(sc->sc_tag, 0);
		printf(": cannot write sensibility high register\n");
		return;
	}

	cmd = ASMS_REG_CONTROL_X; data = 0x08;
	if (iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &data, sizeof data, 0)) {
		iic_release_bus(sc->sc_tag, 0);
		printf(": cannot write control X register\n");
		return;
	}

	cmd = ASMS_REG_CONTROL_Y; data= 0x0f;
	if (iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &data, sizeof data, 0)) {
		iic_release_bus(sc->sc_tag, 0);
		printf(": cannot write control Y register\n");
		return;
	}

	cmd = ASMS_REG_CONTROL_Z; data = 0x4f;
	if (iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &data, sizeof data, 0)) {
		iic_release_bus(sc->sc_tag, 0);
		printf(": cannot write control Z register\n");
		return;
	}

	cmd = ASMS_REG_UNKNOWN1; data = 0x14;
	if (iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &data, sizeof data, 0)) {
		iic_release_bus(sc->sc_tag, 0);
		printf(": cannot write unknown 1 register\n");
		return;
	}

	iic_release_bus(sc->sc_tag, 0);

	printf(": rev %x.%x, version %x.%x", rev1, rev2, ver1, ver2);

	/* Initialize sensor data. */
	strlcpy(sc->sc_sensordev.xname, sc->sc_dev.dv_xname,
	    sizeof(sc->sc_sensordev.xname));

	sc->sc_sensor[ASMS_DATA_X].type = SENSOR_INTEGER;
	strlcpy(sc->sc_sensor[ASMS_DATA_X].desc, "X_ACCEL",
	    sizeof(sc->sc_sensor[ASMS_DATA_X].desc));

	sc->sc_sensor[ASMS_DATA_Y].type = SENSOR_INTEGER;
	strlcpy(sc->sc_sensor[ASMS_DATA_Y].desc, "Y_ACCEL",
	    sizeof(sc->sc_sensor[ASMS_DATA_Y].desc));

	sc->sc_sensor[ASMS_DATA_Z].type = SENSOR_INTEGER;
	strlcpy(sc->sc_sensor[ASMS_DATA_Z].desc, "Z_ACCEL",
	    sizeof(sc->sc_sensor[ASMS_DATA_Z].desc));

	if (sensor_task_register(sc, asms_refresh, 5) == NULL) {
		printf(": unable to register update task\n");
		return;
	}

	for (i = 0; i < ASMS_NUM_SENSORS; i++)
		sensor_attach(&sc->sc_sensordev, &sc->sc_sensor[i]);
	sensordev_install(&sc->sc_sensordev);

	printf("\n");
}

void
asms_refresh(void *arg)
{
	struct asms_softc *sc = arg;
	u_int8_t cmd;
	int8_t sdata;

	iic_acquire_bus(sc->sc_tag, 0);

	cmd = ASMS_REG_DATA_X;
	if (iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &sdata, sizeof sdata, 0) == 0)
		sc->sc_sensor[ASMS_DATA_X].value = sdata;

	cmd = ASMS_REG_DATA_Y;
	if (iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &sdata, sizeof sdata, 0) == 0)
		sc->sc_sensor[ASMS_DATA_Y].value = sdata;

	cmd = ASMS_REG_DATA_Z;
	if (iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP,
	    sc->sc_addr, &cmd, sizeof cmd, &sdata, sizeof sdata, 0) == 0)
		sc->sc_sensor[ASMS_DATA_Z].value = sdata;

	iic_release_bus(sc->sc_tag, 0);
}


code:
/*	$OpenBSD: awacs.c,v 1.31 2015/05/11 06:46:21 ratchov Exp $	*/
/*	$NetBSD: awacs.c,v 1.4 2001/02/26 21:07:51 wiz Exp $	*/

/*-
 * Copyright (c) 2000 Tsubai Masanari.  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.
 * 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.
 */

#include <sys/param.h>
#include <sys/audioio.h>
#include <sys/device.h>
#include <sys/malloc.h>
#include <sys/systm.h>

#include <dev/audio_if.h>

#include <machine/bus.h>
#include <machine/autoconf.h>
#include <macppc/dev/dbdma.h>

#ifdef AWACS_DEBUG
# define DPRINTF printf
#else
# define DPRINTF while (0) printf
#endif

#define	AWACS_DMALIST_MAX	32
#define	AWACS_DMASEG_MAX	NBPG

struct awacs_dma {
	bus_dmamap_t map;
	caddr_t addr;
	bus_dma_segment_t segs[AWACS_DMALIST_MAX];
	int nsegs;
	size_t size;
	struct awacs_dma *next;
};

struct awacs_softc {
	struct device sc_dev;

	void (*sc_ointr)(void *);	/* dma completion intr handler */
	void *sc_oarg;			/* arg for sc_ointr() */

	void (*sc_iintr)(void *);	/* dma completion intr handler */
	void *sc_iarg;			/* arg for sc_iintr() */

	u_int sc_record_source;		/* recording source mask */
	u_int sc_output_mask;		/* output source mask */

	char *sc_reg;
	u_int sc_codecctl0;
	u_int sc_codecctl1;
	u_int sc_codecctl2;
	u_int sc_codecctl4;
	u_int sc_soundctl;

	bus_dma_tag_t sc_dmat;
	struct dbdma_regmap *sc_odma;
	struct dbdma_regmap *sc_idma;
	struct dbdma_command *sc_odmacmd, *sc_odmap;
	struct dbdma_command *sc_idmacmd, *sc_idmap;
	dbdma_t sc_odbdma, sc_idbdma;

	struct awacs_dma *sc_dmas;
};

int awacs_match(struct device *, void *, void *);
void awacs_attach(struct device *, struct device *, void *);
int awacs_intr(void *);
int awacs_tx_intr(void *);
int awacs_rx_intr(void *);

int awacs_open(void *, int);
void awacs_close(void *);
int awacs_query_encoding(void *, struct audio_encoding *);
int awacs_set_params(void *, int, int, struct audio_params *,
			 struct audio_params *);
int awacs_round_blocksize(void *, int);
int awacs_trigger_output(void *, void *, void *, int, void (*)(void *),
			     void *, struct audio_params *);
int awacs_trigger_input(void *, void *, void *, int, void (*)(void *),
			    void *, struct audio_params *);
int awacs_halt_output(void *);
int awacs_halt_input(void *);
int awacs_getdev(void *, struct audio_device *);
int awacs_set_port(void *, mixer_ctrl_t *);
int awacs_get_port(void *, mixer_ctrl_t *);
int awacs_query_devinfo(void *, mixer_devinfo_t *);
size_t awacs_round_buffersize(void *, int, size_t);
paddr_t awacs_mappage(void *, void *, off_t, int);
int awacs_get_props(void *);
void *awacs_allocm(void *, int, size_t, int, int);

static inline u_int awacs_read_reg(struct awacs_softc *, int);
static inline void awacs_write_reg(struct awacs_softc *, int, int);
void awacs_write_codec(struct awacs_softc *, int);
void awacs_set_speaker_volume(struct awacs_softc *, int, int);
void awacs_set_ext_volume(struct awacs_softc *, int, int);
void awacs_set_rate(struct awacs_softc *, struct audio_params *);

struct cfattach awacs_ca = {
	sizeof(struct awacs_softc), awacs_match, awacs_attach
};

struct cfdriver awacs_cd = {
	NULL, "awacs", DV_DULL
};

struct audio_hw_if awacs_hw_if = {
	awacs_open,
	awacs_close,
	NULL,			/* drain */
	awacs_query_encoding,
	awacs_set_params,
	awacs_round_blocksize,
	NULL,			/* commit_setting */
	NULL,			/* init_output */
	NULL,			/* init_input */
	NULL,			/* start_output */
	NULL,			/* start_input */
	awacs_halt_output,
	awacs_halt_input,
	NULL,			/* speaker_ctl */
	awacs_getdev,
	NULL,			/* getfd */
	awacs_set_port,
	awacs_get_port,
	awacs_query_devinfo,
	awacs_allocm,		/* allocm */
	NULL,			/* freem */
	awacs_round_buffersize,	/* round_buffersize */
	awacs_mappage,
	awacs_get_props,
	awacs_trigger_output,
	awacs_trigger_input,
	NULL
};

struct audio_device awacs_device = {
	"AWACS",
	"",
	"awacs"
};

/* register offset */
#define AWACS_SOUND_CTRL	0x00
#define AWACS_CODEC_CTRL	0x10
#define AWACS_CODEC_STATUS	0x20
#define AWACS_CLIP_COUNT	0x30
#define AWACS_BYTE_SWAP		0x40

/* sound control */
#define AWACS_INPUT_SUBFRAME0	0x00000001
#define AWACS_INPUT_SUBFRAME1	0x00000002
#define AWACS_INPUT_SUBFRAME2	0x00000004
#define AWACS_INPUT_SUBFRAME3	0x00000008

#define AWACS_OUTPUT_SUBFRAME0	0x00000010
#define AWACS_OUTPUT_SUBFRAME1	0x00000020
#define AWACS_OUTPUT_SUBFRAME2	0x00000040
#define AWACS_OUTPUT_SUBFRAME3	0x00000080

#define AWACS_RATE_44100	0x00000000
#define AWACS_RATE_29400	0x00000100
#define AWACS_RATE_22050	0x00000200
#define AWACS_RATE_17640	0x00000300
#define AWACS_RATE_14700	0x00000400
#define AWACS_RATE_11025	0x00000500
#define AWACS_RATE_8820		0x00000600
#define AWACS_RATE_7350		0x00000700
#define AWACS_RATE_MASK		0x00000700

#define AWACS_CTL_CNTRLERR 	(1 << 11)
#define AWACS_CTL_PORTCHG 	(1 << 12)
#define AWACS_INT_CNTRLERR 	(1 << 13)
#define AWACS_INT_PORTCHG 	(1 << 14)

/* codec control */
#define AWACS_CODEC_ADDR0	0x00000000
#define AWACS_CODEC_ADDR1	0x00001000
#define AWACS_CODEC_ADDR2	0x00002000
#define AWACS_CODEC_ADDR4	0x00004000
#define AWACS_CODEC_EMSEL0	0x00000000
#define AWACS_CODEC_EMSEL1	0x00400000
#define AWACS_CODEC_EMSEL2	0x00800000
#define AWACS_CODEC_EMSEL4	0x00c00000
#define AWACS_CODEC_BUSY	0x01000000

/* cc0 */
#define AWACS_DEFAULT_CD_GAIN	0x000000bb
#define AWACS_INPUT_CD		0x00000200
#define AWACS_INPUT_LINE	0x00000400
#define AWACS_INPUT_MICROPHONE	0x00000800
#define AWACS_INPUT_MASK	0x00000e00

/* cc1 */
#define AWACS_MUTE_SPEAKER	0x00000080
#define AWACS_MUTE_HEADPHONE	0x00000200

const struct awacs_speed_tab {
	int rate;
	u_int32_t bits;
} awacs_speeds[] = {
	{  7350, AWACS_RATE_7350 },
	{  8820, AWACS_RATE_8820 },
	{ 11025, AWACS_RATE_11025 },
	{ 14700, AWACS_RATE_14700 },
	{ 17640, AWACS_RATE_17640 },
	{ 22050, AWACS_RATE_22050 },
	{ 29400, AWACS_RATE_29400 },
	{ 44100, AWACS_RATE_44100 },
};

int
awacs_match(struct device *parent, void *match, void *aux)
{
	struct confargs *ca = aux;

	if (strcmp(ca->ca_name, "awacs") != 0 &&
	    strcmp(ca->ca_name, "davbus") != 0)
		return 0;

#ifdef DEBUG
	printf("awacs: matched %s nreg %d nintr %d\n",
		ca->ca_name, ca->ca_nreg, ca->ca_nintr);
#endif

	if (ca->ca_nreg < 24 || ca->ca_nintr < 12)
		return 0;

	/* XXX for now
	if (ca->ca_nintr > 12)
		return 0;
	*/

	return 1;
}

void
awacs_attach(struct device *parent, struct device *self, void *aux)
{
	struct awacs_softc *sc = (struct awacs_softc *)self;
	struct confargs *ca = aux;
	int cirq, oirq, iirq;
	int cirq_type, oirq_type, iirq_type;

	ca->ca_reg[0] += ca->ca_baseaddr;
	ca->ca_reg[2] += ca->ca_baseaddr;
	ca->ca_reg[4] += ca->ca_baseaddr;

	sc->sc_reg = mapiodev(ca->ca_reg[0], ca->ca_reg[1]);

	sc->sc_dmat = ca->ca_dmat;
	sc->sc_odma = mapiodev(ca->ca_reg[2], ca->ca_reg[3]); /* out */
	sc->sc_idma = mapiodev(ca->ca_reg[4], ca->ca_reg[5]); /* in */
	sc->sc_odbdma = dbdma_alloc(sc->sc_dmat, AWACS_DMALIST_MAX);
	sc->sc_odmacmd = sc->sc_odbdma->d_addr;
	sc->sc_idbdma = dbdma_alloc(sc->sc_dmat, AWACS_DMALIST_MAX);
	sc->sc_idmacmd = sc->sc_idbdma->d_addr;

	if (ca->ca_nintr == 24) {
		cirq = ca->ca_intr[0];
		oirq = ca->ca_intr[2];
		iirq = ca->ca_intr[4];
		cirq_type = ca->ca_intr[1] ? IST_LEVEL : IST_EDGE;
		oirq_type = ca->ca_intr[3] ? IST_LEVEL : IST_EDGE;
		iirq_type = ca->ca_intr[5] ? IST_LEVEL : IST_EDGE;
	} else {
		cirq = ca->ca_intr[0];
		oirq = ca->ca_intr[1];
		iirq = ca->ca_intr[2];
		cirq_type = oirq_type = iirq_type = IST_LEVEL;
	}
	mac_intr_establish(parent, cirq, cirq_type, IPL_AUDIO | IPL_MPSAFE,
	    awacs_intr, sc, sc->sc_dev.dv_xname);
	mac_intr_establish(parent, oirq, oirq_type, IPL_AUDIO | IPL_MPSAFE,
	    awacs_tx_intr, sc, sc->sc_dev.dv_xname);
	mac_intr_establish(parent, iirq, iirq_type, IPL_AUDIO | IPL_MPSAFE,
	    awacs_rx_intr, sc, sc->sc_dev.dv_xname);

	printf(": irq %d,%d,%d",
		cirq, oirq, iirq);

	sc->sc_soundctl = AWACS_INPUT_SUBFRAME0 | AWACS_OUTPUT_SUBFRAME0 |
	    AWACS_RATE_44100 | AWACS_INT_PORTCHG;
	awacs_write_reg(sc, AWACS_SOUND_CTRL, sc->sc_soundctl);

	sc->sc_codecctl0 = AWACS_CODEC_ADDR0 | AWACS_CODEC_EMSEL0;
	sc->sc_codecctl1 = AWACS_CODEC_ADDR1 | AWACS_CODEC_EMSEL0;
	sc->sc_codecctl2 = AWACS_CODEC_ADDR2 | AWACS_CODEC_EMSEL0;
	sc->sc_codecctl4 = AWACS_CODEC_ADDR4 | AWACS_CODEC_EMSEL0;

	sc->sc_codecctl0 |= AWACS_INPUT_CD | AWACS_DEFAULT_CD_GAIN;
	awacs_write_codec(sc, sc->sc_codecctl0);

	/* Set initial volume[s] */
	awacs_set_speaker_volume(sc, 80, 80);
	awacs_set_ext_volume(sc, 80, 80);

	/* Set loopback (for CD?) */
	/* sc->sc_codecctl1 |= 0x440; */
	sc->sc_codecctl1 |= 0x40;
	awacs_write_codec(sc, sc->sc_codecctl1);

	/* check for headphone present */
	if (awacs_read_reg(sc, AWACS_CODEC_STATUS) & 0x8) {
		/* default output to speakers */
		printf(" headphones");
		sc->sc_output_mask = 1 << 1;
		sc->sc_codecctl1 &= ~AWACS_MUTE_HEADPHONE;
		sc->sc_codecctl1 |= AWACS_MUTE_SPEAKER;
		awacs_write_codec(sc, sc->sc_codecctl1);
	} else {
		/* default output to speakers */
		printf(" speaker");
		sc->sc_output_mask = 1 << 0;
		sc->sc_codecctl1 &= ~AWACS_MUTE_SPEAKER;
		sc->sc_codecctl1 |= AWACS_MUTE_HEADPHONE;
		awacs_write_codec(sc, sc->sc_codecctl1);
	}

	/* default input from CD */
	sc->sc_record_source = 1 << 0;
	sc->sc_codecctl0 &= ~AWACS_INPUT_MASK;
	sc->sc_codecctl0 |= AWACS_INPUT_CD;
	awacs_write_codec(sc, sc->sc_codecctl0);

	/* Enable interrupts and looping mode. */
	/* XXX ... */
	awacs_halt_output(sc);
	awacs_halt_input(sc);
	printf("\n");

	audio_attach_mi(&awacs_hw_if, sc, &sc->sc_dev);
}

u_int
awacs_read_reg(struct awacs_softc *sc, int reg)
{
	char *addr = sc->sc_reg;

	return in32rb(addr + reg);
}

void
awacs_write_reg(struct awacs_softc *sc, int reg, int val)
{
	char *addr = sc->sc_reg;

	out32rb(addr + reg, val);
}

void
awacs_write_codec(struct awacs_softc *sc, int value)
{
	awacs_write_reg(sc, AWACS_CODEC_CTRL, value);
	while (awacs_read_reg(sc, AWACS_CODEC_CTRL) & AWACS_CODEC_BUSY);
}

int
awacs_intr(void *v)
{
	int reason;
	struct awacs_softc *sc = v;

	mtx_enter(&audio_lock);
	reason = awacs_read_reg(sc, AWACS_SOUND_CTRL);
	if (reason & AWACS_CTL_CNTRLERR) {
		/* change outputs ?? */
	}
	if (reason & AWACS_CTL_PORTCHG) {
#ifdef DEBUG
		printf("status = %x\n", awacs_read_reg(sc, AWACS_CODEC_STATUS));
#endif

		if (awacs_read_reg(sc, AWACS_CODEC_STATUS) & 0x8) {
			/* default output to speakers */
			sc->sc_output_mask = 1 << 1;
			sc->sc_codecctl1 &= ~AWACS_MUTE_HEADPHONE;
			sc->sc_codecctl1 |= AWACS_MUTE_SPEAKER;
			awacs_write_codec(sc, sc->sc_codecctl1);
		} else {
			/* default output to speakers */
			sc->sc_output_mask = 1 << 0;
			sc->sc_codecctl1 &= ~AWACS_MUTE_SPEAKER;
			sc->sc_codecctl1 |= AWACS_MUTE_HEADPHONE;
			awacs_write_codec(sc, sc->sc_codecctl1);
		}
	}

	awacs_write_reg(sc, AWACS_SOUND_CTRL, reason); /* clear interrupt */
	mtx_leave(&audio_lock);
	return 1;
}

int
awacs_tx_intr(void *v)
{
	struct awacs_softc *sc = v;
	struct dbdma_command *cmd = sc->sc_odmap;
	u_int16_t c, status;

	/* if not set we are not running */
	if (!cmd)
		return (0);
	mtx_enter(&audio_lock);
	c = in16rb(&cmd->d_command);
	status = in16rb(&cmd->d_status);

	if (c >> 12 == DBDMA_CMD_OUT_LAST)
		sc->sc_odmap = sc->sc_odmacmd;
	else
		sc->sc_odmap++;

	if (c & (DBDMA_INT_ALWAYS << 4)) {
		cmd->d_status = 0;
		if (status)	/* status == 0x8400 */
			if (sc->sc_ointr)
				(*sc->sc_ointr)(sc->sc_oarg);
	}
	mtx_leave(&audio_lock);
	return (1);
}
int
awacs_rx_intr(void *v)
{
	struct awacs_softc *sc = v;
	struct dbdma_command *cmd = sc->sc_idmap;
	u_int16_t c, status;

	/* if not set we are not running */
	if (!cmd)
		return (0);

	mtx_enter(&audio_lock);
	c = in16rb(&cmd->d_command);
	status = in16rb(&cmd->d_status);

	if (c >> 12 == DBDMA_CMD_IN_LAST)
		sc->sc_idmap = sc->sc_idmacmd;
	else
		sc->sc_idmap++;

	if (c & (DBDMA_INT_ALWAYS << 4)) {
		cmd->d_status = 0;
		if (status)	/* status == 0x8400 */
			if (sc->sc_iintr)
				(*sc->sc_iintr)(sc->sc_iarg);
	}
	mtx_leave(&audio_lock);
	return (1);
}

int
awacs_open(void *h, int flags)
{
	return 0;
}

/*
 * Close function is called at splaudio().
 */
void
awacs_close(void *h)
{
	struct awacs_softc *sc = h;

	/* XXX: halt_xxx() already called by upper layer */
	awacs_halt_output(sc);
	awacs_halt_input(sc);

	sc->sc_ointr = 0;
	sc->sc_iintr = 0;
}

int
awacs_query_encoding(void *h, struct audio_encoding *ae)
{
	switch (ae->index) {
	case 0:
		strlcpy(ae->name, AudioEslinear_be, sizeof ae->name);
		ae->encoding = AUDIO_ENCODING_SLINEAR_BE;
		ae->precision = 16;
		ae->flags = 0;
		break;
	default:
		return (EINVAL);
	}
	ae->bps = AUDIO_BPS(ae->precision);
	ae->msb = 1;

	return (0);
}

int
awacs_set_params(void *h, int setmode, int usemode, struct audio_params *play,
    struct audio_params *rec)
{
	struct awacs_softc *sc = h;
	struct audio_params *p;
	int mode;

	/*
	 * This device only has one clock, so make the sample rates match.
	 */
	if (play->sample_rate != rec->sample_rate &&
	    usemode == (AUMODE_PLAY | AUMODE_RECORD)) {
		if (setmode == AUMODE_PLAY) {
			rec->sample_rate = play->sample_rate;
			setmode |= AUMODE_RECORD;
		} else if (setmode == AUMODE_RECORD) {
			play->sample_rate = rec->sample_rate;
			setmode |= AUMODE_PLAY;
		} else
			return EINVAL;
	}

	for (mode = AUMODE_RECORD; mode != -1;
	     mode = mode == AUMODE_RECORD ? AUMODE_PLAY : -1) {
		if ((setmode & mode) == 0)
			continue;

		p = mode == AUMODE_PLAY ? play : rec;

		if (p->sample_rate < 4000)
			p->sample_rate = 4000;
		if (p->sample_rate > 50000)
			p->sample_rate = 50000;

		awacs_write_reg(sc, AWACS_BYTE_SWAP, 0);

		p->encoding = AUDIO_ENCODING_SLINEAR_BE;
		p->precision = 16;
		p->channels = 2;
		p->bps = AUDIO_BPS(p->precision);
		p->msb = 1;
	}

	/* Set the speed */
	awacs_set_rate(sc, p);

	return (0);
}

int
awacs_round_blocksize(void *h, int size)
{
	if (size < PAGE_SIZE)
		size = PAGE_SIZE;
	return (size + PAGE_SIZE / 2) & ~(PGOFSET);
}

int
awacs_halt_output(void *h)
{
	struct awacs_softc *sc = h;

	mtx_enter(&audio_lock);
	dbdma_stop(sc->sc_odma);
	dbdma_reset(sc->sc_odma);
	dbdma_stop(sc->sc_odma);
	sc->sc_odmap = NULL;
	mtx_leave(&audio_lock);
	return 0;
}

int
awacs_halt_input(void *h)
{
	struct awacs_softc *sc = h;

	mtx_enter(&audio_lock);
	dbdma_stop(sc->sc_idma);
	dbdma_reset(sc->sc_idma);
	mtx_leave(&audio_lock);
	return 0;
}

int
awacs_getdev(void *h, struct audio_device *retp)
{
	*retp = awacs_device;
	return 0;
}

enum {
	AWACS_OUTPUT_SELECT,
	AWACS_VOL_SPEAKER,
	AWACS_VOL_HEADPHONE,
	AWACS_OUTPUT_CLASS,
	AWACS_MONITOR_CLASS,
	AWACS_INPUT_SELECT,
	AWACS_VOL_INPUT,
	AWACS_INPUT_CLASS,
	AWACS_RECORD_CLASS,
	AWACS_ENUM_LAST
};

int
awacs_set_port(void *h, mixer_ctrl_t *mc)
{
	struct awacs_softc *sc = h;
	int l, r;

	DPRINTF("awacs_set_port dev = %d, type = %d\n", mc->dev, mc->type);

	l = mc->un.value.level[AUDIO_MIXER_LEVEL_LEFT];
	r = mc->un.value.level[AUDIO_MIXER_LEVEL_RIGHT];

	switch (mc->dev) {
	case AWACS_OUTPUT_SELECT:
		/* no change necessary? */
		if (mc->un.mask == sc->sc_output_mask)
			return 0;
		sc->sc_codecctl1 |= AWACS_MUTE_SPEAKER | AWACS_MUTE_HEADPHONE;
		if (mc->un.mask & 1 << 0)
			sc->sc_codecctl1 &= ~AWACS_MUTE_SPEAKER;
		if (mc->un.mask & 1 << 1)
			sc->sc_codecctl1 &= ~AWACS_MUTE_HEADPHONE;

		awacs_write_codec(sc, sc->sc_codecctl1);
		sc->sc_output_mask = mc->un.mask;
		return 0;

	case AWACS_VOL_SPEAKER:
		awacs_set_speaker_volume(sc, l, r);
		return 0;

	case AWACS_VOL_HEADPHONE:
		awacs_set_ext_volume(sc, l, r);
		return 0;

	case AWACS_VOL_INPUT:
		sc->sc_codecctl0 &= ~0xff;
		sc->sc_codecctl0 |= (l & 0xf0) | (r >> 4);
		awacs_write_codec(sc, sc->sc_codecctl0);
		return 0;

	case AWACS_INPUT_SELECT:
		/* no change necessary? */
		if (mc->un.mask == sc->sc_record_source)
			return 0;
		switch(mc->un.mask) {
		case 1<<0: /* CD */
			sc->sc_codecctl0 &= ~AWACS_INPUT_MASK;
			sc->sc_codecctl0 |= AWACS_INPUT_CD;
			awacs_write_codec(sc, sc->sc_codecctl0);
			break;
		case 1<<1: /* microphone */
			sc->sc_codecctl0 &= ~AWACS_INPUT_MASK;
			sc->sc_codecctl0 |= AWACS_INPUT_MICROPHONE;
			awacs_write_codec(sc, sc->sc_codecctl0);
			break;
		case 1<<2: /* line in */
			sc->sc_codecctl0 &= ~AWACS_INPUT_MASK;
			sc->sc_codecctl0 |= AWACS_INPUT_LINE;
			awacs_write_codec(sc, sc->sc_codecctl0);
			break;
		default: /* invalid argument */
			return -1;
		}
		sc->sc_record_source = mc->un.mask;
		return 0;
	}

	return ENXIO;
}

int
awacs_get_port(void *h, mixer_ctrl_t *mc)
{
	struct awacs_softc *sc = h;
	int vol, l, r;

	DPRINTF("awacs_get_port dev = %d, type = %d\n", mc->dev, mc->type);

	switch (mc->dev) {
	case AWACS_OUTPUT_SELECT:
		mc->un.mask = sc->sc_output_mask;
		return 0;

	case AWACS_VOL_SPEAKER:
		vol = sc->sc_codecctl4;
		l = (15 - ((vol & 0x3c0) >> 6)) * 16;
		r = (15 - (vol & 0x0f)) * 16;
		mc->un.mask = 1 << 0;
		mc->un.value.num_channels = 2;
		mc->un.value.level[AUDIO_MIXER_LEVEL_LEFT] = l;
		mc->un.value.level[AUDIO_MIXER_LEVEL_RIGHT] = r;
		return 0;

	case AWACS_VOL_HEADPHONE:
		vol = sc->sc_codecctl2;
		l = (15 - ((vol & 0x3c0) >> 6)) * 16;
		r = (15 - (vol & 0x0f)) * 16;
		mc->un.mask = 1 << 1;
		mc->un.value.num_channels = 2;
		mc->un.value.level[AUDIO_MIXER_LEVEL_LEFT] = l;
		mc->un.value.level[AUDIO_MIXER_LEVEL_RIGHT] = r;
		return 0;

	case AWACS_INPUT_SELECT:
		mc->un.mask = sc->sc_record_source;
		return 0;

	case AWACS_VOL_INPUT:
		vol = sc->sc_codecctl0 & 0xff;
		l = (vol & 0xf0);
		r = (vol & 0x0f) << 4;
		mc->un.mask = sc->sc_record_source;
		mc->un.value.num_channels = 2;
		mc->un.value.level[AUDIO_MIXER_LEVEL_LEFT] = l;
		mc->un.value.level[AUDIO_MIXER_LEVEL_RIGHT] = r;
		return 0;

	default:
		return ENXIO;
	}

	return 0;
}

int
awacs_query_devinfo(void *h, mixer_devinfo_t *dip)
{
	DPRINTF("query_devinfo %d\n", dip->index);

	switch (dip->index) {

	case AWACS_OUTPUT_SELECT:
		dip->mixer_class = AWACS_OUTPUT_CLASS;
		strlcpy(dip->label.name, AudioNselect, sizeof dip->label.name);
		dip->type = AUDIO_MIXER_SET;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		dip->un.s.num_mem = 2;
		strlcpy(dip->un.s.member[0].label.name, AudioNspeaker,
		    sizeof dip->un.s.member[0].label.name);
		dip->un.s.member[0].mask = 1 << 0;
		strlcpy(dip->un.s.member[1].label.name, AudioNheadphone,
		    sizeof dip->un.s.member[0].label.name);
		dip->un.s.member[1].mask = 1 << 1;
		return 0;

	case AWACS_VOL_SPEAKER:
		dip->mixer_class = AWACS_OUTPUT_CLASS;
		strlcpy(dip->label.name, AudioNspeaker,
		    sizeof dip->label.name);
		dip->type = AUDIO_MIXER_VALUE;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		dip->un.v.num_channels = 2;
		strlcpy(dip->un.v.units.name, AudioNvolume,
		    sizeof dip->un.v.units.name);
		return 0;

	case AWACS_VOL_HEADPHONE:
		dip->mixer_class = AWACS_OUTPUT_CLASS;
		strlcpy(dip->label.name, AudioNheadphone,
		    sizeof dip->label.name);
		dip->type = AUDIO_MIXER_VALUE;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		dip->un.v.num_channels = 2;
		strlcpy(dip->un.v.units.name, AudioNvolume,
		    sizeof dip->un.v.units.name);
		return 0;

	case AWACS_INPUT_SELECT:
		dip->mixer_class = AWACS_RECORD_CLASS;
		strlcpy(dip->label.name, AudioNsource, sizeof dip->label.name);
		dip->type = AUDIO_MIXER_SET;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		dip->un.s.num_mem = 3;
		strlcpy(dip->un.s.member[0].label.name, AudioNcd,
		    sizeof dip->un.s.member[0].label.name);
		dip->un.s.member[0].mask = 1 << 0;
		strlcpy(dip->un.s.member[1].label.name, AudioNmicrophone,
		    sizeof dip->un.s.member[1].label.name);
		dip->un.s.member[1].mask = 1 << 1;
		strlcpy(dip->un.s.member[2].label.name, AudioNline,
		    sizeof dip->un.s.member[2].label.name);
		dip->un.s.member[2].mask = 1 << 2;
		return 0;

	case AWACS_VOL_INPUT:
		dip->mixer_class = AWACS_RECORD_CLASS;
		strlcpy(dip->label.name, AudioNmaster, sizeof dip->label.name);
		dip->type = AUDIO_MIXER_VALUE;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		dip->un.v.num_channels = 2;
		strlcpy(dip->un.v.units.name, AudioNvolume,
		    sizeof dip->un.v.units.name);
		return 0;

	case AWACS_MONITOR_CLASS:
		dip->mixer_class = AWACS_MONITOR_CLASS;
		strlcpy(dip->label.name, AudioCmonitor, sizeof dip->label.name);
		dip->type = AUDIO_MIXER_CLASS;
		dip->next = dip->prev = AUDIO_MIXER_LAST;
		return 0;

	case AWACS_OUTPUT_CLASS:
		dip->mixer_class = AWACS_OUTPUT_CLASS;
		strlcpy(dip->label.name, AudioCoutputs, sizeof dip->label.name);
		dip->type = AUDIO_MIXER_CLASS;
		dip->next = dip->prev = AUDIO_MIXER_LAST;
		return 0;

	case AWACS_RECORD_CLASS:
		dip->mixer_class = AWACS_MONITOR_CLASS;
		strlcpy(dip->label.name, AudioCrecord, sizeof dip->label.name);
		dip->type = AUDIO_MIXER_CLASS;
		dip->next = dip->prev = AUDIO_MIXER_LAST;
		return 0;
	}

	return ENXIO;
}

size_t
awacs_round_buffersize(void *h, int dir, size_t size)
{
	size = (size + PGOFSET) & ~(PGOFSET);
	if (size > AWACS_DMALIST_MAX * AWACS_DMASEG_MAX)
		size = AWACS_DMALIST_MAX * AWACS_DMASEG_MAX;
	return (size);
}

void *
awacs_allocm(void *h, int dir, size_t size, int type, int flags)
{
	struct awacs_softc *sc = h;
	struct awacs_dma *p;
	int error;

	if (size > AWACS_DMALIST_MAX * AWACS_DMASEG_MAX)
		return (NULL);

	p = malloc(sizeof(*p), type, flags | M_ZERO);
	if (!p)
		return (NULL);

	/* convert to the bus.h style, not used otherwise */
	if (flags & M_NOWAIT)
		flags = BUS_DMA_NOWAIT;

	p->size = size;
	if ((error = bus_dmamem_alloc(sc->sc_dmat, p->size, NBPG, 0, p->segs,
	    1, &p->nsegs, flags)) != 0) {
		printf("%s: unable to allocate dma, error = %d\n",
		    sc->sc_dev.dv_xname, error);
		free(p, type, 0);
		return NULL;
	}

	if ((error = bus_dmamem_map(sc->sc_dmat, p->segs, p->nsegs, p->size,
	    &p->addr, flags | BUS_DMA_COHERENT)) != 0) {
		printf("%s: unable to map dma, error = %d\n",
		    sc->sc_dev.dv_xname, error);
		bus_dmamem_free(sc->sc_dmat, p->segs, p->nsegs);
		free(p, type, 0);
		return NULL;
	}

	if ((error = bus_dmamap_create(sc->sc_dmat, p->size, 1,
	    p->size, 0, flags, &p->map)) != 0) {
		printf("%s: unable to create dma map, error = %d\n",
		    sc->sc_dev.dv_xname, error);
		bus_dmamem_unmap(sc->sc_dmat, p->addr, size);
		bus_dmamem_free(sc->sc_dmat, p->segs, p->nsegs);
		free(p, type, 0);
		return NULL;
	}

	if ((error = bus_dmamap_load(sc->sc_dmat, p->map, p->addr, p->size,
	    NULL, flags)) != 0) {
		printf("%s: unable to load dma map, error = %d\n",
		    sc->sc_dev.dv_xname, error);
		bus_dmamap_destroy(sc->sc_dmat, p->map);
		bus_dmamem_unmap(sc->sc_dmat, p->addr, size);
		bus_dmamem_free(sc->sc_dmat, p->segs, p->nsegs);
		free(p, type, 0);
		return NULL;
	}

	p->next = sc->sc_dmas;
	sc->sc_dmas = p;

	return p->addr;
}

paddr_t
awacs_mappage(void *h, void *mem, off_t off, int prot)
{
	if (off < 0)
		return -1;
	return -1;	/* XXX */
}

int
awacs_get_props(void *h)
{
	return AUDIO_PROP_FULLDUPLEX /* | AUDIO_PROP_MMAP */;
}

int
awacs_trigger_output(void *h, void *start, void *end, int bsize,
    void (*intr)(void *), void *arg, struct audio_params *param)
{
	struct awacs_softc *sc = h;
	struct awacs_dma *p;
	struct dbdma_command *cmd = sc->sc_odmacmd;
	vaddr_t spa, pa, epa;
	int c;

	DPRINTF("trigger_output %p %p 0x%x\n", start, end, bsize);

	for (p = sc->sc_dmas; p && p->addr != start; p = p->next);
	if (!p)
		return -1;

	sc->sc_ointr = intr;
	sc->sc_oarg = arg;
	sc->sc_odmap = sc->sc_odmacmd;

	mtx_enter(&audio_lock);
	spa = p->segs[0].ds_addr;
	c = DBDMA_CMD_OUT_MORE;
	for (pa = spa, epa = spa + (end - start);
	    pa < epa; pa += bsize, cmd++) {

		if (pa + bsize == epa)
			c = DBDMA_CMD_OUT_LAST;

		DBDMA_BUILD(cmd, c, 0, bsize, pa, DBDMA_INT_ALWAYS,
			DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);
	}

	DBDMA_BUILD(cmd, DBDMA_CMD_NOP, 0, 0, 0,
		DBDMA_INT_NEVER, DBDMA_WAIT_NEVER, DBDMA_BRANCH_ALWAYS);
	dbdma_st32(&cmd->d_cmddep, sc->sc_odbdma->d_paddr);

	dbdma_start(sc->sc_odma, sc->sc_odbdma);

	mtx_leave(&audio_lock);
	return 0;
}

int
awacs_trigger_input(void *h, void *start, void *end, int bsize,
    void (*intr)(void *), void *arg, struct audio_params *param)
{
	struct awacs_softc *sc = h;
	struct awacs_dma *p;
	struct dbdma_command *cmd = sc->sc_idmacmd;
	vaddr_t spa, pa, epa;
	int c;

	DPRINTF("trigger_input %p %p 0x%x\n", start, end, bsize);

	for (p = sc->sc_dmas; p && p->addr != start; p = p->next);
	if (!p)
		return -1;

	sc->sc_iintr = intr;
	sc->sc_iarg = arg;
	sc->sc_idmap = sc->sc_idmacmd;

	mtx_enter(&audio_lock);
	spa = p->segs[0].ds_addr;
	c = DBDMA_CMD_IN_MORE;
	for (pa = spa, epa = spa + (end - start);
	    pa < epa; pa += bsize, cmd++) {

		if (pa + bsize == epa)
			c = DBDMA_CMD_IN_LAST;

		DBDMA_BUILD(cmd, c, 0, bsize, pa, DBDMA_INT_ALWAYS,
			DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);
	}

	DBDMA_BUILD(cmd, DBDMA_CMD_NOP, 0, 0, 0,
		DBDMA_INT_NEVER, DBDMA_WAIT_NEVER, DBDMA_BRANCH_ALWAYS);
	dbdma_st32(&cmd->d_cmddep, sc->sc_idbdma->d_paddr);

	dbdma_start(sc->sc_idma, sc->sc_idbdma);

	mtx_leave(&audio_lock);
	return 0;
}

void
awacs_set_speaker_volume(struct awacs_softc *sc, int left, int  right)
{
	int lval = 15 - (left  & 0xff) / 16;
	int rval = 15 - (right & 0xff) / 16;

	DPRINTF("speaker_volume %d %d\n", lval, rval);

	sc->sc_codecctl4 &= ~0x3cf;
	sc->sc_codecctl4 |= (lval << 6) | rval;
	awacs_write_codec(sc, sc->sc_codecctl4);
}

void
awacs_set_ext_volume(struct awacs_softc *sc, int left, int  right)
{
	int lval = 15 - (left  & 0xff) / 16;
	int rval = 15 - (right & 0xff) / 16;

	DPRINTF("ext_volume %d %d\n", lval, rval);

	sc->sc_codecctl2 &= ~0x3cf;
	sc->sc_codecctl2 |= (lval << 6) | rval;
	awacs_write_codec(sc, sc->sc_codecctl2);
}

void
awacs_set_rate(struct awacs_softc *sc, struct audio_params *p)
{
	int selected = -1;
	size_t n, i;

	n = sizeof(awacs_speeds)/sizeof(awacs_speeds[0]);

	if (p->sample_rate < awacs_speeds[0].rate)
		selected = 0;
	if (p->sample_rate > awacs_speeds[n - 1].rate)
		selected = n - 1;

	for (i = 1; selected == -1 && i < n; i++) {
		if (p->sample_rate == awacs_speeds[i].rate)
			selected = i;
		else if (p->sample_rate < awacs_speeds[i].rate) {
			u_int diff1, diff2;

			diff1 = p->sample_rate - awacs_speeds[i - 1].rate;
			diff2 = awacs_speeds[i].rate - p->sample_rate;
			selected = (diff1 < diff2) ? i - 1 : i;
		}
	}

	if (selected == -1)
		selected = 0;

	sc->sc_soundctl &= ~AWACS_RATE_MASK;
	sc->sc_soundctl |= awacs_speeds[selected].bits;
	p->sample_rate = awacs_speeds[selected].rate;
	awacs_write_reg(sc, AWACS_SOUND_CTRL, sc->sc_soundctl);
}

license: unknown


code:
/*	$OpenBSD: daca.c,v 1.8 2010/02/26 21:53:43 jasper Exp $	*/

/*-
 * Copyright (c) 2002,2003 Tsubai Masanari.  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.
 * 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.
 */

/*
 * Datasheet is available from
 * http://www.indata.si/grega/pdfs/dac3550a.pdf
 */

#include <sys/param.h>
#include <sys/audioio.h>
#include <sys/device.h>
#include <sys/systm.h>

#include <dev/audio_if.h>
#include <dev/ofw/openfirm.h>
#include <macppc/dev/dbdma.h>

#include <machine/autoconf.h>

#include <macppc/dev/i2svar.h>

#ifdef DACA_DEBUG
# define DPRINTF printf
#else
# define DPRINTF while (0) printf
#endif

/* XXX */
#define daca_softc i2s_softc

/* XXX */
int kiic_write(struct device *, int, int, const void *, int);
int kiic_writereg(struct device *, int, u_int);

int daca_getdev(void *, struct audio_device *);
int daca_match(struct device *, void *, void *);
void daca_attach(struct device *, struct device *, void *);
void daca_defer(struct device *);
void daca_init(struct daca_softc *);
void daca_set_volume(struct daca_softc *, int, int);
void daca_get_default_params(void *, int, struct audio_params *);

struct cfattach daca_ca = {
	sizeof(struct daca_softc), daca_match, daca_attach
};

struct cfdriver daca_cd = {
	NULL, "daca", DV_DULL
};

struct audio_hw_if daca_hw_if = {
	i2s_open,
	i2s_close,
	NULL,
	i2s_query_encoding,
	i2s_set_params,
	i2s_round_blocksize,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	i2s_halt_output,
	i2s_halt_input,
	NULL,
	daca_getdev,
	NULL,
	i2s_set_port,
	i2s_get_port,
	i2s_query_devinfo,
	i2s_allocm,		/* allocm */
	NULL,
	i2s_round_buffersize,
	i2s_mappage,
	i2s_get_props,
	i2s_trigger_output,
	i2s_trigger_input,
	daca_get_default_params
};

struct audio_device daca_device = {
	"DACA",
	"",
	"daca"
};

/* DAC3550A registers */
#define DEQ_SR		0x01	/* Sample rate control (8) */
#define DEQ_AVOL	0x02	/* Analog volume (16) */
#define DEQ_GCFG	0x03	/* Global configuration (8) */

int
daca_match(struct device *parent, void *match, void *aux)
{
	struct confargs *ca = aux;
	int soundbus, soundchip;
	char compat[32];

	if (strcmp(ca->ca_name, "i2s") != 0)
		return (0);

	if ((soundbus = OF_child(ca->ca_node)) == 0 ||
	    (soundchip = OF_child(soundbus)) == 0)
		return (0);

	bzero(compat, sizeof compat);
	OF_getprop(soundchip, "compatible", compat, sizeof compat);

	if (strcmp(compat, "daca") != 0)
		return (0);

	return (1);
}

#define DEQaddr 0x9a

void
daca_attach(struct device *parent,struct device *self, void *aux)
{
	struct daca_softc *sc = (struct daca_softc *)self;

	sc->sc_setvolume = daca_set_volume;

	i2s_attach(parent, sc, aux);
	config_defer(self, daca_defer);
}

void
daca_defer(struct device *dev)
{
	struct daca_softc *sc = (struct daca_softc *)dev;
	struct device *dv;

	TAILQ_FOREACH(dv, &alldevs, dv_list)
		if (strcmp(dv->dv_cfdata->cf_driver->cd_name, "kiic") == 0 &&
		    strcmp(dv->dv_parent->dv_cfdata->cf_driver->cd_name, "macobio") == 0)
			sc->sc_i2c = dv;
	if (sc->sc_i2c == NULL) {
		printf("%s: unable to find i2c\n", sc->sc_dev.dv_xname);
		return;
	}

	/* XXX If i2c has failed to attach, what should we do? */

	audio_attach_mi(&daca_hw_if, sc, &sc->sc_dev);

	daca_init(sc);
}

void
daca_init(struct daca_softc *sc)
{
	i2s_set_rate(sc, 44100);
	kiic_writereg(sc->sc_i2c, 4, 0x01 | 0x02 | 0x04);
}

int
daca_getdev(void *h, struct audio_device *retp)
{
	*retp = daca_device;
	return (0);
}

void
daca_set_volume(struct daca_softc *sc, int left, int right)
{
	u_int16_t data;

	sc->sc_vol_l = left;
	sc->sc_vol_r = right;

	left >>= 2;
	right >>= 2;
	data = left << 8 | right;
	kiic_write(sc->sc_i2c, DEQaddr, DEQ_AVOL, &data, 2);
}

void
daca_get_default_params(void *addr, int mode, struct audio_params *params)
{
	i2s_get_default_params(params);
}


code:
/*	$OpenBSD: dbdma.c,v 1.10 2014/07/12 18:44:42 tedu Exp $	*/
/*	$NetBSD: dbdma.c,v 1.2 1998/08/21 16:13:28 tsubai Exp $	*/

/*
 * Copyright 1991-1998 by Open Software Foundation, Inc.
 *              All Rights Reserved
 *
 * Permission to use, copy, modify, and distribute this software and
 * its documentation for any purpose and without fee is hereby granted,
 * provided that the above copyright notice appears in all copies and
 * that both the copyright notice and this permission notice appear in
 * supporting documentation.
 *
 * OSF DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE.
 *
 * IN NO EVENT SHALL OSF BE LIABLE FOR ANY SPECIAL, INDIRECT, OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN ACTION OF CONTRACT,
 * NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include <sys/param.h>
#include <sys/malloc.h>
#include <sys/systm.h>

#include <uvm/uvm_extern.h>

#include <machine/bus.h>
#include <macppc/dev/dbdma.h>

dbdma_command_t	*dbdma_alloc_commands = NULL;

void
dbdma_start(dbdma_regmap_t *dmap, dbdma_t dt)
{
	u_int32_t addr = dt->d_paddr;

	DBDMA_ST4_ENDIAN(&dmap->d_intselect, DBDMA_CLEAR_CNTRL((0xffff)));
	DBDMA_ST4_ENDIAN(&dmap->d_control, DBDMA_CLEAR_CNTRL((
	    DBDMA_CNTRL_ACTIVE |
	    DBDMA_CNTRL_DEAD |
	    DBDMA_CNTRL_WAKE |
	    DBDMA_CNTRL_FLUSH |
	    DBDMA_CNTRL_PAUSE |
	    DBDMA_CNTRL_RUN)));

	/* XXX time-bind it? */
	do {
		delay(10);
	} while (DBDMA_LD4_ENDIAN(&dmap->d_status) & DBDMA_CNTRL_ACTIVE);

	DBDMA_ST4_ENDIAN(&dmap->d_cmdptrhi, 0); /* 64-bit not yet */
	DBDMA_ST4_ENDIAN(&dmap->d_cmdptrlo, addr);

	DBDMA_ST4_ENDIAN(&dmap->d_control,
		DBDMA_SET_CNTRL(DBDMA_CNTRL_RUN|DBDMA_CNTRL_WAKE)|
		DBDMA_CLEAR_CNTRL(DBDMA_CNTRL_PAUSE|DBDMA_CNTRL_DEAD) );
}

void
dbdma_stop(dbdma_regmap_t *dmap)
{
	DBDMA_ST4_ENDIAN(&dmap->d_control, DBDMA_CLEAR_CNTRL(DBDMA_CNTRL_RUN) |
			  DBDMA_SET_CNTRL(DBDMA_CNTRL_FLUSH));

	while (DBDMA_LD4_ENDIAN(&dmap->d_status) &
		(DBDMA_CNTRL_ACTIVE|DBDMA_CNTRL_FLUSH));
}

void
dbdma_flush(dbdma_regmap_t *dmap)
{
	DBDMA_ST4_ENDIAN(&dmap->d_control, DBDMA_SET_CNTRL(DBDMA_CNTRL_FLUSH));

	/* XXX time-bind it? */
	while (DBDMA_LD4_ENDIAN(&dmap->d_status) & (DBDMA_CNTRL_FLUSH));
}

void
dbdma_reset(dbdma_regmap_t *dmap)
{
	DBDMA_ST4_ENDIAN(&dmap->d_control,
			 DBDMA_CLEAR_CNTRL( (DBDMA_CNTRL_ACTIVE	|
					     DBDMA_CNTRL_DEAD	|
					     DBDMA_CNTRL_WAKE	|
					     DBDMA_CNTRL_FLUSH	|
					     DBDMA_CNTRL_PAUSE	|
					     DBDMA_CNTRL_RUN      )));

	/* XXX time-bind it? */
	while (DBDMA_LD4_ENDIAN(&dmap->d_status) & DBDMA_CNTRL_RUN);
}

void
dbdma_continue(dbdma_regmap_t *dmap)
{
	DBDMA_ST4_ENDIAN(&dmap->d_control,
		DBDMA_SET_CNTRL(DBDMA_CNTRL_RUN | DBDMA_CNTRL_WAKE) |
		DBDMA_CLEAR_CNTRL(DBDMA_CNTRL_PAUSE | DBDMA_CNTRL_DEAD));
}

void
dbdma_pause(dbdma_regmap_t *dmap)
{
	DBDMA_ST4_ENDIAN(&dmap->d_control,DBDMA_SET_CNTRL(DBDMA_CNTRL_PAUSE));

	/* XXX time-bind it? */
	while (DBDMA_LD4_ENDIAN(&dmap->d_status) & DBDMA_CNTRL_ACTIVE);
}

dbdma_t
dbdma_alloc(bus_dma_tag_t dmat, int size)
{
	dbdma_t dt;
	int error;

	dt = malloc(sizeof *dt, M_DEVBUF, M_NOWAIT | M_ZERO);
	if (!dt)
		return (dt);

	dt->d_size = size *= sizeof(dbdma_command_t);
	dt->d_dmat = dmat;
	if ((error = bus_dmamem_alloc(dmat, size, NBPG, 0, dt->d_segs,
	    1, &dt->d_nsegs, BUS_DMA_NOWAIT)) != 0) {
		printf("dbdma: unable to allocate dma, error = %d\n", error);
	} else if ((error = bus_dmamem_map(dmat, dt->d_segs, dt->d_nsegs, size,
	    (caddr_t *)&dt->d_addr, BUS_DMA_NOWAIT | BUS_DMA_COHERENT)) != 0) {
		printf("dbdma: unable to map dma, error = %d\n", error);
	} else if ((error = bus_dmamap_create(dmat, dt->d_size, 1,
	    dt->d_size, 0, BUS_DMA_NOWAIT, &dt->d_map)) != 0) {
		printf("dbdma: unable to create dma map, error = %d\n", error);
	} else if ((error = bus_dmamap_load_raw(dmat, dt->d_map,
	    dt->d_segs, dt->d_nsegs, size, BUS_DMA_NOWAIT)) != 0) {
		printf("dbdma: unable to load dma map, error = %d\n", error);
	} else
		return dt;

	dbdma_free(dt);
	return (NULL);
}

void
dbdma_free(dbdma_t dt)
{
	if (dt->d_map)
		bus_dmamap_destroy(dt->d_dmat, dt->d_map);
	if (dt->d_addr)
		bus_dmamem_unmap(dt->d_dmat, (caddr_t)dt->d_addr, dt->d_size);
	if (dt->d_nsegs)
		bus_dmamem_free(dt->d_dmat, dt->d_segs, dt->d_nsegs);
	free(dt, M_DEVBUF, 0);
}


code:
/*	$OpenBSD: dbdma.h,v 1.4 2006/01/13 19:25:44 miod Exp $	*/
/*	$NetBSD: dbdma.h,v 1.2 1998/08/21 16:13:28 tsubai Exp $	*/

/*
 * Copyright 1991-1998 by Open Software Foundation, Inc.
 *              All Rights Reserved
 *
 * Permission to use, copy, modify, and distribute this software and
 * its documentation for any purpose and without fee is hereby granted,
 * provided that the above copyright notice appears in all copies and
 * that both the copyright notice and this permission notice appear in
 * supporting documentation.
 *
 * OSF DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE.
 *
 * IN NO EVENT SHALL OSF BE LIABLE FOR ANY SPECIAL, INDIRECT, OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN ACTION OF CONTRACT,
 * NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include <machine/bus.h>
#include <machine/pio.h>

#ifndef _POWERMAC_DBDMA_H_
#define _POWERMAC_DBDMA_H_

#define	DBDMA_CMD_OUT_MORE	0
#define	DBDMA_CMD_OUT_LAST	1
#define	DBDMA_CMD_IN_MORE	2
#define	DBDMA_CMD_IN_LAST	3
#define	DBDMA_CMD_STORE_QUAD	4
#define	DBDMA_CMD_LOAD_QUAD	5
#define	DBDMA_CMD_NOP		6
#define	DBDMA_CMD_STOP		7

/* Keys */

#define	DBDMA_KEY_STREAM0	0
#define	DBDMA_KEY_STREAM1	1
#define	DBDMA_KEY_STREAM2	2
#define	DBDMA_KEY_STREAM3	3

/* value 4 is reserved */
#define	DBDMA_KEY_REGS		5
#define	DBDMA_KEY_SYSTEM	6
#define	DBDMA_KEY_DEVICE	7

#define	DBDMA_INT_NEVER		0
#define	DBDMA_INT_IF_TRUE	1
#define	DBDMA_INT_IF_FALSE	2
#define	DBDMA_INT_ALWAYS	3

#define	DBDMA_BRANCH_NEVER	0
#define	DBDMA_BRANCH_IF_TRUE	1
#define	DBDMA_BRANCH_IF_FALSE	2
#define	DBDMA_BRANCH_ALWAYS	3

#define	DBDMA_WAIT_NEVER	0
#define	DBDMA_WAIT_IF_TRUE	1
#define DBDMA_WAIT_IF_FALSE	2
#define	DBDMA_WAIT_ALWAYS	3

/* Channels */

#define	DBDMA_SCSI0		0x0
#define	DBDMA_CURIO_SCSI	DBDMA_SCSI0
#define	DBDMA_FLOPPY		0x1
#define	DBDMA_ETHERNET_TX	0x2
#define	DBDMA_ETHERNET_RV	0x3
#define	DBDMA_SCC_XMIT_A	0x4
#define	DBDMA_SCC_RECV_A	0x5
#define	DBDMA_SCC_XMIT_B	0x6
#define	DBDMA_SCC_RECV_B	0x7
#define	DBDMA_AUDIO_OUT		0x8
#define	DBDMA_AUDIO_IN		0x9
#define	DBDMA_SCSI1		0xA

/* Control register values (in little endian) */

#define	DBDMA_STATUS_MASK	0x000000ff	/* Status Mask */
#define	DBDMA_CNTRL_BRANCH	0x00000100
				/* 0x200 reserved */
#define	DBDMA_CNTRL_ACTIVE	0x00000400
#define	DBDMA_CNTRL_DEAD	0x00000800
#define	DBDMA_CNTRL_WAKE	0x00001000
#define	DBDMA_CNTRL_FLUSH	0x00002000
#define	DBDMA_CNTRL_PAUSE	0x00004000
#define	DBDMA_CNTRL_RUN		0x00008000

#define	DBDMA_SET_CNTRL(x)	( ((x) | (x) << 16) )
#define	DBDMA_CLEAR_CNTRL(x)	( (x) << 16)

#define	DBDMA_COUNT_MAX		0x8000

#define	DBDMA_REGMAP(channel) \
		(dbdma_regmap_t *)((v_u_char *) POWERMAC_IO(PCI_DMA_BASE_PHYS) \
				+ (channel << 8))

/* This struct is layout in little endian format */

struct dbdma_command {
	u_int16_t	d_count;
	u_int16_t	d_command;
	u_int32_t	d_address;
	u_int32_t	d_cmddep;
	u_int16_t	d_resid;
	u_int16_t	d_status;
};

typedef struct dbdma_command dbdma_command_t;

#define	DBDMA_BUILD_CMD(d, cmd, key, interrupt, wait, branch) {		\
		dbdma_st16(&(d)->d_command,				\
				((cmd) << 12) | ((key) << 8) |		\
				((interrupt) << 4) |			\
				((branch) << 2) | (wait));		\
	}

#define	DBDMA_BUILD(d, cmd, key, count, address, interrupt, wait, branch) { \
		dbdma_st16(&(d)->d_count, count);			\
		dbdma_st32(&(d)->d_address, address);			\
		(d)->d_resid = 0;					\
		(d)->d_status = 0;					\
		(d)->d_cmddep = 0;					\
		dbdma_st16(&(d)->d_command,				\
				((cmd) << 12) | ((key) << 8) |		\
				((interrupt) << 4) |			\
				((branch) << 2) | (wait));		\
	}

#if 0
static __inline__ void
dbdma_st32(a, x)
	volatile u_int32_t *a;
	u_int32_t x;
{
	__asm__ volatile
		("stwbrx %0,0,%1" : : "r" (x), "r" (a) : "memory");
	__asm__ volatile ("eieio");
}

static __inline__ void
dbdma_st16(a, x)
	volatile u_int16_t *a;
	u_int16_t x;
{
	__asm__ volatile
		("sthbrx %0,0,%1" : : "r" (x), "r" (a) : "memory");
	__asm__ volatile ("eieio");
}

static __inline__ u_int32_t
dbdma_ld32(a)
	volatile u_int32_t *a;
{
	u_int32_t swap;

	__asm__ volatile ("eieio");
	__asm__ volatile
		("lwbrx %0,0,%1" :  "=r" (swap) : "r" (a));

	return	swap;
}

static __inline__ u_int16_t
dbdma_ld16(a)
	volatile u_int16_t *a;
{
	u_int16_t swap;

	__asm__ volatile ("eieio");
	__asm__ volatile
		("lhbrx %0,0,%1" :  "=r" (swap) : "r" (a));

	return	swap;
}

#define	DBDMA_LD4_ENDIAN(a)	dbdma_ld32(a)
#define	DBDMA_ST4_ENDIAN(a, x)	dbdma_st32(a, x)
#else
#define	DBDMA_LD4_ENDIAN(a)	in32rb(a)
#define	DBDMA_ST4_ENDIAN(a, x)	out32rb(a, x)
#define dbdma_st16(a,x)		out16rb((a),(x))
#define dbdma_ld16(a)		in16rb(a)
#define dbdma_st32(a,x)		out32rb((a),(x))
#define dbdma_ld32(a)		in32rb(a)
#endif

/*
 * DBDMA Channel layout
 *
 * NOTE - This structure is in little-endian format.
 */

struct dbdma_regmap {
	u_int32_t	d_control;	/* Control Register */
	u_int32_t	d_status;	/* DBDMA Status Register */
	u_int32_t	d_cmdptrhi;	/* MSB of command pointer (not used yet) */
	u_int32_t	d_cmdptrlo;	/* LSB of command pointer */
	u_int32_t	d_intselect;	/* Interrupt Select */
	u_int32_t	d_branch;	/* Branch selection */
	u_int32_t	d_wait;		/* Wait selection */
	u_int32_t	d_transmode;	/* Transfer modes */
	u_int32_t	d_dataptrhi;	/* MSB of Data Pointer */
	u_int32_t	d_dataptrlo;	/* LSB of Data Pointer */
	u_int32_t	d_reserved;	/* Reserved for the moment */
	u_int32_t	d_branchptrhi;	/* MSB of Branch Pointer */
	u_int32_t	d_branchptrlo;	/* LSB of Branch Pointer */
	/* The remaining fields are undefinied and unimplemented */
};

typedef volatile struct dbdma_regmap dbdma_regmap_t;

/* DBDMA routines */
typedef
struct dbdma_desc {
	bus_dma_tag_t d_dmat;
	bus_dmamap_t d_map;
	dbdma_command_t *d_addr;
#define	d_paddr	d_segs->ds_addr
	bus_dma_segment_t d_segs[1];
	int d_nsegs;
	size_t d_size;
} *dbdma_t;

dbdma_t	dbdma_alloc(bus_dma_tag_t, int); /* Allocate command structures */
void	dbdma_free(dbdma_t);	/* Dispose command structures */
void	dbdma_start(dbdma_regmap_t *channel, dbdma_t dt);
void	dbdma_stop(dbdma_regmap_t *channel);
void	dbdma_flush(dbdma_regmap_t *channel);
void	dbdma_reset(dbdma_regmap_t *channel);
void	dbdma_continue(dbdma_regmap_t *channel);
void	dbdma_pause(dbdma_regmap_t *channel);

#endif /* !defined(_POWERMAC_DBDMA_H_) */


code:
/*	$OpenBSD: dfs.c,v 1.3 2014/07/08 13:06:58 deraadt Exp $	*/
/*
 * Copyright (c) 2011 Martin Pieuchot <mpi@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/sysctl.h>

#include <dev/ofw/openfirm.h>

#include <machine/cpu.h>
#include <machine/autoconf.h>
#include <macppc/pci/macobio.h>
#include <powerpc/hid.h>

extern int perflevel;

struct dfs_softc {
	struct device	sc_dev;
	int		sc_voltage;
};

int	dfs_match(struct device *, void *, void *);
void	dfs_attach(struct device *, struct device *, void *);
void	dfs_setperf(int);
void	dfs_scale_frequency(u_int);

struct cfattach dfs_ca = {
	sizeof(struct dfs_softc), dfs_match, dfs_attach
};

struct cfdriver dfs_cd = {
	NULL, "dfs", DV_DULL
};

int
dfs_match(struct device *parent, void *arg, void *aux)
{
	struct confargs *ca = aux;
	uint16_t cpu;

	if (strcmp(ca->ca_name, "cpu-vcore-select") != 0)
		return (0);

	cpu = ppc_mfpvr() >> 16;
	if (cpu == PPC_CPU_MPC7447A || cpu == PPC_CPU_MPC7448)
			return (1);

	return (0);
}

void
dfs_attach(struct device *parent, struct device *self, void *aux)
{
	struct dfs_softc *sc = (struct dfs_softc *)self;
	struct confargs *ca = aux;
	uint32_t hid1, reg;
	uint16_t cpu;

	/*
	 * On some models the vcore-select offset is relative to
	 * its parent offset and not to the bus base address.
	 */
	OF_getprop(OF_parent(ca->ca_node), "reg", &reg, sizeof(reg));
	if (reg > ca->ca_reg[0])
		sc->sc_voltage = reg + ca->ca_reg[0];
	else
		sc->sc_voltage = ca->ca_reg[0];

	hid1 = ppc_mfhid1();

	if (hid1 & HID1_DFS4) {
		ppc_curfreq = ppc_maxfreq / 4;
		perflevel = 25;
	} else if (hid1 & HID1_DFS2) {
		ppc_curfreq = ppc_maxfreq / 2;
		perflevel = 50;
	}

	cpu_setperf = dfs_setperf;

	printf(": speeds: %d, %d", ppc_maxfreq, ppc_maxfreq / 2);

	cpu = ppc_mfpvr() >> 16;
	if (cpu == PPC_CPU_MPC7448)
		printf(", %d", ppc_maxfreq / 4);
	printf(" MHz\n");
}

void
dfs_setperf(int perflevel)
{
	struct dfs_softc *sc = dfs_cd.cd_devs[0];

	if (perflevel > 50) {
		if (ppc_curfreq != ppc_maxfreq) {
			macobio_write(sc->sc_voltage, GPIO_DDR_OUTPUT | 1);
			delay(1000);
			dfs_scale_frequency(FREQ_FULL);
		}
	} else {
		uint16_t cpu;

		cpu = ppc_mfpvr() >> 16;
		if (cpu == PPC_CPU_MPC7448 && perflevel <= 25)  {
			if (ppc_curfreq != ppc_maxfreq / 4) {
				dfs_scale_frequency(FREQ_QUARTER);
				macobio_write(sc->sc_voltage,
				    GPIO_DDR_OUTPUT | 0);
				delay(1000);
			}
		} else {
			if (ppc_curfreq != ppc_maxfreq / 2) {
				dfs_scale_frequency(FREQ_HALF);
				macobio_write(sc->sc_voltage,
				    GPIO_DDR_OUTPUT | 0);
				delay(1000);
			}
		}
	}
}

void
dfs_scale_frequency(u_int freq_scale)
{
	uint32_t hid1;
	int s;

	s = splhigh();
	hid1 = ppc_mfhid1();

	hid1 &= ~(HID1_DFS2 | HID1_DFS4);
	switch (freq_scale) {
	case FREQ_QUARTER:
		hid1 |= HID1_DFS4;
		ppc_curfreq = ppc_maxfreq / 4;
		break;
	case FREQ_HALF:
		hid1 |= HID1_DFS2;
		ppc_curfreq = ppc_maxfreq / 2;
		break;
	case FREQ_FULL: /* FALLTHROUGH */
	default:
		ppc_curfreq = ppc_maxfreq;
	}

	asm volatile ("sync");
	ppc_mthid1(hid1);
	asm volatile ("sync; isync");

	splx(s);
}


code:
/* $OpenBSD: esp.c,v 1.11 2014/01/21 03:42:21 dlg Exp $ */

/*-
 * Copyright (c) 1997, 1998 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Charles M. Hannum and by Jason R. Thorpe of the Numerical Aerospace
 * Simulation Facility, NASA Ames Research Center.
 *
 * 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.
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``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 FOUNDATION OR CONTRIBUTORS
 * 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.
 */

/*
 * Copyright (c) 1994 Peter Galbavy
 * 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.
 * 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. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Peter Galbavy
 * 4. 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.
 */

/*
 * Based on aic6360 by Jarle Greipsland
 *
 * Acknowledgements: Many of the algorithms used in this driver are
 * inspired by the work of Julian Elischer (julian@tfs.com) and
 * Charles Hannum (mycroft@duality.gnu.ai.mit.edu).  Thanks a million!
 */

#include <sys/types.h>
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/errno.h>
#include <sys/ioctl.h>
#include <sys/device.h>
#include <sys/buf.h>
#include <sys/proc.h>
#include <sys/queue.h>
#include <sys/malloc.h>

#include <uvm/uvm_extern.h>

#include <scsi/scsi_all.h>
#include <scsi/scsiconf.h>
#include <scsi/scsi_message.h>

#include <dev/ofw/openfirm.h>

#include <machine/cpu.h>
#include <machine/autoconf.h>
#include <machine/pio.h>

#include <dev/ic/ncr53c9xreg.h>
#include <dev/ic/ncr53c9xvar.h>

#include <macppc/dev/dbdma.h>

struct esp_softc {
	struct ncr53c9x_softc sc_ncr53c9x;	/* glue to MI code */

	struct intrhand sc_ih;			/* intr handler */

	volatile u_char *sc_reg;		/* the registers */

	bus_dmamap_t sc_dmamap;
	bus_dma_tag_t sc_dmat;
	dbdma_t sc_dbdma;
	dbdma_regmap_t *sc_dmareg;		/* DMA registers */
	dbdma_command_t *sc_dmacmd;		/* command area for DMA */

	int sc_node;				/* node ID */
	int sc_intr;

	size_t	sc_dmasize;
	caddr_t *sc_dmaaddr;
	size_t  *sc_dmalen;
	int sc_dmaactive;
	int sc_dma_direction;
};

#define D_WRITE 1
#define ESP_DMALIST_MAX	20

void espattach(struct device *, struct device *, void *);
int espmatch(struct device *, void *, void *);

/* Linkup to the rest of the kernel */
struct cfattach esp_ca = {
	sizeof(struct esp_softc), espmatch, espattach,
	NULL, espactivate
};

/*
 * Functions and the switch for the MI code.
 */
u_char	esp_read_reg(struct ncr53c9x_softc *, int);
void	esp_write_reg(struct ncr53c9x_softc *, int, u_char);
int	esp_dma_isintr(struct ncr53c9x_softc *);
void	esp_dma_reset(struct ncr53c9x_softc *);
int	esp_dma_intr(struct ncr53c9x_softc *);
int	esp_dma_setup(struct ncr53c9x_softc *, caddr_t *,
    size_t *, int, size_t *);
void	esp_dma_go(struct ncr53c9x_softc *);
void	esp_dma_stop(struct ncr53c9x_softc *);
int	esp_dma_isactive(struct ncr53c9x_softc *);

struct ncr53c9x_glue esp_glue = {
	esp_read_reg,
	esp_write_reg,
	esp_dma_isintr,
	esp_dma_reset,
	esp_dma_intr,
	esp_dma_setup,
	esp_dma_go,
	esp_dma_stop,
	esp_dma_isactive,
	NULL,			/* gl_clear_latched_intr */
};

static int espdmaintr(struct esp_softc *);

int
espmatch(struct device *parent, void *cf, void *aux)
{
	struct confargs *ca = aux;

	if (strcmp(ca->ca_name, "53c94") != 0)
		return 0;

	if (ca->ca_nreg != 16)
		return 0;
	if (ca->ca_nintr != 8)
		return 0;

	return 1;
}

/*
 * Attach this instance, and then all the sub-devices
 */
void
espattach(struct device *parent, struct device *self, void *aux)
{
	struct confargs *ca = aux;
	struct esp_softc *esc = (void *)self;
	struct ncr53c9x_softc *sc = &esc->sc_ncr53c9x;
	u_int *reg;
	int sz, error;

	/*
	 * Set up glue for MI code early; we use some of it here.
	 */
	sc->sc_glue = &esp_glue;

	esc->sc_node = ca->ca_node;
	esc->sc_intr = ca->ca_intr[0];
	printf(" irq %d", esc->sc_intr);

	/*
	 * Map my registers in.
	 */
	reg = ca->ca_reg;
	esc->sc_reg = mapiodev(ca->ca_baseaddr + reg[0], reg[1]);
	esc->sc_dmareg = mapiodev(ca->ca_baseaddr + reg[2], reg[3]);

	esc->sc_dmat = ca->ca_dmat;
	if ((error = bus_dmamap_create(esc->sc_dmat,
	    ESP_DMALIST_MAX * DBDMA_COUNT_MAX, ESP_DMALIST_MAX,
	    DBDMA_COUNT_MAX, NBPG, BUS_DMA_NOWAIT, &esc->sc_dmamap)) != 0) {
		printf(": cannot create dma map, error = %d\n", error);
		return;
	}

	/* Allocate 16-byte aligned DMA command space */
	esc->sc_dbdma = dbdma_alloc(esc->sc_dmat, ESP_DMALIST_MAX);
	esc->sc_dmacmd = esc->sc_dbdma->d_addr;

	/* Other settings */
	sc->sc_id = 7;
	sz = OF_getprop(ca->ca_node, "clock-frequency",
		&sc->sc_freq, sizeof(int));
	if (sz != sizeof(int))
		sc->sc_freq = 25000000;

	/* gimme MHz */
	sc->sc_freq /= 1000000;

	/*
	 * Set up static configuration info.
	 */
	sc->sc_cfg1 = sc->sc_id | NCRCFG1_PARENB;
	sc->sc_cfg2 = NCRCFG2_SCSI2; /* | NCRCFG2_FE */
	sc->sc_cfg3 = NCRCFG3_CDB;
	sc->sc_rev = NCR_VARIANT_NCR53C94;

	/*
	 * This is the value used to start sync negotiations
	 * Note that the NCR register "SYNCTP" is programmed
	 * in "clocks per byte", and has a minimum value of 4.
	 * The SCSI period used in negotiation is one-fourth
	 * of the time (in nanoseconds) needed to transfer one byte.
	 * Since the chip's clock is given in MHz, we have the following
	 * formula: 4 * period = (1000 / freq) * 4
	 */
	sc->sc_minsync = 1000 / sc->sc_freq;

	sc->sc_maxxfer = 64 * 1024;

	/* and the interuppts */
	mac_intr_establish(parent, esc->sc_intr, IST_LEVEL, IPL_BIO,
	    ncr53c9x_intr, sc, sc->sc_dev.dv_xname);

	/* Turn on target selection using the `DMA' method */
	sc->sc_features |= NCR_F_DMASELECT;

	ncr53c9x_attach(sc);

}

int
esp_activate(struct device *self, int act)
{
	struct ncr53c9x_softc *sc = self;
	int rv = 0;

	switch (act) {
	case DVACT_POWERDOWN:
		rv = config_activate_children(self, act);
		NCRCMD(sc, NCRCMD_RSTSCSI);
		break;
	default:
		rv = config_activate_children(self, act);
		break;
	}
	return (rv);
}

/*
 * Glue functions.
 */

u_char
esp_read_reg(struct ncr53c9x_softc *sc, int reg)
{
	struct esp_softc *esc = (struct esp_softc *)sc;

	return in8(&esc->sc_reg[reg * 16]);
}

void
esp_write_reg(struct ncr53c9x_softc *sc, int reg, u_char val)
{
	struct esp_softc *esc = (struct esp_softc *)sc;
	u_char v = val;

	out8(&esc->sc_reg[reg * 16], v);
}

int
esp_dma_isintr(struct ncr53c9x_softc *sc)
{
	return esp_read_reg(sc, NCR_STAT) & NCRSTAT_INT;
}

void
esp_dma_reset(struct ncr53c9x_softc *sc)
{
	struct esp_softc *esc = (struct esp_softc *)sc;

	dbdma_stop(esc->sc_dmareg);
	esc->sc_dmaactive = 0;
}

int
esp_dma_intr(struct ncr53c9x_softc *sc)
{
	struct esp_softc *esc = (struct esp_softc *)sc;

	return (espdmaintr(esc));
}

int
esp_dma_setup(struct ncr53c9x_softc *sc, caddr_t *addr, size_t *len,
     int datain, size_t *dmasize)
{
	struct esp_softc *esc = (struct esp_softc *)sc;
	dbdma_command_t *cmdp;
	u_int cmd;
	int i, error;

	cmdp = esc->sc_dmacmd;
	cmd = datain ? DBDMA_CMD_IN_MORE : DBDMA_CMD_OUT_MORE;

	esc->sc_dmaaddr = addr;
	esc->sc_dmalen = len;
	esc->sc_dmasize = *dmasize;

	if ((error = bus_dmamap_load(esc->sc_dmat, esc->sc_dmamap, *addr,
	    *dmasize, NULL, BUS_DMA_NOWAIT)) != 0)
		return (error);

	for (i = 0; i < esc->sc_dmamap->dm_nsegs; i++, cmdp++) {
		if (i + 1 == esc->sc_dmamap->dm_nsegs)
			cmd = datain ? DBDMA_CMD_IN_LAST : DBDMA_CMD_OUT_LAST;
		DBDMA_BUILD(cmdp, cmd, 0, esc->sc_dmamap->dm_segs[i].ds_len,
		    esc->sc_dmamap->dm_segs[i].ds_addr, DBDMA_INT_NEVER,
		    DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);
	}
	DBDMA_BUILD(cmdp, DBDMA_CMD_STOP, 0, 0, 0,
	    DBDMA_INT_NEVER, DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);

	esc->sc_dma_direction = datain ? D_WRITE : 0;

	return 0;
}

void
esp_dma_go(struct ncr53c9x_softc *sc)
{
	struct esp_softc *esc = (struct esp_softc *)sc;

	dbdma_start(esc->sc_dmareg, esc->sc_dbdma);
	esc->sc_dmaactive = 1;
}

void
esp_dma_stop(struct ncr53c9x_softc *sc)
{
	struct esp_softc *esc = (struct esp_softc *)sc;

	dbdma_stop(esc->sc_dmareg);
	bus_dmamap_unload(esc->sc_dmat, esc->sc_dmamap);
	esc->sc_dmaactive = 0;
}

int
esp_dma_isactive(struct ncr53c9x_softc *sc)
{
	struct esp_softc *esc = (struct esp_softc *)sc;

	return (esc->sc_dmaactive);
}

/*
 * Pseudo (chained) interrupt from the esp driver to kick the
 * current running DMA transfer. I am replying on espintr() to
 * pickup and clean errors for now
 *
 * return 1 if it was a DMA continue.
 */
int
espdmaintr(struct esp_softc *sc)
{
	struct ncr53c9x_softc *nsc = (struct ncr53c9x_softc *)sc;
	int trans, resid;
	u_long csr = sc->sc_dma_direction;

	/* This is an "assertion" :) */
	if (sc->sc_dmaactive == 0)
		panic("dmaintr: DMA wasn't active");

	/* DMA has stopped */
	dbdma_stop(sc->sc_dmareg);
	bus_dmamap_unload(sc->sc_dmat, sc->sc_dmamap);
	sc->sc_dmaactive = 0;

	if (sc->sc_dmasize == 0) {
		/* A "Transfer Pad" operation completed */
		NCR_DMA(("dmaintr: discarded %d bytes (tcl=%d, tcm=%d)\n",
		    NCR_READ_REG(nsc, NCR_TCL) |
		    (NCR_READ_REG(nsc, NCR_TCM) << 8),
		    NCR_READ_REG(nsc, NCR_TCL),
		    NCR_READ_REG(nsc, NCR_TCM)));
		return 0;
	}

	resid = 0;
	/*
	 * If a transfer onto the SCSI bus gets interrupted by the device
	 * (e.g. for a SAVEPOINTER message), the data in the FIFO counts
	 * as residual since the ESP counter registers get decremented as
	 * bytes are clocked into the FIFO.
	 */
	if (!(csr & D_WRITE) &&
	    (resid = (NCR_READ_REG(nsc, NCR_FFLAG) & NCRFIFO_FF)) != 0) {
		NCR_DMA(("dmaintr: empty esp FIFO of %d ", resid));
	}

	if ((nsc->sc_espstat & NCRSTAT_TC) == 0) {
		/*
		 * `Terminal count' is off, so read the residue
		 * out of the ESP counter registers.
		 */
		resid += (NCR_READ_REG(nsc, NCR_TCL) |
		    (NCR_READ_REG(nsc, NCR_TCM) << 8) |
		    ((nsc->sc_cfg2 & NCRCFG2_FE)
		    ? (NCR_READ_REG(nsc, NCR_TCH) << 16) : 0));

		if (resid == 0 && sc->sc_dmasize == 65536 &&
		    (nsc->sc_cfg2 & NCRCFG2_FE) == 0)
			/* A transfer of 64K is encoded as `TCL=TCM=0' */
			resid = 65536;
	}

	trans = sc->sc_dmasize - resid;
	if (trans < 0) {			/* transferred < 0 ? */
		trans = sc->sc_dmasize;
	}

	NCR_DMA(("dmaintr: tcl=%d, tcm=%d, tch=%d; trans=%d, resid=%d\n",
	    NCR_READ_REG(nsc, NCR_TCL), NCR_READ_REG(nsc, NCR_TCM),
	    (nsc->sc_cfg2 & NCRCFG2_FE) ? NCR_READ_REG(nsc, NCR_TCH) : 0,
	    trans, resid));

	*sc->sc_dmalen -= trans;
	*sc->sc_dmaaddr += trans;

	return 0;
}


code:
/*	$OpenBSD: i2s.c,v 1.29 2015/07/17 22:30:58 mpi Exp $	*/
/*	$NetBSD: i2s.c,v 1.1 2003/12/27 02:19:34 grant Exp $	*/

/*-
 * Copyright (c) 2002 Tsubai Masanari.  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.
 * 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.
 */

#include <sys/param.h>
#include <sys/audioio.h>
#include <sys/device.h>
#include <sys/malloc.h>
#include <sys/systm.h>

#include <dev/audio_if.h>
#include <dev/ofw/openfirm.h>
#include <macppc/dev/dbdma.h>

#include <uvm/uvm_extern.h>

#include <machine/autoconf.h>
#include <machine/pio.h>

#include <macppc/dev/i2svar.h>
#include <macppc/dev/i2sreg.h>
#include <macppc/pci/macobio.h>

#ifdef I2S_DEBUG
# define DPRINTF(x) printf x
#else
# define DPRINTF(x)
#endif

struct audio_params i2s_audio_default = {
	44100,		/* sample_rate */
	AUDIO_ENCODING_SLINEAR_BE, /* encoding */
	16,		/* precision */
	2,		/* bps */
	1,		/* msb */
	2		/* channels */
};

void	i2s_mute(u_int, int);
int	i2s_cint(void *);
u_int	i2s_gpio_offset(struct i2s_softc *, char *, int *);
void	i2s_init(struct i2s_softc *, int);

int	i2s_intr(void *);
int	i2s_iintr(void *);

struct cfdriver i2s_cd = {
	NULL, "i2s", DV_DULL
};

void
i2s_attach(struct device *parent, struct i2s_softc *sc, struct confargs *ca)
{
	int cirq, oirq, iirq, cirq_type, oirq_type, iirq_type;
	u_int32_t reg[6], intr[6];
	char compat[32];
	int child;

	sc->sc_node = OF_child(ca->ca_node);
	sc->sc_baseaddr = ca->ca_baseaddr;

	OF_getprop(sc->sc_node, "reg", reg, sizeof reg);

	child = OF_child(sc->sc_node);
	memset(compat, 0, sizeof(compat));
	OF_getprop(child, "compatible", compat, sizeof(compat));

	/* Deal with broken device-tree on PowerMac7,2 and 7,3. */
	if (strcmp(compat, "AOAK2") == 0) {
		reg[0] += ca->ca_reg[0];
		reg[2] += ca->ca_reg[2];
		reg[4] += ca->ca_reg[2];
	}

	reg[0] += sc->sc_baseaddr;
	reg[2] += sc->sc_baseaddr;
	reg[4] += sc->sc_baseaddr;

	sc->sc_reg = mapiodev(reg[0], reg[1]);

	sc->sc_dmat = ca->ca_dmat;
	sc->sc_odma = mapiodev(reg[2], reg[3]); /* out */
	sc->sc_idma = mapiodev(reg[4], reg[5]); /* in */
	sc->sc_odbdma = dbdma_alloc(sc->sc_dmat, I2S_DMALIST_MAX);
	sc->sc_odmacmd = sc->sc_odbdma->d_addr;
	sc->sc_idbdma = dbdma_alloc(sc->sc_dmat, I2S_DMALIST_MAX);
	sc->sc_idmacmd = sc->sc_idbdma->d_addr;

	OF_getprop(sc->sc_node, "interrupts", intr, sizeof intr);
	cirq = intr[0];
	oirq = intr[2];
	iirq = intr[4];
	cirq_type = (intr[1] & 1) ? IST_LEVEL : IST_EDGE;
	oirq_type = (intr[3] & 1) ? IST_LEVEL : IST_EDGE;
	iirq_type = (intr[5] & 1) ? IST_LEVEL : IST_EDGE;

	/* intr_establish(cirq, cirq_type, IPL_AUDIO, i2s_intr, sc); */
	mac_intr_establish(parent, oirq, oirq_type, IPL_AUDIO | IPL_MPSAFE,
	    i2s_intr, sc, sc->sc_dev.dv_xname);
	mac_intr_establish(parent, iirq, iirq_type, IPL_AUDIO | IPL_MPSAFE,
	    i2s_iintr, sc, sc->sc_dev.dv_xname);

	printf(": irq %d,%d,%d\n", cirq, oirq, iirq);

	/* Need to be explicitly turned on some G5. */
	macobio_enable(I2SClockOffset, I2S0CLKEN|I2S0EN);

	i2s_set_rate(sc, 44100);
	sc->sc_mute = 0;
	i2s_gpio_init(sc, ca->ca_node, parent);
}

int
i2s_intr(v)
	void *v;
{
	struct i2s_softc *sc = v;
	struct dbdma_command *cmd = sc->sc_odmap;
	u_int16_t c, status;

	mtx_enter(&audio_lock);

	/* if not set we are not running */
	if (!cmd) {
		mtx_leave(&audio_lock);
		return (0);
	}
	DPRINTF(("i2s_intr: cmd %x\n", cmd));

	c = in16rb(&cmd->d_command);
	status = in16rb(&cmd->d_status);

	if (c >> 12 == DBDMA_CMD_OUT_LAST)
		sc->sc_odmap = sc->sc_odmacmd;
	else
		sc->sc_odmap++;

	if (c & (DBDMA_INT_ALWAYS << 4)) {
		cmd->d_status = 0;
		if (status)	/* status == 0x8400 */
			if (sc->sc_ointr)
				(*sc->sc_ointr)(sc->sc_oarg);
	}
	mtx_leave(&audio_lock);
	return 1;
}

int
i2s_iintr(v)
	void *v;
{
	struct i2s_softc *sc = v;
	struct dbdma_command *cmd = sc->sc_idmap;
	u_int16_t c, status;

	mtx_enter(&audio_lock);

	/* if not set we are not running */
	if (!cmd) {
		mtx_leave(&audio_lock);
		return (0);
	}
	DPRINTF(("i2s_intr: cmd %x\n", cmd));

	c = in16rb(&cmd->d_command);
	status = in16rb(&cmd->d_status);

	if (c >> 12 == DBDMA_CMD_IN_LAST)
		sc->sc_idmap = sc->sc_idmacmd;
	else
		sc->sc_idmap++;

	if (c & (DBDMA_INT_ALWAYS << 4)) {
		cmd->d_status = 0;
		if (status)	/* status == 0x8400 */
			if (sc->sc_iintr)
				(*sc->sc_iintr)(sc->sc_iarg);
	}
	mtx_leave(&audio_lock);
	return 1;
}

int
i2s_open(h, flags)
	void *h;
	int flags;
{
	return 0;
}

/*
 * Close function is called at splaudio().
 */
void
i2s_close(h)
	void *h;
{
	struct i2s_softc *sc = h;

	i2s_halt_output(sc);
	i2s_halt_input(sc);

	sc->sc_ointr = 0;
	sc->sc_iintr = 0;
}

int
i2s_query_encoding(h, ae)
	void *h;
	struct audio_encoding *ae;
{
	int err = 0;

	switch (ae->index) {
	case 0:
		strlcpy(ae->name, AudioEslinear_be, sizeof(ae->name));
		ae->encoding = AUDIO_ENCODING_SLINEAR_BE;
		ae->precision = 16;
		ae->flags = 0;
		break;
	default:
		err = EINVAL;
		break;
	}
	ae->bps = AUDIO_BPS(ae->precision);
	ae->msb = 1;
	return (err);
}

int
i2s_set_params(h, setmode, usemode, play, rec)
	void *h;
	int setmode, usemode;
	struct audio_params *play, *rec;
{
	struct i2s_softc *sc = h;
	struct audio_params *p;
	int mode;

	p = play; /* default to play */

	/*
	 * This device only has one clock, so make the sample rates match.
	 */
	if (play->sample_rate != rec->sample_rate &&
	    usemode == (AUMODE_PLAY | AUMODE_RECORD)) {
		if (setmode == AUMODE_PLAY) {
			rec->sample_rate = play->sample_rate;
			setmode |= AUMODE_RECORD;
		} else if (setmode == AUMODE_RECORD) {
			play->sample_rate = rec->sample_rate;
			setmode |= AUMODE_PLAY;
		} else
			return EINVAL;
	}

	for (mode = AUMODE_RECORD; mode != -1;
	     mode = mode == AUMODE_RECORD ? AUMODE_PLAY : -1) {
		if ((setmode & mode) == 0)
			continue;

		p = mode == AUMODE_PLAY ? play : rec;

		if (p->sample_rate < 4000)
			p->sample_rate = 4000;
		if (p->sample_rate > 50000)
			p->sample_rate = 50000;
		if (p->precision > 16)
			p->precision = 16;
		if (p->channels > 2)
			p->channels = 2;

		switch (p->encoding) {
		case AUDIO_ENCODING_SLINEAR_BE:
			break;
		default:
			return (EINVAL);
		}
	}

	/* Set the speed */
	if (i2s_set_rate(sc, play->sample_rate))
		return EINVAL;

	p->sample_rate = sc->sc_rate;

	p->bps = AUDIO_BPS(p->precision);
	p->msb = 1;

	return 0;
}

void
i2s_get_default_params(struct audio_params *params)
{
	*params = i2s_audio_default;
}

int
i2s_round_blocksize(h, size)
	void *h;
	int size;
{
	if (size < NBPG)
		size = NBPG;
	return size & ~PGOFSET;
}

int
i2s_halt_output(h)
	void *h;
{
	struct i2s_softc *sc = h;

	dbdma_stop(sc->sc_odma);
	dbdma_reset(sc->sc_odma);
	return 0;
}

int
i2s_halt_input(h)
	void *h;
{
	struct i2s_softc *sc = h;

	dbdma_stop(sc->sc_idma);
	dbdma_reset(sc->sc_idma);
	return 0;
}

enum {
	I2S_OUTPUT_CLASS,
	I2S_RECORD_CLASS,
	I2S_OUTPUT_SELECT,
	I2S_VOL_OUTPUT,
	I2S_INPUT_SELECT,
	I2S_VOL_INPUT,
	I2S_MUTE, 		/* should be before bass/treble */
	I2S_BASS,
	I2S_TREBLE,
	I2S_ENUM_LAST
};

int
i2s_set_port(void *h, mixer_ctrl_t *mc)
{
	struct i2s_softc *sc = h;
	int l, r;

	DPRINTF(("i2s_set_port dev = %d, type = %d\n", mc->dev, mc->type));

	l = mc->un.value.level[AUDIO_MIXER_LEVEL_LEFT];
	r = mc->un.value.level[AUDIO_MIXER_LEVEL_RIGHT];

	switch (mc->dev) {
	case I2S_OUTPUT_SELECT:
		/* No change necessary? */
		if (mc->un.mask == sc->sc_output_mask)
			return 0;

		i2s_mute(sc->sc_spkr, 1);
		i2s_mute(sc->sc_hp, 1);
		i2s_mute(sc->sc_line, 1);
		if (mc->un.mask & I2S_SELECT_SPEAKER)
			i2s_mute(sc->sc_spkr, 0);
		if (mc->un.mask & I2S_SELECT_HEADPHONE)
			i2s_mute(sc->sc_hp, 0);
		if (mc->un.mask & I2S_SELECT_LINEOUT)
			i2s_mute(sc->sc_line, 0);

		sc->sc_output_mask = mc->un.mask;
		return 0;

	case I2S_VOL_OUTPUT:
		(*sc->sc_setvolume)(sc, l, r);
		return 0;

	case I2S_MUTE:
		if (mc->type != AUDIO_MIXER_ENUM)
			return (EINVAL);

		sc->sc_mute = (mc->un.ord != 0);

		if (sc->sc_mute) {
			if (sc->sc_output_mask & I2S_SELECT_SPEAKER)
				i2s_mute(sc->sc_spkr, 1);
			if (sc->sc_output_mask & I2S_SELECT_HEADPHONE)
				i2s_mute(sc->sc_hp, 1);
			if (sc->sc_output_mask & I2S_SELECT_LINEOUT)
				i2s_mute(sc->sc_line, 1);
		} else {
			if (sc->sc_output_mask & I2S_SELECT_SPEAKER)
				i2s_mute(sc->sc_spkr, 0);
			if (sc->sc_output_mask & I2S_SELECT_HEADPHONE)
				i2s_mute(sc->sc_hp, 0);
			if (sc->sc_output_mask & I2S_SELECT_LINEOUT)
				i2s_mute(sc->sc_line, 0);
		}

		return (0);

	case I2S_BASS:
		if (sc->sc_setbass != NULL)
			(*sc->sc_setbass)(sc, l);
		return (0);

	case I2S_TREBLE:
		if (sc->sc_settreble != NULL)
			(*sc->sc_settreble)(sc, l);
		return (0);

	case I2S_INPUT_SELECT:
		/* no change necessary? */
		if (mc->un.mask == sc->sc_record_source)
			return 0;
		switch (mc->un.mask) {
		case I2S_SELECT_SPEAKER:
		case I2S_SELECT_HEADPHONE:
			/* XXX TO BE DONE */
			break;
		default: /* invalid argument */
			return EINVAL;
		}
		if (sc->sc_setinput != NULL)
			(*sc->sc_setinput)(sc, mc->un.mask);
		sc->sc_record_source = mc->un.mask;
		return 0;

	case I2S_VOL_INPUT:
		/* XXX TO BE DONE */
		return 0;
	}

	return ENXIO;
}

int
i2s_get_port(void *h, mixer_ctrl_t *mc)
{
	struct i2s_softc *sc = h;

	DPRINTF(("i2s_get_port dev = %d, type = %d\n", mc->dev, mc->type));

	switch (mc->dev) {
	case I2S_OUTPUT_SELECT:
		mc->un.mask = sc->sc_output_mask;
		return 0;

	case I2S_VOL_OUTPUT:
		mc->un.value.level[AUDIO_MIXER_LEVEL_LEFT] = sc->sc_vol_l;
		mc->un.value.level[AUDIO_MIXER_LEVEL_RIGHT] = sc->sc_vol_r;
		return 0;

	case I2S_MUTE:
		mc->un.ord = sc->sc_mute;
		return (0);

	case I2S_INPUT_SELECT:
		mc->un.mask = sc->sc_record_source;
		return 0;

	case I2S_BASS:
		if (mc->un.value.num_channels != 1)
			return ENXIO;
		mc->un.value.level[AUDIO_MIXER_LEVEL_MONO] = sc->sc_bass;
		return 0;

	case I2S_TREBLE:
		if (mc->un.value.num_channels != 1)
			return ENXIO;
		mc->un.value.level[AUDIO_MIXER_LEVEL_MONO] = sc->sc_treble;
		return 0;

	case I2S_VOL_INPUT:
		/* XXX TO BE DONE */
		mc->un.value.level[AUDIO_MIXER_LEVEL_LEFT] = 0;
		mc->un.value.level[AUDIO_MIXER_LEVEL_RIGHT] = 0;
		return 0;

	default:
		return ENXIO;
	}

	return 0;
}

int
i2s_query_devinfo(void *h, mixer_devinfo_t *dip)
{
	struct i2s_softc *sc = h;
	int n = 0;

	switch (dip->index) {

	case I2S_OUTPUT_SELECT:
		dip->mixer_class = I2S_OUTPUT_CLASS;
		strlcpy(dip->label.name, AudioNselect, sizeof(dip->label.name));
		dip->type = AUDIO_MIXER_SET;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		strlcpy(dip->un.s.member[n].label.name, AudioNspeaker,
		    sizeof(dip->un.s.member[n].label.name));
		dip->un.s.member[n++].mask = I2S_SELECT_SPEAKER;
		if (sc->sc_hp) {
			strlcpy(dip->un.s.member[n].label.name,
			    AudioNheadphone,
			    sizeof(dip->un.s.member[n].label.name));
			dip->un.s.member[n++].mask = I2S_SELECT_HEADPHONE;
		}
		if (sc->sc_line) {
			strlcpy(dip->un.s.member[n].label.name,	AudioNline,
			    sizeof(dip->un.s.member[n].label.name));
			dip->un.s.member[n++].mask = I2S_SELECT_LINEOUT;
		}
		dip->un.s.num_mem = n;
		return 0;

	case I2S_VOL_OUTPUT:
		dip->mixer_class = I2S_OUTPUT_CLASS;
		strlcpy(dip->label.name, AudioNmaster, sizeof(dip->label.name));
		dip->type = AUDIO_MIXER_VALUE;
		dip->prev = AUDIO_MIXER_LAST;
		dip->next = I2S_MUTE;
		dip->un.v.num_channels = 2;
		dip->un.v.delta = 8;
		strlcpy(dip->un.v.units.name, AudioNvolume,
		    sizeof(dip->un.v.units.name));
		return 0;

	case I2S_MUTE:
		dip->mixer_class = I2S_OUTPUT_CLASS;
		dip->prev = I2S_VOL_OUTPUT;
		dip->next = AUDIO_MIXER_LAST;
		strlcpy(dip->label.name, AudioNmute, sizeof(dip->label.name));
		dip->type = AUDIO_MIXER_ENUM;
		dip->un.e.num_mem = 2;
		strlcpy(dip->un.e.member[0].label.name, AudioNoff,
		    sizeof dip->un.e.member[0].label.name);
		dip->un.e.member[0].ord = 0;
		strlcpy(dip->un.e.member[1].label.name, AudioNon,
		    sizeof dip->un.e.member[1].label.name);
		dip->un.e.member[1].ord = 1;
		return (0);

	case I2S_INPUT_SELECT:
		dip->mixer_class = I2S_RECORD_CLASS;
		strlcpy(dip->label.name, AudioNsource, sizeof(dip->label.name));
		dip->type = AUDIO_MIXER_SET;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		dip->un.s.num_mem = 2;
		strlcpy(dip->un.s.member[0].label.name, AudioNmicrophone,
		    sizeof(dip->un.s.member[0].label.name));
		dip->un.s.member[0].mask = I2S_SELECT_SPEAKER;
		strlcpy(dip->un.s.member[1].label.name, AudioNline,
		    sizeof(dip->un.s.member[1].label.name));
		dip->un.s.member[1].mask = I2S_SELECT_HEADPHONE;
		return 0;

	case I2S_VOL_INPUT:
		dip->mixer_class = I2S_RECORD_CLASS;
		strlcpy(dip->label.name, AudioNrecord, sizeof(dip->label.name));
		dip->type = AUDIO_MIXER_VALUE;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		dip->un.v.num_channels = 2;
		strlcpy(dip->un.v.units.name, AudioNvolume,
		    sizeof(dip->un.v.units.name));
		return 0;

	case I2S_OUTPUT_CLASS:
		dip->mixer_class = I2S_OUTPUT_CLASS;
		strlcpy(dip->label.name, AudioCoutputs,
		    sizeof(dip->label.name));
		dip->type = AUDIO_MIXER_CLASS;
		dip->next = dip->prev = AUDIO_MIXER_LAST;
		return 0;

	case I2S_RECORD_CLASS:
		dip->mixer_class = I2S_RECORD_CLASS;
		strlcpy(dip->label.name, AudioCrecord, sizeof(dip->label.name));
		dip->type = AUDIO_MIXER_CLASS;
		dip->next = dip->prev = AUDIO_MIXER_LAST;
		return 0;

	case I2S_BASS:
		if (sc->sc_setbass == NULL)
			return (ENXIO);
		dip->mixer_class = I2S_OUTPUT_CLASS;
		strlcpy(dip->label.name, AudioNbass, sizeof(dip->label.name));
		dip->type = AUDIO_MIXER_VALUE;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		dip->un.v.num_channels = 1;
		return (0);

	case I2S_TREBLE:
		if (sc->sc_settreble == NULL)
			return (ENXIO);
		dip->mixer_class = I2S_OUTPUT_CLASS;
		strlcpy(dip->label.name, AudioNtreble, sizeof(dip->label.name));
		dip->type = AUDIO_MIXER_VALUE;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		dip->un.v.num_channels = 1;
		return (0);
	}

	return ENXIO;
}

size_t
i2s_round_buffersize(h, dir, size)
	void *h;
	int dir;
	size_t size;
{
	if (size > 65536)
		size = 65536;
	return size;
}

paddr_t
i2s_mappage(h, mem, off, prot)
	void *h;
	void *mem;
	off_t off;
	int prot;
{
	if (off < 0)
		return -1;
	return -1;	/* XXX */
}

int
i2s_get_props(h)
	void *h;
{
	return AUDIO_PROP_FULLDUPLEX /* | AUDIO_PROP_MMAP */;
}

int
i2s_trigger_output(h, start, end, bsize, intr, arg, param)
	void *h;
	void *start, *end;
	int bsize;
	void (*intr)(void *);
	void *arg;
	struct audio_params *param;
{
	struct i2s_softc *sc = h;
	struct i2s_dma *p;
	struct dbdma_command *cmd = sc->sc_odmacmd;
	vaddr_t spa, pa, epa;
	int c;

	DPRINTF(("trigger_output %p %p 0x%x\n", start, end, bsize));

	for (p = sc->sc_dmas; p && p->addr != start; p = p->next);
	if (!p)
		return -1;

	sc->sc_ointr = intr;
	sc->sc_oarg = arg;
	sc->sc_odmap = sc->sc_odmacmd;

	spa = p->segs[0].ds_addr;
	c = DBDMA_CMD_OUT_MORE;
	for (pa = spa, epa = spa + (end - start);
	    pa < epa; pa += bsize, cmd++) {

		if (pa + bsize == epa)
			c = DBDMA_CMD_OUT_LAST;

		DBDMA_BUILD(cmd, c, 0, bsize, pa, DBDMA_INT_ALWAYS,
			DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);
	}

	DBDMA_BUILD(cmd, DBDMA_CMD_NOP, 0, 0, 0,
		DBDMA_INT_NEVER, DBDMA_WAIT_NEVER, DBDMA_BRANCH_ALWAYS);
	dbdma_st32(&cmd->d_cmddep, sc->sc_odbdma->d_paddr);

	dbdma_start(sc->sc_odma, sc->sc_odbdma);

	return 0;
}

int
i2s_trigger_input(h, start, end, bsize, intr, arg, param)
	void *h;
	void *start, *end;
	int bsize;
	void (*intr)(void *);
	void *arg;
	struct audio_params *param;
{
	struct i2s_softc *sc = h;
	struct i2s_dma *p;
	struct dbdma_command *cmd = sc->sc_idmacmd;
	vaddr_t spa, pa, epa;
	int c;

	DPRINTF(("trigger_input %p %p 0x%x\n", start, end, bsize));

	for (p = sc->sc_dmas; p && p->addr != start; p = p->next);
	if (!p)
		return -1;

	sc->sc_iintr = intr;
	sc->sc_iarg = arg;
	sc->sc_idmap = sc->sc_idmacmd;

	spa = p->segs[0].ds_addr;
	c = DBDMA_CMD_IN_MORE;
	for (pa = spa, epa = spa + (end - start);
	    pa < epa; pa += bsize, cmd++) {

		if (pa + bsize == epa)
			c = DBDMA_CMD_IN_LAST;

		DBDMA_BUILD(cmd, c, 0, bsize, pa, DBDMA_INT_ALWAYS,
			DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);
	}

	DBDMA_BUILD(cmd, DBDMA_CMD_NOP, 0, 0, 0,
		DBDMA_INT_NEVER, DBDMA_WAIT_NEVER, DBDMA_BRANCH_ALWAYS);
	dbdma_st32(&cmd->d_cmddep, sc->sc_idbdma->d_paddr);

	dbdma_start(sc->sc_idma, sc->sc_idbdma);

	return 0;
}

/* rate = fs = LRCLK
 * SCLK = 64*LRCLK (I2S)
 * MCLK = 256fs (typ. -- changeable)
 * MCLK = clksrc / mdiv
 *  SCLK = MCLK / sdiv
 * rate = SCLK / 64    ( = LRCLK = fs)
 */
int
i2s_set_rate(sc, rate)
	struct i2s_softc *sc;
	int rate;
{
	u_int reg = 0;
	int MCLK;
	int clksrc, mdiv, sdiv;
	int mclk_fs;
	int timo;

	/* sanify */
	if (rate > (48000 + 44100) / 2)
		rate = 48000;
	else
		rate = 44100;

	switch (rate) {
	case 44100:
		clksrc = 45158400;		/* 45MHz */
		reg = CLKSRC_45MHz;
		mclk_fs = 256;
		break;

	case 48000:
		clksrc = 49152000;		/* 49MHz */
		reg = CLKSRC_49MHz;
		mclk_fs = 256;
		break;

	default:
		return EINVAL;
	}

	MCLK = rate * mclk_fs;
	mdiv = clksrc / MCLK;			/* 4 */
	sdiv = mclk_fs / 64;			/* 4 */

	switch (mdiv) {
	case 1:
		reg |= MCLK_DIV1;
		break;
	case 3:
		reg |= MCLK_DIV3;
		break;
	case 5:
		reg |= MCLK_DIV5;
		break;
	default:
		reg |= ((mdiv / 2 - 1) << 24) & 0x1f000000;
		break;
	}

	switch (sdiv) {
	case 1:
		reg |= SCLK_DIV1;
		break;
	case 3:
		reg |= SCLK_DIV3;
		break;
	default:
		reg |= ((sdiv / 2 - 1) << 20) & 0x00f00000;
		break;
	}

	reg |= SCLK_MASTER;	/* XXX master mode */

	reg |= SERIAL_64x;

	if (sc->sc_rate == rate)
		return (0);

	/* stereo input and output */
	DPRINTF(("I2SSetDataWordSizeReg 0x%08x -> 0x%08x\n",
	    in32rb(sc->sc_reg + I2S_WORDSIZE), 0x02000200));
	out32rb(sc->sc_reg + I2S_WORDSIZE, 0x02000200);

	/* Clear CLKSTOPPEND */
	out32rb(sc->sc_reg + I2S_INT, I2S_INT_CLKSTOPPEND);

	macobio_disable(I2SClockOffset, I2S0CLKEN);

	/* Wait until clock is stopped */
	for (timo = 50; timo > 0; timo--) {
		if (in32rb(sc->sc_reg + I2S_INT) & I2S_INT_CLKSTOPPEND)
			goto done;
		delay(10);
	}

	printf("i2s_set_rate: timeout\n");

done:
	DPRINTF(("I2SSetSerialFormatReg 0x%x -> 0x%x\n",
	    in32rb(sc->sc_reg + I2S_FORMAT), reg));
	out32rb(sc->sc_reg + I2S_FORMAT, reg);

	macobio_enable(I2SClockOffset, I2S0CLKEN);

	sc->sc_rate = rate;

	return 0;
}

void
i2s_mute(u_int offset, int mute)
{
	if (offset == 0)
		return;

	DPRINTF(("gpio: %x, %d -> ", offset, macobio_read(offset) & GPIO_DATA));

	/* 0 means mute */
	if (mute == (macobio_read(offset) & GPIO_DATA))
		macobio_write(offset, !mute | GPIO_DDR_OUTPUT);

	DPRINTF(("%d\n", macobio_read(offset) & GPIO_DATA));
}

int
i2s_cint(void *v)
{
	struct i2s_softc *sc = v;
	u_int sense;

	sc->sc_output_mask = 0;
	i2s_mute(sc->sc_spkr, 1);
	i2s_mute(sc->sc_hp, 1);
	i2s_mute(sc->sc_line, 1);

	if (sc->sc_hp_detect)
		sense = macobio_read(sc->sc_hp_detect);
	else
		sense = !sc->sc_hp_active << 1;
	DPRINTF(("headphone detect = 0x%x\n", sense));

	if (((sense & 0x02) >> 1) == sc->sc_hp_active) {
		DPRINTF(("headphone is inserted\n"));
		sc->sc_output_mask |= I2S_SELECT_HEADPHONE;
		if (!sc->sc_mute)
			i2s_mute(sc->sc_hp, 0);
	} else {
		DPRINTF(("headphone is NOT inserted\n"));
	}

	if (sc->sc_line_detect)
		sense = macobio_read(sc->sc_line_detect);
	else
		sense = !sc->sc_line_active << 1;
	DPRINTF(("lineout detect = 0x%x\n", sense));

	if (((sense & 0x02) >> 1) == sc->sc_line_active) {
		DPRINTF(("lineout is inserted\n"));
		sc->sc_output_mask |= I2S_SELECT_LINEOUT;
		if (!sc->sc_mute)
			i2s_mute(sc->sc_line, 0);
	} else {
		DPRINTF(("lineout is NOT inserted\n"));
	}

	if (sc->sc_output_mask == 0) {
		sc->sc_output_mask |= I2S_SELECT_SPEAKER;
		if (!sc->sc_mute)
			i2s_mute(sc->sc_spkr, 0);
	}

	return 1;
}

u_int
i2s_gpio_offset(struct i2s_softc *sc, char *name, int *irq)
{
	u_int32_t reg[2];
	u_int32_t intr[2];
	int gpio;

	if (OF_getprop(sc->sc_node, name, &gpio,
            sizeof(gpio)) != sizeof(gpio) ||
	    OF_getprop(gpio, "reg", &reg[0],
	    sizeof(reg[0])) != sizeof(reg[0]) ||
	    OF_getprop(OF_parent(gpio), "reg", &reg[1],
	    sizeof(reg[1])) != sizeof(reg[1]))
		return (0);

	if (irq && OF_getprop(gpio, "interrupts",
	    intr, sizeof(intr)) == sizeof(intr)) {
		*irq = intr[0];
	}

	return (reg[0] + reg[1]);
}

void
i2s_gpio_init(struct i2s_softc *sc, int node, struct device *parent)
{
	int gpio;
	int hp_detect_intr = -1, line_detect_intr = -1;

	sc->sc_spkr = i2s_gpio_offset(sc, "platform-amp-mute", NULL);
	sc->sc_hp = i2s_gpio_offset(sc, "platform-headphone-mute", NULL);
	sc->sc_hp_detect = i2s_gpio_offset(sc, "platform-headphone-detect",
	    &hp_detect_intr);
	sc->sc_line = i2s_gpio_offset(sc, "platform-lineout-mute", NULL);
	sc->sc_line_detect = i2s_gpio_offset(sc, "platform-lineout-detect",
	    &line_detect_intr);
	sc->sc_hw_reset = i2s_gpio_offset(sc, "platform-hw-reset", NULL);

	gpio = OF_getnodebyname(OF_parent(node), "gpio");
	DPRINTF((" /gpio 0x%x\n", gpio));
	for (gpio = OF_child(gpio); gpio; gpio = OF_peer(gpio)) {
		char name[64], audio_gpio[64];
		int intr[2];
		uint32_t reg;

		reg = 0;
		bzero(name, sizeof name);
		bzero(audio_gpio, sizeof audio_gpio);
		OF_getprop(gpio, "name", name, sizeof name);
		OF_getprop(gpio, "audio-gpio", audio_gpio, sizeof audio_gpio);
		if (OF_getprop(gpio, "reg", &reg, sizeof(reg)) == -1)
			OF_getprop(gpio, "AAPL,address", &reg, sizeof(reg));

		if (reg > sc->sc_baseaddr)
			reg = (reg - sc->sc_baseaddr);

		/* gpio5 */
		if (sc->sc_hp == 0 && strcmp(audio_gpio, "headphone-mute") == 0)
			sc->sc_hp = reg;

		/* gpio6 */
		if (sc->sc_spkr == 0 && strcmp(audio_gpio, "amp-mute") == 0)
			sc->sc_spkr = reg;

		/* extint-gpio15 */
		if (sc->sc_hp_detect == 0 &&
		    strcmp(audio_gpio, "headphone-detect") == 0) {
			sc->sc_hp_detect = reg;
			OF_getprop(gpio, "audio-gpio-active-state",
			    &sc->sc_hp_active, 4);
			OF_getprop(gpio, "interrupts", intr, 8);
			hp_detect_intr = intr[0];
		}

		/* gpio11 (keywest-11) */
		if (sc->sc_hw_reset == 0 &&
		    strcmp(audio_gpio, "audio-hw-reset") == 0)
			sc->sc_hw_reset = reg;
	}
	DPRINTF((" amp-mute 0x%x\n", sc->sc_spkr));
	DPRINTF((" headphone-mute 0x%x\n", sc->sc_hp));
	DPRINTF((" headphone-detect 0x%x\n", sc->sc_hp_detect));
	DPRINTF((" headphone-detect active %x\n", sc->sc_hp_active));
	DPRINTF((" headphone-detect intr %x\n", hp_detect_intr));
	DPRINTF((" lineout-mute 0x%x\n", sc->sc_line));
	DPRINTF((" lineout-detect 0x%x\n", sc->sc_line_detect));
	DPRINTF((" lineout-detect active 0x%x\n", sc->sc_line_active));
	DPRINTF((" lineout-detect intr 0x%x\n", line_detect_intr));
	DPRINTF((" audio-hw-reset 0x%x\n", sc->sc_hw_reset));

	if (hp_detect_intr != -1)
		mac_intr_establish(parent, hp_detect_intr, IST_EDGE,
		    IPL_AUDIO | IPL_MPSAFE, i2s_cint, sc, sc->sc_dev.dv_xname);

	if (line_detect_intr != -1)
		mac_intr_establish(parent, line_detect_intr, IST_EDGE,
		    IPL_AUDIO | IPL_MPSAFE, i2s_cint, sc, sc->sc_dev.dv_xname);

	/* Enable headphone interrupt? */
	macobio_write(sc->sc_hp_detect, 0x80);

	/* Update headphone status. */
	i2s_cint(sc);
}

void *
i2s_allocm(void *h, int dir, size_t size, int type, int flags)
{
	struct i2s_softc *sc = h;
	struct i2s_dma *p;
	int error;

	if (size > I2S_DMALIST_MAX * I2S_DMASEG_MAX)
		return (NULL);

	p = malloc(sizeof(*p), type, flags | M_ZERO);
	if (!p)
		return (NULL);

	/* convert to the bus.h style, not used otherwise */
	if (flags & M_NOWAIT)
		flags = BUS_DMA_NOWAIT;

	p->size = size;
	if ((error = bus_dmamem_alloc(sc->sc_dmat, p->size, NBPG, 0, p->segs,
	    1, &p->nsegs, flags)) != 0) {
		printf("%s: unable to allocate dma, error = %d\n",
		    sc->sc_dev.dv_xname, error);
		free(p, type, 0);
		return NULL;
	}

	if ((error = bus_dmamem_map(sc->sc_dmat, p->segs, p->nsegs, p->size,
	    &p->addr, flags | BUS_DMA_COHERENT)) != 0) {
		printf("%s: unable to map dma, error = %d\n",
		    sc->sc_dev.dv_xname, error);
		bus_dmamem_free(sc->sc_dmat, p->segs, p->nsegs);
		free(p, type, 0);
		return NULL;
	}

	if ((error = bus_dmamap_create(sc->sc_dmat, p->size, 1,
	    p->size, 0, flags, &p->map)) != 0) {
		printf("%s: unable to create dma map, error = %d\n",
		    sc->sc_dev.dv_xname, error);
		bus_dmamem_unmap(sc->sc_dmat, p->addr, size);
		bus_dmamem_free(sc->sc_dmat, p->segs, p->nsegs);
		free(p, type, 0);
		return NULL;
	}

	if ((error = bus_dmamap_load(sc->sc_dmat, p->map, p->addr, p->size,
	    NULL, flags)) != 0) {
		printf("%s: unable to load dma map, error = %d\n",
		    sc->sc_dev.dv_xname, error);
		bus_dmamap_destroy(sc->sc_dmat, p->map);
		bus_dmamem_unmap(sc->sc_dmat, p->addr, size);
		bus_dmamem_free(sc->sc_dmat, p->segs, p->nsegs);
		free(p, type, 0);
		return NULL;
	}

	p->next = sc->sc_dmas;
	sc->sc_dmas = p;

	return p->addr;
}

#define reset_active 0

int
deq_reset(struct i2s_softc *sc)
{
	if (sc->sc_hw_reset == 0)
		return (-1);

	macobio_write(sc->sc_hw_reset, !reset_active | GPIO_DDR_OUTPUT);
	delay(1000000);

	macobio_write(sc->sc_hw_reset, reset_active | GPIO_DDR_OUTPUT);
	delay(1);

	macobio_write(sc->sc_hw_reset, !reset_active | GPIO_DDR_OUTPUT);
	delay(10000);

	return (0);
}


code:
/* $OpenBSD: i2sreg.h,v 1.3 2011/06/07 16:29:51 mpi Exp $ */
/*-
 * Copyright (c) 2002 Tsubai Masanari.  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.
 * 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.
 */

/* I2S registers */
#define I2S_INT		0x00
#define I2S_FORMAT	0x10
#define I2S_FRAMECOUNT	0x40
#define I2S_FRAMEMATCH	0x50
#define I2S_WORDSIZE	0x60

/* I2S_INT register definitions */
#define I2SClockOffset		0x3c
#define I2S_INT_CLKSTOPPEND	0x01000000

#define I2S_SELECT_SPEAKER	1 << 0
#define I2S_SELECT_HEADPHONE	1 << 1
#define I2S_SELECT_LINEOUT	1 << 2

/* FCR(0x3c) bits */
#define I2S0CLKEN	0x1000
#define I2S0EN		0x2000
#define I2S1CLKEN	0x080000
#define I2S1EN		0x100000

#define CLKSRC_49MHz	0x80000000	/* Use 49152000Hz Osc. */
#define CLKSRC_45MHz	0x40000000	/* Use 45158400Hz Osc. */
#define CLKSRC_18MHz	0x00000000	/* Use 18432000Hz Osc. */
#define CLKSRC_VS	0x01fa0000	/* Magic value of xserve vu-meter */
#define MCLK_DIV	0x1f000000	/* MCLK = SRC / DIV */
#define  MCLK_DIV1	0x14000000	/*  MCLK = SRC */
#define  MCLK_DIV3	0x13000000	/*  MCLK = SRC / 3 */
#define  MCLK_DIV5	0x12000000	/*  MCLK = SRC / 5 */
#define SCLK_DIV	0x00f00000	/* SCLK = MCLK / DIV */
#define  SCLK_DIV1	0x00800000
#define  SCLK_DIV3	0x00900000
#define SCLK_MASTER	0x00080000	/* Master mode */
#define SCLK_SLAVE	0x00000000	/* Slave mode */
#define SERIAL_FORMAT	0x00070000
#define  SERIAL_SONY	0x00000000
#define  SERIAL_64x	0x00010000
#define  SERIAL_32x	0x00020000
#define  SERIAL_DAV	0x00040000
#define  SERIAL_SILICON	0x00050000