code:
/*	$OpenBSD: pxa2x0_gpio.c,v 1.24 2014/07/12 18:44:41 tedu Exp $ */
/*	$NetBSD: pxa2x0_gpio.c,v 1.2 2003/07/15 00:24:55 lukem Exp $	*/

/*
 * Copyright 2003 Wasabi Systems, Inc.
 * All rights reserved.
 *
 * Written by Steve C. Woodford for Wasabi Systems, Inc.
 *
 * 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 for the NetBSD Project by
 *      Wasabi Systems, Inc.
 * 4. The name of Wasabi Systems, Inc. may not be used to endorse
 *    or promote products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

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

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

#include <arm/cpufunc.h>

#include <arm/xscale/pxa2x0reg.h>
#include <arm/xscale/pxa2x0var.h>
#include <arm/xscale/pxa2x0_gpio.h>

struct gpio_irq_handler {
	struct gpio_irq_handler *gh_next;
	int (*gh_func)(void *);
	void *gh_arg;
	int gh_spl;
	u_int gh_gpio;
	int gh_level;
	int gh_irq;
	struct evcount gh_count;
};

struct pxagpio_softc {
	struct device sc_dev;
	bus_space_tag_t sc_bust;
	bus_space_handle_t sc_bush;
	void *sc_irqcookie[4];
	u_int32_t sc_mask[3];
#ifdef PXAGPIO_HAS_GPION_INTRS
	struct gpio_irq_handler *sc_handlers[GPIO_NPINS];
	int sc_minipl;
	int sc_maxipl;
#else
	struct gpio_irq_handler *sc_handlers[2];
#endif
	int npins;
	int pxa27x_pins;
};

int	pxagpio_match(struct device *, void *, void *);
void	pxagpio_attach(struct device *, struct device *, void *);

#ifdef __NetBSD__
CFATTACH_DECL(pxagpio, sizeof(struct pxagpio_softc),
    pxagpio_match, pxagpio_attach, NULL, NULL);
#else
struct cfattach pxagpio_ca = {
        sizeof (struct pxagpio_softc), pxagpio_match, pxagpio_attach
};

struct cfdriver pxagpio_cd = {
	NULL, "pxagpio", DV_DULL
};

#endif

static struct pxagpio_softc *pxagpio_softc;
static vaddr_t pxagpio_regs;
#define GPIO_BOOTSTRAP_REG(reg)	\
	(*((volatile u_int32_t *)(pxagpio_regs + (reg))))

void pxa2x0_gpio_set_intr_level(u_int, int);
int pxagpio_intr0(void *);
int pxagpio_intr1(void *);
#ifdef PXAGPIO_HAS_GPION_INTRS
int pxagpio_dispatch(struct pxagpio_softc *, int);
int pxagpio_intrN(void *);
int pxagpio_intrlow(void *);
void pxa2x0_gpio_intr_fixup(int minipl, int maxipl);
#endif
u_int32_t pxagpio_reg_read(struct pxagpio_softc *sc, int reg);
void pxagpio_reg_write(struct pxagpio_softc *sc, int reg, u_int32_t val);

u_int32_t
pxagpio_reg_read(struct pxagpio_softc *sc, int reg)
{
	if (__predict_true(sc != NULL))
		return (bus_space_read_4(sc->sc_bust, sc->sc_bush, reg));
	else
	if (pxagpio_regs)
		return (GPIO_BOOTSTRAP_REG(reg));
	panic("pxagpio_reg_read: not bootstrapped");
}

void
pxagpio_reg_write(struct pxagpio_softc *sc, int reg, u_int32_t val)
{
	if (__predict_true(sc != NULL))
		bus_space_write_4(sc->sc_bust, sc->sc_bush, reg, val);
	else
	if (pxagpio_regs)
		GPIO_BOOTSTRAP_REG(reg) = val;
	else
		panic("pxagpio_reg_write: not bootstrapped");
	return;
}

int
pxagpio_match(struct device *parent, void *cf, void *aux)
{
	struct pxaip_attach_args *pxa = aux;

	if (pxagpio_softc != NULL || pxa->pxa_addr != PXA2X0_GPIO_BASE)
		return (0);

	pxa->pxa_size = PXA2X0_GPIO_SIZE;

	return (1);
}

void
pxagpio_attach(struct device *parent, struct device *self, void *aux)
{
	struct pxagpio_softc *sc = (struct pxagpio_softc *)self;
	struct pxaip_attach_args *pxa = aux;

	sc->sc_bust = pxa->pxa_iot;

	printf(": GPIO Controller\n");

	if ((cputype & ~CPU_ID_XSCALE_COREREV_MASK) == CPU_ID_PXA27X) {
		sc->npins = GPIO_NPINS;
		sc->pxa27x_pins = 1;
	} else  {
		sc->npins = GPIO_NPINS_25x;
		sc->pxa27x_pins = 0;
	}

	if (bus_space_map(sc->sc_bust, pxa->pxa_addr, pxa->pxa_size, 0,
	    &sc->sc_bush)) {
		printf("%s: Can't map registers!\n", sc->sc_dev.dv_xname);
		return;
	}

	memset(sc->sc_handlers, 0, sizeof(sc->sc_handlers));

	/*
	 * Disable all GPIO interrupts
	 */
	pxagpio_reg_write(sc, GPIO_GRER0, 0);
	pxagpio_reg_write(sc, GPIO_GRER1, 0);
	pxagpio_reg_write(sc, GPIO_GRER2, 0);
	pxagpio_reg_write(sc, GPIO_GRER3, 0);
	pxagpio_reg_write(sc, GPIO_GFER0, 0);
	pxagpio_reg_write(sc, GPIO_GFER1, 0);
	pxagpio_reg_write(sc, GPIO_GFER2, 0);
	pxagpio_reg_write(sc, GPIO_GFER3, 0);
	pxagpio_reg_write(sc, GPIO_GEDR0, ~0);
	pxagpio_reg_write(sc, GPIO_GEDR1, ~0);
	pxagpio_reg_write(sc, GPIO_GEDR2, ~0);
	pxagpio_reg_write(sc, GPIO_GEDR3, ~0);

#ifdef PXAGPIO_HAS_GPION_INTRS
	sc->sc_minipl = IPL_NONE;
	sc->sc_maxipl = IPL_NONE;
#endif

	sc->sc_irqcookie[0] = sc->sc_irqcookie[1] = NULL;

	pxagpio_softc = sc;
}

void
pxa2x0_gpio_bootstrap(vaddr_t gpio_regs)
{

	pxagpio_regs = gpio_regs;
}

void *
pxa2x0_gpio_intr_establish(u_int gpio, int level, int spl, int (*func)(void *),
    void *arg, const char *name)
{
	struct pxagpio_softc *sc = pxagpio_softc;
	struct gpio_irq_handler *gh;
	u_int32_t bit;

#ifdef DEBUG
#ifdef PXAGPIO_HAS_GPION_INTRS
	if (gpio >= sc->npins)
		panic("pxa2x0_gpio_intr_establish: bad pin number: %d", gpio);
#else
	if (gpio > 1)
		panic("pxa2x0_gpio_intr_establish: bad pin number: %d", gpio);
#endif
#endif

	if (GPIO_FN_IS_OUT(pxa2x0_gpio_get_function(gpio)) != GPIO_IN)
		panic("pxa2x0_gpio_intr_establish: Pin %d not GPIO_IN", gpio);

	gh = (struct gpio_irq_handler *)malloc(sizeof(struct gpio_irq_handler),
	    M_DEVBUF, M_NOWAIT);

	gh->gh_func = func;
	gh->gh_arg = arg;
	gh->gh_spl = spl;
	gh->gh_gpio = gpio;
	gh->gh_irq = gpio+32;
	gh->gh_level = level;
	evcount_attach(&gh->gh_count, name, &gh->gh_irq);

	gh->gh_next = sc->sc_handlers[gpio];
	sc->sc_handlers[gpio] = gh;

	if (gpio == 0) {
		KDASSERT(sc->sc_irqcookie[0] == NULL);
		sc->sc_irqcookie[0] = pxa2x0_intr_establish(PXA2X0_INT_GPIO0,
		    spl, pxagpio_intr0, sc, NULL);
		KDASSERT(sc->sc_irqcookie[0]);
	} else if (gpio == 1) {
		KDASSERT(sc->sc_irqcookie[1] == NULL);
		sc->sc_irqcookie[1] = pxa2x0_intr_establish(PXA2X0_INT_GPIO1,
		    spl, pxagpio_intr1, sc, NULL);
		KDASSERT(sc->sc_irqcookie[1]);
	} else {
#ifdef PXAGPIO_HAS_GPION_INTRS
		int minipl, maxipl;

		if (sc->sc_maxipl == IPL_NONE || spl > sc->sc_maxipl) {
			maxipl = spl;
		} else {
			maxipl = sc->sc_maxipl;
		}

		if (sc->sc_minipl == IPL_NONE || spl < sc->sc_minipl) {
			minipl = spl;
		} else {
			minipl = sc->sc_minipl;
		}
		pxa2x0_gpio_intr_fixup(minipl, maxipl);
#endif
	}

	bit = GPIO_BIT(gpio);
	sc->sc_mask[GPIO_BANK(gpio)] |= bit;

	pxa2x0_gpio_set_intr_level(gpio, gh->gh_level);

	return (gh);
}

void
pxa2x0_gpio_intr_disestablish(void *cookie)
{
	struct pxagpio_softc *sc = pxagpio_softc;
	struct gpio_irq_handler *gh = cookie;
	u_int32_t bit, reg;

	evcount_detach(&gh->gh_count);

	bit = GPIO_BIT(gh->gh_gpio);

	reg = pxagpio_reg_read(sc, GPIO_REG(GPIO_GFER0, gh->gh_gpio));
	reg &= ~bit;
	pxagpio_reg_write(sc, GPIO_REG(GPIO_GFER0, gh->gh_gpio), reg);
	reg = pxagpio_reg_read(sc, GPIO_REG(GPIO_GRER0, gh->gh_gpio));
	reg &= ~bit;
	pxagpio_reg_write(sc, GPIO_REG(GPIO_GRER0, gh->gh_gpio), reg);

	pxagpio_reg_write(sc, GPIO_REG(GPIO_GEDR0, gh->gh_gpio), bit);

	sc->sc_mask[GPIO_BANK(gh->gh_gpio)] &= ~bit;
	sc->sc_handlers[gh->gh_gpio] = NULL;

	if (gh->gh_gpio == 0) {
		pxa2x0_intr_disestablish(sc->sc_irqcookie[0]);
		sc->sc_irqcookie[0] = NULL;
	} else if (gh->gh_gpio == 1) {
		pxa2x0_intr_disestablish(sc->sc_irqcookie[1]);
		sc->sc_irqcookie[1] = NULL;
	}  else {
#ifdef PXAGPIO_HAS_GPION_INTRS
		int i, minipl, maxipl, ipl;
		minipl = IPL_HIGH;
		maxipl = IPL_NONE;
		for (i = 2; i < sc->npins; i++) {
			if (sc->sc_handlers[i] != NULL) {
				ipl = sc->sc_handlers[i]->gh_spl;
				if (minipl > ipl)
					minipl = ipl;

				if (maxipl < ipl)
					maxipl = ipl;
			}
		}
		pxa2x0_gpio_intr_fixup(minipl, maxipl);
#endif /* PXAGPIO_HAS_GPION_INTRS */
	}

	free(gh, M_DEVBUF, 0);
}

#ifdef PXAGPIO_HAS_GPION_INTRS
void
pxa2x0_gpio_intr_fixup(int minipl, int maxipl)
{
	struct pxagpio_softc *sc = pxagpio_softc;
	int save = disable_interrupts(I32_bit);

	if (maxipl == IPL_NONE  && minipl == IPL_HIGH) {
		/* no remaining interrupts */
		if (sc->sc_irqcookie[2])
			pxa2x0_intr_disestablish(sc->sc_irqcookie[2]);
		sc->sc_irqcookie[2] = NULL;
		if (sc->sc_irqcookie[3])
			pxa2x0_intr_disestablish(sc->sc_irqcookie[3]);
		sc->sc_irqcookie[3] = NULL;
		sc->sc_minipl = IPL_NONE;
		sc->sc_maxipl = IPL_NONE;
		restore_interrupts(save);
		return;
	}

	if (sc->sc_maxipl == IPL_NONE || maxipl > sc->sc_maxipl) {
		if (sc->sc_irqcookie[2])
			pxa2x0_intr_disestablish(sc->sc_irqcookie[2]);

		sc->sc_maxipl = maxipl;
		sc->sc_irqcookie[2] =
		    pxa2x0_intr_establish(PXA2X0_INT_GPION,
		    maxipl, pxagpio_intrN, sc, NULL);

		if (sc->sc_irqcookie[2] == NULL) {
			printf("%s: failed to hook main "
			    "GPIO interrupt\n",
			    sc->sc_dev.dv_xname);
			/* XXX - panic? */
		}
	}
	if (sc->sc_minipl == IPL_NONE || minipl < sc->sc_minipl) {
		if (sc->sc_irqcookie[3])
			pxa2x0_intr_disestablish(sc->sc_irqcookie[3]);

		sc->sc_minipl = minipl;
		sc->sc_irqcookie[3] =
		    pxa2x0_intr_establish(PXA2X0_INT_GPION,
		    sc->sc_minipl, pxagpio_intrlow, sc, NULL);

		if (sc->sc_irqcookie[3] == NULL) {
			printf("%s: failed to hook main "
			    "GPIO interrupt\n",
			    sc->sc_dev.dv_xname);
			/* XXX - panic? */
		}
	}
	restore_interrupts(save);
}
#endif /* PXAGPIO_HAS_GPION_INTRS */

const char *
pxa2x0_gpio_intr_string(void *cookie)
{
	static char irqstr[32];
	struct gpio_irq_handler *gh = cookie;

	if (gh == NULL)
		snprintf(irqstr, sizeof irqstr, "couldn't establish interrupt");
	else
		snprintf(irqstr, sizeof irqstr, "irq %d", gh->gh_irq);
	return(irqstr);
}

