code:
/*	$OpenBSD: audio.c,v 1.138 2015/07/29 21:13:32 ratchov Exp $	*/
/*
 * Copyright (c) 2015 Alexandre Ratchov <alex@caoua.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/fcntl.h>
#include <sys/systm.h>
#include <sys/ioctl.h>
#include <sys/conf.h>
#include <sys/poll.h>
#include <sys/kernel.h>
#include <sys/task.h>
#include <sys/vnode.h>
#include <sys/malloc.h>
#include <sys/device.h>
#include <sys/audioio.h>
#include <dev/audio_if.h>
#include <dev/mulaw.h>
#include "audio.h"
#include "wskbd.h"

#ifdef AUDIO_DEBUG
#define DPRINTF(...)				\
	do {					\
		if (audio_debug)		\
			printf(__VA_ARGS__);	\
	} while(0)
#define DPRINTFN(n, ...)			\
	do {					\
		if (audio_debug > (n))		\
			printf(__VA_ARGS__);	\
	} while(0)
#else
#define DPRINTF(...) do {} while(0)
#define DPRINTFN(n, ...) do {} while(0)
#endif

#define DEVNAME(sc)		((sc)->dev.dv_xname)
#define AUDIO_UNIT(n)		(minor(n) & 0x0f)
#define AUDIO_DEV(n)		(minor(n) & 0xf0)
#define AUDIO_DEV_SOUND		0	/* minor of /dev/sound0 */
#define AUDIO_DEV_MIXER		0x10	/* minor of /dev/mixer0 */
#define AUDIO_DEV_AUDIO		0x80	/* minor of /dev/audio0 */
#define AUDIO_DEV_AUDIOCTL	0xc0	/* minor of /dev/audioctl */
#define AUDIO_BUFSZ		65536	/* buffer size in bytes */

/*
 * dma buffer
 */
struct audio_buf {
	unsigned char *data;		/* DMA memory block */
	size_t datalen;			/* size of DMA memory block */
	size_t len;			/* size of DMA FIFO */
	size_t start;			/* first byte used in the FIFO */
	size_t used;			/* bytes used in the FIFO */
	size_t blksz;			/* DMA block size */
	struct selinfo sel;		/* to record & wakeup poll(2) */
	unsigned int pos;		/* bytes transferred */
	unsigned int xrun;		/* bytes lost by xruns */
	int blocking;			/* read/write blocking */
};

#if NWSKBD > 0
struct wskbd_vol
{
	int val;			/* index of the value control */
	int mute;			/* index of the mute control */
	int step;			/* increment/decrement step */
	int nch;			/* channels in the value control */
	int val_pending;		/* pending change of val */
	int mute_pending;		/* pending mute toggles */
};
#endif

/*
 * device structure
 */
struct audio_softc {
	struct device dev;
	struct audio_hw_if *ops;	/* driver funcs */
	void *arg;			/* first arg to driver funcs */
	int mode;			/* bitmask of AUMODE_* */
	int quiesce;			/* device suspended */
	struct audio_buf play, rec;
	unsigned int sw_enc;		/* user exposed AUDIO_ENCODING_* */
	unsigned int hw_enc;		/* harware AUDIO_ENCODING_* */
	unsigned int bits;		/* bits per sample */
	unsigned int bps;		/* bytes-per-sample */
	unsigned int msb;		/* sample are MSB aligned */
	unsigned int rate;		/* rate in Hz */
	unsigned int round;		/* block size in frames */
	unsigned int nblks;		/* number of play blocks */
	unsigned int pchan, rchan;	/* number of channels */
	unsigned char silence[4];	/* a sample of silence */
	int pause;			/* not trying to start DMA */
	int active;			/* DMA in process */
	int offs;			/* offset between play & rec dir */
	void (*conv_enc)(unsigned char *, int);	/* encode to native */
	void (*conv_dec)(unsigned char *, int);	/* decode to user */
#if NWSKBD > 0
	struct wskbd_vol spkr, mic;
	struct task wskbd_task;
	int wskbd_taskset;
#endif
};

int audio_match(struct device *, void *, void *);
void audio_attach(struct device *, struct device *, void *);
int audio_activate(struct device *, int);
int audio_detach(struct device *, int);
void audio_pintr(void *);
void audio_rintr(void *);
#if NWSKBD > 0
void wskbd_mixer_init(struct audio_softc *);
#endif

const struct cfattach audio_ca = {
	sizeof(struct audio_softc), audio_match, audio_attach,
	audio_detach, audio_activate
};

struct cfdriver audio_cd = {
	NULL, "audio", DV_DULL
};

/*
 * This mutex protects data structures (including registers on the
 * sound-card) that are manipulated by both the interrupt handler and
 * syscall code-paths.
 *
 * Note that driver methods may sleep (e.g. in malloc); consequently the
 * audio layer calls them with the mutex unlocked. Driver methods are
 * responsible for locking the mutex when they manipulate data used by
 * the interrupt handler and interrupts may occur.
 *
 * Similarly, the driver is responsible for locking the mutex in its
 * interrupt handler and to call the audio layer call-backs (i.e.
 * audio_{p,r}int()) with the mutex locked.
 */
struct mutex audio_lock = MUTEX_INITIALIZER(IPL_AUDIO);

#ifdef AUDIO_DEBUG
/*
 * 0 - nothing, as if AUDIO_DEBUG isn't defined
 * 1 - initialisations & setup
 * 2 - blocks & interrupts
 */
int audio_debug = 1;
#endif

unsigned int
audio_gcd(unsigned int a, unsigned int b)
{
	unsigned int r;

	while (b > 0) {
		r = a % b;
		a = b;
		b = r;
	}
	return a;
}

int
audio_buf_init(struct audio_softc *sc, struct audio_buf *buf, int dir)
{
	if (sc->ops->round_buffersize) {
		buf->datalen = sc->ops->round_buffersize(sc->arg,
		    dir, AUDIO_BUFSZ);
	} else
		buf->datalen = AUDIO_BUFSZ;
	if (sc->ops->allocm) {
		buf->data = sc->ops->allocm(sc->arg, dir, buf->datalen,
		    M_DEVBUF, M_WAITOK);
	} else
		buf->data = malloc(buf->datalen, M_DEVBUF, M_WAITOK);
	if (buf->data == NULL)
		return ENOMEM;
	return 0;
}

void
audio_buf_done(struct audio_softc *sc, struct audio_buf *buf)
{
	if (sc->ops->freem)
		sc->ops->freem(sc->arg, buf->data, M_DEVBUF);
	else
		free(buf->data, M_DEVBUF, buf->datalen);
}

/*
 * return the reader pointer and the number of bytes available
 */
unsigned char *
audio_buf_rgetblk(struct audio_buf *buf, size_t *rsize)
{
	size_t count;

	count = buf->len - buf->start;
	if (count > buf->used)
		count = buf->used;
	*rsize = count;
	return buf->data + buf->start;
}

/*
 * discard "count" bytes at the start postion.
 */
void
audio_buf_rdiscard(struct audio_buf *buf, size_t count)
{
#ifdef AUDIO_DEBUG
	if (count > buf->used) {
		panic("audio_buf_rdiscard: bad count = %zu, "
		    "start = %zu, used = %zu\n", count, buf->start, buf->used);
	}
#endif
	buf->used -= count;
	buf->start += count;
	if (buf->start >= buf->len)
		buf->start -= buf->len;
}

/*
 * advance the writer pointer by "count" bytes
 */
void
audio_buf_wcommit(struct audio_buf *buf, size_t count)
{
#ifdef AUDIO_DEBUG
	if (count > (buf->len - buf->used)) {
		panic("audio_buf_wcommit: bad count = %zu, "
		    "start = %zu, used = %zu\n", count, buf->start, buf->used);
	}
#endif
	buf->used += count;
}

/*
 * get writer pointer and the number of bytes writable
 */
unsigned char *
audio_buf_wgetblk(struct audio_buf *buf, size_t *rsize)
{
	size_t end, avail, count;

	end = buf->start + buf->used;
	if (end >= buf->len)
		end -= buf->len;
	avail = buf->len - buf->used;
	count = buf->len - end;
	if (count > avail)
		count = avail;
	*rsize = count;
	return buf->data + end;
}

void
audio_calc_sil(struct audio_softc *sc)
{
	unsigned char *q;
	unsigned int s, i;
	int d, e;

	e = sc->sw_enc;
#ifdef AUDIO_DEBUG
	switch (e) {
	case AUDIO_ENCODING_SLINEAR_LE:
	case AUDIO_ENCODING_ULINEAR_LE:
	case AUDIO_ENCODING_SLINEAR_BE:
	case AUDIO_ENCODING_ULINEAR_BE:
		break;
	default:
		printf("%s: unhandled play encoding %d\n", DEVNAME(sc), e);
		memset(sc->silence, 0, sc->bps);
		return;
	}
#endif
	if (e == AUDIO_ENCODING_SLINEAR_BE || e == AUDIO_ENCODING_ULINEAR_BE) {
		d = -1;
		q = sc->silence + sc->bps - 1;
	} else {
		d = 1;
		q = sc->silence;
	}
	if (e == AUDIO_ENCODING_SLINEAR_LE || e == AUDIO_ENCODING_SLINEAR_BE) {
		s = 0;
	} else {
		s = 0x80000000;
		if (sc->msb)
			s >>= 32 - 8 * sc->bps;
		else
			s >>= 32 - sc->bits;
	}
	for (i = 0; i < sc->bps; i++) {
		*q = s;
		q += d;
		s >>= 8;
	}
	if (sc->conv_enc)
		sc->conv_enc(sc->silence, sc->bps);
}

void
audio_fill_sil(struct audio_softc *sc, unsigned char *ptr, size_t count)
{
	unsigned char *q, *p;
	size_t i, j;

	q = ptr;
	for (j = count / sc->bps; j > 0; j--) {
		p = sc->silence;
		for (i = sc->bps; i > 0; i--)
			*q++ = *p++;
	}
}

void
audio_clear(struct audio_softc *sc)
{
	if (sc->mode & AUMODE_PLAY) {
		sc->play.used = sc->play.start = 0;
		sc->play.pos = sc->play.xrun = 0;
		audio_fill_sil(sc, sc->play.data, sc->play.len);
	}
	if (sc->mode & AUMODE_RECORD) {
		sc->rec.used = sc->rec.start = 0;
		sc->rec.pos = sc->rec.xrun = 0;
		audio_fill_sil(sc, sc->rec.data, sc->rec.len);
	}
}

/*
 * called whenever a block is consumed by the driver
 */
void
audio_pintr(void *addr)
{
	struct audio_softc *sc = addr;
	unsigned char *ptr;
	size_t count;
	int error, nblk, todo;

	MUTEX_ASSERT_LOCKED(&audio_lock);
	if (!(sc->mode & AUMODE_PLAY) || !sc->active) {
		printf("%s: play interrupt but not playing\n", DEVNAME(sc));
		return;
	}
	if (sc->quiesce) {
		DPRINTF("%s: quesced, skipping play intr\n", DEVNAME(sc));
		return;
	}

	/*
	 * check if record pointer wrapped, see explanation
	 * in audio_rintr()
	 */
	if (sc->mode & AUMODE_RECORD) {
		sc->offs--;
		nblk = sc->rec.len / sc->rec.blksz;
		todo = -sc->offs;
		if (todo >= nblk) {
			todo -= todo % nblk;
			DPRINTFN(1, "%s: rec ptr wrapped, moving %d blocks\n",
			    DEVNAME(sc), todo);
			while (todo-- > 0)
				audio_rintr(sc);
		}
	}

	sc->play.pos += sc->play.blksz;
	audio_fill_sil(sc, sc->play.data + sc->play.start, sc->play.blksz);
	audio_buf_rdiscard(&sc->play, sc->play.blksz);
	if (sc->play.used < sc->play.blksz) {
		DPRINTFN(1, "%s: play underrun\n", DEVNAME(sc));
		sc->play.xrun += sc->play.blksz;
		audio_buf_wcommit(&sc->play, sc->play.blksz);
	}

	DPRINTFN(1, "%s: play intr, used -> %zu, start -> %zu\n",
	    DEVNAME(sc), sc->play.used, sc->play.start);

	if (!sc->ops->trigger_output) {
		ptr = audio_buf_rgetblk(&sc->play, &count);
		error = sc->ops->start_output(sc->arg,
		    ptr, sc->play.blksz, audio_pintr, (void *)sc);
		if (error) {
			printf("%s: play restart failed: %d\n",
			    DEVNAME(sc), error);
		}
	}

	if (sc->play.used < sc->play.len) {
		DPRINTFN(1, "%s: play wakeup, chan = %d\n",
		    DEVNAME(sc), sc->play.blocking);
		if (sc->play.blocking) {
			wakeup(&sc->play.blocking);
			sc->play.blocking = 0;
		}
		selwakeup(&sc->play.sel);
	}
}

/*
 * called whenever a block is produced by the driver
 */
void
audio_rintr(void *addr)
{
	struct audio_softc *sc = addr;
	unsigned char *ptr;
	size_t count;
	int error, nblk, todo;

	MUTEX_ASSERT_LOCKED(&audio_lock);
	if (!(sc->mode & AUMODE_RECORD) || !sc->active) {
		printf("%s: rec interrupt but not recording\n", DEVNAME(sc));
		return;
	}
	if (sc->quiesce) {
		DPRINTF("%s: quesced, skipping rec intr\n", DEVNAME(sc));
		return;
	}

	/*
	 * Interrupts may be masked by other sub-systems during 320ms
	 * and more. During such a delay the hardware doesn't stop
	 * playing and the play buffer pointers may wrap, this can't be
	 * detected and corrected by low level drivers. This makes the
	 * record stream ahead of the play stream; this is detected as a
	 * hardware anomaly by userland and cause programs to misbehave.
	 *
	 * We fix this by advancing play position by an integer count of
	 * full buffers, so it reaches the record position.
	 */
	if (sc->mode & AUMODE_PLAY) {
		sc->offs++;
		nblk = sc->play.len / sc->play.blksz;
		todo = sc->offs;
		if (todo >= nblk) {
			todo -= todo % nblk;
			DPRINTFN(1, "%s: play ptr wrapped, moving %d blocks\n",
			    DEVNAME(sc), todo);
			while (todo-- > 0)
				audio_pintr(sc);
		}
	}

	sc->rec.pos += sc->rec.blksz;
	audio_buf_wcommit(&sc->rec, sc->rec.blksz);
	if (sc->rec.used == sc->rec.len) {
		DPRINTFN(1, "%s: rec overrun\n", DEVNAME(sc));
		sc->rec.xrun += sc->rec.blksz;
		audio_buf_rdiscard(&sc->rec, sc->rec.blksz);
	}
	DPRINTFN(1, "%s: rec intr, used -> %zu\n", DEVNAME(sc), sc->rec.used);

	if (!sc->ops->trigger_input) {
		ptr = audio_buf_wgetblk(&sc->rec, &count);
		error = sc->ops->start_input(sc->arg,
		    ptr, sc->rec.blksz, audio_rintr, (void *)sc);
		if (error) {
			printf("%s: rec restart failed: %d\n",
			    DEVNAME(sc), error);
		}
	}

	if (sc->rec.used > 0) {
		DPRINTFN(1, "%s: rec wakeup, chan = %d\n",
		    DEVNAME(sc), sc->rec.blocking);
		if (sc->rec.blocking) {
			wakeup(&sc->rec.blocking);
			sc->rec.blocking = 0;
		}
		selwakeup(&sc->rec.sel);
	}
}

