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