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