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