xref: /netbsd-src/sys/uvm/uvm_page.c (revision 267197ec1eebfcb9810ea27a89625b6ddf68e3e7)
1 /*	$NetBSD: uvm_page.c,v 1.128 2008/01/13 16:46:47 yamt 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@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.128 2008/01/13 16:46:47 yamt Exp $");
75 
76 #include "opt_uvmhist.h"
77 #include "opt_readahead.h"
78 
79 #include <sys/param.h>
80 #include <sys/systm.h>
81 #include <sys/malloc.h>
82 #include <sys/sched.h>
83 #include <sys/kernel.h>
84 #include <sys/vnode.h>
85 #include <sys/proc.h>
86 #include <sys/atomic.h>
87 
88 #include <uvm/uvm.h>
89 #include <uvm/uvm_pdpolicy.h>
90 
91 /*
92  * global vars... XXXCDC: move to uvm. structure.
93  */
94 
95 /*
96  * physical memory config is stored in vm_physmem.
97  */
98 
99 struct vm_physseg vm_physmem[VM_PHYSSEG_MAX];	/* XXXCDC: uvm.physmem */
100 int vm_nphysseg = 0;				/* XXXCDC: uvm.nphysseg */
101 
102 /*
103  * Some supported CPUs in a given architecture don't support all
104  * of the things necessary to do idle page zero'ing efficiently.
105  * We therefore provide a way to disable it from machdep code here.
106  */
107 /*
108  * XXX disabled until we can find a way to do this without causing
109  * problems for either CPU caches or DMA latency.
110  */
111 bool vm_page_zero_enable = false;
112 
113 /*
114  * local variables
115  */
116 
117 /*
118  * these variables record the values returned by vm_page_bootstrap,
119  * for debugging purposes.  The implementation of uvm_pageboot_alloc
120  * and pmap_startup here also uses them internally.
121  */
122 
123 static vaddr_t      virtual_space_start;
124 static vaddr_t      virtual_space_end;
125 
126 /*
127  * we use a hash table with only one bucket during bootup.  we will
128  * later rehash (resize) the hash table once the allocator is ready.
129  * we static allocate the one bootstrap bucket below...
130  */
131 
132 static struct pglist uvm_bootbucket;
133 
134 /*
135  * we allocate an initial number of page colors in uvm_page_init(),
136  * and remember them.  We may re-color pages as cache sizes are
137  * discovered during the autoconfiguration phase.  But we can never
138  * free the initial set of buckets, since they are allocated using
139  * uvm_pageboot_alloc().
140  */
141 
142 static bool have_recolored_pages /* = false */;
143 
144 MALLOC_DEFINE(M_VMPAGE, "VM page", "VM page");
145 
146 #ifdef DEBUG
147 vaddr_t uvm_zerocheckkva;
148 #endif /* DEBUG */
149 
150 /*
151  * locks on the hash table.  allocated in 32 byte chunks to try
152  * and reduce cache traffic between CPUs.
153  */
154 
155 #define	UVM_HASHLOCK_CNT	32
156 #define	uvm_hashlock(hash)	\
157     (&uvm_hashlocks[(hash) & (UVM_HASHLOCK_CNT - 1)].lock)
158 
159 static union {
160 	kmutex_t	lock;
161 	uint8_t		pad[32];
162 } uvm_hashlocks[UVM_HASHLOCK_CNT] __aligned(32);
163 
164 /*
165  * local prototypes
166  */
167 
168 static void uvm_pageinsert(struct vm_page *);
169 static void uvm_pageinsert_after(struct vm_page *, struct vm_page *);
170 static void uvm_pageremove(struct vm_page *);
171 
172 /*
173  * inline functions
174  */
175 
176 /*
177  * uvm_pageinsert: insert a page in the object and the hash table
178  * uvm_pageinsert_after: insert a page into the specified place in listq
179  *
180  * => caller must lock object
181  * => caller must lock page queues
182  * => call should have already set pg's object and offset pointers
183  *    and bumped the version counter
184  */
185 
186 inline static void
187 uvm_pageinsert_after(struct vm_page *pg, struct vm_page *where)
188 {
189 	struct pglist *buck;
190 	struct uvm_object *uobj = pg->uobject;
191 	kmutex_t *lock;
192 	u_int hash;
193 
194 	KASSERT(mutex_owned(&uobj->vmobjlock));
195 	KASSERT((pg->flags & PG_TABLED) == 0);
196 	KASSERT(where == NULL || (where->flags & PG_TABLED));
197 	KASSERT(where == NULL || (where->uobject == uobj));
198 
199 	hash = uvm_pagehash(uobj, pg->offset);
200 	buck = &uvm.page_hash[hash];
201 	lock = uvm_hashlock(hash);
202 	mutex_spin_enter(lock);
203 	TAILQ_INSERT_TAIL(buck, pg, hashq);
204 	mutex_spin_exit(lock);
205 
206 	if (UVM_OBJ_IS_VNODE(uobj)) {
207 		if (uobj->uo_npages == 0) {
208 			struct vnode *vp = (struct vnode *)uobj;
209 
210 			vholdl(vp);
211 		}
212 		if (UVM_OBJ_IS_VTEXT(uobj)) {
213 			atomic_inc_uint(&uvmexp.execpages);
214 		} else {
215 			atomic_inc_uint(&uvmexp.filepages);
216 		}
217 	} else if (UVM_OBJ_IS_AOBJ(uobj)) {
218 		atomic_inc_uint(&uvmexp.anonpages);
219 	}
220 
221 	if (where)
222 		TAILQ_INSERT_AFTER(&uobj->memq, where, pg, listq);
223 	else
224 		TAILQ_INSERT_TAIL(&uobj->memq, pg, listq);
225 	pg->flags |= PG_TABLED;
226 	uobj->uo_npages++;
227 }
228 
229 inline static void
230 uvm_pageinsert(struct vm_page *pg)
231 {
232 
233 	uvm_pageinsert_after(pg, NULL);
234 }
235 
236 /*
237  * uvm_page_remove: remove page from object and hash
238  *
239  * => caller must lock object
240  * => caller must lock page queues
241  */
242 
243 static inline void
244 uvm_pageremove(struct vm_page *pg)
245 {
246 	struct pglist *buck;
247 	struct uvm_object *uobj = pg->uobject;
248 	kmutex_t *lock;
249 	u_int hash;
250 
251 	KASSERT(mutex_owned(&uobj->vmobjlock));
252 	KASSERT(pg->flags & PG_TABLED);
253 
254 	hash = uvm_pagehash(uobj, pg->offset);
255 	buck = &uvm.page_hash[hash];
256 	lock = uvm_hashlock(hash);
257 	mutex_spin_enter(lock);
258 	TAILQ_REMOVE(buck, pg, hashq);
259 	mutex_spin_exit(lock);
260 
261 	if (UVM_OBJ_IS_VNODE(uobj)) {
262 		if (uobj->uo_npages == 1) {
263 			struct vnode *vp = (struct vnode *)uobj;
264 
265 			holdrelel(vp);
266 		}
267 		if (UVM_OBJ_IS_VTEXT(uobj)) {
268 			atomic_dec_uint(&uvmexp.execpages);
269 		} else {
270 			atomic_dec_uint(&uvmexp.filepages);
271 		}
272 	} else if (UVM_OBJ_IS_AOBJ(uobj)) {
273 		atomic_dec_uint(&uvmexp.anonpages);
274 	}
275 
276 	/* object should be locked */
277 	uobj->uo_npages--;
278 	TAILQ_REMOVE(&uobj->memq, pg, listq);
279 	pg->flags &= ~PG_TABLED;
280 	pg->uobject = NULL;
281 }
282 
283 static void
284 uvm_page_init_buckets(struct pgfreelist *pgfl)
285 {
286 	int color, i;
287 
288 	for (color = 0; color < uvmexp.ncolors; color++) {
289 		for (i = 0; i < PGFL_NQUEUES; i++) {
290 			TAILQ_INIT(&pgfl->pgfl_buckets[color].pgfl_queues[i]);
291 		}
292 	}
293 }
294 
295 /*
296  * uvm_page_init: init the page system.   called from uvm_init().
297  *
298  * => we return the range of kernel virtual memory in kvm_startp/kvm_endp
299  */
300 
301 void
302 uvm_page_init(vaddr_t *kvm_startp, vaddr_t *kvm_endp)
303 {
304 	vsize_t freepages, pagecount, bucketcount, n;
305 	struct pgflbucket *bucketarray;
306 	struct vm_page *pagearray;
307 	int lcv;
308 	u_int i;
309 	paddr_t paddr;
310 
311 	/*
312 	 * init the page queues and page queue locks, except the free
313 	 * list; we allocate that later (with the initial vm_page
314 	 * structures).
315 	 */
316 
317 	uvmpdpol_init();
318 	mutex_init(&uvm_pageqlock, MUTEX_DRIVER, IPL_NONE);
319 	mutex_init(&uvm_fpageqlock, MUTEX_DRIVER, IPL_VM);
320 
321 	/*
322 	 * init the <obj,offset> => <page> hash table.  for now
323 	 * we just have one bucket (the bootstrap bucket).  later on we
324 	 * will allocate new buckets as we dynamically resize the hash table.
325 	 */
326 
327 	uvm.page_nhash = 1;			/* 1 bucket */
328 	uvm.page_hashmask = 0;			/* mask for hash function */
329 	uvm.page_hash = &uvm_bootbucket;	/* install bootstrap bucket */
330 	TAILQ_INIT(uvm.page_hash);		/* init hash table */
331 
332 	/*
333 	 * init hashtable locks.  these must be spinlocks, as they are
334 	 * called from sites in the pmap modules where we cannot block.
335 	 * if taking multiple locks, the order is: low numbered first,
336 	 * high numbered second.
337 	 */
338 
339 	for (i = 0; i < UVM_HASHLOCK_CNT; i++)
340 		mutex_init(&uvm_hashlocks[i].lock, MUTEX_SPIN, IPL_VM);
341 
342 	/*
343 	 * allocate vm_page structures.
344 	 */
345 
346 	/*
347 	 * sanity check:
348 	 * before calling this function the MD code is expected to register
349 	 * some free RAM with the uvm_page_physload() function.   our job
350 	 * now is to allocate vm_page structures for this memory.
351 	 */
352 
353 	if (vm_nphysseg == 0)
354 		panic("uvm_page_bootstrap: no memory pre-allocated");
355 
356 	/*
357 	 * first calculate the number of free pages...
358 	 *
359 	 * note that we use start/end rather than avail_start/avail_end.
360 	 * this allows us to allocate extra vm_page structures in case we
361 	 * want to return some memory to the pool after booting.
362 	 */
363 
364 	freepages = 0;
365 	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
366 		freepages += (vm_physmem[lcv].end - vm_physmem[lcv].start);
367 
368 	/*
369 	 * Let MD code initialize the number of colors, or default
370 	 * to 1 color if MD code doesn't care.
371 	 */
372 	if (uvmexp.ncolors == 0)
373 		uvmexp.ncolors = 1;
374 	uvmexp.colormask = uvmexp.ncolors - 1;
375 
376 	/*
377 	 * we now know we have (PAGE_SIZE * freepages) bytes of memory we can
378 	 * use.   for each page of memory we use we need a vm_page structure.
379 	 * thus, the total number of pages we can use is the total size of
380 	 * the memory divided by the PAGE_SIZE plus the size of the vm_page
381 	 * structure.   we add one to freepages as a fudge factor to avoid
382 	 * truncation errors (since we can only allocate in terms of whole
383 	 * pages).
384 	 */
385 
386 	bucketcount = uvmexp.ncolors * VM_NFREELIST;
387 	pagecount = ((freepages + 1) << PAGE_SHIFT) /
388 	    (PAGE_SIZE + sizeof(struct vm_page));
389 
390 	bucketarray = (void *)uvm_pageboot_alloc((bucketcount *
391 	    sizeof(struct pgflbucket)) + (pagecount *
392 	    sizeof(struct vm_page)));
393 	pagearray = (struct vm_page *)(bucketarray + bucketcount);
394 
395 	for (lcv = 0; lcv < VM_NFREELIST; lcv++) {
396 		uvm.page_free[lcv].pgfl_buckets =
397 		    (bucketarray + (lcv * uvmexp.ncolors));
398 		uvm_page_init_buckets(&uvm.page_free[lcv]);
399 	}
400 	memset(pagearray, 0, pagecount * sizeof(struct vm_page));
401 
402 	/*
403 	 * init the vm_page structures and put them in the correct place.
404 	 */
405 
406 	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++) {
407 		n = vm_physmem[lcv].end - vm_physmem[lcv].start;
408 
409 		/* set up page array pointers */
410 		vm_physmem[lcv].pgs = pagearray;
411 		pagearray += n;
412 		pagecount -= n;
413 		vm_physmem[lcv].lastpg = vm_physmem[lcv].pgs + (n - 1);
414 
415 		/* init and free vm_pages (we've already zeroed them) */
416 		paddr = ptoa(vm_physmem[lcv].start);
417 		for (i = 0 ; i < n ; i++, paddr += PAGE_SIZE) {
418 			vm_physmem[lcv].pgs[i].phys_addr = paddr;
419 #ifdef __HAVE_VM_PAGE_MD
420 			VM_MDPAGE_INIT(&vm_physmem[lcv].pgs[i]);
421 #endif
422 			if (atop(paddr) >= vm_physmem[lcv].avail_start &&
423 			    atop(paddr) <= vm_physmem[lcv].avail_end) {
424 				uvmexp.npages++;
425 				/* add page to free pool */
426 				uvm_pagefree(&vm_physmem[lcv].pgs[i]);
427 			}
428 		}
429 	}
430 
431 	/*
432 	 * pass up the values of virtual_space_start and
433 	 * virtual_space_end (obtained by uvm_pageboot_alloc) to the upper
434 	 * layers of the VM.
435 	 */
436 
437 	*kvm_startp = round_page(virtual_space_start);
438 	*kvm_endp = trunc_page(virtual_space_end);
439 #ifdef DEBUG
440 	/*
441 	 * steal kva for uvm_pagezerocheck().
442 	 */
443 	uvm_zerocheckkva = *kvm_startp;
444 	*kvm_startp += PAGE_SIZE;
445 #endif /* DEBUG */
446 
447 	/*
448 	 * init various thresholds.
449 	 */
450 
451 	uvmexp.reserve_pagedaemon = 1;
452 	uvmexp.reserve_kernel = 5;
453 
454 	/*
455 	 * determine if we should zero pages in the idle loop.
456 	 */
457 
458 	uvm.page_idle_zero = vm_page_zero_enable;
459 
460 	/*
461 	 * done!
462 	 */
463 
464 	uvm.page_init_done = true;
465 }
466 
467 /*
468  * uvm_setpagesize: set the page size
469  *
470  * => sets page_shift and page_mask from uvmexp.pagesize.
471  */
472 
473 void
474 uvm_setpagesize(void)
475 {
476 
477 	/*
478 	 * If uvmexp.pagesize is 0 at this point, we expect PAGE_SIZE
479 	 * to be a constant (indicated by being a non-zero value).
480 	 */
481 	if (uvmexp.pagesize == 0) {
482 		if (PAGE_SIZE == 0)
483 			panic("uvm_setpagesize: uvmexp.pagesize not set");
484 		uvmexp.pagesize = PAGE_SIZE;
485 	}
486 	uvmexp.pagemask = uvmexp.pagesize - 1;
487 	if ((uvmexp.pagemask & uvmexp.pagesize) != 0)
488 		panic("uvm_setpagesize: page size not a power of two");
489 	for (uvmexp.pageshift = 0; ; uvmexp.pageshift++)
490 		if ((1 << uvmexp.pageshift) == uvmexp.pagesize)
491 			break;
492 }
493 
494 /*
495  * uvm_pageboot_alloc: steal memory from physmem for bootstrapping
496  */
497 
498 vaddr_t
499 uvm_pageboot_alloc(vsize_t size)
500 {
501 	static bool initialized = false;
502 	vaddr_t addr;
503 #if !defined(PMAP_STEAL_MEMORY)
504 	vaddr_t vaddr;
505 	paddr_t paddr;
506 #endif
507 
508 	/*
509 	 * on first call to this function, initialize ourselves.
510 	 */
511 	if (initialized == false) {
512 		pmap_virtual_space(&virtual_space_start, &virtual_space_end);
513 
514 		/* round it the way we like it */
515 		virtual_space_start = round_page(virtual_space_start);
516 		virtual_space_end = trunc_page(virtual_space_end);
517 
518 		initialized = true;
519 	}
520 
521 	/* round to page size */
522 	size = round_page(size);
523 
524 #if defined(PMAP_STEAL_MEMORY)
525 
526 	/*
527 	 * defer bootstrap allocation to MD code (it may want to allocate
528 	 * from a direct-mapped segment).  pmap_steal_memory should adjust
529 	 * virtual_space_start/virtual_space_end if necessary.
530 	 */
531 
532 	addr = pmap_steal_memory(size, &virtual_space_start,
533 	    &virtual_space_end);
534 
535 	return(addr);
536 
537 #else /* !PMAP_STEAL_MEMORY */
538 
539 	/*
540 	 * allocate virtual memory for this request
541 	 */
542 	if (virtual_space_start == virtual_space_end ||
543 	    (virtual_space_end - virtual_space_start) < size)
544 		panic("uvm_pageboot_alloc: out of virtual space");
545 
546 	addr = virtual_space_start;
547 
548 #ifdef PMAP_GROWKERNEL
549 	/*
550 	 * If the kernel pmap can't map the requested space,
551 	 * then allocate more resources for it.
552 	 */
553 	if (uvm_maxkaddr < (addr + size)) {
554 		uvm_maxkaddr = pmap_growkernel(addr + size);
555 		if (uvm_maxkaddr < (addr + size))
556 			panic("uvm_pageboot_alloc: pmap_growkernel() failed");
557 	}
558 #endif
559 
560 	virtual_space_start += size;
561 
562 	/*
563 	 * allocate and mapin physical pages to back new virtual pages
564 	 */
565 
566 	for (vaddr = round_page(addr) ; vaddr < addr + size ;
567 	    vaddr += PAGE_SIZE) {
568 
569 		if (!uvm_page_physget(&paddr))
570 			panic("uvm_pageboot_alloc: out of memory");
571 
572 		/*
573 		 * Note this memory is no longer managed, so using
574 		 * pmap_kenter is safe.
575 		 */
576 		pmap_kenter_pa(vaddr, paddr, VM_PROT_READ|VM_PROT_WRITE);
577 	}
578 	pmap_update(pmap_kernel());
579 	return(addr);
580 #endif	/* PMAP_STEAL_MEMORY */
581 }
582 
583 #if !defined(PMAP_STEAL_MEMORY)
584 /*
585  * uvm_page_physget: "steal" one page from the vm_physmem structure.
586  *
587  * => attempt to allocate it off the end of a segment in which the "avail"
588  *    values match the start/end values.   if we can't do that, then we
589  *    will advance both values (making them equal, and removing some
590  *    vm_page structures from the non-avail area).
591  * => return false if out of memory.
592  */
593 
594 /* subroutine: try to allocate from memory chunks on the specified freelist */
595 static bool uvm_page_physget_freelist(paddr_t *, int);
596 
597 static bool
598 uvm_page_physget_freelist(paddr_t *paddrp, int freelist)
599 {
600 	int lcv, x;
601 
602 	/* pass 1: try allocating from a matching end */
603 #if (VM_PHYSSEG_STRAT == VM_PSTRAT_BIGFIRST)
604 	for (lcv = vm_nphysseg - 1 ; lcv >= 0 ; lcv--)
605 #else
606 	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
607 #endif
608 	{
609 
610 		if (uvm.page_init_done == true)
611 			panic("uvm_page_physget: called _after_ bootstrap");
612 
613 		if (vm_physmem[lcv].free_list != freelist)
614 			continue;
615 
616 		/* try from front */
617 		if (vm_physmem[lcv].avail_start == vm_physmem[lcv].start &&
618 		    vm_physmem[lcv].avail_start < vm_physmem[lcv].avail_end) {
619 			*paddrp = ptoa(vm_physmem[lcv].avail_start);
620 			vm_physmem[lcv].avail_start++;
621 			vm_physmem[lcv].start++;
622 			/* nothing left?   nuke it */
623 			if (vm_physmem[lcv].avail_start ==
624 			    vm_physmem[lcv].end) {
625 				if (vm_nphysseg == 1)
626 				    panic("uvm_page_physget: out of memory!");
627 				vm_nphysseg--;
628 				for (x = lcv ; x < vm_nphysseg ; x++)
629 					/* structure copy */
630 					vm_physmem[x] = vm_physmem[x+1];
631 			}
632 			return (true);
633 		}
634 
635 		/* try from rear */
636 		if (vm_physmem[lcv].avail_end == vm_physmem[lcv].end &&
637 		    vm_physmem[lcv].avail_start < vm_physmem[lcv].avail_end) {
638 			*paddrp = ptoa(vm_physmem[lcv].avail_end - 1);
639 			vm_physmem[lcv].avail_end--;
640 			vm_physmem[lcv].end--;
641 			/* nothing left?   nuke it */
642 			if (vm_physmem[lcv].avail_end ==
643 			    vm_physmem[lcv].start) {
644 				if (vm_nphysseg == 1)
645 				    panic("uvm_page_physget: out of memory!");
646 				vm_nphysseg--;
647 				for (x = lcv ; x < vm_nphysseg ; x++)
648 					/* structure copy */
649 					vm_physmem[x] = vm_physmem[x+1];
650 			}
651 			return (true);
652 		}
653 	}
654 
655 	/* pass2: forget about matching ends, just allocate something */
656 #if (VM_PHYSSEG_STRAT == VM_PSTRAT_BIGFIRST)
657 	for (lcv = vm_nphysseg - 1 ; lcv >= 0 ; lcv--)
658 #else
659 	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
660 #endif
661 	{
662 
663 		/* any room in this bank? */
664 		if (vm_physmem[lcv].avail_start >= vm_physmem[lcv].avail_end)
665 			continue;  /* nope */
666 
667 		*paddrp = ptoa(vm_physmem[lcv].avail_start);
668 		vm_physmem[lcv].avail_start++;
669 		/* truncate! */
670 		vm_physmem[lcv].start = vm_physmem[lcv].avail_start;
671 
672 		/* nothing left?   nuke it */
673 		if (vm_physmem[lcv].avail_start == vm_physmem[lcv].end) {
674 			if (vm_nphysseg == 1)
675 				panic("uvm_page_physget: out of memory!");
676 			vm_nphysseg--;
677 			for (x = lcv ; x < vm_nphysseg ; x++)
678 				/* structure copy */
679 				vm_physmem[x] = vm_physmem[x+1];
680 		}
681 		return (true);
682 	}
683 
684 	return (false);        /* whoops! */
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  * uvm_page_physload: load physical memory into VM system
702  *
703  * => all args are PFs
704  * => all pages in start/end get vm_page structures
705  * => areas marked by avail_start/avail_end get added to the free page pool
706  * => we are limited to VM_PHYSSEG_MAX physical memory segments
707  */
708 
709 void
710 uvm_page_physload(paddr_t start, paddr_t end, paddr_t avail_start,
711     paddr_t avail_end, int free_list)
712 {
713 	int preload, lcv;
714 	psize_t npages;
715 	struct vm_page *pgs;
716 	struct vm_physseg *ps;
717 
718 	if (uvmexp.pagesize == 0)
719 		panic("uvm_page_physload: page size not set!");
720 	if (free_list >= VM_NFREELIST || free_list < VM_FREELIST_DEFAULT)
721 		panic("uvm_page_physload: bad free list %d", free_list);
722 	if (start >= end)
723 		panic("uvm_page_physload: start >= end");
724 
725 	/*
726 	 * do we have room?
727 	 */
728 
729 	if (vm_nphysseg == VM_PHYSSEG_MAX) {
730 		printf("uvm_page_physload: unable to load physical memory "
731 		    "segment\n");
732 		printf("\t%d segments allocated, ignoring 0x%llx -> 0x%llx\n",
733 		    VM_PHYSSEG_MAX, (long long)start, (long long)end);
734 		printf("\tincrease VM_PHYSSEG_MAX\n");
735 		return;
736 	}
737 
738 	/*
739 	 * check to see if this is a "preload" (i.e. uvm_mem_init hasn't been
740 	 * called yet, so malloc is not available).
741 	 */
742 
743 	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++) {
744 		if (vm_physmem[lcv].pgs)
745 			break;
746 	}
747 	preload = (lcv == vm_nphysseg);
748 
749 	/*
750 	 * if VM is already running, attempt to malloc() vm_page structures
751 	 */
752 
753 	if (!preload) {
754 #if defined(VM_PHYSSEG_NOADD)
755 		panic("uvm_page_physload: tried to add RAM after vm_mem_init");
756 #else
757 		/* XXXCDC: need some sort of lockout for this case */
758 		paddr_t paddr;
759 		npages = end - start;  /* # of pages */
760 		pgs = malloc(sizeof(struct vm_page) * npages,
761 		    M_VMPAGE, M_NOWAIT);
762 		if (pgs == NULL) {
763 			printf("uvm_page_physload: can not malloc vm_page "
764 			    "structs for segment\n");
765 			printf("\tignoring 0x%lx -> 0x%lx\n", start, end);
766 			return;
767 		}
768 		/* zero data, init phys_addr and free_list, and free pages */
769 		memset(pgs, 0, sizeof(struct vm_page) * npages);
770 		for (lcv = 0, paddr = ptoa(start) ;
771 				 lcv < npages ; lcv++, paddr += PAGE_SIZE) {
772 			pgs[lcv].phys_addr = paddr;
773 			pgs[lcv].free_list = free_list;
774 			if (atop(paddr) >= avail_start &&
775 			    atop(paddr) <= avail_end)
776 				uvm_pagefree(&pgs[lcv]);
777 		}
778 		/* XXXCDC: incomplete: need to update uvmexp.free, what else? */
779 		/* XXXCDC: need hook to tell pmap to rebuild pv_list, etc... */
780 #endif
781 	} else {
782 		pgs = NULL;
783 		npages = 0;
784 	}
785 
786 	/*
787 	 * now insert us in the proper place in vm_physmem[]
788 	 */
789 
790 #if (VM_PHYSSEG_STRAT == VM_PSTRAT_RANDOM)
791 	/* random: put it at the end (easy!) */
792 	ps = &vm_physmem[vm_nphysseg];
793 #elif (VM_PHYSSEG_STRAT == VM_PSTRAT_BSEARCH)
794 	{
795 		int x;
796 		/* sort by address for binary search */
797 		for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
798 			if (start < vm_physmem[lcv].start)
799 				break;
800 		ps = &vm_physmem[lcv];
801 		/* move back other entries, if necessary ... */
802 		for (x = vm_nphysseg ; x > lcv ; x--)
803 			/* structure copy */
804 			vm_physmem[x] = vm_physmem[x - 1];
805 	}
806 #elif (VM_PHYSSEG_STRAT == VM_PSTRAT_BIGFIRST)
807 	{
808 		int x;
809 		/* sort by largest segment first */
810 		for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
811 			if ((end - start) >
812 			    (vm_physmem[lcv].end - vm_physmem[lcv].start))
813 				break;
814 		ps = &vm_physmem[lcv];
815 		/* move back other entries, if necessary ... */
816 		for (x = vm_nphysseg ; x > lcv ; x--)
817 			/* structure copy */
818 			vm_physmem[x] = vm_physmem[x - 1];
819 	}
820 #else
821 	panic("uvm_page_physload: unknown physseg strategy selected!");
822 #endif
823 
824 	ps->start = start;
825 	ps->end = end;
826 	ps->avail_start = avail_start;
827 	ps->avail_end = avail_end;
828 	if (preload) {
829 		ps->pgs = NULL;
830 	} else {
831 		ps->pgs = pgs;
832 		ps->lastpg = pgs + npages - 1;
833 	}
834 	ps->free_list = free_list;
835 	vm_nphysseg++;
836 
837 	if (!preload) {
838 		uvm_page_rehash();
839 		uvmpdpol_reinit();
840 	}
841 }
842 
843 /*
844  * uvm_page_rehash: reallocate hash table based on number of free pages.
845  */
846 
847 void
848 uvm_page_rehash(void)
849 {
850 	int freepages, lcv, bucketcount, oldcount, i;
851 	struct pglist *newbuckets, *oldbuckets;
852 	struct vm_page *pg;
853 	size_t newsize, oldsize;
854 
855 	/*
856 	 * compute number of pages that can go in the free pool
857 	 */
858 
859 	freepages = 0;
860 	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
861 		freepages +=
862 		    (vm_physmem[lcv].avail_end - vm_physmem[lcv].avail_start);
863 
864 	/*
865 	 * compute number of buckets needed for this number of pages
866 	 */
867 
868 	bucketcount = 1;
869 	while (bucketcount < freepages)
870 		bucketcount = bucketcount * 2;
871 
872 	/*
873 	 * compute the size of the current table and new table.
874 	 */
875 
876 	oldbuckets = uvm.page_hash;
877 	oldcount = uvm.page_nhash;
878 	oldsize = round_page(sizeof(struct pglist) * oldcount);
879 	newsize = round_page(sizeof(struct pglist) * bucketcount);
880 
881 	/*
882 	 * allocate the new buckets
883 	 */
884 
885 	newbuckets = (struct pglist *) uvm_km_alloc(kernel_map, newsize,
886 	    0, UVM_KMF_WIRED);
887 	if (newbuckets == NULL) {
888 		printf("uvm_page_physrehash: WARNING: could not grow page "
889 		    "hash table\n");
890 		return;
891 	}
892 	for (lcv = 0 ; lcv < bucketcount ; lcv++)
893 		TAILQ_INIT(&newbuckets[lcv]);
894 
895 	/*
896 	 * now replace the old buckets with the new ones and rehash everything
897 	 */
898 
899 	for (i = 0; i < UVM_HASHLOCK_CNT; i++)
900 		mutex_spin_enter(&uvm_hashlocks[i].lock);
901 
902 	uvm.page_hash = newbuckets;
903 	uvm.page_nhash = bucketcount;
904 	uvm.page_hashmask = bucketcount - 1;  /* power of 2 */
905 
906 	/* ... and rehash */
907 	for (lcv = 0 ; lcv < oldcount ; lcv++) {
908 		while ((pg = oldbuckets[lcv].tqh_first) != NULL) {
909 			TAILQ_REMOVE(&oldbuckets[lcv], pg, hashq);
910 			TAILQ_INSERT_TAIL(
911 			  &uvm.page_hash[uvm_pagehash(pg->uobject, pg->offset)],
912 			  pg, hashq);
913 		}
914 	}
915 
916 	for (i = 0; i < UVM_HASHLOCK_CNT; i++)
917 		mutex_spin_exit(&uvm_hashlocks[i].lock);
918 
919 	/*
920 	 * free old bucket array if is not the boot-time table
921 	 */
922 
923 	if (oldbuckets != &uvm_bootbucket)
924 		uvm_km_free(kernel_map, (vaddr_t) oldbuckets, oldsize,
925 		    UVM_KMF_WIRED);
926 }
927 
928 /*
929  * uvm_page_recolor: Recolor the pages if the new bucket count is
930  * larger than the old one.
931  */
932 
933 void
934 uvm_page_recolor(int newncolors)
935 {
936 	struct pgflbucket *bucketarray, *oldbucketarray;
937 	struct pgfreelist pgfl;
938 	struct vm_page *pg;
939 	vsize_t bucketcount;
940 	int lcv, color, i, ocolors;
941 
942 	if (newncolors <= uvmexp.ncolors)
943 		return;
944 
945 	if (uvm.page_init_done == false) {
946 		uvmexp.ncolors = newncolors;
947 		return;
948 	}
949 
950 	bucketcount = newncolors * VM_NFREELIST;
951 	bucketarray = malloc(bucketcount * sizeof(struct pgflbucket),
952 	    M_VMPAGE, M_NOWAIT);
953 	if (bucketarray == NULL) {
954 		printf("WARNING: unable to allocate %ld page color buckets\n",
955 		    (long) bucketcount);
956 		return;
957 	}
958 
959 	mutex_spin_enter(&uvm_fpageqlock);
960 
961 	/* Make sure we should still do this. */
962 	if (newncolors <= uvmexp.ncolors) {
963 		mutex_spin_exit(&uvm_fpageqlock);
964 		free(bucketarray, M_VMPAGE);
965 		return;
966 	}
967 
968 	oldbucketarray = uvm.page_free[0].pgfl_buckets;
969 	ocolors = uvmexp.ncolors;
970 
971 	uvmexp.ncolors = newncolors;
972 	uvmexp.colormask = uvmexp.ncolors - 1;
973 
974 	for (lcv = 0; lcv < VM_NFREELIST; lcv++) {
975 		pgfl.pgfl_buckets = (bucketarray + (lcv * newncolors));
976 		uvm_page_init_buckets(&pgfl);
977 		for (color = 0; color < ocolors; color++) {
978 			for (i = 0; i < PGFL_NQUEUES; i++) {
979 				while ((pg = TAILQ_FIRST(&uvm.page_free[
980 				    lcv].pgfl_buckets[color].pgfl_queues[i]))
981 				    != NULL) {
982 					TAILQ_REMOVE(&uvm.page_free[
983 					    lcv].pgfl_buckets[
984 					    color].pgfl_queues[i], pg, pageq);
985 					TAILQ_INSERT_TAIL(&pgfl.pgfl_buckets[
986 					    VM_PGCOLOR_BUCKET(pg)].pgfl_queues[
987 					    i], pg, pageq);
988 				}
989 			}
990 		}
991 		uvm.page_free[lcv].pgfl_buckets = pgfl.pgfl_buckets;
992 	}
993 
994 	if (have_recolored_pages) {
995 		mutex_spin_exit(&uvm_fpageqlock);
996 		free(oldbucketarray, M_VMPAGE);
997 		return;
998 	}
999 
1000 	have_recolored_pages = true;
1001 	mutex_spin_exit(&uvm_fpageqlock);
1002 }
1003 
1004 /*
1005  * uvm_pagealloc_pgfl: helper routine for uvm_pagealloc_strat
1006  */
1007 
1008 static struct vm_page *
1009 uvm_pagealloc_pgfl(struct pgfreelist *pgfl, int try1, int try2,
1010     int *trycolorp)
1011 {
1012 	struct pglist *freeq;
1013 	struct vm_page *pg;
1014 	int color, trycolor = *trycolorp;
1015 
1016 	color = trycolor;
1017 	do {
1018 		if ((pg = TAILQ_FIRST((freeq =
1019 		    &pgfl->pgfl_buckets[color].pgfl_queues[try1]))) != NULL)
1020 			goto gotit;
1021 		if ((pg = TAILQ_FIRST((freeq =
1022 		    &pgfl->pgfl_buckets[color].pgfl_queues[try2]))) != NULL)
1023 			goto gotit;
1024 		color = (color + 1) & uvmexp.colormask;
1025 	} while (color != trycolor);
1026 
1027 	return (NULL);
1028 
1029  gotit:
1030 	TAILQ_REMOVE(freeq, pg, pageq);
1031 	uvmexp.free--;
1032 
1033 	/* update zero'd page count */
1034 	if (pg->flags & PG_ZERO)
1035 		uvmexp.zeropages--;
1036 
1037 	if (color == trycolor)
1038 		uvmexp.colorhit++;
1039 	else {
1040 		uvmexp.colormiss++;
1041 		*trycolorp = color;
1042 	}
1043 
1044 	return (pg);
1045 }
1046 
1047 /*
1048  * uvm_pagealloc_strat: allocate vm_page from a particular free list.
1049  *
1050  * => return null if no pages free
1051  * => wake up pagedaemon if number of free pages drops below low water mark
1052  * => if obj != NULL, obj must be locked (to put in hash)
1053  * => if anon != NULL, anon must be locked (to put in anon)
1054  * => only one of obj or anon can be non-null
1055  * => caller must activate/deactivate page if it is not wired.
1056  * => free_list is ignored if strat == UVM_PGA_STRAT_NORMAL.
1057  * => policy decision: it is more important to pull a page off of the
1058  *	appropriate priority free list than it is to get a zero'd or
1059  *	unknown contents page.  This is because we live with the
1060  *	consequences of a bad free list decision for the entire
1061  *	lifetime of the page, e.g. if the page comes from memory that
1062  *	is slower to access.
1063  */
1064 
1065 struct vm_page *
1066 uvm_pagealloc_strat(struct uvm_object *obj, voff_t off, struct vm_anon *anon,
1067     int flags, int strat, int free_list)
1068 {
1069 	int lcv, try1, try2, zeroit = 0, color;
1070 	struct vm_page *pg;
1071 	bool use_reserve;
1072 
1073 	KASSERT(obj == NULL || anon == NULL);
1074 	KASSERT(anon == NULL || off == 0);
1075 	KASSERT(off == trunc_page(off));
1076 	KASSERT(obj == NULL || mutex_owned(&obj->vmobjlock));
1077 	KASSERT(anon == NULL || mutex_owned(&anon->an_lock));
1078 
1079 	mutex_spin_enter(&uvm_fpageqlock);
1080 
1081 	/*
1082 	 * This implements a global round-robin page coloring
1083 	 * algorithm.
1084 	 *
1085 	 * XXXJRT: Should we make the `nextcolor' per-CPU?
1086 	 * XXXJRT: What about virtually-indexed caches?
1087 	 */
1088 
1089 	color = uvm.page_free_nextcolor;
1090 
1091 	/*
1092 	 * check to see if we need to generate some free pages waking
1093 	 * the pagedaemon.
1094 	 */
1095 
1096 	uvm_kick_pdaemon();
1097 
1098 	/*
1099 	 * fail if any of these conditions is true:
1100 	 * [1]  there really are no free pages, or
1101 	 * [2]  only kernel "reserved" pages remain and
1102 	 *        the page isn't being allocated to a kernel object.
1103 	 * [3]  only pagedaemon "reserved" pages remain and
1104 	 *        the requestor isn't the pagedaemon.
1105 	 */
1106 
1107 	use_reserve = (flags & UVM_PGA_USERESERVE) ||
1108 		(obj && UVM_OBJ_IS_KERN_OBJECT(obj));
1109 	if ((uvmexp.free <= uvmexp.reserve_kernel && !use_reserve) ||
1110 	    (uvmexp.free <= uvmexp.reserve_pagedaemon &&
1111 	     !(use_reserve && curlwp == uvm.pagedaemon_lwp)))
1112 		goto fail;
1113 
1114 #if PGFL_NQUEUES != 2
1115 #error uvm_pagealloc_strat needs to be updated
1116 #endif
1117 
1118 	/*
1119 	 * If we want a zero'd page, try the ZEROS queue first, otherwise
1120 	 * we try the UNKNOWN queue first.
1121 	 */
1122 	if (flags & UVM_PGA_ZERO) {
1123 		try1 = PGFL_ZEROS;
1124 		try2 = PGFL_UNKNOWN;
1125 	} else {
1126 		try1 = PGFL_UNKNOWN;
1127 		try2 = PGFL_ZEROS;
1128 	}
1129 
1130  again:
1131 	switch (strat) {
1132 	case UVM_PGA_STRAT_NORMAL:
1133 		/* Check all freelists in descending priority order. */
1134 		for (lcv = 0; lcv < VM_NFREELIST; lcv++) {
1135 			pg = uvm_pagealloc_pgfl(&uvm.page_free[lcv],
1136 			    try1, try2, &color);
1137 			if (pg != NULL)
1138 				goto gotit;
1139 		}
1140 
1141 		/* No pages free! */
1142 		goto fail;
1143 
1144 	case UVM_PGA_STRAT_ONLY:
1145 	case UVM_PGA_STRAT_FALLBACK:
1146 		/* Attempt to allocate from the specified free list. */
1147 		KASSERT(free_list >= 0 && free_list < VM_NFREELIST);
1148 		pg = uvm_pagealloc_pgfl(&uvm.page_free[free_list],
1149 		    try1, try2, &color);
1150 		if (pg != NULL)
1151 			goto gotit;
1152 
1153 		/* Fall back, if possible. */
1154 		if (strat == UVM_PGA_STRAT_FALLBACK) {
1155 			strat = UVM_PGA_STRAT_NORMAL;
1156 			goto again;
1157 		}
1158 
1159 		/* No pages free! */
1160 		goto fail;
1161 
1162 	default:
1163 		panic("uvm_pagealloc_strat: bad strat %d", strat);
1164 		/* NOTREACHED */
1165 	}
1166 
1167  gotit:
1168 	/*
1169 	 * We now know which color we actually allocated from; set
1170 	 * the next color accordingly.
1171 	 */
1172 
1173 	uvm.page_free_nextcolor = (color + 1) & uvmexp.colormask;
1174 
1175 	/*
1176 	 * update allocation statistics and remember if we have to
1177 	 * zero the page
1178 	 */
1179 
1180 	if (flags & UVM_PGA_ZERO) {
1181 		if (pg->flags & PG_ZERO) {
1182 			uvmexp.pga_zerohit++;
1183 			zeroit = 0;
1184 		} else {
1185 			uvmexp.pga_zeromiss++;
1186 			zeroit = 1;
1187 		}
1188 	}
1189 	mutex_spin_exit(&uvm_fpageqlock);
1190 
1191 	pg->offset = off;
1192 	pg->uobject = obj;
1193 	pg->uanon = anon;
1194 	pg->flags = PG_BUSY|PG_CLEAN|PG_FAKE;
1195 	if (anon) {
1196 		anon->an_page = pg;
1197 		pg->pqflags = PQ_ANON;
1198 		atomic_inc_uint(&uvmexp.anonpages);
1199 	} else {
1200 		if (obj) {
1201 			uvm_pageinsert(pg);
1202 		}
1203 		pg->pqflags = 0;
1204 	}
1205 #if defined(UVM_PAGE_TRKOWN)
1206 	pg->owner_tag = NULL;
1207 #endif
1208 	UVM_PAGE_OWN(pg, "new alloc");
1209 
1210 	if (flags & UVM_PGA_ZERO) {
1211 		/*
1212 		 * A zero'd page is not clean.  If we got a page not already
1213 		 * zero'd, then we have to zero it ourselves.
1214 		 */
1215 		pg->flags &= ~PG_CLEAN;
1216 		if (zeroit)
1217 			pmap_zero_page(VM_PAGE_TO_PHYS(pg));
1218 	}
1219 
1220 	return(pg);
1221 
1222  fail:
1223 	mutex_spin_exit(&uvm_fpageqlock);
1224 	return (NULL);
1225 }
1226 
1227 /*
1228  * uvm_pagereplace: replace a page with another
1229  *
1230  * => object must be locked
1231  */
1232 
1233 void
1234 uvm_pagereplace(struct vm_page *oldpg, struct vm_page *newpg)
1235 {
1236 
1237 	KASSERT((oldpg->flags & PG_TABLED) != 0);
1238 	KASSERT(oldpg->uobject != NULL);
1239 	KASSERT((newpg->flags & PG_TABLED) == 0);
1240 	KASSERT(newpg->uobject == NULL);
1241 	KASSERT(mutex_owned(&oldpg->uobject->vmobjlock));
1242 
1243 	newpg->uobject = oldpg->uobject;
1244 	newpg->offset = oldpg->offset;
1245 
1246 	uvm_pageinsert_after(newpg, oldpg);
1247 	uvm_pageremove(oldpg);
1248 }
1249 
1250 /*
1251  * uvm_pagerealloc: reallocate a page from one object to another
1252  *
1253  * => both objects must be locked
1254  */
1255 
1256 void
1257 uvm_pagerealloc(struct vm_page *pg, struct uvm_object *newobj, voff_t newoff)
1258 {
1259 	/*
1260 	 * remove it from the old object
1261 	 */
1262 
1263 	if (pg->uobject) {
1264 		uvm_pageremove(pg);
1265 	}
1266 
1267 	/*
1268 	 * put it in the new object
1269 	 */
1270 
1271 	if (newobj) {
1272 		pg->uobject = newobj;
1273 		pg->offset = newoff;
1274 		uvm_pageinsert(pg);
1275 	}
1276 }
1277 
1278 #ifdef DEBUG
1279 /*
1280  * check if page is zero-filled
1281  *
1282  *  - called with free page queue lock held.
1283  */
1284 void
1285 uvm_pagezerocheck(struct vm_page *pg)
1286 {
1287 	int *p, *ep;
1288 
1289 	KASSERT(uvm_zerocheckkva != 0);
1290 	KASSERT(mutex_owned(&uvm_fpageqlock));
1291 
1292 	/*
1293 	 * XXX assuming pmap_kenter_pa and pmap_kremove never call
1294 	 * uvm page allocator.
1295 	 *
1296 	 * it might be better to have "CPU-local temporary map" pmap interface.
1297 	 */
1298 	pmap_kenter_pa(uvm_zerocheckkva, VM_PAGE_TO_PHYS(pg), VM_PROT_READ);
1299 	p = (int *)uvm_zerocheckkva;
1300 	ep = (int *)((char *)p + PAGE_SIZE);
1301 	pmap_update(pmap_kernel());
1302 	while (p < ep) {
1303 		if (*p != 0)
1304 			panic("PG_ZERO page isn't zero-filled");
1305 		p++;
1306 	}
1307 	pmap_kremove(uvm_zerocheckkva, PAGE_SIZE);
1308 }
1309 #endif /* DEBUG */
1310 
1311 /*
1312  * uvm_pagefree: free page
1313  *
1314  * => erase page's identity (i.e. remove from hash/object)
1315  * => put page on free list
1316  * => caller must lock owning object (either anon or uvm_object)
1317  * => caller must lock page queues
1318  * => assumes all valid mappings of pg are gone
1319  */
1320 
1321 void
1322 uvm_pagefree(struct vm_page *pg)
1323 {
1324 	struct pglist *pgfl;
1325 	bool iszero;
1326 
1327 #ifdef DEBUG
1328 	if (pg->uobject == (void *)0xdeadbeef &&
1329 	    pg->uanon == (void *)0xdeadbeef) {
1330 		panic("uvm_pagefree: freeing free page %p", pg);
1331 	}
1332 #endif /* DEBUG */
1333 
1334 	KASSERT((pg->flags & PG_PAGEOUT) == 0);
1335 	KASSERT(mutex_owned(&uvm_pageqlock) || !uvmpdpol_pageisqueued_p(pg));
1336 	KASSERT(pg->uobject == NULL || mutex_owned(&pg->uobject->vmobjlock));
1337 	KASSERT(pg->uobject != NULL || pg->uanon == NULL ||
1338 		mutex_owned(&pg->uanon->an_lock));
1339 
1340 	/*
1341 	 * if the page is loaned, resolve the loan instead of freeing.
1342 	 */
1343 
1344 	if (pg->loan_count) {
1345 		KASSERT(pg->wire_count == 0);
1346 
1347 		/*
1348 		 * if the page is owned by an anon then we just want to
1349 		 * drop anon ownership.  the kernel will free the page when
1350 		 * it is done with it.  if the page is owned by an object,
1351 		 * remove it from the object and mark it dirty for the benefit
1352 		 * of possible anon owners.
1353 		 *
1354 		 * regardless of previous ownership, wakeup any waiters,
1355 		 * unbusy the page, and we're done.
1356 		 */
1357 
1358 		if (pg->uobject != NULL) {
1359 			uvm_pageremove(pg);
1360 			pg->flags &= ~PG_CLEAN;
1361 		} else if (pg->uanon != NULL) {
1362 			if ((pg->pqflags & PQ_ANON) == 0) {
1363 				pg->loan_count--;
1364 			} else {
1365 				pg->pqflags &= ~PQ_ANON;
1366 				atomic_dec_uint(&uvmexp.anonpages);
1367 			}
1368 			pg->uanon->an_page = NULL;
1369 			pg->uanon = NULL;
1370 		}
1371 		if (pg->flags & PG_WANTED) {
1372 			wakeup(pg);
1373 		}
1374 		pg->flags &= ~(PG_WANTED|PG_BUSY|PG_RELEASED|PG_PAGER1);
1375 #ifdef UVM_PAGE_TRKOWN
1376 		pg->owner_tag = NULL;
1377 #endif
1378 		if (pg->loan_count) {
1379 			KASSERT(pg->uobject == NULL);
1380 			if (pg->uanon == NULL) {
1381 				uvm_pagedequeue(pg);
1382 			}
1383 			return;
1384 		}
1385 	}
1386 
1387 	/*
1388 	 * remove page from its object or anon.
1389 	 */
1390 
1391 	if (pg->uobject != NULL) {
1392 		uvm_pageremove(pg);
1393 	} else if (pg->uanon != NULL) {
1394 		pg->uanon->an_page = NULL;
1395 		atomic_dec_uint(&uvmexp.anonpages);
1396 	}
1397 
1398 	/*
1399 	 * now remove the page from the queues.
1400 	 */
1401 
1402 	uvm_pagedequeue(pg);
1403 
1404 	/*
1405 	 * if the page was wired, unwire it now.
1406 	 */
1407 
1408 	if (pg->wire_count) {
1409 		pg->wire_count = 0;
1410 		uvmexp.wired--;
1411 	}
1412 
1413 	/*
1414 	 * and put on free queue
1415 	 */
1416 
1417 	iszero = (pg->flags & PG_ZERO);
1418 	pgfl = &uvm.page_free[uvm_page_lookup_freelist(pg)].
1419 	    pgfl_buckets[VM_PGCOLOR_BUCKET(pg)].
1420 	    pgfl_queues[iszero ? PGFL_ZEROS : PGFL_UNKNOWN];
1421 
1422 	pg->pqflags = PQ_FREE;
1423 #ifdef DEBUG
1424 	pg->uobject = (void *)0xdeadbeef;
1425 	pg->offset = 0xdeadbeef;
1426 	pg->uanon = (void *)0xdeadbeef;
1427 #endif
1428 
1429 	mutex_spin_enter(&uvm_fpageqlock);
1430 
1431 #ifdef DEBUG
1432 	if (iszero)
1433 		uvm_pagezerocheck(pg);
1434 #endif /* DEBUG */
1435 
1436 	TAILQ_INSERT_HEAD(pgfl, pg, pageq);
1437 	uvmexp.free++;
1438 	if (iszero)
1439 		uvmexp.zeropages++;
1440 
1441 	if (uvmexp.zeropages < UVM_PAGEZERO_TARGET)
1442 		uvm.page_idle_zero = vm_page_zero_enable;
1443 
1444 	mutex_spin_exit(&uvm_fpageqlock);
1445 }
1446 
1447 /*
1448  * uvm_page_unbusy: unbusy an array of pages.
1449  *
1450  * => pages must either all belong to the same object, or all belong to anons.
1451  * => if pages are object-owned, object must be locked.
1452  * => if pages are anon-owned, anons must be locked.
1453  * => caller must lock page queues if pages may be released.
1454  * => caller must make sure that anon-owned pages are not PG_RELEASED.
1455  */
1456 
1457 void
1458 uvm_page_unbusy(struct vm_page **pgs, int npgs)
1459 {
1460 	struct vm_page *pg;
1461 	int i;
1462 	UVMHIST_FUNC("uvm_page_unbusy"); UVMHIST_CALLED(ubchist);
1463 
1464 	for (i = 0; i < npgs; i++) {
1465 		pg = pgs[i];
1466 		if (pg == NULL || pg == PGO_DONTCARE) {
1467 			continue;
1468 		}
1469 
1470 		KASSERT(pg->uobject == NULL ||
1471 		    mutex_owned(&pg->uobject->vmobjlock));
1472 		KASSERT(pg->uobject != NULL ||
1473 		    (pg->uanon != NULL && mutex_owned(&pg->uanon->an_lock)));
1474 
1475 		KASSERT(pg->flags & PG_BUSY);
1476 		KASSERT((pg->flags & PG_PAGEOUT) == 0);
1477 		if (pg->flags & PG_WANTED) {
1478 			wakeup(pg);
1479 		}
1480 		if (pg->flags & PG_RELEASED) {
1481 			UVMHIST_LOG(ubchist, "releasing pg %p", pg,0,0,0);
1482 			KASSERT(pg->uobject != NULL ||
1483 			    (pg->uanon != NULL && pg->uanon->an_ref > 0));
1484 			pg->flags &= ~PG_RELEASED;
1485 			uvm_pagefree(pg);
1486 		} else {
1487 			UVMHIST_LOG(ubchist, "unbusying pg %p", pg,0,0,0);
1488 			pg->flags &= ~(PG_WANTED|PG_BUSY);
1489 			UVM_PAGE_OWN(pg, NULL);
1490 		}
1491 	}
1492 }
1493 
1494 #if defined(UVM_PAGE_TRKOWN)
1495 /*
1496  * uvm_page_own: set or release page ownership
1497  *
1498  * => this is a debugging function that keeps track of who sets PG_BUSY
1499  *	and where they do it.   it can be used to track down problems
1500  *	such a process setting "PG_BUSY" and never releasing it.
1501  * => page's object [if any] must be locked
1502  * => if "tag" is NULL then we are releasing page ownership
1503  */
1504 void
1505 uvm_page_own(struct vm_page *pg, const char *tag)
1506 {
1507 	struct uvm_object *uobj;
1508 	struct vm_anon *anon;
1509 
1510 	KASSERT((pg->flags & (PG_PAGEOUT|PG_RELEASED)) == 0);
1511 
1512 	uobj = pg->uobject;
1513 	anon = pg->uanon;
1514 	if (uobj != NULL) {
1515 		KASSERT(mutex_owned(&uobj->vmobjlock));
1516 	} else if (anon != NULL) {
1517 		KASSERT(mutex_owned(&anon->an_lock));
1518 	}
1519 
1520 	KASSERT((pg->flags & PG_WANTED) == 0);
1521 
1522 	/* gain ownership? */
1523 	if (tag) {
1524 		KASSERT((pg->flags & PG_BUSY) != 0);
1525 		if (pg->owner_tag) {
1526 			printf("uvm_page_own: page %p already owned "
1527 			    "by proc %d [%s]\n", pg,
1528 			    pg->owner, pg->owner_tag);
1529 			panic("uvm_page_own");
1530 		}
1531 		pg->owner = (curproc) ? curproc->p_pid :  (pid_t) -1;
1532 		pg->lowner = (curlwp) ? curlwp->l_lid :  (lwpid_t) -1;
1533 		pg->owner_tag = tag;
1534 		return;
1535 	}
1536 
1537 	/* drop ownership */
1538 	KASSERT((pg->flags & PG_BUSY) == 0);
1539 	if (pg->owner_tag == NULL) {
1540 		printf("uvm_page_own: dropping ownership of an non-owned "
1541 		    "page (%p)\n", pg);
1542 		panic("uvm_page_own");
1543 	}
1544 	if (!uvmpdpol_pageisqueued_p(pg)) {
1545 		KASSERT((pg->uanon == NULL && pg->uobject == NULL) ||
1546 		    pg->wire_count > 0);
1547 	} else {
1548 		KASSERT(pg->wire_count == 0);
1549 	}
1550 	pg->owner_tag = NULL;
1551 }
1552 #endif
1553 
1554 /*
1555  * uvm_pageidlezero: zero free pages while the system is idle.
1556  *
1557  * => try to complete one color bucket at a time, to reduce our impact
1558  *	on the CPU cache.
1559  * => we loop until we either reach the target or there is a lwp ready to run.
1560  */
1561 void
1562 uvm_pageidlezero(void)
1563 {
1564 	struct vm_page *pg;
1565 	struct pgfreelist *pgfl;
1566 	int free_list, firstbucket;
1567 	static int nextbucket;
1568 
1569 	mutex_spin_enter(&uvm_fpageqlock);
1570 	firstbucket = nextbucket;
1571 	do {
1572 		if (sched_curcpu_runnable_p()) {
1573 			goto quit;
1574 		}
1575 		if (uvmexp.zeropages >= UVM_PAGEZERO_TARGET) {
1576 			uvm.page_idle_zero = false;
1577 			goto quit;
1578 		}
1579 		for (free_list = 0; free_list < VM_NFREELIST; free_list++) {
1580 			pgfl = &uvm.page_free[free_list];
1581 			while ((pg = TAILQ_FIRST(&pgfl->pgfl_buckets[
1582 			    nextbucket].pgfl_queues[PGFL_UNKNOWN])) != NULL) {
1583 				if (sched_curcpu_runnable_p())
1584 					goto quit;
1585 
1586 				TAILQ_REMOVE(&pgfl->pgfl_buckets[
1587 				    nextbucket].pgfl_queues[PGFL_UNKNOWN],
1588 				    pg, pageq);
1589 				uvmexp.free--;
1590 				mutex_spin_exit(&uvm_fpageqlock);
1591 #ifdef PMAP_PAGEIDLEZERO
1592 				if (!PMAP_PAGEIDLEZERO(VM_PAGE_TO_PHYS(pg))) {
1593 
1594 					/*
1595 					 * The machine-dependent code detected
1596 					 * some reason for us to abort zeroing
1597 					 * pages, probably because there is a
1598 					 * process now ready to run.
1599 					 */
1600 
1601 					mutex_spin_enter(&uvm_fpageqlock);
1602 					TAILQ_INSERT_HEAD(&pgfl->pgfl_buckets[
1603 					    nextbucket].pgfl_queues[
1604 					    PGFL_UNKNOWN], pg, pageq);
1605 					uvmexp.free++;
1606 					uvmexp.zeroaborts++;
1607 					goto quit;
1608 				}
1609 #else
1610 				pmap_zero_page(VM_PAGE_TO_PHYS(pg));
1611 #endif /* PMAP_PAGEIDLEZERO */
1612 				pg->flags |= PG_ZERO;
1613 
1614 				mutex_spin_enter(&uvm_fpageqlock);
1615 				TAILQ_INSERT_HEAD(&pgfl->pgfl_buckets[
1616 				    nextbucket].pgfl_queues[PGFL_ZEROS],
1617 				    pg, pageq);
1618 				uvmexp.free++;
1619 				uvmexp.zeropages++;
1620 			}
1621 		}
1622 		nextbucket = (nextbucket + 1) & uvmexp.colormask;
1623 	} while (nextbucket != firstbucket);
1624 quit:
1625 	mutex_spin_exit(&uvm_fpageqlock);
1626 }
1627 
1628 /*
1629  * uvm_pagelookup: look up a page
1630  *
1631  * => caller should lock object to keep someone from pulling the page
1632  *	out from under it
1633  */
1634 
1635 struct vm_page *
1636 uvm_pagelookup(struct uvm_object *obj, voff_t off)
1637 {
1638 	struct vm_page *pg;
1639 	struct pglist *buck;
1640 	kmutex_t *lock;
1641 	u_int hash;
1642 
1643 	KASSERT(mutex_owned(&obj->vmobjlock));
1644 
1645 	hash = uvm_pagehash(obj, off);
1646 	buck = &uvm.page_hash[hash];
1647 	lock = uvm_hashlock(hash);
1648 	mutex_spin_enter(lock);
1649 	TAILQ_FOREACH(pg, buck, hashq) {
1650 		if (pg->uobject == obj && pg->offset == off) {
1651 			break;
1652 		}
1653 	}
1654 	mutex_spin_exit(lock);
1655 	KASSERT(pg == NULL || obj->uo_npages != 0);
1656 	KASSERT(pg == NULL || (pg->flags & (PG_RELEASED|PG_PAGEOUT)) == 0 ||
1657 		(pg->flags & PG_BUSY) != 0);
1658 	return(pg);
1659 }
1660 
1661 /*
1662  * uvm_pagewire: wire the page, thus removing it from the daemon's grasp
1663  *
1664  * => caller must lock page queues
1665  */
1666 
1667 void
1668 uvm_pagewire(struct vm_page *pg)
1669 {
1670 	KASSERT(mutex_owned(&uvm_pageqlock));
1671 #if defined(READAHEAD_STATS)
1672 	if ((pg->pqflags & PQ_READAHEAD) != 0) {
1673 		uvm_ra_hit.ev_count++;
1674 		pg->pqflags &= ~PQ_READAHEAD;
1675 	}
1676 #endif /* defined(READAHEAD_STATS) */
1677 	if (pg->wire_count == 0) {
1678 		uvm_pagedequeue(pg);
1679 		uvmexp.wired++;
1680 	}
1681 	pg->wire_count++;
1682 }
1683 
1684 /*
1685  * uvm_pageunwire: unwire the page.
1686  *
1687  * => activate if wire count goes to zero.
1688  * => caller must lock page queues
1689  */
1690 
1691 void
1692 uvm_pageunwire(struct vm_page *pg)
1693 {
1694 	KASSERT(mutex_owned(&uvm_pageqlock));
1695 	pg->wire_count--;
1696 	if (pg->wire_count == 0) {
1697 		uvm_pageactivate(pg);
1698 		uvmexp.wired--;
1699 	}
1700 }
1701 
1702 /*
1703  * uvm_pagedeactivate: deactivate page
1704  *
1705  * => caller must lock page queues
1706  * => caller must check to make sure page is not wired
1707  * => object that page belongs to must be locked (so we can adjust pg->flags)
1708  * => caller must clear the reference on the page before calling
1709  */
1710 
1711 void
1712 uvm_pagedeactivate(struct vm_page *pg)
1713 {
1714 
1715 	KASSERT(mutex_owned(&uvm_pageqlock));
1716 	KASSERT(pg->wire_count != 0 || uvmpdpol_pageisqueued_p(pg));
1717 	uvmpdpol_pagedeactivate(pg);
1718 }
1719 
1720 /*
1721  * uvm_pageactivate: activate page
1722  *
1723  * => caller must lock page queues
1724  */
1725 
1726 void
1727 uvm_pageactivate(struct vm_page *pg)
1728 {
1729 
1730 	KASSERT(mutex_owned(&uvm_pageqlock));
1731 #if defined(READAHEAD_STATS)
1732 	if ((pg->pqflags & PQ_READAHEAD) != 0) {
1733 		uvm_ra_hit.ev_count++;
1734 		pg->pqflags &= ~PQ_READAHEAD;
1735 	}
1736 #endif /* defined(READAHEAD_STATS) */
1737 	if (pg->wire_count != 0) {
1738 		return;
1739 	}
1740 	uvmpdpol_pageactivate(pg);
1741 }
1742 
1743 /*
1744  * uvm_pagedequeue: remove a page from any paging queue
1745  */
1746 
1747 void
1748 uvm_pagedequeue(struct vm_page *pg)
1749 {
1750 
1751 	if (uvmpdpol_pageisqueued_p(pg)) {
1752 		KASSERT(mutex_owned(&uvm_pageqlock));
1753 	}
1754 
1755 	uvmpdpol_pagedequeue(pg);
1756 }
1757 
1758 /*
1759  * uvm_pageenqueue: add a page to a paging queue without activating.
1760  * used where a page is not really demanded (yet).  eg. read-ahead
1761  */
1762 
1763 void
1764 uvm_pageenqueue(struct vm_page *pg)
1765 {
1766 
1767 	KASSERT(mutex_owned(&uvm_pageqlock));
1768 	if (pg->wire_count != 0) {
1769 		return;
1770 	}
1771 	uvmpdpol_pageenqueue(pg);
1772 }
1773 
1774 /*
1775  * uvm_pagezero: zero fill a page
1776  *
1777  * => if page is part of an object then the object should be locked
1778  *	to protect pg->flags.
1779  */
1780 
1781 void
1782 uvm_pagezero(struct vm_page *pg)
1783 {
1784 	pg->flags &= ~PG_CLEAN;
1785 	pmap_zero_page(VM_PAGE_TO_PHYS(pg));
1786 }
1787 
1788 /*
1789  * uvm_pagecopy: copy a page
1790  *
1791  * => if page is part of an object then the object should be locked
1792  *	to protect pg->flags.
1793  */
1794 
1795 void
1796 uvm_pagecopy(struct vm_page *src, struct vm_page *dst)
1797 {
1798 
1799 	dst->flags &= ~PG_CLEAN;
1800 	pmap_copy_page(VM_PAGE_TO_PHYS(src), VM_PAGE_TO_PHYS(dst));
1801 }
1802 
1803 /*
1804  * uvm_page_lookup_freelist: look up the free list for the specified page
1805  */
1806 
1807 int
1808 uvm_page_lookup_freelist(struct vm_page *pg)
1809 {
1810 	int lcv;
1811 
1812 	lcv = vm_physseg_find(atop(VM_PAGE_TO_PHYS(pg)), NULL);
1813 	KASSERT(lcv != -1);
1814 	return (vm_physmem[lcv].free_list);
1815 }
1816