code:
/*	$OpenBSD: vcctty.c,v 1.12 2015/01/25 21:42:13 kettenis Exp $	*/
/*
 * Copyright (c) 2009 Mark Kettenis
 *
 * 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/conf.h>
#include <sys/device.h>
#include <sys/malloc.h>
#include <sys/proc.h>
#include <sys/systm.h>
#include <sys/tty.h>

#include <machine/autoconf.h>
#include <machine/conf.h>
#include <machine/hypervisor.h>
#include <machine/mdesc.h>

#include <dev/cons.h>
#include <sparc64/dev/cbusvar.h>
#include <sparc64/dev/ldcvar.h>

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

#define VCCTTY_TX_ENTRIES	128
#define VCCTTY_RX_ENTRIES	128

struct vcctty_msg {
	uint8_t		type;
	uint8_t		size;
	uint16_t	rsvd;
	uint32_t	ctrl_msg;
	uint8_t		data[56];
};

/* Packet types. */
#define LDC_CONSOLE_CTRL	0x01
#define LDC_CONSOLE_DATA	0x02

struct vcctty_softc {
	struct device	sc_dv;
	bus_space_tag_t	sc_bustag;
	bus_dma_tag_t	sc_dmatag;

	uint64_t	sc_tx_ino;
	uint64_t	sc_rx_ino;
	void		*sc_tx_ih;
	void		*sc_rx_ih;

	struct ldc_conn	sc_lc;

	struct tty	*sc_tty;
};

int	vcctty_match(struct device *, void *, void *);
void	vcctty_attach(struct device *, struct device *, void *);

struct cfattach vcctty_ca = {
	sizeof(struct vcctty_softc), vcctty_match, vcctty_attach
};

struct cfdriver vcctty_cd = {
	NULL, "vcctty", DV_DULL
};

int	vcctty_tx_intr(void *);
int	vcctty_rx_intr(void *);

void	vcctty_send_data(struct vcctty_softc *, struct tty *);
void	vcctty_send_break(struct vcctty_softc *);

void	vccttystart(struct tty *);
int	vccttyparam(struct tty *, struct termios *);
int	vccttyhwiflow(struct tty *, int);

int
vcctty_match(struct device *parent, void *match, void *aux)
{
	return (1);
}

void
vcctty_attach(struct device *parent, struct device *self, void *aux)
{
	struct vcctty_softc *sc = (struct vcctty_softc *)self;
	struct cbus_attach_args *ca = aux;
	struct ldc_conn *lc;
	int err;

	sc->sc_bustag = ca->ca_bustag;
	sc->sc_dmatag = ca->ca_dmatag;
	sc->sc_tx_ino = ca->ca_tx_ino;
	sc->sc_rx_ino = ca->ca_rx_ino;

	printf(": ivec 0x%llx, 0x%llx", sc->sc_tx_ino, sc->sc_rx_ino);

	/*
	 * Un-configure queues before registering interrupt handlers,
	 * such that we dont get any stale LDC packets or events.
	 */
	hv_ldc_tx_qconf(ca->ca_id, 0, 0);
	hv_ldc_rx_qconf(ca->ca_id, 0, 0);

	sc->sc_tx_ih = bus_intr_establish(ca->ca_bustag, sc->sc_tx_ino,
	    IPL_TTY, 0, vcctty_tx_intr, sc, sc->sc_dv.dv_xname);
	sc->sc_rx_ih = bus_intr_establish(ca->ca_bustag, sc->sc_rx_ino,
	    IPL_TTY, 0, vcctty_rx_intr, sc, sc->sc_dv.dv_xname);
	if (sc->sc_tx_ih == NULL || sc->sc_rx_ih == NULL) {
		printf(", can't establish interrupt\n");
		return;
	}

	lc = &sc->sc_lc;
	lc->lc_id = ca->ca_id;
	lc->lc_sc = sc;

	lc->lc_txq = ldc_queue_alloc(sc->sc_dmatag, VCCTTY_TX_ENTRIES);
	if (lc->lc_txq == NULL) {
		printf(", can't allocate tx queue\n");
		return;
	}

	lc->lc_rxq = ldc_queue_alloc(sc->sc_dmatag, VCCTTY_RX_ENTRIES);
	if (lc->lc_rxq == NULL) {
		printf(", can't allocate rx queue\n");
		goto free_txqueue;
	}

	err = hv_ldc_tx_qconf(lc->lc_id,
	    lc->lc_txq->lq_map->dm_segs[0].ds_addr, lc->lc_txq->lq_nentries);
	if (err != H_EOK)
		printf("%s: hv_ldc_tx_qconf %d\n", __func__, err);

	err = hv_ldc_rx_qconf(lc->lc_id,
	    lc->lc_rxq->lq_map->dm_segs[0].ds_addr, lc->lc_rxq->lq_nentries);
	if (err != H_EOK)
		printf("%s: hv_ldc_rx_qconf %d\n", __func__, err);

	cbus_intr_setenabled(sc->sc_bustag, sc->sc_tx_ino, INTR_ENABLED);
	cbus_intr_setenabled(sc->sc_bustag, sc->sc_rx_ino, INTR_ENABLED);

	printf(" domain \"%s\"\n", ca->ca_name);
	return;

free_txqueue:
	ldc_queue_free(sc->sc_dmatag, lc->lc_txq);
}

int
vcctty_tx_intr(void *arg)
{
	struct vcctty_softc *sc = arg;
	struct ldc_conn *lc = &sc->sc_lc;
	uint64_t tx_head, tx_tail, tx_state;
	int err;

	err = hv_ldc_tx_get_state(lc->lc_id, &tx_head, &tx_tail, &tx_state);
	if (err != H_EOK) {
		printf("%s: hv_ldc_tx_get_state %d\n", __func__, err);
		return (0);
	}

	if (tx_state != lc->lc_tx_state) {
		switch (tx_state) {
		case LDC_CHANNEL_DOWN:
			DPRINTF(("Tx link down\n"));
			break;
		case LDC_CHANNEL_UP:
			DPRINTF(("Tx link up\n"));
			break;
		case LDC_CHANNEL_RESET:
			DPRINTF(("Tx link reset\n"));
			break;
		}
		lc->lc_tx_state = tx_state;
	}

	return (1);
}

int
vcctty_rx_intr(void *arg)
{
	struct vcctty_softc *sc = arg;
	struct tty *tp = sc->sc_tty;
	struct ldc_conn *lc = &sc->sc_lc;
	uint64_t rx_head, rx_tail, rx_state;
	struct vcctty_msg *msg;
	int err;
	int i;

	err = hv_ldc_rx_get_state(lc->lc_id, &rx_head, &rx_tail, &rx_state);
	if (err != H_EOK) {
		printf("%s: hv_ldc_rx_get_state %d\n", __func__, err);
		return (0);
	}

	if (rx_state != lc->lc_rx_state) {
		switch (rx_state) {
		case LDC_CHANNEL_DOWN:
			DPRINTF(("Rx link down\n"));
			break;
		case LDC_CHANNEL_UP:
			DPRINTF(("Rx link up\n"));
			break;
		case LDC_CHANNEL_RESET:
			DPRINTF(("Rx link reset\n"));
			break;
		}
		lc->lc_rx_state = rx_state;
		return (1);
	}

	if (rx_head == rx_tail)
		return (0);

	msg = (struct vcctty_msg *)(lc->lc_rxq->lq_va + rx_head);
	if (tp && msg->type == LDC_CONSOLE_DATA) {
		for (i = 0; i < msg->size; i++) {
			if (tp->t_state & TS_ISOPEN)
				(*linesw[tp->t_line].l_rint)(msg->data[i], tp);
		}
	}

	rx_head += sizeof(*msg);
	rx_head &= ((lc->lc_rxq->lq_nentries * sizeof(*msg)) - 1);
	err = hv_ldc_rx_set_qhead(lc->lc_id, rx_head);
	if (err != H_EOK)
		printf("%s: hv_ldc_rx_set_qhead %d\n", __func__, err);

	return (1);
}

void
vcctty_send_data(struct vcctty_softc *sc, struct tty *tp)
{
	struct ldc_conn *lc = &sc->sc_lc;
	uint64_t tx_head, tx_tail, tx_state;
	uint64_t next_tx_tail;
	struct vcctty_msg *msg;
	int err;

	err = hv_ldc_tx_get_state(lc->lc_id, &tx_head, &tx_tail, &tx_state);
	if (err != H_EOK || tx_state != LDC_CHANNEL_UP)
		return;

	while (tp->t_outq.c_cc > 0) {
		next_tx_tail = tx_tail + sizeof(*msg);
		next_tx_tail &= ((lc->lc_txq->lq_nentries * sizeof(*msg)) - 1);

		if (next_tx_tail == tx_head)
			return;

		msg = (struct vcctty_msg *)(lc->lc_txq->lq_va + tx_tail);
		bzero(msg, sizeof(*msg));
		msg->type = LDC_CONSOLE_DATA;
		msg->size = q_to_b(&tp->t_outq, msg->data, sizeof(msg->data));

		err = hv_ldc_tx_set_qtail(lc->lc_id, next_tx_tail);
		if (err != H_EOK)
			printf("%s: hv_ldc_tx_set_qtail: %d\n", __func__, err);
		tx_tail = next_tx_tail;
	}
}

void
vcctty_send_break(struct vcctty_softc *sc)
{
	struct ldc_conn *lc = &sc->sc_lc;
	uint64_t tx_head, tx_tail, tx_state;
	struct vcctty_msg *msg;
	int err;

	err = hv_ldc_tx_get_state(lc->lc_id, &tx_head, &tx_tail, &tx_state);
	if (err != H_EOK || tx_state != LDC_CHANNEL_UP)
		return;

	msg = (struct vcctty_msg *)(lc->lc_txq->lq_va + tx_tail);
	bzero(msg, sizeof(*msg));
	msg->type = LDC_CONSOLE_CTRL;
	msg->ctrl_msg = CONS_BREAK;

	tx_tail += sizeof(*msg);
	tx_tail &= ((lc->lc_txq->lq_nentries * sizeof(*msg)) - 1);
	err = hv_ldc_tx_set_qtail(lc->lc_id, tx_tail);
	if (err != H_EOK)
		printf("%s: hv_ldc_tx_set_qtail: %d\n", __func__, err);
}

int
vccttyopen(dev_t dev, int flag, int mode, struct proc *p)
{
	struct vcctty_softc *sc;
	struct tty *tp;
	int unit = minor(dev);

	if (unit >= vcctty_cd.cd_ndevs)
		return (ENXIO);
	sc = vcctty_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	if (sc->sc_tty)
		tp = sc->sc_tty;
	else
		tp = sc->sc_tty = ttymalloc(0);

	tp->t_oproc = vccttystart;
	tp->t_param = vccttyparam;
	tp->t_hwiflow = vccttyhwiflow;
	tp->t_dev = dev;
	if ((tp->t_state & TS_ISOPEN) == 0) {
		ttychars(tp);
		tp->t_iflag = TTYDEF_IFLAG;
		tp->t_oflag = TTYDEF_OFLAG;
		tp->t_cflag = TTYDEF_CFLAG | CRTSCTS;
		tp->t_lflag = TTYDEF_LFLAG;
		tp->t_ispeed = tp->t_ospeed = TTYDEF_SPEED;
		ttsetwater(tp);
	} else if ((tp->t_state & TS_XCLUDE) && suser(p, 0))
		return (EBUSY);
	tp->t_state |= TS_CARR_ON;

	return ((*linesw[tp->t_line].l_open)(dev, tp, p));
}

int
vccttyclose(dev_t dev, int flag, int mode, struct proc *p)
{
	struct vcctty_softc *sc;
	struct tty *tp;
	int unit = minor(dev);

	if (unit >= vcctty_cd.cd_ndevs)
		return (ENXIO);
	sc = vcctty_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	tp = sc->sc_tty;
	(*linesw[tp->t_line].l_close)(tp, flag, p);
	ttyclose(tp);
	return (0);
}

int
vccttyread(dev_t dev, struct uio *uio, int flag)
{
	struct vcctty_softc *sc;
	struct tty *tp;
	int unit = minor(dev);

	if (unit >= vcctty_cd.cd_ndevs)
		return (ENXIO);
	sc = vcctty_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	tp = sc->sc_tty;
	return ((*linesw[tp->t_line].l_read)(tp, uio, flag));
}

int
vccttywrite(dev_t dev, struct uio *uio, int flag)
{
	struct vcctty_softc *sc;
	struct tty *tp;
	int unit = minor(dev);

	if (unit >= vcctty_cd.cd_ndevs)
		return (ENXIO);
	sc = vcctty_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	tp = sc->sc_tty;
	return ((*linesw[tp->t_line].l_write)(tp, uio, flag));
}

int
vccttyioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p)
{
	struct vcctty_softc *sc;
	struct tty *tp;
	int unit = minor(dev);
	int error;

	if (unit >= vcctty_cd.cd_ndevs)
		return (ENXIO);
	sc = vcctty_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	tp = sc->sc_tty;
	error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, p);
	if (error >= 0)
		return error;
	error = ttioctl(tp, cmd, data, flag, p);
	if (error >= 0)
		return (error);

	error = 0;

	switch (cmd) {
	case TIOCSBRK:
		vcctty_send_break(sc);
		break;
	case TIOCCBRK:
		/* BREAK gets cleared automatically. */
		break;
	default:
		error = ENOTTY;
		break;
	}

	return (error);
}

void
vccttystart(struct tty *tp)
{
	struct vcctty_softc *sc = vcctty_cd.cd_devs[minor(tp->t_dev)];
	int s;

	s = spltty();
	if (tp->t_state & (TS_TIMEOUT | TS_BUSY | TS_TTSTOP)) {
		splx(s);
		return;
	}
	ttwakeupwr(tp);
	tp->t_state |= TS_BUSY;
	if (tp->t_outq.c_cc > 0)
		vcctty_send_data(sc, tp);
	tp->t_state &= ~TS_BUSY;
	if (tp->t_outq.c_cc > 0) {
		tp->t_state |= TS_TIMEOUT;
		timeout_add(&tp->t_rstrt_to, 1);
	}
	splx(s);
}

int
vccttystop(struct tty *tp, int flag)
{
	int s;

	s = spltty();
	if (tp->t_state & TS_BUSY)
		if ((tp->t_state & TS_TTSTOP) == 0)
			tp->t_state |= TS_FLUSH;
	splx(s);
	return (0);
}

struct tty *
vccttytty(dev_t dev)
{
	struct vcctty_softc *sc;
	int unit = minor(dev);

	if (unit >= vcctty_cd.cd_ndevs)
		return (NULL);
	sc = vcctty_cd.cd_devs[unit];
	if (sc == NULL)
		return (NULL);

	return sc->sc_tty;
}

int
vccttyparam(struct tty *tp, struct termios *t)
{
	tp->t_ispeed = t->c_ispeed;
	tp->t_ospeed = t->c_ospeed;
	tp->t_cflag = t->c_cflag;
	return (0);
}

int
vccttyhwiflow(struct tty *tp, int stop)
{
	struct vcctty_softc *sc = vcctty_cd.cd_devs[minor(tp->t_dev)];
	uint64_t state = stop ? INTR_DISABLED : INTR_ENABLED;

	cbus_intr_setenabled(sc->sc_bustag, sc->sc_tx_ino, state);
	cbus_intr_setenabled(sc->sc_bustag, sc->sc_rx_ino, state);

	return (1);
}


