code:
/*	$OpenBSD: mb89352.c,v 1.20 2014/10/05 11:46:18 aoyama Exp $	*/
/*	$NetBSD: mb89352.c,v 1.5 2000/03/23 07:01:31 thorpej Exp $	*/
/*	NecBSD: mb89352.c,v 1.4 1998/03/14 07:31:20 kmatsuda Exp	*/

#ifdef DDB
#define	integrate
#else
#define	integrate	__inline static
#endif

/*-
 * Copyright (c) 1996,97,98,99 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Charles M. Hannum, Masaru Oki and Kouichi Matsuda.
 *
 * 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 Charles M. Hannum.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * Copyright (c) 1994 Jarle Greipsland
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
/*
 * [NetBSD for NEC PC-98 series]
 *  Copyright (c) 1996, 1997, 1998
 *	NetBSD/pc98 porting staff. All rights reserved.
 *  Copyright (c) 1996, 1997, 1998
 *	Kouichi Matsuda. All rights reserved.
 */

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

/* TODO list:
 * 1) Get the DMA stuff working.
 * 2) Get the iov/uio stuff working. Is this a good thing ???
 * 3) Get the synch stuff working.
 * 4) Rewrite it to use malloc for the acb structs instead of static alloc.?
 */

/*
 * A few customizable items:
 */

/* Synchronous data transfers? */
#define SPC_USE_SYNCHRONOUS	0
#define SPC_SYNC_REQ_ACK_OFS 	8

/* Wide data transfers? */
#define	SPC_USE_WIDE		0
#define	SPC_MAX_WIDTH		0

/* Max attempts made to transmit a message */
#define SPC_MSG_MAX_ATTEMPT	3 /* Not used now XXX */

/*
 * Some spin loop parameters (essentially how long to wait some places)
 * The problem(?) is that sometimes we expect either to be able to transmit a
 * byte or to get a new one from the SCSI bus pretty soon.  In order to avoid
 * returning from the interrupt just to get yanked back for the next byte we
 * may spin in the interrupt routine waiting for this byte to come.  How long?
 * This is really (SCSI) device and processor dependent.  Tuneable, I guess.
 */
#define SPC_MSGIN_SPIN	1 	/* Will spinwait upto ?ms for a new msg byte */
#define SPC_MSGOUT_SPIN	1

/*
 * Include debug functions?  At the end of this file there are a bunch of
 * functions that will print out various information regarding queued SCSI
 * commands, driver state and chip contents.  You can call them from the
 * kernel debugger.  If you set SPC_DEBUG to 0 they are not included (the
 * kernel uses less memory) but you lose the debugging facilities.
 */
/* #define SPC_DEBUG */

#define	SPC_ABORT_TIMEOUT	2000	/* time to wait for abort */

/* End of customizable parameters */

/*
 * MB89352 SCSI Protocol Controller (SPC) routines.
 */

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

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

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

#include <luna88k/dev/mb89352reg.h>
#include <luna88k/dev/mb89352var.h>

#ifndef DDB
#define	Debugger() panic("should call debugger here (mb89352.c)")
#endif /* ! DDB */

#ifdef SPC_DEBUG
int spc_debug = 0x00; /* SPC_SHOWSTART|SPC_SHOWMISC|SPC_SHOWTRACE; */
#endif

void	spc_done	(struct spc_softc *, struct spc_acb *);
void	spc_dequeue	(struct spc_softc *, struct spc_acb *);
void	spc_scsi_cmd	(struct scsi_xfer *);
int	spc_poll	(struct spc_softc *, struct scsi_xfer *, int);
integrate void	spc_sched_msgout(struct spc_softc *, u_char);
integrate void	spc_setsync(struct spc_softc *, struct spc_tinfo *);
void	spc_select	(struct spc_softc *, struct spc_acb *);
void	spc_timeout	(void *);
void	spc_scsi_reset	(struct spc_softc *);
void	spc_reset	(struct spc_softc *);
void	spc_acb_free	(void *, void *);
void	*spc_acb_alloc	(void *);
int	spc_reselect	(struct spc_softc *, int);
void	spc_sense	(struct spc_softc *, struct spc_acb *);
void	spc_msgin	(struct spc_softc *);
void	spc_abort	(struct spc_softc *, struct spc_acb *);
void	spc_msgout	(struct spc_softc *);
int	spc_dataout_pio	(struct spc_softc *, u_char *, int);
int	spc_datain_pio	(struct spc_softc *, u_char *, int);
#ifdef SPC_DEBUG
void	spc_print_acb	(struct spc_acb *);
void	spc_dump_driver (struct spc_softc *);
void	spc_dump89352	(struct spc_softc *);
void	spc_show_scsi_cmd(struct spc_acb *);
void	spc_print_active_acb(void);
#endif

extern struct cfdriver spc_cd;

/*
 * INITIALIZATION ROUTINES (probe, attach ++)
 */

void
/* spc_attach(sc) */
spc_attach(struct spc_softc *sc, struct scsi_adapter *adapter)
{
	struct scsibus_attach_args saa;
	SPC_TRACE(("spc_attach  "));
	sc->sc_state = SPC_INIT;

	sc->sc_freq = 20;	/* XXXX Assume 20 MHz. */

#if SPC_USE_SYNCHRONOUS
	/*
	 * These are the bounds of the sync period, based on the frequency of
	 * the chip's clock input and the size and offset of the sync period
	 * register.
	 *
	 * For a 20MHz clock, this gives us 25, or 100nS, or 10MB/s, as a
	 * maximum transfer rate, and 112.5, or 450nS, or 2.22MB/s, as a
	 * minimum transfer rate.
	 */
	sc->sc_minsync = (2 * 250) / sc->sc_freq;
	sc->sc_maxsync = (9 * 250) / sc->sc_freq;
#endif

	spc_init(sc);	/* Init chip and driver */

	/*
	 * Fill in the adapter.
	 */
	sc->sc_link.adapter_softc = sc;
	sc->sc_link.adapter_target = sc->sc_initiator;
	sc->sc_link.adapter = adapter;
	sc->sc_link.openings = 2;
	sc->sc_link.pool = &sc->sc_iopool;

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

	/*
	 * ask the adapter what subunits are present
	 */
	config_found(&sc->sc_dev, &saa, scsiprint);
}

/*
 * Initialize MB89352 chip itself
 * The following conditions should hold:
 * spc_isa_probe should have succeeded, i.e. the iobase address in spc_softc
 * must be valid.
 */
void
spc_reset(struct spc_softc *sc)
{
	bus_space_tag_t iot = sc->sc_iot;
	bus_space_handle_t ioh = sc->sc_ioh;

	SPC_TRACE(("spc_reset  "));
	/*
	 * Disable interrupts then reset the FUJITSU chip.
	 */
	bus_space_write_1(iot, ioh, SCTL, SCTL_DISABLE | SCTL_CTRLRST);
	bus_space_write_1(iot, ioh, SCMD, 0);
	bus_space_write_1(iot, ioh, TMOD, 0);
	bus_space_write_1(iot, ioh, PCTL, 0);
	bus_space_write_1(iot, ioh, TEMP, 0);
	bus_space_write_1(iot, ioh, TCH, 0);
	bus_space_write_1(iot, ioh, TCM, 0);
	bus_space_write_1(iot, ioh, TCL, 0);
	bus_space_write_1(iot, ioh, INTS, 0);
	bus_space_write_1(iot, ioh, SCTL,
	    SCTL_DISABLE | SCTL_ABRT_ENAB | SCTL_PARITY_ENAB | SCTL_RESEL_ENAB);
	bus_space_write_1(iot, ioh, BDID, sc->sc_initiator);
	delay(400);
	bus_space_write_1(iot, ioh, SCTL,
	    bus_space_read_1(iot, ioh, SCTL) & ~SCTL_DISABLE);
}

/*
 * Pull the SCSI RST line for 500us.
 */
void
spc_scsi_reset(struct spc_softc *sc)
{
	bus_space_tag_t iot = sc->sc_iot;
	bus_space_handle_t ioh = sc->sc_ioh;

	SPC_TRACE(("spc_scsi_reset  "));
	bus_space_write_1(iot, ioh, SCMD, bus_space_read_1(iot, ioh, SCMD) | SCMD_RST);
	delay(500);
	bus_space_write_1(iot, ioh, SCMD, bus_space_read_1(iot, ioh, SCMD) & ~SCMD_RST);
	delay(50);
}

/*
 * Initialize spc SCSI driver.
 */
void
spc_init(struct spc_softc *sc)
{
	struct spc_acb *acb;
	int r;

	SPC_TRACE(("spc_init  "));
	spc_reset(sc);
	spc_scsi_reset(sc);
	spc_reset(sc);

	if (sc->sc_state == SPC_INIT) {
		/* First time through; initialize. */
		TAILQ_INIT(&sc->ready_list);
		TAILQ_INIT(&sc->nexus_list);
		TAILQ_INIT(&sc->free_list);
		mtx_init(&sc->sc_acb_mtx, IPL_BIO);
		scsi_iopool_init(&sc->sc_iopool, sc, spc_acb_alloc, spc_acb_free);
		sc->sc_nexus = NULL;
		acb = sc->sc_acb;
		bzero(acb, sizeof(sc->sc_acb));
		for (r = 0; r < sizeof(sc->sc_acb) / sizeof(*acb); r++) {
			TAILQ_INSERT_TAIL(&sc->free_list, acb, chain);
			acb++;
		}
		bzero(&sc->sc_tinfo, sizeof(sc->sc_tinfo));
	} else {
		/* Cancel any active commands. */
		sc->sc_state = SPC_CLEANING;
		if ((acb = sc->sc_nexus) != NULL) {
			acb->xs->error = XS_DRIVER_STUFFUP;
			timeout_del(&acb->xs->stimeout);
			spc_done(sc, acb);
		}
		while ((acb = TAILQ_FIRST(&sc->nexus_list)) != NULL) {
			acb->xs->error = XS_DRIVER_STUFFUP;
			timeout_del(&acb->xs->stimeout);
			spc_done(sc, acb);
		}
	}

	sc->sc_prevphase = PH_INVALID;
	for (r = 0; r < 8; r++) {
		struct spc_tinfo *ti = &sc->sc_tinfo[r];

		ti->flags = 0;
#if SPC_USE_SYNCHRONOUS
		ti->flags |= DO_SYNC;
		ti->period = sc->sc_minsync;
		ti->offset = SPC_SYNC_REQ_ACK_OFS;
#else
		ti->period = ti->offset = 0;
#endif
#if SPC_USE_WIDE
		ti->flags |= DO_WIDE;
		ti->width = SPC_MAX_WIDTH;
#else
		ti->width = 0;
#endif
	}

	sc->sc_state = SPC_IDLE;
	bus_space_write_1(sc->sc_iot, sc->sc_ioh, SCTL,
	    bus_space_read_1(sc->sc_iot, sc->sc_ioh, SCTL) | SCTL_INTR_ENAB);
}

void
spc_acb_free(void *xsc, void *xacb)
{
	struct spc_softc *sc = xsc;
	struct spc_acb *acb = xacb;

	SPC_TRACE(("spc_acb_free  "));

	acb->flags = 0;
	mtx_enter(&sc->sc_acb_mtx);
	TAILQ_INSERT_HEAD(&sc->free_list, acb, chain);
	mtx_leave(&sc->sc_acb_mtx);
}

void *
spc_acb_alloc(void *xsc)
{
	struct spc_softc *sc = xsc;
	struct spc_acb *acb;

	SPC_TRACE(("spc_acb_alloc  "));

	mtx_enter(&sc->sc_acb_mtx);
	acb = TAILQ_FIRST(&sc->free_list);
	if (acb)
		TAILQ_REMOVE(&sc->free_list, acb, chain);
	mtx_leave(&sc->sc_acb_mtx);

	return acb;
}

/*
 * DRIVER FUNCTIONS CALLABLE FROM HIGHER LEVEL DRIVERS
 */

/*
 * Expected sequence:
 * 1) Command inserted into ready list
 * 2) Command selected for execution
 * 3) Command won arbitration and has selected target device
 * 4) Send message out (identify message, eventually also sync.negotiations)
 * 5) Send command
 * 5a) Receive disconnect message, disconnect.
 * 5b) Reselected by target
 * 5c) Receive identify message from target.
 * 6) Send or receive data
 * 7) Receive status
 * 8) Receive message (command complete etc.)
 * 9) If status == SCSI_CHECK construct a synthetic request sense SCSI cmd.
 *    Repeat 2-8 (no disconnects please...)
 */

/*
 * Start a SCSI-command
 * This function is called by the higher level SCSI-driver to queue/run
 * SCSI-commands.
 */
void
spc_scsi_cmd(struct scsi_xfer *xs)
{
	struct scsi_link *sc_link = xs->sc_link;
	struct spc_softc *sc = sc_link->adapter_softc;
	struct spc_acb *acb;
	int s, flags;

	SPC_TRACE(("spc_scsi_cmd  "));
	SPC_CMDS(("[0x%x, %d]->%d ", (int)xs->cmd->opcode, xs->cmdlen,
	    sc_link->target));

	flags = xs->flags;
	acb = xs->io;

	/* Initialize acb */
	acb->xs = xs;
	acb->timeout = xs->timeout;
	timeout_set(&xs->stimeout, spc_timeout, acb);

	if (xs->flags & SCSI_RESET) {
		acb->flags |= ACB_RESET;
		acb->scsi_cmd_length = 0;
		acb->data_length = 0;
	} else {
		bcopy(xs->cmd, &acb->scsi_cmd, xs->cmdlen);
		acb->scsi_cmd_length = xs->cmdlen;
		acb->data_addr = xs->data;
		acb->data_length = xs->datalen;
	}
	acb->target_stat = 0;

	s = splbio();

	TAILQ_INSERT_TAIL(&sc->ready_list, acb, chain);
	/*
	 * Start scheduling unless a queue process is in progress.
	 */
	if (sc->sc_state == SPC_IDLE)
		spc_sched(sc);
	/*
	 * After successful sending, check if we should return just now.
	 */

	splx(s);

	if ((flags & SCSI_POLL) == 0)
		return;

	/* Not allowed to use interrupts, use polling instead */
	s = splbio();
	if (spc_poll(sc, xs, acb->timeout)) {
		spc_timeout(acb);
		if (spc_poll(sc, xs, acb->timeout))
			spc_timeout(acb);
	}
	splx(s);
}

/*
 * Used when interrupt driven I/O isn't allowed, e.g. during boot.
 */
int
spc_poll(struct spc_softc *sc, struct scsi_xfer *xs, int count)
{
	bus_space_tag_t iot = sc->sc_iot;
	bus_space_handle_t ioh = sc->sc_ioh;

	SPC_TRACE(("spc_poll  "));
	while (count) {
		/*
		 * If we had interrupts enabled, would we
		 * have got an interrupt?
		 */
		if (bus_space_read_1(iot, ioh, INTS) != 0)
			spc_intr(sc);
		if ((xs->flags & ITSDONE) != 0)
			return 0;
		delay(1000);
		count--;
	}
	return 1;
}

