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