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