code:
#	$OpenBSD: files.luna88k,v 1.27 2015/05/11 06:46:21 ratchov Exp $
#
maxpartitions 16

device 	mainbus {}
attach 	mainbus at root
file	arch/luna88k/luna88k/mainbus.c

device clock
attach clock at mainbus
file	arch/luna88k/dev/timekeeper.c			clock

device lcd
attach lcd at mainbus
file	arch/luna88k/dev/lcd.c				lcd needs-flag

attach le at mainbus: le24
file	arch/luna88k/dev/if_le.c			le

device sio {[channel = -1]}
attach sio at mainbus
file	arch/luna88k/dev/sio.c				sio

device siotty: tty
attach siotty at sio
file	arch/luna88k/dev/siotty.c			siotty needs-flag

device ws: wskbddev,wsmousedev
attach ws at sio
file arch/luna88k/dev/lunaws.c				ws
file arch/luna88k/dev/omkbdmap.c			ws

device fb: wsemuldisplaydev, rasops1
attach fb at mainbus
file arch/luna88k/dev/lunafb.c				fb
file arch/luna88k/dev/omrasops.c			fb
file arch/luna88k/dev/omrasops1.c			fb

# Raster operations
include "dev/rasops/files.rasops"
include "dev/wsfont/files.wsfont"
# "Workstation Console" glue.
include "dev/wscons/files.wscons"

device cpu
attach cpu at mainbus

include "scsi/files.scsi"

major {sd = 4}
major {st = 5}
major {cd = 6}
major {rd = 7}
major {vnd = 8}
major {wd = 9}

device spc: scsi
attach spc at mainbus
file arch/luna88k/dev/spc.c				spc
file arch/luna88k/dev/mb89352.c				spc

device cbus {}
attach	cbus at mainbus
file	arch/luna88k/cbus/cbus.c

device pcex
attach	pcex at cbus
file	arch/luna88k/cbus/pcex.c			pcex needs-flag

# NEC PC-9801-86 sound board
device	necsb: audio
attach	necsb at cbus
file	arch/luna88k/cbus/necsb.c			necsb needs-flag
file	arch/luna88k/cbus/nec86.c			necsb needs-flag
file	arch/luna88k/cbus/nec86hw.c			necsb needs-flag

# PCMCIA devices via NEC PC-9801-102 / PC-9821X[AE]-E01
device	pcic: pcmciabus
attach	pcic at cbus with pcic_cbus
file	dev/ic/i82365.c					pcic needs-flag
file	arch/luna88k/cbus/i82365_cbus.c			pcic needs-flag
include "dev/pcmcia/files.pcmcia"

# Media Independent Interface (mii), used with PCMCIA
include "dev/mii/files.mii"

# Machine-independent ATAPI drivers, used with PCMCIA
include "dev/atapiscsi/files.atapiscsi"
include "dev/ata/files.ata"

# list of standard files
file	arch/luna88k/luna88k/clock.c

file	arch/luna88k/luna88k/autoconf.c
file	arch/luna88k/luna88k/conf.c
file	arch/luna88k/luna88k/m8820x.c
file	arch/luna88k/luna88k/disksubr.c
file	arch/luna88k/luna88k/eh.S
file	arch/luna88k/luna88k/isr.c
file	arch/luna88k/luna88k/machdep.c
file	arch/luna88k/luna88k/pmap_table.c


code:
/*	$OpenBSD: ld.script,v 1.4 2013/11/03 09:42:55 miod Exp $	*/

/*
 * Copyright (c) 2012 Miodrag Vallat.
 *
 * 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.
 */

OUTPUT_FORMAT("elf32-m88k")
OUTPUT_ARCH(m88k)
ENTRY(__start)
SECTIONS
{
	.text :
	{
		*(.text)
		PROVIDE(etext = ABSOLUTE(.));
	}
	. = ALIGN(0x80000);
	.rodata :
	{
		*(.rodata*)
		PROVIDE(erodata = ABSOLUTE(.));
	}
	. = ALIGN(0x80000);
	.data :
	{
		*(.data)
		PROVIDE(edata = ABSOLUTE(.));
	}
	.bss :
	{
		*(.bss)
	}
	PROVIDE(end = ABSOLUTE(.));
	/DISCARD/ :
	{
		*(.comment)
	}
}

license: unknown


code:
/*	$OpenBSD: if_le.c,v 1.8 2014/12/22 02:26:53 tedu Exp $	*/
/*	$NetBSD: if_le.c,v 1.33 1996/11/20 18:56:52 gwr Exp $	*/

/*-
 * Copyright (c) 1996 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Adam Glass and Gordon W. Ross.
 *
 * 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 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.
 */

/* based on OpenBSD: sys/arch/sun3/dev/if_le.c */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/mbuf.h>
#include <sys/syslog.h>
#include <sys/socket.h>
#include <sys/device.h>

#include <net/if.h>

#include <netinet/in.h>
#include <netinet/if_ether.h>

#include <net/if_media.h>

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

#include <dev/ic/lancereg.h>
#include <dev/ic/lancevar.h>
#include <dev/ic/am7990reg.h>
#include <dev/ic/am7990var.h>

#include <luna88k/luna88k/isr.h>

/*
 * LANCE registers.
 * The real stuff is in dev/ic/am7990reg.h
 */
struct lereg1 {
	volatile uint16_t	ler1_rdp;	/* data port */
	volatile unsigned	:16 ;		/* LUNA-88K2 has a 16 bit gap */
	volatile uint16_t	ler1_rap;	/* register select port */
};

/*
 * Ethernet software status per interface.
 * The real stuff is in dev/ic/am7990var.h
 */
struct	le_softc {
	struct	am7990_softc sc_am7990;	/* glue to MI code */

	struct	lereg1 *sc_r1;		/* LANCE registers */
};

int	le_match(struct device *, void *, void *);
void	le_attach(struct device *, struct device *, void *);

const struct cfattach le_ca = {
	sizeof(struct le_softc), le_match, le_attach
};

void lewrcsr(struct lance_softc *, uint16_t, uint16_t);
uint16_t lerdcsr(struct lance_softc *, uint16_t);
void myetheraddr(uint8_t *);

void
lewrcsr(struct lance_softc *sc, uint16_t port, uint16_t val)
{
	register struct lereg1 *ler1 = ((struct le_softc *)sc)->sc_r1;

	ler1->ler1_rap = port;
	ler1->ler1_rdp = val;
}

uint16_t
lerdcsr(struct lance_softc *sc, uint16_t port)
{
	register struct lereg1 *ler1 = ((struct le_softc *)sc)->sc_r1;
	uint16_t val;

	ler1->ler1_rap = port;
	val = ler1->ler1_rdp;
	return (val);
}

int
le_match(struct device *parent, void *cf, void *aux)
{
	struct mainbus_attach_args *ma = aux;

	if (strcmp(ma->ma_name, le_cd.cd_name))
		return (0);

	return (1);
}

