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