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