int
audio_start_do(struct audio_softc *sc)
{
	int error;
	struct audio_params p;
	unsigned char *ptr;
	size_t count;

	DPRINTFN(1, "%s: start play: "
	    "start = %zu, used = %zu, "
	    "len = %zu, blksz = %zu\n",
	    DEVNAME(sc), sc->play.start, sc->play.used,
	    sc->play.len, sc->play.blksz);
	DPRINTFN(1, "%s: start rec: "
	    "start = %zu, used = %zu, "
	    "len = %zu, blksz = %zu\n",
	    DEVNAME(sc), sc->rec.start, sc->rec.used,
	    sc->rec.len, sc->rec.blksz);

	error = 0;
	sc->offs = 0;
	if (sc->mode & AUMODE_PLAY) {
		if (sc->ops->trigger_output) {
			p.encoding = sc->hw_enc;
			p.precision = sc->bits;
			p.bps = sc->bps;
			p.msb = sc->msb;
			p.sample_rate = sc->rate;
			p.channels = sc->pchan;
			error = sc->ops->trigger_output(sc->arg,
			    sc->play.data,
			    sc->play.data + sc->play.len,
			    sc->play.blksz,
			    audio_pintr, (void *)sc, &p);
		} else {
			mtx_enter(&audio_lock);
			ptr = audio_buf_rgetblk(&sc->play, &count);
			error = sc->ops->start_output(sc->arg,
			    ptr, sc->play.blksz, audio_pintr, (void *)sc);
			mtx_leave(&audio_lock);
		}
		if (error)
			printf("%s: failed to start playback\n", DEVNAME(sc));
	}
	if (sc->mode & AUMODE_RECORD) {
		if (sc->ops->trigger_input) {
			p.encoding = sc->hw_enc;
			p.precision = sc->bits;
			p.bps = sc->bps;
			p.msb = sc->msb;
			p.sample_rate = sc->rate;
			p.channels = sc->rchan;
			error = sc->ops->trigger_input(sc->arg,
			    sc->rec.data,
			    sc->rec.data + sc->rec.len,
			    sc->rec.blksz,
			    audio_rintr, (void *)sc, &p);
		} else {
			mtx_enter(&audio_lock);
			ptr = audio_buf_wgetblk(&sc->rec, &count);
			error = sc->ops->start_input(sc->arg,
			    ptr, sc->rec.blksz, audio_rintr, (void *)sc);
			mtx_leave(&audio_lock);
		}
		if (error)
			printf("%s: failed to start recording\n", DEVNAME(sc));
	}
	return error;
}

int
audio_stop_do(struct audio_softc *sc)
{
	if (sc->mode & AUMODE_PLAY)
		sc->ops->halt_output(sc->arg);
	if (sc->mode & AUMODE_RECORD)
		sc->ops->halt_input(sc->arg);
	return 0;
}

int
audio_start(struct audio_softc *sc)
{
	sc->active = 1;
	sc->play.xrun = sc->play.pos = sc->rec.xrun = sc->rec.pos = 0;
	return audio_start_do(sc);
}

int
audio_stop(struct audio_softc *sc)
{
	int error;

	error = audio_stop_do(sc);
	if (error)
		return error;
	audio_clear(sc);
	sc->active = 0;
	return 0;
}

int
audio_setpar(struct audio_softc *sc)
{
	struct audio_params p, r;
	unsigned int nr, np, max, min, mult;
	int error;

	DPRINTF("%s: setpar: req enc=%d bits=%d, bps=%d, msb=%d "
	    "rate=%d, pchan=%d, rchan=%d, round=%u, nblks=%d\n",
	    DEVNAME(sc), sc->sw_enc, sc->bits, sc->bps, sc->msb,
	    sc->rate, sc->pchan, sc->rchan, sc->round, sc->nblks);

	/*
	 * AUDIO_ENCODING_SLINEAR and AUDIO_ENCODING_ULINEAR are not
	 * used anymore, promote them to the _LE and _BE equivalents
	 */
	if (sc->sw_enc == AUDIO_ENCODING_SLINEAR) {
#if BYTE_ORDER == LITTLE_ENDIAN
		sc->sw_enc = AUDIO_ENCODING_SLINEAR_LE;
#else
		sc->sw_enc = AUDIO_ENCODING_SLINEAR_BE;
#endif
	}
	if (sc->sw_enc == AUDIO_ENCODING_ULINEAR) {
#if BYTE_ORDER == LITTLE_ENDIAN
		sc->sw_enc = AUDIO_ENCODING_ULINEAR_LE;
#else
		sc->sw_enc = AUDIO_ENCODING_ULINEAR_BE;
#endif
	}

	/*
	 * check if requested parameters are in the allowed ranges
	 */
	if (sc->mode & AUMODE_PLAY) {
		if (sc->pchan < 1)
			sc->pchan = 1;
		if (sc->pchan > 64)
			sc->pchan = 64;
	}
	if (sc->mode & AUMODE_RECORD) {
		if (sc->rchan < 1)
			sc->rchan = 1;
		if (sc->rchan > 64)
			sc->rchan = 64;
	}
	switch (sc->sw_enc) {
	case AUDIO_ENCODING_ULAW:
	case AUDIO_ENCODING_ALAW:
	case AUDIO_ENCODING_SLINEAR_LE:
	case AUDIO_ENCODING_SLINEAR_BE:
	case AUDIO_ENCODING_ULINEAR_LE:
	case AUDIO_ENCODING_ULINEAR_BE:
		break;
	default:
		sc->sw_enc = AUDIO_ENCODING_SLINEAR_LE;
	}
	if (sc->bits < 8)
		sc->bits = 8;
	if (sc->bits > 32)
		sc->bits = 32;
	if (sc->bps < 1)
		sc->bps = 1;
	if (sc->bps > 4)
		sc->bps = 4;
	if (sc->rate < 4000)
		sc->rate = 4000;
	if (sc->rate > 192000)
		sc->rate = 192000;

	/*
	 * copy into struct audio_params, required by drivers
	 */
	p.encoding = r.encoding = sc->sw_enc;
	p.precision = r.precision = sc->bits;
	p.bps = r.bps = sc->bps;
	p.msb = r.msb = sc->msb;
	p.sample_rate = r.sample_rate = sc->rate;
	p.channels = sc->pchan;
	r.channels = sc->rchan;

	/*
	 * set parameters
	 */
	error = sc->ops->set_params(sc->arg, sc->mode, sc->mode, &p, &r);
	if (error)
		return error;
	if (sc->mode == (AUMODE_PLAY | AUMODE_RECORD)) {
		if (p.encoding != r.encoding ||
		    p.precision != r.precision ||
		    p.bps != r.bps ||
		    p.msb != r.msb ||
		    p.sample_rate != r.sample_rate) {
			printf("%s: different play and record parameters "
			    "returned by hardware\n", DEVNAME(sc));
			return ENODEV;
		}
	}
	if (sc->mode & AUMODE_PLAY) {
		sc->hw_enc = p.encoding;
		sc->bits = p.precision;
		sc->bps = p.bps;
		sc->msb = p.msb;
		sc->rate = p.sample_rate;
		sc->pchan = p.channels;
	}
	if (sc->mode & AUMODE_RECORD) {
		sc->hw_enc = r.encoding;
		sc->bits = r.precision;
		sc->bps = r.bps;
		sc->msb = r.msb;
		sc->rate = r.sample_rate;
		sc->rchan = r.channels;
	}
	if (sc->rate == 0 || sc->bps == 0 || sc->bits == 0) {
		printf("%s: invalid parameters returned by hardware\n",
		    DEVNAME(sc));
		return ENODEV;
	}
	if (sc->ops->commit_settings) {
		error = sc->ops->commit_settings(sc->arg);
		if (error)
			return error;
	}

	/*
	 * conversion from/to exotic/dead encoding, for drivers not supporting
	 * linear
	 */
	switch (sc->hw_enc) {
	case AUDIO_ENCODING_SLINEAR_LE:
	case AUDIO_ENCODING_SLINEAR_BE:
	case AUDIO_ENCODING_ULINEAR_LE:
	case AUDIO_ENCODING_ULINEAR_BE:
		sc->sw_enc = sc->hw_enc;
		sc->conv_dec = sc->conv_enc = NULL;
		break;
	case AUDIO_ENCODING_ULAW:
#if BYTE_ORDER == LITTLE_ENDIAN
		sc->sw_enc = AUDIO_ENCODING_SLINEAR_LE;
#else
		sc->sw_enc = AUDIO_ENCODING_SLINEAR_BE;
#endif
		if (sc->bits == 8) {
			sc->conv_enc = slinear8_to_mulaw;
			sc->conv_dec = mulaw_to_slinear8;
			break;
		} else if (sc->bits == 24) {
			sc->conv_enc = slinear24_to_mulaw24;
			sc->conv_dec = mulaw24_to_slinear24;
			break;
		}
		sc->sw_enc = sc->hw_enc;
		sc->conv_dec = sc->conv_enc = NULL;
		break;
	default:
		printf("%s: setpar: enc = %d, bits = %d: emulation skipped\n",
		    DEVNAME(sc), sc->hw_enc, sc->bits);
		sc->sw_enc = sc->hw_enc;
		sc->conv_dec = sc->conv_enc = NULL;
	}
	audio_calc_sil(sc);

	/*
	 * get least multiplier of the number of frames per block
	 */
	if (sc->ops->round_blocksize) {
		mult = sc->ops->round_blocksize(sc->arg, 1);
		if (mult == 0) {
			printf("%s: 0x%x: bad block size multiplier\n",
			    DEVNAME(sc), mult);
			return ENODEV;
		}
	} else
		mult = 1;
	DPRINTF("%s: hw block size multiplier: %u\n", DEVNAME(sc), mult);
	if (sc->mode & AUMODE_PLAY) {
		np = mult / audio_gcd(sc->pchan * sc->bps, mult);
		if (!(sc->mode & AUMODE_RECORD))
			nr = np;
		DPRINTF("%s: play number of frames multiplier: %u\n",
		    DEVNAME(sc), np);
	}
	if (sc->mode & AUMODE_RECORD) {
		nr = mult / audio_gcd(sc->rchan * sc->bps, mult);
		if (!(sc->mode & AUMODE_PLAY))
			np = nr;
		DPRINTF("%s: record number of frames multiplier: %u\n",
		    DEVNAME(sc), nr);
	}
	mult = nr * np / audio_gcd(nr, np);
	DPRINTF("%s: least common number of frames multiplier: %u\n",
	    DEVNAME(sc), mult);

	/*
	 * get minumum and maximum frames per block
	 */
	if (sc->mode & AUMODE_PLAY) {
		np = sc->play.datalen / (sc->pchan * sc->bps * 2);
		if (!(sc->mode & AUMODE_RECORD))
			nr = np;
	}
	if (sc->mode & AUMODE_RECORD) {
		nr = sc->rec.datalen / (sc->rchan * sc->bps * 2);
		if (!(sc->mode & AUMODE_PLAY))
			np = nr;
	}
	max = np < nr ? np : nr;
	max -= max % mult;
	min = sc->rate / 1000 + mult - 1;
	min -= min % mult;
	DPRINTF("%s: frame number range: %u..%u\n", DEVNAME(sc), min, max);
	if (max < min) {
		printf("%s: %u: bad max frame number\n", DEVNAME(sc), max);
		return EIO;
	}

	/*
	 * adjust the frame per block to match our constraints
	 */
	sc->round += mult / 2;
	sc->round -= sc->round % mult;
	if (sc->round > max)
		sc->round = max;
	if (sc->round < min)
		sc->round = min;
	sc->round = sc->round;

	/*
	 * set buffer size (number of blocks)
	 */
	if (sc->mode & AUMODE_PLAY) {
		sc->play.blksz = sc->round * sc->pchan * sc->bps;
		max = sc->play.datalen / sc->play.blksz;
		if (sc->nblks > max)
			sc->nblks = max;
		if (sc->nblks < 2)
			sc->nblks = 2;
		sc->play.len = sc->nblks * sc->play.blksz;
		sc->nblks = sc->nblks;
	}
	if (sc->mode & AUMODE_RECORD) {
		/*
		 * for recording, buffer size is not the latency (it's
		 * exactly one block), so let's get the maximum buffer
		 * size of maximum reliability during xruns
		 */
		sc->rec.blksz = sc->round * sc->rchan * sc->bps;
		sc->rec.len = sc->rec.datalen;
		sc->rec.len -= sc->rec.datalen % sc->rec.blksz;
	}

	DPRINTF("%s: setpar: new enc=%d bits=%d, bps=%d, msb=%d "
	    "rate=%d, pchan=%d, rchan=%d, round=%u, nblks=%d\n",
	    DEVNAME(sc), sc->sw_enc, sc->bits, sc->bps, sc->msb,
	    sc->rate, sc->pchan, sc->rchan, sc->round, sc->nblks);
	return 0;
}

int
audio_setinfo(struct audio_softc *sc, struct audio_info *ai)
{
	struct audio_prinfo *r = &ai->record, *p = &ai->play;
	int error;
	int set;

	/*
	 * stop the device if requested to stop
	 */
	if (sc->mode != 0) {
		if (sc->mode & AUMODE_PLAY) {
			if (p->pause != (unsigned char)~0)
				sc->pause = p->pause;
		}
		if (sc->mode & AUMODE_RECORD) {
			if (r->pause != (unsigned char)~0)
				sc->pause = r->pause;
		}
		if (sc->pause) {
			if (sc->active)
				audio_stop(sc);
		}
	}

	/*
	 * copy parameters into the softc structure
	 */
	set = 0;
	if (ai->play.encoding != ~0) {
		sc->sw_enc = ai->play.encoding;
		set = 1;
	}
	if (ai->play.precision != ~0) {
		sc->bits = ai->play.precision;
		set = 1;
	}
	if (ai->play.bps != ~0) {
		sc->bps = ai->play.bps;
		set = 1;
	}
	if (ai->play.msb != ~0) {
		sc->msb = ai->play.msb;
		set = 1;
	}
	if (ai->play.sample_rate != ~0) {
		sc->rate = ai->play.sample_rate;
		set = 1;
	}
	if (ai->play.channels != ~0) {
		sc->pchan = ai->play.channels;
		set = 1;
	}
	if (ai->play.block_size != ~0) {
		sc->round = ai->play.block_size /
		    (sc->bps * sc->pchan);
		set = 1;
	}
	if (ai->hiwat != ~0) {
		sc->nblks = ai->hiwat;
		set = 1;
	}
	if (ai->record.encoding != ~0) {
		sc->sw_enc = ai->record.encoding;
		set = 1;
	}
	if (ai->record.precision != ~0) {
		sc->bits = ai->record.precision;
		set = 1;
	}
	if (ai->record.bps != ~0) {
		sc->bps = ai->record.bps;
		set = 1;
	}
	if (ai->record.msb != ~0) {
		sc->msb = ai->record.msb;
		set = 1;
	}
	if (ai->record.sample_rate != ~0) {
		sc->rate = ai->record.sample_rate;
		set = 1;
	}
	if (ai->record.channels != ~0) {
		sc->rchan = ai->record.channels;
		set = 1;
	}
	if (ai->record.block_size != ~0) {
		sc->round = ai->record.block_size /
		    (sc->bps * sc->rchan);
		set = 1;
	}

	DPRINTF("%s: setinfo: set = %d, mode = %d, pause = %d\n",
	    DEVNAME(sc), set, sc->mode, sc->pause);

	/*
	 * if the device not opened, we're done, don't touch the hardware
	 */
	if (sc->mode == 0)
		return 0;

	/*
	 * change parameters and recalculate buffer sizes
	 */
	if (set) {
		if (sc->active) {
			DPRINTF("%s: can't change params during dma\n",
			    DEVNAME(sc));
			return EBUSY;
		}
		error = audio_setpar(sc);
		if (error)
			return error;
		audio_clear(sc);
		if ((sc->mode & AUMODE_PLAY) && sc->ops->init_output) {
			error = sc->ops->init_output(sc->arg,
			    sc->play.data, sc->play.len);
			if (error)
				return error;
		}
		if ((sc->mode & AUMODE_RECORD) && sc->ops->init_input) {
			error = sc->ops->init_input(sc->arg,
			    sc->rec.data, sc->rec.len);
			if (error)
				return error;
		}
	}

	/*
	 * if unpaused, start
	 */
	if (!sc->pause && !sc->active) {
		error = audio_start(sc);
		if (error)
			return error;
	}
	return 0;
}

