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