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