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