/*
 * LOW LEVEL SCSI UTILITIES
 */

integrate void
spc_sched_msgout(struct spc_softc *sc, u_char m)
{
	bus_space_tag_t iot = sc->sc_iot;
	bus_space_handle_t ioh = sc->sc_ioh;

	SPC_TRACE(("spc_sched_msgout  "));
	if (sc->sc_msgpriq == 0)
		bus_space_write_1(iot, ioh, SCMD, SCMD_SET_ATN);
	sc->sc_msgpriq |= m;
}

/*
 * Set synchronous transfer offset and period.
 */
integrate void
spc_setsync(struct spc_softc *sc, struct spc_tinfo *ti)
{
#if SPC_USE_SYNCHRONOUS
	bus_space_tag_t iot = sc->sc_iot;
	bus_space_handle_t ioh = sc->sc_ioh;

	SPC_TRACE(("spc_setsync  "));
	if (ti->offset != 0)
		bus_space_write_1(iot, ioh, TMOD,
		    ((ti->period * sc->sc_freq) / 250 - 2) << 4 | ti->offset);
	else
		bus_space_write_1(iot, ioh, TMOD, 0);
#endif
}

/*
 * Start a selection.  This is used by spc_sched() to select an idle target,
 * and by spc_done() to immediately reselect a target to get sense information.
 */
void
spc_select(struct spc_softc *sc, struct spc_acb *acb)
{
	struct scsi_link *sc_link = acb->xs->sc_link;
	int target = sc_link->target;
	struct spc_tinfo *ti = &sc->sc_tinfo[target];
	bus_space_tag_t iot = sc->sc_iot;
	bus_space_handle_t ioh = sc->sc_ioh;

	SPC_TRACE(("spc_select  "));
	spc_setsync(sc, ti);

#if 0
	bus_space_write_1(iot, ioh, SCMD, SCMD_SET_ATN);
#endif

	bus_space_write_1(iot, ioh, PCTL, 0);
	bus_space_write_1(iot, ioh, TEMP,
	    (1 << sc->sc_initiator) | (1 << target));
	/*
	 * Setup BSY timeout (selection timeout).
	 * 250ms according to the SCSI specification.
	 * T = (X * 256 + 15) * Tclf * 2  (Tclf = 200ns on x68k)
	 * To setup 256ms timeout,
	 * 128000ns/200ns = X * 256 + 15
	 * 640 - 15 = X * 256
	 * X = 625 / 256
	 * X = 2 + 113 / 256
	 *  ==> tch = 2, tcm = 113 (correct?)
	 */
	/* Time to the information transfer phase start. */
	/* XXX These values should be calculated from sc_freq */
	bus_space_write_1(iot, ioh, TCH, 2);
	bus_space_write_1(iot, ioh, TCM, 113);
	bus_space_write_1(iot, ioh, TCL, 3);
	bus_space_write_1(iot, ioh, SCMD, SCMD_SELECT);

	sc->sc_state = SPC_SELECTING;
}

int
spc_reselect(struct spc_softc *sc, int message)
{
	u_char selid, target, lun;
	struct spc_acb *acb;
	struct scsi_link *sc_link;
	struct spc_tinfo *ti;

	SPC_TRACE(("spc_reselect  "));
	/*
	 * The SCSI chip made a snapshot of the data bus while the reselection
	 * was being negotiated.  This enables us to determine which target did
	 * the reselect.
	 */
	selid = sc->sc_selid & ~(1 << sc->sc_initiator);
	if (selid & (selid - 1)) {
		printf("%s: reselect with invalid selid %02x; "
		    "sending DEVICE RESET\n", sc->sc_dev.dv_xname, selid);
		SPC_BREAK();
		goto reset;
	}

	/*
	 * Search wait queue for disconnected cmd
	 * The list should be short, so I haven't bothered with
	 * any more sophisticated structures than a simple
	 * singly linked list.
	 */
	target = ffs(selid) - 1;
	lun = message & 0x07;
	TAILQ_FOREACH(acb, &sc->nexus_list, chain) {
		sc_link = acb->xs->sc_link;
		if (sc_link->target == target &&
		    sc_link->lun == lun)
			break;
	}
	if (acb == NULL) {
		printf("%s: reselect from target %d lun %d with no nexus; "
		    "sending ABORT\n", sc->sc_dev.dv_xname, target, lun);
		SPC_BREAK();
		goto abort;
	}

	/* Make this nexus active again. */
	TAILQ_REMOVE(&sc->nexus_list, acb, chain);
	sc->sc_state = SPC_CONNECTED;
	sc->sc_nexus = acb;
	ti = &sc->sc_tinfo[target];
	ti->lubusy |= (1 << lun);
	spc_setsync(sc, ti);

	if (acb->flags & ACB_RESET)
		spc_sched_msgout(sc, SEND_DEV_RESET);
	else if (acb->flags & ACB_ABORT)
		spc_sched_msgout(sc, SEND_ABORT);

	/* Do an implicit RESTORE POINTERS. */
	sc->sc_dp = acb->data_addr;
	sc->sc_dleft = acb->data_length;
	sc->sc_cp = (u_char *)&acb->scsi_cmd;
	sc->sc_cleft = acb->scsi_cmd_length;

	return (0);

reset:
	spc_sched_msgout(sc, SEND_DEV_RESET);
	return (1);

abort:
	spc_sched_msgout(sc, SEND_ABORT);
	return (1);
}

/*
 * Schedule a SCSI operation.  This has now been pulled out of the interrupt
 * handler so that we may call it from spc_scsi_cmd and spc_done.  This may
 * save us an unnecessary interrupt just to get things going.  Should only be
 * called when state == SPC_IDLE and at bio pl.
 */
void
spc_sched(struct spc_softc *sc)
{
	struct spc_acb *acb;
	struct scsi_link *sc_link;
	struct spc_tinfo *ti;

	/* missing the hw, just return and wait for our hw */
	if (sc->sc_flags & SPC_INACTIVE)
		return;
	SPC_TRACE(("spc_sched  "));
	/*
	 * Find first acb in ready queue that is for a target/lunit pair that
	 * is not busy.
	 */
	TAILQ_FOREACH(acb, &sc->ready_list, chain) {
		sc_link = acb->xs->sc_link;
		ti = &sc->sc_tinfo[sc_link->target];
		if ((ti->lubusy & (1 << sc_link->lun)) == 0) {
			SPC_MISC(("selecting %d:%d  ",
			    sc_link->target, sc_link->lun));
			TAILQ_REMOVE(&sc->ready_list, acb, chain);
			sc->sc_nexus = acb;
			spc_select(sc, acb);
			return;
		} else
			SPC_MISC(("%d:%d busy\n",
			    sc_link->target, sc_link->lun));
	}
	SPC_MISC(("idle  "));
	/* Nothing to start; just enable reselections and wait. */
}

void
spc_sense(struct spc_softc *sc, struct spc_acb *acb)
{
	struct scsi_xfer *xs = acb->xs;
	struct scsi_link *sc_link = xs->sc_link;
	struct spc_tinfo *ti = &sc->sc_tinfo[sc_link->target];
	struct scsi_sense *ss = (void *)&acb->scsi_cmd;

	SPC_MISC(("requesting sense  "));
	/* Next, setup a request sense command block */
	bzero(ss, sizeof(*ss));
	ss->opcode = REQUEST_SENSE;
	ss->byte2 = sc_link->lun << 5;
	ss->length = sizeof(struct scsi_sense_data);
	acb->scsi_cmd_length = sizeof(*ss);
	acb->data_addr = (char *)&xs->sense;
	acb->data_length = sizeof(struct scsi_sense_data);
	acb->flags |= ACB_SENSE;
	ti->senses++;
	if (acb->flags & ACB_NEXUS)
		ti->lubusy &= ~(1 << sc_link->lun);
	if (acb == sc->sc_nexus) {
		spc_select(sc, acb);
	} else {
		spc_dequeue(sc, acb);
		TAILQ_INSERT_HEAD(&sc->ready_list, acb, chain);
		if (sc->sc_state == SPC_IDLE)
			spc_sched(sc);
	}
}

/*
 * POST PROCESSING OF SCSI_CMD (usually current)
 */
void
spc_done(struct spc_softc *sc, struct spc_acb *acb)
{
	struct scsi_xfer *xs = acb->xs;
	struct scsi_link *sc_link = xs->sc_link;
	struct spc_tinfo *ti = &sc->sc_tinfo[sc_link->target];

	SPC_TRACE(("spc_done  "));

	/*
	 * Now, if we've come here with no error code, i.e. we've kept the
	 * initial XS_NOERROR, and the status code signals that we should
	 * check sense, we'll need to set up a request sense cmd block and
	 * push the command back into the ready queue *before* any other
	 * commands for this target/lunit, else we lose the sense info.
	 * We don't support chk sense conditions for the request sense cmd.
	 */
	if (xs->error == XS_NOERROR) {
		if (acb->flags & ACB_ABORT) {
			xs->error = XS_DRIVER_STUFFUP;
		} else if (acb->flags & ACB_SENSE) {
			xs->error = XS_SENSE;
		} else {
			switch (acb->target_stat) {
			case SCSI_CHECK:
				/* First, save the return values */
				xs->resid = acb->data_length;
				xs->status = acb->target_stat;
				spc_sense(sc, acb);
				return;
			case SCSI_BUSY:
				xs->error = XS_BUSY;
				break;
			case SCSI_OK:
				xs->resid = acb->data_length;
				break;
			default:
				xs->error = XS_DRIVER_STUFFUP;
#ifdef SPC_DEBUG
				printf("%s: spc_done: bad stat 0x%x\n",
				    sc->sc_dev.dv_xname, acb->target_stat);
#endif
				break;
			}
		}
	}

#ifdef SPC_DEBUG
	if ((spc_debug & SPC_SHOWMISC) != 0) {
		if (xs->resid != 0)
			printf("resid=%d ", xs->resid);
		if (xs->error == XS_SENSE)
			printf("sense=0x%02x\n", xs->sense.error_code);
		else
			printf("error=%d\n", xs->error);
	}
#endif

	/*
	 * Remove the ACB from whatever queue it happens to be on.
	 */
	if (acb->flags & ACB_NEXUS)
		ti->lubusy &= ~(1 << sc_link->lun);
	if (acb == sc->sc_nexus) {
		sc->sc_nexus = NULL;
		sc->sc_state = SPC_IDLE;
		spc_sched(sc);
	} else
		spc_dequeue(sc, acb);

	ti->cmds++;
	scsi_done(xs);
}

void
spc_dequeue(struct spc_softc *sc, struct spc_acb *acb)
{

	SPC_TRACE(("spc_dequeue  "));
	if (acb->flags & ACB_NEXUS)
		TAILQ_REMOVE(&sc->nexus_list, acb, chain);
	else
		TAILQ_REMOVE(&sc->ready_list, acb, chain);
}

/*
 * INTERRUPT/PROTOCOL ENGINE
 */

/*
 * Precondition:
 * The SCSI bus is already in the MSGI phase and there is a message byte
 * on the bus, along with an asserted REQ signal.
 */
