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(u_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(u_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)
520 vm_page_assert_xbusied(m);
521 locked = mtx_owned(vm_page_lockptr(m));
525 x &= VPB_BIT_WAITERS;
526 if (x != 0 && !locked)
528 if (atomic_cmpset_rel_int(&m->busy_lock,
529 VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1)))
531 if (x != 0 && !locked)
544 * Return a positive value if the page is shared busied, 0 otherwise.
547 vm_page_sbusied(vm_page_t m)
552 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
558 * Shared unbusy a page.
561 vm_page_sunbusy(vm_page_t m)
565 vm_page_assert_sbusied(m);
569 if (VPB_SHARERS(x) > 1) {
570 if (atomic_cmpset_int(&m->busy_lock, x,
575 if ((x & VPB_BIT_WAITERS) == 0) {
576 KASSERT(x == VPB_SHARERS_WORD(1),
577 ("vm_page_sunbusy: invalid lock state"));
578 if (atomic_cmpset_int(&m->busy_lock,
579 VPB_SHARERS_WORD(1), VPB_UNBUSIED))
583 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
584 ("vm_page_sunbusy: invalid lock state for waiters"));
587 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
598 * vm_page_busy_sleep:
600 * Sleep and release the page lock, using the page pointer as wchan.
601 * This is used to implement the hard-path of busying mechanism.
603 * The given page must be locked.
605 * If nonshared is true, sleep only if the page is xbusy.
608 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
612 vm_page_assert_locked(m);
615 if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
616 ((x & VPB_BIT_WAITERS) == 0 &&
617 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
621 msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
627 * Try to shared busy a page.
628 * If the operation succeeds 1 is returned otherwise 0.
629 * The operation never sleeps.
632 vm_page_trysbusy(vm_page_t m)
638 if ((x & VPB_BIT_SHARED) == 0)
640 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
646 * vm_page_xunbusy_hard:
648 * Called after the first try the exclusive unbusy of a page failed.
649 * It is assumed that the waiters bit is on.
652 vm_page_xunbusy_hard(vm_page_t m)
655 vm_page_assert_xbusied(m);
658 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
666 * Wakeup anyone waiting for the page.
667 * The ownership bits do not change.
669 * The given page must be locked.
672 vm_page_flash(vm_page_t m)
676 vm_page_lock_assert(m, MA_OWNED);
680 if ((x & VPB_BIT_WAITERS) == 0)
682 if (atomic_cmpset_int(&m->busy_lock, x,
683 x & (~VPB_BIT_WAITERS)))
690 * Keep page from being freed by the page daemon
691 * much of the same effect as wiring, except much lower
692 * overhead and should be used only for *very* temporary
693 * holding ("wiring").
696 vm_page_hold(vm_page_t mem)
699 vm_page_lock_assert(mem, MA_OWNED);
704 vm_page_unhold(vm_page_t mem)
707 vm_page_lock_assert(mem, MA_OWNED);
708 KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
710 if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
711 vm_page_free_toq(mem);
715 * vm_page_unhold_pages:
717 * Unhold each of the pages that is referenced by the given array.
720 vm_page_unhold_pages(vm_page_t *ma, int count)
722 struct mtx *mtx, *new_mtx;
725 for (; count != 0; count--) {
727 * Avoid releasing and reacquiring the same page lock.
729 new_mtx = vm_page_lockptr(*ma);
730 if (mtx != new_mtx) {
744 PHYS_TO_VM_PAGE(vm_paddr_t pa)
748 #ifdef VM_PHYSSEG_SPARSE
749 m = vm_phys_paddr_to_vm_page(pa);
751 m = vm_phys_fictitious_to_vm_page(pa);
753 #elif defined(VM_PHYSSEG_DENSE)
757 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
758 m = &vm_page_array[pi - first_page];
761 return (vm_phys_fictitious_to_vm_page(pa));
763 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
770 * Create a fictitious page with the specified physical address and
771 * memory attribute. The memory attribute is the only the machine-
772 * dependent aspect of a fictitious page that must be initialized.
775 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
779 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
780 vm_page_initfake(m, paddr, memattr);
785 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
788 if ((m->flags & PG_FICTITIOUS) != 0) {
790 * The page's memattr might have changed since the
791 * previous initialization. Update the pmap to the
796 m->phys_addr = paddr;
798 /* Fictitious pages don't use "segind". */
799 m->flags = PG_FICTITIOUS;
800 /* Fictitious pages don't use "order" or "pool". */
801 m->oflags = VPO_UNMANAGED;
802 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
806 pmap_page_set_memattr(m, memattr);
812 * Release a fictitious page.
815 vm_page_putfake(vm_page_t m)
818 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
819 KASSERT((m->flags & PG_FICTITIOUS) != 0,
820 ("vm_page_putfake: bad page %p", m));
821 uma_zfree(fakepg_zone, m);
825 * vm_page_updatefake:
827 * Update the given fictitious page to the specified physical address and
831 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
834 KASSERT((m->flags & PG_FICTITIOUS) != 0,
835 ("vm_page_updatefake: bad page %p", m));
836 m->phys_addr = paddr;
837 pmap_page_set_memattr(m, memattr);
846 vm_page_free(vm_page_t m)
849 m->flags &= ~PG_ZERO;
856 * Free a page to the zerod-pages queue
859 vm_page_free_zero(vm_page_t m)
867 * Unbusy and handle the page queueing for a page from the VOP_GETPAGES()
868 * array which is not the request page.
871 vm_page_readahead_finish(vm_page_t m)
876 * Since the page is not the requested page, whether
877 * it should be activated or deactivated is not
878 * obvious. Empirical results have shown that
879 * deactivating the page is usually the best choice,
880 * unless the page is wanted by another thread.
883 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
886 vm_page_deactivate(m);
891 * Free the completely invalid page. Such page state
892 * occurs due to the short read operation which did
893 * not covered our page at all, or in case when a read
903 * vm_page_sleep_if_busy:
905 * Sleep and release the page queues lock if the page is busied.
906 * Returns TRUE if the thread slept.
908 * The given page must be unlocked and object containing it must
912 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
916 vm_page_lock_assert(m, MA_NOTOWNED);
917 VM_OBJECT_ASSERT_WLOCKED(m->object);
919 if (vm_page_busied(m)) {
921 * The page-specific object must be cached because page
922 * identity can change during the sleep, causing the
923 * re-lock of a different object.
924 * It is assumed that a reference to the object is already
925 * held by the callers.
929 VM_OBJECT_WUNLOCK(obj);
930 vm_page_busy_sleep(m, msg, false);
931 VM_OBJECT_WLOCK(obj);
938 * vm_page_dirty_KBI: [ internal use only ]
940 * Set all bits in the page's dirty field.
942 * The object containing the specified page must be locked if the
943 * call is made from the machine-independent layer.
945 * See vm_page_clear_dirty_mask().
947 * This function should only be called by vm_page_dirty().
950 vm_page_dirty_KBI(vm_page_t m)
953 /* These assertions refer to this operation by its public name. */
954 KASSERT((m->flags & PG_CACHED) == 0,
955 ("vm_page_dirty: page in cache!"));
956 KASSERT(!VM_PAGE_IS_FREE(m),
957 ("vm_page_dirty: page is free!"));
958 KASSERT(m->valid == VM_PAGE_BITS_ALL,
959 ("vm_page_dirty: page is invalid!"));
960 m->dirty = VM_PAGE_BITS_ALL;
964 * vm_page_insert: [ internal use only ]
966 * Inserts the given mem entry into the object and object list.
968 * The object must be locked.
971 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
975 VM_OBJECT_ASSERT_WLOCKED(object);
976 mpred = vm_radix_lookup_le(&object->rtree, pindex);
977 return (vm_page_insert_after(m, object, pindex, mpred));
981 * vm_page_insert_after:
983 * Inserts the page "m" into the specified object at offset "pindex".
985 * The page "mpred" must immediately precede the offset "pindex" within
986 * the specified object.
988 * The object must be locked.
991 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
996 VM_OBJECT_ASSERT_WLOCKED(object);
997 KASSERT(m->object == NULL,
998 ("vm_page_insert_after: page already inserted"));
1000 KASSERT(mpred->object == object,
1001 ("vm_page_insert_after: object doesn't contain mpred"));
1002 KASSERT(mpred->pindex < pindex,
1003 ("vm_page_insert_after: mpred doesn't precede pindex"));
1004 msucc = TAILQ_NEXT(mpred, listq);
1006 msucc = TAILQ_FIRST(&object->memq);
1008 KASSERT(msucc->pindex > pindex,
1009 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1012 * Record the object/offset pair in this page
1018 * Now link into the object's ordered list of backed pages.
1020 if (vm_radix_insert(&object->rtree, m)) {
1025 vm_page_insert_radixdone(m, object, mpred);
1030 * vm_page_insert_radixdone:
1032 * Complete page "m" insertion into the specified object after the
1033 * radix trie hooking.
1035 * The page "mpred" must precede the offset "m->pindex" within the
1038 * The object must be locked.
1041 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1044 VM_OBJECT_ASSERT_WLOCKED(object);
1045 KASSERT(object != NULL && m->object == object,
1046 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1047 if (mpred != NULL) {
1048 KASSERT(mpred->object == object,
1049 ("vm_page_insert_after: object doesn't contain mpred"));
1050 KASSERT(mpred->pindex < m->pindex,
1051 ("vm_page_insert_after: mpred doesn't precede pindex"));
1055 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1057 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1060 * Show that the object has one more resident page.
1062 object->resident_page_count++;
1065 * Hold the vnode until the last page is released.
1067 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1068 vhold(object->handle);
1071 * Since we are inserting a new and possibly dirty page,
1072 * update the object's OBJ_MIGHTBEDIRTY flag.
1074 if (pmap_page_is_write_mapped(m))
1075 vm_object_set_writeable_dirty(object);
1081 * Removes the given mem entry from the object/offset-page
1082 * table and the object page list, but do not invalidate/terminate
1083 * the backing store.
1085 * The object must be locked. The page must be locked if it is managed.
1088 vm_page_remove(vm_page_t m)
1093 if ((m->oflags & VPO_UNMANAGED) == 0)
1094 vm_page_lock_assert(m, MA_OWNED);
1095 if ((object = m->object) == NULL)
1097 VM_OBJECT_ASSERT_WLOCKED(object);
1098 if (vm_page_xbusied(m)) {
1100 if ((m->oflags & VPO_UNMANAGED) != 0 &&
1101 !mtx_owned(vm_page_lockptr(m))) {
1106 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1112 * Now remove from the object's list of backed pages.
1114 vm_radix_remove(&object->rtree, m->pindex);
1115 TAILQ_REMOVE(&object->memq, m, listq);
1118 * And show that the object has one fewer resident page.
1120 object->resident_page_count--;
1123 * The vnode may now be recycled.
1125 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1126 vdrop(object->handle);
1134 * Returns the page associated with the object/offset
1135 * pair specified; if none is found, NULL is returned.
1137 * The object must be locked.
1140 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1143 VM_OBJECT_ASSERT_LOCKED(object);
1144 return (vm_radix_lookup(&object->rtree, pindex));
1148 * vm_page_find_least:
1150 * Returns the page associated with the object with least pindex
1151 * greater than or equal to the parameter pindex, or NULL.
1153 * The object must be locked.
1156 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1160 VM_OBJECT_ASSERT_LOCKED(object);
1161 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1162 m = vm_radix_lookup_ge(&object->rtree, pindex);
1167 * Returns the given page's successor (by pindex) within the object if it is
1168 * resident; if none is found, NULL is returned.
1170 * The object must be locked.
1173 vm_page_next(vm_page_t m)
1177 VM_OBJECT_ASSERT_WLOCKED(m->object);
1178 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1179 MPASS(next->object == m->object);
1180 if (next->pindex != m->pindex + 1)
1187 * Returns the given page's predecessor (by pindex) within the object if it is
1188 * resident; if none is found, NULL is returned.
1190 * The object must be locked.
1193 vm_page_prev(vm_page_t m)
1197 VM_OBJECT_ASSERT_WLOCKED(m->object);
1198 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1199 MPASS(prev->object == m->object);
1200 if (prev->pindex != m->pindex - 1)
1207 * Uses the page mnew as a replacement for an existing page at index
1208 * pindex which must be already present in the object.
1210 * The existing page must not be on a paging queue.
1213 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1215 vm_page_t mold, mpred;
1217 VM_OBJECT_ASSERT_WLOCKED(object);
1220 * This function mostly follows vm_page_insert() and
1221 * vm_page_remove() without the radix, object count and vnode
1222 * dance. Double check such functions for more comments.
1224 mpred = vm_radix_lookup(&object->rtree, pindex);
1225 KASSERT(mpred != NULL,
1226 ("vm_page_replace: replacing page not present with pindex"));
1227 mpred = TAILQ_PREV(mpred, respgs, listq);
1229 KASSERT(mpred->pindex < pindex,
1230 ("vm_page_insert_after: mpred doesn't precede pindex"));
1232 mnew->object = object;
1233 mnew->pindex = pindex;
1234 mold = vm_radix_replace(&object->rtree, mnew);
1235 KASSERT(mold->queue == PQ_NONE,
1236 ("vm_page_replace: mold is on a paging queue"));
1238 /* Detach the old page from the resident tailq. */
1239 TAILQ_REMOVE(&object->memq, mold, listq);
1241 mold->object = NULL;
1242 vm_page_xunbusy(mold);
1244 /* Insert the new page in the resident tailq. */
1246 TAILQ_INSERT_AFTER(&object->memq, mpred, mnew, listq);
1248 TAILQ_INSERT_HEAD(&object->memq, mnew, listq);
1249 if (pmap_page_is_write_mapped(mnew))
1250 vm_object_set_writeable_dirty(object);
1257 * Move the given memory entry from its
1258 * current object to the specified target object/offset.
1260 * Note: swap associated with the page must be invalidated by the move. We
1261 * have to do this for several reasons: (1) we aren't freeing the
1262 * page, (2) we are dirtying the page, (3) the VM system is probably
1263 * moving the page from object A to B, and will then later move
1264 * the backing store from A to B and we can't have a conflict.
1266 * Note: we *always* dirty the page. It is necessary both for the
1267 * fact that we moved it, and because we may be invalidating
1268 * swap. If the page is on the cache, we have to deactivate it
1269 * or vm_page_dirty() will panic. Dirty pages are not allowed
1272 * The objects must be locked.
1275 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1280 VM_OBJECT_ASSERT_WLOCKED(new_object);
1282 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1283 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1284 ("vm_page_rename: pindex already renamed"));
1287 * Create a custom version of vm_page_insert() which does not depend
1288 * by m_prev and can cheat on the implementation aspects of the
1292 m->pindex = new_pindex;
1293 if (vm_radix_insert(&new_object->rtree, m)) {
1299 * The operation cannot fail anymore. The removal must happen before
1300 * the listq iterator is tainted.
1306 /* Return back to the new pindex to complete vm_page_insert(). */
1307 m->pindex = new_pindex;
1308 m->object = new_object;
1310 vm_page_insert_radixdone(m, new_object, mpred);
1316 * Convert all of the given object's cached pages that have a
1317 * pindex within the given range into free pages. If the value
1318 * zero is given for "end", then the range's upper bound is
1319 * infinity. If the given object is backed by a vnode and it
1320 * transitions from having one or more cached pages to none, the
1321 * vnode's hold count is reduced.
1324 vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1329 mtx_lock(&vm_page_queue_free_mtx);
1330 if (__predict_false(vm_radix_is_empty(&object->cache))) {
1331 mtx_unlock(&vm_page_queue_free_mtx);
1334 while ((m = vm_radix_lookup_ge(&object->cache, start)) != NULL) {
1335 if (end != 0 && m->pindex >= end)
1337 vm_radix_remove(&object->cache, m->pindex);
1338 vm_page_cache_turn_free(m);
1340 empty = vm_radix_is_empty(&object->cache);
1341 mtx_unlock(&vm_page_queue_free_mtx);
1342 if (object->type == OBJT_VNODE && empty)
1343 vdrop(object->handle);
1347 * Returns the cached page that is associated with the given
1348 * object and offset. If, however, none exists, returns NULL.
1350 * The free page queue must be locked.
1352 static inline vm_page_t
1353 vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
1356 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1357 return (vm_radix_lookup(&object->cache, pindex));
1361 * Remove the given cached page from its containing object's
1362 * collection of cached pages.
1364 * The free page queue must be locked.
1367 vm_page_cache_remove(vm_page_t m)
1370 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1371 KASSERT((m->flags & PG_CACHED) != 0,
1372 ("vm_page_cache_remove: page %p is not cached", m));
1373 vm_radix_remove(&m->object->cache, m->pindex);
1375 cnt.v_cache_count--;
1379 * Transfer all of the cached pages with offset greater than or
1380 * equal to 'offidxstart' from the original object's cache to the
1381 * new object's cache. However, any cached pages with offset
1382 * greater than or equal to the new object's size are kept in the
1383 * original object. Initially, the new object's cache must be
1384 * empty. Offset 'offidxstart' in the original object must
1385 * correspond to offset zero in the new object.
1387 * The new object must be locked.
1390 vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1391 vm_object_t new_object)
1396 * Insertion into an object's collection of cached pages
1397 * requires the object to be locked. In contrast, removal does
1400 VM_OBJECT_ASSERT_WLOCKED(new_object);
1401 KASSERT(vm_radix_is_empty(&new_object->cache),
1402 ("vm_page_cache_transfer: object %p has cached pages",
1404 mtx_lock(&vm_page_queue_free_mtx);
1405 while ((m = vm_radix_lookup_ge(&orig_object->cache,
1406 offidxstart)) != NULL) {
1408 * Transfer all of the pages with offset greater than or
1409 * equal to 'offidxstart' from the original object's
1410 * cache to the new object's cache.
1412 if ((m->pindex - offidxstart) >= new_object->size)
1414 vm_radix_remove(&orig_object->cache, m->pindex);
1415 /* Update the page's object and offset. */
1416 m->object = new_object;
1417 m->pindex -= offidxstart;
1418 if (vm_radix_insert(&new_object->cache, m))
1419 vm_page_cache_turn_free(m);
1421 mtx_unlock(&vm_page_queue_free_mtx);
1425 * Returns TRUE if a cached page is associated with the given object and
1426 * offset, and FALSE otherwise.
1428 * The object must be locked.
1431 vm_page_is_cached(vm_object_t object, vm_pindex_t pindex)
1436 * Insertion into an object's collection of cached pages requires the
1437 * object to be locked. Therefore, if the object is locked and the
1438 * object's collection is empty, there is no need to acquire the free
1439 * page queues lock in order to prove that the specified page doesn't
1442 VM_OBJECT_ASSERT_WLOCKED(object);
1443 if (__predict_true(vm_object_cache_is_empty(object)))
1445 mtx_lock(&vm_page_queue_free_mtx);
1446 m = vm_page_cache_lookup(object, pindex);
1447 mtx_unlock(&vm_page_queue_free_mtx);
1454 * Allocate and return a page that is associated with the specified
1455 * object and offset pair. By default, this page is exclusive busied.
1457 * The caller must always specify an allocation class.
1459 * allocation classes:
1460 * VM_ALLOC_NORMAL normal process request
1461 * VM_ALLOC_SYSTEM system *really* needs a page
1462 * VM_ALLOC_INTERRUPT interrupt time request
1464 * optional allocation flags:
1465 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1466 * intends to allocate
1467 * VM_ALLOC_IFCACHED return page only if it is cached
1468 * VM_ALLOC_IFNOTCACHED return NULL, do not reactivate if the page
1470 * VM_ALLOC_NOBUSY do not exclusive busy the page
1471 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1472 * VM_ALLOC_NOOBJ page is not associated with an object and
1473 * should not be exclusive busy
1474 * VM_ALLOC_SBUSY shared busy the allocated page
1475 * VM_ALLOC_WIRED wire the allocated page
1476 * VM_ALLOC_ZERO prefer a zeroed page
1478 * This routine may not sleep.
1481 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1483 struct vnode *vp = NULL;
1484 vm_object_t m_object;
1486 int flags, req_class;
1488 mpred = 0; /* XXX: pacify gcc */
1489 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1490 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1491 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1492 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1493 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1496 VM_OBJECT_ASSERT_WLOCKED(object);
1498 req_class = req & VM_ALLOC_CLASS_MASK;
1501 * The page daemon is allowed to dig deeper into the free page list.
1503 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1504 req_class = VM_ALLOC_SYSTEM;
1506 if (object != NULL) {
1507 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1508 KASSERT(mpred == NULL || mpred->pindex != pindex,
1509 ("vm_page_alloc: pindex already allocated"));
1513 * The page allocation request can came from consumers which already
1514 * hold the free page queue mutex, like vm_page_insert() in
1517 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
1518 if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1519 (req_class == VM_ALLOC_SYSTEM &&
1520 cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1521 (req_class == VM_ALLOC_INTERRUPT &&
1522 cnt.v_free_count + cnt.v_cache_count > 0)) {
1524 * Allocate from the free queue if the number of free pages
1525 * exceeds the minimum for the request class.
1527 if (object != NULL &&
1528 (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1529 if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1530 mtx_unlock(&vm_page_queue_free_mtx);
1533 if (vm_phys_unfree_page(m))
1534 vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1535 #if VM_NRESERVLEVEL > 0
1536 else if (!vm_reserv_reactivate_page(m))
1540 panic("vm_page_alloc: cache page %p is missing"
1541 " from the free queue", m);
1542 } else if ((req & VM_ALLOC_IFCACHED) != 0) {
1543 mtx_unlock(&vm_page_queue_free_mtx);
1545 #if VM_NRESERVLEVEL > 0
1546 } else if (object == NULL || (object->flags & (OBJ_COLORED |
1547 OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1548 vm_reserv_alloc_page(object, pindex, mpred)) == NULL) {
1552 m = vm_phys_alloc_pages(object != NULL ?
1553 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1554 #if VM_NRESERVLEVEL > 0
1555 if (m == NULL && vm_reserv_reclaim_inactive()) {
1556 m = vm_phys_alloc_pages(object != NULL ?
1557 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1564 * Not allocatable, give up.
1566 mtx_unlock(&vm_page_queue_free_mtx);
1567 atomic_add_int(&vm_pageout_deficit,
1568 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1569 pagedaemon_wakeup();
1574 * At this point we had better have found a good page.
1576 KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1577 KASSERT(m->queue == PQ_NONE,
1578 ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1579 KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1580 KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1581 KASSERT(!vm_page_busied(m), ("vm_page_alloc: page %p is busy", m));
1582 KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1583 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1584 ("vm_page_alloc: page %p has unexpected memattr %d", m,
1585 pmap_page_get_memattr(m)));
1586 if ((m->flags & PG_CACHED) != 0) {
1587 KASSERT((m->flags & PG_ZERO) == 0,
1588 ("vm_page_alloc: cached page %p is PG_ZERO", m));
1589 KASSERT(m->valid != 0,
1590 ("vm_page_alloc: cached page %p is invalid", m));
1591 if (m->object == object && m->pindex == pindex)
1592 cnt.v_reactivated++;
1595 m_object = m->object;
1596 vm_page_cache_remove(m);
1597 if (m_object->type == OBJT_VNODE &&
1598 vm_object_cache_is_empty(m_object))
1599 vp = m_object->handle;
1601 KASSERT(VM_PAGE_IS_FREE(m),
1602 ("vm_page_alloc: page %p is not free", m));
1603 KASSERT(m->valid == 0,
1604 ("vm_page_alloc: free page %p is valid", m));
1605 vm_phys_freecnt_adj(m, -1);
1609 * Only the PG_ZERO flag is inherited. The PG_CACHED or PG_FREE flag
1610 * must be cleared before the free page queues lock is released.
1613 if (m->flags & PG_ZERO) {
1614 vm_page_zero_count--;
1615 if (req & VM_ALLOC_ZERO)
1618 if (req & VM_ALLOC_NODUMP)
1621 mtx_unlock(&vm_page_queue_free_mtx);
1623 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1625 m->busy_lock = VPB_UNBUSIED;
1626 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1627 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1628 if ((req & VM_ALLOC_SBUSY) != 0)
1629 m->busy_lock = VPB_SHARERS_WORD(1);
1630 if (req & VM_ALLOC_WIRED) {
1632 * The page lock is not required for wiring a page until that
1633 * page is inserted into the object.
1635 atomic_add_int(&cnt.v_wire_count, 1);
1640 if (object != NULL) {
1641 if (vm_page_insert_after(m, object, pindex, mpred)) {
1642 /* See the comment below about hold count. */
1645 pagedaemon_wakeup();
1646 if (req & VM_ALLOC_WIRED) {
1647 atomic_subtract_int(&cnt.v_wire_count, 1);
1651 m->oflags = VPO_UNMANAGED;
1652 m->busy_lock = VPB_UNBUSIED;
1657 /* Ignore device objects; the pager sets "memattr" for them. */
1658 if (object->memattr != VM_MEMATTR_DEFAULT &&
1659 (object->flags & OBJ_FICTITIOUS) == 0)
1660 pmap_page_set_memattr(m, object->memattr);
1665 * The following call to vdrop() must come after the above call
1666 * to vm_page_insert() in case both affect the same object and
1667 * vnode. Otherwise, the affected vnode's hold count could
1668 * temporarily become zero.
1674 * Don't wakeup too often - wakeup the pageout daemon when
1675 * we would be nearly out of memory.
1677 if (vm_paging_needed())
1678 pagedaemon_wakeup();
1684 vm_page_alloc_contig_vdrop(struct spglist *lst)
1687 while (!SLIST_EMPTY(lst)) {
1688 vdrop((struct vnode *)SLIST_FIRST(lst)-> plinks.s.pv);
1689 SLIST_REMOVE_HEAD(lst, plinks.s.ss);
1694 * vm_page_alloc_contig:
1696 * Allocate a contiguous set of physical pages of the given size "npages"
1697 * from the free lists. All of the physical pages must be at or above
1698 * the given physical address "low" and below the given physical address
1699 * "high". The given value "alignment" determines the alignment of the
1700 * first physical page in the set. If the given value "boundary" is
1701 * non-zero, then the set of physical pages cannot cross any physical
1702 * address boundary that is a multiple of that value. Both "alignment"
1703 * and "boundary" must be a power of two.
1705 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1706 * then the memory attribute setting for the physical pages is configured
1707 * to the object's memory attribute setting. Otherwise, the memory
1708 * attribute setting for the physical pages is configured to "memattr",
1709 * overriding the object's memory attribute setting. However, if the
1710 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1711 * memory attribute setting for the physical pages cannot be configured
1712 * to VM_MEMATTR_DEFAULT.
1714 * The caller must always specify an allocation class.
1716 * allocation classes:
1717 * VM_ALLOC_NORMAL normal process request
1718 * VM_ALLOC_SYSTEM system *really* needs a page
1719 * VM_ALLOC_INTERRUPT interrupt time request
1721 * optional allocation flags:
1722 * VM_ALLOC_NOBUSY do not exclusive busy the page
1723 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1724 * VM_ALLOC_NOOBJ page is not associated with an object and
1725 * should not be exclusive busy
1726 * VM_ALLOC_SBUSY shared busy the allocated page
1727 * VM_ALLOC_WIRED wire the allocated page
1728 * VM_ALLOC_ZERO prefer a zeroed page
1730 * This routine may not sleep.
1733 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1734 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1735 vm_paddr_t boundary, vm_memattr_t memattr)
1738 struct spglist deferred_vdrop_list;
1739 vm_page_t m, m_tmp, m_ret;
1740 u_int flags, oflags;
1743 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1744 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1745 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1746 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1747 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1749 if (object != NULL) {
1750 VM_OBJECT_ASSERT_WLOCKED(object);
1751 KASSERT(object->type == OBJT_PHYS,
1752 ("vm_page_alloc_contig: object %p isn't OBJT_PHYS",
1755 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1756 req_class = req & VM_ALLOC_CLASS_MASK;
1759 * The page daemon is allowed to dig deeper into the free page list.
1761 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1762 req_class = VM_ALLOC_SYSTEM;
1764 SLIST_INIT(&deferred_vdrop_list);
1765 mtx_lock(&vm_page_queue_free_mtx);
1766 if (cnt.v_free_count + cnt.v_cache_count >= npages +
1767 cnt.v_free_reserved || (req_class == VM_ALLOC_SYSTEM &&
1768 cnt.v_free_count + cnt.v_cache_count >= npages +
1769 cnt.v_interrupt_free_min) || (req_class == VM_ALLOC_INTERRUPT &&
1770 cnt.v_free_count + cnt.v_cache_count >= npages)) {
1771 #if VM_NRESERVLEVEL > 0
1773 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1774 (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1775 low, high, alignment, boundary)) == NULL)
1777 m_ret = vm_phys_alloc_contig(npages, low, high,
1778 alignment, boundary);
1780 mtx_unlock(&vm_page_queue_free_mtx);
1781 atomic_add_int(&vm_pageout_deficit, npages);
1782 pagedaemon_wakeup();
1786 for (m = m_ret; m < &m_ret[npages]; m++) {
1787 drop = vm_page_alloc_init(m);
1790 * Enqueue the vnode for deferred vdrop().
1792 m->plinks.s.pv = drop;
1793 SLIST_INSERT_HEAD(&deferred_vdrop_list, m,
1798 #if VM_NRESERVLEVEL > 0
1799 if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1804 mtx_unlock(&vm_page_queue_free_mtx);
1809 * Initialize the pages. Only the PG_ZERO flag is inherited.
1812 if ((req & VM_ALLOC_ZERO) != 0)
1814 if ((req & VM_ALLOC_NODUMP) != 0)
1816 if ((req & VM_ALLOC_WIRED) != 0)
1817 atomic_add_int(&cnt.v_wire_count, npages);
1818 oflags = VPO_UNMANAGED;
1819 if (object != NULL) {
1820 if (object->memattr != VM_MEMATTR_DEFAULT &&
1821 memattr == VM_MEMATTR_DEFAULT)
1822 memattr = object->memattr;
1824 for (m = m_ret; m < &m_ret[npages]; m++) {
1826 m->flags = (m->flags | PG_NODUMP) & flags;
1827 m->busy_lock = VPB_UNBUSIED;
1828 if (object != NULL) {
1829 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
1830 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1831 if ((req & VM_ALLOC_SBUSY) != 0)
1832 m->busy_lock = VPB_SHARERS_WORD(1);
1834 if ((req & VM_ALLOC_WIRED) != 0)
1836 /* Unmanaged pages don't use "act_count". */
1838 if (object != NULL) {
1839 if (vm_page_insert(m, object, pindex)) {
1840 vm_page_alloc_contig_vdrop(
1841 &deferred_vdrop_list);
1842 if (vm_paging_needed())
1843 pagedaemon_wakeup();
1844 if ((req & VM_ALLOC_WIRED) != 0)
1845 atomic_subtract_int(&cnt.v_wire_count,
1847 for (m_tmp = m, m = m_ret;
1848 m < &m_ret[npages]; m++) {
1849 if ((req & VM_ALLOC_WIRED) != 0)
1853 m->oflags |= VPO_UNMANAGED;
1855 m->busy_lock = VPB_UNBUSIED;
1862 if (memattr != VM_MEMATTR_DEFAULT)
1863 pmap_page_set_memattr(m, memattr);
1866 vm_page_alloc_contig_vdrop(&deferred_vdrop_list);
1867 if (vm_paging_needed())
1868 pagedaemon_wakeup();
1873 * Initialize a page that has been freshly dequeued from a freelist.
1874 * The caller has to drop the vnode returned, if it is not NULL.
1876 * This function may only be used to initialize unmanaged pages.
1878 * To be called with vm_page_queue_free_mtx held.
1880 static struct vnode *
1881 vm_page_alloc_init(vm_page_t m)
1884 vm_object_t m_object;
1886 KASSERT(m->queue == PQ_NONE,
1887 ("vm_page_alloc_init: page %p has unexpected queue %d",
1889 KASSERT(m->wire_count == 0,
1890 ("vm_page_alloc_init: page %p is wired", m));
1891 KASSERT(m->hold_count == 0,
1892 ("vm_page_alloc_init: page %p is held", m));
1893 KASSERT(!vm_page_busied(m),
1894 ("vm_page_alloc_init: page %p is busy", m));
1895 KASSERT(m->dirty == 0,
1896 ("vm_page_alloc_init: page %p is dirty", m));
1897 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1898 ("vm_page_alloc_init: page %p has unexpected memattr %d",
1899 m, pmap_page_get_memattr(m)));
1900 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1902 if ((m->flags & PG_CACHED) != 0) {
1903 KASSERT((m->flags & PG_ZERO) == 0,
1904 ("vm_page_alloc_init: cached page %p is PG_ZERO", m));
1906 m_object = m->object;
1907 vm_page_cache_remove(m);
1908 if (m_object->type == OBJT_VNODE &&
1909 vm_object_cache_is_empty(m_object))
1910 drop = m_object->handle;
1912 KASSERT(VM_PAGE_IS_FREE(m),
1913 ("vm_page_alloc_init: page %p is not free", m));
1914 KASSERT(m->valid == 0,
1915 ("vm_page_alloc_init: free page %p is valid", m));
1916 vm_phys_freecnt_adj(m, -1);
1917 if ((m->flags & PG_ZERO) != 0)
1918 vm_page_zero_count--;
1920 /* Don't clear the PG_ZERO flag; we'll need it later. */
1921 m->flags &= PG_ZERO;
1926 * vm_page_alloc_freelist:
1928 * Allocate a physical page from the specified free page list.
1930 * The caller must always specify an allocation class.
1932 * allocation classes:
1933 * VM_ALLOC_NORMAL normal process request
1934 * VM_ALLOC_SYSTEM system *really* needs a page
1935 * VM_ALLOC_INTERRUPT interrupt time request
1937 * optional allocation flags:
1938 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1939 * intends to allocate
1940 * VM_ALLOC_WIRED wire the allocated page
1941 * VM_ALLOC_ZERO prefer a zeroed page
1943 * This routine may not sleep.
1946 vm_page_alloc_freelist(int flind, int req)
1953 req_class = req & VM_ALLOC_CLASS_MASK;
1956 * The page daemon is allowed to dig deeper into the free page list.
1958 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1959 req_class = VM_ALLOC_SYSTEM;
1962 * Do not allocate reserved pages unless the req has asked for it.
1964 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
1965 if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1966 (req_class == VM_ALLOC_SYSTEM &&
1967 cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1968 (req_class == VM_ALLOC_INTERRUPT &&
1969 cnt.v_free_count + cnt.v_cache_count > 0))
1970 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
1972 mtx_unlock(&vm_page_queue_free_mtx);
1973 atomic_add_int(&vm_pageout_deficit,
1974 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1975 pagedaemon_wakeup();
1979 mtx_unlock(&vm_page_queue_free_mtx);
1982 drop = vm_page_alloc_init(m);
1983 mtx_unlock(&vm_page_queue_free_mtx);
1986 * Initialize the page. Only the PG_ZERO flag is inherited.
1990 if ((req & VM_ALLOC_ZERO) != 0)
1993 if ((req & VM_ALLOC_WIRED) != 0) {
1995 * The page lock is not required for wiring a page that does
1996 * not belong to an object.
1998 atomic_add_int(&cnt.v_wire_count, 1);
2001 /* Unmanaged pages don't use "act_count". */
2002 m->oflags = VPO_UNMANAGED;
2005 if (vm_paging_needed())
2006 pagedaemon_wakeup();
2011 * vm_wait: (also see VM_WAIT macro)
2013 * Sleep until free pages are available for allocation.
2014 * - Called in various places before memory allocations.
2020 mtx_lock(&vm_page_queue_free_mtx);
2021 if (curproc == pageproc) {
2022 vm_pageout_pages_needed = 1;
2023 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
2024 PDROP | PSWP, "VMWait", 0);
2026 if (!vm_pages_needed) {
2027 vm_pages_needed = 1;
2028 wakeup(&vm_pages_needed);
2030 msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
2036 * vm_waitpfault: (also see VM_WAITPFAULT macro)
2038 * Sleep until free pages are available for allocation.
2039 * - Called only in vm_fault so that processes page faulting
2040 * can be easily tracked.
2041 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2042 * processes will be able to grab memory first. Do not change
2043 * this balance without careful testing first.
2049 mtx_lock(&vm_page_queue_free_mtx);
2050 if (!vm_pages_needed) {
2051 vm_pages_needed = 1;
2052 wakeup(&vm_pages_needed);
2054 msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
2058 struct vm_pagequeue *
2059 vm_page_pagequeue(vm_page_t m)
2062 return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2068 * Remove the given page from its current page queue.
2070 * The page must be locked.
2073 vm_page_dequeue(vm_page_t m)
2075 struct vm_pagequeue *pq;
2077 vm_page_lock_assert(m, MA_OWNED);
2078 KASSERT(m->queue != PQ_NONE,
2079 ("vm_page_dequeue: page %p is not queued", m));
2080 pq = vm_page_pagequeue(m);
2081 vm_pagequeue_lock(pq);
2083 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2084 vm_pagequeue_cnt_dec(pq);
2085 vm_pagequeue_unlock(pq);
2089 * vm_page_dequeue_locked:
2091 * Remove the given page from its current page queue.
2093 * The page and page queue must be locked.
2096 vm_page_dequeue_locked(vm_page_t m)
2098 struct vm_pagequeue *pq;
2100 vm_page_lock_assert(m, MA_OWNED);
2101 pq = vm_page_pagequeue(m);
2102 vm_pagequeue_assert_locked(pq);
2104 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2105 vm_pagequeue_cnt_dec(pq);
2111 * Add the given page to the specified page queue.
2113 * The page must be locked.
2116 vm_page_enqueue(int queue, vm_page_t m)
2118 struct vm_pagequeue *pq;
2120 vm_page_lock_assert(m, MA_OWNED);
2121 pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2122 vm_pagequeue_lock(pq);
2124 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2125 vm_pagequeue_cnt_inc(pq);
2126 vm_pagequeue_unlock(pq);
2132 * Move the given page to the tail of its current page queue.
2134 * The page must be locked.
2137 vm_page_requeue(vm_page_t m)
2139 struct vm_pagequeue *pq;
2141 vm_page_lock_assert(m, MA_OWNED);
2142 KASSERT(m->queue != PQ_NONE,
2143 ("vm_page_requeue: page %p is not queued", m));
2144 pq = vm_page_pagequeue(m);
2145 vm_pagequeue_lock(pq);
2146 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2147 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2148 vm_pagequeue_unlock(pq);
2152 * vm_page_requeue_locked:
2154 * Move the given page to the tail of its current page queue.
2156 * The page queue must be locked.
2159 vm_page_requeue_locked(vm_page_t m)
2161 struct vm_pagequeue *pq;
2163 KASSERT(m->queue != PQ_NONE,
2164 ("vm_page_requeue_locked: page %p is not queued", m));
2165 pq = vm_page_pagequeue(m);
2166 vm_pagequeue_assert_locked(pq);
2167 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2168 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2174 * Put the specified page on the active list (if appropriate).
2175 * Ensure that act_count is at least ACT_INIT but do not otherwise
2178 * The page must be locked.
2181 vm_page_activate(vm_page_t m)
2185 vm_page_lock_assert(m, MA_OWNED);
2186 if ((queue = m->queue) != PQ_ACTIVE) {
2187 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2188 if (m->act_count < ACT_INIT)
2189 m->act_count = ACT_INIT;
2190 if (queue != PQ_NONE)
2192 vm_page_enqueue(PQ_ACTIVE, m);
2194 KASSERT(queue == PQ_NONE,
2195 ("vm_page_activate: wired page %p is queued", m));
2197 if (m->act_count < ACT_INIT)
2198 m->act_count = ACT_INIT;
2203 * vm_page_free_wakeup:
2205 * Helper routine for vm_page_free_toq() and vm_page_cache(). This
2206 * routine is called when a page has been added to the cache or free
2209 * The page queues must be locked.
2212 vm_page_free_wakeup(void)
2215 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2217 * if pageout daemon needs pages, then tell it that there are
2220 if (vm_pageout_pages_needed &&
2221 cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
2222 wakeup(&vm_pageout_pages_needed);
2223 vm_pageout_pages_needed = 0;
2226 * wakeup processes that are waiting on memory if we hit a
2227 * high water mark. And wakeup scheduler process if we have
2228 * lots of memory. this process will swapin processes.
2230 if (vm_pages_needed && !vm_page_count_min()) {
2231 vm_pages_needed = 0;
2232 wakeup(&cnt.v_free_count);
2237 * Turn a cached page into a free page, by changing its attributes.
2238 * Keep the statistics up-to-date.
2240 * The free page queue must be locked.
2243 vm_page_cache_turn_free(vm_page_t m)
2246 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2250 /* Clear PG_CACHED and set PG_FREE. */
2251 m->flags ^= PG_CACHED | PG_FREE;
2252 KASSERT((m->flags & (PG_CACHED | PG_FREE)) == PG_FREE,
2253 ("vm_page_cache_free: page %p has inconsistent flags", m));
2254 cnt.v_cache_count--;
2255 vm_phys_freecnt_adj(m, 1);
2261 * Returns the given page to the free list,
2262 * disassociating it with any VM object.
2264 * The object must be locked. The page must be locked if it is managed.
2267 vm_page_free_toq(vm_page_t m)
2270 if ((m->oflags & VPO_UNMANAGED) == 0) {
2271 vm_page_lock_assert(m, MA_OWNED);
2272 KASSERT(!pmap_page_is_mapped(m),
2273 ("vm_page_free_toq: freeing mapped page %p", m));
2275 KASSERT(m->queue == PQ_NONE,
2276 ("vm_page_free_toq: unmanaged page %p is queued", m));
2277 PCPU_INC(cnt.v_tfree);
2279 if (VM_PAGE_IS_FREE(m))
2280 panic("vm_page_free: freeing free page %p", m);
2281 else if (vm_page_sbusied(m))
2282 panic("vm_page_free: freeing busy page %p", m);
2285 * Unqueue, then remove page. Note that we cannot destroy
2286 * the page here because we do not want to call the pager's
2287 * callback routine until after we've put the page on the
2288 * appropriate free queue.
2294 * If fictitious remove object association and
2295 * return, otherwise delay object association removal.
2297 if ((m->flags & PG_FICTITIOUS) != 0) {
2304 if (m->wire_count != 0)
2305 panic("vm_page_free: freeing wired page %p", m);
2306 if (m->hold_count != 0) {
2307 m->flags &= ~PG_ZERO;
2308 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2309 ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
2310 m->flags |= PG_UNHOLDFREE;
2313 * Restore the default memory attribute to the page.
2315 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2316 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2319 * Insert the page into the physical memory allocator's
2320 * cache/free page queues.
2322 mtx_lock(&vm_page_queue_free_mtx);
2323 m->flags |= PG_FREE;
2324 vm_phys_freecnt_adj(m, 1);
2325 #if VM_NRESERVLEVEL > 0
2326 if (!vm_reserv_free_page(m))
2330 vm_phys_free_pages(m, 0);
2331 if ((m->flags & PG_ZERO) != 0)
2332 ++vm_page_zero_count;
2334 vm_page_zero_idle_wakeup();
2335 vm_page_free_wakeup();
2336 mtx_unlock(&vm_page_queue_free_mtx);
2343 * Mark this page as wired down by yet
2344 * another map, removing it from paging queues
2347 * If the page is fictitious, then its wire count must remain one.
2349 * The page must be locked.
2352 vm_page_wire(vm_page_t m)
2356 * Only bump the wire statistics if the page is not already wired,
2357 * and only unqueue the page if it is on some queue (if it is unmanaged
2358 * it is already off the queues).
2360 vm_page_lock_assert(m, MA_OWNED);
2361 if ((m->flags & PG_FICTITIOUS) != 0) {
2362 KASSERT(m->wire_count == 1,
2363 ("vm_page_wire: fictitious page %p's wire count isn't one",
2367 if (m->wire_count == 0) {
2368 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
2369 m->queue == PQ_NONE,
2370 ("vm_page_wire: unmanaged page %p is queued", m));
2372 atomic_add_int(&cnt.v_wire_count, 1);
2375 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
2381 * Release one wiring of the specified page, potentially enabling it to be
2382 * paged again. If paging is enabled, then the value of the parameter
2383 * "activate" determines to which queue the page is added. If "activate" is
2384 * non-zero, then the page is added to the active queue. Otherwise, it is
2385 * added to the inactive queue.
2387 * However, unless the page belongs to an object, it is not enqueued because
2388 * it cannot be paged out.
2390 * If a page is fictitious, then its wire count must always be one.
2392 * A managed page must be locked.
2395 vm_page_unwire(vm_page_t m, int activate)
2398 if ((m->oflags & VPO_UNMANAGED) == 0)
2399 vm_page_lock_assert(m, MA_OWNED);
2400 if ((m->flags & PG_FICTITIOUS) != 0) {
2401 KASSERT(m->wire_count == 1,
2402 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
2405 if (m->wire_count > 0) {
2407 if (m->wire_count == 0) {
2408 atomic_subtract_int(&cnt.v_wire_count, 1);
2409 if ((m->oflags & VPO_UNMANAGED) != 0 ||
2413 m->flags &= ~PG_WINATCFLS;
2414 vm_page_enqueue(activate ? PQ_ACTIVE : PQ_INACTIVE, m);
2417 panic("vm_page_unwire: page %p's wire count is zero", m);
2421 * Move the specified page to the inactive queue.
2423 * Many pages placed on the inactive queue should actually go
2424 * into the cache, but it is difficult to figure out which. What
2425 * we do instead, if the inactive target is well met, is to put
2426 * clean pages at the head of the inactive queue instead of the tail.
2427 * This will cause them to be moved to the cache more quickly and
2428 * if not actively re-referenced, reclaimed more quickly. If we just
2429 * stick these pages at the end of the inactive queue, heavy filesystem
2430 * meta-data accesses can cause an unnecessary paging load on memory bound
2431 * processes. This optimization causes one-time-use metadata to be
2432 * reused more quickly.
2434 * Normally athead is 0 resulting in LRU operation. athead is set
2435 * to 1 if we want this page to be 'as if it were placed in the cache',
2436 * except without unmapping it from the process address space.
2438 * The page must be locked.
2441 _vm_page_deactivate(vm_page_t m, int athead)
2443 struct vm_pagequeue *pq;
2446 vm_page_assert_locked(m);
2449 * Ignore if the page is already inactive, unless it is unlikely to be
2452 if ((queue = m->queue) == PQ_INACTIVE && !athead)
2454 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2455 pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
2456 /* Avoid multiple acquisitions of the inactive queue lock. */
2457 if (queue == PQ_INACTIVE) {
2458 vm_pagequeue_lock(pq);
2459 vm_page_dequeue_locked(m);
2461 if (queue != PQ_NONE)
2463 m->flags &= ~PG_WINATCFLS;
2464 vm_pagequeue_lock(pq);
2466 m->queue = PQ_INACTIVE;
2468 TAILQ_INSERT_HEAD(&pq->pq_pl, m, plinks.q);
2470 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2471 vm_pagequeue_cnt_inc(pq);
2472 vm_pagequeue_unlock(pq);
2477 * Move the specified page to the inactive queue.
2479 * The page must be locked.
2482 vm_page_deactivate(vm_page_t m)
2485 _vm_page_deactivate(m, 0);
2489 * vm_page_try_to_cache:
2491 * Returns 0 on failure, 1 on success
2494 vm_page_try_to_cache(vm_page_t m)
2497 vm_page_lock_assert(m, MA_OWNED);
2498 VM_OBJECT_ASSERT_WLOCKED(m->object);
2499 if (m->dirty || m->hold_count || m->wire_count ||
2500 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
2510 * vm_page_try_to_free()
2512 * Attempt to free the page. If we cannot free it, we do nothing.
2513 * 1 is returned on success, 0 on failure.
2516 vm_page_try_to_free(vm_page_t m)
2519 vm_page_lock_assert(m, MA_OWNED);
2520 if (m->object != NULL)
2521 VM_OBJECT_ASSERT_WLOCKED(m->object);
2522 if (m->dirty || m->hold_count || m->wire_count ||
2523 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
2535 * Put the specified page onto the page cache queue (if appropriate).
2537 * The object and page must be locked.
2540 vm_page_cache(vm_page_t m)
2543 boolean_t cache_was_empty;
2545 vm_page_lock_assert(m, MA_OWNED);
2547 VM_OBJECT_ASSERT_WLOCKED(object);
2548 if (vm_page_busied(m) || (m->oflags & VPO_UNMANAGED) ||
2549 m->hold_count || m->wire_count)
2550 panic("vm_page_cache: attempting to cache busy page");
2551 KASSERT(!pmap_page_is_mapped(m),
2552 ("vm_page_cache: page %p is mapped", m));
2553 KASSERT(m->dirty == 0, ("vm_page_cache: page %p is dirty", m));
2554 if (m->valid == 0 || object->type == OBJT_DEFAULT ||
2555 (object->type == OBJT_SWAP &&
2556 !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
2558 * Hypothesis: A cache-elgible page belonging to a
2559 * default object or swap object but without a backing
2560 * store must be zero filled.
2565 KASSERT((m->flags & PG_CACHED) == 0,
2566 ("vm_page_cache: page %p is already cached", m));
2569 * Remove the page from the paging queues.
2574 * Remove the page from the object's collection of resident
2577 vm_radix_remove(&object->rtree, m->pindex);
2578 TAILQ_REMOVE(&object->memq, m, listq);
2579 object->resident_page_count--;
2582 * Restore the default memory attribute to the page.
2584 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2585 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2588 * Insert the page into the object's collection of cached pages
2589 * and the physical memory allocator's cache/free page queues.
2591 m->flags &= ~PG_ZERO;
2592 mtx_lock(&vm_page_queue_free_mtx);
2593 cache_was_empty = vm_radix_is_empty(&object->cache);
2594 if (vm_radix_insert(&object->cache, m)) {
2595 mtx_unlock(&vm_page_queue_free_mtx);
2596 if (object->type == OBJT_VNODE &&
2597 object->resident_page_count == 0)
2598 vdrop(object->handle);
2605 * The above call to vm_radix_insert() could reclaim the one pre-
2606 * existing cached page from this object, resulting in a call to
2609 if (!cache_was_empty)
2610 cache_was_empty = vm_radix_is_singleton(&object->cache);
2612 m->flags |= PG_CACHED;
2613 cnt.v_cache_count++;
2614 PCPU_INC(cnt.v_tcached);
2615 #if VM_NRESERVLEVEL > 0
2616 if (!vm_reserv_free_page(m)) {
2620 vm_phys_set_pool(VM_FREEPOOL_CACHE, m, 0);
2621 vm_phys_free_pages(m, 0);
2623 vm_page_free_wakeup();
2624 mtx_unlock(&vm_page_queue_free_mtx);
2627 * Increment the vnode's hold count if this is the object's only
2628 * cached page. Decrement the vnode's hold count if this was
2629 * the object's only resident page.
2631 if (object->type == OBJT_VNODE) {
2632 if (cache_was_empty && object->resident_page_count != 0)
2633 vhold(object->handle);
2634 else if (!cache_was_empty && object->resident_page_count == 0)
2635 vdrop(object->handle);
2642 * Deactivate or do nothing, as appropriate. This routine is used
2643 * by madvise() and vop_stdadvise().
2645 * The object and page must be locked.
2648 vm_page_advise(vm_page_t m, int advice)
2651 vm_page_assert_locked(m);
2652 VM_OBJECT_ASSERT_WLOCKED(m->object);
2653 if (advice == MADV_FREE)
2655 * Mark the page clean. This will allow the page to be freed
2656 * up by the system. However, such pages are often reused
2657 * quickly by malloc() so we do not do anything that would
2658 * cause a page fault if we can help it.
2660 * Specifically, we do not try to actually free the page now
2661 * nor do we try to put it in the cache (which would cause a
2662 * page fault on reuse).
2664 * But we do make the page as freeable as we can without
2665 * actually taking the step of unmapping it.
2668 else if (advice != MADV_DONTNEED)
2672 * Clear any references to the page. Otherwise, the page daemon will
2673 * immediately reactivate the page.
2675 vm_page_aflag_clear(m, PGA_REFERENCED);
2677 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
2681 * Place clean pages at the head of the inactive queue rather than the
2682 * tail, thus defeating the queue's LRU operation and ensuring that the
2683 * page will be reused quickly.
2685 _vm_page_deactivate(m, m->dirty == 0);
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);
2715 * Reference the page before unlocking and
2716 * sleeping so that the page daemon is less
2717 * likely to reclaim it.
2719 vm_page_aflag_set(m, PGA_REFERENCED);
2721 VM_OBJECT_WUNLOCK(object);
2722 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
2723 VM_ALLOC_IGN_SBUSY) != 0);
2724 VM_OBJECT_WLOCK(object);
2727 if ((allocflags & VM_ALLOC_WIRED) != 0) {
2733 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
2735 if ((allocflags & VM_ALLOC_SBUSY) != 0)
2740 m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_IGN_SBUSY);
2742 VM_OBJECT_WUNLOCK(object);
2744 VM_OBJECT_WLOCK(object);
2746 } else if (m->valid != 0)
2748 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
2754 * Mapping function for valid or dirty bits in a page.
2756 * Inputs are required to range within a page.
2759 vm_page_bits(int base, int size)
2765 base + size <= PAGE_SIZE,
2766 ("vm_page_bits: illegal base/size %d/%d", base, size)
2769 if (size == 0) /* handle degenerate case */
2772 first_bit = base >> DEV_BSHIFT;
2773 last_bit = (base + size - 1) >> DEV_BSHIFT;
2775 return (((vm_page_bits_t)2 << last_bit) -
2776 ((vm_page_bits_t)1 << first_bit));
2780 * vm_page_set_valid_range:
2782 * Sets portions of a page valid. The arguments are expected
2783 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2784 * of any partial chunks touched by the range. The invalid portion of
2785 * such chunks will be zeroed.
2787 * (base + size) must be less then or equal to PAGE_SIZE.
2790 vm_page_set_valid_range(vm_page_t m, int base, int size)
2794 VM_OBJECT_ASSERT_WLOCKED(m->object);
2795 if (size == 0) /* handle degenerate case */
2799 * If the base is not DEV_BSIZE aligned and the valid
2800 * bit is clear, we have to zero out a portion of the
2803 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2804 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2805 pmap_zero_page_area(m, frag, base - frag);
2808 * If the ending offset is not DEV_BSIZE aligned and the
2809 * valid bit is clear, we have to zero out a portion of
2812 endoff = base + size;
2813 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2814 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2815 pmap_zero_page_area(m, endoff,
2816 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2819 * Assert that no previously invalid block that is now being validated
2822 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
2823 ("vm_page_set_valid_range: page %p is dirty", m));
2826 * Set valid bits inclusive of any overlap.
2828 m->valid |= vm_page_bits(base, size);
2832 * Clear the given bits from the specified page's dirty field.
2834 static __inline void
2835 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
2838 #if PAGE_SIZE < 16384
2843 * If the object is locked and the page is neither exclusive busy nor
2844 * write mapped, then the page's dirty field cannot possibly be
2845 * set by a concurrent pmap operation.
2847 VM_OBJECT_ASSERT_WLOCKED(m->object);
2848 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
2849 m->dirty &= ~pagebits;
2852 * The pmap layer can call vm_page_dirty() without
2853 * holding a distinguished lock. The combination of
2854 * the object's lock and an atomic operation suffice
2855 * to guarantee consistency of the page dirty field.
2857 * For PAGE_SIZE == 32768 case, compiler already
2858 * properly aligns the dirty field, so no forcible
2859 * alignment is needed. Only require existence of
2860 * atomic_clear_64 when page size is 32768.
2862 addr = (uintptr_t)&m->dirty;
2863 #if PAGE_SIZE == 32768
2864 atomic_clear_64((uint64_t *)addr, pagebits);
2865 #elif PAGE_SIZE == 16384
2866 atomic_clear_32((uint32_t *)addr, pagebits);
2867 #else /* PAGE_SIZE <= 8192 */
2869 * Use a trick to perform a 32-bit atomic on the
2870 * containing aligned word, to not depend on the existence
2871 * of atomic_clear_{8, 16}.
2873 shift = addr & (sizeof(uint32_t) - 1);
2874 #if BYTE_ORDER == BIG_ENDIAN
2875 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
2879 addr &= ~(sizeof(uint32_t) - 1);
2880 atomic_clear_32((uint32_t *)addr, pagebits << shift);
2881 #endif /* PAGE_SIZE */
2886 * vm_page_set_validclean:
2888 * Sets portions of a page valid and clean. The arguments are expected
2889 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2890 * of any partial chunks touched by the range. The invalid portion of
2891 * such chunks will be zero'd.
2893 * (base + size) must be less then or equal to PAGE_SIZE.
2896 vm_page_set_validclean(vm_page_t m, int base, int size)
2898 vm_page_bits_t oldvalid, pagebits;
2901 VM_OBJECT_ASSERT_WLOCKED(m->object);
2902 if (size == 0) /* handle degenerate case */
2906 * If the base is not DEV_BSIZE aligned and the valid
2907 * bit is clear, we have to zero out a portion of the
2910 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2911 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
2912 pmap_zero_page_area(m, frag, base - frag);
2915 * If the ending offset is not DEV_BSIZE aligned and the
2916 * valid bit is clear, we have to zero out a portion of
2919 endoff = base + size;
2920 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2921 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
2922 pmap_zero_page_area(m, endoff,
2923 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2926 * Set valid, clear dirty bits. If validating the entire
2927 * page we can safely clear the pmap modify bit. We also
2928 * use this opportunity to clear the VPO_NOSYNC flag. If a process
2929 * takes a write fault on a MAP_NOSYNC memory area the flag will
2932 * We set valid bits inclusive of any overlap, but we can only
2933 * clear dirty bits for DEV_BSIZE chunks that are fully within
2936 oldvalid = m->valid;
2937 pagebits = vm_page_bits(base, size);
2938 m->valid |= pagebits;
2940 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
2941 frag = DEV_BSIZE - frag;
2947 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
2949 if (base == 0 && size == PAGE_SIZE) {
2951 * The page can only be modified within the pmap if it is
2952 * mapped, and it can only be mapped if it was previously
2955 if (oldvalid == VM_PAGE_BITS_ALL)
2957 * Perform the pmap_clear_modify() first. Otherwise,
2958 * a concurrent pmap operation, such as
2959 * pmap_protect(), could clear a modification in the
2960 * pmap and set the dirty field on the page before
2961 * pmap_clear_modify() had begun and after the dirty
2962 * field was cleared here.
2964 pmap_clear_modify(m);
2966 m->oflags &= ~VPO_NOSYNC;
2967 } else if (oldvalid != VM_PAGE_BITS_ALL)
2968 m->dirty &= ~pagebits;
2970 vm_page_clear_dirty_mask(m, pagebits);
2974 vm_page_clear_dirty(vm_page_t m, int base, int size)
2977 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
2981 * vm_page_set_invalid:
2983 * Invalidates DEV_BSIZE'd chunks within a page. Both the
2984 * valid and dirty bits for the effected areas are cleared.
2987 vm_page_set_invalid(vm_page_t m, int base, int size)
2989 vm_page_bits_t bits;
2993 VM_OBJECT_ASSERT_WLOCKED(object);
2994 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
2995 size >= object->un_pager.vnp.vnp_size)
2996 bits = VM_PAGE_BITS_ALL;
2998 bits = vm_page_bits(base, size);
2999 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
3002 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3003 !pmap_page_is_mapped(m),
3004 ("vm_page_set_invalid: page %p is mapped", m));
3010 * vm_page_zero_invalid()
3012 * The kernel assumes that the invalid portions of a page contain
3013 * garbage, but such pages can be mapped into memory by user code.
3014 * When this occurs, we must zero out the non-valid portions of the
3015 * page so user code sees what it expects.
3017 * Pages are most often semi-valid when the end of a file is mapped
3018 * into memory and the file's size is not page aligned.
3021 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3026 VM_OBJECT_ASSERT_WLOCKED(m->object);
3028 * Scan the valid bits looking for invalid sections that
3029 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
3030 * valid bit may be set ) have already been zeroed by
3031 * vm_page_set_validclean().
3033 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3034 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3035 (m->valid & ((vm_page_bits_t)1 << i))) {
3037 pmap_zero_page_area(m,
3038 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3045 * setvalid is TRUE when we can safely set the zero'd areas
3046 * as being valid. We can do this if there are no cache consistancy
3047 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3050 m->valid = VM_PAGE_BITS_ALL;
3056 * Is (partial) page valid? Note that the case where size == 0
3057 * will return FALSE in the degenerate case where the page is
3058 * entirely invalid, and TRUE otherwise.
3061 vm_page_is_valid(vm_page_t m, int base, int size)
3063 vm_page_bits_t bits;
3065 VM_OBJECT_ASSERT_LOCKED(m->object);
3066 bits = vm_page_bits(base, size);
3067 return (m->valid != 0 && (m->valid & bits) == bits);
3071 * vm_page_ps_is_valid:
3073 * Returns TRUE if the entire (super)page is valid and FALSE otherwise.
3076 vm_page_ps_is_valid(vm_page_t m)
3080 VM_OBJECT_ASSERT_LOCKED(m->object);
3081 npages = atop(pagesizes[m->psind]);
3084 * The physically contiguous pages that make up a superpage, i.e., a
3085 * page with a page size index ("psind") greater than zero, will
3086 * occupy adjacent entries in vm_page_array[].
3088 for (i = 0; i < npages; i++) {
3089 if (m[i].valid != VM_PAGE_BITS_ALL)
3096 * Set the page's dirty bits if the page is modified.
3099 vm_page_test_dirty(vm_page_t m)
3102 VM_OBJECT_ASSERT_WLOCKED(m->object);
3103 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3108 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3111 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3115 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3118 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3122 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3125 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3128 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3130 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3133 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3137 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3140 mtx_assert_(vm_page_lockptr(m), a, file, line);
3146 vm_page_object_lock_assert(vm_page_t m)
3150 * Certain of the page's fields may only be modified by the
3151 * holder of the containing object's lock or the exclusive busy.
3152 * holder. Unfortunately, the holder of the write busy is
3153 * not recorded, and thus cannot be checked here.
3155 if (m->object != NULL && !vm_page_xbusied(m))
3156 VM_OBJECT_ASSERT_WLOCKED(m->object);
3160 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3163 if ((bits & PGA_WRITEABLE) == 0)
3167 * The PGA_WRITEABLE flag can only be set if the page is
3168 * managed, is exclusively busied or the object is locked.
3169 * Currently, this flag is only set by pmap_enter().
3171 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3172 ("PGA_WRITEABLE on unmanaged page"));
3173 if (!vm_page_xbusied(m))
3174 VM_OBJECT_ASSERT_LOCKED(m->object);
3178 #include "opt_ddb.h"
3180 #include <sys/kernel.h>
3182 #include <ddb/ddb.h>
3184 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3186 db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
3187 db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
3188 db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
3189 db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
3190 db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
3191 db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
3192 db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
3193 db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
3194 db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
3195 db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
3198 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3202 db_printf("pq_free %d pq_cache %d\n",
3203 cnt.v_free_count, cnt.v_cache_count);
3204 for (dom = 0; dom < vm_ndomains; dom++) {
3206 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pass %d\n",
3208 vm_dom[dom].vmd_page_count,
3209 vm_dom[dom].vmd_free_count,
3210 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3211 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
3212 vm_dom[dom].vmd_pass);
3216 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3222 db_printf("show pginfo addr\n");
3226 phys = strchr(modif, 'p') != NULL;
3228 m = PHYS_TO_VM_PAGE(addr);
3230 m = (vm_page_t)addr;
3232 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3233 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3234 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3235 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3236 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);