vm_page.c revision 225843
1154941Sjhb/*-
2154941Sjhb * Copyright (c) 1991 Regents of the University of California.
3154941Sjhb * All rights reserved.
4154941Sjhb * Copyright (c) 1998 Matthew Dillon.  All Rights Reserved.
5154941Sjhb *
6154941Sjhb * This code is derived from software contributed to Berkeley by
7154941Sjhb * The Mach Operating System project at Carnegie-Mellon University.
8154941Sjhb *
9154941Sjhb * Redistribution and use in source and binary forms, with or without
10154941Sjhb * modification, are permitted provided that the following conditions
11154941Sjhb * are met:
12154941Sjhb * 1. Redistributions of source code must retain the above copyright
13154941Sjhb *    notice, this list of conditions and the following disclaimer.
14154941Sjhb * 2. Redistributions in binary form must reproduce the above copyright
15154941Sjhb *    notice, this list of conditions and the following disclaimer in the
16154941Sjhb *    documentation and/or other materials provided with the distribution.
17154941Sjhb * 4. Neither the name of the University nor the names of its contributors
18154941Sjhb *    may be used to endorse or promote products derived from this software
19154941Sjhb *    without specific prior written permission.
20154941Sjhb *
21154941Sjhb * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22154941Sjhb * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23154941Sjhb * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24154941Sjhb * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25154941Sjhb * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26154941Sjhb * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27154941Sjhb * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28154941Sjhb * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29154941Sjhb * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30154941Sjhb * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31154941Sjhb * SUCH DAMAGE.
32154941Sjhb *
33154941Sjhb *	from: @(#)vm_page.c	7.4 (Berkeley) 5/7/91
34154941Sjhb */
35154941Sjhb
36154941Sjhb/*-
37154941Sjhb * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38192853Ssson * All rights reserved.
39167801Sjhb *
40154941Sjhb * Authors: Avadis Tevanian, Jr., Michael Wayne Young
41154941Sjhb *
42154941Sjhb * Permission to use, copy, modify and distribute this software and
43177912Sjeff * its documentation is hereby granted, provided that both the copyright
44154941Sjhb * notice and this permission notice appear in all copies of the
45154941Sjhb * software, derivative works or modified versions, and any portions
46154941Sjhb * thereof, and that both notices appear in supporting documentation.
47154941Sjhb *
48177912Sjeff * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49154941Sjhb * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50154941Sjhb * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51171516Sattilio *
52154941Sjhb * Carnegie Mellon requests users of this software to return to
53154941Sjhb *
54171052Sattilio *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
55171052Sattilio *  School of Computer Science
56167801Sjhb *  Carnegie Mellon University
57167801Sjhb *  Pittsburgh PA 15213-3890
58167801Sjhb *
59167801Sjhb * any improvements or extensions that they make and grant Carnegie the
60177912Sjeff * rights to redistribute these changes.
61177912Sjeff */
62177912Sjeff
63177912Sjeff/*
64177912Sjeff *			GENERAL RULES ON VM_PAGE MANIPULATION
65177912Sjeff *
66177912Sjeff *	- a pageq mutex is required when adding or removing a page from a
67177912Sjeff *	  page queue (vm_page_queue[]), regardless of other mutexes or the
68154941Sjhb *	  busy state of a page.
69154941Sjhb *
70154941Sjhb *	- The object mutex is held when inserting or removing
71154941Sjhb *	  pages from an object (vm_page_insert() or vm_page_remove()).
72154941Sjhb *
73173733Sattilio */
74167368Sjhb
75192853Ssson/*
76192853Ssson *	Resident memory management module.
77192853Ssson */
78167368Sjhb
79154941Sjhb#include <sys/cdefs.h>
80154941Sjhb__FBSDID("$FreeBSD: head/sys/vm/vm_page.c 225843 2011-09-28 16:12:15Z kib $");
81167365Sjhb
82167365Sjhb#include "opt_vm.h"
83173733Sattilio
84154941Sjhb#include <sys/param.h>
85167365Sjhb#include <sys/systm.h>
86154941Sjhb#include <sys/lock.h>
87167368Sjhb#include <sys/kernel.h>
88167368Sjhb#include <sys/limits.h>
89192853Ssson#include <sys/malloc.h>
90192853Ssson#include <sys/msgbuf.h>
91192853Ssson#include <sys/mutex.h>
92154941Sjhb#include <sys/proc.h>
93154941Sjhb#include <sys/sysctl.h>
94157826Sjhb#include <sys/vmmeter.h>
95157826Sjhb#include <sys/vnode.h>
96157826Sjhb
97157826Sjhb#include <vm/vm.h>
98157826Sjhb#include <vm/pmap.h>
99154941Sjhb#include <vm/vm_param.h>
100154941Sjhb#include <vm/vm_kern.h>
101154941Sjhb#include <vm/vm_object.h>
102157826Sjhb#include <vm/vm_page.h>
103171052Sattilio#include <vm/vm_pageout.h>
104171052Sattilio#include <vm/vm_pager.h>
105171052Sattilio#include <vm/vm_phys.h>
106171052Sattilio#include <vm/vm_reserv.h>
107171052Sattilio#include <vm/vm_extern.h>
108171052Sattilio#include <vm/uma.h>
109171052Sattilio#include <vm/uma_int.h>
110171052Sattilio
111171052Sattilio#include <machine/md_var.h>
112171052Sattilio
113171052Sattilio/*
114157826Sjhb *	Associated with page of user-allocatable memory is a
115157826Sjhb *	page structure.
116157826Sjhb */
117157826Sjhb
118157826Sjhbstruct vpgqueues vm_page_queues[PQ_COUNT];
119157826Sjhbstruct vpglocks vm_page_queue_lock;
120154941Sjhbstruct vpglocks vm_page_queue_free_lock;
121154941Sjhb
122154941Sjhbstruct vpglocks	pa_lock[PA_LOCK_COUNT];
123154941Sjhb
124154941Sjhbvm_page_t vm_page_array = 0;
125173733Sattilioint vm_page_array_size = 0;
126173733Sattiliolong first_page = 0;
127173733Sattilioint vm_page_zero_count = 0;
128173733Sattilio
129173733Sattiliostatic int boot_pages = UMA_BOOT_PAGES;
130173733SattilioTUNABLE_INT("vm.boot_pages", &boot_pages);
131173733SattilioSYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RD, &boot_pages, 0,
132167368Sjhb	"number of pages allocated for bootstrapping the VM system");
133167368Sjhb
134167368Sjhbstatic int pa_tryrelock_restart;
135167368SjhbSYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
136167368Sjhb    &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
137167368Sjhb
138167368Sjhbstatic uma_zone_t fakepg_zone;
139167368Sjhb
140167368Sjhbstatic void vm_page_clear_dirty_mask(vm_page_t m, int pagebits);
141167368Sjhbstatic void vm_page_queue_remove(int queue, vm_page_t m);
142167368Sjhbstatic void vm_page_enqueue(int queue, vm_page_t m);
143167368Sjhbstatic void vm_page_init_fakepg(void *dummy);
144167368Sjhb
145167368SjhbSYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init_fakepg, NULL);
146167368Sjhb
147167368Sjhbstatic void
148167368Sjhbvm_page_init_fakepg(void *dummy)
149167368Sjhb{
150167368Sjhb
151167368Sjhb	fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
152167368Sjhb	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
153167368Sjhb}
154167368Sjhb
155167368Sjhb/* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
156167368Sjhb#if PAGE_SIZE == 32768
157167368Sjhb#ifdef CTASSERT
158167368SjhbCTASSERT(sizeof(u_long) >= 8);
159192853Ssson#endif
160192853Ssson#endif
161192853Ssson
162192853Ssson/*
163192853Ssson * Try to acquire a physical address lock while a pmap is locked.  If we
164192853Ssson * fail to trylock we unlock and lock the pmap directly and cache the
165192853Ssson * locked pa in *locked.  The caller should then restart their loop in case
166192853Ssson * the virtual to physical mapping has changed.
167192853Ssson */
168192853Sssonint
169192853Sssonvm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
170192853Ssson{
171192853Ssson	vm_paddr_t lockpa;
172167368Sjhb
173171052Sattilio	lockpa = *locked;
174154941Sjhb	*locked = pa;
175171052Sattilio	if (lockpa) {
176154941Sjhb		PA_LOCK_ASSERT(lockpa, MA_OWNED);
177171052Sattilio		if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
178171052Sattilio			return (0);
179171052Sattilio		PA_UNLOCK(lockpa);
180171052Sattilio	}
181171052Sattilio	if (PA_TRYLOCK(pa))
182171052Sattilio		return (0);
183171052Sattilio	PMAP_UNLOCK(pmap);
184171052Sattilio	atomic_add_int(&pa_tryrelock_restart, 1);
185171052Sattilio	PA_LOCK(pa);
186171052Sattilio	PMAP_LOCK(pmap);
187171052Sattilio	return (EAGAIN);
188171052Sattilio}
189171052Sattilio
190171052Sattilio/*
191154941Sjhb *	vm_set_page_size:
192171052Sattilio *
193171052Sattilio *	Sets the page size, perhaps based upon the memory
194154941Sjhb *	size.  Must be called before any use of page-size
195154941Sjhb *	dependent functions.
196154941Sjhb */
197154941Sjhbvoid
198154941Sjhbvm_set_page_size(void)
199154941Sjhb{
200154941Sjhb	if (cnt.v_page_size == 0)
201171052Sattilio		cnt.v_page_size = PAGE_SIZE;
202169394Sjhb	if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0)
203167787Sjhb		panic("vm_set_page_size: page size not a power of two");
204154941Sjhb}
205154941Sjhb
206154941Sjhb/*
207154941Sjhb *	vm_page_blacklist_lookup:
208154941Sjhb *
209154941Sjhb *	See if a physical address in this page has been listed
210154941Sjhb *	in the blacklist tunable.  Entries in the tunable are
211154941Sjhb *	separated by spaces or commas.  If an invalid integer is
212154941Sjhb *	encountered then the rest of the string is skipped.
213154941Sjhb */
214185778Skmacystatic int
215185778Skmacyvm_page_blacklist_lookup(char *list, vm_paddr_t pa)
216185778Skmacy{
217185778Skmacy	vm_paddr_t bad;
218185778Skmacy	char *cp, *pos;
219185778Skmacy
220185778Skmacy	for (pos = list; *pos != '\0'; pos = cp) {
221185778Skmacy		bad = strtoq(pos, &cp, 0);
222167024Srwatson		if (*cp != '\0') {
223167024Srwatson			if (*cp == ' ' || *cp == ',') {
224167024Srwatson				cp++;
225167024Srwatson				if (cp == pos)
226167024Srwatson					continue;
227167024Srwatson			} else
228167024Srwatson				break;
229154941Sjhb		}
230154941Sjhb		if (pa == trunc_page(bad))
231154941Sjhb			return (1);
232154941Sjhb	}
233154941Sjhb	return (0);
234169394Sjhb}
235169394Sjhb
236167787Sjhb/*
237182914Sjhb *	vm_page_startup:
238154941Sjhb *
239171052Sattilio *	Initializes the resident memory module.
240167787Sjhb *
241160771Sjhb *	Allocates memory for the page cells, and
242154941Sjhb *	for the object/offset-to-page hash table headers.
243154941Sjhb *	Each page cell is initialized and placed on the free list.
244177843Sattilio */
245177843Sattiliovm_offset_t
246177843Sattiliovm_page_startup(vm_offset_t vaddr)
247177843Sattilio{
248177843Sattilio	vm_offset_t mapped;
249177843Sattilio	vm_paddr_t page_range;
250177843Sattilio	vm_paddr_t new_end;
251177843Sattilio	int i;
252177843Sattilio	vm_paddr_t pa;
253177843Sattilio	vm_paddr_t last_pa;
254177843Sattilio	char *list;
255177843Sattilio
256177843Sattilio	/* the biggest memory array is the second group of pages */
257177843Sattilio	vm_paddr_t end;
258177843Sattilio	vm_paddr_t biggestsize;
259177843Sattilio	vm_paddr_t low_water, high_water;
260177843Sattilio	int biggestone;
261177843Sattilio
262177843Sattilio	biggestsize = 0;
263177843Sattilio	biggestone = 0;
264177843Sattilio	vaddr = round_page(vaddr);
265177843Sattilio
266177843Sattilio	for (i = 0; phys_avail[i + 1]; i += 2) {
267177843Sattilio		phys_avail[i] = round_page(phys_avail[i]);
268154941Sjhb		phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
269154941Sjhb	}
270154941Sjhb
271154941Sjhb	low_water = phys_avail[0];
272154941Sjhb	high_water = phys_avail[1];
273169394Sjhb
274169394Sjhb	for (i = 0; phys_avail[i + 1]; i += 2) {
275154941Sjhb		vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
276160771Sjhb
277167787Sjhb		if (size > biggestsize) {
278171052Sattilio			biggestone = i;
279171052Sattilio			biggestsize = size;
280171052Sattilio		}
281192853Ssson		if (phys_avail[i] < low_water)
282154941Sjhb			low_water = phys_avail[i];
283154941Sjhb		if (phys_avail[i + 1] > high_water)
284176017Sjeff			high_water = phys_avail[i + 1];
285176017Sjeff	}
286176017Sjeff
287176017Sjeff#ifdef XEN
288176017Sjeff	low_water = 0;
289176017Sjeff#endif
290176017Sjeff
291176017Sjeff	end = phys_avail[biggestone+1];
292176017Sjeff
293176017Sjeff	/*
294176017Sjeff	 * Initialize the locks.
295154941Sjhb	 */
296154941Sjhb	mtx_init(&vm_page_queue_mtx, "vm page queue mutex", NULL, MTX_DEF |
297154941Sjhb	    MTX_RECURSE);
298154941Sjhb	mtx_init(&vm_page_queue_free_mtx, "vm page queue free mutex", NULL,
299170295Sjeff	    MTX_DEF);
300167801Sjhb
301157846Sjhb	/* Setup page locks. */
302177912Sjeff	for (i = 0; i < PA_LOCK_COUNT; i++)
303177912Sjeff		mtx_init(&pa_lock[i].data, "page lock", NULL, MTX_DEF);
304157851Swkoszek
305189846Sjeff	/*
306167307Sjhb	 * Initialize the queue headers for the hold queue, the active queue,
307167054Skmacy	 * and the inactive queue.
308189846Sjeff	 */
309176017Sjeff	for (i = 0; i < PQ_COUNT; i++)
310192853Ssson		TAILQ_INIT(&vm_page_queues[i].pl);
311192853Ssson	vm_page_queues[PQ_INACTIVE].cnt = &cnt.v_inactive_count;
312192853Ssson	vm_page_queues[PQ_ACTIVE].cnt = &cnt.v_active_count;
313192853Ssson	vm_page_queues[PQ_HOLD].cnt = &cnt.v_active_count;
314192853Ssson
315154941Sjhb	/*
316169394Sjhb	 * Allocate memory for use when boot strapping the kernel memory
317169394Sjhb	 * allocator.
318157826Sjhb	 */
319154941Sjhb	new_end = end - (boot_pages * UMA_SLAB_SIZE);
320167787Sjhb	new_end = trunc_page(new_end);
321182914Sjhb	mapped = pmap_map(&vaddr, new_end, end,
322154941Sjhb	    VM_PROT_READ | VM_PROT_WRITE);
323154941Sjhb	bzero((void *)mapped, end - new_end);
324192853Ssson	uma_startup((void *)mapped, boot_pages);
325192853Ssson
326192853Ssson#if defined(__amd64__) || defined(__i386__) || defined(__arm__) || \
327154941Sjhb    defined(__mips__)
328154941Sjhb	/*
329154941Sjhb	 * Allocate a bitmap to indicate that a random physical page
330154941Sjhb	 * needs to be included in a minidump.
331154941Sjhb	 *
332154941Sjhb	 * The amd64 port needs this to indicate which direct map pages
333154941Sjhb	 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
334154941Sjhb	 *
335154941Sjhb	 * However, i386 still needs this workspace internally within the
336154941Sjhb	 * minidump code.  In theory, they are not needed on i386, but are
337176017Sjeff	 * included should the sf_buf code decide to use them.
338176017Sjeff	 */
339154941Sjhb	last_pa = 0;
340154941Sjhb	for (i = 0; dump_avail[i + 1] != 0; i += 2)
341176017Sjeff		if (dump_avail[i + 1] > last_pa)
342176017Sjeff			last_pa = dump_avail[i + 1];
343154941Sjhb	page_range = last_pa / PAGE_SIZE;
344176017Sjeff	vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
345176017Sjeff	new_end -= vm_page_dump_size;
346167787Sjhb	vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
347154941Sjhb	    new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
348154941Sjhb	bzero((void *)vm_page_dump, vm_page_dump_size);
349176017Sjeff#endif
350176017Sjeff#ifdef __amd64__
351154941Sjhb	/*
352154941Sjhb	 * Request that the physical pages underlying the message buffer be
353157846Sjhb	 * included in a crash dump.  Since the message buffer is accessed
354154941Sjhb	 * through the direct map, they are not automatically included.
355154941Sjhb	 */
356174629Sjeff	pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
357174629Sjeff	last_pa = pa + round_page(msgbufsize);
358154941Sjhb	while (pa < last_pa) {
359173960Sattilio		dump_add_page(pa);
360154941Sjhb		pa += PAGE_SIZE;
361173960Sattilio	}
362173960Sattilio#endif
363173960Sattilio	/*
364173960Sattilio	 * Compute the number of pages of memory that will be available for
365176017Sjeff	 * use (taking into account the overhead of a page structure per
366176017Sjeff	 * page).
367176017Sjeff	 */
368176017Sjeff	first_page = low_water / PAGE_SIZE;
369176017Sjeff#ifdef VM_PHYSSEG_SPARSE
370176017Sjeff	page_range = 0;
371176017Sjeff	for (i = 0; phys_avail[i + 1] != 0; i += 2)
372176017Sjeff		page_range += atop(phys_avail[i + 1] - phys_avail[i]);
373192853Ssson#elif defined(VM_PHYSSEG_DENSE)
374176017Sjeff	page_range = high_water / PAGE_SIZE - first_page;
375192853Ssson#else
376192853Ssson#error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
377192853Ssson#endif
378192853Ssson	end = new_end;
379176017Sjeff
380176017Sjeff	/*
381177912Sjeff	 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
382177912Sjeff	 */
383177912Sjeff	vaddr += PAGE_SIZE;
384177912Sjeff
385177912Sjeff	/*
386177912Sjeff	 * Initialize the mem entry structures now, and put them in the free
387177912Sjeff	 * queue.
388177912Sjeff	 */
389177912Sjeff	new_end = trunc_page(end - page_range * sizeof(struct vm_page));
390177912Sjeff	mapped = pmap_map(&vaddr, new_end, end,
391173960Sattilio	    VM_PROT_READ | VM_PROT_WRITE);
392173960Sattilio	vm_page_array = (vm_page_t) mapped;
393173960Sattilio#if VM_NRESERVLEVEL > 0
394173960Sattilio	/*
395154941Sjhb	 * Allocate memory for the reservation management system's data
396176017Sjeff	 * structures.
397176017Sjeff	 */
398176017Sjeff	new_end = vm_reserv_startup(&vaddr, new_end, high_water);
399154941Sjhb#endif
400170295Sjeff#if defined(__amd64__) || defined(__mips__)
401154941Sjhb	/*
402154941Sjhb	 * pmap_map on amd64 and mips can come out of the direct-map, not kvm
403154941Sjhb	 * like i386, so the pages must be tracked for a crashdump to include
404176017Sjeff	 * this data.  This includes the vm_page_array and the early UMA
405154941Sjhb	 * bootstrap pages.
406176017Sjeff	 */
407176017Sjeff	for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
408170295Sjeff		dump_add_page(pa);
409157846Sjhb#endif
410154941Sjhb	phys_avail[biggestone + 1] = new_end;
411154941Sjhb
412154941Sjhb	/*
413173960Sattilio	 * Clear all of the page structures
414154941Sjhb	 */
415193035Sjhb	bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
416193035Sjhb	for (i = 0; i < page_range; i++)
417193035Sjhb		vm_page_array[i].order = VM_NFREEORDER;
418193035Sjhb	vm_page_array_size = page_range;
419193035Sjhb
420173960Sattilio	/*
421176017Sjeff	 * Initialize the physical memory allocator.
422176017Sjeff	 */
423176017Sjeff	vm_phys_init();
424176017Sjeff
425176017Sjeff	/*
426176017Sjeff	 * Add every available physical page that is not blacklisted to
427176017Sjeff	 * the free lists.
428173960Sattilio	 */
429173960Sattilio	cnt.v_page_count = 0;
430173960Sattilio	cnt.v_free_count = 0;
431173960Sattilio	list = getenv("vm.blacklist");
432176017Sjeff	for (i = 0; phys_avail[i + 1] != 0; i += 2) {
433154941Sjhb		pa = phys_avail[i];
434176017Sjeff		last_pa = phys_avail[i + 1];
435176017Sjeff		while (pa < last_pa) {
436176017Sjeff			if (list != NULL &&
437176017Sjeff			    vm_page_blacklist_lookup(list, pa))
438176017Sjeff				printf("Skipping page with pa 0x%jx\n",
439176017Sjeff				    (uintmax_t)pa);
440176017Sjeff			else
441176017Sjeff				vm_phys_add_page(pa);
442176017Sjeff			pa += PAGE_SIZE;
443176017Sjeff		}
444176017Sjeff	}
445170295Sjeff	freeenv(list);
446157826Sjhb#if VM_NRESERVLEVEL > 0
447157826Sjhb	/*
448157826Sjhb	 * Initialize the reservation management system.
449167787Sjhb	 */
450157826Sjhb	vm_reserv_init();
451157826Sjhb#endif
452154941Sjhb	return (vaddr);
453154941Sjhb}
454154941Sjhb
455154941Sjhb
456154941SjhbCTASSERT(offsetof(struct vm_page, aflags) % sizeof(uint32_t) == 0);
457154941Sjhb
458167787Sjhbvoid
459154941Sjhbvm_page_aflag_set(vm_page_t m, uint8_t bits)
460154941Sjhb{
461192853Ssson	uint32_t *addr, val;
462192853Ssson
463192853Ssson	/*
464170295Sjeff	 * The PGA_WRITEABLE flag can only be set if the page is managed and
465192853Ssson	 * VPO_BUSY.  Currently, this flag is only set by pmap_enter().
466192853Ssson	 */
467192853Ssson	KASSERT((bits & PGA_WRITEABLE) == 0 ||
468192853Ssson	    (m->oflags & (VPO_UNMANAGED | VPO_BUSY)) == VPO_BUSY,
469167787Sjhb	    ("PGA_WRITEABLE and !VPO_BUSY"));
470154941Sjhb
471154941Sjhb	/*
472154941Sjhb	 * We want to use atomic updates for m->aflags, which is a
473154941Sjhb	 * byte wide.  Not all architectures provide atomic operations
474154941Sjhb	 * on the single-byte destination.  Punt and access the whole
475154941Sjhb	 * 4-byte word with an atomic update.  Parallel non-atomic
476154941Sjhb	 * updates to the fields included in the update by proximity
477154941Sjhb	 * are handled properly by atomics.
478154941Sjhb	 */
479192853Ssson	addr = (void *)&m->aflags;
480174629Sjeff	MPASS(((uintptr_t)addr & (sizeof(uint32_t) - 1)) == 0);
481167787Sjhb	val = bits;
482167787Sjhb#if BYTE_ORDER == BIG_ENDIAN
483160771Sjhb	val <<= 24;
484176017Sjeff#endif
485192853Ssson	atomic_set_32(addr, val);
486192853Ssson}
487192853Ssson
488192853Sssonvoid
489192853Sssonvm_page_aflag_clear(vm_page_t m, uint8_t bits)
490192853Ssson{
491192853Ssson	uint32_t *addr, val;
492192853Ssson
493192853Ssson	/*
494192853Ssson	 * The PGA_REFERENCED flag can only be cleared if the object
495154941Sjhb	 * containing the page is locked.
496154941Sjhb	 */
497177843Sattilio	KASSERT((bits & PGA_REFERENCED) == 0 || VM_OBJECT_LOCKED(m->object),
498177843Sattilio	    ("PGA_REFERENCED and !VM_OBJECT_LOCKED"));
499177843Sattilio
500177843Sattilio	/*
501177843Sattilio	 * See the comment in vm_page_aflag_set().
502177843Sattilio	 */
503177843Sattilio	addr = (void *)&m->aflags;
504177843Sattilio	MPASS(((uintptr_t)addr & (sizeof(uint32_t) - 1)) == 0);
505177843Sattilio	val = bits;
506177843Sattilio#if BYTE_ORDER == BIG_ENDIAN
507177843Sattilio	val <<= 24;
508177843Sattilio#endif
509177843Sattilio	atomic_clear_32(addr, val);
510177843Sattilio}
511177843Sattilio
512177843Sattiliovoid
513177843Sattiliovm_page_reference(vm_page_t m)
514177843Sattilio{
515177843Sattilio
516177843Sattilio	vm_page_aflag_set(m, PGA_REFERENCED);
517177843Sattilio}
518177843Sattilio
519177843Sattiliovoid
520177843Sattiliovm_page_busy(vm_page_t m)
521177843Sattilio{
522154941Sjhb
523154941Sjhb	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
524154941Sjhb	KASSERT((m->oflags & VPO_BUSY) == 0,
525154941Sjhb	    ("vm_page_busy: page already busy!!!"));
526176017Sjeff	m->oflags |= VPO_BUSY;
527154941Sjhb}
528169394Sjhb
529169394Sjhb/*
530154941Sjhb *      vm_page_flash:
531160771Sjhb *
532176017Sjeff *      wakeup anyone waiting for the page.
533167787Sjhb */
534167787Sjhbvoid
535154941Sjhbvm_page_flash(vm_page_t m)
536154941Sjhb{
537154941Sjhb
538154941Sjhb	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
539154941Sjhb	if (m->oflags & VPO_WANTED) {
540154941Sjhb		m->oflags &= ~VPO_WANTED;
541154941Sjhb		wakeup(m);
542154941Sjhb	}
543154941Sjhb}
544154941Sjhb
545154941Sjhb/*
546154941Sjhb *      vm_page_wakeup:
547167787Sjhb *
548154941Sjhb *      clear the VPO_BUSY flag and wakeup anyone waiting for the
549154941Sjhb *      page.
550154941Sjhb *
551154941Sjhb */
552154941Sjhbvoid
553154941Sjhbvm_page_wakeup(vm_page_t m)
554154941Sjhb{
555167307Sjhb
556154941Sjhb	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
557154941Sjhb	KASSERT(m->oflags & VPO_BUSY, ("vm_page_wakeup: page not busy!!!"));
558154941Sjhb	m->oflags &= ~VPO_BUSY;
559154941Sjhb	vm_page_flash(m);
560176017Sjeff}
561176017Sjeff
562176017Sjeffvoid
563176017Sjeffvm_page_io_start(vm_page_t m)
564167787Sjhb{
565154941Sjhb
566154941Sjhb	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
567154941Sjhb	m->busy++;
568154941Sjhb}
569154941Sjhb
570154941Sjhbvoid
571154941Sjhbvm_page_io_finish(vm_page_t m)
572176017Sjeff{
573176017Sjeff
574154941Sjhb	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
575170295Sjeff	KASSERT(m->busy > 0, ("vm_page_io_finish: page %p is not busy", m));
576176017Sjeff	m->busy--;
577176017Sjeff	if (m->busy == 0)
578154941Sjhb		vm_page_flash(m);
579154941Sjhb}
580154941Sjhb
581154941Sjhb/*
582154941Sjhb * Keep page from being freed by the page daemon
583154941Sjhb * much of the same effect as wiring, except much lower
584154941Sjhb * overhead and should be used only for *very* temporary
585154941Sjhb * holding ("wiring").
586154941Sjhb */
587154941Sjhbvoid
588154941Sjhbvm_page_hold(vm_page_t mem)
589154941Sjhb{
590154941Sjhb
591154941Sjhb	vm_page_lock_assert(mem, MA_OWNED);
592154941Sjhb        mem->hold_count++;
593154941Sjhb}
594154941Sjhb
595176017Sjeffvoid
596176017Sjeffvm_page_unhold(vm_page_t mem)
597176017Sjeff{
598176017Sjeff
599176017Sjeff	vm_page_lock_assert(mem, MA_OWNED);
600176017Sjeff	--mem->hold_count;
601176017Sjeff	KASSERT(mem->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!"));
602176017Sjeff	if (mem->hold_count == 0 && mem->queue == PQ_HOLD)
603170295Sjeff		vm_page_free_toq(mem);
604154941Sjhb}
605154941Sjhb
606167787Sjhb/*
607154941Sjhb *	vm_page_unhold_pages:
608154941Sjhb *
609154941Sjhb *	Unhold each of the pages that is referenced by the given array.
610154941Sjhb */
611154941Sjhbvoid
612154941Sjhbvm_page_unhold_pages(vm_page_t *ma, int count)
613154941Sjhb{
614154941Sjhb	struct mtx *mtx, *new_mtx;
615154941Sjhb
616154941Sjhb	mtx = NULL;
617167787Sjhb	for (; count != 0; count--) {
618157846Sjhb		/*
619176017Sjeff		 * Avoid releasing and reacquiring the same page lock.
620154941Sjhb		 */
621170295Sjeff		new_mtx = vm_page_lockptr(*ma);
622154941Sjhb		if (mtx != new_mtx) {
623154941Sjhb			if (mtx != NULL)
624192853Ssson				mtx_unlock(mtx);
625154941Sjhb			mtx = new_mtx;
626154941Sjhb			mtx_lock(mtx);
627154941Sjhb		}
628154941Sjhb		vm_page_unhold(*ma);
629154941Sjhb		ma++;
630154941Sjhb	}
631154941Sjhb	if (mtx != NULL)
632154941Sjhb		mtx_unlock(mtx);
633154941Sjhb}
634154941Sjhb
635170295Sjeff/*
636167801Sjhb *	vm_page_getfake:
637157846Sjhb *
638176017Sjeff *	Create a fictitious page with the specified physical address and
639176017Sjeff *	memory attribute.  The memory attribute is the only the machine-
640157851Swkoszek *	dependent aspect of a fictitious page that must be initialized.
641189846Sjeff */
642189846Sjeffvm_page_t
643171516Sattiliovm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
644171516Sattilio{
645189846Sjeff	vm_page_t m;
646192853Ssson
647192853Ssson	m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
648192853Ssson	m->phys_addr = paddr;
649192853Ssson	m->queue = PQ_NONE;
650192853Ssson	/* Fictitious pages don't use "segind". */
651154941Sjhb	m->flags = PG_FICTITIOUS;
652171052Sattilio	/* Fictitious pages don't use "order" or "pool". */
653171052Sattilio	m->oflags = VPO_BUSY | VPO_UNMANAGED;
654171052Sattilio	m->wire_count = 1;
655171052Sattilio	pmap_page_set_memattr(m, memattr);
656171052Sattilio	return (m);
657171052Sattilio}
658171052Sattilio
659171052Sattilio/*
660171052Sattilio *	vm_page_putfake:
661171052Sattilio *
662167787Sjhb *	Release a fictitious page.
663154941Sjhb */
664167787Sjhbvoid
665154941Sjhbvm_page_putfake(vm_page_t m)
666154941Sjhb{
667192853Ssson
668192853Ssson	KASSERT((m->flags & PG_FICTITIOUS) != 0,
669192853Ssson	    ("vm_page_putfake: bad page %p", m));
670174629Sjeff	uma_zfree(fakepg_zone, m);
671174629Sjeff}
672173960Sattilio
673173960Sattilio/*
674173960Sattilio *	vm_page_updatefake:
675173960Sattilio *
676173960Sattilio *	Update the given fictitious page to the specified physical address and
677173960Sattilio *	memory attribute.
678173960Sattilio */
679173960Sattiliovoid
680173960Sattiliovm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
681173960Sattilio{
682173960Sattilio
683173960Sattilio	KASSERT((m->flags & PG_FICTITIOUS) != 0,
684173960Sattilio	    ("vm_page_updatefake: bad page %p", m));
685192853Ssson	m->phys_addr = paddr;
686173960Sattilio	pmap_page_set_memattr(m, memattr);
687192853Ssson}
688192853Ssson
689192853Ssson/*
690192853Ssson *	vm_page_free:
691173960Sattilio *
692173960Sattilio *	Free a page.
693177912Sjeff */
694177912Sjeffvoid
695176017Sjeffvm_page_free(vm_page_t m)
696176017Sjeff{
697176017Sjeff
698176017Sjeff	m->flags &= ~PG_ZERO;
699176017Sjeff	vm_page_free_toq(m);
700176017Sjeff}
701176017Sjeff
702176017Sjeff/*
703177912Sjeff *	vm_page_free_zero:
704176017Sjeff *
705176017Sjeff *	Free a page to the zerod-pages queue
706176017Sjeff */
707176017Sjeffvoid
708192853Sssonvm_page_free_zero(vm_page_t m)
709192853Ssson{
710192853Ssson
711177912Sjeff	m->flags |= PG_ZERO;
712176017Sjeff	vm_page_free_toq(m);
713176017Sjeff}
714173960Sattilio
715170295Sjeff/*
716154941Sjhb *	vm_page_sleep:
717154941Sjhb *
718173960Sattilio *	Sleep and release the page and page queues locks.
719154941Sjhb *
720193035Sjhb *	The object containing the given page must be locked.
721193035Sjhb */
722193035Sjhbvoid
723193035Sjhbvm_page_sleep(vm_page_t m, const char *msg)
724193035Sjhb{
725173960Sattilio
726173960Sattilio	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
727173960Sattilio	if (mtx_owned(&vm_page_queue_mtx))
728173960Sattilio		vm_page_unlock_queues();
729173960Sattilio	if (mtx_owned(vm_page_lockptr(m)))
730173960Sattilio		vm_page_unlock(m);
731173960Sattilio
732173960Sattilio	/*
733173960Sattilio	 * It's possible that while we sleep, the page will get
734173960Sattilio	 * unbusied and freed.  If we are holding the object
735173960Sattilio	 * lock, we will assume we hold a reference to the object
736179334Sattilio	 * such that even if m->object changes, we can re-lock
737179334Sattilio	 * it.
738179334Sattilio	 */
739179334Sattilio	m->oflags |= VPO_WANTED;
740179334Sattilio	msleep(m, VM_OBJECT_MTX(m->object), PVM, msg, 0);
741154941Sjhb}
742176017Sjeff
743176017Sjeff/*
744176017Sjeff *	vm_page_dirty:
745176017Sjeff *
746176017Sjeff *	Set all bits in the page's dirty field.
747176017Sjeff *
748176017Sjeff *	The object containing the specified page must be locked if the
749176017Sjeff *	call is made from the machine-independent layer.
750154941Sjhb *
751154941Sjhb *	See vm_page_clear_dirty_mask().
752170295Sjeff */
753154941Sjhbvoid
754154941Sjhbvm_page_dirty(vm_page_t m)
755154941Sjhb{
756154941Sjhb
757154941Sjhb	KASSERT((m->flags & PG_CACHED) == 0,
758154941Sjhb	    ("vm_page_dirty: page in cache!"));
759154941Sjhb	KASSERT(!VM_PAGE_IS_FREE(m),
760154941Sjhb	    ("vm_page_dirty: page is free!"));
761157826Sjhb	KASSERT(m->valid == VM_PAGE_BITS_ALL,
762157826Sjhb	    ("vm_page_dirty: page is invalid!"));
763157826Sjhb	m->dirty = VM_PAGE_BITS_ALL;
764170295Sjeff}
765157826Sjhb
766157826Sjhb/*
767157826Sjhb *	vm_page_splay:
768167787Sjhb *
769157826Sjhb *	Implements Sleator and Tarjan's top-down splay algorithm.  Returns
770157826Sjhb *	the vm_page containing the given pindex.  If, however, that
771154941Sjhb *	pindex is not found in the vm_object, returns a vm_page that is
772157846Sjhb *	adjacent to the pindex, coming before or after it.
773154941Sjhb */
774154941Sjhbvm_page_t
775154941Sjhbvm_page_splay(vm_pindex_t pindex, vm_page_t root)
776167787Sjhb{
777154941Sjhb	struct vm_page dummy;
778154941Sjhb	vm_page_t lefttreemax, righttreemin, y;
779192853Ssson
780192853Ssson	if (root == NULL)
781192853Ssson		return (root);
782170295Sjeff	lefttreemax = righttreemin = &dummy;
783192853Ssson	for (;; root = y) {
784192853Ssson		if (pindex < root->pindex) {
785192853Ssson			if ((y = root->left) == NULL)
786192853Ssson				break;
787167787Sjhb			if (pindex < y->pindex) {
788154941Sjhb				/* Rotate right. */
789154941Sjhb				root->left = y->right;
790176017Sjeff				y->right = root;
791176017Sjeff				root = y;
792176017Sjeff				if ((y = root->left) == NULL)
793154941Sjhb					break;
794192853Ssson			}
795192853Ssson			/* Link into the new root's right tree. */
796192853Ssson			righttreemin->left = root;
797192853Ssson			righttreemin = root;
798192853Ssson		} else if (pindex > root->pindex) {
799192853Ssson			if ((y = root->right) == NULL)
800192853Ssson				break;
801192853Ssson			if (pindex > y->pindex) {
802192853Ssson				/* Rotate left. */
803192853Ssson				root->right = y->left;
804192853Ssson				y->left = root;
805192853Ssson				root = y;
806154941Sjhb				if ((y = root->right) == NULL)
807154941Sjhb					break;
808154941Sjhb			}
809154941Sjhb			/* Link into the new root's left tree. */
810154941Sjhb			lefttreemax->right = root;
811154941Sjhb			lefttreemax = root;
812154941Sjhb		} else
813154941Sjhb			break;
814154941Sjhb	}
815154941Sjhb	/* Assemble the new root. */
816154941Sjhb	lefttreemax->right = root->left;
817154941Sjhb	righttreemin->left = root->right;
818154941Sjhb	root->left = dummy.right;
819154941Sjhb	root->right = dummy.left;
820171052Sattilio	return (root);
821176017Sjeff}
822171052Sattilio
823171052Sattilio/*
824171052Sattilio *	vm_page_insert:		[ internal use only ]
825171052Sattilio *
826171052Sattilio *	Inserts the given mem entry into the object and object list.
827154941Sjhb *
828154941Sjhb *	The pagetables are not updated but will presumably fault the page
829154941Sjhb *	in if necessary, or if a kernel page the caller will at some point
830167787Sjhb *	enter the page into the kernel's pmap.  We are not allowed to block
831154941Sjhb *	here so we *can't* do this anyway.
832154941Sjhb *
833170295Sjeff *	The object and page must be locked.
834167787Sjhb *	This routine may not block.
835154941Sjhb */
836154941Sjhbvoid
837154941Sjhbvm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
838154941Sjhb{
839154941Sjhb	vm_page_t root;
840154941Sjhb
841154941Sjhb	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
842154941Sjhb	if (m->object != NULL)
843154941Sjhb		panic("vm_page_insert: page already inserted");
844154941Sjhb
845154941Sjhb	/*
846154941Sjhb	 * Record the object/offset pair in this page
847154941Sjhb	 */
848154941Sjhb	m->object = object;
849154941Sjhb	m->pindex = pindex;
850154941Sjhb
851154941Sjhb	/*
852154941Sjhb	 * Now link into the object's ordered list of backed pages.
853157846Sjhb	 */
854176076Sjeff	root = object->root;
855176076Sjeff	if (root == NULL) {
856176076Sjeff		m->left = NULL;
857176076Sjeff		m->right = NULL;
858154941Sjhb		TAILQ_INSERT_TAIL(&object->memq, m, listq);
859157846Sjhb	} else {
860157846Sjhb		root = vm_page_splay(pindex, root);
861167787Sjhb		if (pindex < root->pindex) {
862154941Sjhb			m->left = root->left;
863154941Sjhb			m->right = root;
864154941Sjhb			root->left = NULL;
865154941Sjhb			TAILQ_INSERT_BEFORE(root, m, listq);
866154941Sjhb		} else if (pindex == root->pindex)
867170295Sjeff			panic("vm_page_insert: offset already allocated");
868154941Sjhb		else {
869154941Sjhb			m->right = root->right;
870157882Sjhb			m->left = root;
871157882Sjhb			root->right = NULL;
872157882Sjhb			TAILQ_INSERT_AFTER(&object->memq, root, m, listq);
873157882Sjhb		}
874157882Sjhb	}
875157882Sjhb	object->root = m;
876157882Sjhb
877157882Sjhb	/*
878176017Sjeff	 * show that the object has one more resident page.
879170295Sjeff	 */
880157882Sjhb	object->resident_page_count++;
881157882Sjhb	/*
882169394Sjhb	 * Hold the vnode until the last page is released.
883169394Sjhb	 */
884157882Sjhb	if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
885157882Sjhb		vhold((struct vnode *)object->handle);
886157882Sjhb
887157882Sjhb	/*
888157882Sjhb	 * Since we are inserting a new and possibly dirty page,
889157882Sjhb	 * update the object's OBJ_MIGHTBEDIRTY flag.
890157882Sjhb	 */
891157882Sjhb	if (m->aflags & PGA_WRITEABLE)
892157882Sjhb		vm_object_set_writeable_dirty(object);
893157882Sjhb}
894176017Sjeff
895176017Sjeff/*
896176017Sjeff *	vm_page_remove:
897176017Sjeff *				NOTE: used by device pager as well -wfj
898176017Sjeff *
899176017Sjeff *	Removes the given mem entry from the object/offset-page
900176017Sjeff *	table and the object page list, but do not invalidate/terminate
901176017Sjeff *	the backing store.
902176017Sjeff *
903176017Sjeff *	The object and page must be locked.
904176017Sjeff *	The underlying pmap entry (if any) is NOT removed here.
905157882Sjhb *	This routine may not block.
906176017Sjeff */
907176017Sjeffvoid
908176017Sjeffvm_page_remove(vm_page_t m)
909176017Sjeff{
910176017Sjeff	vm_object_t object;
911176017Sjeff	vm_page_t root;
912176017Sjeff
913176017Sjeff	if ((m->oflags & VPO_UNMANAGED) == 0)
914176017Sjeff		vm_page_lock_assert(m, MA_OWNED);
915176017Sjeff	if ((object = m->object) == NULL)
916176017Sjeff		return;
917176017Sjeff	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
918176017Sjeff	if (m->oflags & VPO_BUSY) {
919176017Sjeff		m->oflags &= ~VPO_BUSY;
920176017Sjeff		vm_page_flash(m);
921176017Sjeff	}
922176017Sjeff
923176017Sjeff	/*
924176017Sjeff	 * Now remove from the object's list of backed pages.
925176017Sjeff	 */
926176017Sjeff	if (m != object->root)
927176017Sjeff		vm_page_splay(m->pindex, object->root);
928176017Sjeff	if (m->left == NULL)
929176017Sjeff		root = m->right;
930170295Sjeff	else {
931176017Sjeff		root = vm_page_splay(m->pindex, m->left);
932167787Sjhb		root->right = m->right;
933176017Sjeff	}
934176017Sjeff	object->root = root;
935167787Sjhb	TAILQ_REMOVE(&object->memq, m, listq);
936157882Sjhb
937192853Ssson	/*
938176017Sjeff	 * And show that the object has one fewer resident page.
939157882Sjhb	 */
940157882Sjhb	object->resident_page_count--;
941157882Sjhb	/*
942157882Sjhb	 * The vnode may now be recycled.
943157882Sjhb	 */
944157882Sjhb	if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
945157882Sjhb		vdrop((struct vnode *)object->handle);
946157882Sjhb
947157882Sjhb	m->object = NULL;
948157882Sjhb}
949157882Sjhb
950176017Sjeff/*
951157882Sjhb *	vm_page_lookup:
952169394Sjhb *
953169394Sjhb *	Returns the page associated with the object/offset
954171052Sattilio *	pair specified; if none is found, NULL is returned.
955171052Sattilio *
956171052Sattilio *	The object must be locked.
957171052Sattilio *	This routine may not block.
958171052Sattilio *	This is a critical path routine
959157882Sjhb */
960167787Sjhbvm_page_t
961157882Sjhbvm_page_lookup(vm_object_t object, vm_pindex_t pindex)
962157882Sjhb{
963157882Sjhb	vm_page_t m;
964157882Sjhb
965176017Sjeff	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
966157882Sjhb	if ((m = object->root) != NULL && m->pindex != pindex) {
967157882Sjhb		m = vm_page_splay(pindex, m);
968157882Sjhb		if ((object->root = m)->pindex != pindex)
969157882Sjhb			m = NULL;
970157882Sjhb	}
971157882Sjhb	return (m);
972157882Sjhb}
973157882Sjhb
974157882Sjhb/*
975170295Sjeff *	vm_page_find_least:
976176017Sjeff *
977176017Sjeff *	Returns the page associated with the object with least pindex
978176017Sjeff *	greater than or equal to the parameter pindex, or NULL.
979176017Sjeff *
980157882Sjhb *	The object must be locked.
981157882Sjhb *	The routine may not block.
982176017Sjeff */
983176017Sjeffvm_page_t
984157882Sjhbvm_page_find_least(vm_object_t object, vm_pindex_t pindex)
985167787Sjhb{
986157882Sjhb	vm_page_t m;
987176017Sjeff
988176017Sjeff	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
989176017Sjeff	if ((m = TAILQ_FIRST(&object->memq)) != NULL) {
990176017Sjeff		if (m->pindex < pindex) {
991176017Sjeff			m = vm_page_splay(pindex, object->root);
992176017Sjeff			if ((object->root = m)->pindex < pindex)
993176017Sjeff				m = TAILQ_NEXT(m, listq);
994176017Sjeff		}
995157882Sjhb	}
996157882Sjhb	return (m);
997176017Sjeff}
998157882Sjhb
999170295Sjeff/*
1000157882Sjhb * Returns the given page's successor (by pindex) within the object if it is
1001176017Sjeff * resident; if none is found, NULL is returned.
1002167787Sjhb *
1003192853Ssson * The object must be locked.
1004157882Sjhb */
1005157882Sjhbvm_page_t
1006154941Sjhbvm_page_next(vm_page_t m)
1007155162Sscottl{
1008154941Sjhb	vm_page_t next;
1009154941Sjhb
1010154941Sjhb	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1011154941Sjhb	if ((next = TAILQ_NEXT(m, listq)) != NULL &&
1012154941Sjhb	    next->pindex != m->pindex + 1)
1013154941Sjhb		next = NULL;
1014154941Sjhb	return (next);
1015154941Sjhb}
1016154941Sjhb
1017154941Sjhb/*
1018154941Sjhb * Returns the given page's predecessor (by pindex) within the object if it is
1019154941Sjhb * resident; if none is found, NULL is returned.
1020154941Sjhb *
1021154941Sjhb * The object must be locked.
1022154941Sjhb */
1023154941Sjhbvm_page_t
1024171052Sattiliovm_page_prev(vm_page_t m)
1025171052Sattilio{
1026154941Sjhb	vm_page_t prev;
1027154941Sjhb
1028167787Sjhb	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1029154941Sjhb	if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
1030154941Sjhb	    prev->pindex != m->pindex - 1)
1031154941Sjhb		prev = NULL;
1032154941Sjhb	return (prev);
1033154941Sjhb}
1034154941Sjhb
1035155061Sscottl/*
1036155061Sscottl *	vm_page_rename:
1037157826Sjhb *
1038154941Sjhb *	Move the given memory entry from its
1039167787Sjhb *	current object to the specified target object/offset.
1040154941Sjhb *
1041171052Sattilio *	The object must be locked.
1042171052Sattilio *	This routine may not block.
1043171052Sattilio *
1044171052Sattilio *	Note: swap associated with the page must be invalidated by the move.  We
1045171052Sattilio *	      have to do this for several reasons:  (1) we aren't freeing the
1046171052Sattilio *	      page, (2) we are dirtying the page, (3) the VM system is probably
1047171052Sattilio *	      moving the page from object A to B, and will then later move
1048171052Sattilio *	      the backing store from A to B and we can't have a conflict.
1049171052Sattilio *
1050171052Sattilio *	Note: we *always* dirty the page.  It is necessary both for the
1051171052Sattilio *	      fact that we moved it, and because we may be invalidating
1052154941Sjhb *	      swap.  If the page is on the cache, we have to deactivate it
1053154941Sjhb *	      or vm_page_dirty() will panic.  Dirty pages are not allowed
1054154941Sjhb *	      on the cache.
1055171052Sattilio */
1056171052Sattiliovoid
1057157826Sjhbvm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1058154941Sjhb{
1059167787Sjhb
1060171052Sattilio	vm_page_remove(m);
1061171052Sattilio	vm_page_insert(m, new_object, new_pindex);
1062171052Sattilio	vm_page_dirty(m);
1063171052Sattilio}
1064171052Sattilio
1065171052Sattilio/*
1066171052Sattilio *	Convert all of the given object's cached pages that have a
1067154941Sjhb *	pindex within the given range into free pages.  If the value
1068154941Sjhb *	zero is given for "end", then the range's upper bound is
1069154941Sjhb *	infinity.  If the given object is backed by a vnode and it
1070167787Sjhb *	transitions from having one or more cached pages to none, the
1071154941Sjhb *	vnode's hold count is reduced.
1072154941Sjhb */
1073154941Sjhbvoid
1074154941Sjhbvm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1075154941Sjhb{
1076157826Sjhb	vm_page_t m, m_next;
1077154941Sjhb	boolean_t empty;
1078167787Sjhb
1079154941Sjhb	mtx_lock(&vm_page_queue_free_mtx);
1080154941Sjhb	if (__predict_false(object->cache == NULL)) {
1081154941Sjhb		mtx_unlock(&vm_page_queue_free_mtx);
1082154941Sjhb		return;
1083154941Sjhb	}
1084154941Sjhb	m = object->cache = vm_page_splay(start, object->cache);
1085154941Sjhb	if (m->pindex < start) {
1086154941Sjhb		if (m->right == NULL)
1087154941Sjhb			m = NULL;
1088154941Sjhb		else {
1089154941Sjhb			m_next = vm_page_splay(start, m->right);
1090154941Sjhb			m_next->left = m;
1091154941Sjhb			m->right = NULL;
1092154941Sjhb			m = object->cache = m_next;
1093154941Sjhb		}
1094154941Sjhb	}
1095154941Sjhb
1096154941Sjhb	/*
1097154941Sjhb	 * At this point, "m" is either (1) a reference to the page
1098154941Sjhb	 * with the least pindex that is greater than or equal to
1099154941Sjhb	 * "start" or (2) NULL.
1100169394Sjhb	 */
1101169394Sjhb	for (; m != NULL && (m->pindex < end || end == 0); m = m_next) {
1102169394Sjhb		/*
1103169394Sjhb		 * Find "m"'s successor and remove "m" from the
1104167504Sjhb		 * object's cache.
1105167504Sjhb		 */
1106154941Sjhb		if (m->right == NULL) {
1107157826Sjhb			object->cache = m->left;
1108154941Sjhb			m_next = NULL;
1109173600Sjulian		} else {
1110171052Sattilio			m_next = vm_page_splay(start, m->right);
1111171052Sattilio			m_next->left = m->left;
1112154941Sjhb			object->cache = m_next;
1113154941Sjhb		}
1114154941Sjhb		/* Convert "m" to a free page. */
1115154941Sjhb		m->object = NULL;
1116154941Sjhb		m->valid = 0;
1117154941Sjhb		/* Clear PG_CACHED and set PG_FREE. */
1118154941Sjhb		m->flags ^= PG_CACHED | PG_FREE;
1119154941Sjhb		KASSERT((m->flags & (PG_CACHED | PG_FREE)) == PG_FREE,
1120154941Sjhb		    ("vm_page_cache_free: page %p has inconsistent flags", m));
1121154941Sjhb		cnt.v_cache_count--;
1122167492Sjhb		cnt.v_free_count++;
1123154941Sjhb	}
1124154941Sjhb	empty = object->cache == NULL;
1125154941Sjhb	mtx_unlock(&vm_page_queue_free_mtx);
1126154941Sjhb	if (object->type == OBJT_VNODE && empty)
1127154941Sjhb		vdrop(object->handle);
1128154941Sjhb}
1129154941Sjhb
1130154941Sjhb/*
1131 *	Returns the cached page that is associated with the given
1132 *	object and offset.  If, however, none exists, returns NULL.
1133 *
1134 *	The free page queue must be locked.
1135 */
1136static inline vm_page_t
1137vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
1138{
1139	vm_page_t m;
1140
1141	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1142	if ((m = object->cache) != NULL && m->pindex != pindex) {
1143		m = vm_page_splay(pindex, m);
1144		if ((object->cache = m)->pindex != pindex)
1145			m = NULL;
1146	}
1147	return (m);
1148}
1149
1150/*
1151 *	Remove the given cached page from its containing object's
1152 *	collection of cached pages.
1153 *
1154 *	The free page queue must be locked.
1155 */
1156void
1157vm_page_cache_remove(vm_page_t m)
1158{
1159	vm_object_t object;
1160	vm_page_t root;
1161
1162	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1163	KASSERT((m->flags & PG_CACHED) != 0,
1164	    ("vm_page_cache_remove: page %p is not cached", m));
1165	object = m->object;
1166	if (m != object->cache) {
1167		root = vm_page_splay(m->pindex, object->cache);
1168		KASSERT(root == m,
1169		    ("vm_page_cache_remove: page %p is not cached in object %p",
1170		    m, object));
1171	}
1172	if (m->left == NULL)
1173		root = m->right;
1174	else if (m->right == NULL)
1175		root = m->left;
1176	else {
1177		root = vm_page_splay(m->pindex, m->left);
1178		root->right = m->right;
1179	}
1180	object->cache = root;
1181	m->object = NULL;
1182	cnt.v_cache_count--;
1183}
1184
1185/*
1186 *	Transfer all of the cached pages with offset greater than or
1187 *	equal to 'offidxstart' from the original object's cache to the
1188 *	new object's cache.  However, any cached pages with offset
1189 *	greater than or equal to the new object's size are kept in the
1190 *	original object.  Initially, the new object's cache must be
1191 *	empty.  Offset 'offidxstart' in the original object must
1192 *	correspond to offset zero in the new object.
1193 *
1194 *	The new object must be locked.
1195 */
1196void
1197vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1198    vm_object_t new_object)
1199{
1200	vm_page_t m, m_next;
1201
1202	/*
1203	 * Insertion into an object's collection of cached pages
1204	 * requires the object to be locked.  In contrast, removal does
1205	 * not.
1206	 */
1207	VM_OBJECT_LOCK_ASSERT(new_object, MA_OWNED);
1208	KASSERT(new_object->cache == NULL,
1209	    ("vm_page_cache_transfer: object %p has cached pages",
1210	    new_object));
1211	mtx_lock(&vm_page_queue_free_mtx);
1212	if ((m = orig_object->cache) != NULL) {
1213		/*
1214		 * Transfer all of the pages with offset greater than or
1215		 * equal to 'offidxstart' from the original object's
1216		 * cache to the new object's cache.
1217		 */
1218		m = vm_page_splay(offidxstart, m);
1219		if (m->pindex < offidxstart) {
1220			orig_object->cache = m;
1221			new_object->cache = m->right;
1222			m->right = NULL;
1223		} else {
1224			orig_object->cache = m->left;
1225			new_object->cache = m;
1226			m->left = NULL;
1227		}
1228		while ((m = new_object->cache) != NULL) {
1229			if ((m->pindex - offidxstart) >= new_object->size) {
1230				/*
1231				 * Return all of the cached pages with
1232				 * offset greater than or equal to the
1233				 * new object's size to the original
1234				 * object's cache.
1235				 */
1236				new_object->cache = m->left;
1237				m->left = orig_object->cache;
1238				orig_object->cache = m;
1239				break;
1240			}
1241			m_next = vm_page_splay(m->pindex, m->right);
1242			/* Update the page's object and offset. */
1243			m->object = new_object;
1244			m->pindex -= offidxstart;
1245			if (m_next == NULL)
1246				break;
1247			m->right = NULL;
1248			m_next->left = m;
1249			new_object->cache = m_next;
1250		}
1251		KASSERT(new_object->cache == NULL ||
1252		    new_object->type == OBJT_SWAP,
1253		    ("vm_page_cache_transfer: object %p's type is incompatible"
1254		    " with cached pages", new_object));
1255	}
1256	mtx_unlock(&vm_page_queue_free_mtx);
1257}
1258
1259/*
1260 *	vm_page_alloc:
1261 *
1262 *	Allocate and return a memory cell associated
1263 *	with this VM object/offset pair.
1264 *
1265 *	The caller must always specify an allocation class.
1266 *
1267 *	allocation classes:
1268 *	VM_ALLOC_NORMAL		normal process request
1269 *	VM_ALLOC_SYSTEM		system *really* needs a page
1270 *	VM_ALLOC_INTERRUPT	interrupt time request
1271 *
1272 *	optional allocation flags:
1273 *	VM_ALLOC_ZERO		prefer a zeroed page
1274 *	VM_ALLOC_WIRED		wire the allocated page
1275 *	VM_ALLOC_NOOBJ		page is not associated with a vm object
1276 *	VM_ALLOC_NOBUSY		do not set the page busy
1277 *	VM_ALLOC_IFCACHED	return page only if it is cached
1278 *	VM_ALLOC_IFNOTCACHED	return NULL, do not reactivate if the page
1279 *				is cached
1280 *
1281 *	This routine may not sleep.
1282 */
1283vm_page_t
1284vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1285{
1286	struct vnode *vp = NULL;
1287	vm_object_t m_object;
1288	vm_page_t m;
1289	int flags, page_req;
1290
1291	if ((req & VM_ALLOC_NOOBJ) == 0) {
1292		KASSERT(object != NULL,
1293		    ("vm_page_alloc: NULL object."));
1294		VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1295	}
1296
1297	page_req = req & VM_ALLOC_CLASS_MASK;
1298
1299	/*
1300	 * The pager is allowed to eat deeper into the free page list.
1301	 */
1302	if ((curproc == pageproc) && (page_req != VM_ALLOC_INTERRUPT))
1303		page_req = VM_ALLOC_SYSTEM;
1304
1305	mtx_lock(&vm_page_queue_free_mtx);
1306	if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1307	    (page_req == VM_ALLOC_SYSTEM &&
1308	    cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1309	    (page_req == VM_ALLOC_INTERRUPT &&
1310	    cnt.v_free_count + cnt.v_cache_count > 0)) {
1311		/*
1312		 * Allocate from the free queue if the number of free pages
1313		 * exceeds the minimum for the request class.
1314		 */
1315		if (object != NULL &&
1316		    (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1317			if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1318				mtx_unlock(&vm_page_queue_free_mtx);
1319				return (NULL);
1320			}
1321			if (vm_phys_unfree_page(m))
1322				vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1323#if VM_NRESERVLEVEL > 0
1324			else if (!vm_reserv_reactivate_page(m))
1325#else
1326			else
1327#endif
1328				panic("vm_page_alloc: cache page %p is missing"
1329				    " from the free queue", m);
1330		} else if ((req & VM_ALLOC_IFCACHED) != 0) {
1331			mtx_unlock(&vm_page_queue_free_mtx);
1332			return (NULL);
1333#if VM_NRESERVLEVEL > 0
1334		} else if (object == NULL || object->type == OBJT_DEVICE ||
1335		    object->type == OBJT_SG ||
1336		    (object->flags & OBJ_COLORED) == 0 ||
1337		    (m = vm_reserv_alloc_page(object, pindex)) == NULL) {
1338#else
1339		} else {
1340#endif
1341			m = vm_phys_alloc_pages(object != NULL ?
1342			    VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1343#if VM_NRESERVLEVEL > 0
1344			if (m == NULL && vm_reserv_reclaim_inactive()) {
1345				m = vm_phys_alloc_pages(object != NULL ?
1346				    VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1347				    0);
1348			}
1349#endif
1350		}
1351	} else {
1352		/*
1353		 * Not allocatable, give up.
1354		 */
1355		mtx_unlock(&vm_page_queue_free_mtx);
1356		atomic_add_int(&vm_pageout_deficit,
1357		    MAX((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1358		pagedaemon_wakeup();
1359		return (NULL);
1360	}
1361
1362	/*
1363	 *  At this point we had better have found a good page.
1364	 */
1365
1366	KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1367	KASSERT(m->queue == PQ_NONE,
1368	    ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1369	KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1370	KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1371	KASSERT(m->busy == 0, ("vm_page_alloc: page %p is busy", m));
1372	KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1373	KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1374	    ("vm_page_alloc: page %p has unexpected memattr %d", m,
1375	    pmap_page_get_memattr(m)));
1376	if ((m->flags & PG_CACHED) != 0) {
1377		KASSERT(m->valid != 0,
1378		    ("vm_page_alloc: cached page %p is invalid", m));
1379		if (m->object == object && m->pindex == pindex)
1380	  		cnt.v_reactivated++;
1381		else
1382			m->valid = 0;
1383		m_object = m->object;
1384		vm_page_cache_remove(m);
1385		if (m_object->type == OBJT_VNODE && m_object->cache == NULL)
1386			vp = m_object->handle;
1387	} else {
1388		KASSERT(VM_PAGE_IS_FREE(m),
1389		    ("vm_page_alloc: page %p is not free", m));
1390		KASSERT(m->valid == 0,
1391		    ("vm_page_alloc: free page %p is valid", m));
1392		cnt.v_free_count--;
1393	}
1394
1395	/*
1396	 * Only the PG_ZERO flag is inherited.  The PG_CACHED or PG_FREE flag
1397	 * must be cleared before the free page queues lock is released.
1398	 */
1399	flags = 0;
1400	if (m->flags & PG_ZERO) {
1401		vm_page_zero_count--;
1402		if (req & VM_ALLOC_ZERO)
1403			flags = PG_ZERO;
1404	}
1405	m->flags = flags;
1406	mtx_unlock(&vm_page_queue_free_mtx);
1407	m->aflags = 0;
1408	if (object == NULL || object->type == OBJT_PHYS)
1409		m->oflags = VPO_UNMANAGED;
1410	else
1411		m->oflags = 0;
1412	if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ)) == 0)
1413		m->oflags |= VPO_BUSY;
1414	if (req & VM_ALLOC_WIRED) {
1415		/*
1416		 * The page lock is not required for wiring a page until that
1417		 * page is inserted into the object.
1418		 */
1419		atomic_add_int(&cnt.v_wire_count, 1);
1420		m->wire_count = 1;
1421	}
1422	m->act_count = 0;
1423
1424	if (object != NULL) {
1425		/* Ignore device objects; the pager sets "memattr" for them. */
1426		if (object->memattr != VM_MEMATTR_DEFAULT &&
1427		    object->type != OBJT_DEVICE && object->type != OBJT_SG)
1428			pmap_page_set_memattr(m, object->memattr);
1429		vm_page_insert(m, object, pindex);
1430	} else
1431		m->pindex = pindex;
1432
1433	/*
1434	 * The following call to vdrop() must come after the above call
1435	 * to vm_page_insert() in case both affect the same object and
1436	 * vnode.  Otherwise, the affected vnode's hold count could
1437	 * temporarily become zero.
1438	 */
1439	if (vp != NULL)
1440		vdrop(vp);
1441
1442	/*
1443	 * Don't wakeup too often - wakeup the pageout daemon when
1444	 * we would be nearly out of memory.
1445	 */
1446	if (vm_paging_needed())
1447		pagedaemon_wakeup();
1448
1449	return (m);
1450}
1451
1452/*
1453 * Initialize a page that has been freshly dequeued from a freelist.
1454 * The caller has to drop the vnode returned, if it is not NULL.
1455 *
1456 * To be called with vm_page_queue_free_mtx held.
1457 */
1458struct vnode *
1459vm_page_alloc_init(vm_page_t m)
1460{
1461	struct vnode *drop;
1462	vm_object_t m_object;
1463
1464	KASSERT(m->queue == PQ_NONE,
1465	    ("vm_page_alloc_init: page %p has unexpected queue %d",
1466	    m, m->queue));
1467	KASSERT(m->wire_count == 0,
1468	    ("vm_page_alloc_init: page %p is wired", m));
1469	KASSERT(m->hold_count == 0,
1470	    ("vm_page_alloc_init: page %p is held", m));
1471	KASSERT(m->busy == 0,
1472	    ("vm_page_alloc_init: page %p is busy", m));
1473	KASSERT(m->dirty == 0,
1474	    ("vm_page_alloc_init: page %p is dirty", m));
1475	KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1476	    ("vm_page_alloc_init: page %p has unexpected memattr %d",
1477	    m, pmap_page_get_memattr(m)));
1478	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1479	drop = NULL;
1480	if ((m->flags & PG_CACHED) != 0) {
1481		m->valid = 0;
1482		m_object = m->object;
1483		vm_page_cache_remove(m);
1484		if (m_object->type == OBJT_VNODE &&
1485		    m_object->cache == NULL)
1486			drop = m_object->handle;
1487	} else {
1488		KASSERT(VM_PAGE_IS_FREE(m),
1489		    ("vm_page_alloc_init: page %p is not free", m));
1490		KASSERT(m->valid == 0,
1491		    ("vm_page_alloc_init: free page %p is valid", m));
1492		cnt.v_free_count--;
1493	}
1494	if (m->flags & PG_ZERO)
1495		vm_page_zero_count--;
1496	/* Don't clear the PG_ZERO flag; we'll need it later. */
1497	m->flags &= PG_ZERO;
1498	m->aflags = 0;
1499	m->oflags = VPO_UNMANAGED;
1500	/* Unmanaged pages don't use "act_count". */
1501	return (drop);
1502}
1503
1504/*
1505 * 	vm_page_alloc_freelist:
1506 *
1507 *	Allocate a page from the specified freelist.
1508 *	Only the ALLOC_CLASS values in req are honored, other request flags
1509 *	are ignored.
1510 */
1511vm_page_t
1512vm_page_alloc_freelist(int flind, int req)
1513{
1514	struct vnode *drop;
1515	vm_page_t m;
1516	int page_req;
1517
1518	m = NULL;
1519	page_req = req & VM_ALLOC_CLASS_MASK;
1520	mtx_lock(&vm_page_queue_free_mtx);
1521	/*
1522	 * Do not allocate reserved pages unless the req has asked for it.
1523	 */
1524	if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1525	    (page_req == VM_ALLOC_SYSTEM &&
1526	    cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1527	    (page_req == VM_ALLOC_INTERRUPT &&
1528	    cnt.v_free_count + cnt.v_cache_count > 0)) {
1529		m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
1530	}
1531	if (m == NULL) {
1532		mtx_unlock(&vm_page_queue_free_mtx);
1533		return (NULL);
1534	}
1535	drop = vm_page_alloc_init(m);
1536	mtx_unlock(&vm_page_queue_free_mtx);
1537	if (drop)
1538		vdrop(drop);
1539	return (m);
1540}
1541
1542/*
1543 *	vm_wait:	(also see VM_WAIT macro)
1544 *
1545 *	Block until free pages are available for allocation
1546 *	- Called in various places before memory allocations.
1547 */
1548void
1549vm_wait(void)
1550{
1551
1552	mtx_lock(&vm_page_queue_free_mtx);
1553	if (curproc == pageproc) {
1554		vm_pageout_pages_needed = 1;
1555		msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
1556		    PDROP | PSWP, "VMWait", 0);
1557	} else {
1558		if (!vm_pages_needed) {
1559			vm_pages_needed = 1;
1560			wakeup(&vm_pages_needed);
1561		}
1562		msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
1563		    "vmwait", 0);
1564	}
1565}
1566
1567/*
1568 *	vm_waitpfault:	(also see VM_WAITPFAULT macro)
1569 *
1570 *	Block until free pages are available for allocation
1571 *	- Called only in vm_fault so that processes page faulting
1572 *	  can be easily tracked.
1573 *	- Sleeps at a lower priority than vm_wait() so that vm_wait()ing
1574 *	  processes will be able to grab memory first.  Do not change
1575 *	  this balance without careful testing first.
1576 */
1577void
1578vm_waitpfault(void)
1579{
1580
1581	mtx_lock(&vm_page_queue_free_mtx);
1582	if (!vm_pages_needed) {
1583		vm_pages_needed = 1;
1584		wakeup(&vm_pages_needed);
1585	}
1586	msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
1587	    "pfault", 0);
1588}
1589
1590/*
1591 *	vm_page_requeue:
1592 *
1593 *	Move the given page to the tail of its present page queue.
1594 *
1595 *	The page queues must be locked.
1596 */
1597void
1598vm_page_requeue(vm_page_t m)
1599{
1600	struct vpgqueues *vpq;
1601	int queue;
1602
1603	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1604	queue = m->queue;
1605	KASSERT(queue != PQ_NONE,
1606	    ("vm_page_requeue: page %p is not queued", m));
1607	vpq = &vm_page_queues[queue];
1608	TAILQ_REMOVE(&vpq->pl, m, pageq);
1609	TAILQ_INSERT_TAIL(&vpq->pl, m, pageq);
1610}
1611
1612/*
1613 *	vm_page_queue_remove:
1614 *
1615 *	Remove the given page from the specified queue.
1616 *
1617 *	The page and page queues must be locked.
1618 */
1619static __inline void
1620vm_page_queue_remove(int queue, vm_page_t m)
1621{
1622	struct vpgqueues *pq;
1623
1624	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1625	vm_page_lock_assert(m, MA_OWNED);
1626	pq = &vm_page_queues[queue];
1627	TAILQ_REMOVE(&pq->pl, m, pageq);
1628	(*pq->cnt)--;
1629}
1630
1631/*
1632 *	vm_pageq_remove:
1633 *
1634 *	Remove a page from its queue.
1635 *
1636 *	The given page must be locked.
1637 *	This routine may not block.
1638 */
1639void
1640vm_pageq_remove(vm_page_t m)
1641{
1642	int queue;
1643
1644	vm_page_lock_assert(m, MA_OWNED);
1645	if ((queue = m->queue) != PQ_NONE) {
1646		vm_page_lock_queues();
1647		m->queue = PQ_NONE;
1648		vm_page_queue_remove(queue, m);
1649		vm_page_unlock_queues();
1650	}
1651}
1652
1653/*
1654 *	vm_page_enqueue:
1655 *
1656 *	Add the given page to the specified queue.
1657 *
1658 *	The page queues must be locked.
1659 */
1660static void
1661vm_page_enqueue(int queue, vm_page_t m)
1662{
1663	struct vpgqueues *vpq;
1664
1665	vpq = &vm_page_queues[queue];
1666	m->queue = queue;
1667	TAILQ_INSERT_TAIL(&vpq->pl, m, pageq);
1668	++*vpq->cnt;
1669}
1670
1671/*
1672 *	vm_page_activate:
1673 *
1674 *	Put the specified page on the active list (if appropriate).
1675 *	Ensure that act_count is at least ACT_INIT but do not otherwise
1676 *	mess with it.
1677 *
1678 *	The page must be locked.
1679 *	This routine may not block.
1680 */
1681void
1682vm_page_activate(vm_page_t m)
1683{
1684	int queue;
1685
1686	vm_page_lock_assert(m, MA_OWNED);
1687	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1688	if ((queue = m->queue) != PQ_ACTIVE) {
1689		if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
1690			if (m->act_count < ACT_INIT)
1691				m->act_count = ACT_INIT;
1692			vm_page_lock_queues();
1693			if (queue != PQ_NONE)
1694				vm_page_queue_remove(queue, m);
1695			vm_page_enqueue(PQ_ACTIVE, m);
1696			vm_page_unlock_queues();
1697		} else
1698			KASSERT(queue == PQ_NONE,
1699			    ("vm_page_activate: wired page %p is queued", m));
1700	} else {
1701		if (m->act_count < ACT_INIT)
1702			m->act_count = ACT_INIT;
1703	}
1704}
1705
1706/*
1707 *	vm_page_free_wakeup:
1708 *
1709 *	Helper routine for vm_page_free_toq() and vm_page_cache().  This
1710 *	routine is called when a page has been added to the cache or free
1711 *	queues.
1712 *
1713 *	The page queues must be locked.
1714 *	This routine may not block.
1715 */
1716static inline void
1717vm_page_free_wakeup(void)
1718{
1719
1720	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1721	/*
1722	 * if pageout daemon needs pages, then tell it that there are
1723	 * some free.
1724	 */
1725	if (vm_pageout_pages_needed &&
1726	    cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
1727		wakeup(&vm_pageout_pages_needed);
1728		vm_pageout_pages_needed = 0;
1729	}
1730	/*
1731	 * wakeup processes that are waiting on memory if we hit a
1732	 * high water mark. And wakeup scheduler process if we have
1733	 * lots of memory. this process will swapin processes.
1734	 */
1735	if (vm_pages_needed && !vm_page_count_min()) {
1736		vm_pages_needed = 0;
1737		wakeup(&cnt.v_free_count);
1738	}
1739}
1740
1741/*
1742 *	vm_page_free_toq:
1743 *
1744 *	Returns the given page to the free list,
1745 *	disassociating it with any VM object.
1746 *
1747 *	Object and page must be locked prior to entry.
1748 *	This routine may not block.
1749 */
1750
1751void
1752vm_page_free_toq(vm_page_t m)
1753{
1754
1755	if ((m->oflags & VPO_UNMANAGED) == 0) {
1756		vm_page_lock_assert(m, MA_OWNED);
1757		KASSERT(!pmap_page_is_mapped(m),
1758		    ("vm_page_free_toq: freeing mapped page %p", m));
1759	}
1760	PCPU_INC(cnt.v_tfree);
1761
1762	if (VM_PAGE_IS_FREE(m))
1763		panic("vm_page_free: freeing free page %p", m);
1764	else if (m->busy != 0)
1765		panic("vm_page_free: freeing busy page %p", m);
1766
1767	/*
1768	 * unqueue, then remove page.  Note that we cannot destroy
1769	 * the page here because we do not want to call the pager's
1770	 * callback routine until after we've put the page on the
1771	 * appropriate free queue.
1772	 */
1773	if ((m->oflags & VPO_UNMANAGED) == 0)
1774		vm_pageq_remove(m);
1775	vm_page_remove(m);
1776
1777	/*
1778	 * If fictitious remove object association and
1779	 * return, otherwise delay object association removal.
1780	 */
1781	if ((m->flags & PG_FICTITIOUS) != 0) {
1782		return;
1783	}
1784
1785	m->valid = 0;
1786	vm_page_undirty(m);
1787
1788	if (m->wire_count != 0)
1789		panic("vm_page_free: freeing wired page %p", m);
1790	if (m->hold_count != 0) {
1791		m->flags &= ~PG_ZERO;
1792		vm_page_lock_queues();
1793		vm_page_enqueue(PQ_HOLD, m);
1794		vm_page_unlock_queues();
1795	} else {
1796		/*
1797		 * Restore the default memory attribute to the page.
1798		 */
1799		if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
1800			pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
1801
1802		/*
1803		 * Insert the page into the physical memory allocator's
1804		 * cache/free page queues.
1805		 */
1806		mtx_lock(&vm_page_queue_free_mtx);
1807		m->flags |= PG_FREE;
1808		cnt.v_free_count++;
1809#if VM_NRESERVLEVEL > 0
1810		if (!vm_reserv_free_page(m))
1811#else
1812		if (TRUE)
1813#endif
1814			vm_phys_free_pages(m, 0);
1815		if ((m->flags & PG_ZERO) != 0)
1816			++vm_page_zero_count;
1817		else
1818			vm_page_zero_idle_wakeup();
1819		vm_page_free_wakeup();
1820		mtx_unlock(&vm_page_queue_free_mtx);
1821	}
1822}
1823
1824/*
1825 *	vm_page_wire:
1826 *
1827 *	Mark this page as wired down by yet
1828 *	another map, removing it from paging queues
1829 *	as necessary.
1830 *
1831 *	If the page is fictitious, then its wire count must remain one.
1832 *
1833 *	The page must be locked.
1834 *	This routine may not block.
1835 */
1836void
1837vm_page_wire(vm_page_t m)
1838{
1839
1840	/*
1841	 * Only bump the wire statistics if the page is not already wired,
1842	 * and only unqueue the page if it is on some queue (if it is unmanaged
1843	 * it is already off the queues).
1844	 */
1845	vm_page_lock_assert(m, MA_OWNED);
1846	if ((m->flags & PG_FICTITIOUS) != 0) {
1847		KASSERT(m->wire_count == 1,
1848		    ("vm_page_wire: fictitious page %p's wire count isn't one",
1849		    m));
1850		return;
1851	}
1852	if (m->wire_count == 0) {
1853		if ((m->oflags & VPO_UNMANAGED) == 0)
1854			vm_pageq_remove(m);
1855		atomic_add_int(&cnt.v_wire_count, 1);
1856	}
1857	m->wire_count++;
1858	KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
1859}
1860
1861/*
1862 * vm_page_unwire:
1863 *
1864 * Release one wiring of the specified page, potentially enabling it to be
1865 * paged again.  If paging is enabled, then the value of the parameter
1866 * "activate" determines to which queue the page is added.  If "activate" is
1867 * non-zero, then the page is added to the active queue.  Otherwise, it is
1868 * added to the inactive queue.
1869 *
1870 * However, unless the page belongs to an object, it is not enqueued because
1871 * it cannot be paged out.
1872 *
1873 * If a page is fictitious, then its wire count must alway be one.
1874 *
1875 * A managed page must be locked.
1876 */
1877void
1878vm_page_unwire(vm_page_t m, int activate)
1879{
1880
1881	if ((m->oflags & VPO_UNMANAGED) == 0)
1882		vm_page_lock_assert(m, MA_OWNED);
1883	if ((m->flags & PG_FICTITIOUS) != 0) {
1884		KASSERT(m->wire_count == 1,
1885	    ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
1886		return;
1887	}
1888	if (m->wire_count > 0) {
1889		m->wire_count--;
1890		if (m->wire_count == 0) {
1891			atomic_subtract_int(&cnt.v_wire_count, 1);
1892			if ((m->oflags & VPO_UNMANAGED) != 0 ||
1893			    m->object == NULL)
1894				return;
1895			vm_page_lock_queues();
1896			if (activate)
1897				vm_page_enqueue(PQ_ACTIVE, m);
1898			else {
1899				m->flags &= ~PG_WINATCFLS;
1900				vm_page_enqueue(PQ_INACTIVE, m);
1901			}
1902			vm_page_unlock_queues();
1903		}
1904	} else
1905		panic("vm_page_unwire: page %p's wire count is zero", m);
1906}
1907
1908/*
1909 * Move the specified page to the inactive queue.
1910 *
1911 * Many pages placed on the inactive queue should actually go
1912 * into the cache, but it is difficult to figure out which.  What
1913 * we do instead, if the inactive target is well met, is to put
1914 * clean pages at the head of the inactive queue instead of the tail.
1915 * This will cause them to be moved to the cache more quickly and
1916 * if not actively re-referenced, reclaimed more quickly.  If we just
1917 * stick these pages at the end of the inactive queue, heavy filesystem
1918 * meta-data accesses can cause an unnecessary paging load on memory bound
1919 * processes.  This optimization causes one-time-use metadata to be
1920 * reused more quickly.
1921 *
1922 * Normally athead is 0 resulting in LRU operation.  athead is set
1923 * to 1 if we want this page to be 'as if it were placed in the cache',
1924 * except without unmapping it from the process address space.
1925 *
1926 * This routine may not block.
1927 */
1928static inline void
1929_vm_page_deactivate(vm_page_t m, int athead)
1930{
1931	int queue;
1932
1933	vm_page_lock_assert(m, MA_OWNED);
1934
1935	/*
1936	 * Ignore if already inactive.
1937	 */
1938	if ((queue = m->queue) == PQ_INACTIVE)
1939		return;
1940	if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
1941		vm_page_lock_queues();
1942		m->flags &= ~PG_WINATCFLS;
1943		if (queue != PQ_NONE)
1944			vm_page_queue_remove(queue, m);
1945		if (athead)
1946			TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m,
1947			    pageq);
1948		else
1949			TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m,
1950			    pageq);
1951		m->queue = PQ_INACTIVE;
1952		cnt.v_inactive_count++;
1953		vm_page_unlock_queues();
1954	}
1955}
1956
1957/*
1958 * Move the specified page to the inactive queue.
1959 *
1960 * The page must be locked.
1961 */
1962void
1963vm_page_deactivate(vm_page_t m)
1964{
1965
1966	_vm_page_deactivate(m, 0);
1967}
1968
1969/*
1970 * vm_page_try_to_cache:
1971 *
1972 * Returns 0 on failure, 1 on success
1973 */
1974int
1975vm_page_try_to_cache(vm_page_t m)
1976{
1977
1978	vm_page_lock_assert(m, MA_OWNED);
1979	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1980	if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1981	    (m->oflags & (VPO_BUSY | VPO_UNMANAGED)) != 0)
1982		return (0);
1983	pmap_remove_all(m);
1984	if (m->dirty)
1985		return (0);
1986	vm_page_cache(m);
1987	return (1);
1988}
1989
1990/*
1991 * vm_page_try_to_free()
1992 *
1993 *	Attempt to free the page.  If we cannot free it, we do nothing.
1994 *	1 is returned on success, 0 on failure.
1995 */
1996int
1997vm_page_try_to_free(vm_page_t m)
1998{
1999
2000	vm_page_lock_assert(m, MA_OWNED);
2001	if (m->object != NULL)
2002		VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2003	if (m->dirty || m->hold_count || m->busy || m->wire_count ||
2004	    (m->oflags & (VPO_BUSY | VPO_UNMANAGED)) != 0)
2005		return (0);
2006	pmap_remove_all(m);
2007	if (m->dirty)
2008		return (0);
2009	vm_page_free(m);
2010	return (1);
2011}
2012
2013/*
2014 * vm_page_cache
2015 *
2016 * Put the specified page onto the page cache queue (if appropriate).
2017 *
2018 * This routine may not block.
2019 */
2020void
2021vm_page_cache(vm_page_t m)
2022{
2023	vm_object_t object;
2024	vm_page_t root;
2025
2026	vm_page_lock_assert(m, MA_OWNED);
2027	object = m->object;
2028	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2029	if ((m->oflags & (VPO_UNMANAGED | VPO_BUSY)) || m->busy ||
2030	    m->hold_count || m->wire_count)
2031		panic("vm_page_cache: attempting to cache busy page");
2032	pmap_remove_all(m);
2033	if (m->dirty != 0)
2034		panic("vm_page_cache: page %p is dirty", m);
2035	if (m->valid == 0 || object->type == OBJT_DEFAULT ||
2036	    (object->type == OBJT_SWAP &&
2037	    !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
2038		/*
2039		 * Hypothesis: A cache-elgible page belonging to a
2040		 * default object or swap object but without a backing
2041		 * store must be zero filled.
2042		 */
2043		vm_page_free(m);
2044		return;
2045	}
2046	KASSERT((m->flags & PG_CACHED) == 0,
2047	    ("vm_page_cache: page %p is already cached", m));
2048	PCPU_INC(cnt.v_tcached);
2049
2050	/*
2051	 * Remove the page from the paging queues.
2052	 */
2053	vm_pageq_remove(m);
2054
2055	/*
2056	 * Remove the page from the object's collection of resident
2057	 * pages.
2058	 */
2059	if (m != object->root)
2060		vm_page_splay(m->pindex, object->root);
2061	if (m->left == NULL)
2062		root = m->right;
2063	else {
2064		root = vm_page_splay(m->pindex, m->left);
2065		root->right = m->right;
2066	}
2067	object->root = root;
2068	TAILQ_REMOVE(&object->memq, m, listq);
2069	object->resident_page_count--;
2070
2071	/*
2072	 * Restore the default memory attribute to the page.
2073	 */
2074	if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2075		pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2076
2077	/*
2078	 * Insert the page into the object's collection of cached pages
2079	 * and the physical memory allocator's cache/free page queues.
2080	 */
2081	m->flags &= ~PG_ZERO;
2082	mtx_lock(&vm_page_queue_free_mtx);
2083	m->flags |= PG_CACHED;
2084	cnt.v_cache_count++;
2085	root = object->cache;
2086	if (root == NULL) {
2087		m->left = NULL;
2088		m->right = NULL;
2089	} else {
2090		root = vm_page_splay(m->pindex, root);
2091		if (m->pindex < root->pindex) {
2092			m->left = root->left;
2093			m->right = root;
2094			root->left = NULL;
2095		} else if (__predict_false(m->pindex == root->pindex))
2096			panic("vm_page_cache: offset already cached");
2097		else {
2098			m->right = root->right;
2099			m->left = root;
2100			root->right = NULL;
2101		}
2102	}
2103	object->cache = m;
2104#if VM_NRESERVLEVEL > 0
2105	if (!vm_reserv_free_page(m)) {
2106#else
2107	if (TRUE) {
2108#endif
2109		vm_phys_set_pool(VM_FREEPOOL_CACHE, m, 0);
2110		vm_phys_free_pages(m, 0);
2111	}
2112	vm_page_free_wakeup();
2113	mtx_unlock(&vm_page_queue_free_mtx);
2114
2115	/*
2116	 * Increment the vnode's hold count if this is the object's only
2117	 * cached page.  Decrement the vnode's hold count if this was
2118	 * the object's only resident page.
2119	 */
2120	if (object->type == OBJT_VNODE) {
2121		if (root == NULL && object->resident_page_count != 0)
2122			vhold(object->handle);
2123		else if (root != NULL && object->resident_page_count == 0)
2124			vdrop(object->handle);
2125	}
2126}
2127
2128/*
2129 * vm_page_dontneed
2130 *
2131 *	Cache, deactivate, or do nothing as appropriate.  This routine
2132 *	is typically used by madvise() MADV_DONTNEED.
2133 *
2134 *	Generally speaking we want to move the page into the cache so
2135 *	it gets reused quickly.  However, this can result in a silly syndrome
2136 *	due to the page recycling too quickly.  Small objects will not be
2137 *	fully cached.  On the otherhand, if we move the page to the inactive
2138 *	queue we wind up with a problem whereby very large objects
2139 *	unnecessarily blow away our inactive and cache queues.
2140 *
2141 *	The solution is to move the pages based on a fixed weighting.  We
2142 *	either leave them alone, deactivate them, or move them to the cache,
2143 *	where moving them to the cache has the highest weighting.
2144 *	By forcing some pages into other queues we eventually force the
2145 *	system to balance the queues, potentially recovering other unrelated
2146 *	space from active.  The idea is to not force this to happen too
2147 *	often.
2148 */
2149void
2150vm_page_dontneed(vm_page_t m)
2151{
2152	int dnw;
2153	int head;
2154
2155	vm_page_lock_assert(m, MA_OWNED);
2156	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2157	dnw = PCPU_GET(dnweight);
2158	PCPU_INC(dnweight);
2159
2160	/*
2161	 * Occasionally leave the page alone.
2162	 */
2163	if ((dnw & 0x01F0) == 0 || m->queue == PQ_INACTIVE) {
2164		if (m->act_count >= ACT_INIT)
2165			--m->act_count;
2166		return;
2167	}
2168
2169	/*
2170	 * Clear any references to the page.  Otherwise, the page daemon will
2171	 * immediately reactivate the page.
2172	 *
2173	 * Perform the pmap_clear_reference() first.  Otherwise, a concurrent
2174	 * pmap operation, such as pmap_remove(), could clear a reference in
2175	 * the pmap and set PGA_REFERENCED on the page before the
2176	 * pmap_clear_reference() had completed.  Consequently, the page would
2177	 * appear referenced based upon an old reference that occurred before
2178	 * this function ran.
2179	 */
2180	pmap_clear_reference(m);
2181	vm_page_aflag_clear(m, PGA_REFERENCED);
2182
2183	if (m->dirty == 0 && pmap_is_modified(m))
2184		vm_page_dirty(m);
2185
2186	if (m->dirty || (dnw & 0x0070) == 0) {
2187		/*
2188		 * Deactivate the page 3 times out of 32.
2189		 */
2190		head = 0;
2191	} else {
2192		/*
2193		 * Cache the page 28 times out of every 32.  Note that
2194		 * the page is deactivated instead of cached, but placed
2195		 * at the head of the queue instead of the tail.
2196		 */
2197		head = 1;
2198	}
2199	_vm_page_deactivate(m, head);
2200}
2201
2202/*
2203 * Grab a page, waiting until we are waken up due to the page
2204 * changing state.  We keep on waiting, if the page continues
2205 * to be in the object.  If the page doesn't exist, first allocate it
2206 * and then conditionally zero it.
2207 *
2208 * The caller must always specify the VM_ALLOC_RETRY flag.  This is intended
2209 * to facilitate its eventual removal.
2210 *
2211 * This routine may block.
2212 */
2213vm_page_t
2214vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
2215{
2216	vm_page_t m;
2217
2218	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2219	KASSERT((allocflags & VM_ALLOC_RETRY) != 0,
2220	    ("vm_page_grab: VM_ALLOC_RETRY is required"));
2221retrylookup:
2222	if ((m = vm_page_lookup(object, pindex)) != NULL) {
2223		if ((m->oflags & VPO_BUSY) != 0 ||
2224		    ((allocflags & VM_ALLOC_IGN_SBUSY) == 0 && m->busy != 0)) {
2225			/*
2226			 * Reference the page before unlocking and
2227			 * sleeping so that the page daemon is less
2228			 * likely to reclaim it.
2229			 */
2230			vm_page_aflag_set(m, PGA_REFERENCED);
2231			vm_page_sleep(m, "pgrbwt");
2232			goto retrylookup;
2233		} else {
2234			if ((allocflags & VM_ALLOC_WIRED) != 0) {
2235				vm_page_lock(m);
2236				vm_page_wire(m);
2237				vm_page_unlock(m);
2238			}
2239			if ((allocflags & VM_ALLOC_NOBUSY) == 0)
2240				vm_page_busy(m);
2241			return (m);
2242		}
2243	}
2244	m = vm_page_alloc(object, pindex, allocflags & ~(VM_ALLOC_RETRY |
2245	    VM_ALLOC_IGN_SBUSY));
2246	if (m == NULL) {
2247		VM_OBJECT_UNLOCK(object);
2248		VM_WAIT;
2249		VM_OBJECT_LOCK(object);
2250		goto retrylookup;
2251	} else if (m->valid != 0)
2252		return (m);
2253	if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
2254		pmap_zero_page(m);
2255	return (m);
2256}
2257
2258/*
2259 * Mapping function for valid bits or for dirty bits in
2260 * a page.  May not block.
2261 *
2262 * Inputs are required to range within a page.
2263 */
2264int
2265vm_page_bits(int base, int size)
2266{
2267	int first_bit;
2268	int last_bit;
2269
2270	KASSERT(
2271	    base + size <= PAGE_SIZE,
2272	    ("vm_page_bits: illegal base/size %d/%d", base, size)
2273	);
2274
2275	if (size == 0)		/* handle degenerate case */
2276		return (0);
2277
2278	first_bit = base >> DEV_BSHIFT;
2279	last_bit = (base + size - 1) >> DEV_BSHIFT;
2280
2281	return ((2 << last_bit) - (1 << first_bit));
2282}
2283
2284/*
2285 *	vm_page_set_valid:
2286 *
2287 *	Sets portions of a page valid.  The arguments are expected
2288 *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2289 *	of any partial chunks touched by the range.  The invalid portion of
2290 *	such chunks will be zeroed.
2291 *
2292 *	(base + size) must be less then or equal to PAGE_SIZE.
2293 */
2294void
2295vm_page_set_valid(vm_page_t m, int base, int size)
2296{
2297	int endoff, frag;
2298
2299	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2300	if (size == 0)	/* handle degenerate case */
2301		return;
2302
2303	/*
2304	 * If the base is not DEV_BSIZE aligned and the valid
2305	 * bit is clear, we have to zero out a portion of the
2306	 * first block.
2307	 */
2308	if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2309	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2310		pmap_zero_page_area(m, frag, base - frag);
2311
2312	/*
2313	 * If the ending offset is not DEV_BSIZE aligned and the
2314	 * valid bit is clear, we have to zero out a portion of
2315	 * the last block.
2316	 */
2317	endoff = base + size;
2318	if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2319	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2320		pmap_zero_page_area(m, endoff,
2321		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2322
2323	/*
2324	 * Assert that no previously invalid block that is now being validated
2325	 * is already dirty.
2326	 */
2327	KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
2328	    ("vm_page_set_valid: page %p is dirty", m));
2329
2330	/*
2331	 * Set valid bits inclusive of any overlap.
2332	 */
2333	m->valid |= vm_page_bits(base, size);
2334}
2335
2336/*
2337 * Clear the given bits from the specified page's dirty field.
2338 */
2339static __inline void
2340vm_page_clear_dirty_mask(vm_page_t m, int pagebits)
2341{
2342	uintptr_t addr;
2343#if PAGE_SIZE < 16384
2344	int shift;
2345#endif
2346
2347	/*
2348	 * If the object is locked and the page is neither VPO_BUSY nor
2349	 * PGA_WRITEABLE, then the page's dirty field cannot possibly be
2350	 * set by a concurrent pmap operation.
2351	 *
2352	 */
2353	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2354	if ((m->oflags & VPO_BUSY) == 0 && (m->aflags & PGA_WRITEABLE) == 0)
2355		m->dirty &= ~pagebits;
2356	else {
2357		/*
2358		 * The pmap layer can call vm_page_dirty() without
2359		 * holding a distinguished lock.  The combination of
2360		 * the object's lock and an atomic operation suffice
2361		 * to guarantee consistency of the page dirty field.
2362		 *
2363		 * For PAGE_SIZE == 32768 case, compiler already
2364		 * properly aligns the dirty field, so no forcible
2365		 * alignment is needed. Only require existence of
2366		 * atomic_clear_64 when page size is 32768.
2367		 */
2368		addr = (uintptr_t)&m->dirty;
2369#if PAGE_SIZE == 32768
2370#error pagebits too short
2371		atomic_clear_64((uint64_t *)addr, pagebits);
2372#elif PAGE_SIZE == 16384
2373		atomic_clear_32((uint32_t *)addr, pagebits);
2374#else		/* PAGE_SIZE <= 8192 */
2375		/*
2376		 * Use a trick to perform a 32-bit atomic on the
2377		 * containing aligned word, to not depend on the existence
2378		 * of atomic_clear_{8, 16}.
2379		 */
2380		shift = addr & (sizeof(uint32_t) - 1);
2381#if BYTE_ORDER == BIG_ENDIAN
2382		shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
2383#else
2384		shift *= NBBY;
2385#endif
2386		addr &= ~(sizeof(uint32_t) - 1);
2387		atomic_clear_32((uint32_t *)addr, pagebits << shift);
2388#endif		/* PAGE_SIZE */
2389	}
2390}
2391
2392/*
2393 *	vm_page_set_validclean:
2394 *
2395 *	Sets portions of a page valid and clean.  The arguments are expected
2396 *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2397 *	of any partial chunks touched by the range.  The invalid portion of
2398 *	such chunks will be zero'd.
2399 *
2400 *	This routine may not block.
2401 *
2402 *	(base + size) must be less then or equal to PAGE_SIZE.
2403 */
2404void
2405vm_page_set_validclean(vm_page_t m, int base, int size)
2406{
2407	u_long oldvalid;
2408	int endoff, frag, pagebits;
2409
2410	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2411	if (size == 0)	/* handle degenerate case */
2412		return;
2413
2414	/*
2415	 * If the base is not DEV_BSIZE aligned and the valid
2416	 * bit is clear, we have to zero out a portion of the
2417	 * first block.
2418	 */
2419	if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2420	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2421		pmap_zero_page_area(m, frag, base - frag);
2422
2423	/*
2424	 * If the ending offset is not DEV_BSIZE aligned and the
2425	 * valid bit is clear, we have to zero out a portion of
2426	 * the last block.
2427	 */
2428	endoff = base + size;
2429	if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2430	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2431		pmap_zero_page_area(m, endoff,
2432		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2433
2434	/*
2435	 * Set valid, clear dirty bits.  If validating the entire
2436	 * page we can safely clear the pmap modify bit.  We also
2437	 * use this opportunity to clear the VPO_NOSYNC flag.  If a process
2438	 * takes a write fault on a MAP_NOSYNC memory area the flag will
2439	 * be set again.
2440	 *
2441	 * We set valid bits inclusive of any overlap, but we can only
2442	 * clear dirty bits for DEV_BSIZE chunks that are fully within
2443	 * the range.
2444	 */
2445	oldvalid = m->valid;
2446	pagebits = vm_page_bits(base, size);
2447	m->valid |= pagebits;
2448#if 0	/* NOT YET */
2449	if ((frag = base & (DEV_BSIZE - 1)) != 0) {
2450		frag = DEV_BSIZE - frag;
2451		base += frag;
2452		size -= frag;
2453		if (size < 0)
2454			size = 0;
2455	}
2456	pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
2457#endif
2458	if (base == 0 && size == PAGE_SIZE) {
2459		/*
2460		 * The page can only be modified within the pmap if it is
2461		 * mapped, and it can only be mapped if it was previously
2462		 * fully valid.
2463		 */
2464		if (oldvalid == VM_PAGE_BITS_ALL)
2465			/*
2466			 * Perform the pmap_clear_modify() first.  Otherwise,
2467			 * a concurrent pmap operation, such as
2468			 * pmap_protect(), could clear a modification in the
2469			 * pmap and set the dirty field on the page before
2470			 * pmap_clear_modify() had begun and after the dirty
2471			 * field was cleared here.
2472			 */
2473			pmap_clear_modify(m);
2474		m->dirty = 0;
2475		m->oflags &= ~VPO_NOSYNC;
2476	} else if (oldvalid != VM_PAGE_BITS_ALL)
2477		m->dirty &= ~pagebits;
2478	else
2479		vm_page_clear_dirty_mask(m, pagebits);
2480}
2481
2482void
2483vm_page_clear_dirty(vm_page_t m, int base, int size)
2484{
2485
2486	vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
2487}
2488
2489/*
2490 *	vm_page_set_invalid:
2491 *
2492 *	Invalidates DEV_BSIZE'd chunks within a page.  Both the
2493 *	valid and dirty bits for the effected areas are cleared.
2494 *
2495 *	May not block.
2496 */
2497void
2498vm_page_set_invalid(vm_page_t m, int base, int size)
2499{
2500	int bits;
2501
2502	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2503	KASSERT((m->oflags & VPO_BUSY) == 0,
2504	    ("vm_page_set_invalid: page %p is busy", m));
2505	bits = vm_page_bits(base, size);
2506	if (m->valid == VM_PAGE_BITS_ALL && bits != 0)
2507		pmap_remove_all(m);
2508	KASSERT(!pmap_page_is_mapped(m),
2509	    ("vm_page_set_invalid: page %p is mapped", m));
2510	m->valid &= ~bits;
2511	m->dirty &= ~bits;
2512}
2513
2514/*
2515 * vm_page_zero_invalid()
2516 *
2517 *	The kernel assumes that the invalid portions of a page contain
2518 *	garbage, but such pages can be mapped into memory by user code.
2519 *	When this occurs, we must zero out the non-valid portions of the
2520 *	page so user code sees what it expects.
2521 *
2522 *	Pages are most often semi-valid when the end of a file is mapped
2523 *	into memory and the file's size is not page aligned.
2524 */
2525void
2526vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
2527{
2528	int b;
2529	int i;
2530
2531	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2532	/*
2533	 * Scan the valid bits looking for invalid sections that
2534	 * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
2535	 * valid bit may be set ) have already been zerod by
2536	 * vm_page_set_validclean().
2537	 */
2538	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
2539		if (i == (PAGE_SIZE / DEV_BSIZE) ||
2540		    (m->valid & (1 << i))
2541		) {
2542			if (i > b) {
2543				pmap_zero_page_area(m,
2544				    b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
2545			}
2546			b = i + 1;
2547		}
2548	}
2549
2550	/*
2551	 * setvalid is TRUE when we can safely set the zero'd areas
2552	 * as being valid.  We can do this if there are no cache consistancy
2553	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
2554	 */
2555	if (setvalid)
2556		m->valid = VM_PAGE_BITS_ALL;
2557}
2558
2559/*
2560 *	vm_page_is_valid:
2561 *
2562 *	Is (partial) page valid?  Note that the case where size == 0
2563 *	will return FALSE in the degenerate case where the page is
2564 *	entirely invalid, and TRUE otherwise.
2565 *
2566 *	May not block.
2567 */
2568int
2569vm_page_is_valid(vm_page_t m, int base, int size)
2570{
2571	int bits = vm_page_bits(base, size);
2572
2573	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2574	if (m->valid && ((m->valid & bits) == bits))
2575		return 1;
2576	else
2577		return 0;
2578}
2579
2580/*
2581 * update dirty bits from pmap/mmu.  May not block.
2582 */
2583void
2584vm_page_test_dirty(vm_page_t m)
2585{
2586
2587	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2588	if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
2589		vm_page_dirty(m);
2590}
2591
2592int so_zerocp_fullpage = 0;
2593
2594/*
2595 *	Replace the given page with a copy.  The copied page assumes
2596 *	the portion of the given page's "wire_count" that is not the
2597 *	responsibility of this copy-on-write mechanism.
2598 *
2599 *	The object containing the given page must have a non-zero
2600 *	paging-in-progress count and be locked.
2601 */
2602void
2603vm_page_cowfault(vm_page_t m)
2604{
2605	vm_page_t mnew;
2606	vm_object_t object;
2607	vm_pindex_t pindex;
2608
2609	mtx_assert(&vm_page_queue_mtx, MA_NOTOWNED);
2610	vm_page_lock_assert(m, MA_OWNED);
2611	object = m->object;
2612	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2613	KASSERT(object->paging_in_progress != 0,
2614	    ("vm_page_cowfault: object %p's paging-in-progress count is zero.",
2615	    object));
2616	pindex = m->pindex;
2617
2618 retry_alloc:
2619	pmap_remove_all(m);
2620	vm_page_remove(m);
2621	mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY);
2622	if (mnew == NULL) {
2623		vm_page_insert(m, object, pindex);
2624		vm_page_unlock(m);
2625		VM_OBJECT_UNLOCK(object);
2626		VM_WAIT;
2627		VM_OBJECT_LOCK(object);
2628		if (m == vm_page_lookup(object, pindex)) {
2629			vm_page_lock(m);
2630			goto retry_alloc;
2631		} else {
2632			/*
2633			 * Page disappeared during the wait.
2634			 */
2635			return;
2636		}
2637	}
2638
2639	if (m->cow == 0) {
2640		/*
2641		 * check to see if we raced with an xmit complete when
2642		 * waiting to allocate a page.  If so, put things back
2643		 * the way they were
2644		 */
2645		vm_page_unlock(m);
2646		vm_page_lock(mnew);
2647		vm_page_free(mnew);
2648		vm_page_unlock(mnew);
2649		vm_page_insert(m, object, pindex);
2650	} else { /* clear COW & copy page */
2651		if (!so_zerocp_fullpage)
2652			pmap_copy_page(m, mnew);
2653		mnew->valid = VM_PAGE_BITS_ALL;
2654		vm_page_dirty(mnew);
2655		mnew->wire_count = m->wire_count - m->cow;
2656		m->wire_count = m->cow;
2657		vm_page_unlock(m);
2658	}
2659}
2660
2661void
2662vm_page_cowclear(vm_page_t m)
2663{
2664
2665	vm_page_lock_assert(m, MA_OWNED);
2666	if (m->cow) {
2667		m->cow--;
2668		/*
2669		 * let vm_fault add back write permission  lazily
2670		 */
2671	}
2672	/*
2673	 *  sf_buf_free() will free the page, so we needn't do it here
2674	 */
2675}
2676
2677int
2678vm_page_cowsetup(vm_page_t m)
2679{
2680
2681	vm_page_lock_assert(m, MA_OWNED);
2682	if ((m->flags & PG_FICTITIOUS) != 0 ||
2683	    (m->oflags & VPO_UNMANAGED) != 0 ||
2684	    m->cow == USHRT_MAX - 1 || !VM_OBJECT_TRYLOCK(m->object))
2685		return (EBUSY);
2686	m->cow++;
2687	pmap_remove_write(m);
2688	VM_OBJECT_UNLOCK(m->object);
2689	return (0);
2690}
2691
2692#ifdef INVARIANTS
2693void
2694vm_page_object_lock_assert(vm_page_t m)
2695{
2696
2697	/*
2698	 * Certain of the page's fields may only be modified by the
2699	 * holder of the containing object's lock or the setter of the
2700	 * page's VPO_BUSY flag.  Unfortunately, the setter of the
2701	 * VPO_BUSY flag is not recorded, and thus cannot be checked
2702	 * here.
2703	 */
2704	if (m->object != NULL && (m->oflags & VPO_BUSY) == 0)
2705		VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2706}
2707#endif
2708
2709#include "opt_ddb.h"
2710#ifdef DDB
2711#include <sys/kernel.h>
2712
2713#include <ddb/ddb.h>
2714
2715DB_SHOW_COMMAND(page, vm_page_print_page_info)
2716{
2717	db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
2718	db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
2719	db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
2720	db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
2721	db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
2722	db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
2723	db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
2724	db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
2725	db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
2726	db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
2727}
2728
2729DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
2730{
2731
2732	db_printf("PQ_FREE:");
2733	db_printf(" %d", cnt.v_free_count);
2734	db_printf("\n");
2735
2736	db_printf("PQ_CACHE:");
2737	db_printf(" %d", cnt.v_cache_count);
2738	db_printf("\n");
2739
2740	db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
2741		*vm_page_queues[PQ_ACTIVE].cnt,
2742		*vm_page_queues[PQ_INACTIVE].cnt);
2743}
2744#endif /* DDB */
2745