Home | History | Annotate | Line # | Download | only in sun3x
pmap.c revision 1.35
      1 /*	$NetBSD: pmap.c,v 1.35 1998/02/09 19:56:37 jeremy 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 <sys/param.h>
    115 #include <sys/systm.h>
    116 #include <sys/proc.h>
    117 #include <sys/malloc.h>
    118 #include <sys/user.h>
    119 #include <sys/queue.h>
    120 #include <sys/kcore.h>
    121 
    122 #include <vm/vm.h>
    123 #include <vm/vm_kern.h>
    124 #include <vm/vm_page.h>
    125 
    126 #include <machine/cpu.h>
    127 #include <machine/kcore.h>
    128 #include <machine/mon.h>
    129 #include <machine/pmap.h>
    130 #include <machine/pte.h>
    131 
    132 #include <sun3/sun3/cache.h>
    133 #include <sun3/sun3/machdep.h>
    134 
    135 #include "pmap_pvt.h"
    136 
    137 /* XXX - What headers declare these? */
    138 extern struct pcb *curpcb;
    139 extern int physmem;
    140 
    141 extern void copypage __P((const void*, void*));
    142 extern void zeropage __P((void*));
    143 
    144 /* Defined in locore.s */
    145 extern char kernel_text[];
    146 
    147 /* Defined by the linker */
    148 extern char etext[], edata[], end[];
    149 extern char *esym;	/* DDB */
    150 
    151 /*************************** DEBUGGING DEFINITIONS ***********************
    152  * Macros, preprocessor defines and variables used in debugging can make *
    153  * code hard to read.  Anything used exclusively for debugging purposes  *
    154  * is defined here to avoid having such mess scattered around the file.  *
    155  *************************************************************************/
    156 #ifdef	PMAP_DEBUG
    157 /*
    158  * To aid the debugging process, macros should be expanded into smaller steps
    159  * that accomplish the same goal, yet provide convenient places for placing
    160  * breakpoints.  When this code is compiled with PMAP_DEBUG mode defined, the
    161  * 'INLINE' keyword is defined to an empty string.  This way, any function
    162  * defined to be a 'static INLINE' will become 'outlined' and compiled as
    163  * a separate function, which is much easier to debug.
    164  */
    165 #define	INLINE	/* nothing */
    166 
    167 /*
    168  * It is sometimes convenient to watch the activity of a particular table
    169  * in the system.  The following variables are used for that purpose.
    170  */
    171 a_tmgr_t *pmap_watch_atbl = 0;
    172 b_tmgr_t *pmap_watch_btbl = 0;
    173 c_tmgr_t *pmap_watch_ctbl = 0;
    174 
    175 int pmap_debug = 0;
    176 #define DPRINT(args) if (pmap_debug) printf args
    177 
    178 #else	/********** Stuff below is defined if NOT debugging **************/
    179 
    180 #define	INLINE	inline
    181 #define DPRINT(args)  /* nada */
    182 
    183 #endif	/* PMAP_DEBUG */
    184 /*********************** END OF DEBUGGING DEFINITIONS ********************/
    185 
    186 /*** Management Structure - Memory Layout
    187  * For every MMU table in the sun3x pmap system there must be a way to
    188  * manage it; we must know which process is using it, what other tables
    189  * depend on it, and whether or not it contains any locked pages.  This
    190  * is solved by the creation of 'table management'  or 'tmgr'
    191  * structures.  One for each MMU table in the system.
    192  *
    193  *                        MAP OF MEMORY USED BY THE PMAP SYSTEM
    194  *
    195  *      towards lower memory
    196  * kernAbase -> +-------------------------------------------------------+
    197  *              | Kernel     MMU A level table                          |
    198  * kernBbase -> +-------------------------------------------------------+
    199  *              | Kernel     MMU B level tables                         |
    200  * kernCbase -> +-------------------------------------------------------+
    201  *              |                                                       |
    202  *              | Kernel     MMU C level tables                         |
    203  *              |                                                       |
    204  * mmuCbase  -> +-------------------------------------------------------+
    205  *              | User       MMU C level tables                         |
    206  * mmuAbase  -> +-------------------------------------------------------+
    207  *              |                                                       |
    208  *              | User       MMU A level tables                         |
    209  *              |                                                       |
    210  * mmuBbase  -> +-------------------------------------------------------+
    211  *              | User       MMU B level tables                         |
    212  * tmgrAbase -> +-------------------------------------------------------+
    213  *              |  TMGR A level table structures                        |
    214  * tmgrBbase -> +-------------------------------------------------------+
    215  *              |  TMGR B level table structures                        |
    216  * tmgrCbase -> +-------------------------------------------------------+
    217  *              |  TMGR C level table structures                        |
    218  * pvbase    -> +-------------------------------------------------------+
    219  *              |  Physical to Virtual mapping table (list heads)       |
    220  * pvebase   -> +-------------------------------------------------------+
    221  *              |  Physical to Virtual mapping table (list elements)    |
    222  *              |                                                       |
    223  *              +-------------------------------------------------------+
    224  *      towards higher memory
    225  *
    226  * For every A table in the MMU A area, there will be a corresponding
    227  * a_tmgr structure in the TMGR A area.  The same will be true for
    228  * the B and C tables.  This arrangement will make it easy to find the
    229  * controling tmgr structure for any table in the system by use of
    230  * (relatively) simple macros.
    231  */
    232 
    233 /*
    234  * Global variables for storing the base addresses for the areas
    235  * labeled above.
    236  */
    237 static vm_offset_t  	kernAphys;
    238 static mmu_long_dte_t	*kernAbase;
    239 static mmu_short_dte_t	*kernBbase;
    240 static mmu_short_pte_t	*kernCbase;
    241 static mmu_short_pte_t	*mmuCbase;
    242 static mmu_short_dte_t	*mmuBbase;
    243 static mmu_long_dte_t	*mmuAbase;
    244 static a_tmgr_t		*Atmgrbase;
    245 static b_tmgr_t		*Btmgrbase;
    246 static c_tmgr_t		*Ctmgrbase;
    247 static pv_t 		*pvbase;
    248 static pv_elem_t	*pvebase;
    249 struct pmap 		kernel_pmap;
    250 
    251 /*
    252  * This holds the CRP currently loaded into the MMU.
    253  */
    254 struct mmu_rootptr kernel_crp;
    255 
    256 /*
    257  * Just all around global variables.
    258  */
    259 static TAILQ_HEAD(a_pool_head_struct, a_tmgr_struct) a_pool;
    260 static TAILQ_HEAD(b_pool_head_struct, b_tmgr_struct) b_pool;
    261 static TAILQ_HEAD(c_pool_head_struct, c_tmgr_struct) c_pool;
    262 
    263 
    264 /*
    265  * Flags used to mark the safety/availability of certain operations or
    266  * resources.
    267  */
    268 static boolean_t pv_initialized = FALSE, /* PV system has been initialized. */
    269        bootstrap_alloc_enabled = FALSE; /*Safe to use pmap_bootstrap_alloc().*/
    270 int tmp_vpages_inuse;	/* Temporary virtual pages are in use */
    271 
    272 /*
    273  * XXX:  For now, retain the traditional variables that were
    274  * used in the old pmap/vm interface (without NONCONTIG).
    275  */
    276 /* Kernel virtual address space available: */
    277 vm_offset_t	virtual_avail, virtual_end;
    278 /* Physical address space available: */
    279 vm_offset_t	avail_start, avail_end;
    280 
    281 /* This keep track of the end of the contiguously mapped range. */
    282 vm_offset_t virtual_contig_end;
    283 
    284 /* Physical address used by pmap_next_page() */
    285 vm_offset_t avail_next;
    286 
    287 /* These are used by pmap_copy_page(), etc. */
    288 vm_offset_t tmp_vpages[2];
    289 
    290 /*
    291  * The 3/80 is the only member of the sun3x family that has non-contiguous
    292  * physical memory.  Memory is divided into 4 banks which are physically
    293  * locatable on the system board.  Although the size of these banks varies
    294  * with the size of memory they contain, their base addresses are
    295  * permenently fixed.  The following structure, which describes these
    296  * banks, is initialized by pmap_bootstrap() after it reads from a similar
    297  * structure provided by the ROM Monitor.
    298  *
    299  * For the other machines in the sun3x architecture which do have contiguous
    300  * RAM, this list will have only one entry, which will describe the entire
    301  * range of available memory.
    302  */
    303 struct pmap_physmem_struct avail_mem[SUN3X_NPHYS_RAM_SEGS];
    304 u_int total_phys_mem;
    305 
    306 /*************************************************************************/
    307 
    308 /*
    309  * XXX - Should "tune" these based on statistics.
    310  *
    311  * My first guess about the relative numbers of these needed is
    312  * based on the fact that a "typical" process will have several
    313  * pages mapped at low virtual addresses (text, data, bss), then
    314  * some mapped shared libraries, and then some stack pages mapped
    315  * near the high end of the VA space.  Each process can use only
    316  * one A table, and most will use only two B tables (maybe three)
    317  * and probably about four C tables.  Therefore, the first guess
    318  * at the relative numbers of these needed is 1:2:4 -gwr
    319  *
    320  * The number of C tables needed is closely related to the amount
    321  * of physical memory available plus a certain amount attributable
    322  * to the use of double mappings.  With a few simulation statistics
    323  * we can find a reasonably good estimation of this unknown value.
    324  * Armed with that and the above ratios, we have a good idea of what
    325  * is needed at each level. -j
    326  *
    327  * Note: It is not physical memory memory size, but the total mapped
    328  * virtual space required by the combined working sets of all the
    329  * currently _runnable_ processes.  (Sleeping ones don't count.)
    330  * The amount of physical memory should be irrelevant. -gwr
    331  */
    332 #ifdef	FIXED_NTABLES
    333 #define NUM_A_TABLES	16
    334 #define NUM_B_TABLES	32
    335 #define NUM_C_TABLES	64
    336 #else
    337 unsigned int	NUM_A_TABLES, NUM_B_TABLES, NUM_C_TABLES;
    338 #endif	/* FIXED_NTABLES */
    339 
    340 /*
    341  * This determines our total virtual mapping capacity.
    342  * Yes, it is a FIXED value so we can pre-allocate.
    343  */
    344 #define NUM_USER_PTES	(NUM_C_TABLES * MMU_C_TBL_SIZE)
    345 
    346 /*
    347  * The size of the Kernel Virtual Address Space (KVAS)
    348  * for purposes of MMU table allocation is -KERNBASE
    349  * (length from KERNBASE to 0xFFFFffff)
    350  */
    351 #define	KVAS_SIZE		(-KERNBASE)
    352 
    353 /* Numbers of kernel MMU tables to support KVAS_SIZE. */
    354 #define KERN_B_TABLES	(KVAS_SIZE >> MMU_TIA_SHIFT)
    355 #define KERN_C_TABLES	(KVAS_SIZE >> MMU_TIB_SHIFT)
    356 #define	NUM_KERN_PTES	(KVAS_SIZE >> MMU_TIC_SHIFT)
    357 
    358 /*************************** MISCELANEOUS MACROS *************************/
    359 #define PMAP_LOCK()	;	/* Nothing, for now */
    360 #define PMAP_UNLOCK()	;	/* same. */
    361 #define	NULL 0
    362 
    363 static INLINE void *      mmu_ptov __P((vm_offset_t pa));
    364 static INLINE vm_offset_t mmu_vtop __P((void * va));
    365 
    366 #if	0
    367 static INLINE a_tmgr_t * mmuA2tmgr __P((mmu_long_dte_t *));
    368 #endif /* 0 */
    369 static INLINE b_tmgr_t * mmuB2tmgr __P((mmu_short_dte_t *));
    370 static INLINE c_tmgr_t * mmuC2tmgr __P((mmu_short_pte_t *));
    371 
    372 static INLINE pv_t *pa2pv __P((vm_offset_t pa));
    373 static INLINE int   pteidx __P((mmu_short_pte_t *));
    374 static INLINE pmap_t current_pmap __P((void));
    375 
    376 /*
    377  * We can always convert between virtual and physical addresses
    378  * for anything in the range [KERNBASE ... avail_start] because
    379  * that range is GUARANTEED to be mapped linearly.
    380  * We rely heavily upon this feature!
    381  */
    382 static INLINE void *
    383 mmu_ptov(pa)
    384 	vm_offset_t pa;
    385 {
    386 	register vm_offset_t va;
    387 
    388 	va = (pa + KERNBASE);
    389 #ifdef	PMAP_DEBUG
    390 	if ((va < KERNBASE) || (va >= virtual_contig_end))
    391 		panic("mmu_ptov");
    392 #endif
    393 	return ((void*)va);
    394 }
    395 static INLINE vm_offset_t
    396 mmu_vtop(vva)
    397 	void *vva;
    398 {
    399 	register vm_offset_t va;
    400 
    401 	va = (vm_offset_t)vva;
    402 #ifdef	PMAP_DEBUG
    403 	if ((va < KERNBASE) || (va >= virtual_contig_end))
    404 		panic("mmu_ptov");
    405 #endif
    406 	return (va - KERNBASE);
    407 }
    408 
    409 /*
    410  * These macros map MMU tables to their corresponding manager structures.
    411  * They are needed quite often because many of the pointers in the pmap
    412  * system reference MMU tables and not the structures that control them.
    413  * There needs to be a way to find one when given the other and these
    414  * macros do so by taking advantage of the memory layout described above.
    415  * Here's a quick step through the first macro, mmuA2tmgr():
    416  *
    417  * 1) find the offset of the given MMU A table from the base of its table
    418  *    pool (table - mmuAbase).
    419  * 2) convert this offset into a table index by dividing it by the
    420  *    size of one MMU 'A' table. (sizeof(mmu_long_dte_t) * MMU_A_TBL_SIZE)
    421  * 3) use this index to select the corresponding 'A' table manager
    422  *    structure from the 'A' table manager pool (Atmgrbase[index]).
    423  */
    424 /*  This function is not currently used. */
    425 #if	0
    426 static INLINE a_tmgr_t *
    427 mmuA2tmgr(mmuAtbl)
    428 	mmu_long_dte_t *mmuAtbl;
    429 {
    430 	register int idx;
    431 
    432 	/* Which table is this in? */
    433 	idx = (mmuAtbl - mmuAbase) / MMU_A_TBL_SIZE;
    434 #ifdef	PMAP_DEBUG
    435 	if ((idx < 0) || (idx >= NUM_A_TABLES))
    436 		panic("mmuA2tmgr");
    437 #endif
    438 	return (&Atmgrbase[idx]);
    439 }
    440 #endif	/* 0 */
    441 
    442 static INLINE b_tmgr_t *
    443 mmuB2tmgr(mmuBtbl)
    444 	mmu_short_dte_t *mmuBtbl;
    445 {
    446 	register int idx;
    447 
    448 	/* Which table is this in? */
    449 	idx = (mmuBtbl - mmuBbase) / MMU_B_TBL_SIZE;
    450 #ifdef	PMAP_DEBUG
    451 	if ((idx < 0) || (idx >= NUM_B_TABLES))
    452 		panic("mmuB2tmgr");
    453 #endif
    454 	return (&Btmgrbase[idx]);
    455 }
    456 
    457 /* mmuC2tmgr			INTERNAL
    458  **
    459  * Given a pte known to belong to a C table, return the address of
    460  * that table's management structure.
    461  */
    462 static INLINE c_tmgr_t *
    463 mmuC2tmgr(mmuCtbl)
    464 	mmu_short_pte_t *mmuCtbl;
    465 {
    466 	register int idx;
    467 
    468 	/* Which table is this in? */
    469 	idx = (mmuCtbl - mmuCbase) / MMU_C_TBL_SIZE;
    470 #ifdef	PMAP_DEBUG
    471 	if ((idx < 0) || (idx >= NUM_C_TABLES))
    472 		panic("mmuC2tmgr");
    473 #endif
    474 	return (&Ctmgrbase[idx]);
    475 }
    476 
    477 /* This is now a function call below.
    478  * #define pa2pv(pa) \
    479  *	(&pvbase[(unsigned long)\
    480  *		m68k_btop(pa)\
    481  *	])
    482  */
    483 
    484 /* pa2pv			INTERNAL
    485  **
    486  * Return the pv_list_head element which manages the given physical
    487  * address.
    488  */
    489 static INLINE pv_t *
    490 pa2pv(pa)
    491 	vm_offset_t pa;
    492 {
    493 	register struct pmap_physmem_struct *bank;
    494 	register int idx;
    495 
    496 	bank = &avail_mem[0];
    497 	while (pa >= bank->pmem_end)
    498 		bank = bank->pmem_next;
    499 
    500 	pa -= bank->pmem_start;
    501 	idx = bank->pmem_pvbase + m68k_btop(pa);
    502 #ifdef	PMAP_DEBUG
    503 	if ((idx < 0) || (idx >= physmem))
    504 		panic("pa2pv");
    505 #endif
    506 	return &pvbase[idx];
    507 }
    508 
    509 /* pteidx			INTERNAL
    510  **
    511  * Return the index of the given PTE within the entire fixed table of
    512  * PTEs.
    513  */
    514 static INLINE int
    515 pteidx(pte)
    516 	mmu_short_pte_t *pte;
    517 {
    518 	return (pte - kernCbase);
    519 }
    520 
    521 /*
    522  * This just offers a place to put some debugging checks,
    523  * and reduces the number of places "curproc" appears...
    524  */
    525 static INLINE pmap_t
    526 current_pmap()
    527 {
    528 	struct proc *p;
    529 	struct vmspace *vm;
    530 	vm_map_t	map;
    531 	pmap_t	pmap;
    532 
    533 	p = curproc;	/* XXX */
    534 	if (p == NULL)
    535 		pmap = &kernel_pmap;
    536 	else {
    537 		vm = p->p_vmspace;
    538 		map = &vm->vm_map;
    539 		pmap = vm_map_pmap(map);
    540 	}
    541 
    542 	return (pmap);
    543 }
    544 
    545 
    546 /*************************** FUNCTION DEFINITIONS ************************
    547  * These appear here merely for the compiler to enforce type checking on *
    548  * all function calls.                                                   *
    549  *************************************************************************/
    550 
    551 /** External functions
    552  ** - functions used within this module but written elsewhere.
    553  **   both of these functions are in locore.s
    554  ** XXX - These functions were later replaced with their more cryptic
    555  **       hp300 counterparts.  They may be removed now.
    556  **/
    557 #if	0	/* deprecated mmu */
    558 void   mmu_seturp __P((vm_offset_t));
    559 void   mmu_flush __P((int, vm_offset_t));
    560 void   mmu_flusha __P((void));
    561 #endif	/* 0 */
    562 
    563 /** Internal functions
    564  ** - all functions used only within this module are defined in
    565  **   pmap_pvt.h
    566  **/
    567 
    568 /** Interface functions
    569  ** - functions required by the Mach VM Pmap interface, with MACHINE_CONTIG
    570  **   defined.
    571  **/
    572 #ifdef INCLUDED_IN_PMAP_H
    573 void   pmap_bootstrap __P((void));
    574 void  *pmap_bootstrap_alloc __P((int));
    575 void   pmap_enter __P((pmap_t, vm_offset_t, vm_offset_t, vm_prot_t, boolean_t));
    576 pmap_t pmap_create __P((vm_size_t));
    577 void   pmap_destroy __P((pmap_t));
    578 void   pmap_reference __P((pmap_t));
    579 boolean_t   pmap_is_referenced __P((vm_offset_t));
    580 boolean_t   pmap_is_modified __P((vm_offset_t));
    581 void   pmap_clear_modify __P((vm_offset_t));
    582 vm_offset_t pmap_extract __P((pmap_t, vm_offset_t));
    583 int    pmap_page_index __P((vm_offset_t));
    584 u_int  pmap_free_pages __P((void));
    585 #endif /* INCLUDED_IN_PMAP_H */
    586 
    587 /********************************** CODE ********************************
    588  * Functions that are called from other parts of the kernel are labeled *
    589  * as 'INTERFACE' functions.  Functions that are only called from       *
    590  * within the pmap module are labeled as 'INTERNAL' functions.          *
    591  * Functions that are internal, but are not (currently) used at all are *
    592  * labeled 'INTERNAL_X'.                                                *
    593  ************************************************************************/
    594 
    595 /* pmap_bootstrap			INTERNAL
    596  **
    597  * Initializes the pmap system.  Called at boot time from
    598  * locore2.c:_vm_init()
    599  *
    600  * Reminder: having a pmap_bootstrap_alloc() and also having the VM
    601  *           system implement pmap_steal_memory() is redundant.
    602  *           Don't release this code without removing one or the other!
    603  */
    604 void
    605 pmap_bootstrap(nextva)
    606 	vm_offset_t nextva;
    607 {
    608 	struct physmemory *membank;
    609 	struct pmap_physmem_struct *pmap_membank;
    610 	vm_offset_t va, pa, eva;
    611 	int b, c, i, j;	/* running table counts */
    612 	int size;
    613 
    614 	/*
    615 	 * This function is called by __bootstrap after it has
    616 	 * determined the type of machine and made the appropriate
    617 	 * patches to the ROM vectors (XXX- I don't quite know what I meant
    618 	 * by that.)  It allocates and sets up enough of the pmap system
    619 	 * to manage the kernel's address space.
    620 	 */
    621 
    622 	/*
    623 	 * Determine the range of kernel virtual and physical
    624 	 * space available. Note that we ABSOLUTELY DEPEND on
    625 	 * the fact that the first bank of memory (4MB) is
    626 	 * mapped linearly to KERNBASE (which we guaranteed in
    627 	 * the first instructions of locore.s).
    628 	 * That is plenty for our bootstrap work.
    629 	 */
    630 	virtual_avail = m68k_round_page(nextva);
    631 	virtual_contig_end = KERNBASE + 0x400000; /* +4MB */
    632 	virtual_end = VM_MAX_KERNEL_ADDRESS;
    633 	/* Don't need avail_start til later. */
    634 
    635 	/* We may now call pmap_bootstrap_alloc(). */
    636 	bootstrap_alloc_enabled = TRUE;
    637 
    638 	/*
    639 	 * This is a somewhat unwrapped loop to deal with
    640 	 * copying the PROM's 'phsymem' banks into the pmap's
    641 	 * banks.  The following is always assumed:
    642 	 * 1. There is always at least one bank of memory.
    643 	 * 2. There is always a last bank of memory, and its
    644 	 *    pmem_next member must be set to NULL.
    645 	 * XXX - Use: do { ... } while (membank->next) instead?
    646 	 * XXX - Why copy this stuff at all? -gwr
    647 	 *     - It is needed in pa2pv().
    648 	 */
    649 	membank = romVectorPtr->v_physmemory;
    650 	pmap_membank = avail_mem;
    651 	total_phys_mem = 0;
    652 
    653 	while (membank->next) {
    654 		pmap_membank->pmem_start = membank->address;
    655 		pmap_membank->pmem_end = membank->address + membank->size;
    656 		total_phys_mem += membank->size;
    657 		/* This silly syntax arises because pmap_membank
    658 		 * is really a pre-allocated array, but it is put into
    659 		 * use as a linked list.
    660 		 */
    661 		pmap_membank->pmem_next = pmap_membank + 1;
    662 		pmap_membank = pmap_membank->pmem_next;
    663 		membank = membank->next;
    664 	}
    665 
    666 	/*
    667 	 * XXX The last bank of memory should be reduced to exclude the
    668 	 * physical pages needed by the PROM monitor from being used
    669 	 * in the VM system.  XXX - See below - Fix!
    670 	 */
    671 	pmap_membank->pmem_start = membank->address;
    672 	pmap_membank->pmem_end = membank->address + membank->size;
    673 	pmap_membank->pmem_next = NULL;
    674 
    675 #if 0	/* XXX - Need to integrate this! */
    676 	/*
    677 	 * The last few pages of physical memory are "owned" by
    678 	 * the PROM.  The total amount of memory we are allowed
    679 	 * to use is given by the romvec pointer. -gwr
    680 	 *
    681 	 * We should dedicate different variables for 'useable'
    682 	 * and 'physically available'.  Most users are used to the
    683 	 * kernel reporting the amount of memory 'physically available'
    684 	 * as opposed to 'useable by the kernel' at boot time. -j
    685 	 */
    686 	total_phys_mem = *romVectorPtr->memoryAvail;
    687 #endif	/* XXX */
    688 
    689 	total_phys_mem += membank->size;	/* XXX see above */
    690 	physmem = btoc(total_phys_mem);
    691 
    692 	/*
    693 	 * Avail_end is set to the first byte of physical memory
    694 	 * after the end of the last bank.  We use this only to
    695 	 * determine if a physical address is "managed" memory.
    696 	 *
    697 	 * XXX - The setting of avail_end is a temporary ROM saving hack.
    698 	 */
    699 	avail_end = pmap_membank->pmem_end -
    700 		(total_phys_mem - *romVectorPtr->memoryAvail);
    701 	avail_end = m68k_trunc_page(avail_end);
    702 
    703 	/*
    704 	 * First allocate enough kernel MMU tables to map all
    705 	 * of kernel virtual space from KERNBASE to 0xFFFFFFFF.
    706 	 * Note: All must be aligned on 256 byte boundaries.
    707 	 * Start with the level-A table (one of those).
    708 	 */
    709 	size = sizeof(mmu_long_dte_t)  * MMU_A_TBL_SIZE;
    710 	kernAbase = pmap_bootstrap_alloc(size);
    711 	bzero(kernAbase, size);
    712 
    713 	/* Now the level-B kernel tables... */
    714 	size = sizeof(mmu_short_dte_t) * MMU_B_TBL_SIZE * KERN_B_TABLES;
    715 	kernBbase = pmap_bootstrap_alloc(size);
    716 	bzero(kernBbase, size);
    717 
    718 	/* Now the level-C kernel tables... */
    719 	size = sizeof(mmu_short_pte_t) * MMU_C_TBL_SIZE * KERN_C_TABLES;
    720 	kernCbase = pmap_bootstrap_alloc(size);
    721 	bzero(kernCbase, size);
    722 	/*
    723 	 * Note: In order for the PV system to work correctly, the kernel
    724 	 * and user-level C tables must be allocated contiguously.
    725 	 * Nothing should be allocated between here and the allocation of
    726 	 * mmuCbase below.  XXX: Should do this as one allocation, and
    727 	 * then compute a pointer for mmuCbase instead of this...
    728 	 *
    729 	 * Allocate user MMU tables.
    730 	 * These must be contiguous with the preceeding.
    731 	 */
    732 
    733 #ifndef	FIXED_NTABLES
    734 	/*
    735 	 * The number of user-level C tables that should be allocated is
    736 	 * related to the size of physical memory.  In general, there should
    737 	 * be enough tables to map four times the amount of available RAM.
    738 	 * The extra amount is needed because some table space is wasted by
    739 	 * fragmentation.
    740 	 */
    741 	NUM_C_TABLES = (total_phys_mem * 4) / (MMU_C_TBL_SIZE * MMU_PAGE_SIZE);
    742 	NUM_B_TABLES = NUM_C_TABLES / 2;
    743 	NUM_A_TABLES = NUM_B_TABLES / 2;
    744 #endif	/* !FIXED_NTABLES */
    745 
    746 	size = sizeof(mmu_short_pte_t) * MMU_C_TBL_SIZE	* NUM_C_TABLES;
    747 	mmuCbase = pmap_bootstrap_alloc(size);
    748 
    749 	size = sizeof(mmu_short_dte_t) * MMU_B_TBL_SIZE	* NUM_B_TABLES;
    750 	mmuBbase = pmap_bootstrap_alloc(size);
    751 
    752 	size = sizeof(mmu_long_dte_t)  * MMU_A_TBL_SIZE * NUM_A_TABLES;
    753 	mmuAbase = pmap_bootstrap_alloc(size);
    754 
    755 	/*
    756 	 * Fill in the never-changing part of the kernel tables.
    757 	 * For simplicity, the kernel's mappings will be editable as a
    758 	 * flat array of page table entries at kernCbase.  The
    759 	 * higher level 'A' and 'B' tables must be initialized to point
    760 	 * to this lower one.
    761 	 */
    762 	b = c = 0;
    763 
    764 	/*
    765 	 * Invalidate all mappings below KERNBASE in the A table.
    766 	 * This area has already been zeroed out, but it is good
    767 	 * practice to explicitly show that we are interpreting
    768 	 * it as a list of A table descriptors.
    769 	 */
    770 	for (i = 0; i < MMU_TIA(KERNBASE); i++) {
    771 		kernAbase[i].addr.raw = 0;
    772 	}
    773 
    774 	/*
    775 	 * Set up the kernel A and B tables so that they will reference the
    776 	 * correct spots in the contiguous table of PTEs allocated for the
    777 	 * kernel's virtual memory space.
    778 	 */
    779 	for (i = MMU_TIA(KERNBASE); i < MMU_A_TBL_SIZE; i++) {
    780 		kernAbase[i].attr.raw =
    781 			MMU_LONG_DTE_LU | MMU_LONG_DTE_SUPV | MMU_DT_SHORT;
    782 		kernAbase[i].addr.raw = mmu_vtop(&kernBbase[b]);
    783 
    784 		for (j=0; j < MMU_B_TBL_SIZE; j++) {
    785 			kernBbase[b + j].attr.raw = mmu_vtop(&kernCbase[c])
    786 				| MMU_DT_SHORT;
    787 			c += MMU_C_TBL_SIZE;
    788 		}
    789 		b += MMU_B_TBL_SIZE;
    790 	}
    791 
    792 	/* XXX - Doing kernel_pmap a little further down. */
    793 
    794 	pmap_alloc_usermmu();	/* Allocate user MMU tables.        */
    795 	pmap_alloc_usertmgr();	/* Allocate user MMU table managers.*/
    796 	pmap_alloc_pv();	/* Allocate physical->virtual map.  */
    797 
    798 	/*
    799 	 * We are now done with pmap_bootstrap_alloc().  Round up
    800 	 * `virtual_avail' to the nearest page, and set the flag
    801 	 * to prevent use of pmap_bootstrap_alloc() hereafter.
    802 	 */
    803 	pmap_bootstrap_aalign(NBPG);
    804 	bootstrap_alloc_enabled = FALSE;
    805 
    806 	/*
    807 	 * Now that we are done with pmap_bootstrap_alloc(), we
    808 	 * must save the virtual and physical addresses of the
    809 	 * end of the linearly mapped range, which are stored in
    810 	 * virtual_contig_end and avail_start, respectively.
    811 	 * These variables will never change after this point.
    812 	 */
    813 	virtual_contig_end = virtual_avail;
    814 	avail_start = virtual_avail - KERNBASE;
    815 
    816 	/*
    817 	 * `avail_next' is a running pointer used by pmap_next_page() to
    818 	 * keep track of the next available physical page to be handed
    819 	 * to the VM system during its initialization, in which it
    820 	 * asks for physical pages, one at a time.
    821 	 */
    822 	avail_next = avail_start;
    823 
    824 	/*
    825 	 * Now allocate some virtual addresses, but not the physical pages
    826 	 * behind them.  Note that virtual_avail is already page-aligned.
    827 	 *
    828 	 * tmp_vpages[] is an array of two virtual pages used for temporary
    829 	 * kernel mappings in the pmap module to facilitate various physical
    830 	 * address-oritented operations.
    831 	 */
    832 	tmp_vpages[0] = virtual_avail;
    833 	virtual_avail += NBPG;
    834 	tmp_vpages[1] = virtual_avail;
    835 	virtual_avail += NBPG;
    836 
    837 	/** Initialize the PV system **/
    838 	pmap_init_pv();
    839 
    840 	/*
    841 	 * Fill in the kernel_pmap structure and kernel_crp.
    842 	 */
    843 	kernAphys = mmu_vtop(kernAbase);
    844 	kernel_pmap.pm_a_tmgr = NULL;
    845 	kernel_pmap.pm_a_phys = kernAphys;
    846 	kernel_pmap.pm_refcount = 1; /* always in use */
    847 
    848 	kernel_crp.rp_attr = MMU_LONG_DTE_LU | MMU_DT_LONG;
    849 	kernel_crp.rp_addr = kernAphys;
    850 
    851 	/*
    852 	 * Now pmap_enter_kernel() may be used safely and will be
    853 	 * the main interface used hereafter to modify the kernel's
    854 	 * virtual address space.  Note that since we are still running
    855 	 * under the PROM's address table, none of these table modifications
    856 	 * actually take effect until pmap_takeover_mmu() is called.
    857 	 *
    858 	 * Note: Our tables do NOT have the PROM linear mappings!
    859 	 * Only the mappings created here exist in our tables, so
    860 	 * remember to map anything we expect to use.
    861 	 */
    862 	va = (vm_offset_t) KERNBASE;
    863 	pa = 0;
    864 
    865 	/*
    866 	 * The first page of the kernel virtual address space is the msgbuf
    867 	 * page.  The page attributes (data, non-cached) are set here, while
    868 	 * the address is assigned to this global pointer in cpu_startup().
    869 	 * It is non-cached, mostly due to paranoia.
    870 	 */
    871 	pmap_enter_kernel(va, pa|PMAP_NC, VM_PROT_ALL);
    872 	va += NBPG; pa += NBPG;
    873 
    874 	/* Next page is used as the temporary stack. */
    875 	pmap_enter_kernel(va, pa, VM_PROT_ALL);
    876 	va += NBPG; pa += NBPG;
    877 
    878 	/*
    879 	 * Map all of the kernel's text segment as read-only and cacheable.
    880 	 * (Cacheable is implied by default).  Unfortunately, the last bytes
    881 	 * of kernel text and the first bytes of kernel data will often be
    882 	 * sharing the same page.  Therefore, the last page of kernel text
    883 	 * has to be mapped as read/write, to accomodate the data.
    884 	 */
    885 	eva = m68k_trunc_page((vm_offset_t)etext);
    886 	for (; va < eva; va += NBPG, pa += NBPG)
    887 		pmap_enter_kernel(va, pa, VM_PROT_READ|VM_PROT_EXECUTE);
    888 
    889 	/*
    890 	 * Map all of the kernel's data as read/write and cacheable.
    891 	 * This includes: data, BSS, symbols, and everything in the
    892 	 * contiguous memory used by pmap_bootstrap_alloc()
    893 	 */
    894 	for (; pa < avail_start; va += NBPG, pa += NBPG)
    895 		pmap_enter_kernel(va, pa, VM_PROT_READ|VM_PROT_WRITE);
    896 
    897 	/*
    898 	 * At this point we are almost ready to take over the MMU.  But first
    899 	 * we must save the PROM's address space in our map, as we call its
    900 	 * routines and make references to its data later in the kernel.
    901 	 */
    902 	pmap_bootstrap_copyprom();
    903 	pmap_takeover_mmu();
    904 	pmap_bootstrap_setprom();
    905 
    906 	/* Notify the VM system of our page size. */
    907 	PAGE_SIZE = NBPG;
    908 	vm_set_page_size();
    909 }
    910 
    911 
    912 /* pmap_alloc_usermmu			INTERNAL
    913  **
    914  * Called from pmap_bootstrap() to allocate MMU tables that will
    915  * eventually be used for user mappings.
    916  */
    917 void
    918 pmap_alloc_usermmu()
    919 {
    920 	/* XXX: Moved into caller. */
    921 }
    922 
    923 /* pmap_alloc_pv			INTERNAL
    924  **
    925  * Called from pmap_bootstrap() to allocate the physical
    926  * to virtual mapping list.  Each physical page of memory
    927  * in the system has a corresponding element in this list.
    928  */
    929 void
    930 pmap_alloc_pv()
    931 {
    932 	int	i;
    933 	unsigned int	total_mem;
    934 
    935 	/*
    936 	 * Allocate a pv_head structure for every page of physical
    937 	 * memory that will be managed by the system.  Since memory on
    938 	 * the 3/80 is non-contiguous, we cannot arrive at a total page
    939 	 * count by subtraction of the lowest available address from the
    940 	 * highest, but rather we have to step through each memory
    941 	 * bank and add the number of pages in each to the total.
    942 	 *
    943 	 * At this time we also initialize the offset of each bank's
    944 	 * starting pv_head within the pv_head list so that the physical
    945 	 * memory state routines (pmap_is_referenced(),
    946 	 * pmap_is_modified(), et al.) can quickly find coresponding
    947 	 * pv_heads in spite of the non-contiguity.
    948 	 */
    949 	total_mem = 0;
    950 	for (i = 0; i < SUN3X_NPHYS_RAM_SEGS; i++) {
    951 		avail_mem[i].pmem_pvbase = m68k_btop(total_mem);
    952 		total_mem += avail_mem[i].pmem_end -
    953 			avail_mem[i].pmem_start;
    954 		if (avail_mem[i].pmem_next == NULL)
    955 			break;
    956 	}
    957 #ifdef	PMAP_DEBUG
    958 	if (total_mem != total_phys_mem)
    959 		panic("pmap_alloc_pv did not arrive at correct page count");
    960 #endif
    961 
    962 	pvbase = (pv_t *) pmap_bootstrap_alloc(sizeof(pv_t) *
    963 		m68k_btop(total_phys_mem));
    964 }
    965 
    966 /* pmap_alloc_usertmgr			INTERNAL
    967  **
    968  * Called from pmap_bootstrap() to allocate the structures which
    969  * facilitate management of user MMU tables.  Each user MMU table
    970  * in the system has one such structure associated with it.
    971  */
    972 void
    973 pmap_alloc_usertmgr()
    974 {
    975 	/* Allocate user MMU table managers */
    976 	/* It would be a lot simpler to just make these BSS, but */
    977 	/* we may want to change their size at boot time... -j */
    978 	Atmgrbase = (a_tmgr_t *) pmap_bootstrap_alloc(sizeof(a_tmgr_t)
    979 		* NUM_A_TABLES);
    980 	Btmgrbase = (b_tmgr_t *) pmap_bootstrap_alloc(sizeof(b_tmgr_t)
    981 		* NUM_B_TABLES);
    982 	Ctmgrbase = (c_tmgr_t *) pmap_bootstrap_alloc(sizeof(c_tmgr_t)
    983 		* NUM_C_TABLES);
    984 
    985 	/*
    986 	 * Allocate PV list elements for the physical to virtual
    987 	 * mapping system.
    988 	 */
    989 	pvebase = (pv_elem_t *) pmap_bootstrap_alloc(
    990 		sizeof(pv_elem_t) * (NUM_USER_PTES + NUM_KERN_PTES));
    991 }
    992 
    993 /* pmap_bootstrap_copyprom()			INTERNAL
    994  **
    995  * Copy the PROM mappings into our own tables.  Note, we
    996  * can use physical addresses until __bootstrap returns.
    997  */
    998 void
    999 pmap_bootstrap_copyprom()
   1000 {
   1001 	struct sunromvec *romp;
   1002 	int *mon_ctbl;
   1003 	mmu_short_pte_t *kpte;
   1004 	int i, len;
   1005 
   1006 	romp = romVectorPtr;
   1007 
   1008 	/*
   1009 	 * Copy the mappings in SUN3X_MON_KDB_BASE...SUN3X_MONEND
   1010 	 * Note: mon_ctbl[0] maps SUN3X_MON_KDB_BASE
   1011 	 */
   1012 	mon_ctbl = *romp->monptaddr;
   1013 	i = m68k_btop(SUN3X_MON_KDB_BASE - KERNBASE);
   1014 	kpte = &kernCbase[i];
   1015 	len = m68k_btop(SUN3X_MONEND - SUN3X_MON_KDB_BASE);
   1016 
   1017 	for (i = 0; i < len; i++) {
   1018 		kpte[i].attr.raw = mon_ctbl[i];
   1019 	}
   1020 
   1021 	/*
   1022 	 * Copy the mappings at MON_DVMA_BASE (to the end).
   1023 	 * Note, in here, mon_ctbl[0] maps MON_DVMA_BASE.
   1024 	 * Actually, we only want the last page, which the
   1025 	 * PROM has set up for use by the "ie" driver.
   1026 	 * (The i82686 needs its SCP there.)
   1027 	 * If we copy all the mappings, pmap_enter_kernel
   1028 	 * may complain about finding valid PTEs that are
   1029 	 * not recorded in our PV lists...
   1030 	 */
   1031 	mon_ctbl = *romp->shadowpteaddr;
   1032 	i = m68k_btop(SUN3X_MON_DVMA_BASE - KERNBASE);
   1033 	kpte = &kernCbase[i];
   1034 	len = m68k_btop(SUN3X_MON_DVMA_SIZE);
   1035 	for (i = (len-1); i < len; i++) {
   1036 		kpte[i].attr.raw = mon_ctbl[i];
   1037 	}
   1038 }
   1039 
   1040 /* pmap_takeover_mmu			INTERNAL
   1041  **
   1042  * Called from pmap_bootstrap() after it has copied enough of the
   1043  * PROM mappings into the kernel map so that we can use our own
   1044  * MMU table.
   1045  */
   1046 void
   1047 pmap_takeover_mmu()
   1048 {
   1049 
   1050 	loadcrp(&kernel_crp);
   1051 }
   1052 
   1053 /* pmap_bootstrap_setprom()			INTERNAL
   1054  **
   1055  * Set the PROM mappings so it can see kernel space.
   1056  * Note that physical addresses are used here, which
   1057  * we can get away with because this runs with the
   1058  * low 1GB set for transparent translation.
   1059  */
   1060 void
   1061 pmap_bootstrap_setprom()
   1062 {
   1063 	mmu_long_dte_t *mon_dte;
   1064 	extern struct mmu_rootptr mon_crp;
   1065 	int i;
   1066 
   1067 	mon_dte = (mmu_long_dte_t *) mon_crp.rp_addr;
   1068 	for (i = MMU_TIA(KERNBASE); i < MMU_TIA(KERN_END); i++) {
   1069 		mon_dte[i].attr.raw = kernAbase[i].attr.raw;
   1070 		mon_dte[i].addr.raw = kernAbase[i].addr.raw;
   1071 	}
   1072 }
   1073 
   1074 
   1075 /* pmap_init			INTERFACE
   1076  **
   1077  * Called at the end of vm_init() to set up the pmap system to go
   1078  * into full time operation.  All initialization of kernel_pmap
   1079  * should be already done by now, so this should just do things
   1080  * needed for user-level pmaps to work.
   1081  */
   1082 void
   1083 pmap_init()
   1084 {
   1085 	/** Initialize the manager pools **/
   1086 	TAILQ_INIT(&a_pool);
   1087 	TAILQ_INIT(&b_pool);
   1088 	TAILQ_INIT(&c_pool);
   1089 
   1090 	/**************************************************************
   1091 	 * Initialize all tmgr structures and MMU tables they manage. *
   1092 	 **************************************************************/
   1093 	/** Initialize A tables **/
   1094 	pmap_init_a_tables();
   1095 	/** Initialize B tables **/
   1096 	pmap_init_b_tables();
   1097 	/** Initialize C tables **/
   1098 	pmap_init_c_tables();
   1099 }
   1100 
   1101 /* pmap_init_a_tables()			INTERNAL
   1102  **
   1103  * Initializes all A managers, their MMU A tables, and inserts
   1104  * them into the A manager pool for use by the system.
   1105  */
   1106 void
   1107 pmap_init_a_tables()
   1108 {
   1109 	int i;
   1110 	a_tmgr_t *a_tbl;
   1111 
   1112 	for (i=0; i < NUM_A_TABLES; i++) {
   1113 		/* Select the next available A manager from the pool */
   1114 		a_tbl = &Atmgrbase[i];
   1115 
   1116 		/*
   1117 		 * Clear its parent entry.  Set its wired and valid
   1118 		 * entry count to zero.
   1119 		 */
   1120 		a_tbl->at_parent = NULL;
   1121 		a_tbl->at_wcnt = a_tbl->at_ecnt = 0;
   1122 
   1123 		/* Assign it the next available MMU A table from the pool */
   1124 		a_tbl->at_dtbl = &mmuAbase[i * MMU_A_TBL_SIZE];
   1125 
   1126 		/*
   1127 		 * Initialize the MMU A table with the table in the `proc0',
   1128 		 * or kernel, mapping.  This ensures that every process has
   1129 		 * the kernel mapped in the top part of its address space.
   1130 		 */
   1131 		bcopy(kernAbase, a_tbl->at_dtbl, MMU_A_TBL_SIZE *
   1132 			sizeof(mmu_long_dte_t));
   1133 
   1134 		/*
   1135 		 * Finally, insert the manager into the A pool,
   1136 		 * making it ready to be used by the system.
   1137 		 */
   1138 		TAILQ_INSERT_TAIL(&a_pool, a_tbl, at_link);
   1139     }
   1140 }
   1141 
   1142 /* pmap_init_b_tables()			INTERNAL
   1143  **
   1144  * Initializes all B table managers, their MMU B tables, and
   1145  * inserts them into the B manager pool for use by the system.
   1146  */
   1147 void
   1148 pmap_init_b_tables()
   1149 {
   1150 	int i,j;
   1151 	b_tmgr_t *b_tbl;
   1152 
   1153 	for (i=0; i < NUM_B_TABLES; i++) {
   1154 		/* Select the next available B manager from the pool */
   1155 		b_tbl = &Btmgrbase[i];
   1156 
   1157 		b_tbl->bt_parent = NULL;	/* clear its parent,  */
   1158 		b_tbl->bt_pidx = 0;		/* parent index,      */
   1159 		b_tbl->bt_wcnt = 0;		/* wired entry count, */
   1160 		b_tbl->bt_ecnt = 0;		/* valid entry count. */
   1161 
   1162 		/* Assign it the next available MMU B table from the pool */
   1163 		b_tbl->bt_dtbl = &mmuBbase[i * MMU_B_TBL_SIZE];
   1164 
   1165 		/* Invalidate every descriptor in the table */
   1166 		for (j=0; j < MMU_B_TBL_SIZE; j++)
   1167 			b_tbl->bt_dtbl[j].attr.raw = MMU_DT_INVALID;
   1168 
   1169 		/* Insert the manager into the B pool */
   1170 		TAILQ_INSERT_TAIL(&b_pool, b_tbl, bt_link);
   1171 	}
   1172 }
   1173 
   1174 /* pmap_init_c_tables()			INTERNAL
   1175  **
   1176  * Initializes all C table managers, their MMU C tables, and
   1177  * inserts them into the C manager pool for use by the system.
   1178  */
   1179 void
   1180 pmap_init_c_tables()
   1181 {
   1182 	int i,j;
   1183 	c_tmgr_t *c_tbl;
   1184 
   1185 	for (i=0; i < NUM_C_TABLES; i++) {
   1186 		/* Select the next available C manager from the pool */
   1187 		c_tbl = &Ctmgrbase[i];
   1188 
   1189 		c_tbl->ct_parent = NULL;	/* clear its parent,  */
   1190 		c_tbl->ct_pidx = 0;		/* parent index,      */
   1191 		c_tbl->ct_wcnt = 0;		/* wired entry count, */
   1192 		c_tbl->ct_ecnt = 0;		/* valid entry count, */
   1193 		c_tbl->ct_pmap = NULL;		/* parent pmap,       */
   1194 		c_tbl->ct_va = 0;		/* base of managed range */
   1195 
   1196 		/* Assign it the next available MMU C table from the pool */
   1197 		c_tbl->ct_dtbl = &mmuCbase[i * MMU_C_TBL_SIZE];
   1198 
   1199 		for (j=0; j < MMU_C_TBL_SIZE; j++)
   1200 			c_tbl->ct_dtbl[j].attr.raw = MMU_DT_INVALID;
   1201 
   1202 		TAILQ_INSERT_TAIL(&c_pool, c_tbl, ct_link);
   1203 	}
   1204 }
   1205 
   1206 /* pmap_init_pv()			INTERNAL
   1207  **
   1208  * Initializes the Physical to Virtual mapping system.
   1209  */
   1210 void
   1211 pmap_init_pv()
   1212 {
   1213 	int	i;
   1214 
   1215 	/* Initialize every PV head. */
   1216 	for (i = 0; i < m68k_btop(total_phys_mem); i++) {
   1217 		pvbase[i].pv_idx = PVE_EOL;	/* Indicate no mappings */
   1218 		pvbase[i].pv_flags = 0;		/* Zero out page flags  */
   1219 	}
   1220 
   1221 	pv_initialized = TRUE;
   1222 }
   1223 
   1224 /* get_a_table			INTERNAL
   1225  **
   1226  * Retrieve and return a level A table for use in a user map.
   1227  */
   1228 a_tmgr_t *
   1229 get_a_table()
   1230 {
   1231 	a_tmgr_t *tbl;
   1232 	pmap_t pmap;
   1233 
   1234 	/* Get the top A table in the pool */
   1235 	tbl = a_pool.tqh_first;
   1236 	if (tbl == NULL) {
   1237 		/*
   1238 		 * XXX - Instead of panicing here and in other get_x_table
   1239 		 * functions, we do have the option of sleeping on the head of
   1240 		 * the table pool.  Any function which updates the table pool
   1241 		 * would then issue a wakeup() on the head, thus waking up any
   1242 		 * processes waiting for a table.
   1243 		 *
   1244 		 * Actually, the place to sleep would be when some process
   1245 		 * asks for a "wired" mapping that would run us short of
   1246 		 * mapping resources.  This design DEPENDS on always having
   1247 		 * some mapping resources in the pool for stealing, so we
   1248 		 * must make sure we NEVER let the pool become empty. -gwr
   1249 		 */
   1250 		panic("get_a_table: out of A tables.");
   1251 	}
   1252 
   1253 	TAILQ_REMOVE(&a_pool, tbl, at_link);
   1254 	/*
   1255 	 * If the table has a non-null parent pointer then it is in use.
   1256 	 * Forcibly abduct it from its parent and clear its entries.
   1257 	 * No re-entrancy worries here.  This table would not be in the
   1258 	 * table pool unless it was available for use.
   1259 	 *
   1260 	 * Note that the second argument to free_a_table() is FALSE.  This
   1261 	 * indicates that the table should not be relinked into the A table
   1262 	 * pool.  That is a job for the function that called us.
   1263 	 */
   1264 	if (tbl->at_parent) {
   1265 		pmap = tbl->at_parent;
   1266 		free_a_table(tbl, FALSE);
   1267 		pmap->pm_a_tmgr = NULL;
   1268 		pmap->pm_a_phys = kernAphys;
   1269 	}
   1270 #ifdef  NON_REENTRANT
   1271 	/*
   1272 	 * If the table isn't to be wired down, re-insert it at the
   1273 	 * end of the pool.
   1274 	 */
   1275 	if (!wired)
   1276 		/*
   1277 		 * Quandary - XXX
   1278 		 * Would it be better to let the calling function insert this
   1279 		 * table into the queue?  By inserting it here, we are allowing
   1280 		 * it to be stolen immediately.  The calling function is
   1281 		 * probably not expecting to use a table that it is not
   1282 		 * assured full control of.
   1283 		 * Answer - In the intrest of re-entrancy, it is best to let
   1284 		 * the calling function determine when a table is available
   1285 		 * for use.  Therefore this code block is not used.
   1286 		 */
   1287 		TAILQ_INSERT_TAIL(&a_pool, tbl, at_link);
   1288 #endif	/* NON_REENTRANT */
   1289 	return tbl;
   1290 }
   1291 
   1292 /* get_b_table			INTERNAL
   1293  **
   1294  * Return a level B table for use.
   1295  */
   1296 b_tmgr_t *
   1297 get_b_table()
   1298 {
   1299 	b_tmgr_t *tbl;
   1300 
   1301 	/* See 'get_a_table' for comments. */
   1302 	tbl = b_pool.tqh_first;
   1303 	if (tbl == NULL)
   1304 		panic("get_b_table: out of B tables.");
   1305 	TAILQ_REMOVE(&b_pool, tbl, bt_link);
   1306 	if (tbl->bt_parent) {
   1307 		tbl->bt_parent->at_dtbl[tbl->bt_pidx].attr.raw = MMU_DT_INVALID;
   1308 		tbl->bt_parent->at_ecnt--;
   1309 		free_b_table(tbl, FALSE);
   1310 	}
   1311 #ifdef	NON_REENTRANT
   1312 	if (!wired)
   1313 		/* XXX see quandary in get_b_table */
   1314 		/* XXX start lock */
   1315 		TAILQ_INSERT_TAIL(&b_pool, tbl, bt_link);
   1316 		/* XXX end lock */
   1317 #endif	/* NON_REENTRANT */
   1318 	return tbl;
   1319 }
   1320 
   1321 /* get_c_table			INTERNAL
   1322  **
   1323  * Return a level C table for use.
   1324  */
   1325 c_tmgr_t *
   1326 get_c_table()
   1327 {
   1328 	c_tmgr_t *tbl;
   1329 
   1330 	/* See 'get_a_table' for comments */
   1331 	tbl = c_pool.tqh_first;
   1332 	if (tbl == NULL)
   1333 		panic("get_c_table: out of C tables.");
   1334 	TAILQ_REMOVE(&c_pool, tbl, ct_link);
   1335 	if (tbl->ct_parent) {
   1336 		tbl->ct_parent->bt_dtbl[tbl->ct_pidx].attr.raw = MMU_DT_INVALID;
   1337 		tbl->ct_parent->bt_ecnt--;
   1338 		free_c_table(tbl, FALSE);
   1339 	}
   1340 #ifdef	NON_REENTRANT
   1341 	if (!wired)
   1342 		/* XXX See quandary in get_a_table */
   1343 		/* XXX start lock */
   1344 		TAILQ_INSERT_TAIL(&c_pool, tbl, c_link);
   1345 		/* XXX end lock */
   1346 #endif	/* NON_REENTRANT */
   1347 
   1348 	return tbl;
   1349 }
   1350 
   1351 /*
   1352  * The following 'free_table' and 'steal_table' functions are called to
   1353  * detach tables from their current obligations (parents and children) and
   1354  * prepare them for reuse in another mapping.
   1355  *
   1356  * Free_table is used when the calling function will handle the fate
   1357  * of the parent table, such as returning it to the free pool when it has
   1358  * no valid entries.  Functions that do not want to handle this should
   1359  * call steal_table, in which the parent table's descriptors and entry
   1360  * count are automatically modified when this table is removed.
   1361  */
   1362 
   1363 /* free_a_table			INTERNAL
   1364  **
   1365  * Unmaps the given A table and all child tables from their current
   1366  * mappings.  Returns the number of pages that were invalidated.
   1367  * If 'relink' is true, the function will return the table to the head
   1368  * of the available table pool.
   1369  *
   1370  * Cache note: The MC68851 will automatically flush all
   1371  * descriptors derived from a given A table from its
   1372  * Automatic Translation Cache (ATC) if we issue a
   1373  * 'PFLUSHR' instruction with the base address of the
   1374  * table.  This function should do, and does so.
   1375  * Note note: We are using an MC68030 - there is no
   1376  * PFLUSHR.
   1377  */
   1378 int
   1379 free_a_table(a_tbl, relink)
   1380 	a_tmgr_t *a_tbl;
   1381 	boolean_t relink;
   1382 {
   1383 	int i, removed_cnt;
   1384 	mmu_long_dte_t	*dte;
   1385 	mmu_short_dte_t *dtbl;
   1386 	b_tmgr_t	*tmgr;
   1387 
   1388 	/*
   1389 	 * Flush the ATC cache of all cached descriptors derived
   1390 	 * from this table.
   1391 	 * Sun3x does not use 68851's cached table feature
   1392 	 * flush_atc_crp(mmu_vtop(a_tbl->dte));
   1393 	 */
   1394 
   1395 	/*
   1396 	 * Remove any pending cache flushes that were designated
   1397 	 * for the pmap this A table belongs to.
   1398 	 * a_tbl->parent->atc_flushq[0] = 0;
   1399 	 * Not implemented in sun3x.
   1400 	 */
   1401 
   1402 	/*
   1403 	 * All A tables in the system should retain a map for the
   1404 	 * kernel. If the table contains any valid descriptors
   1405 	 * (other than those for the kernel area), invalidate them all,
   1406 	 * stopping short of the kernel's entries.
   1407 	 */
   1408 	removed_cnt = 0;
   1409 	if (a_tbl->at_ecnt) {
   1410 		dte = a_tbl->at_dtbl;
   1411 		for (i=0; i < MMU_TIA(KERNBASE); i++) {
   1412 			/*
   1413 			 * If a table entry points to a valid B table, free
   1414 			 * it and its children.
   1415 			 */
   1416 			if (MMU_VALID_DT(dte[i])) {
   1417 				/*
   1418 				 * The following block does several things,
   1419 				 * from innermost expression to the
   1420 				 * outermost:
   1421 				 * 1) It extracts the base (cc 1996)
   1422 				 *    address of the B table pointed
   1423 				 *    to in the A table entry dte[i].
   1424 				 * 2) It converts this base address into
   1425 				 *    the virtual address it can be
   1426 				 *    accessed with. (all MMU tables point
   1427 				 *    to physical addresses.)
   1428 				 * 3) It finds the corresponding manager
   1429 				 *    structure which manages this MMU table.
   1430 				 * 4) It frees the manager structure.
   1431 				 *    (This frees the MMU table and all
   1432 				 *    child tables. See 'free_b_table' for
   1433 				 *    details.)
   1434 				 */
   1435 				dtbl = mmu_ptov(dte[i].addr.raw);
   1436 				tmgr = mmuB2tmgr(dtbl);
   1437 				removed_cnt += free_b_table(tmgr, TRUE);
   1438 				dte[i].attr.raw = MMU_DT_INVALID;
   1439 			}
   1440 		}
   1441 		a_tbl->at_ecnt = 0;
   1442 	}
   1443 	if (relink) {
   1444 		a_tbl->at_parent = NULL;
   1445 		TAILQ_REMOVE(&a_pool, a_tbl, at_link);
   1446 		TAILQ_INSERT_HEAD(&a_pool, a_tbl, at_link);
   1447 	}
   1448 	return removed_cnt;
   1449 }
   1450 
   1451 /* free_b_table			INTERNAL
   1452  **
   1453  * Unmaps the given B table and all its children from their current
   1454  * mappings.  Returns the number of pages that were invalidated.
   1455  * (For comments, see 'free_a_table()').
   1456  */
   1457 int
   1458 free_b_table(b_tbl, relink)
   1459 	b_tmgr_t *b_tbl;
   1460 	boolean_t relink;
   1461 {
   1462 	int i, removed_cnt;
   1463 	mmu_short_dte_t *dte;
   1464 	mmu_short_pte_t	*dtbl;
   1465 	c_tmgr_t	*tmgr;
   1466 
   1467 	removed_cnt = 0;
   1468 	if (b_tbl->bt_ecnt) {
   1469 		dte = b_tbl->bt_dtbl;
   1470 		for (i=0; i < MMU_B_TBL_SIZE; i++) {
   1471 			if (MMU_VALID_DT(dte[i])) {
   1472 				dtbl = mmu_ptov(MMU_DTE_PA(dte[i]));
   1473 				tmgr = mmuC2tmgr(dtbl);
   1474 				removed_cnt += free_c_table(tmgr, TRUE);
   1475 				dte[i].attr.raw = MMU_DT_INVALID;
   1476 			}
   1477 		}
   1478 		b_tbl->bt_ecnt = 0;
   1479 	}
   1480 
   1481 	if (relink) {
   1482 		b_tbl->bt_parent = NULL;
   1483 		TAILQ_REMOVE(&b_pool, b_tbl, bt_link);
   1484 		TAILQ_INSERT_HEAD(&b_pool, b_tbl, bt_link);
   1485 	}
   1486 	return removed_cnt;
   1487 }
   1488 
   1489 /* free_c_table			INTERNAL
   1490  **
   1491  * Unmaps the given C table from use and returns it to the pool for
   1492  * re-use.  Returns the number of pages that were invalidated.
   1493  *
   1494  * This function preserves any physical page modification information
   1495  * contained in the page descriptors within the C table by calling
   1496  * 'pmap_remove_pte().'
   1497  */
   1498 int
   1499 free_c_table(c_tbl, relink)
   1500 	c_tmgr_t *c_tbl;
   1501 	boolean_t relink;
   1502 {
   1503 	int i, removed_cnt;
   1504 
   1505 	removed_cnt = 0;
   1506 	if (c_tbl->ct_ecnt) {
   1507 		for (i=0; i < MMU_C_TBL_SIZE; i++) {
   1508 			if (MMU_VALID_DT(c_tbl->ct_dtbl[i])) {
   1509 				pmap_remove_pte(&c_tbl->ct_dtbl[i]);
   1510 				removed_cnt++;
   1511 			}
   1512 		}
   1513 		c_tbl->ct_ecnt = 0;
   1514 	}
   1515 
   1516 	if (relink) {
   1517 		c_tbl->ct_parent = NULL;
   1518 		TAILQ_REMOVE(&c_pool, c_tbl, ct_link);
   1519 		TAILQ_INSERT_HEAD(&c_pool, c_tbl, ct_link);
   1520 	}
   1521 	return removed_cnt;
   1522 }
   1523 
   1524 #if 0
   1525 /* free_c_table_novalid			INTERNAL
   1526  **
   1527  * Frees the given C table manager without checking to see whether
   1528  * or not it contains any valid page descriptors as it is assumed
   1529  * that it does not.
   1530  */
   1531 void
   1532 free_c_table_novalid(c_tbl)
   1533 	c_tmgr_t *c_tbl;
   1534 {
   1535 	TAILQ_REMOVE(&c_pool, c_tbl, ct_link);
   1536 	TAILQ_INSERT_HEAD(&c_pool, c_tbl, ct_link);
   1537 	c_tbl->ct_parent->bt_dtbl[c_tbl->ct_pidx].attr.raw = MMU_DT_INVALID;
   1538 	c_tbl->ct_parent->bt_ecnt--;
   1539 	/*
   1540 	 * XXX - Should call equiv. of 'free_b_table_novalid' here if
   1541 	 * we just removed the last entry of the parent B table.
   1542 	 * But I want to insure that this will not endanger pmap_enter()
   1543 	 * with sudden removal of tables it is working with.
   1544 	 *
   1545 	 * We should probably add another field to each table, indicating
   1546 	 * whether or not it is 'locked', ie. in the process of being
   1547 	 * modified.
   1548 	 */
   1549 	c_tbl->ct_parent = NULL;
   1550 }
   1551 #endif
   1552 
   1553 /* pmap_remove_pte			INTERNAL
   1554  **
   1555  * Unmap the given pte and preserve any page modification
   1556  * information by transfering it to the pv head of the
   1557  * physical page it maps to.  This function does not update
   1558  * any reference counts because it is assumed that the calling
   1559  * function will do so.
   1560  */
   1561 void
   1562 pmap_remove_pte(pte)
   1563 	mmu_short_pte_t *pte;
   1564 {
   1565 	u_short     pv_idx, targ_idx;
   1566 	int         s;
   1567 	vm_offset_t pa;
   1568 	pv_t       *pv;
   1569 
   1570 	pa = MMU_PTE_PA(*pte);
   1571 	if (is_managed(pa)) {
   1572 		pv = pa2pv(pa);
   1573 		targ_idx = pteidx(pte);	/* Index of PTE being removed    */
   1574 
   1575 		/*
   1576 		 * If the PTE being removed is the first (or only) PTE in
   1577 		 * the list of PTEs currently mapped to this page, remove the
   1578 		 * PTE by changing the index found on the PV head.  Otherwise
   1579 		 * a linear search through the list will have to be executed
   1580 		 * in order to find the PVE which points to the PTE being
   1581 		 * removed, so that it may be modified to point to its new
   1582 		 * neighbor.
   1583 		 */
   1584 		s = splimp();
   1585 		pv_idx = pv->pv_idx;	/* Index of first PTE in PV list */
   1586 		if (pv_idx == targ_idx) {
   1587 			pv->pv_idx = pvebase[targ_idx].pve_next;
   1588 		} else {
   1589 			/*
   1590 			 * Find the PV element pointing to the target
   1591 			 * element.  Note: may have pv_idx==PVE_EOL
   1592 			 */
   1593 			for (;;) {
   1594 				if (pv_idx == PVE_EOL) {
   1595 #ifdef	PMAP_DEBUG
   1596 					printf("pmap_remove_pte: PVE_EOL\n");
   1597 					Debugger();
   1598 #endif
   1599 					goto pv_not_found;
   1600 				}
   1601 				if (pvebase[pv_idx].pve_next == targ_idx)
   1602 					break;
   1603 				pv_idx = pvebase[pv_idx].pve_next;
   1604 			}
   1605 			/*
   1606 			 * At this point, pv_idx is the index of the PV
   1607 			 * element just before the target element in the list.
   1608 			 * Unlink the target.
   1609 			 */
   1610 			pvebase[pv_idx].pve_next = pvebase[targ_idx].pve_next;
   1611 		pv_not_found:
   1612 		}
   1613 		/*
   1614 		 * Save the mod/ref bits of the pte by simply
   1615 		 * ORing the entire pte onto the pv_flags member
   1616 		 * of the pv structure.
   1617 		 * There is no need to use a separate bit pattern
   1618 		 * for usage information on the pv head than that
   1619 		 * which is used on the MMU ptes.
   1620 		 */
   1621 		pv->pv_flags |= (u_short) pte->attr.raw;
   1622 		splx(s);
   1623 	}
   1624 
   1625 	pte->attr.raw = MMU_DT_INVALID;
   1626 }
   1627 
   1628 /* pmap_stroll			INTERNAL
   1629  **
   1630  * Retrieve the addresses of all table managers involved in the mapping of
   1631  * the given virtual address.  If the table walk completed sucessfully,
   1632  * return TRUE.  If it was only partially sucessful, return FALSE.
   1633  * The table walk performed by this function is important to many other
   1634  * functions in this module.
   1635  *
   1636  * Note: This function ought to be easier to read.
   1637  */
   1638 boolean_t
   1639 pmap_stroll(pmap, va, a_tbl, b_tbl, c_tbl, pte, a_idx, b_idx, pte_idx)
   1640 	pmap_t pmap;
   1641 	vm_offset_t va;
   1642 	a_tmgr_t **a_tbl;
   1643 	b_tmgr_t **b_tbl;
   1644 	c_tmgr_t **c_tbl;
   1645 	mmu_short_pte_t **pte;
   1646 	int *a_idx, *b_idx, *pte_idx;
   1647 {
   1648 	mmu_long_dte_t *a_dte;   /* A: long descriptor table          */
   1649 	mmu_short_dte_t *b_dte;  /* B: short descriptor table         */
   1650 
   1651 	if (pmap == pmap_kernel())
   1652 		return FALSE;
   1653 
   1654 	/* Does the given pmap have its own A table? */
   1655 	*a_tbl = pmap->pm_a_tmgr;
   1656 	if (*a_tbl == NULL)
   1657 		return FALSE; /* No.  Return unknown. */
   1658 	/* Does the A table have a valid B table
   1659 	 * under the corresponding table entry?
   1660 	 */
   1661 	*a_idx = MMU_TIA(va);
   1662 	a_dte = &((*a_tbl)->at_dtbl[*a_idx]);
   1663 	if (!MMU_VALID_DT(*a_dte))
   1664 		return FALSE; /* No. Return unknown. */
   1665 	/* Yes. Extract B table from the A table. */
   1666 	*b_tbl = mmuB2tmgr(mmu_ptov(a_dte->addr.raw));
   1667 	/* Does the B table have a valid C table
   1668 	 * under the corresponding table entry?
   1669 	 */
   1670 	*b_idx = MMU_TIB(va);
   1671 	b_dte = &((*b_tbl)->bt_dtbl[*b_idx]);
   1672 	if (!MMU_VALID_DT(*b_dte))
   1673 		return FALSE; /* No. Return unknown. */
   1674 	/* Yes. Extract C table from the B table. */
   1675 	*c_tbl = mmuC2tmgr(mmu_ptov(MMU_DTE_PA(*b_dte)));
   1676 	*pte_idx = MMU_TIC(va);
   1677 	*pte = &((*c_tbl)->ct_dtbl[*pte_idx]);
   1678 
   1679 	return	TRUE;
   1680 }
   1681 
   1682 /* pmap_enter			INTERFACE
   1683  **
   1684  * Called by the kernel to map a virtual address
   1685  * to a physical address in the given process map.
   1686  *
   1687  * Note: this function should apply an exclusive lock
   1688  * on the pmap system for its duration.  (it certainly
   1689  * would save my hair!!)
   1690  * This function ought to be easier to read.
   1691  */
   1692 void
   1693 pmap_enter(pmap, va, pa, prot, wired)
   1694 	pmap_t	pmap;
   1695 	vm_offset_t va;
   1696 	vm_offset_t pa;
   1697 	vm_prot_t prot;
   1698 	boolean_t wired;
   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 }
   2567 
   2568 /* pmap_release				INTERFACE
   2569  **
   2570  * Release any resources held by the given pmap.
   2571  *
   2572  * This is the reverse analog to pmap_pinit.  It does not
   2573  * necessarily mean for the pmap structure to be deallocated,
   2574  * as in pmap_destroy.
   2575  */
   2576 void
   2577 pmap_release(pmap)
   2578 	pmap_t pmap;
   2579 {
   2580 	/*
   2581 	 * As long as the pmap contains no mappings,
   2582 	 * which always should be the case whenever
   2583 	 * this function is called, there really should
   2584 	 * be nothing to do.
   2585 	 */
   2586 #ifdef	PMAP_DEBUG
   2587 	if (pmap == NULL)
   2588 		return;
   2589 	if (pmap == pmap_kernel())
   2590 		panic("pmap_release: kernel pmap");
   2591 #endif
   2592 	/*
   2593 	 * XXX - If this pmap has an A table, give it back.
   2594 	 * The pmap SHOULD be empty by now, and pmap_remove
   2595 	 * should have already given back the A table...
   2596 	 * However, I see:  pmap->pm_a_tmgr->at_ecnt == 1
   2597 	 * at this point, which means some mapping was not
   2598 	 * removed when it should have been. -gwr
   2599 	 */
   2600 	if (pmap->pm_a_tmgr != NULL) {
   2601 		/* First make sure we are not using it! */
   2602 		if (kernel_crp.rp_addr == pmap->pm_a_phys) {
   2603 			kernel_crp.rp_addr = kernAphys;
   2604 			loadcrp(&kernel_crp);
   2605 		}
   2606 #ifdef	PMAP_DEBUG /* XXX - todo! */
   2607 		/* XXX - Now complain... */
   2608 		printf("pmap_release: still have table\n");
   2609 		Debugger();
   2610 #endif
   2611 		free_a_table(pmap->pm_a_tmgr, TRUE);
   2612 		pmap->pm_a_tmgr = NULL;
   2613 		pmap->pm_a_phys = kernAphys;
   2614 	}
   2615 }
   2616 
   2617 /* pmap_reference			INTERFACE
   2618  **
   2619  * Increment the reference count of a pmap.
   2620  */
   2621 void
   2622 pmap_reference(pmap)
   2623 	pmap_t pmap;
   2624 {
   2625 	if (pmap == NULL)
   2626 		return;
   2627 
   2628 	/* pmap_lock(pmap); */
   2629 	pmap->pm_refcount++;
   2630 	/* pmap_unlock(pmap); */
   2631 }
   2632 
   2633 /* pmap_dereference			INTERNAL
   2634  **
   2635  * Decrease the reference count on the given pmap
   2636  * by one and return the current count.
   2637  */
   2638 int
   2639 pmap_dereference(pmap)
   2640 	pmap_t pmap;
   2641 {
   2642 	int rtn;
   2643 
   2644 	if (pmap == NULL)
   2645 		return 0;
   2646 
   2647 	/* pmap_lock(pmap); */
   2648 	rtn = --pmap->pm_refcount;
   2649 	/* pmap_unlock(pmap); */
   2650 
   2651 	return rtn;
   2652 }
   2653 
   2654 /* pmap_destroy			INTERFACE
   2655  **
   2656  * Decrement a pmap's reference count and delete
   2657  * the pmap if it becomes zero.  Will be called
   2658  * only after all mappings have been removed.
   2659  */
   2660 void
   2661 pmap_destroy(pmap)
   2662 	pmap_t pmap;
   2663 {
   2664 	if (pmap == NULL)
   2665 		return;
   2666 	if (pmap == &kernel_pmap)
   2667 		panic("pmap_destroy: kernel_pmap!");
   2668 	if (pmap_dereference(pmap) == 0) {
   2669 		pmap_release(pmap);
   2670 		free(pmap, M_VMPMAP);
   2671 	}
   2672 }
   2673 
   2674 /* pmap_is_referenced			INTERFACE
   2675  **
   2676  * Determine if the given physical page has been
   2677  * referenced (read from [or written to.])
   2678  */
   2679 boolean_t
   2680 pmap_is_referenced(pa)
   2681 	vm_offset_t pa;
   2682 {
   2683 	pv_t      *pv;
   2684 	int       idx, s;
   2685 
   2686 	if (!pv_initialized)
   2687 		return FALSE;
   2688 	/* XXX - this may be unecessary. */
   2689 	if (!is_managed(pa))
   2690 		return FALSE;
   2691 
   2692 	pv = pa2pv(pa);
   2693 	/*
   2694 	 * Check the flags on the pv head.  If they are set,
   2695 	 * return immediately.  Otherwise a search must be done.
   2696 	 */
   2697 	if (pv->pv_flags & PV_FLAGS_USED)
   2698 		return TRUE;
   2699 
   2700 	s = splimp();
   2701 	/*
   2702 	 * Search through all pv elements pointing
   2703 	 * to this page and query their reference bits
   2704 	 */
   2705 	for (idx = pv->pv_idx;
   2706 		 idx != PVE_EOL;
   2707 		 idx = pvebase[idx].pve_next) {
   2708 
   2709 		if (MMU_PTE_USED(kernCbase[idx])) {
   2710 			splx(s);
   2711 			return TRUE;
   2712 		}
   2713 	}
   2714 	splx(s);
   2715 
   2716 	return FALSE;
   2717 }
   2718 
   2719 /* pmap_is_modified			INTERFACE
   2720  **
   2721  * Determine if the given physical page has been
   2722  * modified (written to.)
   2723  */
   2724 boolean_t
   2725 pmap_is_modified(pa)
   2726 	vm_offset_t pa;
   2727 {
   2728 	pv_t      *pv;
   2729 	int       idx, s;
   2730 
   2731 	if (!pv_initialized)
   2732 		return FALSE;
   2733 	/* XXX - this may be unecessary. */
   2734 	if (!is_managed(pa))
   2735 		return FALSE;
   2736 
   2737 	/* see comments in pmap_is_referenced() */
   2738 	pv = pa2pv(pa);
   2739 	if (pv->pv_flags & PV_FLAGS_MDFY)
   2740 		return TRUE;
   2741 
   2742 	s = splimp();
   2743 	for (idx = pv->pv_idx;
   2744 		 idx != PVE_EOL;
   2745 		 idx = pvebase[idx].pve_next) {
   2746 
   2747 		if (MMU_PTE_MODIFIED(kernCbase[idx])) {
   2748 			splx(s);
   2749 			return TRUE;
   2750 		}
   2751 	}
   2752 	splx(s);
   2753 
   2754 	return FALSE;
   2755 }
   2756 
   2757 /* pmap_page_protect			INTERFACE
   2758  **
   2759  * Applies the given protection to all mappings to the given
   2760  * physical page.
   2761  */
   2762 void
   2763 pmap_page_protect(pa, prot)
   2764 	vm_offset_t pa;
   2765 	vm_prot_t prot;
   2766 {
   2767 	pv_t      *pv;
   2768 	int       idx, s;
   2769 	vm_offset_t va;
   2770 	struct mmu_short_pte_struct *pte;
   2771 	c_tmgr_t  *c_tbl;
   2772 	pmap_t    pmap, curpmap;
   2773 
   2774 	if (!is_managed(pa))
   2775 		return;
   2776 
   2777 	curpmap = current_pmap();
   2778 	pv = pa2pv(pa);
   2779 	s = splimp();
   2780 
   2781 	for (idx = pv->pv_idx;
   2782 		 idx != PVE_EOL;
   2783 		 idx = pvebase[idx].pve_next) {
   2784 
   2785 		pte = &kernCbase[idx];
   2786 		switch (prot) {
   2787 			case VM_PROT_ALL:
   2788 				/* do nothing */
   2789 				break;
   2790 			case VM_PROT_EXECUTE:
   2791 			case VM_PROT_READ:
   2792 			case VM_PROT_READ|VM_PROT_EXECUTE:
   2793 				pte->attr.raw |= MMU_SHORT_PTE_WP;
   2794 
   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 				if (pmap == curpmap || pmap == pmap_kernel())
   2801 					TBIS(va);
   2802 				break;
   2803 			case VM_PROT_NONE:
   2804 				/* Save the mod/ref bits. */
   2805 				pv->pv_flags |= pte->attr.raw;
   2806 				/* Invalidate the PTE. */
   2807 				pte->attr.raw = MMU_DT_INVALID;
   2808 
   2809 				/*
   2810 				 * Update table counts.  And flush ATC entries
   2811 				 * if necessary.
   2812 				 */
   2813 				va = pmap_get_pteinfo(idx, &pmap, &c_tbl);
   2814 
   2815 				/*
   2816 				 * If the PTE belongs to the kernel map,
   2817 				 * be sure to flush the page it maps.
   2818 				 */
   2819 				if (pmap == pmap_kernel()) {
   2820 					TBIS(va);
   2821 				} else {
   2822 					/*
   2823 					 * The PTE belongs to a user map.
   2824 					 * update the entry count in the C
   2825 					 * table to which it belongs and flush
   2826 					 * the ATC if the mapping belongs to
   2827 					 * the current pmap.
   2828 					 */
   2829 					c_tbl->ct_ecnt--;
   2830 					if (pmap == curpmap)
   2831 						TBIS(va);
   2832 				}
   2833 				break;
   2834 			default:
   2835 				break;
   2836 		}
   2837 	}
   2838 
   2839 	/*
   2840 	 * If the protection code indicates that all mappings to the page
   2841 	 * be removed, truncate the PV list to zero entries.
   2842 	 */
   2843 	if (prot == VM_PROT_NONE)
   2844 		pv->pv_idx = PVE_EOL;
   2845 	splx(s);
   2846 }
   2847 
   2848 /* pmap_get_pteinfo		INTERNAL
   2849  **
   2850  * Called internally to find the pmap and virtual address within that
   2851  * map to which the pte at the given index maps.  Also includes the PTE's C
   2852  * table manager.
   2853  *
   2854  * Returns the pmap in the argument provided, and the virtual address
   2855  * by return value.
   2856  */
   2857 vm_offset_t
   2858 pmap_get_pteinfo(idx, pmap, tbl)
   2859 	u_int idx;
   2860 	pmap_t *pmap;
   2861 	c_tmgr_t **tbl;
   2862 {
   2863 	vm_offset_t     va = 0;
   2864 
   2865 	/*
   2866 	 * Determine if the PTE is a kernel PTE or a user PTE.
   2867 	 */
   2868 	if (idx >= NUM_KERN_PTES) {
   2869 		/*
   2870 		 * The PTE belongs to a user mapping.
   2871 		 */
   2872 		/* XXX: Would like an inline for this to validate idx... */
   2873 		*tbl = &Ctmgrbase[(idx - NUM_KERN_PTES) / MMU_C_TBL_SIZE];
   2874 
   2875 		*pmap = (*tbl)->ct_pmap;
   2876 		/*
   2877 		 * To find the va to which the PTE maps, we first take
   2878 		 * the table's base virtual address mapping which is stored
   2879 		 * in ct_va.  We then increment this address by a page for
   2880 		 * every slot skipped until we reach the PTE.
   2881 		 */
   2882 		va =    (*tbl)->ct_va;
   2883 		va += m68k_ptob(idx % MMU_C_TBL_SIZE);
   2884 	} else {
   2885 		/*
   2886 		 * The PTE belongs to the kernel map.
   2887 		 */
   2888 		*pmap = pmap_kernel();
   2889 
   2890 		va = m68k_ptob(idx);
   2891 		va += KERNBASE;
   2892 	}
   2893 
   2894 	return va;
   2895 }
   2896 
   2897 /* pmap_clear_modify			INTERFACE
   2898  **
   2899  * Clear the modification bit on the page at the specified
   2900  * physical address.
   2901  *
   2902  */
   2903 void
   2904 pmap_clear_modify(pa)
   2905 	vm_offset_t pa;
   2906 {
   2907 	if (!is_managed(pa))
   2908 		return;
   2909 	pmap_clear_pv(pa, PV_FLAGS_MDFY);
   2910 }
   2911 
   2912 /* pmap_clear_reference			INTERFACE
   2913  **
   2914  * Clear the referenced bit on the page at the specified
   2915  * physical address.
   2916  */
   2917 void
   2918 pmap_clear_reference(pa)
   2919 	vm_offset_t pa;
   2920 {
   2921 	if (!is_managed(pa))
   2922 		return;
   2923 	pmap_clear_pv(pa, PV_FLAGS_USED);
   2924 }
   2925 
   2926 /* pmap_clear_pv			INTERNAL
   2927  **
   2928  * Clears the specified flag from the specified physical address.
   2929  * (Used by pmap_clear_modify() and pmap_clear_reference().)
   2930  *
   2931  * Flag is one of:
   2932  *   PV_FLAGS_MDFY - Page modified bit.
   2933  *   PV_FLAGS_USED - Page used (referenced) bit.
   2934  *
   2935  * This routine must not only clear the flag on the pv list
   2936  * head.  It must also clear the bit on every pte in the pv
   2937  * list associated with the address.
   2938  */
   2939 void
   2940 pmap_clear_pv(pa, flag)
   2941 	vm_offset_t pa;
   2942 	int flag;
   2943 {
   2944 	pv_t      *pv;
   2945 	int       idx, s;
   2946 	vm_offset_t     va;
   2947 	pmap_t          pmap;
   2948 	mmu_short_pte_t *pte;
   2949 	c_tmgr_t        *c_tbl;
   2950 
   2951 	pv = pa2pv(pa);
   2952 
   2953 	s = splimp();
   2954 	pv->pv_flags &= ~(flag);
   2955 
   2956 	for (idx = pv->pv_idx;
   2957 		 idx != PVE_EOL;
   2958 		 idx = pvebase[idx].pve_next) {
   2959 
   2960 		pte = &kernCbase[idx];
   2961 		pte->attr.raw &= ~(flag);
   2962 		/*
   2963 		 * The MC68030 MMU will not set the modified or
   2964 		 * referenced bits on any MMU tables for which it has
   2965 		 * a cached descriptor with its modify bit set.  To insure
   2966 		 * that it will modify these bits on the PTE during the next
   2967 		 * time it is written to or read from, we must flush it from
   2968 		 * the ATC.
   2969 		 *
   2970 		 * Ordinarily it is only necessary to flush the descriptor
   2971 		 * if it is used in the current address space.  But since I
   2972 		 * am not sure that there will always be a notion of
   2973 		 * 'the current address space' when this function is called,
   2974 		 * I will skip the test and always flush the address.  It
   2975 		 * does no harm.
   2976 		 */
   2977 		va = pmap_get_pteinfo(idx, &pmap, &c_tbl);
   2978 		TBIS(va);
   2979 	}
   2980 	splx(s);
   2981 }
   2982 
   2983 /* pmap_extract			INTERFACE
   2984  **
   2985  * Return the physical address mapped by the virtual address
   2986  * in the specified pmap or 0 if it is not known.
   2987  *
   2988  * Note: this function should also apply an exclusive lock
   2989  * on the pmap system during its duration.
   2990  */
   2991 vm_offset_t
   2992 pmap_extract(pmap, va)
   2993 	pmap_t      pmap;
   2994 	vm_offset_t va;
   2995 {
   2996 	int a_idx, b_idx, pte_idx;
   2997 	a_tmgr_t	*a_tbl;
   2998 	b_tmgr_t	*b_tbl;
   2999 	c_tmgr_t	*c_tbl;
   3000 	mmu_short_pte_t	*c_pte;
   3001 
   3002 	if (pmap == pmap_kernel())
   3003 		return pmap_extract_kernel(va);
   3004 	if (pmap == NULL)
   3005 		return 0;
   3006 
   3007 	if (pmap_stroll(pmap, va, &a_tbl, &b_tbl, &c_tbl,
   3008 		&c_pte, &a_idx, &b_idx, &pte_idx) == FALSE)
   3009 		return 0;
   3010 
   3011 	if (!MMU_VALID_DT(*c_pte))
   3012 		return 0;
   3013 
   3014 	return (MMU_PTE_PA(*c_pte));
   3015 }
   3016 
   3017 /* pmap_extract_kernel		INTERNAL
   3018  **
   3019  * Extract a translation from the kernel address space.
   3020  */
   3021 vm_offset_t
   3022 pmap_extract_kernel(va)
   3023 	vm_offset_t va;
   3024 {
   3025 	mmu_short_pte_t *pte;
   3026 
   3027 	pte = &kernCbase[(u_int) m68k_btop(va - KERNBASE)];
   3028 	return MMU_PTE_PA(*pte);
   3029 }
   3030 
   3031 /* pmap_remove_kernel		INTERNAL
   3032  **
   3033  * Remove the mapping of a range of virtual addresses from the kernel map.
   3034  * The arguments are already page-aligned.
   3035  */
   3036 void
   3037 pmap_remove_kernel(sva, eva)
   3038 	vm_offset_t sva;
   3039 	vm_offset_t eva;
   3040 {
   3041 	int idx, eidx;
   3042 
   3043 #ifdef	PMAP_DEBUG
   3044 	if ((sva & PGOFSET) || (eva & PGOFSET))
   3045 		panic("pmap_remove_kernel: alignment");
   3046 #endif
   3047 
   3048 	idx  = m68k_btop(sva - KERNBASE);
   3049 	eidx = m68k_btop(eva - KERNBASE);
   3050 
   3051 	while (idx < eidx) {
   3052 		pmap_remove_pte(&kernCbase[idx++]);
   3053 		TBIS(sva);
   3054 		sva += NBPG;
   3055 	}
   3056 }
   3057 
   3058 /* pmap_remove			INTERFACE
   3059  **
   3060  * Remove the mapping of a range of virtual addresses from the given pmap.
   3061  *
   3062  * If the range contains any wired entries, this function will probably create
   3063  * disaster.
   3064  */
   3065 void
   3066 pmap_remove(pmap, start, end)
   3067 	pmap_t pmap;
   3068 	vm_offset_t start;
   3069 	vm_offset_t end;
   3070 {
   3071 
   3072 	if (pmap == pmap_kernel()) {
   3073 		pmap_remove_kernel(start, end);
   3074 		return;
   3075 	}
   3076 
   3077 	/*
   3078 	 * XXX - Temporary(?) statement to prevent panic caused
   3079 	 * by vm_alloc_with_pager() handing us a software map (ie NULL)
   3080 	 * to remove because it couldn't get backing store.
   3081 	 * (I guess.)
   3082 	 */
   3083 	if (pmap == NULL)
   3084 		return;
   3085 
   3086 	/*
   3087 	 * If the pmap doesn't have an A table of its own, it has no mappings
   3088 	 * that can be removed.
   3089 	 */
   3090 	if (pmap->pm_a_tmgr == NULL)
   3091 		return;
   3092 
   3093 	/*
   3094 	 * Remove the specified range from the pmap.  If the function
   3095 	 * returns true, the operation removed all the valid mappings
   3096 	 * in the pmap and freed its A table.  If this happened to the
   3097 	 * currently loaded pmap, the MMU root pointer must be reloaded
   3098 	 * with the default 'kernel' map.
   3099 	 */
   3100 	if (pmap_remove_a(pmap->pm_a_tmgr, start, end)) {
   3101 		if (kernel_crp.rp_addr == pmap->pm_a_phys) {
   3102 			kernel_crp.rp_addr = kernAphys;
   3103 			loadcrp(&kernel_crp);
   3104 			/* will do TLB flush below */
   3105 		}
   3106 		pmap->pm_a_tmgr = NULL;
   3107 		pmap->pm_a_phys = kernAphys;
   3108 	}
   3109 
   3110 	/*
   3111 	 * If we just modified the current address space,
   3112 	 * make sure to flush the MMU cache.
   3113 	 *
   3114 	 * XXX - this could be an unecessarily large flush.
   3115 	 * XXX - Could decide, based on the size of the VA range
   3116 	 * to be removed, whether to flush "by pages" or "all".
   3117 	 */
   3118 	if (pmap == current_pmap())
   3119 		TBIAU();
   3120 }
   3121 
   3122 /* pmap_remove_a			INTERNAL
   3123  **
   3124  * This is function number one in a set of three that removes a range
   3125  * of memory in the most efficient manner by removing the highest possible
   3126  * tables from the memory space.  This particular function attempts to remove
   3127  * as many B tables as it can, delegating the remaining fragmented ranges to
   3128  * pmap_remove_b().
   3129  *
   3130  * If the removal operation results in an empty A table, the function returns
   3131  * TRUE.
   3132  *
   3133  * It's ugly but will do for now.
   3134  */
   3135 boolean_t
   3136 pmap_remove_a(a_tbl, start, end)
   3137 	a_tmgr_t *a_tbl;
   3138 	vm_offset_t start;
   3139 	vm_offset_t end;
   3140 {
   3141 	boolean_t empty;
   3142 	int idx;
   3143 	vm_offset_t nstart, nend;
   3144 	b_tmgr_t *b_tbl;
   3145 	mmu_long_dte_t  *a_dte;
   3146 	mmu_short_dte_t *b_dte;
   3147 
   3148 	/*
   3149 	 * The following code works with what I call a 'granularity
   3150 	 * reduction algorithim'.  A range of addresses will always have
   3151 	 * the following properties, which are classified according to
   3152 	 * how the range relates to the size of the current granularity
   3153 	 * - an A table entry:
   3154 	 *
   3155 	 *            1 2       3 4
   3156 	 * -+---+---+---+---+---+---+---+-
   3157 	 * -+---+---+---+---+---+---+---+-
   3158 	 *
   3159 	 * A range will always start on a granularity boundary, illustrated
   3160 	 * by '+' signs in the table above, or it will start at some point
   3161 	 * inbetween a granularity boundary, as illustrated by point 1.
   3162 	 * The first step in removing a range of addresses is to remove the
   3163 	 * range between 1 and 2, the nearest granularity boundary.  This
   3164 	 * job is handled by the section of code governed by the
   3165 	 * 'if (start < nstart)' statement.
   3166 	 *
   3167 	 * A range will always encompass zero or more intergral granules,
   3168 	 * illustrated by points 2 and 3.  Integral granules are easy to
   3169 	 * remove.  The removal of these granules is the second step, and
   3170 	 * is handled by the code block 'if (nstart < nend)'.
   3171 	 *
   3172 	 * Lastly, a range will always end on a granularity boundary,
   3173 	 * ill. by point 3, or it will fall just beyond one, ill. by point
   3174 	 * 4.  The last step involves removing this range and is handled by
   3175 	 * the code block 'if (nend < end)'.
   3176 	 */
   3177 	nstart = MMU_ROUND_UP_A(start);
   3178 	nend = MMU_ROUND_A(end);
   3179 
   3180 	if (start < nstart) {
   3181 		/*
   3182 		 * This block is executed if the range starts between
   3183 		 * a granularity boundary.
   3184 		 *
   3185 		 * First find the DTE which is responsible for mapping
   3186 		 * the start of the range.
   3187 		 */
   3188 		idx = MMU_TIA(start);
   3189 		a_dte = &a_tbl->at_dtbl[idx];
   3190 
   3191 		/*
   3192 		 * If the DTE is valid then delegate the removal of the sub
   3193 		 * range to pmap_remove_b(), which can remove addresses at
   3194 		 * a finer granularity.
   3195 		 */
   3196 		if (MMU_VALID_DT(*a_dte)) {
   3197 			b_dte = mmu_ptov(a_dte->addr.raw);
   3198 			b_tbl = mmuB2tmgr(b_dte);
   3199 
   3200 			/*
   3201 			 * The sub range to be removed starts at the start
   3202 			 * of the full range we were asked to remove, and ends
   3203 			 * at the greater of:
   3204 			 * 1. The end of the full range, -or-
   3205 			 * 2. The end of the full range, rounded down to the
   3206 			 *    nearest granularity boundary.
   3207 			 */
   3208 			if (end < nstart)
   3209 				empty = pmap_remove_b(b_tbl, start, end);
   3210 			else
   3211 				empty = pmap_remove_b(b_tbl, start, nstart);
   3212 
   3213 			/*
   3214 			 * If the removal resulted in an empty B table,
   3215 			 * invalidate the DTE that points to it and decrement
   3216 			 * the valid entry count of the A table.
   3217 			 */
   3218 			if (empty) {
   3219 				a_dte->attr.raw = MMU_DT_INVALID;
   3220 				a_tbl->at_ecnt--;
   3221 			}
   3222 		}
   3223 		/*
   3224 		 * If the DTE is invalid, the address range is already non-
   3225 		 * existant and can simply be skipped.
   3226 		 */
   3227 	}
   3228 	if (nstart < nend) {
   3229 		/*
   3230 		 * This block is executed if the range spans a whole number
   3231 		 * multiple of granules (A table entries.)
   3232 		 *
   3233 		 * First find the DTE which is responsible for mapping
   3234 		 * the start of the first granule involved.
   3235 		 */
   3236 		idx = MMU_TIA(nstart);
   3237 		a_dte = &a_tbl->at_dtbl[idx];
   3238 
   3239 		/*
   3240 		 * Remove entire sub-granules (B tables) one at a time,
   3241 		 * until reaching the end of the range.
   3242 		 */
   3243 		for (; nstart < nend; a_dte++, nstart += MMU_TIA_RANGE)
   3244 			if (MMU_VALID_DT(*a_dte)) {
   3245 				/*
   3246 				 * Find the B table manager for the
   3247 				 * entry and free it.
   3248 				 */
   3249 				b_dte = mmu_ptov(a_dte->addr.raw);
   3250 				b_tbl = mmuB2tmgr(b_dte);
   3251 				free_b_table(b_tbl, TRUE);
   3252 
   3253 				/*
   3254 				 * Invalidate the DTE that points to the
   3255 				 * B table and decrement the valid entry
   3256 				 * count of the A table.
   3257 				 */
   3258 				a_dte->attr.raw = MMU_DT_INVALID;
   3259 				a_tbl->at_ecnt--;
   3260 			}
   3261 	}
   3262 	if (nend < end) {
   3263 		/*
   3264 		 * This block is executed if the range ends beyond a
   3265 		 * granularity boundary.
   3266 		 *
   3267 		 * First find the DTE which is responsible for mapping
   3268 		 * the start of the nearest (rounded down) granularity
   3269 		 * boundary.
   3270 		 */
   3271 		idx = MMU_TIA(nend);
   3272 		a_dte = &a_tbl->at_dtbl[idx];
   3273 
   3274 		/*
   3275 		 * If the DTE is valid then delegate the removal of the sub
   3276 		 * range to pmap_remove_b(), which can remove addresses at
   3277 		 * a finer granularity.
   3278 		 */
   3279 		if (MMU_VALID_DT(*a_dte)) {
   3280 			/*
   3281 			 * Find the B table manager for the entry
   3282 			 * and hand it to pmap_remove_b() along with
   3283 			 * the sub range.
   3284 			 */
   3285 			b_dte = mmu_ptov(a_dte->addr.raw);
   3286 			b_tbl = mmuB2tmgr(b_dte);
   3287 
   3288 			empty = pmap_remove_b(b_tbl, nend, end);
   3289 
   3290 			/*
   3291 			 * If the removal resulted in an empty B table,
   3292 			 * invalidate the DTE that points to it and decrement
   3293 			 * the valid entry count of the A table.
   3294 			 */
   3295 			if (empty) {
   3296 				a_dte->attr.raw = MMU_DT_INVALID;
   3297 				a_tbl->at_ecnt--;
   3298 			}
   3299 		}
   3300 	}
   3301 
   3302 	/*
   3303 	 * If there are no more entries in the A table, release it
   3304 	 * back to the available pool and return TRUE.
   3305 	 */
   3306 	if (a_tbl->at_ecnt == 0) {
   3307 		a_tbl->at_parent = NULL;
   3308 		TAILQ_REMOVE(&a_pool, a_tbl, at_link);
   3309 		TAILQ_INSERT_HEAD(&a_pool, a_tbl, at_link);
   3310 		empty = TRUE;
   3311 	} else {
   3312 		empty = FALSE;
   3313 	}
   3314 
   3315 	return empty;
   3316 }
   3317 
   3318 /* pmap_remove_b			INTERNAL
   3319  **
   3320  * Remove a range of addresses from an address space, trying to remove entire
   3321  * C tables if possible.
   3322  *
   3323  * If the operation results in an empty B table, the function returns TRUE.
   3324  */
   3325 boolean_t
   3326 pmap_remove_b(b_tbl, start, end)
   3327 	b_tmgr_t *b_tbl;
   3328 	vm_offset_t start;
   3329 	vm_offset_t end;
   3330 {
   3331 	boolean_t empty;
   3332 	int idx;
   3333 	vm_offset_t nstart, nend, rstart;
   3334 	c_tmgr_t *c_tbl;
   3335 	mmu_short_dte_t  *b_dte;
   3336 	mmu_short_pte_t  *c_dte;
   3337 
   3338 
   3339 	nstart = MMU_ROUND_UP_B(start);
   3340 	nend = MMU_ROUND_B(end);
   3341 
   3342 	if (start < nstart) {
   3343 		idx = MMU_TIB(start);
   3344 		b_dte = &b_tbl->bt_dtbl[idx];
   3345 		if (MMU_VALID_DT(*b_dte)) {
   3346 			c_dte = mmu_ptov(MMU_DTE_PA(*b_dte));
   3347 			c_tbl = mmuC2tmgr(c_dte);
   3348 			if (end < nstart)
   3349 				empty = pmap_remove_c(c_tbl, start, end);
   3350 			else
   3351 				empty = pmap_remove_c(c_tbl, start, nstart);
   3352 			if (empty) {
   3353 				b_dte->attr.raw = MMU_DT_INVALID;
   3354 				b_tbl->bt_ecnt--;
   3355 			}
   3356 		}
   3357 	}
   3358 	if (nstart < nend) {
   3359 		idx = MMU_TIB(nstart);
   3360 		b_dte = &b_tbl->bt_dtbl[idx];
   3361 		rstart = nstart;
   3362 		while (rstart < nend) {
   3363 			if (MMU_VALID_DT(*b_dte)) {
   3364 				c_dte = mmu_ptov(MMU_DTE_PA(*b_dte));
   3365 				c_tbl = mmuC2tmgr(c_dte);
   3366 				free_c_table(c_tbl, TRUE);
   3367 				b_dte->attr.raw = MMU_DT_INVALID;
   3368 				b_tbl->bt_ecnt--;
   3369 			}
   3370 			b_dte++;
   3371 			rstart += MMU_TIB_RANGE;
   3372 		}
   3373 	}
   3374 	if (nend < end) {
   3375 		idx = MMU_TIB(nend);
   3376 		b_dte = &b_tbl->bt_dtbl[idx];
   3377 		if (MMU_VALID_DT(*b_dte)) {
   3378 			c_dte = mmu_ptov(MMU_DTE_PA(*b_dte));
   3379 			c_tbl = mmuC2tmgr(c_dte);
   3380 			empty = pmap_remove_c(c_tbl, nend, end);
   3381 			if (empty) {
   3382 				b_dte->attr.raw = MMU_DT_INVALID;
   3383 				b_tbl->bt_ecnt--;
   3384 			}
   3385 		}
   3386 	}
   3387 
   3388 	if (b_tbl->bt_ecnt == 0) {
   3389 		b_tbl->bt_parent = NULL;
   3390 		TAILQ_REMOVE(&b_pool, b_tbl, bt_link);
   3391 		TAILQ_INSERT_HEAD(&b_pool, b_tbl, bt_link);
   3392 		empty = TRUE;
   3393 	} else {
   3394 		empty = FALSE;
   3395 	}
   3396 
   3397 	return empty;
   3398 }
   3399 
   3400 /* pmap_remove_c			INTERNAL
   3401  **
   3402  * Remove a range of addresses from the given C table.
   3403  */
   3404 boolean_t
   3405 pmap_remove_c(c_tbl, start, end)
   3406 	c_tmgr_t *c_tbl;
   3407 	vm_offset_t start;
   3408 	vm_offset_t end;
   3409 {
   3410 	boolean_t empty;
   3411 	int idx;
   3412 	mmu_short_pte_t *c_pte;
   3413 
   3414 	idx = MMU_TIC(start);
   3415 	c_pte = &c_tbl->ct_dtbl[idx];
   3416 	for (;start < end; start += MMU_PAGE_SIZE, c_pte++) {
   3417 		if (MMU_VALID_DT(*c_pte)) {
   3418 			pmap_remove_pte(c_pte);
   3419 			c_tbl->ct_ecnt--;
   3420 		}
   3421 	}
   3422 
   3423 	if (c_tbl->ct_ecnt == 0) {
   3424 		c_tbl->ct_parent = NULL;
   3425 		TAILQ_REMOVE(&c_pool, c_tbl, ct_link);
   3426 		TAILQ_INSERT_HEAD(&c_pool, c_tbl, ct_link);
   3427 		empty = TRUE;
   3428 	} else {
   3429 		empty = FALSE;
   3430 	}
   3431 
   3432 	return empty;
   3433 }
   3434 
   3435 /* is_managed				INTERNAL
   3436  **
   3437  * Determine if the given physical address is managed by the PV system.
   3438  * Note that this logic assumes that no one will ask for the status of
   3439  * addresses which lie in-between the memory banks on the 3/80.  If they
   3440  * do so, it will falsely report that it is managed.
   3441  *
   3442  * Note: A "managed" address is one that was reported to the VM system as
   3443  * a "usable page" during system startup.  As such, the VM system expects the
   3444  * pmap module to keep an accurate track of the useage of those pages.
   3445  * Any page not given to the VM system at startup does not exist (as far as
   3446  * the VM system is concerned) and is therefore "unmanaged."  Examples are
   3447  * those pages which belong to the ROM monitor and the memory allocated before
   3448  * the VM system was started.
   3449  */
   3450 boolean_t
   3451 is_managed(pa)
   3452 	vm_offset_t pa;
   3453 {
   3454 	if (pa >= avail_start && pa < avail_end)
   3455 		return TRUE;
   3456 	else
   3457 		return FALSE;
   3458 }
   3459 
   3460 /* pmap_bootstrap_alloc			INTERNAL
   3461  **
   3462  * Used internally for memory allocation at startup when malloc is not
   3463  * available.  This code will fail once it crosses the first memory
   3464  * bank boundary on the 3/80.  Hopefully by then however, the VM system
   3465  * will be in charge of allocation.
   3466  */
   3467 void *
   3468 pmap_bootstrap_alloc(size)
   3469 	int size;
   3470 {
   3471 	void *rtn;
   3472 
   3473 #ifdef	PMAP_DEBUG
   3474 	if (bootstrap_alloc_enabled == FALSE) {
   3475 		mon_printf("pmap_bootstrap_alloc: disabled\n");
   3476 		sunmon_abort();
   3477 	}
   3478 #endif
   3479 
   3480 	rtn = (void *) virtual_avail;
   3481 	virtual_avail += size;
   3482 
   3483 #ifdef	PMAP_DEBUG
   3484 	if (virtual_avail > virtual_contig_end) {
   3485 		mon_printf("pmap_bootstrap_alloc: out of mem\n");
   3486 		sunmon_abort();
   3487 	}
   3488 #endif
   3489 
   3490 	return rtn;
   3491 }
   3492 
   3493 /* pmap_bootstap_aalign			INTERNAL
   3494  **
   3495  * Used to insure that the next call to pmap_bootstrap_alloc() will
   3496  * return a chunk of memory aligned to the specified size.
   3497  *
   3498  * Note: This function will only support alignment sizes that are powers
   3499  * of two.
   3500  */
   3501 void
   3502 pmap_bootstrap_aalign(size)
   3503 	int size;
   3504 {
   3505 	int off;
   3506 
   3507 	off = virtual_avail & (size - 1);
   3508 	if (off) {
   3509 		(void) pmap_bootstrap_alloc(size - off);
   3510 	}
   3511 }
   3512 
   3513 /* pmap_pa_exists
   3514  **
   3515  * Used by the /dev/mem driver to see if a given PA is memory
   3516  * that can be mapped.  (The PA is not in a hole.)
   3517  */
   3518 int
   3519 pmap_pa_exists(pa)
   3520 	vm_offset_t pa;
   3521 {
   3522 	register int i;
   3523 
   3524 	for (i = 0; i < SUN3X_NPHYS_RAM_SEGS; i++) {
   3525 		if ((pa >= avail_mem[i].pmem_start) &&
   3526 			(pa <  avail_mem[i].pmem_end))
   3527 			return (1);
   3528 		if (avail_mem[i].pmem_next == NULL)
   3529 			break;
   3530 	}
   3531 	return (0);
   3532 }
   3533 
   3534 /* Called only from locore.s and pmap.c */
   3535 void	_pmap_switch __P((pmap_t pmap));
   3536 
   3537 /*
   3538  * _pmap_switch			INTERNAL
   3539  *
   3540  * This is called by locore.s:cpu_switch() when it is
   3541  * switching to a new process.  Load new translations.
   3542  * Note: done in-line by locore.s unless PMAP_DEBUG
   3543  *
   3544  * Note that we do NOT allocate a context here, but
   3545  * share the "kernel only" context until we really
   3546  * need our own context for user-space mappings in
   3547  * pmap_enter_user().  [ s/context/mmu A table/ ]
   3548  */
   3549 void
   3550 _pmap_switch(pmap)
   3551 	pmap_t pmap;
   3552 {
   3553 	u_long rootpa;
   3554 
   3555 	/*
   3556 	 * Only do reload/flush if we have to.
   3557 	 * Note that if the old and new process
   3558 	 * were BOTH using the "null" context,
   3559 	 * then this will NOT flush the TLB.
   3560 	 */
   3561 	rootpa = pmap->pm_a_phys;
   3562 	if (kernel_crp.rp_addr != rootpa) {
   3563 		DPRINT(("pmap_activate(%p)\n", pmap));
   3564 		kernel_crp.rp_addr = rootpa;
   3565 		loadcrp(&kernel_crp);
   3566 		TBIAU();
   3567 	}
   3568 }
   3569 
   3570 /*
   3571  * Exported version of pmap_activate().  This is called from the
   3572  * machine-independent VM code when a process is given a new pmap.
   3573  * If (p == curproc) do like cpu_switch would do; otherwise just
   3574  * take this as notification that the process has a new pmap.
   3575  */
   3576 void
   3577 pmap_activate(p)
   3578 	struct proc *p;
   3579 {
   3580 	pmap_t pmap = p->p_vmspace->vm_map.pmap;
   3581 	int s;
   3582 
   3583 	if (p == curproc) {
   3584 		s = splimp();
   3585 		_pmap_switch(pmap);
   3586 		splx(s);
   3587 	}
   3588 }
   3589 
   3590 /*
   3591  * pmap_deactivate			INTERFACE
   3592  **
   3593  * This is called to deactivate the specified process's address space.
   3594  * XXX The semantics of this function are currently not well-defined.
   3595  */
   3596 void
   3597 pmap_deactivate(p)
   3598 struct proc *p;
   3599 {
   3600 	/* not implemented. */
   3601 }
   3602 
   3603 /* pmap_update
   3604  **
   3605  * Apply any delayed changes scheduled for all pmaps immediately.
   3606  *
   3607  * No delayed operations are currently done in this pmap.
   3608  */
   3609 void
   3610 pmap_update()
   3611 {
   3612 	/* not implemented. */
   3613 }
   3614 
   3615 /*
   3616  * Fill in the sun3x-specific part of the kernel core header
   3617  * for dumpsys().  (See machdep.c for the rest.)
   3618  */
   3619 void
   3620 pmap_kcore_hdr(sh)
   3621 	struct sun3x_kcore_hdr *sh;
   3622 {
   3623 	u_long spa, len;
   3624 	int i;
   3625 
   3626 	sh->pg_frame = MMU_SHORT_PTE_BASEADDR;
   3627 	sh->pg_valid = MMU_DT_PAGE;
   3628 	sh->contig_end = virtual_contig_end;
   3629 	sh->kernCbase = (u_long) kernCbase;
   3630 	for (i = 0; i < SUN3X_NPHYS_RAM_SEGS; i++) {
   3631 		spa = avail_mem[i].pmem_start;
   3632 		spa = m68k_trunc_page(spa);
   3633 		len = avail_mem[i].pmem_end - spa;
   3634 		len = m68k_round_page(len);
   3635 		sh->ram_segs[i].start = spa;
   3636 		sh->ram_segs[i].size  = len;
   3637 	}
   3638 }
   3639 
   3640 
   3641 /* pmap_virtual_space			INTERFACE
   3642  **
   3643  * Return the current available range of virtual addresses in the
   3644  * arguuments provided.  Only really called once.
   3645  */
   3646 void
   3647 pmap_virtual_space(vstart, vend)
   3648 	vm_offset_t *vstart, *vend;
   3649 {
   3650 	*vstart = virtual_avail;
   3651 	*vend = virtual_end;
   3652 }
   3653 
   3654 /* pmap_free_pages			INTERFACE
   3655  **
   3656  * Return the number of physical pages still available.
   3657  *
   3658  * This is probably going to be a mess, but it's only called
   3659  * once and it's the only function left that I have to implement!
   3660  */
   3661 u_int
   3662 pmap_free_pages()
   3663 {
   3664 	int i;
   3665 	u_int left;
   3666 	vm_offset_t avail;
   3667 
   3668 	avail = avail_next;
   3669 	left = 0;
   3670 	i = 0;
   3671 	while (avail >= avail_mem[i].pmem_end) {
   3672 		if (avail_mem[i].pmem_next == NULL)
   3673 			return 0;
   3674 		i++;
   3675 	}
   3676 	while (i < SUN3X_NPHYS_RAM_SEGS) {
   3677 		if (avail < avail_mem[i].pmem_start) {
   3678 			/* Avail is inside a hole, march it
   3679 			 * up to the next bank.
   3680 			 */
   3681 			avail = avail_mem[i].pmem_start;
   3682 		}
   3683 		left += m68k_btop(avail_mem[i].pmem_end - avail);
   3684 		if (avail_mem[i].pmem_next == NULL)
   3685 			break;
   3686 		i++;
   3687 	}
   3688 
   3689 	return left;
   3690 }
   3691 
   3692 /* pmap_page_index			INTERFACE
   3693  **
   3694  * Return the index of the given physical page in a list of useable
   3695  * physical pages in the system.  Holes in physical memory may be counted
   3696  * if so desired.  As long as pmap_free_pages() and pmap_page_index()
   3697  * agree as to whether holes in memory do or do not count as valid pages,
   3698  * it really doesn't matter.  However, if you like to save a little
   3699  * memory, don't count holes as valid pages.  This is even more true when
   3700  * the holes are large.
   3701  *
   3702  * We will not count holes as valid pages.  We can generate page indices
   3703  * that conform to this by using the memory bank structures initialized
   3704  * in pmap_alloc_pv().
   3705  */
   3706 int
   3707 pmap_page_index(pa)
   3708 	vm_offset_t pa;
   3709 {
   3710 	struct pmap_physmem_struct *bank = avail_mem;
   3711 
   3712 	/* Search for the memory bank with this page. */
   3713 	/* XXX - What if it is not physical memory? */
   3714 	while (pa > bank->pmem_end)
   3715 		bank = bank->pmem_next;
   3716 	pa -= bank->pmem_start;
   3717 
   3718 	return (bank->pmem_pvbase + m68k_btop(pa));
   3719 }
   3720 
   3721 /* pmap_next_page			INTERFACE
   3722  **
   3723  * Place the physical address of the next available page in the
   3724  * argument given.  Returns FALSE if there are no more pages left.
   3725  *
   3726  * This function must jump over any holes in physical memory.
   3727  * Once this function is used, any use of pmap_bootstrap_alloc()
   3728  * is a sin.  Sinners will be punished with erratic behavior.
   3729  */
   3730 boolean_t
   3731 pmap_next_page(pa)
   3732 	vm_offset_t *pa;
   3733 {
   3734 	static struct pmap_physmem_struct *curbank = avail_mem;
   3735 
   3736 	/* XXX - temporary ROM saving hack. */
   3737 	if (avail_next >= avail_end)
   3738 		return FALSE;
   3739 
   3740 	if (avail_next >= curbank->pmem_end)
   3741 		if (curbank->pmem_next == NULL)
   3742 			return FALSE;
   3743 		else {
   3744 			curbank = curbank->pmem_next;
   3745 			avail_next = curbank->pmem_start;
   3746 		}
   3747 
   3748 	*pa = avail_next;
   3749 	avail_next += NBPG;
   3750 	return TRUE;
   3751 }
   3752 
   3753 /* pmap_count			INTERFACE
   3754  **
   3755  * Return the number of resident (valid) pages in the given pmap.
   3756  *
   3757  * Note:  If this function is handed the kernel map, it will report
   3758  * that it has no mappings.  Hopefully the VM system won't ask for kernel
   3759  * map statistics.
   3760  */
   3761 segsz_t
   3762 pmap_count(pmap, type)
   3763 	pmap_t pmap;
   3764 	int    type;
   3765 {
   3766 	u_int     count;
   3767 	int       a_idx, b_idx;
   3768 	a_tmgr_t *a_tbl;
   3769 	b_tmgr_t *b_tbl;
   3770 	c_tmgr_t *c_tbl;
   3771 
   3772 	/*
   3773 	 * If the pmap does not have its own A table manager, it has no
   3774 	 * valid entires.
   3775 	 */
   3776 	if (pmap->pm_a_tmgr == NULL)
   3777 		return 0;
   3778 
   3779 	a_tbl = pmap->pm_a_tmgr;
   3780 
   3781 	count = 0;
   3782 	for (a_idx = 0; a_idx < MMU_TIA(KERNBASE); a_idx++) {
   3783 	    if (MMU_VALID_DT(a_tbl->at_dtbl[a_idx])) {
   3784 	        b_tbl = mmuB2tmgr(mmu_ptov(a_tbl->at_dtbl[a_idx].addr.raw));
   3785 	        for (b_idx = 0; b_idx < MMU_B_TBL_SIZE; b_idx++) {
   3786 	            if (MMU_VALID_DT(b_tbl->bt_dtbl[b_idx])) {
   3787 	                c_tbl = mmuC2tmgr(
   3788 	                    mmu_ptov(MMU_DTE_PA(b_tbl->bt_dtbl[b_idx])));
   3789 	                if (type == 0)
   3790 	                    /*
   3791 	                     * A resident entry count has been requested.
   3792 	                     */
   3793 	                    count += c_tbl->ct_ecnt;
   3794 	                else
   3795 	                    /*
   3796 	                     * A wired entry count has been requested.
   3797 	                     */
   3798 	                    count += c_tbl->ct_wcnt;
   3799 	            }
   3800 	        }
   3801 	    }
   3802 	}
   3803 
   3804 	return count;
   3805 }
   3806 
   3807 /************************ SUN3 COMPATIBILITY ROUTINES ********************
   3808  * The following routines are only used by DDB for tricky kernel text    *
   3809  * text operations in db_memrw.c.  They are provided for sun3            *
   3810  * compatibility.                                                        *
   3811  *************************************************************************/
   3812 /* get_pte			INTERNAL
   3813  **
   3814  * Return the page descriptor the describes the kernel mapping
   3815  * of the given virtual address.
   3816  */
   3817 extern u_long ptest_addr __P((u_long));	/* XXX: locore.s */
   3818 u_int
   3819 get_pte(va)
   3820 	vm_offset_t va;
   3821 {
   3822 	u_long pte_pa;
   3823 	mmu_short_pte_t *pte;
   3824 
   3825 	/* Get the physical address of the PTE */
   3826 	pte_pa = ptest_addr(va & ~PGOFSET);
   3827 
   3828 	/* Convert to a virtual address... */
   3829 	pte = (mmu_short_pte_t *) (KERNBASE + pte_pa);
   3830 
   3831 	/* Make sure it is in our level-C tables... */
   3832 	if ((pte < kernCbase) ||
   3833 		(pte >= &mmuCbase[NUM_USER_PTES]))
   3834 		return 0;
   3835 
   3836 	/* ... and just return its contents. */
   3837 	return (pte->attr.raw);
   3838 }
   3839 
   3840 
   3841 /* set_pte			INTERNAL
   3842  **
   3843  * Set the page descriptor that describes the kernel mapping
   3844  * of the given virtual address.
   3845  */
   3846 void
   3847 set_pte(va, pte)
   3848 	vm_offset_t va;
   3849 	u_int pte;
   3850 {
   3851 	u_long idx;
   3852 
   3853 	if (va < KERNBASE)
   3854 		return;
   3855 
   3856 	idx = (unsigned long) m68k_btop(va - KERNBASE);
   3857 	kernCbase[idx].attr.raw = pte;
   3858 	TBIS(va);
   3859 }
   3860 
   3861 #ifdef	PMAP_DEBUG
   3862 /************************** DEBUGGING ROUTINES **************************
   3863  * The following routines are meant to be an aid to debugging the pmap  *
   3864  * system.  They are callable from the DDB command line and should be   *
   3865  * prepared to be handed unstable or incomplete states of the system.   *
   3866  ************************************************************************/
   3867 
   3868 /* pv_list
   3869  **
   3870  * List all pages found on the pv list for the given physical page.
   3871  * To avoid endless loops, the listing will stop at the end of the list
   3872  * or after 'n' entries - whichever comes first.
   3873  */
   3874 void
   3875 pv_list(pa, n)
   3876 	vm_offset_t pa;
   3877 	int n;
   3878 {
   3879 	int  idx;
   3880 	vm_offset_t va;
   3881 	pv_t *pv;
   3882 	c_tmgr_t *c_tbl;
   3883 	pmap_t pmap;
   3884 
   3885 	pv = pa2pv(pa);
   3886 	idx = pv->pv_idx;
   3887 
   3888 	for (;idx != PVE_EOL && n > 0;
   3889 		 idx=pvebase[idx].pve_next, n--) {
   3890 
   3891 		va = pmap_get_pteinfo(idx, &pmap, &c_tbl);
   3892 		printf("idx %d, pmap 0x%x, va 0x%x, c_tbl %x\n",
   3893 			idx, (u_int) pmap, (u_int) va, (u_int) c_tbl);
   3894 	}
   3895 }
   3896 #endif	/* PMAP_DEBUG */
   3897 
   3898 #ifdef NOT_YET
   3899 /* and maybe not ever */
   3900 /************************** LOW-LEVEL ROUTINES **************************
   3901  * These routines will eventualy be re-written into assembly and placed *
   3902  * in locore.s.  They are here now as stubs so that the pmap module can *
   3903  * be linked as a standalone user program for testing.                  *
   3904  ************************************************************************/
   3905 /* flush_atc_crp			INTERNAL
   3906  **
   3907  * Flush all page descriptors derived from the given CPU Root Pointer
   3908  * (CRP), or 'A' table as it is known here, from the 68851's automatic
   3909  * cache.
   3910  */
   3911 void
   3912 flush_atc_crp(a_tbl)
   3913 {
   3914 	mmu_long_rp_t rp;
   3915 
   3916 	/* Create a temporary root table pointer that points to the
   3917 	 * given A table.
   3918 	 */
   3919 	rp.attr.raw = ~MMU_LONG_RP_LU;
   3920 	rp.addr.raw = (unsigned int) a_tbl;
   3921 
   3922 	mmu_pflushr(&rp);
   3923 	/* mmu_pflushr:
   3924 	 * 	movel   sp(4)@,a0
   3925 	 * 	pflushr a0@
   3926 	 *	rts
   3927 	 */
   3928 }
   3929 #endif /* NOT_YET */
   3930