code:
/*	$OpenBSD: vcons.c,v 1.14 2014/05/10 11:49:31 kettenis Exp $	*/
/*
 * Copyright (c) 2008 Mark Kettenis
 *
 * 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/conf.h>
#include <sys/device.h>
#include <sys/proc.h>
#include <sys/systm.h>
#include <sys/tty.h>

#ifdef DDB
#include <ddb/db_var.h>
#endif

#include <machine/autoconf.h>
#include <machine/conf.h>
#include <machine/hypervisor.h>
#include <machine/openfirm.h>

#include <dev/cons.h>
#include <sparc64/dev/vbusvar.h>

struct vcons_softc {
	struct device	sc_dv;
	void		*sc_ih;
	struct tty	*sc_tty;
	void		*sc_si;
};

int	vcons_match(struct device *, void *, void *);
void	vcons_attach(struct device *, struct device *, void *);

struct cfattach vcons_ca = {
	sizeof(struct vcons_softc), vcons_match, vcons_attach
};

struct cfdriver vcons_cd = {
	NULL, "vcons", DV_DULL
};

int	vcons_intr(void *);

int	vcons_cnlookc(dev_t, int *);
int	vcons_cngetc(dev_t);
void	vcons_cnputc(dev_t, int);

void	vconsstart(struct tty *);
int	vconsparam(struct tty *, struct termios *);
void	vcons_softintr(void *);

int
vcons_match(struct device *parent, void *match, void *aux)
{
	struct vbus_attach_args *va = aux;

	if (strcmp(va->va_name, "console") == 0)
		return (1);

	return (0);
}

void
vcons_attach(struct device *parent, struct device *self, void *aux)
{
	struct vcons_softc *sc = (struct vcons_softc *)self;
	struct vbus_attach_args *va = aux;
	uint64_t sysino;
	int vcons_is_input, vcons_is_output;
	int node, maj;

	sc->sc_si = softintr_establish(IPL_TTY, vcons_softintr, sc);
	if (sc->sc_si == NULL)
		panic(": can't establish soft interrupt");

	if (vbus_intr_map(va->va_node, va->va_intr[0], &sysino))
		printf(": can't map interrupt\n");
	printf(": ivec 0x%llx", sysino);

	sc->sc_ih = bus_intr_establish(va->va_bustag, sysino, IPL_TTY,
	    BUS_INTR_ESTABLISH_MPSAFE, vcons_intr, sc, sc->sc_dv.dv_xname);
	if (sc->sc_ih == NULL) {
		printf(", can't establish interrupt\n");
		return;
	}

	node = OF_instance_to_package(OF_stdin());
	vcons_is_input = (va->va_node == node);
	node = OF_instance_to_package(OF_stdout());
	vcons_is_output = (va->va_node == node);

	if (vcons_is_input || vcons_is_output) {
		if (vcons_is_input) {
			cn_tab->cn_pollc = nullcnpollc;
			cn_tab->cn_getc = vcons_cngetc;

			/* Locate the major number. */
			for (maj = 0; maj < nchrdev; maj++)
				if (cdevsw[maj].d_open == vconsopen)
					break;
			cn_tab->cn_dev = makedev(maj, self->dv_unit);
		}
		if (vcons_is_output)
			cn_tab->cn_putc = vcons_cnputc;

		printf(", console");
	}

	printf("\n");
}

int
vcons_intr(void *arg)
{
	struct vcons_softc *sc = arg;

	if (sc->sc_tty)
		softintr_schedule(sc->sc_si);
	return (1);
}

int
vcons_cnlookc(dev_t dev, int *cp)
{
	int64_t ch;

	if (hv_cons_getchar(&ch) == H_EOK) {
#ifdef DDB
		if (ch == -1 && db_console)
			Debugger();
#endif
		*cp = ch;
		return (1);
	}

	return (0);
}

int
vcons_cngetc(dev_t dev)
{
	int c;

	while(!vcons_cnlookc(dev, &c))
		;

	return (c);
}

void
vcons_cnputc(dev_t dev, int c)
{
	while (hv_cons_putchar(c) == H_EWOULDBLOCK);
}

int
vconsopen(dev_t dev, int flag, int mode, struct proc *p)
{
	struct vcons_softc *sc;
	struct tty *tp;
	int unit = minor(dev);

	if (unit >= vcons_cd.cd_ndevs)
		return (ENXIO);
	sc = vcons_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	if (sc->sc_tty)
		tp = sc->sc_tty;
	else
		tp = sc->sc_tty = ttymalloc(0);

	tp->t_oproc = vconsstart;
	tp->t_param = vconsparam;
	tp->t_dev = dev;
	if ((tp->t_state & TS_ISOPEN) == 0) {
		ttychars(tp);
		tp->t_iflag = TTYDEF_IFLAG;
		tp->t_oflag = TTYDEF_OFLAG;
		tp->t_cflag = TTYDEF_CFLAG;
		tp->t_lflag = TTYDEF_LFLAG;
		tp->t_ispeed = tp->t_ospeed = TTYDEF_SPEED;
		ttsetwater(tp);
	} else if ((tp->t_state & TS_XCLUDE) && suser(p, 0))
		return (EBUSY);
	tp->t_state |= TS_CARR_ON;

	return ((*linesw[tp->t_line].l_open)(dev, tp, p));
}

int
vconsclose(dev_t dev, int flag, int mode, struct proc *p)
{
	struct vcons_softc *sc;
	struct tty *tp;
	int unit = minor(dev);

	if (unit >= vcons_cd.cd_ndevs)
		return (ENXIO);
	sc = vcons_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	tp = sc->sc_tty;
	(*linesw[tp->t_line].l_close)(tp, flag, p);
	ttyclose(tp);
	return (0);
}

int
vconsread(dev_t dev, struct uio *uio, int flag)
{
	struct vcons_softc *sc;
	struct tty *tp;
	int unit = minor(dev);

	if (unit >= vcons_cd.cd_ndevs)
		return (ENXIO);
	sc = vcons_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	tp = sc->sc_tty;
	return ((*linesw[tp->t_line].l_read)(tp, uio, flag));
}

int
vconswrite(dev_t dev, struct uio *uio, int flag)
{
	struct vcons_softc *sc;
	struct tty *tp;
	int unit = minor(dev);

	if (unit >= vcons_cd.cd_ndevs)
		return (ENXIO);
	sc = vcons_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	tp = sc->sc_tty;
	return ((*linesw[tp->t_line].l_write)(tp, uio, flag));
}

int
vconsioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p)
{
	struct vcons_softc *sc;
	struct tty *tp;
	int unit = minor(dev);
	int error;

	if (unit >= vcons_cd.cd_ndevs)
		return (ENXIO);
	sc = vcons_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	tp = sc->sc_tty;
	error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, p);
	if (error >= 0)
		return error;
	error = ttioctl(tp, cmd, data, flag, p);
	if (error >= 0)
		return (error);

	return (ENOTTY);
}

void
vconsstart(struct tty *tp)
{
	int s;

	s = spltty();
	if (tp->t_state & (TS_TTSTOP | TS_BUSY)) {
		splx(s);
		return;
	}
	ttwakeupwr(tp);
	tp->t_state |= TS_BUSY;
	while (tp->t_outq.c_cc != 0)
		vcons_cnputc(tp->t_dev, getc(&tp->t_outq));
	tp->t_state &= ~TS_BUSY;
	splx(s);
}

int
vconsstop(struct tty *tp, int flag)
{
	int s;

	s = spltty();
	if (tp->t_state & TS_BUSY)
		if ((tp->t_state & TS_TTSTOP) == 0)
			tp->t_state |= TS_FLUSH;
	splx(s);
	return (0);
}

struct tty *
vconstty(dev_t dev)
{
	struct vcons_softc *sc;
	int unit = minor(dev);

	if (unit >= vcons_cd.cd_ndevs)
		return (NULL);
	sc = vcons_cd.cd_devs[unit];
	if (sc == NULL)
		return (NULL);

	return sc->sc_tty;
}

int
vconsparam(struct tty *tp, struct termios *t)
{
	tp->t_ispeed = t->c_ispeed;
	tp->t_ospeed = t->c_ospeed;
	tp->t_cflag = t->c_cflag;
	return (0);
}

void
vcons_softintr(void *arg)
{
	struct vcons_softc *sc = arg;
	struct tty *tp = sc->sc_tty;
	int c;

	while (vcons_cnlookc(tp->t_dev, &c)) {
		if (tp->t_state & TS_ISOPEN)
			(*linesw[tp->t_line].l_rint)(c, tp);
	}
}

license: unknown


code:
/*	$OpenBSD: vds.c,v 1.1 2009/12/31 11:58:41 kettenis Exp $	*/
/*
 * Copyright (c) 2009 Mark Kettenis
 *
 * 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/buf.h>
#include <sys/device.h>
#include <sys/malloc.h>
#include <sys/systm.h>

#include <machine/autoconf.h>
#include <machine/hypervisor.h>
#include <machine/mdesc.h>

#include <sparc64/dev/cbusvar.h>

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

struct vds_softc {
	struct device	sc_dv;
	bus_space_tag_t	sc_bustag;
	bus_dma_tag_t	sc_dmatag;
};

int	vds_match(struct device *, void *, void *);
void	vds_attach(struct device *, struct device *, void *);

struct cfattach vds_ca = {
	sizeof(struct vds_softc), vds_match, vds_attach
};

struct cfdriver vds_cd = {
	NULL, "vds", DV_DULL
};

void	vds_get_channel_endpoint(int, struct cbus_attach_args *);

int
vds_match(struct device *parent, void *match, void *aux)
{
	struct cbus_attach_args *ca = aux;

	if (strcmp(ca->ca_name, "virtual-disk-server") == 0)
		return (1);

	return (0);
}

void
vds_attach(struct device *parent, struct device *self, void *aux)
{
	struct cbus_attach_args *ca = aux;
	struct cbus_attach_args nca;
	struct md_header *hdr;
	struct md_element *elem;
	const char *name_blk;
	const char *str;
	int idx;
	int arc;

	printf("\n");

	hdr = (struct md_header *)mdesc;
	elem = (struct md_element *)(mdesc + sizeof(struct md_header));
	name_blk = mdesc + sizeof(struct md_header) + hdr->node_blk_sz;

	idx = ca->ca_idx;
	for (; elem[idx].tag != 'E'; idx++) {
		str = name_blk + elem[idx].name_offset;
		if (elem[idx].tag != 'a' || strcmp(str, "fwd") != 0)
			continue;

		arc = elem[idx].d.val;
		str = name_blk + elem[arc].name_offset;
		if (strcmp(str, "virtual-device-port") == 0) {
			bzero(&nca, sizeof(nca));
			nca.ca_name = "vds-port";
			nca.ca_node = ca->ca_node;
			nca.ca_bustag = ca->ca_bustag;
			nca.ca_dmatag = ca->ca_dmatag;
			vds_get_channel_endpoint(arc, &nca);
			config_found(self, &nca, cbus_print);
		}
	}
}

void
vds_get_channel_endpoint(int idx, struct cbus_attach_args *ca)
{
	struct md_header *hdr;
	struct md_element *elem;
	const char *name_blk;
	const char *str;
	int arc;

	hdr = (struct md_header *)mdesc;
	elem = (struct md_element *)(mdesc + sizeof(struct md_header));
	name_blk = mdesc + sizeof(struct md_header) + hdr->node_blk_sz;

	ca->ca_idx = idx;

	ca->ca_id = -1;
	ca->ca_tx_ino = -1;
	ca->ca_rx_ino = -1;

	for (; elem[idx].tag != 'E'; idx++) {
		str = name_blk + elem[idx].name_offset;
		if (elem[idx].tag != 'a' || strcmp(str, "fwd") != 0)
			continue;

		arc = elem[idx].d.val;
		str = name_blk + elem[arc].name_offset;
		if (strcmp(str, "channel-endpoint") == 0) {
			ca->ca_id = mdesc_get_prop_val(arc, "id");
			ca->ca_tx_ino = mdesc_get_prop_val(arc, "tx-ino");
			ca->ca_rx_ino = mdesc_get_prop_val(arc, "rx-ino");
			return;
		}
	}
}


code:
/*	$OpenBSD: vdsk.c,v 1.46 2015/01/25 21:42:13 kettenis Exp $	*/
/*
 * Copyright (c) 2009, 2011 Mark Kettenis
 *
 * 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/buf.h>
#include <sys/device.h>
#include <sys/malloc.h>
#include <sys/systm.h>

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

#include <uvm/uvm_extern.h>

#include <scsi/scsi_all.h>
#include <scsi/cd.h>
#include <scsi/scsi_disk.h>
#include <scsi/scsiconf.h>

#include <sparc64/dev/cbusvar.h>
#include <sparc64/dev/ldcvar.h>
#include <sparc64/dev/viovar.h>

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

#define VDSK_TX_ENTRIES		32
#define VDSK_RX_ENTRIES		32

struct vd_attr_info {
	struct vio_msg_tag	tag;
	uint8_t			xfer_mode;
	uint8_t			vd_type;
	uint8_t			vd_mtype;
	uint8_t			_reserved1;
	uint32_t		vdisk_block_size;
	uint64_t		operations;
	uint64_t		vdisk_size;
	uint64_t		max_xfer_sz;
	uint64_t		_reserved2[2];
};

#define VD_DISK_TYPE_SLICE	0x01
#define VD_DISK_TYPE_DISK	0x02

#define VD_MEDIA_TYPE_FIXED	0x01
#define VD_MEDIA_TYPE_CD	0x02
#define VD_MEDIA_TYPE_DVD	0x03

/* vDisk version 1.0. */
#define VD_OP_BREAD		0x01
#define VD_OP_BWRITE		0x02
#define VD_OP_FLUSH		0x03
#define VD_OP_GET_WCE		0x04
#define VD_OP_SET_WCE		0x05
#define VD_OP_GET_VTOC		0x06
#define VD_OP_SET_VTOC		0x07
#define VD_OP_GET_DISKGEOM	0x08
#define VD_OP_SET_DISKGEOM	0x09
#define VD_OP_GET_DEVID		0x0b
#define VD_OP_GET_EFI		0x0c
#define VD_OP_SET_EFI		0x0d

/* vDisk version 1.1 */
#define VD_OP_SCSICMD		0x0a
#define VD_OP_RESET		0x0e
#define VD_OP_GET_ACCESS	0x0f
#define VD_OP_SET_ACCESS	0x10
#define VD_OP_GET_CAPACITY	0x11

struct vd_desc {
	struct vio_dring_hdr	hdr;
	uint64_t		req_id;
	uint8_t			operation;
	uint8_t			slice;
	uint16_t		_reserved1;
	uint32_t		status;
	uint64_t		offset;
	uint64_t		size;
	uint32_t		ncookies;
	uint32_t		_reserved2;
	struct ldc_cookie	cookie[MAXPHYS / PAGE_SIZE];
};

#define VD_SLICE_NONE		0xff

struct vdsk_dring {
	bus_dmamap_t		vd_map;
	bus_dma_segment_t	vd_seg;
	struct vd_desc		*vd_desc;
	int			vd_nentries;
};

struct vdsk_dring *vdsk_dring_alloc(bus_dma_tag_t, int);
void	vdsk_dring_free(bus_dma_tag_t, struct vdsk_dring *);

/*
 * We support vDisk 1.0 and 1.1.
 */
#define VDSK_MAJOR	1
#define VDSK_MINOR	1

struct vdsk_soft_desc {
	int		vsd_map_idx[MAXPHYS / PAGE_SIZE];
	struct scsi_xfer *vsd_xs;
	int		vsd_ncookies;
};

struct vdsk_softc {
	struct device	sc_dv;
	bus_space_tag_t	sc_bustag;
	bus_dma_tag_t	sc_dmatag;

	void		*sc_tx_ih;
	void		*sc_rx_ih;

	struct ldc_conn	sc_lc;

	uint16_t	sc_vio_state;
#define VIO_SND_VER_INFO	0x0001
#define VIO_ACK_VER_INFO	0x0002
#define VIO_SND_ATTR_INFO	0x0004
#define VIO_ACK_ATTR_INFO	0x0008
#define VIO_SND_DRING_REG	0x0010
#define VIO_ACK_DRING_REG	0x0020
#define VIO_SND_RDX		0x0040
#define VIO_ACK_RDX		0x0080
#define VIO_ESTABLISHED		0x00ff

	uint16_t	sc_major;
	uint16_t	sc_minor;

	uint32_t	sc_local_sid;
	uint64_t	sc_dring_ident;
	uint64_t	sc_seq_no;

	int		sc_tx_cnt;
	int		sc_tx_prod;
	int		sc_tx_cons;

	struct ldc_map	*sc_lm;
	struct vdsk_dring *sc_vd;
	struct vdsk_soft_desc *sc_vsd;

	struct scsi_iopool sc_iopool;
	struct scsi_adapter sc_switch;
	struct scsi_link sc_link;

	uint32_t	sc_vdisk_block_size;
	uint64_t	sc_vdisk_size;
	uint8_t		sc_vd_mtype;
};

int	vdsk_match(struct device *, void *, void *);
void	vdsk_attach(struct device *, struct device *, void *);

struct cfattach vdsk_ca = {
	sizeof(struct vdsk_softc), vdsk_match, vdsk_attach
};

struct cfdriver vdsk_cd = {
	NULL, "vdsk", DV_DULL
};

