Home | History | Annotate | Line # | Download | only in pmap
pmap.c revision 1.7
      1 /*	$NetBSD: pmap.c,v 1.7 2014/12/24 04:03:02 nonaka Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1998, 2001 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center and by Chris G. Demetriou.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     30  * POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 /*
     34  * Copyright (c) 1992, 1993
     35  *	The Regents of the University of California.  All rights reserved.
     36  *
     37  * This code is derived from software contributed to Berkeley by
     38  * the Systems Programming Group of the University of Utah Computer
     39  * Science Department and Ralph Campbell.
     40  *
     41  * Redistribution and use in source and binary forms, with or without
     42  * modification, are permitted provided that the following conditions
     43  * are met:
     44  * 1. Redistributions of source code must retain the above copyright
     45  *    notice, this list of conditions and the following disclaimer.
     46  * 2. Redistributions in binary form must reproduce the above copyright
     47  *    notice, this list of conditions and the following disclaimer in the
     48  *    documentation and/or other materials provided with the distribution.
     49  * 3. Neither the name of the University nor the names of its contributors
     50  *    may be used to endorse or promote products derived from this software
     51  *    without specific prior written permission.
     52  *
     53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     63  * SUCH DAMAGE.
     64  *
     65  *	@(#)pmap.c	8.4 (Berkeley) 1/26/94
     66  */
     67 
     68 #include <sys/cdefs.h>
     69 
     70 __KERNEL_RCSID(0, "$NetBSD: pmap.c,v 1.7 2014/12/24 04:03:02 nonaka Exp $");
     71 
     72 /*
     73  *	Manages physical address maps.
     74  *
     75  *	In addition to hardware address maps, this
     76  *	module is called upon to provide software-use-only
     77  *	maps which may or may not be stored in the same
     78  *	form as hardware maps.  These pseudo-maps are
     79  *	used to store intermediate results from copy
     80  *	operations to and from address spaces.
     81  *
     82  *	Since the information managed by this module is
     83  *	also stored by the logical address mapping module,
     84  *	this module may throw away valid virtual-to-physical
     85  *	mappings at almost any time.  However, invalidations
     86  *	of virtual-to-physical mappings must be done as
     87  *	requested.
     88  *
     89  *	In order to cope with hardware architectures which
     90  *	make virtual-to-physical map invalidates expensive,
     91  *	this module may delay invalidate or reduced protection
     92  *	operations until such time as they are actually
     93  *	necessary.  This module is given full information as
     94  *	to which processors are currently using which maps,
     95  *	and to when physical maps must be made correct.
     96  */
     97 
     98 #include "opt_modular.h"
     99 #include "opt_multiprocessor.h"
    100 #include "opt_sysv.h"
    101 
    102 #define __PMAP_PRIVATE
    103 
    104 #include <sys/param.h>
    105 #include <sys/systm.h>
    106 #include <sys/proc.h>
    107 #include <sys/buf.h>
    108 #include <sys/pool.h>
    109 #include <sys/atomic.h>
    110 #include <sys/mutex.h>
    111 #include <sys/atomic.h>
    112 #ifdef SYSVSHM
    113 #include <sys/shm.h>
    114 #endif
    115 #include <sys/socketvar.h>	/* XXX: for sock_loan_thresh */
    116 
    117 #include <uvm/uvm.h>
    118 
    119 #define	PMAP_COUNT(name)	(pmap_evcnt_##name.ev_count++ + 0)
    120 #define PMAP_COUNTER(name, desc) \
    121 static struct evcnt pmap_evcnt_##name = \
    122 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "pmap", desc); \
    123 EVCNT_ATTACH_STATIC(pmap_evcnt_##name)
    124 
    125 PMAP_COUNTER(remove_kernel_calls, "remove kernel calls");
    126 PMAP_COUNTER(remove_kernel_pages, "kernel pages unmapped");
    127 PMAP_COUNTER(remove_user_calls, "remove user calls");
    128 PMAP_COUNTER(remove_user_pages, "user pages unmapped");
    129 PMAP_COUNTER(remove_flushes, "remove cache flushes");
    130 PMAP_COUNTER(remove_tlb_ops, "remove tlb ops");
    131 PMAP_COUNTER(remove_pvfirst, "remove pv first");
    132 PMAP_COUNTER(remove_pvsearch, "remove pv search");
    133 
    134 PMAP_COUNTER(prefer_requests, "prefer requests");
    135 PMAP_COUNTER(prefer_adjustments, "prefer adjustments");
    136 
    137 PMAP_COUNTER(idlezeroed_pages, "pages idle zeroed");
    138 PMAP_COUNTER(zeroed_pages, "pages zeroed");
    139 PMAP_COUNTER(copied_pages, "pages copied");
    140 
    141 PMAP_COUNTER(kenter_pa, "kernel fast mapped pages");
    142 PMAP_COUNTER(kenter_pa_bad, "kernel fast mapped pages (bad color)");
    143 PMAP_COUNTER(kenter_pa_unmanaged, "kernel fast mapped unmanaged pages");
    144 PMAP_COUNTER(kremove_pages, "kernel fast unmapped pages");
    145 
    146 PMAP_COUNTER(page_cache_evictions, "pages changed to uncacheable");
    147 PMAP_COUNTER(page_cache_restorations, "pages changed to cacheable");
    148 
    149 PMAP_COUNTER(kernel_mappings_bad, "kernel pages mapped (bad color)");
    150 PMAP_COUNTER(user_mappings_bad, "user pages mapped (bad color)");
    151 PMAP_COUNTER(kernel_mappings, "kernel pages mapped");
    152 PMAP_COUNTER(user_mappings, "user pages mapped");
    153 PMAP_COUNTER(user_mappings_changed, "user mapping changed");
    154 PMAP_COUNTER(kernel_mappings_changed, "kernel mapping changed");
    155 PMAP_COUNTER(uncached_mappings, "uncached pages mapped");
    156 PMAP_COUNTER(unmanaged_mappings, "unmanaged pages mapped");
    157 PMAP_COUNTER(managed_mappings, "managed pages mapped");
    158 PMAP_COUNTER(mappings, "pages mapped");
    159 PMAP_COUNTER(remappings, "pages remapped");
    160 PMAP_COUNTER(unmappings, "pages unmapped");
    161 PMAP_COUNTER(primary_mappings, "page initial mappings");
    162 PMAP_COUNTER(primary_unmappings, "page final unmappings");
    163 PMAP_COUNTER(tlb_hit, "page mapping");
    164 
    165 PMAP_COUNTER(exec_mappings, "exec pages mapped");
    166 PMAP_COUNTER(exec_synced_mappings, "exec pages synced");
    167 PMAP_COUNTER(exec_synced_remove, "exec pages synced (PR)");
    168 PMAP_COUNTER(exec_synced_clear_modify, "exec pages synced (CM)");
    169 PMAP_COUNTER(exec_synced_page_protect, "exec pages synced (PP)");
    170 PMAP_COUNTER(exec_synced_protect, "exec pages synced (P)");
    171 PMAP_COUNTER(exec_uncached_page_protect, "exec pages uncached (PP)");
    172 PMAP_COUNTER(exec_uncached_clear_modify, "exec pages uncached (CM)");
    173 PMAP_COUNTER(exec_uncached_zero_page, "exec pages uncached (ZP)");
    174 PMAP_COUNTER(exec_uncached_copy_page, "exec pages uncached (CP)");
    175 PMAP_COUNTER(exec_uncached_remove, "exec pages uncached (PR)");
    176 
    177 PMAP_COUNTER(create, "creates");
    178 PMAP_COUNTER(reference, "references");
    179 PMAP_COUNTER(dereference, "dereferences");
    180 PMAP_COUNTER(destroy, "destroyed");
    181 PMAP_COUNTER(activate, "activations");
    182 PMAP_COUNTER(deactivate, "deactivations");
    183 PMAP_COUNTER(update, "updates");
    184 #ifdef MULTIPROCESSOR
    185 PMAP_COUNTER(shootdown_ipis, "shootdown IPIs");
    186 #endif
    187 PMAP_COUNTER(unwire, "unwires");
    188 PMAP_COUNTER(copy, "copies");
    189 PMAP_COUNTER(clear_modify, "clear_modifies");
    190 PMAP_COUNTER(protect, "protects");
    191 PMAP_COUNTER(page_protect, "page_protects");
    192 
    193 #define PMAP_ASID_RESERVED 0
    194 CTASSERT(PMAP_ASID_RESERVED == 0);
    195 
    196 /*
    197  * Initialize the kernel pmap.
    198  */
    199 #ifdef MULTIPROCESSOR
    200 #define	PMAP_SIZE	offsetof(struct pmap, pm_pai[MAXCPUS])
    201 #else
    202 #define	PMAP_SIZE	sizeof(struct pmap)
    203 kmutex_t pmap_pvlist_mutex __aligned(COHERENCY_UNIT);
    204 #endif
    205 
    206 struct pmap_kernel kernel_pmap_store = {
    207 	.kernel_pmap = {
    208 		.pm_count = 1,
    209 		.pm_segtab = PMAP_INVALID_SEGTAB_ADDRESS,
    210 		.pm_minaddr = VM_MIN_KERNEL_ADDRESS,
    211 		.pm_maxaddr = VM_MAX_KERNEL_ADDRESS,
    212 	},
    213 };
    214 
    215 struct pmap * const kernel_pmap_ptr = &kernel_pmap_store.kernel_pmap;
    216 
    217 struct pmap_limits pmap_limits;
    218 
    219 #ifdef UVMHIST
    220 static struct kern_history_ent pmapexechistbuf[10000];
    221 static struct kern_history_ent pmaphistbuf[10000];
    222 #endif
    223 
    224 /*
    225  * The pools from which pmap structures and sub-structures are allocated.
    226  */
    227 struct pool pmap_pmap_pool;
    228 struct pool pmap_pv_pool;
    229 
    230 #ifndef PMAP_PV_LOWAT
    231 #define	PMAP_PV_LOWAT	16
    232 #endif
    233 int		pmap_pv_lowat = PMAP_PV_LOWAT;
    234 
    235 bool		pmap_initialized = false;
    236 #define	PMAP_PAGE_COLOROK_P(a, b) \
    237 		((((int)(a) ^ (int)(b)) & pmap_page_colormask) == 0)
    238 u_int		pmap_page_colormask;
    239 
    240 #define PAGE_IS_MANAGED(pa)	\
    241 	(pmap_initialized == true && vm_physseg_find(atop(pa), NULL) != -1)
    242 
    243 #define PMAP_IS_ACTIVE(pm)						\
    244 	((pm) == pmap_kernel() || 					\
    245 	 (pm) == curlwp->l_proc->p_vmspace->vm_map.pmap)
    246 
    247 /* Forward function declarations */
    248 void pmap_remove_pv(pmap_t, vaddr_t, struct vm_page *, bool);
    249 void pmap_enter_pv(pmap_t, vaddr_t, struct vm_page *, u_int *);
    250 
    251 /*
    252  * PV table management functions.
    253  */
    254 void	*pmap_pv_page_alloc(struct pool *, int);
    255 void	pmap_pv_page_free(struct pool *, void *);
    256 
    257 struct pool_allocator pmap_pv_page_allocator = {
    258 	pmap_pv_page_alloc, pmap_pv_page_free, 0,
    259 };
    260 
    261 #define	pmap_pv_alloc()		pool_get(&pmap_pv_pool, PR_NOWAIT)
    262 #define	pmap_pv_free(pv)	pool_put(&pmap_pv_pool, (pv))
    263 
    264 /*
    265  * Misc. functions.
    266  */
    267 
    268 bool
    269 pmap_page_clear_attributes(struct vm_page_md *mdpg, u_int clear_attributes)
    270 {
    271 	volatile u_int * const attrp = &mdpg->mdpg_attrs;
    272 #ifdef MULTIPROCESSOR
    273 	for (;;) {
    274 		u_int old_attr = *attrp;
    275 		if ((old_attr & clear_attributes) == 0)
    276 			return false;
    277 		u_int new_attr = old_attr & ~clear_attributes;
    278 		if (old_attr == atomic_cas_uint(attrp, old_attr, new_attr))
    279 			return true;
    280 	}
    281 #else
    282 	u_int old_attr = *attrp;
    283 	if ((old_attr & clear_attributes) == 0)
    284 		return false;
    285 	*attrp &= ~clear_attributes;
    286 	return true;
    287 #endif
    288 }
    289 
    290 void
    291 pmap_page_set_attributes(struct vm_page_md *mdpg, u_int set_attributes)
    292 {
    293 #ifdef MULTIPROCESSOR
    294 	atomic_or_uint(&mdpg->mdpg_attrs, set_attributes);
    295 #else
    296 	mdpg->mdpg_attrs |= set_attributes;
    297 #endif
    298 }
    299 
    300 static void
    301 pmap_page_syncicache(struct vm_page *pg)
    302 {
    303 #ifndef MULTIPROCESSOR
    304 	struct pmap * const curpmap = curcpu()->ci_curpm;
    305 #endif
    306 	struct vm_page_md * const mdpg = VM_PAGE_TO_MD(pg);
    307 	pv_entry_t pv = &mdpg->mdpg_first;
    308 	kcpuset_t *onproc;
    309 #ifdef MULTIPROCESSOR
    310 	kcpuset_create(&onproc, true);
    311 #else
    312 	onproc = NULL;
    313 #endif
    314 	(void)VM_PAGEMD_PVLIST_LOCK(mdpg, false);
    315 
    316 	if (pv->pv_pmap != NULL) {
    317 		for (; pv != NULL; pv = pv->pv_next) {
    318 #ifdef MULTIPROCESSOR
    319 			kcpuset_merge(onproc, pv->pv_pmap->pm_onproc);
    320 			if (kcpuset_match(onproc, kcpuset_running)) {
    321 				break;
    322 			}
    323 #else
    324 			if (pv->pv_pmap == curpmap) {
    325 				onproc = curcpu()->ci_data.cpu_kcpuset;
    326 				break;
    327 			}
    328 #endif
    329 		}
    330 	}
    331 	VM_PAGEMD_PVLIST_UNLOCK(mdpg);
    332 	kpreempt_disable();
    333 	pmap_md_page_syncicache(pg, onproc);
    334 #ifdef MULTIPROCESSOR
    335 	kcpuset_destroy(onproc);
    336 #endif
    337 	kpreempt_enable();
    338 }
    339 
    340 /*
    341  * Define the initial bounds of the kernel virtual address space.
    342  */
    343 void
    344 pmap_virtual_space(vaddr_t *vstartp, vaddr_t *vendp)
    345 {
    346 
    347 	*vstartp = VM_MIN_KERNEL_ADDRESS;
    348 	*vendp = VM_MAX_KERNEL_ADDRESS;
    349 }
    350 
    351 vaddr_t
    352 pmap_growkernel(vaddr_t maxkvaddr)
    353 {
    354 	vaddr_t virtual_end = pmap_limits.virtual_end;
    355 	maxkvaddr = pmap_round_seg(maxkvaddr) - 1;
    356 
    357 	/*
    358 	 * Reserve PTEs for the new KVA space.
    359 	 */
    360 	for (; virtual_end < maxkvaddr; virtual_end += NBSEG) {
    361 		pmap_pte_reserve(pmap_kernel(), virtual_end, 0);
    362 	}
    363 
    364 	/*
    365 	 * Don't exceed VM_MAX_KERNEL_ADDRESS!
    366 	 */
    367 	if (virtual_end == 0 || virtual_end > VM_MAX_KERNEL_ADDRESS)
    368 		virtual_end = VM_MAX_KERNEL_ADDRESS;
    369 
    370 	/*
    371 	 * Update new end.
    372 	 */
    373 	pmap_limits.virtual_end = virtual_end;
    374 	return virtual_end;
    375 }
    376 
    377 /*
    378  * Bootstrap memory allocator (alternative to vm_bootstrap_steal_memory()).
    379  * This function allows for early dynamic memory allocation until the virtual
    380  * memory system has been bootstrapped.  After that point, either kmem_alloc
    381  * or malloc should be used.  This function works by stealing pages from the
    382  * (to be) managed page pool, then implicitly mapping the pages (by using
    383  * their k0seg addresses) and zeroing them.
    384  *
    385  * It may be used once the physical memory segments have been pre-loaded
    386  * into the vm_physmem[] array.  Early memory allocation MUST use this
    387  * interface!  This cannot be used after vm_page_startup(), and will
    388  * generate a panic if tried.
    389  *
    390  * Note that this memory will never be freed, and in essence it is wired
    391  * down.
    392  *
    393  * We must adjust *vstartp and/or *vendp iff we use address space
    394  * from the kernel virtual address range defined by pmap_virtual_space().
    395  */
    396 vaddr_t
    397 pmap_steal_memory(vsize_t size, vaddr_t *vstartp, vaddr_t *vendp)
    398 {
    399 	u_int npgs;
    400 	paddr_t pa;
    401 	vaddr_t va;
    402 
    403 	size = round_page(size);
    404 	npgs = atop(size);
    405 
    406 	for (u_int bank = 0; bank < vm_nphysseg; bank++) {
    407 		struct vm_physseg * const seg = VM_PHYSMEM_PTR(bank);
    408 		if (uvm.page_init_done == true)
    409 			panic("pmap_steal_memory: called _after_ bootstrap");
    410 
    411 		if (seg->avail_start != seg->start ||
    412 		    seg->avail_start >= seg->avail_end)
    413 			continue;
    414 
    415 		if ((seg->avail_end - seg->avail_start) < npgs)
    416 			continue;
    417 
    418 		/*
    419 		 * There are enough pages here; steal them!
    420 		 */
    421 		pa = ptoa(seg->avail_start);
    422 		seg->avail_start += npgs;
    423 		seg->start += npgs;
    424 
    425 		/*
    426 		 * Have we used up this segment?
    427 		 */
    428 		if (seg->avail_start == seg->end) {
    429 			if (vm_nphysseg == 1)
    430 				panic("pmap_steal_memory: out of memory!");
    431 
    432 			/* Remove this segment from the list. */
    433 			vm_nphysseg--;
    434 			if (bank < vm_nphysseg)
    435 				memmove(seg, seg+1,
    436 				    sizeof(*seg) * (vm_nphysseg - bank));
    437 		}
    438 
    439 		va = pmap_md_map_poolpage(pa, size);
    440 		memset((void *)va, 0, size);
    441 		return va;
    442 	}
    443 
    444 	/*
    445 	 * If we got here, there was no memory left.
    446 	 */
    447 	panic("pmap_steal_memory: no memory to steal");
    448 }
    449 
    450 /*
    451  *	Initialize the pmap module.
    452  *	Called by vm_init, to initialize any structures that the pmap
    453  *	system needs to map virtual memory.
    454  */
    455 void
    456 pmap_init(void)
    457 {
    458 	UVMHIST_INIT_STATIC(pmapexechist, pmapexechistbuf);
    459 	UVMHIST_INIT_STATIC(pmaphist, pmaphistbuf);
    460 
    461 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
    462 
    463 	/*
    464 	 * Initialize the segtab lock.
    465 	 */
    466 	mutex_init(&pmap_segtab_lock, MUTEX_DEFAULT, IPL_HIGH);
    467 
    468 	/*
    469 	 * Set a low water mark on the pv_entry pool, so that we are
    470 	 * more likely to have these around even in extreme memory
    471 	 * starvation.
    472 	 */
    473 	pool_setlowat(&pmap_pv_pool, pmap_pv_lowat);
    474 
    475 	pmap_md_init();
    476 
    477 	/*
    478 	 * Now it is safe to enable pv entry recording.
    479 	 */
    480 	pmap_initialized = true;
    481 }
    482 
    483 /*
    484  *	Create and return a physical map.
    485  *
    486  *	If the size specified for the map
    487  *	is zero, the map is an actual physical
    488  *	map, and may be referenced by the
    489  *	hardware.
    490  *
    491  *	If the size specified is non-zero,
    492  *	the map will be used in software only, and
    493  *	is bounded by that size.
    494  */
    495 pmap_t
    496 pmap_create(void)
    497 {
    498 	pmap_t pmap;
    499 
    500 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
    501 	PMAP_COUNT(create);
    502 
    503 	pmap = pool_get(&pmap_pmap_pool, PR_WAITOK);
    504 	memset(pmap, 0, PMAP_SIZE);
    505 
    506 	KASSERT(pmap->pm_pai[0].pai_link.le_prev == NULL);
    507 
    508 	pmap->pm_count = 1;
    509 	pmap->pm_minaddr = VM_MIN_ADDRESS;
    510 	pmap->pm_maxaddr = VM_MAXUSER_ADDRESS;
    511 
    512 	pmap_segtab_init(pmap);
    513 
    514 #ifdef MULTIPROCESSOR
    515 	kcpuset_create(&pmap->pm_active, true);
    516 	kcpuset_create(&pmap->pm_onproc, true);
    517 #endif
    518 
    519 	UVMHIST_LOG(pmaphist, "<- pmap %p", pmap,0,0,0);
    520 	return pmap;
    521 }
    522 
    523 /*
    524  *	Retire the given physical map from service.
    525  *	Should only be called if the map contains
    526  *	no valid mappings.
    527  */
    528 void
    529 pmap_destroy(pmap_t pmap)
    530 {
    531 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
    532 	UVMHIST_LOG(pmaphist, "(pmap=%p)", pmap, 0,0,0);
    533 
    534 	if (atomic_dec_uint_nv(&pmap->pm_count) > 0) {
    535 		PMAP_COUNT(dereference);
    536 		return;
    537 	}
    538 
    539 	KASSERT(pmap->pm_count == 0);
    540 	PMAP_COUNT(destroy);
    541 	kpreempt_disable();
    542 	pmap_tlb_asid_release_all(pmap);
    543 	pmap_segtab_destroy(pmap, NULL, 0);
    544 
    545 #ifdef MULTIPROCESSOR
    546 	kcpuset_destroy(pmap->pm_active);
    547 	kcpuset_destroy(pmap->pm_onproc);
    548 #endif
    549 
    550 	pool_put(&pmap_pmap_pool, pmap);
    551 	kpreempt_enable();
    552 
    553 	UVMHIST_LOG(pmaphist, "<- done", 0,0,0,0);
    554 }
    555 
    556 /*
    557  *	Add a reference to the specified pmap.
    558  */
    559 void
    560 pmap_reference(pmap_t pmap)
    561 {
    562 
    563 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
    564 	UVMHIST_LOG(pmaphist, "(pmap=%p)", pmap, 0,0,0);
    565 	PMAP_COUNT(reference);
    566 
    567 	if (pmap != NULL) {
    568 		atomic_inc_uint(&pmap->pm_count);
    569 	}
    570 
    571 	UVMHIST_LOG(pmaphist, "<- done", 0,0,0,0);
    572 }
    573 
    574 /*
    575  *	Make a new pmap (vmspace) active for the given process.
    576  */
    577 void
    578 pmap_activate(struct lwp *l)
    579 {
    580 	pmap_t pmap = l->l_proc->p_vmspace->vm_map.pmap;
    581 
    582 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
    583 	UVMHIST_LOG(pmaphist, "(l=%p (pmap=%p))", l, pmap, 0,0);
    584 	PMAP_COUNT(activate);
    585 
    586 	kpreempt_disable();
    587 	pmap_tlb_asid_acquire(pmap, l);
    588 	if (l == curlwp) {
    589 		pmap_segtab_activate(pmap, l);
    590 	}
    591 	kpreempt_enable();
    592 
    593 	UVMHIST_LOG(pmaphist, "<- done", 0,0,0,0);
    594 }
    595 
    596 /*
    597  *	Make a previously active pmap (vmspace) inactive.
    598  */
    599 void
    600 pmap_deactivate(struct lwp *l)
    601 {
    602 	pmap_t pmap = l->l_proc->p_vmspace->vm_map.pmap;
    603 
    604 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
    605 	UVMHIST_LOG(pmaphist, "(l=%p (pmap=%p))", l, pmap, 0,0);
    606 	PMAP_COUNT(deactivate);
    607 
    608 	kpreempt_disable();
    609 	curcpu()->ci_pmap_user_segtab = PMAP_INVALID_SEGTAB_ADDRESS;
    610 	pmap_tlb_asid_deactivate(pmap);
    611 	kpreempt_enable();
    612 
    613 	UVMHIST_LOG(pmaphist, "<- done", 0,0,0,0);
    614 }
    615 
    616 void
    617 pmap_update(struct pmap *pmap)
    618 {
    619 
    620 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
    621 	UVMHIST_LOG(pmaphist, "(pmap=%p)", pmap, 0,0,0);
    622 	PMAP_COUNT(update);
    623 
    624 	kpreempt_disable();
    625 #if defined(MULTIPROCESSOR) && defined(PMAP_NEED_TLB_SHOOTDOWN)
    626 	u_int pending = atomic_swap_uint(&pmap->pm_shootdown_pending, 0);
    627 	if (pending && pmap_tlb_shootdown_bystanders(pmap))
    628 		PMAP_COUNT(shootdown_ipis);
    629 #endif
    630 #ifdef DEBUG
    631 	pmap_tlb_check(pmap, pmap_md_tlb_check_entry);
    632 #endif /* DEBUG */
    633 
    634 	/*
    635 	 * If pmap_remove_all was called, we deactivated ourselves and nuked
    636 	 * our ASID.  Now we have to reactivate ourselves.
    637 	 */
    638 	if (__predict_false(pmap->pm_flags & PMAP_DEFERRED_ACTIVATE)) {
    639 		pmap->pm_flags ^= PMAP_DEFERRED_ACTIVATE;
    640 		pmap_tlb_asid_acquire(pmap, curlwp);
    641 		pmap_segtab_activate(pmap, curlwp);
    642 	}
    643 	kpreempt_enable();
    644 
    645 	UVMHIST_LOG(pmaphist, "<- done", 0,0,0,0);
    646 }
    647 
    648 /*
    649  *	Remove the given range of addresses from the specified map.
    650  *
    651  *	It is assumed that the start and end are properly
    652  *	rounded to the page size.
    653  */
    654 
    655 static bool
    656 pmap_pte_remove(pmap_t pmap, vaddr_t sva, vaddr_t eva, pt_entry_t *ptep,
    657 	uintptr_t flags)
    658 {
    659 	const pt_entry_t npte = flags;
    660 	const bool is_kernel_pmap_p = (pmap == pmap_kernel());
    661 
    662 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
    663 	UVMHIST_LOG(pmaphist, "(pmap=%p %sva=%"PRIxVADDR"..%"PRIxVADDR,
    664 	    pmap, (is_kernel_pmap_p ? "(kernel) " : ""), sva, eva);
    665 	UVMHIST_LOG(pmaphist, "ptep=%p, flags(npte)=%#"PRIxPTR")",
    666 	    ptep, flags, 0, 0);
    667 
    668 	KASSERT(kpreempt_disabled());
    669 
    670 	for (; sva < eva; sva += NBPG, ptep++) {
    671 		pt_entry_t pt_entry = *ptep;
    672 		if (!pte_valid_p(pt_entry))
    673 			continue;
    674 		if (is_kernel_pmap_p)
    675 			PMAP_COUNT(remove_kernel_calls);
    676 		else
    677 			PMAP_COUNT(remove_user_pages);
    678 		if (pte_wired_p(pt_entry))
    679 			pmap->pm_stats.wired_count--;
    680 		pmap->pm_stats.resident_count--;
    681 		struct vm_page *pg = PHYS_TO_VM_PAGE(pte_to_paddr(pt_entry));
    682 		if (__predict_true(pg != NULL)) {
    683 			pmap_remove_pv(pmap, sva, pg,
    684 			   pte_modified_p(pt_entry));
    685 		}
    686 		*ptep = npte;
    687 		/*
    688 		 * Flush the TLB for the given address.
    689 		 */
    690 		pmap_tlb_invalidate_addr(pmap, sva);
    691 	}
    692 	return false;
    693 }
    694 
    695 void
    696 pmap_remove(pmap_t pmap, vaddr_t sva, vaddr_t eva)
    697 {
    698 	const bool is_kernel_pmap_p = (pmap == pmap_kernel());
    699 	const pt_entry_t npte = pte_nv_entry(is_kernel_pmap_p);
    700 
    701 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
    702 	UVMHIST_LOG(pmaphist, "(pmap=%p, va=%#"PRIxVADDR"..%#"PRIxVADDR")",
    703 	    pmap, sva, eva, 0);
    704 
    705 	if (is_kernel_pmap_p)
    706 		PMAP_COUNT(remove_kernel_calls);
    707 	else
    708 		PMAP_COUNT(remove_user_calls);
    709 #ifdef PARANOIADIAG
    710 	if (sva < pm->pm_minaddr || eva > pm->pm_maxaddr)
    711 		panic("%s: va range %#"PRIxVADDR"-%#"PRIxVADDR" not in range",
    712 		    __func__, sva, eva - 1);
    713 	if (PMAP_IS_ACTIVE(pmap)) {
    714 		struct pmap_asid_info * const pai = PMAP_PAI(pmap, curcpu());
    715 		uint32_t asid = tlb_get_asid();
    716 		if (asid != pai->pai_asid) {
    717 			panic("%s: inconsistency for active TLB flush"
    718 			    ": %d <-> %d", __func__, asid, pai->pai_asid);
    719 		}
    720 	}
    721 #endif
    722 	kpreempt_disable();
    723 	pmap_pte_process(pmap, sva, eva, pmap_pte_remove, npte);
    724 	kpreempt_enable();
    725 
    726 	UVMHIST_LOG(pmaphist, "<- done", 0,0,0,0);
    727 }
    728 
    729 /*
    730  *	pmap_page_protect:
    731  *
    732  *	Lower the permission for all mappings to a given page.
    733  */
    734 void
    735 pmap_page_protect(struct vm_page *pg, vm_prot_t prot)
    736 {
    737 	struct vm_page_md * const mdpg = VM_PAGE_TO_MD(pg);
    738 	pv_entry_t pv;
    739 	vaddr_t va;
    740 
    741 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
    742 	UVMHIST_LOG(pmaphist, "(pg=%p (pa %#"PRIxPADDR") prot=%#x)",
    743 	    pg, VM_PAGE_TO_PHYS(pg), prot, 0);
    744 	PMAP_COUNT(page_protect);
    745 
    746 	switch (prot) {
    747 	case VM_PROT_READ|VM_PROT_WRITE:
    748 	case VM_PROT_ALL:
    749 		break;
    750 
    751 	/* copy_on_write */
    752 	case VM_PROT_READ:
    753 	case VM_PROT_READ|VM_PROT_EXECUTE:
    754 		(void)VM_PAGEMD_PVLIST_LOCK(mdpg, false);
    755 		pv = &mdpg->mdpg_first;
    756 		/*
    757 		 * Loop over all current mappings setting/clearing as appropriate.
    758 		 */
    759 		if (pv->pv_pmap != NULL) {
    760 			while (pv != NULL) {
    761 				const pmap_t pmap = pv->pv_pmap;
    762 				const uint16_t gen = VM_PAGEMD_PVLIST_GEN(mdpg);
    763 				va = pv->pv_va;
    764 				VM_PAGEMD_PVLIST_UNLOCK(mdpg);
    765 				pmap_protect(pmap, va, va + PAGE_SIZE, prot);
    766 				KASSERT(pv->pv_pmap == pmap);
    767 				pmap_update(pmap);
    768 				if (gen != VM_PAGEMD_PVLIST_LOCK(mdpg, false)) {
    769 					pv = &mdpg->mdpg_first;
    770 				} else {
    771 					pv = pv->pv_next;
    772 				}
    773 			}
    774 		}
    775 		VM_PAGEMD_PVLIST_UNLOCK(mdpg);
    776 		break;
    777 
    778 	/* remove_all */
    779 	default:
    780 		/*
    781 		 * Do this first so that for each unmapping, pmap_remove_pv
    782 		 * won't try to sync the icache.
    783 		 */
    784 		if (pmap_page_clear_attributes(mdpg, VM_PAGEMD_EXECPAGE)) {
    785 			UVMHIST_LOG(pmapexechist, "pg %p (pa %#"PRIxPADDR
    786 			    "): execpage cleared", pg, VM_PAGE_TO_PHYS(pg),0,0);
    787 			PMAP_COUNT(exec_uncached_page_protect);
    788 		}
    789 		(void)VM_PAGEMD_PVLIST_LOCK(mdpg, false);
    790 		pv = &mdpg->mdpg_first;
    791 		while (pv->pv_pmap != NULL) {
    792 			const pmap_t pmap = pv->pv_pmap;
    793 			va = pv->pv_va;
    794 			VM_PAGEMD_PVLIST_UNLOCK(mdpg);
    795 			pmap_remove(pmap, va, va + PAGE_SIZE);
    796 			pmap_update(pmap);
    797 			(void)VM_PAGEMD_PVLIST_LOCK(mdpg, false);
    798 		}
    799 		VM_PAGEMD_PVLIST_UNLOCK(mdpg);
    800 	}
    801 
    802 	UVMHIST_LOG(pmaphist, "<- done", 0,0,0,0);
    803 }
    804 
    805 static bool
    806 pmap_pte_protect(pmap_t pmap, vaddr_t sva, vaddr_t eva, pt_entry_t *ptep,
    807 	uintptr_t flags)
    808 {
    809 	const vm_prot_t prot = (flags & VM_PROT_ALL);
    810 
    811 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
    812 	UVMHIST_LOG(pmaphist, "(pmap=%p %sva=%"PRIxVADDR"..%"PRIxVADDR,
    813 	    pmap, (pmap == pmap_kernel() ? "(kernel) " : ""), sva, eva);
    814 	UVMHIST_LOG(pmaphist, "ptep=%p, flags(npte)=%#"PRIxPTR")",
    815 	    ptep, flags, 0, 0);
    816 
    817 	KASSERT(kpreempt_disabled());
    818 	/*
    819 	 * Change protection on every valid mapping within this segment.
    820 	 */
    821 	for (; sva < eva; sva += NBPG, ptep++) {
    822 		pt_entry_t pt_entry = *ptep;
    823 		if (!pte_valid_p(pt_entry))
    824 			continue;
    825 		struct vm_page * const pg =
    826 		    PHYS_TO_VM_PAGE(pte_to_paddr(pt_entry));
    827 		if (pg != NULL && pte_modified_p(pt_entry)) {
    828 			struct vm_page_md * const mdpg = VM_PAGE_TO_MD(pg);
    829 			pmap_md_vca_clean(pg, sva, PMAP_WBINV);
    830 			if (VM_PAGEMD_EXECPAGE_P(mdpg)) {
    831 				KASSERT(mdpg->mdpg_first.pv_pmap != NULL);
    832 				if (pte_cached_p(pt_entry)) {
    833 					UVMHIST_LOG(pmapexechist,
    834 					    "pg %p (pa %#"PRIxPADDR"): %s",
    835 					    pg, VM_PAGE_TO_PHYS(pg),
    836 					    "syncicached performed", 0);
    837 					pmap_page_syncicache(pg);
    838 					PMAP_COUNT(exec_synced_protect);
    839 				}
    840 			}
    841 		}
    842 		pt_entry = pte_prot_downgrade(pt_entry, prot);
    843 		if (*ptep != pt_entry) {
    844 			*ptep = pt_entry;
    845 			/*
    846 			 * Update the TLB if needed.
    847 			 */
    848 			pmap_tlb_update_addr(pmap, sva, pt_entry,
    849 			    PMAP_TLB_NEED_IPI);
    850 		}
    851 	}
    852 	return false;
    853 }
    854 
    855 /*
    856  *	Set the physical protection on the
    857  *	specified range of this map as requested.
    858  */
    859 void
    860 pmap_protect(pmap_t pmap, vaddr_t sva, vaddr_t eva, vm_prot_t prot)
    861 {
    862 
    863 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
    864 	UVMHIST_LOG(pmaphist,
    865 	    "  pmap=%p, va=%#"PRIxVADDR"..%#"PRIxVADDR" port=%#x)",
    866 	    pmap, sva, eva, prot);
    867 	PMAP_COUNT(protect);
    868 
    869 	if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
    870 		pmap_remove(pmap, sva, eva);
    871 		UVMHIST_LOG(pmaphist, "<- done", 0,0,0,0);
    872 		return;
    873 	}
    874 
    875 #ifdef PARANOIADIAG
    876 	if (sva < pm->pm_minaddr || eva > pm->pm_maxaddr)
    877 		panic("%s: va range %#"PRIxVADDR"-%#"PRIxVADDR" not in range",
    878 		    __func__, sva, eva - 1);
    879 	if (PMAP_IS_ACTIVE(pmap)) {
    880 		struct pmap_asid_info * const pai = PMAP_PAI(pmap, curcpu());
    881 		uint32_t asid = tlb_get_asid();
    882 		if (asid != pai->pai_asid) {
    883 			panic("%s: inconsistency for active TLB update"
    884 			    ": %d <-> %d", __func__, asid, pai->pai_asid);
    885 		}
    886 	}
    887 #endif
    888 
    889 	/*
    890 	 * Change protection on every valid mapping within this segment.
    891 	 */
    892 	kpreempt_disable();
    893 	pmap_pte_process(pmap, sva, eva, pmap_pte_protect, prot);
    894 	kpreempt_enable();
    895 
    896 	UVMHIST_LOG(pmaphist, "<- done", 0,0,0,0);
    897 }
    898 
    899 #if defined(__PMAP_VIRTUAL_CACHE_ALIASES)
    900 /*
    901  *	pmap_page_cache:
    902  *
    903  *	Change all mappings of a managed page to cached/uncached.
    904  */
    905 static void
    906 pmap_page_cache(struct vm_page *pg, bool cached)
    907 {
    908 	struct vm_page_md * const mdpg = VM_PAGE_TO_MD(pg);
    909 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
    910 	UVMHIST_LOG(pmaphist, "(pg=%p (pa %#"PRIxPADDR") cached=%s)",
    911 	    pg, VM_PAGE_TO_PHYS(pg), cached ? "true" : "false", 0);
    912 	KASSERT(kpreempt_disabled());
    913 
    914 	if (cached) {
    915 		pmap_page_clear_attributes(mdpg, VM_PAGEMD_UNCACHED);
    916 		PMAP_COUNT(page_cache_restorations);
    917 	} else {
    918 		pmap_page_set_attributes(mdpg, VM_PAGEMD_UNCACHED);
    919 		PMAP_COUNT(page_cache_evictions);
    920 	}
    921 
    922 	KASSERT(VM_PAGEMD_PVLIST_LOCKED_P(mdpg));
    923 	KASSERT(kpreempt_disabled());
    924 	for (pv_entry_t pv = &mdpg->mdpg_first;
    925 	     pv != NULL;
    926 	     pv = pv->pv_next) {
    927 		pmap_t pmap = pv->pv_pmap;
    928 		vaddr_t va = pv->pv_va;
    929 
    930 		KASSERT(pmap != NULL);
    931 		KASSERT(pmap != pmap_kernel() || !pmap_md_direct_mapped_vaddr_p(va));
    932 		pt_entry_t * const ptep = pmap_pte_lookup(pmap, va);
    933 		if (ptep == NULL)
    934 			continue;
    935 		pt_entry_t pt_entry = *ptep;
    936 		if (pte_valid_p(pt_entry)) {
    937 			pt_entry = pte_cached_change(pt_entry, cached);
    938 			*ptep = pt_entry;
    939 			pmap_tlb_update_addr(pmap, va, pt_entry,
    940 			    PMAP_TLB_NEED_IPI);
    941 		}
    942 	}
    943 	UVMHIST_LOG(pmaphist, "<- done", 0,0,0,0);
    944 }
    945 #endif	/* __PMAP_VIRTUAL_CACHE_ALIASES */
    946 
    947 /*
    948  *	Insert the given physical page (p) at
    949  *	the specified virtual address (v) in the
    950  *	target physical map with the protection requested.
    951  *
    952  *	If specified, the page will be wired down, meaning
    953  *	that the related pte can not be reclaimed.
    954  *
    955  *	NB:  This is the only routine which MAY NOT lazy-evaluate
    956  *	or lose information.  That is, this routine must actually
    957  *	insert this page into the given map NOW.
    958  */
    959 int
    960 pmap_enter(pmap_t pmap, vaddr_t va, paddr_t pa, vm_prot_t prot, u_int flags)
    961 {
    962 	pt_entry_t npte;
    963 	const bool wired = (flags & PMAP_WIRED) != 0;
    964 	const bool is_kernel_pmap_p = (pmap == pmap_kernel());
    965 #ifdef UVMHIST
    966 	struct kern_history * const histp =
    967 	    ((prot & VM_PROT_EXECUTE) ? &pmapexechist : &pmaphist);
    968 #endif
    969 
    970 	UVMHIST_FUNC(__func__);
    971 #define VM_PROT_STRING(prot) \
    972 	&"\0    (R)\0  (W)\0  (RW)\0 (X)\0  (RX)\0 (WX)\0 (RWX)\0"[UVM_PROTECTION(prot)*6]
    973 	UVMHIST_CALLED(*histp);
    974 	UVMHIST_LOG(*histp, "(pmap=%p, va=%#"PRIxVADDR", pa=%#"PRIxPADDR,
    975 	    pmap, va, pa, 0);
    976 	UVMHIST_LOG(*histp, "prot=%#x%s flags=%#x%s)",
    977 	    prot, VM_PROT_STRING(prot), flags, VM_PROT_STRING(flags));
    978 
    979 	const bool good_color = PMAP_PAGE_COLOROK_P(pa, va);
    980 	if (is_kernel_pmap_p) {
    981 		PMAP_COUNT(kernel_mappings);
    982 		if (!good_color)
    983 			PMAP_COUNT(kernel_mappings_bad);
    984 	} else {
    985 		PMAP_COUNT(user_mappings);
    986 		if (!good_color)
    987 			PMAP_COUNT(user_mappings_bad);
    988 	}
    989 #if defined(DEBUG) || defined(DIAGNOSTIC) || defined(PARANOIADIAG)
    990 	if (va < pmap->pm_minaddr || va >= pmap->pm_maxaddr)
    991 		panic("%s: %s %#"PRIxVADDR" too big",
    992 		    __func__, is_kernel_pmap_p ? "kva" : "uva", va);
    993 #endif
    994 
    995 	KASSERTMSG(prot & VM_PROT_READ,
    996 	    "%s: no READ (%#x) in prot %#x", __func__, VM_PROT_READ, prot);
    997 
    998 	struct vm_page * const pg = PHYS_TO_VM_PAGE(pa);
    999 	struct vm_page_md *mdpg;
   1000 
   1001 	if (pg) {
   1002 		mdpg = VM_PAGE_TO_MD(pg);
   1003 		/* Set page referenced/modified status based on flags */
   1004 		if (flags & VM_PROT_WRITE)
   1005 			pmap_page_set_attributes(mdpg, VM_PAGEMD_MODIFIED|VM_PAGEMD_REFERENCED);
   1006 		else if (flags & VM_PROT_ALL)
   1007 			pmap_page_set_attributes(mdpg, VM_PAGEMD_REFERENCED);
   1008 
   1009 #ifdef __PMAP_VIRTUAL_CACHE_ALIASES
   1010 		if (!VM_PAGEMD_CACHED(pg))
   1011 			flags |= PMAP_NOCACHE;
   1012 #endif
   1013 
   1014 		PMAP_COUNT(managed_mappings);
   1015 	} else {
   1016 		/*
   1017 		 * Assumption: if it is not part of our managed memory
   1018 		 * then it must be device memory which may be volatile.
   1019 		 */
   1020 		mdpg = NULL;
   1021 		flags |= PMAP_NOCACHE;
   1022 		PMAP_COUNT(unmanaged_mappings);
   1023 	}
   1024 
   1025 	npte = pte_make_enter(pa, mdpg, prot, flags, is_kernel_pmap_p);
   1026 
   1027 	kpreempt_disable();
   1028 	pt_entry_t * const ptep = pmap_pte_reserve(pmap, va, flags);
   1029 	if (__predict_false(ptep == NULL)) {
   1030 		kpreempt_enable();
   1031 		UVMHIST_LOG(*histp, "<- ENOMEM", 0,0,0,0);
   1032 		return ENOMEM;
   1033 	}
   1034 	pt_entry_t opte = *ptep;
   1035 
   1036 	/* Done after case that may sleep/return. */
   1037 	if (pg)
   1038 		pmap_enter_pv(pmap, va, pg, &npte);
   1039 
   1040 	/*
   1041 	 * Now validate mapping with desired protection/wiring.
   1042 	 * Assume uniform modified and referenced status for all
   1043 	 * MIPS pages in a MACH page.
   1044 	 */
   1045 	if (wired) {
   1046 		pmap->pm_stats.wired_count++;
   1047 		npte = pte_wire_entry(npte);
   1048 	}
   1049 
   1050 	UVMHIST_LOG(*histp, "new pte %#x (pa %#"PRIxPADDR")", npte, pa, 0,0);
   1051 
   1052 	if (pte_valid_p(opte) && pte_to_paddr(opte) != pa) {
   1053 		pmap_remove(pmap, va, va + NBPG);
   1054 		PMAP_COUNT(user_mappings_changed);
   1055 	}
   1056 
   1057 	KASSERT(pte_valid_p(npte));
   1058 	bool resident = pte_valid_p(opte);
   1059 	if (!resident)
   1060 		pmap->pm_stats.resident_count++;
   1061 	*ptep = npte;
   1062 
   1063 	pmap_tlb_update_addr(pmap, va, npte,
   1064 	    ((flags & VM_PROT_ALL) ? PMAP_TLB_INSERT : 0)
   1065 	    | (resident ? PMAP_TLB_NEED_IPI : 0));
   1066 	kpreempt_enable();
   1067 
   1068 	if (pg != NULL && (prot == (VM_PROT_READ | VM_PROT_EXECUTE))) {
   1069 		KASSERT(mdpg != NULL);
   1070 		PMAP_COUNT(exec_mappings);
   1071 		if (!VM_PAGEMD_EXECPAGE_P(mdpg) && pte_cached_p(npte)) {
   1072 			if (!pte_deferred_exec_p(npte)) {
   1073 				UVMHIST_LOG(*histp,
   1074 				    "va=%#"PRIxVADDR" pg %p: %s syncicache%s",
   1075 				    va, pg, "immediate", "");
   1076 				pmap_page_syncicache(pg);
   1077 				pmap_page_set_attributes(mdpg,
   1078 				    VM_PAGEMD_EXECPAGE);
   1079 				PMAP_COUNT(exec_synced_mappings);
   1080 			} else {
   1081 				UVMHIST_LOG(*histp, "va=%#"PRIxVADDR
   1082 				    " pg %p: %s syncicache: pte %#x",
   1083 				    va, pg, "defer", npte);
   1084 			}
   1085 		} else {
   1086 			UVMHIST_LOG(*histp,
   1087 			    "va=%#"PRIxVADDR" pg %p: %s syncicache%s",
   1088 			    va, pg, "no",
   1089 			    (pte_cached_p(npte)
   1090 				? " (already exec)"
   1091 				: " (uncached)"));
   1092 		}
   1093 	} else if (pg != NULL && (prot & VM_PROT_EXECUTE)) {
   1094 		KASSERT(mdpg != NULL);
   1095 		KASSERT(prot & VM_PROT_WRITE);
   1096 		PMAP_COUNT(exec_mappings);
   1097 		pmap_page_syncicache(pg);
   1098 		pmap_page_clear_attributes(mdpg, VM_PAGEMD_EXECPAGE);
   1099 		UVMHIST_LOG(pmapexechist,
   1100 		    "va=%#"PRIxVADDR" pg %p: %s syncicache%s",
   1101 		    va, pg, "immediate", " (writeable)");
   1102 	}
   1103 
   1104 	if (prot & VM_PROT_EXECUTE) {
   1105 		UVMHIST_LOG(pmapexechist, "<- 0 (OK)", 0,0,0,0);
   1106 	} else {
   1107 		UVMHIST_LOG(pmaphist, "<- 0 (OK)", 0,0,0,0);
   1108 	}
   1109 	return 0;
   1110 }
   1111 
   1112 void
   1113 pmap_kenter_pa(vaddr_t va, paddr_t pa, vm_prot_t prot, u_int flags)
   1114 {
   1115 	struct vm_page * const pg = PHYS_TO_VM_PAGE(pa);
   1116 	struct vm_page_md *mdpg;
   1117 
   1118 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
   1119 	UVMHIST_LOG(pmaphist, "(va=%#"PRIxVADDR" pa=%#"PRIxPADDR
   1120 	    ", prot=%#x, flags=%#x)", va, pa, prot, flags);
   1121 	PMAP_COUNT(kenter_pa);
   1122 
   1123 	if (pg == NULL) {
   1124 		mdpg = NULL;
   1125 		PMAP_COUNT(kenter_pa_unmanaged);
   1126 		flags |= PMAP_NOCACHE;
   1127 	} else {
   1128 		mdpg = VM_PAGE_TO_MD(pg);
   1129 	}
   1130 
   1131 	if ((flags & PMAP_NOCACHE) == 0 && !PMAP_PAGE_COLOROK_P(pa, va))
   1132 		PMAP_COUNT(kenter_pa_bad);
   1133 
   1134 	const pt_entry_t npte = pte_make_kenter_pa(pa, mdpg, prot, flags);
   1135 	kpreempt_disable();
   1136 	pt_entry_t * const ptep = pmap_pte_reserve(pmap_kernel(), va, 0);
   1137 	KASSERT(ptep != NULL);
   1138 	KASSERT(!pte_valid_p(*ptep));
   1139 	*ptep = npte;
   1140 	/*
   1141 	 * We have the option to force this mapping into the TLB but we
   1142 	 * don't.  Instead let the next reference to the page do it.
   1143 	 */
   1144 	pmap_tlb_update_addr(pmap_kernel(), va, npte, 0);
   1145 	kpreempt_enable();
   1146 #if DEBUG > 1
   1147 	for (u_int i = 0; i < PAGE_SIZE / sizeof(long); i++) {
   1148 		if (((long *)va)[i] != ((long *)pa)[i])
   1149 			panic("%s: contents (%lx) of va %#"PRIxVADDR
   1150 			    " != contents (%lx) of pa %#"PRIxPADDR, __func__,
   1151 			    ((long *)va)[i], va, ((long *)pa)[i], pa);
   1152 	}
   1153 #endif
   1154 	UVMHIST_LOG(pmaphist, "<- done", 0,0,0,0);
   1155 }
   1156 
   1157 static bool
   1158 pmap_pte_kremove(pmap_t pmap, vaddr_t sva, vaddr_t eva, pt_entry_t *ptep,
   1159 	uintptr_t flags)
   1160 {
   1161 	const pt_entry_t new_pt_entry = pte_nv_entry(true);
   1162 
   1163 	KASSERT(kpreempt_disabled());
   1164 
   1165 	/*
   1166 	 * Set every pt on every valid mapping within this segment.
   1167 	 */
   1168 	for (; sva < eva; sva += NBPG, ptep++) {
   1169 		pt_entry_t pt_entry = *ptep;
   1170 		if (!pte_valid_p(pt_entry)) {
   1171 			continue;
   1172 		}
   1173 
   1174 		PMAP_COUNT(kremove_pages);
   1175 		struct vm_page * const pg =
   1176 		    PHYS_TO_VM_PAGE(pte_to_paddr(pt_entry));
   1177 		if (pg != NULL)
   1178 			pmap_md_vca_clean(pg, sva, PMAP_WBINV);
   1179 
   1180 		*ptep = new_pt_entry;
   1181 		pmap_tlb_invalidate_addr(pmap_kernel(), sva);
   1182 	}
   1183 
   1184 	return false;
   1185 }
   1186 
   1187 void
   1188 pmap_kremove(vaddr_t va, vsize_t len)
   1189 {
   1190 	const vaddr_t sva = trunc_page(va);
   1191 	const vaddr_t eva = round_page(va + len);
   1192 
   1193 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
   1194 	UVMHIST_LOG(pmaphist, "(va=%#"PRIxVADDR" len=%#"PRIxVSIZE")",
   1195 	    va, len, 0,0);
   1196 
   1197 	kpreempt_disable();
   1198 	pmap_pte_process(pmap_kernel(), sva, eva, pmap_pte_kremove, 0);
   1199 	kpreempt_enable();
   1200 
   1201 	UVMHIST_LOG(pmaphist, "<- done", 0,0,0,0);
   1202 }
   1203 
   1204 void
   1205 pmap_remove_all(struct pmap *pmap)
   1206 {
   1207 	KASSERT(pmap != pmap_kernel());
   1208 
   1209 	kpreempt_disable();
   1210 	/*
   1211 	 * Free all of our ASIDs which means we can skip doing all the
   1212 	 * tlb_invalidate_addrs().
   1213 	 */
   1214 	pmap_tlb_asid_deactivate(pmap);
   1215 	pmap_tlb_asid_release_all(pmap);
   1216 	pmap->pm_flags |= PMAP_DEFERRED_ACTIVATE;
   1217 
   1218 	kpreempt_enable();
   1219 }
   1220 
   1221 /*
   1222  *	Routine:	pmap_unwire
   1223  *	Function:	Clear the wired attribute for a map/virtual-address
   1224  *			pair.
   1225  *	In/out conditions:
   1226  *			The mapping must already exist in the pmap.
   1227  */
   1228 void
   1229 pmap_unwire(pmap_t pmap, vaddr_t va)
   1230 {
   1231 
   1232 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
   1233 	UVMHIST_LOG(pmaphist, "(pmap=%p va=%#"PRIxVADDR")", pmap, va, 0,0);
   1234 	PMAP_COUNT(unwire);
   1235 
   1236 	/*
   1237 	 * Don't need to flush the TLB since PG_WIRED is only in software.
   1238 	 */
   1239 #ifdef PARANOIADIAG
   1240 	if (va < pmap->pm_minaddr || pmap->pm_maxaddr <= va)
   1241 		panic("pmap_unwire");
   1242 #endif
   1243 	kpreempt_disable();
   1244 	pt_entry_t * const ptep = pmap_pte_lookup(pmap, va);
   1245 	pt_entry_t pt_entry = *ptep;
   1246 #ifdef DIAGNOSTIC
   1247 	if (ptep == NULL)
   1248 		panic("%s: pmap %p va %#"PRIxVADDR" invalid STE",
   1249 		    __func__, pmap, va);
   1250 #endif
   1251 
   1252 #ifdef DIAGNOSTIC
   1253 	if (!pte_valid_p(pt_entry))
   1254 		panic("pmap_unwire: pmap %p va %#"PRIxVADDR" invalid PTE",
   1255 		    pmap, va);
   1256 #endif
   1257 
   1258 	if (pte_wired_p(pt_entry)) {
   1259 		*ptep = pte_unwire_entry(*ptep);
   1260 		pmap->pm_stats.wired_count--;
   1261 	}
   1262 #ifdef DIAGNOSTIC
   1263 	else {
   1264 		printf("%s: wiring for pmap %p va %#"PRIxVADDR" unchanged!\n",
   1265 		    __func__, pmap, va);
   1266 	}
   1267 #endif
   1268 	kpreempt_enable();
   1269 }
   1270 
   1271 /*
   1272  *	Routine:	pmap_extract
   1273  *	Function:
   1274  *		Extract the physical page address associated
   1275  *		with the given map/virtual_address pair.
   1276  */
   1277 bool
   1278 pmap_extract(pmap_t pmap, vaddr_t va, paddr_t *pap)
   1279 {
   1280 	paddr_t pa;
   1281 
   1282 	//UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
   1283 	//UVMHIST_LOG(pmaphist, "(pmap=%p va=%#"PRIxVADDR")", pmap, va, 0,0);
   1284 	if (pmap == pmap_kernel()) {
   1285 		if (pmap_md_direct_mapped_vaddr_p(va)) {
   1286 			pa = pmap_md_direct_mapped_vaddr_to_paddr(va);
   1287 			goto done;
   1288 		}
   1289 		if (pmap_md_io_vaddr_p(va))
   1290 			panic("pmap_extract: io address %#"PRIxVADDR"", va);
   1291 	}
   1292 	kpreempt_disable();
   1293 	pt_entry_t * const ptep = pmap_pte_lookup(pmap, va);
   1294 	if (ptep == NULL) {
   1295 		//UVMHIST_LOG(pmaphist, "<- false (not in segmap)", 0,0,0,0);
   1296 		kpreempt_enable();
   1297 		return false;
   1298 	}
   1299 	if (!pte_valid_p(*ptep)) {
   1300 		//UVMHIST_LOG(pmaphist, "<- false (PTE not valid)", 0,0,0,0);
   1301 		kpreempt_enable();
   1302 		return false;
   1303 	}
   1304 	pa = pte_to_paddr(*ptep) | (va & PGOFSET);
   1305 	kpreempt_enable();
   1306 done:
   1307 	if (pap != NULL) {
   1308 		*pap = pa;
   1309 	}
   1310 	//UVMHIST_LOG(pmaphist, "<- true (pa %#"PRIxPADDR")", pa, 0,0,0);
   1311 	return true;
   1312 }
   1313 
   1314 /*
   1315  *	Copy the range specified by src_addr/len
   1316  *	from the source map to the range dst_addr/len
   1317  *	in the destination map.
   1318  *
   1319  *	This routine is only advisory and need not do anything.
   1320  */
   1321 void
   1322 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vaddr_t dst_addr, vsize_t len,
   1323     vaddr_t src_addr)
   1324 {
   1325 
   1326 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
   1327 	PMAP_COUNT(copy);
   1328 }
   1329 
   1330 /*
   1331  *	pmap_clear_reference:
   1332  *
   1333  *	Clear the reference bit on the specified physical page.
   1334  */
   1335 bool
   1336 pmap_clear_reference(struct vm_page *pg)
   1337 {
   1338 	struct vm_page_md * const mdpg = VM_PAGE_TO_MD(pg);
   1339 
   1340 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
   1341 	UVMHIST_LOG(pmaphist, "(pg=%p (pa %#"PRIxPADDR"))",
   1342 	   pg, VM_PAGE_TO_PHYS(pg), 0,0);
   1343 
   1344 	bool rv = pmap_page_clear_attributes(mdpg, VM_PAGEMD_REFERENCED);
   1345 
   1346 	UVMHIST_LOG(pmaphist, "<- %s", rv ? "true" : "false", 0,0,0);
   1347 
   1348 	return rv;
   1349 }
   1350 
   1351 /*
   1352  *	pmap_is_referenced:
   1353  *
   1354  *	Return whether or not the specified physical page is referenced
   1355  *	by any physical maps.
   1356  */
   1357 bool
   1358 pmap_is_referenced(struct vm_page *pg)
   1359 {
   1360 
   1361 	return VM_PAGEMD_REFERENCED_P(VM_PAGE_TO_MD(pg));
   1362 }
   1363 
   1364 /*
   1365  *	Clear the modify bits on the specified physical page.
   1366  */
   1367 bool
   1368 pmap_clear_modify(struct vm_page *pg)
   1369 {
   1370 	struct vm_page_md * const mdpg = VM_PAGE_TO_MD(pg);
   1371 	pv_entry_t pv = &mdpg->mdpg_first;
   1372 	pv_entry_t pv_next;
   1373 	uint16_t gen;
   1374 
   1375 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
   1376 	UVMHIST_LOG(pmaphist, "(pg=%p (%#"PRIxPADDR"))",
   1377 	    pg, VM_PAGE_TO_PHYS(pg), 0,0);
   1378 	PMAP_COUNT(clear_modify);
   1379 
   1380 	if (VM_PAGEMD_EXECPAGE_P(mdpg)) {
   1381 		if (pv->pv_pmap == NULL) {
   1382 			UVMHIST_LOG(pmapexechist,
   1383 			    "pg %p (pa %#"PRIxPADDR"): %s",
   1384 			    pg, VM_PAGE_TO_PHYS(pg), "execpage cleared", 0);
   1385 			pmap_page_clear_attributes(mdpg, VM_PAGEMD_EXECPAGE);
   1386 			PMAP_COUNT(exec_uncached_clear_modify);
   1387 		} else {
   1388 			UVMHIST_LOG(pmapexechist,
   1389 			    "pg %p (pa %#"PRIxPADDR"): %s",
   1390 			    pg, VM_PAGE_TO_PHYS(pg), "syncicache performed", 0);
   1391 			pmap_page_syncicache(pg);
   1392 			PMAP_COUNT(exec_synced_clear_modify);
   1393 		}
   1394 	}
   1395 	if (!pmap_page_clear_attributes(mdpg, VM_PAGEMD_MODIFIED)) {
   1396 		UVMHIST_LOG(pmaphist, "<- false", 0,0,0,0);
   1397 		return false;
   1398 	}
   1399 	if (pv->pv_pmap == NULL) {
   1400 		UVMHIST_LOG(pmaphist, "<- true (no mappings)", 0,0,0,0);
   1401 		return true;
   1402 	}
   1403 
   1404 	/*
   1405 	 * remove write access from any pages that are dirty
   1406 	 * so we can tell if they are written to again later.
   1407 	 * flush the VAC first if there is one.
   1408 	 */
   1409 	kpreempt_disable();
   1410 	gen = VM_PAGEMD_PVLIST_LOCK(mdpg, false);
   1411 	for (; pv != NULL; pv = pv_next) {
   1412 		pmap_t pmap = pv->pv_pmap;
   1413 		vaddr_t va = pv->pv_va;
   1414 		pt_entry_t * const ptep = pmap_pte_lookup(pmap, va);
   1415 		KASSERT(ptep);
   1416 		pv_next = pv->pv_next;
   1417 		pt_entry_t pt_entry = pte_prot_nowrite(*ptep);
   1418 		if (*ptep == pt_entry) {
   1419 			continue;
   1420 		}
   1421 		pmap_md_vca_clean(pg, va, PMAP_WBINV);
   1422 		*ptep = pt_entry;
   1423 		VM_PAGEMD_PVLIST_UNLOCK(mdpg);
   1424 		pmap_tlb_invalidate_addr(pmap, va);
   1425 		pmap_update(pmap);
   1426 		if (__predict_false(gen != VM_PAGEMD_PVLIST_LOCK(mdpg, false))) {
   1427 			/*
   1428 			 * The list changed!  So restart from the beginning.
   1429 			 */
   1430 			pv_next = &mdpg->mdpg_first;
   1431 		}
   1432 	}
   1433 	VM_PAGEMD_PVLIST_UNLOCK(mdpg);
   1434 	kpreempt_enable();
   1435 
   1436 	UVMHIST_LOG(pmaphist, "<- true (mappings changed)", 0,0,0,0);
   1437 	return true;
   1438 }
   1439 
   1440 /*
   1441  *	pmap_is_modified:
   1442  *
   1443  *	Return whether or not the specified physical page is modified
   1444  *	by any physical maps.
   1445  */
   1446 bool
   1447 pmap_is_modified(struct vm_page *pg)
   1448 {
   1449 
   1450 	return VM_PAGEMD_MODIFIED_P(VM_PAGE_TO_MD(pg));
   1451 }
   1452 
   1453 /*
   1454  *	pmap_set_modified:
   1455  *
   1456  *	Sets the page modified reference bit for the specified page.
   1457  */
   1458 void
   1459 pmap_set_modified(paddr_t pa)
   1460 {
   1461 	struct vm_page * const pg = PHYS_TO_VM_PAGE(pa);
   1462 	struct vm_page_md * const mdpg = VM_PAGE_TO_MD(pg);
   1463 	pmap_page_set_attributes(mdpg, VM_PAGEMD_MODIFIED|VM_PAGEMD_REFERENCED);
   1464 }
   1465 
   1466 /******************** pv_entry management ********************/
   1467 
   1468 static void
   1469 pmap_check_pvlist(struct vm_page *pg)
   1470 {
   1471 #ifdef PARANOIADIAG
   1472 	struct vm_page_md * const mdpg = VM_PAGE_TO_MD(pg);
   1473 	pt_entry_t pv = &mdpg->mdpg_first;
   1474 	if (pv->pv_pmap != NULL) {
   1475 		for (; pv != NULL; pv = pv->pv_next) {
   1476 			KASSERT(!pmap_md_direct_mapped_vaddr_p(pv->pv_va));
   1477 		}
   1478 	}
   1479 #endif /* PARANOIADIAG */
   1480 }
   1481 
   1482 /*
   1483  * Enter the pmap and virtual address into the
   1484  * physical to virtual map table.
   1485  */
   1486 void
   1487 pmap_enter_pv(pmap_t pmap, vaddr_t va, struct vm_page *pg, u_int *npte)
   1488 {
   1489 	struct vm_page_md * const mdpg = VM_PAGE_TO_MD(pg);
   1490 	pv_entry_t pv, npv, apv;
   1491 	int16_t gen;
   1492 	bool first __unused = false;
   1493 
   1494 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
   1495 	UVMHIST_LOG(pmaphist,
   1496 	    "(pmap=%p va=%#"PRIxVADDR" pg=%p (%#"PRIxPADDR")",
   1497 	    pmap, va, pg, VM_PAGE_TO_PHYS(pg));
   1498 	UVMHIST_LOG(pmaphist, "nptep=%p (%#x))", npte, *npte, 0, 0);
   1499 
   1500 	KASSERT(kpreempt_disabled());
   1501 	KASSERT(pmap != pmap_kernel() || !pmap_md_direct_mapped_vaddr_p(va));
   1502 
   1503 	apv = NULL;
   1504 	pv = &mdpg->mdpg_first;
   1505 	gen = VM_PAGEMD_PVLIST_LOCK(mdpg, true);
   1506 	pmap_check_pvlist(pg);
   1507 again:
   1508 	if (pv->pv_pmap == NULL) {
   1509 		KASSERT(pv->pv_next == NULL);
   1510 		/*
   1511 		 * No entries yet, use header as the first entry
   1512 		 */
   1513 		PMAP_COUNT(primary_mappings);
   1514 		PMAP_COUNT(mappings);
   1515 		first = true;
   1516 #ifdef __PMAP_VIRTUAL_CACHE_ALIASES
   1517 		pmap_page_clear_attributes(pg, VM_PAGEMD_UNCACHED);
   1518 #endif
   1519 		pv->pv_pmap = pmap;
   1520 		pv->pv_va = va;
   1521 	} else {
   1522 		if (pmap_md_vca_add(pg, va, npte))
   1523 			goto again;
   1524 
   1525 		/*
   1526 		 * There is at least one other VA mapping this page.
   1527 		 * Place this entry after the header.
   1528 		 *
   1529 		 * Note: the entry may already be in the table if
   1530 		 * we are only changing the protection bits.
   1531 		 */
   1532 
   1533 #ifdef PARANOIADIAG
   1534 		const paddr_t pa = VM_PAGE_TO_PHYS(pg);
   1535 #endif
   1536 		for (npv = pv; npv; npv = npv->pv_next) {
   1537 			if (pmap == npv->pv_pmap && va == npv->pv_va) {
   1538 #ifdef PARANOIADIAG
   1539 				pt_entry_t *ptep = pmap_pte_lookup(pmap, va);
   1540 				pt_entry_t pt_entry = (ptep ? *ptep : 0);
   1541 				if (!pte_valid_p(pt_entry)
   1542 				    || pte_to_paddr(pt_entry) != pa)
   1543 					printf(
   1544 		"pmap_enter_pv: found va %#"PRIxVADDR" pa %#"PRIxPADDR" in pv_table but != %x\n",
   1545 					    va, pa, pt_entry);
   1546 #endif
   1547 				PMAP_COUNT(remappings);
   1548 				VM_PAGEMD_PVLIST_UNLOCK(mdpg);
   1549 				if (__predict_false(apv != NULL))
   1550 					pmap_pv_free(apv);
   1551 				return;
   1552 			}
   1553 		}
   1554 		if (__predict_true(apv == NULL)) {
   1555 			/*
   1556 			 * To allocate a PV, we have to release the PVLIST lock
   1557 			 * so get the page generation.  We allocate the PV, and
   1558 			 * then reacquire the lock.
   1559 			 */
   1560 			VM_PAGEMD_PVLIST_UNLOCK(mdpg);
   1561 
   1562 			apv = (pv_entry_t)pmap_pv_alloc();
   1563 			if (apv == NULL)
   1564 				panic("pmap_enter_pv: pmap_pv_alloc() failed");
   1565 
   1566 			/*
   1567 			 * If the generation has changed, then someone else
   1568 			 * tinkered with this page so we should
   1569 			 * start over.
   1570 			 */
   1571 			uint16_t oldgen = gen;
   1572 			gen = VM_PAGEMD_PVLIST_LOCK(mdpg, true);
   1573 			if (gen != oldgen)
   1574 				goto again;
   1575 		}
   1576 		npv = apv;
   1577 		apv = NULL;
   1578 		npv->pv_va = va;
   1579 		npv->pv_pmap = pmap;
   1580 		npv->pv_next = pv->pv_next;
   1581 		pv->pv_next = npv;
   1582 		PMAP_COUNT(mappings);
   1583 	}
   1584 	pmap_check_pvlist(pg);
   1585 	VM_PAGEMD_PVLIST_UNLOCK(mdpg);
   1586 	if (__predict_false(apv != NULL))
   1587 		pmap_pv_free(apv);
   1588 
   1589 	UVMHIST_LOG(pmaphist, "<- done pv=%p%s",
   1590 	    pv, first ? " (first pv)" : "",0,0);
   1591 }
   1592 
   1593 /*
   1594  * Remove a physical to virtual address translation.
   1595  * If cache was inhibited on this page, and there are no more cache
   1596  * conflicts, restore caching.
   1597  * Flush the cache if the last page is removed (should always be cached
   1598  * at this point).
   1599  */
   1600 void
   1601 pmap_remove_pv(pmap_t pmap, vaddr_t va, struct vm_page *pg, bool dirty)
   1602 {
   1603 	struct vm_page_md * const mdpg = VM_PAGE_TO_MD(pg);
   1604 	pv_entry_t pv, npv;
   1605 	bool last;
   1606 
   1607 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pmaphist);
   1608 	UVMHIST_LOG(pmaphist,
   1609 	    "(pmap=%p va=%#"PRIxVADDR" pg=%p (pa %#"PRIxPADDR")\n",
   1610 	    pmap, va, pg, VM_PAGE_TO_PHYS(pg));
   1611 	UVMHIST_LOG(pmaphist, "dirty=%s)", dirty ? "true" : "false", 0,0,0);
   1612 
   1613 	KASSERT(kpreempt_disabled());
   1614 	pv = &mdpg->mdpg_first;
   1615 
   1616 	(void)VM_PAGEMD_PVLIST_LOCK(mdpg, true);
   1617 	pmap_check_pvlist(pg);
   1618 
   1619 	/*
   1620 	 * If it is the first entry on the list, it is actually
   1621 	 * in the header and we must copy the following entry up
   1622 	 * to the header.  Otherwise we must search the list for
   1623 	 * the entry.  In either case we free the now unused entry.
   1624 	 */
   1625 
   1626 	last = false;
   1627 	if (pmap == pv->pv_pmap && va == pv->pv_va) {
   1628 		npv = pv->pv_next;
   1629 		if (npv) {
   1630 			*pv = *npv;
   1631 			KASSERT(pv->pv_pmap != NULL);
   1632 		} else {
   1633 #ifdef __PMAP_VIRTUAL_CACHE_ALIASES
   1634 			pmap_page_clear_attributes(pg, VM_PAGEMD_UNCACHED);
   1635 #endif
   1636 			pv->pv_pmap = NULL;
   1637 			last = true;	/* Last mapping removed */
   1638 		}
   1639 		PMAP_COUNT(remove_pvfirst);
   1640 	} else {
   1641 		for (npv = pv->pv_next; npv; pv = npv, npv = npv->pv_next) {
   1642 			PMAP_COUNT(remove_pvsearch);
   1643 			if (pmap == npv->pv_pmap && va == npv->pv_va)
   1644 				break;
   1645 		}
   1646 		if (npv) {
   1647 			pv->pv_next = npv->pv_next;
   1648 		}
   1649 	}
   1650 	pmap_md_vca_remove(pg, va);
   1651 
   1652 	pmap_check_pvlist(pg);
   1653 	VM_PAGEMD_PVLIST_UNLOCK(mdpg);
   1654 
   1655 	/*
   1656 	 * Free the pv_entry if needed.
   1657 	 */
   1658 	if (npv)
   1659 		pmap_pv_free(npv);
   1660 	if (VM_PAGEMD_EXECPAGE_P(mdpg) && dirty) {
   1661 		if (last) {
   1662 			/*
   1663 			 * If this was the page's last mapping, we no longer
   1664 			 * care about its execness.
   1665 			 */
   1666 			UVMHIST_LOG(pmapexechist,
   1667 			    "pg %p (pa %#"PRIxPADDR")%s: %s",
   1668 			    pg, VM_PAGE_TO_PHYS(pg),
   1669 			    last ? " [last mapping]" : "",
   1670 			    "execpage cleared");
   1671 			pmap_page_clear_attributes(mdpg, VM_PAGEMD_EXECPAGE);
   1672 			PMAP_COUNT(exec_uncached_remove);
   1673 		} else {
   1674 			/*
   1675 			 * Someone still has it mapped as an executable page
   1676 			 * so we must sync it.
   1677 			 */
   1678 			UVMHIST_LOG(pmapexechist,
   1679 			    "pg %p (pa %#"PRIxPADDR")%s: %s",
   1680 			    pg, VM_PAGE_TO_PHYS(pg),
   1681 			    last ? " [last mapping]" : "",
   1682 			    "performed syncicache");
   1683 			pmap_page_syncicache(pg);
   1684 			PMAP_COUNT(exec_synced_remove);
   1685 		}
   1686 	}
   1687 	UVMHIST_LOG(pmaphist, "<- done", 0,0,0,0);
   1688 }
   1689 
   1690 #if defined(MULTIPROCESSOR)
   1691 struct pmap_pvlist_info {
   1692 	kmutex_t *pli_locks[PAGE_SIZE / 32];
   1693 	volatile u_int pli_lock_refs[PAGE_SIZE / 32];
   1694 	volatile u_int pli_lock_index;
   1695 	u_int pli_lock_mask;
   1696 } pmap_pvlist_info;
   1697 
   1698 void
   1699 pmap_pvlist_lock_init(size_t cache_line_size)
   1700 {
   1701 	struct pmap_pvlist_info * const pli = &pmap_pvlist_info;
   1702 	const vaddr_t lock_page = uvm_pageboot_alloc(PAGE_SIZE);
   1703 	vaddr_t lock_va = lock_page;
   1704 	if (sizeof(kmutex_t) > cache_line_size) {
   1705 		cache_line_size = roundup2(sizeof(kmutex_t), cache_line_size);
   1706 	}
   1707 	const size_t nlocks = PAGE_SIZE / cache_line_size;
   1708 	KASSERT((nlocks & (nlocks - 1)) == 0);
   1709 	/*
   1710 	 * Now divide the page into a number of mutexes, one per cacheline.
   1711 	 */
   1712 	for (size_t i = 0; i < nlocks; lock_va += cache_line_size, i++) {
   1713 		kmutex_t * const lock = (kmutex_t *)lock_va;
   1714 		mutex_init(lock, MUTEX_DEFAULT, IPL_VM);
   1715 		pli->pli_locks[i] = lock;
   1716 	}
   1717 	pli->pli_lock_mask = nlocks - 1;
   1718 }
   1719 
   1720 uint16_t
   1721 pmap_pvlist_lock(struct vm_page_md *mdpg, bool list_change)
   1722 {
   1723 	struct pmap_pvlist_info * const pli = &pmap_pvlist_info;
   1724 	kmutex_t *lock = mdpg->mdpg_lock;
   1725 	int16_t gen;
   1726 
   1727 	/*
   1728 	 * Allocate a lock on an as-needed basis.  This will hopefully give us
   1729 	 * semi-random distribution not based on page color.
   1730 	 */
   1731 	if (__predict_false(lock == NULL)) {
   1732 		size_t locknum = atomic_add_int_nv(&pli->pli_lock_index, 37);
   1733 		size_t lockid = locknum & pli->pli_lock_mask;
   1734 		kmutex_t * const new_lock = pli->pli_locks[lockid];
   1735 		/*
   1736 		 * Set the lock.  If some other thread already did, just use
   1737 		 * the one they assigned.
   1738 		 */
   1739 		lock = atomic_cas_ptr(&mdpg->mdpg_lock, NULL, new_lock);
   1740 		if (lock == NULL) {
   1741 			lock = new_lock;
   1742 			atomic_inc_uint(&pli->pli_lock_refs[lockid]);
   1743 		}
   1744 	}
   1745 
   1746 	/*
   1747 	 * Now finally lock the pvlists.
   1748 	 */
   1749 	mutex_spin_enter(lock);
   1750 
   1751 	/*
   1752 	 * If the locker will be changing the list, increment the high 16 bits
   1753 	 * of attrs so we use that as a generation number.
   1754 	 */
   1755 	gen = VM_PAGEMD_PVLIST_GEN(mdpg);		/* get old value */
   1756 	if (list_change)
   1757 		atomic_add_int(&mdpg->mdpg_attrs, 0x10000);
   1758 
   1759 	/*
   1760 	 * Return the generation number.
   1761 	 */
   1762 	return gen;
   1763 }
   1764 #else /* !MULTIPROCESSOR */
   1765 void
   1766 pmap_pvlist_lock_init(size_t cache_line_size)
   1767 {
   1768 	mutex_init(&pmap_pvlist_mutex, MUTEX_DEFAULT, IPL_VM);
   1769 }
   1770 
   1771 #ifdef MODULAR
   1772 uint16_t
   1773 pmap_pvlist_lock(struct vm_page_md *mdpg, bool list_change)
   1774 {
   1775 	/*
   1776 	 * We just use a global lock.
   1777 	 */
   1778 	if (__predict_false(mdpg->mdpg_lock == NULL)) {
   1779 		mdpg->mdpg_lock = &pmap_pvlist_mutex;
   1780 	}
   1781 
   1782 	/*
   1783 	 * Now finally lock the pvlists.
   1784 	 */
   1785 	mutex_spin_enter(mdpg->mdpg_lock);
   1786 
   1787 	return 0;
   1788 }
   1789 #endif /* MODULAR */
   1790 #endif /* !MULTIPROCESSOR */
   1791 
   1792 /*
   1793  * pmap_pv_page_alloc:
   1794  *
   1795  *	Allocate a page for the pv_entry pool.
   1796  */
   1797 void *
   1798 pmap_pv_page_alloc(struct pool *pp, int flags)
   1799 {
   1800 	struct vm_page *pg = PMAP_ALLOC_POOLPAGE(UVM_PGA_USERESERVE);
   1801 	if (pg == NULL)
   1802 		return NULL;
   1803 
   1804 	return (void *)pmap_map_poolpage(VM_PAGE_TO_PHYS(pg));
   1805 }
   1806 
   1807 /*
   1808  * pmap_pv_page_free:
   1809  *
   1810  *	Free a pv_entry pool page.
   1811  */
   1812 void
   1813 pmap_pv_page_free(struct pool *pp, void *v)
   1814 {
   1815 	vaddr_t va = (vaddr_t)v;
   1816 
   1817 	KASSERT(pmap_md_direct_mapped_vaddr_p(va));
   1818 	const paddr_t pa = pmap_md_direct_mapped_vaddr_to_paddr(va);
   1819 	struct vm_page * const pg = PHYS_TO_VM_PAGE(pa);
   1820 	struct vm_page_md * const mdpg = VM_PAGE_TO_MD(pg);
   1821 	pmap_md_vca_remove(pg, va);
   1822 	pmap_page_clear_attributes(mdpg, VM_PAGEMD_POOLPAGE);
   1823 	uvm_pagefree(pg);
   1824 }
   1825 
   1826 #ifdef PMAP_PREFER
   1827 /*
   1828  * Find first virtual address >= *vap that doesn't cause
   1829  * a cache alias conflict.
   1830  */
   1831 void
   1832 pmap_prefer(vaddr_t foff, vaddr_t *vap, vsize_t sz, int td)
   1833 {
   1834 	vaddr_t	va;
   1835 	vsize_t d;
   1836 	vsize_t prefer_mask = ptoa(uvmexp.colormask);
   1837 
   1838 	PMAP_COUNT(prefer_requests);
   1839 
   1840 	prefer_mask |= pmap_md_cache_prefer_mask();
   1841 
   1842 	if (prefer_mask) {
   1843 		va = *vap;
   1844 
   1845 		d = foff - va;
   1846 		d &= prefer_mask;
   1847 		if (d) {
   1848 			if (td)
   1849 				*vap = trunc_page(va -((-d) & prefer_mask));
   1850 			else
   1851 				*vap = round_page(va + d);
   1852 			PMAP_COUNT(prefer_adjustments);
   1853 		}
   1854 	}
   1855 }
   1856 #endif /* PMAP_PREFER */
   1857 
   1858 #ifdef PMAP_MAP_POOLPAGE
   1859 vaddr_t
   1860 pmap_map_poolpage(paddr_t pa)
   1861 {
   1862 
   1863 	struct vm_page * const pg = PHYS_TO_VM_PAGE(pa);
   1864 	KASSERT(pg);
   1865 	struct vm_page_md * const mdpg = VM_PAGE_TO_MD(pg);
   1866 	pmap_page_set_attributes(mdpg, VM_PAGEMD_POOLPAGE);
   1867 
   1868 	const vaddr_t va = pmap_md_map_poolpage(pa, NBPG);
   1869 	pmap_md_vca_add(pg, va, NULL);
   1870 	return va;
   1871 }
   1872 
   1873 paddr_t
   1874 pmap_unmap_poolpage(vaddr_t va)
   1875 {
   1876 
   1877 	KASSERT(pmap_md_direct_mapped_vaddr_p(va));
   1878 	paddr_t pa = pmap_md_direct_mapped_vaddr_to_paddr(va);
   1879 
   1880 	struct vm_page * const pg = PHYS_TO_VM_PAGE(pa);
   1881 	KASSERT(pg);
   1882 	struct vm_page_md * const mdpg = VM_PAGE_TO_MD(pg);
   1883 	pmap_page_clear_attributes(mdpg, VM_PAGEMD_POOLPAGE);
   1884 	pmap_md_unmap_poolpage(va, NBPG);
   1885 	pmap_md_vca_remove(pg, va);
   1886 
   1887 	return pa;
   1888 }
   1889 #endif /* PMAP_MAP_POOLPAGE */
   1890