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