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