Home | History | Annotate | Line # | Download | only in uvm
uvm_page.c revision 1.222
      1 /*	$NetBSD: uvm_page.c,v 1.222 2020/01/09 16:35:03 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2019 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Andrew Doran.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (c) 1997 Charles D. Cranor and Washington University.
     34  * Copyright (c) 1991, 1993, The Regents of the University of California.
     35  *
     36  * All rights reserved.
     37  *
     38  * This code is derived from software contributed to Berkeley by
     39  * The Mach Operating System project at Carnegie-Mellon University.
     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  *	@(#)vm_page.c   8.3 (Berkeley) 3/21/94
     66  * from: Id: uvm_page.c,v 1.1.2.18 1998/02/06 05:24:42 chs Exp
     67  *
     68  *
     69  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
     70  * All rights reserved.
     71  *
     72  * Permission to use, copy, modify and distribute this software and
     73  * its documentation is hereby granted, provided that both the copyright
     74  * notice and this permission notice appear in all copies of the
     75  * software, derivative works or modified versions, and any portions
     76  * thereof, and that both notices appear in supporting documentation.
     77  *
     78  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
     79  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
     80  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
     81  *
     82  * Carnegie Mellon requests users of this software to return to
     83  *
     84  *  Software Distribution Coordinator  or  Software.Distribution (at) CS.CMU.EDU
     85  *  School of Computer Science
     86  *  Carnegie Mellon University
     87  *  Pittsburgh PA 15213-3890
     88  *
     89  * any improvements or extensions that they make and grant Carnegie the
     90  * rights to redistribute these changes.
     91  */
     92 
     93 /*
     94  * uvm_page.c: page ops.
     95  */
     96 
     97 #include <sys/cdefs.h>
     98 __KERNEL_RCSID(0, "$NetBSD: uvm_page.c,v 1.222 2020/01/09 16:35:03 ad Exp $");
     99 
    100 #include "opt_ddb.h"
    101 #include "opt_uvm.h"
    102 #include "opt_uvmhist.h"
    103 #include "opt_readahead.h"
    104 
    105 #include <sys/param.h>
    106 #include <sys/systm.h>
    107 #include <sys/sched.h>
    108 #include <sys/kernel.h>
    109 #include <sys/vnode.h>
    110 #include <sys/proc.h>
    111 #include <sys/radixtree.h>
    112 #include <sys/atomic.h>
    113 #include <sys/cpu.h>
    114 #include <sys/extent.h>
    115 
    116 #include <uvm/uvm.h>
    117 #include <uvm/uvm_ddb.h>
    118 #include <uvm/uvm_pdpolicy.h>
    119 #include <uvm/uvm_pgflcache.h>
    120 
    121 /*
    122  * Some supported CPUs in a given architecture don't support all
    123  * of the things necessary to do idle page zero'ing efficiently.
    124  * We therefore provide a way to enable it from machdep code here.
    125  */
    126 bool vm_page_zero_enable = false;
    127 
    128 /*
    129  * number of pages per-CPU to reserve for the kernel.
    130  */
    131 #ifndef	UVM_RESERVED_PAGES_PER_CPU
    132 #define	UVM_RESERVED_PAGES_PER_CPU	5
    133 #endif
    134 int vm_page_reserve_kernel = UVM_RESERVED_PAGES_PER_CPU;
    135 
    136 /*
    137  * physical memory size;
    138  */
    139 psize_t physmem;
    140 
    141 /*
    142  * local variables
    143  */
    144 
    145 /*
    146  * these variables record the values returned by vm_page_bootstrap,
    147  * for debugging purposes.  The implementation of uvm_pageboot_alloc
    148  * and pmap_startup here also uses them internally.
    149  */
    150 
    151 static vaddr_t      virtual_space_start;
    152 static vaddr_t      virtual_space_end;
    153 
    154 /*
    155  * we allocate an initial number of page colors in uvm_page_init(),
    156  * and remember them.  We may re-color pages as cache sizes are
    157  * discovered during the autoconfiguration phase.  But we can never
    158  * free the initial set of buckets, since they are allocated using
    159  * uvm_pageboot_alloc().
    160  */
    161 
    162 static size_t recolored_pages_memsize /* = 0 */;
    163 static char *recolored_pages_mem;
    164 
    165 /*
    166  * freelist locks - one per bucket.
    167  */
    168 
    169 union uvm_freelist_lock	uvm_freelist_locks[PGFL_MAX_BUCKETS]
    170     __cacheline_aligned;
    171 
    172 /*
    173  * basic NUMA information.
    174  */
    175 
    176 static struct uvm_page_numa_region {
    177 	struct uvm_page_numa_region	*next;
    178 	paddr_t				start;
    179 	paddr_t				size;
    180 	u_int				numa_id;
    181 } *uvm_page_numa_region;
    182 
    183 #ifdef DEBUG
    184 vaddr_t uvm_zerocheckkva;
    185 #endif /* DEBUG */
    186 
    187 /*
    188  * These functions are reserved for uvm(9) internal use and are not
    189  * exported in the header file uvm_physseg.h
    190  *
    191  * Thus they are redefined here.
    192  */
    193 void uvm_physseg_init_seg(uvm_physseg_t, struct vm_page *);
    194 void uvm_physseg_seg_chomp_slab(uvm_physseg_t, struct vm_page *, size_t);
    195 
    196 /* returns a pgs array */
    197 struct vm_page *uvm_physseg_seg_alloc_from_slab(uvm_physseg_t, size_t);
    198 
    199 /*
    200  * inline functions
    201  */
    202 
    203 /*
    204  * uvm_pageinsert: insert a page in the object.
    205  *
    206  * => caller must lock object
    207  * => call should have already set pg's object and offset pointers
    208  *    and bumped the version counter
    209  */
    210 
    211 static inline void
    212 uvm_pageinsert_object(struct uvm_object *uobj, struct vm_page *pg)
    213 {
    214 
    215 	KASSERT(uobj == pg->uobject);
    216 	KASSERT(mutex_owned(uobj->vmobjlock));
    217 	KASSERT((pg->flags & PG_TABLED) == 0);
    218 
    219 	if (UVM_OBJ_IS_VNODE(uobj)) {
    220 		if (uobj->uo_npages == 0) {
    221 			struct vnode *vp = (struct vnode *)uobj;
    222 
    223 			vholdl(vp);
    224 		}
    225 		if (UVM_OBJ_IS_VTEXT(uobj)) {
    226 			cpu_count(CPU_COUNT_EXECPAGES, 1);
    227 		} else {
    228 			cpu_count(CPU_COUNT_FILEPAGES, 1);
    229 		}
    230 	} else if (UVM_OBJ_IS_AOBJ(uobj)) {
    231 		cpu_count(CPU_COUNT_ANONPAGES, 1);
    232 	}
    233 	pg->flags |= PG_TABLED;
    234 	uobj->uo_npages++;
    235 }
    236 
    237 static inline int
    238 uvm_pageinsert_tree(struct uvm_object *uobj, struct vm_page *pg)
    239 {
    240 	const uint64_t idx = pg->offset >> PAGE_SHIFT;
    241 	int error;
    242 
    243 	error = radix_tree_insert_node(&uobj->uo_pages, idx, pg);
    244 	if (error != 0) {
    245 		return error;
    246 	}
    247 	return 0;
    248 }
    249 
    250 /*
    251  * uvm_page_remove: remove page from object.
    252  *
    253  * => caller must lock object
    254  */
    255 
    256 static inline void
    257 uvm_pageremove_object(struct uvm_object *uobj, struct vm_page *pg)
    258 {
    259 
    260 	KASSERT(uobj == pg->uobject);
    261 	KASSERT(mutex_owned(uobj->vmobjlock));
    262 	KASSERT(pg->flags & PG_TABLED);
    263 
    264 	if (UVM_OBJ_IS_VNODE(uobj)) {
    265 		if (uobj->uo_npages == 1) {
    266 			struct vnode *vp = (struct vnode *)uobj;
    267 
    268 			holdrelel(vp);
    269 		}
    270 		if (UVM_OBJ_IS_VTEXT(uobj)) {
    271 			cpu_count(CPU_COUNT_EXECPAGES, -1);
    272 		} else {
    273 			cpu_count(CPU_COUNT_FILEPAGES, -1);
    274 		}
    275 	} else if (UVM_OBJ_IS_AOBJ(uobj)) {
    276 		cpu_count(CPU_COUNT_ANONPAGES, -1);
    277 	}
    278 
    279 	/* object should be locked */
    280 	uobj->uo_npages--;
    281 	pg->flags &= ~PG_TABLED;
    282 	pg->uobject = NULL;
    283 }
    284 
    285 static inline void
    286 uvm_pageremove_tree(struct uvm_object *uobj, struct vm_page *pg)
    287 {
    288 	struct vm_page *opg __unused;
    289 
    290 	opg = radix_tree_remove_node(&uobj->uo_pages, pg->offset >> PAGE_SHIFT);
    291 	KASSERT(pg == opg);
    292 }
    293 
    294 static void
    295 uvm_page_init_bucket(struct pgfreelist *pgfl, struct pgflbucket *pgb, int num)
    296 {
    297 	int i;
    298 
    299 	pgb->pgb_nfree = 0;
    300 	for (i = 0; i < uvmexp.ncolors; i++) {
    301 		LIST_INIT(&pgb->pgb_colors[i]);
    302 	}
    303 	pgfl->pgfl_buckets[num] = pgb;
    304 }
    305 
    306 /*
    307  * uvm_page_init: init the page system.   called from uvm_init().
    308  *
    309  * => we return the range of kernel virtual memory in kvm_startp/kvm_endp
    310  */
    311 
    312 void
    313 uvm_page_init(vaddr_t *kvm_startp, vaddr_t *kvm_endp)
    314 {
    315 	static struct uvm_cpu boot_cpu __cacheline_aligned;
    316 	psize_t freepages, pagecount, bucketsize, n;
    317 	struct pgflbucket *pgb;
    318 	struct vm_page *pagearray;
    319 	char *bucketarray;
    320 	uvm_physseg_t bank;
    321 	int fl, b;
    322 
    323 	KASSERT(ncpu <= 1);
    324 
    325 	/*
    326 	 * init the page queues and free page queue locks, except the
    327 	 * free list; we allocate that later (with the initial vm_page
    328 	 * structures).
    329 	 */
    330 
    331 	curcpu()->ci_data.cpu_uvm = &boot_cpu;
    332 	uvmpdpol_init();
    333 	for (b = 0; b < __arraycount(uvm_freelist_locks); b++) {
    334 		mutex_init(&uvm_freelist_locks[b].lock, MUTEX_DEFAULT, IPL_VM);
    335 	}
    336 
    337 	/*
    338 	 * allocate vm_page structures.
    339 	 */
    340 
    341 	/*
    342 	 * sanity check:
    343 	 * before calling this function the MD code is expected to register
    344 	 * some free RAM with the uvm_page_physload() function.   our job
    345 	 * now is to allocate vm_page structures for this memory.
    346 	 */
    347 
    348 	if (uvm_physseg_get_last() == UVM_PHYSSEG_TYPE_INVALID)
    349 		panic("uvm_page_bootstrap: no memory pre-allocated");
    350 
    351 	/*
    352 	 * first calculate the number of free pages...
    353 	 *
    354 	 * note that we use start/end rather than avail_start/avail_end.
    355 	 * this allows us to allocate extra vm_page structures in case we
    356 	 * want to return some memory to the pool after booting.
    357 	 */
    358 
    359 	freepages = 0;
    360 
    361 	for (bank = uvm_physseg_get_first();
    362 	     uvm_physseg_valid_p(bank) ;
    363 	     bank = uvm_physseg_get_next(bank)) {
    364 		freepages += (uvm_physseg_get_end(bank) - uvm_physseg_get_start(bank));
    365 	}
    366 
    367 	/*
    368 	 * Let MD code initialize the number of colors, or default
    369 	 * to 1 color if MD code doesn't care.
    370 	 */
    371 	if (uvmexp.ncolors == 0)
    372 		uvmexp.ncolors = 1;
    373 	uvmexp.colormask = uvmexp.ncolors - 1;
    374 	KASSERT((uvmexp.colormask & uvmexp.ncolors) == 0);
    375 
    376 	/* We always start with only 1 bucket. */
    377 	uvm.bucketcount = 1;
    378 
    379 	/*
    380 	 * we now know we have (PAGE_SIZE * freepages) bytes of memory we can
    381 	 * use.   for each page of memory we use we need a vm_page structure.
    382 	 * thus, the total number of pages we can use is the total size of
    383 	 * the memory divided by the PAGE_SIZE plus the size of the vm_page
    384 	 * structure.   we add one to freepages as a fudge factor to avoid
    385 	 * truncation errors (since we can only allocate in terms of whole
    386 	 * pages).
    387 	 */
    388 	pagecount = ((freepages + 1) << PAGE_SHIFT) /
    389 	    (PAGE_SIZE + sizeof(struct vm_page));
    390 	bucketsize = offsetof(struct pgflbucket, pgb_colors[uvmexp.ncolors]);
    391 	bucketsize = roundup2(bucketsize, coherency_unit);
    392 	bucketarray = (void *)uvm_pageboot_alloc(
    393 	    bucketsize * VM_NFREELIST +
    394 	    pagecount * sizeof(struct vm_page));
    395 	pagearray = (struct vm_page *)
    396 	    (bucketarray + bucketsize * VM_NFREELIST);
    397 
    398 	for (fl = 0; fl < VM_NFREELIST; fl++) {
    399 		pgb = (struct pgflbucket *)(bucketarray + bucketsize * fl);
    400 		uvm_page_init_bucket(&uvm.page_free[fl], pgb, 0);
    401 	}
    402 	memset(pagearray, 0, pagecount * sizeof(struct vm_page));
    403 
    404 	/*
    405 	 * init the freelist cache in the disabled state.
    406 	 */
    407 	uvm_pgflcache_init();
    408 
    409 	/*
    410 	 * init the vm_page structures and put them in the correct place.
    411 	 */
    412 	/* First init the extent */
    413 
    414 	for (bank = uvm_physseg_get_first(),
    415 		 uvm_physseg_seg_chomp_slab(bank, pagearray, pagecount);
    416 	     uvm_physseg_valid_p(bank);
    417 	     bank = uvm_physseg_get_next(bank)) {
    418 
    419 		n = uvm_physseg_get_end(bank) - uvm_physseg_get_start(bank);
    420 		uvm_physseg_seg_alloc_from_slab(bank, n);
    421 		uvm_physseg_init_seg(bank, pagearray);
    422 
    423 		/* set up page array pointers */
    424 		pagearray += n;
    425 		pagecount -= n;
    426 	}
    427 
    428 	/*
    429 	 * pass up the values of virtual_space_start and
    430 	 * virtual_space_end (obtained by uvm_pageboot_alloc) to the upper
    431 	 * layers of the VM.
    432 	 */
    433 
    434 	*kvm_startp = round_page(virtual_space_start);
    435 	*kvm_endp = trunc_page(virtual_space_end);
    436 #ifdef DEBUG
    437 	/*
    438 	 * steal kva for uvm_pagezerocheck().
    439 	 */
    440 	uvm_zerocheckkva = *kvm_startp;
    441 	*kvm_startp += PAGE_SIZE;
    442 #endif /* DEBUG */
    443 
    444 	/*
    445 	 * init various thresholds.
    446 	 */
    447 
    448 	uvmexp.reserve_pagedaemon = 1;
    449 	uvmexp.reserve_kernel = vm_page_reserve_kernel;
    450 
    451 	/*
    452 	 * done!
    453 	 */
    454 
    455 	uvm.page_init_done = true;
    456 }
    457 
    458 /*
    459  * uvm_pgfl_lock: lock all freelist buckets
    460  */
    461 
    462 void
    463 uvm_pgfl_lock(void)
    464 {
    465 	int i;
    466 
    467 	for (i = 0; i < __arraycount(uvm_freelist_locks); i++) {
    468 		mutex_spin_enter(&uvm_freelist_locks[i].lock);
    469 	}
    470 }
    471 
    472 /*
    473  * uvm_pgfl_unlock: unlock all freelist buckets
    474  */
    475 
    476 void
    477 uvm_pgfl_unlock(void)
    478 {
    479 	int i;
    480 
    481 	for (i = 0; i < __arraycount(uvm_freelist_locks); i++) {
    482 		mutex_spin_exit(&uvm_freelist_locks[i].lock);
    483 	}
    484 }
    485 
    486 /*
    487  * uvm_setpagesize: set the page size
    488  *
    489  * => sets page_shift and page_mask from uvmexp.pagesize.
    490  */
    491 
    492 void
    493 uvm_setpagesize(void)
    494 {
    495 
    496 	/*
    497 	 * If uvmexp.pagesize is 0 at this point, we expect PAGE_SIZE
    498 	 * to be a constant (indicated by being a non-zero value).
    499 	 */
    500 	if (uvmexp.pagesize == 0) {
    501 		if (PAGE_SIZE == 0)
    502 			panic("uvm_setpagesize: uvmexp.pagesize not set");
    503 		uvmexp.pagesize = PAGE_SIZE;
    504 	}
    505 	uvmexp.pagemask = uvmexp.pagesize - 1;
    506 	if ((uvmexp.pagemask & uvmexp.pagesize) != 0)
    507 		panic("uvm_setpagesize: page size %u (%#x) not a power of two",
    508 		    uvmexp.pagesize, uvmexp.pagesize);
    509 	for (uvmexp.pageshift = 0; ; uvmexp.pageshift++)
    510 		if ((1 << uvmexp.pageshift) == uvmexp.pagesize)
    511 			break;
    512 }
    513 
    514 /*
    515  * uvm_pageboot_alloc: steal memory from physmem for bootstrapping
    516  */
    517 
    518 vaddr_t
    519 uvm_pageboot_alloc(vsize_t size)
    520 {
    521 	static bool initialized = false;
    522 	vaddr_t addr;
    523 #if !defined(PMAP_STEAL_MEMORY)
    524 	vaddr_t vaddr;
    525 	paddr_t paddr;
    526 #endif
    527 
    528 	/*
    529 	 * on first call to this function, initialize ourselves.
    530 	 */
    531 	if (initialized == false) {
    532 		pmap_virtual_space(&virtual_space_start, &virtual_space_end);
    533 
    534 		/* round it the way we like it */
    535 		virtual_space_start = round_page(virtual_space_start);
    536 		virtual_space_end = trunc_page(virtual_space_end);
    537 
    538 		initialized = true;
    539 	}
    540 
    541 	/* round to page size */
    542 	size = round_page(size);
    543 	uvmexp.bootpages += atop(size);
    544 
    545 #if defined(PMAP_STEAL_MEMORY)
    546 
    547 	/*
    548 	 * defer bootstrap allocation to MD code (it may want to allocate
    549 	 * from a direct-mapped segment).  pmap_steal_memory should adjust
    550 	 * virtual_space_start/virtual_space_end if necessary.
    551 	 */
    552 
    553 	addr = pmap_steal_memory(size, &virtual_space_start,
    554 	    &virtual_space_end);
    555 
    556 	return(addr);
    557 
    558 #else /* !PMAP_STEAL_MEMORY */
    559 
    560 	/*
    561 	 * allocate virtual memory for this request
    562 	 */
    563 	if (virtual_space_start == virtual_space_end ||
    564 	    (virtual_space_end - virtual_space_start) < size)
    565 		panic("uvm_pageboot_alloc: out of virtual space");
    566 
    567 	addr = virtual_space_start;
    568 
    569 #ifdef PMAP_GROWKERNEL
    570 	/*
    571 	 * If the kernel pmap can't map the requested space,
    572 	 * then allocate more resources for it.
    573 	 */
    574 	if (uvm_maxkaddr < (addr + size)) {
    575 		uvm_maxkaddr = pmap_growkernel(addr + size);
    576 		if (uvm_maxkaddr < (addr + size))
    577 			panic("uvm_pageboot_alloc: pmap_growkernel() failed");
    578 	}
    579 #endif
    580 
    581 	virtual_space_start += size;
    582 
    583 	/*
    584 	 * allocate and mapin physical pages to back new virtual pages
    585 	 */
    586 
    587 	for (vaddr = round_page(addr) ; vaddr < addr + size ;
    588 	    vaddr += PAGE_SIZE) {
    589 
    590 		if (!uvm_page_physget(&paddr))
    591 			panic("uvm_pageboot_alloc: out of memory");
    592 
    593 		/*
    594 		 * Note this memory is no longer managed, so using
    595 		 * pmap_kenter is safe.
    596 		 */
    597 		pmap_kenter_pa(vaddr, paddr, VM_PROT_READ|VM_PROT_WRITE, 0);
    598 	}
    599 	pmap_update(pmap_kernel());
    600 	return(addr);
    601 #endif	/* PMAP_STEAL_MEMORY */
    602 }
    603 
    604 #if !defined(PMAP_STEAL_MEMORY)
    605 /*
    606  * uvm_page_physget: "steal" one page from the vm_physmem structure.
    607  *
    608  * => attempt to allocate it off the end of a segment in which the "avail"
    609  *    values match the start/end values.   if we can't do that, then we
    610  *    will advance both values (making them equal, and removing some
    611  *    vm_page structures from the non-avail area).
    612  * => return false if out of memory.
    613  */
    614 
    615 /* subroutine: try to allocate from memory chunks on the specified freelist */
    616 static bool uvm_page_physget_freelist(paddr_t *, int);
    617 
    618 static bool
    619 uvm_page_physget_freelist(paddr_t *paddrp, int freelist)
    620 {
    621 	uvm_physseg_t lcv;
    622 
    623 	/* pass 1: try allocating from a matching end */
    624 #if (VM_PHYSSEG_STRAT == VM_PSTRAT_BIGFIRST)
    625 	for (lcv = uvm_physseg_get_last(); uvm_physseg_valid_p(lcv); lcv = uvm_physseg_get_prev(lcv))
    626 #else
    627 	for (lcv = uvm_physseg_get_first(); uvm_physseg_valid_p(lcv); lcv = uvm_physseg_get_next(lcv))
    628 #endif
    629 	{
    630 		if (uvm.page_init_done == true)
    631 			panic("uvm_page_physget: called _after_ bootstrap");
    632 
    633 		/* Try to match at front or back on unused segment */
    634 		if (uvm_page_physunload(lcv, freelist, paddrp))
    635 			return true;
    636 	}
    637 
    638 	/* pass2: forget about matching ends, just allocate something */
    639 #if (VM_PHYSSEG_STRAT == VM_PSTRAT_BIGFIRST)
    640 	for (lcv = uvm_physseg_get_last(); uvm_physseg_valid_p(lcv); lcv = uvm_physseg_get_prev(lcv))
    641 #else
    642 	for (lcv = uvm_physseg_get_first(); uvm_physseg_valid_p(lcv); lcv = uvm_physseg_get_next(lcv))
    643 #endif
    644 	{
    645 		/* Try the front regardless. */
    646 		if (uvm_page_physunload_force(lcv, freelist, paddrp))
    647 			return true;
    648 	}
    649 	return false;
    650 }
    651 
    652 bool
    653 uvm_page_physget(paddr_t *paddrp)
    654 {
    655 	int i;
    656 
    657 	/* try in the order of freelist preference */
    658 	for (i = 0; i < VM_NFREELIST; i++)
    659 		if (uvm_page_physget_freelist(paddrp, i) == true)
    660 			return (true);
    661 	return (false);
    662 }
    663 #endif /* PMAP_STEAL_MEMORY */
    664 
    665 /*
    666  * PHYS_TO_VM_PAGE: find vm_page for a PA.   used by MI code to get vm_pages
    667  * back from an I/O mapping (ugh!).   used in some MD code as well.
    668  */
    669 struct vm_page *
    670 uvm_phys_to_vm_page(paddr_t pa)
    671 {
    672 	paddr_t pf = atop(pa);
    673 	paddr_t	off;
    674 	uvm_physseg_t	upm;
    675 
    676 	upm = uvm_physseg_find(pf, &off);
    677 	if (upm != UVM_PHYSSEG_TYPE_INVALID)
    678 		return uvm_physseg_get_pg(upm, off);
    679 	return(NULL);
    680 }
    681 
    682 paddr_t
    683 uvm_vm_page_to_phys(const struct vm_page *pg)
    684 {
    685 
    686 	return pg->phys_addr & ~(PAGE_SIZE - 1);
    687 }
    688 
    689 /*
    690  * uvm_page_numa_load: load NUMA range description.
    691  */
    692 void
    693 uvm_page_numa_load(paddr_t start, paddr_t size, u_int numa_id)
    694 {
    695 	struct uvm_page_numa_region *d;
    696 
    697 	KASSERT(numa_id < PGFL_MAX_BUCKETS);
    698 
    699 	d = kmem_alloc(sizeof(*d), KM_SLEEP);
    700 	d->start = start;
    701 	d->size = size;
    702 	d->numa_id = numa_id;
    703 	d->next = uvm_page_numa_region;
    704 	uvm_page_numa_region = d;
    705 }
    706 
    707 /*
    708  * uvm_page_numa_lookup: lookup NUMA node for the given page.
    709  */
    710 static u_int
    711 uvm_page_numa_lookup(struct vm_page *pg)
    712 {
    713 	struct uvm_page_numa_region *d;
    714 	static bool warned;
    715 	paddr_t pa;
    716 
    717 	KASSERT(uvm.numa_alloc);
    718 	KASSERT(uvm_page_numa_region != NULL);
    719 
    720 	pa = VM_PAGE_TO_PHYS(pg);
    721 	for (d = uvm_page_numa_region; d != NULL; d = d->next) {
    722 		if (pa >= d->start && pa < d->start + d->size) {
    723 			return d->numa_id;
    724 		}
    725 	}
    726 
    727 	if (!warned) {
    728 		printf("uvm_page_numa_lookup: failed, first pg=%p pa=%#"
    729 		    PRIxPADDR "\n", pg, VM_PAGE_TO_PHYS(pg));
    730 		warned = true;
    731 	}
    732 
    733 	return 0;
    734 }
    735 
    736 /*
    737  * uvm_page_redim: adjust freelist dimensions if they have changed.
    738  */
    739 
    740 static void
    741 uvm_page_redim(int newncolors, int newnbuckets)
    742 {
    743 	struct pgfreelist npgfl;
    744 	struct pgflbucket *opgb, *npgb;
    745 	struct pgflist *ohead, *nhead;
    746 	struct vm_page *pg;
    747 	size_t bucketsize, bucketmemsize, oldbucketmemsize;
    748 	int fl, ob, oc, nb, nc, obuckets, ocolors;
    749 	char *bucketarray, *oldbucketmem, *bucketmem;
    750 
    751 	KASSERT(((newncolors - 1) & newncolors) == 0);
    752 
    753 	/* Anything to do? */
    754 	if (newncolors <= uvmexp.ncolors &&
    755 	    newnbuckets == uvm.bucketcount) {
    756 		return;
    757 	}
    758 	if (uvm.page_init_done == false) {
    759 		uvmexp.ncolors = newncolors;
    760 		return;
    761 	}
    762 
    763 	bucketsize = offsetof(struct pgflbucket, pgb_colors[newncolors]);
    764 	bucketsize = roundup2(bucketsize, coherency_unit);
    765 	bucketmemsize = bucketsize * newnbuckets * VM_NFREELIST +
    766 	    coherency_unit - 1;
    767 	bucketmem = kmem_zalloc(bucketmemsize, KM_SLEEP);
    768 	bucketarray = (char *)roundup2((uintptr_t)bucketmem, coherency_unit);
    769 
    770 	ocolors = uvmexp.ncolors;
    771 	obuckets = uvm.bucketcount;
    772 
    773 	/* Freelist cache musn't be enabled. */
    774 	uvm_pgflcache_pause();
    775 
    776 	/* Make sure we should still do this. */
    777 	uvm_pgfl_lock();
    778 	if (newncolors <= uvmexp.ncolors &&
    779 	    newnbuckets == uvm.bucketcount) {
    780 		uvm_pgfl_unlock();
    781 		uvm_pgflcache_resume();
    782 		kmem_free(bucketmem, bucketmemsize);
    783 		return;
    784 	}
    785 
    786 	uvmexp.ncolors = newncolors;
    787 	uvmexp.colormask = uvmexp.ncolors - 1;
    788 	uvm.bucketcount = newnbuckets;
    789 
    790 	for (fl = 0; fl < VM_NFREELIST; fl++) {
    791 		/* Init new buckets in new freelist. */
    792 		memset(&npgfl, 0, sizeof(npgfl));
    793 		for (nb = 0; nb < newnbuckets; nb++) {
    794 			npgb = (struct pgflbucket *)bucketarray;
    795 			uvm_page_init_bucket(&npgfl, npgb, nb);
    796 			bucketarray += bucketsize;
    797 		}
    798 		/* Now transfer pages from the old freelist. */
    799 		for (nb = ob = 0; ob < obuckets; ob++) {
    800 			opgb = uvm.page_free[fl].pgfl_buckets[ob];
    801 			for (oc = 0; oc < ocolors; oc++) {
    802 				ohead = &opgb->pgb_colors[oc];
    803 				while ((pg = LIST_FIRST(ohead)) != NULL) {
    804 					LIST_REMOVE(pg, pageq.list);
    805 					/*
    806 					 * Here we decide on the NEW color &
    807 					 * bucket for the page.  For NUMA
    808 					 * we'll use the info that the
    809 					 * hardware gave us.  For non-NUMA
    810 					 * assign take physical page frame
    811 					 * number and cache color into
    812 					 * account.  We do this to try and
    813 					 * avoid defeating any memory
    814 					 * interleaving in the hardware.
    815 					 */
    816 					KASSERT(
    817 					    uvm_page_get_bucket(pg) == ob);
    818 					KASSERT(fl ==
    819 					    uvm_page_get_freelist(pg));
    820 					if (uvm.numa_alloc) {
    821 						nb = uvm_page_numa_lookup(pg);
    822 					} else {
    823 						nb = atop(VM_PAGE_TO_PHYS(pg))
    824 						    / uvmexp.ncolors / 8
    825 						    % newnbuckets;
    826 					}
    827 					uvm_page_set_bucket(pg, nb);
    828 					npgb = npgfl.pgfl_buckets[nb];
    829 					npgb->pgb_nfree++;
    830 					nc = VM_PGCOLOR(pg);
    831 					nhead = &npgb->pgb_colors[nc];
    832 					LIST_INSERT_HEAD(nhead, pg, pageq.list);
    833 				}
    834 			}
    835 		}
    836 		/* Install the new freelist. */
    837 		memcpy(&uvm.page_free[fl], &npgfl, sizeof(npgfl));
    838 	}
    839 
    840 	/* Unlock and free the old memory. */
    841 	oldbucketmemsize = recolored_pages_memsize;
    842 	oldbucketmem = recolored_pages_mem;
    843 	recolored_pages_memsize = bucketmemsize;
    844 	recolored_pages_mem = bucketmem;
    845 
    846 	uvm_pgfl_unlock();
    847 	uvm_pgflcache_resume();
    848 
    849 	if (oldbucketmemsize) {
    850 		kmem_free(oldbucketmem, oldbucketmemsize);
    851 	}
    852 
    853 	/*
    854 	 * this calls uvm_km_alloc() which may want to hold
    855 	 * uvm_freelist_lock.
    856 	 */
    857 	uvm_pager_realloc_emerg();
    858 }
    859 
    860 /*
    861  * uvm_page_recolor: Recolor the pages if the new color count is
    862  * larger than the old one.
    863  */
    864 
    865 void
    866 uvm_page_recolor(int newncolors)
    867 {
    868 
    869 	uvm_page_redim(newncolors, uvm.bucketcount);
    870 }
    871 
    872 /*
    873  * uvm_page_rebucket: Determine a bucket structure and redim the free
    874  * lists to match.
    875  */
    876 
    877 void
    878 uvm_page_rebucket(void)
    879 {
    880 	u_int min_numa, max_numa, npackage, shift;
    881 	struct cpu_info *ci, *ci2, *ci3;
    882 	CPU_INFO_ITERATOR cii;
    883 
    884 	/*
    885 	 * If we have more than one NUMA node, and the maximum NUMA node ID
    886 	 * is less than PGFL_MAX_BUCKETS, then we'll use NUMA distribution
    887 	 * for free pages.  uvm_pagefree() will not reassign pages to a
    888 	 * different bucket on free.
    889 	 */
    890 	min_numa = (u_int)-1;
    891 	max_numa = 0;
    892 	for (CPU_INFO_FOREACH(cii, ci)) {
    893 		if (ci->ci_numa_id < min_numa) {
    894 			min_numa = ci->ci_numa_id;
    895 		}
    896 		if (ci->ci_numa_id > max_numa) {
    897 			max_numa = ci->ci_numa_id;
    898 		}
    899 	}
    900 	if (min_numa != max_numa && max_numa < PGFL_MAX_BUCKETS) {
    901 #ifdef NUMA
    902 		/*
    903 		 * We can do this, and it seems to work well, but until
    904 		 * further experiments are done we'll stick with the cache
    905 		 * locality strategy.
    906 		 */
    907 		aprint_debug("UVM: using NUMA allocation scheme\n");
    908 		for (CPU_INFO_FOREACH(cii, ci)) {
    909 			ci->ci_data.cpu_uvm->pgflbucket = ci->ci_numa_id;
    910 		}
    911 		uvm.numa_alloc = true;
    912 	 	uvm_page_redim(uvmexp.ncolors, max_numa + 1);
    913 	 	return;
    914 #endif
    915 	}
    916 
    917 	/*
    918 	 * Otherwise we'll go with a scheme to maximise L2/L3 cache locality
    919 	 * and minimise lock contention.  Count the total number of CPU
    920 	 * packages, and then try to distribute the buckets among CPU
    921 	 * packages evenly.  uvm_pagefree() will reassign pages to the
    922 	 * freeing CPU's preferred bucket on free.
    923 	 */
    924 	npackage = curcpu()->ci_nsibling[CPUREL_PACKAGE1ST];
    925 
    926 	/*
    927 	 * Figure out how to arrange the packages & buckets, and the total
    928 	 * number of buckets we need.  XXX 2 may not be the best factor.
    929 	 */
    930 	for (shift = 0; npackage > PGFL_MAX_BUCKETS; shift++) {
    931 		npackage >>= 1;
    932 	}
    933  	uvm_page_redim(uvmexp.ncolors, npackage);
    934 
    935  	/*
    936  	 * Now tell each CPU which bucket to use.  In the outer loop, scroll
    937  	 * through all CPU packages.
    938  	 */
    939  	npackage = 0;
    940 	ci = curcpu();
    941 	ci2 = ci->ci_sibling[CPUREL_PACKAGE1ST];
    942 	do {
    943 		/*
    944 		 * In the inner loop, scroll through all CPUs in the package
    945 		 * and assign the same bucket ID.
    946 		 */
    947 		ci3 = ci2;
    948 		do {
    949 			ci3->ci_data.cpu_uvm->pgflbucket = npackage >> shift;
    950 			ci3 = ci3->ci_sibling[CPUREL_PACKAGE];
    951 		} while (ci3 != ci2);
    952 		npackage++;
    953 		ci2 = ci2->ci_sibling[CPUREL_PACKAGE1ST];
    954 	} while (ci2 != ci->ci_sibling[CPUREL_PACKAGE1ST]);
    955 
    956 	aprint_debug("UVM: using package allocation scheme, "
    957 	    "%d package(s) per bucket\n", 1 << shift);
    958 }
    959 
    960 /*
    961  * uvm_cpu_attach: initialize per-CPU data structures.
    962  */
    963 
    964 void
    965 uvm_cpu_attach(struct cpu_info *ci)
    966 {
    967 	struct uvm_cpu *ucpu;
    968 
    969 	/* Already done in uvm_page_init(). */
    970 	if (!CPU_IS_PRIMARY(ci)) {
    971 		/* Add more reserve pages for this CPU. */
    972 		uvmexp.reserve_kernel += vm_page_reserve_kernel;
    973 
    974 		/* Allocate per-CPU data structures. */
    975 		ucpu = kmem_zalloc(sizeof(struct uvm_cpu) + coherency_unit - 1,
    976 		    KM_SLEEP);
    977 		ucpu = (struct uvm_cpu *)roundup2((uintptr_t)ucpu,
    978 		    coherency_unit);
    979 		ci->ci_data.cpu_uvm = ucpu;
    980 	} else {
    981 		ucpu = ci->ci_data.cpu_uvm;
    982 	}
    983 
    984 	uvmpdpol_init_cpu(ucpu);
    985 
    986 	/*
    987 	 * Attach RNG source for this CPU's VM events
    988 	 */
    989         rnd_attach_source(&ucpu->rs, ci->ci_data.cpu_name, RND_TYPE_VM,
    990 	    RND_FLAG_COLLECT_TIME|RND_FLAG_COLLECT_VALUE|
    991 	    RND_FLAG_ESTIMATE_VALUE);
    992 }
    993 
    994 /*
    995  * uvm_availmem: fetch the total amount of free memory in pages.  this can
    996  * have a detrimental effect on performance due to false sharing; don't call
    997  * unless needed.
    998  */
    999 
   1000 int
   1001 uvm_availmem(void)
   1002 {
   1003 	struct pgfreelist *pgfl;
   1004 	int fl, b, fpages;
   1005 
   1006 	fpages = 0;
   1007 	for (fl = 0; fl < VM_NFREELIST; fl++) {
   1008 		pgfl = &uvm.page_free[fl];
   1009 		for (b = 0; b < uvm.bucketcount; b++) {
   1010 			fpages += pgfl->pgfl_buckets[b]->pgb_nfree;
   1011 		}
   1012 	}
   1013 	return fpages;
   1014 }
   1015 
   1016 /*
   1017  * uvm_pagealloc_pgb: helper routine that tries to allocate any color from a
   1018  * specific freelist and specific bucket only.
   1019  *
   1020  * => must be at IPL_VM or higher to protect per-CPU data structures.
   1021  */
   1022 
   1023 static struct vm_page *
   1024 uvm_pagealloc_pgb(struct uvm_cpu *ucpu, int f, int b, int *trycolorp, int flags)
   1025 {
   1026 	int c, trycolor, colormask;
   1027 	struct pgflbucket *pgb;
   1028 	struct vm_page *pg;
   1029 	kmutex_t *lock;
   1030 	bool fill;
   1031 
   1032 	/*
   1033 	 * Skip the bucket if empty, no lock needed.  There could be many
   1034 	 * empty freelists/buckets.
   1035 	 */
   1036 	pgb = uvm.page_free[f].pgfl_buckets[b];
   1037 	if (pgb->pgb_nfree == 0) {
   1038 		return NULL;
   1039 	}
   1040 
   1041 	/* Skip bucket if low on memory. */
   1042 	lock = &uvm_freelist_locks[b].lock;
   1043 	mutex_spin_enter(lock);
   1044 	if (__predict_false(pgb->pgb_nfree <= uvmexp.reserve_kernel)) {
   1045 		if ((flags & UVM_PGA_USERESERVE) == 0 ||
   1046 		    (pgb->pgb_nfree <= uvmexp.reserve_pagedaemon &&
   1047 		     curlwp != uvm.pagedaemon_lwp)) {
   1048 			mutex_spin_exit(lock);
   1049 		     	return NULL;
   1050 		}
   1051 		fill = false;
   1052 	} else {
   1053 		fill = true;
   1054 	}
   1055 
   1056 	/* Try all page colors as needed. */
   1057 	c = trycolor = *trycolorp;
   1058 	colormask = uvmexp.colormask;
   1059 	do {
   1060 		pg = LIST_FIRST(&pgb->pgb_colors[c]);
   1061 		if (__predict_true(pg != NULL)) {
   1062 			/*
   1063 			 * Got a free page!  PG_FREE must be cleared under
   1064 			 * lock because of uvm_pglistalloc().
   1065 			 */
   1066 			LIST_REMOVE(pg, pageq.list);
   1067 			KASSERT(pg->flags & PG_FREE);
   1068 			pg->flags &= PG_ZERO;
   1069 			pgb->pgb_nfree--;
   1070 
   1071 			/*
   1072 			 * While we have the bucket locked and our data
   1073 			 * structures fresh in L1 cache, we have an ideal
   1074 			 * opportunity to grab some pages for the freelist
   1075 			 * cache without causing extra contention.  Only do
   1076 			 * so if we found pages in this CPU's preferred
   1077 			 * bucket.
   1078 			 */
   1079 			if (__predict_true(b == ucpu->pgflbucket && fill)) {
   1080 				uvm_pgflcache_fill(ucpu, f, b, c);
   1081 			}
   1082 			mutex_spin_exit(lock);
   1083 			KASSERT(uvm_page_get_bucket(pg) == b);
   1084 			CPU_COUNT(c == trycolor ?
   1085 			    CPU_COUNT_COLORHIT : CPU_COUNT_COLORMISS, 1);
   1086 			CPU_COUNT(CPU_COUNT_CPUMISS, 1);
   1087 			*trycolorp = c;
   1088 			return pg;
   1089 		}
   1090 		c = (c + 1) & colormask;
   1091 	} while (c != trycolor);
   1092 	mutex_spin_exit(lock);
   1093 
   1094 	return NULL;
   1095 }
   1096 
   1097 /*
   1098  * uvm_pagealloc_pgfl: helper routine for uvm_pagealloc_strat that allocates
   1099  * any color from any bucket, in a specific freelist.
   1100  *
   1101  * => must be at IPL_VM or higher to protect per-CPU data structures.
   1102  */
   1103 
   1104 static struct vm_page *
   1105 uvm_pagealloc_pgfl(struct uvm_cpu *ucpu, int f, int *trycolorp, int flags)
   1106 {
   1107 	int b, trybucket, bucketcount;
   1108 	struct vm_page *pg;
   1109 
   1110 	/* Try for the exact thing in the per-CPU cache. */
   1111 	if ((pg = uvm_pgflcache_alloc(ucpu, f, *trycolorp)) != NULL) {
   1112 		CPU_COUNT(CPU_COUNT_CPUHIT, 1);
   1113 		CPU_COUNT(CPU_COUNT_COLORHIT, 1);
   1114 		return pg;
   1115 	}
   1116 
   1117 	/* Walk through all buckets, trying our preferred bucket first. */
   1118 	trybucket = ucpu->pgflbucket;
   1119 	b = trybucket;
   1120 	bucketcount = uvm.bucketcount;
   1121 	do {
   1122 		pg = uvm_pagealloc_pgb(ucpu, f, b, trycolorp, flags);
   1123 		if (pg != NULL) {
   1124 			return pg;
   1125 		}
   1126 		b = (b + 1 == bucketcount ? 0 : b + 1);
   1127 	} while (b != trybucket);
   1128 
   1129 	return NULL;
   1130 }
   1131 
   1132 /*
   1133  * uvm_pagealloc_strat: allocate vm_page from a particular free list.
   1134  *
   1135  * => return null if no pages free
   1136  * => wake up pagedaemon if number of free pages drops below low water mark
   1137  * => if obj != NULL, obj must be locked (to put in obj's tree)
   1138  * => if anon != NULL, anon must be locked (to put in anon)
   1139  * => only one of obj or anon can be non-null
   1140  * => caller must activate/deactivate page if it is not wired.
   1141  * => free_list is ignored if strat == UVM_PGA_STRAT_NORMAL.
   1142  * => policy decision: it is more important to pull a page off of the
   1143  *	appropriate priority free list than it is to get a zero'd or
   1144  *	unknown contents page.  This is because we live with the
   1145  *	consequences of a bad free list decision for the entire
   1146  *	lifetime of the page, e.g. if the page comes from memory that
   1147  *	is slower to access.
   1148  */
   1149 
   1150 struct vm_page *
   1151 uvm_pagealloc_strat(struct uvm_object *obj, voff_t off, struct vm_anon *anon,
   1152     int flags, int strat, int free_list)
   1153 {
   1154 	int zeroit = 0, color;
   1155 	int lcv, error, s;
   1156 	struct uvm_cpu *ucpu;
   1157 	struct vm_page *pg;
   1158 	lwp_t *l;
   1159 
   1160 	KASSERT(obj == NULL || anon == NULL);
   1161 	KASSERT(anon == NULL || (flags & UVM_FLAG_COLORMATCH) || off == 0);
   1162 	KASSERT(off == trunc_page(off));
   1163 	KASSERT(obj == NULL || mutex_owned(obj->vmobjlock));
   1164 	KASSERT(anon == NULL || anon->an_lock == NULL ||
   1165 	    mutex_owned(anon->an_lock));
   1166 
   1167 	/*
   1168 	 * This implements a global round-robin page coloring
   1169 	 * algorithm.
   1170 	 */
   1171 
   1172 	s = splvm();
   1173 	ucpu = curcpu()->ci_data.cpu_uvm;
   1174 	if (flags & UVM_FLAG_COLORMATCH) {
   1175 		color = atop(off) & uvmexp.colormask;
   1176 	} else {
   1177 		color = ucpu->pgflcolor;
   1178 	}
   1179 
   1180 	/*
   1181 	 * fail if any of these conditions is true:
   1182 	 * [1]  there really are no free pages, or
   1183 	 * [2]  only kernel "reserved" pages remain and
   1184 	 *        reserved pages have not been requested.
   1185 	 * [3]  only pagedaemon "reserved" pages remain and
   1186 	 *        the requestor isn't the pagedaemon.
   1187 	 * we make kernel reserve pages available if called by a
   1188 	 * kernel thread or a realtime thread.
   1189 	 */
   1190 	l = curlwp;
   1191 	if (__predict_true(l != NULL) && lwp_eprio(l) >= PRI_KTHREAD) {
   1192 		flags |= UVM_PGA_USERESERVE;
   1193 	}
   1194 
   1195 	/* If the allocator's running in NUMA mode, go with NUMA strategy. */
   1196 	if (uvm.numa_alloc && strat == UVM_PGA_STRAT_NORMAL) {
   1197 		strat = UVM_PGA_STRAT_NUMA;
   1198 	}
   1199 
   1200  again:
   1201 	switch (strat) {
   1202 	case UVM_PGA_STRAT_NORMAL:
   1203 		/* Check freelists: descending priority (ascending id) order. */
   1204 		for (lcv = 0; lcv < VM_NFREELIST; lcv++) {
   1205 			pg = uvm_pagealloc_pgfl(ucpu, lcv, &color, flags);
   1206 			if (pg != NULL) {
   1207 				goto gotit;
   1208 			}
   1209 		}
   1210 
   1211 		/* No pages free!  Have pagedaemon free some memory. */
   1212 		splx(s);
   1213 		uvm_kick_pdaemon();
   1214 		return NULL;
   1215 
   1216 	case UVM_PGA_STRAT_ONLY:
   1217 	case UVM_PGA_STRAT_FALLBACK:
   1218 		/* Attempt to allocate from the specified free list. */
   1219 		KASSERT(free_list >= 0 && free_list < VM_NFREELIST);
   1220 		pg = uvm_pagealloc_pgfl(ucpu, free_list, &color, flags);
   1221 		if (pg != NULL) {
   1222 			goto gotit;
   1223 		}
   1224 
   1225 		/* Fall back, if possible. */
   1226 		if (strat == UVM_PGA_STRAT_FALLBACK) {
   1227 			strat = UVM_PGA_STRAT_NORMAL;
   1228 			goto again;
   1229 		}
   1230 
   1231 		/* No pages free!  Have pagedaemon free some memory. */
   1232 		splx(s);
   1233 		uvm_kick_pdaemon();
   1234 		return NULL;
   1235 
   1236 	case UVM_PGA_STRAT_NUMA:
   1237 		/*
   1238 		 * NUMA strategy: allocating from the correct bucket is more
   1239 		 * important than observing freelist priority.  Look only to
   1240 		 * the current NUMA node; if that fails, we need to look to
   1241 		 * other NUMA nodes, so retry with the normal strategy.
   1242 		 */
   1243 		for (lcv = 0; lcv < VM_NFREELIST; lcv++) {
   1244 			pg = uvm_pgflcache_alloc(ucpu, lcv, color);
   1245 			if (pg != NULL) {
   1246 				CPU_COUNT(CPU_COUNT_CPUHIT, 1);
   1247 				CPU_COUNT(CPU_COUNT_COLORHIT, 1);
   1248 				goto gotit;
   1249 			}
   1250 			pg = uvm_pagealloc_pgb(ucpu, lcv,
   1251 			    ucpu->pgflbucket, &color, flags);
   1252 			if (pg != NULL) {
   1253 				goto gotit;
   1254 			}
   1255 		}
   1256 		strat = UVM_PGA_STRAT_NORMAL;
   1257 		goto again;
   1258 
   1259 	default:
   1260 		panic("uvm_pagealloc_strat: bad strat %d", strat);
   1261 		/* NOTREACHED */
   1262 	}
   1263 
   1264  gotit:
   1265 	/*
   1266 	 * We now know which color we actually allocated from; set
   1267 	 * the next color accordingly.
   1268 	 */
   1269 
   1270 	ucpu->pgflcolor = (color + 1) & uvmexp.colormask;
   1271 
   1272 	/*
   1273 	 * while still at IPL_VM, update allocation statistics and remember
   1274 	 * if we have to zero the page
   1275 	 */
   1276 
   1277 	if (flags & UVM_PGA_ZERO) {
   1278 		if (pg->flags & PG_ZERO) {
   1279 		    	CPU_COUNT(CPU_COUNT_PGA_ZEROHIT, 1);
   1280 			zeroit = 0;
   1281 		} else {
   1282 		    	CPU_COUNT(CPU_COUNT_PGA_ZEROMISS, 1);
   1283 			zeroit = 1;
   1284 		}
   1285 	}
   1286 	if (pg->flags & PG_ZERO) {
   1287 	    	CPU_COUNT(CPU_COUNT_ZEROPAGES, -1);
   1288 	}
   1289 	if (anon) {
   1290 		CPU_COUNT(CPU_COUNT_ANONPAGES, 1);
   1291 	}
   1292 	splx(s);
   1293 	KASSERT((pg->flags & ~(PG_ZERO|PG_FREE)) == 0);
   1294 
   1295 	/*
   1296 	 * assign the page to the object.  as the page was free, we know
   1297 	 * that pg->uobject and pg->uanon are NULL.  we only need to take
   1298 	 * the page's interlock if we are changing the values.
   1299 	 */
   1300 	if (anon != NULL || obj != NULL) {
   1301 		mutex_enter(&pg->interlock);
   1302 	}
   1303 	pg->offset = off;
   1304 	pg->uobject = obj;
   1305 	pg->uanon = anon;
   1306 	KASSERT(uvm_page_owner_locked_p(pg));
   1307 	pg->flags = PG_BUSY|PG_CLEAN|PG_FAKE;
   1308 	if (anon) {
   1309 		anon->an_page = pg;
   1310 		pg->flags |= PG_ANON;
   1311 		mutex_exit(&pg->interlock);
   1312 	} else if (obj) {
   1313 		uvm_pageinsert_object(obj, pg);
   1314 		mutex_exit(&pg->interlock);
   1315 		error = uvm_pageinsert_tree(obj, pg);
   1316 		if (error != 0) {
   1317 			mutex_enter(&pg->interlock);
   1318 			uvm_pageremove_object(obj, pg);
   1319 			mutex_exit(&pg->interlock);
   1320 			uvm_pagefree(pg);
   1321 			return NULL;
   1322 		}
   1323 	}
   1324 
   1325 #if defined(UVM_PAGE_TRKOWN)
   1326 	pg->owner_tag = NULL;
   1327 #endif
   1328 	UVM_PAGE_OWN(pg, "new alloc");
   1329 
   1330 	if (flags & UVM_PGA_ZERO) {
   1331 		/*
   1332 		 * A zero'd page is not clean.  If we got a page not already
   1333 		 * zero'd, then we have to zero it ourselves.
   1334 		 */
   1335 		pg->flags &= ~PG_CLEAN;
   1336 		if (zeroit)
   1337 			pmap_zero_page(VM_PAGE_TO_PHYS(pg));
   1338 	}
   1339 
   1340 	return(pg);
   1341 }
   1342 
   1343 /*
   1344  * uvm_pagereplace: replace a page with another
   1345  *
   1346  * => object must be locked
   1347  * => page interlocks must be held
   1348  */
   1349 
   1350 void
   1351 uvm_pagereplace(struct vm_page *oldpg, struct vm_page *newpg)
   1352 {
   1353 	struct uvm_object *uobj = oldpg->uobject;
   1354 	struct vm_page *pg __diagused;
   1355 
   1356 	KASSERT((oldpg->flags & PG_TABLED) != 0);
   1357 	KASSERT(uobj != NULL);
   1358 	KASSERT((newpg->flags & PG_TABLED) == 0);
   1359 	KASSERT(newpg->uobject == NULL);
   1360 	KASSERT(mutex_owned(uobj->vmobjlock));
   1361 	KASSERT(mutex_owned(&oldpg->interlock));
   1362 	KASSERT(mutex_owned(&newpg->interlock));
   1363 
   1364 	newpg->offset = oldpg->offset;
   1365 	pg = radix_tree_replace_node(&uobj->uo_pages,
   1366 	    newpg->offset >> PAGE_SHIFT, newpg);
   1367 	KASSERT(pg == oldpg);
   1368 
   1369 	newpg->uobject = uobj;
   1370 	uvm_pageinsert_object(uobj, newpg);
   1371 	uvm_pageremove_object(uobj, oldpg);
   1372 }
   1373 
   1374 /*
   1375  * uvm_pagerealloc: reallocate a page from one object to another
   1376  *
   1377  * => both objects must be locked
   1378  * => both interlocks must be held
   1379  */
   1380 
   1381 void
   1382 uvm_pagerealloc(struct vm_page *pg, struct uvm_object *newobj, voff_t newoff)
   1383 {
   1384 	/*
   1385 	 * remove it from the old object
   1386 	 */
   1387 
   1388 	if (pg->uobject) {
   1389 		uvm_pageremove_tree(pg->uobject, pg);
   1390 		uvm_pageremove_object(pg->uobject, pg);
   1391 	}
   1392 
   1393 	/*
   1394 	 * put it in the new object
   1395 	 */
   1396 
   1397 	if (newobj) {
   1398 		/*
   1399 		 * XXX we have no in-tree users of this functionality
   1400 		 */
   1401 		panic("uvm_pagerealloc: no impl");
   1402 	}
   1403 }
   1404 
   1405 #ifdef DEBUG
   1406 /*
   1407  * check if page is zero-filled
   1408  */
   1409 void
   1410 uvm_pagezerocheck(struct vm_page *pg)
   1411 {
   1412 	int *p, *ep;
   1413 
   1414 	KASSERT(uvm_zerocheckkva != 0);
   1415 
   1416 	/*
   1417 	 * XXX assuming pmap_kenter_pa and pmap_kremove never call
   1418 	 * uvm page allocator.
   1419 	 *
   1420 	 * it might be better to have "CPU-local temporary map" pmap interface.
   1421 	 */
   1422 	pmap_kenter_pa(uvm_zerocheckkva, VM_PAGE_TO_PHYS(pg), VM_PROT_READ, 0);
   1423 	p = (int *)uvm_zerocheckkva;
   1424 	ep = (int *)((char *)p + PAGE_SIZE);
   1425 	pmap_update(pmap_kernel());
   1426 	while (p < ep) {
   1427 		if (*p != 0)
   1428 			panic("PG_ZERO page isn't zero-filled");
   1429 		p++;
   1430 	}
   1431 	pmap_kremove(uvm_zerocheckkva, PAGE_SIZE);
   1432 	/*
   1433 	 * pmap_update() is not necessary here because no one except us
   1434 	 * uses this VA.
   1435 	 */
   1436 }
   1437 #endif /* DEBUG */
   1438 
   1439 /*
   1440  * uvm_pagefree: free page
   1441  *
   1442  * => erase page's identity (i.e. remove from object)
   1443  * => put page on free list
   1444  * => caller must lock owning object (either anon or uvm_object)
   1445  * => assumes all valid mappings of pg are gone
   1446  */
   1447 
   1448 void
   1449 uvm_pagefree(struct vm_page *pg)
   1450 {
   1451 	struct pgfreelist *pgfl;
   1452 	struct pgflbucket *pgb;
   1453 	struct uvm_cpu *ucpu;
   1454 	kmutex_t *lock;
   1455 	int bucket, s;
   1456 	bool locked;
   1457 
   1458 #ifdef DEBUG
   1459 	if (pg->uobject == (void *)0xdeadbeef &&
   1460 	    pg->uanon == (void *)0xdeadbeef) {
   1461 		panic("uvm_pagefree: freeing free page %p", pg);
   1462 	}
   1463 #endif /* DEBUG */
   1464 
   1465 	KASSERT((pg->flags & PG_PAGEOUT) == 0);
   1466 	KASSERT(!(pg->flags & PG_FREE));
   1467 	KASSERT(pg->uobject == NULL || mutex_owned(pg->uobject->vmobjlock));
   1468 	KASSERT(pg->uobject != NULL || pg->uanon == NULL ||
   1469 		mutex_owned(pg->uanon->an_lock));
   1470 
   1471 	/*
   1472 	 * remove the page from the object's tree beore acquiring any page
   1473 	 * interlocks: this can acquire locks to free radixtree nodes.
   1474 	 */
   1475 	if (pg->uobject != NULL) {
   1476 		uvm_pageremove_tree(pg->uobject, pg);
   1477 	}
   1478 
   1479 	/*
   1480 	 * if the page is loaned, resolve the loan instead of freeing.
   1481 	 */
   1482 
   1483 	if (pg->loan_count) {
   1484 		KASSERT(pg->wire_count == 0);
   1485 
   1486 		/*
   1487 		 * if the page is owned by an anon then we just want to
   1488 		 * drop anon ownership.  the kernel will free the page when
   1489 		 * it is done with it.  if the page is owned by an object,
   1490 		 * remove it from the object and mark it dirty for the benefit
   1491 		 * of possible anon owners.
   1492 		 *
   1493 		 * regardless of previous ownership, wakeup any waiters,
   1494 		 * unbusy the page, and we're done.
   1495 		 */
   1496 
   1497 		uvm_pagelock(pg);
   1498 		locked = true;
   1499 		if (pg->uobject != NULL) {
   1500 			uvm_pageremove_object(pg->uobject, pg);
   1501 			pg->flags &= ~PG_CLEAN;
   1502 		} else if (pg->uanon != NULL) {
   1503 			if ((pg->flags & PG_ANON) == 0) {
   1504 				pg->loan_count--;
   1505 			} else {
   1506 				pg->flags &= ~PG_ANON;
   1507 				cpu_count(CPU_COUNT_ANONPAGES, -1);
   1508 			}
   1509 			pg->uanon->an_page = NULL;
   1510 			pg->uanon = NULL;
   1511 		}
   1512 		if (pg->flags & PG_WANTED) {
   1513 			wakeup(pg);
   1514 		}
   1515 		pg->flags &= ~(PG_WANTED|PG_BUSY|PG_RELEASED|PG_PAGER1);
   1516 #ifdef UVM_PAGE_TRKOWN
   1517 		pg->owner_tag = NULL;
   1518 #endif
   1519 		if (pg->loan_count) {
   1520 			KASSERT(pg->uobject == NULL);
   1521 			if (pg->uanon == NULL) {
   1522 				uvm_pagedequeue(pg);
   1523 			}
   1524 			uvm_pageunlock(pg);
   1525 			return;
   1526 		}
   1527 	} else if (pg->uobject != NULL || pg->uanon != NULL ||
   1528 	           pg->wire_count != 0) {
   1529 		uvm_pagelock(pg);
   1530 		locked = true;
   1531 	} else {
   1532 		locked = false;
   1533 	}
   1534 
   1535 	/*
   1536 	 * remove page from its object or anon.
   1537 	 */
   1538 	if (pg->uobject != NULL) {
   1539 		uvm_pageremove_object(pg->uobject, pg);
   1540 	} else if (pg->uanon != NULL) {
   1541 		pg->uanon->an_page = NULL;
   1542 		pg->uanon = NULL;
   1543 		cpu_count(CPU_COUNT_ANONPAGES, -1);
   1544 	}
   1545 
   1546 	/*
   1547 	 * if the page was wired, unwire it now.
   1548 	 */
   1549 
   1550 	if (pg->wire_count) {
   1551 		pg->wire_count = 0;
   1552 		atomic_dec_uint(&uvmexp.wired);
   1553 	}
   1554 	if (locked) {
   1555 		/*
   1556 		 * now remove the page from the queues.
   1557 		 */
   1558 		uvm_pagedequeue(pg);
   1559 		uvm_pageunlock(pg);
   1560 	} else {
   1561 		KASSERT(!uvmpdpol_pageisqueued_p(pg));
   1562 	}
   1563 
   1564 	/*
   1565 	 * and put on free queue
   1566 	 */
   1567 
   1568 #ifdef DEBUG
   1569 	pg->uobject = (void *)0xdeadbeef;
   1570 	pg->uanon = (void *)0xdeadbeef;
   1571 	if (pg->flags & PG_ZERO)
   1572 		uvm_pagezerocheck(pg);
   1573 #endif /* DEBUG */
   1574 
   1575 	/* Try to send the page to the per-CPU cache. */
   1576 	s = splvm();
   1577 	ucpu = curcpu()->ci_data.cpu_uvm;
   1578 	bucket = uvm_page_get_bucket(pg);
   1579 	if (bucket == ucpu->pgflbucket && uvm_pgflcache_free(ucpu, pg)) {
   1580 		splx(s);
   1581 		return;
   1582 	}
   1583 
   1584 	/* Didn't work.  Never mind, send it to a global bucket. */
   1585 	pgfl = &uvm.page_free[uvm_page_get_freelist(pg)];
   1586 	pgb = pgfl->pgfl_buckets[bucket];
   1587 	lock = &uvm_freelist_locks[bucket].lock;
   1588 
   1589 	mutex_spin_enter(lock);
   1590 	/* PG_FREE must be set under lock because of uvm_pglistalloc(). */
   1591 	pg->flags = (pg->flags & PG_ZERO) | PG_FREE;
   1592 	LIST_INSERT_HEAD(&pgb->pgb_colors[VM_PGCOLOR(pg)], pg, pageq.list);
   1593 	pgb->pgb_nfree++;
   1594 	mutex_spin_exit(lock);
   1595 	splx(s);
   1596 }
   1597 
   1598 /*
   1599  * uvm_page_unbusy: unbusy an array of pages.
   1600  *
   1601  * => pages must either all belong to the same object, or all belong to anons.
   1602  * => if pages are object-owned, object must be locked.
   1603  * => if pages are anon-owned, anons must be locked.
   1604  * => caller must make sure that anon-owned pages are not PG_RELEASED.
   1605  */
   1606 
   1607 void
   1608 uvm_page_unbusy(struct vm_page **pgs, int npgs)
   1609 {
   1610 	struct vm_page *pg;
   1611 	int i;
   1612 	UVMHIST_FUNC("uvm_page_unbusy"); UVMHIST_CALLED(ubchist);
   1613 
   1614 	for (i = 0; i < npgs; i++) {
   1615 		pg = pgs[i];
   1616 		if (pg == NULL || pg == PGO_DONTCARE) {
   1617 			continue;
   1618 		}
   1619 
   1620 		KASSERT(uvm_page_owner_locked_p(pg));
   1621 		KASSERT(pg->flags & PG_BUSY);
   1622 		KASSERT((pg->flags & PG_PAGEOUT) == 0);
   1623 		if (pg->flags & PG_WANTED) {
   1624 			/* XXXAD thundering herd problem. */
   1625 			wakeup(pg);
   1626 		}
   1627 		if (pg->flags & PG_RELEASED) {
   1628 			UVMHIST_LOG(ubchist, "releasing pg %#jx",
   1629 			    (uintptr_t)pg, 0, 0, 0);
   1630 			KASSERT(pg->uobject != NULL ||
   1631 			    (pg->uanon != NULL && pg->uanon->an_ref > 0));
   1632 			pg->flags &= ~PG_RELEASED;
   1633 			uvm_pagefree(pg);
   1634 		} else {
   1635 			UVMHIST_LOG(ubchist, "unbusying pg %#jx",
   1636 			    (uintptr_t)pg, 0, 0, 0);
   1637 			KASSERT((pg->flags & PG_FAKE) == 0);
   1638 			pg->flags &= ~(PG_WANTED|PG_BUSY);
   1639 			UVM_PAGE_OWN(pg, NULL);
   1640 		}
   1641 	}
   1642 }
   1643 
   1644 #if defined(UVM_PAGE_TRKOWN)
   1645 /*
   1646  * uvm_page_own: set or release page ownership
   1647  *
   1648  * => this is a debugging function that keeps track of who sets PG_BUSY
   1649  *	and where they do it.   it can be used to track down problems
   1650  *	such a process setting "PG_BUSY" and never releasing it.
   1651  * => page's object [if any] must be locked
   1652  * => if "tag" is NULL then we are releasing page ownership
   1653  */
   1654 void
   1655 uvm_page_own(struct vm_page *pg, const char *tag)
   1656 {
   1657 
   1658 	KASSERT((pg->flags & (PG_PAGEOUT|PG_RELEASED)) == 0);
   1659 	KASSERT((pg->flags & PG_WANTED) == 0);
   1660 	KASSERT(uvm_page_owner_locked_p(pg));
   1661 
   1662 	/* gain ownership? */
   1663 	if (tag) {
   1664 		KASSERT((pg->flags & PG_BUSY) != 0);
   1665 		if (pg->owner_tag) {
   1666 			printf("uvm_page_own: page %p already owned "
   1667 			    "by proc %d [%s]\n", pg,
   1668 			    pg->owner, pg->owner_tag);
   1669 			panic("uvm_page_own");
   1670 		}
   1671 		pg->owner = curproc->p_pid;
   1672 		pg->lowner = curlwp->l_lid;
   1673 		pg->owner_tag = tag;
   1674 		return;
   1675 	}
   1676 
   1677 	/* drop ownership */
   1678 	KASSERT((pg->flags & PG_BUSY) == 0);
   1679 	if (pg->owner_tag == NULL) {
   1680 		printf("uvm_page_own: dropping ownership of an non-owned "
   1681 		    "page (%p)\n", pg);
   1682 		panic("uvm_page_own");
   1683 	}
   1684 	pg->owner_tag = NULL;
   1685 }
   1686 #endif
   1687 
   1688 /*
   1689  * uvm_pageidlezero: zero free pages while the system is idle.
   1690  */
   1691 void
   1692 uvm_pageidlezero(void)
   1693 {
   1694 
   1695 	/*
   1696 	 * Disabled for the moment.  Previous strategy too cache heavy.  In
   1697 	 * the future we may experiment with zeroing the pages held in the
   1698 	 * per-CPU cache (uvm_pgflcache).
   1699 	 */
   1700 }
   1701 
   1702 /*
   1703  * uvm_pagelookup: look up a page
   1704  *
   1705  * => caller should lock object to keep someone from pulling the page
   1706  *	out from under it
   1707  */
   1708 
   1709 struct vm_page *
   1710 uvm_pagelookup(struct uvm_object *obj, voff_t off)
   1711 {
   1712 	struct vm_page *pg;
   1713 
   1714 	/* No - used from DDB. KASSERT(mutex_owned(obj->vmobjlock)); */
   1715 
   1716 	pg = radix_tree_lookup_node(&obj->uo_pages, off >> PAGE_SHIFT);
   1717 
   1718 	KASSERT(pg == NULL || obj->uo_npages != 0);
   1719 	KASSERT(pg == NULL || (pg->flags & (PG_RELEASED|PG_PAGEOUT)) == 0 ||
   1720 		(pg->flags & PG_BUSY) != 0);
   1721 	return pg;
   1722 }
   1723 
   1724 /*
   1725  * uvm_pagewire: wire the page, thus removing it from the daemon's grasp
   1726  *
   1727  * => caller must lock objects
   1728  * => caller must hold pg->interlock
   1729  */
   1730 
   1731 void
   1732 uvm_pagewire(struct vm_page *pg)
   1733 {
   1734 
   1735 	KASSERT(uvm_page_owner_locked_p(pg));
   1736 	KASSERT(mutex_owned(&pg->interlock));
   1737 #if defined(READAHEAD_STATS)
   1738 	if ((pg->flags & PG_READAHEAD) != 0) {
   1739 		uvm_ra_hit.ev_count++;
   1740 		pg->flags &= ~PG_READAHEAD;
   1741 	}
   1742 #endif /* defined(READAHEAD_STATS) */
   1743 	if (pg->wire_count == 0) {
   1744 		uvm_pagedequeue(pg);
   1745 		atomic_inc_uint(&uvmexp.wired);
   1746 	}
   1747 	pg->wire_count++;
   1748 	KASSERT(pg->wire_count > 0);	/* detect wraparound */
   1749 }
   1750 
   1751 /*
   1752  * uvm_pageunwire: unwire the page.
   1753  *
   1754  * => activate if wire count goes to zero.
   1755  * => caller must lock objects
   1756  * => caller must hold pg->interlock
   1757  */
   1758 
   1759 void
   1760 uvm_pageunwire(struct vm_page *pg)
   1761 {
   1762 
   1763 	KASSERT(uvm_page_owner_locked_p(pg));
   1764 	KASSERT(pg->wire_count != 0);
   1765 	KASSERT(!uvmpdpol_pageisqueued_p(pg));
   1766 	KASSERT(mutex_owned(&pg->interlock));
   1767 	pg->wire_count--;
   1768 	if (pg->wire_count == 0) {
   1769 		uvm_pageactivate(pg);
   1770 		KASSERT(uvmexp.wired != 0);
   1771 		atomic_dec_uint(&uvmexp.wired);
   1772 	}
   1773 }
   1774 
   1775 /*
   1776  * uvm_pagedeactivate: deactivate page
   1777  *
   1778  * => caller must lock objects
   1779  * => caller must check to make sure page is not wired
   1780  * => object that page belongs to must be locked (so we can adjust pg->flags)
   1781  * => caller must clear the reference on the page before calling
   1782  * => caller must hold pg->interlock
   1783  */
   1784 
   1785 void
   1786 uvm_pagedeactivate(struct vm_page *pg)
   1787 {
   1788 
   1789 	KASSERT(uvm_page_owner_locked_p(pg));
   1790 	KASSERT(mutex_owned(&pg->interlock));
   1791 	if (pg->wire_count == 0) {
   1792 		KASSERT(uvmpdpol_pageisqueued_p(pg));
   1793 		uvmpdpol_pagedeactivate(pg);
   1794 	}
   1795 }
   1796 
   1797 /*
   1798  * uvm_pageactivate: activate page
   1799  *
   1800  * => caller must lock objects
   1801  * => caller must hold pg->interlock
   1802  */
   1803 
   1804 void
   1805 uvm_pageactivate(struct vm_page *pg)
   1806 {
   1807 
   1808 	KASSERT(uvm_page_owner_locked_p(pg));
   1809 	KASSERT(mutex_owned(&pg->interlock));
   1810 #if defined(READAHEAD_STATS)
   1811 	if ((pg->flags & PG_READAHEAD) != 0) {
   1812 		uvm_ra_hit.ev_count++;
   1813 		pg->flags &= ~PG_READAHEAD;
   1814 	}
   1815 #endif /* defined(READAHEAD_STATS) */
   1816 	if (pg->wire_count == 0) {
   1817 		uvmpdpol_pageactivate(pg);
   1818 	}
   1819 }
   1820 
   1821 /*
   1822  * uvm_pagedequeue: remove a page from any paging queue
   1823  *
   1824  * => caller must lock objects
   1825  * => caller must hold pg->interlock
   1826  */
   1827 void
   1828 uvm_pagedequeue(struct vm_page *pg)
   1829 {
   1830 
   1831 	KASSERT(uvm_page_owner_locked_p(pg));
   1832 	KASSERT(mutex_owned(&pg->interlock));
   1833 	if (uvmpdpol_pageisqueued_p(pg)) {
   1834 		uvmpdpol_pagedequeue(pg);
   1835 	}
   1836 }
   1837 
   1838 /*
   1839  * uvm_pageenqueue: add a page to a paging queue without activating.
   1840  * used where a page is not really demanded (yet).  eg. read-ahead
   1841  *
   1842  * => caller must lock objects
   1843  * => caller must hold pg->interlock
   1844  */
   1845 void
   1846 uvm_pageenqueue(struct vm_page *pg)
   1847 {
   1848 
   1849 	KASSERT(uvm_page_owner_locked_p(pg));
   1850 	KASSERT(mutex_owned(&pg->interlock));
   1851 	if (pg->wire_count == 0 && !uvmpdpol_pageisqueued_p(pg)) {
   1852 		uvmpdpol_pageenqueue(pg);
   1853 	}
   1854 }
   1855 
   1856 /*
   1857  * uvm_pagelock: acquire page interlock
   1858  */
   1859 void
   1860 uvm_pagelock(struct vm_page *pg)
   1861 {
   1862 
   1863 	mutex_enter(&pg->interlock);
   1864 }
   1865 
   1866 /*
   1867  * uvm_pagelock2: acquire two page interlocks
   1868  */
   1869 void
   1870 uvm_pagelock2(struct vm_page *pg1, struct vm_page *pg2)
   1871 {
   1872 
   1873 	if (pg1 < pg2) {
   1874 		mutex_enter(&pg1->interlock);
   1875 		mutex_enter(&pg2->interlock);
   1876 	} else {
   1877 		mutex_enter(&pg2->interlock);
   1878 		mutex_enter(&pg1->interlock);
   1879 	}
   1880 }
   1881 
   1882 /*
   1883  * uvm_pageunlock: release page interlock, and if a page replacement intent
   1884  * is set on the page, pass it to uvmpdpol to make real.
   1885  *
   1886  * => caller must hold pg->interlock
   1887  */
   1888 void
   1889 uvm_pageunlock(struct vm_page *pg)
   1890 {
   1891 
   1892 	if ((pg->pqflags & PQ_INTENT_SET) == 0 ||
   1893 	    (pg->pqflags & PQ_INTENT_QUEUED) != 0) {
   1894 	    	mutex_exit(&pg->interlock);
   1895 	    	return;
   1896 	}
   1897 	pg->pqflags |= PQ_INTENT_QUEUED;
   1898 	mutex_exit(&pg->interlock);
   1899 	uvmpdpol_pagerealize(pg);
   1900 }
   1901 
   1902 /*
   1903  * uvm_pageunlock2: release two page interlocks, and for both pages if a
   1904  * page replacement intent is set on the page, pass it to uvmpdpol to make
   1905  * real.
   1906  *
   1907  * => caller must hold pg->interlock
   1908  */
   1909 void
   1910 uvm_pageunlock2(struct vm_page *pg1, struct vm_page *pg2)
   1911 {
   1912 
   1913 	if ((pg1->pqflags & PQ_INTENT_SET) == 0 ||
   1914 	    (pg1->pqflags & PQ_INTENT_QUEUED) != 0) {
   1915 	    	mutex_exit(&pg1->interlock);
   1916 	    	pg1 = NULL;
   1917 	} else {
   1918 		pg1->pqflags |= PQ_INTENT_QUEUED;
   1919 		mutex_exit(&pg1->interlock);
   1920 	}
   1921 
   1922 	if ((pg2->pqflags & PQ_INTENT_SET) == 0 ||
   1923 	    (pg2->pqflags & PQ_INTENT_QUEUED) != 0) {
   1924 	    	mutex_exit(&pg2->interlock);
   1925 	    	pg2 = NULL;
   1926 	} else {
   1927 		pg2->pqflags |= PQ_INTENT_QUEUED;
   1928 		mutex_exit(&pg2->interlock);
   1929 	}
   1930 
   1931 	if (pg1 != NULL) {
   1932 		uvmpdpol_pagerealize(pg1);
   1933 	}
   1934 	if (pg2 != NULL) {
   1935 		uvmpdpol_pagerealize(pg2);
   1936 	}
   1937 }
   1938 
   1939 /*
   1940  * uvm_pagezero: zero fill a page
   1941  *
   1942  * => if page is part of an object then the object should be locked
   1943  *	to protect pg->flags.
   1944  */
   1945 
   1946 void
   1947 uvm_pagezero(struct vm_page *pg)
   1948 {
   1949 	pg->flags &= ~PG_CLEAN;
   1950 	pmap_zero_page(VM_PAGE_TO_PHYS(pg));
   1951 }
   1952 
   1953 /*
   1954  * uvm_pagecopy: copy a page
   1955  *
   1956  * => if page is part of an object then the object should be locked
   1957  *	to protect pg->flags.
   1958  */
   1959 
   1960 void
   1961 uvm_pagecopy(struct vm_page *src, struct vm_page *dst)
   1962 {
   1963 
   1964 	dst->flags &= ~PG_CLEAN;
   1965 	pmap_copy_page(VM_PAGE_TO_PHYS(src), VM_PAGE_TO_PHYS(dst));
   1966 }
   1967 
   1968 /*
   1969  * uvm_pageismanaged: test it see that a page (specified by PA) is managed.
   1970  */
   1971 
   1972 bool
   1973 uvm_pageismanaged(paddr_t pa)
   1974 {
   1975 
   1976 	return (uvm_physseg_find(atop(pa), NULL) != UVM_PHYSSEG_TYPE_INVALID);
   1977 }
   1978 
   1979 /*
   1980  * uvm_page_lookup_freelist: look up the free list for the specified page
   1981  */
   1982 
   1983 int
   1984 uvm_page_lookup_freelist(struct vm_page *pg)
   1985 {
   1986 	uvm_physseg_t upm;
   1987 
   1988 	upm = uvm_physseg_find(atop(VM_PAGE_TO_PHYS(pg)), NULL);
   1989 	KASSERT(upm != UVM_PHYSSEG_TYPE_INVALID);
   1990 	return uvm_physseg_get_free_list(upm);
   1991 }
   1992 
   1993 /*
   1994  * uvm_page_owner_locked_p: return true if object associated with page is
   1995  * locked.  this is a weak check for runtime assertions only.
   1996  */
   1997 
   1998 bool
   1999 uvm_page_owner_locked_p(struct vm_page *pg)
   2000 {
   2001 
   2002 	if (pg->uobject != NULL) {
   2003 		return mutex_owned(pg->uobject->vmobjlock);
   2004 	}
   2005 	if (pg->uanon != NULL) {
   2006 		return mutex_owned(pg->uanon->an_lock);
   2007 	}
   2008 	return true;
   2009 }
   2010 
   2011 #ifdef PMAP_DIRECT
   2012 /*
   2013  * Call pmap to translate physical address into a virtual and to run a callback
   2014  * for it. Used to avoid actually mapping the pages, pmap most likely uses direct map
   2015  * or equivalent.
   2016  */
   2017 int
   2018 uvm_direct_process(struct vm_page **pgs, u_int npages, voff_t off, vsize_t len,
   2019             int (*process)(void *, size_t, void *), void *arg)
   2020 {
   2021 	int error = 0;
   2022 	paddr_t pa;
   2023 	size_t todo;
   2024 	voff_t pgoff = (off & PAGE_MASK);
   2025 	struct vm_page *pg;
   2026 
   2027 	KASSERT(npages > 0 && len > 0);
   2028 
   2029 	for (int i = 0; i < npages; i++) {
   2030 		pg = pgs[i];
   2031 
   2032 		KASSERT(len > 0);
   2033 
   2034 		/*
   2035 		 * Caller is responsible for ensuring all the pages are
   2036 		 * available.
   2037 		 */
   2038 		KASSERT(pg != NULL && pg != PGO_DONTCARE);
   2039 
   2040 		pa = VM_PAGE_TO_PHYS(pg);
   2041 		todo = MIN(len, PAGE_SIZE - pgoff);
   2042 
   2043 		error = pmap_direct_process(pa, pgoff, todo, process, arg);
   2044 		if (error)
   2045 			break;
   2046 
   2047 		pgoff = 0;
   2048 		len -= todo;
   2049 	}
   2050 
   2051 	KASSERTMSG(error != 0 || len == 0, "len %lu != 0 for non-error", len);
   2052 	return error;
   2053 }
   2054 #endif /* PMAP_DIRECT */
   2055 
   2056 #if defined(DDB) || defined(DEBUGPRINT)
   2057 
   2058 /*
   2059  * uvm_page_printit: actually print the page
   2060  */
   2061 
   2062 static const char page_flagbits[] = UVM_PGFLAGBITS;
   2063 
   2064 void
   2065 uvm_page_printit(struct vm_page *pg, bool full,
   2066     void (*pr)(const char *, ...))
   2067 {
   2068 	struct vm_page *tpg;
   2069 	struct uvm_object *uobj;
   2070 	struct pgflbucket *pgb;
   2071 	struct pgflist *pgl;
   2072 	char pgbuf[128];
   2073 
   2074 	(*pr)("PAGE %p:\n", pg);
   2075 	snprintb(pgbuf, sizeof(pgbuf), page_flagbits, pg->flags);
   2076 	(*pr)("  flags=%s, pqflags=%x, wire_count=%d, pa=0x%lx\n",
   2077 	    pgbuf, pg->pqflags, pg->wire_count, (long)VM_PAGE_TO_PHYS(pg));
   2078 	(*pr)("  uobject=%p, uanon=%p, offset=0x%llx loan_count=%d\n",
   2079 	    pg->uobject, pg->uanon, (long long)pg->offset, pg->loan_count);
   2080 	(*pr)("  bucket=%d freelist=%d\n",
   2081 	    uvm_page_get_bucket(pg), uvm_page_get_freelist(pg));
   2082 #if defined(UVM_PAGE_TRKOWN)
   2083 	if (pg->flags & PG_BUSY)
   2084 		(*pr)("  owning process = %d, tag=%s\n",
   2085 		    pg->owner, pg->owner_tag);
   2086 	else
   2087 		(*pr)("  page not busy, no owner\n");
   2088 #else
   2089 	(*pr)("  [page ownership tracking disabled]\n");
   2090 #endif
   2091 
   2092 	if (!full)
   2093 		return;
   2094 
   2095 	/* cross-verify object/anon */
   2096 	if ((pg->flags & PG_FREE) == 0) {
   2097 		if (pg->flags & PG_ANON) {
   2098 			if (pg->uanon == NULL || pg->uanon->an_page != pg)
   2099 			    (*pr)("  >>> ANON DOES NOT POINT HERE <<< (%p)\n",
   2100 				(pg->uanon) ? pg->uanon->an_page : NULL);
   2101 			else
   2102 				(*pr)("  anon backpointer is OK\n");
   2103 		} else {
   2104 			uobj = pg->uobject;
   2105 			if (uobj) {
   2106 				(*pr)("  checking object list\n");
   2107 				tpg = uvm_pagelookup(uobj, pg->offset);
   2108 				if (tpg)
   2109 					(*pr)("  page found on object list\n");
   2110 				else
   2111 			(*pr)("  >>> PAGE NOT FOUND ON OBJECT LIST! <<<\n");
   2112 			}
   2113 		}
   2114 	}
   2115 
   2116 	/* cross-verify page queue */
   2117 	if (pg->flags & PG_FREE) {
   2118 		int fl = uvm_page_get_freelist(pg);
   2119 		int b = uvm_page_get_bucket(pg);
   2120 		pgb = uvm.page_free[fl].pgfl_buckets[b];
   2121 		pgl = &pgb->pgb_colors[VM_PGCOLOR(pg)];
   2122 		(*pr)("  checking pageq list\n");
   2123 		LIST_FOREACH(tpg, pgl, pageq.list) {
   2124 			if (tpg == pg) {
   2125 				break;
   2126 			}
   2127 		}
   2128 		if (tpg)
   2129 			(*pr)("  page found on pageq list\n");
   2130 		else
   2131 			(*pr)("  >>> PAGE NOT FOUND ON PAGEQ LIST! <<<\n");
   2132 	}
   2133 }
   2134 
   2135 /*
   2136  * uvm_page_printall - print a summary of all managed pages
   2137  */
   2138 
   2139 void
   2140 uvm_page_printall(void (*pr)(const char *, ...))
   2141 {
   2142 	uvm_physseg_t i;
   2143 	paddr_t pfn;
   2144 	struct vm_page *pg;
   2145 
   2146 	(*pr)("%18s %4s %4s %18s %18s"
   2147 #ifdef UVM_PAGE_TRKOWN
   2148 	    " OWNER"
   2149 #endif
   2150 	    "\n", "PAGE", "FLAG", "PQ", "UOBJECT", "UANON");
   2151 	for (i = uvm_physseg_get_first();
   2152 	     uvm_physseg_valid_p(i);
   2153 	     i = uvm_physseg_get_next(i)) {
   2154 		for (pfn = uvm_physseg_get_start(i);
   2155 		     pfn < uvm_physseg_get_end(i);
   2156 		     pfn++) {
   2157 			pg = PHYS_TO_VM_PAGE(ptoa(pfn));
   2158 
   2159 			(*pr)("%18p %04x %08x %18p %18p",
   2160 			    pg, pg->flags, pg->pqflags, pg->uobject,
   2161 			    pg->uanon);
   2162 #ifdef UVM_PAGE_TRKOWN
   2163 			if (pg->flags & PG_BUSY)
   2164 				(*pr)(" %d [%s]", pg->owner, pg->owner_tag);
   2165 #endif
   2166 			(*pr)("\n");
   2167 		}
   2168 	}
   2169 }
   2170 
   2171 /*
   2172  * uvm_page_print_freelists - print a summary freelists
   2173  */
   2174 
   2175 void
   2176 uvm_page_print_freelists(void (*pr)(const char *, ...))
   2177 {
   2178 	struct pgfreelist *pgfl;
   2179 	struct pgflbucket *pgb;
   2180 	int fl, b, c;
   2181 
   2182 	(*pr)("There are %d freelists with %d buckets of %d colors.\n\n",
   2183 	    VM_NFREELIST, uvm.bucketcount, uvmexp.ncolors);
   2184 
   2185 	for (fl = 0; fl < VM_NFREELIST; fl++) {
   2186 		pgfl = &uvm.page_free[fl];
   2187 		(*pr)("freelist(%d) @ %p\n", fl, pgfl);
   2188 		for (b = 0; b < uvm.bucketcount; b++) {
   2189 			pgb = uvm.page_free[fl].pgfl_buckets[b];
   2190 			(*pr)("    bucket(%d) @ %p, nfree = %d, lock @ %p:\n",
   2191 			    b, pgb, pgb->pgb_nfree,
   2192 			    &uvm_freelist_locks[b].lock);
   2193 			for (c = 0; c < uvmexp.ncolors; c++) {
   2194 				(*pr)("        color(%d) @ %p, ", c,
   2195 				    &pgb->pgb_colors[c]);
   2196 				(*pr)("first page = %p\n",
   2197 				    LIST_FIRST(&pgb->pgb_colors[c]));
   2198 			}
   2199 		}
   2200 	}
   2201 }
   2202 
   2203 #endif /* DDB || DEBUGPRINT */
   2204