int
pxagpio_intr0(void *arg)
{
	struct pxagpio_softc *sc = arg;
	int ret;

#ifdef DIAGNOSTIC
	if (sc->sc_handlers[0] == NULL) {
		printf("%s: stray GPIO#0 edge interrupt\n",
		    sc->sc_dev.dv_xname);
		return (0);
	}
#endif

	bus_space_write_4(sc->sc_bust, sc->sc_bush, GPIO_REG(GPIO_GEDR0, 0),
	    GPIO_BIT(0));

	ret = (sc->sc_handlers[0]->gh_func)(sc->sc_handlers[0]->gh_arg);
	if (ret != 0)
		sc->sc_handlers[0]->gh_count.ec_count++;
	return ret;
}

int
pxagpio_intr1(void *arg)
{
	struct pxagpio_softc *sc = arg;
	int ret;

#ifdef DIAGNOSTIC
	if (sc->sc_handlers[1] == NULL) {
		printf("%s: stray GPIO#1 edge interrupt\n",
		    sc->sc_dev.dv_xname);
		return (0);
	}
#endif

	bus_space_write_4(sc->sc_bust, sc->sc_bush, GPIO_REG(GPIO_GEDR0, 1),
	    GPIO_BIT(1));

	ret =  (sc->sc_handlers[1]->gh_func)(sc->sc_handlers[1]->gh_arg);
	if (ret != 0)
		sc->sc_handlers[1]->gh_count.ec_count++;
	return ret;
}

#ifdef PXAGPIO_HAS_GPION_INTRS
int
pxagpio_dispatch(struct pxagpio_softc *sc, int gpio_base)
{
	struct gpio_irq_handler **ghp, *gh;
	int i, s, nhandled, handled, pins;
	u_int32_t gedr, mask;
	int bank;

	/* Fetch bitmap of pending interrupts on this GPIO bank */
	gedr = pxagpio_reg_read(sc, GPIO_REG(GPIO_GEDR0, gpio_base));

	/* Don't handle GPIO 0/1 here */
	if (gpio_base == 0)
		gedr &= ~(GPIO_BIT(0) | GPIO_BIT(1));

	/* Bail early if there are no pending interrupts in this bank */
	if (gedr == 0)
		return (0);

	/* Acknowledge pending interrupts. */
	pxagpio_reg_write(sc, GPIO_REG(GPIO_GEDR0, gpio_base), gedr);

	bank = GPIO_BANK(gpio_base);

	/*
	 * We're only interested in those for which we have a handler
	 * registered
	 */
#ifdef DEBUG
	if ((gedr & sc->sc_mask[bank]) == 0) {
		printf("%s: stray GPIO interrupt. Bank %d, GEDR 0x%08x, mask 0x%08x\n",
		    sc->sc_dev.dv_xname, bank, gedr, sc->sc_mask[bank]);
		return (1);	/* XXX: Pretend we dealt with it */
	}
#endif

	gedr &= sc->sc_mask[bank];
	ghp = &sc->sc_handlers[gpio_base];
	if (sc->pxa27x_pins == 1)
		pins = (gpio_base < 96) ? 32 : 25;
	else
		pins = (gpio_base < 64) ? 32 : 17;
	handled = 0;

	for (i = 0, mask = 1; i < pins && gedr; i++, ghp++, mask <<= 1) {
		if ((gedr & mask) == 0)
			continue;
		gedr &= ~mask;

		if ((gh = *ghp) == NULL) {
			printf("%s: unhandled GPIO interrupt. GPIO#%d\n",
			    sc->sc_dev.dv_xname, gpio_base + i);
			continue;
		}

		s = _splraise(gh->gh_spl);
		do {
			nhandled = (gh->gh_func)(gh->gh_arg);
			if (nhandled != 0)
				gh->gh_count.ec_count++;
			handled |= nhandled;
			gh = gh->gh_next;
		} while (gh != NULL);
		splx(s);
	}

	return (handled);
}

int
pxagpio_intrN(void *arg)
{
	struct pxagpio_softc *sc = arg;
	int handled;

	handled = pxagpio_dispatch(sc, 0);
	handled |= pxagpio_dispatch(sc, 32);
	handled |= pxagpio_dispatch(sc, 64);
	handled |= pxagpio_dispatch(sc, 96);

	return (handled);
}

int
pxagpio_intrlow(void *arg)
{
	/* dummy */
	return 0;
}
#endif	/* PXAGPIO_HAS_GPION_INTRS */

u_int
pxa2x0_gpio_get_function(u_int gpio)
{
	struct pxagpio_softc *sc = pxagpio_softc;
	u_int32_t rv, io;

	if (__predict_true(sc != NULL))
		KDASSERT(gpio < sc->npins);

	rv = pxagpio_reg_read(sc, GPIO_FN_REG(gpio)) >> GPIO_FN_SHIFT(gpio);
	rv = GPIO_FN(rv);

	io = pxagpio_reg_read(sc, GPIO_REG(GPIO_GPDR0, gpio));
	if (io & GPIO_BIT(gpio))
		rv |= GPIO_OUT;

	io = pxagpio_reg_read(sc, GPIO_REG(GPIO_GPLR0, gpio));
	if (io & GPIO_BIT(gpio))
		rv |= GPIO_SET;

	return (rv);
}

u_int
pxa2x0_gpio_set_function(u_int gpio, u_int fn)
{
	struct pxagpio_softc *sc = pxagpio_softc;
	u_int32_t rv, bit;
	u_int oldfn;

	if (__predict_true(sc != NULL))
		KDASSERT(gpio < sc->npins);

	oldfn = pxa2x0_gpio_get_function(gpio);

	if (GPIO_FN(fn) == GPIO_FN(oldfn) &&
	    GPIO_FN_IS_OUT(fn) == GPIO_FN_IS_OUT(oldfn)) {
		/*
		 * The pin's function is not changing.
		 * For Alternate Functions and GPIO input, we can just
		 * return now.
		 * For GPIO output pins, check the initial state is
		 * the same.
		 *
		 * Return 'fn' instead of 'oldfn' so the caller can
		 * reliably detect that we didn't change anything.
		 * (The initial state might be different for non-
		 * GPIO output pins).
		 */
		if (!GPIO_IS_GPIO_OUT(fn) ||
		    GPIO_FN_IS_SET(fn) == GPIO_FN_IS_SET(oldfn))
			return (fn);
	}

	/*
	 * See section 4.1.3.7 of the PXA2x0 Developer's Manual for
	 * the correct procedure for changing GPIO pin functions.
	 */

	bit = GPIO_BIT(gpio);

	/*
	 * 1. Configure the correct set/clear state of the pin
	 */
	if (GPIO_FN_IS_SET(fn))
		pxagpio_reg_write(sc, GPIO_REG(GPIO_GPSR0, gpio), bit);
	else
		pxagpio_reg_write(sc, GPIO_REG(GPIO_GPCR0, gpio), bit);

	/*
	 * 2. Configure the pin as an input or output as appropriate
	 */
	rv = pxagpio_reg_read(sc, GPIO_REG(GPIO_GPDR0, gpio)) & ~bit;
	if (GPIO_FN_IS_OUT(fn))
		rv |= bit;
	pxagpio_reg_write(sc, GPIO_REG(GPIO_GPDR0, gpio), rv);

	/*
	 * 3. Configure the pin's function
	 */
	bit = GPIO_FN_MASK << GPIO_FN_SHIFT(gpio);
	fn = GPIO_FN(fn) << GPIO_FN_SHIFT(gpio);
	rv = pxagpio_reg_read(sc, GPIO_FN_REG(gpio)) & ~bit;
	pxagpio_reg_write(sc, GPIO_FN_REG(gpio), rv | fn);

	return (oldfn);
}

/*
 * Quick function to read pin value
 */
int
pxa2x0_gpio_get_bit(u_int gpio)
{
	struct pxagpio_softc *sc = pxagpio_softc;
	int bit;

	bit = GPIO_BIT(gpio);
	if (pxagpio_reg_read(sc, GPIO_REG(GPIO_GPLR0, gpio)) & bit)
		return 1;
	else
		return 0;
}

/*
 * Quick function to set pin to 1
 */
void
pxa2x0_gpio_set_bit(u_int gpio)
{
	struct pxagpio_softc *sc = pxagpio_softc;
	int bit;

	bit = GPIO_BIT(gpio);
	pxagpio_reg_write(sc, GPIO_REG(GPIO_GPSR0, gpio), bit);
}

/*
 * Quick function to set pin to 0
 */
void
pxa2x0_gpio_clear_bit(u_int gpio)
{
	struct pxagpio_softc *sc = pxagpio_softc;
	int bit;

	bit = GPIO_BIT(gpio);
	pxagpio_reg_write(sc, GPIO_REG(GPIO_GPCR0, gpio), bit);
}

/*
 * Quick function to change pin direction
 */
void
pxa2x0_gpio_set_dir(u_int gpio, int dir)
{
	struct pxagpio_softc *sc = pxagpio_softc;
	int bit;
	u_int32_t reg;

	bit = GPIO_BIT(gpio);

	reg = pxagpio_reg_read(sc, GPIO_REG(GPIO_GPDR0, gpio)) & ~bit;
	if (GPIO_FN_IS_OUT(dir))
		reg |= bit;
	pxagpio_reg_write(sc, GPIO_REG(GPIO_GPDR0, gpio), reg);
}

/*
 * Quick function to clear interrupt status on a pin
 * GPIO pins may be toggle in an interrupt and we dont want
 * extra spurious interrupts to occur.
 * Suppose this causes a slight race if a key is pressed while
 * the interrupt handler is running. (yes this is for the keyboard driver)
 */
void
pxa2x0_gpio_clear_intr(u_int gpio)
{
	struct pxagpio_softc *sc = pxagpio_softc;
	int bit;

	bit = GPIO_BIT(gpio);
	pxagpio_reg_write(sc, GPIO_REG(GPIO_GEDR0, gpio), bit);
}

/*
 * Quick function to mask (disable) a GPIO interrupt
 */
void
pxa2x0_gpio_intr_mask(void *v)
{
	struct gpio_irq_handler *gh = v;

	pxa2x0_gpio_set_intr_level(gh->gh_gpio, IPL_NONE);
}

/*
 * Quick function to unmask (enable) a GPIO interrupt
 */
void
pxa2x0_gpio_intr_unmask(void *v)
{
	struct gpio_irq_handler *gh = v;

	pxa2x0_gpio_set_intr_level(gh->gh_gpio, gh->gh_level);
}

/*
 * Configure the edge sensitivity of interrupt pins
 */
void
pxa2x0_gpio_set_intr_level(u_int gpio, int level)
{
	struct pxagpio_softc *sc = pxagpio_softc;
	u_int32_t bit;
	u_int32_t gfer;
	u_int32_t grer;
	int s;

	s = splhigh();

	bit = GPIO_BIT(gpio);
	gfer = pxagpio_reg_read(sc, GPIO_REG(GPIO_GFER0, gpio));
	grer = pxagpio_reg_read(sc, GPIO_REG(GPIO_GRER0, gpio));

	switch (level) {
	case IST_NONE:
		gfer &= ~bit;
		grer &= ~bit;
		break;
	case IST_EDGE_FALLING:
		gfer |= bit;
		grer &= ~bit;
		break;
	case IST_EDGE_RISING:
		gfer &= ~bit;
		grer |= bit;
		break;
	case IST_EDGE_BOTH:
		gfer |= bit;
		grer |= bit;
		break;
	default:
		panic("pxa2x0_gpio_set_intr_level: bad level: %d", level);
		break;
	}

	pxagpio_reg_write(sc, GPIO_REG(GPIO_GFER0, gpio), gfer);
	pxagpio_reg_write(sc, GPIO_REG(GPIO_GRER0, gpio), grer);

	splx(s);
}


code:
/*	$OpenBSD: pxa2x0_gpio.h,v 1.6 2009/08/22 02:54:50 mk Exp $ */
/*	$wasabi$	*/

/*
 * Copyright 2003 Wasabi Systems, Inc.
 * All rights reserved.
 *
 * Written by Steve C. Woodford for Wasabi Systems, Inc.
 *
 * 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 for the NetBSD Project by
 *      Wasabi Systems, Inc.
 * 4. The name of Wasabi Systems, Inc. may not be used to endorse
 *    or promote products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef _PXA2X0_GPIO_H
#define _PXA2X0_GPIO_H

/*
 * If you want to fiddle with GPIO registers before the
 * driver has been autoconfigured (e.g. from initarm()),
 * call this function with the virtual address of the
 * GPIO controller's registers
 */
void pxa2x0_gpio_bootstrap(vaddr_t);

/*
 * GPIO pin function query/manipulation functions
 */
u_int pxa2x0_gpio_get_function(u_int);
u_int pxa2x0_gpio_set_function(u_int, u_int);
int pxa2x0_gpio_get_bit(u_int gpio);
void pxa2x0_gpio_set_bit(u_int gpio);
void pxa2x0_gpio_clear_bit(u_int gpio);
void pxa2x0_gpio_set_dir(u_int gpio, int dir);
void pxa2x0_gpio_clear_intr(u_int gpio);

/*
 * Establish/Disestablish interrupt handlers for GPIO pins
 */
void *pxa2x0_gpio_intr_establish(u_int, int, int, int (*)(void *), void *,
    const char *);
void pxa2x0_gpio_intr_disestablish(void *);
const char *pxa2x0_gpio_intr_string(void *);
void pxa2x0_gpio_intr_mask(void *);
void pxa2x0_gpio_intr_unmask(void *);

#endif /* _PXA2X0_GPIO_H */

license: unknown


code:
/*	$OpenBSD: pxa2x0_i2c.c,v 1.2 2005/05/26 03:52:07 pascoe Exp $	*/

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

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

#include <arm/xscale/pxa2x0reg.h>
#include <arm/xscale/pxa2x0var.h>
#include <arm/xscale/pxa2x0_i2c.h>
#include <arm/xscale/pxa2x0_gpio.h>

#define I2C_RETRY_COUNT	10