void
spc_msgin(struct spc_softc *sc)
{
	bus_space_tag_t iot = sc->sc_iot;
	bus_space_handle_t ioh = sc->sc_ioh;
	int n;

	SPC_TRACE(("spc_msgin  "));

	if (sc->sc_prevphase == PH_MSGIN) {
		/* This is a continuation of the previous message. */
		n = sc->sc_imp - sc->sc_imess;
		goto nextbyte;
	}

	/* This is a new MESSAGE IN phase.  Clean up our state. */
	sc->sc_flags &= ~SPC_DROP_MSGIN;

nextmsg:
	n = 0;
	sc->sc_imp = &sc->sc_imess[n];

nextbyte:
	/*
	 * Read a whole message, but don't ack the last byte.  If we reject the
	 * message, we have to assert ATN during the message transfer phase
	 * itself.
	 */
	for (;;) {
#if 0
		for (;;) {
			if ((bus_space_read_1(iot, ioh, PSNS) & PSNS_REQ) != 0)
				break;
			/* Wait for REQINIT.  XXX Need timeout. */
		}
#endif
		if (bus_space_read_1(iot, ioh, INTS) != 0) {
			/*
			 * Target left MESSAGE IN, probably because it
			 * a) noticed our ATN signal, or
			 * b) ran out of messages.
			 */
			goto out;
		}

		/* If parity error, just dump everything on the floor. */
		if ((bus_space_read_1(iot, ioh, SERR) &
		     (SERR_SCSI_PAR|SERR_SPC_PAR)) != 0) {
			sc->sc_flags |= SPC_DROP_MSGIN;
			spc_sched_msgout(sc, SEND_PARITY_ERROR);
		}

		/* send TRANSFER command. */
		bus_space_write_1(iot, ioh, TCH, 0);
		bus_space_write_1(iot, ioh, TCM, 0);
		bus_space_write_1(iot, ioh, TCL, 1);
		bus_space_write_1(iot, ioh, PCTL,
				  sc->sc_phase | PCTL_BFINT_ENAB);
#ifdef x68k
		bus_space_write_1(iot, ioh, SCMD, SCMD_XFR); /* | SCMD_PROG_XFR */
#else
		bus_space_write_1(iot, ioh, SCMD, SCMD_XFR | SCMD_PROG_XFR);	/* XXX */
#endif
		for (;;) {
			/*if ((bus_space_read_1(iot, ioh, SSTS) & SSTS_BUSY) != 0
				&& (bus_space_read_1(iot, ioh, SSTS) & SSTS_DREG_EMPTY) != 0)*/
			if ((bus_space_read_1(iot, ioh, SSTS) & SSTS_DREG_EMPTY) == 0)
				break;
			if (bus_space_read_1(iot, ioh, INTS) != 0)
				goto out;
		}

		/* Gather incoming message bytes if needed. */
		if ((sc->sc_flags & SPC_DROP_MSGIN) == 0) {
			if (n >= SPC_MAX_MSG_LEN) {
				(void) bus_space_read_1(iot, ioh, DREG);
				sc->sc_flags |= SPC_DROP_MSGIN;
				spc_sched_msgout(sc, SEND_REJECT);
			} else {
				*sc->sc_imp++ = bus_space_read_1(iot, ioh, DREG);
				n++;
				/*
				 * This testing is suboptimal, but most
				 * messages will be of the one byte variety, so
				 * it should not affect performance
				 * significantly.
				 */
				if (n == 1 && IS1BYTEMSG(sc->sc_imess[0]))
					break;
				if (n == 2 && IS2BYTEMSG(sc->sc_imess[0]))
					break;
				if (n >= 3 && ISEXTMSG(sc->sc_imess[0]) &&
				    n == sc->sc_imess[1] + 2)
					break;
			}
		} else
			(void) bus_space_read_1(iot, ioh, DREG);

		/*
		 * If we reach this spot we're either:
		 * a) in the middle of a multi-byte message, or
		 * b) dropping bytes.
		 */
#if 0
		/* Ack the last byte read. */
		/*(void) bus_space_read_1(iot, ioh, DREG);*/
		while ((bus_space_read_1(iot, ioh, PSNS) & ACKI) != 0)
			;
#endif
	}

	SPC_MISC(("n=%d imess=0x%02x  ", n, sc->sc_imess[0]));

	/* We now have a complete message.  Parse it. */
	switch (sc->sc_state) {
		struct spc_acb *acb;
		struct scsi_link *sc_link;
		struct spc_tinfo *ti;

	case SPC_CONNECTED:
		SPC_ASSERT(sc->sc_nexus != NULL);
		acb = sc->sc_nexus;
		ti = &sc->sc_tinfo[acb->xs->sc_link->target];

		switch (sc->sc_imess[0]) {
		case MSG_CMDCOMPLETE:
			if (sc->sc_dleft < 0) {
				sc_link = acb->xs->sc_link;
				printf("%s: %ld extra bytes from %d:%d\n",
				    sc->sc_dev.dv_xname, -sc->sc_dleft,
				    sc_link->target, sc_link->lun);
				acb->data_length = 0;
			}
			acb->xs->resid = acb->data_length = sc->sc_dleft;
			sc->sc_state = SPC_CMDCOMPLETE;
			break;

		case MSG_PARITY_ERROR:
			/* Resend the last message. */
			spc_sched_msgout(sc, sc->sc_lastmsg);
			break;

		case MSG_MESSAGE_REJECT:
			SPC_MISC(("message rejected %02x  ", sc->sc_lastmsg));
			switch (sc->sc_lastmsg) {
#if SPC_USE_SYNCHRONOUS + SPC_USE_WIDE
			case SEND_IDENTIFY:
				ti->flags &= ~(DO_SYNC | DO_WIDE);
				ti->period = ti->offset = 0;
				spc_setsync(sc, ti);
				ti->width = 0;
				break;
#endif
#if SPC_USE_SYNCHRONOUS
			case SEND_SDTR:
				ti->flags &= ~DO_SYNC;
				ti->period = ti->offset = 0;
				spc_setsync(sc, ti);
				break;
#endif
#if SPC_USE_WIDE
			case SEND_WDTR:
				ti->flags &= ~DO_WIDE;
				ti->width = 0;
				break;
#endif
			case SEND_INIT_DET_ERR:
				spc_sched_msgout(sc, SEND_ABORT);
				break;
			}
			break;

		case MSG_NOOP:
			break;

		case MSG_DISCONNECT:
			ti->dconns++;
			sc->sc_state = SPC_DISCONNECT;
			break;

		case MSG_SAVEDATAPOINTER:
			acb->data_addr = sc->sc_dp;
			acb->data_length = sc->sc_dleft;
			break;

		case MSG_RESTOREPOINTERS:
			sc->sc_dp = acb->data_addr;
			sc->sc_dleft = acb->data_length;
			sc->sc_cp = (u_char *)&acb->scsi_cmd;
			sc->sc_cleft = acb->scsi_cmd_length;
			break;

		case MSG_EXTENDED:
			switch (sc->sc_imess[2]) {
#if SPC_USE_SYNCHRONOUS
			case MSG_EXT_SDTR:
				if (sc->sc_imess[1] != 3)
					goto reject;
				ti->period = sc->sc_imess[3];
				ti->offset = sc->sc_imess[4];
				ti->flags &= ~DO_SYNC;
				if (ti->offset == 0) {
				} else if (ti->period < sc->sc_minsync ||
					   ti->period > sc->sc_maxsync ||
					   ti->offset > 8) {
					ti->period = ti->offset = 0;
					spc_sched_msgout(sc, SEND_SDTR);
				} else {
					sc_print_addr(acb->xs->sc_link);
					printf("sync, offset %d, "
					    "period %dnsec\n",
					    ti->offset, ti->period * 4);
				}
				spc_setsync(sc, ti);
				break;
#endif

#if SPC_USE_WIDE
			case MSG_EXT_WDTR:
				if (sc->sc_imess[1] != 2)
					goto reject;
				ti->width = sc->sc_imess[3];
				ti->flags &= ~DO_WIDE;
				if (ti->width == 0) {
				} else if (ti->width > SPC_MAX_WIDTH) {
					ti->width = 0;
					spc_sched_msgout(sc, SEND_WDTR);
				} else {
					sc_print_addr(acb->xs->sc_link);
					printf("wide, width %d\n",
					    1 << (3 + ti->width));
				}
				break;
#endif

			default:
				printf("%s: unrecognized MESSAGE EXTENDED; "
				    "sending REJECT\n", sc->sc_dev.dv_xname);
				SPC_BREAK();
				goto reject;
			}
			break;

		default:
			printf("%s: unrecognized MESSAGE; sending REJECT\n",
			    sc->sc_dev.dv_xname);
			SPC_BREAK();
		reject:
			spc_sched_msgout(sc, SEND_REJECT);
			break;
		}
		break;

	case SPC_RESELECTED:
		if (!MSG_ISIDENTIFY(sc->sc_imess[0])) {
			printf("%s: reselect without IDENTIFY; "
			    "sending DEVICE RESET\n", sc->sc_dev.dv_xname);
			SPC_BREAK();
			goto reset;
		}

		(void) spc_reselect(sc, sc->sc_imess[0]);
		break;

	default:
		printf("%s: unexpected MESSAGE IN; sending DEVICE RESET\n",
		    sc->sc_dev.dv_xname);
		SPC_BREAK();
	reset:
		spc_sched_msgout(sc, SEND_DEV_RESET);
		break;

#ifdef notdef
	abort:
		spc_sched_msgout(sc, SEND_ABORT);
		break;
#endif
	}

	/* Ack the last message byte. */
#if 0 /* XXX? */
	(void) bus_space_read_1(iot, ioh, DREG);
	while ((bus_space_read_1(iot, ioh, PSNS) & ACKI) != 0)
		;
#endif

	/* Go get the next message, if any. */
	goto nextmsg;

out:
	bus_space_write_1(iot, ioh, SCMD, SCMD_RST_ACK);
	SPC_MISC(("n=%d imess=0x%02x  ", n, sc->sc_imess[0]));
}

/*
 * Send the highest priority, scheduled message.
 */
void
spc_msgout(struct spc_softc *sc)
{
	bus_space_tag_t iot = sc->sc_iot;
	bus_space_handle_t ioh = sc->sc_ioh;
#if SPC_USE_SYNCHRONOUS
	struct spc_tinfo *ti;
#endif
	int n;

	SPC_TRACE(("spc_msgout  "));

	if (sc->sc_prevphase == PH_MSGOUT) {
		if (sc->sc_omp == sc->sc_omess) {
			/*
			 * This is a retransmission.
			 *
			 * We get here if the target stayed in MESSAGE OUT
			 * phase.  Section 5.1.9.2 of the SCSI 2 spec indicates
			 * that all of the previously transmitted messages must
			 * be sent again, in the same order.  Therefore, we
			 * requeue all the previously transmitted messages, and
			 * start again from the top.  Our simple priority
			 * scheme keeps the messages in the right order.
			 */
			SPC_MISC(("retransmitting  "));
			sc->sc_msgpriq |= sc->sc_msgoutq;
			/*
			 * Set ATN.  If we're just sending a trivial 1-byte
			 * message, we'll clear ATN later on anyway.
			 */
			bus_space_write_1(iot, ioh, SCMD,
			    SCMD_SET_ATN); /* XXX? */
		} else {
			/* This is a continuation of the previous message. */
			n = sc->sc_omp - sc->sc_omess;
			goto nextbyte;
		}
	}

	/* No messages transmitted so far. */
	sc->sc_msgoutq = 0;
	sc->sc_lastmsg = 0;

nextmsg:
	/* Pick up highest priority message. */
	sc->sc_currmsg = sc->sc_msgpriq & -sc->sc_msgpriq;
	sc->sc_msgpriq &= ~sc->sc_currmsg;
	sc->sc_msgoutq |= sc->sc_currmsg;

	/* Build the outgoing message data. */
	switch (sc->sc_currmsg) {
	case SEND_IDENTIFY:
		SPC_ASSERT(sc->sc_nexus != NULL);
		sc->sc_omess[0] =
		    MSG_IDENTIFY(sc->sc_nexus->xs->sc_link->lun, 1);
		n = 1;
		break;

#if SPC_USE_SYNCHRONOUS
	case SEND_SDTR:
		SPC_ASSERT(sc->sc_nexus != NULL);
		ti = &sc->sc_tinfo[sc->sc_nexus->xs->sc_link->target];
		sc->sc_omess[4] = MSG_EXTENDED;
		sc->sc_omess[3] = MSG_EXT_SDTR_LEN;
		sc->sc_omess[2] = MSG_EXT_SDTR;
		sc->sc_omess[1] = ti->period >> 2;
		sc->sc_omess[0] = ti->offset;
		n = 5;
		break;
#endif

#if SPC_USE_WIDE
	case SEND_WDTR:
		SPC_ASSERT(sc->sc_nexus != NULL);
		ti = &sc->sc_tinfo[sc->sc_nexus->xs->sc_link->target];
		sc->sc_omess[3] = MSG_EXTENDED;
		sc->sc_omess[2] = MSG_EXT_WDTR_LEN;
		sc->sc_omess[1] = MSG_EXT_WDTR;
		sc->sc_omess[0] = ti->width;
		n = 4;
		break;
#endif

	case SEND_DEV_RESET:
		sc->sc_flags |= SPC_ABORTING;
		sc->sc_omess[0] = MSG_BUS_DEV_RESET;
		n = 1;
		break;

	case SEND_REJECT:
		sc->sc_omess[0] = MSG_MESSAGE_REJECT;
		n = 1;
		break;

	case SEND_PARITY_ERROR:
		sc->sc_omess[0] = MSG_PARITY_ERROR;
		n = 1;
		break;

	case SEND_INIT_DET_ERR:
		sc->sc_omess[0] = MSG_INITIATOR_DET_ERR;
		n = 1;
		break;

	case SEND_ABORT:
		sc->sc_flags |= SPC_ABORTING;
		sc->sc_omess[0] = MSG_ABORT;
		n = 1;
		break;

	default:
		printf("%s: unexpected MESSAGE OUT; sending NOOP\n",
		    sc->sc_dev.dv_xname);
		SPC_BREAK();
		sc->sc_omess[0] = MSG_NOOP;
		n = 1;
		break;
	}
	sc->sc_omp = &sc->sc_omess[n];

nextbyte:
	/* Send message bytes. */
	/* send TRANSFER command. */
	bus_space_write_1(iot, ioh, TCH, n >> 16);
	bus_space_write_1(iot, ioh, TCM, n >> 8);
	bus_space_write_1(iot, ioh, TCL, n);
	bus_space_write_1(iot, ioh, PCTL, sc->sc_phase | PCTL_BFINT_ENAB);
#ifdef x68k
	bus_space_write_1(iot, ioh, SCMD, SCMD_XFR);	/* XXX */
#else
	bus_space_write_1(iot, ioh, SCMD,
	    SCMD_XFR | SCMD_PROG_XFR | SCMD_ICPT_XFR);
#endif
	for (;;) {
		if ((bus_space_read_1(iot, ioh, SSTS) & SSTS_BUSY) != 0)
			break;
		if (bus_space_read_1(iot, ioh, INTS) != 0)
			goto out;
	}
	for (;;) {
#if 0
		for (;;) {
			if ((bus_space_read_1(iot, ioh, PSNS) & PSNS_REQ) != 0)
				break;
			/* Wait for REQINIT.  XXX Need timeout. */
		}
#endif
		if (bus_space_read_1(iot, ioh, INTS) != 0) {
			/*
			 * Target left MESSAGE OUT, possibly to reject
			 * our message.
			 *
			 * If this is the last message being sent, then we
			 * deassert ATN, since either the target is going to
			 * ignore this message, or it's going to ask for a
			 * retransmission via MESSAGE PARITY ERROR (in which
			 * case we reassert ATN anyway).
			 */
#if 0
			if (sc->sc_msgpriq == 0)
				bus_space_write_1(iot, ioh, SCMD, SCMD_RST_ATN);
#endif
			goto out;
		}

#if 0
		/* Clear ATN before last byte if this is the last message. */
		if (n == 1 && sc->sc_msgpriq == 0)
			bus_space_write_1(iot, ioh, SCMD, SCMD_RST_ATN);
#endif

		while ((bus_space_read_1(iot, ioh, SSTS) & SSTS_DREG_FULL) != 0)
			;
		/* Send message byte. */
		bus_space_write_1(iot, ioh, DREG, *--sc->sc_omp);
		--n;
		/* Keep track of the last message we've sent any bytes of. */
		sc->sc_lastmsg = sc->sc_currmsg;
#if 0
		/* Wait for ACK to be negated.  XXX Need timeout. */
		while ((bus_space_read_1(iot, ioh, PSNS) & ACKI) != 0)
			;
#endif

		if (n == 0)
			break;
	}

	/* We get here only if the entire message has been transmitted. */
	if (sc->sc_msgpriq != 0) {
		/* There are more outgoing messages. */
		goto nextmsg;
	}

	/*
	 * The last message has been transmitted.  We need to remember the last
	 * message transmitted (in case the target switches to MESSAGE IN phase
	 * and sends a MESSAGE REJECT), and the list of messages transmitted
	 * this time around (in case the target stays in MESSAGE OUT phase to
	 * request a retransmit).
	 */

out:
	/* Disable REQ/ACK protocol. */
	return;
}

/*
 * spc_dataout_pio: perform a data transfer using the FIFO datapath in the spc
 * Precondition: The SCSI bus should be in the DOUT phase, with REQ asserted
 * and ACK deasserted (i.e. waiting for a data byte).
 *
 * This new revision has been optimized (I tried) to make the common case fast,
 * and the rarer cases (as a result) somewhat more complex.
 */
