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