vm_page.c revision 170292
143313Sbrian/*-
243313Sbrian * Copyright (c) 1991 Regents of the University of California.
343313Sbrian * All rights reserved.
443313Sbrian *
543313Sbrian * This code is derived from software contributed to Berkeley by
643313Sbrian * The Mach Operating System project at Carnegie-Mellon University.
743313Sbrian *
843313Sbrian * Redistribution and use in source and binary forms, with or without
943313Sbrian * modification, are permitted provided that the following conditions
1043313Sbrian * are met:
1143313Sbrian * 1. Redistributions of source code must retain the above copyright
1243313Sbrian *    notice, this list of conditions and the following disclaimer.
1343313Sbrian * 2. Redistributions in binary form must reproduce the above copyright
1443313Sbrian *    notice, this list of conditions and the following disclaimer in the
1543313Sbrian *    documentation and/or other materials provided with the distribution.
1643313Sbrian * 4. Neither the name of the University nor the names of its contributors
1743313Sbrian *    may be used to endorse or promote products derived from this software
1843313Sbrian *    without specific prior written permission.
1943313Sbrian *
2043313Sbrian * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2143313Sbrian * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2243313Sbrian * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2343313Sbrian * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2443313Sbrian * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2543313Sbrian * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2650479Speter * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2743313Sbrian * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2843313Sbrian * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2943313Sbrian * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3043313Sbrian * SUCH DAMAGE.
3198132Sbrian *
3258032Sbrian *	from: @(#)vm_page.c	7.4 (Berkeley) 5/7/91
3343313Sbrian */
3443313Sbrian
3543313Sbrian/*-
3643313Sbrian * Copyright (c) 1987, 1990 Carnegie-Mellon University.
3743313Sbrian * All rights reserved.
3858032Sbrian *
3943313Sbrian * Authors: Avadis Tevanian, Jr., Michael Wayne Young
4058037Sbrian *
4158037Sbrian * Permission to use, copy, modify and distribute this software and
4296324Sbrian * its documentation is hereby granted, provided that both the copyright
4358037Sbrian * notice and this permission notice appear in all copies of the
4458037Sbrian * software, derivative works or modified versions, and any portions
4596324Sbrian * thereof, and that both notices appear in supporting documentation.
4658037Sbrian *
4758037Sbrian * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
4843313Sbrian * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
4998132Sbrian * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
5098132Sbrian *
5198132Sbrian * Carnegie Mellon requests users of this software to return to
52102500Sbrian *
5343313Sbrian *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
5443313Sbrian *  School of Computer Science
5543313Sbrian *  Carnegie Mellon University
5643693Sbrian *  Pittsburgh PA 15213-3890
5743313Sbrian *
5850840Sbrian * any improvements or extensions that they make and grant Carnegie the
5950840Sbrian * rights to redistribute these changes.
6043313Sbrian */
6146686Sbrian
6243313Sbrian/*
6343313Sbrian *			GENERAL RULES ON VM_PAGE MANIPULATION
6443313Sbrian *
6543313Sbrian *	- a pageq mutex is required when adding or removing a page from a
6643313Sbrian *	  page queue (vm_page_queue[]), regardless of other mutexes or the
6743313Sbrian *	  busy state of a page.
6843313Sbrian *
6943313Sbrian *	- a hash chain mutex is required when associating or disassociating
7043313Sbrian *	  a page from the VM PAGE CACHE hash table (vm_page_buckets),
7143313Sbrian *	  regardless of other mutexes or the busy state of a page.
7243313Sbrian *
7343313Sbrian *	- either a hash chain mutex OR a busied page is required in order
7481634Sbrian *	  to modify the page flags.  A hash chain mutex must be obtained in
7581634Sbrian *	  order to busy a page.  A page's flags cannot be modified by a
7643313Sbrian *	  hash chain mutex if the page is marked busy.
7781634Sbrian *
7843313Sbrian *	- The object memq mutex is held when inserting or removing
7943313Sbrian *	  pages from an object (vm_page_insert() or vm_page_remove()).  This
8043313Sbrian *	  is different from the object's main mutex.
8143313Sbrian *
8243313Sbrian *	Generally speaking, you have to be aware of side effects when running
8343313Sbrian *	vm_page ops.  A vm_page_lookup() will return with the hash chain
8443313Sbrian *	locked, whether it was able to lookup the page or not.  vm_page_free(),
8543313Sbrian *	vm_page_cache(), vm_page_activate(), and a number of other routines
8643693Sbrian *	will release the hash chain mutex for you.  Intermediate manipulation
8743693Sbrian *	routines such as vm_page_flag_set() expect the hash chain to be held
8843693Sbrian *	on entry and the hash chain will remain held on return.
8943693Sbrian *
9043693Sbrian *	pageq scanning can only occur with the pageq in question locked.
9143693Sbrian *	We have a known bottleneck with the active queue, but the cache
9243693Sbrian *	and free queues are actually arrays already.
9381634Sbrian */
9443313Sbrian
9596324Sbrian/*
9643313Sbrian *	Resident memory management module.
9796324Sbrian */
9896730Sbrian
9996324Sbrian#include <sys/cdefs.h>
10096324Sbrian__FBSDID("$FreeBSD: head/sys/vm/vm_page.c 170292 2007-06-04 21:45:18Z attilio $");
10196324Sbrian
10296324Sbrian#include <sys/param.h>
10396324Sbrian#include <sys/systm.h>
10496730Sbrian#include <sys/lock.h>
10596730Sbrian#include <sys/kernel.h>
10696730Sbrian#include <sys/malloc.h>
10796730Sbrian#include <sys/mutex.h>
10896730Sbrian#include <sys/proc.h>
10996730Sbrian#include <sys/sysctl.h>
11096730Sbrian#include <sys/vmmeter.h>
11196730Sbrian#include <sys/vnode.h>
11298132Sbrian
11398132Sbrian#include <vm/vm.h>
11498132Sbrian#include <vm/vm_param.h>
11596324Sbrian#include <vm/vm_kern.h>
11696324Sbrian#include <vm/vm_object.h>
11798132Sbrian#include <vm/vm_page.h>
11898132Sbrian#include <vm/vm_pageout.h>
11998132Sbrian#include <vm/vm_pager.h>
12098132Sbrian#include <vm/vm_extern.h>
12198132Sbrian#include <vm/uma.h>
12298132Sbrian#include <vm/uma_int.h>
12398132Sbrian
12498132Sbrian#include <machine/md_var.h>
12598132Sbrian
12698132Sbrian/*
12798132Sbrian *	Associated with page of user-allocatable memory is a
12898132Sbrian *	page structure.
12998132Sbrian */
13098132Sbrian
13198132Sbrianstruct mtx vm_page_queue_mtx;
13298132Sbrianstruct mtx vm_page_queue_free_mtx;
13398132Sbrian
13498132Sbrianvm_page_t vm_page_array = 0;
13598132Sbrianint vm_page_array_size = 0;
13698132Sbrianlong first_page = 0;
13798132Sbrianint vm_page_zero_count = 0;
13898132Sbrian
13998132Sbrianstatic int boot_pages = UMA_BOOT_PAGES;
14098132SbrianTUNABLE_INT("vm.boot_pages", &boot_pages);
14198132SbrianSYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RD, &boot_pages, 0,
14298132Sbrian	"number of pages allocated for bootstrapping the VM system");
14398132Sbrian
14498132Sbrian/*
14598132Sbrian *	vm_set_page_size:
14698132Sbrian *
14798132Sbrian *	Sets the page size, perhaps based upon the memory
14898132Sbrian *	size.  Must be called before any use of page-size
14998132Sbrian *	dependent functions.
15098132Sbrian */
15198132Sbrianvoid
15298132Sbrianvm_set_page_size(void)
15398132Sbrian{
15498132Sbrian	if (cnt.v_page_size == 0)
15598132Sbrian		cnt.v_page_size = PAGE_SIZE;
15698132Sbrian	if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0)
15798132Sbrian		panic("vm_set_page_size: page size not a power of two");
15898132Sbrian}
15998132Sbrian
16098132Sbrian/*
16198132Sbrian *	vm_page_blacklist_lookup:
16298132Sbrian *
16398132Sbrian *	See if a physical address in this page has been listed
16498132Sbrian *	in the blacklist tunable.  Entries in the tunable are
16598132Sbrian *	separated by spaces or commas.  If an invalid integer is
16698132Sbrian *	encountered then the rest of the string is skipped.
16798132Sbrian */
16898132Sbrianstatic int
16998132Sbrianvm_page_blacklist_lookup(char *list, vm_paddr_t pa)
17098132Sbrian{
17198132Sbrian	vm_paddr_t bad;
17298132Sbrian	char *cp, *pos;
17398132Sbrian
17498132Sbrian	for (pos = list; *pos != '\0'; pos = cp) {
17598132Sbrian		bad = strtoq(pos, &cp, 0);
17698132Sbrian		if (*cp != '\0') {
17798132Sbrian			if (*cp == ' ' || *cp == ',') {
17898132Sbrian				cp++;
17998132Sbrian				if (cp == pos)
18098132Sbrian					continue;
18198132Sbrian			} else
18298132Sbrian				break;
18398132Sbrian		}
18498132Sbrian		if (pa == trunc_page(bad))
18598132Sbrian			return (1);
18698132Sbrian	}
18798132Sbrian	return (0);
18898132Sbrian}
18998132Sbrian
19098132Sbrian/*
19198132Sbrian *	vm_page_startup:
19298132Sbrian *
19398132Sbrian *	Initializes the resident memory module.
19498132Sbrian *
19598132Sbrian *	Allocates memory for the page cells, and
19698132Sbrian *	for the object/offset-to-page hash table headers.
19798132Sbrian *	Each page cell is initialized and placed on the free list.
19898132Sbrian */
19998132Sbrianvm_offset_t
20098132Sbrianvm_page_startup(vm_offset_t vaddr)
20198132Sbrian{
20298132Sbrian	vm_offset_t mapped;
20398132Sbrian	vm_size_t npages;
20498132Sbrian	vm_paddr_t page_range;
20598132Sbrian	vm_paddr_t new_end;
20698132Sbrian	int i;
20798132Sbrian	vm_paddr_t pa;
20898132Sbrian	int nblocks;
20998132Sbrian	vm_paddr_t last_pa;
21098132Sbrian	char *list;
21198132Sbrian
21298132Sbrian	/* the biggest memory array is the second group of pages */
21398132Sbrian	vm_paddr_t end;
21498132Sbrian	vm_paddr_t biggestsize;
21598132Sbrian	vm_paddr_t low_water, high_water;
21698132Sbrian	int biggestone;
21798132Sbrian
21898132Sbrian	vm_paddr_t total;
219116622Sume
220116622Sume	total = 0;
221116622Sume	biggestsize = 0;
222116622Sume	biggestone = 0;
223116622Sume	nblocks = 0;
224116622Sume	vaddr = round_page(vaddr);
225116622Sume
226116622Sume	for (i = 0; phys_avail[i + 1]; i += 2) {
227116622Sume		phys_avail[i] = round_page(phys_avail[i]);
228116622Sume		phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
229116622Sume	}
230116622Sume
231116622Sume	low_water = phys_avail[0];
232116622Sume	high_water = phys_avail[1];
233116622Sume
234116622Sume	for (i = 0; phys_avail[i + 1]; i += 2) {
235116622Sume		vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
236116622Sume
237116622Sume		if (size > biggestsize) {
23843693Sbrian			biggestone = i;
23943693Sbrian			biggestsize = size;
24043693Sbrian		}
24143693Sbrian		if (phys_avail[i] < low_water)
24243693Sbrian			low_water = phys_avail[i];
24343313Sbrian		if (phys_avail[i + 1] > high_water)
24443313Sbrian			high_water = phys_avail[i + 1];
24543693Sbrian		++nblocks;
24696324Sbrian		total += size;
24745910Sbrian	}
24881634Sbrian
24981634Sbrian	end = phys_avail[biggestone+1];
25043693Sbrian
25171972Sbrian	/*
25296324Sbrian	 * Initialize the locks.
25381634Sbrian	 */
254116586Sume	mtx_init(&vm_page_queue_mtx, "vm page queue mutex", NULL, MTX_DEF |
255116622Sume	    MTX_RECURSE);
256116586Sume	mtx_init(&vm_page_queue_free_mtx, "vm page queue free mutex", NULL,
257116586Sume	    MTX_DEF);
25843313Sbrian
25943693Sbrian	/*
26071972Sbrian	 * Initialize the queue headers for the free queue, the active queue
26143313Sbrian	 * and the inactive queue.
26243313Sbrian	 */
26343313Sbrian	vm_pageq_init();
26471972Sbrian
26571972Sbrian	/*
26671972Sbrian	 * Allocate memory for use when boot strapping the kernel memory
26771972Sbrian	 * allocator.
26871972Sbrian	 */
26943313Sbrian	new_end = end - (boot_pages * UMA_SLAB_SIZE);
27043313Sbrian	new_end = trunc_page(new_end);
27143693Sbrian	mapped = pmap_map(&vaddr, new_end, end,
27271972Sbrian	    VM_PROT_READ | VM_PROT_WRITE);
27396324Sbrian	bzero((void *)mapped, end - new_end);
27496324Sbrian	uma_startup((void *)mapped, boot_pages);
27596324Sbrian
27696324Sbrian#if defined(__amd64__) || defined(__i386__)
27796324Sbrian	/*
27843693Sbrian	 * Allocate a bitmap to indicate that a random physical page
27943313Sbrian	 * needs to be included in a minidump.
28043313Sbrian	 *
28143693Sbrian	 * The amd64 port needs this to indicate which direct map pages
28271972Sbrian	 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
28371972Sbrian	 *
28443693Sbrian	 * However, i386 still needs this workspace internally within the
28543693Sbrian	 * minidump code.  In theory, they are not needed on i386, but are
28643313Sbrian	 * included should the sf_buf code decide to use them.
28765178Sbrian	 */
28871972Sbrian	page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE;
28971972Sbrian	vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
29071972Sbrian	new_end -= vm_page_dump_size;
29171972Sbrian	vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
29265178Sbrian	    new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
29365178Sbrian	bzero((void *)vm_page_dump, vm_page_dump_size);
29465178Sbrian#endif
29565178Sbrian	/*
29643313Sbrian	 * Compute the number of pages of memory that will be available for
29771972Sbrian	 * use (taking into account the overhead of a page structure per
29871972Sbrian	 * page).
29971972Sbrian	 */
30043693Sbrian	first_page = low_water / PAGE_SIZE;
30143693Sbrian#ifdef VM_PHYSSEG_SPARSE
30243313Sbrian	page_range = 0;
30343313Sbrian	for (i = 0; phys_avail[i + 1] != 0; i += 2)
30471972Sbrian		page_range += atop(phys_avail[i + 1] - phys_avail[i]);
30543693Sbrian#elif defined(VM_PHYSSEG_DENSE)
30671972Sbrian	page_range = high_water / PAGE_SIZE - first_page;
30771972Sbrian#else
30843693Sbrian#error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
30943693Sbrian#endif
31043313Sbrian	npages = (total - (page_range * sizeof(struct vm_page)) -
31143313Sbrian	    (end - new_end)) / PAGE_SIZE;
31296324Sbrian	end = new_end;
31343313Sbrian
31443313Sbrian	/*
31543313Sbrian	 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
31696324Sbrian	 */
31796324Sbrian	vaddr += PAGE_SIZE;
31843313Sbrian
31943313Sbrian	/*
32096324Sbrian	 * Initialize the mem entry structures now, and put them in the free
32143313Sbrian	 * queue.
32243313Sbrian	 */
32396153Sbrian	new_end = trunc_page(end - page_range * sizeof(struct vm_page));
32496153Sbrian	mapped = pmap_map(&vaddr, new_end, end,
32596153Sbrian	    VM_PROT_READ | VM_PROT_WRITE);
32696153Sbrian	vm_page_array = (vm_page_t) mapped;
32796324Sbrian#ifdef __amd64__
32896153Sbrian	/*
32996153Sbrian	 * pmap_map on amd64 comes out of the direct-map, not kvm like i386,
33096153Sbrian	 * so the pages must be tracked for a crashdump to include this data.
33196324Sbrian	 * This includes the vm_page_array and the early UMA bootstrap pages.
33296153Sbrian	 */
33396153Sbrian	for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
33496153Sbrian		dump_add_page(pa);
33596153Sbrian#endif
33696324Sbrian	phys_avail[biggestone + 1] = new_end;
33796153Sbrian
33896153Sbrian	/*
33943313Sbrian	 * Clear all of the page structures
34043313Sbrian	 */
34196324Sbrian	bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
34243313Sbrian	vm_page_array_size = page_range;
34343313Sbrian
34443313Sbrian	/*
34543313Sbrian	 * This assertion tests the hypothesis that npages and total are
34696324Sbrian	 * redundant.  XXX
34743313Sbrian	 */
34843313Sbrian	page_range = 0;
34943313Sbrian	for (i = 0; phys_avail[i + 1] != 0; i += 2)
35043313Sbrian		page_range += atop(phys_avail[i + 1] - phys_avail[i]);
35143313Sbrian	KASSERT(page_range == npages,
35243313Sbrian	    ("vm_page_startup: inconsistent page counts"));
35343313Sbrian
35443313Sbrian	/*
35543313Sbrian	 * Construct the free queue(s) in descending order (by physical
35643313Sbrian	 * address) so that the first 16MB of physical memory is allocated
35743313Sbrian	 * last rather than first.  On large-memory machines, this avoids
35896324Sbrian	 * the exhaustion of low physical memory before isa_dma_init has run.
35943313Sbrian	 */
36043313Sbrian	cnt.v_page_count = 0;
36143313Sbrian	cnt.v_free_count = 0;
36243313Sbrian	list = getenv("vm.blacklist");
36343313Sbrian	for (i = 0; phys_avail[i + 1] != 0; i += 2) {
36443313Sbrian		pa = phys_avail[i];
36543313Sbrian		last_pa = phys_avail[i + 1];
36643313Sbrian		while (pa < last_pa) {
36743313Sbrian			if (list != NULL &&
36843313Sbrian			    vm_page_blacklist_lookup(list, pa))
36943313Sbrian				printf("Skipping page with pa 0x%jx\n",
37043693Sbrian				    (uintmax_t)pa);
37196324Sbrian			else
37243693Sbrian				vm_pageq_add_new_page(pa);
37343693Sbrian			pa += PAGE_SIZE;
37443313Sbrian		}
37543313Sbrian	}
37696324Sbrian	freeenv(list);
37743693Sbrian	return (vaddr);
37881634Sbrian}
379116586Sume
38081634Sbrianvoid
38143313Sbrianvm_page_flag_set(vm_page_t m, unsigned short bits)
38254914Sbrian{
38354914Sbrian
38454914Sbrian	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
38554914Sbrian	m->flags |= bits;
38643313Sbrian}
38743313Sbrian
38843313Sbrianvoid
38981634Sbrianvm_page_flag_clear(vm_page_t m, unsigned short bits)
39081634Sbrian{
39143313Sbrian
39243313Sbrian	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
39343313Sbrian	m->flags &= ~bits;
39481634Sbrian}
39581634Sbrian
39643313Sbrianvoid
39781634Sbrianvm_page_busy(vm_page_t m)
39881634Sbrian{
39981634Sbrian
40043313Sbrian	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
40143313Sbrian	KASSERT((m->oflags & VPO_BUSY) == 0,
40243313Sbrian	    ("vm_page_busy: page already busy!!!"));
40343313Sbrian	m->oflags |= VPO_BUSY;
40443313Sbrian}
40543313Sbrian
40643313Sbrian/*
40781634Sbrian *      vm_page_flash:
40843313Sbrian *
40981634Sbrian *      wakeup anyone waiting for the page.
41043313Sbrian */
41143313Sbrianvoid
41243313Sbrianvm_page_flash(vm_page_t m)
41381634Sbrian{
41443313Sbrian
41543313Sbrian	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
41643313Sbrian	if (m->oflags & VPO_WANTED) {
41796324Sbrian		m->oflags &= ~VPO_WANTED;
41896324Sbrian		wakeup(m);
41996324Sbrian	}
42096324Sbrian}
42196324Sbrian
42296324Sbrian/*
42396324Sbrian *      vm_page_wakeup:
42496324Sbrian *
42596324Sbrian *      clear the VPO_BUSY flag and wakeup anyone waiting for the
42696324Sbrian *      page.
42796324Sbrian *
42896324Sbrian */
429116586Sumevoid
430116622Sumevm_page_wakeup(vm_page_t m)
431116622Sume{
432116622Sume
433116622Sume	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
434116622Sume	KASSERT(m->oflags & VPO_BUSY, ("vm_page_wakeup: page not busy!!!"));
435116622Sume	m->oflags &= ~VPO_BUSY;
436116622Sume	vm_page_flash(m);
437116586Sume}
438116586Sume
439116586Sumevoid
440116586Sumevm_page_io_start(vm_page_t m)
441116586Sume{
442116586Sume
443116586Sume	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
444116586Sume	m->busy++;
445116586Sume}
446116586Sume
447116586Sumevoid
448116586Sumevm_page_io_finish(vm_page_t m)
449116586Sume{
450116586Sume
451116586Sume	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
452116586Sume	m->busy--;
453116586Sume	if (m->busy == 0)
454116586Sume		vm_page_flash(m);
455116586Sume}
456116586Sume
457116586Sume/*
458116586Sume * Keep page from being freed by the page daemon
459116586Sume * much of the same effect as wiring, except much lower
460116586Sume * overhead and should be used only for *very* temporary
461116586Sume * holding ("wiring").
462116586Sume */
463116586Sumevoid
464116586Sumevm_page_hold(vm_page_t mem)
465116586Sume{
466116586Sume
467116586Sume	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
468116586Sume        mem->hold_count++;
469116586Sume}
470116586Sume
471116586Sumevoid
472116586Sumevm_page_unhold(vm_page_t mem)
473116586Sume{
474116586Sume
475116586Sume	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
476116586Sume	--mem->hold_count;
477116586Sume	KASSERT(mem->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!"));
478116586Sume	if (mem->hold_count == 0 && VM_PAGE_INQUEUE2(mem, PQ_HOLD))
479116586Sume		vm_page_free_toq(mem);
480116586Sume}
481116586Sume
482116586Sume/*
483116586Sume *	vm_page_free:
484116586Sume *
485116586Sume *	Free a page.
486116586Sume */
487116586Sumevoid
48896324Sbrianvm_page_free(vm_page_t m)
48996324Sbrian{
49096324Sbrian
49196324Sbrian	m->flags &= ~PG_ZERO;
49296324Sbrian	vm_page_free_toq(m);
49396324Sbrian}
49496324Sbrian
49596324Sbrian/*
49696324Sbrian *	vm_page_free_zero:
49796324Sbrian *
49896324Sbrian *	Free a page to the zerod-pages queue
49996324Sbrian */
50098132Sbrianvoid
50196324Sbrianvm_page_free_zero(vm_page_t m)
50296324Sbrian{
50398149Sbrian
50498149Sbrian	m->flags |= PG_ZERO;
50598149Sbrian	vm_page_free_toq(m);
50698712Sbrian}
50798712Sbrian
50898712Sbrian/*
50998712Sbrian *	vm_page_sleep:
51098712Sbrian *
51198712Sbrian *	Sleep and release the page queues lock.
51298712Sbrian *
51398967Sbrian *	The object containing the given page must be locked.
51498967Sbrian */
51598967Sbrianvoid
51698712Sbrianvm_page_sleep(vm_page_t m, const char *msg)
51798712Sbrian{
51898149Sbrian
51998149Sbrian	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
52098149Sbrian	if (!mtx_owned(&vm_page_queue_mtx))
52198149Sbrian		vm_page_lock_queues();
52298149Sbrian	vm_page_flag_set(m, PG_REFERENCED);
52398149Sbrian	vm_page_unlock_queues();
52498149Sbrian
52596324Sbrian	/*
52696324Sbrian	 * It's possible that while we sleep, the page will get
52796730Sbrian	 * unbusied and freed.  If we are holding the object
52896730Sbrian	 * lock, we will assume we hold a reference to the object
52996730Sbrian	 * such that even if m->object changes, we can re-lock
53098149Sbrian	 * it.
53198149Sbrian	 */
53298149Sbrian	m->oflags |= VPO_WANTED;
53398712Sbrian	msleep(m, VM_OBJECT_MTX(m->object), PVM, msg, 0);
53498712Sbrian}
53598712Sbrian
53698712Sbrian/*
53798712Sbrian *	vm_page_dirty:
53898712Sbrian *
53998712Sbrian *	make page all dirty
54098967Sbrian */
54198967Sbrianvoid
54298967Sbrianvm_page_dirty(vm_page_t m)
54398712Sbrian{
54498712Sbrian	KASSERT(VM_PAGE_GETKNOWNQUEUE1(m) != PQ_CACHE,
54598149Sbrian	    ("vm_page_dirty: page in cache!"));
54698149Sbrian	KASSERT(VM_PAGE_GETKNOWNQUEUE1(m) != PQ_FREE,
54798149Sbrian	    ("vm_page_dirty: page is free!"));
54898149Sbrian	m->dirty = VM_PAGE_BITS_ALL;
54998149Sbrian}
55098149Sbrian
55198149Sbrian/*
55298149Sbrian *	vm_page_splay:
55396730Sbrian *
55496730Sbrian *	Implements Sleator and Tarjan's top-down splay algorithm.  Returns
55598243Sbrian *	the vm_page containing the given pindex.  If, however, that
55698132Sbrian *	pindex is not found in the vm_object, returns a vm_page that is
55798132Sbrian *	adjacent to the pindex, coming before or after it.
55898132Sbrian */
55998132Sbrianvm_page_t
56098132Sbrianvm_page_splay(vm_pindex_t pindex, vm_page_t root)
56198132Sbrian{
56298132Sbrian	struct vm_page dummy;
56398132Sbrian	vm_page_t lefttreemax, righttreemin, y;
56498132Sbrian
56598132Sbrian	if (root == NULL)
56698132Sbrian		return (root);
56798132Sbrian	lefttreemax = righttreemin = &dummy;
56898132Sbrian	for (;; root = y) {
56998132Sbrian		if (pindex < root->pindex) {
57098132Sbrian			if ((y = root->left) == NULL)
57198132Sbrian				break;
57298132Sbrian			if (pindex < y->pindex) {
57398132Sbrian				/* Rotate right. */
57498132Sbrian				root->left = y->right;
57598132Sbrian				y->right = root;
57698132Sbrian				root = y;
57798132Sbrian				if ((y = root->left) == NULL)
57898132Sbrian					break;
57998132Sbrian			}
58096324Sbrian			/* Link into the new root's right tree. */
58196324Sbrian			righttreemin->left = root;
58296324Sbrian			righttreemin = root;
58396324Sbrian		} else if (pindex > root->pindex) {
58496324Sbrian			if ((y = root->right) == NULL)
58596324Sbrian				break;
58696324Sbrian			if (pindex > y->pindex) {
58796324Sbrian				/* Rotate left. */
58896324Sbrian				root->right = y->left;
58996324Sbrian				y->left = root;
59096324Sbrian				root = y;
59196324Sbrian				if ((y = root->right) == NULL)
59296324Sbrian					break;
59396324Sbrian			}
59496324Sbrian			/* Link into the new root's left tree. */
59596324Sbrian			lefttreemax->right = root;
59696324Sbrian			lefttreemax = root;
59743313Sbrian		} else
59843313Sbrian			break;
59943313Sbrian	}
60096324Sbrian	/* Assemble the new root. */
60143693Sbrian	lefttreemax->right = root->left;
60243693Sbrian	righttreemin->left = root->right;
60343693Sbrian	root->left = dummy.right;
60496324Sbrian	root->right = dummy.left;
60596324Sbrian	return (root);
60696324Sbrian}
60743693Sbrian
60843693Sbrian/*
60943313Sbrian *	vm_page_insert:		[ internal use only ]
61096324Sbrian *
61143693Sbrian *	Inserts the given mem entry into the object and object list.
61243313Sbrian *
61343693Sbrian *	The pagetables are not updated but will presumably fault the page
61458038Sbrian *	in if necessary, or if a kernel page the caller will at some point
61543693Sbrian *	enter the page into the kernel's pmap.  We are not allowed to block
61643693Sbrian *	here so we *can't* do this anyway.
61743693Sbrian *
61843693Sbrian *	The object and page must be locked.
61943693Sbrian *	This routine may not block.
62043693Sbrian */
62143313Sbrianvoid
62243693Sbrianvm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
62343693Sbrian{
62443693Sbrian	vm_page_t root;
62543693Sbrian
62643693Sbrian	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
62743693Sbrian	if (m->object != NULL)
62843693Sbrian		panic("vm_page_insert: page already inserted");
62943693Sbrian
63043693Sbrian	/*
63143313Sbrian	 * Record the object/offset pair in this page
63243313Sbrian	 */
63343693Sbrian	m->object = object;
63443693Sbrian	m->pindex = pindex;
63543693Sbrian
63643693Sbrian	/*
63743693Sbrian	 * Now link into the object's ordered list of backed pages.
63843693Sbrian	 */
63943693Sbrian	root = object->root;
64043693Sbrian	if (root == NULL) {
64143693Sbrian		m->left = NULL;
64243693Sbrian		m->right = NULL;
64343693Sbrian		TAILQ_INSERT_TAIL(&object->memq, m, listq);
64443693Sbrian	} else {
64543693Sbrian		root = vm_page_splay(pindex, root);
64658028Sbrian		if (pindex < root->pindex) {
64743693Sbrian			m->left = root->left;
64843693Sbrian			m->right = root;
64943693Sbrian			root->left = NULL;
65043693Sbrian			TAILQ_INSERT_BEFORE(root, m, listq);
65143693Sbrian		} else if (pindex == root->pindex)
65258038Sbrian			panic("vm_page_insert: offset already allocated");
65343693Sbrian		else {
65443693Sbrian			m->right = root->right;
65558028Sbrian			m->left = root;
65643693Sbrian			root->right = NULL;
65743693Sbrian			TAILQ_INSERT_AFTER(&object->memq, root, m, listq);
65843693Sbrian		}
65943693Sbrian	}
66043693Sbrian	object->root = m;
66143693Sbrian	object->generation++;
66243693Sbrian
66343693Sbrian	/*
66443693Sbrian	 * show that the object has one more resident page.
66543693Sbrian	 */
66643693Sbrian	object->resident_page_count++;
66743693Sbrian	/*
66843693Sbrian	 * Hold the vnode until the last page is released.
66943693Sbrian	 */
67043693Sbrian	if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
67158038Sbrian		vhold((struct vnode *)object->handle);
67243693Sbrian
67343693Sbrian	/*
67458028Sbrian	 * Since we are inserting a new and possibly dirty page,
67543693Sbrian	 * update the object's OBJ_MIGHTBEDIRTY flag.
67643693Sbrian	 */
67743693Sbrian	if (m->flags & PG_WRITEABLE)
67843693Sbrian		vm_object_set_writeable_dirty(object);
67943693Sbrian}
68043693Sbrian
68143693Sbrian/*
68258038Sbrian *	vm_page_remove:
68343693Sbrian *				NOTE: used by device pager as well -wfj
68443693Sbrian *
68558028Sbrian *	Removes the given mem entry from the object/offset-page
68643693Sbrian *	table and the object page list, but do not invalidate/terminate
68743693Sbrian *	the backing store.
68843693Sbrian *
68943693Sbrian *	The object and page must be locked.
69043693Sbrian *	The underlying pmap entry (if any) is NOT removed here.
69143693Sbrian *	This routine may not block.
69243693Sbrian */
69343693Sbrianvoid
69443693Sbrianvm_page_remove(vm_page_t m)
69543313Sbrian{
69643693Sbrian	vm_object_t object;
69743693Sbrian	vm_page_t root;
69843693Sbrian
69943693Sbrian	if ((object = m->object) == NULL)
70043693Sbrian		return;
70143693Sbrian	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
70243693Sbrian	if (m->oflags & VPO_BUSY) {
70396324Sbrian		m->oflags &= ~VPO_BUSY;
70496324Sbrian		vm_page_flash(m);
70543693Sbrian	}
70696324Sbrian	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
70796324Sbrian
70896324Sbrian	/*
70996324Sbrian	 * Now remove from the object's list of backed pages.
71096324Sbrian	 */
71196324Sbrian	if (m != object->root)
71296324Sbrian		vm_page_splay(m->pindex, object->root);
71396730Sbrian	if (m->left == NULL)
71496324Sbrian		root = m->right;
715116586Sume	else {
716116622Sume		root = vm_page_splay(m->pindex, m->left);
717116586Sume		root->right = m->right;
718116586Sume	}
71996324Sbrian	object->root = root;
72098132Sbrian	TAILQ_REMOVE(&object->memq, m, listq);
72198132Sbrian
72298132Sbrian	/*
72398132Sbrian	 * And show that the object has one fewer resident page.
72498132Sbrian	 */
72598132Sbrian	object->resident_page_count--;
72696324Sbrian	object->generation++;
72765178Sbrian	/*
72843693Sbrian	 * The vnode may now be recycled.
72943693Sbrian	 */
73043693Sbrian	if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
73143693Sbrian		vdrop((struct vnode *)object->handle);
73243693Sbrian
73343693Sbrian	m->object = NULL;
73443693Sbrian}
73543693Sbrian
73643693Sbrian/*
73765178Sbrian *	vm_page_lookup:
73843693Sbrian *
73943693Sbrian *	Returns the page associated with the object/offset
740116586Sume *	pair specified; if none is found, NULL is returned.
741116586Sume *
742116586Sume *	The object must be locked.
74396153Sbrian *	This routine may not block.
74496153Sbrian *	This is a critical path routine
74596730Sbrian */
74696730Sbrianvm_page_t
74796324Sbrianvm_page_lookup(vm_object_t object, vm_pindex_t pindex)
74896324Sbrian{
749116622Sume	vm_page_t m;
750116622Sume
751116622Sume	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
752116622Sume	if ((m = object->root) != NULL && m->pindex != pindex) {
75396324Sbrian		m = vm_page_splay(pindex, m);
75496324Sbrian		if ((object->root = m)->pindex != pindex)
75598132Sbrian			m = NULL;
75698132Sbrian	}
75798132Sbrian	return (m);
75898132Sbrian}
75998132Sbrian
76098132Sbrian/*
76143693Sbrian *	vm_page_rename:
76243693Sbrian *
76343693Sbrian *	Move the given memory entry from its
76443693Sbrian *	current object to the specified target object/offset.
76543693Sbrian *
76643693Sbrian *	The object must be locked.
76796582Sbrian *	This routine may not block.
76896582Sbrian *
76996582Sbrian *	Note: swap associated with the page must be invalidated by the move.  We
77096582Sbrian *	      have to do this for several reasons:  (1) we aren't freeing the
77196582Sbrian *	      page, (2) we are dirtying the page, (3) the VM system is probably
77296582Sbrian *	      moving the page from object A to B, and will then later move
77396582Sbrian *	      the backing store from A to B and we can't have a conflict.
77496582Sbrian *
77596582Sbrian *	Note: we *always* dirty the page.  It is necessary both for the
77696582Sbrian *	      fact that we moved it, and because we may be invalidating
77796582Sbrian *	      swap.  If the page is on the cache, we have to deactivate it
77896582Sbrian *	      or vm_page_dirty() will panic.  Dirty pages are not allowed
77996582Sbrian *	      on the cache.
78096582Sbrian */
78196582Sbrianvoid
78296582Sbrianvm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
78396582Sbrian{
78496582Sbrian
78596582Sbrian	vm_page_remove(m);
78696582Sbrian	vm_page_insert(m, new_object, new_pindex);
78796582Sbrian	if (VM_PAGE_INQUEUE1(m, PQ_CACHE))
78896582Sbrian		vm_page_deactivate(m);
78996582Sbrian	vm_page_dirty(m);
79096582Sbrian}
79196582Sbrian
79296582Sbrian/*
79396582Sbrian *	vm_page_select_cache:
79496582Sbrian *
79596582Sbrian *	Move a page of the given color from the cache queue to the free
79696582Sbrian *	queue.  As pages might be found, but are not applicable, they are
79796582Sbrian *	deactivated.
79896582Sbrian *
79996582Sbrian *	This routine may not block.
80096582Sbrian */
80196582Sbrianvm_page_t
80296582Sbrianvm_page_select_cache(int color)
80396582Sbrian{
80496582Sbrian	vm_object_t object;
80596582Sbrian	vm_page_t m;
80696582Sbrian	boolean_t was_trylocked;
80796582Sbrian
80896582Sbrian	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
80996582Sbrian	while ((m = vm_pageq_find(PQ_CACHE, color, FALSE)) != NULL) {
81096582Sbrian		KASSERT(m->dirty == 0, ("Found dirty cache page %p", m));
81196582Sbrian		KASSERT(!pmap_page_is_mapped(m),
81243693Sbrian		    ("Found mapped cache page %p", m));
81343693Sbrian		KASSERT((m->flags & PG_UNMANAGED) == 0,
81443693Sbrian		    ("Found unmanaged cache page %p", m));
81596730Sbrian		KASSERT(m->wire_count == 0, ("Found wired cache page %p", m));
81643693Sbrian		if (m->hold_count == 0 && (object = m->object,
81796730Sbrian		    (was_trylocked = VM_OBJECT_TRYLOCK(object)) ||
81898311Sbrian		    VM_OBJECT_LOCKED(object))) {
81943693Sbrian			KASSERT((m->oflags & VPO_BUSY) == 0 && m->busy == 0,
82043693Sbrian			    ("Found busy cache page %p", m));
82196582Sbrian			vm_page_free(m);
82274049Sbrian			if (was_trylocked)
82397738Sbrian				VM_OBJECT_UNLOCK(object);
82450840Sbrian			break;
82598132Sbrian		}
82697738Sbrian		vm_page_deactivate(m);
82796324Sbrian	}
82896730Sbrian	return (m);
82996730Sbrian}
83098311Sbrian
83196324Sbrian/*
83243693Sbrian *	vm_page_alloc:
83343693Sbrian *
83496730Sbrian *	Allocate and return a memory cell associated
83543693Sbrian *	with this VM object/offset pair.
83643693Sbrian *
83743693Sbrian *	page_req classes:
83843693Sbrian *	VM_ALLOC_NORMAL		normal process request
83943693Sbrian *	VM_ALLOC_SYSTEM		system *really* needs a page
84043693Sbrian *	VM_ALLOC_INTERRUPT	interrupt time request
84196730Sbrian *	VM_ALLOC_ZERO		zero page
84243693Sbrian *
84343693Sbrian *	This routine may not block.
84443693Sbrian *
84565178Sbrian *	Additional special handling is required when called from an
84665178Sbrian *	interrupt (VM_ALLOC_INTERRUPT).  We are not allowed to mess with
84796730Sbrian *	the page cache in this case.
84843693Sbrian */
84943693Sbrianvm_page_t
85043693Sbrianvm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
85143693Sbrian{
85243693Sbrian	vm_page_t m = NULL;
85396730Sbrian	int color, flags, page_req;
85443693Sbrian
85543693Sbrian	page_req = req & VM_ALLOC_CLASS_MASK;
85643693Sbrian	KASSERT(curthread->td_intr_nesting_level == 0 ||
85743693Sbrian	    page_req == VM_ALLOC_INTERRUPT,
85843693Sbrian	    ("vm_page_alloc(NORMAL|SYSTEM) in interrupt context"));
85996730Sbrian
86043693Sbrian	if ((req & VM_ALLOC_NOOBJ) == 0) {
86143693Sbrian		KASSERT(object != NULL,
86299418Sbrian		    ("vm_page_alloc: NULL object."));
86343693Sbrian		VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
86443693Sbrian		color = (pindex + object->pg_color) & PQ_COLORMASK;
86543693Sbrian	} else
86643693Sbrian		color = pindex & PQ_COLORMASK;
86796730Sbrian
86843693Sbrian	/*
86943693Sbrian	 * The pager is allowed to eat deeper into the free page list.
87096324Sbrian	 */
87196324Sbrian	if ((curproc == pageproc) && (page_req != VM_ALLOC_INTERRUPT)) {
87296324Sbrian		page_req = VM_ALLOC_SYSTEM;
87396324Sbrian	};
87496324Sbrian
87543693Sbrianloop:
87643693Sbrian	mtx_lock(&vm_page_queue_free_mtx);
87796730Sbrian	if (cnt.v_free_count > cnt.v_free_reserved ||
87843693Sbrian	    (page_req == VM_ALLOC_SYSTEM &&
87996324Sbrian	     cnt.v_cache_count == 0 &&
88096324Sbrian	     cnt.v_free_count > cnt.v_interrupt_free_min) ||
88196324Sbrian	    (page_req == VM_ALLOC_INTERRUPT && cnt.v_free_count > 0)) {
88296324Sbrian		/*
88396324Sbrian		 * Allocate from the free queue if the number of free pages
88496324Sbrian		 * exceeds the minimum for the request class.
88596730Sbrian		 */
88696324Sbrian		m = vm_pageq_find(PQ_FREE, color, (req & VM_ALLOC_ZERO) != 0);
88796324Sbrian	} else if (page_req != VM_ALLOC_INTERRUPT) {
88896324Sbrian		mtx_unlock(&vm_page_queue_free_mtx);
88996730Sbrian		/*
89096324Sbrian		 * Allocatable from cache (non-interrupt only).  On success,
89196324Sbrian		 * we must free the page and try again, thus ensuring that
89296324Sbrian		 * cnt.v_*_free_min counters are replenished.
89396324Sbrian		 */
89496324Sbrian		vm_page_lock_queues();
89596324Sbrian		if ((m = vm_page_select_cache(color)) == NULL) {
89696730Sbrian			KASSERT(cnt.v_cache_count == 0,
89796324Sbrian			    ("vm_page_alloc: cache queue is missing %d pages",
89896730Sbrian			    cnt.v_cache_count));
89996324Sbrian			vm_page_unlock_queues();
90096730Sbrian			atomic_add_int(&vm_pageout_deficit, 1);
90196324Sbrian			pagedaemon_wakeup();
90296730Sbrian
90396730Sbrian			if (page_req != VM_ALLOC_SYSTEM)
90496730Sbrian				return (NULL);
90596730Sbrian
90696730Sbrian			mtx_lock(&vm_page_queue_free_mtx);
90796324Sbrian			if (cnt.v_free_count <= cnt.v_interrupt_free_min) {
90896730Sbrian				mtx_unlock(&vm_page_queue_free_mtx);
90996730Sbrian				return (NULL);
91096324Sbrian			}
91196324Sbrian			m = vm_pageq_find(PQ_FREE, color, (req & VM_ALLOC_ZERO) != 0);
91296324Sbrian		} else {
91398311Sbrian			vm_page_unlock_queues();
91496730Sbrian			goto loop;
91596730Sbrian		}
91696730Sbrian	} else {
91796730Sbrian		/*
91896730Sbrian		 * Not allocatable from cache from interrupt, give up.
91998311Sbrian		 */
92096730Sbrian		mtx_unlock(&vm_page_queue_free_mtx);
92196730Sbrian		atomic_add_int(&vm_pageout_deficit, 1);
92296730Sbrian		pagedaemon_wakeup();
92398311Sbrian		return (NULL);
92498311Sbrian	}
92596730Sbrian
92698311Sbrian	/*
92798311Sbrian	 *  At this point we had better have found a good page.
92896730Sbrian	 */
92996730Sbrian
93096730Sbrian	KASSERT(
93196730Sbrian	    m != NULL,
93296324Sbrian	    ("vm_page_alloc(): missing page on free queue")
93396324Sbrian	);
93498243Sbrian
93596324Sbrian	/*
93696324Sbrian	 * Remove from free queue
93796730Sbrian	 */
93896324Sbrian	vm_pageq_remove_nowakeup(m);
93943693Sbrian
94043693Sbrian	/*
94150840Sbrian	 * Initialize structure.  Only the PG_ZERO flag is inherited.
94250840Sbrian	 */
94350840Sbrian	flags = 0;
94497738Sbrian	if (m->flags & PG_ZERO) {
94550840Sbrian		vm_page_zero_count--;
94650840Sbrian		if (req & VM_ALLOC_ZERO)
94750840Sbrian			flags = PG_ZERO;
94850840Sbrian	}
94950840Sbrian	if (object != NULL && object->type == OBJT_PHYS)
95050840Sbrian		flags |= PG_UNMANAGED;
95196730Sbrian	m->flags = flags;
95250840Sbrian	if (req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ))
95350840Sbrian		m->oflags = 0;
95497738Sbrian	else
95550840Sbrian		m->oflags = VPO_BUSY;
95650840Sbrian	if (req & VM_ALLOC_WIRED) {
95750840Sbrian		atomic_add_int(&cnt.v_wire_count, 1);
95850840Sbrian		m->wire_count = 1;
95996730Sbrian	} else
96050840Sbrian		m->wire_count = 0;
96150840Sbrian	m->hold_count = 0;
96250840Sbrian	m->act_count = 0;
96396582Sbrian	m->busy = 0;
96450840Sbrian	m->valid = 0;
96571972Sbrian	KASSERT(m->dirty == 0, ("vm_page_alloc: free/cache page %p was dirty", m));
96643693Sbrian	mtx_unlock(&vm_page_queue_free_mtx);
96743693Sbrian
96843693Sbrian	if ((req & VM_ALLOC_NOOBJ) == 0)
96943693Sbrian		vm_page_insert(m, object, pindex);
97043693Sbrian	else
97143693Sbrian		m->pindex = pindex;
97243693Sbrian
97371972Sbrian	/*
97443693Sbrian	 * Don't wakeup too often - wakeup the pageout daemon when
97543693Sbrian	 * we would be nearly out of memory.
97643693Sbrian	 */
97796730Sbrian	if (vm_paging_needed())
97896730Sbrian		pagedaemon_wakeup();
97943693Sbrian
98043693Sbrian	return (m);
981116588Sume}
982116588Sume
983116588Sume/*
984116588Sume *	vm_wait:	(also see VM_WAIT macro)
985116588Sume *
986116588Sume *	Block until free pages are available for allocation
987116588Sume *	- Called in various places before memory allocations.
988116588Sume */
989116588Sumevoid
990116588Sumevm_wait(void)
991116588Sume{
992116588Sume
993116588Sume	mtx_lock(&vm_page_queue_free_mtx);
994116588Sume	if (curproc == pageproc) {
995116588Sume		vm_pageout_pages_needed = 1;
996116588Sume		msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
997116588Sume		    PDROP | PSWP, "VMWait", 0);
998116588Sume	} else {
999116588Sume		if (!vm_pages_needed) {
1000116588Sume			vm_pages_needed = 1;
100143693Sbrian			wakeup(&vm_pages_needed);
100265178Sbrian		}
100365178Sbrian		msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
100465178Sbrian		    "vmwait", 0);
100598243Sbrian	}
1006116588Sume}
100765178Sbrian
100865178Sbrian/*
100996582Sbrian *	vm_waitpfault:	(also see VM_WAITPFAULT macro)
101074049Sbrian *
101197738Sbrian *	Block until free pages are available for allocation
101265178Sbrian *	- Called only in vm_fault so that processes page faulting
101398132Sbrian *	  can be easily tracked.
101497738Sbrian *	- Sleeps at a lower priority than vm_wait() so that vm_wait()ing
101565178Sbrian *	  processes will be able to grab memory first.  Do not change
101665178Sbrian *	  this balance without careful testing first.
101765178Sbrian */
101865178Sbrianvoid
101965178Sbrianvm_waitpfault(void)
102065178Sbrian{
102165178Sbrian
102265178Sbrian	mtx_lock(&vm_page_queue_free_mtx);
102365178Sbrian	if (!vm_pages_needed) {
102465178Sbrian		vm_pages_needed = 1;
102565178Sbrian		wakeup(&vm_pages_needed);
102698132Sbrian	}
102765178Sbrian	msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
102867133Sbrian	    "pfault", 0);
102965178Sbrian}
103065178Sbrian
103165178Sbrian/*
103265178Sbrian *	vm_page_activate:
103365178Sbrian *
103465178Sbrian *	Put the specified page on the active list (if appropriate).
103565178Sbrian *	Ensure that act_count is at least ACT_INIT but do not otherwise
103665178Sbrian *	mess with it.
103765178Sbrian *
103865178Sbrian *	The page queues must be locked.
103965178Sbrian *	This routine may not block.
104065178Sbrian */
104165178Sbrianvoid
104265178Sbrianvm_page_activate(vm_page_t m)
104365178Sbrian{
104465178Sbrian
104565178Sbrian	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
104665178Sbrian	if (VM_PAGE_GETKNOWNQUEUE2(m) != PQ_ACTIVE) {
104765178Sbrian		if (VM_PAGE_INQUEUE1(m, PQ_CACHE))
104865178Sbrian			PCPU_INC(cnt.v_reactivated);
104999418Sbrian		vm_pageq_remove(m);
105065178Sbrian		if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
105165178Sbrian			if (m->act_count < ACT_INIT)
105265178Sbrian				m->act_count = ACT_INIT;
105398243Sbrian			vm_pageq_enqueue(PQ_ACTIVE, m);
105465178Sbrian		}
105597904Sbrian	} else {
105697904Sbrian		if (m->act_count < ACT_INIT)
105799418Sbrian			m->act_count = ACT_INIT;
105865178Sbrian	}
105965178Sbrian}
106065178Sbrian
106165178Sbrian/*
106265178Sbrian *	vm_page_free_wakeup:
106365178Sbrian *
106465178Sbrian *	Helper routine for vm_page_free_toq() and vm_page_cache().  This
106565178Sbrian *	routine is called when a page has been added to the cache or free
106665178Sbrian *	queues.
1067116588Sume *
106865178Sbrian *	The page queues must be locked.
106965178Sbrian *	This routine may not block.
107065178Sbrian */
107165178Sbrianstatic inline void
1072116588Sumevm_page_free_wakeup(void)
1073116588Sume{
1074116588Sume
1075116588Sume	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1076116588Sume	/*
1077116588Sume	 * if pageout daemon needs pages, then tell it that there are
1078116588Sume	 * some free.
1079116588Sume	 */
1080116588Sume	if (vm_pageout_pages_needed &&
1081116588Sume	    cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
1082116588Sume		wakeup(&vm_pageout_pages_needed);
1083116588Sume		vm_pageout_pages_needed = 0;
1084116588Sume	}
1085116588Sume	/*
1086116588Sume	 * wakeup processes that are waiting on memory if we hit a
1087116588Sume	 * high water mark. And wakeup scheduler process if we have
1088116588Sume	 * lots of memory. this process will swapin processes.
1089116622Sume	 */
1090116622Sume	if (vm_pages_needed && !vm_page_count_min()) {
1091116622Sume		vm_pages_needed = 0;
1092116622Sume		wakeup(&cnt.v_free_count);
1093116622Sume	}
1094116622Sume}
1095116622Sume
1096116622Sume/*
1097116622Sume *	vm_page_free_toq:
1098116622Sume *
1099116622Sume *	Returns the given page to the PQ_FREE list,
1100116622Sume *	disassociating it with any VM object.
1101116588Sume *
1102116588Sume *	Object and page must be locked prior to entry.
1103116588Sume *	This routine may not block.
1104116588Sume */
1105116588Sume
1106116588Sumevoid
110765178Sbrianvm_page_free_toq(vm_page_t m)
110865178Sbrian{
110965178Sbrian	struct vpgqueues *pq;
111065178Sbrian
111197738Sbrian	if (VM_PAGE_GETQUEUE(m) != PQ_NONE)
111265178Sbrian		mtx_assert(&vm_page_queue_mtx, MA_OWNED);
111365178Sbrian	KASSERT(!pmap_page_is_mapped(m),
111465178Sbrian	    ("vm_page_free_toq: freeing mapped page %p", m));
111565178Sbrian	PCPU_INC(cnt.v_tfree);
111665178Sbrian
111765178Sbrian	if (m->busy || VM_PAGE_INQUEUE1(m, PQ_FREE)) {
111865178Sbrian		printf(
111965178Sbrian		"vm_page_free: pindex(%lu), busy(%d), VPO_BUSY(%d), hold(%d)\n",
112065178Sbrian		    (u_long)m->pindex, m->busy, (m->oflags & VPO_BUSY) ? 1 : 0,
112197738Sbrian		    m->hold_count);
112265178Sbrian		if (VM_PAGE_INQUEUE1(m, PQ_FREE))
112365178Sbrian			panic("vm_page_free: freeing free page");
112465178Sbrian		else
112565178Sbrian			panic("vm_page_free: freeing busy page");
112665178Sbrian	}
112765178Sbrian
112865178Sbrian	/*
112965178Sbrian	 * unqueue, then remove page.  Note that we cannot destroy
113096582Sbrian	 * the page here because we do not want to call the pager's
113165178Sbrian	 * callback routine until after we've put the page on the
113265178Sbrian	 * appropriate free queue.
113398243Sbrian	 */
113465178Sbrian	vm_pageq_remove_nowakeup(m);
113565178Sbrian	vm_page_remove(m);
113698243Sbrian
113765178Sbrian	/*
113865178Sbrian	 * If fictitious remove object association and
113965178Sbrian	 * return, otherwise delay object association removal.
114065178Sbrian	 */
114165178Sbrian	if ((m->flags & PG_FICTITIOUS) != 0) {
114265178Sbrian		return;
114365178Sbrian	}
114465178Sbrian
114565178Sbrian	m->valid = 0;
114665178Sbrian	vm_page_undirty(m);
114765178Sbrian
114865178Sbrian	if (m->wire_count != 0) {
114965178Sbrian		if (m->wire_count > 1) {
115065178Sbrian			panic("vm_page_free: invalid wire count (%d), pindex: 0x%lx",
115165178Sbrian				m->wire_count, (long)m->pindex);
115265178Sbrian		}
115365178Sbrian		panic("vm_page_free: freeing wired page");
115465178Sbrian	}
115565178Sbrian	if (m->hold_count != 0) {
115665178Sbrian		m->flags &= ~PG_ZERO;
115771972Sbrian		vm_pageq_enqueue(PQ_HOLD, m);
115865178Sbrian		return;
115965178Sbrian	}
116065178Sbrian	VM_PAGE_SETQUEUE1(m, PQ_FREE);
116165178Sbrian	mtx_lock(&vm_page_queue_free_mtx);
116265178Sbrian	pq = &vm_page_queues[VM_PAGE_GETQUEUE(m)];
116365178Sbrian	pq->lcnt++;
116471972Sbrian	++(*pq->cnt);
116565178Sbrian
116665178Sbrian	/*
116765178Sbrian	 * Put zero'd pages on the end ( where we look for zero'd pages
116865178Sbrian	 * first ) and non-zerod pages at the head.
116965178Sbrian	 */
117065178Sbrian	if (m->flags & PG_ZERO) {
117143693Sbrian		TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
117243693Sbrian		++vm_page_zero_count;
117343693Sbrian	} else {
117443313Sbrian		TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
117543313Sbrian		vm_page_zero_idle_wakeup();
117671657Sbrian	}
117771657Sbrian	vm_page_free_wakeup();
117843313Sbrian	mtx_unlock(&vm_page_queue_free_mtx);
117971657Sbrian}
118071657Sbrian
118171657Sbrian/*
118271657Sbrian *	vm_page_wire:
118396324Sbrian *
118498132Sbrian *	Mark this page as wired down by yet
118598132Sbrian *	another map, removing it from paging queues
118698132Sbrian *	as necessary.
118798132Sbrian *
118898132Sbrian *	The page queues must be locked.
118998132Sbrian *	This routine may not block.
119098132Sbrian */
119198132Sbrianvoid
119296730Sbrianvm_page_wire(vm_page_t m)
119396730Sbrian{
119496324Sbrian
119543313Sbrian	/*
119671657Sbrian	 * Only bump the wire statistics if the page is not already wired,
1197116586Sume	 * and only unqueue the page if it is on some queue (if it is unmanaged
1198116586Sume	 * it is already off the queues).
1199116586Sume	 */
1200116586Sume	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
120143313Sbrian	if (m->flags & PG_FICTITIOUS)
120243313Sbrian		return;
120343313Sbrian	if (m->wire_count == 0) {
1204		if ((m->flags & PG_UNMANAGED) == 0)
1205			vm_pageq_remove(m);
1206		atomic_add_int(&cnt.v_wire_count, 1);
1207	}
1208	m->wire_count++;
1209	KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
1210}
1211
1212/*
1213 *	vm_page_unwire:
1214 *
1215 *	Release one wiring of this page, potentially
1216 *	enabling it to be paged again.
1217 *
1218 *	Many pages placed on the inactive queue should actually go
1219 *	into the cache, but it is difficult to figure out which.  What
1220 *	we do instead, if the inactive target is well met, is to put
1221 *	clean pages at the head of the inactive queue instead of the tail.
1222 *	This will cause them to be moved to the cache more quickly and
1223 *	if not actively re-referenced, freed more quickly.  If we just
1224 *	stick these pages at the end of the inactive queue, heavy filesystem
1225 *	meta-data accesses can cause an unnecessary paging load on memory bound
1226 *	processes.  This optimization causes one-time-use metadata to be
1227 *	reused more quickly.
1228 *
1229 *	BUT, if we are in a low-memory situation we have no choice but to
1230 *	put clean pages on the cache queue.
1231 *
1232 *	A number of routines use vm_page_unwire() to guarantee that the page
1233 *	will go into either the inactive or active queues, and will NEVER
1234 *	be placed in the cache - for example, just after dirtying a page.
1235 *	dirty pages in the cache are not allowed.
1236 *
1237 *	The page queues must be locked.
1238 *	This routine may not block.
1239 */
1240void
1241vm_page_unwire(vm_page_t m, int activate)
1242{
1243
1244	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1245	if (m->flags & PG_FICTITIOUS)
1246		return;
1247	if (m->wire_count > 0) {
1248		m->wire_count--;
1249		if (m->wire_count == 0) {
1250			atomic_subtract_int(&cnt.v_wire_count, 1);
1251			if (m->flags & PG_UNMANAGED) {
1252				;
1253			} else if (activate)
1254				vm_pageq_enqueue(PQ_ACTIVE, m);
1255			else {
1256				vm_page_flag_clear(m, PG_WINATCFLS);
1257				vm_pageq_enqueue(PQ_INACTIVE, m);
1258			}
1259		}
1260	} else {
1261		panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
1262	}
1263}
1264
1265
1266/*
1267 * Move the specified page to the inactive queue.  If the page has
1268 * any associated swap, the swap is deallocated.
1269 *
1270 * Normally athead is 0 resulting in LRU operation.  athead is set
1271 * to 1 if we want this page to be 'as if it were placed in the cache',
1272 * except without unmapping it from the process address space.
1273 *
1274 * This routine may not block.
1275 */
1276static inline void
1277_vm_page_deactivate(vm_page_t m, int athead)
1278{
1279
1280	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1281
1282	/*
1283	 * Ignore if already inactive.
1284	 */
1285	if (VM_PAGE_INQUEUE2(m, PQ_INACTIVE))
1286		return;
1287	if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1288		if (VM_PAGE_INQUEUE1(m, PQ_CACHE))
1289			PCPU_INC(cnt.v_reactivated);
1290		vm_page_flag_clear(m, PG_WINATCFLS);
1291		vm_pageq_remove(m);
1292		if (athead)
1293			TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1294		else
1295			TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1296		VM_PAGE_SETQUEUE2(m, PQ_INACTIVE);
1297		vm_page_queues[PQ_INACTIVE].lcnt++;
1298
1299		/*
1300		 * Just not use an atomic here since vm_page_queues_lock
1301		 * alredy protects this field.
1302		 */
1303		cnt.v_inactive_count++;
1304	}
1305}
1306
1307void
1308vm_page_deactivate(vm_page_t m)
1309{
1310    _vm_page_deactivate(m, 0);
1311}
1312
1313/*
1314 * vm_page_try_to_cache:
1315 *
1316 * Returns 0 on failure, 1 on success
1317 */
1318int
1319vm_page_try_to_cache(vm_page_t m)
1320{
1321
1322	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1323	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1324	if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1325	    (m->oflags & VPO_BUSY) || (m->flags & PG_UNMANAGED)) {
1326		return (0);
1327	}
1328	pmap_remove_all(m);
1329	if (m->dirty)
1330		return (0);
1331	vm_page_cache(m);
1332	return (1);
1333}
1334
1335/*
1336 * vm_page_try_to_free()
1337 *
1338 *	Attempt to free the page.  If we cannot free it, we do nothing.
1339 *	1 is returned on success, 0 on failure.
1340 */
1341int
1342vm_page_try_to_free(vm_page_t m)
1343{
1344
1345	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1346	if (m->object != NULL)
1347		VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1348	if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1349	    (m->oflags & VPO_BUSY) || (m->flags & PG_UNMANAGED)) {
1350		return (0);
1351	}
1352	pmap_remove_all(m);
1353	if (m->dirty)
1354		return (0);
1355	vm_page_free(m);
1356	return (1);
1357}
1358
1359/*
1360 * vm_page_cache
1361 *
1362 * Put the specified page onto the page cache queue (if appropriate).
1363 *
1364 * This routine may not block.
1365 */
1366void
1367vm_page_cache(vm_page_t m)
1368{
1369
1370	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1371	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1372	if ((m->flags & PG_UNMANAGED) || (m->oflags & VPO_BUSY) || m->busy ||
1373	    m->hold_count || m->wire_count) {
1374		printf("vm_page_cache: attempting to cache busy page\n");
1375		return;
1376	}
1377	if (VM_PAGE_INQUEUE1(m, PQ_CACHE))
1378		return;
1379
1380	/*
1381	 * Remove all pmaps and indicate that the page is not
1382	 * writeable or mapped.
1383	 */
1384	pmap_remove_all(m);
1385	if (m->dirty != 0) {
1386		panic("vm_page_cache: caching a dirty page, pindex: %ld",
1387			(long)m->pindex);
1388	}
1389	vm_pageq_remove_nowakeup(m);
1390	vm_pageq_enqueue(PQ_CACHE + m->pc, m);
1391	mtx_lock(&vm_page_queue_free_mtx);
1392	vm_page_free_wakeup();
1393	mtx_unlock(&vm_page_queue_free_mtx);
1394}
1395
1396/*
1397 * vm_page_dontneed
1398 *
1399 *	Cache, deactivate, or do nothing as appropriate.  This routine
1400 *	is typically used by madvise() MADV_DONTNEED.
1401 *
1402 *	Generally speaking we want to move the page into the cache so
1403 *	it gets reused quickly.  However, this can result in a silly syndrome
1404 *	due to the page recycling too quickly.  Small objects will not be
1405 *	fully cached.  On the otherhand, if we move the page to the inactive
1406 *	queue we wind up with a problem whereby very large objects
1407 *	unnecessarily blow away our inactive and cache queues.
1408 *
1409 *	The solution is to move the pages based on a fixed weighting.  We
1410 *	either leave them alone, deactivate them, or move them to the cache,
1411 *	where moving them to the cache has the highest weighting.
1412 *	By forcing some pages into other queues we eventually force the
1413 *	system to balance the queues, potentially recovering other unrelated
1414 *	space from active.  The idea is to not force this to happen too
1415 *	often.
1416 */
1417void
1418vm_page_dontneed(vm_page_t m)
1419{
1420	static int dnweight;
1421	int dnw;
1422	int head;
1423
1424	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1425	dnw = ++dnweight;
1426
1427	/*
1428	 * occassionally leave the page alone
1429	 */
1430	if ((dnw & 0x01F0) == 0 ||
1431	    VM_PAGE_INQUEUE2(m, PQ_INACTIVE) ||
1432	    VM_PAGE_INQUEUE1(m, PQ_CACHE)
1433	) {
1434		if (m->act_count >= ACT_INIT)
1435			--m->act_count;
1436		return;
1437	}
1438
1439	if (m->dirty == 0 && pmap_is_modified(m))
1440		vm_page_dirty(m);
1441
1442	if (m->dirty || (dnw & 0x0070) == 0) {
1443		/*
1444		 * Deactivate the page 3 times out of 32.
1445		 */
1446		head = 0;
1447	} else {
1448		/*
1449		 * Cache the page 28 times out of every 32.  Note that
1450		 * the page is deactivated instead of cached, but placed
1451		 * at the head of the queue instead of the tail.
1452		 */
1453		head = 1;
1454	}
1455	_vm_page_deactivate(m, head);
1456}
1457
1458/*
1459 * Grab a page, waiting until we are waken up due to the page
1460 * changing state.  We keep on waiting, if the page continues
1461 * to be in the object.  If the page doesn't exist, first allocate it
1462 * and then conditionally zero it.
1463 *
1464 * This routine may block.
1465 */
1466vm_page_t
1467vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
1468{
1469	vm_page_t m;
1470
1471	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1472retrylookup:
1473	if ((m = vm_page_lookup(object, pindex)) != NULL) {
1474		if (vm_page_sleep_if_busy(m, TRUE, "pgrbwt")) {
1475			if ((allocflags & VM_ALLOC_RETRY) == 0)
1476				return (NULL);
1477			goto retrylookup;
1478		} else {
1479			if ((allocflags & VM_ALLOC_WIRED) != 0) {
1480				vm_page_lock_queues();
1481				vm_page_wire(m);
1482				vm_page_unlock_queues();
1483			}
1484			if ((allocflags & VM_ALLOC_NOBUSY) == 0)
1485				vm_page_busy(m);
1486			return (m);
1487		}
1488	}
1489	m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_RETRY);
1490	if (m == NULL) {
1491		VM_OBJECT_UNLOCK(object);
1492		VM_WAIT;
1493		VM_OBJECT_LOCK(object);
1494		if ((allocflags & VM_ALLOC_RETRY) == 0)
1495			return (NULL);
1496		goto retrylookup;
1497	}
1498	if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
1499		pmap_zero_page(m);
1500	return (m);
1501}
1502
1503/*
1504 * Mapping function for valid bits or for dirty bits in
1505 * a page.  May not block.
1506 *
1507 * Inputs are required to range within a page.
1508 */
1509inline int
1510vm_page_bits(int base, int size)
1511{
1512	int first_bit;
1513	int last_bit;
1514
1515	KASSERT(
1516	    base + size <= PAGE_SIZE,
1517	    ("vm_page_bits: illegal base/size %d/%d", base, size)
1518	);
1519
1520	if (size == 0)		/* handle degenerate case */
1521		return (0);
1522
1523	first_bit = base >> DEV_BSHIFT;
1524	last_bit = (base + size - 1) >> DEV_BSHIFT;
1525
1526	return ((2 << last_bit) - (1 << first_bit));
1527}
1528
1529/*
1530 *	vm_page_set_validclean:
1531 *
1532 *	Sets portions of a page valid and clean.  The arguments are expected
1533 *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
1534 *	of any partial chunks touched by the range.  The invalid portion of
1535 *	such chunks will be zero'd.
1536 *
1537 *	This routine may not block.
1538 *
1539 *	(base + size) must be less then or equal to PAGE_SIZE.
1540 */
1541void
1542vm_page_set_validclean(vm_page_t m, int base, int size)
1543{
1544	int pagebits;
1545	int frag;
1546	int endoff;
1547
1548	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1549	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1550	if (size == 0)	/* handle degenerate case */
1551		return;
1552
1553	/*
1554	 * If the base is not DEV_BSIZE aligned and the valid
1555	 * bit is clear, we have to zero out a portion of the
1556	 * first block.
1557	 */
1558	if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
1559	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
1560		pmap_zero_page_area(m, frag, base - frag);
1561
1562	/*
1563	 * If the ending offset is not DEV_BSIZE aligned and the
1564	 * valid bit is clear, we have to zero out a portion of
1565	 * the last block.
1566	 */
1567	endoff = base + size;
1568	if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
1569	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
1570		pmap_zero_page_area(m, endoff,
1571		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
1572
1573	/*
1574	 * Set valid, clear dirty bits.  If validating the entire
1575	 * page we can safely clear the pmap modify bit.  We also
1576	 * use this opportunity to clear the VPO_NOSYNC flag.  If a process
1577	 * takes a write fault on a MAP_NOSYNC memory area the flag will
1578	 * be set again.
1579	 *
1580	 * We set valid bits inclusive of any overlap, but we can only
1581	 * clear dirty bits for DEV_BSIZE chunks that are fully within
1582	 * the range.
1583	 */
1584	pagebits = vm_page_bits(base, size);
1585	m->valid |= pagebits;
1586#if 0	/* NOT YET */
1587	if ((frag = base & (DEV_BSIZE - 1)) != 0) {
1588		frag = DEV_BSIZE - frag;
1589		base += frag;
1590		size -= frag;
1591		if (size < 0)
1592			size = 0;
1593	}
1594	pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
1595#endif
1596	m->dirty &= ~pagebits;
1597	if (base == 0 && size == PAGE_SIZE) {
1598		pmap_clear_modify(m);
1599		m->oflags &= ~VPO_NOSYNC;
1600	}
1601}
1602
1603void
1604vm_page_clear_dirty(vm_page_t m, int base, int size)
1605{
1606
1607	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1608	m->dirty &= ~vm_page_bits(base, size);
1609}
1610
1611/*
1612 *	vm_page_set_invalid:
1613 *
1614 *	Invalidates DEV_BSIZE'd chunks within a page.  Both the
1615 *	valid and dirty bits for the effected areas are cleared.
1616 *
1617 *	May not block.
1618 */
1619void
1620vm_page_set_invalid(vm_page_t m, int base, int size)
1621{
1622	int bits;
1623
1624	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1625	bits = vm_page_bits(base, size);
1626	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1627	if (m->valid == VM_PAGE_BITS_ALL && bits != 0)
1628		pmap_remove_all(m);
1629	m->valid &= ~bits;
1630	m->dirty &= ~bits;
1631	m->object->generation++;
1632}
1633
1634/*
1635 * vm_page_zero_invalid()
1636 *
1637 *	The kernel assumes that the invalid portions of a page contain
1638 *	garbage, but such pages can be mapped into memory by user code.
1639 *	When this occurs, we must zero out the non-valid portions of the
1640 *	page so user code sees what it expects.
1641 *
1642 *	Pages are most often semi-valid when the end of a file is mapped
1643 *	into memory and the file's size is not page aligned.
1644 */
1645void
1646vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
1647{
1648	int b;
1649	int i;
1650
1651	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1652	/*
1653	 * Scan the valid bits looking for invalid sections that
1654	 * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
1655	 * valid bit may be set ) have already been zerod by
1656	 * vm_page_set_validclean().
1657	 */
1658	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
1659		if (i == (PAGE_SIZE / DEV_BSIZE) ||
1660		    (m->valid & (1 << i))
1661		) {
1662			if (i > b) {
1663				pmap_zero_page_area(m,
1664				    b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
1665			}
1666			b = i + 1;
1667		}
1668	}
1669
1670	/*
1671	 * setvalid is TRUE when we can safely set the zero'd areas
1672	 * as being valid.  We can do this if there are no cache consistancy
1673	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
1674	 */
1675	if (setvalid)
1676		m->valid = VM_PAGE_BITS_ALL;
1677}
1678
1679/*
1680 *	vm_page_is_valid:
1681 *
1682 *	Is (partial) page valid?  Note that the case where size == 0
1683 *	will return FALSE in the degenerate case where the page is
1684 *	entirely invalid, and TRUE otherwise.
1685 *
1686 *	May not block.
1687 */
1688int
1689vm_page_is_valid(vm_page_t m, int base, int size)
1690{
1691	int bits = vm_page_bits(base, size);
1692
1693	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1694	if (m->valid && ((m->valid & bits) == bits))
1695		return 1;
1696	else
1697		return 0;
1698}
1699
1700/*
1701 * update dirty bits from pmap/mmu.  May not block.
1702 */
1703void
1704vm_page_test_dirty(vm_page_t m)
1705{
1706	if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
1707		vm_page_dirty(m);
1708	}
1709}
1710
1711int so_zerocp_fullpage = 0;
1712
1713void
1714vm_page_cowfault(vm_page_t m)
1715{
1716	vm_page_t mnew;
1717	vm_object_t object;
1718	vm_pindex_t pindex;
1719
1720	object = m->object;
1721	pindex = m->pindex;
1722
1723 retry_alloc:
1724	pmap_remove_all(m);
1725	vm_page_remove(m);
1726	mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY);
1727	if (mnew == NULL) {
1728		vm_page_insert(m, object, pindex);
1729		vm_page_unlock_queues();
1730		VM_OBJECT_UNLOCK(object);
1731		VM_WAIT;
1732		VM_OBJECT_LOCK(object);
1733		vm_page_lock_queues();
1734		goto retry_alloc;
1735	}
1736
1737	if (m->cow == 0) {
1738		/*
1739		 * check to see if we raced with an xmit complete when
1740		 * waiting to allocate a page.  If so, put things back
1741		 * the way they were
1742		 */
1743		vm_page_free(mnew);
1744		vm_page_insert(m, object, pindex);
1745	} else { /* clear COW & copy page */
1746		if (!so_zerocp_fullpage)
1747			pmap_copy_page(m, mnew);
1748		mnew->valid = VM_PAGE_BITS_ALL;
1749		vm_page_dirty(mnew);
1750		mnew->wire_count = m->wire_count - m->cow;
1751		m->wire_count = m->cow;
1752	}
1753}
1754
1755void
1756vm_page_cowclear(vm_page_t m)
1757{
1758
1759	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1760	if (m->cow) {
1761		m->cow--;
1762		/*
1763		 * let vm_fault add back write permission  lazily
1764		 */
1765	}
1766	/*
1767	 *  sf_buf_free() will free the page, so we needn't do it here
1768	 */
1769}
1770
1771void
1772vm_page_cowsetup(vm_page_t m)
1773{
1774
1775	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1776	m->cow++;
1777	pmap_remove_write(m);
1778}
1779
1780#include "opt_ddb.h"
1781#ifdef DDB
1782#include <sys/kernel.h>
1783
1784#include <ddb/ddb.h>
1785
1786DB_SHOW_COMMAND(page, vm_page_print_page_info)
1787{
1788	db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
1789	db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
1790	db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
1791	db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
1792	db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
1793	db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
1794	db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
1795	db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
1796	db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
1797	db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
1798}
1799
1800DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
1801{
1802	int i;
1803	db_printf("PQ_FREE:");
1804	for (i = 0; i < PQ_NUMCOLORS; i++) {
1805		db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt);
1806	}
1807	db_printf("\n");
1808
1809	db_printf("PQ_CACHE:");
1810	for (i = 0; i < PQ_NUMCOLORS; i++) {
1811		db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt);
1812	}
1813	db_printf("\n");
1814
1815	db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
1816		vm_page_queues[PQ_ACTIVE].lcnt,
1817		vm_page_queues[PQ_INACTIVE].lcnt);
1818}
1819#endif /* DDB */
1820