int
spc_dataout_pio(struct spc_softc *sc, u_char *p, int n)
{
	bus_space_tag_t iot = sc->sc_iot;
	bus_space_handle_t ioh = sc->sc_ioh;
	u_char intstat = 0;
	int out = 0;
#define DOUTAMOUNT 8		/* Full FIFO */

	SPC_TRACE(("spc_dataout_pio  "));
	/* send TRANSFER command. */
	bus_space_write_1(iot, ioh, TCH, n >> 16);
	bus_space_write_1(iot, ioh, TCM, n >> 8);
	bus_space_write_1(iot, ioh, TCL, n);
	bus_space_write_1(iot, ioh, PCTL, sc->sc_phase | PCTL_BFINT_ENAB);
#ifdef x68k
	bus_space_write_1(iot, ioh, SCMD, SCMD_XFR);	/* XXX */
#else
	bus_space_write_1(iot, ioh, SCMD,
	    SCMD_XFR | SCMD_PROG_XFR | SCMD_ICPT_XFR);	/* XXX */
#endif
	for (;;) {
		if ((bus_space_read_1(iot, ioh, SSTS) & SSTS_BUSY) != 0)
			break;
		if (bus_space_read_1(iot, ioh, INTS) != 0)
			break;
	}

	/*
	 * I have tried to make the main loop as tight as possible.  This
	 * means that some of the code following the loop is a bit more
	 * complex than otherwise.
	 */
	while (n > 0) {
		int xfer;

		for (;;) {
			intstat = bus_space_read_1(iot, ioh, INTS);
			/* Wait till buffer is empty. */
			if ((bus_space_read_1(iot, ioh, SSTS) &
			    SSTS_DREG_EMPTY) != 0)
				break;
			/* Break on interrupt. */
			if (intstat != 0)
				goto phasechange;
		}

		xfer = min(DOUTAMOUNT, n);

		SPC_MISC(("%d> ", xfer));

		n -= xfer;
		out += xfer;
		bus_space_write_multi_1(iot, ioh, DREG, p, xfer);
		p += xfer;
	}

	if (out == 0) {
		for (;;) {
			if (bus_space_read_1(iot, ioh, INTS) != 0)
				break;
		}
		SPC_MISC(("extra data  "));
	} else {
		/* See the bytes off chip */
		for (;;) {
			/* Wait till buffer is empty. */
			if ((bus_space_read_1(iot, ioh, SSTS) &
			    SSTS_DREG_EMPTY) != 0)
				break;
			intstat = bus_space_read_1(iot, ioh, INTS);
			/* Break on interrupt. */
			if (intstat != 0)
				goto phasechange;
		}
	}

phasechange:
	/* Stop the FIFO data path. */

	if (intstat != 0) {
		/* Some sort of phase change. */
		int amount;

		amount = ((bus_space_read_1(iot, ioh, TCH) << 16) |
		    (bus_space_read_1(iot, ioh, TCM) << 8) |
		    bus_space_read_1(iot, ioh, TCL));
		if (amount > 0) {
			out -= amount;
			SPC_MISC(("+%d ", amount));
		}
	}

	return out;
}

/*
 * spc_datain_pio: perform data transfers using the FIFO datapath in the spc
 * Precondition: The SCSI bus should be in the DIN phase, with REQ asserted
 * and ACK deasserted (i.e. at least one byte is ready).
 *
 * For now, uses a pretty dumb algorithm, hangs around until all data has been
 * transferred.  This, is OK for fast targets, but not so smart for slow
 * targets which don't disconnect or for huge transfers.
 */
int
spc_datain_pio(struct spc_softc *sc, u_char *p, int n)
{
	bus_space_tag_t iot = sc->sc_iot;
	bus_space_handle_t ioh = sc->sc_ioh;
	u_int8_t intstat, sstat;
	int in = 0;
#define DINAMOUNT 8		/* Full FIFO */

	SPC_TRACE(("spc_datain_pio  "));
	/* send TRANSFER command. */
	bus_space_write_1(iot, ioh, TCH, n >> 16);
	bus_space_write_1(iot, ioh, TCM, n >> 8);
	bus_space_write_1(iot, ioh, TCL, n);
	bus_space_write_1(iot, ioh, PCTL, sc->sc_phase | PCTL_BFINT_ENAB);
#ifdef x68k
	bus_space_write_1(iot, ioh, SCMD, SCMD_XFR);	/* XXX */
#else
	bus_space_write_1(iot, ioh, SCMD,
	    SCMD_XFR | SCMD_PROG_XFR);	/* XXX */
#endif
	for (;;) {
		if ((bus_space_read_1(iot, ioh, SSTS) & SSTS_BUSY) != 0)
			break;
		if (bus_space_read_1(iot, ioh, INTS) != 0)
			goto phasechange;
	}

	/*
	 * We leave this loop if one or more of the following is true:
	 * a) phase != PH_DATAIN && FIFOs are empty
	 * b) reset has occurred or busfree is detected.
	 */
	while (n > 0) {
		int xfer;

		/* Wait for fifo half full or phase mismatch */
		for (;;) {
			intstat = bus_space_read_1(iot, ioh, INTS);
			sstat = bus_space_read_1(iot, ioh, SSTS);
			if (intstat != 0 ||
			    (sstat & SSTS_DREG_FULL) != 0 ||
			    (sstat & SSTS_DREG_EMPTY) == 0)
				break;
		}

#if 1
		if (intstat != 0)
			goto phasechange;
#else
		if (intstat != 0 &&
		    (sstat & SSTS_DREG_EMPTY) != 0)
			goto phasechange;
#endif
		if ((sstat & SSTS_DREG_FULL) != 0)
			xfer = min(DINAMOUNT, n);
		else
			xfer = 1;

		SPC_MISC((">%d ", xfer));

		n -= xfer;
		in += xfer;
		bus_space_read_multi_1(iot, ioh, DREG, p, xfer);
		p += xfer;

		if (intstat != 0)
			goto phasechange;
	}

	/*
	 * Some SCSI-devices are rude enough to transfer more data than what
	 * was requested, e.g. 2048 bytes from a CD-ROM instead of the
	 * requested 512.  Test for progress, i.e. real transfers.  If no real
	 * transfers have been performed (n is probably already zero) and the
	 * FIFO is not empty, waste some bytes....
	 */
	if (in == 0) {
		for (;;) {
			/* XXX needs timeout */
			if (bus_space_read_1(iot, ioh, INTS) != 0)
				break;
		}
		SPC_MISC(("extra data  "));
	}

phasechange:
	/* Stop the FIFO data path. */

	return in;
}

/*
 * Catch an interrupt from the adaptor
 */
/*
 * This is the workhorse routine of the driver.
 * Deficiencies (for now):
 * 1) always uses programmed I/O
 */
int
spc_intr(void *arg)
{
	struct spc_softc *sc = arg;
	bus_space_tag_t iot = sc->sc_iot;
	bus_space_handle_t ioh = sc->sc_ioh;
	u_char ints;
	struct spc_acb *acb;
	struct scsi_link *sc_link;
	struct spc_tinfo *ti;
	int n;

	/*
	 * On LUNA-88K2, 2 spc(4)'s share the level 3 interrupt.
	 * So, first, check if this deivce needs to process this interrupt.
	 */
	ints = bus_space_read_1(iot, ioh, INTS);
	if (ints == 0)		/* No interrupt event on this device */
		return 0;

	/*
	 * Disable interrupt.
	 */
	bus_space_write_1(iot, ioh, SCTL,
	    bus_space_read_1(iot, ioh, SCTL) & ~SCTL_INTR_ENAB);

	SPC_TRACE(("spc_intr  "));

loop:
	/*
	 * Loop until transfer completion.
	 */
	/*
	 * First check for abnormal conditions, such as reset.
	 */
#ifdef x68k			/* XXX? */
	while ((ints = bus_space_read_1(iot, ioh, INTS)) == 0)
		delay(1);
	SPC_MISC(("ints = 0x%x  ", ints));
#else
	ints = bus_space_read_1(iot, ioh, INTS);
	SPC_MISC(("ints = 0x%x  ", ints));
#endif

	if ((ints & INTS_RST) != 0) {
		printf("%s: SCSI bus reset\n", sc->sc_dev.dv_xname);
		goto reset;
	}

	/*
	 * Check for less serious errors.
	 */
	if ((bus_space_read_1(iot, ioh, SERR) & (SERR_SCSI_PAR|SERR_SPC_PAR))
	    != 0) {
		printf("%s: SCSI bus parity error\n", sc->sc_dev.dv_xname);
		if (sc->sc_prevphase == PH_MSGIN) {
			sc->sc_flags |= SPC_DROP_MSGIN;
			spc_sched_msgout(sc, SEND_PARITY_ERROR);
		} else
			spc_sched_msgout(sc, SEND_INIT_DET_ERR);
	}

	/*
	 * If we're not already busy doing something test for the following
	 * conditions:
	 * 1) We have been reselected by something
	 * 2) We have selected something successfully
	 * 3) Our selection process has timed out
	 * 4) This is really a bus free interrupt just to get a new command
	 *    going?
	 * 5) Spurious interrupt?
	 */
	switch (sc->sc_state) {
	case SPC_IDLE:
	case SPC_SELECTING:
		SPC_MISC(("ints:0x%02x ", ints));

		if ((ints & INTS_SEL) != 0) {
			/*
			 * We don't currently support target mode.
			 */
			printf("%s: target mode selected; going to BUS FREE\n",
			    sc->sc_dev.dv_xname);

			goto sched;
		} else if ((ints & INTS_RESEL) != 0) {
			SPC_MISC(("reselected  "));

			/*
			 * If we're trying to select a target ourselves,
			 * push our command back into the ready list.
			 */
			if (sc->sc_state == SPC_SELECTING) {
				SPC_MISC(("backoff selector  "));
				SPC_ASSERT(sc->sc_nexus != NULL);
				acb = sc->sc_nexus;
				sc->sc_nexus = NULL;
				TAILQ_INSERT_HEAD(&sc->ready_list, acb, chain);
			}

			/* Save reselection ID. */
			sc->sc_selid = bus_space_read_1(iot, ioh, TEMP);

			sc->sc_state = SPC_RESELECTED;
		} else if ((ints & INTS_CMD_DONE) != 0) {
			SPC_MISC(("selected  "));

			/*
			 * We have selected a target. Things to do:
			 * a) Determine what message(s) to send.
			 * b) Verify that we're still selecting the target.
			 * c) Mark device as busy.
			 */
			if (sc->sc_state != SPC_SELECTING) {
				printf("%s: selection out while idle; "
				    "resetting\n", sc->sc_dev.dv_xname);
				SPC_BREAK();
				goto reset;
			}
			SPC_ASSERT(sc->sc_nexus != NULL);
			acb = sc->sc_nexus;
			sc_link = acb->xs->sc_link;
			ti = &sc->sc_tinfo[sc_link->target];

			sc->sc_msgpriq = SEND_IDENTIFY;
			if (acb->flags & ACB_RESET)
				sc->sc_msgpriq |= SEND_DEV_RESET;
			else if (acb->flags & ACB_ABORT)
				sc->sc_msgpriq |= SEND_ABORT;
			else {
#if SPC_USE_SYNCHRONOUS
				if ((ti->flags & DO_SYNC) != 0)
					sc->sc_msgpriq |= SEND_SDTR;
#endif
#if SPC_USE_WIDE
				if ((ti->flags & DO_WIDE) != 0)
					sc->sc_msgpriq |= SEND_WDTR;
#endif
			}

			acb->flags |= ACB_NEXUS;
			ti->lubusy |= (1 << sc_link->lun);

			/* Do an implicit RESTORE POINTERS. */
			sc->sc_dp = acb->data_addr;
			sc->sc_dleft = acb->data_length;
			sc->sc_cp = (u_char *)&acb->scsi_cmd;
			sc->sc_cleft = acb->scsi_cmd_length;

			/* On our first connection, schedule a timeout. */
			if ((acb->xs->flags & SCSI_POLL) == 0)
				timeout_add_msec(&acb->xs->stimeout,
				    acb->timeout);
			sc->sc_state = SPC_CONNECTED;
		} else if ((ints & INTS_TIMEOUT) != 0) {
			SPC_MISC(("selection timeout  "));

			if (sc->sc_state != SPC_SELECTING) {
				printf("%s: selection timeout while idle; "
				    "resetting\n", sc->sc_dev.dv_xname);
				SPC_BREAK();
				goto reset;
			}
			SPC_ASSERT(sc->sc_nexus != NULL);
			acb = sc->sc_nexus;

			delay(250);

			acb->xs->error = XS_SELTIMEOUT;
			goto finish;
		} else {
			if (sc->sc_state != SPC_IDLE) {
				printf("%s: BUS FREE while not idle; "
				    "state=%d\n",
				    sc->sc_dev.dv_xname, sc->sc_state);
				SPC_BREAK();
				goto out;
			}

			goto sched;
		}

		/*
		 * Turn off selection stuff, and prepare to catch bus free
		 * interrupts, parity errors, and phase changes.
		 */

		sc->sc_flags = 0;
		sc->sc_prevphase = PH_INVALID;
		goto dophase;
	}

	if ((ints & INTS_DISCON) != 0) {
		/* disable disconnect interrupt */
		bus_space_write_1(iot, ioh, PCTL,
		    bus_space_read_1(iot, ioh, PCTL) & ~PCTL_BFINT_ENAB);
		/* XXX reset interrput */
		bus_space_write_1(iot, ioh, INTS, ints);

		switch (sc->sc_state) {
		case SPC_RESELECTED:
			goto sched;

		case SPC_CONNECTED:
			SPC_ASSERT(sc->sc_nexus != NULL);
			acb = sc->sc_nexus;

#if SPC_USE_SYNCHRONOUS + SPC_USE_WIDE
			if (sc->sc_prevphase == PH_MSGOUT) {
				/*
				 * If the target went to BUS FREE phase during
				 * or immediately after sending a SDTR or WDTR
				 * message, disable negotiation.
				 */
				sc_link = acb->xs->sc_link;
				ti = &sc->sc_tinfo[sc_link->target];
				switch (sc->sc_lastmsg) {
#if SPC_USE_SYNCHRONOUS
				case SEND_SDTR:
					ti->flags &= ~DO_SYNC;
					ti->period = ti->offset = 0;
					break;
#endif
#if SPC_USE_WIDE
				case SEND_WDTR:
					ti->flags &= ~DO_WIDE;
					ti->width = 0;
					break;
#endif
				}
			}
#endif

			if ((sc->sc_flags & SPC_ABORTING) == 0) {
				/*
				 * Section 5.1.1 of the SCSI 2 spec suggests
				 * issuing a REQUEST SENSE following an
				 * unexpected disconnect.  Some devices go into
				 * a contingent allegiance condition when
				 * disconnecting, and this is necessary to
				 * clean up their state.
				 */
				printf("%s: unexpected disconnect; "
				    "sending REQUEST SENSE\n",
				    sc->sc_dev.dv_xname);
				SPC_BREAK();
				spc_sense(sc, acb);
				goto out;
			}

			acb->xs->error = XS_DRIVER_STUFFUP;
			goto finish;

		case SPC_DISCONNECT:
			SPC_ASSERT(sc->sc_nexus != NULL);
			acb = sc->sc_nexus;
			TAILQ_INSERT_HEAD(&sc->nexus_list, acb, chain);
			sc->sc_nexus = NULL;
			goto sched;

		case SPC_CMDCOMPLETE:
			SPC_ASSERT(sc->sc_nexus != NULL);
			acb = sc->sc_nexus;
			goto finish;
		}
	}
	else if ((ints & INTS_CMD_DONE) != 0 &&
	    sc->sc_prevphase == PH_MSGIN && sc->sc_state != SPC_CONNECTED)
		goto out;

dophase:
#if 0
	if ((bus_space_read_1(iot, ioh, PSNS) & PSNS_REQ) == 0) {
		/* Wait for REQINIT. */
		goto out;
	}
#else
	bus_space_write_1(iot, ioh, INTS, ints);
	ints = 0;
	while ((bus_space_read_1(iot, ioh, PSNS) & PSNS_REQ) == 0)
		delay(1);	/* need timeout XXX */
#endif

	/*
	 * State transition.
	 */
	sc->sc_phase = bus_space_read_1(iot, ioh, PSNS) & PH_MASK;
#if 0
	bus_space_write_1(iot, ioh, PCTL, sc->sc_phase);
#endif

	SPC_MISC(("phase=%d\n", sc->sc_phase));
	switch (sc->sc_phase) {
	case PH_MSGOUT:
		if (sc->sc_state != SPC_CONNECTED &&
		    sc->sc_state != SPC_RESELECTED)
			break;
		spc_msgout(sc);
		sc->sc_prevphase = PH_MSGOUT;
		goto loop;

	case PH_MSGIN:
		if (sc->sc_state != SPC_CONNECTED &&
		    sc->sc_state != SPC_RESELECTED)
			break;
		spc_msgin(sc);
		sc->sc_prevphase = PH_MSGIN;
		goto loop;

	case PH_CMD:
		if (sc->sc_state != SPC_CONNECTED)
			break;
#ifdef SPC_DEBUG
		if ((spc_debug & SPC_SHOWMISC) != 0) {
			SPC_ASSERT(sc->sc_nexus != NULL);
			acb = sc->sc_nexus;
			printf("cmd=0x%02x+%d  ",
			    acb->scsi_cmd.opcode, acb->scsi_cmd_length - 1);
		}
#endif
		n = spc_dataout_pio(sc, sc->sc_cp, sc->sc_cleft);
		sc->sc_cp += n;
		sc->sc_cleft -= n;
		sc->sc_prevphase = PH_CMD;
		goto loop;

	case PH_DATAOUT:
		if (sc->sc_state != SPC_CONNECTED)
			break;
		SPC_MISC(("dataout dleft=%d  ", sc->sc_dleft));
		n = spc_dataout_pio(sc, sc->sc_dp, sc->sc_dleft);
		sc->sc_dp += n;
		sc->sc_dleft -= n;
		sc->sc_prevphase = PH_DATAOUT;
		goto loop;

	case PH_DATAIN:
		if (sc->sc_state != SPC_CONNECTED)
			break;
		SPC_MISC(("datain  "));
		n = spc_datain_pio(sc, sc->sc_dp, sc->sc_dleft);
		sc->sc_dp += n;
		sc->sc_dleft -= n;
		sc->sc_prevphase = PH_DATAIN;
		goto loop;

	case PH_STAT:
		if (sc->sc_state != SPC_CONNECTED)
			break;
		SPC_ASSERT(sc->sc_nexus != NULL);
		acb = sc->sc_nexus;
		/*acb->target_stat = bus_space_read_1(iot, ioh, DREG);*/
		spc_datain_pio(sc, &acb->target_stat, 1);
		SPC_MISC(("target_stat=0x%02x  ", acb->target_stat));
		sc->sc_prevphase = PH_STAT;
		goto loop;
	}

	printf("%s: unexpected bus phase; resetting\n", sc->sc_dev.dv_xname);
	SPC_BREAK();
reset:
	spc_init(sc);
	return 1;

finish:
	timeout_del(&acb->xs->stimeout);
	bus_space_write_1(iot, ioh, INTS, ints);
	ints = 0;
	spc_done(sc, acb);
	goto out;

sched:
	sc->sc_state = SPC_IDLE;
	spc_sched(sc);
	goto out;

out:
	if (ints)
		bus_space_write_1(iot, ioh, INTS, ints);
	bus_space_write_1(iot, ioh, SCTL,
	    bus_space_read_1(iot, ioh, SCTL) | SCTL_INTR_ENAB);
	return 1;
}

