vm_page.c revision 128613
1264377Sdes/*
2224638Sbrooks * Copyright (c) 1991 Regents of the University of California.
357429Smarkm * All rights reserved.
457429Smarkm *
557429Smarkm * This code is derived from software contributed to Berkeley by
657429Smarkm * The Mach Operating System project at Carnegie-Mellon University.
760576Skris *
865674Skris * Redistribution and use in source and binary forms, with or without
965674Skris * modification, are permitted provided that the following conditions
1065674Skris * are met:
1165674Skris * 1. Redistributions of source code must retain the above copyright
1265674Skris *    notice, this list of conditions and the following disclaimer.
1360576Skris * 2. Redistributions in binary form must reproduce the above copyright
1465674Skris *    notice, this list of conditions and the following disclaimer in the
1565674Skris *    documentation and/or other materials provided with the distribution.
1692559Sdes * 4. Neither the name of the University nor the names of its contributors
1765674Skris *    may be used to endorse or promote products derived from this software
1865674Skris *    without specific prior written permission.
1965674Skris *
2065674Skris * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2165674Skris * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2265674Skris * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2365674Skris * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2465674Skris * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2565674Skris * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2665674Skris * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2765674Skris * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2865674Skris * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2965674Skris * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3065674Skris * SUCH DAMAGE.
3165674Skris *
3265674Skris *	from: @(#)vm_page.c	7.4 (Berkeley) 5/7/91
3365674Skris */
3465674Skris
3565674Skris/*
3665674Skris * Copyright (c) 1987, 1990 Carnegie-Mellon University.
3757429Smarkm * All rights reserved.
3857429Smarkm *
3957429Smarkm * Authors: Avadis Tevanian, Jr., Michael Wayne Young
4057429Smarkm *
41162856Sdes * Permission to use, copy, modify and distribute this software and
42162856Sdes * its documentation is hereby granted, provided that both the copyright
43162856Sdes * notice and this permission notice appear in all copies of the
44162856Sdes * software, derivative works or modified versions, and any portions
45262566Sdes * thereof, and that both notices appear in supporting documentation.
46162856Sdes *
4760576Skris * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
4876262Sgreen * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
49262566Sdes * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
5076262Sgreen *
51264377Sdes * Carnegie Mellon requests users of this software to return to
52264377Sdes *
5357429Smarkm *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
54149753Sdes *  School of Computer Science
55149753Sdes *  Carnegie Mellon University
5698941Sdes *  Pittsburgh PA 15213-3890
57124211Sdes *
58124211Sdes * any improvements or extensions that they make and grant Carnegie the
59124211Sdes * rights to redistribute these changes.
6057429Smarkm */
6192559Sdes
6292559Sdes/*
6392559Sdes *			GENERAL RULES ON VM_PAGE MANIPULATION
6492559Sdes *
6592559Sdes *	- a pageq mutex is required when adding or removing a page from a
66248619Sdes *	  page queue (vm_page_queue[]), regardless of other mutexes or the
67248619Sdes *	  busy state of a page.
68149753Sdes *
69262566Sdes *	- a hash chain mutex is required when associating or disassociating
70262566Sdes *	  a page from the VM PAGE CACHE hash table (vm_page_buckets),
71262566Sdes *	  regardless of other mutexes or the busy state of a page.
7298684Sdes *
73255767Sdes *	- either a hash chain mutex OR a busied page is required in order
74255767Sdes *	  to modify the page flags.  A hash chain mutex must be obtained in
75255767Sdes *	  order to busy a page.  A page's flags cannot be modified by a
76248619Sdes *	  hash chain mutex if the page is marked busy.
77248619Sdes *
78248619Sdes *	- The object memq mutex is held when inserting or removing
79248619Sdes *	  pages from an object (vm_page_insert() or vm_page_remove()).  This
8069591Sgreen *	  is different from the object's main mutex.
81248619Sdes *
82248619Sdes *	Generally speaking, you have to be aware of side effects when running
83248619Sdes *	vm_page ops.  A vm_page_lookup() will return with the hash chain
84248619Sdes *	locked, whether it was able to lookup the page or not.  vm_page_free(),
85248619Sdes *	vm_page_cache(), vm_page_activate(), and a number of other routines
86248619Sdes *	will release the hash chain mutex for you.  Intermediate manipulation
87248619Sdes *	routines such as vm_page_flag_set() expect the hash chain to be held
88248619Sdes *	on entry and the hash chain will remain held on return.
89248619Sdes *
90248619Sdes *	pageq scanning can only occur with the pageq in question locked.
91248619Sdes *	We have a known bottleneck with the active queue, but the cache
9298684Sdes *	and free queues are actually arrays already.
93248619Sdes */
94248619Sdes
95248619Sdes/*
96248619Sdes *	Resident memory management module.
97248619Sdes */
98248619Sdes
99248619Sdes#include <sys/cdefs.h>
100248619Sdes__FBSDID("$FreeBSD: head/sys/vm/vm_page.c 128613 2004-04-24 20:53:55Z alc $");
101248619Sdes
10298684Sdes#include <sys/param.h>
103262566Sdes#include <sys/systm.h>
104262566Sdes#include <sys/lock.h>
105248619Sdes#include <sys/malloc.h>
10692559Sdes#include <sys/mutex.h>
10769591Sgreen#include <sys/proc.h>
10892559Sdes#include <sys/vmmeter.h>
10957429Smarkm#include <sys/vnode.h>
110262566Sdes
111255767Sdes#include <vm/vm.h>
112262566Sdes#include <vm/vm_param.h>
113255767Sdes#include <vm/vm_kern.h>
114255767Sdes#include <vm/vm_object.h>
115255767Sdes#include <vm/vm_page.h>
116255767Sdes#include <vm/vm_pageout.h>
117255767Sdes#include <vm/vm_pager.h>
118255767Sdes#include <vm/vm_extern.h>
119255767Sdes#include <vm/uma.h>
120255767Sdes#include <vm/uma_int.h>
121262566Sdes
122262566Sdes/*
123255767Sdes *	Associated with page of user-allocatable memory is a
124262566Sdes *	page structure.
125255767Sdes */
126255767Sdes
127255767Sdesstruct mtx vm_page_queue_mtx;
128255767Sdesstruct mtx vm_page_queue_free_mtx;
129255767Sdes
130255767Sdesvm_page_t vm_page_array = 0;
131255767Sdesint vm_page_array_size = 0;
132255767Sdeslong first_page = 0;
13398684Sdesint vm_page_zero_count = 0;
134126277Sdes
13557429Smarkm/*
13692559Sdes *	vm_set_page_size:
13757429Smarkm *
13899063Sdes *	Sets the page size, perhaps based upon the memory
13998684Sdes *	size.  Must be called before any use of page-size
140126277Sdes *	dependent functions.
14169591Sgreen */
14292559Sdesvoid
14369591Sgreenvm_set_page_size(void)
14499063Sdes{
14598684Sdes	if (cnt.v_page_size == 0)
146262566Sdes		cnt.v_page_size = PAGE_SIZE;
147262566Sdes	if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0)
148262566Sdes		panic("vm_set_page_size: page size not a power of two");
149262566Sdes}
150262566Sdes
151262566Sdes/*
152262566Sdes *	vm_page_startup:
153262566Sdes *
154248619Sdes *	Initializes the resident memory module.
155248619Sdes *
156248619Sdes *	Allocates memory for the page cells, and
157248619Sdes *	for the object/offset-to-page hash table headers.
158248619Sdes *	Each page cell is initialized and placed on the free list.
159248619Sdes */
160248619Sdesvm_offset_t
161248619Sdesvm_page_startup(vm_offset_t vaddr)
162262566Sdes{
163262566Sdes	vm_offset_t mapped;
164262566Sdes	vm_size_t npages;
165262566Sdes	vm_paddr_t page_range;
166262566Sdes	vm_paddr_t new_end;
167262566Sdes	int i;
168248619Sdes	vm_paddr_t pa;
169248619Sdes	int nblocks;
170248619Sdes	vm_paddr_t last_pa;
171126277Sdes
17298684Sdes	/* the biggest memory array is the second group of pages */
17398684Sdes	vm_paddr_t end;
17498684Sdes	vm_paddr_t biggestsize;
17569591Sgreen	int biggestone;
17676262Sgreen
177192595Sdes	vm_paddr_t total;
178192595Sdes	vm_size_t bootpages;
179262566Sdes
180192595Sdes	total = 0;
181192595Sdes	biggestsize = 0;
182192595Sdes	biggestone = 0;
18369591Sgreen	nblocks = 0;
18457429Smarkm	vaddr = round_page(vaddr);
18576262Sgreen
18692559Sdes	for (i = 0; phys_avail[i + 1]; i += 2) {
18757429Smarkm		phys_avail[i] = round_page(phys_avail[i]);
18869591Sgreen		phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
18969591Sgreen	}
19069591Sgreen
19157429Smarkm	for (i = 0; phys_avail[i + 1]; i += 2) {
19257429Smarkm		vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
19369591Sgreen
194255767Sdes		if (size > biggestsize) {
19569591Sgreen			biggestone = i;
19660576Skris			biggestsize = size;
197255767Sdes		}
19869591Sgreen		++nblocks;
199147005Sdes		total += size;
20069591Sgreen	}
20169591Sgreen
20260576Skris	end = phys_avail[biggestone+1];
20357429Smarkm
204255767Sdes	/*
20569591Sgreen	 * Initialize the locks.
20657429Smarkm	 */
207255767Sdes	mtx_init(&vm_page_queue_mtx, "vm page queue mutex", NULL, MTX_DEF);
20869591Sgreen	mtx_init(&vm_page_queue_free_mtx, "vm page queue free mutex", NULL,
20969591Sgreen	    MTX_SPIN);
21069591Sgreen
21169591Sgreen	/*
21257429Smarkm	 * Initialize the queue headers for the free queue, the active queue
21357429Smarkm	 * and the inactive queue.
21460576Skris	 */
21560576Skris	vm_pageq_init();
21660576Skris
21760576Skris	/*
218255767Sdes	 * Allocate memory for use when boot strapping the kernel memory
219137019Sdes	 * allocator.
22060576Skris	 */
22160576Skris	bootpages = UMA_BOOT_PAGES * UMA_SLAB_SIZE;
22261212Skris	new_end = end - bootpages;
22360576Skris	new_end = trunc_page(new_end);
224137019Sdes	mapped = pmap_map(&vaddr, new_end, end,
22569591Sgreen	    VM_PROT_READ | VM_PROT_WRITE);
22692559Sdes	bzero((caddr_t) mapped, end - new_end);
22769591Sgreen	uma_startup((caddr_t)mapped);
228224638Sbrooks
229224638Sbrooks	/*
230224638Sbrooks	 * Compute the number of pages of memory that will be available for
231224638Sbrooks	 * use (taking into account the overhead of a page structure per
232224638Sbrooks	 * page).
233224638Sbrooks	 */
23469591Sgreen	first_page = phys_avail[0] / PAGE_SIZE;
235255767Sdes	page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE - first_page;
23660576Skris	npages = (total - (page_range * sizeof(struct vm_page)) -
23760576Skris	    (end - new_end)) / PAGE_SIZE;
23860576Skris	end = new_end;
23969591Sgreen
240255767Sdes	/*
24160576Skris	 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
24260576Skris	 */
24360576Skris	vaddr += PAGE_SIZE;
24457429Smarkm
24557429Smarkm	/*
24657429Smarkm	 * Initialize the mem entry structures now, and put them in the free
24757429Smarkm	 * queue.
24857429Smarkm	 */
24957429Smarkm	new_end = trunc_page(end - page_range * sizeof(struct vm_page));
25057429Smarkm	mapped = pmap_map(&vaddr, new_end, end,
25157429Smarkm	    VM_PROT_READ | VM_PROT_WRITE);
252255767Sdes	vm_page_array = (vm_page_t) mapped;
25361212Skris	phys_avail[biggestone + 1] = new_end;
25461212Skris
255147005Sdes	/*
256147005Sdes	 * Clear all of the page structures
257147005Sdes	 */
258147005Sdes	bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
25957429Smarkm	vm_page_array_size = page_range;
26057429Smarkm
26169591Sgreen	/*
26269591Sgreen	 * Construct the free queue(s) in descending order (by physical
26357429Smarkm	 * address) so that the first 16MB of physical memory is allocated
264255767Sdes	 * last rather than first.  On large-memory machines, this avoids
26569591Sgreen	 * the exhaustion of low physical memory before isa_dmainit has run.
26657429Smarkm	 */
26757429Smarkm	cnt.v_page_count = 0;
26860576Skris	cnt.v_free_count = 0;
269255767Sdes	for (i = 0; phys_avail[i + 1] && npages > 0; i += 2) {
27092559Sdes		pa = phys_avail[i];
271137019Sdes		last_pa = phys_avail[i + 1];
27257429Smarkm		while (pa < last_pa && npages-- > 0) {
27392559Sdes			vm_pageq_add_new_page(pa);
27498941Sdes			pa += PAGE_SIZE;
27598941Sdes		}
27698941Sdes	}
27792559Sdes	return (vaddr);
278149753Sdes}
27998941Sdes
280149753Sdesvoid
28192559Sdesvm_page_flag_set(vm_page_t m, unsigned short bits)
28292559Sdes{
28392559Sdes
28492559Sdes	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
28592559Sdes	m->flags |= bits;
28692559Sdes}
28792559Sdes
28892559Sdesvoid
28992559Sdesvm_page_flag_clear(vm_page_t m, unsigned short bits)
29092559Sdes{
29192559Sdes
292248619Sdes	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
29392559Sdes	m->flags &= ~bits;
29469591Sgreen}
29569591Sgreen
29669591Sgreenvoid
297248619Sdesvm_page_busy(vm_page_t m)
29869591Sgreen{
29969591Sgreen	KASSERT((m->flags & PG_BUSY) == 0,
30069591Sgreen	    ("vm_page_busy: page already busy!!!"));
30192559Sdes	vm_page_flag_set(m, PG_BUSY);
302262566Sdes}
303262566Sdes
304262566Sdes/*
305262566Sdes *      vm_page_flash:
30692559Sdes *
30792559Sdes *      wakeup anyone waiting for the page.
30898941Sdes */
30998941Sdesvoid
31098941Sdesvm_page_flash(vm_page_t m)
31198941Sdes{
31298941Sdes	if (m->flags & PG_WANTED) {
31398941Sdes		vm_page_flag_clear(m, PG_WANTED);
31498941Sdes		wakeup(m);
315137019Sdes	}
31698941Sdes}
31792559Sdes
318137019Sdes/*
31992559Sdes *      vm_page_wakeup:
32092559Sdes *
321248619Sdes *      clear the PG_BUSY flag and wakeup anyone waiting for the
322248619Sdes *      page.
323248619Sdes *
324248619Sdes */
325248619Sdesvoid
32692559Sdesvm_page_wakeup(vm_page_t m)
327149753Sdes{
328113911Sdes	KASSERT(m->flags & PG_BUSY, ("vm_page_wakeup: page not busy!!!"));
32992559Sdes	vm_page_flag_clear(m, PG_BUSY);
33092559Sdes	vm_page_flash(m);
33192559Sdes}
33292559Sdes
33392559Sdesvoid
33492559Sdesvm_page_io_start(vm_page_t m)
33592559Sdes{
33698941Sdes
337149753Sdes	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
338149753Sdes	m->busy++;
339149753Sdes}
340149753Sdes
341149753Sdesvoid
342149753Sdesvm_page_io_finish(vm_page_t m)
343149753Sdes{
344264377Sdes
345255767Sdes	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
346255767Sdes	m->busy--;
347149753Sdes	if (m->busy == 0)
34857429Smarkm		vm_page_flash(m);
34957429Smarkm}
350248619Sdes
351248619Sdes/*
352248619Sdes * Keep page from being freed by the page daemon
353248619Sdes * much of the same effect as wiring, except much lower
354248619Sdes * overhead and should be used only for *very* temporary
355248619Sdes * holding ("wiring").
356248619Sdes */
357248619Sdesvoid
358248619Sdesvm_page_hold(vm_page_t mem)
359262566Sdes{
360262566Sdes
361248619Sdes	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
362262566Sdes        mem->hold_count++;
363262566Sdes}
364248619Sdes
36560576Skrisvoid
366262566Sdesvm_page_unhold(vm_page_t mem)
367262566Sdes{
368262566Sdes
369248619Sdes	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
370248619Sdes	--mem->hold_count;
371248619Sdes	KASSERT(mem->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!"));
372248619Sdes	if (mem->hold_count == 0 && mem->queue == PQ_HOLD)
373248619Sdes		vm_page_free_toq(mem);
374248619Sdes}
375248619Sdes
376248619Sdes/*
377248619Sdes *	vm_page_free:
378248619Sdes *
379248619Sdes *	Free a page
380248619Sdes *
381248619Sdes *	The clearing of PG_ZERO is a temporary safety until the code can be
382248619Sdes *	reviewed to determine that PG_ZERO is being properly cleared on
383248619Sdes *	write faults or maps.  PG_ZERO was previously cleared in
384248619Sdes *	vm_page_alloc().
385248619Sdes */
386248619Sdesvoid
387248619Sdesvm_page_free(vm_page_t m)
388248619Sdes{
389248619Sdes	vm_page_flag_clear(m, PG_ZERO);
39069591Sgreen	vm_page_free_toq(m);
391248619Sdes	vm_page_zero_idle_wakeup();
392248619Sdes}
393248619Sdes
394248619Sdes/*
395248619Sdes *	vm_page_free_zero:
396248619Sdes *
397248619Sdes *	Free a page to the zerod-pages queue
398248619Sdes */
399248619Sdesvoid
400248619Sdesvm_page_free_zero(vm_page_t m)
401262566Sdes{
402248619Sdes	vm_page_flag_set(m, PG_ZERO);
403248619Sdes	vm_page_free_toq(m);
404248619Sdes}
405248619Sdes
406248619Sdes/*
407248619Sdes *	vm_page_sleep_if_busy:
408262566Sdes *
40960576Skris *	Sleep and release the page queues lock if PG_BUSY is set or,
41060576Skris *	if also_m_busy is TRUE, busy is non-zero.  Returns TRUE if the
411262566Sdes *	thread slept and the page queues lock was released.
412262566Sdes *	Otherwise, retains the page queues lock and returns FALSE.
413262566Sdes */
414262566Sdesint
415262566Sdesvm_page_sleep_if_busy(vm_page_t m, int also_m_busy, const char *msg)
416262566Sdes{
417262566Sdes	int is_object_locked;
418262566Sdes
419262566Sdes	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
420262566Sdes	if ((m->flags & PG_BUSY) || (also_m_busy && m->busy)) {
421262566Sdes		vm_page_flag_set(m, PG_WANTED | PG_REFERENCED);
422262566Sdes		/*
423262566Sdes		 * Remove mtx_owned() after vm_object locking is finished.
424262566Sdes		 */
42560576Skris		if ((is_object_locked = m->object != NULL &&
42692559Sdes		     mtx_owned(&m->object->mtx)))
42757429Smarkm			mtx_unlock(&m->object->mtx);
428262566Sdes		msleep(m, &vm_page_queue_mtx, PDROP | PVM, msg, 0);
429264377Sdes		if (is_object_locked)
430262566Sdes			mtx_lock(&m->object->mtx);
43192559Sdes		return (TRUE);
43257429Smarkm	}
43357429Smarkm	return (FALSE);
43469591Sgreen}
43569591Sgreen
43669591Sgreen/*
43769591Sgreen *	vm_page_dirty:
43857429Smarkm *
43960576Skris *	make page all dirty
440255767Sdes */
441137019Sdesvoid
44257429Smarkmvm_page_dirty(vm_page_t m)
44376262Sgreen{
44457429Smarkm	KASSERT(m->queue - m->pc != PQ_CACHE,
445264377Sdes	    ("vm_page_dirty: page in cache!"));
446264377Sdes	KASSERT(m->queue - m->pc != PQ_FREE,
447264377Sdes	    ("vm_page_dirty: page is free!"));
44857429Smarkm	m->dirty = VM_PAGE_BITS_ALL;
449137019Sdes}
45057429Smarkm
451264377Sdes/*
45257429Smarkm *	vm_page_splay:
45392559Sdes *
45492559Sdes *	Implements Sleator and Tarjan's top-down splay algorithm.  Returns
45598684Sdes *	the vm_page containing the given pindex.  If, however, that
45698684Sdes *	pindex is not found in the vm_object, returns a vm_page that is
45798684Sdes *	adjacent to the pindex, coming before or after it.
45898684Sdes */
45998684Sdesvm_page_t
46098684Sdesvm_page_splay(vm_pindex_t pindex, vm_page_t root)
461126277Sdes{
46298684Sdes	struct vm_page dummy;
463255767Sdes	vm_page_t lefttreemax, righttreemin, y;
46498684Sdes
46598684Sdes	if (root == NULL)
46698684Sdes		return (root);
46798684Sdes	lefttreemax = righttreemin = &dummy;
468262566Sdes	for (;; root = y) {
469262566Sdes		if (pindex < root->pindex) {
47098684Sdes			if ((y = root->left) == NULL)
47198684Sdes				break;
47298684Sdes			if (pindex < y->pindex) {
47398684Sdes				/* Rotate right. */
47498684Sdes				root->left = y->right;
47598684Sdes				y->right = root;
47698684Sdes				root = y;
47798684Sdes				if ((y = root->left) == NULL)
478255767Sdes					break;
47998684Sdes			}
48098684Sdes			/* Link into the new root's right tree. */
481262566Sdes			righttreemin->left = root;
482262566Sdes			righttreemin = root;
483262566Sdes		} else if (pindex > root->pindex) {
484262566Sdes			if ((y = root->right) == NULL)
485262566Sdes				break;
486262566Sdes			if (pindex > y->pindex) {
48798684Sdes				/* Rotate left. */
488224638Sbrooks				root->right = y->left;
489224638Sbrooks				y->left = root;
490224638Sbrooks				root = y;
49198684Sdes				if ((y = root->right) == NULL)
49298684Sdes					break;
49398684Sdes			}
49498684Sdes			/* Link into the new root's left tree. */
495149753Sdes			lefttreemax->right = root;
49698684Sdes			lefttreemax = root;
497149753Sdes		} else
49898684Sdes			break;
49998684Sdes	}
500157019Sdes	/* Assemble the new root. */
501124211Sdes	lefttreemax->right = root->left;
502124211Sdes	righttreemin->left = root->right;
503124211Sdes	root->left = dummy.right;
50498684Sdes	root->right = dummy.left;
505248619Sdes	return (root);
506124211Sdes}
507124211Sdes
508124211Sdes/*
509248619Sdes *	vm_page_insert:		[ internal use only ]
510248619Sdes *
51198684Sdes *	Inserts the given mem entry into the object and object list.
512124211Sdes *
513124211Sdes *	The pagetables are not updated but will presumably fault the page
514124211Sdes *	in if necessary, or if a kernel page the caller will at some point
51598684Sdes *	enter the page into the kernel's pmap.  We are not allowed to block
51698684Sdes *	here so we *can't* do this anyway.
51798684Sdes *
51898684Sdes *	The object and page must be locked, and must be splhigh.
51998684Sdes *	This routine may not block.
52098684Sdes */
52198684Sdesvoid
52298684Sdesvm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
523255767Sdes{
52498684Sdes	vm_page_t root;
52598684Sdes
526262566Sdes	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
527262566Sdes	if (m->object != NULL)
528262566Sdes		panic("vm_page_insert: page already inserted");
52998684Sdes
530224638Sbrooks	/*
531224638Sbrooks	 * Record the object/offset pair in this page
532224638Sbrooks	 */
53398684Sdes	m->object = object;
53498684Sdes	m->pindex = pindex;
53598684Sdes
53698684Sdes	/*
53798684Sdes	 * Now link into the object's ordered list of backed pages.
53898684Sdes	 */
539157019Sdes	root = object->root;
540124211Sdes	if (root == NULL) {
541124211Sdes		m->left = NULL;
542124211Sdes		m->right = NULL;
54398684Sdes		TAILQ_INSERT_TAIL(&object->memq, m, listq);
544248619Sdes	} else {
545124211Sdes		root = vm_page_splay(pindex, root);
546124211Sdes		if (pindex < root->pindex) {
547124211Sdes			m->left = root->left;
548248619Sdes			m->right = root;
549248619Sdes			root->left = NULL;
55098684Sdes			TAILQ_INSERT_BEFORE(root, m, listq);
551124211Sdes		} else if (pindex == root->pindex)
552124211Sdes			panic("vm_page_insert: offset already allocated");
553124211Sdes		else {
55498684Sdes			m->right = root->right;
55598684Sdes			m->left = root;
55698684Sdes			root->right = NULL;
55798684Sdes			TAILQ_INSERT_AFTER(&object->memq, root, m, listq);
55898684Sdes		}
55998684Sdes	}
560126277Sdes	object->root = m;
56198684Sdes	object->generation++;
562255767Sdes
56398684Sdes	/*
56498684Sdes	 * show that the object has one more resident page.
565248619Sdes	 */
56698684Sdes	object->resident_page_count++;
56798684Sdes
56898684Sdes	/*
56998684Sdes	 * Since we are inserting a new and possibly dirty page,
57098684Sdes	 * update the object's OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY flags.
57198684Sdes	 */
57298684Sdes	if (m->flags & PG_WRITEABLE)
57398684Sdes		vm_object_set_writeable_dirty(object);
57498684Sdes}
57598684Sdes
57698684Sdes/*
577255767Sdes *	vm_page_remove:
57898684Sdes *				NOTE: used by device pager as well -wfj
57998684Sdes *
580248619Sdes *	Removes the given mem entry from the object/offset-page
58198684Sdes *	table and the object page list, but do not invalidate/terminate
58298684Sdes *	the backing store.
58398684Sdes *
58498684Sdes *	The object and page must be locked, and at splhigh.
585 *	The underlying pmap entry (if any) is NOT removed here.
586 *	This routine may not block.
587 */
588void
589vm_page_remove(vm_page_t m)
590{
591	vm_object_t object;
592	vm_page_t root;
593
594	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
595	if (m->object == NULL)
596		return;
597#ifndef	__alpha__
598	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
599#endif
600	if ((m->flags & PG_BUSY) == 0) {
601		panic("vm_page_remove: page not busy");
602	}
603
604	/*
605	 * Basically destroy the page.
606	 */
607	vm_page_wakeup(m);
608
609	object = m->object;
610
611	/*
612	 * Now remove from the object's list of backed pages.
613	 */
614	if (m != object->root)
615		vm_page_splay(m->pindex, object->root);
616	if (m->left == NULL)
617		root = m->right;
618	else {
619		root = vm_page_splay(m->pindex, m->left);
620		root->right = m->right;
621	}
622	object->root = root;
623	TAILQ_REMOVE(&object->memq, m, listq);
624
625	/*
626	 * And show that the object has one fewer resident page.
627	 */
628	object->resident_page_count--;
629	object->generation++;
630
631	m->object = NULL;
632}
633
634/*
635 *	vm_page_lookup:
636 *
637 *	Returns the page associated with the object/offset
638 *	pair specified; if none is found, NULL is returned.
639 *
640 *	The object must be locked.
641 *	This routine may not block.
642 *	This is a critical path routine
643 */
644vm_page_t
645vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
646{
647	vm_page_t m;
648
649	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
650	if ((m = object->root) != NULL && m->pindex != pindex) {
651		m = vm_page_splay(pindex, m);
652		if ((object->root = m)->pindex != pindex)
653			m = NULL;
654	}
655	return (m);
656}
657
658/*
659 *	vm_page_rename:
660 *
661 *	Move the given memory entry from its
662 *	current object to the specified target object/offset.
663 *
664 *	The object must be locked.
665 *	This routine may not block.
666 *
667 *	Note: this routine will raise itself to splvm(), the caller need not.
668 *
669 *	Note: swap associated with the page must be invalidated by the move.  We
670 *	      have to do this for several reasons:  (1) we aren't freeing the
671 *	      page, (2) we are dirtying the page, (3) the VM system is probably
672 *	      moving the page from object A to B, and will then later move
673 *	      the backing store from A to B and we can't have a conflict.
674 *
675 *	Note: we *always* dirty the page.  It is necessary both for the
676 *	      fact that we moved it, and because we may be invalidating
677 *	      swap.  If the page is on the cache, we have to deactivate it
678 *	      or vm_page_dirty() will panic.  Dirty pages are not allowed
679 *	      on the cache.
680 */
681void
682vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
683{
684	int s;
685
686	s = splvm();
687	vm_page_remove(m);
688	vm_page_insert(m, new_object, new_pindex);
689	if (m->queue - m->pc == PQ_CACHE)
690		vm_page_deactivate(m);
691	vm_page_dirty(m);
692	splx(s);
693}
694
695/*
696 *	vm_page_select_cache:
697 *
698 *	Find a page on the cache queue with color optimization.  As pages
699 *	might be found, but not applicable, they are deactivated.  This
700 *	keeps us from using potentially busy cached pages.
701 *
702 *	This routine must be called at splvm().
703 *	This routine may not block.
704 */
705vm_page_t
706vm_page_select_cache(int color)
707{
708	vm_page_t m;
709
710	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
711	while (TRUE) {
712		m = vm_pageq_find(PQ_CACHE, color, FALSE);
713		if (m && ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy ||
714			       m->hold_count || m->wire_count ||
715			  (!VM_OBJECT_TRYLOCK(m->object) &&
716			   !VM_OBJECT_LOCKED(m->object)))) {
717			vm_page_deactivate(m);
718			continue;
719		}
720		return m;
721	}
722}
723
724/*
725 *	vm_page_alloc:
726 *
727 *	Allocate and return a memory cell associated
728 *	with this VM object/offset pair.
729 *
730 *	page_req classes:
731 *	VM_ALLOC_NORMAL		normal process request
732 *	VM_ALLOC_SYSTEM		system *really* needs a page
733 *	VM_ALLOC_INTERRUPT	interrupt time request
734 *	VM_ALLOC_ZERO		zero page
735 *
736 *	This routine may not block.
737 *
738 *	Additional special handling is required when called from an
739 *	interrupt (VM_ALLOC_INTERRUPT).  We are not allowed to mess with
740 *	the page cache in this case.
741 */
742vm_page_t
743vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
744{
745	vm_object_t m_object;
746	vm_page_t m = NULL;
747	int color, flags, page_req, s;
748
749	page_req = req & VM_ALLOC_CLASS_MASK;
750
751	if ((req & VM_ALLOC_NOOBJ) == 0) {
752		KASSERT(object != NULL,
753		    ("vm_page_alloc: NULL object."));
754		VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
755		color = (pindex + object->pg_color) & PQ_L2_MASK;
756	} else
757		color = pindex & PQ_L2_MASK;
758
759	/*
760	 * The pager is allowed to eat deeper into the free page list.
761	 */
762	if ((curproc == pageproc) && (page_req != VM_ALLOC_INTERRUPT)) {
763		page_req = VM_ALLOC_SYSTEM;
764	};
765
766	s = splvm();
767loop:
768	mtx_lock_spin(&vm_page_queue_free_mtx);
769	if (cnt.v_free_count > cnt.v_free_reserved ||
770	    (page_req == VM_ALLOC_SYSTEM &&
771	     cnt.v_cache_count == 0 &&
772	     cnt.v_free_count > cnt.v_interrupt_free_min) ||
773	    (page_req == VM_ALLOC_INTERRUPT && cnt.v_free_count > 0)) {
774		/*
775		 * Allocate from the free queue if the number of free pages
776		 * exceeds the minimum for the request class.
777		 */
778		m = vm_pageq_find(PQ_FREE, color, (req & VM_ALLOC_ZERO) != 0);
779	} else if (page_req != VM_ALLOC_INTERRUPT) {
780		mtx_unlock_spin(&vm_page_queue_free_mtx);
781		/*
782		 * Allocatable from cache (non-interrupt only).  On success,
783		 * we must free the page and try again, thus ensuring that
784		 * cnt.v_*_free_min counters are replenished.
785		 */
786		vm_page_lock_queues();
787		if ((m = vm_page_select_cache(color)) == NULL) {
788			vm_page_unlock_queues();
789			splx(s);
790#if defined(DIAGNOSTIC)
791			if (cnt.v_cache_count > 0)
792				printf("vm_page_alloc(NORMAL): missing pages on cache queue: %d\n", cnt.v_cache_count);
793#endif
794			atomic_add_int(&vm_pageout_deficit, 1);
795			pagedaemon_wakeup();
796			return (NULL);
797		}
798		KASSERT(m->dirty == 0, ("Found dirty cache page %p", m));
799		m_object = m->object;
800		VM_OBJECT_LOCK_ASSERT(m_object, MA_OWNED);
801		vm_page_busy(m);
802		pmap_remove_all(m);
803		vm_page_free(m);
804		vm_page_unlock_queues();
805		if (m_object != object)
806			VM_OBJECT_UNLOCK(m_object);
807		goto loop;
808	} else {
809		/*
810		 * Not allocatable from cache from interrupt, give up.
811		 */
812		mtx_unlock_spin(&vm_page_queue_free_mtx);
813		splx(s);
814		atomic_add_int(&vm_pageout_deficit, 1);
815		pagedaemon_wakeup();
816		return (NULL);
817	}
818
819	/*
820	 *  At this point we had better have found a good page.
821	 */
822
823	KASSERT(
824	    m != NULL,
825	    ("vm_page_alloc(): missing page on free queue\n")
826	);
827
828	/*
829	 * Remove from free queue
830	 */
831
832	vm_pageq_remove_nowakeup(m);
833
834	/*
835	 * Initialize structure.  Only the PG_ZERO flag is inherited.
836	 */
837	flags = PG_BUSY;
838	if (m->flags & PG_ZERO) {
839		vm_page_zero_count--;
840		if (req & VM_ALLOC_ZERO)
841			flags = PG_ZERO | PG_BUSY;
842	}
843	m->flags = flags;
844	if (req & VM_ALLOC_WIRED) {
845		atomic_add_int(&cnt.v_wire_count, 1);
846		m->wire_count = 1;
847	} else
848		m->wire_count = 0;
849	m->hold_count = 0;
850	m->act_count = 0;
851	m->busy = 0;
852	m->valid = 0;
853	KASSERT(m->dirty == 0, ("vm_page_alloc: free/cache page %p was dirty", m));
854	mtx_unlock_spin(&vm_page_queue_free_mtx);
855
856	/*
857	 * vm_page_insert() is safe prior to the splx().  Note also that
858	 * inserting a page here does not insert it into the pmap (which
859	 * could cause us to block allocating memory).  We cannot block
860	 * anywhere.
861	 */
862	if ((req & VM_ALLOC_NOOBJ) == 0)
863		vm_page_insert(m, object, pindex);
864	else
865		m->pindex = pindex;
866
867	/*
868	 * Don't wakeup too often - wakeup the pageout daemon when
869	 * we would be nearly out of memory.
870	 */
871	if (vm_paging_needed())
872		pagedaemon_wakeup();
873
874	splx(s);
875	return (m);
876}
877
878/*
879 *	vm_wait:	(also see VM_WAIT macro)
880 *
881 *	Block until free pages are available for allocation
882 *	- Called in various places before memory allocations.
883 */
884void
885vm_wait(void)
886{
887	int s;
888
889	s = splvm();
890	vm_page_lock_queues();
891	if (curproc == pageproc) {
892		vm_pageout_pages_needed = 1;
893		msleep(&vm_pageout_pages_needed, &vm_page_queue_mtx,
894		    PDROP | PSWP, "VMWait", 0);
895	} else {
896		if (!vm_pages_needed) {
897			vm_pages_needed = 1;
898			wakeup(&vm_pages_needed);
899		}
900		msleep(&cnt.v_free_count, &vm_page_queue_mtx, PDROP | PVM,
901		    "vmwait", 0);
902	}
903	splx(s);
904}
905
906/*
907 *	vm_waitpfault:	(also see VM_WAITPFAULT macro)
908 *
909 *	Block until free pages are available for allocation
910 *	- Called only in vm_fault so that processes page faulting
911 *	  can be easily tracked.
912 *	- Sleeps at a lower priority than vm_wait() so that vm_wait()ing
913 *	  processes will be able to grab memory first.  Do not change
914 *	  this balance without careful testing first.
915 */
916void
917vm_waitpfault(void)
918{
919	int s;
920
921	s = splvm();
922	vm_page_lock_queues();
923	if (!vm_pages_needed) {
924		vm_pages_needed = 1;
925		wakeup(&vm_pages_needed);
926	}
927	msleep(&cnt.v_free_count, &vm_page_queue_mtx, PDROP | PUSER,
928	    "pfault", 0);
929	splx(s);
930}
931
932/*
933 *	vm_page_activate:
934 *
935 *	Put the specified page on the active list (if appropriate).
936 *	Ensure that act_count is at least ACT_INIT but do not otherwise
937 *	mess with it.
938 *
939 *	The page queues must be locked.
940 *	This routine may not block.
941 */
942void
943vm_page_activate(vm_page_t m)
944{
945	int s;
946
947	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
948	s = splvm();
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	splx(s);
963}
964
965/*
966 *	vm_page_free_wakeup:
967 *
968 *	Helper routine for vm_page_free_toq() and vm_page_cache().  This
969 *	routine is called when a page has been added to the cache or free
970 *	queues.
971 *
972 *	This routine may not block.
973 *	This routine must be called at splvm()
974 */
975static __inline void
976vm_page_free_wakeup(void)
977{
978
979	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
980	/*
981	 * if pageout daemon needs pages, then tell it that there are
982	 * some free.
983	 */
984	if (vm_pageout_pages_needed &&
985	    cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
986		wakeup(&vm_pageout_pages_needed);
987		vm_pageout_pages_needed = 0;
988	}
989	/*
990	 * wakeup processes that are waiting on memory if we hit a
991	 * high water mark. And wakeup scheduler process if we have
992	 * lots of memory. this process will swapin processes.
993	 */
994	if (vm_pages_needed && !vm_page_count_min()) {
995		vm_pages_needed = 0;
996		wakeup(&cnt.v_free_count);
997	}
998}
999
1000/*
1001 *	vm_page_free_toq:
1002 *
1003 *	Returns the given page to the PQ_FREE list,
1004 *	disassociating it with any VM object.
1005 *
1006 *	Object and page must be locked prior to entry.
1007 *	This routine may not block.
1008 */
1009
1010void
1011vm_page_free_toq(vm_page_t m)
1012{
1013	int s;
1014	struct vpgqueues *pq;
1015	vm_object_t object = m->object;
1016
1017	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1018	s = splvm();
1019	cnt.v_tfree++;
1020
1021	if (m->busy || ((m->queue - m->pc) == PQ_FREE)) {
1022		printf(
1023		"vm_page_free: pindex(%lu), busy(%d), PG_BUSY(%d), hold(%d)\n",
1024		    (u_long)m->pindex, m->busy, (m->flags & PG_BUSY) ? 1 : 0,
1025		    m->hold_count);
1026		if ((m->queue - m->pc) == PQ_FREE)
1027			panic("vm_page_free: freeing free page");
1028		else
1029			panic("vm_page_free: freeing busy page");
1030	}
1031
1032	/*
1033	 * unqueue, then remove page.  Note that we cannot destroy
1034	 * the page here because we do not want to call the pager's
1035	 * callback routine until after we've put the page on the
1036	 * appropriate free queue.
1037	 */
1038	vm_pageq_remove_nowakeup(m);
1039	vm_page_remove(m);
1040
1041	/*
1042	 * If fictitious remove object association and
1043	 * return, otherwise delay object association removal.
1044	 */
1045	if ((m->flags & PG_FICTITIOUS) != 0) {
1046		splx(s);
1047		return;
1048	}
1049
1050	m->valid = 0;
1051	vm_page_undirty(m);
1052
1053	if (m->wire_count != 0) {
1054		if (m->wire_count > 1) {
1055			panic("vm_page_free: invalid wire count (%d), pindex: 0x%lx",
1056				m->wire_count, (long)m->pindex);
1057		}
1058		panic("vm_page_free: freeing wired page\n");
1059	}
1060
1061	/*
1062	 * If we've exhausted the object's resident pages we want to free
1063	 * it up.
1064	 */
1065	if (object &&
1066	    (object->type == OBJT_VNODE) &&
1067	    ((object->flags & OBJ_DEAD) == 0)
1068	) {
1069		struct vnode *vp = (struct vnode *)object->handle;
1070
1071		if (vp) {
1072			VI_LOCK(vp);
1073			if (VSHOULDFREE(vp))
1074				vfree(vp);
1075			VI_UNLOCK(vp);
1076		}
1077	}
1078
1079	/*
1080	 * Clear the UNMANAGED flag when freeing an unmanaged page.
1081	 */
1082	if (m->flags & PG_UNMANAGED) {
1083		m->flags &= ~PG_UNMANAGED;
1084	}
1085
1086	if (m->hold_count != 0) {
1087		m->flags &= ~PG_ZERO;
1088		m->queue = PQ_HOLD;
1089	} else
1090		m->queue = PQ_FREE + m->pc;
1091	pq = &vm_page_queues[m->queue];
1092	mtx_lock_spin(&vm_page_queue_free_mtx);
1093	pq->lcnt++;
1094	++(*pq->cnt);
1095
1096	/*
1097	 * Put zero'd pages on the end ( where we look for zero'd pages
1098	 * first ) and non-zerod pages at the head.
1099	 */
1100	if (m->flags & PG_ZERO) {
1101		TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
1102		++vm_page_zero_count;
1103	} else {
1104		TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
1105	}
1106	mtx_unlock_spin(&vm_page_queue_free_mtx);
1107	vm_page_free_wakeup();
1108	splx(s);
1109}
1110
1111/*
1112 *	vm_page_unmanage:
1113 *
1114 * 	Prevent PV management from being done on the page.  The page is
1115 *	removed from the paging queues as if it were wired, and as a
1116 *	consequence of no longer being managed the pageout daemon will not
1117 *	touch it (since there is no way to locate the pte mappings for the
1118 *	page).  madvise() calls that mess with the pmap will also no longer
1119 *	operate on the page.
1120 *
1121 *	Beyond that the page is still reasonably 'normal'.  Freeing the page
1122 *	will clear the flag.
1123 *
1124 *	This routine is used by OBJT_PHYS objects - objects using unswappable
1125 *	physical memory as backing store rather then swap-backed memory and
1126 *	will eventually be extended to support 4MB unmanaged physical
1127 *	mappings.
1128 */
1129void
1130vm_page_unmanage(vm_page_t m)
1131{
1132	int s;
1133
1134	s = splvm();
1135	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1136	if ((m->flags & PG_UNMANAGED) == 0) {
1137		if (m->wire_count == 0)
1138			vm_pageq_remove(m);
1139	}
1140	vm_page_flag_set(m, PG_UNMANAGED);
1141	splx(s);
1142}
1143
1144/*
1145 *	vm_page_wire:
1146 *
1147 *	Mark this page as wired down by yet
1148 *	another map, removing it from paging queues
1149 *	as necessary.
1150 *
1151 *	The page queues must be locked.
1152 *	This routine may not block.
1153 */
1154void
1155vm_page_wire(vm_page_t m)
1156{
1157	int s;
1158
1159	/*
1160	 * Only bump the wire statistics if the page is not already wired,
1161	 * and only unqueue the page if it is on some queue (if it is unmanaged
1162	 * it is already off the queues).
1163	 */
1164	s = splvm();
1165	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1166	if (m->wire_count == 0) {
1167		if ((m->flags & PG_UNMANAGED) == 0)
1168			vm_pageq_remove(m);
1169		atomic_add_int(&cnt.v_wire_count, 1);
1170	}
1171	m->wire_count++;
1172	KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
1173	splx(s);
1174}
1175
1176/*
1177 *	vm_page_unwire:
1178 *
1179 *	Release one wiring of this page, potentially
1180 *	enabling it to be paged again.
1181 *
1182 *	Many pages placed on the inactive queue should actually go
1183 *	into the cache, but it is difficult to figure out which.  What
1184 *	we do instead, if the inactive target is well met, is to put
1185 *	clean pages at the head of the inactive queue instead of the tail.
1186 *	This will cause them to be moved to the cache more quickly and
1187 *	if not actively re-referenced, freed more quickly.  If we just
1188 *	stick these pages at the end of the inactive queue, heavy filesystem
1189 *	meta-data accesses can cause an unnecessary paging load on memory bound
1190 *	processes.  This optimization causes one-time-use metadata to be
1191 *	reused more quickly.
1192 *
1193 *	BUT, if we are in a low-memory situation we have no choice but to
1194 *	put clean pages on the cache queue.
1195 *
1196 *	A number of routines use vm_page_unwire() to guarantee that the page
1197 *	will go into either the inactive or active queues, and will NEVER
1198 *	be placed in the cache - for example, just after dirtying a page.
1199 *	dirty pages in the cache are not allowed.
1200 *
1201 *	The page queues must be locked.
1202 *	This routine may not block.
1203 */
1204void
1205vm_page_unwire(vm_page_t m, int activate)
1206{
1207	int s;
1208
1209	s = splvm();
1210	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1211	if (m->wire_count > 0) {
1212		m->wire_count--;
1213		if (m->wire_count == 0) {
1214			atomic_subtract_int(&cnt.v_wire_count, 1);
1215			if (m->flags & PG_UNMANAGED) {
1216				;
1217			} else if (activate)
1218				vm_pageq_enqueue(PQ_ACTIVE, m);
1219			else {
1220				vm_page_flag_clear(m, PG_WINATCFLS);
1221				vm_pageq_enqueue(PQ_INACTIVE, m);
1222			}
1223		}
1224	} else {
1225		panic("vm_page_unwire: invalid wire count: %d\n", m->wire_count);
1226	}
1227	splx(s);
1228}
1229
1230
1231/*
1232 * Move the specified page to the inactive queue.  If the page has
1233 * any associated swap, the swap is deallocated.
1234 *
1235 * Normally athead is 0 resulting in LRU operation.  athead is set
1236 * to 1 if we want this page to be 'as if it were placed in the cache',
1237 * except without unmapping it from the process address space.
1238 *
1239 * This routine may not block.
1240 */
1241static __inline void
1242_vm_page_deactivate(vm_page_t m, int athead)
1243{
1244	int s;
1245
1246	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1247	/*
1248	 * Ignore if already inactive.
1249	 */
1250	if (m->queue == PQ_INACTIVE)
1251		return;
1252
1253	s = splvm();
1254	if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1255		if ((m->queue - m->pc) == PQ_CACHE)
1256			cnt.v_reactivated++;
1257		vm_page_flag_clear(m, PG_WINATCFLS);
1258		vm_pageq_remove(m);
1259		if (athead)
1260			TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1261		else
1262			TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1263		m->queue = PQ_INACTIVE;
1264		vm_page_queues[PQ_INACTIVE].lcnt++;
1265		cnt.v_inactive_count++;
1266	}
1267	splx(s);
1268}
1269
1270void
1271vm_page_deactivate(vm_page_t m)
1272{
1273    _vm_page_deactivate(m, 0);
1274}
1275
1276/*
1277 * vm_page_try_to_cache:
1278 *
1279 * Returns 0 on failure, 1 on success
1280 */
1281int
1282vm_page_try_to_cache(vm_page_t m)
1283{
1284
1285	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1286	if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1287	    (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1288		return (0);
1289	}
1290	pmap_remove_all(m);
1291	if (m->dirty)
1292		return (0);
1293	vm_page_cache(m);
1294	return (1);
1295}
1296
1297/*
1298 * vm_page_try_to_free()
1299 *
1300 *	Attempt to free the page.  If we cannot free it, we do nothing.
1301 *	1 is returned on success, 0 on failure.
1302 */
1303int
1304vm_page_try_to_free(vm_page_t m)
1305{
1306
1307	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1308	if (m->object != NULL)
1309		VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1310	if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1311	    (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1312		return (0);
1313	}
1314	pmap_remove_all(m);
1315	if (m->dirty)
1316		return (0);
1317	vm_page_busy(m);
1318	vm_page_free(m);
1319	return (1);
1320}
1321
1322/*
1323 * vm_page_cache
1324 *
1325 * Put the specified page onto the page cache queue (if appropriate).
1326 *
1327 * This routine may not block.
1328 */
1329void
1330vm_page_cache(vm_page_t m)
1331{
1332	int s;
1333
1334	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1335	if ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy ||
1336	    m->hold_count || m->wire_count) {
1337		printf("vm_page_cache: attempting to cache busy page\n");
1338		return;
1339	}
1340	if ((m->queue - m->pc) == PQ_CACHE)
1341		return;
1342
1343	/*
1344	 * Remove all pmaps and indicate that the page is not
1345	 * writeable or mapped.
1346	 */
1347	pmap_remove_all(m);
1348	if (m->dirty != 0) {
1349		panic("vm_page_cache: caching a dirty page, pindex: %ld",
1350			(long)m->pindex);
1351	}
1352	s = splvm();
1353	vm_pageq_remove_nowakeup(m);
1354	vm_pageq_enqueue(PQ_CACHE + m->pc, m);
1355	vm_page_free_wakeup();
1356	splx(s);
1357}
1358
1359/*
1360 * vm_page_dontneed
1361 *
1362 *	Cache, deactivate, or do nothing as appropriate.  This routine
1363 *	is typically used by madvise() MADV_DONTNEED.
1364 *
1365 *	Generally speaking we want to move the page into the cache so
1366 *	it gets reused quickly.  However, this can result in a silly syndrome
1367 *	due to the page recycling too quickly.  Small objects will not be
1368 *	fully cached.  On the otherhand, if we move the page to the inactive
1369 *	queue we wind up with a problem whereby very large objects
1370 *	unnecessarily blow away our inactive and cache queues.
1371 *
1372 *	The solution is to move the pages based on a fixed weighting.  We
1373 *	either leave them alone, deactivate them, or move them to the cache,
1374 *	where moving them to the cache has the highest weighting.
1375 *	By forcing some pages into other queues we eventually force the
1376 *	system to balance the queues, potentially recovering other unrelated
1377 *	space from active.  The idea is to not force this to happen too
1378 *	often.
1379 */
1380void
1381vm_page_dontneed(vm_page_t m)
1382{
1383	static int dnweight;
1384	int dnw;
1385	int head;
1386
1387	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1388	dnw = ++dnweight;
1389
1390	/*
1391	 * occassionally leave the page alone
1392	 */
1393	if ((dnw & 0x01F0) == 0 ||
1394	    m->queue == PQ_INACTIVE ||
1395	    m->queue - m->pc == PQ_CACHE
1396	) {
1397		if (m->act_count >= ACT_INIT)
1398			--m->act_count;
1399		return;
1400	}
1401
1402	if (m->dirty == 0 && pmap_is_modified(m))
1403		vm_page_dirty(m);
1404
1405	if (m->dirty || (dnw & 0x0070) == 0) {
1406		/*
1407		 * Deactivate the page 3 times out of 32.
1408		 */
1409		head = 0;
1410	} else {
1411		/*
1412		 * Cache the page 28 times out of every 32.  Note that
1413		 * the page is deactivated instead of cached, but placed
1414		 * at the head of the queue instead of the tail.
1415		 */
1416		head = 1;
1417	}
1418	_vm_page_deactivate(m, head);
1419}
1420
1421/*
1422 * Grab a page, waiting until we are waken up due to the page
1423 * changing state.  We keep on waiting, if the page continues
1424 * to be in the object.  If the page doesn't exist, allocate it.
1425 *
1426 * This routine may block.
1427 */
1428vm_page_t
1429vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
1430{
1431	vm_page_t m;
1432
1433	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1434retrylookup:
1435	if ((m = vm_page_lookup(object, pindex)) != NULL) {
1436		vm_page_lock_queues();
1437		if (m->busy || (m->flags & PG_BUSY)) {
1438			vm_page_flag_set(m, PG_WANTED | PG_REFERENCED);
1439			VM_OBJECT_UNLOCK(object);
1440			msleep(m, &vm_page_queue_mtx, PDROP | PVM, "pgrbwt", 0);
1441			VM_OBJECT_LOCK(object);
1442			if ((allocflags & VM_ALLOC_RETRY) == 0)
1443				return (NULL);
1444			goto retrylookup;
1445		} else {
1446			if (allocflags & VM_ALLOC_WIRED)
1447				vm_page_wire(m);
1448			vm_page_busy(m);
1449			vm_page_unlock_queues();
1450			return m;
1451		}
1452	}
1453
1454	m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_RETRY);
1455	if (m == NULL) {
1456		VM_OBJECT_UNLOCK(object);
1457		VM_WAIT;
1458		VM_OBJECT_LOCK(object);
1459		if ((allocflags & VM_ALLOC_RETRY) == 0)
1460			return NULL;
1461		goto retrylookup;
1462	}
1463	if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
1464		pmap_zero_page(m);
1465
1466	return m;
1467}
1468
1469/*
1470 * Mapping function for valid bits or for dirty bits in
1471 * a page.  May not block.
1472 *
1473 * Inputs are required to range within a page.
1474 */
1475__inline int
1476vm_page_bits(int base, int size)
1477{
1478	int first_bit;
1479	int last_bit;
1480
1481	KASSERT(
1482	    base + size <= PAGE_SIZE,
1483	    ("vm_page_bits: illegal base/size %d/%d", base, size)
1484	);
1485
1486	if (size == 0)		/* handle degenerate case */
1487		return (0);
1488
1489	first_bit = base >> DEV_BSHIFT;
1490	last_bit = (base + size - 1) >> DEV_BSHIFT;
1491
1492	return ((2 << last_bit) - (1 << first_bit));
1493}
1494
1495/*
1496 *	vm_page_set_validclean:
1497 *
1498 *	Sets portions of a page valid and clean.  The arguments are expected
1499 *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
1500 *	of any partial chunks touched by the range.  The invalid portion of
1501 *	such chunks will be zero'd.
1502 *
1503 *	This routine may not block.
1504 *
1505 *	(base + size) must be less then or equal to PAGE_SIZE.
1506 */
1507void
1508vm_page_set_validclean(vm_page_t m, int base, int size)
1509{
1510	int pagebits;
1511	int frag;
1512	int endoff;
1513
1514	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1515	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1516	if (size == 0)	/* handle degenerate case */
1517		return;
1518
1519	/*
1520	 * If the base is not DEV_BSIZE aligned and the valid
1521	 * bit is clear, we have to zero out a portion of the
1522	 * first block.
1523	 */
1524	if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
1525	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
1526		pmap_zero_page_area(m, frag, base - frag);
1527
1528	/*
1529	 * If the ending offset is not DEV_BSIZE aligned and the
1530	 * valid bit is clear, we have to zero out a portion of
1531	 * the last block.
1532	 */
1533	endoff = base + size;
1534	if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
1535	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
1536		pmap_zero_page_area(m, endoff,
1537		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
1538
1539	/*
1540	 * Set valid, clear dirty bits.  If validating the entire
1541	 * page we can safely clear the pmap modify bit.  We also
1542	 * use this opportunity to clear the PG_NOSYNC flag.  If a process
1543	 * takes a write fault on a MAP_NOSYNC memory area the flag will
1544	 * be set again.
1545	 *
1546	 * We set valid bits inclusive of any overlap, but we can only
1547	 * clear dirty bits for DEV_BSIZE chunks that are fully within
1548	 * the range.
1549	 */
1550	pagebits = vm_page_bits(base, size);
1551	m->valid |= pagebits;
1552#if 0	/* NOT YET */
1553	if ((frag = base & (DEV_BSIZE - 1)) != 0) {
1554		frag = DEV_BSIZE - frag;
1555		base += frag;
1556		size -= frag;
1557		if (size < 0)
1558			size = 0;
1559	}
1560	pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
1561#endif
1562	m->dirty &= ~pagebits;
1563	if (base == 0 && size == PAGE_SIZE) {
1564		pmap_clear_modify(m);
1565		vm_page_flag_clear(m, PG_NOSYNC);
1566	}
1567}
1568
1569void
1570vm_page_clear_dirty(vm_page_t m, int base, int size)
1571{
1572
1573	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1574	m->dirty &= ~vm_page_bits(base, size);
1575}
1576
1577/*
1578 *	vm_page_set_invalid:
1579 *
1580 *	Invalidates DEV_BSIZE'd chunks within a page.  Both the
1581 *	valid and dirty bits for the effected areas are cleared.
1582 *
1583 *	May not block.
1584 */
1585void
1586vm_page_set_invalid(vm_page_t m, int base, int size)
1587{
1588	int bits;
1589
1590	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1591	bits = vm_page_bits(base, size);
1592	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1593	m->valid &= ~bits;
1594	m->dirty &= ~bits;
1595	m->object->generation++;
1596}
1597
1598/*
1599 * vm_page_zero_invalid()
1600 *
1601 *	The kernel assumes that the invalid portions of a page contain
1602 *	garbage, but such pages can be mapped into memory by user code.
1603 *	When this occurs, we must zero out the non-valid portions of the
1604 *	page so user code sees what it expects.
1605 *
1606 *	Pages are most often semi-valid when the end of a file is mapped
1607 *	into memory and the file's size is not page aligned.
1608 */
1609void
1610vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
1611{
1612	int b;
1613	int i;
1614
1615	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1616	/*
1617	 * Scan the valid bits looking for invalid sections that
1618	 * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
1619	 * valid bit may be set ) have already been zerod by
1620	 * vm_page_set_validclean().
1621	 */
1622	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
1623		if (i == (PAGE_SIZE / DEV_BSIZE) ||
1624		    (m->valid & (1 << i))
1625		) {
1626			if (i > b) {
1627				pmap_zero_page_area(m,
1628				    b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
1629			}
1630			b = i + 1;
1631		}
1632	}
1633
1634	/*
1635	 * setvalid is TRUE when we can safely set the zero'd areas
1636	 * as being valid.  We can do this if there are no cache consistancy
1637	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
1638	 */
1639	if (setvalid)
1640		m->valid = VM_PAGE_BITS_ALL;
1641}
1642
1643/*
1644 *	vm_page_is_valid:
1645 *
1646 *	Is (partial) page valid?  Note that the case where size == 0
1647 *	will return FALSE in the degenerate case where the page is
1648 *	entirely invalid, and TRUE otherwise.
1649 *
1650 *	May not block.
1651 */
1652int
1653vm_page_is_valid(vm_page_t m, int base, int size)
1654{
1655	int bits = vm_page_bits(base, size);
1656
1657	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1658	if (m->valid && ((m->valid & bits) == bits))
1659		return 1;
1660	else
1661		return 0;
1662}
1663
1664/*
1665 * update dirty bits from pmap/mmu.  May not block.
1666 */
1667void
1668vm_page_test_dirty(vm_page_t m)
1669{
1670	if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
1671		vm_page_dirty(m);
1672	}
1673}
1674
1675int so_zerocp_fullpage = 0;
1676
1677void
1678vm_page_cowfault(vm_page_t m)
1679{
1680	vm_page_t mnew;
1681	vm_object_t object;
1682	vm_pindex_t pindex;
1683
1684	object = m->object;
1685	pindex = m->pindex;
1686	vm_page_busy(m);
1687
1688 retry_alloc:
1689	vm_page_remove(m);
1690	/*
1691	 * An interrupt allocation is requested because the page
1692	 * queues lock is held.
1693	 */
1694	mnew = vm_page_alloc(object, pindex, VM_ALLOC_INTERRUPT);
1695	if (mnew == NULL) {
1696		vm_page_insert(m, object, pindex);
1697		vm_page_unlock_queues();
1698		VM_OBJECT_UNLOCK(object);
1699		VM_WAIT;
1700		VM_OBJECT_LOCK(object);
1701		vm_page_lock_queues();
1702		goto retry_alloc;
1703	}
1704
1705	if (m->cow == 0) {
1706		/*
1707		 * check to see if we raced with an xmit complete when
1708		 * waiting to allocate a page.  If so, put things back
1709		 * the way they were
1710		 */
1711		vm_page_busy(mnew);
1712		vm_page_free(mnew);
1713		vm_page_insert(m, object, pindex);
1714	} else { /* clear COW & copy page */
1715		if (!so_zerocp_fullpage)
1716			pmap_copy_page(m, mnew);
1717		mnew->valid = VM_PAGE_BITS_ALL;
1718		vm_page_dirty(mnew);
1719		vm_page_flag_clear(mnew, PG_BUSY);
1720	}
1721}
1722
1723void
1724vm_page_cowclear(vm_page_t m)
1725{
1726
1727	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1728	if (m->cow) {
1729		m->cow--;
1730		/*
1731		 * let vm_fault add back write permission  lazily
1732		 */
1733	}
1734	/*
1735	 *  sf_buf_free() will free the page, so we needn't do it here
1736	 */
1737}
1738
1739void
1740vm_page_cowsetup(vm_page_t m)
1741{
1742
1743	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1744	m->cow++;
1745	pmap_page_protect(m, VM_PROT_READ);
1746}
1747
1748#include "opt_ddb.h"
1749#ifdef DDB
1750#include <sys/kernel.h>
1751
1752#include <ddb/ddb.h>
1753
1754DB_SHOW_COMMAND(page, vm_page_print_page_info)
1755{
1756	db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
1757	db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
1758	db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
1759	db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
1760	db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
1761	db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
1762	db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
1763	db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
1764	db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
1765	db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
1766}
1767
1768DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
1769{
1770	int i;
1771	db_printf("PQ_FREE:");
1772	for (i = 0; i < PQ_L2_SIZE; i++) {
1773		db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt);
1774	}
1775	db_printf("\n");
1776
1777	db_printf("PQ_CACHE:");
1778	for (i = 0; i < PQ_L2_SIZE; i++) {
1779		db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt);
1780	}
1781	db_printf("\n");
1782
1783	db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
1784		vm_page_queues[PQ_ACTIVE].lcnt,
1785		vm_page_queues[PQ_INACTIVE].lcnt);
1786}
1787#endif /* DDB */
1788