int
pxa2x0_i2c_attach_sub(struct pxa2x0_i2c_softc *sc)
{
	if (bus_space_map(sc->sc_iot, PXA2X0_I2C_BASE,
	    PXA2X0_I2C_SIZE, 0, &sc->sc_ioh)) {
		sc->sc_size = 0;
		return EIO;
	}
	bus_space_barrier(sc->sc_iot, sc->sc_ioh, 0, sc->sc_size,
	    BUS_SPACE_BARRIER_READ|BUS_SPACE_BARRIER_WRITE);

	/*
	 * Configure the alternate functions.  The _IN is arbitrary, as the
	 * direction is managed by the I2C unit when comms are in progress.
	 */
	pxa2x0_gpio_set_function(117, GPIO_ALT_FN_1_IN);	/* SCL */
	pxa2x0_gpio_set_function(118, GPIO_ALT_FN_1_IN);	/* SDA */

	pxa2x0_i2c_init(sc);

	return 0;
}

int
pxa2x0_i2c_detach_sub(struct pxa2x0_i2c_softc *sc)
{
	if (sc->sc_size) {
		bus_space_unmap(sc->sc_iot, sc->sc_ioh, sc->sc_size);
		sc->sc_size = 0;
	}
	pxa2x0_clkman_config(CKEN_I2C, 0);

	return 0;
}

void
pxa2x0_i2c_init(struct pxa2x0_i2c_softc *sc)
{
	pxa2x0_i2c_open(sc);
	pxa2x0_i2c_close(sc);
}

void
pxa2x0_i2c_open(struct pxa2x0_i2c_softc *sc)
{
	/* Enable the clock to the standard I2C unit. */
	pxa2x0_clkman_config(CKEN_I2C, 1);
}

void
pxa2x0_i2c_close(struct pxa2x0_i2c_softc *sc)
{
	/* Reset and disable the standard I2C unit. */
	bus_space_write_4(sc->sc_iot, sc->sc_ioh, I2C_ICR, ICR_UR);
	bus_space_write_4(sc->sc_iot, sc->sc_ioh, I2C_ISAR, 0);
	delay(1);
	pxa2x0_clkman_config(CKEN_I2C, 0);
}

int
pxa2x0_i2c_read(struct pxa2x0_i2c_softc *sc, u_char slave, u_char *valuep)
{
	u_int32_t rv;
	int timeout;
	int tries = I2C_RETRY_COUNT;
	bus_space_tag_t iot = sc->sc_iot;
	bus_space_handle_t ioh = sc->sc_ioh;

retry:
	bus_space_write_4(iot, ioh, I2C_ICR, ICR_UR);
	bus_space_write_4(iot, ioh, I2C_ISAR, 0x00);
	bus_space_write_4(iot, ioh, I2C_ISR, ISR_ITE | ISR_IRF);
	delay(1);
	bus_space_write_4(iot, ioh, I2C_ICR, ICR_IUE | ICR_SCLE);

	/* Write slave device address. */
	bus_space_write_4(iot, ioh, I2C_IDBR, (slave<<1) | 0x1);
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv | ICR_START);
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv & ~ICR_STOP);
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv | ICR_TB);

	timeout = 10000;
	while ((bus_space_read_4(iot, ioh, I2C_ISR) & ISR_ITE) == 0) {
		if (timeout-- == 0)
			goto err;
		delay(1);
	}

	bus_space_write_4(iot, ioh, I2C_ISR, ISR_ITE);

	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv & ~ICR_START);

	/* Read data value. */
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv |
	    (ICR_STOP | ICR_ACKNAK));
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv | ICR_TB);

	timeout = 10000;
	while ((bus_space_read_4(iot, ioh, I2C_ISR) & ISR_IRF) == 0) {
		if (timeout-- == 0)
			goto err;
		delay(1);
	}

	bus_space_write_4(iot, ioh, I2C_ISR, ISR_IRF);

	rv = bus_space_read_4(iot, ioh, I2C_IDBR);
	*valuep = (u_char)rv;
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv &
	    ~(ICR_STOP | ICR_ACKNAK));

	return (0);
err:
	if (tries-- >= 0)
		goto retry;

	bus_space_write_4(iot, ioh, I2C_ICR, ICR_UR);
	bus_space_write_4(iot, ioh, I2C_ISAR, 0x00);
	bus_space_write_4(iot, ioh, I2C_ISR, ISR_ITE | ISR_IRF);
	bus_space_write_4(iot, ioh, I2C_ICR, ICR_IUE | ICR_SCLE);

	return (-EIO);
}

int
pxa2x0_i2c_write(struct pxa2x0_i2c_softc *sc, u_char slave, u_char value)
{
	u_int32_t rv;
	int timeout;
	int tries = I2C_RETRY_COUNT;
	bus_space_tag_t iot = sc->sc_iot;
	bus_space_handle_t ioh = sc->sc_ioh;

retry:
	bus_space_write_4(iot, ioh, I2C_ICR, ICR_UR);
	bus_space_write_4(iot, ioh, I2C_ISAR, 0x00);
	bus_space_write_4(iot, ioh, I2C_ISR, ISR_ITE);
	delay(1);
	bus_space_write_4(iot, ioh, I2C_ICR, ICR_IUE | ICR_SCLE);

	/* Write slave device address. */
	bus_space_write_4(iot, ioh, I2C_IDBR, (slave<<1));
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv | ICR_START);
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv & ~ICR_STOP);
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv | ICR_TB);

	timeout = 10000;
	while ((bus_space_read_4(iot, ioh, I2C_ISR) & ISR_ITE) == 0) {
		if (timeout-- == 0)
			goto err;
		delay(1);
	}
	if ((bus_space_read_4(iot, ioh, I2C_ISR) & ISR_ACKNAK) != 0)
		goto err;

	bus_space_write_4(iot, ioh, I2C_ISR, ISR_ITE);

	/* Write data. */
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv & ~ICR_START);
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv | ICR_STOP);
	bus_space_write_4(iot, ioh, I2C_IDBR, value);
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv | ICR_TB);

	timeout = 10000;
	while ((bus_space_read_4(iot, ioh, I2C_ISR) & ISR_ITE) == 0) {
		if (timeout-- == 0)
			goto err;
		delay(1);
	}
	if ((bus_space_read_4(iot, ioh, I2C_ISR) & ISR_ACKNAK) != 0)
		goto err;

	bus_space_write_4(iot, ioh, I2C_ISR, ISR_ITE);

	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv & ~ICR_STOP);

	return (0);
err:
	if (tries-- >= 0)
		goto retry;

	bus_space_write_4(iot, ioh, I2C_ICR, ICR_UR);
	bus_space_write_4(iot, ioh, I2C_ISAR, 0x00);
	bus_space_write_4(iot, ioh, I2C_ISR, ISR_ITE);
	bus_space_write_4(iot, ioh, I2C_ICR, ICR_IUE | ICR_SCLE);

	return (-EIO);
}

int
pxa2x0_i2c_write_2(struct pxa2x0_i2c_softc *sc, u_char slave, u_short value)
{
	u_int32_t rv;
	int timeout;
	int tries = I2C_RETRY_COUNT;
	bus_space_tag_t iot = sc->sc_iot;
	bus_space_handle_t ioh = sc->sc_ioh;

retry:
	bus_space_write_4(iot, ioh, I2C_ICR, ICR_UR);
	bus_space_write_4(iot, ioh, I2C_ISAR, 0x00);
	bus_space_write_4(iot, ioh, I2C_ISR, ISR_ITE);
	delay(1);
	bus_space_write_4(iot, ioh, I2C_ICR, ICR_IUE | ICR_SCLE);

	/* Write slave device address. */
	bus_space_write_4(iot, ioh, I2C_IDBR, (slave<<1));
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv | ICR_START);
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv & ~ICR_STOP);
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv | ICR_TB);

	timeout = 10000;
	while ((bus_space_read_4(iot, ioh, I2C_ISR) & ISR_ITE) == 0) {
		if (timeout-- == 0)
			goto err;
		delay(1);
	}
	if ((bus_space_read_4(iot, ioh, I2C_ISR) & ISR_ACKNAK) != 0)
		goto err;

	bus_space_write_4(iot, ioh, I2C_ISR, ISR_ITE);

	/* Write upper 8 bits of data. */
	bus_space_write_4(iot, ioh, I2C_IDBR, (value >> 8) & 0xff);
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv & ~ICR_START);
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv & ~ICR_STOP);
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv | ICR_TB);

	timeout = 10000;
	while ((bus_space_read_4(iot, ioh, I2C_ISR) & ISR_ITE) == 0) {
		if (timeout-- == 0)
			goto err;
		delay(1);
	}
	if ((bus_space_read_4(iot, ioh, I2C_ISR) & ISR_ACKNAK) != 0)
		goto err;

	bus_space_write_4(iot, ioh, I2C_ISR, ISR_ITE);

	/* Write lower 8 bits of data. */
	bus_space_write_4(iot, ioh, I2C_IDBR, value & 0xff);
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv & ~ICR_START);
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv | ICR_STOP);
	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv | ICR_TB);

	timeout = 10000;
	while ((bus_space_read_4(iot, ioh, I2C_ISR) & ISR_ITE) == 0) {
		if (timeout-- == 0)
			goto err;
		delay(1);
	}
	if ((bus_space_read_4(iot, ioh, I2C_ISR) & ISR_ACKNAK) != 0)
		goto err;

	bus_space_write_4(iot, ioh, I2C_ISR, ISR_ITE);

	rv = bus_space_read_4(iot, ioh, I2C_ICR);
	bus_space_write_4(iot, ioh, I2C_ICR, rv & ~ICR_STOP);

	return (0);
err:
	if (tries-- >= 0)
		goto retry;

	bus_space_write_4(iot, ioh, I2C_ICR, ICR_UR);
	bus_space_write_4(iot, ioh, I2C_ISAR, 0x00);
	bus_space_write_4(iot, ioh, I2C_ISR, ISR_ITE);
	bus_space_write_4(iot, ioh, I2C_ICR, ICR_IUE | ICR_SCLE);

	return (-EIO);
}


code:
/*	$OpenBSD: pxa2x0_i2c.h,v 1.2 2005/05/26 03:52:07 pascoe Exp $	*/

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

#ifndef _PXA2X0_I2C_H_
#define _PXA2X0_I2C_H_

#include <machine/bus.h>

struct pxa2x0_i2c_softc {
	struct device sc_dev;
	bus_space_tag_t sc_iot;
	bus_space_handle_t sc_ioh;
	bus_size_t sc_size;
};

int	pxa2x0_i2c_attach_sub(struct pxa2x0_i2c_softc *);
int	pxa2x0_i2c_detach_sub(struct pxa2x0_i2c_softc *);
void	pxa2x0_i2c_init(struct pxa2x0_i2c_softc *);
void	pxa2x0_i2c_open(struct pxa2x0_i2c_softc *);
void	pxa2x0_i2c_close(struct pxa2x0_i2c_softc *);
int	pxa2x0_i2c_read(struct pxa2x0_i2c_softc *sc, u_char, u_char *);
int	pxa2x0_i2c_write(struct pxa2x0_i2c_softc *, u_char, u_char);
int	pxa2x0_i2c_write_2(struct pxa2x0_i2c_softc *, u_char, u_short);

#endif


code:
/*	$OpenBSD: pxa2x0_i2s.c,v 1.8 2014/07/12 18:44:41 tedu Exp $	*/

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

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

#include <arm/xscale/pxa2x0reg.h>
#include <arm/xscale/pxa2x0var.h>
#include <arm/xscale/pxa2x0_gpio.h>
#include <arm/xscale/pxa2x0_i2s.h>
#include <arm/xscale/pxa2x0_dmac.h>

struct pxa2x0_i2s_dma {
	struct pxa2x0_i2s_dma *next;
	caddr_t addr;
	size_t size;
	bus_dmamap_t map;
	bus_dma_segment_t seg;
};

void
pxa2x0_i2s_init(struct pxa2x0_i2s_softc *sc)
{
	bus_space_write_4(sc->sc_iot, sc->sc_ioh, I2S_SACR0, SACR0_RST);
	delay(100);
	bus_space_write_4(sc->sc_iot, sc->sc_ioh, I2S_SACR0,
	    SACR0_BCKD | SACR0_SET_TFTH(7) | SACR0_SET_RFTH(7));
	bus_space_write_4(sc->sc_iot, sc->sc_ioh, I2S_SACR1, 0);
	bus_space_write_4(sc->sc_iot, sc->sc_ioh, I2S_SADR, 0);
	bus_space_write_4(sc->sc_iot, sc->sc_ioh, I2S_SADIV, sc->sc_sadiv);
	bus_space_write_4(sc->sc_iot, sc->sc_ioh, I2S_SACR0,
		SACR0_BCKD | SACR0_SET_TFTH(7) | SACR0_SET_RFTH(7) | SACR0_ENB);
}

int
pxa2x0_i2s_attach_sub(struct pxa2x0_i2s_softc *sc)
{
	if (bus_space_map(sc->sc_iot, PXA2X0_I2S_BASE, PXA2X0_I2S_SIZE, 0,
	    &sc->sc_ioh)) {
		sc->sc_size = 0;
		return 1;
	}
	sc->sc_sadiv = SADIV_3_058MHz;

	bus_space_barrier(sc->sc_iot, sc->sc_ioh, 0, sc->sc_size,
	    BUS_SPACE_BARRIER_READ|BUS_SPACE_BARRIER_WRITE);

	pxa2x0_gpio_set_function(28, GPIO_ALT_FN_1_OUT);  /* I2S_BITCLK */
	pxa2x0_gpio_set_function(113, GPIO_ALT_FN_1_OUT); /* I2S_SYSCLK */
	pxa2x0_gpio_set_function(31, GPIO_ALT_FN_1_OUT);  /* I2S_SYNC */
	pxa2x0_gpio_set_function(30, GPIO_ALT_FN_1_OUT);  /* I2S_SDATA_OUT */
	pxa2x0_gpio_set_function(29, GPIO_ALT_FN_2_IN);   /* I2S_SDATA_IN */

	pxa2x0_i2s_init(sc);

	return 0;
}