void
spc_abort(struct spc_softc *sc, struct spc_acb *acb)
{

	/* 2 secs for the abort */
	acb->timeout = SPC_ABORT_TIMEOUT;
	acb->flags |= ACB_ABORT;

	if (acb == sc->sc_nexus) {
		/*
		 * If we're still selecting, the message will be scheduled
		 * after selection is complete.
		 */
		if (sc->sc_state == SPC_CONNECTED)
			spc_sched_msgout(sc, SEND_ABORT);
	} else {
		spc_dequeue(sc, acb);
		TAILQ_INSERT_HEAD(&sc->ready_list, acb, chain);
		if (sc->sc_state == SPC_IDLE)
			spc_sched(sc);
	}
}

void
spc_timeout(void *arg)
{
	struct spc_acb *acb = arg;
	struct scsi_xfer *xs = acb->xs;
	struct scsi_link *sc_link = xs->sc_link;
	struct spc_softc *sc = sc_link->adapter_softc;
	int s;

	sc_print_addr(sc_link);
	printf("timed out");

	s = splbio();

	if (acb->flags & ACB_ABORT) {
		/* abort timed out */
		printf(" AGAIN\n");
		/* XXX Must reset! */
	} else {
		/* abort the operation that has timed out */
		printf("\n");
		acb->xs->error = XS_TIMEOUT;
		spc_abort(sc, acb);
	}

	splx(s);
}

#ifdef SPC_DEBUG
/*
 * The following functions are mostly used for debugging purposes, either
 * directly called from the driver or from the kernel debugger.
 */

void
spc_show_scsi_cmd(spc_acb *acb)
{
	u_char  *b = (u_char *)&acb->scsi_cmd;
	struct scsi_link *sc_link = acb->xs->sc_link;
	int i;

	sc_print_addr(sc_link);
	if ((acb->xs->flags & SCSI_RESET) == 0) {
		for (i = 0; i < acb->scsi_cmd_length; i++) {
			if (i)
				printf(",");
			printf("%x", b[i]);
		}
		printf("\n");
	} else
		printf("RESET\n");
}

void
spc_print_acb(spc_acb *acb)
{

	printf("acb@%p xs=%p flags=%x", acb, acb->xs, acb->flags);
	printf(" dp=%p dleft=%d target_stat=%x\n",
	       acb->data_addr, acb->data_length, acb->target_stat);
	spc_show_scsi_cmd(acb);
}

void
spc_print_active_acb()
{
	struct spc_acb *acb;
	struct spc_softc *sc = spc_cd.cd_devs[0]; /* XXX */

	printf("ready list:\n");
	TAILQ_FOREACH(acb, &sc->ready_list, chain)
		spc_print_acb(acb);
	printf("nexus:\n");
	if (sc->sc_nexus != NULL)
		spc_print_acb(sc->sc_nexus);
	printf("nexus list:\n");
	TAILQ_FOREACH(acb, &sc->nexus_list, chain)
		spc_print_acb(acb);
}

void
spc_dump89352(struct spc_softc *sc)
{
	bus_space_tag_t iot = sc->sc_iot;
	bus_space_handle_t ioh = sc->sc_ioh;

	printf("mb89352: BDID=%x SCTL=%x SCMD=%x TMOD=%x\n",
	    bus_space_read_1(iot, ioh, BDID),
	    bus_space_read_1(iot, ioh, SCTL),
	    bus_space_read_1(iot, ioh, SCMD),
	    bus_space_read_1(iot, ioh, TMOD));
	printf("         INTS=%x PSNS=%x SSTS=%x SERR=%x PCTL=%x\n",
	    bus_space_read_1(iot, ioh, INTS),
	    bus_space_read_1(iot, ioh, PSNS),
	    bus_space_read_1(iot, ioh, SSTS),
	    bus_space_read_1(iot, ioh, SERR),
	    bus_space_read_1(iot, ioh, PCTL));
	printf("         MBC=%x DREG=%x TEMP=%x TCH=%x TCM=%x\n",
	    bus_space_read_1(iot, ioh, MBC),
#if 0
	    bus_space_read_1(iot, ioh, DREG),
#else
	    0,
#endif
	    bus_space_read_1(iot, ioh, TEMP),
	    bus_space_read_1(iot, ioh, TCH),
	    bus_space_read_1(iot, ioh, TCM));
	printf("         TCL=%x EXBF=%x\n",
	    bus_space_read_1(iot, ioh, TCL),
	    bus_space_read_1(iot, ioh, EXBF));
}

void
spc_dump_driver(struct spc_softc *sc)
{
	struct spc_tinfo *ti;
	int i;

	printf("nexus=%p prevphase=%x\n", sc->sc_nexus, sc->sc_prevphase);
	printf("state=%x msgin=%x msgpriq=%x msgoutq=%x lastmsg=%x "
	    "currmsg=%x\n", sc->sc_state, sc->sc_imess[0],
	    sc->sc_msgpriq, sc->sc_msgoutq, sc->sc_lastmsg, sc->sc_currmsg);
	for (i = 0; i < 7; i++) {
		ti = &sc->sc_tinfo[i];
		printf("tinfo%d: %d cmds %d disconnects %d timeouts",
		    i, ti->cmds, ti->dconns, ti->touts);
		printf(" %d senses flags=%x\n", ti->senses, ti->flags);
	}
}
#endif


code:
/*	$OpenBSD: mb89352reg.h,v 1.4 2008/10/17 18:30:20 okan Exp $	*/
/*	$NetBSD: mb89352reg.h,v 1.3 2003/08/07 16:31:02 agc Exp $	*/
/*	NecBSD: mb89352reg.h,v 1.3 1998/03/14 07:04:34 kmatsuda Exp 	*/

/*-
 * Copyright (c) 1990, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Charles M. Hannum, Masaru Oki and Kouichi Matsuda.
 *
 * This code is derived from software contributed to Berkeley by
 * Van Jacobson of Lawrence Berkeley Laboratory.
 *
 * 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. Neither the name of the University nor the names of its contributors
 *    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.
 *
 *	@(#)scsireg.h	8.1 (Berkeley) 6/10/93
 */

/*-
 * Copyright (c) 1996,97,98,99 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Charles M. Hannum, Masaru Oki and Kouichi Matsuda.
 *
 * This code is derived from software contributed to Berkeley by
 * Van Jacobson of Lawrence Berkeley Laboratory.
 *
 * 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 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.
 *
 *	@(#)scsireg.h	8.1 (Berkeley) 6/10/93
 */
/*
 * [NetBSD for NEC PC-98 series]
 *  Copyright (c) 1996, 1997, 1998
 *	NetBSD/pc98 porting staff. All rights reserved.
 *  Copyright (c) 1996, 1997, 1998
 *	Kouichi Matsuda. All rights reserved.
 */

/*
 * FUJITSU MB89352A SCSI Protocol Controller Hardware Description.
 */

/* Definitions, most of them has turned out to be unneccesary, but here they
 * are anyway.
 */

#define BDID		0x00	/* Bus Device ID (R/W) */
#define SCTL		0x01	/* SPC Control register (R/W) */
#define SCMD		0x02	/* Command Register (R/W) */
#define TMOD		0x03	/* Transmit Mode Register (synch models) */
#define INTS		0x04	/* Interrupt sense (R); Interrupt Reset (W) */
#define PSNS		0x05	/* Phase Sense (R); SPC Diagnostic Control (W) */
#define SSTS		0x06	/* SPC status (R/O) */
#define SERR		0x07	/* SPC error status (R/O) */
#define PCTL		0x08	/* Phase Control (R/W) */
#define MBC		0x09	/* Modified Byte Counter (R/O) */
#define DREG		0x0a	/* Data Register (R/W) */
#define TEMP		0x0b	/* Temporary Register (R/W) */
#define TCH		0x0c	/* Transfer Counter High (R/W) */
#define TCM		0x0d	/* Transfer Counter Middle (R/W) */
#define TCL		0x0e	/* Transfer Counter Low (R/W) */
#define EXBF		0x0f	/* External Buffer (synch models) */

/* What all the bits do */

/* SCSI_BDID */
/* SCSI selection/reselection ID (both target *and* initiator) */
#define SELID7		0x80
#define SELID6		0x40
#define SELID5		0x20
#define SELID4		0x10
#define SELID3		0x08
#define SELID2		0x04
#define SELID1		0x02
#define SELID0		0x01

/* SCSI_SCTL */
#define SCTL_DISABLE	0x80
#define SCTL_CTRLRST	0x40
#define SCTL_DIAG	0x20
#define SCTL_ABRT_ENAB	0x10
#define SCTL_PARITY_ENAB 0x08
#define SCTL_SEL_ENAB	0x04
#define SCTL_RESEL_ENAB	0x02
#define SCTL_INTR_ENAB	0x01

/* SCSI_SCMD */
#define SCMD_RST	0x10
#define SCMD_ICPT_XFR	0x08
#define SCMD_PROG_XFR	0x04
#define SCMD_PAD	0x01	/* if initiator */
#define SCMD_PERR_STOP	0x01	/* if target */
	/* command codes */
#define SCMD_BUS_REL	0x00
#define SCMD_SELECT	0x20
#define SCMD_RST_ATN	0x40
#define SCMD_SET_ATN	0x60
#define SCMD_XFR	0x80
#define SCMD_XFR_PAUSE	0xa0
#define SCMD_RST_ACK	0xc0
#define SCMD_SET_ACK	0xe0

/* SCSI_TMOD */
#define TMOD_SYNC	0x80

/* SCSI_INTS */
#define INTS_SEL	0x80
#define INTS_RESEL	0x40
#define INTS_DISCON	0x20
#define INTS_CMD_DONE	0x10
#define INTS_SRV_REQ	0x08
#define INTS_TIMEOUT	0x04
#define INTS_HARD_ERR	0x02
#define INTS_RST	0x01

/* SCSI_PSNS */
#define PSNS_REQ	0x80
#define PSNS_ACK	0x40
#define PSNS_ATN	0x20
#define PSNS_SEL	0x10
#define PSNS_BSY	0x08

/* PSNS */
#define REQI		0x80
#define ACKI		0x40
#define ATNI		0x20
#define SELI		0x10
#define BSYI		0x08
#define MSGI		0x04
#define CDI		0x02
#define IOI		0x01

/* Important! The 3 most significant bits of this register, in initiator mode,
 * represents the "expected" SCSI bus phase and can be used to trigger phase
 * mismatch and phase change interrupts.  But more important:  If there is a
 * phase mismatch the chip will not transfer any data!  This is actually a nice
 * feature as it gives us a bit more control over what is happening when we are
 * bursting data (in) through the FIFOs and the phase suddenly changes from
 * DATA IN to STATUS or MESSAGE IN.  The transfer will stop and wait for the
 * proper phase to be set in this register instead of dumping the bits into the
 * FIFOs.
 */
#if 0
#define REQO		0x80
#define ACKO		0x40
#define ATNO		0x20
#define SELO		0x10
#define BSYO		0x08
#endif
/* PCTL */
#define MSGO		0x04
#define CDO		0x02
#define IOO		0x01

