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