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