2 * Copyright (c) 1991 Regents of the University of California.
5 * This code is derived from software contributed to Berkeley by
6 * The Mach Operating System project at Carnegie-Mellon University.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * from: @(#)vm_page.c 7.4 (Berkeley) 5/7/91
36 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
37 * All rights reserved.
39 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
41 * Permission to use, copy, modify and distribute this software and
42 * its documentation is hereby granted, provided that both the copyright
43 * notice and this permission notice appear in all copies of the
44 * software, derivative works or modified versions, and any portions
45 * thereof, and that both notices appear in supporting documentation.
47 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
48 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
49 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51 * Carnegie Mellon requests users of this software to return to
53 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
54 * School of Computer Science
55 * Carnegie Mellon University
56 * Pittsburgh PA 15213-3890
58 * any improvements or extensions that they make and grant Carnegie the
59 * rights to redistribute these changes.
63 * GENERAL RULES ON VM_PAGE MANIPULATION
65 * - a pageq mutex is required when adding or removing a page from a
66 * page queue (vm_page_queue[]), regardless of other mutexes or the
67 * busy state of a page.
69 * - a hash chain mutex is required when associating or disassociating
70 * a page from the VM PAGE CACHE hash table (vm_page_buckets),
71 * regardless of other mutexes or the busy state of a page.
73 * - either a hash chain mutex OR a busied page is required in order
74 * to modify the page flags. A hash chain mutex must be obtained in
75 * order to busy a page. A page's flags cannot be modified by a
76 * hash chain mutex if the page is marked busy.
78 * - The object memq mutex is held when inserting or removing
79 * pages from an object (vm_page_insert() or vm_page_remove()). This
80 * is different from the object's main mutex.
82 * Generally speaking, you have to be aware of side effects when running
83 * vm_page ops. A vm_page_lookup() will return with the hash chain
84 * locked, whether it was able to lookup the page or not. vm_page_free(),
85 * vm_page_cache(), vm_page_activate(), and a number of other routines
86 * will release the hash chain mutex for you. Intermediate manipulation
87 * routines such as vm_page_flag_set() expect the hash chain to be held
88 * on entry and the hash chain will remain held on return.
90 * pageq scanning can only occur with the pageq in question locked.
91 * We have a known bottleneck with the active queue, but the cache
92 * and free queues are actually arrays already.
96 * Resident memory management module.
99 #include <sys/cdefs.h>
100 __FBSDID("$FreeBSD$");
102 #include <sys/param.h>
103 #include <sys/systm.h>
104 #include <sys/lock.h>
105 #include <sys/kernel.h>
106 #include <sys/malloc.h>
107 #include <sys/mutex.h>
108 #include <sys/proc.h>
109 #include <sys/sysctl.h>
110 #include <sys/vmmeter.h>
111 #include <sys/vnode.h>
114 #include <vm/vm_param.h>
115 #include <vm/vm_kern.h>
116 #include <vm/vm_object.h>
117 #include <vm/vm_page.h>
118 #include <vm/vm_pageout.h>
119 #include <vm/vm_pager.h>
120 #include <vm/vm_extern.h>
122 #include <vm/uma_int.h>
125 * Associated with page of user-allocatable memory is a
129 struct mtx vm_page_queue_mtx;
130 struct mtx vm_page_queue_free_mtx;
132 vm_page_t vm_page_array = 0;
133 int vm_page_array_size = 0;
135 int vm_page_zero_count = 0;
137 static int boot_pages = UMA_BOOT_PAGES;
138 TUNABLE_INT("vm.boot_pages", &boot_pages);
139 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RD, &boot_pages, 0,
140 "number of pages allocated for bootstrapping the VM system");
145 * Sets the page size, perhaps based upon the memory
146 * size. Must be called before any use of page-size
147 * dependent functions.
150 vm_set_page_size(void)
152 if (cnt.v_page_size == 0)
153 cnt.v_page_size = PAGE_SIZE;
154 if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0)
155 panic("vm_set_page_size: page size not a power of two");
161 * Initializes the resident memory module.
163 * Allocates memory for the page cells, and
164 * for the object/offset-to-page hash table headers.
165 * Each page cell is initialized and placed on the free list.
168 vm_page_startup(vm_offset_t vaddr)
172 vm_paddr_t page_range;
179 /* the biggest memory array is the second group of pages */
181 vm_paddr_t biggestsize;
190 vaddr = round_page(vaddr);
192 for (i = 0; phys_avail[i + 1]; i += 2) {
193 phys_avail[i] = round_page(phys_avail[i]);
194 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
197 for (i = 0; phys_avail[i + 1]; i += 2) {
198 vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
200 if (size > biggestsize) {
208 end = phys_avail[biggestone+1];
211 * Initialize the locks.
213 mtx_init(&vm_page_queue_mtx, "vm page queue mutex", NULL, MTX_DEF |
215 mtx_init(&vm_page_queue_free_mtx, "vm page queue free mutex", NULL,
219 * Initialize the queue headers for the free queue, the active queue
220 * and the inactive queue.
225 * Allocate memory for use when boot strapping the kernel memory
228 new_end = end - (boot_pages * UMA_SLAB_SIZE);
229 new_end = trunc_page(new_end);
230 mapped = pmap_map(&vaddr, new_end, end,
231 VM_PROT_READ | VM_PROT_WRITE);
232 bzero((caddr_t) mapped, end - new_end);
233 uma_startup((caddr_t)mapped);
236 * Compute the number of pages of memory that will be available for
237 * use (taking into account the overhead of a page structure per
240 first_page = phys_avail[0] / PAGE_SIZE;
241 page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE - first_page;
242 npages = (total - (page_range * sizeof(struct vm_page)) -
243 (end - new_end)) / PAGE_SIZE;
247 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
252 * Initialize the mem entry structures now, and put them in the free
255 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
256 mapped = pmap_map(&vaddr, new_end, end,
257 VM_PROT_READ | VM_PROT_WRITE);
258 vm_page_array = (vm_page_t) mapped;
259 phys_avail[biggestone + 1] = new_end;
262 * Clear all of the page structures
264 bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
265 vm_page_array_size = page_range;
268 * Construct the free queue(s) in descending order (by physical
269 * address) so that the first 16MB of physical memory is allocated
270 * last rather than first. On large-memory machines, this avoids
271 * the exhaustion of low physical memory before isa_dma_init has run.
273 cnt.v_page_count = 0;
274 cnt.v_free_count = 0;
275 for (i = 0; phys_avail[i + 1] && npages > 0; i += 2) {
277 last_pa = phys_avail[i + 1];
278 while (pa < last_pa && npages-- > 0) {
279 vm_pageq_add_new_page(pa);
287 vm_page_flag_set(vm_page_t m, unsigned short bits)
290 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
295 vm_page_flag_clear(vm_page_t m, unsigned short bits)
298 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
303 vm_page_busy(vm_page_t m)
306 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
307 KASSERT((m->flags & PG_BUSY) == 0,
308 ("vm_page_busy: page already busy!!!"));
309 vm_page_flag_set(m, PG_BUSY);
315 * wakeup anyone waiting for the page.
318 vm_page_flash(vm_page_t m)
321 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
322 if (m->flags & PG_WANTED) {
323 vm_page_flag_clear(m, PG_WANTED);
331 * clear the PG_BUSY flag and wakeup anyone waiting for the
336 vm_page_wakeup(vm_page_t m)
339 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
340 KASSERT(m->flags & PG_BUSY, ("vm_page_wakeup: page not busy!!!"));
341 vm_page_flag_clear(m, PG_BUSY);
346 vm_page_io_start(vm_page_t m)
349 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
354 vm_page_io_finish(vm_page_t m)
357 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
358 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
365 * Keep page from being freed by the page daemon
366 * much of the same effect as wiring, except much lower
367 * overhead and should be used only for *very* temporary
368 * holding ("wiring").
371 vm_page_hold(vm_page_t mem)
374 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
379 vm_page_unhold(vm_page_t mem)
382 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
384 KASSERT(mem->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!"));
385 if (mem->hold_count == 0 && mem->queue == PQ_HOLD)
386 vm_page_free_toq(mem);
394 * The clearing of PG_ZERO is a temporary safety until the code can be
395 * reviewed to determine that PG_ZERO is being properly cleared on
396 * write faults or maps. PG_ZERO was previously cleared in
400 vm_page_free(vm_page_t m)
402 vm_page_flag_clear(m, PG_ZERO);
404 vm_page_zero_idle_wakeup();
410 * Free a page to the zerod-pages queue
413 vm_page_free_zero(vm_page_t m)
415 vm_page_flag_set(m, PG_ZERO);
420 * vm_page_sleep_if_busy:
422 * Sleep and release the page queues lock if PG_BUSY is set or,
423 * if also_m_busy is TRUE, busy is non-zero. Returns TRUE if the
424 * thread slept and the page queues lock was released.
425 * Otherwise, retains the page queues lock and returns FALSE.
428 vm_page_sleep_if_busy(vm_page_t m, int also_m_busy, const char *msg)
432 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
433 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
434 if ((m->flags & PG_BUSY) || (also_m_busy && m->busy)) {
435 vm_page_flag_set(m, PG_WANTED | PG_REFERENCED);
437 * It's possible that while we sleep, the page will get
438 * unbusied and freed. If we are holding the object
439 * lock, we will assume we hold a reference to the object
440 * such that even if m->object changes, we can re-lock
444 VM_OBJECT_UNLOCK(object);
445 msleep(m, &vm_page_queue_mtx, PDROP | PVM, msg, 0);
446 VM_OBJECT_LOCK(object);
455 * make page all dirty
458 vm_page_dirty(vm_page_t m)
460 KASSERT(m->queue - m->pc != PQ_CACHE,
461 ("vm_page_dirty: page in cache!"));
462 KASSERT(m->queue - m->pc != PQ_FREE,
463 ("vm_page_dirty: page is free!"));
464 m->dirty = VM_PAGE_BITS_ALL;
470 * Implements Sleator and Tarjan's top-down splay algorithm. Returns
471 * the vm_page containing the given pindex. If, however, that
472 * pindex is not found in the vm_object, returns a vm_page that is
473 * adjacent to the pindex, coming before or after it.
476 vm_page_splay(vm_pindex_t pindex, vm_page_t root)
478 struct vm_page dummy;
479 vm_page_t lefttreemax, righttreemin, y;
483 lefttreemax = righttreemin = &dummy;
485 if (pindex < root->pindex) {
486 if ((y = root->left) == NULL)
488 if (pindex < y->pindex) {
490 root->left = y->right;
493 if ((y = root->left) == NULL)
496 /* Link into the new root's right tree. */
497 righttreemin->left = root;
499 } else if (pindex > root->pindex) {
500 if ((y = root->right) == NULL)
502 if (pindex > y->pindex) {
504 root->right = y->left;
507 if ((y = root->right) == NULL)
510 /* Link into the new root's left tree. */
511 lefttreemax->right = root;
516 /* Assemble the new root. */
517 lefttreemax->right = root->left;
518 righttreemin->left = root->right;
519 root->left = dummy.right;
520 root->right = dummy.left;
525 * vm_page_insert: [ internal use only ]
527 * Inserts the given mem entry into the object and object list.
529 * The pagetables are not updated but will presumably fault the page
530 * in if necessary, or if a kernel page the caller will at some point
531 * enter the page into the kernel's pmap. We are not allowed to block
532 * here so we *can't* do this anyway.
534 * The object and page must be locked.
535 * This routine may not block.
538 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
542 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
543 if (m->object != NULL)
544 panic("vm_page_insert: page already inserted");
547 * Record the object/offset pair in this page
553 * Now link into the object's ordered list of backed pages.
559 TAILQ_INSERT_TAIL(&object->memq, m, listq);
561 root = vm_page_splay(pindex, root);
562 if (pindex < root->pindex) {
563 m->left = root->left;
566 TAILQ_INSERT_BEFORE(root, m, listq);
567 } else if (pindex == root->pindex)
568 panic("vm_page_insert: offset already allocated");
570 m->right = root->right;
573 TAILQ_INSERT_AFTER(&object->memq, root, m, listq);
577 object->generation++;
580 * show that the object has one more resident page.
582 object->resident_page_count++;
584 * Hold the vnode until the last page is released.
586 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
587 vhold((struct vnode *)object->handle);
590 * Since we are inserting a new and possibly dirty page,
591 * update the object's OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY flags.
593 if (m->flags & PG_WRITEABLE)
594 vm_object_set_writeable_dirty(object);
599 * NOTE: used by device pager as well -wfj
601 * Removes the given mem entry from the object/offset-page
602 * table and the object page list, but do not invalidate/terminate
605 * The object and page must be locked.
606 * The underlying pmap entry (if any) is NOT removed here.
607 * This routine may not block.
610 vm_page_remove(vm_page_t m)
615 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
616 if ((object = m->object) == NULL)
618 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
619 if (m->flags & PG_BUSY) {
620 vm_page_flag_clear(m, PG_BUSY);
625 * Now remove from the object's list of backed pages.
627 if (m != object->root)
628 vm_page_splay(m->pindex, object->root);
632 root = vm_page_splay(m->pindex, m->left);
633 root->right = m->right;
636 TAILQ_REMOVE(&object->memq, m, listq);
639 * And show that the object has one fewer resident page.
641 object->resident_page_count--;
642 object->generation++;
644 * The vnode may now be recycled.
646 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
647 vdrop((struct vnode *)object->handle);
655 * Returns the page associated with the object/offset
656 * pair specified; if none is found, NULL is returned.
658 * The object must be locked.
659 * This routine may not block.
660 * This is a critical path routine
663 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
667 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
668 if ((m = object->root) != NULL && m->pindex != pindex) {
669 m = vm_page_splay(pindex, m);
670 if ((object->root = m)->pindex != pindex)
679 * Move the given memory entry from its
680 * current object to the specified target object/offset.
682 * The object must be locked.
683 * This routine may not block.
685 * Note: swap associated with the page must be invalidated by the move. We
686 * have to do this for several reasons: (1) we aren't freeing the
687 * page, (2) we are dirtying the page, (3) the VM system is probably
688 * moving the page from object A to B, and will then later move
689 * the backing store from A to B and we can't have a conflict.
691 * Note: we *always* dirty the page. It is necessary both for the
692 * fact that we moved it, and because we may be invalidating
693 * swap. If the page is on the cache, we have to deactivate it
694 * or vm_page_dirty() will panic. Dirty pages are not allowed
698 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
702 vm_page_insert(m, new_object, new_pindex);
703 if (m->queue - m->pc == PQ_CACHE)
704 vm_page_deactivate(m);
709 * vm_page_select_cache:
711 * Move a page of the given color from the cache queue to the free
712 * queue. As pages might be found, but are not applicable, they are
715 * This routine may not block.
718 vm_page_select_cache(int color)
722 boolean_t was_trylocked;
724 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
725 while ((m = vm_pageq_find(PQ_CACHE, color, FALSE)) != NULL) {
726 KASSERT(m->dirty == 0, ("Found dirty cache page %p", m));
727 KASSERT(!pmap_page_is_mapped(m),
728 ("Found mapped cache page %p", m));
729 KASSERT((m->flags & PG_UNMANAGED) == 0,
730 ("Found unmanaged cache page %p", m));
731 KASSERT(m->wire_count == 0, ("Found wired cache page %p", m));
732 if (m->hold_count == 0 && (object = m->object,
733 (was_trylocked = VM_OBJECT_TRYLOCK(object)) ||
734 VM_OBJECT_LOCKED(object))) {
735 KASSERT((m->flags & PG_BUSY) == 0 && m->busy == 0,
736 ("Found busy cache page %p", m));
739 VM_OBJECT_UNLOCK(object);
742 vm_page_deactivate(m);
750 * Allocate and return a memory cell associated
751 * with this VM object/offset pair.
754 * VM_ALLOC_NORMAL normal process request
755 * VM_ALLOC_SYSTEM system *really* needs a page
756 * VM_ALLOC_INTERRUPT interrupt time request
757 * VM_ALLOC_ZERO zero page
759 * This routine may not block.
761 * Additional special handling is required when called from an
762 * interrupt (VM_ALLOC_INTERRUPT). We are not allowed to mess with
763 * the page cache in this case.
766 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
769 int color, flags, page_req;
771 page_req = req & VM_ALLOC_CLASS_MASK;
772 KASSERT(curthread->td_intr_nesting_level == 0 ||
773 page_req == VM_ALLOC_INTERRUPT,
774 ("vm_page_alloc(NORMAL|SYSTEM) in interrupt context"));
776 if ((req & VM_ALLOC_NOOBJ) == 0) {
777 KASSERT(object != NULL,
778 ("vm_page_alloc: NULL object."));
779 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
780 color = (pindex + object->pg_color) & PQ_L2_MASK;
782 color = pindex & PQ_L2_MASK;
785 * The pager is allowed to eat deeper into the free page list.
787 if ((curproc == pageproc) && (page_req != VM_ALLOC_INTERRUPT)) {
788 page_req = VM_ALLOC_SYSTEM;
792 mtx_lock_spin(&vm_page_queue_free_mtx);
793 if (cnt.v_free_count > cnt.v_free_reserved ||
794 (page_req == VM_ALLOC_SYSTEM &&
795 cnt.v_cache_count == 0 &&
796 cnt.v_free_count > cnt.v_interrupt_free_min) ||
797 (page_req == VM_ALLOC_INTERRUPT && cnt.v_free_count > 0)) {
799 * Allocate from the free queue if the number of free pages
800 * exceeds the minimum for the request class.
802 m = vm_pageq_find(PQ_FREE, color, (req & VM_ALLOC_ZERO) != 0);
803 } else if (page_req != VM_ALLOC_INTERRUPT) {
804 mtx_unlock_spin(&vm_page_queue_free_mtx);
806 * Allocatable from cache (non-interrupt only). On success,
807 * we must free the page and try again, thus ensuring that
808 * cnt.v_*_free_min counters are replenished.
810 vm_page_lock_queues();
811 if ((m = vm_page_select_cache(color)) == NULL) {
812 #if defined(DIAGNOSTIC)
813 if (cnt.v_cache_count > 0)
814 printf("vm_page_alloc(NORMAL): missing pages on cache queue: %d\n", cnt.v_cache_count);
816 vm_page_unlock_queues();
817 atomic_add_int(&vm_pageout_deficit, 1);
821 vm_page_unlock_queues();
825 * Not allocatable from cache from interrupt, give up.
827 mtx_unlock_spin(&vm_page_queue_free_mtx);
828 atomic_add_int(&vm_pageout_deficit, 1);
834 * At this point we had better have found a good page.
839 ("vm_page_alloc(): missing page on free queue")
843 * Remove from free queue
845 vm_pageq_remove_nowakeup(m);
848 * Initialize structure. Only the PG_ZERO flag is inherited.
851 if (m->flags & PG_ZERO) {
852 vm_page_zero_count--;
853 if (req & VM_ALLOC_ZERO)
854 flags = PG_ZERO | PG_BUSY;
856 if (req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ))
859 if (req & VM_ALLOC_WIRED) {
860 atomic_add_int(&cnt.v_wire_count, 1);
868 KASSERT(m->dirty == 0, ("vm_page_alloc: free/cache page %p was dirty", m));
869 mtx_unlock_spin(&vm_page_queue_free_mtx);
871 if ((req & VM_ALLOC_NOOBJ) == 0)
872 vm_page_insert(m, object, pindex);
877 * Don't wakeup too often - wakeup the pageout daemon when
878 * we would be nearly out of memory.
880 if (vm_paging_needed())
887 * vm_wait: (also see VM_WAIT macro)
889 * Block until free pages are available for allocation
890 * - Called in various places before memory allocations.
896 vm_page_lock_queues();
897 if (curproc == pageproc) {
898 vm_pageout_pages_needed = 1;
899 msleep(&vm_pageout_pages_needed, &vm_page_queue_mtx,
900 PDROP | PSWP, "VMWait", 0);
902 if (!vm_pages_needed) {
904 wakeup(&vm_pages_needed);
906 msleep(&cnt.v_free_count, &vm_page_queue_mtx, PDROP | PVM,
912 * vm_waitpfault: (also see VM_WAITPFAULT macro)
914 * Block until free pages are available for allocation
915 * - Called only in vm_fault so that processes page faulting
916 * can be easily tracked.
917 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
918 * processes will be able to grab memory first. Do not change
919 * this balance without careful testing first.
925 vm_page_lock_queues();
926 if (!vm_pages_needed) {
928 wakeup(&vm_pages_needed);
930 msleep(&cnt.v_free_count, &vm_page_queue_mtx, PDROP | PUSER,
937 * Put the specified page on the active list (if appropriate).
938 * Ensure that act_count is at least ACT_INIT but do not otherwise
941 * The page queues must be locked.
942 * This routine may not block.
945 vm_page_activate(vm_page_t m)
948 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
949 if (m->queue != PQ_ACTIVE) {
950 if ((m->queue - m->pc) == PQ_CACHE)
953 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
954 if (m->act_count < ACT_INIT)
955 m->act_count = ACT_INIT;
956 vm_pageq_enqueue(PQ_ACTIVE, m);
959 if (m->act_count < ACT_INIT)
960 m->act_count = ACT_INIT;
965 * vm_page_free_wakeup:
967 * Helper routine for vm_page_free_toq() and vm_page_cache(). This
968 * routine is called when a page has been added to the cache or free
971 * The page queues must be locked.
972 * This routine may not block.
975 vm_page_free_wakeup(void)
978 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
980 * if pageout daemon needs pages, then tell it that there are
983 if (vm_pageout_pages_needed &&
984 cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
985 wakeup(&vm_pageout_pages_needed);
986 vm_pageout_pages_needed = 0;
989 * wakeup processes that are waiting on memory if we hit a
990 * high water mark. And wakeup scheduler process if we have
991 * lots of memory. this process will swapin processes.
993 if (vm_pages_needed && !vm_page_count_min()) {
995 wakeup(&cnt.v_free_count);
1002 * Returns the given page to the PQ_FREE list,
1003 * disassociating it with any VM object.
1005 * Object and page must be locked prior to entry.
1006 * This routine may not block.
1010 vm_page_free_toq(vm_page_t m)
1012 struct vpgqueues *pq;
1014 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1017 if (m->busy || ((m->queue - m->pc) == PQ_FREE)) {
1019 "vm_page_free: pindex(%lu), busy(%d), PG_BUSY(%d), hold(%d)\n",
1020 (u_long)m->pindex, m->busy, (m->flags & PG_BUSY) ? 1 : 0,
1022 if ((m->queue - m->pc) == PQ_FREE)
1023 panic("vm_page_free: freeing free page");
1025 panic("vm_page_free: freeing busy page");
1029 * unqueue, then remove page. Note that we cannot destroy
1030 * the page here because we do not want to call the pager's
1031 * callback routine until after we've put the page on the
1032 * appropriate free queue.
1034 vm_pageq_remove_nowakeup(m);
1038 * If fictitious remove object association and
1039 * return, otherwise delay object association removal.
1041 if ((m->flags & PG_FICTITIOUS) != 0) {
1048 if (m->wire_count != 0) {
1049 if (m->wire_count > 1) {
1050 panic("vm_page_free: invalid wire count (%d), pindex: 0x%lx",
1051 m->wire_count, (long)m->pindex);
1053 panic("vm_page_free: freeing wired page");
1057 * Clear the UNMANAGED flag when freeing an unmanaged page.
1059 if (m->flags & PG_UNMANAGED) {
1060 m->flags &= ~PG_UNMANAGED;
1063 if (m->hold_count != 0) {
1064 m->flags &= ~PG_ZERO;
1067 m->queue = PQ_FREE + m->pc;
1068 pq = &vm_page_queues[m->queue];
1069 mtx_lock_spin(&vm_page_queue_free_mtx);
1074 * Put zero'd pages on the end ( where we look for zero'd pages
1075 * first ) and non-zerod pages at the head.
1077 if (m->flags & PG_ZERO) {
1078 TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
1079 ++vm_page_zero_count;
1081 TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
1083 mtx_unlock_spin(&vm_page_queue_free_mtx);
1084 vm_page_free_wakeup();
1090 * Prevent PV management from being done on the page. The page is
1091 * removed from the paging queues as if it were wired, and as a
1092 * consequence of no longer being managed the pageout daemon will not
1093 * touch it (since there is no way to locate the pte mappings for the
1094 * page). madvise() calls that mess with the pmap will also no longer
1095 * operate on the page.
1097 * Beyond that the page is still reasonably 'normal'. Freeing the page
1098 * will clear the flag.
1100 * This routine is used by OBJT_PHYS objects - objects using unswappable
1101 * physical memory as backing store rather then swap-backed memory and
1102 * will eventually be extended to support 4MB unmanaged physical
1106 vm_page_unmanage(vm_page_t m)
1109 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1110 if ((m->flags & PG_UNMANAGED) == 0) {
1111 if (m->wire_count == 0)
1114 vm_page_flag_set(m, PG_UNMANAGED);
1120 * Mark this page as wired down by yet
1121 * another map, removing it from paging queues
1124 * The page queues must be locked.
1125 * This routine may not block.
1128 vm_page_wire(vm_page_t m)
1132 * Only bump the wire statistics if the page is not already wired,
1133 * and only unqueue the page if it is on some queue (if it is unmanaged
1134 * it is already off the queues).
1136 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1137 if (m->flags & PG_FICTITIOUS)
1139 if (m->wire_count == 0) {
1140 if ((m->flags & PG_UNMANAGED) == 0)
1142 atomic_add_int(&cnt.v_wire_count, 1);
1145 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
1151 * Release one wiring of this page, potentially
1152 * enabling it to be paged again.
1154 * Many pages placed on the inactive queue should actually go
1155 * into the cache, but it is difficult to figure out which. What
1156 * we do instead, if the inactive target is well met, is to put
1157 * clean pages at the head of the inactive queue instead of the tail.
1158 * This will cause them to be moved to the cache more quickly and
1159 * if not actively re-referenced, freed more quickly. If we just
1160 * stick these pages at the end of the inactive queue, heavy filesystem
1161 * meta-data accesses can cause an unnecessary paging load on memory bound
1162 * processes. This optimization causes one-time-use metadata to be
1163 * reused more quickly.
1165 * BUT, if we are in a low-memory situation we have no choice but to
1166 * put clean pages on the cache queue.
1168 * A number of routines use vm_page_unwire() to guarantee that the page
1169 * will go into either the inactive or active queues, and will NEVER
1170 * be placed in the cache - for example, just after dirtying a page.
1171 * dirty pages in the cache are not allowed.
1173 * The page queues must be locked.
1174 * This routine may not block.
1177 vm_page_unwire(vm_page_t m, int activate)
1180 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1181 if (m->flags & PG_FICTITIOUS)
1183 if (m->wire_count > 0) {
1185 if (m->wire_count == 0) {
1186 atomic_subtract_int(&cnt.v_wire_count, 1);
1187 if (m->flags & PG_UNMANAGED) {
1189 } else if (activate)
1190 vm_pageq_enqueue(PQ_ACTIVE, m);
1192 vm_page_flag_clear(m, PG_WINATCFLS);
1193 vm_pageq_enqueue(PQ_INACTIVE, m);
1197 panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
1203 * Move the specified page to the inactive queue. If the page has
1204 * any associated swap, the swap is deallocated.
1206 * Normally athead is 0 resulting in LRU operation. athead is set
1207 * to 1 if we want this page to be 'as if it were placed in the cache',
1208 * except without unmapping it from the process address space.
1210 * This routine may not block.
1212 static __inline void
1213 _vm_page_deactivate(vm_page_t m, int athead)
1216 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1219 * Ignore if already inactive.
1221 if (m->queue == PQ_INACTIVE)
1223 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1224 if ((m->queue - m->pc) == PQ_CACHE)
1225 cnt.v_reactivated++;
1226 vm_page_flag_clear(m, PG_WINATCFLS);
1229 TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1231 TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1232 m->queue = PQ_INACTIVE;
1233 vm_page_queues[PQ_INACTIVE].lcnt++;
1234 cnt.v_inactive_count++;
1239 vm_page_deactivate(vm_page_t m)
1241 _vm_page_deactivate(m, 0);
1245 * vm_page_try_to_cache:
1247 * Returns 0 on failure, 1 on success
1250 vm_page_try_to_cache(vm_page_t m)
1253 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1254 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1255 if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1256 (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1267 * vm_page_try_to_free()
1269 * Attempt to free the page. If we cannot free it, we do nothing.
1270 * 1 is returned on success, 0 on failure.
1273 vm_page_try_to_free(vm_page_t m)
1276 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1277 if (m->object != NULL)
1278 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1279 if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1280 (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1293 * Put the specified page onto the page cache queue (if appropriate).
1295 * This routine may not block.
1298 vm_page_cache(vm_page_t m)
1301 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1302 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1303 if ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy ||
1304 m->hold_count || m->wire_count) {
1305 printf("vm_page_cache: attempting to cache busy page\n");
1308 if ((m->queue - m->pc) == PQ_CACHE)
1312 * Remove all pmaps and indicate that the page is not
1313 * writeable or mapped.
1316 if (m->dirty != 0) {
1317 panic("vm_page_cache: caching a dirty page, pindex: %ld",
1320 vm_pageq_remove_nowakeup(m);
1321 vm_pageq_enqueue(PQ_CACHE + m->pc, m);
1322 vm_page_free_wakeup();
1328 * Cache, deactivate, or do nothing as appropriate. This routine
1329 * is typically used by madvise() MADV_DONTNEED.
1331 * Generally speaking we want to move the page into the cache so
1332 * it gets reused quickly. However, this can result in a silly syndrome
1333 * due to the page recycling too quickly. Small objects will not be
1334 * fully cached. On the otherhand, if we move the page to the inactive
1335 * queue we wind up with a problem whereby very large objects
1336 * unnecessarily blow away our inactive and cache queues.
1338 * The solution is to move the pages based on a fixed weighting. We
1339 * either leave them alone, deactivate them, or move them to the cache,
1340 * where moving them to the cache has the highest weighting.
1341 * By forcing some pages into other queues we eventually force the
1342 * system to balance the queues, potentially recovering other unrelated
1343 * space from active. The idea is to not force this to happen too
1347 vm_page_dontneed(vm_page_t m)
1349 static int dnweight;
1353 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1357 * occassionally leave the page alone
1359 if ((dnw & 0x01F0) == 0 ||
1360 m->queue == PQ_INACTIVE ||
1361 m->queue - m->pc == PQ_CACHE
1363 if (m->act_count >= ACT_INIT)
1368 if (m->dirty == 0 && pmap_is_modified(m))
1371 if (m->dirty || (dnw & 0x0070) == 0) {
1373 * Deactivate the page 3 times out of 32.
1378 * Cache the page 28 times out of every 32. Note that
1379 * the page is deactivated instead of cached, but placed
1380 * at the head of the queue instead of the tail.
1384 _vm_page_deactivate(m, head);
1388 * Grab a page, waiting until we are waken up due to the page
1389 * changing state. We keep on waiting, if the page continues
1390 * to be in the object. If the page doesn't exist, first allocate it
1391 * and then conditionally zero it.
1393 * This routine may block.
1396 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
1400 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1402 if ((m = vm_page_lookup(object, pindex)) != NULL) {
1403 vm_page_lock_queues();
1404 if (m->busy || (m->flags & PG_BUSY)) {
1405 vm_page_flag_set(m, PG_WANTED | PG_REFERENCED);
1406 VM_OBJECT_UNLOCK(object);
1407 msleep(m, &vm_page_queue_mtx, PDROP | PVM, "pgrbwt", 0);
1408 VM_OBJECT_LOCK(object);
1409 if ((allocflags & VM_ALLOC_RETRY) == 0)
1413 if (allocflags & VM_ALLOC_WIRED)
1415 if ((allocflags & VM_ALLOC_NOBUSY) == 0)
1417 vm_page_unlock_queues();
1421 m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_RETRY);
1423 VM_OBJECT_UNLOCK(object);
1425 VM_OBJECT_LOCK(object);
1426 if ((allocflags & VM_ALLOC_RETRY) == 0)
1430 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
1436 * Mapping function for valid bits or for dirty bits in
1437 * a page. May not block.
1439 * Inputs are required to range within a page.
1442 vm_page_bits(int base, int size)
1448 base + size <= PAGE_SIZE,
1449 ("vm_page_bits: illegal base/size %d/%d", base, size)
1452 if (size == 0) /* handle degenerate case */
1455 first_bit = base >> DEV_BSHIFT;
1456 last_bit = (base + size - 1) >> DEV_BSHIFT;
1458 return ((2 << last_bit) - (1 << first_bit));
1462 * vm_page_set_validclean:
1464 * Sets portions of a page valid and clean. The arguments are expected
1465 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
1466 * of any partial chunks touched by the range. The invalid portion of
1467 * such chunks will be zero'd.
1469 * This routine may not block.
1471 * (base + size) must be less then or equal to PAGE_SIZE.
1474 vm_page_set_validclean(vm_page_t m, int base, int size)
1480 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1481 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1482 if (size == 0) /* handle degenerate case */
1486 * If the base is not DEV_BSIZE aligned and the valid
1487 * bit is clear, we have to zero out a portion of the
1490 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
1491 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
1492 pmap_zero_page_area(m, frag, base - frag);
1495 * If the ending offset is not DEV_BSIZE aligned and the
1496 * valid bit is clear, we have to zero out a portion of
1499 endoff = base + size;
1500 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
1501 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
1502 pmap_zero_page_area(m, endoff,
1503 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
1506 * Set valid, clear dirty bits. If validating the entire
1507 * page we can safely clear the pmap modify bit. We also
1508 * use this opportunity to clear the PG_NOSYNC flag. If a process
1509 * takes a write fault on a MAP_NOSYNC memory area the flag will
1512 * We set valid bits inclusive of any overlap, but we can only
1513 * clear dirty bits for DEV_BSIZE chunks that are fully within
1516 pagebits = vm_page_bits(base, size);
1517 m->valid |= pagebits;
1519 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
1520 frag = DEV_BSIZE - frag;
1526 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
1528 m->dirty &= ~pagebits;
1529 if (base == 0 && size == PAGE_SIZE) {
1530 pmap_clear_modify(m);
1531 vm_page_flag_clear(m, PG_NOSYNC);
1536 vm_page_clear_dirty(vm_page_t m, int base, int size)
1539 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1540 m->dirty &= ~vm_page_bits(base, size);
1544 * vm_page_set_invalid:
1546 * Invalidates DEV_BSIZE'd chunks within a page. Both the
1547 * valid and dirty bits for the effected areas are cleared.
1552 vm_page_set_invalid(vm_page_t m, int base, int size)
1556 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1557 bits = vm_page_bits(base, size);
1558 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1561 m->object->generation++;
1565 * vm_page_zero_invalid()
1567 * The kernel assumes that the invalid portions of a page contain
1568 * garbage, but such pages can be mapped into memory by user code.
1569 * When this occurs, we must zero out the non-valid portions of the
1570 * page so user code sees what it expects.
1572 * Pages are most often semi-valid when the end of a file is mapped
1573 * into memory and the file's size is not page aligned.
1576 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
1581 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1583 * Scan the valid bits looking for invalid sections that
1584 * must be zerod. Invalid sub-DEV_BSIZE'd areas ( where the
1585 * valid bit may be set ) have already been zerod by
1586 * vm_page_set_validclean().
1588 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
1589 if (i == (PAGE_SIZE / DEV_BSIZE) ||
1590 (m->valid & (1 << i))
1593 pmap_zero_page_area(m,
1594 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
1601 * setvalid is TRUE when we can safely set the zero'd areas
1602 * as being valid. We can do this if there are no cache consistancy
1603 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
1606 m->valid = VM_PAGE_BITS_ALL;
1612 * Is (partial) page valid? Note that the case where size == 0
1613 * will return FALSE in the degenerate case where the page is
1614 * entirely invalid, and TRUE otherwise.
1619 vm_page_is_valid(vm_page_t m, int base, int size)
1621 int bits = vm_page_bits(base, size);
1623 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1624 if (m->valid && ((m->valid & bits) == bits))
1631 * update dirty bits from pmap/mmu. May not block.
1634 vm_page_test_dirty(vm_page_t m)
1636 if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
1641 int so_zerocp_fullpage = 0;
1644 vm_page_cowfault(vm_page_t m)
1655 mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL);
1657 vm_page_insert(m, object, pindex);
1658 vm_page_unlock_queues();
1659 VM_OBJECT_UNLOCK(object);
1661 VM_OBJECT_LOCK(object);
1662 vm_page_lock_queues();
1668 * check to see if we raced with an xmit complete when
1669 * waiting to allocate a page. If so, put things back
1673 vm_page_insert(m, object, pindex);
1674 } else { /* clear COW & copy page */
1675 if (!so_zerocp_fullpage)
1676 pmap_copy_page(m, mnew);
1677 mnew->valid = VM_PAGE_BITS_ALL;
1678 vm_page_dirty(mnew);
1679 vm_page_flag_clear(mnew, PG_BUSY);
1684 vm_page_cowclear(vm_page_t m)
1687 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1691 * let vm_fault add back write permission lazily
1695 * sf_buf_free() will free the page, so we needn't do it here
1700 vm_page_cowsetup(vm_page_t m)
1703 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1705 pmap_page_protect(m, VM_PROT_READ);
1708 #include "opt_ddb.h"
1710 #include <sys/kernel.h>
1712 #include <ddb/ddb.h>
1714 DB_SHOW_COMMAND(page, vm_page_print_page_info)
1716 db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
1717 db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
1718 db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
1719 db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
1720 db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
1721 db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
1722 db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
1723 db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
1724 db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
1725 db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
1728 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
1731 db_printf("PQ_FREE:");
1732 for (i = 0; i < PQ_L2_SIZE; i++) {
1733 db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt);
1737 db_printf("PQ_CACHE:");
1738 for (i = 0; i < PQ_L2_SIZE; i++) {
1739 db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt);
1743 db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
1744 vm_page_queues[PQ_ACTIVE].lcnt,
1745 vm_page_queues[PQ_INACTIVE].lcnt);