code:
/*	$OpenBSD: autoconf.c,v 1.100 2015/03/30 20:30:22 miod Exp $	*/
/*	$NetBSD: autoconf.c,v 1.73 1997/07/29 09:41:53 fair Exp $ */

/*
 * Copyright (c) 1996
 *    The President and Fellows of Harvard College. All rights reserved.
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This software was developed by the Computer Systems Engineering group
 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
 * contributed to Berkeley.
 *
 * All advertising materials mentioning features or use of this software
 * must display the following acknowledgement:
 *	This product includes software developed by Harvard University.
 *	This product includes software developed by the University of
 *	California, Lawrence Berkeley Laboratory.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)autoconf.c	8.4 (Berkeley) 10/1/93
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/buf.h>
#include <sys/disklabel.h>
#include <sys/device.h>
#include <sys/disk.h>
#include <sys/conf.h>
#include <sys/reboot.h>
#include <sys/socket.h>
#include <sys/malloc.h>
#include <sys/queue.h>
#include <sys/proc.h>
#include <sys/user.h>

#include <net/if.h>

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

#include <dev/cons.h>

#include <uvm/uvm_extern.h>

#include <machine/autoconf.h>
#include <machine/bsd_openprom.h>
#ifdef SUN4
#include <machine/oldmon.h>
#include <machine/idprom.h>
#include <sparc/sparc/memreg.h>
#endif
#include <machine/cpu.h>
#include <machine/ctlreg.h>
#include <machine/pmap.h>
#include <sparc/sparc/asm.h>
#include <sparc/sparc/cpuvar.h>
#include <sparc/sparc/timerreg.h>

#ifdef DDB
#include <machine/db_machdep.h>
#include <ddb/db_sym.h>
#include <ddb/db_extern.h>
#endif

/*
 * The following several variables are related to
 * the configuration process, and are used in initializing
 * the machine.
 */
int	fbnode;		/* node ID of ROM's console frame buffer */
int	optionsnode;	/* node ID of ROM's options */
int	mmu_3l;		/* SUN4_400 models have a 3-level MMU */

#ifdef KGDB
extern	int kgdb_debug_panic;
#endif

static	int rootnode;
static	char *str2hex(char *, int *);
static	int mbprint(void *, const char *);
static	void crazymap(char *, int *);
void	sync_crash(void);
int	mainbus_match(struct device *, void *, void *);
static	void mainbus_attach(struct device *, struct device *, void *);

struct	bootpath bootpath[8];
int	nbootpath;
static	void bootpath_build(void);
static	void bootpath_fake(struct bootpath *, char *);
static	void bootpath_print(struct bootpath *);
int	search_prom(int, char *);
char	mainbus_model[30];

/* Translate SBus interrupt level to processor IPL */
int	intr_sbus2ipl_4c[] = {
	0, 1, 2, 3, 5, 7, 8, 9
};
int	intr_sbus2ipl_4m[] = {
	0, 2, 3, 5, 7, 9, 11, 13
};

/*
 * Convert hex ASCII string to a value.  Returns updated pointer.
 * Depends on ASCII order (this *is* machine-dependent code, you know).
 */
static char *
str2hex(str, vp)
	register char *str;
	register int *vp;
{
	register int v, c;

	for (v = 0;; v = v * 16 + c, str++) {
		c = *(u_char *)str;
		if (c <= '9') {
			if ((c -= '0') < 0)
				break;
		} else if (c <= 'F') {
			if ((c -= 'A' - 10) < 10)
				break;
		} else if (c <= 'f') {
			if ((c -= 'a' - 10) < 10)
				break;
		} else
			break;
	}
	*vp = v;
	return (str);
}

#ifdef SUN4
struct promvec promvecdat;
struct om_vector *oldpvec = (struct om_vector *)PROM_BASE;
#endif

#if (defined(SUN4) || defined(SUN4C) || defined(SUN4E)) && \
    (defined(SUN4D) || defined(SUN4M)) && !defined(SMALL_KERNEL)
vaddr_t vm_kernel_space_size;
#endif

/*
 * locore.s code calls bootstrap() just before calling main(), after double
 * mapping the kernel to high memory and setting up the trap base register.
 * We must finish mapping the kernel properly and glean any bootstrap info.
 */
void
bootstrap()
{
#if defined(SUN4C) || defined(SUN4E)
	/*
	 * If we are running on a sun4e system, we need to differentiate it
	 * from sun4c now. Note that we can't use CPU_ISSUN4C here because
	 * it might have been optimized depending upon the kernel
	 * configuration.
	 */
	if (cputyp == CPU_SUN4C) {
		char tmpstr[24];
		u_long pgsiz;

		pgsiz = 0;
		snprintf(tmpstr, sizeof tmpstr, "pagesize %lx l!",
		    (u_long)&pgsiz);
		rominterpret(tmpstr);
		if (pgsiz == 1 << SUN4_PGSHIFT) {
#if defined(SUN4E)
			extern int nbpg, pgofset;

			cputyp = CPU_SUN4E;
			nbpg = 1 << SUN4_PGSHIFT;
			pgofset = nbpg - 1;
#else
			printf("OpenBSD/sparc: this kernel does not support the sun4e\n");
			romhalt();
#endif
		} else {
#if defined(SUN4C)
			/* cputyp, nbpg and pgofset already set in locore */
#else
			printf("OpenBSD/sparc: this kernel does not support the sun4c\n");
			romhalt();
#endif
		}
	}
#endif

#if defined(SUN4)
	if (CPU_ISSUN4) {
		extern void oldmon_w_cmd(u_long, char *);

		/*
		 * XXX:
		 * The promvec is bogus. We need to build a
		 * fake one from scratch as soon as possible.
		 */
		bzero(&promvecdat, sizeof promvecdat);
		promvec = &promvecdat;

		promvec->pv_stdin = oldpvec->inSource;
		promvec->pv_stdout = oldpvec->outSink;
		promvec->pv_putchar = oldpvec->putChar;
		promvec->pv_putstr = oldpvec->fbWriteStr;
		promvec->pv_nbgetchar = oldpvec->mayGet;
		promvec->pv_getchar = oldpvec->getChar;
		promvec->pv_romvec_vers = 0;		/* eek! */
		promvec->pv_reboot = oldpvec->reBoot;
		promvec->pv_abort = oldpvec->abortEntry;
		promvec->pv_setctxt = oldpvec->setcxsegmap;
		promvec->pv_v0bootargs = (struct v0bootargs **)(oldpvec->bootParam);
		promvec->pv_halt = oldpvec->exitToMon;

		/*
		 * Discover parts of the machine memory organization
		 * that we need this early.
		 */
		if (oldpvec->romvecVersion >= 2)
			*oldpvec->vector_cmd = oldmon_w_cmd;
	}
#endif /* SUN4 */

	/*
	 * Decide upon which address space partition to use if it could not
	 * be decided at compile-time (i.e. for GENERIC kernels supporting
	 * both the old Sun MMU and the SRMMU).
	 */
#if (defined(SUN4) || defined(SUN4C) || defined(SUN4E)) && \
    (defined(SUN4D) || defined(SUN4M)) && !defined(SMALL_KERNEL)
	if (CPU_ISSUN4OR4COR4E)
		vm_min_kernel_address = VM_MIN_KERNEL_ADDRESS_SUN4;
	else
		vm_min_kernel_address = VM_MIN_KERNEL_ADDRESS_SRMMU;
	vm_kernel_space_size = VM_MAX_KERNEL_ADDRESS - vm_min_kernel_address;
#endif

	bzero(&cpuinfo, sizeof(struct cpu_softc));
	cpuinfo.master = 1;
	getcpuinfo(&cpuinfo, 0);

	pmap_bootstrap(cpuinfo.mmu_ncontext,
		       cpuinfo.mmu_nregion,
		       cpuinfo.mmu_nsegment);
	/* Moved zs_kgdb_init() to zs.c:consinit() */
#ifdef DDB
	db_machine_init();
	ddb_init();
#endif

	/*
	 * On sun4ms we have to do some nasty stuff here. We need to map
	 * in the interrupt registers (since we need to find out where
	 * they are from the PROM, since they aren't in a fixed place), and
	 * disable all interrupts. We can't do this easily from locore
	 * since the PROM is ugly to use from assembly. We also need to map
	 * in the counter registers because we can't disable the level 14
	 * (statclock) interrupt, so we need a handler early on (ugh).
	 *
	 * NOTE: We *demand* the psl to stay at splhigh() at least until
	 * we get here. The system _cannot_ take interrupts until we map
	 * the interrupt registers.
	 */

#if defined(SUN4M)
#define getpte4m(va)	lda(((va) & 0xFFFFF000) | ASI_SRMMUFP_L3, ASI_SRMMUFP)

	/* First we'll do the interrupt registers */
	if (CPU_ISSUN4M) {
		register int node;
		struct romaux ra;
		register u_int pte;
		register int i;
		extern void setpte4m(u_int, u_int);
		extern struct timer_4m *timerreg_4m;
		extern struct counter_4m *counterreg_4m;

		if ((node = opennode("/obio/interrupt")) == 0)
		    if ((node=search_prom(findroot(),"interrupt"))==0)
			panic("bootstrap: could not get interrupt "
			      "node from prom");

		if (!romprop(&ra, "interrupt", node))
		    panic("bootstrap: could not get interrupt properties");
		if (ra.ra_nvaddrs < 2)
		    panic("bootstrap: less than 2 interrupt regs. available");
		if (ra.ra_nvaddrs > 5)
		    panic("bootstrap: cannot support capability of > 4 CPUs");

		for (i = 0; i < ra.ra_nvaddrs - 1; i++) {

			pte = getpte4m((u_int)ra.ra_vaddrs[i]);
			if ((pte & SRMMU_TETYPE) != SRMMU_TEPTE)
			    panic("bootstrap: PROM has invalid mapping for "
				  "processor interrupt register %d",i);
			pte |= PPROT_S;

			/* Duplicate existing mapping */

			setpte4m(PI_INTR_VA + (_MAXNBPG * i), pte);
		}

		/*
		 * That was the processor register...now get system register;
		 * it is the last returned by the PROM
		 */
		pte = getpte4m((u_int)ra.ra_vaddrs[i]);
		if ((pte & SRMMU_TETYPE) != SRMMU_TEPTE)
		    panic("bootstrap: PROM has invalid mapping for system "
			  "interrupt register");
		pte |= PPROT_S;

		setpte4m(SI_INTR_VA, pte);

		/* Now disable interrupts */
		intreg_set_4m(SINTR_MA);

		/* Send all interrupts to primary processor */
		*((u_int *)ICR_ITR) = 0;

#ifdef DEBUG
/*		printf("SINTR: mask: 0x%x, pend: 0x%x\n", *(int *)ICR_SI_MASK,
		       *(int *)ICR_SI_PEND);
*/
#endif

		/*
		 * Now map in the counters
		 * (XXX: fix for multiple CPUs! We assume 1)
		 * The processor register is the first; the system is the last.
		 * See also timerattach() in clock.c.
		 * This shouldn't be necessary; we ought to keep interrupts off
		 * and/or disable the (level 14) counter...
		 */

		if ((node = opennode("/obio/counter")) == 0)
		    if ((node=search_prom(findroot(),"counter"))==0)
			panic("bootstrap: could not find counter in OPENPROM");

		if (!romprop(&ra, "counter", node))
			panic("bootstrap: could not find counter properties");

		counterreg_4m = (struct counter_4m *)ra.ra_vaddrs[0];
		timerreg_4m = (struct timer_4m *)ra.ra_vaddrs[ra.ra_nvaddrs-1];
	}
#endif /* SUN4M */

#if defined(SUN4) || defined(SUN4C) || defined(SUN4E)
	if (CPU_ISSUN4OR4COR4E) {
		/* Map Interrupt Enable Register */
		/*
		 * XXX on non-Sun4, we ought to get the address from
		 * XXX the `interrupt-enable' node.
		 */
		pmap_kenter_pa(INTRREG_VA, PMAP_NC | PMAP_OBIO |
		    (CPU_ISSUN4E ? INT_ENABLE_REG_PHYSADR_4E :
		     INT_ENABLE_REG_PHYSADR_44C), PROT_READ | PROT_WRITE);
		pmap_update(pmap_kernel());
		/* Disable all interrupts */
		*((unsigned char *)INTRREG_VA) = 0;
	}
#endif
}

/*
 * bootpath_build: build a bootpath. Used when booting a generic
 * kernel to find our root device.  Newer proms give us a bootpath,
 * for older proms we have to create one.  An element in a bootpath
 * has 4 fields: name (device name), val[0], val[1], and val[2]. Note that:
 * Interpretation of val[] is device-dependent. Some examples:
 *
 * if (val[0] == -1) {
 *	val[1] is a unit number    (happens most often with old proms)
 * } else {
 *	[sbus device] val[0] is a sbus slot, and val[1] is an sbus offset
 *	[scsi disk] val[0] is target, val[1] is lun, val[2] is partition
 *	[scsi tape] val[0] is target, val[1] is lun, val[2] is file #
 * }
 *
 */

static void
bootpath_build()
{
	register char *cp, *pp;
	register struct bootpath *bp;

	/*
	 * On SS1s, promvec->pv_v0bootargs->ba_argv[1] contains the flags
	 * that were given after the boot command.  On SS2s, pv_v0bootargs
	 * is NULL but *promvec->pv_v2bootargs.v2_bootargs points to
	 * "vmunix -s" or whatever.
	 * XXX	DO THIS BEFORE pmap_bootstrap?
	 */
	bzero(bootpath, sizeof(bootpath));
	bp = bootpath;
	if (promvec->pv_romvec_vers < 2) {
		/*
		 * Grab boot device name and values.  build fake bootpath.
		 */
		cp = (*promvec->pv_v0bootargs)->ba_argv[0];

		if (cp != NULL)
			bootpath_fake(bp, cp);

		/* Setup pointer to boot flags */
		cp = (*promvec->pv_v0bootargs)->ba_argv[1];
		if (cp == NULL || *cp != '-')
			return;
	} else {
		/*
		 * Grab boot path from PROM
		 */
		cp = *promvec->pv_v2bootargs.v2_bootpath;
		while (cp != NULL && *cp == '/') {
			/* Step over '/' */
			++cp;
			/* Extract name */
			pp = bp->name;
			while (*cp != '@' && *cp != '/' && *cp != '\0')
				*pp++ = *cp++;
			*pp = '\0';
			if (*cp == '@') {
				cp = str2hex(++cp, &bp->val[0]);
				if (*cp == ',')
					cp = str2hex(++cp, &bp->val[1]);
				if (*cp == ':') {
					/*
					 * We only store one character here,
					 * as we will only use this field
					 * to compute a partition index
					 * for block devices.  However, it
					 * might be an ethernet media
					 * specification, so be sure to
					 * skip all letters.
					 */
					bp->val[2] = *++cp - 'a';
					while (*cp != '\0' && *cp != '/')
						cp++;
				}
			} else {
				bp->val[0] = -1; /* no #'s: assume unit 0, no
							sbus offset/address */
			}
			++bp;
			++nbootpath;
		}
		bp->name[0] = 0;

		/* Setup pointer to boot flags */
		cp = *promvec->pv_v2bootargs.v2_bootargs;
		if (cp == NULL)
			return;
		while (*cp != '-')
			if (*cp++ == '\0')
				return;
	}
	for (;;) {
		switch (*++cp) {

		case '\0':
			return;

		case 'a':
			boothowto |= RB_ASKNAME;
			break;

		case 'c':
			boothowto |= RB_CONFIG;
			break;

		case 'd':	/* kgdb - always on zs	XXX */
#ifdef KGDB
			boothowto |= RB_KDB;	/* XXX unused */
			kgdb_debug_panic = 1;
			kgdb_connect(1);
#elif DDB
			Debugger();
#else
			printf("kernel has no debugger\n");
#endif
			break;

		case 's':
			boothowto |= RB_SINGLE;
			break;
		}
	}
}