int	vdsk_tx_intr(void *);
int	vdsk_rx_intr(void *);

void	vdsk_rx_data(struct ldc_conn *, struct ldc_pkt *);
void	vdsk_rx_vio_ctrl(struct vdsk_softc *, struct vio_msg *);
void	vdsk_rx_vio_ver_info(struct vdsk_softc *, struct vio_msg_tag *);
void	vdsk_rx_vio_attr_info(struct vdsk_softc *, struct vio_msg_tag *);
void	vdsk_rx_vio_dring_reg(struct vdsk_softc *, struct vio_msg_tag *);
void	vdsk_rx_vio_rdx(struct vdsk_softc *sc, struct vio_msg_tag *);
void	vdsk_rx_vio_data(struct vdsk_softc *sc, struct vio_msg *);
void	vdsk_rx_vio_dring_data(struct vdsk_softc *sc, struct vio_msg_tag *);

void	vdsk_ldc_reset(struct ldc_conn *);
void	vdsk_ldc_start(struct ldc_conn *);

void	vdsk_sendmsg(struct vdsk_softc *, void *, size_t);
void	vdsk_send_ver_info(struct vdsk_softc *, uint16_t, uint16_t);
void	vdsk_send_attr_info(struct vdsk_softc *);
void	vdsk_send_dring_reg(struct vdsk_softc *);
void	vdsk_send_rdx(struct vdsk_softc *);

void	*vdsk_io_get(void *);
void	vdsk_io_put(void *, void *);

void	vdsk_scsi_cmd(struct scsi_xfer *);
int	vdsk_submit_cmd(struct scsi_xfer *);
void	vdsk_complete_cmd(struct scsi_xfer *, int);
int	vdsk_dev_probe(struct scsi_link *);
void	vdsk_dev_free(struct scsi_link *);

void	vdsk_scsi_inq(struct scsi_xfer *);
void	vdsk_scsi_inquiry(struct scsi_xfer *);
void	vdsk_scsi_capacity(struct scsi_xfer *);
void	vdsk_scsi_capacity16(struct scsi_xfer *);
void	vdsk_scsi_done(struct scsi_xfer *, int);

int
vdsk_match(struct device *parent, void *match, void *aux)
{
	struct cbus_attach_args *ca = aux;

	if (strcmp(ca->ca_name, "disk") == 0)
		return (1);

	return (0);
}

void
vdsk_attach(struct device *parent, struct device *self, void *aux)
{
	struct vdsk_softc *sc = (struct vdsk_softc *)self;
	struct cbus_attach_args *ca = aux;
	struct scsibus_attach_args saa;
	struct ldc_conn *lc;
	int err, s;
	int timeout;

	sc->sc_bustag = ca->ca_bustag;
	sc->sc_dmatag = ca->ca_dmatag;

	printf(": ivec 0x%llx, 0x%llx", ca->ca_tx_ino, ca->ca_rx_ino);

	/*
	 * Un-configure queues before registering interrupt handlers,
	 * such that we dont get any stale LDC packets or events.
	 */
	hv_ldc_tx_qconf(ca->ca_id, 0, 0);
	hv_ldc_rx_qconf(ca->ca_id, 0, 0);

	sc->sc_tx_ih = bus_intr_establish(ca->ca_bustag, ca->ca_tx_ino,
	    IPL_BIO, 0, vdsk_tx_intr, sc, sc->sc_dv.dv_xname);
	sc->sc_rx_ih = bus_intr_establish(ca->ca_bustag, ca->ca_rx_ino,
	    IPL_BIO, 0, vdsk_rx_intr, sc, sc->sc_dv.dv_xname);
	if (sc->sc_tx_ih == NULL || sc->sc_rx_ih == NULL) {
		printf(", can't establish interrupt\n");
		return;
	}

	lc = &sc->sc_lc;
	lc->lc_id = ca->ca_id;
	lc->lc_sc = sc;
	lc->lc_reset = vdsk_ldc_reset;
	lc->lc_start = vdsk_ldc_start;
	lc->lc_rx_data = vdsk_rx_data;

	lc->lc_txq = ldc_queue_alloc(sc->sc_dmatag, VDSK_TX_ENTRIES);
	if (lc->lc_txq == NULL) {
		printf(", can't allocate tx queue\n");
		return;
	}

	lc->lc_rxq = ldc_queue_alloc(sc->sc_dmatag, VDSK_RX_ENTRIES);
	if (lc->lc_rxq == NULL) {
		printf(", can't allocate rx queue\n");
		goto free_txqueue;
	}

	sc->sc_lm = ldc_map_alloc(sc->sc_dmatag, 2048);
	if (sc->sc_lm == NULL) {
		printf(", can't allocate LDC mapping table\n");
		goto free_rxqueue;
	}

	err = hv_ldc_set_map_table(lc->lc_id,
	    sc->sc_lm->lm_map->dm_segs[0].ds_addr, sc->sc_lm->lm_nentries);
	if (err != H_EOK) {
		printf("hv_ldc_set_map_table %d\n", err);
		goto free_map;
	}

	sc->sc_vd = vdsk_dring_alloc(sc->sc_dmatag, 32);
	if (sc->sc_vd == NULL) {
		printf(", can't allocate dring\n");
		goto free_map;
	}
	sc->sc_vsd = malloc(32 * sizeof(*sc->sc_vsd), M_DEVBUF, M_NOWAIT);
	if (sc->sc_vsd == NULL) {
		printf(", can't allocate software ring\n");
		goto free_dring;
	}

	sc->sc_lm->lm_slot[0].entry = sc->sc_vd->vd_map->dm_segs[0].ds_addr;
	sc->sc_lm->lm_slot[0].entry &= LDC_MTE_RA_MASK;
	sc->sc_lm->lm_slot[0].entry |= LDC_MTE_CPR | LDC_MTE_CPW;
	sc->sc_lm->lm_slot[0].entry |= LDC_MTE_R | LDC_MTE_W;
	sc->sc_lm->lm_next = 1;
	sc->sc_lm->lm_count = 1;

	err = hv_ldc_tx_qconf(lc->lc_id,
	    lc->lc_txq->lq_map->dm_segs[0].ds_addr, lc->lc_txq->lq_nentries);
	if (err != H_EOK)
		printf("hv_ldc_tx_qconf %d\n", err);

	err = hv_ldc_rx_qconf(lc->lc_id,
	    lc->lc_rxq->lq_map->dm_segs[0].ds_addr, lc->lc_rxq->lq_nentries);
	if (err != H_EOK)
		printf("hv_ldc_rx_qconf %d\n", err);

	cbus_intr_setenabled(sc->sc_bustag, ca->ca_tx_ino, INTR_ENABLED);
	cbus_intr_setenabled(sc->sc_bustag, ca->ca_rx_ino, INTR_ENABLED);

	ldc_send_vers(lc);

	printf("\n");

	/*
	 * Interrupts aren't enabled during autoconf, so poll for VIO
	 * peer-to-peer hanshake completion.
	 */
	s = splbio();
	timeout = 1000;
	do {
		if (vdsk_rx_intr(sc) && sc->sc_vio_state == VIO_ESTABLISHED)
			break;

		delay(1000);
	} while(--timeout > 0);
	splx(s);

	if (sc->sc_vio_state != VIO_ESTABLISHED)
		return;

	scsi_iopool_init(&sc->sc_iopool, sc, vdsk_io_get, vdsk_io_put);

	sc->sc_switch.scsi_cmd = vdsk_scsi_cmd;
	sc->sc_switch.scsi_minphys = scsi_minphys;
	sc->sc_switch.dev_probe = vdsk_dev_probe;
	sc->sc_switch.dev_free = vdsk_dev_free;

	sc->sc_link.adapter = &sc->sc_switch;
	sc->sc_link.adapter_softc = self;
	sc->sc_link.adapter_buswidth = 2;
	sc->sc_link.luns = 1; /* XXX slices should be presented as luns? */
	sc->sc_link.adapter_target = 2;
	sc->sc_link.openings = sc->sc_vd->vd_nentries - 1;
	sc->sc_link.pool = &sc->sc_iopool;

	bzero(&saa, sizeof(saa));
	saa.saa_sc_link = &sc->sc_link;
	config_found(self, &saa, scsiprint);

	return;

free_dring:
	vdsk_dring_free(sc->sc_dmatag, sc->sc_vd);
free_map:
	hv_ldc_set_map_table(lc->lc_id, 0, 0);
	ldc_map_free(sc->sc_dmatag, sc->sc_lm);
free_rxqueue:
	ldc_queue_free(sc->sc_dmatag, lc->lc_rxq);
free_txqueue:
	ldc_queue_free(sc->sc_dmatag, lc->lc_txq);
}

int
vdsk_tx_intr(void *arg)
{
	struct vdsk_softc *sc = arg;
	struct ldc_conn *lc = &sc->sc_lc;
	uint64_t tx_head, tx_tail, tx_state;

	hv_ldc_tx_get_state(lc->lc_id, &tx_head, &tx_tail, &tx_state);
	if (tx_state != lc->lc_tx_state) {
		switch (tx_state) {
		case LDC_CHANNEL_DOWN:
			DPRINTF(("Tx link down\n"));
			break;
		case LDC_CHANNEL_UP:
			DPRINTF(("Tx link up\n"));
			break;
		case LDC_CHANNEL_RESET:
			DPRINTF(("Tx link reset\n"));
			break;
		}
		lc->lc_tx_state = tx_state;
	}

	return (1);
}

int
vdsk_rx_intr(void *arg)
{
	struct vdsk_softc *sc = arg;
	struct ldc_conn *lc = &sc->sc_lc;
	uint64_t rx_head, rx_tail, rx_state;
	struct ldc_pkt *lp;
	int err;

	err = hv_ldc_rx_get_state(lc->lc_id, &rx_head, &rx_tail, &rx_state);
	if (err == H_EINVAL)
		return (0);
	if (err != H_EOK) {
		printf("hv_ldc_rx_get_state %d\n", err);
		return (0);
	}

	if (rx_state != lc->lc_rx_state) {
		sc->sc_vio_state = 0;
		lc->lc_tx_seqid = 0;
		lc->lc_state = 0;
		switch (rx_state) {
		case LDC_CHANNEL_DOWN:
			DPRINTF(("Rx link down\n"));
			break;
		case LDC_CHANNEL_UP:
			DPRINTF(("Rx link up\n"));
			ldc_send_vers(lc);
			break;
		case LDC_CHANNEL_RESET:
			DPRINTF(("Rx link reset\n"));
			break;
		}
		lc->lc_rx_state = rx_state;
		hv_ldc_rx_set_qhead(lc->lc_id, rx_tail);
		return (1);
	}

	if (rx_head == rx_tail)
		return (0);

	lp = (struct ldc_pkt *)(lc->lc_rxq->lq_va + rx_head);
	switch (lp->type) {
	case LDC_CTRL:
		ldc_rx_ctrl(lc, lp);
		break;

	case LDC_DATA:
		ldc_rx_data(lc, lp);
		break;

	default:
		DPRINTF(("%0x02/%0x02/%0x02\n", lp->type, lp->stype,
		    lp->ctrl));
		ldc_reset(lc);
		break;
	}

	if (lc->lc_state == 0)
		return (1);

	rx_head += sizeof(*lp);
	rx_head &= ((lc->lc_rxq->lq_nentries * sizeof(*lp)) - 1);
	err = hv_ldc_rx_set_qhead(lc->lc_id, rx_head);
	if (err != H_EOK)
		printf("%s: hv_ldc_rx_set_qhead %d\n", __func__, err);

	return (1);
}

void
vdsk_rx_data(struct ldc_conn *lc, struct ldc_pkt *lp)
{
	struct vio_msg *vm = (struct vio_msg *)lp;

	switch (vm->type) {
	case VIO_TYPE_CTRL:
		if ((lp->env & LDC_FRAG_START) == 0 &&
		    (lp->env & LDC_FRAG_STOP) == 0)
			return;
		vdsk_rx_vio_ctrl(lc->lc_sc, vm);
		break;

	case VIO_TYPE_DATA:
		if((lp->env & LDC_FRAG_START) == 0)
			return;
		vdsk_rx_vio_data(lc->lc_sc, vm);
		break;

	default:
		DPRINTF(("Unhandled packet type 0x%02x\n", vm->type));
		ldc_reset(lc);
		break;
	}
}

void
vdsk_rx_vio_ctrl(struct vdsk_softc *sc, struct vio_msg *vm)
{
	struct vio_msg_tag *tag = (struct vio_msg_tag *)&vm->type;

	switch (tag->stype_env) {
	case VIO_VER_INFO:
		vdsk_rx_vio_ver_info(sc, tag);
		break;
	case VIO_ATTR_INFO:
		vdsk_rx_vio_attr_info(sc, tag);
		break;
	case VIO_DRING_REG:
		vdsk_rx_vio_dring_reg(sc, tag);
		break;
	case VIO_RDX:
		vdsk_rx_vio_rdx(sc, tag);
		break;
	default:
		DPRINTF(("CTRL/0x%02x/0x%04x\n", tag->stype, tag->stype_env));
		break;
	}
}

void
vdsk_rx_vio_ver_info(struct vdsk_softc *sc, struct vio_msg_tag *tag)
{
	struct vio_ver_info *vi = (struct vio_ver_info *)tag;

	switch (vi->tag.stype) {
	case VIO_SUBTYPE_INFO:
		DPRINTF(("CTRL/INFO/VER_INFO\n"));
		break;

	case VIO_SUBTYPE_ACK:
		DPRINTF(("CTRL/ACK/VER_INFO\n"));
		if (!ISSET(sc->sc_vio_state, VIO_SND_VER_INFO)) {
			ldc_reset(&sc->sc_lc);
			break;
		}
		sc->sc_major = vi->major;
		sc->sc_minor = vi->minor;
		sc->sc_vio_state |= VIO_ACK_VER_INFO;
		break;

	default:
		DPRINTF(("CTRL/0x%02x/VER_INFO\n", vi->tag.stype));
		break;
	}

	if (ISSET(sc->sc_vio_state, VIO_ACK_VER_INFO))
		vdsk_send_attr_info(sc);
}

void
vdsk_rx_vio_attr_info(struct vdsk_softc *sc, struct vio_msg_tag *tag)
{
	struct vd_attr_info *ai = (struct vd_attr_info *)tag;

	switch (ai->tag.stype) {
	case VIO_SUBTYPE_INFO:
		DPRINTF(("CTRL/INFO/ATTR_INFO\n"));
		break;

	case VIO_SUBTYPE_ACK:
		DPRINTF(("CTRL/ACK/ATTR_INFO\n"));
		if (!ISSET(sc->sc_vio_state, VIO_SND_ATTR_INFO)) {
			ldc_reset(&sc->sc_lc);
			break;
		}

		sc->sc_vdisk_block_size = ai->vdisk_block_size;
		sc->sc_vdisk_size = ai->vdisk_size;
		if (sc->sc_major > 1 || sc->sc_minor >= 1)
			sc->sc_vd_mtype = ai->vd_mtype;
		else
			sc->sc_vd_mtype = VD_MEDIA_TYPE_FIXED;

		sc->sc_vio_state |= VIO_ACK_ATTR_INFO;
		break;

	default:
		DPRINTF(("CTRL/0x%02x/ATTR_INFO\n", ai->tag.stype));
		break;
	}

	if (ISSET(sc->sc_vio_state, VIO_ACK_ATTR_INFO))
		vdsk_send_dring_reg(sc);

}

void
vdsk_rx_vio_dring_reg(struct vdsk_softc *sc, struct vio_msg_tag *tag)
{
	struct vio_dring_reg *dr = (struct vio_dring_reg *)tag;

	switch (dr->tag.stype) {
	case VIO_SUBTYPE_INFO:
		DPRINTF(("CTRL/INFO/DRING_REG\n"));
		break;

	case VIO_SUBTYPE_ACK:
		DPRINTF(("CTRL/ACK/DRING_REG\n"));
		if (!ISSET(sc->sc_vio_state, VIO_SND_DRING_REG)) {
			ldc_reset(&sc->sc_lc);
			break;
		}

		sc->sc_dring_ident = dr->dring_ident;
		sc->sc_seq_no = 1;

		sc->sc_vio_state |= VIO_ACK_DRING_REG;
		break;

	default:
		DPRINTF(("CTRL/0x%02x/DRING_REG\n", dr->tag.stype));
		break;
	}

	if (ISSET(sc->sc_vio_state, VIO_ACK_DRING_REG))
		vdsk_send_rdx(sc);
}

