xref: /freebsd/sys/vm/vm_page.c (revision 8c5a9161d16094d9db474fe78ddead1325246d05)
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/lock.h>
77 #include <sys/domainset.h>
78 #include <sys/kernel.h>
79 #include <sys/limits.h>
80 #include <sys/linker.h>
81 #include <sys/malloc.h>
82 #include <sys/mman.h>
83 #include <sys/msgbuf.h>
84 #include <sys/mutex.h>
85 #include <sys/proc.h>
86 #include <sys/rwlock.h>
87 #include <sys/sbuf.h>
88 #include <sys/sched.h>
89 #include <sys/smp.h>
90 #include <sys/sysctl.h>
91 #include <sys/vmmeter.h>
92 #include <sys/vnode.h>
93 
94 #include <vm/vm.h>
95 #include <vm/pmap.h>
96 #include <vm/vm_param.h>
97 #include <vm/vm_domainset.h>
98 #include <vm/vm_kern.h>
99 #include <vm/vm_map.h>
100 #include <vm/vm_object.h>
101 #include <vm/vm_page.h>
102 #include <vm/vm_pageout.h>
103 #include <vm/vm_phys.h>
104 #include <vm/vm_pagequeue.h>
105 #include <vm/vm_pager.h>
106 #include <vm/vm_radix.h>
107 #include <vm/vm_reserv.h>
108 #include <vm/vm_extern.h>
109 #include <vm/uma.h>
110 #include <vm/uma_int.h>
111 
112 #include <machine/md_var.h>
113 
114 extern int	uma_startup_count(int);
115 extern void	uma_startup(void *, int);
116 extern int	vmem_startup_count(void);
117 
118 struct vm_domain vm_dom[MAXMEMDOM];
119 
120 DPCPU_DEFINE_STATIC(struct vm_batchqueue, pqbatch[MAXMEMDOM][PQ_COUNT]);
121 
122 struct mtx_padalign __exclusive_cache_line pa_lock[PA_LOCK_COUNT];
123 
124 struct mtx_padalign __exclusive_cache_line vm_domainset_lock;
125 /* The following fields are protected by the domainset lock. */
126 domainset_t __exclusive_cache_line vm_min_domains;
127 domainset_t __exclusive_cache_line vm_severe_domains;
128 static int vm_min_waiters;
129 static int vm_severe_waiters;
130 static int vm_pageproc_waiters;
131 
132 /*
133  * bogus page -- for I/O to/from partially complete buffers,
134  * or for paging into sparsely invalid regions.
135  */
136 vm_page_t bogus_page;
137 
138 vm_page_t vm_page_array;
139 long vm_page_array_size;
140 long first_page;
141 
142 static int boot_pages;
143 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
144     &boot_pages, 0,
145     "number of pages allocated for bootstrapping the VM system");
146 
147 static int pa_tryrelock_restart;
148 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
149     &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
150 
151 static TAILQ_HEAD(, vm_page) blacklist_head;
152 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
153 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
154     CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
155 
156 static uma_zone_t fakepg_zone;
157 
158 static void vm_page_alloc_check(vm_page_t m);
159 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
160 static void vm_page_dequeue_complete(vm_page_t m);
161 static void vm_page_enqueue(vm_page_t m, uint8_t queue);
162 static void vm_page_init(void *dummy);
163 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
164     vm_pindex_t pindex, vm_page_t mpred);
165 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
166     vm_page_t mpred);
167 static int vm_page_reclaim_run(int req_class, int domain, u_long npages,
168     vm_page_t m_run, vm_paddr_t high);
169 static int vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object,
170     int req);
171 static int vm_page_import(void *arg, void **store, int cnt, int domain,
172     int flags);
173 static void vm_page_release(void *arg, void **store, int cnt);
174 
175 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
176 
177 static void
178 vm_page_init(void *dummy)
179 {
180 
181 	fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
182 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
183 	bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
184 	    VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
185 }
186 
187 /*
188  * The cache page zone is initialized later since we need to be able to allocate
189  * pages before UMA is fully initialized.
190  */
191 static void
192 vm_page_init_cache_zones(void *dummy __unused)
193 {
194 	struct vm_domain *vmd;
195 	int i;
196 
197 	for (i = 0; i < vm_ndomains; i++) {
198 		vmd = VM_DOMAIN(i);
199 		/*
200 		 * Don't allow the page cache to take up more than .25% of
201 		 * memory.
202 		 */
203 		if (vmd->vmd_page_count / 400 < 256 * mp_ncpus)
204 			continue;
205 		vmd->vmd_pgcache = uma_zcache_create("vm pgcache",
206 		    sizeof(struct vm_page), NULL, NULL, NULL, NULL,
207 		    vm_page_import, vm_page_release, vmd,
208 		    UMA_ZONE_MAXBUCKET | UMA_ZONE_VM);
209 		(void )uma_zone_set_maxcache(vmd->vmd_pgcache, 0);
210 	}
211 }
212 SYSINIT(vm_page2, SI_SUB_VM_CONF, SI_ORDER_ANY, vm_page_init_cache_zones, NULL);
213 
214 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
215 #if PAGE_SIZE == 32768
216 #ifdef CTASSERT
217 CTASSERT(sizeof(u_long) >= 8);
218 #endif
219 #endif
220 
221 /*
222  * Try to acquire a physical address lock while a pmap is locked.  If we
223  * fail to trylock we unlock and lock the pmap directly and cache the
224  * locked pa in *locked.  The caller should then restart their loop in case
225  * the virtual to physical mapping has changed.
226  */
227 int
228 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
229 {
230 	vm_paddr_t lockpa;
231 
232 	lockpa = *locked;
233 	*locked = pa;
234 	if (lockpa) {
235 		PA_LOCK_ASSERT(lockpa, MA_OWNED);
236 		if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
237 			return (0);
238 		PA_UNLOCK(lockpa);
239 	}
240 	if (PA_TRYLOCK(pa))
241 		return (0);
242 	PMAP_UNLOCK(pmap);
243 	atomic_add_int(&pa_tryrelock_restart, 1);
244 	PA_LOCK(pa);
245 	PMAP_LOCK(pmap);
246 	return (EAGAIN);
247 }
248 
249 /*
250  *	vm_set_page_size:
251  *
252  *	Sets the page size, perhaps based upon the memory
253  *	size.  Must be called before any use of page-size
254  *	dependent functions.
255  */
256 void
257 vm_set_page_size(void)
258 {
259 	if (vm_cnt.v_page_size == 0)
260 		vm_cnt.v_page_size = PAGE_SIZE;
261 	if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
262 		panic("vm_set_page_size: page size not a power of two");
263 }
264 
265 /*
266  *	vm_page_blacklist_next:
267  *
268  *	Find the next entry in the provided string of blacklist
269  *	addresses.  Entries are separated by space, comma, or newline.
270  *	If an invalid integer is encountered then the rest of the
271  *	string is skipped.  Updates the list pointer to the next
272  *	character, or NULL if the string is exhausted or invalid.
273  */
274 static vm_paddr_t
275 vm_page_blacklist_next(char **list, char *end)
276 {
277 	vm_paddr_t bad;
278 	char *cp, *pos;
279 
280 	if (list == NULL || *list == NULL)
281 		return (0);
282 	if (**list =='\0') {
283 		*list = NULL;
284 		return (0);
285 	}
286 
287 	/*
288 	 * If there's no end pointer then the buffer is coming from
289 	 * the kenv and we know it's null-terminated.
290 	 */
291 	if (end == NULL)
292 		end = *list + strlen(*list);
293 
294 	/* Ensure that strtoq() won't walk off the end */
295 	if (*end != '\0') {
296 		if (*end == '\n' || *end == ' ' || *end  == ',')
297 			*end = '\0';
298 		else {
299 			printf("Blacklist not terminated, skipping\n");
300 			*list = NULL;
301 			return (0);
302 		}
303 	}
304 
305 	for (pos = *list; *pos != '\0'; pos = cp) {
306 		bad = strtoq(pos, &cp, 0);
307 		if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
308 			if (bad == 0) {
309 				if (++cp < end)
310 					continue;
311 				else
312 					break;
313 			}
314 		} else
315 			break;
316 		if (*cp == '\0' || ++cp >= end)
317 			*list = NULL;
318 		else
319 			*list = cp;
320 		return (trunc_page(bad));
321 	}
322 	printf("Garbage in RAM blacklist, skipping\n");
323 	*list = NULL;
324 	return (0);
325 }
326 
327 bool
328 vm_page_blacklist_add(vm_paddr_t pa, bool verbose)
329 {
330 	struct vm_domain *vmd;
331 	vm_page_t m;
332 	int ret;
333 
334 	m = vm_phys_paddr_to_vm_page(pa);
335 	if (m == NULL)
336 		return (true); /* page does not exist, no failure */
337 
338 	vmd = vm_pagequeue_domain(m);
339 	vm_domain_free_lock(vmd);
340 	ret = vm_phys_unfree_page(m);
341 	vm_domain_free_unlock(vmd);
342 	if (ret != 0) {
343 		vm_domain_freecnt_inc(vmd, -1);
344 		TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
345 		if (verbose)
346 			printf("Skipping page with pa 0x%jx\n", (uintmax_t)pa);
347 	}
348 	return (ret);
349 }
350 
351 /*
352  *	vm_page_blacklist_check:
353  *
354  *	Iterate through the provided string of blacklist addresses, pulling
355  *	each entry out of the physical allocator free list and putting it
356  *	onto a list for reporting via the vm.page_blacklist sysctl.
357  */
358 static void
359 vm_page_blacklist_check(char *list, char *end)
360 {
361 	vm_paddr_t pa;
362 	char *next;
363 
364 	next = list;
365 	while (next != NULL) {
366 		if ((pa = vm_page_blacklist_next(&next, end)) == 0)
367 			continue;
368 		vm_page_blacklist_add(pa, bootverbose);
369 	}
370 }
371 
372 /*
373  *	vm_page_blacklist_load:
374  *
375  *	Search for a special module named "ram_blacklist".  It'll be a
376  *	plain text file provided by the user via the loader directive
377  *	of the same name.
378  */
379 static void
380 vm_page_blacklist_load(char **list, char **end)
381 {
382 	void *mod;
383 	u_char *ptr;
384 	u_int len;
385 
386 	mod = NULL;
387 	ptr = NULL;
388 
389 	mod = preload_search_by_type("ram_blacklist");
390 	if (mod != NULL) {
391 		ptr = preload_fetch_addr(mod);
392 		len = preload_fetch_size(mod);
393         }
394 	*list = ptr;
395 	if (ptr != NULL)
396 		*end = ptr + len;
397 	else
398 		*end = NULL;
399 	return;
400 }
401 
402 static int
403 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
404 {
405 	vm_page_t m;
406 	struct sbuf sbuf;
407 	int error, first;
408 
409 	first = 1;
410 	error = sysctl_wire_old_buffer(req, 0);
411 	if (error != 0)
412 		return (error);
413 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
414 	TAILQ_FOREACH(m, &blacklist_head, listq) {
415 		sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
416 		    (uintmax_t)m->phys_addr);
417 		first = 0;
418 	}
419 	error = sbuf_finish(&sbuf);
420 	sbuf_delete(&sbuf);
421 	return (error);
422 }
423 
424 /*
425  * Initialize a dummy page for use in scans of the specified paging queue.
426  * In principle, this function only needs to set the flag PG_MARKER.
427  * Nonetheless, it write busies and initializes the hold count to one as
428  * safety precautions.
429  */
430 static void
431 vm_page_init_marker(vm_page_t marker, int queue, uint8_t aflags)
432 {
433 
434 	bzero(marker, sizeof(*marker));
435 	marker->flags = PG_MARKER;
436 	marker->aflags = aflags;
437 	marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
438 	marker->queue = queue;
439 	marker->hold_count = 1;
440 }
441 
442 static void
443 vm_page_domain_init(int domain)
444 {
445 	struct vm_domain *vmd;
446 	struct vm_pagequeue *pq;
447 	int i;
448 
449 	vmd = VM_DOMAIN(domain);
450 	bzero(vmd, sizeof(*vmd));
451 	*__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
452 	    "vm inactive pagequeue";
453 	*__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
454 	    "vm active pagequeue";
455 	*__DECONST(char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
456 	    "vm laundry pagequeue";
457 	*__DECONST(char **, &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_name) =
458 	    "vm unswappable pagequeue";
459 	vmd->vmd_domain = domain;
460 	vmd->vmd_page_count = 0;
461 	vmd->vmd_free_count = 0;
462 	vmd->vmd_segs = 0;
463 	vmd->vmd_oom = FALSE;
464 	for (i = 0; i < PQ_COUNT; i++) {
465 		pq = &vmd->vmd_pagequeues[i];
466 		TAILQ_INIT(&pq->pq_pl);
467 		mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
468 		    MTX_DEF | MTX_DUPOK);
469 		pq->pq_pdpages = 0;
470 		vm_page_init_marker(&vmd->vmd_markers[i], i, 0);
471 	}
472 	mtx_init(&vmd->vmd_free_mtx, "vm page free queue", NULL, MTX_DEF);
473 	mtx_init(&vmd->vmd_pageout_mtx, "vm pageout lock", NULL, MTX_DEF);
474 	snprintf(vmd->vmd_name, sizeof(vmd->vmd_name), "%d", domain);
475 
476 	/*
477 	 * inacthead is used to provide FIFO ordering for LRU-bypassing
478 	 * insertions.
479 	 */
480 	vm_page_init_marker(&vmd->vmd_inacthead, PQ_INACTIVE, PGA_ENQUEUED);
481 	TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_INACTIVE].pq_pl,
482 	    &vmd->vmd_inacthead, plinks.q);
483 
484 	/*
485 	 * The clock pages are used to implement active queue scanning without
486 	 * requeues.  Scans start at clock[0], which is advanced after the scan
487 	 * ends.  When the two clock hands meet, they are reset and scanning
488 	 * resumes from the head of the queue.
489 	 */
490 	vm_page_init_marker(&vmd->vmd_clock[0], PQ_ACTIVE, PGA_ENQUEUED);
491 	vm_page_init_marker(&vmd->vmd_clock[1], PQ_ACTIVE, PGA_ENQUEUED);
492 	TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
493 	    &vmd->vmd_clock[0], plinks.q);
494 	TAILQ_INSERT_TAIL(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
495 	    &vmd->vmd_clock[1], plinks.q);
496 }
497 
498 /*
499  * Initialize a physical page in preparation for adding it to the free
500  * lists.
501  */
502 static void
503 vm_page_init_page(vm_page_t m, vm_paddr_t pa, int segind)
504 {
505 
506 	m->object = NULL;
507 	m->wire_count = 0;
508 	m->busy_lock = VPB_UNBUSIED;
509 	m->hold_count = 0;
510 	m->flags = m->aflags = 0;
511 	m->phys_addr = pa;
512 	m->queue = PQ_NONE;
513 	m->psind = 0;
514 	m->segind = segind;
515 	m->order = VM_NFREEORDER;
516 	m->pool = VM_FREEPOOL_DEFAULT;
517 	m->valid = m->dirty = 0;
518 	pmap_page_init(m);
519 }
520 
521 /*
522  *	vm_page_startup:
523  *
524  *	Initializes the resident memory module.  Allocates physical memory for
525  *	bootstrapping UMA and some data structures that are used to manage
526  *	physical pages.  Initializes these structures, and populates the free
527  *	page queues.
528  */
529 vm_offset_t
530 vm_page_startup(vm_offset_t vaddr)
531 {
532 	struct vm_phys_seg *seg;
533 	vm_page_t m;
534 	char *list, *listend;
535 	vm_offset_t mapped;
536 	vm_paddr_t end, high_avail, low_avail, new_end, page_range, size;
537 	vm_paddr_t biggestsize, last_pa, pa;
538 	u_long pagecount;
539 	int biggestone, i, segind;
540 #ifdef WITNESS
541 	int witness_size;
542 #endif
543 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
544 	long ii;
545 #endif
546 
547 	biggestsize = 0;
548 	biggestone = 0;
549 	vaddr = round_page(vaddr);
550 
551 	for (i = 0; phys_avail[i + 1]; i += 2) {
552 		phys_avail[i] = round_page(phys_avail[i]);
553 		phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
554 	}
555 	for (i = 0; phys_avail[i + 1]; i += 2) {
556 		size = phys_avail[i + 1] - phys_avail[i];
557 		if (size > biggestsize) {
558 			biggestone = i;
559 			biggestsize = size;
560 		}
561 	}
562 
563 	end = phys_avail[biggestone+1];
564 
565 	/*
566 	 * Initialize the page and queue locks.
567 	 */
568 	mtx_init(&vm_domainset_lock, "vm domainset lock", NULL, MTX_DEF);
569 	for (i = 0; i < PA_LOCK_COUNT; i++)
570 		mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
571 	for (i = 0; i < vm_ndomains; i++)
572 		vm_page_domain_init(i);
573 
574 	/*
575 	 * Allocate memory for use when boot strapping the kernel memory
576 	 * allocator.  Tell UMA how many zones we are going to create
577 	 * before going fully functional.  UMA will add its zones.
578 	 *
579 	 * VM startup zones: vmem, vmem_btag, VM OBJECT, RADIX NODE, MAP,
580 	 * KMAP ENTRY, MAP ENTRY, VMSPACE.
581 	 */
582 	boot_pages = uma_startup_count(8);
583 
584 #ifndef UMA_MD_SMALL_ALLOC
585 	/* vmem_startup() calls uma_prealloc(). */
586 	boot_pages += vmem_startup_count();
587 	/* vm_map_startup() calls uma_prealloc(). */
588 	boot_pages += howmany(MAX_KMAP,
589 	    UMA_SLAB_SPACE / sizeof(struct vm_map));
590 
591 	/*
592 	 * Before going fully functional kmem_init() does allocation
593 	 * from "KMAP ENTRY" and vmem_create() does allocation from "vmem".
594 	 */
595 	boot_pages += 2;
596 #endif
597 	/*
598 	 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
599 	 * manually fetch the value.
600 	 */
601 	TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
602 	new_end = end - (boot_pages * UMA_SLAB_SIZE);
603 	new_end = trunc_page(new_end);
604 	mapped = pmap_map(&vaddr, new_end, end,
605 	    VM_PROT_READ | VM_PROT_WRITE);
606 	bzero((void *)mapped, end - new_end);
607 	uma_startup((void *)mapped, boot_pages);
608 
609 #ifdef WITNESS
610 	witness_size = round_page(witness_startup_count());
611 	new_end -= witness_size;
612 	mapped = pmap_map(&vaddr, new_end, new_end + witness_size,
613 	    VM_PROT_READ | VM_PROT_WRITE);
614 	bzero((void *)mapped, witness_size);
615 	witness_startup((void *)mapped);
616 #endif
617 
618 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
619     defined(__i386__) || defined(__mips__) || defined(__riscv)
620 	/*
621 	 * Allocate a bitmap to indicate that a random physical page
622 	 * needs to be included in a minidump.
623 	 *
624 	 * The amd64 port needs this to indicate which direct map pages
625 	 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
626 	 *
627 	 * However, i386 still needs this workspace internally within the
628 	 * minidump code.  In theory, they are not needed on i386, but are
629 	 * included should the sf_buf code decide to use them.
630 	 */
631 	last_pa = 0;
632 	for (i = 0; dump_avail[i + 1] != 0; i += 2)
633 		if (dump_avail[i + 1] > last_pa)
634 			last_pa = dump_avail[i + 1];
635 	page_range = last_pa / PAGE_SIZE;
636 	vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
637 	new_end -= vm_page_dump_size;
638 	vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
639 	    new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
640 	bzero((void *)vm_page_dump, vm_page_dump_size);
641 #else
642 	(void)last_pa;
643 #endif
644 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
645     defined(__riscv)
646 	/*
647 	 * Include the UMA bootstrap pages, witness pages and vm_page_dump
648 	 * in a crash dump.  When pmap_map() uses the direct map, they are
649 	 * not automatically included.
650 	 */
651 	for (pa = new_end; pa < end; pa += PAGE_SIZE)
652 		dump_add_page(pa);
653 #endif
654 	phys_avail[biggestone + 1] = new_end;
655 #ifdef __amd64__
656 	/*
657 	 * Request that the physical pages underlying the message buffer be
658 	 * included in a crash dump.  Since the message buffer is accessed
659 	 * through the direct map, they are not automatically included.
660 	 */
661 	pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
662 	last_pa = pa + round_page(msgbufsize);
663 	while (pa < last_pa) {
664 		dump_add_page(pa);
665 		pa += PAGE_SIZE;
666 	}
667 #endif
668 	/*
669 	 * Compute the number of pages of memory that will be available for
670 	 * use, taking into account the overhead of a page structure per page.
671 	 * In other words, solve
672 	 *	"available physical memory" - round_page(page_range *
673 	 *	    sizeof(struct vm_page)) = page_range * PAGE_SIZE
674 	 * for page_range.
675 	 */
676 	low_avail = phys_avail[0];
677 	high_avail = phys_avail[1];
678 	for (i = 0; i < vm_phys_nsegs; i++) {
679 		if (vm_phys_segs[i].start < low_avail)
680 			low_avail = vm_phys_segs[i].start;
681 		if (vm_phys_segs[i].end > high_avail)
682 			high_avail = vm_phys_segs[i].end;
683 	}
684 	/* Skip the first chunk.  It is already accounted for. */
685 	for (i = 2; phys_avail[i + 1] != 0; i += 2) {
686 		if (phys_avail[i] < low_avail)
687 			low_avail = phys_avail[i];
688 		if (phys_avail[i + 1] > high_avail)
689 			high_avail = phys_avail[i + 1];
690 	}
691 	first_page = low_avail / PAGE_SIZE;
692 #ifdef VM_PHYSSEG_SPARSE
693 	size = 0;
694 	for (i = 0; i < vm_phys_nsegs; i++)
695 		size += vm_phys_segs[i].end - vm_phys_segs[i].start;
696 	for (i = 0; phys_avail[i + 1] != 0; i += 2)
697 		size += phys_avail[i + 1] - phys_avail[i];
698 #elif defined(VM_PHYSSEG_DENSE)
699 	size = high_avail - low_avail;
700 #else
701 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
702 #endif
703 
704 #ifdef VM_PHYSSEG_DENSE
705 	/*
706 	 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
707 	 * the overhead of a page structure per page only if vm_page_array is
708 	 * allocated from the last physical memory chunk.  Otherwise, we must
709 	 * allocate page structures representing the physical memory
710 	 * underlying vm_page_array, even though they will not be used.
711 	 */
712 	if (new_end != high_avail)
713 		page_range = size / PAGE_SIZE;
714 	else
715 #endif
716 	{
717 		page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
718 
719 		/*
720 		 * If the partial bytes remaining are large enough for
721 		 * a page (PAGE_SIZE) without a corresponding
722 		 * 'struct vm_page', then new_end will contain an
723 		 * extra page after subtracting the length of the VM
724 		 * page array.  Compensate by subtracting an extra
725 		 * page from new_end.
726 		 */
727 		if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
728 			if (new_end == high_avail)
729 				high_avail -= PAGE_SIZE;
730 			new_end -= PAGE_SIZE;
731 		}
732 	}
733 	end = new_end;
734 
735 	/*
736 	 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
737 	 * However, because this page is allocated from KVM, out-of-bounds
738 	 * accesses using the direct map will not be trapped.
739 	 */
740 	vaddr += PAGE_SIZE;
741 
742 	/*
743 	 * Allocate physical memory for the page structures, and map it.
744 	 */
745 	new_end = trunc_page(end - page_range * sizeof(struct vm_page));
746 	mapped = pmap_map(&vaddr, new_end, end,
747 	    VM_PROT_READ | VM_PROT_WRITE);
748 	vm_page_array = (vm_page_t)mapped;
749 	vm_page_array_size = page_range;
750 
751 #if VM_NRESERVLEVEL > 0
752 	/*
753 	 * Allocate physical memory for the reservation management system's
754 	 * data structures, and map it.
755 	 */
756 	if (high_avail == end)
757 		high_avail = new_end;
758 	new_end = vm_reserv_startup(&vaddr, new_end, high_avail);
759 #endif
760 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
761     defined(__riscv)
762 	/*
763 	 * Include vm_page_array and vm_reserv_array in a crash dump.
764 	 */
765 	for (pa = new_end; pa < end; pa += PAGE_SIZE)
766 		dump_add_page(pa);
767 #endif
768 	phys_avail[biggestone + 1] = new_end;
769 
770 	/*
771 	 * Add physical memory segments corresponding to the available
772 	 * physical pages.
773 	 */
774 	for (i = 0; phys_avail[i + 1] != 0; i += 2)
775 		vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
776 
777 	/*
778 	 * Initialize the physical memory allocator.
779 	 */
780 	vm_phys_init();
781 
782 	/*
783 	 * Initialize the page structures and add every available page to the
784 	 * physical memory allocator's free lists.
785 	 */
786 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
787 	for (ii = 0; ii < vm_page_array_size; ii++) {
788 		m = &vm_page_array[ii];
789 		vm_page_init_page(m, (first_page + ii) << PAGE_SHIFT, 0);
790 		m->flags = PG_FICTITIOUS;
791 	}
792 #endif
793 	vm_cnt.v_page_count = 0;
794 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
795 		seg = &vm_phys_segs[segind];
796 		for (m = seg->first_page, pa = seg->start; pa < seg->end;
797 		    m++, pa += PAGE_SIZE)
798 			vm_page_init_page(m, pa, segind);
799 
800 		/*
801 		 * Add the segment to the free lists only if it is covered by
802 		 * one of the ranges in phys_avail.  Because we've added the
803 		 * ranges to the vm_phys_segs array, we can assume that each
804 		 * segment is either entirely contained in one of the ranges,
805 		 * or doesn't overlap any of them.
806 		 */
807 		for (i = 0; phys_avail[i + 1] != 0; i += 2) {
808 			struct vm_domain *vmd;
809 
810 			if (seg->start < phys_avail[i] ||
811 			    seg->end > phys_avail[i + 1])
812 				continue;
813 
814 			m = seg->first_page;
815 			pagecount = (u_long)atop(seg->end - seg->start);
816 
817 			vmd = VM_DOMAIN(seg->domain);
818 			vm_domain_free_lock(vmd);
819 			vm_phys_enqueue_contig(m, pagecount);
820 			vm_domain_free_unlock(vmd);
821 			vm_domain_freecnt_inc(vmd, pagecount);
822 			vm_cnt.v_page_count += (u_int)pagecount;
823 
824 			vmd = VM_DOMAIN(seg->domain);
825 			vmd->vmd_page_count += (u_int)pagecount;
826 			vmd->vmd_segs |= 1UL << m->segind;
827 			break;
828 		}
829 	}
830 
831 	/*
832 	 * Remove blacklisted pages from the physical memory allocator.
833 	 */
834 	TAILQ_INIT(&blacklist_head);
835 	vm_page_blacklist_load(&list, &listend);
836 	vm_page_blacklist_check(list, listend);
837 
838 	list = kern_getenv("vm.blacklist");
839 	vm_page_blacklist_check(list, NULL);
840 
841 	freeenv(list);
842 #if VM_NRESERVLEVEL > 0
843 	/*
844 	 * Initialize the reservation management system.
845 	 */
846 	vm_reserv_init();
847 #endif
848 
849 	return (vaddr);
850 }
851 
852 void
853 vm_page_reference(vm_page_t m)
854 {
855 
856 	vm_page_aflag_set(m, PGA_REFERENCED);
857 }
858 
859 /*
860  *	vm_page_busy_downgrade:
861  *
862  *	Downgrade an exclusive busy page into a single shared busy page.
863  */
864 void
865 vm_page_busy_downgrade(vm_page_t m)
866 {
867 	u_int x;
868 	bool locked;
869 
870 	vm_page_assert_xbusied(m);
871 	locked = mtx_owned(vm_page_lockptr(m));
872 
873 	for (;;) {
874 		x = m->busy_lock;
875 		x &= VPB_BIT_WAITERS;
876 		if (x != 0 && !locked)
877 			vm_page_lock(m);
878 		if (atomic_cmpset_rel_int(&m->busy_lock,
879 		    VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1)))
880 			break;
881 		if (x != 0 && !locked)
882 			vm_page_unlock(m);
883 	}
884 	if (x != 0) {
885 		wakeup(m);
886 		if (!locked)
887 			vm_page_unlock(m);
888 	}
889 }
890 
891 /*
892  *	vm_page_sbusied:
893  *
894  *	Return a positive value if the page is shared busied, 0 otherwise.
895  */
896 int
897 vm_page_sbusied(vm_page_t m)
898 {
899 	u_int x;
900 
901 	x = m->busy_lock;
902 	return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
903 }
904 
905 /*
906  *	vm_page_sunbusy:
907  *
908  *	Shared unbusy a page.
909  */
910 void
911 vm_page_sunbusy(vm_page_t m)
912 {
913 	u_int x;
914 
915 	vm_page_lock_assert(m, MA_NOTOWNED);
916 	vm_page_assert_sbusied(m);
917 
918 	for (;;) {
919 		x = m->busy_lock;
920 		if (VPB_SHARERS(x) > 1) {
921 			if (atomic_cmpset_int(&m->busy_lock, x,
922 			    x - VPB_ONE_SHARER))
923 				break;
924 			continue;
925 		}
926 		if ((x & VPB_BIT_WAITERS) == 0) {
927 			KASSERT(x == VPB_SHARERS_WORD(1),
928 			    ("vm_page_sunbusy: invalid lock state"));
929 			if (atomic_cmpset_int(&m->busy_lock,
930 			    VPB_SHARERS_WORD(1), VPB_UNBUSIED))
931 				break;
932 			continue;
933 		}
934 		KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
935 		    ("vm_page_sunbusy: invalid lock state for waiters"));
936 
937 		vm_page_lock(m);
938 		if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
939 			vm_page_unlock(m);
940 			continue;
941 		}
942 		wakeup(m);
943 		vm_page_unlock(m);
944 		break;
945 	}
946 }
947 
948 /*
949  *	vm_page_busy_sleep:
950  *
951  *	Sleep and release the page lock, using the page pointer as wchan.
952  *	This is used to implement the hard-path of busying mechanism.
953  *
954  *	The given page must be locked.
955  *
956  *	If nonshared is true, sleep only if the page is xbusy.
957  */
958 void
959 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
960 {
961 	u_int x;
962 
963 	vm_page_assert_locked(m);
964 
965 	x = m->busy_lock;
966 	if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
967 	    ((x & VPB_BIT_WAITERS) == 0 &&
968 	    !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
969 		vm_page_unlock(m);
970 		return;
971 	}
972 	msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
973 }
974 
975 /*
976  *	vm_page_trysbusy:
977  *
978  *	Try to shared busy a page.
979  *	If the operation succeeds 1 is returned otherwise 0.
980  *	The operation never sleeps.
981  */
982 int
983 vm_page_trysbusy(vm_page_t m)
984 {
985 	u_int x;
986 
987 	for (;;) {
988 		x = m->busy_lock;
989 		if ((x & VPB_BIT_SHARED) == 0)
990 			return (0);
991 		if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
992 			return (1);
993 	}
994 }
995 
996 static void
997 vm_page_xunbusy_locked(vm_page_t m)
998 {
999 
1000 	vm_page_assert_xbusied(m);
1001 	vm_page_assert_locked(m);
1002 
1003 	atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1004 	/* There is a waiter, do wakeup() instead of vm_page_flash(). */
1005 	wakeup(m);
1006 }
1007 
1008 void
1009 vm_page_xunbusy_maybelocked(vm_page_t m)
1010 {
1011 	bool lockacq;
1012 
1013 	vm_page_assert_xbusied(m);
1014 
1015 	/*
1016 	 * Fast path for unbusy.  If it succeeds, we know that there
1017 	 * are no waiters, so we do not need a wakeup.
1018 	 */
1019 	if (atomic_cmpset_rel_int(&m->busy_lock, VPB_SINGLE_EXCLUSIVER,
1020 	    VPB_UNBUSIED))
1021 		return;
1022 
1023 	lockacq = !mtx_owned(vm_page_lockptr(m));
1024 	if (lockacq)
1025 		vm_page_lock(m);
1026 	vm_page_xunbusy_locked(m);
1027 	if (lockacq)
1028 		vm_page_unlock(m);
1029 }
1030 
1031 /*
1032  *	vm_page_xunbusy_hard:
1033  *
1034  *	Called after the first try the exclusive unbusy of a page failed.
1035  *	It is assumed that the waiters bit is on.
1036  */
1037 void
1038 vm_page_xunbusy_hard(vm_page_t m)
1039 {
1040 
1041 	vm_page_assert_xbusied(m);
1042 
1043 	vm_page_lock(m);
1044 	vm_page_xunbusy_locked(m);
1045 	vm_page_unlock(m);
1046 }
1047 
1048 /*
1049  *	vm_page_flash:
1050  *
1051  *	Wakeup anyone waiting for the page.
1052  *	The ownership bits do not change.
1053  *
1054  *	The given page must be locked.
1055  */
1056 void
1057 vm_page_flash(vm_page_t m)
1058 {
1059 	u_int x;
1060 
1061 	vm_page_lock_assert(m, MA_OWNED);
1062 
1063 	for (;;) {
1064 		x = m->busy_lock;
1065 		if ((x & VPB_BIT_WAITERS) == 0)
1066 			return;
1067 		if (atomic_cmpset_int(&m->busy_lock, x,
1068 		    x & (~VPB_BIT_WAITERS)))
1069 			break;
1070 	}
1071 	wakeup(m);
1072 }
1073 
1074 /*
1075  * Avoid releasing and reacquiring the same page lock.
1076  */
1077 void
1078 vm_page_change_lock(vm_page_t m, struct mtx **mtx)
1079 {
1080 	struct mtx *mtx1;
1081 
1082 	mtx1 = vm_page_lockptr(m);
1083 	if (*mtx == mtx1)
1084 		return;
1085 	if (*mtx != NULL)
1086 		mtx_unlock(*mtx);
1087 	*mtx = mtx1;
1088 	mtx_lock(mtx1);
1089 }
1090 
1091 /*
1092  * Keep page from being freed by the page daemon
1093  * much of the same effect as wiring, except much lower
1094  * overhead and should be used only for *very* temporary
1095  * holding ("wiring").
1096  */
1097 void
1098 vm_page_hold(vm_page_t mem)
1099 {
1100 
1101 	vm_page_lock_assert(mem, MA_OWNED);
1102         mem->hold_count++;
1103 }
1104 
1105 void
1106 vm_page_unhold(vm_page_t mem)
1107 {
1108 
1109 	vm_page_lock_assert(mem, MA_OWNED);
1110 	KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
1111 	--mem->hold_count;
1112 	if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
1113 		vm_page_free_toq(mem);
1114 }
1115 
1116 /*
1117  *	vm_page_unhold_pages:
1118  *
1119  *	Unhold each of the pages that is referenced by the given array.
1120  */
1121 void
1122 vm_page_unhold_pages(vm_page_t *ma, int count)
1123 {
1124 	struct mtx *mtx;
1125 
1126 	mtx = NULL;
1127 	for (; count != 0; count--) {
1128 		vm_page_change_lock(*ma, &mtx);
1129 		vm_page_unhold(*ma);
1130 		ma++;
1131 	}
1132 	if (mtx != NULL)
1133 		mtx_unlock(mtx);
1134 }
1135 
1136 vm_page_t
1137 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1138 {
1139 	vm_page_t m;
1140 
1141 #ifdef VM_PHYSSEG_SPARSE
1142 	m = vm_phys_paddr_to_vm_page(pa);
1143 	if (m == NULL)
1144 		m = vm_phys_fictitious_to_vm_page(pa);
1145 	return (m);
1146 #elif defined(VM_PHYSSEG_DENSE)
1147 	long pi;
1148 
1149 	pi = atop(pa);
1150 	if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1151 		m = &vm_page_array[pi - first_page];
1152 		return (m);
1153 	}
1154 	return (vm_phys_fictitious_to_vm_page(pa));
1155 #else
1156 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1157 #endif
1158 }
1159 
1160 /*
1161  *	vm_page_getfake:
1162  *
1163  *	Create a fictitious page with the specified physical address and
1164  *	memory attribute.  The memory attribute is the only the machine-
1165  *	dependent aspect of a fictitious page that must be initialized.
1166  */
1167 vm_page_t
1168 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1169 {
1170 	vm_page_t m;
1171 
1172 	m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1173 	vm_page_initfake(m, paddr, memattr);
1174 	return (m);
1175 }
1176 
1177 void
1178 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1179 {
1180 
1181 	if ((m->flags & PG_FICTITIOUS) != 0) {
1182 		/*
1183 		 * The page's memattr might have changed since the
1184 		 * previous initialization.  Update the pmap to the
1185 		 * new memattr.
1186 		 */
1187 		goto memattr;
1188 	}
1189 	m->phys_addr = paddr;
1190 	m->queue = PQ_NONE;
1191 	/* Fictitious pages don't use "segind". */
1192 	m->flags = PG_FICTITIOUS;
1193 	/* Fictitious pages don't use "order" or "pool". */
1194 	m->oflags = VPO_UNMANAGED;
1195 	m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1196 	m->wire_count = 1;
1197 	pmap_page_init(m);
1198 memattr:
1199 	pmap_page_set_memattr(m, memattr);
1200 }
1201 
1202 /*
1203  *	vm_page_putfake:
1204  *
1205  *	Release a fictitious page.
1206  */
1207 void
1208 vm_page_putfake(vm_page_t m)
1209 {
1210 
1211 	KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1212 	KASSERT((m->flags & PG_FICTITIOUS) != 0,
1213 	    ("vm_page_putfake: bad page %p", m));
1214 	uma_zfree(fakepg_zone, m);
1215 }
1216 
1217 /*
1218  *	vm_page_updatefake:
1219  *
1220  *	Update the given fictitious page to the specified physical address and
1221  *	memory attribute.
1222  */
1223 void
1224 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1225 {
1226 
1227 	KASSERT((m->flags & PG_FICTITIOUS) != 0,
1228 	    ("vm_page_updatefake: bad page %p", m));
1229 	m->phys_addr = paddr;
1230 	pmap_page_set_memattr(m, memattr);
1231 }
1232 
1233 /*
1234  *	vm_page_free:
1235  *
1236  *	Free a page.
1237  */
1238 void
1239 vm_page_free(vm_page_t m)
1240 {
1241 
1242 	m->flags &= ~PG_ZERO;
1243 	vm_page_free_toq(m);
1244 }
1245 
1246 /*
1247  *	vm_page_free_zero:
1248  *
1249  *	Free a page to the zerod-pages queue
1250  */
1251 void
1252 vm_page_free_zero(vm_page_t m)
1253 {
1254 
1255 	m->flags |= PG_ZERO;
1256 	vm_page_free_toq(m);
1257 }
1258 
1259 /*
1260  * Unbusy and handle the page queueing for a page from a getpages request that
1261  * was optionally read ahead or behind.
1262  */
1263 void
1264 vm_page_readahead_finish(vm_page_t m)
1265 {
1266 
1267 	/* We shouldn't put invalid pages on queues. */
1268 	KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
1269 
1270 	/*
1271 	 * Since the page is not the actually needed one, whether it should
1272 	 * be activated or deactivated is not obvious.  Empirical results
1273 	 * have shown that deactivating the page is usually the best choice,
1274 	 * unless the page is wanted by another thread.
1275 	 */
1276 	vm_page_lock(m);
1277 	if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1278 		vm_page_activate(m);
1279 	else
1280 		vm_page_deactivate(m);
1281 	vm_page_unlock(m);
1282 	vm_page_xunbusy(m);
1283 }
1284 
1285 /*
1286  *	vm_page_sleep_if_busy:
1287  *
1288  *	Sleep and release the page queues lock if the page is busied.
1289  *	Returns TRUE if the thread slept.
1290  *
1291  *	The given page must be unlocked and object containing it must
1292  *	be locked.
1293  */
1294 int
1295 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1296 {
1297 	vm_object_t obj;
1298 
1299 	vm_page_lock_assert(m, MA_NOTOWNED);
1300 	VM_OBJECT_ASSERT_WLOCKED(m->object);
1301 
1302 	if (vm_page_busied(m)) {
1303 		/*
1304 		 * The page-specific object must be cached because page
1305 		 * identity can change during the sleep, causing the
1306 		 * re-lock of a different object.
1307 		 * It is assumed that a reference to the object is already
1308 		 * held by the callers.
1309 		 */
1310 		obj = m->object;
1311 		vm_page_lock(m);
1312 		VM_OBJECT_WUNLOCK(obj);
1313 		vm_page_busy_sleep(m, msg, false);
1314 		VM_OBJECT_WLOCK(obj);
1315 		return (TRUE);
1316 	}
1317 	return (FALSE);
1318 }
1319 
1320 /*
1321  *	vm_page_dirty_KBI:		[ internal use only ]
1322  *
1323  *	Set all bits in the page's dirty field.
1324  *
1325  *	The object containing the specified page must be locked if the
1326  *	call is made from the machine-independent layer.
1327  *
1328  *	See vm_page_clear_dirty_mask().
1329  *
1330  *	This function should only be called by vm_page_dirty().
1331  */
1332 void
1333 vm_page_dirty_KBI(vm_page_t m)
1334 {
1335 
1336 	/* Refer to this operation by its public name. */
1337 	KASSERT(m->valid == VM_PAGE_BITS_ALL,
1338 	    ("vm_page_dirty: page is invalid!"));
1339 	m->dirty = VM_PAGE_BITS_ALL;
1340 }
1341 
1342 /*
1343  *	vm_page_insert:		[ internal use only ]
1344  *
1345  *	Inserts the given mem entry into the object and object list.
1346  *
1347  *	The object must be locked.
1348  */
1349 int
1350 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1351 {
1352 	vm_page_t mpred;
1353 
1354 	VM_OBJECT_ASSERT_WLOCKED(object);
1355 	mpred = vm_radix_lookup_le(&object->rtree, pindex);
1356 	return (vm_page_insert_after(m, object, pindex, mpred));
1357 }
1358 
1359 /*
1360  *	vm_page_insert_after:
1361  *
1362  *	Inserts the page "m" into the specified object at offset "pindex".
1363  *
1364  *	The page "mpred" must immediately precede the offset "pindex" within
1365  *	the specified object.
1366  *
1367  *	The object must be locked.
1368  */
1369 static int
1370 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1371     vm_page_t mpred)
1372 {
1373 	vm_page_t msucc;
1374 
1375 	VM_OBJECT_ASSERT_WLOCKED(object);
1376 	KASSERT(m->object == NULL,
1377 	    ("vm_page_insert_after: page already inserted"));
1378 	if (mpred != NULL) {
1379 		KASSERT(mpred->object == object,
1380 		    ("vm_page_insert_after: object doesn't contain mpred"));
1381 		KASSERT(mpred->pindex < pindex,
1382 		    ("vm_page_insert_after: mpred doesn't precede pindex"));
1383 		msucc = TAILQ_NEXT(mpred, listq);
1384 	} else
1385 		msucc = TAILQ_FIRST(&object->memq);
1386 	if (msucc != NULL)
1387 		KASSERT(msucc->pindex > pindex,
1388 		    ("vm_page_insert_after: msucc doesn't succeed pindex"));
1389 
1390 	/*
1391 	 * Record the object/offset pair in this page
1392 	 */
1393 	m->object = object;
1394 	m->pindex = pindex;
1395 
1396 	/*
1397 	 * Now link into the object's ordered list of backed pages.
1398 	 */
1399 	if (vm_radix_insert(&object->rtree, m)) {
1400 		m->object = NULL;
1401 		m->pindex = 0;
1402 		return (1);
1403 	}
1404 	vm_page_insert_radixdone(m, object, mpred);
1405 	return (0);
1406 }
1407 
1408 /*
1409  *	vm_page_insert_radixdone:
1410  *
1411  *	Complete page "m" insertion into the specified object after the
1412  *	radix trie hooking.
1413  *
1414  *	The page "mpred" must precede the offset "m->pindex" within the
1415  *	specified object.
1416  *
1417  *	The object must be locked.
1418  */
1419 static void
1420 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1421 {
1422 
1423 	VM_OBJECT_ASSERT_WLOCKED(object);
1424 	KASSERT(object != NULL && m->object == object,
1425 	    ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1426 	if (mpred != NULL) {
1427 		KASSERT(mpred->object == object,
1428 		    ("vm_page_insert_after: object doesn't contain mpred"));
1429 		KASSERT(mpred->pindex < m->pindex,
1430 		    ("vm_page_insert_after: mpred doesn't precede pindex"));
1431 	}
1432 
1433 	if (mpred != NULL)
1434 		TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1435 	else
1436 		TAILQ_INSERT_HEAD(&object->memq, m, listq);
1437 
1438 	/*
1439 	 * Show that the object has one more resident page.
1440 	 */
1441 	object->resident_page_count++;
1442 
1443 	/*
1444 	 * Hold the vnode until the last page is released.
1445 	 */
1446 	if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1447 		vhold(object->handle);
1448 
1449 	/*
1450 	 * Since we are inserting a new and possibly dirty page,
1451 	 * update the object's OBJ_MIGHTBEDIRTY flag.
1452 	 */
1453 	if (pmap_page_is_write_mapped(m))
1454 		vm_object_set_writeable_dirty(object);
1455 }
1456 
1457 /*
1458  *	vm_page_remove:
1459  *
1460  *	Removes the specified page from its containing object, but does not
1461  *	invalidate any backing storage.  Return true if the page may be safely
1462  *	freed and false otherwise.
1463  *
1464  *	The object must be locked.  The page must be locked if it is managed.
1465  */
1466 bool
1467 vm_page_remove(vm_page_t m)
1468 {
1469 	vm_object_t object;
1470 	vm_page_t mrem;
1471 
1472 	object = m->object;
1473 
1474 	if ((m->oflags & VPO_UNMANAGED) == 0)
1475 		vm_page_assert_locked(m);
1476 	VM_OBJECT_ASSERT_WLOCKED(object);
1477 	if (vm_page_xbusied(m))
1478 		vm_page_xunbusy_maybelocked(m);
1479 	mrem = vm_radix_remove(&object->rtree, m->pindex);
1480 	KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1481 
1482 	/*
1483 	 * Now remove from the object's list of backed pages.
1484 	 */
1485 	TAILQ_REMOVE(&object->memq, m, listq);
1486 
1487 	/*
1488 	 * And show that the object has one fewer resident page.
1489 	 */
1490 	object->resident_page_count--;
1491 
1492 	/*
1493 	 * The vnode may now be recycled.
1494 	 */
1495 	if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1496 		vdrop(object->handle);
1497 
1498 	m->object = NULL;
1499 	return (!vm_page_wired(m));
1500 }
1501 
1502 /*
1503  *	vm_page_lookup:
1504  *
1505  *	Returns the page associated with the object/offset
1506  *	pair specified; if none is found, NULL is returned.
1507  *
1508  *	The object must be locked.
1509  */
1510 vm_page_t
1511 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1512 {
1513 
1514 	VM_OBJECT_ASSERT_LOCKED(object);
1515 	return (vm_radix_lookup(&object->rtree, pindex));
1516 }
1517 
1518 /*
1519  *	vm_page_find_least:
1520  *
1521  *	Returns the page associated with the object with least pindex
1522  *	greater than or equal to the parameter pindex, or NULL.
1523  *
1524  *	The object must be locked.
1525  */
1526 vm_page_t
1527 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1528 {
1529 	vm_page_t m;
1530 
1531 	VM_OBJECT_ASSERT_LOCKED(object);
1532 	if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1533 		m = vm_radix_lookup_ge(&object->rtree, pindex);
1534 	return (m);
1535 }
1536 
1537 /*
1538  * Returns the given page's successor (by pindex) within the object if it is
1539  * resident; if none is found, NULL is returned.
1540  *
1541  * The object must be locked.
1542  */
1543 vm_page_t
1544 vm_page_next(vm_page_t m)
1545 {
1546 	vm_page_t next;
1547 
1548 	VM_OBJECT_ASSERT_LOCKED(m->object);
1549 	if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1550 		MPASS(next->object == m->object);
1551 		if (next->pindex != m->pindex + 1)
1552 			next = NULL;
1553 	}
1554 	return (next);
1555 }
1556 
1557 /*
1558  * Returns the given page's predecessor (by pindex) within the object if it is
1559  * resident; if none is found, NULL is returned.
1560  *
1561  * The object must be locked.
1562  */
1563 vm_page_t
1564 vm_page_prev(vm_page_t m)
1565 {
1566 	vm_page_t prev;
1567 
1568 	VM_OBJECT_ASSERT_LOCKED(m->object);
1569 	if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1570 		MPASS(prev->object == m->object);
1571 		if (prev->pindex != m->pindex - 1)
1572 			prev = NULL;
1573 	}
1574 	return (prev);
1575 }
1576 
1577 /*
1578  * Uses the page mnew as a replacement for an existing page at index
1579  * pindex which must be already present in the object.
1580  *
1581  * The existing page must not be on a paging queue.
1582  */
1583 vm_page_t
1584 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1585 {
1586 	vm_page_t mold;
1587 
1588 	VM_OBJECT_ASSERT_WLOCKED(object);
1589 	KASSERT(mnew->object == NULL,
1590 	    ("vm_page_replace: page %p already in object", mnew));
1591 	KASSERT(mnew->queue == PQ_NONE,
1592 	    ("vm_page_replace: new page %p is on a paging queue", mnew));
1593 
1594 	/*
1595 	 * This function mostly follows vm_page_insert() and
1596 	 * vm_page_remove() without the radix, object count and vnode
1597 	 * dance.  Double check such functions for more comments.
1598 	 */
1599 
1600 	mnew->object = object;
1601 	mnew->pindex = pindex;
1602 	mold = vm_radix_replace(&object->rtree, mnew);
1603 	KASSERT(mold->queue == PQ_NONE,
1604 	    ("vm_page_replace: old page %p is on a paging queue", mold));
1605 
1606 	/* Keep the resident page list in sorted order. */
1607 	TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1608 	TAILQ_REMOVE(&object->memq, mold, listq);
1609 
1610 	mold->object = NULL;
1611 	vm_page_xunbusy_maybelocked(mold);
1612 
1613 	/*
1614 	 * The object's resident_page_count does not change because we have
1615 	 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1616 	 */
1617 	if (pmap_page_is_write_mapped(mnew))
1618 		vm_object_set_writeable_dirty(object);
1619 	return (mold);
1620 }
1621 
1622 /*
1623  *	vm_page_rename:
1624  *
1625  *	Move the given memory entry from its
1626  *	current object to the specified target object/offset.
1627  *
1628  *	Note: swap associated with the page must be invalidated by the move.  We
1629  *	      have to do this for several reasons:  (1) we aren't freeing the
1630  *	      page, (2) we are dirtying the page, (3) the VM system is probably
1631  *	      moving the page from object A to B, and will then later move
1632  *	      the backing store from A to B and we can't have a conflict.
1633  *
1634  *	Note: we *always* dirty the page.  It is necessary both for the
1635  *	      fact that we moved it, and because we may be invalidating
1636  *	      swap.
1637  *
1638  *	The objects must be locked.
1639  */
1640 int
1641 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1642 {
1643 	vm_page_t mpred;
1644 	vm_pindex_t opidx;
1645 
1646 	VM_OBJECT_ASSERT_WLOCKED(new_object);
1647 
1648 	mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1649 	KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1650 	    ("vm_page_rename: pindex already renamed"));
1651 
1652 	/*
1653 	 * Create a custom version of vm_page_insert() which does not depend
1654 	 * by m_prev and can cheat on the implementation aspects of the
1655 	 * function.
1656 	 */
1657 	opidx = m->pindex;
1658 	m->pindex = new_pindex;
1659 	if (vm_radix_insert(&new_object->rtree, m)) {
1660 		m->pindex = opidx;
1661 		return (1);
1662 	}
1663 
1664 	/*
1665 	 * The operation cannot fail anymore.  The removal must happen before
1666 	 * the listq iterator is tainted.
1667 	 */
1668 	m->pindex = opidx;
1669 	vm_page_lock(m);
1670 	(void)vm_page_remove(m);
1671 
1672 	/* Return back to the new pindex to complete vm_page_insert(). */
1673 	m->pindex = new_pindex;
1674 	m->object = new_object;
1675 	vm_page_unlock(m);
1676 	vm_page_insert_radixdone(m, new_object, mpred);
1677 	vm_page_dirty(m);
1678 	return (0);
1679 }
1680 
1681 /*
1682  *	vm_page_alloc:
1683  *
1684  *	Allocate and return a page that is associated with the specified
1685  *	object and offset pair.  By default, this page is exclusive busied.
1686  *
1687  *	The caller must always specify an allocation class.
1688  *
1689  *	allocation classes:
1690  *	VM_ALLOC_NORMAL		normal process request
1691  *	VM_ALLOC_SYSTEM		system *really* needs a page
1692  *	VM_ALLOC_INTERRUPT	interrupt time request
1693  *
1694  *	optional allocation flags:
1695  *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
1696  *				intends to allocate
1697  *	VM_ALLOC_NOBUSY		do not exclusive busy the page
1698  *	VM_ALLOC_NODUMP		do not include the page in a kernel core dump
1699  *	VM_ALLOC_NOOBJ		page is not associated with an object and
1700  *				should not be exclusive busy
1701  *	VM_ALLOC_SBUSY		shared busy the allocated page
1702  *	VM_ALLOC_WIRED		wire the allocated page
1703  *	VM_ALLOC_ZERO		prefer a zeroed page
1704  */
1705 vm_page_t
1706 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1707 {
1708 
1709 	return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1710 	    vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1711 }
1712 
1713 vm_page_t
1714 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1715     int req)
1716 {
1717 
1718 	return (vm_page_alloc_domain_after(object, pindex, domain, req,
1719 	    object != NULL ? vm_radix_lookup_le(&object->rtree, pindex) :
1720 	    NULL));
1721 }
1722 
1723 /*
1724  * Allocate a page in the specified object with the given page index.  To
1725  * optimize insertion of the page into the object, the caller must also specifiy
1726  * the resident page in the object with largest index smaller than the given
1727  * page index, or NULL if no such page exists.
1728  */
1729 vm_page_t
1730 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1731     int req, vm_page_t mpred)
1732 {
1733 	struct vm_domainset_iter di;
1734 	vm_page_t m;
1735 	int domain;
1736 
1737 	vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1738 	do {
1739 		m = vm_page_alloc_domain_after(object, pindex, domain, req,
1740 		    mpred);
1741 		if (m != NULL)
1742 			break;
1743 	} while (vm_domainset_iter_page(&di, object, &domain) == 0);
1744 
1745 	return (m);
1746 }
1747 
1748 /*
1749  * Returns true if the number of free pages exceeds the minimum
1750  * for the request class and false otherwise.
1751  */
1752 int
1753 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
1754 {
1755 	u_int limit, old, new;
1756 
1757 	req = req & VM_ALLOC_CLASS_MASK;
1758 
1759 	/*
1760 	 * The page daemon is allowed to dig deeper into the free page list.
1761 	 */
1762 	if (curproc == pageproc && req != VM_ALLOC_INTERRUPT)
1763 		req = VM_ALLOC_SYSTEM;
1764 	if (req == VM_ALLOC_INTERRUPT)
1765 		limit = 0;
1766 	else if (req == VM_ALLOC_SYSTEM)
1767 		limit = vmd->vmd_interrupt_free_min;
1768 	else
1769 		limit = vmd->vmd_free_reserved;
1770 
1771 	/*
1772 	 * Attempt to reserve the pages.  Fail if we're below the limit.
1773 	 */
1774 	limit += npages;
1775 	old = vmd->vmd_free_count;
1776 	do {
1777 		if (old < limit)
1778 			return (0);
1779 		new = old - npages;
1780 	} while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
1781 
1782 	/* Wake the page daemon if we've crossed the threshold. */
1783 	if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
1784 		pagedaemon_wakeup(vmd->vmd_domain);
1785 
1786 	/* Only update bitsets on transitions. */
1787 	if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
1788 	    (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
1789 		vm_domain_set(vmd);
1790 
1791 	return (1);
1792 }
1793 
1794 vm_page_t
1795 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
1796     int req, vm_page_t mpred)
1797 {
1798 	struct vm_domain *vmd;
1799 	vm_page_t m;
1800 	int flags;
1801 
1802 	KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1803 	    (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1804 	    ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1805 	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1806 	    ("inconsistent object(%p)/req(%x)", object, req));
1807 	KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1808 	    ("Can't sleep and retry object insertion."));
1809 	KASSERT(mpred == NULL || mpred->pindex < pindex,
1810 	    ("mpred %p doesn't precede pindex 0x%jx", mpred,
1811 	    (uintmax_t)pindex));
1812 	if (object != NULL)
1813 		VM_OBJECT_ASSERT_WLOCKED(object);
1814 
1815 	flags = 0;
1816 	m = NULL;
1817 again:
1818 #if VM_NRESERVLEVEL > 0
1819 	/*
1820 	 * Can we allocate the page from a reservation?
1821 	 */
1822 	if (vm_object_reserv(object) &&
1823 	    (m = vm_reserv_alloc_page(object, pindex, domain, req, mpred)) !=
1824 	    NULL) {
1825 		domain = vm_phys_domain(m);
1826 		vmd = VM_DOMAIN(domain);
1827 		goto found;
1828 	}
1829 #endif
1830 	vmd = VM_DOMAIN(domain);
1831 	if (object != NULL && vmd->vmd_pgcache != NULL) {
1832 		m = uma_zalloc(vmd->vmd_pgcache, M_NOWAIT);
1833 		if (m != NULL) {
1834 			flags |= PG_PCPU_CACHE;
1835 			goto found;
1836 		}
1837 	}
1838 	if (vm_domain_allocate(vmd, req, 1)) {
1839 		/*
1840 		 * If not, allocate it from the free page queues.
1841 		 */
1842 		vm_domain_free_lock(vmd);
1843 		m = vm_phys_alloc_pages(domain, object != NULL ?
1844 		    VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1845 		vm_domain_free_unlock(vmd);
1846 		if (m == NULL) {
1847 			vm_domain_freecnt_inc(vmd, 1);
1848 #if VM_NRESERVLEVEL > 0
1849 			if (vm_reserv_reclaim_inactive(domain))
1850 				goto again;
1851 #endif
1852 		}
1853 	}
1854 	if (m == NULL) {
1855 		/*
1856 		 * Not allocatable, give up.
1857 		 */
1858 		if (vm_domain_alloc_fail(vmd, object, req))
1859 			goto again;
1860 		return (NULL);
1861 	}
1862 
1863 	/*
1864 	 * At this point we had better have found a good page.
1865 	 */
1866 found:
1867 	vm_page_dequeue(m);
1868 	vm_page_alloc_check(m);
1869 
1870 	/*
1871 	 * Initialize the page.  Only the PG_ZERO flag is inherited.
1872 	 */
1873 	if ((req & VM_ALLOC_ZERO) != 0)
1874 		flags |= (m->flags & PG_ZERO);
1875 	if ((req & VM_ALLOC_NODUMP) != 0)
1876 		flags |= PG_NODUMP;
1877 	m->flags = flags;
1878 	m->aflags = 0;
1879 	m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1880 	    VPO_UNMANAGED : 0;
1881 	m->busy_lock = VPB_UNBUSIED;
1882 	if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1883 		m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1884 	if ((req & VM_ALLOC_SBUSY) != 0)
1885 		m->busy_lock = VPB_SHARERS_WORD(1);
1886 	if (req & VM_ALLOC_WIRED) {
1887 		/*
1888 		 * The page lock is not required for wiring a page until that
1889 		 * page is inserted into the object.
1890 		 */
1891 		vm_wire_add(1);
1892 		m->wire_count = 1;
1893 	}
1894 	m->act_count = 0;
1895 
1896 	if (object != NULL) {
1897 		if (vm_page_insert_after(m, object, pindex, mpred)) {
1898 			if (req & VM_ALLOC_WIRED) {
1899 				vm_wire_sub(1);
1900 				m->wire_count = 0;
1901 			}
1902 			KASSERT(m->object == NULL, ("page %p has object", m));
1903 			m->oflags = VPO_UNMANAGED;
1904 			m->busy_lock = VPB_UNBUSIED;
1905 			/* Don't change PG_ZERO. */
1906 			vm_page_free_toq(m);
1907 			if (req & VM_ALLOC_WAITFAIL) {
1908 				VM_OBJECT_WUNLOCK(object);
1909 				vm_radix_wait();
1910 				VM_OBJECT_WLOCK(object);
1911 			}
1912 			return (NULL);
1913 		}
1914 
1915 		/* Ignore device objects; the pager sets "memattr" for them. */
1916 		if (object->memattr != VM_MEMATTR_DEFAULT &&
1917 		    (object->flags & OBJ_FICTITIOUS) == 0)
1918 			pmap_page_set_memattr(m, object->memattr);
1919 	} else
1920 		m->pindex = pindex;
1921 
1922 	return (m);
1923 }
1924 
1925 /*
1926  *	vm_page_alloc_contig:
1927  *
1928  *	Allocate a contiguous set of physical pages of the given size "npages"
1929  *	from the free lists.  All of the physical pages must be at or above
1930  *	the given physical address "low" and below the given physical address
1931  *	"high".  The given value "alignment" determines the alignment of the
1932  *	first physical page in the set.  If the given value "boundary" is
1933  *	non-zero, then the set of physical pages cannot cross any physical
1934  *	address boundary that is a multiple of that value.  Both "alignment"
1935  *	and "boundary" must be a power of two.
1936  *
1937  *	If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1938  *	then the memory attribute setting for the physical pages is configured
1939  *	to the object's memory attribute setting.  Otherwise, the memory
1940  *	attribute setting for the physical pages is configured to "memattr",
1941  *	overriding the object's memory attribute setting.  However, if the
1942  *	object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1943  *	memory attribute setting for the physical pages cannot be configured
1944  *	to VM_MEMATTR_DEFAULT.
1945  *
1946  *	The specified object may not contain fictitious pages.
1947  *
1948  *	The caller must always specify an allocation class.
1949  *
1950  *	allocation classes:
1951  *	VM_ALLOC_NORMAL		normal process request
1952  *	VM_ALLOC_SYSTEM		system *really* needs a page
1953  *	VM_ALLOC_INTERRUPT	interrupt time request
1954  *
1955  *	optional allocation flags:
1956  *	VM_ALLOC_NOBUSY		do not exclusive busy the page
1957  *	VM_ALLOC_NODUMP		do not include the page in a kernel core dump
1958  *	VM_ALLOC_NOOBJ		page is not associated with an object and
1959  *				should not be exclusive busy
1960  *	VM_ALLOC_SBUSY		shared busy the allocated page
1961  *	VM_ALLOC_WIRED		wire the allocated page
1962  *	VM_ALLOC_ZERO		prefer a zeroed page
1963  */
1964 vm_page_t
1965 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1966     u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1967     vm_paddr_t boundary, vm_memattr_t memattr)
1968 {
1969 	struct vm_domainset_iter di;
1970 	vm_page_t m;
1971 	int domain;
1972 
1973 	vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1974 	do {
1975 		m = vm_page_alloc_contig_domain(object, pindex, domain, req,
1976 		    npages, low, high, alignment, boundary, memattr);
1977 		if (m != NULL)
1978 			break;
1979 	} while (vm_domainset_iter_page(&di, object, &domain) == 0);
1980 
1981 	return (m);
1982 }
1983 
1984 vm_page_t
1985 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1986     int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1987     vm_paddr_t boundary, vm_memattr_t memattr)
1988 {
1989 	struct vm_domain *vmd;
1990 	vm_page_t m, m_ret, mpred;
1991 	u_int busy_lock, flags, oflags;
1992 
1993 	mpred = NULL;	/* XXX: pacify gcc */
1994 	KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1995 	    (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1996 	    ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1997 	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1998 	    ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
1999 	    req));
2000 	KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2001 	    ("Can't sleep and retry object insertion."));
2002 	if (object != NULL) {
2003 		VM_OBJECT_ASSERT_WLOCKED(object);
2004 		KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2005 		    ("vm_page_alloc_contig: object %p has fictitious pages",
2006 		    object));
2007 	}
2008 	KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2009 
2010 	if (object != NULL) {
2011 		mpred = vm_radix_lookup_le(&object->rtree, pindex);
2012 		KASSERT(mpred == NULL || mpred->pindex != pindex,
2013 		    ("vm_page_alloc_contig: pindex already allocated"));
2014 	}
2015 
2016 	/*
2017 	 * Can we allocate the pages without the number of free pages falling
2018 	 * below the lower bound for the allocation class?
2019 	 */
2020 	m_ret = NULL;
2021 again:
2022 #if VM_NRESERVLEVEL > 0
2023 	/*
2024 	 * Can we allocate the pages from a reservation?
2025 	 */
2026 	if (vm_object_reserv(object) &&
2027 	    (m_ret = vm_reserv_alloc_contig(object, pindex, domain, req,
2028 	    mpred, npages, low, high, alignment, boundary)) != NULL) {
2029 		domain = vm_phys_domain(m_ret);
2030 		vmd = VM_DOMAIN(domain);
2031 		goto found;
2032 	}
2033 #endif
2034 	vmd = VM_DOMAIN(domain);
2035 	if (vm_domain_allocate(vmd, req, npages)) {
2036 		/*
2037 		 * allocate them from the free page queues.
2038 		 */
2039 		vm_domain_free_lock(vmd);
2040 		m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2041 		    alignment, boundary);
2042 		vm_domain_free_unlock(vmd);
2043 		if (m_ret == NULL) {
2044 			vm_domain_freecnt_inc(vmd, npages);
2045 #if VM_NRESERVLEVEL > 0
2046 			if (vm_reserv_reclaim_contig(domain, npages, low,
2047 			    high, alignment, boundary))
2048 				goto again;
2049 #endif
2050 		}
2051 	}
2052 	if (m_ret == NULL) {
2053 		if (vm_domain_alloc_fail(vmd, object, req))
2054 			goto again;
2055 		return (NULL);
2056 	}
2057 #if VM_NRESERVLEVEL > 0
2058 found:
2059 #endif
2060 	for (m = m_ret; m < &m_ret[npages]; m++) {
2061 		vm_page_dequeue(m);
2062 		vm_page_alloc_check(m);
2063 	}
2064 
2065 	/*
2066 	 * Initialize the pages.  Only the PG_ZERO flag is inherited.
2067 	 */
2068 	flags = 0;
2069 	if ((req & VM_ALLOC_ZERO) != 0)
2070 		flags = PG_ZERO;
2071 	if ((req & VM_ALLOC_NODUMP) != 0)
2072 		flags |= PG_NODUMP;
2073 	oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2074 	    VPO_UNMANAGED : 0;
2075 	busy_lock = VPB_UNBUSIED;
2076 	if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2077 		busy_lock = VPB_SINGLE_EXCLUSIVER;
2078 	if ((req & VM_ALLOC_SBUSY) != 0)
2079 		busy_lock = VPB_SHARERS_WORD(1);
2080 	if ((req & VM_ALLOC_WIRED) != 0)
2081 		vm_wire_add(npages);
2082 	if (object != NULL) {
2083 		if (object->memattr != VM_MEMATTR_DEFAULT &&
2084 		    memattr == VM_MEMATTR_DEFAULT)
2085 			memattr = object->memattr;
2086 	}
2087 	for (m = m_ret; m < &m_ret[npages]; m++) {
2088 		m->aflags = 0;
2089 		m->flags = (m->flags | PG_NODUMP) & flags;
2090 		m->busy_lock = busy_lock;
2091 		if ((req & VM_ALLOC_WIRED) != 0)
2092 			m->wire_count = 1;
2093 		m->act_count = 0;
2094 		m->oflags = oflags;
2095 		if (object != NULL) {
2096 			if (vm_page_insert_after(m, object, pindex, mpred)) {
2097 				if ((req & VM_ALLOC_WIRED) != 0)
2098 					vm_wire_sub(npages);
2099 				KASSERT(m->object == NULL,
2100 				    ("page %p has object", m));
2101 				mpred = m;
2102 				for (m = m_ret; m < &m_ret[npages]; m++) {
2103 					if (m <= mpred &&
2104 					    (req & VM_ALLOC_WIRED) != 0)
2105 						m->wire_count = 0;
2106 					m->oflags = VPO_UNMANAGED;
2107 					m->busy_lock = VPB_UNBUSIED;
2108 					/* Don't change PG_ZERO. */
2109 					vm_page_free_toq(m);
2110 				}
2111 				if (req & VM_ALLOC_WAITFAIL) {
2112 					VM_OBJECT_WUNLOCK(object);
2113 					vm_radix_wait();
2114 					VM_OBJECT_WLOCK(object);
2115 				}
2116 				return (NULL);
2117 			}
2118 			mpred = m;
2119 		} else
2120 			m->pindex = pindex;
2121 		if (memattr != VM_MEMATTR_DEFAULT)
2122 			pmap_page_set_memattr(m, memattr);
2123 		pindex++;
2124 	}
2125 	return (m_ret);
2126 }
2127 
2128 /*
2129  * Check a page that has been freshly dequeued from a freelist.
2130  */
2131 static void
2132 vm_page_alloc_check(vm_page_t m)
2133 {
2134 
2135 	KASSERT(m->object == NULL, ("page %p has object", m));
2136 	KASSERT(m->queue == PQ_NONE && (m->aflags & PGA_QUEUE_STATE_MASK) == 0,
2137 	    ("page %p has unexpected queue %d, flags %#x",
2138 	    m, m->queue, (m->aflags & PGA_QUEUE_STATE_MASK)));
2139 	KASSERT(!vm_page_held(m), ("page %p is held", m));
2140 	KASSERT(!vm_page_busied(m), ("page %p is busy", m));
2141 	KASSERT(m->dirty == 0, ("page %p is dirty", m));
2142 	KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2143 	    ("page %p has unexpected memattr %d",
2144 	    m, pmap_page_get_memattr(m)));
2145 	KASSERT(m->valid == 0, ("free page %p is valid", m));
2146 }
2147 
2148 /*
2149  * 	vm_page_alloc_freelist:
2150  *
2151  *	Allocate a physical page from the specified free page list.
2152  *
2153  *	The caller must always specify an allocation class.
2154  *
2155  *	allocation classes:
2156  *	VM_ALLOC_NORMAL		normal process request
2157  *	VM_ALLOC_SYSTEM		system *really* needs a page
2158  *	VM_ALLOC_INTERRUPT	interrupt time request
2159  *
2160  *	optional allocation flags:
2161  *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
2162  *				intends to allocate
2163  *	VM_ALLOC_WIRED		wire the allocated page
2164  *	VM_ALLOC_ZERO		prefer a zeroed page
2165  */
2166 vm_page_t
2167 vm_page_alloc_freelist(int freelist, int req)
2168 {
2169 	struct vm_domainset_iter di;
2170 	vm_page_t m;
2171 	int domain;
2172 
2173 	vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2174 	do {
2175 		m = vm_page_alloc_freelist_domain(domain, freelist, req);
2176 		if (m != NULL)
2177 			break;
2178 	} while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2179 
2180 	return (m);
2181 }
2182 
2183 vm_page_t
2184 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2185 {
2186 	struct vm_domain *vmd;
2187 	vm_page_t m;
2188 	u_int flags;
2189 
2190 	m = NULL;
2191 	vmd = VM_DOMAIN(domain);
2192 again:
2193 	if (vm_domain_allocate(vmd, req, 1)) {
2194 		vm_domain_free_lock(vmd);
2195 		m = vm_phys_alloc_freelist_pages(domain, freelist,
2196 		    VM_FREEPOOL_DIRECT, 0);
2197 		vm_domain_free_unlock(vmd);
2198 		if (m == NULL)
2199 			vm_domain_freecnt_inc(vmd, 1);
2200 	}
2201 	if (m == NULL) {
2202 		if (vm_domain_alloc_fail(vmd, NULL, req))
2203 			goto again;
2204 		return (NULL);
2205 	}
2206 	vm_page_dequeue(m);
2207 	vm_page_alloc_check(m);
2208 
2209 	/*
2210 	 * Initialize the page.  Only the PG_ZERO flag is inherited.
2211 	 */
2212 	m->aflags = 0;
2213 	flags = 0;
2214 	if ((req & VM_ALLOC_ZERO) != 0)
2215 		flags = PG_ZERO;
2216 	m->flags &= flags;
2217 	if ((req & VM_ALLOC_WIRED) != 0) {
2218 		/*
2219 		 * The page lock is not required for wiring a page that does
2220 		 * not belong to an object.
2221 		 */
2222 		vm_wire_add(1);
2223 		m->wire_count = 1;
2224 	}
2225 	/* Unmanaged pages don't use "act_count". */
2226 	m->oflags = VPO_UNMANAGED;
2227 	return (m);
2228 }
2229 
2230 static int
2231 vm_page_import(void *arg, void **store, int cnt, int domain, int flags)
2232 {
2233 	struct vm_domain *vmd;
2234 	int i;
2235 
2236 	vmd = arg;
2237 	/* Only import if we can bring in a full bucket. */
2238 	if (cnt == 1 || !vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2239 		return (0);
2240 	domain = vmd->vmd_domain;
2241 	vm_domain_free_lock(vmd);
2242 	i = vm_phys_alloc_npages(domain, VM_FREEPOOL_DEFAULT, cnt,
2243 	    (vm_page_t *)store);
2244 	vm_domain_free_unlock(vmd);
2245 	if (cnt != i)
2246 		vm_domain_freecnt_inc(vmd, cnt - i);
2247 
2248 	return (i);
2249 }
2250 
2251 static void
2252 vm_page_release(void *arg, void **store, int cnt)
2253 {
2254 	struct vm_domain *vmd;
2255 	vm_page_t m;
2256 	int i;
2257 
2258 	vmd = arg;
2259 	vm_domain_free_lock(vmd);
2260 	for (i = 0; i < cnt; i++) {
2261 		m = (vm_page_t)store[i];
2262 		vm_phys_free_pages(m, 0);
2263 	}
2264 	vm_domain_free_unlock(vmd);
2265 	vm_domain_freecnt_inc(vmd, cnt);
2266 }
2267 
2268 #define	VPSC_ANY	0	/* No restrictions. */
2269 #define	VPSC_NORESERV	1	/* Skip reservations; implies VPSC_NOSUPER. */
2270 #define	VPSC_NOSUPER	2	/* Skip superpages. */
2271 
2272 /*
2273  *	vm_page_scan_contig:
2274  *
2275  *	Scan vm_page_array[] between the specified entries "m_start" and
2276  *	"m_end" for a run of contiguous physical pages that satisfy the
2277  *	specified conditions, and return the lowest page in the run.  The
2278  *	specified "alignment" determines the alignment of the lowest physical
2279  *	page in the run.  If the specified "boundary" is non-zero, then the
2280  *	run of physical pages cannot span a physical address that is a
2281  *	multiple of "boundary".
2282  *
2283  *	"m_end" is never dereferenced, so it need not point to a vm_page
2284  *	structure within vm_page_array[].
2285  *
2286  *	"npages" must be greater than zero.  "m_start" and "m_end" must not
2287  *	span a hole (or discontiguity) in the physical address space.  Both
2288  *	"alignment" and "boundary" must be a power of two.
2289  */
2290 vm_page_t
2291 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2292     u_long alignment, vm_paddr_t boundary, int options)
2293 {
2294 	struct mtx *m_mtx;
2295 	vm_object_t object;
2296 	vm_paddr_t pa;
2297 	vm_page_t m, m_run;
2298 #if VM_NRESERVLEVEL > 0
2299 	int level;
2300 #endif
2301 	int m_inc, order, run_ext, run_len;
2302 
2303 	KASSERT(npages > 0, ("npages is 0"));
2304 	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2305 	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2306 	m_run = NULL;
2307 	run_len = 0;
2308 	m_mtx = NULL;
2309 	for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2310 		KASSERT((m->flags & PG_MARKER) == 0,
2311 		    ("page %p is PG_MARKER", m));
2312 		KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->wire_count == 1,
2313 		    ("fictitious page %p has invalid wire count", m));
2314 
2315 		/*
2316 		 * If the current page would be the start of a run, check its
2317 		 * physical address against the end, alignment, and boundary
2318 		 * conditions.  If it doesn't satisfy these conditions, either
2319 		 * terminate the scan or advance to the next page that
2320 		 * satisfies the failed condition.
2321 		 */
2322 		if (run_len == 0) {
2323 			KASSERT(m_run == NULL, ("m_run != NULL"));
2324 			if (m + npages > m_end)
2325 				break;
2326 			pa = VM_PAGE_TO_PHYS(m);
2327 			if ((pa & (alignment - 1)) != 0) {
2328 				m_inc = atop(roundup2(pa, alignment) - pa);
2329 				continue;
2330 			}
2331 			if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2332 			    boundary) != 0) {
2333 				m_inc = atop(roundup2(pa, boundary) - pa);
2334 				continue;
2335 			}
2336 		} else
2337 			KASSERT(m_run != NULL, ("m_run == NULL"));
2338 
2339 		vm_page_change_lock(m, &m_mtx);
2340 		m_inc = 1;
2341 retry:
2342 		if (vm_page_held(m))
2343 			run_ext = 0;
2344 #if VM_NRESERVLEVEL > 0
2345 		else if ((level = vm_reserv_level(m)) >= 0 &&
2346 		    (options & VPSC_NORESERV) != 0) {
2347 			run_ext = 0;
2348 			/* Advance to the end of the reservation. */
2349 			pa = VM_PAGE_TO_PHYS(m);
2350 			m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2351 			    pa);
2352 		}
2353 #endif
2354 		else if ((object = m->object) != NULL) {
2355 			/*
2356 			 * The page is considered eligible for relocation if
2357 			 * and only if it could be laundered or reclaimed by
2358 			 * the page daemon.
2359 			 */
2360 			if (!VM_OBJECT_TRYRLOCK(object)) {
2361 				mtx_unlock(m_mtx);
2362 				VM_OBJECT_RLOCK(object);
2363 				mtx_lock(m_mtx);
2364 				if (m->object != object) {
2365 					/*
2366 					 * The page may have been freed.
2367 					 */
2368 					VM_OBJECT_RUNLOCK(object);
2369 					goto retry;
2370 				} else if (vm_page_held(m)) {
2371 					run_ext = 0;
2372 					goto unlock;
2373 				}
2374 			}
2375 			KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2376 			    ("page %p is PG_UNHOLDFREE", m));
2377 			/* Don't care: PG_NODUMP, PG_ZERO. */
2378 			if (object->type != OBJT_DEFAULT &&
2379 			    object->type != OBJT_SWAP &&
2380 			    object->type != OBJT_VNODE) {
2381 				run_ext = 0;
2382 #if VM_NRESERVLEVEL > 0
2383 			} else if ((options & VPSC_NOSUPER) != 0 &&
2384 			    (level = vm_reserv_level_iffullpop(m)) >= 0) {
2385 				run_ext = 0;
2386 				/* Advance to the end of the superpage. */
2387 				pa = VM_PAGE_TO_PHYS(m);
2388 				m_inc = atop(roundup2(pa + 1,
2389 				    vm_reserv_size(level)) - pa);
2390 #endif
2391 			} else if (object->memattr == VM_MEMATTR_DEFAULT &&
2392 			    vm_page_queue(m) != PQ_NONE && !vm_page_busied(m)) {
2393 				/*
2394 				 * The page is allocated but eligible for
2395 				 * relocation.  Extend the current run by one
2396 				 * page.
2397 				 */
2398 				KASSERT(pmap_page_get_memattr(m) ==
2399 				    VM_MEMATTR_DEFAULT,
2400 				    ("page %p has an unexpected memattr", m));
2401 				KASSERT((m->oflags & (VPO_SWAPINPROG |
2402 				    VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2403 				    ("page %p has unexpected oflags", m));
2404 				/* Don't care: VPO_NOSYNC. */
2405 				run_ext = 1;
2406 			} else
2407 				run_ext = 0;
2408 unlock:
2409 			VM_OBJECT_RUNLOCK(object);
2410 #if VM_NRESERVLEVEL > 0
2411 		} else if (level >= 0) {
2412 			/*
2413 			 * The page is reserved but not yet allocated.  In
2414 			 * other words, it is still free.  Extend the current
2415 			 * run by one page.
2416 			 */
2417 			run_ext = 1;
2418 #endif
2419 		} else if ((order = m->order) < VM_NFREEORDER) {
2420 			/*
2421 			 * The page is enqueued in the physical memory
2422 			 * allocator's free page queues.  Moreover, it is the
2423 			 * first page in a power-of-two-sized run of
2424 			 * contiguous free pages.  Add these pages to the end
2425 			 * of the current run, and jump ahead.
2426 			 */
2427 			run_ext = 1 << order;
2428 			m_inc = 1 << order;
2429 		} else {
2430 			/*
2431 			 * Skip the page for one of the following reasons: (1)
2432 			 * It is enqueued in the physical memory allocator's
2433 			 * free page queues.  However, it is not the first
2434 			 * page in a run of contiguous free pages.  (This case
2435 			 * rarely occurs because the scan is performed in
2436 			 * ascending order.) (2) It is not reserved, and it is
2437 			 * transitioning from free to allocated.  (Conversely,
2438 			 * the transition from allocated to free for managed
2439 			 * pages is blocked by the page lock.) (3) It is
2440 			 * allocated but not contained by an object and not
2441 			 * wired, e.g., allocated by Xen's balloon driver.
2442 			 */
2443 			run_ext = 0;
2444 		}
2445 
2446 		/*
2447 		 * Extend or reset the current run of pages.
2448 		 */
2449 		if (run_ext > 0) {
2450 			if (run_len == 0)
2451 				m_run = m;
2452 			run_len += run_ext;
2453 		} else {
2454 			if (run_len > 0) {
2455 				m_run = NULL;
2456 				run_len = 0;
2457 			}
2458 		}
2459 	}
2460 	if (m_mtx != NULL)
2461 		mtx_unlock(m_mtx);
2462 	if (run_len >= npages)
2463 		return (m_run);
2464 	return (NULL);
2465 }
2466 
2467 /*
2468  *	vm_page_reclaim_run:
2469  *
2470  *	Try to relocate each of the allocated virtual pages within the
2471  *	specified run of physical pages to a new physical address.  Free the
2472  *	physical pages underlying the relocated virtual pages.  A virtual page
2473  *	is relocatable if and only if it could be laundered or reclaimed by
2474  *	the page daemon.  Whenever possible, a virtual page is relocated to a
2475  *	physical address above "high".
2476  *
2477  *	Returns 0 if every physical page within the run was already free or
2478  *	just freed by a successful relocation.  Otherwise, returns a non-zero
2479  *	value indicating why the last attempt to relocate a virtual page was
2480  *	unsuccessful.
2481  *
2482  *	"req_class" must be an allocation class.
2483  */
2484 static int
2485 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2486     vm_paddr_t high)
2487 {
2488 	struct vm_domain *vmd;
2489 	struct mtx *m_mtx;
2490 	struct spglist free;
2491 	vm_object_t object;
2492 	vm_paddr_t pa;
2493 	vm_page_t m, m_end, m_new;
2494 	int error, order, req;
2495 
2496 	KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2497 	    ("req_class is not an allocation class"));
2498 	SLIST_INIT(&free);
2499 	error = 0;
2500 	m = m_run;
2501 	m_end = m_run + npages;
2502 	m_mtx = NULL;
2503 	for (; error == 0 && m < m_end; m++) {
2504 		KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2505 		    ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2506 
2507 		/*
2508 		 * Avoid releasing and reacquiring the same page lock.
2509 		 */
2510 		vm_page_change_lock(m, &m_mtx);
2511 retry:
2512 		if (vm_page_held(m))
2513 			error = EBUSY;
2514 		else if ((object = m->object) != NULL) {
2515 			/*
2516 			 * The page is relocated if and only if it could be
2517 			 * laundered or reclaimed by the page daemon.
2518 			 */
2519 			if (!VM_OBJECT_TRYWLOCK(object)) {
2520 				mtx_unlock(m_mtx);
2521 				VM_OBJECT_WLOCK(object);
2522 				mtx_lock(m_mtx);
2523 				if (m->object != object) {
2524 					/*
2525 					 * The page may have been freed.
2526 					 */
2527 					VM_OBJECT_WUNLOCK(object);
2528 					goto retry;
2529 				} else if (vm_page_held(m)) {
2530 					error = EBUSY;
2531 					goto unlock;
2532 				}
2533 			}
2534 			KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2535 			    ("page %p is PG_UNHOLDFREE", m));
2536 			/* Don't care: PG_NODUMP, PG_ZERO. */
2537 			if (object->type != OBJT_DEFAULT &&
2538 			    object->type != OBJT_SWAP &&
2539 			    object->type != OBJT_VNODE)
2540 				error = EINVAL;
2541 			else if (object->memattr != VM_MEMATTR_DEFAULT)
2542 				error = EINVAL;
2543 			else if (vm_page_queue(m) != PQ_NONE &&
2544 			    !vm_page_busied(m)) {
2545 				KASSERT(pmap_page_get_memattr(m) ==
2546 				    VM_MEMATTR_DEFAULT,
2547 				    ("page %p has an unexpected memattr", m));
2548 				KASSERT((m->oflags & (VPO_SWAPINPROG |
2549 				    VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2550 				    ("page %p has unexpected oflags", m));
2551 				/* Don't care: VPO_NOSYNC. */
2552 				if (m->valid != 0) {
2553 					/*
2554 					 * First, try to allocate a new page
2555 					 * that is above "high".  Failing
2556 					 * that, try to allocate a new page
2557 					 * that is below "m_run".  Allocate
2558 					 * the new page between the end of
2559 					 * "m_run" and "high" only as a last
2560 					 * resort.
2561 					 */
2562 					req = req_class | VM_ALLOC_NOOBJ;
2563 					if ((m->flags & PG_NODUMP) != 0)
2564 						req |= VM_ALLOC_NODUMP;
2565 					if (trunc_page(high) !=
2566 					    ~(vm_paddr_t)PAGE_MASK) {
2567 						m_new = vm_page_alloc_contig(
2568 						    NULL, 0, req, 1,
2569 						    round_page(high),
2570 						    ~(vm_paddr_t)0,
2571 						    PAGE_SIZE, 0,
2572 						    VM_MEMATTR_DEFAULT);
2573 					} else
2574 						m_new = NULL;
2575 					if (m_new == NULL) {
2576 						pa = VM_PAGE_TO_PHYS(m_run);
2577 						m_new = vm_page_alloc_contig(
2578 						    NULL, 0, req, 1,
2579 						    0, pa - 1, PAGE_SIZE, 0,
2580 						    VM_MEMATTR_DEFAULT);
2581 					}
2582 					if (m_new == NULL) {
2583 						pa += ptoa(npages);
2584 						m_new = vm_page_alloc_contig(
2585 						    NULL, 0, req, 1,
2586 						    pa, high, PAGE_SIZE, 0,
2587 						    VM_MEMATTR_DEFAULT);
2588 					}
2589 					if (m_new == NULL) {
2590 						error = ENOMEM;
2591 						goto unlock;
2592 					}
2593 					KASSERT(!vm_page_wired(m_new),
2594 					    ("page %p is wired", m_new));
2595 
2596 					/*
2597 					 * Replace "m" with the new page.  For
2598 					 * vm_page_replace(), "m" must be busy
2599 					 * and dequeued.  Finally, change "m"
2600 					 * as if vm_page_free() was called.
2601 					 */
2602 					if (object->ref_count != 0)
2603 						pmap_remove_all(m);
2604 					m_new->aflags = m->aflags &
2605 					    ~PGA_QUEUE_STATE_MASK;
2606 					KASSERT(m_new->oflags == VPO_UNMANAGED,
2607 					    ("page %p is managed", m_new));
2608 					m_new->oflags = m->oflags & VPO_NOSYNC;
2609 					pmap_copy_page(m, m_new);
2610 					m_new->valid = m->valid;
2611 					m_new->dirty = m->dirty;
2612 					m->flags &= ~PG_ZERO;
2613 					vm_page_xbusy(m);
2614 					vm_page_dequeue(m);
2615 					vm_page_replace_checked(m_new, object,
2616 					    m->pindex, m);
2617 					if (vm_page_free_prep(m))
2618 						SLIST_INSERT_HEAD(&free, m,
2619 						    plinks.s.ss);
2620 
2621 					/*
2622 					 * The new page must be deactivated
2623 					 * before the object is unlocked.
2624 					 */
2625 					vm_page_change_lock(m_new, &m_mtx);
2626 					vm_page_deactivate(m_new);
2627 				} else {
2628 					m->flags &= ~PG_ZERO;
2629 					vm_page_dequeue(m);
2630 					if (vm_page_free_prep(m))
2631 						SLIST_INSERT_HEAD(&free, m,
2632 						    plinks.s.ss);
2633 					KASSERT(m->dirty == 0,
2634 					    ("page %p is dirty", m));
2635 				}
2636 			} else
2637 				error = EBUSY;
2638 unlock:
2639 			VM_OBJECT_WUNLOCK(object);
2640 		} else {
2641 			MPASS(vm_phys_domain(m) == domain);
2642 			vmd = VM_DOMAIN(domain);
2643 			vm_domain_free_lock(vmd);
2644 			order = m->order;
2645 			if (order < VM_NFREEORDER) {
2646 				/*
2647 				 * The page is enqueued in the physical memory
2648 				 * allocator's free page queues.  Moreover, it
2649 				 * is the first page in a power-of-two-sized
2650 				 * run of contiguous free pages.  Jump ahead
2651 				 * to the last page within that run, and
2652 				 * continue from there.
2653 				 */
2654 				m += (1 << order) - 1;
2655 			}
2656 #if VM_NRESERVLEVEL > 0
2657 			else if (vm_reserv_is_page_free(m))
2658 				order = 0;
2659 #endif
2660 			vm_domain_free_unlock(vmd);
2661 			if (order == VM_NFREEORDER)
2662 				error = EINVAL;
2663 		}
2664 	}
2665 	if (m_mtx != NULL)
2666 		mtx_unlock(m_mtx);
2667 	if ((m = SLIST_FIRST(&free)) != NULL) {
2668 		int cnt;
2669 
2670 		vmd = VM_DOMAIN(domain);
2671 		cnt = 0;
2672 		vm_domain_free_lock(vmd);
2673 		do {
2674 			MPASS(vm_phys_domain(m) == domain);
2675 			SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2676 			vm_phys_free_pages(m, 0);
2677 			cnt++;
2678 		} while ((m = SLIST_FIRST(&free)) != NULL);
2679 		vm_domain_free_unlock(vmd);
2680 		vm_domain_freecnt_inc(vmd, cnt);
2681 	}
2682 	return (error);
2683 }
2684 
2685 #define	NRUNS	16
2686 
2687 CTASSERT(powerof2(NRUNS));
2688 
2689 #define	RUN_INDEX(count)	((count) & (NRUNS - 1))
2690 
2691 #define	MIN_RECLAIM	8
2692 
2693 /*
2694  *	vm_page_reclaim_contig:
2695  *
2696  *	Reclaim allocated, contiguous physical memory satisfying the specified
2697  *	conditions by relocating the virtual pages using that physical memory.
2698  *	Returns true if reclamation is successful and false otherwise.  Since
2699  *	relocation requires the allocation of physical pages, reclamation may
2700  *	fail due to a shortage of free pages.  When reclamation fails, callers
2701  *	are expected to perform vm_wait() before retrying a failed allocation
2702  *	operation, e.g., vm_page_alloc_contig().
2703  *
2704  *	The caller must always specify an allocation class through "req".
2705  *
2706  *	allocation classes:
2707  *	VM_ALLOC_NORMAL		normal process request
2708  *	VM_ALLOC_SYSTEM		system *really* needs a page
2709  *	VM_ALLOC_INTERRUPT	interrupt time request
2710  *
2711  *	The optional allocation flags are ignored.
2712  *
2713  *	"npages" must be greater than zero.  Both "alignment" and "boundary"
2714  *	must be a power of two.
2715  */
2716 bool
2717 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
2718     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2719 {
2720 	struct vm_domain *vmd;
2721 	vm_paddr_t curr_low;
2722 	vm_page_t m_run, m_runs[NRUNS];
2723 	u_long count, reclaimed;
2724 	int error, i, options, req_class;
2725 
2726 	KASSERT(npages > 0, ("npages is 0"));
2727 	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2728 	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2729 	req_class = req & VM_ALLOC_CLASS_MASK;
2730 
2731 	/*
2732 	 * The page daemon is allowed to dig deeper into the free page list.
2733 	 */
2734 	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2735 		req_class = VM_ALLOC_SYSTEM;
2736 
2737 	/*
2738 	 * Return if the number of free pages cannot satisfy the requested
2739 	 * allocation.
2740 	 */
2741 	vmd = VM_DOMAIN(domain);
2742 	count = vmd->vmd_free_count;
2743 	if (count < npages + vmd->vmd_free_reserved || (count < npages +
2744 	    vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2745 	    (count < npages && req_class == VM_ALLOC_INTERRUPT))
2746 		return (false);
2747 
2748 	/*
2749 	 * Scan up to three times, relaxing the restrictions ("options") on
2750 	 * the reclamation of reservations and superpages each time.
2751 	 */
2752 	for (options = VPSC_NORESERV;;) {
2753 		/*
2754 		 * Find the highest runs that satisfy the given constraints
2755 		 * and restrictions, and record them in "m_runs".
2756 		 */
2757 		curr_low = low;
2758 		count = 0;
2759 		for (;;) {
2760 			m_run = vm_phys_scan_contig(domain, npages, curr_low,
2761 			    high, alignment, boundary, options);
2762 			if (m_run == NULL)
2763 				break;
2764 			curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2765 			m_runs[RUN_INDEX(count)] = m_run;
2766 			count++;
2767 		}
2768 
2769 		/*
2770 		 * Reclaim the highest runs in LIFO (descending) order until
2771 		 * the number of reclaimed pages, "reclaimed", is at least
2772 		 * MIN_RECLAIM.  Reset "reclaimed" each time because each
2773 		 * reclamation is idempotent, and runs will (likely) recur
2774 		 * from one scan to the next as restrictions are relaxed.
2775 		 */
2776 		reclaimed = 0;
2777 		for (i = 0; count > 0 && i < NRUNS; i++) {
2778 			count--;
2779 			m_run = m_runs[RUN_INDEX(count)];
2780 			error = vm_page_reclaim_run(req_class, domain, npages,
2781 			    m_run, high);
2782 			if (error == 0) {
2783 				reclaimed += npages;
2784 				if (reclaimed >= MIN_RECLAIM)
2785 					return (true);
2786 			}
2787 		}
2788 
2789 		/*
2790 		 * Either relax the restrictions on the next scan or return if
2791 		 * the last scan had no restrictions.
2792 		 */
2793 		if (options == VPSC_NORESERV)
2794 			options = VPSC_NOSUPER;
2795 		else if (options == VPSC_NOSUPER)
2796 			options = VPSC_ANY;
2797 		else if (options == VPSC_ANY)
2798 			return (reclaimed != 0);
2799 	}
2800 }
2801 
2802 bool
2803 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2804     u_long alignment, vm_paddr_t boundary)
2805 {
2806 	struct vm_domainset_iter di;
2807 	int domain;
2808 	bool ret;
2809 
2810 	vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2811 	do {
2812 		ret = vm_page_reclaim_contig_domain(domain, req, npages, low,
2813 		    high, alignment, boundary);
2814 		if (ret)
2815 			break;
2816 	} while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2817 
2818 	return (ret);
2819 }
2820 
2821 /*
2822  * Set the domain in the appropriate page level domainset.
2823  */
2824 void
2825 vm_domain_set(struct vm_domain *vmd)
2826 {
2827 
2828 	mtx_lock(&vm_domainset_lock);
2829 	if (!vmd->vmd_minset && vm_paging_min(vmd)) {
2830 		vmd->vmd_minset = 1;
2831 		DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
2832 	}
2833 	if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
2834 		vmd->vmd_severeset = 1;
2835 		DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
2836 	}
2837 	mtx_unlock(&vm_domainset_lock);
2838 }
2839 
2840 /*
2841  * Clear the domain from the appropriate page level domainset.
2842  */
2843 void
2844 vm_domain_clear(struct vm_domain *vmd)
2845 {
2846 
2847 	mtx_lock(&vm_domainset_lock);
2848 	if (vmd->vmd_minset && !vm_paging_min(vmd)) {
2849 		vmd->vmd_minset = 0;
2850 		DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
2851 		if (vm_min_waiters != 0) {
2852 			vm_min_waiters = 0;
2853 			wakeup(&vm_min_domains);
2854 		}
2855 	}
2856 	if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
2857 		vmd->vmd_severeset = 0;
2858 		DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
2859 		if (vm_severe_waiters != 0) {
2860 			vm_severe_waiters = 0;
2861 			wakeup(&vm_severe_domains);
2862 		}
2863 	}
2864 
2865 	/*
2866 	 * If pageout daemon needs pages, then tell it that there are
2867 	 * some free.
2868 	 */
2869 	if (vmd->vmd_pageout_pages_needed &&
2870 	    vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
2871 		wakeup(&vmd->vmd_pageout_pages_needed);
2872 		vmd->vmd_pageout_pages_needed = 0;
2873 	}
2874 
2875 	/* See comments in vm_wait_doms(). */
2876 	if (vm_pageproc_waiters) {
2877 		vm_pageproc_waiters = 0;
2878 		wakeup(&vm_pageproc_waiters);
2879 	}
2880 	mtx_unlock(&vm_domainset_lock);
2881 }
2882 
2883 /*
2884  * Wait for free pages to exceed the min threshold globally.
2885  */
2886 void
2887 vm_wait_min(void)
2888 {
2889 
2890 	mtx_lock(&vm_domainset_lock);
2891 	while (vm_page_count_min()) {
2892 		vm_min_waiters++;
2893 		msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
2894 	}
2895 	mtx_unlock(&vm_domainset_lock);
2896 }
2897 
2898 /*
2899  * Wait for free pages to exceed the severe threshold globally.
2900  */
2901 void
2902 vm_wait_severe(void)
2903 {
2904 
2905 	mtx_lock(&vm_domainset_lock);
2906 	while (vm_page_count_severe()) {
2907 		vm_severe_waiters++;
2908 		msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
2909 		    "vmwait", 0);
2910 	}
2911 	mtx_unlock(&vm_domainset_lock);
2912 }
2913 
2914 u_int
2915 vm_wait_count(void)
2916 {
2917 
2918 	return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
2919 }
2920 
2921 void
2922 vm_wait_doms(const domainset_t *wdoms)
2923 {
2924 
2925 	/*
2926 	 * We use racey wakeup synchronization to avoid expensive global
2927 	 * locking for the pageproc when sleeping with a non-specific vm_wait.
2928 	 * To handle this, we only sleep for one tick in this instance.  It
2929 	 * is expected that most allocations for the pageproc will come from
2930 	 * kmem or vm_page_grab* which will use the more specific and
2931 	 * race-free vm_wait_domain().
2932 	 */
2933 	if (curproc == pageproc) {
2934 		mtx_lock(&vm_domainset_lock);
2935 		vm_pageproc_waiters++;
2936 		msleep(&vm_pageproc_waiters, &vm_domainset_lock, PVM | PDROP,
2937 		    "pageprocwait", 1);
2938 	} else {
2939 		/*
2940 		 * XXX Ideally we would wait only until the allocation could
2941 		 * be satisfied.  This condition can cause new allocators to
2942 		 * consume all freed pages while old allocators wait.
2943 		 */
2944 		mtx_lock(&vm_domainset_lock);
2945 		if (vm_page_count_min_set(wdoms)) {
2946 			vm_min_waiters++;
2947 			msleep(&vm_min_domains, &vm_domainset_lock,
2948 			    PVM | PDROP, "vmwait", 0);
2949 		} else
2950 			mtx_unlock(&vm_domainset_lock);
2951 	}
2952 }
2953 
2954 /*
2955  *	vm_wait_domain:
2956  *
2957  *	Sleep until free pages are available for allocation.
2958  *	- Called in various places after failed memory allocations.
2959  */
2960 void
2961 vm_wait_domain(int domain)
2962 {
2963 	struct vm_domain *vmd;
2964 	domainset_t wdom;
2965 
2966 	vmd = VM_DOMAIN(domain);
2967 	vm_domain_free_assert_unlocked(vmd);
2968 
2969 	if (curproc == pageproc) {
2970 		mtx_lock(&vm_domainset_lock);
2971 		if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
2972 			vmd->vmd_pageout_pages_needed = 1;
2973 			msleep(&vmd->vmd_pageout_pages_needed,
2974 			    &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
2975 		} else
2976 			mtx_unlock(&vm_domainset_lock);
2977 	} else {
2978 		if (pageproc == NULL)
2979 			panic("vm_wait in early boot");
2980 		DOMAINSET_ZERO(&wdom);
2981 		DOMAINSET_SET(vmd->vmd_domain, &wdom);
2982 		vm_wait_doms(&wdom);
2983 	}
2984 }
2985 
2986 /*
2987  *	vm_wait:
2988  *
2989  *	Sleep until free pages are available for allocation in the
2990  *	affinity domains of the obj.  If obj is NULL, the domain set
2991  *	for the calling thread is used.
2992  *	Called in various places after failed memory allocations.
2993  */
2994 void
2995 vm_wait(vm_object_t obj)
2996 {
2997 	struct domainset *d;
2998 
2999 	d = NULL;
3000 
3001 	/*
3002 	 * Carefully fetch pointers only once: the struct domainset
3003 	 * itself is ummutable but the pointer might change.
3004 	 */
3005 	if (obj != NULL)
3006 		d = obj->domain.dr_policy;
3007 	if (d == NULL)
3008 		d = curthread->td_domain.dr_policy;
3009 
3010 	vm_wait_doms(&d->ds_mask);
3011 }
3012 
3013 /*
3014  *	vm_domain_alloc_fail:
3015  *
3016  *	Called when a page allocation function fails.  Informs the
3017  *	pagedaemon and performs the requested wait.  Requires the
3018  *	domain_free and object lock on entry.  Returns with the
3019  *	object lock held and free lock released.  Returns an error when
3020  *	retry is necessary.
3021  *
3022  */
3023 static int
3024 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3025 {
3026 
3027 	vm_domain_free_assert_unlocked(vmd);
3028 
3029 	atomic_add_int(&vmd->vmd_pageout_deficit,
3030 	    max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3031 	if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3032 		if (object != NULL)
3033 			VM_OBJECT_WUNLOCK(object);
3034 		vm_wait_domain(vmd->vmd_domain);
3035 		if (object != NULL)
3036 			VM_OBJECT_WLOCK(object);
3037 		if (req & VM_ALLOC_WAITOK)
3038 			return (EAGAIN);
3039 	}
3040 
3041 	return (0);
3042 }
3043 
3044 /*
3045  *	vm_waitpfault:
3046  *
3047  *	Sleep until free pages are available for allocation.
3048  *	- Called only in vm_fault so that processes page faulting
3049  *	  can be easily tracked.
3050  *	- Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3051  *	  processes will be able to grab memory first.  Do not change
3052  *	  this balance without careful testing first.
3053  */
3054 void
3055 vm_waitpfault(struct domainset *dset)
3056 {
3057 
3058 	/*
3059 	 * XXX Ideally we would wait only until the allocation could
3060 	 * be satisfied.  This condition can cause new allocators to
3061 	 * consume all freed pages while old allocators wait.
3062 	 */
3063 	mtx_lock(&vm_domainset_lock);
3064 	if (vm_page_count_min_set(&dset->ds_mask)) {
3065 		vm_min_waiters++;
3066 		msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3067 		    "pfault", 0);
3068 	} else
3069 		mtx_unlock(&vm_domainset_lock);
3070 }
3071 
3072 struct vm_pagequeue *
3073 vm_page_pagequeue(vm_page_t m)
3074 {
3075 
3076 	return (&vm_pagequeue_domain(m)->vmd_pagequeues[m->queue]);
3077 }
3078 
3079 static struct mtx *
3080 vm_page_pagequeue_lockptr(vm_page_t m)
3081 {
3082 	uint8_t queue;
3083 
3084 	if ((queue = atomic_load_8(&m->queue)) == PQ_NONE)
3085 		return (NULL);
3086 	return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue].pq_mutex);
3087 }
3088 
3089 static inline void
3090 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m)
3091 {
3092 	struct vm_domain *vmd;
3093 	uint8_t qflags;
3094 
3095 	CRITICAL_ASSERT(curthread);
3096 	vm_pagequeue_assert_locked(pq);
3097 
3098 	/*
3099 	 * The page daemon is allowed to set m->queue = PQ_NONE without
3100 	 * the page queue lock held.  In this case it is about to free the page,
3101 	 * which must not have any queue state.
3102 	 */
3103 	qflags = atomic_load_8(&m->aflags) & PGA_QUEUE_STATE_MASK;
3104 	KASSERT(pq == vm_page_pagequeue(m) || qflags == 0,
3105 	    ("page %p doesn't belong to queue %p but has queue state %#x",
3106 	    m, pq, qflags));
3107 
3108 	if ((qflags & PGA_DEQUEUE) != 0) {
3109 		if (__predict_true((qflags & PGA_ENQUEUED) != 0)) {
3110 			TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3111 			vm_pagequeue_cnt_dec(pq);
3112 		}
3113 		vm_page_dequeue_complete(m);
3114 	} else if ((qflags & (PGA_REQUEUE | PGA_REQUEUE_HEAD)) != 0) {
3115 		if ((qflags & PGA_ENQUEUED) != 0)
3116 			TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3117 		else {
3118 			vm_pagequeue_cnt_inc(pq);
3119 			vm_page_aflag_set(m, PGA_ENQUEUED);
3120 		}
3121 		if ((qflags & PGA_REQUEUE_HEAD) != 0) {
3122 			KASSERT(m->queue == PQ_INACTIVE,
3123 			    ("head enqueue not supported for page %p", m));
3124 			vmd = vm_pagequeue_domain(m);
3125 			TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3126 		} else
3127 			TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3128 
3129 		/*
3130 		 * PGA_REQUEUE and PGA_REQUEUE_HEAD must be cleared after
3131 		 * setting PGA_ENQUEUED in order to synchronize with the
3132 		 * page daemon.
3133 		 */
3134 		vm_page_aflag_clear(m, PGA_REQUEUE | PGA_REQUEUE_HEAD);
3135 	}
3136 }
3137 
3138 static void
3139 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3140     uint8_t queue)
3141 {
3142 	vm_page_t m;
3143 	int i;
3144 
3145 	for (i = 0; i < bq->bq_cnt; i++) {
3146 		m = bq->bq_pa[i];
3147 		if (__predict_false(m->queue != queue))
3148 			continue;
3149 		vm_pqbatch_process_page(pq, m);
3150 	}
3151 	vm_batchqueue_init(bq);
3152 }
3153 
3154 static void
3155 vm_pqbatch_submit_page(vm_page_t m, uint8_t queue)
3156 {
3157 	struct vm_batchqueue *bq;
3158 	struct vm_pagequeue *pq;
3159 	int domain;
3160 
3161 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3162 	    ("page %p is unmanaged", m));
3163 	KASSERT(mtx_owned(vm_page_lockptr(m)) ||
3164 	    (m->object == NULL && (m->aflags & PGA_DEQUEUE) != 0),
3165 	    ("missing synchronization for page %p", m));
3166 	KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3167 
3168 	domain = vm_phys_domain(m);
3169 	pq = &vm_pagequeue_domain(m)->vmd_pagequeues[queue];
3170 
3171 	critical_enter();
3172 	bq = DPCPU_PTR(pqbatch[domain][queue]);
3173 	if (vm_batchqueue_insert(bq, m)) {
3174 		critical_exit();
3175 		return;
3176 	}
3177 	if (!vm_pagequeue_trylock(pq)) {
3178 		critical_exit();
3179 		vm_pagequeue_lock(pq);
3180 		critical_enter();
3181 		bq = DPCPU_PTR(pqbatch[domain][queue]);
3182 	}
3183 	vm_pqbatch_process(pq, bq, queue);
3184 
3185 	/*
3186 	 * The page may have been logically dequeued before we acquired the
3187 	 * page queue lock.  In this case, since we either hold the page lock
3188 	 * or the page is being freed, a different thread cannot be concurrently
3189 	 * enqueuing the page.
3190 	 */
3191 	if (__predict_true(m->queue == queue))
3192 		vm_pqbatch_process_page(pq, m);
3193 	else {
3194 		KASSERT(m->queue == PQ_NONE,
3195 		    ("invalid queue transition for page %p", m));
3196 		KASSERT((m->aflags & PGA_ENQUEUED) == 0,
3197 		    ("page %p is enqueued with invalid queue index", m));
3198 		vm_page_aflag_clear(m, PGA_QUEUE_STATE_MASK);
3199 	}
3200 	vm_pagequeue_unlock(pq);
3201 	critical_exit();
3202 }
3203 
3204 /*
3205  *	vm_page_drain_pqbatch:		[ internal use only ]
3206  *
3207  *	Force all per-CPU page queue batch queues to be drained.  This is
3208  *	intended for use in severe memory shortages, to ensure that pages
3209  *	do not remain stuck in the batch queues.
3210  */
3211 void
3212 vm_page_drain_pqbatch(void)
3213 {
3214 	struct thread *td;
3215 	struct vm_domain *vmd;
3216 	struct vm_pagequeue *pq;
3217 	int cpu, domain, queue;
3218 
3219 	td = curthread;
3220 	CPU_FOREACH(cpu) {
3221 		thread_lock(td);
3222 		sched_bind(td, cpu);
3223 		thread_unlock(td);
3224 
3225 		for (domain = 0; domain < vm_ndomains; domain++) {
3226 			vmd = VM_DOMAIN(domain);
3227 			for (queue = 0; queue < PQ_COUNT; queue++) {
3228 				pq = &vmd->vmd_pagequeues[queue];
3229 				vm_pagequeue_lock(pq);
3230 				critical_enter();
3231 				vm_pqbatch_process(pq,
3232 				    DPCPU_PTR(pqbatch[domain][queue]), queue);
3233 				critical_exit();
3234 				vm_pagequeue_unlock(pq);
3235 			}
3236 		}
3237 	}
3238 	thread_lock(td);
3239 	sched_unbind(td);
3240 	thread_unlock(td);
3241 }
3242 
3243 /*
3244  * Complete the logical removal of a page from a page queue.  We must be
3245  * careful to synchronize with the page daemon, which may be concurrently
3246  * examining the page with only the page lock held.  The page must not be
3247  * in a state where it appears to be logically enqueued.
3248  */
3249 static void
3250 vm_page_dequeue_complete(vm_page_t m)
3251 {
3252 
3253 	m->queue = PQ_NONE;
3254 	atomic_thread_fence_rel();
3255 	vm_page_aflag_clear(m, PGA_QUEUE_STATE_MASK);
3256 }
3257 
3258 /*
3259  *	vm_page_dequeue_deferred:	[ internal use only ]
3260  *
3261  *	Request removal of the given page from its current page
3262  *	queue.  Physical removal from the queue may be deferred
3263  *	indefinitely.
3264  *
3265  *	The page must be locked.
3266  */
3267 void
3268 vm_page_dequeue_deferred(vm_page_t m)
3269 {
3270 	uint8_t queue;
3271 
3272 	vm_page_assert_locked(m);
3273 
3274 	if ((queue = vm_page_queue(m)) == PQ_NONE)
3275 		return;
3276 	vm_page_aflag_set(m, PGA_DEQUEUE);
3277 	vm_pqbatch_submit_page(m, queue);
3278 }
3279 
3280 /*
3281  * A variant of vm_page_dequeue_deferred() that does not assert the page
3282  * lock and is only to be called from vm_page_free_prep().  It is just an
3283  * open-coded implementation of vm_page_dequeue_deferred().  Because the
3284  * page is being freed, we can assume that nothing else is scheduling queue
3285  * operations on this page, so we get for free the mutual exclusion that
3286  * is otherwise provided by the page lock.
3287  */
3288 static void
3289 vm_page_dequeue_deferred_free(vm_page_t m)
3290 {
3291 	uint8_t queue;
3292 
3293 	KASSERT(m->object == NULL, ("page %p has an object reference", m));
3294 
3295 	if ((m->aflags & PGA_DEQUEUE) != 0)
3296 		return;
3297 	atomic_thread_fence_acq();
3298 	if ((queue = m->queue) == PQ_NONE)
3299 		return;
3300 	vm_page_aflag_set(m, PGA_DEQUEUE);
3301 	vm_pqbatch_submit_page(m, queue);
3302 }
3303 
3304 /*
3305  *	vm_page_dequeue:
3306  *
3307  *	Remove the page from whichever page queue it's in, if any.
3308  *	The page must either be locked or unallocated.  This constraint
3309  *	ensures that the queue state of the page will remain consistent
3310  *	after this function returns.
3311  */
3312 void
3313 vm_page_dequeue(vm_page_t m)
3314 {
3315 	struct mtx *lock, *lock1;
3316 	struct vm_pagequeue *pq;
3317 	uint8_t aflags;
3318 
3319 	KASSERT(mtx_owned(vm_page_lockptr(m)) || m->order == VM_NFREEORDER,
3320 	    ("page %p is allocated and unlocked", m));
3321 
3322 	for (;;) {
3323 		lock = vm_page_pagequeue_lockptr(m);
3324 		if (lock == NULL) {
3325 			/*
3326 			 * A thread may be concurrently executing
3327 			 * vm_page_dequeue_complete().  Ensure that all queue
3328 			 * state is cleared before we return.
3329 			 */
3330 			aflags = atomic_load_8(&m->aflags);
3331 			if ((aflags & PGA_QUEUE_STATE_MASK) == 0)
3332 				return;
3333 			KASSERT((aflags & PGA_DEQUEUE) != 0,
3334 			    ("page %p has unexpected queue state flags %#x",
3335 			    m, aflags));
3336 
3337 			/*
3338 			 * Busy wait until the thread updating queue state is
3339 			 * finished.  Such a thread must be executing in a
3340 			 * critical section.
3341 			 */
3342 			cpu_spinwait();
3343 			continue;
3344 		}
3345 		mtx_lock(lock);
3346 		if ((lock1 = vm_page_pagequeue_lockptr(m)) == lock)
3347 			break;
3348 		mtx_unlock(lock);
3349 		lock = lock1;
3350 	}
3351 	KASSERT(lock == vm_page_pagequeue_lockptr(m),
3352 	    ("%s: page %p migrated directly between queues", __func__, m));
3353 	KASSERT((m->aflags & PGA_DEQUEUE) != 0 ||
3354 	    mtx_owned(vm_page_lockptr(m)),
3355 	    ("%s: queued unlocked page %p", __func__, m));
3356 
3357 	if ((m->aflags & PGA_ENQUEUED) != 0) {
3358 		pq = vm_page_pagequeue(m);
3359 		TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3360 		vm_pagequeue_cnt_dec(pq);
3361 	}
3362 	vm_page_dequeue_complete(m);
3363 	mtx_unlock(lock);
3364 }
3365 
3366 /*
3367  * Schedule the given page for insertion into the specified page queue.
3368  * Physical insertion of the page may be deferred indefinitely.
3369  */
3370 static void
3371 vm_page_enqueue(vm_page_t m, uint8_t queue)
3372 {
3373 
3374 	vm_page_assert_locked(m);
3375 	KASSERT(m->queue == PQ_NONE && (m->aflags & PGA_QUEUE_STATE_MASK) == 0,
3376 	    ("%s: page %p is already enqueued", __func__, m));
3377 
3378 	m->queue = queue;
3379 	if ((m->aflags & PGA_REQUEUE) == 0)
3380 		vm_page_aflag_set(m, PGA_REQUEUE);
3381 	vm_pqbatch_submit_page(m, queue);
3382 }
3383 
3384 /*
3385  *	vm_page_requeue:		[ internal use only ]
3386  *
3387  *	Schedule a requeue of the given page.
3388  *
3389  *	The page must be locked.
3390  */
3391 void
3392 vm_page_requeue(vm_page_t m)
3393 {
3394 
3395 	vm_page_assert_locked(m);
3396 	KASSERT(vm_page_queue(m) != PQ_NONE,
3397 	    ("%s: page %p is not logically enqueued", __func__, m));
3398 
3399 	if ((m->aflags & PGA_REQUEUE) == 0)
3400 		vm_page_aflag_set(m, PGA_REQUEUE);
3401 	vm_pqbatch_submit_page(m, atomic_load_8(&m->queue));
3402 }
3403 
3404 /*
3405  *	vm_page_free_prep:
3406  *
3407  *	Prepares the given page to be put on the free list,
3408  *	disassociating it from any VM object. The caller may return
3409  *	the page to the free list only if this function returns true.
3410  *
3411  *	The object must be locked.  The page must be locked if it is
3412  *	managed.
3413  */
3414 bool
3415 vm_page_free_prep(vm_page_t m)
3416 {
3417 
3418 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
3419 	if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
3420 		uint64_t *p;
3421 		int i;
3422 		p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3423 		for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
3424 			KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
3425 			    m, i, (uintmax_t)*p));
3426 	}
3427 #endif
3428 	if ((m->oflags & VPO_UNMANAGED) == 0) {
3429 		vm_page_lock_assert(m, MA_OWNED);
3430 		KASSERT(!pmap_page_is_mapped(m),
3431 		    ("vm_page_free_prep: freeing mapped page %p", m));
3432 	} else
3433 		KASSERT(m->queue == PQ_NONE,
3434 		    ("vm_page_free_prep: unmanaged page %p is queued", m));
3435 	VM_CNT_INC(v_tfree);
3436 
3437 	if (vm_page_sbusied(m))
3438 		panic("vm_page_free_prep: freeing busy page %p", m);
3439 
3440 	if (m->object != NULL)
3441 		(void)vm_page_remove(m);
3442 
3443 	/*
3444 	 * If fictitious remove object association and
3445 	 * return.
3446 	 */
3447 	if ((m->flags & PG_FICTITIOUS) != 0) {
3448 		KASSERT(m->wire_count == 1,
3449 		    ("fictitious page %p is not wired", m));
3450 		KASSERT(m->queue == PQ_NONE,
3451 		    ("fictitious page %p is queued", m));
3452 		return (false);
3453 	}
3454 
3455 	/*
3456 	 * Pages need not be dequeued before they are returned to the physical
3457 	 * memory allocator, but they must at least be marked for a deferred
3458 	 * dequeue.
3459 	 */
3460 	if ((m->oflags & VPO_UNMANAGED) == 0)
3461 		vm_page_dequeue_deferred_free(m);
3462 
3463 	m->valid = 0;
3464 	vm_page_undirty(m);
3465 
3466 	if (vm_page_wired(m) != 0)
3467 		panic("vm_page_free_prep: freeing wired page %p", m);
3468 	if (m->hold_count != 0) {
3469 		m->flags &= ~PG_ZERO;
3470 		KASSERT((m->flags & PG_UNHOLDFREE) == 0,
3471 		    ("vm_page_free_prep: freeing PG_UNHOLDFREE page %p", m));
3472 		m->flags |= PG_UNHOLDFREE;
3473 		return (false);
3474 	}
3475 
3476 	/*
3477 	 * Restore the default memory attribute to the page.
3478 	 */
3479 	if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3480 		pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3481 
3482 #if VM_NRESERVLEVEL > 0
3483 	if (vm_reserv_free_page(m))
3484 		return (false);
3485 #endif
3486 
3487 	return (true);
3488 }
3489 
3490 /*
3491  *	vm_page_free_toq:
3492  *
3493  *	Returns the given page to the free list, disassociating it
3494  *	from any VM object.
3495  *
3496  *	The object must be locked.  The page must be locked if it is
3497  *	managed.
3498  */
3499 void
3500 vm_page_free_toq(vm_page_t m)
3501 {
3502 	struct vm_domain *vmd;
3503 
3504 	if (!vm_page_free_prep(m))
3505 		return;
3506 
3507 	vmd = vm_pagequeue_domain(m);
3508 	if ((m->flags & PG_PCPU_CACHE) != 0 && vmd->vmd_pgcache != NULL) {
3509 		uma_zfree(vmd->vmd_pgcache, m);
3510 		return;
3511 	}
3512 	vm_domain_free_lock(vmd);
3513 	vm_phys_free_pages(m, 0);
3514 	vm_domain_free_unlock(vmd);
3515 	vm_domain_freecnt_inc(vmd, 1);
3516 }
3517 
3518 /*
3519  *	vm_page_free_pages_toq:
3520  *
3521  *	Returns a list of pages to the free list, disassociating it
3522  *	from any VM object.  In other words, this is equivalent to
3523  *	calling vm_page_free_toq() for each page of a list of VM objects.
3524  *
3525  *	The objects must be locked.  The pages must be locked if it is
3526  *	managed.
3527  */
3528 void
3529 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
3530 {
3531 	vm_page_t m;
3532 	int count;
3533 
3534 	if (SLIST_EMPTY(free))
3535 		return;
3536 
3537 	count = 0;
3538 	while ((m = SLIST_FIRST(free)) != NULL) {
3539 		count++;
3540 		SLIST_REMOVE_HEAD(free, plinks.s.ss);
3541 		vm_page_free_toq(m);
3542 	}
3543 
3544 	if (update_wire_count)
3545 		vm_wire_sub(count);
3546 }
3547 
3548 /*
3549  *	vm_page_wire:
3550  *
3551  * Mark this page as wired down.  If the page is fictitious, then
3552  * its wire count must remain one.
3553  *
3554  * The page must be locked.
3555  */
3556 void
3557 vm_page_wire(vm_page_t m)
3558 {
3559 
3560 	vm_page_assert_locked(m);
3561 	if ((m->flags & PG_FICTITIOUS) != 0) {
3562 		KASSERT(m->wire_count == 1,
3563 		    ("vm_page_wire: fictitious page %p's wire count isn't one",
3564 		    m));
3565 		return;
3566 	}
3567 	if (!vm_page_wired(m)) {
3568 		KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
3569 		    m->queue == PQ_NONE,
3570 		    ("vm_page_wire: unmanaged page %p is queued", m));
3571 		vm_wire_add(1);
3572 	}
3573 	m->wire_count++;
3574 	KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
3575 }
3576 
3577 /*
3578  * vm_page_unwire:
3579  *
3580  * Release one wiring of the specified page, potentially allowing it to be
3581  * paged out.  Returns TRUE if the number of wirings transitions to zero and
3582  * FALSE otherwise.
3583  *
3584  * Only managed pages belonging to an object can be paged out.  If the number
3585  * of wirings transitions to zero and the page is eligible for page out, then
3586  * the page is added to the specified paging queue (unless PQ_NONE is
3587  * specified, in which case the page is dequeued if it belongs to a paging
3588  * queue).
3589  *
3590  * If a page is fictitious, then its wire count must always be one.
3591  *
3592  * A managed page must be locked.
3593  */
3594 bool
3595 vm_page_unwire(vm_page_t m, uint8_t queue)
3596 {
3597 	bool unwired;
3598 
3599 	KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
3600 	    ("vm_page_unwire: invalid queue %u request for page %p",
3601 	    queue, m));
3602 	if ((m->oflags & VPO_UNMANAGED) == 0)
3603 		vm_page_assert_locked(m);
3604 
3605 	unwired = vm_page_unwire_noq(m);
3606 	if (!unwired || (m->oflags & VPO_UNMANAGED) != 0 || m->object == NULL)
3607 		return (unwired);
3608 
3609 	if (vm_page_queue(m) == queue) {
3610 		if (queue == PQ_ACTIVE)
3611 			vm_page_reference(m);
3612 		else if (queue != PQ_NONE)
3613 			vm_page_requeue(m);
3614 	} else {
3615 		vm_page_dequeue(m);
3616 		if (queue != PQ_NONE) {
3617 			vm_page_enqueue(m, queue);
3618 			if (queue == PQ_ACTIVE)
3619 				/* Initialize act_count. */
3620 				vm_page_activate(m);
3621 		}
3622 	}
3623 	return (unwired);
3624 }
3625 
3626 /*
3627  *
3628  * vm_page_unwire_noq:
3629  *
3630  * Unwire a page without (re-)inserting it into a page queue.  It is up
3631  * to the caller to enqueue, requeue, or free the page as appropriate.
3632  * In most cases, vm_page_unwire() should be used instead.
3633  */
3634 bool
3635 vm_page_unwire_noq(vm_page_t m)
3636 {
3637 
3638 	if ((m->oflags & VPO_UNMANAGED) == 0)
3639 		vm_page_assert_locked(m);
3640 	if ((m->flags & PG_FICTITIOUS) != 0) {
3641 		KASSERT(m->wire_count == 1,
3642 	    ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
3643 		return (false);
3644 	}
3645 	if (!vm_page_wired(m))
3646 		panic("vm_page_unwire: page %p's wire count is zero", m);
3647 	m->wire_count--;
3648 	if (m->wire_count == 0) {
3649 		vm_wire_sub(1);
3650 		return (true);
3651 	} else
3652 		return (false);
3653 }
3654 
3655 /*
3656  *	vm_page_activate:
3657  *
3658  *	Put the specified page on the active list (if appropriate).
3659  *	Ensure that act_count is at least ACT_INIT but do not otherwise
3660  *	mess with it.
3661  *
3662  *	The page must be locked.
3663  */
3664 void
3665 vm_page_activate(vm_page_t m)
3666 {
3667 
3668 	vm_page_assert_locked(m);
3669 
3670 	if (vm_page_wired(m) || (m->oflags & VPO_UNMANAGED) != 0)
3671 		return;
3672 	if (vm_page_queue(m) == PQ_ACTIVE) {
3673 		if (m->act_count < ACT_INIT)
3674 			m->act_count = ACT_INIT;
3675 		return;
3676 	}
3677 
3678 	vm_page_dequeue(m);
3679 	if (m->act_count < ACT_INIT)
3680 		m->act_count = ACT_INIT;
3681 	vm_page_enqueue(m, PQ_ACTIVE);
3682 }
3683 
3684 /*
3685  * Move the specified page to the tail of the inactive queue, or requeue
3686  * the page if it is already in the inactive queue.
3687  *
3688  * The page must be locked.
3689  */
3690 void
3691 vm_page_deactivate(vm_page_t m)
3692 {
3693 
3694 	vm_page_assert_locked(m);
3695 
3696 	if (vm_page_wired(m) || (m->oflags & VPO_UNMANAGED) != 0)
3697 		return;
3698 
3699 	if (!vm_page_inactive(m)) {
3700 		vm_page_dequeue(m);
3701 		vm_page_enqueue(m, PQ_INACTIVE);
3702 	} else
3703 		vm_page_requeue(m);
3704 }
3705 
3706 /*
3707  * Move the specified page close to the head of the inactive queue,
3708  * bypassing LRU.  A marker page is used to maintain FIFO ordering.
3709  * As with regular enqueues, we use a per-CPU batch queue to reduce
3710  * contention on the page queue lock.
3711  *
3712  * The page must be locked.
3713  */
3714 void
3715 vm_page_deactivate_noreuse(vm_page_t m)
3716 {
3717 
3718 	vm_page_assert_locked(m);
3719 
3720 	if (vm_page_wired(m) || (m->oflags & VPO_UNMANAGED) != 0)
3721 		return;
3722 
3723 	if (!vm_page_inactive(m)) {
3724 		vm_page_dequeue(m);
3725 		m->queue = PQ_INACTIVE;
3726 	}
3727 	if ((m->aflags & PGA_REQUEUE_HEAD) == 0)
3728 		vm_page_aflag_set(m, PGA_REQUEUE_HEAD);
3729 	vm_pqbatch_submit_page(m, PQ_INACTIVE);
3730 }
3731 
3732 /*
3733  * vm_page_launder
3734  *
3735  * 	Put a page in the laundry, or requeue it if it is already there.
3736  */
3737 void
3738 vm_page_launder(vm_page_t m)
3739 {
3740 
3741 	vm_page_assert_locked(m);
3742 	if (vm_page_wired(m) || (m->oflags & VPO_UNMANAGED) != 0)
3743 		return;
3744 
3745 	if (vm_page_in_laundry(m))
3746 		vm_page_requeue(m);
3747 	else {
3748 		vm_page_dequeue(m);
3749 		vm_page_enqueue(m, PQ_LAUNDRY);
3750 	}
3751 }
3752 
3753 /*
3754  * vm_page_unswappable
3755  *
3756  *	Put a page in the PQ_UNSWAPPABLE holding queue.
3757  */
3758 void
3759 vm_page_unswappable(vm_page_t m)
3760 {
3761 
3762 	vm_page_assert_locked(m);
3763 	KASSERT(!vm_page_wired(m) && (m->oflags & VPO_UNMANAGED) == 0,
3764 	    ("page %p already unswappable", m));
3765 
3766 	vm_page_dequeue(m);
3767 	vm_page_enqueue(m, PQ_UNSWAPPABLE);
3768 }
3769 
3770 /*
3771  * Attempt to free the page.  If it cannot be freed, do nothing.  Returns true
3772  * if the page is freed and false otherwise.
3773  *
3774  * The page must be managed.  The page and its containing object must be
3775  * locked.
3776  */
3777 bool
3778 vm_page_try_to_free(vm_page_t m)
3779 {
3780 
3781 	vm_page_assert_locked(m);
3782 	VM_OBJECT_ASSERT_WLOCKED(m->object);
3783 	KASSERT((m->oflags & VPO_UNMANAGED) == 0, ("page %p is unmanaged", m));
3784 	if (m->dirty != 0 || vm_page_held(m) || vm_page_busied(m))
3785 		return (false);
3786 	if (m->object->ref_count != 0) {
3787 		pmap_remove_all(m);
3788 		if (m->dirty != 0)
3789 			return (false);
3790 	}
3791 	vm_page_free(m);
3792 	return (true);
3793 }
3794 
3795 /*
3796  * vm_page_advise
3797  *
3798  * 	Apply the specified advice to the given page.
3799  *
3800  *	The object and page must be locked.
3801  */
3802 void
3803 vm_page_advise(vm_page_t m, int advice)
3804 {
3805 
3806 	vm_page_assert_locked(m);
3807 	VM_OBJECT_ASSERT_WLOCKED(m->object);
3808 	if (advice == MADV_FREE)
3809 		/*
3810 		 * Mark the page clean.  This will allow the page to be freed
3811 		 * without first paging it out.  MADV_FREE pages are often
3812 		 * quickly reused by malloc(3), so we do not do anything that
3813 		 * would result in a page fault on a later access.
3814 		 */
3815 		vm_page_undirty(m);
3816 	else if (advice != MADV_DONTNEED) {
3817 		if (advice == MADV_WILLNEED)
3818 			vm_page_activate(m);
3819 		return;
3820 	}
3821 
3822 	/*
3823 	 * Clear any references to the page.  Otherwise, the page daemon will
3824 	 * immediately reactivate the page.
3825 	 */
3826 	vm_page_aflag_clear(m, PGA_REFERENCED);
3827 
3828 	if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3829 		vm_page_dirty(m);
3830 
3831 	/*
3832 	 * Place clean pages near the head of the inactive queue rather than
3833 	 * the tail, thus defeating the queue's LRU operation and ensuring that
3834 	 * the page will be reused quickly.  Dirty pages not already in the
3835 	 * laundry are moved there.
3836 	 */
3837 	if (m->dirty == 0)
3838 		vm_page_deactivate_noreuse(m);
3839 	else if (!vm_page_in_laundry(m))
3840 		vm_page_launder(m);
3841 }
3842 
3843 /*
3844  * Grab a page, waiting until we are waken up due to the page
3845  * changing state.  We keep on waiting, if the page continues
3846  * to be in the object.  If the page doesn't exist, first allocate it
3847  * and then conditionally zero it.
3848  *
3849  * This routine may sleep.
3850  *
3851  * The object must be locked on entry.  The lock will, however, be released
3852  * and reacquired if the routine sleeps.
3853  */
3854 vm_page_t
3855 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3856 {
3857 	vm_page_t m;
3858 	int sleep;
3859 	int pflags;
3860 
3861 	VM_OBJECT_ASSERT_WLOCKED(object);
3862 	KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3863 	    (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3864 	    ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3865 	pflags = allocflags &
3866 	    ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
3867 	if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3868 		pflags |= VM_ALLOC_WAITFAIL;
3869 retrylookup:
3870 	if ((m = vm_page_lookup(object, pindex)) != NULL) {
3871 		sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3872 		    vm_page_xbusied(m) : vm_page_busied(m);
3873 		if (sleep) {
3874 			if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3875 				return (NULL);
3876 			/*
3877 			 * Reference the page before unlocking and
3878 			 * sleeping so that the page daemon is less
3879 			 * likely to reclaim it.
3880 			 */
3881 			vm_page_aflag_set(m, PGA_REFERENCED);
3882 			vm_page_lock(m);
3883 			VM_OBJECT_WUNLOCK(object);
3884 			vm_page_busy_sleep(m, "pgrbwt", (allocflags &
3885 			    VM_ALLOC_IGN_SBUSY) != 0);
3886 			VM_OBJECT_WLOCK(object);
3887 			goto retrylookup;
3888 		} else {
3889 			if ((allocflags & VM_ALLOC_WIRED) != 0) {
3890 				vm_page_lock(m);
3891 				vm_page_wire(m);
3892 				vm_page_unlock(m);
3893 			}
3894 			if ((allocflags &
3895 			    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3896 				vm_page_xbusy(m);
3897 			if ((allocflags & VM_ALLOC_SBUSY) != 0)
3898 				vm_page_sbusy(m);
3899 			return (m);
3900 		}
3901 	}
3902 	m = vm_page_alloc(object, pindex, pflags);
3903 	if (m == NULL) {
3904 		if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3905 			return (NULL);
3906 		goto retrylookup;
3907 	}
3908 	if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3909 		pmap_zero_page(m);
3910 	return (m);
3911 }
3912 
3913 /*
3914  * Return the specified range of pages from the given object.  For each
3915  * page offset within the range, if a page already exists within the object
3916  * at that offset and it is busy, then wait for it to change state.  If,
3917  * instead, the page doesn't exist, then allocate it.
3918  *
3919  * The caller must always specify an allocation class.
3920  *
3921  * allocation classes:
3922  *	VM_ALLOC_NORMAL		normal process request
3923  *	VM_ALLOC_SYSTEM		system *really* needs the pages
3924  *
3925  * The caller must always specify that the pages are to be busied and/or
3926  * wired.
3927  *
3928  * optional allocation flags:
3929  *	VM_ALLOC_IGN_SBUSY	do not sleep on soft busy pages
3930  *	VM_ALLOC_NOBUSY		do not exclusive busy the page
3931  *	VM_ALLOC_NOWAIT		do not sleep
3932  *	VM_ALLOC_SBUSY		set page to sbusy state
3933  *	VM_ALLOC_WIRED		wire the pages
3934  *	VM_ALLOC_ZERO		zero and validate any invalid pages
3935  *
3936  * If VM_ALLOC_NOWAIT is not specified, this routine may sleep.  Otherwise, it
3937  * may return a partial prefix of the requested range.
3938  */
3939 int
3940 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
3941     vm_page_t *ma, int count)
3942 {
3943 	vm_page_t m, mpred;
3944 	int pflags;
3945 	int i;
3946 	bool sleep;
3947 
3948 	VM_OBJECT_ASSERT_WLOCKED(object);
3949 	KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
3950 	    ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
3951 	KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
3952 	    (allocflags & VM_ALLOC_WIRED) != 0,
3953 	    ("vm_page_grab_pages: the pages must be busied or wired"));
3954 	KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3955 	    (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3956 	    ("vm_page_grab_pages: VM_ALLOC_SBUSY/IGN_SBUSY mismatch"));
3957 	if (count == 0)
3958 		return (0);
3959 	pflags = allocflags & ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK |
3960 	    VM_ALLOC_WAITFAIL | VM_ALLOC_IGN_SBUSY);
3961 	if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3962 		pflags |= VM_ALLOC_WAITFAIL;
3963 	i = 0;
3964 retrylookup:
3965 	m = vm_radix_lookup_le(&object->rtree, pindex + i);
3966 	if (m == NULL || m->pindex != pindex + i) {
3967 		mpred = m;
3968 		m = NULL;
3969 	} else
3970 		mpred = TAILQ_PREV(m, pglist, listq);
3971 	for (; i < count; i++) {
3972 		if (m != NULL) {
3973 			sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3974 			    vm_page_xbusied(m) : vm_page_busied(m);
3975 			if (sleep) {
3976 				if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3977 					break;
3978 				/*
3979 				 * Reference the page before unlocking and
3980 				 * sleeping so that the page daemon is less
3981 				 * likely to reclaim it.
3982 				 */
3983 				vm_page_aflag_set(m, PGA_REFERENCED);
3984 				vm_page_lock(m);
3985 				VM_OBJECT_WUNLOCK(object);
3986 				vm_page_busy_sleep(m, "grbmaw", (allocflags &
3987 				    VM_ALLOC_IGN_SBUSY) != 0);
3988 				VM_OBJECT_WLOCK(object);
3989 				goto retrylookup;
3990 			}
3991 			if ((allocflags & VM_ALLOC_WIRED) != 0) {
3992 				vm_page_lock(m);
3993 				vm_page_wire(m);
3994 				vm_page_unlock(m);
3995 			}
3996 			if ((allocflags & (VM_ALLOC_NOBUSY |
3997 			    VM_ALLOC_SBUSY)) == 0)
3998 				vm_page_xbusy(m);
3999 			if ((allocflags & VM_ALLOC_SBUSY) != 0)
4000 				vm_page_sbusy(m);
4001 		} else {
4002 			m = vm_page_alloc_after(object, pindex + i,
4003 			    pflags | VM_ALLOC_COUNT(count - i), mpred);
4004 			if (m == NULL) {
4005 				if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4006 					break;
4007 				goto retrylookup;
4008 			}
4009 		}
4010 		if (m->valid == 0 && (allocflags & VM_ALLOC_ZERO) != 0) {
4011 			if ((m->flags & PG_ZERO) == 0)
4012 				pmap_zero_page(m);
4013 			m->valid = VM_PAGE_BITS_ALL;
4014 		}
4015 		ma[i] = mpred = m;
4016 		m = vm_page_next(m);
4017 	}
4018 	return (i);
4019 }
4020 
4021 /*
4022  * Mapping function for valid or dirty bits in a page.
4023  *
4024  * Inputs are required to range within a page.
4025  */
4026 vm_page_bits_t
4027 vm_page_bits(int base, int size)
4028 {
4029 	int first_bit;
4030 	int last_bit;
4031 
4032 	KASSERT(
4033 	    base + size <= PAGE_SIZE,
4034 	    ("vm_page_bits: illegal base/size %d/%d", base, size)
4035 	);
4036 
4037 	if (size == 0)		/* handle degenerate case */
4038 		return (0);
4039 
4040 	first_bit = base >> DEV_BSHIFT;
4041 	last_bit = (base + size - 1) >> DEV_BSHIFT;
4042 
4043 	return (((vm_page_bits_t)2 << last_bit) -
4044 	    ((vm_page_bits_t)1 << first_bit));
4045 }
4046 
4047 /*
4048  *	vm_page_set_valid_range:
4049  *
4050  *	Sets portions of a page valid.  The arguments are expected
4051  *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4052  *	of any partial chunks touched by the range.  The invalid portion of
4053  *	such chunks will be zeroed.
4054  *
4055  *	(base + size) must be less then or equal to PAGE_SIZE.
4056  */
4057 void
4058 vm_page_set_valid_range(vm_page_t m, int base, int size)
4059 {
4060 	int endoff, frag;
4061 
4062 	VM_OBJECT_ASSERT_WLOCKED(m->object);
4063 	if (size == 0)	/* handle degenerate case */
4064 		return;
4065 
4066 	/*
4067 	 * If the base is not DEV_BSIZE aligned and the valid
4068 	 * bit is clear, we have to zero out a portion of the
4069 	 * first block.
4070 	 */
4071 	if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4072 	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
4073 		pmap_zero_page_area(m, frag, base - frag);
4074 
4075 	/*
4076 	 * If the ending offset is not DEV_BSIZE aligned and the
4077 	 * valid bit is clear, we have to zero out a portion of
4078 	 * the last block.
4079 	 */
4080 	endoff = base + size;
4081 	if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4082 	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
4083 		pmap_zero_page_area(m, endoff,
4084 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4085 
4086 	/*
4087 	 * Assert that no previously invalid block that is now being validated
4088 	 * is already dirty.
4089 	 */
4090 	KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
4091 	    ("vm_page_set_valid_range: page %p is dirty", m));
4092 
4093 	/*
4094 	 * Set valid bits inclusive of any overlap.
4095 	 */
4096 	m->valid |= vm_page_bits(base, size);
4097 }
4098 
4099 /*
4100  * Clear the given bits from the specified page's dirty field.
4101  */
4102 static __inline void
4103 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
4104 {
4105 	uintptr_t addr;
4106 #if PAGE_SIZE < 16384
4107 	int shift;
4108 #endif
4109 
4110 	/*
4111 	 * If the object is locked and the page is neither exclusive busy nor
4112 	 * write mapped, then the page's dirty field cannot possibly be
4113 	 * set by a concurrent pmap operation.
4114 	 */
4115 	VM_OBJECT_ASSERT_WLOCKED(m->object);
4116 	if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
4117 		m->dirty &= ~pagebits;
4118 	else {
4119 		/*
4120 		 * The pmap layer can call vm_page_dirty() without
4121 		 * holding a distinguished lock.  The combination of
4122 		 * the object's lock and an atomic operation suffice
4123 		 * to guarantee consistency of the page dirty field.
4124 		 *
4125 		 * For PAGE_SIZE == 32768 case, compiler already
4126 		 * properly aligns the dirty field, so no forcible
4127 		 * alignment is needed. Only require existence of
4128 		 * atomic_clear_64 when page size is 32768.
4129 		 */
4130 		addr = (uintptr_t)&m->dirty;
4131 #if PAGE_SIZE == 32768
4132 		atomic_clear_64((uint64_t *)addr, pagebits);
4133 #elif PAGE_SIZE == 16384
4134 		atomic_clear_32((uint32_t *)addr, pagebits);
4135 #else		/* PAGE_SIZE <= 8192 */
4136 		/*
4137 		 * Use a trick to perform a 32-bit atomic on the
4138 		 * containing aligned word, to not depend on the existence
4139 		 * of atomic_clear_{8, 16}.
4140 		 */
4141 		shift = addr & (sizeof(uint32_t) - 1);
4142 #if BYTE_ORDER == BIG_ENDIAN
4143 		shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
4144 #else
4145 		shift *= NBBY;
4146 #endif
4147 		addr &= ~(sizeof(uint32_t) - 1);
4148 		atomic_clear_32((uint32_t *)addr, pagebits << shift);
4149 #endif		/* PAGE_SIZE */
4150 	}
4151 }
4152 
4153 /*
4154  *	vm_page_set_validclean:
4155  *
4156  *	Sets portions of a page valid and clean.  The arguments are expected
4157  *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4158  *	of any partial chunks touched by the range.  The invalid portion of
4159  *	such chunks will be zero'd.
4160  *
4161  *	(base + size) must be less then or equal to PAGE_SIZE.
4162  */
4163 void
4164 vm_page_set_validclean(vm_page_t m, int base, int size)
4165 {
4166 	vm_page_bits_t oldvalid, pagebits;
4167 	int endoff, frag;
4168 
4169 	VM_OBJECT_ASSERT_WLOCKED(m->object);
4170 	if (size == 0)	/* handle degenerate case */
4171 		return;
4172 
4173 	/*
4174 	 * If the base is not DEV_BSIZE aligned and the valid
4175 	 * bit is clear, we have to zero out a portion of the
4176 	 * first block.
4177 	 */
4178 	if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4179 	    (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
4180 		pmap_zero_page_area(m, frag, base - frag);
4181 
4182 	/*
4183 	 * If the ending offset is not DEV_BSIZE aligned and the
4184 	 * valid bit is clear, we have to zero out a portion of
4185 	 * the last block.
4186 	 */
4187 	endoff = base + size;
4188 	if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4189 	    (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
4190 		pmap_zero_page_area(m, endoff,
4191 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4192 
4193 	/*
4194 	 * Set valid, clear dirty bits.  If validating the entire
4195 	 * page we can safely clear the pmap modify bit.  We also
4196 	 * use this opportunity to clear the VPO_NOSYNC flag.  If a process
4197 	 * takes a write fault on a MAP_NOSYNC memory area the flag will
4198 	 * be set again.
4199 	 *
4200 	 * We set valid bits inclusive of any overlap, but we can only
4201 	 * clear dirty bits for DEV_BSIZE chunks that are fully within
4202 	 * the range.
4203 	 */
4204 	oldvalid = m->valid;
4205 	pagebits = vm_page_bits(base, size);
4206 	m->valid |= pagebits;
4207 #if 0	/* NOT YET */
4208 	if ((frag = base & (DEV_BSIZE - 1)) != 0) {
4209 		frag = DEV_BSIZE - frag;
4210 		base += frag;
4211 		size -= frag;
4212 		if (size < 0)
4213 			size = 0;
4214 	}
4215 	pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
4216 #endif
4217 	if (base == 0 && size == PAGE_SIZE) {
4218 		/*
4219 		 * The page can only be modified within the pmap if it is
4220 		 * mapped, and it can only be mapped if it was previously
4221 		 * fully valid.
4222 		 */
4223 		if (oldvalid == VM_PAGE_BITS_ALL)
4224 			/*
4225 			 * Perform the pmap_clear_modify() first.  Otherwise,
4226 			 * a concurrent pmap operation, such as
4227 			 * pmap_protect(), could clear a modification in the
4228 			 * pmap and set the dirty field on the page before
4229 			 * pmap_clear_modify() had begun and after the dirty
4230 			 * field was cleared here.
4231 			 */
4232 			pmap_clear_modify(m);
4233 		m->dirty = 0;
4234 		m->oflags &= ~VPO_NOSYNC;
4235 	} else if (oldvalid != VM_PAGE_BITS_ALL)
4236 		m->dirty &= ~pagebits;
4237 	else
4238 		vm_page_clear_dirty_mask(m, pagebits);
4239 }
4240 
4241 void
4242 vm_page_clear_dirty(vm_page_t m, int base, int size)
4243 {
4244 
4245 	vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
4246 }
4247 
4248 /*
4249  *	vm_page_set_invalid:
4250  *
4251  *	Invalidates DEV_BSIZE'd chunks within a page.  Both the
4252  *	valid and dirty bits for the effected areas are cleared.
4253  */
4254 void
4255 vm_page_set_invalid(vm_page_t m, int base, int size)
4256 {
4257 	vm_page_bits_t bits;
4258 	vm_object_t object;
4259 
4260 	object = m->object;
4261 	VM_OBJECT_ASSERT_WLOCKED(object);
4262 	if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
4263 	    size >= object->un_pager.vnp.vnp_size)
4264 		bits = VM_PAGE_BITS_ALL;
4265 	else
4266 		bits = vm_page_bits(base, size);
4267 	if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
4268 	    bits != 0)
4269 		pmap_remove_all(m);
4270 	KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
4271 	    !pmap_page_is_mapped(m),
4272 	    ("vm_page_set_invalid: page %p is mapped", m));
4273 	m->valid &= ~bits;
4274 	m->dirty &= ~bits;
4275 }
4276 
4277 /*
4278  * vm_page_zero_invalid()
4279  *
4280  *	The kernel assumes that the invalid portions of a page contain
4281  *	garbage, but such pages can be mapped into memory by user code.
4282  *	When this occurs, we must zero out the non-valid portions of the
4283  *	page so user code sees what it expects.
4284  *
4285  *	Pages are most often semi-valid when the end of a file is mapped
4286  *	into memory and the file's size is not page aligned.
4287  */
4288 void
4289 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
4290 {
4291 	int b;
4292 	int i;
4293 
4294 	VM_OBJECT_ASSERT_WLOCKED(m->object);
4295 	/*
4296 	 * Scan the valid bits looking for invalid sections that
4297 	 * must be zeroed.  Invalid sub-DEV_BSIZE'd areas ( where the
4298 	 * valid bit may be set ) have already been zeroed by
4299 	 * vm_page_set_validclean().
4300 	 */
4301 	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
4302 		if (i == (PAGE_SIZE / DEV_BSIZE) ||
4303 		    (m->valid & ((vm_page_bits_t)1 << i))) {
4304 			if (i > b) {
4305 				pmap_zero_page_area(m,
4306 				    b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
4307 			}
4308 			b = i + 1;
4309 		}
4310 	}
4311 
4312 	/*
4313 	 * setvalid is TRUE when we can safely set the zero'd areas
4314 	 * as being valid.  We can do this if there are no cache consistancy
4315 	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
4316 	 */
4317 	if (setvalid)
4318 		m->valid = VM_PAGE_BITS_ALL;
4319 }
4320 
4321 /*
4322  *	vm_page_is_valid:
4323  *
4324  *	Is (partial) page valid?  Note that the case where size == 0
4325  *	will return FALSE in the degenerate case where the page is
4326  *	entirely invalid, and TRUE otherwise.
4327  */
4328 int
4329 vm_page_is_valid(vm_page_t m, int base, int size)
4330 {
4331 	vm_page_bits_t bits;
4332 
4333 	VM_OBJECT_ASSERT_LOCKED(m->object);
4334 	bits = vm_page_bits(base, size);
4335 	return (m->valid != 0 && (m->valid & bits) == bits);
4336 }
4337 
4338 /*
4339  * Returns true if all of the specified predicates are true for the entire
4340  * (super)page and false otherwise.
4341  */
4342 bool
4343 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
4344 {
4345 	vm_object_t object;
4346 	int i, npages;
4347 
4348 	object = m->object;
4349 	if (skip_m != NULL && skip_m->object != object)
4350 		return (false);
4351 	VM_OBJECT_ASSERT_LOCKED(object);
4352 	npages = atop(pagesizes[m->psind]);
4353 
4354 	/*
4355 	 * The physically contiguous pages that make up a superpage, i.e., a
4356 	 * page with a page size index ("psind") greater than zero, will
4357 	 * occupy adjacent entries in vm_page_array[].
4358 	 */
4359 	for (i = 0; i < npages; i++) {
4360 		/* Always test object consistency, including "skip_m". */
4361 		if (m[i].object != object)
4362 			return (false);
4363 		if (&m[i] == skip_m)
4364 			continue;
4365 		if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
4366 			return (false);
4367 		if ((flags & PS_ALL_DIRTY) != 0) {
4368 			/*
4369 			 * Calling vm_page_test_dirty() or pmap_is_modified()
4370 			 * might stop this case from spuriously returning
4371 			 * "false".  However, that would require a write lock
4372 			 * on the object containing "m[i]".
4373 			 */
4374 			if (m[i].dirty != VM_PAGE_BITS_ALL)
4375 				return (false);
4376 		}
4377 		if ((flags & PS_ALL_VALID) != 0 &&
4378 		    m[i].valid != VM_PAGE_BITS_ALL)
4379 			return (false);
4380 	}
4381 	return (true);
4382 }
4383 
4384 /*
4385  * Set the page's dirty bits if the page is modified.
4386  */
4387 void
4388 vm_page_test_dirty(vm_page_t m)
4389 {
4390 
4391 	VM_OBJECT_ASSERT_WLOCKED(m->object);
4392 	if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
4393 		vm_page_dirty(m);
4394 }
4395 
4396 void
4397 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
4398 {
4399 
4400 	mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
4401 }
4402 
4403 void
4404 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
4405 {
4406 
4407 	mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
4408 }
4409 
4410 int
4411 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
4412 {
4413 
4414 	return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
4415 }
4416 
4417 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
4418 void
4419 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
4420 {
4421 
4422 	vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
4423 }
4424 
4425 void
4426 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
4427 {
4428 
4429 	mtx_assert_(vm_page_lockptr(m), a, file, line);
4430 }
4431 #endif
4432 
4433 #ifdef INVARIANTS
4434 void
4435 vm_page_object_lock_assert(vm_page_t m)
4436 {
4437 
4438 	/*
4439 	 * Certain of the page's fields may only be modified by the
4440 	 * holder of the containing object's lock or the exclusive busy.
4441 	 * holder.  Unfortunately, the holder of the write busy is
4442 	 * not recorded, and thus cannot be checked here.
4443 	 */
4444 	if (m->object != NULL && !vm_page_xbusied(m))
4445 		VM_OBJECT_ASSERT_WLOCKED(m->object);
4446 }
4447 
4448 void
4449 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
4450 {
4451 
4452 	if ((bits & PGA_WRITEABLE) == 0)
4453 		return;
4454 
4455 	/*
4456 	 * The PGA_WRITEABLE flag can only be set if the page is
4457 	 * managed, is exclusively busied or the object is locked.
4458 	 * Currently, this flag is only set by pmap_enter().
4459 	 */
4460 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4461 	    ("PGA_WRITEABLE on unmanaged page"));
4462 	if (!vm_page_xbusied(m))
4463 		VM_OBJECT_ASSERT_LOCKED(m->object);
4464 }
4465 #endif
4466 
4467 #include "opt_ddb.h"
4468 #ifdef DDB
4469 #include <sys/kernel.h>
4470 
4471 #include <ddb/ddb.h>
4472 
4473 DB_SHOW_COMMAND(page, vm_page_print_page_info)
4474 {
4475 
4476 	db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
4477 	db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
4478 	db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
4479 	db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
4480 	db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
4481 	db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
4482 	db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
4483 	db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
4484 	db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
4485 }
4486 
4487 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
4488 {
4489 	int dom;
4490 
4491 	db_printf("pq_free %d\n", vm_free_count());
4492 	for (dom = 0; dom < vm_ndomains; dom++) {
4493 		db_printf(
4494     "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
4495 		    dom,
4496 		    vm_dom[dom].vmd_page_count,
4497 		    vm_dom[dom].vmd_free_count,
4498 		    vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
4499 		    vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
4500 		    vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
4501 		    vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
4502 	}
4503 }
4504 
4505 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
4506 {
4507 	vm_page_t m;
4508 	boolean_t phys, virt;
4509 
4510 	if (!have_addr) {
4511 		db_printf("show pginfo addr\n");
4512 		return;
4513 	}
4514 
4515 	phys = strchr(modif, 'p') != NULL;
4516 	virt = strchr(modif, 'v') != NULL;
4517 	if (virt)
4518 		m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
4519 	else if (phys)
4520 		m = PHYS_TO_VM_PAGE(addr);
4521 	else
4522 		m = (vm_page_t)addr;
4523 	db_printf(
4524     "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
4525     "  af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
4526 	    m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
4527 	    m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
4528 	    m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);
4529 }
4530 #endif /* DDB */
4531