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