void
le_attach(struct device *parent, struct device *self, void *aux)
{
	struct le_softc *lesc = (struct le_softc *)self;
	struct lance_softc *sc = &lesc->sc_am7990.lsc;
        struct mainbus_attach_args *ma = aux;

        lesc->sc_r1 = (struct lereg1 *)ma->ma_addr;     /* LANCE */

        sc->sc_mem = (void *)0x71000000;                /* SRAM */
        sc->sc_conf3 = LE_C3_BSWP;
        sc->sc_addr = (u_long)sc->sc_mem & 0xffffff;
        sc->sc_memsize = 64 * 1024;                     /* 64KB */

        myetheraddr(sc->sc_arpcom.ac_enaddr);

	sc->sc_copytodesc = lance_copytobuf_contig;
	sc->sc_copyfromdesc = lance_copyfrombuf_contig;
	sc->sc_copytobuf = lance_copytobuf_contig;
	sc->sc_copyfrombuf = lance_copyfrombuf_contig;
	sc->sc_zerobuf = lance_zerobuf_contig;

	sc->sc_rdcsr = lerdcsr;
	sc->sc_wrcsr = lewrcsr;
	sc->sc_hwreset = NULL;
	sc->sc_hwinit = NULL;

	am7990_config(&lesc->sc_am7990);

        isrlink_autovec(am7990_intr, (void *)sc, ma->ma_ilvl, ISRPRI_NET,
	    self->dv_xname);
}

/*
 * Partially taken from NetBSD/luna68k
 *
 * LUNA-88K has FUSE ROM, which contains MAC address.  The FUSE ROM
 * contents are stored in fuse_rom_data[] during cpu_startup().
 *
 * LUNA-88K2 has 16Kbit NVSRAM on its ethercard, whose contents are
 * accessible 4bit-wise by ctl register operation.  The register is
 * mapped at 0xF1000008.
 */

extern int machtype;
extern char fuse_rom_data[];

void
myetheraddr(uint8_t *ether)
{
	unsigned i, loc;
	volatile struct { uint32_t ctl; } *ds1220;

	switch (machtype) {
	case LUNA_88K:
		/*
		 * fuse_rom_data[] begins with "ENADDR=00000Axxxxxx"
		 */
		loc = 7;
		for (i = 0; i < 6; i++) {
			int u, l;

			u = fuse_rom_data[loc];
			u = (u < 'A') ? u & 0xf : u - 'A' + 10;
			l = fuse_rom_data[loc + 1];
			l = (l < 'A') ? l & 0xf : l - 'A' + 10;

			ether[i] = l | (u << 4);
			loc += 2;
		}
		break;
	case LUNA_88K2:
		ds1220 = (void *)0xF1000008;
		loc = 12;
		for (i = 0; i < 6; i++) {
			unsigned u, l, hex;

			ds1220->ctl = (loc) << 16;
			u = 0xf0 & (ds1220->ctl >> 12);
			ds1220->ctl = (loc + 1) << 16;
			l = 0x0f & (ds1220->ctl >> 16);
			hex = (u < '9') ? l : l + 9;

			ds1220->ctl = (loc + 2) << 16;
			u = 0xf0 & (ds1220->ctl >> 12);
			ds1220->ctl = (loc + 3) << 16;
			l = 0x0f & (ds1220->ctl >> 16);

			ether[i] = ((u < '9') ? l : l + 9) | (hex << 4);
			loc += 4;
		}
		break;
	default:
		ether[0] = 0x00; ether[1] = 0x00; ether[2] = 0x0a;
		ether[3] = 0xDE; ether[4] = 0xAD; ether[5] = 0x00;
		break;
	}
}


code:
/* $OpenBSD: lcd.c,v 1.7 2015/02/10 22:42:35 miod Exp $ */
/* $NetBSD: lcd.c,v 1.2 2000/01/07 05:13:08 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.
 */

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

#include <machine/autoconf.h>
#include <machine/conf.h>
#include <machine/lcd.h>

#define PIO1_MODE_OUTPUT	0x84
#define PIO1_MODE_INPUT		0x94

#define POWER	0x10

#define ENABLE	0x80
#define DISABLE	0x00

#define WRITE_CMD	(0x00 | 0x00)
#define WRITE_DATA	(0x00 | 0x40)
#define READ_BUSY	(0x20 | 0x00)
#define READ_DATA	(0x20 | 0x40)

#define LCD_INIT	0x38
#define LCD_ENTRY	0x06
#define LCD_ON		0x0c
#define LCD_CLS		0x01
#define LCD_HOME	0x02
#define LCD_LOCATE(X, Y)	(((Y) & 1 ? 0xc0 : 0x80) | ((X) & 0x0f))

#define LCD_MAXBUFLEN	80

struct pio {
	volatile u_int8_t portA;
        volatile unsigned : 24;
	volatile u_int8_t portB;
        volatile unsigned : 24;
	volatile u_int8_t portC;
        volatile unsigned : 24;
	volatile u_int8_t cntrl;
        volatile unsigned : 24;
};

/* Autoconf stuff */
int  lcd_match(struct device *, void *, void *);
void lcd_attach(struct device *, struct device *, void *);

struct lcd_softc {
	struct device sc_dev;
	int sc_opened;
};

struct cfattach lcd_ca = {
	sizeof(struct lcd_softc), lcd_match, lcd_attach
};

struct cfdriver lcd_cd = {
	NULL, "lcd", DV_DULL, 0
};

/* Internal prototypes */
void lcdbusywait(void);
void lcdput(int);
void lcdctrl(int);
void lcdshow(const char *);
void greeting(void);

/* Internal variables */
				     /* "1234567890123456" */
static const char lcd_boot_message1[] = "OpenBSD/luna88k ";
static const char lcd_boot_message2[] = "   SX-9100/DT   ";

/*
 * Autoconf functions
 */
int
lcd_match(struct device *parent, void *cf, void *aux)
{
	struct mainbus_attach_args *ma = aux;

	if (strcmp(ma->ma_name, lcd_cd.cd_name))
		return 0;
	if (badaddr((vaddr_t)ma->ma_addr, 4))
		return 0;
	return 1;
}

void
lcd_attach(struct device *parent, struct device *self, void *aux)
{
	printf("\n");

	/* Say hello to the world on LCD. */
	greeting();
}

/*
 * open/close/write/ioctl
 */

int
lcdopen(dev_t dev, int flags, int fmt, struct proc *p)
{
	int unit = minor(dev);
	struct lcd_softc *sc;

	if (unit >= lcd_cd.cd_ndevs)
		return ENXIO;
	if ((sc = lcd_cd.cd_devs[unit]) == NULL)
		return ENXIO;
	if (sc->sc_opened)
		return EBUSY;
	sc->sc_opened = 1;

	return 0;
}

int
lcdclose(dev_t dev, int flags, int fmt, struct proc *p)
{
	int unit = minor(dev);
	struct lcd_softc *sc;

	sc = lcd_cd.cd_devs[unit];
	sc->sc_opened = 0;

	return 0;
}

