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 TUNABLE_INT("vm.boot_pages", &boot_pages);
138 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RD, &boot_pages, 0,
139 "number of pages allocated for bootstrapping the VM system");
141 static int pa_tryrelock_restart;
142 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
143 &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
145 static uma_zone_t fakepg_zone;
147 static struct vnode *vm_page_alloc_init(vm_page_t m);
148 static void vm_page_cache_turn_free(vm_page_t m);
149 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
150 static void vm_page_enqueue(int queue, vm_page_t m);
151 static void vm_page_init_fakepg(void *dummy);
152 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
153 vm_pindex_t pindex, vm_page_t mpred);
154 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
157 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init_fakepg, NULL);
160 vm_page_init_fakepg(void *dummy)
163 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
164 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
167 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
168 #if PAGE_SIZE == 32768
170 CTASSERT(sizeof(u_long) >= 8);
175 * Try to acquire a physical address lock while a pmap is locked. If we
176 * fail to trylock we unlock and lock the pmap directly and cache the
177 * locked pa in *locked. The caller should then restart their loop in case
178 * the virtual to physical mapping has changed.
181 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
188 PA_LOCK_ASSERT(lockpa, MA_OWNED);
189 if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
196 atomic_add_int(&pa_tryrelock_restart, 1);
205 * Sets the page size, perhaps based upon the memory
206 * size. Must be called before any use of page-size
207 * dependent functions.
210 vm_set_page_size(void)
212 if (cnt.v_page_size == 0)
213 cnt.v_page_size = PAGE_SIZE;
214 if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0)
215 panic("vm_set_page_size: page size not a power of two");
219 * vm_page_blacklist_lookup:
221 * See if a physical address in this page has been listed
222 * in the blacklist tunable. Entries in the tunable are
223 * separated by spaces or commas. If an invalid integer is
224 * encountered then the rest of the string is skipped.
227 vm_page_blacklist_lookup(char *list, vm_paddr_t pa)
232 for (pos = list; *pos != '\0'; pos = cp) {
233 bad = strtoq(pos, &cp, 0);
235 if (*cp == ' ' || *cp == ',') {
242 if (pa == trunc_page(bad))
249 vm_page_domain_init(struct vm_domain *vmd)
251 struct vm_pagequeue *pq;
254 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
255 "vm inactive pagequeue";
256 *__DECONST(int **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_vcnt) =
257 &cnt.v_inactive_count;
258 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
259 "vm active pagequeue";
260 *__DECONST(int **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_vcnt) =
262 vmd->vmd_page_count = 0;
263 vmd->vmd_free_count = 0;
265 vmd->vmd_oom = FALSE;
267 for (i = 0; i < PQ_COUNT; i++) {
268 pq = &vmd->vmd_pagequeues[i];
269 TAILQ_INIT(&pq->pq_pl);
270 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
271 MTX_DEF | MTX_DUPOK);
278 * Initializes the resident memory module.
280 * Allocates memory for the page cells, and
281 * for the object/offset-to-page hash table headers.
282 * Each page cell is initialized and placed on the free list.
285 vm_page_startup(vm_offset_t vaddr)
288 vm_paddr_t page_range;
295 /* the biggest memory array is the second group of pages */
297 vm_paddr_t biggestsize;
298 vm_paddr_t low_water, high_water;
303 vaddr = round_page(vaddr);
305 for (i = 0; phys_avail[i + 1]; i += 2) {
306 phys_avail[i] = round_page(phys_avail[i]);
307 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
312 * There is no obvious reason why i386 PV Xen needs vm_page structs
313 * created for these pseudo-physical addresses. XXX
315 vm_phys_add_seg(0, phys_avail[0]);
318 low_water = phys_avail[0];
319 high_water = phys_avail[1];
321 for (i = 0; i < vm_phys_nsegs; i++) {
322 if (vm_phys_segs[i].start < low_water)
323 low_water = vm_phys_segs[i].start;
324 if (vm_phys_segs[i].end > high_water)
325 high_water = vm_phys_segs[i].end;
327 for (i = 0; phys_avail[i + 1]; i += 2) {
328 vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
330 if (size > biggestsize) {
334 if (phys_avail[i] < low_water)
335 low_water = phys_avail[i];
336 if (phys_avail[i + 1] > high_water)
337 high_water = phys_avail[i + 1];
340 end = phys_avail[biggestone+1];
343 * Initialize the page and queue locks.
345 mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
346 for (i = 0; i < PA_LOCK_COUNT; i++)
347 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
348 for (i = 0; i < vm_ndomains; i++)
349 vm_page_domain_init(&vm_dom[i]);
352 * Allocate memory for use when boot strapping the kernel memory
355 new_end = end - (boot_pages * UMA_SLAB_SIZE);
356 new_end = trunc_page(new_end);
357 mapped = pmap_map(&vaddr, new_end, end,
358 VM_PROT_READ | VM_PROT_WRITE);
359 bzero((void *)mapped, end - new_end);
360 uma_startup((void *)mapped, boot_pages);
362 #if defined(__amd64__) || defined(__i386__) || defined(__arm__) || \
365 * Allocate a bitmap to indicate that a random physical page
366 * needs to be included in a minidump.
368 * The amd64 port needs this to indicate which direct map pages
369 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
371 * However, i386 still needs this workspace internally within the
372 * minidump code. In theory, they are not needed on i386, but are
373 * included should the sf_buf code decide to use them.
376 for (i = 0; dump_avail[i + 1] != 0; i += 2)
377 if (dump_avail[i + 1] > last_pa)
378 last_pa = dump_avail[i + 1];
379 page_range = last_pa / PAGE_SIZE;
380 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
381 new_end -= vm_page_dump_size;
382 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
383 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
384 bzero((void *)vm_page_dump, vm_page_dump_size);
388 * Request that the physical pages underlying the message buffer be
389 * included in a crash dump. Since the message buffer is accessed
390 * through the direct map, they are not automatically included.
392 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
393 last_pa = pa + round_page(msgbufsize);
394 while (pa < last_pa) {
400 * Compute the number of pages of memory that will be available for
401 * use (taking into account the overhead of a page structure per
404 first_page = low_water / PAGE_SIZE;
405 #ifdef VM_PHYSSEG_SPARSE
407 for (i = 0; i < vm_phys_nsegs; i++) {
408 page_range += atop(vm_phys_segs[i].end -
409 vm_phys_segs[i].start);
411 for (i = 0; phys_avail[i + 1] != 0; i += 2)
412 page_range += atop(phys_avail[i + 1] - phys_avail[i]);
413 #elif defined(VM_PHYSSEG_DENSE)
414 page_range = high_water / PAGE_SIZE - first_page;
416 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
421 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
426 * Initialize the mem entry structures now, and put them in the free
429 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
430 mapped = pmap_map(&vaddr, new_end, end,
431 VM_PROT_READ | VM_PROT_WRITE);
432 vm_page_array = (vm_page_t) mapped;
433 #if VM_NRESERVLEVEL > 0
435 * Allocate memory for the reservation management system's data
438 new_end = vm_reserv_startup(&vaddr, new_end, high_water);
440 #if defined(__amd64__) || defined(__mips__)
442 * pmap_map on amd64 and mips can come out of the direct-map, not kvm
443 * like i386, so the pages must be tracked for a crashdump to include
444 * this data. This includes the vm_page_array and the early UMA
447 for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
450 phys_avail[biggestone + 1] = new_end;
453 * Add physical memory segments corresponding to the available
456 for (i = 0; phys_avail[i + 1] != 0; i += 2)
457 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
460 * Clear all of the page structures
462 bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
463 for (i = 0; i < page_range; i++)
464 vm_page_array[i].order = VM_NFREEORDER;
465 vm_page_array_size = page_range;
468 * Initialize the physical memory allocator.
473 * Add every available physical page that is not blacklisted to
476 cnt.v_page_count = 0;
477 cnt.v_free_count = 0;
478 list = getenv("vm.blacklist");
479 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
481 last_pa = phys_avail[i + 1];
482 while (pa < last_pa) {
484 vm_page_blacklist_lookup(list, pa))
485 printf("Skipping page with pa 0x%jx\n",
488 vm_phys_add_page(pa);
493 #if VM_NRESERVLEVEL > 0
495 * Initialize the reservation management system.
503 vm_page_reference(vm_page_t m)
506 vm_page_aflag_set(m, PGA_REFERENCED);
510 * vm_page_busy_downgrade:
512 * Downgrade an exclusive busy page into a single shared busy page.
515 vm_page_busy_downgrade(vm_page_t m)
519 vm_page_assert_xbusied(m);
523 x &= VPB_BIT_WAITERS;
524 if (atomic_cmpset_rel_int(&m->busy_lock,
525 VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1) | x))
533 * Return a positive value if the page is shared busied, 0 otherwise.
536 vm_page_sbusied(vm_page_t m)
541 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
547 * Shared unbusy a page.
550 vm_page_sunbusy(vm_page_t m)
554 vm_page_assert_sbusied(m);
558 if (VPB_SHARERS(x) > 1) {
559 if (atomic_cmpset_int(&m->busy_lock, x,
564 if ((x & VPB_BIT_WAITERS) == 0) {
565 KASSERT(x == VPB_SHARERS_WORD(1),
566 ("vm_page_sunbusy: invalid lock state"));
567 if (atomic_cmpset_int(&m->busy_lock,
568 VPB_SHARERS_WORD(1), VPB_UNBUSIED))
572 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
573 ("vm_page_sunbusy: invalid lock state for waiters"));
576 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
587 * vm_page_busy_sleep:
589 * Sleep and release the page lock, using the page pointer as wchan.
590 * This is used to implement the hard-path of busying mechanism.
592 * The given page must be locked.
595 vm_page_busy_sleep(vm_page_t m, const char *wmesg)
599 vm_page_lock_assert(m, MA_OWNED);
602 if (x == VPB_UNBUSIED) {
606 if ((x & VPB_BIT_WAITERS) == 0 &&
607 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS)) {
611 msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
617 * Try to shared busy a page.
618 * If the operation succeeds 1 is returned otherwise 0.
619 * The operation never sleeps.
622 vm_page_trysbusy(vm_page_t m)
628 if ((x & VPB_BIT_SHARED) == 0)
630 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
636 * vm_page_xunbusy_hard:
638 * Called after the first try the exclusive unbusy of a page failed.
639 * It is assumed that the waiters bit is on.
642 vm_page_xunbusy_hard(vm_page_t m)
645 vm_page_assert_xbusied(m);
648 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
656 * Wakeup anyone waiting for the page.
657 * The ownership bits do not change.
659 * The given page must be locked.
662 vm_page_flash(vm_page_t m)
666 vm_page_lock_assert(m, MA_OWNED);
670 if ((x & VPB_BIT_WAITERS) == 0)
672 if (atomic_cmpset_int(&m->busy_lock, x,
673 x & (~VPB_BIT_WAITERS)))
680 * Keep page from being freed by the page daemon
681 * much of the same effect as wiring, except much lower
682 * overhead and should be used only for *very* temporary
683 * holding ("wiring").
686 vm_page_hold(vm_page_t mem)
689 vm_page_lock_assert(mem, MA_OWNED);
694 vm_page_unhold(vm_page_t mem)
697 vm_page_lock_assert(mem, MA_OWNED);
698 KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
700 if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
701 vm_page_free_toq(mem);
705 * vm_page_unhold_pages:
707 * Unhold each of the pages that is referenced by the given array.
710 vm_page_unhold_pages(vm_page_t *ma, int count)
712 struct mtx *mtx, *new_mtx;
715 for (; count != 0; count--) {
717 * Avoid releasing and reacquiring the same page lock.
719 new_mtx = vm_page_lockptr(*ma);
720 if (mtx != new_mtx) {
734 PHYS_TO_VM_PAGE(vm_paddr_t pa)
738 #ifdef VM_PHYSSEG_SPARSE
739 m = vm_phys_paddr_to_vm_page(pa);
741 m = vm_phys_fictitious_to_vm_page(pa);
743 #elif defined(VM_PHYSSEG_DENSE)
747 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
748 m = &vm_page_array[pi - first_page];
751 return (vm_phys_fictitious_to_vm_page(pa));
753 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
760 * Create a fictitious page with the specified physical address and
761 * memory attribute. The memory attribute is the only the machine-
762 * dependent aspect of a fictitious page that must be initialized.
765 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
769 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
770 vm_page_initfake(m, paddr, memattr);
775 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
778 if ((m->flags & PG_FICTITIOUS) != 0) {
780 * The page's memattr might have changed since the
781 * previous initialization. Update the pmap to the
786 m->phys_addr = paddr;
788 /* Fictitious pages don't use "segind". */
789 m->flags = PG_FICTITIOUS;
790 /* Fictitious pages don't use "order" or "pool". */
791 m->oflags = VPO_UNMANAGED;
792 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
796 pmap_page_set_memattr(m, memattr);
802 * Release a fictitious page.
805 vm_page_putfake(vm_page_t m)
808 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
809 KASSERT((m->flags & PG_FICTITIOUS) != 0,
810 ("vm_page_putfake: bad page %p", m));
811 uma_zfree(fakepg_zone, m);
815 * vm_page_updatefake:
817 * Update the given fictitious page to the specified physical address and
821 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
824 KASSERT((m->flags & PG_FICTITIOUS) != 0,
825 ("vm_page_updatefake: bad page %p", m));
826 m->phys_addr = paddr;
827 pmap_page_set_memattr(m, memattr);
836 vm_page_free(vm_page_t m)
839 m->flags &= ~PG_ZERO;
846 * Free a page to the zerod-pages queue
849 vm_page_free_zero(vm_page_t m)
857 * Unbusy and handle the page queueing for a page from the VOP_GETPAGES()
858 * array which is not the request page.
861 vm_page_readahead_finish(vm_page_t m)
866 * Since the page is not the requested page, whether
867 * it should be activated or deactivated is not
868 * obvious. Empirical results have shown that
869 * deactivating the page is usually the best choice,
870 * unless the page is wanted by another thread.
873 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
876 vm_page_deactivate(m);
881 * Free the completely invalid page. Such page state
882 * occurs due to the short read operation which did
883 * not covered our page at all, or in case when a read
893 * vm_page_sleep_if_busy:
895 * Sleep and release the page queues lock if the page is busied.
896 * Returns TRUE if the thread slept.
898 * The given page must be unlocked and object containing it must
902 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
906 vm_page_lock_assert(m, MA_NOTOWNED);
907 VM_OBJECT_ASSERT_WLOCKED(m->object);
909 if (vm_page_busied(m)) {
911 * The page-specific object must be cached because page
912 * identity can change during the sleep, causing the
913 * re-lock of a different object.
914 * It is assumed that a reference to the object is already
915 * held by the callers.
919 VM_OBJECT_WUNLOCK(obj);
920 vm_page_busy_sleep(m, msg);
921 VM_OBJECT_WLOCK(obj);
928 * vm_page_dirty_KBI: [ internal use only ]
930 * Set all bits in the page's dirty field.
932 * The object containing the specified page must be locked if the
933 * call is made from the machine-independent layer.
935 * See vm_page_clear_dirty_mask().
937 * This function should only be called by vm_page_dirty().
940 vm_page_dirty_KBI(vm_page_t m)
943 /* These assertions refer to this operation by its public name. */
944 KASSERT((m->flags & PG_CACHED) == 0,
945 ("vm_page_dirty: page in cache!"));
946 KASSERT(!VM_PAGE_IS_FREE(m),
947 ("vm_page_dirty: page is free!"));
948 KASSERT(m->valid == VM_PAGE_BITS_ALL,
949 ("vm_page_dirty: page is invalid!"));
950 m->dirty = VM_PAGE_BITS_ALL;
954 * vm_page_insert: [ internal use only ]
956 * Inserts the given mem entry into the object and object list.
958 * The object must be locked.
961 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
965 VM_OBJECT_ASSERT_WLOCKED(object);
966 mpred = vm_radix_lookup_le(&object->rtree, pindex);
967 return (vm_page_insert_after(m, object, pindex, mpred));
971 * vm_page_insert_after:
973 * Inserts the page "m" into the specified object at offset "pindex".
975 * The page "mpred" must immediately precede the offset "pindex" within
976 * the specified object.
978 * The object must be locked.
981 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
988 VM_OBJECT_ASSERT_WLOCKED(object);
989 KASSERT(m->object == NULL,
990 ("vm_page_insert_after: page already inserted"));
992 KASSERT(mpred->object == object,
993 ("vm_page_insert_after: object doesn't contain mpred"));
994 KASSERT(mpred->pindex < pindex,
995 ("vm_page_insert_after: mpred doesn't precede pindex"));
996 msucc = TAILQ_NEXT(mpred, listq);
998 msucc = TAILQ_FIRST(&object->memq);
1000 KASSERT(msucc->pindex > pindex,
1001 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1004 * Record the object/offset pair in this page
1012 * Now link into the object's ordered list of backed pages.
1014 if (vm_radix_insert(&object->rtree, m)) {
1019 vm_page_insert_radixdone(m, object, mpred);
1024 * vm_page_insert_radixdone:
1026 * Complete page "m" insertion into the specified object after the
1027 * radix trie hooking.
1029 * The page "mpred" must precede the offset "m->pindex" within the
1032 * The object must be locked.
1035 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1038 VM_OBJECT_ASSERT_WLOCKED(object);
1039 KASSERT(object != NULL && m->object == object,
1040 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1041 if (mpred != NULL) {
1042 KASSERT(mpred->object == object,
1043 ("vm_page_insert_after: object doesn't contain mpred"));
1044 KASSERT(mpred->pindex < m->pindex,
1045 ("vm_page_insert_after: mpred doesn't precede pindex"));
1049 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1051 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1054 * Show that the object has one more resident page.
1056 object->resident_page_count++;
1059 * Hold the vnode until the last page is released.
1061 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1062 vhold(object->handle);
1065 * Since we are inserting a new and possibly dirty page,
1066 * update the object's OBJ_MIGHTBEDIRTY flag.
1068 if (pmap_page_is_write_mapped(m))
1069 vm_object_set_writeable_dirty(object);
1075 * Removes the given mem entry from the object/offset-page
1076 * table and the object page list, but do not invalidate/terminate
1077 * the backing store.
1079 * The object must be locked. The page must be locked if it is managed.
1082 vm_page_remove(vm_page_t m)
1087 if ((m->oflags & VPO_UNMANAGED) == 0)
1088 vm_page_lock_assert(m, MA_OWNED);
1089 if ((object = m->object) == NULL)
1091 VM_OBJECT_ASSERT_WLOCKED(object);
1092 if (vm_page_xbusied(m)) {
1094 if ((m->oflags & VPO_UNMANAGED) != 0 &&
1095 !mtx_owned(vm_page_lockptr(m))) {
1100 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1106 * Now remove from the object's list of backed pages.
1108 vm_radix_remove(&object->rtree, m->pindex);
1109 TAILQ_REMOVE(&object->memq, m, listq);
1112 * And show that the object has one fewer resident page.
1114 object->resident_page_count--;
1117 * The vnode may now be recycled.
1119 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1120 vdrop(object->handle);
1128 * Returns the page associated with the object/offset
1129 * pair specified; if none is found, NULL is returned.
1131 * The object must be locked.
1134 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1137 VM_OBJECT_ASSERT_LOCKED(object);
1138 return (vm_radix_lookup(&object->rtree, pindex));
1142 * vm_page_find_least:
1144 * Returns the page associated with the object with least pindex
1145 * greater than or equal to the parameter pindex, or NULL.
1147 * The object must be locked.
1150 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1154 VM_OBJECT_ASSERT_LOCKED(object);
1155 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1156 m = vm_radix_lookup_ge(&object->rtree, pindex);
1161 * Returns the given page's successor (by pindex) within the object if it is
1162 * resident; if none is found, NULL is returned.
1164 * The object must be locked.
1167 vm_page_next(vm_page_t m)
1171 VM_OBJECT_ASSERT_WLOCKED(m->object);
1172 if ((next = TAILQ_NEXT(m, listq)) != NULL &&
1173 next->pindex != m->pindex + 1)
1179 * Returns the given page's predecessor (by pindex) within the object if it is
1180 * resident; if none is found, NULL is returned.
1182 * The object must be locked.
1185 vm_page_prev(vm_page_t m)
1189 VM_OBJECT_ASSERT_WLOCKED(m->object);
1190 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
1191 prev->pindex != m->pindex - 1)
1197 * Uses the page mnew as a replacement for an existing page at index
1198 * pindex which must be already present in the object.
1200 * The existing page must not be on a paging queue.
1203 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1205 vm_page_t mold, mpred;
1207 VM_OBJECT_ASSERT_WLOCKED(object);
1210 * This function mostly follows vm_page_insert() and
1211 * vm_page_remove() without the radix, object count and vnode
1212 * dance. Double check such functions for more comments.
1214 mpred = vm_radix_lookup(&object->rtree, pindex);
1215 KASSERT(mpred != NULL,
1216 ("vm_page_replace: replacing page not present with pindex"));
1217 mpred = TAILQ_PREV(mpred, respgs, listq);
1219 KASSERT(mpred->pindex < pindex,
1220 ("vm_page_insert_after: mpred doesn't precede pindex"));
1222 mnew->object = object;
1223 mnew->pindex = pindex;
1224 mold = vm_radix_replace(&object->rtree, mnew);
1225 KASSERT(mold->queue == PQ_NONE,
1226 ("vm_page_replace: mold is on a paging queue"));
1228 /* Detach the old page from the resident tailq. */
1229 TAILQ_REMOVE(&object->memq, mold, listq);
1231 mold->object = NULL;
1232 vm_page_xunbusy(mold);
1234 /* Insert the new page in the resident tailq. */
1236 TAILQ_INSERT_AFTER(&object->memq, mpred, mnew, listq);
1238 TAILQ_INSERT_HEAD(&object->memq, mnew, listq);
1239 if (pmap_page_is_write_mapped(mnew))
1240 vm_object_set_writeable_dirty(object);
1247 * Move the given memory entry from its
1248 * current object to the specified target object/offset.
1250 * Note: swap associated with the page must be invalidated by the move. We
1251 * have to do this for several reasons: (1) we aren't freeing the
1252 * page, (2) we are dirtying the page, (3) the VM system is probably
1253 * moving the page from object A to B, and will then later move
1254 * the backing store from A to B and we can't have a conflict.
1256 * Note: we *always* dirty the page. It is necessary both for the
1257 * fact that we moved it, and because we may be invalidating
1258 * swap. If the page is on the cache, we have to deactivate it
1259 * or vm_page_dirty() will panic. Dirty pages are not allowed
1262 * The objects must be locked.
1265 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1270 VM_OBJECT_ASSERT_WLOCKED(new_object);
1272 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1273 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1274 ("vm_page_rename: pindex already renamed"));
1277 * Create a custom version of vm_page_insert() which does not depend
1278 * by m_prev and can cheat on the implementation aspects of the
1282 m->pindex = new_pindex;
1283 if (vm_radix_insert(&new_object->rtree, m)) {
1289 * The operation cannot fail anymore. The removal must happen before
1290 * the listq iterator is tainted.
1296 /* Return back to the new pindex to complete vm_page_insert(). */
1297 m->pindex = new_pindex;
1298 m->object = new_object;
1300 vm_page_insert_radixdone(m, new_object, mpred);
1306 * Convert all of the given object's cached pages that have a
1307 * pindex within the given range into free pages. If the value
1308 * zero is given for "end", then the range's upper bound is
1309 * infinity. If the given object is backed by a vnode and it
1310 * transitions from having one or more cached pages to none, the
1311 * vnode's hold count is reduced.
1314 vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1319 mtx_lock(&vm_page_queue_free_mtx);
1320 if (__predict_false(vm_radix_is_empty(&object->cache))) {
1321 mtx_unlock(&vm_page_queue_free_mtx);
1324 while ((m = vm_radix_lookup_ge(&object->cache, start)) != NULL) {
1325 if (end != 0 && m->pindex >= end)
1327 vm_radix_remove(&object->cache, m->pindex);
1328 vm_page_cache_turn_free(m);
1330 empty = vm_radix_is_empty(&object->cache);
1331 mtx_unlock(&vm_page_queue_free_mtx);
1332 if (object->type == OBJT_VNODE && empty)
1333 vdrop(object->handle);
1337 * Returns the cached page that is associated with the given
1338 * object and offset. If, however, none exists, returns NULL.
1340 * The free page queue must be locked.
1342 static inline vm_page_t
1343 vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
1346 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1347 return (vm_radix_lookup(&object->cache, pindex));
1351 * Remove the given cached page from its containing object's
1352 * collection of cached pages.
1354 * The free page queue must be locked.
1357 vm_page_cache_remove(vm_page_t m)
1360 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1361 KASSERT((m->flags & PG_CACHED) != 0,
1362 ("vm_page_cache_remove: page %p is not cached", m));
1363 vm_radix_remove(&m->object->cache, m->pindex);
1365 cnt.v_cache_count--;
1369 * Transfer all of the cached pages with offset greater than or
1370 * equal to 'offidxstart' from the original object's cache to the
1371 * new object's cache. However, any cached pages with offset
1372 * greater than or equal to the new object's size are kept in the
1373 * original object. Initially, the new object's cache must be
1374 * empty. Offset 'offidxstart' in the original object must
1375 * correspond to offset zero in the new object.
1377 * The new object must be locked.
1380 vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1381 vm_object_t new_object)
1386 * Insertion into an object's collection of cached pages
1387 * requires the object to be locked. In contrast, removal does
1390 VM_OBJECT_ASSERT_WLOCKED(new_object);
1391 KASSERT(vm_radix_is_empty(&new_object->cache),
1392 ("vm_page_cache_transfer: object %p has cached pages",
1394 mtx_lock(&vm_page_queue_free_mtx);
1395 while ((m = vm_radix_lookup_ge(&orig_object->cache,
1396 offidxstart)) != NULL) {
1398 * Transfer all of the pages with offset greater than or
1399 * equal to 'offidxstart' from the original object's
1400 * cache to the new object's cache.
1402 if ((m->pindex - offidxstart) >= new_object->size)
1404 vm_radix_remove(&orig_object->cache, m->pindex);
1405 /* Update the page's object and offset. */
1406 m->object = new_object;
1407 m->pindex -= offidxstart;
1408 if (vm_radix_insert(&new_object->cache, m))
1409 vm_page_cache_turn_free(m);
1411 mtx_unlock(&vm_page_queue_free_mtx);
1415 * Returns TRUE if a cached page is associated with the given object and
1416 * offset, and FALSE otherwise.
1418 * The object must be locked.
1421 vm_page_is_cached(vm_object_t object, vm_pindex_t pindex)
1426 * Insertion into an object's collection of cached pages requires the
1427 * object to be locked. Therefore, if the object is locked and the
1428 * object's collection is empty, there is no need to acquire the free
1429 * page queues lock in order to prove that the specified page doesn't
1432 VM_OBJECT_ASSERT_WLOCKED(object);
1433 if (__predict_true(vm_object_cache_is_empty(object)))
1435 mtx_lock(&vm_page_queue_free_mtx);
1436 m = vm_page_cache_lookup(object, pindex);
1437 mtx_unlock(&vm_page_queue_free_mtx);
1444 * Allocate and return a page that is associated with the specified
1445 * object and offset pair. By default, this page is exclusive busied.
1447 * The caller must always specify an allocation class.
1449 * allocation classes:
1450 * VM_ALLOC_NORMAL normal process request
1451 * VM_ALLOC_SYSTEM system *really* needs a page
1452 * VM_ALLOC_INTERRUPT interrupt time request
1454 * optional allocation flags:
1455 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1456 * intends to allocate
1457 * VM_ALLOC_IFCACHED return page only if it is cached
1458 * VM_ALLOC_IFNOTCACHED return NULL, do not reactivate if the page
1460 * VM_ALLOC_NOBUSY do not exclusive busy the page
1461 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1462 * VM_ALLOC_NOOBJ page is not associated with an object and
1463 * should not be exclusive busy
1464 * VM_ALLOC_SBUSY shared busy the allocated page
1465 * VM_ALLOC_WIRED wire the allocated page
1466 * VM_ALLOC_ZERO prefer a zeroed page
1468 * This routine may not sleep.
1471 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1473 struct vnode *vp = NULL;
1474 vm_object_t m_object;
1476 int flags, req_class;
1478 mpred = 0; /* XXX: pacify gcc */
1479 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1480 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1481 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1482 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1483 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1486 VM_OBJECT_ASSERT_WLOCKED(object);
1488 req_class = req & VM_ALLOC_CLASS_MASK;
1491 * The page daemon is allowed to dig deeper into the free page list.
1493 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1494 req_class = VM_ALLOC_SYSTEM;
1496 if (object != NULL) {
1497 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1498 KASSERT(mpred == NULL || mpred->pindex != pindex,
1499 ("vm_page_alloc: pindex already allocated"));
1503 * The page allocation request can came from consumers which already
1504 * hold the free page queue mutex, like vm_page_insert() in
1507 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
1508 if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1509 (req_class == VM_ALLOC_SYSTEM &&
1510 cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1511 (req_class == VM_ALLOC_INTERRUPT &&
1512 cnt.v_free_count + cnt.v_cache_count > 0)) {
1514 * Allocate from the free queue if the number of free pages
1515 * exceeds the minimum for the request class.
1517 if (object != NULL &&
1518 (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1519 if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1520 mtx_unlock(&vm_page_queue_free_mtx);
1523 if (vm_phys_unfree_page(m))
1524 vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1525 #if VM_NRESERVLEVEL > 0
1526 else if (!vm_reserv_reactivate_page(m))
1530 panic("vm_page_alloc: cache page %p is missing"
1531 " from the free queue", m);
1532 } else if ((req & VM_ALLOC_IFCACHED) != 0) {
1533 mtx_unlock(&vm_page_queue_free_mtx);
1535 #if VM_NRESERVLEVEL > 0
1536 } else if (object == NULL || (object->flags & (OBJ_COLORED |
1537 OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1538 vm_reserv_alloc_page(object, pindex, mpred)) == NULL) {
1542 m = vm_phys_alloc_pages(object != NULL ?
1543 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1544 #if VM_NRESERVLEVEL > 0
1545 if (m == NULL && vm_reserv_reclaim_inactive()) {
1546 m = vm_phys_alloc_pages(object != NULL ?
1547 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1554 * Not allocatable, give up.
1556 mtx_unlock(&vm_page_queue_free_mtx);
1557 atomic_add_int(&vm_pageout_deficit,
1558 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1559 pagedaemon_wakeup();
1564 * At this point we had better have found a good page.
1566 KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1567 KASSERT(m->queue == PQ_NONE,
1568 ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1569 KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1570 KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1571 KASSERT(!vm_page_sbusied(m),
1572 ("vm_page_alloc: page %p is busy", m));
1573 KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1574 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1575 ("vm_page_alloc: page %p has unexpected memattr %d", m,
1576 pmap_page_get_memattr(m)));
1577 if ((m->flags & PG_CACHED) != 0) {
1578 KASSERT((m->flags & PG_ZERO) == 0,
1579 ("vm_page_alloc: cached page %p is PG_ZERO", m));
1580 KASSERT(m->valid != 0,
1581 ("vm_page_alloc: cached page %p is invalid", m));
1582 if (m->object == object && m->pindex == pindex)
1583 cnt.v_reactivated++;
1586 m_object = m->object;
1587 vm_page_cache_remove(m);
1588 if (m_object->type == OBJT_VNODE &&
1589 vm_object_cache_is_empty(m_object))
1590 vp = m_object->handle;
1592 KASSERT(VM_PAGE_IS_FREE(m),
1593 ("vm_page_alloc: page %p is not free", m));
1594 KASSERT(m->valid == 0,
1595 ("vm_page_alloc: free page %p is valid", m));
1596 vm_phys_freecnt_adj(m, -1);
1600 * Only the PG_ZERO flag is inherited. The PG_CACHED or PG_FREE flag
1601 * must be cleared before the free page queues lock is released.
1604 if (m->flags & PG_ZERO) {
1605 vm_page_zero_count--;
1606 if (req & VM_ALLOC_ZERO)
1609 if (req & VM_ALLOC_NODUMP)
1612 mtx_unlock(&vm_page_queue_free_mtx);
1614 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1616 m->busy_lock = VPB_UNBUSIED;
1617 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1618 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1619 if ((req & VM_ALLOC_SBUSY) != 0)
1620 m->busy_lock = VPB_SHARERS_WORD(1);
1621 if (req & VM_ALLOC_WIRED) {
1623 * The page lock is not required for wiring a page until that
1624 * page is inserted into the object.
1626 atomic_add_int(&cnt.v_wire_count, 1);
1631 if (object != NULL) {
1632 if (vm_page_insert_after(m, object, pindex, mpred)) {
1633 /* See the comment below about hold count. */
1636 pagedaemon_wakeup();
1637 if (req & VM_ALLOC_WIRED) {
1638 atomic_subtract_int(&cnt.v_wire_count, 1);
1642 m->oflags = VPO_UNMANAGED;
1647 /* Ignore device objects; the pager sets "memattr" for them. */
1648 if (object->memattr != VM_MEMATTR_DEFAULT &&
1649 (object->flags & OBJ_FICTITIOUS) == 0)
1650 pmap_page_set_memattr(m, object->memattr);
1655 * The following call to vdrop() must come after the above call
1656 * to vm_page_insert() in case both affect the same object and
1657 * vnode. Otherwise, the affected vnode's hold count could
1658 * temporarily become zero.
1664 * Don't wakeup too often - wakeup the pageout daemon when
1665 * we would be nearly out of memory.
1667 if (vm_paging_needed())
1668 pagedaemon_wakeup();
1674 vm_page_alloc_contig_vdrop(struct spglist *lst)
1677 while (!SLIST_EMPTY(lst)) {
1678 vdrop((struct vnode *)SLIST_FIRST(lst)-> plinks.s.pv);
1679 SLIST_REMOVE_HEAD(lst, plinks.s.ss);
1684 * vm_page_alloc_contig:
1686 * Allocate a contiguous set of physical pages of the given size "npages"
1687 * from the free lists. All of the physical pages must be at or above
1688 * the given physical address "low" and below the given physical address
1689 * "high". The given value "alignment" determines the alignment of the
1690 * first physical page in the set. If the given value "boundary" is
1691 * non-zero, then the set of physical pages cannot cross any physical
1692 * address boundary that is a multiple of that value. Both "alignment"
1693 * and "boundary" must be a power of two.
1695 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1696 * then the memory attribute setting for the physical pages is configured
1697 * to the object's memory attribute setting. Otherwise, the memory
1698 * attribute setting for the physical pages is configured to "memattr",
1699 * overriding the object's memory attribute setting. However, if the
1700 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1701 * memory attribute setting for the physical pages cannot be configured
1702 * to VM_MEMATTR_DEFAULT.
1704 * The caller must always specify an allocation class.
1706 * allocation classes:
1707 * VM_ALLOC_NORMAL normal process request
1708 * VM_ALLOC_SYSTEM system *really* needs a page
1709 * VM_ALLOC_INTERRUPT interrupt time request
1711 * optional allocation flags:
1712 * VM_ALLOC_NOBUSY do not exclusive busy the page
1713 * VM_ALLOC_NOOBJ page is not associated with an object and
1714 * should not be exclusive busy
1715 * VM_ALLOC_SBUSY shared busy the allocated page
1716 * VM_ALLOC_WIRED wire the allocated page
1717 * VM_ALLOC_ZERO prefer a zeroed page
1719 * This routine may not sleep.
1722 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1723 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1724 vm_paddr_t boundary, vm_memattr_t memattr)
1727 struct spglist deferred_vdrop_list;
1728 vm_page_t m, m_tmp, m_ret;
1729 u_int flags, oflags;
1732 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1733 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1734 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1735 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1736 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1738 if (object != NULL) {
1739 VM_OBJECT_ASSERT_WLOCKED(object);
1740 KASSERT(object->type == OBJT_PHYS,
1741 ("vm_page_alloc_contig: object %p isn't OBJT_PHYS",
1744 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1745 req_class = req & VM_ALLOC_CLASS_MASK;
1748 * The page daemon is allowed to dig deeper into the free page list.
1750 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1751 req_class = VM_ALLOC_SYSTEM;
1753 SLIST_INIT(&deferred_vdrop_list);
1754 mtx_lock(&vm_page_queue_free_mtx);
1755 if (cnt.v_free_count + cnt.v_cache_count >= npages +
1756 cnt.v_free_reserved || (req_class == VM_ALLOC_SYSTEM &&
1757 cnt.v_free_count + cnt.v_cache_count >= npages +
1758 cnt.v_interrupt_free_min) || (req_class == VM_ALLOC_INTERRUPT &&
1759 cnt.v_free_count + cnt.v_cache_count >= npages)) {
1760 #if VM_NRESERVLEVEL > 0
1762 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1763 (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1764 low, high, alignment, boundary)) == NULL)
1766 m_ret = vm_phys_alloc_contig(npages, low, high,
1767 alignment, boundary);
1769 mtx_unlock(&vm_page_queue_free_mtx);
1770 atomic_add_int(&vm_pageout_deficit, npages);
1771 pagedaemon_wakeup();
1775 for (m = m_ret; m < &m_ret[npages]; m++) {
1776 drop = vm_page_alloc_init(m);
1779 * Enqueue the vnode for deferred vdrop().
1781 m->plinks.s.pv = drop;
1782 SLIST_INSERT_HEAD(&deferred_vdrop_list, m,
1787 #if VM_NRESERVLEVEL > 0
1788 if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1793 mtx_unlock(&vm_page_queue_free_mtx);
1798 * Initialize the pages. Only the PG_ZERO flag is inherited.
1801 if ((req & VM_ALLOC_ZERO) != 0)
1803 if ((req & VM_ALLOC_NODUMP) != 0)
1805 if ((req & VM_ALLOC_WIRED) != 0)
1806 atomic_add_int(&cnt.v_wire_count, npages);
1807 oflags = VPO_UNMANAGED;
1808 if (object != NULL) {
1809 if (object->memattr != VM_MEMATTR_DEFAULT &&
1810 memattr == VM_MEMATTR_DEFAULT)
1811 memattr = object->memattr;
1813 for (m = m_ret; m < &m_ret[npages]; m++) {
1815 m->flags = (m->flags | PG_NODUMP) & flags;
1816 m->busy_lock = VPB_UNBUSIED;
1817 if (object != NULL) {
1818 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
1819 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1820 if ((req & VM_ALLOC_SBUSY) != 0)
1821 m->busy_lock = VPB_SHARERS_WORD(1);
1823 if ((req & VM_ALLOC_WIRED) != 0)
1825 /* Unmanaged pages don't use "act_count". */
1827 if (object != NULL) {
1828 if (vm_page_insert(m, object, pindex)) {
1829 vm_page_alloc_contig_vdrop(
1830 &deferred_vdrop_list);
1831 if (vm_paging_needed())
1832 pagedaemon_wakeup();
1833 if ((req & VM_ALLOC_WIRED) != 0)
1834 atomic_subtract_int(&cnt.v_wire_count,
1836 for (m_tmp = m, m = m_ret;
1837 m < &m_ret[npages]; m++) {
1838 if ((req & VM_ALLOC_WIRED) != 0)
1848 if (memattr != VM_MEMATTR_DEFAULT)
1849 pmap_page_set_memattr(m, memattr);
1852 vm_page_alloc_contig_vdrop(&deferred_vdrop_list);
1853 if (vm_paging_needed())
1854 pagedaemon_wakeup();
1859 * Initialize a page that has been freshly dequeued from a freelist.
1860 * The caller has to drop the vnode returned, if it is not NULL.
1862 * This function may only be used to initialize unmanaged pages.
1864 * To be called with vm_page_queue_free_mtx held.
1866 static struct vnode *
1867 vm_page_alloc_init(vm_page_t m)
1870 vm_object_t m_object;
1872 KASSERT(m->queue == PQ_NONE,
1873 ("vm_page_alloc_init: page %p has unexpected queue %d",
1875 KASSERT(m->wire_count == 0,
1876 ("vm_page_alloc_init: page %p is wired", m));
1877 KASSERT(m->hold_count == 0,
1878 ("vm_page_alloc_init: page %p is held", m));
1879 KASSERT(!vm_page_sbusied(m),
1880 ("vm_page_alloc_init: page %p is busy", m));
1881 KASSERT(m->dirty == 0,
1882 ("vm_page_alloc_init: page %p is dirty", m));
1883 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1884 ("vm_page_alloc_init: page %p has unexpected memattr %d",
1885 m, pmap_page_get_memattr(m)));
1886 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1888 if ((m->flags & PG_CACHED) != 0) {
1889 KASSERT((m->flags & PG_ZERO) == 0,
1890 ("vm_page_alloc_init: cached page %p is PG_ZERO", m));
1892 m_object = m->object;
1893 vm_page_cache_remove(m);
1894 if (m_object->type == OBJT_VNODE &&
1895 vm_object_cache_is_empty(m_object))
1896 drop = m_object->handle;
1898 KASSERT(VM_PAGE_IS_FREE(m),
1899 ("vm_page_alloc_init: page %p is not free", m));
1900 KASSERT(m->valid == 0,
1901 ("vm_page_alloc_init: free page %p is valid", m));
1902 vm_phys_freecnt_adj(m, -1);
1903 if ((m->flags & PG_ZERO) != 0)
1904 vm_page_zero_count--;
1906 /* Don't clear the PG_ZERO flag; we'll need it later. */
1907 m->flags &= PG_ZERO;
1912 * vm_page_alloc_freelist:
1914 * Allocate a physical page from the specified free page list.
1916 * The caller must always specify an allocation class.
1918 * allocation classes:
1919 * VM_ALLOC_NORMAL normal process request
1920 * VM_ALLOC_SYSTEM system *really* needs a page
1921 * VM_ALLOC_INTERRUPT interrupt time request
1923 * optional allocation flags:
1924 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1925 * intends to allocate
1926 * VM_ALLOC_WIRED wire the allocated page
1927 * VM_ALLOC_ZERO prefer a zeroed page
1929 * This routine may not sleep.
1932 vm_page_alloc_freelist(int flind, int req)
1939 req_class = req & VM_ALLOC_CLASS_MASK;
1942 * The page daemon is allowed to dig deeper into the free page list.
1944 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1945 req_class = VM_ALLOC_SYSTEM;
1948 * Do not allocate reserved pages unless the req has asked for it.
1950 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
1951 if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1952 (req_class == VM_ALLOC_SYSTEM &&
1953 cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1954 (req_class == VM_ALLOC_INTERRUPT &&
1955 cnt.v_free_count + cnt.v_cache_count > 0))
1956 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
1958 mtx_unlock(&vm_page_queue_free_mtx);
1959 atomic_add_int(&vm_pageout_deficit,
1960 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1961 pagedaemon_wakeup();
1965 mtx_unlock(&vm_page_queue_free_mtx);
1968 drop = vm_page_alloc_init(m);
1969 mtx_unlock(&vm_page_queue_free_mtx);
1972 * Initialize the page. Only the PG_ZERO flag is inherited.
1976 if ((req & VM_ALLOC_ZERO) != 0)
1979 if ((req & VM_ALLOC_WIRED) != 0) {
1981 * The page lock is not required for wiring a page that does
1982 * not belong to an object.
1984 atomic_add_int(&cnt.v_wire_count, 1);
1987 /* Unmanaged pages don't use "act_count". */
1988 m->oflags = VPO_UNMANAGED;
1991 if (vm_paging_needed())
1992 pagedaemon_wakeup();
1997 * vm_wait: (also see VM_WAIT macro)
1999 * Sleep until free pages are available for allocation.
2000 * - Called in various places before memory allocations.
2006 mtx_lock(&vm_page_queue_free_mtx);
2007 if (curproc == pageproc) {
2008 vm_pageout_pages_needed = 1;
2009 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
2010 PDROP | PSWP, "VMWait", 0);
2012 if (!vm_pages_needed) {
2013 vm_pages_needed = 1;
2014 wakeup(&vm_pages_needed);
2016 msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
2022 * vm_waitpfault: (also see VM_WAITPFAULT macro)
2024 * Sleep until free pages are available for allocation.
2025 * - Called only in vm_fault so that processes page faulting
2026 * can be easily tracked.
2027 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2028 * processes will be able to grab memory first. Do not change
2029 * this balance without careful testing first.
2035 mtx_lock(&vm_page_queue_free_mtx);
2036 if (!vm_pages_needed) {
2037 vm_pages_needed = 1;
2038 wakeup(&vm_pages_needed);
2040 msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
2044 struct vm_pagequeue *
2045 vm_page_pagequeue(vm_page_t m)
2048 return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2054 * Remove the given page from its current page queue.
2056 * The page must be locked.
2059 vm_page_dequeue(vm_page_t m)
2061 struct vm_pagequeue *pq;
2063 vm_page_lock_assert(m, MA_OWNED);
2064 KASSERT(m->queue != PQ_NONE,
2065 ("vm_page_dequeue: page %p is not queued", m));
2066 pq = vm_page_pagequeue(m);
2067 vm_pagequeue_lock(pq);
2069 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2070 vm_pagequeue_cnt_dec(pq);
2071 vm_pagequeue_unlock(pq);
2075 * vm_page_dequeue_locked:
2077 * Remove the given page from its current page queue.
2079 * The page and page queue must be locked.
2082 vm_page_dequeue_locked(vm_page_t m)
2084 struct vm_pagequeue *pq;
2086 vm_page_lock_assert(m, MA_OWNED);
2087 pq = vm_page_pagequeue(m);
2088 vm_pagequeue_assert_locked(pq);
2090 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2091 vm_pagequeue_cnt_dec(pq);
2097 * Add the given page to the specified page queue.
2099 * The page must be locked.
2102 vm_page_enqueue(int queue, vm_page_t m)
2104 struct vm_pagequeue *pq;
2106 vm_page_lock_assert(m, MA_OWNED);
2107 pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2108 vm_pagequeue_lock(pq);
2110 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2111 vm_pagequeue_cnt_inc(pq);
2112 vm_pagequeue_unlock(pq);
2118 * Move the given page to the tail of its current page queue.
2120 * The page must be locked.
2123 vm_page_requeue(vm_page_t m)
2125 struct vm_pagequeue *pq;
2127 vm_page_lock_assert(m, MA_OWNED);
2128 KASSERT(m->queue != PQ_NONE,
2129 ("vm_page_requeue: page %p is not queued", m));
2130 pq = vm_page_pagequeue(m);
2131 vm_pagequeue_lock(pq);
2132 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2133 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2134 vm_pagequeue_unlock(pq);
2138 * vm_page_requeue_locked:
2140 * Move the given page to the tail of its current page queue.
2142 * The page queue must be locked.
2145 vm_page_requeue_locked(vm_page_t m)
2147 struct vm_pagequeue *pq;
2149 KASSERT(m->queue != PQ_NONE,
2150 ("vm_page_requeue_locked: page %p is not queued", m));
2151 pq = vm_page_pagequeue(m);
2152 vm_pagequeue_assert_locked(pq);
2153 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2154 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2160 * Put the specified page on the active list (if appropriate).
2161 * Ensure that act_count is at least ACT_INIT but do not otherwise
2164 * The page must be locked.
2167 vm_page_activate(vm_page_t m)
2171 vm_page_lock_assert(m, MA_OWNED);
2172 if ((queue = m->queue) != PQ_ACTIVE) {
2173 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2174 if (m->act_count < ACT_INIT)
2175 m->act_count = ACT_INIT;
2176 if (queue != PQ_NONE)
2178 vm_page_enqueue(PQ_ACTIVE, m);
2180 KASSERT(queue == PQ_NONE,
2181 ("vm_page_activate: wired page %p is queued", m));
2183 if (m->act_count < ACT_INIT)
2184 m->act_count = ACT_INIT;
2189 * vm_page_free_wakeup:
2191 * Helper routine for vm_page_free_toq() and vm_page_cache(). This
2192 * routine is called when a page has been added to the cache or free
2195 * The page queues must be locked.
2198 vm_page_free_wakeup(void)
2201 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2203 * if pageout daemon needs pages, then tell it that there are
2206 if (vm_pageout_pages_needed &&
2207 cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
2208 wakeup(&vm_pageout_pages_needed);
2209 vm_pageout_pages_needed = 0;
2212 * wakeup processes that are waiting on memory if we hit a
2213 * high water mark. And wakeup scheduler process if we have
2214 * lots of memory. this process will swapin processes.
2216 if (vm_pages_needed && !vm_page_count_min()) {
2217 vm_pages_needed = 0;
2218 wakeup(&cnt.v_free_count);
2223 * Turn a cached page into a free page, by changing its attributes.
2224 * Keep the statistics up-to-date.
2226 * The free page queue must be locked.
2229 vm_page_cache_turn_free(vm_page_t m)
2232 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2236 /* Clear PG_CACHED and set PG_FREE. */
2237 m->flags ^= PG_CACHED | PG_FREE;
2238 KASSERT((m->flags & (PG_CACHED | PG_FREE)) == PG_FREE,
2239 ("vm_page_cache_free: page %p has inconsistent flags", m));
2240 cnt.v_cache_count--;
2241 vm_phys_freecnt_adj(m, 1);
2247 * Returns the given page to the free list,
2248 * disassociating it with any VM object.
2250 * The object must be locked. The page must be locked if it is managed.
2253 vm_page_free_toq(vm_page_t m)
2256 if ((m->oflags & VPO_UNMANAGED) == 0) {
2257 vm_page_lock_assert(m, MA_OWNED);
2258 KASSERT(!pmap_page_is_mapped(m),
2259 ("vm_page_free_toq: freeing mapped page %p", m));
2261 KASSERT(m->queue == PQ_NONE,
2262 ("vm_page_free_toq: unmanaged page %p is queued", m));
2263 PCPU_INC(cnt.v_tfree);
2265 if (VM_PAGE_IS_FREE(m))
2266 panic("vm_page_free: freeing free page %p", m);
2267 else if (vm_page_sbusied(m))
2268 panic("vm_page_free: freeing busy page %p", m);
2271 * Unqueue, then remove page. Note that we cannot destroy
2272 * the page here because we do not want to call the pager's
2273 * callback routine until after we've put the page on the
2274 * appropriate free queue.
2280 * If fictitious remove object association and
2281 * return, otherwise delay object association removal.
2283 if ((m->flags & PG_FICTITIOUS) != 0) {
2290 if (m->wire_count != 0)
2291 panic("vm_page_free: freeing wired page %p", m);
2292 if (m->hold_count != 0) {
2293 m->flags &= ~PG_ZERO;
2294 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2295 ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
2296 m->flags |= PG_UNHOLDFREE;
2299 * Restore the default memory attribute to the page.
2301 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2302 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2305 * Insert the page into the physical memory allocator's
2306 * cache/free page queues.
2308 mtx_lock(&vm_page_queue_free_mtx);
2309 m->flags |= PG_FREE;
2310 vm_phys_freecnt_adj(m, 1);
2311 #if VM_NRESERVLEVEL > 0
2312 if (!vm_reserv_free_page(m))
2316 vm_phys_free_pages(m, 0);
2317 if ((m->flags & PG_ZERO) != 0)
2318 ++vm_page_zero_count;
2320 vm_page_zero_idle_wakeup();
2321 vm_page_free_wakeup();
2322 mtx_unlock(&vm_page_queue_free_mtx);
2329 * Mark this page as wired down by yet
2330 * another map, removing it from paging queues
2333 * If the page is fictitious, then its wire count must remain one.
2335 * The page must be locked.
2338 vm_page_wire(vm_page_t m)
2342 * Only bump the wire statistics if the page is not already wired,
2343 * and only unqueue the page if it is on some queue (if it is unmanaged
2344 * it is already off the queues).
2346 vm_page_lock_assert(m, MA_OWNED);
2347 if ((m->flags & PG_FICTITIOUS) != 0) {
2348 KASSERT(m->wire_count == 1,
2349 ("vm_page_wire: fictitious page %p's wire count isn't one",
2353 if (m->wire_count == 0) {
2354 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
2355 m->queue == PQ_NONE,
2356 ("vm_page_wire: unmanaged page %p is queued", m));
2358 atomic_add_int(&cnt.v_wire_count, 1);
2361 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
2367 * Release one wiring of the specified page, potentially enabling it to be
2368 * paged again. If paging is enabled, then the value of the parameter
2369 * "activate" determines to which queue the page is added. If "activate" is
2370 * non-zero, then the page is added to the active queue. Otherwise, it is
2371 * added to the inactive queue.
2373 * However, unless the page belongs to an object, it is not enqueued because
2374 * it cannot be paged out.
2376 * If a page is fictitious, then its wire count must always be one.
2378 * A managed page must be locked.
2381 vm_page_unwire(vm_page_t m, int activate)
2384 if ((m->oflags & VPO_UNMANAGED) == 0)
2385 vm_page_lock_assert(m, MA_OWNED);
2386 if ((m->flags & PG_FICTITIOUS) != 0) {
2387 KASSERT(m->wire_count == 1,
2388 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
2391 if (m->wire_count > 0) {
2393 if (m->wire_count == 0) {
2394 atomic_subtract_int(&cnt.v_wire_count, 1);
2395 if ((m->oflags & VPO_UNMANAGED) != 0 ||
2399 m->flags &= ~PG_WINATCFLS;
2400 vm_page_enqueue(activate ? PQ_ACTIVE : PQ_INACTIVE, m);
2403 panic("vm_page_unwire: page %p's wire count is zero", m);
2407 * Move the specified page to the inactive queue.
2409 * Many pages placed on the inactive queue should actually go
2410 * into the cache, but it is difficult to figure out which. What
2411 * we do instead, if the inactive target is well met, is to put
2412 * clean pages at the head of the inactive queue instead of the tail.
2413 * This will cause them to be moved to the cache more quickly and
2414 * if not actively re-referenced, reclaimed more quickly. If we just
2415 * stick these pages at the end of the inactive queue, heavy filesystem
2416 * meta-data accesses can cause an unnecessary paging load on memory bound
2417 * processes. This optimization causes one-time-use metadata to be
2418 * reused more quickly.
2420 * Normally athead is 0 resulting in LRU operation. athead is set
2421 * to 1 if we want this page to be 'as if it were placed in the cache',
2422 * except without unmapping it from the process address space.
2424 * The page must be locked.
2427 _vm_page_deactivate(vm_page_t m, int athead)
2429 struct vm_pagequeue *pq;
2432 vm_page_lock_assert(m, MA_OWNED);
2435 * Ignore if already inactive.
2437 if ((queue = m->queue) == PQ_INACTIVE)
2439 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2440 if (queue != PQ_NONE)
2442 m->flags &= ~PG_WINATCFLS;
2443 pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
2444 vm_pagequeue_lock(pq);
2445 m->queue = PQ_INACTIVE;
2447 TAILQ_INSERT_HEAD(&pq->pq_pl, m, plinks.q);
2449 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2450 vm_pagequeue_cnt_inc(pq);
2451 vm_pagequeue_unlock(pq);
2456 * Move the specified page to the inactive queue.
2458 * The page must be locked.
2461 vm_page_deactivate(vm_page_t m)
2464 _vm_page_deactivate(m, 0);
2468 * vm_page_try_to_cache:
2470 * Returns 0 on failure, 1 on success
2473 vm_page_try_to_cache(vm_page_t m)
2476 vm_page_lock_assert(m, MA_OWNED);
2477 VM_OBJECT_ASSERT_WLOCKED(m->object);
2478 if (m->dirty || m->hold_count || m->wire_count ||
2479 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
2489 * vm_page_try_to_free()
2491 * Attempt to free the page. If we cannot free it, we do nothing.
2492 * 1 is returned on success, 0 on failure.
2495 vm_page_try_to_free(vm_page_t m)
2498 vm_page_lock_assert(m, MA_OWNED);
2499 if (m->object != NULL)
2500 VM_OBJECT_ASSERT_WLOCKED(m->object);
2501 if (m->dirty || m->hold_count || m->wire_count ||
2502 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
2514 * Put the specified page onto the page cache queue (if appropriate).
2516 * The object and page must be locked.
2519 vm_page_cache(vm_page_t m)
2522 boolean_t cache_was_empty;
2524 vm_page_lock_assert(m, MA_OWNED);
2526 VM_OBJECT_ASSERT_WLOCKED(object);
2527 if (vm_page_busied(m) || (m->oflags & VPO_UNMANAGED) ||
2528 m->hold_count || m->wire_count)
2529 panic("vm_page_cache: attempting to cache busy page");
2530 KASSERT(!pmap_page_is_mapped(m),
2531 ("vm_page_cache: page %p is mapped", m));
2532 KASSERT(m->dirty == 0, ("vm_page_cache: page %p is dirty", m));
2533 if (m->valid == 0 || object->type == OBJT_DEFAULT ||
2534 (object->type == OBJT_SWAP &&
2535 !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
2537 * Hypothesis: A cache-elgible page belonging to a
2538 * default object or swap object but without a backing
2539 * store must be zero filled.
2544 KASSERT((m->flags & PG_CACHED) == 0,
2545 ("vm_page_cache: page %p is already cached", m));
2548 * Remove the page from the paging queues.
2553 * Remove the page from the object's collection of resident
2556 vm_radix_remove(&object->rtree, m->pindex);
2557 TAILQ_REMOVE(&object->memq, m, listq);
2558 object->resident_page_count--;
2561 * Restore the default memory attribute to the page.
2563 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2564 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2567 * Insert the page into the object's collection of cached pages
2568 * and the physical memory allocator's cache/free page queues.
2570 m->flags &= ~PG_ZERO;
2571 mtx_lock(&vm_page_queue_free_mtx);
2572 cache_was_empty = vm_radix_is_empty(&object->cache);
2573 if (vm_radix_insert(&object->cache, m)) {
2574 mtx_unlock(&vm_page_queue_free_mtx);
2575 if (object->resident_page_count == 0)
2576 vdrop(object->handle);
2583 * The above call to vm_radix_insert() could reclaim the one pre-
2584 * existing cached page from this object, resulting in a call to
2587 if (!cache_was_empty)
2588 cache_was_empty = vm_radix_is_singleton(&object->cache);
2590 m->flags |= PG_CACHED;
2591 cnt.v_cache_count++;
2592 PCPU_INC(cnt.v_tcached);
2593 #if VM_NRESERVLEVEL > 0
2594 if (!vm_reserv_free_page(m)) {
2598 vm_phys_set_pool(VM_FREEPOOL_CACHE, m, 0);
2599 vm_phys_free_pages(m, 0);
2601 vm_page_free_wakeup();
2602 mtx_unlock(&vm_page_queue_free_mtx);
2605 * Increment the vnode's hold count if this is the object's only
2606 * cached page. Decrement the vnode's hold count if this was
2607 * the object's only resident page.
2609 if (object->type == OBJT_VNODE) {
2610 if (cache_was_empty && object->resident_page_count != 0)
2611 vhold(object->handle);
2612 else if (!cache_was_empty && object->resident_page_count == 0)
2613 vdrop(object->handle);
2620 * Cache, deactivate, or do nothing as appropriate. This routine
2621 * is used by madvise().
2623 * Generally speaking we want to move the page into the cache so
2624 * it gets reused quickly. However, this can result in a silly syndrome
2625 * due to the page recycling too quickly. Small objects will not be
2626 * fully cached. On the other hand, if we move the page to the inactive
2627 * queue we wind up with a problem whereby very large objects
2628 * unnecessarily blow away our inactive and cache queues.
2630 * The solution is to move the pages based on a fixed weighting. We
2631 * either leave them alone, deactivate them, or move them to the cache,
2632 * where moving them to the cache has the highest weighting.
2633 * By forcing some pages into other queues we eventually force the
2634 * system to balance the queues, potentially recovering other unrelated
2635 * space from active. The idea is to not force this to happen too
2638 * The object and page must be locked.
2641 vm_page_advise(vm_page_t m, int advice)
2645 vm_page_assert_locked(m);
2646 VM_OBJECT_ASSERT_WLOCKED(m->object);
2647 if (advice == MADV_FREE) {
2649 * Mark the page clean. This will allow the page to be freed
2650 * up by the system. However, such pages are often reused
2651 * quickly by malloc() so we do not do anything that would
2652 * cause a page fault if we can help it.
2654 * Specifically, we do not try to actually free the page now
2655 * nor do we try to put it in the cache (which would cause a
2656 * page fault on reuse).
2658 * But we do make the page is freeable as we can without
2659 * actually taking the step of unmapping it.
2663 } else if (advice != MADV_DONTNEED)
2665 dnw = PCPU_GET(dnweight);
2669 * Occasionally leave the page alone.
2671 if ((dnw & 0x01F0) == 0 || m->queue == PQ_INACTIVE) {
2672 if (m->act_count >= ACT_INIT)
2678 * Clear any references to the page. Otherwise, the page daemon will
2679 * immediately reactivate the page.
2681 vm_page_aflag_clear(m, PGA_REFERENCED);
2683 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
2686 if (m->dirty || (dnw & 0x0070) == 0) {
2688 * Deactivate the page 3 times out of 32.
2693 * Cache the page 28 times out of every 32. Note that
2694 * the page is deactivated instead of cached, but placed
2695 * at the head of the queue instead of the tail.
2699 _vm_page_deactivate(m, head);
2703 * Grab a page, waiting until we are waken up due to the page
2704 * changing state. We keep on waiting, if the page continues
2705 * to be in the object. If the page doesn't exist, first allocate it
2706 * and then conditionally zero it.
2708 * This routine may sleep.
2710 * The object must be locked on entry. The lock will, however, be released
2711 * and reacquired if the routine sleeps.
2714 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
2719 VM_OBJECT_ASSERT_WLOCKED(object);
2720 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
2721 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
2722 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
2724 if ((m = vm_page_lookup(object, pindex)) != NULL) {
2725 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
2726 vm_page_xbusied(m) : vm_page_busied(m);
2729 * Reference the page before unlocking and
2730 * sleeping so that the page daemon is less
2731 * likely to reclaim it.
2733 vm_page_aflag_set(m, PGA_REFERENCED);
2735 VM_OBJECT_WUNLOCK(object);
2736 vm_page_busy_sleep(m, "pgrbwt");
2737 VM_OBJECT_WLOCK(object);
2740 if ((allocflags & VM_ALLOC_WIRED) != 0) {
2746 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
2748 if ((allocflags & VM_ALLOC_SBUSY) != 0)
2753 m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_IGN_SBUSY);
2755 VM_OBJECT_WUNLOCK(object);
2757 VM_OBJECT_WLOCK(object);
2759 } else if (m->valid != 0)
2761 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
2767 * Mapping function for valid or dirty bits in a page.
2769 * Inputs are required to range within a page.
2772 vm_page_bits(int base, int size)
2778 base + size <= PAGE_SIZE,
2779 ("vm_page_bits: illegal base/size %d/%d", base, size)
2782 if (size == 0) /* handle degenerate case */
2785 first_bit = base >> DEV_BSHIFT;
2786 last_bit = (base + size - 1) >> DEV_BSHIFT;
2788 return (((vm_page_bits_t)2 << last_bit) -
2789 ((vm_page_bits_t)1 << first_bit));
2793 * vm_page_set_valid_range:
2795 * Sets portions of a page valid. The arguments are expected
2796 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2797 * of any partial chunks touched by the range. The invalid portion of
2798 * such chunks will be zeroed.
2800 * (base + size) must be less then or equal to PAGE_SIZE.
2803 vm_page_set_valid_range(vm_page_t m, int base, int size)
2807 VM_OBJECT_ASSERT_WLOCKED(m->object);
2808 if (size == 0) /* handle degenerate case */
2812 * If the base is not DEV_BSIZE aligned and the valid
2813 * bit is clear, we have to zero out a portion of the
2816 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2817 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2818 pmap_zero_page_area(m, frag, base - frag);
2821 * If the ending offset is not DEV_BSIZE aligned and the
2822 * valid bit is clear, we have to zero out a portion of
2825 endoff = base + size;
2826 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2827 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2828 pmap_zero_page_area(m, endoff,
2829 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2832 * Assert that no previously invalid block that is now being validated
2835 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
2836 ("vm_page_set_valid_range: page %p is dirty", m));
2839 * Set valid bits inclusive of any overlap.
2841 m->valid |= vm_page_bits(base, size);
2845 * Clear the given bits from the specified page's dirty field.
2847 static __inline void
2848 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
2851 #if PAGE_SIZE < 16384
2856 * If the object is locked and the page is neither exclusive busy nor
2857 * write mapped, then the page's dirty field cannot possibly be
2858 * set by a concurrent pmap operation.
2860 VM_OBJECT_ASSERT_WLOCKED(m->object);
2861 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
2862 m->dirty &= ~pagebits;
2865 * The pmap layer can call vm_page_dirty() without
2866 * holding a distinguished lock. The combination of
2867 * the object's lock and an atomic operation suffice
2868 * to guarantee consistency of the page dirty field.
2870 * For PAGE_SIZE == 32768 case, compiler already
2871 * properly aligns the dirty field, so no forcible
2872 * alignment is needed. Only require existence of
2873 * atomic_clear_64 when page size is 32768.
2875 addr = (uintptr_t)&m->dirty;
2876 #if PAGE_SIZE == 32768
2877 atomic_clear_64((uint64_t *)addr, pagebits);
2878 #elif PAGE_SIZE == 16384
2879 atomic_clear_32((uint32_t *)addr, pagebits);
2880 #else /* PAGE_SIZE <= 8192 */
2882 * Use a trick to perform a 32-bit atomic on the
2883 * containing aligned word, to not depend on the existence
2884 * of atomic_clear_{8, 16}.
2886 shift = addr & (sizeof(uint32_t) - 1);
2887 #if BYTE_ORDER == BIG_ENDIAN
2888 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
2892 addr &= ~(sizeof(uint32_t) - 1);
2893 atomic_clear_32((uint32_t *)addr, pagebits << shift);
2894 #endif /* PAGE_SIZE */
2899 * vm_page_set_validclean:
2901 * Sets portions of a page valid and clean. The arguments are expected
2902 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2903 * of any partial chunks touched by the range. The invalid portion of
2904 * such chunks will be zero'd.
2906 * (base + size) must be less then or equal to PAGE_SIZE.
2909 vm_page_set_validclean(vm_page_t m, int base, int size)
2911 vm_page_bits_t oldvalid, pagebits;
2914 VM_OBJECT_ASSERT_WLOCKED(m->object);
2915 if (size == 0) /* handle degenerate case */
2919 * If the base is not DEV_BSIZE aligned and the valid
2920 * bit is clear, we have to zero out a portion of the
2923 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2924 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
2925 pmap_zero_page_area(m, frag, base - frag);
2928 * If the ending offset is not DEV_BSIZE aligned and the
2929 * valid bit is clear, we have to zero out a portion of
2932 endoff = base + size;
2933 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2934 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
2935 pmap_zero_page_area(m, endoff,
2936 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2939 * Set valid, clear dirty bits. If validating the entire
2940 * page we can safely clear the pmap modify bit. We also
2941 * use this opportunity to clear the VPO_NOSYNC flag. If a process
2942 * takes a write fault on a MAP_NOSYNC memory area the flag will
2945 * We set valid bits inclusive of any overlap, but we can only
2946 * clear dirty bits for DEV_BSIZE chunks that are fully within
2949 oldvalid = m->valid;
2950 pagebits = vm_page_bits(base, size);
2951 m->valid |= pagebits;
2953 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
2954 frag = DEV_BSIZE - frag;
2960 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
2962 if (base == 0 && size == PAGE_SIZE) {
2964 * The page can only be modified within the pmap if it is
2965 * mapped, and it can only be mapped if it was previously
2968 if (oldvalid == VM_PAGE_BITS_ALL)
2970 * Perform the pmap_clear_modify() first. Otherwise,
2971 * a concurrent pmap operation, such as
2972 * pmap_protect(), could clear a modification in the
2973 * pmap and set the dirty field on the page before
2974 * pmap_clear_modify() had begun and after the dirty
2975 * field was cleared here.
2977 pmap_clear_modify(m);
2979 m->oflags &= ~VPO_NOSYNC;
2980 } else if (oldvalid != VM_PAGE_BITS_ALL)
2981 m->dirty &= ~pagebits;
2983 vm_page_clear_dirty_mask(m, pagebits);
2987 vm_page_clear_dirty(vm_page_t m, int base, int size)
2990 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
2994 * vm_page_set_invalid:
2996 * Invalidates DEV_BSIZE'd chunks within a page. Both the
2997 * valid and dirty bits for the effected areas are cleared.
3000 vm_page_set_invalid(vm_page_t m, int base, int size)
3002 vm_page_bits_t bits;
3006 VM_OBJECT_ASSERT_WLOCKED(object);
3007 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
3008 size >= object->un_pager.vnp.vnp_size)
3009 bits = VM_PAGE_BITS_ALL;
3011 bits = vm_page_bits(base, size);
3012 if (m->valid == VM_PAGE_BITS_ALL && bits != 0)
3014 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3015 !pmap_page_is_mapped(m),
3016 ("vm_page_set_invalid: page %p is mapped", m));
3022 * vm_page_zero_invalid()
3024 * The kernel assumes that the invalid portions of a page contain
3025 * garbage, but such pages can be mapped into memory by user code.
3026 * When this occurs, we must zero out the non-valid portions of the
3027 * page so user code sees what it expects.
3029 * Pages are most often semi-valid when the end of a file is mapped
3030 * into memory and the file's size is not page aligned.
3033 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3038 VM_OBJECT_ASSERT_WLOCKED(m->object);
3040 * Scan the valid bits looking for invalid sections that
3041 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
3042 * valid bit may be set ) have already been zeroed by
3043 * vm_page_set_validclean().
3045 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3046 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3047 (m->valid & ((vm_page_bits_t)1 << i))) {
3049 pmap_zero_page_area(m,
3050 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3057 * setvalid is TRUE when we can safely set the zero'd areas
3058 * as being valid. We can do this if there are no cache consistancy
3059 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3062 m->valid = VM_PAGE_BITS_ALL;
3068 * Is (partial) page valid? Note that the case where size == 0
3069 * will return FALSE in the degenerate case where the page is
3070 * entirely invalid, and TRUE otherwise.
3073 vm_page_is_valid(vm_page_t m, int base, int size)
3075 vm_page_bits_t bits;
3077 VM_OBJECT_ASSERT_LOCKED(m->object);
3078 bits = vm_page_bits(base, size);
3079 return (m->valid != 0 && (m->valid & bits) == bits);
3083 * vm_page_ps_is_valid:
3085 * Returns TRUE if the entire (super)page is valid and FALSE otherwise.
3088 vm_page_ps_is_valid(vm_page_t m)
3092 VM_OBJECT_ASSERT_LOCKED(m->object);
3093 npages = atop(pagesizes[m->psind]);
3096 * The physically contiguous pages that make up a superpage, i.e., a
3097 * page with a page size index ("psind") greater than zero, will
3098 * occupy adjacent entries in vm_page_array[].
3100 for (i = 0; i < npages; i++) {
3101 if (m[i].valid != VM_PAGE_BITS_ALL)
3108 * Set the page's dirty bits if the page is modified.
3111 vm_page_test_dirty(vm_page_t m)
3114 VM_OBJECT_ASSERT_WLOCKED(m->object);
3115 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3120 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3123 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3127 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3130 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3134 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3137 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3140 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3142 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3145 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3149 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3152 mtx_assert_(vm_page_lockptr(m), a, file, line);
3158 vm_page_object_lock_assert(vm_page_t m)
3162 * Certain of the page's fields may only be modified by the
3163 * holder of the containing object's lock or the exclusive busy.
3164 * holder. Unfortunately, the holder of the write busy is
3165 * not recorded, and thus cannot be checked here.
3167 if (m->object != NULL && !vm_page_xbusied(m))
3168 VM_OBJECT_ASSERT_WLOCKED(m->object);
3172 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3175 if ((bits & PGA_WRITEABLE) == 0)
3179 * The PGA_WRITEABLE flag can only be set if the page is
3180 * managed, is exclusively busied or the object is locked.
3181 * Currently, this flag is only set by pmap_enter().
3183 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3184 ("PGA_WRITEABLE on unmanaged page"));
3185 if (!vm_page_xbusied(m))
3186 VM_OBJECT_ASSERT_LOCKED(m->object);
3190 #include "opt_ddb.h"
3192 #include <sys/kernel.h>
3194 #include <ddb/ddb.h>
3196 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3198 db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
3199 db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
3200 db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
3201 db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
3202 db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
3203 db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
3204 db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
3205 db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
3206 db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
3207 db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
3210 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3214 db_printf("pq_free %d pq_cache %d\n",
3215 cnt.v_free_count, cnt.v_cache_count);
3216 for (dom = 0; dom < vm_ndomains; dom++) {
3218 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pass %d\n",
3220 vm_dom[dom].vmd_page_count,
3221 vm_dom[dom].vmd_free_count,
3222 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3223 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
3224 vm_dom[dom].vmd_pass);
3228 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3234 db_printf("show pginfo addr\n");
3238 phys = strchr(modif, 'p') != NULL;
3240 m = PHYS_TO_VM_PAGE(addr);
3242 m = (vm_page_t)addr;
3244 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3245 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3246 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3247 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3248 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);