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