/* Information transfer phases */
#define PH_DATAOUT	(0)
#define PH_DATAIN	(IOI)
#define PH_CMD		(CDI)
#define PH_STAT		(CDI | IOI)
#define PH_MSGOUT	(MSGI | CDI)
#define PH_MSGIN	(MSGI | CDI | IOI)

#define PH_MASK		(MSGI | CDI | IOI)

#define PH_INVALID	0xff

/* SCSI_SSTS */
#define SSTS_INITIATOR	0x80
#define SSTS_TARGET	0x40
#define SSTS_BUSY	0x20
#define SSTS_XFR	0x10
#define SSTS_ACTIVE	(SSTS_INITIATOR|SSTS_XFR)
#define SSTS_RST	0x08
#define SSTS_TCZERO	0x04
#define SSTS_DREG_FULL	0x02
#define SSTS_DREG_EMPTY	0x01

/* SCSI_SERR */
#define SERR_SCSI_PAR	0x80
#define SERR_SPC_PAR	0x40
#define SERR_TC_PAR	0x08
#define SERR_PHASE_ERR	0x04
#define SERR_SHORT_XFR	0x02
#define SERR_OFFSET	0x01

/* SCSI_PCTL */
#define PCTL_BFINT_ENAB	0x80

license: unknown


code:
/*	$OpenBSD: mb89352var.h,v 1.5 2014/05/08 22:17:33 miod Exp $	*/
/*	$NetBSD: mb89352var.h,v 1.6 2003/08/02 12:48:09 tsutsui Exp $	*/
/*	NecBSD: mb89352var.h,v 1.4 1998/03/14 07:31:22 kmatsuda Exp 	*/

/*-
 * Copyright (c) 1996,97,98,99 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Charles M. Hannum, Masaru Oki and Kouichi Matsuda.
 *
 * 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 Charles M. Hannum.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * Copyright (c) 1994 Jarle Greipsland
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
/*
 * [NetBSD for NEC PC-98 series]
 *  Copyright (c) 1996, 1997, 1998
 *	NetBSD/pc98 porting staff. All rights reserved.
 *  Copyright (c) 1996, 1997, 1998
 *	Kouich Matsuda. All rights reserved.
 */

#ifndef	_MB89352VAR_H_
#define	_MB89352VAR_H_

/*
 * ACB. Holds additional information for each SCSI command Comments: We
 * need a separate scsi command block because we may need to overwrite it
 * with a request sense command.  Basicly, we refrain from fiddling with
 * the scsi_xfer struct (except do the expected updating of return values).
 * We'll generally update: xs->{flags,resid,error,sense,status} and
 * occasionally xs->retries.
 */
struct spc_acb {
	struct scsi_generic scsi_cmd;
	int scsi_cmd_length;
	u_char *data_addr;		/* Saved data pointer */
	int data_length;		/* Residue */

	u_char target_stat;		/* SCSI status byte */

#ifdef notdef
	struct spc_dma_seg dma[SPC_NSEG]; /* Physical addresses+len */
#endif

	TAILQ_ENTRY(spc_acb) chain;
	struct scsi_xfer *xs;	/* SCSI xfer ctrl block from above */
	int flags;
#define ACB_NEXUS	0x02
#define ACB_SENSE	0x04
#define ACB_ABORT	0x40
#define ACB_RESET	0x80
	int timeout;
};

/*
 * Some info about each (possible) target on the SCSI bus.  This should
 * probably have been a "per target+lunit" structure, but we'll leave it at
 * this for now.
 */
struct spc_tinfo {
	int	cmds;		/* #commands processed */
	int	dconns;		/* #disconnects */
	int	touts;		/* #timeouts */
	int	perrs;		/* #parity errors */
	int	senses;		/* #request sense commands sent */
	ushort	lubusy;		/* What local units/subr. are busy? */
	u_char  flags;
#define DO_SYNC		0x01	/* (Re)Negotiate synchronous options */
#define DO_WIDE		0x02	/* (Re)Negotiate wide options */
	u_char  period;		/* Period suggestion */
	u_char  offset;		/* Offset suggestion */
	u_char	width;		/* Width suggestion */
};

struct spc_softc {
	struct device sc_dev;

	bus_space_tag_t sc_iot;
	bus_space_handle_t sc_ioh;

	struct scsi_link sc_link;	/* prototype for subdevs */

	TAILQ_HEAD(, spc_acb) free_list, ready_list, nexus_list;
	struct spc_acb *sc_nexus;	/* current command */
	struct spc_acb sc_acb[8];
	struct spc_tinfo sc_tinfo[8];
	struct mutex sc_acb_mtx;
	struct scsi_iopool sc_iopool;

	/* Data about the current nexus (updated for every cmd switch) */
	u_char	*sc_dp;		/* Current data pointer */
	ssize_t	sc_dleft;	/* Data bytes left to transfer */
	u_char	*sc_cp;		/* Current command pointer */
	size_t	sc_cleft;	/* Command bytes left to transfer */

	/* Adapter state */
	u_char	 sc_phase;	/* Current bus phase */
	u_char	 sc_prevphase;	/* Previous bus phase */
	u_char	 sc_state;	/* State applicable to the adapter */
#define SPC_INIT	0
#define SPC_IDLE	1
#define SPC_SELECTING	2	/* SCSI command is arbiting  */
#define SPC_RESELECTED	3	/* Has been reselected */
#define SPC_CONNECTED	4	/* Actively using the SCSI bus */
#define SPC_DISCONNECT	5	/* MSG_DISCONNECT received */
#define SPC_CMDCOMPLETE	6	/* MSG_CMDCOMPLETE received */
#define SPC_CLEANING	7
	u_char	 sc_flags;
#define SPC_DROP_MSGIN	0x01	/* Discard all msgs (parity err detected) */
#define SPC_ABORTING	0x02	/* Bailing out */
#define SPC_DOINGDMA	0x04	/* doing DMA */
#define SPC_INACTIVE	0x80	/* The FIFO data path is active! */
	u_char	sc_selid;	/* Reselection ID */

	/* Message stuff */
	u_char	sc_msgpriq;	/* Messages we want to send */
	u_char	sc_msgoutq;	/* Messages sent during last MESSAGE OUT */
	u_char	sc_lastmsg;	/* Message last transmitted */
	u_char	sc_currmsg;	/* Message currently ready to transmit */
#define SEND_DEV_RESET		0x01
#define SEND_PARITY_ERROR	0x02
#define SEND_INIT_DET_ERR	0x04
#define SEND_REJECT		0x08
#define SEND_IDENTIFY		0x10
#define SEND_ABORT		0x20
#define SEND_SDTR		0x40
#define SEND_WDTR		0x80
#define SPC_MAX_MSG_LEN 8
	u_char  sc_omess[SPC_MAX_MSG_LEN];
	u_char	*sc_omp;		/* Outgoing message pointer */
	u_char	sc_imess[SPC_MAX_MSG_LEN];
	u_char	*sc_imp;		/* Incoming message pointer */

	/* Hardware stuff */
	int	sc_initiator;		/* Our scsi id */
	int	sc_freq;		/* Clock frequency in MHz */
	int	sc_minsync;		/* Minimum sync period / 4 */
	int	sc_maxsync;		/* Maximum sync period / 4 */

	/* DMA function set from MD code */
	void (*sc_dma_start)(struct spc_softc *, void *, size_t, int);
	void (*sc_dma_done)(struct spc_softc *);
};

#if SPC_DEBUG
#define SPC_SHOWACBS	0x01
#define SPC_SHOWINTS	0x02
#define SPC_SHOWCMDS	0x04
#define SPC_SHOWMISC	0x08
#define SPC_SHOWTRACE	0x10
#define SPC_SHOWSTART	0x20
#define SPC_DOBREAK	0x40
extern int spc_debug; /* SPC_SHOWSTART|SPC_SHOWMISC|SPC_SHOWTRACE; */
#define SPC_PRINT(b, s)	do {if ((spc_debug & (b)) != 0) printf s;} while (0)
#define SPC_BREAK()	do {if ((spc_debug & SPC_DOBREAK) != 0) Debugger();} while (0)
#define SPC_ASSERT(x)	do {if (x) {} else {printf("%s at line %d: assertion failed\n", sc->sc_dev.dv_xname, __LINE__); Debugger();}} while (0)
#else
#define SPC_PRINT(b, s)
#define SPC_BREAK()
#define SPC_ASSERT(x)
#endif

#define SPC_ACBS(s)	SPC_PRINT(SPC_SHOWACBS, s)
#define SPC_INTS(s)	SPC_PRINT(SPC_SHOWINTS, s)
#define SPC_CMDS(s)	SPC_PRINT(SPC_SHOWCMDS, s)
#define SPC_MISC(s)	SPC_PRINT(SPC_SHOWMISC, s)
#define SPC_TRACE(s)	SPC_PRINT(SPC_SHOWTRACE, s)
#define SPC_START(s)	SPC_PRINT(SPC_SHOWSTART, s)

void	spc_attach(struct spc_softc *, struct scsi_adapter *);
int	spc_intr(void *);
int	spc_find(bus_space_tag_t, bus_space_handle_t, int);
void	spc_init(struct spc_softc *);
void	spc_sched(struct spc_softc *);
void	spc_scsi_cmd(struct scsi_xfer *);
void	spc_minphys(struct buf *);
#endif	/* _MB89352VAR_H_ */


code:
/*	$OpenBSD: omkbdmap.c,v 1.2 2013/11/16 18:31:44 miod Exp $	*/

/* Partially from:
 *	$NetBSD: lunaws.c,v 1.6 2002/03/17 19:40:42 atatat Exp $
 *
 * Copyright (c) 2000 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Tohru Nishimura.
 *
 * 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/types.h>

#include <dev/wscons/wsksymdef.h>
#include <dev/wscons/wsksymvar.h>

#include <luna88k/dev/omkbdmap.h>

#ifdef WSDISPLAY_COMPAT_RAWKBD
#include <dev/wscons/wskbdraw.h>

/*
 * Translate LUNA keycodes to US keyboard XT scancodes, for proper
 * X11-over-wsmux operation.
 */
const u_int8_t omkbd_raw[0x80] = {
	RAWKEY_Null,		/* 0x00 */
	RAWKEY_Null,		/* 0x01 */
	RAWKEY_Null,		/* 0x02 */
	RAWKEY_Null,		/* 0x03 */
	RAWKEY_Null,		/* 0x04 */
	RAWKEY_Null,		/* 0x05 */
	RAWKEY_Null,		/* 0x06 */
	RAWKEY_Null,		/* 0x07 */
	RAWKEY_Null,		/* 0x08 */
	RAWKEY_Tab,		/* 0x09 */
	RAWKEY_Control_L,	/* 0x0a */
	0x70,			/* 0x0b: Kana / No RAWKEY_XXX symbol */
	RAWKEY_Shift_R,		/* 0x0c */
	RAWKEY_Shift_L,		/* 0x0d */
	RAWKEY_Caps_Lock,	/* 0x0e */
	RAWKEY_Alt_L,		/* 0x0f: Zenmen */
	RAWKEY_Escape,		/* 0x10 */
	RAWKEY_BackSpace,	/* 0x11 */
	RAWKEY_Return,		/* 0x12 */
	RAWKEY_Null,		/* 0x13 */
	RAWKEY_space,		/* 0x14 */
	RAWKEY_Delete,		/* 0x15 */
	RAWKEY_Alt_L,		/* 0x16: Henkan */
	RAWKEY_Alt_R,		/* 0x17: Kakutei */
	RAWKEY_f11,		/* 0x18: Shokyo */
	RAWKEY_f12,		/* 0x19: Yobidashi */
	RAWKEY_Null,		/* 0x1a: Bunsetsu L / f13 */
	RAWKEY_Null,		/* 0x1b: Bunsetsu R / f14 */
	RAWKEY_KP_Up,		/* 0x1c */
	RAWKEY_KP_Left,		/* 0x1d */
	RAWKEY_KP_Right,	/* 0x1e */
	RAWKEY_KP_Down,		/* 0x1f */
	RAWKEY_f11,		/* 0x20 */
	RAWKEY_f12,		/* 0x21 */
	RAWKEY_1,		/* 0x22: exclam */
	RAWKEY_2,		/* 0x23: quotedbl */
	RAWKEY_3,		/* 0x24: numbersign */
	RAWKEY_4,		/* 0x25: dollar */
	RAWKEY_5,		/* 0x26: percent */
	RAWKEY_6,		/* 0x27: ampersand */
	RAWKEY_7,		/* 0x28: apostrophe */
	RAWKEY_8,		/* 0x29: parenleft */
	RAWKEY_9,		/* 0x2a: parenright  */
	RAWKEY_0,		/* 0x2b */
	RAWKEY_minus,		/* 0x2c: equal */
	RAWKEY_equal,		/* 0x2d: asciitilde */
	0x7d,			/* 0x2e: bar / No RAWKEY_XXX symbol */
	RAWKEY_Null, 		/* 0x2f */
	RAWKEY_Null, 		/* 0x30: f13 */
	RAWKEY_Null, 		/* 0x31: f14 */
	RAWKEY_q,		/* 0x32 */
	RAWKEY_w,		/* 0x33 */
	RAWKEY_e,		/* 0x34 */
	RAWKEY_r,		/* 0x35 */
	RAWKEY_t,		/* 0x36 */
	RAWKEY_y,		/* 0x37 */
	RAWKEY_u,		/* 0x38 */
	RAWKEY_i,		/* 0x39 */
	RAWKEY_o,		/* 0x3a */
	RAWKEY_p,		/* 0x3b */
	RAWKEY_bracketleft,	/* 0x3c: grave */
	RAWKEY_bracketright,	/* 0x3d: braceleft */
	RAWKEY_Null,		/* 0x3e */
	RAWKEY_Null,		/* 0x3f */
	RAWKEY_Null,		/* 0x40 */
	RAWKEY_Null,		/* 0x41 */
	RAWKEY_a,		/* 0x42 */
	RAWKEY_s,		/* 0x43 */
	RAWKEY_d,		/* 0x44 */
	RAWKEY_f,		/* 0x45 */
	RAWKEY_g,		/* 0x46 */
	RAWKEY_h,		/* 0x47 */
	RAWKEY_j,		/* 0x48 */
	RAWKEY_k,		/* 0x49 */
	RAWKEY_l,		/* 0x4a */
	RAWKEY_semicolon,	/* 0x4b: plus */
	RAWKEY_apostrophe,	/* 0x4c: asterisk */
	RAWKEY_backslash,	/* 0x4d: braceright */
	RAWKEY_Null,		/* 0x4e */
	RAWKEY_Null,		/* 0x4f */
	RAWKEY_Null,		/* 0x50 */
	RAWKEY_Null,		/* 0x51 */
	RAWKEY_z,		/* 0x52 */
	RAWKEY_x,		/* 0x53 */
	RAWKEY_c,		/* 0x54 */
	RAWKEY_v,		/* 0x55 */
	RAWKEY_b,		/* 0x56 */
	RAWKEY_n,		/* 0x57 */
	RAWKEY_m,		/* 0x58 */
	RAWKEY_comma,		/* 0x59: less */
	RAWKEY_period,		/* 0x5a: greater */
	RAWKEY_slash,		/* 0x5b: question */
	RAWKEY_Meta_L,		/* 0x5c: underscore */
	RAWKEY_Null,		/* 0x5d */
	RAWKEY_Null,		/* 0x5e */
	RAWKEY_Null,		/* 0x5f */
	RAWKEY_KP_Delete,	/* 0x60 */
	RAWKEY_KP_Add,		/* 0x61 */
	RAWKEY_KP_Subtract,	/* 0x62 */
	RAWKEY_KP_Home,		/* 0x63: KP 7 */
	RAWKEY_KP_Up,		/* 0x64: KP 8 */
	RAWKEY_KP_Prior,	/* 0x65: KP 9 */
	RAWKEY_KP_Left,		/* 0x66: KP 4 */
	RAWKEY_KP_Begin,	/* 0x67: KP 5 */
	RAWKEY_KP_Right,	/* 0x68: KP 6 */
	RAWKEY_KP_End,		/* 0x69: KP 1 */
	RAWKEY_KP_Down,		/* 0x6a: KP 2 */
	RAWKEY_KP_Next,		/* 0x6b: KP 3 */
	RAWKEY_KP_Insert,	/* 0x6c: KP 0 */
	RAWKEY_KP_Delete,	/* 0x6d: KP Decimal */
	RAWKEY_KP_Enter,	/* 0x6e */
	RAWKEY_Null,		/* 0x6f */
	RAWKEY_Null,		/* 0x70 */
	RAWKEY_Null,		/* 0x71 */
	RAWKEY_f1,		/* 0x72 */
	RAWKEY_f2,		/* 0x73 */
	RAWKEY_f3,		/* 0x74 */
	RAWKEY_f4,		/* 0x75 */
	RAWKEY_f5,		/* 0x76 */
	RAWKEY_f6,		/* 0x77 */
	RAWKEY_f7,		/* 0x78 */
	RAWKEY_f8,		/* 0x79 */
	RAWKEY_f9,		/* 0x7a */
	RAWKEY_f10,		/* 0x7b */
	RAWKEY_KP_Multiply,	/* 0x7c */
	RAWKEY_KP_Divide,	/* 0x7d */
	RAWKEY_KP_Equal,	/* 0x7E */
	RAWKEY_Null,		/* 0x7f: KP Separator */
};
#endif

