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