void pxa2x0_i2s_open(struct pxa2x0_i2s_softc *sc)
{
	sc->sc_open++;
	pxa2x0_clkman_config(CKEN_I2S, 1);
}

void pxa2x0_i2s_close(struct pxa2x0_i2s_softc *sc)
{
	pxa2x0_clkman_config(CKEN_I2S, 0);
	sc->sc_open--;
}

int
pxa2x0_i2s_detach_sub(struct pxa2x0_i2s_softc *sc)
{
	if (sc->sc_size > 0) {
		bus_space_unmap(sc->sc_iot, sc->sc_ioh, sc->sc_size);
		sc->sc_size = 0;
	}
	pxa2x0_clkman_config(CKEN_I2S, 0);

	return (0);
}

void pxa2x0_i2s_write(struct pxa2x0_i2s_softc *sc, u_int32_t data)
{
	if (! sc->sc_open)
		return;

	/* Clear intr and underrun bit if set. */
	if (bus_space_read_4(sc->sc_iot, sc->sc_ioh, I2S_SASR0) & SASR0_TUR)
		bus_space_write_4(sc->sc_iot, sc->sc_ioh, I2S_SAICR, SAICR_TUR);

	/* Wait for transmit fifo to have space. */
	while ((bus_space_read_4(sc->sc_iot, sc->sc_ioh, I2S_SASR0) & SASR0_TNF)
	     == 0)
		;	/* nothing */

	/* Queue data */
	bus_space_write_4(sc->sc_iot, sc->sc_ioh, I2S_SADR, data);
}

void
pxa2x0_i2s_setspeed(struct pxa2x0_i2s_softc *sc, u_long *argp)
{
	/*
	 * The available speeds are in the following table.
	 * Keep the speeds in increasing order.
	 */
	typedef struct {
		int speed;
		int div;
	} speed_struct;
	u_long arg = *argp;

	static speed_struct speed_table[] = {
		{8000,	SADIV_513_25kHz},
		{11025,	SADIV_702_75kHz},
		{16000,	SADIV_1_026MHz},
		{22050,	SADIV_1_405MHz},
		{44100,	SADIV_2_836MHz},
		{48000,	SADIV_3_058MHz},
	};

	int i, n, selected = -1;

	n = sizeof(speed_table) / sizeof(speed_struct);

	if (arg < speed_table[0].speed)
		selected = 0;
	if (arg > speed_table[n - 1].speed)
		selected = n - 1;

	for (i = 1; selected == -1 && i < n; i++) {
		if (speed_table[i].speed == arg)
			selected = i;
		else if (speed_table[i].speed > arg) {
			int diff1, diff2;

			diff1 = arg - speed_table[i - 1].speed;
			diff2 = speed_table[i].speed - arg;
			if (diff1 < diff2)
				selected = i - 1;
			else
				selected = i;
		}
	}

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

	*argp = speed_table[selected].speed;

	sc->sc_sadiv = speed_table[selected].div;
	bus_space_write_4(sc->sc_iot, sc->sc_ioh, I2S_SADIV, sc->sc_sadiv);
}

void *
pxa2x0_i2s_allocm(void *hdl, int direction, size_t size, int type, int flags)
{
	struct device *sc_dev = hdl;
	struct pxa2x0_i2s_softc *sc =
	    (struct pxa2x0_i2s_softc *)((struct device *)hdl + 1);
	struct pxa2x0_i2s_dma *p;
	int error;
	int rseg;

	p = malloc(sizeof(*p), type, flags);
	if (!p)
		return 0;

	p->size = size;
	if ((error = bus_dmamem_alloc(sc->sc_dmat, size, NBPG, 0, &p->seg, 1,
	    &rseg, BUS_DMA_NOWAIT)) != 0) {
		printf("%s: unable to allocate dma, error = %d\n",
		    sc_dev->dv_xname, error);
		goto fail_alloc;
	}

	if ((error = bus_dmamem_map(sc->sc_dmat, &p->seg, rseg, size, &p->addr,
	    BUS_DMA_NOWAIT | BUS_DMA_COHERENT)) != 0) {
		printf("%s: unable to map dma, error = %d\n",
		    sc_dev->dv_xname, error);
		goto fail_map;
	}

	if ((error = bus_dmamap_create(sc->sc_dmat, size, 1, size, 0,
	    BUS_DMA_NOWAIT, &p->map)) != 0) {
		printf("%s: unable to create dma map, error = %d\n",
		    sc_dev->dv_xname, error);
		goto fail_create;
	}

	if ((error = bus_dmamap_load(sc->sc_dmat, p->map, p->addr, size, NULL,
	    BUS_DMA_NOWAIT)) != 0) {
		printf("%s: unable to load dma map, error = %d\n",
		    sc_dev->dv_xname, error);
		goto fail_load;
	}

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

	return p->addr;

fail_load:
	bus_dmamap_destroy(sc->sc_dmat, p->map);
fail_create:
	bus_dmamem_unmap(sc->sc_dmat, p->addr, size);
fail_map:
	bus_dmamem_free(sc->sc_dmat, &p->seg, 1);
fail_alloc:
	free(p, type, 0);
	return 0;
}

void
pxa2x0_i2s_freem(void *hdl, void *ptr, int type)
{
	struct pxa2x0_i2s_softc *sc =
	    (struct pxa2x0_i2s_softc *)((struct device *)hdl + 1);
	struct pxa2x0_i2s_dma **pp, *p;

	for (pp = &(sc->sc_dmas); (p = *pp) != NULL; pp = &p->next)
		if (p->addr == ptr) {
			bus_dmamap_unload(sc->sc_dmat, p->map);
			bus_dmamap_destroy(sc->sc_dmat, p->map);
			bus_dmamem_unmap(sc->sc_dmat, p->addr, p->size);
			bus_dmamem_free(sc->sc_dmat, &p->seg, 1);

			*pp = p->next;
			free(p, type, 0);
			return;
		}

	panic("pxa2x0_i2s_freem: trying to free unallocated memory");
}

paddr_t
pxa2x0_i2s_mappage(void *hdl, void *mem, off_t off, int prot)
{
	struct pxa2x0_i2s_softc *sc =
	    (struct pxa2x0_i2s_softc *)((struct device *)hdl + 1);
	struct pxa2x0_i2s_dma *p;

	if (off < 0)
		return -1;

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

	if (off > p->size)
		return -1;

	return bus_dmamem_mmap(sc->sc_dmat, &p->seg, 1, off, prot,
	    BUS_DMA_WAITOK);
}

int
pxa2x0_i2s_round_blocksize(void *hdl, int bs)
{
	/* Enforce individual DMA block size limit */
	if (bs > DCMD_LENGTH_MASK)
		return (DCMD_LENGTH_MASK & ~0x03);

	return (bs + 0x03) & ~0x03;	/* 32-bit multiples */
}

size_t
pxa2x0_i2s_round_buffersize(void *hdl, int direction, size_t bufsize)
{
	return bufsize;
}

int
pxa2x0_i2s_start_output(struct pxa2x0_i2s_softc *sc, void *block, int bsize,
    void (*intr)(void *), void *intrarg)
{
	struct pxa2x0_i2s_dma *p;
	int offset;

	/* Find mapping which contains block completely */
	for (p = sc->sc_dmas; p && (((caddr_t)block < p->addr) ||
	    ((caddr_t)block + bsize > p->addr + p->size)); p = p->next)
		;	/* Nothing */

	if (!p) {
		printf("pxa2x0_i2s_start_output: request with bad start "
		    "address: %p, size: %d)\n", block, bsize);
		return ENXIO;
	}

	/* Offset into block to use in mapped block */
	offset = (caddr_t)block - p->addr;

	/* Start DMA */
	pxa2x0_dma_to_fifo(3, 1, 0x40400080, 4, 32,
	    p->map->dm_segs[0].ds_addr + offset, bsize, intr, intrarg);

	return 0;
}

int
pxa2x0_i2s_start_input(struct pxa2x0_i2s_softc *sc, void *block, int bsize,
    void (*intr)(void *), void *intrarg)
{
	struct pxa2x0_i2s_dma *p;
	int offset;

	/* Find mapping which contains block completely */
	for (p = sc->sc_dmas; p && (((caddr_t)block < p->addr) ||
	    ((caddr_t)block + bsize > p->addr + p->size)); p = p->next)
		;	/* Nothing */

	if (!p) {
		printf("pxa2x0_i2s_start_input: request with bad start "
		    "address: %p, size: %d)\n", block, bsize);
		return ENXIO;
	}

	/* Offset into block to use in mapped block */
	offset = (caddr_t)block - p->addr;

	/* Start DMA */
	pxa2x0_dma_from_fifo(2, 2, 0x40400080, 4, 32,
	    p->map->dm_segs[0].ds_addr + offset, bsize, intr, intrarg);

	return 0;
}


code:
/*	$OpenBSD: pxa2x0_i2s.h,v 1.3 2006/04/04 11:45:40 pascoe Exp $	*/

/*
 * Copyright (c) 2005 Uwe Stuehler <uwe@bsdx.de>
 *
 * 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.
 */

#ifndef _PXA2X0_I2S_H_
#define _PXA2X0_I2S_H_

#include <machine/bus.h>

struct pxa2x0_i2s_dma;

struct pxa2x0_i2s_softc {
	bus_space_tag_t sc_iot;
	bus_space_handle_t sc_ioh;
	bus_size_t sc_size;
	bus_dma_tag_t sc_dmat;

	int sc_open;
	u_int32_t sc_sadiv;

	struct pxa2x0_i2s_dma *sc_dmas;
};

void	pxa2x0_i2s_init(struct pxa2x0_i2s_softc *sc);
int	pxa2x0_i2s_attach_sub(struct pxa2x0_i2s_softc *);
int	pxa2x0_i2s_detach_sub(struct pxa2x0_i2s_softc *);
void	pxa2x0_i2s_open(struct pxa2x0_i2s_softc *);
void	pxa2x0_i2s_close(struct pxa2x0_i2s_softc *);
void	pxa2x0_i2s_write(struct pxa2x0_i2s_softc *, u_int32_t);

void	pxa2x0_i2s_setspeed(struct pxa2x0_i2s_softc *, u_long *);

void *	pxa2x0_i2s_allocm(void *, int, size_t, int, int);
void	pxa2x0_i2s_freem(void  *, void *, int);
paddr_t	pxa2x0_i2s_mappage(void *, void *, off_t, int);
int	pxa2x0_i2s_round_blocksize(void *, int);
size_t	pxa2x0_i2s_round_buffersize(void *, int, size_t);

int	pxa2x0_i2s_start_output(struct pxa2x0_i2s_softc *, void *, int,
	    void (*)(void *), void *);
int	pxa2x0_i2s_start_input(struct pxa2x0_i2s_softc *, void *, int,
	    void (*)(void *), void *);

#endif


code:
/*	$OpenBSD: pxa2x0_intr.c,v 1.26 2014/07/12 18:44:41 tedu Exp $ */
/*	$NetBSD: pxa2x0_intr.c,v 1.5 2003/07/15 00:24:55 lukem Exp $	*/

/*
 * Copyright (c) 2002  Genetec Corporation.  All rights reserved.
 * Written by Hiroyuki Bessho for Genetec Corporation.
 *
 * 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 for the NetBSD Project by
 *	Genetec Corporation.
 * 4. The name of Genetec Corporation may not be used to endorse or
 *    promote products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY GENETEC CORPORATION ``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 GENETEC CORPORATION
 * 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.
 */

/*
 * IRQ handler for the Intel PXA2X0 processor.
 * It has integrated interrupt controller.
 */

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

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

#include <arm/xscale/pxa2x0reg.h>
#include <arm/xscale/pxa2x0var.h>
#include <arm/xscale/pxa2x0_intr.h>
#include <arm/sa11x0/sa11x0_var.h>

/*
 * INTC autoconf glue
 */
int	pxaintc_match(struct device *, void *, void *);
void	pxaintc_attach(struct device *, struct device *, void *);

#ifdef __NetBSD__
CFATTACH_DECL(pxaintc, sizeof(struct device),
    pxaintc_match, pxaintc_attach, NULL, NULL);
#else
struct cfattach pxaintc_ca = {
        sizeof(struct device), pxaintc_match, pxaintc_attach
};

struct cfdriver pxaintc_cd = {
	NULL, "pxaintc", DV_DULL
};

#endif

static int pxaintc_attached;

int pxa2x0_stray_interrupt(void *);
void pxa2x0_init_interrupt_masks(void);

/*
 * interrupt dispatch table.
 */
#if 1
#define MULTIPLE_HANDLERS_ON_ONE_IRQ
#endif
#ifdef MULTIPLE_HANDLERS_ON_ONE_IRQ
struct intrhand {
	TAILQ_ENTRY(intrhand)	ih_list;		/* link on intrq list */
	int 			(*ih_func)(void *);	/* handler */
	void 			*ih_arg;		/* arg for handler */
	char 			*ih_name;
	struct evcount  	ih_count;
	int 			ih_irq;
	int 			ih_level;
};
#endif

static struct intrhandler{
#ifdef MULTIPLE_HANDLERS_ON_ONE_IRQ
	TAILQ_HEAD(,intrhand) list;
#else
	pxa2x0_irq_handler_t func;
	char *name;
	void *arg;		/* NULL for stackframe */
	int ih_irq;
	struct evcount ih_count;
#endif
} handler[ICU_LEN];

volatile int softint_pending;
volatile int current_spl_level;
/* interrupt masks for each level */
int pxa2x0_imask[NIPL];
static int extirq_level[ICU_LEN];

int
pxaintc_match(struct device *parent, void *cf, void *aux)
{
	struct pxaip_attach_args *pxa = aux;

	if (pxaintc_attached || pxa->pxa_addr != PXA2X0_INTCTL_BASE)
		return (0);

	return (1);
}