int
lcdwrite(dev_t dev, struct uio *uio, int flag)
{
	int error;
	size_t len;
	size_t i, n;
	char buf[LCD_MAXBUFLEN];

	len = n = uio->uio_resid;

	if (len > LCD_MAXBUFLEN)
		return EIO;

	while (n > 0) {
		error = uiomove(buf, n, uio);
		if (error)
			return EIO;
		n = uio->uio_resid;
	}

	for (i = 0; i < len; i++) {
		lcdput((int)buf[i]);
	}

	return 0;
}

int
lcdioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
{
	int val;

	/* check if the device opened with write mode */
	switch(cmd) {
	case LCDCLS:
	case LCDHOME:
	case LCDMODE:
	case LCDDISP:
	case LCDMOVE:
	case LCDSEEK:
	case LCDRESTORE:
		if ((flag & FWRITE) == 0)
			return EACCES;
		break;
	}

	switch(cmd) {
	case LCDCLS:
		lcdctrl(LCD_CLS);
		break;

	case LCDHOME:
		lcdctrl(LCD_HOME);
		break;

	case LCDMODE:
		val = *(int *)addr;
		switch (val) {
		case LCDMODE_C_LEFT:
		case LCDMODE_C_RIGHT:
		case LCDMODE_D_LEFT:
		case LCDMODE_D_RIGHT:
			lcdctrl(val);
			break;
		default:
			return EINVAL;
		}
		break;

	case LCDDISP:
		val = *(int *)addr;
		if ((val & 0x7) != val)
			return EINVAL;
		lcdctrl(val | 0x8);
		break;

	case LCDMOVE:
		val = *(int *)addr;
		switch (val) {
		case LCDMOVE_C_LEFT:
		case LCDMOVE_C_RIGHT:
		case LCDMOVE_D_LEFT:
		case LCDMOVE_D_RIGHT:
			lcdctrl(val);
			break;
		default:
			return EINVAL;
		}
		break;

	case LCDSEEK:
		val = *(int *)addr & 0x7f;
		lcdctrl(val | 0x80);
		break;

	case LCDRESTORE:
		greeting();
		break;

	default:
		return ENOTTY;
	}
	return 0;
}

/*
 * Internal functions
 */
void
lcdbusywait()
{
	struct pio *p1 = (struct pio *)0x4D000000;
	int msb, s;

	s = splhigh();
	p1->cntrl = PIO1_MODE_INPUT;
	p1->portC = POWER | READ_BUSY | ENABLE;
	splx(s);

	do {
		msb = p1->portA & ENABLE;
		delay(5);
	} while (msb != 0);

	s = splhigh();
	p1->portC = POWER | READ_BUSY | DISABLE;
	splx(s);
}

void
lcdput(int cc)
{
	struct pio *p1 = (struct pio *)0x4D000000;
	int s;

	lcdbusywait();

	s = splhigh();
	p1->cntrl = PIO1_MODE_OUTPUT;

	p1->portC = POWER | WRITE_DATA | ENABLE;
	p1->portA = cc;
	p1->portC = POWER | WRITE_DATA | DISABLE;
	splx(s);
}

void
lcdctrl(int cc)
{
	struct pio *p1 = (struct pio *)0x4D000000;
	int s;

	lcdbusywait();

	s = splhigh();
	p1->cntrl = PIO1_MODE_OUTPUT;

	p1->portC = POWER | WRITE_CMD | ENABLE;
	p1->portA = cc;
	p1->portC = POWER | WRITE_CMD | DISABLE;
	splx(s);
}

void
lcdshow(const char *s)
{
	int cc;

	while ((cc = *s++) != '\0')
		lcdput(cc);
}

void
greeting()
{
	lcdctrl(LCD_INIT);
	lcdctrl(LCD_ENTRY);
	lcdctrl(LCD_ON);

	lcdctrl(LCD_CLS);
	lcdctrl(LCD_HOME);

	lcdctrl(LCD_LOCATE(0, 0));
	lcdshow(lcd_boot_message1);
	lcdctrl(LCD_LOCATE(0, 1));
	lcdshow(lcd_boot_message2);
}


code:
/* $OpenBSD: lunafb.c,v 1.22 2014/07/22 13:39:16 aoyama Exp $ */
/* $NetBSD: lunafb.c,v 1.7.6.1 2002/08/07 01:48:34 lukem 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/param.h>
#include <sys/systm.h>
#include <sys/conf.h>
#include <sys/device.h>
#include <sys/ioctl.h>
#include <sys/malloc.h>
#include <sys/mman.h>
#include <sys/proc.h>
#include <sys/tty.h>
#include <sys/errno.h>
#include <sys/buf.h>

#include <uvm/uvm_extern.h>

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

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

struct bt454 {
	volatile u_int8_t bt_addr;	/* map address register */
	volatile u_int8_t bt_cmap;	/* colormap data register */
};

struct bt458 {
	volatile u_int8_t bt_addr;	/* map address register */
		unsigned :24;
	volatile u_int8_t bt_cmap;	/* colormap data register */
		unsigned :24;
	volatile u_int8_t bt_ctrl;	/* control register */
		unsigned :24;
	volatile u_int8_t bt_omap;	/* overlay (cursor) map register */
		unsigned :24;
};

#define	OMFB_RFCNT	0xB1000000	/* video h-origin/v-origin */
#define	OMFB_PLANEMASK	0xB1040000	/* planemask register */
#define	OMFB_FB_WADDR	0xB1080008	/* common plane */
#define	OMFB_FB_RADDR	0xB10C0008	/* plane #0 */
#define OMFB_FB_PLANESIZE  0x40000	/* size of 1 plane, 2048 / 8 * 1024 */
#define	OMFB_ROPFUNC	0xB12C0000	/* ROP function code */
#define	OMFB_RAMDAC	0xC1100000	/* Bt454/Bt458 RAMDAC */
#define	OMFB_SIZE	(0xB1300000 - 0xB1080000 + PAGE_SIZE)

struct hwcmap {
#define CMAP_SIZE 256
	u_int8_t r[CMAP_SIZE];
	u_int8_t g[CMAP_SIZE];
	u_int8_t b[CMAP_SIZE];
};

struct om_hwdevconfig {
	int	dc_wid;			/* width of frame buffer */
	int	dc_ht;			/* height of frame buffer */
	int	dc_depth;		/* depth, bits per pixel */
	int	dc_rowbytes;		/* bytes in a FB scan line */
	int	dc_depth_checked;	/* depth is really checked or not */
	int	dc_cmsize;		/* colormap size */
	struct hwcmap dc_cmap;		/* software copy of colormap */
	vaddr_t	dc_videobase;		/* base of flat frame buffer */
	struct rasops_info dc_ri;	/* raster blitter variables */
};

struct omfb_softc {
	struct device sc_dev;		/* base device */
	struct om_hwdevconfig *sc_dc;	/* device configuration */
	int nscreens;
};

int  omgetcmap(struct omfb_softc *, struct wsdisplay_cmap *);
int  omsetcmap(struct omfb_softc *, struct wsdisplay_cmap *);

struct om_hwdevconfig omfb_console_dc;
void omfb_getdevconfig(paddr_t, struct om_hwdevconfig *);

