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