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