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