/*
 * Fake a ROM generated bootpath.
 * The argument `cp' points to a string such as "xd(0,0,0)bsd"
 */

static void
bootpath_fake(bp, cp)
	struct bootpath *bp;
	char *cp;
{
	register char *pp;
	int v0val[3];

#define BP_APPEND(BP,N,V0,V1,V2) { \
	strlcpy((BP)->name, N, sizeof (BP)->name); \
	(BP)->val[0] = (V0); \
	(BP)->val[1] = (V1); \
	(BP)->val[2] = (V2); \
	(BP)++; \
	nbootpath++; \
}

	pp = cp + 2;
	v0val[0] = v0val[1] = v0val[2] = 0;
	if (*pp == '(' 					/* for vi: ) */
 	    && *(pp = str2hex(++pp, &v0val[0])) == ','
	    && *(pp = str2hex(++pp, &v0val[1])) == ',')
		(void)str2hex(++pp, &v0val[2]);

#if defined(SUN4)
	if (CPU_ISSUN4) {
		char tmpname[8];

		/*
		 *  xylogics VME dev: xd, xy, xt
		 *  fake looks like: /vmel0/xdc0/xd@1,0
		 */
		if (cp[0] == 'x') {
			if (cp[1] == 'd') {/* xd? */
				BP_APPEND(bp, "vmel", -1, 0, 0);
			} else {
				BP_APPEND(bp, "vmes", -1, 0, 0);
			}
			snprintf(tmpname,sizeof tmpname,"x%cc", cp[1]); /* e.g. xdc */
			BP_APPEND(bp, tmpname,-1, v0val[0], 0);
			snprintf(tmpname,sizeof tmpname,"%c%c", cp[0], cp[1]);
			BP_APPEND(bp, tmpname,v0val[1], v0val[2], 0); /* e.g. xd */
			return;
		}

		/*
		 * ethernet: ie, le (rom supports only obio?)
		 * fake looks like: /obio0/le0
		 */
		if ((cp[0] == 'i' || cp[0] == 'l') && cp[1] == 'e')  {
			BP_APPEND(bp, "obio", -1, 0, 0);
			snprintf(tmpname,sizeof tmpname,"%c%c", cp[0], cp[1]);
			BP_APPEND(bp, tmpname, -1, 0, 0);
			return;
		}

		/*
		 * scsi: sd, st, sr
		 * assume: 4/100 = sw: /obio0/sw0/sd@0,0:a
		 * 4/200 & 4/400 = si/sc: /vmes0/si0/sd@0,0:a
 		 * 4/300 = esp: /obio0/esp0/sd@0,0:a
		 * (note we expect sc to mimic an si...)
		 */
		if (cp[0] == 's' &&
			(cp[1] == 'd' || cp[1] == 't' || cp[1] == 'r')) {

			int  target, lun;

			switch (cpuinfo.cpu_type) {
			case CPUTYP_4_200:
			case CPUTYP_4_400:
				BP_APPEND(bp, "vmes", -1, 0, 0);
				BP_APPEND(bp, "si", -1, v0val[0], 0);
				break;
			case CPUTYP_4_100:
				BP_APPEND(bp, "obio", -1, 0, 0);
				BP_APPEND(bp, "sw", -1, v0val[0], 0);
				break;
			case CPUTYP_4_300:
				BP_APPEND(bp, "obio", -1, 0, 0);
				BP_APPEND(bp, "esp", -1, v0val[0], 0);
				break;
			default:
				panic("bootpath_fake: unknown system type %d",
				      cpuinfo.cpu_type);
			}
			/*
			 * Deal with target/lun encodings.
			 * Note: more special casing in device_register().
			 */
			if (oldpvec->monId[0] > '1') {
				target = v0val[1] >> 3; /* new format */
				lun    = v0val[1] & 0x7;
			} else {
				target = v0val[1] >> 2; /* old format */
				lun    = v0val[1] & 0x3;
			}
			snprintf(tmpname, sizeof tmpname, "%c%c", cp[0], cp[1]);
			BP_APPEND(bp, tmpname, target, lun, v0val[2]);
			return;
		}

		return; /* didn't grok bootpath, no change */
	}
#endif /* SUN4 */

#if defined(SUN4C) || defined(SUN4E)
	/*
	 * sun4c stuff
	 */

	/*
	 * floppy: fd
	 * fake looks like: /fd@0,0:a
	 */
	if (cp[0] == 'f' && cp[1] == 'd') {
		/*
		 * Assume `fd(c,u,p)' means:
		 * partition `p' on floppy drive `u' on controller `c'
		 */
		BP_APPEND(bp, "fd", v0val[0], v0val[1], v0val[2]);
		return;
	}

	/*
	 * ethernet: le
	 * fake looks like: /sbus0/le0
	 */
	if (cp[0] == 'l' && cp[1] == 'e') {
		BP_APPEND(bp, "sbus", -1, 0, 0);
		BP_APPEND(bp, "le", -1, v0val[0], 0);
		return;
	}

	/*
	 * scsi: sd, st, sr
	 * fake looks like: /sbus0/esp0/sd@3,0:a
	 */
	if (cp[0] == 's' && (cp[1] == 'd' || cp[1] == 't' || cp[1] == 'r')) {
		char tmpname[8];
		int  target, lun;

		BP_APPEND(bp, "sbus", -1, 0, 0);
		BP_APPEND(bp, "esp", -1, v0val[0], 0);
		if (cp[1] == 'r')
			snprintf(tmpname, sizeof tmpname, "cd"); /* OpenBSD uses 'cd', not 'sr'*/
		else
			snprintf(tmpname, sizeof tmpname, "%c%c", cp[0], cp[1]);
		/* XXX - is TARGET/LUN encoded in v0val[1]? */
		target = v0val[1];
		lun = 0;
		BP_APPEND(bp, tmpname, target, lun, v0val[2]);
		return;
	}
#endif /* SUN4C || SUN4E */

	/*
	 * unknown; return
	 */

#undef BP_APPEND
}

/*
 * print out the bootpath
 * the %x isn't 0x%x because the Sun EPROMs do it this way, and
 * consistency with the EPROMs is probably better here.
 */

static void
bootpath_print(bp)
	struct bootpath *bp;
{
	printf("bootpath: ");
	while (bp->name[0]) {
		if (bp->val[0] == -1)
			printf("/%s%x", bp->name, bp->val[1]);
		else
			printf("/%s@%x,%x", bp->name, bp->val[0], bp->val[1]);
		if (bp->val[2] != 0)
			printf(":%c", bp->val[2] + 'a');
		bp++;
	}
	printf("\n");
}

/*
 * save or read a bootpath pointer from the boothpath store.
 *
 * XXX. required because of SCSI... we don't have control over the "sd"
 * device, so we can't set boot device there.   we patch in with
 * device_register(), and use this to recover the bootpath.
 */

struct bootpath *
bootpath_store(storep, bp)
	int storep;
	struct bootpath *bp;
{
	static struct bootpath *save;
	struct bootpath *retval;

	retval = save;
	if (storep)
		save = bp;

	return (retval);
}

/*
 * Set up the sd target mappings for non SUN4 PROMs.
 * Find out about the real SCSI target, given the PROM's idea of the
 * target of the (boot) device (i.e., the value in bp->v0val[0]).
 */
static void
crazymap(prop, map)
	char *prop;
	int *map;
{
	int i;
	char *propval;

	if (!CPU_ISSUN4 && promvec->pv_romvec_vers < 2) {
		/*
		 * Machines with real v0 proms have an `s[dt]-targets' property
		 * which contains the mapping for us to use. v2 proms donot
		 * require remapping.
		 */
		propval = getpropstring(optionsnode, prop);
		if (propval == NULL || strlen(propval) != 8) {
 build_default_map:
			printf("WARNING: %s map is bogus, using default\n",
				prop);
			for (i = 0; i < 8; ++i)
				map[i] = i;
			i = map[0];
			map[0] = map[3];
			map[3] = i;
			return;
		}
		for (i = 0; i < 8; ++i) {
			map[i] = propval[i] - '0';
			if (map[i] < 0 ||
			    map[i] >= 8)
				goto build_default_map;
		}
	} else {
		/*
		 * Set up the identity mapping for old sun4 monitors
		 * and v[2-] OpenPROMs. Note: device_register() does the
		 * SCSI-target juggling for sun4 monitors.
		 */
		for (i = 0; i < 8; ++i)
			map[i] = i;
	}
}

int
sd_crazymap(n)
	int	n;
{
	static int prom_sd_crazymap[8]; /* static: compute only once! */
	static int init = 0;

	if (init == 0) {
		crazymap("sd-targets", prom_sd_crazymap);
		init = 1;
	}
	return prom_sd_crazymap[n];
}

/*
 * Determine mass storage and memory configuration for a machine.
 * We get the PROM's root device and make sure we understand it, then
 * attach it as `mainbus0'.  We also set up to handle the PROM `sync'
 * command.
 */
void
cpu_configure()
{
	struct confargs oca;
	register int node = 0;
	register char *cp;
	int s;
	extern struct user *proc0paddr;
	extern struct sparc_bus_dma_tag dvma_dmatag;

	/* build the bootpath */
	bootpath_build();

	if (boothowto & RB_CONFIG) {
#ifdef BOOT_CONFIG
		user_config();
#else
		printf("kernel does not support -c; continuing..\n");
#endif
	}

#if defined(SUN4)
	if (CPU_ISSUN4) {
		extern struct cfdata cfdata[];
		extern struct cfdriver memreg_cd, obio_cd;
		struct cfdata *cf, *memregcf = NULL;
		register short *p;
		struct rom_reg rr;

		for (cf = cfdata; memregcf==NULL && cf->cf_driver; cf++) {
			if (cf->cf_driver != &memreg_cd ||
				cf->cf_loc[0] == -1) /* avoid sun4m memreg0 */
				continue;
			for (p = cf->cf_parents; memregcf==NULL && *p >= 0; p++)
				if (cfdata[*p].cf_driver == &obio_cd)
					memregcf = cf;
		}
		if (memregcf == NULL)
			panic("cpu_configure: no memreg found!");

		rr.rr_iospace = PMAP_OBIO;
		rr.rr_paddr = (void *)memregcf->cf_loc[0];
		rr.rr_len = NBPG;
		par_err_reg = (u_int *)bus_map(&rr, NBPG);
		if (par_err_reg == NULL)
			panic("cpu_configure: ROM hasn't mapped memreg!");
	}
#endif
#if defined(SUN4C) || defined(SUN4E)
	if (CPU_ISSUN4C || CPU_ISSUN4E) {
		node = findroot();
		cp = getpropstring(node, "device_type");
		if (strcmp(cp, "cpu") != 0)
			panic("PROM root device type = %s (need CPU)", cp);
	}
#endif
#if defined(SUN4M)
	if (CPU_ISSUN4M)
		node = findroot();
#endif

	if (!CPU_ISSUN4)
		*promvec->pv_synchook = sync_crash;

	oca.ca_ra.ra_node = node;
	oca.ca_ra.ra_name = cp = "mainbus";
	oca.ca_dmat = &dvma_dmatag;
	if (config_rootfound(cp, (void *)&oca) == NULL)
		panic("mainbus not configured");

	/* Enable device interrupts */
#if defined(SUN4M)
	if (CPU_ISSUN4M)
		intreg_clr_4m(SINTR_MA);
#endif
#if defined(SUN4) || defined(SUN4C) || defined(SUN4E)
	if (CPU_ISSUN4OR4COR4E)
		intreg_set_44c(IE_ALLIE);
#endif
	(void)spl0();

	/*
	 * Re-zero proc0's user area, to nullify the effect of the
	 * stack running into it during auto-configuration.
	 * XXX - should fix stack usage.
	 */
	s = splhigh();
	bzero(proc0paddr, sizeof(struct user));

	pmap_redzone();
	splx(s);
	cold = 0;
}

void
diskconf(void)
{
	struct bootpath *bp;
	struct device *bootdv;

	/*
	 * Configure swap area and related system
	 * parameter based on device(s) used.
	 */
	bootpath_print(bootpath);

	bp = nbootpath == 0 ? NULL : &bootpath[nbootpath-1];
	bootdv = (bp == NULL) ? NULL : bp->dev;

	setroot(bootdv, bp->val[2], RB_USERREQ | RB_HALT);
	dumpconf();
}

/*
 * Console `sync' command.  SunOS just does a `panic: zero' so I guess
 * no one really wants anything fancy...
 */
void
sync_crash()
{

	panic("PROM sync command");
}

char *
clockfreq(freq)
	register int freq;
{
	register char *p;
	static char buf[10];

	freq /= 1000;
	snprintf(buf, sizeof buf, "%d", freq / 1000);
	freq %= 1000;
	if (freq) {
		freq += 1000;	/* now in 1000..1999 */
		p = buf + strlen(buf);
		snprintf(p, buf + sizeof buf - p, "%d", freq);
		*p = '.';	/* now buf = %d.%3d */
	}
	return (buf);
}

/* ARGSUSED */
static int
mbprint(aux, name)
	void *aux;
	const char *name;
{
	register struct confargs *ca = aux;

	if (name)
		printf("%s at %s", ca->ca_ra.ra_name, name);
	if (ca->ca_ra.ra_paddr)
		printf(" %saddr 0x%x", ca->ca_ra.ra_iospace ? "io" : "",
		    (int)ca->ca_ra.ra_paddr);
	return (UNCONF);
}