int
audio_getinfo(struct audio_softc *sc, struct audio_info *ai)
{
	ai->play.sample_rate = ai->record.sample_rate = sc->rate;
	ai->play.encoding = ai->record.encoding = sc->sw_enc;
	ai->play.precision = ai->record.precision = sc->bits;
	ai->play.bps = ai->record.bps = sc->bps;
	ai->play.msb = ai->record.msb = sc->msb;
	ai->play.channels = sc->pchan;
	ai->record.channels = sc->rchan;

	/*
	 * XXX: this is used only to display counters through audioctl
	 * and the pos counters are more useful
	 */
	mtx_enter(&audio_lock);
	ai->play.samples = sc->play.pos - sc->play.xrun;
	ai->record.samples = sc->rec.pos - sc->rec.xrun;
	mtx_leave(&audio_lock);

	ai->play.pause = ai->record.pause = sc->pause;
	ai->play.active = ai->record.active = sc->active;

	ai->play.buffer_size = sc->play.datalen;
	ai->record.buffer_size = sc->rec.datalen;

	ai->play.block_size =  sc->round * sc->bps * sc->pchan;
	ai->record.block_size = sc->round * sc->bps * sc->rchan;

	ai->hiwat = sc->nblks;
	ai->lowat = sc->nblks;
	ai->mode = sc->mode;
	return 0;
}

int
audio_match(struct device *parent, void *match, void *aux)
{
	struct audio_attach_args *sa = aux;

	return (sa->type == AUDIODEV_TYPE_AUDIO) ? 1 : 0;
}

void
audio_attach(struct device *parent, struct device *self, void *aux)
{
	struct audio_softc *sc = (void *)self;
	struct audio_attach_args *sa = aux;
	struct audio_hw_if *ops = sa->hwif;
	void *arg = sa->hdl;
	int error;

	printf("\n");

#ifdef DIAGNOSTIC
	if (ops == 0 ||
	    ops->open == 0 ||
	    ops->close == 0 ||
	    ops->query_encoding == 0 ||
	    ops->set_params == 0 ||
	    (ops->start_output == 0 && ops->trigger_output == 0) ||
	    (ops->start_input == 0 && ops->trigger_input == 0) ||
	    ops->halt_output == 0 ||
	    ops->halt_input == 0 ||
	    ops->getdev == 0 ||
	    ops->set_port == 0 ||
	    ops->get_port == 0 ||
	    ops->query_devinfo == 0 ||
	    ops->get_props == 0) {
		printf("%s: missing method\n", DEVNAME(sc));
		sc->ops = 0;
		return;
	}
#endif
	sc->ops = ops;
	sc->arg = arg;

#if NWSKBD > 0
	wskbd_mixer_init(sc);
#endif /* NWSKBD > 0 */

	error = audio_buf_init(sc, &sc->play, AUMODE_PLAY);
	if (error) {
		sc->ops = 0;
		printf("%s: could not allocate play buffer\n", DEVNAME(sc));
		return;
	}
	error = audio_buf_init(sc, &sc->rec, AUMODE_RECORD);
	if (error) {
		audio_buf_done(sc, &sc->play);
		sc->ops = 0;
		printf("%s: could not allocate record buffer\n", DEVNAME(sc));
		return;
	}

	/* set defaults */
	sc->sw_enc = AUDIO_ENCODING_SLINEAR;
	sc->bits = 16;
	sc->bps = 2;
	sc->msb = 1;
	sc->rate = 48000;
	sc->pchan = 2;
	sc->rchan = 2;
	sc->round = 960;
	sc->nblks = 2;
	sc->play.pos = sc->play.xrun = sc->rec.pos = sc->rec.xrun = 0;
}

int
audio_activate(struct device *self, int act)
{
	struct audio_softc *sc = (struct audio_softc *)self;

	switch (act) {
	case DVACT_QUIESCE:
		/*
		 * good drivers run play and rec handlers in a single
		 * interrupt. Grab the lock to ensure we expose the same
		 * sc->quiesce value to both play and rec handlers
		 */
		mtx_enter(&audio_lock);
		sc->quiesce = 1;
		mtx_leave(&audio_lock);

		/*
		 * once sc->quiesce is set, interrupts may occur, but
		 * counters are not advanced and consequently processes
		 * keep sleeping.
		 *
		 * XXX: ensure read/write/ioctl don't start/stop
		 * DMA at the same time, this needs a "ready" condvar
		 */
		if (sc->mode != 0 && sc->active)
			audio_stop_do(sc);
		DPRINTF("%s: quesce: active = %d\n", DEVNAME(sc), sc->active);
		break;
	case DVACT_WAKEUP:
		DPRINTF("%s: wakeup: active = %d\n", DEVNAME(sc), sc->active);

		/*
		 * keep buffer usage the same, but set start pointer to
		 * the beginning of the buffer.
		 *
		 * No need to grab the audio_lock as DMA is stopped and
		 * this is the only thread running (caller ensures this)
		 */
		sc->quiesce = 0;
		wakeup(&sc->quiesce);

		if(sc->mode != 0) {
			if (audio_setpar(sc) != 0)
				break;
			if (sc->mode & AUMODE_PLAY) {
				sc->play.start = 0;
				audio_fill_sil(sc, sc->play.data, sc->play.len);
			}
			if (sc->mode & AUMODE_RECORD) {
				sc->rec.start = sc->rec.len - sc->rec.used;
				audio_fill_sil(sc, sc->rec.data, sc->rec.len);
			}
			if (sc->active)
				audio_start_do(sc);
		}
		break;
	}
	return 0;
}

int
audio_detach(struct device *self, int flags)
{
	struct audio_softc *sc = (struct audio_softc *)self;
	int maj, mn;

	DPRINTF("%s: audio_detach: flags = %d\n", DEVNAME(sc), flags);

	wakeup(&sc->quiesce);

	/* locate the major number */
	for (maj = 0; maj < nchrdev; maj++)
		if (cdevsw[maj].d_open == audioopen)
			break;
	/*
	 * Nuke the vnodes for any open instances, calls close but as
	 * close uses device_lookup, it returns EXIO and does nothing
	 */
	mn = self->dv_unit;
	vdevgone(maj, mn | AUDIO_DEV_SOUND, mn | AUDIO_DEV_SOUND, VCHR);
	vdevgone(maj, mn | AUDIO_DEV_AUDIO, mn | AUDIO_DEV_AUDIO, VCHR);
	vdevgone(maj, mn | AUDIO_DEV_AUDIOCTL, mn | AUDIO_DEV_AUDIOCTL, VCHR);
	vdevgone(maj, mn | AUDIO_DEV_MIXER, mn | AUDIO_DEV_MIXER, VCHR);

	/*
	 * The close() method did nothing, quickly halt DMA (normally
	 * parent is already gone, and code below is no-op), and wake-up
	 * user-land blocked in read/write/ioctl, which return EIO.
	 */
	if (sc->mode != 0) {
		if (sc->active) {
			wakeup(&sc->play.blocking);
			selwakeup(&sc->play.sel);
			wakeup(&sc->rec.blocking);
			selwakeup(&sc->rec.sel);
			audio_stop(sc);
		}
		sc->ops->close(sc->arg);
		sc->mode = 0;
	}

	/* free resources */
	audio_buf_done(sc, &sc->play);
	audio_buf_done(sc, &sc->rec);
	return 0;
}

struct device *
audio_attach_mi(struct audio_hw_if *ops, void *arg, struct device *dev)
{
	struct audio_attach_args aa;

	aa.type = AUDIODEV_TYPE_AUDIO;
	aa.hwif = ops;
	aa.hdl = arg;

	/*
	 * attach this driver to the caller (hardware driver), this
	 * checks the kernel config and possibly calls audio_attach()
	 */
	return config_found(dev, &aa, audioprint);
}

int
audioprint(void *aux, const char *pnp)
{
	struct audio_attach_args *arg = aux;
	const char *type;

	if (pnp != NULL) {
		switch (arg->type) {
		case AUDIODEV_TYPE_AUDIO:
			type = "audio";
			break;
		case AUDIODEV_TYPE_OPL:
			type = "opl";
			break;
		case AUDIODEV_TYPE_MPU:
			type = "mpu";
			break;
		default:
			panic("audioprint: unknown type %d", arg->type);
		}
		printf("%s at %s", type, pnp);
	}
	return UNCONF;
}

int
audio_open(struct audio_softc *sc, int flags)
{
	int error;
	int props;

	if (sc->mode)
		return EBUSY;
	error = sc->ops->open(sc->arg, flags);
	if (error)
		return error;
	sc->active = 0;
	sc->pause = 1;
	sc->rec.blocking = 0;
	sc->play.blocking = 0;
	sc->mode = 0;
	if (flags & FWRITE)
		sc->mode |= AUMODE_PLAY;
	if (flags & FREAD)
		sc->mode |= AUMODE_RECORD;
	props = sc->ops->get_props(sc->arg);
	if (sc->mode == (AUMODE_PLAY | AUMODE_RECORD)) {
		if (!(props & AUDIO_PROP_FULLDUPLEX)) {
			error = ENOTTY;
			goto bad;
		}
		if (sc->ops->setfd) {
			error = sc->ops->setfd(sc->arg, 1);
			if (error)
				goto bad;
		}
	}

	if (sc->ops->speaker_ctl) {
		/*
		 * XXX: what is this used for?
		 */
		sc->ops->speaker_ctl(sc->arg,
		    (sc->mode & AUMODE_PLAY) ? SPKR_ON : SPKR_OFF);
	}

	error = audio_setpar(sc);
	if (error)
		goto bad;
	audio_clear(sc);

	/*
	 * allow read(2)/write(2) to automatically start DMA, without
	 * the need for ioctl(), to make /dev/audio usable in scripts
	 */
	sc->pause = 0;
	return 0;
bad:
	sc->ops->close(sc->arg);
	sc->mode = 0;
	return error;
}

int
audio_drain(struct audio_softc *sc)
{
	int error, xrun;
	unsigned char *ptr;
	size_t count, bpf;

	DPRINTF("%s: drain: mode = %d, pause = %d, active = %d, used = %zu\n",
	    DEVNAME(sc), sc->mode, sc->pause, sc->active, sc->play.used);
	if (!(sc->mode & AUMODE_PLAY) || sc->pause)
		return 0;

	/* discard partial samples, required by audio_fill_sil() */
	mtx_enter(&audio_lock);
	bpf = sc->pchan * sc->bps;
	sc->play.used -= sc->play.used % bpf;
	if (sc->play.used == 0) {
		mtx_leave(&audio_lock);
		return 0;
	}

	if (!sc->active) {
		/*
		 * dma not started yet because buffer was not full
		 * enough to start automatically. Pad it and start now.
		 */
		for (;;) {
			ptr = audio_buf_wgetblk(&sc->play, &count);
			if (count == 0)
				break;
			audio_fill_sil(sc, ptr, count);
			audio_buf_wcommit(&sc->play, count);
		}
		mtx_leave(&audio_lock);
		error = audio_start(sc);
		if (error)
			return error;
		mtx_enter(&audio_lock);
	}

	xrun = sc->play.xrun;
	while (sc->play.xrun == xrun) {
		DPRINTF("%s: drain: used = %zu, xrun = %d\n",
		    DEVNAME(sc), sc->play.used, sc->play.xrun);

		/*
		 * set a 5 second timeout, in case interrupts don't
		 * work, useful only for debugging drivers
		 */
		sc->play.blocking = 1;
		error = msleep(&sc->play.blocking, &audio_lock,
		    PWAIT | PCATCH, "au_dr", 5 * hz);
		if (!(sc->dev.dv_flags & DVF_ACTIVE))
			error = EIO;
		if (error) {
			DPRINTF("%s: drain, err = %d\n", DEVNAME(sc), error);
			break;
		}
	}
	mtx_leave(&audio_lock);
	return error;
}

int
audio_close(struct audio_softc *sc)
{
	audio_drain(sc);
	if (sc->active)
		audio_stop(sc);
	sc->ops->close(sc->arg);
	sc->mode = 0;
	DPRINTF("%s: close: done\n", DEVNAME(sc));
	return 0;
}

int
audio_read(struct audio_softc *sc, struct uio *uio, int ioflag)
{
	unsigned char *ptr;
	size_t count;
	int error;

	DPRINTFN(1, "%s: read: resid = %zd\n",  DEVNAME(sc), uio->uio_resid);

	/* block if quiesced */
	while (sc->quiesce)
		tsleep(&sc->quiesce, 0, "au_qrd", 0);

	/* start automatically if setinfo() was never called */
	mtx_enter(&audio_lock);
	if (!sc->active && !sc->pause && sc->rec.used == 0) {
		mtx_leave(&audio_lock);
		error = audio_start(sc);
		if (error)
			return error;
		mtx_enter(&audio_lock);
	}

	/* if there is no data then sleep */
	while (sc->rec.used == 0) {
		if (ioflag & IO_NDELAY) {
			mtx_leave(&audio_lock);
			return EWOULDBLOCK;
		}
		DPRINTFN(1, "%s: read sleep\n", DEVNAME(sc));
		sc->rec.blocking = 1;
		error = msleep(&sc->rec.blocking,
		    &audio_lock, PWAIT | PCATCH, "au_rd", 0);
		if (!(sc->dev.dv_flags & DVF_ACTIVE))
			error = EIO;
#ifdef AUDIO_DEBUG
		if (error) {
			DPRINTF("%s: read woke up error = %d\n",
			    DEVNAME(sc), error);
		}
#endif
		if (error) {
			mtx_leave(&audio_lock);
			return error;
		}
	}

	/* at this stage, there is data to transfer */
	while (uio->uio_resid > 0 && sc->rec.used > 0) {
		ptr = audio_buf_rgetblk(&sc->rec, &count);
		if (count > uio->uio_resid)
			count = uio->uio_resid;
		mtx_leave(&audio_lock);
		DPRINTFN(1, "%s: read: start = %zu, count = %zu\n",
		    DEVNAME(sc), ptr - sc->rec.data, count);
		if (sc->conv_dec)
			sc->conv_dec(ptr, count);
		error = uiomove(ptr, count, uio);
		if (error)
			return error;
		mtx_enter(&audio_lock);
		audio_buf_rdiscard(&sc->rec, count);
	}
	mtx_leave(&audio_lock);
	return 0;
}

