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);
349 vm_page_io_finish(vm_page_t m)
352 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
353 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
360 * Keep page from being freed by the page daemon
361 * much of the same effect as wiring, except much lower
362 * overhead and should be used only for *very* temporary
363 * holding ("wiring").
366 vm_page_hold(vm_page_t mem)
369 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
374 vm_page_unhold(vm_page_t mem)
377 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
379 KASSERT(mem->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!"));
380 if (mem->hold_count == 0 && mem->queue == PQ_HOLD)
381 vm_page_free_toq(mem);
389 * The clearing of PG_ZERO is a temporary safety until the code can be
390 * reviewed to determine that PG_ZERO is being properly cleared on
391 * write faults or maps. PG_ZERO was previously cleared in
395 vm_page_free(vm_page_t m)
397 vm_page_flag_clear(m, PG_ZERO);
399 vm_page_zero_idle_wakeup();
405 * Free a page to the zerod-pages queue
408 vm_page_free_zero(vm_page_t m)
410 vm_page_flag_set(m, PG_ZERO);
415 * vm_page_sleep_if_busy:
417 * Sleep and release the page queues lock if PG_BUSY is set or,
418 * if also_m_busy is TRUE, busy is non-zero. Returns TRUE if the
419 * thread slept and the page queues lock was released.
420 * Otherwise, retains the page queues lock and returns FALSE.
423 vm_page_sleep_if_busy(vm_page_t m, int also_m_busy, const char *msg)
427 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
428 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
429 if ((m->flags & PG_BUSY) || (also_m_busy && m->busy)) {
430 vm_page_flag_set(m, PG_WANTED | PG_REFERENCED);
432 * It's possible that while we sleep, the page will get
433 * unbusied and freed. If we are holding the object
434 * lock, we will assume we hold a reference to the object
435 * such that even if m->object changes, we can re-lock
439 VM_OBJECT_UNLOCK(object);
440 msleep(m, &vm_page_queue_mtx, PDROP | PVM, msg, 0);
441 VM_OBJECT_LOCK(object);
450 * make page all dirty
453 vm_page_dirty(vm_page_t m)
455 KASSERT(m->queue - m->pc != PQ_CACHE,
456 ("vm_page_dirty: page in cache!"));
457 KASSERT(m->queue - m->pc != PQ_FREE,
458 ("vm_page_dirty: page is free!"));
459 m->dirty = VM_PAGE_BITS_ALL;
465 * Implements Sleator and Tarjan's top-down splay algorithm. Returns
466 * the vm_page containing the given pindex. If, however, that
467 * pindex is not found in the vm_object, returns a vm_page that is
468 * adjacent to the pindex, coming before or after it.
471 vm_page_splay(vm_pindex_t pindex, vm_page_t root)
473 struct vm_page dummy;
474 vm_page_t lefttreemax, righttreemin, y;
478 lefttreemax = righttreemin = &dummy;
480 if (pindex < root->pindex) {
481 if ((y = root->left) == NULL)
483 if (pindex < y->pindex) {
485 root->left = y->right;
488 if ((y = root->left) == NULL)
491 /* Link into the new root's right tree. */
492 righttreemin->left = root;
494 } else if (pindex > root->pindex) {
495 if ((y = root->right) == NULL)
497 if (pindex > y->pindex) {
499 root->right = y->left;
502 if ((y = root->right) == NULL)
505 /* Link into the new root's left tree. */
506 lefttreemax->right = root;
511 /* Assemble the new root. */
512 lefttreemax->right = root->left;
513 righttreemin->left = root->right;
514 root->left = dummy.right;
515 root->right = dummy.left;
520 * vm_page_insert: [ internal use only ]
522 * Inserts the given mem entry into the object and object list.
524 * The pagetables are not updated but will presumably fault the page
525 * in if necessary, or if a kernel page the caller will at some point
526 * enter the page into the kernel's pmap. We are not allowed to block
527 * here so we *can't* do this anyway.
529 * The object and page must be locked.
530 * This routine may not block.
533 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
537 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
538 if (m->object != NULL)
539 panic("vm_page_insert: page already inserted");
542 * Record the object/offset pair in this page
548 * Now link into the object's ordered list of backed pages.
554 TAILQ_INSERT_TAIL(&object->memq, m, listq);
556 root = vm_page_splay(pindex, root);
557 if (pindex < root->pindex) {
558 m->left = root->left;
561 TAILQ_INSERT_BEFORE(root, m, listq);
562 } else if (pindex == root->pindex)
563 panic("vm_page_insert: offset already allocated");
565 m->right = root->right;
568 TAILQ_INSERT_AFTER(&object->memq, root, m, listq);
572 object->generation++;
575 * show that the object has one more resident page.
577 object->resident_page_count++;
580 * Since we are inserting a new and possibly dirty page,
581 * update the object's OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY flags.
583 if (m->flags & PG_WRITEABLE)
584 vm_object_set_writeable_dirty(object);
589 * NOTE: used by device pager as well -wfj
591 * Removes the given mem entry from the object/offset-page
592 * table and the object page list, but do not invalidate/terminate
595 * The object and page must be locked.
596 * The underlying pmap entry (if any) is NOT removed here.
597 * This routine may not block.
600 vm_page_remove(vm_page_t m)
605 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
606 if ((object = m->object) == NULL)
608 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
609 if (m->flags & PG_BUSY) {
610 vm_page_flag_clear(m, PG_BUSY);
615 * Now remove from the object's list of backed pages.
617 if (m != object->root)
618 vm_page_splay(m->pindex, object->root);
622 root = vm_page_splay(m->pindex, m->left);
623 root->right = m->right;
626 TAILQ_REMOVE(&object->memq, m, listq);
629 * And show that the object has one fewer resident page.
631 object->resident_page_count--;
632 object->generation++;
640 * Returns the page associated with the object/offset
641 * pair specified; if none is found, NULL is returned.
643 * The object must be locked.
644 * This routine may not block.
645 * This is a critical path routine
648 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
652 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
653 if ((m = object->root) != NULL && m->pindex != pindex) {
654 m = vm_page_splay(pindex, m);
655 if ((object->root = m)->pindex != pindex)
664 * Move the given memory entry from its
665 * current object to the specified target object/offset.
667 * The object must be locked.
668 * This routine may not block.
670 * Note: swap associated with the page must be invalidated by the move. We
671 * have to do this for several reasons: (1) we aren't freeing the
672 * page, (2) we are dirtying the page, (3) the VM system is probably
673 * moving the page from object A to B, and will then later move
674 * the backing store from A to B and we can't have a conflict.
676 * Note: we *always* dirty the page. It is necessary both for the
677 * fact that we moved it, and because we may be invalidating
678 * swap. If the page is on the cache, we have to deactivate it
679 * or vm_page_dirty() will panic. Dirty pages are not allowed
683 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
687 vm_page_insert(m, new_object, new_pindex);
688 if (m->queue - m->pc == PQ_CACHE)
689 vm_page_deactivate(m);
694 * vm_page_select_cache:
696 * Find a page on the cache queue with color optimization. As pages
697 * might be found, but not applicable, they are deactivated. This
698 * keeps us from using potentially busy cached pages.
700 * This routine may not block.
703 vm_page_select_cache(int color)
707 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
708 while ((m = vm_pageq_find(PQ_CACHE, color, FALSE)) != NULL) {
709 if ((m->flags & PG_BUSY) == 0 && m->busy == 0 &&
710 m->hold_count == 0 && (VM_OBJECT_TRYLOCK(m->object) ||
711 VM_OBJECT_LOCKED(m->object))) {
712 KASSERT(m->dirty == 0,
713 ("Found dirty cache page %p", m));
714 KASSERT(!pmap_page_is_mapped(m),
715 ("Found mapped cache page %p", m));
716 KASSERT((m->flags & PG_UNMANAGED) == 0,
717 ("Found unmanaged cache page %p", m));
718 KASSERT(m->wire_count == 0,
719 ("Found wired cache page %p", m));
722 vm_page_deactivate(m);
730 * Allocate and return a memory cell associated
731 * with this VM object/offset pair.
734 * VM_ALLOC_NORMAL normal process request
735 * VM_ALLOC_SYSTEM system *really* needs a page
736 * VM_ALLOC_INTERRUPT interrupt time request
737 * VM_ALLOC_ZERO zero page
739 * This routine may not block.
741 * Additional special handling is required when called from an
742 * interrupt (VM_ALLOC_INTERRUPT). We are not allowed to mess with
743 * the page cache in this case.
746 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
748 vm_object_t m_object;
750 int color, flags, page_req;
752 page_req = req & VM_ALLOC_CLASS_MASK;
754 if ((req & VM_ALLOC_NOOBJ) == 0) {
755 KASSERT(object != NULL,
756 ("vm_page_alloc: NULL object."));
757 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
758 color = (pindex + object->pg_color) & PQ_L2_MASK;
760 color = pindex & PQ_L2_MASK;
763 * The pager is allowed to eat deeper into the free page list.
765 if ((curproc == pageproc) && (page_req != VM_ALLOC_INTERRUPT)) {
766 page_req = VM_ALLOC_SYSTEM;
770 mtx_lock_spin(&vm_page_queue_free_mtx);
771 if (cnt.v_free_count > cnt.v_free_reserved ||
772 (page_req == VM_ALLOC_SYSTEM &&
773 cnt.v_cache_count == 0 &&
774 cnt.v_free_count > cnt.v_interrupt_free_min) ||
775 (page_req == VM_ALLOC_INTERRUPT && cnt.v_free_count > 0)) {
777 * Allocate from the free queue if the number of free pages
778 * exceeds the minimum for the request class.
780 m = vm_pageq_find(PQ_FREE, color, (req & VM_ALLOC_ZERO) != 0);
781 } else if (page_req != VM_ALLOC_INTERRUPT) {
782 mtx_unlock_spin(&vm_page_queue_free_mtx);
784 * Allocatable from cache (non-interrupt only). On success,
785 * we must free the page and try again, thus ensuring that
786 * cnt.v_*_free_min counters are replenished.
788 vm_page_lock_queues();
789 if ((m = vm_page_select_cache(color)) == NULL) {
790 #if defined(DIAGNOSTIC)
791 if (cnt.v_cache_count > 0)
792 printf("vm_page_alloc(NORMAL): missing pages on cache queue: %d\n", cnt.v_cache_count);
794 vm_page_unlock_queues();
795 atomic_add_int(&vm_pageout_deficit, 1);
799 m_object = m->object;
800 VM_OBJECT_LOCK_ASSERT(m_object, MA_OWNED);
802 vm_page_unlock_queues();
803 if (m_object != object)
804 VM_OBJECT_UNLOCK(m_object);
808 * Not allocatable from cache from interrupt, give up.
810 mtx_unlock_spin(&vm_page_queue_free_mtx);
811 atomic_add_int(&vm_pageout_deficit, 1);
817 * At this point we had better have found a good page.
822 ("vm_page_alloc(): missing page on free queue")
826 * Remove from free queue
828 vm_pageq_remove_nowakeup(m);
831 * Initialize structure. Only the PG_ZERO flag is inherited.
834 if (m->flags & PG_ZERO) {
835 vm_page_zero_count--;
836 if (req & VM_ALLOC_ZERO)
837 flags = PG_ZERO | PG_BUSY;
839 if (req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ))
842 if (req & VM_ALLOC_WIRED) {
843 atomic_add_int(&cnt.v_wire_count, 1);
851 KASSERT(m->dirty == 0, ("vm_page_alloc: free/cache page %p was dirty", m));
852 mtx_unlock_spin(&vm_page_queue_free_mtx);
854 if ((req & VM_ALLOC_NOOBJ) == 0)
855 vm_page_insert(m, object, pindex);
860 * Don't wakeup too often - wakeup the pageout daemon when
861 * we would be nearly out of memory.
863 if (vm_paging_needed())
870 * vm_wait: (also see VM_WAIT macro)
872 * Block until free pages are available for allocation
873 * - Called in various places before memory allocations.
879 vm_page_lock_queues();
880 if (curproc == pageproc) {
881 vm_pageout_pages_needed = 1;
882 msleep(&vm_pageout_pages_needed, &vm_page_queue_mtx,
883 PDROP | PSWP, "VMWait", 0);
885 if (!vm_pages_needed) {
887 wakeup(&vm_pages_needed);
889 msleep(&cnt.v_free_count, &vm_page_queue_mtx, PDROP | PVM,
895 * vm_waitpfault: (also see VM_WAITPFAULT macro)
897 * Block until free pages are available for allocation
898 * - Called only in vm_fault so that processes page faulting
899 * can be easily tracked.
900 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
901 * processes will be able to grab memory first. Do not change
902 * this balance without careful testing first.
908 vm_page_lock_queues();
909 if (!vm_pages_needed) {
911 wakeup(&vm_pages_needed);
913 msleep(&cnt.v_free_count, &vm_page_queue_mtx, PDROP | PUSER,
920 * Put the specified page on the active list (if appropriate).
921 * Ensure that act_count is at least ACT_INIT but do not otherwise
924 * The page queues must be locked.
925 * This routine may not block.
928 vm_page_activate(vm_page_t m)
931 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
932 if (m->queue != PQ_ACTIVE) {
933 if ((m->queue - m->pc) == PQ_CACHE)
936 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
937 if (m->act_count < ACT_INIT)
938 m->act_count = ACT_INIT;
939 vm_pageq_enqueue(PQ_ACTIVE, m);
942 if (m->act_count < ACT_INIT)
943 m->act_count = ACT_INIT;
948 * vm_page_free_wakeup:
950 * Helper routine for vm_page_free_toq() and vm_page_cache(). This
951 * routine is called when a page has been added to the cache or free
954 * The page queues must be locked.
955 * This routine may not block.
958 vm_page_free_wakeup(void)
961 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
963 * if pageout daemon needs pages, then tell it that there are
966 if (vm_pageout_pages_needed &&
967 cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
968 wakeup(&vm_pageout_pages_needed);
969 vm_pageout_pages_needed = 0;
972 * wakeup processes that are waiting on memory if we hit a
973 * high water mark. And wakeup scheduler process if we have
974 * lots of memory. this process will swapin processes.
976 if (vm_pages_needed && !vm_page_count_min()) {
978 wakeup(&cnt.v_free_count);
985 * Returns the given page to the PQ_FREE list,
986 * disassociating it with any VM object.
988 * Object and page must be locked prior to entry.
989 * This routine may not block.
993 vm_page_free_toq(vm_page_t m)
995 struct vpgqueues *pq;
996 vm_object_t object = m->object;
998 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1001 if (m->busy || ((m->queue - m->pc) == PQ_FREE)) {
1003 "vm_page_free: pindex(%lu), busy(%d), PG_BUSY(%d), hold(%d)\n",
1004 (u_long)m->pindex, m->busy, (m->flags & PG_BUSY) ? 1 : 0,
1006 if ((m->queue - m->pc) == PQ_FREE)
1007 panic("vm_page_free: freeing free page");
1009 panic("vm_page_free: freeing busy page");
1013 * unqueue, then remove page. Note that we cannot destroy
1014 * the page here because we do not want to call the pager's
1015 * callback routine until after we've put the page on the
1016 * appropriate free queue.
1018 vm_pageq_remove_nowakeup(m);
1022 * If fictitious remove object association and
1023 * return, otherwise delay object association removal.
1025 if ((m->flags & PG_FICTITIOUS) != 0) {
1032 if (m->wire_count != 0) {
1033 if (m->wire_count > 1) {
1034 panic("vm_page_free: invalid wire count (%d), pindex: 0x%lx",
1035 m->wire_count, (long)m->pindex);
1037 panic("vm_page_free: freeing wired page");
1041 * If we've exhausted the object's resident pages we want to free
1045 (object->type == OBJT_VNODE) &&
1046 ((object->flags & OBJ_DEAD) == 0)
1048 struct vnode *vp = (struct vnode *)object->handle;
1052 if (VSHOULDFREE(vp))
1059 * Clear the UNMANAGED flag when freeing an unmanaged page.
1061 if (m->flags & PG_UNMANAGED) {
1062 m->flags &= ~PG_UNMANAGED;
1065 if (m->hold_count != 0) {
1066 m->flags &= ~PG_ZERO;
1069 m->queue = PQ_FREE + m->pc;
1070 pq = &vm_page_queues[m->queue];
1071 mtx_lock_spin(&vm_page_queue_free_mtx);
1076 * Put zero'd pages on the end ( where we look for zero'd pages
1077 * first ) and non-zerod pages at the head.
1079 if (m->flags & PG_ZERO) {
1080 TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
1081 ++vm_page_zero_count;
1083 TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
1085 mtx_unlock_spin(&vm_page_queue_free_mtx);
1086 vm_page_free_wakeup();
1092 * Prevent PV management from being done on the page. The page is
1093 * removed from the paging queues as if it were wired, and as a
1094 * consequence of no longer being managed the pageout daemon will not
1095 * touch it (since there is no way to locate the pte mappings for the
1096 * page). madvise() calls that mess with the pmap will also no longer
1097 * operate on the page.
1099 * Beyond that the page is still reasonably 'normal'. Freeing the page
1100 * will clear the flag.
1102 * This routine is used by OBJT_PHYS objects - objects using unswappable
1103 * physical memory as backing store rather then swap-backed memory and
1104 * will eventually be extended to support 4MB unmanaged physical
1108 vm_page_unmanage(vm_page_t m)
1111 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1112 if ((m->flags & PG_UNMANAGED) == 0) {
1113 if (m->wire_count == 0)
1116 vm_page_flag_set(m, PG_UNMANAGED);
1122 * Mark this page as wired down by yet
1123 * another map, removing it from paging queues
1126 * The page queues must be locked.
1127 * This routine may not block.
1130 vm_page_wire(vm_page_t m)
1134 * Only bump the wire statistics if the page is not already wired,
1135 * and only unqueue the page if it is on some queue (if it is unmanaged
1136 * it is already off the queues).
1138 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1139 if (m->flags & PG_FICTITIOUS)
1141 if (m->wire_count == 0) {
1142 if ((m->flags & PG_UNMANAGED) == 0)
1144 atomic_add_int(&cnt.v_wire_count, 1);
1147 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
1153 * Release one wiring of this page, potentially
1154 * enabling it to be paged again.
1156 * Many pages placed on the inactive queue should actually go
1157 * into the cache, but it is difficult to figure out which. What
1158 * we do instead, if the inactive target is well met, is to put
1159 * clean pages at the head of the inactive queue instead of the tail.
1160 * This will cause them to be moved to the cache more quickly and
1161 * if not actively re-referenced, freed more quickly. If we just
1162 * stick these pages at the end of the inactive queue, heavy filesystem
1163 * meta-data accesses can cause an unnecessary paging load on memory bound
1164 * processes. This optimization causes one-time-use metadata to be
1165 * reused more quickly.
1167 * BUT, if we are in a low-memory situation we have no choice but to
1168 * put clean pages on the cache queue.
1170 * A number of routines use vm_page_unwire() to guarantee that the page
1171 * will go into either the inactive or active queues, and will NEVER
1172 * be placed in the cache - for example, just after dirtying a page.
1173 * dirty pages in the cache are not allowed.
1175 * The page queues must be locked.
1176 * This routine may not block.
1179 vm_page_unwire(vm_page_t m, int activate)
1182 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1183 if (m->flags & PG_FICTITIOUS)
1185 if (m->wire_count > 0) {
1187 if (m->wire_count == 0) {
1188 atomic_subtract_int(&cnt.v_wire_count, 1);
1189 if (m->flags & PG_UNMANAGED) {
1191 } else if (activate)
1192 vm_pageq_enqueue(PQ_ACTIVE, m);
1194 vm_page_flag_clear(m, PG_WINATCFLS);
1195 vm_pageq_enqueue(PQ_INACTIVE, m);
1199 panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
1205 * Move the specified page to the inactive queue. If the page has
1206 * any associated swap, the swap is deallocated.
1208 * Normally athead is 0 resulting in LRU operation. athead is set
1209 * to 1 if we want this page to be 'as if it were placed in the cache',
1210 * except without unmapping it from the process address space.
1212 * This routine may not block.
1214 static __inline void
1215 _vm_page_deactivate(vm_page_t m, int athead)
1218 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1221 * Ignore if already inactive.
1223 if (m->queue == PQ_INACTIVE)
1225 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1226 if ((m->queue - m->pc) == PQ_CACHE)
1227 cnt.v_reactivated++;
1228 vm_page_flag_clear(m, PG_WINATCFLS);
1231 TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1233 TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1234 m->queue = PQ_INACTIVE;
1235 vm_page_queues[PQ_INACTIVE].lcnt++;
1236 cnt.v_inactive_count++;
1241 vm_page_deactivate(vm_page_t m)
1243 _vm_page_deactivate(m, 0);
1247 * vm_page_try_to_cache:
1249 * Returns 0 on failure, 1 on success
1252 vm_page_try_to_cache(vm_page_t m)
1255 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1256 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1257 if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1258 (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1269 * vm_page_try_to_free()
1271 * Attempt to free the page. If we cannot free it, we do nothing.
1272 * 1 is returned on success, 0 on failure.
1275 vm_page_try_to_free(vm_page_t m)
1278 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1279 if (m->object != NULL)
1280 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1281 if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1282 (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1295 * Put the specified page onto the page cache queue (if appropriate).
1297 * This routine may not block.
1300 vm_page_cache(vm_page_t m)
1303 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1304 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1305 if ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy ||
1306 m->hold_count || m->wire_count) {
1307 printf("vm_page_cache: attempting to cache busy page\n");
1310 if ((m->queue - m->pc) == PQ_CACHE)
1314 * Remove all pmaps and indicate that the page is not
1315 * writeable or mapped.
1318 if (m->dirty != 0) {
1319 panic("vm_page_cache: caching a dirty page, pindex: %ld",
1322 vm_pageq_remove_nowakeup(m);
1323 vm_pageq_enqueue(PQ_CACHE + m->pc, m);
1324 vm_page_free_wakeup();
1330 * Cache, deactivate, or do nothing as appropriate. This routine
1331 * is typically used by madvise() MADV_DONTNEED.
1333 * Generally speaking we want to move the page into the cache so
1334 * it gets reused quickly. However, this can result in a silly syndrome
1335 * due to the page recycling too quickly. Small objects will not be
1336 * fully cached. On the otherhand, if we move the page to the inactive
1337 * queue we wind up with a problem whereby very large objects
1338 * unnecessarily blow away our inactive and cache queues.
1340 * The solution is to move the pages based on a fixed weighting. We
1341 * either leave them alone, deactivate them, or move them to the cache,
1342 * where moving them to the cache has the highest weighting.
1343 * By forcing some pages into other queues we eventually force the
1344 * system to balance the queues, potentially recovering other unrelated
1345 * space from active. The idea is to not force this to happen too
1349 vm_page_dontneed(vm_page_t m)
1351 static int dnweight;
1355 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1359 * occassionally leave the page alone
1361 if ((dnw & 0x01F0) == 0 ||
1362 m->queue == PQ_INACTIVE ||
1363 m->queue - m->pc == PQ_CACHE
1365 if (m->act_count >= ACT_INIT)
1370 if (m->dirty == 0 && pmap_is_modified(m))
1373 if (m->dirty || (dnw & 0x0070) == 0) {
1375 * Deactivate the page 3 times out of 32.
1380 * Cache the page 28 times out of every 32. Note that
1381 * the page is deactivated instead of cached, but placed
1382 * at the head of the queue instead of the tail.
1386 _vm_page_deactivate(m, head);
1390 * Grab a page, waiting until we are waken up due to the page
1391 * changing state. We keep on waiting, if the page continues
1392 * to be in the object. If the page doesn't exist, first allocate it
1393 * and then conditionally zero it.
1395 * This routine may block.
1398 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
1402 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1404 if ((m = vm_page_lookup(object, pindex)) != NULL) {
1405 vm_page_lock_queues();
1406 if (m->busy || (m->flags & PG_BUSY)) {
1407 vm_page_flag_set(m, PG_WANTED | PG_REFERENCED);
1408 VM_OBJECT_UNLOCK(object);
1409 msleep(m, &vm_page_queue_mtx, PDROP | PVM, "pgrbwt", 0);
1410 VM_OBJECT_LOCK(object);
1411 if ((allocflags & VM_ALLOC_RETRY) == 0)
1415 if (allocflags & VM_ALLOC_WIRED)
1417 if ((allocflags & VM_ALLOC_NOBUSY) == 0)
1419 vm_page_unlock_queues();
1423 m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_RETRY);
1425 VM_OBJECT_UNLOCK(object);
1427 VM_OBJECT_LOCK(object);
1428 if ((allocflags & VM_ALLOC_RETRY) == 0)
1432 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
1438 * Mapping function for valid bits or for dirty bits in
1439 * a page. May not block.
1441 * Inputs are required to range within a page.
1444 vm_page_bits(int base, int size)
1450 base + size <= PAGE_SIZE,
1451 ("vm_page_bits: illegal base/size %d/%d", base, size)
1454 if (size == 0) /* handle degenerate case */
1457 first_bit = base >> DEV_BSHIFT;
1458 last_bit = (base + size - 1) >> DEV_BSHIFT;
1460 return ((2 << last_bit) - (1 << first_bit));
1464 * vm_page_set_validclean:
1466 * Sets portions of a page valid and clean. The arguments are expected
1467 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
1468 * of any partial chunks touched by the range. The invalid portion of
1469 * such chunks will be zero'd.
1471 * This routine may not block.
1473 * (base + size) must be less then or equal to PAGE_SIZE.
1476 vm_page_set_validclean(vm_page_t m, int base, int size)
1482 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1483 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1484 if (size == 0) /* handle degenerate case */
1488 * If the base is not DEV_BSIZE aligned and the valid
1489 * bit is clear, we have to zero out a portion of the
1492 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
1493 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
1494 pmap_zero_page_area(m, frag, base - frag);
1497 * If the ending offset is not DEV_BSIZE aligned and the
1498 * valid bit is clear, we have to zero out a portion of
1501 endoff = base + size;
1502 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
1503 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
1504 pmap_zero_page_area(m, endoff,
1505 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
1508 * Set valid, clear dirty bits. If validating the entire
1509 * page we can safely clear the pmap modify bit. We also
1510 * use this opportunity to clear the PG_NOSYNC flag. If a process
1511 * takes a write fault on a MAP_NOSYNC memory area the flag will
1514 * We set valid bits inclusive of any overlap, but we can only
1515 * clear dirty bits for DEV_BSIZE chunks that are fully within
1518 pagebits = vm_page_bits(base, size);
1519 m->valid |= pagebits;
1521 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
1522 frag = DEV_BSIZE - frag;
1528 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
1530 m->dirty &= ~pagebits;
1531 if (base == 0 && size == PAGE_SIZE) {
1532 pmap_clear_modify(m);
1533 vm_page_flag_clear(m, PG_NOSYNC);
1538 vm_page_clear_dirty(vm_page_t m, int base, int size)
1541 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1542 m->dirty &= ~vm_page_bits(base, size);
1546 * vm_page_set_invalid:
1548 * Invalidates DEV_BSIZE'd chunks within a page. Both the
1549 * valid and dirty bits for the effected areas are cleared.
1554 vm_page_set_invalid(vm_page_t m, int base, int size)
1558 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1559 bits = vm_page_bits(base, size);
1560 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1563 m->object->generation++;
1567 * vm_page_zero_invalid()
1569 * The kernel assumes that the invalid portions of a page contain
1570 * garbage, but such pages can be mapped into memory by user code.
1571 * When this occurs, we must zero out the non-valid portions of the
1572 * page so user code sees what it expects.
1574 * Pages are most often semi-valid when the end of a file is mapped
1575 * into memory and the file's size is not page aligned.
1578 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
1583 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1585 * Scan the valid bits looking for invalid sections that
1586 * must be zerod. Invalid sub-DEV_BSIZE'd areas ( where the
1587 * valid bit may be set ) have already been zerod by
1588 * vm_page_set_validclean().
1590 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
1591 if (i == (PAGE_SIZE / DEV_BSIZE) ||
1592 (m->valid & (1 << i))
1595 pmap_zero_page_area(m,
1596 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
1603 * setvalid is TRUE when we can safely set the zero'd areas
1604 * as being valid. We can do this if there are no cache consistancy
1605 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
1608 m->valid = VM_PAGE_BITS_ALL;
1614 * Is (partial) page valid? Note that the case where size == 0
1615 * will return FALSE in the degenerate case where the page is
1616 * entirely invalid, and TRUE otherwise.
1621 vm_page_is_valid(vm_page_t m, int base, int size)
1623 int bits = vm_page_bits(base, size);
1625 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1626 if (m->valid && ((m->valid & bits) == bits))
1633 * update dirty bits from pmap/mmu. May not block.
1636 vm_page_test_dirty(vm_page_t m)
1638 if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
1643 int so_zerocp_fullpage = 0;
1646 vm_page_cowfault(vm_page_t m)
1657 mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL);
1659 vm_page_insert(m, object, pindex);
1660 vm_page_unlock_queues();
1661 VM_OBJECT_UNLOCK(object);
1663 VM_OBJECT_LOCK(object);
1664 vm_page_lock_queues();
1670 * check to see if we raced with an xmit complete when
1671 * waiting to allocate a page. If so, put things back
1675 vm_page_insert(m, object, pindex);
1676 } else { /* clear COW & copy page */
1677 if (!so_zerocp_fullpage)
1678 pmap_copy_page(m, mnew);
1679 mnew->valid = VM_PAGE_BITS_ALL;
1680 vm_page_dirty(mnew);
1681 vm_page_flag_clear(mnew, PG_BUSY);
1686 vm_page_cowclear(vm_page_t m)
1689 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1693 * let vm_fault add back write permission lazily
1697 * sf_buf_free() will free the page, so we needn't do it here
1702 vm_page_cowsetup(vm_page_t m)
1705 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1707 pmap_page_protect(m, VM_PROT_READ);
1710 #include "opt_ddb.h"
1712 #include <sys/kernel.h>
1714 #include <ddb/ddb.h>
1716 DB_SHOW_COMMAND(page, vm_page_print_page_info)
1718 db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
1719 db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
1720 db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
1721 db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
1722 db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
1723 db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
1724 db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
1725 db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
1726 db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
1727 db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
1730 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
1733 db_printf("PQ_FREE:");
1734 for (i = 0; i < PQ_L2_SIZE; i++) {
1735 db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt);
1739 db_printf("PQ_CACHE:");
1740 for (i = 0; i < PQ_L2_SIZE; i++) {
1741 db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt);
1745 db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
1746 vm_page_queues[PQ_ACTIVE].lcnt,
1747 vm_page_queues[PQ_INACTIVE].lcnt);