int
findroot()
{
	register int node;

	if ((node = rootnode) == 0 && (node = nextsibling(0)) == 0)
		panic("no PROM root device");
	rootnode = node;
	return (node);
}

/*
 * Given a `first child' node number, locate the node with the given name.
 * Return the node number, or 0 if not found.
 */
int
findnode(first, name)
	int first;
	register const char *name;
{
	register int node;

	for (node = first; node; node = nextsibling(node))
		if (strcmp(getpropstring(node, "name"), name) == 0)
			return (node);
	return (0);
}

/*
 * Fill in a romaux.  Returns 1 on success, 0 if the register property
 * was not the right size.
 */
int
romprop(rp, cp, node)
	register struct romaux *rp;
	const char *cp;
	register int node;
{
	int len, n, intr;
	union { char regbuf[256]; struct rom_reg rr[RA_MAXREG]; } u;
	static const char pl[] = "property length";

	bzero(u.regbuf, sizeof u);
	len = getprop(node, "reg", (void *)u.regbuf, sizeof(u.regbuf));
	if (len == -1 &&
	    node_has_property(node, "device_type") &&
	    strcmp(getpropstring(node, "device_type"), "hierarchical") == 0)
		len = 0;
	if (len % sizeof(struct rom_reg)) {
		printf("%s \"reg\" %s = %d (need multiple of %zu)\n",
			cp, pl, len, sizeof(struct rom_reg));
		return (0);
	}
	if (len > RA_MAXREG * sizeof(struct rom_reg))
		printf("warning: %s \"reg\" %s %d > %zu, excess ignored\n",
		    cp, pl, len, RA_MAXREG * sizeof(struct rom_reg));
	rp->ra_node = node;
	rp->ra_name = cp;
	rp->ra_nreg = len / sizeof(struct rom_reg);
	bcopy(u.rr, rp->ra_reg, len);

	len = getprop(node, "address", (void *)rp->ra_vaddrs,
		      sizeof(rp->ra_vaddrs));
	if (len == -1) {
		rp->ra_vaddr = 0;	/* XXX - driver compat */
		len = 0;
	}
	if (len & 3) {
		printf("%s \"address\" %s = %d (need multiple of 4)\n",
		    cp, pl, len);
		len = 0;
	}
	rp->ra_nvaddrs = len >> 2;

	len = getprop(node, "intr", (void *)&rp->ra_intr, sizeof rp->ra_intr);
	if (len == -1)
		len = 0;

	/*
	 * Some SBus cards only provide an "interrupts" properly, listing
	 * SBus levels. But since obio devices will usually also provide
	 * both properties, only check for "interrupts" last.
	 */
	if (len == 0) {
		u_int32_t *interrupts;
		len = getproplen(node, "interrupts");
		if (len > 0 &&
		    (interrupts = malloc(len, M_TEMP, M_NOWAIT)) != NULL) {
			/* Build rom_intr structures from the list */
			getprop(node, "interrupts", interrupts, len);
			len /= sizeof(u_int32_t);
			for (n = 0; n < len; n++) {
				intr = interrupts[n];
				/*
				 * Non-SBus devices (such as the cgfourteen,
				 * which attaches on obio) do not need their
				 * interrupt level translated.
				 */
				if (intr < 8) {
					intr = CPU_ISSUN4M ?
					    intr_sbus2ipl_4m[intr] :
					    intr_sbus2ipl_4c[intr];
				}
				rp->ra_intr[n].int_pri = intr;
				rp->ra_intr[n].int_vec = 0;
			};
			len *= sizeof(struct rom_intr);
			free(interrupts, M_TEMP, 0);
		} else
			len = 0;
	}

	if (len & 7) {
		printf("%s \"intr\" %s = %d (need multiple of 8)\n",
		    cp, pl, len);
		len = 0;
	}
	rp->ra_nintr = len >>= 3;
	/* SPARCstation interrupts are not hardware-vectored */
	while (--len >= 0) {
		if (rp->ra_intr[len].int_vec) {
			printf("WARNING: %s interrupt %d has nonzero vector\n",
			    cp, len);
			break;
		}
#if defined(SUN4M)
		if (CPU_ISSUN4M) {
			/* What's in these high bits anyway? */
			rp->ra_intr[len].int_pri &= 0xf;
		}
#endif

	}
	return (1);
}

int
mainbus_match(parent, self, aux)
	struct device *parent;
	void *self;
	void *aux;
{
	struct cfdata *cf = self;
	register struct confargs *ca = aux;
	register struct romaux *ra = &ca->ca_ra;

	return (strcmp(cf->cf_driver->cd_name, ra->ra_name) == 0);
}

int autoconf_nzs = 0;	/* must be global so obio.c can see it */

/*
 * Attach the mainbus.
 *
 * Our main job is to attach the CPU (the root node we got in cpu_configure())
 * and iterate down the list of `mainbus devices' (children of that node).
 * We also record the `node id' of the default frame buffer, if any.
 */
static void
mainbus_attach(parent, dev, aux)
	struct device *parent, *dev;
	void *aux;
{
	struct confargs oca;
	register const char *const *ssp, *sp = NULL;
	struct confargs *ca = aux;
#if defined(SUN4C) || defined(SUN4D) || defined(SUN4E) || defined(SUN4M)
	register int node0, node;
	const char *const *openboot_special;
#define L1A_HACK		/* XXX hack to allow L1-A during autoconf */
#ifdef L1A_HACK
	int audio = 0;
#endif
#endif
#if defined(SUN4)
	static const char *const oldmon_special[] = {
		"vmel",
		"vmes",
		"led",
		NULL
	};
#endif /* SUN4 */

#if defined(SUN4C)
	static const char *const openboot_special4c[] = {
		/* find these first (end with empty string) */
		"memory-error",	/* as early as convenient, in case of error */
		"eeprom",
		"counter-timer",
		"auxiliary-io",
		"",

		/* ignore these (end with NULL) */
		"aliases",
		"interrupt-enable",
		"memory",
		"openprom",
		"options",
		"packages",
		"virtual-memory",
		NULL
	};
#endif
#if defined(SUN4E)
	static const char *const openboot_special4e[] = {
		/* find these first (end with empty string) */
		"memory-error",	/* as early as convenient, in case of error */
		"eeprom",
		"counter-timer",
		"auxiliary-io",
		"",

		/* ignore these (end with NULL) */
		"interrupt-enable",
		"options",
		"p2bus",	/* memory bus, has `eccmem' child */
		NULL
	};
#endif
#if defined(SUN4M)
	static const char *const openboot_special4m[] = {
		/* find these first */
		"obio",		/* smart enough to get eeprom/etc mapped */
		"",

		/* ignore these (end with NULL) */
		/*
		 * These are _root_ devices to ignore. Others must be handled
		 * elsewhere.
		 */
		"SUNW,sx",		/* XXX: no driver for SX yet */
		"virtual-memory",
		"aliases",
		"memory",
		"openprom",
		"options",
		"packages",
		/* we also skip any nodes with device_type == "cpu" */
		NULL
	};
#endif

	if (CPU_ISSUN4)
		snprintf(mainbus_model, sizeof mainbus_model,
			"SUN-4/%d series", cpuinfo.classlvl);
	else
		strlcat(mainbus_model, getpropstring(ca->ca_ra.ra_node,"name"),
			sizeof mainbus_model);
	printf(": %s\n", mainbus_model);

	/*
	 * Locate and configure the ``early'' devices.  These must be
	 * configured before we can do the rest.  For instance, the
	 * EEPROM contains the Ethernet address for the LANCE chip.
	 * If the device cannot be located or configured, panic.
	 */

#if defined(SUN4)
	if (CPU_ISSUN4) {
		/* Configure the CPU. */
		bzero(&oca, sizeof(oca));
		oca.ca_ra.ra_name = "cpu";
		oca.ca_dmat = ca->ca_dmat;
		config_found(dev, (void *)&oca, mbprint);

		/* Start at the beginning of the bootpath */
		bzero(&oca, sizeof(oca));
		oca.ca_ra.ra_bp = bootpath;
		oca.ca_dmat = ca->ca_dmat;

		oca.ca_bustype = BUS_MAIN;
		oca.ca_ra.ra_name = "obio";
		if (config_found(dev, (void *)&oca, mbprint) == NULL)
			panic("obio missing");

		for (ssp = oldmon_special; (sp = *ssp) != NULL; ssp++) {
			oca.ca_bustype = BUS_MAIN;
			oca.ca_ra.ra_name = sp;
			config_found(dev, (void *)&oca, mbprint);
		}
		return;
	}
#endif

/*
 * The rest of this routine is for OBP machines exclusively.
 */
#if defined(SUN4C) || defined(SUN4D) || defined(SUN4E) || defined(SUN4M)

	switch (cputyp) {
#ifdef SUN4C
	case CPU_SUN4C:
		openboot_special = openboot_special4c;
		break;
#endif
#ifdef SUN4E
	case CPU_SUN4E:
		openboot_special = openboot_special4e;
		break;
#endif
#ifdef SUN4M
	case CPU_SUN4M:
		openboot_special = openboot_special4m;
		break;
#endif
	default:
		/* panic("can't happen"); */
		openboot_special = NULL;
		break;
	}

	node = ca->ca_ra.ra_node;	/* i.e., the root node */

	/* the first early device to be configured is the cpu */
	if (CPU_ISSUN4M) {
		/* XXX - what to do on multiprocessor machines? */
		register const char *cp;

		for (node = firstchild(node); node; node = nextsibling(node)) {
			cp = getpropstring(node, "device_type");
			if (strcmp(cp, "cpu") == 0) {
				bzero(&oca, sizeof(oca));
				oca.ca_ra.ra_node = node;
				oca.ca_ra.ra_name = "cpu";
				oca.ca_ra.ra_paddr = 0;
				oca.ca_ra.ra_nreg = 0;
				oca.ca_dmat = ca->ca_dmat;
				config_found(dev, (void *)&oca, mbprint);
			}
		}
	} else if (CPU_ISSUN4C || CPU_ISSUN4E) {
		bzero(&oca, sizeof(oca));
		oca.ca_ra.ra_node = node;
		oca.ca_ra.ra_name = "cpu";
		oca.ca_ra.ra_paddr = 0;
		oca.ca_ra.ra_nreg = 0;
		oca.ca_dmat = ca->ca_dmat;
		config_found(dev, (void *)&oca, mbprint);
	}

	node = ca->ca_ra.ra_node;	/* re-init root node */

	if (promvec->pv_romvec_vers <= 2) {
		/*
		 * Revision 1 prom will always return a framebuffer device
		 * node if a framebuffer is installed, even if console is
		 * set to serial.
		 */
		if (*promvec->pv_stdout != PROMDEV_SCREEN ||
		    *promvec->pv_stdin != PROMDEV_KBD)
			fbnode = 0;
		else {
			/* remember which frame buffer is the console */
			fbnode = getpropint(node, "fb", 0);
		}
	} else {
		/* fbnode already initialized in consinit() */
	}

	/* Find the "options" node */
	node0 = firstchild(node);
	optionsnode = findnode(node0, "options");
	if (optionsnode == 0)
		panic("no options in OPENPROM");

	/* Start at the beginning of the bootpath */
	oca.ca_ra.ra_bp = bootpath;

	for (ssp = openboot_special; *(sp = *ssp) != 0; ssp++) {
		if ((node = findnode(node0, sp)) == 0) {
			printf("could not find %s in OPENPROM\n", sp);
			panic(sp);
		}
		oca.ca_bustype = BUS_MAIN;
		if (!romprop(&oca.ca_ra, sp, node) ||
		    (config_found(dev, (void *)&oca, mbprint) == NULL))
			panic(sp);
	}

	/*
	 * Configure the rest of the devices, in PROM order.  Skip
	 * PROM entries that are not for devices, or which must be
	 * done before we get here.
	 */
	for (node = node0; node; node = nextsibling(node)) {
		register const char *cp;

#if defined(SUN4D) || defined(SUN4M)
		if (CPU_ISSUN4DOR4M) /* skip the CPUs */
			if (node_has_property(node, "device_type") &&
			    !strcmp(getpropstring(node, "device_type"), "cpu"))
				continue;
#endif
		cp = getpropstring(node, "name");
		for (ssp = openboot_special; (sp = *ssp) != NULL; ssp++)
			if (strcmp(cp, sp) == 0)
				break;
		if (sp == NULL && romprop(&oca.ca_ra, cp, node)) {
#ifdef L1A_HACK
			if (strcmp(cp, "audio") == 0)
				audio = 1;
			if (strcmp(cp, "zs") == 0)
				autoconf_nzs++;
			if (/*audio &&*/ autoconf_nzs >= 2)	/*XXX*/
				splx(11 << 8);		/*XXX*/
#endif
			oca.ca_bustype = BUS_MAIN;
			config_found(dev, (void *)&oca, mbprint);
		}
	}

#if defined(SUN4E)
	if (CPU_ISSUN4E) {
		/*
		 * Attach the leds.
		 * XXX This is not a natural attachment, but since there
		 * XXX is more than one led, this does not fit in the usual
		 * XXX auxio blink framework.
		 */
		bzero(&oca, sizeof(oca));
		oca.ca_bustype = BUS_MAIN;
		oca.ca_ra.ra_name = "led";
		oca.ca_dmat = ca->ca_dmat;
		config_found(dev, (void *)&oca, mbprint);
	}
#endif
#endif /* SUN4C || SUN4D || SUN4E || SUN4M */
}

struct cfattach mainbus_ca = {
	sizeof(struct device), mainbus_match, mainbus_attach
};

struct cfdriver mainbus_cd = {
	NULL, "mainbus", DV_DULL
};

/*
 * findzs() is called from the zs driver (which is, at least in theory,
 * generic to any machine with a Zilog ZSCC chip).  It should return the
 * address of the corresponding zs channel.  It may not fail, and it
 * may be called before the VM code can be used.  Here we count on the
 * FORTH PROM to map in the required zs chips.
 */