int
audio_write(struct audio_softc *sc, struct uio *uio, int ioflag)
{
	unsigned char *ptr;
	size_t count;
	int error;

	DPRINTFN(1, "%s: write: resid = %zd\n",  DEVNAME(sc), uio->uio_resid);

	/* block if quiesced */
	while (sc->quiesce)
		tsleep(&sc->quiesce, 0, "au_qwr", 0);

	/*
	 * if IO_NDELAY flag is set then check if there is enough room
	 * in the buffer to store at least one byte. If not then dont
	 * start the write process.
	 */
	mtx_enter(&audio_lock);
	if (uio->uio_resid > 0 && (ioflag & IO_NDELAY)) {
		if (sc->play.used == sc->play.len) {
			mtx_leave(&audio_lock);
			return EWOULDBLOCK;
		}
	}

	while (uio->uio_resid > 0) {
		while (1) {
			ptr = audio_buf_wgetblk(&sc->play, &count);
			if (count > 0)
				break;
			if (ioflag & IO_NDELAY) {
				/*
				 * At this stage at least one byte is already
				 * moved so we do not return EWOULDBLOCK
				 */
				mtx_leave(&audio_lock);
				return 0;
			}
			DPRINTFN(1, "%s: write sleep\n", DEVNAME(sc));
			sc->play.blocking = 1;
			error = msleep(&sc->play.blocking,
			    &audio_lock, PWAIT | PCATCH, "au_wr", 0);
			if (!(sc->dev.dv_flags & DVF_ACTIVE))
				error = EIO;
#ifdef AUDIO_DEBUG
			if (error) {
				DPRINTF("%s: write woke up error = %d\n",
				    DEVNAME(sc), error);
			}
#endif
			if (error) {
				mtx_leave(&audio_lock);
				return error;
			}
		}
		if (count > uio->uio_resid)
			count = uio->uio_resid;
		mtx_leave(&audio_lock);
		error = uiomove(ptr, count, uio);
		if (error)
			return 0;
		if (sc->conv_enc) {
			sc->conv_enc(ptr, count);
			DPRINTFN(1, "audio_write: converted count = %zu\n",
			    count);
		}
		mtx_enter(&audio_lock);
		audio_buf_wcommit(&sc->play, count);

		/* start automatically if setinfo() was never called */
		if (!sc->active && !sc->pause &&
		    sc->play.used == sc->play.len) {
			mtx_leave(&audio_lock);
			error = audio_start(sc);
			if (error)
				return error;
			mtx_enter(&audio_lock);
		}
	}
	mtx_leave(&audio_lock);
	return 0;
}

int
audio_ioctl(struct audio_softc *sc, unsigned long cmd, void *addr)
{
	struct audio_offset *ao;
	struct audio_pos *ap;
	int error = 0, fd;

	/* block if quiesced */
	while (sc->quiesce)
		tsleep(&sc->quiesce, 0, "au_qio", 0);

	switch (cmd) {
	case FIONBIO:
		/* All handled in the upper FS layer. */
		break;
	case AUDIO_PERROR:
		mtx_enter(&audio_lock);
		*(int *)addr = sc->play.xrun / (sc->pchan * sc->bps);
		mtx_leave(&audio_lock);
		break;
	case AUDIO_RERROR:
		mtx_enter(&audio_lock);
		*(int *)addr = sc->rec.xrun / (sc->rchan * sc->bps);
		mtx_leave(&audio_lock);
		break;
	case AUDIO_GETOOFFS:
		mtx_enter(&audio_lock);
		ao = (struct audio_offset *)addr;
		ao->samples = sc->play.pos;
		mtx_leave(&audio_lock);
		break;
	case AUDIO_GETIOFFS:
		mtx_enter(&audio_lock);
		ao = (struct audio_offset *)addr;
		ao->samples = sc->rec.pos;
		mtx_leave(&audio_lock);
		break;
	case AUDIO_GETPOS:
		mtx_enter(&audio_lock);
		ap = (struct audio_pos *)addr;
		ap->play_pos = sc->play.pos;
		ap->play_xrun = sc->play.xrun;
		ap->rec_pos = sc->rec.pos;
		ap->rec_xrun = sc->rec.xrun;
		mtx_leave(&audio_lock);
		break;
	case AUDIO_SETINFO:
		error = audio_setinfo(sc, (struct audio_info *)addr);
		break;
	case AUDIO_GETINFO:
		error = audio_getinfo(sc, (struct audio_info *)addr);
		break;
	case AUDIO_GETDEV:
		error = sc->ops->getdev(sc->arg, (audio_device_t *)addr);
		break;
	case AUDIO_GETENC:
		error = sc->ops->query_encoding(sc->arg,
		    (struct audio_encoding *)addr);
		break;
	case AUDIO_GETFD:
		*(int *)addr = (sc->mode & (AUMODE_PLAY | AUMODE_RECORD)) ==
		    (AUMODE_PLAY | AUMODE_RECORD);
		break;
	case AUDIO_SETFD:
		fd = *(int *)addr;
		if ((sc->mode & (AUMODE_PLAY | AUMODE_RECORD)) !=
		    (AUMODE_PLAY | AUMODE_RECORD) || !fd)
			return EINVAL;
		break;
	case AUDIO_GETPROPS:
		*(int *)addr = sc->ops->get_props(sc->arg);
		break;
	default:
		DPRINTF("%s: unknown ioctl 0x%lx\n", DEVNAME(sc), cmd);
		error = ENOTTY;
		break;
	}
	return error;
}

int
audio_ioctl_mixer(struct audio_softc *sc, unsigned long cmd, void *addr)
{
	int error;

	/* block if quiesced */
	while (sc->quiesce)
		tsleep(&sc->quiesce, 0, "mix_qio", 0);

	switch (cmd) {
	case FIONBIO:
		/* All handled in the upper FS layer. */
		break;
	case AUDIO_MIXER_DEVINFO:
		((mixer_devinfo_t *)addr)->un.v.delta = 0;
		return sc->ops->query_devinfo(sc->arg, (mixer_devinfo_t *)addr);
	case AUDIO_MIXER_READ:
		return sc->ops->get_port(sc->arg, (mixer_ctrl_t *)addr);
	case AUDIO_MIXER_WRITE:
		error = sc->ops->set_port(sc->arg, (mixer_ctrl_t *)addr);
		if (error)
			return error;
		if (sc->ops->commit_settings)
			return sc->ops->commit_settings(sc->arg);
		break;
	default:
		return ENOTTY;
	}
	return 0;
}

int
audio_poll(struct audio_softc *sc, int events, struct proc *p)
{
	int revents = 0;

	mtx_enter(&audio_lock);
	if ((sc->mode & AUMODE_RECORD) && sc->rec.used > 0)
		revents |= events & (POLLIN | POLLRDNORM);
	if ((sc->mode & AUMODE_PLAY) && sc->play.used < sc->play.len)
		revents |= events & (POLLOUT | POLLWRNORM);
	if (revents == 0) {
		if (events & (POLLIN | POLLRDNORM))
			selrecord(p, &sc->rec.sel);
		if (events & (POLLOUT | POLLWRNORM))
			selrecord(p, &sc->play.sel);
	}
	mtx_leave(&audio_lock);
	return revents;
}

int
audioopen(dev_t dev, int flags, int mode, struct proc *p)
{
	struct audio_softc *sc;
	int error;

	sc = (struct audio_softc *)device_lookup(&audio_cd, AUDIO_UNIT(dev));
	if (sc == NULL)
		return ENXIO;
	if (sc->ops == NULL)
		error = ENXIO;
	else {
		switch (AUDIO_DEV(dev)) {
		case AUDIO_DEV_SOUND:
		case AUDIO_DEV_AUDIO:
			error = audio_open(sc, flags);
			break;
		case AUDIO_DEV_AUDIOCTL:
		case AUDIO_DEV_MIXER:
			error = 0;
			break;
		default:
			error = ENXIO;
		}
	}
	device_unref(&sc->dev);
	return error;
}

int
audioclose(dev_t dev, int flags, int ifmt, struct proc *p)
{
	struct audio_softc *sc;
	int error;

	sc = (struct audio_softc *)device_lookup(&audio_cd, AUDIO_UNIT(dev));
	if (sc == NULL)
		return ENXIO;
	switch (AUDIO_DEV(dev)) {
	case AUDIO_DEV_SOUND:
	case AUDIO_DEV_AUDIO:
		error = audio_close(sc);
		break;
	case AUDIO_DEV_MIXER:
	case AUDIO_DEV_AUDIOCTL:
		error = 0;
	default:
		error = ENXIO;
	}
	device_unref(&sc->dev);
	return error;
}

int
audioread(dev_t dev, struct uio *uio, int ioflag)
{
	struct audio_softc *sc;
	int error;

	sc = (struct audio_softc *)device_lookup(&audio_cd, AUDIO_UNIT(dev));
	if (sc == NULL)
		return ENXIO;
	switch (AUDIO_DEV(dev)) {
	case AUDIO_DEV_SOUND:
	case AUDIO_DEV_AUDIO:
		error = audio_read(sc, uio, ioflag);
		break;
	case AUDIO_DEV_AUDIOCTL:
	case AUDIO_DEV_MIXER:
		error = ENODEV;
		break;
	default:
		error = ENXIO;
	}
	device_unref(&sc->dev);
	return error;
}

int
audiowrite(dev_t dev, struct uio *uio, int ioflag)
{
	struct audio_softc *sc;
	int error;

	sc = (struct audio_softc *)device_lookup(&audio_cd, AUDIO_UNIT(dev));
	if (sc == NULL)
		return ENXIO;
	switch (AUDIO_DEV(dev)) {
	case AUDIO_DEV_SOUND:
	case AUDIO_DEV_AUDIO:
		error = audio_write(sc, uio, ioflag);
		break;
	case AUDIO_DEV_AUDIOCTL:
	case AUDIO_DEV_MIXER:
		error = ENODEV;
		break;
	default:
		error = ENXIO;
	}
	device_unref(&sc->dev);
	return error;
}

int
audioioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
{
	struct audio_softc *sc;
	int error;

	sc = (struct audio_softc *)device_lookup(&audio_cd, AUDIO_UNIT(dev));
	if (sc == NULL)
		return ENXIO;
	switch (AUDIO_DEV(dev)) {
	case AUDIO_DEV_SOUND:
	case AUDIO_DEV_AUDIO:
		error = audio_ioctl(sc, cmd, addr);
		break;
	case AUDIO_DEV_AUDIOCTL:
		if (cmd == AUDIO_SETINFO && sc->mode != 0) {
			error = EBUSY;
			break;
		}
		error = audio_ioctl(sc, cmd, addr);
		break;
	case AUDIO_DEV_MIXER:
		error = audio_ioctl_mixer(sc, cmd, addr);
		break;
	default:
		error = ENXIO;
	}
	device_unref(&sc->dev);
	return error;
}

int
audiopoll(dev_t dev, int events, struct proc *p)
{
	struct audio_softc *sc;
	int revents;

	sc = (struct audio_softc *)device_lookup(&audio_cd, AUDIO_UNIT(dev));
	if (sc == NULL)
		return POLLERR;
	switch (AUDIO_DEV(dev)) {
	case AUDIO_DEV_SOUND:
	case AUDIO_DEV_AUDIO:
		revents = audio_poll(sc, events, p);
		break;
	case AUDIO_DEV_AUDIOCTL:
	case AUDIO_DEV_MIXER:
		revents = 0;
		break;
	default:
		revents = 0;
	}
	device_unref(&sc->dev);
	return revents;
}

#if NWSKBD > 0
int
wskbd_initmute(struct audio_softc *sc, struct mixer_devinfo *vol)
{
	struct mixer_devinfo mi;

	mi.index = vol->next;
	for (mi.index = vol->next; mi.index != -1; mi.index = mi.next) {
		if (sc->ops->query_devinfo(sc->arg, &mi) != 0)
			break;
		if (strcmp(mi.label.name, AudioNmute) == 0)
			return mi.index;
	}
	return -1;
}

int
wskbd_initvol(struct audio_softc *sc, struct wskbd_vol *vol, char *cn, char *dn)
{
	struct mixer_devinfo dev, cls;

	for (dev.index = 0; ; dev.index++) {
		if (sc->ops->query_devinfo(sc->arg, &dev) != 0)
			break;
		cls.index = dev.mixer_class;
		if (sc->ops->query_devinfo(sc->arg, &cls) != 0)
			continue;
		if (strcmp(cls.label.name, cn) == 0 &&
		    strcmp(dev.label.name, dn) == 0) {
			vol->val = dev.index;
			vol->nch = dev.un.v.num_channels;
			vol->step = dev.un.v.delta > 8 ? dev.un.v.delta : 8;
			vol->mute = wskbd_initmute(sc, &dev);
			vol->val_pending = vol->mute_pending = 0;
			DPRINTF("%s: wskbd using %s.%s, %s\n",
			    DEVNAME(sc), cn, dn, vol->mute >= -1 ? "mute control" : "");
			return 1;
		}
	}
	vol->val = vol->mute = -1;
	return 0;
}

void
wskbd_mixer_init(struct audio_softc *sc)
{
	static struct {
		char *cn, *dn;
	} spkr_names[] = {
		{AudioCoutputs, AudioNmaster},
		{AudioCinputs,  AudioNdac},
		{AudioCoutputs, AudioNdac},
		{AudioCoutputs, AudioNoutput}
	}, mic_names[] = {
		{AudioCrecord, AudioNrecord},
		{AudioCrecord, AudioNvolume},
		{AudioCinputs, AudioNrecord},
		{AudioCinputs, AudioNvolume},
		{AudioCinputs, AudioNinput}
	};
	int i;

	if (sc->dev.dv_unit != 0) {
		DPRINTF("%s: not configuring wskbd keys\n", DEVNAME(sc));
		return;
	}
	for (i = 0; i < sizeof(spkr_names) / sizeof(spkr_names[0]); i++) {
		if (wskbd_initvol(sc, &sc->spkr,
			spkr_names[i].cn, spkr_names[i].dn))
			break;
	}
	for (i = 0; i < sizeof(mic_names) / sizeof(mic_names[0]); i++) {
		if (wskbd_initvol(sc, &sc->mic,
			mic_names[i].cn, mic_names[i].dn))
			break;
	}
}

