Home | History | Annotate | Line # | Download | only in sun3x
pmap.c revision 1.12
      1 /*	$NetBSD: pmap.c,v 1.12 1997/03/02 07:59:21 jeremy Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1996, 1997 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jeremy Cooper.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *        This product includes software developed by the NetBSD
     21  *        Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 /*
     40  * XXX These comments aren't quite accurate.  Need to change.
     41  * The sun3x uses the MC68851 Memory Management Unit, which is built
     42  * into the CPU.  The 68851 maps virtual to physical addresses using
     43  * a multi-level table lookup, which is stored in the very memory that
     44  * it maps.  The number of levels of lookup is configurable from one
     45  * to four.  In this implementation, we use three, named 'A' through 'C'.
     46  *
     47  * The MMU translates virtual addresses into physical addresses by
     48  * traversing these tables in a proccess called a 'table walk'.  The most
     49  * significant 7 bits of the Virtual Address ('VA') being translated are
     50  * used as an index into the level A table, whose base in physical memory
     51  * is stored in a special MMU register, the 'CPU Root Pointer' or CRP.  The
     52  * address found at that index in the A table is used as the base
     53  * address for the next table, the B table.  The next six bits of the VA are
     54  * used as an index into the B table, which in turn gives the base address
     55  * of the third and final C table.
     56  *
     57  * The next six bits of the VA are used as an index into the C table to
     58  * locate a Page Table Entry (PTE).  The PTE is a physical address in memory
     59  * to which the remaining 13 bits of the VA are added, producing the
     60  * mapped physical address.
     61  *
     62  * To map the entire memory space in this manner would require 2114296 bytes
     63  * of page tables per process - quite expensive.  Instead we will
     64  * allocate a fixed but considerably smaller space for the page tables at
     65  * the time the VM system is initialized.  When the pmap code is asked by
     66  * the kernel to map a VA to a PA, it allocates tables as needed from this
     67  * pool.  When there are no more tables in the pool, tables are stolen
     68  * from the oldest mapped entries in the tree.  This is only possible
     69  * because all memory mappings are stored in the kernel memory map
     70  * structures, independent of the pmap structures.  A VA which references
     71  * one of these invalidated maps will cause a page fault.  The kernel
     72  * will determine that the page fault was caused by a task using a valid
     73  * VA, but for some reason (which does not concern it), that address was
     74  * not mapped.  It will ask the pmap code to re-map the entry and then
     75  * it will resume executing the faulting task.
     76  *
     77  * In this manner the most efficient use of the page table space is
     78  * achieved.  Tasks which do not execute often will have their tables
     79  * stolen and reused by tasks which execute more frequently.  The best
     80  * size for the page table pool will probably be determined by
     81  * experimentation.
     82  *
     83  * You read all of the comments so far.  Good for you.
     84  * Now go play!
     85  */
     86 
     87 /*** A Note About the 68851 Address Translation Cache
     88  * The MC68851 has a 64 entry cache, called the Address Translation Cache
     89  * or 'ATC'.  This cache stores the most recently used page descriptors
     90  * accessed by the MMU when it does translations.  Using a marker called a
     91  * 'task alias' the MMU can store the descriptors from 8 different table
     92  * spaces concurrently.  The task alias is associated with the base
     93  * address of the level A table of that address space.  When an address
     94  * space is currently active (the CRP currently points to its A table)
     95  * the only cached descriptors that will be obeyed are ones which have a
     96  * matching task alias of the current space associated with them.
     97  *
     98  * Since the cache is always consulted before any table lookups are done,
     99  * it is important that it accurately reflect the state of the MMU tables.
    100  * Whenever a change has been made to a table that has been loaded into
    101  * the MMU, the code must be sure to flush any cached entries that are
    102  * affected by the change.  These instances are documented in the code at
    103  * various points.
    104  */
    105 /*** A Note About the Note About the 68851 Address Translation Cache
    106  * 4 months into this code I discovered that the sun3x does not have
    107  * a MC68851 chip. Instead, it has a version of this MMU that is part of the
    108  * the 68030 CPU.
    109  * All though it behaves very similarly to the 68851, it only has 1 task
    110  * alias and a 22 entry cache.  So sadly (or happily), the first paragraph
    111  * of the previous note does not apply to the sun3x pmap.
    112  */
    113 
    114 #include <sys/param.h>
    115 #include <sys/systm.h>
    116 #include <sys/proc.h>
    117 #include <sys/malloc.h>
    118 #include <sys/user.h>
    119 #include <sys/queue.h>
    120 
    121 #include <vm/vm.h>
    122 #include <vm/vm_kern.h>
    123 #include <vm/vm_page.h>
    124 
    125 #include <machine/cpu.h>
    126 #include <machine/pmap.h>
    127 #include <machine/pte.h>
    128 #include <machine/machdep.h>
    129 #include <machine/mon.h>
    130 
    131 #include "pmap_pvt.h"
    132 
    133 /* XXX - What headers declare these? */
    134 extern struct pcb *curpcb;
    135 extern int physmem;
    136 
    137 extern void copypage __P((const void*, void*));
    138 extern void zeropage __P((void*));
    139 
    140 /* Defined in locore.s */
    141 extern char kernel_text[];
    142 
    143 /* Defined by the linker */
    144 extern char etext[], edata[], end[];
    145 extern char *esym;	/* DDB */
    146 
    147 /*************************** DEBUGGING DEFINITIONS ***********************
    148  * Macros, preprocessor defines and variables used in debugging can make *
    149  * code hard to read.  Anything used exclusively for debugging purposes  *
    150  * is defined here to avoid having such mess scattered around the file.  *
    151  *************************************************************************/
    152 #ifdef	PMAP_DEBUG
    153 /*
    154  * To aid the debugging process, macros should be expanded into smaller steps
    155  * that accomplish the same goal, yet provide convenient places for placing
    156  * breakpoints.  When this code is compiled with PMAP_DEBUG mode defined, the
    157  * 'INLINE' keyword is defined to an empty string.  This way, any function
    158  * defined to be a 'static INLINE' will become 'outlined' and compiled as
    159  * a separate function, which is much easier to debug.
    160  */
    161 #define	INLINE	/* nothing */
    162 
    163 /*
    164  * It is sometimes convenient to watch the activity of a particular table
    165  * in the system.  The following variables are used for that purpose.
    166  */
    167 a_tmgr_t *pmap_watch_atbl = 0;
    168 b_tmgr_t *pmap_watch_btbl = 0;
    169 c_tmgr_t *pmap_watch_ctbl = 0;
    170 
    171 int pmap_debug = 0;
    172 #define DPRINT(args) if (pmap_debug) printf args
    173 
    174 #else	/********** Stuff below is defined if NOT debugging **************/
    175 
    176 #define	INLINE	inline
    177 #define DPRINT(args)  /* nada */
    178 
    179 #endif	/* PMAP_DEBUG */
    180 /*********************** END OF DEBUGGING DEFINITIONS ********************/
    181 
    182 /*** Management Structure - Memory Layout
    183  * For every MMU table in the sun3x pmap system there must be a way to
    184  * manage it; we must know which process is using it, what other tables
    185  * depend on it, and whether or not it contains any locked pages.  This
    186  * is solved by the creation of 'table management'  or 'tmgr'
    187  * structures.  One for each MMU table in the system.
    188  *
    189  *                        MAP OF MEMORY USED BY THE PMAP SYSTEM
    190  *
    191  *      towards lower memory
    192  * kernAbase -> +-------------------------------------------------------+
    193  *              | Kernel     MMU A level table                          |
    194  * kernBbase -> +-------------------------------------------------------+
    195  *              | Kernel     MMU B level tables                         |
    196  * kernCbase -> +-------------------------------------------------------+
    197  *              |                                                       |
    198  *              | Kernel     MMU C level tables                         |
    199  *              |                                                       |
    200  * mmuCbase  -> +-------------------------------------------------------+
    201  *              | User       MMU C level tables                         |
    202  * mmuAbase  -> +-------------------------------------------------------+
    203  *              |                                                       |
    204  *              | User       MMU A level tables                         |
    205  *              |                                                       |
    206  * mmuBbase  -> +-------------------------------------------------------+
    207  *              | User       MMU B level tables                         |
    208  * tmgrAbase -> +-------------------------------------------------------+
    209  *              |  TMGR A level table structures                        |
    210  * tmgrBbase -> +-------------------------------------------------------+
    211  *              |  TMGR B level table structures                        |
    212  * tmgrCbase -> +-------------------------------------------------------+
    213  *              |  TMGR C level table structures                        |
    214  * pvbase    -> +-------------------------------------------------------+
    215  *              |  Physical to Virtual mapping table (list heads)       |
    216  * pvebase   -> +-------------------------------------------------------+
    217  *              |  Physical to Virtual mapping table (list elements)    |
    218  *              |                                                       |
    219  *              +-------------------------------------------------------+
    220  *      towards higher memory
    221  *
    222  * For every A table in the MMU A area, there will be a corresponding
    223  * a_tmgr structure in the TMGR A area.  The same will be true for
    224  * the B and C tables.  This arrangement will make it easy to find the
    225  * controling tmgr structure for any table in the system by use of
    226  * (relatively) simple macros.
    227  */
    228 
    229 /*
    230  * Global variables for storing the base addresses for the areas
    231  * labeled above.
    232  */
    233 static vm_offset_t  	kernAphys;
    234 static mmu_long_dte_t	*kernAbase;
    235 static mmu_short_dte_t	*kernBbase;
    236 static mmu_short_pte_t	*kernCbase;
    237 static mmu_long_dte_t	*mmuAbase;
    238 static mmu_short_dte_t	*mmuBbase;
    239 static mmu_short_pte_t	*mmuCbase;
    240 static a_tmgr_t		*Atmgrbase;
    241 static b_tmgr_t		*Btmgrbase;
    242 static c_tmgr_t		*Ctmgrbase;
    243 static pv_t		*pvbase;
    244 static pv_elem_t	*pvebase;
    245 struct pmap		kernel_pmap;
    246 
    247 /*
    248  * This holds the CRP currently loaded into the MMU.
    249  */
    250 struct mmu_rootptr kernel_crp;
    251 
    252 /*
    253  * Just all around global variables.
    254  */
    255 static TAILQ_HEAD(a_pool_head_struct, a_tmgr_struct) a_pool;
    256 static TAILQ_HEAD(b_pool_head_struct, b_tmgr_struct) b_pool;
    257 static TAILQ_HEAD(c_pool_head_struct, c_tmgr_struct) c_pool;
    258 
    259 
    260 /*
    261  * Flags used to mark the safety/availability of certain operations or
    262  * resources.
    263  */
    264 static boolean_t
    265     pv_initialized = FALSE,          /* PV system has been initialized. */
    266     tmp_vpages_inuse = FALSE,        /*
    267                                       * Temp. virtual pages are in use.
    268                                       * (see pmap_copy_page, et. al.)
    269                                       */
    270     bootstrap_alloc_enabled = FALSE; /* Safe to use pmap_bootstrap_alloc(). */
    271 
    272 /*
    273  * XXX:  For now, retain the traditional variables that were
    274  * used in the old pmap/vm interface (without NONCONTIG).
    275  */
    276 /* Kernel virtual address space available: */
    277 vm_offset_t	virtual_avail, virtual_end;
    278 /* Physical address space available: */
    279 vm_offset_t	avail_start, avail_end;
    280 
    281 /* This keep track of the end of the contiguously mapped range. */
    282 vm_offset_t virtual_contig_end;
    283 
    284 /* Physical address used by pmap_next_page() */
    285 vm_offset_t avail_next;
    286 
    287 /* These are used by pmap_copy_page(), etc. */
    288 vm_offset_t tmp_vpages[2];
    289 
    290 /*
    291  * The 3/80 is the only member of the sun3x family that has non-contiguous
    292  * physical memory.  Memory is divided into 4 banks which are physically
    293  * locatable on the system board.  Although the size of these banks varies
    294  * with the size of memory they contain, their base addresses are
    295  * permenently fixed.  The following structure, which describes these
    296  * banks, is initialized by pmap_bootstrap() after it reads from a similar
    297  * structure provided by the ROM Monitor.
    298  *
    299  * For the other machines in the sun3x architecture which do have contiguous
    300  * RAM, this list will have only one entry, which will describe the entire
    301  * range of available memory.
    302  */
    303 struct pmap_physmem_struct avail_mem[SUN3X_80_MEM_BANKS];
    304 u_int total_phys_mem;
    305 
    306 /*************************************************************************/
    307 
    308 /*
    309  * XXX - Should "tune" these based on statistics.
    310  *
    311  * My first guess about the relative numbers of these needed is
    312  * based on the fact that a "typical" process will have several
    313  * pages mapped at low virtual addresses (text, data, bss), then
    314  * some mapped shared libraries, and then some stack pages mapped
    315  * near the high end of the VA space.  Each process can use only
    316  * one A table, and most will use only two B tables (maybe three)
    317  * and probably about four C tables.  Therefore, the first guess
    318  * at the relative numbers of these needed is 1:2:4 -gwr
    319  *
    320  * The number of C tables needed is closely related to the amount
    321  * of physical memory available plus a certain amount attributable
    322  * to the use of double mappings.  With a few simulation statistics
    323  * we can find a reasonably good estimation of this unknown value.
    324  * Armed with that and the above ratios, we have a good idea of what
    325  * is needed at each level. -j
    326  *
    327  * Note: It is not physical memory memory size, but the total mapped
    328  * virtual space required by the combined working sets of all the
    329  * currently _runnable_ processes.  (Sleeping ones don't count.)
    330  * The amount of physical memory should be irrelevant. -gwr
    331  */
    332 #define NUM_A_TABLES	16
    333 #define NUM_B_TABLES	32
    334 #define NUM_C_TABLES	64
    335 
    336 /*
    337  * This determines our total virtual mapping capacity.
    338  * Yes, it is a FIXED value so we can pre-allocate.
    339  */
    340 #define NUM_USER_PTES	(NUM_C_TABLES * MMU_C_TBL_SIZE)
    341 #define	NUM_KERN_PTES	\
    342 	(sun3x_btop(VM_MIN_KERNEL_ADDRESS - VM_MAX_KERNEL_ADDRESS))
    343 
    344 /*************************** MISCELANEOUS MACROS *************************/
    345 #define PMAP_LOCK()	;	/* Nothing, for now */
    346 #define PMAP_UNLOCK()	;	/* same. */
    347 #define	NULL 0
    348 
    349 static INLINE void *      mmu_ptov __P((vm_offset_t pa));
    350 static INLINE vm_offset_t mmu_vtop __P((void * va));
    351 
    352 #if	0
    353 static INLINE a_tmgr_t * mmuA2tmgr __P((mmu_long_dte_t *));
    354 #endif
    355 static INLINE b_tmgr_t * mmuB2tmgr __P((mmu_short_dte_t *));
    356 static INLINE c_tmgr_t * mmuC2tmgr __P((mmu_short_pte_t *));
    357 
    358 static INLINE pv_t *pa2pv __P((vm_offset_t pa));
    359 static INLINE int   pteidx __P((mmu_short_pte_t *));
    360 static INLINE pmap_t current_pmap __P((void));
    361 
    362 /*
    363  * We can always convert between virtual and physical addresses
    364  * for anything in the range [KERNBASE ... avail_start] because
    365  * that range is GUARANTEED to be mapped linearly.
    366  * We rely heavily upon this feature!
    367  */
    368 static INLINE void *
    369 mmu_ptov(pa)
    370 	vm_offset_t pa;
    371 {
    372 	register vm_offset_t va;
    373 
    374 	va = (pa + KERNBASE);
    375 #ifdef	PMAP_DEBUG
    376 	if ((va < KERNBASE) || (va >= virtual_contig_end))
    377 		panic("mmu_ptov");
    378 #endif
    379 	return ((void*)va);
    380 }
    381 static INLINE vm_offset_t
    382 mmu_vtop(vva)
    383 	void *vva;
    384 {
    385 	register vm_offset_t va;
    386 
    387 	va = (vm_offset_t)vva;
    388 #ifdef	PMAP_DEBUG
    389 	if ((va < KERNBASE) || (va >= virtual_contig_end))
    390 		panic("mmu_ptov");
    391 #endif
    392 	return (va - KERNBASE);
    393 }
    394 
    395 /*
    396  * These macros map MMU tables to their corresponding manager structures.
    397  * They are needed quite often because many of the pointers in the pmap
    398  * system reference MMU tables and not the structures that control them.
    399  * There needs to be a way to find one when given the other and these
    400  * macros do so by taking advantage of the memory layout described above.
    401  * Here's a quick step through the first macro, mmuA2tmgr():
    402  *
    403  * 1) find the offset of the given MMU A table from the base of its table
    404  *    pool (table - mmuAbase).
    405  * 2) convert this offset into a table index by dividing it by the
    406  *    size of one MMU 'A' table. (sizeof(mmu_long_dte_t) * MMU_A_TBL_SIZE)
    407  * 3) use this index to select the corresponding 'A' table manager
    408  *    structure from the 'A' table manager pool (Atmgrbase[index]).
    409  */
    410 /*  This function is not currently used. */
    411 #if	0
    412 static INLINE a_tmgr_t *
    413 mmuA2tmgr(mmuAtbl)
    414 	mmu_long_dte_t *mmuAtbl;
    415 {
    416 	register int idx;
    417 
    418 	/* Which table is this in? */
    419 	idx = (mmuAtbl - mmuAbase) / MMU_A_TBL_SIZE;
    420 #ifdef	PMAP_DEBUG
    421 	if ((idx < 0) || (idx >= NUM_A_TABLES))
    422 		panic("mmuA2tmgr");
    423 #endif
    424 	return (&Atmgrbase[idx]);
    425 }
    426 #endif	/* 0 */
    427 
    428 static INLINE b_tmgr_t *
    429 mmuB2tmgr(mmuBtbl)
    430 	mmu_short_dte_t *mmuBtbl;
    431 {
    432 	register int idx;
    433 
    434 	/* Which table is this in? */
    435 	idx = (mmuBtbl - mmuBbase) / MMU_B_TBL_SIZE;
    436 #ifdef	PMAP_DEBUG
    437 	if ((idx < 0) || (idx >= NUM_B_TABLES))
    438 		panic("mmuB2tmgr");
    439 #endif
    440 	return (&Btmgrbase[idx]);
    441 }
    442 
    443 /* mmuC2tmgr			INTERNAL
    444  **
    445  * Given a pte known to belong to a C table, return the address of
    446  * that table's management structure.
    447  */
    448 static INLINE c_tmgr_t *
    449 mmuC2tmgr(mmuCtbl)
    450 	mmu_short_pte_t *mmuCtbl;
    451 {
    452 	register int idx;
    453 
    454 	/* Which table is this in? */
    455 	idx = (mmuCtbl - mmuCbase) / MMU_C_TBL_SIZE;
    456 #ifdef	PMAP_DEBUG
    457 	if ((idx < 0) || (idx >= NUM_C_TABLES))
    458 		panic("mmuC2tmgr");
    459 #endif
    460 	return (&Ctmgrbase[idx]);
    461 }
    462 
    463 /* This is now a function call below.
    464  * #define pa2pv(pa) \
    465  *	(&pvbase[(unsigned long)\
    466  *		sun3x_btop(pa)\
    467  *	])
    468  */
    469 
    470 /* pa2pv			INTERNAL
    471  **
    472  * Return the pv_list_head element which manages the given physical
    473  * address.
    474  */
    475 static INLINE pv_t *
    476 pa2pv(pa)
    477 	vm_offset_t pa;
    478 {
    479 	register struct pmap_physmem_struct *bank;
    480 	register int idx;
    481 
    482 	bank = &avail_mem[0];
    483 	while (pa >= bank->pmem_end)
    484 		bank = bank->pmem_next;
    485 
    486 	pa -= bank->pmem_start;
    487 	idx = bank->pmem_pvbase + sun3x_btop(pa);
    488 #ifdef	PMAP_DEBUG
    489 	if ((idx < 0) || (idx >= physmem))
    490 		panic("pa2pv");
    491 #endif
    492 	return &pvbase[idx];
    493 }
    494 
    495 /* pteidx			INTERNAL
    496  **
    497  * Return the index of the given PTE within the entire fixed table of
    498  * PTEs.
    499  */
    500 static INLINE int
    501 pteidx(pte)
    502 	mmu_short_pte_t *pte;
    503 {
    504 	return (pte - kernCbase);
    505 }
    506 
    507 /*
    508  * This just offers a place to put some debugging checks,
    509  * and reduces the number of places "curproc" appears...
    510  */
    511 static INLINE pmap_t
    512 current_pmap()
    513 {
    514 	struct proc *p;
    515 	struct vmspace *vm;
    516 	vm_map_t	map;
    517 	pmap_t	pmap;
    518 
    519 	p = curproc;	/* XXX */
    520 	if (p == NULL)
    521 		pmap = &kernel_pmap;
    522 	else {
    523 		vm = p->p_vmspace;
    524 		map = &vm->vm_map;
    525 		pmap = vm_map_pmap(map);
    526 	}
    527 
    528 	return (pmap);
    529 }
    530 
    531 
    532 /*************************** FUNCTION DEFINITIONS ************************
    533  * These appear here merely for the compiler to enforce type checking on *
    534  * all function calls.                                                   *
    535  *************************************************************************/
    536 
    537 /** External functions
    538  ** - functions used within this module but written elsewhere.
    539  **   both of these functions are in locore.s
    540  ** XXX - These functions were later replaced with their more cryptic
    541  **       hp300 counterparts.  They may be removed now.
    542  **/
    543 #if	0	/* deprecated mmu */
    544 void   mmu_seturp __P((vm_offset_t));
    545 void   mmu_flush __P((int, vm_offset_t));
    546 void   mmu_flusha __P((void));
    547 #endif	/* 0 */
    548 
    549 /** Internal functions
    550  ** - all functions used only within this module are defined in
    551  **   pmap_pvt.h
    552  **/
    553 
    554 /** Interface functions
    555  ** - functions required by the Mach VM Pmap interface, with MACHINE_CONTIG
    556  **   defined.
    557  **/
    558 #ifdef INCLUDED_IN_PMAP_H
    559 void   pmap_bootstrap __P((void));
    560 void  *pmap_bootstrap_alloc __P((int));
    561 void   pmap_enter __P((pmap_t, vm_offset_t, vm_offset_t, vm_prot_t, boolean_t));
    562 pmap_t pmap_create __P((vm_size_t));
    563 void   pmap_destroy __P((pmap_t));
    564 void   pmap_reference __P((pmap_t));
    565 boolean_t   pmap_is_referenced __P((vm_offset_t));
    566 boolean_t   pmap_is_modified __P((vm_offset_t));
    567 void   pmap_clear_modify __P((vm_offset_t));
    568 vm_offset_t pmap_extract __P((pmap_t, vm_offset_t));
    569 void   pmap_activate __P((pmap_t));
    570 int    pmap_page_index __P((vm_offset_t));
    571 u_int  pmap_free_pages __P((void));
    572 #endif /* INCLUDED_IN_PMAP_H */
    573 
    574 /********************************** CODE ********************************
    575  * Functions that are called from other parts of the kernel are labeled *
    576  * as 'INTERFACE' functions.  Functions that are only called from       *
    577  * within the pmap module are labeled as 'INTERNAL' functions.          *
    578  * Functions that are internal, but are not (currently) used at all are *
    579  * labeled 'INTERNAL_X'.                                                *
    580  ************************************************************************/
    581 
    582 /* pmap_bootstrap			INTERNAL
    583  **
    584  * Initializes the pmap system.  Called at boot time from sun3x_vm_init()
    585  * in _startup.c.
    586  *
    587  * Reminder: having a pmap_bootstrap_alloc() and also having the VM
    588  *           system implement pmap_steal_memory() is redundant.
    589  *           Don't release this code without removing one or the other!
    590  */
    591 void
    592 pmap_bootstrap(nextva)
    593 	vm_offset_t nextva;
    594 {
    595 	struct physmemory *membank;
    596 	struct pmap_physmem_struct *pmap_membank;
    597 	vm_offset_t va, pa, eva;
    598 	int b, c, i, j;	/* running table counts */
    599 	int size;
    600 
    601 	/*
    602 	 * This function is called by __bootstrap after it has
    603 	 * determined the type of machine and made the appropriate
    604 	 * patches to the ROM vectors (XXX- I don't quite know what I meant
    605 	 * by that.)  It allocates and sets up enough of the pmap system
    606 	 * to manage the kernel's address space.
    607 	 */
    608 
    609 	/*
    610 	 * Determine the range of kernel virtual and physical
    611 	 * space available. Note that we ABSOLUTELY DEPEND on
    612 	 * the fact that the first bank of memory (4MB) is
    613 	 * mapped linearly to KERNBASE (which we guaranteed in
    614 	 * the first instructions of locore.s).
    615 	 * That is plenty for our bootstrap work.
    616 	 */
    617 	virtual_avail = sun3x_round_page(nextva);
    618 	virtual_contig_end = KERNBASE + 0x400000; /* +4MB */
    619 	virtual_end = VM_MAX_KERNEL_ADDRESS;
    620 	/* Don't need avail_start til later. */
    621 
    622 	/* We may now call pmap_bootstrap_alloc(). */
    623 	bootstrap_alloc_enabled = TRUE;
    624 
    625 	/*
    626 	 * This is a somewhat unwrapped loop to deal with
    627 	 * copying the PROM's 'phsymem' banks into the pmap's
    628 	 * banks.  The following is always assumed:
    629 	 * 1. There is always at least one bank of memory.
    630 	 * 2. There is always a last bank of memory, and its
    631 	 *    pmem_next member must be set to NULL.
    632 	 * XXX - Use: do { ... } while (membank->next) instead?
    633 	 * XXX - Why copy this stuff at all? -gwr
    634 	 *     - It is needed in pa2pv().
    635 	 */
    636 	membank = romVectorPtr->v_physmemory;
    637 	pmap_membank = avail_mem;
    638 	total_phys_mem = 0;
    639 
    640 	while (membank->next) {
    641 		pmap_membank->pmem_start = membank->address;
    642 		pmap_membank->pmem_end = membank->address + membank->size;
    643 		total_phys_mem += membank->size;
    644 		/* This silly syntax arises because pmap_membank
    645 		 * is really a pre-allocated array, but it is put into
    646 		 * use as a linked list.
    647 		 */
    648 		pmap_membank->pmem_next = pmap_membank + 1;
    649 		pmap_membank = pmap_membank->pmem_next;
    650 		membank = membank->next;
    651 	}
    652 
    653 	/*
    654 	 * XXX The last bank of memory should be reduced to exclude the
    655 	 * physical pages needed by the PROM monitor from being used
    656 	 * in the VM system.  XXX - See below - Fix!
    657 	 */
    658 	pmap_membank->pmem_start = membank->address;
    659 	pmap_membank->pmem_end = membank->address + membank->size;
    660 	pmap_membank->pmem_next = NULL;
    661 
    662 #if 0	/* XXX - Need to integrate this! */
    663 	/*
    664 	 * The last few pages of physical memory are "owned" by
    665 	 * the PROM.  The total amount of memory we are allowed
    666 	 * to use is given by the romvec pointer. -gwr
    667 	 *
    668 	 * We should dedicate different variables for 'useable'
    669 	 * and 'physically available'.  Most users are used to the
    670 	 * kernel reporting the amount of memory 'physically available'
    671 	 * as opposed to 'useable by the kernel' at boot time. -j
    672 	 */
    673 	total_phys_mem = *romVectorPtr->memoryAvail;
    674 #endif	/* XXX */
    675 
    676 	total_phys_mem += membank->size;	/* XXX see above */
    677 	physmem = btoc(total_phys_mem);
    678 
    679 	/*
    680 	 * Avail_end is set to the first byte of physical memory
    681 	 * after the end of the last bank.  We use this only to
    682 	 * determine if a physical address is "managed" memory.
    683 	 *
    684 	 * XXX - The setting of avail_end is a temporary ROM saving hack.
    685 	 */
    686 	avail_end = pmap_membank->pmem_end -
    687 		(total_phys_mem - *romVectorPtr->memoryAvail);
    688 	avail_end = sun3x_trunc_page(avail_end);
    689 
    690 	/*
    691 	 * The first step is to allocate MMU tables.
    692 	 * Note: All must be aligned on 256 byte boundaries.
    693 	 *
    694 	 * Start with the top level, or 'A' table.
    695 	 */
    696 	size = sizeof(mmu_long_dte_t) * MMU_A_TBL_SIZE;
    697 	kernAbase = pmap_bootstrap_alloc(size);
    698 	bzero(kernAbase, size);
    699 
    700 	/*
    701 	 * Allocate enough B tables to map from KERNBASE to
    702 	 * the end of VM.
    703 	 */
    704 	size = sizeof(mmu_short_dte_t) *
    705 		(MMU_A_TBL_SIZE - MMU_TIA(KERNBASE)) * MMU_B_TBL_SIZE;
    706 	kernBbase = pmap_bootstrap_alloc(size);
    707 	bzero(kernBbase, size);
    708 
    709 	/*
    710 	 * Allocate enough C tables.
    711 	 * Note: In order for the PV system to work correctly, the kernel
    712 	 * and user-level C tables must be allocated contiguously.
    713 	 * Nothing should be allocated between here and the allocation of
    714 	 * mmuCbase below.  XXX: Should do this as one allocation, and
    715 	 * then compute a pointer for mmuCbase instead of this...
    716 	 */
    717 	size = sizeof (mmu_short_pte_t) *
    718 		(MMU_A_TBL_SIZE - MMU_TIA(KERNBASE))
    719 		* MMU_B_TBL_SIZE * MMU_C_TBL_SIZE;
    720 	kernCbase = pmap_bootstrap_alloc(size);
    721 	bzero(kernCbase, size);
    722 
    723 	/*
    724 	 * Allocate user MMU tables.
    725 	 * These must be aligned on 256 byte boundaries.
    726 	 *
    727 	 * As noted in the comment preceding the allocation of the kernel
    728 	 * C tables in pmap_bootstrap(), user-level C tables must be the
    729 	 * flush with (up against) the kernel-level C tables.
    730 	 */
    731 	mmuCbase = (mmu_short_pte_t *)
    732 		pmap_bootstrap_alloc(sizeof(mmu_short_pte_t)
    733 		* MMU_C_TBL_SIZE
    734 		* NUM_C_TABLES);
    735 	mmuAbase = (mmu_long_dte_t *)
    736 		pmap_bootstrap_alloc(sizeof(mmu_long_dte_t)
    737 		* MMU_A_TBL_SIZE
    738 		* NUM_A_TABLES);
    739 	mmuBbase = (mmu_short_dte_t *)
    740 		pmap_bootstrap_alloc(sizeof(mmu_short_dte_t)
    741 		* MMU_B_TBL_SIZE
    742 		* NUM_B_TABLES);
    743 
    744 	/*
    745 	 * Fill in the never-changing part of the kernel tables.
    746 	 * For simplicity, the kernel's mappings will be editable as a
    747 	 * flat array of page table entries at kernCbase.  The
    748 	 * higher level 'A' and 'B' tables must be initialized to point
    749 	 * to this lower one.
    750 	 */
    751 	b = c = 0;
    752 
    753 	/*
    754 	 * Invalidate all mappings below KERNBASE in the A table.
    755 	 * This area has already been zeroed out, but it is good
    756 	 * practice to explicitly show that we are interpreting
    757 	 * it as a list of A table descriptors.
    758 	 */
    759 	for (i = 0; i < MMU_TIA(KERNBASE); i++) {
    760 		kernAbase[i].addr.raw = 0;
    761 	}
    762 
    763 	/*
    764 	 * Set up the kernel A and B tables so that they will reference the
    765 	 * correct spots in the contiguous table of PTEs allocated for the
    766 	 * kernel's virtual memory space.
    767 	 */
    768 	for (i = MMU_TIA(KERNBASE); i < MMU_A_TBL_SIZE; i++) {
    769 		kernAbase[i].attr.raw =
    770 			MMU_LONG_DTE_LU | MMU_LONG_DTE_SUPV | MMU_DT_SHORT;
    771 		kernAbase[i].addr.raw = mmu_vtop(&kernBbase[b]);
    772 
    773 		for (j=0; j < MMU_B_TBL_SIZE; j++) {
    774 			kernBbase[b + j].attr.raw = mmu_vtop(&kernCbase[c])
    775 				| MMU_DT_SHORT;
    776 			c += MMU_C_TBL_SIZE;
    777 		}
    778 		b += MMU_B_TBL_SIZE;
    779 	}
    780 
    781 	/* XXX - Doing kernel_pmap a little further down. */
    782 
    783 	pmap_alloc_usermmu();	/* Allocate user MMU tables.        */
    784 	pmap_alloc_usertmgr();	/* Allocate user MMU table managers.*/
    785 	pmap_alloc_pv();	/* Allocate physical->virtual map.  */
    786 
    787 	/*
    788 	 * We are now done with pmap_bootstrap_alloc().  Round up
    789 	 * `virtual_avail' to the nearest page, and set the flag
    790 	 * to prevent use of pmap_bootstrap_alloc() hereafter.
    791 	 */
    792 	pmap_bootstrap_aalign(NBPG);
    793 	bootstrap_alloc_enabled = FALSE;
    794 
    795 	/*
    796 	 * Now that we are done with pmap_bootstrap_alloc(), we
    797 	 * must save the virtual and physical addresses of the
    798 	 * end of the linearly mapped range, which are stored in
    799 	 * virtual_contig_end and avail_start, respectively.
    800 	 * These variables will never change after this point.
    801 	 */
    802 	virtual_contig_end = virtual_avail;
    803 	avail_start = virtual_avail - KERNBASE;
    804 
    805 	/*
    806 	 * `avail_next' is a running pointer used by pmap_next_page() to
    807 	 * keep track of the next available physical page to be handed
    808 	 * to the VM system during its initialization, in which it
    809 	 * asks for physical pages, one at a time.
    810 	 */
    811 	avail_next = avail_start;
    812 
    813 	/*
    814 	 * Now allocate some virtual addresses, but not the physical pages
    815 	 * behind them.  Note that virtual_avail is already page-aligned.
    816 	 *
    817 	 * tmp_vpages[] is an array of two virtual pages used for temporary
    818 	 * kernel mappings in the pmap module to facilitate various physical
    819 	 * address-oritented operations.
    820 	 */
    821 	tmp_vpages[0] = virtual_avail;
    822 	virtual_avail += NBPG;
    823 	tmp_vpages[1] = virtual_avail;
    824 	virtual_avail += NBPG;
    825 
    826 	/** Initialize the PV system **/
    827 	pmap_init_pv();
    828 
    829 	/*
    830 	 * Fill in the kernel_pmap structure and kernel_crp.
    831 	 */
    832 	kernAphys = mmu_vtop(kernAbase);
    833 	kernel_pmap.pm_a_tmgr = NULL;
    834 	kernel_pmap.pm_a_phys = kernAphys;
    835 	kernel_pmap.pm_refcount = 1; /* always in use */
    836 
    837 	kernel_crp.rp_attr = MMU_LONG_DTE_LU | MMU_DT_LONG;
    838 	kernel_crp.rp_addr = kernAphys;
    839 
    840 	/*
    841 	 * Now pmap_enter_kernel() may be used safely and will be
    842 	 * the main interface used hereafter to modify the kernel's
    843 	 * virtual address space.  Note that since we are still running
    844 	 * under the PROM's address table, none of these table modifications
    845 	 * actually take effect until pmap_takeover_mmu() is called.
    846 	 *
    847 	 * Note: Our tables do NOT have the PROM linear mappings!
    848 	 * Only the mappings created here exist in our tables, so
    849 	 * remember to map anything we expect to use.
    850 	 */
    851 	va = (vm_offset_t) KERNBASE;
    852 	pa = 0;
    853 
    854 	/*
    855 	 * The first page of the kernel virtual address space is the msgbuf
    856 	 * page.  The page attributes (data, non-cached) are set here, while
    857 	 * the address is assigned to this global pointer in cpu_startup().
    858 	 * XXX - Make it non-cached?
    859 	 */
    860 	pmap_enter_kernel(va, pa|PMAP_NC, VM_PROT_ALL);
    861 	va += NBPG; pa += NBPG;
    862 
    863 	/* Next page is used as the temporary stack. */
    864 	pmap_enter_kernel(va, pa, VM_PROT_ALL);
    865 	va += NBPG; pa += NBPG;
    866 
    867 	/*
    868 	 * Map all of the kernel's text segment as read-only and cacheable.
    869 	 * (Cacheable is implied by default).  Unfortunately, the last bytes
    870 	 * of kernel text and the first bytes of kernel data will often be
    871 	 * sharing the same page.  Therefore, the last page of kernel text
    872 	 * has to be mapped as read/write, to accomodate the data.
    873 	 */
    874 	eva = sun3x_trunc_page((vm_offset_t)etext);
    875 	for (; va < eva; va += NBPG, pa += NBPG)
    876 		pmap_enter_kernel(va, pa, VM_PROT_READ|VM_PROT_EXECUTE);
    877 
    878 	/*
    879 	 * Map all of the kernel's data as read/write and cacheable.
    880 	 * This includes: data, BSS, symbols, and everything in the
    881 	 * contiguous memory used by pmap_bootstrap_alloc()
    882 	 */
    883 	for (; pa < avail_start; va += NBPG, pa += NBPG)
    884 		pmap_enter_kernel(va, pa, VM_PROT_READ|VM_PROT_WRITE);
    885 
    886 	/*
    887 	 * At this point we are almost ready to take over the MMU.  But first
    888 	 * we must save the PROM's address space in our map, as we call its
    889 	 * routines and make references to its data later in the kernel.
    890 	 */
    891 	pmap_bootstrap_copyprom();
    892 	pmap_takeover_mmu();
    893 
    894 	/*
    895 	 * XXX - Todo:  Fill in the PROM's level-A table for the VA range
    896 	 * KERNBASE ... 0xFE000000 so that the PROM monitor can see our
    897 	 * mappings.  This should make bouncing in/out of PROM easier.
    898 	 * XXX - Add (i.e.) pmap_setup_prommap();
    899 	 */
    900 
    901 	/* Notify the VM system of our page size. */
    902 	PAGE_SIZE = NBPG;
    903 	vm_set_page_size();
    904 }
    905 
    906 
    907 /* pmap_alloc_usermmu			INTERNAL
    908  **
    909  * Called from pmap_bootstrap() to allocate MMU tables that will
    910  * eventually be used for user mappings.
    911  */
    912 void
    913 pmap_alloc_usermmu()
    914 {
    915 	/* XXX: Moved into caller. */
    916 }
    917 
    918 /* pmap_alloc_pv			INTERNAL
    919  **
    920  * Called from pmap_bootstrap() to allocate the physical
    921  * to virtual mapping list.  Each physical page of memory
    922  * in the system has a corresponding element in this list.
    923  */
    924 void
    925 pmap_alloc_pv()
    926 {
    927 	int	i;
    928 	unsigned int	total_mem;
    929 
    930 	/*
    931 	 * Allocate a pv_head structure for every page of physical
    932 	 * memory that will be managed by the system.  Since memory on
    933 	 * the 3/80 is non-contiguous, we cannot arrive at a total page
    934 	 * count by subtraction of the lowest available address from the
    935 	 * highest, but rather we have to step through each memory
    936 	 * bank and add the number of pages in each to the total.
    937 	 *
    938 	 * At this time we also initialize the offset of each bank's
    939 	 * starting pv_head within the pv_head list so that the physical
    940 	 * memory state routines (pmap_is_referenced(),
    941 	 * pmap_is_modified(), et al.) can quickly find coresponding
    942 	 * pv_heads in spite of the non-contiguity.
    943 	 */
    944 	total_mem = 0;
    945 	for (i = 0; i < SUN3X_80_MEM_BANKS; i++) {
    946 		avail_mem[i].pmem_pvbase = sun3x_btop(total_mem);
    947 		total_mem += avail_mem[i].pmem_end -
    948 			avail_mem[i].pmem_start;
    949 		if (avail_mem[i].pmem_next == NULL)
    950 			break;
    951 	}
    952 #ifdef	PMAP_DEBUG
    953 	if (total_mem != total_phys_mem)
    954 		panic("pmap_alloc_pv did not arrive at correct page count");
    955 #endif
    956 
    957 	pvbase = (pv_t *) pmap_bootstrap_alloc(sizeof(pv_t) *
    958 		sun3x_btop(total_phys_mem));
    959 }
    960 
    961 /* pmap_alloc_usertmgr			INTERNAL
    962  **
    963  * Called from pmap_bootstrap() to allocate the structures which
    964  * facilitate management of user MMU tables.  Each user MMU table
    965  * in the system has one such structure associated with it.
    966  */
    967 void
    968 pmap_alloc_usertmgr()
    969 {
    970 	/* Allocate user MMU table managers */
    971 	/* It would be a lot simpler to just make these BSS, but */
    972 	/* we may want to change their size at boot time... -j */
    973 	Atmgrbase = (a_tmgr_t *) pmap_bootstrap_alloc(sizeof(a_tmgr_t)
    974 		* NUM_A_TABLES);
    975 	Btmgrbase = (b_tmgr_t *) pmap_bootstrap_alloc(sizeof(b_tmgr_t)
    976 		* NUM_B_TABLES);
    977 	Ctmgrbase = (c_tmgr_t *) pmap_bootstrap_alloc(sizeof(c_tmgr_t)
    978 		* NUM_C_TABLES);
    979 
    980 	/*
    981 	 * Allocate PV list elements for the physical to virtual
    982 	 * mapping system.
    983 	 */
    984 	pvebase = (pv_elem_t *) pmap_bootstrap_alloc(
    985 		sizeof(pv_elem_t) * (NUM_USER_PTES + NUM_KERN_PTES));
    986 }
    987 
    988 /* pmap_bootstrap_copyprom()			INTERNAL
    989  **
    990  * Copy the PROM mappings into our own tables.  Note, we
    991  * can use physical addresses until __bootstrap returns.
    992  */
    993 void
    994 pmap_bootstrap_copyprom()
    995 {
    996 	MachMonRomVector *romp;
    997 	int *mon_ctbl;
    998 	mmu_short_pte_t *kpte;
    999 	int i, len;
   1000 
   1001 	romp = romVectorPtr;
   1002 
   1003 	/*
   1004 	 * Copy the mappings in MON_KDB_START...MONEND
   1005 	 * Note: mon_ctbl[0] maps MON_KDB_START
   1006 	 */
   1007 	mon_ctbl = *romp->monptaddr;
   1008 	i = sun3x_btop(MON_KDB_START - KERNBASE);
   1009 	kpte = &kernCbase[i];
   1010 	len = sun3x_btop(MONEND - MON_KDB_START);
   1011 
   1012 	for (i = 0; i < len; i++) {
   1013 		kpte[i].attr.raw = mon_ctbl[i];
   1014 	}
   1015 
   1016 	/*
   1017 	 * Copy the mappings at MON_DVMA_BASE (to the end).
   1018 	 * Note, in here, mon_ctbl[0] maps MON_DVMA_BASE.
   1019 	 * XXX - This does not appear to be necessary, but
   1020 	 * I'm not sure yet if it is or not. -gwr
   1021 	 */
   1022 	mon_ctbl = *romp->shadowpteaddr;
   1023 	i = sun3x_btop(MON_DVMA_BASE - KERNBASE);
   1024 	kpte = &kernCbase[i];
   1025 	len = sun3x_btop(MON_DVMA_SIZE);
   1026 
   1027 	for (i = 0; i < len; i++) {
   1028 		kpte[i].attr.raw = mon_ctbl[i];
   1029 	}
   1030 }
   1031 
   1032 /* pmap_takeover_mmu			INTERNAL
   1033  **
   1034  * Called from pmap_bootstrap() after it has copied enough of the
   1035  * PROM mappings into the kernel map so that we can use our own
   1036  * MMU table.
   1037  */
   1038 void
   1039 pmap_takeover_mmu()
   1040 {
   1041 	struct mmu_rootptr *crp;
   1042 
   1043 	crp = &kernel_crp;
   1044 	loadcrp(crp);
   1045 }
   1046 
   1047 /* pmap_init			INTERFACE
   1048  **
   1049  * Called at the end of vm_init() to set up the pmap system to go
   1050  * into full time operation.  All initialization of kernel_pmap
   1051  * should be already done by now, so this should just do things
   1052  * needed for user-level pmaps to work.
   1053  */
   1054 void
   1055 pmap_init()
   1056 {
   1057 	/** Initialize the manager pools **/
   1058 	TAILQ_INIT(&a_pool);
   1059 	TAILQ_INIT(&b_pool);
   1060 	TAILQ_INIT(&c_pool);
   1061 
   1062 	/**************************************************************
   1063 	 * Initialize all tmgr structures and MMU tables they manage. *
   1064 	 **************************************************************/
   1065 	/** Initialize A tables **/
   1066 	pmap_init_a_tables();
   1067 	/** Initialize B tables **/
   1068 	pmap_init_b_tables();
   1069 	/** Initialize C tables **/
   1070 	pmap_init_c_tables();
   1071 }
   1072 
   1073 /* pmap_init_a_tables()			INTERNAL
   1074  **
   1075  * Initializes all A managers, their MMU A tables, and inserts
   1076  * them into the A manager pool for use by the system.
   1077  */
   1078 void
   1079 pmap_init_a_tables()
   1080 {
   1081 	int i;
   1082 	a_tmgr_t *a_tbl;
   1083 
   1084 	for (i=0; i < NUM_A_TABLES; i++) {
   1085 		/* Select the next available A manager from the pool */
   1086 		a_tbl = &Atmgrbase[i];
   1087 
   1088 		/*
   1089 		 * Clear its parent entry.  Set its wired and valid
   1090 		 * entry count to zero.
   1091 		 */
   1092 		a_tbl->at_parent = NULL;
   1093 		a_tbl->at_wcnt = a_tbl->at_ecnt = 0;
   1094 
   1095 		/* Assign it the next available MMU A table from the pool */
   1096 		a_tbl->at_dtbl = &mmuAbase[i * MMU_A_TBL_SIZE];
   1097 
   1098 		/*
   1099 		 * Initialize the MMU A table with the table in the `proc0',
   1100 		 * or kernel, mapping.  This ensures that every process has
   1101 		 * the kernel mapped in the top part of its address space.
   1102 		 */
   1103 		bcopy(kernAbase, a_tbl->at_dtbl, MMU_A_TBL_SIZE *
   1104 			sizeof(mmu_long_dte_t));
   1105 
   1106 		/*
   1107 		 * Finally, insert the manager into the A pool,
   1108 		 * making it ready to be used by the system.
   1109 		 */
   1110 		TAILQ_INSERT_TAIL(&a_pool, a_tbl, at_link);
   1111     }
   1112 }
   1113 
   1114 /* pmap_init_b_tables()			INTERNAL
   1115  **
   1116  * Initializes all B table managers, their MMU B tables, and
   1117  * inserts them into the B manager pool for use by the system.
   1118  */
   1119 void
   1120 pmap_init_b_tables()
   1121 {
   1122 	int i,j;
   1123 	b_tmgr_t *b_tbl;
   1124 
   1125 	for (i=0; i < NUM_B_TABLES; i++) {
   1126 		/* Select the next available B manager from the pool */
   1127 		b_tbl = &Btmgrbase[i];
   1128 
   1129 		b_tbl->bt_parent = NULL;	/* clear its parent,  */
   1130 		b_tbl->bt_pidx = 0;		/* parent index,      */
   1131 		b_tbl->bt_wcnt = 0;		/* wired entry count, */
   1132 		b_tbl->bt_ecnt = 0;		/* valid entry count. */
   1133 
   1134 		/* Assign it the next available MMU B table from the pool */
   1135 		b_tbl->bt_dtbl = &mmuBbase[i * MMU_B_TBL_SIZE];
   1136 
   1137 		/* Invalidate every descriptor in the table */
   1138 		for (j=0; j < MMU_B_TBL_SIZE; j++)
   1139 			b_tbl->bt_dtbl[j].attr.raw = MMU_DT_INVALID;
   1140 
   1141 		/* Insert the manager into the B pool */
   1142 		TAILQ_INSERT_TAIL(&b_pool, b_tbl, bt_link);
   1143 	}
   1144 }
   1145 
   1146 /* pmap_init_c_tables()			INTERNAL
   1147  **
   1148  * Initializes all C table managers, their MMU C tables, and
   1149  * inserts them into the C manager pool for use by the system.
   1150  */
   1151 void
   1152 pmap_init_c_tables()
   1153 {
   1154 	int i,j;
   1155 	c_tmgr_t *c_tbl;
   1156 
   1157 	for (i=0; i < NUM_C_TABLES; i++) {
   1158 		/* Select the next available C manager from the pool */
   1159 		c_tbl = &Ctmgrbase[i];
   1160 
   1161 		c_tbl->ct_parent = NULL;	/* clear its parent,  */
   1162 		c_tbl->ct_pidx = 0;		/* parent index,      */
   1163 		c_tbl->ct_wcnt = 0;		/* wired entry count, */
   1164 		c_tbl->ct_ecnt = 0;		/* valid entry count. */
   1165 
   1166 		/* Assign it the next available MMU C table from the pool */
   1167 		c_tbl->ct_dtbl = &mmuCbase[i * MMU_C_TBL_SIZE];
   1168 
   1169 		for (j=0; j < MMU_C_TBL_SIZE; j++)
   1170 			c_tbl->ct_dtbl[j].attr.raw = MMU_DT_INVALID;
   1171 
   1172 		TAILQ_INSERT_TAIL(&c_pool, c_tbl, ct_link);
   1173 	}
   1174 }
   1175 
   1176 /* pmap_init_pv()			INTERNAL
   1177  **
   1178  * Initializes the Physical to Virtual mapping system.
   1179  */
   1180 void
   1181 pmap_init_pv()
   1182 {
   1183 	int	i;
   1184 
   1185 	/* Initialize every PV head. */
   1186 	for (i = 0; i < sun3x_btop(total_phys_mem); i++) {
   1187 		pvbase[i].pv_idx = PVE_EOL;	/* Indicate no mappings */
   1188 		pvbase[i].pv_flags = 0;		/* Zero out page flags  */
   1189 	}
   1190 
   1191 	pv_initialized = TRUE;
   1192 }
   1193 
   1194 /* get_a_table			INTERNAL
   1195  **
   1196  * Retrieve and return a level A table for use in a user map.
   1197  */
   1198 a_tmgr_t *
   1199 get_a_table()
   1200 {
   1201 	a_tmgr_t *tbl;
   1202 	pmap_t pmap;
   1203 
   1204 	/* Get the top A table in the pool */
   1205 	tbl = a_pool.tqh_first;
   1206 	if (tbl == NULL) {
   1207 		/*
   1208 		 * XXX - Instead of panicing here and in other get_x_table
   1209 		 * functions, we do have the option of sleeping on the head of
   1210 		 * the table pool.  Any function which updates the table pool
   1211 		 * would then issue a wakeup() on the head, thus waking up any
   1212 		 * processes waiting for a table.
   1213 		 *
   1214 		 * Actually, the place to sleep would be when some process
   1215 		 * asks for a "wired" mapping that would run us short of
   1216 		 * mapping resources.  This design DEPENDS on always having
   1217 		 * some mapping resources in the pool for stealing, so we
   1218 		 * must make sure we NEVER let the pool become empty. -gwr
   1219 		 */
   1220 		panic("get_a_table: out of A tables.");
   1221 	}
   1222 
   1223 	TAILQ_REMOVE(&a_pool, tbl, at_link);
   1224 	/*
   1225 	 * If the table has a non-null parent pointer then it is in use.
   1226 	 * Forcibly abduct it from its parent and clear its entries.
   1227 	 * No re-entrancy worries here.  This table would not be in the
   1228 	 * table pool unless it was available for use.
   1229 	 *
   1230 	 * Note that the second argument to free_a_table() is FALSE.  This
   1231 	 * indicates that the table should not be relinked into the A table
   1232 	 * pool.  That is a job for the function that called us.
   1233 	 */
   1234 	if (tbl->at_parent) {
   1235 		pmap = tbl->at_parent;
   1236 		free_a_table(tbl, FALSE);
   1237 		pmap->pm_a_tmgr = NULL;
   1238 		pmap->pm_a_phys = kernAphys;
   1239 	}
   1240 #ifdef  NON_REENTRANT
   1241 	/*
   1242 	 * If the table isn't to be wired down, re-insert it at the
   1243 	 * end of the pool.
   1244 	 */
   1245 	if (!wired)
   1246 		/*
   1247 		 * Quandary - XXX
   1248 		 * Would it be better to let the calling function insert this
   1249 		 * table into the queue?  By inserting it here, we are allowing
   1250 		 * it to be stolen immediately.  The calling function is
   1251 		 * probably not expecting to use a table that it is not
   1252 		 * assured full control of.
   1253 		 * Answer - In the intrest of re-entrancy, it is best to let
   1254 		 * the calling function determine when a table is available
   1255 		 * for use.  Therefore this code block is not used.
   1256 		 */
   1257 		TAILQ_INSERT_TAIL(&a_pool, tbl, at_link);
   1258 #endif	/* NON_REENTRANT */
   1259 	return tbl;
   1260 }
   1261 
   1262 /* get_b_table			INTERNAL
   1263  **
   1264  * Return a level B table for use.
   1265  */
   1266 b_tmgr_t *
   1267 get_b_table()
   1268 {
   1269 	b_tmgr_t *tbl;
   1270 
   1271 	/* See 'get_a_table' for comments. */
   1272 	tbl = b_pool.tqh_first;
   1273 	if (tbl == NULL)
   1274 		panic("get_b_table: out of B tables.");
   1275 	TAILQ_REMOVE(&b_pool, tbl, bt_link);
   1276 	if (tbl->bt_parent) {
   1277 		tbl->bt_parent->at_dtbl[tbl->bt_pidx].attr.raw = MMU_DT_INVALID;
   1278 		tbl->bt_parent->at_ecnt--;
   1279 		free_b_table(tbl, FALSE);
   1280 	}
   1281 #ifdef	NON_REENTRANT
   1282 	if (!wired)
   1283 		/* XXX see quandary in get_b_table */
   1284 		/* XXX start lock */
   1285 		TAILQ_INSERT_TAIL(&b_pool, tbl, bt_link);
   1286 		/* XXX end lock */
   1287 #endif	/* NON_REENTRANT */
   1288 	return tbl;
   1289 }
   1290 
   1291 /* get_c_table			INTERNAL
   1292  **
   1293  * Return a level C table for use.
   1294  */
   1295 c_tmgr_t *
   1296 get_c_table()
   1297 {
   1298 	c_tmgr_t *tbl;
   1299 
   1300 	/* See 'get_a_table' for comments */
   1301 	tbl = c_pool.tqh_first;
   1302 	if (tbl == NULL)
   1303 		panic("get_c_table: out of C tables.");
   1304 	TAILQ_REMOVE(&c_pool, tbl, ct_link);
   1305 	if (tbl->ct_parent) {
   1306 		tbl->ct_parent->bt_dtbl[tbl->ct_pidx].attr.raw = MMU_DT_INVALID;
   1307 		tbl->ct_parent->bt_ecnt--;
   1308 		free_c_table(tbl, FALSE);
   1309 	}
   1310 #ifdef	NON_REENTRANT
   1311 	if (!wired)
   1312 		/* XXX See quandary in get_a_table */
   1313 		/* XXX start lock */
   1314 		TAILQ_INSERT_TAIL(&c_pool, tbl, c_link);
   1315 		/* XXX end lock */
   1316 #endif	/* NON_REENTRANT */
   1317 
   1318 	return tbl;
   1319 }
   1320 
   1321 /*
   1322  * The following 'free_table' and 'steal_table' functions are called to
   1323  * detach tables from their current obligations (parents and children) and
   1324  * prepare them for reuse in another mapping.
   1325  *
   1326  * Free_table is used when the calling function will handle the fate
   1327  * of the parent table, such as returning it to the free pool when it has
   1328  * no valid entries.  Functions that do not want to handle this should
   1329  * call steal_table, in which the parent table's descriptors and entry
   1330  * count are automatically modified when this table is removed.
   1331  */
   1332 
   1333 /* free_a_table			INTERNAL
   1334  **
   1335  * Unmaps the given A table and all child tables from their current
   1336  * mappings.  Returns the number of pages that were invalidated.
   1337  * If 'relink' is true, the function will return the table to the head
   1338  * of the available table pool.
   1339  *
   1340  * Cache note: The MC68851 will automatically flush all
   1341  * descriptors derived from a given A table from its
   1342  * Automatic Translation Cache (ATC) if we issue a
   1343  * 'PFLUSHR' instruction with the base address of the
   1344  * table.  This function should do, and does so.
   1345  * Note note: We are using an MC68030 - there is no
   1346  * PFLUSHR.
   1347  */
   1348 int
   1349 free_a_table(a_tbl, relink)
   1350 	a_tmgr_t *a_tbl;
   1351 	boolean_t relink;
   1352 {
   1353 	int i, removed_cnt;
   1354 	mmu_long_dte_t	*dte;
   1355 	mmu_short_dte_t *dtbl;
   1356 	b_tmgr_t	*tmgr;
   1357 
   1358 	/*
   1359 	 * Flush the ATC cache of all cached descriptors derived
   1360 	 * from this table.
   1361 	 * XXX - Sun3x does not use 68851's cached table feature
   1362 	 * flush_atc_crp(mmu_vtop(a_tbl->dte));
   1363 	 */
   1364 
   1365 	/*
   1366 	 * Remove any pending cache flushes that were designated
   1367 	 * for the pmap this A table belongs to.
   1368 	 * a_tbl->parent->atc_flushq[0] = 0;
   1369 	 * XXX - Not implemented in sun3x.
   1370 	 */
   1371 
   1372 	/*
   1373 	 * All A tables in the system should retain a map for the
   1374 	 * kernel. If the table contains any valid descriptors
   1375 	 * (other than those for the kernel area), invalidate them all,
   1376 	 * stopping short of the kernel's entries.
   1377 	 */
   1378 	removed_cnt = 0;
   1379 	if (a_tbl->at_ecnt) {
   1380 		dte = a_tbl->at_dtbl;
   1381 		for (i=0; i < MMU_TIA(KERNBASE); i++) {
   1382 			/*
   1383 			 * If a table entry points to a valid B table, free
   1384 			 * it and its children.
   1385 			 */
   1386 			if (MMU_VALID_DT(dte[i])) {
   1387 				/*
   1388 				 * The following block does several things,
   1389 				 * from innermost expression to the
   1390 				 * outermost:
   1391 				 * 1) It extracts the base (cc 1996)
   1392 				 *    address of the B table pointed
   1393 				 *    to in the A table entry dte[i].
   1394 				 * 2) It converts this base address into
   1395 				 *    the virtual address it can be
   1396 				 *    accessed with. (all MMU tables point
   1397 				 *    to physical addresses.)
   1398 				 * 3) It finds the corresponding manager
   1399 				 *    structure which manages this MMU table.
   1400 				 * 4) It frees the manager structure.
   1401 				 *    (This frees the MMU table and all
   1402 				 *    child tables. See 'free_b_table' for
   1403 				 *    details.)
   1404 				 */
   1405 				dtbl = mmu_ptov(dte[i].addr.raw);
   1406 				tmgr = mmuB2tmgr(dtbl);
   1407 				removed_cnt += free_b_table(tmgr, TRUE);
   1408 				dte[i].attr.raw = MMU_DT_INVALID;
   1409 			}
   1410 		}
   1411 		a_tbl->at_ecnt = 0;
   1412 	}
   1413 	if (relink) {
   1414 		a_tbl->at_parent = NULL;
   1415 		TAILQ_REMOVE(&a_pool, a_tbl, at_link);
   1416 		TAILQ_INSERT_HEAD(&a_pool, a_tbl, at_link);
   1417 	}
   1418 	return removed_cnt;
   1419 }
   1420 
   1421 /* free_b_table			INTERNAL
   1422  **
   1423  * Unmaps the given B table and all its children from their current
   1424  * mappings.  Returns the number of pages that were invalidated.
   1425  * (For comments, see 'free_a_table()').
   1426  */
   1427 int
   1428 free_b_table(b_tbl, relink)
   1429 	b_tmgr_t *b_tbl;
   1430 	boolean_t relink;
   1431 {
   1432 	int i, removed_cnt;
   1433 	mmu_short_dte_t *dte;
   1434 	mmu_short_pte_t	*dtbl;
   1435 	c_tmgr_t	*tmgr;
   1436 
   1437 	removed_cnt = 0;
   1438 	if (b_tbl->bt_ecnt) {
   1439 		dte = b_tbl->bt_dtbl;
   1440 		for (i=0; i < MMU_B_TBL_SIZE; i++) {
   1441 			if (MMU_VALID_DT(dte[i])) {
   1442 				dtbl = mmu_ptov(MMU_DTE_PA(dte[i]));
   1443 				tmgr = mmuC2tmgr(dtbl);
   1444 				removed_cnt += free_c_table(tmgr, TRUE);
   1445 				dte[i].attr.raw = MMU_DT_INVALID;
   1446 			}
   1447 		}
   1448 		b_tbl->bt_ecnt = 0;
   1449 	}
   1450 
   1451 	if (relink) {
   1452 		b_tbl->bt_parent = NULL;
   1453 		TAILQ_REMOVE(&b_pool, b_tbl, bt_link);
   1454 		TAILQ_INSERT_HEAD(&b_pool, b_tbl, bt_link);
   1455 	}
   1456 	return removed_cnt;
   1457 }
   1458 
   1459 /* free_c_table			INTERNAL
   1460  **
   1461  * Unmaps the given C table from use and returns it to the pool for
   1462  * re-use.  Returns the number of pages that were invalidated.
   1463  *
   1464  * This function preserves any physical page modification information
   1465  * contained in the page descriptors within the C table by calling
   1466  * 'pmap_remove_pte().'
   1467  */
   1468 int
   1469 free_c_table(c_tbl, relink)
   1470 	c_tmgr_t *c_tbl;
   1471 	boolean_t relink;
   1472 {
   1473 	int i, removed_cnt;
   1474 
   1475 	removed_cnt = 0;
   1476 	if (c_tbl->ct_ecnt) {
   1477 		for (i=0; i < MMU_C_TBL_SIZE; i++) {
   1478 			if (MMU_VALID_DT(c_tbl->ct_dtbl[i])) {
   1479 				pmap_remove_pte(&c_tbl->ct_dtbl[i]);
   1480 				removed_cnt++;
   1481 			}
   1482 		}
   1483 		c_tbl->ct_ecnt = 0;
   1484 	}
   1485 
   1486 	if (relink) {
   1487 		c_tbl->ct_parent = NULL;
   1488 		TAILQ_REMOVE(&c_pool, c_tbl, ct_link);
   1489 		TAILQ_INSERT_HEAD(&c_pool, c_tbl, ct_link);
   1490 	}
   1491 	return removed_cnt;
   1492 }
   1493 
   1494 #if 0
   1495 /* free_c_table_novalid			INTERNAL
   1496  **
   1497  * Frees the given C table manager without checking to see whether
   1498  * or not it contains any valid page descriptors as it is assumed
   1499  * that it does not.
   1500  */
   1501 void
   1502 free_c_table_novalid(c_tbl)
   1503 	c_tmgr_t *c_tbl;
   1504 {
   1505 	TAILQ_REMOVE(&c_pool, c_tbl, ct_link);
   1506 	TAILQ_INSERT_HEAD(&c_pool, c_tbl, ct_link);
   1507 	c_tbl->ct_parent->bt_dtbl[c_tbl->ct_pidx].attr.raw = MMU_DT_INVALID;
   1508 	c_tbl->ct_parent->bt_ecnt--;
   1509 	/*
   1510 	 * XXX - Should call equiv. of 'free_b_table_novalid' here if
   1511 	 * we just removed the last entry of the parent B table.
   1512 	 * But I want to insure that this will not endanger pmap_enter()
   1513 	 * with sudden removal of tables it is working with.
   1514 	 *
   1515 	 * We should probably add another field to each table, indicating
   1516 	 * whether or not it is 'locked', ie. in the process of being
   1517 	 * modified.
   1518 	 */
   1519 	c_tbl->ct_parent = NULL;
   1520 }
   1521 #endif
   1522 
   1523 /* pmap_remove_pte			INTERNAL
   1524  **
   1525  * Unmap the given pte and preserve any page modification
   1526  * information by transfering it to the pv head of the
   1527  * physical page it maps to.  This function does not update
   1528  * any reference counts because it is assumed that the calling
   1529  * function will do so.
   1530  */
   1531 void
   1532 pmap_remove_pte(pte)
   1533 	mmu_short_pte_t *pte;
   1534 {
   1535 	u_short     pv_idx, targ_idx;
   1536 	int         s;
   1537 	vm_offset_t pa;
   1538 	pv_t       *pv;
   1539 
   1540 	pa = MMU_PTE_PA(*pte);
   1541 	if (is_managed(pa)) {
   1542 		pv = pa2pv(pa);
   1543 		targ_idx = pteidx(pte);	/* Index of PTE being removed    */
   1544 
   1545 		/*
   1546 		 * If the PTE being removed is the first (or only) PTE in
   1547 		 * the list of PTEs currently mapped to this page, remove the
   1548 		 * PTE by changing the index found on the PV head.  Otherwise
   1549 		 * a linear search through the list will have to be executed
   1550 		 * in order to find the PVE which points to the PTE being
   1551 		 * removed, so that it may be modified to point to its new
   1552 		 * neighbor.
   1553 		 */
   1554 		s = splimp();
   1555 		pv_idx = pv->pv_idx;	/* Index of first PTE in PV list */
   1556 		if (pv_idx == targ_idx) {
   1557 			pv->pv_idx = pvebase[targ_idx].pve_next;
   1558 		} else {
   1559 			/*
   1560 			 * Find the PV element which points to the target
   1561 			 * element.
   1562 			 */
   1563 			while (pvebase[pv_idx].pve_next != targ_idx) {
   1564 				pv_idx = pvebase[pv_idx].pve_next;
   1565 #ifdef	DIAGNOSTIC
   1566 				if (pv_idx == PVE_EOL)
   1567 					panic("pmap_remove_pte: pv list end!");
   1568 #endif
   1569 			}
   1570 
   1571 			/*
   1572 			 * At this point, pv_idx is the index of the PV
   1573 			 * element just before the target element in the list.
   1574 			 * Unlink the target.
   1575 			 */
   1576 			pvebase[pv_idx].pve_next = pvebase[targ_idx].pve_next;
   1577 		}
   1578 		/*
   1579 		 * Save the mod/ref bits of the pte by simply
   1580 		 * ORing the entire pte onto the pv_flags member
   1581 		 * of the pv structure.
   1582 		 * There is no need to use a separate bit pattern
   1583 		 * for usage information on the pv head than that
   1584 		 * which is used on the MMU ptes.
   1585 		 */
   1586 		pv->pv_flags |= (u_short) pte->attr.raw;
   1587 		splx(s);
   1588 	}
   1589 
   1590 	pte->attr.raw = MMU_DT_INVALID;
   1591 }
   1592 
   1593 #if	0	/* XXX - I am eliminating this function. -j */
   1594 /* pmap_dereference_pte			INTERNAL
   1595  **
   1596  * Update the necessary reference counts in any tables and pmaps to
   1597  * reflect the removal of the given pte.  Only called when no knowledge of
   1598  * the pte's associated pmap is unknown.  This only occurs in the PV call
   1599  * 'pmap_page_protect()' with a protection of VM_PROT_NONE, which means
   1600  * that all references to a given physical page must be removed.
   1601  */
   1602 void
   1603 pmap_dereference_pte(pte)
   1604 	mmu_short_pte_t *pte;
   1605 {
   1606 	vm_offset_t va;
   1607 	c_tmgr_t *c_tbl;
   1608 	pmap_t pmap;
   1609 
   1610 	va = pmap_get_pteinfo(pte, &pmap, &c_tbl);
   1611 	/*
   1612 	 * Flush the translation cache of the page mapped by the PTE, should
   1613 	 * it prove to be in the current pmap.  Kernel mappings appear in
   1614 	 * all address spaces, so they always should be flushed
   1615 	 */
   1616 	if (pmap == pmap_kernel() || pmap == current_pmap())
   1617 		TBIS(va);
   1618 
   1619 	/*
   1620 	 * If the mapping belongs to a user map, update the necessary
   1621 	 * reference counts in the table manager.  XXX - It would be
   1622 	 * much easier to keep the resident count in the c_tmgr_t -gwr
   1623 	 */
   1624 	if (pmap != pmap_kernel()) {
   1625 		/*
   1626 		 * Most of the situations in which pmap_dereference_pte() is
   1627 		 * called are usually temporary removals of a mapping.  Often
   1628 		 * the mapping is reinserted shortly afterwards. If the parent
   1629 		 * C table's valid entry count reaches zero as a result of
   1630 		 * removing this mapping, we could return it to the free pool,
   1631 		 * but we leave it alone because it is likely to be used as
   1632 		 * stated above.
   1633 		 */
   1634 		c_tbl->ct_ecnt--;
   1635 		pmap->pm_stats.resident_count--;
   1636 	}
   1637 }
   1638 #endif	0	/* function elimination */
   1639 
   1640 /* pmap_stroll			INTERNAL
   1641  **
   1642  * Retrieve the addresses of all table managers involved in the mapping of
   1643  * the given virtual address.  If the table walk completed sucessfully,
   1644  * return TRUE.  If it was only partially sucessful, return FALSE.
   1645  * The table walk performed by this function is important to many other
   1646  * functions in this module.
   1647  *
   1648  * Note: This function ought to be easier to read.
   1649  */
   1650 boolean_t
   1651 pmap_stroll(pmap, va, a_tbl, b_tbl, c_tbl, pte, a_idx, b_idx, pte_idx)
   1652 	pmap_t pmap;
   1653 	vm_offset_t va;
   1654 	a_tmgr_t **a_tbl;
   1655 	b_tmgr_t **b_tbl;
   1656 	c_tmgr_t **c_tbl;
   1657 	mmu_short_pte_t **pte;
   1658 	int *a_idx, *b_idx, *pte_idx;
   1659 {
   1660 	mmu_long_dte_t *a_dte;   /* A: long descriptor table          */
   1661 	mmu_short_dte_t *b_dte;  /* B: short descriptor table         */
   1662 
   1663 	if (pmap == pmap_kernel())
   1664 		return FALSE;
   1665 
   1666 	/* Does the given pmap have its own A table? */
   1667 	*a_tbl = pmap->pm_a_tmgr;
   1668 	if (*a_tbl == NULL)
   1669 		return FALSE; /* No.  Return unknown. */
   1670 	/* Does the A table have a valid B table
   1671 	 * under the corresponding table entry?
   1672 	 */
   1673 	*a_idx = MMU_TIA(va);
   1674 	a_dte = &((*a_tbl)->at_dtbl[*a_idx]);
   1675 	if (!MMU_VALID_DT(*a_dte))
   1676 		return FALSE; /* No. Return unknown. */
   1677 	/* Yes. Extract B table from the A table. */
   1678 	*b_tbl = mmuB2tmgr(mmu_ptov(a_dte->addr.raw));
   1679 	/* Does the B table have a valid C table
   1680 	 * under the corresponding table entry?
   1681 	 */
   1682 	*b_idx = MMU_TIB(va);
   1683 	b_dte = &((*b_tbl)->bt_dtbl[*b_idx]);
   1684 	if (!MMU_VALID_DT(*b_dte))
   1685 		return FALSE; /* No. Return unknown. */
   1686 	/* Yes. Extract C table from the B table. */
   1687 	*c_tbl = mmuC2tmgr(mmu_ptov(MMU_DTE_PA(*b_dte)));
   1688 	*pte_idx = MMU_TIC(va);
   1689 	*pte = &((*c_tbl)->ct_dtbl[*pte_idx]);
   1690 
   1691 	return	TRUE;
   1692 }
   1693 
   1694 /* pmap_enter			INTERFACE
   1695  **
   1696  * Called by the kernel to map a virtual address
   1697  * to a physical address in the given process map.
   1698  *
   1699  * Note: this function should apply an exclusive lock
   1700  * on the pmap system for its duration.  (it certainly
   1701  * would save my hair!!)
   1702  * This function ought to be easier to read.
   1703  */
   1704 void
   1705 pmap_enter(pmap, va, pa, prot, wired)
   1706 	pmap_t	pmap;
   1707 	vm_offset_t va;
   1708 	vm_offset_t pa;
   1709 	vm_prot_t prot;
   1710 	boolean_t wired;
   1711 {
   1712 	boolean_t insert, managed; /* Marks the need for PV insertion.*/
   1713 	u_short nidx;            /* PV list index                     */
   1714 	int s;                   /* Used for splimp()/splx()          */
   1715 	int flags;               /* Mapping flags. eg. Cache inhibit  */
   1716 	u_int a_idx, b_idx, pte_idx; /* table indices                 */
   1717 	a_tmgr_t *a_tbl;         /* A: long descriptor table manager  */
   1718 	b_tmgr_t *b_tbl;         /* B: short descriptor table manager */
   1719 	c_tmgr_t *c_tbl;         /* C: short page table manager       */
   1720 	mmu_long_dte_t *a_dte;   /* A: long descriptor table          */
   1721 	mmu_short_dte_t *b_dte;  /* B: short descriptor table         */
   1722 	mmu_short_pte_t *c_pte;  /* C: short page descriptor table    */
   1723 	pv_t      *pv;           /* pv list head                      */
   1724 	enum {NONE, NEWA, NEWB, NEWC} llevel; /* used at end   */
   1725 
   1726 	if (pmap == NULL)
   1727 		return;
   1728 	if (pmap == pmap_kernel()) {
   1729 		pmap_enter_kernel(va, pa, prot);
   1730 		return;
   1731 	}
   1732 
   1733 	flags  = (pa & ~MMU_PAGE_MASK);
   1734 	pa    &= MMU_PAGE_MASK;
   1735 
   1736 	/*
   1737 	 * Determine if the physical address being mapped is managed.
   1738 	 * If it isn't, the mapping should be cache inhibited.  (This is
   1739 	 * applied later in the function.)   XXX - Why non-cached? -gwr
   1740 	 */
   1741 	if ((managed = is_managed(pa)) == FALSE)
   1742 		flags |= PMAP_NC;
   1743 
   1744 	/*
   1745 	 * For user mappings we walk along the MMU tables of the given
   1746 	 * pmap, reaching a PTE which describes the virtual page being
   1747 	 * mapped or changed.  If any level of the walk ends in an invalid
   1748 	 * entry, a table must be allocated and the entry must be updated
   1749 	 * to point to it.
   1750 	 * There is a bit of confusion as to whether this code must be
   1751 	 * re-entrant.  For now we will assume it is.  To support
   1752 	 * re-entrancy we must unlink tables from the table pool before
   1753 	 * we assume we may use them.  Tables are re-linked into the pool
   1754 	 * when we are finished with them at the end of the function.
   1755 	 * But I don't feel like doing that until we have proof that this
   1756 	 * needs to be re-entrant.
   1757 	 * 'llevel' records which tables need to be relinked.
   1758 	 */
   1759 	llevel = NONE;
   1760 
   1761 	/*
   1762 	 * Step 1 - Retrieve the A table from the pmap.  If it has no
   1763 	 * A table, allocate a new one from the available pool.
   1764 	 */
   1765 
   1766 	a_tbl = pmap->pm_a_tmgr;
   1767 	if (a_tbl == NULL) {
   1768 		/*
   1769 		 * This pmap does not currently have an A table.  Allocate
   1770 		 * a new one.
   1771 		 */
   1772 		a_tbl = get_a_table();
   1773 		a_tbl->at_parent = pmap;
   1774 
   1775 		/*
   1776 		 * Assign this new A table to the pmap, and calculate its
   1777 		 * physical address so that loadcrp() can be used to make
   1778 		 * the table active.
   1779 		 */
   1780 		pmap->pm_a_tmgr = a_tbl;
   1781 		pmap->pm_a_phys = mmu_vtop(a_tbl->at_dtbl);
   1782 
   1783 		/*
   1784 		 * If the process receiving a new A table is the current
   1785 		 * process, we are responsible for setting the MMU so that
   1786 		 * it becomes the current address space.  This only adds
   1787 		 * new mappings, so no need to flush anything.
   1788 		 */
   1789 		if (pmap == current_pmap()) {
   1790 			kernel_crp.rp_addr = pmap->pm_a_phys;
   1791 			loadcrp(&kernel_crp);
   1792 		}
   1793 
   1794 		if (!wired)
   1795 			llevel = NEWA;
   1796 	} else {
   1797 		/*
   1798 		 * Use the A table already allocated for this pmap.
   1799 		 * Unlink it from the A table pool if necessary.
   1800 		 */
   1801 		if (wired && !a_tbl->at_wcnt)
   1802 			TAILQ_REMOVE(&a_pool, a_tbl, at_link);
   1803 	}
   1804 
   1805 	/*
   1806 	 * Step 2 - Walk into the B table.  If there is no valid B table,
   1807 	 * allocate one.
   1808 	 */
   1809 
   1810 	a_idx = MMU_TIA(va);            /* Calculate the TIA of the VA. */
   1811 	a_dte = &a_tbl->at_dtbl[a_idx]; /* Retrieve descriptor from table */
   1812 	if (MMU_VALID_DT(*a_dte)) {     /* Is the descriptor valid? */
   1813 		/* The descriptor is valid.  Use the B table it points to. */
   1814 		/*************************************
   1815 		 *               a_idx               *
   1816 		 *                 v                 *
   1817 		 * a_tbl -> +-+-+-+-+-+-+-+-+-+-+-+- *
   1818 		 *          | | | | | | | | | | | |  *
   1819 		 *          +-+-+-+-+-+-+-+-+-+-+-+- *
   1820 		 *                 |                 *
   1821 		 *                 \- b_tbl -> +-+-  *
   1822 		 *                             | |   *
   1823 		 *                             +-+-  *
   1824 		 *************************************/
   1825 		b_dte = mmu_ptov(a_dte->addr.raw);
   1826 		b_tbl = mmuB2tmgr(b_dte);
   1827 
   1828 		/*
   1829 		 * If the requested mapping must be wired, but this table
   1830 		 * being used to map it is not, the table must be removed
   1831 		 * from the available pool and its wired entry count
   1832 		 * incremented.
   1833 		 */
   1834 		if (wired && !b_tbl->bt_wcnt) {
   1835 			TAILQ_REMOVE(&b_pool, b_tbl, bt_link);
   1836 			a_tbl->at_wcnt++;
   1837 		}
   1838 	} else {
   1839 		/* The descriptor is invalid.  Allocate a new B table. */
   1840 		b_tbl = get_b_table();
   1841 
   1842 		/* Point the parent A table descriptor to this new B table. */
   1843 		a_dte->addr.raw = mmu_vtop(b_tbl->bt_dtbl);
   1844 		a_dte->attr.raw = MMU_LONG_DTE_LU | MMU_DT_SHORT;
   1845 		a_tbl->at_ecnt++; /* Update parent's valid entry count */
   1846 
   1847 		/* Create the necessary back references to the parent table */
   1848 		b_tbl->bt_parent = a_tbl;
   1849 		b_tbl->bt_pidx = a_idx;
   1850 
   1851 		/*
   1852 		 * If this table is to be wired, make sure the parent A table
   1853 		 * wired count is updated to reflect that it has another wired
   1854 		 * entry.
   1855 		 */
   1856 		if (wired)
   1857 			a_tbl->at_wcnt++;
   1858 		else if (llevel == NONE)
   1859 			llevel = NEWB;
   1860 	}
   1861 
   1862 	/*
   1863 	 * Step 3 - Walk into the C table, if there is no valid C table,
   1864 	 * allocate one.
   1865 	 */
   1866 
   1867 	b_idx = MMU_TIB(va);            /* Calculate the TIB of the VA */
   1868 	b_dte = &b_tbl->bt_dtbl[b_idx]; /* Retrieve descriptor from table */
   1869 	if (MMU_VALID_DT(*b_dte)) {     /* Is the descriptor valid? */
   1870 		/* The descriptor is valid.  Use the C table it points to. */
   1871 		/**************************************
   1872 		 *               c_idx                *
   1873 		 * |                v                 *
   1874 		 * \- b_tbl -> +-+-+-+-+-+-+-+-+-+-+- *
   1875 		 *             | | | | | | | | | | |  *
   1876 		 *             +-+-+-+-+-+-+-+-+-+-+- *
   1877 		 *                  |                 *
   1878 		 *                  \- c_tbl -> +-+-- *
   1879 		 *                              | | | *
   1880 		 *                              +-+-- *
   1881 		 **************************************/
   1882 		c_pte = mmu_ptov(MMU_PTE_PA(*b_dte));
   1883 		c_tbl = mmuC2tmgr(c_pte);
   1884 
   1885 		/* If mapping is wired and table is not */
   1886 		if (wired && !c_tbl->ct_wcnt) {
   1887 			TAILQ_REMOVE(&c_pool, c_tbl, ct_link);
   1888 			b_tbl->bt_wcnt++;
   1889 		}
   1890 	} else {
   1891 		/* The descriptor is invalid.  Allocate a new C table. */
   1892 		c_tbl = get_c_table();
   1893 
   1894 		/* Point the parent B table descriptor to this new C table. */
   1895 		b_dte->attr.raw = mmu_vtop(c_tbl->ct_dtbl);
   1896 		b_dte->attr.raw |= MMU_DT_SHORT;
   1897 		b_tbl->bt_ecnt++; /* Update parent's valid entry count */
   1898 
   1899 		/* Create the necessary back references to the parent table */
   1900 		c_tbl->ct_parent = b_tbl;
   1901 		c_tbl->ct_pidx = b_idx;
   1902 
   1903 		/*
   1904 		 * If this table is to be wired, make sure the parent B table
   1905 		 * wired count is updated to reflect that it has another wired
   1906 		 * entry.
   1907 		 */
   1908 		if (wired)
   1909 			b_tbl->bt_wcnt++;
   1910 		else if (llevel == NONE)
   1911 			llevel = NEWC;
   1912 	}
   1913 
   1914 	/*
   1915 	 * Step 4 - Deposit a page descriptor (PTE) into the appropriate
   1916 	 * slot of the C table, describing the PA to which the VA is mapped.
   1917 	 */
   1918 
   1919 	pte_idx = MMU_TIC(va);
   1920 	c_pte = &c_tbl->ct_dtbl[pte_idx];
   1921 	if (MMU_VALID_DT(*c_pte)) { /* Is the entry currently valid? */
   1922 		/*
   1923 		 * The PTE is currently valid.  This particular call
   1924 		 * is just a synonym for one (or more) of the following
   1925 		 * operations:
   1926 		 *     change protection of a page
   1927 		 *     change wiring status of a page
   1928 		 *     remove the mapping of a page
   1929 		 *
   1930 		 * XXX - Semi critical: This code should unwire the PTE
   1931 		 * and, possibly, associated parent tables if this is a
   1932 		 * change wiring operation.  Currently it does not.
   1933 		 *
   1934 		 * This may be ok if pmap_change_wiring() is the only
   1935 		 * interface used to UNWIRE a page.
   1936 		 */
   1937 
   1938 		/* First check if this is a wiring operation. */
   1939 		if (wired && (c_pte->attr.raw & MMU_SHORT_PTE_WIRED)) {
   1940 			/*
   1941 			 * The PTE is already wired.  To prevent it from being
   1942 			 * counted as a new wiring operation, reset the 'wired'
   1943 			 * variable.
   1944 			 */
   1945 			wired = FALSE;
   1946 		}
   1947 
   1948 		/* Is the new address the same as the old? */
   1949 		if (MMU_PTE_PA(*c_pte) == pa) {
   1950 			/*
   1951 			 * Yes, mark that it does not need to be reinserted
   1952 			 * into the PV list.
   1953 			 */
   1954 			insert = FALSE;
   1955 
   1956 			/*
   1957 			 * Clear all but the modified, referenced and wired
   1958 			 * bits on the PTE.
   1959 			 */
   1960 			c_pte->attr.raw &= (MMU_SHORT_PTE_M
   1961 				| MMU_SHORT_PTE_USED | MMU_SHORT_PTE_WIRED);
   1962 		} else {
   1963 			/* No, remove the old entry */
   1964 			pmap_remove_pte(c_pte);
   1965 			insert = TRUE;
   1966 		}
   1967 
   1968 		/*
   1969 		 * TLB flush is only necessary if modifying current map.
   1970 		 * However, in pmap_enter(), the pmap almost always IS
   1971 		 * the current pmap, so don't even bother to check.
   1972 		 */
   1973 		TBIS(va);
   1974 	} else {
   1975 		/*
   1976 		 * The PTE is invalid.  Increment the valid entry count in
   1977 		 * the C table manager to reflect the addition of a new entry.
   1978 		 */
   1979 		c_tbl->ct_ecnt++;
   1980 
   1981 		/* XXX - temporarily make sure the PTE is cleared. */
   1982 		c_pte->attr.raw = 0;
   1983 
   1984 		/* It will also need to be inserted into the PV list. */
   1985 		insert = TRUE;
   1986 	}
   1987 
   1988 	/*
   1989 	 * If page is changing from unwired to wired status, set an unused bit
   1990 	 * within the PTE to indicate that it is wired.  Also increment the
   1991 	 * wired entry count in the C table manager.
   1992 	 */
   1993 	if (wired) {
   1994 		c_pte->attr.raw |= MMU_SHORT_PTE_WIRED;
   1995 		c_tbl->ct_wcnt++;
   1996 	}
   1997 
   1998 	/*
   1999 	 * Map the page, being careful to preserve modify/reference/wired
   2000 	 * bits.  At this point it is assumed that the PTE either has no bits
   2001 	 * set, or if there are set bits, they are only modified, reference or
   2002 	 * wired bits.  If not, the following statement will cause erratic
   2003 	 * behavior.
   2004 	 */
   2005 #ifdef	PMAP_DEBUG
   2006 	if (c_pte->attr.raw & ~(MMU_SHORT_PTE_M |
   2007 		MMU_SHORT_PTE_USED | MMU_SHORT_PTE_WIRED)) {
   2008 		printf("pmap_enter: junk left in PTE at %p\n", c_pte);
   2009 		Debugger();
   2010 	}
   2011 #endif
   2012 	c_pte->attr.raw |= ((u_long) pa | MMU_DT_PAGE);
   2013 
   2014 	/*
   2015 	 * If the mapping should be read-only, set the write protect
   2016 	 * bit in the PTE.
   2017 	 */
   2018 	if (!(prot & VM_PROT_WRITE))
   2019 		c_pte->attr.raw |= MMU_SHORT_PTE_WP;
   2020 
   2021 	/*
   2022 	 * If the mapping should be cache inhibited (indicated by the flag
   2023 	 * bits found on the lower order of the physical address.)
   2024 	 * mark the PTE as a cache inhibited page.
   2025 	 */
   2026 	if (flags & PMAP_NC)
   2027 		c_pte->attr.raw |= MMU_SHORT_PTE_CI;
   2028 
   2029 	/*
   2030 	 * If the physical address being mapped is managed by the PV
   2031 	 * system then link the pte into the list of pages mapped to that
   2032 	 * address.
   2033 	 */
   2034 	if (insert && managed) {
   2035 		pv = pa2pv(pa);
   2036 		nidx = pteidx(c_pte);
   2037 
   2038 		s = splimp();
   2039 		pvebase[nidx].pve_next = pv->pv_idx;
   2040 		pv->pv_idx = nidx;
   2041 		splx(s);
   2042 	}
   2043 
   2044 	/* Move any allocated tables back into the active pool. */
   2045 
   2046 	switch (llevel) {
   2047 		case NEWA:
   2048 			TAILQ_INSERT_TAIL(&a_pool, a_tbl, at_link);
   2049 			/* FALLTHROUGH */
   2050 		case NEWB:
   2051 			TAILQ_INSERT_TAIL(&b_pool, b_tbl, bt_link);
   2052 			/* FALLTHROUGH */
   2053 		case NEWC:
   2054 			TAILQ_INSERT_TAIL(&c_pool, c_tbl, ct_link);
   2055 			/* FALLTHROUGH */
   2056 		default:
   2057 			break;
   2058 	}
   2059 }
   2060 
   2061 /* pmap_enter_kernel			INTERNAL
   2062  **
   2063  * Map the given virtual address to the given physical address within the
   2064  * kernel address space.  This function exists because the kernel map does
   2065  * not do dynamic table allocation.  It consists of a contiguous array of ptes
   2066  * and can be edited directly without the need to walk through any tables.
   2067  *
   2068  * XXX: "Danger, Will Robinson!"
   2069  * Note that the kernel should never take a fault on any page
   2070  * between [ KERNBASE .. virtual_avail ] and this is checked in
   2071  * trap.c for kernel-mode MMU faults.  This means that mappings
   2072  * created in that range must be implicily wired. -gwr
   2073  */
   2074 void
   2075 pmap_enter_kernel(va, pa, prot)
   2076 	vm_offset_t va;
   2077 	vm_offset_t pa;
   2078 	vm_prot_t   prot;
   2079 {
   2080 	boolean_t       was_valid, insert;
   2081 	u_short         pte_idx, pv_idx;
   2082 	int             s, flags;
   2083 	mmu_short_pte_t *pte;
   2084 	pv_t            *pv;
   2085 	vm_offset_t     old_pa;
   2086 
   2087 	flags  = (pa & ~MMU_PAGE_MASK);
   2088 	pa    &= MMU_PAGE_MASK;
   2089 
   2090 	/*
   2091 	 * Calculate the index of the PTE being modified.
   2092 	 */
   2093 	pte_idx = (u_long) sun3x_btop(va - KERNBASE);
   2094 
   2095 	/* XXX - This array is traditionally named "Sysmap" */
   2096 	pte = &kernCbase[pte_idx];
   2097 
   2098 	s = splimp();
   2099 	if (MMU_VALID_DT(*pte)) {
   2100 		was_valid = TRUE;
   2101 		/*
   2102 		 * If the PTE is already mapped to an address and it differs
   2103 		 * from the address requested, unlink it from the PV list.
   2104 		 *
   2105 		 * This only applies to mappings within virtual_avail
   2106 		 * and VM_MAX_KERNEL_ADDRESS.  All others are not requests
   2107 		 * from the VM system and should not be part of the PV system.
   2108 		 */
   2109 		if ((va >= virtual_avail) && (va < VM_MAX_KERNEL_ADDRESS)) {
   2110 		    old_pa = MMU_PTE_PA(*pte);
   2111 		    if (pa != old_pa) {
   2112 		        if (is_managed(old_pa)) {
   2113 		            /* XXX - Make this into a function call? */
   2114 		            pv = pa2pv(old_pa);
   2115 		            pv_idx = pv->pv_idx;
   2116 		            if (pv_idx == pte_idx) {
   2117 		                pv->pv_idx = pvebase[pte_idx].pve_next;
   2118 		            } else {
   2119 		                while (pvebase[pv_idx].pve_next != pte_idx)
   2120 		                    pv_idx = pvebase[pv_idx].pve_next;
   2121 		                pvebase[pv_idx].pve_next =
   2122 		                    pvebase[pte_idx].pve_next;
   2123 		            }
   2124 		            /* Save modified/reference bits */
   2125 		            pv->pv_flags |= (u_short) pte->attr.raw;
   2126 		        }
   2127 		        if (is_managed(pa))
   2128 		            insert = TRUE;
   2129 		        else
   2130 		            insert = FALSE;
   2131 		        /*
   2132 		         * Clear out any old bits in the PTE.
   2133 		         */
   2134 		        pte->attr.raw = MMU_DT_INVALID;
   2135 		    } else {
   2136 		        /*
   2137 		         * Old PA and new PA are the same.  No need to relink
   2138 		         * the mapping within the PV list.
   2139 		         */
   2140 		        insert = FALSE;
   2141 
   2142 		        /*
   2143 		         * Save any mod/ref bits on the PTE.
   2144 		         */
   2145 		        pte->attr.raw &= (MMU_SHORT_PTE_USED|MMU_SHORT_PTE_M);
   2146 		    }
   2147 		} else {
   2148 		    /*
   2149 		     * If the VA lies below virtual_avail or beyond
   2150 		     * VM_MAX_KERNEL_ADDRESS, it is not a request by the VM
   2151 		     * system and hence does not need to be linked into the PV
   2152 		     * system.
   2153 		     */
   2154 		    insert = FALSE;
   2155 		    pte->attr.raw = MMU_DT_INVALID;
   2156 		}
   2157 	} else {
   2158 		pte->attr.raw = MMU_DT_INVALID;
   2159 		was_valid = FALSE;
   2160 		if ((va >= virtual_avail) && (va < VM_MAX_KERNEL_ADDRESS)) {
   2161 			if (is_managed(pa))
   2162 				insert = TRUE;
   2163 			else
   2164 				insert = FALSE;
   2165 		} else
   2166 			insert = FALSE;
   2167 	}
   2168 
   2169 	/*
   2170 	 * Map the page.  Being careful to preserve modified/referenced bits
   2171 	 * on the PTE.
   2172 	 */
   2173 	pte->attr.raw |= (pa | MMU_DT_PAGE);
   2174 
   2175 	if (!(prot & VM_PROT_WRITE)) /* If access should be read-only */
   2176 		pte->attr.raw |= MMU_SHORT_PTE_WP;
   2177 	if (flags & PMAP_NC)
   2178 		pte->attr.raw |= MMU_SHORT_PTE_CI;
   2179 	if (was_valid)
   2180 		TBIS(va);
   2181 
   2182 	/*
   2183 	 * Insert the PTE into the PV system, if need be.
   2184 	 */
   2185 	if (insert) {
   2186 		pv = pa2pv(pa);
   2187 		pvebase[pte_idx].pve_next = pv->pv_idx;
   2188 		pv->pv_idx = pte_idx;
   2189 	}
   2190 	splx(s);
   2191 
   2192 }
   2193 
   2194 /* pmap_protect			INTERFACE
   2195  **
   2196  * Apply the given protection to the given virtual address range within
   2197  * the given map.
   2198  *
   2199  * It is ok for the protection applied to be stronger than what is
   2200  * specified.  We use this to our advantage when the given map has no
   2201  * mapping for the virtual address.  By skipping a page when this
   2202  * is discovered, we are effectively applying a protection of VM_PROT_NONE,
   2203  * and therefore do not need to map the page just to apply a protection
   2204  * code.  Only pmap_enter() needs to create new mappings if they do not exist.
   2205  *
   2206  * XXX - This function could be speeded up by using pmap_stroll() for inital
   2207  *       setup, and then manual scrolling in the for() loop.
   2208  */
   2209 void
   2210 pmap_protect(pmap, startva, endva, prot)
   2211 	pmap_t pmap;
   2212 	vm_offset_t startva, endva;
   2213 	vm_prot_t prot;
   2214 {
   2215 	boolean_t iscurpmap;
   2216 	int a_idx, b_idx, c_idx;
   2217 	a_tmgr_t *a_tbl;
   2218 	b_tmgr_t *b_tbl;
   2219 	c_tmgr_t *c_tbl;
   2220 	mmu_short_pte_t *pte;
   2221 
   2222 	if (pmap == NULL)
   2223 		return;
   2224 	if (pmap == pmap_kernel()) {
   2225 		pmap_protect_kernel(startva, endva, prot);
   2226 		return;
   2227 	}
   2228 
   2229 	/*
   2230 	 * In this particular pmap implementation, there are only three
   2231 	 * types of memory protection: 'all' (read/write/execute),
   2232 	 * 'read-only' (read/execute) and 'none' (no mapping.)
   2233 	 * It is not possible for us to treat 'executable' as a separate
   2234 	 * protection type.  Therefore, protection requests that seek to
   2235 	 * remove execute permission while retaining read or write, and those
   2236 	 * that make little sense (write-only for example) are ignored.
   2237 	 */
   2238 	switch (prot) {
   2239 		case VM_PROT_NONE:
   2240 			/*
   2241 			 * A request to apply the protection code of
   2242 			 * 'VM_PROT_NONE' is a synonym for pmap_remove().
   2243 			 */
   2244 			pmap_remove(pmap, startva, endva);
   2245 			return;
   2246 		case	VM_PROT_EXECUTE:
   2247 		case	VM_PROT_READ:
   2248 		case	VM_PROT_READ|VM_PROT_EXECUTE:
   2249 			/* continue */
   2250 			break;
   2251 		case	VM_PROT_WRITE:
   2252 		case	VM_PROT_WRITE|VM_PROT_READ:
   2253 		case	VM_PROT_WRITE|VM_PROT_EXECUTE:
   2254 		case	VM_PROT_ALL:
   2255 			/* None of these should happen in a sane system. */
   2256 			return;
   2257 	}
   2258 
   2259 	/*
   2260 	 * If the pmap has no A table, it has no mappings and therefore
   2261 	 * there is nothing to protect.
   2262 	 */
   2263 	if ((a_tbl = pmap->pm_a_tmgr) == NULL)
   2264 		return;
   2265 
   2266 	a_idx = MMU_TIA(startva);
   2267 	b_idx = MMU_TIB(startva);
   2268 	c_idx = MMU_TIC(startva);
   2269 	b_tbl = (b_tmgr_t *) c_tbl = NULL;
   2270 
   2271 	iscurpmap = (pmap == current_pmap());
   2272 	while (startva < endva) {
   2273 		if (b_tbl || MMU_VALID_DT(a_tbl->at_dtbl[a_idx])) {
   2274 		  if (b_tbl == NULL) {
   2275 		    b_tbl = (b_tmgr_t *) a_tbl->at_dtbl[a_idx].addr.raw;
   2276 		    b_tbl = mmu_ptov((vm_offset_t) b_tbl);
   2277 		    b_tbl = mmuB2tmgr((mmu_short_dte_t *) b_tbl);
   2278 		  }
   2279 		  if (c_tbl || MMU_VALID_DT(b_tbl->bt_dtbl[b_idx])) {
   2280 		    if (c_tbl == NULL) {
   2281 		      c_tbl = (c_tmgr_t *) MMU_DTE_PA(b_tbl->bt_dtbl[b_idx]);
   2282 		      c_tbl = mmu_ptov((vm_offset_t) c_tbl);
   2283 		      c_tbl = mmuC2tmgr((mmu_short_pte_t *) c_tbl);
   2284 		    }
   2285 		    if (MMU_VALID_DT(c_tbl->ct_dtbl[c_idx])) {
   2286 		      pte = &c_tbl->ct_dtbl[c_idx];
   2287 		      /* make the mapping read-only */
   2288 		      pte->attr.raw |= MMU_SHORT_PTE_WP;
   2289 		      /*
   2290 		       * If we just modified the current address space,
   2291 		       * flush any translations for the modified page from
   2292 		       * the translation cache and any data from it in the
   2293 		       * data cache.
   2294 		       */
   2295 		      if (iscurpmap)
   2296 		          TBIS(startva);
   2297 		    }
   2298 		    startva += NBPG;
   2299 
   2300 		    if (++c_idx >= MMU_C_TBL_SIZE) { /* exceeded C table? */
   2301 		      c_tbl = NULL;
   2302 		      c_idx = 0;
   2303 		      if (++b_idx >= MMU_B_TBL_SIZE) { /* exceeded B table? */
   2304 		        b_tbl = NULL;
   2305 		        b_idx = 0;
   2306 		      }
   2307 		    }
   2308 		  } else { /* C table wasn't valid */
   2309 		    c_tbl = NULL;
   2310 		    c_idx = 0;
   2311 		    startva += MMU_TIB_RANGE;
   2312 		    if (++b_idx >= MMU_B_TBL_SIZE) { /* exceeded B table? */
   2313 		      b_tbl = NULL;
   2314 		      b_idx = 0;
   2315 		    }
   2316 		  } /* C table */
   2317 		} else { /* B table wasn't valid */
   2318 		  b_tbl = NULL;
   2319 		  b_idx = 0;
   2320 		  startva += MMU_TIA_RANGE;
   2321 		  a_idx++;
   2322 		} /* B table */
   2323 	}
   2324 }
   2325 
   2326 /* pmap_protect_kernel			INTERNAL
   2327  **
   2328  * Apply the given protection code to a kernel address range.
   2329  */
   2330 void
   2331 pmap_protect_kernel(startva, endva, prot)
   2332 	vm_offset_t startva, endva;
   2333 	vm_prot_t prot;
   2334 {
   2335 	vm_offset_t va;
   2336 	mmu_short_pte_t *pte;
   2337 
   2338 	pte = &kernCbase[(unsigned long) sun3x_btop(startva - KERNBASE)];
   2339 	for (va = startva; va < endva; va += NBPG, pte++) {
   2340 		if (MMU_VALID_DT(*pte)) {
   2341 		    switch (prot) {
   2342 		        case VM_PROT_ALL:
   2343 		            break;
   2344 		        case VM_PROT_EXECUTE:
   2345 		        case VM_PROT_READ:
   2346 		        case VM_PROT_READ|VM_PROT_EXECUTE:
   2347 		            pte->attr.raw |= MMU_SHORT_PTE_WP;
   2348 		            break;
   2349 		        case VM_PROT_NONE:
   2350 		            /* this is an alias for 'pmap_remove_kernel' */
   2351 		            pmap_remove_pte(pte);
   2352 		            break;
   2353 		        default:
   2354 		            break;
   2355 		    }
   2356 		    /*
   2357 		     * since this is the kernel, immediately flush any cached
   2358 		     * descriptors for this address.
   2359 		     */
   2360 		    TBIS(va);
   2361 		}
   2362 	}
   2363 }
   2364 
   2365 /* pmap_change_wiring			INTERFACE
   2366  **
   2367  * Changes the wiring of the specified page.
   2368  *
   2369  * This function is called from vm_fault.c to unwire
   2370  * a mapping.  It really should be called 'pmap_unwire'
   2371  * because it is never asked to do anything but remove
   2372  * wirings.
   2373  */
   2374 void
   2375 pmap_change_wiring(pmap, va, wire)
   2376 	pmap_t pmap;
   2377 	vm_offset_t va;
   2378 	boolean_t wire;
   2379 {
   2380 	int a_idx, b_idx, c_idx;
   2381 	a_tmgr_t *a_tbl;
   2382 	b_tmgr_t *b_tbl;
   2383 	c_tmgr_t *c_tbl;
   2384 	mmu_short_pte_t *pte;
   2385 
   2386 	/* Kernel mappings always remain wired. */
   2387 	if (pmap == pmap_kernel())
   2388 		return;
   2389 
   2390 #ifdef	PMAP_DEBUG
   2391 	if (wire == TRUE)
   2392 		panic("pmap_change_wiring: wire requested.");
   2393 #endif
   2394 
   2395 	/*
   2396 	 * Walk through the tables.  If the walk terminates without
   2397 	 * a valid PTE then the address wasn't wired in the first place.
   2398 	 * Return immediately.
   2399 	 */
   2400 	if (pmap_stroll(pmap, va, &a_tbl, &b_tbl, &c_tbl, &pte, &a_idx,
   2401 		&b_idx, &c_idx) == FALSE)
   2402 		return;
   2403 
   2404 
   2405 	/* Is the PTE wired?  If not, return. */
   2406 	if (!(pte->attr.raw & MMU_SHORT_PTE_WIRED))
   2407 		return;
   2408 
   2409 	/* Remove the wiring bit. */
   2410 	pte->attr.raw &= ~(MMU_SHORT_PTE_WIRED);
   2411 
   2412 	/*
   2413 	 * Decrement the wired entry count in the C table.
   2414 	 * If it reaches zero the following things happen:
   2415 	 * 1. The table no longer has any wired entries and is considered
   2416 	 *    unwired.
   2417 	 * 2. It is placed on the available queue.
   2418 	 * 3. The parent table's wired entry count is decremented.
   2419 	 * 4. If it reaches zero, this process repeats at step 1 and
   2420 	 *    stops at after reaching the A table.
   2421 	 */
   2422 	if (--c_tbl->ct_wcnt == 0) {
   2423 		TAILQ_INSERT_TAIL(&c_pool, c_tbl, ct_link);
   2424 		if (--b_tbl->bt_wcnt == 0) {
   2425 			TAILQ_INSERT_TAIL(&b_pool, b_tbl, bt_link);
   2426 			if (--a_tbl->at_wcnt == 0) {
   2427 				TAILQ_INSERT_TAIL(&a_pool, a_tbl, at_link);
   2428 			}
   2429 		}
   2430 	}
   2431 }
   2432 
   2433 /* pmap_pageable			INTERFACE
   2434  **
   2435  * Make the specified range of addresses within the given pmap,
   2436  * 'pageable' or 'not-pageable'.  A pageable page must not cause
   2437  * any faults when referenced.  A non-pageable page may.
   2438  *
   2439  * This routine is only advisory.  The VM system will call pmap_enter()
   2440  * to wire or unwire pages that are going to be made pageable before calling
   2441  * this function.  By the time this routine is called, everything that needs
   2442  * to be done has already been done.
   2443  */
   2444 void
   2445 pmap_pageable(pmap, start, end, pageable)
   2446 	pmap_t pmap;
   2447 	vm_offset_t start, end;
   2448 	boolean_t pageable;
   2449 {
   2450 	/* not implemented. */
   2451 }
   2452 
   2453 /* pmap_copy				INTERFACE
   2454  **
   2455  * Copy the mappings of a range of addresses in one pmap, into
   2456  * the destination address of another.
   2457  *
   2458  * This routine is advisory.  Should we one day decide that MMU tables
   2459  * may be shared by more than one pmap, this function should be used to
   2460  * link them together.  Until that day however, we do nothing.
   2461  */
   2462 void
   2463 pmap_copy(pmap_a, pmap_b, dst, len, src)
   2464 	pmap_t pmap_a, pmap_b;
   2465 	vm_offset_t dst;
   2466 	vm_size_t   len;
   2467 	vm_offset_t src;
   2468 {
   2469 	/* not implemented. */
   2470 }
   2471 
   2472 /* pmap_copy_page			INTERFACE
   2473  **
   2474  * Copy the contents of one physical page into another.
   2475  *
   2476  * This function makes use of two virtual pages allocated in pmap_bootstrap()
   2477  * to map the two specified physical pages into the kernel address space.  It
   2478  * then uses bcopy() to copy one into the other.
   2479  *
   2480  * Note: We could use the transparent translation registers to make the
   2481  * mappings.  If we do so, be sure to disable interrupts before using them.
   2482  */
   2483 void
   2484 pmap_copy_page(src, dst)
   2485 	vm_offset_t src, dst;
   2486 {
   2487 	PMAP_LOCK();
   2488 	if (tmp_vpages_inuse)
   2489 		panic("pmap_copy_page: temporary vpages are in use.");
   2490 	tmp_vpages_inuse++;
   2491 
   2492 	/* XXX - Use non-cached mappings to avoid cache polution? */
   2493 	pmap_enter_kernel(tmp_vpages[0], src, VM_PROT_READ);
   2494 	pmap_enter_kernel(tmp_vpages[1], dst, VM_PROT_READ|VM_PROT_WRITE);
   2495 	copypage((char *) tmp_vpages[0], (char *) tmp_vpages[1]);
   2496 
   2497 	tmp_vpages_inuse--;
   2498 	PMAP_UNLOCK();
   2499 }
   2500 
   2501 /* pmap_zero_page			INTERFACE
   2502  **
   2503  * Zero the contents of the specified physical page.
   2504  *
   2505  * Uses one of the virtual pages allocated in pmap_boostrap()
   2506  * to map the specified page into the kernel address space.  Then uses
   2507  * bzero() to zero out the page.
   2508  */
   2509 void
   2510 pmap_zero_page(pa)
   2511 	vm_offset_t pa;
   2512 {
   2513 	PMAP_LOCK();
   2514 	if (tmp_vpages_inuse)
   2515 		panic("pmap_zero_page: temporary vpages are in use.");
   2516 	tmp_vpages_inuse++;
   2517 
   2518 	pmap_enter_kernel(tmp_vpages[0], pa, VM_PROT_READ|VM_PROT_WRITE);
   2519 	zeropage((char *) tmp_vpages[0]);
   2520 
   2521 	tmp_vpages_inuse--;
   2522 	PMAP_UNLOCK();
   2523 }
   2524 
   2525 /* pmap_collect			INTERFACE
   2526  **
   2527  * Called from the VM system when we are about to swap out
   2528  * the process using this pmap.  This should give up any
   2529  * resources held here, including all its MMU tables.
   2530  */
   2531 void
   2532 pmap_collect(pmap)
   2533 	pmap_t pmap;
   2534 {
   2535 	/* XXX - todo... */
   2536 }
   2537 
   2538 /* pmap_create			INTERFACE
   2539  **
   2540  * Create and return a pmap structure.
   2541  */
   2542 pmap_t
   2543 pmap_create(size)
   2544 	vm_size_t size;
   2545 {
   2546 	pmap_t	pmap;
   2547 
   2548 	if (size)
   2549 		return NULL;
   2550 
   2551 	pmap = (pmap_t) malloc(sizeof(struct pmap), M_VMPMAP, M_WAITOK);
   2552 	pmap_pinit(pmap);
   2553 
   2554 	return pmap;
   2555 }
   2556 
   2557 /* pmap_pinit			INTERNAL
   2558  **
   2559  * Initialize a pmap structure.
   2560  */
   2561 void
   2562 pmap_pinit(pmap)
   2563 	pmap_t pmap;
   2564 {
   2565 	bzero(pmap, sizeof(struct pmap));
   2566 	pmap->pm_a_tmgr = NULL;
   2567 	pmap->pm_a_phys = kernAphys;
   2568 }
   2569 
   2570 /* pmap_release				INTERFACE
   2571  **
   2572  * Release any resources held by the given pmap.
   2573  *
   2574  * This is the reverse analog to pmap_pinit.  It does not
   2575  * necessarily mean for the pmap structure to be deallocated,
   2576  * as in pmap_destroy.
   2577  */
   2578 void
   2579 pmap_release(pmap)
   2580 	pmap_t pmap;
   2581 {
   2582 	/*
   2583 	 * As long as the pmap contains no mappings,
   2584 	 * which always should be the case whenever
   2585 	 * this function is called, there really should
   2586 	 * be nothing to do.
   2587 	 *
   2588 	 * XXX - This function is being called while there are
   2589 	 * still valid mappings, so I guess the above must not
   2590 	 * be true.
   2591 	 * XXX - Unless the mappings persist due to a bug here...
   2592 	 *     + That's what was happening.  The map had no mappings,
   2593 	 *       but it still had an A table.  pmap_remove() was not
   2594 	 *       releasing tables when they were empty.
   2595 	 */
   2596 #ifdef	PMAP_DEBUG
   2597 	if (pmap == NULL)
   2598 		return;
   2599 	if (pmap == pmap_kernel())
   2600 		panic("pmap_release: kernel pmap");
   2601 #endif
   2602 	/*
   2603 	 * XXX - If this pmap has an A table, give it back.
   2604 	 * The pmap SHOULD be empty by now, and pmap_remove
   2605 	 * should have already given back the A table...
   2606 	 * However, I see:  pmap->pm_a_tmgr->at_ecnt == 1
   2607 	 * at this point, which means some mapping was not
   2608 	 * removed when it should have been. -gwr
   2609 	 */
   2610 	if (pmap->pm_a_tmgr != NULL) {
   2611 		/* First make sure we are not using it! */
   2612 		if (kernel_crp.rp_addr == pmap->pm_a_phys) {
   2613 			kernel_crp.rp_addr = kernAphys;
   2614 			loadcrp(&kernel_crp);
   2615 		}
   2616 		free_a_table(pmap->pm_a_tmgr, TRUE);
   2617 		pmap->pm_a_tmgr = NULL;
   2618 		pmap->pm_a_phys = kernAphys;
   2619 	}
   2620 }
   2621 
   2622 /* pmap_reference			INTERFACE
   2623  **
   2624  * Increment the reference count of a pmap.
   2625  */
   2626 void
   2627 pmap_reference(pmap)
   2628 	pmap_t pmap;
   2629 {
   2630 	if (pmap == NULL)
   2631 		return;
   2632 
   2633 	/* pmap_lock(pmap); */
   2634 	pmap->pm_refcount++;
   2635 	/* pmap_unlock(pmap); */
   2636 }
   2637 
   2638 /* pmap_dereference			INTERNAL
   2639  **
   2640  * Decrease the reference count on the given pmap
   2641  * by one and return the current count.
   2642  */
   2643 int
   2644 pmap_dereference(pmap)
   2645 	pmap_t pmap;
   2646 {
   2647 	int rtn;
   2648 
   2649 	if (pmap == NULL)
   2650 		return 0;
   2651 
   2652 	/* pmap_lock(pmap); */
   2653 	rtn = --pmap->pm_refcount;
   2654 	/* pmap_unlock(pmap); */
   2655 
   2656 	return rtn;
   2657 }
   2658 
   2659 /* pmap_destroy			INTERFACE
   2660  **
   2661  * Decrement a pmap's reference count and delete
   2662  * the pmap if it becomes zero.  Will be called
   2663  * only after all mappings have been removed.
   2664  */
   2665 void
   2666 pmap_destroy(pmap)
   2667 	pmap_t pmap;
   2668 {
   2669 	if (pmap == NULL)
   2670 		return;
   2671 	if (pmap == &kernel_pmap)
   2672 		panic("pmap_destroy: kernel_pmap!");
   2673 	if (pmap_dereference(pmap) == 0) {
   2674 		pmap_release(pmap);
   2675 		free(pmap, M_VMPMAP);
   2676 	}
   2677 }
   2678 
   2679 /* pmap_is_referenced			INTERFACE
   2680  **
   2681  * Determine if the given physical page has been
   2682  * referenced (read from [or written to.])
   2683  */
   2684 boolean_t
   2685 pmap_is_referenced(pa)
   2686 	vm_offset_t pa;
   2687 {
   2688 	pv_t      *pv;
   2689 	int       idx, s;
   2690 
   2691 	if (!pv_initialized)
   2692 		return FALSE;
   2693 	/* XXX - this may be unecessary. */
   2694 	if (!is_managed(pa))
   2695 		return FALSE;
   2696 
   2697 	pv = pa2pv(pa);
   2698 	/*
   2699 	 * Check the flags on the pv head.  If they are set,
   2700 	 * return immediately.  Otherwise a search must be done.
   2701 	 */
   2702 	if (pv->pv_flags & PV_FLAGS_USED)
   2703 		return TRUE;
   2704 	else {
   2705 		s = splimp();
   2706 		/*
   2707 		 * Search through all pv elements pointing
   2708 		 * to this page and query their reference bits
   2709 		 */
   2710 		for (idx = pv->pv_idx; idx != PVE_EOL; idx =
   2711 			pvebase[idx].pve_next)
   2712 			if (MMU_PTE_USED(kernCbase[idx])) {
   2713 				splx(s);
   2714 				return TRUE;
   2715 			}
   2716 		splx(s);
   2717 	}
   2718 
   2719 	return FALSE;
   2720 }
   2721 
   2722 /* pmap_is_modified			INTERFACE
   2723  **
   2724  * Determine if the given physical page has been
   2725  * modified (written to.)
   2726  */
   2727 boolean_t
   2728 pmap_is_modified(pa)
   2729 	vm_offset_t pa;
   2730 {
   2731 	pv_t      *pv;
   2732 	int       idx, s;
   2733 
   2734 	if (!pv_initialized)
   2735 		return FALSE;
   2736 	/* XXX - this may be unecessary. */
   2737 	if (!is_managed(pa))
   2738 		return FALSE;
   2739 
   2740 	/* see comments in pmap_is_referenced() */
   2741 	pv = pa2pv(pa);
   2742 	if (pv->pv_flags & PV_FLAGS_MDFY) {
   2743 		return TRUE;
   2744 	} else {
   2745 		s = splimp();
   2746 		for (idx = pv->pv_idx; idx != PVE_EOL; idx =
   2747 			pvebase[idx].pve_next)
   2748 			if (MMU_PTE_MODIFIED(kernCbase[idx])) {
   2749 				splx(s);
   2750 				return TRUE;
   2751 			}
   2752 		splx(s);
   2753 	}
   2754 
   2755 	return FALSE;
   2756 }
   2757 
   2758 /* pmap_page_protect			INTERFACE
   2759  **
   2760  * Applies the given protection to all mappings to the given
   2761  * physical page.
   2762  */
   2763 void
   2764 pmap_page_protect(pa, prot)
   2765 	vm_offset_t pa;
   2766 	vm_prot_t prot;
   2767 {
   2768 	pv_t      *pv;
   2769 	int       idx, s;
   2770 	vm_offset_t va;
   2771 	struct mmu_short_pte_struct *pte;
   2772 	c_tmgr_t  *c_tbl;
   2773 	pmap_t    pmap, curpmap;
   2774 
   2775 	if (!is_managed(pa))
   2776 		return;
   2777 
   2778 	curpmap = current_pmap();
   2779 	pv = pa2pv(pa);
   2780 	s = splimp();
   2781 	for (idx = pv->pv_idx; idx != PVE_EOL; idx = pvebase[idx].pve_next) {
   2782 		pte = &kernCbase[idx];
   2783 		switch (prot) {
   2784 			case VM_PROT_ALL:
   2785 				/* do nothing */
   2786 				break;
   2787 			case VM_PROT_EXECUTE:
   2788 			case VM_PROT_READ:
   2789 			case VM_PROT_READ|VM_PROT_EXECUTE:
   2790 				pte->attr.raw |= MMU_SHORT_PTE_WP;
   2791 
   2792 				/*
   2793 				 * Determine the virtual address mapped by
   2794 				 * the PTE and flush ATC entries if necessary.
   2795 				 */
   2796 				va = pmap_get_pteinfo(idx, &pmap, &c_tbl);
   2797 				if (pmap == curpmap || pmap == pmap_kernel())
   2798 					TBIS(va);
   2799 				break;
   2800 			case VM_PROT_NONE:
   2801 				/* Save the mod/ref bits. */
   2802 				pv->pv_flags |= pte->attr.raw;
   2803 				/* Invalidate the PTE. */
   2804 				pte->attr.raw = MMU_DT_INVALID;
   2805 
   2806 				/*
   2807 				 * Update table counts.  And flush ATC entries
   2808 				 * if necessary.
   2809 				 */
   2810 				va = pmap_get_pteinfo(idx, &pmap, &c_tbl);
   2811 
   2812 				/*
   2813 				 * If the PTE belongs to the kernel map,
   2814 				 * be sure to flush the page it maps.
   2815 				 */
   2816 				if (pmap == pmap_kernel()) {
   2817 					TBIS(va);
   2818 				} else {
   2819 					/*
   2820 					 * The PTE belongs to a user map.
   2821 					 * update the entry count in the C
   2822 					 * table to which it belongs and flush
   2823 					 * the ATC if the mapping belongs to
   2824 					 * the current pmap.
   2825 					 */
   2826 					c_tbl->ct_ecnt--;
   2827 					if (pmap == curpmap)
   2828 						TBIS(va);
   2829 				}
   2830 				break;
   2831 			default:
   2832 				break;
   2833 		}
   2834 	}
   2835 
   2836 	/*
   2837 	 * If the protection code indicates that all mappings to the page
   2838 	 * be removed, truncate the PV list to zero entries.
   2839 	 */
   2840 	if (prot == VM_PROT_NONE)
   2841 		pv->pv_idx = PVE_EOL;
   2842 	splx(s);
   2843 }
   2844 
   2845 /* pmap_get_pteinfo		INTERNAL
   2846  **
   2847  * Called internally to find the pmap and virtual address within that
   2848  * map to which the pte at the given index maps.  Also includes the PTE's C
   2849  * table manager.
   2850  *
   2851  * Returns the pmap in the argument provided, and the virtual address
   2852  * by return value.
   2853  */
   2854 vm_offset_t
   2855 pmap_get_pteinfo(idx, pmap, tbl)
   2856 	u_int idx;
   2857 	pmap_t *pmap;
   2858 	c_tmgr_t **tbl;
   2859 {
   2860 	a_tmgr_t    *a_tbl;
   2861 	b_tmgr_t    *b_tbl;
   2862 	c_tmgr_t    *c_tbl;
   2863 	vm_offset_t     va = 0;
   2864 
   2865 	/*
   2866 	 * Determine if the PTE is a kernel PTE or a user PTE.
   2867 	 */
   2868 	if (idx >= NUM_KERN_PTES) {
   2869 		/*
   2870 		 * The PTE belongs to a user mapping.
   2871 		 * Find the virtual address by decoding table indices.
   2872 		 * Each successive decode will reveal the address from
   2873 		 * least to most significant bit fashion.
   2874 		 *
   2875 		 * 31                              0
   2876 		 * +-------------------------------+
   2877 		 * |AAAAAAABBBBBBCCCCCC............|
   2878 		 * +-------------------------------+
   2879 		 */
   2880 		/* XXX: c_tbl = mmuC2tmgr(pte); */
   2881 		/* XXX: Would like an inline for this to validate idx... */
   2882 		c_tbl = &Ctmgrbase[(idx - NUM_KERN_PTES) / MMU_C_TBL_SIZE];
   2883 		b_tbl = c_tbl->ct_parent;
   2884 		a_tbl = b_tbl->bt_parent;
   2885 		*pmap = a_tbl->at_parent;
   2886 		*tbl = c_tbl;
   2887 
   2888 		/* Start with the 'C' bits, then add B and A... */
   2889 		va |= ((idx % MMU_C_TBL_SIZE) << MMU_TIC_SHIFT);
   2890 		va |= (c_tbl->ct_pidx << MMU_TIB_SHIFT);
   2891 		va |= (b_tbl->bt_pidx << MMU_TIA_SHIFT);
   2892 	} else {
   2893 		/*
   2894 		 * The PTE belongs to the kernel map.
   2895 		 */
   2896 		*pmap = pmap_kernel();
   2897 
   2898 		va = sun3x_ptob(idx);
   2899 		va += KERNBASE;
   2900 	}
   2901 
   2902 	return va;
   2903 }
   2904 
   2905 #if	0	/* XXX - I am eliminating this function. */
   2906 /* pmap_find_tic			INTERNAL
   2907  **
   2908  * Given the address of a pte, find the TIC (level 'C' table index) for
   2909  * the pte within its C table.
   2910  */
   2911 char
   2912 pmap_find_tic(pte)
   2913 	mmu_short_pte_t *pte;
   2914 {
   2915 	return ((pte - mmuCbase) % MMU_C_TBL_SIZE);
   2916 }
   2917 #endif	/* 0 */
   2918 
   2919 
   2920 /* pmap_clear_modify			INTERFACE
   2921  **
   2922  * Clear the modification bit on the page at the specified
   2923  * physical address.
   2924  *
   2925  */
   2926 void
   2927 pmap_clear_modify(pa)
   2928 	vm_offset_t pa;
   2929 {
   2930 	pmap_clear_pv(pa, PV_FLAGS_MDFY);
   2931 }
   2932 
   2933 /* pmap_clear_reference			INTERFACE
   2934  **
   2935  * Clear the referenced bit on the page at the specified
   2936  * physical address.
   2937  */
   2938 void
   2939 pmap_clear_reference(pa)
   2940 	vm_offset_t pa;
   2941 {
   2942 	pmap_clear_pv(pa, PV_FLAGS_USED);
   2943 }
   2944 
   2945 /* pmap_clear_pv			INTERNAL
   2946  **
   2947  * Clears the specified flag from the specified physical address.
   2948  * (Used by pmap_clear_modify() and pmap_clear_reference().)
   2949  *
   2950  * Flag is one of:
   2951  *   PV_FLAGS_MDFY - Page modified bit.
   2952  *   PV_FLAGS_USED - Page used (referenced) bit.
   2953  *
   2954  * This routine must not only clear the flag on the pv list
   2955  * head.  It must also clear the bit on every pte in the pv
   2956  * list associated with the address.
   2957  */
   2958 void
   2959 pmap_clear_pv(pa, flag)
   2960 	vm_offset_t pa;
   2961 	int flag;
   2962 {
   2963 	pv_t      *pv;
   2964 	int       idx, s;
   2965 	vm_offset_t     va;
   2966 	pmap_t          pmap;
   2967 	mmu_short_pte_t *pte;
   2968 	c_tmgr_t        *c_tbl;
   2969 
   2970 	pv = pa2pv(pa);
   2971 
   2972 	s = splimp();
   2973 	pv->pv_flags &= ~(flag);
   2974 	for (idx = pv->pv_idx; idx != PVE_EOL; idx = pvebase[idx].pve_next) {
   2975 		pte = &kernCbase[idx];
   2976 		pte->attr.raw &= ~(flag);
   2977 		/*
   2978 		 * The MC68030 MMU will not set the modified or
   2979 		 * referenced bits on any MMU tables for which it has
   2980 		 * a cached descriptor with its modify bit set.  To insure
   2981 		 * that it will modify these bits on the PTE during the next
   2982 		 * time it is written to or read from, we must flush it from
   2983 		 * the ATC.
   2984 		 *
   2985 		 * Ordinarily it is only necessary to flush the descriptor
   2986 		 * if it is used in the current address space.  But since I
   2987 		 * am not sure that there will always be a notion of
   2988 		 * 'the current address space' when this function is called,
   2989 		 * I will skip the test and always flush the address.  It
   2990 		 * does no harm.
   2991 		 */
   2992 		va = pmap_get_pteinfo(idx, &pmap, &c_tbl);
   2993 		TBIS(va);
   2994 	}
   2995 	splx(s);
   2996 }
   2997 
   2998 /* pmap_extract			INTERFACE
   2999  **
   3000  * Return the physical address mapped by the virtual address
   3001  * in the specified pmap or 0 if it is not known.
   3002  *
   3003  * Note: this function should also apply an exclusive lock
   3004  * on the pmap system during its duration.
   3005  */
   3006 vm_offset_t
   3007 pmap_extract(pmap, va)
   3008 	pmap_t      pmap;
   3009 	vm_offset_t va;
   3010 {
   3011 	int a_idx, b_idx, pte_idx;
   3012 	a_tmgr_t	*a_tbl;
   3013 	b_tmgr_t	*b_tbl;
   3014 	c_tmgr_t	*c_tbl;
   3015 	mmu_short_pte_t	*c_pte;
   3016 
   3017 	if (pmap == pmap_kernel())
   3018 		return pmap_extract_kernel(va);
   3019 	if (pmap == NULL)
   3020 		return 0;
   3021 
   3022 	if (pmap_stroll(pmap, va, &a_tbl, &b_tbl, &c_tbl,
   3023 		&c_pte, &a_idx, &b_idx, &pte_idx) == FALSE)
   3024 		return 0;
   3025 
   3026 	if (!MMU_VALID_DT(*c_pte))
   3027 		return 0;
   3028 
   3029 	return (MMU_PTE_PA(*c_pte));
   3030 }
   3031 
   3032 /* pmap_extract_kernel		INTERNAL
   3033  **
   3034  * Extract a translation from the kernel address space.
   3035  */
   3036 vm_offset_t
   3037 pmap_extract_kernel(va)
   3038 	vm_offset_t va;
   3039 {
   3040 	mmu_short_pte_t *pte;
   3041 
   3042 	pte = &kernCbase[(u_int) sun3x_btop(va - KERNBASE)];
   3043 	return MMU_PTE_PA(*pte);
   3044 }
   3045 
   3046 /* pmap_remove_kernel		INTERNAL
   3047  **
   3048  * Remove the mapping of a range of virtual addresses from the kernel map.
   3049  * The arguments are already page-aligned.
   3050  */
   3051 void
   3052 pmap_remove_kernel(sva, eva)
   3053 	vm_offset_t sva;
   3054 	vm_offset_t eva;
   3055 {
   3056 	int idx, eidx;
   3057 
   3058 #ifdef	PMAP_DEBUG
   3059 	if ((sva & PGOFSET) || (eva & PGOFSET))
   3060 		panic("pmap_remove_kernel: alignment");
   3061 #endif
   3062 
   3063 	idx  = sun3x_btop(sva - KERNBASE);
   3064 	eidx = sun3x_btop(eva - KERNBASE);
   3065 
   3066 	while (idx < eidx)
   3067 		pmap_remove_pte(&kernCbase[idx++]);
   3068 	/* Always flush the ATC when maniplating the kernel address space. */
   3069 	TBIAS();
   3070 }
   3071 
   3072 /* pmap_remove			INTERFACE
   3073  **
   3074  * Remove the mapping of a range of virtual addresses from the given pmap.
   3075  *
   3076  * If the range contains any wired entries, this function will probably create
   3077  * disaster.
   3078  */
   3079 void
   3080 pmap_remove(pmap, start, end)
   3081 	pmap_t pmap;
   3082 	vm_offset_t start;
   3083 	vm_offset_t end;
   3084 {
   3085 
   3086 	if (pmap == pmap_kernel()) {
   3087 		pmap_remove_kernel(start, end);
   3088 		return;
   3089 	}
   3090 
   3091 	/*
   3092 	 * XXX - Temporary(?) statement to prevent panic caused
   3093 	 * by vm_alloc_with_pager() handing us a software map (ie NULL)
   3094 	 * to remove because it couldn't get backing store.
   3095 	 * (I guess.)
   3096 	 */
   3097 	if (pmap == NULL)
   3098 		return;
   3099 
   3100 	/*
   3101 	 * If the pmap doesn't have an A table of its own, it has no mappings
   3102 	 * that can be removed.
   3103 	 */
   3104 	if (pmap->pm_a_tmgr == NULL)
   3105 		return;
   3106 
   3107 	/*
   3108 	 * Remove the specified range from the pmap.  If the function
   3109 	 * returns true, the operation removed all the valid mappings
   3110 	 * in the pmap and freed its A table.  If this happened to the
   3111 	 * currently loaded pmap, the MMU root pointer must be reloaded
   3112 	 * with the default 'kernel' map.
   3113 	 */
   3114 	if (pmap_remove_a(pmap->pm_a_tmgr, start, end)) {
   3115 		if (kernel_crp.rp_addr == pmap->pm_a_phys) {
   3116 			kernel_crp.rp_addr = kernAphys;
   3117 			loadcrp(&kernel_crp);
   3118 			/* will do TLB flush below */
   3119 		}
   3120 		pmap->pm_a_tmgr = NULL;
   3121 		pmap->pm_a_phys = kernAphys;
   3122 	}
   3123 
   3124 	/*
   3125 	 * If we just modified the current address space,
   3126 	 * make sure to flush the MMU cache.
   3127 	 *
   3128 	 * XXX - this could be an unecessarily large flush.
   3129 	 * XXX - Could decide, based on the size of the VA range
   3130 	 * to be removed, whether to flush "by pages" or "all".
   3131 	 */
   3132 	if (pmap == current_pmap())
   3133 		TBIAU();
   3134 }
   3135 
   3136 /* pmap_remove_a			INTERNAL
   3137  **
   3138  * This is function number one in a set of three that removes a range
   3139  * of memory in the most efficient manner by removing the highest possible
   3140  * tables from the memory space.  This particular function attempts to remove
   3141  * as many B tables as it can, delegating the remaining fragmented ranges to
   3142  * pmap_remove_b().
   3143  *
   3144  * If the removal operation results in an empty A table, the function returns
   3145  * TRUE.
   3146  *
   3147  * It's ugly but will do for now.
   3148  */
   3149 boolean_t
   3150 pmap_remove_a(a_tbl, start, end)
   3151 	a_tmgr_t *a_tbl;
   3152 	vm_offset_t start;
   3153 	vm_offset_t end;
   3154 {
   3155 	boolean_t empty;
   3156 	int idx;
   3157 	vm_offset_t nstart, nend;
   3158 	b_tmgr_t *b_tbl;
   3159 	mmu_long_dte_t  *a_dte;
   3160 	mmu_short_dte_t *b_dte;
   3161 
   3162 	/*
   3163 	 * The following code works with what I call a 'granularity
   3164 	 * reduction algorithim'.  A range of addresses will always have
   3165 	 * the following properties, which are classified according to
   3166 	 * how the range relates to the size of the current granularity
   3167 	 * - an A table entry:
   3168 	 *
   3169 	 *            1 2       3 4
   3170 	 * -+---+---+---+---+---+---+---+-
   3171 	 * -+---+---+---+---+---+---+---+-
   3172 	 *
   3173 	 * A range will always start on a granularity boundary, illustrated
   3174 	 * by '+' signs in the table above, or it will start at some point
   3175 	 * inbetween a granularity boundary, as illustrated by point 1.
   3176 	 * The first step in removing a range of addresses is to remove the
   3177 	 * range between 1 and 2, the nearest granularity boundary.  This
   3178 	 * job is handled by the section of code governed by the
   3179 	 * 'if (start < nstart)' statement.
   3180 	 *
   3181 	 * A range will always encompass zero or more intergral granules,
   3182 	 * illustrated by points 2 and 3.  Integral granules are easy to
   3183 	 * remove.  The removal of these granules is the second step, and
   3184 	 * is handled by the code block 'if (nstart < nend)'.
   3185 	 *
   3186 	 * Lastly, a range will always end on a granularity boundary,
   3187 	 * ill. by point 3, or it will fall just beyond one, ill. by point
   3188 	 * 4.  The last step involves removing this range and is handled by
   3189 	 * the code block 'if (nend < end)'.
   3190 	 */
   3191 	nstart = MMU_ROUND_UP_A(start);
   3192 	nend = MMU_ROUND_A(end);
   3193 
   3194 	if (start < nstart) {
   3195 		/*
   3196 		 * This block is executed if the range starts between
   3197 		 * a granularity boundary.
   3198 		 *
   3199 		 * First find the DTE which is responsible for mapping
   3200 		 * the start of the range.
   3201 		 */
   3202 		idx = MMU_TIA(start);
   3203 		a_dte = &a_tbl->at_dtbl[idx];
   3204 
   3205 		/*
   3206 		 * If the DTE is valid then delegate the removal of the sub
   3207 		 * range to pmap_remove_b(), which can remove addresses at
   3208 		 * a finer granularity.
   3209 		 */
   3210 		if (MMU_VALID_DT(*a_dte)) {
   3211 			b_dte = mmu_ptov(a_dte->addr.raw);
   3212 			b_tbl = mmuB2tmgr(b_dte);
   3213 
   3214 			/*
   3215 			 * The sub range to be removed starts at the start
   3216 			 * of the full range we were asked to remove, and ends
   3217 			 * at the greater of:
   3218 			 * 1. The end of the full range, -or-
   3219 			 * 2. The end of the full range, rounded down to the
   3220 			 *    nearest granularity boundary.
   3221 			 */
   3222 			if (end < nstart)
   3223 				empty = pmap_remove_b(b_tbl, start, end);
   3224 			else
   3225 				empty = pmap_remove_b(b_tbl, start, nstart);
   3226 
   3227 			/*
   3228 			 * If the removal resulted in an empty B table,
   3229 			 * invalidate the DTE that points to it and decrement
   3230 			 * the valid entry count of the A table.
   3231 			 */
   3232 			if (empty) {
   3233 				a_dte->attr.raw = MMU_DT_INVALID;
   3234 				a_tbl->at_ecnt--;
   3235 			}
   3236 		}
   3237 		/*
   3238 		 * If the DTE is invalid, the address range is already non-
   3239 		 * existant and can simply be skipped.
   3240 		 */
   3241 	}
   3242 	if (nstart < nend) {
   3243 		/*
   3244 		 * This block is executed if the range spans a whole number
   3245 		 * multiple of granules (A table entries.)
   3246 		 *
   3247 		 * First find the DTE which is responsible for mapping
   3248 		 * the start of the first granule involved.
   3249 		 */
   3250 		idx = MMU_TIA(nstart);
   3251 		a_dte = &a_tbl->at_dtbl[idx];
   3252 
   3253 		/*
   3254 		 * Remove entire sub-granules (B tables) one at a time,
   3255 		 * until reaching the end of the range.
   3256 		 */
   3257 		for (; nstart < nend; a_dte++, nstart += MMU_TIA_RANGE)
   3258 			if (MMU_VALID_DT(*a_dte)) {
   3259 				/*
   3260 				 * Find the B table manager for the
   3261 				 * entry and free it.
   3262 				 */
   3263 				b_dte = mmu_ptov(a_dte->addr.raw);
   3264 				b_tbl = mmuB2tmgr(b_dte);
   3265 				free_b_table(b_tbl, TRUE);
   3266 
   3267 				/*
   3268 				 * Invalidate the DTE that points to the
   3269 				 * B table and decrement the valid entry
   3270 				 * count of the A table.
   3271 				 */
   3272 				a_dte->attr.raw = MMU_DT_INVALID;
   3273 				a_tbl->at_ecnt--;
   3274 			}
   3275 	}
   3276 	if (nend < end) {
   3277 		/*
   3278 		 * This block is executed if the range ends beyond a
   3279 		 * granularity boundary.
   3280 		 *
   3281 		 * First find the DTE which is responsible for mapping
   3282 		 * the start of the nearest (rounded down) granularity
   3283 		 * boundary.
   3284 		 */
   3285 		idx = MMU_TIA(nend);
   3286 		a_dte = &a_tbl->at_dtbl[idx];
   3287 
   3288 		/*
   3289 		 * If the DTE is valid then delegate the removal of the sub
   3290 		 * range to pmap_remove_b(), which can remove addresses at
   3291 		 * a finer granularity.
   3292 		 */
   3293 		if (MMU_VALID_DT(*a_dte)) {
   3294 			/*
   3295 			 * Find the B table manager for the entry
   3296 			 * and hand it to pmap_remove_b() along with
   3297 			 * the sub range.
   3298 			 */
   3299 			b_dte = mmu_ptov(a_dte->addr.raw);
   3300 			b_tbl = mmuB2tmgr(b_dte);
   3301 
   3302 			empty = pmap_remove_b(b_tbl, nend, end);
   3303 
   3304 			/*
   3305 			 * If the removal resulted in an empty B table,
   3306 			 * invalidate the DTE that points to it and decrement
   3307 			 * the valid entry count of the A table.
   3308 			 */
   3309 			if (empty) {
   3310 				a_dte->attr.raw = MMU_DT_INVALID;
   3311 				a_tbl->at_ecnt--;
   3312 			}
   3313 		}
   3314 	}
   3315 
   3316 	/*
   3317 	 * If there are no more entries in the A table, release it
   3318 	 * back to the available pool and return TRUE.
   3319 	 */
   3320 	if (a_tbl->at_ecnt == 0) {
   3321 		a_tbl->at_parent = NULL;
   3322 		TAILQ_REMOVE(&a_pool, a_tbl, at_link);
   3323 		TAILQ_INSERT_HEAD(&a_pool, a_tbl, at_link);
   3324 		empty = TRUE;
   3325 	} else {
   3326 		empty = FALSE;
   3327 	}
   3328 
   3329 	return empty;
   3330 }
   3331 
   3332 /* pmap_remove_b			INTERNAL
   3333  **
   3334  * Remove a range of addresses from an address space, trying to remove entire
   3335  * C tables if possible.
   3336  *
   3337  * If the operation results in an empty B table, the function returns TRUE.
   3338  */
   3339 boolean_t
   3340 pmap_remove_b(b_tbl, start, end)
   3341 	b_tmgr_t *b_tbl;
   3342 	vm_offset_t start;
   3343 	vm_offset_t end;
   3344 {
   3345 	boolean_t empty;
   3346 	int idx;
   3347 	vm_offset_t nstart, nend, rstart;
   3348 	c_tmgr_t *c_tbl;
   3349 	mmu_short_dte_t  *b_dte;
   3350 	mmu_short_pte_t  *c_dte;
   3351 
   3352 
   3353 	nstart = MMU_ROUND_UP_B(start);
   3354 	nend = MMU_ROUND_B(end);
   3355 
   3356 	if (start < nstart) {
   3357 		idx = MMU_TIB(start);
   3358 		b_dte = &b_tbl->bt_dtbl[idx];
   3359 		if (MMU_VALID_DT(*b_dte)) {
   3360 			c_dte = mmu_ptov(MMU_DTE_PA(*b_dte));
   3361 			c_tbl = mmuC2tmgr(c_dte);
   3362 			if (end < nstart)
   3363 				empty = pmap_remove_c(c_tbl, start, end);
   3364 			else
   3365 				empty = pmap_remove_c(c_tbl, start, nstart);
   3366 			if (empty) {
   3367 				b_dte->attr.raw = MMU_DT_INVALID;
   3368 				b_tbl->bt_ecnt--;
   3369 			}
   3370 		}
   3371 	}
   3372 	if (nstart < nend) {
   3373 		idx = MMU_TIB(nstart);
   3374 		b_dte = &b_tbl->bt_dtbl[idx];
   3375 		rstart = nstart;
   3376 		while (rstart < nend) {
   3377 			if (MMU_VALID_DT(*b_dte)) {
   3378 				c_dte = mmu_ptov(MMU_DTE_PA(*b_dte));
   3379 				c_tbl = mmuC2tmgr(c_dte);
   3380 				free_c_table(c_tbl, TRUE);
   3381 				b_dte->attr.raw = MMU_DT_INVALID;
   3382 				b_tbl->bt_ecnt--;
   3383 			}
   3384 			b_dte++;
   3385 			rstart += MMU_TIB_RANGE;
   3386 		}
   3387 	}
   3388 	if (nend < end) {
   3389 		idx = MMU_TIB(nend);
   3390 		b_dte = &b_tbl->bt_dtbl[idx];
   3391 		if (MMU_VALID_DT(*b_dte)) {
   3392 			c_dte = mmu_ptov(MMU_DTE_PA(*b_dte));
   3393 			c_tbl = mmuC2tmgr(c_dte);
   3394 			empty = pmap_remove_c(c_tbl, nend, end);
   3395 			if (empty) {
   3396 				b_dte->attr.raw = MMU_DT_INVALID;
   3397 				b_tbl->bt_ecnt--;
   3398 			}
   3399 		}
   3400 	}
   3401 
   3402 	if (b_tbl->bt_ecnt == 0) {
   3403 		b_tbl->bt_parent = NULL;
   3404 		TAILQ_REMOVE(&b_pool, b_tbl, bt_link);
   3405 		TAILQ_INSERT_HEAD(&b_pool, b_tbl, bt_link);
   3406 		empty = TRUE;
   3407 	} else {
   3408 		empty = FALSE;
   3409 	}
   3410 
   3411 	return empty;
   3412 }
   3413 
   3414 /* pmap_remove_c			INTERNAL
   3415  **
   3416  * Remove a range of addresses from the given C table.
   3417  */
   3418 boolean_t
   3419 pmap_remove_c(c_tbl, start, end)
   3420 	c_tmgr_t *c_tbl;
   3421 	vm_offset_t start;
   3422 	vm_offset_t end;
   3423 {
   3424 	boolean_t empty;
   3425 	int idx;
   3426 	mmu_short_pte_t *c_pte;
   3427 
   3428 	idx = MMU_TIC(start);
   3429 	c_pte = &c_tbl->ct_dtbl[idx];
   3430 	for (;start < end; start += MMU_PAGE_SIZE, c_pte++) {
   3431 		if (MMU_VALID_DT(*c_pte)) {
   3432 			pmap_remove_pte(c_pte);
   3433 			c_tbl->ct_ecnt--;
   3434 		}
   3435 	}
   3436 
   3437 	if (c_tbl->ct_ecnt == 0) {
   3438 		c_tbl->ct_parent = NULL;
   3439 		TAILQ_REMOVE(&c_pool, c_tbl, ct_link);
   3440 		TAILQ_INSERT_HEAD(&c_pool, c_tbl, ct_link);
   3441 		empty = TRUE;
   3442 	} else {
   3443 		empty = FALSE;
   3444 	}
   3445 
   3446 	return empty;
   3447 }
   3448 
   3449 /* is_managed				INTERNAL
   3450  **
   3451  * Determine if the given physical address is managed by the PV system.
   3452  * Note that this logic assumes that no one will ask for the status of
   3453  * addresses which lie in-between the memory banks on the 3/80.  If they
   3454  * do so, it will falsely report that it is managed.
   3455  *
   3456  * Note: A "managed" address is one that was reported to the VM system as
   3457  * a "usable page" during system startup.  As such, the VM system expects the
   3458  * pmap module to keep an accurate track of the useage of those pages.
   3459  * Any page not given to the VM system at startup does not exist (as far as
   3460  * the VM system is concerned) and is therefore "unmanaged."  Examples are
   3461  * those pages which belong to the ROM monitor and the memory allocated before
   3462  * the VM system was started.
   3463  */
   3464 boolean_t
   3465 is_managed(pa)
   3466 	vm_offset_t pa;
   3467 {
   3468 	if (pa >= avail_start && pa < avail_end)
   3469 		return TRUE;
   3470 	else
   3471 		return FALSE;
   3472 }
   3473 
   3474 /* pmap_bootstrap_alloc			INTERNAL
   3475  **
   3476  * Used internally for memory allocation at startup when malloc is not
   3477  * available.  This code will fail once it crosses the first memory
   3478  * bank boundary on the 3/80.  Hopefully by then however, the VM system
   3479  * will be in charge of allocation.
   3480  */
   3481 void *
   3482 pmap_bootstrap_alloc(size)
   3483 	int size;
   3484 {
   3485 	void *rtn;
   3486 
   3487 #ifdef	PMAP_DEBUG
   3488 	if (bootstrap_alloc_enabled == FALSE) {
   3489 		mon_printf("pmap_bootstrap_alloc: disabled\n");
   3490 		sunmon_abort();
   3491 	}
   3492 #endif
   3493 
   3494 	rtn = (void *) virtual_avail;
   3495 	virtual_avail += size;
   3496 
   3497 #ifdef	PMAP_DEBUG
   3498 	if (virtual_avail > virtual_contig_end) {
   3499 		mon_printf("pmap_bootstrap_alloc: out of mem\n");
   3500 		sunmon_abort();
   3501 	}
   3502 #endif
   3503 
   3504 	return rtn;
   3505 }
   3506 
   3507 /* pmap_bootstap_aalign			INTERNAL
   3508  **
   3509  * Used to insure that the next call to pmap_bootstrap_alloc() will
   3510  * return a chunk of memory aligned to the specified size.
   3511  *
   3512  * Note: This function will only support alignment sizes that are powers
   3513  * of two.
   3514  */
   3515 void
   3516 pmap_bootstrap_aalign(size)
   3517 	int size;
   3518 {
   3519 	int off;
   3520 
   3521 	off = virtual_avail & (size - 1);
   3522 	if (off) {
   3523 		(void) pmap_bootstrap_alloc(size - off);
   3524 	}
   3525 }
   3526 
   3527 /* pmap_pa_exists
   3528  **
   3529  * Used by the /dev/mem driver to see if a given PA is memory
   3530  * that can be mapped.  (The PA is not in a hole.)
   3531  */
   3532 int
   3533 pmap_pa_exists(pa)
   3534 	vm_offset_t pa;
   3535 {
   3536 	/* XXX - NOTYET */
   3537 	return (0);
   3538 }
   3539 
   3540 /* pmap_activate			INTERFACE
   3541  **
   3542  * This is called by locore.s:cpu_switch when we are switching to a
   3543  * new process.  This should load the MMU context for the new proc.
   3544  * XXX - Later, this should be done directly in locore.s
   3545  */
   3546 void
   3547 pmap_activate(pmap)
   3548 pmap_t	pmap;
   3549 {
   3550 	u_long rootpa;
   3551 
   3552 	/* Only do reload/flush if we have to. */
   3553 	rootpa = pmap->pm_a_phys;
   3554 	if (kernel_crp.rp_addr != rootpa) {
   3555 		DPRINT(("pmap_activate(%p)\n", pmap));
   3556 		kernel_crp.rp_addr = rootpa;
   3557 		loadcrp(&kernel_crp);
   3558 		TBIAU();
   3559 	}
   3560 }
   3561 
   3562 
   3563 /* pmap_update
   3564  **
   3565  * Apply any delayed changes scheduled for all pmaps immediately.
   3566  *
   3567  * No delayed operations are currently done in this pmap.
   3568  */
   3569 void
   3570 pmap_update()
   3571 {
   3572 	/* not implemented. */
   3573 }
   3574 
   3575 /* pmap_virtual_space			INTERFACE
   3576  **
   3577  * Return the current available range of virtual addresses in the
   3578  * arguuments provided.  Only really called once.
   3579  */
   3580 void
   3581 pmap_virtual_space(vstart, vend)
   3582 	vm_offset_t *vstart, *vend;
   3583 {
   3584 	*vstart = virtual_avail;
   3585 	*vend = virtual_end;
   3586 }
   3587 
   3588 /* pmap_free_pages			INTERFACE
   3589  **
   3590  * Return the number of physical pages still available.
   3591  *
   3592  * This is probably going to be a mess, but it's only called
   3593  * once and it's the only function left that I have to implement!
   3594  */
   3595 u_int
   3596 pmap_free_pages()
   3597 {
   3598 	int i;
   3599 	u_int left;
   3600 	vm_offset_t avail;
   3601 
   3602 	avail = avail_next;
   3603 	left = 0;
   3604 	i = 0;
   3605 	while (avail >= avail_mem[i].pmem_end) {
   3606 		if (avail_mem[i].pmem_next == NULL)
   3607 			return 0;
   3608 		i++;
   3609 	}
   3610 	while (i < SUN3X_80_MEM_BANKS) {
   3611 		if (avail < avail_mem[i].pmem_start) {
   3612 			/* Avail is inside a hole, march it
   3613 			 * up to the next bank.
   3614 			 */
   3615 			avail = avail_mem[i].pmem_start;
   3616 		}
   3617 		left += sun3x_btop(avail_mem[i].pmem_end - avail);
   3618 		if (avail_mem[i].pmem_next == NULL)
   3619 			break;
   3620 		i++;
   3621 	}
   3622 
   3623 	return left;
   3624 }
   3625 
   3626 /* pmap_page_index			INTERFACE
   3627  **
   3628  * Return the index of the given physical page in a list of useable
   3629  * physical pages in the system.  Holes in physical memory may be counted
   3630  * if so desired.  As long as pmap_free_pages() and pmap_page_index()
   3631  * agree as to whether holes in memory do or do not count as valid pages,
   3632  * it really doesn't matter.  However, if you like to save a little
   3633  * memory, don't count holes as valid pages.  This is even more true when
   3634  * the holes are large.
   3635  *
   3636  * We will not count holes as valid pages.  We can generate page indices
   3637  * that conform to this by using the memory bank structures initialized
   3638  * in pmap_alloc_pv().
   3639  */
   3640 int
   3641 pmap_page_index(pa)
   3642 	vm_offset_t pa;
   3643 {
   3644 	struct pmap_physmem_struct *bank = avail_mem;
   3645 
   3646 	/* Search for the memory bank with this page. */
   3647 	/* XXX - What if it is not physical memory? */
   3648 	while (pa > bank->pmem_end)
   3649 		bank = bank->pmem_next;
   3650 	pa -= bank->pmem_start;
   3651 
   3652 	return (bank->pmem_pvbase + sun3x_btop(pa));
   3653 }
   3654 
   3655 /* pmap_next_page			INTERFACE
   3656  **
   3657  * Place the physical address of the next available page in the
   3658  * argument given.  Returns FALSE if there are no more pages left.
   3659  *
   3660  * This function must jump over any holes in physical memory.
   3661  * Once this function is used, any use of pmap_bootstrap_alloc()
   3662  * is a sin.  Sinners will be punished with erratic behavior.
   3663  */
   3664 boolean_t
   3665 pmap_next_page(pa)
   3666 	vm_offset_t *pa;
   3667 {
   3668 	static struct pmap_physmem_struct *curbank = avail_mem;
   3669 
   3670 	/* XXX - temporary ROM saving hack. */
   3671 	if (avail_next >= avail_end)
   3672 		return FALSE;
   3673 
   3674 	if (avail_next >= curbank->pmem_end)
   3675 		if (curbank->pmem_next == NULL)
   3676 			return FALSE;
   3677 		else {
   3678 			curbank = curbank->pmem_next;
   3679 			avail_next = curbank->pmem_start;
   3680 		}
   3681 
   3682 	*pa = avail_next;
   3683 	avail_next += NBPG;
   3684 	return TRUE;
   3685 }
   3686 
   3687 /* pmap_count			INTERFACE
   3688  **
   3689  * Return the number of resident (valid) pages in the given pmap.
   3690  *
   3691  * Note:  If this function is handed the kernel map, it will report
   3692  * that it has no mappings.  Hopefully the VM system won't ask for kernel
   3693  * map statistics.
   3694  */
   3695 segsz_t
   3696 pmap_count(pmap, type)
   3697 	pmap_t pmap;
   3698 	int    type;
   3699 {
   3700 	u_int     count;
   3701 	int       a_idx, b_idx;
   3702 	a_tmgr_t *a_tbl;
   3703 	b_tmgr_t *b_tbl;
   3704 	c_tmgr_t *c_tbl;
   3705 
   3706 	/*
   3707 	 * If the pmap does not have its own A table manager, it has no
   3708 	 * valid entires.
   3709 	 */
   3710 	if (pmap->pm_a_tmgr == NULL)
   3711 		return 0;
   3712 
   3713 	a_tbl = pmap->pm_a_tmgr;
   3714 
   3715 	count = 0;
   3716 	for (a_idx = 0; a_idx < MMU_TIA(KERNBASE); a_idx++) {
   3717 	    if (MMU_VALID_DT(a_tbl->at_dtbl[a_idx])) {
   3718 	        b_tbl = mmuB2tmgr(mmu_ptov(a_tbl->at_dtbl[a_idx].addr.raw));
   3719 	        for (b_idx = 0; b_idx < MMU_B_TBL_SIZE; b_idx++) {
   3720 	            if (MMU_VALID_DT(b_tbl->bt_dtbl[b_idx])) {
   3721 	                c_tbl = mmuC2tmgr(
   3722 	                    mmu_ptov(MMU_DTE_PA(b_tbl->bt_dtbl[b_idx])));
   3723 	                if (type == 0)
   3724 	                    /*
   3725 	                     * A resident entry count has been requested.
   3726 	                     */
   3727 	                    count += c_tbl->ct_ecnt;
   3728 	                else
   3729 	                    /*
   3730 	                     * A wired entry count has been requested.
   3731 	                     */
   3732 	                    count += c_tbl->ct_wcnt;
   3733 	            }
   3734 	        }
   3735 	    }
   3736 	}
   3737 
   3738 	return count;
   3739 }
   3740 
   3741 /************************ SUN3 COMPATIBILITY ROUTINES ********************
   3742  * The following routines are only used by DDB for tricky kernel text    *
   3743  * text operations in db_memrw.c.  They are provided for sun3            *
   3744  * compatibility.                                                        *
   3745  *************************************************************************/
   3746 /* get_pte			INTERNAL
   3747  **
   3748  * Return the page descriptor the describes the kernel mapping
   3749  * of the given virtual address.
   3750  *
   3751  * XXX - It might be nice if this worked outside of the MMU
   3752  * structures we manage.  (Could do it with ptest). -gwr
   3753  */
   3754 vm_offset_t
   3755 get_pte(va)
   3756 	vm_offset_t va;
   3757 {
   3758 	u_long idx;
   3759 
   3760 	if (va < KERNBASE)
   3761 		return 0;
   3762 
   3763 	idx = (u_long) sun3x_btop(va - KERNBASE);
   3764 	return (kernCbase[idx].attr.raw);
   3765 }
   3766 
   3767 /* set_pte			INTERNAL
   3768  **
   3769  * Set the page descriptor that describes the kernel mapping
   3770  * of the given virtual address.
   3771  */
   3772 void
   3773 set_pte(va, pte)
   3774 	vm_offset_t va;
   3775 	vm_offset_t pte;
   3776 {
   3777 	u_long idx;
   3778 
   3779 	if (va < KERNBASE)
   3780 		return;
   3781 
   3782 	idx = (unsigned long) sun3x_btop(va - KERNBASE);
   3783 	kernCbase[idx].attr.raw = pte;
   3784 }
   3785 
   3786 #ifdef	PMAP_DEBUG
   3787 /************************** DEBUGGING ROUTINES **************************
   3788  * The following routines are meant to be an aid to debugging the pmap  *
   3789  * system.  They are callable from the DDB command line and should be   *
   3790  * prepared to be handed unstable or incomplete states of the system.   *
   3791  ************************************************************************/
   3792 
   3793 /* pv_list
   3794  **
   3795  * List all pages found on the pv list for the given physical page.
   3796  * To avoid endless loops, the listing will stop at the end of the list
   3797  * or after 'n' entries - whichever comes first.
   3798  */
   3799 void
   3800 pv_list(pa, n)
   3801 	vm_offset_t pa;
   3802 	int n;
   3803 {
   3804 	int  idx;
   3805 	vm_offset_t va;
   3806 	pv_t *pv;
   3807 	c_tmgr_t *c_tbl;
   3808 	pmap_t pmap;
   3809 
   3810 	pv = pa2pv(pa);
   3811 	idx = pv->pv_idx;
   3812 
   3813 	for (;idx != PVE_EOL && n > 0; idx=pvebase[idx].pve_next, n--) {
   3814 		va = pmap_get_pteinfo(idx, &pmap, &c_tbl);
   3815 		printf("idx %d, pmap 0x%x, va 0x%x, c_tbl %x\n",
   3816 			idx, (u_int) pmap, (u_int) va, (u_int) c_tbl);
   3817 	}
   3818 }
   3819 #endif	/* PMAP_DEBUG */
   3820 
   3821 #ifdef NOT_YET
   3822 /* and maybe not ever */
   3823 /************************** LOW-LEVEL ROUTINES **************************
   3824  * These routines will eventualy be re-written into assembly and placed *
   3825  * in locore.s.  They are here now as stubs so that the pmap module can *
   3826  * be linked as a standalone user program for testing.                  *
   3827  ************************************************************************/
   3828 /* flush_atc_crp			INTERNAL
   3829  **
   3830  * Flush all page descriptors derived from the given CPU Root Pointer
   3831  * (CRP), or 'A' table as it is known here, from the 68851's automatic
   3832  * cache.
   3833  */
   3834 void
   3835 flush_atc_crp(a_tbl)
   3836 {
   3837 	mmu_long_rp_t rp;
   3838 
   3839 	/* Create a temporary root table pointer that points to the
   3840 	 * given A table.
   3841 	 */
   3842 	rp.attr.raw = ~MMU_LONG_RP_LU;
   3843 	rp.addr.raw = (unsigned int) a_tbl;
   3844 
   3845 	mmu_pflushr(&rp);
   3846 	/* mmu_pflushr:
   3847 	 * 	movel   sp(4)@,a0
   3848 	 * 	pflushr a0@
   3849 	 *	rts
   3850 	 */
   3851 }
   3852 #endif /* NOT_YET */
   3853