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