void
pxaintc_attach(struct device *parent, struct device *self, void *args)
{
	int i;

	pxaintc_attached = 1;

	printf(": Interrupt Controller\n");

#define	SAIPIC_ICCR	0x14

	write_icu(SAIPIC_ICCR, 1);
	write_icu(SAIPIC_MR, 0);

	for(i = 0; i < sizeof handler / sizeof handler[0]; ++i){
#ifdef MULTIPLE_HANDLERS_ON_ONE_IRQ
		TAILQ_INIT(&handler[i].list);
		extirq_level[i] = IPL_NONE;
#else
		handler[i].name = "stray";
		handler[i].func = pxa2x0_stray_interrupt;
		handler[i].arg = (void *)(u_int32_t) i;
		extirq_level[i] = IPL_HIGH;
#endif

	}

	pxa2x0_init_interrupt_masks();

	_splraise(IPL_HIGH);
	enable_interrupts(I32_bit);
}

/*
 * Invoked very early on from the board-specific initarm(), in order to
 * inform us the virtual address of the interrupt controller's registers.
 */
vaddr_t pxaic_base;
void
pxa2x0_intr_bootstrap(vaddr_t addr)
{

	pxaic_base = addr;
}

/*
 * PXA27x has MSL interface and SSP3 interrupts [0,1], USIM interface
 * and SSP2 interrupts [15,16]. PXA255 has bits [0..6,15] reserved and
 * bit [16] network SSP interrupt.  We don't need any of those, so we
 * map software interrupts to bits [0..1,15..16].  Sadly there are no
 * four contiguous bits safe enough to use on both processors.
 */
#define SI_TO_IRQBIT(si)  ((si) < 2 ? 1U<<(si) : 1U<<(15-2+(si)))

/*
 * Map a software interrupt queue to an interrupt priority level.
 */
static const int si_to_ipl[SI_NQUEUES] = {
	IPL_SOFT,		/* SI_SOFT */
	IPL_SOFTCLOCK,		/* SI_SOFTCLOCK */
	IPL_SOFTNET,		/* SI_SOFTNET */
	IPL_SOFTTTY,		/* SI_SOFTTTY */
};

/*
 * called from irq_entry.
 */
void
pxa2x0_irq_handler(void *arg)
{
	struct clockframe *frame = arg;
	uint32_t irqbits;
	int irqno;
	int saved_spl_level;
#ifdef MULTIPLE_HANDLERS_ON_ONE_IRQ
	struct intrhand *ih;
#endif

	saved_spl_level = current_spl_level;

	/* get pending IRQs */
	irqbits = read_icu(SAIPIC_IP);

	while ((irqno = find_first_bit(irqbits)) >= 0) {
		/* XXX: Should we handle IRQs in priority order? */

		/* raise spl to stop interrupts of lower priorities */
		if (saved_spl_level < extirq_level[irqno])
			pxa2x0_setipl(extirq_level[irqno]);

		/* Enable interrupt */
		enable_interrupts(I32_bit);

#ifndef MULTIPLE_HANDLERS_ON_ONE_IRQ
		(* handler[irqno].func)(
			handler[irqno].arg == 0
			? frame : handler[irqno].arg );
		handler[irqno].ih_count.ec_count++;
#else
		TAILQ_FOREACH(ih, &handler[irqno].list, ih_list) {
			if ((ih->ih_func)( ih->ih_arg == 0
			    ? frame : ih->ih_arg))
				ih->ih_count.ec_count++;
		}
#endif

		/* Disable interrupt */
		disable_interrupts(I32_bit);

		irqbits &= ~(1<<irqno);
	}

	/* restore spl to that was when this interrupt happen */
	pxa2x0_setipl(saved_spl_level);

	if(softint_pending & pxa2x0_imask[current_spl_level])
		pxa2x0_do_pending();
}

int
pxa2x0_stray_interrupt(void *cookie)
{
	int irqno = (int)cookie;
	printf("stray interrupt %d\n", irqno);

	if (PXA2X0_IRQ_MIN <= irqno && irqno < ICU_LEN){
		int save = disable_interrupts(I32_bit);
		write_icu(SAIPIC_MR,
		    read_icu(SAIPIC_MR) & ~(1U<<irqno));
		restore_interrupts(save);
	}

	return 0;
}

/*
 * Interrupt Mask Handling
 */

#ifdef MULTIPLE_HANDLERS_ON_ONE_IRQ
void pxa2x0_update_intr_masks(void);

void
pxa2x0_update_intr_masks()
#else
void pxa2x0_update_intr_masks(int irqno, int level);

void
pxa2x0_update_intr_masks(int irqno, int irqlevel)
#endif
{
	int psw;

#ifdef MULTIPLE_HANDLERS_ON_ONE_IRQ
	int irq;
#ifdef DEBUG
	int level;
#endif
	struct intrhand *ih;
	psw = disable_interrupts(I32_bit);

	/* First figure out which levels each IRQ uses. */
	for (irq = 0; irq < ICU_LEN; irq++) {
		int i;
		int max = IPL_NONE;
		int min = IPL_HIGH;
		TAILQ_FOREACH(ih, &handler[irq].list, ih_list) {
			if (ih->ih_level > max)
				max = ih->ih_level;

			if (ih->ih_level < min)
				min = ih->ih_level;
		}

		extirq_level[irq] = max;

		if (min == IPL_HIGH)
			min = IPL_NONE;

		/* Enable interrupt at lower level */
		for(i = 0; i < min; ++i)
			pxa2x0_imask[i] |= (1 << irq);

		/* Disable interrupt at upper level */
		for( ; i < NIPL; ++i)
			pxa2x0_imask[i] &= ~(1 << irq);
	}

	/* fixup */
	pxa2x0_imask[IPL_NONE] |=
	    SI_TO_IRQBIT(SI_SOFT) |
	    SI_TO_IRQBIT(SI_SOFTCLOCK) |
	    SI_TO_IRQBIT(SI_SOFTNET) |
	    SI_TO_IRQBIT(SI_SOFTTTY);
	pxa2x0_imask[IPL_SOFT] |=
	    SI_TO_IRQBIT(SI_SOFTCLOCK) |
	    SI_TO_IRQBIT(SI_SOFTNET) |
	    SI_TO_IRQBIT(SI_SOFTTTY);
	pxa2x0_imask[IPL_SOFTCLOCK] |=
	    SI_TO_IRQBIT(SI_SOFTNET) |
	    SI_TO_IRQBIT(SI_SOFTTTY);
	pxa2x0_imask[IPL_SOFTNET] |=
	    SI_TO_IRQBIT(SI_SOFTTTY);
	pxa2x0_imask[IPL_SOFTTTY] |=
	    0;
#else
	int level; /* debug */
	int mask = 1U<<irqno;
	int i;
	psw = disable_interrupts(I32_bit);

	for(i = 0; i < irqlevel; ++i)
		pxa2x0_imask[i] |= mask; /* Enable interrupt at lower level */

	for( ; i < NIPL; ++i)
		pxa2x0_imask[i] &= ~mask; /* Disable interrupt at upper level */
#endif

	/*
	 * Enforce a hierarchy that gives "slow" device (or devices with
	 * limited input buffer space/"real-time" requirements) a better
	 * chance at not dropping data.
	 */
	pxa2x0_imask[IPL_BIO] &= pxa2x0_imask[IPL_SOFTNET];
	pxa2x0_imask[IPL_NET] &= pxa2x0_imask[IPL_BIO];
	pxa2x0_imask[IPL_SOFTTTY] &= pxa2x0_imask[IPL_NET];
	pxa2x0_imask[IPL_TTY] &= pxa2x0_imask[IPL_SOFTTTY];

	/*
	 * splvm() blocks all interrupts that use the kernel memory
	 * allocation facilities.
	 */
	pxa2x0_imask[IPL_VM] &= pxa2x0_imask[IPL_TTY];

	/*
	 * Audio devices are not allowed to perform memory allocation
	 * in their interrupt routines, and they have fairly "real-time"
	 * requirements, so give them a high interrupt priority.
	 */
	pxa2x0_imask[IPL_AUDIO] &= pxa2x0_imask[IPL_VM];

	/*
	 * splclock() must block anything that uses the scheduler.
	 */
	pxa2x0_imask[IPL_CLOCK] &= pxa2x0_imask[IPL_AUDIO];

	/*
	 * splhigh() must block "everything".
	 */
	pxa2x0_imask[IPL_HIGH] &= pxa2x0_imask[IPL_STATCLOCK];

#ifdef DEBUG
	for (level = IPL_NONE; level < NIPL; level++) {
		printf("imask %d, %x\n", level, pxa2x0_imask[level]);
	}
#endif

#ifdef MULTIPLE_HANDLERS_ON_ONE_IRQ
	for (irq = 0; irq < ICU_LEN; irq++) {
		int max_irq = IPL_NONE;
		TAILQ_FOREACH(ih, &handler[irq].list, ih_list) {
			if (ih->ih_level > max_irq)
				max_irq  = ih->ih_level;
		}
		extirq_level[irq] = max_irq;
	}
#endif

	write_icu(SAIPIC_MR, pxa2x0_imask[current_spl_level]);

	restore_interrupts(psw);
}

void
pxa2x0_init_interrupt_masks(void)
{

	memset(pxa2x0_imask, 0, sizeof(pxa2x0_imask));

	/*
	 * IPL_NONE has soft interrupts enabled only, at least until
	 * hardware handlers are installed.
	 */
	pxa2x0_imask[IPL_NONE] =
	    SI_TO_IRQBIT(SI_SOFT) |
	    SI_TO_IRQBIT(SI_SOFTCLOCK) |
	    SI_TO_IRQBIT(SI_SOFTNET) |
	    SI_TO_IRQBIT(SI_SOFTTTY);

	/*
	 * Initialize the soft interrupt masks to block themselves.
	 */
	pxa2x0_imask[IPL_SOFT] = ~SI_TO_IRQBIT(SI_SOFT);
	pxa2x0_imask[IPL_SOFTCLOCK] = ~SI_TO_IRQBIT(SI_SOFTCLOCK);
	pxa2x0_imask[IPL_SOFTNET] = ~SI_TO_IRQBIT(SI_SOFTNET);
	pxa2x0_imask[IPL_SOFTTTY] = ~SI_TO_IRQBIT(SI_SOFTTTY);

	pxa2x0_imask[IPL_SOFT] &= pxa2x0_imask[IPL_NONE];

	/*
	 * splsoftclock() is the only interface that users of the
	 * generic software interrupt facility have to block their
	 * soft intrs, so splsoftclock() must also block IPL_SOFT.
	 */
	pxa2x0_imask[IPL_SOFTCLOCK] &= pxa2x0_imask[IPL_SOFT];

	/*
	 * splsoftnet() must also block splsoftclock(), since we don't
	 * want timer-driven network events to occur while we're
	 * processing incoming packets.
	 */
	pxa2x0_imask[IPL_SOFTNET] &= pxa2x0_imask[IPL_SOFTCLOCK];
}

void
pxa2x0_do_pending(void)
{
	static __cpu_simple_lock_t processing = __SIMPLELOCK_UNLOCKED;
	int oldirqstate, spl_save;

	if (__cpu_simple_lock_try(&processing) == 0)
		return;

	spl_save = current_spl_level;

	oldirqstate = disable_interrupts(I32_bit);

#if 1
#define	DO_SOFTINT(si,ipl)						\
	if ((softint_pending & pxa2x0_imask[current_spl_level]) & 	\
	    SI_TO_IRQBIT(si)) {		\
		softint_pending &= ~SI_TO_IRQBIT(si);			\
		if (current_spl_level < ipl)				\
			pxa2x0_setipl(ipl);				\
		restore_interrupts(oldirqstate);			\
		softintr_dispatch(si);					\
		oldirqstate = disable_interrupts(I32_bit);		\
		pxa2x0_setipl(spl_save);				\
	}

	do {
		DO_SOFTINT(SI_SOFTTTY,IPL_SOFTTTY);
		DO_SOFTINT(SI_SOFTNET, IPL_SOFTNET);
		DO_SOFTINT(SI_SOFTCLOCK, IPL_SOFTCLOCK);
		DO_SOFTINT(SI_SOFT, IPL_SOFT);
	} while( softint_pending & pxa2x0_imask[current_spl_level] );
#else
	while( (si = find_first_bit(softint_pending & pxa2x0_imask[current_spl_level])) >= 0 ){
		softint_pending &= ~SI_TO_IRQBIT(si);
		if (current_spl_level < ipl)
			pxa2x0_setipl(ipl);
		restore_interrupts(oldirqstate);
		softintr_dispatch(si);
		oldirqstate = disable_interrupts(I32_bit);
		pxa2x0_setipl(spl_save);
	}
#endif

	__cpu_simple_unlock(&processing);

	restore_interrupts(oldirqstate);
}

#undef splx
void
splx(int ipl)
{

	pxa2x0_splx(ipl);
}

#undef _splraise
int
_splraise(int ipl)
{

	return pxa2x0_splraise(ipl);
}

#undef _spllower
int
_spllower(int ipl)
{

	return pxa2x0_spllower(ipl);
}

#undef _setsoftintr
void
_setsoftintr(int si)
{

	return pxa2x0_setsoftintr(si);
}

void *
pxa2x0_intr_establish(int irqno, int level,
    int (*func)(void *), void *arg, const char *name)
{
	int psw;
#ifdef MULTIPLE_HANDLERS_ON_ONE_IRQ
	struct intrhand *ih;
#else
	struct intrhandler *ih;
#endif

	if (irqno < PXA2X0_IRQ_MIN || irqno >= ICU_LEN)
		panic("intr_establish: bogus irq number %d", irqno);

	psw = disable_interrupts(I32_bit);

#ifdef MULTIPLE_HANDLERS_ON_ONE_IRQ
	/* no point in sleeping unless someone can free memory. */
	ih = (struct intrhand *)malloc(sizeof *ih, M_DEVBUF,
	    cold ? M_NOWAIT : M_WAITOK);
	if (ih == NULL)
		panic("intr_establish: can't malloc handler info");
        ih->ih_func = func;
	ih->ih_arg = arg;
	ih->ih_level = level;
	ih->ih_irq = irqno;

	TAILQ_INSERT_TAIL(&handler[irqno].list, ih, ih_list);
#else
	ih = &handler[irqno];
	ih->arg = arg;
	ih->func = func;
	ih->name = name;
	ih->ih_irq = irqno;
	extirq_level[irqno] = level;
#endif

	if (name != NULL)
		evcount_attach(&ih->ih_count, name, &ih->ih_irq);

#ifdef MULTIPLE_HANDLERS_ON_ONE_IRQ
	pxa2x0_update_intr_masks();
#else
	pxa2x0_update_intr_masks(irqno, level);
#endif

	restore_interrupts(psw);

	return (ih);
}