void
vdsk_rx_vio_rdx(struct vdsk_softc *sc, struct vio_msg_tag *tag)
{
	switch(tag->stype) {
	case VIO_SUBTYPE_INFO:
		DPRINTF(("CTRL/INFO/RDX\n"));
		break;

	case VIO_SUBTYPE_ACK:
	{
		int prod;

		DPRINTF(("CTRL/ACK/RDX\n"));
		if (!ISSET(sc->sc_vio_state, VIO_SND_RDX)) {
			ldc_reset(&sc->sc_lc);
			break;
		}
		sc->sc_vio_state |= VIO_ACK_RDX;

		/*
		 * If this ACK is the result of a reconnect, we may
		 * have pending I/O that we need to resubmit.  We need
		 * to rebuild the ring descriptors though since the
		 * vDisk server on the other side may have touched
		 * them already.  So we just clean up the ring and the
		 * LDC map and resubmit the SCSI commands based on our
		 * soft descriptors.
		 */
		prod = sc->sc_tx_prod;
		sc->sc_tx_prod = sc->sc_tx_cons;
		sc->sc_tx_cnt = 0;
		sc->sc_lm->lm_next = 1;
		sc->sc_lm->lm_count = 1;
		while (sc->sc_tx_prod != prod)
			vdsk_submit_cmd(sc->sc_vsd[sc->sc_tx_prod].vsd_xs);

		scsi_iopool_run(&sc->sc_iopool);
		break;
	}

	default:
		DPRINTF(("CTRL/0x%02x/RDX (VIO)\n", tag->stype));
		break;
	}
}

void
vdsk_rx_vio_data(struct vdsk_softc *sc, struct vio_msg *vm)
{
	struct vio_msg_tag *tag = (struct vio_msg_tag *)&vm->type;

	if (sc->sc_vio_state != VIO_ESTABLISHED) {
		DPRINTF(("Spurious DATA/0x%02x/0x%04x\n", tag->stype,
		    tag->stype_env));
		return;
	}

	switch(tag->stype_env) {
	case VIO_DRING_DATA:
		vdsk_rx_vio_dring_data(sc, tag);
		break;

	default:
		DPRINTF(("DATA/0x%02x/0x%04x\n", tag->stype, tag->stype_env));
		break;
	}
}

void
vdsk_rx_vio_dring_data(struct vdsk_softc *sc, struct vio_msg_tag *tag)
{
	switch(tag->stype) {
	case VIO_SUBTYPE_INFO:
		DPRINTF(("DATA/INFO/DRING_DATA\n"));
		break;

	case VIO_SUBTYPE_ACK:
	{
		struct scsi_xfer *xs;
		int cons;

		cons = sc->sc_tx_cons;
		while (sc->sc_vd->vd_desc[cons].hdr.dstate == VIO_DESC_DONE) {
			xs = sc->sc_vsd[cons].vsd_xs;
			if (ISSET(xs->flags, SCSI_POLL) == 0)
				vdsk_complete_cmd(xs, cons);
			cons++;
			cons &= (sc->sc_vd->vd_nentries - 1);
		}
		sc->sc_tx_cons = cons;
		break;
	}

	case VIO_SUBTYPE_NACK:
		DPRINTF(("DATA/NACK/DRING_DATA\n"));
		break;

	default:
		DPRINTF(("DATA/0x%02x/DRING_DATA\n", tag->stype));
		break;
	}
}

void
vdsk_ldc_reset(struct ldc_conn *lc)
{
	struct vdsk_softc *sc = lc->lc_sc;

	sc->sc_vio_state = 0;
}

void
vdsk_ldc_start(struct ldc_conn *lc)
{
	struct vdsk_softc *sc = lc->lc_sc;

	vdsk_send_ver_info(sc, VDSK_MAJOR, VDSK_MINOR);
}

void
vdsk_sendmsg(struct vdsk_softc *sc, void *msg, size_t len)
{
	struct ldc_conn *lc = &sc->sc_lc;
	int err;

	err = ldc_send_unreliable(lc, msg, len);
	if (err)
		printf("%s: ldc_send_unreliable: %d\n", __func__, err);
}

void
vdsk_send_ver_info(struct vdsk_softc *sc, uint16_t major, uint16_t minor)
{
	struct vio_ver_info vi;

	/* Allocate new session ID. */
	sc->sc_local_sid = tick();

	bzero(&vi, sizeof(vi));
	vi.tag.type = VIO_TYPE_CTRL;
	vi.tag.stype = VIO_SUBTYPE_INFO;
	vi.tag.stype_env = VIO_VER_INFO;
	vi.tag.sid = sc->sc_local_sid;
	vi.major = major;
	vi.minor = minor;
	vi.dev_class = VDEV_DISK;
	vdsk_sendmsg(sc, &vi, sizeof(vi));

	sc->sc_vio_state |= VIO_SND_VER_INFO;
}

void
vdsk_send_attr_info(struct vdsk_softc *sc)
{
	struct vd_attr_info ai;

	bzero(&ai, sizeof(ai));
	ai.tag.type = VIO_TYPE_CTRL;
	ai.tag.stype = VIO_SUBTYPE_INFO;
	ai.tag.stype_env = VIO_ATTR_INFO;
	ai.tag.sid = sc->sc_local_sid;
	ai.xfer_mode = VIO_DRING_MODE;
	ai.vdisk_block_size = DEV_BSIZE;
	ai.max_xfer_sz = MAXPHYS / DEV_BSIZE;
	vdsk_sendmsg(sc, &ai, sizeof(ai));

	sc->sc_vio_state |= VIO_SND_ATTR_INFO;
}

void
vdsk_send_dring_reg(struct vdsk_softc *sc)
{
	struct vio_dring_reg dr;

	bzero(&dr, sizeof(dr));
	dr.tag.type = VIO_TYPE_CTRL;
	dr.tag.stype = VIO_SUBTYPE_INFO;
	dr.tag.stype_env = VIO_DRING_REG;
	dr.tag.sid = sc->sc_local_sid;
	dr.dring_ident = 0;
	dr.num_descriptors = sc->sc_vd->vd_nentries;
	dr.descriptor_size = sizeof(struct vd_desc);
	dr.options = VIO_TX_RING | VIO_RX_RING;
	dr.ncookies = 1;
	dr.cookie[0].addr = 0;
	dr.cookie[0].size = PAGE_SIZE;
	vdsk_sendmsg(sc, &dr, sizeof(dr));

	sc->sc_vio_state |= VIO_SND_DRING_REG;
};

void
vdsk_send_rdx(struct vdsk_softc *sc)
{
	struct vio_rdx rdx;

	bzero(&rdx, sizeof(rdx));
	rdx.tag.type = VIO_TYPE_CTRL;
	rdx.tag.stype = VIO_SUBTYPE_INFO;
	rdx.tag.stype_env = VIO_RDX;
	rdx.tag.sid = sc->sc_local_sid;
	vdsk_sendmsg(sc, &rdx, sizeof(rdx));

	sc->sc_vio_state |= VIO_SND_RDX;
}

struct vdsk_dring *
vdsk_dring_alloc(bus_dma_tag_t t, int nentries)
{
	struct vdsk_dring *vd;
	bus_size_t size;
	caddr_t va;
	int nsegs;
	int i;

	vd = malloc(sizeof(struct vdsk_dring), M_DEVBUF, M_NOWAIT);
	if (vd == NULL)
		return NULL;

	size = roundup(nentries * sizeof(struct vd_desc), PAGE_SIZE);

	if (bus_dmamap_create(t, size, 1, size, 0,
	    BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW, &vd->vd_map) != 0)
		return (NULL);

	if (bus_dmamem_alloc(t, size, PAGE_SIZE, 0, &vd->vd_seg, 1,
	    &nsegs, BUS_DMA_NOWAIT) != 0)
		goto destroy;

	if (bus_dmamem_map(t, &vd->vd_seg, 1, size, &va,
	    BUS_DMA_NOWAIT) != 0)
		goto free;

	if (bus_dmamap_load(t, vd->vd_map, va, size, NULL,
	    BUS_DMA_NOWAIT) != 0)
		goto unmap;

	vd->vd_desc = (struct vd_desc *)va;
	vd->vd_nentries = nentries;
	bzero(vd->vd_desc, nentries * sizeof(struct vd_desc));
	for (i = 0; i < vd->vd_nentries; i++)
		vd->vd_desc[i].hdr.dstate = VIO_DESC_FREE;
	return (vd);

unmap:
	bus_dmamem_unmap(t, va, size);
free:
	bus_dmamem_free(t, &vd->vd_seg, 1);
destroy:
	bus_dmamap_destroy(t, vd->vd_map);

	return (NULL);
}

void
vdsk_dring_free(bus_dma_tag_t t, struct vdsk_dring *vd)
{
	bus_size_t size;

	size = vd->vd_nentries * sizeof(struct vd_desc);
	size = roundup(size, PAGE_SIZE);

	bus_dmamap_unload(t, vd->vd_map);
	bus_dmamem_unmap(t, (caddr_t)vd->vd_desc, size);
	bus_dmamem_free(t, &vd->vd_seg, 1);
	bus_dmamap_destroy(t, vd->vd_map);
	free(vd, M_DEVBUF, 0);
}

void *
vdsk_io_get(void *xsc)
{
	struct vdsk_softc *sc = xsc;
	void *rv = sc; /* just has to be !NULL */
	int s;

	s = splbio();
	if (sc->sc_vio_state != VIO_ESTABLISHED ||
	    sc->sc_tx_cnt >= sc->sc_vd->vd_nentries)
		rv = NULL;
	else
		sc->sc_tx_cnt++;
	splx(s);

	return (rv);
}

void
vdsk_io_put(void *xsc, void *io)
{
	struct vdsk_softc *sc = xsc;
	int s;

#ifdef DIAGNOSTIC
	if (sc != io)
		panic("vsdk_io_put: unexpected io");
#endif

	s = splbio();
	sc->sc_tx_cnt--;
	splx(s);
}

void
vdsk_scsi_cmd(struct scsi_xfer *xs)
{
	struct vdsk_softc *sc = xs->sc_link->adapter_softc;
	int timeout, s;
	int desc;

	switch (xs->cmd->opcode) {
	case READ_BIG:
	case READ_COMMAND:
	case READ_12:
	case READ_16:
	case WRITE_BIG:
	case WRITE_COMMAND:
	case WRITE_12:
	case WRITE_16:
	case SYNCHRONIZE_CACHE:
		break;

	case INQUIRY:
		vdsk_scsi_inq(xs);
		return;
	case READ_CAPACITY:
		vdsk_scsi_capacity(xs);
		return;
	case READ_CAPACITY_16:
		vdsk_scsi_capacity16(xs);
		return;

	case TEST_UNIT_READY:
	case START_STOP:
	case PREVENT_ALLOW:
		vdsk_scsi_done(xs, XS_NOERROR);
		return;

	default:
		printf("%s cmd 0x%02x\n", __func__, xs->cmd->opcode);
	case MODE_SENSE:
	case MODE_SENSE_BIG:
	case REPORT_LUNS:
	case READ_TOC:
		vdsk_scsi_done(xs, XS_DRIVER_STUFFUP);
		return;
	}

	s = splbio();
	desc = vdsk_submit_cmd(xs);

	if (!ISSET(xs->flags, SCSI_POLL)) {
		splx(s);
		return;
	}

	timeout = 1000;
	do {
		if (sc->sc_vd->vd_desc[desc].hdr.dstate == VIO_DESC_DONE)
			break;

		delay(1000);
	} while(--timeout > 0);
	if (sc->sc_vd->vd_desc[desc].hdr.dstate == VIO_DESC_DONE) {
		vdsk_complete_cmd(xs, desc);
	} else {
		ldc_reset(&sc->sc_lc);
		vdsk_scsi_done(xs, XS_TIMEOUT);
	}
	splx(s);
}

int
vdsk_submit_cmd(struct scsi_xfer *xs)
{
	struct vdsk_softc *sc = xs->sc_link->adapter_softc;
	struct ldc_map *map = sc->sc_lm;
	struct vio_dring_msg dm;
	struct scsi_rw *rw;
	struct scsi_rw_big *rwb;
	struct scsi_rw_12 *rw12;
	struct scsi_rw_16 *rw16;
	u_int64_t lba;
	u_int32_t sector_count;
	uint8_t operation;
	vaddr_t va;
	paddr_t pa;
	psize_t nbytes;
	int len, ncookies;
	int desc;

	switch (xs->cmd->opcode) {
	case READ_BIG:
	case READ_COMMAND:
	case READ_12:
	case READ_16:
		operation = VD_OP_BREAD;
		break;

	case WRITE_BIG:
	case WRITE_COMMAND:
	case WRITE_12:
	case WRITE_16:
		operation = VD_OP_BWRITE;
		break;

	case SYNCHRONIZE_CACHE:
		operation = VD_OP_FLUSH;
		break;
	}

	/*
	 * READ/WRITE/SYNCHRONIZE commands. SYNCHRONIZE CACHE has same
	 * layout as 10-byte READ/WRITE commands.
	 */
	if (xs->cmdlen == 6) {
		rw = (struct scsi_rw *)xs->cmd;
		lba = _3btol(rw->addr) & (SRW_TOPADDR << 16 | 0xffff);
		sector_count = rw->length ? rw->length : 0x100;
	} else if (xs->cmdlen == 10) {
		rwb = (struct scsi_rw_big *)xs->cmd;
		lba = _4btol(rwb->addr);
		sector_count = _2btol(rwb->length);
	} else if (xs->cmdlen == 12) {
		rw12 = (struct scsi_rw_12 *)xs->cmd;
		lba = _4btol(rw12->addr);
		sector_count = _4btol(rw12->length);
	} else if (xs->cmdlen == 16) {
		rw16 = (struct scsi_rw_16 *)xs->cmd;
		lba = _8btol(rw16->addr);
		sector_count = _4btol(rw16->length);
	}

	desc = sc->sc_tx_prod;

	ncookies = 0;
	len = xs->datalen;
	va = (vaddr_t)xs->data;
	while (len > 0) {
		KASSERT(ncookies < MAXPHYS / PAGE_SIZE);
		pmap_extract(pmap_kernel(), va, &pa);
		while (map->lm_slot[map->lm_next].entry != 0) {
			map->lm_next++;
			map->lm_next &= (map->lm_nentries - 1);
		}
		map->lm_slot[map->lm_next].entry = (pa & LDC_MTE_RA_MASK);
		map->lm_slot[map->lm_next].entry |= LDC_MTE_CPR | LDC_MTE_CPW;
		map->lm_slot[map->lm_next].entry |= LDC_MTE_IOR | LDC_MTE_IOW;
		map->lm_slot[map->lm_next].entry |= LDC_MTE_R | LDC_MTE_W;
		map->lm_count++;

		nbytes = MIN(len, PAGE_SIZE - (pa & PAGE_MASK));

		sc->sc_vd->vd_desc[desc].cookie[ncookies].addr =
		    map->lm_next << PAGE_SHIFT | (pa & PAGE_MASK);
		sc->sc_vd->vd_desc[desc].cookie[ncookies].size = nbytes;

		sc->sc_vsd[desc].vsd_map_idx[ncookies] = map->lm_next;
		va += nbytes;
		len -= nbytes;
		ncookies++;
	}

	if (ISSET(xs->flags, SCSI_POLL) == 0)
		sc->sc_vd->vd_desc[desc].hdr.ack = 1;
	else
		sc->sc_vd->vd_desc[desc].hdr.ack = 0;
	sc->sc_vd->vd_desc[desc].operation = operation;
	sc->sc_vd->vd_desc[desc].slice = VD_SLICE_NONE;
	sc->sc_vd->vd_desc[desc].status = 0xffffffff;
	sc->sc_vd->vd_desc[desc].offset = lba;
	sc->sc_vd->vd_desc[desc].size = xs->datalen;
	sc->sc_vd->vd_desc[desc].ncookies = ncookies;
	membar(Sync);
	sc->sc_vd->vd_desc[desc].hdr.dstate = VIO_DESC_READY;

	sc->sc_vsd[desc].vsd_xs = xs;
	sc->sc_vsd[desc].vsd_ncookies = ncookies;

	sc->sc_tx_prod++;
	sc->sc_tx_prod &= (sc->sc_vd->vd_nentries - 1);

	bzero(&dm, sizeof(dm));
	dm.tag.type = VIO_TYPE_DATA;
	dm.tag.stype = VIO_SUBTYPE_INFO;
	dm.tag.stype_env = VIO_DRING_DATA;
	dm.tag.sid = sc->sc_local_sid;
	dm.seq_no = sc->sc_seq_no++;
	dm.dring_ident = sc->sc_dring_ident;
	dm.start_idx = dm.end_idx = desc;
	vdsk_sendmsg(sc, &dm, sizeof(dm));

	return desc;
}

