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 vm_paddr_t biggestsize;
295 vm_paddr_t low_water, high_water;
300 vaddr = round_page(vaddr);
302 for (i = 0; phys_avail[i + 1]; i += 2) {
303 phys_avail[i] = round_page(phys_avail[i]);
304 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
309 * There is no obvious reason why i386 PV Xen needs vm_page structs
310 * created for these pseudo-physical addresses. XXX
312 vm_phys_add_seg(0, phys_avail[0]);
315 low_water = phys_avail[0];
316 high_water = phys_avail[1];
318 for (i = 0; i < vm_phys_nsegs; i++) {
319 if (vm_phys_segs[i].start < low_water)
320 low_water = vm_phys_segs[i].start;
321 if (vm_phys_segs[i].end > high_water)
322 high_water = vm_phys_segs[i].end;
324 for (i = 0; phys_avail[i + 1]; i += 2) {
325 vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
327 if (size > biggestsize) {
331 if (phys_avail[i] < low_water)
332 low_water = phys_avail[i];
333 if (phys_avail[i + 1] > high_water)
334 high_water = phys_avail[i + 1];
337 end = phys_avail[biggestone+1];
340 * Initialize the page and queue locks.
342 mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
343 for (i = 0; i < PA_LOCK_COUNT; i++)
344 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
345 for (i = 0; i < vm_ndomains; i++)
346 vm_page_domain_init(&vm_dom[i]);
349 * Allocate memory for use when boot strapping the kernel memory
352 new_end = end - (boot_pages * UMA_SLAB_SIZE);
353 new_end = trunc_page(new_end);
354 mapped = pmap_map(&vaddr, new_end, end,
355 VM_PROT_READ | VM_PROT_WRITE);
356 bzero((void *)mapped, end - new_end);
357 uma_startup((void *)mapped, boot_pages);
359 #if defined(__amd64__) || defined(__i386__) || defined(__arm__) || \
362 * Allocate a bitmap to indicate that a random physical page
363 * needs to be included in a minidump.
365 * The amd64 port needs this to indicate which direct map pages
366 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
368 * However, i386 still needs this workspace internally within the
369 * minidump code. In theory, they are not needed on i386, but are
370 * included should the sf_buf code decide to use them.
373 for (i = 0; dump_avail[i + 1] != 0; i += 2)
374 if (dump_avail[i + 1] > last_pa)
375 last_pa = dump_avail[i + 1];
376 page_range = last_pa / PAGE_SIZE;
377 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
378 new_end -= vm_page_dump_size;
379 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
380 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
381 bzero((void *)vm_page_dump, vm_page_dump_size);
385 * Request that the physical pages underlying the message buffer be
386 * included in a crash dump. Since the message buffer is accessed
387 * through the direct map, they are not automatically included.
389 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
390 last_pa = pa + round_page(msgbufsize);
391 while (pa < last_pa) {
397 * Compute the number of pages of memory that will be available for
398 * use (taking into account the overhead of a page structure per
401 first_page = low_water / PAGE_SIZE;
402 #ifdef VM_PHYSSEG_SPARSE
404 for (i = 0; i < vm_phys_nsegs; i++) {
405 page_range += atop(vm_phys_segs[i].end -
406 vm_phys_segs[i].start);
408 for (i = 0; phys_avail[i + 1] != 0; i += 2)
409 page_range += atop(phys_avail[i + 1] - phys_avail[i]);
410 #elif defined(VM_PHYSSEG_DENSE)
411 page_range = high_water / PAGE_SIZE - first_page;
413 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
418 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
423 * Initialize the mem entry structures now, and put them in the free
426 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
427 mapped = pmap_map(&vaddr, new_end, end,
428 VM_PROT_READ | VM_PROT_WRITE);
429 vm_page_array = (vm_page_t) mapped;
430 #if VM_NRESERVLEVEL > 0
432 * Allocate memory for the reservation management system's data
435 new_end = vm_reserv_startup(&vaddr, new_end, high_water);
437 #if defined(__amd64__) || defined(__mips__)
439 * pmap_map on amd64 and mips can come out of the direct-map, not kvm
440 * like i386, so the pages must be tracked for a crashdump to include
441 * this data. This includes the vm_page_array and the early UMA
444 for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
447 phys_avail[biggestone + 1] = new_end;
450 * Add physical memory segments corresponding to the available
453 for (i = 0; phys_avail[i + 1] != 0; i += 2)
454 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
457 * Clear all of the page structures
459 bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
460 for (i = 0; i < page_range; i++)
461 vm_page_array[i].order = VM_NFREEORDER;
462 vm_page_array_size = page_range;
465 * Initialize the physical memory allocator.
470 * Add every available physical page that is not blacklisted to
473 vm_cnt.v_page_count = 0;
474 vm_cnt.v_free_count = 0;
475 list = kern_getenv("vm.blacklist");
476 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
478 last_pa = phys_avail[i + 1];
479 while (pa < last_pa) {
481 vm_page_blacklist_lookup(list, pa))
482 printf("Skipping page with pa 0x%jx\n",
485 vm_phys_add_page(pa);
490 #if VM_NRESERVLEVEL > 0
492 * Initialize the reservation management system.
500 vm_page_reference(vm_page_t m)
503 vm_page_aflag_set(m, PGA_REFERENCED);
507 * vm_page_busy_downgrade:
509 * Downgrade an exclusive busy page into a single shared busy page.
512 vm_page_busy_downgrade(vm_page_t m)
516 vm_page_assert_xbusied(m);
520 x &= VPB_BIT_WAITERS;
521 if (atomic_cmpset_rel_int(&m->busy_lock,
522 VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1) | x))
530 * Return a positive value if the page is shared busied, 0 otherwise.
533 vm_page_sbusied(vm_page_t m)
538 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
544 * Shared unbusy a page.
547 vm_page_sunbusy(vm_page_t m)
551 vm_page_assert_sbusied(m);
555 if (VPB_SHARERS(x) > 1) {
556 if (atomic_cmpset_int(&m->busy_lock, x,
561 if ((x & VPB_BIT_WAITERS) == 0) {
562 KASSERT(x == VPB_SHARERS_WORD(1),
563 ("vm_page_sunbusy: invalid lock state"));
564 if (atomic_cmpset_int(&m->busy_lock,
565 VPB_SHARERS_WORD(1), VPB_UNBUSIED))
569 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
570 ("vm_page_sunbusy: invalid lock state for waiters"));
573 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
584 * vm_page_busy_sleep:
586 * Sleep and release the page lock, using the page pointer as wchan.
587 * This is used to implement the hard-path of busying mechanism.
589 * The given page must be locked.
592 vm_page_busy_sleep(vm_page_t m, const char *wmesg)
596 vm_page_lock_assert(m, MA_OWNED);
599 if (x == VPB_UNBUSIED) {
603 if ((x & VPB_BIT_WAITERS) == 0 &&
604 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS)) {
608 msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
614 * Try to shared busy a page.
615 * If the operation succeeds 1 is returned otherwise 0.
616 * The operation never sleeps.
619 vm_page_trysbusy(vm_page_t m)
625 if ((x & VPB_BIT_SHARED) == 0)
627 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
633 * vm_page_xunbusy_hard:
635 * Called after the first try the exclusive unbusy of a page failed.
636 * It is assumed that the waiters bit is on.
639 vm_page_xunbusy_hard(vm_page_t m)
642 vm_page_assert_xbusied(m);
645 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
653 * Wakeup anyone waiting for the page.
654 * The ownership bits do not change.
656 * The given page must be locked.
659 vm_page_flash(vm_page_t m)
663 vm_page_lock_assert(m, MA_OWNED);
667 if ((x & VPB_BIT_WAITERS) == 0)
669 if (atomic_cmpset_int(&m->busy_lock, x,
670 x & (~VPB_BIT_WAITERS)))
677 * Keep page from being freed by the page daemon
678 * much of the same effect as wiring, except much lower
679 * overhead and should be used only for *very* temporary
680 * holding ("wiring").
683 vm_page_hold(vm_page_t mem)
686 vm_page_lock_assert(mem, MA_OWNED);
691 vm_page_unhold(vm_page_t mem)
694 vm_page_lock_assert(mem, MA_OWNED);
695 KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
697 if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
698 vm_page_free_toq(mem);
702 * vm_page_unhold_pages:
704 * Unhold each of the pages that is referenced by the given array.
707 vm_page_unhold_pages(vm_page_t *ma, int count)
709 struct mtx *mtx, *new_mtx;
712 for (; count != 0; count--) {
714 * Avoid releasing and reacquiring the same page lock.
716 new_mtx = vm_page_lockptr(*ma);
717 if (mtx != new_mtx) {
731 PHYS_TO_VM_PAGE(vm_paddr_t pa)
735 #ifdef VM_PHYSSEG_SPARSE
736 m = vm_phys_paddr_to_vm_page(pa);
738 m = vm_phys_fictitious_to_vm_page(pa);
740 #elif defined(VM_PHYSSEG_DENSE)
744 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
745 m = &vm_page_array[pi - first_page];
748 return (vm_phys_fictitious_to_vm_page(pa));
750 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
757 * Create a fictitious page with the specified physical address and
758 * memory attribute. The memory attribute is the only the machine-
759 * dependent aspect of a fictitious page that must be initialized.
762 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
766 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
767 vm_page_initfake(m, paddr, memattr);
772 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
775 if ((m->flags & PG_FICTITIOUS) != 0) {
777 * The page's memattr might have changed since the
778 * previous initialization. Update the pmap to the
783 m->phys_addr = paddr;
785 /* Fictitious pages don't use "segind". */
786 m->flags = PG_FICTITIOUS;
787 /* Fictitious pages don't use "order" or "pool". */
788 m->oflags = VPO_UNMANAGED;
789 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
793 pmap_page_set_memattr(m, memattr);
799 * Release a fictitious page.
802 vm_page_putfake(vm_page_t m)
805 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
806 KASSERT((m->flags & PG_FICTITIOUS) != 0,
807 ("vm_page_putfake: bad page %p", m));
808 uma_zfree(fakepg_zone, m);
812 * vm_page_updatefake:
814 * Update the given fictitious page to the specified physical address and
818 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
821 KASSERT((m->flags & PG_FICTITIOUS) != 0,
822 ("vm_page_updatefake: bad page %p", m));
823 m->phys_addr = paddr;
824 pmap_page_set_memattr(m, memattr);
833 vm_page_free(vm_page_t m)
836 m->flags &= ~PG_ZERO;
843 * Free a page to the zerod-pages queue
846 vm_page_free_zero(vm_page_t m)
854 * Unbusy and handle the page queueing for a page from the VOP_GETPAGES()
855 * array which is not the request page.
858 vm_page_readahead_finish(vm_page_t m)
863 * Since the page is not the requested page, whether
864 * it should be activated or deactivated is not
865 * obvious. Empirical results have shown that
866 * deactivating the page is usually the best choice,
867 * unless the page is wanted by another thread.
870 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
873 vm_page_deactivate(m);
878 * Free the completely invalid page. Such page state
879 * occurs due to the short read operation which did
880 * not covered our page at all, or in case when a read
890 * vm_page_sleep_if_busy:
892 * Sleep and release the page queues lock if the page is busied.
893 * Returns TRUE if the thread slept.
895 * The given page must be unlocked and object containing it must
899 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
903 vm_page_lock_assert(m, MA_NOTOWNED);
904 VM_OBJECT_ASSERT_WLOCKED(m->object);
906 if (vm_page_busied(m)) {
908 * The page-specific object must be cached because page
909 * identity can change during the sleep, causing the
910 * re-lock of a different object.
911 * It is assumed that a reference to the object is already
912 * held by the callers.
916 VM_OBJECT_WUNLOCK(obj);
917 vm_page_busy_sleep(m, msg);
918 VM_OBJECT_WLOCK(obj);
925 * vm_page_dirty_KBI: [ internal use only ]
927 * Set all bits in the page's dirty field.
929 * The object containing the specified page must be locked if the
930 * call is made from the machine-independent layer.
932 * See vm_page_clear_dirty_mask().
934 * This function should only be called by vm_page_dirty().
937 vm_page_dirty_KBI(vm_page_t m)
940 /* These assertions refer to this operation by its public name. */
941 KASSERT((m->flags & PG_CACHED) == 0,
942 ("vm_page_dirty: page in cache!"));
943 KASSERT(m->valid == VM_PAGE_BITS_ALL,
944 ("vm_page_dirty: page is invalid!"));
945 m->dirty = VM_PAGE_BITS_ALL;
949 * vm_page_insert: [ internal use only ]
951 * Inserts the given mem entry into the object and object list.
953 * The object must be locked.
956 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
960 VM_OBJECT_ASSERT_WLOCKED(object);
961 mpred = vm_radix_lookup_le(&object->rtree, pindex);
962 return (vm_page_insert_after(m, object, pindex, mpred));
966 * vm_page_insert_after:
968 * Inserts the page "m" into the specified object at offset "pindex".
970 * The page "mpred" must immediately precede the offset "pindex" within
971 * the specified object.
973 * The object must be locked.
976 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
983 VM_OBJECT_ASSERT_WLOCKED(object);
984 KASSERT(m->object == NULL,
985 ("vm_page_insert_after: page already inserted"));
987 KASSERT(mpred->object == object,
988 ("vm_page_insert_after: object doesn't contain mpred"));
989 KASSERT(mpred->pindex < pindex,
990 ("vm_page_insert_after: mpred doesn't precede pindex"));
991 msucc = TAILQ_NEXT(mpred, listq);
993 msucc = TAILQ_FIRST(&object->memq);
995 KASSERT(msucc->pindex > pindex,
996 ("vm_page_insert_after: msucc doesn't succeed pindex"));
999 * Record the object/offset pair in this page
1007 * Now link into the object's ordered list of backed pages.
1009 if (vm_radix_insert(&object->rtree, m)) {
1014 vm_page_insert_radixdone(m, object, mpred);
1019 * vm_page_insert_radixdone:
1021 * Complete page "m" insertion into the specified object after the
1022 * radix trie hooking.
1024 * The page "mpred" must precede the offset "m->pindex" within the
1027 * The object must be locked.
1030 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1033 VM_OBJECT_ASSERT_WLOCKED(object);
1034 KASSERT(object != NULL && m->object == object,
1035 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1036 if (mpred != NULL) {
1037 KASSERT(mpred->object == object,
1038 ("vm_page_insert_after: object doesn't contain mpred"));
1039 KASSERT(mpred->pindex < m->pindex,
1040 ("vm_page_insert_after: mpred doesn't precede pindex"));
1044 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1046 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1049 * Show that the object has one more resident page.
1051 object->resident_page_count++;
1054 * Hold the vnode until the last page is released.
1056 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1057 vhold(object->handle);
1060 * Since we are inserting a new and possibly dirty page,
1061 * update the object's OBJ_MIGHTBEDIRTY flag.
1063 if (pmap_page_is_write_mapped(m))
1064 vm_object_set_writeable_dirty(object);
1070 * Removes the given mem entry from the object/offset-page
1071 * table and the object page list, but do not invalidate/terminate
1072 * the backing store.
1074 * The object must be locked. The page must be locked if it is managed.
1077 vm_page_remove(vm_page_t m)
1082 if ((m->oflags & VPO_UNMANAGED) == 0)
1083 vm_page_lock_assert(m, MA_OWNED);
1084 if ((object = m->object) == NULL)
1086 VM_OBJECT_ASSERT_WLOCKED(object);
1087 if (vm_page_xbusied(m)) {
1089 if ((m->oflags & VPO_UNMANAGED) != 0 &&
1090 !mtx_owned(vm_page_lockptr(m))) {
1095 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1101 * Now remove from the object's list of backed pages.
1103 vm_radix_remove(&object->rtree, m->pindex);
1104 TAILQ_REMOVE(&object->memq, m, listq);
1107 * And show that the object has one fewer resident page.
1109 object->resident_page_count--;
1112 * The vnode may now be recycled.
1114 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1115 vdrop(object->handle);
1123 * Returns the page associated with the object/offset
1124 * pair specified; if none is found, NULL is returned.
1126 * The object must be locked.
1129 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1132 VM_OBJECT_ASSERT_LOCKED(object);
1133 return (vm_radix_lookup(&object->rtree, pindex));
1137 * vm_page_find_least:
1139 * Returns the page associated with the object with least pindex
1140 * greater than or equal to the parameter pindex, or NULL.
1142 * The object must be locked.
1145 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1149 VM_OBJECT_ASSERT_LOCKED(object);
1150 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1151 m = vm_radix_lookup_ge(&object->rtree, pindex);
1156 * Returns the given page's successor (by pindex) within the object if it is
1157 * resident; if none is found, NULL is returned.
1159 * The object must be locked.
1162 vm_page_next(vm_page_t m)
1166 VM_OBJECT_ASSERT_WLOCKED(m->object);
1167 if ((next = TAILQ_NEXT(m, listq)) != NULL &&
1168 next->pindex != m->pindex + 1)
1174 * Returns the given page's predecessor (by pindex) within the object if it is
1175 * resident; if none is found, NULL is returned.
1177 * The object must be locked.
1180 vm_page_prev(vm_page_t m)
1184 VM_OBJECT_ASSERT_WLOCKED(m->object);
1185 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
1186 prev->pindex != m->pindex - 1)
1192 * Uses the page mnew as a replacement for an existing page at index
1193 * pindex which must be already present in the object.
1195 * The existing page must not be on a paging queue.
1198 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1200 vm_page_t mold, mpred;
1202 VM_OBJECT_ASSERT_WLOCKED(object);
1205 * This function mostly follows vm_page_insert() and
1206 * vm_page_remove() without the radix, object count and vnode
1207 * dance. Double check such functions for more comments.
1209 mpred = vm_radix_lookup(&object->rtree, pindex);
1210 KASSERT(mpred != NULL,
1211 ("vm_page_replace: replacing page not present with pindex"));
1212 mpred = TAILQ_PREV(mpred, respgs, listq);
1214 KASSERT(mpred->pindex < pindex,
1215 ("vm_page_insert_after: mpred doesn't precede pindex"));
1217 mnew->object = object;
1218 mnew->pindex = pindex;
1219 mold = vm_radix_replace(&object->rtree, mnew);
1220 KASSERT(mold->queue == PQ_NONE,
1221 ("vm_page_replace: mold is on a paging queue"));
1223 /* Detach the old page from the resident tailq. */
1224 TAILQ_REMOVE(&object->memq, mold, listq);
1226 mold->object = NULL;
1227 vm_page_xunbusy(mold);
1229 /* Insert the new page in the resident tailq. */
1231 TAILQ_INSERT_AFTER(&object->memq, mpred, mnew, listq);
1233 TAILQ_INSERT_HEAD(&object->memq, mnew, listq);
1234 if (pmap_page_is_write_mapped(mnew))
1235 vm_object_set_writeable_dirty(object);
1242 * Move the given memory entry from its
1243 * current object to the specified target object/offset.
1245 * Note: swap associated with the page must be invalidated by the move. We
1246 * have to do this for several reasons: (1) we aren't freeing the
1247 * page, (2) we are dirtying the page, (3) the VM system is probably
1248 * moving the page from object A to B, and will then later move
1249 * the backing store from A to B and we can't have a conflict.
1251 * Note: we *always* dirty the page. It is necessary both for the
1252 * fact that we moved it, and because we may be invalidating
1253 * swap. If the page is on the cache, we have to deactivate it
1254 * or vm_page_dirty() will panic. Dirty pages are not allowed
1257 * The objects must be locked.
1260 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1265 VM_OBJECT_ASSERT_WLOCKED(new_object);
1267 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1268 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1269 ("vm_page_rename: pindex already renamed"));
1272 * Create a custom version of vm_page_insert() which does not depend
1273 * by m_prev and can cheat on the implementation aspects of the
1277 m->pindex = new_pindex;
1278 if (vm_radix_insert(&new_object->rtree, m)) {
1284 * The operation cannot fail anymore. The removal must happen before
1285 * the listq iterator is tainted.
1291 /* Return back to the new pindex to complete vm_page_insert(). */
1292 m->pindex = new_pindex;
1293 m->object = new_object;
1295 vm_page_insert_radixdone(m, new_object, mpred);
1301 * Convert all of the given object's cached pages that have a
1302 * pindex within the given range into free pages. If the value
1303 * zero is given for "end", then the range's upper bound is
1304 * infinity. If the given object is backed by a vnode and it
1305 * transitions from having one or more cached pages to none, the
1306 * vnode's hold count is reduced.
1309 vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1314 mtx_lock(&vm_page_queue_free_mtx);
1315 if (__predict_false(vm_radix_is_empty(&object->cache))) {
1316 mtx_unlock(&vm_page_queue_free_mtx);
1319 while ((m = vm_radix_lookup_ge(&object->cache, start)) != NULL) {
1320 if (end != 0 && m->pindex >= end)
1322 vm_radix_remove(&object->cache, m->pindex);
1323 vm_page_cache_turn_free(m);
1325 empty = vm_radix_is_empty(&object->cache);
1326 mtx_unlock(&vm_page_queue_free_mtx);
1327 if (object->type == OBJT_VNODE && empty)
1328 vdrop(object->handle);
1332 * Returns the cached page that is associated with the given
1333 * object and offset. If, however, none exists, returns NULL.
1335 * The free page queue must be locked.
1337 static inline vm_page_t
1338 vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
1341 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1342 return (vm_radix_lookup(&object->cache, pindex));
1346 * Remove the given cached page from its containing object's
1347 * collection of cached pages.
1349 * The free page queue must be locked.
1352 vm_page_cache_remove(vm_page_t m)
1355 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1356 KASSERT((m->flags & PG_CACHED) != 0,
1357 ("vm_page_cache_remove: page %p is not cached", m));
1358 vm_radix_remove(&m->object->cache, m->pindex);
1360 vm_cnt.v_cache_count--;
1364 * Transfer all of the cached pages with offset greater than or
1365 * equal to 'offidxstart' from the original object's cache to the
1366 * new object's cache. However, any cached pages with offset
1367 * greater than or equal to the new object's size are kept in the
1368 * original object. Initially, the new object's cache must be
1369 * empty. Offset 'offidxstart' in the original object must
1370 * correspond to offset zero in the new object.
1372 * The new object must be locked.
1375 vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1376 vm_object_t new_object)
1381 * Insertion into an object's collection of cached pages
1382 * requires the object to be locked. In contrast, removal does
1385 VM_OBJECT_ASSERT_WLOCKED(new_object);
1386 KASSERT(vm_radix_is_empty(&new_object->cache),
1387 ("vm_page_cache_transfer: object %p has cached pages",
1389 mtx_lock(&vm_page_queue_free_mtx);
1390 while ((m = vm_radix_lookup_ge(&orig_object->cache,
1391 offidxstart)) != NULL) {
1393 * Transfer all of the pages with offset greater than or
1394 * equal to 'offidxstart' from the original object's
1395 * cache to the new object's cache.
1397 if ((m->pindex - offidxstart) >= new_object->size)
1399 vm_radix_remove(&orig_object->cache, m->pindex);
1400 /* Update the page's object and offset. */
1401 m->object = new_object;
1402 m->pindex -= offidxstart;
1403 if (vm_radix_insert(&new_object->cache, m))
1404 vm_page_cache_turn_free(m);
1406 mtx_unlock(&vm_page_queue_free_mtx);
1410 * Returns TRUE if a cached page is associated with the given object and
1411 * offset, and FALSE otherwise.
1413 * The object must be locked.
1416 vm_page_is_cached(vm_object_t object, vm_pindex_t pindex)
1421 * Insertion into an object's collection of cached pages requires the
1422 * object to be locked. Therefore, if the object is locked and the
1423 * object's collection is empty, there is no need to acquire the free
1424 * page queues lock in order to prove that the specified page doesn't
1427 VM_OBJECT_ASSERT_WLOCKED(object);
1428 if (__predict_true(vm_object_cache_is_empty(object)))
1430 mtx_lock(&vm_page_queue_free_mtx);
1431 m = vm_page_cache_lookup(object, pindex);
1432 mtx_unlock(&vm_page_queue_free_mtx);
1439 * Allocate and return a page that is associated with the specified
1440 * object and offset pair. By default, this page is exclusive busied.
1442 * The caller must always specify an allocation class.
1444 * allocation classes:
1445 * VM_ALLOC_NORMAL normal process request
1446 * VM_ALLOC_SYSTEM system *really* needs a page
1447 * VM_ALLOC_INTERRUPT interrupt time request
1449 * optional allocation flags:
1450 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1451 * intends to allocate
1452 * VM_ALLOC_IFCACHED return page only if it is cached
1453 * VM_ALLOC_IFNOTCACHED return NULL, do not reactivate if the page
1455 * VM_ALLOC_NOBUSY do not exclusive busy the page
1456 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1457 * VM_ALLOC_NOOBJ page is not associated with an object and
1458 * should not be exclusive busy
1459 * VM_ALLOC_SBUSY shared busy the allocated page
1460 * VM_ALLOC_WIRED wire the allocated page
1461 * VM_ALLOC_ZERO prefer a zeroed page
1463 * This routine may not sleep.
1466 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1468 struct vnode *vp = NULL;
1469 vm_object_t m_object;
1471 int flags, req_class;
1473 mpred = 0; /* XXX: pacify gcc */
1474 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1475 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1476 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1477 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1478 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1481 VM_OBJECT_ASSERT_WLOCKED(object);
1483 req_class = req & VM_ALLOC_CLASS_MASK;
1486 * The page daemon is allowed to dig deeper into the free page list.
1488 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1489 req_class = VM_ALLOC_SYSTEM;
1491 if (object != NULL) {
1492 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1493 KASSERT(mpred == NULL || mpred->pindex != pindex,
1494 ("vm_page_alloc: pindex already allocated"));
1498 * The page allocation request can came from consumers which already
1499 * hold the free page queue mutex, like vm_page_insert() in
1502 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
1503 if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
1504 (req_class == VM_ALLOC_SYSTEM &&
1505 vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
1506 (req_class == VM_ALLOC_INTERRUPT &&
1507 vm_cnt.v_free_count + vm_cnt.v_cache_count > 0)) {
1509 * Allocate from the free queue if the number of free pages
1510 * exceeds the minimum for the request class.
1512 if (object != NULL &&
1513 (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1514 if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1515 mtx_unlock(&vm_page_queue_free_mtx);
1518 if (vm_phys_unfree_page(m))
1519 vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1520 #if VM_NRESERVLEVEL > 0
1521 else if (!vm_reserv_reactivate_page(m))
1525 panic("vm_page_alloc: cache page %p is missing"
1526 " from the free queue", m);
1527 } else if ((req & VM_ALLOC_IFCACHED) != 0) {
1528 mtx_unlock(&vm_page_queue_free_mtx);
1530 #if VM_NRESERVLEVEL > 0
1531 } else if (object == NULL || (object->flags & (OBJ_COLORED |
1532 OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1533 vm_reserv_alloc_page(object, pindex, mpred)) == NULL) {
1537 m = vm_phys_alloc_pages(object != NULL ?
1538 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1539 #if VM_NRESERVLEVEL > 0
1540 if (m == NULL && vm_reserv_reclaim_inactive()) {
1541 m = vm_phys_alloc_pages(object != NULL ?
1542 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1549 * Not allocatable, give up.
1551 mtx_unlock(&vm_page_queue_free_mtx);
1552 atomic_add_int(&vm_pageout_deficit,
1553 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1554 pagedaemon_wakeup();
1559 * At this point we had better have found a good page.
1561 KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1562 KASSERT(m->queue == PQ_NONE,
1563 ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1564 KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1565 KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1566 KASSERT(!vm_page_sbusied(m),
1567 ("vm_page_alloc: page %p is busy", m));
1568 KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1569 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1570 ("vm_page_alloc: page %p has unexpected memattr %d", m,
1571 pmap_page_get_memattr(m)));
1572 if ((m->flags & PG_CACHED) != 0) {
1573 KASSERT((m->flags & PG_ZERO) == 0,
1574 ("vm_page_alloc: cached page %p is PG_ZERO", m));
1575 KASSERT(m->valid != 0,
1576 ("vm_page_alloc: cached page %p is invalid", m));
1577 if (m->object == object && m->pindex == pindex)
1578 vm_cnt.v_reactivated++;
1581 m_object = m->object;
1582 vm_page_cache_remove(m);
1583 if (m_object->type == OBJT_VNODE &&
1584 vm_object_cache_is_empty(m_object))
1585 vp = m_object->handle;
1587 KASSERT(m->valid == 0,
1588 ("vm_page_alloc: free page %p is valid", m));
1589 vm_phys_freecnt_adj(m, -1);
1590 if ((m->flags & PG_ZERO) != 0)
1591 vm_page_zero_count--;
1593 mtx_unlock(&vm_page_queue_free_mtx);
1596 * Initialize the page. Only the PG_ZERO flag is inherited.
1599 if ((req & VM_ALLOC_ZERO) != 0)
1602 if ((req & VM_ALLOC_NODUMP) != 0)
1606 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1608 m->busy_lock = VPB_UNBUSIED;
1609 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1610 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1611 if ((req & VM_ALLOC_SBUSY) != 0)
1612 m->busy_lock = VPB_SHARERS_WORD(1);
1613 if (req & VM_ALLOC_WIRED) {
1615 * The page lock is not required for wiring a page until that
1616 * page is inserted into the object.
1618 atomic_add_int(&vm_cnt.v_wire_count, 1);
1623 if (object != NULL) {
1624 if (vm_page_insert_after(m, object, pindex, mpred)) {
1625 /* See the comment below about hold count. */
1628 pagedaemon_wakeup();
1629 if (req & VM_ALLOC_WIRED) {
1630 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1638 /* Ignore device objects; the pager sets "memattr" for them. */
1639 if (object->memattr != VM_MEMATTR_DEFAULT &&
1640 (object->flags & OBJ_FICTITIOUS) == 0)
1641 pmap_page_set_memattr(m, object->memattr);
1646 * The following call to vdrop() must come after the above call
1647 * to vm_page_insert() in case both affect the same object and
1648 * vnode. Otherwise, the affected vnode's hold count could
1649 * temporarily become zero.
1655 * Don't wakeup too often - wakeup the pageout daemon when
1656 * we would be nearly out of memory.
1658 if (vm_paging_needed())
1659 pagedaemon_wakeup();
1665 vm_page_alloc_contig_vdrop(struct spglist *lst)
1668 while (!SLIST_EMPTY(lst)) {
1669 vdrop((struct vnode *)SLIST_FIRST(lst)-> plinks.s.pv);
1670 SLIST_REMOVE_HEAD(lst, plinks.s.ss);
1675 * vm_page_alloc_contig:
1677 * Allocate a contiguous set of physical pages of the given size "npages"
1678 * from the free lists. All of the physical pages must be at or above
1679 * the given physical address "low" and below the given physical address
1680 * "high". The given value "alignment" determines the alignment of the
1681 * first physical page in the set. If the given value "boundary" is
1682 * non-zero, then the set of physical pages cannot cross any physical
1683 * address boundary that is a multiple of that value. Both "alignment"
1684 * and "boundary" must be a power of two.
1686 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1687 * then the memory attribute setting for the physical pages is configured
1688 * to the object's memory attribute setting. Otherwise, the memory
1689 * attribute setting for the physical pages is configured to "memattr",
1690 * overriding the object's memory attribute setting. However, if the
1691 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1692 * memory attribute setting for the physical pages cannot be configured
1693 * to VM_MEMATTR_DEFAULT.
1695 * The caller must always specify an allocation class.
1697 * allocation classes:
1698 * VM_ALLOC_NORMAL normal process request
1699 * VM_ALLOC_SYSTEM system *really* needs a page
1700 * VM_ALLOC_INTERRUPT interrupt time request
1702 * optional allocation flags:
1703 * VM_ALLOC_NOBUSY do not exclusive busy the page
1704 * VM_ALLOC_NOOBJ page is not associated with an object and
1705 * should not be exclusive busy
1706 * VM_ALLOC_SBUSY shared busy the allocated page
1707 * VM_ALLOC_WIRED wire the allocated page
1708 * VM_ALLOC_ZERO prefer a zeroed page
1710 * This routine may not sleep.
1713 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1714 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1715 vm_paddr_t boundary, vm_memattr_t memattr)
1718 struct spglist deferred_vdrop_list;
1719 vm_page_t m, m_tmp, m_ret;
1723 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1724 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1725 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1726 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1727 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1729 if (object != NULL) {
1730 VM_OBJECT_ASSERT_WLOCKED(object);
1731 KASSERT(object->type == OBJT_PHYS,
1732 ("vm_page_alloc_contig: object %p isn't OBJT_PHYS",
1735 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1736 req_class = req & VM_ALLOC_CLASS_MASK;
1739 * The page daemon is allowed to dig deeper into the free page list.
1741 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1742 req_class = VM_ALLOC_SYSTEM;
1744 SLIST_INIT(&deferred_vdrop_list);
1745 mtx_lock(&vm_page_queue_free_mtx);
1746 if (vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1747 vm_cnt.v_free_reserved || (req_class == VM_ALLOC_SYSTEM &&
1748 vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1749 vm_cnt.v_interrupt_free_min) || (req_class == VM_ALLOC_INTERRUPT &&
1750 vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages)) {
1751 #if VM_NRESERVLEVEL > 0
1753 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1754 (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1755 low, high, alignment, boundary)) == NULL)
1757 m_ret = vm_phys_alloc_contig(npages, low, high,
1758 alignment, boundary);
1760 mtx_unlock(&vm_page_queue_free_mtx);
1761 atomic_add_int(&vm_pageout_deficit, npages);
1762 pagedaemon_wakeup();
1766 for (m = m_ret; m < &m_ret[npages]; m++) {
1767 drop = vm_page_alloc_init(m);
1770 * Enqueue the vnode for deferred vdrop().
1772 m->plinks.s.pv = drop;
1773 SLIST_INSERT_HEAD(&deferred_vdrop_list, m,
1778 #if VM_NRESERVLEVEL > 0
1779 if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1784 mtx_unlock(&vm_page_queue_free_mtx);
1789 * Initialize the pages. Only the PG_ZERO flag is inherited.
1792 if ((req & VM_ALLOC_ZERO) != 0)
1794 if ((req & VM_ALLOC_NODUMP) != 0)
1796 if ((req & VM_ALLOC_WIRED) != 0)
1797 atomic_add_int(&vm_cnt.v_wire_count, npages);
1798 if (object != NULL) {
1799 if (object->memattr != VM_MEMATTR_DEFAULT &&
1800 memattr == VM_MEMATTR_DEFAULT)
1801 memattr = object->memattr;
1803 for (m = m_ret; m < &m_ret[npages]; m++) {
1805 m->flags = (m->flags | PG_NODUMP) & flags;
1806 m->busy_lock = VPB_UNBUSIED;
1807 if (object != NULL) {
1808 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
1809 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1810 if ((req & VM_ALLOC_SBUSY) != 0)
1811 m->busy_lock = VPB_SHARERS_WORD(1);
1813 if ((req & VM_ALLOC_WIRED) != 0)
1815 /* Unmanaged pages don't use "act_count". */
1816 m->oflags = VPO_UNMANAGED;
1817 if (object != NULL) {
1818 if (vm_page_insert(m, object, pindex)) {
1819 vm_page_alloc_contig_vdrop(
1820 &deferred_vdrop_list);
1821 if (vm_paging_needed())
1822 pagedaemon_wakeup();
1823 if ((req & VM_ALLOC_WIRED) != 0)
1824 atomic_subtract_int(&vm_cnt.v_wire_count,
1826 for (m_tmp = m, m = m_ret;
1827 m < &m_ret[npages]; m++) {
1828 if ((req & VM_ALLOC_WIRED) != 0)
1838 if (memattr != VM_MEMATTR_DEFAULT)
1839 pmap_page_set_memattr(m, memattr);
1842 vm_page_alloc_contig_vdrop(&deferred_vdrop_list);
1843 if (vm_paging_needed())
1844 pagedaemon_wakeup();
1849 * Initialize a page that has been freshly dequeued from a freelist.
1850 * The caller has to drop the vnode returned, if it is not NULL.
1852 * This function may only be used to initialize unmanaged pages.
1854 * To be called with vm_page_queue_free_mtx held.
1856 static struct vnode *
1857 vm_page_alloc_init(vm_page_t m)
1860 vm_object_t m_object;
1862 KASSERT(m->queue == PQ_NONE,
1863 ("vm_page_alloc_init: page %p has unexpected queue %d",
1865 KASSERT(m->wire_count == 0,
1866 ("vm_page_alloc_init: page %p is wired", m));
1867 KASSERT(m->hold_count == 0,
1868 ("vm_page_alloc_init: page %p is held", m));
1869 KASSERT(!vm_page_sbusied(m),
1870 ("vm_page_alloc_init: page %p is busy", m));
1871 KASSERT(m->dirty == 0,
1872 ("vm_page_alloc_init: page %p is dirty", m));
1873 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1874 ("vm_page_alloc_init: page %p has unexpected memattr %d",
1875 m, pmap_page_get_memattr(m)));
1876 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1878 if ((m->flags & PG_CACHED) != 0) {
1879 KASSERT((m->flags & PG_ZERO) == 0,
1880 ("vm_page_alloc_init: cached page %p is PG_ZERO", m));
1882 m_object = m->object;
1883 vm_page_cache_remove(m);
1884 if (m_object->type == OBJT_VNODE &&
1885 vm_object_cache_is_empty(m_object))
1886 drop = m_object->handle;
1888 KASSERT(m->valid == 0,
1889 ("vm_page_alloc_init: free page %p is valid", m));
1890 vm_phys_freecnt_adj(m, -1);
1891 if ((m->flags & PG_ZERO) != 0)
1892 vm_page_zero_count--;
1898 * vm_page_alloc_freelist:
1900 * Allocate a physical page from the specified free page list.
1902 * The caller must always specify an allocation class.
1904 * allocation classes:
1905 * VM_ALLOC_NORMAL normal process request
1906 * VM_ALLOC_SYSTEM system *really* needs a page
1907 * VM_ALLOC_INTERRUPT interrupt time request
1909 * optional allocation flags:
1910 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1911 * intends to allocate
1912 * VM_ALLOC_WIRED wire the allocated page
1913 * VM_ALLOC_ZERO prefer a zeroed page
1915 * This routine may not sleep.
1918 vm_page_alloc_freelist(int flind, int req)
1925 req_class = req & VM_ALLOC_CLASS_MASK;
1928 * The page daemon is allowed to dig deeper into the free page list.
1930 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1931 req_class = VM_ALLOC_SYSTEM;
1934 * Do not allocate reserved pages unless the req has asked for it.
1936 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
1937 if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
1938 (req_class == VM_ALLOC_SYSTEM &&
1939 vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
1940 (req_class == VM_ALLOC_INTERRUPT &&
1941 vm_cnt.v_free_count + vm_cnt.v_cache_count > 0))
1942 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
1944 mtx_unlock(&vm_page_queue_free_mtx);
1945 atomic_add_int(&vm_pageout_deficit,
1946 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1947 pagedaemon_wakeup();
1951 mtx_unlock(&vm_page_queue_free_mtx);
1954 drop = vm_page_alloc_init(m);
1955 mtx_unlock(&vm_page_queue_free_mtx);
1958 * Initialize the page. Only the PG_ZERO flag is inherited.
1962 if ((req & VM_ALLOC_ZERO) != 0)
1965 if ((req & VM_ALLOC_WIRED) != 0) {
1967 * The page lock is not required for wiring a page that does
1968 * not belong to an object.
1970 atomic_add_int(&vm_cnt.v_wire_count, 1);
1973 /* Unmanaged pages don't use "act_count". */
1974 m->oflags = VPO_UNMANAGED;
1977 if (vm_paging_needed())
1978 pagedaemon_wakeup();
1983 * vm_wait: (also see VM_WAIT macro)
1985 * Sleep until free pages are available for allocation.
1986 * - Called in various places before memory allocations.
1992 mtx_lock(&vm_page_queue_free_mtx);
1993 if (curproc == pageproc) {
1994 vm_pageout_pages_needed = 1;
1995 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
1996 PDROP | PSWP, "VMWait", 0);
1998 if (!vm_pages_needed) {
1999 vm_pages_needed = 1;
2000 wakeup(&vm_pages_needed);
2002 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
2008 * vm_waitpfault: (also see VM_WAITPFAULT macro)
2010 * Sleep until free pages are available for allocation.
2011 * - Called only in vm_fault so that processes page faulting
2012 * can be easily tracked.
2013 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2014 * processes will be able to grab memory first. Do not change
2015 * this balance without careful testing first.
2021 mtx_lock(&vm_page_queue_free_mtx);
2022 if (!vm_pages_needed) {
2023 vm_pages_needed = 1;
2024 wakeup(&vm_pages_needed);
2026 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
2030 struct vm_pagequeue *
2031 vm_page_pagequeue(vm_page_t m)
2034 return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2040 * Remove the given page from its current page queue.
2042 * The page must be locked.
2045 vm_page_dequeue(vm_page_t m)
2047 struct vm_pagequeue *pq;
2049 vm_page_assert_locked(m);
2050 KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
2052 pq = vm_page_pagequeue(m);
2053 vm_pagequeue_lock(pq);
2055 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2056 vm_pagequeue_cnt_dec(pq);
2057 vm_pagequeue_unlock(pq);
2061 * vm_page_dequeue_locked:
2063 * Remove the given page from its current page queue.
2065 * The page and page queue must be locked.
2068 vm_page_dequeue_locked(vm_page_t m)
2070 struct vm_pagequeue *pq;
2072 vm_page_lock_assert(m, MA_OWNED);
2073 pq = vm_page_pagequeue(m);
2074 vm_pagequeue_assert_locked(pq);
2076 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2077 vm_pagequeue_cnt_dec(pq);
2083 * Add the given page to the specified page queue.
2085 * The page must be locked.
2088 vm_page_enqueue(uint8_t queue, vm_page_t m)
2090 struct vm_pagequeue *pq;
2092 vm_page_lock_assert(m, MA_OWNED);
2093 KASSERT(queue < PQ_COUNT,
2094 ("vm_page_enqueue: invalid queue %u request for page %p",
2096 pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2097 vm_pagequeue_lock(pq);
2099 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2100 vm_pagequeue_cnt_inc(pq);
2101 vm_pagequeue_unlock(pq);
2107 * Move the given page to the tail of its current page queue.
2109 * The page must be locked.
2112 vm_page_requeue(vm_page_t m)
2114 struct vm_pagequeue *pq;
2116 vm_page_lock_assert(m, MA_OWNED);
2117 KASSERT(m->queue != PQ_NONE,
2118 ("vm_page_requeue: page %p is not queued", m));
2119 pq = vm_page_pagequeue(m);
2120 vm_pagequeue_lock(pq);
2121 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2122 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2123 vm_pagequeue_unlock(pq);
2127 * vm_page_requeue_locked:
2129 * Move the given page to the tail of its current page queue.
2131 * The page queue must be locked.
2134 vm_page_requeue_locked(vm_page_t m)
2136 struct vm_pagequeue *pq;
2138 KASSERT(m->queue != PQ_NONE,
2139 ("vm_page_requeue_locked: page %p is not queued", m));
2140 pq = vm_page_pagequeue(m);
2141 vm_pagequeue_assert_locked(pq);
2142 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2143 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2149 * Put the specified page on the active list (if appropriate).
2150 * Ensure that act_count is at least ACT_INIT but do not otherwise
2153 * The page must be locked.
2156 vm_page_activate(vm_page_t m)
2160 vm_page_lock_assert(m, MA_OWNED);
2161 if ((queue = m->queue) != PQ_ACTIVE) {
2162 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2163 if (m->act_count < ACT_INIT)
2164 m->act_count = ACT_INIT;
2165 if (queue != PQ_NONE)
2167 vm_page_enqueue(PQ_ACTIVE, m);
2169 KASSERT(queue == PQ_NONE,
2170 ("vm_page_activate: wired page %p is queued", m));
2172 if (m->act_count < ACT_INIT)
2173 m->act_count = ACT_INIT;
2178 * vm_page_free_wakeup:
2180 * Helper routine for vm_page_free_toq() and vm_page_cache(). This
2181 * routine is called when a page has been added to the cache or free
2184 * The page queues must be locked.
2187 vm_page_free_wakeup(void)
2190 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2192 * if pageout daemon needs pages, then tell it that there are
2195 if (vm_pageout_pages_needed &&
2196 vm_cnt.v_cache_count + vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
2197 wakeup(&vm_pageout_pages_needed);
2198 vm_pageout_pages_needed = 0;
2201 * wakeup processes that are waiting on memory if we hit a
2202 * high water mark. And wakeup scheduler process if we have
2203 * lots of memory. this process will swapin processes.
2205 if (vm_pages_needed && !vm_page_count_min()) {
2206 vm_pages_needed = 0;
2207 wakeup(&vm_cnt.v_free_count);
2212 * Turn a cached page into a free page, by changing its attributes.
2213 * Keep the statistics up-to-date.
2215 * The free page queue must be locked.
2218 vm_page_cache_turn_free(vm_page_t m)
2221 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2225 KASSERT((m->flags & PG_CACHED) != 0,
2226 ("vm_page_cache_turn_free: page %p is not cached", m));
2227 m->flags &= ~PG_CACHED;
2228 vm_cnt.v_cache_count--;
2229 vm_phys_freecnt_adj(m, 1);
2235 * Returns the given page to the free list,
2236 * disassociating it with any VM object.
2238 * The object must be locked. The page must be locked if it is managed.
2241 vm_page_free_toq(vm_page_t m)
2244 if ((m->oflags & VPO_UNMANAGED) == 0) {
2245 vm_page_lock_assert(m, MA_OWNED);
2246 KASSERT(!pmap_page_is_mapped(m),
2247 ("vm_page_free_toq: freeing mapped page %p", m));
2249 KASSERT(m->queue == PQ_NONE,
2250 ("vm_page_free_toq: unmanaged page %p is queued", m));
2251 PCPU_INC(cnt.v_tfree);
2253 if (vm_page_sbusied(m))
2254 panic("vm_page_free: freeing busy page %p", m);
2257 * Unqueue, then remove page. Note that we cannot destroy
2258 * the page here because we do not want to call the pager's
2259 * callback routine until after we've put the page on the
2260 * appropriate free queue.
2266 * If fictitious remove object association and
2267 * return, otherwise delay object association removal.
2269 if ((m->flags & PG_FICTITIOUS) != 0) {
2276 if (m->wire_count != 0)
2277 panic("vm_page_free: freeing wired page %p", m);
2278 if (m->hold_count != 0) {
2279 m->flags &= ~PG_ZERO;
2280 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2281 ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
2282 m->flags |= PG_UNHOLDFREE;
2285 * Restore the default memory attribute to the page.
2287 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2288 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2291 * Insert the page into the physical memory allocator's
2292 * cache/free page queues.
2294 mtx_lock(&vm_page_queue_free_mtx);
2295 vm_phys_freecnt_adj(m, 1);
2296 #if VM_NRESERVLEVEL > 0
2297 if (!vm_reserv_free_page(m))
2301 vm_phys_free_pages(m, 0);
2302 if ((m->flags & PG_ZERO) != 0)
2303 ++vm_page_zero_count;
2305 vm_page_zero_idle_wakeup();
2306 vm_page_free_wakeup();
2307 mtx_unlock(&vm_page_queue_free_mtx);
2314 * Mark this page as wired down by yet
2315 * another map, removing it from paging queues
2318 * If the page is fictitious, then its wire count must remain one.
2320 * The page must be locked.
2323 vm_page_wire(vm_page_t m)
2327 * Only bump the wire statistics if the page is not already wired,
2328 * and only unqueue the page if it is on some queue (if it is unmanaged
2329 * it is already off the queues).
2331 vm_page_lock_assert(m, MA_OWNED);
2332 if ((m->flags & PG_FICTITIOUS) != 0) {
2333 KASSERT(m->wire_count == 1,
2334 ("vm_page_wire: fictitious page %p's wire count isn't one",
2338 if (m->wire_count == 0) {
2339 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
2340 m->queue == PQ_NONE,
2341 ("vm_page_wire: unmanaged page %p is queued", m));
2343 atomic_add_int(&vm_cnt.v_wire_count, 1);
2346 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
2352 * Release one wiring of the specified page, potentially enabling it to be
2353 * paged again. If paging is enabled, then the value of the parameter
2354 * "queue" determines the queue to which the page is added.
2356 * However, unless the page belongs to an object, it is not enqueued because
2357 * it cannot be paged out.
2359 * If a page is fictitious, then its wire count must always be one.
2361 * A managed page must be locked.
2364 vm_page_unwire(vm_page_t m, uint8_t queue)
2367 KASSERT(queue < PQ_COUNT,
2368 ("vm_page_unwire: invalid queue %u request for page %p",
2370 if ((m->oflags & VPO_UNMANAGED) == 0)
2371 vm_page_lock_assert(m, MA_OWNED);
2372 if ((m->flags & PG_FICTITIOUS) != 0) {
2373 KASSERT(m->wire_count == 1,
2374 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
2377 if (m->wire_count > 0) {
2379 if (m->wire_count == 0) {
2380 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2381 if ((m->oflags & VPO_UNMANAGED) != 0 ||
2384 if (queue == PQ_INACTIVE)
2385 m->flags &= ~PG_WINATCFLS;
2386 vm_page_enqueue(queue, m);
2389 panic("vm_page_unwire: page %p's wire count is zero", m);
2393 * Move the specified page to the inactive queue.
2395 * Many pages placed on the inactive queue should actually go
2396 * into the cache, but it is difficult to figure out which. What
2397 * we do instead, if the inactive target is well met, is to put
2398 * clean pages at the head of the inactive queue instead of the tail.
2399 * This will cause them to be moved to the cache more quickly and
2400 * if not actively re-referenced, reclaimed more quickly. If we just
2401 * stick these pages at the end of the inactive queue, heavy filesystem
2402 * meta-data accesses can cause an unnecessary paging load on memory bound
2403 * processes. This optimization causes one-time-use metadata to be
2404 * reused more quickly.
2406 * Normally athead is 0 resulting in LRU operation. athead is set
2407 * to 1 if we want this page to be 'as if it were placed in the cache',
2408 * except without unmapping it from the process address space.
2410 * The page must be locked.
2413 _vm_page_deactivate(vm_page_t m, int athead)
2415 struct vm_pagequeue *pq;
2418 vm_page_lock_assert(m, MA_OWNED);
2421 * Ignore if already inactive.
2423 if ((queue = m->queue) == PQ_INACTIVE)
2425 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2426 if (queue != PQ_NONE)
2428 m->flags &= ~PG_WINATCFLS;
2429 pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
2430 vm_pagequeue_lock(pq);
2431 m->queue = PQ_INACTIVE;
2433 TAILQ_INSERT_HEAD(&pq->pq_pl, m, plinks.q);
2435 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2436 vm_pagequeue_cnt_inc(pq);
2437 vm_pagequeue_unlock(pq);
2442 * Move the specified page to the inactive queue.
2444 * The page must be locked.
2447 vm_page_deactivate(vm_page_t m)
2450 _vm_page_deactivate(m, 0);
2454 * vm_page_try_to_cache:
2456 * Returns 0 on failure, 1 on success
2459 vm_page_try_to_cache(vm_page_t m)
2462 vm_page_lock_assert(m, MA_OWNED);
2463 VM_OBJECT_ASSERT_WLOCKED(m->object);
2464 if (m->dirty || m->hold_count || m->wire_count ||
2465 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
2475 * vm_page_try_to_free()
2477 * Attempt to free the page. If we cannot free it, we do nothing.
2478 * 1 is returned on success, 0 on failure.
2481 vm_page_try_to_free(vm_page_t m)
2484 vm_page_lock_assert(m, MA_OWNED);
2485 if (m->object != NULL)
2486 VM_OBJECT_ASSERT_WLOCKED(m->object);
2487 if (m->dirty || m->hold_count || m->wire_count ||
2488 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
2500 * Put the specified page onto the page cache queue (if appropriate).
2502 * The object and page must be locked.
2505 vm_page_cache(vm_page_t m)
2508 boolean_t cache_was_empty;
2510 vm_page_lock_assert(m, MA_OWNED);
2512 VM_OBJECT_ASSERT_WLOCKED(object);
2513 if (vm_page_busied(m) || (m->oflags & VPO_UNMANAGED) ||
2514 m->hold_count || m->wire_count)
2515 panic("vm_page_cache: attempting to cache busy page");
2516 KASSERT(!pmap_page_is_mapped(m),
2517 ("vm_page_cache: page %p is mapped", m));
2518 KASSERT(m->dirty == 0, ("vm_page_cache: page %p is dirty", m));
2519 if (m->valid == 0 || object->type == OBJT_DEFAULT ||
2520 (object->type == OBJT_SWAP &&
2521 !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
2523 * Hypothesis: A cache-eligible page belonging to a
2524 * default object or swap object but without a backing
2525 * store must be zero filled.
2530 KASSERT((m->flags & PG_CACHED) == 0,
2531 ("vm_page_cache: page %p is already cached", m));
2534 * Remove the page from the paging queues.
2539 * Remove the page from the object's collection of resident
2542 vm_radix_remove(&object->rtree, m->pindex);
2543 TAILQ_REMOVE(&object->memq, m, listq);
2544 object->resident_page_count--;
2547 * Restore the default memory attribute to the page.
2549 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2550 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2553 * Insert the page into the object's collection of cached pages
2554 * and the physical memory allocator's cache/free page queues.
2556 m->flags &= ~PG_ZERO;
2557 mtx_lock(&vm_page_queue_free_mtx);
2558 cache_was_empty = vm_radix_is_empty(&object->cache);
2559 if (vm_radix_insert(&object->cache, m)) {
2560 mtx_unlock(&vm_page_queue_free_mtx);
2561 if (object->resident_page_count == 0)
2562 vdrop(object->handle);
2569 * The above call to vm_radix_insert() could reclaim the one pre-
2570 * existing cached page from this object, resulting in a call to
2573 if (!cache_was_empty)
2574 cache_was_empty = vm_radix_is_singleton(&object->cache);
2576 m->flags |= PG_CACHED;
2577 vm_cnt.v_cache_count++;
2578 PCPU_INC(cnt.v_tcached);
2579 #if VM_NRESERVLEVEL > 0
2580 if (!vm_reserv_free_page(m)) {
2584 vm_phys_set_pool(VM_FREEPOOL_CACHE, m, 0);
2585 vm_phys_free_pages(m, 0);
2587 vm_page_free_wakeup();
2588 mtx_unlock(&vm_page_queue_free_mtx);
2591 * Increment the vnode's hold count if this is the object's only
2592 * cached page. Decrement the vnode's hold count if this was
2593 * the object's only resident page.
2595 if (object->type == OBJT_VNODE) {
2596 if (cache_was_empty && object->resident_page_count != 0)
2597 vhold(object->handle);
2598 else if (!cache_was_empty && object->resident_page_count == 0)
2599 vdrop(object->handle);
2606 * Cache, deactivate, or do nothing as appropriate. This routine
2607 * is used by madvise().
2609 * Generally speaking we want to move the page into the cache so
2610 * it gets reused quickly. However, this can result in a silly syndrome
2611 * due to the page recycling too quickly. Small objects will not be
2612 * fully cached. On the other hand, if we move the page to the inactive
2613 * queue we wind up with a problem whereby very large objects
2614 * unnecessarily blow away our inactive and cache queues.
2616 * The solution is to move the pages based on a fixed weighting. We
2617 * either leave them alone, deactivate them, or move them to the cache,
2618 * where moving them to the cache has the highest weighting.
2619 * By forcing some pages into other queues we eventually force the
2620 * system to balance the queues, potentially recovering other unrelated
2621 * space from active. The idea is to not force this to happen too
2624 * The object and page must be locked.
2627 vm_page_advise(vm_page_t m, int advice)
2631 vm_page_assert_locked(m);
2632 VM_OBJECT_ASSERT_WLOCKED(m->object);
2633 if (advice == MADV_FREE) {
2635 * Mark the page clean. This will allow the page to be freed
2636 * up by the system. However, such pages are often reused
2637 * quickly by malloc() so we do not do anything that would
2638 * cause a page fault if we can help it.
2640 * Specifically, we do not try to actually free the page now
2641 * nor do we try to put it in the cache (which would cause a
2642 * page fault on reuse).
2644 * But we do make the page is freeable as we can without
2645 * actually taking the step of unmapping it.
2649 } else if (advice != MADV_DONTNEED)
2651 dnw = PCPU_GET(dnweight);
2655 * Occasionally leave the page alone.
2657 if ((dnw & 0x01F0) == 0 || m->queue == PQ_INACTIVE) {
2658 if (m->act_count >= ACT_INIT)
2664 * Clear any references to the page. Otherwise, the page daemon will
2665 * immediately reactivate the page.
2667 vm_page_aflag_clear(m, PGA_REFERENCED);
2669 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
2672 if (m->dirty || (dnw & 0x0070) == 0) {
2674 * Deactivate the page 3 times out of 32.
2679 * Cache the page 28 times out of every 32. Note that
2680 * the page is deactivated instead of cached, but placed
2681 * at the head of the queue instead of the tail.
2685 _vm_page_deactivate(m, head);
2689 * Grab a page, waiting until we are waken up due to the page
2690 * changing state. We keep on waiting, if the page continues
2691 * to be in the object. If the page doesn't exist, first allocate it
2692 * and then conditionally zero it.
2694 * This routine may sleep.
2696 * The object must be locked on entry. The lock will, however, be released
2697 * and reacquired if the routine sleeps.
2700 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
2705 VM_OBJECT_ASSERT_WLOCKED(object);
2706 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
2707 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
2708 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
2710 if ((m = vm_page_lookup(object, pindex)) != NULL) {
2711 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
2712 vm_page_xbusied(m) : vm_page_busied(m);
2714 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
2717 * Reference the page before unlocking and
2718 * sleeping so that the page daemon is less
2719 * likely to reclaim it.
2721 vm_page_aflag_set(m, PGA_REFERENCED);
2723 VM_OBJECT_WUNLOCK(object);
2724 vm_page_busy_sleep(m, "pgrbwt");
2725 VM_OBJECT_WLOCK(object);
2728 if ((allocflags & VM_ALLOC_WIRED) != 0) {
2734 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
2736 if ((allocflags & VM_ALLOC_SBUSY) != 0)
2741 m = vm_page_alloc(object, pindex, allocflags);
2743 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
2745 VM_OBJECT_WUNLOCK(object);
2747 VM_OBJECT_WLOCK(object);
2749 } else if (m->valid != 0)
2751 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
2757 * Mapping function for valid or dirty bits in a page.
2759 * Inputs are required to range within a page.
2762 vm_page_bits(int base, int size)
2768 base + size <= PAGE_SIZE,
2769 ("vm_page_bits: illegal base/size %d/%d", base, size)
2772 if (size == 0) /* handle degenerate case */
2775 first_bit = base >> DEV_BSHIFT;
2776 last_bit = (base + size - 1) >> DEV_BSHIFT;
2778 return (((vm_page_bits_t)2 << last_bit) -
2779 ((vm_page_bits_t)1 << first_bit));
2783 * vm_page_set_valid_range:
2785 * Sets portions of a page valid. The arguments are expected
2786 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2787 * of any partial chunks touched by the range. The invalid portion of
2788 * such chunks will be zeroed.
2790 * (base + size) must be less then or equal to PAGE_SIZE.
2793 vm_page_set_valid_range(vm_page_t m, int base, int size)
2797 VM_OBJECT_ASSERT_WLOCKED(m->object);
2798 if (size == 0) /* handle degenerate case */
2802 * If the base is not DEV_BSIZE aligned and the valid
2803 * bit is clear, we have to zero out a portion of the
2806 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2807 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2808 pmap_zero_page_area(m, frag, base - frag);
2811 * If the ending offset is not DEV_BSIZE aligned and the
2812 * valid bit is clear, we have to zero out a portion of
2815 endoff = base + size;
2816 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2817 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2818 pmap_zero_page_area(m, endoff,
2819 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2822 * Assert that no previously invalid block that is now being validated
2825 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
2826 ("vm_page_set_valid_range: page %p is dirty", m));
2829 * Set valid bits inclusive of any overlap.
2831 m->valid |= vm_page_bits(base, size);
2835 * Clear the given bits from the specified page's dirty field.
2837 static __inline void
2838 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
2841 #if PAGE_SIZE < 16384
2846 * If the object is locked and the page is neither exclusive busy nor
2847 * write mapped, then the page's dirty field cannot possibly be
2848 * set by a concurrent pmap operation.
2850 VM_OBJECT_ASSERT_WLOCKED(m->object);
2851 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
2852 m->dirty &= ~pagebits;
2855 * The pmap layer can call vm_page_dirty() without
2856 * holding a distinguished lock. The combination of
2857 * the object's lock and an atomic operation suffice
2858 * to guarantee consistency of the page dirty field.
2860 * For PAGE_SIZE == 32768 case, compiler already
2861 * properly aligns the dirty field, so no forcible
2862 * alignment is needed. Only require existence of
2863 * atomic_clear_64 when page size is 32768.
2865 addr = (uintptr_t)&m->dirty;
2866 #if PAGE_SIZE == 32768
2867 atomic_clear_64((uint64_t *)addr, pagebits);
2868 #elif PAGE_SIZE == 16384
2869 atomic_clear_32((uint32_t *)addr, pagebits);
2870 #else /* PAGE_SIZE <= 8192 */
2872 * Use a trick to perform a 32-bit atomic on the
2873 * containing aligned word, to not depend on the existence
2874 * of atomic_clear_{8, 16}.
2876 shift = addr & (sizeof(uint32_t) - 1);
2877 #if BYTE_ORDER == BIG_ENDIAN
2878 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
2882 addr &= ~(sizeof(uint32_t) - 1);
2883 atomic_clear_32((uint32_t *)addr, pagebits << shift);
2884 #endif /* PAGE_SIZE */
2889 * vm_page_set_validclean:
2891 * Sets portions of a page valid and clean. The arguments are expected
2892 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2893 * of any partial chunks touched by the range. The invalid portion of
2894 * such chunks will be zero'd.
2896 * (base + size) must be less then or equal to PAGE_SIZE.
2899 vm_page_set_validclean(vm_page_t m, int base, int size)
2901 vm_page_bits_t oldvalid, pagebits;
2904 VM_OBJECT_ASSERT_WLOCKED(m->object);
2905 if (size == 0) /* handle degenerate case */
2909 * If the base is not DEV_BSIZE aligned and the valid
2910 * bit is clear, we have to zero out a portion of the
2913 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2914 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
2915 pmap_zero_page_area(m, frag, base - frag);
2918 * If the ending offset is not DEV_BSIZE aligned and the
2919 * valid bit is clear, we have to zero out a portion of
2922 endoff = base + size;
2923 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2924 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
2925 pmap_zero_page_area(m, endoff,
2926 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2929 * Set valid, clear dirty bits. If validating the entire
2930 * page we can safely clear the pmap modify bit. We also
2931 * use this opportunity to clear the VPO_NOSYNC flag. If a process
2932 * takes a write fault on a MAP_NOSYNC memory area the flag will
2935 * We set valid bits inclusive of any overlap, but we can only
2936 * clear dirty bits for DEV_BSIZE chunks that are fully within
2939 oldvalid = m->valid;
2940 pagebits = vm_page_bits(base, size);
2941 m->valid |= pagebits;
2943 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
2944 frag = DEV_BSIZE - frag;
2950 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
2952 if (base == 0 && size == PAGE_SIZE) {
2954 * The page can only be modified within the pmap if it is
2955 * mapped, and it can only be mapped if it was previously
2958 if (oldvalid == VM_PAGE_BITS_ALL)
2960 * Perform the pmap_clear_modify() first. Otherwise,
2961 * a concurrent pmap operation, such as
2962 * pmap_protect(), could clear a modification in the
2963 * pmap and set the dirty field on the page before
2964 * pmap_clear_modify() had begun and after the dirty
2965 * field was cleared here.
2967 pmap_clear_modify(m);
2969 m->oflags &= ~VPO_NOSYNC;
2970 } else if (oldvalid != VM_PAGE_BITS_ALL)
2971 m->dirty &= ~pagebits;
2973 vm_page_clear_dirty_mask(m, pagebits);
2977 vm_page_clear_dirty(vm_page_t m, int base, int size)
2980 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
2984 * vm_page_set_invalid:
2986 * Invalidates DEV_BSIZE'd chunks within a page. Both the
2987 * valid and dirty bits for the effected areas are cleared.
2990 vm_page_set_invalid(vm_page_t m, int base, int size)
2992 vm_page_bits_t bits;
2996 VM_OBJECT_ASSERT_WLOCKED(object);
2997 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
2998 size >= object->un_pager.vnp.vnp_size)
2999 bits = VM_PAGE_BITS_ALL;
3001 bits = vm_page_bits(base, size);
3002 if (m->valid == VM_PAGE_BITS_ALL && bits != 0)
3004 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3005 !pmap_page_is_mapped(m),
3006 ("vm_page_set_invalid: page %p is mapped", m));
3012 * vm_page_zero_invalid()
3014 * The kernel assumes that the invalid portions of a page contain
3015 * garbage, but such pages can be mapped into memory by user code.
3016 * When this occurs, we must zero out the non-valid portions of the
3017 * page so user code sees what it expects.
3019 * Pages are most often semi-valid when the end of a file is mapped
3020 * into memory and the file's size is not page aligned.
3023 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3028 VM_OBJECT_ASSERT_WLOCKED(m->object);
3030 * Scan the valid bits looking for invalid sections that
3031 * must be zerod. Invalid sub-DEV_BSIZE'd areas ( where the
3032 * valid bit may be set ) have already been zerod by
3033 * vm_page_set_validclean().
3035 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3036 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3037 (m->valid & ((vm_page_bits_t)1 << i))) {
3039 pmap_zero_page_area(m,
3040 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3047 * setvalid is TRUE when we can safely set the zero'd areas
3048 * as being valid. We can do this if there are no cache consistancy
3049 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3052 m->valid = VM_PAGE_BITS_ALL;
3058 * Is (partial) page valid? Note that the case where size == 0
3059 * will return FALSE in the degenerate case where the page is
3060 * entirely invalid, and TRUE otherwise.
3063 vm_page_is_valid(vm_page_t m, int base, int size)
3065 vm_page_bits_t bits;
3067 VM_OBJECT_ASSERT_LOCKED(m->object);
3068 bits = vm_page_bits(base, size);
3069 return (m->valid != 0 && (m->valid & bits) == bits);
3073 * vm_page_ps_is_valid:
3075 * Returns TRUE if the entire (super)page is valid and FALSE otherwise.
3078 vm_page_ps_is_valid(vm_page_t m)
3082 VM_OBJECT_ASSERT_LOCKED(m->object);
3083 npages = atop(pagesizes[m->psind]);
3086 * The physically contiguous pages that make up a superpage, i.e., a
3087 * page with a page size index ("psind") greater than zero, will
3088 * occupy adjacent entries in vm_page_array[].
3090 for (i = 0; i < npages; i++) {
3091 if (m[i].valid != VM_PAGE_BITS_ALL)
3098 * Set the page's dirty bits if the page is modified.
3101 vm_page_test_dirty(vm_page_t m)
3104 VM_OBJECT_ASSERT_WLOCKED(m->object);
3105 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3110 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3113 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3117 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3120 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3124 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3127 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3130 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3132 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3135 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3139 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3142 mtx_assert_(vm_page_lockptr(m), a, file, line);
3148 vm_page_object_lock_assert(vm_page_t m)
3152 * Certain of the page's fields may only be modified by the
3153 * holder of the containing object's lock or the exclusive busy.
3154 * holder. Unfortunately, the holder of the write busy is
3155 * not recorded, and thus cannot be checked here.
3157 if (m->object != NULL && !vm_page_xbusied(m))
3158 VM_OBJECT_ASSERT_WLOCKED(m->object);
3162 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3165 if ((bits & PGA_WRITEABLE) == 0)
3169 * The PGA_WRITEABLE flag can only be set if the page is
3170 * managed, is exclusively busied or the object is locked.
3171 * Currently, this flag is only set by pmap_enter().
3173 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3174 ("PGA_WRITEABLE on unmanaged page"));
3175 if (!vm_page_xbusied(m))
3176 VM_OBJECT_ASSERT_LOCKED(m->object);
3180 #include "opt_ddb.h"
3182 #include <sys/kernel.h>
3184 #include <ddb/ddb.h>
3186 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3188 db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
3189 db_printf("vm_cnt.v_cache_count: %d\n", vm_cnt.v_cache_count);
3190 db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
3191 db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
3192 db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
3193 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
3194 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
3195 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
3196 db_printf("vm_cnt.v_cache_min: %d\n", vm_cnt.v_cache_min);
3197 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
3200 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3204 db_printf("pq_free %d pq_cache %d\n",
3205 vm_cnt.v_free_count, vm_cnt.v_cache_count);
3206 for (dom = 0; dom < vm_ndomains; dom++) {
3208 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pass %d\n",
3210 vm_dom[dom].vmd_page_count,
3211 vm_dom[dom].vmd_free_count,
3212 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3213 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
3214 vm_dom[dom].vmd_pass);
3218 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3224 db_printf("show pginfo addr\n");
3228 phys = strchr(modif, 'p') != NULL;
3230 m = PHYS_TO_VM_PAGE(addr);
3232 m = (vm_page_t)addr;
3234 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3235 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3236 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3237 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3238 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);