void
pxa2x0_intr_disestablish(void *cookie)
{

#ifdef MULTIPLE_HANDLERS_ON_ONE_IRQ
	int psw;
	struct intrhand *ih = cookie;
	int irqno =  ih->ih_irq;

	psw = disable_interrupts(I32_bit);
	TAILQ_REMOVE(&handler[irqno].list, ih, ih_list);

	free(ih, M_DEVBUF, 0);

	pxa2x0_update_intr_masks();

	restore_interrupts(psw);
#else
	struct intrhandler *lhandler = cookie;
	int irqno;
	int psw;
	struct intrhandler *ih;
	irqno = lhandler - handler;

	if (irqno < PXA2X0_IRQ_MIN || irqno >= ICU_LEN)
		panic("intr_disestablish: bogus irq number %d", irqno);

	psw = disable_interrupts(I32_bit);

	ih = &handler[irqno];
	if (ih->name != NULL)
		evcount_detach(&ih->ih_count);

	ih->arg = (void *) irqno;
	ih->func = pxa2x0_stray_interrupt;
	ih->name = "stray";
	extirq_level[irqno] = IPL_HIGH;
	pxa2x0_update_intr_masks(irqno, IPL_HIGH);

	restore_interrupts(psw);
#endif
}

/*
 * Glue for drivers of sa11x0 compatible integrated logic.
 */
void *
sa11x0_intr_establish(sa11x0_chipset_tag_t ic, int irq, int type, int level,
    int (*ih_fun)(void *), void *ih_arg, const char *name)
{

	return pxa2x0_intr_establish(irq, level, ih_fun, ih_arg, name);
}

void
pxa2x0_setipl(int new)
{
	u_int32_t intr_mask;

	intr_mask = pxa2x0_imask[new];
	current_spl_level = new;
	write_icu( SAIPIC_MR, intr_mask );
}

void
pxa2x0_splx(int new)
{
	int psw;

	psw = disable_interrupts(I32_bit);
	pxa2x0_setipl(new);
	restore_interrupts(psw);

	/* If there are pending software interrupts, process them. */
	if (softint_pending & pxa2x0_imask[current_spl_level])
		pxa2x0_do_pending();
}

int
pxa2x0_splraise(int ipl)
{
	int	old, psw;

	old = current_spl_level;
	if( ipl > current_spl_level ){
		psw = disable_interrupts(I32_bit);
		pxa2x0_setipl(ipl);
		restore_interrupts(psw);
	}

	return (old);
}

int
pxa2x0_spllower(int ipl)
{
	int old = current_spl_level;
	int psw = disable_interrupts(I32_bit);
	pxa2x0_splx(ipl);
	restore_interrupts(psw);
	return(old);
}

void
pxa2x0_setsoftintr(int si)
{
	softint_pending |=  SI_TO_IRQBIT(si);

	/* Process unmasked pending soft interrupts. */
	if ( softint_pending & pxa2x0_imask[current_spl_level] )
		pxa2x0_do_pending();
}

const char *
pxa2x0_intr_string(void *cookie)
{
#ifdef MULTIPLE_HANDLERS_ON_ONE_IRQ
	struct intrhand *ih = cookie;
#else
	struct intrhandler *lhandler = cookie;
#endif
	static char irqstr[32];

	if (ih == NULL)
		snprintf(irqstr, sizeof irqstr, "couldn't establish interrupt");
	else
		snprintf(irqstr, sizeof irqstr, "irq %d", ih->ih_irq);

	return irqstr;
}

#ifdef DIAGNOSTIC
void
pxa2x0_splassert_check(int wantipl, const char *func)
{
	int oldipl = current_spl_level, psw;

	if (oldipl < wantipl) {
		splassert_fail(wantipl, oldipl, func);
		/*
		 * If the splassert_ctl is set to not panic, raise the ipl
		 * in a feeble attempt to reduce damage.
		 */
		psw = disable_interrupts(I32_bit);
		pxa2x0_setipl(wantipl);
		restore_interrupts(psw);
	}
}
#endif


code:
/*	$OpenBSD: pxa2x0_intr.h,v 1.14 2014/03/29 18:09:28 guenther Exp $ */
/*	$NetBSD: pxa2x0_intr.h,v 1.4 2003/07/05 06:53:08 dogcow Exp $ */

/* Derived from i80321_intr.h */

/*
 * Copyright (c) 2001, 2002 Wasabi Systems, Inc.
 * All rights reserved.
 *
 * Written by Jason R. Thorpe for Wasabi Systems, Inc.
 *
 * 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 for the NetBSD Project by
 *	Wasabi Systems, Inc.
 * 4. The name of Wasabi Systems, Inc. may not be used to endorse
 *    or promote products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef _PXA2X0_INTR_H_
#define _PXA2X0_INTR_H_

#define	ARM_IRQ_HANDLER	_C_LABEL(pxa2x0_irq_handler)

#ifndef _LOCORE

#include <arm/armreg.h>
#include <arm/cpufunc.h>
#include <arm/softintr.h>

extern vaddr_t pxaic_base;		/* Shared with pxa2x0_irq.S */
#define read_icu(offset) (*(volatile uint32_t *)(pxaic_base+(offset)))
#define write_icu(offset,value) \
 (*(volatile uint32_t *)(pxaic_base+(offset))=(value))

extern volatile int current_spl_level;
extern volatile int softint_pending;
extern int pxa2x0_imask[];
void pxa2x0_do_pending(void);

void pxa2x0_setipl(int new);
void pxa2x0_splx(int new);
int pxa2x0_splraise(int ipl);
int pxa2x0_spllower(int ipl);
void pxa2x0_setsoftintr(int si);

/*
 * An useful function for interrupt handlers.
 * XXX: This shouldn't be here.
 */
static __inline int
find_first_bit( uint32_t bits )
{
	int count;

	/* since CLZ is available only on ARMv5, this isn't portable
	 * to all ARM CPUs.  This file is for PXA2[15]0 processor.
	 */
	asm( "clz %0, %1" : "=r" (count) : "r" (bits) );
	return 31-count;
}

int	_splraise(int);
int	_spllower(int);
void	splx(int);
void	_setsoftintr(int);

/*
 * This function *MUST* be called very early on in a port's
 * initarm() function, before ANY spl*() functions are called.
 *
 * The parameter is the virtual address of the PXA2x0's Interrupt
 * Controller registers.
 */
void pxa2x0_intr_bootstrap(vaddr_t);

void pxa2x0_irq_handler(void *);
void *pxa2x0_intr_establish(int irqno, int level, int (*func)(void *),
    void *cookie, const char *name);
void pxa2x0_intr_disestablish(void *cookie);
const char *pxa2x0_intr_string(void *cookie);

#ifdef DIAGNOSTIC
/*
 * Although this function is implemented in MI code, it must be in this MD
 * header because we don't want this header to include MI includes.
 */
void splassert_fail(int, int, const char *);
extern int splassert_ctl;
void pxa2x0_splassert_check(int, const char *);
#define splassert(__wantipl) do {				\
	if (splassert_ctl > 0) {				\
		pxa2x0_splassert_check(__wantipl, __func__);	\
	}							\
} while (0)
#define splsoftassert(wantipl) splassert(wantipl)
#else
#define	splassert(wantipl)	do { /* nothing */ } while (0)
#define	splsoftassert(wantipl)	do { /* nothing */ } while (0)
#endif

#endif /* ! _LOCORE */

#endif /* _PXA2X0_INTR_H_ */


code:
/*	$OpenBSD: pxa2x0_lcd.c,v 1.26 2014/07/12 18:44:41 tedu Exp $ */
/* $NetBSD: pxa2x0_lcd.c,v 1.8 2003/10/03 07:24:05 bsh Exp $ */

/*
 * Copyright (c) 2002  Genetec Corporation.  All rights reserved.
 * Written by Hiroyuki Bessho for Genetec Corporation.
 *
 * 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 for the NetBSD Project by
 *	Genetec Corporation.
 * 4. The name of Genetec Corporation may not be used to endorse or
 *    promote products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY GENETEC CORPORATION ``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 GENETEC CORPORATION
 * 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.
 */

/*
 * Support PXA2[15]0's integrated LCD controller.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/conf.h>
#include <sys/uio.h>
#include <sys/malloc.h>
#include <sys/kernel.h>			/* for cold */

#include <uvm/uvm_extern.h>

#include <dev/cons.h>

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

#include <machine/bus.h>
#include <machine/cpu.h>
#include <arm/cpufunc.h>

#include <arm/xscale/pxa2x0var.h>
#include <arm/xscale/pxa2x0reg.h>
#include <arm/xscale/pxa2x0_lcd.h>
#include <arm/xscale/pxa2x0_gpio.h>

/*
 * Console variables. These are necessary since console is setup very early,
 * before devices get attached.
 */
struct {
	bus_space_tag_t			 iot;
	bus_space_handle_t		 ioh;
	bus_dma_tag_t			 dma_tag;
	const struct lcd_panel_geometry	*geometry;
	struct pxa2x0_lcd_screen	 scr;
} pxa2x0_lcd_console;

int	lcdintr(void *);
void	pxa2x0_lcd_geometry(bus_space_tag_t, bus_space_handle_t,
	    const struct lcd_panel_geometry *);
void	pxa2x0_lcd_initialize(bus_space_tag_t, bus_space_handle_t,
	    const struct lcd_panel_geometry *, void (*)(u_int, int));
int	pxa2x0_lcd_new_screen(struct pxa2x0_lcd_softc *,
	    struct pxa2x0_lcd_screen *, int);
void	pxa2x0_lcd_setup_console(struct pxa2x0_lcd_softc *,
	    const struct pxa2x0_wsscreen_descr *);
void	pxa2x0_lcd_setup_rasops(struct rasops_info *,
	    struct pxa2x0_wsscreen_descr *,
	    const struct lcd_panel_geometry *);
void	pxa2x0_lcd_start_dma(bus_space_tag_t, bus_space_handle_t,
	    struct pxa2x0_lcd_screen *);
void	pxa2x0_lcd_stop_dma(bus_space_tag_t, bus_space_handle_t);

/*
 * Setup display geometry parameters.
 */
void
pxa2x0_lcd_geometry(bus_space_tag_t iot, bus_space_handle_t ioh,
    const struct lcd_panel_geometry *info)
{
	int lines;
	uint32_t ccr0;

	ccr0 = LCCR0_IMASK;
	if (info->panel_info & LCDPANEL_ACTIVE)
		ccr0 |= LCCR0_PAS;	/* active mode */
	if ((info->panel_info & (LCDPANEL_DUAL | LCDPANEL_ACTIVE))
	    == LCDPANEL_DUAL)
		ccr0 |= LCCR0_SDS; /* dual panel */
	if (info->panel_info & LCDPANEL_MONOCHROME)
		ccr0 |= LCCR0_CMS;
	/* XXX - Zaurus C3000 */
	ccr0 |= LCCR0_LDDALT |
	    LCCR0_OUC |
	    LCCR0_CMDIM |
	    LCCR0_RDSTM;

	bus_space_write_4(iot, ioh, LCDC_LCCR0, ccr0);

	bus_space_write_4(iot, ioh, LCDC_LCCR1,
	    (info->panel_width - 1)
	    | ((info->hsync_pulse_width - 1) << 10)
	    | ((info->end_line_wait - 1) << 16)
	    | ((info->beg_line_wait - 1) << 24));

	if (info->panel_info & LCDPANEL_DUAL)
		lines = info->panel_height / 2 + info->extra_lines;
	else
		lines = info->panel_height + info->extra_lines;

	bus_space_write_4(iot, ioh, LCDC_LCCR2,
	    (lines - 1)
	    | (info->vsync_pulse_width << 10)
	    | (info->end_frame_wait << 16)
	    | (info->beg_frame_wait << 24));

	bus_space_write_4(iot, ioh, LCDC_LCCR3,
	    (info->pixel_clock_div << 0)
	    | (info->ac_bias << 8)
	    | ((info->panel_info &
		(LCDPANEL_VSP | LCDPANEL_HSP | LCDPANEL_PCP | LCDPANEL_OEP))
		<< 20)
	    | (4 << 24) /* 16bpp */
	    | ((info->panel_info & LCDPANEL_DPC) ? (1 << 27) : 0)
	    );
}

/*
 * Initialize the LCD controller.
 */
