vm_page.c revision 209407
1/*-
2 * Copyright (c) 1991 Regents of the University of California.
3 * All rights reserved.
4 * Copyright (c) 1998 Matthew Dillon.  All Rights Reserved.
5 *
6 * This code is derived from software contributed to Berkeley by
7 * The Mach Operating System project at Carnegie-Mellon University.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 *	from: @(#)vm_page.c	7.4 (Berkeley) 5/7/91
34 */
35
36/*-
37 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38 * All rights reserved.
39 *
40 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
41 *
42 * Permission to use, copy, modify and distribute this software and
43 * its documentation is hereby granted, provided that both the copyright
44 * notice and this permission notice appear in all copies of the
45 * software, derivative works or modified versions, and any portions
46 * thereof, and that both notices appear in supporting documentation.
47 *
48 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49 * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51 *
52 * Carnegie Mellon requests users of this software to return to
53 *
54 *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
55 *  School of Computer Science
56 *  Carnegie Mellon University
57 *  Pittsburgh PA 15213-3890
58 *
59 * any improvements or extensions that they make and grant Carnegie the
60 * rights to redistribute these changes.
61 */
62
63/*
64 *			GENERAL RULES ON VM_PAGE MANIPULATION
65 *
66 *	- a pageq mutex is required when adding or removing a page from a
67 *	  page queue (vm_page_queue[]), regardless of other mutexes or the
68 *	  busy state of a page.
69 *
70 *	- a hash chain mutex is required when associating or disassociating
71 *	  a page from the VM PAGE CACHE hash table (vm_page_buckets),
72 *	  regardless of other mutexes or the busy state of a page.
73 *
74 *	- either a hash chain mutex OR a busied page is required in order
75 *	  to modify the page flags.  A hash chain mutex must be obtained in
76 *	  order to busy a page.  A page's flags cannot be modified by a
77 *	  hash chain mutex if the page is marked busy.
78 *
79 *	- The object memq mutex is held when inserting or removing
80 *	  pages from an object (vm_page_insert() or vm_page_remove()).  This
81 *	  is different from the object's main mutex.
82 *
83 *	Generally speaking, you have to be aware of side effects when running
84 *	vm_page ops.  A vm_page_lookup() will return with the hash chain
85 *	locked, whether it was able to lookup the page or not.  vm_page_free(),
86 *	vm_page_cache(), vm_page_activate(), and a number of other routines
87 *	will release the hash chain mutex for you.  Intermediate manipulation
88 *	routines such as vm_page_flag_set() expect the hash chain to be held
89 *	on entry and the hash chain will remain held on return.
90 *
91 *	pageq scanning can only occur with the pageq in question locked.
92 *	We have a known bottleneck with the active queue, but the cache
93 *	and free queues are actually arrays already.
94 */
95
96/*
97 *	Resident memory management module.
98 */
99
100#include <sys/cdefs.h>
101__FBSDID("$FreeBSD: head/sys/vm/vm_page.c 209407 2010-06-21 23:27:24Z alc $");
102
103#include "opt_vm.h"
104
105#include <sys/param.h>
106#include <sys/systm.h>
107#include <sys/lock.h>
108#include <sys/kernel.h>
109#include <sys/limits.h>
110#include <sys/malloc.h>
111#include <sys/msgbuf.h>
112#include <sys/mutex.h>
113#include <sys/proc.h>
114#include <sys/sysctl.h>
115#include <sys/vmmeter.h>
116#include <sys/vnode.h>
117
118#include <vm/vm.h>
119#include <vm/pmap.h>
120#include <vm/vm_param.h>
121#include <vm/vm_kern.h>
122#include <vm/vm_object.h>
123#include <vm/vm_page.h>
124#include <vm/vm_pageout.h>
125#include <vm/vm_pager.h>
126#include <vm/vm_phys.h>
127#include <vm/vm_reserv.h>
128#include <vm/vm_extern.h>
129#include <vm/uma.h>
130#include <vm/uma_int.h>
131
132#include <machine/md_var.h>
133
134#if defined(__amd64__) || defined (__i386__)
135extern struct sysctl_oid_list sysctl__vm_pmap_children;
136#else
137SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
138#endif
139
140static uint64_t pmap_tryrelock_calls;
141SYSCTL_QUAD(_vm_pmap, OID_AUTO, tryrelock_calls, CTLFLAG_RD,
142    &pmap_tryrelock_calls, 0, "Number of tryrelock calls");
143
144static int pmap_tryrelock_restart;
145SYSCTL_INT(_vm_pmap, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
146    &pmap_tryrelock_restart, 0, "Number of tryrelock restarts");
147
148static int pmap_tryrelock_race;
149SYSCTL_INT(_vm_pmap, OID_AUTO, tryrelock_race, CTLFLAG_RD,
150    &pmap_tryrelock_race, 0, "Number of tryrelock pmap race cases");
151
152/*
153 *	Associated with page of user-allocatable memory is a
154 *	page structure.
155 */
156
157struct vpgqueues vm_page_queues[PQ_COUNT];
158struct vpglocks vm_page_queue_lock;
159struct vpglocks vm_page_queue_free_lock;
160
161struct vpglocks	pa_lock[PA_LOCK_COUNT] __aligned(CACHE_LINE_SIZE);
162
163vm_page_t vm_page_array = 0;
164int vm_page_array_size = 0;
165long first_page = 0;
166int vm_page_zero_count = 0;
167
168static int boot_pages = UMA_BOOT_PAGES;
169TUNABLE_INT("vm.boot_pages", &boot_pages);
170SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RD, &boot_pages, 0,
171	"number of pages allocated for bootstrapping the VM system");
172
173static void vm_page_clear_dirty_mask(vm_page_t m, int pagebits);
174static void vm_page_queue_remove(int queue, vm_page_t m);
175static void vm_page_enqueue(int queue, vm_page_t m);
176
177/* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
178#if PAGE_SIZE == 32768
179#ifdef CTASSERT
180CTASSERT(sizeof(u_long) >= 8);
181#endif
182#endif
183
184/*
185 * Try to acquire a physical address lock while a pmap is locked.  If we
186 * fail to trylock we unlock and lock the pmap directly and cache the
187 * locked pa in *locked.  The caller should then restart their loop in case
188 * the virtual to physical mapping has changed.
189 */
190int
191vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
192{
193	vm_paddr_t lockpa;
194	uint32_t gen_count;
195
196	gen_count = pmap->pm_gen_count;
197	atomic_add_long((volatile long *)&pmap_tryrelock_calls, 1);
198	lockpa = *locked;
199	*locked = pa;
200	if (lockpa) {
201		PA_LOCK_ASSERT(lockpa, MA_OWNED);
202		if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
203			return (0);
204		PA_UNLOCK(lockpa);
205	}
206	if (PA_TRYLOCK(pa))
207		return (0);
208	PMAP_UNLOCK(pmap);
209	atomic_add_int((volatile int *)&pmap_tryrelock_restart, 1);
210	PA_LOCK(pa);
211	PMAP_LOCK(pmap);
212
213	if (pmap->pm_gen_count != gen_count + 1) {
214		pmap->pm_retries++;
215		atomic_add_int((volatile int *)&pmap_tryrelock_race, 1);
216		return (EAGAIN);
217	}
218	return (0);
219}
220
221/*
222 *	vm_set_page_size:
223 *
224 *	Sets the page size, perhaps based upon the memory
225 *	size.  Must be called before any use of page-size
226 *	dependent functions.
227 */
228void
229vm_set_page_size(void)
230{
231	if (cnt.v_page_size == 0)
232		cnt.v_page_size = PAGE_SIZE;
233	if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0)
234		panic("vm_set_page_size: page size not a power of two");
235}
236
237/*
238 *	vm_page_blacklist_lookup:
239 *
240 *	See if a physical address in this page has been listed
241 *	in the blacklist tunable.  Entries in the tunable are
242 *	separated by spaces or commas.  If an invalid integer is
243 *	encountered then the rest of the string is skipped.
244 */
245static int
246vm_page_blacklist_lookup(char *list, vm_paddr_t pa)
247{
248	vm_paddr_t bad;
249	char *cp, *pos;
250
251	for (pos = list; *pos != '\0'; pos = cp) {
252		bad = strtoq(pos, &cp, 0);
253		if (*cp != '\0') {
254			if (*cp == ' ' || *cp == ',') {
255				cp++;
256				if (cp == pos)
257					continue;
258			} else
259				break;
260		}
261		if (pa == trunc_page(bad))
262			return (1);
263	}
264	return (0);
265}
266
267/*
268 *	vm_page_startup:
269 *
270 *	Initializes the resident memory module.
271 *
272 *	Allocates memory for the page cells, and
273 *	for the object/offset-to-page hash table headers.
274 *	Each page cell is initialized and placed on the free list.
275 */
276vm_offset_t
277vm_page_startup(vm_offset_t vaddr)
278{
279	vm_offset_t mapped;
280	vm_paddr_t page_range;
281	vm_paddr_t new_end;
282	int i;
283	vm_paddr_t pa;
284	int nblocks;
285	vm_paddr_t last_pa;
286	char *list;
287
288	/* the biggest memory array is the second group of pages */
289	vm_paddr_t end;
290	vm_paddr_t biggestsize;
291	vm_paddr_t low_water, high_water;
292	int biggestone;
293
294	biggestsize = 0;
295	biggestone = 0;
296	nblocks = 0;
297	vaddr = round_page(vaddr);
298
299	for (i = 0; phys_avail[i + 1]; i += 2) {
300		phys_avail[i] = round_page(phys_avail[i]);
301		phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
302	}
303
304	low_water = phys_avail[0];
305	high_water = phys_avail[1];
306
307	for (i = 0; phys_avail[i + 1]; i += 2) {
308		vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
309
310		if (size > biggestsize) {
311			biggestone = i;
312			biggestsize = size;
313		}
314		if (phys_avail[i] < low_water)
315			low_water = phys_avail[i];
316		if (phys_avail[i + 1] > high_water)
317			high_water = phys_avail[i + 1];
318		++nblocks;
319	}
320
321#ifdef XEN
322	low_water = 0;
323#endif
324
325	end = phys_avail[biggestone+1];
326
327	/*
328	 * Initialize the locks.
329	 */
330	mtx_init(&vm_page_queue_mtx, "vm page queue mutex", NULL, MTX_DEF |
331	    MTX_RECURSE);
332	mtx_init(&vm_page_queue_free_mtx, "vm page queue free mutex", NULL,
333	    MTX_DEF);
334
335	/* Setup page locks. */
336	for (i = 0; i < PA_LOCK_COUNT; i++)
337		mtx_init(&pa_lock[i].data, "page lock", NULL,
338		    MTX_DEF | MTX_RECURSE | MTX_DUPOK);
339
340	/*
341	 * Initialize the queue headers for the hold queue, the active queue,
342	 * and the inactive queue.
343	 */
344	for (i = 0; i < PQ_COUNT; i++)
345		TAILQ_INIT(&vm_page_queues[i].pl);
346	vm_page_queues[PQ_INACTIVE].cnt = &cnt.v_inactive_count;
347	vm_page_queues[PQ_ACTIVE].cnt = &cnt.v_active_count;
348	vm_page_queues[PQ_HOLD].cnt = &cnt.v_active_count;
349
350	/*
351	 * Allocate memory for use when boot strapping the kernel memory
352	 * allocator.
353	 */
354	new_end = end - (boot_pages * UMA_SLAB_SIZE);
355	new_end = trunc_page(new_end);
356	mapped = pmap_map(&vaddr, new_end, end,
357	    VM_PROT_READ | VM_PROT_WRITE);
358	bzero((void *)mapped, end - new_end);
359	uma_startup((void *)mapped, boot_pages);
360
361#if defined(__amd64__) || defined(__i386__) || defined(__arm__)
362	/*
363	 * Allocate a bitmap to indicate that a random physical page
364	 * needs to be included in a minidump.
365	 *
366	 * The amd64 port needs this to indicate which direct map pages
367	 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
368	 *
369	 * However, i386 still needs this workspace internally within the
370	 * minidump code.  In theory, they are not needed on i386, but are
371	 * included should the sf_buf code decide to use them.
372	 */
373	page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE;
374	vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
375	new_end -= vm_page_dump_size;
376	vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
377	    new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
378	bzero((void *)vm_page_dump, vm_page_dump_size);
379#endif
380#ifdef __amd64__
381	/*
382	 * Request that the physical pages underlying the message buffer be
383	 * included in a crash dump.  Since the message buffer is accessed
384	 * through the direct map, they are not automatically included.
385	 */
386	pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
387	last_pa = pa + round_page(MSGBUF_SIZE);
388	while (pa < last_pa) {
389		dump_add_page(pa);
390		pa += PAGE_SIZE;
391	}
392#endif
393	/*
394	 * Compute the number of pages of memory that will be available for
395	 * use (taking into account the overhead of a page structure per
396	 * page).
397	 */
398	first_page = low_water / PAGE_SIZE;
399#ifdef VM_PHYSSEG_SPARSE
400	page_range = 0;
401	for (i = 0; phys_avail[i + 1] != 0; i += 2)
402		page_range += atop(phys_avail[i + 1] - phys_avail[i]);
403#elif defined(VM_PHYSSEG_DENSE)
404	page_range = high_water / PAGE_SIZE - first_page;
405#else
406#error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
407#endif
408	end = new_end;
409
410	/*
411	 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
412	 */
413	vaddr += PAGE_SIZE;
414
415	/*
416	 * Initialize the mem entry structures now, and put them in the free
417	 * queue.
418	 */
419	new_end = trunc_page(end - page_range * sizeof(struct vm_page));
420	mapped = pmap_map(&vaddr, new_end, end,
421	    VM_PROT_READ | VM_PROT_WRITE);
422	vm_page_array = (vm_page_t) mapped;
423#if VM_NRESERVLEVEL > 0
424	/*
425	 * Allocate memory for the reservation management system's data
426	 * structures.
427	 */
428	new_end = vm_reserv_startup(&vaddr, new_end, high_water);
429#endif
430#ifdef __amd64__
431	/*
432	 * pmap_map on amd64 comes out of the direct-map, not kvm like i386,
433	 * so the pages must be tracked for a crashdump to include this data.
434	 * This includes the vm_page_array and the early UMA bootstrap pages.
435	 */
436	for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
437		dump_add_page(pa);
438#endif
439	phys_avail[biggestone + 1] = new_end;
440
441	/*
442	 * Clear all of the page structures
443	 */
444	bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
445	for (i = 0; i < page_range; i++)
446		vm_page_array[i].order = VM_NFREEORDER;
447	vm_page_array_size = page_range;
448
449	/*
450	 * Initialize the physical memory allocator.
451	 */
452	vm_phys_init();
453
454	/*
455	 * Add every available physical page that is not blacklisted to
456	 * the free lists.
457	 */
458	cnt.v_page_count = 0;
459	cnt.v_free_count = 0;
460	list = getenv("vm.blacklist");
461	for (i = 0; phys_avail[i + 1] != 0; i += 2) {
462		pa = phys_avail[i];
463		last_pa = phys_avail[i + 1];
464		while (pa < last_pa) {
465			if (list != NULL &&
466			    vm_page_blacklist_lookup(list, pa))
467				printf("Skipping page with pa 0x%jx\n",
468				    (uintmax_t)pa);
469			else
470				vm_phys_add_page(pa);
471			pa += PAGE_SIZE;
472		}
473	}
474	freeenv(list);
475#if VM_NRESERVLEVEL > 0
476	/*
477	 * Initialize the reservation management system.
478	 */
479	vm_reserv_init();
480#endif
481	return (vaddr);
482}
483
484void
485vm_page_flag_set(vm_page_t m, unsigned short bits)
486{
487
488	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
489	/*
490	 * The PG_WRITEABLE flag can only be set if the page is managed and
491	 * VPO_BUSY.  Currently, this flag is only set by pmap_enter().
492	 */
493	KASSERT((bits & PG_WRITEABLE) == 0 ||
494	    ((m->flags & (PG_UNMANAGED | PG_FICTITIOUS)) == 0 &&
495	    (m->oflags & VPO_BUSY) != 0), ("PG_WRITEABLE and !VPO_BUSY"));
496	m->flags |= bits;
497}
498
499void
500vm_page_flag_clear(vm_page_t m, unsigned short bits)
501{
502
503	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
504	/*
505	 * The PG_REFERENCED flag can only be cleared if the object
506	 * containing the page is locked.
507	 */
508	KASSERT((bits & PG_REFERENCED) == 0 || VM_OBJECT_LOCKED(m->object),
509	    ("PG_REFERENCED and !VM_OBJECT_LOCKED"));
510	m->flags &= ~bits;
511}
512
513void
514vm_page_busy(vm_page_t m)
515{
516
517	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
518	KASSERT((m->oflags & VPO_BUSY) == 0,
519	    ("vm_page_busy: page already busy!!!"));
520	m->oflags |= VPO_BUSY;
521}
522
523/*
524 *      vm_page_flash:
525 *
526 *      wakeup anyone waiting for the page.
527 */
528void
529vm_page_flash(vm_page_t m)
530{
531
532	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
533	if (m->oflags & VPO_WANTED) {
534		m->oflags &= ~VPO_WANTED;
535		wakeup(m);
536	}
537}
538
539/*
540 *      vm_page_wakeup:
541 *
542 *      clear the VPO_BUSY flag and wakeup anyone waiting for the
543 *      page.
544 *
545 */
546void
547vm_page_wakeup(vm_page_t m)
548{
549
550	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
551	KASSERT(m->oflags & VPO_BUSY, ("vm_page_wakeup: page not busy!!!"));
552	m->oflags &= ~VPO_BUSY;
553	vm_page_flash(m);
554}
555
556void
557vm_page_io_start(vm_page_t m)
558{
559
560	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
561	m->busy++;
562}
563
564void
565vm_page_io_finish(vm_page_t m)
566{
567
568	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
569	m->busy--;
570	if (m->busy == 0)
571		vm_page_flash(m);
572}
573
574/*
575 * Keep page from being freed by the page daemon
576 * much of the same effect as wiring, except much lower
577 * overhead and should be used only for *very* temporary
578 * holding ("wiring").
579 */
580void
581vm_page_hold(vm_page_t mem)
582{
583
584	vm_page_lock_assert(mem, MA_OWNED);
585        mem->hold_count++;
586}
587
588void
589vm_page_unhold(vm_page_t mem)
590{
591
592	vm_page_lock_assert(mem, MA_OWNED);
593	--mem->hold_count;
594	KASSERT(mem->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!"));
595	if (mem->hold_count == 0 && VM_PAGE_INQUEUE2(mem, PQ_HOLD))
596		vm_page_free_toq(mem);
597}
598
599/*
600 *	vm_page_free:
601 *
602 *	Free a page.
603 */
604void
605vm_page_free(vm_page_t m)
606{
607
608	m->flags &= ~PG_ZERO;
609	vm_page_free_toq(m);
610}
611
612/*
613 *	vm_page_free_zero:
614 *
615 *	Free a page to the zerod-pages queue
616 */
617void
618vm_page_free_zero(vm_page_t m)
619{
620
621	m->flags |= PG_ZERO;
622	vm_page_free_toq(m);
623}
624
625/*
626 *	vm_page_sleep:
627 *
628 *	Sleep and release the page and page queues locks.
629 *
630 *	The object containing the given page must be locked.
631 */
632void
633vm_page_sleep(vm_page_t m, const char *msg)
634{
635
636	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
637	if (mtx_owned(&vm_page_queue_mtx))
638		vm_page_unlock_queues();
639	if (mtx_owned(vm_page_lockptr(m)))
640		vm_page_unlock(m);
641
642	/*
643	 * It's possible that while we sleep, the page will get
644	 * unbusied and freed.  If we are holding the object
645	 * lock, we will assume we hold a reference to the object
646	 * such that even if m->object changes, we can re-lock
647	 * it.
648	 */
649	m->oflags |= VPO_WANTED;
650	msleep(m, VM_OBJECT_MTX(m->object), PVM, msg, 0);
651}
652
653/*
654 *	vm_page_dirty:
655 *
656 *	make page all dirty
657 */
658void
659vm_page_dirty(vm_page_t m)
660{
661
662	KASSERT((m->flags & PG_CACHED) == 0,
663	    ("vm_page_dirty: page in cache!"));
664	KASSERT(!VM_PAGE_IS_FREE(m),
665	    ("vm_page_dirty: page is free!"));
666	KASSERT(m->valid == VM_PAGE_BITS_ALL,
667	    ("vm_page_dirty: page is invalid!"));
668	m->dirty = VM_PAGE_BITS_ALL;
669}
670
671/*
672 *	vm_page_splay:
673 *
674 *	Implements Sleator and Tarjan's top-down splay algorithm.  Returns
675 *	the vm_page containing the given pindex.  If, however, that
676 *	pindex is not found in the vm_object, returns a vm_page that is
677 *	adjacent to the pindex, coming before or after it.
678 */
679vm_page_t
680vm_page_splay(vm_pindex_t pindex, vm_page_t root)
681{
682	struct vm_page dummy;
683	vm_page_t lefttreemax, righttreemin, y;
684
685	if (root == NULL)
686		return (root);
687	lefttreemax = righttreemin = &dummy;
688	for (;; root = y) {
689		if (pindex < root->pindex) {
690			if ((y = root->left) == NULL)
691				break;
692			if (pindex < y->pindex) {
693				/* Rotate right. */
694				root->left = y->right;
695				y->right = root;
696				root = y;
697				if ((y = root->left) == NULL)
698					break;
699			}
700			/* Link into the new root's right tree. */
701			righttreemin->left = root;
702			righttreemin = root;
703		} else if (pindex > root->pindex) {
704			if ((y = root->right) == NULL)
705				break;
706			if (pindex > y->pindex) {
707				/* Rotate left. */
708				root->right = y->left;
709				y->left = root;
710				root = y;
711				if ((y = root->right) == NULL)
712					break;
713			}
714			/* Link into the new root's left tree. */
715			lefttreemax->right = root;
716			lefttreemax = root;
717		} else
718			break;
719	}
720	/* Assemble the new root. */
721	lefttreemax->right = root->left;
722	righttreemin->left = root->right;
723	root->left = dummy.right;
724	root->right = dummy.left;
725	return (root);
726}
727
728/*
729 *	vm_page_insert:		[ internal use only ]
730 *
731 *	Inserts the given mem entry into the object and object list.
732 *
733 *	The pagetables are not updated but will presumably fault the page
734 *	in if necessary, or if a kernel page the caller will at some point
735 *	enter the page into the kernel's pmap.  We are not allowed to block
736 *	here so we *can't* do this anyway.
737 *
738 *	The object and page must be locked.
739 *	This routine may not block.
740 */
741void
742vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
743{
744	vm_page_t root;
745
746	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
747	if (m->object != NULL)
748		panic("vm_page_insert: page already inserted");
749
750	/*
751	 * Record the object/offset pair in this page
752	 */
753	m->object = object;
754	m->pindex = pindex;
755
756	/*
757	 * Now link into the object's ordered list of backed pages.
758	 */
759	root = object->root;
760	if (root == NULL) {
761		m->left = NULL;
762		m->right = NULL;
763		TAILQ_INSERT_TAIL(&object->memq, m, listq);
764	} else {
765		root = vm_page_splay(pindex, root);
766		if (pindex < root->pindex) {
767			m->left = root->left;
768			m->right = root;
769			root->left = NULL;
770			TAILQ_INSERT_BEFORE(root, m, listq);
771		} else if (pindex == root->pindex)
772			panic("vm_page_insert: offset already allocated");
773		else {
774			m->right = root->right;
775			m->left = root;
776			root->right = NULL;
777			TAILQ_INSERT_AFTER(&object->memq, root, m, listq);
778		}
779	}
780	object->root = m;
781	object->generation++;
782
783	/*
784	 * show that the object has one more resident page.
785	 */
786	object->resident_page_count++;
787	/*
788	 * Hold the vnode until the last page is released.
789	 */
790	if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
791		vhold((struct vnode *)object->handle);
792
793	/*
794	 * Since we are inserting a new and possibly dirty page,
795	 * update the object's OBJ_MIGHTBEDIRTY flag.
796	 */
797	if (m->flags & PG_WRITEABLE)
798		vm_object_set_writeable_dirty(object);
799}
800
801/*
802 *	vm_page_remove:
803 *				NOTE: used by device pager as well -wfj
804 *
805 *	Removes the given mem entry from the object/offset-page
806 *	table and the object page list, but do not invalidate/terminate
807 *	the backing store.
808 *
809 *	The object and page must be locked.
810 *	The underlying pmap entry (if any) is NOT removed here.
811 *	This routine may not block.
812 */
813void
814vm_page_remove(vm_page_t m)
815{
816	vm_object_t object;
817	vm_page_t root;
818
819	if ((m->flags & PG_UNMANAGED) == 0)
820		vm_page_lock_assert(m, MA_OWNED);
821	if ((object = m->object) == NULL)
822		return;
823	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
824	if (m->oflags & VPO_BUSY) {
825		m->oflags &= ~VPO_BUSY;
826		vm_page_flash(m);
827	}
828
829	/*
830	 * Now remove from the object's list of backed pages.
831	 */
832	if (m != object->root)
833		vm_page_splay(m->pindex, object->root);
834	if (m->left == NULL)
835		root = m->right;
836	else {
837		root = vm_page_splay(m->pindex, m->left);
838		root->right = m->right;
839	}
840	object->root = root;
841	TAILQ_REMOVE(&object->memq, m, listq);
842
843	/*
844	 * And show that the object has one fewer resident page.
845	 */
846	object->resident_page_count--;
847	object->generation++;
848	/*
849	 * The vnode may now be recycled.
850	 */
851	if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
852		vdrop((struct vnode *)object->handle);
853
854	m->object = NULL;
855}
856
857/*
858 *	vm_page_lookup:
859 *
860 *	Returns the page associated with the object/offset
861 *	pair specified; if none is found, NULL is returned.
862 *
863 *	The object must be locked.
864 *	This routine may not block.
865 *	This is a critical path routine
866 */
867vm_page_t
868vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
869{
870	vm_page_t m;
871
872	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
873	if ((m = object->root) != NULL && m->pindex != pindex) {
874		m = vm_page_splay(pindex, m);
875		if ((object->root = m)->pindex != pindex)
876			m = NULL;
877	}
878	return (m);
879}
880
881/*
882 * Returns the given page's successor (by pindex) within the object if it is
883 * resident; if none is found, NULL is returned.
884 *
885 * The object must be locked.
886 */
887vm_page_t
888vm_page_next(vm_page_t m)
889{
890	vm_page_t next;
891
892	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
893	if ((next = TAILQ_NEXT(m, listq)) != NULL &&
894	    next->pindex != m->pindex + 1)
895		next = NULL;
896	return (next);
897}
898
899/*
900 * Returns the given page's predecessor (by pindex) within the object if it is
901 * resident; if none is found, NULL is returned.
902 *
903 * The object must be locked.
904 */
905vm_page_t
906vm_page_prev(vm_page_t m)
907{
908	vm_page_t prev;
909
910	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
911	if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
912	    prev->pindex != m->pindex - 1)
913		prev = NULL;
914	return (prev);
915}
916
917/*
918 *	vm_page_rename:
919 *
920 *	Move the given memory entry from its
921 *	current object to the specified target object/offset.
922 *
923 *	The object must be locked.
924 *	This routine may not block.
925 *
926 *	Note: swap associated with the page must be invalidated by the move.  We
927 *	      have to do this for several reasons:  (1) we aren't freeing the
928 *	      page, (2) we are dirtying the page, (3) the VM system is probably
929 *	      moving the page from object A to B, and will then later move
930 *	      the backing store from A to B and we can't have a conflict.
931 *
932 *	Note: we *always* dirty the page.  It is necessary both for the
933 *	      fact that we moved it, and because we may be invalidating
934 *	      swap.  If the page is on the cache, we have to deactivate it
935 *	      or vm_page_dirty() will panic.  Dirty pages are not allowed
936 *	      on the cache.
937 */
938void
939vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
940{
941
942	vm_page_remove(m);
943	vm_page_insert(m, new_object, new_pindex);
944	vm_page_dirty(m);
945}
946
947/*
948 *	Convert all of the given object's cached pages that have a
949 *	pindex within the given range into free pages.  If the value
950 *	zero is given for "end", then the range's upper bound is
951 *	infinity.  If the given object is backed by a vnode and it
952 *	transitions from having one or more cached pages to none, the
953 *	vnode's hold count is reduced.
954 */
955void
956vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
957{
958	vm_page_t m, m_next;
959	boolean_t empty;
960
961	mtx_lock(&vm_page_queue_free_mtx);
962	if (__predict_false(object->cache == NULL)) {
963		mtx_unlock(&vm_page_queue_free_mtx);
964		return;
965	}
966	m = object->cache = vm_page_splay(start, object->cache);
967	if (m->pindex < start) {
968		if (m->right == NULL)
969			m = NULL;
970		else {
971			m_next = vm_page_splay(start, m->right);
972			m_next->left = m;
973			m->right = NULL;
974			m = object->cache = m_next;
975		}
976	}
977
978	/*
979	 * At this point, "m" is either (1) a reference to the page
980	 * with the least pindex that is greater than or equal to
981	 * "start" or (2) NULL.
982	 */
983	for (; m != NULL && (m->pindex < end || end == 0); m = m_next) {
984		/*
985		 * Find "m"'s successor and remove "m" from the
986		 * object's cache.
987		 */
988		if (m->right == NULL) {
989			object->cache = m->left;
990			m_next = NULL;
991		} else {
992			m_next = vm_page_splay(start, m->right);
993			m_next->left = m->left;
994			object->cache = m_next;
995		}
996		/* Convert "m" to a free page. */
997		m->object = NULL;
998		m->valid = 0;
999		/* Clear PG_CACHED and set PG_FREE. */
1000		m->flags ^= PG_CACHED | PG_FREE;
1001		KASSERT((m->flags & (PG_CACHED | PG_FREE)) == PG_FREE,
1002		    ("vm_page_cache_free: page %p has inconsistent flags", m));
1003		cnt.v_cache_count--;
1004		cnt.v_free_count++;
1005	}
1006	empty = object->cache == NULL;
1007	mtx_unlock(&vm_page_queue_free_mtx);
1008	if (object->type == OBJT_VNODE && empty)
1009		vdrop(object->handle);
1010}
1011
1012/*
1013 *	Returns the cached page that is associated with the given
1014 *	object and offset.  If, however, none exists, returns NULL.
1015 *
1016 *	The free page queue must be locked.
1017 */
1018static inline vm_page_t
1019vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
1020{
1021	vm_page_t m;
1022
1023	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1024	if ((m = object->cache) != NULL && m->pindex != pindex) {
1025		m = vm_page_splay(pindex, m);
1026		if ((object->cache = m)->pindex != pindex)
1027			m = NULL;
1028	}
1029	return (m);
1030}
1031
1032/*
1033 *	Remove the given cached page from its containing object's
1034 *	collection of cached pages.
1035 *
1036 *	The free page queue must be locked.
1037 */
1038void
1039vm_page_cache_remove(vm_page_t m)
1040{
1041	vm_object_t object;
1042	vm_page_t root;
1043
1044	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1045	KASSERT((m->flags & PG_CACHED) != 0,
1046	    ("vm_page_cache_remove: page %p is not cached", m));
1047	object = m->object;
1048	if (m != object->cache) {
1049		root = vm_page_splay(m->pindex, object->cache);
1050		KASSERT(root == m,
1051		    ("vm_page_cache_remove: page %p is not cached in object %p",
1052		    m, object));
1053	}
1054	if (m->left == NULL)
1055		root = m->right;
1056	else if (m->right == NULL)
1057		root = m->left;
1058	else {
1059		root = vm_page_splay(m->pindex, m->left);
1060		root->right = m->right;
1061	}
1062	object->cache = root;
1063	m->object = NULL;
1064	cnt.v_cache_count--;
1065}
1066
1067/*
1068 *	Transfer all of the cached pages with offset greater than or
1069 *	equal to 'offidxstart' from the original object's cache to the
1070 *	new object's cache.  However, any cached pages with offset
1071 *	greater than or equal to the new object's size are kept in the
1072 *	original object.  Initially, the new object's cache must be
1073 *	empty.  Offset 'offidxstart' in the original object must
1074 *	correspond to offset zero in the new object.
1075 *
1076 *	The new object must be locked.
1077 */
1078void
1079vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1080    vm_object_t new_object)
1081{
1082	vm_page_t m, m_next;
1083
1084	/*
1085	 * Insertion into an object's collection of cached pages
1086	 * requires the object to be locked.  In contrast, removal does
1087	 * not.
1088	 */
1089	VM_OBJECT_LOCK_ASSERT(new_object, MA_OWNED);
1090	KASSERT(new_object->cache == NULL,
1091	    ("vm_page_cache_transfer: object %p has cached pages",
1092	    new_object));
1093	mtx_lock(&vm_page_queue_free_mtx);
1094	if ((m = orig_object->cache) != NULL) {
1095		/*
1096		 * Transfer all of the pages with offset greater than or
1097		 * equal to 'offidxstart' from the original object's
1098		 * cache to the new object's cache.
1099		 */
1100		m = vm_page_splay(offidxstart, m);
1101		if (m->pindex < offidxstart) {
1102			orig_object->cache = m;
1103			new_object->cache = m->right;
1104			m->right = NULL;
1105		} else {
1106			orig_object->cache = m->left;
1107			new_object->cache = m;
1108			m->left = NULL;
1109		}
1110		while ((m = new_object->cache) != NULL) {
1111			if ((m->pindex - offidxstart) >= new_object->size) {
1112				/*
1113				 * Return all of the cached pages with
1114				 * offset greater than or equal to the
1115				 * new object's size to the original
1116				 * object's cache.
1117				 */
1118				new_object->cache = m->left;
1119				m->left = orig_object->cache;
1120				orig_object->cache = m;
1121				break;
1122			}
1123			m_next = vm_page_splay(m->pindex, m->right);
1124			/* Update the page's object and offset. */
1125			m->object = new_object;
1126			m->pindex -= offidxstart;
1127			if (m_next == NULL)
1128				break;
1129			m->right = NULL;
1130			m_next->left = m;
1131			new_object->cache = m_next;
1132		}
1133		KASSERT(new_object->cache == NULL ||
1134		    new_object->type == OBJT_SWAP,
1135		    ("vm_page_cache_transfer: object %p's type is incompatible"
1136		    " with cached pages", new_object));
1137	}
1138	mtx_unlock(&vm_page_queue_free_mtx);
1139}
1140
1141/*
1142 *	vm_page_alloc:
1143 *
1144 *	Allocate and return a memory cell associated
1145 *	with this VM object/offset pair.
1146 *
1147 *	page_req classes:
1148 *	VM_ALLOC_NORMAL		normal process request
1149 *	VM_ALLOC_SYSTEM		system *really* needs a page
1150 *	VM_ALLOC_INTERRUPT	interrupt time request
1151 *	VM_ALLOC_ZERO		zero page
1152 *	VM_ALLOC_WIRED		wire the allocated page
1153 *	VM_ALLOC_NOOBJ		page is not associated with a vm object
1154 *	VM_ALLOC_NOBUSY		do not set the page busy
1155 *	VM_ALLOC_IFNOTCACHED	return NULL, do not reactivate if the page
1156 *				is cached
1157 *
1158 *	This routine may not sleep.
1159 */
1160vm_page_t
1161vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1162{
1163	struct vnode *vp = NULL;
1164	vm_object_t m_object;
1165	vm_page_t m;
1166	int flags, page_req;
1167
1168	page_req = req & VM_ALLOC_CLASS_MASK;
1169	KASSERT(curthread->td_intr_nesting_level == 0 ||
1170	    page_req == VM_ALLOC_INTERRUPT,
1171	    ("vm_page_alloc(NORMAL|SYSTEM) in interrupt context"));
1172
1173	if ((req & VM_ALLOC_NOOBJ) == 0) {
1174		KASSERT(object != NULL,
1175		    ("vm_page_alloc: NULL object."));
1176		VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1177	}
1178
1179	/*
1180	 * The pager is allowed to eat deeper into the free page list.
1181	 */
1182	if ((curproc == pageproc) && (page_req != VM_ALLOC_INTERRUPT)) {
1183		page_req = VM_ALLOC_SYSTEM;
1184	};
1185
1186	mtx_lock(&vm_page_queue_free_mtx);
1187	if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1188	    (page_req == VM_ALLOC_SYSTEM &&
1189	    cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1190	    (page_req == VM_ALLOC_INTERRUPT &&
1191	    cnt.v_free_count + cnt.v_cache_count > 0)) {
1192		/*
1193		 * Allocate from the free queue if the number of free pages
1194		 * exceeds the minimum for the request class.
1195		 */
1196		if (object != NULL &&
1197		    (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1198			if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1199				mtx_unlock(&vm_page_queue_free_mtx);
1200				return (NULL);
1201			}
1202			if (vm_phys_unfree_page(m))
1203				vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1204#if VM_NRESERVLEVEL > 0
1205			else if (!vm_reserv_reactivate_page(m))
1206#else
1207			else
1208#endif
1209				panic("vm_page_alloc: cache page %p is missing"
1210				    " from the free queue", m);
1211		} else if ((req & VM_ALLOC_IFCACHED) != 0) {
1212			mtx_unlock(&vm_page_queue_free_mtx);
1213			return (NULL);
1214#if VM_NRESERVLEVEL > 0
1215		} else if (object == NULL || object->type == OBJT_DEVICE ||
1216		    object->type == OBJT_SG ||
1217		    (object->flags & OBJ_COLORED) == 0 ||
1218		    (m = vm_reserv_alloc_page(object, pindex)) == NULL) {
1219#else
1220		} else {
1221#endif
1222			m = vm_phys_alloc_pages(object != NULL ?
1223			    VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1224#if VM_NRESERVLEVEL > 0
1225			if (m == NULL && vm_reserv_reclaim_inactive()) {
1226				m = vm_phys_alloc_pages(object != NULL ?
1227				    VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1228				    0);
1229			}
1230#endif
1231		}
1232	} else {
1233		/*
1234		 * Not allocatable, give up.
1235		 */
1236		mtx_unlock(&vm_page_queue_free_mtx);
1237		atomic_add_int(&vm_pageout_deficit, 1);
1238		pagedaemon_wakeup();
1239		return (NULL);
1240	}
1241
1242	/*
1243	 *  At this point we had better have found a good page.
1244	 */
1245
1246	KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1247	KASSERT(m->queue == PQ_NONE,
1248	    ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1249	KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1250	KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1251	KASSERT(m->busy == 0, ("vm_page_alloc: page %p is busy", m));
1252	KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1253	KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1254	    ("vm_page_alloc: page %p has unexpected memattr %d", m,
1255	    pmap_page_get_memattr(m)));
1256	if ((m->flags & PG_CACHED) != 0) {
1257		KASSERT(m->valid != 0,
1258		    ("vm_page_alloc: cached page %p is invalid", m));
1259		if (m->object == object && m->pindex == pindex)
1260	  		cnt.v_reactivated++;
1261		else
1262			m->valid = 0;
1263		m_object = m->object;
1264		vm_page_cache_remove(m);
1265		if (m_object->type == OBJT_VNODE && m_object->cache == NULL)
1266			vp = m_object->handle;
1267	} else {
1268		KASSERT(VM_PAGE_IS_FREE(m),
1269		    ("vm_page_alloc: page %p is not free", m));
1270		KASSERT(m->valid == 0,
1271		    ("vm_page_alloc: free page %p is valid", m));
1272		cnt.v_free_count--;
1273	}
1274
1275	/*
1276	 * Initialize structure.  Only the PG_ZERO flag is inherited.
1277	 */
1278	flags = 0;
1279	if (m->flags & PG_ZERO) {
1280		vm_page_zero_count--;
1281		if (req & VM_ALLOC_ZERO)
1282			flags = PG_ZERO;
1283	}
1284	if (object == NULL || object->type == OBJT_PHYS)
1285		flags |= PG_UNMANAGED;
1286	m->flags = flags;
1287	if (req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ))
1288		m->oflags = 0;
1289	else
1290		m->oflags = VPO_BUSY;
1291	if (req & VM_ALLOC_WIRED) {
1292		atomic_add_int(&cnt.v_wire_count, 1);
1293		m->wire_count = 1;
1294	}
1295	m->act_count = 0;
1296	mtx_unlock(&vm_page_queue_free_mtx);
1297
1298	if (object != NULL) {
1299		/* Ignore device objects; the pager sets "memattr" for them. */
1300		if (object->memattr != VM_MEMATTR_DEFAULT &&
1301		    object->type != OBJT_DEVICE && object->type != OBJT_SG)
1302			pmap_page_set_memattr(m, object->memattr);
1303		vm_page_insert(m, object, pindex);
1304	} else
1305		m->pindex = pindex;
1306
1307	/*
1308	 * The following call to vdrop() must come after the above call
1309	 * to vm_page_insert() in case both affect the same object and
1310	 * vnode.  Otherwise, the affected vnode's hold count could
1311	 * temporarily become zero.
1312	 */
1313	if (vp != NULL)
1314		vdrop(vp);
1315
1316	/*
1317	 * Don't wakeup too often - wakeup the pageout daemon when
1318	 * we would be nearly out of memory.
1319	 */
1320	if (vm_paging_needed())
1321		pagedaemon_wakeup();
1322
1323	return (m);
1324}
1325
1326/*
1327 *	vm_wait:	(also see VM_WAIT macro)
1328 *
1329 *	Block until free pages are available for allocation
1330 *	- Called in various places before memory allocations.
1331 */
1332void
1333vm_wait(void)
1334{
1335
1336	mtx_lock(&vm_page_queue_free_mtx);
1337	if (curproc == pageproc) {
1338		vm_pageout_pages_needed = 1;
1339		msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
1340		    PDROP | PSWP, "VMWait", 0);
1341	} else {
1342		if (!vm_pages_needed) {
1343			vm_pages_needed = 1;
1344			wakeup(&vm_pages_needed);
1345		}
1346		msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
1347		    "vmwait", 0);
1348	}
1349}
1350
1351/*
1352 *	vm_waitpfault:	(also see VM_WAITPFAULT macro)
1353 *
1354 *	Block until free pages are available for allocation
1355 *	- Called only in vm_fault so that processes page faulting
1356 *	  can be easily tracked.
1357 *	- Sleeps at a lower priority than vm_wait() so that vm_wait()ing
1358 *	  processes will be able to grab memory first.  Do not change
1359 *	  this balance without careful testing first.
1360 */
1361void
1362vm_waitpfault(void)
1363{
1364
1365	mtx_lock(&vm_page_queue_free_mtx);
1366	if (!vm_pages_needed) {
1367		vm_pages_needed = 1;
1368		wakeup(&vm_pages_needed);
1369	}
1370	msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
1371	    "pfault", 0);
1372}
1373
1374/*
1375 *	vm_page_requeue:
1376 *
1377 *	Move the given page to the tail of its present page queue.
1378 *
1379 *	The page queues must be locked.
1380 */
1381void
1382vm_page_requeue(vm_page_t m)
1383{
1384	int queue = VM_PAGE_GETQUEUE(m);
1385	struct vpgqueues *vpq;
1386
1387	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1388	KASSERT(queue != PQ_NONE,
1389	    ("vm_page_requeue: page %p is not queued", m));
1390	vpq = &vm_page_queues[queue];
1391	TAILQ_REMOVE(&vpq->pl, m, pageq);
1392	TAILQ_INSERT_TAIL(&vpq->pl, m, pageq);
1393}
1394
1395/*
1396 *	vm_page_queue_remove:
1397 *
1398 *	Remove the given page from the specified queue.
1399 *
1400 *	The page and page queues must be locked.
1401 */
1402static __inline void
1403vm_page_queue_remove(int queue, vm_page_t m)
1404{
1405	struct vpgqueues *pq;
1406
1407	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1408	vm_page_lock_assert(m, MA_OWNED);
1409	pq = &vm_page_queues[queue];
1410	TAILQ_REMOVE(&pq->pl, m, pageq);
1411	(*pq->cnt)--;
1412}
1413
1414/*
1415 *	vm_pageq_remove:
1416 *
1417 *	Remove a page from its queue.
1418 *
1419 *	The given page must be locked.
1420 *	This routine may not block.
1421 */
1422void
1423vm_pageq_remove(vm_page_t m)
1424{
1425	int queue = VM_PAGE_GETQUEUE(m);
1426
1427	vm_page_lock_assert(m, MA_OWNED);
1428	if (queue != PQ_NONE) {
1429		vm_page_lock_queues();
1430		VM_PAGE_SETQUEUE2(m, PQ_NONE);
1431		vm_page_queue_remove(queue, m);
1432		vm_page_unlock_queues();
1433	}
1434}
1435
1436/*
1437 *	vm_page_enqueue:
1438 *
1439 *	Add the given page to the specified queue.
1440 *
1441 *	The page queues must be locked.
1442 */
1443static void
1444vm_page_enqueue(int queue, vm_page_t m)
1445{
1446	struct vpgqueues *vpq;
1447
1448	vpq = &vm_page_queues[queue];
1449	VM_PAGE_SETQUEUE2(m, queue);
1450	TAILQ_INSERT_TAIL(&vpq->pl, m, pageq);
1451	++*vpq->cnt;
1452}
1453
1454/*
1455 *	vm_page_activate:
1456 *
1457 *	Put the specified page on the active list (if appropriate).
1458 *	Ensure that act_count is at least ACT_INIT but do not otherwise
1459 *	mess with it.
1460 *
1461 *	The page must be locked.
1462 *	This routine may not block.
1463 */
1464void
1465vm_page_activate(vm_page_t m)
1466{
1467	int queue;
1468
1469	vm_page_lock_assert(m, MA_OWNED);
1470	if ((queue = VM_PAGE_GETKNOWNQUEUE2(m)) != PQ_ACTIVE) {
1471		if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1472			if (m->act_count < ACT_INIT)
1473				m->act_count = ACT_INIT;
1474			vm_page_lock_queues();
1475			if (queue != PQ_NONE)
1476				vm_page_queue_remove(queue, m);
1477			vm_page_enqueue(PQ_ACTIVE, m);
1478			vm_page_unlock_queues();
1479		} else
1480			KASSERT(queue == PQ_NONE,
1481			    ("vm_page_activate: wired page %p is queued", m));
1482	} else {
1483		if (m->act_count < ACT_INIT)
1484			m->act_count = ACT_INIT;
1485	}
1486}
1487
1488/*
1489 *	vm_page_free_wakeup:
1490 *
1491 *	Helper routine for vm_page_free_toq() and vm_page_cache().  This
1492 *	routine is called when a page has been added to the cache or free
1493 *	queues.
1494 *
1495 *	The page queues must be locked.
1496 *	This routine may not block.
1497 */
1498static inline void
1499vm_page_free_wakeup(void)
1500{
1501
1502	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1503	/*
1504	 * if pageout daemon needs pages, then tell it that there are
1505	 * some free.
1506	 */
1507	if (vm_pageout_pages_needed &&
1508	    cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
1509		wakeup(&vm_pageout_pages_needed);
1510		vm_pageout_pages_needed = 0;
1511	}
1512	/*
1513	 * wakeup processes that are waiting on memory if we hit a
1514	 * high water mark. And wakeup scheduler process if we have
1515	 * lots of memory. this process will swapin processes.
1516	 */
1517	if (vm_pages_needed && !vm_page_count_min()) {
1518		vm_pages_needed = 0;
1519		wakeup(&cnt.v_free_count);
1520	}
1521}
1522
1523/*
1524 *	vm_page_free_toq:
1525 *
1526 *	Returns the given page to the free list,
1527 *	disassociating it with any VM object.
1528 *
1529 *	Object and page must be locked prior to entry.
1530 *	This routine may not block.
1531 */
1532
1533void
1534vm_page_free_toq(vm_page_t m)
1535{
1536
1537	if ((m->flags & PG_UNMANAGED) == 0) {
1538		vm_page_lock_assert(m, MA_OWNED);
1539		KASSERT(!pmap_page_is_mapped(m),
1540		    ("vm_page_free_toq: freeing mapped page %p", m));
1541	}
1542	PCPU_INC(cnt.v_tfree);
1543
1544	if (m->busy || VM_PAGE_IS_FREE(m)) {
1545		printf(
1546		"vm_page_free: pindex(%lu), busy(%d), VPO_BUSY(%d), hold(%d)\n",
1547		    (u_long)m->pindex, m->busy, (m->oflags & VPO_BUSY) ? 1 : 0,
1548		    m->hold_count);
1549		if (VM_PAGE_IS_FREE(m))
1550			panic("vm_page_free: freeing free page");
1551		else
1552			panic("vm_page_free: freeing busy page");
1553	}
1554
1555	/*
1556	 * unqueue, then remove page.  Note that we cannot destroy
1557	 * the page here because we do not want to call the pager's
1558	 * callback routine until after we've put the page on the
1559	 * appropriate free queue.
1560	 */
1561	if ((m->flags & PG_UNMANAGED) == 0)
1562		vm_pageq_remove(m);
1563	vm_page_remove(m);
1564
1565	/*
1566	 * If fictitious remove object association and
1567	 * return, otherwise delay object association removal.
1568	 */
1569	if ((m->flags & PG_FICTITIOUS) != 0) {
1570		return;
1571	}
1572
1573	m->valid = 0;
1574	vm_page_undirty(m);
1575
1576	if (m->wire_count != 0) {
1577		if (m->wire_count > 1) {
1578			panic("vm_page_free: invalid wire count (%d), pindex: 0x%lx",
1579				m->wire_count, (long)m->pindex);
1580		}
1581		panic("vm_page_free: freeing wired page");
1582	}
1583	if (m->hold_count != 0) {
1584		m->flags &= ~PG_ZERO;
1585		vm_page_lock_queues();
1586		vm_page_enqueue(PQ_HOLD, m);
1587		vm_page_unlock_queues();
1588	} else {
1589		/*
1590		 * Restore the default memory attribute to the page.
1591		 */
1592		if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
1593			pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
1594
1595		/*
1596		 * Insert the page into the physical memory allocator's
1597		 * cache/free page queues.
1598		 */
1599		mtx_lock(&vm_page_queue_free_mtx);
1600		m->flags |= PG_FREE;
1601		cnt.v_free_count++;
1602#if VM_NRESERVLEVEL > 0
1603		if (!vm_reserv_free_page(m))
1604#else
1605		if (TRUE)
1606#endif
1607			vm_phys_free_pages(m, 0);
1608		if ((m->flags & PG_ZERO) != 0)
1609			++vm_page_zero_count;
1610		else
1611			vm_page_zero_idle_wakeup();
1612		vm_page_free_wakeup();
1613		mtx_unlock(&vm_page_queue_free_mtx);
1614	}
1615}
1616
1617/*
1618 *	vm_page_wire:
1619 *
1620 *	Mark this page as wired down by yet
1621 *	another map, removing it from paging queues
1622 *	as necessary.
1623 *
1624 *	If the page is fictitious, then its wire count must remain one.
1625 *
1626 *	The page must be locked.
1627 *	This routine may not block.
1628 */
1629void
1630vm_page_wire(vm_page_t m)
1631{
1632
1633	/*
1634	 * Only bump the wire statistics if the page is not already wired,
1635	 * and only unqueue the page if it is on some queue (if it is unmanaged
1636	 * it is already off the queues).
1637	 */
1638	vm_page_lock_assert(m, MA_OWNED);
1639	if ((m->flags & PG_FICTITIOUS) != 0) {
1640		KASSERT(m->wire_count == 1,
1641		    ("vm_page_wire: fictitious page %p's wire count isn't one",
1642		    m));
1643		return;
1644	}
1645	if (m->wire_count == 0) {
1646		if ((m->flags & PG_UNMANAGED) == 0)
1647			vm_pageq_remove(m);
1648		atomic_add_int(&cnt.v_wire_count, 1);
1649	}
1650	m->wire_count++;
1651	KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
1652}
1653
1654/*
1655 * vm_page_unwire:
1656 *
1657 * Release one wiring of the specified page, potentially enabling it to be
1658 * paged again.  If paging is enabled, then the value of the parameter
1659 * "activate" determines to which queue the page is added.  If "activate" is
1660 * non-zero, then the page is added to the active queue.  Otherwise, it is
1661 * added to the inactive queue.
1662 *
1663 * However, unless the page belongs to an object, it is not enqueued because
1664 * it cannot be paged out.
1665 *
1666 * If a page is fictitious, then its wire count must alway be one.
1667 *
1668 * A managed page must be locked.
1669 */
1670void
1671vm_page_unwire(vm_page_t m, int activate)
1672{
1673
1674	if ((m->flags & PG_UNMANAGED) == 0)
1675		vm_page_lock_assert(m, MA_OWNED);
1676	if ((m->flags & PG_FICTITIOUS) != 0) {
1677		KASSERT(m->wire_count == 1,
1678	    ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
1679		return;
1680	}
1681	if (m->wire_count > 0) {
1682		m->wire_count--;
1683		if (m->wire_count == 0) {
1684			atomic_subtract_int(&cnt.v_wire_count, 1);
1685			if ((m->flags & PG_UNMANAGED) != 0 ||
1686			    m->object == NULL)
1687				return;
1688			vm_page_lock_queues();
1689			if (activate)
1690				vm_page_enqueue(PQ_ACTIVE, m);
1691			else {
1692				vm_page_flag_clear(m, PG_WINATCFLS);
1693				vm_page_enqueue(PQ_INACTIVE, m);
1694			}
1695			vm_page_unlock_queues();
1696		}
1697	} else
1698		panic("vm_page_unwire: page %p's wire count is zero", m);
1699}
1700
1701/*
1702 * Move the specified page to the inactive queue.
1703 *
1704 * Many pages placed on the inactive queue should actually go
1705 * into the cache, but it is difficult to figure out which.  What
1706 * we do instead, if the inactive target is well met, is to put
1707 * clean pages at the head of the inactive queue instead of the tail.
1708 * This will cause them to be moved to the cache more quickly and
1709 * if not actively re-referenced, reclaimed more quickly.  If we just
1710 * stick these pages at the end of the inactive queue, heavy filesystem
1711 * meta-data accesses can cause an unnecessary paging load on memory bound
1712 * processes.  This optimization causes one-time-use metadata to be
1713 * reused more quickly.
1714 *
1715 * Normally athead is 0 resulting in LRU operation.  athead is set
1716 * to 1 if we want this page to be 'as if it were placed in the cache',
1717 * except without unmapping it from the process address space.
1718 *
1719 * This routine may not block.
1720 */
1721static inline void
1722_vm_page_deactivate(vm_page_t m, int athead)
1723{
1724	int queue;
1725
1726	vm_page_lock_assert(m, MA_OWNED);
1727
1728	/*
1729	 * Ignore if already inactive.
1730	 */
1731	if ((queue = VM_PAGE_GETKNOWNQUEUE2(m)) == PQ_INACTIVE)
1732		return;
1733	if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1734		vm_page_lock_queues();
1735		vm_page_flag_clear(m, PG_WINATCFLS);
1736		if (queue != PQ_NONE)
1737			vm_page_queue_remove(queue, m);
1738		if (athead)
1739			TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m,
1740			    pageq);
1741		else
1742			TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m,
1743			    pageq);
1744		VM_PAGE_SETQUEUE2(m, PQ_INACTIVE);
1745		cnt.v_inactive_count++;
1746		vm_page_unlock_queues();
1747	}
1748}
1749
1750/*
1751 * Move the specified page to the inactive queue.
1752 *
1753 * The page must be locked.
1754 */
1755void
1756vm_page_deactivate(vm_page_t m)
1757{
1758
1759	_vm_page_deactivate(m, 0);
1760}
1761
1762/*
1763 * vm_page_try_to_cache:
1764 *
1765 * Returns 0 on failure, 1 on success
1766 */
1767int
1768vm_page_try_to_cache(vm_page_t m)
1769{
1770
1771	vm_page_lock_assert(m, MA_OWNED);
1772	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1773	if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1774	    (m->oflags & VPO_BUSY) || (m->flags & PG_UNMANAGED))
1775		return (0);
1776	pmap_remove_all(m);
1777	if (m->dirty)
1778		return (0);
1779	vm_page_cache(m);
1780	return (1);
1781}
1782
1783/*
1784 * vm_page_try_to_free()
1785 *
1786 *	Attempt to free the page.  If we cannot free it, we do nothing.
1787 *	1 is returned on success, 0 on failure.
1788 */
1789int
1790vm_page_try_to_free(vm_page_t m)
1791{
1792
1793	vm_page_lock_assert(m, MA_OWNED);
1794	if (m->object != NULL)
1795		VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1796	if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1797	    (m->oflags & VPO_BUSY) || (m->flags & PG_UNMANAGED))
1798		return (0);
1799	pmap_remove_all(m);
1800	if (m->dirty)
1801		return (0);
1802	vm_page_free(m);
1803	return (1);
1804}
1805
1806/*
1807 * vm_page_cache
1808 *
1809 * Put the specified page onto the page cache queue (if appropriate).
1810 *
1811 * This routine may not block.
1812 */
1813void
1814vm_page_cache(vm_page_t m)
1815{
1816	vm_object_t object;
1817	vm_page_t root;
1818
1819	vm_page_lock_assert(m, MA_OWNED);
1820	object = m->object;
1821	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1822	if ((m->flags & PG_UNMANAGED) || (m->oflags & VPO_BUSY) || m->busy ||
1823	    m->hold_count || m->wire_count)
1824		panic("vm_page_cache: attempting to cache busy page");
1825	pmap_remove_all(m);
1826	if (m->dirty != 0)
1827		panic("vm_page_cache: page %p is dirty", m);
1828	if (m->valid == 0 || object->type == OBJT_DEFAULT ||
1829	    (object->type == OBJT_SWAP &&
1830	    !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
1831		/*
1832		 * Hypothesis: A cache-elgible page belonging to a
1833		 * default object or swap object but without a backing
1834		 * store must be zero filled.
1835		 */
1836		vm_page_free(m);
1837		return;
1838	}
1839	KASSERT((m->flags & PG_CACHED) == 0,
1840	    ("vm_page_cache: page %p is already cached", m));
1841	PCPU_INC(cnt.v_tcached);
1842
1843	/*
1844	 * Remove the page from the paging queues.
1845	 */
1846	vm_pageq_remove(m);
1847
1848	/*
1849	 * Remove the page from the object's collection of resident
1850	 * pages.
1851	 */
1852	if (m != object->root)
1853		vm_page_splay(m->pindex, object->root);
1854	if (m->left == NULL)
1855		root = m->right;
1856	else {
1857		root = vm_page_splay(m->pindex, m->left);
1858		root->right = m->right;
1859	}
1860	object->root = root;
1861	TAILQ_REMOVE(&object->memq, m, listq);
1862	object->resident_page_count--;
1863	object->generation++;
1864
1865	/*
1866	 * Restore the default memory attribute to the page.
1867	 */
1868	if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
1869		pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
1870
1871	/*
1872	 * Insert the page into the object's collection of cached pages
1873	 * and the physical memory allocator's cache/free page queues.
1874	 */
1875	m->flags &= ~PG_ZERO;
1876	mtx_lock(&vm_page_queue_free_mtx);
1877	m->flags |= PG_CACHED;
1878	cnt.v_cache_count++;
1879	root = object->cache;
1880	if (root == NULL) {
1881		m->left = NULL;
1882		m->right = NULL;
1883	} else {
1884		root = vm_page_splay(m->pindex, root);
1885		if (m->pindex < root->pindex) {
1886			m->left = root->left;
1887			m->right = root;
1888			root->left = NULL;
1889		} else if (__predict_false(m->pindex == root->pindex))
1890			panic("vm_page_cache: offset already cached");
1891		else {
1892			m->right = root->right;
1893			m->left = root;
1894			root->right = NULL;
1895		}
1896	}
1897	object->cache = m;
1898#if VM_NRESERVLEVEL > 0
1899	if (!vm_reserv_free_page(m)) {
1900#else
1901	if (TRUE) {
1902#endif
1903		vm_phys_set_pool(VM_FREEPOOL_CACHE, m, 0);
1904		vm_phys_free_pages(m, 0);
1905	}
1906	vm_page_free_wakeup();
1907	mtx_unlock(&vm_page_queue_free_mtx);
1908
1909	/*
1910	 * Increment the vnode's hold count if this is the object's only
1911	 * cached page.  Decrement the vnode's hold count if this was
1912	 * the object's only resident page.
1913	 */
1914	if (object->type == OBJT_VNODE) {
1915		if (root == NULL && object->resident_page_count != 0)
1916			vhold(object->handle);
1917		else if (root != NULL && object->resident_page_count == 0)
1918			vdrop(object->handle);
1919	}
1920}
1921
1922/*
1923 * vm_page_dontneed
1924 *
1925 *	Cache, deactivate, or do nothing as appropriate.  This routine
1926 *	is typically used by madvise() MADV_DONTNEED.
1927 *
1928 *	Generally speaking we want to move the page into the cache so
1929 *	it gets reused quickly.  However, this can result in a silly syndrome
1930 *	due to the page recycling too quickly.  Small objects will not be
1931 *	fully cached.  On the otherhand, if we move the page to the inactive
1932 *	queue we wind up with a problem whereby very large objects
1933 *	unnecessarily blow away our inactive and cache queues.
1934 *
1935 *	The solution is to move the pages based on a fixed weighting.  We
1936 *	either leave them alone, deactivate them, or move them to the cache,
1937 *	where moving them to the cache has the highest weighting.
1938 *	By forcing some pages into other queues we eventually force the
1939 *	system to balance the queues, potentially recovering other unrelated
1940 *	space from active.  The idea is to not force this to happen too
1941 *	often.
1942 */
1943void
1944vm_page_dontneed(vm_page_t m)
1945{
1946	int dnw;
1947	int head;
1948
1949	vm_page_lock_assert(m, MA_OWNED);
1950	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1951	dnw = PCPU_GET(dnweight);
1952	PCPU_INC(dnweight);
1953
1954	/*
1955	 * Occasionally leave the page alone.
1956	 */
1957	if ((dnw & 0x01F0) == 0 ||
1958	    VM_PAGE_INQUEUE2(m, PQ_INACTIVE)) {
1959		if (m->act_count >= ACT_INIT)
1960			--m->act_count;
1961		return;
1962	}
1963
1964	/*
1965	 * Clear any references to the page.  Otherwise, the page daemon will
1966	 * immediately reactivate the page.
1967	 *
1968	 * Perform the pmap_clear_reference() first.  Otherwise, a concurrent
1969	 * pmap operation, such as pmap_remove(), could clear a reference in
1970	 * the pmap and set PG_REFERENCED on the page before the
1971	 * pmap_clear_reference() had completed.  Consequently, the page would
1972	 * appear referenced based upon an old reference that occurred before
1973	 * this function ran.
1974	 */
1975	pmap_clear_reference(m);
1976	vm_page_lock_queues();
1977	vm_page_flag_clear(m, PG_REFERENCED);
1978	vm_page_unlock_queues();
1979
1980	if (m->dirty == 0 && pmap_is_modified(m))
1981		vm_page_dirty(m);
1982
1983	if (m->dirty || (dnw & 0x0070) == 0) {
1984		/*
1985		 * Deactivate the page 3 times out of 32.
1986		 */
1987		head = 0;
1988	} else {
1989		/*
1990		 * Cache the page 28 times out of every 32.  Note that
1991		 * the page is deactivated instead of cached, but placed
1992		 * at the head of the queue instead of the tail.
1993		 */
1994		head = 1;
1995	}
1996	_vm_page_deactivate(m, head);
1997}
1998
1999/*
2000 * Grab a page, waiting until we are waken up due to the page
2001 * changing state.  We keep on waiting, if the page continues
2002 * to be in the object.  If the page doesn't exist, first allocate it
2003 * and then conditionally zero it.
2004 *
2005 * This routine may block.
2006 */
2007vm_page_t
2008vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
2009{
2010	vm_page_t m;
2011
2012	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2013retrylookup:
2014	if ((m = vm_page_lookup(object, pindex)) != NULL) {
2015		if ((m->oflags & VPO_BUSY) != 0 || m->busy != 0) {
2016			if ((allocflags & VM_ALLOC_RETRY) != 0) {
2017				/*
2018				 * Reference the page before unlocking and
2019				 * sleeping so that the page daemon is less
2020				 * likely to reclaim it.
2021				 */
2022				vm_page_lock_queues();
2023				vm_page_flag_set(m, PG_REFERENCED);
2024			}
2025			vm_page_sleep(m, "pgrbwt");
2026			if ((allocflags & VM_ALLOC_RETRY) == 0)
2027				return (NULL);
2028			goto retrylookup;
2029		} else {
2030			if ((allocflags & VM_ALLOC_WIRED) != 0) {
2031				vm_page_lock(m);
2032				vm_page_wire(m);
2033				vm_page_unlock(m);
2034			}
2035			if ((allocflags & VM_ALLOC_NOBUSY) == 0)
2036				vm_page_busy(m);
2037			return (m);
2038		}
2039	}
2040	m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_RETRY);
2041	if (m == NULL) {
2042		VM_OBJECT_UNLOCK(object);
2043		VM_WAIT;
2044		VM_OBJECT_LOCK(object);
2045		if ((allocflags & VM_ALLOC_RETRY) == 0)
2046			return (NULL);
2047		goto retrylookup;
2048	} else if (m->valid != 0)
2049		return (m);
2050	if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
2051		pmap_zero_page(m);
2052	return (m);
2053}
2054
2055/*
2056 * Mapping function for valid bits or for dirty bits in
2057 * a page.  May not block.
2058 *
2059 * Inputs are required to range within a page.
2060 */
2061int
2062vm_page_bits(int base, int size)
2063{
2064	int first_bit;
2065	int last_bit;
2066
2067	KASSERT(
2068	    base + size <= PAGE_SIZE,
2069	    ("vm_page_bits: illegal base/size %d/%d", base, size)
2070	);
2071
2072	if (size == 0)		/* handle degenerate case */
2073		return (0);
2074
2075	first_bit = base >> DEV_BSHIFT;
2076	last_bit = (base + size - 1) >> DEV_BSHIFT;
2077
2078	return ((2 << last_bit) - (1 << first_bit));
2079}
2080
2081/*
2082 *	vm_page_set_valid:
2083 *
2084 *	Sets portions of a page valid.  The arguments are expected
2085 *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2086 *	of any partial chunks touched by the range.  The invalid portion of
2087 *	such chunks will be zeroed.
2088 *
2089 *	(base + size) must be less then or equal to PAGE_SIZE.
2090 */
2091void
2092vm_page_set_valid(vm_page_t m, int base, int size)
2093{
2094	int endoff, frag;
2095
2096	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2097	if (size == 0)	/* handle degenerate case */
2098		return;
2099
2100	/*
2101	 * If the base is not DEV_BSIZE aligned and the valid
2102	 * bit is clear, we have to zero out a portion of the
2103	 * first block.
2104	 */
2105	if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2106	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2107		pmap_zero_page_area(m, frag, base - frag);
2108
2109	/*
2110	 * If the ending offset is not DEV_BSIZE aligned and the
2111	 * valid bit is clear, we have to zero out a portion of
2112	 * the last block.
2113	 */
2114	endoff = base + size;
2115	if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2116	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2117		pmap_zero_page_area(m, endoff,
2118		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2119
2120	/*
2121	 * Assert that no previously invalid block that is now being validated
2122	 * is already dirty.
2123	 */
2124	KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
2125	    ("vm_page_set_valid: page %p is dirty", m));
2126
2127	/*
2128	 * Set valid bits inclusive of any overlap.
2129	 */
2130	m->valid |= vm_page_bits(base, size);
2131}
2132
2133/*
2134 * Clear the given bits from the specified page's dirty field.
2135 */
2136static __inline void
2137vm_page_clear_dirty_mask(vm_page_t m, int pagebits)
2138{
2139
2140	/*
2141	 * If the object is locked and the page is neither VPO_BUSY nor
2142	 * PG_WRITEABLE, then the page's dirty field cannot possibly be
2143	 * modified by a concurrent pmap operation.
2144	 */
2145	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2146	if ((m->oflags & VPO_BUSY) == 0 && (m->flags & PG_WRITEABLE) == 0)
2147		m->dirty &= ~pagebits;
2148	else {
2149		vm_page_lock_queues();
2150		m->dirty &= ~pagebits;
2151		vm_page_unlock_queues();
2152	}
2153}
2154
2155/*
2156 *	vm_page_set_validclean:
2157 *
2158 *	Sets portions of a page valid and clean.  The arguments are expected
2159 *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2160 *	of any partial chunks touched by the range.  The invalid portion of
2161 *	such chunks will be zero'd.
2162 *
2163 *	This routine may not block.
2164 *
2165 *	(base + size) must be less then or equal to PAGE_SIZE.
2166 */
2167void
2168vm_page_set_validclean(vm_page_t m, int base, int size)
2169{
2170	u_long oldvalid;
2171	int endoff, frag, pagebits;
2172
2173	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2174	if (size == 0)	/* handle degenerate case */
2175		return;
2176
2177	/*
2178	 * If the base is not DEV_BSIZE aligned and the valid
2179	 * bit is clear, we have to zero out a portion of the
2180	 * first block.
2181	 */
2182	if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2183	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2184		pmap_zero_page_area(m, frag, base - frag);
2185
2186	/*
2187	 * If the ending offset is not DEV_BSIZE aligned and the
2188	 * valid bit is clear, we have to zero out a portion of
2189	 * the last block.
2190	 */
2191	endoff = base + size;
2192	if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2193	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2194		pmap_zero_page_area(m, endoff,
2195		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2196
2197	/*
2198	 * Set valid, clear dirty bits.  If validating the entire
2199	 * page we can safely clear the pmap modify bit.  We also
2200	 * use this opportunity to clear the VPO_NOSYNC flag.  If a process
2201	 * takes a write fault on a MAP_NOSYNC memory area the flag will
2202	 * be set again.
2203	 *
2204	 * We set valid bits inclusive of any overlap, but we can only
2205	 * clear dirty bits for DEV_BSIZE chunks that are fully within
2206	 * the range.
2207	 */
2208	oldvalid = m->valid;
2209	pagebits = vm_page_bits(base, size);
2210	m->valid |= pagebits;
2211#if 0	/* NOT YET */
2212	if ((frag = base & (DEV_BSIZE - 1)) != 0) {
2213		frag = DEV_BSIZE - frag;
2214		base += frag;
2215		size -= frag;
2216		if (size < 0)
2217			size = 0;
2218	}
2219	pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
2220#endif
2221	if (base == 0 && size == PAGE_SIZE) {
2222		/*
2223		 * The page can only be modified within the pmap if it is
2224		 * mapped, and it can only be mapped if it was previously
2225		 * fully valid.
2226		 */
2227		if (oldvalid == VM_PAGE_BITS_ALL)
2228			/*
2229			 * Perform the pmap_clear_modify() first.  Otherwise,
2230			 * a concurrent pmap operation, such as
2231			 * pmap_protect(), could clear a modification in the
2232			 * pmap and set the dirty field on the page before
2233			 * pmap_clear_modify() had begun and after the dirty
2234			 * field was cleared here.
2235			 */
2236			pmap_clear_modify(m);
2237		m->dirty = 0;
2238		m->oflags &= ~VPO_NOSYNC;
2239	} else if (oldvalid != VM_PAGE_BITS_ALL)
2240		m->dirty &= ~pagebits;
2241	else
2242		vm_page_clear_dirty_mask(m, pagebits);
2243}
2244
2245void
2246vm_page_clear_dirty(vm_page_t m, int base, int size)
2247{
2248
2249	vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
2250}
2251
2252/*
2253 *	vm_page_set_invalid:
2254 *
2255 *	Invalidates DEV_BSIZE'd chunks within a page.  Both the
2256 *	valid and dirty bits for the effected areas are cleared.
2257 *
2258 *	May not block.
2259 */
2260void
2261vm_page_set_invalid(vm_page_t m, int base, int size)
2262{
2263	int bits;
2264
2265	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2266	KASSERT((m->oflags & VPO_BUSY) == 0,
2267	    ("vm_page_set_invalid: page %p is busy", m));
2268	bits = vm_page_bits(base, size);
2269	if (m->valid == VM_PAGE_BITS_ALL && bits != 0)
2270		pmap_remove_all(m);
2271	KASSERT(!pmap_page_is_mapped(m),
2272	    ("vm_page_set_invalid: page %p is mapped", m));
2273	m->valid &= ~bits;
2274	m->dirty &= ~bits;
2275	m->object->generation++;
2276}
2277
2278/*
2279 * vm_page_zero_invalid()
2280 *
2281 *	The kernel assumes that the invalid portions of a page contain
2282 *	garbage, but such pages can be mapped into memory by user code.
2283 *	When this occurs, we must zero out the non-valid portions of the
2284 *	page so user code sees what it expects.
2285 *
2286 *	Pages are most often semi-valid when the end of a file is mapped
2287 *	into memory and the file's size is not page aligned.
2288 */
2289void
2290vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
2291{
2292	int b;
2293	int i;
2294
2295	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2296	/*
2297	 * Scan the valid bits looking for invalid sections that
2298	 * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
2299	 * valid bit may be set ) have already been zerod by
2300	 * vm_page_set_validclean().
2301	 */
2302	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
2303		if (i == (PAGE_SIZE / DEV_BSIZE) ||
2304		    (m->valid & (1 << i))
2305		) {
2306			if (i > b) {
2307				pmap_zero_page_area(m,
2308				    b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
2309			}
2310			b = i + 1;
2311		}
2312	}
2313
2314	/*
2315	 * setvalid is TRUE when we can safely set the zero'd areas
2316	 * as being valid.  We can do this if there are no cache consistancy
2317	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
2318	 */
2319	if (setvalid)
2320		m->valid = VM_PAGE_BITS_ALL;
2321}
2322
2323/*
2324 *	vm_page_is_valid:
2325 *
2326 *	Is (partial) page valid?  Note that the case where size == 0
2327 *	will return FALSE in the degenerate case where the page is
2328 *	entirely invalid, and TRUE otherwise.
2329 *
2330 *	May not block.
2331 */
2332int
2333vm_page_is_valid(vm_page_t m, int base, int size)
2334{
2335	int bits = vm_page_bits(base, size);
2336
2337	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2338	if (m->valid && ((m->valid & bits) == bits))
2339		return 1;
2340	else
2341		return 0;
2342}
2343
2344/*
2345 * update dirty bits from pmap/mmu.  May not block.
2346 */
2347void
2348vm_page_test_dirty(vm_page_t m)
2349{
2350
2351	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2352	if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
2353		vm_page_dirty(m);
2354}
2355
2356int so_zerocp_fullpage = 0;
2357
2358/*
2359 *	Replace the given page with a copy.  The copied page assumes
2360 *	the portion of the given page's "wire_count" that is not the
2361 *	responsibility of this copy-on-write mechanism.
2362 *
2363 *	The object containing the given page must have a non-zero
2364 *	paging-in-progress count and be locked.
2365 */
2366void
2367vm_page_cowfault(vm_page_t m)
2368{
2369	vm_page_t mnew;
2370	vm_object_t object;
2371	vm_pindex_t pindex;
2372
2373	mtx_assert(&vm_page_queue_mtx, MA_NOTOWNED);
2374	vm_page_lock_assert(m, MA_OWNED);
2375	object = m->object;
2376	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2377	KASSERT(object->paging_in_progress != 0,
2378	    ("vm_page_cowfault: object %p's paging-in-progress count is zero.",
2379	    object));
2380	pindex = m->pindex;
2381
2382 retry_alloc:
2383	pmap_remove_all(m);
2384	vm_page_remove(m);
2385	mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY);
2386	if (mnew == NULL) {
2387		vm_page_insert(m, object, pindex);
2388		vm_page_unlock(m);
2389		VM_OBJECT_UNLOCK(object);
2390		VM_WAIT;
2391		VM_OBJECT_LOCK(object);
2392		if (m == vm_page_lookup(object, pindex)) {
2393			vm_page_lock(m);
2394			goto retry_alloc;
2395		} else {
2396			/*
2397			 * Page disappeared during the wait.
2398			 */
2399			return;
2400		}
2401	}
2402
2403	if (m->cow == 0) {
2404		/*
2405		 * check to see if we raced with an xmit complete when
2406		 * waiting to allocate a page.  If so, put things back
2407		 * the way they were
2408		 */
2409		vm_page_unlock(m);
2410		vm_page_lock(mnew);
2411		vm_page_free(mnew);
2412		vm_page_unlock(mnew);
2413		vm_page_insert(m, object, pindex);
2414	} else { /* clear COW & copy page */
2415		if (!so_zerocp_fullpage)
2416			pmap_copy_page(m, mnew);
2417		mnew->valid = VM_PAGE_BITS_ALL;
2418		vm_page_dirty(mnew);
2419		mnew->wire_count = m->wire_count - m->cow;
2420		m->wire_count = m->cow;
2421		vm_page_unlock(m);
2422	}
2423}
2424
2425void
2426vm_page_cowclear(vm_page_t m)
2427{
2428
2429	vm_page_lock_assert(m, MA_OWNED);
2430	if (m->cow) {
2431		m->cow--;
2432		/*
2433		 * let vm_fault add back write permission  lazily
2434		 */
2435	}
2436	/*
2437	 *  sf_buf_free() will free the page, so we needn't do it here
2438	 */
2439}
2440
2441int
2442vm_page_cowsetup(vm_page_t m)
2443{
2444
2445	vm_page_lock_assert(m, MA_OWNED);
2446	if ((m->flags & (PG_FICTITIOUS | PG_UNMANAGED)) != 0 ||
2447	    m->cow == USHRT_MAX - 1 || !VM_OBJECT_TRYLOCK(m->object))
2448		return (EBUSY);
2449	m->cow++;
2450	pmap_remove_write(m);
2451	VM_OBJECT_UNLOCK(m->object);
2452	return (0);
2453}
2454
2455#include "opt_ddb.h"
2456#ifdef DDB
2457#include <sys/kernel.h>
2458
2459#include <ddb/ddb.h>
2460
2461DB_SHOW_COMMAND(page, vm_page_print_page_info)
2462{
2463	db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
2464	db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
2465	db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
2466	db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
2467	db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
2468	db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
2469	db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
2470	db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
2471	db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
2472	db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
2473}
2474
2475DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
2476{
2477
2478	db_printf("PQ_FREE:");
2479	db_printf(" %d", cnt.v_free_count);
2480	db_printf("\n");
2481
2482	db_printf("PQ_CACHE:");
2483	db_printf(" %d", cnt.v_cache_count);
2484	db_printf("\n");
2485
2486	db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
2487		*vm_page_queues[PQ_ACTIVE].cnt,
2488		*vm_page_queues[PQ_INACTIVE].cnt);
2489}
2490#endif /* DDB */
2491