#define KC(n) KS_KEYCODE(n)

static const keysym_t omkbd_keydesc_jp[] = {
/*	pos		command		normal		shifted */
	KC(0x09),			KS_Tab,
	KC(0x0a),   KS_Cmd1,		KS_Control_L,
	KC(0x0b),			KS_Mode_switch,	/* Kana */
	KC(0x0c),			KS_Shift_R,
	KC(0x0d),			KS_Shift_L,
	KC(0x0e),			KS_Caps_Lock,
	KC(0x0f),   KS_Cmd2,		KS_Meta_L,	/* Zenmen */
	KC(0x10),   KS_Cmd_Debugger,	KS_Escape,
	KC(0x11),			KS_BackSpace,
	KC(0x12),			KS_Return,
	KC(0x14),			KS_space,
	KC(0x15),			KS_Delete,
	KC(0x16),			KS_Alt_L,	/* Henkan */
	KC(0x17),			KS_Alt_R,	/* Kakutei */
	KC(0x18),			KS_f11,		/* Shokyo */
	KC(0x19),			KS_f12,		/* Yobidashi */
	KC(0x1a),			KS_f13,		/* Bunsetsu L */
	KC(0x1b),			KS_f14,		/* Bunsetsu R */
	KC(0x1c),			KS_KP_Up,
	KC(0x1d),			KS_KP_Left,
	KC(0x1e),			KS_KP_Right,
	KC(0x1f),			KS_KP_Down,
	/* 0x20, 			KS_f11, */
	/* 0x21,			KS_f12, */
	KC(0x22),			KS_1,		KS_exclam,
	KC(0x23),			KS_2,		KS_quotedbl,
	KC(0x24),			KS_3,		KS_numbersign,
	KC(0x25),			KS_4,		KS_dollar,
	KC(0x26),			KS_5,		KS_percent,
	KC(0x27),			KS_6,		KS_ampersand,
	KC(0x28),			KS_7,		KS_apostrophe,
	KC(0x29),			KS_8,		KS_parenleft,
	KC(0x2a),			KS_9,		KS_parenright,
	KC(0x2b),			KS_0,
	KC(0x2c),			KS_minus,	KS_equal,
	KC(0x2d),			KS_asciicircum,	KS_asciitilde,
	KC(0x2e),			KS_backslash,	KS_bar,

	/* 0x30,			KS_f13, */
	/* 0x31,			KS_f14, */
	KC(0x32),			KS_q,
	KC(0x33),			KS_w,
	KC(0x34),			KS_e,
	KC(0x35),			KS_r,
	KC(0x36),			KS_t,
	KC(0x37),			KS_y,
	KC(0x38),			KS_u,
	KC(0x39),			KS_i,
	KC(0x3a),			KS_o,
	KC(0x3b),			KS_p,
	KC(0x3c),			KS_at,		KS_grave,
	KC(0x3d),			KS_bracketleft,	KS_braceleft,

	KC(0x42),			KS_a,
	KC(0x43),			KS_s,
	KC(0x44),			KS_d,
	KC(0x45),			KS_f,
	KC(0x46),			KS_g,
	KC(0x47),			KS_h,
	KC(0x48),			KS_j,
	KC(0x49),			KS_k,
	KC(0x4a),			KS_l,
	KC(0x4b),			KS_semicolon,	KS_plus,
	KC(0x4c),			KS_colon,	KS_asterisk,
	KC(0x4d),			KS_bracketright, KS_braceright,

	KC(0x52),			KS_z,
	KC(0x53),			KS_x,
	KC(0x54),			KS_c,
	KC(0x55),			KS_v,
	KC(0x56),			KS_b,
	KC(0x57),			KS_n,
	KC(0x58),			KS_m,
	KC(0x59),			KS_comma,	KS_less,
	KC(0x5a),			KS_period,	KS_greater,
	KC(0x5b),			KS_slash,	KS_question,
	KC(0x5c),			KS_underscore,

	KC(0x60),			KS_KP_Delete,
	KC(0x61),			KS_KP_Add,
	KC(0x62),			KS_KP_Subtract,
	KC(0x63),			KS_KP_7,
	KC(0x64),			KS_KP_8,
	KC(0x65),			KS_KP_9,
	KC(0x66),			KS_KP_4,
	KC(0x67),			KS_KP_5,
	KC(0x68),			KS_KP_6,
	KC(0x69),			KS_KP_1,
	KC(0x6a),			KS_KP_2,
	KC(0x6b),			KS_KP_3,
	KC(0x6c),			KS_KP_0,
	KC(0x6d),			KS_KP_Decimal,
	KC(0x6e),			KS_KP_Enter,

	KC(0x72),			KS_f1,
	KC(0x73),			KS_f2,
	KC(0x74),			KS_f3,
	KC(0x75),			KS_f4,
	KC(0x76),			KS_f5,
	KC(0x77),			KS_f6,
	KC(0x78),			KS_f7,
	KC(0x79),			KS_f8,
	KC(0x7a),			KS_f9,
	KC(0x7b),			KS_f10,
	KC(0x7c),			KS_KP_Multiply,
	KC(0x7d),			KS_KP_Divide,
	KC(0x7e),			KS_KP_Equal,
	KC(0x7f),			KS_KP_Separator,
};

#define	SIZE(map) (sizeof(map)/sizeof(keysym_t))

const struct wscons_keydesc omkbd_keydesctab[] = {
       { KB_JP, 0, SIZE(omkbd_keydesc_jp), omkbd_keydesc_jp, },
       { 0, 0, 0, 0 },
};


code:
/*	$OpenBSD: omkbdmap.h,v 1.1 2013/05/22 11:35:02 aoyama Exp $	*/

/*
 * Copyright (c) 2013 Kenji Aoyama
 *
 * 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.
 */

extern const struct wscons_keydesc omkbd_keydesctab[];
#ifdef WSDISPLAY_COMPAT_RAWKBD
extern const u_int8_t omkbd_raw[0x80];
#endif


code:
/* $OpenBSD: omrasops.c,v 1.13 2014/10/01 10:06:27 aoyama Exp $ */
/* $NetBSD: omrasops.c,v 1.1 2000/01/05 08:48:56 nisimura Exp $ */

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

/*
 * Designed specifically for 'm68k bitorder';
 *	- most significant byte is stored at lower address,
 *	- most significant bit is displayed at left most on screen.
 * Implementation relies on;
 *	- every memory reference is done in aligned 32bit chunks,
 *	- font glyphs are stored in 32bit padded.
 */

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

#include <dev/wscons/wsconsio.h>
#include <dev/wscons/wsdisplayvar.h>
#include <dev/rasops/rasops.h>

#include <luna88k/dev/omrasops.h>

/* wscons emulator operations */
int	om_copycols(void *, int, int, int, int);
int	om_copyrows(void *, int, int, int num);
int	om_erasecols(void *, int, int, int, long);
int	om_eraserows(void *, int, int, long);
int	om1_cursor(void *, int, int, int);
int	om1_putchar(void *, int, int, u_int, long);
int	om4_cursor(void *, int, int, int);
int	om4_putchar(void *, int, int, u_int, long);

/* depth-depended setup functions */
void	setup_omrasops1(struct rasops_info *);
void	setup_omrasops4(struct rasops_info *);

/* internal functions for 1bpp/4bpp */
int	om1_windowmove(struct rasops_info *, u_int16_t, u_int16_t, u_int16_t,
		u_int16_t, u_int16_t, u_int16_t, int16_t, int16_t);
int	om4_windowmove(struct rasops_info *, u_int16_t, u_int16_t, u_int16_t,
		u_int16_t, u_int16_t, u_int16_t, int16_t, int16_t);

/* MI function in src/sys/dev/rasops/rasops.c */
int     rasops_alloc_cattr(void *, int, int, int, long *);

static int (*om_windowmove)(struct rasops_info *, u_int16_t, u_int16_t,
		u_int16_t, u_int16_t, u_int16_t, u_int16_t, int16_t, int16_t);

extern struct wsscreen_descr omfb_stdscreen;

#define	ALL1BITS	(~0U)
#define	ALL0BITS	(0U)
#define	BLITWIDTH	(32)
#define	ALIGNMASK	(0x1f)
#define	BYTESDONE	(4)

/*
 * Blit a character at the specified co-ordinates.
 * - 1bpp version -
 */
int
om1_putchar(void *cookie, int row, int startcol, u_int uc, long attr)
{
	struct rasops_info *ri = cookie;
	u_int8_t *p;
	int scanspan, startx, height, width, align, y;
	u_int32_t lmask, rmask, glyph, inverse;
	int i, fg, bg;
	u_int8_t *fb;

	scanspan = ri->ri_stride;
	y = ri->ri_font->fontheight * row;
	startx = ri->ri_font->fontwidth * startcol;
	height = ri->ri_font->fontheight;
	fb = (u_int8_t *)ri->ri_font->data +
	    (uc - ri->ri_font->firstchar) * ri->ri_fontscale;
	ri->ri_ops.unpack_attr(cookie, attr, &fg, &bg, NULL);
	inverse = (bg != 0) ? ALL1BITS : ALL0BITS;

	p = (u_int8_t *)ri->ri_bits + y * scanspan + ((startx / 32) * 4);
	align = startx & ALIGNMASK;
	width = ri->ri_font->fontwidth + align;
	lmask = ALL1BITS >> align;
	rmask = ALL1BITS << (-width & ALIGNMASK);
	if (width <= BLITWIDTH) {
		lmask &= rmask;
		while (height > 0) {
			glyph = 0;
			for (i = ri->ri_font->stride; i != 0; i--)
				glyph = (glyph << 8) | *fb++;
			glyph <<= (4 - ri->ri_font->stride) * NBBY;
			glyph = (glyph >> align) ^ inverse;
			*W(p) = (*R(p) & ~lmask) | (glyph & lmask);
			p += scanspan;
			height--;
		}
	} else {
		u_int8_t *q = p;
		u_int32_t lhalf, rhalf;

		while (height > 0) {
			glyph = 0;
			for (i = ri->ri_font->stride; i != 0; i--)
				glyph = (glyph << 8) | *fb++;
			glyph <<= (4 - ri->ri_font->stride) * NBBY;
			lhalf = (glyph >> align) ^ inverse;
			*W(p) = (*R(p) & ~lmask) | (lhalf & lmask);

			p += BYTESDONE;

			rhalf = (glyph << (BLITWIDTH - align)) ^ inverse;
			*W(p) = (rhalf & rmask) | (*R(p) & ~rmask);

			p = (q += scanspan);
			height--;
		}
	}

	return 0;
}

/*
 * Blit a character at the specified co-ordinates
 * - 4bpp version -
 */