void
pxa2x0_lcd_initialize(bus_space_tag_t iot, bus_space_handle_t ioh,
    const struct lcd_panel_geometry *geom, void (*clkman)(u_int, int))
{
	int nldd;
	u_int32_t lccr0, lscr;

	/* Check if LCD is enabled before programming, it should not
	 * be enabled while it is being reprogrammed, therefore disable
	 * it first.
	 */
	lccr0 = bus_space_read_4(iot, ioh, LCDC_LCCR0);
	if (lccr0 & LCCR0_ENB) {
		lccr0 |= LCCR0_LDM;
		bus_space_write_4(iot, ioh, LCDC_LCCR0, lccr0);
		lccr0 = bus_space_read_4(iot, ioh, LCDC_LCCR0); /* paranoia */
		lccr0 |= LCCR0_DIS;
		bus_space_write_4(iot, ioh, LCDC_LCCR0, lccr0);
		do {
			lscr = bus_space_read_4(iot, ioh, LCDC_LCSR);
		} while (!(lscr & LCSR_LDD));
	}

	/* enable clock */
	(*clkman)(CKEN_LCD, 1);

	bus_space_write_4(iot, ioh, LCDC_LCCR0, LCCR0_IMASK);

	/*
	 * setup GP[77:58] for LCD
	 */
	/* Always use [FLP]CLK, ACBIAS */
	pxa2x0_gpio_set_function(74, GPIO_ALT_FN_2_OUT);
	pxa2x0_gpio_set_function(75, GPIO_ALT_FN_2_OUT);
	pxa2x0_gpio_set_function(76, GPIO_ALT_FN_2_OUT);
	pxa2x0_gpio_set_function(77, GPIO_ALT_FN_2_OUT);

	if ((geom->panel_info & LCDPANEL_ACTIVE) ||
	    ((geom->panel_info & (LCDPANEL_MONOCHROME|LCDPANEL_DUAL)) ==
	    LCDPANEL_DUAL)) {
		/* active and color dual panel need L_DD[15:0] */
		nldd = 16;
	} else if ((geom->panel_info & LCDPANEL_DUAL) ||
	    !(geom->panel_info & LCDPANEL_MONOCHROME)) {
		/* dual or color need L_DD[7:0] */
		nldd = 8;
	} else {
		/* Otherwise just L_DD[3:0] */
		nldd = 4;
	}

	while (nldd--)
		pxa2x0_gpio_set_function(58 + nldd, GPIO_ALT_FN_2_OUT);

	pxa2x0_lcd_geometry(iot, ioh, geom);
}

/*
 * Common driver attachment code.
 */
void
pxa2x0_lcd_attach_sub(struct pxa2x0_lcd_softc *sc,
    struct pxaip_attach_args *pxa, struct pxa2x0_wsscreen_descr *descr,
    const struct lcd_panel_geometry *geom, int console)
{
	bus_space_tag_t iot;
	bus_space_handle_t ioh;
	int error;

	sc->n_screens = 0;
	LIST_INIT(&sc->screens);

	/* map controller registers if not console */
	if (console != 0) {
		iot = pxa2x0_lcd_console.iot;
		ioh = pxa2x0_lcd_console.ioh;
	} else {
		iot = pxa->pxa_iot;
		error = bus_space_map(iot, PXA2X0_LCDC_BASE, PXA2X0_LCDC_SIZE,
		    0, &ioh);
		if (error) {
			printf(": failed to map registers %d", error);
			return;
		}
	}

	sc->iot = iot;
	sc->ioh = ioh;
	sc->dma_tag = &pxa2x0_bus_dma_tag;

	sc->ih = pxa2x0_intr_establish(17, IPL_BIO, lcdintr, sc,
	    sc->dev.dv_xname);
	if (sc->ih == NULL)
		printf("%s: unable to establish interrupt at irq %d",
		    sc->dev.dv_xname, 17);

	sc->geometry = geom;

	if (console != 0) {
		/* complete console attachment */
		pxa2x0_lcd_setup_console(sc, descr);
	} else {
		struct rasops_info dummy;

		pxa2x0_lcd_initialize(iot, ioh, geom, pxa2x0_clkman_config);

		/*
		 * Initialize a dummy rasops_info to compute fontsize and
		 * the screen size in chars.
		 */
		bzero(&dummy, sizeof(dummy));
		pxa2x0_lcd_setup_rasops(&dummy, descr, geom);
	}
}

/*
 * Interrupt handler.
 */
int
lcdintr(void *arg)
{
	struct pxa2x0_lcd_softc *sc = arg;
	bus_space_tag_t iot = sc->iot;
	bus_space_handle_t ioh = sc->ioh;

	static uint32_t status;

	status = bus_space_read_4(iot, ioh, LCDC_LCSR);
	/* Clear sticky status bits */
	bus_space_write_4(iot, ioh, LCDC_LCSR, status);

	return 1;
}

/*
 * Enable DMA to cause the display to be refreshed periodically.
 * This brings the screen to life...
 */
void
pxa2x0_lcd_start_dma(bus_space_tag_t iot, bus_space_handle_t ioh,
    struct pxa2x0_lcd_screen *scr)
{
	uint32_t tmp;
	int val, save;

	save = disable_interrupts(I32_bit);

	switch (scr->depth) {
	case 1: val = 0; break;
	case 2: val = 1; break;
	case 4: val = 2; break;
	case 8: val = 3; break;
	case 16:
		/* FALLTHROUGH */
	default:
		val = 4; break;
	}

	tmp = bus_space_read_4(iot, ioh, LCDC_LCCR3);
	bus_space_write_4(iot, ioh, LCDC_LCCR3,
	    (tmp & ~LCCR3_BPP) | (val << LCCR3_BPP_SHIFT));

	bus_space_write_4(iot, ioh, LCDC_FDADR0,
	    scr->depth == 16 ? scr->dma_desc_pa :
	    scr->dma_desc_pa + 2 * sizeof (struct lcd_dma_descriptor));
	bus_space_write_4(iot, ioh, LCDC_FDADR1,
	    scr->dma_desc_pa + 1 * sizeof (struct lcd_dma_descriptor));

	/* clear status */
	bus_space_write_4(iot, ioh, LCDC_LCSR, 0);

	delay(1000);			/* ??? */

	/* Enable LCDC */
	tmp = bus_space_read_4(iot, ioh, LCDC_LCCR0);
	/*tmp &= ~LCCR0_SFM;*/
	bus_space_write_4(iot, ioh, LCDC_LCCR0, tmp | LCCR0_ENB);

	restore_interrupts(save);
}

/*
 * Disable screen refresh.
 */
void
pxa2x0_lcd_stop_dma(bus_space_tag_t iot, bus_space_handle_t ioh)
{

	/* Stop LCD DMA after current frame */
	bus_space_write_4(iot, ioh, LCDC_LCCR0,
	    LCCR0_DIS |
	    bus_space_read_4(iot, ioh, LCDC_LCCR0));

	/* wait for disabling done.
	   XXX: use interrupt. */
	while (LCCR0_ENB &
	    bus_space_read_4(iot, ioh, LCDC_LCCR0))
		;

	bus_space_write_4(iot, ioh, LCDC_LCCR0,
	    ~LCCR0_DIS &
	    bus_space_read_4(iot, ioh, LCDC_LCCR0));
}

#define _rgb(r,g,b)	(((r)<<11) | ((g)<<5) | b)
#define rgb(r,g,b)	_rgb((r)>>1,g,(b)>>1)

#define L	0x1f			/* low intensity */
#define H	0x3f			/* high intensity */

static uint16_t basic_color_map[] = {
	rgb(	0,   0,   0),		/* black */
	rgb(	L,   0,   0),		/* red */
	rgb(	0,   L,   0),		/* green */
	rgb(	L,   L,   0),		/* brown */
	rgb(	0,   0,   L),		/* blue */
	rgb(	L,   0,   L),		/* magenta */
	rgb(	0,   L,   L),		/* cyan */
	rgb( 0x31,0x31,0x31),		/* white */

	rgb(	L,   L,   L),		/* black */
	rgb(	H,   0,   0),		/* red */
	rgb(	0,   H,   0),		/* green */
	rgb(	H,   H,   0),		/* brown */
	rgb(	0,   0,   H),		/* blue */
	rgb(	H,   0,   H),		/* magenta */
	rgb(	0,   H,   H),		/* cyan */
	rgb(	H,   H,   H)
};

#undef H
#undef L

static void
init_palette(uint16_t *buf, int depth)
{
	int i;

	/* convert RGB332 to RGB565 */
	switch (depth) {
	case 8:
	case 4:
#if 0
		for (i = 0; i <= 255; ++i) {
			buf[i] = ((9 * ((i >> 5) & 0x07)) << 11) |
			    ((9 * ((i >> 2) & 0x07)) << 5) |
			    ((21 * (i & 0x03)) / 2);
		}
#else
		memcpy(buf, basic_color_map, sizeof basic_color_map);
		for (i = 16; i < (1 << depth); ++i)
			buf[i] = 0xffff;
#endif
		break;
	case 16:
		/* palette is not needed */
		break;
	default:
		/* other depths are not supported */
		break;
	}
}

/*
 * Create and initialize a new screen buffer.
 */
int
pxa2x0_lcd_new_screen(struct pxa2x0_lcd_softc *sc,
    struct pxa2x0_lcd_screen *scr, int depth)
{
	bus_space_tag_t iot;
	bus_space_handle_t ioh;
	bus_dma_tag_t dma_tag;
	const struct lcd_panel_geometry *geometry;
	int width, height;
	bus_size_t size;
	int error, palette_size;
	int busdma_flag = (cold ? BUS_DMA_NOWAIT : BUS_DMA_WAITOK);
	struct lcd_dma_descriptor *desc;
	paddr_t buf_pa, desc_pa;

	if (sc != NULL) {
		iot = sc->iot;
		ioh = sc->ioh;
		dma_tag = sc->dma_tag;
		geometry = sc->geometry;
	} else {
		/* We are creating the console screen. */
		iot = pxa2x0_lcd_console.iot;
		ioh = pxa2x0_lcd_console.ioh;
		dma_tag = pxa2x0_lcd_console.dma_tag;
		geometry = pxa2x0_lcd_console.geometry;
	}

	width = geometry->panel_width;
	height = geometry->panel_height;
	palette_size = 0;

	switch (depth) {
	case 1:
	case 2:
	case 4:
	case 8:
		palette_size = (1 << depth) * sizeof (uint16_t);
		/* FALLTHROUGH */
	case 16:
		size = roundup(width, 4) * depth / 8 * height;
		break;
	default:
		printf("%s: Unknown depth (%d)\n",
		    sc != NULL ? sc->dev.dv_xname : "console", depth);
		return (EINVAL);
	}

	bzero(scr, sizeof *scr);

	scr->nsegs = 0;
	scr->depth = depth;
	scr->buf_size = size;
	scr->buf_va = NULL;
	size = roundup(size, 16) + 3 * sizeof (struct lcd_dma_descriptor)
	    + palette_size;

	error = bus_dmamem_alloc(dma_tag, size, 16, 0,
	    scr->segs, 1, &(scr->nsegs), busdma_flag);
	if (error != 0 || scr->nsegs != 1) {
		/* XXX: Actually we can handle nsegs > 1 case by means
		   of multiple DMA descriptors for a panel.  It would
		    make code here a bit hairy */
		if (error == 0)
			error = E2BIG;
		goto bad;
	}

	error = bus_dmamem_map(dma_tag, scr->segs, scr->nsegs,
	    size, (caddr_t *)&(scr->buf_va), busdma_flag | BUS_DMA_COHERENT);
	if (error != 0)
		goto bad;

	memset(scr->buf_va, 0, scr->buf_size);

	/* map memory for DMA */
	if (bus_dmamap_create(dma_tag, 1024 * 1024 * 2, 1,
	    1024 * 1024 * 2, 0,  busdma_flag, &scr->dma))
		goto bad;
	error = bus_dmamap_load(dma_tag, scr->dma,
	    scr->buf_va, size, NULL, busdma_flag);
	if (error != 0) {
		goto bad;
	}

	buf_pa = scr->segs[0].ds_addr;
	desc_pa = buf_pa + roundup(size, PAGE_SIZE) - 3 * sizeof *desc;

	/* make descriptors at the top of mapped memory */
	desc = (struct lcd_dma_descriptor *)
	    ((caddr_t)(scr->buf_va) + roundup(size, PAGE_SIZE) -
	     3 * sizeof *desc);

	desc[0].fdadr = desc_pa;
	desc[0].fsadr = buf_pa;
	desc[0].ldcmd = scr->buf_size;

	if (palette_size) {
		init_palette((uint16_t *)((char *)desc - palette_size), depth);

		desc[2].fdadr = desc_pa; /* chain to panel 0 */
		desc[2].fsadr = desc_pa - palette_size;
		desc[2].ldcmd = palette_size | LDCMD_PAL;
	}

	if (geometry->panel_info & LCDPANEL_DUAL) {
		/* Dual panel */
		desc[1].fdadr = desc_pa + sizeof *desc;
		desc[1].fsadr = buf_pa + scr->buf_size / 2;
		desc[0].ldcmd = desc[1].ldcmd = scr->buf_size / 2;

	}

#if 0
	desc[0].ldcmd |= LDCMD_SOFINT;
	desc[1].ldcmd |= LDCMD_SOFINT;
#endif

	scr->dma_desc = desc;
	scr->dma_desc_pa = desc_pa;
	scr->map_size = size;		/* used when unmap this. */

	if (sc != NULL) {
		LIST_INSERT_HEAD(&(sc->screens), scr, link);
		sc->n_screens++;
	}

	return (0);

 bad:
	if (scr->buf_va)
		bus_dmamem_unmap(dma_tag, scr->buf_va, size);
	if (scr->nsegs)
		bus_dmamem_free(dma_tag, scr->segs, scr->nsegs);
	return (error);
}

/*
 * Initialize rasops for a screen, as well as struct wsscreen_descr if this
 * is the first screen creation.
 */
void
pxa2x0_lcd_setup_rasops(struct rasops_info *rinfo,
    struct pxa2x0_wsscreen_descr *descr,
    const struct lcd_panel_geometry *geom)
{

	rinfo->ri_flg = descr->flags;
	rinfo->ri_depth = descr->depth;
	rinfo->ri_width = geom->panel_width;
	rinfo->ri_height = geom->panel_height;
	rinfo->ri_stride = rinfo->ri_width * rinfo->ri_depth / 8;
#ifdef notyet
	rinfo->ri_wsfcookie = -1;	/* XXX */
#endif

	/* swap B and R */
	if (descr->depth == 16) {
		rinfo->ri_rnum = 5;
		rinfo->ri_rpos = 11;
		rinfo->ri_gnum = 6;
		rinfo->ri_gpos = 5;
		rinfo->ri_bnum = 5;
		rinfo->ri_bpos = 0;
	}

	if (descr->c.nrows == 0) {
		/* get rasops to compute screen size the first time */
		rasops_init(rinfo, 100, 100);
	} else
#ifndef __zaurus__
		rasops_init(rinfo, descr->c.nrows, descr->c.ncols);
#else
		/* XXX swap rows/cols for second call because of rotation */
		rasops_init(rinfo, descr->c.ncols, descr->c.nrows);
#endif

	descr->c.nrows = rinfo->ri_rows;
	descr->c.ncols = rinfo->ri_cols;
	descr->c.capabilities = rinfo->ri_caps;
	descr->c.textops = &rinfo->ri_ops;
}

