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