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