void *
findzs(zs)
	int zs;
{

#if defined(SUN4)
#define ZS0_PHYS	0xf1000000
#define ZS1_PHYS	0xf0000000
#define ZS2_PHYS	0xe0000000

	if (CPU_ISSUN4) {
		struct rom_reg rr;
		register void *vaddr;

		switch (zs) {
		case 0:
			rr.rr_paddr = (void *)ZS0_PHYS;
			break;
		case 1:
			rr.rr_paddr = (void *)ZS1_PHYS;
			break;
		case 2:
			rr.rr_paddr = (void *)ZS2_PHYS;
			break;
		default:
			panic("findzs: unknown zs device %d", zs);
		}

		rr.rr_iospace = PMAP_OBIO;
		rr.rr_len = NBPG;
		vaddr = bus_map(&rr, NBPG);
		if (vaddr)
			return (vaddr);
	}
#endif

#if defined(SUN4C) || defined(SUN4D) || defined(SUN4E) || defined(SUN4M)
	if (!CPU_ISSUN4) {
		int node;

		node = firstchild(findroot());
		if (CPU_ISSUN4M) { /* zs is in "obio" tree on Sun4M */
			node = findnode(node, "obio");
			if (!node)
				panic("findzs: no obio node");
			node = firstchild(node);
		}
		while ((node = findnode(node, "zs")) != 0) {
			int vaddrs[10];

			if (getpropint(node, "slave", -1) != zs) {
				node = nextsibling(node);
				continue;
			}

			/*
			 * On some machines (e.g. the Voyager), the zs
			 * device has multi-valued register properties.
			 */
			if (getprop(node, "address",
			    (void *)vaddrs, sizeof(vaddrs)) != 0)
				return ((void *)vaddrs[0]);
		}
		return (NULL);
	}
#endif
	panic("findzs: cannot find zs%d", zs);
	/* NOTREACHED */
}

int
makememarr(struct memarr *ap, u_int xmax, int which)
{
#if defined(SUN4C) || defined(SUN4D) || defined(SUN4E) || defined(SUN4M)
	struct v0mlist *mp;
	int node, n;
	char *prop;
#endif

#ifdef DIAGNOSTIC
	if (which != MEMARR_AVAILPHYS && which != MEMARR_TOTALPHYS)
		panic("makememarr");
#endif

#ifdef DIAGNOSTIC
	if (which != MEMARR_AVAILPHYS && which != MEMARR_TOTALPHYS)
		panic("makememarr");
#endif

#if defined(SUN4)
	if (CPU_ISSUN4) {
		if (ap != NULL && xmax != 0) {
			ap[0].addr_hi = 0;
			ap[0].addr_lo = 0;
			ap[0].len = which == MEMARR_AVAILPHYS ?
			    *oldpvec->memoryAvail : *oldpvec->memorySize;
		}
		return 1;
	}
#endif
#if defined(SUN4C) || defined(SUN4D) || defined(SUN4E) || defined(SUN4M)
	switch (n = promvec->pv_romvec_vers) {
	case 0:
		/*
		 * Version 0 PROMs use a linked list to describe these
		 * guys.
		 */
		mp = which == MEMARR_AVAILPHYS ?
		    *promvec->pv_v0mem.v0_physavail :
		    *promvec->pv_v0mem.v0_phystot;

		for (n = 0; mp != NULL; mp = mp->next, n++) {
			if (ap == NULL || n >= xmax)
				continue;
			ap->addr_hi = 0;
			ap->addr_lo = (uint32_t)mp->addr;
			ap->len = mp->nbytes;
			ap++;
		}
		break;
	default:
		printf("makememarr: hope version %d PROM is like version 2\n",
		    n);
		/* FALLTHROUGH */
	case 3:
	case 2:
		/*
		 * Version 2 PROMs use a property array to describe them.
		 */
		if ((node = findnode(firstchild(findroot()), "memory")) == 0)
			panic("makememarr: cannot find \"memory\" node");
		prop = which == MEMARR_AVAILPHYS ? "available" : "reg";
		n = getproplen(node, prop) / sizeof(struct memarr);
		if (ap != NULL) {
			if (getprop(node, prop, ap,
			    xmax * sizeof(struct memarr)) <= 0)
				panic("makememarr: cannot get property");
		}
		break;
	}

	if (n <= 0)
		panic("makememarr: no memory found");
	return (n);
#endif	/* SUN4C || SUN4D || SUN4E || SUN4M */
}

/*
 * Internal form of getprop().  Returns the actual length.
 */
int
getprop(node, name, buf, bufsiz)
	int node;
	char *name;
	void *buf;
	register int bufsiz;
{
#if defined(SUN4C) || defined(SUN4D) || defined(SUN4E) || defined(SUN4M)
	register struct nodeops *no;
	register int len;
#endif

#if defined(SUN4)
	if (CPU_ISSUN4) {
		printf("WARNING: getprop not valid on sun4! %s\n", name);
		return (0);
	}
#endif

#if defined(SUN4C) || defined(SUN4D) || defined(SUN4E) || defined(SUN4M)
	no = promvec->pv_nodeops;
	len = no->no_proplen(node, name);
	if (len > bufsiz) {
		printf("node 0x%x property %s length %d > %d\n",
		    node, name, len, bufsiz);
#ifdef DEBUG
		panic("getprop");
#else
		return (0);
#endif
	}
	no->no_getprop(node, name, buf);
	return (len);
#endif
}

/*
 * Internal form of proplen().  Returns the property length.
 */
int
getproplen(node, name)
	int node;
	char *name;
{
	register struct nodeops *no = promvec->pv_nodeops;

	return (no->no_proplen(node, name));
}

/*
 * Return a string property.  There is a (small) limit on the length;
 * the string is fetched into a static buffer which is overwritten on
 * subsequent calls.
 */
char *
getpropstring(node, name)
	int node;
	char *name;
{
	register int len;
	static char stringbuf[32];

	len = getprop(node, name, (void *)stringbuf, sizeof stringbuf - 1);
	if (len == -1)
		len = 0;
	stringbuf[len] = '\0';	/* usually unnecessary */
	return (stringbuf);
}

/*
 * Fetch an integer (or pointer) property.
 * The return value is the property, or the default if there was none.
 */
int
getpropint(node, name, deflt)
	int node;
	char *name;
	int deflt;
{
	register int len;
	char intbuf[16];

	len = getprop(node, name, (void *)intbuf, sizeof intbuf);
	if (len != 4)
		return (deflt);
	return (*(int *)intbuf);
}

/*
 * OPENPROM functions.  These are here mainly to hide the OPENPROM interface
 * from the rest of the kernel.
 */
int
firstchild(node)
	int node;
{

	return (promvec->pv_nodeops->no_child(node));
}

int
nextsibling(node)
	int node;
{

	return (promvec->pv_nodeops->no_nextnode(node));
}

/* The following recursively searches a PROM tree for a given node */
int
search_prom(rootnode, name)
        register int rootnode;
        register char *name;
{
        register int rtnnode;
        register int node = rootnode;

        if (node == findroot() || !strcmp("hierarchical",
                                          getpropstring(node, "device_type")))
            node = firstchild(node);

        if (!node)
            panic("search_prom: null node");

        do {
                if (strcmp(getpropstring(node, "name"),name) == 0)
                    return node;

                if (node_has_property(node,"device_type") &&
                    (!strcmp(getpropstring(node, "device_type"),"hierarchical")
                     || !strcmp(getpropstring(node, "name"),"iommu"))
                    && (rtnnode = search_prom(node, name)) != 0)
                        return rtnnode;

        } while ((node = nextsibling(node)));

        return 0;
}

/* The following are used primarily in consinit() */

int
opennode(path)		/* translate phys. device path to node */
	register char *path;
{
	register int fd;

	if (promvec->pv_romvec_vers < 2) {
		printf("WARNING: opennode not valid on sun4! %s\n", path);
		return (0);
	}
	fd = promvec->pv_v2devops.v2_open(path);
	if (fd == 0)
		return 0;
	return promvec->pv_v2devops.v2_fd_phandle(fd);
}

int
node_has_property(node, prop)	/* returns 1 if node has given property */
	register int node;
	register const char *prop;
{

	return ((*promvec->pv_nodeops->no_proplen)(node, (caddr_t)prop) != -1);
}

/* Pass a string to the FORTH PROM to be interpreted */
void
rominterpret(s)
	register char *s;
{

	if (promvec->pv_romvec_vers < 2)
		promvec->pv_fortheval.v0_eval(strlen(s), s);
	else
		promvec->pv_fortheval.v2_eval(s);
}

/*
 * Try to figure out where the PROM stores the cursor row & column
 * variables.  Returns nonzero on error.
 */
int
romgetcursoraddr(rowp, colp)
	register int **rowp, **colp;
{
	char buf[100];

	/*
	 * line# and column# are global in older proms (rom vector < 2)
	 * and in some newer proms.  They are local in version 2.9.  The
	 * correct cutoff point is unknown, as yet; we use 2.9 here.
	 */
	if (promvec->pv_romvec_vers < 2 || promvec->pv_printrev < 0x00020009)
		snprintf(buf, sizeof buf,
		    "' line# >body >user %lx ! ' column# >body >user %lx !",
		    (u_long)rowp, (u_long)colp);
	else
		snprintf(buf, sizeof buf,
		    "stdout @ is my-self addr line# %lx ! addr column# %lx !",
		    (u_long)rowp, (u_long)colp);
	*rowp = *colp = NULL;
	rominterpret(buf);
	return (*rowp == NULL || *colp == NULL);
}

void
romhalt()
{
	if (!CPU_ISSUN4)
		*promvec->pv_synchook = NULL;

	promvec->pv_halt();
	panic("PROM exit failed");
}

void
romboot(str)
	char *str;
{
	if (!CPU_ISSUN4)
		*promvec->pv_synchook = NULL;

	promvec->pv_reboot(str);
	panic("PROM boot failed");
}

void
callrom()
{

#if 0			/* sun4c FORTH PROMs do this for us */
	if (CPU_ISSUN4)
		fb_unblank();
#endif
	promvec->pv_abort();
}

/*
 * find the boot device (if it was a disk).   we must check to see if
 * unit info in saved bootpath structure matches unit info in our softc.
 * note that knowing the device name (e.g. "xd0") is not useful... we
 * must check the drive number (or target/lun, in the case of SCSI).
 * (XXX is it worth ifdef'ing this?)
 */

void
device_register(struct device *dev, void *aux)
{
	struct bootpath *bp = bootpath_store(0, NULL); /* restore bootpath! */

	if (bp == NULL)
		return;

	/*
	 * scsi: sd,cd
	 */
	if (strcmp("sd", dev->dv_cfdata->cf_driver->cd_name) == 0 ||
	    strcmp("cd", dev->dv_cfdata->cf_driver->cd_name) == 0) {
		struct scsi_attach_args *sa = aux;
		struct scsibus_softc *sbsc;
		int target, lun;

		sbsc = (struct scsibus_softc *)dev->dv_parent;

		target = bp->val[0];
		lun = bp->val[1];

#if defined(SUN4)
		if (CPU_ISSUN4 && dev->dv_xname[0] == 's' &&
		    target == 0 && scsi_get_link(sbsc, 0, 0) == NULL) {
			/*
			 * disk unit 0 is magic: if there is actually no
			 * target 0 scsi device, the PROM will call
			 * target 3 `sd0'.
			 * XXX - what if someone puts a tape at target 0?
			 */
			/* Note that sbsc:0:0 will be NULL when we are
			 * invoked to match the device for target 0, if it
			 * exists. But then the attachment args will have
			 * its own target set to zero. It this case, skip
			 * the remapping.
			 */
			if (sa->sa_sc_link->target != 0) {
				target = 3;	/* remap to 3 */
				lun = 0;
			}
		}
#endif

#if defined(SUN4C) || defined(SUN4E)
		if ((CPU_ISSUN4C || CPU_ISSUN4E) && dev->dv_xname[0] == 's')
			target = sd_crazymap(target);
#endif

		if (sa->sa_sc_link->target == target &&
		    sa->sa_sc_link->lun == lun) {
			bp->dev = dev;	/* got it! */
			return;
		}
	}
}

/*
 * find a device matching "name" and unit number
 */
struct device *
getdevunit(name, unit)
	char *name;
	int unit;
{
	struct device *dev = TAILQ_FIRST(&alldevs);
	char num[10], fullname[16];
	int lunit;

	/* compute length of name and decimal expansion of unit number */
	snprintf(num, sizeof num, "%d", unit);
	lunit = strlen(num);
	if (strlen(name) + lunit >= sizeof(fullname) - 1)
		panic("config_attach: device name too long");

	strlcpy(fullname, name, sizeof fullname);
	strlcat(fullname, num, sizeof fullname);

	while (strcmp(dev->dv_xname, fullname) != 0) {
		if ((dev = TAILQ_NEXT(dev, dv_list)) == NULL)
			return NULL;
	}
	return dev;
}

struct nam2blk nam2blk[] = {
	{ "xy",		 3 },
	{ "sd",		 7 },
	{ "xd",		10 },
	{ "st",		11 },
	{ "fd",		16 },
	{ "rd",		17 },
	{ "cd",		18 },
	{ "raid",	25 },
	{ "vnd",	8 },
	{ NULL,		-1 }
};


code:
/*	$OpenBSD: auxioreg.h,v 1.5 2005/07/08 12:36:38 miod Exp $	*/
/*	$NetBSD: auxreg.h,v 1.7 1997/05/17 17:52:52 pk Exp $ */

/*
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This software was developed by the Computer Systems Engineering group
 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
 * contributed to Berkeley.
 *
 * All advertising materials mentioning features or use of this software
 * must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Lawrence Berkeley Laboratory.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)auxreg.h	8.1 (Berkeley) 6/11/93
 */

/*
 * Sun-4c Auxiliary I/O register.  This register talks to the floppy
 * (if it exists) and the front-panel LED.
 */

#define	AUXIO4C_MB1	0xf0		/* must be set on write */
#define	AUXIO4C_FHD	0x20		/* floppy: high density (unreliable?)*/
#define	AUXIO4C_FDC	0x10		/* floppy: diskette was changed */
#define	AUXIO4C_FDS	0x08		/* floppy: drive select */
#define	AUXIO4C_FTC	0x04		/* floppy: drives Terminal Count pin */
#define	AUXIO4C_FEJ	0x02		/* floppy: eject disk */
#define	AUXIO4C_LED	0x01		/* front panel LED */

#define	AUXIO4M_MB1	0xc0		/* must be set on write? */
#define	AUXIO4M_FHD	0x20		/* floppy: high density (unreliable?)*/
#define	AUXIO4M_LTE	0x08		/* link-test enable */
#define	AUXIO4M_MMX	0x04		/* Monitor/Mouse MUX; what is it? */
#define	AUXIO4M_FTC	0x02		/* floppy: drives Terminal Count pin */
#define	AUXIO4M_LED	0x01		/* front panel LED */

/*
 * Tadpole Auxiliary I/O registers.  Those control various power management
 * features.
 */

#define	AUXIO_MODEM		0x01	/* enable modem power */
#define	AUXIO_ISDN		0x04	/* enable ISDN power */
#define	AUXIO_MODEM_RESET	0x08	/* reset modem line (active low) */
#define	AUXIO_TFT		0x80	/* S3000 XT tft power */

