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