/* in omrasops.c */
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);
void	setup_omrasops1(struct rasops_info *);
void	setup_omrasops4(struct rasops_info *);

struct wsscreen_descr omfb_stdscreen = {
	"std"
};

const struct wsscreen_descr *_omfb_scrlist[] = {
	&omfb_stdscreen,
};

const struct wsscreen_list omfb_screenlist = {
	sizeof(_omfb_scrlist) / sizeof(struct wsscreen_descr *), _omfb_scrlist
};

int	omfbioctl(void *, u_long, caddr_t, int, struct proc *);
paddr_t	omfbmmap(void *, off_t, int);
int	omfb_alloc_screen(void *, const struct wsscreen_descr *,
	    void **, int *, int *, long *);
void	omfb_free_screen(void *, void *);
int	omfb_show_screen(void *, void *, int, void (*) (void *, int, int),
	    void *);
int	omfb_load_font(void *, void *, struct wsdisplay_font *);
int	omfb_list_font(void *, struct wsdisplay_font *);
int	omfb_set_gfxmode(struct omfb_softc *, struct wsdisplay_gfx_mode *);

void	omfb_set_default_cmap(struct om_hwdevconfig *);
void	omfb_clear_framebuffer(struct om_hwdevconfig *);

const struct wsdisplay_accessops omfb_accessops = {
	.ioctl = omfbioctl,
	.mmap = omfbmmap,
	.alloc_screen = omfb_alloc_screen,
	.free_screen = omfb_free_screen,
	.show_screen = omfb_show_screen,
	.load_font = omfb_load_font,
	.list_font = omfb_list_font
};

int  omfbmatch(struct device *, void *, void *);
void omfbattach(struct device *, struct device *, void *);

const struct cfattach fb_ca = {
	sizeof(struct omfb_softc), omfbmatch, omfbattach
};

struct cfdriver fb_cd = {
        NULL, "fb", DV_DULL
};

/* hardware plane bits; retrieved at boot, will be updated */
extern int hwplanebits;

int omfb_console;
int omfb_cnattach(void);

int
omfbmatch(struct device *parent, void *cf, void *aux)
{
	struct mainbus_attach_args *ma = aux;

	if (strcmp(ma->ma_name, fb_cd.cd_name))
		return (0);
#if 0	/* XXX badaddr() bombs if no framebuffer is installed */
	if (badaddr((caddr_t)ma->ma_addr, 4))
		return (0);
#else
	if (hwplanebits == 0)
		return (0);
#endif
	return (1);
}

void
omfbattach(struct device *parent, struct device *self, void *args)
{
	struct omfb_softc *sc = (struct omfb_softc *)self;
	struct wsemuldisplaydev_attach_args waa;

	if (omfb_console) {
		sc->sc_dc = &omfb_console_dc;
		sc->nscreens = 1;
	} else {
		sc->sc_dc = (struct om_hwdevconfig *)
		    malloc(sizeof(struct om_hwdevconfig), M_DEVBUF,
			M_WAITOK | M_ZERO);
		omfb_getdevconfig(OMFB_FB_WADDR, sc->sc_dc);
	}
	printf(": %d x %d, %dbpp\n", sc->sc_dc->dc_wid, sc->sc_dc->dc_ht,
	    hwplanebits);

	waa.console = omfb_console;
	waa.scrdata = &omfb_screenlist;
	waa.accessops = &omfb_accessops;
	waa.accesscookie = sc;
	waa.defaultscreens = 0;

	config_found(self, &waa, wsemuldisplaydevprint);
}

/* EXPORT */ int
omfb_cnattach(void)
{
	struct om_hwdevconfig *dc = &omfb_console_dc;
	struct rasops_info *ri = &dc->dc_ri;
	long defattr;

	omfb_getdevconfig(OMFB_FB_WADDR, dc);
	ri->ri_ops.alloc_attr(ri, 0, 0, 0, &defattr);
	wsdisplay_cnattach(&omfb_stdscreen, ri, 0, 0, defattr);
	omfb_console = 1;
	return (0);
}

int
omfbioctl(void *v, u_long cmd, caddr_t data, int flag, struct proc *p)
{
	struct omfb_softc *sc = v;
	struct om_hwdevconfig *dc = sc->sc_dc;

	switch (cmd) {
	case WSDISPLAYIO_GTYPE:
		*(u_int *)data = WSDISPLAY_TYPE_LUNA;
		break;

	case WSDISPLAYIO_GINFO:
#define	wsd_fbip ((struct wsdisplay_fbinfo *)data)
		wsd_fbip->height = dc->dc_ht;
		wsd_fbip->width = dc->dc_wid;
		wsd_fbip->depth = dc->dc_depth;
		wsd_fbip->cmsize = dc->dc_cmsize;
#undef wsd_fbip
		break;

	case WSDISPLAYIO_LINEBYTES:
		*(u_int *)data = dc->dc_rowbytes;
		break;

	case WSDISPLAYIO_GETCMAP:
		return omgetcmap(sc, (struct wsdisplay_cmap *)data);

	case WSDISPLAYIO_PUTCMAP:
		return omsetcmap(sc, (struct wsdisplay_cmap *)data);

	case WSDISPLAYIO_GETSUPPORTEDDEPTH:
		*(u_int *)data = WSDISPLAYIO_DEPTH_1;
		break;

        case WSDISPLAYIO_SETGFXMODE:
                return omfb_set_gfxmode(sc, (struct wsdisplay_gfx_mode *)data);

	case WSDISPLAYIO_SVIDEO:
	case WSDISPLAYIO_GVIDEO:
		break;

	case WSDISPLAYIO_GCURPOS:
	case WSDISPLAYIO_SCURPOS:
	case WSDISPLAYIO_GCURMAX:
	case WSDISPLAYIO_GCURSOR:
	case WSDISPLAYIO_SCURSOR:
	default:
		return (-1);
	}

	return (0);
}

/*
 * Return the address that would map the given device at the given
 * offset, allowing for the given protection, or return -1 for error.
 */

paddr_t
omfbmmap(void *v, off_t offset, int prot)
{
	struct omfb_softc *sc = v;
	struct om_hwdevconfig *dc = sc->sc_dc;
	paddr_t cookie = -1;

	if ((offset & PAGE_MASK) != 0)
		return (-1);

#if 0	/* Workaround for making Xorg mono server work */
	if (offset >= 0 && offset < OMFB_SIZE)
		cookie = (paddr_t)(trunc_page(dc->dc_videobase) + offset);
#else
	if (offset >= 0 && offset < dc->dc_rowbytes * dc->dc_ht * hwplanebits)
		cookie = (paddr_t)(trunc_page(OMFB_FB_RADDR) + offset);
#endif
	return cookie;
}

