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