/*
 * Early console attachment.
 * This initializes the LCD, then creates and displays a screen buffer.
 * This screen will be accounted for in the softc when the lcd device attaches.
 */
int
pxa2x0_lcd_cnattach(struct pxa2x0_wsscreen_descr *descr,
    const struct lcd_panel_geometry *geom, void (*clkman)(u_int, int))
{
	struct rasops_info *ri;
	long defattr;
	int error;

	/* map controller registers */
	pxa2x0_lcd_console.iot = &pxa2x0_bs_tag;
	error = bus_space_map(pxa2x0_lcd_console.iot,
	    PXA2X0_LCDC_BASE, PXA2X0_LCDC_SIZE, 0, &pxa2x0_lcd_console.ioh);
	if (error != 0)
		return (error);

	pxa2x0_lcd_console.dma_tag = &pxa2x0_bus_dma_tag;
	pxa2x0_lcd_console.geometry = geom;

	pxa2x0_lcd_initialize(pxa2x0_lcd_console.iot, pxa2x0_lcd_console.ioh,
	    pxa2x0_lcd_console.geometry, clkman);

	error = pxa2x0_lcd_new_screen(NULL, &pxa2x0_lcd_console.scr,
	    descr->depth);
	if (error != 0)
		return (error);

	ri = &pxa2x0_lcd_console.scr.rinfo;
	ri->ri_hw = (void *)&pxa2x0_lcd_console.scr;
	ri->ri_bits = pxa2x0_lcd_console.scr.buf_va;
	pxa2x0_lcd_setup_rasops(ri, descr, pxa2x0_lcd_console.geometry);

	/* assumes 16 bpp */
	ri->ri_ops.alloc_attr(ri, 0, 0, 0, &defattr);

	pxa2x0_lcd_start_dma(pxa2x0_lcd_console.iot, pxa2x0_lcd_console.ioh,
	    &pxa2x0_lcd_console.scr);

	wsdisplay_cnattach(&descr->c, ri, ri->ri_ccol, ri->ri_crow, defattr);

	return (0);
}

/*
 * Do the necessary accounting to bring the console variables in the softc.
 */
void
pxa2x0_lcd_setup_console(struct pxa2x0_lcd_softc *sc,
    const struct pxa2x0_wsscreen_descr *descr)
{
	struct pxa2x0_lcd_screen *scr = &pxa2x0_lcd_console.scr;

	/*
	 * Register the console screen as if it had been created
	 * when the lcd device attached.
	 */
	LIST_INSERT_HEAD(&(sc->screens), &pxa2x0_lcd_console.scr, link);
	sc->n_screens++;
	sc->active = scr;
}

/*
 * wsdisplay accessops
 */

int
pxa2x0_lcd_show_screen(void *v, void *cookie, int waitok,
    void (*cb)(void *, int, int), void *cbarg)
{
	struct pxa2x0_lcd_softc *sc = v;
	struct rasops_info *ri = cookie;
	struct pxa2x0_lcd_screen *scr = ri->ri_hw, *old;

	old = sc->active;
	if (old == scr)
		return 0;

	if (old)
		pxa2x0_lcd_stop_dma(sc->iot, sc->ioh);

	pxa2x0_lcd_start_dma(sc->iot, sc->ioh, scr);

	sc->active = scr;
	return 0;
}

int
pxa2x0_lcd_alloc_screen(void *v, const struct wsscreen_descr *_type,
    void **cookiep, int *curxp, int *curyp, long *attrp)
{
	struct pxa2x0_lcd_softc *sc = v;
	struct pxa2x0_lcd_screen *scr;
	struct rasops_info *ri;
	struct pxa2x0_wsscreen_descr *type =
	    (struct pxa2x0_wsscreen_descr *)_type;
	int error;

	scr = malloc(sizeof *scr, M_DEVBUF, (cold ? M_NOWAIT : M_WAITOK));
	if (scr == NULL)
		return (ENOMEM);

	error = pxa2x0_lcd_new_screen(sc, scr, type->depth);
	if (error != 0) {
		free(scr, M_DEVBUF, 0);
		return (error);
	}

	/*
	 * initialize raster operation for this screen.
	 */
	ri = &scr->rinfo;
	ri->ri_hw = (void *)scr;
	ri->ri_bits = scr->buf_va;
	pxa2x0_lcd_setup_rasops(ri, type, sc->geometry);

	/* assumes 16 bpp */
	ri->ri_ops.alloc_attr(ri, 0, 0, 0, attrp);

	*cookiep = ri;
	*curxp = 0;
	*curyp = 0;

	return 0;
}

void
pxa2x0_lcd_free_screen(void *v, void *cookie)
{
	struct pxa2x0_lcd_softc *sc = v;
	struct rasops_info *ri = cookie;
	struct pxa2x0_lcd_screen *scr = ri->ri_hw;

	LIST_REMOVE(scr, link);
	sc->n_screens--;
	if (scr == sc->active) {
		/* at first, we need to stop LCD DMA */
		sc->active = NULL;

#ifdef DEBUG
		printf("lcd_free on active screen\n");
#endif

		pxa2x0_lcd_stop_dma(sc->iot, sc->ioh);
	}

	if (scr->buf_va)
		bus_dmamem_unmap(sc->dma_tag, scr->buf_va, scr->map_size);

	if (scr->nsegs > 0)
		bus_dmamem_free(sc->dma_tag, scr->segs, scr->nsegs);

	free(scr, M_DEVBUF, 0);
}

int
pxa2x0_lcd_ioctl(void *v, u_long cmd, caddr_t data, int flag, struct proc *p)
{
	struct pxa2x0_lcd_softc *sc = v;
	struct wsdisplay_fbinfo *wsdisp_info;
	struct pxa2x0_lcd_screen *scr = sc->active;  /* ??? */

	switch (cmd) {
	case WSDISPLAYIO_GTYPE:
		*(u_int *)data = WSDISPLAY_TYPE_PXALCD; /* XXX */
		break;

	case WSDISPLAYIO_GINFO:
		wsdisp_info = (struct wsdisplay_fbinfo *)data;

		wsdisp_info->height = sc->geometry->panel_height;
		wsdisp_info->width = sc->geometry->panel_width;
		wsdisp_info->depth = 16; /* XXX */
		wsdisp_info->cmsize = 0;
		break;

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

	case WSDISPLAYIO_GETCMAP:
	case WSDISPLAYIO_PUTCMAP:
		return EINVAL;	/* XXX Colormap */

	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;	/* not implemented */

        case WSDISPLAYIO_LINEBYTES:
		*(u_int *)data = scr->rinfo.ri_stride;
		break;
	}
	return (0);
}

paddr_t
pxa2x0_lcd_mmap(void *v, off_t offset, int prot)
{
	struct pxa2x0_lcd_softc *sc = v;
	struct pxa2x0_lcd_screen *screen = sc->active;  /* ??? */

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

	if (screen == NULL)
		return (-1);

	if (offset < 0 ||
	    offset >= screen->rinfo.ri_stride * screen->rinfo.ri_height)
		return (-1);

	return (bus_dmamem_mmap(sc->dma_tag, screen->segs, screen->nsegs,
	    offset, prot, BUS_DMA_WAITOK | BUS_DMA_COHERENT));
}

int
pxa2x0_lcd_load_font(void *v, void *emulcookie, struct wsdisplay_font *font)
{
	struct pxa2x0_lcd_softc *sc = v;
	struct pxa2x0_lcd_screen *screen = sc->active;

	if (screen == NULL)
		return ENXIO;

	return rasops_load_font(&screen->rinfo, emulcookie, font);
}

int
pxa2x0_lcd_list_font(void *v, struct wsdisplay_font *font)
{
	struct pxa2x0_lcd_softc *sc = v;
	struct pxa2x0_lcd_screen *screen = sc->active;

	if (screen == NULL)
		return ENXIO;

	return rasops_list_font(&screen->rinfo, font);
}

void
pxa2x0_lcd_suspend(struct pxa2x0_lcd_softc *sc)
{

	if (sc->active != NULL) {
		pxa2x0_lcd_stop_dma(sc->iot, sc->ioh);

		pxa2x0_clkman_config(CKEN_LCD, 0);
	}
}

void
pxa2x0_lcd_resume(struct pxa2x0_lcd_softc *sc)
{

	if (sc->active != NULL) {
		pxa2x0_lcd_initialize(sc->iot, sc->ioh, sc->geometry,
		    pxa2x0_clkman_config);
		pxa2x0_lcd_start_dma(sc->iot, sc->ioh, sc->active);
	}
}


code:
/*	$OpenBSD: pxa2x0_lcd.h,v 1.12 2013/10/21 10:36:10 miod Exp $ */
/* $NetBSD: pxa2x0_lcd.h,v 1.2 2003/06/17 09:43:14 bsh Exp $ */
/*
 * Copyright (c) 2002  Genetec Corporation.  All rights reserved.
 * Written by Hiroyuki Bessho for Genetec Corporation.
 *
 * 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 for the NetBSD Project by
 *	Genetec Corporation.
 * 4. The name of Genetec Corporation may not be used to endorse or
 *    promote products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY GENETEC CORPORATION ``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 GENETEC CORPORATION
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef _ARM_XSCALE_PXA2X0_LCD_H
#define _ARM_XSCALE_PXA2X0_LCD_H

#include <dev/rasops/rasops.h>
#include <machine/bus.h>

/* LCD Controller */

struct	lcd_dma_descriptor {
	uint32_t	fdadr;	/* next frame descriptor */
	uint32_t	fsadr;	/* frame start address */
	uint32_t	fidr;	/* frame ID */
	uint32_t	ldcmd;	/* DMA command */
#define	LDCMD_PAL	(1U<<26)	/* Palette buffer */
#define LDCMD_SOFINT	(1U<<22)	/* Start of Frame interrupt */
#define LDCMD_EOFINT	(1U<<21)	/* End of Frame interrupt */
};

struct pxa2x0_lcd_screen {
	LIST_ENTRY(pxa2x0_lcd_screen) link;

	/* Frame buffer */
	bus_dmamap_t dma;
	bus_dma_segment_t segs[1];
	int 	nsegs;
	size_t  buf_size;
	size_t  map_size;
	void 	*buf_va;
	int	depth;

	/* DMA frame descriptor */
	struct	lcd_dma_descriptor *dma_desc;
	paddr_t	dma_desc_pa;

	/* rasterop */
	struct rasops_info rinfo;
};

struct pxa2x0_lcd_softc {
	struct device  dev;
	/* control register */
	bus_space_tag_t  	iot;
	bus_space_handle_t	ioh;
	bus_dma_tag_t		dma_tag;

	const struct lcd_panel_geometry *geometry;

	int n_screens;
	LIST_HEAD(, pxa2x0_lcd_screen) screens;
	struct pxa2x0_lcd_screen *active;

	void *ih;			/* interrupt handler */
};

struct lcd_panel_geometry {
	short panel_width;
	short panel_height;
	short extra_lines;

	short panel_info;
#define LCDPANEL_VSP	(1<<0)		/* L_FCLK pin is active low */
#define LCDPANEL_HSP	(1<<1)		/* L_LCLK pin is active low */
#define LCDPANEL_PCP	(1<<2)		/* use L_PCLK falling edge */
#define LCDPANEL_OEP	(1<<3)		/* L_BIAS pin is active low */
#define LCDPANEL_DPC	(1<<4)		/* double pixel clock mode */

#define LCDPANEL_DUAL	(1<<5)		/* Dual or single */
#define LCDPANEL_SINGLE 0
#define LCDPANEL_ACTIVE	(1<<6)		/* Active or Passive */
#define LCDPANEL_PASSIVE 0
#define LCDPANEL_MONOCHROME (1<<7)	/* depth=1 */

	short pixel_clock_div;		/* pixel clock divider */
	short ac_bias;			/* AC bias pin frequency */

	short hsync_pulse_width;	/* Horizontal sync pulse width */
	short beg_line_wait;		/* beginning of line wait (BLW) */
	short end_line_wait;		/* end of line pxel wait (ELW) */

	short vsync_pulse_width;	/* vertical sync pulse width */
	short beg_frame_wait;		/* beginning of frame wait (BFW) */
	short end_frame_wait;		/* end of frame wait (EFW) */
};

/*
 * we need bits-per-pixel value to configure wsdisplay screen
 */
struct pxa2x0_wsscreen_descr {
	struct wsscreen_descr  c;	/* standard descriptor */
	int depth;			/* bits per pixel */
	int flags;			/* rasops flags */
};

void	pxa2x0_lcd_attach_sub(struct pxa2x0_lcd_softc *,
	    struct pxaip_attach_args *, struct pxa2x0_wsscreen_descr *,
	    const struct lcd_panel_geometry *, int);
int	pxa2x0_lcd_cnattach(struct pxa2x0_wsscreen_descr *,
	    const struct lcd_panel_geometry *, void (*)(u_int, int));

int	pxa2x0_lcd_alloc_screen(void *, const struct wsscreen_descr *,
	    void **, int *, int *, long *);
void	pxa2x0_lcd_free_screen(void *, void *);
int	pxa2x0_lcd_ioctl(void *, u_long, caddr_t, int, struct proc *);
int	pxa2x0_lcd_load_font(void *, void *, struct wsdisplay_font *);
int	pxa2x0_lcd_list_font(void *, struct wsdisplay_font *);
paddr_t	pxa2x0_lcd_mmap(void *, off_t, int);
int	pxa2x0_lcd_show_screen(void *, void *, int, void (*)(void *, int, int),
	    void *);

void	pxa2x0_lcd_power(int, void *);
void	pxa2x0_lcd_suspend(struct pxa2x0_lcd_softc *);
void	pxa2x0_lcd_resume(struct pxa2x0_lcd_softc *);

#endif /* _ARM_XSCALE_PXA2X0_LCD_H */