xref: /freebsd/sys/vm/vm_page.c (revision 57f804675e65951d630a38d94c07be4a27ae4053)
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  *	vm_page_relookup:
1675  *
1676  *	Returns a page that must already have been busied by
1677  *	the caller.  Used for bogus page replacement.
1678  */
1679 vm_page_t
1680 vm_page_relookup(vm_object_t object, vm_pindex_t pindex)
1681 {
1682 	vm_page_t m;
1683 
1684 	m = vm_radix_lookup_unlocked(&object->rtree, pindex);
1685 	KASSERT(m != NULL && vm_page_busied(m) &&
1686 	    m->object == object && m->pindex == pindex,
1687 	    ("vm_page_relookup: Invalid page %p", m));
1688 	return (m);
1689 }
1690 
1691 /*
1692  * This should only be used by lockless functions for releasing transient
1693  * incorrect acquires.  The page may have been freed after we acquired a
1694  * busy lock.  In this case busy_lock == VPB_FREED and we have nothing
1695  * further to do.
1696  */
1697 static void
1698 vm_page_busy_release(vm_page_t m)
1699 {
1700 	u_int x;
1701 
1702 	x = atomic_load_int(&m->busy_lock);
1703 	for (;;) {
1704 		if (x == VPB_FREED)
1705 			break;
1706 		if ((x & VPB_BIT_SHARED) != 0 && VPB_SHARERS(x) > 1) {
1707 			if (atomic_fcmpset_int(&m->busy_lock, &x,
1708 			    x - VPB_ONE_SHARER))
1709 				break;
1710 			continue;
1711 		}
1712 		KASSERT((x & VPB_BIT_SHARED) != 0 ||
1713 		    (x & ~VPB_BIT_WAITERS) == VPB_CURTHREAD_EXCLUSIVE,
1714 		    ("vm_page_busy_release: %p xbusy not owned.", m));
1715 		if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
1716 			continue;
1717 		if ((x & VPB_BIT_WAITERS) != 0)
1718 			wakeup(m);
1719 		break;
1720 	}
1721 }
1722 
1723 /*
1724  *	vm_page_find_least:
1725  *
1726  *	Returns the page associated with the object with least pindex
1727  *	greater than or equal to the parameter pindex, or NULL.
1728  *
1729  *	The object must be locked.
1730  */
1731 vm_page_t
1732 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1733 {
1734 	vm_page_t m;
1735 
1736 	VM_OBJECT_ASSERT_LOCKED(object);
1737 	if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1738 		m = vm_radix_lookup_ge(&object->rtree, pindex);
1739 	return (m);
1740 }
1741 
1742 /*
1743  * Returns the given page's successor (by pindex) within the object if it is
1744  * resident; if none is found, NULL is returned.
1745  *
1746  * The object must be locked.
1747  */
1748 vm_page_t
1749 vm_page_next(vm_page_t m)
1750 {
1751 	vm_page_t next;
1752 
1753 	VM_OBJECT_ASSERT_LOCKED(m->object);
1754 	if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1755 		MPASS(next->object == m->object);
1756 		if (next->pindex != m->pindex + 1)
1757 			next = NULL;
1758 	}
1759 	return (next);
1760 }
1761 
1762 /*
1763  * Returns the given page's predecessor (by pindex) within the object if it is
1764  * resident; if none is found, NULL is returned.
1765  *
1766  * The object must be locked.
1767  */
1768 vm_page_t
1769 vm_page_prev(vm_page_t m)
1770 {
1771 	vm_page_t prev;
1772 
1773 	VM_OBJECT_ASSERT_LOCKED(m->object);
1774 	if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1775 		MPASS(prev->object == m->object);
1776 		if (prev->pindex != m->pindex - 1)
1777 			prev = NULL;
1778 	}
1779 	return (prev);
1780 }
1781 
1782 /*
1783  * Uses the page mnew as a replacement for an existing page at index
1784  * pindex which must be already present in the object.
1785  *
1786  * Both pages must be exclusively busied on enter.  The old page is
1787  * unbusied on exit.
1788  *
1789  * A return value of true means mold is now free.  If this is not the
1790  * final ref and the caller does not hold a wire reference it may not
1791  * continue to access the page.
1792  */
1793 static bool
1794 vm_page_replace_hold(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1795     vm_page_t mold)
1796 {
1797 	vm_page_t mret;
1798 	bool dropped;
1799 
1800 	VM_OBJECT_ASSERT_WLOCKED(object);
1801 	vm_page_assert_xbusied(mold);
1802 	KASSERT(mnew->object == NULL && (mnew->ref_count & VPRC_OBJREF) == 0,
1803 	    ("vm_page_replace: page %p already in object", mnew));
1804 
1805 	/*
1806 	 * This function mostly follows vm_page_insert() and
1807 	 * vm_page_remove() without the radix, object count and vnode
1808 	 * dance.  Double check such functions for more comments.
1809 	 */
1810 
1811 	mnew->object = object;
1812 	mnew->pindex = pindex;
1813 	atomic_set_int(&mnew->ref_count, VPRC_OBJREF);
1814 	mret = vm_radix_replace(&object->rtree, mnew);
1815 	KASSERT(mret == mold,
1816 	    ("invalid page replacement, mold=%p, mret=%p", mold, mret));
1817 	KASSERT((mold->oflags & VPO_UNMANAGED) ==
1818 	    (mnew->oflags & VPO_UNMANAGED),
1819 	    ("vm_page_replace: mismatched VPO_UNMANAGED"));
1820 
1821 	/* Keep the resident page list in sorted order. */
1822 	TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1823 	TAILQ_REMOVE(&object->memq, mold, listq);
1824 	mold->object = NULL;
1825 
1826 	/*
1827 	 * The object's resident_page_count does not change because we have
1828 	 * swapped one page for another, but the generation count should
1829 	 * change if the page is dirty.
1830 	 */
1831 	if (pmap_page_is_write_mapped(mnew))
1832 		vm_object_set_writeable_dirty(object);
1833 	dropped = vm_page_drop(mold, VPRC_OBJREF) == VPRC_OBJREF;
1834 	vm_page_xunbusy(mold);
1835 
1836 	return (dropped);
1837 }
1838 
1839 void
1840 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1841     vm_page_t mold)
1842 {
1843 
1844 	vm_page_assert_xbusied(mnew);
1845 
1846 	if (vm_page_replace_hold(mnew, object, pindex, mold))
1847 		vm_page_free(mold);
1848 }
1849 
1850 /*
1851  *	vm_page_rename:
1852  *
1853  *	Move the given memory entry from its
1854  *	current object to the specified target object/offset.
1855  *
1856  *	Note: swap associated with the page must be invalidated by the move.  We
1857  *	      have to do this for several reasons:  (1) we aren't freeing the
1858  *	      page, (2) we are dirtying the page, (3) the VM system is probably
1859  *	      moving the page from object A to B, and will then later move
1860  *	      the backing store from A to B and we can't have a conflict.
1861  *
1862  *	Note: we *always* dirty the page.  It is necessary both for the
1863  *	      fact that we moved it, and because we may be invalidating
1864  *	      swap.
1865  *
1866  *	The objects must be locked.
1867  */
1868 int
1869 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1870 {
1871 	vm_page_t mpred;
1872 	vm_pindex_t opidx;
1873 
1874 	VM_OBJECT_ASSERT_WLOCKED(new_object);
1875 
1876 	KASSERT(m->ref_count != 0, ("vm_page_rename: page %p has no refs", m));
1877 	mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1878 	KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1879 	    ("vm_page_rename: pindex already renamed"));
1880 
1881 	/*
1882 	 * Create a custom version of vm_page_insert() which does not depend
1883 	 * by m_prev and can cheat on the implementation aspects of the
1884 	 * function.
1885 	 */
1886 	opidx = m->pindex;
1887 	m->pindex = new_pindex;
1888 	if (vm_radix_insert(&new_object->rtree, m)) {
1889 		m->pindex = opidx;
1890 		return (1);
1891 	}
1892 
1893 	/*
1894 	 * The operation cannot fail anymore.  The removal must happen before
1895 	 * the listq iterator is tainted.
1896 	 */
1897 	m->pindex = opidx;
1898 	vm_page_object_remove(m);
1899 
1900 	/* Return back to the new pindex to complete vm_page_insert(). */
1901 	m->pindex = new_pindex;
1902 	m->object = new_object;
1903 
1904 	vm_page_insert_radixdone(m, new_object, mpred);
1905 	vm_page_dirty(m);
1906 	return (0);
1907 }
1908 
1909 /*
1910  *	vm_page_alloc:
1911  *
1912  *	Allocate and return a page that is associated with the specified
1913  *	object and offset pair.  By default, this page is exclusive busied.
1914  *
1915  *	The caller must always specify an allocation class.
1916  *
1917  *	allocation classes:
1918  *	VM_ALLOC_NORMAL		normal process request
1919  *	VM_ALLOC_SYSTEM		system *really* needs a page
1920  *	VM_ALLOC_INTERRUPT	interrupt time request
1921  *
1922  *	optional allocation flags:
1923  *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
1924  *				intends to allocate
1925  *	VM_ALLOC_NOBUSY		do not exclusive busy the page
1926  *	VM_ALLOC_NODUMP		do not include the page in a kernel core dump
1927  *	VM_ALLOC_NOOBJ		page is not associated with an object and
1928  *				should not be exclusive busy
1929  *	VM_ALLOC_SBUSY		shared busy the allocated page
1930  *	VM_ALLOC_WIRED		wire the allocated page
1931  *	VM_ALLOC_ZERO		prefer a zeroed page
1932  */
1933 vm_page_t
1934 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1935 {
1936 
1937 	return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1938 	    vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1939 }
1940 
1941 vm_page_t
1942 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1943     int req)
1944 {
1945 
1946 	return (vm_page_alloc_domain_after(object, pindex, domain, req,
1947 	    object != NULL ? vm_radix_lookup_le(&object->rtree, pindex) :
1948 	    NULL));
1949 }
1950 
1951 /*
1952  * Allocate a page in the specified object with the given page index.  To
1953  * optimize insertion of the page into the object, the caller must also specifiy
1954  * the resident page in the object with largest index smaller than the given
1955  * page index, or NULL if no such page exists.
1956  */
1957 vm_page_t
1958 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1959     int req, vm_page_t mpred)
1960 {
1961 	struct vm_domainset_iter di;
1962 	vm_page_t m;
1963 	int domain;
1964 
1965 	vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1966 	do {
1967 		m = vm_page_alloc_domain_after(object, pindex, domain, req,
1968 		    mpred);
1969 		if (m != NULL)
1970 			break;
1971 	} while (vm_domainset_iter_page(&di, object, &domain) == 0);
1972 
1973 	return (m);
1974 }
1975 
1976 /*
1977  * Returns true if the number of free pages exceeds the minimum
1978  * for the request class and false otherwise.
1979  */
1980 static int
1981 _vm_domain_allocate(struct vm_domain *vmd, int req_class, int npages)
1982 {
1983 	u_int limit, old, new;
1984 
1985 	if (req_class == VM_ALLOC_INTERRUPT)
1986 		limit = 0;
1987 	else if (req_class == VM_ALLOC_SYSTEM)
1988 		limit = vmd->vmd_interrupt_free_min;
1989 	else
1990 		limit = vmd->vmd_free_reserved;
1991 
1992 	/*
1993 	 * Attempt to reserve the pages.  Fail if we're below the limit.
1994 	 */
1995 	limit += npages;
1996 	old = vmd->vmd_free_count;
1997 	do {
1998 		if (old < limit)
1999 			return (0);
2000 		new = old - npages;
2001 	} while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
2002 
2003 	/* Wake the page daemon if we've crossed the threshold. */
2004 	if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
2005 		pagedaemon_wakeup(vmd->vmd_domain);
2006 
2007 	/* Only update bitsets on transitions. */
2008 	if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
2009 	    (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
2010 		vm_domain_set(vmd);
2011 
2012 	return (1);
2013 }
2014 
2015 int
2016 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
2017 {
2018 	int req_class;
2019 
2020 	/*
2021 	 * The page daemon is allowed to dig deeper into the free page list.
2022 	 */
2023 	req_class = req & VM_ALLOC_CLASS_MASK;
2024 	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2025 		req_class = VM_ALLOC_SYSTEM;
2026 	return (_vm_domain_allocate(vmd, req_class, npages));
2027 }
2028 
2029 vm_page_t
2030 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
2031     int req, vm_page_t mpred)
2032 {
2033 	struct vm_domain *vmd;
2034 	vm_page_t m;
2035 	int flags, pool;
2036 
2037 	KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
2038 	    (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
2039 	    ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2040 	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2041 	    ("inconsistent object(%p)/req(%x)", object, req));
2042 	KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2043 	    ("Can't sleep and retry object insertion."));
2044 	KASSERT(mpred == NULL || mpred->pindex < pindex,
2045 	    ("mpred %p doesn't precede pindex 0x%jx", mpred,
2046 	    (uintmax_t)pindex));
2047 	if (object != NULL)
2048 		VM_OBJECT_ASSERT_WLOCKED(object);
2049 
2050 	flags = 0;
2051 	m = NULL;
2052 	pool = object != NULL ? VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT;
2053 again:
2054 #if VM_NRESERVLEVEL > 0
2055 	/*
2056 	 * Can we allocate the page from a reservation?
2057 	 */
2058 	if (vm_object_reserv(object) &&
2059 	    (m = vm_reserv_alloc_page(object, pindex, domain, req, mpred)) !=
2060 	    NULL) {
2061 		domain = vm_phys_domain(m);
2062 		vmd = VM_DOMAIN(domain);
2063 		goto found;
2064 	}
2065 #endif
2066 	vmd = VM_DOMAIN(domain);
2067 	if (vmd->vmd_pgcache[pool].zone != NULL) {
2068 		m = uma_zalloc(vmd->vmd_pgcache[pool].zone, M_NOWAIT | M_NOVM);
2069 		if (m != NULL) {
2070 			flags |= PG_PCPU_CACHE;
2071 			goto found;
2072 		}
2073 	}
2074 	if (vm_domain_allocate(vmd, req, 1)) {
2075 		/*
2076 		 * If not, allocate it from the free page queues.
2077 		 */
2078 		vm_domain_free_lock(vmd);
2079 		m = vm_phys_alloc_pages(domain, pool, 0);
2080 		vm_domain_free_unlock(vmd);
2081 		if (m == NULL) {
2082 			vm_domain_freecnt_inc(vmd, 1);
2083 #if VM_NRESERVLEVEL > 0
2084 			if (vm_reserv_reclaim_inactive(domain))
2085 				goto again;
2086 #endif
2087 		}
2088 	}
2089 	if (m == NULL) {
2090 		/*
2091 		 * Not allocatable, give up.
2092 		 */
2093 		if (vm_domain_alloc_fail(vmd, object, req))
2094 			goto again;
2095 		return (NULL);
2096 	}
2097 
2098 	/*
2099 	 * At this point we had better have found a good page.
2100 	 */
2101 found:
2102 	vm_page_dequeue(m);
2103 	vm_page_alloc_check(m);
2104 
2105 	/*
2106 	 * Initialize the page.  Only the PG_ZERO flag is inherited.
2107 	 */
2108 	if ((req & VM_ALLOC_ZERO) != 0)
2109 		flags |= (m->flags & PG_ZERO);
2110 	if ((req & VM_ALLOC_NODUMP) != 0)
2111 		flags |= PG_NODUMP;
2112 	m->flags = flags;
2113 	m->a.flags = 0;
2114 	m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2115 	    VPO_UNMANAGED : 0;
2116 	if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2117 		m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2118 	else if ((req & VM_ALLOC_SBUSY) != 0)
2119 		m->busy_lock = VPB_SHARERS_WORD(1);
2120 	else
2121 		m->busy_lock = VPB_UNBUSIED;
2122 	if (req & VM_ALLOC_WIRED) {
2123 		vm_wire_add(1);
2124 		m->ref_count = 1;
2125 	}
2126 	m->a.act_count = 0;
2127 
2128 	if (object != NULL) {
2129 		if (vm_page_insert_after(m, object, pindex, mpred)) {
2130 			if (req & VM_ALLOC_WIRED) {
2131 				vm_wire_sub(1);
2132 				m->ref_count = 0;
2133 			}
2134 			KASSERT(m->object == NULL, ("page %p has object", m));
2135 			m->oflags = VPO_UNMANAGED;
2136 			m->busy_lock = VPB_UNBUSIED;
2137 			/* Don't change PG_ZERO. */
2138 			vm_page_free_toq(m);
2139 			if (req & VM_ALLOC_WAITFAIL) {
2140 				VM_OBJECT_WUNLOCK(object);
2141 				vm_radix_wait();
2142 				VM_OBJECT_WLOCK(object);
2143 			}
2144 			return (NULL);
2145 		}
2146 
2147 		/* Ignore device objects; the pager sets "memattr" for them. */
2148 		if (object->memattr != VM_MEMATTR_DEFAULT &&
2149 		    (object->flags & OBJ_FICTITIOUS) == 0)
2150 			pmap_page_set_memattr(m, object->memattr);
2151 	} else
2152 		m->pindex = pindex;
2153 
2154 	return (m);
2155 }
2156 
2157 /*
2158  *	vm_page_alloc_contig:
2159  *
2160  *	Allocate a contiguous set of physical pages of the given size "npages"
2161  *	from the free lists.  All of the physical pages must be at or above
2162  *	the given physical address "low" and below the given physical address
2163  *	"high".  The given value "alignment" determines the alignment of the
2164  *	first physical page in the set.  If the given value "boundary" is
2165  *	non-zero, then the set of physical pages cannot cross any physical
2166  *	address boundary that is a multiple of that value.  Both "alignment"
2167  *	and "boundary" must be a power of two.
2168  *
2169  *	If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
2170  *	then the memory attribute setting for the physical pages is configured
2171  *	to the object's memory attribute setting.  Otherwise, the memory
2172  *	attribute setting for the physical pages is configured to "memattr",
2173  *	overriding the object's memory attribute setting.  However, if the
2174  *	object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
2175  *	memory attribute setting for the physical pages cannot be configured
2176  *	to VM_MEMATTR_DEFAULT.
2177  *
2178  *	The specified object may not contain fictitious pages.
2179  *
2180  *	The caller must always specify an allocation class.
2181  *
2182  *	allocation classes:
2183  *	VM_ALLOC_NORMAL		normal process request
2184  *	VM_ALLOC_SYSTEM		system *really* needs a page
2185  *	VM_ALLOC_INTERRUPT	interrupt time request
2186  *
2187  *	optional allocation flags:
2188  *	VM_ALLOC_NOBUSY		do not exclusive busy the page
2189  *	VM_ALLOC_NODUMP		do not include the page in a kernel core dump
2190  *	VM_ALLOC_NOOBJ		page is not associated with an object and
2191  *				should not be exclusive busy
2192  *	VM_ALLOC_SBUSY		shared busy the allocated page
2193  *	VM_ALLOC_WIRED		wire the allocated page
2194  *	VM_ALLOC_ZERO		prefer a zeroed page
2195  */
2196 vm_page_t
2197 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
2198     u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2199     vm_paddr_t boundary, vm_memattr_t memattr)
2200 {
2201 	struct vm_domainset_iter di;
2202 	vm_page_t m;
2203 	int domain;
2204 
2205 	vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
2206 	do {
2207 		m = vm_page_alloc_contig_domain(object, pindex, domain, req,
2208 		    npages, low, high, alignment, boundary, memattr);
2209 		if (m != NULL)
2210 			break;
2211 	} while (vm_domainset_iter_page(&di, object, &domain) == 0);
2212 
2213 	return (m);
2214 }
2215 
2216 vm_page_t
2217 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
2218     int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2219     vm_paddr_t boundary, vm_memattr_t memattr)
2220 {
2221 	struct vm_domain *vmd;
2222 	vm_page_t m, m_ret, mpred;
2223 	u_int busy_lock, flags, oflags;
2224 
2225 	mpred = NULL;	/* XXX: pacify gcc */
2226 	KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
2227 	    (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
2228 	    ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2229 	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2230 	    ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
2231 	    req));
2232 	KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2233 	    ("Can't sleep and retry object insertion."));
2234 	if (object != NULL) {
2235 		VM_OBJECT_ASSERT_WLOCKED(object);
2236 		KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2237 		    ("vm_page_alloc_contig: object %p has fictitious pages",
2238 		    object));
2239 	}
2240 	KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2241 
2242 	if (object != NULL) {
2243 		mpred = vm_radix_lookup_le(&object->rtree, pindex);
2244 		KASSERT(mpred == NULL || mpred->pindex != pindex,
2245 		    ("vm_page_alloc_contig: pindex already allocated"));
2246 	}
2247 
2248 	/*
2249 	 * Can we allocate the pages without the number of free pages falling
2250 	 * below the lower bound for the allocation class?
2251 	 */
2252 	m_ret = NULL;
2253 again:
2254 #if VM_NRESERVLEVEL > 0
2255 	/*
2256 	 * Can we allocate the pages from a reservation?
2257 	 */
2258 	if (vm_object_reserv(object) &&
2259 	    (m_ret = vm_reserv_alloc_contig(object, pindex, domain, req,
2260 	    mpred, npages, low, high, alignment, boundary)) != NULL) {
2261 		domain = vm_phys_domain(m_ret);
2262 		vmd = VM_DOMAIN(domain);
2263 		goto found;
2264 	}
2265 #endif
2266 	vmd = VM_DOMAIN(domain);
2267 	if (vm_domain_allocate(vmd, req, npages)) {
2268 		/*
2269 		 * allocate them from the free page queues.
2270 		 */
2271 		vm_domain_free_lock(vmd);
2272 		m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2273 		    alignment, boundary);
2274 		vm_domain_free_unlock(vmd);
2275 		if (m_ret == NULL) {
2276 			vm_domain_freecnt_inc(vmd, npages);
2277 #if VM_NRESERVLEVEL > 0
2278 			if (vm_reserv_reclaim_contig(domain, npages, low,
2279 			    high, alignment, boundary))
2280 				goto again;
2281 #endif
2282 		}
2283 	}
2284 	if (m_ret == NULL) {
2285 		if (vm_domain_alloc_fail(vmd, object, req))
2286 			goto again;
2287 		return (NULL);
2288 	}
2289 #if VM_NRESERVLEVEL > 0
2290 found:
2291 #endif
2292 	for (m = m_ret; m < &m_ret[npages]; m++) {
2293 		vm_page_dequeue(m);
2294 		vm_page_alloc_check(m);
2295 	}
2296 
2297 	/*
2298 	 * Initialize the pages.  Only the PG_ZERO flag is inherited.
2299 	 */
2300 	flags = 0;
2301 	if ((req & VM_ALLOC_ZERO) != 0)
2302 		flags = PG_ZERO;
2303 	if ((req & VM_ALLOC_NODUMP) != 0)
2304 		flags |= PG_NODUMP;
2305 	oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2306 	    VPO_UNMANAGED : 0;
2307 	if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2308 		busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2309 	else if ((req & VM_ALLOC_SBUSY) != 0)
2310 		busy_lock = VPB_SHARERS_WORD(1);
2311 	else
2312 		busy_lock = VPB_UNBUSIED;
2313 	if ((req & VM_ALLOC_WIRED) != 0)
2314 		vm_wire_add(npages);
2315 	if (object != NULL) {
2316 		if (object->memattr != VM_MEMATTR_DEFAULT &&
2317 		    memattr == VM_MEMATTR_DEFAULT)
2318 			memattr = object->memattr;
2319 	}
2320 	for (m = m_ret; m < &m_ret[npages]; m++) {
2321 		m->a.flags = 0;
2322 		m->flags = (m->flags | PG_NODUMP) & flags;
2323 		m->busy_lock = busy_lock;
2324 		if ((req & VM_ALLOC_WIRED) != 0)
2325 			m->ref_count = 1;
2326 		m->a.act_count = 0;
2327 		m->oflags = oflags;
2328 		if (object != NULL) {
2329 			if (vm_page_insert_after(m, object, pindex, mpred)) {
2330 				if ((req & VM_ALLOC_WIRED) != 0)
2331 					vm_wire_sub(npages);
2332 				KASSERT(m->object == NULL,
2333 				    ("page %p has object", m));
2334 				mpred = m;
2335 				for (m = m_ret; m < &m_ret[npages]; m++) {
2336 					if (m <= mpred &&
2337 					    (req & VM_ALLOC_WIRED) != 0)
2338 						m->ref_count = 0;
2339 					m->oflags = VPO_UNMANAGED;
2340 					m->busy_lock = VPB_UNBUSIED;
2341 					/* Don't change PG_ZERO. */
2342 					vm_page_free_toq(m);
2343 				}
2344 				if (req & VM_ALLOC_WAITFAIL) {
2345 					VM_OBJECT_WUNLOCK(object);
2346 					vm_radix_wait();
2347 					VM_OBJECT_WLOCK(object);
2348 				}
2349 				return (NULL);
2350 			}
2351 			mpred = m;
2352 		} else
2353 			m->pindex = pindex;
2354 		if (memattr != VM_MEMATTR_DEFAULT)
2355 			pmap_page_set_memattr(m, memattr);
2356 		pindex++;
2357 	}
2358 	return (m_ret);
2359 }
2360 
2361 /*
2362  * Check a page that has been freshly dequeued from a freelist.
2363  */
2364 static void
2365 vm_page_alloc_check(vm_page_t m)
2366 {
2367 
2368 	KASSERT(m->object == NULL, ("page %p has object", m));
2369 	KASSERT(m->a.queue == PQ_NONE &&
2370 	    (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
2371 	    ("page %p has unexpected queue %d, flags %#x",
2372 	    m, m->a.queue, (m->a.flags & PGA_QUEUE_STATE_MASK)));
2373 	KASSERT(m->ref_count == 0, ("page %p has references", m));
2374 	KASSERT(vm_page_busy_freed(m), ("page %p is not freed", m));
2375 	KASSERT(m->dirty == 0, ("page %p is dirty", m));
2376 	KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2377 	    ("page %p has unexpected memattr %d",
2378 	    m, pmap_page_get_memattr(m)));
2379 	KASSERT(m->valid == 0, ("free page %p is valid", m));
2380 }
2381 
2382 /*
2383  * 	vm_page_alloc_freelist:
2384  *
2385  *	Allocate a physical page from the specified free page list.
2386  *
2387  *	The caller must always specify an allocation class.
2388  *
2389  *	allocation classes:
2390  *	VM_ALLOC_NORMAL		normal process request
2391  *	VM_ALLOC_SYSTEM		system *really* needs a page
2392  *	VM_ALLOC_INTERRUPT	interrupt time request
2393  *
2394  *	optional allocation flags:
2395  *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
2396  *				intends to allocate
2397  *	VM_ALLOC_WIRED		wire the allocated page
2398  *	VM_ALLOC_ZERO		prefer a zeroed page
2399  */
2400 vm_page_t
2401 vm_page_alloc_freelist(int freelist, int req)
2402 {
2403 	struct vm_domainset_iter di;
2404 	vm_page_t m;
2405 	int domain;
2406 
2407 	vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2408 	do {
2409 		m = vm_page_alloc_freelist_domain(domain, freelist, req);
2410 		if (m != NULL)
2411 			break;
2412 	} while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2413 
2414 	return (m);
2415 }
2416 
2417 vm_page_t
2418 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2419 {
2420 	struct vm_domain *vmd;
2421 	vm_page_t m;
2422 	u_int flags;
2423 
2424 	m = NULL;
2425 	vmd = VM_DOMAIN(domain);
2426 again:
2427 	if (vm_domain_allocate(vmd, req, 1)) {
2428 		vm_domain_free_lock(vmd);
2429 		m = vm_phys_alloc_freelist_pages(domain, freelist,
2430 		    VM_FREEPOOL_DIRECT, 0);
2431 		vm_domain_free_unlock(vmd);
2432 		if (m == NULL)
2433 			vm_domain_freecnt_inc(vmd, 1);
2434 	}
2435 	if (m == NULL) {
2436 		if (vm_domain_alloc_fail(vmd, NULL, req))
2437 			goto again;
2438 		return (NULL);
2439 	}
2440 	vm_page_dequeue(m);
2441 	vm_page_alloc_check(m);
2442 
2443 	/*
2444 	 * Initialize the page.  Only the PG_ZERO flag is inherited.
2445 	 */
2446 	m->a.flags = 0;
2447 	flags = 0;
2448 	if ((req & VM_ALLOC_ZERO) != 0)
2449 		flags = PG_ZERO;
2450 	m->flags &= flags;
2451 	if ((req & VM_ALLOC_WIRED) != 0) {
2452 		vm_wire_add(1);
2453 		m->ref_count = 1;
2454 	}
2455 	/* Unmanaged pages don't use "act_count". */
2456 	m->oflags = VPO_UNMANAGED;
2457 	return (m);
2458 }
2459 
2460 static int
2461 vm_page_zone_import(void *arg, void **store, int cnt, int domain, int flags)
2462 {
2463 	struct vm_domain *vmd;
2464 	struct vm_pgcache *pgcache;
2465 	int i;
2466 
2467 	pgcache = arg;
2468 	vmd = VM_DOMAIN(pgcache->domain);
2469 
2470 	/*
2471 	 * The page daemon should avoid creating extra memory pressure since its
2472 	 * main purpose is to replenish the store of free pages.
2473 	 */
2474 	if (vmd->vmd_severeset || curproc == pageproc ||
2475 	    !_vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2476 		return (0);
2477 	domain = vmd->vmd_domain;
2478 	vm_domain_free_lock(vmd);
2479 	i = vm_phys_alloc_npages(domain, pgcache->pool, cnt,
2480 	    (vm_page_t *)store);
2481 	vm_domain_free_unlock(vmd);
2482 	if (cnt != i)
2483 		vm_domain_freecnt_inc(vmd, cnt - i);
2484 
2485 	return (i);
2486 }
2487 
2488 static void
2489 vm_page_zone_release(void *arg, void **store, int cnt)
2490 {
2491 	struct vm_domain *vmd;
2492 	struct vm_pgcache *pgcache;
2493 	vm_page_t m;
2494 	int i;
2495 
2496 	pgcache = arg;
2497 	vmd = VM_DOMAIN(pgcache->domain);
2498 	vm_domain_free_lock(vmd);
2499 	for (i = 0; i < cnt; i++) {
2500 		m = (vm_page_t)store[i];
2501 		vm_phys_free_pages(m, 0);
2502 	}
2503 	vm_domain_free_unlock(vmd);
2504 	vm_domain_freecnt_inc(vmd, cnt);
2505 }
2506 
2507 #define	VPSC_ANY	0	/* No restrictions. */
2508 #define	VPSC_NORESERV	1	/* Skip reservations; implies VPSC_NOSUPER. */
2509 #define	VPSC_NOSUPER	2	/* Skip superpages. */
2510 
2511 /*
2512  *	vm_page_scan_contig:
2513  *
2514  *	Scan vm_page_array[] between the specified entries "m_start" and
2515  *	"m_end" for a run of contiguous physical pages that satisfy the
2516  *	specified conditions, and return the lowest page in the run.  The
2517  *	specified "alignment" determines the alignment of the lowest physical
2518  *	page in the run.  If the specified "boundary" is non-zero, then the
2519  *	run of physical pages cannot span a physical address that is a
2520  *	multiple of "boundary".
2521  *
2522  *	"m_end" is never dereferenced, so it need not point to a vm_page
2523  *	structure within vm_page_array[].
2524  *
2525  *	"npages" must be greater than zero.  "m_start" and "m_end" must not
2526  *	span a hole (or discontiguity) in the physical address space.  Both
2527  *	"alignment" and "boundary" must be a power of two.
2528  */
2529 vm_page_t
2530 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2531     u_long alignment, vm_paddr_t boundary, int options)
2532 {
2533 	vm_object_t object;
2534 	vm_paddr_t pa;
2535 	vm_page_t m, m_run;
2536 #if VM_NRESERVLEVEL > 0
2537 	int level;
2538 #endif
2539 	int m_inc, order, run_ext, run_len;
2540 
2541 	KASSERT(npages > 0, ("npages is 0"));
2542 	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2543 	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2544 	m_run = NULL;
2545 	run_len = 0;
2546 	for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2547 		KASSERT((m->flags & PG_MARKER) == 0,
2548 		    ("page %p is PG_MARKER", m));
2549 		KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->ref_count >= 1,
2550 		    ("fictitious page %p has invalid ref count", m));
2551 
2552 		/*
2553 		 * If the current page would be the start of a run, check its
2554 		 * physical address against the end, alignment, and boundary
2555 		 * conditions.  If it doesn't satisfy these conditions, either
2556 		 * terminate the scan or advance to the next page that
2557 		 * satisfies the failed condition.
2558 		 */
2559 		if (run_len == 0) {
2560 			KASSERT(m_run == NULL, ("m_run != NULL"));
2561 			if (m + npages > m_end)
2562 				break;
2563 			pa = VM_PAGE_TO_PHYS(m);
2564 			if ((pa & (alignment - 1)) != 0) {
2565 				m_inc = atop(roundup2(pa, alignment) - pa);
2566 				continue;
2567 			}
2568 			if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2569 			    boundary) != 0) {
2570 				m_inc = atop(roundup2(pa, boundary) - pa);
2571 				continue;
2572 			}
2573 		} else
2574 			KASSERT(m_run != NULL, ("m_run == NULL"));
2575 
2576 retry:
2577 		m_inc = 1;
2578 		if (vm_page_wired(m))
2579 			run_ext = 0;
2580 #if VM_NRESERVLEVEL > 0
2581 		else if ((level = vm_reserv_level(m)) >= 0 &&
2582 		    (options & VPSC_NORESERV) != 0) {
2583 			run_ext = 0;
2584 			/* Advance to the end of the reservation. */
2585 			pa = VM_PAGE_TO_PHYS(m);
2586 			m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2587 			    pa);
2588 		}
2589 #endif
2590 		else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2591 			/*
2592 			 * The page is considered eligible for relocation if
2593 			 * and only if it could be laundered or reclaimed by
2594 			 * the page daemon.
2595 			 */
2596 			VM_OBJECT_RLOCK(object);
2597 			if (object != m->object) {
2598 				VM_OBJECT_RUNLOCK(object);
2599 				goto retry;
2600 			}
2601 			/* Don't care: PG_NODUMP, PG_ZERO. */
2602 			if (object->type != OBJT_DEFAULT &&
2603 			    object->type != OBJT_SWAP &&
2604 			    object->type != OBJT_VNODE) {
2605 				run_ext = 0;
2606 #if VM_NRESERVLEVEL > 0
2607 			} else if ((options & VPSC_NOSUPER) != 0 &&
2608 			    (level = vm_reserv_level_iffullpop(m)) >= 0) {
2609 				run_ext = 0;
2610 				/* Advance to the end of the superpage. */
2611 				pa = VM_PAGE_TO_PHYS(m);
2612 				m_inc = atop(roundup2(pa + 1,
2613 				    vm_reserv_size(level)) - pa);
2614 #endif
2615 			} else if (object->memattr == VM_MEMATTR_DEFAULT &&
2616 			    vm_page_queue(m) != PQ_NONE && !vm_page_busied(m)) {
2617 				/*
2618 				 * The page is allocated but eligible for
2619 				 * relocation.  Extend the current run by one
2620 				 * page.
2621 				 */
2622 				KASSERT(pmap_page_get_memattr(m) ==
2623 				    VM_MEMATTR_DEFAULT,
2624 				    ("page %p has an unexpected memattr", m));
2625 				KASSERT((m->oflags & (VPO_SWAPINPROG |
2626 				    VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2627 				    ("page %p has unexpected oflags", m));
2628 				/* Don't care: PGA_NOSYNC. */
2629 				run_ext = 1;
2630 			} else
2631 				run_ext = 0;
2632 			VM_OBJECT_RUNLOCK(object);
2633 #if VM_NRESERVLEVEL > 0
2634 		} else if (level >= 0) {
2635 			/*
2636 			 * The page is reserved but not yet allocated.  In
2637 			 * other words, it is still free.  Extend the current
2638 			 * run by one page.
2639 			 */
2640 			run_ext = 1;
2641 #endif
2642 		} else if ((order = m->order) < VM_NFREEORDER) {
2643 			/*
2644 			 * The page is enqueued in the physical memory
2645 			 * allocator's free page queues.  Moreover, it is the
2646 			 * first page in a power-of-two-sized run of
2647 			 * contiguous free pages.  Add these pages to the end
2648 			 * of the current run, and jump ahead.
2649 			 */
2650 			run_ext = 1 << order;
2651 			m_inc = 1 << order;
2652 		} else {
2653 			/*
2654 			 * Skip the page for one of the following reasons: (1)
2655 			 * It is enqueued in the physical memory allocator's
2656 			 * free page queues.  However, it is not the first
2657 			 * page in a run of contiguous free pages.  (This case
2658 			 * rarely occurs because the scan is performed in
2659 			 * ascending order.) (2) It is not reserved, and it is
2660 			 * transitioning from free to allocated.  (Conversely,
2661 			 * the transition from allocated to free for managed
2662 			 * pages is blocked by the page lock.) (3) It is
2663 			 * allocated but not contained by an object and not
2664 			 * wired, e.g., allocated by Xen's balloon driver.
2665 			 */
2666 			run_ext = 0;
2667 		}
2668 
2669 		/*
2670 		 * Extend or reset the current run of pages.
2671 		 */
2672 		if (run_ext > 0) {
2673 			if (run_len == 0)
2674 				m_run = m;
2675 			run_len += run_ext;
2676 		} else {
2677 			if (run_len > 0) {
2678 				m_run = NULL;
2679 				run_len = 0;
2680 			}
2681 		}
2682 	}
2683 	if (run_len >= npages)
2684 		return (m_run);
2685 	return (NULL);
2686 }
2687 
2688 /*
2689  *	vm_page_reclaim_run:
2690  *
2691  *	Try to relocate each of the allocated virtual pages within the
2692  *	specified run of physical pages to a new physical address.  Free the
2693  *	physical pages underlying the relocated virtual pages.  A virtual page
2694  *	is relocatable if and only if it could be laundered or reclaimed by
2695  *	the page daemon.  Whenever possible, a virtual page is relocated to a
2696  *	physical address above "high".
2697  *
2698  *	Returns 0 if every physical page within the run was already free or
2699  *	just freed by a successful relocation.  Otherwise, returns a non-zero
2700  *	value indicating why the last attempt to relocate a virtual page was
2701  *	unsuccessful.
2702  *
2703  *	"req_class" must be an allocation class.
2704  */
2705 static int
2706 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2707     vm_paddr_t high)
2708 {
2709 	struct vm_domain *vmd;
2710 	struct spglist free;
2711 	vm_object_t object;
2712 	vm_paddr_t pa;
2713 	vm_page_t m, m_end, m_new;
2714 	int error, order, req;
2715 
2716 	KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2717 	    ("req_class is not an allocation class"));
2718 	SLIST_INIT(&free);
2719 	error = 0;
2720 	m = m_run;
2721 	m_end = m_run + npages;
2722 	for (; error == 0 && m < m_end; m++) {
2723 		KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2724 		    ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2725 
2726 		/*
2727 		 * Racily check for wirings.  Races are handled once the object
2728 		 * lock is held and the page is unmapped.
2729 		 */
2730 		if (vm_page_wired(m))
2731 			error = EBUSY;
2732 		else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2733 			/*
2734 			 * The page is relocated if and only if it could be
2735 			 * laundered or reclaimed by the page daemon.
2736 			 */
2737 			VM_OBJECT_WLOCK(object);
2738 			/* Don't care: PG_NODUMP, PG_ZERO. */
2739 			if (m->object != object ||
2740 			    (object->type != OBJT_DEFAULT &&
2741 			    object->type != OBJT_SWAP &&
2742 			    object->type != OBJT_VNODE))
2743 				error = EINVAL;
2744 			else if (object->memattr != VM_MEMATTR_DEFAULT)
2745 				error = EINVAL;
2746 			else if (vm_page_queue(m) != PQ_NONE &&
2747 			    vm_page_tryxbusy(m) != 0) {
2748 				if (vm_page_wired(m)) {
2749 					vm_page_xunbusy(m);
2750 					error = EBUSY;
2751 					goto unlock;
2752 				}
2753 				KASSERT(pmap_page_get_memattr(m) ==
2754 				    VM_MEMATTR_DEFAULT,
2755 				    ("page %p has an unexpected memattr", m));
2756 				KASSERT(m->oflags == 0,
2757 				    ("page %p has unexpected oflags", m));
2758 				/* Don't care: PGA_NOSYNC. */
2759 				if (!vm_page_none_valid(m)) {
2760 					/*
2761 					 * First, try to allocate a new page
2762 					 * that is above "high".  Failing
2763 					 * that, try to allocate a new page
2764 					 * that is below "m_run".  Allocate
2765 					 * the new page between the end of
2766 					 * "m_run" and "high" only as a last
2767 					 * resort.
2768 					 */
2769 					req = req_class | VM_ALLOC_NOOBJ;
2770 					if ((m->flags & PG_NODUMP) != 0)
2771 						req |= VM_ALLOC_NODUMP;
2772 					if (trunc_page(high) !=
2773 					    ~(vm_paddr_t)PAGE_MASK) {
2774 						m_new = vm_page_alloc_contig(
2775 						    NULL, 0, req, 1,
2776 						    round_page(high),
2777 						    ~(vm_paddr_t)0,
2778 						    PAGE_SIZE, 0,
2779 						    VM_MEMATTR_DEFAULT);
2780 					} else
2781 						m_new = NULL;
2782 					if (m_new == NULL) {
2783 						pa = VM_PAGE_TO_PHYS(m_run);
2784 						m_new = vm_page_alloc_contig(
2785 						    NULL, 0, req, 1,
2786 						    0, pa - 1, PAGE_SIZE, 0,
2787 						    VM_MEMATTR_DEFAULT);
2788 					}
2789 					if (m_new == NULL) {
2790 						pa += ptoa(npages);
2791 						m_new = vm_page_alloc_contig(
2792 						    NULL, 0, req, 1,
2793 						    pa, high, PAGE_SIZE, 0,
2794 						    VM_MEMATTR_DEFAULT);
2795 					}
2796 					if (m_new == NULL) {
2797 						vm_page_xunbusy(m);
2798 						error = ENOMEM;
2799 						goto unlock;
2800 					}
2801 
2802 					/*
2803 					 * Unmap the page and check for new
2804 					 * wirings that may have been acquired
2805 					 * through a pmap lookup.
2806 					 */
2807 					if (object->ref_count != 0 &&
2808 					    !vm_page_try_remove_all(m)) {
2809 						vm_page_xunbusy(m);
2810 						vm_page_free(m_new);
2811 						error = EBUSY;
2812 						goto unlock;
2813 					}
2814 
2815 					/*
2816 					 * Replace "m" with the new page.  For
2817 					 * vm_page_replace(), "m" must be busy
2818 					 * and dequeued.  Finally, change "m"
2819 					 * as if vm_page_free() was called.
2820 					 */
2821 					m_new->a.flags = m->a.flags &
2822 					    ~PGA_QUEUE_STATE_MASK;
2823 					KASSERT(m_new->oflags == VPO_UNMANAGED,
2824 					    ("page %p is managed", m_new));
2825 					m_new->oflags = 0;
2826 					pmap_copy_page(m, m_new);
2827 					m_new->valid = m->valid;
2828 					m_new->dirty = m->dirty;
2829 					m->flags &= ~PG_ZERO;
2830 					vm_page_dequeue(m);
2831 					if (vm_page_replace_hold(m_new, object,
2832 					    m->pindex, m) &&
2833 					    vm_page_free_prep(m))
2834 						SLIST_INSERT_HEAD(&free, m,
2835 						    plinks.s.ss);
2836 
2837 					/*
2838 					 * The new page must be deactivated
2839 					 * before the object is unlocked.
2840 					 */
2841 					vm_page_deactivate(m_new);
2842 				} else {
2843 					m->flags &= ~PG_ZERO;
2844 					vm_page_dequeue(m);
2845 					if (vm_page_free_prep(m))
2846 						SLIST_INSERT_HEAD(&free, m,
2847 						    plinks.s.ss);
2848 					KASSERT(m->dirty == 0,
2849 					    ("page %p is dirty", m));
2850 				}
2851 			} else
2852 				error = EBUSY;
2853 unlock:
2854 			VM_OBJECT_WUNLOCK(object);
2855 		} else {
2856 			MPASS(vm_phys_domain(m) == domain);
2857 			vmd = VM_DOMAIN(domain);
2858 			vm_domain_free_lock(vmd);
2859 			order = m->order;
2860 			if (order < VM_NFREEORDER) {
2861 				/*
2862 				 * The page is enqueued in the physical memory
2863 				 * allocator's free page queues.  Moreover, it
2864 				 * is the first page in a power-of-two-sized
2865 				 * run of contiguous free pages.  Jump ahead
2866 				 * to the last page within that run, and
2867 				 * continue from there.
2868 				 */
2869 				m += (1 << order) - 1;
2870 			}
2871 #if VM_NRESERVLEVEL > 0
2872 			else if (vm_reserv_is_page_free(m))
2873 				order = 0;
2874 #endif
2875 			vm_domain_free_unlock(vmd);
2876 			if (order == VM_NFREEORDER)
2877 				error = EINVAL;
2878 		}
2879 	}
2880 	if ((m = SLIST_FIRST(&free)) != NULL) {
2881 		int cnt;
2882 
2883 		vmd = VM_DOMAIN(domain);
2884 		cnt = 0;
2885 		vm_domain_free_lock(vmd);
2886 		do {
2887 			MPASS(vm_phys_domain(m) == domain);
2888 			SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2889 			vm_phys_free_pages(m, 0);
2890 			cnt++;
2891 		} while ((m = SLIST_FIRST(&free)) != NULL);
2892 		vm_domain_free_unlock(vmd);
2893 		vm_domain_freecnt_inc(vmd, cnt);
2894 	}
2895 	return (error);
2896 }
2897 
2898 #define	NRUNS	16
2899 
2900 CTASSERT(powerof2(NRUNS));
2901 
2902 #define	RUN_INDEX(count)	((count) & (NRUNS - 1))
2903 
2904 #define	MIN_RECLAIM	8
2905 
2906 /*
2907  *	vm_page_reclaim_contig:
2908  *
2909  *	Reclaim allocated, contiguous physical memory satisfying the specified
2910  *	conditions by relocating the virtual pages using that physical memory.
2911  *	Returns true if reclamation is successful and false otherwise.  Since
2912  *	relocation requires the allocation of physical pages, reclamation may
2913  *	fail due to a shortage of free pages.  When reclamation fails, callers
2914  *	are expected to perform vm_wait() before retrying a failed allocation
2915  *	operation, e.g., vm_page_alloc_contig().
2916  *
2917  *	The caller must always specify an allocation class through "req".
2918  *
2919  *	allocation classes:
2920  *	VM_ALLOC_NORMAL		normal process request
2921  *	VM_ALLOC_SYSTEM		system *really* needs a page
2922  *	VM_ALLOC_INTERRUPT	interrupt time request
2923  *
2924  *	The optional allocation flags are ignored.
2925  *
2926  *	"npages" must be greater than zero.  Both "alignment" and "boundary"
2927  *	must be a power of two.
2928  */
2929 bool
2930 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
2931     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2932 {
2933 	struct vm_domain *vmd;
2934 	vm_paddr_t curr_low;
2935 	vm_page_t m_run, m_runs[NRUNS];
2936 	u_long count, reclaimed;
2937 	int error, i, options, req_class;
2938 
2939 	KASSERT(npages > 0, ("npages is 0"));
2940 	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2941 	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2942 	req_class = req & VM_ALLOC_CLASS_MASK;
2943 
2944 	/*
2945 	 * The page daemon is allowed to dig deeper into the free page list.
2946 	 */
2947 	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2948 		req_class = VM_ALLOC_SYSTEM;
2949 
2950 	/*
2951 	 * Return if the number of free pages cannot satisfy the requested
2952 	 * allocation.
2953 	 */
2954 	vmd = VM_DOMAIN(domain);
2955 	count = vmd->vmd_free_count;
2956 	if (count < npages + vmd->vmd_free_reserved || (count < npages +
2957 	    vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2958 	    (count < npages && req_class == VM_ALLOC_INTERRUPT))
2959 		return (false);
2960 
2961 	/*
2962 	 * Scan up to three times, relaxing the restrictions ("options") on
2963 	 * the reclamation of reservations and superpages each time.
2964 	 */
2965 	for (options = VPSC_NORESERV;;) {
2966 		/*
2967 		 * Find the highest runs that satisfy the given constraints
2968 		 * and restrictions, and record them in "m_runs".
2969 		 */
2970 		curr_low = low;
2971 		count = 0;
2972 		for (;;) {
2973 			m_run = vm_phys_scan_contig(domain, npages, curr_low,
2974 			    high, alignment, boundary, options);
2975 			if (m_run == NULL)
2976 				break;
2977 			curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2978 			m_runs[RUN_INDEX(count)] = m_run;
2979 			count++;
2980 		}
2981 
2982 		/*
2983 		 * Reclaim the highest runs in LIFO (descending) order until
2984 		 * the number of reclaimed pages, "reclaimed", is at least
2985 		 * MIN_RECLAIM.  Reset "reclaimed" each time because each
2986 		 * reclamation is idempotent, and runs will (likely) recur
2987 		 * from one scan to the next as restrictions are relaxed.
2988 		 */
2989 		reclaimed = 0;
2990 		for (i = 0; count > 0 && i < NRUNS; i++) {
2991 			count--;
2992 			m_run = m_runs[RUN_INDEX(count)];
2993 			error = vm_page_reclaim_run(req_class, domain, npages,
2994 			    m_run, high);
2995 			if (error == 0) {
2996 				reclaimed += npages;
2997 				if (reclaimed >= MIN_RECLAIM)
2998 					return (true);
2999 			}
3000 		}
3001 
3002 		/*
3003 		 * Either relax the restrictions on the next scan or return if
3004 		 * the last scan had no restrictions.
3005 		 */
3006 		if (options == VPSC_NORESERV)
3007 			options = VPSC_NOSUPER;
3008 		else if (options == VPSC_NOSUPER)
3009 			options = VPSC_ANY;
3010 		else if (options == VPSC_ANY)
3011 			return (reclaimed != 0);
3012 	}
3013 }
3014 
3015 bool
3016 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
3017     u_long alignment, vm_paddr_t boundary)
3018 {
3019 	struct vm_domainset_iter di;
3020 	int domain;
3021 	bool ret;
3022 
3023 	vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
3024 	do {
3025 		ret = vm_page_reclaim_contig_domain(domain, req, npages, low,
3026 		    high, alignment, boundary);
3027 		if (ret)
3028 			break;
3029 	} while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
3030 
3031 	return (ret);
3032 }
3033 
3034 /*
3035  * Set the domain in the appropriate page level domainset.
3036  */
3037 void
3038 vm_domain_set(struct vm_domain *vmd)
3039 {
3040 
3041 	mtx_lock(&vm_domainset_lock);
3042 	if (!vmd->vmd_minset && vm_paging_min(vmd)) {
3043 		vmd->vmd_minset = 1;
3044 		DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
3045 	}
3046 	if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
3047 		vmd->vmd_severeset = 1;
3048 		DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
3049 	}
3050 	mtx_unlock(&vm_domainset_lock);
3051 }
3052 
3053 /*
3054  * Clear the domain from the appropriate page level domainset.
3055  */
3056 void
3057 vm_domain_clear(struct vm_domain *vmd)
3058 {
3059 
3060 	mtx_lock(&vm_domainset_lock);
3061 	if (vmd->vmd_minset && !vm_paging_min(vmd)) {
3062 		vmd->vmd_minset = 0;
3063 		DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
3064 		if (vm_min_waiters != 0) {
3065 			vm_min_waiters = 0;
3066 			wakeup(&vm_min_domains);
3067 		}
3068 	}
3069 	if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
3070 		vmd->vmd_severeset = 0;
3071 		DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
3072 		if (vm_severe_waiters != 0) {
3073 			vm_severe_waiters = 0;
3074 			wakeup(&vm_severe_domains);
3075 		}
3076 	}
3077 
3078 	/*
3079 	 * If pageout daemon needs pages, then tell it that there are
3080 	 * some free.
3081 	 */
3082 	if (vmd->vmd_pageout_pages_needed &&
3083 	    vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
3084 		wakeup(&vmd->vmd_pageout_pages_needed);
3085 		vmd->vmd_pageout_pages_needed = 0;
3086 	}
3087 
3088 	/* See comments in vm_wait_doms(). */
3089 	if (vm_pageproc_waiters) {
3090 		vm_pageproc_waiters = 0;
3091 		wakeup(&vm_pageproc_waiters);
3092 	}
3093 	mtx_unlock(&vm_domainset_lock);
3094 }
3095 
3096 /*
3097  * Wait for free pages to exceed the min threshold globally.
3098  */
3099 void
3100 vm_wait_min(void)
3101 {
3102 
3103 	mtx_lock(&vm_domainset_lock);
3104 	while (vm_page_count_min()) {
3105 		vm_min_waiters++;
3106 		msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
3107 	}
3108 	mtx_unlock(&vm_domainset_lock);
3109 }
3110 
3111 /*
3112  * Wait for free pages to exceed the severe threshold globally.
3113  */
3114 void
3115 vm_wait_severe(void)
3116 {
3117 
3118 	mtx_lock(&vm_domainset_lock);
3119 	while (vm_page_count_severe()) {
3120 		vm_severe_waiters++;
3121 		msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
3122 		    "vmwait", 0);
3123 	}
3124 	mtx_unlock(&vm_domainset_lock);
3125 }
3126 
3127 u_int
3128 vm_wait_count(void)
3129 {
3130 
3131 	return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
3132 }
3133 
3134 void
3135 vm_wait_doms(const domainset_t *wdoms)
3136 {
3137 
3138 	/*
3139 	 * We use racey wakeup synchronization to avoid expensive global
3140 	 * locking for the pageproc when sleeping with a non-specific vm_wait.
3141 	 * To handle this, we only sleep for one tick in this instance.  It
3142 	 * is expected that most allocations for the pageproc will come from
3143 	 * kmem or vm_page_grab* which will use the more specific and
3144 	 * race-free vm_wait_domain().
3145 	 */
3146 	if (curproc == pageproc) {
3147 		mtx_lock(&vm_domainset_lock);
3148 		vm_pageproc_waiters++;
3149 		msleep(&vm_pageproc_waiters, &vm_domainset_lock, PVM | PDROP,
3150 		    "pageprocwait", 1);
3151 	} else {
3152 		/*
3153 		 * XXX Ideally we would wait only until the allocation could
3154 		 * be satisfied.  This condition can cause new allocators to
3155 		 * consume all freed pages while old allocators wait.
3156 		 */
3157 		mtx_lock(&vm_domainset_lock);
3158 		if (vm_page_count_min_set(wdoms)) {
3159 			vm_min_waiters++;
3160 			msleep(&vm_min_domains, &vm_domainset_lock,
3161 			    PVM | PDROP, "vmwait", 0);
3162 		} else
3163 			mtx_unlock(&vm_domainset_lock);
3164 	}
3165 }
3166 
3167 /*
3168  *	vm_wait_domain:
3169  *
3170  *	Sleep until free pages are available for allocation.
3171  *	- Called in various places after failed memory allocations.
3172  */
3173 void
3174 vm_wait_domain(int domain)
3175 {
3176 	struct vm_domain *vmd;
3177 	domainset_t wdom;
3178 
3179 	vmd = VM_DOMAIN(domain);
3180 	vm_domain_free_assert_unlocked(vmd);
3181 
3182 	if (curproc == pageproc) {
3183 		mtx_lock(&vm_domainset_lock);
3184 		if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
3185 			vmd->vmd_pageout_pages_needed = 1;
3186 			msleep(&vmd->vmd_pageout_pages_needed,
3187 			    &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
3188 		} else
3189 			mtx_unlock(&vm_domainset_lock);
3190 	} else {
3191 		if (pageproc == NULL)
3192 			panic("vm_wait in early boot");
3193 		DOMAINSET_ZERO(&wdom);
3194 		DOMAINSET_SET(vmd->vmd_domain, &wdom);
3195 		vm_wait_doms(&wdom);
3196 	}
3197 }
3198 
3199 /*
3200  *	vm_wait:
3201  *
3202  *	Sleep until free pages are available for allocation in the
3203  *	affinity domains of the obj.  If obj is NULL, the domain set
3204  *	for the calling thread is used.
3205  *	Called in various places after failed memory allocations.
3206  */
3207 void
3208 vm_wait(vm_object_t obj)
3209 {
3210 	struct domainset *d;
3211 
3212 	d = NULL;
3213 
3214 	/*
3215 	 * Carefully fetch pointers only once: the struct domainset
3216 	 * itself is ummutable but the pointer might change.
3217 	 */
3218 	if (obj != NULL)
3219 		d = obj->domain.dr_policy;
3220 	if (d == NULL)
3221 		d = curthread->td_domain.dr_policy;
3222 
3223 	vm_wait_doms(&d->ds_mask);
3224 }
3225 
3226 /*
3227  *	vm_domain_alloc_fail:
3228  *
3229  *	Called when a page allocation function fails.  Informs the
3230  *	pagedaemon and performs the requested wait.  Requires the
3231  *	domain_free and object lock on entry.  Returns with the
3232  *	object lock held and free lock released.  Returns an error when
3233  *	retry is necessary.
3234  *
3235  */
3236 static int
3237 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3238 {
3239 
3240 	vm_domain_free_assert_unlocked(vmd);
3241 
3242 	atomic_add_int(&vmd->vmd_pageout_deficit,
3243 	    max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3244 	if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3245 		if (object != NULL)
3246 			VM_OBJECT_WUNLOCK(object);
3247 		vm_wait_domain(vmd->vmd_domain);
3248 		if (object != NULL)
3249 			VM_OBJECT_WLOCK(object);
3250 		if (req & VM_ALLOC_WAITOK)
3251 			return (EAGAIN);
3252 	}
3253 
3254 	return (0);
3255 }
3256 
3257 /*
3258  *	vm_waitpfault:
3259  *
3260  *	Sleep until free pages are available for allocation.
3261  *	- Called only in vm_fault so that processes page faulting
3262  *	  can be easily tracked.
3263  *	- Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3264  *	  processes will be able to grab memory first.  Do not change
3265  *	  this balance without careful testing first.
3266  */
3267 void
3268 vm_waitpfault(struct domainset *dset, int timo)
3269 {
3270 
3271 	/*
3272 	 * XXX Ideally we would wait only until the allocation could
3273 	 * be satisfied.  This condition can cause new allocators to
3274 	 * consume all freed pages while old allocators wait.
3275 	 */
3276 	mtx_lock(&vm_domainset_lock);
3277 	if (vm_page_count_min_set(&dset->ds_mask)) {
3278 		vm_min_waiters++;
3279 		msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3280 		    "pfault", timo);
3281 	} else
3282 		mtx_unlock(&vm_domainset_lock);
3283 }
3284 
3285 static struct vm_pagequeue *
3286 _vm_page_pagequeue(vm_page_t m, uint8_t queue)
3287 {
3288 
3289 	return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue]);
3290 }
3291 
3292 #ifdef INVARIANTS
3293 static struct vm_pagequeue *
3294 vm_page_pagequeue(vm_page_t m)
3295 {
3296 
3297 	return (_vm_page_pagequeue(m, vm_page_astate_load(m).queue));
3298 }
3299 #endif
3300 
3301 static __always_inline bool
3302 vm_page_pqstate_fcmpset(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3303 {
3304 	vm_page_astate_t tmp;
3305 
3306 	tmp = *old;
3307 	do {
3308 		if (__predict_true(vm_page_astate_fcmpset(m, old, new)))
3309 			return (true);
3310 		counter_u64_add(pqstate_commit_retries, 1);
3311 	} while (old->_bits == tmp._bits);
3312 
3313 	return (false);
3314 }
3315 
3316 /*
3317  * Do the work of committing a queue state update that moves the page out of
3318  * its current queue.
3319  */
3320 static bool
3321 _vm_page_pqstate_commit_dequeue(struct vm_pagequeue *pq, vm_page_t m,
3322     vm_page_astate_t *old, vm_page_astate_t new)
3323 {
3324 	vm_page_t next;
3325 
3326 	vm_pagequeue_assert_locked(pq);
3327 	KASSERT(vm_page_pagequeue(m) == pq,
3328 	    ("%s: queue %p does not match page %p", __func__, pq, m));
3329 	KASSERT(old->queue != PQ_NONE && new.queue != old->queue,
3330 	    ("%s: invalid queue indices %d %d",
3331 	    __func__, old->queue, new.queue));
3332 
3333 	/*
3334 	 * Once the queue index of the page changes there is nothing
3335 	 * synchronizing with further updates to the page's physical
3336 	 * queue state.  Therefore we must speculatively remove the page
3337 	 * from the queue now and be prepared to roll back if the queue
3338 	 * state update fails.  If the page is not physically enqueued then
3339 	 * we just update its queue index.
3340 	 */
3341 	if ((old->flags & PGA_ENQUEUED) != 0) {
3342 		new.flags &= ~PGA_ENQUEUED;
3343 		next = TAILQ_NEXT(m, plinks.q);
3344 		TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3345 		vm_pagequeue_cnt_dec(pq);
3346 		if (!vm_page_pqstate_fcmpset(m, old, new)) {
3347 			if (next == NULL)
3348 				TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3349 			else
3350 				TAILQ_INSERT_BEFORE(next, m, plinks.q);
3351 			vm_pagequeue_cnt_inc(pq);
3352 			return (false);
3353 		} else {
3354 			return (true);
3355 		}
3356 	} else {
3357 		return (vm_page_pqstate_fcmpset(m, old, new));
3358 	}
3359 }
3360 
3361 static bool
3362 vm_page_pqstate_commit_dequeue(vm_page_t m, vm_page_astate_t *old,
3363     vm_page_astate_t new)
3364 {
3365 	struct vm_pagequeue *pq;
3366 	vm_page_astate_t as;
3367 	bool ret;
3368 
3369 	pq = _vm_page_pagequeue(m, old->queue);
3370 
3371 	/*
3372 	 * The queue field and PGA_ENQUEUED flag are stable only so long as the
3373 	 * corresponding page queue lock is held.
3374 	 */
3375 	vm_pagequeue_lock(pq);
3376 	as = vm_page_astate_load(m);
3377 	if (__predict_false(as._bits != old->_bits)) {
3378 		*old = as;
3379 		ret = false;
3380 	} else {
3381 		ret = _vm_page_pqstate_commit_dequeue(pq, m, old, new);
3382 	}
3383 	vm_pagequeue_unlock(pq);
3384 	return (ret);
3385 }
3386 
3387 /*
3388  * Commit a queue state update that enqueues or requeues a page.
3389  */
3390 static bool
3391 _vm_page_pqstate_commit_requeue(struct vm_pagequeue *pq, vm_page_t m,
3392     vm_page_astate_t *old, vm_page_astate_t new)
3393 {
3394 	struct vm_domain *vmd;
3395 
3396 	vm_pagequeue_assert_locked(pq);
3397 	KASSERT(old->queue != PQ_NONE && new.queue == old->queue,
3398 	    ("%s: invalid queue indices %d %d",
3399 	    __func__, old->queue, new.queue));
3400 
3401 	new.flags |= PGA_ENQUEUED;
3402 	if (!vm_page_pqstate_fcmpset(m, old, new))
3403 		return (false);
3404 
3405 	if ((old->flags & PGA_ENQUEUED) != 0)
3406 		TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3407 	else
3408 		vm_pagequeue_cnt_inc(pq);
3409 
3410 	/*
3411 	 * Give PGA_REQUEUE_HEAD precedence over PGA_REQUEUE.  In particular, if
3412 	 * both flags are set in close succession, only PGA_REQUEUE_HEAD will be
3413 	 * applied, even if it was set first.
3414 	 */
3415 	if ((old->flags & PGA_REQUEUE_HEAD) != 0) {
3416 		vmd = vm_pagequeue_domain(m);
3417 		KASSERT(pq == &vmd->vmd_pagequeues[PQ_INACTIVE],
3418 		    ("%s: invalid page queue for page %p", __func__, m));
3419 		TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3420 	} else {
3421 		TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3422 	}
3423 	return (true);
3424 }
3425 
3426 /*
3427  * Commit a queue state update that encodes a request for a deferred queue
3428  * operation.
3429  */
3430 static bool
3431 vm_page_pqstate_commit_request(vm_page_t m, vm_page_astate_t *old,
3432     vm_page_astate_t new)
3433 {
3434 
3435 	KASSERT(old->queue == new.queue || new.queue != PQ_NONE,
3436 	    ("%s: invalid state, queue %d flags %x",
3437 	    __func__, new.queue, new.flags));
3438 
3439 	if (old->_bits != new._bits &&
3440 	    !vm_page_pqstate_fcmpset(m, old, new))
3441 		return (false);
3442 	vm_page_pqbatch_submit(m, new.queue);
3443 	return (true);
3444 }
3445 
3446 /*
3447  * A generic queue state update function.  This handles more cases than the
3448  * specialized functions above.
3449  */
3450 bool
3451 vm_page_pqstate_commit(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3452 {
3453 
3454 	if (old->_bits == new._bits)
3455 		return (true);
3456 
3457 	if (old->queue != PQ_NONE && new.queue != old->queue) {
3458 		if (!vm_page_pqstate_commit_dequeue(m, old, new))
3459 			return (false);
3460 		if (new.queue != PQ_NONE)
3461 			vm_page_pqbatch_submit(m, new.queue);
3462 	} else {
3463 		if (!vm_page_pqstate_fcmpset(m, old, new))
3464 			return (false);
3465 		if (new.queue != PQ_NONE &&
3466 		    ((new.flags & ~old->flags) & PGA_QUEUE_OP_MASK) != 0)
3467 			vm_page_pqbatch_submit(m, new.queue);
3468 	}
3469 	return (true);
3470 }
3471 
3472 /*
3473  * Apply deferred queue state updates to a page.
3474  */
3475 static inline void
3476 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m, uint8_t queue)
3477 {
3478 	vm_page_astate_t new, old;
3479 
3480 	CRITICAL_ASSERT(curthread);
3481 	vm_pagequeue_assert_locked(pq);
3482 	KASSERT(queue < PQ_COUNT,
3483 	    ("%s: invalid queue index %d", __func__, queue));
3484 	KASSERT(pq == _vm_page_pagequeue(m, queue),
3485 	    ("%s: page %p does not belong to queue %p", __func__, m, pq));
3486 
3487 	for (old = vm_page_astate_load(m);;) {
3488 		if (__predict_false(old.queue != queue ||
3489 		    (old.flags & PGA_QUEUE_OP_MASK) == 0)) {
3490 			counter_u64_add(queue_nops, 1);
3491 			break;
3492 		}
3493 		KASSERT(old.queue != PQ_NONE || (old.flags & PGA_QUEUE_STATE_MASK) == 0,
3494 		    ("%s: page %p has unexpected queue state", __func__, m));
3495 
3496 		new = old;
3497 		if ((old.flags & PGA_DEQUEUE) != 0) {
3498 			new.flags &= ~PGA_QUEUE_OP_MASK;
3499 			new.queue = PQ_NONE;
3500 			if (__predict_true(_vm_page_pqstate_commit_dequeue(pq,
3501 			    m, &old, new))) {
3502 				counter_u64_add(queue_ops, 1);
3503 				break;
3504 			}
3505 		} else {
3506 			new.flags &= ~(PGA_REQUEUE | PGA_REQUEUE_HEAD);
3507 			if (__predict_true(_vm_page_pqstate_commit_requeue(pq,
3508 			    m, &old, new))) {
3509 				counter_u64_add(queue_ops, 1);
3510 				break;
3511 			}
3512 		}
3513 	}
3514 }
3515 
3516 static void
3517 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3518     uint8_t queue)
3519 {
3520 	int i;
3521 
3522 	for (i = 0; i < bq->bq_cnt; i++)
3523 		vm_pqbatch_process_page(pq, bq->bq_pa[i], queue);
3524 	vm_batchqueue_init(bq);
3525 }
3526 
3527 /*
3528  *	vm_page_pqbatch_submit:		[ internal use only ]
3529  *
3530  *	Enqueue a page in the specified page queue's batched work queue.
3531  *	The caller must have encoded the requested operation in the page
3532  *	structure's a.flags field.
3533  */
3534 void
3535 vm_page_pqbatch_submit(vm_page_t m, uint8_t queue)
3536 {
3537 	struct vm_batchqueue *bq;
3538 	struct vm_pagequeue *pq;
3539 	int domain;
3540 
3541 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3542 	    ("page %p is unmanaged", m));
3543 	KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3544 
3545 	domain = vm_phys_domain(m);
3546 	pq = &vm_pagequeue_domain(m)->vmd_pagequeues[queue];
3547 
3548 	critical_enter();
3549 	bq = DPCPU_PTR(pqbatch[domain][queue]);
3550 	if (vm_batchqueue_insert(bq, m)) {
3551 		critical_exit();
3552 		return;
3553 	}
3554 	critical_exit();
3555 	vm_pagequeue_lock(pq);
3556 	critical_enter();
3557 	bq = DPCPU_PTR(pqbatch[domain][queue]);
3558 	vm_pqbatch_process(pq, bq, queue);
3559 	vm_pqbatch_process_page(pq, m, queue);
3560 	vm_pagequeue_unlock(pq);
3561 	critical_exit();
3562 }
3563 
3564 /*
3565  *	vm_page_pqbatch_drain:		[ internal use only ]
3566  *
3567  *	Force all per-CPU page queue batch queues to be drained.  This is
3568  *	intended for use in severe memory shortages, to ensure that pages
3569  *	do not remain stuck in the batch queues.
3570  */
3571 void
3572 vm_page_pqbatch_drain(void)
3573 {
3574 	struct thread *td;
3575 	struct vm_domain *vmd;
3576 	struct vm_pagequeue *pq;
3577 	int cpu, domain, queue;
3578 
3579 	td = curthread;
3580 	CPU_FOREACH(cpu) {
3581 		thread_lock(td);
3582 		sched_bind(td, cpu);
3583 		thread_unlock(td);
3584 
3585 		for (domain = 0; domain < vm_ndomains; domain++) {
3586 			vmd = VM_DOMAIN(domain);
3587 			for (queue = 0; queue < PQ_COUNT; queue++) {
3588 				pq = &vmd->vmd_pagequeues[queue];
3589 				vm_pagequeue_lock(pq);
3590 				critical_enter();
3591 				vm_pqbatch_process(pq,
3592 				    DPCPU_PTR(pqbatch[domain][queue]), queue);
3593 				critical_exit();
3594 				vm_pagequeue_unlock(pq);
3595 			}
3596 		}
3597 	}
3598 	thread_lock(td);
3599 	sched_unbind(td);
3600 	thread_unlock(td);
3601 }
3602 
3603 /*
3604  *	vm_page_dequeue_deferred:	[ internal use only ]
3605  *
3606  *	Request removal of the given page from its current page
3607  *	queue.  Physical removal from the queue may be deferred
3608  *	indefinitely.
3609  *
3610  *	The page must be locked.
3611  */
3612 void
3613 vm_page_dequeue_deferred(vm_page_t m)
3614 {
3615 	vm_page_astate_t new, old;
3616 
3617 	old = vm_page_astate_load(m);
3618 	do {
3619 		if (old.queue == PQ_NONE) {
3620 			KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3621 			    ("%s: page %p has unexpected queue state",
3622 			    __func__, m));
3623 			break;
3624 		}
3625 		new = old;
3626 		new.flags |= PGA_DEQUEUE;
3627 	} while (!vm_page_pqstate_commit_request(m, &old, new));
3628 }
3629 
3630 /*
3631  *	vm_page_dequeue:
3632  *
3633  *	Remove the page from whichever page queue it's in, if any, before
3634  *	returning.
3635  */
3636 void
3637 vm_page_dequeue(vm_page_t m)
3638 {
3639 	vm_page_astate_t new, old;
3640 
3641 	old = vm_page_astate_load(m);
3642 	do {
3643 		if (old.queue == PQ_NONE) {
3644 			KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3645 			    ("%s: page %p has unexpected queue state",
3646 			    __func__, m));
3647 			break;
3648 		}
3649 		new = old;
3650 		new.flags &= ~PGA_QUEUE_OP_MASK;
3651 		new.queue = PQ_NONE;
3652 	} while (!vm_page_pqstate_commit_dequeue(m, &old, new));
3653 
3654 }
3655 
3656 /*
3657  * Schedule the given page for insertion into the specified page queue.
3658  * Physical insertion of the page may be deferred indefinitely.
3659  */
3660 static void
3661 vm_page_enqueue(vm_page_t m, uint8_t queue)
3662 {
3663 
3664 	KASSERT(m->a.queue == PQ_NONE &&
3665 	    (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
3666 	    ("%s: page %p is already enqueued", __func__, m));
3667 	KASSERT(m->ref_count > 0,
3668 	    ("%s: page %p does not carry any references", __func__, m));
3669 
3670 	m->a.queue = queue;
3671 	if ((m->a.flags & PGA_REQUEUE) == 0)
3672 		vm_page_aflag_set(m, PGA_REQUEUE);
3673 	vm_page_pqbatch_submit(m, queue);
3674 }
3675 
3676 /*
3677  *	vm_page_free_prep:
3678  *
3679  *	Prepares the given page to be put on the free list,
3680  *	disassociating it from any VM object. The caller may return
3681  *	the page to the free list only if this function returns true.
3682  *
3683  *	The object must be locked.  The page must be locked if it is
3684  *	managed.
3685  */
3686 static bool
3687 vm_page_free_prep(vm_page_t m)
3688 {
3689 
3690 	/*
3691 	 * Synchronize with threads that have dropped a reference to this
3692 	 * page.
3693 	 */
3694 	atomic_thread_fence_acq();
3695 
3696 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
3697 	if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
3698 		uint64_t *p;
3699 		int i;
3700 		p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3701 		for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
3702 			KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
3703 			    m, i, (uintmax_t)*p));
3704 	}
3705 #endif
3706 	if ((m->oflags & VPO_UNMANAGED) == 0) {
3707 		KASSERT(!pmap_page_is_mapped(m),
3708 		    ("vm_page_free_prep: freeing mapped page %p", m));
3709 		KASSERT((m->a.flags & (PGA_EXECUTABLE | PGA_WRITEABLE)) == 0,
3710 		    ("vm_page_free_prep: mapping flags set in page %p", m));
3711 	} else {
3712 		KASSERT(m->a.queue == PQ_NONE,
3713 		    ("vm_page_free_prep: unmanaged page %p is queued", m));
3714 	}
3715 	VM_CNT_INC(v_tfree);
3716 
3717 	if (m->object != NULL) {
3718 		KASSERT(((m->oflags & VPO_UNMANAGED) != 0) ==
3719 		    ((m->object->flags & OBJ_UNMANAGED) != 0),
3720 		    ("vm_page_free_prep: managed flag mismatch for page %p",
3721 		    m));
3722 		vm_page_assert_xbusied(m);
3723 
3724 		/*
3725 		 * The object reference can be released without an atomic
3726 		 * operation.
3727 		 */
3728 		KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
3729 		    m->ref_count == VPRC_OBJREF,
3730 		    ("vm_page_free_prep: page %p has unexpected ref_count %u",
3731 		    m, m->ref_count));
3732 		vm_page_object_remove(m);
3733 		m->ref_count -= VPRC_OBJREF;
3734 	} else
3735 		vm_page_assert_unbusied(m);
3736 
3737 	vm_page_busy_free(m);
3738 
3739 	/*
3740 	 * If fictitious remove object association and
3741 	 * return.
3742 	 */
3743 	if ((m->flags & PG_FICTITIOUS) != 0) {
3744 		KASSERT(m->ref_count == 1,
3745 		    ("fictitious page %p is referenced", m));
3746 		KASSERT(m->a.queue == PQ_NONE,
3747 		    ("fictitious page %p is queued", m));
3748 		return (false);
3749 	}
3750 
3751 	/*
3752 	 * Pages need not be dequeued before they are returned to the physical
3753 	 * memory allocator, but they must at least be marked for a deferred
3754 	 * dequeue.
3755 	 */
3756 	if ((m->oflags & VPO_UNMANAGED) == 0)
3757 		vm_page_dequeue_deferred(m);
3758 
3759 	m->valid = 0;
3760 	vm_page_undirty(m);
3761 
3762 	if (m->ref_count != 0)
3763 		panic("vm_page_free_prep: page %p has references", m);
3764 
3765 	/*
3766 	 * Restore the default memory attribute to the page.
3767 	 */
3768 	if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3769 		pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3770 
3771 #if VM_NRESERVLEVEL > 0
3772 	/*
3773 	 * Determine whether the page belongs to a reservation.  If the page was
3774 	 * allocated from a per-CPU cache, it cannot belong to a reservation, so
3775 	 * as an optimization, we avoid the check in that case.
3776 	 */
3777 	if ((m->flags & PG_PCPU_CACHE) == 0 && vm_reserv_free_page(m))
3778 		return (false);
3779 #endif
3780 
3781 	return (true);
3782 }
3783 
3784 /*
3785  *	vm_page_free_toq:
3786  *
3787  *	Returns the given page to the free list, disassociating it
3788  *	from any VM object.
3789  *
3790  *	The object must be locked.  The page must be locked if it is
3791  *	managed.
3792  */
3793 static void
3794 vm_page_free_toq(vm_page_t m)
3795 {
3796 	struct vm_domain *vmd;
3797 	uma_zone_t zone;
3798 
3799 	if (!vm_page_free_prep(m))
3800 		return;
3801 
3802 	vmd = vm_pagequeue_domain(m);
3803 	zone = vmd->vmd_pgcache[m->pool].zone;
3804 	if ((m->flags & PG_PCPU_CACHE) != 0 && zone != NULL) {
3805 		uma_zfree(zone, m);
3806 		return;
3807 	}
3808 	vm_domain_free_lock(vmd);
3809 	vm_phys_free_pages(m, 0);
3810 	vm_domain_free_unlock(vmd);
3811 	vm_domain_freecnt_inc(vmd, 1);
3812 }
3813 
3814 /*
3815  *	vm_page_free_pages_toq:
3816  *
3817  *	Returns a list of pages to the free list, disassociating it
3818  *	from any VM object.  In other words, this is equivalent to
3819  *	calling vm_page_free_toq() for each page of a list of VM objects.
3820  *
3821  *	The objects must be locked.  The pages must be locked if it is
3822  *	managed.
3823  */
3824 void
3825 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
3826 {
3827 	vm_page_t m;
3828 	int count;
3829 
3830 	if (SLIST_EMPTY(free))
3831 		return;
3832 
3833 	count = 0;
3834 	while ((m = SLIST_FIRST(free)) != NULL) {
3835 		count++;
3836 		SLIST_REMOVE_HEAD(free, plinks.s.ss);
3837 		vm_page_free_toq(m);
3838 	}
3839 
3840 	if (update_wire_count)
3841 		vm_wire_sub(count);
3842 }
3843 
3844 /*
3845  * Mark this page as wired down, preventing reclamation by the page daemon
3846  * or when the containing object is destroyed.
3847  */
3848 void
3849 vm_page_wire(vm_page_t m)
3850 {
3851 	u_int old;
3852 
3853 	KASSERT(m->object != NULL,
3854 	    ("vm_page_wire: page %p does not belong to an object", m));
3855 	if (!vm_page_busied(m) && !vm_object_busied(m->object))
3856 		VM_OBJECT_ASSERT_LOCKED(m->object);
3857 	KASSERT((m->flags & PG_FICTITIOUS) == 0 ||
3858 	    VPRC_WIRE_COUNT(m->ref_count) >= 1,
3859 	    ("vm_page_wire: fictitious page %p has zero wirings", m));
3860 
3861 	old = atomic_fetchadd_int(&m->ref_count, 1);
3862 	KASSERT(VPRC_WIRE_COUNT(old) != VPRC_WIRE_COUNT_MAX,
3863 	    ("vm_page_wire: counter overflow for page %p", m));
3864 	if (VPRC_WIRE_COUNT(old) == 0) {
3865 		if ((m->oflags & VPO_UNMANAGED) == 0)
3866 			vm_page_aflag_set(m, PGA_DEQUEUE);
3867 		vm_wire_add(1);
3868 	}
3869 }
3870 
3871 /*
3872  * Attempt to wire a mapped page following a pmap lookup of that page.
3873  * This may fail if a thread is concurrently tearing down mappings of the page.
3874  * The transient failure is acceptable because it translates to the
3875  * failure of the caller pmap_extract_and_hold(), which should be then
3876  * followed by the vm_fault() fallback, see e.g. vm_fault_quick_hold_pages().
3877  */
3878 bool
3879 vm_page_wire_mapped(vm_page_t m)
3880 {
3881 	u_int old;
3882 
3883 	old = m->ref_count;
3884 	do {
3885 		KASSERT(old > 0,
3886 		    ("vm_page_wire_mapped: wiring unreferenced page %p", m));
3887 		if ((old & VPRC_BLOCKED) != 0)
3888 			return (false);
3889 	} while (!atomic_fcmpset_int(&m->ref_count, &old, old + 1));
3890 
3891 	if (VPRC_WIRE_COUNT(old) == 0) {
3892 		if ((m->oflags & VPO_UNMANAGED) == 0)
3893 			vm_page_aflag_set(m, PGA_DEQUEUE);
3894 		vm_wire_add(1);
3895 	}
3896 	return (true);
3897 }
3898 
3899 /*
3900  * Release a wiring reference to a managed page.  If the page still belongs to
3901  * an object, update its position in the page queues to reflect the reference.
3902  * If the wiring was the last reference to the page, free the page.
3903  */
3904 static void
3905 vm_page_unwire_managed(vm_page_t m, uint8_t nqueue, bool noreuse)
3906 {
3907 	u_int old;
3908 
3909 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3910 	    ("%s: page %p is unmanaged", __func__, m));
3911 
3912 	/*
3913 	 * Update LRU state before releasing the wiring reference.
3914 	 * Use a release store when updating the reference count to
3915 	 * synchronize with vm_page_free_prep().
3916 	 */
3917 	old = m->ref_count;
3918 	do {
3919 		KASSERT(VPRC_WIRE_COUNT(old) > 0,
3920 		    ("vm_page_unwire: wire count underflow for page %p", m));
3921 
3922 		if (old > VPRC_OBJREF + 1) {
3923 			/*
3924 			 * The page has at least one other wiring reference.  An
3925 			 * earlier iteration of this loop may have called
3926 			 * vm_page_release_toq() and cleared PGA_DEQUEUE, so
3927 			 * re-set it if necessary.
3928 			 */
3929 			if ((vm_page_astate_load(m).flags & PGA_DEQUEUE) == 0)
3930 				vm_page_aflag_set(m, PGA_DEQUEUE);
3931 		} else if (old == VPRC_OBJREF + 1) {
3932 			/*
3933 			 * This is the last wiring.  Clear PGA_DEQUEUE and
3934 			 * update the page's queue state to reflect the
3935 			 * reference.  If the page does not belong to an object
3936 			 * (i.e., the VPRC_OBJREF bit is clear), we only need to
3937 			 * clear leftover queue state.
3938 			 */
3939 			vm_page_release_toq(m, nqueue, false);
3940 		} else if (old == 1) {
3941 			vm_page_aflag_clear(m, PGA_DEQUEUE);
3942 		}
3943 	} while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
3944 
3945 	if (VPRC_WIRE_COUNT(old) == 1) {
3946 		vm_wire_sub(1);
3947 		if (old == 1)
3948 			vm_page_free(m);
3949 	}
3950 }
3951 
3952 /*
3953  * Release one wiring of the specified page, potentially allowing it to be
3954  * paged out.
3955  *
3956  * Only managed pages belonging to an object can be paged out.  If the number
3957  * of wirings transitions to zero and the page is eligible for page out, then
3958  * the page is added to the specified paging queue.  If the released wiring
3959  * represented the last reference to the page, the page is freed.
3960  *
3961  * A managed page must be locked.
3962  */
3963 void
3964 vm_page_unwire(vm_page_t m, uint8_t nqueue)
3965 {
3966 
3967 	KASSERT(nqueue < PQ_COUNT,
3968 	    ("vm_page_unwire: invalid queue %u request for page %p",
3969 	    nqueue, m));
3970 
3971 	if ((m->oflags & VPO_UNMANAGED) != 0) {
3972 		if (vm_page_unwire_noq(m) && m->ref_count == 0)
3973 			vm_page_free(m);
3974 		return;
3975 	}
3976 	vm_page_unwire_managed(m, nqueue, false);
3977 }
3978 
3979 /*
3980  * Unwire a page without (re-)inserting it into a page queue.  It is up
3981  * to the caller to enqueue, requeue, or free the page as appropriate.
3982  * In most cases involving managed pages, vm_page_unwire() should be used
3983  * instead.
3984  */
3985 bool
3986 vm_page_unwire_noq(vm_page_t m)
3987 {
3988 	u_int old;
3989 
3990 	old = vm_page_drop(m, 1);
3991 	KASSERT(VPRC_WIRE_COUNT(old) != 0,
3992 	    ("vm_page_unref: counter underflow for page %p", m));
3993 	KASSERT((m->flags & PG_FICTITIOUS) == 0 || VPRC_WIRE_COUNT(old) > 1,
3994 	    ("vm_page_unref: missing ref on fictitious page %p", m));
3995 
3996 	if (VPRC_WIRE_COUNT(old) > 1)
3997 		return (false);
3998 	if ((m->oflags & VPO_UNMANAGED) == 0)
3999 		vm_page_aflag_clear(m, PGA_DEQUEUE);
4000 	vm_wire_sub(1);
4001 	return (true);
4002 }
4003 
4004 /*
4005  * Ensure that the page ends up in the specified page queue.  If the page is
4006  * active or being moved to the active queue, ensure that its act_count is
4007  * at least ACT_INIT but do not otherwise mess with it.
4008  *
4009  * A managed page must be locked.
4010  */
4011 static __always_inline void
4012 vm_page_mvqueue(vm_page_t m, const uint8_t nqueue, const uint16_t nflag)
4013 {
4014 	vm_page_astate_t old, new;
4015 
4016 	KASSERT(m->ref_count > 0,
4017 	    ("%s: page %p does not carry any references", __func__, m));
4018 	KASSERT(nflag == PGA_REQUEUE || nflag == PGA_REQUEUE_HEAD,
4019 	    ("%s: invalid flags %x", __func__, nflag));
4020 
4021 	if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
4022 		return;
4023 
4024 	old = vm_page_astate_load(m);
4025 	do {
4026 		if ((old.flags & PGA_DEQUEUE) != 0)
4027 			break;
4028 		new = old;
4029 		new.flags &= ~PGA_QUEUE_OP_MASK;
4030 		if (nqueue == PQ_ACTIVE)
4031 			new.act_count = max(old.act_count, ACT_INIT);
4032 		if (old.queue == nqueue) {
4033 			if (nqueue != PQ_ACTIVE)
4034 				new.flags |= nflag;
4035 		} else {
4036 			new.flags |= nflag;
4037 			new.queue = nqueue;
4038 		}
4039 	} while (!vm_page_pqstate_commit(m, &old, new));
4040 }
4041 
4042 /*
4043  * Put the specified page on the active list (if appropriate).
4044  */
4045 void
4046 vm_page_activate(vm_page_t m)
4047 {
4048 
4049 	vm_page_mvqueue(m, PQ_ACTIVE, PGA_REQUEUE);
4050 }
4051 
4052 /*
4053  * Move the specified page to the tail of the inactive queue, or requeue
4054  * the page if it is already in the inactive queue.
4055  */
4056 void
4057 vm_page_deactivate(vm_page_t m)
4058 {
4059 
4060 	vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE);
4061 }
4062 
4063 void
4064 vm_page_deactivate_noreuse(vm_page_t m)
4065 {
4066 
4067 	vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE_HEAD);
4068 }
4069 
4070 /*
4071  * Put a page in the laundry, or requeue it if it is already there.
4072  */
4073 void
4074 vm_page_launder(vm_page_t m)
4075 {
4076 
4077 	vm_page_mvqueue(m, PQ_LAUNDRY, PGA_REQUEUE);
4078 }
4079 
4080 /*
4081  * Put a page in the PQ_UNSWAPPABLE holding queue.
4082  */
4083 void
4084 vm_page_unswappable(vm_page_t m)
4085 {
4086 
4087 	KASSERT(!vm_page_wired(m) && (m->oflags & VPO_UNMANAGED) == 0,
4088 	    ("page %p already unswappable", m));
4089 
4090 	vm_page_dequeue(m);
4091 	vm_page_enqueue(m, PQ_UNSWAPPABLE);
4092 }
4093 
4094 /*
4095  * Release a page back to the page queues in preparation for unwiring.
4096  */
4097 static void
4098 vm_page_release_toq(vm_page_t m, uint8_t nqueue, const bool noreuse)
4099 {
4100 	vm_page_astate_t old, new;
4101 	uint16_t nflag;
4102 
4103 	/*
4104 	 * Use a check of the valid bits to determine whether we should
4105 	 * accelerate reclamation of the page.  The object lock might not be
4106 	 * held here, in which case the check is racy.  At worst we will either
4107 	 * accelerate reclamation of a valid page and violate LRU, or
4108 	 * unnecessarily defer reclamation of an invalid page.
4109 	 *
4110 	 * If we were asked to not cache the page, place it near the head of the
4111 	 * inactive queue so that is reclaimed sooner.
4112 	 */
4113 	if (noreuse || m->valid == 0) {
4114 		nqueue = PQ_INACTIVE;
4115 		nflag = PGA_REQUEUE_HEAD;
4116 	} else {
4117 		nflag = PGA_REQUEUE;
4118 	}
4119 
4120 	old = vm_page_astate_load(m);
4121 	do {
4122 		new = old;
4123 
4124 		/*
4125 		 * If the page is already in the active queue and we are not
4126 		 * trying to accelerate reclamation, simply mark it as
4127 		 * referenced and avoid any queue operations.
4128 		 */
4129 		new.flags &= ~PGA_QUEUE_OP_MASK;
4130 		if (nflag != PGA_REQUEUE_HEAD && old.queue == PQ_ACTIVE)
4131 			new.flags |= PGA_REFERENCED;
4132 		else {
4133 			new.flags |= nflag;
4134 			new.queue = nqueue;
4135 		}
4136 	} while (!vm_page_pqstate_commit(m, &old, new));
4137 }
4138 
4139 /*
4140  * Unwire a page and either attempt to free it or re-add it to the page queues.
4141  */
4142 void
4143 vm_page_release(vm_page_t m, int flags)
4144 {
4145 	vm_object_t object;
4146 
4147 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4148 	    ("vm_page_release: page %p is unmanaged", m));
4149 
4150 	if ((flags & VPR_TRYFREE) != 0) {
4151 		for (;;) {
4152 			object = atomic_load_ptr(&m->object);
4153 			if (object == NULL)
4154 				break;
4155 			/* Depends on type-stability. */
4156 			if (vm_page_busied(m) || !VM_OBJECT_TRYWLOCK(object))
4157 				break;
4158 			if (object == m->object) {
4159 				vm_page_release_locked(m, flags);
4160 				VM_OBJECT_WUNLOCK(object);
4161 				return;
4162 			}
4163 			VM_OBJECT_WUNLOCK(object);
4164 		}
4165 	}
4166 	vm_page_unwire_managed(m, PQ_INACTIVE, flags != 0);
4167 }
4168 
4169 /* See vm_page_release(). */
4170 void
4171 vm_page_release_locked(vm_page_t m, int flags)
4172 {
4173 
4174 	VM_OBJECT_ASSERT_WLOCKED(m->object);
4175 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4176 	    ("vm_page_release_locked: page %p is unmanaged", m));
4177 
4178 	if (vm_page_unwire_noq(m)) {
4179 		if ((flags & VPR_TRYFREE) != 0 &&
4180 		    (m->object->ref_count == 0 || !pmap_page_is_mapped(m)) &&
4181 		    m->dirty == 0 && vm_page_tryxbusy(m)) {
4182 			vm_page_free(m);
4183 		} else {
4184 			vm_page_release_toq(m, PQ_INACTIVE, flags != 0);
4185 		}
4186 	}
4187 }
4188 
4189 static bool
4190 vm_page_try_blocked_op(vm_page_t m, void (*op)(vm_page_t))
4191 {
4192 	u_int old;
4193 
4194 	KASSERT(m->object != NULL && (m->oflags & VPO_UNMANAGED) == 0,
4195 	    ("vm_page_try_blocked_op: page %p has no object", m));
4196 	KASSERT(vm_page_busied(m),
4197 	    ("vm_page_try_blocked_op: page %p is not busy", m));
4198 	VM_OBJECT_ASSERT_LOCKED(m->object);
4199 
4200 	old = m->ref_count;
4201 	do {
4202 		KASSERT(old != 0,
4203 		    ("vm_page_try_blocked_op: page %p has no references", m));
4204 		if (VPRC_WIRE_COUNT(old) != 0)
4205 			return (false);
4206 	} while (!atomic_fcmpset_int(&m->ref_count, &old, old | VPRC_BLOCKED));
4207 
4208 	(op)(m);
4209 
4210 	/*
4211 	 * If the object is read-locked, new wirings may be created via an
4212 	 * object lookup.
4213 	 */
4214 	old = vm_page_drop(m, VPRC_BLOCKED);
4215 	KASSERT(!VM_OBJECT_WOWNED(m->object) ||
4216 	    old == (VPRC_BLOCKED | VPRC_OBJREF),
4217 	    ("vm_page_try_blocked_op: unexpected refcount value %u for %p",
4218 	    old, m));
4219 	return (true);
4220 }
4221 
4222 /*
4223  * Atomically check for wirings and remove all mappings of the page.
4224  */
4225 bool
4226 vm_page_try_remove_all(vm_page_t m)
4227 {
4228 
4229 	return (vm_page_try_blocked_op(m, pmap_remove_all));
4230 }
4231 
4232 /*
4233  * Atomically check for wirings and remove all writeable mappings of the page.
4234  */
4235 bool
4236 vm_page_try_remove_write(vm_page_t m)
4237 {
4238 
4239 	return (vm_page_try_blocked_op(m, pmap_remove_write));
4240 }
4241 
4242 /*
4243  * vm_page_advise
4244  *
4245  * 	Apply the specified advice to the given page.
4246  *
4247  *	The object and page must be locked.
4248  */
4249 void
4250 vm_page_advise(vm_page_t m, int advice)
4251 {
4252 
4253 	VM_OBJECT_ASSERT_WLOCKED(m->object);
4254 	if (advice == MADV_FREE)
4255 		/*
4256 		 * Mark the page clean.  This will allow the page to be freed
4257 		 * without first paging it out.  MADV_FREE pages are often
4258 		 * quickly reused by malloc(3), so we do not do anything that
4259 		 * would result in a page fault on a later access.
4260 		 */
4261 		vm_page_undirty(m);
4262 	else if (advice != MADV_DONTNEED) {
4263 		if (advice == MADV_WILLNEED)
4264 			vm_page_activate(m);
4265 		return;
4266 	}
4267 
4268 	if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
4269 		vm_page_dirty(m);
4270 
4271 	/*
4272 	 * Clear any references to the page.  Otherwise, the page daemon will
4273 	 * immediately reactivate the page.
4274 	 */
4275 	vm_page_aflag_clear(m, PGA_REFERENCED);
4276 
4277 	/*
4278 	 * Place clean pages near the head of the inactive queue rather than
4279 	 * the tail, thus defeating the queue's LRU operation and ensuring that
4280 	 * the page will be reused quickly.  Dirty pages not already in the
4281 	 * laundry are moved there.
4282 	 */
4283 	if (m->dirty == 0)
4284 		vm_page_deactivate_noreuse(m);
4285 	else if (!vm_page_in_laundry(m))
4286 		vm_page_launder(m);
4287 }
4288 
4289 /*
4290  *	vm_page_grab_release
4291  *
4292  *	Helper routine for grab functions to release busy on return.
4293  */
4294 static inline void
4295 vm_page_grab_release(vm_page_t m, int allocflags)
4296 {
4297 
4298 	if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4299 		if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4300 			vm_page_sunbusy(m);
4301 		else
4302 			vm_page_xunbusy(m);
4303 	}
4304 }
4305 
4306 /*
4307  *	vm_page_grab_sleep
4308  *
4309  *	Sleep for busy according to VM_ALLOC_ parameters.  Returns true
4310  *	if the caller should retry and false otherwise.
4311  *
4312  *	If the object is locked on entry the object will be unlocked with
4313  *	false returns and still locked but possibly having been dropped
4314  *	with true returns.
4315  */
4316 static bool
4317 vm_page_grab_sleep(vm_object_t object, vm_page_t m, vm_pindex_t pindex,
4318     const char *wmesg, int allocflags, bool locked)
4319 {
4320 
4321 	if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4322 		return (false);
4323 
4324 	/*
4325 	 * Reference the page before unlocking and sleeping so that
4326 	 * the page daemon is less likely to reclaim it.
4327 	 */
4328 	if (locked && (allocflags & VM_ALLOC_NOCREAT) == 0)
4329 		vm_page_reference(m);
4330 
4331 	if (_vm_page_busy_sleep(object, m, m->pindex, wmesg, allocflags,
4332 	    locked) && locked)
4333 		VM_OBJECT_WLOCK(object);
4334 	if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
4335 		return (false);
4336 
4337 	return (true);
4338 }
4339 
4340 /*
4341  * Assert that the grab flags are valid.
4342  */
4343 static inline void
4344 vm_page_grab_check(int allocflags)
4345 {
4346 
4347 	KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
4348 	    (allocflags & VM_ALLOC_WIRED) != 0,
4349 	    ("vm_page_grab*: the pages must be busied or wired"));
4350 
4351 	KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4352 	    (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4353 	    ("vm_page_grab*: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4354 }
4355 
4356 /*
4357  * Calculate the page allocation flags for grab.
4358  */
4359 static inline int
4360 vm_page_grab_pflags(int allocflags)
4361 {
4362 	int pflags;
4363 
4364 	pflags = allocflags &
4365 	    ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL |
4366 	    VM_ALLOC_NOBUSY);
4367 	if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4368 		pflags |= VM_ALLOC_WAITFAIL;
4369 	if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4370 		pflags |= VM_ALLOC_SBUSY;
4371 
4372 	return (pflags);
4373 }
4374 
4375 /*
4376  * Grab a page, waiting until we are waken up due to the page
4377  * changing state.  We keep on waiting, if the page continues
4378  * to be in the object.  If the page doesn't exist, first allocate it
4379  * and then conditionally zero it.
4380  *
4381  * This routine may sleep.
4382  *
4383  * The object must be locked on entry.  The lock will, however, be released
4384  * and reacquired if the routine sleeps.
4385  */
4386 vm_page_t
4387 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
4388 {
4389 	vm_page_t m;
4390 
4391 	VM_OBJECT_ASSERT_WLOCKED(object);
4392 	vm_page_grab_check(allocflags);
4393 
4394 retrylookup:
4395 	if ((m = vm_page_lookup(object, pindex)) != NULL) {
4396 		if (!vm_page_tryacquire(m, allocflags)) {
4397 			if (vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4398 			    allocflags, true))
4399 				goto retrylookup;
4400 			return (NULL);
4401 		}
4402 		goto out;
4403 	}
4404 	if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4405 		return (NULL);
4406 	m = vm_page_alloc(object, pindex, vm_page_grab_pflags(allocflags));
4407 	if (m == NULL) {
4408 		if ((allocflags & (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL)) != 0)
4409 			return (NULL);
4410 		goto retrylookup;
4411 	}
4412 	if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
4413 		pmap_zero_page(m);
4414 
4415 out:
4416 	vm_page_grab_release(m, allocflags);
4417 
4418 	return (m);
4419 }
4420 
4421 /*
4422  * Locklessly attempt to acquire a page given a (object, pindex) tuple
4423  * and an optional previous page to avoid the radix lookup.  The resulting
4424  * page will be validated against the identity tuple and busied or wired
4425  * as requested.  A NULL *mp return guarantees that the page was not in
4426  * radix at the time of the call but callers must perform higher level
4427  * synchronization or retry the operation under a lock if they require
4428  * an atomic answer.  This is the only lock free validation routine,
4429  * other routines can depend on the resulting page state.
4430  *
4431  * The return value indicates whether the operation failed due to caller
4432  * flags.  The return is tri-state with mp:
4433  *
4434  * (true, *mp != NULL) - The operation was successful.
4435  * (true, *mp == NULL) - The page was not found in tree.
4436  * (false, *mp == NULL) - WAITFAIL or NOWAIT prevented acquisition.
4437  */
4438 static bool
4439 vm_page_acquire_unlocked(vm_object_t object, vm_pindex_t pindex,
4440     vm_page_t prev, vm_page_t *mp, int allocflags)
4441 {
4442 	vm_page_t m;
4443 
4444 	vm_page_grab_check(allocflags);
4445 	MPASS(prev == NULL || vm_page_busied(prev) || vm_page_wired(prev));
4446 
4447 	*mp = NULL;
4448 	for (;;) {
4449 		/*
4450 		 * We may see a false NULL here because the previous page
4451 		 * has been removed or just inserted and the list is loaded
4452 		 * without barriers.  Switch to radix to verify.
4453 		 */
4454 		if (prev == NULL || (m = TAILQ_NEXT(prev, listq)) == NULL ||
4455 		    m->pindex != pindex ||
4456 		    atomic_load_ptr(&m->object) != object) {
4457 			prev = NULL;
4458 			/*
4459 			 * This guarantees the result is instantaneously
4460 			 * correct.
4461 			 */
4462 			m = vm_radix_lookup_unlocked(&object->rtree, pindex);
4463 		}
4464 		if (m == NULL)
4465 			return (true);
4466 		if (vm_page_trybusy(m, allocflags)) {
4467 			if (m->object == object && m->pindex == pindex)
4468 				break;
4469 			/* relookup. */
4470 			vm_page_busy_release(m);
4471 			cpu_spinwait();
4472 			continue;
4473 		}
4474 		if (!vm_page_grab_sleep(object, m, pindex, "pgnslp",
4475 		    allocflags, false))
4476 			return (false);
4477 	}
4478 	if ((allocflags & VM_ALLOC_WIRED) != 0)
4479 		vm_page_wire(m);
4480 	vm_page_grab_release(m, allocflags);
4481 	*mp = m;
4482 	return (true);
4483 }
4484 
4485 /*
4486  * Try to locklessly grab a page and fall back to the object lock if NOCREAT
4487  * is not set.
4488  */
4489 vm_page_t
4490 vm_page_grab_unlocked(vm_object_t object, vm_pindex_t pindex, int allocflags)
4491 {
4492 	vm_page_t m;
4493 
4494 	vm_page_grab_check(allocflags);
4495 
4496 	if (!vm_page_acquire_unlocked(object, pindex, NULL, &m, allocflags))
4497 		return (NULL);
4498 	if (m != NULL)
4499 		return (m);
4500 
4501 	/*
4502 	 * The radix lockless lookup should never return a false negative
4503 	 * errors.  If the user specifies NOCREAT they are guaranteed there
4504 	 * was no page present at the instant of the call.  A NOCREAT caller
4505 	 * must handle create races gracefully.
4506 	 */
4507 	if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4508 		return (NULL);
4509 
4510 	VM_OBJECT_WLOCK(object);
4511 	m = vm_page_grab(object, pindex, allocflags);
4512 	VM_OBJECT_WUNLOCK(object);
4513 
4514 	return (m);
4515 }
4516 
4517 /*
4518  * Grab a page and make it valid, paging in if necessary.  Pages missing from
4519  * their pager are zero filled and validated.  If a VM_ALLOC_COUNT is supplied
4520  * and the page is not valid as many as VM_INITIAL_PAGEIN pages can be brought
4521  * in simultaneously.  Additional pages will be left on a paging queue but
4522  * will neither be wired nor busy regardless of allocflags.
4523  */
4524 int
4525 vm_page_grab_valid(vm_page_t *mp, vm_object_t object, vm_pindex_t pindex, int allocflags)
4526 {
4527 	vm_page_t m;
4528 	vm_page_t ma[VM_INITIAL_PAGEIN];
4529 	int after, i, pflags, rv;
4530 
4531 	KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4532 	    (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4533 	    ("vm_page_grab_valid: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4534 	KASSERT((allocflags &
4535 	    (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4536 	    ("vm_page_grab_valid: Invalid flags 0x%X", allocflags));
4537 	VM_OBJECT_ASSERT_WLOCKED(object);
4538 	pflags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY);
4539 	pflags |= VM_ALLOC_WAITFAIL;
4540 
4541 retrylookup:
4542 	if ((m = vm_page_lookup(object, pindex)) != NULL) {
4543 		/*
4544 		 * If the page is fully valid it can only become invalid
4545 		 * with the object lock held.  If it is not valid it can
4546 		 * become valid with the busy lock held.  Therefore, we
4547 		 * may unnecessarily lock the exclusive busy here if we
4548 		 * race with I/O completion not using the object lock.
4549 		 * However, we will not end up with an invalid page and a
4550 		 * shared lock.
4551 		 */
4552 		if (!vm_page_trybusy(m,
4553 		    vm_page_all_valid(m) ? allocflags : 0)) {
4554 			(void)vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4555 			    allocflags, true);
4556 			goto retrylookup;
4557 		}
4558 		if (vm_page_all_valid(m))
4559 			goto out;
4560 		if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4561 			vm_page_busy_release(m);
4562 			*mp = NULL;
4563 			return (VM_PAGER_FAIL);
4564 		}
4565 	} else if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4566 		*mp = NULL;
4567 		return (VM_PAGER_FAIL);
4568 	} else if ((m = vm_page_alloc(object, pindex, pflags)) == NULL) {
4569 		goto retrylookup;
4570 	}
4571 
4572 	vm_page_assert_xbusied(m);
4573 	if (vm_pager_has_page(object, pindex, NULL, &after)) {
4574 		after = MIN(after, VM_INITIAL_PAGEIN);
4575 		after = MIN(after, allocflags >> VM_ALLOC_COUNT_SHIFT);
4576 		after = MAX(after, 1);
4577 		ma[0] = m;
4578 		for (i = 1; i < after; i++) {
4579 			if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
4580 				if (ma[i]->valid || !vm_page_tryxbusy(ma[i]))
4581 					break;
4582 			} else {
4583 				ma[i] = vm_page_alloc(object, m->pindex + i,
4584 				    VM_ALLOC_NORMAL);
4585 				if (ma[i] == NULL)
4586 					break;
4587 			}
4588 		}
4589 		after = i;
4590 		vm_object_pip_add(object, after);
4591 		VM_OBJECT_WUNLOCK(object);
4592 		rv = vm_pager_get_pages(object, ma, after, NULL, NULL);
4593 		VM_OBJECT_WLOCK(object);
4594 		vm_object_pip_wakeupn(object, after);
4595 		/* Pager may have replaced a page. */
4596 		m = ma[0];
4597 		if (rv != VM_PAGER_OK) {
4598 			for (i = 0; i < after; i++) {
4599 				if (!vm_page_wired(ma[i]))
4600 					vm_page_free(ma[i]);
4601 				else
4602 					vm_page_xunbusy(ma[i]);
4603 			}
4604 			*mp = NULL;
4605 			return (rv);
4606 		}
4607 		for (i = 1; i < after; i++)
4608 			vm_page_readahead_finish(ma[i]);
4609 		MPASS(vm_page_all_valid(m));
4610 	} else {
4611 		vm_page_zero_invalid(m, TRUE);
4612 	}
4613 out:
4614 	if ((allocflags & VM_ALLOC_WIRED) != 0)
4615 		vm_page_wire(m);
4616 	if ((allocflags & VM_ALLOC_SBUSY) != 0 && vm_page_xbusied(m))
4617 		vm_page_busy_downgrade(m);
4618 	else if ((allocflags & VM_ALLOC_NOBUSY) != 0)
4619 		vm_page_busy_release(m);
4620 	*mp = m;
4621 	return (VM_PAGER_OK);
4622 }
4623 
4624 /*
4625  * Locklessly grab a valid page.  If the page is not valid or not yet
4626  * allocated this will fall back to the object lock method.
4627  */
4628 int
4629 vm_page_grab_valid_unlocked(vm_page_t *mp, vm_object_t object,
4630     vm_pindex_t pindex, int allocflags)
4631 {
4632 	vm_page_t m;
4633 	int flags;
4634 	int error;
4635 
4636 	KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4637 	    (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4638 	    ("vm_page_grab_valid_unlocked: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY "
4639 	    "mismatch"));
4640 	KASSERT((allocflags &
4641 	    (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4642 	    ("vm_page_grab_valid_unlocked: Invalid flags 0x%X", allocflags));
4643 
4644 	/*
4645 	 * Attempt a lockless lookup and busy.  We need at least an sbusy
4646 	 * before we can inspect the valid field and return a wired page.
4647 	 */
4648 	flags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
4649 	if (!vm_page_acquire_unlocked(object, pindex, NULL, mp, flags))
4650 		return (VM_PAGER_FAIL);
4651 	if ((m = *mp) != NULL) {
4652 		if (vm_page_all_valid(m)) {
4653 			if ((allocflags & VM_ALLOC_WIRED) != 0)
4654 				vm_page_wire(m);
4655 			vm_page_grab_release(m, allocflags);
4656 			return (VM_PAGER_OK);
4657 		}
4658 		vm_page_busy_release(m);
4659 	}
4660 	if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4661 		*mp = NULL;
4662 		return (VM_PAGER_FAIL);
4663 	}
4664 	VM_OBJECT_WLOCK(object);
4665 	error = vm_page_grab_valid(mp, object, pindex, allocflags);
4666 	VM_OBJECT_WUNLOCK(object);
4667 
4668 	return (error);
4669 }
4670 
4671 /*
4672  * Return the specified range of pages from the given object.  For each
4673  * page offset within the range, if a page already exists within the object
4674  * at that offset and it is busy, then wait for it to change state.  If,
4675  * instead, the page doesn't exist, then allocate it.
4676  *
4677  * The caller must always specify an allocation class.
4678  *
4679  * allocation classes:
4680  *	VM_ALLOC_NORMAL		normal process request
4681  *	VM_ALLOC_SYSTEM		system *really* needs the pages
4682  *
4683  * The caller must always specify that the pages are to be busied and/or
4684  * wired.
4685  *
4686  * optional allocation flags:
4687  *	VM_ALLOC_IGN_SBUSY	do not sleep on soft busy pages
4688  *	VM_ALLOC_NOBUSY		do not exclusive busy the page
4689  *	VM_ALLOC_NOWAIT		do not sleep
4690  *	VM_ALLOC_SBUSY		set page to sbusy state
4691  *	VM_ALLOC_WIRED		wire the pages
4692  *	VM_ALLOC_ZERO		zero and validate any invalid pages
4693  *
4694  * If VM_ALLOC_NOWAIT is not specified, this routine may sleep.  Otherwise, it
4695  * may return a partial prefix of the requested range.
4696  */
4697 int
4698 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
4699     vm_page_t *ma, int count)
4700 {
4701 	vm_page_t m, mpred;
4702 	int pflags;
4703 	int i;
4704 
4705 	VM_OBJECT_ASSERT_WLOCKED(object);
4706 	KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
4707 	    ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
4708 	vm_page_grab_check(allocflags);
4709 
4710 	pflags = vm_page_grab_pflags(allocflags);
4711 	if (count == 0)
4712 		return (0);
4713 
4714 	i = 0;
4715 retrylookup:
4716 	m = vm_radix_lookup_le(&object->rtree, pindex + i);
4717 	if (m == NULL || m->pindex != pindex + i) {
4718 		mpred = m;
4719 		m = NULL;
4720 	} else
4721 		mpred = TAILQ_PREV(m, pglist, listq);
4722 	for (; i < count; i++) {
4723 		if (m != NULL) {
4724 			if (!vm_page_tryacquire(m, allocflags)) {
4725 				if (vm_page_grab_sleep(object, m, pindex,
4726 				    "grbmaw", allocflags, true))
4727 					goto retrylookup;
4728 				break;
4729 			}
4730 		} else {
4731 			if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4732 				break;
4733 			m = vm_page_alloc_after(object, pindex + i,
4734 			    pflags | VM_ALLOC_COUNT(count - i), mpred);
4735 			if (m == NULL) {
4736 				if ((allocflags & (VM_ALLOC_NOWAIT |
4737 				    VM_ALLOC_WAITFAIL)) != 0)
4738 					break;
4739 				goto retrylookup;
4740 			}
4741 		}
4742 		if (vm_page_none_valid(m) &&
4743 		    (allocflags & VM_ALLOC_ZERO) != 0) {
4744 			if ((m->flags & PG_ZERO) == 0)
4745 				pmap_zero_page(m);
4746 			vm_page_valid(m);
4747 		}
4748 		vm_page_grab_release(m, allocflags);
4749 		ma[i] = mpred = m;
4750 		m = vm_page_next(m);
4751 	}
4752 	return (i);
4753 }
4754 
4755 /*
4756  * Unlocked variant of vm_page_grab_pages().  This accepts the same flags
4757  * and will fall back to the locked variant to handle allocation.
4758  */
4759 int
4760 vm_page_grab_pages_unlocked(vm_object_t object, vm_pindex_t pindex,
4761     int allocflags, vm_page_t *ma, int count)
4762 {
4763 	vm_page_t m, pred;
4764 	int flags;
4765 	int i;
4766 
4767 	vm_page_grab_check(allocflags);
4768 
4769 	/*
4770 	 * Modify flags for lockless acquire to hold the page until we
4771 	 * set it valid if necessary.
4772 	 */
4773 	flags = allocflags & ~VM_ALLOC_NOBUSY;
4774 	pred = NULL;
4775 	for (i = 0; i < count; i++, pindex++) {
4776 		if (!vm_page_acquire_unlocked(object, pindex, pred, &m, flags))
4777 			return (i);
4778 		if (m == NULL)
4779 			break;
4780 		if ((flags & VM_ALLOC_ZERO) != 0 && vm_page_none_valid(m)) {
4781 			if ((m->flags & PG_ZERO) == 0)
4782 				pmap_zero_page(m);
4783 			vm_page_valid(m);
4784 		}
4785 		/* m will still be wired or busy according to flags. */
4786 		vm_page_grab_release(m, allocflags);
4787 		pred = ma[i] = m;
4788 	}
4789 	if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4790 		return (i);
4791 	count -= i;
4792 	VM_OBJECT_WLOCK(object);
4793 	i += vm_page_grab_pages(object, pindex, allocflags, &ma[i], count);
4794 	VM_OBJECT_WUNLOCK(object);
4795 
4796 	return (i);
4797 }
4798 
4799 /*
4800  * Mapping function for valid or dirty bits in a page.
4801  *
4802  * Inputs are required to range within a page.
4803  */
4804 vm_page_bits_t
4805 vm_page_bits(int base, int size)
4806 {
4807 	int first_bit;
4808 	int last_bit;
4809 
4810 	KASSERT(
4811 	    base + size <= PAGE_SIZE,
4812 	    ("vm_page_bits: illegal base/size %d/%d", base, size)
4813 	);
4814 
4815 	if (size == 0)		/* handle degenerate case */
4816 		return (0);
4817 
4818 	first_bit = base >> DEV_BSHIFT;
4819 	last_bit = (base + size - 1) >> DEV_BSHIFT;
4820 
4821 	return (((vm_page_bits_t)2 << last_bit) -
4822 	    ((vm_page_bits_t)1 << first_bit));
4823 }
4824 
4825 void
4826 vm_page_bits_set(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t set)
4827 {
4828 
4829 #if PAGE_SIZE == 32768
4830 	atomic_set_64((uint64_t *)bits, set);
4831 #elif PAGE_SIZE == 16384
4832 	atomic_set_32((uint32_t *)bits, set);
4833 #elif (PAGE_SIZE == 8192) && defined(atomic_set_16)
4834 	atomic_set_16((uint16_t *)bits, set);
4835 #elif (PAGE_SIZE == 4096) && defined(atomic_set_8)
4836 	atomic_set_8((uint8_t *)bits, set);
4837 #else		/* PAGE_SIZE <= 8192 */
4838 	uintptr_t addr;
4839 	int shift;
4840 
4841 	addr = (uintptr_t)bits;
4842 	/*
4843 	 * Use a trick to perform a 32-bit atomic on the
4844 	 * containing aligned word, to not depend on the existence
4845 	 * of atomic_{set, clear}_{8, 16}.
4846 	 */
4847 	shift = addr & (sizeof(uint32_t) - 1);
4848 #if BYTE_ORDER == BIG_ENDIAN
4849 	shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4850 #else
4851 	shift *= NBBY;
4852 #endif
4853 	addr &= ~(sizeof(uint32_t) - 1);
4854 	atomic_set_32((uint32_t *)addr, set << shift);
4855 #endif		/* PAGE_SIZE */
4856 }
4857 
4858 static inline void
4859 vm_page_bits_clear(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t clear)
4860 {
4861 
4862 #if PAGE_SIZE == 32768
4863 	atomic_clear_64((uint64_t *)bits, clear);
4864 #elif PAGE_SIZE == 16384
4865 	atomic_clear_32((uint32_t *)bits, clear);
4866 #elif (PAGE_SIZE == 8192) && defined(atomic_clear_16)
4867 	atomic_clear_16((uint16_t *)bits, clear);
4868 #elif (PAGE_SIZE == 4096) && defined(atomic_clear_8)
4869 	atomic_clear_8((uint8_t *)bits, clear);
4870 #else		/* PAGE_SIZE <= 8192 */
4871 	uintptr_t addr;
4872 	int shift;
4873 
4874 	addr = (uintptr_t)bits;
4875 	/*
4876 	 * Use a trick to perform a 32-bit atomic on the
4877 	 * containing aligned word, to not depend on the existence
4878 	 * of atomic_{set, clear}_{8, 16}.
4879 	 */
4880 	shift = addr & (sizeof(uint32_t) - 1);
4881 #if BYTE_ORDER == BIG_ENDIAN
4882 	shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4883 #else
4884 	shift *= NBBY;
4885 #endif
4886 	addr &= ~(sizeof(uint32_t) - 1);
4887 	atomic_clear_32((uint32_t *)addr, clear << shift);
4888 #endif		/* PAGE_SIZE */
4889 }
4890 
4891 static inline vm_page_bits_t
4892 vm_page_bits_swap(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t newbits)
4893 {
4894 #if PAGE_SIZE == 32768
4895 	uint64_t old;
4896 
4897 	old = *bits;
4898 	while (atomic_fcmpset_64(bits, &old, newbits) == 0);
4899 	return (old);
4900 #elif PAGE_SIZE == 16384
4901 	uint32_t old;
4902 
4903 	old = *bits;
4904 	while (atomic_fcmpset_32(bits, &old, newbits) == 0);
4905 	return (old);
4906 #elif (PAGE_SIZE == 8192) && defined(atomic_fcmpset_16)
4907 	uint16_t old;
4908 
4909 	old = *bits;
4910 	while (atomic_fcmpset_16(bits, &old, newbits) == 0);
4911 	return (old);
4912 #elif (PAGE_SIZE == 4096) && defined(atomic_fcmpset_8)
4913 	uint8_t old;
4914 
4915 	old = *bits;
4916 	while (atomic_fcmpset_8(bits, &old, newbits) == 0);
4917 	return (old);
4918 #else		/* PAGE_SIZE <= 4096*/
4919 	uintptr_t addr;
4920 	uint32_t old, new, mask;
4921 	int shift;
4922 
4923 	addr = (uintptr_t)bits;
4924 	/*
4925 	 * Use a trick to perform a 32-bit atomic on the
4926 	 * containing aligned word, to not depend on the existence
4927 	 * of atomic_{set, swap, clear}_{8, 16}.
4928 	 */
4929 	shift = addr & (sizeof(uint32_t) - 1);
4930 #if BYTE_ORDER == BIG_ENDIAN
4931 	shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4932 #else
4933 	shift *= NBBY;
4934 #endif
4935 	addr &= ~(sizeof(uint32_t) - 1);
4936 	mask = VM_PAGE_BITS_ALL << shift;
4937 
4938 	old = *bits;
4939 	do {
4940 		new = old & ~mask;
4941 		new |= newbits << shift;
4942 	} while (atomic_fcmpset_32((uint32_t *)addr, &old, new) == 0);
4943 	return (old >> shift);
4944 #endif		/* PAGE_SIZE */
4945 }
4946 
4947 /*
4948  *	vm_page_set_valid_range:
4949  *
4950  *	Sets portions of a page valid.  The arguments are expected
4951  *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4952  *	of any partial chunks touched by the range.  The invalid portion of
4953  *	such chunks will be zeroed.
4954  *
4955  *	(base + size) must be less then or equal to PAGE_SIZE.
4956  */
4957 void
4958 vm_page_set_valid_range(vm_page_t m, int base, int size)
4959 {
4960 	int endoff, frag;
4961 	vm_page_bits_t pagebits;
4962 
4963 	vm_page_assert_busied(m);
4964 	if (size == 0)	/* handle degenerate case */
4965 		return;
4966 
4967 	/*
4968 	 * If the base is not DEV_BSIZE aligned and the valid
4969 	 * bit is clear, we have to zero out a portion of the
4970 	 * first block.
4971 	 */
4972 	if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4973 	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
4974 		pmap_zero_page_area(m, frag, base - frag);
4975 
4976 	/*
4977 	 * If the ending offset is not DEV_BSIZE aligned and the
4978 	 * valid bit is clear, we have to zero out a portion of
4979 	 * the last block.
4980 	 */
4981 	endoff = base + size;
4982 	if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4983 	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
4984 		pmap_zero_page_area(m, endoff,
4985 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4986 
4987 	/*
4988 	 * Assert that no previously invalid block that is now being validated
4989 	 * is already dirty.
4990 	 */
4991 	KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
4992 	    ("vm_page_set_valid_range: page %p is dirty", m));
4993 
4994 	/*
4995 	 * Set valid bits inclusive of any overlap.
4996 	 */
4997 	pagebits = vm_page_bits(base, size);
4998 	if (vm_page_xbusied(m))
4999 		m->valid |= pagebits;
5000 	else
5001 		vm_page_bits_set(m, &m->valid, pagebits);
5002 }
5003 
5004 /*
5005  * Set the page dirty bits and free the invalid swap space if
5006  * present.  Returns the previous dirty bits.
5007  */
5008 vm_page_bits_t
5009 vm_page_set_dirty(vm_page_t m)
5010 {
5011 	vm_page_bits_t old;
5012 
5013 	VM_PAGE_OBJECT_BUSY_ASSERT(m);
5014 
5015 	if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m)) {
5016 		old = m->dirty;
5017 		m->dirty = VM_PAGE_BITS_ALL;
5018 	} else
5019 		old = vm_page_bits_swap(m, &m->dirty, VM_PAGE_BITS_ALL);
5020 	if (old == 0 && (m->a.flags & PGA_SWAP_SPACE) != 0)
5021 		vm_pager_page_unswapped(m);
5022 
5023 	return (old);
5024 }
5025 
5026 /*
5027  * Clear the given bits from the specified page's dirty field.
5028  */
5029 static __inline void
5030 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
5031 {
5032 
5033 	vm_page_assert_busied(m);
5034 
5035 	/*
5036 	 * If the page is xbusied and not write mapped we are the
5037 	 * only thread that can modify dirty bits.  Otherwise, The pmap
5038 	 * layer can call vm_page_dirty() without holding a distinguished
5039 	 * lock.  The combination of page busy and atomic operations
5040 	 * suffice to guarantee consistency of the page dirty field.
5041 	 */
5042 	if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
5043 		m->dirty &= ~pagebits;
5044 	else
5045 		vm_page_bits_clear(m, &m->dirty, pagebits);
5046 }
5047 
5048 /*
5049  *	vm_page_set_validclean:
5050  *
5051  *	Sets portions of a page valid and clean.  The arguments are expected
5052  *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
5053  *	of any partial chunks touched by the range.  The invalid portion of
5054  *	such chunks will be zero'd.
5055  *
5056  *	(base + size) must be less then or equal to PAGE_SIZE.
5057  */
5058 void
5059 vm_page_set_validclean(vm_page_t m, int base, int size)
5060 {
5061 	vm_page_bits_t oldvalid, pagebits;
5062 	int endoff, frag;
5063 
5064 	vm_page_assert_busied(m);
5065 	if (size == 0)	/* handle degenerate case */
5066 		return;
5067 
5068 	/*
5069 	 * If the base is not DEV_BSIZE aligned and the valid
5070 	 * bit is clear, we have to zero out a portion of the
5071 	 * first block.
5072 	 */
5073 	if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5074 	    (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
5075 		pmap_zero_page_area(m, frag, base - frag);
5076 
5077 	/*
5078 	 * If the ending offset is not DEV_BSIZE aligned and the
5079 	 * valid bit is clear, we have to zero out a portion of
5080 	 * the last block.
5081 	 */
5082 	endoff = base + size;
5083 	if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5084 	    (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
5085 		pmap_zero_page_area(m, endoff,
5086 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5087 
5088 	/*
5089 	 * Set valid, clear dirty bits.  If validating the entire
5090 	 * page we can safely clear the pmap modify bit.  We also
5091 	 * use this opportunity to clear the PGA_NOSYNC flag.  If a process
5092 	 * takes a write fault on a MAP_NOSYNC memory area the flag will
5093 	 * be set again.
5094 	 *
5095 	 * We set valid bits inclusive of any overlap, but we can only
5096 	 * clear dirty bits for DEV_BSIZE chunks that are fully within
5097 	 * the range.
5098 	 */
5099 	oldvalid = m->valid;
5100 	pagebits = vm_page_bits(base, size);
5101 	if (vm_page_xbusied(m))
5102 		m->valid |= pagebits;
5103 	else
5104 		vm_page_bits_set(m, &m->valid, pagebits);
5105 #if 0	/* NOT YET */
5106 	if ((frag = base & (DEV_BSIZE - 1)) != 0) {
5107 		frag = DEV_BSIZE - frag;
5108 		base += frag;
5109 		size -= frag;
5110 		if (size < 0)
5111 			size = 0;
5112 	}
5113 	pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
5114 #endif
5115 	if (base == 0 && size == PAGE_SIZE) {
5116 		/*
5117 		 * The page can only be modified within the pmap if it is
5118 		 * mapped, and it can only be mapped if it was previously
5119 		 * fully valid.
5120 		 */
5121 		if (oldvalid == VM_PAGE_BITS_ALL)
5122 			/*
5123 			 * Perform the pmap_clear_modify() first.  Otherwise,
5124 			 * a concurrent pmap operation, such as
5125 			 * pmap_protect(), could clear a modification in the
5126 			 * pmap and set the dirty field on the page before
5127 			 * pmap_clear_modify() had begun and after the dirty
5128 			 * field was cleared here.
5129 			 */
5130 			pmap_clear_modify(m);
5131 		m->dirty = 0;
5132 		vm_page_aflag_clear(m, PGA_NOSYNC);
5133 	} else if (oldvalid != VM_PAGE_BITS_ALL && vm_page_xbusied(m))
5134 		m->dirty &= ~pagebits;
5135 	else
5136 		vm_page_clear_dirty_mask(m, pagebits);
5137 }
5138 
5139 void
5140 vm_page_clear_dirty(vm_page_t m, int base, int size)
5141 {
5142 
5143 	vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
5144 }
5145 
5146 /*
5147  *	vm_page_set_invalid:
5148  *
5149  *	Invalidates DEV_BSIZE'd chunks within a page.  Both the
5150  *	valid and dirty bits for the effected areas are cleared.
5151  */
5152 void
5153 vm_page_set_invalid(vm_page_t m, int base, int size)
5154 {
5155 	vm_page_bits_t bits;
5156 	vm_object_t object;
5157 
5158 	/*
5159 	 * The object lock is required so that pages can't be mapped
5160 	 * read-only while we're in the process of invalidating them.
5161 	 */
5162 	object = m->object;
5163 	VM_OBJECT_ASSERT_WLOCKED(object);
5164 	vm_page_assert_busied(m);
5165 
5166 	if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
5167 	    size >= object->un_pager.vnp.vnp_size)
5168 		bits = VM_PAGE_BITS_ALL;
5169 	else
5170 		bits = vm_page_bits(base, size);
5171 	if (object->ref_count != 0 && vm_page_all_valid(m) && bits != 0)
5172 		pmap_remove_all(m);
5173 	KASSERT((bits == 0 && vm_page_all_valid(m)) ||
5174 	    !pmap_page_is_mapped(m),
5175 	    ("vm_page_set_invalid: page %p is mapped", m));
5176 	if (vm_page_xbusied(m)) {
5177 		m->valid &= ~bits;
5178 		m->dirty &= ~bits;
5179 	} else {
5180 		vm_page_bits_clear(m, &m->valid, bits);
5181 		vm_page_bits_clear(m, &m->dirty, bits);
5182 	}
5183 }
5184 
5185 /*
5186  *	vm_page_invalid:
5187  *
5188  *	Invalidates the entire page.  The page must be busy, unmapped, and
5189  *	the enclosing object must be locked.  The object locks protects
5190  *	against concurrent read-only pmap enter which is done without
5191  *	busy.
5192  */
5193 void
5194 vm_page_invalid(vm_page_t m)
5195 {
5196 
5197 	vm_page_assert_busied(m);
5198 	VM_OBJECT_ASSERT_LOCKED(m->object);
5199 	MPASS(!pmap_page_is_mapped(m));
5200 
5201 	if (vm_page_xbusied(m))
5202 		m->valid = 0;
5203 	else
5204 		vm_page_bits_clear(m, &m->valid, VM_PAGE_BITS_ALL);
5205 }
5206 
5207 /*
5208  * vm_page_zero_invalid()
5209  *
5210  *	The kernel assumes that the invalid portions of a page contain
5211  *	garbage, but such pages can be mapped into memory by user code.
5212  *	When this occurs, we must zero out the non-valid portions of the
5213  *	page so user code sees what it expects.
5214  *
5215  *	Pages are most often semi-valid when the end of a file is mapped
5216  *	into memory and the file's size is not page aligned.
5217  */
5218 void
5219 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
5220 {
5221 	int b;
5222 	int i;
5223 
5224 	/*
5225 	 * Scan the valid bits looking for invalid sections that
5226 	 * must be zeroed.  Invalid sub-DEV_BSIZE'd areas ( where the
5227 	 * valid bit may be set ) have already been zeroed by
5228 	 * vm_page_set_validclean().
5229 	 */
5230 	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
5231 		if (i == (PAGE_SIZE / DEV_BSIZE) ||
5232 		    (m->valid & ((vm_page_bits_t)1 << i))) {
5233 			if (i > b) {
5234 				pmap_zero_page_area(m,
5235 				    b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
5236 			}
5237 			b = i + 1;
5238 		}
5239 	}
5240 
5241 	/*
5242 	 * setvalid is TRUE when we can safely set the zero'd areas
5243 	 * as being valid.  We can do this if there are no cache consistancy
5244 	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
5245 	 */
5246 	if (setvalid)
5247 		vm_page_valid(m);
5248 }
5249 
5250 /*
5251  *	vm_page_is_valid:
5252  *
5253  *	Is (partial) page valid?  Note that the case where size == 0
5254  *	will return FALSE in the degenerate case where the page is
5255  *	entirely invalid, and TRUE otherwise.
5256  *
5257  *	Some callers envoke this routine without the busy lock held and
5258  *	handle races via higher level locks.  Typical callers should
5259  *	hold a busy lock to prevent invalidation.
5260  */
5261 int
5262 vm_page_is_valid(vm_page_t m, int base, int size)
5263 {
5264 	vm_page_bits_t bits;
5265 
5266 	bits = vm_page_bits(base, size);
5267 	return (m->valid != 0 && (m->valid & bits) == bits);
5268 }
5269 
5270 /*
5271  * Returns true if all of the specified predicates are true for the entire
5272  * (super)page and false otherwise.
5273  */
5274 bool
5275 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
5276 {
5277 	vm_object_t object;
5278 	int i, npages;
5279 
5280 	object = m->object;
5281 	if (skip_m != NULL && skip_m->object != object)
5282 		return (false);
5283 	VM_OBJECT_ASSERT_LOCKED(object);
5284 	npages = atop(pagesizes[m->psind]);
5285 
5286 	/*
5287 	 * The physically contiguous pages that make up a superpage, i.e., a
5288 	 * page with a page size index ("psind") greater than zero, will
5289 	 * occupy adjacent entries in vm_page_array[].
5290 	 */
5291 	for (i = 0; i < npages; i++) {
5292 		/* Always test object consistency, including "skip_m". */
5293 		if (m[i].object != object)
5294 			return (false);
5295 		if (&m[i] == skip_m)
5296 			continue;
5297 		if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
5298 			return (false);
5299 		if ((flags & PS_ALL_DIRTY) != 0) {
5300 			/*
5301 			 * Calling vm_page_test_dirty() or pmap_is_modified()
5302 			 * might stop this case from spuriously returning
5303 			 * "false".  However, that would require a write lock
5304 			 * on the object containing "m[i]".
5305 			 */
5306 			if (m[i].dirty != VM_PAGE_BITS_ALL)
5307 				return (false);
5308 		}
5309 		if ((flags & PS_ALL_VALID) != 0 &&
5310 		    m[i].valid != VM_PAGE_BITS_ALL)
5311 			return (false);
5312 	}
5313 	return (true);
5314 }
5315 
5316 /*
5317  * Set the page's dirty bits if the page is modified.
5318  */
5319 void
5320 vm_page_test_dirty(vm_page_t m)
5321 {
5322 
5323 	vm_page_assert_busied(m);
5324 	if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
5325 		vm_page_dirty(m);
5326 }
5327 
5328 void
5329 vm_page_valid(vm_page_t m)
5330 {
5331 
5332 	vm_page_assert_busied(m);
5333 	if (vm_page_xbusied(m))
5334 		m->valid = VM_PAGE_BITS_ALL;
5335 	else
5336 		vm_page_bits_set(m, &m->valid, VM_PAGE_BITS_ALL);
5337 }
5338 
5339 void
5340 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
5341 {
5342 
5343 	mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
5344 }
5345 
5346 void
5347 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
5348 {
5349 
5350 	mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
5351 }
5352 
5353 int
5354 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
5355 {
5356 
5357 	return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
5358 }
5359 
5360 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
5361 void
5362 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
5363 {
5364 
5365 	vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
5366 }
5367 
5368 void
5369 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
5370 {
5371 
5372 	mtx_assert_(vm_page_lockptr(m), a, file, line);
5373 }
5374 #endif
5375 
5376 #ifdef INVARIANTS
5377 void
5378 vm_page_object_busy_assert(vm_page_t m)
5379 {
5380 
5381 	/*
5382 	 * Certain of the page's fields may only be modified by the
5383 	 * holder of a page or object busy.
5384 	 */
5385 	if (m->object != NULL && !vm_page_busied(m))
5386 		VM_OBJECT_ASSERT_BUSY(m->object);
5387 }
5388 
5389 void
5390 vm_page_assert_pga_writeable(vm_page_t m, uint16_t bits)
5391 {
5392 
5393 	if ((bits & PGA_WRITEABLE) == 0)
5394 		return;
5395 
5396 	/*
5397 	 * The PGA_WRITEABLE flag can only be set if the page is
5398 	 * managed, is exclusively busied or the object is locked.
5399 	 * Currently, this flag is only set by pmap_enter().
5400 	 */
5401 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5402 	    ("PGA_WRITEABLE on unmanaged page"));
5403 	if (!vm_page_xbusied(m))
5404 		VM_OBJECT_ASSERT_BUSY(m->object);
5405 }
5406 #endif
5407 
5408 #include "opt_ddb.h"
5409 #ifdef DDB
5410 #include <sys/kernel.h>
5411 
5412 #include <ddb/ddb.h>
5413 
5414 DB_SHOW_COMMAND(page, vm_page_print_page_info)
5415 {
5416 
5417 	db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
5418 	db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
5419 	db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
5420 	db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
5421 	db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
5422 	db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
5423 	db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
5424 	db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
5425 	db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
5426 }
5427 
5428 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
5429 {
5430 	int dom;
5431 
5432 	db_printf("pq_free %d\n", vm_free_count());
5433 	for (dom = 0; dom < vm_ndomains; dom++) {
5434 		db_printf(
5435     "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
5436 		    dom,
5437 		    vm_dom[dom].vmd_page_count,
5438 		    vm_dom[dom].vmd_free_count,
5439 		    vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
5440 		    vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
5441 		    vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
5442 		    vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
5443 	}
5444 }
5445 
5446 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
5447 {
5448 	vm_page_t m;
5449 	boolean_t phys, virt;
5450 
5451 	if (!have_addr) {
5452 		db_printf("show pginfo addr\n");
5453 		return;
5454 	}
5455 
5456 	phys = strchr(modif, 'p') != NULL;
5457 	virt = strchr(modif, 'v') != NULL;
5458 	if (virt)
5459 		m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
5460 	else if (phys)
5461 		m = PHYS_TO_VM_PAGE(addr);
5462 	else
5463 		m = (vm_page_t)addr;
5464 	db_printf(
5465     "page %p obj %p pidx 0x%jx phys 0x%jx q %d ref %u\n"
5466     "  af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
5467 	    m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
5468 	    m->a.queue, m->ref_count, m->a.flags, m->oflags,
5469 	    m->flags, m->a.act_count, m->busy_lock, m->valid, m->dirty);
5470 }
5471 #endif /* DDB */
5472