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