void
vdsk_complete_cmd(struct scsi_xfer *xs, int desc)
{
	struct vdsk_softc *sc = xs->sc_link->adapter_softc;
	struct ldc_map *map = sc->sc_lm;
	int cookie, idx;
	int error;

	cookie = 0;
	while (cookie < sc->sc_vsd[desc].vsd_ncookies) {
		idx = sc->sc_vsd[desc].vsd_map_idx[cookie++];
		map->lm_slot[idx].entry = 0;
		map->lm_count--;
	}

	error = XS_NOERROR;
	if (sc->sc_vd->vd_desc[desc].status != 0)
		error = XS_DRIVER_STUFFUP;
	xs->resid = xs->datalen -
		sc->sc_vd->vd_desc[desc].size;
	vdsk_scsi_done(xs, error);

	sc->sc_vd->vd_desc[desc].hdr.dstate = VIO_DESC_FREE;
}

void
vdsk_scsi_inq(struct scsi_xfer *xs)
{
	struct scsi_inquiry *inq = (struct scsi_inquiry *)xs->cmd;

	if (ISSET(inq->flags, SI_EVPD))
		vdsk_scsi_done(xs, XS_DRIVER_STUFFUP);
	else
		vdsk_scsi_inquiry(xs);
}

void
vdsk_scsi_inquiry(struct scsi_xfer *xs)
{
	struct vdsk_softc *sc = xs->sc_link->adapter_softc;
	struct scsi_inquiry_data inq;
	char buf[5];

	bzero(&inq, sizeof(inq));

	switch (sc->sc_vd_mtype) {
	case VD_MEDIA_TYPE_CD:
	case VD_MEDIA_TYPE_DVD:
		inq.device = T_CDROM;
		break;

	case VD_MEDIA_TYPE_FIXED:
	default:
		inq.device = T_DIRECT;
		break;
	}

	inq.version = 0x05; /* SPC-3 */
	inq.response_format = 2;
	inq.additional_length = 32;
	inq.flags |= SID_CmdQue;
	bcopy("SUN     ", inq.vendor, sizeof(inq.vendor));
	bcopy("Virtual Disk    ", inq.product, sizeof(inq.product));
	snprintf(buf, sizeof(buf), "%u.%u ", sc->sc_major, sc->sc_minor);
	bcopy(buf, inq.revision, sizeof(inq.revision));

	bcopy(&inq, xs->data, MIN(sizeof(inq), xs->datalen));

	vdsk_scsi_done(xs, XS_NOERROR);
}

void
vdsk_scsi_capacity(struct scsi_xfer *xs)
{
	struct vdsk_softc *sc = xs->sc_link->adapter_softc;
	struct scsi_read_cap_data rcd;
	uint64_t capacity;

	bzero(&rcd, sizeof(rcd));

	capacity = sc->sc_vdisk_size - 1;
	if (capacity > 0xffffffff)
		capacity = 0xffffffff;

	_lto4b(capacity, rcd.addr);
	_lto4b(sc->sc_vdisk_block_size, rcd.length);

	bcopy(&rcd, xs->data, MIN(sizeof(rcd), xs->datalen));

	vdsk_scsi_done(xs, XS_NOERROR);
}

void
vdsk_scsi_capacity16(struct scsi_xfer *xs)
{
	struct vdsk_softc *sc = xs->sc_link->adapter_softc;
	struct scsi_read_cap_data_16 rcd;

	bzero(&rcd, sizeof(rcd));

	_lto8b(sc->sc_vdisk_size - 1, rcd.addr);
	_lto4b(sc->sc_vdisk_block_size, rcd.length);

	bcopy(&rcd, xs->data, MIN(sizeof(rcd), xs->datalen));

	vdsk_scsi_done(xs, XS_NOERROR);
}

void
vdsk_scsi_done(struct scsi_xfer *xs, int error)
{
	xs->error = error;

	scsi_done(xs);
}

int
vdsk_dev_probe(struct scsi_link *link)
{
	KASSERT(link->lun == 0);

	if (link->target == 0)
		return (0);

	return (ENODEV);
}

void
vdsk_dev_free(struct scsi_link *link)
{
	printf("%s\n", __func__);
}


code:
/*	$OpenBSD: vdsp.c,v 1.39 2015/02/11 12:09:18 miod Exp $	*/
/*
 * Copyright (c) 2009, 2011, 2014 Mark Kettenis
 *
 * 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/conf.h>
#include <sys/proc.h>
#include <sys/buf.h>
#include <sys/device.h>
#include <sys/disklabel.h>
#include <sys/fcntl.h>
#include <sys/lock.h>
#include <sys/malloc.h>
#include <sys/mutex.h>
#include <sys/namei.h>
#include <sys/systm.h>
#include <sys/task.h>
#include <sys/vnode.h>
#include <sys/dkio.h>
#include <sys/specdev.h>

#include <machine/autoconf.h>
#include <machine/conf.h>
#include <machine/hypervisor.h>
#include <machine/mdesc.h>

#include <uvm/uvm_extern.h>

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

#include <isofs/cd9660/iso.h>

#include <dev/sun/disklabel.h>

#include <sparc64/dev/cbusvar.h>
#include <sparc64/dev/ldcvar.h>
#include <sparc64/dev/viovar.h>

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

#define VDSK_TX_ENTRIES			64
#define VDSK_RX_ENTRIES			64

#define VDSK_MAX_DESCRIPTORS		1024
#define VDSK_MAX_DESCRIPTOR_SIZE	512

struct vd_attr_info {
	struct vio_msg_tag	tag;
	uint8_t			xfer_mode;
	uint8_t			vd_type;
	uint8_t			vd_mtype;
	uint8_t			_reserved1;
	uint32_t		vdisk_block_size;
	uint64_t		operations;
	uint64_t		vdisk_size;
	uint64_t		max_xfer_sz;
	uint64_t		_reserved2[2];
};

#define VD_DISK_TYPE_SLICE	0x01
#define VD_DISK_TYPE_DISK	0x02

#define VD_MEDIA_TYPE_FIXED	0x01
#define VD_MEDIA_TYPE_CD	0x02
#define VD_MEDIA_TYPE_DVD	0x03

/* vDisk version 1.0. */
#define VD_OP_BREAD		0x01
#define VD_OP_BWRITE		0x02
#define VD_OP_FLUSH		0x03
#define VD_OP_GET_WCE		0x04
#define VD_OP_SET_WCE		0x05
#define VD_OP_GET_VTOC		0x06
#define VD_OP_SET_VTOC		0x07
#define VD_OP_GET_DISKGEOM	0x08
#define VD_OP_SET_DISKGEOM	0x09
#define VD_OP_GET_DEVID		0x0b
#define VD_OP_GET_EFI		0x0c
#define VD_OP_SET_EFI		0x0d

/* vDisk version 1.1 */
#define VD_OP_SCSICMD		0x0a
#define VD_OP_RESET		0x0e
#define VD_OP_GET_ACCESS	0x0f
#define VD_OP_SET_ACCESS	0x10
#define VD_OP_GET_CAPACITY	0x11

/* Sun standard fields. */
struct sun_vtoc_preamble {
	char	sl_text[128];
	u_int	sl_version;	/* label version */
	char	sl_volume[8];	/* short volume name */
	u_short	sl_nparts;	/* partition count */

	struct sun_partinfo sl_part[8];

	u_int	sl_bootinfo[3];
	u_int	sl_sanity;
};

struct vd_vtoc_part {
	uint16_t	id_tag;
	uint16_t	perm;
	uint32_t	reserved;
	uint64_t	start;
	uint64_t	nblocks;

};
struct vd_vtoc {
	uint8_t		volume_name[8];
	uint16_t	sector_size;
	uint16_t	num_partitions;
	uint32_t	reserved;
	uint8_t		ascii_label[128];
	struct vd_vtoc_part partition[8];
};

struct vd_diskgeom {
	uint16_t	ncyl;
	uint16_t	acyl;
	uint16_t	bcyl;
	uint16_t	nhead;
	uint16_t	nsect;
	uint16_t	intrlv;
	uint16_t	apc;
	uint16_t	rpm;
	uint16_t	pcyl;
	uint16_t	write_reinstruct;
	uint16_t	read_reinstruct;
};

struct vd_desc {
	struct vio_dring_hdr	hdr;
	uint64_t		req_id;
	uint8_t			operation;
	uint8_t			slice;
	uint16_t		_reserved1;
	uint32_t		status;
	uint64_t		offset;
	uint64_t		size;
	uint32_t		ncookies;
	uint32_t		_reserved2;
	struct ldc_cookie	cookie[1];
};

#define VD_SLICE_NONE		0xff

struct vdsk_desc_msg {
	struct vio_msg_tag	tag;
	uint64_t		seq_no;
	uint64_t		desc_handle;
	uint64_t		req_id;
	uint8_t			operation;
	uint8_t			slice;
	uint16_t		_reserved1;
	uint32_t		status;
	uint64_t		offset;
	uint64_t		size;
	uint32_t		ncookies;
	uint32_t		_reserved2;
	struct ldc_cookie	cookie[1];
};

/*
 * We support vDisk 1.1.
 */
#define VDSK_MAJOR	1
#define VDSK_MINOR	1

/*
 * But we only support a subset of the defined commands.
 */
#define VD_OP_MASK \
    ((1 << VD_OP_BREAD) | (1 << VD_OP_BWRITE) | (1 << VD_OP_FLUSH) | \
     (1 << VD_OP_GET_WCE) | (1 << VD_OP_SET_WCE) | \
     (1 << VD_OP_GET_VTOC) | (1 << VD_OP_SET_VTOC) | \
     (1 << VD_OP_GET_DISKGEOM))

struct vdsp_softc {
	struct device	sc_dv;
	int		sc_idx;
	bus_space_tag_t	sc_bustag;
	bus_dma_tag_t	sc_dmatag;

	uint64_t	sc_tx_ino;
	uint64_t	sc_rx_ino;
	void		*sc_tx_ih;
	void		*sc_rx_ih;

	struct ldc_conn	sc_lc;

	uint16_t	sc_vio_state;
#define VIO_SND_VER_INFO	0x0001
#define VIO_ACK_VER_INFO	0x0002
#define VIO_RCV_VER_INFO	0x0004
#define VIO_SND_ATTR_INFO	0x0008
#define VIO_ACK_ATTR_INFO	0x0010
#define VIO_RCV_ATTR_INFO	0x0020
#define VIO_SND_DRING_REG	0x0040
#define VIO_ACK_DRING_REG	0x0080
#define VIO_RCV_DRING_REG	0x0100
#define VIO_SND_RDX		0x0200
#define VIO_ACK_RDX		0x0400
#define VIO_RCV_RDX		0x0800

	uint16_t	sc_major;
	uint16_t	sc_minor;

	uint8_t		sc_xfer_mode;

	uint32_t	sc_local_sid;
	uint64_t	sc_seq_no;

	uint64_t	sc_dring_ident;
	uint32_t	sc_num_descriptors;
	uint32_t	sc_descriptor_size;
	struct ldc_cookie sc_dring_cookie;

	struct task	sc_open_task;
	struct task	sc_alloc_task;
	struct task	sc_close_task;

	struct mutex	sc_desc_mtx;
	struct vdsk_desc_msg *sc_desc_msg[VDSK_RX_ENTRIES];
	int		sc_desc_head;
	int		sc_desc_tail;

	struct task	sc_read_task;

	caddr_t		sc_vd;
	struct task	sc_vd_task;
	struct vd_desc	**sc_vd_ring;
	u_int		sc_vd_prod;
	u_int		sc_vd_cons;

	uint32_t	sc_vdisk_block_size;
	uint64_t	sc_vdisk_size;

	struct vnode	*sc_vp;

	struct sun_disklabel *sc_label;
	uint16_t	sc_ncyl;
	uint16_t	sc_acyl;
	uint16_t	sc_nhead;
	uint16_t	sc_nsect;
};

int	vdsp_match(struct device *, void *, void *);
void	vdsp_attach(struct device *, struct device *, void *);

struct cfattach vdsp_ca = {
	sizeof(struct vdsp_softc), vdsp_match, vdsp_attach
};

struct cfdriver vdsp_cd = {
	NULL, "vdsp", DV_DULL
};

int	vdsp_tx_intr(void *);
int	vdsp_rx_intr(void *);

void	vdsp_rx_data(struct ldc_conn *, struct ldc_pkt *);
void	vdsp_rx_vio_ctrl(struct vdsp_softc *, struct vio_msg *);
void	vdsp_rx_vio_ver_info(struct vdsp_softc *, struct vio_msg_tag *);
void	vdsp_rx_vio_attr_info(struct vdsp_softc *, struct vio_msg_tag *);
void	vdsp_rx_vio_dring_reg(struct vdsp_softc *, struct vio_msg_tag *);
void	vdsp_rx_vio_rdx(struct vdsp_softc *sc, struct vio_msg_tag *);
void	vdsp_rx_vio_data(struct vdsp_softc *sc, struct vio_msg *);
void	vdsp_rx_vio_dring_data(struct vdsp_softc *sc,
	    struct vio_msg_tag *);
void	vdsp_rx_vio_desc_data(struct vdsp_softc *sc, struct vio_msg_tag *);

void	vdsp_ldc_reset(struct ldc_conn *);
void	vdsp_ldc_start(struct ldc_conn *);

void	vdsp_sendmsg(struct vdsp_softc *, void *, size_t, int dowait);

void	vdsp_open(void *);
void	vdsp_close(void *);
void	vdsp_alloc(void *);
void	vdsp_readlabel(struct vdsp_softc *);
int	vdsp_writelabel(struct vdsp_softc *);
int	vdsp_is_iso(struct vdsp_softc *);
void	vdsp_read(void *);
void	vdsp_read_desc(struct vdsp_softc *, struct vdsk_desc_msg *);
void	vdsp_vd_task(void *);
void	vdsp_read_dring(void *, void *);
void	vdsp_write_dring(void *, void *);
void	vdsp_flush_dring(void *, void *);
void	vdsp_get_vtoc(void *, void *);
void	vdsp_set_vtoc(void *, void *);
void	vdsp_get_diskgeom(void *, void *);
void	vdsp_unimp(void *, void *);

void	vdsp_ack_desc(struct vdsp_softc *, struct vd_desc *);

int
vdsp_match(struct device *parent, void *match, void *aux)
{
	struct cbus_attach_args *ca = aux;

	if (strcmp(ca->ca_name, "vds-port") == 0)
		return (1);

	return (0);
}

