vm_page.c revision 153385
155682Smarkm/*-
2233294Sstas * Copyright (c) 1991 Regents of the University of California.
3233294Sstas * All rights reserved.
4233294Sstas *
555682Smarkm * This code is derived from software contributed to Berkeley by
6233294Sstas * The Mach Operating System project at Carnegie-Mellon University.
755682Smarkm *
8233294Sstas * Redistribution and use in source and binary forms, with or without
9233294Sstas * modification, are permitted provided that the following conditions
10233294Sstas * are met:
1155682Smarkm * 1. Redistributions of source code must retain the above copyright
12233294Sstas *    notice, this list of conditions and the following disclaimer.
13233294Sstas * 2. Redistributions in binary form must reproduce the above copyright
1455682Smarkm *    notice, this list of conditions and the following disclaimer in the
15233294Sstas *    documentation and/or other materials provided with the distribution.
16233294Sstas * 4. Neither the name of the University nor the names of its contributors
17233294Sstas *    may be used to endorse or promote products derived from this software
1855682Smarkm *    without specific prior written permission.
19233294Sstas *
20233294Sstas * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21233294Sstas * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22233294Sstas * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23233294Sstas * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24233294Sstas * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25233294Sstas * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26233294Sstas * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27233294Sstas * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28233294Sstas * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29233294Sstas * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30233294Sstas * SUCH DAMAGE.
31233294Sstas *
32233294Sstas *	from: @(#)vm_page.c	7.4 (Berkeley) 5/7/91
33233294Sstas */
3455682Smarkm
3555682Smarkm/*-
3655682Smarkm * Copyright (c) 1987, 1990 Carnegie-Mellon University.
37233294Sstas * All rights reserved.
3855682Smarkm *
3955682Smarkm * Authors: Avadis Tevanian, Jr., Michael Wayne Young
4055682Smarkm *
4155682Smarkm * Permission to use, copy, modify and distribute this software and
42178825Sdfr * its documentation is hereby granted, provided that both the copyright
43178825Sdfr * notice and this permission notice appear in all copies of the
4455682Smarkm * software, derivative works or modified versions, and any portions
4555682Smarkm * thereof, and that both notices appear in supporting documentation.
4655682Smarkm *
4755682Smarkm * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
4855682Smarkm * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
4955682Smarkm * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
5055682Smarkm *
51178825Sdfr * Carnegie Mellon requests users of this software to return to
5255682Smarkm *
5355682Smarkm *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
54178825Sdfr *  School of Computer Science
5555682Smarkm *  Carnegie Mellon University
5655682Smarkm *  Pittsburgh PA 15213-3890
5755682Smarkm *
5855682Smarkm * any improvements or extensions that they make and grant Carnegie the
5955682Smarkm * rights to redistribute these changes.
6072445Sassar */
61102644Snectar
6255682Smarkm/*
6355682Smarkm *			GENERAL RULES ON VM_PAGE MANIPULATION
6455682Smarkm *
6555682Smarkm *	- a pageq mutex is required when adding or removing a page from a
6655682Smarkm *	  page queue (vm_page_queue[]), regardless of other mutexes or the
6772445Sassar *	  busy state of a page.
6855682Smarkm *
6955682Smarkm *	- a hash chain mutex is required when associating or disassociating
7055682Smarkm *	  a page from the VM PAGE CACHE hash table (vm_page_buckets),
7155682Smarkm *	  regardless of other mutexes or the busy state of a page.
7255682Smarkm *
7355682Smarkm *	- either a hash chain mutex OR a busied page is required in order
7455682Smarkm *	  to modify the page flags.  A hash chain mutex must be obtained in
7555682Smarkm *	  order to busy a page.  A page's flags cannot be modified by a
7655682Smarkm *	  hash chain mutex if the page is marked busy.
7755682Smarkm *
7855682Smarkm *	- The object memq mutex is held when inserting or removing
7955682Smarkm *	  pages from an object (vm_page_insert() or vm_page_remove()).  This
8055682Smarkm *	  is different from the object's main mutex.
8155682Smarkm *
8255682Smarkm *	Generally speaking, you have to be aware of side effects when running
8355682Smarkm *	vm_page ops.  A vm_page_lookup() will return with the hash chain
8455682Smarkm *	locked, whether it was able to lookup the page or not.  vm_page_free(),
8555682Smarkm *	vm_page_cache(), vm_page_activate(), and a number of other routines
8655682Smarkm *	will release the hash chain mutex for you.  Intermediate manipulation
8755682Smarkm *	routines such as vm_page_flag_set() expect the hash chain to be held
8855682Smarkm *	on entry and the hash chain will remain held on return.
8955682Smarkm *
9055682Smarkm *	pageq scanning can only occur with the pageq in question locked.
9155682Smarkm *	We have a known bottleneck with the active queue, but the cache
9255682Smarkm *	and free queues are actually arrays already.
9355682Smarkm */
9455682Smarkm
9555682Smarkm/*
9655682Smarkm *	Resident memory management module.
9755682Smarkm */
9855682Smarkm
9955682Smarkm#include <sys/cdefs.h>
10055682Smarkm__FBSDID("$FreeBSD: head/sys/vm/vm_page.c 153385 2005-12-13 19:59:09Z alc $");
10155682Smarkm
10255682Smarkm#include <sys/param.h>
10355682Smarkm#include <sys/systm.h>
10455682Smarkm#include <sys/lock.h>
10555682Smarkm#include <sys/kernel.h>
10655682Smarkm#include <sys/malloc.h>
10755682Smarkm#include <sys/mutex.h>
10855682Smarkm#include <sys/proc.h>
10955682Smarkm#include <sys/sysctl.h>
11055682Smarkm#include <sys/vmmeter.h>
11155682Smarkm#include <sys/vnode.h>
11255682Smarkm
11355682Smarkm#include <vm/vm.h>
11455682Smarkm#include <vm/vm_param.h>
11555682Smarkm#include <vm/vm_kern.h>
11655682Smarkm#include <vm/vm_object.h>
11755682Smarkm#include <vm/vm_page.h>
118233294Sstas#include <vm/vm_pageout.h>
11955682Smarkm#include <vm/vm_pager.h>
12055682Smarkm#include <vm/vm_extern.h>
12155682Smarkm#include <vm/uma.h>
12255682Smarkm#include <vm/uma_int.h>
12355682Smarkm
12478527Sassar/*
125233294Sstas *	Associated with page of user-allocatable memory is a
126233294Sstas *	page structure.
12755682Smarkm */
12878527Sassar
12955682Smarkmstruct mtx vm_page_queue_mtx;
13055682Smarkmstruct mtx vm_page_queue_free_mtx;
13155682Smarkm
132233294Sstasvm_page_t vm_page_array = 0;
133233294Sstasint vm_page_array_size = 0;
13455682Smarkmlong first_page = 0;
13555682Smarkmint vm_page_zero_count = 0;
13655682Smarkm
13755682Smarkmstatic int boot_pages = UMA_BOOT_PAGES;
13855682SmarkmTUNABLE_INT("vm.boot_pages", &boot_pages);
13955682SmarkmSYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RD, &boot_pages, 0,
140233294Sstas	"number of pages allocated for bootstrapping the VM system");
14155682Smarkm
14255682Smarkm/*
14355682Smarkm *	vm_set_page_size:
14455682Smarkm *
145178825Sdfr *	Sets the page size, perhaps based upon the memory
146178825Sdfr *	size.  Must be called before any use of page-size
14755682Smarkm *	dependent functions.
14855682Smarkm */
14955682Smarkmvoid
15078527Sassarvm_set_page_size(void)
151233294Sstas{
152233294Sstas	if (cnt.v_page_size == 0)
15355682Smarkm		cnt.v_page_size = PAGE_SIZE;
15478527Sassar	if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0)
15555682Smarkm		panic("vm_set_page_size: page size not a power of two");
15655682Smarkm}
157178825Sdfr
158178825Sdfr/*
15955682Smarkm *	vm_page_startup:
16055682Smarkm *
16155682Smarkm *	Initializes the resident memory module.
16255682Smarkm *
16355682Smarkm *	Allocates memory for the page cells, and
164102644Snectar *	for the object/offset-to-page hash table headers.
16555682Smarkm *	Each page cell is initialized and placed on the free list.
16655682Smarkm */
16755682Smarkmvm_offset_t
168233294Sstasvm_page_startup(vm_offset_t vaddr)
169178825Sdfr{
17055682Smarkm	vm_offset_t mapped;
17155682Smarkm	vm_size_t npages;
172233294Sstas	vm_paddr_t page_range;
17355682Smarkm	vm_paddr_t new_end;
174102644Snectar	int i;
17555682Smarkm	vm_paddr_t pa;
17655682Smarkm	int nblocks;
17755682Smarkm	vm_paddr_t last_pa;
178233294Sstas
17955682Smarkm	/* the biggest memory array is the second group of pages */
18055682Smarkm	vm_paddr_t end;
18155682Smarkm	vm_paddr_t biggestsize;
18255682Smarkm	int biggestone;
18355682Smarkm
18455682Smarkm	vm_paddr_t total;
18555682Smarkm
18655682Smarkm	total = 0;
18755682Smarkm	biggestsize = 0;
18855682Smarkm	biggestone = 0;
18955682Smarkm	nblocks = 0;
190102644Snectar	vaddr = round_page(vaddr);
19155682Smarkm
19255682Smarkm	for (i = 0; phys_avail[i + 1]; i += 2) {
19378527Sassar		phys_avail[i] = round_page(phys_avail[i]);
194233294Sstas		phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
195233294Sstas	}
19655682Smarkm
19778527Sassar	for (i = 0; phys_avail[i + 1]; i += 2) {
19855682Smarkm		vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
19955682Smarkm
20055682Smarkm		if (size > biggestsize) {
20155682Smarkm			biggestone = i;
20255682Smarkm			biggestsize = size;
20355682Smarkm		}
20455682Smarkm		++nblocks;
20555682Smarkm		total += size;
20655682Smarkm	}
20755682Smarkm
20855682Smarkm	end = phys_avail[biggestone+1];
20955682Smarkm
21055682Smarkm	/*
21155682Smarkm	 * Initialize the locks.
212102644Snectar	 */
213102644Snectar	mtx_init(&vm_page_queue_mtx, "vm page queue mutex", NULL, MTX_DEF |
21455682Smarkm	    MTX_RECURSE);
21555682Smarkm	mtx_init(&vm_page_queue_free_mtx, "vm page queue free mutex", NULL,
21655682Smarkm	    MTX_SPIN);
21755682Smarkm
218233294Sstas	/*
219178825Sdfr	 * Initialize the queue headers for the free queue, the active queue
22055682Smarkm	 * and the inactive queue.
22155682Smarkm	 */
22255682Smarkm	vm_pageq_init();
22355682Smarkm
224233294Sstas	/*
225233294Sstas	 * Allocate memory for use when boot strapping the kernel memory
22655682Smarkm	 * allocator.
22755682Smarkm	 */
22855682Smarkm	new_end = end - (boot_pages * UMA_SLAB_SIZE);
22955682Smarkm	new_end = trunc_page(new_end);
230233294Sstas	mapped = pmap_map(&vaddr, new_end, end,
231233294Sstas	    VM_PROT_READ | VM_PROT_WRITE);
232233294Sstas	bzero((void *)mapped, end - new_end);
233233294Sstas	uma_startup((void *)mapped, boot_pages);
234233294Sstas
235233294Sstas	/*
236233294Sstas	 * Compute the number of pages of memory that will be available for
237233294Sstas	 * use (taking into account the overhead of a page structure per
238178825Sdfr	 * page).
23955682Smarkm	 */
240178825Sdfr	first_page = phys_avail[0] / PAGE_SIZE;
241178825Sdfr	page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE - first_page;
24255682Smarkm	npages = (total - (page_range * sizeof(struct vm_page)) -
24355682Smarkm	    (end - new_end)) / PAGE_SIZE;
244233294Sstas	end = new_end;
24555682Smarkm
24655682Smarkm	/*
24755682Smarkm	 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
24855682Smarkm	 */
24955682Smarkm	vaddr += PAGE_SIZE;
25055682Smarkm
25155682Smarkm	/*
25255682Smarkm	 * Initialize the mem entry structures now, and put them in the free
25355682Smarkm	 * queue.
25455682Smarkm	 */
255102644Snectar	new_end = trunc_page(end - page_range * sizeof(struct vm_page));
25655682Smarkm	mapped = pmap_map(&vaddr, new_end, end,
25755682Smarkm	    VM_PROT_READ | VM_PROT_WRITE);
25878527Sassar	vm_page_array = (vm_page_t) mapped;
259233294Sstas	phys_avail[biggestone + 1] = new_end;
260233294Sstas
26155682Smarkm	/*
26278527Sassar	 * Clear all of the page structures
26355682Smarkm	 */
26455682Smarkm	bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
26555682Smarkm	vm_page_array_size = page_range;
26655682Smarkm
26755682Smarkm	/*
26855682Smarkm	 * Construct the free queue(s) in descending order (by physical
26955682Smarkm	 * address) so that the first 16MB of physical memory is allocated
27055682Smarkm	 * last rather than first.  On large-memory machines, this avoids
27155682Smarkm	 * the exhaustion of low physical memory before isa_dma_init has run.
27255682Smarkm	 */
273233294Sstas	cnt.v_page_count = 0;
27478527Sassar	cnt.v_free_count = 0;
27555682Smarkm	for (i = 0; phys_avail[i + 1] && npages > 0; i += 2) {
27655682Smarkm		pa = phys_avail[i];
27755682Smarkm		last_pa = phys_avail[i + 1];
27855682Smarkm		while (pa < last_pa && npages-- > 0) {
27978527Sassar			vm_pageq_add_new_page(pa);
28078527Sassar			pa += PAGE_SIZE;
28155682Smarkm		}
28255682Smarkm	}
28355682Smarkm	return (vaddr);
28455682Smarkm}
28555682Smarkm
28655682Smarkmvoid
28755682Smarkmvm_page_flag_set(vm_page_t m, unsigned short bits)
28855682Smarkm{
28955682Smarkm
29055682Smarkm	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
29155682Smarkm	m->flags |= bits;
29255682Smarkm}
29355682Smarkm
29478527Sassarvoid
295233294Sstasvm_page_flag_clear(vm_page_t m, unsigned short bits)
296233294Sstas{
29778527Sassar
29878527Sassar	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
29955682Smarkm	m->flags &= ~bits;
30055682Smarkm}
30155682Smarkm
30255682Smarkmvoid
30355682Smarkmvm_page_busy(vm_page_t m)
30455682Smarkm{
305178825Sdfr
30655682Smarkm	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
30755682Smarkm	KASSERT((m->flags & PG_BUSY) == 0,
30855682Smarkm	    ("vm_page_busy: page already busy!!!"));
30955682Smarkm	vm_page_flag_set(m, PG_BUSY);
31078527Sassar}
311233294Sstas
312233294Sstas/*
31355682Smarkm *      vm_page_flash:
31478527Sassar *
31555682Smarkm *      wakeup anyone waiting for the page.
316233294Sstas */
31755682Smarkmvoid
31878527Sassarvm_page_flash(vm_page_t m)
31978527Sassar{
320233294Sstas
321233294Sstas	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
32278527Sassar	if (m->flags & PG_WANTED) {
323178825Sdfr		vm_page_flag_clear(m, PG_WANTED);
32478527Sassar		wakeup(m);
32578527Sassar	}
326233294Sstas}
32755682Smarkm
32855682Smarkm/*
32978527Sassar *      vm_page_wakeup:
33055682Smarkm *
331233294Sstas *      clear the PG_BUSY flag and wakeup anyone waiting for the
332233294Sstas *      page.
333233294Sstas *
334178825Sdfr */
33578527Sassarvoid
33655682Smarkmvm_page_wakeup(vm_page_t m)
33755682Smarkm{
33855682Smarkm
33955682Smarkm	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
340178825Sdfr	KASSERT(m->flags & PG_BUSY, ("vm_page_wakeup: page not busy!!!"));
34155682Smarkm	vm_page_flag_clear(m, PG_BUSY);
342102644Snectar	vm_page_flash(m);
343102644Snectar}
344102644Snectar
345102644Snectarvoid
346102644Snectarvm_page_io_start(vm_page_t m)
347102644Snectar{
348102644Snectar
349102644Snectar	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
350102644Snectar	m->busy++;
351102644Snectar}
352102644Snectar
353102644Snectarvoid
35455682Smarkmvm_page_io_finish(vm_page_t m)
35555682Smarkm{
35655682Smarkm
357233294Sstas	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
358233294Sstas	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
35955682Smarkm	m->busy--;
36055682Smarkm	if (m->busy == 0)
36155682Smarkm		vm_page_flash(m);
36255682Smarkm}
36355682Smarkm
364233294Sstas/*
36555682Smarkm * Keep page from being freed by the page daemon
36655682Smarkm * much of the same effect as wiring, except much lower
36755682Smarkm * overhead and should be used only for *very* temporary
36855682Smarkm * holding ("wiring").
36955682Smarkm */
37055682Smarkmvoid
37155682Smarkmvm_page_hold(vm_page_t mem)
37255682Smarkm{
37355682Smarkm
37455682Smarkm	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
37555682Smarkm        mem->hold_count++;
37655682Smarkm}
37755682Smarkm
37855682Smarkmvoid
37955682Smarkmvm_page_unhold(vm_page_t mem)
380233294Sstas{
38155682Smarkm
38255682Smarkm	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
38355682Smarkm	--mem->hold_count;
38455682Smarkm	KASSERT(mem->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!"));
385233294Sstas	if (mem->hold_count == 0 && mem->queue == PQ_HOLD)
38655682Smarkm		vm_page_free_toq(mem);
38755682Smarkm}
388233294Sstas
38955682Smarkm/*
39055682Smarkm *	vm_page_free:
39155682Smarkm *
39255682Smarkm *	Free a page
39355682Smarkm *
394178825Sdfr *	The clearing of PG_ZERO is a temporary safety until the code can be
395178825Sdfr *	reviewed to determine that PG_ZERO is being properly cleared on
396178825Sdfr *	write faults or maps.  PG_ZERO was previously cleared in
397178825Sdfr *	vm_page_alloc().
398178825Sdfr */
399178825Sdfrvoid
400178825Sdfrvm_page_free(vm_page_t m)
40155682Smarkm{
40255682Smarkm	vm_page_flag_clear(m, PG_ZERO);
40355682Smarkm	vm_page_free_toq(m);
40455682Smarkm	vm_page_zero_idle_wakeup();
40555682Smarkm}
40655682Smarkm
407233294Sstas/*
40855682Smarkm *	vm_page_free_zero:
40955682Smarkm *
41055682Smarkm *	Free a page to the zerod-pages queue
41155682Smarkm */
41255682Smarkmvoid
41355682Smarkmvm_page_free_zero(vm_page_t m)
41455682Smarkm{
41555682Smarkm	vm_page_flag_set(m, PG_ZERO);
416233294Sstas	vm_page_free_toq(m);
417103423Snectar}
418103423Snectar
41955682Smarkm/*
420103423Snectar *	vm_page_sleep_if_busy:
42155682Smarkm *
42255682Smarkm *	Sleep and release the page queues lock if PG_BUSY is set or,
423103423Snectar *	if also_m_busy is TRUE, busy is non-zero.  Returns TRUE if the
424233294Sstas *	thread slept and the page queues lock was released.
425103423Snectar *	Otherwise, retains the page queues lock and returns FALSE.
426103423Snectar */
427103423Snectarint
428103423Snectarvm_page_sleep_if_busy(vm_page_t m, int also_m_busy, const char *msg)
429103423Snectar{
430103423Snectar	vm_object_t object;
431233294Sstas
432233294Sstas	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
433103423Snectar	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
434103423Snectar	if ((m->flags & PG_BUSY) || (also_m_busy && m->busy)) {
435103423Snectar		vm_page_flag_set(m, PG_WANTED | PG_REFERENCED);
436103423Snectar		/*
437178825Sdfr		 * It's possible that while we sleep, the page will get
438103423Snectar		 * unbusied and freed.  If we are holding the object
439103423Snectar		 * lock, we will assume we hold a reference to the object
440103423Snectar		 * such that even if m->object changes, we can re-lock
441103423Snectar		 * it.
442103423Snectar		 */
44355682Smarkm		object = m->object;
44455682Smarkm		VM_OBJECT_UNLOCK(object);
44555682Smarkm		msleep(m, &vm_page_queue_mtx, PDROP | PVM, msg, 0);
446233294Sstas		VM_OBJECT_LOCK(object);
44755682Smarkm		return (TRUE);
44855682Smarkm	}
44955682Smarkm	return (FALSE);
45055682Smarkm}
45155682Smarkm
45255682Smarkm/*
45355682Smarkm *	vm_page_dirty:
454103423Snectar *
45555682Smarkm *	make page all dirty
45655682Smarkm */
457233294Sstasvoid
45855682Smarkmvm_page_dirty(vm_page_t m)
45955682Smarkm{
46055682Smarkm	KASSERT(m->queue - m->pc != PQ_CACHE,
46155682Smarkm	    ("vm_page_dirty: page in cache!"));
46255682Smarkm	KASSERT(m->queue - m->pc != PQ_FREE,
46355682Smarkm	    ("vm_page_dirty: page is free!"));
46455682Smarkm	m->dirty = VM_PAGE_BITS_ALL;
46555682Smarkm}
46655682Smarkm
46755682Smarkm/*
46855682Smarkm *	vm_page_splay:
46955682Smarkm *
47055682Smarkm *	Implements Sleator and Tarjan's top-down splay algorithm.  Returns
47155682Smarkm *	the vm_page containing the given pindex.  If, however, that
47255682Smarkm *	pindex is not found in the vm_object, returns a vm_page that is
47355682Smarkm *	adjacent to the pindex, coming before or after it.
47455682Smarkm */
47555682Smarkmvm_page_t
476233294Sstasvm_page_splay(vm_pindex_t pindex, vm_page_t root)
47755682Smarkm{
47855682Smarkm	struct vm_page dummy;
47955682Smarkm	vm_page_t lefttreemax, righttreemin, y;
48055682Smarkm
48155682Smarkm	if (root == NULL)
48255682Smarkm		return (root);
48355682Smarkm	lefttreemax = righttreemin = &dummy;
48455682Smarkm	for (;; root = y) {
48555682Smarkm		if (pindex < root->pindex) {
48655682Smarkm			if ((y = root->left) == NULL)
48755682Smarkm				break;
48855682Smarkm			if (pindex < y->pindex) {
48955682Smarkm				/* Rotate right. */
49055682Smarkm				root->left = y->right;
49155682Smarkm				y->right = root;
49255682Smarkm				root = y;
493233294Sstas				if ((y = root->left) == NULL)
494233294Sstas					break;
495233294Sstas			}
496233294Sstas			/* Link into the new root's right tree. */
497233294Sstas			righttreemin->left = root;
498233294Sstas			righttreemin = root;
499233294Sstas		} else if (pindex > root->pindex) {
500233294Sstas			if ((y = root->right) == NULL)
501233294Sstas				break;
502233294Sstas			if (pindex > y->pindex) {
503233294Sstas				/* Rotate left. */
504233294Sstas				root->right = y->left;
505233294Sstas				y->left = root;
506233294Sstas				root = y;
507233294Sstas				if ((y = root->right) == NULL)
508233294Sstas					break;
509233294Sstas			}
510233294Sstas			/* Link into the new root's left tree. */
511233294Sstas			lefttreemax->right = root;
512233294Sstas			lefttreemax = root;
513233294Sstas		} else
514233294Sstas			break;
515233294Sstas	}
516233294Sstas	/* Assemble the new root. */
517	lefttreemax->right = root->left;
518	righttreemin->left = root->right;
519	root->left = dummy.right;
520	root->right = dummy.left;
521	return (root);
522}
523
524/*
525 *	vm_page_insert:		[ internal use only ]
526 *
527 *	Inserts the given mem entry into the object and object list.
528 *
529 *	The pagetables are not updated but will presumably fault the page
530 *	in if necessary, or if a kernel page the caller will at some point
531 *	enter the page into the kernel's pmap.  We are not allowed to block
532 *	here so we *can't* do this anyway.
533 *
534 *	The object and page must be locked.
535 *	This routine may not block.
536 */
537void
538vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
539{
540	vm_page_t root;
541
542	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
543	if (m->object != NULL)
544		panic("vm_page_insert: page already inserted");
545
546	/*
547	 * Record the object/offset pair in this page
548	 */
549	m->object = object;
550	m->pindex = pindex;
551
552	/*
553	 * Now link into the object's ordered list of backed pages.
554	 */
555	root = object->root;
556	if (root == NULL) {
557		m->left = NULL;
558		m->right = NULL;
559		TAILQ_INSERT_TAIL(&object->memq, m, listq);
560	} else {
561		root = vm_page_splay(pindex, root);
562		if (pindex < root->pindex) {
563			m->left = root->left;
564			m->right = root;
565			root->left = NULL;
566			TAILQ_INSERT_BEFORE(root, m, listq);
567		} else if (pindex == root->pindex)
568			panic("vm_page_insert: offset already allocated");
569		else {
570			m->right = root->right;
571			m->left = root;
572			root->right = NULL;
573			TAILQ_INSERT_AFTER(&object->memq, root, m, listq);
574		}
575	}
576	object->root = m;
577	object->generation++;
578
579	/*
580	 * show that the object has one more resident page.
581	 */
582	object->resident_page_count++;
583	/*
584	 * Hold the vnode until the last page is released.
585	 */
586	if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
587		vhold((struct vnode *)object->handle);
588
589	/*
590	 * Since we are inserting a new and possibly dirty page,
591	 * update the object's OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY flags.
592	 */
593	if (m->flags & PG_WRITEABLE)
594		vm_object_set_writeable_dirty(object);
595}
596
597/*
598 *	vm_page_remove:
599 *				NOTE: used by device pager as well -wfj
600 *
601 *	Removes the given mem entry from the object/offset-page
602 *	table and the object page list, but do not invalidate/terminate
603 *	the backing store.
604 *
605 *	The object and page must be locked.
606 *	The underlying pmap entry (if any) is NOT removed here.
607 *	This routine may not block.
608 */
609void
610vm_page_remove(vm_page_t m)
611{
612	vm_object_t object;
613	vm_page_t root;
614
615	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
616	if ((object = m->object) == NULL)
617		return;
618	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
619	if (m->flags & PG_BUSY) {
620		vm_page_flag_clear(m, PG_BUSY);
621		vm_page_flash(m);
622	}
623
624	/*
625	 * Now remove from the object's list of backed pages.
626	 */
627	if (m != object->root)
628		vm_page_splay(m->pindex, object->root);
629	if (m->left == NULL)
630		root = m->right;
631	else {
632		root = vm_page_splay(m->pindex, m->left);
633		root->right = m->right;
634	}
635	object->root = root;
636	TAILQ_REMOVE(&object->memq, m, listq);
637
638	/*
639	 * And show that the object has one fewer resident page.
640	 */
641	object->resident_page_count--;
642	object->generation++;
643	/*
644	 * The vnode may now be recycled.
645	 */
646	if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
647		vdrop((struct vnode *)object->handle);
648
649	m->object = NULL;
650}
651
652/*
653 *	vm_page_lookup:
654 *
655 *	Returns the page associated with the object/offset
656 *	pair specified; if none is found, NULL is returned.
657 *
658 *	The object must be locked.
659 *	This routine may not block.
660 *	This is a critical path routine
661 */
662vm_page_t
663vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
664{
665	vm_page_t m;
666
667	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
668	if ((m = object->root) != NULL && m->pindex != pindex) {
669		m = vm_page_splay(pindex, m);
670		if ((object->root = m)->pindex != pindex)
671			m = NULL;
672	}
673	return (m);
674}
675
676/*
677 *	vm_page_rename:
678 *
679 *	Move the given memory entry from its
680 *	current object to the specified target object/offset.
681 *
682 *	The object must be locked.
683 *	This routine may not block.
684 *
685 *	Note: swap associated with the page must be invalidated by the move.  We
686 *	      have to do this for several reasons:  (1) we aren't freeing the
687 *	      page, (2) we are dirtying the page, (3) the VM system is probably
688 *	      moving the page from object A to B, and will then later move
689 *	      the backing store from A to B and we can't have a conflict.
690 *
691 *	Note: we *always* dirty the page.  It is necessary both for the
692 *	      fact that we moved it, and because we may be invalidating
693 *	      swap.  If the page is on the cache, we have to deactivate it
694 *	      or vm_page_dirty() will panic.  Dirty pages are not allowed
695 *	      on the cache.
696 */
697void
698vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
699{
700
701	vm_page_remove(m);
702	vm_page_insert(m, new_object, new_pindex);
703	if (m->queue - m->pc == PQ_CACHE)
704		vm_page_deactivate(m);
705	vm_page_dirty(m);
706}
707
708/*
709 *	vm_page_select_cache:
710 *
711 *	Move a page of the given color from the cache queue to the free
712 *	queue.  As pages might be found, but are not applicable, they are
713 *	deactivated.
714 *
715 *	This routine may not block.
716 */
717vm_page_t
718vm_page_select_cache(int color)
719{
720	vm_object_t object;
721	vm_page_t m;
722	boolean_t was_trylocked;
723
724	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
725	while ((m = vm_pageq_find(PQ_CACHE, color, FALSE)) != NULL) {
726		KASSERT(m->dirty == 0, ("Found dirty cache page %p", m));
727		KASSERT(!pmap_page_is_mapped(m),
728		    ("Found mapped cache page %p", m));
729		KASSERT((m->flags & PG_UNMANAGED) == 0,
730		    ("Found unmanaged cache page %p", m));
731		KASSERT(m->wire_count == 0, ("Found wired cache page %p", m));
732		if (m->hold_count == 0 && (object = m->object,
733		    (was_trylocked = VM_OBJECT_TRYLOCK(object)) ||
734		    VM_OBJECT_LOCKED(object))) {
735			KASSERT((m->flags & PG_BUSY) == 0 && m->busy == 0,
736			    ("Found busy cache page %p", m));
737			vm_page_free(m);
738			if (was_trylocked)
739				VM_OBJECT_UNLOCK(object);
740			break;
741		}
742		vm_page_deactivate(m);
743	}
744	return (m);
745}
746
747/*
748 *	vm_page_alloc:
749 *
750 *	Allocate and return a memory cell associated
751 *	with this VM object/offset pair.
752 *
753 *	page_req classes:
754 *	VM_ALLOC_NORMAL		normal process request
755 *	VM_ALLOC_SYSTEM		system *really* needs a page
756 *	VM_ALLOC_INTERRUPT	interrupt time request
757 *	VM_ALLOC_ZERO		zero page
758 *
759 *	This routine may not block.
760 *
761 *	Additional special handling is required when called from an
762 *	interrupt (VM_ALLOC_INTERRUPT).  We are not allowed to mess with
763 *	the page cache in this case.
764 */
765vm_page_t
766vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
767{
768	vm_page_t m = NULL;
769	int color, flags, page_req;
770
771	page_req = req & VM_ALLOC_CLASS_MASK;
772	KASSERT(curthread->td_intr_nesting_level == 0 ||
773	    page_req == VM_ALLOC_INTERRUPT,
774	    ("vm_page_alloc(NORMAL|SYSTEM) in interrupt context"));
775
776	if ((req & VM_ALLOC_NOOBJ) == 0) {
777		KASSERT(object != NULL,
778		    ("vm_page_alloc: NULL object."));
779		VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
780		color = (pindex + object->pg_color) & PQ_L2_MASK;
781	} else
782		color = pindex & PQ_L2_MASK;
783
784	/*
785	 * The pager is allowed to eat deeper into the free page list.
786	 */
787	if ((curproc == pageproc) && (page_req != VM_ALLOC_INTERRUPT)) {
788		page_req = VM_ALLOC_SYSTEM;
789	};
790
791loop:
792	mtx_lock_spin(&vm_page_queue_free_mtx);
793	if (cnt.v_free_count > cnt.v_free_reserved ||
794	    (page_req == VM_ALLOC_SYSTEM &&
795	     cnt.v_cache_count == 0 &&
796	     cnt.v_free_count > cnt.v_interrupt_free_min) ||
797	    (page_req == VM_ALLOC_INTERRUPT && cnt.v_free_count > 0)) {
798		/*
799		 * Allocate from the free queue if the number of free pages
800		 * exceeds the minimum for the request class.
801		 */
802		m = vm_pageq_find(PQ_FREE, color, (req & VM_ALLOC_ZERO) != 0);
803	} else if (page_req != VM_ALLOC_INTERRUPT) {
804		mtx_unlock_spin(&vm_page_queue_free_mtx);
805		/*
806		 * Allocatable from cache (non-interrupt only).  On success,
807		 * we must free the page and try again, thus ensuring that
808		 * cnt.v_*_free_min counters are replenished.
809		 */
810		vm_page_lock_queues();
811		if ((m = vm_page_select_cache(color)) == NULL) {
812#if defined(DIAGNOSTIC)
813			if (cnt.v_cache_count > 0)
814				printf("vm_page_alloc(NORMAL): missing pages on cache queue: %d\n", cnt.v_cache_count);
815#endif
816			vm_page_unlock_queues();
817			atomic_add_int(&vm_pageout_deficit, 1);
818			pagedaemon_wakeup();
819			return (NULL);
820		}
821		vm_page_unlock_queues();
822		goto loop;
823	} else {
824		/*
825		 * Not allocatable from cache from interrupt, give up.
826		 */
827		mtx_unlock_spin(&vm_page_queue_free_mtx);
828		atomic_add_int(&vm_pageout_deficit, 1);
829		pagedaemon_wakeup();
830		return (NULL);
831	}
832
833	/*
834	 *  At this point we had better have found a good page.
835	 */
836
837	KASSERT(
838	    m != NULL,
839	    ("vm_page_alloc(): missing page on free queue")
840	);
841
842	/*
843	 * Remove from free queue
844	 */
845	vm_pageq_remove_nowakeup(m);
846
847	/*
848	 * Initialize structure.  Only the PG_ZERO flag is inherited.
849	 */
850	flags = PG_BUSY;
851	if (m->flags & PG_ZERO) {
852		vm_page_zero_count--;
853		if (req & VM_ALLOC_ZERO)
854			flags = PG_ZERO | PG_BUSY;
855	}
856	if (req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ))
857		flags &= ~PG_BUSY;
858	m->flags = flags;
859	if (req & VM_ALLOC_WIRED) {
860		atomic_add_int(&cnt.v_wire_count, 1);
861		m->wire_count = 1;
862	} else
863		m->wire_count = 0;
864	m->hold_count = 0;
865	m->act_count = 0;
866	m->busy = 0;
867	m->valid = 0;
868	KASSERT(m->dirty == 0, ("vm_page_alloc: free/cache page %p was dirty", m));
869	mtx_unlock_spin(&vm_page_queue_free_mtx);
870
871	if ((req & VM_ALLOC_NOOBJ) == 0)
872		vm_page_insert(m, object, pindex);
873	else
874		m->pindex = pindex;
875
876	/*
877	 * Don't wakeup too often - wakeup the pageout daemon when
878	 * we would be nearly out of memory.
879	 */
880	if (vm_paging_needed())
881		pagedaemon_wakeup();
882
883	return (m);
884}
885
886/*
887 *	vm_wait:	(also see VM_WAIT macro)
888 *
889 *	Block until free pages are available for allocation
890 *	- Called in various places before memory allocations.
891 */
892void
893vm_wait(void)
894{
895
896	vm_page_lock_queues();
897	if (curproc == pageproc) {
898		vm_pageout_pages_needed = 1;
899		msleep(&vm_pageout_pages_needed, &vm_page_queue_mtx,
900		    PDROP | PSWP, "VMWait", 0);
901	} else {
902		if (!vm_pages_needed) {
903			vm_pages_needed = 1;
904			wakeup(&vm_pages_needed);
905		}
906		msleep(&cnt.v_free_count, &vm_page_queue_mtx, PDROP | PVM,
907		    "vmwait", 0);
908	}
909}
910
911/*
912 *	vm_waitpfault:	(also see VM_WAITPFAULT macro)
913 *
914 *	Block until free pages are available for allocation
915 *	- Called only in vm_fault so that processes page faulting
916 *	  can be easily tracked.
917 *	- Sleeps at a lower priority than vm_wait() so that vm_wait()ing
918 *	  processes will be able to grab memory first.  Do not change
919 *	  this balance without careful testing first.
920 */
921void
922vm_waitpfault(void)
923{
924
925	vm_page_lock_queues();
926	if (!vm_pages_needed) {
927		vm_pages_needed = 1;
928		wakeup(&vm_pages_needed);
929	}
930	msleep(&cnt.v_free_count, &vm_page_queue_mtx, PDROP | PUSER,
931	    "pfault", 0);
932}
933
934/*
935 *	vm_page_activate:
936 *
937 *	Put the specified page on the active list (if appropriate).
938 *	Ensure that act_count is at least ACT_INIT but do not otherwise
939 *	mess with it.
940 *
941 *	The page queues must be locked.
942 *	This routine may not block.
943 */
944void
945vm_page_activate(vm_page_t m)
946{
947
948	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
949	if (m->queue != PQ_ACTIVE) {
950		if ((m->queue - m->pc) == PQ_CACHE)
951			cnt.v_reactivated++;
952		vm_pageq_remove(m);
953		if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
954			if (m->act_count < ACT_INIT)
955				m->act_count = ACT_INIT;
956			vm_pageq_enqueue(PQ_ACTIVE, m);
957		}
958	} else {
959		if (m->act_count < ACT_INIT)
960			m->act_count = ACT_INIT;
961	}
962}
963
964/*
965 *	vm_page_free_wakeup:
966 *
967 *	Helper routine for vm_page_free_toq() and vm_page_cache().  This
968 *	routine is called when a page has been added to the cache or free
969 *	queues.
970 *
971 *	The page queues must be locked.
972 *	This routine may not block.
973 */
974static __inline void
975vm_page_free_wakeup(void)
976{
977
978	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
979	/*
980	 * if pageout daemon needs pages, then tell it that there are
981	 * some free.
982	 */
983	if (vm_pageout_pages_needed &&
984	    cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
985		wakeup(&vm_pageout_pages_needed);
986		vm_pageout_pages_needed = 0;
987	}
988	/*
989	 * wakeup processes that are waiting on memory if we hit a
990	 * high water mark. And wakeup scheduler process if we have
991	 * lots of memory. this process will swapin processes.
992	 */
993	if (vm_pages_needed && !vm_page_count_min()) {
994		vm_pages_needed = 0;
995		wakeup(&cnt.v_free_count);
996	}
997}
998
999/*
1000 *	vm_page_free_toq:
1001 *
1002 *	Returns the given page to the PQ_FREE list,
1003 *	disassociating it with any VM object.
1004 *
1005 *	Object and page must be locked prior to entry.
1006 *	This routine may not block.
1007 */
1008
1009void
1010vm_page_free_toq(vm_page_t m)
1011{
1012	struct vpgqueues *pq;
1013
1014	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1015	KASSERT(!pmap_page_is_mapped(m),
1016	    ("vm_page_free_toq: freeing mapped page %p", m));
1017	cnt.v_tfree++;
1018
1019	if (m->busy || ((m->queue - m->pc) == PQ_FREE)) {
1020		printf(
1021		"vm_page_free: pindex(%lu), busy(%d), PG_BUSY(%d), hold(%d)\n",
1022		    (u_long)m->pindex, m->busy, (m->flags & PG_BUSY) ? 1 : 0,
1023		    m->hold_count);
1024		if ((m->queue - m->pc) == PQ_FREE)
1025			panic("vm_page_free: freeing free page");
1026		else
1027			panic("vm_page_free: freeing busy page");
1028	}
1029
1030	/*
1031	 * unqueue, then remove page.  Note that we cannot destroy
1032	 * the page here because we do not want to call the pager's
1033	 * callback routine until after we've put the page on the
1034	 * appropriate free queue.
1035	 */
1036	vm_pageq_remove_nowakeup(m);
1037	vm_page_remove(m);
1038
1039	/*
1040	 * If fictitious remove object association and
1041	 * return, otherwise delay object association removal.
1042	 */
1043	if ((m->flags & PG_FICTITIOUS) != 0) {
1044		return;
1045	}
1046
1047	m->valid = 0;
1048	vm_page_undirty(m);
1049
1050	if (m->wire_count != 0) {
1051		if (m->wire_count > 1) {
1052			panic("vm_page_free: invalid wire count (%d), pindex: 0x%lx",
1053				m->wire_count, (long)m->pindex);
1054		}
1055		panic("vm_page_free: freeing wired page");
1056	}
1057
1058	/*
1059	 * Clear the UNMANAGED flag when freeing an unmanaged page.
1060	 */
1061	if (m->flags & PG_UNMANAGED) {
1062		m->flags &= ~PG_UNMANAGED;
1063	}
1064
1065	if (m->hold_count != 0) {
1066		m->flags &= ~PG_ZERO;
1067		m->queue = PQ_HOLD;
1068	} else
1069		m->queue = PQ_FREE + m->pc;
1070	pq = &vm_page_queues[m->queue];
1071	mtx_lock_spin(&vm_page_queue_free_mtx);
1072	pq->lcnt++;
1073	++(*pq->cnt);
1074
1075	/*
1076	 * Put zero'd pages on the end ( where we look for zero'd pages
1077	 * first ) and non-zerod pages at the head.
1078	 */
1079	if (m->flags & PG_ZERO) {
1080		TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
1081		++vm_page_zero_count;
1082	} else {
1083		TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
1084	}
1085	mtx_unlock_spin(&vm_page_queue_free_mtx);
1086	vm_page_free_wakeup();
1087}
1088
1089/*
1090 *	vm_page_unmanage:
1091 *
1092 * 	Prevent PV management from being done on the page.  The page is
1093 *	removed from the paging queues as if it were wired, and as a
1094 *	consequence of no longer being managed the pageout daemon will not
1095 *	touch it (since there is no way to locate the pte mappings for the
1096 *	page).  madvise() calls that mess with the pmap will also no longer
1097 *	operate on the page.
1098 *
1099 *	Beyond that the page is still reasonably 'normal'.  Freeing the page
1100 *	will clear the flag.
1101 *
1102 *	This routine is used by OBJT_PHYS objects - objects using unswappable
1103 *	physical memory as backing store rather then swap-backed memory and
1104 *	will eventually be extended to support 4MB unmanaged physical
1105 *	mappings.
1106 */
1107void
1108vm_page_unmanage(vm_page_t m)
1109{
1110
1111	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1112	if ((m->flags & PG_UNMANAGED) == 0) {
1113		if (m->wire_count == 0)
1114			vm_pageq_remove(m);
1115	}
1116	vm_page_flag_set(m, PG_UNMANAGED);
1117}
1118
1119/*
1120 *	vm_page_wire:
1121 *
1122 *	Mark this page as wired down by yet
1123 *	another map, removing it from paging queues
1124 *	as necessary.
1125 *
1126 *	The page queues must be locked.
1127 *	This routine may not block.
1128 */
1129void
1130vm_page_wire(vm_page_t m)
1131{
1132
1133	/*
1134	 * Only bump the wire statistics if the page is not already wired,
1135	 * and only unqueue the page if it is on some queue (if it is unmanaged
1136	 * it is already off the queues).
1137	 */
1138	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1139	if (m->flags & PG_FICTITIOUS)
1140		return;
1141	if (m->wire_count == 0) {
1142		if ((m->flags & PG_UNMANAGED) == 0)
1143			vm_pageq_remove(m);
1144		atomic_add_int(&cnt.v_wire_count, 1);
1145	}
1146	m->wire_count++;
1147	KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
1148}
1149
1150/*
1151 *	vm_page_unwire:
1152 *
1153 *	Release one wiring of this page, potentially
1154 *	enabling it to be paged again.
1155 *
1156 *	Many pages placed on the inactive queue should actually go
1157 *	into the cache, but it is difficult to figure out which.  What
1158 *	we do instead, if the inactive target is well met, is to put
1159 *	clean pages at the head of the inactive queue instead of the tail.
1160 *	This will cause them to be moved to the cache more quickly and
1161 *	if not actively re-referenced, freed more quickly.  If we just
1162 *	stick these pages at the end of the inactive queue, heavy filesystem
1163 *	meta-data accesses can cause an unnecessary paging load on memory bound
1164 *	processes.  This optimization causes one-time-use metadata to be
1165 *	reused more quickly.
1166 *
1167 *	BUT, if we are in a low-memory situation we have no choice but to
1168 *	put clean pages on the cache queue.
1169 *
1170 *	A number of routines use vm_page_unwire() to guarantee that the page
1171 *	will go into either the inactive or active queues, and will NEVER
1172 *	be placed in the cache - for example, just after dirtying a page.
1173 *	dirty pages in the cache are not allowed.
1174 *
1175 *	The page queues must be locked.
1176 *	This routine may not block.
1177 */
1178void
1179vm_page_unwire(vm_page_t m, int activate)
1180{
1181
1182	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1183	if (m->flags & PG_FICTITIOUS)
1184		return;
1185	if (m->wire_count > 0) {
1186		m->wire_count--;
1187		if (m->wire_count == 0) {
1188			atomic_subtract_int(&cnt.v_wire_count, 1);
1189			if (m->flags & PG_UNMANAGED) {
1190				;
1191			} else if (activate)
1192				vm_pageq_enqueue(PQ_ACTIVE, m);
1193			else {
1194				vm_page_flag_clear(m, PG_WINATCFLS);
1195				vm_pageq_enqueue(PQ_INACTIVE, m);
1196			}
1197		}
1198	} else {
1199		panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
1200	}
1201}
1202
1203
1204/*
1205 * Move the specified page to the inactive queue.  If the page has
1206 * any associated swap, the swap is deallocated.
1207 *
1208 * Normally athead is 0 resulting in LRU operation.  athead is set
1209 * to 1 if we want this page to be 'as if it were placed in the cache',
1210 * except without unmapping it from the process address space.
1211 *
1212 * This routine may not block.
1213 */
1214static __inline void
1215_vm_page_deactivate(vm_page_t m, int athead)
1216{
1217
1218	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1219
1220	/*
1221	 * Ignore if already inactive.
1222	 */
1223	if (m->queue == PQ_INACTIVE)
1224		return;
1225	if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1226		if ((m->queue - m->pc) == PQ_CACHE)
1227			cnt.v_reactivated++;
1228		vm_page_flag_clear(m, PG_WINATCFLS);
1229		vm_pageq_remove(m);
1230		if (athead)
1231			TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1232		else
1233			TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1234		m->queue = PQ_INACTIVE;
1235		vm_page_queues[PQ_INACTIVE].lcnt++;
1236		cnt.v_inactive_count++;
1237	}
1238}
1239
1240void
1241vm_page_deactivate(vm_page_t m)
1242{
1243    _vm_page_deactivate(m, 0);
1244}
1245
1246/*
1247 * vm_page_try_to_cache:
1248 *
1249 * Returns 0 on failure, 1 on success
1250 */
1251int
1252vm_page_try_to_cache(vm_page_t m)
1253{
1254
1255	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1256	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1257	if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1258	    (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1259		return (0);
1260	}
1261	pmap_remove_all(m);
1262	if (m->dirty)
1263		return (0);
1264	vm_page_cache(m);
1265	return (1);
1266}
1267
1268/*
1269 * vm_page_try_to_free()
1270 *
1271 *	Attempt to free the page.  If we cannot free it, we do nothing.
1272 *	1 is returned on success, 0 on failure.
1273 */
1274int
1275vm_page_try_to_free(vm_page_t m)
1276{
1277
1278	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1279	if (m->object != NULL)
1280		VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1281	if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1282	    (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1283		return (0);
1284	}
1285	pmap_remove_all(m);
1286	if (m->dirty)
1287		return (0);
1288	vm_page_free(m);
1289	return (1);
1290}
1291
1292/*
1293 * vm_page_cache
1294 *
1295 * Put the specified page onto the page cache queue (if appropriate).
1296 *
1297 * This routine may not block.
1298 */
1299void
1300vm_page_cache(vm_page_t m)
1301{
1302
1303	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1304	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1305	if ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy ||
1306	    m->hold_count || m->wire_count) {
1307		printf("vm_page_cache: attempting to cache busy page\n");
1308		return;
1309	}
1310	if ((m->queue - m->pc) == PQ_CACHE)
1311		return;
1312
1313	/*
1314	 * Remove all pmaps and indicate that the page is not
1315	 * writeable or mapped.
1316	 */
1317	pmap_remove_all(m);
1318	if (m->dirty != 0) {
1319		panic("vm_page_cache: caching a dirty page, pindex: %ld",
1320			(long)m->pindex);
1321	}
1322	vm_pageq_remove_nowakeup(m);
1323	vm_pageq_enqueue(PQ_CACHE + m->pc, m);
1324	vm_page_free_wakeup();
1325}
1326
1327/*
1328 * vm_page_dontneed
1329 *
1330 *	Cache, deactivate, or do nothing as appropriate.  This routine
1331 *	is typically used by madvise() MADV_DONTNEED.
1332 *
1333 *	Generally speaking we want to move the page into the cache so
1334 *	it gets reused quickly.  However, this can result in a silly syndrome
1335 *	due to the page recycling too quickly.  Small objects will not be
1336 *	fully cached.  On the otherhand, if we move the page to the inactive
1337 *	queue we wind up with a problem whereby very large objects
1338 *	unnecessarily blow away our inactive and cache queues.
1339 *
1340 *	The solution is to move the pages based on a fixed weighting.  We
1341 *	either leave them alone, deactivate them, or move them to the cache,
1342 *	where moving them to the cache has the highest weighting.
1343 *	By forcing some pages into other queues we eventually force the
1344 *	system to balance the queues, potentially recovering other unrelated
1345 *	space from active.  The idea is to not force this to happen too
1346 *	often.
1347 */
1348void
1349vm_page_dontneed(vm_page_t m)
1350{
1351	static int dnweight;
1352	int dnw;
1353	int head;
1354
1355	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1356	dnw = ++dnweight;
1357
1358	/*
1359	 * occassionally leave the page alone
1360	 */
1361	if ((dnw & 0x01F0) == 0 ||
1362	    m->queue == PQ_INACTIVE ||
1363	    m->queue - m->pc == PQ_CACHE
1364	) {
1365		if (m->act_count >= ACT_INIT)
1366			--m->act_count;
1367		return;
1368	}
1369
1370	if (m->dirty == 0 && pmap_is_modified(m))
1371		vm_page_dirty(m);
1372
1373	if (m->dirty || (dnw & 0x0070) == 0) {
1374		/*
1375		 * Deactivate the page 3 times out of 32.
1376		 */
1377		head = 0;
1378	} else {
1379		/*
1380		 * Cache the page 28 times out of every 32.  Note that
1381		 * the page is deactivated instead of cached, but placed
1382		 * at the head of the queue instead of the tail.
1383		 */
1384		head = 1;
1385	}
1386	_vm_page_deactivate(m, head);
1387}
1388
1389/*
1390 * Grab a page, waiting until we are waken up due to the page
1391 * changing state.  We keep on waiting, if the page continues
1392 * to be in the object.  If the page doesn't exist, first allocate it
1393 * and then conditionally zero it.
1394 *
1395 * This routine may block.
1396 */
1397vm_page_t
1398vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
1399{
1400	vm_page_t m;
1401
1402	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1403retrylookup:
1404	if ((m = vm_page_lookup(object, pindex)) != NULL) {
1405		vm_page_lock_queues();
1406		if (m->busy || (m->flags & PG_BUSY)) {
1407			vm_page_flag_set(m, PG_WANTED | PG_REFERENCED);
1408			VM_OBJECT_UNLOCK(object);
1409			msleep(m, &vm_page_queue_mtx, PDROP | PVM, "pgrbwt", 0);
1410			VM_OBJECT_LOCK(object);
1411			if ((allocflags & VM_ALLOC_RETRY) == 0)
1412				return (NULL);
1413			goto retrylookup;
1414		} else {
1415			if (allocflags & VM_ALLOC_WIRED)
1416				vm_page_wire(m);
1417			if ((allocflags & VM_ALLOC_NOBUSY) == 0)
1418				vm_page_busy(m);
1419			vm_page_unlock_queues();
1420			return (m);
1421		}
1422	}
1423	m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_RETRY);
1424	if (m == NULL) {
1425		VM_OBJECT_UNLOCK(object);
1426		VM_WAIT;
1427		VM_OBJECT_LOCK(object);
1428		if ((allocflags & VM_ALLOC_RETRY) == 0)
1429			return (NULL);
1430		goto retrylookup;
1431	}
1432	if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
1433		pmap_zero_page(m);
1434	return (m);
1435}
1436
1437/*
1438 * Mapping function for valid bits or for dirty bits in
1439 * a page.  May not block.
1440 *
1441 * Inputs are required to range within a page.
1442 */
1443__inline int
1444vm_page_bits(int base, int size)
1445{
1446	int first_bit;
1447	int last_bit;
1448
1449	KASSERT(
1450	    base + size <= PAGE_SIZE,
1451	    ("vm_page_bits: illegal base/size %d/%d", base, size)
1452	);
1453
1454	if (size == 0)		/* handle degenerate case */
1455		return (0);
1456
1457	first_bit = base >> DEV_BSHIFT;
1458	last_bit = (base + size - 1) >> DEV_BSHIFT;
1459
1460	return ((2 << last_bit) - (1 << first_bit));
1461}
1462
1463/*
1464 *	vm_page_set_validclean:
1465 *
1466 *	Sets portions of a page valid and clean.  The arguments are expected
1467 *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
1468 *	of any partial chunks touched by the range.  The invalid portion of
1469 *	such chunks will be zero'd.
1470 *
1471 *	This routine may not block.
1472 *
1473 *	(base + size) must be less then or equal to PAGE_SIZE.
1474 */
1475void
1476vm_page_set_validclean(vm_page_t m, int base, int size)
1477{
1478	int pagebits;
1479	int frag;
1480	int endoff;
1481
1482	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1483	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1484	if (size == 0)	/* handle degenerate case */
1485		return;
1486
1487	/*
1488	 * If the base is not DEV_BSIZE aligned and the valid
1489	 * bit is clear, we have to zero out a portion of the
1490	 * first block.
1491	 */
1492	if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
1493	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
1494		pmap_zero_page_area(m, frag, base - frag);
1495
1496	/*
1497	 * If the ending offset is not DEV_BSIZE aligned and the
1498	 * valid bit is clear, we have to zero out a portion of
1499	 * the last block.
1500	 */
1501	endoff = base + size;
1502	if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
1503	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
1504		pmap_zero_page_area(m, endoff,
1505		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
1506
1507	/*
1508	 * Set valid, clear dirty bits.  If validating the entire
1509	 * page we can safely clear the pmap modify bit.  We also
1510	 * use this opportunity to clear the PG_NOSYNC flag.  If a process
1511	 * takes a write fault on a MAP_NOSYNC memory area the flag will
1512	 * be set again.
1513	 *
1514	 * We set valid bits inclusive of any overlap, but we can only
1515	 * clear dirty bits for DEV_BSIZE chunks that are fully within
1516	 * the range.
1517	 */
1518	pagebits = vm_page_bits(base, size);
1519	m->valid |= pagebits;
1520#if 0	/* NOT YET */
1521	if ((frag = base & (DEV_BSIZE - 1)) != 0) {
1522		frag = DEV_BSIZE - frag;
1523		base += frag;
1524		size -= frag;
1525		if (size < 0)
1526			size = 0;
1527	}
1528	pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
1529#endif
1530	m->dirty &= ~pagebits;
1531	if (base == 0 && size == PAGE_SIZE) {
1532		pmap_clear_modify(m);
1533		vm_page_flag_clear(m, PG_NOSYNC);
1534	}
1535}
1536
1537void
1538vm_page_clear_dirty(vm_page_t m, int base, int size)
1539{
1540
1541	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1542	m->dirty &= ~vm_page_bits(base, size);
1543}
1544
1545/*
1546 *	vm_page_set_invalid:
1547 *
1548 *	Invalidates DEV_BSIZE'd chunks within a page.  Both the
1549 *	valid and dirty bits for the effected areas are cleared.
1550 *
1551 *	May not block.
1552 */
1553void
1554vm_page_set_invalid(vm_page_t m, int base, int size)
1555{
1556	int bits;
1557
1558	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1559	bits = vm_page_bits(base, size);
1560	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1561	m->valid &= ~bits;
1562	m->dirty &= ~bits;
1563	m->object->generation++;
1564}
1565
1566/*
1567 * vm_page_zero_invalid()
1568 *
1569 *	The kernel assumes that the invalid portions of a page contain
1570 *	garbage, but such pages can be mapped into memory by user code.
1571 *	When this occurs, we must zero out the non-valid portions of the
1572 *	page so user code sees what it expects.
1573 *
1574 *	Pages are most often semi-valid when the end of a file is mapped
1575 *	into memory and the file's size is not page aligned.
1576 */
1577void
1578vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
1579{
1580	int b;
1581	int i;
1582
1583	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1584	/*
1585	 * Scan the valid bits looking for invalid sections that
1586	 * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
1587	 * valid bit may be set ) have already been zerod by
1588	 * vm_page_set_validclean().
1589	 */
1590	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
1591		if (i == (PAGE_SIZE / DEV_BSIZE) ||
1592		    (m->valid & (1 << i))
1593		) {
1594			if (i > b) {
1595				pmap_zero_page_area(m,
1596				    b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
1597			}
1598			b = i + 1;
1599		}
1600	}
1601
1602	/*
1603	 * setvalid is TRUE when we can safely set the zero'd areas
1604	 * as being valid.  We can do this if there are no cache consistancy
1605	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
1606	 */
1607	if (setvalid)
1608		m->valid = VM_PAGE_BITS_ALL;
1609}
1610
1611/*
1612 *	vm_page_is_valid:
1613 *
1614 *	Is (partial) page valid?  Note that the case where size == 0
1615 *	will return FALSE in the degenerate case where the page is
1616 *	entirely invalid, and TRUE otherwise.
1617 *
1618 *	May not block.
1619 */
1620int
1621vm_page_is_valid(vm_page_t m, int base, int size)
1622{
1623	int bits = vm_page_bits(base, size);
1624
1625	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1626	if (m->valid && ((m->valid & bits) == bits))
1627		return 1;
1628	else
1629		return 0;
1630}
1631
1632/*
1633 * update dirty bits from pmap/mmu.  May not block.
1634 */
1635void
1636vm_page_test_dirty(vm_page_t m)
1637{
1638	if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
1639		vm_page_dirty(m);
1640	}
1641}
1642
1643int so_zerocp_fullpage = 0;
1644
1645void
1646vm_page_cowfault(vm_page_t m)
1647{
1648	vm_page_t mnew;
1649	vm_object_t object;
1650	vm_pindex_t pindex;
1651
1652	object = m->object;
1653	pindex = m->pindex;
1654
1655 retry_alloc:
1656	pmap_remove_all(m);
1657	vm_page_remove(m);
1658	mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL);
1659	if (mnew == NULL) {
1660		vm_page_insert(m, object, pindex);
1661		vm_page_unlock_queues();
1662		VM_OBJECT_UNLOCK(object);
1663		VM_WAIT;
1664		VM_OBJECT_LOCK(object);
1665		vm_page_lock_queues();
1666		goto retry_alloc;
1667	}
1668
1669	if (m->cow == 0) {
1670		/*
1671		 * check to see if we raced with an xmit complete when
1672		 * waiting to allocate a page.  If so, put things back
1673		 * the way they were
1674		 */
1675		vm_page_free(mnew);
1676		vm_page_insert(m, object, pindex);
1677	} else { /* clear COW & copy page */
1678		if (!so_zerocp_fullpage)
1679			pmap_copy_page(m, mnew);
1680		mnew->valid = VM_PAGE_BITS_ALL;
1681		vm_page_dirty(mnew);
1682		vm_page_flag_clear(mnew, PG_BUSY);
1683		mnew->wire_count = m->wire_count - m->cow;
1684		m->wire_count = m->cow;
1685	}
1686}
1687
1688void
1689vm_page_cowclear(vm_page_t m)
1690{
1691
1692	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1693	if (m->cow) {
1694		m->cow--;
1695		/*
1696		 * let vm_fault add back write permission  lazily
1697		 */
1698	}
1699	/*
1700	 *  sf_buf_free() will free the page, so we needn't do it here
1701	 */
1702}
1703
1704void
1705vm_page_cowsetup(vm_page_t m)
1706{
1707
1708	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1709	m->cow++;
1710	pmap_page_protect(m, VM_PROT_READ);
1711}
1712
1713#include "opt_ddb.h"
1714#ifdef DDB
1715#include <sys/kernel.h>
1716
1717#include <ddb/ddb.h>
1718
1719DB_SHOW_COMMAND(page, vm_page_print_page_info)
1720{
1721	db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
1722	db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
1723	db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
1724	db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
1725	db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
1726	db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
1727	db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
1728	db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
1729	db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
1730	db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
1731}
1732
1733DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
1734{
1735	int i;
1736	db_printf("PQ_FREE:");
1737	for (i = 0; i < PQ_L2_SIZE; i++) {
1738		db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt);
1739	}
1740	db_printf("\n");
1741
1742	db_printf("PQ_CACHE:");
1743	for (i = 0; i < PQ_L2_SIZE; i++) {
1744		db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt);
1745	}
1746	db_printf("\n");
1747
1748	db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
1749		vm_page_queues[PQ_ACTIVE].lcnt,
1750		vm_page_queues[PQ_INACTIVE].lcnt);
1751}
1752#endif /* DDB */
1753