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