#define	AUXIO2_SERIAL		0x01	/* enable serial ports power */

/*
 * We use a fixed virtual address for the register because we use it for
 * timing short sections of code (via external hardware attached to the LED).
 */
#define	AUXIO4C_REG	((volatile u_char *)(AUXREG_VA + 3))
#define	AUXIO4M_REG	((volatile u_char *)(AUXREG_VA))

#define LED_ON		do {						\
	if (CPU_ISSUN4M) {						\
		auxio_regval |= AUXIO4M_LED;				\
		*AUXIO4M_REG = auxio_regval;				\
	} else {							\
		auxio_regval |= AUXIO4C_LED;				\
		*AUXIO4C_REG = auxio_regval;				\
	}								\
} while(0)

#define LED_OFF		do {						\
	if (CPU_ISSUN4M) {						\
		auxio_regval &= ~AUXIO4M_LED;				\
		*AUXIO4M_REG = auxio_regval;				\
	} else {							\
		auxio_regval &= ~AUXIO4C_LED;				\
		*AUXIO4C_REG = auxio_regval;				\
	}								\
} while(0)

#define LED_FLIP	do {						\
	if (CPU_ISSUN4M) {						\
		auxio_regval ^= AUXIO4M_LED;				\
		*AUXIO4M_REG = auxio_regval;				\
	} else {							\
		auxio_regval ^= AUXIO4C_LED;				\
		*AUXIO4C_REG = auxio_regval;				\
	}								\
} while(0)

#define FTC_FLIP	do {						\
	if (CPU_ISSUN4M) {						\
		auxio_regval |= AUXIO4M_FTC;				\
		*AUXIO4M_REG = auxio_regval;				\
		*AUXIO4M_REG = *AUXIO4M_REG | AUXIO4M_MB1 | AUXIO4M_FTC;\
	} else {							\
		auxio_regval |= AUXIO4C_FTC;				\
		*AUXIO4C_REG = auxio_regval;				\
		DELAY(10);						\
		auxio_regval &= ~AUXIO4C_FTC;				\
		*AUXIO4C_REG = auxio_regval;				\
	}								\
} while(0)

#define	AUXIO_BITS	(						\
	CPU_ISSUN4M							\
		? "\20\6FHD\4LTE\3MMX\2FTC\1LED"			\
		: "\20\6FHD\5FDC\4FDS\3FTC\2FEJ\1LED"			\
)

#ifndef _LOCORE
extern u_char auxio_regval;
unsigned int auxregbisc(int, int);
unsigned int sb_auxregbisc(int, int, int);
#endif

license: unknown


code:
/*	$OpenBSD: auxreg.c,v 1.15 2010/07/10 19:32:24 miod Exp $	*/
/*	$NetBSD: auxreg.c,v 1.21 1997/05/24 20:15:59 pk Exp $ */

/*
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This software was developed by the Computer Systems Engineering group
 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
 * contributed to Berkeley.
 *
 * All advertising materials mentioning features or use of this software
 * must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Lawrence Berkeley Laboratory.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)auxreg.c	8.1 (Berkeley) 6/11/93
 */

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

#include <uvm/uvm_param.h>

#include <machine/autoconf.h>

#include <sparc/sparc/vaddrs.h>
#include <sparc/sparc/auxioreg.h>

static int auxregmatch(struct device *, void *, void *);
static void auxregattach(struct device *, struct device *, void *);

struct cfattach auxreg_ca = {
	sizeof(struct device), auxregmatch, auxregattach
};

struct cfdriver auxreg_cd = {
	0, "auxreg", DV_DULL
};

volatile u_char *auxio_reg;	/* Copy of AUXIO_REG */
u_char auxio_regval;

#ifdef SUN4M	/* Tadpole SPARCbook */
volatile u_char *sb_auxio_reg;
volatile u_char *sb_auxio2_reg;
#endif

extern int sparc_led_blink;	/* from machdep */
struct timeout sparc_led_to;

void
led_blink(zero)
	void *zero;
{
	int s;

	/* Don't do anything if there's no auxreg, ok? */
	if (auxio_reg == NULL)
		return;

	if (!sparc_led_blink) {
		/* If blink has been disabled, make sure it goes back on... */
		s = splhigh();
		LED_ON;
		splx(s);

		return;
	}

	s = splhigh();
	LED_FLIP;
	splx(s);
	/*
	 * Blink rate is:
	 *	full cycle every second if completely idle (loadav = 0)
	 *	full cycle every 2 seconds if loadav = 1
	 *	full cycle every 3 seconds if loadav = 2
	 * etc.
	 */
	s = (((averunnable.ldavg[0] + FSCALE) * hz) >> (FSHIFT + 1));

	timeout_add(&sparc_led_to, s);
}

/*
 * The OPENPROM calls this "auxiliary-io".
 * We also need to match the "auxio2" register on Tadpole SPARCbooks.
 */
static int
auxregmatch(struct device *parent, void *cf, void *aux)
{
	struct confargs *ca = aux;

	switch (cputyp) {
	case CPU_SUN4:
	default:
		return (0);
	case CPU_SUN4C:
	case CPU_SUN4E:
		return (strcmp("auxiliary-io", ca->ca_ra.ra_name) == 0);
	case CPU_SUN4M:
		return (strcmp("auxio", ca->ca_ra.ra_name) == 0 ||
			strcmp("auxio2", ca->ca_ra.ra_name) == 0);
	}
}

/* ARGSUSED */
static void
auxregattach(struct device *parent, struct device *self, void *aux)
{
	struct confargs *ca = aux;
	struct romaux *ra = &ca->ca_ra;
#ifdef SUN4M
	volatile u_char **regp;

	if (CPU_ISSUN4M && strncmp("Tadpole", mainbus_model, 7) == 0) {
		if (strcmp("auxio", ra->ra_name) == 0)
			regp = &sb_auxio_reg;
		else
			regp = &sb_auxio2_reg;
		if (*regp == NULL)
			*regp = mapiodev(ra->ra_reg, 0, sizeof(char));
	} else
#endif
	if (auxio_reg == NULL) {
		(void)mapdev(ra->ra_reg, AUXREG_VA, 0, sizeof(long));
		if (CPU_ISSUN4M) {
			auxio_reg = AUXIO4M_REG;
			auxio_regval = *AUXIO4M_REG | AUXIO4M_MB1;
		} else {
			auxio_reg = AUXIO4C_REG;
			auxio_regval = *AUXIO4C_REG | AUXIO4C_FEJ | AUXIO4C_MB1;
		}

		timeout_set(&sparc_led_to, led_blink, NULL);
		/* In case it's initialized to true... */
		if (sparc_led_blink)
			led_blink((caddr_t)0);
	}

	printf("\n");
}

unsigned int
auxregbisc(int bis, int bic)
{
	int s;

#ifdef DIAGNOSTIC
	if (auxio_reg == NULL)
		/*
		 * Not all machines have an `aux' register; devices that
		 * depend on it should not get configured if it's absent.
		 */
		panic("no aux register");
#endif

	s = splhigh();
	auxio_regval = (auxio_regval | bis) & ~bic;
	*auxio_reg = auxio_regval;
	splx(s);
	return (auxio_regval);
}

#ifdef SUN4M
unsigned int
sb_auxregbisc(int isreg2, int bis, int bic)
{
	int s;
	volatile u_char *auxreg;
	u_char aux;

	auxreg = isreg2 ? sb_auxio2_reg : sb_auxio_reg;
	if (auxreg == NULL)
		return (0);

	s = splhigh();
	aux = (*auxreg | bis) & ~bic;
	*auxreg = aux;
	splx(s);
	return (aux);
}
#endif


code:
/*	$OpenBSD: bsd_fdintr.s,v 1.13 2010/08/17 20:05:08 miod Exp $	*/
/*	$NetBSD: bsd_fdintr.s,v 1.11 1997/04/07 21:00:36 pk Exp $ */

/*
 * Copyright (c) 1995 Paul Kranenburg
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by Paul Kranenburg.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#ifndef FDC_C_HANDLER
#include "assym.h"
#include <machine/param.h>
#include <machine/psl.h>
#include <machine/asm.h>
#include <sparc/sparc/intreg.h>
#include <sparc/sparc/auxioreg.h>
#include <sparc/sparc/vaddrs.h>
#include <sparc/dev/fdreg.h>
#include <sparc/dev/fdvar.h>

/*
 * Note the following code hardcodes soft interrupt level 4, instead of
 * picking the actual bits from the softintr cookie. We don't have enough
 * free registers to be able to pick it easily, anyway; it's just not
 * worth doing.
 */

#define FD_SET_SWINTR_4C				\
	sethi	%hi(INTRREG_VA), %l5;			\
	ldub	[%l5 + %lo(INTRREG_VA)], %l6;		\
	or	%l6, IE_L4, %l6;			\
	stb	%l6, [%l5 + %lo(INTRREG_VA)]

! raise(0,IPL_FDSOFT)	! NOTE: CPU#0 and IPL_FDSOFT=4
#define FD_SET_SWINTR_4M				\
	sethi	%hi(1 << (16 + 4)), %l5;		\
	set	ICR_PI_SET, %l6;			\
	st	%l5, [%l6]

/* set software interrupt */
#if (defined(SUN4) || defined(SUN4C)) && !defined(SUN4M)
#define FD_SET_SWINTR	FD_SET_SWINTR_4C
#elif !(defined(SUN4) || defined(SUN4C)) && defined(SUN4M)
#define FD_SET_SWINTR	FD_SET_SWINTR_4M
#else
#define FD_SET_SWINTR					\
	sethi	%hi(_C_LABEL(cputyp)), %l5;		\
	ld	[%l5 + %lo(_C_LABEL(cputyp))], %l5;	\
	cmp	%l5, CPU_SUN4M;				\
	be	8f;					\
	FD_SET_SWINTR_4C;				\
	ba,a	9f;					\
8:							\
	FD_SET_SWINTR_4M;				\
9:
#endif

! flip TC bit in auxreg
! assumes %l6 remains unchanged between ASSERT and DEASSERT
#define FD_ASSERT_TC_4C					\
	sethi	%hi(AUXREG_VA), %l6;			\
	ldub	[%l6 + %lo(AUXREG_VA) + 3], %l7;	\
	or	%l7, AUXIO4C_MB1|AUXIO4C_FTC, %l7;	\
	stb	%l7, [%l6 + %lo(AUXREG_VA) + 3];

#define FD_DEASSERT_TC_4C				\
	ldub	[%l6 + %lo(AUXREG_VA) + 3], %l7;	\
	andn	%l7, AUXIO4C_FTC, %l7;			\
	or	%l7, AUXIO4C_MB1, %l7;			\
	stb	%l7, [%l6 + %lo(AUXREG_VA) + 3];

! flip TC bit in auxreg
#define FD_ASSERT_TC_4M					\
	sethi	%hi(AUXREG_VA), %l6;			\
	ldub	[%l6 + %lo(AUXREG_VA) + 3], %l7;	\
	or	%l7, AUXIO4M_MB1|AUXIO4M_FTC, %l7;	\
	stb	%l7, [%l6 + %lo(AUXREG_VA) + 3];

#define FD_DEASSERT_TC_4M

/*
 * flip TC bit in auxreg
 * assumes %l5 remains unchanged between ASSERT and DEASSERT
 */
#if (defined(SUN4) || defined(SUN4C)) && !defined(SUN4M)
#define FD_ASSERT_TC		FD_ASSERT_TC_4C
#define FD_DEASSERT_TC		FD_DEASSERT_TC_4C
#elif !(defined(SUN4) || defined(SUN4C)) && defined(SUN4M)
#define FD_ASSERT_TC		FD_ASSERT_TC_4M
#define FD_DEASSERT_TC		FD_DEASSERT_TC_4M
#else
#define FD_ASSERT_TC					\
	sethi	%hi(_C_LABEL(cputyp)), %l5;		\
	ld	[%l5 + %lo(_C_LABEL(cputyp))], %l5;	\
	cmp	%l5, CPU_SUN4M;				\
	be	8f;					\
	 nop;						\
	FD_ASSERT_TC_4C;				\
	ba,a	9f;					\
8:							\
	FD_ASSERT_TC_4M;				\
9:
#define FD_DEASSERT_TC					\
	cmp	%l5, CPU_SUN4M;				\
	be	8f;					\
	 nop;						\
	FD_DEASSERT_TC_4C;				\
	ba,a	9f;					\
8:							\
	FD_DEASSERT_TC_4M;				\
9:
#endif

/* Timeout waiting for chip ready */
#define POLL_TIMO	100000

/*
 * register mnemonics. note overlapping assignments.
 */
#define R_fdc	%l0
#define R_msr	%l1
#define R_fifo	%l2
#define R_buf	%l3
#define R_tc	%l4
#define R_stat	%l3
#define R_nstat	%l4
#define R_stcnt	%l5
/* use %l6 and %l7 as short term temporaries */

	.seg	"data"
	.align	8
	.global _C_LABEL(fdciop)
/* A save haven for three precious registers */
save_l:
	.word	0
	.word	0
	.word	0
/* Pointer to a `struct fdcio', set in fd.c */
_C_LABEL(fdciop):
	.word	0

	.seg	"text"
	.align	4
	.global _C_LABEL(fdchwintr)

_C_LABEL(fdchwintr):
	set	save_l, %l7
	std	%l0, [%l7]
	st	%l2, [%l7 + 8]

	! tally interrupt
	sethi	%hi(_C_LABEL(uvmexp)+V_INTR), %l7
	ld	[%l7 + %lo(_C_LABEL(uvmexp)+V_INTR)], %l6
	inc	%l6
	st	%l6, [%l7 + %lo(_C_LABEL(uvmexp)+V_INTR)]

	! load fdc, if it's NULL there's nothing to do: schedule soft interrupt
	sethi	%hi(_C_LABEL(fdciop)), %l7
	ld	[%l7 + %lo(_C_LABEL(fdciop))], R_fdc

	! tally interrupt
	ldd	[R_fdc + FDC_COUNT], %l4
	inccc	%l5
	addx	%l4, 0, %l4
	std	%l4, [R_fdc + FDC_COUNT]

	! load chips register addresses
	ld	[R_fdc + FDC_REG_MSR], R_msr	! get chip MSR reg addr
	ld	[R_fdc + FDC_REG_FIFO], R_fifo	! get chip FIFO reg addr
	!!ld	[R_fdc + FDC_REG_DOR], R_dor	! get chip DOR reg addr

	! find out what we are supposed to do
	ld	[R_fdc + FDC_ITASK], %l7	! get task from fdc
	cmp	%l7, FDC_ITASK_SENSEI
	be	sensei
	 !nop
	cmp	%l7, FDC_ITASK_RESULT
	be	resultphase
	 !nop
	cmp	%l7, FDC_ITASK_DMA
	bne,a	ssi				! a spurious interrupt
	 mov	FDC_ISTATUS_SPURIOUS, %l7	! set status and post sw intr

	! pseudo DMA
	ld	[R_fdc + FDC_TC], R_tc		! residual count
	ld	[R_fdc + FDC_DATA], R_buf	! IO buffer

	ldub	[R_msr], %l7			! get MSR value
