2 * Copyright (c) 1991 Regents of the University of California.
4 * Copyright (c) 1998 Matthew Dillon. All Rights Reserved.
6 * This code is derived from software contributed to Berkeley by
7 * The Mach Operating System project at Carnegie-Mellon University.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * from: @(#)vm_page.c 7.4 (Berkeley) 5/7/91
37 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38 * All rights reserved.
40 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
42 * Permission to use, copy, modify and distribute this software and
43 * its documentation is hereby granted, provided that both the copyright
44 * notice and this permission notice appear in all copies of the
45 * software, derivative works or modified versions, and any portions
46 * thereof, and that both notices appear in supporting documentation.
48 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
52 * Carnegie Mellon requests users of this software to return to
54 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
55 * School of Computer Science
56 * Carnegie Mellon University
57 * Pittsburgh PA 15213-3890
59 * any improvements or extensions that they make and grant Carnegie the
60 * rights to redistribute these changes.
64 * GENERAL RULES ON VM_PAGE MANIPULATION
66 * - a pageq mutex is required when adding or removing a page from a
67 * page queue (vm_page_queue[]), regardless of other mutexes or the
68 * busy state of a page.
70 * - a hash chain mutex is required when associating or disassociating
71 * a page from the VM PAGE CACHE hash table (vm_page_buckets),
72 * regardless of other mutexes or the busy state of a page.
74 * - either a hash chain mutex OR a busied page is required in order
75 * to modify the page flags. A hash chain mutex must be obtained in
76 * order to busy a page. A page's flags cannot be modified by a
77 * hash chain mutex if the page is marked busy.
79 * - The object memq mutex is held when inserting or removing
80 * pages from an object (vm_page_insert() or vm_page_remove()). This
81 * is different from the object's main mutex.
83 * Generally speaking, you have to be aware of side effects when running
84 * vm_page ops. A vm_page_lookup() will return with the hash chain
85 * locked, whether it was able to lookup the page or not. vm_page_free(),
86 * vm_page_cache(), vm_page_activate(), and a number of other routines
87 * will release the hash chain mutex for you. Intermediate manipulation
88 * routines such as vm_page_flag_set() expect the hash chain to be held
89 * on entry and the hash chain will remain held on return.
91 * pageq scanning can only occur with the pageq in question locked.
92 * We have a known bottleneck with the active queue, but the cache
93 * and free queues are actually arrays already.
97 * Resident memory management module.
100 #include <sys/cdefs.h>
101 __FBSDID("$FreeBSD$");
105 #include <sys/param.h>
106 #include <sys/systm.h>
107 #include <sys/lock.h>
108 #include <sys/kernel.h>
109 #include <sys/limits.h>
110 #include <sys/malloc.h>
111 #include <sys/msgbuf.h>
112 #include <sys/mutex.h>
113 #include <sys/proc.h>
114 #include <sys/sysctl.h>
115 #include <sys/vmmeter.h>
116 #include <sys/vnode.h>
119 #include <vm/vm_param.h>
120 #include <vm/vm_kern.h>
121 #include <vm/vm_object.h>
122 #include <vm/vm_page.h>
123 #include <vm/vm_pageout.h>
124 #include <vm/vm_pager.h>
125 #include <vm/vm_phys.h>
126 #include <vm/vm_reserv.h>
127 #include <vm/vm_extern.h>
129 #include <vm/uma_int.h>
131 #include <machine/md_var.h>
134 * Associated with page of user-allocatable memory is a
138 struct vpgqueues vm_page_queues[PQ_COUNT];
139 struct mtx vm_page_queue_mtx;
140 struct mtx vm_page_queue_free_mtx;
142 vm_page_t vm_page_array = 0;
143 int vm_page_array_size = 0;
145 int vm_page_zero_count = 0;
147 static int boot_pages = UMA_BOOT_PAGES;
148 TUNABLE_INT("vm.boot_pages", &boot_pages);
149 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RD, &boot_pages, 0,
150 "number of pages allocated for bootstrapping the VM system");
152 static void vm_page_enqueue(int queue, vm_page_t m);
154 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
155 #if PAGE_SIZE == 32768
157 CTASSERT(sizeof(u_long) >= 8);
164 * Sets the page size, perhaps based upon the memory
165 * size. Must be called before any use of page-size
166 * dependent functions.
169 vm_set_page_size(void)
171 if (cnt.v_page_size == 0)
172 cnt.v_page_size = PAGE_SIZE;
173 if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0)
174 panic("vm_set_page_size: page size not a power of two");
178 * vm_page_blacklist_lookup:
180 * See if a physical address in this page has been listed
181 * in the blacklist tunable. Entries in the tunable are
182 * separated by spaces or commas. If an invalid integer is
183 * encountered then the rest of the string is skipped.
186 vm_page_blacklist_lookup(char *list, vm_paddr_t pa)
191 for (pos = list; *pos != '\0'; pos = cp) {
192 bad = strtoq(pos, &cp, 0);
194 if (*cp == ' ' || *cp == ',') {
201 if (pa == trunc_page(bad))
210 * Initializes the resident memory module.
212 * Allocates memory for the page cells, and
213 * for the object/offset-to-page hash table headers.
214 * Each page cell is initialized and placed on the free list.
217 vm_page_startup(vm_offset_t vaddr)
220 vm_paddr_t page_range;
227 /* the biggest memory array is the second group of pages */
229 vm_paddr_t biggestsize;
230 vm_paddr_t low_water, high_water;
235 vaddr = round_page(vaddr);
237 for (i = 0; phys_avail[i + 1]; i += 2) {
238 phys_avail[i] = round_page(phys_avail[i]);
239 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
242 low_water = phys_avail[0];
243 high_water = phys_avail[1];
245 for (i = 0; phys_avail[i + 1]; i += 2) {
246 vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
248 if (size > biggestsize) {
252 if (phys_avail[i] < low_water)
253 low_water = phys_avail[i];
254 if (phys_avail[i + 1] > high_water)
255 high_water = phys_avail[i + 1];
262 end = phys_avail[biggestone+1];
265 * Initialize the locks.
267 mtx_init(&vm_page_queue_mtx, "vm page queue mutex", NULL, MTX_DEF |
269 mtx_init(&vm_page_queue_free_mtx, "vm page queue free mutex", NULL,
273 * Initialize the queue headers for the hold queue, the active queue,
274 * and the inactive queue.
276 for (i = 0; i < PQ_COUNT; i++)
277 TAILQ_INIT(&vm_page_queues[i].pl);
278 vm_page_queues[PQ_INACTIVE].cnt = &cnt.v_inactive_count;
279 vm_page_queues[PQ_ACTIVE].cnt = &cnt.v_active_count;
280 vm_page_queues[PQ_HOLD].cnt = &cnt.v_active_count;
283 * Allocate memory for use when boot strapping the kernel memory
286 new_end = end - (boot_pages * UMA_SLAB_SIZE);
287 new_end = trunc_page(new_end);
288 mapped = pmap_map(&vaddr, new_end, end,
289 VM_PROT_READ | VM_PROT_WRITE);
290 bzero((void *)mapped, end - new_end);
291 uma_startup((void *)mapped, boot_pages);
293 #if defined(__amd64__) || defined(__i386__) || defined(__arm__) || \
296 * Allocate a bitmap to indicate that a random physical page
297 * needs to be included in a minidump.
299 * The amd64 port needs this to indicate which direct map pages
300 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
302 * However, i386 still needs this workspace internally within the
303 * minidump code. In theory, they are not needed on i386, but are
304 * included should the sf_buf code decide to use them.
307 for (i = 0; dump_avail[i + 1] != 0; i += 2)
308 if (dump_avail[i + 1] > last_pa)
309 last_pa = dump_avail[i + 1];
310 page_range = last_pa / PAGE_SIZE;
311 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
312 new_end -= vm_page_dump_size;
313 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
314 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
315 bzero((void *)vm_page_dump, vm_page_dump_size);
319 * Request that the physical pages underlying the message buffer be
320 * included in a crash dump. Since the message buffer is accessed
321 * through the direct map, they are not automatically included.
323 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
324 last_pa = pa + round_page(msgbufsize);
325 while (pa < last_pa) {
331 * Compute the number of pages of memory that will be available for
332 * use (taking into account the overhead of a page structure per
335 first_page = low_water / PAGE_SIZE;
336 #ifdef VM_PHYSSEG_SPARSE
338 for (i = 0; phys_avail[i + 1] != 0; i += 2)
339 page_range += atop(phys_avail[i + 1] - phys_avail[i]);
340 #elif defined(VM_PHYSSEG_DENSE)
341 page_range = high_water / PAGE_SIZE - first_page;
343 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
348 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
353 * Initialize the mem entry structures now, and put them in the free
356 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
357 mapped = pmap_map(&vaddr, new_end, end,
358 VM_PROT_READ | VM_PROT_WRITE);
359 vm_page_array = (vm_page_t) mapped;
360 #if VM_NRESERVLEVEL > 0
362 * Allocate memory for the reservation management system's data
365 new_end = vm_reserv_startup(&vaddr, new_end, high_water);
369 * pmap_map on amd64 comes out of the direct-map, not kvm like i386,
370 * so the pages must be tracked for a crashdump to include this data.
371 * This includes the vm_page_array and the early UMA bootstrap pages.
373 for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
376 phys_avail[biggestone + 1] = new_end;
379 * Clear all of the page structures
381 bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
382 for (i = 0; i < page_range; i++)
383 vm_page_array[i].order = VM_NFREEORDER;
384 vm_page_array_size = page_range;
387 * Initialize the physical memory allocator.
392 * Add every available physical page that is not blacklisted to
395 cnt.v_page_count = 0;
396 cnt.v_free_count = 0;
397 list = getenv("vm.blacklist");
398 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
400 last_pa = phys_avail[i + 1];
401 while (pa < last_pa) {
403 vm_page_blacklist_lookup(list, pa))
404 printf("Skipping page with pa 0x%jx\n",
407 vm_phys_add_page(pa);
412 #if VM_NRESERVLEVEL > 0
414 * Initialize the reservation management system.
422 vm_page_flag_set(vm_page_t m, unsigned short bits)
425 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
430 vm_page_flag_clear(vm_page_t m, unsigned short bits)
433 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
438 vm_page_busy(vm_page_t m)
441 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
442 KASSERT((m->oflags & VPO_BUSY) == 0,
443 ("vm_page_busy: page already busy!!!"));
444 m->oflags |= VPO_BUSY;
450 * wakeup anyone waiting for the page.
453 vm_page_flash(vm_page_t m)
456 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
457 if (m->oflags & VPO_WANTED) {
458 m->oflags &= ~VPO_WANTED;
466 * clear the VPO_BUSY flag and wakeup anyone waiting for the
471 vm_page_wakeup(vm_page_t m)
474 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
475 KASSERT(m->oflags & VPO_BUSY, ("vm_page_wakeup: page not busy!!!"));
476 m->oflags &= ~VPO_BUSY;
481 vm_page_io_start(vm_page_t m)
484 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
489 vm_page_io_finish(vm_page_t m)
492 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
499 * Keep page from being freed by the page daemon
500 * much of the same effect as wiring, except much lower
501 * overhead and should be used only for *very* temporary
502 * holding ("wiring").
505 vm_page_hold(vm_page_t mem)
508 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
513 vm_page_unhold(vm_page_t mem)
516 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
518 KASSERT(mem->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!"));
519 if (mem->hold_count == 0 && VM_PAGE_INQUEUE2(mem, PQ_HOLD))
520 vm_page_free_toq(mem);
529 vm_page_free(vm_page_t m)
532 m->flags &= ~PG_ZERO;
539 * Free a page to the zerod-pages queue
542 vm_page_free_zero(vm_page_t m)
552 * Sleep and release the page queues lock.
554 * The object containing the given page must be locked.
557 vm_page_sleep(vm_page_t m, const char *msg)
560 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
561 if (!mtx_owned(&vm_page_queue_mtx))
562 vm_page_lock_queues();
563 vm_page_flag_set(m, PG_REFERENCED);
564 vm_page_unlock_queues();
567 * It's possible that while we sleep, the page will get
568 * unbusied and freed. If we are holding the object
569 * lock, we will assume we hold a reference to the object
570 * such that even if m->object changes, we can re-lock
573 m->oflags |= VPO_WANTED;
574 msleep(m, VM_OBJECT_MTX(m->object), PVM, msg, 0);
580 * make page all dirty
583 vm_page_dirty(vm_page_t m)
586 KASSERT((m->flags & PG_CACHED) == 0,
587 ("vm_page_dirty: page in cache!"));
588 KASSERT(!VM_PAGE_IS_FREE(m),
589 ("vm_page_dirty: page is free!"));
590 KASSERT(m->valid == VM_PAGE_BITS_ALL,
591 ("vm_page_dirty: page is invalid!"));
592 m->dirty = VM_PAGE_BITS_ALL;
598 * Implements Sleator and Tarjan's top-down splay algorithm. Returns
599 * the vm_page containing the given pindex. If, however, that
600 * pindex is not found in the vm_object, returns a vm_page that is
601 * adjacent to the pindex, coming before or after it.
604 vm_page_splay(vm_pindex_t pindex, vm_page_t root)
606 struct vm_page dummy;
607 vm_page_t lefttreemax, righttreemin, y;
611 lefttreemax = righttreemin = &dummy;
613 if (pindex < root->pindex) {
614 if ((y = root->left) == NULL)
616 if (pindex < y->pindex) {
618 root->left = y->right;
621 if ((y = root->left) == NULL)
624 /* Link into the new root's right tree. */
625 righttreemin->left = root;
627 } else if (pindex > root->pindex) {
628 if ((y = root->right) == NULL)
630 if (pindex > y->pindex) {
632 root->right = y->left;
635 if ((y = root->right) == NULL)
638 /* Link into the new root's left tree. */
639 lefttreemax->right = root;
644 /* Assemble the new root. */
645 lefttreemax->right = root->left;
646 righttreemin->left = root->right;
647 root->left = dummy.right;
648 root->right = dummy.left;
653 * vm_page_insert: [ internal use only ]
655 * Inserts the given mem entry into the object and object list.
657 * The pagetables are not updated but will presumably fault the page
658 * in if necessary, or if a kernel page the caller will at some point
659 * enter the page into the kernel's pmap. We are not allowed to block
660 * here so we *can't* do this anyway.
662 * The object and page must be locked.
663 * This routine may not block.
666 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
670 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
671 if (m->object != NULL)
672 panic("vm_page_insert: page already inserted");
675 * Record the object/offset pair in this page
681 * Now link into the object's ordered list of backed pages.
687 TAILQ_INSERT_TAIL(&object->memq, m, listq);
689 root = vm_page_splay(pindex, root);
690 if (pindex < root->pindex) {
691 m->left = root->left;
694 TAILQ_INSERT_BEFORE(root, m, listq);
695 } else if (pindex == root->pindex)
696 panic("vm_page_insert: offset already allocated");
698 m->right = root->right;
701 TAILQ_INSERT_AFTER(&object->memq, root, m, listq);
707 * show that the object has one more resident page.
709 object->resident_page_count++;
711 * Hold the vnode until the last page is released.
713 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
714 vhold((struct vnode *)object->handle);
717 * Since we are inserting a new and possibly dirty page,
718 * update the object's OBJ_MIGHTBEDIRTY flag.
720 if (m->flags & PG_WRITEABLE)
721 vm_object_set_writeable_dirty(object);
726 * NOTE: used by device pager as well -wfj
728 * Removes the given mem entry from the object/offset-page
729 * table and the object page list, but do not invalidate/terminate
732 * The object and page must be locked.
733 * The underlying pmap entry (if any) is NOT removed here.
734 * This routine may not block.
737 vm_page_remove(vm_page_t m)
742 if ((object = m->object) == NULL)
744 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
745 if (m->oflags & VPO_BUSY) {
746 m->oflags &= ~VPO_BUSY;
749 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
752 * Now remove from the object's list of backed pages.
754 if (m != object->root)
755 vm_page_splay(m->pindex, object->root);
759 root = vm_page_splay(m->pindex, m->left);
760 root->right = m->right;
763 TAILQ_REMOVE(&object->memq, m, listq);
766 * And show that the object has one fewer resident page.
768 object->resident_page_count--;
770 * The vnode may now be recycled.
772 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
773 vdrop((struct vnode *)object->handle);
781 * Returns the page associated with the object/offset
782 * pair specified; if none is found, NULL is returned.
784 * The object must be locked.
785 * This routine may not block.
786 * This is a critical path routine
789 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
793 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
794 if ((m = object->root) != NULL && m->pindex != pindex) {
795 m = vm_page_splay(pindex, m);
796 if ((object->root = m)->pindex != pindex)
803 * vm_page_find_least:
805 * Returns the page associated with the object with least pindex
806 * greater than or equal to the parameter pindex, or NULL.
808 * The object must be locked.
809 * The routine may not block.
812 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
816 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
817 if ((m = TAILQ_FIRST(&object->memq)) != NULL) {
818 if (m->pindex < pindex) {
819 m = vm_page_splay(pindex, object->root);
820 if ((object->root = m)->pindex < pindex)
821 m = TAILQ_NEXT(m, listq);
828 * Returns the given page's successor (by pindex) within the object if it is
829 * resident; if none is found, NULL is returned.
831 * The object must be locked.
834 vm_page_next(vm_page_t m)
838 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
839 if ((next = TAILQ_NEXT(m, listq)) != NULL &&
840 next->pindex != m->pindex + 1)
846 * Returns the given page's predecessor (by pindex) within the object if it is
847 * resident; if none is found, NULL is returned.
849 * The object must be locked.
852 vm_page_prev(vm_page_t m)
856 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
857 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
858 prev->pindex != m->pindex - 1)
866 * Move the given memory entry from its
867 * current object to the specified target object/offset.
869 * The object must be locked.
870 * This routine may not block.
872 * Note: swap associated with the page must be invalidated by the move. We
873 * have to do this for several reasons: (1) we aren't freeing the
874 * page, (2) we are dirtying the page, (3) the VM system is probably
875 * moving the page from object A to B, and will then later move
876 * the backing store from A to B and we can't have a conflict.
878 * Note: we *always* dirty the page. It is necessary both for the
879 * fact that we moved it, and because we may be invalidating
880 * swap. If the page is on the cache, we have to deactivate it
881 * or vm_page_dirty() will panic. Dirty pages are not allowed
885 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
889 vm_page_insert(m, new_object, new_pindex);
894 * Convert all of the given object's cached pages that have a
895 * pindex within the given range into free pages. If the value
896 * zero is given for "end", then the range's upper bound is
897 * infinity. If the given object is backed by a vnode and it
898 * transitions from having one or more cached pages to none, the
899 * vnode's hold count is reduced.
902 vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
907 mtx_lock(&vm_page_queue_free_mtx);
908 if (__predict_false(object->cache == NULL)) {
909 mtx_unlock(&vm_page_queue_free_mtx);
912 m = object->cache = vm_page_splay(start, object->cache);
913 if (m->pindex < start) {
914 if (m->right == NULL)
917 m_next = vm_page_splay(start, m->right);
920 m = object->cache = m_next;
925 * At this point, "m" is either (1) a reference to the page
926 * with the least pindex that is greater than or equal to
927 * "start" or (2) NULL.
929 for (; m != NULL && (m->pindex < end || end == 0); m = m_next) {
931 * Find "m"'s successor and remove "m" from the
934 if (m->right == NULL) {
935 object->cache = m->left;
938 m_next = vm_page_splay(start, m->right);
939 m_next->left = m->left;
940 object->cache = m_next;
942 /* Convert "m" to a free page. */
945 /* Clear PG_CACHED and set PG_FREE. */
946 m->flags ^= PG_CACHED | PG_FREE;
947 KASSERT((m->flags & (PG_CACHED | PG_FREE)) == PG_FREE,
948 ("vm_page_cache_free: page %p has inconsistent flags", m));
952 empty = object->cache == NULL;
953 mtx_unlock(&vm_page_queue_free_mtx);
954 if (object->type == OBJT_VNODE && empty)
955 vdrop(object->handle);
959 * Returns the cached page that is associated with the given
960 * object and offset. If, however, none exists, returns NULL.
962 * The free page queue must be locked.
964 static inline vm_page_t
965 vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
969 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
970 if ((m = object->cache) != NULL && m->pindex != pindex) {
971 m = vm_page_splay(pindex, m);
972 if ((object->cache = m)->pindex != pindex)
979 * Remove the given cached page from its containing object's
980 * collection of cached pages.
982 * The free page queue must be locked.
985 vm_page_cache_remove(vm_page_t m)
990 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
991 KASSERT((m->flags & PG_CACHED) != 0,
992 ("vm_page_cache_remove: page %p is not cached", m));
994 if (m != object->cache) {
995 root = vm_page_splay(m->pindex, object->cache);
997 ("vm_page_cache_remove: page %p is not cached in object %p",
1000 if (m->left == NULL)
1002 else if (m->right == NULL)
1005 root = vm_page_splay(m->pindex, m->left);
1006 root->right = m->right;
1008 object->cache = root;
1010 cnt.v_cache_count--;
1014 * Transfer all of the cached pages with offset greater than or
1015 * equal to 'offidxstart' from the original object's cache to the
1016 * new object's cache. However, any cached pages with offset
1017 * greater than or equal to the new object's size are kept in the
1018 * original object. Initially, the new object's cache must be
1019 * empty. Offset 'offidxstart' in the original object must
1020 * correspond to offset zero in the new object.
1022 * The new object must be locked.
1025 vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1026 vm_object_t new_object)
1028 vm_page_t m, m_next;
1031 * Insertion into an object's collection of cached pages
1032 * requires the object to be locked. In contrast, removal does
1035 VM_OBJECT_LOCK_ASSERT(new_object, MA_OWNED);
1036 KASSERT(new_object->cache == NULL,
1037 ("vm_page_cache_transfer: object %p has cached pages",
1039 mtx_lock(&vm_page_queue_free_mtx);
1040 if ((m = orig_object->cache) != NULL) {
1042 * Transfer all of the pages with offset greater than or
1043 * equal to 'offidxstart' from the original object's
1044 * cache to the new object's cache.
1046 m = vm_page_splay(offidxstart, m);
1047 if (m->pindex < offidxstart) {
1048 orig_object->cache = m;
1049 new_object->cache = m->right;
1052 orig_object->cache = m->left;
1053 new_object->cache = m;
1056 while ((m = new_object->cache) != NULL) {
1057 if ((m->pindex - offidxstart) >= new_object->size) {
1059 * Return all of the cached pages with
1060 * offset greater than or equal to the
1061 * new object's size to the original
1064 new_object->cache = m->left;
1065 m->left = orig_object->cache;
1066 orig_object->cache = m;
1069 m_next = vm_page_splay(m->pindex, m->right);
1070 /* Update the page's object and offset. */
1071 m->object = new_object;
1072 m->pindex -= offidxstart;
1077 new_object->cache = m_next;
1079 KASSERT(new_object->cache == NULL ||
1080 new_object->type == OBJT_SWAP,
1081 ("vm_page_cache_transfer: object %p's type is incompatible"
1082 " with cached pages", new_object));
1084 mtx_unlock(&vm_page_queue_free_mtx);
1090 * Allocate and return a memory cell associated
1091 * with this VM object/offset pair.
1093 * The caller must always specify an allocation class.
1095 * allocation classes:
1096 * VM_ALLOC_NORMAL normal process request
1097 * VM_ALLOC_SYSTEM system *really* needs a page
1098 * VM_ALLOC_INTERRUPT interrupt time request
1100 * optional allocation flags:
1101 * VM_ALLOC_ZERO prefer a zeroed page
1102 * VM_ALLOC_WIRED wire the allocated page
1103 * VM_ALLOC_NOOBJ page is not associated with a vm object
1104 * VM_ALLOC_NOBUSY do not set the page busy
1105 * VM_ALLOC_IFCACHED return page only if it is cached
1106 * VM_ALLOC_IFNOTCACHED return NULL, do not reactivate if the page
1109 * This routine may not sleep.
1112 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1114 struct vnode *vp = NULL;
1115 vm_object_t m_object;
1117 int flags, page_req;
1119 if ((req & VM_ALLOC_NOOBJ) == 0) {
1120 KASSERT(object != NULL,
1121 ("vm_page_alloc: NULL object."));
1122 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1125 page_req = req & VM_ALLOC_CLASS_MASK;
1128 * The pager is allowed to eat deeper into the free page list.
1130 if ((curproc == pageproc) && (page_req != VM_ALLOC_INTERRUPT))
1131 page_req = VM_ALLOC_SYSTEM;
1133 mtx_lock(&vm_page_queue_free_mtx);
1134 if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1135 (page_req == VM_ALLOC_SYSTEM &&
1136 cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1137 (page_req == VM_ALLOC_INTERRUPT &&
1138 cnt.v_free_count + cnt.v_cache_count > 0)) {
1140 * Allocate from the free queue if the number of free pages
1141 * exceeds the minimum for the request class.
1143 if (object != NULL &&
1144 (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1145 if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1146 mtx_unlock(&vm_page_queue_free_mtx);
1149 if (vm_phys_unfree_page(m))
1150 vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1151 #if VM_NRESERVLEVEL > 0
1152 else if (!vm_reserv_reactivate_page(m))
1156 panic("vm_page_alloc: cache page %p is missing"
1157 " from the free queue", m);
1158 } else if ((req & VM_ALLOC_IFCACHED) != 0) {
1159 mtx_unlock(&vm_page_queue_free_mtx);
1161 #if VM_NRESERVLEVEL > 0
1162 } else if (object == NULL || object->type == OBJT_DEVICE ||
1163 object->type == OBJT_SG ||
1164 (object->flags & OBJ_COLORED) == 0 ||
1165 (m = vm_reserv_alloc_page(object, pindex)) == NULL) {
1169 m = vm_phys_alloc_pages(object != NULL ?
1170 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1171 #if VM_NRESERVLEVEL > 0
1172 if (m == NULL && vm_reserv_reclaim_inactive()) {
1173 m = vm_phys_alloc_pages(object != NULL ?
1174 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1181 * Not allocatable, give up.
1183 mtx_unlock(&vm_page_queue_free_mtx);
1184 atomic_add_int(&vm_pageout_deficit, 1);
1185 pagedaemon_wakeup();
1190 * At this point we had better have found a good page.
1193 KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1194 KASSERT(m->queue == PQ_NONE,
1195 ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1196 KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1197 KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1198 KASSERT(m->busy == 0, ("vm_page_alloc: page %p is busy", m));
1199 KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1200 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1201 ("vm_page_alloc: page %p has unexpected memattr %d", m,
1202 pmap_page_get_memattr(m)));
1203 if ((m->flags & PG_CACHED) != 0) {
1204 KASSERT(m->valid != 0,
1205 ("vm_page_alloc: cached page %p is invalid", m));
1206 if (m->object == object && m->pindex == pindex)
1207 cnt.v_reactivated++;
1210 m_object = m->object;
1211 vm_page_cache_remove(m);
1212 if (m_object->type == OBJT_VNODE && m_object->cache == NULL)
1213 vp = m_object->handle;
1215 KASSERT(VM_PAGE_IS_FREE(m),
1216 ("vm_page_alloc: page %p is not free", m));
1217 KASSERT(m->valid == 0,
1218 ("vm_page_alloc: free page %p is valid", m));
1223 * Initialize structure. Only the PG_ZERO flag is inherited.
1226 if (m->flags & PG_ZERO) {
1227 vm_page_zero_count--;
1228 if (req & VM_ALLOC_ZERO)
1231 if (object == NULL || object->type == OBJT_PHYS)
1232 flags |= PG_UNMANAGED;
1234 if (req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ))
1237 m->oflags = VPO_BUSY;
1238 if (req & VM_ALLOC_WIRED) {
1239 atomic_add_int(&cnt.v_wire_count, 1);
1243 mtx_unlock(&vm_page_queue_free_mtx);
1245 if (object != NULL) {
1246 /* Ignore device objects; the pager sets "memattr" for them. */
1247 if (object->memattr != VM_MEMATTR_DEFAULT &&
1248 object->type != OBJT_DEVICE && object->type != OBJT_SG)
1249 pmap_page_set_memattr(m, object->memattr);
1250 vm_page_insert(m, object, pindex);
1255 * The following call to vdrop() must come after the above call
1256 * to vm_page_insert() in case both affect the same object and
1257 * vnode. Otherwise, the affected vnode's hold count could
1258 * temporarily become zero.
1264 * Don't wakeup too often - wakeup the pageout daemon when
1265 * we would be nearly out of memory.
1267 if (vm_paging_needed())
1268 pagedaemon_wakeup();
1274 * Initialize a page that has been freshly dequeued from a freelist.
1275 * The caller has to drop the vnode returned, if it is not NULL.
1277 * To be called with vm_page_queue_free_mtx held.
1280 vm_page_alloc_init(vm_page_t m)
1283 vm_object_t m_object;
1285 KASSERT(m->queue == PQ_NONE,
1286 ("vm_page_alloc_init: page %p has unexpected queue %d",
1288 KASSERT(m->wire_count == 0,
1289 ("vm_page_alloc_init: page %p is wired", m));
1290 KASSERT(m->hold_count == 0,
1291 ("vm_page_alloc_init: page %p is held", m));
1292 KASSERT(m->busy == 0,
1293 ("vm_page_alloc_init: page %p is busy", m));
1294 KASSERT(m->dirty == 0,
1295 ("vm_page_alloc_init: page %p is dirty", m));
1296 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1297 ("vm_page_alloc_init: page %p has unexpected memattr %d",
1298 m, pmap_page_get_memattr(m)));
1299 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1301 if ((m->flags & PG_CACHED) != 0) {
1303 m_object = m->object;
1304 vm_page_cache_remove(m);
1305 if (m_object->type == OBJT_VNODE &&
1306 m_object->cache == NULL)
1307 drop = m_object->handle;
1309 KASSERT(VM_PAGE_IS_FREE(m),
1310 ("vm_page_alloc_init: page %p is not free", m));
1311 KASSERT(m->valid == 0,
1312 ("vm_page_alloc_init: free page %p is valid", m));
1315 if (m->flags & PG_ZERO)
1316 vm_page_zero_count--;
1317 /* Don't clear the PG_ZERO flag; we'll need it later. */
1318 m->flags = PG_UNMANAGED | (m->flags & PG_ZERO);
1320 /* Unmanaged pages don't use "act_count". */
1325 * vm_page_alloc_freelist:
1327 * Allocate a page from the specified freelist.
1328 * Only the ALLOC_CLASS values in req are honored, other request flags
1332 vm_page_alloc_freelist(int flind, int req)
1339 page_req = req & VM_ALLOC_CLASS_MASK;
1340 mtx_lock(&vm_page_queue_free_mtx);
1342 * Do not allocate reserved pages unless the req has asked for it.
1344 if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1345 (page_req == VM_ALLOC_SYSTEM &&
1346 cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1347 (page_req == VM_ALLOC_INTERRUPT &&
1348 cnt.v_free_count + cnt.v_cache_count > 0)) {
1349 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
1352 mtx_unlock(&vm_page_queue_free_mtx);
1355 drop = vm_page_alloc_init(m);
1356 mtx_unlock(&vm_page_queue_free_mtx);
1363 * vm_wait: (also see VM_WAIT macro)
1365 * Block until free pages are available for allocation
1366 * - Called in various places before memory allocations.
1372 mtx_lock(&vm_page_queue_free_mtx);
1373 if (curproc == pageproc) {
1374 vm_pageout_pages_needed = 1;
1375 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
1376 PDROP | PSWP, "VMWait", 0);
1378 if (!vm_pages_needed) {
1379 vm_pages_needed = 1;
1380 wakeup(&vm_pages_needed);
1382 msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
1388 * vm_waitpfault: (also see VM_WAITPFAULT macro)
1390 * Block until free pages are available for allocation
1391 * - Called only in vm_fault so that processes page faulting
1392 * can be easily tracked.
1393 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
1394 * processes will be able to grab memory first. Do not change
1395 * this balance without careful testing first.
1401 mtx_lock(&vm_page_queue_free_mtx);
1402 if (!vm_pages_needed) {
1403 vm_pages_needed = 1;
1404 wakeup(&vm_pages_needed);
1406 msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
1413 * If the given page is contained within a page queue, move it to the tail
1416 * The page queues must be locked.
1419 vm_page_requeue(vm_page_t m)
1421 int queue = VM_PAGE_GETQUEUE(m);
1422 struct vpgqueues *vpq;
1424 if (queue != PQ_NONE) {
1425 vpq = &vm_page_queues[queue];
1426 TAILQ_REMOVE(&vpq->pl, m, pageq);
1427 TAILQ_INSERT_TAIL(&vpq->pl, m, pageq);
1434 * Remove a page from its queue.
1436 * The queue containing the given page must be locked.
1437 * This routine may not block.
1440 vm_pageq_remove(vm_page_t m)
1442 int queue = VM_PAGE_GETQUEUE(m);
1443 struct vpgqueues *pq;
1445 if (queue != PQ_NONE) {
1446 VM_PAGE_SETQUEUE2(m, PQ_NONE);
1447 pq = &vm_page_queues[queue];
1448 TAILQ_REMOVE(&pq->pl, m, pageq);
1456 * Add the given page to the specified queue.
1458 * The page queues must be locked.
1461 vm_page_enqueue(int queue, vm_page_t m)
1463 struct vpgqueues *vpq;
1465 vpq = &vm_page_queues[queue];
1466 VM_PAGE_SETQUEUE2(m, queue);
1467 TAILQ_INSERT_TAIL(&vpq->pl, m, pageq);
1474 * Put the specified page on the active list (if appropriate).
1475 * Ensure that act_count is at least ACT_INIT but do not otherwise
1478 * The page queues must be locked.
1479 * This routine may not block.
1482 vm_page_activate(vm_page_t m)
1485 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1486 if (VM_PAGE_GETKNOWNQUEUE2(m) != PQ_ACTIVE) {
1488 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1489 if (m->act_count < ACT_INIT)
1490 m->act_count = ACT_INIT;
1491 vm_page_enqueue(PQ_ACTIVE, m);
1494 if (m->act_count < ACT_INIT)
1495 m->act_count = ACT_INIT;
1500 * vm_page_free_wakeup:
1502 * Helper routine for vm_page_free_toq() and vm_page_cache(). This
1503 * routine is called when a page has been added to the cache or free
1506 * The page queues must be locked.
1507 * This routine may not block.
1510 vm_page_free_wakeup(void)
1513 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1515 * if pageout daemon needs pages, then tell it that there are
1518 if (vm_pageout_pages_needed &&
1519 cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
1520 wakeup(&vm_pageout_pages_needed);
1521 vm_pageout_pages_needed = 0;
1524 * wakeup processes that are waiting on memory if we hit a
1525 * high water mark. And wakeup scheduler process if we have
1526 * lots of memory. this process will swapin processes.
1528 if (vm_pages_needed && !vm_page_count_min()) {
1529 vm_pages_needed = 0;
1530 wakeup(&cnt.v_free_count);
1537 * Returns the given page to the free list,
1538 * disassociating it with any VM object.
1540 * Object and page must be locked prior to entry.
1541 * This routine may not block.
1545 vm_page_free_toq(vm_page_t m)
1548 if (VM_PAGE_GETQUEUE(m) != PQ_NONE)
1549 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1550 KASSERT(!pmap_page_is_mapped(m),
1551 ("vm_page_free_toq: freeing mapped page %p", m));
1552 PCPU_INC(cnt.v_tfree);
1554 if (m->busy || VM_PAGE_IS_FREE(m)) {
1556 "vm_page_free: pindex(%lu), busy(%d), VPO_BUSY(%d), hold(%d)\n",
1557 (u_long)m->pindex, m->busy, (m->oflags & VPO_BUSY) ? 1 : 0,
1559 if (VM_PAGE_IS_FREE(m))
1560 panic("vm_page_free: freeing free page");
1562 panic("vm_page_free: freeing busy page");
1566 * unqueue, then remove page. Note that we cannot destroy
1567 * the page here because we do not want to call the pager's
1568 * callback routine until after we've put the page on the
1569 * appropriate free queue.
1575 * If fictitious remove object association and
1576 * return, otherwise delay object association removal.
1578 if ((m->flags & PG_FICTITIOUS) != 0) {
1585 if (m->wire_count != 0) {
1586 if (m->wire_count > 1) {
1587 panic("vm_page_free: invalid wire count (%d), pindex: 0x%lx",
1588 m->wire_count, (long)m->pindex);
1590 panic("vm_page_free: freeing wired page");
1592 if (m->hold_count != 0) {
1593 m->flags &= ~PG_ZERO;
1594 vm_page_enqueue(PQ_HOLD, m);
1597 * Restore the default memory attribute to the page.
1599 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
1600 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
1603 * Insert the page into the physical memory allocator's
1604 * cache/free page queues.
1606 mtx_lock(&vm_page_queue_free_mtx);
1607 m->flags |= PG_FREE;
1609 #if VM_NRESERVLEVEL > 0
1610 if (!vm_reserv_free_page(m))
1614 vm_phys_free_pages(m, 0);
1615 if ((m->flags & PG_ZERO) != 0)
1616 ++vm_page_zero_count;
1618 vm_page_zero_idle_wakeup();
1619 vm_page_free_wakeup();
1620 mtx_unlock(&vm_page_queue_free_mtx);
1627 * Mark this page as wired down by yet
1628 * another map, removing it from paging queues
1631 * The page queues must be locked.
1632 * This routine may not block.
1635 vm_page_wire(vm_page_t m)
1639 * Only bump the wire statistics if the page is not already wired,
1640 * and only unqueue the page if it is on some queue (if it is unmanaged
1641 * it is already off the queues).
1643 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1644 if (m->flags & PG_FICTITIOUS)
1646 if (m->wire_count == 0) {
1647 if ((m->flags & PG_UNMANAGED) == 0)
1649 atomic_add_int(&cnt.v_wire_count, 1);
1652 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
1658 * Release one wiring of this page, potentially
1659 * enabling it to be paged again.
1661 * Many pages placed on the inactive queue should actually go
1662 * into the cache, but it is difficult to figure out which. What
1663 * we do instead, if the inactive target is well met, is to put
1664 * clean pages at the head of the inactive queue instead of the tail.
1665 * This will cause them to be moved to the cache more quickly and
1666 * if not actively re-referenced, freed more quickly. If we just
1667 * stick these pages at the end of the inactive queue, heavy filesystem
1668 * meta-data accesses can cause an unnecessary paging load on memory bound
1669 * processes. This optimization causes one-time-use metadata to be
1670 * reused more quickly.
1672 * BUT, if we are in a low-memory situation we have no choice but to
1673 * put clean pages on the cache queue.
1675 * A number of routines use vm_page_unwire() to guarantee that the page
1676 * will go into either the inactive or active queues, and will NEVER
1677 * be placed in the cache - for example, just after dirtying a page.
1678 * dirty pages in the cache are not allowed.
1680 * The page queues must be locked.
1681 * This routine may not block.
1684 vm_page_unwire(vm_page_t m, int activate)
1687 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1688 if (m->flags & PG_FICTITIOUS)
1690 if (m->wire_count > 0) {
1692 if (m->wire_count == 0) {
1693 atomic_subtract_int(&cnt.v_wire_count, 1);
1694 if (m->flags & PG_UNMANAGED) {
1696 } else if (activate)
1697 vm_page_enqueue(PQ_ACTIVE, m);
1699 vm_page_flag_clear(m, PG_WINATCFLS);
1700 vm_page_enqueue(PQ_INACTIVE, m);
1704 panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
1710 * Move the specified page to the inactive queue. If the page has
1711 * any associated swap, the swap is deallocated.
1713 * Normally athead is 0 resulting in LRU operation. athead is set
1714 * to 1 if we want this page to be 'as if it were placed in the cache',
1715 * except without unmapping it from the process address space.
1717 * This routine may not block.
1720 _vm_page_deactivate(vm_page_t m, int athead)
1723 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1726 * Ignore if already inactive.
1728 if (VM_PAGE_INQUEUE2(m, PQ_INACTIVE))
1730 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1731 vm_page_flag_clear(m, PG_WINATCFLS);
1734 TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1736 TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1737 VM_PAGE_SETQUEUE2(m, PQ_INACTIVE);
1738 cnt.v_inactive_count++;
1743 vm_page_deactivate(vm_page_t m)
1745 _vm_page_deactivate(m, 0);
1749 * vm_page_try_to_cache:
1751 * Returns 0 on failure, 1 on success
1754 vm_page_try_to_cache(vm_page_t m)
1757 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1758 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1759 if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1760 (m->oflags & VPO_BUSY) || (m->flags & PG_UNMANAGED)) {
1771 * vm_page_try_to_free()
1773 * Attempt to free the page. If we cannot free it, we do nothing.
1774 * 1 is returned on success, 0 on failure.
1777 vm_page_try_to_free(vm_page_t m)
1780 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1781 if (m->object != NULL)
1782 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1783 if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1784 (m->oflags & VPO_BUSY) || (m->flags & PG_UNMANAGED)) {
1797 * Put the specified page onto the page cache queue (if appropriate).
1799 * This routine may not block.
1802 vm_page_cache(vm_page_t m)
1807 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1809 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1810 if ((m->flags & PG_UNMANAGED) || (m->oflags & VPO_BUSY) || m->busy ||
1811 m->hold_count || m->wire_count) {
1812 panic("vm_page_cache: attempting to cache busy page");
1816 panic("vm_page_cache: page %p is dirty", m);
1817 if (m->valid == 0 || object->type == OBJT_DEFAULT ||
1818 (object->type == OBJT_SWAP &&
1819 !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
1821 * Hypothesis: A cache-elgible page belonging to a
1822 * default object or swap object but without a backing
1823 * store must be zero filled.
1828 KASSERT((m->flags & PG_CACHED) == 0,
1829 ("vm_page_cache: page %p is already cached", m));
1833 * Remove the page from the paging queues.
1838 * Remove the page from the object's collection of resident
1841 if (m != object->root)
1842 vm_page_splay(m->pindex, object->root);
1843 if (m->left == NULL)
1846 root = vm_page_splay(m->pindex, m->left);
1847 root->right = m->right;
1849 object->root = root;
1850 TAILQ_REMOVE(&object->memq, m, listq);
1851 object->resident_page_count--;
1854 * Restore the default memory attribute to the page.
1856 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
1857 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
1860 * Insert the page into the object's collection of cached pages
1861 * and the physical memory allocator's cache/free page queues.
1863 vm_page_flag_clear(m, PG_ZERO);
1864 mtx_lock(&vm_page_queue_free_mtx);
1865 m->flags |= PG_CACHED;
1866 cnt.v_cache_count++;
1867 root = object->cache;
1872 root = vm_page_splay(m->pindex, root);
1873 if (m->pindex < root->pindex) {
1874 m->left = root->left;
1877 } else if (__predict_false(m->pindex == root->pindex))
1878 panic("vm_page_cache: offset already cached");
1880 m->right = root->right;
1886 #if VM_NRESERVLEVEL > 0
1887 if (!vm_reserv_free_page(m)) {
1891 vm_phys_set_pool(VM_FREEPOOL_CACHE, m, 0);
1892 vm_phys_free_pages(m, 0);
1894 vm_page_free_wakeup();
1895 mtx_unlock(&vm_page_queue_free_mtx);
1898 * Increment the vnode's hold count if this is the object's only
1899 * cached page. Decrement the vnode's hold count if this was
1900 * the object's only resident page.
1902 if (object->type == OBJT_VNODE) {
1903 if (root == NULL && object->resident_page_count != 0)
1904 vhold(object->handle);
1905 else if (root != NULL && object->resident_page_count == 0)
1906 vdrop(object->handle);
1913 * Cache, deactivate, or do nothing as appropriate. This routine
1914 * is typically used by madvise() MADV_DONTNEED.
1916 * Generally speaking we want to move the page into the cache so
1917 * it gets reused quickly. However, this can result in a silly syndrome
1918 * due to the page recycling too quickly. Small objects will not be
1919 * fully cached. On the otherhand, if we move the page to the inactive
1920 * queue we wind up with a problem whereby very large objects
1921 * unnecessarily blow away our inactive and cache queues.
1923 * The solution is to move the pages based on a fixed weighting. We
1924 * either leave them alone, deactivate them, or move them to the cache,
1925 * where moving them to the cache has the highest weighting.
1926 * By forcing some pages into other queues we eventually force the
1927 * system to balance the queues, potentially recovering other unrelated
1928 * space from active. The idea is to not force this to happen too
1932 vm_page_dontneed(vm_page_t m)
1934 static int dnweight;
1938 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1942 * occassionally leave the page alone
1944 if ((dnw & 0x01F0) == 0 ||
1945 VM_PAGE_INQUEUE2(m, PQ_INACTIVE)) {
1946 if (m->act_count >= ACT_INIT)
1952 * Clear any references to the page. Otherwise, the page daemon will
1953 * immediately reactivate the page.
1955 vm_page_flag_clear(m, PG_REFERENCED);
1956 pmap_clear_reference(m);
1958 if (m->dirty == 0 && pmap_is_modified(m))
1961 if (m->dirty || (dnw & 0x0070) == 0) {
1963 * Deactivate the page 3 times out of 32.
1968 * Cache the page 28 times out of every 32. Note that
1969 * the page is deactivated instead of cached, but placed
1970 * at the head of the queue instead of the tail.
1974 _vm_page_deactivate(m, head);
1978 * Grab a page, waiting until we are waken up due to the page
1979 * changing state. We keep on waiting, if the page continues
1980 * to be in the object. If the page doesn't exist, first allocate it
1981 * and then conditionally zero it.
1983 * This routine may block.
1986 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
1990 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1992 if ((m = vm_page_lookup(object, pindex)) != NULL) {
1993 if (vm_page_sleep_if_busy(m, TRUE, "pgrbwt")) {
1994 if ((allocflags & VM_ALLOC_RETRY) == 0)
1998 if ((allocflags & VM_ALLOC_WIRED) != 0) {
1999 vm_page_lock_queues();
2001 vm_page_unlock_queues();
2003 if ((allocflags & VM_ALLOC_NOBUSY) == 0)
2008 m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_RETRY);
2010 VM_OBJECT_UNLOCK(object);
2012 VM_OBJECT_LOCK(object);
2013 if ((allocflags & VM_ALLOC_RETRY) == 0)
2016 } else if (m->valid != 0)
2018 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
2024 * Mapping function for valid bits or for dirty bits in
2025 * a page. May not block.
2027 * Inputs are required to range within a page.
2030 vm_page_bits(int base, int size)
2036 base + size <= PAGE_SIZE,
2037 ("vm_page_bits: illegal base/size %d/%d", base, size)
2040 if (size == 0) /* handle degenerate case */
2043 first_bit = base >> DEV_BSHIFT;
2044 last_bit = (base + size - 1) >> DEV_BSHIFT;
2046 return ((2 << last_bit) - (1 << first_bit));
2050 * vm_page_set_valid:
2052 * Sets portions of a page valid. The arguments are expected
2053 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2054 * of any partial chunks touched by the range. The invalid portion of
2055 * such chunks will be zeroed.
2057 * (base + size) must be less then or equal to PAGE_SIZE.
2060 vm_page_set_valid(vm_page_t m, int base, int size)
2064 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2065 if (size == 0) /* handle degenerate case */
2069 * If the base is not DEV_BSIZE aligned and the valid
2070 * bit is clear, we have to zero out a portion of the
2073 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2074 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2075 pmap_zero_page_area(m, frag, base - frag);
2078 * If the ending offset is not DEV_BSIZE aligned and the
2079 * valid bit is clear, we have to zero out a portion of
2082 endoff = base + size;
2083 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2084 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2085 pmap_zero_page_area(m, endoff,
2086 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2089 * Assert that no previously invalid block that is now being validated
2092 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
2093 ("vm_page_set_valid: page %p is dirty", m));
2096 * Set valid bits inclusive of any overlap.
2098 m->valid |= vm_page_bits(base, size);
2102 * vm_page_set_validclean:
2104 * Sets portions of a page valid and clean. The arguments are expected
2105 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2106 * of any partial chunks touched by the range. The invalid portion of
2107 * such chunks will be zero'd.
2109 * This routine may not block.
2111 * (base + size) must be less then or equal to PAGE_SIZE.
2114 vm_page_set_validclean(vm_page_t m, int base, int size)
2120 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2121 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2122 if (size == 0) /* handle degenerate case */
2126 * If the base is not DEV_BSIZE aligned and the valid
2127 * bit is clear, we have to zero out a portion of the
2130 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2131 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2132 pmap_zero_page_area(m, frag, base - frag);
2135 * If the ending offset is not DEV_BSIZE aligned and the
2136 * valid bit is clear, we have to zero out a portion of
2139 endoff = base + size;
2140 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2141 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2142 pmap_zero_page_area(m, endoff,
2143 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2146 * Set valid, clear dirty bits. If validating the entire
2147 * page we can safely clear the pmap modify bit. We also
2148 * use this opportunity to clear the VPO_NOSYNC flag. If a process
2149 * takes a write fault on a MAP_NOSYNC memory area the flag will
2152 * We set valid bits inclusive of any overlap, but we can only
2153 * clear dirty bits for DEV_BSIZE chunks that are fully within
2156 pagebits = vm_page_bits(base, size);
2157 m->valid |= pagebits;
2159 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
2160 frag = DEV_BSIZE - frag;
2166 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
2168 m->dirty &= ~pagebits;
2169 if (base == 0 && size == PAGE_SIZE) {
2170 pmap_clear_modify(m);
2171 m->oflags &= ~VPO_NOSYNC;
2176 vm_page_clear_dirty(vm_page_t m, int base, int size)
2179 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2180 m->dirty &= ~vm_page_bits(base, size);
2184 * vm_page_set_invalid:
2186 * Invalidates DEV_BSIZE'd chunks within a page. Both the
2187 * valid and dirty bits for the effected areas are cleared.
2192 vm_page_set_invalid(vm_page_t m, int base, int size)
2196 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2197 bits = vm_page_bits(base, size);
2198 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2199 if (m->valid == VM_PAGE_BITS_ALL && bits != 0)
2206 * vm_page_zero_invalid()
2208 * The kernel assumes that the invalid portions of a page contain
2209 * garbage, but such pages can be mapped into memory by user code.
2210 * When this occurs, we must zero out the non-valid portions of the
2211 * page so user code sees what it expects.
2213 * Pages are most often semi-valid when the end of a file is mapped
2214 * into memory and the file's size is not page aligned.
2217 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
2222 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2224 * Scan the valid bits looking for invalid sections that
2225 * must be zerod. Invalid sub-DEV_BSIZE'd areas ( where the
2226 * valid bit may be set ) have already been zerod by
2227 * vm_page_set_validclean().
2229 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
2230 if (i == (PAGE_SIZE / DEV_BSIZE) ||
2231 (m->valid & (1 << i))
2234 pmap_zero_page_area(m,
2235 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
2242 * setvalid is TRUE when we can safely set the zero'd areas
2243 * as being valid. We can do this if there are no cache consistancy
2244 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
2247 m->valid = VM_PAGE_BITS_ALL;
2253 * Is (partial) page valid? Note that the case where size == 0
2254 * will return FALSE in the degenerate case where the page is
2255 * entirely invalid, and TRUE otherwise.
2260 vm_page_is_valid(vm_page_t m, int base, int size)
2262 int bits = vm_page_bits(base, size);
2264 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2265 if (m->valid && ((m->valid & bits) == bits))
2272 * update dirty bits from pmap/mmu. May not block.
2275 vm_page_test_dirty(vm_page_t m)
2277 if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
2282 int so_zerocp_fullpage = 0;
2285 * Replace the given page with a copy. The copied page assumes
2286 * the portion of the given page's "wire_count" that is not the
2287 * responsibility of this copy-on-write mechanism.
2289 * The object containing the given page must have a non-zero
2290 * paging-in-progress count and be locked.
2293 vm_page_cowfault(vm_page_t m)
2300 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2301 KASSERT(object->paging_in_progress != 0,
2302 ("vm_page_cowfault: object %p's paging-in-progress count is zero.",
2309 mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY);
2311 vm_page_insert(m, object, pindex);
2312 vm_page_unlock_queues();
2313 VM_OBJECT_UNLOCK(object);
2315 VM_OBJECT_LOCK(object);
2316 if (m == vm_page_lookup(object, pindex)) {
2317 vm_page_lock_queues();
2321 * Page disappeared during the wait.
2323 vm_page_lock_queues();
2330 * check to see if we raced with an xmit complete when
2331 * waiting to allocate a page. If so, put things back
2335 vm_page_insert(m, object, pindex);
2336 } else { /* clear COW & copy page */
2337 if (!so_zerocp_fullpage)
2338 pmap_copy_page(m, mnew);
2339 mnew->valid = VM_PAGE_BITS_ALL;
2340 vm_page_dirty(mnew);
2341 mnew->wire_count = m->wire_count - m->cow;
2342 m->wire_count = m->cow;
2347 vm_page_cowclear(vm_page_t m)
2350 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2354 * let vm_fault add back write permission lazily
2358 * sf_buf_free() will free the page, so we needn't do it here
2363 vm_page_cowsetup(vm_page_t m)
2366 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2367 if (m->cow == USHRT_MAX - 1)
2370 pmap_remove_write(m);
2374 #include "opt_ddb.h"
2376 #include <sys/kernel.h>
2378 #include <ddb/ddb.h>
2380 DB_SHOW_COMMAND(page, vm_page_print_page_info)
2382 db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
2383 db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
2384 db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
2385 db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
2386 db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
2387 db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
2388 db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
2389 db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
2390 db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
2391 db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
2394 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
2397 db_printf("PQ_FREE:");
2398 db_printf(" %d", cnt.v_free_count);
2401 db_printf("PQ_CACHE:");
2402 db_printf(" %d", cnt.v_cache_count);
2405 db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
2406 *vm_page_queues[PQ_ACTIVE].cnt,
2407 *vm_page_queues[PQ_INACTIVE].cnt);