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