int
om4_putchar(void *cookie, int row, int startcol, u_int uc, long attr)
{
	struct rasops_info *ri = cookie;
	u_int8_t *p;
	int scanspan, startx, height, width, align, y;
	u_int32_t lmask, rmask, glyph, glyphbg, fgpat, bgpat;
	u_int32_t fgmask0, fgmask1, fgmask2, fgmask3;
	u_int32_t bgmask0, bgmask1, bgmask2, bgmask3;
	int i, fg, bg;
	u_int8_t *fb;

	scanspan = ri->ri_stride;
	y = ri->ri_font->fontheight * row;
	startx = ri->ri_font->fontwidth * startcol;
	height = ri->ri_font->fontheight;
	fb = (u_int8_t *)ri->ri_font->data +
	    (uc - ri->ri_font->firstchar) * ri->ri_fontscale;
	ri->ri_ops.unpack_attr(cookie, attr, &fg, &bg, NULL);
	fgmask0 = (fg & 0x01) ? ALL1BITS : ALL0BITS;
	fgmask1 = (fg & 0x02) ? ALL1BITS : ALL0BITS;
	fgmask2 = (fg & 0x04) ? ALL1BITS : ALL0BITS;
	fgmask3 = (fg & 0x08) ? ALL1BITS : ALL0BITS;
	bgmask0 = (bg & 0x01) ? ALL1BITS : ALL0BITS;
	bgmask1 = (bg & 0x02) ? ALL1BITS : ALL0BITS;
	bgmask2 = (bg & 0x04) ? ALL1BITS : ALL0BITS;
	bgmask3 = (bg & 0x08) ? ALL1BITS : ALL0BITS;

	p = (u_int8_t *)ri->ri_bits + y * scanspan + ((startx / 32) * 4);
	align = startx & ALIGNMASK;
	width = ri->ri_font->fontwidth + align;
	lmask = ALL1BITS >> align;
	rmask = ALL1BITS << (-width & ALIGNMASK);

	/* select all planes for later ROP function target */
	*(volatile u_int32_t *)OMFB_PLANEMASK = 0xff;

	if (width <= BLITWIDTH) {
		lmask &= rmask;
		/* set lmask as ROP mask value, with THROUGH mode */
		((volatile u_int32_t *)OMFB_ROPFUNC)[ROP_THROUGH] = lmask;

		while (height > 0) {
			glyph = 0;
			for (i = ri->ri_font->stride; i != 0; i--)
				glyph = (glyph << 8) | *fb++;
			glyph <<= (4 - ri->ri_font->stride) * NBBY;
			glyph = (glyph >> align);
			glyphbg = glyph ^ ALL1BITS;

			fgpat = glyph & fgmask0;
			bgpat = glyphbg & bgmask0;
			*P0(p) = (fgpat | bgpat);
			fgpat = glyph & fgmask1;
			bgpat = glyphbg & bgmask1;
			*P1(p) = (fgpat | bgpat);
			fgpat = glyph & fgmask2;
			bgpat = glyphbg & bgmask2;
			*P2(p) = (fgpat | bgpat);
			fgpat = glyph & fgmask3;
			bgpat = glyphbg & bgmask3;
			*P3(p) = (fgpat | bgpat);

			p += scanspan;
			height--;
		}
		/* reset mask value */
		((volatile u_int32_t *)OMFB_ROPFUNC)[ROP_THROUGH] = ALL1BITS;
	} else {
		u_int8_t *q = p;
		u_int32_t lhalf, rhalf;
		u_int32_t lhalfbg, rhalfbg;

		while (height > 0) {
			glyph = 0;
			for (i = ri->ri_font->stride; i != 0; i--)
				glyph = (glyph << 8) | *fb++;
			glyph <<= (4 - ri->ri_font->stride) * NBBY;
			lhalf = (glyph >> align);
			lhalfbg = lhalf ^ ALL1BITS;
			/* set lmask as ROP mask value, with THROUGH mode */
			((volatile u_int32_t *)OMFB_ROPFUNC)[ROP_THROUGH]
				= lmask;

			fgpat = lhalf & fgmask0;
			bgpat = lhalfbg & bgmask0;
			*P0(p) = (fgpat | bgpat);
			fgpat = lhalf & fgmask1;
			bgpat = lhalfbg & bgmask1;
			*P1(p) = (fgpat | bgpat);
			fgpat = lhalf & fgmask2;
			bgpat = lhalfbg & bgmask2;
			*P2(p) = (fgpat | bgpat);
			fgpat = lhalf & fgmask3;
			bgpat = lhalfbg & bgmask3;
			*P3(p) = (fgpat | bgpat);

			p += BYTESDONE;

			rhalf = (glyph << (BLITWIDTH - align));
			rhalfbg = rhalf ^ ALL1BITS;
			/* set rmask as ROP mask value, with THROUGH mode */
			((volatile u_int32_t *)OMFB_ROPFUNC)[ROP_THROUGH]
				= rmask;

			fgpat = rhalf & fgmask0;
			bgpat = rhalfbg & bgmask0;
			*P0(p) = (fgpat | bgpat);
			fgpat = rhalf & fgmask1;
			bgpat = rhalfbg & bgmask1;
			*P1(p) = (fgpat | bgpat);
			fgpat = rhalf & fgmask2;
			bgpat = rhalfbg & bgmask2;
			*P2(p) = (fgpat | bgpat);
			fgpat = rhalf & fgmask3;
			bgpat = rhalfbg & bgmask3;
			*P3(p) = (fgpat | bgpat);

			p = (q += scanspan);
			height--;
		}
		/* reset mask value */
		((volatile u_int32_t *)OMFB_ROPFUNC)[ROP_THROUGH] = ALL1BITS;
	}
	/* select plane #0 only; XXX need this ? */
	*(volatile u_int32_t *)OMFB_PLANEMASK = 0x01;

	return 0;
}

int
om_erasecols(void *cookie, int row, int col, int num, long attr)
{
	struct rasops_info *ri = cookie;
	int fg, bg;
	int snum, scol, srow;

	ri->ri_ops.unpack_attr(cookie, attr, &fg, &bg, NULL);

	snum = num * ri->ri_font->fontwidth;
	scol = col * ri->ri_font->fontwidth  + ri->ri_xorigin;
	srow = row * ri->ri_font->fontheight + ri->ri_yorigin;

	/*
	 * If this is too tricky for the simple raster ops engine,
	 * pass the fun to rasops.
	 */
	if ((*om_windowmove)(ri, scol, srow, scol, srow, snum,
	    ri->ri_font->fontheight, RR_CLEAR, 0xff ^ bg) != 0)
		rasops_erasecols(cookie, row, col, num, attr);

	return 0;
}

int
om_eraserows(void *cookie, int row, int num, long attr)
{
	struct rasops_info *ri = cookie;
	int fg, bg;
	int srow, snum;
	int rc;

	ri->ri_ops.unpack_attr(cookie, attr, &fg, &bg, NULL);
	bg ^= 0xff;

	if (num == ri->ri_rows && (ri->ri_flg & RI_FULLCLEAR)) {
		rc = (*om_windowmove)(ri, 0, 0, 0, 0, ri->ri_width,
			ri->ri_height, RR_CLEAR, bg);
	} else {
		srow = row * ri->ri_font->fontheight + ri->ri_yorigin;
		snum = num * ri->ri_font->fontheight;
		rc = (*om_windowmove)(ri, ri->ri_xorigin, srow, ri->ri_xorigin,
		    srow, ri->ri_emuwidth, snum, RR_CLEAR, bg);
	}
	if (rc != 0)
		rasops_eraserows(cookie, row, num, attr);

	return 0;
}

int
om_copyrows(void *cookie, int src, int dst, int n)
{
	struct rasops_info *ri = cookie;

	n   *= ri->ri_font->fontheight;
	src *= ri->ri_font->fontheight;
	dst *= ri->ri_font->fontheight;

	(*om_windowmove)(ri, ri->ri_xorigin, ri->ri_yorigin + src,
		ri->ri_xorigin, ri->ri_yorigin + dst,
		ri->ri_emuwidth, n, RR_COPY, 0xff);

	return 0;
}

int
om_copycols(void *cookie, int row, int src, int dst, int n)
{
	struct rasops_info *ri = cookie;

	n   *= ri->ri_font->fontwidth;
	src *= ri->ri_font->fontwidth;
	dst *= ri->ri_font->fontwidth;
	row *= ri->ri_font->fontheight;

	(*om_windowmove)(ri, ri->ri_xorigin + src, ri->ri_yorigin + row,
		ri->ri_xorigin + dst, ri->ri_yorigin + row,
		n, ri->ri_font->fontheight, RR_COPY, 0xff);

	return 0;
}

/*
 * Position|{enable|disable} the cursor at the specified location.
 * - 1bpp version -
 */
int
om1_cursor(void *cookie, int on, int row, int col)
{
	struct rasops_info *ri = cookie;
	u_int8_t *p;
	int scanspan, startx, height, width, align, y;
	u_int32_t lmask, rmask, image;

	if (!on) {
		/* make sure it's on */
		if ((ri->ri_flg & RI_CURSOR) == 0)
			return 0;

		row = ri->ri_crow;
		col = ri->ri_ccol;
	} else {
		/* unpaint the old copy. */
		ri->ri_crow = row;
		ri->ri_ccol = col;
	}

	scanspan = ri->ri_stride;
	y = ri->ri_font->fontheight * row;
	startx = ri->ri_font->fontwidth * col;
	height = ri->ri_font->fontheight;

	p = (u_int8_t *)ri->ri_bits + y * scanspan + ((startx / 32) * 4);
	align = startx & ALIGNMASK;
	width = ri->ri_font->fontwidth + align;
	lmask = ALL1BITS >> align;
	rmask = ALL1BITS << (-width & ALIGNMASK);
	if (width <= BLITWIDTH) {
		lmask &= rmask;
		while (height > 0) {
			image = *R(p);
			*W(p) = (image & ~lmask) | ((image ^ ALL1BITS) & lmask);
			p += scanspan;
			height--;
		}
	} else {
		u_int8_t *q = p;

		while (height > 0) {
			image = *R(p);
			*W(p) = (image & ~lmask) | ((image ^ ALL1BITS) & lmask);
			p += BYTESDONE;

			image = *R(p);
			*W(p) = ((image ^ ALL1BITS) & rmask) | (image & ~rmask);
			p = (q += scanspan);
			height--;
		}
	}
	ri->ri_flg ^= RI_CURSOR;

	return 0;
}

/*
 * Position|{enable|disable} the cursor at the specified location
 * - 4bpp version -
 */
int
om4_cursor(void *cookie, int on, int row, int col)
{
	struct rasops_info *ri = cookie;
	u_int8_t *p;
	int scanspan, startx, height, width, align, y;
	u_int32_t lmask, rmask;

	if (!on) {
		/* make sure it's on */
		if ((ri->ri_flg & RI_CURSOR) == 0)
			return 0;

		row = ri->ri_crow;
		col = ri->ri_ccol;
	} else {
		/* unpaint the old copy. */
		ri->ri_crow = row;
		ri->ri_ccol = col;
	}

	scanspan = ri->ri_stride;
	y = ri->ri_font->fontheight * row;
	startx = ri->ri_font->fontwidth * col;
	height = ri->ri_font->fontheight;

	p = (u_int8_t *)ri->ri_bits + y * scanspan + ((startx / 32) * 4);
	align = startx & ALIGNMASK;
	width = ri->ri_font->fontwidth + align;
	lmask = ALL1BITS >> align;
	rmask = ALL1BITS << (-width & ALIGNMASK);

	/* select all planes for later ROP function target */
	*(volatile u_int32_t *)OMFB_PLANEMASK = 0xff;

	if (width <= BLITWIDTH) {
		lmask &= rmask;
		/* set lmask as ROP mask value, with INV2 mode */
		((volatile u_int32_t *)OMFB_ROPFUNC)[ROP_INV2] = lmask;

		while (height > 0) {
			*W(p) = ALL1BITS;
			p += scanspan;
			height--;
		}
		/* reset mask value */
		((volatile u_int32_t *)OMFB_ROPFUNC)[ROP_THROUGH] = ALL1BITS;
	} else {
		u_int8_t *q = p;

		while (height > 0) {
			/* set lmask as ROP mask value, with INV2 mode */
			((volatile u_int32_t *)OMFB_ROPFUNC)[ROP_INV2] = lmask;
			*W(p) = ALL1BITS;

			p += BYTESDONE;

			/* set rmask as ROP mask value, with INV2 mode */
			((volatile u_int32_t *)OMFB_ROPFUNC)[ROP_INV2] = rmask;
			*W(p) = ALL1BITS;

			p = (q += scanspan);
			height--;
		}
		/* reset mask value */
		((volatile u_int32_t *)OMFB_ROPFUNC)[ROP_THROUGH] = ALL1BITS;
	}
	/* select plane #0 only; XXX need this ? */
	*(volatile u_int32_t *)OMFB_PLANEMASK = 0x01;

	ri->ri_flg ^= RI_CURSOR;

	return 0;
}

/*
 * After calling rasops_init(), set up our depth-depend emulops,
 * block move function and capabilities.
 */
void
setup_omrasops1(struct rasops_info *ri)
{
	om_windowmove = om1_windowmove;
	ri->ri_ops.cursor  = om1_cursor;
	ri->ri_ops.putchar = om1_putchar;
	omfb_stdscreen.capabilities
		= ri->ri_caps & ~WSSCREEN_UNDERLINE;
}

void
setup_omrasops4(struct rasops_info *ri)
{
	om_windowmove = om4_windowmove;
	ri->ri_ops.cursor  = om4_cursor;
	ri->ri_ops.putchar = om4_putchar;
	omfb_stdscreen.capabilities
		= WSSCREEN_HILIT | WSSCREEN_WSCOLORS | WSSCREEN_REVERSE;
	/*
	 * Since we set ri->ri_depth == 1, rasops_init() set
	 * rasops_alloc_mattr for us.  But we use the color version,
	 * rasops_alloc_cattr, on 4bpp/8bpp frame buffer.
	 */
	ri->ri_ops.alloc_attr = rasops_alloc_cattr;
}


code:
/*
 * Copyright (c) 2013 Kenji Aoyama
 *
 * 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.
 */

/*
 * Base addresses of LUNA's frame buffer
 * XXX: We consider only 1bpp and 4bpp for now
 */

#define OMFB_PLANEMASK	0xB1040000	/* BMSEL register */
#define OMFB_FB_WADDR   0xB1080008      /* common plane */
#define OMFB_FB_RADDR   0xB10C0008      /* plane #0 */
#define OMFB_ROPFUNC	0xB12C0000	/* common ROP function */

/*
 * Helper macros
 */
#define W(addr)  ((u_int32_t *)(addr))
#define R(addr)  ((u_int32_t *)((u_int8_t *)(addr) +  0x40000))
#define P0(addr) ((u_int32_t *)((u_int8_t *)(addr) +  0x40000))
#define P1(addr) ((u_int32_t *)((u_int8_t *)(addr) +  0x80000))
#define P2(addr) ((u_int32_t *)((u_int8_t *)(addr) +  0xC0000))
#define P3(addr) ((u_int32_t *)((u_int8_t *)(addr) + 0x100000))

/*
 * Replacement Rules (rops) (derived from hp300)
 */
#define RR_CLEAR        0x0
#define RR_COPY         0x3

/*
 * ROP function
 *
 * LUNA's frame buffer uses Hitach HM53462 video RAM, which has raster
 * (logic) operation, or ROP, function.  To use ROP function on LUNA, write
 * a 32bit `mask' value to the specified address corresponding to each ROP
 * logic.
 *
 * D: the data writing to the video RAM
 * M: the data already stored on the video RAM
 */

/* operation		index	the video RAM contents will be */
#define ROP_ZERO	 0	/* all 0	*/
#define ROP_AND1	 1	/* D & M	*/
#define ROP_AND2	 2	/* ~D & M	*/
/* Not used on LUNA	 3			*/
#define ROP_AND3	 4	/* D & ~M	*/
#define ROP_THROUGH	 5	/* D		*/
#define ROP_EOR		 6	/* (~D & M) | (D & ~M)	*/
#define ROP_OR1		 7	/* D | M	*/
#define ROP_NOR		 8	/* ~D | ~M	*/
#define ROP_ENOR	 9	/* (D & M) | (~D & ~M)	*/
#define ROP_INV1	10	/* ~D		*/
#define ROP_OR2		11	/* ~D | M	*/
#define ROP_INV2	12	/* ~M		*/
#define ROP_OR3		13	/* D | ~M	*/
#define ROP_NAND	14	/* ~D | ~M	*/
#define ROP_ONE		15	/* all 1	*/