int
omgetcmap(struct omfb_softc *sc, struct wsdisplay_cmap *p)
{
	u_int index = p->index, count = p->count;
        unsigned int cmsize;
	int error;

	cmsize = sc->sc_dc->dc_cmsize;

	/* Don't touch colormap when we use 1bpp */
	if (cmsize == 0)
		return (0);

	if (index >= cmsize || count > cmsize - index)
		return (EINVAL);

	error = copyout(&sc->sc_dc->dc_cmap.r[index], p->red, count);
	if (error != 0)
		return (error);
	error = copyout(&sc->sc_dc->dc_cmap.g[index], p->green, count);
	if (error != 0)
		return (error);
	error = copyout(&sc->sc_dc->dc_cmap.b[index], p->blue, count);
	if (error != 0)
		return (error);

	return (0);
}

int
omsetcmap(struct omfb_softc *sc, struct wsdisplay_cmap *p)
{
	struct hwcmap cmap;
	u_int index = p->index, count = p->count;
        unsigned int cmsize, i;
	int error;

	cmsize = sc->sc_dc->dc_cmsize;

	/* Don't touch colormap when we use 1bpp */
	if (cmsize == 0)
		return (0);

	if (index >= cmsize || count > cmsize - index)
		return (EINVAL);

	error = copyin(p->red, &cmap.r[index], count);
	if (error != 0)
		return (error);
	error = copyin(p->green, &cmap.g[index], count);
	if (error != 0)
		return (error);
	error = copyin(p->blue, &cmap.b[index], count);
	if (error != 0)
		return (error);

	memcpy(&sc->sc_dc->dc_cmap.r[index], &cmap.r[index], count);
	memcpy(&sc->sc_dc->dc_cmap.g[index], &cmap.g[index], count);
	memcpy(&sc->sc_dc->dc_cmap.b[index], &cmap.b[index], count);

	if (hwplanebits == 4) {
		struct bt454 *odac = (struct bt454 *)OMFB_RAMDAC;
		odac->bt_addr = (u_int8_t)index;
		for (i = index; i < index + count; i++) {
			odac->bt_cmap = sc->sc_dc->dc_cmap.r[i];
			odac->bt_cmap = sc->sc_dc->dc_cmap.g[i];
			odac->bt_cmap = sc->sc_dc->dc_cmap.b[i];
		}
	}
	else if (hwplanebits == 8) {
		struct bt458 *ndac = (struct bt458 *)OMFB_RAMDAC;
		ndac->bt_addr = (u_int8_t)index;
		for (i = index; i < index + count; i++) {
			ndac->bt_cmap = sc->sc_dc->dc_cmap.r[i];
			ndac->bt_cmap = sc->sc_dc->dc_cmap.g[i];
			ndac->bt_cmap = sc->sc_dc->dc_cmap.b[i];
		}
	}
	return (0);
}

void
omfb_getdevconfig(paddr_t paddr, struct om_hwdevconfig *dc)
{
	struct rasops_info *ri;
	union {
		struct { short h, v; } p;
		u_int32_t u;
	} rfcnt;

	/*
	 * If this is the first time call, check how many planes we really
	 * have.  This method is for 1, 4, and 8 bpp boards, must be checked
	 * different way for 24 bpp board...
	 */
	if ((hwplanebits > 0) && (dc->dc_depth_checked == 0)) {
		int i;
		u_int32_t *max, save;

		for (i = 0; i < 8; i++) {
			max = (u_int32_t *)trunc_page(OMFB_FB_RADDR
			    + OMFB_FB_PLANESIZE * i);
			save = *max;
			*(volatile uint32_t *)max = 0x5a5a5a5a;
			if (*max != 0x5a5a5a5a)
				break;
			*max = save;
		}
		hwplanebits = i;	/* should be 1, 4, or 8 */

		dc->dc_depth_checked = 1;
	}

	dc->dc_wid = 1280;
	dc->dc_ht = 1024;
	dc->dc_depth = hwplanebits;
	dc->dc_rowbytes = 2048 / 8;
	dc->dc_cmsize = (hwplanebits == 1) ? 0 : 1 << hwplanebits;
	dc->dc_videobase = paddr;

	/* set default colormap */
	omfb_set_default_cmap(dc);

	/* adjust h/v origin on screen */
	rfcnt.p.h = 7;
	rfcnt.p.v = -27;
	/* single write of 0x007ffe6 */
	*(volatile u_int32_t *)OMFB_RFCNT = rfcnt.u;

	/* clear the screen */
	omfb_clear_framebuffer(dc);

	/* initialize the raster */
	ri = &dc->dc_ri;
	ri->ri_width = dc->dc_wid;
	ri->ri_height = dc->dc_ht;
	ri->ri_depth = 1;	/* since planes are independently addressed */
	ri->ri_stride = dc->dc_rowbytes;
	ri->ri_bits = (void *)dc->dc_videobase;
	ri->ri_flg = RI_CENTER;
	ri->ri_hw = dc;

	rasops_init(ri, 35, 80);

	ri->ri_ops.copycols = om_copycols;
	ri->ri_ops.erasecols = om_erasecols;
	ri->ri_ops.copyrows = om_copyrows;
	ri->ri_ops.eraserows = om_eraserows;
	omfb_stdscreen.ncols = ri->ri_cols;
	omfb_stdscreen.nrows = ri->ri_rows;
	omfb_stdscreen.textops = &ri->ri_ops;
	omfb_stdscreen.fontwidth = ri->ri_font->fontwidth;
	omfb_stdscreen.fontheight = ri->ri_font->fontheight;

	/* set up depth-depend functions and so on */
	if ((hwplanebits == 4) || (hwplanebits == 8)) {
		setup_omrasops4(ri);
	} else {
		setup_omrasops1(ri);
	}
}

int
omfb_alloc_screen(void *v, const struct wsscreen_descr *type, void **cookiep,
    int *curxp, int *curyp, long *attrp)
{
	struct omfb_softc *sc = v;
	struct rasops_info *ri = &sc->sc_dc->dc_ri;

	if (sc->nscreens > 0)
		return (ENOMEM);

	*cookiep = ri;
	*curxp = 0;
	*curyp = 0;
	ri->ri_ops.alloc_attr(ri, 0, 0, 0, attrp);
	sc->nscreens++;
	return (0);
}

void
omfb_free_screen(void *v, void *cookie)
{
	struct omfb_softc *sc = v;

	sc->nscreens--;
}

int
omfb_show_screen(void *v, void *cookie, int waitok,
    void (*cb)(void *, int, int), void *cbarg)
{
	return 0;
}

int
omfb_load_font(void *v, void *emulcookie, struct wsdisplay_font *font)
{
	struct omfb_softc *sc = v;
	struct rasops_info *ri = &sc->sc_dc->dc_ri;

	return rasops_load_font(ri, emulcookie, font);
}

int
omfb_list_font(void *v, struct wsdisplay_font *font)
{
	struct omfb_softc *sc = v;
	struct rasops_info *ri = &sc->sc_dc->dc_ri;

	return rasops_list_font(ri, font);
}

/*
 * Change `pseudo' depth, set the default colormap, and clear frame buffer.
 * Note: when called with depth == 0, change to the original hardware depth.
 */
