xref: /freebsd/sys/vm/vm_page.c (revision 21a4258d89a4e27632cfd87e5ad6e8538a6e77a2)
1 /*-
2  * Copyright (c) 1991 Regents of the University of California.
3  * All rights reserved.
4  * Copyright (c) 1998 Matthew Dillon.  All Rights Reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * The Mach Operating System project at Carnegie-Mellon University.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	from: @(#)vm_page.c	7.4 (Berkeley) 5/7/91
34  */
35 
36 /*-
37  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38  * All rights reserved.
39  *
40  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
41  *
42  * Permission to use, copy, modify and distribute this software and
43  * its documentation is hereby granted, provided that both the copyright
44  * notice and this permission notice appear in all copies of the
45  * software, derivative works or modified versions, and any portions
46  * thereof, and that both notices appear in supporting documentation.
47  *
48  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51  *
52  * Carnegie Mellon requests users of this software to return to
53  *
54  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
55  *  School of Computer Science
56  *  Carnegie Mellon University
57  *  Pittsburgh PA 15213-3890
58  *
59  * any improvements or extensions that they make and grant Carnegie the
60  * rights to redistribute these changes.
61  */
62 
63 /*
64  *			GENERAL RULES ON VM_PAGE MANIPULATION
65  *
66  *	- A page queue lock is required when adding or removing a page from a
67  *	  page queue regardless of other locks or the busy state of a page.
68  *
69  *		* In general, no thread besides the page daemon can acquire or
70  *		  hold more than one page queue lock at a time.
71  *
72  *		* The page daemon can acquire and hold any pair of page queue
73  *		  locks in any order.
74  *
75  *	- The object lock is required when inserting or removing
76  *	  pages from an object (vm_page_insert() or vm_page_remove()).
77  *
78  */
79 
80 /*
81  *	Resident memory management module.
82  */
83 
84 #include <sys/cdefs.h>
85 __FBSDID("$FreeBSD$");
86 
87 #include "opt_vm.h"
88 
89 #include <sys/param.h>
90 #include <sys/systm.h>
91 #include <sys/lock.h>
92 #include <sys/kernel.h>
93 #include <sys/limits.h>
94 #include <sys/linker.h>
95 #include <sys/malloc.h>
96 #include <sys/mman.h>
97 #include <sys/msgbuf.h>
98 #include <sys/mutex.h>
99 #include <sys/proc.h>
100 #include <sys/rwlock.h>
101 #include <sys/sbuf.h>
102 #include <sys/smp.h>
103 #include <sys/sysctl.h>
104 #include <sys/vmmeter.h>
105 #include <sys/vnode.h>
106 
107 #include <vm/vm.h>
108 #include <vm/pmap.h>
109 #include <vm/vm_param.h>
110 #include <vm/vm_kern.h>
111 #include <vm/vm_object.h>
112 #include <vm/vm_page.h>
113 #include <vm/vm_pageout.h>
114 #include <vm/vm_pager.h>
115 #include <vm/vm_phys.h>
116 #include <vm/vm_radix.h>
117 #include <vm/vm_reserv.h>
118 #include <vm/vm_extern.h>
119 #include <vm/uma.h>
120 #include <vm/uma_int.h>
121 
122 #include <machine/md_var.h>
123 
124 /*
125  *	Associated with page of user-allocatable memory is a
126  *	page structure.
127  */
128 
129 struct vm_domain vm_dom[MAXMEMDOM];
130 struct mtx_padalign vm_page_queue_free_mtx;
131 
132 struct mtx_padalign pa_lock[PA_LOCK_COUNT];
133 
134 vm_page_t vm_page_array;
135 long vm_page_array_size;
136 long first_page;
137 
138 static int boot_pages = UMA_BOOT_PAGES;
139 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
140     &boot_pages, 0,
141     "number of pages allocated for bootstrapping the VM system");
142 
143 static int pa_tryrelock_restart;
144 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
145     &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
146 
147 static TAILQ_HEAD(, vm_page) blacklist_head;
148 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
149 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
150     CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
151 
152 /* Is the page daemon waiting for free pages? */
153 static int vm_pageout_pages_needed;
154 
155 static uma_zone_t fakepg_zone;
156 
157 static struct vnode *vm_page_alloc_init(vm_page_t m);
158 static void vm_page_cache_turn_free(vm_page_t m);
159 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
160 static void vm_page_enqueue(uint8_t queue, vm_page_t m);
161 static void vm_page_free_wakeup(void);
162 static void vm_page_init_fakepg(void *dummy);
163 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
164     vm_pindex_t pindex, vm_page_t mpred);
165 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
166     vm_page_t mpred);
167 static int vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
168     vm_paddr_t high);
169 
170 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init_fakepg, NULL);
171 
172 static void
173 vm_page_init_fakepg(void *dummy)
174 {
175 
176 	fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
177 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
178 }
179 
180 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
181 #if PAGE_SIZE == 32768
182 #ifdef CTASSERT
183 CTASSERT(sizeof(u_long) >= 8);
184 #endif
185 #endif
186 
187 /*
188  * Try to acquire a physical address lock while a pmap is locked.  If we
189  * fail to trylock we unlock and lock the pmap directly and cache the
190  * locked pa in *locked.  The caller should then restart their loop in case
191  * the virtual to physical mapping has changed.
192  */
193 int
194 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
195 {
196 	vm_paddr_t lockpa;
197 
198 	lockpa = *locked;
199 	*locked = pa;
200 	if (lockpa) {
201 		PA_LOCK_ASSERT(lockpa, MA_OWNED);
202 		if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
203 			return (0);
204 		PA_UNLOCK(lockpa);
205 	}
206 	if (PA_TRYLOCK(pa))
207 		return (0);
208 	PMAP_UNLOCK(pmap);
209 	atomic_add_int(&pa_tryrelock_restart, 1);
210 	PA_LOCK(pa);
211 	PMAP_LOCK(pmap);
212 	return (EAGAIN);
213 }
214 
215 /*
216  *	vm_set_page_size:
217  *
218  *	Sets the page size, perhaps based upon the memory
219  *	size.  Must be called before any use of page-size
220  *	dependent functions.
221  */
222 void
223 vm_set_page_size(void)
224 {
225 	if (vm_cnt.v_page_size == 0)
226 		vm_cnt.v_page_size = PAGE_SIZE;
227 	if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
228 		panic("vm_set_page_size: page size not a power of two");
229 }
230 
231 /*
232  *	vm_page_blacklist_next:
233  *
234  *	Find the next entry in the provided string of blacklist
235  *	addresses.  Entries are separated by space, comma, or newline.
236  *	If an invalid integer is encountered then the rest of the
237  *	string is skipped.  Updates the list pointer to the next
238  *	character, or NULL if the string is exhausted or invalid.
239  */
240 static vm_paddr_t
241 vm_page_blacklist_next(char **list, char *end)
242 {
243 	vm_paddr_t bad;
244 	char *cp, *pos;
245 
246 	if (list == NULL || *list == NULL)
247 		return (0);
248 	if (**list =='\0') {
249 		*list = NULL;
250 		return (0);
251 	}
252 
253 	/*
254 	 * If there's no end pointer then the buffer is coming from
255 	 * the kenv and we know it's null-terminated.
256 	 */
257 	if (end == NULL)
258 		end = *list + strlen(*list);
259 
260 	/* Ensure that strtoq() won't walk off the end */
261 	if (*end != '\0') {
262 		if (*end == '\n' || *end == ' ' || *end  == ',')
263 			*end = '\0';
264 		else {
265 			printf("Blacklist not terminated, skipping\n");
266 			*list = NULL;
267 			return (0);
268 		}
269 	}
270 
271 	for (pos = *list; *pos != '\0'; pos = cp) {
272 		bad = strtoq(pos, &cp, 0);
273 		if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
274 			if (bad == 0) {
275 				if (++cp < end)
276 					continue;
277 				else
278 					break;
279 			}
280 		} else
281 			break;
282 		if (*cp == '\0' || ++cp >= end)
283 			*list = NULL;
284 		else
285 			*list = cp;
286 		return (trunc_page(bad));
287 	}
288 	printf("Garbage in RAM blacklist, skipping\n");
289 	*list = NULL;
290 	return (0);
291 }
292 
293 /*
294  *	vm_page_blacklist_check:
295  *
296  *	Iterate through the provided string of blacklist addresses, pulling
297  *	each entry out of the physical allocator free list and putting it
298  *	onto a list for reporting via the vm.page_blacklist sysctl.
299  */
300 static void
301 vm_page_blacklist_check(char *list, char *end)
302 {
303 	vm_paddr_t pa;
304 	vm_page_t m;
305 	char *next;
306 	int ret;
307 
308 	next = list;
309 	while (next != NULL) {
310 		if ((pa = vm_page_blacklist_next(&next, end)) == 0)
311 			continue;
312 		m = vm_phys_paddr_to_vm_page(pa);
313 		if (m == NULL)
314 			continue;
315 		mtx_lock(&vm_page_queue_free_mtx);
316 		ret = vm_phys_unfree_page(m);
317 		mtx_unlock(&vm_page_queue_free_mtx);
318 		if (ret == TRUE) {
319 			TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
320 			if (bootverbose)
321 				printf("Skipping page with pa 0x%jx\n",
322 				    (uintmax_t)pa);
323 		}
324 	}
325 }
326 
327 /*
328  *	vm_page_blacklist_load:
329  *
330  *	Search for a special module named "ram_blacklist".  It'll be a
331  *	plain text file provided by the user via the loader directive
332  *	of the same name.
333  */
334 static void
335 vm_page_blacklist_load(char **list, char **end)
336 {
337 	void *mod;
338 	u_char *ptr;
339 	u_int len;
340 
341 	mod = NULL;
342 	ptr = NULL;
343 
344 	mod = preload_search_by_type("ram_blacklist");
345 	if (mod != NULL) {
346 		ptr = preload_fetch_addr(mod);
347 		len = preload_fetch_size(mod);
348         }
349 	*list = ptr;
350 	if (ptr != NULL)
351 		*end = ptr + len;
352 	else
353 		*end = NULL;
354 	return;
355 }
356 
357 static int
358 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
359 {
360 	vm_page_t m;
361 	struct sbuf sbuf;
362 	int error, first;
363 
364 	first = 1;
365 	error = sysctl_wire_old_buffer(req, 0);
366 	if (error != 0)
367 		return (error);
368 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
369 	TAILQ_FOREACH(m, &blacklist_head, listq) {
370 		sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
371 		    (uintmax_t)m->phys_addr);
372 		first = 0;
373 	}
374 	error = sbuf_finish(&sbuf);
375 	sbuf_delete(&sbuf);
376 	return (error);
377 }
378 
379 static void
380 vm_page_domain_init(struct vm_domain *vmd)
381 {
382 	struct vm_pagequeue *pq;
383 	int i;
384 
385 	*__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
386 	    "vm inactive pagequeue";
387 	*__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_vcnt) =
388 	    &vm_cnt.v_inactive_count;
389 	*__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
390 	    "vm active pagequeue";
391 	*__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_vcnt) =
392 	    &vm_cnt.v_active_count;
393 	vmd->vmd_page_count = 0;
394 	vmd->vmd_free_count = 0;
395 	vmd->vmd_segs = 0;
396 	vmd->vmd_oom = FALSE;
397 	for (i = 0; i < PQ_COUNT; i++) {
398 		pq = &vmd->vmd_pagequeues[i];
399 		TAILQ_INIT(&pq->pq_pl);
400 		mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
401 		    MTX_DEF | MTX_DUPOK);
402 	}
403 }
404 
405 /*
406  *	vm_page_startup:
407  *
408  *	Initializes the resident memory module.
409  *
410  *	Allocates memory for the page cells, and
411  *	for the object/offset-to-page hash table headers.
412  *	Each page cell is initialized and placed on the free list.
413  */
414 vm_offset_t
415 vm_page_startup(vm_offset_t vaddr)
416 {
417 	vm_offset_t mapped;
418 	vm_paddr_t page_range;
419 	vm_paddr_t new_end;
420 	int i;
421 	vm_paddr_t pa;
422 	vm_paddr_t last_pa;
423 	char *list, *listend;
424 	vm_paddr_t end;
425 	vm_paddr_t biggestsize;
426 	vm_paddr_t low_water, high_water;
427 	int biggestone;
428 	int pages_per_zone;
429 
430 	biggestsize = 0;
431 	biggestone = 0;
432 	vaddr = round_page(vaddr);
433 
434 	for (i = 0; phys_avail[i + 1]; i += 2) {
435 		phys_avail[i] = round_page(phys_avail[i]);
436 		phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
437 	}
438 
439 	low_water = phys_avail[0];
440 	high_water = phys_avail[1];
441 
442 	for (i = 0; i < vm_phys_nsegs; i++) {
443 		if (vm_phys_segs[i].start < low_water)
444 			low_water = vm_phys_segs[i].start;
445 		if (vm_phys_segs[i].end > high_water)
446 			high_water = vm_phys_segs[i].end;
447 	}
448 	for (i = 0; phys_avail[i + 1]; i += 2) {
449 		vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
450 
451 		if (size > biggestsize) {
452 			biggestone = i;
453 			biggestsize = size;
454 		}
455 		if (phys_avail[i] < low_water)
456 			low_water = phys_avail[i];
457 		if (phys_avail[i + 1] > high_water)
458 			high_water = phys_avail[i + 1];
459 	}
460 
461 	end = phys_avail[biggestone+1];
462 
463 	/*
464 	 * Initialize the page and queue locks.
465 	 */
466 	mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
467 	for (i = 0; i < PA_LOCK_COUNT; i++)
468 		mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
469 	for (i = 0; i < vm_ndomains; i++)
470 		vm_page_domain_init(&vm_dom[i]);
471 
472 	/*
473 	 * Almost all of the pages needed for boot strapping UMA are used
474 	 * for zone structures, so if the number of CPUs results in those
475 	 * structures taking more than one page each, we set aside more pages
476 	 * in proportion to the zone structure size.
477 	 */
478 	pages_per_zone = howmany(sizeof(struct uma_zone) +
479 	    sizeof(struct uma_cache) * (mp_maxid + 1), UMA_SLAB_SIZE);
480 	if (pages_per_zone > 1) {
481 		/* Reserve more pages so that we don't run out. */
482 		boot_pages = UMA_BOOT_PAGES_ZONES * pages_per_zone;
483 	}
484 
485 	/*
486 	 * Allocate memory for use when boot strapping the kernel memory
487 	 * allocator.
488 	 *
489 	 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
490 	 * manually fetch the value.
491 	 */
492 	TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
493 	new_end = end - (boot_pages * UMA_SLAB_SIZE);
494 	new_end = trunc_page(new_end);
495 	mapped = pmap_map(&vaddr, new_end, end,
496 	    VM_PROT_READ | VM_PROT_WRITE);
497 	bzero((void *)mapped, end - new_end);
498 	uma_startup((void *)mapped, boot_pages);
499 
500 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
501     defined(__i386__) || defined(__mips__)
502 	/*
503 	 * Allocate a bitmap to indicate that a random physical page
504 	 * needs to be included in a minidump.
505 	 *
506 	 * The amd64 port needs this to indicate which direct map pages
507 	 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
508 	 *
509 	 * However, i386 still needs this workspace internally within the
510 	 * minidump code.  In theory, they are not needed on i386, but are
511 	 * included should the sf_buf code decide to use them.
512 	 */
513 	last_pa = 0;
514 	for (i = 0; dump_avail[i + 1] != 0; i += 2)
515 		if (dump_avail[i + 1] > last_pa)
516 			last_pa = dump_avail[i + 1];
517 	page_range = last_pa / PAGE_SIZE;
518 	vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
519 	new_end -= vm_page_dump_size;
520 	vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
521 	    new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
522 	bzero((void *)vm_page_dump, vm_page_dump_size);
523 #endif
524 #ifdef __amd64__
525 	/*
526 	 * Request that the physical pages underlying the message buffer be
527 	 * included in a crash dump.  Since the message buffer is accessed
528 	 * through the direct map, they are not automatically included.
529 	 */
530 	pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
531 	last_pa = pa + round_page(msgbufsize);
532 	while (pa < last_pa) {
533 		dump_add_page(pa);
534 		pa += PAGE_SIZE;
535 	}
536 #endif
537 	/*
538 	 * Compute the number of pages of memory that will be available for
539 	 * use (taking into account the overhead of a page structure per
540 	 * page).
541 	 */
542 	first_page = low_water / PAGE_SIZE;
543 #ifdef VM_PHYSSEG_SPARSE
544 	page_range = 0;
545 	for (i = 0; i < vm_phys_nsegs; i++) {
546 		page_range += atop(vm_phys_segs[i].end -
547 		    vm_phys_segs[i].start);
548 	}
549 	for (i = 0; phys_avail[i + 1] != 0; i += 2)
550 		page_range += atop(phys_avail[i + 1] - phys_avail[i]);
551 #elif defined(VM_PHYSSEG_DENSE)
552 	page_range = high_water / PAGE_SIZE - first_page;
553 #else
554 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
555 #endif
556 	end = new_end;
557 
558 	/*
559 	 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
560 	 */
561 	vaddr += PAGE_SIZE;
562 
563 	/*
564 	 * Initialize the mem entry structures now, and put them in the free
565 	 * queue.
566 	 */
567 	new_end = trunc_page(end - page_range * sizeof(struct vm_page));
568 	mapped = pmap_map(&vaddr, new_end, end,
569 	    VM_PROT_READ | VM_PROT_WRITE);
570 	vm_page_array = (vm_page_t) mapped;
571 #if VM_NRESERVLEVEL > 0
572 	/*
573 	 * Allocate memory for the reservation management system's data
574 	 * structures.
575 	 */
576 	new_end = vm_reserv_startup(&vaddr, new_end, high_water);
577 #endif
578 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
579 	/*
580 	 * pmap_map on arm64, amd64, and mips can come out of the direct-map,
581 	 * not kvm like i386, so the pages must be tracked for a crashdump to
582 	 * include this data.  This includes the vm_page_array and the early
583 	 * UMA bootstrap pages.
584 	 */
585 	for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
586 		dump_add_page(pa);
587 #endif
588 	phys_avail[biggestone + 1] = new_end;
589 
590 	/*
591 	 * Add physical memory segments corresponding to the available
592 	 * physical pages.
593 	 */
594 	for (i = 0; phys_avail[i + 1] != 0; i += 2)
595 		vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
596 
597 	/*
598 	 * Clear all of the page structures
599 	 */
600 	bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
601 	for (i = 0; i < page_range; i++)
602 		vm_page_array[i].order = VM_NFREEORDER;
603 	vm_page_array_size = page_range;
604 
605 	/*
606 	 * Initialize the physical memory allocator.
607 	 */
608 	vm_phys_init();
609 
610 	/*
611 	 * Add every available physical page that is not blacklisted to
612 	 * the free lists.
613 	 */
614 	vm_cnt.v_page_count = 0;
615 	vm_cnt.v_free_count = 0;
616 	for (i = 0; phys_avail[i + 1] != 0; i += 2) {
617 		pa = phys_avail[i];
618 		last_pa = phys_avail[i + 1];
619 		while (pa < last_pa) {
620 			vm_phys_add_page(pa);
621 			pa += PAGE_SIZE;
622 		}
623 	}
624 
625 	TAILQ_INIT(&blacklist_head);
626 	vm_page_blacklist_load(&list, &listend);
627 	vm_page_blacklist_check(list, listend);
628 
629 	list = kern_getenv("vm.blacklist");
630 	vm_page_blacklist_check(list, NULL);
631 
632 	freeenv(list);
633 #if VM_NRESERVLEVEL > 0
634 	/*
635 	 * Initialize the reservation management system.
636 	 */
637 	vm_reserv_init();
638 #endif
639 	return (vaddr);
640 }
641 
642 void
643 vm_page_reference(vm_page_t m)
644 {
645 
646 	vm_page_aflag_set(m, PGA_REFERENCED);
647 }
648 
649 /*
650  *	vm_page_busy_downgrade:
651  *
652  *	Downgrade an exclusive busy page into a single shared busy page.
653  */
654 void
655 vm_page_busy_downgrade(vm_page_t m)
656 {
657 	u_int x;
658 
659 	vm_page_assert_xbusied(m);
660 
661 	for (;;) {
662 		x = m->busy_lock;
663 		x &= VPB_BIT_WAITERS;
664 		if (atomic_cmpset_rel_int(&m->busy_lock,
665 		    VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1) | x))
666 			break;
667 	}
668 }
669 
670 /*
671  *	vm_page_sbusied:
672  *
673  *	Return a positive value if the page is shared busied, 0 otherwise.
674  */
675 int
676 vm_page_sbusied(vm_page_t m)
677 {
678 	u_int x;
679 
680 	x = m->busy_lock;
681 	return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
682 }
683 
684 /*
685  *	vm_page_sunbusy:
686  *
687  *	Shared unbusy a page.
688  */
689 void
690 vm_page_sunbusy(vm_page_t m)
691 {
692 	u_int x;
693 
694 	vm_page_assert_sbusied(m);
695 
696 	for (;;) {
697 		x = m->busy_lock;
698 		if (VPB_SHARERS(x) > 1) {
699 			if (atomic_cmpset_int(&m->busy_lock, x,
700 			    x - VPB_ONE_SHARER))
701 				break;
702 			continue;
703 		}
704 		if ((x & VPB_BIT_WAITERS) == 0) {
705 			KASSERT(x == VPB_SHARERS_WORD(1),
706 			    ("vm_page_sunbusy: invalid lock state"));
707 			if (atomic_cmpset_int(&m->busy_lock,
708 			    VPB_SHARERS_WORD(1), VPB_UNBUSIED))
709 				break;
710 			continue;
711 		}
712 		KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
713 		    ("vm_page_sunbusy: invalid lock state for waiters"));
714 
715 		vm_page_lock(m);
716 		if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
717 			vm_page_unlock(m);
718 			continue;
719 		}
720 		wakeup(m);
721 		vm_page_unlock(m);
722 		break;
723 	}
724 }
725 
726 /*
727  *	vm_page_busy_sleep:
728  *
729  *	Sleep and release the page lock, using the page pointer as wchan.
730  *	This is used to implement the hard-path of busying mechanism.
731  *
732  *	The given page must be locked.
733  */
734 void
735 vm_page_busy_sleep(vm_page_t m, const char *wmesg)
736 {
737 	u_int x;
738 
739 	vm_page_lock_assert(m, MA_OWNED);
740 
741 	x = m->busy_lock;
742 	if (x == VPB_UNBUSIED) {
743 		vm_page_unlock(m);
744 		return;
745 	}
746 	if ((x & VPB_BIT_WAITERS) == 0 &&
747 	    !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS)) {
748 		vm_page_unlock(m);
749 		return;
750 	}
751 	msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
752 }
753 
754 /*
755  *	vm_page_trysbusy:
756  *
757  *	Try to shared busy a page.
758  *	If the operation succeeds 1 is returned otherwise 0.
759  *	The operation never sleeps.
760  */
761 int
762 vm_page_trysbusy(vm_page_t m)
763 {
764 	u_int x;
765 
766 	for (;;) {
767 		x = m->busy_lock;
768 		if ((x & VPB_BIT_SHARED) == 0)
769 			return (0);
770 		if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
771 			return (1);
772 	}
773 }
774 
775 static void
776 vm_page_xunbusy_locked(vm_page_t m)
777 {
778 
779 	vm_page_assert_xbusied(m);
780 	vm_page_assert_locked(m);
781 
782 	atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
783 	/* There is a waiter, do wakeup() instead of vm_page_flash(). */
784 	wakeup(m);
785 }
786 
787 static void
788 vm_page_xunbusy_maybelocked(vm_page_t m)
789 {
790 	bool lockacq;
791 
792 	vm_page_assert_xbusied(m);
793 
794 	/*
795 	 * Fast path for unbusy.  If it succeeds, we know that there
796 	 * are no waiters, so we do not need a wakeup.
797 	 */
798 	if (atomic_cmpset_rel_int(&m->busy_lock, VPB_SINGLE_EXCLUSIVER,
799 	    VPB_UNBUSIED))
800 		return;
801 
802 	lockacq = !mtx_owned(vm_page_lockptr(m));
803 	if (lockacq)
804 		vm_page_lock(m);
805 	vm_page_xunbusy_locked(m);
806 	if (lockacq)
807 		vm_page_unlock(m);
808 }
809 
810 /*
811  *	vm_page_xunbusy_hard:
812  *
813  *	Called after the first try the exclusive unbusy of a page failed.
814  *	It is assumed that the waiters bit is on.
815  */
816 void
817 vm_page_xunbusy_hard(vm_page_t m)
818 {
819 
820 	vm_page_assert_xbusied(m);
821 
822 	vm_page_lock(m);
823 	vm_page_xunbusy_locked(m);
824 	vm_page_unlock(m);
825 }
826 
827 /*
828  *	vm_page_flash:
829  *
830  *	Wakeup anyone waiting for the page.
831  *	The ownership bits do not change.
832  *
833  *	The given page must be locked.
834  */
835 void
836 vm_page_flash(vm_page_t m)
837 {
838 	u_int x;
839 
840 	vm_page_lock_assert(m, MA_OWNED);
841 
842 	for (;;) {
843 		x = m->busy_lock;
844 		if ((x & VPB_BIT_WAITERS) == 0)
845 			return;
846 		if (atomic_cmpset_int(&m->busy_lock, x,
847 		    x & (~VPB_BIT_WAITERS)))
848 			break;
849 	}
850 	wakeup(m);
851 }
852 
853 /*
854  * Keep page from being freed by the page daemon
855  * much of the same effect as wiring, except much lower
856  * overhead and should be used only for *very* temporary
857  * holding ("wiring").
858  */
859 void
860 vm_page_hold(vm_page_t mem)
861 {
862 
863 	vm_page_lock_assert(mem, MA_OWNED);
864         mem->hold_count++;
865 }
866 
867 void
868 vm_page_unhold(vm_page_t mem)
869 {
870 
871 	vm_page_lock_assert(mem, MA_OWNED);
872 	KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
873 	--mem->hold_count;
874 	if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
875 		vm_page_free_toq(mem);
876 }
877 
878 /*
879  *	vm_page_unhold_pages:
880  *
881  *	Unhold each of the pages that is referenced by the given array.
882  */
883 void
884 vm_page_unhold_pages(vm_page_t *ma, int count)
885 {
886 	struct mtx *mtx, *new_mtx;
887 
888 	mtx = NULL;
889 	for (; count != 0; count--) {
890 		/*
891 		 * Avoid releasing and reacquiring the same page lock.
892 		 */
893 		new_mtx = vm_page_lockptr(*ma);
894 		if (mtx != new_mtx) {
895 			if (mtx != NULL)
896 				mtx_unlock(mtx);
897 			mtx = new_mtx;
898 			mtx_lock(mtx);
899 		}
900 		vm_page_unhold(*ma);
901 		ma++;
902 	}
903 	if (mtx != NULL)
904 		mtx_unlock(mtx);
905 }
906 
907 vm_page_t
908 PHYS_TO_VM_PAGE(vm_paddr_t pa)
909 {
910 	vm_page_t m;
911 
912 #ifdef VM_PHYSSEG_SPARSE
913 	m = vm_phys_paddr_to_vm_page(pa);
914 	if (m == NULL)
915 		m = vm_phys_fictitious_to_vm_page(pa);
916 	return (m);
917 #elif defined(VM_PHYSSEG_DENSE)
918 	long pi;
919 
920 	pi = atop(pa);
921 	if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
922 		m = &vm_page_array[pi - first_page];
923 		return (m);
924 	}
925 	return (vm_phys_fictitious_to_vm_page(pa));
926 #else
927 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
928 #endif
929 }
930 
931 /*
932  *	vm_page_getfake:
933  *
934  *	Create a fictitious page with the specified physical address and
935  *	memory attribute.  The memory attribute is the only the machine-
936  *	dependent aspect of a fictitious page that must be initialized.
937  */
938 vm_page_t
939 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
940 {
941 	vm_page_t m;
942 
943 	m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
944 	vm_page_initfake(m, paddr, memattr);
945 	return (m);
946 }
947 
948 void
949 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
950 {
951 
952 	if ((m->flags & PG_FICTITIOUS) != 0) {
953 		/*
954 		 * The page's memattr might have changed since the
955 		 * previous initialization.  Update the pmap to the
956 		 * new memattr.
957 		 */
958 		goto memattr;
959 	}
960 	m->phys_addr = paddr;
961 	m->queue = PQ_NONE;
962 	/* Fictitious pages don't use "segind". */
963 	m->flags = PG_FICTITIOUS;
964 	/* Fictitious pages don't use "order" or "pool". */
965 	m->oflags = VPO_UNMANAGED;
966 	m->busy_lock = VPB_SINGLE_EXCLUSIVER;
967 	m->wire_count = 1;
968 	pmap_page_init(m);
969 memattr:
970 	pmap_page_set_memattr(m, memattr);
971 }
972 
973 /*
974  *	vm_page_putfake:
975  *
976  *	Release a fictitious page.
977  */
978 void
979 vm_page_putfake(vm_page_t m)
980 {
981 
982 	KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
983 	KASSERT((m->flags & PG_FICTITIOUS) != 0,
984 	    ("vm_page_putfake: bad page %p", m));
985 	uma_zfree(fakepg_zone, m);
986 }
987 
988 /*
989  *	vm_page_updatefake:
990  *
991  *	Update the given fictitious page to the specified physical address and
992  *	memory attribute.
993  */
994 void
995 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
996 {
997 
998 	KASSERT((m->flags & PG_FICTITIOUS) != 0,
999 	    ("vm_page_updatefake: bad page %p", m));
1000 	m->phys_addr = paddr;
1001 	pmap_page_set_memattr(m, memattr);
1002 }
1003 
1004 /*
1005  *	vm_page_free:
1006  *
1007  *	Free a page.
1008  */
1009 void
1010 vm_page_free(vm_page_t m)
1011 {
1012 
1013 	m->flags &= ~PG_ZERO;
1014 	vm_page_free_toq(m);
1015 }
1016 
1017 /*
1018  *	vm_page_free_zero:
1019  *
1020  *	Free a page to the zerod-pages queue
1021  */
1022 void
1023 vm_page_free_zero(vm_page_t m)
1024 {
1025 
1026 	m->flags |= PG_ZERO;
1027 	vm_page_free_toq(m);
1028 }
1029 
1030 /*
1031  * Unbusy and handle the page queueing for a page from a getpages request that
1032  * was optionally read ahead or behind.
1033  */
1034 void
1035 vm_page_readahead_finish(vm_page_t m)
1036 {
1037 
1038 	/* We shouldn't put invalid pages on queues. */
1039 	KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
1040 
1041 	/*
1042 	 * Since the page is not the actually needed one, whether it should
1043 	 * be activated or deactivated is not obvious.  Empirical results
1044 	 * have shown that deactivating the page is usually the best choice,
1045 	 * unless the page is wanted by another thread.
1046 	 */
1047 	vm_page_lock(m);
1048 	if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1049 		vm_page_activate(m);
1050 	else
1051 		vm_page_deactivate(m);
1052 	vm_page_unlock(m);
1053 	vm_page_xunbusy(m);
1054 }
1055 
1056 /*
1057  *	vm_page_sleep_if_busy:
1058  *
1059  *	Sleep and release the page queues lock if the page is busied.
1060  *	Returns TRUE if the thread slept.
1061  *
1062  *	The given page must be unlocked and object containing it must
1063  *	be locked.
1064  */
1065 int
1066 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1067 {
1068 	vm_object_t obj;
1069 
1070 	vm_page_lock_assert(m, MA_NOTOWNED);
1071 	VM_OBJECT_ASSERT_WLOCKED(m->object);
1072 
1073 	if (vm_page_busied(m)) {
1074 		/*
1075 		 * The page-specific object must be cached because page
1076 		 * identity can change during the sleep, causing the
1077 		 * re-lock of a different object.
1078 		 * It is assumed that a reference to the object is already
1079 		 * held by the callers.
1080 		 */
1081 		obj = m->object;
1082 		vm_page_lock(m);
1083 		VM_OBJECT_WUNLOCK(obj);
1084 		vm_page_busy_sleep(m, msg);
1085 		VM_OBJECT_WLOCK(obj);
1086 		return (TRUE);
1087 	}
1088 	return (FALSE);
1089 }
1090 
1091 /*
1092  *	vm_page_dirty_KBI:		[ internal use only ]
1093  *
1094  *	Set all bits in the page's dirty field.
1095  *
1096  *	The object containing the specified page must be locked if the
1097  *	call is made from the machine-independent layer.
1098  *
1099  *	See vm_page_clear_dirty_mask().
1100  *
1101  *	This function should only be called by vm_page_dirty().
1102  */
1103 void
1104 vm_page_dirty_KBI(vm_page_t m)
1105 {
1106 
1107 	/* These assertions refer to this operation by its public name. */
1108 	KASSERT((m->flags & PG_CACHED) == 0,
1109 	    ("vm_page_dirty: page in cache!"));
1110 	KASSERT(m->valid == VM_PAGE_BITS_ALL,
1111 	    ("vm_page_dirty: page is invalid!"));
1112 	m->dirty = VM_PAGE_BITS_ALL;
1113 }
1114 
1115 /*
1116  *	vm_page_insert:		[ internal use only ]
1117  *
1118  *	Inserts the given mem entry into the object and object list.
1119  *
1120  *	The object must be locked.
1121  */
1122 int
1123 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1124 {
1125 	vm_page_t mpred;
1126 
1127 	VM_OBJECT_ASSERT_WLOCKED(object);
1128 	mpred = vm_radix_lookup_le(&object->rtree, pindex);
1129 	return (vm_page_insert_after(m, object, pindex, mpred));
1130 }
1131 
1132 /*
1133  *	vm_page_insert_after:
1134  *
1135  *	Inserts the page "m" into the specified object at offset "pindex".
1136  *
1137  *	The page "mpred" must immediately precede the offset "pindex" within
1138  *	the specified object.
1139  *
1140  *	The object must be locked.
1141  */
1142 static int
1143 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1144     vm_page_t mpred)
1145 {
1146 	vm_page_t msucc;
1147 
1148 	VM_OBJECT_ASSERT_WLOCKED(object);
1149 	KASSERT(m->object == NULL,
1150 	    ("vm_page_insert_after: page already inserted"));
1151 	if (mpred != NULL) {
1152 		KASSERT(mpred->object == object,
1153 		    ("vm_page_insert_after: object doesn't contain mpred"));
1154 		KASSERT(mpred->pindex < pindex,
1155 		    ("vm_page_insert_after: mpred doesn't precede pindex"));
1156 		msucc = TAILQ_NEXT(mpred, listq);
1157 	} else
1158 		msucc = TAILQ_FIRST(&object->memq);
1159 	if (msucc != NULL)
1160 		KASSERT(msucc->pindex > pindex,
1161 		    ("vm_page_insert_after: msucc doesn't succeed pindex"));
1162 
1163 	/*
1164 	 * Record the object/offset pair in this page
1165 	 */
1166 	m->object = object;
1167 	m->pindex = pindex;
1168 
1169 	/*
1170 	 * Now link into the object's ordered list of backed pages.
1171 	 */
1172 	if (vm_radix_insert(&object->rtree, m)) {
1173 		m->object = NULL;
1174 		m->pindex = 0;
1175 		return (1);
1176 	}
1177 	vm_page_insert_radixdone(m, object, mpred);
1178 	return (0);
1179 }
1180 
1181 /*
1182  *	vm_page_insert_radixdone:
1183  *
1184  *	Complete page "m" insertion into the specified object after the
1185  *	radix trie hooking.
1186  *
1187  *	The page "mpred" must precede the offset "m->pindex" within the
1188  *	specified object.
1189  *
1190  *	The object must be locked.
1191  */
1192 static void
1193 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1194 {
1195 
1196 	VM_OBJECT_ASSERT_WLOCKED(object);
1197 	KASSERT(object != NULL && m->object == object,
1198 	    ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1199 	if (mpred != NULL) {
1200 		KASSERT(mpred->object == object,
1201 		    ("vm_page_insert_after: object doesn't contain mpred"));
1202 		KASSERT(mpred->pindex < m->pindex,
1203 		    ("vm_page_insert_after: mpred doesn't precede pindex"));
1204 	}
1205 
1206 	if (mpred != NULL)
1207 		TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1208 	else
1209 		TAILQ_INSERT_HEAD(&object->memq, m, listq);
1210 
1211 	/*
1212 	 * Show that the object has one more resident page.
1213 	 */
1214 	object->resident_page_count++;
1215 
1216 	/*
1217 	 * Hold the vnode until the last page is released.
1218 	 */
1219 	if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1220 		vhold(object->handle);
1221 
1222 	/*
1223 	 * Since we are inserting a new and possibly dirty page,
1224 	 * update the object's OBJ_MIGHTBEDIRTY flag.
1225 	 */
1226 	if (pmap_page_is_write_mapped(m))
1227 		vm_object_set_writeable_dirty(object);
1228 }
1229 
1230 /*
1231  *	vm_page_remove:
1232  *
1233  *	Removes the given mem entry from the object/offset-page
1234  *	table and the object page list, but do not invalidate/terminate
1235  *	the backing store.
1236  *
1237  *	The object must be locked.  The page must be locked if it is managed.
1238  */
1239 void
1240 vm_page_remove(vm_page_t m)
1241 {
1242 	vm_object_t object;
1243 
1244 	if ((m->oflags & VPO_UNMANAGED) == 0)
1245 		vm_page_assert_locked(m);
1246 	if ((object = m->object) == NULL)
1247 		return;
1248 	VM_OBJECT_ASSERT_WLOCKED(object);
1249 	if (vm_page_xbusied(m))
1250 		vm_page_xunbusy_maybelocked(m);
1251 
1252 	/*
1253 	 * Now remove from the object's list of backed pages.
1254 	 */
1255 	vm_radix_remove(&object->rtree, m->pindex);
1256 	TAILQ_REMOVE(&object->memq, m, listq);
1257 
1258 	/*
1259 	 * And show that the object has one fewer resident page.
1260 	 */
1261 	object->resident_page_count--;
1262 
1263 	/*
1264 	 * The vnode may now be recycled.
1265 	 */
1266 	if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1267 		vdrop(object->handle);
1268 
1269 	m->object = NULL;
1270 }
1271 
1272 /*
1273  *	vm_page_lookup:
1274  *
1275  *	Returns the page associated with the object/offset
1276  *	pair specified; if none is found, NULL is returned.
1277  *
1278  *	The object must be locked.
1279  */
1280 vm_page_t
1281 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1282 {
1283 
1284 	VM_OBJECT_ASSERT_LOCKED(object);
1285 	return (vm_radix_lookup(&object->rtree, pindex));
1286 }
1287 
1288 /*
1289  *	vm_page_find_least:
1290  *
1291  *	Returns the page associated with the object with least pindex
1292  *	greater than or equal to the parameter pindex, or NULL.
1293  *
1294  *	The object must be locked.
1295  */
1296 vm_page_t
1297 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1298 {
1299 	vm_page_t m;
1300 
1301 	VM_OBJECT_ASSERT_LOCKED(object);
1302 	if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1303 		m = vm_radix_lookup_ge(&object->rtree, pindex);
1304 	return (m);
1305 }
1306 
1307 /*
1308  * Returns the given page's successor (by pindex) within the object if it is
1309  * resident; if none is found, NULL is returned.
1310  *
1311  * The object must be locked.
1312  */
1313 vm_page_t
1314 vm_page_next(vm_page_t m)
1315 {
1316 	vm_page_t next;
1317 
1318 	VM_OBJECT_ASSERT_LOCKED(m->object);
1319 	if ((next = TAILQ_NEXT(m, listq)) != NULL &&
1320 	    next->pindex != m->pindex + 1)
1321 		next = NULL;
1322 	return (next);
1323 }
1324 
1325 /*
1326  * Returns the given page's predecessor (by pindex) within the object if it is
1327  * resident; if none is found, NULL is returned.
1328  *
1329  * The object must be locked.
1330  */
1331 vm_page_t
1332 vm_page_prev(vm_page_t m)
1333 {
1334 	vm_page_t prev;
1335 
1336 	VM_OBJECT_ASSERT_LOCKED(m->object);
1337 	if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
1338 	    prev->pindex != m->pindex - 1)
1339 		prev = NULL;
1340 	return (prev);
1341 }
1342 
1343 /*
1344  * Uses the page mnew as a replacement for an existing page at index
1345  * pindex which must be already present in the object.
1346  *
1347  * The existing page must not be on a paging queue.
1348  */
1349 vm_page_t
1350 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1351 {
1352 	vm_page_t mold;
1353 
1354 	VM_OBJECT_ASSERT_WLOCKED(object);
1355 	KASSERT(mnew->object == NULL,
1356 	    ("vm_page_replace: page already in object"));
1357 
1358 	/*
1359 	 * This function mostly follows vm_page_insert() and
1360 	 * vm_page_remove() without the radix, object count and vnode
1361 	 * dance.  Double check such functions for more comments.
1362 	 */
1363 
1364 	mnew->object = object;
1365 	mnew->pindex = pindex;
1366 	mold = vm_radix_replace(&object->rtree, mnew);
1367 	KASSERT(mold->queue == PQ_NONE,
1368 	    ("vm_page_replace: mold is on a paging queue"));
1369 
1370 	/* Keep the resident page list in sorted order. */
1371 	TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1372 	TAILQ_REMOVE(&object->memq, mold, listq);
1373 
1374 	mold->object = NULL;
1375 	vm_page_xunbusy_maybelocked(mold);
1376 
1377 	/*
1378 	 * The object's resident_page_count does not change because we have
1379 	 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1380 	 */
1381 	if (pmap_page_is_write_mapped(mnew))
1382 		vm_object_set_writeable_dirty(object);
1383 	return (mold);
1384 }
1385 
1386 /*
1387  *	vm_page_rename:
1388  *
1389  *	Move the given memory entry from its
1390  *	current object to the specified target object/offset.
1391  *
1392  *	Note: swap associated with the page must be invalidated by the move.  We
1393  *	      have to do this for several reasons:  (1) we aren't freeing the
1394  *	      page, (2) we are dirtying the page, (3) the VM system is probably
1395  *	      moving the page from object A to B, and will then later move
1396  *	      the backing store from A to B and we can't have a conflict.
1397  *
1398  *	Note: we *always* dirty the page.  It is necessary both for the
1399  *	      fact that we moved it, and because we may be invalidating
1400  *	      swap.  If the page is on the cache, we have to deactivate it
1401  *	      or vm_page_dirty() will panic.  Dirty pages are not allowed
1402  *	      on the cache.
1403  *
1404  *	The objects must be locked.
1405  */
1406 int
1407 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1408 {
1409 	vm_page_t mpred;
1410 	vm_pindex_t opidx;
1411 
1412 	VM_OBJECT_ASSERT_WLOCKED(new_object);
1413 
1414 	mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1415 	KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1416 	    ("vm_page_rename: pindex already renamed"));
1417 
1418 	/*
1419 	 * Create a custom version of vm_page_insert() which does not depend
1420 	 * by m_prev and can cheat on the implementation aspects of the
1421 	 * function.
1422 	 */
1423 	opidx = m->pindex;
1424 	m->pindex = new_pindex;
1425 	if (vm_radix_insert(&new_object->rtree, m)) {
1426 		m->pindex = opidx;
1427 		return (1);
1428 	}
1429 
1430 	/*
1431 	 * The operation cannot fail anymore.  The removal must happen before
1432 	 * the listq iterator is tainted.
1433 	 */
1434 	m->pindex = opidx;
1435 	vm_page_lock(m);
1436 	vm_page_remove(m);
1437 
1438 	/* Return back to the new pindex to complete vm_page_insert(). */
1439 	m->pindex = new_pindex;
1440 	m->object = new_object;
1441 	vm_page_unlock(m);
1442 	vm_page_insert_radixdone(m, new_object, mpred);
1443 	vm_page_dirty(m);
1444 	return (0);
1445 }
1446 
1447 /*
1448  *	Convert all of the given object's cached pages that have a
1449  *	pindex within the given range into free pages.  If the value
1450  *	zero is given for "end", then the range's upper bound is
1451  *	infinity.  If the given object is backed by a vnode and it
1452  *	transitions from having one or more cached pages to none, the
1453  *	vnode's hold count is reduced.
1454  */
1455 void
1456 vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1457 {
1458 	vm_page_t m;
1459 	boolean_t empty;
1460 
1461 	mtx_lock(&vm_page_queue_free_mtx);
1462 	if (__predict_false(vm_radix_is_empty(&object->cache))) {
1463 		mtx_unlock(&vm_page_queue_free_mtx);
1464 		return;
1465 	}
1466 	while ((m = vm_radix_lookup_ge(&object->cache, start)) != NULL) {
1467 		if (end != 0 && m->pindex >= end)
1468 			break;
1469 		vm_radix_remove(&object->cache, m->pindex);
1470 		vm_page_cache_turn_free(m);
1471 	}
1472 	empty = vm_radix_is_empty(&object->cache);
1473 	mtx_unlock(&vm_page_queue_free_mtx);
1474 	if (object->type == OBJT_VNODE && empty)
1475 		vdrop(object->handle);
1476 }
1477 
1478 /*
1479  *	Returns the cached page that is associated with the given
1480  *	object and offset.  If, however, none exists, returns NULL.
1481  *
1482  *	The free page queue must be locked.
1483  */
1484 static inline vm_page_t
1485 vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
1486 {
1487 
1488 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1489 	return (vm_radix_lookup(&object->cache, pindex));
1490 }
1491 
1492 /*
1493  *	Remove the given cached page from its containing object's
1494  *	collection of cached pages.
1495  *
1496  *	The free page queue must be locked.
1497  */
1498 static void
1499 vm_page_cache_remove(vm_page_t m)
1500 {
1501 
1502 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1503 	KASSERT((m->flags & PG_CACHED) != 0,
1504 	    ("vm_page_cache_remove: page %p is not cached", m));
1505 	vm_radix_remove(&m->object->cache, m->pindex);
1506 	m->object = NULL;
1507 	vm_cnt.v_cache_count--;
1508 }
1509 
1510 /*
1511  *	Transfer all of the cached pages with offset greater than or
1512  *	equal to 'offidxstart' from the original object's cache to the
1513  *	new object's cache.  However, any cached pages with offset
1514  *	greater than or equal to the new object's size are kept in the
1515  *	original object.  Initially, the new object's cache must be
1516  *	empty.  Offset 'offidxstart' in the original object must
1517  *	correspond to offset zero in the new object.
1518  *
1519  *	The new object must be locked.
1520  */
1521 void
1522 vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1523     vm_object_t new_object)
1524 {
1525 	vm_page_t m;
1526 
1527 	/*
1528 	 * Insertion into an object's collection of cached pages
1529 	 * requires the object to be locked.  In contrast, removal does
1530 	 * not.
1531 	 */
1532 	VM_OBJECT_ASSERT_WLOCKED(new_object);
1533 	KASSERT(vm_radix_is_empty(&new_object->cache),
1534 	    ("vm_page_cache_transfer: object %p has cached pages",
1535 	    new_object));
1536 	mtx_lock(&vm_page_queue_free_mtx);
1537 	while ((m = vm_radix_lookup_ge(&orig_object->cache,
1538 	    offidxstart)) != NULL) {
1539 		/*
1540 		 * Transfer all of the pages with offset greater than or
1541 		 * equal to 'offidxstart' from the original object's
1542 		 * cache to the new object's cache.
1543 		 */
1544 		if ((m->pindex - offidxstart) >= new_object->size)
1545 			break;
1546 		vm_radix_remove(&orig_object->cache, m->pindex);
1547 		/* Update the page's object and offset. */
1548 		m->object = new_object;
1549 		m->pindex -= offidxstart;
1550 		if (vm_radix_insert(&new_object->cache, m))
1551 			vm_page_cache_turn_free(m);
1552 	}
1553 	mtx_unlock(&vm_page_queue_free_mtx);
1554 }
1555 
1556 /*
1557  *	Returns TRUE if a cached page is associated with the given object and
1558  *	offset, and FALSE otherwise.
1559  *
1560  *	The object must be locked.
1561  */
1562 boolean_t
1563 vm_page_is_cached(vm_object_t object, vm_pindex_t pindex)
1564 {
1565 	vm_page_t m;
1566 
1567 	/*
1568 	 * Insertion into an object's collection of cached pages requires the
1569 	 * object to be locked.  Therefore, if the object is locked and the
1570 	 * object's collection is empty, there is no need to acquire the free
1571 	 * page queues lock in order to prove that the specified page doesn't
1572 	 * exist.
1573 	 */
1574 	VM_OBJECT_ASSERT_WLOCKED(object);
1575 	if (__predict_true(vm_object_cache_is_empty(object)))
1576 		return (FALSE);
1577 	mtx_lock(&vm_page_queue_free_mtx);
1578 	m = vm_page_cache_lookup(object, pindex);
1579 	mtx_unlock(&vm_page_queue_free_mtx);
1580 	return (m != NULL);
1581 }
1582 
1583 /*
1584  *	vm_page_alloc:
1585  *
1586  *	Allocate and return a page that is associated with the specified
1587  *	object and offset pair.  By default, this page is exclusive busied.
1588  *
1589  *	The caller must always specify an allocation class.
1590  *
1591  *	allocation classes:
1592  *	VM_ALLOC_NORMAL		normal process request
1593  *	VM_ALLOC_SYSTEM		system *really* needs a page
1594  *	VM_ALLOC_INTERRUPT	interrupt time request
1595  *
1596  *	optional allocation flags:
1597  *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
1598  *				intends to allocate
1599  *	VM_ALLOC_IFCACHED	return page only if it is cached
1600  *	VM_ALLOC_IFNOTCACHED	return NULL, do not reactivate if the page
1601  *				is cached
1602  *	VM_ALLOC_NOBUSY		do not exclusive busy the page
1603  *	VM_ALLOC_NODUMP		do not include the page in a kernel core dump
1604  *	VM_ALLOC_NOOBJ		page is not associated with an object and
1605  *				should not be exclusive busy
1606  *	VM_ALLOC_SBUSY		shared busy the allocated page
1607  *	VM_ALLOC_WIRED		wire the allocated page
1608  *	VM_ALLOC_ZERO		prefer a zeroed page
1609  *
1610  *	This routine may not sleep.
1611  */
1612 vm_page_t
1613 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1614 {
1615 	struct vnode *vp = NULL;
1616 	vm_object_t m_object;
1617 	vm_page_t m, mpred;
1618 	int flags, req_class;
1619 
1620 	mpred = 0;	/* XXX: pacify gcc */
1621 	KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1622 	    (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1623 	    ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1624 	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1625 	    ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1626 	    req));
1627 	if (object != NULL)
1628 		VM_OBJECT_ASSERT_WLOCKED(object);
1629 
1630 	req_class = req & VM_ALLOC_CLASS_MASK;
1631 
1632 	/*
1633 	 * The page daemon is allowed to dig deeper into the free page list.
1634 	 */
1635 	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1636 		req_class = VM_ALLOC_SYSTEM;
1637 
1638 	if (object != NULL) {
1639 		mpred = vm_radix_lookup_le(&object->rtree, pindex);
1640 		KASSERT(mpred == NULL || mpred->pindex != pindex,
1641 		   ("vm_page_alloc: pindex already allocated"));
1642 	}
1643 
1644 	/*
1645 	 * The page allocation request can came from consumers which already
1646 	 * hold the free page queue mutex, like vm_page_insert() in
1647 	 * vm_page_cache().
1648 	 */
1649 	mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
1650 	if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
1651 	    (req_class == VM_ALLOC_SYSTEM &&
1652 	    vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
1653 	    (req_class == VM_ALLOC_INTERRUPT &&
1654 	    vm_cnt.v_free_count + vm_cnt.v_cache_count > 0)) {
1655 		/*
1656 		 * Allocate from the free queue if the number of free pages
1657 		 * exceeds the minimum for the request class.
1658 		 */
1659 		if (object != NULL &&
1660 		    (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1661 			if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1662 				mtx_unlock(&vm_page_queue_free_mtx);
1663 				return (NULL);
1664 			}
1665 			if (vm_phys_unfree_page(m))
1666 				vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1667 #if VM_NRESERVLEVEL > 0
1668 			else if (!vm_reserv_reactivate_page(m))
1669 #else
1670 			else
1671 #endif
1672 				panic("vm_page_alloc: cache page %p is missing"
1673 				    " from the free queue", m);
1674 		} else if ((req & VM_ALLOC_IFCACHED) != 0) {
1675 			mtx_unlock(&vm_page_queue_free_mtx);
1676 			return (NULL);
1677 #if VM_NRESERVLEVEL > 0
1678 		} else if (object == NULL || (object->flags & (OBJ_COLORED |
1679 		    OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1680 		    vm_reserv_alloc_page(object, pindex, mpred)) == NULL) {
1681 #else
1682 		} else {
1683 #endif
1684 			m = vm_phys_alloc_pages(object != NULL ?
1685 			    VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1686 #if VM_NRESERVLEVEL > 0
1687 			if (m == NULL && vm_reserv_reclaim_inactive()) {
1688 				m = vm_phys_alloc_pages(object != NULL ?
1689 				    VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1690 				    0);
1691 			}
1692 #endif
1693 		}
1694 	} else {
1695 		/*
1696 		 * Not allocatable, give up.
1697 		 */
1698 		mtx_unlock(&vm_page_queue_free_mtx);
1699 		atomic_add_int(&vm_pageout_deficit,
1700 		    max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1701 		pagedaemon_wakeup();
1702 		return (NULL);
1703 	}
1704 
1705 	/*
1706 	 *  At this point we had better have found a good page.
1707 	 */
1708 	KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1709 	KASSERT(m->queue == PQ_NONE,
1710 	    ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1711 	KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1712 	KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1713 	KASSERT(!vm_page_busied(m), ("vm_page_alloc: page %p is busy", m));
1714 	KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1715 	KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1716 	    ("vm_page_alloc: page %p has unexpected memattr %d", m,
1717 	    pmap_page_get_memattr(m)));
1718 	if ((m->flags & PG_CACHED) != 0) {
1719 		KASSERT((m->flags & PG_ZERO) == 0,
1720 		    ("vm_page_alloc: cached page %p is PG_ZERO", m));
1721 		KASSERT(m->valid != 0,
1722 		    ("vm_page_alloc: cached page %p is invalid", m));
1723 		if (m->object == object && m->pindex == pindex)
1724 			vm_cnt.v_reactivated++;
1725 		else
1726 			m->valid = 0;
1727 		m_object = m->object;
1728 		vm_page_cache_remove(m);
1729 		if (m_object->type == OBJT_VNODE &&
1730 		    vm_object_cache_is_empty(m_object))
1731 			vp = m_object->handle;
1732 	} else {
1733 		KASSERT(m->valid == 0,
1734 		    ("vm_page_alloc: free page %p is valid", m));
1735 		vm_phys_freecnt_adj(m, -1);
1736 	}
1737 	mtx_unlock(&vm_page_queue_free_mtx);
1738 
1739 	/*
1740 	 * Initialize the page.  Only the PG_ZERO flag is inherited.
1741 	 */
1742 	flags = 0;
1743 	if ((req & VM_ALLOC_ZERO) != 0)
1744 		flags = PG_ZERO;
1745 	flags &= m->flags;
1746 	if ((req & VM_ALLOC_NODUMP) != 0)
1747 		flags |= PG_NODUMP;
1748 	m->flags = flags;
1749 	m->aflags = 0;
1750 	m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1751 	    VPO_UNMANAGED : 0;
1752 	m->busy_lock = VPB_UNBUSIED;
1753 	if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1754 		m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1755 	if ((req & VM_ALLOC_SBUSY) != 0)
1756 		m->busy_lock = VPB_SHARERS_WORD(1);
1757 	if (req & VM_ALLOC_WIRED) {
1758 		/*
1759 		 * The page lock is not required for wiring a page until that
1760 		 * page is inserted into the object.
1761 		 */
1762 		atomic_add_int(&vm_cnt.v_wire_count, 1);
1763 		m->wire_count = 1;
1764 	}
1765 	m->act_count = 0;
1766 
1767 	if (object != NULL) {
1768 		if (vm_page_insert_after(m, object, pindex, mpred)) {
1769 			/* See the comment below about hold count. */
1770 			if (vp != NULL)
1771 				vdrop(vp);
1772 			pagedaemon_wakeup();
1773 			if (req & VM_ALLOC_WIRED) {
1774 				atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1775 				m->wire_count = 0;
1776 			}
1777 			m->object = NULL;
1778 			m->oflags = VPO_UNMANAGED;
1779 			m->busy_lock = VPB_UNBUSIED;
1780 			vm_page_free(m);
1781 			return (NULL);
1782 		}
1783 
1784 		/* Ignore device objects; the pager sets "memattr" for them. */
1785 		if (object->memattr != VM_MEMATTR_DEFAULT &&
1786 		    (object->flags & OBJ_FICTITIOUS) == 0)
1787 			pmap_page_set_memattr(m, object->memattr);
1788 	} else
1789 		m->pindex = pindex;
1790 
1791 	/*
1792 	 * The following call to vdrop() must come after the above call
1793 	 * to vm_page_insert() in case both affect the same object and
1794 	 * vnode.  Otherwise, the affected vnode's hold count could
1795 	 * temporarily become zero.
1796 	 */
1797 	if (vp != NULL)
1798 		vdrop(vp);
1799 
1800 	/*
1801 	 * Don't wakeup too often - wakeup the pageout daemon when
1802 	 * we would be nearly out of memory.
1803 	 */
1804 	if (vm_paging_needed())
1805 		pagedaemon_wakeup();
1806 
1807 	return (m);
1808 }
1809 
1810 static void
1811 vm_page_alloc_contig_vdrop(struct spglist *lst)
1812 {
1813 
1814 	while (!SLIST_EMPTY(lst)) {
1815 		vdrop((struct vnode *)SLIST_FIRST(lst)-> plinks.s.pv);
1816 		SLIST_REMOVE_HEAD(lst, plinks.s.ss);
1817 	}
1818 }
1819 
1820 /*
1821  *	vm_page_alloc_contig:
1822  *
1823  *	Allocate a contiguous set of physical pages of the given size "npages"
1824  *	from the free lists.  All of the physical pages must be at or above
1825  *	the given physical address "low" and below the given physical address
1826  *	"high".  The given value "alignment" determines the alignment of the
1827  *	first physical page in the set.  If the given value "boundary" is
1828  *	non-zero, then the set of physical pages cannot cross any physical
1829  *	address boundary that is a multiple of that value.  Both "alignment"
1830  *	and "boundary" must be a power of two.
1831  *
1832  *	If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1833  *	then the memory attribute setting for the physical pages is configured
1834  *	to the object's memory attribute setting.  Otherwise, the memory
1835  *	attribute setting for the physical pages is configured to "memattr",
1836  *	overriding the object's memory attribute setting.  However, if the
1837  *	object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1838  *	memory attribute setting for the physical pages cannot be configured
1839  *	to VM_MEMATTR_DEFAULT.
1840  *
1841  *	The caller must always specify an allocation class.
1842  *
1843  *	allocation classes:
1844  *	VM_ALLOC_NORMAL		normal process request
1845  *	VM_ALLOC_SYSTEM		system *really* needs a page
1846  *	VM_ALLOC_INTERRUPT	interrupt time request
1847  *
1848  *	optional allocation flags:
1849  *	VM_ALLOC_NOBUSY		do not exclusive busy the page
1850  *	VM_ALLOC_NODUMP		do not include the page in a kernel core dump
1851  *	VM_ALLOC_NOOBJ		page is not associated with an object and
1852  *				should not be exclusive busy
1853  *	VM_ALLOC_SBUSY		shared busy the allocated page
1854  *	VM_ALLOC_WIRED		wire the allocated page
1855  *	VM_ALLOC_ZERO		prefer a zeroed page
1856  *
1857  *	This routine may not sleep.
1858  */
1859 vm_page_t
1860 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1861     u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1862     vm_paddr_t boundary, vm_memattr_t memattr)
1863 {
1864 	struct vnode *drop;
1865 	struct spglist deferred_vdrop_list;
1866 	vm_page_t m, m_tmp, m_ret;
1867 	u_int flags;
1868 	int req_class;
1869 
1870 	KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1871 	    (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1872 	    ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1873 	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1874 	    ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1875 	    req));
1876 	if (object != NULL) {
1877 		VM_OBJECT_ASSERT_WLOCKED(object);
1878 		KASSERT(object->type == OBJT_PHYS,
1879 		    ("vm_page_alloc_contig: object %p isn't OBJT_PHYS",
1880 		    object));
1881 	}
1882 	KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1883 	req_class = req & VM_ALLOC_CLASS_MASK;
1884 
1885 	/*
1886 	 * The page daemon is allowed to dig deeper into the free page list.
1887 	 */
1888 	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1889 		req_class = VM_ALLOC_SYSTEM;
1890 
1891 	SLIST_INIT(&deferred_vdrop_list);
1892 	mtx_lock(&vm_page_queue_free_mtx);
1893 	if (vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1894 	    vm_cnt.v_free_reserved || (req_class == VM_ALLOC_SYSTEM &&
1895 	    vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1896 	    vm_cnt.v_interrupt_free_min) || (req_class == VM_ALLOC_INTERRUPT &&
1897 	    vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages)) {
1898 #if VM_NRESERVLEVEL > 0
1899 retry:
1900 		if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1901 		    (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1902 		    low, high, alignment, boundary)) == NULL)
1903 #endif
1904 			m_ret = vm_phys_alloc_contig(npages, low, high,
1905 			    alignment, boundary);
1906 	} else {
1907 		mtx_unlock(&vm_page_queue_free_mtx);
1908 		atomic_add_int(&vm_pageout_deficit, npages);
1909 		pagedaemon_wakeup();
1910 		return (NULL);
1911 	}
1912 	if (m_ret != NULL)
1913 		for (m = m_ret; m < &m_ret[npages]; m++) {
1914 			drop = vm_page_alloc_init(m);
1915 			if (drop != NULL) {
1916 				/*
1917 				 * Enqueue the vnode for deferred vdrop().
1918 				 */
1919 				m->plinks.s.pv = drop;
1920 				SLIST_INSERT_HEAD(&deferred_vdrop_list, m,
1921 				    plinks.s.ss);
1922 			}
1923 		}
1924 	else {
1925 #if VM_NRESERVLEVEL > 0
1926 		if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1927 		    boundary))
1928 			goto retry;
1929 #endif
1930 	}
1931 	mtx_unlock(&vm_page_queue_free_mtx);
1932 	if (m_ret == NULL)
1933 		return (NULL);
1934 
1935 	/*
1936 	 * Initialize the pages.  Only the PG_ZERO flag is inherited.
1937 	 */
1938 	flags = 0;
1939 	if ((req & VM_ALLOC_ZERO) != 0)
1940 		flags = PG_ZERO;
1941 	if ((req & VM_ALLOC_NODUMP) != 0)
1942 		flags |= PG_NODUMP;
1943 	if ((req & VM_ALLOC_WIRED) != 0)
1944 		atomic_add_int(&vm_cnt.v_wire_count, npages);
1945 	if (object != NULL) {
1946 		if (object->memattr != VM_MEMATTR_DEFAULT &&
1947 		    memattr == VM_MEMATTR_DEFAULT)
1948 			memattr = object->memattr;
1949 	}
1950 	for (m = m_ret; m < &m_ret[npages]; m++) {
1951 		m->aflags = 0;
1952 		m->flags = (m->flags | PG_NODUMP) & flags;
1953 		m->busy_lock = VPB_UNBUSIED;
1954 		if (object != NULL) {
1955 			if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
1956 				m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1957 			if ((req & VM_ALLOC_SBUSY) != 0)
1958 				m->busy_lock = VPB_SHARERS_WORD(1);
1959 		}
1960 		if ((req & VM_ALLOC_WIRED) != 0)
1961 			m->wire_count = 1;
1962 		/* Unmanaged pages don't use "act_count". */
1963 		m->oflags = VPO_UNMANAGED;
1964 		if (object != NULL) {
1965 			if (vm_page_insert(m, object, pindex)) {
1966 				vm_page_alloc_contig_vdrop(
1967 				    &deferred_vdrop_list);
1968 				if (vm_paging_needed())
1969 					pagedaemon_wakeup();
1970 				if ((req & VM_ALLOC_WIRED) != 0)
1971 					atomic_subtract_int(&vm_cnt.v_wire_count,
1972 					    npages);
1973 				for (m_tmp = m, m = m_ret;
1974 				    m < &m_ret[npages]; m++) {
1975 					if ((req & VM_ALLOC_WIRED) != 0)
1976 						m->wire_count = 0;
1977 					if (m >= m_tmp) {
1978 						m->object = NULL;
1979 						m->oflags |= VPO_UNMANAGED;
1980 					}
1981 					m->busy_lock = VPB_UNBUSIED;
1982 					vm_page_free(m);
1983 				}
1984 				return (NULL);
1985 			}
1986 		} else
1987 			m->pindex = pindex;
1988 		if (memattr != VM_MEMATTR_DEFAULT)
1989 			pmap_page_set_memattr(m, memattr);
1990 		pindex++;
1991 	}
1992 	vm_page_alloc_contig_vdrop(&deferred_vdrop_list);
1993 	if (vm_paging_needed())
1994 		pagedaemon_wakeup();
1995 	return (m_ret);
1996 }
1997 
1998 /*
1999  * Initialize a page that has been freshly dequeued from a freelist.
2000  * The caller has to drop the vnode returned, if it is not NULL.
2001  *
2002  * This function may only be used to initialize unmanaged pages.
2003  *
2004  * To be called with vm_page_queue_free_mtx held.
2005  */
2006 static struct vnode *
2007 vm_page_alloc_init(vm_page_t m)
2008 {
2009 	struct vnode *drop;
2010 	vm_object_t m_object;
2011 
2012 	KASSERT(m->queue == PQ_NONE,
2013 	    ("vm_page_alloc_init: page %p has unexpected queue %d",
2014 	    m, m->queue));
2015 	KASSERT(m->wire_count == 0,
2016 	    ("vm_page_alloc_init: page %p is wired", m));
2017 	KASSERT(m->hold_count == 0,
2018 	    ("vm_page_alloc_init: page %p is held", m));
2019 	KASSERT(!vm_page_busied(m),
2020 	    ("vm_page_alloc_init: page %p is busy", m));
2021 	KASSERT(m->dirty == 0,
2022 	    ("vm_page_alloc_init: page %p is dirty", m));
2023 	KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2024 	    ("vm_page_alloc_init: page %p has unexpected memattr %d",
2025 	    m, pmap_page_get_memattr(m)));
2026 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2027 	drop = NULL;
2028 	if ((m->flags & PG_CACHED) != 0) {
2029 		KASSERT((m->flags & PG_ZERO) == 0,
2030 		    ("vm_page_alloc_init: cached page %p is PG_ZERO", m));
2031 		m->valid = 0;
2032 		m_object = m->object;
2033 		vm_page_cache_remove(m);
2034 		if (m_object->type == OBJT_VNODE &&
2035 		    vm_object_cache_is_empty(m_object))
2036 			drop = m_object->handle;
2037 	} else {
2038 		KASSERT(m->valid == 0,
2039 		    ("vm_page_alloc_init: free page %p is valid", m));
2040 		vm_phys_freecnt_adj(m, -1);
2041 	}
2042 	return (drop);
2043 }
2044 
2045 /*
2046  * 	vm_page_alloc_freelist:
2047  *
2048  *	Allocate a physical page from the specified free page list.
2049  *
2050  *	The caller must always specify an allocation class.
2051  *
2052  *	allocation classes:
2053  *	VM_ALLOC_NORMAL		normal process request
2054  *	VM_ALLOC_SYSTEM		system *really* needs a page
2055  *	VM_ALLOC_INTERRUPT	interrupt time request
2056  *
2057  *	optional allocation flags:
2058  *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
2059  *				intends to allocate
2060  *	VM_ALLOC_WIRED		wire the allocated page
2061  *	VM_ALLOC_ZERO		prefer a zeroed page
2062  *
2063  *	This routine may not sleep.
2064  */
2065 vm_page_t
2066 vm_page_alloc_freelist(int flind, int req)
2067 {
2068 	struct vnode *drop;
2069 	vm_page_t m;
2070 	u_int flags;
2071 	int req_class;
2072 
2073 	req_class = req & VM_ALLOC_CLASS_MASK;
2074 
2075 	/*
2076 	 * The page daemon is allowed to dig deeper into the free page list.
2077 	 */
2078 	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2079 		req_class = VM_ALLOC_SYSTEM;
2080 
2081 	/*
2082 	 * Do not allocate reserved pages unless the req has asked for it.
2083 	 */
2084 	mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
2085 	if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
2086 	    (req_class == VM_ALLOC_SYSTEM &&
2087 	    vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
2088 	    (req_class == VM_ALLOC_INTERRUPT &&
2089 	    vm_cnt.v_free_count + vm_cnt.v_cache_count > 0))
2090 		m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
2091 	else {
2092 		mtx_unlock(&vm_page_queue_free_mtx);
2093 		atomic_add_int(&vm_pageout_deficit,
2094 		    max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
2095 		pagedaemon_wakeup();
2096 		return (NULL);
2097 	}
2098 	if (m == NULL) {
2099 		mtx_unlock(&vm_page_queue_free_mtx);
2100 		return (NULL);
2101 	}
2102 	drop = vm_page_alloc_init(m);
2103 	mtx_unlock(&vm_page_queue_free_mtx);
2104 
2105 	/*
2106 	 * Initialize the page.  Only the PG_ZERO flag is inherited.
2107 	 */
2108 	m->aflags = 0;
2109 	flags = 0;
2110 	if ((req & VM_ALLOC_ZERO) != 0)
2111 		flags = PG_ZERO;
2112 	m->flags &= flags;
2113 	if ((req & VM_ALLOC_WIRED) != 0) {
2114 		/*
2115 		 * The page lock is not required for wiring a page that does
2116 		 * not belong to an object.
2117 		 */
2118 		atomic_add_int(&vm_cnt.v_wire_count, 1);
2119 		m->wire_count = 1;
2120 	}
2121 	/* Unmanaged pages don't use "act_count". */
2122 	m->oflags = VPO_UNMANAGED;
2123 	if (drop != NULL)
2124 		vdrop(drop);
2125 	if (vm_paging_needed())
2126 		pagedaemon_wakeup();
2127 	return (m);
2128 }
2129 
2130 #define	VPSC_ANY	0	/* No restrictions. */
2131 #define	VPSC_NORESERV	1	/* Skip reservations; implies VPSC_NOSUPER. */
2132 #define	VPSC_NOSUPER	2	/* Skip superpages. */
2133 
2134 /*
2135  *	vm_page_scan_contig:
2136  *
2137  *	Scan vm_page_array[] between the specified entries "m_start" and
2138  *	"m_end" for a run of contiguous physical pages that satisfy the
2139  *	specified conditions, and return the lowest page in the run.  The
2140  *	specified "alignment" determines the alignment of the lowest physical
2141  *	page in the run.  If the specified "boundary" is non-zero, then the
2142  *	run of physical pages cannot span a physical address that is a
2143  *	multiple of "boundary".
2144  *
2145  *	"m_end" is never dereferenced, so it need not point to a vm_page
2146  *	structure within vm_page_array[].
2147  *
2148  *	"npages" must be greater than zero.  "m_start" and "m_end" must not
2149  *	span a hole (or discontiguity) in the physical address space.  Both
2150  *	"alignment" and "boundary" must be a power of two.
2151  */
2152 vm_page_t
2153 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2154     u_long alignment, vm_paddr_t boundary, int options)
2155 {
2156 	struct mtx *m_mtx, *new_mtx;
2157 	vm_object_t object;
2158 	vm_paddr_t pa;
2159 	vm_page_t m, m_run;
2160 #if VM_NRESERVLEVEL > 0
2161 	int level;
2162 #endif
2163 	int m_inc, order, run_ext, run_len;
2164 
2165 	KASSERT(npages > 0, ("npages is 0"));
2166 	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2167 	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2168 	m_run = NULL;
2169 	run_len = 0;
2170 	m_mtx = NULL;
2171 	for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2172 		KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2173 		    ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2174 
2175 		/*
2176 		 * If the current page would be the start of a run, check its
2177 		 * physical address against the end, alignment, and boundary
2178 		 * conditions.  If it doesn't satisfy these conditions, either
2179 		 * terminate the scan or advance to the next page that
2180 		 * satisfies the failed condition.
2181 		 */
2182 		if (run_len == 0) {
2183 			KASSERT(m_run == NULL, ("m_run != NULL"));
2184 			if (m + npages > m_end)
2185 				break;
2186 			pa = VM_PAGE_TO_PHYS(m);
2187 			if ((pa & (alignment - 1)) != 0) {
2188 				m_inc = atop(roundup2(pa, alignment) - pa);
2189 				continue;
2190 			}
2191 			if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2192 			    boundary) != 0) {
2193 				m_inc = atop(roundup2(pa, boundary) - pa);
2194 				continue;
2195 			}
2196 		} else
2197 			KASSERT(m_run != NULL, ("m_run == NULL"));
2198 
2199 		/*
2200 		 * Avoid releasing and reacquiring the same page lock.
2201 		 */
2202 		new_mtx = vm_page_lockptr(m);
2203 		if (m_mtx != new_mtx) {
2204 			if (m_mtx != NULL)
2205 				mtx_unlock(m_mtx);
2206 			m_mtx = new_mtx;
2207 			mtx_lock(m_mtx);
2208 		}
2209 		m_inc = 1;
2210 retry:
2211 		if (m->wire_count != 0 || m->hold_count != 0)
2212 			run_ext = 0;
2213 #if VM_NRESERVLEVEL > 0
2214 		else if ((level = vm_reserv_level(m)) >= 0 &&
2215 		    (options & VPSC_NORESERV) != 0) {
2216 			run_ext = 0;
2217 			/* Advance to the end of the reservation. */
2218 			pa = VM_PAGE_TO_PHYS(m);
2219 			m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2220 			    pa);
2221 		}
2222 #endif
2223 		else if ((object = m->object) != NULL) {
2224 			/*
2225 			 * The page is considered eligible for relocation if
2226 			 * and only if it could be laundered or reclaimed by
2227 			 * the page daemon.
2228 			 */
2229 			if (!VM_OBJECT_TRYRLOCK(object)) {
2230 				mtx_unlock(m_mtx);
2231 				VM_OBJECT_RLOCK(object);
2232 				mtx_lock(m_mtx);
2233 				if (m->object != object) {
2234 					/*
2235 					 * The page may have been freed.
2236 					 */
2237 					VM_OBJECT_RUNLOCK(object);
2238 					goto retry;
2239 				} else if (m->wire_count != 0 ||
2240 				    m->hold_count != 0) {
2241 					run_ext = 0;
2242 					goto unlock;
2243 				}
2244 			}
2245 			KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2246 			    ("page %p is PG_UNHOLDFREE", m));
2247 			/* Don't care: PG_NODUMP, PG_WINATCFLS, PG_ZERO. */
2248 			if (object->type != OBJT_DEFAULT &&
2249 			    object->type != OBJT_SWAP &&
2250 			    object->type != OBJT_VNODE)
2251 				run_ext = 0;
2252 			else if ((m->flags & PG_CACHED) != 0 ||
2253 			    m != vm_page_lookup(object, m->pindex)) {
2254 				/*
2255 				 * The page is cached or recently converted
2256 				 * from cached to free.
2257 				 */
2258 #if VM_NRESERVLEVEL > 0
2259 				if (level >= 0) {
2260 					/*
2261 					 * The page is reserved.  Extend the
2262 					 * current run by one page.
2263 					 */
2264 					run_ext = 1;
2265 				} else
2266 #endif
2267 				if ((order = m->order) < VM_NFREEORDER) {
2268 					/*
2269 					 * The page is enqueued in the
2270 					 * physical memory allocator's cache/
2271 					 * free page queues.  Moreover, it is
2272 					 * the first page in a power-of-two-
2273 					 * sized run of contiguous cache/free
2274 					 * pages.  Add these pages to the end
2275 					 * of the current run, and jump
2276 					 * ahead.
2277 					 */
2278 					run_ext = 1 << order;
2279 					m_inc = 1 << order;
2280 				} else
2281 					run_ext = 0;
2282 #if VM_NRESERVLEVEL > 0
2283 			} else if ((options & VPSC_NOSUPER) != 0 &&
2284 			    (level = vm_reserv_level_iffullpop(m)) >= 0) {
2285 				run_ext = 0;
2286 				/* Advance to the end of the superpage. */
2287 				pa = VM_PAGE_TO_PHYS(m);
2288 				m_inc = atop(roundup2(pa + 1,
2289 				    vm_reserv_size(level)) - pa);
2290 #endif
2291 			} else if (object->memattr == VM_MEMATTR_DEFAULT &&
2292 			    m->queue != PQ_NONE && !vm_page_busied(m)) {
2293 				/*
2294 				 * The page is allocated but eligible for
2295 				 * relocation.  Extend the current run by one
2296 				 * page.
2297 				 */
2298 				KASSERT(pmap_page_get_memattr(m) ==
2299 				    VM_MEMATTR_DEFAULT,
2300 				    ("page %p has an unexpected memattr", m));
2301 				KASSERT((m->oflags & (VPO_SWAPINPROG |
2302 				    VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2303 				    ("page %p has unexpected oflags", m));
2304 				/* Don't care: VPO_NOSYNC. */
2305 				run_ext = 1;
2306 			} else
2307 				run_ext = 0;
2308 unlock:
2309 			VM_OBJECT_RUNLOCK(object);
2310 #if VM_NRESERVLEVEL > 0
2311 		} else if (level >= 0) {
2312 			/*
2313 			 * The page is reserved but not yet allocated.  In
2314 			 * other words, it is still cached or free.  Extend
2315 			 * the current run by one page.
2316 			 */
2317 			run_ext = 1;
2318 #endif
2319 		} else if ((order = m->order) < VM_NFREEORDER) {
2320 			/*
2321 			 * The page is enqueued in the physical memory
2322 			 * allocator's cache/free page queues.  Moreover, it
2323 			 * is the first page in a power-of-two-sized run of
2324 			 * contiguous cache/free pages.  Add these pages to
2325 			 * the end of the current run, and jump ahead.
2326 			 */
2327 			run_ext = 1 << order;
2328 			m_inc = 1 << order;
2329 		} else {
2330 			/*
2331 			 * Skip the page for one of the following reasons: (1)
2332 			 * It is enqueued in the physical memory allocator's
2333 			 * cache/free page queues.  However, it is not the
2334 			 * first page in a run of contiguous cache/free pages.
2335 			 * (This case rarely occurs because the scan is
2336 			 * performed in ascending order.) (2) It is not
2337 			 * reserved, and it is transitioning from free to
2338 			 * allocated.  (Conversely, the transition from
2339 			 * allocated to free for managed pages is blocked by
2340 			 * the page lock.) (3) It is allocated but not
2341 			 * contained by an object and not wired, e.g.,
2342 			 * allocated by Xen's balloon driver.
2343 			 */
2344 			run_ext = 0;
2345 		}
2346 
2347 		/*
2348 		 * Extend or reset the current run of pages.
2349 		 */
2350 		if (run_ext > 0) {
2351 			if (run_len == 0)
2352 				m_run = m;
2353 			run_len += run_ext;
2354 		} else {
2355 			if (run_len > 0) {
2356 				m_run = NULL;
2357 				run_len = 0;
2358 			}
2359 		}
2360 	}
2361 	if (m_mtx != NULL)
2362 		mtx_unlock(m_mtx);
2363 	if (run_len >= npages)
2364 		return (m_run);
2365 	return (NULL);
2366 }
2367 
2368 /*
2369  *	vm_page_reclaim_run:
2370  *
2371  *	Try to relocate each of the allocated virtual pages within the
2372  *	specified run of physical pages to a new physical address.  Free the
2373  *	physical pages underlying the relocated virtual pages.  A virtual page
2374  *	is relocatable if and only if it could be laundered or reclaimed by
2375  *	the page daemon.  Whenever possible, a virtual page is relocated to a
2376  *	physical address above "high".
2377  *
2378  *	Returns 0 if every physical page within the run was already free or
2379  *	just freed by a successful relocation.  Otherwise, returns a non-zero
2380  *	value indicating why the last attempt to relocate a virtual page was
2381  *	unsuccessful.
2382  *
2383  *	"req_class" must be an allocation class.
2384  */
2385 static int
2386 vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
2387     vm_paddr_t high)
2388 {
2389 	struct mtx *m_mtx, *new_mtx;
2390 	struct spglist free;
2391 	vm_object_t object;
2392 	vm_paddr_t pa;
2393 	vm_page_t m, m_end, m_new;
2394 	int error, order, req;
2395 
2396 	KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2397 	    ("req_class is not an allocation class"));
2398 	SLIST_INIT(&free);
2399 	error = 0;
2400 	m = m_run;
2401 	m_end = m_run + npages;
2402 	m_mtx = NULL;
2403 	for (; error == 0 && m < m_end; m++) {
2404 		KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2405 		    ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2406 
2407 		/*
2408 		 * Avoid releasing and reacquiring the same page lock.
2409 		 */
2410 		new_mtx = vm_page_lockptr(m);
2411 		if (m_mtx != new_mtx) {
2412 			if (m_mtx != NULL)
2413 				mtx_unlock(m_mtx);
2414 			m_mtx = new_mtx;
2415 			mtx_lock(m_mtx);
2416 		}
2417 retry:
2418 		if (m->wire_count != 0 || m->hold_count != 0)
2419 			error = EBUSY;
2420 		else if ((object = m->object) != NULL) {
2421 			/*
2422 			 * The page is relocated if and only if it could be
2423 			 * laundered or reclaimed by the page daemon.
2424 			 */
2425 			if (!VM_OBJECT_TRYWLOCK(object)) {
2426 				mtx_unlock(m_mtx);
2427 				VM_OBJECT_WLOCK(object);
2428 				mtx_lock(m_mtx);
2429 				if (m->object != object) {
2430 					/*
2431 					 * The page may have been freed.
2432 					 */
2433 					VM_OBJECT_WUNLOCK(object);
2434 					goto retry;
2435 				} else if (m->wire_count != 0 ||
2436 				    m->hold_count != 0) {
2437 					error = EBUSY;
2438 					goto unlock;
2439 				}
2440 			}
2441 			KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2442 			    ("page %p is PG_UNHOLDFREE", m));
2443 			/* Don't care: PG_NODUMP, PG_WINATCFLS, PG_ZERO. */
2444 			if (object->type != OBJT_DEFAULT &&
2445 			    object->type != OBJT_SWAP &&
2446 			    object->type != OBJT_VNODE)
2447 				error = EINVAL;
2448 			else if ((m->flags & PG_CACHED) != 0 ||
2449 			    m != vm_page_lookup(object, m->pindex)) {
2450 				/*
2451 				 * The page is cached or recently converted
2452 				 * from cached to free.
2453 				 */
2454 				VM_OBJECT_WUNLOCK(object);
2455 				goto cached;
2456 			} else if (object->memattr != VM_MEMATTR_DEFAULT)
2457 				error = EINVAL;
2458 			else if (m->queue != PQ_NONE && !vm_page_busied(m)) {
2459 				KASSERT(pmap_page_get_memattr(m) ==
2460 				    VM_MEMATTR_DEFAULT,
2461 				    ("page %p has an unexpected memattr", m));
2462 				KASSERT((m->oflags & (VPO_SWAPINPROG |
2463 				    VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2464 				    ("page %p has unexpected oflags", m));
2465 				/* Don't care: VPO_NOSYNC. */
2466 				if (m->valid != 0) {
2467 					/*
2468 					 * First, try to allocate a new page
2469 					 * that is above "high".  Failing
2470 					 * that, try to allocate a new page
2471 					 * that is below "m_run".  Allocate
2472 					 * the new page between the end of
2473 					 * "m_run" and "high" only as a last
2474 					 * resort.
2475 					 */
2476 					req = req_class | VM_ALLOC_NOOBJ;
2477 					if ((m->flags & PG_NODUMP) != 0)
2478 						req |= VM_ALLOC_NODUMP;
2479 					if (trunc_page(high) !=
2480 					    ~(vm_paddr_t)PAGE_MASK) {
2481 						m_new = vm_page_alloc_contig(
2482 						    NULL, 0, req, 1,
2483 						    round_page(high),
2484 						    ~(vm_paddr_t)0,
2485 						    PAGE_SIZE, 0,
2486 						    VM_MEMATTR_DEFAULT);
2487 					} else
2488 						m_new = NULL;
2489 					if (m_new == NULL) {
2490 						pa = VM_PAGE_TO_PHYS(m_run);
2491 						m_new = vm_page_alloc_contig(
2492 						    NULL, 0, req, 1,
2493 						    0, pa - 1, PAGE_SIZE, 0,
2494 						    VM_MEMATTR_DEFAULT);
2495 					}
2496 					if (m_new == NULL) {
2497 						pa += ptoa(npages);
2498 						m_new = vm_page_alloc_contig(
2499 						    NULL, 0, req, 1,
2500 						    pa, high, PAGE_SIZE, 0,
2501 						    VM_MEMATTR_DEFAULT);
2502 					}
2503 					if (m_new == NULL) {
2504 						error = ENOMEM;
2505 						goto unlock;
2506 					}
2507 					KASSERT(m_new->wire_count == 0,
2508 					    ("page %p is wired", m));
2509 
2510 					/*
2511 					 * Replace "m" with the new page.  For
2512 					 * vm_page_replace(), "m" must be busy
2513 					 * and dequeued.  Finally, change "m"
2514 					 * as if vm_page_free() was called.
2515 					 */
2516 					if (object->ref_count != 0)
2517 						pmap_remove_all(m);
2518 					m_new->aflags = m->aflags;
2519 					KASSERT(m_new->oflags == VPO_UNMANAGED,
2520 					    ("page %p is managed", m));
2521 					m_new->oflags = m->oflags & VPO_NOSYNC;
2522 					pmap_copy_page(m, m_new);
2523 					m_new->valid = m->valid;
2524 					m_new->dirty = m->dirty;
2525 					m->flags &= ~PG_ZERO;
2526 					vm_page_xbusy(m);
2527 					vm_page_remque(m);
2528 					vm_page_replace_checked(m_new, object,
2529 					    m->pindex, m);
2530 					m->valid = 0;
2531 					vm_page_undirty(m);
2532 
2533 					/*
2534 					 * The new page must be deactivated
2535 					 * before the object is unlocked.
2536 					 */
2537 					new_mtx = vm_page_lockptr(m_new);
2538 					if (m_mtx != new_mtx) {
2539 						mtx_unlock(m_mtx);
2540 						m_mtx = new_mtx;
2541 						mtx_lock(m_mtx);
2542 					}
2543 					vm_page_deactivate(m_new);
2544 				} else {
2545 					m->flags &= ~PG_ZERO;
2546 					vm_page_remque(m);
2547 					vm_page_remove(m);
2548 					KASSERT(m->dirty == 0,
2549 					    ("page %p is dirty", m));
2550 				}
2551 				SLIST_INSERT_HEAD(&free, m, plinks.s.ss);
2552 			} else
2553 				error = EBUSY;
2554 unlock:
2555 			VM_OBJECT_WUNLOCK(object);
2556 		} else {
2557 cached:
2558 			mtx_lock(&vm_page_queue_free_mtx);
2559 			order = m->order;
2560 			if (order < VM_NFREEORDER) {
2561 				/*
2562 				 * The page is enqueued in the physical memory
2563 				 * allocator's cache/free page queues.
2564 				 * Moreover, it is the first page in a power-
2565 				 * of-two-sized run of contiguous cache/free
2566 				 * pages.  Jump ahead to the last page within
2567 				 * that run, and continue from there.
2568 				 */
2569 				m += (1 << order) - 1;
2570 			}
2571 #if VM_NRESERVLEVEL > 0
2572 			else if (vm_reserv_is_page_free(m))
2573 				order = 0;
2574 #endif
2575 			mtx_unlock(&vm_page_queue_free_mtx);
2576 			if (order == VM_NFREEORDER)
2577 				error = EINVAL;
2578 		}
2579 	}
2580 	if (m_mtx != NULL)
2581 		mtx_unlock(m_mtx);
2582 	if ((m = SLIST_FIRST(&free)) != NULL) {
2583 		mtx_lock(&vm_page_queue_free_mtx);
2584 		do {
2585 			SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2586 			vm_phys_freecnt_adj(m, 1);
2587 #if VM_NRESERVLEVEL > 0
2588 			if (!vm_reserv_free_page(m))
2589 #else
2590 			if (true)
2591 #endif
2592 				vm_phys_free_pages(m, 0);
2593 		} while ((m = SLIST_FIRST(&free)) != NULL);
2594 		vm_page_free_wakeup();
2595 		mtx_unlock(&vm_page_queue_free_mtx);
2596 	}
2597 	return (error);
2598 }
2599 
2600 #define	NRUNS	16
2601 
2602 CTASSERT(powerof2(NRUNS));
2603 
2604 #define	RUN_INDEX(count)	((count) & (NRUNS - 1))
2605 
2606 #define	MIN_RECLAIM	8
2607 
2608 /*
2609  *	vm_page_reclaim_contig:
2610  *
2611  *	Reclaim allocated, contiguous physical memory satisfying the specified
2612  *	conditions by relocating the virtual pages using that physical memory.
2613  *	Returns true if reclamation is successful and false otherwise.  Since
2614  *	relocation requires the allocation of physical pages, reclamation may
2615  *	fail due to a shortage of cache/free pages.  When reclamation fails,
2616  *	callers are expected to perform VM_WAIT before retrying a failed
2617  *	allocation operation, e.g., vm_page_alloc_contig().
2618  *
2619  *	The caller must always specify an allocation class through "req".
2620  *
2621  *	allocation classes:
2622  *	VM_ALLOC_NORMAL		normal process request
2623  *	VM_ALLOC_SYSTEM		system *really* needs a page
2624  *	VM_ALLOC_INTERRUPT	interrupt time request
2625  *
2626  *	The optional allocation flags are ignored.
2627  *
2628  *	"npages" must be greater than zero.  Both "alignment" and "boundary"
2629  *	must be a power of two.
2630  */
2631 bool
2632 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2633     u_long alignment, vm_paddr_t boundary)
2634 {
2635 	vm_paddr_t curr_low;
2636 	vm_page_t m_run, m_runs[NRUNS];
2637 	u_long count, reclaimed;
2638 	int error, i, options, req_class;
2639 
2640 	KASSERT(npages > 0, ("npages is 0"));
2641 	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2642 	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2643 	req_class = req & VM_ALLOC_CLASS_MASK;
2644 
2645 	/*
2646 	 * The page daemon is allowed to dig deeper into the free page list.
2647 	 */
2648 	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2649 		req_class = VM_ALLOC_SYSTEM;
2650 
2651 	/*
2652 	 * Return if the number of cached and free pages cannot satisfy the
2653 	 * requested allocation.
2654 	 */
2655 	count = vm_cnt.v_free_count + vm_cnt.v_cache_count;
2656 	if (count < npages + vm_cnt.v_free_reserved || (count < npages +
2657 	    vm_cnt.v_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2658 	    (count < npages && req_class == VM_ALLOC_INTERRUPT))
2659 		return (false);
2660 
2661 	/*
2662 	 * Scan up to three times, relaxing the restrictions ("options") on
2663 	 * the reclamation of reservations and superpages each time.
2664 	 */
2665 	for (options = VPSC_NORESERV;;) {
2666 		/*
2667 		 * Find the highest runs that satisfy the given constraints
2668 		 * and restrictions, and record them in "m_runs".
2669 		 */
2670 		curr_low = low;
2671 		count = 0;
2672 		for (;;) {
2673 			m_run = vm_phys_scan_contig(npages, curr_low, high,
2674 			    alignment, boundary, options);
2675 			if (m_run == NULL)
2676 				break;
2677 			curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2678 			m_runs[RUN_INDEX(count)] = m_run;
2679 			count++;
2680 		}
2681 
2682 		/*
2683 		 * Reclaim the highest runs in LIFO (descending) order until
2684 		 * the number of reclaimed pages, "reclaimed", is at least
2685 		 * MIN_RECLAIM.  Reset "reclaimed" each time because each
2686 		 * reclamation is idempotent, and runs will (likely) recur
2687 		 * from one scan to the next as restrictions are relaxed.
2688 		 */
2689 		reclaimed = 0;
2690 		for (i = 0; count > 0 && i < NRUNS; i++) {
2691 			count--;
2692 			m_run = m_runs[RUN_INDEX(count)];
2693 			error = vm_page_reclaim_run(req_class, npages, m_run,
2694 			    high);
2695 			if (error == 0) {
2696 				reclaimed += npages;
2697 				if (reclaimed >= MIN_RECLAIM)
2698 					return (true);
2699 			}
2700 		}
2701 
2702 		/*
2703 		 * Either relax the restrictions on the next scan or return if
2704 		 * the last scan had no restrictions.
2705 		 */
2706 		if (options == VPSC_NORESERV)
2707 			options = VPSC_NOSUPER;
2708 		else if (options == VPSC_NOSUPER)
2709 			options = VPSC_ANY;
2710 		else if (options == VPSC_ANY)
2711 			return (reclaimed != 0);
2712 	}
2713 }
2714 
2715 /*
2716  *	vm_wait:	(also see VM_WAIT macro)
2717  *
2718  *	Sleep until free pages are available for allocation.
2719  *	- Called in various places before memory allocations.
2720  */
2721 void
2722 vm_wait(void)
2723 {
2724 
2725 	mtx_lock(&vm_page_queue_free_mtx);
2726 	if (curproc == pageproc) {
2727 		vm_pageout_pages_needed = 1;
2728 		msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
2729 		    PDROP | PSWP, "VMWait", 0);
2730 	} else {
2731 		if (!vm_pageout_wanted) {
2732 			vm_pageout_wanted = true;
2733 			wakeup(&vm_pageout_wanted);
2734 		}
2735 		vm_pages_needed = true;
2736 		msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
2737 		    "vmwait", 0);
2738 	}
2739 }
2740 
2741 /*
2742  *	vm_waitpfault:	(also see VM_WAITPFAULT macro)
2743  *
2744  *	Sleep until free pages are available for allocation.
2745  *	- Called only in vm_fault so that processes page faulting
2746  *	  can be easily tracked.
2747  *	- Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2748  *	  processes will be able to grab memory first.  Do not change
2749  *	  this balance without careful testing first.
2750  */
2751 void
2752 vm_waitpfault(void)
2753 {
2754 
2755 	mtx_lock(&vm_page_queue_free_mtx);
2756 	if (!vm_pageout_wanted) {
2757 		vm_pageout_wanted = true;
2758 		wakeup(&vm_pageout_wanted);
2759 	}
2760 	vm_pages_needed = true;
2761 	msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
2762 	    "pfault", 0);
2763 }
2764 
2765 struct vm_pagequeue *
2766 vm_page_pagequeue(vm_page_t m)
2767 {
2768 
2769 	return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2770 }
2771 
2772 /*
2773  *	vm_page_dequeue:
2774  *
2775  *	Remove the given page from its current page queue.
2776  *
2777  *	The page must be locked.
2778  */
2779 void
2780 vm_page_dequeue(vm_page_t m)
2781 {
2782 	struct vm_pagequeue *pq;
2783 
2784 	vm_page_assert_locked(m);
2785 	KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
2786 	    m));
2787 	pq = vm_page_pagequeue(m);
2788 	vm_pagequeue_lock(pq);
2789 	m->queue = PQ_NONE;
2790 	TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2791 	vm_pagequeue_cnt_dec(pq);
2792 	vm_pagequeue_unlock(pq);
2793 }
2794 
2795 /*
2796  *	vm_page_dequeue_locked:
2797  *
2798  *	Remove the given page from its current page queue.
2799  *
2800  *	The page and page queue must be locked.
2801  */
2802 void
2803 vm_page_dequeue_locked(vm_page_t m)
2804 {
2805 	struct vm_pagequeue *pq;
2806 
2807 	vm_page_lock_assert(m, MA_OWNED);
2808 	pq = vm_page_pagequeue(m);
2809 	vm_pagequeue_assert_locked(pq);
2810 	m->queue = PQ_NONE;
2811 	TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2812 	vm_pagequeue_cnt_dec(pq);
2813 }
2814 
2815 /*
2816  *	vm_page_enqueue:
2817  *
2818  *	Add the given page to the specified page queue.
2819  *
2820  *	The page must be locked.
2821  */
2822 static void
2823 vm_page_enqueue(uint8_t queue, vm_page_t m)
2824 {
2825 	struct vm_pagequeue *pq;
2826 
2827 	vm_page_lock_assert(m, MA_OWNED);
2828 	KASSERT(queue < PQ_COUNT,
2829 	    ("vm_page_enqueue: invalid queue %u request for page %p",
2830 	    queue, m));
2831 	pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2832 	vm_pagequeue_lock(pq);
2833 	m->queue = queue;
2834 	TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2835 	vm_pagequeue_cnt_inc(pq);
2836 	vm_pagequeue_unlock(pq);
2837 }
2838 
2839 /*
2840  *	vm_page_requeue:
2841  *
2842  *	Move the given page to the tail of its current page queue.
2843  *
2844  *	The page must be locked.
2845  */
2846 void
2847 vm_page_requeue(vm_page_t m)
2848 {
2849 	struct vm_pagequeue *pq;
2850 
2851 	vm_page_lock_assert(m, MA_OWNED);
2852 	KASSERT(m->queue != PQ_NONE,
2853 	    ("vm_page_requeue: page %p is not queued", m));
2854 	pq = vm_page_pagequeue(m);
2855 	vm_pagequeue_lock(pq);
2856 	TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2857 	TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2858 	vm_pagequeue_unlock(pq);
2859 }
2860 
2861 /*
2862  *	vm_page_requeue_locked:
2863  *
2864  *	Move the given page to the tail of its current page queue.
2865  *
2866  *	The page queue must be locked.
2867  */
2868 void
2869 vm_page_requeue_locked(vm_page_t m)
2870 {
2871 	struct vm_pagequeue *pq;
2872 
2873 	KASSERT(m->queue != PQ_NONE,
2874 	    ("vm_page_requeue_locked: page %p is not queued", m));
2875 	pq = vm_page_pagequeue(m);
2876 	vm_pagequeue_assert_locked(pq);
2877 	TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2878 	TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2879 }
2880 
2881 /*
2882  *	vm_page_activate:
2883  *
2884  *	Put the specified page on the active list (if appropriate).
2885  *	Ensure that act_count is at least ACT_INIT but do not otherwise
2886  *	mess with it.
2887  *
2888  *	The page must be locked.
2889  */
2890 void
2891 vm_page_activate(vm_page_t m)
2892 {
2893 	int queue;
2894 
2895 	vm_page_lock_assert(m, MA_OWNED);
2896 	if ((queue = m->queue) != PQ_ACTIVE) {
2897 		if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2898 			if (m->act_count < ACT_INIT)
2899 				m->act_count = ACT_INIT;
2900 			if (queue != PQ_NONE)
2901 				vm_page_dequeue(m);
2902 			vm_page_enqueue(PQ_ACTIVE, m);
2903 		} else
2904 			KASSERT(queue == PQ_NONE,
2905 			    ("vm_page_activate: wired page %p is queued", m));
2906 	} else {
2907 		if (m->act_count < ACT_INIT)
2908 			m->act_count = ACT_INIT;
2909 	}
2910 }
2911 
2912 /*
2913  *	vm_page_free_wakeup:
2914  *
2915  *	Helper routine for vm_page_free_toq() and vm_page_cache().  This
2916  *	routine is called when a page has been added to the cache or free
2917  *	queues.
2918  *
2919  *	The page queues must be locked.
2920  */
2921 static inline void
2922 vm_page_free_wakeup(void)
2923 {
2924 
2925 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2926 	/*
2927 	 * if pageout daemon needs pages, then tell it that there are
2928 	 * some free.
2929 	 */
2930 	if (vm_pageout_pages_needed &&
2931 	    vm_cnt.v_cache_count + vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
2932 		wakeup(&vm_pageout_pages_needed);
2933 		vm_pageout_pages_needed = 0;
2934 	}
2935 	/*
2936 	 * wakeup processes that are waiting on memory if we hit a
2937 	 * high water mark. And wakeup scheduler process if we have
2938 	 * lots of memory. this process will swapin processes.
2939 	 */
2940 	if (vm_pages_needed && !vm_page_count_min()) {
2941 		vm_pages_needed = false;
2942 		wakeup(&vm_cnt.v_free_count);
2943 	}
2944 }
2945 
2946 /*
2947  *	Turn a cached page into a free page, by changing its attributes.
2948  *	Keep the statistics up-to-date.
2949  *
2950  *	The free page queue must be locked.
2951  */
2952 static void
2953 vm_page_cache_turn_free(vm_page_t m)
2954 {
2955 
2956 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2957 
2958 	m->object = NULL;
2959 	m->valid = 0;
2960 	KASSERT((m->flags & PG_CACHED) != 0,
2961 	    ("vm_page_cache_turn_free: page %p is not cached", m));
2962 	m->flags &= ~PG_CACHED;
2963 	vm_cnt.v_cache_count--;
2964 	vm_phys_freecnt_adj(m, 1);
2965 }
2966 
2967 /*
2968  *	vm_page_free_toq:
2969  *
2970  *	Returns the given page to the free list,
2971  *	disassociating it with any VM object.
2972  *
2973  *	The object must be locked.  The page must be locked if it is managed.
2974  */
2975 void
2976 vm_page_free_toq(vm_page_t m)
2977 {
2978 
2979 	if ((m->oflags & VPO_UNMANAGED) == 0) {
2980 		vm_page_lock_assert(m, MA_OWNED);
2981 		KASSERT(!pmap_page_is_mapped(m),
2982 		    ("vm_page_free_toq: freeing mapped page %p", m));
2983 	} else
2984 		KASSERT(m->queue == PQ_NONE,
2985 		    ("vm_page_free_toq: unmanaged page %p is queued", m));
2986 	PCPU_INC(cnt.v_tfree);
2987 
2988 	if (vm_page_sbusied(m))
2989 		panic("vm_page_free: freeing busy page %p", m);
2990 
2991 	/*
2992 	 * Unqueue, then remove page.  Note that we cannot destroy
2993 	 * the page here because we do not want to call the pager's
2994 	 * callback routine until after we've put the page on the
2995 	 * appropriate free queue.
2996 	 */
2997 	vm_page_remque(m);
2998 	vm_page_remove(m);
2999 
3000 	/*
3001 	 * If fictitious remove object association and
3002 	 * return, otherwise delay object association removal.
3003 	 */
3004 	if ((m->flags & PG_FICTITIOUS) != 0) {
3005 		return;
3006 	}
3007 
3008 	m->valid = 0;
3009 	vm_page_undirty(m);
3010 
3011 	if (m->wire_count != 0)
3012 		panic("vm_page_free: freeing wired page %p", m);
3013 	if (m->hold_count != 0) {
3014 		m->flags &= ~PG_ZERO;
3015 		KASSERT((m->flags & PG_UNHOLDFREE) == 0,
3016 		    ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
3017 		m->flags |= PG_UNHOLDFREE;
3018 	} else {
3019 		/*
3020 		 * Restore the default memory attribute to the page.
3021 		 */
3022 		if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3023 			pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3024 
3025 		/*
3026 		 * Insert the page into the physical memory allocator's
3027 		 * cache/free page queues.
3028 		 */
3029 		mtx_lock(&vm_page_queue_free_mtx);
3030 		vm_phys_freecnt_adj(m, 1);
3031 #if VM_NRESERVLEVEL > 0
3032 		if (!vm_reserv_free_page(m))
3033 #else
3034 		if (TRUE)
3035 #endif
3036 			vm_phys_free_pages(m, 0);
3037 		vm_page_free_wakeup();
3038 		mtx_unlock(&vm_page_queue_free_mtx);
3039 	}
3040 }
3041 
3042 /*
3043  *	vm_page_wire:
3044  *
3045  *	Mark this page as wired down by yet
3046  *	another map, removing it from paging queues
3047  *	as necessary.
3048  *
3049  *	If the page is fictitious, then its wire count must remain one.
3050  *
3051  *	The page must be locked.
3052  */
3053 void
3054 vm_page_wire(vm_page_t m)
3055 {
3056 
3057 	/*
3058 	 * Only bump the wire statistics if the page is not already wired,
3059 	 * and only unqueue the page if it is on some queue (if it is unmanaged
3060 	 * it is already off the queues).
3061 	 */
3062 	vm_page_lock_assert(m, MA_OWNED);
3063 	if ((m->flags & PG_FICTITIOUS) != 0) {
3064 		KASSERT(m->wire_count == 1,
3065 		    ("vm_page_wire: fictitious page %p's wire count isn't one",
3066 		    m));
3067 		return;
3068 	}
3069 	if (m->wire_count == 0) {
3070 		KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
3071 		    m->queue == PQ_NONE,
3072 		    ("vm_page_wire: unmanaged page %p is queued", m));
3073 		vm_page_remque(m);
3074 		atomic_add_int(&vm_cnt.v_wire_count, 1);
3075 	}
3076 	m->wire_count++;
3077 	KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
3078 }
3079 
3080 /*
3081  * vm_page_unwire:
3082  *
3083  * Release one wiring of the specified page, potentially allowing it to be
3084  * paged out.  Returns TRUE if the number of wirings transitions to zero and
3085  * FALSE otherwise.
3086  *
3087  * Only managed pages belonging to an object can be paged out.  If the number
3088  * of wirings transitions to zero and the page is eligible for page out, then
3089  * the page is added to the specified paging queue (unless PQ_NONE is
3090  * specified).
3091  *
3092  * If a page is fictitious, then its wire count must always be one.
3093  *
3094  * A managed page must be locked.
3095  */
3096 boolean_t
3097 vm_page_unwire(vm_page_t m, uint8_t queue)
3098 {
3099 
3100 	KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
3101 	    ("vm_page_unwire: invalid queue %u request for page %p",
3102 	    queue, m));
3103 	if ((m->oflags & VPO_UNMANAGED) == 0)
3104 		vm_page_assert_locked(m);
3105 	if ((m->flags & PG_FICTITIOUS) != 0) {
3106 		KASSERT(m->wire_count == 1,
3107 	    ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
3108 		return (FALSE);
3109 	}
3110 	if (m->wire_count > 0) {
3111 		m->wire_count--;
3112 		if (m->wire_count == 0) {
3113 			atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3114 			if ((m->oflags & VPO_UNMANAGED) == 0 &&
3115 			    m->object != NULL && queue != PQ_NONE) {
3116 				if (queue == PQ_INACTIVE)
3117 					m->flags &= ~PG_WINATCFLS;
3118 				vm_page_enqueue(queue, m);
3119 			}
3120 			return (TRUE);
3121 		} else
3122 			return (FALSE);
3123 	} else
3124 		panic("vm_page_unwire: page %p's wire count is zero", m);
3125 }
3126 
3127 /*
3128  * Move the specified page to the inactive queue.
3129  *
3130  * Many pages placed on the inactive queue should actually go
3131  * into the cache, but it is difficult to figure out which.  What
3132  * we do instead, if the inactive target is well met, is to put
3133  * clean pages at the head of the inactive queue instead of the tail.
3134  * This will cause them to be moved to the cache more quickly and
3135  * if not actively re-referenced, reclaimed more quickly.  If we just
3136  * stick these pages at the end of the inactive queue, heavy filesystem
3137  * meta-data accesses can cause an unnecessary paging load on memory bound
3138  * processes.  This optimization causes one-time-use metadata to be
3139  * reused more quickly.
3140  *
3141  * Normally noreuse is FALSE, resulting in LRU operation.  noreuse is set
3142  * to TRUE if we want this page to be 'as if it were placed in the cache',
3143  * except without unmapping it from the process address space.  In
3144  * practice this is implemented by inserting the page at the head of the
3145  * queue, using a marker page to guide FIFO insertion ordering.
3146  *
3147  * The page must be locked.
3148  */
3149 static inline void
3150 _vm_page_deactivate(vm_page_t m, boolean_t noreuse)
3151 {
3152 	struct vm_pagequeue *pq;
3153 	int queue;
3154 
3155 	vm_page_assert_locked(m);
3156 
3157 	/*
3158 	 * Ignore if the page is already inactive, unless it is unlikely to be
3159 	 * reactivated.
3160 	 */
3161 	if ((queue = m->queue) == PQ_INACTIVE && !noreuse)
3162 		return;
3163 	if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
3164 		pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
3165 		/* Avoid multiple acquisitions of the inactive queue lock. */
3166 		if (queue == PQ_INACTIVE) {
3167 			vm_pagequeue_lock(pq);
3168 			vm_page_dequeue_locked(m);
3169 		} else {
3170 			if (queue != PQ_NONE)
3171 				vm_page_dequeue(m);
3172 			m->flags &= ~PG_WINATCFLS;
3173 			vm_pagequeue_lock(pq);
3174 		}
3175 		m->queue = PQ_INACTIVE;
3176 		if (noreuse)
3177 			TAILQ_INSERT_BEFORE(&vm_phys_domain(m)->vmd_inacthead,
3178 			    m, plinks.q);
3179 		else
3180 			TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3181 		vm_pagequeue_cnt_inc(pq);
3182 		vm_pagequeue_unlock(pq);
3183 	}
3184 }
3185 
3186 /*
3187  * Move the specified page to the inactive queue.
3188  *
3189  * The page must be locked.
3190  */
3191 void
3192 vm_page_deactivate(vm_page_t m)
3193 {
3194 
3195 	_vm_page_deactivate(m, FALSE);
3196 }
3197 
3198 /*
3199  * Move the specified page to the inactive queue with the expectation
3200  * that it is unlikely to be reused.
3201  *
3202  * The page must be locked.
3203  */
3204 void
3205 vm_page_deactivate_noreuse(vm_page_t m)
3206 {
3207 
3208 	_vm_page_deactivate(m, TRUE);
3209 }
3210 
3211 /*
3212  * vm_page_try_to_cache:
3213  *
3214  * Returns 0 on failure, 1 on success
3215  */
3216 int
3217 vm_page_try_to_cache(vm_page_t m)
3218 {
3219 
3220 	vm_page_lock_assert(m, MA_OWNED);
3221 	VM_OBJECT_ASSERT_WLOCKED(m->object);
3222 	if (m->dirty || m->hold_count || m->wire_count ||
3223 	    (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
3224 		return (0);
3225 	pmap_remove_all(m);
3226 	if (m->dirty)
3227 		return (0);
3228 	vm_page_cache(m);
3229 	return (1);
3230 }
3231 
3232 /*
3233  * vm_page_try_to_free()
3234  *
3235  *	Attempt to free the page.  If we cannot free it, we do nothing.
3236  *	1 is returned on success, 0 on failure.
3237  */
3238 int
3239 vm_page_try_to_free(vm_page_t m)
3240 {
3241 
3242 	vm_page_lock_assert(m, MA_OWNED);
3243 	if (m->object != NULL)
3244 		VM_OBJECT_ASSERT_WLOCKED(m->object);
3245 	if (m->dirty || m->hold_count || m->wire_count ||
3246 	    (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
3247 		return (0);
3248 	pmap_remove_all(m);
3249 	if (m->dirty)
3250 		return (0);
3251 	vm_page_free(m);
3252 	return (1);
3253 }
3254 
3255 /*
3256  * vm_page_cache
3257  *
3258  * Put the specified page onto the page cache queue (if appropriate).
3259  *
3260  * The object and page must be locked.
3261  */
3262 void
3263 vm_page_cache(vm_page_t m)
3264 {
3265 	vm_object_t object;
3266 	boolean_t cache_was_empty;
3267 
3268 	vm_page_lock_assert(m, MA_OWNED);
3269 	object = m->object;
3270 	VM_OBJECT_ASSERT_WLOCKED(object);
3271 	if (vm_page_busied(m) || (m->oflags & VPO_UNMANAGED) ||
3272 	    m->hold_count || m->wire_count)
3273 		panic("vm_page_cache: attempting to cache busy page");
3274 	KASSERT(!pmap_page_is_mapped(m),
3275 	    ("vm_page_cache: page %p is mapped", m));
3276 	KASSERT(m->dirty == 0, ("vm_page_cache: page %p is dirty", m));
3277 	if (m->valid == 0 || object->type == OBJT_DEFAULT ||
3278 	    (object->type == OBJT_SWAP &&
3279 	    !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
3280 		/*
3281 		 * Hypothesis: A cache-eligible page belonging to a
3282 		 * default object or swap object but without a backing
3283 		 * store must be zero filled.
3284 		 */
3285 		vm_page_free(m);
3286 		return;
3287 	}
3288 	KASSERT((m->flags & PG_CACHED) == 0,
3289 	    ("vm_page_cache: page %p is already cached", m));
3290 
3291 	/*
3292 	 * Remove the page from the paging queues.
3293 	 */
3294 	vm_page_remque(m);
3295 
3296 	/*
3297 	 * Remove the page from the object's collection of resident
3298 	 * pages.
3299 	 */
3300 	vm_radix_remove(&object->rtree, m->pindex);
3301 	TAILQ_REMOVE(&object->memq, m, listq);
3302 	object->resident_page_count--;
3303 
3304 	/*
3305 	 * Restore the default memory attribute to the page.
3306 	 */
3307 	if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3308 		pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3309 
3310 	/*
3311 	 * Insert the page into the object's collection of cached pages
3312 	 * and the physical memory allocator's cache/free page queues.
3313 	 */
3314 	m->flags &= ~PG_ZERO;
3315 	mtx_lock(&vm_page_queue_free_mtx);
3316 	cache_was_empty = vm_radix_is_empty(&object->cache);
3317 	if (vm_radix_insert(&object->cache, m)) {
3318 		mtx_unlock(&vm_page_queue_free_mtx);
3319 		if (object->type == OBJT_VNODE &&
3320 		    object->resident_page_count == 0)
3321 			vdrop(object->handle);
3322 		m->object = NULL;
3323 		vm_page_free(m);
3324 		return;
3325 	}
3326 
3327 	/*
3328 	 * The above call to vm_radix_insert() could reclaim the one pre-
3329 	 * existing cached page from this object, resulting in a call to
3330 	 * vdrop().
3331 	 */
3332 	if (!cache_was_empty)
3333 		cache_was_empty = vm_radix_is_singleton(&object->cache);
3334 
3335 	m->flags |= PG_CACHED;
3336 	vm_cnt.v_cache_count++;
3337 	PCPU_INC(cnt.v_tcached);
3338 #if VM_NRESERVLEVEL > 0
3339 	if (!vm_reserv_free_page(m)) {
3340 #else
3341 	if (TRUE) {
3342 #endif
3343 		vm_phys_free_pages(m, 0);
3344 	}
3345 	vm_page_free_wakeup();
3346 	mtx_unlock(&vm_page_queue_free_mtx);
3347 
3348 	/*
3349 	 * Increment the vnode's hold count if this is the object's only
3350 	 * cached page.  Decrement the vnode's hold count if this was
3351 	 * the object's only resident page.
3352 	 */
3353 	if (object->type == OBJT_VNODE) {
3354 		if (cache_was_empty && object->resident_page_count != 0)
3355 			vhold(object->handle);
3356 		else if (!cache_was_empty && object->resident_page_count == 0)
3357 			vdrop(object->handle);
3358 	}
3359 }
3360 
3361 /*
3362  * vm_page_advise
3363  *
3364  * 	Deactivate or do nothing, as appropriate.
3365  *
3366  *	The object and page must be locked.
3367  */
3368 void
3369 vm_page_advise(vm_page_t m, int advice)
3370 {
3371 
3372 	vm_page_assert_locked(m);
3373 	VM_OBJECT_ASSERT_WLOCKED(m->object);
3374 	if (advice == MADV_FREE)
3375 		/*
3376 		 * Mark the page clean.  This will allow the page to be freed
3377 		 * up by the system.  However, such pages are often reused
3378 		 * quickly by malloc() so we do not do anything that would
3379 		 * cause a page fault if we can help it.
3380 		 *
3381 		 * Specifically, we do not try to actually free the page now
3382 		 * nor do we try to put it in the cache (which would cause a
3383 		 * page fault on reuse).
3384 		 *
3385 		 * But we do make the page as freeable as we can without
3386 		 * actually taking the step of unmapping it.
3387 		 */
3388 		vm_page_undirty(m);
3389 	else if (advice != MADV_DONTNEED)
3390 		return;
3391 
3392 	/*
3393 	 * Clear any references to the page.  Otherwise, the page daemon will
3394 	 * immediately reactivate the page.
3395 	 */
3396 	vm_page_aflag_clear(m, PGA_REFERENCED);
3397 
3398 	if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3399 		vm_page_dirty(m);
3400 
3401 	/*
3402 	 * Place clean pages near the head of the inactive queue rather than
3403 	 * the tail, thus defeating the queue's LRU operation and ensuring that
3404 	 * the page will be reused quickly.  Dirty pages are given a chance to
3405 	 * cycle once through the inactive queue before becoming eligible for
3406 	 * laundering.
3407 	 */
3408 	_vm_page_deactivate(m, m->dirty == 0);
3409 }
3410 
3411 /*
3412  * Grab a page, waiting until we are waken up due to the page
3413  * changing state.  We keep on waiting, if the page continues
3414  * to be in the object.  If the page doesn't exist, first allocate it
3415  * and then conditionally zero it.
3416  *
3417  * This routine may sleep.
3418  *
3419  * The object must be locked on entry.  The lock will, however, be released
3420  * and reacquired if the routine sleeps.
3421  */
3422 vm_page_t
3423 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3424 {
3425 	vm_page_t m;
3426 	int sleep;
3427 
3428 	VM_OBJECT_ASSERT_WLOCKED(object);
3429 	KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3430 	    (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3431 	    ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3432 retrylookup:
3433 	if ((m = vm_page_lookup(object, pindex)) != NULL) {
3434 		sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3435 		    vm_page_xbusied(m) : vm_page_busied(m);
3436 		if (sleep) {
3437 			if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3438 				return (NULL);
3439 			/*
3440 			 * Reference the page before unlocking and
3441 			 * sleeping so that the page daemon is less
3442 			 * likely to reclaim it.
3443 			 */
3444 			vm_page_aflag_set(m, PGA_REFERENCED);
3445 			vm_page_lock(m);
3446 			VM_OBJECT_WUNLOCK(object);
3447 			vm_page_busy_sleep(m, "pgrbwt");
3448 			VM_OBJECT_WLOCK(object);
3449 			goto retrylookup;
3450 		} else {
3451 			if ((allocflags & VM_ALLOC_WIRED) != 0) {
3452 				vm_page_lock(m);
3453 				vm_page_wire(m);
3454 				vm_page_unlock(m);
3455 			}
3456 			if ((allocflags &
3457 			    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3458 				vm_page_xbusy(m);
3459 			if ((allocflags & VM_ALLOC_SBUSY) != 0)
3460 				vm_page_sbusy(m);
3461 			return (m);
3462 		}
3463 	}
3464 	m = vm_page_alloc(object, pindex, allocflags);
3465 	if (m == NULL) {
3466 		if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3467 			return (NULL);
3468 		VM_OBJECT_WUNLOCK(object);
3469 		VM_WAIT;
3470 		VM_OBJECT_WLOCK(object);
3471 		goto retrylookup;
3472 	} else if (m->valid != 0)
3473 		return (m);
3474 	if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3475 		pmap_zero_page(m);
3476 	return (m);
3477 }
3478 
3479 /*
3480  * Mapping function for valid or dirty bits in a page.
3481  *
3482  * Inputs are required to range within a page.
3483  */
3484 vm_page_bits_t
3485 vm_page_bits(int base, int size)
3486 {
3487 	int first_bit;
3488 	int last_bit;
3489 
3490 	KASSERT(
3491 	    base + size <= PAGE_SIZE,
3492 	    ("vm_page_bits: illegal base/size %d/%d", base, size)
3493 	);
3494 
3495 	if (size == 0)		/* handle degenerate case */
3496 		return (0);
3497 
3498 	first_bit = base >> DEV_BSHIFT;
3499 	last_bit = (base + size - 1) >> DEV_BSHIFT;
3500 
3501 	return (((vm_page_bits_t)2 << last_bit) -
3502 	    ((vm_page_bits_t)1 << first_bit));
3503 }
3504 
3505 /*
3506  *	vm_page_set_valid_range:
3507  *
3508  *	Sets portions of a page valid.  The arguments are expected
3509  *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3510  *	of any partial chunks touched by the range.  The invalid portion of
3511  *	such chunks will be zeroed.
3512  *
3513  *	(base + size) must be less then or equal to PAGE_SIZE.
3514  */
3515 void
3516 vm_page_set_valid_range(vm_page_t m, int base, int size)
3517 {
3518 	int endoff, frag;
3519 
3520 	VM_OBJECT_ASSERT_WLOCKED(m->object);
3521 	if (size == 0)	/* handle degenerate case */
3522 		return;
3523 
3524 	/*
3525 	 * If the base is not DEV_BSIZE aligned and the valid
3526 	 * bit is clear, we have to zero out a portion of the
3527 	 * first block.
3528 	 */
3529 	if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3530 	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
3531 		pmap_zero_page_area(m, frag, base - frag);
3532 
3533 	/*
3534 	 * If the ending offset is not DEV_BSIZE aligned and the
3535 	 * valid bit is clear, we have to zero out a portion of
3536 	 * the last block.
3537 	 */
3538 	endoff = base + size;
3539 	if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3540 	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
3541 		pmap_zero_page_area(m, endoff,
3542 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3543 
3544 	/*
3545 	 * Assert that no previously invalid block that is now being validated
3546 	 * is already dirty.
3547 	 */
3548 	KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
3549 	    ("vm_page_set_valid_range: page %p is dirty", m));
3550 
3551 	/*
3552 	 * Set valid bits inclusive of any overlap.
3553 	 */
3554 	m->valid |= vm_page_bits(base, size);
3555 }
3556 
3557 /*
3558  * Clear the given bits from the specified page's dirty field.
3559  */
3560 static __inline void
3561 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
3562 {
3563 	uintptr_t addr;
3564 #if PAGE_SIZE < 16384
3565 	int shift;
3566 #endif
3567 
3568 	/*
3569 	 * If the object is locked and the page is neither exclusive busy nor
3570 	 * write mapped, then the page's dirty field cannot possibly be
3571 	 * set by a concurrent pmap operation.
3572 	 */
3573 	VM_OBJECT_ASSERT_WLOCKED(m->object);
3574 	if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
3575 		m->dirty &= ~pagebits;
3576 	else {
3577 		/*
3578 		 * The pmap layer can call vm_page_dirty() without
3579 		 * holding a distinguished lock.  The combination of
3580 		 * the object's lock and an atomic operation suffice
3581 		 * to guarantee consistency of the page dirty field.
3582 		 *
3583 		 * For PAGE_SIZE == 32768 case, compiler already
3584 		 * properly aligns the dirty field, so no forcible
3585 		 * alignment is needed. Only require existence of
3586 		 * atomic_clear_64 when page size is 32768.
3587 		 */
3588 		addr = (uintptr_t)&m->dirty;
3589 #if PAGE_SIZE == 32768
3590 		atomic_clear_64((uint64_t *)addr, pagebits);
3591 #elif PAGE_SIZE == 16384
3592 		atomic_clear_32((uint32_t *)addr, pagebits);
3593 #else		/* PAGE_SIZE <= 8192 */
3594 		/*
3595 		 * Use a trick to perform a 32-bit atomic on the
3596 		 * containing aligned word, to not depend on the existence
3597 		 * of atomic_clear_{8, 16}.
3598 		 */
3599 		shift = addr & (sizeof(uint32_t) - 1);
3600 #if BYTE_ORDER == BIG_ENDIAN
3601 		shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
3602 #else
3603 		shift *= NBBY;
3604 #endif
3605 		addr &= ~(sizeof(uint32_t) - 1);
3606 		atomic_clear_32((uint32_t *)addr, pagebits << shift);
3607 #endif		/* PAGE_SIZE */
3608 	}
3609 }
3610 
3611 /*
3612  *	vm_page_set_validclean:
3613  *
3614  *	Sets portions of a page valid and clean.  The arguments are expected
3615  *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3616  *	of any partial chunks touched by the range.  The invalid portion of
3617  *	such chunks will be zero'd.
3618  *
3619  *	(base + size) must be less then or equal to PAGE_SIZE.
3620  */
3621 void
3622 vm_page_set_validclean(vm_page_t m, int base, int size)
3623 {
3624 	vm_page_bits_t oldvalid, pagebits;
3625 	int endoff, frag;
3626 
3627 	VM_OBJECT_ASSERT_WLOCKED(m->object);
3628 	if (size == 0)	/* handle degenerate case */
3629 		return;
3630 
3631 	/*
3632 	 * If the base is not DEV_BSIZE aligned and the valid
3633 	 * bit is clear, we have to zero out a portion of the
3634 	 * first block.
3635 	 */
3636 	if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3637 	    (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
3638 		pmap_zero_page_area(m, frag, base - frag);
3639 
3640 	/*
3641 	 * If the ending offset is not DEV_BSIZE aligned and the
3642 	 * valid bit is clear, we have to zero out a portion of
3643 	 * the last block.
3644 	 */
3645 	endoff = base + size;
3646 	if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3647 	    (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
3648 		pmap_zero_page_area(m, endoff,
3649 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3650 
3651 	/*
3652 	 * Set valid, clear dirty bits.  If validating the entire
3653 	 * page we can safely clear the pmap modify bit.  We also
3654 	 * use this opportunity to clear the VPO_NOSYNC flag.  If a process
3655 	 * takes a write fault on a MAP_NOSYNC memory area the flag will
3656 	 * be set again.
3657 	 *
3658 	 * We set valid bits inclusive of any overlap, but we can only
3659 	 * clear dirty bits for DEV_BSIZE chunks that are fully within
3660 	 * the range.
3661 	 */
3662 	oldvalid = m->valid;
3663 	pagebits = vm_page_bits(base, size);
3664 	m->valid |= pagebits;
3665 #if 0	/* NOT YET */
3666 	if ((frag = base & (DEV_BSIZE - 1)) != 0) {
3667 		frag = DEV_BSIZE - frag;
3668 		base += frag;
3669 		size -= frag;
3670 		if (size < 0)
3671 			size = 0;
3672 	}
3673 	pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
3674 #endif
3675 	if (base == 0 && size == PAGE_SIZE) {
3676 		/*
3677 		 * The page can only be modified within the pmap if it is
3678 		 * mapped, and it can only be mapped if it was previously
3679 		 * fully valid.
3680 		 */
3681 		if (oldvalid == VM_PAGE_BITS_ALL)
3682 			/*
3683 			 * Perform the pmap_clear_modify() first.  Otherwise,
3684 			 * a concurrent pmap operation, such as
3685 			 * pmap_protect(), could clear a modification in the
3686 			 * pmap and set the dirty field on the page before
3687 			 * pmap_clear_modify() had begun and after the dirty
3688 			 * field was cleared here.
3689 			 */
3690 			pmap_clear_modify(m);
3691 		m->dirty = 0;
3692 		m->oflags &= ~VPO_NOSYNC;
3693 	} else if (oldvalid != VM_PAGE_BITS_ALL)
3694 		m->dirty &= ~pagebits;
3695 	else
3696 		vm_page_clear_dirty_mask(m, pagebits);
3697 }
3698 
3699 void
3700 vm_page_clear_dirty(vm_page_t m, int base, int size)
3701 {
3702 
3703 	vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
3704 }
3705 
3706 /*
3707  *	vm_page_set_invalid:
3708  *
3709  *	Invalidates DEV_BSIZE'd chunks within a page.  Both the
3710  *	valid and dirty bits for the effected areas are cleared.
3711  */
3712 void
3713 vm_page_set_invalid(vm_page_t m, int base, int size)
3714 {
3715 	vm_page_bits_t bits;
3716 	vm_object_t object;
3717 
3718 	object = m->object;
3719 	VM_OBJECT_ASSERT_WLOCKED(object);
3720 	if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
3721 	    size >= object->un_pager.vnp.vnp_size)
3722 		bits = VM_PAGE_BITS_ALL;
3723 	else
3724 		bits = vm_page_bits(base, size);
3725 	if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
3726 	    bits != 0)
3727 		pmap_remove_all(m);
3728 	KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3729 	    !pmap_page_is_mapped(m),
3730 	    ("vm_page_set_invalid: page %p is mapped", m));
3731 	m->valid &= ~bits;
3732 	m->dirty &= ~bits;
3733 }
3734 
3735 /*
3736  * vm_page_zero_invalid()
3737  *
3738  *	The kernel assumes that the invalid portions of a page contain
3739  *	garbage, but such pages can be mapped into memory by user code.
3740  *	When this occurs, we must zero out the non-valid portions of the
3741  *	page so user code sees what it expects.
3742  *
3743  *	Pages are most often semi-valid when the end of a file is mapped
3744  *	into memory and the file's size is not page aligned.
3745  */
3746 void
3747 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3748 {
3749 	int b;
3750 	int i;
3751 
3752 	VM_OBJECT_ASSERT_WLOCKED(m->object);
3753 	/*
3754 	 * Scan the valid bits looking for invalid sections that
3755 	 * must be zeroed.  Invalid sub-DEV_BSIZE'd areas ( where the
3756 	 * valid bit may be set ) have already been zeroed by
3757 	 * vm_page_set_validclean().
3758 	 */
3759 	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3760 		if (i == (PAGE_SIZE / DEV_BSIZE) ||
3761 		    (m->valid & ((vm_page_bits_t)1 << i))) {
3762 			if (i > b) {
3763 				pmap_zero_page_area(m,
3764 				    b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3765 			}
3766 			b = i + 1;
3767 		}
3768 	}
3769 
3770 	/*
3771 	 * setvalid is TRUE when we can safely set the zero'd areas
3772 	 * as being valid.  We can do this if there are no cache consistancy
3773 	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
3774 	 */
3775 	if (setvalid)
3776 		m->valid = VM_PAGE_BITS_ALL;
3777 }
3778 
3779 /*
3780  *	vm_page_is_valid:
3781  *
3782  *	Is (partial) page valid?  Note that the case where size == 0
3783  *	will return FALSE in the degenerate case where the page is
3784  *	entirely invalid, and TRUE otherwise.
3785  */
3786 int
3787 vm_page_is_valid(vm_page_t m, int base, int size)
3788 {
3789 	vm_page_bits_t bits;
3790 
3791 	VM_OBJECT_ASSERT_LOCKED(m->object);
3792 	bits = vm_page_bits(base, size);
3793 	return (m->valid != 0 && (m->valid & bits) == bits);
3794 }
3795 
3796 /*
3797  *	vm_page_ps_is_valid:
3798  *
3799  *	Returns TRUE if the entire (super)page is valid and FALSE otherwise.
3800  */
3801 boolean_t
3802 vm_page_ps_is_valid(vm_page_t m)
3803 {
3804 	int i, npages;
3805 
3806 	VM_OBJECT_ASSERT_LOCKED(m->object);
3807 	npages = atop(pagesizes[m->psind]);
3808 
3809 	/*
3810 	 * The physically contiguous pages that make up a superpage, i.e., a
3811 	 * page with a page size index ("psind") greater than zero, will
3812 	 * occupy adjacent entries in vm_page_array[].
3813 	 */
3814 	for (i = 0; i < npages; i++) {
3815 		if (m[i].valid != VM_PAGE_BITS_ALL)
3816 			return (FALSE);
3817 	}
3818 	return (TRUE);
3819 }
3820 
3821 /*
3822  * Set the page's dirty bits if the page is modified.
3823  */
3824 void
3825 vm_page_test_dirty(vm_page_t m)
3826 {
3827 
3828 	VM_OBJECT_ASSERT_WLOCKED(m->object);
3829 	if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3830 		vm_page_dirty(m);
3831 }
3832 
3833 void
3834 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3835 {
3836 
3837 	mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3838 }
3839 
3840 void
3841 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3842 {
3843 
3844 	mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3845 }
3846 
3847 int
3848 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3849 {
3850 
3851 	return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3852 }
3853 
3854 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3855 void
3856 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3857 {
3858 
3859 	vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3860 }
3861 
3862 void
3863 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3864 {
3865 
3866 	mtx_assert_(vm_page_lockptr(m), a, file, line);
3867 }
3868 #endif
3869 
3870 #ifdef INVARIANTS
3871 void
3872 vm_page_object_lock_assert(vm_page_t m)
3873 {
3874 
3875 	/*
3876 	 * Certain of the page's fields may only be modified by the
3877 	 * holder of the containing object's lock or the exclusive busy.
3878 	 * holder.  Unfortunately, the holder of the write busy is
3879 	 * not recorded, and thus cannot be checked here.
3880 	 */
3881 	if (m->object != NULL && !vm_page_xbusied(m))
3882 		VM_OBJECT_ASSERT_WLOCKED(m->object);
3883 }
3884 
3885 void
3886 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3887 {
3888 
3889 	if ((bits & PGA_WRITEABLE) == 0)
3890 		return;
3891 
3892 	/*
3893 	 * The PGA_WRITEABLE flag can only be set if the page is
3894 	 * managed, is exclusively busied or the object is locked.
3895 	 * Currently, this flag is only set by pmap_enter().
3896 	 */
3897 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3898 	    ("PGA_WRITEABLE on unmanaged page"));
3899 	if (!vm_page_xbusied(m))
3900 		VM_OBJECT_ASSERT_LOCKED(m->object);
3901 }
3902 #endif
3903 
3904 #include "opt_ddb.h"
3905 #ifdef DDB
3906 #include <sys/kernel.h>
3907 
3908 #include <ddb/ddb.h>
3909 
3910 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3911 {
3912 	db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
3913 	db_printf("vm_cnt.v_cache_count: %d\n", vm_cnt.v_cache_count);
3914 	db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
3915 	db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
3916 	db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
3917 	db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
3918 	db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
3919 	db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
3920 	db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
3921 }
3922 
3923 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3924 {
3925 	int dom;
3926 
3927 	db_printf("pq_free %d pq_cache %d\n",
3928 	    vm_cnt.v_free_count, vm_cnt.v_cache_count);
3929 	for (dom = 0; dom < vm_ndomains; dom++) {
3930 		db_printf("dom %d page_cnt %d free %d pq_act %d pq_inact %d\n",
3931 		    dom,
3932 		    vm_dom[dom].vmd_page_count,
3933 		    vm_dom[dom].vmd_free_count,
3934 		    vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3935 		    vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt);
3936 	}
3937 }
3938 
3939 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3940 {
3941 	vm_page_t m;
3942 	boolean_t phys;
3943 
3944 	if (!have_addr) {
3945 		db_printf("show pginfo addr\n");
3946 		return;
3947 	}
3948 
3949 	phys = strchr(modif, 'p') != NULL;
3950 	if (phys)
3951 		m = PHYS_TO_VM_PAGE(addr);
3952 	else
3953 		m = (vm_page_t)addr;
3954 	db_printf(
3955     "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3956     "  af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3957 	    m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3958 	    m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3959 	    m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);
3960 }
3961 #endif /* DDB */
3962