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 page queue lock is required when adding or removing a page from a
67 * page queue regardless of other locks or the busy state of a page.
69 * * In general, no thread besides the page daemon can acquire or
70 * hold more than one page queue lock at a time.
72 * * The page daemon can acquire and hold any pair of page queue
75 * - The object lock is required when inserting or removing
76 * pages from an object (vm_page_insert() or vm_page_remove()).
81 * Resident memory management module.
84 #include <sys/cdefs.h>
85 __FBSDID("$FreeBSD$");
89 #include <sys/param.h>
90 #include <sys/systm.h>
92 #include <sys/kernel.h>
93 #include <sys/limits.h>
94 #include <sys/malloc.h>
96 #include <sys/msgbuf.h>
97 #include <sys/mutex.h>
99 #include <sys/rwlock.h>
100 #include <sys/sysctl.h>
101 #include <sys/vmmeter.h>
102 #include <sys/vnode.h>
106 #include <vm/vm_param.h>
107 #include <vm/vm_kern.h>
108 #include <vm/vm_object.h>
109 #include <vm/vm_page.h>
110 #include <vm/vm_pageout.h>
111 #include <vm/vm_pager.h>
112 #include <vm/vm_phys.h>
113 #include <vm/vm_radix.h>
114 #include <vm/vm_reserv.h>
115 #include <vm/vm_extern.h>
117 #include <vm/uma_int.h>
119 #include <machine/md_var.h>
122 * Associated with page of user-allocatable memory is a
126 struct vm_domain vm_dom[MAXMEMDOM];
127 struct mtx_padalign vm_page_queue_free_mtx;
129 struct mtx_padalign pa_lock[PA_LOCK_COUNT];
131 vm_page_t vm_page_array;
132 long vm_page_array_size;
134 int vm_page_zero_count;
136 static int boot_pages = UMA_BOOT_PAGES;
137 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN, &boot_pages, 0,
138 "number of pages allocated for bootstrapping the VM system");
140 static int pa_tryrelock_restart;
141 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
142 &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
144 static uma_zone_t fakepg_zone;
146 static struct vnode *vm_page_alloc_init(vm_page_t m);
147 static void vm_page_cache_turn_free(vm_page_t m);
148 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
149 static void vm_page_enqueue(uint8_t queue, vm_page_t m);
150 static void vm_page_init_fakepg(void *dummy);
151 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
152 vm_pindex_t pindex, vm_page_t mpred);
153 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
156 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init_fakepg, NULL);
159 vm_page_init_fakepg(void *dummy)
162 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
163 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
166 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
167 #if PAGE_SIZE == 32768
169 CTASSERT(sizeof(u_long) >= 8);
174 * Try to acquire a physical address lock while a pmap is locked. If we
175 * fail to trylock we unlock and lock the pmap directly and cache the
176 * locked pa in *locked. The caller should then restart their loop in case
177 * the virtual to physical mapping has changed.
180 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
187 PA_LOCK_ASSERT(lockpa, MA_OWNED);
188 if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
195 atomic_add_int(&pa_tryrelock_restart, 1);
204 * Sets the page size, perhaps based upon the memory
205 * size. Must be called before any use of page-size
206 * dependent functions.
209 vm_set_page_size(void)
211 if (vm_cnt.v_page_size == 0)
212 vm_cnt.v_page_size = PAGE_SIZE;
213 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
214 panic("vm_set_page_size: page size not a power of two");
218 * vm_page_blacklist_lookup:
220 * See if a physical address in this page has been listed
221 * in the blacklist tunable. Entries in the tunable are
222 * separated by spaces or commas. If an invalid integer is
223 * encountered then the rest of the string is skipped.
226 vm_page_blacklist_lookup(char *list, vm_paddr_t pa)
231 for (pos = list; *pos != '\0'; pos = cp) {
232 bad = strtoq(pos, &cp, 0);
234 if (*cp == ' ' || *cp == ',') {
241 if (pa == trunc_page(bad))
248 vm_page_domain_init(struct vm_domain *vmd)
250 struct vm_pagequeue *pq;
253 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
254 "vm inactive pagequeue";
255 *__DECONST(int **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_vcnt) =
256 &vm_cnt.v_inactive_count;
257 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
258 "vm active pagequeue";
259 *__DECONST(int **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_vcnt) =
260 &vm_cnt.v_active_count;
261 vmd->vmd_page_count = 0;
262 vmd->vmd_free_count = 0;
264 vmd->vmd_oom = FALSE;
266 for (i = 0; i < PQ_COUNT; i++) {
267 pq = &vmd->vmd_pagequeues[i];
268 TAILQ_INIT(&pq->pq_pl);
269 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
270 MTX_DEF | MTX_DUPOK);
277 * Initializes the resident memory module.
279 * Allocates memory for the page cells, and
280 * for the object/offset-to-page hash table headers.
281 * Each page cell is initialized and placed on the free list.
284 vm_page_startup(vm_offset_t vaddr)
287 vm_paddr_t page_range;
294 /* the biggest memory array is the second group of pages */
296 vm_paddr_t biggestsize;
297 vm_paddr_t low_water, high_water;
302 vaddr = round_page(vaddr);
304 for (i = 0; phys_avail[i + 1]; i += 2) {
305 phys_avail[i] = round_page(phys_avail[i]);
306 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
309 low_water = phys_avail[0];
310 high_water = phys_avail[1];
312 for (i = 0; phys_avail[i + 1]; i += 2) {
313 vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
315 if (size > biggestsize) {
319 if (phys_avail[i] < low_water)
320 low_water = phys_avail[i];
321 if (phys_avail[i + 1] > high_water)
322 high_water = phys_avail[i + 1];
329 end = phys_avail[biggestone+1];
332 * Initialize the page and queue locks.
334 mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
335 for (i = 0; i < PA_LOCK_COUNT; i++)
336 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
337 for (i = 0; i < vm_ndomains; i++)
338 vm_page_domain_init(&vm_dom[i]);
341 * Allocate memory for use when boot strapping the kernel memory
344 new_end = end - (boot_pages * UMA_SLAB_SIZE);
345 new_end = trunc_page(new_end);
346 mapped = pmap_map(&vaddr, new_end, end,
347 VM_PROT_READ | VM_PROT_WRITE);
348 bzero((void *)mapped, end - new_end);
349 uma_startup((void *)mapped, boot_pages);
351 #if defined(__amd64__) || defined(__i386__) || defined(__arm__) || \
354 * Allocate a bitmap to indicate that a random physical page
355 * needs to be included in a minidump.
357 * The amd64 port needs this to indicate which direct map pages
358 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
360 * However, i386 still needs this workspace internally within the
361 * minidump code. In theory, they are not needed on i386, but are
362 * included should the sf_buf code decide to use them.
365 for (i = 0; dump_avail[i + 1] != 0; i += 2)
366 if (dump_avail[i + 1] > last_pa)
367 last_pa = dump_avail[i + 1];
368 page_range = last_pa / PAGE_SIZE;
369 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
370 new_end -= vm_page_dump_size;
371 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
372 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
373 bzero((void *)vm_page_dump, vm_page_dump_size);
377 * Request that the physical pages underlying the message buffer be
378 * included in a crash dump. Since the message buffer is accessed
379 * through the direct map, they are not automatically included.
381 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
382 last_pa = pa + round_page(msgbufsize);
383 while (pa < last_pa) {
389 * Compute the number of pages of memory that will be available for
390 * use (taking into account the overhead of a page structure per
393 first_page = low_water / PAGE_SIZE;
394 #ifdef VM_PHYSSEG_SPARSE
396 for (i = 0; phys_avail[i + 1] != 0; i += 2)
397 page_range += atop(phys_avail[i + 1] - phys_avail[i]);
398 #elif defined(VM_PHYSSEG_DENSE)
399 page_range = high_water / PAGE_SIZE - first_page;
401 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
406 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
411 * Initialize the mem entry structures now, and put them in the free
414 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
415 mapped = pmap_map(&vaddr, new_end, end,
416 VM_PROT_READ | VM_PROT_WRITE);
417 vm_page_array = (vm_page_t) mapped;
418 #if VM_NRESERVLEVEL > 0
420 * Allocate memory for the reservation management system's data
423 new_end = vm_reserv_startup(&vaddr, new_end, high_water);
425 #if defined(__amd64__) || defined(__mips__)
427 * pmap_map on amd64 and mips can come out of the direct-map, not kvm
428 * like i386, so the pages must be tracked for a crashdump to include
429 * this data. This includes the vm_page_array and the early UMA
432 for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
435 phys_avail[biggestone + 1] = new_end;
438 * Clear all of the page structures
440 bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
441 for (i = 0; i < page_range; i++)
442 vm_page_array[i].order = VM_NFREEORDER;
443 vm_page_array_size = page_range;
446 * Initialize the physical memory allocator.
451 * Add every available physical page that is not blacklisted to
454 vm_cnt.v_page_count = 0;
455 vm_cnt.v_free_count = 0;
456 list = getenv("vm.blacklist");
457 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
459 last_pa = phys_avail[i + 1];
460 while (pa < last_pa) {
462 vm_page_blacklist_lookup(list, pa))
463 printf("Skipping page with pa 0x%jx\n",
466 vm_phys_add_page(pa);
471 #if VM_NRESERVLEVEL > 0
473 * Initialize the reservation management system.
481 vm_page_reference(vm_page_t m)
484 vm_page_aflag_set(m, PGA_REFERENCED);
488 * vm_page_busy_downgrade:
490 * Downgrade an exclusive busy page into a single shared busy page.
493 vm_page_busy_downgrade(vm_page_t m)
497 vm_page_assert_xbusied(m);
501 x &= VPB_BIT_WAITERS;
502 if (atomic_cmpset_rel_int(&m->busy_lock,
503 VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1) | x))
511 * Return a positive value if the page is shared busied, 0 otherwise.
514 vm_page_sbusied(vm_page_t m)
519 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
525 * Shared unbusy a page.
528 vm_page_sunbusy(vm_page_t m)
532 vm_page_assert_sbusied(m);
536 if (VPB_SHARERS(x) > 1) {
537 if (atomic_cmpset_int(&m->busy_lock, x,
542 if ((x & VPB_BIT_WAITERS) == 0) {
543 KASSERT(x == VPB_SHARERS_WORD(1),
544 ("vm_page_sunbusy: invalid lock state"));
545 if (atomic_cmpset_int(&m->busy_lock,
546 VPB_SHARERS_WORD(1), VPB_UNBUSIED))
550 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
551 ("vm_page_sunbusy: invalid lock state for waiters"));
554 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
565 * vm_page_busy_sleep:
567 * Sleep and release the page lock, using the page pointer as wchan.
568 * This is used to implement the hard-path of busying mechanism.
570 * The given page must be locked.
573 vm_page_busy_sleep(vm_page_t m, const char *wmesg)
577 vm_page_lock_assert(m, MA_OWNED);
580 if (x == VPB_UNBUSIED) {
584 if ((x & VPB_BIT_WAITERS) == 0 &&
585 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS)) {
589 msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
595 * Try to shared busy a page.
596 * If the operation succeeds 1 is returned otherwise 0.
597 * The operation never sleeps.
600 vm_page_trysbusy(vm_page_t m)
606 if ((x & VPB_BIT_SHARED) == 0)
608 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
614 * vm_page_xunbusy_hard:
616 * Called after the first try the exclusive unbusy of a page failed.
617 * It is assumed that the waiters bit is on.
620 vm_page_xunbusy_hard(vm_page_t m)
623 vm_page_assert_xbusied(m);
626 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
634 * Wakeup anyone waiting for the page.
635 * The ownership bits do not change.
637 * The given page must be locked.
640 vm_page_flash(vm_page_t m)
644 vm_page_lock_assert(m, MA_OWNED);
648 if ((x & VPB_BIT_WAITERS) == 0)
650 if (atomic_cmpset_int(&m->busy_lock, x,
651 x & (~VPB_BIT_WAITERS)))
658 * Keep page from being freed by the page daemon
659 * much of the same effect as wiring, except much lower
660 * overhead and should be used only for *very* temporary
661 * holding ("wiring").
664 vm_page_hold(vm_page_t mem)
667 vm_page_lock_assert(mem, MA_OWNED);
672 vm_page_unhold(vm_page_t mem)
675 vm_page_lock_assert(mem, MA_OWNED);
676 KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
678 if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
679 vm_page_free_toq(mem);
683 * vm_page_unhold_pages:
685 * Unhold each of the pages that is referenced by the given array.
688 vm_page_unhold_pages(vm_page_t *ma, int count)
690 struct mtx *mtx, *new_mtx;
693 for (; count != 0; count--) {
695 * Avoid releasing and reacquiring the same page lock.
697 new_mtx = vm_page_lockptr(*ma);
698 if (mtx != new_mtx) {
712 PHYS_TO_VM_PAGE(vm_paddr_t pa)
716 #ifdef VM_PHYSSEG_SPARSE
717 m = vm_phys_paddr_to_vm_page(pa);
719 m = vm_phys_fictitious_to_vm_page(pa);
721 #elif defined(VM_PHYSSEG_DENSE)
725 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
726 m = &vm_page_array[pi - first_page];
729 return (vm_phys_fictitious_to_vm_page(pa));
731 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
738 * Create a fictitious page with the specified physical address and
739 * memory attribute. The memory attribute is the only the machine-
740 * dependent aspect of a fictitious page that must be initialized.
743 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
747 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
748 vm_page_initfake(m, paddr, memattr);
753 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
756 if ((m->flags & PG_FICTITIOUS) != 0) {
758 * The page's memattr might have changed since the
759 * previous initialization. Update the pmap to the
764 m->phys_addr = paddr;
766 /* Fictitious pages don't use "segind". */
767 m->flags = PG_FICTITIOUS;
768 /* Fictitious pages don't use "order" or "pool". */
769 m->oflags = VPO_UNMANAGED;
770 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
774 pmap_page_set_memattr(m, memattr);
780 * Release a fictitious page.
783 vm_page_putfake(vm_page_t m)
786 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
787 KASSERT((m->flags & PG_FICTITIOUS) != 0,
788 ("vm_page_putfake: bad page %p", m));
789 uma_zfree(fakepg_zone, m);
793 * vm_page_updatefake:
795 * Update the given fictitious page to the specified physical address and
799 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
802 KASSERT((m->flags & PG_FICTITIOUS) != 0,
803 ("vm_page_updatefake: bad page %p", m));
804 m->phys_addr = paddr;
805 pmap_page_set_memattr(m, memattr);
814 vm_page_free(vm_page_t m)
817 m->flags &= ~PG_ZERO;
824 * Free a page to the zerod-pages queue
827 vm_page_free_zero(vm_page_t m)
835 * Unbusy and handle the page queueing for a page from the VOP_GETPAGES()
836 * array which is not the request page.
839 vm_page_readahead_finish(vm_page_t m)
844 * Since the page is not the requested page, whether
845 * it should be activated or deactivated is not
846 * obvious. Empirical results have shown that
847 * deactivating the page is usually the best choice,
848 * unless the page is wanted by another thread.
851 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
854 vm_page_deactivate(m);
859 * Free the completely invalid page. Such page state
860 * occurs due to the short read operation which did
861 * not covered our page at all, or in case when a read
871 * vm_page_sleep_if_busy:
873 * Sleep and release the page queues lock if the page is busied.
874 * Returns TRUE if the thread slept.
876 * The given page must be unlocked and object containing it must
880 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
884 vm_page_lock_assert(m, MA_NOTOWNED);
885 VM_OBJECT_ASSERT_WLOCKED(m->object);
887 if (vm_page_busied(m)) {
889 * The page-specific object must be cached because page
890 * identity can change during the sleep, causing the
891 * re-lock of a different object.
892 * It is assumed that a reference to the object is already
893 * held by the callers.
897 VM_OBJECT_WUNLOCK(obj);
898 vm_page_busy_sleep(m, msg);
899 VM_OBJECT_WLOCK(obj);
906 * vm_page_dirty_KBI: [ internal use only ]
908 * Set all bits in the page's dirty field.
910 * The object containing the specified page must be locked if the
911 * call is made from the machine-independent layer.
913 * See vm_page_clear_dirty_mask().
915 * This function should only be called by vm_page_dirty().
918 vm_page_dirty_KBI(vm_page_t m)
921 /* These assertions refer to this operation by its public name. */
922 KASSERT((m->flags & PG_CACHED) == 0,
923 ("vm_page_dirty: page in cache!"));
924 KASSERT(m->valid == VM_PAGE_BITS_ALL,
925 ("vm_page_dirty: page is invalid!"));
926 m->dirty = VM_PAGE_BITS_ALL;
930 * vm_page_insert: [ internal use only ]
932 * Inserts the given mem entry into the object and object list.
934 * The object must be locked.
937 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
941 VM_OBJECT_ASSERT_WLOCKED(object);
942 mpred = vm_radix_lookup_le(&object->rtree, pindex);
943 return (vm_page_insert_after(m, object, pindex, mpred));
947 * vm_page_insert_after:
949 * Inserts the page "m" into the specified object at offset "pindex".
951 * The page "mpred" must immediately precede the offset "pindex" within
952 * the specified object.
954 * The object must be locked.
957 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
964 VM_OBJECT_ASSERT_WLOCKED(object);
965 KASSERT(m->object == NULL,
966 ("vm_page_insert_after: page already inserted"));
968 KASSERT(mpred->object == object,
969 ("vm_page_insert_after: object doesn't contain mpred"));
970 KASSERT(mpred->pindex < pindex,
971 ("vm_page_insert_after: mpred doesn't precede pindex"));
972 msucc = TAILQ_NEXT(mpred, listq);
974 msucc = TAILQ_FIRST(&object->memq);
976 KASSERT(msucc->pindex > pindex,
977 ("vm_page_insert_after: msucc doesn't succeed pindex"));
980 * Record the object/offset pair in this page
988 * Now link into the object's ordered list of backed pages.
990 if (vm_radix_insert(&object->rtree, m)) {
995 vm_page_insert_radixdone(m, object, mpred);
1000 * vm_page_insert_radixdone:
1002 * Complete page "m" insertion into the specified object after the
1003 * radix trie hooking.
1005 * The page "mpred" must precede the offset "m->pindex" within the
1008 * The object must be locked.
1011 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1014 VM_OBJECT_ASSERT_WLOCKED(object);
1015 KASSERT(object != NULL && m->object == object,
1016 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1017 if (mpred != NULL) {
1018 KASSERT(mpred->object == object,
1019 ("vm_page_insert_after: object doesn't contain mpred"));
1020 KASSERT(mpred->pindex < m->pindex,
1021 ("vm_page_insert_after: mpred doesn't precede pindex"));
1025 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1027 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1030 * Show that the object has one more resident page.
1032 object->resident_page_count++;
1035 * Hold the vnode until the last page is released.
1037 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1038 vhold(object->handle);
1041 * Since we are inserting a new and possibly dirty page,
1042 * update the object's OBJ_MIGHTBEDIRTY flag.
1044 if (pmap_page_is_write_mapped(m))
1045 vm_object_set_writeable_dirty(object);
1051 * Removes the given mem entry from the object/offset-page
1052 * table and the object page list, but do not invalidate/terminate
1053 * the backing store.
1055 * The object must be locked. The page must be locked if it is managed.
1058 vm_page_remove(vm_page_t m)
1063 if ((m->oflags & VPO_UNMANAGED) == 0)
1064 vm_page_lock_assert(m, MA_OWNED);
1065 if ((object = m->object) == NULL)
1067 VM_OBJECT_ASSERT_WLOCKED(object);
1068 if (vm_page_xbusied(m)) {
1070 if ((m->oflags & VPO_UNMANAGED) != 0 &&
1071 !mtx_owned(vm_page_lockptr(m))) {
1076 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1082 * Now remove from the object's list of backed pages.
1084 vm_radix_remove(&object->rtree, m->pindex);
1085 TAILQ_REMOVE(&object->memq, m, listq);
1088 * And show that the object has one fewer resident page.
1090 object->resident_page_count--;
1093 * The vnode may now be recycled.
1095 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1096 vdrop(object->handle);
1104 * Returns the page associated with the object/offset
1105 * pair specified; if none is found, NULL is returned.
1107 * The object must be locked.
1110 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1113 VM_OBJECT_ASSERT_LOCKED(object);
1114 return (vm_radix_lookup(&object->rtree, pindex));
1118 * vm_page_find_least:
1120 * Returns the page associated with the object with least pindex
1121 * greater than or equal to the parameter pindex, or NULL.
1123 * The object must be locked.
1126 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1130 VM_OBJECT_ASSERT_LOCKED(object);
1131 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1132 m = vm_radix_lookup_ge(&object->rtree, pindex);
1137 * Returns the given page's successor (by pindex) within the object if it is
1138 * resident; if none is found, NULL is returned.
1140 * The object must be locked.
1143 vm_page_next(vm_page_t m)
1147 VM_OBJECT_ASSERT_WLOCKED(m->object);
1148 if ((next = TAILQ_NEXT(m, listq)) != NULL &&
1149 next->pindex != m->pindex + 1)
1155 * Returns the given page's predecessor (by pindex) within the object if it is
1156 * resident; if none is found, NULL is returned.
1158 * The object must be locked.
1161 vm_page_prev(vm_page_t m)
1165 VM_OBJECT_ASSERT_WLOCKED(m->object);
1166 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
1167 prev->pindex != m->pindex - 1)
1173 * Uses the page mnew as a replacement for an existing page at index
1174 * pindex which must be already present in the object.
1176 * The existing page must not be on a paging queue.
1179 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1181 vm_page_t mold, mpred;
1183 VM_OBJECT_ASSERT_WLOCKED(object);
1186 * This function mostly follows vm_page_insert() and
1187 * vm_page_remove() without the radix, object count and vnode
1188 * dance. Double check such functions for more comments.
1190 mpred = vm_radix_lookup(&object->rtree, pindex);
1191 KASSERT(mpred != NULL,
1192 ("vm_page_replace: replacing page not present with pindex"));
1193 mpred = TAILQ_PREV(mpred, respgs, listq);
1195 KASSERT(mpred->pindex < pindex,
1196 ("vm_page_insert_after: mpred doesn't precede pindex"));
1198 mnew->object = object;
1199 mnew->pindex = pindex;
1200 mold = vm_radix_replace(&object->rtree, mnew);
1201 KASSERT(mold->queue == PQ_NONE,
1202 ("vm_page_replace: mold is on a paging queue"));
1204 /* Detach the old page from the resident tailq. */
1205 TAILQ_REMOVE(&object->memq, mold, listq);
1207 mold->object = NULL;
1208 vm_page_xunbusy(mold);
1210 /* Insert the new page in the resident tailq. */
1212 TAILQ_INSERT_AFTER(&object->memq, mpred, mnew, listq);
1214 TAILQ_INSERT_HEAD(&object->memq, mnew, listq);
1215 if (pmap_page_is_write_mapped(mnew))
1216 vm_object_set_writeable_dirty(object);
1223 * Move the given memory entry from its
1224 * current object to the specified target object/offset.
1226 * Note: swap associated with the page must be invalidated by the move. We
1227 * have to do this for several reasons: (1) we aren't freeing the
1228 * page, (2) we are dirtying the page, (3) the VM system is probably
1229 * moving the page from object A to B, and will then later move
1230 * the backing store from A to B and we can't have a conflict.
1232 * Note: we *always* dirty the page. It is necessary both for the
1233 * fact that we moved it, and because we may be invalidating
1234 * swap. If the page is on the cache, we have to deactivate it
1235 * or vm_page_dirty() will panic. Dirty pages are not allowed
1238 * The objects must be locked.
1241 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1246 VM_OBJECT_ASSERT_WLOCKED(new_object);
1248 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1249 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1250 ("vm_page_rename: pindex already renamed"));
1253 * Create a custom version of vm_page_insert() which does not depend
1254 * by m_prev and can cheat on the implementation aspects of the
1258 m->pindex = new_pindex;
1259 if (vm_radix_insert(&new_object->rtree, m)) {
1265 * The operation cannot fail anymore. The removal must happen before
1266 * the listq iterator is tainted.
1272 /* Return back to the new pindex to complete vm_page_insert(). */
1273 m->pindex = new_pindex;
1274 m->object = new_object;
1276 vm_page_insert_radixdone(m, new_object, mpred);
1282 * Convert all of the given object's cached pages that have a
1283 * pindex within the given range into free pages. If the value
1284 * zero is given for "end", then the range's upper bound is
1285 * infinity. If the given object is backed by a vnode and it
1286 * transitions from having one or more cached pages to none, the
1287 * vnode's hold count is reduced.
1290 vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1295 mtx_lock(&vm_page_queue_free_mtx);
1296 if (__predict_false(vm_radix_is_empty(&object->cache))) {
1297 mtx_unlock(&vm_page_queue_free_mtx);
1300 while ((m = vm_radix_lookup_ge(&object->cache, start)) != NULL) {
1301 if (end != 0 && m->pindex >= end)
1303 vm_radix_remove(&object->cache, m->pindex);
1304 vm_page_cache_turn_free(m);
1306 empty = vm_radix_is_empty(&object->cache);
1307 mtx_unlock(&vm_page_queue_free_mtx);
1308 if (object->type == OBJT_VNODE && empty)
1309 vdrop(object->handle);
1313 * Returns the cached page that is associated with the given
1314 * object and offset. If, however, none exists, returns NULL.
1316 * The free page queue must be locked.
1318 static inline vm_page_t
1319 vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
1322 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1323 return (vm_radix_lookup(&object->cache, pindex));
1327 * Remove the given cached page from its containing object's
1328 * collection of cached pages.
1330 * The free page queue must be locked.
1333 vm_page_cache_remove(vm_page_t m)
1336 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1337 KASSERT((m->flags & PG_CACHED) != 0,
1338 ("vm_page_cache_remove: page %p is not cached", m));
1339 vm_radix_remove(&m->object->cache, m->pindex);
1341 vm_cnt.v_cache_count--;
1345 * Transfer all of the cached pages with offset greater than or
1346 * equal to 'offidxstart' from the original object's cache to the
1347 * new object's cache. However, any cached pages with offset
1348 * greater than or equal to the new object's size are kept in the
1349 * original object. Initially, the new object's cache must be
1350 * empty. Offset 'offidxstart' in the original object must
1351 * correspond to offset zero in the new object.
1353 * The new object must be locked.
1356 vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1357 vm_object_t new_object)
1362 * Insertion into an object's collection of cached pages
1363 * requires the object to be locked. In contrast, removal does
1366 VM_OBJECT_ASSERT_WLOCKED(new_object);
1367 KASSERT(vm_radix_is_empty(&new_object->cache),
1368 ("vm_page_cache_transfer: object %p has cached pages",
1370 mtx_lock(&vm_page_queue_free_mtx);
1371 while ((m = vm_radix_lookup_ge(&orig_object->cache,
1372 offidxstart)) != NULL) {
1374 * Transfer all of the pages with offset greater than or
1375 * equal to 'offidxstart' from the original object's
1376 * cache to the new object's cache.
1378 if ((m->pindex - offidxstart) >= new_object->size)
1380 vm_radix_remove(&orig_object->cache, m->pindex);
1381 /* Update the page's object and offset. */
1382 m->object = new_object;
1383 m->pindex -= offidxstart;
1384 if (vm_radix_insert(&new_object->cache, m))
1385 vm_page_cache_turn_free(m);
1387 mtx_unlock(&vm_page_queue_free_mtx);
1391 * Returns TRUE if a cached page is associated with the given object and
1392 * offset, and FALSE otherwise.
1394 * The object must be locked.
1397 vm_page_is_cached(vm_object_t object, vm_pindex_t pindex)
1402 * Insertion into an object's collection of cached pages requires the
1403 * object to be locked. Therefore, if the object is locked and the
1404 * object's collection is empty, there is no need to acquire the free
1405 * page queues lock in order to prove that the specified page doesn't
1408 VM_OBJECT_ASSERT_WLOCKED(object);
1409 if (__predict_true(vm_object_cache_is_empty(object)))
1411 mtx_lock(&vm_page_queue_free_mtx);
1412 m = vm_page_cache_lookup(object, pindex);
1413 mtx_unlock(&vm_page_queue_free_mtx);
1420 * Allocate and return a page that is associated with the specified
1421 * object and offset pair. By default, this page is exclusive busied.
1423 * The caller must always specify an allocation class.
1425 * allocation classes:
1426 * VM_ALLOC_NORMAL normal process request
1427 * VM_ALLOC_SYSTEM system *really* needs a page
1428 * VM_ALLOC_INTERRUPT interrupt time request
1430 * optional allocation flags:
1431 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1432 * intends to allocate
1433 * VM_ALLOC_IFCACHED return page only if it is cached
1434 * VM_ALLOC_IFNOTCACHED return NULL, do not reactivate if the page
1436 * VM_ALLOC_NOBUSY do not exclusive busy the page
1437 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1438 * VM_ALLOC_NOOBJ page is not associated with an object and
1439 * should not be exclusive busy
1440 * VM_ALLOC_SBUSY shared busy the allocated page
1441 * VM_ALLOC_WIRED wire the allocated page
1442 * VM_ALLOC_ZERO prefer a zeroed page
1444 * This routine may not sleep.
1447 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1449 struct vnode *vp = NULL;
1450 vm_object_t m_object;
1452 int flags, req_class;
1454 mpred = 0; /* XXX: pacify gcc */
1455 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1456 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1457 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1458 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1459 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1462 VM_OBJECT_ASSERT_WLOCKED(object);
1464 req_class = req & VM_ALLOC_CLASS_MASK;
1467 * The page daemon is allowed to dig deeper into the free page list.
1469 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1470 req_class = VM_ALLOC_SYSTEM;
1472 if (object != NULL) {
1473 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1474 KASSERT(mpred == NULL || mpred->pindex != pindex,
1475 ("vm_page_alloc: pindex already allocated"));
1479 * The page allocation request can came from consumers which already
1480 * hold the free page queue mutex, like vm_page_insert() in
1483 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
1484 if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
1485 (req_class == VM_ALLOC_SYSTEM &&
1486 vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
1487 (req_class == VM_ALLOC_INTERRUPT &&
1488 vm_cnt.v_free_count + vm_cnt.v_cache_count > 0)) {
1490 * Allocate from the free queue if the number of free pages
1491 * exceeds the minimum for the request class.
1493 if (object != NULL &&
1494 (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1495 if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1496 mtx_unlock(&vm_page_queue_free_mtx);
1499 if (vm_phys_unfree_page(m))
1500 vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1501 #if VM_NRESERVLEVEL > 0
1502 else if (!vm_reserv_reactivate_page(m))
1506 panic("vm_page_alloc: cache page %p is missing"
1507 " from the free queue", m);
1508 } else if ((req & VM_ALLOC_IFCACHED) != 0) {
1509 mtx_unlock(&vm_page_queue_free_mtx);
1511 #if VM_NRESERVLEVEL > 0
1512 } else if (object == NULL || (object->flags & (OBJ_COLORED |
1513 OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1514 vm_reserv_alloc_page(object, pindex, mpred)) == NULL) {
1518 m = vm_phys_alloc_pages(object != NULL ?
1519 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1520 #if VM_NRESERVLEVEL > 0
1521 if (m == NULL && vm_reserv_reclaim_inactive()) {
1522 m = vm_phys_alloc_pages(object != NULL ?
1523 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1530 * Not allocatable, give up.
1532 mtx_unlock(&vm_page_queue_free_mtx);
1533 atomic_add_int(&vm_pageout_deficit,
1534 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1535 pagedaemon_wakeup();
1540 * At this point we had better have found a good page.
1542 KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1543 KASSERT(m->queue == PQ_NONE,
1544 ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1545 KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1546 KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1547 KASSERT(!vm_page_sbusied(m),
1548 ("vm_page_alloc: page %p is busy", m));
1549 KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1550 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1551 ("vm_page_alloc: page %p has unexpected memattr %d", m,
1552 pmap_page_get_memattr(m)));
1553 if ((m->flags & PG_CACHED) != 0) {
1554 KASSERT((m->flags & PG_ZERO) == 0,
1555 ("vm_page_alloc: cached page %p is PG_ZERO", m));
1556 KASSERT(m->valid != 0,
1557 ("vm_page_alloc: cached page %p is invalid", m));
1558 if (m->object == object && m->pindex == pindex)
1559 vm_cnt.v_reactivated++;
1562 m_object = m->object;
1563 vm_page_cache_remove(m);
1564 if (m_object->type == OBJT_VNODE &&
1565 vm_object_cache_is_empty(m_object))
1566 vp = m_object->handle;
1568 KASSERT(m->valid == 0,
1569 ("vm_page_alloc: free page %p is valid", m));
1570 vm_phys_freecnt_adj(m, -1);
1571 if ((m->flags & PG_ZERO) != 0)
1572 vm_page_zero_count--;
1574 mtx_unlock(&vm_page_queue_free_mtx);
1577 * Initialize the page. Only the PG_ZERO flag is inherited.
1580 if ((req & VM_ALLOC_ZERO) != 0)
1583 if ((req & VM_ALLOC_NODUMP) != 0)
1587 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1589 m->busy_lock = VPB_UNBUSIED;
1590 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1591 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1592 if ((req & VM_ALLOC_SBUSY) != 0)
1593 m->busy_lock = VPB_SHARERS_WORD(1);
1594 if (req & VM_ALLOC_WIRED) {
1596 * The page lock is not required for wiring a page until that
1597 * page is inserted into the object.
1599 atomic_add_int(&vm_cnt.v_wire_count, 1);
1604 if (object != NULL) {
1605 if (vm_page_insert_after(m, object, pindex, mpred)) {
1606 /* See the comment below about hold count. */
1609 pagedaemon_wakeup();
1610 if (req & VM_ALLOC_WIRED) {
1611 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1619 /* Ignore device objects; the pager sets "memattr" for them. */
1620 if (object->memattr != VM_MEMATTR_DEFAULT &&
1621 (object->flags & OBJ_FICTITIOUS) == 0)
1622 pmap_page_set_memattr(m, object->memattr);
1627 * The following call to vdrop() must come after the above call
1628 * to vm_page_insert() in case both affect the same object and
1629 * vnode. Otherwise, the affected vnode's hold count could
1630 * temporarily become zero.
1636 * Don't wakeup too often - wakeup the pageout daemon when
1637 * we would be nearly out of memory.
1639 if (vm_paging_needed())
1640 pagedaemon_wakeup();
1646 vm_page_alloc_contig_vdrop(struct spglist *lst)
1649 while (!SLIST_EMPTY(lst)) {
1650 vdrop((struct vnode *)SLIST_FIRST(lst)-> plinks.s.pv);
1651 SLIST_REMOVE_HEAD(lst, plinks.s.ss);
1656 * vm_page_alloc_contig:
1658 * Allocate a contiguous set of physical pages of the given size "npages"
1659 * from the free lists. All of the physical pages must be at or above
1660 * the given physical address "low" and below the given physical address
1661 * "high". The given value "alignment" determines the alignment of the
1662 * first physical page in the set. If the given value "boundary" is
1663 * non-zero, then the set of physical pages cannot cross any physical
1664 * address boundary that is a multiple of that value. Both "alignment"
1665 * and "boundary" must be a power of two.
1667 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1668 * then the memory attribute setting for the physical pages is configured
1669 * to the object's memory attribute setting. Otherwise, the memory
1670 * attribute setting for the physical pages is configured to "memattr",
1671 * overriding the object's memory attribute setting. However, if the
1672 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1673 * memory attribute setting for the physical pages cannot be configured
1674 * to VM_MEMATTR_DEFAULT.
1676 * The caller must always specify an allocation class.
1678 * allocation classes:
1679 * VM_ALLOC_NORMAL normal process request
1680 * VM_ALLOC_SYSTEM system *really* needs a page
1681 * VM_ALLOC_INTERRUPT interrupt time request
1683 * optional allocation flags:
1684 * VM_ALLOC_NOBUSY do not exclusive busy the page
1685 * VM_ALLOC_NOOBJ page is not associated with an object and
1686 * should not be exclusive busy
1687 * VM_ALLOC_SBUSY shared busy the allocated page
1688 * VM_ALLOC_WIRED wire the allocated page
1689 * VM_ALLOC_ZERO prefer a zeroed page
1691 * This routine may not sleep.
1694 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1695 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1696 vm_paddr_t boundary, vm_memattr_t memattr)
1699 struct spglist deferred_vdrop_list;
1700 vm_page_t m, m_tmp, m_ret;
1704 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1705 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1706 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1707 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1708 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1710 if (object != NULL) {
1711 VM_OBJECT_ASSERT_WLOCKED(object);
1712 KASSERT(object->type == OBJT_PHYS,
1713 ("vm_page_alloc_contig: object %p isn't OBJT_PHYS",
1716 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1717 req_class = req & VM_ALLOC_CLASS_MASK;
1720 * The page daemon is allowed to dig deeper into the free page list.
1722 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1723 req_class = VM_ALLOC_SYSTEM;
1725 SLIST_INIT(&deferred_vdrop_list);
1726 mtx_lock(&vm_page_queue_free_mtx);
1727 if (vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1728 vm_cnt.v_free_reserved || (req_class == VM_ALLOC_SYSTEM &&
1729 vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1730 vm_cnt.v_interrupt_free_min) || (req_class == VM_ALLOC_INTERRUPT &&
1731 vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages)) {
1732 #if VM_NRESERVLEVEL > 0
1734 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1735 (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1736 low, high, alignment, boundary)) == NULL)
1738 m_ret = vm_phys_alloc_contig(npages, low, high,
1739 alignment, boundary);
1741 mtx_unlock(&vm_page_queue_free_mtx);
1742 atomic_add_int(&vm_pageout_deficit, npages);
1743 pagedaemon_wakeup();
1747 for (m = m_ret; m < &m_ret[npages]; m++) {
1748 drop = vm_page_alloc_init(m);
1751 * Enqueue the vnode for deferred vdrop().
1753 m->plinks.s.pv = drop;
1754 SLIST_INSERT_HEAD(&deferred_vdrop_list, m,
1759 #if VM_NRESERVLEVEL > 0
1760 if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1765 mtx_unlock(&vm_page_queue_free_mtx);
1770 * Initialize the pages. Only the PG_ZERO flag is inherited.
1773 if ((req & VM_ALLOC_ZERO) != 0)
1775 if ((req & VM_ALLOC_NODUMP) != 0)
1777 if ((req & VM_ALLOC_WIRED) != 0)
1778 atomic_add_int(&vm_cnt.v_wire_count, npages);
1779 if (object != NULL) {
1780 if (object->memattr != VM_MEMATTR_DEFAULT &&
1781 memattr == VM_MEMATTR_DEFAULT)
1782 memattr = object->memattr;
1784 for (m = m_ret; m < &m_ret[npages]; m++) {
1786 m->flags = (m->flags | PG_NODUMP) & flags;
1787 m->busy_lock = VPB_UNBUSIED;
1788 if (object != NULL) {
1789 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
1790 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1791 if ((req & VM_ALLOC_SBUSY) != 0)
1792 m->busy_lock = VPB_SHARERS_WORD(1);
1794 if ((req & VM_ALLOC_WIRED) != 0)
1796 /* Unmanaged pages don't use "act_count". */
1797 m->oflags = VPO_UNMANAGED;
1798 if (object != NULL) {
1799 if (vm_page_insert(m, object, pindex)) {
1800 vm_page_alloc_contig_vdrop(
1801 &deferred_vdrop_list);
1802 if (vm_paging_needed())
1803 pagedaemon_wakeup();
1804 if ((req & VM_ALLOC_WIRED) != 0)
1805 atomic_subtract_int(&vm_cnt.v_wire_count,
1807 for (m_tmp = m, m = m_ret;
1808 m < &m_ret[npages]; m++) {
1809 if ((req & VM_ALLOC_WIRED) != 0)
1819 if (memattr != VM_MEMATTR_DEFAULT)
1820 pmap_page_set_memattr(m, memattr);
1823 vm_page_alloc_contig_vdrop(&deferred_vdrop_list);
1824 if (vm_paging_needed())
1825 pagedaemon_wakeup();
1830 * Initialize a page that has been freshly dequeued from a freelist.
1831 * The caller has to drop the vnode returned, if it is not NULL.
1833 * This function may only be used to initialize unmanaged pages.
1835 * To be called with vm_page_queue_free_mtx held.
1837 static struct vnode *
1838 vm_page_alloc_init(vm_page_t m)
1841 vm_object_t m_object;
1843 KASSERT(m->queue == PQ_NONE,
1844 ("vm_page_alloc_init: page %p has unexpected queue %d",
1846 KASSERT(m->wire_count == 0,
1847 ("vm_page_alloc_init: page %p is wired", m));
1848 KASSERT(m->hold_count == 0,
1849 ("vm_page_alloc_init: page %p is held", m));
1850 KASSERT(!vm_page_sbusied(m),
1851 ("vm_page_alloc_init: page %p is busy", m));
1852 KASSERT(m->dirty == 0,
1853 ("vm_page_alloc_init: page %p is dirty", m));
1854 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1855 ("vm_page_alloc_init: page %p has unexpected memattr %d",
1856 m, pmap_page_get_memattr(m)));
1857 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1859 if ((m->flags & PG_CACHED) != 0) {
1860 KASSERT((m->flags & PG_ZERO) == 0,
1861 ("vm_page_alloc_init: cached page %p is PG_ZERO", m));
1863 m_object = m->object;
1864 vm_page_cache_remove(m);
1865 if (m_object->type == OBJT_VNODE &&
1866 vm_object_cache_is_empty(m_object))
1867 drop = m_object->handle;
1869 KASSERT(m->valid == 0,
1870 ("vm_page_alloc_init: free page %p is valid", m));
1871 vm_phys_freecnt_adj(m, -1);
1872 if ((m->flags & PG_ZERO) != 0)
1873 vm_page_zero_count--;
1879 * vm_page_alloc_freelist:
1881 * Allocate a physical page from the specified free page list.
1883 * The caller must always specify an allocation class.
1885 * allocation classes:
1886 * VM_ALLOC_NORMAL normal process request
1887 * VM_ALLOC_SYSTEM system *really* needs a page
1888 * VM_ALLOC_INTERRUPT interrupt time request
1890 * optional allocation flags:
1891 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1892 * intends to allocate
1893 * VM_ALLOC_WIRED wire the allocated page
1894 * VM_ALLOC_ZERO prefer a zeroed page
1896 * This routine may not sleep.
1899 vm_page_alloc_freelist(int flind, int req)
1906 req_class = req & VM_ALLOC_CLASS_MASK;
1909 * The page daemon is allowed to dig deeper into the free page list.
1911 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1912 req_class = VM_ALLOC_SYSTEM;
1915 * Do not allocate reserved pages unless the req has asked for it.
1917 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
1918 if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
1919 (req_class == VM_ALLOC_SYSTEM &&
1920 vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
1921 (req_class == VM_ALLOC_INTERRUPT &&
1922 vm_cnt.v_free_count + vm_cnt.v_cache_count > 0))
1923 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
1925 mtx_unlock(&vm_page_queue_free_mtx);
1926 atomic_add_int(&vm_pageout_deficit,
1927 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1928 pagedaemon_wakeup();
1932 mtx_unlock(&vm_page_queue_free_mtx);
1935 drop = vm_page_alloc_init(m);
1936 mtx_unlock(&vm_page_queue_free_mtx);
1939 * Initialize the page. Only the PG_ZERO flag is inherited.
1943 if ((req & VM_ALLOC_ZERO) != 0)
1946 if ((req & VM_ALLOC_WIRED) != 0) {
1948 * The page lock is not required for wiring a page that does
1949 * not belong to an object.
1951 atomic_add_int(&vm_cnt.v_wire_count, 1);
1954 /* Unmanaged pages don't use "act_count". */
1955 m->oflags = VPO_UNMANAGED;
1958 if (vm_paging_needed())
1959 pagedaemon_wakeup();
1964 * vm_wait: (also see VM_WAIT macro)
1966 * Sleep until free pages are available for allocation.
1967 * - Called in various places before memory allocations.
1973 mtx_lock(&vm_page_queue_free_mtx);
1974 if (curproc == pageproc) {
1975 vm_pageout_pages_needed = 1;
1976 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
1977 PDROP | PSWP, "VMWait", 0);
1979 if (!vm_pages_needed) {
1980 vm_pages_needed = 1;
1981 wakeup(&vm_pages_needed);
1983 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
1989 * vm_waitpfault: (also see VM_WAITPFAULT macro)
1991 * Sleep until free pages are available for allocation.
1992 * - Called only in vm_fault so that processes page faulting
1993 * can be easily tracked.
1994 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
1995 * processes will be able to grab memory first. Do not change
1996 * this balance without careful testing first.
2002 mtx_lock(&vm_page_queue_free_mtx);
2003 if (!vm_pages_needed) {
2004 vm_pages_needed = 1;
2005 wakeup(&vm_pages_needed);
2007 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
2011 struct vm_pagequeue *
2012 vm_page_pagequeue(vm_page_t m)
2015 return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2021 * Remove the given page from its current page queue.
2023 * The page must be locked.
2026 vm_page_dequeue(vm_page_t m)
2028 struct vm_pagequeue *pq;
2030 vm_page_assert_locked(m);
2031 KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
2033 pq = vm_page_pagequeue(m);
2034 vm_pagequeue_lock(pq);
2036 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2037 vm_pagequeue_cnt_dec(pq);
2038 vm_pagequeue_unlock(pq);
2042 * vm_page_dequeue_locked:
2044 * Remove the given page from its current page queue.
2046 * The page and page queue must be locked.
2049 vm_page_dequeue_locked(vm_page_t m)
2051 struct vm_pagequeue *pq;
2053 vm_page_lock_assert(m, MA_OWNED);
2054 pq = vm_page_pagequeue(m);
2055 vm_pagequeue_assert_locked(pq);
2057 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2058 vm_pagequeue_cnt_dec(pq);
2064 * Add the given page to the specified page queue.
2066 * The page must be locked.
2069 vm_page_enqueue(uint8_t queue, vm_page_t m)
2071 struct vm_pagequeue *pq;
2073 vm_page_lock_assert(m, MA_OWNED);
2074 KASSERT(queue < PQ_COUNT,
2075 ("vm_page_enqueue: invalid queue %u request for page %p",
2077 pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2078 vm_pagequeue_lock(pq);
2080 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2081 vm_pagequeue_cnt_inc(pq);
2082 vm_pagequeue_unlock(pq);
2088 * Move the given page to the tail of its current page queue.
2090 * The page must be locked.
2093 vm_page_requeue(vm_page_t m)
2095 struct vm_pagequeue *pq;
2097 vm_page_lock_assert(m, MA_OWNED);
2098 KASSERT(m->queue != PQ_NONE,
2099 ("vm_page_requeue: page %p is not queued", m));
2100 pq = vm_page_pagequeue(m);
2101 vm_pagequeue_lock(pq);
2102 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2103 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2104 vm_pagequeue_unlock(pq);
2108 * vm_page_requeue_locked:
2110 * Move the given page to the tail of its current page queue.
2112 * The page queue must be locked.
2115 vm_page_requeue_locked(vm_page_t m)
2117 struct vm_pagequeue *pq;
2119 KASSERT(m->queue != PQ_NONE,
2120 ("vm_page_requeue_locked: page %p is not queued", m));
2121 pq = vm_page_pagequeue(m);
2122 vm_pagequeue_assert_locked(pq);
2123 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2124 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2130 * Put the specified page on the active list (if appropriate).
2131 * Ensure that act_count is at least ACT_INIT but do not otherwise
2134 * The page must be locked.
2137 vm_page_activate(vm_page_t m)
2141 vm_page_lock_assert(m, MA_OWNED);
2142 if ((queue = m->queue) != PQ_ACTIVE) {
2143 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2144 if (m->act_count < ACT_INIT)
2145 m->act_count = ACT_INIT;
2146 if (queue != PQ_NONE)
2148 vm_page_enqueue(PQ_ACTIVE, m);
2150 KASSERT(queue == PQ_NONE,
2151 ("vm_page_activate: wired page %p is queued", m));
2153 if (m->act_count < ACT_INIT)
2154 m->act_count = ACT_INIT;
2159 * vm_page_free_wakeup:
2161 * Helper routine for vm_page_free_toq() and vm_page_cache(). This
2162 * routine is called when a page has been added to the cache or free
2165 * The page queues must be locked.
2168 vm_page_free_wakeup(void)
2171 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2173 * if pageout daemon needs pages, then tell it that there are
2176 if (vm_pageout_pages_needed &&
2177 vm_cnt.v_cache_count + vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
2178 wakeup(&vm_pageout_pages_needed);
2179 vm_pageout_pages_needed = 0;
2182 * wakeup processes that are waiting on memory if we hit a
2183 * high water mark. And wakeup scheduler process if we have
2184 * lots of memory. this process will swapin processes.
2186 if (vm_pages_needed && !vm_page_count_min()) {
2187 vm_pages_needed = 0;
2188 wakeup(&vm_cnt.v_free_count);
2193 * Turn a cached page into a free page, by changing its attributes.
2194 * Keep the statistics up-to-date.
2196 * The free page queue must be locked.
2199 vm_page_cache_turn_free(vm_page_t m)
2202 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2206 KASSERT((m->flags & PG_CACHED) != 0,
2207 ("vm_page_cache_turn_free: page %p is not cached", m));
2208 m->flags &= ~PG_CACHED;
2209 vm_cnt.v_cache_count--;
2210 vm_phys_freecnt_adj(m, 1);
2216 * Returns the given page to the free list,
2217 * disassociating it with any VM object.
2219 * The object must be locked. The page must be locked if it is managed.
2222 vm_page_free_toq(vm_page_t m)
2225 if ((m->oflags & VPO_UNMANAGED) == 0) {
2226 vm_page_lock_assert(m, MA_OWNED);
2227 KASSERT(!pmap_page_is_mapped(m),
2228 ("vm_page_free_toq: freeing mapped page %p", m));
2230 KASSERT(m->queue == PQ_NONE,
2231 ("vm_page_free_toq: unmanaged page %p is queued", m));
2232 PCPU_INC(cnt.v_tfree);
2234 if (vm_page_sbusied(m))
2235 panic("vm_page_free: freeing busy page %p", m);
2238 * Unqueue, then remove page. Note that we cannot destroy
2239 * the page here because we do not want to call the pager's
2240 * callback routine until after we've put the page on the
2241 * appropriate free queue.
2247 * If fictitious remove object association and
2248 * return, otherwise delay object association removal.
2250 if ((m->flags & PG_FICTITIOUS) != 0) {
2257 if (m->wire_count != 0)
2258 panic("vm_page_free: freeing wired page %p", m);
2259 if (m->hold_count != 0) {
2260 m->flags &= ~PG_ZERO;
2261 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2262 ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
2263 m->flags |= PG_UNHOLDFREE;
2266 * Restore the default memory attribute to the page.
2268 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2269 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2272 * Insert the page into the physical memory allocator's
2273 * cache/free page queues.
2275 mtx_lock(&vm_page_queue_free_mtx);
2276 vm_phys_freecnt_adj(m, 1);
2277 #if VM_NRESERVLEVEL > 0
2278 if (!vm_reserv_free_page(m))
2282 vm_phys_free_pages(m, 0);
2283 if ((m->flags & PG_ZERO) != 0)
2284 ++vm_page_zero_count;
2286 vm_page_zero_idle_wakeup();
2287 vm_page_free_wakeup();
2288 mtx_unlock(&vm_page_queue_free_mtx);
2295 * Mark this page as wired down by yet
2296 * another map, removing it from paging queues
2299 * If the page is fictitious, then its wire count must remain one.
2301 * The page must be locked.
2304 vm_page_wire(vm_page_t m)
2308 * Only bump the wire statistics if the page is not already wired,
2309 * and only unqueue the page if it is on some queue (if it is unmanaged
2310 * it is already off the queues).
2312 vm_page_lock_assert(m, MA_OWNED);
2313 if ((m->flags & PG_FICTITIOUS) != 0) {
2314 KASSERT(m->wire_count == 1,
2315 ("vm_page_wire: fictitious page %p's wire count isn't one",
2319 if (m->wire_count == 0) {
2320 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
2321 m->queue == PQ_NONE,
2322 ("vm_page_wire: unmanaged page %p is queued", m));
2324 atomic_add_int(&vm_cnt.v_wire_count, 1);
2327 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
2333 * Release one wiring of the specified page, potentially enabling it to be
2334 * paged again. If paging is enabled, then the value of the parameter
2335 * "queue" determines the queue to which the page is added.
2337 * However, unless the page belongs to an object, it is not enqueued because
2338 * it cannot be paged out.
2340 * If a page is fictitious, then its wire count must always be one.
2342 * A managed page must be locked.
2345 vm_page_unwire(vm_page_t m, uint8_t queue)
2348 KASSERT(queue < PQ_COUNT,
2349 ("vm_page_unwire: invalid queue %u request for page %p",
2351 if ((m->oflags & VPO_UNMANAGED) == 0)
2352 vm_page_lock_assert(m, MA_OWNED);
2353 if ((m->flags & PG_FICTITIOUS) != 0) {
2354 KASSERT(m->wire_count == 1,
2355 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
2358 if (m->wire_count > 0) {
2360 if (m->wire_count == 0) {
2361 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2362 if ((m->oflags & VPO_UNMANAGED) != 0 ||
2365 if (queue == PQ_INACTIVE)
2366 m->flags &= ~PG_WINATCFLS;
2367 vm_page_enqueue(queue, m);
2370 panic("vm_page_unwire: page %p's wire count is zero", m);
2374 * Move the specified page to the inactive queue.
2376 * Many pages placed on the inactive queue should actually go
2377 * into the cache, but it is difficult to figure out which. What
2378 * we do instead, if the inactive target is well met, is to put
2379 * clean pages at the head of the inactive queue instead of the tail.
2380 * This will cause them to be moved to the cache more quickly and
2381 * if not actively re-referenced, reclaimed more quickly. If we just
2382 * stick these pages at the end of the inactive queue, heavy filesystem
2383 * meta-data accesses can cause an unnecessary paging load on memory bound
2384 * processes. This optimization causes one-time-use metadata to be
2385 * reused more quickly.
2387 * Normally athead is 0 resulting in LRU operation. athead is set
2388 * to 1 if we want this page to be 'as if it were placed in the cache',
2389 * except without unmapping it from the process address space.
2391 * The page must be locked.
2394 _vm_page_deactivate(vm_page_t m, int athead)
2396 struct vm_pagequeue *pq;
2399 vm_page_lock_assert(m, MA_OWNED);
2402 * Ignore if already inactive.
2404 if ((queue = m->queue) == PQ_INACTIVE)
2406 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2407 if (queue != PQ_NONE)
2409 m->flags &= ~PG_WINATCFLS;
2410 pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
2411 vm_pagequeue_lock(pq);
2412 m->queue = PQ_INACTIVE;
2414 TAILQ_INSERT_HEAD(&pq->pq_pl, m, plinks.q);
2416 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2417 vm_pagequeue_cnt_inc(pq);
2418 vm_pagequeue_unlock(pq);
2423 * Move the specified page to the inactive queue.
2425 * The page must be locked.
2428 vm_page_deactivate(vm_page_t m)
2431 _vm_page_deactivate(m, 0);
2435 * vm_page_try_to_cache:
2437 * Returns 0 on failure, 1 on success
2440 vm_page_try_to_cache(vm_page_t m)
2443 vm_page_lock_assert(m, MA_OWNED);
2444 VM_OBJECT_ASSERT_WLOCKED(m->object);
2445 if (m->dirty || m->hold_count || m->wire_count ||
2446 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
2456 * vm_page_try_to_free()
2458 * Attempt to free the page. If we cannot free it, we do nothing.
2459 * 1 is returned on success, 0 on failure.
2462 vm_page_try_to_free(vm_page_t m)
2465 vm_page_lock_assert(m, MA_OWNED);
2466 if (m->object != NULL)
2467 VM_OBJECT_ASSERT_WLOCKED(m->object);
2468 if (m->dirty || m->hold_count || m->wire_count ||
2469 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
2481 * Put the specified page onto the page cache queue (if appropriate).
2483 * The object and page must be locked.
2486 vm_page_cache(vm_page_t m)
2489 boolean_t cache_was_empty;
2491 vm_page_lock_assert(m, MA_OWNED);
2493 VM_OBJECT_ASSERT_WLOCKED(object);
2494 if (vm_page_busied(m) || (m->oflags & VPO_UNMANAGED) ||
2495 m->hold_count || m->wire_count)
2496 panic("vm_page_cache: attempting to cache busy page");
2497 KASSERT(!pmap_page_is_mapped(m),
2498 ("vm_page_cache: page %p is mapped", m));
2499 KASSERT(m->dirty == 0, ("vm_page_cache: page %p is dirty", m));
2500 if (m->valid == 0 || object->type == OBJT_DEFAULT ||
2501 (object->type == OBJT_SWAP &&
2502 !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
2504 * Hypothesis: A cache-eligible page belonging to a
2505 * default object or swap object but without a backing
2506 * store must be zero filled.
2511 KASSERT((m->flags & PG_CACHED) == 0,
2512 ("vm_page_cache: page %p is already cached", m));
2515 * Remove the page from the paging queues.
2520 * Remove the page from the object's collection of resident
2523 vm_radix_remove(&object->rtree, m->pindex);
2524 TAILQ_REMOVE(&object->memq, m, listq);
2525 object->resident_page_count--;
2528 * Restore the default memory attribute to the page.
2530 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2531 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2534 * Insert the page into the object's collection of cached pages
2535 * and the physical memory allocator's cache/free page queues.
2537 m->flags &= ~PG_ZERO;
2538 mtx_lock(&vm_page_queue_free_mtx);
2539 cache_was_empty = vm_radix_is_empty(&object->cache);
2540 if (vm_radix_insert(&object->cache, m)) {
2541 mtx_unlock(&vm_page_queue_free_mtx);
2542 if (object->resident_page_count == 0)
2543 vdrop(object->handle);
2550 * The above call to vm_radix_insert() could reclaim the one pre-
2551 * existing cached page from this object, resulting in a call to
2554 if (!cache_was_empty)
2555 cache_was_empty = vm_radix_is_singleton(&object->cache);
2557 m->flags |= PG_CACHED;
2558 vm_cnt.v_cache_count++;
2559 PCPU_INC(cnt.v_tcached);
2560 #if VM_NRESERVLEVEL > 0
2561 if (!vm_reserv_free_page(m)) {
2565 vm_phys_set_pool(VM_FREEPOOL_CACHE, m, 0);
2566 vm_phys_free_pages(m, 0);
2568 vm_page_free_wakeup();
2569 mtx_unlock(&vm_page_queue_free_mtx);
2572 * Increment the vnode's hold count if this is the object's only
2573 * cached page. Decrement the vnode's hold count if this was
2574 * the object's only resident page.
2576 if (object->type == OBJT_VNODE) {
2577 if (cache_was_empty && object->resident_page_count != 0)
2578 vhold(object->handle);
2579 else if (!cache_was_empty && object->resident_page_count == 0)
2580 vdrop(object->handle);
2587 * Cache, deactivate, or do nothing as appropriate. This routine
2588 * is used by madvise().
2590 * Generally speaking we want to move the page into the cache so
2591 * it gets reused quickly. However, this can result in a silly syndrome
2592 * due to the page recycling too quickly. Small objects will not be
2593 * fully cached. On the other hand, if we move the page to the inactive
2594 * queue we wind up with a problem whereby very large objects
2595 * unnecessarily blow away our inactive and cache queues.
2597 * The solution is to move the pages based on a fixed weighting. We
2598 * either leave them alone, deactivate them, or move them to the cache,
2599 * where moving them to the cache has the highest weighting.
2600 * By forcing some pages into other queues we eventually force the
2601 * system to balance the queues, potentially recovering other unrelated
2602 * space from active. The idea is to not force this to happen too
2605 * The object and page must be locked.
2608 vm_page_advise(vm_page_t m, int advice)
2612 vm_page_assert_locked(m);
2613 VM_OBJECT_ASSERT_WLOCKED(m->object);
2614 if (advice == MADV_FREE) {
2616 * Mark the page clean. This will allow the page to be freed
2617 * up by the system. However, such pages are often reused
2618 * quickly by malloc() so we do not do anything that would
2619 * cause a page fault if we can help it.
2621 * Specifically, we do not try to actually free the page now
2622 * nor do we try to put it in the cache (which would cause a
2623 * page fault on reuse).
2625 * But we do make the page is freeable as we can without
2626 * actually taking the step of unmapping it.
2630 } else if (advice != MADV_DONTNEED)
2632 dnw = PCPU_GET(dnweight);
2636 * Occasionally leave the page alone.
2638 if ((dnw & 0x01F0) == 0 || m->queue == PQ_INACTIVE) {
2639 if (m->act_count >= ACT_INIT)
2645 * Clear any references to the page. Otherwise, the page daemon will
2646 * immediately reactivate the page.
2648 vm_page_aflag_clear(m, PGA_REFERENCED);
2650 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
2653 if (m->dirty || (dnw & 0x0070) == 0) {
2655 * Deactivate the page 3 times out of 32.
2660 * Cache the page 28 times out of every 32. Note that
2661 * the page is deactivated instead of cached, but placed
2662 * at the head of the queue instead of the tail.
2666 _vm_page_deactivate(m, head);
2670 * Grab a page, waiting until we are waken up due to the page
2671 * changing state. We keep on waiting, if the page continues
2672 * to be in the object. If the page doesn't exist, first allocate it
2673 * and then conditionally zero it.
2675 * This routine may sleep.
2677 * The object must be locked on entry. The lock will, however, be released
2678 * and reacquired if the routine sleeps.
2681 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
2686 VM_OBJECT_ASSERT_WLOCKED(object);
2687 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
2688 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
2689 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
2691 if ((m = vm_page_lookup(object, pindex)) != NULL) {
2692 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
2693 vm_page_xbusied(m) : vm_page_busied(m);
2696 * Reference the page before unlocking and
2697 * sleeping so that the page daemon is less
2698 * likely to reclaim it.
2700 vm_page_aflag_set(m, PGA_REFERENCED);
2702 VM_OBJECT_WUNLOCK(object);
2703 vm_page_busy_sleep(m, "pgrbwt");
2704 VM_OBJECT_WLOCK(object);
2707 if ((allocflags & VM_ALLOC_WIRED) != 0) {
2713 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
2715 if ((allocflags & VM_ALLOC_SBUSY) != 0)
2720 m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_IGN_SBUSY);
2722 VM_OBJECT_WUNLOCK(object);
2724 VM_OBJECT_WLOCK(object);
2726 } else if (m->valid != 0)
2728 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
2734 * Mapping function for valid or dirty bits in a page.
2736 * Inputs are required to range within a page.
2739 vm_page_bits(int base, int size)
2745 base + size <= PAGE_SIZE,
2746 ("vm_page_bits: illegal base/size %d/%d", base, size)
2749 if (size == 0) /* handle degenerate case */
2752 first_bit = base >> DEV_BSHIFT;
2753 last_bit = (base + size - 1) >> DEV_BSHIFT;
2755 return (((vm_page_bits_t)2 << last_bit) -
2756 ((vm_page_bits_t)1 << first_bit));
2760 * vm_page_set_valid_range:
2762 * Sets portions of a page valid. The arguments are expected
2763 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2764 * of any partial chunks touched by the range. The invalid portion of
2765 * such chunks will be zeroed.
2767 * (base + size) must be less then or equal to PAGE_SIZE.
2770 vm_page_set_valid_range(vm_page_t m, int base, int size)
2774 VM_OBJECT_ASSERT_WLOCKED(m->object);
2775 if (size == 0) /* handle degenerate case */
2779 * If the base is not DEV_BSIZE aligned and the valid
2780 * bit is clear, we have to zero out a portion of the
2783 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2784 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2785 pmap_zero_page_area(m, frag, base - frag);
2788 * If the ending offset is not DEV_BSIZE aligned and the
2789 * valid bit is clear, we have to zero out a portion of
2792 endoff = base + size;
2793 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2794 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2795 pmap_zero_page_area(m, endoff,
2796 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2799 * Assert that no previously invalid block that is now being validated
2802 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
2803 ("vm_page_set_valid_range: page %p is dirty", m));
2806 * Set valid bits inclusive of any overlap.
2808 m->valid |= vm_page_bits(base, size);
2812 * Clear the given bits from the specified page's dirty field.
2814 static __inline void
2815 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
2818 #if PAGE_SIZE < 16384
2823 * If the object is locked and the page is neither exclusive busy nor
2824 * write mapped, then the page's dirty field cannot possibly be
2825 * set by a concurrent pmap operation.
2827 VM_OBJECT_ASSERT_WLOCKED(m->object);
2828 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
2829 m->dirty &= ~pagebits;
2832 * The pmap layer can call vm_page_dirty() without
2833 * holding a distinguished lock. The combination of
2834 * the object's lock and an atomic operation suffice
2835 * to guarantee consistency of the page dirty field.
2837 * For PAGE_SIZE == 32768 case, compiler already
2838 * properly aligns the dirty field, so no forcible
2839 * alignment is needed. Only require existence of
2840 * atomic_clear_64 when page size is 32768.
2842 addr = (uintptr_t)&m->dirty;
2843 #if PAGE_SIZE == 32768
2844 atomic_clear_64((uint64_t *)addr, pagebits);
2845 #elif PAGE_SIZE == 16384
2846 atomic_clear_32((uint32_t *)addr, pagebits);
2847 #else /* PAGE_SIZE <= 8192 */
2849 * Use a trick to perform a 32-bit atomic on the
2850 * containing aligned word, to not depend on the existence
2851 * of atomic_clear_{8, 16}.
2853 shift = addr & (sizeof(uint32_t) - 1);
2854 #if BYTE_ORDER == BIG_ENDIAN
2855 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
2859 addr &= ~(sizeof(uint32_t) - 1);
2860 atomic_clear_32((uint32_t *)addr, pagebits << shift);
2861 #endif /* PAGE_SIZE */
2866 * vm_page_set_validclean:
2868 * Sets portions of a page valid and clean. The arguments are expected
2869 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2870 * of any partial chunks touched by the range. The invalid portion of
2871 * such chunks will be zero'd.
2873 * (base + size) must be less then or equal to PAGE_SIZE.
2876 vm_page_set_validclean(vm_page_t m, int base, int size)
2878 vm_page_bits_t oldvalid, pagebits;
2881 VM_OBJECT_ASSERT_WLOCKED(m->object);
2882 if (size == 0) /* handle degenerate case */
2886 * If the base is not DEV_BSIZE aligned and the valid
2887 * bit is clear, we have to zero out a portion of the
2890 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2891 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
2892 pmap_zero_page_area(m, frag, base - frag);
2895 * If the ending offset is not DEV_BSIZE aligned and the
2896 * valid bit is clear, we have to zero out a portion of
2899 endoff = base + size;
2900 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2901 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
2902 pmap_zero_page_area(m, endoff,
2903 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2906 * Set valid, clear dirty bits. If validating the entire
2907 * page we can safely clear the pmap modify bit. We also
2908 * use this opportunity to clear the VPO_NOSYNC flag. If a process
2909 * takes a write fault on a MAP_NOSYNC memory area the flag will
2912 * We set valid bits inclusive of any overlap, but we can only
2913 * clear dirty bits for DEV_BSIZE chunks that are fully within
2916 oldvalid = m->valid;
2917 pagebits = vm_page_bits(base, size);
2918 m->valid |= pagebits;
2920 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
2921 frag = DEV_BSIZE - frag;
2927 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
2929 if (base == 0 && size == PAGE_SIZE) {
2931 * The page can only be modified within the pmap if it is
2932 * mapped, and it can only be mapped if it was previously
2935 if (oldvalid == VM_PAGE_BITS_ALL)
2937 * Perform the pmap_clear_modify() first. Otherwise,
2938 * a concurrent pmap operation, such as
2939 * pmap_protect(), could clear a modification in the
2940 * pmap and set the dirty field on the page before
2941 * pmap_clear_modify() had begun and after the dirty
2942 * field was cleared here.
2944 pmap_clear_modify(m);
2946 m->oflags &= ~VPO_NOSYNC;
2947 } else if (oldvalid != VM_PAGE_BITS_ALL)
2948 m->dirty &= ~pagebits;
2950 vm_page_clear_dirty_mask(m, pagebits);
2954 vm_page_clear_dirty(vm_page_t m, int base, int size)
2957 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
2961 * vm_page_set_invalid:
2963 * Invalidates DEV_BSIZE'd chunks within a page. Both the
2964 * valid and dirty bits for the effected areas are cleared.
2967 vm_page_set_invalid(vm_page_t m, int base, int size)
2969 vm_page_bits_t bits;
2973 VM_OBJECT_ASSERT_WLOCKED(object);
2974 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
2975 size >= object->un_pager.vnp.vnp_size)
2976 bits = VM_PAGE_BITS_ALL;
2978 bits = vm_page_bits(base, size);
2979 if (m->valid == VM_PAGE_BITS_ALL && bits != 0)
2981 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
2982 !pmap_page_is_mapped(m),
2983 ("vm_page_set_invalid: page %p is mapped", m));
2989 * vm_page_zero_invalid()
2991 * The kernel assumes that the invalid portions of a page contain
2992 * garbage, but such pages can be mapped into memory by user code.
2993 * When this occurs, we must zero out the non-valid portions of the
2994 * page so user code sees what it expects.
2996 * Pages are most often semi-valid when the end of a file is mapped
2997 * into memory and the file's size is not page aligned.
3000 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3005 VM_OBJECT_ASSERT_WLOCKED(m->object);
3007 * Scan the valid bits looking for invalid sections that
3008 * must be zerod. Invalid sub-DEV_BSIZE'd areas ( where the
3009 * valid bit may be set ) have already been zerod by
3010 * vm_page_set_validclean().
3012 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3013 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3014 (m->valid & ((vm_page_bits_t)1 << i))) {
3016 pmap_zero_page_area(m,
3017 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3024 * setvalid is TRUE when we can safely set the zero'd areas
3025 * as being valid. We can do this if there are no cache consistancy
3026 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3029 m->valid = VM_PAGE_BITS_ALL;
3035 * Is (partial) page valid? Note that the case where size == 0
3036 * will return FALSE in the degenerate case where the page is
3037 * entirely invalid, and TRUE otherwise.
3040 vm_page_is_valid(vm_page_t m, int base, int size)
3042 vm_page_bits_t bits;
3044 VM_OBJECT_ASSERT_LOCKED(m->object);
3045 bits = vm_page_bits(base, size);
3046 return (m->valid != 0 && (m->valid & bits) == bits);
3050 * vm_page_ps_is_valid:
3052 * Returns TRUE if the entire (super)page is valid and FALSE otherwise.
3055 vm_page_ps_is_valid(vm_page_t m)
3059 VM_OBJECT_ASSERT_LOCKED(m->object);
3060 npages = atop(pagesizes[m->psind]);
3063 * The physically contiguous pages that make up a superpage, i.e., a
3064 * page with a page size index ("psind") greater than zero, will
3065 * occupy adjacent entries in vm_page_array[].
3067 for (i = 0; i < npages; i++) {
3068 if (m[i].valid != VM_PAGE_BITS_ALL)
3075 * Set the page's dirty bits if the page is modified.
3078 vm_page_test_dirty(vm_page_t m)
3081 VM_OBJECT_ASSERT_WLOCKED(m->object);
3082 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3087 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3090 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3094 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3097 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3101 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3104 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3107 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3109 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3112 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3116 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3119 mtx_assert_(vm_page_lockptr(m), a, file, line);
3125 vm_page_object_lock_assert(vm_page_t m)
3129 * Certain of the page's fields may only be modified by the
3130 * holder of the containing object's lock or the exclusive busy.
3131 * holder. Unfortunately, the holder of the write busy is
3132 * not recorded, and thus cannot be checked here.
3134 if (m->object != NULL && !vm_page_xbusied(m))
3135 VM_OBJECT_ASSERT_WLOCKED(m->object);
3139 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3142 if ((bits & PGA_WRITEABLE) == 0)
3146 * The PGA_WRITEABLE flag can only be set if the page is
3147 * managed, is exclusively busied or the object is locked.
3148 * Currently, this flag is only set by pmap_enter().
3150 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3151 ("PGA_WRITEABLE on unmanaged page"));
3152 if (!vm_page_xbusied(m))
3153 VM_OBJECT_ASSERT_LOCKED(m->object);
3157 #include "opt_ddb.h"
3159 #include <sys/kernel.h>
3161 #include <ddb/ddb.h>
3163 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3165 db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
3166 db_printf("vm_cnt.v_cache_count: %d\n", vm_cnt.v_cache_count);
3167 db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
3168 db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
3169 db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
3170 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
3171 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
3172 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
3173 db_printf("vm_cnt.v_cache_min: %d\n", vm_cnt.v_cache_min);
3174 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
3177 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3181 db_printf("pq_free %d pq_cache %d\n",
3182 vm_cnt.v_free_count, vm_cnt.v_cache_count);
3183 for (dom = 0; dom < vm_ndomains; dom++) {
3185 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pass %d\n",
3187 vm_dom[dom].vmd_page_count,
3188 vm_dom[dom].vmd_free_count,
3189 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3190 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
3191 vm_dom[dom].vmd_pass);
3195 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3201 db_printf("show pginfo addr\n");
3205 phys = strchr(modif, 'p') != NULL;
3207 m = PHYS_TO_VM_PAGE(addr);
3209 m = (vm_page_t)addr;
3211 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3212 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3213 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3214 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3215 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);