nextc:
	btst	NE7_RQM, %l7			! room in fifo?
	bnz,a	0f
	 btst	NE7_NDM, %l7			! overrun?

	! we filled/emptied the FIFO; update fdc->sc_buf & fdc->sc_tc
	st	R_tc, [R_fdc + FDC_TC]
	b	x
	st	R_buf, [R_fdc + FDC_DATA]

0:
	bz	resultphase			! overrun/underrun
	btst	NE7_DIO, %l7			! IO direction
	bz	1f
	 deccc	R_tc
	ldub	[R_fifo], %l7			! reading:
	b	2f
	stb	%l7, [R_buf]			!    *fdc->sc_bufp = *reg_fifo

1:
	ldub	[R_buf], %l7			! writing:
	stb	%l7, [R_fifo]			!    *reg_fifo = *fdc->sc_bufp
2:
	inc	R_buf				! fdc->sc_bufp++
	bne,a	nextc				! if (--fdc->sc_tc) goto ...
	 ldub	[R_msr], %l7			! get MSR value

	! xfer done: update fdc->sc_buf & fdc->sc_tc, mark istate DONE
	st	R_tc, [R_fdc + FDC_TC]
	st	R_buf, [R_fdc + FDC_DATA]

	! flip TC bit in auxreg
	FD_ASSERT_TC

	! we have some time to kill; anticipate on upcoming
	! result phase.
	add	R_fdc, FDC_STATUS, R_stat	! &fdc->sc_status[0]
	mov	-1, %l7
	st	%l7, [R_fdc + FDC_NSTAT]	! fdc->sc_nstat = -1;

	FD_DEASSERT_TC
	b,a	resultphase1

sensei:
	ldub	[R_msr], %l7
	set	POLL_TIMO, %l6
1:	deccc	%l6				! timeout?
	be,a	ssi				! if so, set status
	 mov	FDC_ISTATUS_ERROR, %l7		! and post sw interrupt
	and	%l7, (NE7_RQM | NE7_DIO | NE7_CB), %l7
	cmp	%l7, NE7_RQM
	bne,a	1b				! loop till chip ready
	 ldub	[R_msr], %l7
	mov	NE7CMD_SENSEI, %l7
	stb	%l7, [R_fifo]

resultphase:
	! prepare for result phase
	add	R_fdc, FDC_STATUS, R_stat	! &fdc->sc_status[0]
	mov	-1, %l7
	st	%l7, [R_fdc + FDC_NSTAT]	! fdc->sc_nstat = -1;

resultphase1:
	clr	R_stcnt
	ldub	[R_msr], %l7
	set	POLL_TIMO, %l6
1:	deccc	%l6				! timeout?
	be,a	ssi				! if so, set status
	 mov	FDC_ISTATUS_ERROR, %l7		! and post sw interrupt
	and	%l7, (NE7_RQM | NE7_DIO | NE7_CB), %l7
	cmp	%l7, NE7_RQM
	be	3f				! done
	cmp	%l7, (NE7_RQM | NE7_DIO | NE7_CB)
	bne,a	1b				! loop till chip ready
	 ldub	[R_msr], %l7

	cmp	R_stcnt, FDC_NSTATUS		! status overrun?
	bge	2f				! if so, load but dont store
	ldub	[R_fifo], %l7			! load the status byte
	stb	%l7, [R_stat]
	inc	R_stat
	inc	R_stcnt
2:	b	1b
	 ldub	[R_msr], %l7

3:
	! got status, update sc_nstat and mark istate DONE
	st	R_stcnt, [R_fdc + FDC_NSTAT]
	mov	FDC_ISTATUS_DONE, %l7

ssi:
	! set software interrupt
	! enter here with status in %l7
	st	%l7, [R_fdc + FDC_ISTATUS]
	ld	[R_fdc + FDC_SIH], %l6
	mov	1, %l7
	st	%l7, [%l6 + SIH_PENDING]
	FD_SET_SWINTR

x:
	/*
	 * Restore psr -- note: psr delay honored by pc restore loads.
	 */
	set	save_l, %l7
	ldd	[%l7], %l0
	mov	%l0, %psr
	 nop
	ld	[%l7 + 8], %l2
	jmp	%l1
	rett	%l2
#endif


code:
/*	$OpenBSD: cache.c,v 1.20 2010/07/10 19:32:24 miod Exp $	*/
/*	$NetBSD: cache.c,v 1.34 1997/09/26 22:17:23 pk Exp $	*/

/*
 * Copyright (c) 1996
 *	The President and Fellows of Harvard College. All rights reserved.
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This software was developed by the Computer Systems Engineering group
 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
 * contributed to Berkeley.
 *
 * All advertising materials mentioning features or use of this software
 * must display the following acknowledgement:
 *	This product includes software developed by Harvard University.
 *	This product includes software developed by the University of
 *	California, Lawrence Berkeley Laboratory.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Aaron Brown and
 *	Harvard University.
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. 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.
 *
 *	@(#)cache.c	8.2 (Berkeley) 10/30/93
 *
 */

/*
 * Cache routines.
 *
 * TODO:
 *	- rework range flush
 */

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

#include <uvm/uvm_extern.h>

#include <machine/ctlreg.h>

#include <sparc/sparc/asm.h>
#include <sparc/sparc/cache.h>
#include <sparc/sparc/cpuvar.h>

#if defined(solbourne)
#include <machine/idt.h>
#include <machine/kap.h>
#endif

struct cachestats cachestats;

int cache_alias_dist;		/* Cache anti-aliasing constants */
int cache_alias_bits;

/*
 * Enable the cache.
 * We need to clear out the valid bits first.
 */
void
sun4_cache_enable()
{
	u_int i, lim, ls, ts;

	cache_alias_bits = CPU_ISSUN4OR4E
				? CACHE_ALIAS_BITS_SUN4
				: CACHE_ALIAS_BITS_SUN4C;
	cache_alias_dist = CPU_ISSUN4OR4E
				? CACHE_ALIAS_DIST_SUN4
				: CACHE_ALIAS_DIST_SUN4C;

	ls = CACHEINFO.c_linesize;
	ts = CACHEINFO.c_totalsize;

	for (i = AC_CACHETAGS, lim = i + ts; i < lim; i += ls)
		sta(i, ASI_CONTROL, 0);

	stba(AC_SYSENABLE, ASI_CONTROL,
	     lduba(AC_SYSENABLE, ASI_CONTROL) | SYSEN_CACHE);
	CACHEINFO.c_enabled = 1;

	printf("cache enabled\n");

#ifdef notyet
	if (cpuinfo.flags & SUN4_IOCACHE) {
		stba(AC_SYSENABLE, ASI_CONTROL,
		     lduba(AC_SYSENABLE, ASI_CONTROL) | SYSEN_IOCACHE);
		printf("iocache enabled\n");
	}
#endif
}

#if defined(SUN4M)
void
ms1_cache_enable()
{
	u_int pcr;

	cache_alias_dist = max(
	    CACHEINFO.ic_totalsize / CACHEINFO.ic_associativity,
	    CACHEINFO.dc_totalsize / CACHEINFO.dc_associativity);
	cache_alias_bits = (cache_alias_dist - 1) & ~PGOFSET;

	pcr = lda(SRMMU_PCR, ASI_SRMMU);

	/* We "flash-clear" the I/D caches. */
	if ((pcr & MS1_PCR_ICE) == 0)
		sta(0, ASI_ICACHECLR, 0);
	if ((pcr & MS1_PCR_DCE) == 0)
		sta(0, ASI_DCACHECLR, 0);

	/* Turn on caches */
	sta(SRMMU_PCR, ASI_SRMMU, pcr | MS1_PCR_DCE | MS1_PCR_ICE);

	CACHEINFO.c_enabled = CACHEINFO.dc_enabled = 1;

	/*
	 * When zeroing or copying pages, there might still be entries in
	 * the cache, since we don't flush pages from the cache when
	 * unmapping them (`vactype' is VAC_NONE).  Fortunately, the
	 * MS1 cache is write-through and not write-allocate, so we can
	 * use cacheable accesses while not displacing cache lines.
	 */
	cpuinfo.flags |= CPUFLG_CACHE_MANDATORY;

	printf("cache enabled\n");
}

void
viking_cache_enable()
{
	u_int pcr;

	cache_alias_dist = max(
		CACHEINFO.ic_totalsize / CACHEINFO.ic_associativity,
		CACHEINFO.dc_totalsize / CACHEINFO.dc_associativity);
	cache_alias_bits = (cache_alias_dist - 1) & ~PGOFSET;

	pcr = lda(SRMMU_PCR, ASI_SRMMU);

	if ((pcr & VIKING_PCR_ICE) == 0) {
		/* I-cache not on; "flash-clear" it now. */
		sta(0x80000000, ASI_ICACHECLR, 0);	/* Unlock */
		sta(0, ASI_ICACHECLR, 0);		/* clear */
	}
	if ((pcr & VIKING_PCR_DCE) == 0) {
		/* D-cache not on: "flash-clear" it. */
		sta(0x80000000, ASI_DCACHECLR, 0);
		sta(0, ASI_DCACHECLR, 0);
	}

	/* Turn on caches via MMU */
	sta(SRMMU_PCR, ASI_SRMMU, pcr | VIKING_PCR_DCE | VIKING_PCR_ICE);

	CACHEINFO.c_enabled = CACHEINFO.dc_enabled = 1;

	/* Now turn on MultiCache if it exists */
	if (cpuinfo.mxcc && CACHEINFO.ec_totalsize > 0) {
		/* Multicache controller */
		stda(MXCC_ENABLE_ADDR, ASI_CONTROL,
		     ldda(MXCC_ENABLE_ADDR, ASI_CONTROL) |
		     (u_int64_t)MXCC_ENABLE_BIT);
		cpuinfo.flags |= CPUFLG_CACHEPAGETABLES; /* Ok to cache PTEs */
		CACHEINFO.ec_enabled = 1;
	}
	printf("cache enabled\n");
}

void
hypersparc_cache_enable()
{
	int i, ls, ts;
	u_int pcr, v;
	extern u_long dvma_cachealign;

	ls = CACHEINFO.c_linesize;
	ts = CACHEINFO.c_totalsize;

	pcr = lda(SRMMU_PCR, ASI_SRMMU);

	/*
	 * Setup the anti-aliasing constants and DVMA alignment constraint.
	 */
	cache_alias_dist = CACHEINFO.c_totalsize;
	cache_alias_bits = (cache_alias_dist - 1) & ~PGOFSET;
	dvma_cachealign = cache_alias_dist;

	/* Now reset cache tag memory if cache not yet enabled */
	if ((pcr & HYPERSPARC_PCR_CE) == 0)
		for (i = 0; i < ts; i += ls) {
			sta(i, ASI_DCACHETAG, 0);
			while (lda(i, ASI_DCACHETAG))
				sta(i, ASI_DCACHETAG, 0);
		}

	pcr &= ~(HYPERSPARC_PCR_CE | HYPERSPARC_PCR_CM);

	hypersparc_cache_flush_all();

	pcr |= HYPERSPARC_PCR_CE;
	if (CACHEINFO.c_vactype == VAC_WRITEBACK)
		pcr |= HYPERSPARC_PCR_CM;

	sta(SRMMU_PCR, ASI_SRMMU, pcr);
	CACHEINFO.c_enabled = 1;

	/* XXX: should add support */
	if (CACHEINFO.c_hwflush)
		panic("cache_enable: can't handle 4M with hw-flush cache");

#ifdef notyet
	/*
	 * Enable instruction cache and, on single-processor machines,
	 * disable `Unimplemented Flush Traps'.
	 */
	v = HYPERSPARC_ICCR_ICE | (ncpu == 1 ? HYPERSPARC_ICCR_FTD : 0);
#else
	v = HYPERSPARC_ICCR_FTD | HYPERSPARC_ICCR_ICE;
#endif
	wrasr(v, HYPERSPARC_ASRNUM_ICCR);

	printf("cache enabled\n");
}

void
swift_cache_enable()
{
	int i, ls, ts;
	u_int pcr;

	cache_alias_dist = max(
		CACHEINFO.ic_totalsize / CACHEINFO.ic_associativity,
		CACHEINFO.dc_totalsize / CACHEINFO.dc_associativity);
	cache_alias_bits = (cache_alias_dist - 1) & ~PGOFSET;

	pcr = lda(SRMMU_PCR, ASI_SRMMU);
	pcr |= (SWIFT_PCR_ICE | SWIFT_PCR_DCE);
	sta(SRMMU_PCR, ASI_SRMMU, pcr);

	/* Now reset cache tag memory if cache not yet enabled */
	ls = CACHEINFO.ic_linesize;
	ts = CACHEINFO.ic_totalsize;
	if ((pcr & SWIFT_PCR_ICE) == 0)
		for (i = 0; i < ts; i += ls)
			sta(i, ASI_ICACHETAG, 0);

	ls = CACHEINFO.dc_linesize;
	ts = CACHEINFO.dc_totalsize;
	if ((pcr & SWIFT_PCR_DCE) == 0)
		for (i = 0; i < ts; i += ls) {
			sta(i, ASI_DCACHETAG, 0);
			while (lda(i, ASI_DCACHETAG))
				sta(i, ASI_DCACHETAG, 0);
		}

	CACHEINFO.c_enabled = 1;
	printf("cache enabled\n");
}

void
cypress_cache_enable()
{
	int i, ls, ts;
	u_int pcr;
	extern u_long dvma_cachealign;

	cache_alias_dist = CACHEINFO.c_totalsize;
	cache_alias_bits = (cache_alias_dist - 1) & ~PGOFSET;
	dvma_cachealign = cache_alias_dist;

	pcr = lda(SRMMU_PCR, ASI_SRMMU);
	pcr &= ~CYPRESS_PCR_CM;

	/* Now reset cache tag memory if cache not yet enabled */
	if ((pcr & CYPRESS_PCR_CE) == 0) {
		ls = CACHEINFO.c_linesize;
		ts = CACHEINFO.c_totalsize;
		for (i = 0; i < ts; i += ls)
			sta(i, ASI_DCACHETAG, 0);
		pcr |= CYPRESS_PCR_CE;
	}

	/* If put in write-back mode, turn it on */
	if (CACHEINFO.c_vactype == VAC_WRITEBACK)
		pcr |= CYPRESS_PCR_CM;

	sta(SRMMU_PCR, ASI_SRMMU, pcr);
	CACHEINFO.c_enabled = 1;
	printf("cache enabled\n");
}