void
vdsp_attach(struct device *parent, struct device *self, void *aux)
{
	struct vdsp_softc *sc = (struct vdsp_softc *)self;
	struct cbus_attach_args *ca = aux;
	struct ldc_conn *lc;

	sc->sc_idx = ca->ca_idx;
	sc->sc_bustag = ca->ca_bustag;
	sc->sc_dmatag = ca->ca_dmatag;
	sc->sc_tx_ino = ca->ca_tx_ino;
	sc->sc_rx_ino = ca->ca_rx_ino;

	printf(": ivec 0x%llx, 0x%llx", sc->sc_tx_ino, sc->sc_rx_ino);

	mtx_init(&sc->sc_desc_mtx, IPL_BIO);

	/*
	 * Un-configure queues before registering interrupt handlers,
	 * such that we dont get any stale LDC packets or events.
	 */
	hv_ldc_tx_qconf(ca->ca_id, 0, 0);
	hv_ldc_rx_qconf(ca->ca_id, 0, 0);

	sc->sc_tx_ih = bus_intr_establish(ca->ca_bustag, sc->sc_tx_ino,
	    IPL_BIO, BUS_INTR_ESTABLISH_MPSAFE, vdsp_tx_intr, sc,
	    sc->sc_dv.dv_xname);
	sc->sc_rx_ih = bus_intr_establish(ca->ca_bustag, sc->sc_rx_ino,
	    IPL_BIO, BUS_INTR_ESTABLISH_MPSAFE, vdsp_rx_intr, sc,
	    sc->sc_dv.dv_xname);
	if (sc->sc_tx_ih == NULL || sc->sc_rx_ih == NULL) {
		printf(", can't establish interrupt\n");
		return;
	}

	lc = &sc->sc_lc;
	lc->lc_id = ca->ca_id;
	lc->lc_sc = sc;
	lc->lc_reset = vdsp_ldc_reset;
	lc->lc_start = vdsp_ldc_start;
	lc->lc_rx_data = vdsp_rx_data;

	lc->lc_txq = ldc_queue_alloc(sc->sc_dmatag, VDSK_TX_ENTRIES);
	if (lc->lc_txq == NULL) {
		printf(", can't allocate tx queue\n");
		return;
	}

	lc->lc_rxq = ldc_queue_alloc(sc->sc_dmatag, VDSK_RX_ENTRIES);
	if (lc->lc_rxq == NULL) {
		printf(", can't allocate rx queue\n");
		goto free_txqueue;
	}

	task_set(&sc->sc_open_task, vdsp_open, sc);
	task_set(&sc->sc_alloc_task, vdsp_alloc, sc);
	task_set(&sc->sc_close_task, vdsp_close, sc);
	task_set(&sc->sc_read_task, vdsp_read, sc);

	printf("\n");

	return;

#if 0
free_rxqueue:
	ldc_queue_free(sc->sc_dmatag, lc->lc_rxq);
#endif
free_txqueue:
	ldc_queue_free(sc->sc_dmatag, lc->lc_txq);
}

int
vdsp_tx_intr(void *arg)
{
	struct vdsp_softc *sc = arg;
	struct ldc_conn *lc = &sc->sc_lc;
	uint64_t tx_head, tx_tail, tx_state;
	int err;

	err = hv_ldc_tx_get_state(lc->lc_id, &tx_head, &tx_tail, &tx_state);
	if (err != H_EOK) {
		printf("hv_ldc_rx_get_state %d\n", err);
		return (0);
	}

	if (tx_state != lc->lc_tx_state) {
		switch (tx_state) {
		case LDC_CHANNEL_DOWN:
			DPRINTF(("Tx link down\n"));
			break;
		case LDC_CHANNEL_UP:
			DPRINTF(("Tx link up\n"));
			break;
		case LDC_CHANNEL_RESET:
			DPRINTF(("Tx link reset\n"));
			break;
		}
		lc->lc_tx_state = tx_state;
	}

	wakeup(lc->lc_txq);
	return (1);
}

int
vdsp_rx_intr(void *arg)
{
	struct vdsp_softc *sc = arg;
	struct ldc_conn *lc = &sc->sc_lc;
	uint64_t rx_head, rx_tail, rx_state;
	struct ldc_pkt *lp;
	int err;

	err = hv_ldc_rx_get_state(lc->lc_id, &rx_head, &rx_tail, &rx_state);
	if (err == H_EINVAL)
		return (0);
	if (err != H_EOK) {
		printf("hv_ldc_rx_get_state %d\n", err);
		return (0);
	}

	if (rx_state != lc->lc_rx_state) {
		switch (rx_state) {
		case LDC_CHANNEL_DOWN:
			DPRINTF(("Rx link down\n"));
			lc->lc_tx_seqid = 0;
			lc->lc_state = 0;
			lc->lc_reset(lc);
			break;
		case LDC_CHANNEL_UP:
			DPRINTF(("Rx link up\n"));
			break;
		case LDC_CHANNEL_RESET:
			DPRINTF(("Rx link reset\n"));
			lc->lc_tx_seqid = 0;
			lc->lc_state = 0;
			lc->lc_reset(lc);
			break;
		}
		lc->lc_rx_state = rx_state;
		return (1);
	}

	if (lc->lc_rx_state == LDC_CHANNEL_DOWN)
		return (1);

	lp = (struct ldc_pkt *)(lc->lc_rxq->lq_va + rx_head);
	switch (lp->type) {
	case LDC_CTRL:
		ldc_rx_ctrl(lc, lp);
		break;

	case LDC_DATA:
		ldc_rx_data(lc, lp);
		break;

	default:
		DPRINTF(("0x%02x/0x%02x/0x%02x\n", lp->type, lp->stype,
		    lp->ctrl));
		ldc_reset(lc);
		break;
	}

	rx_head += sizeof(*lp);
	rx_head &= ((lc->lc_rxq->lq_nentries * sizeof(*lp)) - 1);
	err = hv_ldc_rx_set_qhead(lc->lc_id, rx_head);
	if (err != H_EOK)
		printf("%s: hv_ldc_rx_set_qhead %d\n", __func__, err);

	return (1);
}

void
vdsp_rx_data(struct ldc_conn *lc, struct ldc_pkt *lp)
{
	struct vio_msg *vm = (struct vio_msg *)lp;

	switch (vm->type) {
	case VIO_TYPE_CTRL:
		if ((lp->env & LDC_FRAG_START) == 0 &&
		    (lp->env & LDC_FRAG_STOP) == 0)
			return;
		vdsp_rx_vio_ctrl(lc->lc_sc, vm);
		break;

	case VIO_TYPE_DATA:
		if((lp->env & LDC_FRAG_START) == 0)
			return;
		vdsp_rx_vio_data(lc->lc_sc, vm);
		break;

	default:
		DPRINTF(("Unhandled packet type 0x%02x\n", vm->type));
		ldc_reset(lc);
		break;
	}
}

void
vdsp_rx_vio_ctrl(struct vdsp_softc *sc, struct vio_msg *vm)
{
	struct vio_msg_tag *tag = (struct vio_msg_tag *)&vm->type;

	switch (tag->stype_env) {
	case VIO_VER_INFO:
		vdsp_rx_vio_ver_info(sc, tag);
		break;
	case VIO_ATTR_INFO:
		vdsp_rx_vio_attr_info(sc, tag);
		break;
	case VIO_DRING_REG:
		vdsp_rx_vio_dring_reg(sc, tag);
		break;
	case VIO_RDX:
		vdsp_rx_vio_rdx(sc, tag);
		break;
	default:
		DPRINTF(("CTRL/0x%02x/0x%04x\n", tag->stype, tag->stype_env));
		break;
	}
}

void
vdsp_rx_vio_ver_info(struct vdsp_softc *sc, struct vio_msg_tag *tag)
{
	struct vio_ver_info *vi = (struct vio_ver_info *)tag;

	switch (vi->tag.stype) {
	case VIO_SUBTYPE_INFO:
		DPRINTF(("CTRL/INFO/VER_INFO\n"));

		/* Make sure we're talking to a virtual disk. */
		if (vi->dev_class != VDEV_DISK) {
			/* Huh, we're not talking to a disk device? */
			printf("%s: peer is not a disk device\n",
			    sc->sc_dv.dv_xname);
			vi->tag.stype = VIO_SUBTYPE_NACK;
			vi->major = 0;
			vdsp_sendmsg(sc, vi, sizeof(*vi), 0);
			return;
		}

		if (vi->major != VDSK_MAJOR) {
			vi->tag.stype = VIO_SUBTYPE_NACK;
			vi->major = VDSK_MAJOR;
			vi->minor = VDSK_MINOR;
			vdsp_sendmsg(sc, vi, sizeof(*vi), 0);
			return;
		}

		sc->sc_major = vi->major;
		sc->sc_minor = vi->minor;
		sc->sc_local_sid = vi->tag.sid;

		vi->tag.stype = VIO_SUBTYPE_ACK;
		if (vi->minor > VDSK_MINOR)
			vi->minor = VDSK_MINOR;
		vi->dev_class = VDEV_DISK_SERVER;
		vdsp_sendmsg(sc, vi, sizeof(*vi), 0);
		sc->sc_vio_state |= VIO_RCV_VER_INFO;
		break;

	case VIO_SUBTYPE_ACK:
		DPRINTF(("CTRL/ACK/VER_INFO\n"));
		break;

	default:
		DPRINTF(("CTRL/0x%02x/VER_INFO\n", vi->tag.stype));
		break;
	}
}

void
vdsp_rx_vio_attr_info(struct vdsp_softc *sc, struct vio_msg_tag *tag)
{
	struct vd_attr_info *ai = (struct vd_attr_info *)tag;

	switch (ai->tag.stype) {
	case VIO_SUBTYPE_INFO:
		DPRINTF(("CTRL/INFO/ATTR_INFO\n"));

		if (ai->xfer_mode != VIO_DESC_MODE &&
		    ai->xfer_mode != VIO_DRING_MODE) {
			printf("%s: peer uses unsupported xfer mode 0x%02x\n",
			    sc->sc_dv.dv_xname, ai->xfer_mode);
			ai->tag.stype = VIO_SUBTYPE_NACK;
			vdsp_sendmsg(sc, ai, sizeof(*ai), 0);
			return;
		}
		sc->sc_xfer_mode = ai->xfer_mode;
		sc->sc_vio_state |= VIO_RCV_ATTR_INFO;

		task_add(systq, &sc->sc_open_task);
		break;

	case VIO_SUBTYPE_ACK:
		DPRINTF(("CTRL/ACK/ATTR_INFO\n"));
		break;

	default:
		DPRINTF(("CTRL/0x%02x/ATTR_INFO\n", ai->tag.stype));
		break;
	}
}

void
vdsp_rx_vio_dring_reg(struct vdsp_softc *sc, struct vio_msg_tag *tag)
{
	struct vio_dring_reg *dr = (struct vio_dring_reg *)tag;

	switch (dr->tag.stype) {
	case VIO_SUBTYPE_INFO:
		DPRINTF(("CTRL/INFO/DRING_REG\n"));

		if (dr->num_descriptors > VDSK_MAX_DESCRIPTORS ||
		    dr->descriptor_size > VDSK_MAX_DESCRIPTOR_SIZE ||
		    dr->ncookies > 1) {
			dr->tag.stype = VIO_SUBTYPE_NACK;
			vdsp_sendmsg(sc, dr, sizeof(*dr), 0);
			return;
		}
		sc->sc_num_descriptors = dr->num_descriptors;
		sc->sc_descriptor_size = dr->descriptor_size;
		sc->sc_dring_cookie = dr->cookie[0];
		sc->sc_vio_state |= VIO_RCV_DRING_REG;

		task_add(systq, &sc->sc_alloc_task);
		break;

	case VIO_SUBTYPE_ACK:
		DPRINTF(("CTRL/ACK/DRING_REG\n"));
		break;

	default:
		DPRINTF(("CTRL/0x%02x/DRING_REG\n", dr->tag.stype));
		break;
	}
}

void
vdsp_rx_vio_rdx(struct vdsp_softc *sc, struct vio_msg_tag *tag)
{
	switch(tag->stype) {
	case VIO_SUBTYPE_INFO:
		DPRINTF(("CTRL/INFO/RDX\n"));

		tag->stype = VIO_SUBTYPE_ACK;
		tag->sid = sc->sc_local_sid;
		vdsp_sendmsg(sc, tag, sizeof(*tag), 0);
		sc->sc_vio_state |= VIO_RCV_RDX;
		break;

	case VIO_SUBTYPE_ACK:
		DPRINTF(("CTRL/ACK/RDX\n"));
		break;

	default:
		DPRINTF(("CTRL/0x%02x/RDX (VIO)\n", tag->stype));
		break;
	}
}

void
vdsp_rx_vio_data(struct vdsp_softc *sc, struct vio_msg *vm)
{
	struct vio_msg_tag *tag = (struct vio_msg_tag *)&vm->type;

	if (!ISSET(sc->sc_vio_state, VIO_RCV_RDX)) {
		DPRINTF(("Spurious DATA/0x%02x/0x%04x\n", tag->stype,
		    tag->stype_env));
		return;
	}

	switch(tag->stype_env) {
	case VIO_DESC_DATA:
		vdsp_rx_vio_desc_data(sc, tag);
		break;

	case VIO_DRING_DATA:
		vdsp_rx_vio_dring_data(sc, tag);
		break;

	default:
		DPRINTF(("DATA/0x%02x/0x%04x\n", tag->stype, tag->stype_env));
		break;
	}
}

void
vdsp_rx_vio_dring_data(struct vdsp_softc *sc, struct vio_msg_tag *tag)
{
	struct vio_dring_msg *dm = (struct vio_dring_msg *)tag;
	struct vd_desc *vd;
	vaddr_t va;
	paddr_t pa;
	uint64_t size, off;
	psize_t nbytes;
	int err;

	switch(tag->stype) {
	case VIO_SUBTYPE_INFO:
		DPRINTF(("DATA/INFO/DRING_DATA\n"));

		if (dm->dring_ident != sc->sc_dring_ident ||
		    dm->start_idx >= sc->sc_num_descriptors) {
			dm->tag.stype = VIO_SUBTYPE_NACK;
			vdsp_sendmsg(sc, dm, sizeof(*dm), 0);
			return;
		}

		off = dm->start_idx * sc->sc_descriptor_size;
		vd = (struct vd_desc *)(sc->sc_vd + off);
		va = (vaddr_t)vd;
		size = sc->sc_descriptor_size;
		while (size > 0) {
			pmap_extract(pmap_kernel(), va, &pa);
			nbytes = MIN(size, PAGE_SIZE - (off & PAGE_MASK));
			err = hv_ldc_copy(sc->sc_lc.lc_id, LDC_COPY_IN,
			    sc->sc_dring_cookie.addr + off, pa,
			    nbytes, &nbytes);
			if (err != H_EOK) {
				printf("%s: hv_ldc_copy %d\n", __func__, err);
				return;
			}
			va += nbytes;
			size -= nbytes;
			off += nbytes;
		}

		sc->sc_vd_ring[sc->sc_vd_prod % sc->sc_num_descriptors] = vd;
		membar_producer();
		sc->sc_vd_prod++;
		task_add(systq, &sc->sc_vd_task);

		break;

	case VIO_SUBTYPE_ACK:
		DPRINTF(("DATA/ACK/DRING_DATA\n"));
		break;

	case VIO_SUBTYPE_NACK:
		DPRINTF(("DATA/NACK/DRING_DATA\n"));
		break;

	default:
		DPRINTF(("DATA/0x%02x/DRING_DATA\n", tag->stype));
		break;
	}
}

void
vdsp_vd_task(void *xsc)
{
	struct vdsp_softc *sc = xsc;
	struct vd_desc *vd;

	while (sc->sc_vd_cons != sc->sc_vd_prod) {
		membar_consumer();
		vd = sc->sc_vd_ring[sc->sc_vd_cons++ % sc->sc_num_descriptors];

		DPRINTF(("%s: operation %x\n", sc->sc_dv.dv_xname,
		    vd->operation));
		switch (vd->operation) {
		case VD_OP_BREAD:
			vdsp_read_dring(sc, vd);
			break;
		case VD_OP_BWRITE:
			vdsp_write_dring(sc, vd);
			break;
		case VD_OP_FLUSH:
			vdsp_flush_dring(sc, vd);
			break;
		case VD_OP_GET_VTOC:
			vdsp_get_vtoc(sc, vd);
			break;
		case VD_OP_SET_VTOC:
			vdsp_set_vtoc(sc, vd);
			break;
		case VD_OP_GET_DISKGEOM:
			vdsp_get_diskgeom(sc, vd);
			break;
		case VD_OP_GET_WCE:
		case VD_OP_SET_WCE:
		case VD_OP_GET_DEVID:
			/*
			 * Solaris issues VD_OP_GET_DEVID despite the
			 * fact that we don't advertise it.  It seems
			 * to be able to handle failure just fine, so
			 * we silently ignore it.
			 */
			vdsp_unimp(sc, vd);
			break;
		default:
			printf("%s: unsupported operation 0x%02x\n",
			    sc->sc_dv.dv_xname, vd->operation);
			vdsp_unimp(sc, vd);
			break;
		}
	}
}

