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