void
turbosparc_cache_enable()
{
	int i, ls, ts;
	u_int pcr, pcf;

	cache_alias_dist = max(
		CACHEINFO.ic_totalsize / CACHEINFO.ic_associativity,
		CACHEINFO.dc_totalsize / CACHEINFO.dc_associativity);
	cache_alias_bits = (cache_alias_dist - 1) & ~PGOFSET;

	pcr = lda(SRMMU_PCR, ASI_SRMMU);

	/* Now reset cache tag memory if cache not yet enabled */
	ls = CACHEINFO.ic_linesize;
	ts = CACHEINFO.ic_totalsize;
	if ((pcr & TURBOSPARC_PCR_ICE) == 0)
		for (i = 0; i < ts; i += ls)
			sta(i, ASI_ICACHETAG, 0);

	ls = CACHEINFO.dc_linesize;
	ts = CACHEINFO.dc_totalsize;
	if ((pcr & TURBOSPARC_PCR_DCE) == 0)
		for (i = 0; i < ts; i += ls) {
			sta(i, ASI_DCACHETAG, 0);
			while (lda(i, ASI_DCACHETAG))
				sta(i, ASI_DCACHETAG, 0);
		}

	pcr |= (TURBOSPARC_PCR_ICE | TURBOSPARC_PCR_DCE);
	sta(SRMMU_PCR, ASI_SRMMU, pcr);

	pcf = lda(SRMMU_PCFG, ASI_SRMMU);
	if (pcf & TURBOSPARC_PCFG_SNP)
		printf("DVMA coherent ");

	CACHEINFO.c_enabled = 1;
	printf("cache enabled\n");
}
#endif /* defined(SUN4M) */

#if defined(SUN4) || defined(SUN4C) || defined(SUN4E)
/*
 * Flush the current context from the cache.
 *
 * This is done by writing to each cache line in the `flush context'
 * address space (or, for hardware flush, once to each page in the
 * hardware flush space, for all cache pages).
 */
void
sun4_vcache_flush_context()
{
	char *p;
	int i, ls;

	cachestats.cs_ncxflush++;
	p = (char *)0;	/* addresses 0..cacheinfo.c_totalsize will do fine */
	if (CACHEINFO.c_hwflush) {
		ls = NBPG;
		i = CACHEINFO.c_totalsize >> PGSHIFT;
		for (; --i >= 0; p += ls)
			sta(p, ASI_HWFLUSHCTX, 0);
	} else {
		ls = CACHEINFO.c_linesize;
		i = CACHEINFO.c_totalsize >> CACHEINFO.c_l2linesize;
		for (; --i >= 0; p += ls)
			sta(p, ASI_FLUSHCTX, 0);
	}
}

/*
 * Flush the given virtual region from the cache.
 *
 * This is also done by writing to each cache line, except that
 * now the addresses must include the virtual region number, and
 * we use the `flush region' space.
 *
 * This function is only called on sun4's with 3-level MMUs; there's
 * no hw-flush space.
 */
void
sun4_vcache_flush_region(vreg)
	int vreg;
{
	int i, ls;
	char *p;

	cachestats.cs_nrgflush++;
	p = (char *)VRTOVA(vreg);	/* reg..reg+sz rather than 0..sz */
	ls = CACHEINFO.c_linesize;
	i = CACHEINFO.c_totalsize >> CACHEINFO.c_l2linesize;
	for (; --i >= 0; p += ls)
		sta(p, ASI_FLUSHREG, 0);
}

/*
 * Flush the given virtual segment from the cache.
 *
 * This is also done by writing to each cache line, except that
 * now the addresses must include the virtual segment number, and
 * we use the `flush segment' space.
 *
 * Again, for hardware, we just write each page (in hw-flush space).
 */
void
sun4_vcache_flush_segment(vreg, vseg)
	int vreg, vseg;
{
	int i, ls;
	char *p;

	cachestats.cs_nsgflush++;
	p = (char *)VSTOVA(vreg, vseg);	/* seg..seg+sz rather than 0..sz */
	if (CACHEINFO.c_hwflush) {
		ls = NBPG;
		i = CACHEINFO.c_totalsize >> PGSHIFT;
		for (; --i >= 0; p += ls)
			sta(p, ASI_HWFLUSHSEG, 0);
	} else {
		ls = CACHEINFO.c_linesize;
		i = CACHEINFO.c_totalsize >> CACHEINFO.c_l2linesize;
		for (; --i >= 0; p += ls)
			sta(p, ASI_FLUSHSEG, 0);
	}
}

/*
 * Flush the given virtual page from the cache.
 * (va is the actual address, and must be aligned on a page boundary.)
 * Again we write to each cache line.
 */
void
sun4_vcache_flush_page(va)
	int va;
{
	int i, ls;
	char *p;

#ifdef DEBUG
	if (va & PGOFSET)
		panic("cache_flush_page: asked to flush misaligned va 0x%x",va);
#endif

	cachestats.cs_npgflush++;
	p = (char *)va;
	if (CACHEINFO.c_hwflush)
		sta(p, ASI_HWFLUSHPG, 0);
	else {
		ls = CACHEINFO.c_linesize;
		i = NBPG >> CACHEINFO.c_l2linesize;
		for (; --i >= 0; p += ls)
			sta(p, ASI_FLUSHPG, 0);
	}
}

/*
 * Flush a range of virtual addresses (in the current context).
 * The first byte is at (base&~PGOFSET) and the last one is just
 * before byte (base+len).
 *
 * We choose the best of (context,segment,page) here.
 */

#define CACHE_FLUSH_MAGIC	(CACHEINFO.c_totalsize / NBPG)

void
sun4_cache_flush(base, len)
	caddr_t base;
	u_int len;
{
	int i, ls, baseoff;
	char *p;

	if (CACHEINFO.c_vactype == VAC_NONE)
		return;

	/*
	 * Figure out how much must be flushed.
	 *
	 * If we need to do CACHE_FLUSH_MAGIC pages,  we can do a segment
	 * in the same number of loop iterations.  We can also do the whole
	 * region. If we need to do between 2 and NSEGRG, do the region.
	 * If we need to do two or more regions, just go ahead and do the
	 * whole context. This might not be ideal (e.g., fsck likes to do
	 * 65536-byte reads, which might not necessarily be aligned).
	 *
	 * We could try to be sneaky here and use the direct mapping
	 * to avoid flushing things `below' the start and `above' the
	 * ending address (rather than rounding to whole pages and
	 * segments), but I did not want to debug that now and it is
	 * not clear it would help much.
	 *
	 * (XXX the magic number 16 is now wrong, must review policy)
	 */
	baseoff = (int)base & PGOFSET;
	i = (baseoff + len + PGOFSET) >> PGSHIFT;

	cachestats.cs_nraflush++;
#ifdef notyet
	cachestats.cs_ra[min(i, MAXCACHERANGE)]++;
#endif

	if (i < CACHE_FLUSH_MAGIC) {
		/* cache_flush_page, for i pages */
		p = (char *)((int)base & ~baseoff);
		if (CACHEINFO.c_hwflush) {
			for (; --i >= 0; p += NBPG)
				sta(p, ASI_HWFLUSHPG, 0);
		} else {
			ls = CACHEINFO.c_linesize;
			i <<= PGSHIFT - CACHEINFO.c_l2linesize;
			for (; --i >= 0; p += ls)
				sta(p, ASI_FLUSHPG, 0);
		}
		return;
	}
	baseoff = (u_int)base & SGOFSET;
	i = (baseoff + len + SGOFSET) >> SGSHIFT;
	if (i == 1)
		sun4_vcache_flush_segment(VA_VREG(base), VA_VSEG(base));
	else {
		if (HASSUN4_MMU3L) {
			baseoff = (u_int)base & RGOFSET;
			i = (baseoff + len + RGOFSET) >> RGSHIFT;
			if (i == 1)
				sun4_vcache_flush_region(VA_VREG(base));
			else
				sun4_vcache_flush_context();
		} else
			sun4_vcache_flush_context();
	}
}
#endif /* SUN4 || SUN4C || SUN4E */

#if defined(SUN4M)
/*
 * Flush the current context from the cache.
 *
 * This is done by writing to each cache line in the `flush context'
 * address space (or, for hardware flush, once to each page in the
 * hardware flush space, for all cache pages).
 */
void
srmmu_vcache_flush_context()
{
	char *p;
	int i, ls;

	cachestats.cs_ncxflush++;
	p = (char *)0;	/* addresses 0..cacheinfo.c_totalsize will do fine */
	ls = CACHEINFO.c_linesize;
	i = CACHEINFO.c_totalsize >> CACHEINFO.c_l2linesize;
	for (; --i >= 0; p += ls)
		sta(p, ASI_IDCACHELFC, 0);
}

/*
 * Flush the given virtual region from the cache.
 *
 * This is also done by writing to each cache line, except that
 * now the addresses must include the virtual region number, and
 * we use the `flush region' space.
 */
void
srmmu_vcache_flush_region(vreg)
	int vreg;
{
	int i, ls;
	char *p;

	cachestats.cs_nrgflush++;
	p = (char *)VRTOVA(vreg);	/* reg..reg+sz rather than 0..sz */
	ls = CACHEINFO.c_linesize;
	i = CACHEINFO.c_totalsize >> CACHEINFO.c_l2linesize;
	for (; --i >= 0; p += ls)
		sta(p, ASI_IDCACHELFR, 0);
}

/*
 * Flush the given virtual segment from the cache.
 *
 * This is also done by writing to each cache line, except that
 * now the addresses must include the virtual segment number, and
 * we use the `flush segment' space.
 *
 * Again, for hardware, we just write each page (in hw-flush space).
 */
void
srmmu_vcache_flush_segment(vreg, vseg)
	int vreg, vseg;
{
	int i, ls;
	char *p;

	cachestats.cs_nsgflush++;
	p = (char *)VSTOVA(vreg, vseg);	/* seg..seg+sz rather than 0..sz */
	ls = CACHEINFO.c_linesize;
	i = CACHEINFO.c_totalsize >> CACHEINFO.c_l2linesize;
	for (; --i >= 0; p += ls)
		sta(p, ASI_IDCACHELFS, 0);
}

/*
 * Flush the given virtual page from the cache.
 * (va is the actual address, and must be aligned on a page boundary.)
 * Again we write to each cache line.
 */
void
srmmu_vcache_flush_page(va)
	int va;
{
	int i, ls;
	char *p;

#ifdef DEBUG
	if (va & PGOFSET)
		panic("cache_flush_page: asked to flush misaligned va 0x%x",va);
#endif

	cachestats.cs_npgflush++;
	p = (char *)va;
	ls = CACHEINFO.c_linesize;
	i = NBPG >> CACHEINFO.c_l2linesize;
	for (; --i >= 0; p += ls)
		sta(p, ASI_IDCACHELFP, 0);
}

void
srmmu_cache_flush_all()
{
	srmmu_vcache_flush_context();
}

/*
 * Flush a range of virtual addresses (in the current context).
 * The first byte is at (base&~PGOFSET) and the last one is just
 * before byte (base+len).
 *
 * We choose the best of (context,segment,page) here.
 */

#define CACHE_FLUSH_MAGIC	(CACHEINFO.c_totalsize / NBPG)

void
srmmu_cache_flush(base, len)
	caddr_t base;
	u_int len;
{
	int i, ls, baseoff;
	char *p;

	/*
	 * Figure out how much must be flushed.
	 *
	 * If we need to do CACHE_FLUSH_MAGIC pages,  we can do a segment
	 * in the same number of loop iterations.  We can also do the whole
	 * region. If we need to do between 2 and NSEGRG, do the region.
	 * If we need to do two or more regions, just go ahead and do the
	 * whole context. This might not be ideal (e.g., fsck likes to do
	 * 65536-byte reads, which might not necessarily be aligned).
	 *
	 * We could try to be sneaky here and use the direct mapping
	 * to avoid flushing things `below' the start and `above' the
	 * ending address (rather than rounding to whole pages and
	 * segments), but I did not want to debug that now and it is
	 * not clear it would help much.
	 *
	 * (XXX the magic number 16 is now wrong, must review policy)
	 */
	baseoff = (int)base & PGOFSET;
	i = (baseoff + len + PGOFSET) >> PGSHIFT;

	cachestats.cs_nraflush++;
#ifdef notyet
	cachestats.cs_ra[min(i, MAXCACHERANGE)]++;
#endif

	if (i < CACHE_FLUSH_MAGIC) {
		/* cache_flush_page, for i pages */
		p = (char *)((int)base & ~baseoff);
		ls = CACHEINFO.c_linesize;
		i <<= PGSHIFT - CACHEINFO.c_l2linesize;
		for (; --i >= 0; p += ls)
			sta(p, ASI_IDCACHELFP, 0);
		return;
	}
	baseoff = (u_int)base & SGOFSET;
	i = (baseoff + len + SGOFSET) >> SGSHIFT;
	if (i == 1)
		srmmu_vcache_flush_segment(VA_VREG(base), VA_VSEG(base));
	else {
		baseoff = (u_int)base & RGOFSET;
		i = (baseoff + len + RGOFSET) >> RGSHIFT;
		if (i == 1)
			srmmu_vcache_flush_region(VA_VREG(base));
		else
			srmmu_vcache_flush_context();
	}
}

#ifndef	MS1_CACHEFLUSH_MAGIC
#define	MS1_CACHEFLUSH_MAGIC	0 /* 48 */
#endif
void
ms1_cache_flush(base, len)
	caddr_t base;
	u_int len;
{
	/*
	 * Although physically tagged, we still need to flush the
	 * data cache after (if we have a write-through cache) or before
	 * (in case of write-back caches) DMA operations.
	 */
#if MS1_CACHEFLUSH_MAGIC != 0
	if (len <= MS1_CACHEFLUSH_MAGIC) {
		/*
		 * If the range to be flushed is sufficiently small
		 * invalidate the covered cache lines by hand.
		 *
		 * The MicroSPARC I has a direct-mapped virtually addressed
		 * physically tagged data cache which is organised as
		 * 128 lines of 16 bytes. Virtual address bits [4-10]
		 * select the cache line. The cache tags are accessed
		 * through the standard DCACHE control space using the
		 * same address bits as those used to select the cache
		 * line in the virtual address.
		 *
		 * Note: we don't bother to compare the actual tags
		 * since that would require looking up physical addresses.
		 *
		 * The format of the tags we read from ASI_DCACHE control
		 * space is:
		 *
		 * 31     27 26            11 10         1 0
		 * +--------+----------------+------------+-+
		 * |  xxx   |    PA[26-11]   |    xxx     |V|
		 * +--------+----------------+------------+-+
		 *
		 * PA: bits 11-26 of the physical address
		 * V:  line valid bit
		 */
		int tagaddr = ((u_int)base & 0x7f0);

		len = roundup(len, 16);
		while (len != 0) {
			int tag = lda(tagaddr, ASI_DCACHETAG);
			if ((tag & 1) == 1) {
				/* Mark this cache line invalid */
				sta(tagaddr, ASI_DCACHETAG, 0);
			}
			len -= 16;
			tagaddr = (tagaddr + 16) & 0x7f0;
		}
	} else
#endif
		/* Flush entire data cache */
		sta(0, ASI_DCACHECLR, 0);
}

