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 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * from: @(#)vm_page.c 7.4 (Berkeley) 5/7/91
41 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
42 * All rights reserved.
44 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
46 * Permission to use, copy, modify and distribute this software and
47 * its documentation is hereby granted, provided that both the copyright
48 * notice and this permission notice appear in all copies of the
49 * software, derivative works or modified versions, and any portions
50 * thereof, and that both notices appear in supporting documentation.
52 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
53 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
54 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
56 * Carnegie Mellon requests users of this software to return to
58 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
59 * School of Computer Science
60 * Carnegie Mellon University
61 * Pittsburgh PA 15213-3890
63 * any improvements or extensions that they make and grant Carnegie the
64 * rights to redistribute these changes.
68 * GENERAL RULES ON VM_PAGE MANIPULATION
70 * - a pageq mutex is required when adding or removing a page from a
71 * page queue (vm_page_queue[]), regardless of other mutexes or the
72 * busy state of a page.
74 * - a hash chain mutex is required when associating or disassociating
75 * a page from the VM PAGE CACHE hash table (vm_page_buckets),
76 * regardless of other mutexes or the busy state of a page.
78 * - either a hash chain mutex OR a busied page is required in order
79 * to modify the page flags. A hash chain mutex must be obtained in
80 * order to busy a page. A page's flags cannot be modified by a
81 * hash chain mutex if the page is marked busy.
83 * - The object memq mutex is held when inserting or removing
84 * pages from an object (vm_page_insert() or vm_page_remove()). This
85 * is different from the object's main mutex.
87 * Generally speaking, you have to be aware of side effects when running
88 * vm_page ops. A vm_page_lookup() will return with the hash chain
89 * locked, whether it was able to lookup the page or not. vm_page_free(),
90 * vm_page_cache(), vm_page_activate(), and a number of other routines
91 * will release the hash chain mutex for you. Intermediate manipulation
92 * routines such as vm_page_flag_set() expect the hash chain to be held
93 * on entry and the hash chain will remain held on return.
95 * pageq scanning can only occur with the pageq in question locked.
96 * We have a known bottleneck with the active queue, but the cache
97 * and free queues are actually arrays already.
101 * Resident memory management module.
104 #include <sys/param.h>
105 #include <sys/systm.h>
106 #include <sys/lock.h>
107 #include <sys/malloc.h>
108 #include <sys/mutex.h>
109 #include <sys/proc.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
128 static struct mtx vm_page_buckets_mtx;
129 static struct vm_page **vm_page_buckets; /* Array of buckets */
130 static int vm_page_bucket_count; /* How big is array? */
131 static int vm_page_hash_mask; /* Mask for hash function */
133 struct mtx vm_page_queue_mtx;
134 struct mtx vm_page_queue_free_mtx;
136 vm_page_t vm_page_array = 0;
137 int vm_page_array_size = 0;
139 int vm_page_zero_count = 0;
144 * Sets the page size, perhaps based upon the memory
145 * size. Must be called before any use of page-size
146 * dependent functions.
149 vm_set_page_size(void)
151 if (cnt.v_page_size == 0)
152 cnt.v_page_size = PAGE_SIZE;
153 if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0)
154 panic("vm_set_page_size: page size not a power of two");
160 * Initializes the resident memory module.
162 * Allocates memory for the page cells, and
163 * for the object/offset-to-page hash table headers.
164 * Each page cell is initialized and placed on the free list.
167 vm_page_startup(vm_offset_t starta, vm_offset_t enda, vm_offset_t vaddr)
170 struct vm_page **bucket;
171 vm_size_t npages, page_range;
178 /* the biggest memory array is the second group of pages */
180 vm_offset_t biggestone, biggestsize;
189 vaddr = round_page(vaddr);
191 for (i = 0; phys_avail[i + 1]; i += 2) {
192 phys_avail[i] = round_page(phys_avail[i]);
193 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
196 for (i = 0; phys_avail[i + 1]; i += 2) {
197 vm_size_t size = phys_avail[i + 1] - phys_avail[i];
199 if (size > biggestsize) {
207 end = phys_avail[biggestone+1];
210 * Initialize the locks.
212 mtx_init(&vm_page_queue_mtx, "vm page queue mutex", NULL, MTX_DEF);
213 mtx_init(&vm_page_queue_free_mtx, "vm page queue free mutex", NULL,
217 * Initialize the queue headers for the free queue, the active queue
218 * and the inactive queue.
223 * Allocate memory for use when boot strapping the kernel memory allocator
225 bootpages = UMA_BOOT_PAGES * UMA_SLAB_SIZE;
226 new_end = end - bootpages;
227 new_end = trunc_page(new_end);
228 mapped = pmap_map(&vaddr, new_end, end,
229 VM_PROT_READ | VM_PROT_WRITE);
230 bzero((caddr_t) mapped, end - new_end);
231 uma_startup((caddr_t)mapped);
236 * Allocate (and initialize) the hash table buckets.
238 * The number of buckets MUST BE a power of 2, and the actual value is
239 * the next power of 2 greater than the number of physical pages in
242 * We make the hash table approximately 2x the number of pages to
243 * reduce the chain length. This is about the same size using the
244 * singly-linked list as the 1x hash table we were using before
245 * using TAILQ but the chain length will be smaller.
247 * Note: This computation can be tweaked if desired.
249 if (vm_page_bucket_count == 0) {
250 vm_page_bucket_count = 1;
251 while (vm_page_bucket_count < atop(total))
252 vm_page_bucket_count <<= 1;
254 vm_page_bucket_count <<= 1;
255 vm_page_hash_mask = vm_page_bucket_count - 1;
258 * Validate these addresses.
260 new_end = end - vm_page_bucket_count * sizeof(struct vm_page *);
261 new_end = trunc_page(new_end);
262 mapped = pmap_map(&vaddr, new_end, end,
263 VM_PROT_READ | VM_PROT_WRITE);
264 bzero((caddr_t) mapped, end - new_end);
266 mtx_init(&vm_page_buckets_mtx, "vm page buckets mutex", NULL, MTX_SPIN);
267 vm_page_buckets = (struct vm_page **)mapped;
268 bucket = vm_page_buckets;
269 for (i = 0; i < vm_page_bucket_count; i++) {
275 * Compute the number of pages of memory that will be available for
276 * use (taking into account the overhead of a page structure per
279 first_page = phys_avail[0] / PAGE_SIZE;
280 page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE - first_page;
281 npages = (total - (page_range * sizeof(struct vm_page)) -
282 (end - new_end)) / PAGE_SIZE;
286 * Initialize the mem entry structures now, and put them in the free
289 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
290 mapped = pmap_map(&vaddr, new_end, end,
291 VM_PROT_READ | VM_PROT_WRITE);
292 vm_page_array = (vm_page_t) mapped;
295 * Clear all of the page structures
297 bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
298 vm_page_array_size = page_range;
301 * Construct the free queue(s) in descending order (by physical
302 * address) so that the first 16MB of physical memory is allocated
303 * last rather than first. On large-memory machines, this avoids
304 * the exhaustion of low physical memory before isa_dmainit has run.
306 cnt.v_page_count = 0;
307 cnt.v_free_count = 0;
308 for (i = 0; phys_avail[i + 1] && npages > 0; i += 2) {
313 last_pa = phys_avail[i + 1];
314 while (pa < last_pa && npages-- > 0) {
315 vm_pageq_add_new_page(pa);
325 * Distributes the object/offset key pair among hash buckets.
327 * NOTE: This macro depends on vm_page_bucket_count being a power of 2.
328 * This routine may not block.
330 * We try to randomize the hash based on the object to spread the pages
331 * out in the hash table without it costing us too much.
334 vm_page_hash(vm_object_t object, vm_pindex_t pindex)
336 int i = ((uintptr_t)object + pindex) ^ object->hash_rand;
338 return (i & vm_page_hash_mask);
342 vm_page_flag_set(vm_page_t m, unsigned short bits)
349 vm_page_flag_clear(vm_page_t m, unsigned short bits)
356 vm_page_busy(vm_page_t m)
358 KASSERT((m->flags & PG_BUSY) == 0,
359 ("vm_page_busy: page already busy!!!"));
360 vm_page_flag_set(m, PG_BUSY);
366 * wakeup anyone waiting for the page.
369 vm_page_flash(vm_page_t m)
371 if (m->flags & PG_WANTED) {
372 vm_page_flag_clear(m, PG_WANTED);
380 * clear the PG_BUSY flag and wakeup anyone waiting for the
385 vm_page_wakeup(vm_page_t m)
387 KASSERT(m->flags & PG_BUSY, ("vm_page_wakeup: page not busy!!!"));
388 vm_page_flag_clear(m, PG_BUSY);
397 vm_page_io_start(vm_page_t m)
404 vm_page_io_finish(vm_page_t m)
413 * Keep page from being freed by the page daemon
414 * much of the same effect as wiring, except much lower
415 * overhead and should be used only for *very* temporary
416 * holding ("wiring").
419 vm_page_hold(vm_page_t mem)
426 vm_page_unhold(vm_page_t mem)
430 KASSERT(mem->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!"));
431 if (mem->hold_count == 0 && mem->queue == PQ_HOLD)
432 vm_page_free_toq(mem);
438 * Reduce the protection of a page. This routine never raises the
439 * protection and therefore can be safely called if the page is already
440 * at VM_PROT_NONE (it will be a NOP effectively ).
443 vm_page_protect(vm_page_t mem, int prot)
445 if (prot == VM_PROT_NONE) {
446 if (mem->flags & (PG_WRITEABLE|PG_MAPPED)) {
447 pmap_page_protect(mem, VM_PROT_NONE);
448 vm_page_flag_clear(mem, PG_WRITEABLE|PG_MAPPED);
450 } else if ((prot == VM_PROT_READ) && (mem->flags & PG_WRITEABLE)) {
451 pmap_page_protect(mem, VM_PROT_READ);
452 vm_page_flag_clear(mem, PG_WRITEABLE);
458 * Zero-fill the specified page.
459 * Written as a standard pagein routine, to
460 * be used by the zero-fill object.
463 vm_page_zero_fill(vm_page_t m)
470 * vm_page_zero_fill_area:
472 * Like vm_page_zero_fill but only fill the specified area.
475 vm_page_zero_fill_area(vm_page_t m, int off, int size)
477 pmap_zero_page_area(m, off, size);
484 * Copy one page to another
487 vm_page_copy(vm_page_t src_m, vm_page_t dest_m)
489 pmap_copy_page(src_m, dest_m);
490 dest_m->valid = VM_PAGE_BITS_ALL;
498 * The clearing of PG_ZERO is a temporary safety until the code can be
499 * reviewed to determine that PG_ZERO is being properly cleared on
500 * write faults or maps. PG_ZERO was previously cleared in
504 vm_page_free(vm_page_t m)
506 vm_page_flag_clear(m, PG_ZERO);
508 vm_page_zero_idle_wakeup();
514 * Free a page to the zerod-pages queue
517 vm_page_free_zero(vm_page_t m)
519 vm_page_flag_set(m, PG_ZERO);
524 * vm_page_sleep_busy:
526 * Wait until page is no longer PG_BUSY or (if also_m_busy is TRUE)
527 * m->busy is zero. Returns TRUE if it had to sleep ( including if
528 * it almost had to sleep and made temporary spl*() mods), FALSE
531 * This routine assumes that interrupts can only remove the busy
532 * status from a page, not set the busy status or change it from
533 * PG_BUSY to m->busy or vise versa (which would create a timing
537 vm_page_sleep_busy(vm_page_t m, int also_m_busy, const char *msg)
540 if ((m->flags & PG_BUSY) || (also_m_busy && m->busy)) {
542 if ((m->flags & PG_BUSY) || (also_m_busy && m->busy)) {
544 * Page is busy. Wait and retry.
546 vm_page_flag_set(m, PG_WANTED | PG_REFERENCED);
547 tsleep(m, PVM, msg, 0);
558 * make page all dirty
561 vm_page_dirty(vm_page_t m)
563 KASSERT(m->queue - m->pc != PQ_CACHE,
564 ("vm_page_dirty: page in cache!"));
565 m->dirty = VM_PAGE_BITS_ALL;
571 * Set page to not be dirty. Note: does not clear pmap modify bits
574 vm_page_undirty(vm_page_t m)
580 * vm_page_insert: [ internal use only ]
582 * Inserts the given mem entry into the object and object list.
584 * The pagetables are not updated but will presumably fault the page
585 * in if necessary, or if a kernel page the caller will at some point
586 * enter the page into the kernel's pmap. We are not allowed to block
587 * here so we *can't* do this anyway.
589 * The object and page must be locked, and must be splhigh.
590 * This routine may not block.
593 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
595 struct vm_page **bucket;
599 if (m->object != NULL)
600 panic("vm_page_insert: already inserted");
603 * Record the object/offset pair in this page
609 * Insert it into the object_object/offset hash table
611 bucket = &vm_page_buckets[vm_page_hash(object, pindex)];
612 mtx_lock_spin(&vm_page_buckets_mtx);
615 mtx_unlock_spin(&vm_page_buckets_mtx);
618 * Now link into the object's list of backed pages.
620 TAILQ_INSERT_TAIL(&object->memq, m, listq);
621 object->generation++;
624 * show that the object has one more resident page.
626 object->resident_page_count++;
629 * Since we are inserting a new and possibly dirty page,
630 * update the object's OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY flags.
632 if (m->flags & PG_WRITEABLE)
633 vm_object_set_writeable_dirty(object);
638 * NOTE: used by device pager as well -wfj
640 * Removes the given mem entry from the object/offset-page
641 * table and the object page list, but do not invalidate/terminate
644 * The object and page must be locked, and at splhigh.
645 * The underlying pmap entry (if any) is NOT removed here.
646 * This routine may not block.
649 vm_page_remove(vm_page_t m)
656 if (m->object == NULL)
659 if ((m->flags & PG_BUSY) == 0) {
660 panic("vm_page_remove: page not busy");
664 * Basically destroy the page.
671 * Remove from the object_object/offset hash table. The object
672 * must be on the hash queue, we will panic if it isn't
674 bucket = &vm_page_buckets[vm_page_hash(m->object, m->pindex)];
675 mtx_lock_spin(&vm_page_buckets_mtx);
676 while (*bucket != m) {
678 panic("vm_page_remove(): page not found in hash");
679 bucket = &(*bucket)->hnext;
683 mtx_unlock_spin(&vm_page_buckets_mtx);
686 * Now remove from the object's list of backed pages.
688 TAILQ_REMOVE(&object->memq, m, listq);
691 * And show that the object has one fewer resident page.
693 object->resident_page_count--;
694 object->generation++;
702 * Returns the page associated with the object/offset
703 * pair specified; if none is found, NULL is returned.
705 * The object must be locked. No side effects.
706 * This routine may not block.
707 * This is a critical path routine
710 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
713 struct vm_page **bucket;
716 * Search the hash table for this object/offset pair
718 bucket = &vm_page_buckets[vm_page_hash(object, pindex)];
719 mtx_lock_spin(&vm_page_buckets_mtx);
720 for (m = *bucket; m != NULL; m = m->hnext)
721 if (m->object == object && m->pindex == pindex)
723 mtx_unlock_spin(&vm_page_buckets_mtx);
730 * Move the given memory entry from its
731 * current object to the specified target object/offset.
733 * The object must be locked.
734 * This routine may not block.
736 * Note: this routine will raise itself to splvm(), the caller need not.
738 * Note: swap associated with the page must be invalidated by the move. We
739 * have to do this for several reasons: (1) we aren't freeing the
740 * page, (2) we are dirtying the page, (3) the VM system is probably
741 * moving the page from object A to B, and will then later move
742 * the backing store from A to B and we can't have a conflict.
744 * Note: we *always* dirty the page. It is necessary both for the
745 * fact that we moved it, and because we may be invalidating
746 * swap. If the page is on the cache, we have to deactivate it
747 * or vm_page_dirty() will panic. Dirty pages are not allowed
751 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
756 vm_page_lock_queues();
758 vm_page_insert(m, new_object, new_pindex);
759 if (m->queue - m->pc == PQ_CACHE)
760 vm_page_deactivate(m);
762 vm_page_unlock_queues();
767 * vm_page_select_cache:
769 * Find a page on the cache queue with color optimization. As pages
770 * might be found, but not applicable, they are deactivated. This
771 * keeps us from using potentially busy cached pages.
773 * This routine must be called at splvm().
774 * This routine may not block.
777 vm_page_select_cache(vm_object_t object, vm_pindex_t pindex)
781 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
785 (pindex + object->pg_color) & PQ_L2_MASK,
788 if (m && ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy ||
789 m->hold_count || m->wire_count)) {
790 vm_page_deactivate(m);
798 * vm_page_select_free:
800 * Find a free or zero page, with specified preference.
802 * This routine must be called at splvm().
803 * This routine may not block.
805 static __inline vm_page_t
806 vm_page_select_free(vm_object_t object, vm_pindex_t pindex, boolean_t prefer_zero)
812 (pindex + object->pg_color) & PQ_L2_MASK,
821 * Allocate and return a memory cell associated
822 * with this VM object/offset pair.
825 * VM_ALLOC_NORMAL normal process request
826 * VM_ALLOC_SYSTEM system *really* needs a page
827 * VM_ALLOC_INTERRUPT interrupt time request
828 * VM_ALLOC_ZERO zero page
830 * This routine may not block.
832 * Additional special handling is required when called from an
833 * interrupt (VM_ALLOC_INTERRUPT). We are not allowed to mess with
834 * the page cache in this case.
837 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int page_req)
840 boolean_t prefer_zero;
845 KASSERT(!vm_page_lookup(object, pindex),
846 ("vm_page_alloc: page already allocated"));
848 prefer_zero = (page_req & VM_ALLOC_ZERO) != 0 ? TRUE : FALSE;
849 page_req &= ~VM_ALLOC_ZERO;
852 * The pager is allowed to eat deeper into the free page list.
854 if ((curproc == pageproc) && (page_req != VM_ALLOC_INTERRUPT)) {
855 page_req = VM_ALLOC_SYSTEM;
860 mtx_lock_spin(&vm_page_queue_free_mtx);
861 if (cnt.v_free_count > cnt.v_free_reserved) {
863 * Allocate from the free queue if there are plenty of pages
866 m = vm_page_select_free(object, pindex, prefer_zero);
868 (page_req == VM_ALLOC_SYSTEM &&
869 cnt.v_cache_count == 0 &&
870 cnt.v_free_count > cnt.v_interrupt_free_min) ||
871 (page_req == VM_ALLOC_INTERRUPT && cnt.v_free_count > 0)
874 * Interrupt or system, dig deeper into the free list.
876 m = vm_page_select_free(object, pindex, FALSE);
877 } else if (page_req != VM_ALLOC_INTERRUPT) {
878 mtx_unlock_spin(&vm_page_queue_free_mtx);
880 * Allocatable from cache (non-interrupt only). On success,
881 * we must free the page and try again, thus ensuring that
882 * cnt.v_*_free_min counters are replenished.
884 vm_page_lock_queues();
885 if ((m = vm_page_select_cache(object, pindex)) == NULL) {
886 vm_page_unlock_queues();
888 #if defined(DIAGNOSTIC)
889 if (cnt.v_cache_count > 0)
890 printf("vm_page_alloc(NORMAL): missing pages on cache queue: %d\n", cnt.v_cache_count);
892 vm_pageout_deficit++;
896 KASSERT(m->dirty == 0, ("Found dirty cache page %p", m));
898 vm_page_protect(m, VM_PROT_NONE);
900 vm_page_unlock_queues();
904 * Not allocatable from cache from interrupt, give up.
906 mtx_unlock_spin(&vm_page_queue_free_mtx);
908 vm_pageout_deficit++;
914 * At this point we had better have found a good page.
919 ("vm_page_alloc(): missing page on free queue\n")
923 * Remove from free queue
926 vm_pageq_remove_nowakeup(m);
929 * Initialize structure. Only the PG_ZERO flag is inherited.
931 if (m->flags & PG_ZERO) {
932 vm_page_zero_count--;
933 m->flags = PG_ZERO | PG_BUSY;
942 KASSERT(m->dirty == 0, ("vm_page_alloc: free/cache page %p was dirty", m));
943 mtx_unlock_spin(&vm_page_queue_free_mtx);
946 * vm_page_insert() is safe prior to the splx(). Note also that
947 * inserting a page here does not insert it into the pmap (which
948 * could cause us to block allocating memory). We cannot block
951 vm_page_insert(m, object, pindex);
954 * Don't wakeup too often - wakeup the pageout daemon when
955 * we would be nearly out of memory.
957 if (vm_paging_needed())
965 * vm_wait: (also see VM_WAIT macro)
967 * Block until free pages are available for allocation
968 * - Called in various places before memory allocations.
976 if (curproc == pageproc) {
977 vm_pageout_pages_needed = 1;
978 tsleep(&vm_pageout_pages_needed, PSWP, "VMWait", 0);
980 if (!vm_pages_needed) {
982 wakeup(&vm_pages_needed);
984 tsleep(&cnt.v_free_count, PVM, "vmwait", 0);
990 * vm_waitpfault: (also see VM_WAITPFAULT macro)
992 * Block until free pages are available for allocation
993 * - Called only in vm_fault so that processes page faulting
994 * can be easily tracked.
995 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
996 * processes will be able to grab memory first. Do not change
997 * this balance without careful testing first.
1005 if (!vm_pages_needed) {
1006 vm_pages_needed = 1;
1007 wakeup(&vm_pages_needed);
1009 tsleep(&cnt.v_free_count, PUSER, "pfault", 0);
1016 * Put the specified page on the active list (if appropriate).
1017 * Ensure that act_count is at least ACT_INIT but do not otherwise
1020 * The page queues must be locked.
1021 * This routine may not block.
1024 vm_page_activate(vm_page_t m)
1030 if (m->queue != PQ_ACTIVE) {
1031 if ((m->queue - m->pc) == PQ_CACHE)
1032 cnt.v_reactivated++;
1034 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1035 if (m->act_count < ACT_INIT)
1036 m->act_count = ACT_INIT;
1037 vm_pageq_enqueue(PQ_ACTIVE, m);
1040 if (m->act_count < ACT_INIT)
1041 m->act_count = ACT_INIT;
1047 * vm_page_free_wakeup:
1049 * Helper routine for vm_page_free_toq() and vm_page_cache(). This
1050 * routine is called when a page has been added to the cache or free
1053 * This routine may not block.
1054 * This routine must be called at splvm()
1056 static __inline void
1057 vm_page_free_wakeup(void)
1060 * if pageout daemon needs pages, then tell it that there are
1063 if (vm_pageout_pages_needed &&
1064 cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
1065 wakeup(&vm_pageout_pages_needed);
1066 vm_pageout_pages_needed = 0;
1069 * wakeup processes that are waiting on memory if we hit a
1070 * high water mark. And wakeup scheduler process if we have
1071 * lots of memory. this process will swapin processes.
1073 if (vm_pages_needed && !vm_page_count_min()) {
1074 vm_pages_needed = 0;
1075 wakeup(&cnt.v_free_count);
1082 * Returns the given page to the PQ_FREE list,
1083 * disassociating it with any VM object.
1085 * Object and page must be locked prior to entry.
1086 * This routine may not block.
1090 vm_page_free_toq(vm_page_t m)
1093 struct vpgqueues *pq;
1094 vm_object_t object = m->object;
1100 if (m->busy || ((m->queue - m->pc) == PQ_FREE)) {
1102 "vm_page_free: pindex(%lu), busy(%d), PG_BUSY(%d), hold(%d)\n",
1103 (u_long)m->pindex, m->busy, (m->flags & PG_BUSY) ? 1 : 0,
1105 if ((m->queue - m->pc) == PQ_FREE)
1106 panic("vm_page_free: freeing free page");
1108 panic("vm_page_free: freeing busy page");
1112 * unqueue, then remove page. Note that we cannot destroy
1113 * the page here because we do not want to call the pager's
1114 * callback routine until after we've put the page on the
1115 * appropriate free queue.
1117 vm_pageq_remove_nowakeup(m);
1121 * If fictitious remove object association and
1122 * return, otherwise delay object association removal.
1124 if ((m->flags & PG_FICTITIOUS) != 0) {
1132 if (m->wire_count != 0) {
1133 if (m->wire_count > 1) {
1134 panic("vm_page_free: invalid wire count (%d), pindex: 0x%lx",
1135 m->wire_count, (long)m->pindex);
1137 panic("vm_page_free: freeing wired page\n");
1141 * If we've exhausted the object's resident pages we want to free
1145 (object->type == OBJT_VNODE) &&
1146 ((object->flags & OBJ_DEAD) == 0)
1148 struct vnode *vp = (struct vnode *)object->handle;
1150 if (vp && VSHOULDFREE(vp))
1155 * Clear the UNMANAGED flag when freeing an unmanaged page.
1157 if (m->flags & PG_UNMANAGED) {
1158 m->flags &= ~PG_UNMANAGED;
1161 pmap_page_is_free(m);
1165 if (m->hold_count != 0) {
1166 m->flags &= ~PG_ZERO;
1169 m->queue = PQ_FREE + m->pc;
1170 pq = &vm_page_queues[m->queue];
1171 mtx_lock_spin(&vm_page_queue_free_mtx);
1176 * Put zero'd pages on the end ( where we look for zero'd pages
1177 * first ) and non-zerod pages at the head.
1179 if (m->flags & PG_ZERO) {
1180 TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
1181 ++vm_page_zero_count;
1183 TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
1185 mtx_unlock_spin(&vm_page_queue_free_mtx);
1186 vm_page_free_wakeup();
1193 * Prevent PV management from being done on the page. The page is
1194 * removed from the paging queues as if it were wired, and as a
1195 * consequence of no longer being managed the pageout daemon will not
1196 * touch it (since there is no way to locate the pte mappings for the
1197 * page). madvise() calls that mess with the pmap will also no longer
1198 * operate on the page.
1200 * Beyond that the page is still reasonably 'normal'. Freeing the page
1201 * will clear the flag.
1203 * This routine is used by OBJT_PHYS objects - objects using unswappable
1204 * physical memory as backing store rather then swap-backed memory and
1205 * will eventually be extended to support 4MB unmanaged physical
1209 vm_page_unmanage(vm_page_t m)
1214 if ((m->flags & PG_UNMANAGED) == 0) {
1215 if (m->wire_count == 0)
1218 vm_page_flag_set(m, PG_UNMANAGED);
1225 * Mark this page as wired down by yet
1226 * another map, removing it from paging queues
1229 * The page queues must be locked.
1230 * This routine may not block.
1233 vm_page_wire(vm_page_t m)
1238 * Only bump the wire statistics if the page is not already wired,
1239 * and only unqueue the page if it is on some queue (if it is unmanaged
1240 * it is already off the queues).
1243 if (m->wire_count == 0) {
1244 if ((m->flags & PG_UNMANAGED) == 0)
1249 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
1251 vm_page_flag_set(m, PG_MAPPED);
1257 * Release one wiring of this page, potentially
1258 * enabling it to be paged again.
1260 * Many pages placed on the inactive queue should actually go
1261 * into the cache, but it is difficult to figure out which. What
1262 * we do instead, if the inactive target is well met, is to put
1263 * clean pages at the head of the inactive queue instead of the tail.
1264 * This will cause them to be moved to the cache more quickly and
1265 * if not actively re-referenced, freed more quickly. If we just
1266 * stick these pages at the end of the inactive queue, heavy filesystem
1267 * meta-data accesses can cause an unnecessary paging load on memory bound
1268 * processes. This optimization causes one-time-use metadata to be
1269 * reused more quickly.
1271 * BUT, if we are in a low-memory situation we have no choice but to
1272 * put clean pages on the cache queue.
1274 * A number of routines use vm_page_unwire() to guarantee that the page
1275 * will go into either the inactive or active queues, and will NEVER
1276 * be placed in the cache - for example, just after dirtying a page.
1277 * dirty pages in the cache are not allowed.
1279 * The page queues must be locked.
1280 * This routine may not block.
1283 vm_page_unwire(vm_page_t m, int activate)
1288 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1289 if (m->wire_count > 0) {
1291 if (m->wire_count == 0) {
1293 if (m->flags & PG_UNMANAGED) {
1295 } else if (activate)
1296 vm_pageq_enqueue(PQ_ACTIVE, m);
1298 vm_page_flag_clear(m, PG_WINATCFLS);
1299 vm_pageq_enqueue(PQ_INACTIVE, m);
1303 panic("vm_page_unwire: invalid wire count: %d\n", m->wire_count);
1310 * Move the specified page to the inactive queue. If the page has
1311 * any associated swap, the swap is deallocated.
1313 * Normally athead is 0 resulting in LRU operation. athead is set
1314 * to 1 if we want this page to be 'as if it were placed in the cache',
1315 * except without unmapping it from the process address space.
1317 * This routine may not block.
1319 static __inline void
1320 _vm_page_deactivate(vm_page_t m, int athead)
1326 * Ignore if already inactive.
1328 if (m->queue == PQ_INACTIVE)
1332 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1333 if ((m->queue - m->pc) == PQ_CACHE)
1334 cnt.v_reactivated++;
1335 vm_page_flag_clear(m, PG_WINATCFLS);
1338 TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1340 TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1341 m->queue = PQ_INACTIVE;
1342 vm_page_queues[PQ_INACTIVE].lcnt++;
1343 cnt.v_inactive_count++;
1349 vm_page_deactivate(vm_page_t m)
1351 _vm_page_deactivate(m, 0);
1355 * vm_page_try_to_cache:
1357 * Returns 0 on failure, 1 on success
1360 vm_page_try_to_cache(vm_page_t m)
1364 if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1365 (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1368 vm_page_test_dirty(m);
1376 * vm_page_try_to_free()
1378 * Attempt to free the page. If we cannot free it, we do nothing.
1379 * 1 is returned on success, 0 on failure.
1382 vm_page_try_to_free(vm_page_t m)
1384 if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1385 (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1388 vm_page_test_dirty(m);
1392 vm_page_protect(m, VM_PROT_NONE);
1400 * Put the specified page onto the page cache queue (if appropriate).
1402 * This routine may not block.
1405 vm_page_cache(vm_page_t m)
1410 if ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy || m->wire_count) {
1411 printf("vm_page_cache: attempting to cache busy page\n");
1414 if ((m->queue - m->pc) == PQ_CACHE)
1418 * Remove all pmaps and indicate that the page is not
1419 * writeable or mapped.
1421 vm_page_protect(m, VM_PROT_NONE);
1422 if (m->dirty != 0) {
1423 panic("vm_page_cache: caching a dirty page, pindex: %ld",
1427 vm_pageq_remove_nowakeup(m);
1428 vm_pageq_enqueue(PQ_CACHE + m->pc, m);
1429 vm_page_free_wakeup();
1436 * Cache, deactivate, or do nothing as appropriate. This routine
1437 * is typically used by madvise() MADV_DONTNEED.
1439 * Generally speaking we want to move the page into the cache so
1440 * it gets reused quickly. However, this can result in a silly syndrome
1441 * due to the page recycling too quickly. Small objects will not be
1442 * fully cached. On the otherhand, if we move the page to the inactive
1443 * queue we wind up with a problem whereby very large objects
1444 * unnecessarily blow away our inactive and cache queues.
1446 * The solution is to move the pages based on a fixed weighting. We
1447 * either leave them alone, deactivate them, or move them to the cache,
1448 * where moving them to the cache has the highest weighting.
1449 * By forcing some pages into other queues we eventually force the
1450 * system to balance the queues, potentially recovering other unrelated
1451 * space from active. The idea is to not force this to happen too
1455 vm_page_dontneed(vm_page_t m)
1457 static int dnweight;
1465 * occassionally leave the page alone
1467 if ((dnw & 0x01F0) == 0 ||
1468 m->queue == PQ_INACTIVE ||
1469 m->queue - m->pc == PQ_CACHE
1471 if (m->act_count >= ACT_INIT)
1477 vm_page_test_dirty(m);
1479 if (m->dirty || (dnw & 0x0070) == 0) {
1481 * Deactivate the page 3 times out of 32.
1486 * Cache the page 28 times out of every 32. Note that
1487 * the page is deactivated instead of cached, but placed
1488 * at the head of the queue instead of the tail.
1492 _vm_page_deactivate(m, head);
1496 * Grab a page, waiting until we are waken up due to the page
1497 * changing state. We keep on waiting, if the page continues
1498 * to be in the object. If the page doesn't exist, allocate it.
1500 * This routine may block.
1503 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
1510 if ((m = vm_page_lookup(object, pindex)) != NULL) {
1511 if (m->busy || (m->flags & PG_BUSY)) {
1512 generation = object->generation;
1515 while ((object->generation == generation) &&
1516 (m->busy || (m->flags & PG_BUSY))) {
1517 vm_page_flag_set(m, PG_WANTED | PG_REFERENCED);
1518 tsleep(m, PVM, "pgrbwt", 0);
1519 if ((allocflags & VM_ALLOC_RETRY) == 0) {
1532 m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_RETRY);
1535 if ((allocflags & VM_ALLOC_RETRY) == 0)
1544 * Mapping function for valid bits or for dirty bits in
1545 * a page. May not block.
1547 * Inputs are required to range within a page.
1550 vm_page_bits(int base, int size)
1556 base + size <= PAGE_SIZE,
1557 ("vm_page_bits: illegal base/size %d/%d", base, size)
1560 if (size == 0) /* handle degenerate case */
1563 first_bit = base >> DEV_BSHIFT;
1564 last_bit = (base + size - 1) >> DEV_BSHIFT;
1566 return ((2 << last_bit) - (1 << first_bit));
1570 * vm_page_set_validclean:
1572 * Sets portions of a page valid and clean. The arguments are expected
1573 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
1574 * of any partial chunks touched by the range. The invalid portion of
1575 * such chunks will be zero'd.
1577 * This routine may not block.
1579 * (base + size) must be less then or equal to PAGE_SIZE.
1582 vm_page_set_validclean(vm_page_t m, int base, int size)
1589 if (size == 0) /* handle degenerate case */
1593 * If the base is not DEV_BSIZE aligned and the valid
1594 * bit is clear, we have to zero out a portion of the
1597 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
1598 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
1599 pmap_zero_page_area(m, frag, base - frag);
1602 * If the ending offset is not DEV_BSIZE aligned and the
1603 * valid bit is clear, we have to zero out a portion of
1606 endoff = base + size;
1607 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
1608 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
1609 pmap_zero_page_area(m, endoff,
1610 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
1613 * Set valid, clear dirty bits. If validating the entire
1614 * page we can safely clear the pmap modify bit. We also
1615 * use this opportunity to clear the PG_NOSYNC flag. If a process
1616 * takes a write fault on a MAP_NOSYNC memory area the flag will
1619 * We set valid bits inclusive of any overlap, but we can only
1620 * clear dirty bits for DEV_BSIZE chunks that are fully within
1623 pagebits = vm_page_bits(base, size);
1624 m->valid |= pagebits;
1626 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
1627 frag = DEV_BSIZE - frag;
1633 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
1635 m->dirty &= ~pagebits;
1636 if (base == 0 && size == PAGE_SIZE) {
1637 pmap_clear_modify(m);
1638 vm_page_flag_clear(m, PG_NOSYNC);
1645 vm_page_set_dirty(vm_page_t m, int base, int size)
1647 m->dirty |= vm_page_bits(base, size);
1653 vm_page_clear_dirty(vm_page_t m, int base, int size)
1656 m->dirty &= ~vm_page_bits(base, size);
1660 * vm_page_set_invalid:
1662 * Invalidates DEV_BSIZE'd chunks within a page. Both the
1663 * valid and dirty bits for the effected areas are cleared.
1668 vm_page_set_invalid(vm_page_t m, int base, int size)
1673 bits = vm_page_bits(base, size);
1676 m->object->generation++;
1680 * vm_page_zero_invalid()
1682 * The kernel assumes that the invalid portions of a page contain
1683 * garbage, but such pages can be mapped into memory by user code.
1684 * When this occurs, we must zero out the non-valid portions of the
1685 * page so user code sees what it expects.
1687 * Pages are most often semi-valid when the end of a file is mapped
1688 * into memory and the file's size is not page aligned.
1691 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
1697 * Scan the valid bits looking for invalid sections that
1698 * must be zerod. Invalid sub-DEV_BSIZE'd areas ( where the
1699 * valid bit may be set ) have already been zerod by
1700 * vm_page_set_validclean().
1702 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
1703 if (i == (PAGE_SIZE / DEV_BSIZE) ||
1704 (m->valid & (1 << i))
1707 pmap_zero_page_area(m,
1708 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
1715 * setvalid is TRUE when we can safely set the zero'd areas
1716 * as being valid. We can do this if there are no cache consistancy
1717 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
1720 m->valid = VM_PAGE_BITS_ALL;
1726 * Is (partial) page valid? Note that the case where size == 0
1727 * will return FALSE in the degenerate case where the page is
1728 * entirely invalid, and TRUE otherwise.
1733 vm_page_is_valid(vm_page_t m, int base, int size)
1735 int bits = vm_page_bits(base, size);
1737 if (m->valid && ((m->valid & bits) == bits))
1744 * update dirty bits from pmap/mmu. May not block.
1747 vm_page_test_dirty(vm_page_t m)
1749 if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
1754 int so_zerocp_fullpage = 0;
1757 vm_page_cowfault(vm_page_t m)
1769 mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL);
1771 vm_page_insert(m, object, pindex);
1778 * check to see if we raced with an xmit complete when
1779 * waiting to allocate a page. If so, put things back
1784 vm_page_insert(m, object, pindex);
1785 } else { /* clear COW & copy page */
1786 if (so_zerocp_fullpage) {
1787 mnew->valid = VM_PAGE_BITS_ALL;
1789 vm_page_copy(m, mnew);
1791 vm_page_dirty(mnew);
1792 vm_page_flag_clear(mnew, PG_BUSY);
1797 vm_page_cowclear(vm_page_t m)
1800 /* XXX KDM find out if giant is required here. */
1803 atomic_subtract_int(&m->cow, 1);
1805 * let vm_fault add back write permission lazily
1809 * sf_buf_free() will free the page, so we needn't do it here
1814 vm_page_cowsetup(vm_page_t m)
1816 /* XXX KDM find out if giant is required here */
1818 atomic_add_int(&m->cow, 1);
1819 vm_page_protect(m, VM_PROT_READ);
1822 #include "opt_ddb.h"
1824 #include <sys/kernel.h>
1826 #include <ddb/ddb.h>
1828 DB_SHOW_COMMAND(page, vm_page_print_page_info)
1830 db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
1831 db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
1832 db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
1833 db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
1834 db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
1835 db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
1836 db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
1837 db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
1838 db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
1839 db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
1842 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
1845 db_printf("PQ_FREE:");
1846 for (i = 0; i < PQ_L2_SIZE; i++) {
1847 db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt);
1851 db_printf("PQ_CACHE:");
1852 for (i = 0; i < PQ_L2_SIZE; i++) {
1853 db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt);
1857 db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
1858 vm_page_queues[PQ_ACTIVE].lcnt,
1859 vm_page_queues[PQ_INACTIVE].lcnt);