vm_page.c revision 252161
1178479Sjb/*-
2178479Sjb * Copyright (c) 1991 Regents of the University of California.
3178479Sjb * All rights reserved.
4178479Sjb * Copyright (c) 1998 Matthew Dillon.  All Rights Reserved.
5178479Sjb *
6178479Sjb * This code is derived from software contributed to Berkeley by
7178479Sjb * The Mach Operating System project at Carnegie-Mellon University.
8178479Sjb *
9178479Sjb * Redistribution and use in source and binary forms, with or without
10178479Sjb * modification, are permitted provided that the following conditions
11178479Sjb * are met:
12178479Sjb * 1. Redistributions of source code must retain the above copyright
13178479Sjb *    notice, this list of conditions and the following disclaimer.
14178479Sjb * 2. Redistributions in binary form must reproduce the above copyright
15178479Sjb *    notice, this list of conditions and the following disclaimer in the
16178479Sjb *    documentation and/or other materials provided with the distribution.
17178479Sjb * 4. Neither the name of the University nor the names of its contributors
18178479Sjb *    may be used to endorse or promote products derived from this software
19178479Sjb *    without specific prior written permission.
20178479Sjb *
21178479Sjb * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22178479Sjb * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23178479Sjb * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24178479Sjb * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25178479Sjb * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26178479Sjb * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27178479Sjb * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28178479Sjb * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29178479Sjb * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30178479Sjb * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31178479Sjb * SUCH DAMAGE.
32178479Sjb *
33178479Sjb *	from: @(#)vm_page.c	7.4 (Berkeley) 5/7/91
34178479Sjb */
35178479Sjb
36178479Sjb/*-
37178479Sjb * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38178479Sjb * All rights reserved.
39178479Sjb *
40178479Sjb * Authors: Avadis Tevanian, Jr., Michael Wayne Young
41178479Sjb *
42178479Sjb * Permission to use, copy, modify and distribute this software and
43178479Sjb * its documentation is hereby granted, provided that both the copyright
44178479Sjb * notice and this permission notice appear in all copies of the
45178479Sjb * software, derivative works or modified versions, and any portions
46178479Sjb * thereof, and that both notices appear in supporting documentation.
47178479Sjb *
48178479Sjb * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49178479Sjb * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50178479Sjb * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51178479Sjb *
52178479Sjb * Carnegie Mellon requests users of this software to return to
53178479Sjb *
54178479Sjb *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
55178479Sjb *  School of Computer Science
56178479Sjb *  Carnegie Mellon University
57178479Sjb *  Pittsburgh PA 15213-3890
58178479Sjb *
59178479Sjb * any improvements or extensions that they make and grant Carnegie the
60178479Sjb * rights to redistribute these changes.
61178479Sjb */
62178479Sjb
63178479Sjb/*
64178479Sjb *			GENERAL RULES ON VM_PAGE MANIPULATION
65178479Sjb *
66178479Sjb *	- A page queue lock is required when adding or removing a page from a
67178479Sjb *	  page queue (vm_pagequeues[]), regardless of other locks or the
68178479Sjb *	  busy state of a page.
69178479Sjb *
70178479Sjb *		* In general, no thread besides the page daemon can acquire or
71178479Sjb *		  hold more than one page queue lock at a time.
72178479Sjb *
73178479Sjb *		* The page daemon can acquire and hold any pair of page queue
74178479Sjb *		  locks in any order.
75178479Sjb *
76178479Sjb *	- The object lock is required when inserting or removing
77178479Sjb *	  pages from an object (vm_page_insert() or vm_page_remove()).
78178479Sjb *
79178479Sjb */
80178479Sjb
81178479Sjb/*
82178479Sjb *	Resident memory management module.
83178479Sjb */
84178479Sjb
85178479Sjb#include <sys/cdefs.h>
86178479Sjb__FBSDID("$FreeBSD: head/sys/vm/vm_page.c 252161 2013-06-24 13:36:16Z glebius $");
87178479Sjb
88178479Sjb#include "opt_vm.h"
89178479Sjb
90178479Sjb#include <sys/param.h>
91178479Sjb#include <sys/systm.h>
92178479Sjb#include <sys/lock.h>
93178479Sjb#include <sys/kernel.h>
94178479Sjb#include <sys/limits.h>
95178479Sjb#include <sys/malloc.h>
96178479Sjb#include <sys/mman.h>
97178479Sjb#include <sys/msgbuf.h>
98178479Sjb#include <sys/mutex.h>
99178479Sjb#include <sys/proc.h>
100178479Sjb#include <sys/rwlock.h>
101178479Sjb#include <sys/sysctl.h>
102178479Sjb#include <sys/vmmeter.h>
103178479Sjb#include <sys/vnode.h>
104178479Sjb
105178479Sjb#include <vm/vm.h>
106178479Sjb#include <vm/pmap.h>
107178479Sjb#include <vm/vm_param.h>
108178479Sjb#include <vm/vm_kern.h>
109178479Sjb#include <vm/vm_object.h>
110178479Sjb#include <vm/vm_page.h>
111178479Sjb#include <vm/vm_pageout.h>
112178479Sjb#include <vm/vm_pager.h>
113178479Sjb#include <vm/vm_phys.h>
114178479Sjb#include <vm/vm_radix.h>
115178479Sjb#include <vm/vm_reserv.h>
116178479Sjb#include <vm/vm_extern.h>
117178479Sjb#include <vm/uma.h>
118178479Sjb#include <vm/uma_int.h>
119178479Sjb
120178479Sjb#include <machine/md_var.h>
121178479Sjb
122178479Sjb/*
123178479Sjb *	Associated with page of user-allocatable memory is a
124178479Sjb *	page structure.
125178479Sjb */
126178479Sjb
127178479Sjbstruct vm_pagequeue vm_pagequeues[PQ_COUNT] = {
128178479Sjb	[PQ_INACTIVE] = {
129178479Sjb		.pq_pl = TAILQ_HEAD_INITIALIZER(
130178479Sjb		    vm_pagequeues[PQ_INACTIVE].pq_pl),
131178479Sjb		.pq_cnt = &cnt.v_inactive_count,
132178479Sjb		.pq_name = "vm inactive pagequeue"
133178479Sjb	},
134178479Sjb	[PQ_ACTIVE] = {
135178479Sjb		.pq_pl = TAILQ_HEAD_INITIALIZER(
136178479Sjb		    vm_pagequeues[PQ_ACTIVE].pq_pl),
137178479Sjb		.pq_cnt = &cnt.v_active_count,
138178479Sjb		.pq_name = "vm active pagequeue"
139178479Sjb	}
140178479Sjb};
141178479Sjbstruct mtx_padalign vm_page_queue_free_mtx;
142178479Sjb
143178479Sjbstruct mtx_padalign pa_lock[PA_LOCK_COUNT];
144178479Sjb
145178479Sjbvm_page_t vm_page_array;
146178479Sjblong vm_page_array_size;
147178479Sjblong first_page;
148178479Sjbint vm_page_zero_count;
149178479Sjb
150178479Sjbstatic int boot_pages = UMA_BOOT_PAGES;
151178479SjbTUNABLE_INT("vm.boot_pages", &boot_pages);
152178479SjbSYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RD, &boot_pages, 0,
153178479Sjb	"number of pages allocated for bootstrapping the VM system");
154178479Sjb
155178479Sjbstatic int pa_tryrelock_restart;
156178479SjbSYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
157178479Sjb    &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
158178479Sjb
159178479Sjbstatic uma_zone_t fakepg_zone;
160178479Sjb
161178479Sjbstatic struct vnode *vm_page_alloc_init(vm_page_t m);
162178479Sjbstatic void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
163178479Sjbstatic void vm_page_enqueue(int queue, vm_page_t m);
164178479Sjbstatic void vm_page_init_fakepg(void *dummy);
165178479Sjbstatic void vm_page_insert_after(vm_page_t m, vm_object_t object,
166178479Sjb    vm_pindex_t pindex, vm_page_t mpred);
167178479Sjb
168178479SjbSYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init_fakepg, NULL);
169178479Sjb
170178479Sjbstatic void
171178479Sjbvm_page_init_fakepg(void *dummy)
172178479Sjb{
173178479Sjb
174178479Sjb	fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
175178479Sjb	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
176178479Sjb}
177178479Sjb
178178479Sjb/* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
179178479Sjb#if PAGE_SIZE == 32768
180178479Sjb#ifdef CTASSERT
181178479SjbCTASSERT(sizeof(u_long) >= 8);
182178479Sjb#endif
183178479Sjb#endif
184178479Sjb
185178479Sjb/*
186178479Sjb * Try to acquire a physical address lock while a pmap is locked.  If we
187178479Sjb * fail to trylock we unlock and lock the pmap directly and cache the
188178479Sjb * locked pa in *locked.  The caller should then restart their loop in case
189178479Sjb * the virtual to physical mapping has changed.
190178479Sjb */
191178479Sjbint
192178479Sjbvm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
193178479Sjb{
194178479Sjb	vm_paddr_t lockpa;
195178479Sjb
196178479Sjb	lockpa = *locked;
197178479Sjb	*locked = pa;
198178479Sjb	if (lockpa) {
199178479Sjb		PA_LOCK_ASSERT(lockpa, MA_OWNED);
200178479Sjb		if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
201178479Sjb			return (0);
202178479Sjb		PA_UNLOCK(lockpa);
203178479Sjb	}
204178479Sjb	if (PA_TRYLOCK(pa))
205178479Sjb		return (0);
206178479Sjb	PMAP_UNLOCK(pmap);
207178479Sjb	atomic_add_int(&pa_tryrelock_restart, 1);
208178479Sjb	PA_LOCK(pa);
209178479Sjb	PMAP_LOCK(pmap);
210178479Sjb	return (EAGAIN);
211178479Sjb}
212178479Sjb
213178479Sjb/*
214178479Sjb *	vm_set_page_size:
215178479Sjb *
216178479Sjb *	Sets the page size, perhaps based upon the memory
217178479Sjb *	size.  Must be called before any use of page-size
218178479Sjb *	dependent functions.
219178479Sjb */
220178479Sjbvoid
221178479Sjbvm_set_page_size(void)
222178479Sjb{
223178479Sjb	if (cnt.v_page_size == 0)
224178479Sjb		cnt.v_page_size = PAGE_SIZE;
225178479Sjb	if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0)
226178479Sjb		panic("vm_set_page_size: page size not a power of two");
227178479Sjb}
228178479Sjb
229178479Sjb/*
230178479Sjb *	vm_page_blacklist_lookup:
231178479Sjb *
232178479Sjb *	See if a physical address in this page has been listed
233178479Sjb *	in the blacklist tunable.  Entries in the tunable are
234178479Sjb *	separated by spaces or commas.  If an invalid integer is
235178479Sjb *	encountered then the rest of the string is skipped.
236178479Sjb */
237178479Sjbstatic int
238178479Sjbvm_page_blacklist_lookup(char *list, vm_paddr_t pa)
239178479Sjb{
240178479Sjb	vm_paddr_t bad;
241178479Sjb	char *cp, *pos;
242178479Sjb
243178479Sjb	for (pos = list; *pos != '\0'; pos = cp) {
244178479Sjb		bad = strtoq(pos, &cp, 0);
245178479Sjb		if (*cp != '\0') {
246178479Sjb			if (*cp == ' ' || *cp == ',') {
247178479Sjb				cp++;
248178479Sjb				if (cp == pos)
249178479Sjb					continue;
250178479Sjb			} else
251178479Sjb				break;
252178479Sjb		}
253178479Sjb		if (pa == trunc_page(bad))
254178479Sjb			return (1);
255178479Sjb	}
256178479Sjb	return (0);
257178479Sjb}
258178479Sjb
259178479Sjb/*
260178479Sjb *	vm_page_startup:
261178479Sjb *
262178479Sjb *	Initializes the resident memory module.
263178479Sjb *
264178479Sjb *	Allocates memory for the page cells, and
265178479Sjb *	for the object/offset-to-page hash table headers.
266178479Sjb *	Each page cell is initialized and placed on the free list.
267178479Sjb */
268178479Sjbvm_offset_t
269178479Sjbvm_page_startup(vm_offset_t vaddr)
270178479Sjb{
271178479Sjb	vm_offset_t mapped;
272178479Sjb	vm_paddr_t page_range;
273178479Sjb	vm_paddr_t new_end;
274178479Sjb	int i;
275178479Sjb	vm_paddr_t pa;
276178479Sjb	vm_paddr_t last_pa;
277178479Sjb	char *list;
278178479Sjb
279178479Sjb	/* the biggest memory array is the second group of pages */
280178479Sjb	vm_paddr_t end;
281178479Sjb	vm_paddr_t biggestsize;
282178479Sjb	vm_paddr_t low_water, high_water;
283178479Sjb	int biggestone;
284178479Sjb
285178479Sjb	biggestsize = 0;
286178479Sjb	biggestone = 0;
287178479Sjb	vaddr = round_page(vaddr);
288178479Sjb
289178479Sjb	for (i = 0; phys_avail[i + 1]; i += 2) {
290178479Sjb		phys_avail[i] = round_page(phys_avail[i]);
291178479Sjb		phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
292178479Sjb	}
293178479Sjb
294178479Sjb	low_water = phys_avail[0];
295178479Sjb	high_water = phys_avail[1];
296178479Sjb
297178479Sjb	for (i = 0; phys_avail[i + 1]; i += 2) {
298178479Sjb		vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
299178479Sjb
300178479Sjb		if (size > biggestsize) {
301178479Sjb			biggestone = i;
302178479Sjb			biggestsize = size;
303178479Sjb		}
304178479Sjb		if (phys_avail[i] < low_water)
305178479Sjb			low_water = phys_avail[i];
306178479Sjb		if (phys_avail[i + 1] > high_water)
307178479Sjb			high_water = phys_avail[i + 1];
308178479Sjb	}
309178479Sjb
310178479Sjb#ifdef XEN
311178479Sjb	low_water = 0;
312178479Sjb#endif
313178479Sjb
314178479Sjb	end = phys_avail[biggestone+1];
315178479Sjb
316178479Sjb	/*
317178479Sjb	 * Initialize the page and queue locks.
318178479Sjb	 */
319178479Sjb	mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
320178479Sjb	for (i = 0; i < PA_LOCK_COUNT; i++)
321178479Sjb		mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
322178479Sjb	for (i = 0; i < PQ_COUNT; i++)
323178479Sjb		vm_pagequeue_init_lock(&vm_pagequeues[i]);
324178479Sjb
325178479Sjb	/*
326178479Sjb	 * Allocate memory for use when boot strapping the kernel memory
327178479Sjb	 * allocator.
328178479Sjb	 */
329178479Sjb	new_end = end - (boot_pages * UMA_SLAB_SIZE);
330178479Sjb	new_end = trunc_page(new_end);
331178479Sjb	mapped = pmap_map(&vaddr, new_end, end,
332178479Sjb	    VM_PROT_READ | VM_PROT_WRITE);
333178479Sjb	bzero((void *)mapped, end - new_end);
334178479Sjb	uma_startup((void *)mapped, boot_pages);
335178479Sjb
336178479Sjb#if defined(__amd64__) || defined(__i386__) || defined(__arm__) || \
337178479Sjb    defined(__mips__)
338178479Sjb	/*
339178479Sjb	 * Allocate a bitmap to indicate that a random physical page
340178479Sjb	 * needs to be included in a minidump.
341178479Sjb	 *
342178479Sjb	 * The amd64 port needs this to indicate which direct map pages
343178479Sjb	 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
344178479Sjb	 *
345178479Sjb	 * However, i386 still needs this workspace internally within the
346178479Sjb	 * minidump code.  In theory, they are not needed on i386, but are
347178479Sjb	 * included should the sf_buf code decide to use them.
348178479Sjb	 */
349178479Sjb	last_pa = 0;
350178479Sjb	for (i = 0; dump_avail[i + 1] != 0; i += 2)
351178479Sjb		if (dump_avail[i + 1] > last_pa)
352178479Sjb			last_pa = dump_avail[i + 1];
353178479Sjb	page_range = last_pa / PAGE_SIZE;
354178479Sjb	vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
355178479Sjb	new_end -= vm_page_dump_size;
356178479Sjb	vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
357178479Sjb	    new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
358178479Sjb	bzero((void *)vm_page_dump, vm_page_dump_size);
359178479Sjb#endif
360178479Sjb#ifdef __amd64__
361178479Sjb	/*
362178479Sjb	 * Request that the physical pages underlying the message buffer be
363178479Sjb	 * included in a crash dump.  Since the message buffer is accessed
364178479Sjb	 * through the direct map, they are not automatically included.
365178479Sjb	 */
366178479Sjb	pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
367178479Sjb	last_pa = pa + round_page(msgbufsize);
368178479Sjb	while (pa < last_pa) {
369178479Sjb		dump_add_page(pa);
370178479Sjb		pa += PAGE_SIZE;
371178479Sjb	}
372178479Sjb#endif
373178479Sjb	/*
374178479Sjb	 * Compute the number of pages of memory that will be available for
375178479Sjb	 * use (taking into account the overhead of a page structure per
376178479Sjb	 * page).
377178479Sjb	 */
378178479Sjb	first_page = low_water / PAGE_SIZE;
379178479Sjb#ifdef VM_PHYSSEG_SPARSE
380178479Sjb	page_range = 0;
381178479Sjb	for (i = 0; phys_avail[i + 1] != 0; i += 2)
382178479Sjb		page_range += atop(phys_avail[i + 1] - phys_avail[i]);
383178479Sjb#elif defined(VM_PHYSSEG_DENSE)
384178479Sjb	page_range = high_water / PAGE_SIZE - first_page;
385178479Sjb#else
386178479Sjb#error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
387178479Sjb#endif
388178479Sjb	end = new_end;
389178479Sjb
390178479Sjb	/*
391178479Sjb	 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
392178479Sjb	 */
393178479Sjb	vaddr += PAGE_SIZE;
394178479Sjb
395178479Sjb	/*
396178479Sjb	 * Initialize the mem entry structures now, and put them in the free
397178479Sjb	 * queue.
398178479Sjb	 */
399178479Sjb	new_end = trunc_page(end - page_range * sizeof(struct vm_page));
400178479Sjb	mapped = pmap_map(&vaddr, new_end, end,
401178479Sjb	    VM_PROT_READ | VM_PROT_WRITE);
402178479Sjb	vm_page_array = (vm_page_t) mapped;
403178479Sjb#if VM_NRESERVLEVEL > 0
404178479Sjb	/*
405178479Sjb	 * Allocate memory for the reservation management system's data
406178479Sjb	 * structures.
407178479Sjb	 */
408178479Sjb	new_end = vm_reserv_startup(&vaddr, new_end, high_water);
409178479Sjb#endif
410178479Sjb#if defined(__amd64__) || defined(__mips__)
411178479Sjb	/*
412178479Sjb	 * pmap_map on amd64 and mips can come out of the direct-map, not kvm
413178479Sjb	 * like i386, so the pages must be tracked for a crashdump to include
414178479Sjb	 * this data.  This includes the vm_page_array and the early UMA
415178479Sjb	 * bootstrap pages.
416178479Sjb	 */
417178479Sjb	for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
418178479Sjb		dump_add_page(pa);
419178479Sjb#endif
420178479Sjb	phys_avail[biggestone + 1] = new_end;
421178479Sjb
422178479Sjb	/*
423178479Sjb	 * Clear all of the page structures
424178479Sjb	 */
425178479Sjb	bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
426178479Sjb	for (i = 0; i < page_range; i++)
427178479Sjb		vm_page_array[i].order = VM_NFREEORDER;
428178479Sjb	vm_page_array_size = page_range;
429178479Sjb
430178479Sjb	/*
431178479Sjb	 * Initialize the physical memory allocator.
432178479Sjb	 */
433178479Sjb	vm_phys_init();
434178479Sjb
435178479Sjb	/*
436178479Sjb	 * Add every available physical page that is not blacklisted to
437178479Sjb	 * the free lists.
438178479Sjb	 */
439178479Sjb	cnt.v_page_count = 0;
440178479Sjb	cnt.v_free_count = 0;
441178479Sjb	list = getenv("vm.blacklist");
442178479Sjb	for (i = 0; phys_avail[i + 1] != 0; i += 2) {
443178479Sjb		pa = phys_avail[i];
444178479Sjb		last_pa = phys_avail[i + 1];
445178479Sjb		while (pa < last_pa) {
446178479Sjb			if (list != NULL &&
447178479Sjb			    vm_page_blacklist_lookup(list, pa))
448178479Sjb				printf("Skipping page with pa 0x%jx\n",
449178479Sjb				    (uintmax_t)pa);
450178479Sjb			else
451178479Sjb				vm_phys_add_page(pa);
452178479Sjb			pa += PAGE_SIZE;
453178479Sjb		}
454178479Sjb	}
455178479Sjb	freeenv(list);
456178479Sjb#if VM_NRESERVLEVEL > 0
457178479Sjb	/*
458178479Sjb	 * Initialize the reservation management system.
459178479Sjb	 */
460178479Sjb	vm_reserv_init();
461178479Sjb#endif
462178479Sjb	return (vaddr);
463178479Sjb}
464178479Sjb
465178479Sjbvoid
466178479Sjbvm_page_reference(vm_page_t m)
467178479Sjb{
468178479Sjb
469178479Sjb	vm_page_aflag_set(m, PGA_REFERENCED);
470178479Sjb}
471178479Sjb
472178479Sjbvoid
473178479Sjbvm_page_busy(vm_page_t m)
474178479Sjb{
475178479Sjb
476178479Sjb	VM_OBJECT_ASSERT_WLOCKED(m->object);
477178479Sjb	KASSERT((m->oflags & VPO_BUSY) == 0,
478178479Sjb	    ("vm_page_busy: page already busy!!!"));
479178479Sjb	m->oflags |= VPO_BUSY;
480178479Sjb}
481178479Sjb
482178479Sjb/*
483178479Sjb *      vm_page_flash:
484178479Sjb *
485178479Sjb *      wakeup anyone waiting for the page.
486178479Sjb */
487178479Sjbvoid
488178479Sjbvm_page_flash(vm_page_t m)
489178479Sjb{
490178479Sjb
491178479Sjb	VM_OBJECT_ASSERT_WLOCKED(m->object);
492178479Sjb	if (m->oflags & VPO_WANTED) {
493178479Sjb		m->oflags &= ~VPO_WANTED;
494178479Sjb		wakeup(m);
495178479Sjb	}
496178479Sjb}
497178479Sjb
498178479Sjb/*
499178479Sjb *      vm_page_wakeup:
500178479Sjb *
501178479Sjb *      clear the VPO_BUSY flag and wakeup anyone waiting for the
502178479Sjb *      page.
503178479Sjb *
504178479Sjb */
505178479Sjbvoid
506178479Sjbvm_page_wakeup(vm_page_t m)
507178479Sjb{
508178479Sjb
509178479Sjb	VM_OBJECT_ASSERT_WLOCKED(m->object);
510178479Sjb	KASSERT(m->oflags & VPO_BUSY, ("vm_page_wakeup: page not busy!!!"));
511178479Sjb	m->oflags &= ~VPO_BUSY;
512178479Sjb	vm_page_flash(m);
513178479Sjb}
514178479Sjb
515178479Sjbvoid
516178479Sjbvm_page_io_start(vm_page_t m)
517178479Sjb{
518178479Sjb
519178479Sjb	VM_OBJECT_ASSERT_WLOCKED(m->object);
520178479Sjb	m->busy++;
521178479Sjb}
522178479Sjb
523178479Sjbvoid
524178479Sjbvm_page_io_finish(vm_page_t m)
525178479Sjb{
526178479Sjb
527178479Sjb	VM_OBJECT_ASSERT_WLOCKED(m->object);
528178479Sjb	KASSERT(m->busy > 0, ("vm_page_io_finish: page %p is not busy", m));
529178479Sjb	m->busy--;
530178479Sjb	if (m->busy == 0)
531178479Sjb		vm_page_flash(m);
532178479Sjb}
533178479Sjb
534178479Sjb/*
535178479Sjb * Keep page from being freed by the page daemon
536178479Sjb * much of the same effect as wiring, except much lower
537178479Sjb * overhead and should be used only for *very* temporary
538178479Sjb * holding ("wiring").
539178479Sjb */
540178479Sjbvoid
541178479Sjbvm_page_hold(vm_page_t mem)
542178479Sjb{
543178479Sjb
544178479Sjb	vm_page_lock_assert(mem, MA_OWNED);
545178479Sjb        mem->hold_count++;
546178479Sjb}
547178479Sjb
548178479Sjbvoid
549178479Sjbvm_page_unhold(vm_page_t mem)
550178479Sjb{
551178479Sjb
552178479Sjb	vm_page_lock_assert(mem, MA_OWNED);
553178479Sjb	--mem->hold_count;
554178479Sjb	KASSERT(mem->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!"));
555178479Sjb	if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
556178479Sjb		vm_page_free_toq(mem);
557178479Sjb}
558178479Sjb
559178479Sjb/*
560178479Sjb *	vm_page_unhold_pages:
561178479Sjb *
562178479Sjb *	Unhold each of the pages that is referenced by the given array.
563178479Sjb */
564178479Sjbvoid
565178479Sjbvm_page_unhold_pages(vm_page_t *ma, int count)
566178479Sjb{
567178479Sjb	struct mtx *mtx, *new_mtx;
568178479Sjb
569178479Sjb	mtx = NULL;
570178479Sjb	for (; count != 0; count--) {
571178479Sjb		/*
572178479Sjb		 * Avoid releasing and reacquiring the same page lock.
573178479Sjb		 */
574178479Sjb		new_mtx = vm_page_lockptr(*ma);
575178479Sjb		if (mtx != new_mtx) {
576178479Sjb			if (mtx != NULL)
577178479Sjb				mtx_unlock(mtx);
578178479Sjb			mtx = new_mtx;
579178479Sjb			mtx_lock(mtx);
580178479Sjb		}
581178479Sjb		vm_page_unhold(*ma);
582178479Sjb		ma++;
583178479Sjb	}
584178479Sjb	if (mtx != NULL)
585178479Sjb		mtx_unlock(mtx);
586178479Sjb}
587178479Sjb
588178479Sjbvm_page_t
589178479SjbPHYS_TO_VM_PAGE(vm_paddr_t pa)
590178479Sjb{
591178479Sjb	vm_page_t m;
592178479Sjb
593178479Sjb#ifdef VM_PHYSSEG_SPARSE
594178479Sjb	m = vm_phys_paddr_to_vm_page(pa);
595178479Sjb	if (m == NULL)
596178479Sjb		m = vm_phys_fictitious_to_vm_page(pa);
597178479Sjb	return (m);
598178479Sjb#elif defined(VM_PHYSSEG_DENSE)
599178479Sjb	long pi;
600178479Sjb
601178479Sjb	pi = atop(pa);
602178479Sjb	if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
603178479Sjb		m = &vm_page_array[pi - first_page];
604178479Sjb		return (m);
605178479Sjb	}
606178479Sjb	return (vm_phys_fictitious_to_vm_page(pa));
607178479Sjb#else
608178479Sjb#error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
609178479Sjb#endif
610178479Sjb}
611178479Sjb
612178479Sjb/*
613178479Sjb *	vm_page_getfake:
614178479Sjb *
615178479Sjb *	Create a fictitious page with the specified physical address and
616178479Sjb *	memory attribute.  The memory attribute is the only the machine-
617178479Sjb *	dependent aspect of a fictitious page that must be initialized.
618178479Sjb */
619178479Sjbvm_page_t
620178479Sjbvm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
621178479Sjb{
622178479Sjb	vm_page_t m;
623178479Sjb
624178479Sjb	m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
625178479Sjb	vm_page_initfake(m, paddr, memattr);
626178479Sjb	return (m);
627178479Sjb}
628178479Sjb
629178479Sjbvoid
630178479Sjbvm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
631178479Sjb{
632178479Sjb
633178479Sjb	if ((m->flags & PG_FICTITIOUS) != 0) {
634178479Sjb		/*
635178479Sjb		 * The page's memattr might have changed since the
636178479Sjb		 * previous initialization.  Update the pmap to the
637178479Sjb		 * new memattr.
638178479Sjb		 */
639178479Sjb		goto memattr;
640178479Sjb	}
641178479Sjb	m->phys_addr = paddr;
642178479Sjb	m->queue = PQ_NONE;
643178479Sjb	/* Fictitious pages don't use "segind". */
644178479Sjb	m->flags = PG_FICTITIOUS;
645178479Sjb	/* Fictitious pages don't use "order" or "pool". */
646178479Sjb	m->oflags = VPO_BUSY | VPO_UNMANAGED;
647178479Sjb	m->wire_count = 1;
648178479Sjbmemattr:
649178479Sjb	pmap_page_set_memattr(m, memattr);
650178479Sjb}
651178479Sjb
652178479Sjb/*
653178479Sjb *	vm_page_putfake:
654178479Sjb *
655178479Sjb *	Release a fictitious page.
656178479Sjb */
657178479Sjbvoid
658178479Sjbvm_page_putfake(vm_page_t m)
659178479Sjb{
660178479Sjb
661178479Sjb	KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
662178479Sjb	KASSERT((m->flags & PG_FICTITIOUS) != 0,
663178479Sjb	    ("vm_page_putfake: bad page %p", m));
664178479Sjb	uma_zfree(fakepg_zone, m);
665178479Sjb}
666178479Sjb
667178479Sjb/*
668178479Sjb *	vm_page_updatefake:
669178479Sjb *
670178479Sjb *	Update the given fictitious page to the specified physical address and
671178479Sjb *	memory attribute.
672178479Sjb */
673178479Sjbvoid
674178479Sjbvm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
675178479Sjb{
676178479Sjb
677178479Sjb	KASSERT((m->flags & PG_FICTITIOUS) != 0,
678178479Sjb	    ("vm_page_updatefake: bad page %p", m));
679178479Sjb	m->phys_addr = paddr;
680178479Sjb	pmap_page_set_memattr(m, memattr);
681178479Sjb}
682178479Sjb
683178479Sjb/*
684178479Sjb *	vm_page_free:
685178479Sjb *
686178479Sjb *	Free a page.
687178479Sjb */
688178479Sjbvoid
689178479Sjbvm_page_free(vm_page_t m)
690178479Sjb{
691178479Sjb
692178479Sjb	m->flags &= ~PG_ZERO;
693178479Sjb	vm_page_free_toq(m);
694178479Sjb}
695178479Sjb
696178479Sjb/*
697178479Sjb *	vm_page_free_zero:
698178479Sjb *
699178479Sjb *	Free a page to the zerod-pages queue
700178479Sjb */
701178479Sjbvoid
702178479Sjbvm_page_free_zero(vm_page_t m)
703178479Sjb{
704178479Sjb
705178479Sjb	m->flags |= PG_ZERO;
706178479Sjb	vm_page_free_toq(m);
707178479Sjb}
708178479Sjb
709178479Sjb/*
710178479Sjb * Unbusy and handle the page queueing for a page from the VOP_GETPAGES()
711178479Sjb * array which is not the request page.
712178479Sjb */
713178479Sjbvoid
714178479Sjbvm_page_readahead_finish(vm_page_t m)
715178479Sjb{
716178479Sjb
717178479Sjb	if (m->valid != 0) {
718178479Sjb		/*
719178479Sjb		 * Since the page is not the requested page, whether
720178479Sjb		 * it should be activated or deactivated is not
721178479Sjb		 * obvious.  Empirical results have shown that
722178479Sjb		 * deactivating the page is usually the best choice,
723178479Sjb		 * unless the page is wanted by another thread.
724178479Sjb		 */
725178479Sjb		if (m->oflags & VPO_WANTED) {
726178479Sjb			vm_page_lock(m);
727178479Sjb			vm_page_activate(m);
728178479Sjb			vm_page_unlock(m);
729178479Sjb		} else {
730178479Sjb			vm_page_lock(m);
731178479Sjb			vm_page_deactivate(m);
732178479Sjb			vm_page_unlock(m);
733178479Sjb		}
734178479Sjb		vm_page_wakeup(m);
735178479Sjb	} else {
736178479Sjb		/*
737178479Sjb		 * Free the completely invalid page.  Such page state
738178479Sjb		 * occurs due to the short read operation which did
739178479Sjb		 * not covered our page at all, or in case when a read
740178479Sjb		 * error happens.
741178479Sjb		 */
742178479Sjb		vm_page_lock(m);
743178479Sjb		vm_page_free(m);
744178479Sjb		vm_page_unlock(m);
745178479Sjb	}
746178479Sjb}
747178479Sjb
748178479Sjb/*
749178479Sjb *	vm_page_sleep:
750178479Sjb *
751178479Sjb *	Sleep and release the page lock.
752178479Sjb *
753178479Sjb *	The object containing the given page must be locked.
754178479Sjb */
755178479Sjbvoid
756178479Sjbvm_page_sleep(vm_page_t m, const char *msg)
757178479Sjb{
758178479Sjb
759178479Sjb	VM_OBJECT_ASSERT_WLOCKED(m->object);
760178479Sjb	if (mtx_owned(vm_page_lockptr(m)))
761178479Sjb		vm_page_unlock(m);
762178479Sjb
763178479Sjb	/*
764178479Sjb	 * It's possible that while we sleep, the page will get
765178479Sjb	 * unbusied and freed.  If we are holding the object
766178479Sjb	 * lock, we will assume we hold a reference to the object
767178479Sjb	 * such that even if m->object changes, we can re-lock
768178479Sjb	 * it.
769178479Sjb	 */
770178479Sjb	m->oflags |= VPO_WANTED;
771178479Sjb	VM_OBJECT_SLEEP(m->object, m, PVM, msg, 0);
772178479Sjb}
773178479Sjb
774178479Sjb/*
775178479Sjb *	vm_page_dirty_KBI:		[ internal use only ]
776178479Sjb *
777178479Sjb *	Set all bits in the page's dirty field.
778178479Sjb *
779178479Sjb *	The object containing the specified page must be locked if the
780178479Sjb *	call is made from the machine-independent layer.
781178479Sjb *
782178479Sjb *	See vm_page_clear_dirty_mask().
783178479Sjb *
784178479Sjb *	This function should only be called by vm_page_dirty().
785178479Sjb */
786178479Sjbvoid
787178479Sjbvm_page_dirty_KBI(vm_page_t m)
788178479Sjb{
789178479Sjb
790178479Sjb	/* These assertions refer to this operation by its public name. */
791178479Sjb	KASSERT((m->flags & PG_CACHED) == 0,
792178479Sjb	    ("vm_page_dirty: page in cache!"));
793178479Sjb	KASSERT(!VM_PAGE_IS_FREE(m),
794178479Sjb	    ("vm_page_dirty: page is free!"));
795178479Sjb	KASSERT(m->valid == VM_PAGE_BITS_ALL,
796178479Sjb	    ("vm_page_dirty: page is invalid!"));
797178479Sjb	m->dirty = VM_PAGE_BITS_ALL;
798178479Sjb}
799178479Sjb
800178479Sjb/*
801178479Sjb *	vm_page_insert:		[ internal use only ]
802178479Sjb *
803178479Sjb *	Inserts the given mem entry into the object and object list.
804178479Sjb *
805178479Sjb *	The object must be locked.
806178479Sjb */
807178479Sjbvoid
808178479Sjbvm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
809178479Sjb{
810178479Sjb	vm_page_t mpred;
811178479Sjb
812178479Sjb	VM_OBJECT_ASSERT_WLOCKED(object);
813178479Sjb	mpred = vm_radix_lookup_le(&object->rtree, pindex);
814178479Sjb	vm_page_insert_after(m, object, pindex, mpred);
815178479Sjb}
816178479Sjb
817178479Sjb/*
818178479Sjb *	vm_page_insert_after:
819178479Sjb *
820178479Sjb *	Inserts the page "m" into the specified object at offset "pindex".
821178479Sjb *
822178479Sjb *	The page "mpred" must immediately precede the offset "pindex" within
823178479Sjb *	the specified object.
824178479Sjb *
825178479Sjb *	The object must be locked.
826178479Sjb */
827178479Sjbstatic void
828178479Sjbvm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
829178479Sjb    vm_page_t mpred)
830178479Sjb{
831178479Sjb	vm_page_t msucc;
832178479Sjb
833178479Sjb	VM_OBJECT_ASSERT_WLOCKED(object);
834178479Sjb	KASSERT(m->object == NULL,
835178479Sjb	    ("vm_page_insert_after: page already inserted"));
836178479Sjb	if (mpred != NULL) {
837178479Sjb		KASSERT(mpred->object == object ||
838178479Sjb		    (mpred->flags & PG_SLAB) != 0,
839178479Sjb		    ("vm_page_insert_after: object doesn't contain mpred"));
840178479Sjb		KASSERT(mpred->pindex < pindex,
841178479Sjb		    ("vm_page_insert_after: mpred doesn't precede pindex"));
842178479Sjb		msucc = TAILQ_NEXT(mpred, listq);
843178479Sjb	} else
844178479Sjb		msucc = TAILQ_FIRST(&object->memq);
845178479Sjb	if (msucc != NULL)
846178479Sjb		KASSERT(msucc->pindex > pindex,
847178479Sjb		    ("vm_page_insert_after: msucc doesn't succeed pindex"));
848178479Sjb
849178479Sjb	/*
850178479Sjb	 * Record the object/offset pair in this page
851178479Sjb	 */
852178479Sjb	m->object = object;
853178479Sjb	m->pindex = pindex;
854178479Sjb
855178479Sjb	/*
856178479Sjb	 * Now link into the object's ordered list of backed pages.
857178479Sjb	 */
858178479Sjb	if (mpred != NULL)
859178479Sjb		TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
860178479Sjb	else
861178479Sjb		TAILQ_INSERT_HEAD(&object->memq, m, listq);
862178479Sjb	vm_radix_insert(&object->rtree, m);
863178479Sjb
864	/*
865	 * Show that the object has one more resident page.
866	 */
867	object->resident_page_count++;
868
869	/*
870	 * Hold the vnode until the last page is released.
871	 */
872	if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
873		vhold(object->handle);
874
875	/*
876	 * Since we are inserting a new and possibly dirty page,
877	 * update the object's OBJ_MIGHTBEDIRTY flag.
878	 */
879	if (pmap_page_is_write_mapped(m))
880		vm_object_set_writeable_dirty(object);
881}
882
883/*
884 *	vm_page_remove:
885 *
886 *	Removes the given mem entry from the object/offset-page
887 *	table and the object page list, but do not invalidate/terminate
888 *	the backing store.
889 *
890 *	The object must be locked.  The page must be locked if it is managed.
891 */
892void
893vm_page_remove(vm_page_t m)
894{
895	vm_object_t object;
896
897	if ((m->oflags & VPO_UNMANAGED) == 0)
898		vm_page_lock_assert(m, MA_OWNED);
899	if ((object = m->object) == NULL)
900		return;
901	VM_OBJECT_ASSERT_WLOCKED(object);
902	if (m->oflags & VPO_BUSY) {
903		m->oflags &= ~VPO_BUSY;
904		vm_page_flash(m);
905	}
906
907	/*
908	 * Now remove from the object's list of backed pages.
909	 */
910	vm_radix_remove(&object->rtree, m->pindex);
911	TAILQ_REMOVE(&object->memq, m, listq);
912
913	/*
914	 * And show that the object has one fewer resident page.
915	 */
916	object->resident_page_count--;
917
918	/*
919	 * The vnode may now be recycled.
920	 */
921	if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
922		vdrop(object->handle);
923
924	m->object = NULL;
925}
926
927/*
928 *	vm_page_lookup:
929 *
930 *	Returns the page associated with the object/offset
931 *	pair specified; if none is found, NULL is returned.
932 *
933 *	The object must be locked.
934 */
935vm_page_t
936vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
937{
938
939	VM_OBJECT_ASSERT_LOCKED(object);
940	return (vm_radix_lookup(&object->rtree, pindex));
941}
942
943/*
944 *	vm_page_find_least:
945 *
946 *	Returns the page associated with the object with least pindex
947 *	greater than or equal to the parameter pindex, or NULL.
948 *
949 *	The object must be locked.
950 */
951vm_page_t
952vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
953{
954	vm_page_t m;
955
956	VM_OBJECT_ASSERT_LOCKED(object);
957	if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
958		m = vm_radix_lookup_ge(&object->rtree, pindex);
959	return (m);
960}
961
962/*
963 * Returns the given page's successor (by pindex) within the object if it is
964 * resident; if none is found, NULL is returned.
965 *
966 * The object must be locked.
967 */
968vm_page_t
969vm_page_next(vm_page_t m)
970{
971	vm_page_t next;
972
973	VM_OBJECT_ASSERT_WLOCKED(m->object);
974	if ((next = TAILQ_NEXT(m, listq)) != NULL &&
975	    next->pindex != m->pindex + 1)
976		next = NULL;
977	return (next);
978}
979
980/*
981 * Returns the given page's predecessor (by pindex) within the object if it is
982 * resident; if none is found, NULL is returned.
983 *
984 * The object must be locked.
985 */
986vm_page_t
987vm_page_prev(vm_page_t m)
988{
989	vm_page_t prev;
990
991	VM_OBJECT_ASSERT_WLOCKED(m->object);
992	if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
993	    prev->pindex != m->pindex - 1)
994		prev = NULL;
995	return (prev);
996}
997
998/*
999 *	vm_page_rename:
1000 *
1001 *	Move the given memory entry from its
1002 *	current object to the specified target object/offset.
1003 *
1004 *	Note: swap associated with the page must be invalidated by the move.  We
1005 *	      have to do this for several reasons:  (1) we aren't freeing the
1006 *	      page, (2) we are dirtying the page, (3) the VM system is probably
1007 *	      moving the page from object A to B, and will then later move
1008 *	      the backing store from A to B and we can't have a conflict.
1009 *
1010 *	Note: we *always* dirty the page.  It is necessary both for the
1011 *	      fact that we moved it, and because we may be invalidating
1012 *	      swap.  If the page is on the cache, we have to deactivate it
1013 *	      or vm_page_dirty() will panic.  Dirty pages are not allowed
1014 *	      on the cache.
1015 *
1016 *	The objects must be locked.  The page must be locked if it is managed.
1017 */
1018void
1019vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1020{
1021
1022	vm_page_remove(m);
1023	vm_page_insert(m, new_object, new_pindex);
1024	vm_page_dirty(m);
1025}
1026
1027/*
1028 *	Convert all of the given object's cached pages that have a
1029 *	pindex within the given range into free pages.  If the value
1030 *	zero is given for "end", then the range's upper bound is
1031 *	infinity.  If the given object is backed by a vnode and it
1032 *	transitions from having one or more cached pages to none, the
1033 *	vnode's hold count is reduced.
1034 */
1035void
1036vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1037{
1038	vm_page_t m;
1039	boolean_t empty;
1040
1041	mtx_lock(&vm_page_queue_free_mtx);
1042	if (__predict_false(vm_radix_is_empty(&object->cache))) {
1043		mtx_unlock(&vm_page_queue_free_mtx);
1044		return;
1045	}
1046	while ((m = vm_radix_lookup_ge(&object->cache, start)) != NULL) {
1047		if (end != 0 && m->pindex >= end)
1048			break;
1049		vm_radix_remove(&object->cache, m->pindex);
1050		m->object = NULL;
1051		m->valid = 0;
1052		/* Clear PG_CACHED and set PG_FREE. */
1053		m->flags ^= PG_CACHED | PG_FREE;
1054		KASSERT((m->flags & (PG_CACHED | PG_FREE)) == PG_FREE,
1055		    ("vm_page_cache_free: page %p has inconsistent flags", m));
1056		cnt.v_cache_count--;
1057		cnt.v_free_count++;
1058	}
1059	empty = vm_radix_is_empty(&object->cache);
1060	mtx_unlock(&vm_page_queue_free_mtx);
1061	if (object->type == OBJT_VNODE && empty)
1062		vdrop(object->handle);
1063}
1064
1065/*
1066 *	Returns the cached page that is associated with the given
1067 *	object and offset.  If, however, none exists, returns NULL.
1068 *
1069 *	The free page queue must be locked.
1070 */
1071static inline vm_page_t
1072vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
1073{
1074
1075	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1076	return (vm_radix_lookup(&object->cache, pindex));
1077}
1078
1079/*
1080 *	Remove the given cached page from its containing object's
1081 *	collection of cached pages.
1082 *
1083 *	The free page queue must be locked.
1084 */
1085static void
1086vm_page_cache_remove(vm_page_t m)
1087{
1088
1089	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1090	KASSERT((m->flags & PG_CACHED) != 0,
1091	    ("vm_page_cache_remove: page %p is not cached", m));
1092	vm_radix_remove(&m->object->cache, m->pindex);
1093	m->object = NULL;
1094	cnt.v_cache_count--;
1095}
1096
1097/*
1098 *	Transfer all of the cached pages with offset greater than or
1099 *	equal to 'offidxstart' from the original object's cache to the
1100 *	new object's cache.  However, any cached pages with offset
1101 *	greater than or equal to the new object's size are kept in the
1102 *	original object.  Initially, the new object's cache must be
1103 *	empty.  Offset 'offidxstart' in the original object must
1104 *	correspond to offset zero in the new object.
1105 *
1106 *	The new object must be locked.
1107 */
1108void
1109vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1110    vm_object_t new_object)
1111{
1112	vm_page_t m;
1113
1114	/*
1115	 * Insertion into an object's collection of cached pages
1116	 * requires the object to be locked.  In contrast, removal does
1117	 * not.
1118	 */
1119	VM_OBJECT_ASSERT_WLOCKED(new_object);
1120	KASSERT(vm_radix_is_empty(&new_object->cache),
1121	    ("vm_page_cache_transfer: object %p has cached pages",
1122	    new_object));
1123	mtx_lock(&vm_page_queue_free_mtx);
1124	while ((m = vm_radix_lookup_ge(&orig_object->cache,
1125	    offidxstart)) != NULL) {
1126		/*
1127		 * Transfer all of the pages with offset greater than or
1128		 * equal to 'offidxstart' from the original object's
1129		 * cache to the new object's cache.
1130		 */
1131		if ((m->pindex - offidxstart) >= new_object->size)
1132			break;
1133		vm_radix_remove(&orig_object->cache, m->pindex);
1134		/* Update the page's object and offset. */
1135		m->object = new_object;
1136		m->pindex -= offidxstart;
1137		vm_radix_insert(&new_object->cache, m);
1138	}
1139	mtx_unlock(&vm_page_queue_free_mtx);
1140}
1141
1142/*
1143 *	Returns TRUE if a cached page is associated with the given object and
1144 *	offset, and FALSE otherwise.
1145 *
1146 *	The object must be locked.
1147 */
1148boolean_t
1149vm_page_is_cached(vm_object_t object, vm_pindex_t pindex)
1150{
1151	vm_page_t m;
1152
1153	/*
1154	 * Insertion into an object's collection of cached pages requires the
1155	 * object to be locked.  Therefore, if the object is locked and the
1156	 * object's collection is empty, there is no need to acquire the free
1157	 * page queues lock in order to prove that the specified page doesn't
1158	 * exist.
1159	 */
1160	VM_OBJECT_ASSERT_WLOCKED(object);
1161	if (__predict_true(vm_object_cache_is_empty(object)))
1162		return (FALSE);
1163	mtx_lock(&vm_page_queue_free_mtx);
1164	m = vm_page_cache_lookup(object, pindex);
1165	mtx_unlock(&vm_page_queue_free_mtx);
1166	return (m != NULL);
1167}
1168
1169/*
1170 *	vm_page_alloc:
1171 *
1172 *	Allocate and return a page that is associated with the specified
1173 *	object and offset pair.  By default, this page has the flag VPO_BUSY
1174 *	set.
1175 *
1176 *	The caller must always specify an allocation class.
1177 *
1178 *	allocation classes:
1179 *	VM_ALLOC_NORMAL		normal process request
1180 *	VM_ALLOC_SYSTEM		system *really* needs a page
1181 *	VM_ALLOC_INTERRUPT	interrupt time request
1182 *
1183 *	optional allocation flags:
1184 *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
1185 *				intends to allocate
1186 *	VM_ALLOC_IFCACHED	return page only if it is cached
1187 *	VM_ALLOC_IFNOTCACHED	return NULL, do not reactivate if the page
1188 *				is cached
1189 *	VM_ALLOC_NOBUSY		do not set the flag VPO_BUSY on the page
1190 *	VM_ALLOC_NODUMP		do not include the page in a kernel core dump
1191 *	VM_ALLOC_NOOBJ		page is not associated with an object and
1192 *				should not have the flag VPO_BUSY set
1193 *	VM_ALLOC_WIRED		wire the allocated page
1194 *	VM_ALLOC_ZERO		prefer a zeroed page
1195 *
1196 *	This routine may not sleep.
1197 */
1198vm_page_t
1199vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1200{
1201	struct vnode *vp = NULL;
1202	vm_object_t m_object;
1203	vm_page_t m, mpred;
1204	int flags, req_class;
1205
1206	mpred = 0;	/* XXX: pacify gcc */
1207	KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0),
1208	    ("vm_page_alloc: inconsistent object/req"));
1209	if (object != NULL)
1210		VM_OBJECT_ASSERT_WLOCKED(object);
1211
1212	req_class = req & VM_ALLOC_CLASS_MASK;
1213
1214	/*
1215	 * The page daemon is allowed to dig deeper into the free page list.
1216	 */
1217	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1218		req_class = VM_ALLOC_SYSTEM;
1219
1220	if (object != NULL) {
1221		mpred = vm_radix_lookup_le(&object->rtree, pindex);
1222		KASSERT(mpred == NULL || mpred->pindex != pindex,
1223		   ("vm_page_alloc: pindex already allocated"));
1224	}
1225	mtx_lock(&vm_page_queue_free_mtx);
1226	if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1227	    (req_class == VM_ALLOC_SYSTEM &&
1228	    cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1229	    (req_class == VM_ALLOC_INTERRUPT &&
1230	    cnt.v_free_count + cnt.v_cache_count > 0)) {
1231		/*
1232		 * Allocate from the free queue if the number of free pages
1233		 * exceeds the minimum for the request class.
1234		 */
1235		if (object != NULL &&
1236		    (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1237			if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1238				mtx_unlock(&vm_page_queue_free_mtx);
1239				return (NULL);
1240			}
1241			if (vm_phys_unfree_page(m))
1242				vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1243#if VM_NRESERVLEVEL > 0
1244			else if (!vm_reserv_reactivate_page(m))
1245#else
1246			else
1247#endif
1248				panic("vm_page_alloc: cache page %p is missing"
1249				    " from the free queue", m);
1250		} else if ((req & VM_ALLOC_IFCACHED) != 0) {
1251			mtx_unlock(&vm_page_queue_free_mtx);
1252			return (NULL);
1253#if VM_NRESERVLEVEL > 0
1254		} else if (object == NULL || (object->flags & (OBJ_COLORED |
1255		    OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1256		    vm_reserv_alloc_page(object, pindex, mpred)) == NULL) {
1257#else
1258		} else {
1259#endif
1260			m = vm_phys_alloc_pages(object != NULL ?
1261			    VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1262#if VM_NRESERVLEVEL > 0
1263			if (m == NULL && vm_reserv_reclaim_inactive()) {
1264				m = vm_phys_alloc_pages(object != NULL ?
1265				    VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1266				    0);
1267			}
1268#endif
1269		}
1270	} else {
1271		/*
1272		 * Not allocatable, give up.
1273		 */
1274		mtx_unlock(&vm_page_queue_free_mtx);
1275		atomic_add_int(&vm_pageout_deficit,
1276		    max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1277		pagedaemon_wakeup();
1278		return (NULL);
1279	}
1280
1281	/*
1282	 *  At this point we had better have found a good page.
1283	 */
1284	KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1285	KASSERT(m->queue == PQ_NONE,
1286	    ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1287	KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1288	KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1289	KASSERT(m->busy == 0, ("vm_page_alloc: page %p is busy", m));
1290	KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1291	KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1292	    ("vm_page_alloc: page %p has unexpected memattr %d", m,
1293	    pmap_page_get_memattr(m)));
1294	if ((m->flags & PG_CACHED) != 0) {
1295		KASSERT((m->flags & PG_ZERO) == 0,
1296		    ("vm_page_alloc: cached page %p is PG_ZERO", m));
1297		KASSERT(m->valid != 0,
1298		    ("vm_page_alloc: cached page %p is invalid", m));
1299		if (m->object == object && m->pindex == pindex)
1300	  		cnt.v_reactivated++;
1301		else
1302			m->valid = 0;
1303		m_object = m->object;
1304		vm_page_cache_remove(m);
1305		if (m_object->type == OBJT_VNODE &&
1306		    vm_object_cache_is_empty(m_object))
1307			vp = m_object->handle;
1308	} else {
1309		KASSERT(VM_PAGE_IS_FREE(m),
1310		    ("vm_page_alloc: page %p is not free", m));
1311		KASSERT(m->valid == 0,
1312		    ("vm_page_alloc: free page %p is valid", m));
1313		cnt.v_free_count--;
1314	}
1315
1316	/*
1317	 * Only the PG_ZERO flag is inherited.  The PG_CACHED or PG_FREE flag
1318	 * must be cleared before the free page queues lock is released.
1319	 */
1320	flags = 0;
1321	if (m->flags & PG_ZERO) {
1322		vm_page_zero_count--;
1323		if (req & VM_ALLOC_ZERO)
1324			flags = PG_ZERO;
1325	}
1326	if (req & VM_ALLOC_NODUMP)
1327		flags |= PG_NODUMP;
1328	m->flags = flags;
1329	mtx_unlock(&vm_page_queue_free_mtx);
1330	m->aflags = 0;
1331	m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1332	    VPO_UNMANAGED : 0;
1333	if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ)) == 0)
1334		m->oflags |= VPO_BUSY;
1335	if (req & VM_ALLOC_WIRED) {
1336		/*
1337		 * The page lock is not required for wiring a page until that
1338		 * page is inserted into the object.
1339		 */
1340		atomic_add_int(&cnt.v_wire_count, 1);
1341		m->wire_count = 1;
1342	}
1343	m->act_count = 0;
1344
1345	if (object != NULL) {
1346		/* Ignore device objects; the pager sets "memattr" for them. */
1347		if (object->memattr != VM_MEMATTR_DEFAULT &&
1348		    (object->flags & OBJ_FICTITIOUS) == 0)
1349			pmap_page_set_memattr(m, object->memattr);
1350		vm_page_insert_after(m, object, pindex, mpred);
1351	} else
1352		m->pindex = pindex;
1353
1354	/*
1355	 * The following call to vdrop() must come after the above call
1356	 * to vm_page_insert() in case both affect the same object and
1357	 * vnode.  Otherwise, the affected vnode's hold count could
1358	 * temporarily become zero.
1359	 */
1360	if (vp != NULL)
1361		vdrop(vp);
1362
1363	/*
1364	 * Don't wakeup too often - wakeup the pageout daemon when
1365	 * we would be nearly out of memory.
1366	 */
1367	if (vm_paging_needed())
1368		pagedaemon_wakeup();
1369
1370	return (m);
1371}
1372
1373/*
1374 *	vm_page_alloc_contig:
1375 *
1376 *	Allocate a contiguous set of physical pages of the given size "npages"
1377 *	from the free lists.  All of the physical pages must be at or above
1378 *	the given physical address "low" and below the given physical address
1379 *	"high".  The given value "alignment" determines the alignment of the
1380 *	first physical page in the set.  If the given value "boundary" is
1381 *	non-zero, then the set of physical pages cannot cross any physical
1382 *	address boundary that is a multiple of that value.  Both "alignment"
1383 *	and "boundary" must be a power of two.
1384 *
1385 *	If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1386 *	then the memory attribute setting for the physical pages is configured
1387 *	to the object's memory attribute setting.  Otherwise, the memory
1388 *	attribute setting for the physical pages is configured to "memattr",
1389 *	overriding the object's memory attribute setting.  However, if the
1390 *	object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1391 *	memory attribute setting for the physical pages cannot be configured
1392 *	to VM_MEMATTR_DEFAULT.
1393 *
1394 *	The caller must always specify an allocation class.
1395 *
1396 *	allocation classes:
1397 *	VM_ALLOC_NORMAL		normal process request
1398 *	VM_ALLOC_SYSTEM		system *really* needs a page
1399 *	VM_ALLOC_INTERRUPT	interrupt time request
1400 *
1401 *	optional allocation flags:
1402 *	VM_ALLOC_NOBUSY		do not set the flag VPO_BUSY on the page
1403 *	VM_ALLOC_NOOBJ		page is not associated with an object and
1404 *				should not have the flag VPO_BUSY set
1405 *	VM_ALLOC_WIRED		wire the allocated page
1406 *	VM_ALLOC_ZERO		prefer a zeroed page
1407 *
1408 *	This routine may not sleep.
1409 */
1410vm_page_t
1411vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1412    u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1413    vm_paddr_t boundary, vm_memattr_t memattr)
1414{
1415	struct vnode *drop;
1416	vm_page_t deferred_vdrop_list, m, m_ret;
1417	u_int flags, oflags;
1418	int req_class;
1419
1420	KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0),
1421	    ("vm_page_alloc_contig: inconsistent object/req"));
1422	if (object != NULL) {
1423		VM_OBJECT_ASSERT_WLOCKED(object);
1424		KASSERT(object->type == OBJT_PHYS,
1425		    ("vm_page_alloc_contig: object %p isn't OBJT_PHYS",
1426		    object));
1427	}
1428	KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1429	req_class = req & VM_ALLOC_CLASS_MASK;
1430
1431	/*
1432	 * The page daemon is allowed to dig deeper into the free page list.
1433	 */
1434	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1435		req_class = VM_ALLOC_SYSTEM;
1436
1437	deferred_vdrop_list = NULL;
1438	mtx_lock(&vm_page_queue_free_mtx);
1439	if (cnt.v_free_count + cnt.v_cache_count >= npages +
1440	    cnt.v_free_reserved || (req_class == VM_ALLOC_SYSTEM &&
1441	    cnt.v_free_count + cnt.v_cache_count >= npages +
1442	    cnt.v_interrupt_free_min) || (req_class == VM_ALLOC_INTERRUPT &&
1443	    cnt.v_free_count + cnt.v_cache_count >= npages)) {
1444#if VM_NRESERVLEVEL > 0
1445retry:
1446		if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1447		    (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1448		    low, high, alignment, boundary)) == NULL)
1449#endif
1450			m_ret = vm_phys_alloc_contig(npages, low, high,
1451			    alignment, boundary);
1452	} else {
1453		mtx_unlock(&vm_page_queue_free_mtx);
1454		atomic_add_int(&vm_pageout_deficit, npages);
1455		pagedaemon_wakeup();
1456		return (NULL);
1457	}
1458	if (m_ret != NULL)
1459		for (m = m_ret; m < &m_ret[npages]; m++) {
1460			drop = vm_page_alloc_init(m);
1461			if (drop != NULL) {
1462				/*
1463				 * Enqueue the vnode for deferred vdrop().
1464				 *
1465				 * Once the pages are removed from the free
1466				 * page list, "pageq" can be safely abused to
1467				 * construct a short-lived list of vnodes.
1468				 */
1469				m->pageq.tqe_prev = (void *)drop;
1470				m->pageq.tqe_next = deferred_vdrop_list;
1471				deferred_vdrop_list = m;
1472			}
1473		}
1474	else {
1475#if VM_NRESERVLEVEL > 0
1476		if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1477		    boundary))
1478			goto retry;
1479#endif
1480	}
1481	mtx_unlock(&vm_page_queue_free_mtx);
1482	if (m_ret == NULL)
1483		return (NULL);
1484
1485	/*
1486	 * Initialize the pages.  Only the PG_ZERO flag is inherited.
1487	 */
1488	flags = 0;
1489	if ((req & VM_ALLOC_ZERO) != 0)
1490		flags = PG_ZERO;
1491	if ((req & VM_ALLOC_NODUMP) != 0)
1492		flags |= PG_NODUMP;
1493	if ((req & VM_ALLOC_WIRED) != 0)
1494		atomic_add_int(&cnt.v_wire_count, npages);
1495	oflags = VPO_UNMANAGED;
1496	if (object != NULL) {
1497		if ((req & VM_ALLOC_NOBUSY) == 0)
1498			oflags |= VPO_BUSY;
1499		if (object->memattr != VM_MEMATTR_DEFAULT &&
1500		    memattr == VM_MEMATTR_DEFAULT)
1501			memattr = object->memattr;
1502	}
1503	for (m = m_ret; m < &m_ret[npages]; m++) {
1504		m->aflags = 0;
1505		m->flags = (m->flags | PG_NODUMP) & flags;
1506		if ((req & VM_ALLOC_WIRED) != 0)
1507			m->wire_count = 1;
1508		/* Unmanaged pages don't use "act_count". */
1509		m->oflags = oflags;
1510		if (memattr != VM_MEMATTR_DEFAULT)
1511			pmap_page_set_memattr(m, memattr);
1512		if (object != NULL)
1513			vm_page_insert(m, object, pindex);
1514		else
1515			m->pindex = pindex;
1516		pindex++;
1517	}
1518	while (deferred_vdrop_list != NULL) {
1519		vdrop((struct vnode *)deferred_vdrop_list->pageq.tqe_prev);
1520		deferred_vdrop_list = deferred_vdrop_list->pageq.tqe_next;
1521	}
1522	if (vm_paging_needed())
1523		pagedaemon_wakeup();
1524	return (m_ret);
1525}
1526
1527/*
1528 * Initialize a page that has been freshly dequeued from a freelist.
1529 * The caller has to drop the vnode returned, if it is not NULL.
1530 *
1531 * This function may only be used to initialize unmanaged pages.
1532 *
1533 * To be called with vm_page_queue_free_mtx held.
1534 */
1535static struct vnode *
1536vm_page_alloc_init(vm_page_t m)
1537{
1538	struct vnode *drop;
1539	vm_object_t m_object;
1540
1541	KASSERT(m->queue == PQ_NONE,
1542	    ("vm_page_alloc_init: page %p has unexpected queue %d",
1543	    m, m->queue));
1544	KASSERT(m->wire_count == 0,
1545	    ("vm_page_alloc_init: page %p is wired", m));
1546	KASSERT(m->hold_count == 0,
1547	    ("vm_page_alloc_init: page %p is held", m));
1548	KASSERT(m->busy == 0,
1549	    ("vm_page_alloc_init: page %p is busy", m));
1550	KASSERT(m->dirty == 0,
1551	    ("vm_page_alloc_init: page %p is dirty", m));
1552	KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1553	    ("vm_page_alloc_init: page %p has unexpected memattr %d",
1554	    m, pmap_page_get_memattr(m)));
1555	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1556	drop = NULL;
1557	if ((m->flags & PG_CACHED) != 0) {
1558		KASSERT((m->flags & PG_ZERO) == 0,
1559		    ("vm_page_alloc_init: cached page %p is PG_ZERO", m));
1560		m->valid = 0;
1561		m_object = m->object;
1562		vm_page_cache_remove(m);
1563		if (m_object->type == OBJT_VNODE &&
1564		    vm_object_cache_is_empty(m_object))
1565			drop = m_object->handle;
1566	} else {
1567		KASSERT(VM_PAGE_IS_FREE(m),
1568		    ("vm_page_alloc_init: page %p is not free", m));
1569		KASSERT(m->valid == 0,
1570		    ("vm_page_alloc_init: free page %p is valid", m));
1571		cnt.v_free_count--;
1572		if ((m->flags & PG_ZERO) != 0)
1573			vm_page_zero_count--;
1574	}
1575	/* Don't clear the PG_ZERO flag; we'll need it later. */
1576	m->flags &= PG_ZERO;
1577	return (drop);
1578}
1579
1580/*
1581 * 	vm_page_alloc_freelist:
1582 *
1583 *	Allocate a physical page from the specified free page list.
1584 *
1585 *	The caller must always specify an allocation class.
1586 *
1587 *	allocation classes:
1588 *	VM_ALLOC_NORMAL		normal process request
1589 *	VM_ALLOC_SYSTEM		system *really* needs a page
1590 *	VM_ALLOC_INTERRUPT	interrupt time request
1591 *
1592 *	optional allocation flags:
1593 *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
1594 *				intends to allocate
1595 *	VM_ALLOC_WIRED		wire the allocated page
1596 *	VM_ALLOC_ZERO		prefer a zeroed page
1597 *
1598 *	This routine may not sleep.
1599 */
1600vm_page_t
1601vm_page_alloc_freelist(int flind, int req)
1602{
1603	struct vnode *drop;
1604	vm_page_t m;
1605	u_int flags;
1606	int req_class;
1607
1608	req_class = req & VM_ALLOC_CLASS_MASK;
1609
1610	/*
1611	 * The page daemon is allowed to dig deeper into the free page list.
1612	 */
1613	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1614		req_class = VM_ALLOC_SYSTEM;
1615
1616	/*
1617	 * Do not allocate reserved pages unless the req has asked for it.
1618	 */
1619	mtx_lock(&vm_page_queue_free_mtx);
1620	if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1621	    (req_class == VM_ALLOC_SYSTEM &&
1622	    cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1623	    (req_class == VM_ALLOC_INTERRUPT &&
1624	    cnt.v_free_count + cnt.v_cache_count > 0))
1625		m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
1626	else {
1627		mtx_unlock(&vm_page_queue_free_mtx);
1628		atomic_add_int(&vm_pageout_deficit,
1629		    max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1630		pagedaemon_wakeup();
1631		return (NULL);
1632	}
1633	if (m == NULL) {
1634		mtx_unlock(&vm_page_queue_free_mtx);
1635		return (NULL);
1636	}
1637	drop = vm_page_alloc_init(m);
1638	mtx_unlock(&vm_page_queue_free_mtx);
1639
1640	/*
1641	 * Initialize the page.  Only the PG_ZERO flag is inherited.
1642	 */
1643	m->aflags = 0;
1644	flags = 0;
1645	if ((req & VM_ALLOC_ZERO) != 0)
1646		flags = PG_ZERO;
1647	m->flags &= flags;
1648	if ((req & VM_ALLOC_WIRED) != 0) {
1649		/*
1650		 * The page lock is not required for wiring a page that does
1651		 * not belong to an object.
1652		 */
1653		atomic_add_int(&cnt.v_wire_count, 1);
1654		m->wire_count = 1;
1655	}
1656	/* Unmanaged pages don't use "act_count". */
1657	m->oflags = VPO_UNMANAGED;
1658	if (drop != NULL)
1659		vdrop(drop);
1660	if (vm_paging_needed())
1661		pagedaemon_wakeup();
1662	return (m);
1663}
1664
1665/*
1666 *	vm_wait:	(also see VM_WAIT macro)
1667 *
1668 *	Sleep until free pages are available for allocation.
1669 *	- Called in various places before memory allocations.
1670 */
1671void
1672vm_wait(void)
1673{
1674
1675	mtx_lock(&vm_page_queue_free_mtx);
1676	if (curproc == pageproc) {
1677		vm_pageout_pages_needed = 1;
1678		msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
1679		    PDROP | PSWP, "VMWait", 0);
1680	} else {
1681		if (!vm_pages_needed) {
1682			vm_pages_needed = 1;
1683			wakeup(&vm_pages_needed);
1684		}
1685		msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
1686		    "vmwait", 0);
1687	}
1688}
1689
1690/*
1691 *	vm_waitpfault:	(also see VM_WAITPFAULT macro)
1692 *
1693 *	Sleep until free pages are available for allocation.
1694 *	- Called only in vm_fault so that processes page faulting
1695 *	  can be easily tracked.
1696 *	- Sleeps at a lower priority than vm_wait() so that vm_wait()ing
1697 *	  processes will be able to grab memory first.  Do not change
1698 *	  this balance without careful testing first.
1699 */
1700void
1701vm_waitpfault(void)
1702{
1703
1704	mtx_lock(&vm_page_queue_free_mtx);
1705	if (!vm_pages_needed) {
1706		vm_pages_needed = 1;
1707		wakeup(&vm_pages_needed);
1708	}
1709	msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
1710	    "pfault", 0);
1711}
1712
1713/*
1714 *	vm_page_dequeue:
1715 *
1716 *	Remove the given page from its current page queue.
1717 *
1718 *	The page must be locked.
1719 */
1720void
1721vm_page_dequeue(vm_page_t m)
1722{
1723	struct vm_pagequeue *pq;
1724
1725	vm_page_lock_assert(m, MA_OWNED);
1726	KASSERT(m->queue != PQ_NONE,
1727	    ("vm_page_dequeue: page %p is not queued", m));
1728	pq = &vm_pagequeues[m->queue];
1729	vm_pagequeue_lock(pq);
1730	m->queue = PQ_NONE;
1731	TAILQ_REMOVE(&pq->pq_pl, m, pageq);
1732	(*pq->pq_cnt)--;
1733	vm_pagequeue_unlock(pq);
1734}
1735
1736/*
1737 *	vm_page_dequeue_locked:
1738 *
1739 *	Remove the given page from its current page queue.
1740 *
1741 *	The page and page queue must be locked.
1742 */
1743void
1744vm_page_dequeue_locked(vm_page_t m)
1745{
1746	struct vm_pagequeue *pq;
1747
1748	vm_page_lock_assert(m, MA_OWNED);
1749	pq = &vm_pagequeues[m->queue];
1750	vm_pagequeue_assert_locked(pq);
1751	m->queue = PQ_NONE;
1752	TAILQ_REMOVE(&pq->pq_pl, m, pageq);
1753	(*pq->pq_cnt)--;
1754}
1755
1756/*
1757 *	vm_page_enqueue:
1758 *
1759 *	Add the given page to the specified page queue.
1760 *
1761 *	The page must be locked.
1762 */
1763static void
1764vm_page_enqueue(int queue, vm_page_t m)
1765{
1766	struct vm_pagequeue *pq;
1767
1768	vm_page_lock_assert(m, MA_OWNED);
1769	pq = &vm_pagequeues[queue];
1770	vm_pagequeue_lock(pq);
1771	m->queue = queue;
1772	TAILQ_INSERT_TAIL(&pq->pq_pl, m, pageq);
1773	++*pq->pq_cnt;
1774	vm_pagequeue_unlock(pq);
1775}
1776
1777/*
1778 *	vm_page_requeue:
1779 *
1780 *	Move the given page to the tail of its current page queue.
1781 *
1782 *	The page must be locked.
1783 */
1784void
1785vm_page_requeue(vm_page_t m)
1786{
1787	struct vm_pagequeue *pq;
1788
1789	vm_page_lock_assert(m, MA_OWNED);
1790	KASSERT(m->queue != PQ_NONE,
1791	    ("vm_page_requeue: page %p is not queued", m));
1792	pq = &vm_pagequeues[m->queue];
1793	vm_pagequeue_lock(pq);
1794	TAILQ_REMOVE(&pq->pq_pl, m, pageq);
1795	TAILQ_INSERT_TAIL(&pq->pq_pl, m, pageq);
1796	vm_pagequeue_unlock(pq);
1797}
1798
1799/*
1800 *	vm_page_requeue_locked:
1801 *
1802 *	Move the given page to the tail of its current page queue.
1803 *
1804 *	The page queue must be locked.
1805 */
1806void
1807vm_page_requeue_locked(vm_page_t m)
1808{
1809	struct vm_pagequeue *pq;
1810
1811	KASSERT(m->queue != PQ_NONE,
1812	    ("vm_page_requeue_locked: page %p is not queued", m));
1813	pq = &vm_pagequeues[m->queue];
1814	vm_pagequeue_assert_locked(pq);
1815	TAILQ_REMOVE(&pq->pq_pl, m, pageq);
1816	TAILQ_INSERT_TAIL(&pq->pq_pl, m, pageq);
1817}
1818
1819/*
1820 *	vm_page_activate:
1821 *
1822 *	Put the specified page on the active list (if appropriate).
1823 *	Ensure that act_count is at least ACT_INIT but do not otherwise
1824 *	mess with it.
1825 *
1826 *	The page must be locked.
1827 */
1828void
1829vm_page_activate(vm_page_t m)
1830{
1831	int queue;
1832
1833	vm_page_lock_assert(m, MA_OWNED);
1834	if ((queue = m->queue) != PQ_ACTIVE) {
1835		if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
1836			if (m->act_count < ACT_INIT)
1837				m->act_count = ACT_INIT;
1838			if (queue != PQ_NONE)
1839				vm_page_dequeue(m);
1840			vm_page_enqueue(PQ_ACTIVE, m);
1841		} else
1842			KASSERT(queue == PQ_NONE,
1843			    ("vm_page_activate: wired page %p is queued", m));
1844	} else {
1845		if (m->act_count < ACT_INIT)
1846			m->act_count = ACT_INIT;
1847	}
1848}
1849
1850/*
1851 *	vm_page_free_wakeup:
1852 *
1853 *	Helper routine for vm_page_free_toq() and vm_page_cache().  This
1854 *	routine is called when a page has been added to the cache or free
1855 *	queues.
1856 *
1857 *	The page queues must be locked.
1858 */
1859static inline void
1860vm_page_free_wakeup(void)
1861{
1862
1863	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1864	/*
1865	 * if pageout daemon needs pages, then tell it that there are
1866	 * some free.
1867	 */
1868	if (vm_pageout_pages_needed &&
1869	    cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
1870		wakeup(&vm_pageout_pages_needed);
1871		vm_pageout_pages_needed = 0;
1872	}
1873	/*
1874	 * wakeup processes that are waiting on memory if we hit a
1875	 * high water mark. And wakeup scheduler process if we have
1876	 * lots of memory. this process will swapin processes.
1877	 */
1878	if (vm_pages_needed && !vm_page_count_min()) {
1879		vm_pages_needed = 0;
1880		wakeup(&cnt.v_free_count);
1881	}
1882}
1883
1884/*
1885 *	vm_page_free_toq:
1886 *
1887 *	Returns the given page to the free list,
1888 *	disassociating it with any VM object.
1889 *
1890 *	The object must be locked.  The page must be locked if it is managed.
1891 */
1892void
1893vm_page_free_toq(vm_page_t m)
1894{
1895
1896	if ((m->oflags & VPO_UNMANAGED) == 0) {
1897		vm_page_lock_assert(m, MA_OWNED);
1898		KASSERT(!pmap_page_is_mapped(m),
1899		    ("vm_page_free_toq: freeing mapped page %p", m));
1900	} else
1901		KASSERT(m->queue == PQ_NONE,
1902		    ("vm_page_free_toq: unmanaged page %p is queued", m));
1903	PCPU_INC(cnt.v_tfree);
1904
1905	if (VM_PAGE_IS_FREE(m))
1906		panic("vm_page_free: freeing free page %p", m);
1907	else if (m->busy != 0)
1908		panic("vm_page_free: freeing busy page %p", m);
1909
1910	/*
1911	 * Unqueue, then remove page.  Note that we cannot destroy
1912	 * the page here because we do not want to call the pager's
1913	 * callback routine until after we've put the page on the
1914	 * appropriate free queue.
1915	 */
1916	vm_page_remque(m);
1917	vm_page_remove(m);
1918
1919	/*
1920	 * If fictitious remove object association and
1921	 * return, otherwise delay object association removal.
1922	 */
1923	if ((m->flags & PG_FICTITIOUS) != 0) {
1924		return;
1925	}
1926
1927	m->valid = 0;
1928	vm_page_undirty(m);
1929
1930	if (m->wire_count != 0)
1931		panic("vm_page_free: freeing wired page %p", m);
1932	if (m->hold_count != 0) {
1933		m->flags &= ~PG_ZERO;
1934		KASSERT((m->flags & PG_UNHOLDFREE) == 0,
1935		    ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
1936		m->flags |= PG_UNHOLDFREE;
1937	} else {
1938		/*
1939		 * Restore the default memory attribute to the page.
1940		 */
1941		if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
1942			pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
1943
1944		/*
1945		 * Insert the page into the physical memory allocator's
1946		 * cache/free page queues.
1947		 */
1948		mtx_lock(&vm_page_queue_free_mtx);
1949		m->flags |= PG_FREE;
1950		cnt.v_free_count++;
1951#if VM_NRESERVLEVEL > 0
1952		if (!vm_reserv_free_page(m))
1953#else
1954		if (TRUE)
1955#endif
1956			vm_phys_free_pages(m, 0);
1957		if ((m->flags & PG_ZERO) != 0)
1958			++vm_page_zero_count;
1959		else
1960			vm_page_zero_idle_wakeup();
1961		vm_page_free_wakeup();
1962		mtx_unlock(&vm_page_queue_free_mtx);
1963	}
1964}
1965
1966/*
1967 *	vm_page_wire:
1968 *
1969 *	Mark this page as wired down by yet
1970 *	another map, removing it from paging queues
1971 *	as necessary.
1972 *
1973 *	If the page is fictitious, then its wire count must remain one.
1974 *
1975 *	The page must be locked.
1976 */
1977void
1978vm_page_wire(vm_page_t m)
1979{
1980
1981	/*
1982	 * Only bump the wire statistics if the page is not already wired,
1983	 * and only unqueue the page if it is on some queue (if it is unmanaged
1984	 * it is already off the queues).
1985	 */
1986	vm_page_lock_assert(m, MA_OWNED);
1987	if ((m->flags & PG_FICTITIOUS) != 0) {
1988		KASSERT(m->wire_count == 1,
1989		    ("vm_page_wire: fictitious page %p's wire count isn't one",
1990		    m));
1991		return;
1992	}
1993	if (m->wire_count == 0) {
1994		KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
1995		    m->queue == PQ_NONE,
1996		    ("vm_page_wire: unmanaged page %p is queued", m));
1997		vm_page_remque(m);
1998		atomic_add_int(&cnt.v_wire_count, 1);
1999	}
2000	m->wire_count++;
2001	KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
2002}
2003
2004/*
2005 * vm_page_unwire:
2006 *
2007 * Release one wiring of the specified page, potentially enabling it to be
2008 * paged again.  If paging is enabled, then the value of the parameter
2009 * "activate" determines to which queue the page is added.  If "activate" is
2010 * non-zero, then the page is added to the active queue.  Otherwise, it is
2011 * added to the inactive queue.
2012 *
2013 * However, unless the page belongs to an object, it is not enqueued because
2014 * it cannot be paged out.
2015 *
2016 * If a page is fictitious, then its wire count must always be one.
2017 *
2018 * A managed page must be locked.
2019 */
2020void
2021vm_page_unwire(vm_page_t m, int activate)
2022{
2023
2024	if ((m->oflags & VPO_UNMANAGED) == 0)
2025		vm_page_lock_assert(m, MA_OWNED);
2026	if ((m->flags & PG_FICTITIOUS) != 0) {
2027		KASSERT(m->wire_count == 1,
2028	    ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
2029		return;
2030	}
2031	if (m->wire_count > 0) {
2032		m->wire_count--;
2033		if (m->wire_count == 0) {
2034			atomic_subtract_int(&cnt.v_wire_count, 1);
2035			if ((m->oflags & VPO_UNMANAGED) != 0 ||
2036			    m->object == NULL)
2037				return;
2038			if (!activate)
2039				m->flags &= ~PG_WINATCFLS;
2040			vm_page_enqueue(activate ? PQ_ACTIVE : PQ_INACTIVE, m);
2041		}
2042	} else
2043		panic("vm_page_unwire: page %p's wire count is zero", m);
2044}
2045
2046/*
2047 * Move the specified page to the inactive queue.
2048 *
2049 * Many pages placed on the inactive queue should actually go
2050 * into the cache, but it is difficult to figure out which.  What
2051 * we do instead, if the inactive target is well met, is to put
2052 * clean pages at the head of the inactive queue instead of the tail.
2053 * This will cause them to be moved to the cache more quickly and
2054 * if not actively re-referenced, reclaimed more quickly.  If we just
2055 * stick these pages at the end of the inactive queue, heavy filesystem
2056 * meta-data accesses can cause an unnecessary paging load on memory bound
2057 * processes.  This optimization causes one-time-use metadata to be
2058 * reused more quickly.
2059 *
2060 * Normally athead is 0 resulting in LRU operation.  athead is set
2061 * to 1 if we want this page to be 'as if it were placed in the cache',
2062 * except without unmapping it from the process address space.
2063 *
2064 * The page must be locked.
2065 */
2066static inline void
2067_vm_page_deactivate(vm_page_t m, int athead)
2068{
2069	struct vm_pagequeue *pq;
2070	int queue;
2071
2072	vm_page_lock_assert(m, MA_OWNED);
2073
2074	/*
2075	 * Ignore if already inactive.
2076	 */
2077	if ((queue = m->queue) == PQ_INACTIVE)
2078		return;
2079	if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2080		if (queue != PQ_NONE)
2081			vm_page_dequeue(m);
2082		m->flags &= ~PG_WINATCFLS;
2083		pq = &vm_pagequeues[PQ_INACTIVE];
2084		vm_pagequeue_lock(pq);
2085		m->queue = PQ_INACTIVE;
2086		if (athead)
2087			TAILQ_INSERT_HEAD(&pq->pq_pl, m, pageq);
2088		else
2089			TAILQ_INSERT_TAIL(&pq->pq_pl, m, pageq);
2090		cnt.v_inactive_count++;
2091		vm_pagequeue_unlock(pq);
2092	}
2093}
2094
2095/*
2096 * Move the specified page to the inactive queue.
2097 *
2098 * The page must be locked.
2099 */
2100void
2101vm_page_deactivate(vm_page_t m)
2102{
2103
2104	_vm_page_deactivate(m, 0);
2105}
2106
2107/*
2108 * vm_page_try_to_cache:
2109 *
2110 * Returns 0 on failure, 1 on success
2111 */
2112int
2113vm_page_try_to_cache(vm_page_t m)
2114{
2115
2116	vm_page_lock_assert(m, MA_OWNED);
2117	VM_OBJECT_ASSERT_WLOCKED(m->object);
2118	if (m->dirty || m->hold_count || m->busy || m->wire_count ||
2119	    (m->oflags & (VPO_BUSY | VPO_UNMANAGED)) != 0)
2120		return (0);
2121	pmap_remove_all(m);
2122	if (m->dirty)
2123		return (0);
2124	vm_page_cache(m);
2125	return (1);
2126}
2127
2128/*
2129 * vm_page_try_to_free()
2130 *
2131 *	Attempt to free the page.  If we cannot free it, we do nothing.
2132 *	1 is returned on success, 0 on failure.
2133 */
2134int
2135vm_page_try_to_free(vm_page_t m)
2136{
2137
2138	vm_page_lock_assert(m, MA_OWNED);
2139	if (m->object != NULL)
2140		VM_OBJECT_ASSERT_WLOCKED(m->object);
2141	if (m->dirty || m->hold_count || m->busy || m->wire_count ||
2142	    (m->oflags & (VPO_BUSY | VPO_UNMANAGED)) != 0)
2143		return (0);
2144	pmap_remove_all(m);
2145	if (m->dirty)
2146		return (0);
2147	vm_page_free(m);
2148	return (1);
2149}
2150
2151/*
2152 * vm_page_cache
2153 *
2154 * Put the specified page onto the page cache queue (if appropriate).
2155 *
2156 * The object and page must be locked.
2157 */
2158void
2159vm_page_cache(vm_page_t m)
2160{
2161	vm_object_t object;
2162	boolean_t cache_was_empty;
2163
2164	vm_page_lock_assert(m, MA_OWNED);
2165	object = m->object;
2166	VM_OBJECT_ASSERT_WLOCKED(object);
2167	if ((m->oflags & (VPO_UNMANAGED | VPO_BUSY)) || m->busy ||
2168	    m->hold_count || m->wire_count)
2169		panic("vm_page_cache: attempting to cache busy page");
2170	KASSERT(!pmap_page_is_mapped(m),
2171	    ("vm_page_cache: page %p is mapped", m));
2172	KASSERT(m->dirty == 0, ("vm_page_cache: page %p is dirty", m));
2173	if (m->valid == 0 || object->type == OBJT_DEFAULT ||
2174	    (object->type == OBJT_SWAP &&
2175	    !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
2176		/*
2177		 * Hypothesis: A cache-elgible page belonging to a
2178		 * default object or swap object but without a backing
2179		 * store must be zero filled.
2180		 */
2181		vm_page_free(m);
2182		return;
2183	}
2184	KASSERT((m->flags & PG_CACHED) == 0,
2185	    ("vm_page_cache: page %p is already cached", m));
2186	PCPU_INC(cnt.v_tcached);
2187
2188	/*
2189	 * Remove the page from the paging queues.
2190	 */
2191	vm_page_remque(m);
2192
2193	/*
2194	 * Remove the page from the object's collection of resident
2195	 * pages.
2196	 */
2197	vm_radix_remove(&object->rtree, m->pindex);
2198	TAILQ_REMOVE(&object->memq, m, listq);
2199	object->resident_page_count--;
2200
2201	/*
2202	 * Restore the default memory attribute to the page.
2203	 */
2204	if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2205		pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2206
2207	/*
2208	 * Insert the page into the object's collection of cached pages
2209	 * and the physical memory allocator's cache/free page queues.
2210	 */
2211	m->flags &= ~PG_ZERO;
2212	mtx_lock(&vm_page_queue_free_mtx);
2213	m->flags |= PG_CACHED;
2214	cnt.v_cache_count++;
2215	cache_was_empty = vm_radix_is_empty(&object->cache);
2216	vm_radix_insert(&object->cache, m);
2217#if VM_NRESERVLEVEL > 0
2218	if (!vm_reserv_free_page(m)) {
2219#else
2220	if (TRUE) {
2221#endif
2222		vm_phys_set_pool(VM_FREEPOOL_CACHE, m, 0);
2223		vm_phys_free_pages(m, 0);
2224	}
2225	vm_page_free_wakeup();
2226	mtx_unlock(&vm_page_queue_free_mtx);
2227
2228	/*
2229	 * Increment the vnode's hold count if this is the object's only
2230	 * cached page.  Decrement the vnode's hold count if this was
2231	 * the object's only resident page.
2232	 */
2233	if (object->type == OBJT_VNODE) {
2234		if (cache_was_empty && object->resident_page_count != 0)
2235			vhold(object->handle);
2236		else if (!cache_was_empty && object->resident_page_count == 0)
2237			vdrop(object->handle);
2238	}
2239}
2240
2241/*
2242 * vm_page_advise
2243 *
2244 *	Cache, deactivate, or do nothing as appropriate.  This routine
2245 *	is used by madvise().
2246 *
2247 *	Generally speaking we want to move the page into the cache so
2248 *	it gets reused quickly.  However, this can result in a silly syndrome
2249 *	due to the page recycling too quickly.  Small objects will not be
2250 *	fully cached.  On the other hand, if we move the page to the inactive
2251 *	queue we wind up with a problem whereby very large objects
2252 *	unnecessarily blow away our inactive and cache queues.
2253 *
2254 *	The solution is to move the pages based on a fixed weighting.  We
2255 *	either leave them alone, deactivate them, or move them to the cache,
2256 *	where moving them to the cache has the highest weighting.
2257 *	By forcing some pages into other queues we eventually force the
2258 *	system to balance the queues, potentially recovering other unrelated
2259 *	space from active.  The idea is to not force this to happen too
2260 *	often.
2261 *
2262 *	The object and page must be locked.
2263 */
2264void
2265vm_page_advise(vm_page_t m, int advice)
2266{
2267	int dnw, head;
2268
2269	vm_page_assert_locked(m);
2270	VM_OBJECT_ASSERT_WLOCKED(m->object);
2271	if (advice == MADV_FREE) {
2272		/*
2273		 * Mark the page clean.  This will allow the page to be freed
2274		 * up by the system.  However, such pages are often reused
2275		 * quickly by malloc() so we do not do anything that would
2276		 * cause a page fault if we can help it.
2277		 *
2278		 * Specifically, we do not try to actually free the page now
2279		 * nor do we try to put it in the cache (which would cause a
2280		 * page fault on reuse).
2281		 *
2282		 * But we do make the page is freeable as we can without
2283		 * actually taking the step of unmapping it.
2284		 */
2285		pmap_clear_modify(m);
2286		m->dirty = 0;
2287		m->act_count = 0;
2288	} else if (advice != MADV_DONTNEED)
2289		return;
2290	dnw = PCPU_GET(dnweight);
2291	PCPU_INC(dnweight);
2292
2293	/*
2294	 * Occasionally leave the page alone.
2295	 */
2296	if ((dnw & 0x01F0) == 0 || m->queue == PQ_INACTIVE) {
2297		if (m->act_count >= ACT_INIT)
2298			--m->act_count;
2299		return;
2300	}
2301
2302	/*
2303	 * Clear any references to the page.  Otherwise, the page daemon will
2304	 * immediately reactivate the page.
2305	 *
2306	 * Perform the pmap_clear_reference() first.  Otherwise, a concurrent
2307	 * pmap operation, such as pmap_remove(), could clear a reference in
2308	 * the pmap and set PGA_REFERENCED on the page before the
2309	 * pmap_clear_reference() had completed.  Consequently, the page would
2310	 * appear referenced based upon an old reference that occurred before
2311	 * this function ran.
2312	 */
2313	pmap_clear_reference(m);
2314	vm_page_aflag_clear(m, PGA_REFERENCED);
2315
2316	if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
2317		vm_page_dirty(m);
2318
2319	if (m->dirty || (dnw & 0x0070) == 0) {
2320		/*
2321		 * Deactivate the page 3 times out of 32.
2322		 */
2323		head = 0;
2324	} else {
2325		/*
2326		 * Cache the page 28 times out of every 32.  Note that
2327		 * the page is deactivated instead of cached, but placed
2328		 * at the head of the queue instead of the tail.
2329		 */
2330		head = 1;
2331	}
2332	_vm_page_deactivate(m, head);
2333}
2334
2335/*
2336 * Grab a page, waiting until we are waken up due to the page
2337 * changing state.  We keep on waiting, if the page continues
2338 * to be in the object.  If the page doesn't exist, first allocate it
2339 * and then conditionally zero it.
2340 *
2341 * The caller must always specify the VM_ALLOC_RETRY flag.  This is intended
2342 * to facilitate its eventual removal.
2343 *
2344 * This routine may sleep.
2345 *
2346 * The object must be locked on entry.  The lock will, however, be released
2347 * and reacquired if the routine sleeps.
2348 */
2349vm_page_t
2350vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
2351{
2352	vm_page_t m;
2353
2354	VM_OBJECT_ASSERT_WLOCKED(object);
2355	KASSERT((allocflags & VM_ALLOC_RETRY) != 0,
2356	    ("vm_page_grab: VM_ALLOC_RETRY is required"));
2357retrylookup:
2358	if ((m = vm_page_lookup(object, pindex)) != NULL) {
2359		if ((m->oflags & VPO_BUSY) != 0 ||
2360		    ((allocflags & VM_ALLOC_IGN_SBUSY) == 0 && m->busy != 0)) {
2361			/*
2362			 * Reference the page before unlocking and
2363			 * sleeping so that the page daemon is less
2364			 * likely to reclaim it.
2365			 */
2366			vm_page_aflag_set(m, PGA_REFERENCED);
2367			vm_page_sleep(m, "pgrbwt");
2368			goto retrylookup;
2369		} else {
2370			if ((allocflags & VM_ALLOC_WIRED) != 0) {
2371				vm_page_lock(m);
2372				vm_page_wire(m);
2373				vm_page_unlock(m);
2374			}
2375			if ((allocflags & VM_ALLOC_NOBUSY) == 0)
2376				vm_page_busy(m);
2377			return (m);
2378		}
2379	}
2380	m = vm_page_alloc(object, pindex, allocflags & ~(VM_ALLOC_RETRY |
2381	    VM_ALLOC_IGN_SBUSY));
2382	if (m == NULL) {
2383		VM_OBJECT_WUNLOCK(object);
2384		VM_WAIT;
2385		VM_OBJECT_WLOCK(object);
2386		goto retrylookup;
2387	} else if (m->valid != 0)
2388		return (m);
2389	if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
2390		pmap_zero_page(m);
2391	return (m);
2392}
2393
2394/*
2395 * Mapping function for valid or dirty bits in a page.
2396 *
2397 * Inputs are required to range within a page.
2398 */
2399vm_page_bits_t
2400vm_page_bits(int base, int size)
2401{
2402	int first_bit;
2403	int last_bit;
2404
2405	KASSERT(
2406	    base + size <= PAGE_SIZE,
2407	    ("vm_page_bits: illegal base/size %d/%d", base, size)
2408	);
2409
2410	if (size == 0)		/* handle degenerate case */
2411		return (0);
2412
2413	first_bit = base >> DEV_BSHIFT;
2414	last_bit = (base + size - 1) >> DEV_BSHIFT;
2415
2416	return (((vm_page_bits_t)2 << last_bit) -
2417	    ((vm_page_bits_t)1 << first_bit));
2418}
2419
2420/*
2421 *	vm_page_set_valid_range:
2422 *
2423 *	Sets portions of a page valid.  The arguments are expected
2424 *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2425 *	of any partial chunks touched by the range.  The invalid portion of
2426 *	such chunks will be zeroed.
2427 *
2428 *	(base + size) must be less then or equal to PAGE_SIZE.
2429 */
2430void
2431vm_page_set_valid_range(vm_page_t m, int base, int size)
2432{
2433	int endoff, frag;
2434
2435	VM_OBJECT_ASSERT_WLOCKED(m->object);
2436	if (size == 0)	/* handle degenerate case */
2437		return;
2438
2439	/*
2440	 * If the base is not DEV_BSIZE aligned and the valid
2441	 * bit is clear, we have to zero out a portion of the
2442	 * first block.
2443	 */
2444	if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2445	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2446		pmap_zero_page_area(m, frag, base - frag);
2447
2448	/*
2449	 * If the ending offset is not DEV_BSIZE aligned and the
2450	 * valid bit is clear, we have to zero out a portion of
2451	 * the last block.
2452	 */
2453	endoff = base + size;
2454	if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2455	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2456		pmap_zero_page_area(m, endoff,
2457		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2458
2459	/*
2460	 * Assert that no previously invalid block that is now being validated
2461	 * is already dirty.
2462	 */
2463	KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
2464	    ("vm_page_set_valid_range: page %p is dirty", m));
2465
2466	/*
2467	 * Set valid bits inclusive of any overlap.
2468	 */
2469	m->valid |= vm_page_bits(base, size);
2470}
2471
2472/*
2473 * Clear the given bits from the specified page's dirty field.
2474 */
2475static __inline void
2476vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
2477{
2478	uintptr_t addr;
2479#if PAGE_SIZE < 16384
2480	int shift;
2481#endif
2482
2483	/*
2484	 * If the object is locked and the page is neither VPO_BUSY nor
2485	 * write mapped, then the page's dirty field cannot possibly be
2486	 * set by a concurrent pmap operation.
2487	 */
2488	VM_OBJECT_ASSERT_WLOCKED(m->object);
2489	if ((m->oflags & VPO_BUSY) == 0 && !pmap_page_is_write_mapped(m))
2490		m->dirty &= ~pagebits;
2491	else {
2492		/*
2493		 * The pmap layer can call vm_page_dirty() without
2494		 * holding a distinguished lock.  The combination of
2495		 * the object's lock and an atomic operation suffice
2496		 * to guarantee consistency of the page dirty field.
2497		 *
2498		 * For PAGE_SIZE == 32768 case, compiler already
2499		 * properly aligns the dirty field, so no forcible
2500		 * alignment is needed. Only require existence of
2501		 * atomic_clear_64 when page size is 32768.
2502		 */
2503		addr = (uintptr_t)&m->dirty;
2504#if PAGE_SIZE == 32768
2505		atomic_clear_64((uint64_t *)addr, pagebits);
2506#elif PAGE_SIZE == 16384
2507		atomic_clear_32((uint32_t *)addr, pagebits);
2508#else		/* PAGE_SIZE <= 8192 */
2509		/*
2510		 * Use a trick to perform a 32-bit atomic on the
2511		 * containing aligned word, to not depend on the existence
2512		 * of atomic_clear_{8, 16}.
2513		 */
2514		shift = addr & (sizeof(uint32_t) - 1);
2515#if BYTE_ORDER == BIG_ENDIAN
2516		shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
2517#else
2518		shift *= NBBY;
2519#endif
2520		addr &= ~(sizeof(uint32_t) - 1);
2521		atomic_clear_32((uint32_t *)addr, pagebits << shift);
2522#endif		/* PAGE_SIZE */
2523	}
2524}
2525
2526/*
2527 *	vm_page_set_validclean:
2528 *
2529 *	Sets portions of a page valid and clean.  The arguments are expected
2530 *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2531 *	of any partial chunks touched by the range.  The invalid portion of
2532 *	such chunks will be zero'd.
2533 *
2534 *	(base + size) must be less then or equal to PAGE_SIZE.
2535 */
2536void
2537vm_page_set_validclean(vm_page_t m, int base, int size)
2538{
2539	vm_page_bits_t oldvalid, pagebits;
2540	int endoff, frag;
2541
2542	VM_OBJECT_ASSERT_WLOCKED(m->object);
2543	if (size == 0)	/* handle degenerate case */
2544		return;
2545
2546	/*
2547	 * If the base is not DEV_BSIZE aligned and the valid
2548	 * bit is clear, we have to zero out a portion of the
2549	 * first block.
2550	 */
2551	if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2552	    (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
2553		pmap_zero_page_area(m, frag, base - frag);
2554
2555	/*
2556	 * If the ending offset is not DEV_BSIZE aligned and the
2557	 * valid bit is clear, we have to zero out a portion of
2558	 * the last block.
2559	 */
2560	endoff = base + size;
2561	if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2562	    (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
2563		pmap_zero_page_area(m, endoff,
2564		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2565
2566	/*
2567	 * Set valid, clear dirty bits.  If validating the entire
2568	 * page we can safely clear the pmap modify bit.  We also
2569	 * use this opportunity to clear the VPO_NOSYNC flag.  If a process
2570	 * takes a write fault on a MAP_NOSYNC memory area the flag will
2571	 * be set again.
2572	 *
2573	 * We set valid bits inclusive of any overlap, but we can only
2574	 * clear dirty bits for DEV_BSIZE chunks that are fully within
2575	 * the range.
2576	 */
2577	oldvalid = m->valid;
2578	pagebits = vm_page_bits(base, size);
2579	m->valid |= pagebits;
2580#if 0	/* NOT YET */
2581	if ((frag = base & (DEV_BSIZE - 1)) != 0) {
2582		frag = DEV_BSIZE - frag;
2583		base += frag;
2584		size -= frag;
2585		if (size < 0)
2586			size = 0;
2587	}
2588	pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
2589#endif
2590	if (base == 0 && size == PAGE_SIZE) {
2591		/*
2592		 * The page can only be modified within the pmap if it is
2593		 * mapped, and it can only be mapped if it was previously
2594		 * fully valid.
2595		 */
2596		if (oldvalid == VM_PAGE_BITS_ALL)
2597			/*
2598			 * Perform the pmap_clear_modify() first.  Otherwise,
2599			 * a concurrent pmap operation, such as
2600			 * pmap_protect(), could clear a modification in the
2601			 * pmap and set the dirty field on the page before
2602			 * pmap_clear_modify() had begun and after the dirty
2603			 * field was cleared here.
2604			 */
2605			pmap_clear_modify(m);
2606		m->dirty = 0;
2607		m->oflags &= ~VPO_NOSYNC;
2608	} else if (oldvalid != VM_PAGE_BITS_ALL)
2609		m->dirty &= ~pagebits;
2610	else
2611		vm_page_clear_dirty_mask(m, pagebits);
2612}
2613
2614void
2615vm_page_clear_dirty(vm_page_t m, int base, int size)
2616{
2617
2618	vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
2619}
2620
2621/*
2622 *	vm_page_set_invalid:
2623 *
2624 *	Invalidates DEV_BSIZE'd chunks within a page.  Both the
2625 *	valid and dirty bits for the effected areas are cleared.
2626 */
2627void
2628vm_page_set_invalid(vm_page_t m, int base, int size)
2629{
2630	vm_page_bits_t bits;
2631
2632	VM_OBJECT_ASSERT_WLOCKED(m->object);
2633	KASSERT((m->oflags & VPO_BUSY) == 0,
2634	    ("vm_page_set_invalid: page %p is busy", m));
2635	bits = vm_page_bits(base, size);
2636	if (m->valid == VM_PAGE_BITS_ALL && bits != 0)
2637		pmap_remove_all(m);
2638	KASSERT(!pmap_page_is_mapped(m),
2639	    ("vm_page_set_invalid: page %p is mapped", m));
2640	m->valid &= ~bits;
2641	m->dirty &= ~bits;
2642}
2643
2644/*
2645 * vm_page_zero_invalid()
2646 *
2647 *	The kernel assumes that the invalid portions of a page contain
2648 *	garbage, but such pages can be mapped into memory by user code.
2649 *	When this occurs, we must zero out the non-valid portions of the
2650 *	page so user code sees what it expects.
2651 *
2652 *	Pages are most often semi-valid when the end of a file is mapped
2653 *	into memory and the file's size is not page aligned.
2654 */
2655void
2656vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
2657{
2658	int b;
2659	int i;
2660
2661	VM_OBJECT_ASSERT_WLOCKED(m->object);
2662	/*
2663	 * Scan the valid bits looking for invalid sections that
2664	 * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
2665	 * valid bit may be set ) have already been zerod by
2666	 * vm_page_set_validclean().
2667	 */
2668	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
2669		if (i == (PAGE_SIZE / DEV_BSIZE) ||
2670		    (m->valid & ((vm_page_bits_t)1 << i))) {
2671			if (i > b) {
2672				pmap_zero_page_area(m,
2673				    b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
2674			}
2675			b = i + 1;
2676		}
2677	}
2678
2679	/*
2680	 * setvalid is TRUE when we can safely set the zero'd areas
2681	 * as being valid.  We can do this if there are no cache consistancy
2682	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
2683	 */
2684	if (setvalid)
2685		m->valid = VM_PAGE_BITS_ALL;
2686}
2687
2688/*
2689 *	vm_page_is_valid:
2690 *
2691 *	Is (partial) page valid?  Note that the case where size == 0
2692 *	will return FALSE in the degenerate case where the page is
2693 *	entirely invalid, and TRUE otherwise.
2694 */
2695int
2696vm_page_is_valid(vm_page_t m, int base, int size)
2697{
2698	vm_page_bits_t bits;
2699
2700	VM_OBJECT_ASSERT_WLOCKED(m->object);
2701	bits = vm_page_bits(base, size);
2702	return (m->valid != 0 && (m->valid & bits) == bits);
2703}
2704
2705/*
2706 * Set the page's dirty bits if the page is modified.
2707 */
2708void
2709vm_page_test_dirty(vm_page_t m)
2710{
2711
2712	VM_OBJECT_ASSERT_WLOCKED(m->object);
2713	if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
2714		vm_page_dirty(m);
2715}
2716
2717void
2718vm_page_lock_KBI(vm_page_t m, const char *file, int line)
2719{
2720
2721	mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
2722}
2723
2724void
2725vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
2726{
2727
2728	mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
2729}
2730
2731int
2732vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
2733{
2734
2735	return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
2736}
2737
2738#if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
2739void
2740vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
2741{
2742
2743	vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
2744}
2745
2746void
2747vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
2748{
2749
2750	mtx_assert_(vm_page_lockptr(m), a, file, line);
2751}
2752#endif
2753
2754int so_zerocp_fullpage = 0;
2755
2756/*
2757 *	Replace the given page with a copy.  The copied page assumes
2758 *	the portion of the given page's "wire_count" that is not the
2759 *	responsibility of this copy-on-write mechanism.
2760 *
2761 *	The object containing the given page must have a non-zero
2762 *	paging-in-progress count and be locked.
2763 */
2764void
2765vm_page_cowfault(vm_page_t m)
2766{
2767	vm_page_t mnew;
2768	vm_object_t object;
2769	vm_pindex_t pindex;
2770
2771	vm_page_lock_assert(m, MA_OWNED);
2772	object = m->object;
2773	VM_OBJECT_ASSERT_WLOCKED(object);
2774	KASSERT(object->paging_in_progress != 0,
2775	    ("vm_page_cowfault: object %p's paging-in-progress count is zero.",
2776	    object));
2777	pindex = m->pindex;
2778
2779 retry_alloc:
2780	pmap_remove_all(m);
2781	vm_page_remove(m);
2782	mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY);
2783	if (mnew == NULL) {
2784		vm_page_insert(m, object, pindex);
2785		vm_page_unlock(m);
2786		VM_OBJECT_WUNLOCK(object);
2787		VM_WAIT;
2788		VM_OBJECT_WLOCK(object);
2789		if (m == vm_page_lookup(object, pindex)) {
2790			vm_page_lock(m);
2791			goto retry_alloc;
2792		} else {
2793			/*
2794			 * Page disappeared during the wait.
2795			 */
2796			return;
2797		}
2798	}
2799
2800	if (m->cow == 0) {
2801		/*
2802		 * check to see if we raced with an xmit complete when
2803		 * waiting to allocate a page.  If so, put things back
2804		 * the way they were
2805		 */
2806		vm_page_unlock(m);
2807		vm_page_lock(mnew);
2808		vm_page_free(mnew);
2809		vm_page_unlock(mnew);
2810		vm_page_insert(m, object, pindex);
2811	} else { /* clear COW & copy page */
2812		if (!so_zerocp_fullpage)
2813			pmap_copy_page(m, mnew);
2814		mnew->valid = VM_PAGE_BITS_ALL;
2815		vm_page_dirty(mnew);
2816		mnew->wire_count = m->wire_count - m->cow;
2817		m->wire_count = m->cow;
2818		vm_page_unlock(m);
2819	}
2820}
2821
2822void
2823vm_page_cowclear(vm_page_t m)
2824{
2825
2826	vm_page_lock_assert(m, MA_OWNED);
2827	if (m->cow) {
2828		m->cow--;
2829		/*
2830		 * let vm_fault add back write permission  lazily
2831		 */
2832	}
2833	/*
2834	 *  sf_buf_free() will free the page, so we needn't do it here
2835	 */
2836}
2837
2838int
2839vm_page_cowsetup(vm_page_t m)
2840{
2841
2842	vm_page_lock_assert(m, MA_OWNED);
2843	if ((m->flags & PG_FICTITIOUS) != 0 ||
2844	    (m->oflags & VPO_UNMANAGED) != 0 ||
2845	    m->cow == USHRT_MAX - 1 || !VM_OBJECT_TRYWLOCK(m->object))
2846		return (EBUSY);
2847	m->cow++;
2848	pmap_remove_write(m);
2849	VM_OBJECT_WUNLOCK(m->object);
2850	return (0);
2851}
2852
2853#ifdef INVARIANTS
2854void
2855vm_page_object_lock_assert(vm_page_t m)
2856{
2857
2858	/*
2859	 * Certain of the page's fields may only be modified by the
2860	 * holder of the containing object's lock or the setter of the
2861	 * page's VPO_BUSY flag.  Unfortunately, the setter of the
2862	 * VPO_BUSY flag is not recorded, and thus cannot be checked
2863	 * here.
2864	 */
2865	if (m->object != NULL && (m->oflags & VPO_BUSY) == 0)
2866		VM_OBJECT_ASSERT_WLOCKED(m->object);
2867}
2868#endif
2869
2870#include "opt_ddb.h"
2871#ifdef DDB
2872#include <sys/kernel.h>
2873
2874#include <ddb/ddb.h>
2875
2876DB_SHOW_COMMAND(page, vm_page_print_page_info)
2877{
2878	db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
2879	db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
2880	db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
2881	db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
2882	db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
2883	db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
2884	db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
2885	db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
2886	db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
2887	db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
2888}
2889
2890DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
2891{
2892
2893	db_printf("PQ_FREE:");
2894	db_printf(" %d", cnt.v_free_count);
2895	db_printf("\n");
2896
2897	db_printf("PQ_CACHE:");
2898	db_printf(" %d", cnt.v_cache_count);
2899	db_printf("\n");
2900
2901	db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
2902		*vm_pagequeues[PQ_ACTIVE].pq_cnt,
2903		*vm_pagequeues[PQ_INACTIVE].pq_cnt);
2904}
2905
2906DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
2907{
2908	vm_page_t m;
2909	boolean_t phys;
2910
2911	if (!have_addr) {
2912		db_printf("show pginfo addr\n");
2913		return;
2914	}
2915
2916	phys = strchr(modif, 'p') != NULL;
2917	if (phys)
2918		m = PHYS_TO_VM_PAGE(addr);
2919	else
2920		m = (vm_page_t)addr;
2921	db_printf(
2922    "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
2923    "  af 0x%x of 0x%x f 0x%x act %d busy %d valid 0x%x dirty 0x%x\n",
2924	    m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
2925	    m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
2926	    m->flags, m->act_count, m->busy, m->valid, m->dirty);
2927}
2928#endif /* DDB */
2929