void
vdsp_rx_vio_desc_data(struct vdsp_softc *sc, struct vio_msg_tag *tag)
{
	struct vdsk_desc_msg *dm = (struct vdsk_desc_msg *)tag;

	switch(tag->stype) {
	case VIO_SUBTYPE_INFO:
		DPRINTF(("DATA/INFO/DESC_DATA\n"));

		switch (dm->operation) {
		case VD_OP_BREAD:
			mtx_enter(&sc->sc_desc_mtx);
			sc->sc_desc_msg[sc->sc_desc_head++] = dm;
			sc->sc_desc_head &= (VDSK_RX_ENTRIES - 1);
			KASSERT(sc->sc_desc_head != sc->sc_desc_tail);
			mtx_leave(&sc->sc_desc_mtx);
			task_add(systq, &sc->sc_read_task);
			break;
		default:
			printf("%s: unsupported operation 0x%02x\n",
			    sc->sc_dv.dv_xname, dm->operation);
			break;
		}
		break;

	case VIO_SUBTYPE_ACK:
		DPRINTF(("DATA/ACK/DESC_DATA\n"));
		break;

	case VIO_SUBTYPE_NACK:
		DPRINTF(("DATA/NACK/DESC_DATA\n"));
		break;

	default:
		DPRINTF(("DATA/0x%02x/DESC_DATA\n", tag->stype));
		break;
	}
}

void
vdsp_ldc_reset(struct ldc_conn *lc)
{
	struct vdsp_softc *sc = lc->lc_sc;

	sc->sc_vio_state = 0;
	task_add(systq, &sc->sc_close_task);
}

void
vdsp_ldc_start(struct ldc_conn *lc)
{
	/* The vDisk client is supposed to initiate the handshake. */
}

void
vdsp_sendmsg(struct vdsp_softc *sc, void *msg, size_t len, int dowait)
{
	struct ldc_conn *lc = &sc->sc_lc;
	int err;

	do {
		err = ldc_send_unreliable(lc, msg, len);
		if (dowait && err == EWOULDBLOCK) {
			/*
			 * Seems like the hypervisor doesn't actually
			 * generate interrupts for transmit queues, so
			 * we specify a timeout such that we don't
			 * block forever.
			 */
			err = tsleep(lc->lc_txq, PWAIT, "vdsp", 1);
		}
	} while (dowait && err == EWOULDBLOCK);
}

void
vdsp_open(void *arg1)
{
	struct vdsp_softc *sc = arg1;
	struct proc *p = curproc;
	struct vd_attr_info ai;

	if (sc->sc_vp == NULL) {
		struct nameidata nd;
		struct vattr va;
		struct partinfo pi;
		const char *name;
		dev_t dev;
		int error;

		name = mdesc_get_prop_str(sc->sc_idx, "vds-block-device");
		if (name == NULL)
			return;

		NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, name, p);
		error = vn_open(&nd, FREAD | FWRITE, 0);
		if (error) {
			printf("VOP_OPEN: %s, %d\n", name, error);
			return;
		}

		if (nd.ni_vp->v_type == VBLK) {
			dev = nd.ni_vp->v_rdev;
			error = (*bdevsw[major(dev)].d_ioctl)(dev,
			    DIOCGPART, (caddr_t)&pi, FREAD, curproc);
			if (error)
				printf("DIOCGPART: %s, %d\n", name, error);
			sc->sc_vdisk_block_size = pi.disklab->d_secsize;
			sc->sc_vdisk_size = DL_GETPSIZE(pi.part);
		} else {
			error = VOP_GETATTR(nd.ni_vp, &va, p->p_ucred, p);
			if (error)
				printf("VOP_GETATTR: %s, %d\n", name, error);
			sc->sc_vdisk_block_size = DEV_BSIZE;
			sc->sc_vdisk_size = va.va_size / DEV_BSIZE;
		}

		VOP_UNLOCK(nd.ni_vp, 0, p);
		sc->sc_vp = nd.ni_vp;

		vdsp_readlabel(sc);
	}

	bzero(&ai, sizeof(ai));
	ai.tag.type = VIO_TYPE_CTRL;
	ai.tag.stype = VIO_SUBTYPE_ACK;
	ai.tag.stype_env = VIO_ATTR_INFO;
	ai.tag.sid = sc->sc_local_sid;
	ai.xfer_mode = sc->sc_xfer_mode;
	ai.vd_type = VD_DISK_TYPE_DISK;
	if (sc->sc_major > 1 || sc->sc_minor >= 1) {
		if (vdsp_is_iso(sc))
			ai.vd_mtype = VD_MEDIA_TYPE_CD;
		else
			ai.vd_mtype = VD_MEDIA_TYPE_FIXED;
	}
	ai.vdisk_block_size = sc->sc_vdisk_block_size;
	ai.operations = VD_OP_MASK;
	ai.vdisk_size = sc->sc_vdisk_size;
	ai.max_xfer_sz = MAXPHYS / sc->sc_vdisk_block_size;
	vdsp_sendmsg(sc, &ai, sizeof(ai), 1);
}

void
vdsp_close(void *arg1)
{
	struct vdsp_softc *sc = arg1;
	struct proc *p = curproc;

	sc->sc_seq_no = 0;

	if (sc->sc_vd) {
		free(sc->sc_vd, M_DEVBUF, 0);
		sc->sc_vd = NULL;
	}
	if (sc->sc_vd_ring != NULL) {
		free(sc->sc_vd_ring, M_DEVBUF,
		    sc->sc_num_descriptors * sizeof(*sc->sc_vd_ring));
		sc->sc_vd_ring = NULL;
	}
	if (sc->sc_label) {
		free(sc->sc_label, M_DEVBUF, 0);
		sc->sc_label = NULL;
	}
	if (sc->sc_vp) {
		vn_close(sc->sc_vp, FREAD | FWRITE, p->p_ucred, p);
		sc->sc_vp = NULL;
	}
}

void
vdsp_readlabel(struct vdsp_softc *sc)
{
	struct proc *p = curproc;
	struct iovec iov;
	struct uio uio;
	int err;

	if (sc->sc_vp == NULL)
		return;

	sc->sc_label = malloc(sizeof(*sc->sc_label), M_DEVBUF, M_WAITOK);

	iov.iov_base = sc->sc_label;
	iov.iov_len = sizeof(*sc->sc_label);
	uio.uio_iov = &iov;
	uio.uio_iovcnt = 1;
	uio.uio_offset = 0;
	uio.uio_resid = sizeof(*sc->sc_label);
	uio.uio_segflg = UIO_SYSSPACE;
	uio.uio_rw = UIO_READ;
	uio.uio_procp = p;

	vn_lock(sc->sc_vp, LK_EXCLUSIVE | LK_RETRY, p);
	err = VOP_READ(sc->sc_vp, &uio, 0, p->p_ucred);
	VOP_UNLOCK(sc->sc_vp, 0, p);
	if (err) {
		free(sc->sc_label, M_DEVBUF, 0);
		sc->sc_label = NULL;
	}
}

int
vdsp_writelabel(struct vdsp_softc *sc)
{
	struct proc *p = curproc;
	struct iovec iov;
	struct uio uio;
	int err;

	if (sc->sc_vp == NULL || sc->sc_label == NULL)
		return (EINVAL);

	iov.iov_base = sc->sc_label;
	iov.iov_len = sizeof(*sc->sc_label);
	uio.uio_iov = &iov;
	uio.uio_iovcnt = 1;
	uio.uio_offset = 0;
	uio.uio_resid = sizeof(*sc->sc_label);
	uio.uio_segflg = UIO_SYSSPACE;
	uio.uio_rw = UIO_WRITE;
	uio.uio_procp = p;

	vn_lock(sc->sc_vp, LK_EXCLUSIVE | LK_RETRY, p);
	err = VOP_WRITE(sc->sc_vp, &uio, 0, p->p_ucred);
	VOP_UNLOCK(sc->sc_vp, 0, p);

	return (err);
}

int
vdsp_is_iso(struct vdsp_softc *sc)
{
	struct proc *p = curproc;
	struct iovec iov;
	struct uio uio;
	struct iso_volume_descriptor *vdp;
	int err;

	if (sc->sc_vp == NULL)
		return (0);

	vdp = malloc(sizeof(*vdp), M_DEVBUF, M_WAITOK);

	iov.iov_base = vdp;
	iov.iov_len = sizeof(*vdp);
	uio.uio_iov = &iov;
	uio.uio_iovcnt = 1;
	uio.uio_offset = 16 * ISO_DEFAULT_BLOCK_SIZE;
	uio.uio_resid = sizeof(*vdp);
	uio.uio_segflg = UIO_SYSSPACE;
	uio.uio_rw = UIO_READ;
	uio.uio_procp = p;

	vn_lock(sc->sc_vp, LK_EXCLUSIVE | LK_RETRY, p);
	err = VOP_READ(sc->sc_vp, &uio, 0, p->p_ucred);
	VOP_UNLOCK(sc->sc_vp, 0, p);

	if (err == 0 && memcmp(vdp->id, ISO_STANDARD_ID, sizeof(vdp->id)))
		err = ENOENT;

	free(vdp, M_DEVBUF, 0);
	return (err == 0);
}

void
vdsp_alloc(void *arg1)
{
	struct vdsp_softc *sc = arg1;
	struct vio_dring_reg dr;

	KASSERT(sc->sc_num_descriptors <= VDSK_MAX_DESCRIPTORS);
	KASSERT(sc->sc_descriptor_size <= VDSK_MAX_DESCRIPTOR_SIZE);
	sc->sc_vd = mallocarray(sc->sc_num_descriptors,
	    sc->sc_descriptor_size, M_DEVBUF, M_WAITOK);
	sc->sc_vd_ring = mallocarray(sc->sc_num_descriptors,
	    sizeof(*sc->sc_vd_ring), M_DEVBUF, M_WAITOK);
	task_set(&sc->sc_vd_task, vdsp_vd_task, sc);

	bzero(&dr, sizeof(dr));
	dr.tag.type = VIO_TYPE_CTRL;
	dr.tag.stype = VIO_SUBTYPE_ACK;
	dr.tag.stype_env = VIO_DRING_REG;
	dr.tag.sid = sc->sc_local_sid;
	dr.dring_ident = ++sc->sc_dring_ident;
	vdsp_sendmsg(sc, &dr, sizeof(dr), 1);
}

void
vdsp_read(void *arg1)
{
	struct vdsp_softc *sc = arg1;

	mtx_enter(&sc->sc_desc_mtx);
	while (sc->sc_desc_tail != sc->sc_desc_head) {
		mtx_leave(&sc->sc_desc_mtx);
		vdsp_read_desc(sc, sc->sc_desc_msg[sc->sc_desc_tail]);
		mtx_enter(&sc->sc_desc_mtx);
		sc->sc_desc_tail++;
		sc->sc_desc_tail &= (VDSK_RX_ENTRIES - 1);
	}
	mtx_leave(&sc->sc_desc_mtx);
}

void
vdsp_read_desc(struct vdsp_softc *sc, struct vdsk_desc_msg *dm)
{
	struct ldc_conn *lc = &sc->sc_lc;
	struct proc *p = curproc;
	struct iovec iov;
	struct uio uio;
	caddr_t buf;
	vaddr_t va;
	paddr_t pa;
	uint64_t size, off;
	psize_t nbytes;
	int err, i;

	if (sc->sc_vp == NULL)
		return;

	buf = malloc(dm->size, M_DEVBUF, M_WAITOK);

	iov.iov_base = buf;
	iov.iov_len = dm->size;
	uio.uio_iov = &iov;
	uio.uio_iovcnt = 1;
	uio.uio_offset = dm->offset * DEV_BSIZE;
	uio.uio_resid = dm->size;
	uio.uio_segflg = UIO_SYSSPACE;
	uio.uio_rw = UIO_READ;
	uio.uio_procp = p;

	vn_lock(sc->sc_vp, LK_EXCLUSIVE | LK_RETRY, p);
	dm->status = VOP_READ(sc->sc_vp, &uio, 0, p->p_ucred);
	VOP_UNLOCK(sc->sc_vp, 0, p);

	KERNEL_UNLOCK();
	if (dm->status == 0) {
		i = 0;
		va = (vaddr_t)buf;
		size = dm->size;
		off = 0;
		while (size > 0 && i < dm->ncookies) {
			pmap_extract(pmap_kernel(), va, &pa);
			nbytes = MIN(size, dm->cookie[i].size - off);
			nbytes = MIN(nbytes, PAGE_SIZE - (off & PAGE_MASK));
			err = hv_ldc_copy(lc->lc_id, LDC_COPY_OUT,
			    dm->cookie[i].addr + off, pa, nbytes, &nbytes);
			if (err != H_EOK) {
				printf("%s: hv_ldc_copy: %d\n", __func__, err);
				dm->status = EIO;
				KERNEL_LOCK();
				goto fail;
			}
			va += nbytes;
			size -= nbytes;
			off += nbytes;
			if (off >= dm->cookie[i].size) {
				off = 0;
				i++;
			}
		}
	}
	KERNEL_LOCK();

fail:
	free(buf, M_DEVBUF, 0);

	/* ACK the descriptor. */
	dm->tag.stype = VIO_SUBTYPE_ACK;
	dm->tag.sid = sc->sc_local_sid;
	vdsp_sendmsg(sc, dm, sizeof(*dm) +
	    (dm->ncookies - 1) * sizeof(struct ldc_cookie), 1);
}

void
vdsp_read_dring(void *arg1, void *arg2)
{
	struct vdsp_softc *sc = arg1;
	struct ldc_conn *lc = &sc->sc_lc;
	struct vd_desc *vd = arg2;
	struct proc *p = curproc;
	struct iovec iov;
	struct uio uio;
	caddr_t buf;
	vaddr_t va;
	paddr_t pa;
	uint64_t size, off;
	psize_t nbytes;
	int err, i;

	if (sc->sc_vp == NULL)
		return;

	buf = malloc(vd->size, M_DEVBUF, M_WAITOK);

	iov.iov_base = buf;
	iov.iov_len = vd->size;
	uio.uio_iov = &iov;
	uio.uio_iovcnt = 1;
	uio.uio_offset = vd->offset * DEV_BSIZE;
	uio.uio_resid = vd->size;
	uio.uio_segflg = UIO_SYSSPACE;
	uio.uio_rw = UIO_READ;
	uio.uio_procp = p;

	vn_lock(sc->sc_vp, LK_EXCLUSIVE | LK_RETRY, p);
	vd->status = VOP_READ(sc->sc_vp, &uio, 0, p->p_ucred);
	VOP_UNLOCK(sc->sc_vp, 0, p);

	KERNEL_UNLOCK();
	if (vd->status == 0) {
		i = 0;
		va = (vaddr_t)buf;
		size = vd->size;
		off = 0;
		while (size > 0 && i < vd->ncookies) {
			pmap_extract(pmap_kernel(), va, &pa);
			nbytes = MIN(size, vd->cookie[i].size - off);
			nbytes = MIN(nbytes, PAGE_SIZE - (off & PAGE_MASK));
			err = hv_ldc_copy(lc->lc_id, LDC_COPY_OUT,
			    vd->cookie[i].addr + off, pa, nbytes, &nbytes);
			if (err != H_EOK) {
				printf("%s: hv_ldc_copy: %d\n", __func__, err);
				vd->status = EIO;
				KERNEL_LOCK();
				goto fail;
			}
			va += nbytes;
			size -= nbytes;
			off += nbytes;
			if (off >= vd->cookie[i].size) {
				off = 0;
				i++;
			}
		}
	}
	KERNEL_LOCK();

fail:
	free(buf, M_DEVBUF, 0);

	/* ACK the descriptor. */
	vd->hdr.dstate = VIO_DESC_DONE;
	vdsp_ack_desc(sc, vd);
}