int
omfb_set_gfxmode(struct omfb_softc *sc, struct wsdisplay_gfx_mode *wsd_gfxmode)
{
        /* LUNA's fb is fixed size */
        if ((wsd_gfxmode->width != sc->sc_dc->dc_wid)
                || (wsd_gfxmode->height != sc->sc_dc->dc_ht))
                        return -1;

	/* if depth == 0, set the original hardware depth */
	if (wsd_gfxmode->depth == 0)
		wsd_gfxmode->depth = hwplanebits;

        switch (wsd_gfxmode->depth) {
        case 1:
		/* all frame buffer support this */
		sc->sc_dc->dc_depth = 1;
		sc->sc_dc->dc_cmsize = 0;
                break;
        case 4:
		if ((hwplanebits == 4) || (hwplanebits == 8)) {
			sc->sc_dc->dc_depth = 4;
			sc->sc_dc->dc_cmsize = 16;
			break;
		} else
			return -1;
        case 8:
		if (hwplanebits == 8) {
			sc->sc_dc->dc_depth = 8;
			sc->sc_dc->dc_cmsize = 256;
			break;
		} else
			return -1;
        default:
                return -1;
        }

	omfb_set_default_cmap(sc->sc_dc);
	omfb_clear_framebuffer(sc->sc_dc);

        return 0;
}

/*
 * Clear all planes of frame buffer
 */
void
omfb_clear_framebuffer(struct om_hwdevconfig *dc)
{
	int i;

	*(volatile u_int32_t *)OMFB_PLANEMASK = 0xff;	/* all planes */
	((volatile u_int32_t *)OMFB_ROPFUNC)[5] = ~0;	/* ROP copy */
	for (i = 0; i < dc->dc_ht * dc->dc_rowbytes / sizeof(u_int32_t); i++)
		*((volatile u_int32_t *)dc->dc_videobase + i) = 0;
	*(volatile u_int32_t *)OMFB_PLANEMASK = 0x01;	/* plane #0 only */
}

/*
 * Set default colormap; white on black for 1bpp, ANSI 16 colors for 4/8 bpp.
 *
 * Note about workaround for 8bpp frame buffer:
 *
 * Current LUNA wscons touches only first 4 planes (plane #0-#3), but
 * other program (e.g. mlterm-fb) can use all 8 planes on an 8bpp
 * frame buffer.  When such program exits, it may not clear all planes,
 * so there may be some visible garbage data on the other 4 planes
 * (plane #4-#7) when we use default 256 rasops_cmap directly.
 *
 * We should manage all 8 planes on LUNA, but that will be too much
 * overhead for 16 colors wscons.  So, by repeating 16 colors in 256
 * colormap, we can ignore the values on the other 4 planes.
 */
void
omfb_set_default_cmap(struct om_hwdevconfig *dc)
{
	int i;

	if ((hwplanebits == 1) || (hwplanebits == 4)) {
		struct bt454 *odac = (struct bt454 *)OMFB_RAMDAC;

		odac->bt_addr = 0;
		if (dc->dc_depth == 1) {
			/* white on black */
			for (i = 0; i < 16; i++) {
				u_int8_t val = i % 2 ? 255 : 0;

				odac->bt_cmap = dc->dc_cmap.r[i] = val;
				odac->bt_cmap = dc->dc_cmap.g[i] = val;
				odac->bt_cmap = dc->dc_cmap.b[i] = val;
			}
		} else {
			for (i = 0; i < 16; i++) {
			/* Set ANSI 16 colors */
				odac->bt_cmap = dc->dc_cmap.r[i]
				    = rasops_cmap[i * 3];
				odac->bt_cmap = dc->dc_cmap.g[i]
				    = rasops_cmap[i * 3 + 1];
				odac->bt_cmap = dc->dc_cmap.b[i]
				    = rasops_cmap[i * 3 + 2];
			}
		}
	} else if (hwplanebits == 8) {
		struct bt458 *ndac = (struct bt458 *)OMFB_RAMDAC;

		/*
		 * Initialize the Bt458.  When we write to control registers,
		 * the address is not incremented automatically. So we specify
		 * it ourselves for each control register.
		 */
		ndac->bt_addr = 0x04;
		ndac->bt_ctrl = 0xff; /* all planes will be read */
		ndac->bt_addr = 0x05;
		ndac->bt_ctrl = 0x00; /* all planes have non-blink */
		ndac->bt_addr = 0x06;
		ndac->bt_ctrl = 0x40; /* palette enabled, ovly plane disabled */
		ndac->bt_addr = 0x07;
		ndac->bt_ctrl = 0x00; /* no test mode */

		ndac->bt_addr = 0;
		if (dc->dc_depth == 1) {
			/* white on black */
			for (i = 0; i < 256; i++) {
				u_int8_t val = i % 2 ? 255 : 0;

				ndac->bt_cmap = dc->dc_cmap.r[i] = val;
				ndac->bt_cmap = dc->dc_cmap.g[i] = val;
				ndac->bt_cmap = dc->dc_cmap.b[i] = val;
			}
		} else {
			/*
			 * Set ANSI 16 colors.  On 8bpp frame buffer, repeat
			 * 16 colors in 256 colormap as described above.
			 */
			for (i = 0; i < 256; i++) {
				int index = i % 16;
				ndac->bt_cmap = dc->dc_cmap.r[i]
				    = rasops_cmap[index * 3];
				ndac->bt_cmap = dc->dc_cmap.g[i]
				    = rasops_cmap[index * 3 + 1];
				ndac->bt_cmap = dc->dc_cmap.b[i]
				    = rasops_cmap[index * 3 + 2];
			}
		}
	}
}


code:
/*	$OpenBSD: lunaws.c,v 1.11 2014/06/07 11:55:35 aoyama Exp $	*/
/* $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/param.h>
#include <sys/systm.h>
#include <sys/conf.h>
#include <sys/device.h>

#include <dev/wscons/wsconsio.h>
#include <dev/wscons/wskbdvar.h>
#include <dev/wscons/wsksymdef.h>
#include <dev/wscons/wsksymvar.h>
#ifdef WSDISPLAY_COMPAT_RAWKBD
#include <dev/wscons/wskbdraw.h>
#endif
#include "wsmouse.h"
#if NWSMOUSE > 0
#include <dev/wscons/wsmousevar.h>
#endif

#include <luna88k/dev/omkbdmap.h>
#include <luna88k/dev/sioreg.h>
#include <luna88k/dev/siovar.h>

static const u_int8_t ch1_regs[6] = {
	WR0_RSTINT,				/* Reset E/S Interrupt */
	WR1_RXALLS,				/* Rx per char, No Tx */
	0,					/* */
	WR3_RX8BIT | WR3_RXENBL,		/* Rx */
	WR4_BAUD96 | WR4_STOP1 | WR4_NPARITY,	/* Tx/Rx */
	WR5_TX8BIT | WR5_TXENBL,		/* Tx */
};

struct ws_softc {
	struct device	sc_dv;
	struct sioreg	*sc_ctl;
	u_int8_t	sc_wr[6];
	struct device	*sc_wskbddev;
#if NWSMOUSE > 0
	struct device	*sc_wsmousedev;
	int		sc_msreport;
	int		buttons, dx, dy;
#endif

#ifdef WSDISPLAY_COMPAT_RAWKBD
	int		sc_rawkbd;
#endif
};

