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