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