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/malloc.h>
106 #include <sys/mutex.h>
107 #include <sys/proc.h>
108 #include <sys/vmmeter.h>
109 #include <sys/vnode.h>
112 #include <vm/vm_param.h>
113 #include <vm/vm_kern.h>
114 #include <vm/vm_object.h>
115 #include <vm/vm_page.h>
116 #include <vm/vm_pageout.h>
117 #include <vm/vm_pager.h>
118 #include <vm/vm_extern.h>
120 #include <vm/uma_int.h>
123 * Associated with page of user-allocatable memory is a
127 struct mtx vm_page_queue_mtx;
128 struct mtx vm_page_queue_free_mtx;
130 vm_page_t vm_page_array = 0;
131 int vm_page_array_size = 0;
133 int vm_page_zero_count = 0;
138 * Sets the page size, perhaps based upon the memory
139 * size. Must be called before any use of page-size
140 * dependent functions.
143 vm_set_page_size(void)
145 if (cnt.v_page_size == 0)
146 cnt.v_page_size = PAGE_SIZE;
147 if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0)
148 panic("vm_set_page_size: page size not a power of two");
154 * Initializes the resident memory module.
156 * Allocates memory for the page cells, and
157 * for the object/offset-to-page hash table headers.
158 * Each page cell is initialized and placed on the free list.
161 vm_page_startup(vm_offset_t vaddr)
165 vm_paddr_t page_range;
172 /* the biggest memory array is the second group of pages */
174 vm_paddr_t biggestsize;
184 vaddr = round_page(vaddr);
186 for (i = 0; phys_avail[i + 1]; i += 2) {
187 phys_avail[i] = round_page(phys_avail[i]);
188 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
191 for (i = 0; phys_avail[i + 1]; i += 2) {
192 vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
194 if (size > biggestsize) {
202 end = phys_avail[biggestone+1];
205 * Initialize the locks.
207 mtx_init(&vm_page_queue_mtx, "vm page queue mutex", NULL, MTX_DEF |
209 mtx_init(&vm_page_queue_free_mtx, "vm page queue free mutex", NULL,
213 * Initialize the queue headers for the free queue, the active queue
214 * and the inactive queue.
219 * Allocate memory for use when boot strapping the kernel memory
222 bootpages = UMA_BOOT_PAGES * UMA_SLAB_SIZE;
223 new_end = end - bootpages;
224 new_end = trunc_page(new_end);
225 mapped = pmap_map(&vaddr, new_end, end,
226 VM_PROT_READ | VM_PROT_WRITE);
227 bzero((caddr_t) mapped, end - new_end);
228 uma_startup((caddr_t)mapped);
231 * Compute the number of pages of memory that will be available for
232 * use (taking into account the overhead of a page structure per
235 first_page = phys_avail[0] / PAGE_SIZE;
236 page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE - first_page;
237 npages = (total - (page_range * sizeof(struct vm_page)) -
238 (end - new_end)) / PAGE_SIZE;
242 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
247 * Initialize the mem entry structures now, and put them in the free
250 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
251 mapped = pmap_map(&vaddr, new_end, end,
252 VM_PROT_READ | VM_PROT_WRITE);
253 vm_page_array = (vm_page_t) mapped;
254 phys_avail[biggestone + 1] = new_end;
257 * Clear all of the page structures
259 bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
260 vm_page_array_size = page_range;
263 * Construct the free queue(s) in descending order (by physical
264 * address) so that the first 16MB of physical memory is allocated
265 * last rather than first. On large-memory machines, this avoids
266 * the exhaustion of low physical memory before isa_dma_init has run.
268 cnt.v_page_count = 0;
269 cnt.v_free_count = 0;
270 for (i = 0; phys_avail[i + 1] && npages > 0; i += 2) {
272 last_pa = phys_avail[i + 1];
273 while (pa < last_pa && npages-- > 0) {
274 vm_pageq_add_new_page(pa);
282 vm_page_flag_set(vm_page_t m, unsigned short bits)
285 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
290 vm_page_flag_clear(vm_page_t m, unsigned short bits)
293 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
298 vm_page_busy(vm_page_t m)
301 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
302 KASSERT((m->flags & PG_BUSY) == 0,
303 ("vm_page_busy: page already busy!!!"));
304 vm_page_flag_set(m, PG_BUSY);
310 * wakeup anyone waiting for the page.
313 vm_page_flash(vm_page_t m)
316 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
317 if (m->flags & PG_WANTED) {
318 vm_page_flag_clear(m, PG_WANTED);
326 * clear the PG_BUSY flag and wakeup anyone waiting for the
331 vm_page_wakeup(vm_page_t m)
334 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
335 KASSERT(m->flags & PG_BUSY, ("vm_page_wakeup: page not busy!!!"));
336 vm_page_flag_clear(m, PG_BUSY);
341 vm_page_io_start(vm_page_t m)
344 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
345 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
350 vm_page_io_finish(vm_page_t m)
353 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
354 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
361 * Keep page from being freed by the page daemon
362 * much of the same effect as wiring, except much lower
363 * overhead and should be used only for *very* temporary
364 * holding ("wiring").
367 vm_page_hold(vm_page_t mem)
370 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
375 vm_page_unhold(vm_page_t mem)
378 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
380 KASSERT(mem->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!"));
381 if (mem->hold_count == 0 && mem->queue == PQ_HOLD)
382 vm_page_free_toq(mem);
390 * The clearing of PG_ZERO is a temporary safety until the code can be
391 * reviewed to determine that PG_ZERO is being properly cleared on
392 * write faults or maps. PG_ZERO was previously cleared in
396 vm_page_free(vm_page_t m)
398 vm_page_flag_clear(m, PG_ZERO);
400 vm_page_zero_idle_wakeup();
406 * Free a page to the zerod-pages queue
409 vm_page_free_zero(vm_page_t m)
411 vm_page_flag_set(m, PG_ZERO);
416 * vm_page_sleep_if_busy:
418 * Sleep and release the page queues lock if PG_BUSY is set or,
419 * if also_m_busy is TRUE, busy is non-zero. Returns TRUE if the
420 * thread slept and the page queues lock was released.
421 * Otherwise, retains the page queues lock and returns FALSE.
424 vm_page_sleep_if_busy(vm_page_t m, int also_m_busy, const char *msg)
427 int is_object_locked;
429 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
430 if ((m->flags & PG_BUSY) || (also_m_busy && m->busy)) {
431 vm_page_flag_set(m, PG_WANTED | PG_REFERENCED);
433 * It's possible that while we sleep, the page will get
434 * unbusied and freed. If we are holding the object
435 * lock, we will assume we hold a reference to the object
436 * such that even if m->object changes, we can re-lock
439 * Remove mtx_owned() after vm_object locking is finished.
442 if ((is_object_locked = object != NULL &&
443 mtx_owned(&object->mtx)))
444 mtx_unlock(&object->mtx);
445 msleep(m, &vm_page_queue_mtx, PDROP | PVM, msg, 0);
446 if (is_object_locked)
447 mtx_lock(&object->mtx);
456 * make page all dirty
459 vm_page_dirty(vm_page_t m)
461 KASSERT(m->queue - m->pc != PQ_CACHE,
462 ("vm_page_dirty: page in cache!"));
463 KASSERT(m->queue - m->pc != PQ_FREE,
464 ("vm_page_dirty: page is free!"));
465 m->dirty = VM_PAGE_BITS_ALL;
471 * Implements Sleator and Tarjan's top-down splay algorithm. Returns
472 * the vm_page containing the given pindex. If, however, that
473 * pindex is not found in the vm_object, returns a vm_page that is
474 * adjacent to the pindex, coming before or after it.
477 vm_page_splay(vm_pindex_t pindex, vm_page_t root)
479 struct vm_page dummy;
480 vm_page_t lefttreemax, righttreemin, y;
484 lefttreemax = righttreemin = &dummy;
486 if (pindex < root->pindex) {
487 if ((y = root->left) == NULL)
489 if (pindex < y->pindex) {
491 root->left = y->right;
494 if ((y = root->left) == NULL)
497 /* Link into the new root's right tree. */
498 righttreemin->left = root;
500 } else if (pindex > root->pindex) {
501 if ((y = root->right) == NULL)
503 if (pindex > y->pindex) {
505 root->right = y->left;
508 if ((y = root->right) == NULL)
511 /* Link into the new root's left tree. */
512 lefttreemax->right = root;
517 /* Assemble the new root. */
518 lefttreemax->right = root->left;
519 righttreemin->left = root->right;
520 root->left = dummy.right;
521 root->right = dummy.left;
526 * vm_page_insert: [ internal use only ]
528 * Inserts the given mem entry into the object and object list.
530 * The pagetables are not updated but will presumably fault the page
531 * in if necessary, or if a kernel page the caller will at some point
532 * enter the page into the kernel's pmap. We are not allowed to block
533 * here so we *can't* do this anyway.
535 * The object and page must be locked.
536 * This routine may not block.
539 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
543 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
544 if (m->object != NULL)
545 panic("vm_page_insert: page already inserted");
548 * Record the object/offset pair in this page
554 * Now link into the object's ordered list of backed pages.
560 TAILQ_INSERT_TAIL(&object->memq, m, listq);
562 root = vm_page_splay(pindex, root);
563 if (pindex < root->pindex) {
564 m->left = root->left;
567 TAILQ_INSERT_BEFORE(root, m, listq);
568 } else if (pindex == root->pindex)
569 panic("vm_page_insert: offset already allocated");
571 m->right = root->right;
574 TAILQ_INSERT_AFTER(&object->memq, root, m, listq);
578 object->generation++;
581 * show that the object has one more resident page.
583 object->resident_page_count++;
586 * Since we are inserting a new and possibly dirty page,
587 * update the object's OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY flags.
589 if (m->flags & PG_WRITEABLE)
590 vm_object_set_writeable_dirty(object);
595 * NOTE: used by device pager as well -wfj
597 * Removes the given mem entry from the object/offset-page
598 * table and the object page list, but do not invalidate/terminate
601 * The object and page must be locked.
602 * The underlying pmap entry (if any) is NOT removed here.
603 * This routine may not block.
606 vm_page_remove(vm_page_t m)
611 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
612 if (m->object == NULL)
614 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
615 if ((m->flags & PG_BUSY) == 0) {
616 panic("vm_page_remove: page not busy");
620 * Basically destroy the page.
627 * Now remove from the object's list of backed pages.
629 if (m != object->root)
630 vm_page_splay(m->pindex, object->root);
634 root = vm_page_splay(m->pindex, m->left);
635 root->right = m->right;
638 TAILQ_REMOVE(&object->memq, m, listq);
641 * And show that the object has one fewer resident page.
643 object->resident_page_count--;
644 object->generation++;
652 * Returns the page associated with the object/offset
653 * pair specified; if none is found, NULL is returned.
655 * The object must be locked.
656 * This routine may not block.
657 * This is a critical path routine
660 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
664 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
665 if ((m = object->root) != NULL && m->pindex != pindex) {
666 m = vm_page_splay(pindex, m);
667 if ((object->root = m)->pindex != pindex)
676 * Move the given memory entry from its
677 * current object to the specified target object/offset.
679 * The object must be locked.
680 * This routine may not block.
682 * Note: swap associated with the page must be invalidated by the move. We
683 * have to do this for several reasons: (1) we aren't freeing the
684 * page, (2) we are dirtying the page, (3) the VM system is probably
685 * moving the page from object A to B, and will then later move
686 * the backing store from A to B and we can't have a conflict.
688 * Note: we *always* dirty the page. It is necessary both for the
689 * fact that we moved it, and because we may be invalidating
690 * swap. If the page is on the cache, we have to deactivate it
691 * or vm_page_dirty() will panic. Dirty pages are not allowed
695 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
699 vm_page_insert(m, new_object, new_pindex);
700 if (m->queue - m->pc == PQ_CACHE)
701 vm_page_deactivate(m);
706 * vm_page_select_cache:
708 * Find a page on the cache queue with color optimization. As pages
709 * might be found, but not applicable, they are deactivated. This
710 * keeps us from using potentially busy cached pages.
712 * This routine may not block.
715 vm_page_select_cache(int color)
719 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
720 while ((m = vm_pageq_find(PQ_CACHE, color, FALSE)) != NULL) {
721 if ((m->flags & PG_BUSY) == 0 && m->busy == 0 &&
722 m->hold_count == 0 && (VM_OBJECT_TRYLOCK(m->object) ||
723 VM_OBJECT_LOCKED(m->object))) {
724 KASSERT(m->dirty == 0,
725 ("Found dirty cache page %p", m));
726 KASSERT(!pmap_page_is_mapped(m),
727 ("Found mapped cache page %p", m));
728 KASSERT((m->flags & PG_UNMANAGED) == 0,
729 ("Found unmanaged cache page %p", m));
730 KASSERT(m->wire_count == 0,
731 ("Found wired cache page %p", m));
734 vm_page_deactivate(m);
742 * Allocate and return a memory cell associated
743 * with this VM object/offset pair.
746 * VM_ALLOC_NORMAL normal process request
747 * VM_ALLOC_SYSTEM system *really* needs a page
748 * VM_ALLOC_INTERRUPT interrupt time request
749 * VM_ALLOC_ZERO zero page
751 * This routine may not block.
753 * Additional special handling is required when called from an
754 * interrupt (VM_ALLOC_INTERRUPT). We are not allowed to mess with
755 * the page cache in this case.
758 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
760 vm_object_t m_object;
762 int color, flags, page_req;
764 page_req = req & VM_ALLOC_CLASS_MASK;
766 if ((req & VM_ALLOC_NOOBJ) == 0) {
767 KASSERT(object != NULL,
768 ("vm_page_alloc: NULL object."));
769 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
770 color = (pindex + object->pg_color) & PQ_L2_MASK;
772 color = pindex & PQ_L2_MASK;
775 * The pager is allowed to eat deeper into the free page list.
777 if ((curproc == pageproc) && (page_req != VM_ALLOC_INTERRUPT)) {
778 page_req = VM_ALLOC_SYSTEM;
782 mtx_lock_spin(&vm_page_queue_free_mtx);
783 if (cnt.v_free_count > cnt.v_free_reserved ||
784 (page_req == VM_ALLOC_SYSTEM &&
785 cnt.v_cache_count == 0 &&
786 cnt.v_free_count > cnt.v_interrupt_free_min) ||
787 (page_req == VM_ALLOC_INTERRUPT && cnt.v_free_count > 0)) {
789 * Allocate from the free queue if the number of free pages
790 * exceeds the minimum for the request class.
792 m = vm_pageq_find(PQ_FREE, color, (req & VM_ALLOC_ZERO) != 0);
793 } else if (page_req != VM_ALLOC_INTERRUPT) {
794 mtx_unlock_spin(&vm_page_queue_free_mtx);
796 * Allocatable from cache (non-interrupt only). On success,
797 * we must free the page and try again, thus ensuring that
798 * cnt.v_*_free_min counters are replenished.
800 vm_page_lock_queues();
801 if ((m = vm_page_select_cache(color)) == NULL) {
802 #if defined(DIAGNOSTIC)
803 if (cnt.v_cache_count > 0)
804 printf("vm_page_alloc(NORMAL): missing pages on cache queue: %d\n", cnt.v_cache_count);
806 vm_page_unlock_queues();
807 atomic_add_int(&vm_pageout_deficit, 1);
811 m_object = m->object;
812 VM_OBJECT_LOCK_ASSERT(m_object, MA_OWNED);
815 vm_page_unlock_queues();
816 if (m_object != object)
817 VM_OBJECT_UNLOCK(m_object);
821 * Not allocatable from cache from interrupt, give up.
823 mtx_unlock_spin(&vm_page_queue_free_mtx);
824 atomic_add_int(&vm_pageout_deficit, 1);
830 * At this point we had better have found a good page.
835 ("vm_page_alloc(): missing page on free queue")
839 * Remove from free queue
841 vm_pageq_remove_nowakeup(m);
844 * Initialize structure. Only the PG_ZERO flag is inherited.
847 if (m->flags & PG_ZERO) {
848 vm_page_zero_count--;
849 if (req & VM_ALLOC_ZERO)
850 flags = PG_ZERO | PG_BUSY;
852 if (req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ))
855 if (req & VM_ALLOC_WIRED) {
856 atomic_add_int(&cnt.v_wire_count, 1);
864 KASSERT(m->dirty == 0, ("vm_page_alloc: free/cache page %p was dirty", m));
865 mtx_unlock_spin(&vm_page_queue_free_mtx);
867 if ((req & VM_ALLOC_NOOBJ) == 0)
868 vm_page_insert(m, object, pindex);
873 * Don't wakeup too often - wakeup the pageout daemon when
874 * we would be nearly out of memory.
876 if (vm_paging_needed())
883 * vm_wait: (also see VM_WAIT macro)
885 * Block until free pages are available for allocation
886 * - Called in various places before memory allocations.
892 vm_page_lock_queues();
893 if (curproc == pageproc) {
894 vm_pageout_pages_needed = 1;
895 msleep(&vm_pageout_pages_needed, &vm_page_queue_mtx,
896 PDROP | PSWP, "VMWait", 0);
898 if (!vm_pages_needed) {
900 wakeup(&vm_pages_needed);
902 msleep(&cnt.v_free_count, &vm_page_queue_mtx, PDROP | PVM,
908 * vm_waitpfault: (also see VM_WAITPFAULT macro)
910 * Block until free pages are available for allocation
911 * - Called only in vm_fault so that processes page faulting
912 * can be easily tracked.
913 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
914 * processes will be able to grab memory first. Do not change
915 * this balance without careful testing first.
921 vm_page_lock_queues();
922 if (!vm_pages_needed) {
924 wakeup(&vm_pages_needed);
926 msleep(&cnt.v_free_count, &vm_page_queue_mtx, PDROP | PUSER,
933 * Put the specified page on the active list (if appropriate).
934 * Ensure that act_count is at least ACT_INIT but do not otherwise
937 * The page queues must be locked.
938 * This routine may not block.
941 vm_page_activate(vm_page_t m)
944 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
945 if (m->queue != PQ_ACTIVE) {
946 if ((m->queue - m->pc) == PQ_CACHE)
949 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
950 if (m->act_count < ACT_INIT)
951 m->act_count = ACT_INIT;
952 vm_pageq_enqueue(PQ_ACTIVE, m);
955 if (m->act_count < ACT_INIT)
956 m->act_count = ACT_INIT;
961 * vm_page_free_wakeup:
963 * Helper routine for vm_page_free_toq() and vm_page_cache(). This
964 * routine is called when a page has been added to the cache or free
967 * The page queues must be locked.
968 * This routine may not block.
971 vm_page_free_wakeup(void)
974 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
976 * if pageout daemon needs pages, then tell it that there are
979 if (vm_pageout_pages_needed &&
980 cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
981 wakeup(&vm_pageout_pages_needed);
982 vm_pageout_pages_needed = 0;
985 * wakeup processes that are waiting on memory if we hit a
986 * high water mark. And wakeup scheduler process if we have
987 * lots of memory. this process will swapin processes.
989 if (vm_pages_needed && !vm_page_count_min()) {
991 wakeup(&cnt.v_free_count);
998 * Returns the given page to the PQ_FREE list,
999 * disassociating it with any VM object.
1001 * Object and page must be locked prior to entry.
1002 * This routine may not block.
1006 vm_page_free_toq(vm_page_t m)
1008 struct vpgqueues *pq;
1009 vm_object_t object = m->object;
1011 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1014 if (m->busy || ((m->queue - m->pc) == PQ_FREE)) {
1016 "vm_page_free: pindex(%lu), busy(%d), PG_BUSY(%d), hold(%d)\n",
1017 (u_long)m->pindex, m->busy, (m->flags & PG_BUSY) ? 1 : 0,
1019 if ((m->queue - m->pc) == PQ_FREE)
1020 panic("vm_page_free: freeing free page");
1022 panic("vm_page_free: freeing busy page");
1026 * unqueue, then remove page. Note that we cannot destroy
1027 * the page here because we do not want to call the pager's
1028 * callback routine until after we've put the page on the
1029 * appropriate free queue.
1031 vm_pageq_remove_nowakeup(m);
1035 * If fictitious remove object association and
1036 * return, otherwise delay object association removal.
1038 if ((m->flags & PG_FICTITIOUS) != 0) {
1045 if (m->wire_count != 0) {
1046 if (m->wire_count > 1) {
1047 panic("vm_page_free: invalid wire count (%d), pindex: 0x%lx",
1048 m->wire_count, (long)m->pindex);
1050 panic("vm_page_free: freeing wired page");
1054 * If we've exhausted the object's resident pages we want to free
1058 (object->type == OBJT_VNODE) &&
1059 ((object->flags & OBJ_DEAD) == 0)
1061 struct vnode *vp = (struct vnode *)object->handle;
1065 if (VSHOULDFREE(vp))
1072 * Clear the UNMANAGED flag when freeing an unmanaged page.
1074 if (m->flags & PG_UNMANAGED) {
1075 m->flags &= ~PG_UNMANAGED;
1078 if (m->hold_count != 0) {
1079 m->flags &= ~PG_ZERO;
1082 m->queue = PQ_FREE + m->pc;
1083 pq = &vm_page_queues[m->queue];
1084 mtx_lock_spin(&vm_page_queue_free_mtx);
1089 * Put zero'd pages on the end ( where we look for zero'd pages
1090 * first ) and non-zerod pages at the head.
1092 if (m->flags & PG_ZERO) {
1093 TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
1094 ++vm_page_zero_count;
1096 TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
1098 mtx_unlock_spin(&vm_page_queue_free_mtx);
1099 vm_page_free_wakeup();
1105 * Prevent PV management from being done on the page. The page is
1106 * removed from the paging queues as if it were wired, and as a
1107 * consequence of no longer being managed the pageout daemon will not
1108 * touch it (since there is no way to locate the pte mappings for the
1109 * page). madvise() calls that mess with the pmap will also no longer
1110 * operate on the page.
1112 * Beyond that the page is still reasonably 'normal'. Freeing the page
1113 * will clear the flag.
1115 * This routine is used by OBJT_PHYS objects - objects using unswappable
1116 * physical memory as backing store rather then swap-backed memory and
1117 * will eventually be extended to support 4MB unmanaged physical
1121 vm_page_unmanage(vm_page_t m)
1124 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1125 if ((m->flags & PG_UNMANAGED) == 0) {
1126 if (m->wire_count == 0)
1129 vm_page_flag_set(m, PG_UNMANAGED);
1135 * Mark this page as wired down by yet
1136 * another map, removing it from paging queues
1139 * The page queues must be locked.
1140 * This routine may not block.
1143 vm_page_wire(vm_page_t m)
1147 * Only bump the wire statistics if the page is not already wired,
1148 * and only unqueue the page if it is on some queue (if it is unmanaged
1149 * it is already off the queues).
1151 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1152 if (m->flags & PG_FICTITIOUS)
1154 if (m->wire_count == 0) {
1155 if ((m->flags & PG_UNMANAGED) == 0)
1157 atomic_add_int(&cnt.v_wire_count, 1);
1160 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
1166 * Release one wiring of this page, potentially
1167 * enabling it to be paged again.
1169 * Many pages placed on the inactive queue should actually go
1170 * into the cache, but it is difficult to figure out which. What
1171 * we do instead, if the inactive target is well met, is to put
1172 * clean pages at the head of the inactive queue instead of the tail.
1173 * This will cause them to be moved to the cache more quickly and
1174 * if not actively re-referenced, freed more quickly. If we just
1175 * stick these pages at the end of the inactive queue, heavy filesystem
1176 * meta-data accesses can cause an unnecessary paging load on memory bound
1177 * processes. This optimization causes one-time-use metadata to be
1178 * reused more quickly.
1180 * BUT, if we are in a low-memory situation we have no choice but to
1181 * put clean pages on the cache queue.
1183 * A number of routines use vm_page_unwire() to guarantee that the page
1184 * will go into either the inactive or active queues, and will NEVER
1185 * be placed in the cache - for example, just after dirtying a page.
1186 * dirty pages in the cache are not allowed.
1188 * The page queues must be locked.
1189 * This routine may not block.
1192 vm_page_unwire(vm_page_t m, int activate)
1195 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1196 if (m->flags & PG_FICTITIOUS)
1198 if (m->wire_count > 0) {
1200 if (m->wire_count == 0) {
1201 atomic_subtract_int(&cnt.v_wire_count, 1);
1202 if (m->flags & PG_UNMANAGED) {
1204 } else if (activate)
1205 vm_pageq_enqueue(PQ_ACTIVE, m);
1207 vm_page_flag_clear(m, PG_WINATCFLS);
1208 vm_pageq_enqueue(PQ_INACTIVE, m);
1212 panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
1218 * Move the specified page to the inactive queue. If the page has
1219 * any associated swap, the swap is deallocated.
1221 * Normally athead is 0 resulting in LRU operation. athead is set
1222 * to 1 if we want this page to be 'as if it were placed in the cache',
1223 * except without unmapping it from the process address space.
1225 * This routine may not block.
1227 static __inline void
1228 _vm_page_deactivate(vm_page_t m, int athead)
1231 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1234 * Ignore if already inactive.
1236 if (m->queue == PQ_INACTIVE)
1238 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1239 if ((m->queue - m->pc) == PQ_CACHE)
1240 cnt.v_reactivated++;
1241 vm_page_flag_clear(m, PG_WINATCFLS);
1244 TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1246 TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1247 m->queue = PQ_INACTIVE;
1248 vm_page_queues[PQ_INACTIVE].lcnt++;
1249 cnt.v_inactive_count++;
1254 vm_page_deactivate(vm_page_t m)
1256 _vm_page_deactivate(m, 0);
1260 * vm_page_try_to_cache:
1262 * Returns 0 on failure, 1 on success
1265 vm_page_try_to_cache(vm_page_t m)
1268 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1269 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1270 if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1271 (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1282 * vm_page_try_to_free()
1284 * Attempt to free the page. If we cannot free it, we do nothing.
1285 * 1 is returned on success, 0 on failure.
1288 vm_page_try_to_free(vm_page_t m)
1291 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1292 if (m->object != NULL)
1293 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1294 if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1295 (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1309 * Put the specified page onto the page cache queue (if appropriate).
1311 * This routine may not block.
1314 vm_page_cache(vm_page_t m)
1317 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1318 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1319 if ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy ||
1320 m->hold_count || m->wire_count) {
1321 printf("vm_page_cache: attempting to cache busy page\n");
1324 if ((m->queue - m->pc) == PQ_CACHE)
1328 * Remove all pmaps and indicate that the page is not
1329 * writeable or mapped.
1332 if (m->dirty != 0) {
1333 panic("vm_page_cache: caching a dirty page, pindex: %ld",
1336 vm_pageq_remove_nowakeup(m);
1337 vm_pageq_enqueue(PQ_CACHE + m->pc, m);
1338 vm_page_free_wakeup();
1344 * Cache, deactivate, or do nothing as appropriate. This routine
1345 * is typically used by madvise() MADV_DONTNEED.
1347 * Generally speaking we want to move the page into the cache so
1348 * it gets reused quickly. However, this can result in a silly syndrome
1349 * due to the page recycling too quickly. Small objects will not be
1350 * fully cached. On the otherhand, if we move the page to the inactive
1351 * queue we wind up with a problem whereby very large objects
1352 * unnecessarily blow away our inactive and cache queues.
1354 * The solution is to move the pages based on a fixed weighting. We
1355 * either leave them alone, deactivate them, or move them to the cache,
1356 * where moving them to the cache has the highest weighting.
1357 * By forcing some pages into other queues we eventually force the
1358 * system to balance the queues, potentially recovering other unrelated
1359 * space from active. The idea is to not force this to happen too
1363 vm_page_dontneed(vm_page_t m)
1365 static int dnweight;
1369 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1373 * occassionally leave the page alone
1375 if ((dnw & 0x01F0) == 0 ||
1376 m->queue == PQ_INACTIVE ||
1377 m->queue - m->pc == PQ_CACHE
1379 if (m->act_count >= ACT_INIT)
1384 if (m->dirty == 0 && pmap_is_modified(m))
1387 if (m->dirty || (dnw & 0x0070) == 0) {
1389 * Deactivate the page 3 times out of 32.
1394 * Cache the page 28 times out of every 32. Note that
1395 * the page is deactivated instead of cached, but placed
1396 * at the head of the queue instead of the tail.
1400 _vm_page_deactivate(m, head);
1404 * Grab a page, waiting until we are waken up due to the page
1405 * changing state. We keep on waiting, if the page continues
1406 * to be in the object. If the page doesn't exist, first allocate it
1407 * and then conditionally zero it.
1409 * This routine may block.
1412 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
1416 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1418 if ((m = vm_page_lookup(object, pindex)) != NULL) {
1419 vm_page_lock_queues();
1420 if (m->busy || (m->flags & PG_BUSY)) {
1421 vm_page_flag_set(m, PG_WANTED | PG_REFERENCED);
1422 VM_OBJECT_UNLOCK(object);
1423 msleep(m, &vm_page_queue_mtx, PDROP | PVM, "pgrbwt", 0);
1424 VM_OBJECT_LOCK(object);
1425 if ((allocflags & VM_ALLOC_RETRY) == 0)
1429 if (allocflags & VM_ALLOC_WIRED)
1431 if ((allocflags & VM_ALLOC_NOBUSY) == 0)
1433 vm_page_unlock_queues();
1437 m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_RETRY);
1439 VM_OBJECT_UNLOCK(object);
1441 VM_OBJECT_LOCK(object);
1442 if ((allocflags & VM_ALLOC_RETRY) == 0)
1446 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
1452 * Mapping function for valid bits or for dirty bits in
1453 * a page. May not block.
1455 * Inputs are required to range within a page.
1458 vm_page_bits(int base, int size)
1464 base + size <= PAGE_SIZE,
1465 ("vm_page_bits: illegal base/size %d/%d", base, size)
1468 if (size == 0) /* handle degenerate case */
1471 first_bit = base >> DEV_BSHIFT;
1472 last_bit = (base + size - 1) >> DEV_BSHIFT;
1474 return ((2 << last_bit) - (1 << first_bit));
1478 * vm_page_set_validclean:
1480 * Sets portions of a page valid and clean. The arguments are expected
1481 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
1482 * of any partial chunks touched by the range. The invalid portion of
1483 * such chunks will be zero'd.
1485 * This routine may not block.
1487 * (base + size) must be less then or equal to PAGE_SIZE.
1490 vm_page_set_validclean(vm_page_t m, int base, int size)
1496 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1497 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1498 if (size == 0) /* handle degenerate case */
1502 * If the base is not DEV_BSIZE aligned and the valid
1503 * bit is clear, we have to zero out a portion of the
1506 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
1507 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
1508 pmap_zero_page_area(m, frag, base - frag);
1511 * If the ending offset is not DEV_BSIZE aligned and the
1512 * valid bit is clear, we have to zero out a portion of
1515 endoff = base + size;
1516 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
1517 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
1518 pmap_zero_page_area(m, endoff,
1519 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
1522 * Set valid, clear dirty bits. If validating the entire
1523 * page we can safely clear the pmap modify bit. We also
1524 * use this opportunity to clear the PG_NOSYNC flag. If a process
1525 * takes a write fault on a MAP_NOSYNC memory area the flag will
1528 * We set valid bits inclusive of any overlap, but we can only
1529 * clear dirty bits for DEV_BSIZE chunks that are fully within
1532 pagebits = vm_page_bits(base, size);
1533 m->valid |= pagebits;
1535 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
1536 frag = DEV_BSIZE - frag;
1542 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
1544 m->dirty &= ~pagebits;
1545 if (base == 0 && size == PAGE_SIZE) {
1546 pmap_clear_modify(m);
1547 vm_page_flag_clear(m, PG_NOSYNC);
1552 vm_page_clear_dirty(vm_page_t m, int base, int size)
1555 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1556 m->dirty &= ~vm_page_bits(base, size);
1560 * vm_page_set_invalid:
1562 * Invalidates DEV_BSIZE'd chunks within a page. Both the
1563 * valid and dirty bits for the effected areas are cleared.
1568 vm_page_set_invalid(vm_page_t m, int base, int size)
1572 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1573 bits = vm_page_bits(base, size);
1574 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1577 m->object->generation++;
1581 * vm_page_zero_invalid()
1583 * The kernel assumes that the invalid portions of a page contain
1584 * garbage, but such pages can be mapped into memory by user code.
1585 * When this occurs, we must zero out the non-valid portions of the
1586 * page so user code sees what it expects.
1588 * Pages are most often semi-valid when the end of a file is mapped
1589 * into memory and the file's size is not page aligned.
1592 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
1597 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1599 * Scan the valid bits looking for invalid sections that
1600 * must be zerod. Invalid sub-DEV_BSIZE'd areas ( where the
1601 * valid bit may be set ) have already been zerod by
1602 * vm_page_set_validclean().
1604 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
1605 if (i == (PAGE_SIZE / DEV_BSIZE) ||
1606 (m->valid & (1 << i))
1609 pmap_zero_page_area(m,
1610 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
1617 * setvalid is TRUE when we can safely set the zero'd areas
1618 * as being valid. We can do this if there are no cache consistancy
1619 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
1622 m->valid = VM_PAGE_BITS_ALL;
1628 * Is (partial) page valid? Note that the case where size == 0
1629 * will return FALSE in the degenerate case where the page is
1630 * entirely invalid, and TRUE otherwise.
1635 vm_page_is_valid(vm_page_t m, int base, int size)
1637 int bits = vm_page_bits(base, size);
1639 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1640 if (m->valid && ((m->valid & bits) == bits))
1647 * update dirty bits from pmap/mmu. May not block.
1650 vm_page_test_dirty(vm_page_t m)
1652 if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
1657 int so_zerocp_fullpage = 0;
1660 vm_page_cowfault(vm_page_t m)
1672 mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL);
1674 vm_page_insert(m, object, pindex);
1675 vm_page_unlock_queues();
1676 VM_OBJECT_UNLOCK(object);
1678 VM_OBJECT_LOCK(object);
1679 vm_page_lock_queues();
1685 * check to see if we raced with an xmit complete when
1686 * waiting to allocate a page. If so, put things back
1690 vm_page_insert(m, object, pindex);
1691 } else { /* clear COW & copy page */
1692 if (!so_zerocp_fullpage)
1693 pmap_copy_page(m, mnew);
1694 mnew->valid = VM_PAGE_BITS_ALL;
1695 vm_page_dirty(mnew);
1696 vm_page_flag_clear(mnew, PG_BUSY);
1701 vm_page_cowclear(vm_page_t m)
1704 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1708 * let vm_fault add back write permission lazily
1712 * sf_buf_free() will free the page, so we needn't do it here
1717 vm_page_cowsetup(vm_page_t m)
1720 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1722 pmap_page_protect(m, VM_PROT_READ);
1725 #include "opt_ddb.h"
1727 #include <sys/kernel.h>
1729 #include <ddb/ddb.h>
1731 DB_SHOW_COMMAND(page, vm_page_print_page_info)
1733 db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
1734 db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
1735 db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
1736 db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
1737 db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
1738 db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
1739 db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
1740 db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
1741 db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
1742 db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
1745 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
1748 db_printf("PQ_FREE:");
1749 for (i = 0; i < PQ_L2_SIZE; i++) {
1750 db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt);
1754 db_printf("PQ_CACHE:");
1755 for (i = 0; i < PQ_L2_SIZE; i++) {
1756 db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt);
1760 db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
1761 vm_page_queues[PQ_ACTIVE].lcnt,
1762 vm_page_queues[PQ_INACTIVE].lcnt);