void
wskbd_mixer_update(struct audio_softc *sc, struct wskbd_vol *vol)
{
	struct mixer_ctrl ctrl;
	int val_pending, mute_pending, i, gain, error, s;

	s = spltty();
	val_pending = vol->val_pending;
	vol->val_pending = 0;
	mute_pending = vol->mute_pending;
	vol->mute_pending = 0;
	splx(s);

	if (sc->ops == NULL)
		return;
	if (vol->mute >= 0 && mute_pending) {
		ctrl.dev = vol->mute;
		ctrl.type = AUDIO_MIXER_ENUM;
		error = sc->ops->get_port(sc->arg, &ctrl);
		if (error) {
			DPRINTF("%s: get mute err = %d\n", DEVNAME(sc), error);
			return;
		}
		ctrl.un.ord = ctrl.un.ord ^ mute_pending;
		DPRINTFN(1, "%s: wskbd mute setting to %d\n",
		    DEVNAME(sc), ctrl.un.ord);
		error = sc->ops->set_port(sc->arg, &ctrl);
		if (error) {
			DPRINTF("%s: set mute err = %d\n", DEVNAME(sc), error);
			return;
		}
	}
	if (vol->val >= 0 && val_pending) {
		ctrl.dev = vol->val;
		ctrl.type = AUDIO_MIXER_VALUE;
		ctrl.un.value.num_channels = vol->nch;
		error = sc->ops->get_port(sc->arg, &ctrl);
		if (error) {
			DPRINTF("%s: get mute err = %d\n", DEVNAME(sc), error);
			return;
		}
		for (i = 0; i < vol->nch; i++) {
			gain = ctrl.un.value.level[i] + vol->step * val_pending;
			if (gain > AUDIO_MAX_GAIN)
				gain = AUDIO_MAX_GAIN;
			if (gain < AUDIO_MIN_GAIN)
				gain = AUDIO_MIN_GAIN;
			ctrl.un.value.level[i] = gain;
			DPRINTFN(1, "%s: wskbd level %d set to %d\n",
			    DEVNAME(sc), i, gain);
		}
		error = sc->ops->set_port(sc->arg, &ctrl);
		if (error) {
			DPRINTF("%s: set vol err = %d\n", DEVNAME(sc), error);
			return;
		}
	}
}

void
wskbd_mixer_cb(void *addr)
{
	struct audio_softc *sc = addr;
	int s;

	wskbd_mixer_update(sc, &sc->spkr);
	wskbd_mixer_update(sc, &sc->mic);
	s = spltty();
	sc->wskbd_taskset = 0;
	splx(s);
	device_unref(&sc->dev);
}

int
wskbd_set_mixervolume(long dir, long out)
{
	struct audio_softc *sc;
	struct wskbd_vol *vol;

	sc = (struct audio_softc *)device_lookup(&audio_cd, 0);
	if (sc == NULL)
		return ENODEV;
	vol = out ? &sc->spkr : &sc->mic;
	if (dir == 0)
		vol->mute_pending ^= 1;
	else
		vol->val_pending += dir;
	if (!sc->wskbd_taskset) {
		task_set(&sc->wskbd_task, wskbd_mixer_cb, sc);
		task_add(systq, &sc->wskbd_task);
		sc->wskbd_taskset = 1;
	}
	return 0;
}
#endif /* NWSKBD > 0 */


code:
/*	$OpenBSD: audio_if.h,v 1.30 2015/06/25 06:43:46 ratchov Exp $	*/
/*	$NetBSD: audio_if.h,v 1.24 1998/01/10 14:07:25 tv Exp $	*/

/*
 * Copyright (c) 1994 Havard Eidnes.
 * 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 the Computer Systems
 *	Engineering Group at Lawrence Berkeley Laboratory.
 * 4. Neither the name of the University nor of the Laboratory may be used
 *    to endorse or promote products derived from this software without
 *    specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
 *
 */

#ifndef _SYS_DEV_AUDIO_IF_H_
#define _SYS_DEV_AUDIO_IF_H_

#include <sys/mutex.h>

#define AUDIO_BPS(bits)		(bits) <= 8 ? 1 : ((bits) <= 16 ? 2 : 4)

/*
 * Generic interface to hardware driver.
 */

struct audio_device;
struct audio_encoding;
struct mixer_devinfo;
struct mixer_ctrl;

struct audio_params {
	u_long	sample_rate;			/* sample rate */
	u_int	encoding;			/* mu-law, linear, etc */
	u_int	precision;			/* bits/sample */
	u_int	bps;				/* bytes/sample */
	u_int	msb;				/* data alignment */
	u_int	channels;			/* mono(1), stereo(2) */
};

struct audio_hw_if {
	int	(*open)(void *, int);	/* open hardware */
	void	(*close)(void *);		/* close hardware */
	int	(*drain)(void *);		/* Optional: drain buffers */

	/* Encoding. */
	/* XXX should we have separate in/out? */
	int	(*query_encoding)(void *, struct audio_encoding *);

	/* Set the audio encoding parameters (record and play).
	 * Return 0 on success, or an error code if the
	 * requested parameters are impossible.
	 * The values in the params struct may be changed (e.g. rounding
	 * to the nearest sample rate.)
	 */
	int	(*set_params)(void *, int, int, struct audio_params *,
		    struct audio_params *);

	/* Hardware may have some say in the blocksize to choose */
	int	(*round_blocksize)(void *, int);

	/*
	 * Changing settings may require taking device out of "data mode",
	 * which can be quite expensive.  Also, audiosetinfo() may
	 * change several settings in quick succession.  To avoid
	 * having to take the device in/out of "data mode", we provide
	 * this function which indicates completion of settings
	 * adjustment.
	 */
	int	(*commit_settings)(void *);

	/* Start input/output routines. These usually control DMA. */
	int	(*init_output)(void *, void *, int);
	int	(*init_input)(void *, void *, int);
	int	(*start_output)(void *, void *, int, void (*)(void *), void *);
	int	(*start_input)(void *, void *, int, void (*)(void *), void *);
	int	(*halt_output)(void *);
	int	(*halt_input)(void *);

	int	(*speaker_ctl)(void *, int);
#define SPKR_ON		1
#define SPKR_OFF	0

	int	(*getdev)(void *, struct audio_device *);
	int	(*setfd)(void *, int);

	/* Mixer (in/out ports) */
	int	(*set_port)(void *, struct mixer_ctrl *);
	int	(*get_port)(void *, struct mixer_ctrl *);

	int	(*query_devinfo)(void *, struct mixer_devinfo *);

	/* Allocate/free memory for the ring buffer. Usually malloc/free. */
	/* The _old interfaces have been deprecated and will not be
	   called in newer kernels if the new interfaces are present */
	void	*(*allocm)(void *, int, size_t, int, int);
	void	(*freem)(void *, void *, int);
	size_t	(*round_buffersize)(void *, int, size_t);
	paddr_t	(*mappage)(void *, void *, off_t, int);

	int	(*get_props)(void *); /* device properties */

	int	(*trigger_output)(void *, void *, void *, int,
		    void (*)(void *), void *, struct audio_params *);
	int	(*trigger_input)(void *, void *, void *, int,
		    void (*)(void *), void *, struct audio_params *);
	void	(*get_default_params)(void *, int, struct audio_params *);
};

struct audio_attach_args {
	int	type;
	void	*hwif;		/* either audio_hw_if * or midi_hw_if * */
	void	*hdl;
};
#define	AUDIODEV_TYPE_AUDIO	0
#define	AUDIODEV_TYPE_MIDI	1
#define AUDIODEV_TYPE_OPL	2
#define AUDIODEV_TYPE_MPU	3
#define AUDIODEV_TYPE_RADIO	4

/* Attach the MI driver(s) to the MD driver. */
struct device *audio_attach_mi(struct audio_hw_if *, void *, struct device *);
int	       audioprint(void *, const char *);

extern struct mutex audio_lock;

#endif /* _SYS_DEV_AUDIO_IF_H_ */

license: unknown


code:
/*	$OpenBSD: bio.c,v 1.16 2015/05/29 00:33:37 uebayasi Exp $	*/

/*
 * Copyright (c) 2002 Niklas Hallqvist.  All rights reserved.
 * Copyright (c) 2012 Joel Sing <jsing@openbsd.org>.  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.
 *
 * 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.
 */

/* A device controller ioctl tunnelling device.  */

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

#include <dev/biovar.h>

struct bio_mapping {
	LIST_ENTRY(bio_mapping) bm_link;
	struct device *bm_dev;
	int (*bm_ioctl)(struct device *, u_long, caddr_t);
};

LIST_HEAD(, bio_mapping) bios = LIST_HEAD_INITIALIZER(bios);

void	bioattach(int);
int	bioclose(dev_t, int, int, struct proc *);
int	bioioctl(dev_t, u_long, caddr_t, int, struct proc *);
int	bioopen(dev_t, int, int, struct proc *);

int	bio_delegate_ioctl(struct bio_mapping *, u_long, caddr_t);
struct	bio_mapping *bio_lookup(char *);
int	bio_validate(void *);

void
bioattach(int nunits)
{
}

int
bioopen(dev_t dev, int flags, int mode, struct proc *p)
{
	return (0);
}

int
bioclose(dev_t dev, int flags, int mode, struct proc *p)
{
	return (0);
}

int
bioioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
{
	struct bio_locate *locate;
	struct bio *bio;
	char name[16];
	int error;

	switch (cmd) {
	case BIOCLOCATE:
		locate = (struct bio_locate *)addr;
		error = copyinstr(locate->bl_name, name, sizeof name, NULL);
		if (error != 0)
			return (error);
		locate->bl_bio.bio_cookie = bio_lookup(name);
		if (locate->bl_bio.bio_cookie == NULL)
			return (ENOENT);
		break;

	case BIOCINQ:
	case BIOCDISK:
	case BIOCVOL:
	case BIOCALARM:
	case BIOCBLINK:
	case BIOCSETSTATE:
	case BIOCCREATERAID:
	case BIOCDELETERAID:
	case BIOCDISCIPLINE:
	case BIOCPATROL:
		bio = (struct bio *)addr;
		if (!bio_validate(bio->bio_cookie))
			return (ENOENT);
		return (bio_delegate_ioctl(
		    (struct bio_mapping *)bio->bio_cookie, cmd, addr));

	default:
		return (ENXIO);
	}
	return (0);
}

int
bio_register(struct device *dev, int (*ioctl)(struct device *, u_long, caddr_t))
{
	struct bio_mapping *bm;

	bm = malloc(sizeof *bm, M_DEVBUF, M_NOWAIT);
	if (bm == NULL)
		return (ENOMEM);
	bm->bm_dev = dev;
	bm->bm_ioctl = ioctl;
	LIST_INSERT_HEAD(&bios, bm, bm_link);
	return (0);
}

void
bio_unregister(struct device *dev)
{
	struct bio_mapping *bm, *next;

	for (bm = LIST_FIRST(&bios); bm != NULL; bm = next) {
		next = LIST_NEXT(bm, bm_link);

		if (dev == bm->bm_dev) {
			LIST_REMOVE(bm, bm_link);
			free(bm, M_DEVBUF, 0);
		}
	}
}

struct bio_mapping *
bio_lookup(char *name)
{
	struct bio_mapping *bm;

	LIST_FOREACH(bm, &bios, bm_link)
		if (strcmp(name, bm->bm_dev->dv_xname) == 0)
			return (bm);
	return (NULL);
}

int
bio_validate(void *cookie)
{
	struct bio_mapping *bm;

	LIST_FOREACH(bm, &bios, bm_link)
		if (bm == cookie)
			return (1);
	return (0);
}

int
bio_delegate_ioctl(struct bio_mapping *bm, u_long cmd, caddr_t addr)
{
	return (bm->bm_ioctl(bm->bm_dev, cmd, addr));
}

void
bio_info(struct bio_status *bs, int print, const char *fmt, ...)
{
	va_list	ap;

	va_start(ap, fmt);
	bio_status(bs, print, BIO_MSG_INFO, fmt, &ap);
	va_end(ap);
}

void
bio_warn(struct bio_status *bs, int print, const char *fmt, ...)
{
	va_list	ap;

	va_start(ap, fmt);
	bio_status(bs, print, BIO_MSG_WARN, fmt, &ap);
	va_end(ap);
}

void
bio_error(struct bio_status *bs, int print, const char *fmt, ...)
{
	va_list	ap;

	va_start(ap, fmt);
	bio_status(bs, print, BIO_MSG_ERROR, fmt, &ap);
	va_end(ap);
}

void
bio_status_init(struct bio_status *bs, struct device *dv)
{
	bzero(bs, sizeof(struct bio_status));

	bs->bs_status = BIO_STATUS_UNKNOWN;

	strlcpy(bs->bs_controller, dv->dv_xname, sizeof(bs->bs_controller));
}

void
bio_status(struct bio_status *bs, int print, int msg_type, const char *fmt,
    va_list *ap)
{
	int idx;

	if (bs->bs_msg_count >= BIO_MSG_COUNT) {
		printf("%s: insufficient message buffers\n", bs->bs_controller);
		return;
	}

	idx = bs->bs_msg_count++;

	bs->bs_msgs[idx].bm_type = msg_type;
	vsnprintf(bs->bs_msgs[idx].bm_msg, BIO_MSG_LEN, fmt, *ap);

	if (print)
		printf("%s: %s\n", bs->bs_controller, bs->bs_msgs[idx].bm_msg);
}


code:
/*	$OpenBSD: biovar.h,v 1.44 2015/05/29 00:33:37 uebayasi Exp $	*/

/*
 * Copyright (c) 2002 Niklas Hallqvist.  All rights reserved.
 * Copyright (c) 2005 Marco Peereboom.  All rights reserved.
 * Copyright (c) 2012 Joel Sing <jsing@openbsd.org>.  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.
 *
 * 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.
 */

/*
 * Devices getting ioctls through this interface should use ioctl class 'B'
 * and command numbers starting from 32, lower ones are reserved for generic
 * ioctls. All ioctl data must be structures which start with a struct bio.
 */

#include <sys/types.h>

#define	BIO_MSG_COUNT	5
#define	BIO_MSG_LEN	128

struct bio_msg {
	int		bm_type;
#define	BIO_MSG_INFO	1
#define	BIO_MSG_WARN	2
#define	BIO_MSG_ERROR	3
	char		bm_msg[BIO_MSG_LEN];
};

struct bio_status {
	char		bs_controller[16];
	int		bs_status;
#define	BIO_STATUS_UNKNOWN	0
#define	BIO_STATUS_SUCCESS	1
#define	BIO_STATUS_ERROR	2
	int		bs_msg_count;
	struct bio_msg	bs_msgs[BIO_MSG_COUNT];
};

struct bio {
	void			*bio_cookie;
	struct bio_status	bio_status;
};

/* convert name to a cookie */
#define BIOCLOCATE _IOWR('B', 0, struct bio_locate)
struct bio_locate {
	struct bio	bl_bio;
	char		*bl_name;
};

#define BIOCINQ _IOWR('B', 32, struct bioc_inq)
struct bioc_inq {
	struct bio	bi_bio;

	char		bi_dev[16];	/* controller device */
	int		bi_novol;	/* nr of volumes */
	int		bi_nodisk;	/* nr of total disks */
};

#define BIOCDISK _IOWR('B', 33, struct bioc_disk)
/* structure that represents a disk in a RAID volume */
struct bioc_disk {
	struct bio	bd_bio;

	u_int16_t	bd_channel;
	u_int16_t	bd_target;
	u_int16_t	bd_lun;
	u_int16_t	bd_other_id;	/* unused for now  */