void
vdsp_write_dring(void *arg1, void *arg2)
{
	struct vdsp_softc *sc = arg1;
	struct ldc_conn *lc = &sc->sc_lc;
	struct vd_desc *vd = arg2;
	struct proc *p = curproc;
	struct iovec iov;
	struct uio uio;
	caddr_t buf;
	vaddr_t va;
	paddr_t pa;
	uint64_t size, off;
	psize_t nbytes;
	int err, i;

	if (sc->sc_vp == NULL)
		return;

	buf = malloc(vd->size, M_DEVBUF, M_WAITOK);

	KERNEL_UNLOCK();
	i = 0;
	va = (vaddr_t)buf;
	size = vd->size;
	off = 0;
	while (size > 0 && i < vd->ncookies) {
		pmap_extract(pmap_kernel(), va, &pa);
		nbytes = MIN(size, vd->cookie[i].size - off);
		nbytes = MIN(nbytes, PAGE_SIZE - (off & PAGE_MASK));
		err = hv_ldc_copy(lc->lc_id, LDC_COPY_IN,
		    vd->cookie[i].addr + off, pa, nbytes, &nbytes);
		if (err != H_EOK) {
			printf("%s: hv_ldc_copy: %d\n", __func__, err);
			vd->status = EIO;
			KERNEL_LOCK();
			goto fail;
		}
		va += nbytes;
		size -= nbytes;
		off += nbytes;
		if (off >= vd->cookie[i].size) {
			off = 0;
			i++;
		}
	}
	KERNEL_LOCK();

	iov.iov_base = buf;
	iov.iov_len = vd->size;
	uio.uio_iov = &iov;
	uio.uio_iovcnt = 1;
	uio.uio_offset = vd->offset * DEV_BSIZE;
	uio.uio_resid = vd->size;
	uio.uio_segflg = UIO_SYSSPACE;
	uio.uio_rw = UIO_WRITE;
	uio.uio_procp = p;

	vn_lock(sc->sc_vp, LK_EXCLUSIVE | LK_RETRY, p);
	vd->status = VOP_WRITE(sc->sc_vp, &uio, 0, p->p_ucred);
	VOP_UNLOCK(sc->sc_vp, 0, p);

fail:
	free(buf, M_DEVBUF, 0);

	/* ACK the descriptor. */
	vd->hdr.dstate = VIO_DESC_DONE;
	vdsp_ack_desc(sc, vd);
}

void
vdsp_flush_dring(void *arg1, void *arg2)
{
	struct vdsp_softc *sc = arg1;
	struct vd_desc *vd = arg2;

	if (sc->sc_vp == NULL)
		return;

	/* ACK the descriptor. */
	vd->status = 0;
	vd->hdr.dstate = VIO_DESC_DONE;
	vdsp_ack_desc(sc, vd);
}

void
vdsp_get_vtoc(void *arg1, void *arg2)
{
	struct vdsp_softc *sc = arg1;
	struct ldc_conn *lc = &sc->sc_lc;
	struct vd_desc *vd = arg2;
	struct sun_vtoc_preamble *sl;
	struct vd_vtoc *vt;
	vaddr_t va;
	paddr_t pa;
	uint64_t size, off;
	psize_t nbytes;
	int err, i;

	vt = malloc(PAGE_SIZE, M_DEVBUF, M_WAITOK | M_ZERO);

	if (sc->sc_label == NULL)
		vdsp_readlabel(sc);

	if (sc->sc_label && sc->sc_label->sl_magic == SUN_DKMAGIC) {
		sl = (struct sun_vtoc_preamble *)sc->sc_label;

		memcpy(vt->ascii_label, sl->sl_text, sizeof(sl->sl_text));
		memcpy(vt->volume_name, sl->sl_volume, sizeof(sl->sl_volume));
		vt->sector_size = DEV_BSIZE;
		vt->num_partitions = sl->sl_nparts;
		for (i = 0; i < vt->num_partitions; i++) {
			vt->partition[i].id_tag = sl->sl_part[i].spi_tag;
			vt->partition[i].perm = sl->sl_part[i].spi_flag;
			vt->partition[i].start =
			    sc->sc_label->sl_part[i].sdkp_cyloffset *
				sc->sc_label->sl_ntracks *
				sc->sc_label->sl_nsectors;
			vt->partition[i].nblocks =
			    sc->sc_label->sl_part[i].sdkp_nsectors;
		}
	} else {
		uint64_t disk_size;
		int unit;

		/* Human-readable disk size. */
		disk_size = sc->sc_vdisk_size * sc->sc_vdisk_block_size;
		disk_size >>= 10;
		unit = 'K';
		if (disk_size > (2 << 10)) {
			disk_size >>= 10;
			unit = 'M';
		}
		if (disk_size > (2 << 10)) {
			disk_size >>= 10;
			unit = 'G';
		}

		snprintf(vt->ascii_label, sizeof(vt->ascii_label),
		    "OpenBSD-DiskImage-%lld%cB cyl %d alt %d hd %d sec %d",
		    disk_size, unit, sc->sc_ncyl, sc->sc_acyl,
		    sc->sc_nhead, sc->sc_nsect);
		vt->sector_size = sc->sc_vdisk_block_size;
		vt->num_partitions = 8;
		vt->partition[2].id_tag = SPTAG_WHOLE_DISK;
		vt->partition[2].nblocks =
		    sc->sc_ncyl * sc->sc_nhead * sc->sc_nsect;
	}

	i = 0;
	va = (vaddr_t)vt;
	size = roundup(sizeof(*vt), 64);
	off = 0;
	while (size > 0 && i < vd->ncookies) {
		pmap_extract(pmap_kernel(), va, &pa);
		nbytes = MIN(size, vd->cookie[i].size - off);
		nbytes = MIN(nbytes, PAGE_SIZE - (off & PAGE_MASK));
		err = hv_ldc_copy(lc->lc_id, LDC_COPY_OUT,
		    vd->cookie[i].addr + off, pa, nbytes, &nbytes);
		if (err != H_EOK) {
			printf("%s: hv_ldc_copy: %d\n", __func__, err);
			vd->status = EIO;
			goto fail;
		}
		va += nbytes;
		size -= nbytes;
		off += nbytes;
		if (off >= vd->cookie[i].size) {
			off = 0;
			i++;
		}
	}

	vd->status = 0;

fail:
	free(vt, M_DEVBUF, 0);

	/* ACK the descriptor. */
	vd->hdr.dstate = VIO_DESC_DONE;
	vdsp_ack_desc(sc, vd);
}

void
vdsp_set_vtoc(void *arg1, void *arg2)
{
	struct vdsp_softc *sc = arg1;
	struct ldc_conn *lc = &sc->sc_lc;
	struct vd_desc *vd = arg2;
	struct sun_vtoc_preamble *sl;
	struct vd_vtoc *vt;
	u_short cksum = 0, *sp1, *sp2;
	vaddr_t va;
	paddr_t pa;
	uint64_t size, off;
	psize_t nbytes;
	int err, i;

	vt = malloc(PAGE_SIZE, M_DEVBUF, M_WAITOK | M_ZERO);

	i = 0;
	va = (vaddr_t)vt;
	size = sizeof(*vt);
	off = 0;
	while (size > 0 && i < vd->ncookies) {
		pmap_extract(pmap_kernel(), va, &pa);
		nbytes = MIN(size, vd->cookie[i].size - off);
		nbytes = MIN(nbytes, PAGE_SIZE - (off & PAGE_MASK));
		err = hv_ldc_copy(lc->lc_id, LDC_COPY_IN,
		    vd->cookie[i].addr + off, pa, nbytes, &nbytes);
		if (err != H_EOK) {
			printf("%s: hv_ldc_copy: %d\n", __func__, err);
			vd->status = EIO;
			goto fail;
		}
		va += nbytes;
		size -= nbytes;
		off += nbytes;
		if (off >= vd->cookie[i].size) {
			off = 0;
			i++;
		}
	}

	if (vt->num_partitions > nitems(sc->sc_label->sl_part)) {
		vd->status = EINVAL;
		goto fail;
	}

	if (sc->sc_label == NULL || sc->sc_label->sl_magic != SUN_DKMAGIC) {
		sc->sc_label = malloc(sizeof(*sc->sc_label),
		    M_DEVBUF, M_WAITOK | M_ZERO);

		sc->sc_label->sl_ntracks = sc->sc_nhead;
		sc->sc_label->sl_nsectors = sc->sc_nsect;
		sc->sc_label->sl_ncylinders = sc->sc_ncyl;
		sc->sc_label->sl_acylinders = sc->sc_acyl;
		sc->sc_label->sl_pcylinders = sc->sc_ncyl + sc->sc_acyl;
		sc->sc_label->sl_rpm = 3600;

		sc->sc_label->sl_magic = SUN_DKMAGIC;
	}

	sl = (struct sun_vtoc_preamble *)sc->sc_label;
	memcpy(sl->sl_text, vt->ascii_label, sizeof(sl->sl_text));
	sl->sl_version = 0x01;
	memcpy(sl->sl_volume, sl->sl_volume, sizeof(sl->sl_volume));
	sl->sl_nparts = vt->num_partitions;
	for (i = 0; i < vt->num_partitions; i++) {
		sl->sl_part[i].spi_tag = vt->partition[i].id_tag;
		sl->sl_part[i].spi_flag = vt->partition[i].perm;
		sc->sc_label->sl_part[i].sdkp_cyloffset =
		    vt->partition[i].start / (sc->sc_nhead * sc->sc_nsect);
		sc->sc_label->sl_part[i].sdkp_nsectors =
		    vt->partition[i].nblocks;
	}
	sl->sl_sanity = 0x600ddeee;

	/* Compute the checksum. */
	sp1 = (u_short *)sc->sc_label;
	sp2 = (u_short *)(sc->sc_label + 1);
	while (sp1 < sp2)
		cksum ^= *sp1++;
	sc->sc_label->sl_cksum = cksum;

	vd->status = vdsp_writelabel(sc);

fail:
	free(vt, M_DEVBUF, 0);

	/* ACK the descriptor. */
	vd->hdr.dstate = VIO_DESC_DONE;
	vdsp_ack_desc(sc, vd);
}

void
vdsp_get_diskgeom(void *arg1, void *arg2)
{
	struct vdsp_softc *sc = arg1;
	struct ldc_conn *lc = &sc->sc_lc;
	struct vd_desc *vd = arg2;
	struct vd_diskgeom *vg;
	vaddr_t va;
	paddr_t pa;
	uint64_t size, off;
	psize_t nbytes;
	int err, i;

	vg = malloc(PAGE_SIZE, M_DEVBUF, M_WAITOK | M_ZERO);

	if (sc->sc_label == NULL)
		vdsp_readlabel(sc);

	if (sc->sc_label && sc->sc_label->sl_magic == SUN_DKMAGIC) {
		vg->ncyl = sc->sc_label->sl_ncylinders;
		vg->acyl = sc->sc_label->sl_acylinders;
		vg->nhead = sc->sc_label->sl_ntracks;
		vg->nsect = sc->sc_label->sl_nsectors;
		vg->intrlv = sc->sc_label->sl_interleave;
		vg->apc = sc->sc_label->sl_sparespercyl;
		vg->rpm = sc->sc_label->sl_rpm;
		vg->pcyl = sc->sc_label->sl_pcylinders;
	} else {
		uint64_t disk_size, block_size;

		disk_size = sc->sc_vdisk_size * sc->sc_vdisk_block_size;
		block_size = sc->sc_vdisk_block_size;

		if (disk_size >= 8L * 1024 * 1024 * 1024) {
			vg->nhead = 96;
			vg->nsect = 768;
		} else if (disk_size >= 2 *1024 * 1024) {
			vg->nhead = 1;
			vg->nsect = 600;
		} else {
			vg->nhead = 1;
			vg->nsect = 200;
		}

		vg->pcyl = disk_size / (block_size * vg->nhead * vg->nsect);
		if (vg->pcyl == 0)
			vg->pcyl = 1;
		if (vg->pcyl > 2)
			vg->acyl = 2;
		vg->ncyl = vg->pcyl - vg->acyl;

		vg->rpm = 3600;
	}

	sc->sc_ncyl = vg->ncyl;
	sc->sc_acyl = vg->acyl;
	sc->sc_nhead = vg->nhead;
	sc->sc_nsect = vg->nsect;

	i = 0;
	va = (vaddr_t)vg;
	size = roundup(sizeof(*vg), 64);
	off = 0;
	while (size > 0 && i < vd->ncookies) {
		pmap_extract(pmap_kernel(), va, &pa);
		nbytes = MIN(size, vd->cookie[i].size - off);
		nbytes = MIN(nbytes, PAGE_SIZE - (off & PAGE_MASK));
		err = hv_ldc_copy(lc->lc_id, LDC_COPY_OUT,
		    vd->cookie[i].addr + off, pa, nbytes, &nbytes);
		if (err != H_EOK) {
			printf("%s: hv_ldc_copy: %d\n", __func__, err);
			vd->status = EIO;
			goto fail;
		}
		va += nbytes;
		size -= nbytes;
		off += nbytes;
		if (off >= vd->cookie[i].size) {
			off = 0;
			i++;
		}
	}

	vd->status = 0;

fail:
	free(vg, M_DEVBUF, 0);

	/* ACK the descriptor. */
	vd->hdr.dstate = VIO_DESC_DONE;
	vdsp_ack_desc(sc, vd);
}

void
vdsp_unimp(void *arg1, void *arg2)
{
	struct vdsp_softc *sc = arg1;
	struct vd_desc *vd = arg2;

	/* ACK the descriptor. */
	vd->status = ENOTSUP;
	vd->hdr.dstate = VIO_DESC_DONE;
	vdsp_ack_desc(sc, vd);
}

void
vdsp_ack_desc(struct vdsp_softc *sc, struct vd_desc *vd)
{
	struct vio_dring_msg dm;
	vaddr_t va;
	paddr_t pa;
	uint64_t size, off;
	psize_t nbytes;
	int err;

	va = (vaddr_t)vd;
	off = (caddr_t)vd - sc->sc_vd;
	size = sc->sc_descriptor_size;
	while (size > 0) {
		pmap_extract(pmap_kernel(), va, &pa);
		nbytes = MIN(size, PAGE_SIZE - (off & PAGE_MASK));
		err = hv_ldc_copy(sc->sc_lc.lc_id, LDC_COPY_OUT,
		    sc->sc_dring_cookie.addr + off, pa, nbytes, &nbytes);
		if (err != H_EOK) {
			printf("%s: hv_ldc_copy %d\n", __func__, err);
			return;
		}
		va += nbytes;
		size -= nbytes;
		off += nbytes;
	}

	/* ACK the descriptor. */
	bzero(&dm, sizeof(dm));
	dm.tag.type = VIO_TYPE_DATA;
	dm.tag.stype = VIO_SUBTYPE_ACK;
	dm.tag.stype_env = VIO_DRING_DATA;
	dm.tag.sid = sc->sc_local_sid;
	dm.seq_no = ++sc->sc_seq_no;
	dm.dring_ident = sc->sc_dring_ident;
	off = (caddr_t)vd - sc->sc_vd;
	dm.start_idx = off / sc->sc_descriptor_size;
	dm.end_idx = off / sc->sc_descriptor_size;
	vdsp_sendmsg(sc, &dm, sizeof(dm), 1);
}

int
vdspopen(dev_t dev, int flag, int mode, struct proc *p)
{
	struct vdsp_softc *sc;
	struct ldc_conn *lc;
	int unit = minor(dev);
	int err;

	if (unit >= vdsp_cd.cd_ndevs)
		return (ENXIO);
	sc = vdsp_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	lc = &sc->sc_lc;

	err = hv_ldc_tx_qconf(lc->lc_id,
	    lc->lc_txq->lq_map->dm_segs[0].ds_addr, lc->lc_txq->lq_nentries);
	if (err != H_EOK)
		printf("%s: hv_ldc_tx_qconf %d\n", __func__, err);

	err = hv_ldc_rx_qconf(lc->lc_id,
	    lc->lc_rxq->lq_map->dm_segs[0].ds_addr, lc->lc_rxq->lq_nentries);
	if (err != H_EOK)
		printf("%s: hv_ldc_rx_qconf %d\n", __func__, err);

	cbus_intr_setenabled(sc->sc_bustag, sc->sc_tx_ino, INTR_ENABLED);
	cbus_intr_setenabled(sc->sc_bustag, sc->sc_rx_ino, INTR_ENABLED);

	return (0);
}

int
vdspclose(dev_t dev, int flag, int mode, struct proc *p)
{
	struct vdsp_softc *sc;
	int unit = minor(dev);

	if (unit >= vdsp_cd.cd_ndevs)
		return (ENXIO);
	sc = vdsp_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	cbus_intr_setenabled(sc->sc_bustag, sc->sc_tx_ino, INTR_DISABLED);
	cbus_intr_setenabled(sc->sc_bustag, sc->sc_rx_ino, INTR_DISABLED);

	hv_ldc_tx_qconf(sc->sc_lc.lc_id, 0, 0);
	hv_ldc_rx_qconf(sc->sc_lc.lc_id, 0, 0);

	task_add(systq, &sc->sc_close_task);
	return (0);
}

int
vdspioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p)
{
	struct vdsp_softc *sc;
	int unit = minor(dev);

	if (unit >= vdsp_cd.cd_ndevs)
		return (ENXIO);
	sc = vdsp_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	return (ENOTTY);
}