Home | History | Annotate | Line # | Download | only in uvm
uvm_page.c revision 1.82
      1 /*	$NetBSD: uvm_page.c,v 1.82 2003/01/27 02:10:20 enami Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1997 Charles D. Cranor and Washington University.
      5  * Copyright (c) 1991, 1993, The Regents of the University of California.
      6  *
      7  * All rights reserved.
      8  *
      9  * This code is derived from software contributed to Berkeley by
     10  * The Mach Operating System project at Carnegie-Mellon University.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by Charles D. Cranor,
     23  *      Washington University, the University of California, Berkeley and
     24  *      its contributors.
     25  * 4. Neither the name of the University nor the names of its contributors
     26  *    may be used to endorse or promote products derived from this software
     27  *    without specific prior written permission.
     28  *
     29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     39  * SUCH DAMAGE.
     40  *
     41  *	@(#)vm_page.c   8.3 (Berkeley) 3/21/94
     42  * from: Id: uvm_page.c,v 1.1.2.18 1998/02/06 05:24:42 chs Exp
     43  *
     44  *
     45  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
     46  * All rights reserved.
     47  *
     48  * Permission to use, copy, modify and distribute this software and
     49  * its documentation is hereby granted, provided that both the copyright
     50  * notice and this permission notice appear in all copies of the
     51  * software, derivative works or modified versions, and any portions
     52  * thereof, and that both notices appear in supporting documentation.
     53  *
     54  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
     55  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
     56  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
     57  *
     58  * Carnegie Mellon requests users of this software to return to
     59  *
     60  *  Software Distribution Coordinator  or  Software.Distribution (at) CS.CMU.EDU
     61  *  School of Computer Science
     62  *  Carnegie Mellon University
     63  *  Pittsburgh PA 15213-3890
     64  *
     65  * any improvements or extensions that they make and grant Carnegie the
     66  * rights to redistribute these changes.
     67  */
     68 
     69 /*
     70  * uvm_page.c: page ops.
     71  */
     72 
     73 #include <sys/cdefs.h>
     74 __KERNEL_RCSID(0, "$NetBSD: uvm_page.c,v 1.82 2003/01/27 02:10:20 enami Exp $");
     75 
     76 #include "opt_uvmhist.h"
     77 
     78 #include <sys/param.h>
     79 #include <sys/systm.h>
     80 #include <sys/malloc.h>
     81 #include <sys/sched.h>
     82 #include <sys/kernel.h>
     83 #include <sys/vnode.h>
     84 #include <sys/proc.h>
     85 
     86 #define UVM_PAGE                /* pull in uvm_page.h functions */
     87 #include <uvm/uvm.h>
     88 
     89 /*
     90  * global vars... XXXCDC: move to uvm. structure.
     91  */
     92 
     93 /*
     94  * physical memory config is stored in vm_physmem.
     95  */
     96 
     97 struct vm_physseg vm_physmem[VM_PHYSSEG_MAX];	/* XXXCDC: uvm.physmem */
     98 int vm_nphysseg = 0;				/* XXXCDC: uvm.nphysseg */
     99 
    100 /*
    101  * Some supported CPUs in a given architecture don't support all
    102  * of the things necessary to do idle page zero'ing efficiently.
    103  * We therefore provide a way to disable it from machdep code here.
    104  */
    105 /*
    106  * XXX disabled until we can find a way to do this without causing
    107  * problems for either cpu caches or DMA latency.
    108  */
    109 boolean_t vm_page_zero_enable = FALSE;
    110 
    111 /*
    112  * local variables
    113  */
    114 
    115 /*
    116  * these variables record the values returned by vm_page_bootstrap,
    117  * for debugging purposes.  The implementation of uvm_pageboot_alloc
    118  * and pmap_startup here also uses them internally.
    119  */
    120 
    121 static vaddr_t      virtual_space_start;
    122 static vaddr_t      virtual_space_end;
    123 
    124 /*
    125  * we use a hash table with only one bucket during bootup.  we will
    126  * later rehash (resize) the hash table once the allocator is ready.
    127  * we static allocate the one bootstrap bucket below...
    128  */
    129 
    130 static struct pglist uvm_bootbucket;
    131 
    132 /*
    133  * we allocate an initial number of page colors in uvm_page_init(),
    134  * and remember them.  We may re-color pages as cache sizes are
    135  * discovered during the autoconfiguration phase.  But we can never
    136  * free the initial set of buckets, since they are allocated using
    137  * uvm_pageboot_alloc().
    138  */
    139 
    140 static boolean_t have_recolored_pages /* = FALSE */;
    141 
    142 /*
    143  * local prototypes
    144  */
    145 
    146 static void uvm_pageinsert __P((struct vm_page *));
    147 static void uvm_pageremove __P((struct vm_page *));
    148 
    149 /*
    150  * inline functions
    151  */
    152 
    153 /*
    154  * uvm_pageinsert: insert a page in the object and the hash table
    155  *
    156  * => caller must lock object
    157  * => caller must lock page queues
    158  * => call should have already set pg's object and offset pointers
    159  *    and bumped the version counter
    160  */
    161 
    162 __inline static void
    163 uvm_pageinsert(pg)
    164 	struct vm_page *pg;
    165 {
    166 	struct pglist *buck;
    167 	struct uvm_object *uobj = pg->uobject;
    168 
    169 	KASSERT((pg->flags & PG_TABLED) == 0);
    170 	buck = &uvm.page_hash[uvm_pagehash(uobj, pg->offset)];
    171 	simple_lock(&uvm.hashlock);
    172 	TAILQ_INSERT_TAIL(buck, pg, hashq);
    173 	simple_unlock(&uvm.hashlock);
    174 
    175 	if (UVM_OBJ_IS_AOBJ(uobj)) {
    176 		uvmexp.anonpages++;
    177 	}
    178 
    179 	TAILQ_INSERT_TAIL(&uobj->memq, pg, listq);
    180 	pg->flags |= PG_TABLED;
    181 	uobj->uo_npages++;
    182 }
    183 
    184 /*
    185  * uvm_page_remove: remove page from object and hash
    186  *
    187  * => caller must lock object
    188  * => caller must lock page queues
    189  */
    190 
    191 static __inline void
    192 uvm_pageremove(pg)
    193 	struct vm_page *pg;
    194 {
    195 	struct pglist *buck;
    196 	struct uvm_object *uobj = pg->uobject;
    197 
    198 	KASSERT(pg->flags & PG_TABLED);
    199 	buck = &uvm.page_hash[uvm_pagehash(uobj, pg->offset)];
    200 	simple_lock(&uvm.hashlock);
    201 	TAILQ_REMOVE(buck, pg, hashq);
    202 	simple_unlock(&uvm.hashlock);
    203 
    204 	if (UVM_OBJ_IS_VTEXT(uobj)) {
    205 		uvmexp.execpages--;
    206 	} else if (UVM_OBJ_IS_VNODE(uobj)) {
    207 		uvmexp.filepages--;
    208 	} else if (UVM_OBJ_IS_AOBJ(uobj)) {
    209 		uvmexp.anonpages--;
    210 	}
    211 
    212 	/* object should be locked */
    213 	uobj->uo_npages--;
    214 	TAILQ_REMOVE(&uobj->memq, pg, listq);
    215 	pg->flags &= ~PG_TABLED;
    216 	pg->uobject = NULL;
    217 }
    218 
    219 static void
    220 uvm_page_init_buckets(struct pgfreelist *pgfl)
    221 {
    222 	int color, i;
    223 
    224 	for (color = 0; color < uvmexp.ncolors; color++) {
    225 		for (i = 0; i < PGFL_NQUEUES; i++) {
    226 			TAILQ_INIT(&pgfl->pgfl_buckets[
    227 			    color].pgfl_queues[i]);
    228 		}
    229 	}
    230 }
    231 
    232 /*
    233  * uvm_page_init: init the page system.   called from uvm_init().
    234  *
    235  * => we return the range of kernel virtual memory in kvm_startp/kvm_endp
    236  */
    237 
    238 void
    239 uvm_page_init(kvm_startp, kvm_endp)
    240 	vaddr_t *kvm_startp, *kvm_endp;
    241 {
    242 	vsize_t freepages, pagecount, bucketcount, n;
    243 	struct pgflbucket *bucketarray;
    244 	struct vm_page *pagearray;
    245 	int lcv;
    246 	u_int i;
    247 	paddr_t paddr;
    248 
    249 	/*
    250 	 * init the page queues and page queue locks, except the free
    251 	 * list; we allocate that later (with the initial vm_page
    252 	 * structures).
    253 	 */
    254 
    255 	TAILQ_INIT(&uvm.page_active);
    256 	TAILQ_INIT(&uvm.page_inactive);
    257 	simple_lock_init(&uvm.pageqlock);
    258 	simple_lock_init(&uvm.fpageqlock);
    259 
    260 	/*
    261 	 * init the <obj,offset> => <page> hash table.  for now
    262 	 * we just have one bucket (the bootstrap bucket).  later on we
    263 	 * will allocate new buckets as we dynamically resize the hash table.
    264 	 */
    265 
    266 	uvm.page_nhash = 1;			/* 1 bucket */
    267 	uvm.page_hashmask = 0;			/* mask for hash function */
    268 	uvm.page_hash = &uvm_bootbucket;	/* install bootstrap bucket */
    269 	TAILQ_INIT(uvm.page_hash);		/* init hash table */
    270 	simple_lock_init(&uvm.hashlock);	/* init hash table lock */
    271 
    272 	/*
    273 	 * allocate vm_page structures.
    274 	 */
    275 
    276 	/*
    277 	 * sanity check:
    278 	 * before calling this function the MD code is expected to register
    279 	 * some free RAM with the uvm_page_physload() function.   our job
    280 	 * now is to allocate vm_page structures for this memory.
    281 	 */
    282 
    283 	if (vm_nphysseg == 0)
    284 		panic("uvm_page_bootstrap: no memory pre-allocated");
    285 
    286 	/*
    287 	 * first calculate the number of free pages...
    288 	 *
    289 	 * note that we use start/end rather than avail_start/avail_end.
    290 	 * this allows us to allocate extra vm_page structures in case we
    291 	 * want to return some memory to the pool after booting.
    292 	 */
    293 
    294 	freepages = 0;
    295 	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
    296 		freepages += (vm_physmem[lcv].end - vm_physmem[lcv].start);
    297 
    298 	/*
    299 	 * Let MD code initialize the number of colors, or default
    300 	 * to 1 color if MD code doesn't care.
    301 	 */
    302 	if (uvmexp.ncolors == 0)
    303 		uvmexp.ncolors = 1;
    304 	uvmexp.colormask = uvmexp.ncolors - 1;
    305 
    306 	/*
    307 	 * we now know we have (PAGE_SIZE * freepages) bytes of memory we can
    308 	 * use.   for each page of memory we use we need a vm_page structure.
    309 	 * thus, the total number of pages we can use is the total size of
    310 	 * the memory divided by the PAGE_SIZE plus the size of the vm_page
    311 	 * structure.   we add one to freepages as a fudge factor to avoid
    312 	 * truncation errors (since we can only allocate in terms of whole
    313 	 * pages).
    314 	 */
    315 
    316 	bucketcount = uvmexp.ncolors * VM_NFREELIST;
    317 	pagecount = ((freepages + 1) << PAGE_SHIFT) /
    318 	    (PAGE_SIZE + sizeof(struct vm_page));
    319 
    320 	bucketarray = (void *)uvm_pageboot_alloc((bucketcount *
    321 	    sizeof(struct pgflbucket)) + (pagecount *
    322 	    sizeof(struct vm_page)));
    323 	pagearray = (struct vm_page *)(bucketarray + bucketcount);
    324 
    325 	for (lcv = 0; lcv < VM_NFREELIST; lcv++) {
    326 		uvm.page_free[lcv].pgfl_buckets =
    327 		    (bucketarray + (lcv * uvmexp.ncolors));
    328 		uvm_page_init_buckets(&uvm.page_free[lcv]);
    329 	}
    330 	memset(pagearray, 0, pagecount * sizeof(struct vm_page));
    331 
    332 	/*
    333 	 * init the vm_page structures and put them in the correct place.
    334 	 */
    335 
    336 	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++) {
    337 		n = vm_physmem[lcv].end - vm_physmem[lcv].start;
    338 
    339 		/* set up page array pointers */
    340 		vm_physmem[lcv].pgs = pagearray;
    341 		pagearray += n;
    342 		pagecount -= n;
    343 		vm_physmem[lcv].lastpg = vm_physmem[lcv].pgs + (n - 1);
    344 
    345 		/* init and free vm_pages (we've already zeroed them) */
    346 		paddr = ptoa(vm_physmem[lcv].start);
    347 		for (i = 0 ; i < n ; i++, paddr += PAGE_SIZE) {
    348 			vm_physmem[lcv].pgs[i].phys_addr = paddr;
    349 #ifdef __HAVE_VM_PAGE_MD
    350 			VM_MDPAGE_INIT(&vm_physmem[lcv].pgs[i]);
    351 #endif
    352 			if (atop(paddr) >= vm_physmem[lcv].avail_start &&
    353 			    atop(paddr) <= vm_physmem[lcv].avail_end) {
    354 				uvmexp.npages++;
    355 				/* add page to free pool */
    356 				uvm_pagefree(&vm_physmem[lcv].pgs[i]);
    357 			}
    358 		}
    359 	}
    360 
    361 	/*
    362 	 * pass up the values of virtual_space_start and
    363 	 * virtual_space_end (obtained by uvm_pageboot_alloc) to the upper
    364 	 * layers of the VM.
    365 	 */
    366 
    367 	*kvm_startp = round_page(virtual_space_start);
    368 	*kvm_endp = trunc_page(virtual_space_end);
    369 
    370 	/*
    371 	 * init locks for kernel threads
    372 	 */
    373 
    374 	simple_lock_init(&uvm.pagedaemon_lock);
    375 	simple_lock_init(&uvm.aiodoned_lock);
    376 
    377 	/*
    378 	 * init various thresholds.
    379 	 */
    380 
    381 	uvmexp.reserve_pagedaemon = 1;
    382 	uvmexp.reserve_kernel = 5;
    383 	uvmexp.anonminpct = 10;
    384 	uvmexp.fileminpct = 10;
    385 	uvmexp.execminpct = 5;
    386 	uvmexp.anonmaxpct = 80;
    387 	uvmexp.filemaxpct = 50;
    388 	uvmexp.execmaxpct = 30;
    389 	uvmexp.anonmin = uvmexp.anonminpct * 256 / 100;
    390 	uvmexp.filemin = uvmexp.fileminpct * 256 / 100;
    391 	uvmexp.execmin = uvmexp.execminpct * 256 / 100;
    392 	uvmexp.anonmax = uvmexp.anonmaxpct * 256 / 100;
    393 	uvmexp.filemax = uvmexp.filemaxpct * 256 / 100;
    394 	uvmexp.execmax = uvmexp.execmaxpct * 256 / 100;
    395 
    396 	/*
    397 	 * determine if we should zero pages in the idle loop.
    398 	 */
    399 
    400 	uvm.page_idle_zero = vm_page_zero_enable;
    401 
    402 	/*
    403 	 * done!
    404 	 */
    405 
    406 	uvm.page_init_done = TRUE;
    407 }
    408 
    409 /*
    410  * uvm_setpagesize: set the page size
    411  *
    412  * => sets page_shift and page_mask from uvmexp.pagesize.
    413  */
    414 
    415 void
    416 uvm_setpagesize()
    417 {
    418 	if (uvmexp.pagesize == 0)
    419 		uvmexp.pagesize = DEFAULT_PAGE_SIZE;
    420 	uvmexp.pagemask = uvmexp.pagesize - 1;
    421 	if ((uvmexp.pagemask & uvmexp.pagesize) != 0)
    422 		panic("uvm_setpagesize: page size not a power of two");
    423 	for (uvmexp.pageshift = 0; ; uvmexp.pageshift++)
    424 		if ((1 << uvmexp.pageshift) == uvmexp.pagesize)
    425 			break;
    426 }
    427 
    428 /*
    429  * uvm_pageboot_alloc: steal memory from physmem for bootstrapping
    430  */
    431 
    432 vaddr_t
    433 uvm_pageboot_alloc(size)
    434 	vsize_t size;
    435 {
    436 	static boolean_t initialized = FALSE;
    437 	vaddr_t addr;
    438 #if !defined(PMAP_STEAL_MEMORY)
    439 	vaddr_t vaddr;
    440 	paddr_t paddr;
    441 #endif
    442 
    443 	/*
    444 	 * on first call to this function, initialize ourselves.
    445 	 */
    446 	if (initialized == FALSE) {
    447 		pmap_virtual_space(&virtual_space_start, &virtual_space_end);
    448 
    449 		/* round it the way we like it */
    450 		virtual_space_start = round_page(virtual_space_start);
    451 		virtual_space_end = trunc_page(virtual_space_end);
    452 
    453 		initialized = TRUE;
    454 	}
    455 
    456 	/* round to page size */
    457 	size = round_page(size);
    458 
    459 #if defined(PMAP_STEAL_MEMORY)
    460 
    461 	/*
    462 	 * defer bootstrap allocation to MD code (it may want to allocate
    463 	 * from a direct-mapped segment).  pmap_steal_memory should adjust
    464 	 * virtual_space_start/virtual_space_end if necessary.
    465 	 */
    466 
    467 	addr = pmap_steal_memory(size, &virtual_space_start,
    468 	    &virtual_space_end);
    469 
    470 	return(addr);
    471 
    472 #else /* !PMAP_STEAL_MEMORY */
    473 
    474 	/*
    475 	 * allocate virtual memory for this request
    476 	 */
    477 	if (virtual_space_start == virtual_space_end ||
    478 	    (virtual_space_end - virtual_space_start) < size)
    479 		panic("uvm_pageboot_alloc: out of virtual space");
    480 
    481 	addr = virtual_space_start;
    482 
    483 #ifdef PMAP_GROWKERNEL
    484 	/*
    485 	 * If the kernel pmap can't map the requested space,
    486 	 * then allocate more resources for it.
    487 	 */
    488 	if (uvm_maxkaddr < (addr + size)) {
    489 		uvm_maxkaddr = pmap_growkernel(addr + size);
    490 		if (uvm_maxkaddr < (addr + size))
    491 			panic("uvm_pageboot_alloc: pmap_growkernel() failed");
    492 	}
    493 #endif
    494 
    495 	virtual_space_start += size;
    496 
    497 	/*
    498 	 * allocate and mapin physical pages to back new virtual pages
    499 	 */
    500 
    501 	for (vaddr = round_page(addr) ; vaddr < addr + size ;
    502 	    vaddr += PAGE_SIZE) {
    503 
    504 		if (!uvm_page_physget(&paddr))
    505 			panic("uvm_pageboot_alloc: out of memory");
    506 
    507 		/*
    508 		 * Note this memory is no longer managed, so using
    509 		 * pmap_kenter is safe.
    510 		 */
    511 		pmap_kenter_pa(vaddr, paddr, VM_PROT_READ|VM_PROT_WRITE);
    512 	}
    513 	pmap_update(pmap_kernel());
    514 	return(addr);
    515 #endif	/* PMAP_STEAL_MEMORY */
    516 }
    517 
    518 #if !defined(PMAP_STEAL_MEMORY)
    519 /*
    520  * uvm_page_physget: "steal" one page from the vm_physmem structure.
    521  *
    522  * => attempt to allocate it off the end of a segment in which the "avail"
    523  *    values match the start/end values.   if we can't do that, then we
    524  *    will advance both values (making them equal, and removing some
    525  *    vm_page structures from the non-avail area).
    526  * => return false if out of memory.
    527  */
    528 
    529 /* subroutine: try to allocate from memory chunks on the specified freelist */
    530 static boolean_t uvm_page_physget_freelist __P((paddr_t *, int));
    531 
    532 static boolean_t
    533 uvm_page_physget_freelist(paddrp, freelist)
    534 	paddr_t *paddrp;
    535 	int freelist;
    536 {
    537 	int lcv, x;
    538 
    539 	/* pass 1: try allocating from a matching end */
    540 #if (VM_PHYSSEG_STRAT == VM_PSTRAT_BIGFIRST)
    541 	for (lcv = vm_nphysseg - 1 ; lcv >= 0 ; lcv--)
    542 #else
    543 	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
    544 #endif
    545 	{
    546 
    547 		if (uvm.page_init_done == TRUE)
    548 			panic("uvm_page_physget: called _after_ bootstrap");
    549 
    550 		if (vm_physmem[lcv].free_list != freelist)
    551 			continue;
    552 
    553 		/* try from front */
    554 		if (vm_physmem[lcv].avail_start == vm_physmem[lcv].start &&
    555 		    vm_physmem[lcv].avail_start < vm_physmem[lcv].avail_end) {
    556 			*paddrp = ptoa(vm_physmem[lcv].avail_start);
    557 			vm_physmem[lcv].avail_start++;
    558 			vm_physmem[lcv].start++;
    559 			/* nothing left?   nuke it */
    560 			if (vm_physmem[lcv].avail_start ==
    561 			    vm_physmem[lcv].end) {
    562 				if (vm_nphysseg == 1)
    563 				    panic("vum_page_physget: out of memory!");
    564 				vm_nphysseg--;
    565 				for (x = lcv ; x < vm_nphysseg ; x++)
    566 					/* structure copy */
    567 					vm_physmem[x] = vm_physmem[x+1];
    568 			}
    569 			return (TRUE);
    570 		}
    571 
    572 		/* try from rear */
    573 		if (vm_physmem[lcv].avail_end == vm_physmem[lcv].end &&
    574 		    vm_physmem[lcv].avail_start < vm_physmem[lcv].avail_end) {
    575 			*paddrp = ptoa(vm_physmem[lcv].avail_end - 1);
    576 			vm_physmem[lcv].avail_end--;
    577 			vm_physmem[lcv].end--;
    578 			/* nothing left?   nuke it */
    579 			if (vm_physmem[lcv].avail_end ==
    580 			    vm_physmem[lcv].start) {
    581 				if (vm_nphysseg == 1)
    582 				    panic("uvm_page_physget: out of memory!");
    583 				vm_nphysseg--;
    584 				for (x = lcv ; x < vm_nphysseg ; x++)
    585 					/* structure copy */
    586 					vm_physmem[x] = vm_physmem[x+1];
    587 			}
    588 			return (TRUE);
    589 		}
    590 	}
    591 
    592 	/* pass2: forget about matching ends, just allocate something */
    593 #if (VM_PHYSSEG_STRAT == VM_PSTRAT_BIGFIRST)
    594 	for (lcv = vm_nphysseg - 1 ; lcv >= 0 ; lcv--)
    595 #else
    596 	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
    597 #endif
    598 	{
    599 
    600 		/* any room in this bank? */
    601 		if (vm_physmem[lcv].avail_start >= vm_physmem[lcv].avail_end)
    602 			continue;  /* nope */
    603 
    604 		*paddrp = ptoa(vm_physmem[lcv].avail_start);
    605 		vm_physmem[lcv].avail_start++;
    606 		/* truncate! */
    607 		vm_physmem[lcv].start = vm_physmem[lcv].avail_start;
    608 
    609 		/* nothing left?   nuke it */
    610 		if (vm_physmem[lcv].avail_start == vm_physmem[lcv].end) {
    611 			if (vm_nphysseg == 1)
    612 				panic("uvm_page_physget: out of memory!");
    613 			vm_nphysseg--;
    614 			for (x = lcv ; x < vm_nphysseg ; x++)
    615 				/* structure copy */
    616 				vm_physmem[x] = vm_physmem[x+1];
    617 		}
    618 		return (TRUE);
    619 	}
    620 
    621 	return (FALSE);        /* whoops! */
    622 }
    623 
    624 boolean_t
    625 uvm_page_physget(paddrp)
    626 	paddr_t *paddrp;
    627 {
    628 	int i;
    629 
    630 	/* try in the order of freelist preference */
    631 	for (i = 0; i < VM_NFREELIST; i++)
    632 		if (uvm_page_physget_freelist(paddrp, i) == TRUE)
    633 			return (TRUE);
    634 	return (FALSE);
    635 }
    636 #endif /* PMAP_STEAL_MEMORY */
    637 
    638 /*
    639  * uvm_page_physload: load physical memory into VM system
    640  *
    641  * => all args are PFs
    642  * => all pages in start/end get vm_page structures
    643  * => areas marked by avail_start/avail_end get added to the free page pool
    644  * => we are limited to VM_PHYSSEG_MAX physical memory segments
    645  */
    646 
    647 void
    648 uvm_page_physload(start, end, avail_start, avail_end, free_list)
    649 	paddr_t start, end, avail_start, avail_end;
    650 	int free_list;
    651 {
    652 	int preload, lcv;
    653 	psize_t npages;
    654 	struct vm_page *pgs;
    655 	struct vm_physseg *ps;
    656 
    657 	if (uvmexp.pagesize == 0)
    658 		panic("uvm_page_physload: page size not set!");
    659 	if (free_list >= VM_NFREELIST || free_list < VM_FREELIST_DEFAULT)
    660 		panic("uvm_page_physload: bad free list %d", free_list);
    661 	if (start >= end)
    662 		panic("uvm_page_physload: start >= end");
    663 
    664 	/*
    665 	 * do we have room?
    666 	 */
    667 
    668 	if (vm_nphysseg == VM_PHYSSEG_MAX) {
    669 		printf("uvm_page_physload: unable to load physical memory "
    670 		    "segment\n");
    671 		printf("\t%d segments allocated, ignoring 0x%llx -> 0x%llx\n",
    672 		    VM_PHYSSEG_MAX, (long long)start, (long long)end);
    673 		printf("\tincrease VM_PHYSSEG_MAX\n");
    674 		return;
    675 	}
    676 
    677 	/*
    678 	 * check to see if this is a "preload" (i.e. uvm_mem_init hasn't been
    679 	 * called yet, so malloc is not available).
    680 	 */
    681 
    682 	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++) {
    683 		if (vm_physmem[lcv].pgs)
    684 			break;
    685 	}
    686 	preload = (lcv == vm_nphysseg);
    687 
    688 	/*
    689 	 * if VM is already running, attempt to malloc() vm_page structures
    690 	 */
    691 
    692 	if (!preload) {
    693 #if defined(VM_PHYSSEG_NOADD)
    694 		panic("uvm_page_physload: tried to add RAM after vm_mem_init");
    695 #else
    696 		/* XXXCDC: need some sort of lockout for this case */
    697 		paddr_t paddr;
    698 		npages = end - start;  /* # of pages */
    699 		pgs = malloc(sizeof(struct vm_page) * npages,
    700 		    M_VMPAGE, M_NOWAIT);
    701 		if (pgs == NULL) {
    702 			printf("uvm_page_physload: can not malloc vm_page "
    703 			    "structs for segment\n");
    704 			printf("\tignoring 0x%lx -> 0x%lx\n", start, end);
    705 			return;
    706 		}
    707 		/* zero data, init phys_addr and free_list, and free pages */
    708 		memset(pgs, 0, sizeof(struct vm_page) * npages);
    709 		for (lcv = 0, paddr = ptoa(start) ;
    710 				 lcv < npages ; lcv++, paddr += PAGE_SIZE) {
    711 			pgs[lcv].phys_addr = paddr;
    712 			pgs[lcv].free_list = free_list;
    713 			if (atop(paddr) >= avail_start &&
    714 			    atop(paddr) <= avail_end)
    715 				uvm_pagefree(&pgs[lcv]);
    716 		}
    717 		/* XXXCDC: incomplete: need to update uvmexp.free, what else? */
    718 		/* XXXCDC: need hook to tell pmap to rebuild pv_list, etc... */
    719 #endif
    720 	} else {
    721 		pgs = NULL;
    722 		npages = 0;
    723 	}
    724 
    725 	/*
    726 	 * now insert us in the proper place in vm_physmem[]
    727 	 */
    728 
    729 #if (VM_PHYSSEG_STRAT == VM_PSTRAT_RANDOM)
    730 	/* random: put it at the end (easy!) */
    731 	ps = &vm_physmem[vm_nphysseg];
    732 #elif (VM_PHYSSEG_STRAT == VM_PSTRAT_BSEARCH)
    733 	{
    734 		int x;
    735 		/* sort by address for binary search */
    736 		for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
    737 			if (start < vm_physmem[lcv].start)
    738 				break;
    739 		ps = &vm_physmem[lcv];
    740 		/* move back other entries, if necessary ... */
    741 		for (x = vm_nphysseg ; x > lcv ; x--)
    742 			/* structure copy */
    743 			vm_physmem[x] = vm_physmem[x - 1];
    744 	}
    745 #elif (VM_PHYSSEG_STRAT == VM_PSTRAT_BIGFIRST)
    746 	{
    747 		int x;
    748 		/* sort by largest segment first */
    749 		for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
    750 			if ((end - start) >
    751 			    (vm_physmem[lcv].end - vm_physmem[lcv].start))
    752 				break;
    753 		ps = &vm_physmem[lcv];
    754 		/* move back other entries, if necessary ... */
    755 		for (x = vm_nphysseg ; x > lcv ; x--)
    756 			/* structure copy */
    757 			vm_physmem[x] = vm_physmem[x - 1];
    758 	}
    759 #else
    760 	panic("uvm_page_physload: unknown physseg strategy selected!");
    761 #endif
    762 
    763 	ps->start = start;
    764 	ps->end = end;
    765 	ps->avail_start = avail_start;
    766 	ps->avail_end = avail_end;
    767 	if (preload) {
    768 		ps->pgs = NULL;
    769 	} else {
    770 		ps->pgs = pgs;
    771 		ps->lastpg = pgs + npages - 1;
    772 	}
    773 	ps->free_list = free_list;
    774 	vm_nphysseg++;
    775 
    776 	if (!preload)
    777 		uvm_page_rehash();
    778 }
    779 
    780 /*
    781  * uvm_page_rehash: reallocate hash table based on number of free pages.
    782  */
    783 
    784 void
    785 uvm_page_rehash()
    786 {
    787 	int freepages, lcv, bucketcount, oldcount;
    788 	struct pglist *newbuckets, *oldbuckets;
    789 	struct vm_page *pg;
    790 	size_t newsize, oldsize;
    791 
    792 	/*
    793 	 * compute number of pages that can go in the free pool
    794 	 */
    795 
    796 	freepages = 0;
    797 	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
    798 		freepages +=
    799 		    (vm_physmem[lcv].avail_end - vm_physmem[lcv].avail_start);
    800 
    801 	/*
    802 	 * compute number of buckets needed for this number of pages
    803 	 */
    804 
    805 	bucketcount = 1;
    806 	while (bucketcount < freepages)
    807 		bucketcount = bucketcount * 2;
    808 
    809 	/*
    810 	 * compute the size of the current table and new table.
    811 	 */
    812 
    813 	oldbuckets = uvm.page_hash;
    814 	oldcount = uvm.page_nhash;
    815 	oldsize = round_page(sizeof(struct pglist) * oldcount);
    816 	newsize = round_page(sizeof(struct pglist) * bucketcount);
    817 
    818 	/*
    819 	 * allocate the new buckets
    820 	 */
    821 
    822 	newbuckets = (struct pglist *) uvm_km_alloc(kernel_map, newsize);
    823 	if (newbuckets == NULL) {
    824 		printf("uvm_page_physrehash: WARNING: could not grow page "
    825 		    "hash table\n");
    826 		return;
    827 	}
    828 	for (lcv = 0 ; lcv < bucketcount ; lcv++)
    829 		TAILQ_INIT(&newbuckets[lcv]);
    830 
    831 	/*
    832 	 * now replace the old buckets with the new ones and rehash everything
    833 	 */
    834 
    835 	simple_lock(&uvm.hashlock);
    836 	uvm.page_hash = newbuckets;
    837 	uvm.page_nhash = bucketcount;
    838 	uvm.page_hashmask = bucketcount - 1;  /* power of 2 */
    839 
    840 	/* ... and rehash */
    841 	for (lcv = 0 ; lcv < oldcount ; lcv++) {
    842 		while ((pg = oldbuckets[lcv].tqh_first) != NULL) {
    843 			TAILQ_REMOVE(&oldbuckets[lcv], pg, hashq);
    844 			TAILQ_INSERT_TAIL(
    845 			  &uvm.page_hash[uvm_pagehash(pg->uobject, pg->offset)],
    846 			  pg, hashq);
    847 		}
    848 	}
    849 	simple_unlock(&uvm.hashlock);
    850 
    851 	/*
    852 	 * free old bucket array if is not the boot-time table
    853 	 */
    854 
    855 	if (oldbuckets != &uvm_bootbucket)
    856 		uvm_km_free(kernel_map, (vaddr_t) oldbuckets, oldsize);
    857 }
    858 
    859 /*
    860  * uvm_page_recolor: Recolor the pages if the new bucket count is
    861  * larger than the old one.
    862  */
    863 
    864 void
    865 uvm_page_recolor(int newncolors)
    866 {
    867 	struct pgflbucket *bucketarray, *oldbucketarray;
    868 	struct pgfreelist pgfl;
    869 	struct vm_page *pg;
    870 	vsize_t bucketcount;
    871 	int s, lcv, color, i, ocolors;
    872 
    873 	if (newncolors <= uvmexp.ncolors)
    874 		return;
    875 
    876 	if (uvm.page_init_done == FALSE) {
    877 		uvmexp.ncolors = newncolors;
    878 		return;
    879 	}
    880 
    881 	bucketcount = newncolors * VM_NFREELIST;
    882 	bucketarray = malloc(bucketcount * sizeof(struct pgflbucket),
    883 	    M_VMPAGE, M_NOWAIT);
    884 	if (bucketarray == NULL) {
    885 		printf("WARNING: unable to allocate %ld page color buckets\n",
    886 		    (long) bucketcount);
    887 		return;
    888 	}
    889 
    890 	s = uvm_lock_fpageq();
    891 
    892 	/* Make sure we should still do this. */
    893 	if (newncolors <= uvmexp.ncolors) {
    894 		uvm_unlock_fpageq(s);
    895 		free(bucketarray, M_VMPAGE);
    896 		return;
    897 	}
    898 
    899 	oldbucketarray = uvm.page_free[0].pgfl_buckets;
    900 	ocolors = uvmexp.ncolors;
    901 
    902 	uvmexp.ncolors = newncolors;
    903 	uvmexp.colormask = uvmexp.ncolors - 1;
    904 
    905 	for (lcv = 0; lcv < VM_NFREELIST; lcv++) {
    906 		pgfl.pgfl_buckets = (bucketarray + (lcv * newncolors));
    907 		uvm_page_init_buckets(&pgfl);
    908 		for (color = 0; color < ocolors; color++) {
    909 			for (i = 0; i < PGFL_NQUEUES; i++) {
    910 				while ((pg = TAILQ_FIRST(&uvm.page_free[
    911 				    lcv].pgfl_buckets[color].pgfl_queues[i]))
    912 				    != NULL) {
    913 					TAILQ_REMOVE(&uvm.page_free[
    914 					    lcv].pgfl_buckets[
    915 					    color].pgfl_queues[i], pg, pageq);
    916 					TAILQ_INSERT_TAIL(&pgfl.pgfl_buckets[
    917 					    VM_PGCOLOR_BUCKET(pg)].pgfl_queues[
    918 					    i], pg, pageq);
    919 				}
    920 			}
    921 		}
    922 		uvm.page_free[lcv].pgfl_buckets = pgfl.pgfl_buckets;
    923 	}
    924 
    925 	if (have_recolored_pages) {
    926 		uvm_unlock_fpageq(s);
    927 		free(oldbucketarray, M_VMPAGE);
    928 		return;
    929 	}
    930 
    931 	have_recolored_pages = TRUE;
    932 	uvm_unlock_fpageq(s);
    933 }
    934 
    935 /*
    936  * uvm_pagealloc_pgfl: helper routine for uvm_pagealloc_strat
    937  */
    938 
    939 static __inline struct vm_page *
    940 uvm_pagealloc_pgfl(struct pgfreelist *pgfl, int try1, int try2,
    941     int *trycolorp)
    942 {
    943 	struct pglist *freeq;
    944 	struct vm_page *pg;
    945 	int color, trycolor = *trycolorp;
    946 
    947 	color = trycolor;
    948 	do {
    949 		if ((pg = TAILQ_FIRST((freeq =
    950 		    &pgfl->pgfl_buckets[color].pgfl_queues[try1]))) != NULL)
    951 			goto gotit;
    952 		if ((pg = TAILQ_FIRST((freeq =
    953 		    &pgfl->pgfl_buckets[color].pgfl_queues[try2]))) != NULL)
    954 			goto gotit;
    955 		color = (color + 1) & uvmexp.colormask;
    956 	} while (color != trycolor);
    957 
    958 	return (NULL);
    959 
    960  gotit:
    961 	TAILQ_REMOVE(freeq, pg, pageq);
    962 	uvmexp.free--;
    963 
    964 	/* update zero'd page count */
    965 	if (pg->flags & PG_ZERO)
    966 		uvmexp.zeropages--;
    967 
    968 	if (color == trycolor)
    969 		uvmexp.colorhit++;
    970 	else {
    971 		uvmexp.colormiss++;
    972 		*trycolorp = color;
    973 	}
    974 
    975 	return (pg);
    976 }
    977 
    978 /*
    979  * uvm_pagealloc_strat: allocate vm_page from a particular free list.
    980  *
    981  * => return null if no pages free
    982  * => wake up pagedaemon if number of free pages drops below low water mark
    983  * => if obj != NULL, obj must be locked (to put in hash)
    984  * => if anon != NULL, anon must be locked (to put in anon)
    985  * => only one of obj or anon can be non-null
    986  * => caller must activate/deactivate page if it is not wired.
    987  * => free_list is ignored if strat == UVM_PGA_STRAT_NORMAL.
    988  * => policy decision: it is more important to pull a page off of the
    989  *	appropriate priority free list than it is to get a zero'd or
    990  *	unknown contents page.  This is because we live with the
    991  *	consequences of a bad free list decision for the entire
    992  *	lifetime of the page, e.g. if the page comes from memory that
    993  *	is slower to access.
    994  */
    995 
    996 struct vm_page *
    997 uvm_pagealloc_strat(obj, off, anon, flags, strat, free_list)
    998 	struct uvm_object *obj;
    999 	voff_t off;
   1000 	int flags;
   1001 	struct vm_anon *anon;
   1002 	int strat, free_list;
   1003 {
   1004 	int lcv, try1, try2, s, zeroit = 0, color;
   1005 	struct vm_page *pg;
   1006 	boolean_t use_reserve;
   1007 
   1008 	KASSERT(obj == NULL || anon == NULL);
   1009 	KASSERT(off == trunc_page(off));
   1010 	LOCK_ASSERT(obj == NULL || simple_lock_held(&obj->vmobjlock));
   1011 	LOCK_ASSERT(anon == NULL || simple_lock_held(&anon->an_lock));
   1012 
   1013 	s = uvm_lock_fpageq();
   1014 
   1015 	/*
   1016 	 * This implements a global round-robin page coloring
   1017 	 * algorithm.
   1018 	 *
   1019 	 * XXXJRT: Should we make the `nextcolor' per-cpu?
   1020 	 * XXXJRT: What about virtually-indexed caches?
   1021 	 */
   1022 
   1023 	color = uvm.page_free_nextcolor;
   1024 
   1025 	/*
   1026 	 * check to see if we need to generate some free pages waking
   1027 	 * the pagedaemon.
   1028 	 */
   1029 
   1030 	UVM_KICK_PDAEMON();
   1031 
   1032 	/*
   1033 	 * fail if any of these conditions is true:
   1034 	 * [1]  there really are no free pages, or
   1035 	 * [2]  only kernel "reserved" pages remain and
   1036 	 *        the page isn't being allocated to a kernel object.
   1037 	 * [3]  only pagedaemon "reserved" pages remain and
   1038 	 *        the requestor isn't the pagedaemon.
   1039 	 */
   1040 
   1041 	use_reserve = (flags & UVM_PGA_USERESERVE) ||
   1042 		(obj && UVM_OBJ_IS_KERN_OBJECT(obj));
   1043 	if ((uvmexp.free <= uvmexp.reserve_kernel && !use_reserve) ||
   1044 	    (uvmexp.free <= uvmexp.reserve_pagedaemon &&
   1045 	     !(use_reserve && curproc == uvm.pagedaemon_proc)))
   1046 		goto fail;
   1047 
   1048 #if PGFL_NQUEUES != 2
   1049 #error uvm_pagealloc_strat needs to be updated
   1050 #endif
   1051 
   1052 	/*
   1053 	 * If we want a zero'd page, try the ZEROS queue first, otherwise
   1054 	 * we try the UNKNOWN queue first.
   1055 	 */
   1056 	if (flags & UVM_PGA_ZERO) {
   1057 		try1 = PGFL_ZEROS;
   1058 		try2 = PGFL_UNKNOWN;
   1059 	} else {
   1060 		try1 = PGFL_UNKNOWN;
   1061 		try2 = PGFL_ZEROS;
   1062 	}
   1063 
   1064  again:
   1065 	switch (strat) {
   1066 	case UVM_PGA_STRAT_NORMAL:
   1067 		/* Check all freelists in descending priority order. */
   1068 		for (lcv = 0; lcv < VM_NFREELIST; lcv++) {
   1069 			pg = uvm_pagealloc_pgfl(&uvm.page_free[lcv],
   1070 			    try1, try2, &color);
   1071 			if (pg != NULL)
   1072 				goto gotit;
   1073 		}
   1074 
   1075 		/* No pages free! */
   1076 		goto fail;
   1077 
   1078 	case UVM_PGA_STRAT_ONLY:
   1079 	case UVM_PGA_STRAT_FALLBACK:
   1080 		/* Attempt to allocate from the specified free list. */
   1081 		KASSERT(free_list >= 0 && free_list < VM_NFREELIST);
   1082 		pg = uvm_pagealloc_pgfl(&uvm.page_free[free_list],
   1083 		    try1, try2, &color);
   1084 		if (pg != NULL)
   1085 			goto gotit;
   1086 
   1087 		/* Fall back, if possible. */
   1088 		if (strat == UVM_PGA_STRAT_FALLBACK) {
   1089 			strat = UVM_PGA_STRAT_NORMAL;
   1090 			goto again;
   1091 		}
   1092 
   1093 		/* No pages free! */
   1094 		goto fail;
   1095 
   1096 	default:
   1097 		panic("uvm_pagealloc_strat: bad strat %d", strat);
   1098 		/* NOTREACHED */
   1099 	}
   1100 
   1101  gotit:
   1102 	/*
   1103 	 * We now know which color we actually allocated from; set
   1104 	 * the next color accordingly.
   1105 	 */
   1106 
   1107 	uvm.page_free_nextcolor = (color + 1) & uvmexp.colormask;
   1108 
   1109 	/*
   1110 	 * update allocation statistics and remember if we have to
   1111 	 * zero the page
   1112 	 */
   1113 
   1114 	if (flags & UVM_PGA_ZERO) {
   1115 		if (pg->flags & PG_ZERO) {
   1116 			uvmexp.pga_zerohit++;
   1117 			zeroit = 0;
   1118 		} else {
   1119 			uvmexp.pga_zeromiss++;
   1120 			zeroit = 1;
   1121 		}
   1122 	}
   1123 	uvm_unlock_fpageq(s);
   1124 
   1125 	pg->offset = off;
   1126 	pg->uobject = obj;
   1127 	pg->uanon = anon;
   1128 	pg->flags = PG_BUSY|PG_CLEAN|PG_FAKE;
   1129 	if (anon) {
   1130 		anon->u.an_page = pg;
   1131 		pg->pqflags = PQ_ANON;
   1132 		uvmexp.anonpages++;
   1133 	} else {
   1134 		if (obj) {
   1135 			uvm_pageinsert(pg);
   1136 		}
   1137 		pg->pqflags = 0;
   1138 	}
   1139 #if defined(UVM_PAGE_TRKOWN)
   1140 	pg->owner_tag = NULL;
   1141 #endif
   1142 	UVM_PAGE_OWN(pg, "new alloc");
   1143 
   1144 	if (flags & UVM_PGA_ZERO) {
   1145 		/*
   1146 		 * A zero'd page is not clean.  If we got a page not already
   1147 		 * zero'd, then we have to zero it ourselves.
   1148 		 */
   1149 		pg->flags &= ~PG_CLEAN;
   1150 		if (zeroit)
   1151 			pmap_zero_page(VM_PAGE_TO_PHYS(pg));
   1152 	}
   1153 
   1154 	return(pg);
   1155 
   1156  fail:
   1157 	uvm_unlock_fpageq(s);
   1158 	return (NULL);
   1159 }
   1160 
   1161 /*
   1162  * uvm_pagerealloc: reallocate a page from one object to another
   1163  *
   1164  * => both objects must be locked
   1165  */
   1166 
   1167 void
   1168 uvm_pagerealloc(pg, newobj, newoff)
   1169 	struct vm_page *pg;
   1170 	struct uvm_object *newobj;
   1171 	voff_t newoff;
   1172 {
   1173 	/*
   1174 	 * remove it from the old object
   1175 	 */
   1176 
   1177 	if (pg->uobject) {
   1178 		uvm_pageremove(pg);
   1179 	}
   1180 
   1181 	/*
   1182 	 * put it in the new object
   1183 	 */
   1184 
   1185 	if (newobj) {
   1186 		pg->uobject = newobj;
   1187 		pg->offset = newoff;
   1188 		uvm_pageinsert(pg);
   1189 	}
   1190 }
   1191 
   1192 /*
   1193  * uvm_pagefree: free page
   1194  *
   1195  * => erase page's identity (i.e. remove from hash/object)
   1196  * => put page on free list
   1197  * => caller must lock owning object (either anon or uvm_object)
   1198  * => caller must lock page queues
   1199  * => assumes all valid mappings of pg are gone
   1200  */
   1201 
   1202 void
   1203 uvm_pagefree(pg)
   1204 	struct vm_page *pg;
   1205 {
   1206 	int s;
   1207 
   1208 	KASSERT((pg->flags & PG_PAGEOUT) == 0);
   1209 	LOCK_ASSERT(simple_lock_held(&uvm.pageqlock) ||
   1210 		    (pg->pqflags & (PQ_ACTIVE|PQ_INACTIVE)) == 0);
   1211 	LOCK_ASSERT(pg->uobject == NULL ||
   1212 		    simple_lock_held(&pg->uobject->vmobjlock));
   1213 	LOCK_ASSERT(pg->uobject != NULL || pg->uanon == NULL ||
   1214 		    simple_lock_held(&pg->uanon->an_lock));
   1215 
   1216 #ifdef DEBUG
   1217 	if (pg->uobject == (void *)0xdeadbeef &&
   1218 	    pg->uanon == (void *)0xdeadbeef) {
   1219 		panic("uvm_pagefree: freeing free page %p", pg);
   1220 	}
   1221 #endif
   1222 
   1223 	/*
   1224 	 * if the page is loaned, resolve the loan instead of freeing.
   1225 	 */
   1226 
   1227 	if (pg->loan_count) {
   1228 		KASSERT(pg->wire_count == 0);
   1229 
   1230 		/*
   1231 		 * if the page is owned by an anon then we just want to
   1232 		 * drop anon ownership.  the kernel will free the page when
   1233 		 * it is done with it.  if the page is owned by an object,
   1234 		 * remove it from the object and mark it dirty for the benefit
   1235 		 * of possible anon owners.
   1236 		 *
   1237 		 * regardless of previous ownership, wakeup any waiters,
   1238 		 * unbusy the page, and we're done.
   1239 		 */
   1240 
   1241 		if (pg->uobject != NULL) {
   1242 			uvm_pageremove(pg);
   1243 			pg->flags &= ~PG_CLEAN;
   1244 		} else if (pg->uanon != NULL) {
   1245 			if ((pg->pqflags & PQ_ANON) == 0) {
   1246 				pg->loan_count--;
   1247 			} else {
   1248 				pg->pqflags &= ~PQ_ANON;
   1249 			}
   1250 			pg->uanon = NULL;
   1251 		}
   1252 		if (pg->flags & PG_WANTED) {
   1253 			wakeup(pg);
   1254 		}
   1255 		pg->flags &= ~(PG_WANTED|PG_BUSY|PG_RELEASED);
   1256 #ifdef UVM_PAGE_TRKOWN
   1257 		pg->owner_tag = NULL;
   1258 #endif
   1259 		if (pg->loan_count) {
   1260 			uvm_pagedequeue(pg);
   1261 			return;
   1262 		}
   1263 	}
   1264 
   1265 	/*
   1266 	 * remove page from its object or anon.
   1267 	 */
   1268 
   1269 	if (pg->uobject != NULL) {
   1270 		uvm_pageremove(pg);
   1271 	} else if (pg->uanon != NULL) {
   1272 		pg->uanon->u.an_page = NULL;
   1273 		uvmexp.anonpages--;
   1274 	}
   1275 
   1276 	/*
   1277 	 * now remove the page from the queues.
   1278 	 */
   1279 
   1280 	uvm_pagedequeue(pg);
   1281 
   1282 	/*
   1283 	 * if the page was wired, unwire it now.
   1284 	 */
   1285 
   1286 	if (pg->wire_count) {
   1287 		pg->wire_count = 0;
   1288 		uvmexp.wired--;
   1289 	}
   1290 
   1291 	/*
   1292 	 * and put on free queue
   1293 	 */
   1294 
   1295 	pg->flags &= ~PG_ZERO;
   1296 
   1297 	s = uvm_lock_fpageq();
   1298 	TAILQ_INSERT_TAIL(&uvm.page_free[
   1299 	    uvm_page_lookup_freelist(pg)].pgfl_buckets[
   1300 	    VM_PGCOLOR_BUCKET(pg)].pgfl_queues[PGFL_UNKNOWN], pg, pageq);
   1301 	pg->pqflags = PQ_FREE;
   1302 #ifdef DEBUG
   1303 	pg->uobject = (void *)0xdeadbeef;
   1304 	pg->offset = 0xdeadbeef;
   1305 	pg->uanon = (void *)0xdeadbeef;
   1306 #endif
   1307 	uvmexp.free++;
   1308 
   1309 	if (uvmexp.zeropages < UVM_PAGEZERO_TARGET)
   1310 		uvm.page_idle_zero = vm_page_zero_enable;
   1311 
   1312 	uvm_unlock_fpageq(s);
   1313 }
   1314 
   1315 /*
   1316  * uvm_page_unbusy: unbusy an array of pages.
   1317  *
   1318  * => pages must either all belong to the same object, or all belong to anons.
   1319  * => if pages are object-owned, object must be locked.
   1320  * => if pages are anon-owned, anons must be locked.
   1321  * => caller must lock page queues if pages may be released.
   1322  */
   1323 
   1324 void
   1325 uvm_page_unbusy(pgs, npgs)
   1326 	struct vm_page **pgs;
   1327 	int npgs;
   1328 {
   1329 	struct vm_page *pg;
   1330 	int i;
   1331 	UVMHIST_FUNC("uvm_page_unbusy"); UVMHIST_CALLED(ubchist);
   1332 
   1333 	for (i = 0; i < npgs; i++) {
   1334 		pg = pgs[i];
   1335 		if (pg == NULL || pg == PGO_DONTCARE) {
   1336 			continue;
   1337 		}
   1338 		if (pg->flags & PG_WANTED) {
   1339 			wakeup(pg);
   1340 		}
   1341 		if (pg->flags & PG_RELEASED) {
   1342 			UVMHIST_LOG(ubchist, "releasing pg %p", pg,0,0,0);
   1343 			pg->flags &= ~PG_RELEASED;
   1344 			uvm_pagefree(pg);
   1345 		} else {
   1346 			UVMHIST_LOG(ubchist, "unbusying pg %p", pg,0,0,0);
   1347 			pg->flags &= ~(PG_WANTED|PG_BUSY);
   1348 			UVM_PAGE_OWN(pg, NULL);
   1349 		}
   1350 	}
   1351 }
   1352 
   1353 #if defined(UVM_PAGE_TRKOWN)
   1354 /*
   1355  * uvm_page_own: set or release page ownership
   1356  *
   1357  * => this is a debugging function that keeps track of who sets PG_BUSY
   1358  *	and where they do it.   it can be used to track down problems
   1359  *	such a process setting "PG_BUSY" and never releasing it.
   1360  * => page's object [if any] must be locked
   1361  * => if "tag" is NULL then we are releasing page ownership
   1362  */
   1363 void
   1364 uvm_page_own(pg, tag)
   1365 	struct vm_page *pg;
   1366 	char *tag;
   1367 {
   1368 	KASSERT((pg->flags & (PG_PAGEOUT|PG_RELEASED)) == 0);
   1369 
   1370 	/* gain ownership? */
   1371 	if (tag) {
   1372 		if (pg->owner_tag) {
   1373 			printf("uvm_page_own: page %p already owned "
   1374 			    "by proc %d [%s]\n", pg,
   1375 			    pg->owner, pg->owner_tag);
   1376 			panic("uvm_page_own");
   1377 		}
   1378 		pg->owner = (curproc) ? curproc->p_pid :  (pid_t) -1;
   1379 		pg->owner_tag = tag;
   1380 		return;
   1381 	}
   1382 
   1383 	/* drop ownership */
   1384 	if (pg->owner_tag == NULL) {
   1385 		printf("uvm_page_own: dropping ownership of an non-owned "
   1386 		    "page (%p)\n", pg);
   1387 		panic("uvm_page_own");
   1388 	}
   1389 	KASSERT((pg->pqflags & (PQ_ACTIVE|PQ_INACTIVE)) ||
   1390 	    (pg->uanon == NULL && pg->uobject == NULL) ||
   1391 	    pg->uobject == uvm.kernel_object ||
   1392 	    pg->wire_count > 0 ||
   1393 	    (pg->loan_count == 1 && pg->uanon == NULL) ||
   1394 	    pg->loan_count > 1);
   1395 	pg->owner_tag = NULL;
   1396 }
   1397 #endif
   1398 
   1399 /*
   1400  * uvm_pageidlezero: zero free pages while the system is idle.
   1401  *
   1402  * => try to complete one color bucket at a time, to reduce our impact
   1403  *	on the CPU cache.
   1404  * => we loop until we either reach the target or whichqs indicates that
   1405  *	there is a process ready to run.
   1406  */
   1407 void
   1408 uvm_pageidlezero()
   1409 {
   1410 	struct vm_page *pg;
   1411 	struct pgfreelist *pgfl;
   1412 	int free_list, s, firstbucket;
   1413 	static int nextbucket;
   1414 
   1415 	s = uvm_lock_fpageq();
   1416 	firstbucket = nextbucket;
   1417 	do {
   1418 		if (sched_whichqs != 0) {
   1419 			uvm_unlock_fpageq(s);
   1420 			return;
   1421 		}
   1422 		if (uvmexp.zeropages >= UVM_PAGEZERO_TARGET) {
   1423 			uvm.page_idle_zero = FALSE;
   1424 			uvm_unlock_fpageq(s);
   1425 			return;
   1426 		}
   1427 		for (free_list = 0; free_list < VM_NFREELIST; free_list++) {
   1428 			pgfl = &uvm.page_free[free_list];
   1429 			while ((pg = TAILQ_FIRST(&pgfl->pgfl_buckets[
   1430 			    nextbucket].pgfl_queues[PGFL_UNKNOWN])) != NULL) {
   1431 				if (sched_whichqs != 0) {
   1432 					uvm_unlock_fpageq(s);
   1433 					return;
   1434 				}
   1435 
   1436 				TAILQ_REMOVE(&pgfl->pgfl_buckets[
   1437 				    nextbucket].pgfl_queues[PGFL_UNKNOWN],
   1438 				    pg, pageq);
   1439 				uvmexp.free--;
   1440 				uvm_unlock_fpageq(s);
   1441 #ifdef PMAP_PAGEIDLEZERO
   1442 				if (!PMAP_PAGEIDLEZERO(VM_PAGE_TO_PHYS(pg))) {
   1443 
   1444 					/*
   1445 					 * The machine-dependent code detected
   1446 					 * some reason for us to abort zeroing
   1447 					 * pages, probably because there is a
   1448 					 * process now ready to run.
   1449 					 */
   1450 
   1451 					s = uvm_lock_fpageq();
   1452 					TAILQ_INSERT_HEAD(&pgfl->pgfl_buckets[
   1453 					    nextbucket].pgfl_queues[
   1454 					    PGFL_UNKNOWN], pg, pageq);
   1455 					uvmexp.free++;
   1456 					uvmexp.zeroaborts++;
   1457 					uvm_unlock_fpageq(s);
   1458 					return;
   1459 				}
   1460 #else
   1461 				pmap_zero_page(VM_PAGE_TO_PHYS(pg));
   1462 #endif /* PMAP_PAGEIDLEZERO */
   1463 				pg->flags |= PG_ZERO;
   1464 
   1465 				s = uvm_lock_fpageq();
   1466 				TAILQ_INSERT_HEAD(&pgfl->pgfl_buckets[
   1467 				    nextbucket].pgfl_queues[PGFL_ZEROS],
   1468 				    pg, pageq);
   1469 				uvmexp.free++;
   1470 				uvmexp.zeropages++;
   1471 			}
   1472 		}
   1473 		nextbucket = (nextbucket + 1) & uvmexp.colormask;
   1474 	} while (nextbucket != firstbucket);
   1475 	uvm_unlock_fpageq(s);
   1476 }
   1477