	int		bd_volid;	/* associate with volume */
	int		bd_diskid;	/* virtual disk */
	int		bd_status;	/* current status */
#define BIOC_SDONLINE		0x00
#define BIOC_SDONLINE_S		"Online"
#define BIOC_SDOFFLINE		0x01
#define BIOC_SDOFFLINE_S	"Offline"
#define BIOC_SDFAILED		0x02
#define BIOC_SDFAILED_S		"Failed"
#define BIOC_SDREBUILD		0x03
#define BIOC_SDREBUILD_S	"Rebuild"
#define BIOC_SDHOTSPARE		0x04
#define BIOC_SDHOTSPARE_S	"Hot spare"
#define BIOC_SDUNUSED		0x05
#define BIOC_SDUNUSED_S		"Unused"
#define BIOC_SDSCRUB		0x06
#define BIOC_SDSCRUB_S		"Scrubbing"
#define BIOC_SDINVALID		0xff
#define BIOC_SDINVALID_S	"Invalid"
	u_quad_t	bd_size;	/* size of the disk */

	char		bd_vendor[32];	/* scsi string */
	char		bd_serial[32];	/* serial number */
	char		bd_procdev[16];	/* processor device */

	struct {
		int		bdp_percent;
		int		bdp_seconds;
	}		bd_patrol;
};

#define BIOCVOL _IOWR('B', 34, struct bioc_vol)
/* structure that represents a RAID volume */
struct bioc_vol {
	struct bio	bv_bio;
	int		bv_volid;	/* volume id */

	int16_t		bv_percent;	/* percent done operation */
	u_int16_t	bv_seconds;	/* seconds of progress so far */

	int		bv_status;	/* current status */
#define BIOC_SVONLINE		0x00
#define BIOC_SVONLINE_S		"Online"
#define BIOC_SVOFFLINE		0x01
#define BIOC_SVOFFLINE_S	"Offline"
#define BIOC_SVDEGRADED		0x02
#define BIOC_SVDEGRADED_S	"Degraded"
#define BIOC_SVBUILDING		0x03
#define BIOC_SVBUILDING_S	"Building"
#define BIOC_SVSCRUB		0x04
#define BIOC_SVSCRUB_S		"Scrubbing"
#define BIOC_SVREBUILD		0x05
#define BIOC_SVREBUILD_S	"Rebuild"
#define BIOC_SVINVALID		0xff
#define BIOC_SVINVALID_S	"Invalid"
	u_quad_t	bv_size;	/* size of the disk */
	int		bv_level;	/* raid level */
	int		bv_nodisk;	/* nr of drives */
	int		bv_cache;	/* cache mode */
#define BIOC_CVUNKNOWN		0x00
#define BIOC_CVUNKNOWN_S	""
#define BIOC_CVWRITEBACK	0x01
#define BIOC_CVWRITEBACK_S	"WB"
#define BIOC_CVWRITETHROUGH	0x02
#define BIOC_CVWRITETHROUGH_S	"WT"

	char		bv_dev[16];	/* device */
	char		bv_vendor[32];	/* scsi string */
};

#define BIOCALARM _IOWR('B', 35, struct bioc_alarm)
struct bioc_alarm {
	struct bio	ba_bio;
	int		ba_opcode;

	int		ba_status;	/* only used with get state */
#define BIOC_SADISABLE		0x00	/* disable alarm */
#define BIOC_SAENABLE		0x01	/* enable alarm */
#define BIOC_SASILENCE		0x02	/* silence alarm */
#define BIOC_GASTATUS		0x03	/* get status */
#define BIOC_SATEST		0x04	/* test alarm */
};

#define BIOCBLINK _IOWR('B', 36, struct bioc_blink)
struct bioc_blink {
	struct bio	bb_bio;
	u_int16_t	bb_channel;
	u_int16_t	bb_target;

	int		bb_status;	/* current status */
#define BIOC_SBUNBLINK		0x00	/* disable blinking */
#define BIOC_SBBLINK		0x01	/* enable blink */
#define BIOC_SBALARM		0x02	/* enable alarm blink */
};

#define BIOCSETSTATE _IOWR('B', 37, struct bioc_setstate)
struct bioc_setstate {
	struct bio	bs_bio;
	u_int16_t	bs_channel;
	u_int16_t	bs_target;
	u_int16_t	bs_lun;
	u_int16_t	bs_other_id_type; /* use other_id instead of ctl */
#define BIOC_SSOTHER_UNUSED	0x00
#define BIOC_SSOTHER_DEVT	0x01
	int		bs_other_id;	/* cram dev_t or other id in here */

	int		bs_status;	/* change to this status */
#define BIOC_SSONLINE		0x00	/* online disk */
#define BIOC_SSOFFLINE		0x01	/* offline disk */
#define BIOC_SSHOTSPARE		0x02	/* mark as hotspare */
#define BIOC_SSREBUILD		0x03	/* rebuild on this disk */
	int		bs_volid;	/* volume id for rebuild */
};

#define BIOCCREATERAID _IOWR('B', 38, struct bioc_createraid)
struct bioc_createraid {
	struct bio	bc_bio;
	void		*bc_dev_list;
	u_int16_t	bc_dev_list_len;
	int32_t		bc_key_disk;
#define BIOC_CRMAXLEN		1024
	u_int16_t	bc_level;
	u_int32_t	bc_flags;
#define BIOC_SCFORCE		0x01	/* do not assemble, force create */
#define BIOC_SCDEVT		0x02	/* dev_t array or string in dev_list */
#define BIOC_SCNOAUTOASSEMBLE	0x04	/* do not assemble during autoconf */
#define BIOC_SCBOOTABLE		0x08	/* device is bootable */
	u_int32_t	bc_opaque_size;
	u_int32_t	bc_opaque_flags;
#define	BIOC_SOINVALID		0x00	/* no opaque pointer */
#define	BIOC_SOIN		0x01	/* kernel perspective direction */
#define BIOC_SOOUT		0x02	/* kernel perspective direction */
	u_int32_t	bc_opaque_status;
#define	BIOC_SOINOUT_FAILED	0x00	/* operation failed */
#define	BIOC_SOINOUT_OK		0x01	/* operation succeeded */
	void		*bc_opaque;
};

#define BIOCDELETERAID _IOWR('B', 39, struct bioc_deleteraid)
struct bioc_deleteraid {
	struct bio	bd_bio;
	u_int32_t	bd_flags;
#define BIOC_SDCLEARMETA	0x01	/* clear metadata region */
	char		bd_dev[16];	/* device */
};

#define BIOCDISCIPLINE _IOWR('B', 40, struct bioc_discipline)
struct bioc_discipline {
	struct bio	bd_bio;
	char		bd_dev[16];
	u_int32_t	bd_cmd;
	u_int32_t	bd_size;
	void		*bd_data;
};

#define BIOCINSTALLBOOT _IOWR('B', 41, struct bioc_installboot)
struct bioc_installboot {
	struct bio	bb_bio;
	char		bb_dev[16];
	void		*bb_bootblk;
	void		*bb_bootldr;
	u_int32_t	bb_bootblk_size;
	u_int32_t	bb_bootldr_size;
};

#define BIOCPATROL _IOWR('B', 42, struct bioc_patrol)
struct bioc_patrol {
	struct bio	bp_bio;
	int		bp_opcode;
#define BIOC_SPSTOP		0x00	/* stop patrol */
#define BIOC_SPSTART		0x01	/* start patrol */
#define BIOC_GPSTATUS		0x02	/* get status */
#define BIOC_SPDISABLE		0x03	/* disable patrol */
#define BIOC_SPAUTO		0x04	/* enable patrol as auto */
#define BIOC_SPMANUAL		0x05	/* enable patrol as manual */

	int		bp_mode;
#define	BIOC_SPMAUTO		0x00
#define	BIOC_SPMMANUAL		0x01
#define BIOC_SPMDISABLED	0x02
	int		bp_status;	/* only used with get state */
#define	BIOC_SPSSTOPPED		0x00
#define	BIOC_SPSREADY		0x01
#define BIOC_SPSACTIVE		0x02
#define BIOC_SPSABORTED		0xff

	int		bp_autoival;
	int		bp_autonext;
	int		bp_autonow;
};

/* kernel and userspace defines */
#define BIOC_INQ		0x0001
#define BIOC_DISK		0x0002
#define BIOC_VOL		0x0004
#define BIOC_ALARM		0x0008
#define BIOC_BLINK		0x0010
#define BIOC_SETSTATE		0x0020
#define BIOC_CREATERAID		0x0040
#define BIOC_DELETERAID		0x0080
#define BIOC_DISCIPLINE		0x0100
#define BIOC_INSTALLBOOT	0x0200
#define BIOC_PATROL		0x0400

/* user space defines */
#define BIOC_DEVLIST		0x10000

#ifdef _KERNEL
int	bio_register(struct device *, int (*)(struct device *, u_long,
	    caddr_t));
void	bio_unregister(struct device *);

void	bio_status_init(struct bio_status *, struct device *);
void	bio_status(struct bio_status *, int, int, const char *, va_list *);

void	bio_info(struct bio_status *, int, const char *, ...);
void	bio_warn(struct bio_status *, int, const char *, ...);
void	bio_error(struct bio_status *, int, const char *, ...);
#endif


code: src/sys/dev/cardbus

path: sys/dev/cardbus/CVS/Repository


code:
/*	$OpenBSD: cardbus.c,v 1.50 2015/03/14 03:38:47 jsg Exp $	*/
/*	$NetBSD: cardbus.c,v 1.24 2000/04/02 19:11:37 mycroft Exp $	*/

/*
 * Copyright (c) 1997, 1998, 1999 and 2000
 *     HAYAKAWA Koichi.  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.
 *
 *
 * 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/systm.h>
#include <sys/device.h>
#include <sys/malloc.h>
#include <sys/kernel.h>

#include <machine/bus.h>

#include <dev/cardbus/cardbusvar.h>
#include <dev/pci/pcidevs.h>

#include <dev/cardbus/cardbus_exrom.h>

#include <dev/pci/pcivar.h>	/* XXX */
#include <dev/pci/pcireg.h>	/* XXX */

#include <dev/pcmcia/pcmciareg.h>

#ifdef CARDBUS_DEBUG
#define STATIC
#define DPRINTF(a) printf a
#else
#ifdef DDB
#define STATIC
#else
#define STATIC static
#endif
#define DPRINTF(a)
#endif

STATIC void cardbusattach(struct device *, struct device *, void *);
/* STATIC int cardbusprint(void *, const char *); */

STATIC int cardbusmatch(struct device *, void *, void *);
STATIC int cardbussubmatch(struct device *, void *, void *);
STATIC int cardbusprint(void *, const char *);

typedef void (*tuple_decode_func)(u_int8_t *, int, void *);

STATIC int decode_tuples(u_int8_t *, int, tuple_decode_func, void *);
STATIC void parse_tuple(u_int8_t *, int, void *);
#ifdef CARDBUS_DEBUG
static void print_tuple(u_int8_t *, int, void *);
#endif

STATIC int cardbus_read_tuples(struct cardbus_attach_args *,
    pcireg_t, u_int8_t *, size_t);

STATIC void enable_function(struct cardbus_softc *, int, int);
STATIC void disable_function(struct cardbus_softc *, int);

struct cfattach cardbus_ca = {
	sizeof(struct cardbus_softc), cardbusmatch, cardbusattach
};

struct cfdriver cardbus_cd = {
	NULL, "cardbus", DV_DULL
};

STATIC int
cardbusmatch(struct device *parent, void *match, void *aux)
{
	struct cfdata *cf = match;
	struct cbslot_attach_args *cba = aux;

	if (strcmp(cba->cba_busname, cf->cf_driver->cd_name)) {
		DPRINTF(("cardbusmatch: busname differs %s <=> %s\n",
		    cba->cba_busname, cf->cf_driver->cd_name));
		return (0);
	}

	return (1);
}

STATIC void
cardbusattach(struct device *parent, struct device *self, void *aux)
{
	struct cardbus_softc *sc = (void *)self;
	struct cbslot_attach_args *cba = aux;
	int cdstatus;

	sc->sc_bus = cba->cba_bus;
	sc->sc_device = 0;
	sc->sc_intrline = cba->cba_intrline;
	sc->sc_cacheline = cba->cba_cacheline;
	sc->sc_lattimer = cba->cba_lattimer;

	printf(": bus %d device %d", sc->sc_bus, sc->sc_device);
	printf(" cacheline 0x%x, lattimer 0x%x\n",
	    sc->sc_cacheline,sc->sc_lattimer);

	sc->sc_iot = cba->cba_iot;	/* CardBus I/O space tag */
	sc->sc_memt = cba->cba_memt;	/* CardBus MEM space tag */
	sc->sc_dmat = cba->cba_dmat;	/* DMA tag */
	sc->sc_cc = cba->cba_cc;
	sc->sc_pc = cba->cba_pc;
	sc->sc_cf = cba->cba_cf;
	sc->sc_rbus_iot = cba->cba_rbus_iot;
	sc->sc_rbus_memt = cba->cba_rbus_memt;

	cdstatus = 0;
}

