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