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