STATIC int
cardbus_read_tuples(struct cardbus_attach_args *ca, pcireg_t cis_ptr,
    u_int8_t *tuples, size_t len)
{
	struct cardbus_softc *sc = ca->ca_ct->ct_sc;
	pci_chipset_tag_t pc = ca->ca_pc;
	pcitag_t tag = ca->ca_tag;
	pcireg_t command;
	int found = 0;

	int i, j;
	int cardbus_space = cis_ptr & CARDBUS_CIS_ASIMASK;
	bus_space_tag_t bar_tag;
	bus_space_handle_t bar_memh;
	bus_size_t bar_size;
	bus_addr_t bar_addr;

	int reg;

	memset(tuples, 0, len);

	cis_ptr = cis_ptr & CARDBUS_CIS_ADDRMASK;

	switch (cardbus_space) {
	case CARDBUS_CIS_ASI_TUPLE:
		DPRINTF(("%s: reading CIS data from configuration space\n",
		    sc->sc_dev.dv_xname));
		for (i = cis_ptr, j = 0; i < 0xff; i += 4) {
			u_int32_t e = pci_conf_read(pc, tag, i);
			tuples[j] = 0xff & e;
			e >>= 8;
			tuples[j + 1] = 0xff & e;
			e >>= 8;
			tuples[j + 2] = 0xff & e;
			e >>= 8;
			tuples[j + 3] = 0xff & e;
			j += 4;
		}
		found++;
		break;

	case CARDBUS_CIS_ASI_BAR0:
	case CARDBUS_CIS_ASI_BAR1:
	case CARDBUS_CIS_ASI_BAR2:
	case CARDBUS_CIS_ASI_BAR3:
	case CARDBUS_CIS_ASI_BAR4:
	case CARDBUS_CIS_ASI_BAR5:
	case CARDBUS_CIS_ASI_ROM:
		if (cardbus_space == CARDBUS_CIS_ASI_ROM) {
			reg = CARDBUS_ROM_REG;
			DPRINTF(("%s: reading CIS data from ROM\n",
			    sc->sc_dev.dv_xname));
		} else {
			reg = CARDBUS_BASE0_REG + (cardbus_space - 1) * 4;
			DPRINTF(("%s: reading CIS data from BAR%d\n",
			    sc->sc_dev.dv_xname, cardbus_space - 1));
		}

		/* XXX zero register so mapreg_map doesn't get confused by old
		   contents */
		pci_conf_write(pc, tag, reg, 0);
		if (Cardbus_mapreg_map(ca->ca_ct, reg,
		    PCI_MAPREG_TYPE_MEM | PCI_MAPREG_MEM_TYPE_32BIT, 0,
		    &bar_tag, &bar_memh, &bar_addr, &bar_size)) {
			printf("%s: can't map memory\n",
			    sc->sc_dev.dv_xname);
			return (1);
		}

		if (cardbus_space == CARDBUS_CIS_ASI_ROM) {
			pcireg_t exrom;
			int save;
			struct cardbus_rom_image_head rom_image;
			struct cardbus_rom_image *p;

			save = splhigh();
			/* enable rom address decoder */
			exrom = pci_conf_read(pc, tag, reg);
			pci_conf_write(pc, tag, reg, exrom | 1);

			command = pci_conf_read(pc, tag,
			    PCI_COMMAND_STATUS_REG);
			pci_conf_write(pc, tag,
			    PCI_COMMAND_STATUS_REG,
			    command | PCI_COMMAND_MEM_ENABLE);

			if (cardbus_read_exrom(ca->ca_memt, bar_memh,
			    &rom_image))
				goto out;

			for (p = SIMPLEQ_FIRST(&rom_image); p;
			    p = SIMPLEQ_NEXT(p, next)) {
				if (p->rom_image ==
				    CARDBUS_CIS_ASI_ROM_IMAGE(cis_ptr)) {
					bus_space_read_region_1(p->romt,
					    p->romh, CARDBUS_CIS_ADDR(cis_ptr),
					    tuples, MIN(p->image_size, len));
					found++;
					break;
				}
			}

		out:
			while ((p = SIMPLEQ_FIRST(&rom_image)) != NULL) {
				SIMPLEQ_REMOVE_HEAD(&rom_image, next);
				free(p, M_DEVBUF, 0);
			}
			exrom = pci_conf_read(pc, tag, reg);
			pci_conf_write(pc, tag, reg, exrom & ~1);
			splx(save);
		} else {
			command = pci_conf_read(pc, tag,
			    PCI_COMMAND_STATUS_REG);
			pci_conf_write(pc, tag,
			    PCI_COMMAND_STATUS_REG,
    			    command | PCI_COMMAND_MEM_ENABLE);
			/* XXX byte order? */
			bus_space_read_region_1(ca->ca_memt, bar_memh,
			    cis_ptr, tuples, 256);
			found++;
		}
		command = pci_conf_read(pc, tag,
		    PCI_COMMAND_STATUS_REG);
		pci_conf_write(pc, tag, PCI_COMMAND_STATUS_REG,
		    command & ~PCI_COMMAND_MEM_ENABLE);
		pci_conf_write(pc, tag, reg, 0);

		Cardbus_mapreg_unmap(ca->ca_ct, reg, bar_tag, bar_memh,
		    bar_size);
		break;

#ifdef DIAGNOSTIC
		default:
			panic("%s: bad CIS space (%d)", sc->sc_dev.dv_xname,
			    cardbus_space);
#endif
	}
	return (!found);
}

STATIC void
parse_tuple(u_int8_t *tuple, int len, void *data)
{
	struct cardbus_cis_info *cis = data;
	int bar_index;
	int i;
	char *p;

	switch (tuple[0]) {
	case PCMCIA_CISTPL_MANFID:
		if (tuple[1] < 4) {
			DPRINTF(("%s: wrong length manufacturer id (%d)\n",
			    __func__, tuple[1]));
			break;
		}
		cis->manufacturer = tuple[2] | (tuple[3] << 8);
		cis->product = tuple[4] | (tuple[5] << 8);
		break;
	case PCMCIA_CISTPL_VERS_1:
		bcopy(tuple + 2, cis->cis1_info_buf, tuple[1]);
		i = 0;
		p = cis->cis1_info_buf + 2;
		while (i <
		    sizeof(cis->cis1_info) / sizeof(cis->cis1_info[0])) {
			if (p >= cis->cis1_info_buf + tuple[1] || *p == '\xff')
				break;
			cis->cis1_info[i++] = p;
			while (*p != '\0' && *p != '\xff')
				p++;
			if (*p == '\0')
				p++;
		}
		break;
	case PCMCIA_CISTPL_BAR:
		if (tuple[1] != 6) {
			DPRINTF(("%s: BAR with short length (%d)\n",
			    __func__, tuple[1]));
			break;
		}
		bar_index = tuple[2] & 7;
		if (bar_index == 0) {
			DPRINTF(("%s: invalid ASI in BAR tuple\n",
			    __func__));
			break;
		}
		bar_index--;
		cis->bar[bar_index].flags = tuple[2];
		cis->bar[bar_index].size = (tuple[4] << 0) |
		    (tuple[5] << 8) | (tuple[6] << 16) | (tuple[7] << 24);
		break;
    case PCMCIA_CISTPL_FUNCID:
		cis->funcid = tuple[2];
		break;

    case PCMCIA_CISTPL_FUNCE:
		switch (cis->funcid) {
		case PCMCIA_FUNCTION_SERIAL:
			if (tuple[1] >= 2 &&
			    tuple[2] == 0
			    /* XXX PCMCIA_TPLFE_TYPE_SERIAL_??? */) {
				cis->funce.serial.uart_type = tuple[3] & 0x1f;
				cis->funce.serial.uart_present = 1;
			}
			break;
		case PCMCIA_FUNCTION_NETWORK:
			if (tuple[1] >= 8 && tuple[2] ==
			    PCMCIA_TPLFE_TYPE_LAN_NID) {
				if (tuple[3] >
				    sizeof(cis->funce.network.netid)) {
					DPRINTF(("%s: unknown network id type"
					    " (len = %d)\n", __func__,
					    tuple[3]));
				} else {
					cis->funce.network.netid_present = 1;
					bcopy(tuple + 4,
					    cis->funce.network.netid, tuple[3]);
				}
			}
		}
		break;
	}
}

/*
 * int cardbus_attach_card(struct cardbus_softc *sc)
 *
 *    This function attaches the card on the slot: turns on power,
 *    reads and analyses tuple, sets configuration index.
 *
 *    This function returns the number of recognised device functions.
 *    If no functions are recognised, return 0.
 */
int
cardbus_attach_card(struct cardbus_softc *sc)
{
	cardbus_chipset_tag_t cc;
	cardbus_function_tag_t cf;
	int cdstatus;
	pcitag_t tag;
	pcireg_t id, class, cis_ptr;
	pcireg_t bhlc;
	u_int8_t *tuple;
	int function, nfunction;
	struct device *csc;
	int no_work_funcs = 0;
	cardbus_devfunc_t ct;
	pci_chipset_tag_t pc = sc->sc_pc;
	int i;

	cc = sc->sc_cc;
	cf = sc->sc_cf;

	DPRINTF(("cardbus_attach_card: cb%d start\n", sc->sc_dev.dv_unit));

	/* inspect initial voltage */
	if (0 == (cdstatus = (cf->cardbus_ctrl)(cc, CARDBUS_CD))) {
		DPRINTF(("cardbusattach: no CardBus card on cb%d\n",
		    sc->sc_dev.dv_unit));
		return (0);
	}

	/* XXX use fake function 8 to keep power on during whole configuration */
	enable_function(sc, cdstatus, 8);

	function = 0;

	tag = pci_make_tag(pc, sc->sc_bus, sc->sc_device, function);

	/* Wait until power comes up.  Maximum 500 ms. */
	for (i = 0; i < 5; ++i) {
		id = pci_conf_read(pc, tag, PCI_ID_REG);
		if (id != 0xffffffff && id != 0)
			break;
		if (cold) {	/* before kernel thread invoked */
			delay(100*1000);
		} else {	/* thread context */
			if (tsleep((void *)sc, PCATCH, "cardbus",
			    hz/10) != EWOULDBLOCK) {
				break;
			}
		}
	}
	if (i == 5)
		return (0);

	bhlc = pci_conf_read(pc, tag, PCI_BHLC_REG);
	DPRINTF(("%s bhlc 0x%08x -> ", sc->sc_dev.dv_xname, bhlc));
	nfunction = PCI_HDRTYPE_MULTIFN(bhlc) ? 8 : 1;

	tuple = malloc(2048, M_TEMP, M_NOWAIT);
	if (tuple == NULL)
		panic("no room for cardbus tuples");

	for (function = 0; function < nfunction; function++) {
		struct cardbus_attach_args ca;

		tag = pci_make_tag(pc, sc->sc_bus, sc->sc_device,
		    function);

		id = pci_conf_read(pc, tag, PCI_ID_REG);
		class = pci_conf_read(pc, tag, PCI_CLASS_REG);
		cis_ptr = pci_conf_read(pc, tag, CARDBUS_CIS_REG);

		/* Invalid vendor ID value? */
		if (PCI_VENDOR(id) == PCI_VENDOR_INVALID)
			continue;

		DPRINTF(("cardbus_attach_card: Vendor 0x%x, Product 0x%x, "
		    "CIS 0x%x\n", PCI_VENDOR(id), PCI_PRODUCT(id),
		    cis_ptr));

		enable_function(sc, cdstatus, function);

		/* clean up every BAR */
		pci_conf_write(pc, tag, CARDBUS_BASE0_REG, 0);
		pci_conf_write(pc, tag, CARDBUS_BASE1_REG, 0);
		pci_conf_write(pc, tag, CARDBUS_BASE2_REG, 0);
		pci_conf_write(pc, tag, CARDBUS_BASE3_REG, 0);
		pci_conf_write(pc, tag, CARDBUS_BASE4_REG, 0);
		pci_conf_write(pc, tag, CARDBUS_BASE5_REG, 0);
		pci_conf_write(pc, tag, CARDBUS_ROM_REG, 0);

		/* set initial latency and cacheline size */
		bhlc = pci_conf_read(pc, tag, PCI_BHLC_REG);
		DPRINTF(("%s func%d bhlc 0x%08x -> ", sc->sc_dev.dv_xname,
		    function, bhlc));
		bhlc &= ~((PCI_LATTIMER_MASK << PCI_LATTIMER_SHIFT) |
		    (PCI_CACHELINE_MASK << PCI_CACHELINE_SHIFT));
		bhlc |= ((sc->sc_cacheline & PCI_CACHELINE_MASK) <<
		    PCI_CACHELINE_SHIFT);
		bhlc |= ((sc->sc_lattimer & PCI_LATTIMER_MASK) <<
		    PCI_LATTIMER_SHIFT);

		pci_conf_write(pc, tag, PCI_BHLC_REG, bhlc);
		bhlc = pci_conf_read(pc, tag, PCI_BHLC_REG);
		DPRINTF(("0x%08x\n", bhlc));

		if (PCI_LATTIMER(bhlc) < 0x10) {
			bhlc &= ~(PCI_LATTIMER_MASK <<
			    PCI_LATTIMER_SHIFT);
			bhlc |= (0x10 << PCI_LATTIMER_SHIFT);
			pci_conf_write(pc, tag, PCI_BHLC_REG,
			    bhlc);
		}

		/*
		 * We need to allocate the ct here, since we might
		 * need it when reading the CIS
		 */
		if ((ct =
		    (cardbus_devfunc_t)malloc(sizeof(struct cardbus_devfunc),
		    M_DEVBUF, M_NOWAIT)) == NULL)
			panic("no room for cardbus_tag");

		ct->ct_cc = sc->sc_cc;
		ct->ct_cf = sc->sc_cf;
		ct->ct_bus = sc->sc_bus;
		ct->ct_dev = sc->sc_device;
		ct->ct_func = function;
		ct->ct_sc = sc;
		sc->sc_funcs[function] = ct;

		memset(&ca, 0, sizeof(ca));

		ca.ca_unit = sc->sc_dev.dv_unit;
		ca.ca_ct = ct;

		ca.ca_iot = sc->sc_iot;
		ca.ca_memt = sc->sc_memt;
		ca.ca_dmat = sc->sc_dmat;
		ca.ca_rbus_iot = sc->sc_rbus_iot;
		ca.ca_rbus_memt = sc->sc_rbus_memt;
		ca.ca_tag = tag;
		ca.ca_bus = sc->sc_bus;
		ca.ca_device = sc->sc_device;
		ca.ca_function = function;
		ca.ca_id = id;
		ca.ca_class = class;
		ca.ca_pc = sc->sc_pc;

		ca.ca_intrline = sc->sc_intrline;

		if (cis_ptr != 0) {
			if (cardbus_read_tuples(&ca, cis_ptr, tuple, 2048)) {
				printf("cardbus_attach_card: failed to "
				    "read CIS\n");
			} else {
#ifdef CARDBUS_DEBUG
				decode_tuples(tuple, 2048, print_tuple, NULL);
#endif
				decode_tuples(tuple, 2048, parse_tuple,
				    &ca.ca_cis);
			}
		}

		if ((csc = config_found_sm((void *)sc, &ca, cardbusprint,
		    cardbussubmatch)) == NULL) {
			/* do not match */
			disable_function(sc, function);
			sc->sc_funcs[function] = NULL;
			free(ct, M_DEVBUF, 0);
		} else {
			/* found */
			ct->ct_device = csc;
			++no_work_funcs;
		}
	}
	/*
	 * XXX power down pseudo function 8 (this will power down the card
	 * if no functions were attached).
	 */
	disable_function(sc, 8);
	free(tuple, M_TEMP, 0);

	return (no_work_funcs);
}

STATIC int
cardbussubmatch(struct device *parent, void *match, void *aux)
{
	struct cfdata *cf = match;
	struct cardbus_attach_args *ca = aux;

	if (cf->cardbuscf_dev != CARDBUS_UNK_DEV &&
		cf->cardbuscf_dev != ca->ca_unit) {
		return (0);
	}
	if (cf->cardbuscf_function != CARDBUS_UNK_FUNCTION &&
	    cf->cardbuscf_function != ca->ca_function) {
		return (0);
	}

	return ((*cf->cf_attach->ca_match)(parent, cf, aux));
}

STATIC int
cardbusprint(void *aux, const char *pnp)
{
	struct cardbus_attach_args *ca = aux;
	char devinfo[256];

	if (pnp) {
		pci_devinfo(ca->ca_id, ca->ca_class, 1, devinfo,
		    sizeof(devinfo));
		printf("%s at %s", devinfo, pnp);
	}
	printf(" dev %d function %d", ca->ca_device, ca->ca_function);
	if (!pnp) {
		pci_devinfo(ca->ca_id, ca->ca_class, 0, devinfo,
		    sizeof(devinfo));
		printf(" %s", devinfo);
	}

	return (UNCONF);
}

/*
 * void cardbus_detach_card(struct cardbus_softc *sc)
 *
 *    This function detaches the card on the slot: detach device data
 *    structure and turns off the power.
 *
 *    This function must not be called under interrupt context.
 */
