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