xref: /netbsd-src/sys/uvm/uvm_page.c (revision 8ac07aec990b9d2e483062509d0a9fa5b4f57cf2)
1 /*	$NetBSD: uvm_page.c,v 1.131 2008/03/24 08:53:25 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.131 2008/03/24 08:53:25 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 	KASSERT(mutex_owned(&uvm_fpageqlock));
1017 
1018 	color = trycolor;
1019 	do {
1020 		if ((pg = TAILQ_FIRST((freeq =
1021 		    &pgfl->pgfl_buckets[color].pgfl_queues[try1]))) != NULL)
1022 			goto gotit;
1023 		if ((pg = TAILQ_FIRST((freeq =
1024 		    &pgfl->pgfl_buckets[color].pgfl_queues[try2]))) != NULL)
1025 			goto gotit;
1026 		color = (color + 1) & uvmexp.colormask;
1027 	} while (color != trycolor);
1028 
1029 	return (NULL);
1030 
1031  gotit:
1032 	TAILQ_REMOVE(freeq, pg, pageq);
1033 	uvmexp.free--;
1034 
1035 	/* update zero'd page count */
1036 	if (pg->flags & PG_ZERO)
1037 		uvmexp.zeropages--;
1038 
1039 	if (color == trycolor)
1040 		uvmexp.colorhit++;
1041 	else {
1042 		uvmexp.colormiss++;
1043 		*trycolorp = color;
1044 	}
1045 
1046 	return (pg);
1047 }
1048 
1049 /*
1050  * uvm_pagealloc_strat: allocate vm_page from a particular free list.
1051  *
1052  * => return null if no pages free
1053  * => wake up pagedaemon if number of free pages drops below low water mark
1054  * => if obj != NULL, obj must be locked (to put in hash)
1055  * => if anon != NULL, anon must be locked (to put in anon)
1056  * => only one of obj or anon can be non-null
1057  * => caller must activate/deactivate page if it is not wired.
1058  * => free_list is ignored if strat == UVM_PGA_STRAT_NORMAL.
1059  * => policy decision: it is more important to pull a page off of the
1060  *	appropriate priority free list than it is to get a zero'd or
1061  *	unknown contents page.  This is because we live with the
1062  *	consequences of a bad free list decision for the entire
1063  *	lifetime of the page, e.g. if the page comes from memory that
1064  *	is slower to access.
1065  */
1066 
1067 struct vm_page *
1068 uvm_pagealloc_strat(struct uvm_object *obj, voff_t off, struct vm_anon *anon,
1069     int flags, int strat, int free_list)
1070 {
1071 	int lcv, try1, try2, zeroit = 0, color;
1072 	struct vm_page *pg;
1073 	bool use_reserve;
1074 
1075 	KASSERT(obj == NULL || anon == NULL);
1076 	KASSERT(anon == NULL || off == 0);
1077 	KASSERT(off == trunc_page(off));
1078 	KASSERT(obj == NULL || mutex_owned(&obj->vmobjlock));
1079 	KASSERT(anon == NULL || mutex_owned(&anon->an_lock));
1080 
1081 	mutex_spin_enter(&uvm_fpageqlock);
1082 
1083 	/*
1084 	 * This implements a global round-robin page coloring
1085 	 * algorithm.
1086 	 *
1087 	 * XXXJRT: Should we make the `nextcolor' per-CPU?
1088 	 * XXXJRT: What about virtually-indexed caches?
1089 	 */
1090 
1091 	color = uvm.page_free_nextcolor;
1092 
1093 	/*
1094 	 * check to see if we need to generate some free pages waking
1095 	 * the pagedaemon.
1096 	 */
1097 
1098 	uvm_kick_pdaemon();
1099 
1100 	/*
1101 	 * fail if any of these conditions is true:
1102 	 * [1]  there really are no free pages, or
1103 	 * [2]  only kernel "reserved" pages remain and
1104 	 *        the page isn't being allocated to a kernel object.
1105 	 * [3]  only pagedaemon "reserved" pages remain and
1106 	 *        the requestor isn't the pagedaemon.
1107 	 */
1108 
1109 	use_reserve = (flags & UVM_PGA_USERESERVE) ||
1110 		(obj && UVM_OBJ_IS_KERN_OBJECT(obj));
1111 	if ((uvmexp.free <= uvmexp.reserve_kernel && !use_reserve) ||
1112 	    (uvmexp.free <= uvmexp.reserve_pagedaemon &&
1113 	     !(use_reserve && curlwp == uvm.pagedaemon_lwp)))
1114 		goto fail;
1115 
1116 #if PGFL_NQUEUES != 2
1117 #error uvm_pagealloc_strat needs to be updated
1118 #endif
1119 
1120 	/*
1121 	 * If we want a zero'd page, try the ZEROS queue first, otherwise
1122 	 * we try the UNKNOWN queue first.
1123 	 */
1124 	if (flags & UVM_PGA_ZERO) {
1125 		try1 = PGFL_ZEROS;
1126 		try2 = PGFL_UNKNOWN;
1127 	} else {
1128 		try1 = PGFL_UNKNOWN;
1129 		try2 = PGFL_ZEROS;
1130 	}
1131 
1132  again:
1133 	switch (strat) {
1134 	case UVM_PGA_STRAT_NORMAL:
1135 		/* Check all freelists in descending priority order. */
1136 		for (lcv = 0; lcv < VM_NFREELIST; lcv++) {
1137 			pg = uvm_pagealloc_pgfl(&uvm.page_free[lcv],
1138 			    try1, try2, &color);
1139 			if (pg != NULL)
1140 				goto gotit;
1141 		}
1142 
1143 		/* No pages free! */
1144 		goto fail;
1145 
1146 	case UVM_PGA_STRAT_ONLY:
1147 	case UVM_PGA_STRAT_FALLBACK:
1148 		/* Attempt to allocate from the specified free list. */
1149 		KASSERT(free_list >= 0 && free_list < VM_NFREELIST);
1150 		pg = uvm_pagealloc_pgfl(&uvm.page_free[free_list],
1151 		    try1, try2, &color);
1152 		if (pg != NULL)
1153 			goto gotit;
1154 
1155 		/* Fall back, if possible. */
1156 		if (strat == UVM_PGA_STRAT_FALLBACK) {
1157 			strat = UVM_PGA_STRAT_NORMAL;
1158 			goto again;
1159 		}
1160 
1161 		/* No pages free! */
1162 		goto fail;
1163 
1164 	default:
1165 		panic("uvm_pagealloc_strat: bad strat %d", strat);
1166 		/* NOTREACHED */
1167 	}
1168 
1169  gotit:
1170 	/*
1171 	 * We now know which color we actually allocated from; set
1172 	 * the next color accordingly.
1173 	 */
1174 
1175 	uvm.page_free_nextcolor = (color + 1) & uvmexp.colormask;
1176 
1177 	/*
1178 	 * update allocation statistics and remember if we have to
1179 	 * zero the page
1180 	 */
1181 
1182 	if (flags & UVM_PGA_ZERO) {
1183 		if (pg->flags & PG_ZERO) {
1184 			uvmexp.pga_zerohit++;
1185 			zeroit = 0;
1186 		} else {
1187 			uvmexp.pga_zeromiss++;
1188 			zeroit = 1;
1189 		}
1190 	}
1191 	mutex_spin_exit(&uvm_fpageqlock);
1192 
1193 	pg->offset = off;
1194 	pg->uobject = obj;
1195 	pg->uanon = anon;
1196 	pg->flags = PG_BUSY|PG_CLEAN|PG_FAKE;
1197 	if (anon) {
1198 		anon->an_page = pg;
1199 		pg->pqflags = PQ_ANON;
1200 		atomic_inc_uint(&uvmexp.anonpages);
1201 	} else {
1202 		if (obj) {
1203 			uvm_pageinsert(pg);
1204 		}
1205 		pg->pqflags = 0;
1206 	}
1207 #if defined(UVM_PAGE_TRKOWN)
1208 	pg->owner_tag = NULL;
1209 #endif
1210 	UVM_PAGE_OWN(pg, "new alloc");
1211 
1212 	if (flags & UVM_PGA_ZERO) {
1213 		/*
1214 		 * A zero'd page is not clean.  If we got a page not already
1215 		 * zero'd, then we have to zero it ourselves.
1216 		 */
1217 		pg->flags &= ~PG_CLEAN;
1218 		if (zeroit)
1219 			pmap_zero_page(VM_PAGE_TO_PHYS(pg));
1220 	}
1221 
1222 	return(pg);
1223 
1224  fail:
1225 	mutex_spin_exit(&uvm_fpageqlock);
1226 	return (NULL);
1227 }
1228 
1229 /*
1230  * uvm_pagereplace: replace a page with another
1231  *
1232  * => object must be locked
1233  */
1234 
1235 void
1236 uvm_pagereplace(struct vm_page *oldpg, struct vm_page *newpg)
1237 {
1238 
1239 	KASSERT((oldpg->flags & PG_TABLED) != 0);
1240 	KASSERT(oldpg->uobject != NULL);
1241 	KASSERT((newpg->flags & PG_TABLED) == 0);
1242 	KASSERT(newpg->uobject == NULL);
1243 	KASSERT(mutex_owned(&oldpg->uobject->vmobjlock));
1244 
1245 	newpg->uobject = oldpg->uobject;
1246 	newpg->offset = oldpg->offset;
1247 
1248 	uvm_pageinsert_after(newpg, oldpg);
1249 	uvm_pageremove(oldpg);
1250 }
1251 
1252 /*
1253  * uvm_pagerealloc: reallocate a page from one object to another
1254  *
1255  * => both objects must be locked
1256  */
1257 
1258 void
1259 uvm_pagerealloc(struct vm_page *pg, struct uvm_object *newobj, voff_t newoff)
1260 {
1261 	/*
1262 	 * remove it from the old object
1263 	 */
1264 
1265 	if (pg->uobject) {
1266 		uvm_pageremove(pg);
1267 	}
1268 
1269 	/*
1270 	 * put it in the new object
1271 	 */
1272 
1273 	if (newobj) {
1274 		pg->uobject = newobj;
1275 		pg->offset = newoff;
1276 		uvm_pageinsert(pg);
1277 	}
1278 }
1279 
1280 #ifdef DEBUG
1281 /*
1282  * check if page is zero-filled
1283  *
1284  *  - called with free page queue lock held.
1285  */
1286 void
1287 uvm_pagezerocheck(struct vm_page *pg)
1288 {
1289 	int *p, *ep;
1290 
1291 	KASSERT(uvm_zerocheckkva != 0);
1292 	KASSERT(mutex_owned(&uvm_fpageqlock));
1293 
1294 	/*
1295 	 * XXX assuming pmap_kenter_pa and pmap_kremove never call
1296 	 * uvm page allocator.
1297 	 *
1298 	 * it might be better to have "CPU-local temporary map" pmap interface.
1299 	 */
1300 	pmap_kenter_pa(uvm_zerocheckkva, VM_PAGE_TO_PHYS(pg), VM_PROT_READ);
1301 	p = (int *)uvm_zerocheckkva;
1302 	ep = (int *)((char *)p + PAGE_SIZE);
1303 	pmap_update(pmap_kernel());
1304 	while (p < ep) {
1305 		if (*p != 0)
1306 			panic("PG_ZERO page isn't zero-filled");
1307 		p++;
1308 	}
1309 	pmap_kremove(uvm_zerocheckkva, PAGE_SIZE);
1310 	/*
1311 	 * pmap_update() is not necessary here because no one except us
1312 	 * uses this VA.
1313 	 */
1314 }
1315 #endif /* DEBUG */
1316 
1317 /*
1318  * uvm_pagefree: free page
1319  *
1320  * => erase page's identity (i.e. remove from hash/object)
1321  * => put page on free list
1322  * => caller must lock owning object (either anon or uvm_object)
1323  * => caller must lock page queues
1324  * => assumes all valid mappings of pg are gone
1325  */
1326 
1327 void
1328 uvm_pagefree(struct vm_page *pg)
1329 {
1330 	struct pglist *pgfl;
1331 	bool iszero;
1332 
1333 #ifdef DEBUG
1334 	if (pg->uobject == (void *)0xdeadbeef &&
1335 	    pg->uanon == (void *)0xdeadbeef) {
1336 		panic("uvm_pagefree: freeing free page %p", pg);
1337 	}
1338 #endif /* DEBUG */
1339 
1340 	KASSERT((pg->flags & PG_PAGEOUT) == 0);
1341 	KASSERT(mutex_owned(&uvm_pageqlock) || !uvmpdpol_pageisqueued_p(pg));
1342 	KASSERT(pg->uobject == NULL || mutex_owned(&pg->uobject->vmobjlock));
1343 	KASSERT(pg->uobject != NULL || pg->uanon == NULL ||
1344 		mutex_owned(&pg->uanon->an_lock));
1345 
1346 	/*
1347 	 * if the page is loaned, resolve the loan instead of freeing.
1348 	 */
1349 
1350 	if (pg->loan_count) {
1351 		KASSERT(pg->wire_count == 0);
1352 
1353 		/*
1354 		 * if the page is owned by an anon then we just want to
1355 		 * drop anon ownership.  the kernel will free the page when
1356 		 * it is done with it.  if the page is owned by an object,
1357 		 * remove it from the object and mark it dirty for the benefit
1358 		 * of possible anon owners.
1359 		 *
1360 		 * regardless of previous ownership, wakeup any waiters,
1361 		 * unbusy the page, and we're done.
1362 		 */
1363 
1364 		if (pg->uobject != NULL) {
1365 			uvm_pageremove(pg);
1366 			pg->flags &= ~PG_CLEAN;
1367 		} else if (pg->uanon != NULL) {
1368 			if ((pg->pqflags & PQ_ANON) == 0) {
1369 				pg->loan_count--;
1370 			} else {
1371 				pg->pqflags &= ~PQ_ANON;
1372 				atomic_dec_uint(&uvmexp.anonpages);
1373 			}
1374 			pg->uanon->an_page = NULL;
1375 			pg->uanon = NULL;
1376 		}
1377 		if (pg->flags & PG_WANTED) {
1378 			wakeup(pg);
1379 		}
1380 		pg->flags &= ~(PG_WANTED|PG_BUSY|PG_RELEASED|PG_PAGER1);
1381 #ifdef UVM_PAGE_TRKOWN
1382 		pg->owner_tag = NULL;
1383 #endif
1384 		if (pg->loan_count) {
1385 			KASSERT(pg->uobject == NULL);
1386 			if (pg->uanon == NULL) {
1387 				uvm_pagedequeue(pg);
1388 			}
1389 			return;
1390 		}
1391 	}
1392 
1393 	/*
1394 	 * remove page from its object or anon.
1395 	 */
1396 
1397 	if (pg->uobject != NULL) {
1398 		uvm_pageremove(pg);
1399 	} else if (pg->uanon != NULL) {
1400 		pg->uanon->an_page = NULL;
1401 		atomic_dec_uint(&uvmexp.anonpages);
1402 	}
1403 
1404 	/*
1405 	 * now remove the page from the queues.
1406 	 */
1407 
1408 	uvm_pagedequeue(pg);
1409 
1410 	/*
1411 	 * if the page was wired, unwire it now.
1412 	 */
1413 
1414 	if (pg->wire_count) {
1415 		pg->wire_count = 0;
1416 		uvmexp.wired--;
1417 	}
1418 
1419 	/*
1420 	 * and put on free queue
1421 	 */
1422 
1423 	iszero = (pg->flags & PG_ZERO);
1424 	pgfl = &uvm.page_free[uvm_page_lookup_freelist(pg)].
1425 	    pgfl_buckets[VM_PGCOLOR_BUCKET(pg)].
1426 	    pgfl_queues[iszero ? PGFL_ZEROS : PGFL_UNKNOWN];
1427 
1428 	pg->pqflags = PQ_FREE;
1429 #ifdef DEBUG
1430 	pg->uobject = (void *)0xdeadbeef;
1431 	pg->offset = 0xdeadbeef;
1432 	pg->uanon = (void *)0xdeadbeef;
1433 #endif
1434 
1435 	mutex_spin_enter(&uvm_fpageqlock);
1436 
1437 #ifdef DEBUG
1438 	if (iszero)
1439 		uvm_pagezerocheck(pg);
1440 #endif /* DEBUG */
1441 
1442 	TAILQ_INSERT_HEAD(pgfl, pg, pageq);
1443 	uvmexp.free++;
1444 	if (iszero)
1445 		uvmexp.zeropages++;
1446 
1447 	if (uvmexp.zeropages < UVM_PAGEZERO_TARGET)
1448 		uvm.page_idle_zero = vm_page_zero_enable;
1449 
1450 	mutex_spin_exit(&uvm_fpageqlock);
1451 }
1452 
1453 /*
1454  * uvm_page_unbusy: unbusy an array of pages.
1455  *
1456  * => pages must either all belong to the same object, or all belong to anons.
1457  * => if pages are object-owned, object must be locked.
1458  * => if pages are anon-owned, anons must be locked.
1459  * => caller must lock page queues if pages may be released.
1460  * => caller must make sure that anon-owned pages are not PG_RELEASED.
1461  */
1462 
1463 void
1464 uvm_page_unbusy(struct vm_page **pgs, int npgs)
1465 {
1466 	struct vm_page *pg;
1467 	int i;
1468 	UVMHIST_FUNC("uvm_page_unbusy"); UVMHIST_CALLED(ubchist);
1469 
1470 	for (i = 0; i < npgs; i++) {
1471 		pg = pgs[i];
1472 		if (pg == NULL || pg == PGO_DONTCARE) {
1473 			continue;
1474 		}
1475 
1476 		KASSERT(pg->uobject == NULL ||
1477 		    mutex_owned(&pg->uobject->vmobjlock));
1478 		KASSERT(pg->uobject != NULL ||
1479 		    (pg->uanon != NULL && mutex_owned(&pg->uanon->an_lock)));
1480 
1481 		KASSERT(pg->flags & PG_BUSY);
1482 		KASSERT((pg->flags & PG_PAGEOUT) == 0);
1483 		if (pg->flags & PG_WANTED) {
1484 			wakeup(pg);
1485 		}
1486 		if (pg->flags & PG_RELEASED) {
1487 			UVMHIST_LOG(ubchist, "releasing pg %p", pg,0,0,0);
1488 			KASSERT(pg->uobject != NULL ||
1489 			    (pg->uanon != NULL && pg->uanon->an_ref > 0));
1490 			pg->flags &= ~PG_RELEASED;
1491 			uvm_pagefree(pg);
1492 		} else {
1493 			UVMHIST_LOG(ubchist, "unbusying pg %p", pg,0,0,0);
1494 			pg->flags &= ~(PG_WANTED|PG_BUSY);
1495 			UVM_PAGE_OWN(pg, NULL);
1496 		}
1497 	}
1498 }
1499 
1500 #if defined(UVM_PAGE_TRKOWN)
1501 /*
1502  * uvm_page_own: set or release page ownership
1503  *
1504  * => this is a debugging function that keeps track of who sets PG_BUSY
1505  *	and where they do it.   it can be used to track down problems
1506  *	such a process setting "PG_BUSY" and never releasing it.
1507  * => page's object [if any] must be locked
1508  * => if "tag" is NULL then we are releasing page ownership
1509  */
1510 void
1511 uvm_page_own(struct vm_page *pg, const char *tag)
1512 {
1513 	struct uvm_object *uobj;
1514 	struct vm_anon *anon;
1515 
1516 	KASSERT((pg->flags & (PG_PAGEOUT|PG_RELEASED)) == 0);
1517 
1518 	uobj = pg->uobject;
1519 	anon = pg->uanon;
1520 	if (uobj != NULL) {
1521 		KASSERT(mutex_owned(&uobj->vmobjlock));
1522 	} else if (anon != NULL) {
1523 		KASSERT(mutex_owned(&anon->an_lock));
1524 	}
1525 
1526 	KASSERT((pg->flags & PG_WANTED) == 0);
1527 
1528 	/* gain ownership? */
1529 	if (tag) {
1530 		KASSERT((pg->flags & PG_BUSY) != 0);
1531 		if (pg->owner_tag) {
1532 			printf("uvm_page_own: page %p already owned "
1533 			    "by proc %d [%s]\n", pg,
1534 			    pg->owner, pg->owner_tag);
1535 			panic("uvm_page_own");
1536 		}
1537 		pg->owner = (curproc) ? curproc->p_pid :  (pid_t) -1;
1538 		pg->lowner = (curlwp) ? curlwp->l_lid :  (lwpid_t) -1;
1539 		pg->owner_tag = tag;
1540 		return;
1541 	}
1542 
1543 	/* drop ownership */
1544 	KASSERT((pg->flags & PG_BUSY) == 0);
1545 	if (pg->owner_tag == NULL) {
1546 		printf("uvm_page_own: dropping ownership of an non-owned "
1547 		    "page (%p)\n", pg);
1548 		panic("uvm_page_own");
1549 	}
1550 	if (!uvmpdpol_pageisqueued_p(pg)) {
1551 		KASSERT((pg->uanon == NULL && pg->uobject == NULL) ||
1552 		    pg->wire_count > 0);
1553 	} else {
1554 		KASSERT(pg->wire_count == 0);
1555 	}
1556 	pg->owner_tag = NULL;
1557 }
1558 #endif
1559 
1560 /*
1561  * uvm_pageidlezero: zero free pages while the system is idle.
1562  *
1563  * => try to complete one color bucket at a time, to reduce our impact
1564  *	on the CPU cache.
1565  * => we loop until we either reach the target or there is a lwp ready to run.
1566  */
1567 void
1568 uvm_pageidlezero(void)
1569 {
1570 	struct vm_page *pg;
1571 	struct pgfreelist *pgfl;
1572 	int free_list, firstbucket;
1573 	static int nextbucket;
1574 
1575 	mutex_spin_enter(&uvm_fpageqlock);
1576 	firstbucket = nextbucket;
1577 	do {
1578 		if (sched_curcpu_runnable_p()) {
1579 			goto quit;
1580 		}
1581 		if (uvmexp.zeropages >= UVM_PAGEZERO_TARGET) {
1582 			uvm.page_idle_zero = false;
1583 			goto quit;
1584 		}
1585 		for (free_list = 0; free_list < VM_NFREELIST; free_list++) {
1586 			pgfl = &uvm.page_free[free_list];
1587 			while ((pg = TAILQ_FIRST(&pgfl->pgfl_buckets[
1588 			    nextbucket].pgfl_queues[PGFL_UNKNOWN])) != NULL) {
1589 				if (sched_curcpu_runnable_p())
1590 					goto quit;
1591 
1592 				TAILQ_REMOVE(&pgfl->pgfl_buckets[
1593 				    nextbucket].pgfl_queues[PGFL_UNKNOWN],
1594 				    pg, pageq);
1595 				uvmexp.free--;
1596 				mutex_spin_exit(&uvm_fpageqlock);
1597 #ifdef PMAP_PAGEIDLEZERO
1598 				if (!PMAP_PAGEIDLEZERO(VM_PAGE_TO_PHYS(pg))) {
1599 
1600 					/*
1601 					 * The machine-dependent code detected
1602 					 * some reason for us to abort zeroing
1603 					 * pages, probably because there is a
1604 					 * process now ready to run.
1605 					 */
1606 
1607 					mutex_spin_enter(&uvm_fpageqlock);
1608 					TAILQ_INSERT_HEAD(&pgfl->pgfl_buckets[
1609 					    nextbucket].pgfl_queues[
1610 					    PGFL_UNKNOWN], pg, pageq);
1611 					uvmexp.free++;
1612 					uvmexp.zeroaborts++;
1613 					goto quit;
1614 				}
1615 #else
1616 				pmap_zero_page(VM_PAGE_TO_PHYS(pg));
1617 #endif /* PMAP_PAGEIDLEZERO */
1618 				pg->flags |= PG_ZERO;
1619 
1620 				mutex_spin_enter(&uvm_fpageqlock);
1621 				TAILQ_INSERT_HEAD(&pgfl->pgfl_buckets[
1622 				    nextbucket].pgfl_queues[PGFL_ZEROS],
1623 				    pg, pageq);
1624 				uvmexp.free++;
1625 				uvmexp.zeropages++;
1626 			}
1627 		}
1628 		nextbucket = (nextbucket + 1) & uvmexp.colormask;
1629 	} while (nextbucket != firstbucket);
1630 quit:
1631 	mutex_spin_exit(&uvm_fpageqlock);
1632 }
1633 
1634 /*
1635  * uvm_pagelookup: look up a page
1636  *
1637  * => caller should lock object to keep someone from pulling the page
1638  *	out from under it
1639  */
1640 
1641 struct vm_page *
1642 uvm_pagelookup(struct uvm_object *obj, voff_t off)
1643 {
1644 	struct vm_page *pg;
1645 	struct pglist *buck;
1646 	kmutex_t *lock;
1647 	u_int hash;
1648 
1649 	KASSERT(mutex_owned(&obj->vmobjlock));
1650 
1651 	hash = uvm_pagehash(obj, off);
1652 	buck = &uvm.page_hash[hash];
1653 	lock = uvm_hashlock(hash);
1654 	mutex_spin_enter(lock);
1655 	TAILQ_FOREACH(pg, buck, hashq) {
1656 		if (pg->uobject == obj && pg->offset == off) {
1657 			break;
1658 		}
1659 	}
1660 	mutex_spin_exit(lock);
1661 	KASSERT(pg == NULL || obj->uo_npages != 0);
1662 	KASSERT(pg == NULL || (pg->flags & (PG_RELEASED|PG_PAGEOUT)) == 0 ||
1663 		(pg->flags & PG_BUSY) != 0);
1664 	return(pg);
1665 }
1666 
1667 /*
1668  * uvm_pagewire: wire the page, thus removing it from the daemon's grasp
1669  *
1670  * => caller must lock page queues
1671  */
1672 
1673 void
1674 uvm_pagewire(struct vm_page *pg)
1675 {
1676 	KASSERT(mutex_owned(&uvm_pageqlock));
1677 #if defined(READAHEAD_STATS)
1678 	if ((pg->pqflags & PQ_READAHEAD) != 0) {
1679 		uvm_ra_hit.ev_count++;
1680 		pg->pqflags &= ~PQ_READAHEAD;
1681 	}
1682 #endif /* defined(READAHEAD_STATS) */
1683 	if (pg->wire_count == 0) {
1684 		uvm_pagedequeue(pg);
1685 		uvmexp.wired++;
1686 	}
1687 	pg->wire_count++;
1688 }
1689 
1690 /*
1691  * uvm_pageunwire: unwire the page.
1692  *
1693  * => activate if wire count goes to zero.
1694  * => caller must lock page queues
1695  */
1696 
1697 void
1698 uvm_pageunwire(struct vm_page *pg)
1699 {
1700 	KASSERT(mutex_owned(&uvm_pageqlock));
1701 	pg->wire_count--;
1702 	if (pg->wire_count == 0) {
1703 		uvm_pageactivate(pg);
1704 		uvmexp.wired--;
1705 	}
1706 }
1707 
1708 /*
1709  * uvm_pagedeactivate: deactivate page
1710  *
1711  * => caller must lock page queues
1712  * => caller must check to make sure page is not wired
1713  * => object that page belongs to must be locked (so we can adjust pg->flags)
1714  * => caller must clear the reference on the page before calling
1715  */
1716 
1717 void
1718 uvm_pagedeactivate(struct vm_page *pg)
1719 {
1720 
1721 	KASSERT(mutex_owned(&uvm_pageqlock));
1722 	KASSERT(pg->wire_count != 0 || uvmpdpol_pageisqueued_p(pg));
1723 	uvmpdpol_pagedeactivate(pg);
1724 }
1725 
1726 /*
1727  * uvm_pageactivate: activate page
1728  *
1729  * => caller must lock page queues
1730  */
1731 
1732 void
1733 uvm_pageactivate(struct vm_page *pg)
1734 {
1735 
1736 	KASSERT(mutex_owned(&uvm_pageqlock));
1737 #if defined(READAHEAD_STATS)
1738 	if ((pg->pqflags & PQ_READAHEAD) != 0) {
1739 		uvm_ra_hit.ev_count++;
1740 		pg->pqflags &= ~PQ_READAHEAD;
1741 	}
1742 #endif /* defined(READAHEAD_STATS) */
1743 	if (pg->wire_count != 0) {
1744 		return;
1745 	}
1746 	uvmpdpol_pageactivate(pg);
1747 }
1748 
1749 /*
1750  * uvm_pagedequeue: remove a page from any paging queue
1751  */
1752 
1753 void
1754 uvm_pagedequeue(struct vm_page *pg)
1755 {
1756 
1757 	if (uvmpdpol_pageisqueued_p(pg)) {
1758 		KASSERT(mutex_owned(&uvm_pageqlock));
1759 	}
1760 
1761 	uvmpdpol_pagedequeue(pg);
1762 }
1763 
1764 /*
1765  * uvm_pageenqueue: add a page to a paging queue without activating.
1766  * used where a page is not really demanded (yet).  eg. read-ahead
1767  */
1768 
1769 void
1770 uvm_pageenqueue(struct vm_page *pg)
1771 {
1772 
1773 	KASSERT(mutex_owned(&uvm_pageqlock));
1774 	if (pg->wire_count != 0) {
1775 		return;
1776 	}
1777 	uvmpdpol_pageenqueue(pg);
1778 }
1779 
1780 /*
1781  * uvm_pagezero: zero fill a page
1782  *
1783  * => if page is part of an object then the object should be locked
1784  *	to protect pg->flags.
1785  */
1786 
1787 void
1788 uvm_pagezero(struct vm_page *pg)
1789 {
1790 	pg->flags &= ~PG_CLEAN;
1791 	pmap_zero_page(VM_PAGE_TO_PHYS(pg));
1792 }
1793 
1794 /*
1795  * uvm_pagecopy: copy a page
1796  *
1797  * => if page is part of an object then the object should be locked
1798  *	to protect pg->flags.
1799  */
1800 
1801 void
1802 uvm_pagecopy(struct vm_page *src, struct vm_page *dst)
1803 {
1804 
1805 	dst->flags &= ~PG_CLEAN;
1806 	pmap_copy_page(VM_PAGE_TO_PHYS(src), VM_PAGE_TO_PHYS(dst));
1807 }
1808 
1809 /*
1810  * uvm_page_lookup_freelist: look up the free list for the specified page
1811  */
1812 
1813 int
1814 uvm_page_lookup_freelist(struct vm_page *pg)
1815 {
1816 	int lcv;
1817 
1818 	lcv = vm_physseg_find(atop(VM_PAGE_TO_PHYS(pg)), NULL);
1819 	KASSERT(lcv != -1);
1820 	return (vm_physmem[lcv].free_list);
1821 }
1822