xref: /freebsd/sys/vm/vm_page.c (revision 02e9120893770924227138ba49df1edb3896112a)
1 /*-
2  * SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)
3  *
4  * Copyright (c) 1991 Regents of the University of California.
5  * All rights reserved.
6  * Copyright (c) 1998 Matthew Dillon.  All Rights Reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * The Mach Operating System project at Carnegie-Mellon University.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
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  *	Resident memory management module.
65  */
66 
67 #include <sys/cdefs.h>
68 #include "opt_vm.h"
69 
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/counter.h>
73 #include <sys/domainset.h>
74 #include <sys/kernel.h>
75 #include <sys/limits.h>
76 #include <sys/linker.h>
77 #include <sys/lock.h>
78 #include <sys/malloc.h>
79 #include <sys/mman.h>
80 #include <sys/msgbuf.h>
81 #include <sys/mutex.h>
82 #include <sys/proc.h>
83 #include <sys/rwlock.h>
84 #include <sys/sleepqueue.h>
85 #include <sys/sbuf.h>
86 #include <sys/sched.h>
87 #include <sys/smp.h>
88 #include <sys/sysctl.h>
89 #include <sys/vmmeter.h>
90 #include <sys/vnode.h>
91 
92 #include <vm/vm.h>
93 #include <vm/pmap.h>
94 #include <vm/vm_param.h>
95 #include <vm/vm_domainset.h>
96 #include <vm/vm_kern.h>
97 #include <vm/vm_map.h>
98 #include <vm/vm_object.h>
99 #include <vm/vm_page.h>
100 #include <vm/vm_pageout.h>
101 #include <vm/vm_phys.h>
102 #include <vm/vm_pagequeue.h>
103 #include <vm/vm_pager.h>
104 #include <vm/vm_radix.h>
105 #include <vm/vm_reserv.h>
106 #include <vm/vm_extern.h>
107 #include <vm/vm_dumpset.h>
108 #include <vm/uma.h>
109 #include <vm/uma_int.h>
110 
111 #include <machine/md_var.h>
112 
113 struct vm_domain vm_dom[MAXMEMDOM];
114 
115 DPCPU_DEFINE_STATIC(struct vm_batchqueue, pqbatch[MAXMEMDOM][PQ_COUNT]);
116 
117 struct mtx_padalign __exclusive_cache_line pa_lock[PA_LOCK_COUNT];
118 
119 struct mtx_padalign __exclusive_cache_line vm_domainset_lock;
120 /* The following fields are protected by the domainset lock. */
121 domainset_t __exclusive_cache_line vm_min_domains;
122 domainset_t __exclusive_cache_line vm_severe_domains;
123 static int vm_min_waiters;
124 static int vm_severe_waiters;
125 static int vm_pageproc_waiters;
126 
127 static SYSCTL_NODE(_vm_stats, OID_AUTO, page, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
128     "VM page statistics");
129 
130 static COUNTER_U64_DEFINE_EARLY(pqstate_commit_retries);
131 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, pqstate_commit_retries,
132     CTLFLAG_RD, &pqstate_commit_retries,
133     "Number of failed per-page atomic queue state updates");
134 
135 static COUNTER_U64_DEFINE_EARLY(queue_ops);
136 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, queue_ops,
137     CTLFLAG_RD, &queue_ops,
138     "Number of batched queue operations");
139 
140 static COUNTER_U64_DEFINE_EARLY(queue_nops);
141 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, queue_nops,
142     CTLFLAG_RD, &queue_nops,
143     "Number of batched queue operations with no effects");
144 
145 /*
146  * bogus page -- for I/O to/from partially complete buffers,
147  * or for paging into sparsely invalid regions.
148  */
149 vm_page_t bogus_page;
150 
151 vm_page_t vm_page_array;
152 long vm_page_array_size;
153 long first_page;
154 
155 struct bitset *vm_page_dump;
156 long vm_page_dump_pages;
157 
158 static TAILQ_HEAD(, vm_page) blacklist_head;
159 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
160 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
161     CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
162 
163 static uma_zone_t fakepg_zone;
164 
165 static void vm_page_alloc_check(vm_page_t m);
166 static bool _vm_page_busy_sleep(vm_object_t obj, vm_page_t m,
167     vm_pindex_t pindex, const char *wmesg, int allocflags, bool locked);
168 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
169 static void vm_page_enqueue(vm_page_t m, uint8_t queue);
170 static bool vm_page_free_prep(vm_page_t m);
171 static void vm_page_free_toq(vm_page_t m);
172 static void vm_page_init(void *dummy);
173 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
174     vm_pindex_t pindex, vm_page_t mpred);
175 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
176     vm_page_t mpred);
177 static void vm_page_mvqueue(vm_page_t m, const uint8_t queue,
178     const uint16_t nflag);
179 static int vm_page_reclaim_run(int req_class, int domain, u_long npages,
180     vm_page_t m_run, vm_paddr_t high);
181 static void vm_page_release_toq(vm_page_t m, uint8_t nqueue, bool noreuse);
182 static int vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object,
183     int req);
184 static int vm_page_zone_import(void *arg, void **store, int cnt, int domain,
185     int flags);
186 static void vm_page_zone_release(void *arg, void **store, int cnt);
187 
188 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
189 
190 static void
191 vm_page_init(void *dummy)
192 {
193 
194 	fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
195 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
196 	bogus_page = vm_page_alloc_noobj(VM_ALLOC_WIRED);
197 }
198 
199 static int pgcache_zone_max_pcpu;
200 SYSCTL_INT(_vm, OID_AUTO, pgcache_zone_max_pcpu,
201     CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pgcache_zone_max_pcpu, 0,
202     "Per-CPU page cache size");
203 
204 /*
205  * The cache page zone is initialized later since we need to be able to allocate
206  * pages before UMA is fully initialized.
207  */
208 static void
209 vm_page_init_cache_zones(void *dummy __unused)
210 {
211 	struct vm_domain *vmd;
212 	struct vm_pgcache *pgcache;
213 	int cache, domain, maxcache, pool;
214 
215 	TUNABLE_INT_FETCH("vm.pgcache_zone_max_pcpu", &pgcache_zone_max_pcpu);
216 	maxcache = pgcache_zone_max_pcpu * mp_ncpus;
217 	for (domain = 0; domain < vm_ndomains; domain++) {
218 		vmd = VM_DOMAIN(domain);
219 		for (pool = 0; pool < VM_NFREEPOOL; pool++) {
220 			pgcache = &vmd->vmd_pgcache[pool];
221 			pgcache->domain = domain;
222 			pgcache->pool = pool;
223 			pgcache->zone = uma_zcache_create("vm pgcache",
224 			    PAGE_SIZE, NULL, NULL, NULL, NULL,
225 			    vm_page_zone_import, vm_page_zone_release, pgcache,
226 			    UMA_ZONE_VM);
227 
228 			/*
229 			 * Limit each pool's zone to 0.1% of the pages in the
230 			 * domain.
231 			 */
232 			cache = maxcache != 0 ? maxcache :
233 			    vmd->vmd_page_count / 1000;
234 			uma_zone_set_maxcache(pgcache->zone, cache);
235 		}
236 	}
237 }
238 SYSINIT(vm_page2, SI_SUB_VM_CONF, SI_ORDER_ANY, vm_page_init_cache_zones, NULL);
239 
240 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
241 #if PAGE_SIZE == 32768
242 #ifdef CTASSERT
243 CTASSERT(sizeof(u_long) >= 8);
244 #endif
245 #endif
246 
247 /*
248  *	vm_set_page_size:
249  *
250  *	Sets the page size, perhaps based upon the memory
251  *	size.  Must be called before any use of page-size
252  *	dependent functions.
253  */
254 void
255 vm_set_page_size(void)
256 {
257 	if (vm_cnt.v_page_size == 0)
258 		vm_cnt.v_page_size = PAGE_SIZE;
259 	if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
260 		panic("vm_set_page_size: page size not a power of two");
261 }
262 
263 /*
264  *	vm_page_blacklist_next:
265  *
266  *	Find the next entry in the provided string of blacklist
267  *	addresses.  Entries are separated by space, comma, or newline.
268  *	If an invalid integer is encountered then the rest of the
269  *	string is skipped.  Updates the list pointer to the next
270  *	character, or NULL if the string is exhausted or invalid.
271  */
272 static vm_paddr_t
273 vm_page_blacklist_next(char **list, char *end)
274 {
275 	vm_paddr_t bad;
276 	char *cp, *pos;
277 
278 	if (list == NULL || *list == NULL)
279 		return (0);
280 	if (**list =='\0') {
281 		*list = NULL;
282 		return (0);
283 	}
284 
285 	/*
286 	 * If there's no end pointer then the buffer is coming from
287 	 * the kenv and we know it's null-terminated.
288 	 */
289 	if (end == NULL)
290 		end = *list + strlen(*list);
291 
292 	/* Ensure that strtoq() won't walk off the end */
293 	if (*end != '\0') {
294 		if (*end == '\n' || *end == ' ' || *end  == ',')
295 			*end = '\0';
296 		else {
297 			printf("Blacklist not terminated, skipping\n");
298 			*list = NULL;
299 			return (0);
300 		}
301 	}
302 
303 	for (pos = *list; *pos != '\0'; pos = cp) {
304 		bad = strtoq(pos, &cp, 0);
305 		if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
306 			if (bad == 0) {
307 				if (++cp < end)
308 					continue;
309 				else
310 					break;
311 			}
312 		} else
313 			break;
314 		if (*cp == '\0' || ++cp >= end)
315 			*list = NULL;
316 		else
317 			*list = cp;
318 		return (trunc_page(bad));
319 	}
320 	printf("Garbage in RAM blacklist, skipping\n");
321 	*list = NULL;
322 	return (0);
323 }
324 
325 bool
326 vm_page_blacklist_add(vm_paddr_t pa, bool verbose)
327 {
328 	struct vm_domain *vmd;
329 	vm_page_t m;
330 	bool found;
331 
332 	m = vm_phys_paddr_to_vm_page(pa);
333 	if (m == NULL)
334 		return (true); /* page does not exist, no failure */
335 
336 	vmd = vm_pagequeue_domain(m);
337 	vm_domain_free_lock(vmd);
338 	found = vm_phys_unfree_page(m);
339 	vm_domain_free_unlock(vmd);
340 	if (found) {
341 		vm_domain_freecnt_inc(vmd, -1);
342 		TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
343 		if (verbose)
344 			printf("Skipping page with pa 0x%jx\n", (uintmax_t)pa);
345 	}
346 	return (found);
347 }
348 
349 /*
350  *	vm_page_blacklist_check:
351  *
352  *	Iterate through the provided string of blacklist addresses, pulling
353  *	each entry out of the physical allocator free list and putting it
354  *	onto a list for reporting via the vm.page_blacklist sysctl.
355  */
356 static void
357 vm_page_blacklist_check(char *list, char *end)
358 {
359 	vm_paddr_t pa;
360 	char *next;
361 
362 	next = list;
363 	while (next != NULL) {
364 		if ((pa = vm_page_blacklist_next(&next, end)) == 0)
365 			continue;
366 		vm_page_blacklist_add(pa, bootverbose);
367 	}
368 }
369 
370 /*
371  *	vm_page_blacklist_load:
372  *
373  *	Search for a special module named "ram_blacklist".  It'll be a
374  *	plain text file provided by the user via the loader directive
375  *	of the same name.
376  */
377 static void
378 vm_page_blacklist_load(char **list, char **end)
379 {
380 	void *mod;
381 	u_char *ptr;
382 	u_int len;
383 
384 	mod = NULL;
385 	ptr = NULL;
386 
387 	mod = preload_search_by_type("ram_blacklist");
388 	if (mod != NULL) {
389 		ptr = preload_fetch_addr(mod);
390 		len = preload_fetch_size(mod);
391         }
392 	*list = ptr;
393 	if (ptr != NULL)
394 		*end = ptr + len;
395 	else
396 		*end = NULL;
397 	return;
398 }
399 
400 static int
401 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
402 {
403 	vm_page_t m;
404 	struct sbuf sbuf;
405 	int error, first;
406 
407 	first = 1;
408 	error = sysctl_wire_old_buffer(req, 0);
409 	if (error != 0)
410 		return (error);
411 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
412 	TAILQ_FOREACH(m, &blacklist_head, listq) {
413 		sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
414 		    (uintmax_t)m->phys_addr);
415 		first = 0;
416 	}
417 	error = sbuf_finish(&sbuf);
418 	sbuf_delete(&sbuf);
419 	return (error);
420 }
421 
422 /*
423  * Initialize a dummy page for use in scans of the specified paging queue.
424  * In principle, this function only needs to set the flag PG_MARKER.
425  * Nonetheless, it write busies the page as a safety precaution.
426  */
427 void
428 vm_page_init_marker(vm_page_t marker, int queue, uint16_t aflags)
429 {
430 
431 	bzero(marker, sizeof(*marker));
432 	marker->flags = PG_MARKER;
433 	marker->a.flags = aflags;
434 	marker->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
435 	marker->a.queue = queue;
436 }
437 
438 static void
439 vm_page_domain_init(int domain)
440 {
441 	struct vm_domain *vmd;
442 	struct vm_pagequeue *pq;
443 	int i;
444 
445 	vmd = VM_DOMAIN(domain);
446 	bzero(vmd, sizeof(*vmd));
447 	*__DECONST(const char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
448 	    "vm inactive pagequeue";
449 	*__DECONST(const char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
450 	    "vm active pagequeue";
451 	*__DECONST(const char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
452 	    "vm laundry pagequeue";
453 	*__DECONST(const char **,
454 	    &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_name) =
455 	    "vm unswappable pagequeue";
456 	vmd->vmd_domain = domain;
457 	vmd->vmd_page_count = 0;
458 	vmd->vmd_free_count = 0;
459 	vmd->vmd_segs = 0;
460 	vmd->vmd_oom = FALSE;
461 	for (i = 0; i < PQ_COUNT; i++) {
462 		pq = &vmd->vmd_pagequeues[i];
463 		TAILQ_INIT(&pq->pq_pl);
464 		mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
465 		    MTX_DEF | MTX_DUPOK);
466 		pq->pq_pdpages = 0;
467 		vm_page_init_marker(&vmd->vmd_markers[i], i, 0);
468 	}
469 	mtx_init(&vmd->vmd_free_mtx, "vm page free queue", NULL, MTX_DEF);
470 	mtx_init(&vmd->vmd_pageout_mtx, "vm pageout lock", NULL, MTX_DEF);
471 	snprintf(vmd->vmd_name, sizeof(vmd->vmd_name), "%d", domain);
472 
473 	/*
474 	 * inacthead is used to provide FIFO ordering for LRU-bypassing
475 	 * insertions.
476 	 */
477 	vm_page_init_marker(&vmd->vmd_inacthead, PQ_INACTIVE, PGA_ENQUEUED);
478 	TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_INACTIVE].pq_pl,
479 	    &vmd->vmd_inacthead, plinks.q);
480 
481 	/*
482 	 * The clock pages are used to implement active queue scanning without
483 	 * requeues.  Scans start at clock[0], which is advanced after the scan
484 	 * ends.  When the two clock hands meet, they are reset and scanning
485 	 * resumes from the head of the queue.
486 	 */
487 	vm_page_init_marker(&vmd->vmd_clock[0], PQ_ACTIVE, PGA_ENQUEUED);
488 	vm_page_init_marker(&vmd->vmd_clock[1], PQ_ACTIVE, PGA_ENQUEUED);
489 	TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
490 	    &vmd->vmd_clock[0], plinks.q);
491 	TAILQ_INSERT_TAIL(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
492 	    &vmd->vmd_clock[1], plinks.q);
493 }
494 
495 /*
496  * Initialize a physical page in preparation for adding it to the free
497  * lists.
498  */
499 void
500 vm_page_init_page(vm_page_t m, vm_paddr_t pa, int segind)
501 {
502 
503 	m->object = NULL;
504 	m->ref_count = 0;
505 	m->busy_lock = VPB_FREED;
506 	m->flags = m->a.flags = 0;
507 	m->phys_addr = pa;
508 	m->a.queue = PQ_NONE;
509 	m->psind = 0;
510 	m->segind = segind;
511 	m->order = VM_NFREEORDER;
512 	m->pool = VM_FREEPOOL_DEFAULT;
513 	m->valid = m->dirty = 0;
514 	pmap_page_init(m);
515 }
516 
517 #ifndef PMAP_HAS_PAGE_ARRAY
518 static vm_paddr_t
519 vm_page_array_alloc(vm_offset_t *vaddr, vm_paddr_t end, vm_paddr_t page_range)
520 {
521 	vm_paddr_t new_end;
522 
523 	/*
524 	 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
525 	 * However, because this page is allocated from KVM, out-of-bounds
526 	 * accesses using the direct map will not be trapped.
527 	 */
528 	*vaddr += PAGE_SIZE;
529 
530 	/*
531 	 * Allocate physical memory for the page structures, and map it.
532 	 */
533 	new_end = trunc_page(end - page_range * sizeof(struct vm_page));
534 	vm_page_array = (vm_page_t)pmap_map(vaddr, new_end, end,
535 	    VM_PROT_READ | VM_PROT_WRITE);
536 	vm_page_array_size = page_range;
537 
538 	return (new_end);
539 }
540 #endif
541 
542 /*
543  *	vm_page_startup:
544  *
545  *	Initializes the resident memory module.  Allocates physical memory for
546  *	bootstrapping UMA and some data structures that are used to manage
547  *	physical pages.  Initializes these structures, and populates the free
548  *	page queues.
549  */
550 vm_offset_t
551 vm_page_startup(vm_offset_t vaddr)
552 {
553 	struct vm_phys_seg *seg;
554 	struct vm_domain *vmd;
555 	vm_page_t m;
556 	char *list, *listend;
557 	vm_paddr_t end, high_avail, low_avail, new_end, size;
558 	vm_paddr_t page_range __unused;
559 	vm_paddr_t last_pa, pa, startp, endp;
560 	u_long pagecount;
561 #if MINIDUMP_PAGE_TRACKING
562 	u_long vm_page_dump_size;
563 #endif
564 	int biggestone, i, segind;
565 #ifdef WITNESS
566 	vm_offset_t mapped;
567 	int witness_size;
568 #endif
569 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
570 	long ii;
571 #endif
572 
573 	vaddr = round_page(vaddr);
574 
575 	vm_phys_early_startup();
576 	biggestone = vm_phys_avail_largest();
577 	end = phys_avail[biggestone+1];
578 
579 	/*
580 	 * Initialize the page and queue locks.
581 	 */
582 	mtx_init(&vm_domainset_lock, "vm domainset lock", NULL, MTX_DEF);
583 	for (i = 0; i < PA_LOCK_COUNT; i++)
584 		mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
585 	for (i = 0; i < vm_ndomains; i++)
586 		vm_page_domain_init(i);
587 
588 	new_end = end;
589 #ifdef WITNESS
590 	witness_size = round_page(witness_startup_count());
591 	new_end -= witness_size;
592 	mapped = pmap_map(&vaddr, new_end, new_end + witness_size,
593 	    VM_PROT_READ | VM_PROT_WRITE);
594 	bzero((void *)mapped, witness_size);
595 	witness_startup((void *)mapped);
596 #endif
597 
598 #if MINIDUMP_PAGE_TRACKING
599 	/*
600 	 * Allocate a bitmap to indicate that a random physical page
601 	 * needs to be included in a minidump.
602 	 *
603 	 * The amd64 port needs this to indicate which direct map pages
604 	 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
605 	 *
606 	 * However, i386 still needs this workspace internally within the
607 	 * minidump code.  In theory, they are not needed on i386, but are
608 	 * included should the sf_buf code decide to use them.
609 	 */
610 	last_pa = 0;
611 	vm_page_dump_pages = 0;
612 	for (i = 0; dump_avail[i + 1] != 0; i += 2) {
613 		vm_page_dump_pages += howmany(dump_avail[i + 1], PAGE_SIZE) -
614 		    dump_avail[i] / PAGE_SIZE;
615 		if (dump_avail[i + 1] > last_pa)
616 			last_pa = dump_avail[i + 1];
617 	}
618 	vm_page_dump_size = round_page(BITSET_SIZE(vm_page_dump_pages));
619 	new_end -= vm_page_dump_size;
620 	vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
621 	    new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
622 	bzero((void *)vm_page_dump, vm_page_dump_size);
623 #else
624 	(void)last_pa;
625 #endif
626 #if defined(__aarch64__) || defined(__amd64__) || \
627     defined(__riscv) || defined(__powerpc64__)
628 	/*
629 	 * Include the UMA bootstrap pages, witness pages and vm_page_dump
630 	 * in a crash dump.  When pmap_map() uses the direct map, they are
631 	 * not automatically included.
632 	 */
633 	for (pa = new_end; pa < end; pa += PAGE_SIZE)
634 		dump_add_page(pa);
635 #endif
636 	phys_avail[biggestone + 1] = new_end;
637 #ifdef __amd64__
638 	/*
639 	 * Request that the physical pages underlying the message buffer be
640 	 * included in a crash dump.  Since the message buffer is accessed
641 	 * through the direct map, they are not automatically included.
642 	 */
643 	pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
644 	last_pa = pa + round_page(msgbufsize);
645 	while (pa < last_pa) {
646 		dump_add_page(pa);
647 		pa += PAGE_SIZE;
648 	}
649 #endif
650 	/*
651 	 * Compute the number of pages of memory that will be available for
652 	 * use, taking into account the overhead of a page structure per page.
653 	 * In other words, solve
654 	 *	"available physical memory" - round_page(page_range *
655 	 *	    sizeof(struct vm_page)) = page_range * PAGE_SIZE
656 	 * for page_range.
657 	 */
658 	low_avail = phys_avail[0];
659 	high_avail = phys_avail[1];
660 	for (i = 0; i < vm_phys_nsegs; i++) {
661 		if (vm_phys_segs[i].start < low_avail)
662 			low_avail = vm_phys_segs[i].start;
663 		if (vm_phys_segs[i].end > high_avail)
664 			high_avail = vm_phys_segs[i].end;
665 	}
666 	/* Skip the first chunk.  It is already accounted for. */
667 	for (i = 2; phys_avail[i + 1] != 0; i += 2) {
668 		if (phys_avail[i] < low_avail)
669 			low_avail = phys_avail[i];
670 		if (phys_avail[i + 1] > high_avail)
671 			high_avail = phys_avail[i + 1];
672 	}
673 	first_page = low_avail / PAGE_SIZE;
674 #ifdef VM_PHYSSEG_SPARSE
675 	size = 0;
676 	for (i = 0; i < vm_phys_nsegs; i++)
677 		size += vm_phys_segs[i].end - vm_phys_segs[i].start;
678 	for (i = 0; phys_avail[i + 1] != 0; i += 2)
679 		size += phys_avail[i + 1] - phys_avail[i];
680 #elif defined(VM_PHYSSEG_DENSE)
681 	size = high_avail - low_avail;
682 #else
683 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
684 #endif
685 
686 #ifdef PMAP_HAS_PAGE_ARRAY
687 	pmap_page_array_startup(size / PAGE_SIZE);
688 	biggestone = vm_phys_avail_largest();
689 	end = new_end = phys_avail[biggestone + 1];
690 #else
691 #ifdef VM_PHYSSEG_DENSE
692 	/*
693 	 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
694 	 * the overhead of a page structure per page only if vm_page_array is
695 	 * allocated from the last physical memory chunk.  Otherwise, we must
696 	 * allocate page structures representing the physical memory
697 	 * underlying vm_page_array, even though they will not be used.
698 	 */
699 	if (new_end != high_avail)
700 		page_range = size / PAGE_SIZE;
701 	else
702 #endif
703 	{
704 		page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
705 
706 		/*
707 		 * If the partial bytes remaining are large enough for
708 		 * a page (PAGE_SIZE) without a corresponding
709 		 * 'struct vm_page', then new_end will contain an
710 		 * extra page after subtracting the length of the VM
711 		 * page array.  Compensate by subtracting an extra
712 		 * page from new_end.
713 		 */
714 		if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
715 			if (new_end == high_avail)
716 				high_avail -= PAGE_SIZE;
717 			new_end -= PAGE_SIZE;
718 		}
719 	}
720 	end = new_end;
721 	new_end = vm_page_array_alloc(&vaddr, end, page_range);
722 #endif
723 
724 #if VM_NRESERVLEVEL > 0
725 	/*
726 	 * Allocate physical memory for the reservation management system's
727 	 * data structures, and map it.
728 	 */
729 	new_end = vm_reserv_startup(&vaddr, new_end);
730 #endif
731 #if defined(__aarch64__) || defined(__amd64__) || \
732     defined(__riscv) || defined(__powerpc64__)
733 	/*
734 	 * Include vm_page_array and vm_reserv_array in a crash dump.
735 	 */
736 	for (pa = new_end; pa < end; pa += PAGE_SIZE)
737 		dump_add_page(pa);
738 #endif
739 	phys_avail[biggestone + 1] = new_end;
740 
741 	/*
742 	 * Add physical memory segments corresponding to the available
743 	 * physical pages.
744 	 */
745 	for (i = 0; phys_avail[i + 1] != 0; i += 2)
746 		if (vm_phys_avail_size(i) != 0)
747 			vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
748 
749 	/*
750 	 * Initialize the physical memory allocator.
751 	 */
752 	vm_phys_init();
753 
754 	/*
755 	 * Initialize the page structures and add every available page to the
756 	 * physical memory allocator's free lists.
757 	 */
758 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
759 	for (ii = 0; ii < vm_page_array_size; ii++) {
760 		m = &vm_page_array[ii];
761 		vm_page_init_page(m, (first_page + ii) << PAGE_SHIFT, 0);
762 		m->flags = PG_FICTITIOUS;
763 	}
764 #endif
765 	vm_cnt.v_page_count = 0;
766 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
767 		seg = &vm_phys_segs[segind];
768 		for (m = seg->first_page, pa = seg->start; pa < seg->end;
769 		    m++, pa += PAGE_SIZE)
770 			vm_page_init_page(m, pa, segind);
771 
772 		/*
773 		 * Add the segment's pages that are covered by one of
774 		 * phys_avail's ranges to the free lists.
775 		 */
776 		for (i = 0; phys_avail[i + 1] != 0; i += 2) {
777 			if (seg->end <= phys_avail[i] ||
778 			    seg->start >= phys_avail[i + 1])
779 				continue;
780 
781 			startp = MAX(seg->start, phys_avail[i]);
782 			endp = MIN(seg->end, phys_avail[i + 1]);
783 			pagecount = (u_long)atop(endp - startp);
784 			if (pagecount == 0)
785 				continue;
786 
787 			m = seg->first_page + atop(startp - seg->start);
788 			vmd = VM_DOMAIN(seg->domain);
789 			vm_domain_free_lock(vmd);
790 			vm_phys_enqueue_contig(m, pagecount);
791 			vm_domain_free_unlock(vmd);
792 			vm_domain_freecnt_inc(vmd, pagecount);
793 			vm_cnt.v_page_count += (u_int)pagecount;
794 			vmd->vmd_page_count += (u_int)pagecount;
795 			vmd->vmd_segs |= 1UL << segind;
796 		}
797 	}
798 
799 	/*
800 	 * Remove blacklisted pages from the physical memory allocator.
801 	 */
802 	TAILQ_INIT(&blacklist_head);
803 	vm_page_blacklist_load(&list, &listend);
804 	vm_page_blacklist_check(list, listend);
805 
806 	list = kern_getenv("vm.blacklist");
807 	vm_page_blacklist_check(list, NULL);
808 
809 	freeenv(list);
810 #if VM_NRESERVLEVEL > 0
811 	/*
812 	 * Initialize the reservation management system.
813 	 */
814 	vm_reserv_init();
815 #endif
816 
817 	return (vaddr);
818 }
819 
820 void
821 vm_page_reference(vm_page_t m)
822 {
823 
824 	vm_page_aflag_set(m, PGA_REFERENCED);
825 }
826 
827 /*
828  *	vm_page_trybusy
829  *
830  *	Helper routine for grab functions to trylock busy.
831  *
832  *	Returns true on success and false on failure.
833  */
834 static bool
835 vm_page_trybusy(vm_page_t m, int allocflags)
836 {
837 
838 	if ((allocflags & (VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY)) != 0)
839 		return (vm_page_trysbusy(m));
840 	else
841 		return (vm_page_tryxbusy(m));
842 }
843 
844 /*
845  *	vm_page_tryacquire
846  *
847  *	Helper routine for grab functions to trylock busy and wire.
848  *
849  *	Returns true on success and false on failure.
850  */
851 static inline bool
852 vm_page_tryacquire(vm_page_t m, int allocflags)
853 {
854 	bool locked;
855 
856 	locked = vm_page_trybusy(m, allocflags);
857 	if (locked && (allocflags & VM_ALLOC_WIRED) != 0)
858 		vm_page_wire(m);
859 	return (locked);
860 }
861 
862 /*
863  *	vm_page_busy_acquire:
864  *
865  *	Acquire the busy lock as described by VM_ALLOC_* flags.  Will loop
866  *	and drop the object lock if necessary.
867  */
868 bool
869 vm_page_busy_acquire(vm_page_t m, int allocflags)
870 {
871 	vm_object_t obj;
872 	bool locked;
873 
874 	/*
875 	 * The page-specific object must be cached because page
876 	 * identity can change during the sleep, causing the
877 	 * re-lock of a different object.
878 	 * It is assumed that a reference to the object is already
879 	 * held by the callers.
880 	 */
881 	obj = atomic_load_ptr(&m->object);
882 	for (;;) {
883 		if (vm_page_tryacquire(m, allocflags))
884 			return (true);
885 		if ((allocflags & VM_ALLOC_NOWAIT) != 0)
886 			return (false);
887 		if (obj != NULL)
888 			locked = VM_OBJECT_WOWNED(obj);
889 		else
890 			locked = false;
891 		MPASS(locked || vm_page_wired(m));
892 		if (_vm_page_busy_sleep(obj, m, m->pindex, "vmpba", allocflags,
893 		    locked) && locked)
894 			VM_OBJECT_WLOCK(obj);
895 		if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
896 			return (false);
897 		KASSERT(m->object == obj || m->object == NULL,
898 		    ("vm_page_busy_acquire: page %p does not belong to %p",
899 		    m, obj));
900 	}
901 }
902 
903 /*
904  *	vm_page_busy_downgrade:
905  *
906  *	Downgrade an exclusive busy page into a single shared busy page.
907  */
908 void
909 vm_page_busy_downgrade(vm_page_t m)
910 {
911 	u_int x;
912 
913 	vm_page_assert_xbusied(m);
914 
915 	x = vm_page_busy_fetch(m);
916 	for (;;) {
917 		if (atomic_fcmpset_rel_int(&m->busy_lock,
918 		    &x, VPB_SHARERS_WORD(1)))
919 			break;
920 	}
921 	if ((x & VPB_BIT_WAITERS) != 0)
922 		wakeup(m);
923 }
924 
925 /*
926  *
927  *	vm_page_busy_tryupgrade:
928  *
929  *	Attempt to upgrade a single shared busy into an exclusive busy.
930  */
931 int
932 vm_page_busy_tryupgrade(vm_page_t m)
933 {
934 	u_int ce, x;
935 
936 	vm_page_assert_sbusied(m);
937 
938 	x = vm_page_busy_fetch(m);
939 	ce = VPB_CURTHREAD_EXCLUSIVE;
940 	for (;;) {
941 		if (VPB_SHARERS(x) > 1)
942 			return (0);
943 		KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
944 		    ("vm_page_busy_tryupgrade: invalid lock state"));
945 		if (!atomic_fcmpset_acq_int(&m->busy_lock, &x,
946 		    ce | (x & VPB_BIT_WAITERS)))
947 			continue;
948 		return (1);
949 	}
950 }
951 
952 /*
953  *	vm_page_sbusied:
954  *
955  *	Return a positive value if the page is shared busied, 0 otherwise.
956  */
957 int
958 vm_page_sbusied(vm_page_t m)
959 {
960 	u_int x;
961 
962 	x = vm_page_busy_fetch(m);
963 	return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
964 }
965 
966 /*
967  *	vm_page_sunbusy:
968  *
969  *	Shared unbusy a page.
970  */
971 void
972 vm_page_sunbusy(vm_page_t m)
973 {
974 	u_int x;
975 
976 	vm_page_assert_sbusied(m);
977 
978 	x = vm_page_busy_fetch(m);
979 	for (;;) {
980 		KASSERT(x != VPB_FREED,
981 		    ("vm_page_sunbusy: Unlocking freed page."));
982 		if (VPB_SHARERS(x) > 1) {
983 			if (atomic_fcmpset_int(&m->busy_lock, &x,
984 			    x - VPB_ONE_SHARER))
985 				break;
986 			continue;
987 		}
988 		KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
989 		    ("vm_page_sunbusy: invalid lock state"));
990 		if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
991 			continue;
992 		if ((x & VPB_BIT_WAITERS) == 0)
993 			break;
994 		wakeup(m);
995 		break;
996 	}
997 }
998 
999 /*
1000  *	vm_page_busy_sleep:
1001  *
1002  *	Sleep if the page is busy, using the page pointer as wchan.
1003  *	This is used to implement the hard-path of the busying mechanism.
1004  *
1005  *	If VM_ALLOC_IGN_SBUSY is specified in allocflags, the function
1006  *	will not sleep if the page is shared-busy.
1007  *
1008  *	The object lock must be held on entry.
1009  *
1010  *	Returns true if it slept and dropped the object lock, or false
1011  *	if there was no sleep and the lock is still held.
1012  */
1013 bool
1014 vm_page_busy_sleep(vm_page_t m, const char *wmesg, int allocflags)
1015 {
1016 	vm_object_t obj;
1017 
1018 	obj = m->object;
1019 	VM_OBJECT_ASSERT_LOCKED(obj);
1020 
1021 	return (_vm_page_busy_sleep(obj, m, m->pindex, wmesg, allocflags,
1022 	    true));
1023 }
1024 
1025 /*
1026  *	vm_page_busy_sleep_unlocked:
1027  *
1028  *	Sleep if the page is busy, using the page pointer as wchan.
1029  *	This is used to implement the hard-path of busying mechanism.
1030  *
1031  *	If VM_ALLOC_IGN_SBUSY is specified in allocflags, the function
1032  *	will not sleep if the page is shared-busy.
1033  *
1034  *	The object lock must not be held on entry.  The operation will
1035  *	return if the page changes identity.
1036  */
1037 void
1038 vm_page_busy_sleep_unlocked(vm_object_t obj, vm_page_t m, vm_pindex_t pindex,
1039     const char *wmesg, int allocflags)
1040 {
1041 	VM_OBJECT_ASSERT_UNLOCKED(obj);
1042 
1043 	(void)_vm_page_busy_sleep(obj, m, pindex, wmesg, allocflags, false);
1044 }
1045 
1046 /*
1047  *	_vm_page_busy_sleep:
1048  *
1049  *	Internal busy sleep function.  Verifies the page identity and
1050  *	lockstate against parameters.  Returns true if it sleeps and
1051  *	false otherwise.
1052  *
1053  *	allocflags uses VM_ALLOC_* flags to specify the lock required.
1054  *
1055  *	If locked is true the lock will be dropped for any true returns
1056  *	and held for any false returns.
1057  */
1058 static bool
1059 _vm_page_busy_sleep(vm_object_t obj, vm_page_t m, vm_pindex_t pindex,
1060     const char *wmesg, int allocflags, bool locked)
1061 {
1062 	bool xsleep;
1063 	u_int x;
1064 
1065 	/*
1066 	 * If the object is busy we must wait for that to drain to zero
1067 	 * before trying the page again.
1068 	 */
1069 	if (obj != NULL && vm_object_busied(obj)) {
1070 		if (locked)
1071 			VM_OBJECT_DROP(obj);
1072 		vm_object_busy_wait(obj, wmesg);
1073 		return (true);
1074 	}
1075 
1076 	if (!vm_page_busied(m))
1077 		return (false);
1078 
1079 	xsleep = (allocflags & (VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY)) != 0;
1080 	sleepq_lock(m);
1081 	x = vm_page_busy_fetch(m);
1082 	do {
1083 		/*
1084 		 * If the page changes objects or becomes unlocked we can
1085 		 * simply return.
1086 		 */
1087 		if (x == VPB_UNBUSIED ||
1088 		    (xsleep && (x & VPB_BIT_SHARED) != 0) ||
1089 		    m->object != obj || m->pindex != pindex) {
1090 			sleepq_release(m);
1091 			return (false);
1092 		}
1093 		if ((x & VPB_BIT_WAITERS) != 0)
1094 			break;
1095 	} while (!atomic_fcmpset_int(&m->busy_lock, &x, x | VPB_BIT_WAITERS));
1096 	if (locked)
1097 		VM_OBJECT_DROP(obj);
1098 	DROP_GIANT();
1099 	sleepq_add(m, NULL, wmesg, 0, 0);
1100 	sleepq_wait(m, PVM);
1101 	PICKUP_GIANT();
1102 	return (true);
1103 }
1104 
1105 /*
1106  *	vm_page_trysbusy:
1107  *
1108  *	Try to shared busy a page.
1109  *	If the operation succeeds 1 is returned otherwise 0.
1110  *	The operation never sleeps.
1111  */
1112 int
1113 vm_page_trysbusy(vm_page_t m)
1114 {
1115 	vm_object_t obj;
1116 	u_int x;
1117 
1118 	obj = m->object;
1119 	x = vm_page_busy_fetch(m);
1120 	for (;;) {
1121 		if ((x & VPB_BIT_SHARED) == 0)
1122 			return (0);
1123 		/*
1124 		 * Reduce the window for transient busies that will trigger
1125 		 * false negatives in vm_page_ps_test().
1126 		 */
1127 		if (obj != NULL && vm_object_busied(obj))
1128 			return (0);
1129 		if (atomic_fcmpset_acq_int(&m->busy_lock, &x,
1130 		    x + VPB_ONE_SHARER))
1131 			break;
1132 	}
1133 
1134 	/* Refetch the object now that we're guaranteed that it is stable. */
1135 	obj = m->object;
1136 	if (obj != NULL && vm_object_busied(obj)) {
1137 		vm_page_sunbusy(m);
1138 		return (0);
1139 	}
1140 	return (1);
1141 }
1142 
1143 /*
1144  *	vm_page_tryxbusy:
1145  *
1146  *	Try to exclusive busy a page.
1147  *	If the operation succeeds 1 is returned otherwise 0.
1148  *	The operation never sleeps.
1149  */
1150 int
1151 vm_page_tryxbusy(vm_page_t m)
1152 {
1153 	vm_object_t obj;
1154 
1155         if (atomic_cmpset_acq_int(&m->busy_lock, VPB_UNBUSIED,
1156             VPB_CURTHREAD_EXCLUSIVE) == 0)
1157 		return (0);
1158 
1159 	obj = m->object;
1160 	if (obj != NULL && vm_object_busied(obj)) {
1161 		vm_page_xunbusy(m);
1162 		return (0);
1163 	}
1164 	return (1);
1165 }
1166 
1167 static void
1168 vm_page_xunbusy_hard_tail(vm_page_t m)
1169 {
1170 	atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1171 	/* Wake the waiter. */
1172 	wakeup(m);
1173 }
1174 
1175 /*
1176  *	vm_page_xunbusy_hard:
1177  *
1178  *	Called when unbusy has failed because there is a waiter.
1179  */
1180 void
1181 vm_page_xunbusy_hard(vm_page_t m)
1182 {
1183 	vm_page_assert_xbusied(m);
1184 	vm_page_xunbusy_hard_tail(m);
1185 }
1186 
1187 void
1188 vm_page_xunbusy_hard_unchecked(vm_page_t m)
1189 {
1190 	vm_page_assert_xbusied_unchecked(m);
1191 	vm_page_xunbusy_hard_tail(m);
1192 }
1193 
1194 static void
1195 vm_page_busy_free(vm_page_t m)
1196 {
1197 	u_int x;
1198 
1199 	atomic_thread_fence_rel();
1200 	x = atomic_swap_int(&m->busy_lock, VPB_FREED);
1201 	if ((x & VPB_BIT_WAITERS) != 0)
1202 		wakeup(m);
1203 }
1204 
1205 /*
1206  *	vm_page_unhold_pages:
1207  *
1208  *	Unhold each of the pages that is referenced by the given array.
1209  */
1210 void
1211 vm_page_unhold_pages(vm_page_t *ma, int count)
1212 {
1213 
1214 	for (; count != 0; count--) {
1215 		vm_page_unwire(*ma, PQ_ACTIVE);
1216 		ma++;
1217 	}
1218 }
1219 
1220 vm_page_t
1221 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1222 {
1223 	vm_page_t m;
1224 
1225 #ifdef VM_PHYSSEG_SPARSE
1226 	m = vm_phys_paddr_to_vm_page(pa);
1227 	if (m == NULL)
1228 		m = vm_phys_fictitious_to_vm_page(pa);
1229 	return (m);
1230 #elif defined(VM_PHYSSEG_DENSE)
1231 	long pi;
1232 
1233 	pi = atop(pa);
1234 	if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1235 		m = &vm_page_array[pi - first_page];
1236 		return (m);
1237 	}
1238 	return (vm_phys_fictitious_to_vm_page(pa));
1239 #else
1240 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1241 #endif
1242 }
1243 
1244 /*
1245  *	vm_page_getfake:
1246  *
1247  *	Create a fictitious page with the specified physical address and
1248  *	memory attribute.  The memory attribute is the only the machine-
1249  *	dependent aspect of a fictitious page that must be initialized.
1250  */
1251 vm_page_t
1252 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1253 {
1254 	vm_page_t m;
1255 
1256 	m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1257 	vm_page_initfake(m, paddr, memattr);
1258 	return (m);
1259 }
1260 
1261 void
1262 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1263 {
1264 
1265 	if ((m->flags & PG_FICTITIOUS) != 0) {
1266 		/*
1267 		 * The page's memattr might have changed since the
1268 		 * previous initialization.  Update the pmap to the
1269 		 * new memattr.
1270 		 */
1271 		goto memattr;
1272 	}
1273 	m->phys_addr = paddr;
1274 	m->a.queue = PQ_NONE;
1275 	/* Fictitious pages don't use "segind". */
1276 	m->flags = PG_FICTITIOUS;
1277 	/* Fictitious pages don't use "order" or "pool". */
1278 	m->oflags = VPO_UNMANAGED;
1279 	m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
1280 	/* Fictitious pages are unevictable. */
1281 	m->ref_count = 1;
1282 	pmap_page_init(m);
1283 memattr:
1284 	pmap_page_set_memattr(m, memattr);
1285 }
1286 
1287 /*
1288  *	vm_page_putfake:
1289  *
1290  *	Release a fictitious page.
1291  */
1292 void
1293 vm_page_putfake(vm_page_t m)
1294 {
1295 
1296 	KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1297 	KASSERT((m->flags & PG_FICTITIOUS) != 0,
1298 	    ("vm_page_putfake: bad page %p", m));
1299 	vm_page_assert_xbusied(m);
1300 	vm_page_busy_free(m);
1301 	uma_zfree(fakepg_zone, m);
1302 }
1303 
1304 /*
1305  *	vm_page_updatefake:
1306  *
1307  *	Update the given fictitious page to the specified physical address and
1308  *	memory attribute.
1309  */
1310 void
1311 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1312 {
1313 
1314 	KASSERT((m->flags & PG_FICTITIOUS) != 0,
1315 	    ("vm_page_updatefake: bad page %p", m));
1316 	m->phys_addr = paddr;
1317 	pmap_page_set_memattr(m, memattr);
1318 }
1319 
1320 /*
1321  *	vm_page_free:
1322  *
1323  *	Free a page.
1324  */
1325 void
1326 vm_page_free(vm_page_t m)
1327 {
1328 
1329 	m->flags &= ~PG_ZERO;
1330 	vm_page_free_toq(m);
1331 }
1332 
1333 /*
1334  *	vm_page_free_zero:
1335  *
1336  *	Free a page to the zerod-pages queue
1337  */
1338 void
1339 vm_page_free_zero(vm_page_t m)
1340 {
1341 
1342 	m->flags |= PG_ZERO;
1343 	vm_page_free_toq(m);
1344 }
1345 
1346 /*
1347  * Unbusy and handle the page queueing for a page from a getpages request that
1348  * was optionally read ahead or behind.
1349  */
1350 void
1351 vm_page_readahead_finish(vm_page_t m)
1352 {
1353 
1354 	/* We shouldn't put invalid pages on queues. */
1355 	KASSERT(!vm_page_none_valid(m), ("%s: %p is invalid", __func__, m));
1356 
1357 	/*
1358 	 * Since the page is not the actually needed one, whether it should
1359 	 * be activated or deactivated is not obvious.  Empirical results
1360 	 * have shown that deactivating the page is usually the best choice,
1361 	 * unless the page is wanted by another thread.
1362 	 */
1363 	if ((vm_page_busy_fetch(m) & VPB_BIT_WAITERS) != 0)
1364 		vm_page_activate(m);
1365 	else
1366 		vm_page_deactivate(m);
1367 	vm_page_xunbusy_unchecked(m);
1368 }
1369 
1370 /*
1371  * Destroy the identity of an invalid page and free it if possible.
1372  * This is intended to be used when reading a page from backing store fails.
1373  */
1374 void
1375 vm_page_free_invalid(vm_page_t m)
1376 {
1377 
1378 	KASSERT(vm_page_none_valid(m), ("page %p is valid", m));
1379 	KASSERT(!pmap_page_is_mapped(m), ("page %p is mapped", m));
1380 	KASSERT(m->object != NULL, ("page %p has no object", m));
1381 	VM_OBJECT_ASSERT_WLOCKED(m->object);
1382 
1383 	/*
1384 	 * We may be attempting to free the page as part of the handling for an
1385 	 * I/O error, in which case the page was xbusied by a different thread.
1386 	 */
1387 	vm_page_xbusy_claim(m);
1388 
1389 	/*
1390 	 * If someone has wired this page while the object lock
1391 	 * was not held, then the thread that unwires is responsible
1392 	 * for freeing the page.  Otherwise just free the page now.
1393 	 * The wire count of this unmapped page cannot change while
1394 	 * we have the page xbusy and the page's object wlocked.
1395 	 */
1396 	if (vm_page_remove(m))
1397 		vm_page_free(m);
1398 }
1399 
1400 /*
1401  *	vm_page_dirty_KBI:		[ internal use only ]
1402  *
1403  *	Set all bits in the page's dirty field.
1404  *
1405  *	The object containing the specified page must be locked if the
1406  *	call is made from the machine-independent layer.
1407  *
1408  *	See vm_page_clear_dirty_mask().
1409  *
1410  *	This function should only be called by vm_page_dirty().
1411  */
1412 void
1413 vm_page_dirty_KBI(vm_page_t m)
1414 {
1415 
1416 	/* Refer to this operation by its public name. */
1417 	KASSERT(vm_page_all_valid(m), ("vm_page_dirty: page is invalid!"));
1418 	m->dirty = VM_PAGE_BITS_ALL;
1419 }
1420 
1421 /*
1422  *	vm_page_insert:		[ internal use only ]
1423  *
1424  *	Inserts the given mem entry into the object and object list.
1425  *
1426  *	The object must be locked.
1427  */
1428 int
1429 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1430 {
1431 	vm_page_t mpred;
1432 
1433 	VM_OBJECT_ASSERT_WLOCKED(object);
1434 	mpred = vm_radix_lookup_le(&object->rtree, pindex);
1435 	return (vm_page_insert_after(m, object, pindex, mpred));
1436 }
1437 
1438 /*
1439  *	vm_page_insert_after:
1440  *
1441  *	Inserts the page "m" into the specified object at offset "pindex".
1442  *
1443  *	The page "mpred" must immediately precede the offset "pindex" within
1444  *	the specified object.
1445  *
1446  *	The object must be locked.
1447  */
1448 static int
1449 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1450     vm_page_t mpred)
1451 {
1452 	vm_page_t msucc;
1453 
1454 	VM_OBJECT_ASSERT_WLOCKED(object);
1455 	KASSERT(m->object == NULL,
1456 	    ("vm_page_insert_after: page already inserted"));
1457 	if (mpred != NULL) {
1458 		KASSERT(mpred->object == object,
1459 		    ("vm_page_insert_after: object doesn't contain mpred"));
1460 		KASSERT(mpred->pindex < pindex,
1461 		    ("vm_page_insert_after: mpred doesn't precede pindex"));
1462 		msucc = TAILQ_NEXT(mpred, listq);
1463 	} else
1464 		msucc = TAILQ_FIRST(&object->memq);
1465 	if (msucc != NULL)
1466 		KASSERT(msucc->pindex > pindex,
1467 		    ("vm_page_insert_after: msucc doesn't succeed pindex"));
1468 
1469 	/*
1470 	 * Record the object/offset pair in this page.
1471 	 */
1472 	m->object = object;
1473 	m->pindex = pindex;
1474 	m->ref_count |= VPRC_OBJREF;
1475 
1476 	/*
1477 	 * Now link into the object's ordered list of backed pages.
1478 	 */
1479 	if (vm_radix_insert(&object->rtree, m)) {
1480 		m->object = NULL;
1481 		m->pindex = 0;
1482 		m->ref_count &= ~VPRC_OBJREF;
1483 		return (1);
1484 	}
1485 	vm_page_insert_radixdone(m, object, mpred);
1486 	vm_pager_page_inserted(object, m);
1487 	return (0);
1488 }
1489 
1490 /*
1491  *	vm_page_insert_radixdone:
1492  *
1493  *	Complete page "m" insertion into the specified object after the
1494  *	radix trie hooking.
1495  *
1496  *	The page "mpred" must precede the offset "m->pindex" within the
1497  *	specified object.
1498  *
1499  *	The object must be locked.
1500  */
1501 static void
1502 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1503 {
1504 
1505 	VM_OBJECT_ASSERT_WLOCKED(object);
1506 	KASSERT(object != NULL && m->object == object,
1507 	    ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1508 	KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1509 	    ("vm_page_insert_radixdone: page %p is missing object ref", m));
1510 	if (mpred != NULL) {
1511 		KASSERT(mpred->object == object,
1512 		    ("vm_page_insert_radixdone: object doesn't contain mpred"));
1513 		KASSERT(mpred->pindex < m->pindex,
1514 		    ("vm_page_insert_radixdone: mpred doesn't precede pindex"));
1515 	}
1516 
1517 	if (mpred != NULL)
1518 		TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1519 	else
1520 		TAILQ_INSERT_HEAD(&object->memq, m, listq);
1521 
1522 	/*
1523 	 * Show that the object has one more resident page.
1524 	 */
1525 	object->resident_page_count++;
1526 
1527 	/*
1528 	 * Hold the vnode until the last page is released.
1529 	 */
1530 	if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1531 		vhold(object->handle);
1532 
1533 	/*
1534 	 * Since we are inserting a new and possibly dirty page,
1535 	 * update the object's generation count.
1536 	 */
1537 	if (pmap_page_is_write_mapped(m))
1538 		vm_object_set_writeable_dirty(object);
1539 }
1540 
1541 /*
1542  * Do the work to remove a page from its object.  The caller is responsible for
1543  * updating the page's fields to reflect this removal.
1544  */
1545 static void
1546 vm_page_object_remove(vm_page_t m)
1547 {
1548 	vm_object_t object;
1549 	vm_page_t mrem __diagused;
1550 
1551 	vm_page_assert_xbusied(m);
1552 	object = m->object;
1553 	VM_OBJECT_ASSERT_WLOCKED(object);
1554 	KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1555 	    ("page %p is missing its object ref", m));
1556 
1557 	/* Deferred free of swap space. */
1558 	if ((m->a.flags & PGA_SWAP_FREE) != 0)
1559 		vm_pager_page_unswapped(m);
1560 
1561 	vm_pager_page_removed(object, m);
1562 
1563 	m->object = NULL;
1564 	mrem = vm_radix_remove(&object->rtree, m->pindex);
1565 	KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1566 
1567 	/*
1568 	 * Now remove from the object's list of backed pages.
1569 	 */
1570 	TAILQ_REMOVE(&object->memq, m, listq);
1571 
1572 	/*
1573 	 * And show that the object has one fewer resident page.
1574 	 */
1575 	object->resident_page_count--;
1576 
1577 	/*
1578 	 * The vnode may now be recycled.
1579 	 */
1580 	if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1581 		vdrop(object->handle);
1582 }
1583 
1584 /*
1585  *	vm_page_remove:
1586  *
1587  *	Removes the specified page from its containing object, but does not
1588  *	invalidate any backing storage.  Returns true if the object's reference
1589  *	was the last reference to the page, and false otherwise.
1590  *
1591  *	The object must be locked and the page must be exclusively busied.
1592  *	The exclusive busy will be released on return.  If this is not the
1593  *	final ref and the caller does not hold a wire reference it may not
1594  *	continue to access the page.
1595  */
1596 bool
1597 vm_page_remove(vm_page_t m)
1598 {
1599 	bool dropped;
1600 
1601 	dropped = vm_page_remove_xbusy(m);
1602 	vm_page_xunbusy(m);
1603 
1604 	return (dropped);
1605 }
1606 
1607 /*
1608  *	vm_page_remove_xbusy
1609  *
1610  *	Removes the page but leaves the xbusy held.  Returns true if this
1611  *	removed the final ref and false otherwise.
1612  */
1613 bool
1614 vm_page_remove_xbusy(vm_page_t m)
1615 {
1616 
1617 	vm_page_object_remove(m);
1618 	return (vm_page_drop(m, VPRC_OBJREF) == VPRC_OBJREF);
1619 }
1620 
1621 /*
1622  *	vm_page_lookup:
1623  *
1624  *	Returns the page associated with the object/offset
1625  *	pair specified; if none is found, NULL is returned.
1626  *
1627  *	The object must be locked.
1628  */
1629 vm_page_t
1630 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1631 {
1632 
1633 	VM_OBJECT_ASSERT_LOCKED(object);
1634 	return (vm_radix_lookup(&object->rtree, pindex));
1635 }
1636 
1637 /*
1638  *	vm_page_lookup_unlocked:
1639  *
1640  *	Returns the page associated with the object/offset pair specified;
1641  *	if none is found, NULL is returned.  The page may be no longer be
1642  *	present in the object at the time that this function returns.  Only
1643  *	useful for opportunistic checks such as inmem().
1644  */
1645 vm_page_t
1646 vm_page_lookup_unlocked(vm_object_t object, vm_pindex_t pindex)
1647 {
1648 
1649 	return (vm_radix_lookup_unlocked(&object->rtree, pindex));
1650 }
1651 
1652 /*
1653  *	vm_page_relookup:
1654  *
1655  *	Returns a page that must already have been busied by
1656  *	the caller.  Used for bogus page replacement.
1657  */
1658 vm_page_t
1659 vm_page_relookup(vm_object_t object, vm_pindex_t pindex)
1660 {
1661 	vm_page_t m;
1662 
1663 	m = vm_radix_lookup_unlocked(&object->rtree, pindex);
1664 	KASSERT(m != NULL && (vm_page_busied(m) || vm_page_wired(m)) &&
1665 	    m->object == object && m->pindex == pindex,
1666 	    ("vm_page_relookup: Invalid page %p", m));
1667 	return (m);
1668 }
1669 
1670 /*
1671  * This should only be used by lockless functions for releasing transient
1672  * incorrect acquires.  The page may have been freed after we acquired a
1673  * busy lock.  In this case busy_lock == VPB_FREED and we have nothing
1674  * further to do.
1675  */
1676 static void
1677 vm_page_busy_release(vm_page_t m)
1678 {
1679 	u_int x;
1680 
1681 	x = vm_page_busy_fetch(m);
1682 	for (;;) {
1683 		if (x == VPB_FREED)
1684 			break;
1685 		if ((x & VPB_BIT_SHARED) != 0 && VPB_SHARERS(x) > 1) {
1686 			if (atomic_fcmpset_int(&m->busy_lock, &x,
1687 			    x - VPB_ONE_SHARER))
1688 				break;
1689 			continue;
1690 		}
1691 		KASSERT((x & VPB_BIT_SHARED) != 0 ||
1692 		    (x & ~VPB_BIT_WAITERS) == VPB_CURTHREAD_EXCLUSIVE,
1693 		    ("vm_page_busy_release: %p xbusy not owned.", m));
1694 		if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
1695 			continue;
1696 		if ((x & VPB_BIT_WAITERS) != 0)
1697 			wakeup(m);
1698 		break;
1699 	}
1700 }
1701 
1702 /*
1703  *	vm_page_find_least:
1704  *
1705  *	Returns the page associated with the object with least pindex
1706  *	greater than or equal to the parameter pindex, or NULL.
1707  *
1708  *	The object must be locked.
1709  */
1710 vm_page_t
1711 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1712 {
1713 	vm_page_t m;
1714 
1715 	VM_OBJECT_ASSERT_LOCKED(object);
1716 	if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1717 		m = vm_radix_lookup_ge(&object->rtree, pindex);
1718 	return (m);
1719 }
1720 
1721 /*
1722  * Returns the given page's successor (by pindex) within the object if it is
1723  * resident; if none is found, NULL is returned.
1724  *
1725  * The object must be locked.
1726  */
1727 vm_page_t
1728 vm_page_next(vm_page_t m)
1729 {
1730 	vm_page_t next;
1731 
1732 	VM_OBJECT_ASSERT_LOCKED(m->object);
1733 	if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1734 		MPASS(next->object == m->object);
1735 		if (next->pindex != m->pindex + 1)
1736 			next = NULL;
1737 	}
1738 	return (next);
1739 }
1740 
1741 /*
1742  * Returns the given page's predecessor (by pindex) within the object if it is
1743  * resident; if none is found, NULL is returned.
1744  *
1745  * The object must be locked.
1746  */
1747 vm_page_t
1748 vm_page_prev(vm_page_t m)
1749 {
1750 	vm_page_t prev;
1751 
1752 	VM_OBJECT_ASSERT_LOCKED(m->object);
1753 	if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1754 		MPASS(prev->object == m->object);
1755 		if (prev->pindex != m->pindex - 1)
1756 			prev = NULL;
1757 	}
1758 	return (prev);
1759 }
1760 
1761 /*
1762  * Uses the page mnew as a replacement for an existing page at index
1763  * pindex which must be already present in the object.
1764  *
1765  * Both pages must be exclusively busied on enter.  The old page is
1766  * unbusied on exit.
1767  *
1768  * A return value of true means mold is now free.  If this is not the
1769  * final ref and the caller does not hold a wire reference it may not
1770  * continue to access the page.
1771  */
1772 static bool
1773 vm_page_replace_hold(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1774     vm_page_t mold)
1775 {
1776 	vm_page_t mret __diagused;
1777 	bool dropped;
1778 
1779 	VM_OBJECT_ASSERT_WLOCKED(object);
1780 	vm_page_assert_xbusied(mold);
1781 	KASSERT(mnew->object == NULL && (mnew->ref_count & VPRC_OBJREF) == 0,
1782 	    ("vm_page_replace: page %p already in object", mnew));
1783 
1784 	/*
1785 	 * This function mostly follows vm_page_insert() and
1786 	 * vm_page_remove() without the radix, object count and vnode
1787 	 * dance.  Double check such functions for more comments.
1788 	 */
1789 
1790 	mnew->object = object;
1791 	mnew->pindex = pindex;
1792 	atomic_set_int(&mnew->ref_count, VPRC_OBJREF);
1793 	mret = vm_radix_replace(&object->rtree, mnew);
1794 	KASSERT(mret == mold,
1795 	    ("invalid page replacement, mold=%p, mret=%p", mold, mret));
1796 	KASSERT((mold->oflags & VPO_UNMANAGED) ==
1797 	    (mnew->oflags & VPO_UNMANAGED),
1798 	    ("vm_page_replace: mismatched VPO_UNMANAGED"));
1799 
1800 	/* Keep the resident page list in sorted order. */
1801 	TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1802 	TAILQ_REMOVE(&object->memq, mold, listq);
1803 	mold->object = NULL;
1804 
1805 	/*
1806 	 * The object's resident_page_count does not change because we have
1807 	 * swapped one page for another, but the generation count should
1808 	 * change if the page is dirty.
1809 	 */
1810 	if (pmap_page_is_write_mapped(mnew))
1811 		vm_object_set_writeable_dirty(object);
1812 	dropped = vm_page_drop(mold, VPRC_OBJREF) == VPRC_OBJREF;
1813 	vm_page_xunbusy(mold);
1814 
1815 	return (dropped);
1816 }
1817 
1818 void
1819 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1820     vm_page_t mold)
1821 {
1822 
1823 	vm_page_assert_xbusied(mnew);
1824 
1825 	if (vm_page_replace_hold(mnew, object, pindex, mold))
1826 		vm_page_free(mold);
1827 }
1828 
1829 /*
1830  *	vm_page_rename:
1831  *
1832  *	Move the given memory entry from its
1833  *	current object to the specified target object/offset.
1834  *
1835  *	Note: swap associated with the page must be invalidated by the move.  We
1836  *	      have to do this for several reasons:  (1) we aren't freeing the
1837  *	      page, (2) we are dirtying the page, (3) the VM system is probably
1838  *	      moving the page from object A to B, and will then later move
1839  *	      the backing store from A to B and we can't have a conflict.
1840  *
1841  *	Note: we *always* dirty the page.  It is necessary both for the
1842  *	      fact that we moved it, and because we may be invalidating
1843  *	      swap.
1844  *
1845  *	The objects must be locked.
1846  */
1847 int
1848 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1849 {
1850 	vm_page_t mpred;
1851 	vm_pindex_t opidx;
1852 
1853 	VM_OBJECT_ASSERT_WLOCKED(new_object);
1854 
1855 	KASSERT(m->ref_count != 0, ("vm_page_rename: page %p has no refs", m));
1856 	mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1857 	KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1858 	    ("vm_page_rename: pindex already renamed"));
1859 
1860 	/*
1861 	 * Create a custom version of vm_page_insert() which does not depend
1862 	 * by m_prev and can cheat on the implementation aspects of the
1863 	 * function.
1864 	 */
1865 	opidx = m->pindex;
1866 	m->pindex = new_pindex;
1867 	if (vm_radix_insert(&new_object->rtree, m)) {
1868 		m->pindex = opidx;
1869 		return (1);
1870 	}
1871 
1872 	/*
1873 	 * The operation cannot fail anymore.  The removal must happen before
1874 	 * the listq iterator is tainted.
1875 	 */
1876 	m->pindex = opidx;
1877 	vm_page_object_remove(m);
1878 
1879 	/* Return back to the new pindex to complete vm_page_insert(). */
1880 	m->pindex = new_pindex;
1881 	m->object = new_object;
1882 
1883 	vm_page_insert_radixdone(m, new_object, mpred);
1884 	vm_page_dirty(m);
1885 	vm_pager_page_inserted(new_object, m);
1886 	return (0);
1887 }
1888 
1889 /*
1890  *	vm_page_alloc:
1891  *
1892  *	Allocate and return a page that is associated with the specified
1893  *	object and offset pair.  By default, this page is exclusive busied.
1894  *
1895  *	The caller must always specify an allocation class.
1896  *
1897  *	allocation classes:
1898  *	VM_ALLOC_NORMAL		normal process request
1899  *	VM_ALLOC_SYSTEM		system *really* needs a page
1900  *	VM_ALLOC_INTERRUPT	interrupt time request
1901  *
1902  *	optional allocation flags:
1903  *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
1904  *				intends to allocate
1905  *	VM_ALLOC_NOBUSY		do not exclusive busy the page
1906  *	VM_ALLOC_NODUMP		do not include the page in a kernel core dump
1907  *	VM_ALLOC_SBUSY		shared busy the allocated page
1908  *	VM_ALLOC_WIRED		wire the allocated page
1909  *	VM_ALLOC_ZERO		prefer a zeroed page
1910  */
1911 vm_page_t
1912 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1913 {
1914 
1915 	return (vm_page_alloc_after(object, pindex, req,
1916 	    vm_radix_lookup_le(&object->rtree, pindex)));
1917 }
1918 
1919 vm_page_t
1920 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1921     int req)
1922 {
1923 
1924 	return (vm_page_alloc_domain_after(object, pindex, domain, req,
1925 	    vm_radix_lookup_le(&object->rtree, pindex)));
1926 }
1927 
1928 /*
1929  * Allocate a page in the specified object with the given page index.  To
1930  * optimize insertion of the page into the object, the caller must also specifiy
1931  * the resident page in the object with largest index smaller than the given
1932  * page index, or NULL if no such page exists.
1933  */
1934 vm_page_t
1935 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1936     int req, vm_page_t mpred)
1937 {
1938 	struct vm_domainset_iter di;
1939 	vm_page_t m;
1940 	int domain;
1941 
1942 	vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1943 	do {
1944 		m = vm_page_alloc_domain_after(object, pindex, domain, req,
1945 		    mpred);
1946 		if (m != NULL)
1947 			break;
1948 	} while (vm_domainset_iter_page(&di, object, &domain) == 0);
1949 
1950 	return (m);
1951 }
1952 
1953 /*
1954  * Returns true if the number of free pages exceeds the minimum
1955  * for the request class and false otherwise.
1956  */
1957 static int
1958 _vm_domain_allocate(struct vm_domain *vmd, int req_class, int npages)
1959 {
1960 	u_int limit, old, new;
1961 
1962 	if (req_class == VM_ALLOC_INTERRUPT)
1963 		limit = 0;
1964 	else if (req_class == VM_ALLOC_SYSTEM)
1965 		limit = vmd->vmd_interrupt_free_min;
1966 	else
1967 		limit = vmd->vmd_free_reserved;
1968 
1969 	/*
1970 	 * Attempt to reserve the pages.  Fail if we're below the limit.
1971 	 */
1972 	limit += npages;
1973 	old = vmd->vmd_free_count;
1974 	do {
1975 		if (old < limit)
1976 			return (0);
1977 		new = old - npages;
1978 	} while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
1979 
1980 	/* Wake the page daemon if we've crossed the threshold. */
1981 	if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
1982 		pagedaemon_wakeup(vmd->vmd_domain);
1983 
1984 	/* Only update bitsets on transitions. */
1985 	if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
1986 	    (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
1987 		vm_domain_set(vmd);
1988 
1989 	return (1);
1990 }
1991 
1992 int
1993 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
1994 {
1995 	int req_class;
1996 
1997 	/*
1998 	 * The page daemon is allowed to dig deeper into the free page list.
1999 	 */
2000 	req_class = req & VM_ALLOC_CLASS_MASK;
2001 	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2002 		req_class = VM_ALLOC_SYSTEM;
2003 	return (_vm_domain_allocate(vmd, req_class, npages));
2004 }
2005 
2006 vm_page_t
2007 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
2008     int req, vm_page_t mpred)
2009 {
2010 	struct vm_domain *vmd;
2011 	vm_page_t m;
2012 	int flags;
2013 
2014 #define	VPA_FLAGS	(VM_ALLOC_CLASS_MASK | VM_ALLOC_WAITFAIL |	\
2015 			 VM_ALLOC_NOWAIT | VM_ALLOC_NOBUSY |		\
2016 			 VM_ALLOC_SBUSY | VM_ALLOC_WIRED |		\
2017 			 VM_ALLOC_NODUMP | VM_ALLOC_ZERO | VM_ALLOC_COUNT_MASK)
2018 	KASSERT((req & ~VPA_FLAGS) == 0,
2019 	    ("invalid request %#x", req));
2020 	KASSERT(((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2021 	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2022 	    ("invalid request %#x", req));
2023 	KASSERT(mpred == NULL || mpred->pindex < pindex,
2024 	    ("mpred %p doesn't precede pindex 0x%jx", mpred,
2025 	    (uintmax_t)pindex));
2026 	VM_OBJECT_ASSERT_WLOCKED(object);
2027 
2028 	flags = 0;
2029 	m = NULL;
2030 	if (!vm_pager_can_alloc_page(object, pindex))
2031 		return (NULL);
2032 again:
2033 #if VM_NRESERVLEVEL > 0
2034 	/*
2035 	 * Can we allocate the page from a reservation?
2036 	 */
2037 	if (vm_object_reserv(object) &&
2038 	    (m = vm_reserv_alloc_page(object, pindex, domain, req, mpred)) !=
2039 	    NULL) {
2040 		goto found;
2041 	}
2042 #endif
2043 	vmd = VM_DOMAIN(domain);
2044 	if (vmd->vmd_pgcache[VM_FREEPOOL_DEFAULT].zone != NULL) {
2045 		m = uma_zalloc(vmd->vmd_pgcache[VM_FREEPOOL_DEFAULT].zone,
2046 		    M_NOWAIT | M_NOVM);
2047 		if (m != NULL) {
2048 			flags |= PG_PCPU_CACHE;
2049 			goto found;
2050 		}
2051 	}
2052 	if (vm_domain_allocate(vmd, req, 1)) {
2053 		/*
2054 		 * If not, allocate it from the free page queues.
2055 		 */
2056 		vm_domain_free_lock(vmd);
2057 		m = vm_phys_alloc_pages(domain, VM_FREEPOOL_DEFAULT, 0);
2058 		vm_domain_free_unlock(vmd);
2059 		if (m == NULL) {
2060 			vm_domain_freecnt_inc(vmd, 1);
2061 #if VM_NRESERVLEVEL > 0
2062 			if (vm_reserv_reclaim_inactive(domain))
2063 				goto again;
2064 #endif
2065 		}
2066 	}
2067 	if (m == NULL) {
2068 		/*
2069 		 * Not allocatable, give up.
2070 		 */
2071 		if (vm_domain_alloc_fail(vmd, object, req))
2072 			goto again;
2073 		return (NULL);
2074 	}
2075 
2076 	/*
2077 	 * At this point we had better have found a good page.
2078 	 */
2079 found:
2080 	vm_page_dequeue(m);
2081 	vm_page_alloc_check(m);
2082 
2083 	/*
2084 	 * Initialize the page.  Only the PG_ZERO flag is inherited.
2085 	 */
2086 	flags |= m->flags & PG_ZERO;
2087 	if ((req & VM_ALLOC_NODUMP) != 0)
2088 		flags |= PG_NODUMP;
2089 	m->flags = flags;
2090 	m->a.flags = 0;
2091 	m->oflags = (object->flags & OBJ_UNMANAGED) != 0 ? VPO_UNMANAGED : 0;
2092 	if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
2093 		m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2094 	else if ((req & VM_ALLOC_SBUSY) != 0)
2095 		m->busy_lock = VPB_SHARERS_WORD(1);
2096 	else
2097 		m->busy_lock = VPB_UNBUSIED;
2098 	if (req & VM_ALLOC_WIRED) {
2099 		vm_wire_add(1);
2100 		m->ref_count = 1;
2101 	}
2102 	m->a.act_count = 0;
2103 
2104 	if (vm_page_insert_after(m, object, pindex, mpred)) {
2105 		if (req & VM_ALLOC_WIRED) {
2106 			vm_wire_sub(1);
2107 			m->ref_count = 0;
2108 		}
2109 		KASSERT(m->object == NULL, ("page %p has object", m));
2110 		m->oflags = VPO_UNMANAGED;
2111 		m->busy_lock = VPB_UNBUSIED;
2112 		/* Don't change PG_ZERO. */
2113 		vm_page_free_toq(m);
2114 		if (req & VM_ALLOC_WAITFAIL) {
2115 			VM_OBJECT_WUNLOCK(object);
2116 			vm_radix_wait();
2117 			VM_OBJECT_WLOCK(object);
2118 		}
2119 		return (NULL);
2120 	}
2121 
2122 	/* Ignore device objects; the pager sets "memattr" for them. */
2123 	if (object->memattr != VM_MEMATTR_DEFAULT &&
2124 	    (object->flags & OBJ_FICTITIOUS) == 0)
2125 		pmap_page_set_memattr(m, object->memattr);
2126 
2127 	return (m);
2128 }
2129 
2130 /*
2131  *	vm_page_alloc_contig:
2132  *
2133  *	Allocate a contiguous set of physical pages of the given size "npages"
2134  *	from the free lists.  All of the physical pages must be at or above
2135  *	the given physical address "low" and below the given physical address
2136  *	"high".  The given value "alignment" determines the alignment of the
2137  *	first physical page in the set.  If the given value "boundary" is
2138  *	non-zero, then the set of physical pages cannot cross any physical
2139  *	address boundary that is a multiple of that value.  Both "alignment"
2140  *	and "boundary" must be a power of two.
2141  *
2142  *	If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
2143  *	then the memory attribute setting for the physical pages is configured
2144  *	to the object's memory attribute setting.  Otherwise, the memory
2145  *	attribute setting for the physical pages is configured to "memattr",
2146  *	overriding the object's memory attribute setting.  However, if the
2147  *	object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
2148  *	memory attribute setting for the physical pages cannot be configured
2149  *	to VM_MEMATTR_DEFAULT.
2150  *
2151  *	The specified object may not contain fictitious pages.
2152  *
2153  *	The caller must always specify an allocation class.
2154  *
2155  *	allocation classes:
2156  *	VM_ALLOC_NORMAL		normal process request
2157  *	VM_ALLOC_SYSTEM		system *really* needs a page
2158  *	VM_ALLOC_INTERRUPT	interrupt time request
2159  *
2160  *	optional allocation flags:
2161  *	VM_ALLOC_NOBUSY		do not exclusive busy the page
2162  *	VM_ALLOC_NODUMP		do not include the page in a kernel core dump
2163  *	VM_ALLOC_SBUSY		shared busy the allocated page
2164  *	VM_ALLOC_WIRED		wire the allocated page
2165  *	VM_ALLOC_ZERO		prefer a zeroed page
2166  */
2167 vm_page_t
2168 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
2169     u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2170     vm_paddr_t boundary, vm_memattr_t memattr)
2171 {
2172 	struct vm_domainset_iter di;
2173 	vm_page_t bounds[2];
2174 	vm_page_t m;
2175 	int domain;
2176 	int start_segind;
2177 
2178 	start_segind = -1;
2179 
2180 	vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
2181 	do {
2182 		m = vm_page_alloc_contig_domain(object, pindex, domain, req,
2183 		    npages, low, high, alignment, boundary, memattr);
2184 		if (m != NULL)
2185 			break;
2186 		if (start_segind == -1)
2187 			start_segind = vm_phys_lookup_segind(low);
2188 		if (vm_phys_find_range(bounds, start_segind, domain,
2189 		    npages, low, high) == -1) {
2190 			vm_domainset_iter_ignore(&di, domain);
2191 		}
2192 	} while (vm_domainset_iter_page(&di, object, &domain) == 0);
2193 
2194 	return (m);
2195 }
2196 
2197 static vm_page_t
2198 vm_page_find_contig_domain(int domain, int req, u_long npages, vm_paddr_t low,
2199     vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2200 {
2201 	struct vm_domain *vmd;
2202 	vm_page_t m_ret;
2203 
2204 	/*
2205 	 * Can we allocate the pages without the number of free pages falling
2206 	 * below the lower bound for the allocation class?
2207 	 */
2208 	vmd = VM_DOMAIN(domain);
2209 	if (!vm_domain_allocate(vmd, req, npages))
2210 		return (NULL);
2211 	/*
2212 	 * Try to allocate the pages from the free page queues.
2213 	 */
2214 	vm_domain_free_lock(vmd);
2215 	m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2216 	    alignment, boundary);
2217 	vm_domain_free_unlock(vmd);
2218 	if (m_ret != NULL)
2219 		return (m_ret);
2220 #if VM_NRESERVLEVEL > 0
2221 	/*
2222 	 * Try to break a reservation to allocate the pages.
2223 	 */
2224 	if ((req & VM_ALLOC_NORECLAIM) == 0) {
2225 		m_ret = vm_reserv_reclaim_contig(domain, npages, low,
2226 	            high, alignment, boundary);
2227 		if (m_ret != NULL)
2228 			return (m_ret);
2229 	}
2230 #endif
2231 	vm_domain_freecnt_inc(vmd, npages);
2232 	return (NULL);
2233 }
2234 
2235 vm_page_t
2236 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
2237     int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2238     vm_paddr_t boundary, vm_memattr_t memattr)
2239 {
2240 	vm_page_t m, m_ret, mpred;
2241 	u_int busy_lock, flags, oflags;
2242 
2243 #define	VPAC_FLAGS	(VPA_FLAGS | VM_ALLOC_NORECLAIM)
2244 	KASSERT((req & ~VPAC_FLAGS) == 0,
2245 	    ("invalid request %#x", req));
2246 	KASSERT(((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2247 	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2248 	    ("invalid request %#x", req));
2249 	KASSERT((req & (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM)) !=
2250 	    (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM),
2251 	    ("invalid request %#x", req));
2252 	VM_OBJECT_ASSERT_WLOCKED(object);
2253 	KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2254 	    ("vm_page_alloc_contig: object %p has fictitious pages",
2255 	    object));
2256 	KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2257 
2258 	mpred = vm_radix_lookup_le(&object->rtree, pindex);
2259 	KASSERT(mpred == NULL || mpred->pindex != pindex,
2260 	    ("vm_page_alloc_contig: pindex already allocated"));
2261 	for (;;) {
2262 #if VM_NRESERVLEVEL > 0
2263 		/*
2264 		 * Can we allocate the pages from a reservation?
2265 		 */
2266 		if (vm_object_reserv(object) &&
2267 		    (m_ret = vm_reserv_alloc_contig(object, pindex, domain, req,
2268 		    mpred, npages, low, high, alignment, boundary)) != NULL) {
2269 			break;
2270 		}
2271 #endif
2272 		if ((m_ret = vm_page_find_contig_domain(domain, req, npages,
2273 		    low, high, alignment, boundary)) != NULL)
2274 			break;
2275 		if (!vm_domain_alloc_fail(VM_DOMAIN(domain), object, req))
2276 			return (NULL);
2277 	}
2278 	for (m = m_ret; m < &m_ret[npages]; m++) {
2279 		vm_page_dequeue(m);
2280 		vm_page_alloc_check(m);
2281 	}
2282 
2283 	/*
2284 	 * Initialize the pages.  Only the PG_ZERO flag is inherited.
2285 	 */
2286 	flags = PG_ZERO;
2287 	if ((req & VM_ALLOC_NODUMP) != 0)
2288 		flags |= PG_NODUMP;
2289 	oflags = (object->flags & OBJ_UNMANAGED) != 0 ? VPO_UNMANAGED : 0;
2290 	if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
2291 		busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2292 	else if ((req & VM_ALLOC_SBUSY) != 0)
2293 		busy_lock = VPB_SHARERS_WORD(1);
2294 	else
2295 		busy_lock = VPB_UNBUSIED;
2296 	if ((req & VM_ALLOC_WIRED) != 0)
2297 		vm_wire_add(npages);
2298 	if (object->memattr != VM_MEMATTR_DEFAULT &&
2299 	    memattr == VM_MEMATTR_DEFAULT)
2300 		memattr = object->memattr;
2301 	for (m = m_ret; m < &m_ret[npages]; m++) {
2302 		m->a.flags = 0;
2303 		m->flags = (m->flags | PG_NODUMP) & flags;
2304 		m->busy_lock = busy_lock;
2305 		if ((req & VM_ALLOC_WIRED) != 0)
2306 			m->ref_count = 1;
2307 		m->a.act_count = 0;
2308 		m->oflags = oflags;
2309 		if (vm_page_insert_after(m, object, pindex, mpred)) {
2310 			if ((req & VM_ALLOC_WIRED) != 0)
2311 				vm_wire_sub(npages);
2312 			KASSERT(m->object == NULL,
2313 			    ("page %p has object", m));
2314 			mpred = m;
2315 			for (m = m_ret; m < &m_ret[npages]; m++) {
2316 				if (m <= mpred &&
2317 				    (req & VM_ALLOC_WIRED) != 0)
2318 					m->ref_count = 0;
2319 				m->oflags = VPO_UNMANAGED;
2320 				m->busy_lock = VPB_UNBUSIED;
2321 				/* Don't change PG_ZERO. */
2322 				vm_page_free_toq(m);
2323 			}
2324 			if (req & VM_ALLOC_WAITFAIL) {
2325 				VM_OBJECT_WUNLOCK(object);
2326 				vm_radix_wait();
2327 				VM_OBJECT_WLOCK(object);
2328 			}
2329 			return (NULL);
2330 		}
2331 		mpred = m;
2332 		if (memattr != VM_MEMATTR_DEFAULT)
2333 			pmap_page_set_memattr(m, memattr);
2334 		pindex++;
2335 	}
2336 	return (m_ret);
2337 }
2338 
2339 /*
2340  * Allocate a physical page that is not intended to be inserted into a VM
2341  * object.  If the "freelist" parameter is not equal to VM_NFREELIST, then only
2342  * pages from the specified vm_phys freelist will be returned.
2343  */
2344 static __always_inline vm_page_t
2345 _vm_page_alloc_noobj_domain(int domain, const int freelist, int req)
2346 {
2347 	struct vm_domain *vmd;
2348 	vm_page_t m;
2349 	int flags;
2350 
2351 #define	VPAN_FLAGS	(VM_ALLOC_CLASS_MASK | VM_ALLOC_WAITFAIL |      \
2352 			 VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK |		\
2353 			 VM_ALLOC_NOBUSY | VM_ALLOC_WIRED |		\
2354 			 VM_ALLOC_NODUMP | VM_ALLOC_ZERO | VM_ALLOC_COUNT_MASK)
2355 	KASSERT((req & ~VPAN_FLAGS) == 0,
2356 	    ("invalid request %#x", req));
2357 
2358 	flags = (req & VM_ALLOC_NODUMP) != 0 ? PG_NODUMP : 0;
2359 	vmd = VM_DOMAIN(domain);
2360 again:
2361 	if (freelist == VM_NFREELIST &&
2362 	    vmd->vmd_pgcache[VM_FREEPOOL_DIRECT].zone != NULL) {
2363 		m = uma_zalloc(vmd->vmd_pgcache[VM_FREEPOOL_DIRECT].zone,
2364 		    M_NOWAIT | M_NOVM);
2365 		if (m != NULL) {
2366 			flags |= PG_PCPU_CACHE;
2367 			goto found;
2368 		}
2369 	}
2370 
2371 	if (vm_domain_allocate(vmd, req, 1)) {
2372 		vm_domain_free_lock(vmd);
2373 		if (freelist == VM_NFREELIST)
2374 			m = vm_phys_alloc_pages(domain, VM_FREEPOOL_DIRECT, 0);
2375 		else
2376 			m = vm_phys_alloc_freelist_pages(domain, freelist,
2377 			    VM_FREEPOOL_DIRECT, 0);
2378 		vm_domain_free_unlock(vmd);
2379 		if (m == NULL) {
2380 			vm_domain_freecnt_inc(vmd, 1);
2381 #if VM_NRESERVLEVEL > 0
2382 			if (freelist == VM_NFREELIST &&
2383 			    vm_reserv_reclaim_inactive(domain))
2384 				goto again;
2385 #endif
2386 		}
2387 	}
2388 	if (m == NULL) {
2389 		if (vm_domain_alloc_fail(vmd, NULL, req))
2390 			goto again;
2391 		return (NULL);
2392 	}
2393 
2394 found:
2395 	vm_page_dequeue(m);
2396 	vm_page_alloc_check(m);
2397 
2398 	/*
2399 	 * Consumers should not rely on a useful default pindex value.
2400 	 */
2401 	m->pindex = 0xdeadc0dedeadc0de;
2402 	m->flags = (m->flags & PG_ZERO) | flags;
2403 	m->a.flags = 0;
2404 	m->oflags = VPO_UNMANAGED;
2405 	m->busy_lock = VPB_UNBUSIED;
2406 	if ((req & VM_ALLOC_WIRED) != 0) {
2407 		vm_wire_add(1);
2408 		m->ref_count = 1;
2409 	}
2410 
2411 	if ((req & VM_ALLOC_ZERO) != 0 && (m->flags & PG_ZERO) == 0)
2412 		pmap_zero_page(m);
2413 
2414 	return (m);
2415 }
2416 
2417 vm_page_t
2418 vm_page_alloc_freelist(int freelist, int req)
2419 {
2420 	struct vm_domainset_iter di;
2421 	vm_page_t m;
2422 	int domain;
2423 
2424 	vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2425 	do {
2426 		m = vm_page_alloc_freelist_domain(domain, freelist, req);
2427 		if (m != NULL)
2428 			break;
2429 	} while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2430 
2431 	return (m);
2432 }
2433 
2434 vm_page_t
2435 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2436 {
2437 	KASSERT(freelist >= 0 && freelist < VM_NFREELIST,
2438 	    ("%s: invalid freelist %d", __func__, freelist));
2439 
2440 	return (_vm_page_alloc_noobj_domain(domain, freelist, req));
2441 }
2442 
2443 vm_page_t
2444 vm_page_alloc_noobj(int req)
2445 {
2446 	struct vm_domainset_iter di;
2447 	vm_page_t m;
2448 	int domain;
2449 
2450 	vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2451 	do {
2452 		m = vm_page_alloc_noobj_domain(domain, req);
2453 		if (m != NULL)
2454 			break;
2455 	} while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2456 
2457 	return (m);
2458 }
2459 
2460 vm_page_t
2461 vm_page_alloc_noobj_domain(int domain, int req)
2462 {
2463 	return (_vm_page_alloc_noobj_domain(domain, VM_NFREELIST, req));
2464 }
2465 
2466 vm_page_t
2467 vm_page_alloc_noobj_contig(int req, u_long npages, vm_paddr_t low,
2468     vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
2469     vm_memattr_t memattr)
2470 {
2471 	struct vm_domainset_iter di;
2472 	vm_page_t m;
2473 	int domain;
2474 
2475 	vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2476 	do {
2477 		m = vm_page_alloc_noobj_contig_domain(domain, req, npages, low,
2478 		    high, alignment, boundary, memattr);
2479 		if (m != NULL)
2480 			break;
2481 	} while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2482 
2483 	return (m);
2484 }
2485 
2486 vm_page_t
2487 vm_page_alloc_noobj_contig_domain(int domain, int req, u_long npages,
2488     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
2489     vm_memattr_t memattr)
2490 {
2491 	vm_page_t m, m_ret;
2492 	u_int flags;
2493 
2494 #define	VPANC_FLAGS	(VPAN_FLAGS | VM_ALLOC_NORECLAIM)
2495 	KASSERT((req & ~VPANC_FLAGS) == 0,
2496 	    ("invalid request %#x", req));
2497 	KASSERT((req & (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM)) !=
2498 	    (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM),
2499 	    ("invalid request %#x", req));
2500 	KASSERT(((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2501 	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2502 	    ("invalid request %#x", req));
2503 	KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2504 
2505 	while ((m_ret = vm_page_find_contig_domain(domain, req, npages,
2506 	    low, high, alignment, boundary)) == NULL) {
2507 		if (!vm_domain_alloc_fail(VM_DOMAIN(domain), NULL, req))
2508 			return (NULL);
2509 	}
2510 
2511 	/*
2512 	 * Initialize the pages.  Only the PG_ZERO flag is inherited.
2513 	 */
2514 	flags = PG_ZERO;
2515 	if ((req & VM_ALLOC_NODUMP) != 0)
2516 		flags |= PG_NODUMP;
2517 	if ((req & VM_ALLOC_WIRED) != 0)
2518 		vm_wire_add(npages);
2519 	for (m = m_ret; m < &m_ret[npages]; m++) {
2520 		vm_page_dequeue(m);
2521 		vm_page_alloc_check(m);
2522 
2523 		/*
2524 		 * Consumers should not rely on a useful default pindex value.
2525 		 */
2526 		m->pindex = 0xdeadc0dedeadc0de;
2527 		m->a.flags = 0;
2528 		m->flags = (m->flags | PG_NODUMP) & flags;
2529 		m->busy_lock = VPB_UNBUSIED;
2530 		if ((req & VM_ALLOC_WIRED) != 0)
2531 			m->ref_count = 1;
2532 		m->a.act_count = 0;
2533 		m->oflags = VPO_UNMANAGED;
2534 
2535 		/*
2536 		 * Zero the page before updating any mappings since the page is
2537 		 * not yet shared with any devices which might require the
2538 		 * non-default memory attribute.  pmap_page_set_memattr()
2539 		 * flushes data caches before returning.
2540 		 */
2541 		if ((req & VM_ALLOC_ZERO) != 0 && (m->flags & PG_ZERO) == 0)
2542 			pmap_zero_page(m);
2543 		if (memattr != VM_MEMATTR_DEFAULT)
2544 			pmap_page_set_memattr(m, memattr);
2545 	}
2546 	return (m_ret);
2547 }
2548 
2549 /*
2550  * Check a page that has been freshly dequeued from a freelist.
2551  */
2552 static void
2553 vm_page_alloc_check(vm_page_t m)
2554 {
2555 
2556 	KASSERT(m->object == NULL, ("page %p has object", m));
2557 	KASSERT(m->a.queue == PQ_NONE &&
2558 	    (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
2559 	    ("page %p has unexpected queue %d, flags %#x",
2560 	    m, m->a.queue, (m->a.flags & PGA_QUEUE_STATE_MASK)));
2561 	KASSERT(m->ref_count == 0, ("page %p has references", m));
2562 	KASSERT(vm_page_busy_freed(m), ("page %p is not freed", m));
2563 	KASSERT(m->dirty == 0, ("page %p is dirty", m));
2564 	KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2565 	    ("page %p has unexpected memattr %d",
2566 	    m, pmap_page_get_memattr(m)));
2567 	KASSERT(vm_page_none_valid(m), ("free page %p is valid", m));
2568 	pmap_vm_page_alloc_check(m);
2569 }
2570 
2571 static int
2572 vm_page_zone_import(void *arg, void **store, int cnt, int domain, int flags)
2573 {
2574 	struct vm_domain *vmd;
2575 	struct vm_pgcache *pgcache;
2576 	int i;
2577 
2578 	pgcache = arg;
2579 	vmd = VM_DOMAIN(pgcache->domain);
2580 
2581 	/*
2582 	 * The page daemon should avoid creating extra memory pressure since its
2583 	 * main purpose is to replenish the store of free pages.
2584 	 */
2585 	if (vmd->vmd_severeset || curproc == pageproc ||
2586 	    !_vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2587 		return (0);
2588 	domain = vmd->vmd_domain;
2589 	vm_domain_free_lock(vmd);
2590 	i = vm_phys_alloc_npages(domain, pgcache->pool, cnt,
2591 	    (vm_page_t *)store);
2592 	vm_domain_free_unlock(vmd);
2593 	if (cnt != i)
2594 		vm_domain_freecnt_inc(vmd, cnt - i);
2595 
2596 	return (i);
2597 }
2598 
2599 static void
2600 vm_page_zone_release(void *arg, void **store, int cnt)
2601 {
2602 	struct vm_domain *vmd;
2603 	struct vm_pgcache *pgcache;
2604 	vm_page_t m;
2605 	int i;
2606 
2607 	pgcache = arg;
2608 	vmd = VM_DOMAIN(pgcache->domain);
2609 	vm_domain_free_lock(vmd);
2610 	for (i = 0; i < cnt; i++) {
2611 		m = (vm_page_t)store[i];
2612 		vm_phys_free_pages(m, 0);
2613 	}
2614 	vm_domain_free_unlock(vmd);
2615 	vm_domain_freecnt_inc(vmd, cnt);
2616 }
2617 
2618 #define	VPSC_ANY	0	/* No restrictions. */
2619 #define	VPSC_NORESERV	1	/* Skip reservations; implies VPSC_NOSUPER. */
2620 #define	VPSC_NOSUPER	2	/* Skip superpages. */
2621 
2622 /*
2623  *	vm_page_scan_contig:
2624  *
2625  *	Scan vm_page_array[] between the specified entries "m_start" and
2626  *	"m_end" for a run of contiguous physical pages that satisfy the
2627  *	specified conditions, and return the lowest page in the run.  The
2628  *	specified "alignment" determines the alignment of the lowest physical
2629  *	page in the run.  If the specified "boundary" is non-zero, then the
2630  *	run of physical pages cannot span a physical address that is a
2631  *	multiple of "boundary".
2632  *
2633  *	"m_end" is never dereferenced, so it need not point to a vm_page
2634  *	structure within vm_page_array[].
2635  *
2636  *	"npages" must be greater than zero.  "m_start" and "m_end" must not
2637  *	span a hole (or discontiguity) in the physical address space.  Both
2638  *	"alignment" and "boundary" must be a power of two.
2639  */
2640 static vm_page_t
2641 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2642     u_long alignment, vm_paddr_t boundary, int options)
2643 {
2644 	vm_object_t object;
2645 	vm_paddr_t pa;
2646 	vm_page_t m, m_run;
2647 #if VM_NRESERVLEVEL > 0
2648 	int level;
2649 #endif
2650 	int m_inc, order, run_ext, run_len;
2651 
2652 	KASSERT(npages > 0, ("npages is 0"));
2653 	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2654 	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2655 	m_run = NULL;
2656 	run_len = 0;
2657 	for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2658 		KASSERT((m->flags & PG_MARKER) == 0,
2659 		    ("page %p is PG_MARKER", m));
2660 		KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->ref_count >= 1,
2661 		    ("fictitious page %p has invalid ref count", m));
2662 
2663 		/*
2664 		 * If the current page would be the start of a run, check its
2665 		 * physical address against the end, alignment, and boundary
2666 		 * conditions.  If it doesn't satisfy these conditions, either
2667 		 * terminate the scan or advance to the next page that
2668 		 * satisfies the failed condition.
2669 		 */
2670 		if (run_len == 0) {
2671 			KASSERT(m_run == NULL, ("m_run != NULL"));
2672 			if (m + npages > m_end)
2673 				break;
2674 			pa = VM_PAGE_TO_PHYS(m);
2675 			if (!vm_addr_align_ok(pa, alignment)) {
2676 				m_inc = atop(roundup2(pa, alignment) - pa);
2677 				continue;
2678 			}
2679 			if (!vm_addr_bound_ok(pa, ptoa(npages), boundary)) {
2680 				m_inc = atop(roundup2(pa, boundary) - pa);
2681 				continue;
2682 			}
2683 		} else
2684 			KASSERT(m_run != NULL, ("m_run == NULL"));
2685 
2686 retry:
2687 		m_inc = 1;
2688 		if (vm_page_wired(m))
2689 			run_ext = 0;
2690 #if VM_NRESERVLEVEL > 0
2691 		else if ((level = vm_reserv_level(m)) >= 0 &&
2692 		    (options & VPSC_NORESERV) != 0) {
2693 			run_ext = 0;
2694 			/* Advance to the end of the reservation. */
2695 			pa = VM_PAGE_TO_PHYS(m);
2696 			m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2697 			    pa);
2698 		}
2699 #endif
2700 		else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2701 			/*
2702 			 * The page is considered eligible for relocation if
2703 			 * and only if it could be laundered or reclaimed by
2704 			 * the page daemon.
2705 			 */
2706 			VM_OBJECT_RLOCK(object);
2707 			if (object != m->object) {
2708 				VM_OBJECT_RUNLOCK(object);
2709 				goto retry;
2710 			}
2711 			/* Don't care: PG_NODUMP, PG_ZERO. */
2712 			if ((object->flags & OBJ_SWAP) == 0 &&
2713 			    object->type != OBJT_VNODE) {
2714 				run_ext = 0;
2715 #if VM_NRESERVLEVEL > 0
2716 			} else if ((options & VPSC_NOSUPER) != 0 &&
2717 			    (level = vm_reserv_level_iffullpop(m)) >= 0) {
2718 				run_ext = 0;
2719 				/* Advance to the end of the superpage. */
2720 				pa = VM_PAGE_TO_PHYS(m);
2721 				m_inc = atop(roundup2(pa + 1,
2722 				    vm_reserv_size(level)) - pa);
2723 #endif
2724 			} else if (object->memattr == VM_MEMATTR_DEFAULT &&
2725 			    vm_page_queue(m) != PQ_NONE && !vm_page_busied(m)) {
2726 				/*
2727 				 * The page is allocated but eligible for
2728 				 * relocation.  Extend the current run by one
2729 				 * page.
2730 				 */
2731 				KASSERT(pmap_page_get_memattr(m) ==
2732 				    VM_MEMATTR_DEFAULT,
2733 				    ("page %p has an unexpected memattr", m));
2734 				KASSERT((m->oflags & (VPO_SWAPINPROG |
2735 				    VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2736 				    ("page %p has unexpected oflags", m));
2737 				/* Don't care: PGA_NOSYNC. */
2738 				run_ext = 1;
2739 			} else
2740 				run_ext = 0;
2741 			VM_OBJECT_RUNLOCK(object);
2742 #if VM_NRESERVLEVEL > 0
2743 		} else if (level >= 0) {
2744 			/*
2745 			 * The page is reserved but not yet allocated.  In
2746 			 * other words, it is still free.  Extend the current
2747 			 * run by one page.
2748 			 */
2749 			run_ext = 1;
2750 #endif
2751 		} else if ((order = m->order) < VM_NFREEORDER) {
2752 			/*
2753 			 * The page is enqueued in the physical memory
2754 			 * allocator's free page queues.  Moreover, it is the
2755 			 * first page in a power-of-two-sized run of
2756 			 * contiguous free pages.  Add these pages to the end
2757 			 * of the current run, and jump ahead.
2758 			 */
2759 			run_ext = 1 << order;
2760 			m_inc = 1 << order;
2761 		} else {
2762 			/*
2763 			 * Skip the page for one of the following reasons: (1)
2764 			 * It is enqueued in the physical memory allocator's
2765 			 * free page queues.  However, it is not the first
2766 			 * page in a run of contiguous free pages.  (This case
2767 			 * rarely occurs because the scan is performed in
2768 			 * ascending order.) (2) It is not reserved, and it is
2769 			 * transitioning from free to allocated.  (Conversely,
2770 			 * the transition from allocated to free for managed
2771 			 * pages is blocked by the page busy lock.) (3) It is
2772 			 * allocated but not contained by an object and not
2773 			 * wired, e.g., allocated by Xen's balloon driver.
2774 			 */
2775 			run_ext = 0;
2776 		}
2777 
2778 		/*
2779 		 * Extend or reset the current run of pages.
2780 		 */
2781 		if (run_ext > 0) {
2782 			if (run_len == 0)
2783 				m_run = m;
2784 			run_len += run_ext;
2785 		} else {
2786 			if (run_len > 0) {
2787 				m_run = NULL;
2788 				run_len = 0;
2789 			}
2790 		}
2791 	}
2792 	if (run_len >= npages)
2793 		return (m_run);
2794 	return (NULL);
2795 }
2796 
2797 /*
2798  *	vm_page_reclaim_run:
2799  *
2800  *	Try to relocate each of the allocated virtual pages within the
2801  *	specified run of physical pages to a new physical address.  Free the
2802  *	physical pages underlying the relocated virtual pages.  A virtual page
2803  *	is relocatable if and only if it could be laundered or reclaimed by
2804  *	the page daemon.  Whenever possible, a virtual page is relocated to a
2805  *	physical address above "high".
2806  *
2807  *	Returns 0 if every physical page within the run was already free or
2808  *	just freed by a successful relocation.  Otherwise, returns a non-zero
2809  *	value indicating why the last attempt to relocate a virtual page was
2810  *	unsuccessful.
2811  *
2812  *	"req_class" must be an allocation class.
2813  */
2814 static int
2815 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2816     vm_paddr_t high)
2817 {
2818 	struct vm_domain *vmd;
2819 	struct spglist free;
2820 	vm_object_t object;
2821 	vm_paddr_t pa;
2822 	vm_page_t m, m_end, m_new;
2823 	int error, order, req;
2824 
2825 	KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2826 	    ("req_class is not an allocation class"));
2827 	SLIST_INIT(&free);
2828 	error = 0;
2829 	m = m_run;
2830 	m_end = m_run + npages;
2831 	for (; error == 0 && m < m_end; m++) {
2832 		KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2833 		    ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2834 
2835 		/*
2836 		 * Racily check for wirings.  Races are handled once the object
2837 		 * lock is held and the page is unmapped.
2838 		 */
2839 		if (vm_page_wired(m))
2840 			error = EBUSY;
2841 		else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2842 			/*
2843 			 * The page is relocated if and only if it could be
2844 			 * laundered or reclaimed by the page daemon.
2845 			 */
2846 			VM_OBJECT_WLOCK(object);
2847 			/* Don't care: PG_NODUMP, PG_ZERO. */
2848 			if (m->object != object ||
2849 			    ((object->flags & OBJ_SWAP) == 0 &&
2850 			    object->type != OBJT_VNODE))
2851 				error = EINVAL;
2852 			else if (object->memattr != VM_MEMATTR_DEFAULT)
2853 				error = EINVAL;
2854 			else if (vm_page_queue(m) != PQ_NONE &&
2855 			    vm_page_tryxbusy(m) != 0) {
2856 				if (vm_page_wired(m)) {
2857 					vm_page_xunbusy(m);
2858 					error = EBUSY;
2859 					goto unlock;
2860 				}
2861 				KASSERT(pmap_page_get_memattr(m) ==
2862 				    VM_MEMATTR_DEFAULT,
2863 				    ("page %p has an unexpected memattr", m));
2864 				KASSERT(m->oflags == 0,
2865 				    ("page %p has unexpected oflags", m));
2866 				/* Don't care: PGA_NOSYNC. */
2867 				if (!vm_page_none_valid(m)) {
2868 					/*
2869 					 * First, try to allocate a new page
2870 					 * that is above "high".  Failing
2871 					 * that, try to allocate a new page
2872 					 * that is below "m_run".  Allocate
2873 					 * the new page between the end of
2874 					 * "m_run" and "high" only as a last
2875 					 * resort.
2876 					 */
2877 					req = req_class;
2878 					if ((m->flags & PG_NODUMP) != 0)
2879 						req |= VM_ALLOC_NODUMP;
2880 					if (trunc_page(high) !=
2881 					    ~(vm_paddr_t)PAGE_MASK) {
2882 						m_new =
2883 						    vm_page_alloc_noobj_contig(
2884 						    req, 1, round_page(high),
2885 						    ~(vm_paddr_t)0, PAGE_SIZE,
2886 						    0, VM_MEMATTR_DEFAULT);
2887 					} else
2888 						m_new = NULL;
2889 					if (m_new == NULL) {
2890 						pa = VM_PAGE_TO_PHYS(m_run);
2891 						m_new =
2892 						    vm_page_alloc_noobj_contig(
2893 						    req, 1, 0, pa - 1,
2894 						    PAGE_SIZE, 0,
2895 						    VM_MEMATTR_DEFAULT);
2896 					}
2897 					if (m_new == NULL) {
2898 						pa += ptoa(npages);
2899 						m_new =
2900 						    vm_page_alloc_noobj_contig(
2901 						    req, 1, pa, high, PAGE_SIZE,
2902 						    0, VM_MEMATTR_DEFAULT);
2903 					}
2904 					if (m_new == NULL) {
2905 						vm_page_xunbusy(m);
2906 						error = ENOMEM;
2907 						goto unlock;
2908 					}
2909 
2910 					/*
2911 					 * Unmap the page and check for new
2912 					 * wirings that may have been acquired
2913 					 * through a pmap lookup.
2914 					 */
2915 					if (object->ref_count != 0 &&
2916 					    !vm_page_try_remove_all(m)) {
2917 						vm_page_xunbusy(m);
2918 						vm_page_free(m_new);
2919 						error = EBUSY;
2920 						goto unlock;
2921 					}
2922 
2923 					/*
2924 					 * Replace "m" with the new page.  For
2925 					 * vm_page_replace(), "m" must be busy
2926 					 * and dequeued.  Finally, change "m"
2927 					 * as if vm_page_free() was called.
2928 					 */
2929 					m_new->a.flags = m->a.flags &
2930 					    ~PGA_QUEUE_STATE_MASK;
2931 					KASSERT(m_new->oflags == VPO_UNMANAGED,
2932 					    ("page %p is managed", m_new));
2933 					m_new->oflags = 0;
2934 					pmap_copy_page(m, m_new);
2935 					m_new->valid = m->valid;
2936 					m_new->dirty = m->dirty;
2937 					m->flags &= ~PG_ZERO;
2938 					vm_page_dequeue(m);
2939 					if (vm_page_replace_hold(m_new, object,
2940 					    m->pindex, m) &&
2941 					    vm_page_free_prep(m))
2942 						SLIST_INSERT_HEAD(&free, m,
2943 						    plinks.s.ss);
2944 
2945 					/*
2946 					 * The new page must be deactivated
2947 					 * before the object is unlocked.
2948 					 */
2949 					vm_page_deactivate(m_new);
2950 				} else {
2951 					m->flags &= ~PG_ZERO;
2952 					vm_page_dequeue(m);
2953 					if (vm_page_free_prep(m))
2954 						SLIST_INSERT_HEAD(&free, m,
2955 						    plinks.s.ss);
2956 					KASSERT(m->dirty == 0,
2957 					    ("page %p is dirty", m));
2958 				}
2959 			} else
2960 				error = EBUSY;
2961 unlock:
2962 			VM_OBJECT_WUNLOCK(object);
2963 		} else {
2964 			MPASS(vm_page_domain(m) == domain);
2965 			vmd = VM_DOMAIN(domain);
2966 			vm_domain_free_lock(vmd);
2967 			order = m->order;
2968 			if (order < VM_NFREEORDER) {
2969 				/*
2970 				 * The page is enqueued in the physical memory
2971 				 * allocator's free page queues.  Moreover, it
2972 				 * is the first page in a power-of-two-sized
2973 				 * run of contiguous free pages.  Jump ahead
2974 				 * to the last page within that run, and
2975 				 * continue from there.
2976 				 */
2977 				m += (1 << order) - 1;
2978 			}
2979 #if VM_NRESERVLEVEL > 0
2980 			else if (vm_reserv_is_page_free(m))
2981 				order = 0;
2982 #endif
2983 			vm_domain_free_unlock(vmd);
2984 			if (order == VM_NFREEORDER)
2985 				error = EINVAL;
2986 		}
2987 	}
2988 	if ((m = SLIST_FIRST(&free)) != NULL) {
2989 		int cnt;
2990 
2991 		vmd = VM_DOMAIN(domain);
2992 		cnt = 0;
2993 		vm_domain_free_lock(vmd);
2994 		do {
2995 			MPASS(vm_page_domain(m) == domain);
2996 			SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2997 			vm_phys_free_pages(m, 0);
2998 			cnt++;
2999 		} while ((m = SLIST_FIRST(&free)) != NULL);
3000 		vm_domain_free_unlock(vmd);
3001 		vm_domain_freecnt_inc(vmd, cnt);
3002 	}
3003 	return (error);
3004 }
3005 
3006 #define	NRUNS	16
3007 
3008 #define	RUN_INDEX(count, nruns)	((count) % (nruns))
3009 
3010 #define	MIN_RECLAIM	8
3011 
3012 /*
3013  *	vm_page_reclaim_contig:
3014  *
3015  *	Reclaim allocated, contiguous physical memory satisfying the specified
3016  *	conditions by relocating the virtual pages using that physical memory.
3017  *	Returns 0 if reclamation is successful, ERANGE if the specified domain
3018  *	can't possibly satisfy the reclamation request, or ENOMEM if not
3019  *	currently able to reclaim the requested number of pages.  Since
3020  *	relocation requires the allocation of physical pages, reclamation may
3021  *	fail with ENOMEM due to a shortage of free pages.  When reclamation
3022  *	fails in this manner, callers are expected to perform vm_wait() before
3023  *	retrying a failed allocation operation, e.g., vm_page_alloc_contig().
3024  *
3025  *	The caller must always specify an allocation class through "req".
3026  *
3027  *	allocation classes:
3028  *	VM_ALLOC_NORMAL		normal process request
3029  *	VM_ALLOC_SYSTEM		system *really* needs a page
3030  *	VM_ALLOC_INTERRUPT	interrupt time request
3031  *
3032  *	The optional allocation flags are ignored.
3033  *
3034  *	"npages" must be greater than zero.  Both "alignment" and "boundary"
3035  *	must be a power of two.
3036  */
3037 int
3038 vm_page_reclaim_contig_domain_ext(int domain, int req, u_long npages,
3039     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
3040     int desired_runs)
3041 {
3042 	struct vm_domain *vmd;
3043 	vm_page_t bounds[2], m_run, _m_runs[NRUNS], *m_runs;
3044 	u_long count, minalign, reclaimed;
3045 	int error, i, min_reclaim, nruns, options, req_class;
3046 	int segind, start_segind;
3047 	int ret;
3048 
3049 	KASSERT(npages > 0, ("npages is 0"));
3050 	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
3051 	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
3052 
3053 	ret = ENOMEM;
3054 
3055 	/*
3056 	 * If the caller wants to reclaim multiple runs, try to allocate
3057 	 * space to store the runs.  If that fails, fall back to the old
3058 	 * behavior of just reclaiming MIN_RECLAIM pages.
3059 	 */
3060 	if (desired_runs > 1)
3061 		m_runs = malloc((NRUNS + desired_runs) * sizeof(*m_runs),
3062 		    M_TEMP, M_NOWAIT);
3063 	else
3064 		m_runs = NULL;
3065 
3066 	if (m_runs == NULL) {
3067 		m_runs = _m_runs;
3068 		nruns = NRUNS;
3069 	} else {
3070 		nruns = NRUNS + desired_runs - 1;
3071 	}
3072 	min_reclaim = MAX(desired_runs * npages, MIN_RECLAIM);
3073 
3074 	/*
3075 	 * The caller will attempt an allocation after some runs have been
3076 	 * reclaimed and added to the vm_phys buddy lists.  Due to limitations
3077 	 * of vm_phys_alloc_contig(), round up the requested length to the next
3078 	 * power of two or maximum chunk size, and ensure that each run is
3079 	 * suitably aligned.
3080 	 */
3081 	minalign = 1ul << imin(flsl(npages - 1), VM_NFREEORDER - 1);
3082 	npages = roundup2(npages, minalign);
3083 	if (alignment < ptoa(minalign))
3084 		alignment = ptoa(minalign);
3085 
3086 	/*
3087 	 * The page daemon is allowed to dig deeper into the free page list.
3088 	 */
3089 	req_class = req & VM_ALLOC_CLASS_MASK;
3090 	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
3091 		req_class = VM_ALLOC_SYSTEM;
3092 
3093 	start_segind = vm_phys_lookup_segind(low);
3094 
3095 	/*
3096 	 * Return if the number of free pages cannot satisfy the requested
3097 	 * allocation.
3098 	 */
3099 	vmd = VM_DOMAIN(domain);
3100 	count = vmd->vmd_free_count;
3101 	if (count < npages + vmd->vmd_free_reserved || (count < npages +
3102 	    vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
3103 	    (count < npages && req_class == VM_ALLOC_INTERRUPT))
3104 		goto done;
3105 
3106 	/*
3107 	 * Scan up to three times, relaxing the restrictions ("options") on
3108 	 * the reclamation of reservations and superpages each time.
3109 	 */
3110 	for (options = VPSC_NORESERV;;) {
3111 		bool phys_range_exists = false;
3112 
3113 		/*
3114 		 * Find the highest runs that satisfy the given constraints
3115 		 * and restrictions, and record them in "m_runs".
3116 		 */
3117 		count = 0;
3118 		segind = start_segind;
3119 		while ((segind = vm_phys_find_range(bounds, segind, domain,
3120 		    npages, low, high)) != -1) {
3121 			phys_range_exists = true;
3122 			while ((m_run = vm_page_scan_contig(npages, bounds[0],
3123 			    bounds[1], alignment, boundary, options))) {
3124 				bounds[0] = m_run + npages;
3125 				m_runs[RUN_INDEX(count, nruns)] = m_run;
3126 				count++;
3127 			}
3128 			segind++;
3129 		}
3130 
3131 		if (!phys_range_exists) {
3132 			ret = ERANGE;
3133 			goto done;
3134 		}
3135 
3136 		/*
3137 		 * Reclaim the highest runs in LIFO (descending) order until
3138 		 * the number of reclaimed pages, "reclaimed", is at least
3139 		 * "min_reclaim".  Reset "reclaimed" each time because each
3140 		 * reclamation is idempotent, and runs will (likely) recur
3141 		 * from one scan to the next as restrictions are relaxed.
3142 		 */
3143 		reclaimed = 0;
3144 		for (i = 0; count > 0 && i < nruns; i++) {
3145 			count--;
3146 			m_run = m_runs[RUN_INDEX(count, nruns)];
3147 			error = vm_page_reclaim_run(req_class, domain, npages,
3148 			    m_run, high);
3149 			if (error == 0) {
3150 				reclaimed += npages;
3151 				if (reclaimed >= min_reclaim) {
3152 					ret = 0;
3153 					goto done;
3154 				}
3155 			}
3156 		}
3157 
3158 		/*
3159 		 * Either relax the restrictions on the next scan or return if
3160 		 * the last scan had no restrictions.
3161 		 */
3162 		if (options == VPSC_NORESERV)
3163 			options = VPSC_NOSUPER;
3164 		else if (options == VPSC_NOSUPER)
3165 			options = VPSC_ANY;
3166 		else if (options == VPSC_ANY) {
3167 			if (reclaimed != 0)
3168 				ret = 0;
3169 			goto done;
3170 		}
3171 	}
3172 done:
3173 	if (m_runs != _m_runs)
3174 		free(m_runs, M_TEMP);
3175 	return (ret);
3176 }
3177 
3178 int
3179 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
3180     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
3181 {
3182 	return (vm_page_reclaim_contig_domain_ext(domain, req, npages, low, high,
3183 	    alignment, boundary, 1));
3184 }
3185 
3186 int
3187 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
3188     u_long alignment, vm_paddr_t boundary)
3189 {
3190 	struct vm_domainset_iter di;
3191 	int domain, ret, status;
3192 
3193 	ret = ERANGE;
3194 
3195 	vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
3196 	do {
3197 		status = vm_page_reclaim_contig_domain(domain, req, npages, low,
3198 		    high, alignment, boundary);
3199 		if (status == 0)
3200 			return (0);
3201 		else if (status == ERANGE)
3202 			vm_domainset_iter_ignore(&di, domain);
3203 		else {
3204 			KASSERT(status == ENOMEM, ("Unrecognized error %d "
3205 			    "from vm_page_reclaim_contig_domain()", status));
3206 			ret = ENOMEM;
3207 		}
3208 	} while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
3209 
3210 	return (ret);
3211 }
3212 
3213 /*
3214  * Set the domain in the appropriate page level domainset.
3215  */
3216 void
3217 vm_domain_set(struct vm_domain *vmd)
3218 {
3219 
3220 	mtx_lock(&vm_domainset_lock);
3221 	if (!vmd->vmd_minset && vm_paging_min(vmd)) {
3222 		vmd->vmd_minset = 1;
3223 		DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
3224 	}
3225 	if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
3226 		vmd->vmd_severeset = 1;
3227 		DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
3228 	}
3229 	mtx_unlock(&vm_domainset_lock);
3230 }
3231 
3232 /*
3233  * Clear the domain from the appropriate page level domainset.
3234  */
3235 void
3236 vm_domain_clear(struct vm_domain *vmd)
3237 {
3238 
3239 	mtx_lock(&vm_domainset_lock);
3240 	if (vmd->vmd_minset && !vm_paging_min(vmd)) {
3241 		vmd->vmd_minset = 0;
3242 		DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
3243 		if (vm_min_waiters != 0) {
3244 			vm_min_waiters = 0;
3245 			wakeup(&vm_min_domains);
3246 		}
3247 	}
3248 	if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
3249 		vmd->vmd_severeset = 0;
3250 		DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
3251 		if (vm_severe_waiters != 0) {
3252 			vm_severe_waiters = 0;
3253 			wakeup(&vm_severe_domains);
3254 		}
3255 	}
3256 
3257 	/*
3258 	 * If pageout daemon needs pages, then tell it that there are
3259 	 * some free.
3260 	 */
3261 	if (vmd->vmd_pageout_pages_needed &&
3262 	    vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
3263 		wakeup(&vmd->vmd_pageout_pages_needed);
3264 		vmd->vmd_pageout_pages_needed = 0;
3265 	}
3266 
3267 	/* See comments in vm_wait_doms(). */
3268 	if (vm_pageproc_waiters) {
3269 		vm_pageproc_waiters = 0;
3270 		wakeup(&vm_pageproc_waiters);
3271 	}
3272 	mtx_unlock(&vm_domainset_lock);
3273 }
3274 
3275 /*
3276  * Wait for free pages to exceed the min threshold globally.
3277  */
3278 void
3279 vm_wait_min(void)
3280 {
3281 
3282 	mtx_lock(&vm_domainset_lock);
3283 	while (vm_page_count_min()) {
3284 		vm_min_waiters++;
3285 		msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
3286 	}
3287 	mtx_unlock(&vm_domainset_lock);
3288 }
3289 
3290 /*
3291  * Wait for free pages to exceed the severe threshold globally.
3292  */
3293 void
3294 vm_wait_severe(void)
3295 {
3296 
3297 	mtx_lock(&vm_domainset_lock);
3298 	while (vm_page_count_severe()) {
3299 		vm_severe_waiters++;
3300 		msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
3301 		    "vmwait", 0);
3302 	}
3303 	mtx_unlock(&vm_domainset_lock);
3304 }
3305 
3306 u_int
3307 vm_wait_count(void)
3308 {
3309 
3310 	return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
3311 }
3312 
3313 int
3314 vm_wait_doms(const domainset_t *wdoms, int mflags)
3315 {
3316 	int error;
3317 
3318 	error = 0;
3319 
3320 	/*
3321 	 * We use racey wakeup synchronization to avoid expensive global
3322 	 * locking for the pageproc when sleeping with a non-specific vm_wait.
3323 	 * To handle this, we only sleep for one tick in this instance.  It
3324 	 * is expected that most allocations for the pageproc will come from
3325 	 * kmem or vm_page_grab* which will use the more specific and
3326 	 * race-free vm_wait_domain().
3327 	 */
3328 	if (curproc == pageproc) {
3329 		mtx_lock(&vm_domainset_lock);
3330 		vm_pageproc_waiters++;
3331 		error = msleep(&vm_pageproc_waiters, &vm_domainset_lock,
3332 		    PVM | PDROP | mflags, "pageprocwait", 1);
3333 	} else {
3334 		/*
3335 		 * XXX Ideally we would wait only until the allocation could
3336 		 * be satisfied.  This condition can cause new allocators to
3337 		 * consume all freed pages while old allocators wait.
3338 		 */
3339 		mtx_lock(&vm_domainset_lock);
3340 		if (vm_page_count_min_set(wdoms)) {
3341 			if (pageproc == NULL)
3342 				panic("vm_wait in early boot");
3343 			vm_min_waiters++;
3344 			error = msleep(&vm_min_domains, &vm_domainset_lock,
3345 			    PVM | PDROP | mflags, "vmwait", 0);
3346 		} else
3347 			mtx_unlock(&vm_domainset_lock);
3348 	}
3349 	return (error);
3350 }
3351 
3352 /*
3353  *	vm_wait_domain:
3354  *
3355  *	Sleep until free pages are available for allocation.
3356  *	- Called in various places after failed memory allocations.
3357  */
3358 void
3359 vm_wait_domain(int domain)
3360 {
3361 	struct vm_domain *vmd;
3362 	domainset_t wdom;
3363 
3364 	vmd = VM_DOMAIN(domain);
3365 	vm_domain_free_assert_unlocked(vmd);
3366 
3367 	if (curproc == pageproc) {
3368 		mtx_lock(&vm_domainset_lock);
3369 		if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
3370 			vmd->vmd_pageout_pages_needed = 1;
3371 			msleep(&vmd->vmd_pageout_pages_needed,
3372 			    &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
3373 		} else
3374 			mtx_unlock(&vm_domainset_lock);
3375 	} else {
3376 		DOMAINSET_ZERO(&wdom);
3377 		DOMAINSET_SET(vmd->vmd_domain, &wdom);
3378 		vm_wait_doms(&wdom, 0);
3379 	}
3380 }
3381 
3382 static int
3383 vm_wait_flags(vm_object_t obj, int mflags)
3384 {
3385 	struct domainset *d;
3386 
3387 	d = NULL;
3388 
3389 	/*
3390 	 * Carefully fetch pointers only once: the struct domainset
3391 	 * itself is ummutable but the pointer might change.
3392 	 */
3393 	if (obj != NULL)
3394 		d = obj->domain.dr_policy;
3395 	if (d == NULL)
3396 		d = curthread->td_domain.dr_policy;
3397 
3398 	return (vm_wait_doms(&d->ds_mask, mflags));
3399 }
3400 
3401 /*
3402  *	vm_wait:
3403  *
3404  *	Sleep until free pages are available for allocation in the
3405  *	affinity domains of the obj.  If obj is NULL, the domain set
3406  *	for the calling thread is used.
3407  *	Called in various places after failed memory allocations.
3408  */
3409 void
3410 vm_wait(vm_object_t obj)
3411 {
3412 	(void)vm_wait_flags(obj, 0);
3413 }
3414 
3415 int
3416 vm_wait_intr(vm_object_t obj)
3417 {
3418 	return (vm_wait_flags(obj, PCATCH));
3419 }
3420 
3421 /*
3422  *	vm_domain_alloc_fail:
3423  *
3424  *	Called when a page allocation function fails.  Informs the
3425  *	pagedaemon and performs the requested wait.  Requires the
3426  *	domain_free and object lock on entry.  Returns with the
3427  *	object lock held and free lock released.  Returns an error when
3428  *	retry is necessary.
3429  *
3430  */
3431 static int
3432 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3433 {
3434 
3435 	vm_domain_free_assert_unlocked(vmd);
3436 
3437 	atomic_add_int(&vmd->vmd_pageout_deficit,
3438 	    max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3439 	if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3440 		if (object != NULL)
3441 			VM_OBJECT_WUNLOCK(object);
3442 		vm_wait_domain(vmd->vmd_domain);
3443 		if (object != NULL)
3444 			VM_OBJECT_WLOCK(object);
3445 		if (req & VM_ALLOC_WAITOK)
3446 			return (EAGAIN);
3447 	}
3448 
3449 	return (0);
3450 }
3451 
3452 /*
3453  *	vm_waitpfault:
3454  *
3455  *	Sleep until free pages are available for allocation.
3456  *	- Called only in vm_fault so that processes page faulting
3457  *	  can be easily tracked.
3458  *	- Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3459  *	  processes will be able to grab memory first.  Do not change
3460  *	  this balance without careful testing first.
3461  */
3462 void
3463 vm_waitpfault(struct domainset *dset, int timo)
3464 {
3465 
3466 	/*
3467 	 * XXX Ideally we would wait only until the allocation could
3468 	 * be satisfied.  This condition can cause new allocators to
3469 	 * consume all freed pages while old allocators wait.
3470 	 */
3471 	mtx_lock(&vm_domainset_lock);
3472 	if (vm_page_count_min_set(&dset->ds_mask)) {
3473 		vm_min_waiters++;
3474 		msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3475 		    "pfault", timo);
3476 	} else
3477 		mtx_unlock(&vm_domainset_lock);
3478 }
3479 
3480 static struct vm_pagequeue *
3481 _vm_page_pagequeue(vm_page_t m, uint8_t queue)
3482 {
3483 
3484 	return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue]);
3485 }
3486 
3487 #ifdef INVARIANTS
3488 static struct vm_pagequeue *
3489 vm_page_pagequeue(vm_page_t m)
3490 {
3491 
3492 	return (_vm_page_pagequeue(m, vm_page_astate_load(m).queue));
3493 }
3494 #endif
3495 
3496 static __always_inline bool
3497 vm_page_pqstate_fcmpset(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3498 {
3499 	vm_page_astate_t tmp;
3500 
3501 	tmp = *old;
3502 	do {
3503 		if (__predict_true(vm_page_astate_fcmpset(m, old, new)))
3504 			return (true);
3505 		counter_u64_add(pqstate_commit_retries, 1);
3506 	} while (old->_bits == tmp._bits);
3507 
3508 	return (false);
3509 }
3510 
3511 /*
3512  * Do the work of committing a queue state update that moves the page out of
3513  * its current queue.
3514  */
3515 static bool
3516 _vm_page_pqstate_commit_dequeue(struct vm_pagequeue *pq, vm_page_t m,
3517     vm_page_astate_t *old, vm_page_astate_t new)
3518 {
3519 	vm_page_t next;
3520 
3521 	vm_pagequeue_assert_locked(pq);
3522 	KASSERT(vm_page_pagequeue(m) == pq,
3523 	    ("%s: queue %p does not match page %p", __func__, pq, m));
3524 	KASSERT(old->queue != PQ_NONE && new.queue != old->queue,
3525 	    ("%s: invalid queue indices %d %d",
3526 	    __func__, old->queue, new.queue));
3527 
3528 	/*
3529 	 * Once the queue index of the page changes there is nothing
3530 	 * synchronizing with further updates to the page's physical
3531 	 * queue state.  Therefore we must speculatively remove the page
3532 	 * from the queue now and be prepared to roll back if the queue
3533 	 * state update fails.  If the page is not physically enqueued then
3534 	 * we just update its queue index.
3535 	 */
3536 	if ((old->flags & PGA_ENQUEUED) != 0) {
3537 		new.flags &= ~PGA_ENQUEUED;
3538 		next = TAILQ_NEXT(m, plinks.q);
3539 		TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3540 		vm_pagequeue_cnt_dec(pq);
3541 		if (!vm_page_pqstate_fcmpset(m, old, new)) {
3542 			if (next == NULL)
3543 				TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3544 			else
3545 				TAILQ_INSERT_BEFORE(next, m, plinks.q);
3546 			vm_pagequeue_cnt_inc(pq);
3547 			return (false);
3548 		} else {
3549 			return (true);
3550 		}
3551 	} else {
3552 		return (vm_page_pqstate_fcmpset(m, old, new));
3553 	}
3554 }
3555 
3556 static bool
3557 vm_page_pqstate_commit_dequeue(vm_page_t m, vm_page_astate_t *old,
3558     vm_page_astate_t new)
3559 {
3560 	struct vm_pagequeue *pq;
3561 	vm_page_astate_t as;
3562 	bool ret;
3563 
3564 	pq = _vm_page_pagequeue(m, old->queue);
3565 
3566 	/*
3567 	 * The queue field and PGA_ENQUEUED flag are stable only so long as the
3568 	 * corresponding page queue lock is held.
3569 	 */
3570 	vm_pagequeue_lock(pq);
3571 	as = vm_page_astate_load(m);
3572 	if (__predict_false(as._bits != old->_bits)) {
3573 		*old = as;
3574 		ret = false;
3575 	} else {
3576 		ret = _vm_page_pqstate_commit_dequeue(pq, m, old, new);
3577 	}
3578 	vm_pagequeue_unlock(pq);
3579 	return (ret);
3580 }
3581 
3582 /*
3583  * Commit a queue state update that enqueues or requeues a page.
3584  */
3585 static bool
3586 _vm_page_pqstate_commit_requeue(struct vm_pagequeue *pq, vm_page_t m,
3587     vm_page_astate_t *old, vm_page_astate_t new)
3588 {
3589 	struct vm_domain *vmd;
3590 
3591 	vm_pagequeue_assert_locked(pq);
3592 	KASSERT(old->queue != PQ_NONE && new.queue == old->queue,
3593 	    ("%s: invalid queue indices %d %d",
3594 	    __func__, old->queue, new.queue));
3595 
3596 	new.flags |= PGA_ENQUEUED;
3597 	if (!vm_page_pqstate_fcmpset(m, old, new))
3598 		return (false);
3599 
3600 	if ((old->flags & PGA_ENQUEUED) != 0)
3601 		TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3602 	else
3603 		vm_pagequeue_cnt_inc(pq);
3604 
3605 	/*
3606 	 * Give PGA_REQUEUE_HEAD precedence over PGA_REQUEUE.  In particular, if
3607 	 * both flags are set in close succession, only PGA_REQUEUE_HEAD will be
3608 	 * applied, even if it was set first.
3609 	 */
3610 	if ((old->flags & PGA_REQUEUE_HEAD) != 0) {
3611 		vmd = vm_pagequeue_domain(m);
3612 		KASSERT(pq == &vmd->vmd_pagequeues[PQ_INACTIVE],
3613 		    ("%s: invalid page queue for page %p", __func__, m));
3614 		TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3615 	} else {
3616 		TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3617 	}
3618 	return (true);
3619 }
3620 
3621 /*
3622  * Commit a queue state update that encodes a request for a deferred queue
3623  * operation.
3624  */
3625 static bool
3626 vm_page_pqstate_commit_request(vm_page_t m, vm_page_astate_t *old,
3627     vm_page_astate_t new)
3628 {
3629 
3630 	KASSERT(old->queue == new.queue || new.queue != PQ_NONE,
3631 	    ("%s: invalid state, queue %d flags %x",
3632 	    __func__, new.queue, new.flags));
3633 
3634 	if (old->_bits != new._bits &&
3635 	    !vm_page_pqstate_fcmpset(m, old, new))
3636 		return (false);
3637 	vm_page_pqbatch_submit(m, new.queue);
3638 	return (true);
3639 }
3640 
3641 /*
3642  * A generic queue state update function.  This handles more cases than the
3643  * specialized functions above.
3644  */
3645 bool
3646 vm_page_pqstate_commit(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3647 {
3648 
3649 	if (old->_bits == new._bits)
3650 		return (true);
3651 
3652 	if (old->queue != PQ_NONE && new.queue != old->queue) {
3653 		if (!vm_page_pqstate_commit_dequeue(m, old, new))
3654 			return (false);
3655 		if (new.queue != PQ_NONE)
3656 			vm_page_pqbatch_submit(m, new.queue);
3657 	} else {
3658 		if (!vm_page_pqstate_fcmpset(m, old, new))
3659 			return (false);
3660 		if (new.queue != PQ_NONE &&
3661 		    ((new.flags & ~old->flags) & PGA_QUEUE_OP_MASK) != 0)
3662 			vm_page_pqbatch_submit(m, new.queue);
3663 	}
3664 	return (true);
3665 }
3666 
3667 /*
3668  * Apply deferred queue state updates to a page.
3669  */
3670 static inline void
3671 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m, uint8_t queue)
3672 {
3673 	vm_page_astate_t new, old;
3674 
3675 	CRITICAL_ASSERT(curthread);
3676 	vm_pagequeue_assert_locked(pq);
3677 	KASSERT(queue < PQ_COUNT,
3678 	    ("%s: invalid queue index %d", __func__, queue));
3679 	KASSERT(pq == _vm_page_pagequeue(m, queue),
3680 	    ("%s: page %p does not belong to queue %p", __func__, m, pq));
3681 
3682 	for (old = vm_page_astate_load(m);;) {
3683 		if (__predict_false(old.queue != queue ||
3684 		    (old.flags & PGA_QUEUE_OP_MASK) == 0)) {
3685 			counter_u64_add(queue_nops, 1);
3686 			break;
3687 		}
3688 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3689 		    ("%s: page %p is unmanaged", __func__, m));
3690 
3691 		new = old;
3692 		if ((old.flags & PGA_DEQUEUE) != 0) {
3693 			new.flags &= ~PGA_QUEUE_OP_MASK;
3694 			new.queue = PQ_NONE;
3695 			if (__predict_true(_vm_page_pqstate_commit_dequeue(pq,
3696 			    m, &old, new))) {
3697 				counter_u64_add(queue_ops, 1);
3698 				break;
3699 			}
3700 		} else {
3701 			new.flags &= ~(PGA_REQUEUE | PGA_REQUEUE_HEAD);
3702 			if (__predict_true(_vm_page_pqstate_commit_requeue(pq,
3703 			    m, &old, new))) {
3704 				counter_u64_add(queue_ops, 1);
3705 				break;
3706 			}
3707 		}
3708 	}
3709 }
3710 
3711 static void
3712 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3713     uint8_t queue)
3714 {
3715 	int i;
3716 
3717 	for (i = 0; i < bq->bq_cnt; i++)
3718 		vm_pqbatch_process_page(pq, bq->bq_pa[i], queue);
3719 	vm_batchqueue_init(bq);
3720 }
3721 
3722 /*
3723  *	vm_page_pqbatch_submit:		[ internal use only ]
3724  *
3725  *	Enqueue a page in the specified page queue's batched work queue.
3726  *	The caller must have encoded the requested operation in the page
3727  *	structure's a.flags field.
3728  */
3729 void
3730 vm_page_pqbatch_submit(vm_page_t m, uint8_t queue)
3731 {
3732 	struct vm_batchqueue *bq;
3733 	struct vm_pagequeue *pq;
3734 	int domain, slots_remaining;
3735 
3736 	KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3737 
3738 	domain = vm_page_domain(m);
3739 	critical_enter();
3740 	bq = DPCPU_PTR(pqbatch[domain][queue]);
3741 	slots_remaining = vm_batchqueue_insert(bq, m);
3742 	if (slots_remaining > (VM_BATCHQUEUE_SIZE >> 1)) {
3743 		/* keep building the bq */
3744 		critical_exit();
3745 		return;
3746 	} else if (slots_remaining > 0 ) {
3747 		/* Try to process the bq if we can get the lock */
3748 		pq = &VM_DOMAIN(domain)->vmd_pagequeues[queue];
3749 		if (vm_pagequeue_trylock(pq)) {
3750 			vm_pqbatch_process(pq, bq, queue);
3751 			vm_pagequeue_unlock(pq);
3752 		}
3753 		critical_exit();
3754 		return;
3755 	}
3756 	critical_exit();
3757 
3758 	/* if we make it here, the bq is full so wait for the lock */
3759 
3760 	pq = &VM_DOMAIN(domain)->vmd_pagequeues[queue];
3761 	vm_pagequeue_lock(pq);
3762 	critical_enter();
3763 	bq = DPCPU_PTR(pqbatch[domain][queue]);
3764 	vm_pqbatch_process(pq, bq, queue);
3765 	vm_pqbatch_process_page(pq, m, queue);
3766 	vm_pagequeue_unlock(pq);
3767 	critical_exit();
3768 }
3769 
3770 /*
3771  *	vm_page_pqbatch_drain:		[ internal use only ]
3772  *
3773  *	Force all per-CPU page queue batch queues to be drained.  This is
3774  *	intended for use in severe memory shortages, to ensure that pages
3775  *	do not remain stuck in the batch queues.
3776  */
3777 void
3778 vm_page_pqbatch_drain(void)
3779 {
3780 	struct thread *td;
3781 	struct vm_domain *vmd;
3782 	struct vm_pagequeue *pq;
3783 	int cpu, domain, queue;
3784 
3785 	td = curthread;
3786 	CPU_FOREACH(cpu) {
3787 		thread_lock(td);
3788 		sched_bind(td, cpu);
3789 		thread_unlock(td);
3790 
3791 		for (domain = 0; domain < vm_ndomains; domain++) {
3792 			vmd = VM_DOMAIN(domain);
3793 			for (queue = 0; queue < PQ_COUNT; queue++) {
3794 				pq = &vmd->vmd_pagequeues[queue];
3795 				vm_pagequeue_lock(pq);
3796 				critical_enter();
3797 				vm_pqbatch_process(pq,
3798 				    DPCPU_PTR(pqbatch[domain][queue]), queue);
3799 				critical_exit();
3800 				vm_pagequeue_unlock(pq);
3801 			}
3802 		}
3803 	}
3804 	thread_lock(td);
3805 	sched_unbind(td);
3806 	thread_unlock(td);
3807 }
3808 
3809 /*
3810  *	vm_page_dequeue_deferred:	[ internal use only ]
3811  *
3812  *	Request removal of the given page from its current page
3813  *	queue.  Physical removal from the queue may be deferred
3814  *	indefinitely.
3815  */
3816 void
3817 vm_page_dequeue_deferred(vm_page_t m)
3818 {
3819 	vm_page_astate_t new, old;
3820 
3821 	old = vm_page_astate_load(m);
3822 	do {
3823 		if (old.queue == PQ_NONE) {
3824 			KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3825 			    ("%s: page %p has unexpected queue state",
3826 			    __func__, m));
3827 			break;
3828 		}
3829 		new = old;
3830 		new.flags |= PGA_DEQUEUE;
3831 	} while (!vm_page_pqstate_commit_request(m, &old, new));
3832 }
3833 
3834 /*
3835  *	vm_page_dequeue:
3836  *
3837  *	Remove the page from whichever page queue it's in, if any, before
3838  *	returning.
3839  */
3840 void
3841 vm_page_dequeue(vm_page_t m)
3842 {
3843 	vm_page_astate_t new, old;
3844 
3845 	old = vm_page_astate_load(m);
3846 	do {
3847 		if (old.queue == PQ_NONE) {
3848 			KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3849 			    ("%s: page %p has unexpected queue state",
3850 			    __func__, m));
3851 			break;
3852 		}
3853 		new = old;
3854 		new.flags &= ~PGA_QUEUE_OP_MASK;
3855 		new.queue = PQ_NONE;
3856 	} while (!vm_page_pqstate_commit_dequeue(m, &old, new));
3857 
3858 }
3859 
3860 /*
3861  * Schedule the given page for insertion into the specified page queue.
3862  * Physical insertion of the page may be deferred indefinitely.
3863  */
3864 static void
3865 vm_page_enqueue(vm_page_t m, uint8_t queue)
3866 {
3867 
3868 	KASSERT(m->a.queue == PQ_NONE &&
3869 	    (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
3870 	    ("%s: page %p is already enqueued", __func__, m));
3871 	KASSERT(m->ref_count > 0,
3872 	    ("%s: page %p does not carry any references", __func__, m));
3873 
3874 	m->a.queue = queue;
3875 	if ((m->a.flags & PGA_REQUEUE) == 0)
3876 		vm_page_aflag_set(m, PGA_REQUEUE);
3877 	vm_page_pqbatch_submit(m, queue);
3878 }
3879 
3880 /*
3881  *	vm_page_free_prep:
3882  *
3883  *	Prepares the given page to be put on the free list,
3884  *	disassociating it from any VM object. The caller may return
3885  *	the page to the free list only if this function returns true.
3886  *
3887  *	The object, if it exists, must be locked, and then the page must
3888  *	be xbusy.  Otherwise the page must be not busied.  A managed
3889  *	page must be unmapped.
3890  */
3891 static bool
3892 vm_page_free_prep(vm_page_t m)
3893 {
3894 
3895 	/*
3896 	 * Synchronize with threads that have dropped a reference to this
3897 	 * page.
3898 	 */
3899 	atomic_thread_fence_acq();
3900 
3901 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
3902 	if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
3903 		uint64_t *p;
3904 		int i;
3905 		p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3906 		for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
3907 			KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
3908 			    m, i, (uintmax_t)*p));
3909 	}
3910 #endif
3911 	if ((m->oflags & VPO_UNMANAGED) == 0) {
3912 		KASSERT(!pmap_page_is_mapped(m),
3913 		    ("vm_page_free_prep: freeing mapped page %p", m));
3914 		KASSERT((m->a.flags & (PGA_EXECUTABLE | PGA_WRITEABLE)) == 0,
3915 		    ("vm_page_free_prep: mapping flags set in page %p", m));
3916 	} else {
3917 		KASSERT(m->a.queue == PQ_NONE,
3918 		    ("vm_page_free_prep: unmanaged page %p is queued", m));
3919 	}
3920 	VM_CNT_INC(v_tfree);
3921 
3922 	if (m->object != NULL) {
3923 		KASSERT(((m->oflags & VPO_UNMANAGED) != 0) ==
3924 		    ((m->object->flags & OBJ_UNMANAGED) != 0),
3925 		    ("vm_page_free_prep: managed flag mismatch for page %p",
3926 		    m));
3927 		vm_page_assert_xbusied(m);
3928 
3929 		/*
3930 		 * The object reference can be released without an atomic
3931 		 * operation.
3932 		 */
3933 		KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
3934 		    m->ref_count == VPRC_OBJREF,
3935 		    ("vm_page_free_prep: page %p has unexpected ref_count %u",
3936 		    m, m->ref_count));
3937 		vm_page_object_remove(m);
3938 		m->ref_count -= VPRC_OBJREF;
3939 	} else
3940 		vm_page_assert_unbusied(m);
3941 
3942 	vm_page_busy_free(m);
3943 
3944 	/*
3945 	 * If fictitious remove object association and
3946 	 * return.
3947 	 */
3948 	if ((m->flags & PG_FICTITIOUS) != 0) {
3949 		KASSERT(m->ref_count == 1,
3950 		    ("fictitious page %p is referenced", m));
3951 		KASSERT(m->a.queue == PQ_NONE,
3952 		    ("fictitious page %p is queued", m));
3953 		return (false);
3954 	}
3955 
3956 	/*
3957 	 * Pages need not be dequeued before they are returned to the physical
3958 	 * memory allocator, but they must at least be marked for a deferred
3959 	 * dequeue.
3960 	 */
3961 	if ((m->oflags & VPO_UNMANAGED) == 0)
3962 		vm_page_dequeue_deferred(m);
3963 
3964 	m->valid = 0;
3965 	vm_page_undirty(m);
3966 
3967 	if (m->ref_count != 0)
3968 		panic("vm_page_free_prep: page %p has references", m);
3969 
3970 	/*
3971 	 * Restore the default memory attribute to the page.
3972 	 */
3973 	if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3974 		pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3975 
3976 #if VM_NRESERVLEVEL > 0
3977 	/*
3978 	 * Determine whether the page belongs to a reservation.  If the page was
3979 	 * allocated from a per-CPU cache, it cannot belong to a reservation, so
3980 	 * as an optimization, we avoid the check in that case.
3981 	 */
3982 	if ((m->flags & PG_PCPU_CACHE) == 0 && vm_reserv_free_page(m))
3983 		return (false);
3984 #endif
3985 
3986 	return (true);
3987 }
3988 
3989 /*
3990  *	vm_page_free_toq:
3991  *
3992  *	Returns the given page to the free list, disassociating it
3993  *	from any VM object.
3994  *
3995  *	The object must be locked.  The page must be exclusively busied if it
3996  *	belongs to an object.
3997  */
3998 static void
3999 vm_page_free_toq(vm_page_t m)
4000 {
4001 	struct vm_domain *vmd;
4002 	uma_zone_t zone;
4003 
4004 	if (!vm_page_free_prep(m))
4005 		return;
4006 
4007 	vmd = vm_pagequeue_domain(m);
4008 	zone = vmd->vmd_pgcache[m->pool].zone;
4009 	if ((m->flags & PG_PCPU_CACHE) != 0 && zone != NULL) {
4010 		uma_zfree(zone, m);
4011 		return;
4012 	}
4013 	vm_domain_free_lock(vmd);
4014 	vm_phys_free_pages(m, 0);
4015 	vm_domain_free_unlock(vmd);
4016 	vm_domain_freecnt_inc(vmd, 1);
4017 }
4018 
4019 /*
4020  *	vm_page_free_pages_toq:
4021  *
4022  *	Returns a list of pages to the free list, disassociating it
4023  *	from any VM object.  In other words, this is equivalent to
4024  *	calling vm_page_free_toq() for each page of a list of VM objects.
4025  */
4026 void
4027 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
4028 {
4029 	vm_page_t m;
4030 	int count;
4031 
4032 	if (SLIST_EMPTY(free))
4033 		return;
4034 
4035 	count = 0;
4036 	while ((m = SLIST_FIRST(free)) != NULL) {
4037 		count++;
4038 		SLIST_REMOVE_HEAD(free, plinks.s.ss);
4039 		vm_page_free_toq(m);
4040 	}
4041 
4042 	if (update_wire_count)
4043 		vm_wire_sub(count);
4044 }
4045 
4046 /*
4047  * Mark this page as wired down.  For managed pages, this prevents reclamation
4048  * by the page daemon, or when the containing object, if any, is destroyed.
4049  */
4050 void
4051 vm_page_wire(vm_page_t m)
4052 {
4053 	u_int old;
4054 
4055 #ifdef INVARIANTS
4056 	if (m->object != NULL && !vm_page_busied(m) &&
4057 	    !vm_object_busied(m->object))
4058 		VM_OBJECT_ASSERT_LOCKED(m->object);
4059 #endif
4060 	KASSERT((m->flags & PG_FICTITIOUS) == 0 ||
4061 	    VPRC_WIRE_COUNT(m->ref_count) >= 1,
4062 	    ("vm_page_wire: fictitious page %p has zero wirings", m));
4063 
4064 	old = atomic_fetchadd_int(&m->ref_count, 1);
4065 	KASSERT(VPRC_WIRE_COUNT(old) != VPRC_WIRE_COUNT_MAX,
4066 	    ("vm_page_wire: counter overflow for page %p", m));
4067 	if (VPRC_WIRE_COUNT(old) == 0) {
4068 		if ((m->oflags & VPO_UNMANAGED) == 0)
4069 			vm_page_aflag_set(m, PGA_DEQUEUE);
4070 		vm_wire_add(1);
4071 	}
4072 }
4073 
4074 /*
4075  * Attempt to wire a mapped page following a pmap lookup of that page.
4076  * This may fail if a thread is concurrently tearing down mappings of the page.
4077  * The transient failure is acceptable because it translates to the
4078  * failure of the caller pmap_extract_and_hold(), which should be then
4079  * followed by the vm_fault() fallback, see e.g. vm_fault_quick_hold_pages().
4080  */
4081 bool
4082 vm_page_wire_mapped(vm_page_t m)
4083 {
4084 	u_int old;
4085 
4086 	old = m->ref_count;
4087 	do {
4088 		KASSERT(old > 0,
4089 		    ("vm_page_wire_mapped: wiring unreferenced page %p", m));
4090 		if ((old & VPRC_BLOCKED) != 0)
4091 			return (false);
4092 	} while (!atomic_fcmpset_int(&m->ref_count, &old, old + 1));
4093 
4094 	if (VPRC_WIRE_COUNT(old) == 0) {
4095 		if ((m->oflags & VPO_UNMANAGED) == 0)
4096 			vm_page_aflag_set(m, PGA_DEQUEUE);
4097 		vm_wire_add(1);
4098 	}
4099 	return (true);
4100 }
4101 
4102 /*
4103  * Release a wiring reference to a managed page.  If the page still belongs to
4104  * an object, update its position in the page queues to reflect the reference.
4105  * If the wiring was the last reference to the page, free the page.
4106  */
4107 static void
4108 vm_page_unwire_managed(vm_page_t m, uint8_t nqueue, bool noreuse)
4109 {
4110 	u_int old;
4111 
4112 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4113 	    ("%s: page %p is unmanaged", __func__, m));
4114 
4115 	/*
4116 	 * Update LRU state before releasing the wiring reference.
4117 	 * Use a release store when updating the reference count to
4118 	 * synchronize with vm_page_free_prep().
4119 	 */
4120 	old = m->ref_count;
4121 	do {
4122 		KASSERT(VPRC_WIRE_COUNT(old) > 0,
4123 		    ("vm_page_unwire: wire count underflow for page %p", m));
4124 
4125 		if (old > VPRC_OBJREF + 1) {
4126 			/*
4127 			 * The page has at least one other wiring reference.  An
4128 			 * earlier iteration of this loop may have called
4129 			 * vm_page_release_toq() and cleared PGA_DEQUEUE, so
4130 			 * re-set it if necessary.
4131 			 */
4132 			if ((vm_page_astate_load(m).flags & PGA_DEQUEUE) == 0)
4133 				vm_page_aflag_set(m, PGA_DEQUEUE);
4134 		} else if (old == VPRC_OBJREF + 1) {
4135 			/*
4136 			 * This is the last wiring.  Clear PGA_DEQUEUE and
4137 			 * update the page's queue state to reflect the
4138 			 * reference.  If the page does not belong to an object
4139 			 * (i.e., the VPRC_OBJREF bit is clear), we only need to
4140 			 * clear leftover queue state.
4141 			 */
4142 			vm_page_release_toq(m, nqueue, noreuse);
4143 		} else if (old == 1) {
4144 			vm_page_aflag_clear(m, PGA_DEQUEUE);
4145 		}
4146 	} while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
4147 
4148 	if (VPRC_WIRE_COUNT(old) == 1) {
4149 		vm_wire_sub(1);
4150 		if (old == 1)
4151 			vm_page_free(m);
4152 	}
4153 }
4154 
4155 /*
4156  * Release one wiring of the specified page, potentially allowing it to be
4157  * paged out.
4158  *
4159  * Only managed pages belonging to an object can be paged out.  If the number
4160  * of wirings transitions to zero and the page is eligible for page out, then
4161  * the page is added to the specified paging queue.  If the released wiring
4162  * represented the last reference to the page, the page is freed.
4163  */
4164 void
4165 vm_page_unwire(vm_page_t m, uint8_t nqueue)
4166 {
4167 
4168 	KASSERT(nqueue < PQ_COUNT,
4169 	    ("vm_page_unwire: invalid queue %u request for page %p",
4170 	    nqueue, m));
4171 
4172 	if ((m->oflags & VPO_UNMANAGED) != 0) {
4173 		if (vm_page_unwire_noq(m) && m->ref_count == 0)
4174 			vm_page_free(m);
4175 		return;
4176 	}
4177 	vm_page_unwire_managed(m, nqueue, false);
4178 }
4179 
4180 /*
4181  * Unwire a page without (re-)inserting it into a page queue.  It is up
4182  * to the caller to enqueue, requeue, or free the page as appropriate.
4183  * In most cases involving managed pages, vm_page_unwire() should be used
4184  * instead.
4185  */
4186 bool
4187 vm_page_unwire_noq(vm_page_t m)
4188 {
4189 	u_int old;
4190 
4191 	old = vm_page_drop(m, 1);
4192 	KASSERT(VPRC_WIRE_COUNT(old) != 0,
4193 	    ("%s: counter underflow for page %p", __func__,  m));
4194 	KASSERT((m->flags & PG_FICTITIOUS) == 0 || VPRC_WIRE_COUNT(old) > 1,
4195 	    ("%s: missing ref on fictitious page %p", __func__, m));
4196 
4197 	if (VPRC_WIRE_COUNT(old) > 1)
4198 		return (false);
4199 	if ((m->oflags & VPO_UNMANAGED) == 0)
4200 		vm_page_aflag_clear(m, PGA_DEQUEUE);
4201 	vm_wire_sub(1);
4202 	return (true);
4203 }
4204 
4205 /*
4206  * Ensure that the page ends up in the specified page queue.  If the page is
4207  * active or being moved to the active queue, ensure that its act_count is
4208  * at least ACT_INIT but do not otherwise mess with it.
4209  */
4210 static __always_inline void
4211 vm_page_mvqueue(vm_page_t m, const uint8_t nqueue, const uint16_t nflag)
4212 {
4213 	vm_page_astate_t old, new;
4214 
4215 	KASSERT(m->ref_count > 0,
4216 	    ("%s: page %p does not carry any references", __func__, m));
4217 	KASSERT(nflag == PGA_REQUEUE || nflag == PGA_REQUEUE_HEAD,
4218 	    ("%s: invalid flags %x", __func__, nflag));
4219 
4220 	if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
4221 		return;
4222 
4223 	old = vm_page_astate_load(m);
4224 	do {
4225 		if ((old.flags & PGA_DEQUEUE) != 0)
4226 			break;
4227 		new = old;
4228 		new.flags &= ~PGA_QUEUE_OP_MASK;
4229 		if (nqueue == PQ_ACTIVE)
4230 			new.act_count = max(old.act_count, ACT_INIT);
4231 		if (old.queue == nqueue) {
4232 			/*
4233 			 * There is no need to requeue pages already in the
4234 			 * active queue.
4235 			 */
4236 			if (nqueue != PQ_ACTIVE ||
4237 			    (old.flags & PGA_ENQUEUED) == 0)
4238 				new.flags |= nflag;
4239 		} else {
4240 			new.flags |= nflag;
4241 			new.queue = nqueue;
4242 		}
4243 	} while (!vm_page_pqstate_commit(m, &old, new));
4244 }
4245 
4246 /*
4247  * Put the specified page on the active list (if appropriate).
4248  */
4249 void
4250 vm_page_activate(vm_page_t m)
4251 {
4252 
4253 	vm_page_mvqueue(m, PQ_ACTIVE, PGA_REQUEUE);
4254 }
4255 
4256 /*
4257  * Move the specified page to the tail of the inactive queue, or requeue
4258  * the page if it is already in the inactive queue.
4259  */
4260 void
4261 vm_page_deactivate(vm_page_t m)
4262 {
4263 
4264 	vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE);
4265 }
4266 
4267 void
4268 vm_page_deactivate_noreuse(vm_page_t m)
4269 {
4270 
4271 	vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE_HEAD);
4272 }
4273 
4274 /*
4275  * Put a page in the laundry, or requeue it if it is already there.
4276  */
4277 void
4278 vm_page_launder(vm_page_t m)
4279 {
4280 
4281 	vm_page_mvqueue(m, PQ_LAUNDRY, PGA_REQUEUE);
4282 }
4283 
4284 /*
4285  * Put a page in the PQ_UNSWAPPABLE holding queue.
4286  */
4287 void
4288 vm_page_unswappable(vm_page_t m)
4289 {
4290 
4291 	VM_OBJECT_ASSERT_LOCKED(m->object);
4292 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4293 	    ("page %p already unswappable", m));
4294 
4295 	vm_page_dequeue(m);
4296 	vm_page_enqueue(m, PQ_UNSWAPPABLE);
4297 }
4298 
4299 /*
4300  * Release a page back to the page queues in preparation for unwiring.
4301  */
4302 static void
4303 vm_page_release_toq(vm_page_t m, uint8_t nqueue, const bool noreuse)
4304 {
4305 	vm_page_astate_t old, new;
4306 	uint16_t nflag;
4307 
4308 	/*
4309 	 * Use a check of the valid bits to determine whether we should
4310 	 * accelerate reclamation of the page.  The object lock might not be
4311 	 * held here, in which case the check is racy.  At worst we will either
4312 	 * accelerate reclamation of a valid page and violate LRU, or
4313 	 * unnecessarily defer reclamation of an invalid page.
4314 	 *
4315 	 * If we were asked to not cache the page, place it near the head of the
4316 	 * inactive queue so that is reclaimed sooner.
4317 	 */
4318 	if (noreuse || vm_page_none_valid(m)) {
4319 		nqueue = PQ_INACTIVE;
4320 		nflag = PGA_REQUEUE_HEAD;
4321 	} else {
4322 		nflag = PGA_REQUEUE;
4323 	}
4324 
4325 	old = vm_page_astate_load(m);
4326 	do {
4327 		new = old;
4328 
4329 		/*
4330 		 * If the page is already in the active queue and we are not
4331 		 * trying to accelerate reclamation, simply mark it as
4332 		 * referenced and avoid any queue operations.
4333 		 */
4334 		new.flags &= ~PGA_QUEUE_OP_MASK;
4335 		if (nflag != PGA_REQUEUE_HEAD && old.queue == PQ_ACTIVE &&
4336 		    (old.flags & PGA_ENQUEUED) != 0)
4337 			new.flags |= PGA_REFERENCED;
4338 		else {
4339 			new.flags |= nflag;
4340 			new.queue = nqueue;
4341 		}
4342 	} while (!vm_page_pqstate_commit(m, &old, new));
4343 }
4344 
4345 /*
4346  * Unwire a page and either attempt to free it or re-add it to the page queues.
4347  */
4348 void
4349 vm_page_release(vm_page_t m, int flags)
4350 {
4351 	vm_object_t object;
4352 
4353 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4354 	    ("vm_page_release: page %p is unmanaged", m));
4355 
4356 	if ((flags & VPR_TRYFREE) != 0) {
4357 		for (;;) {
4358 			object = atomic_load_ptr(&m->object);
4359 			if (object == NULL)
4360 				break;
4361 			/* Depends on type-stability. */
4362 			if (vm_page_busied(m) || !VM_OBJECT_TRYWLOCK(object))
4363 				break;
4364 			if (object == m->object) {
4365 				vm_page_release_locked(m, flags);
4366 				VM_OBJECT_WUNLOCK(object);
4367 				return;
4368 			}
4369 			VM_OBJECT_WUNLOCK(object);
4370 		}
4371 	}
4372 	vm_page_unwire_managed(m, PQ_INACTIVE, flags != 0);
4373 }
4374 
4375 /* See vm_page_release(). */
4376 void
4377 vm_page_release_locked(vm_page_t m, int flags)
4378 {
4379 
4380 	VM_OBJECT_ASSERT_WLOCKED(m->object);
4381 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4382 	    ("vm_page_release_locked: page %p is unmanaged", m));
4383 
4384 	if (vm_page_unwire_noq(m)) {
4385 		if ((flags & VPR_TRYFREE) != 0 &&
4386 		    (m->object->ref_count == 0 || !pmap_page_is_mapped(m)) &&
4387 		    m->dirty == 0 && vm_page_tryxbusy(m)) {
4388 			/*
4389 			 * An unlocked lookup may have wired the page before the
4390 			 * busy lock was acquired, in which case the page must
4391 			 * not be freed.
4392 			 */
4393 			if (__predict_true(!vm_page_wired(m))) {
4394 				vm_page_free(m);
4395 				return;
4396 			}
4397 			vm_page_xunbusy(m);
4398 		} else {
4399 			vm_page_release_toq(m, PQ_INACTIVE, flags != 0);
4400 		}
4401 	}
4402 }
4403 
4404 static bool
4405 vm_page_try_blocked_op(vm_page_t m, void (*op)(vm_page_t))
4406 {
4407 	u_int old;
4408 
4409 	KASSERT(m->object != NULL && (m->oflags & VPO_UNMANAGED) == 0,
4410 	    ("vm_page_try_blocked_op: page %p has no object", m));
4411 	KASSERT(vm_page_busied(m),
4412 	    ("vm_page_try_blocked_op: page %p is not busy", m));
4413 	VM_OBJECT_ASSERT_LOCKED(m->object);
4414 
4415 	old = m->ref_count;
4416 	do {
4417 		KASSERT(old != 0,
4418 		    ("vm_page_try_blocked_op: page %p has no references", m));
4419 		if (VPRC_WIRE_COUNT(old) != 0)
4420 			return (false);
4421 	} while (!atomic_fcmpset_int(&m->ref_count, &old, old | VPRC_BLOCKED));
4422 
4423 	(op)(m);
4424 
4425 	/*
4426 	 * If the object is read-locked, new wirings may be created via an
4427 	 * object lookup.
4428 	 */
4429 	old = vm_page_drop(m, VPRC_BLOCKED);
4430 	KASSERT(!VM_OBJECT_WOWNED(m->object) ||
4431 	    old == (VPRC_BLOCKED | VPRC_OBJREF),
4432 	    ("vm_page_try_blocked_op: unexpected refcount value %u for %p",
4433 	    old, m));
4434 	return (true);
4435 }
4436 
4437 /*
4438  * Atomically check for wirings and remove all mappings of the page.
4439  */
4440 bool
4441 vm_page_try_remove_all(vm_page_t m)
4442 {
4443 
4444 	return (vm_page_try_blocked_op(m, pmap_remove_all));
4445 }
4446 
4447 /*
4448  * Atomically check for wirings and remove all writeable mappings of the page.
4449  */
4450 bool
4451 vm_page_try_remove_write(vm_page_t m)
4452 {
4453 
4454 	return (vm_page_try_blocked_op(m, pmap_remove_write));
4455 }
4456 
4457 /*
4458  * vm_page_advise
4459  *
4460  * 	Apply the specified advice to the given page.
4461  */
4462 void
4463 vm_page_advise(vm_page_t m, int advice)
4464 {
4465 
4466 	VM_OBJECT_ASSERT_WLOCKED(m->object);
4467 	vm_page_assert_xbusied(m);
4468 
4469 	if (advice == MADV_FREE)
4470 		/*
4471 		 * Mark the page clean.  This will allow the page to be freed
4472 		 * without first paging it out.  MADV_FREE pages are often
4473 		 * quickly reused by malloc(3), so we do not do anything that
4474 		 * would result in a page fault on a later access.
4475 		 */
4476 		vm_page_undirty(m);
4477 	else if (advice != MADV_DONTNEED) {
4478 		if (advice == MADV_WILLNEED)
4479 			vm_page_activate(m);
4480 		return;
4481 	}
4482 
4483 	if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
4484 		vm_page_dirty(m);
4485 
4486 	/*
4487 	 * Clear any references to the page.  Otherwise, the page daemon will
4488 	 * immediately reactivate the page.
4489 	 */
4490 	vm_page_aflag_clear(m, PGA_REFERENCED);
4491 
4492 	/*
4493 	 * Place clean pages near the head of the inactive queue rather than
4494 	 * the tail, thus defeating the queue's LRU operation and ensuring that
4495 	 * the page will be reused quickly.  Dirty pages not already in the
4496 	 * laundry are moved there.
4497 	 */
4498 	if (m->dirty == 0)
4499 		vm_page_deactivate_noreuse(m);
4500 	else if (!vm_page_in_laundry(m))
4501 		vm_page_launder(m);
4502 }
4503 
4504 /*
4505  *	vm_page_grab_release
4506  *
4507  *	Helper routine for grab functions to release busy on return.
4508  */
4509 static inline void
4510 vm_page_grab_release(vm_page_t m, int allocflags)
4511 {
4512 
4513 	if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4514 		if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4515 			vm_page_sunbusy(m);
4516 		else
4517 			vm_page_xunbusy(m);
4518 	}
4519 }
4520 
4521 /*
4522  *	vm_page_grab_sleep
4523  *
4524  *	Sleep for busy according to VM_ALLOC_ parameters.  Returns true
4525  *	if the caller should retry and false otherwise.
4526  *
4527  *	If the object is locked on entry the object will be unlocked with
4528  *	false returns and still locked but possibly having been dropped
4529  *	with true returns.
4530  */
4531 static bool
4532 vm_page_grab_sleep(vm_object_t object, vm_page_t m, vm_pindex_t pindex,
4533     const char *wmesg, int allocflags, bool locked)
4534 {
4535 
4536 	if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4537 		return (false);
4538 
4539 	/*
4540 	 * Reference the page before unlocking and sleeping so that
4541 	 * the page daemon is less likely to reclaim it.
4542 	 */
4543 	if (locked && (allocflags & VM_ALLOC_NOCREAT) == 0)
4544 		vm_page_reference(m);
4545 
4546 	if (_vm_page_busy_sleep(object, m, pindex, wmesg, allocflags, locked) &&
4547 	    locked)
4548 		VM_OBJECT_WLOCK(object);
4549 	if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
4550 		return (false);
4551 
4552 	return (true);
4553 }
4554 
4555 /*
4556  * Assert that the grab flags are valid.
4557  */
4558 static inline void
4559 vm_page_grab_check(int allocflags)
4560 {
4561 
4562 	KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
4563 	    (allocflags & VM_ALLOC_WIRED) != 0,
4564 	    ("vm_page_grab*: the pages must be busied or wired"));
4565 
4566 	KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4567 	    (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4568 	    ("vm_page_grab*: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4569 }
4570 
4571 /*
4572  * Calculate the page allocation flags for grab.
4573  */
4574 static inline int
4575 vm_page_grab_pflags(int allocflags)
4576 {
4577 	int pflags;
4578 
4579 	pflags = allocflags &
4580 	    ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL |
4581 	    VM_ALLOC_NOBUSY | VM_ALLOC_IGN_SBUSY);
4582 	if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4583 		pflags |= VM_ALLOC_WAITFAIL;
4584 	if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4585 		pflags |= VM_ALLOC_SBUSY;
4586 
4587 	return (pflags);
4588 }
4589 
4590 /*
4591  * Grab a page, waiting until we are waken up due to the page
4592  * changing state.  We keep on waiting, if the page continues
4593  * to be in the object.  If the page doesn't exist, first allocate it
4594  * and then conditionally zero it.
4595  *
4596  * This routine may sleep.
4597  *
4598  * The object must be locked on entry.  The lock will, however, be released
4599  * and reacquired if the routine sleeps.
4600  */
4601 vm_page_t
4602 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
4603 {
4604 	vm_page_t m;
4605 
4606 	VM_OBJECT_ASSERT_WLOCKED(object);
4607 	vm_page_grab_check(allocflags);
4608 
4609 retrylookup:
4610 	if ((m = vm_page_lookup(object, pindex)) != NULL) {
4611 		if (!vm_page_tryacquire(m, allocflags)) {
4612 			if (vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4613 			    allocflags, true))
4614 				goto retrylookup;
4615 			return (NULL);
4616 		}
4617 		goto out;
4618 	}
4619 	if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4620 		return (NULL);
4621 	m = vm_page_alloc(object, pindex, vm_page_grab_pflags(allocflags));
4622 	if (m == NULL) {
4623 		if ((allocflags & (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL)) != 0)
4624 			return (NULL);
4625 		goto retrylookup;
4626 	}
4627 	if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
4628 		pmap_zero_page(m);
4629 
4630 out:
4631 	vm_page_grab_release(m, allocflags);
4632 
4633 	return (m);
4634 }
4635 
4636 /*
4637  * Locklessly attempt to acquire a page given a (object, pindex) tuple
4638  * and an optional previous page to avoid the radix lookup.  The resulting
4639  * page will be validated against the identity tuple and busied or wired
4640  * as requested.  A NULL *mp return guarantees that the page was not in
4641  * radix at the time of the call but callers must perform higher level
4642  * synchronization or retry the operation under a lock if they require
4643  * an atomic answer.  This is the only lock free validation routine,
4644  * other routines can depend on the resulting page state.
4645  *
4646  * The return value indicates whether the operation failed due to caller
4647  * flags.  The return is tri-state with mp:
4648  *
4649  * (true, *mp != NULL) - The operation was successful.
4650  * (true, *mp == NULL) - The page was not found in tree.
4651  * (false, *mp == NULL) - WAITFAIL or NOWAIT prevented acquisition.
4652  */
4653 static bool
4654 vm_page_acquire_unlocked(vm_object_t object, vm_pindex_t pindex,
4655     vm_page_t prev, vm_page_t *mp, int allocflags)
4656 {
4657 	vm_page_t m;
4658 
4659 	vm_page_grab_check(allocflags);
4660 	MPASS(prev == NULL || vm_page_busied(prev) || vm_page_wired(prev));
4661 
4662 	*mp = NULL;
4663 	for (;;) {
4664 		/*
4665 		 * We may see a false NULL here because the previous page
4666 		 * has been removed or just inserted and the list is loaded
4667 		 * without barriers.  Switch to radix to verify.
4668 		 */
4669 		if (prev == NULL || (m = TAILQ_NEXT(prev, listq)) == NULL ||
4670 		    QMD_IS_TRASHED(m) || m->pindex != pindex ||
4671 		    atomic_load_ptr(&m->object) != object) {
4672 			prev = NULL;
4673 			/*
4674 			 * This guarantees the result is instantaneously
4675 			 * correct.
4676 			 */
4677 			m = vm_radix_lookup_unlocked(&object->rtree, pindex);
4678 		}
4679 		if (m == NULL)
4680 			return (true);
4681 		if (vm_page_trybusy(m, allocflags)) {
4682 			if (m->object == object && m->pindex == pindex)
4683 				break;
4684 			/* relookup. */
4685 			vm_page_busy_release(m);
4686 			cpu_spinwait();
4687 			continue;
4688 		}
4689 		if (!vm_page_grab_sleep(object, m, pindex, "pgnslp",
4690 		    allocflags, false))
4691 			return (false);
4692 	}
4693 	if ((allocflags & VM_ALLOC_WIRED) != 0)
4694 		vm_page_wire(m);
4695 	vm_page_grab_release(m, allocflags);
4696 	*mp = m;
4697 	return (true);
4698 }
4699 
4700 /*
4701  * Try to locklessly grab a page and fall back to the object lock if NOCREAT
4702  * is not set.
4703  */
4704 vm_page_t
4705 vm_page_grab_unlocked(vm_object_t object, vm_pindex_t pindex, int allocflags)
4706 {
4707 	vm_page_t m;
4708 
4709 	vm_page_grab_check(allocflags);
4710 
4711 	if (!vm_page_acquire_unlocked(object, pindex, NULL, &m, allocflags))
4712 		return (NULL);
4713 	if (m != NULL)
4714 		return (m);
4715 
4716 	/*
4717 	 * The radix lockless lookup should never return a false negative
4718 	 * errors.  If the user specifies NOCREAT they are guaranteed there
4719 	 * was no page present at the instant of the call.  A NOCREAT caller
4720 	 * must handle create races gracefully.
4721 	 */
4722 	if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4723 		return (NULL);
4724 
4725 	VM_OBJECT_WLOCK(object);
4726 	m = vm_page_grab(object, pindex, allocflags);
4727 	VM_OBJECT_WUNLOCK(object);
4728 
4729 	return (m);
4730 }
4731 
4732 /*
4733  * Grab a page and make it valid, paging in if necessary.  Pages missing from
4734  * their pager are zero filled and validated.  If a VM_ALLOC_COUNT is supplied
4735  * and the page is not valid as many as VM_INITIAL_PAGEIN pages can be brought
4736  * in simultaneously.  Additional pages will be left on a paging queue but
4737  * will neither be wired nor busy regardless of allocflags.
4738  */
4739 int
4740 vm_page_grab_valid(vm_page_t *mp, vm_object_t object, vm_pindex_t pindex, int allocflags)
4741 {
4742 	vm_page_t m;
4743 	vm_page_t ma[VM_INITIAL_PAGEIN];
4744 	int after, i, pflags, rv;
4745 
4746 	KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4747 	    (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4748 	    ("vm_page_grab_valid: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4749 	KASSERT((allocflags &
4750 	    (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4751 	    ("vm_page_grab_valid: Invalid flags 0x%X", allocflags));
4752 	VM_OBJECT_ASSERT_WLOCKED(object);
4753 	pflags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY |
4754 	    VM_ALLOC_WIRED | VM_ALLOC_IGN_SBUSY);
4755 	pflags |= VM_ALLOC_WAITFAIL;
4756 
4757 retrylookup:
4758 	if ((m = vm_page_lookup(object, pindex)) != NULL) {
4759 		/*
4760 		 * If the page is fully valid it can only become invalid
4761 		 * with the object lock held.  If it is not valid it can
4762 		 * become valid with the busy lock held.  Therefore, we
4763 		 * may unnecessarily lock the exclusive busy here if we
4764 		 * race with I/O completion not using the object lock.
4765 		 * However, we will not end up with an invalid page and a
4766 		 * shared lock.
4767 		 */
4768 		if (!vm_page_trybusy(m,
4769 		    vm_page_all_valid(m) ? allocflags : 0)) {
4770 			(void)vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4771 			    allocflags, true);
4772 			goto retrylookup;
4773 		}
4774 		if (vm_page_all_valid(m))
4775 			goto out;
4776 		if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4777 			vm_page_busy_release(m);
4778 			*mp = NULL;
4779 			return (VM_PAGER_FAIL);
4780 		}
4781 	} else if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4782 		*mp = NULL;
4783 		return (VM_PAGER_FAIL);
4784 	} else if ((m = vm_page_alloc(object, pindex, pflags)) == NULL) {
4785 		if (!vm_pager_can_alloc_page(object, pindex)) {
4786 			*mp = NULL;
4787 			return (VM_PAGER_AGAIN);
4788 		}
4789 		goto retrylookup;
4790 	}
4791 
4792 	vm_page_assert_xbusied(m);
4793 	if (vm_pager_has_page(object, pindex, NULL, &after)) {
4794 		after = MIN(after, VM_INITIAL_PAGEIN);
4795 		after = MIN(after, allocflags >> VM_ALLOC_COUNT_SHIFT);
4796 		after = MAX(after, 1);
4797 		ma[0] = m;
4798 		for (i = 1; i < after; i++) {
4799 			if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
4800 				if (vm_page_any_valid(ma[i]) ||
4801 				    !vm_page_tryxbusy(ma[i]))
4802 					break;
4803 			} else {
4804 				ma[i] = vm_page_alloc(object, m->pindex + i,
4805 				    VM_ALLOC_NORMAL);
4806 				if (ma[i] == NULL)
4807 					break;
4808 			}
4809 		}
4810 		after = i;
4811 		vm_object_pip_add(object, after);
4812 		VM_OBJECT_WUNLOCK(object);
4813 		rv = vm_pager_get_pages(object, ma, after, NULL, NULL);
4814 		VM_OBJECT_WLOCK(object);
4815 		vm_object_pip_wakeupn(object, after);
4816 		/* Pager may have replaced a page. */
4817 		m = ma[0];
4818 		if (rv != VM_PAGER_OK) {
4819 			for (i = 0; i < after; i++) {
4820 				if (!vm_page_wired(ma[i]))
4821 					vm_page_free(ma[i]);
4822 				else
4823 					vm_page_xunbusy(ma[i]);
4824 			}
4825 			*mp = NULL;
4826 			return (rv);
4827 		}
4828 		for (i = 1; i < after; i++)
4829 			vm_page_readahead_finish(ma[i]);
4830 		MPASS(vm_page_all_valid(m));
4831 	} else {
4832 		vm_page_zero_invalid(m, TRUE);
4833 	}
4834 out:
4835 	if ((allocflags & VM_ALLOC_WIRED) != 0)
4836 		vm_page_wire(m);
4837 	if ((allocflags & VM_ALLOC_SBUSY) != 0 && vm_page_xbusied(m))
4838 		vm_page_busy_downgrade(m);
4839 	else if ((allocflags & VM_ALLOC_NOBUSY) != 0)
4840 		vm_page_busy_release(m);
4841 	*mp = m;
4842 	return (VM_PAGER_OK);
4843 }
4844 
4845 /*
4846  * Locklessly grab a valid page.  If the page is not valid or not yet
4847  * allocated this will fall back to the object lock method.
4848  */
4849 int
4850 vm_page_grab_valid_unlocked(vm_page_t *mp, vm_object_t object,
4851     vm_pindex_t pindex, int allocflags)
4852 {
4853 	vm_page_t m;
4854 	int flags;
4855 	int error;
4856 
4857 	KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4858 	    (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4859 	    ("vm_page_grab_valid_unlocked: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY "
4860 	    "mismatch"));
4861 	KASSERT((allocflags &
4862 	    (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4863 	    ("vm_page_grab_valid_unlocked: Invalid flags 0x%X", allocflags));
4864 
4865 	/*
4866 	 * Attempt a lockless lookup and busy.  We need at least an sbusy
4867 	 * before we can inspect the valid field and return a wired page.
4868 	 */
4869 	flags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
4870 	if (!vm_page_acquire_unlocked(object, pindex, NULL, mp, flags))
4871 		return (VM_PAGER_FAIL);
4872 	if ((m = *mp) != NULL) {
4873 		if (vm_page_all_valid(m)) {
4874 			if ((allocflags & VM_ALLOC_WIRED) != 0)
4875 				vm_page_wire(m);
4876 			vm_page_grab_release(m, allocflags);
4877 			return (VM_PAGER_OK);
4878 		}
4879 		vm_page_busy_release(m);
4880 	}
4881 	if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4882 		*mp = NULL;
4883 		return (VM_PAGER_FAIL);
4884 	}
4885 	VM_OBJECT_WLOCK(object);
4886 	error = vm_page_grab_valid(mp, object, pindex, allocflags);
4887 	VM_OBJECT_WUNLOCK(object);
4888 
4889 	return (error);
4890 }
4891 
4892 /*
4893  * Return the specified range of pages from the given object.  For each
4894  * page offset within the range, if a page already exists within the object
4895  * at that offset and it is busy, then wait for it to change state.  If,
4896  * instead, the page doesn't exist, then allocate it.
4897  *
4898  * The caller must always specify an allocation class.
4899  *
4900  * allocation classes:
4901  *	VM_ALLOC_NORMAL		normal process request
4902  *	VM_ALLOC_SYSTEM		system *really* needs the pages
4903  *
4904  * The caller must always specify that the pages are to be busied and/or
4905  * wired.
4906  *
4907  * optional allocation flags:
4908  *	VM_ALLOC_IGN_SBUSY	do not sleep on soft busy pages
4909  *	VM_ALLOC_NOBUSY		do not exclusive busy the page
4910  *	VM_ALLOC_NOWAIT		do not sleep
4911  *	VM_ALLOC_SBUSY		set page to sbusy state
4912  *	VM_ALLOC_WIRED		wire the pages
4913  *	VM_ALLOC_ZERO		zero and validate any invalid pages
4914  *
4915  * If VM_ALLOC_NOWAIT is not specified, this routine may sleep.  Otherwise, it
4916  * may return a partial prefix of the requested range.
4917  */
4918 int
4919 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
4920     vm_page_t *ma, int count)
4921 {
4922 	vm_page_t m, mpred;
4923 	int pflags;
4924 	int i;
4925 
4926 	VM_OBJECT_ASSERT_WLOCKED(object);
4927 	KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
4928 	    ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
4929 	KASSERT(count > 0,
4930 	    ("vm_page_grab_pages: invalid page count %d", count));
4931 	vm_page_grab_check(allocflags);
4932 
4933 	pflags = vm_page_grab_pflags(allocflags);
4934 	i = 0;
4935 retrylookup:
4936 	m = vm_radix_lookup_le(&object->rtree, pindex + i);
4937 	if (m == NULL || m->pindex != pindex + i) {
4938 		mpred = m;
4939 		m = NULL;
4940 	} else
4941 		mpred = TAILQ_PREV(m, pglist, listq);
4942 	for (; i < count; i++) {
4943 		if (m != NULL) {
4944 			if (!vm_page_tryacquire(m, allocflags)) {
4945 				if (vm_page_grab_sleep(object, m, pindex + i,
4946 				    "grbmaw", allocflags, true))
4947 					goto retrylookup;
4948 				break;
4949 			}
4950 		} else {
4951 			if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4952 				break;
4953 			m = vm_page_alloc_after(object, pindex + i,
4954 			    pflags | VM_ALLOC_COUNT(count - i), mpred);
4955 			if (m == NULL) {
4956 				if ((allocflags & (VM_ALLOC_NOWAIT |
4957 				    VM_ALLOC_WAITFAIL)) != 0)
4958 					break;
4959 				goto retrylookup;
4960 			}
4961 		}
4962 		if (vm_page_none_valid(m) &&
4963 		    (allocflags & VM_ALLOC_ZERO) != 0) {
4964 			if ((m->flags & PG_ZERO) == 0)
4965 				pmap_zero_page(m);
4966 			vm_page_valid(m);
4967 		}
4968 		vm_page_grab_release(m, allocflags);
4969 		ma[i] = mpred = m;
4970 		m = vm_page_next(m);
4971 	}
4972 	return (i);
4973 }
4974 
4975 /*
4976  * Unlocked variant of vm_page_grab_pages().  This accepts the same flags
4977  * and will fall back to the locked variant to handle allocation.
4978  */
4979 int
4980 vm_page_grab_pages_unlocked(vm_object_t object, vm_pindex_t pindex,
4981     int allocflags, vm_page_t *ma, int count)
4982 {
4983 	vm_page_t m, pred;
4984 	int flags;
4985 	int i;
4986 
4987 	KASSERT(count > 0,
4988 	    ("vm_page_grab_pages_unlocked: invalid page count %d", count));
4989 	vm_page_grab_check(allocflags);
4990 
4991 	/*
4992 	 * Modify flags for lockless acquire to hold the page until we
4993 	 * set it valid if necessary.
4994 	 */
4995 	flags = allocflags & ~VM_ALLOC_NOBUSY;
4996 	pred = NULL;
4997 	for (i = 0; i < count; i++, pindex++) {
4998 		if (!vm_page_acquire_unlocked(object, pindex, pred, &m, flags))
4999 			return (i);
5000 		if (m == NULL)
5001 			break;
5002 		if ((flags & VM_ALLOC_ZERO) != 0 && vm_page_none_valid(m)) {
5003 			if ((m->flags & PG_ZERO) == 0)
5004 				pmap_zero_page(m);
5005 			vm_page_valid(m);
5006 		}
5007 		/* m will still be wired or busy according to flags. */
5008 		vm_page_grab_release(m, allocflags);
5009 		pred = ma[i] = m;
5010 	}
5011 	if (i == count || (allocflags & VM_ALLOC_NOCREAT) != 0)
5012 		return (i);
5013 	count -= i;
5014 	VM_OBJECT_WLOCK(object);
5015 	i += vm_page_grab_pages(object, pindex, allocflags, &ma[i], count);
5016 	VM_OBJECT_WUNLOCK(object);
5017 
5018 	return (i);
5019 }
5020 
5021 /*
5022  * Mapping function for valid or dirty bits in a page.
5023  *
5024  * Inputs are required to range within a page.
5025  */
5026 vm_page_bits_t
5027 vm_page_bits(int base, int size)
5028 {
5029 	int first_bit;
5030 	int last_bit;
5031 
5032 	KASSERT(
5033 	    base + size <= PAGE_SIZE,
5034 	    ("vm_page_bits: illegal base/size %d/%d", base, size)
5035 	);
5036 
5037 	if (size == 0)		/* handle degenerate case */
5038 		return (0);
5039 
5040 	first_bit = base >> DEV_BSHIFT;
5041 	last_bit = (base + size - 1) >> DEV_BSHIFT;
5042 
5043 	return (((vm_page_bits_t)2 << last_bit) -
5044 	    ((vm_page_bits_t)1 << first_bit));
5045 }
5046 
5047 void
5048 vm_page_bits_set(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t set)
5049 {
5050 
5051 #if PAGE_SIZE == 32768
5052 	atomic_set_64((uint64_t *)bits, set);
5053 #elif PAGE_SIZE == 16384
5054 	atomic_set_32((uint32_t *)bits, set);
5055 #elif (PAGE_SIZE == 8192) && defined(atomic_set_16)
5056 	atomic_set_16((uint16_t *)bits, set);
5057 #elif (PAGE_SIZE == 4096) && defined(atomic_set_8)
5058 	atomic_set_8((uint8_t *)bits, set);
5059 #else		/* PAGE_SIZE <= 8192 */
5060 	uintptr_t addr;
5061 	int shift;
5062 
5063 	addr = (uintptr_t)bits;
5064 	/*
5065 	 * Use a trick to perform a 32-bit atomic on the
5066 	 * containing aligned word, to not depend on the existence
5067 	 * of atomic_{set, clear}_{8, 16}.
5068 	 */
5069 	shift = addr & (sizeof(uint32_t) - 1);
5070 #if BYTE_ORDER == BIG_ENDIAN
5071 	shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
5072 #else
5073 	shift *= NBBY;
5074 #endif
5075 	addr &= ~(sizeof(uint32_t) - 1);
5076 	atomic_set_32((uint32_t *)addr, set << shift);
5077 #endif		/* PAGE_SIZE */
5078 }
5079 
5080 static inline void
5081 vm_page_bits_clear(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t clear)
5082 {
5083 
5084 #if PAGE_SIZE == 32768
5085 	atomic_clear_64((uint64_t *)bits, clear);
5086 #elif PAGE_SIZE == 16384
5087 	atomic_clear_32((uint32_t *)bits, clear);
5088 #elif (PAGE_SIZE == 8192) && defined(atomic_clear_16)
5089 	atomic_clear_16((uint16_t *)bits, clear);
5090 #elif (PAGE_SIZE == 4096) && defined(atomic_clear_8)
5091 	atomic_clear_8((uint8_t *)bits, clear);
5092 #else		/* PAGE_SIZE <= 8192 */
5093 	uintptr_t addr;
5094 	int shift;
5095 
5096 	addr = (uintptr_t)bits;
5097 	/*
5098 	 * Use a trick to perform a 32-bit atomic on the
5099 	 * containing aligned word, to not depend on the existence
5100 	 * of atomic_{set, clear}_{8, 16}.
5101 	 */
5102 	shift = addr & (sizeof(uint32_t) - 1);
5103 #if BYTE_ORDER == BIG_ENDIAN
5104 	shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
5105 #else
5106 	shift *= NBBY;
5107 #endif
5108 	addr &= ~(sizeof(uint32_t) - 1);
5109 	atomic_clear_32((uint32_t *)addr, clear << shift);
5110 #endif		/* PAGE_SIZE */
5111 }
5112 
5113 static inline vm_page_bits_t
5114 vm_page_bits_swap(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t newbits)
5115 {
5116 #if PAGE_SIZE == 32768
5117 	uint64_t old;
5118 
5119 	old = *bits;
5120 	while (atomic_fcmpset_64(bits, &old, newbits) == 0);
5121 	return (old);
5122 #elif PAGE_SIZE == 16384
5123 	uint32_t old;
5124 
5125 	old = *bits;
5126 	while (atomic_fcmpset_32(bits, &old, newbits) == 0);
5127 	return (old);
5128 #elif (PAGE_SIZE == 8192) && defined(atomic_fcmpset_16)
5129 	uint16_t old;
5130 
5131 	old = *bits;
5132 	while (atomic_fcmpset_16(bits, &old, newbits) == 0);
5133 	return (old);
5134 #elif (PAGE_SIZE == 4096) && defined(atomic_fcmpset_8)
5135 	uint8_t old;
5136 
5137 	old = *bits;
5138 	while (atomic_fcmpset_8(bits, &old, newbits) == 0);
5139 	return (old);
5140 #else		/* PAGE_SIZE <= 4096*/
5141 	uintptr_t addr;
5142 	uint32_t old, new, mask;
5143 	int shift;
5144 
5145 	addr = (uintptr_t)bits;
5146 	/*
5147 	 * Use a trick to perform a 32-bit atomic on the
5148 	 * containing aligned word, to not depend on the existence
5149 	 * of atomic_{set, swap, clear}_{8, 16}.
5150 	 */
5151 	shift = addr & (sizeof(uint32_t) - 1);
5152 #if BYTE_ORDER == BIG_ENDIAN
5153 	shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
5154 #else
5155 	shift *= NBBY;
5156 #endif
5157 	addr &= ~(sizeof(uint32_t) - 1);
5158 	mask = VM_PAGE_BITS_ALL << shift;
5159 
5160 	old = *bits;
5161 	do {
5162 		new = old & ~mask;
5163 		new |= newbits << shift;
5164 	} while (atomic_fcmpset_32((uint32_t *)addr, &old, new) == 0);
5165 	return (old >> shift);
5166 #endif		/* PAGE_SIZE */
5167 }
5168 
5169 /*
5170  *	vm_page_set_valid_range:
5171  *
5172  *	Sets portions of a page valid.  The arguments are expected
5173  *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
5174  *	of any partial chunks touched by the range.  The invalid portion of
5175  *	such chunks will be zeroed.
5176  *
5177  *	(base + size) must be less then or equal to PAGE_SIZE.
5178  */
5179 void
5180 vm_page_set_valid_range(vm_page_t m, int base, int size)
5181 {
5182 	int endoff, frag;
5183 	vm_page_bits_t pagebits;
5184 
5185 	vm_page_assert_busied(m);
5186 	if (size == 0)	/* handle degenerate case */
5187 		return;
5188 
5189 	/*
5190 	 * If the base is not DEV_BSIZE aligned and the valid
5191 	 * bit is clear, we have to zero out a portion of the
5192 	 * first block.
5193 	 */
5194 	if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5195 	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
5196 		pmap_zero_page_area(m, frag, base - frag);
5197 
5198 	/*
5199 	 * If the ending offset is not DEV_BSIZE aligned and the
5200 	 * valid bit is clear, we have to zero out a portion of
5201 	 * the last block.
5202 	 */
5203 	endoff = base + size;
5204 	if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5205 	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
5206 		pmap_zero_page_area(m, endoff,
5207 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5208 
5209 	/*
5210 	 * Assert that no previously invalid block that is now being validated
5211 	 * is already dirty.
5212 	 */
5213 	KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
5214 	    ("vm_page_set_valid_range: page %p is dirty", m));
5215 
5216 	/*
5217 	 * Set valid bits inclusive of any overlap.
5218 	 */
5219 	pagebits = vm_page_bits(base, size);
5220 	if (vm_page_xbusied(m))
5221 		m->valid |= pagebits;
5222 	else
5223 		vm_page_bits_set(m, &m->valid, pagebits);
5224 }
5225 
5226 /*
5227  * Set the page dirty bits and free the invalid swap space if
5228  * present.  Returns the previous dirty bits.
5229  */
5230 vm_page_bits_t
5231 vm_page_set_dirty(vm_page_t m)
5232 {
5233 	vm_page_bits_t old;
5234 
5235 	VM_PAGE_OBJECT_BUSY_ASSERT(m);
5236 
5237 	if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m)) {
5238 		old = m->dirty;
5239 		m->dirty = VM_PAGE_BITS_ALL;
5240 	} else
5241 		old = vm_page_bits_swap(m, &m->dirty, VM_PAGE_BITS_ALL);
5242 	if (old == 0 && (m->a.flags & PGA_SWAP_SPACE) != 0)
5243 		vm_pager_page_unswapped(m);
5244 
5245 	return (old);
5246 }
5247 
5248 /*
5249  * Clear the given bits from the specified page's dirty field.
5250  */
5251 static __inline void
5252 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
5253 {
5254 
5255 	vm_page_assert_busied(m);
5256 
5257 	/*
5258 	 * If the page is xbusied and not write mapped we are the
5259 	 * only thread that can modify dirty bits.  Otherwise, The pmap
5260 	 * layer can call vm_page_dirty() without holding a distinguished
5261 	 * lock.  The combination of page busy and atomic operations
5262 	 * suffice to guarantee consistency of the page dirty field.
5263 	 */
5264 	if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
5265 		m->dirty &= ~pagebits;
5266 	else
5267 		vm_page_bits_clear(m, &m->dirty, pagebits);
5268 }
5269 
5270 /*
5271  *	vm_page_set_validclean:
5272  *
5273  *	Sets portions of a page valid and clean.  The arguments are expected
5274  *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
5275  *	of any partial chunks touched by the range.  The invalid portion of
5276  *	such chunks will be zero'd.
5277  *
5278  *	(base + size) must be less then or equal to PAGE_SIZE.
5279  */
5280 void
5281 vm_page_set_validclean(vm_page_t m, int base, int size)
5282 {
5283 	vm_page_bits_t oldvalid, pagebits;
5284 	int endoff, frag;
5285 
5286 	vm_page_assert_busied(m);
5287 	if (size == 0)	/* handle degenerate case */
5288 		return;
5289 
5290 	/*
5291 	 * If the base is not DEV_BSIZE aligned and the valid
5292 	 * bit is clear, we have to zero out a portion of the
5293 	 * first block.
5294 	 */
5295 	if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5296 	    (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
5297 		pmap_zero_page_area(m, frag, base - frag);
5298 
5299 	/*
5300 	 * If the ending offset is not DEV_BSIZE aligned and the
5301 	 * valid bit is clear, we have to zero out a portion of
5302 	 * the last block.
5303 	 */
5304 	endoff = base + size;
5305 	if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5306 	    (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
5307 		pmap_zero_page_area(m, endoff,
5308 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5309 
5310 	/*
5311 	 * Set valid, clear dirty bits.  If validating the entire
5312 	 * page we can safely clear the pmap modify bit.  We also
5313 	 * use this opportunity to clear the PGA_NOSYNC flag.  If a process
5314 	 * takes a write fault on a MAP_NOSYNC memory area the flag will
5315 	 * be set again.
5316 	 *
5317 	 * We set valid bits inclusive of any overlap, but we can only
5318 	 * clear dirty bits for DEV_BSIZE chunks that are fully within
5319 	 * the range.
5320 	 */
5321 	oldvalid = m->valid;
5322 	pagebits = vm_page_bits(base, size);
5323 	if (vm_page_xbusied(m))
5324 		m->valid |= pagebits;
5325 	else
5326 		vm_page_bits_set(m, &m->valid, pagebits);
5327 #if 0	/* NOT YET */
5328 	if ((frag = base & (DEV_BSIZE - 1)) != 0) {
5329 		frag = DEV_BSIZE - frag;
5330 		base += frag;
5331 		size -= frag;
5332 		if (size < 0)
5333 			size = 0;
5334 	}
5335 	pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
5336 #endif
5337 	if (base == 0 && size == PAGE_SIZE) {
5338 		/*
5339 		 * The page can only be modified within the pmap if it is
5340 		 * mapped, and it can only be mapped if it was previously
5341 		 * fully valid.
5342 		 */
5343 		if (oldvalid == VM_PAGE_BITS_ALL)
5344 			/*
5345 			 * Perform the pmap_clear_modify() first.  Otherwise,
5346 			 * a concurrent pmap operation, such as
5347 			 * pmap_protect(), could clear a modification in the
5348 			 * pmap and set the dirty field on the page before
5349 			 * pmap_clear_modify() had begun and after the dirty
5350 			 * field was cleared here.
5351 			 */
5352 			pmap_clear_modify(m);
5353 		m->dirty = 0;
5354 		vm_page_aflag_clear(m, PGA_NOSYNC);
5355 	} else if (oldvalid != VM_PAGE_BITS_ALL && vm_page_xbusied(m))
5356 		m->dirty &= ~pagebits;
5357 	else
5358 		vm_page_clear_dirty_mask(m, pagebits);
5359 }
5360 
5361 void
5362 vm_page_clear_dirty(vm_page_t m, int base, int size)
5363 {
5364 
5365 	vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
5366 }
5367 
5368 /*
5369  *	vm_page_set_invalid:
5370  *
5371  *	Invalidates DEV_BSIZE'd chunks within a page.  Both the
5372  *	valid and dirty bits for the effected areas are cleared.
5373  */
5374 void
5375 vm_page_set_invalid(vm_page_t m, int base, int size)
5376 {
5377 	vm_page_bits_t bits;
5378 	vm_object_t object;
5379 
5380 	/*
5381 	 * The object lock is required so that pages can't be mapped
5382 	 * read-only while we're in the process of invalidating them.
5383 	 */
5384 	object = m->object;
5385 	VM_OBJECT_ASSERT_WLOCKED(object);
5386 	vm_page_assert_busied(m);
5387 
5388 	if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
5389 	    size >= object->un_pager.vnp.vnp_size)
5390 		bits = VM_PAGE_BITS_ALL;
5391 	else
5392 		bits = vm_page_bits(base, size);
5393 	if (object->ref_count != 0 && vm_page_all_valid(m) && bits != 0)
5394 		pmap_remove_all(m);
5395 	KASSERT((bits == 0 && vm_page_all_valid(m)) ||
5396 	    !pmap_page_is_mapped(m),
5397 	    ("vm_page_set_invalid: page %p is mapped", m));
5398 	if (vm_page_xbusied(m)) {
5399 		m->valid &= ~bits;
5400 		m->dirty &= ~bits;
5401 	} else {
5402 		vm_page_bits_clear(m, &m->valid, bits);
5403 		vm_page_bits_clear(m, &m->dirty, bits);
5404 	}
5405 }
5406 
5407 /*
5408  *	vm_page_invalid:
5409  *
5410  *	Invalidates the entire page.  The page must be busy, unmapped, and
5411  *	the enclosing object must be locked.  The object locks protects
5412  *	against concurrent read-only pmap enter which is done without
5413  *	busy.
5414  */
5415 void
5416 vm_page_invalid(vm_page_t m)
5417 {
5418 
5419 	vm_page_assert_busied(m);
5420 	VM_OBJECT_ASSERT_WLOCKED(m->object);
5421 	MPASS(!pmap_page_is_mapped(m));
5422 
5423 	if (vm_page_xbusied(m))
5424 		m->valid = 0;
5425 	else
5426 		vm_page_bits_clear(m, &m->valid, VM_PAGE_BITS_ALL);
5427 }
5428 
5429 /*
5430  * vm_page_zero_invalid()
5431  *
5432  *	The kernel assumes that the invalid portions of a page contain
5433  *	garbage, but such pages can be mapped into memory by user code.
5434  *	When this occurs, we must zero out the non-valid portions of the
5435  *	page so user code sees what it expects.
5436  *
5437  *	Pages are most often semi-valid when the end of a file is mapped
5438  *	into memory and the file's size is not page aligned.
5439  */
5440 void
5441 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
5442 {
5443 	int b;
5444 	int i;
5445 
5446 	/*
5447 	 * Scan the valid bits looking for invalid sections that
5448 	 * must be zeroed.  Invalid sub-DEV_BSIZE'd areas ( where the
5449 	 * valid bit may be set ) have already been zeroed by
5450 	 * vm_page_set_validclean().
5451 	 */
5452 	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
5453 		if (i == (PAGE_SIZE / DEV_BSIZE) ||
5454 		    (m->valid & ((vm_page_bits_t)1 << i))) {
5455 			if (i > b) {
5456 				pmap_zero_page_area(m,
5457 				    b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
5458 			}
5459 			b = i + 1;
5460 		}
5461 	}
5462 
5463 	/*
5464 	 * setvalid is TRUE when we can safely set the zero'd areas
5465 	 * as being valid.  We can do this if there are no cache consistency
5466 	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
5467 	 */
5468 	if (setvalid)
5469 		vm_page_valid(m);
5470 }
5471 
5472 /*
5473  *	vm_page_is_valid:
5474  *
5475  *	Is (partial) page valid?  Note that the case where size == 0
5476  *	will return FALSE in the degenerate case where the page is
5477  *	entirely invalid, and TRUE otherwise.
5478  *
5479  *	Some callers envoke this routine without the busy lock held and
5480  *	handle races via higher level locks.  Typical callers should
5481  *	hold a busy lock to prevent invalidation.
5482  */
5483 int
5484 vm_page_is_valid(vm_page_t m, int base, int size)
5485 {
5486 	vm_page_bits_t bits;
5487 
5488 	bits = vm_page_bits(base, size);
5489 	return (vm_page_any_valid(m) && (m->valid & bits) == bits);
5490 }
5491 
5492 /*
5493  * Returns true if all of the specified predicates are true for the entire
5494  * (super)page and false otherwise.
5495  */
5496 bool
5497 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
5498 {
5499 	vm_object_t object;
5500 	int i, npages;
5501 
5502 	object = m->object;
5503 	if (skip_m != NULL && skip_m->object != object)
5504 		return (false);
5505 	VM_OBJECT_ASSERT_LOCKED(object);
5506 	npages = atop(pagesizes[m->psind]);
5507 
5508 	/*
5509 	 * The physically contiguous pages that make up a superpage, i.e., a
5510 	 * page with a page size index ("psind") greater than zero, will
5511 	 * occupy adjacent entries in vm_page_array[].
5512 	 */
5513 	for (i = 0; i < npages; i++) {
5514 		/* Always test object consistency, including "skip_m". */
5515 		if (m[i].object != object)
5516 			return (false);
5517 		if (&m[i] == skip_m)
5518 			continue;
5519 		if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
5520 			return (false);
5521 		if ((flags & PS_ALL_DIRTY) != 0) {
5522 			/*
5523 			 * Calling vm_page_test_dirty() or pmap_is_modified()
5524 			 * might stop this case from spuriously returning
5525 			 * "false".  However, that would require a write lock
5526 			 * on the object containing "m[i]".
5527 			 */
5528 			if (m[i].dirty != VM_PAGE_BITS_ALL)
5529 				return (false);
5530 		}
5531 		if ((flags & PS_ALL_VALID) != 0 &&
5532 		    m[i].valid != VM_PAGE_BITS_ALL)
5533 			return (false);
5534 	}
5535 	return (true);
5536 }
5537 
5538 /*
5539  * Set the page's dirty bits if the page is modified.
5540  */
5541 void
5542 vm_page_test_dirty(vm_page_t m)
5543 {
5544 
5545 	vm_page_assert_busied(m);
5546 	if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
5547 		vm_page_dirty(m);
5548 }
5549 
5550 void
5551 vm_page_valid(vm_page_t m)
5552 {
5553 
5554 	vm_page_assert_busied(m);
5555 	if (vm_page_xbusied(m))
5556 		m->valid = VM_PAGE_BITS_ALL;
5557 	else
5558 		vm_page_bits_set(m, &m->valid, VM_PAGE_BITS_ALL);
5559 }
5560 
5561 void
5562 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
5563 {
5564 
5565 	mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
5566 }
5567 
5568 void
5569 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
5570 {
5571 
5572 	mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
5573 }
5574 
5575 int
5576 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
5577 {
5578 
5579 	return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
5580 }
5581 
5582 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
5583 void
5584 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
5585 {
5586 
5587 	vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
5588 }
5589 
5590 void
5591 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
5592 {
5593 
5594 	mtx_assert_(vm_page_lockptr(m), a, file, line);
5595 }
5596 #endif
5597 
5598 #ifdef INVARIANTS
5599 void
5600 vm_page_object_busy_assert(vm_page_t m)
5601 {
5602 
5603 	/*
5604 	 * Certain of the page's fields may only be modified by the
5605 	 * holder of a page or object busy.
5606 	 */
5607 	if (m->object != NULL && !vm_page_busied(m))
5608 		VM_OBJECT_ASSERT_BUSY(m->object);
5609 }
5610 
5611 void
5612 vm_page_assert_pga_writeable(vm_page_t m, uint16_t bits)
5613 {
5614 
5615 	if ((bits & PGA_WRITEABLE) == 0)
5616 		return;
5617 
5618 	/*
5619 	 * The PGA_WRITEABLE flag can only be set if the page is
5620 	 * managed, is exclusively busied or the object is locked.
5621 	 * Currently, this flag is only set by pmap_enter().
5622 	 */
5623 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5624 	    ("PGA_WRITEABLE on unmanaged page"));
5625 	if (!vm_page_xbusied(m))
5626 		VM_OBJECT_ASSERT_BUSY(m->object);
5627 }
5628 #endif
5629 
5630 #include "opt_ddb.h"
5631 #ifdef DDB
5632 #include <sys/kernel.h>
5633 
5634 #include <ddb/ddb.h>
5635 
5636 DB_SHOW_COMMAND_FLAGS(page, vm_page_print_page_info, DB_CMD_MEMSAFE)
5637 {
5638 
5639 	db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
5640 	db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
5641 	db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
5642 	db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
5643 	db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
5644 	db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
5645 	db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
5646 	db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
5647 	db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
5648 }
5649 
5650 DB_SHOW_COMMAND_FLAGS(pageq, vm_page_print_pageq_info, DB_CMD_MEMSAFE)
5651 {
5652 	int dom;
5653 
5654 	db_printf("pq_free %d\n", vm_free_count());
5655 	for (dom = 0; dom < vm_ndomains; dom++) {
5656 		db_printf(
5657     "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
5658 		    dom,
5659 		    vm_dom[dom].vmd_page_count,
5660 		    vm_dom[dom].vmd_free_count,
5661 		    vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
5662 		    vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
5663 		    vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
5664 		    vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
5665 	}
5666 }
5667 
5668 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
5669 {
5670 	vm_page_t m;
5671 	boolean_t phys, virt;
5672 
5673 	if (!have_addr) {
5674 		db_printf("show pginfo addr\n");
5675 		return;
5676 	}
5677 
5678 	phys = strchr(modif, 'p') != NULL;
5679 	virt = strchr(modif, 'v') != NULL;
5680 	if (virt)
5681 		m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
5682 	else if (phys)
5683 		m = PHYS_TO_VM_PAGE(addr);
5684 	else
5685 		m = (vm_page_t)addr;
5686 	db_printf(
5687     "page %p obj %p pidx 0x%jx phys 0x%jx q %d ref 0x%x\n"
5688     "  af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
5689 	    m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
5690 	    m->a.queue, m->ref_count, m->a.flags, m->oflags,
5691 	    m->flags, m->a.act_count, m->busy_lock, m->valid, m->dirty);
5692 }
5693 #endif /* DDB */
5694