void
cardbus_detach_card(struct cardbus_softc *sc)
{
	struct cardbus_devfunc *ct;
	int f;

	for (f = 0; f < 8; f++) {
		ct = sc->sc_funcs[f];
		if (ct == NULL)
			continue;

		DPRINTF(("%s: detaching %s\n", sc->sc_dev.dv_xname,
		    ct->ct_device->dv_xname));

		if (config_detach(ct->ct_device, 0) != 0) {
			printf("%s: cannot detach dev %s, function %d\n",
			    sc->sc_dev.dv_xname, ct->ct_device->dv_xname,
			    ct->ct_func);
		} else {
			sc->sc_poweron_func &= ~(1 << ct->ct_func);
			sc->sc_funcs[ct->ct_func] = NULL;
			free(ct, M_DEVBUF, 0);
		}
	}

	sc->sc_poweron_func = 0;
	sc->sc_cf->cardbus_power(sc->sc_cc, CARDBUS_VCC_0V | CARDBUS_VPP_0V);
}

/*
 * void *cardbus_intr_establish(cc, cf, irq, level, func, arg, name)
 *   Interrupt handler of pccard.
 *  args:
 *   cardbus_chipset_tag_t *cc
 *   int irq:
 */
void *
cardbus_intr_establish(cardbus_chipset_tag_t cc, cardbus_function_tag_t cf,
    cardbus_intr_handle_t irq, int level, int (*func)(void *), void *arg,
    const char *name)
{
	DPRINTF(("- cardbus_intr_establish: irq %d\n", irq));

	return (*cf->cardbus_intr_establish)(cc, irq, level, func, arg, name);
}

/*
 * void cardbus_intr_disestablish(cc, cf, handler)
 *   Interrupt handler of pccard.
 *  args:
 *   cardbus_chipset_tag_t *cc
 */
void
cardbus_intr_disestablish(cardbus_chipset_tag_t cc, cardbus_function_tag_t cf,
    void *handler)
{
	DPRINTF(("- pccard_intr_disestablish\n"));

	(*cf->cardbus_intr_disestablish)(cc, handler);
}

/* XXX this should be merged with cardbus_function_{enable,disable},
   but we don't have a ct when these functions are called */

STATIC void
enable_function(struct cardbus_softc *sc, int cdstatus, int function)
{
	if (sc->sc_poweron_func == 0) {
		/* switch to 3V and/or wait for power to stabilize */
		if (cdstatus & CARDBUS_3V_CARD) {
			sc->sc_cf->cardbus_power(sc->sc_cc, CARDBUS_VCC_3V);
		} else {
			/* No cards other than 3.3V cards. */
			return;
		}
		(sc->sc_cf->cardbus_ctrl)(sc->sc_cc, CARDBUS_RESET);
	}
	sc->sc_poweron_func |= (1 << function);
}

STATIC void
disable_function(struct cardbus_softc *sc, int function)
{
	sc->sc_poweron_func &= ~(1 << function);
	if (sc->sc_poweron_func == 0) {
		/* power-off because no functions are enabled */
		sc->sc_cf->cardbus_power(sc->sc_cc, CARDBUS_VCC_0V);
	}
}

/*
 * int cardbus_function_enable(struct cardbus_softc *sc, int func)
 *
 *   This function enables a function on a card.  When no power is
 *  applied on the card, power will be applied on it.
 */
int
cardbus_function_enable(struct cardbus_softc *sc, int func)
{
	pci_chipset_tag_t pc = sc->sc_pc;
	pcireg_t command;
	pcitag_t tag;

	DPRINTF(("entering cardbus_function_enable...  "));

	/* entering critical area */

	/* XXX: sc_vold should be used */
	enable_function(sc, CARDBUS_3V_CARD, func);

	/* exiting critical area */

	tag = pci_make_tag(pc, sc->sc_bus, sc->sc_device, func);

	command = pci_conf_read(pc, tag, PCI_COMMAND_STATUS_REG);
	command |= (PCI_COMMAND_MEM_ENABLE | PCI_COMMAND_IO_ENABLE |
	    PCI_COMMAND_MASTER_ENABLE); /* XXX: good guess needed */

	pci_conf_write(pc, tag, PCI_COMMAND_STATUS_REG, command);

	DPRINTF(("%x\n", sc->sc_poweron_func));

	return (0);
}

/*
 * int cardbus_function_disable(struct cardbus_softc *, int func)
 *
 *   This function disable a function on a card.  When no functions are
 *  enabled, it turns off the power.
 */
int
cardbus_function_disable(struct cardbus_softc *sc, int func)
{
	DPRINTF(("entering cardbus_function_disable...  "));

	disable_function(sc, func);

	return (0);
}

int
cardbus_matchbyid(struct cardbus_attach_args *ca,
    const struct pci_matchid *ids, int nent)
{
	const struct pci_matchid *pm;
	int i;

	for (i = 0, pm = ids; i < nent; i++, pm++)
		if (PCI_VENDOR(ca->ca_id) == pm->pm_vid &&
		    PCI_PRODUCT(ca->ca_id) == pm->pm_pid)
			return (1);
	return (0);
}

/*
 * below this line, there are some functions for decoding tuples.
 * They should go out from this file.
 */

STATIC u_int8_t *
decode_tuple(u_int8_t *, u_int8_t *, tuple_decode_func, void *);

STATIC int
decode_tuples(u_int8_t *tuple, int buflen, tuple_decode_func func, void *data)
{
	u_int8_t *tp = tuple;

	if (PCMCIA_CISTPL_LINKTARGET != *tuple) {
		DPRINTF(("WRONG TUPLE: 0x%x\n", *tuple));
		return (0);
	}

	while ((tp = decode_tuple(tp, tuple + buflen, func, data)) != NULL)
		;

	return (1);
}

STATIC u_int8_t *
decode_tuple(u_int8_t *tuple, u_int8_t *end, tuple_decode_func func,
    void *data)
{
	u_int8_t type;
	u_int8_t len;

	type = tuple[0];
	switch (type) {
	case PCMCIA_CISTPL_NULL:
	case PCMCIA_CISTPL_END:
		len = 1;
		break;
	default:
		if (tuple + 2 > end)
			return (NULL);
		len = tuple[1] + 2;
		break;
	}

	if (tuple + len > end)
		return (NULL);

	(*func)(tuple, len, data);

	if (PCMCIA_CISTPL_END == type || tuple + len == end)
		return (NULL);

	return (tuple + len);
}

#ifdef CARDBUS_DEBUG
static char *tuple_name(int type);

static char *
tuple_name(int type)
{
	static char *tuple_name_s [] = {
	    "TPL_NULL", "TPL_DEVICE", "Reserved", "Reserved",	  /* 0-3 */
	    "CONFIG_CB", "CFTABLE_ENTRY_CB", "Reserved", "BAR",	  /* 4-7 */
	    "Reserved", "Reserved", "Reserved", "Reserved",	  /* 8-B */
	    "Reserved", "Reserved", "Reserved", "Reserved",	  /* C-F */
	    "CHECKSUM", "LONGLINK_A", "LONGLINK_C", "LINKTARGET", /* 10-13 */
	    "NO_LINK", "VERS_1", "ALTSTR", "DEVICE_A",		  /* 14-17 */
	    "JEDEC_C", "JEDEC_A", "CONFIG", "CFTABLE_ENTRY",	  /* 18-1B */
	    "DEVICE_OC", "DEVICE_OA", "DEVICE_GEO",		  /* 1C-1E */
	    "DEVICE_GEO_A", "MANFID", "FUNCID", "FUNCE", "SWIL",  /* 1F-23 */
	    "Reserved", "Reserved", "Reserved", "Reserved",	  /* 24-27 */
	    "Reserved", "Reserved", "Reserved", "Reserved",	  /* 28-2B */
	    "Reserved", "Reserved", "Reserved", "Reserved",	  /* 2C-2F */
	    "Reserved", "Reserved", "Reserved", "Reserved",	  /* 30-33 */
	    "Reserved", "Reserved", "Reserved", "Reserved",	  /* 34-37 */
	    "Reserved", "Reserved", "Reserved", "Reserved",	  /* 38-3B */
	    "Reserved", "Reserved", "Reserved", "Reserved",	  /* 3C-3F */
	    "VERS_2", "FORMAT", "GEOMETRY", "BYTEORDER",	  /* 40-43 */
	    "DATE", "BATTERY", "ORG", "FORMAT_A"		  /* 44-47 */
	};

	if (type > 0 && type < nitems(tuple_name_s))
		return (tuple_name_s[type]);
	else if (0xff == type)
		return ("END");
	else
		return ("Reserved");
}

static void
print_tuple(u_int8_t *tuple, int len, void *data)
{
	int i;

	printf("tuple: %s len %d\n", tuple_name(tuple[0]), len);

	for (i = 0; i < len; ++i) {
		if (i % 16 == 0)
			printf("  0x%02x:", i);
		printf(" %x",tuple[i]);
		if (i % 16 == 15)
			printf("\n");
	}
	if (i % 16 != 0)
		printf("\n");
}
#endif


code:
/*	$OpenBSD: cardbus_exrom.c,v 1.6 2014/07/12 18:48:17 tedu Exp $	*/
/*	$NetBSD: cardbus_exrom.c,v 1.4 2000/02/03 06:47:31 thorpej Exp $	*/

/*
 * Copyright (c) 1999 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to
 * The NetBSD Foundation by Johan Danielsson.
 *
 * 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.
 */

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

#include <machine/bus.h>

#include <dev/cardbus/cardbus_exrom.h>

#if defined(CARDBUS_DEBUG)
#define	DPRINTF(a)	printf a
#else
#define	DPRINTF(a)
#endif

#define READ_INT16(T, H, O)  \
	(bus_space_read_1((T), (H), (O)) | \
	 (bus_space_read_1((T), (H), (O) + 1) << 8))

/*
 *  A PCI ROM is divided into a number of images. Each image has two
 *  data structures, a header located at the start of the image, and a
 *  `data structure' at some offset into it.
 *
 *  The header is a 26 byte structure:
 *
 *  Offset	Length	Description
 *  0x00	   1	signature byte 1 (0x55)
 *  0x01	   1	signature byte 2 (0xAA)
 *  0x02	  22	processor architecture data
 *  0x18	   2	pointer to the data structure
 *
 *  The data structure is a 24 byte structure:
 *
 *  Offset	Length	Description
 *  0x00	   4	signature (PCIR)
 *  0x04	   2	vendor id
 *  0x06	   2	device id
 *  0x08	   2	reserved
 *  0x0A	   2	data structure length
 *  0x0C	   1	data structure revision (0)
 *  0x0D	   3	class code
 *  0x10	   2	image length (in 512 byte blocks)
 *  0x12	   2	code revision level
 *  0x14	   1	code type
 *  0x15	   1	indicator (bit 7 indicates final image)
 *  0x16	   2	reserved
 *
 */

/*
 *  Scan through a PCI expansion ROM, and create subregions for each
 *  ROM image. This function assumes that the ROM is mapped at
 *  (tag,handle), and that the expansion ROM address decoder is
 *  enabled. The PCI specification requires that no other BAR should
 *  be accessed while the ROM is enabled, so interrupts should be
 *  disabled.
 *
 * XXX This routine is way too pessimistic and returns as soon as it encounters
 * a problem, although not being able to malloc or read a particular image
 * may not prevent further images from being read successfully.
 */
int
cardbus_read_exrom(bus_space_tag_t romt, bus_space_handle_t romh,
    struct cardbus_rom_image_head *head)
{
	size_t addr = 0; /* offset of current rom image */
	size_t dataptr;
	unsigned int rom_image = 0;
	size_t image_size;
	struct cardbus_rom_image *image;
	u_int16_t val;

	SIMPLEQ_INIT(head);
	do {
		val = READ_INT16(romt, romh, addr + CARDBUS_EXROM_SIGNATURE);
		if (val != 0xaa55) {
			DPRINTF(("%s: bad header signature in ROM image "
			    "%u: 0x%04x\n", __func__, rom_image, val));
			return (1);
		}
		dataptr = addr + READ_INT16(romt, romh,
		    addr + CARDBUS_EXROM_DATA_PTR);

		/* get the ROM image size, in blocks */
		image_size = READ_INT16(romt, romh,
		    dataptr + CARDBUS_EXROM_DATA_IMAGE_LENGTH);
		/* XXX
		 * Some ROMs seem to have this as zero, can we assume
		 * this means 1 block?
		 */
		if (image_size == 0)
			image_size = 1;
		image_size <<= 9;

		image = malloc(sizeof(*image), M_DEVBUF, M_NOWAIT);
		if (image == NULL) {
			DPRINTF(("%s: out of memory\n", __func__));
			return (1);
		}
		image->rom_image = rom_image;
		image->image_size = image_size;
		image->romt = romt;
		if (bus_space_subregion(romt, romh, addr,
		    image_size, &image->romh)) {
			DPRINTF(("%s: bus_space_subregion failed", __func__));
			free(image, M_DEVBUF, 0);
			return (1);
		}
		SIMPLEQ_INSERT_TAIL(head, image, next);
		addr += image_size;
		rom_image++;
	} while ((bus_space_read_1(romt, romh,
	    dataptr + CARDBUS_EXROM_DATA_INDICATOR) & 0x80) == 0);

	return (0);
}


code:
/*	$OpenBSD: cardbus_exrom.h,v 1.4 2013/06/20 09:52:09 mpi Exp $	*/
/*	$NetBSD: cardbus_exrom.h,v 1.2 1999/12/15 12:28:54 kleink Exp $	*/

/*
 * Copyright (c) 1999 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to
 * The NetBSD Foundation by Johan Danielsson.
 *
 * 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.
 */

#ifndef _DEV_CARDBUS_CARDBUS_EXROM_H_
#define _DEV_CARDBUS_CARDBUS_EXROM_H_

/* PCI ROM header fields */
#define CARDBUS_EXROM_SIGNATURE	0x00
#define CARDBUS_EXROM_DATA_PTR	0x18

/* PCI ROM data structure fields */
#define CARDBUS_EXROM_DATA_SIGNATURE	0x00 /* Signature ("PCIR") */
#define CARDBUS_EXROM_DATA_VENDOR_ID	0x04 /* Vendor Identification */
#define CARDBUS_EXROM_DATA_DEVICE_ID	0x06 /* Device Identification */
#define CARDBUS_EXROM_DATA_LENGTH	0x0a /* PCI Data Structure Length */
#define CARDBUS_EXROM_DATA_REV		0x0c /* PCI Data Structure Revision */
#define CARDBUS_EXROM_DATA_CLASS_CODE	0x0d /* Class Code */
#define CARDBUS_EXROM_DATA_IMAGE_LENGTH	0x10 /* Image Length */
#define CARDBUS_EXROM_DATA_DATA_REV	0x12 /* Revision Level of Code/Data */
#define CARDBUS_EXROM_DATA_CODE_TYPE	0x14 /* Code Type */
#define CARDBUS_EXROM_DATA_INDICATOR	0x15 /* Indicator */

struct cardbus_rom_image {
	unsigned int		rom_image;	/* image number */
	size_t			image_size;
	bus_space_tag_t		romt;
	bus_space_handle_t	romh;		/* subregion */
	SIMPLEQ_ENTRY(cardbus_rom_image) next;
};

SIMPLEQ_HEAD(cardbus_rom_image_head, cardbus_rom_image);

int	cardbus_read_exrom(bus_space_tag_t, bus_space_handle_t,
	    struct cardbus_rom_image_head *);

#endif /* !_DEV_CARDBUS_CARDBUS_EXROM_H_ */