void omkbd_input(void *, int);
void omkbd_decode(void *, int, u_int *, int *);
int  omkbd_enable(void *, int);
void omkbd_set_leds(void *, int);
int  omkbd_ioctl(void *, u_long, caddr_t, int, struct proc *);

const struct wskbd_mapdata omkbd_keymapdata = {
	omkbd_keydesctab,
#ifdef	OMKBD_LAYOUT
	OMKBD_LAYOUT,
#else
	KB_JP | KB_DEFAULT,
#endif
};

const struct wskbd_accessops omkbd_accessops = {
	omkbd_enable,
	omkbd_set_leds,
	omkbd_ioctl,
};

void	ws_cnattach(void);
void ws_cngetc(void *, u_int *, int *);
void ws_cnpollc(void *, int);
const struct wskbd_consops ws_consops = {
	ws_cngetc,
	ws_cnpollc,
	NULL	/* bell */
};

#if NWSMOUSE > 0
int  omms_enable(void *);
int  omms_ioctl(void *, u_long, caddr_t, int, struct proc *);
void omms_disable(void *);

const struct wsmouse_accessops omms_accessops = {
	omms_enable,
	omms_ioctl,
	omms_disable,
};
#endif

void wsintr(int);

int  wsmatch(struct device *, void *, void *);
void wsattach(struct device *, struct device *, void *);
int  ws_submatch_kbd(struct device *, void *, void *);
#if NWSMOUSE > 0
int  ws_submatch_mouse(struct device *, void *, void *);
#endif

const struct cfattach ws_ca = {
	sizeof(struct ws_softc), wsmatch, wsattach
};

struct cfdriver ws_cd = {
        NULL, "ws", DV_TTY
};

extern int  syscngetc(dev_t);
extern void syscnputc(dev_t, int);

int
wsmatch(struct device *parent, void *match, void *aux)
{
	struct sio_attach_args *args = aux;

	if (args->channel != 1)
		return 0;
	return 1;
}

void
wsattach(struct device *parent, struct device *self, void *aux)
{
	struct ws_softc *sc = (struct ws_softc *)self;
	struct sio_softc *scp = (struct sio_softc *)parent;
	struct sio_attach_args *args = aux;
	struct wskbddev_attach_args a;

	sc->sc_ctl = (struct sioreg *)scp->scp_ctl + 1;
	bcopy(ch1_regs, sc->sc_wr, sizeof(ch1_regs));
	scp->scp_intr[1] = wsintr;

	setsioreg(sc->sc_ctl, WR0, sc->sc_wr[WR0]);
	setsioreg(sc->sc_ctl, WR4, sc->sc_wr[WR4]);
	setsioreg(sc->sc_ctl, WR3, sc->sc_wr[WR3]);
	setsioreg(sc->sc_ctl, WR5, sc->sc_wr[WR5]);
	setsioreg(sc->sc_ctl, WR0, sc->sc_wr[WR0]);
	setsioreg(sc->sc_ctl, WR1, sc->sc_wr[WR1]);

	syscnputc((dev_t)1, 0x20); /* keep quiet mouse */

	printf("\n");

	a.console = (args->hwflags == 1);
	a.keymap = &omkbd_keymapdata;
	a.accessops = &omkbd_accessops;
	a.accesscookie = (void *)sc;
	sc->sc_wskbddev = config_found_sm(self, &a, wskbddevprint,
					ws_submatch_kbd);

#if NWSMOUSE > 0
	{
	struct wsmousedev_attach_args b;
	b.accessops = &omms_accessops;
	b.accesscookie = (void *)sc;
	sc->sc_wsmousedev = config_found_sm(self, &b, wsmousedevprint,
					ws_submatch_mouse);
	sc->sc_msreport = 0;
	}
#endif
}

int
ws_submatch_kbd(struct device *parent, void *match, void *aux)
{
	struct cfdata *cf = match;

        if (strcmp(cf->cf_driver->cd_name, "wskbd"))
                return (0);
        return ((*cf->cf_attach->ca_match)(parent, cf, aux));
}

#if NWSMOUSE > 0

int
ws_submatch_mouse(struct device *parent, void *match, void *aux)
{
	struct cfdata *cf = match;

        if (strcmp(cf->cf_driver->cd_name, "wsmouse"))
                return (0);
        return ((*cf->cf_attach->ca_match)(parent, cf, aux));
}

#endif

/*ARGSUSED*/
void
wsintr(int chan)
{
	struct ws_softc *sc = ws_cd.cd_devs[0];
	struct sioreg *sio = sc->sc_ctl;
	u_int code;
	int rr;

	rr = getsiocsr(sio);
	if (rr & RR_RXRDY) {
		do {
			code = sio->sio_data;
			if (rr & (RR_FRAMING | RR_OVERRUN | RR_PARITY)) {
				sio->sio_cmd = WR0_ERRRST;
				continue;
			}
#if NWSMOUSE > 0
			/*
			 * if (code >= 0x80 && code <= 0x87), then
			 * it's the first byte of 3 byte long mouse report
			 * 	code[0] & 07 -> LMR button condition
			 *	code[1], [2] -> x,y delta
			 * otherwise, key press or release event.
			 */
			if (sc->sc_msreport == 0) {
				if (code < 0x80 || code > 0x87) {
					omkbd_input(sc, code);
					continue;
				}
				code = (code & 07) ^ 07;
				/* LMR->RML: wsevent counts 0 for leftmost */
				sc->buttons = (code & 02);
				if (code & 01)
					sc->buttons |= 04;
				if (code & 04)
					sc->buttons |= 01;
				sc->sc_msreport = 1;
			}
			else if (sc->sc_msreport == 1) {
				sc->dx = (signed char)code;
				sc->sc_msreport = 2;
			}
			else if (sc->sc_msreport == 2) {
				sc->dy = (signed char)code;
				if (sc->sc_wsmousedev != NULL)
					wsmouse_input(sc->sc_wsmousedev,
					    sc->buttons, sc->dx, sc->dy, 0, 0,
					    WSMOUSE_INPUT_DELTA);
				sc->sc_msreport = 0;
			}
#else
			omkbd_input(sc, code);
#endif
		} while ((rr = getsiocsr(sio)) & RR_RXRDY);
	}
	if (rr & RR_TXRDY)
		sio->sio_cmd = WR0_RSTPEND;
	/* not capable of transmit, yet */
}

void
omkbd_input(void *v, int data)
{
	struct ws_softc *sc = v;
	u_int type;
	int key;

	omkbd_decode(v, data, &type, &key);

#if WSDISPLAY_COMPAT_RAWKBD
	if (sc->sc_rawkbd) {
		u_char cbuf[2];
		int c, j = 0;

		c = omkbd_raw[key];
		if (c != RAWKEY_Null) {
			/* fake extended scancode if necessary */
			if (c & 0x80)
				cbuf[j++] = 0xe0;
			cbuf[j] = c & 0x7f;
			if (type == WSCONS_EVENT_KEY_UP)
				cbuf[j] |= 0x80;
			j++;

			wskbd_rawinput(sc->sc_wskbddev, cbuf, j);
		}
	} else
#endif
	{
		if (sc->sc_wskbddev != NULL)
			wskbd_input(sc->sc_wskbddev, type, key);
	}
}