/*
 * Flush entire cache.
 */
void
ms1_cache_flush_all()
{

	/* Flash-clear both caches */
	sta(0, ASI_ICACHECLR, 0);
	sta(0, ASI_DCACHECLR, 0);
}

void
hypersparc_cache_flush_all()
{

	srmmu_vcache_flush_context();
	/* Flush instruction cache */
	hypersparc_pure_vcache_flush();
}

void
cypress_cache_flush_all()
{
	extern char kernel_text[];
	char *p;
	int i, ls;

	/* Fill the cache with known read-only content */
	p = (char *)kernel_text;
	ls = CACHEINFO.c_linesize;
	i = CACHEINFO.c_totalsize >> CACHEINFO.c_l2linesize;
	for (; --i >= 0; p += ls)
		(*(volatile char *)p);
}

void
viking_cache_flush(base, len)
	caddr_t base;
	u_int len;
{
	/*
	 * Although physically tagged, we still need to flush the
	 * data cache after (if we have a write-through cache) or before
	 * (in case of write-back caches) DMA operations.
	 */

}

void
viking_pcache_flush_line(va, pa)
	int va;
	int pa;
{
	/*
	 * Flush cache line corresponding to virtual address `va'
	 * which is mapped at physical address `pa'.
	 */
	extern char etext[];
	static char *base;
	int i;
	char *v;

	/*
	 * Construct a virtual address that hits the same cache line
	 * as PA, then read from 2*ASSOCIATIVITY-1 different physical
	 * locations (all different from PA).
	 */

#if 0
	if (base == 0) {
		cshift = CACHEINFO.ic_l2linesize;
		csize = CACHEINFO.ic_nlines << cshift;
		cmask = csize - 1;
		base = (char *)roundup((int)etext, csize);
	}

	v = base + (((va & cmask) >> cshift) << cshift);
	i = CACHEINFO.dc_associativity * 2 - 1;

	while (i--) {
		(*(volatile int *)v);
		v += csize;
	}
#else
#define cshift	5			/* CACHEINFO.ic_l2linesize */
#define csize	(128 << cshift)		/* CACHEINFO.ic_nlines << cshift */
#define cmask	(csize - 1)
#define cass	4			/* CACHEINFO.dc_associativity */

	if (base == 0)
		base = (char *)roundup((unsigned int)etext, csize);

	v = base + (((pa & cmask) >> cshift) << cshift);
	i = 2 * cass - 1;

	while (i--) {
		(*(volatile int *)v);
		v += csize;
	}
#undef cass
#undef cmask
#undef csize
#undef cshift
#endif
}

void
srmmu_pcache_flush_line(va, pa)
	int va;
	int pa;
{
	/*
	 * Flush cache line corresponding to virtual address `va'
	 * which is mapped at physical address `pa'.
	 */
	sta(va, ASI_IDCACHELFP, 0);
}
#endif /* SUN4M */

#if defined(solbourne)
void
kap_cache_enable()
{
	kap_cache_flush(NULL, 0);
	sta(0, ASI_ICACHE_INVAL, 0);

	sta(ICU_CONF, ASI_PHYS_IO,
	    lda(ICU_CONF, ASI_PHYS_IO) & ~CONF_ICACHE_DISABLE);
	CACHEINFO.c_enabled = 1;

	printf("cache enabled\n");
}

void
kap_vcache_flush_context()
{
	kap_cache_flush(0, 0);
	sta(0, ASI_DCACHE_INVAL, 0);
	sta(0, ASI_ICACHE_INVAL, 0);
}

void
kap_vcache_flush_page(va)
	int va;
{
	kap_cache_flush((caddr_t)va, PAGE_SIZE);
}

void
kap_cache_flush(base, len)
	caddr_t base;
	u_int len;
{
	u_int line;
	u_int32_t mmcr;

	/*
	 * Due to the small size of the data cache and the fact that we
	 * would be flushing 4 bytes by 4 bytes, it is faster to flush
	 * the whole cache instead.
	 */

	mmcr = lda(0, ASI_MMCR) & ~(MMCR_DSET0 | MMCR_DSET1);
	/* flush bank 0 */
	sta(0, ASI_MMCR, mmcr | MMCR_DSET0);
	for (line = 0; line < DCACHE_LINE(DCACHE_LINES); line += DCACHE_INCR)
		(void)lda(line, ASI_DCACHE_FLUSH);
	/* flush bank 1 */
	sta(0, ASI_MMCR, mmcr | MMCR_DSET1);
	for (line = 0; line < DCACHE_LINE(DCACHE_LINES); line += DCACHE_INCR)
		(void)lda(line, ASI_DCACHE_FLUSH);
}

#endif	/* solbourne */


code:
/*	$OpenBSD: cache.h,v 1.12 2015/01/11 21:24:32 miod Exp $	*/
/*	$NetBSD: cache.h,v 1.16 1997/07/06 21:15:14 pk Exp $ */

/*
 * Copyright (c) 1996
 * 	The President and Fellows of Harvard College. All rights reserved.
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This software was developed by the Computer Systems Engineering group
 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
 * contributed to Berkeley.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Aaron Brown and
 *	Harvard University.
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. 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.
 *
 *	@(#)cache.h	8.1 (Berkeley) 6/11/93
 */

#ifndef SPARC_CACHE_H
#define SPARC_CACHE_H

/*
 * Sun-4 and Sun-4c virtual address cache.
 *
 * Sun-4 virtual caches come in two flavors, write-through (Sun-4c)
 * and write-back (Sun-4).  The write-back caches are much faster
 * but require a bit more care.
 *
 */
enum vactype { VAC_UNKNOWN, VAC_NONE, VAC_WRITETHROUGH, VAC_WRITEBACK };

/*
 * Cache tags can be written in control space, and must be set to 0
 * (or invalid anyway) before turning on the cache.  The tags are
 * addressed as an array of 32-bit structures of the form:
 *
 *	struct cache_tag {
 *		u_int	:7,		(unused; must be zero)
 *			ct_cid:3,	(context ID)
 *			ct_w:1,		(write flag from PTE)
 *			ct_s:1,		(supervisor flag from PTE)
 *			ct_v:1,		(set => cache entry is valid)
 *			:3,		(unused; must be zero)
 *			ct_tid:14,	(cache tag ID)
 *			:2;		(unused; must be zero)
 *	};
 *
 * The SPARCstation 1 cache sees virtual addresses as:
 *
 *	struct cache_va {
 *		u_int	:2,		(unused; probably copies of va_tid<13>)
 *			cva_tid:14,	(tag ID)
 *			cva_line:12,	(cache line number)
 *			cva_byte:4;	(byte in cache line)
 *	};
 *
 * (The SS2 cache is similar but has half as many lines, each twice as long.)
 *
 * Note that, because the 12-bit line ID is `wider' than the page offset,
 * it is possible to have one page map to two different cache lines.
 * This can happen whenever two different physical pages have the same bits
 * in the part of the virtual address that overlaps the cache line ID, i.e.,
 * bits <15:12>.  In order to prevent cache duplication, we have to
 * make sure that no one page has more than one virtual address where
 * (va1 & 0xf000) != (va2 & 0xf000).  (The cache hardware turns off ct_v
 * when a cache miss occurs on a write, i.e., if va1 is in the cache and
 * va2 is not, and you write to va2, va1 goes out of the cache.  If va1
 * is in the cache and va2 is not, reading va2 also causes va1 to become
 * uncached, and the [same] data is then read from main memory into the
 * cache.)
 *
 * The other alternative, of course, is to disable caching of aliased
 * pages.  (In a few cases this might be faster anyway, but we do it
 * only when forced.)
 *
 * The Sun4, since it has an 8K pagesize instead of 4K, needs to check
 * bits that are one position higher.
 */

/* Some more well-known values: */

#define	CACHE_ALIAS_DIST_SUN4	0x20000
#define	CACHE_ALIAS_DIST_SUN4C	0x10000

#define	CACHE_ALIAS_BITS_SUN4	0x1e000
#define	CACHE_ALIAS_BITS_SUN4C	0xf000

extern int cache_alias_dist;
extern int cache_alias_bits;

/* Optimize cache alias macros on single architecture kernels */
#if (defined(SUN4) || defined(SUN4E)) && !(defined(SUN4C) || defined(SUN4D) || defined(SUN4M))
#define	CACHE_ALIAS_DIST	CACHE_ALIAS_DIST_SUN4
#define	CACHE_ALIAS_BITS	CACHE_ALIAS_BITS_SUN4
#elif !(defined(SUN4) || defined(SUN4E)) && defined(SUN4C) && !(defined(SUN4D) || defined(SUN4M))
#define	CACHE_ALIAS_DIST	CACHE_ALIAS_DIST_SUN4C
#define	CACHE_ALIAS_BITS	CACHE_ALIAS_BITS_SUN4C
#else
#define	CACHE_ALIAS_DIST	cache_alias_dist
#define	CACHE_ALIAS_BITS	cache_alias_bits
#endif

/*
 * True iff a1 and a2 are `bad' aliases (will cause cache duplication).
 */
#define	BADALIAS(a1, a2) (((int)(a1) ^ (int)(a2)) & CACHE_ALIAS_BITS)

/*
 * Routines for dealing with the cache.
 */
void	sun4_cache_enable(void);		/* turn it on */
void	ms1_cache_enable(void);			/* turn it on */
void	viking_cache_enable(void);		/* turn it on */
void	hypersparc_cache_enable(void);		/* turn it on */
void	swift_cache_enable(void);		/* turn it on */
void	cypress_cache_enable(void);		/* turn it on */
void	turbosparc_cache_enable(void);		/* turn it on */
void	kap_cache_enable(void);			/* turn it on */

void	sun4_vcache_flush_context(void);	/* flush current context */
void	sun4_vcache_flush_region(int);		/* flush region in cur ctx */
void	sun4_vcache_flush_segment(int, int);	/* flush seg in cur ctx */
void	sun4_vcache_flush_page(int va);		/* flush page in cur ctx */
void	sun4_cache_flush(caddr_t, u_int);	/* flush region */

void	srmmu_vcache_flush_context(void);	/* flush current context */
void	srmmu_vcache_flush_region(int);		/* flush region in cur ctx */
void	srmmu_vcache_flush_segment(int, int);	/* flush seg in cur ctx */
void	srmmu_vcache_flush_page(int va);	/* flush page in cur ctx */
void	srmmu_cache_flush(caddr_t, u_int);	/* flush region */
void	hypersparc_pure_vcache_flush(void);

void	ms1_cache_flush_all(void);
void	srmmu_cache_flush_all(void);
void	cypress_cache_flush_all(void);
void	hypersparc_cache_flush_all(void);

void	ms1_cache_flush(caddr_t, u_int);
void	viking_cache_flush(caddr_t, u_int);
void	viking_pcache_flush_line(int, int);
void	srmmu_pcache_flush_line(int, int);

void	kap_vcache_flush_context(void);		/* flush current context */
void	kap_vcache_flush_page(int va);		/* flush page in cur ctx */
void	kap_cache_flush(caddr_t, u_int);	/* flush region */

extern void sparc_noop(void);

#define noop_vcache_flush_context \
	(void (*)(void)) sparc_noop
#define noop_vcache_flush_region \
	(void (*)(int)) sparc_noop
#define noop_vcache_flush_segment \
	(void (*)(int,int)) sparc_noop
#define noop_vcache_flush_page \
	(void (*)(int)) sparc_noop
#define noop_cache_flush \
	(void (*)(caddr_t, u_int)) sparc_noop
#define noop_pcache_flush_line \
	(void (*)(int, int)) sparc_noop
#define noop_pure_vcache_flush \
	(void (*)(void)) sparc_noop
#define noop_cache_flush_all \
	(void (*)(void)) sparc_noop

#define cache_flush_page(va)		cpuinfo.vcache_flush_page(va)
#define cache_flush_segment(vr,vs)	cpuinfo.vcache_flush_segment(vr,vs)
#define cache_flush_region(vr)		cpuinfo.vcache_flush_region(vr)
#define cache_flush_context()		cpuinfo.vcache_flush_context()

/*
 * Cache control information.
 */
struct cacheinfo {
	int	c_totalsize;		/* total size, in bytes */
					/* if split, MAX(icache,dcache) */
	int	c_enabled;		/* true => cache is enabled */
	int	c_hwflush;		/* true => have hardware flush */
	int	c_linesize;		/* line size, in bytes */
	int	c_l2linesize;		/* log2(linesize) */
	int	c_nlines;		/* number of cache lines */
	int	c_physical;		/* true => cache has physical
						   address tags */
	int 	c_associativity;	/* # of "buckets" in cache line */
	int 	c_split;		/* true => cache is split */

	int 	ic_totalsize;		/* instruction cache */
	int 	ic_enabled;
	int 	ic_linesize;
	int 	ic_l2linesize;
	int 	ic_nlines;
	int 	ic_associativity;

	int 	dc_totalsize;		/* data cache */
	int 	dc_enabled;
	int 	dc_linesize;
	int 	dc_l2linesize;
	int 	dc_nlines;
	int 	dc_associativity;

	int	ec_totalsize;		/* external cache info */
	int 	ec_enabled;
	int	ec_linesize;
	int	ec_l2linesize;
	int 	ec_nlines;
	int 	ec_associativity;

	enum vactype	c_vactype;
};

#define CACHEINFO cpuinfo.cacheinfo

/*
 * Cache control statistics.
 */
struct cachestats {
	int	cs_npgflush;		/* # page flushes */
	int	cs_nsgflush;		/* # seg flushes */
	int	cs_nrgflush;		/* # seg flushes */
	int	cs_ncxflush;		/* # context flushes */
	int	cs_nraflush;		/* # range flushes */
#ifdef notyet
	int	cs_ra[65];		/* pages/range */
#endif
};
#endif /* SPARC_CACHE_H */