void
omkbd_decode(void *v, int datain, u_int *type, int *dataout)
{
	*type = (datain & 0x80) ? WSCONS_EVENT_KEY_UP : WSCONS_EVENT_KEY_DOWN;
	*dataout = datain & 0x7f;
}

void
ws_cngetc(void *v, u_int *type, int *data)
{
	int code;

	code = syscngetc((dev_t)1);
	omkbd_decode(v, code, type, data);
}

void
ws_cnpollc(void *v, int on)
{
}

/* EXPORT */ void
ws_cnattach()
{
	static int voidfill;

	/* XXX need CH.B initialization XXX */

	wskbd_cnattach(&ws_consops, &voidfill, &omkbd_keymapdata);
}

int
omkbd_enable(void *v, int on)
{
	return 0;
}

void
omkbd_set_leds(void *v, int leds)
{
#if 0
	syscnputc((dev_t)1, 0x10); /* kana LED on */
	syscnputc((dev_t)1, 0x00); /* kana LED off */
	syscnputc((dev_t)1, 0x11); /* caps LED on */
	syscnputc((dev_t)1, 0x01); /* caps LED off */
#endif
}

int
omkbd_ioctl(void *v, u_long cmd, caddr_t data, int flag, struct proc *p)
{
#if WSDISPLAY_COMPAT_RAWKBD
	struct ws_softc *sc = v;
#endif

	switch (cmd) {
	case WSKBDIO_GTYPE:
		*(int *)data = WSKBD_TYPE_LUNA;
		return 0;
	case WSKBDIO_SETLEDS:
	case WSKBDIO_GETLEDS:
	case WSKBDIO_COMPLEXBELL:	/* XXX capable of complex bell */
		return -1;
#if WSDISPLAY_COMPAT_RAWKBD
	case WSKBDIO_SETMODE:
		sc->sc_rawkbd = *(int *)data == WSKBD_RAW;
		return 0;
	case WSKBDIO_GETMODE:
		*(int *)data = sc->sc_rawkbd;
		return 0;
#endif
	}
	return -1;
}

#if NWSMOUSE > 0

int
omms_enable(void *v)
{
	struct ws_softc *sc = v;

	syscnputc((dev_t)1, 0x60); /* enable 3 byte long mouse reporting */
	sc->sc_msreport = 0;
	return 0;
}

/*ARGUSED*/
int
omms_ioctl(void *v, u_long cmd, caddr_t data, int flag, struct proc *p)
{
#if 0
	struct ws_softc *sc = v;
#endif

	switch (cmd) {
	case WSMOUSEIO_GTYPE:
		*(u_int *)data = WSMOUSE_TYPE_LUNA;
		return 0;
	}

	return -1;
}

void
omms_disable(void *v)
{
	struct ws_softc *sc = v;

	syscnputc((dev_t)1, 0x20); /* quiet mouse */
	sc->sc_msreport = 0;
}
#endif


code:
/*	$OpenBSD: maskbits.h,v 1.2 2014/01/02 15:30:34 aoyama Exp $	*/
/*	$NetBSD: maskbits.h,v 1.3 1997/03/31 07:37:28 scottr Exp $	*/

/*-
 * Copyright (c) 1994
 *	The Regents of the University of California.  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. 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.
 *
 *	@(#)maskbits.h	8.2 (Berkeley) 3/21/94
 */

#include <luna88k/dev/omrasops.h>	/* R(), W(), RR_* defines */

/* This file is derived from OpenBSD:/usr/src/sys/arch/hp300/dev/maskbits.h */

/*
 * Derived from X11R4
 */

/* the following notes use the following conventions:
SCREEN LEFT				SCREEN RIGHT
in this file and maskbits.c, left and right refer to screen coordinates,
NOT bit numbering in registers.

rasops_lmask[n]
	bits[0,n-1] = 0	bits[n,31] = 1
rasops_rmask[n] =
	bits[0,n-1] = 1	bits[n,31] = 0

maskbits(x, w, startmask, endmask, nlw)
	for a span of width w starting at position x, returns
a mask for ragged bits at start, mask for ragged bits at end,
and the number of whole longwords between the ends.

*/

#define maskbits(x, w, startmask, endmask, nlw)				\
do {									\
	startmask = rasops_lmask[(x) & 0x1f];				\
	endmask = rasops_rmask[((x) + (w)) & 0x1f];			\
	if (startmask)							\
		nlw = (((w) - (32 - ((x) & 0x1f))) >> 5);		\
	else								\
		nlw = (w) >> 5;						\
} while (0)

/*
 * On LUNA's frame buffer, MSB(bit 31) is displayed at most left hand of
 * the screen.  This is different from rasops_masks.{c,h} assumption.
 * So we use our own MBL(Move Bit Left)/MBR(Move Bit Right) macros to
 * handle display memory images.
 */

#define OMFB_MBL(x,y)        ((y) > 31 ? 0 : (x) << (y))
#define OMFB_MBR(x,y)        ((y) > 31 ? 0 : (x) >> (y))

/*
 * And, our private version of GETBITS/PUTBITS.
 * XXX: We consider only 1 bpp for now.
 */

/* Get a number of bits ( <= 32 ) from *sp and store in dw */
#define OMFB_GETBITS(sp, x, w, dw)					\
do {									\
	dw = OMFB_MBL(*(sp), (x));					\
	if (((x) + (w)) > 32)						\
		dw |= (OMFB_MBR(*(sp + 1), 32 - (x)));	 		\
} while(0);

/* Put a number of bits ( <= 32 ) from sw to *dp */
#define OMFB_PUTBITS(sw, x, w, dp)					\
do {									\
	int n = (x) + (w) - 32;						\
									\
	if (n <= 0) {							\
		n = rasops_pmask[x & 31][w & 31];			\
		*(dp) = (*(dp) & ~n) | (OMFB_MBR(sw, x) & n);		\
	} else {							\
		*(dp) = (*(dp) & rasops_rmask[x])			\
			| (OMFB_MBR(sw, x));				\
		*(dp + 1) = (*(dp + 1) & rasops_lmask[n])		\
			| (OMFB_MBL(sw, 32-(x)) & rasops_rmask[n]);	\
	}								\
} while(0);

#define getandputrop(psrc, srcbit, dstbit, width, pdst, rop)		\
do {									\
	u_int32_t _tmpdst; 						\
	if (rop == RR_CLEAR)						\
		_tmpdst = 0;						\
	else								\
		OMFB_GETBITS(psrc, srcbit, width, _tmpdst);		\
	OMFB_PUTBITS(_tmpdst, dstbit, width, pdst); 			\
} while (0)

#define getunalignedword(psrc, x, dst)					\
do {									\
        u_int32_t _tmp; 						\
        OMFB_GETBITS(psrc, x, 32, _tmp);				\
        dst = _tmp;							\
} while (0)