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/linker.h>
95 #include <sys/malloc.h>
97 #include <sys/msgbuf.h>
98 #include <sys/mutex.h>
100 #include <sys/rwlock.h>
101 #include <sys/sbuf.h>
102 #include <sys/sysctl.h>
103 #include <sys/vmmeter.h>
104 #include <sys/vnode.h>
108 #include <vm/vm_param.h>
109 #include <vm/vm_kern.h>
110 #include <vm/vm_object.h>
111 #include <vm/vm_page.h>
112 #include <vm/vm_pageout.h>
113 #include <vm/vm_pager.h>
114 #include <vm/vm_phys.h>
115 #include <vm/vm_radix.h>
116 #include <vm/vm_reserv.h>
117 #include <vm/vm_extern.h>
119 #include <vm/uma_int.h>
121 #include <machine/md_var.h>
124 * Associated with page of user-allocatable memory is a
128 struct vm_domain vm_dom[MAXMEMDOM];
129 struct mtx_padalign vm_page_queue_free_mtx;
131 struct mtx_padalign pa_lock[PA_LOCK_COUNT];
133 vm_page_t vm_page_array;
134 long vm_page_array_size;
136 int vm_page_zero_count;
138 static int boot_pages = UMA_BOOT_PAGES;
139 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
141 "number of pages allocated for bootstrapping the VM system");
143 static int pa_tryrelock_restart;
144 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
145 &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
147 static TAILQ_HEAD(, vm_page) blacklist_head;
148 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
149 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
150 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
152 /* Is the page daemon waiting for free pages? */
153 static int vm_pageout_pages_needed;
155 static uma_zone_t fakepg_zone;
157 static struct vnode *vm_page_alloc_init(vm_page_t m);
158 static void vm_page_cache_turn_free(vm_page_t m);
159 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
160 static void vm_page_enqueue(uint8_t queue, vm_page_t m);
161 static void vm_page_init_fakepg(void *dummy);
162 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
163 vm_pindex_t pindex, vm_page_t mpred);
164 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
167 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init_fakepg, NULL);
170 vm_page_init_fakepg(void *dummy)
173 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
174 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
177 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
178 #if PAGE_SIZE == 32768
180 CTASSERT(sizeof(u_long) >= 8);
185 * Try to acquire a physical address lock while a pmap is locked. If we
186 * fail to trylock we unlock and lock the pmap directly and cache the
187 * locked pa in *locked. The caller should then restart their loop in case
188 * the virtual to physical mapping has changed.
191 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
198 PA_LOCK_ASSERT(lockpa, MA_OWNED);
199 if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
206 atomic_add_int(&pa_tryrelock_restart, 1);
215 * Sets the page size, perhaps based upon the memory
216 * size. Must be called before any use of page-size
217 * dependent functions.
220 vm_set_page_size(void)
222 if (vm_cnt.v_page_size == 0)
223 vm_cnt.v_page_size = PAGE_SIZE;
224 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
225 panic("vm_set_page_size: page size not a power of two");
229 * vm_page_blacklist_next:
231 * Find the next entry in the provided string of blacklist
232 * addresses. Entries are separated by space, comma, or newline.
233 * If an invalid integer is encountered then the rest of the
234 * string is skipped. Updates the list pointer to the next
235 * character, or NULL if the string is exhausted or invalid.
238 vm_page_blacklist_next(char **list, char *end)
243 if (list == NULL || *list == NULL)
251 * If there's no end pointer then the buffer is coming from
252 * the kenv and we know it's null-terminated.
255 end = *list + strlen(*list);
257 /* Ensure that strtoq() won't walk off the end */
259 if (*end == '\n' || *end == ' ' || *end == ',')
262 printf("Blacklist not terminated, skipping\n");
268 for (pos = *list; *pos != '\0'; pos = cp) {
269 bad = strtoq(pos, &cp, 0);
270 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
279 if (*cp == '\0' || ++cp >= end)
283 return (trunc_page(bad));
285 printf("Garbage in RAM blacklist, skipping\n");
291 * vm_page_blacklist_check:
293 * Iterate through the provided string of blacklist addresses, pulling
294 * each entry out of the physical allocator free list and putting it
295 * onto a list for reporting via the vm.page_blacklist sysctl.
298 vm_page_blacklist_check(char *list, char *end)
306 while (next != NULL) {
307 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
309 m = vm_phys_paddr_to_vm_page(pa);
312 mtx_lock(&vm_page_queue_free_mtx);
313 ret = vm_phys_unfree_page(m);
314 mtx_unlock(&vm_page_queue_free_mtx);
316 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
318 printf("Skipping page with pa 0x%jx\n",
325 * vm_page_blacklist_load:
327 * Search for a special module named "ram_blacklist". It'll be a
328 * plain text file provided by the user via the loader directive
332 vm_page_blacklist_load(char **list, char **end)
341 mod = preload_search_by_type("ram_blacklist");
343 ptr = preload_fetch_addr(mod);
344 len = preload_fetch_size(mod);
355 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
362 error = sysctl_wire_old_buffer(req, 0);
365 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
366 TAILQ_FOREACH(m, &blacklist_head, listq) {
367 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
368 (uintmax_t)m->phys_addr);
371 error = sbuf_finish(&sbuf);
377 vm_page_domain_init(struct vm_domain *vmd)
379 struct vm_pagequeue *pq;
382 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
383 "vm inactive pagequeue";
384 *__DECONST(int **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_vcnt) =
385 &vm_cnt.v_inactive_count;
386 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
387 "vm active pagequeue";
388 *__DECONST(int **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_vcnt) =
389 &vm_cnt.v_active_count;
390 vmd->vmd_page_count = 0;
391 vmd->vmd_free_count = 0;
393 vmd->vmd_oom = FALSE;
395 for (i = 0; i < PQ_COUNT; i++) {
396 pq = &vmd->vmd_pagequeues[i];
397 TAILQ_INIT(&pq->pq_pl);
398 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
399 MTX_DEF | MTX_DUPOK);
406 * Initializes the resident memory module.
408 * Allocates memory for the page cells, and
409 * for the object/offset-to-page hash table headers.
410 * Each page cell is initialized and placed on the free list.
413 vm_page_startup(vm_offset_t vaddr)
416 vm_paddr_t page_range;
421 char *list, *listend;
423 vm_paddr_t biggestsize;
424 vm_paddr_t low_water, high_water;
429 vaddr = round_page(vaddr);
431 for (i = 0; phys_avail[i + 1]; i += 2) {
432 phys_avail[i] = round_page(phys_avail[i]);
433 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
436 low_water = phys_avail[0];
437 high_water = phys_avail[1];
439 for (i = 0; i < vm_phys_nsegs; i++) {
440 if (vm_phys_segs[i].start < low_water)
441 low_water = vm_phys_segs[i].start;
442 if (vm_phys_segs[i].end > high_water)
443 high_water = vm_phys_segs[i].end;
445 for (i = 0; phys_avail[i + 1]; i += 2) {
446 vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
448 if (size > biggestsize) {
452 if (phys_avail[i] < low_water)
453 low_water = phys_avail[i];
454 if (phys_avail[i + 1] > high_water)
455 high_water = phys_avail[i + 1];
458 end = phys_avail[biggestone+1];
461 * Initialize the page and queue locks.
463 mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
464 for (i = 0; i < PA_LOCK_COUNT; i++)
465 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
466 for (i = 0; i < vm_ndomains; i++)
467 vm_page_domain_init(&vm_dom[i]);
470 * Allocate memory for use when boot strapping the kernel memory
473 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
474 * manually fetch the value.
476 TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
477 new_end = end - (boot_pages * UMA_SLAB_SIZE);
478 new_end = trunc_page(new_end);
479 mapped = pmap_map(&vaddr, new_end, end,
480 VM_PROT_READ | VM_PROT_WRITE);
481 bzero((void *)mapped, end - new_end);
482 uma_startup((void *)mapped, boot_pages);
484 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
485 defined(__i386__) || defined(__mips__)
487 * Allocate a bitmap to indicate that a random physical page
488 * needs to be included in a minidump.
490 * The amd64 port needs this to indicate which direct map pages
491 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
493 * However, i386 still needs this workspace internally within the
494 * minidump code. In theory, they are not needed on i386, but are
495 * included should the sf_buf code decide to use them.
498 for (i = 0; dump_avail[i + 1] != 0; i += 2)
499 if (dump_avail[i + 1] > last_pa)
500 last_pa = dump_avail[i + 1];
501 page_range = last_pa / PAGE_SIZE;
502 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
503 new_end -= vm_page_dump_size;
504 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
505 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
506 bzero((void *)vm_page_dump, vm_page_dump_size);
510 * Request that the physical pages underlying the message buffer be
511 * included in a crash dump. Since the message buffer is accessed
512 * through the direct map, they are not automatically included.
514 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
515 last_pa = pa + round_page(msgbufsize);
516 while (pa < last_pa) {
522 * Compute the number of pages of memory that will be available for
523 * use (taking into account the overhead of a page structure per
526 first_page = low_water / PAGE_SIZE;
527 #ifdef VM_PHYSSEG_SPARSE
529 for (i = 0; i < vm_phys_nsegs; i++) {
530 page_range += atop(vm_phys_segs[i].end -
531 vm_phys_segs[i].start);
533 for (i = 0; phys_avail[i + 1] != 0; i += 2)
534 page_range += atop(phys_avail[i + 1] - phys_avail[i]);
535 #elif defined(VM_PHYSSEG_DENSE)
536 page_range = high_water / PAGE_SIZE - first_page;
538 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
543 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
548 * Initialize the mem entry structures now, and put them in the free
551 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
552 mapped = pmap_map(&vaddr, new_end, end,
553 VM_PROT_READ | VM_PROT_WRITE);
554 vm_page_array = (vm_page_t) mapped;
555 #if VM_NRESERVLEVEL > 0
557 * Allocate memory for the reservation management system's data
560 new_end = vm_reserv_startup(&vaddr, new_end, high_water);
562 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
564 * pmap_map on arm64, amd64, and mips can come out of the direct-map,
565 * not kvm like i386, so the pages must be tracked for a crashdump to
566 * include this data. This includes the vm_page_array and the early
567 * UMA bootstrap pages.
569 for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
572 phys_avail[biggestone + 1] = new_end;
575 * Add physical memory segments corresponding to the available
578 for (i = 0; phys_avail[i + 1] != 0; i += 2)
579 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
582 * Clear all of the page structures
584 bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
585 for (i = 0; i < page_range; i++)
586 vm_page_array[i].order = VM_NFREEORDER;
587 vm_page_array_size = page_range;
590 * Initialize the physical memory allocator.
595 * Add every available physical page that is not blacklisted to
598 vm_cnt.v_page_count = 0;
599 vm_cnt.v_free_count = 0;
600 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
602 last_pa = phys_avail[i + 1];
603 while (pa < last_pa) {
604 vm_phys_add_page(pa);
609 TAILQ_INIT(&blacklist_head);
610 vm_page_blacklist_load(&list, &listend);
611 vm_page_blacklist_check(list, listend);
613 list = kern_getenv("vm.blacklist");
614 vm_page_blacklist_check(list, NULL);
617 #if VM_NRESERVLEVEL > 0
619 * Initialize the reservation management system.
627 vm_page_reference(vm_page_t m)
630 vm_page_aflag_set(m, PGA_REFERENCED);
634 * vm_page_busy_downgrade:
636 * Downgrade an exclusive busy page into a single shared busy page.
639 vm_page_busy_downgrade(vm_page_t m)
643 vm_page_assert_xbusied(m);
647 x &= VPB_BIT_WAITERS;
648 if (atomic_cmpset_rel_int(&m->busy_lock,
649 VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1) | x))
657 * Return a positive value if the page is shared busied, 0 otherwise.
660 vm_page_sbusied(vm_page_t m)
665 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
671 * Shared unbusy a page.
674 vm_page_sunbusy(vm_page_t m)
678 vm_page_assert_sbusied(m);
682 if (VPB_SHARERS(x) > 1) {
683 if (atomic_cmpset_int(&m->busy_lock, x,
688 if ((x & VPB_BIT_WAITERS) == 0) {
689 KASSERT(x == VPB_SHARERS_WORD(1),
690 ("vm_page_sunbusy: invalid lock state"));
691 if (atomic_cmpset_int(&m->busy_lock,
692 VPB_SHARERS_WORD(1), VPB_UNBUSIED))
696 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
697 ("vm_page_sunbusy: invalid lock state for waiters"));
700 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
711 * vm_page_busy_sleep:
713 * Sleep and release the page lock, using the page pointer as wchan.
714 * This is used to implement the hard-path of busying mechanism.
716 * The given page must be locked.
719 vm_page_busy_sleep(vm_page_t m, const char *wmesg)
723 vm_page_lock_assert(m, MA_OWNED);
726 if (x == VPB_UNBUSIED) {
730 if ((x & VPB_BIT_WAITERS) == 0 &&
731 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS)) {
735 msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
741 * Try to shared busy a page.
742 * If the operation succeeds 1 is returned otherwise 0.
743 * The operation never sleeps.
746 vm_page_trysbusy(vm_page_t m)
752 if ((x & VPB_BIT_SHARED) == 0)
754 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
760 * vm_page_xunbusy_hard:
762 * Called after the first try the exclusive unbusy of a page failed.
763 * It is assumed that the waiters bit is on.
766 vm_page_xunbusy_hard(vm_page_t m)
769 vm_page_assert_xbusied(m);
772 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
780 * Wakeup anyone waiting for the page.
781 * The ownership bits do not change.
783 * The given page must be locked.
786 vm_page_flash(vm_page_t m)
790 vm_page_lock_assert(m, MA_OWNED);
794 if ((x & VPB_BIT_WAITERS) == 0)
796 if (atomic_cmpset_int(&m->busy_lock, x,
797 x & (~VPB_BIT_WAITERS)))
804 * Keep page from being freed by the page daemon
805 * much of the same effect as wiring, except much lower
806 * overhead and should be used only for *very* temporary
807 * holding ("wiring").
810 vm_page_hold(vm_page_t mem)
813 vm_page_lock_assert(mem, MA_OWNED);
818 vm_page_unhold(vm_page_t mem)
821 vm_page_lock_assert(mem, MA_OWNED);
822 KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
824 if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
825 vm_page_free_toq(mem);
829 * vm_page_unhold_pages:
831 * Unhold each of the pages that is referenced by the given array.
834 vm_page_unhold_pages(vm_page_t *ma, int count)
836 struct mtx *mtx, *new_mtx;
839 for (; count != 0; count--) {
841 * Avoid releasing and reacquiring the same page lock.
843 new_mtx = vm_page_lockptr(*ma);
844 if (mtx != new_mtx) {
858 PHYS_TO_VM_PAGE(vm_paddr_t pa)
862 #ifdef VM_PHYSSEG_SPARSE
863 m = vm_phys_paddr_to_vm_page(pa);
865 m = vm_phys_fictitious_to_vm_page(pa);
867 #elif defined(VM_PHYSSEG_DENSE)
871 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
872 m = &vm_page_array[pi - first_page];
875 return (vm_phys_fictitious_to_vm_page(pa));
877 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
884 * Create a fictitious page with the specified physical address and
885 * memory attribute. The memory attribute is the only the machine-
886 * dependent aspect of a fictitious page that must be initialized.
889 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
893 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
894 vm_page_initfake(m, paddr, memattr);
899 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
902 if ((m->flags & PG_FICTITIOUS) != 0) {
904 * The page's memattr might have changed since the
905 * previous initialization. Update the pmap to the
910 m->phys_addr = paddr;
912 /* Fictitious pages don't use "segind". */
913 m->flags = PG_FICTITIOUS;
914 /* Fictitious pages don't use "order" or "pool". */
915 m->oflags = VPO_UNMANAGED;
916 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
920 pmap_page_set_memattr(m, memattr);
926 * Release a fictitious page.
929 vm_page_putfake(vm_page_t m)
932 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
933 KASSERT((m->flags & PG_FICTITIOUS) != 0,
934 ("vm_page_putfake: bad page %p", m));
935 uma_zfree(fakepg_zone, m);
939 * vm_page_updatefake:
941 * Update the given fictitious page to the specified physical address and
945 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
948 KASSERT((m->flags & PG_FICTITIOUS) != 0,
949 ("vm_page_updatefake: bad page %p", m));
950 m->phys_addr = paddr;
951 pmap_page_set_memattr(m, memattr);
960 vm_page_free(vm_page_t m)
963 m->flags &= ~PG_ZERO;
970 * Free a page to the zerod-pages queue
973 vm_page_free_zero(vm_page_t m)
981 * Unbusy and handle the page queueing for a page from the VOP_GETPAGES()
982 * array which is not the request page.
985 vm_page_readahead_finish(vm_page_t m)
990 * Since the page is not the requested page, whether
991 * it should be activated or deactivated is not
992 * obvious. Empirical results have shown that
993 * deactivating the page is usually the best choice,
994 * unless the page is wanted by another thread.
997 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1000 vm_page_deactivate(m);
1005 * Free the completely invalid page. Such page state
1006 * occurs due to the short read operation which did
1007 * not covered our page at all, or in case when a read
1017 * vm_page_sleep_if_busy:
1019 * Sleep and release the page queues lock if the page is busied.
1020 * Returns TRUE if the thread slept.
1022 * The given page must be unlocked and object containing it must
1026 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1030 vm_page_lock_assert(m, MA_NOTOWNED);
1031 VM_OBJECT_ASSERT_WLOCKED(m->object);
1033 if (vm_page_busied(m)) {
1035 * The page-specific object must be cached because page
1036 * identity can change during the sleep, causing the
1037 * re-lock of a different object.
1038 * It is assumed that a reference to the object is already
1039 * held by the callers.
1043 VM_OBJECT_WUNLOCK(obj);
1044 vm_page_busy_sleep(m, msg);
1045 VM_OBJECT_WLOCK(obj);
1052 * vm_page_dirty_KBI: [ internal use only ]
1054 * Set all bits in the page's dirty field.
1056 * The object containing the specified page must be locked if the
1057 * call is made from the machine-independent layer.
1059 * See vm_page_clear_dirty_mask().
1061 * This function should only be called by vm_page_dirty().
1064 vm_page_dirty_KBI(vm_page_t m)
1067 /* These assertions refer to this operation by its public name. */
1068 KASSERT((m->flags & PG_CACHED) == 0,
1069 ("vm_page_dirty: page in cache!"));
1070 KASSERT(m->valid == VM_PAGE_BITS_ALL,
1071 ("vm_page_dirty: page is invalid!"));
1072 m->dirty = VM_PAGE_BITS_ALL;
1076 * vm_page_insert: [ internal use only ]
1078 * Inserts the given mem entry into the object and object list.
1080 * The object must be locked.
1083 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1087 VM_OBJECT_ASSERT_WLOCKED(object);
1088 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1089 return (vm_page_insert_after(m, object, pindex, mpred));
1093 * vm_page_insert_after:
1095 * Inserts the page "m" into the specified object at offset "pindex".
1097 * The page "mpred" must immediately precede the offset "pindex" within
1098 * the specified object.
1100 * The object must be locked.
1103 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1110 VM_OBJECT_ASSERT_WLOCKED(object);
1111 KASSERT(m->object == NULL,
1112 ("vm_page_insert_after: page already inserted"));
1113 if (mpred != NULL) {
1114 KASSERT(mpred->object == object,
1115 ("vm_page_insert_after: object doesn't contain mpred"));
1116 KASSERT(mpred->pindex < pindex,
1117 ("vm_page_insert_after: mpred doesn't precede pindex"));
1118 msucc = TAILQ_NEXT(mpred, listq);
1120 msucc = TAILQ_FIRST(&object->memq);
1122 KASSERT(msucc->pindex > pindex,
1123 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1126 * Record the object/offset pair in this page
1134 * Now link into the object's ordered list of backed pages.
1136 if (vm_radix_insert(&object->rtree, m)) {
1141 vm_page_insert_radixdone(m, object, mpred);
1146 * vm_page_insert_radixdone:
1148 * Complete page "m" insertion into the specified object after the
1149 * radix trie hooking.
1151 * The page "mpred" must precede the offset "m->pindex" within the
1154 * The object must be locked.
1157 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1160 VM_OBJECT_ASSERT_WLOCKED(object);
1161 KASSERT(object != NULL && m->object == object,
1162 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1163 if (mpred != NULL) {
1164 KASSERT(mpred->object == object,
1165 ("vm_page_insert_after: object doesn't contain mpred"));
1166 KASSERT(mpred->pindex < m->pindex,
1167 ("vm_page_insert_after: mpred doesn't precede pindex"));
1171 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1173 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1176 * Show that the object has one more resident page.
1178 object->resident_page_count++;
1181 * Hold the vnode until the last page is released.
1183 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1184 vhold(object->handle);
1187 * Since we are inserting a new and possibly dirty page,
1188 * update the object's OBJ_MIGHTBEDIRTY flag.
1190 if (pmap_page_is_write_mapped(m))
1191 vm_object_set_writeable_dirty(object);
1197 * Removes the given mem entry from the object/offset-page
1198 * table and the object page list, but do not invalidate/terminate
1199 * the backing store.
1201 * The object must be locked. The page must be locked if it is managed.
1204 vm_page_remove(vm_page_t m)
1209 if ((m->oflags & VPO_UNMANAGED) == 0)
1210 vm_page_lock_assert(m, MA_OWNED);
1211 if ((object = m->object) == NULL)
1213 VM_OBJECT_ASSERT_WLOCKED(object);
1214 if (vm_page_xbusied(m)) {
1216 if ((m->oflags & VPO_UNMANAGED) != 0 &&
1217 !mtx_owned(vm_page_lockptr(m))) {
1222 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1228 * Now remove from the object's list of backed pages.
1230 vm_radix_remove(&object->rtree, m->pindex);
1231 TAILQ_REMOVE(&object->memq, m, listq);
1234 * And show that the object has one fewer resident page.
1236 object->resident_page_count--;
1239 * The vnode may now be recycled.
1241 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1242 vdrop(object->handle);
1250 * Returns the page associated with the object/offset
1251 * pair specified; if none is found, NULL is returned.
1253 * The object must be locked.
1256 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1259 VM_OBJECT_ASSERT_LOCKED(object);
1260 return (vm_radix_lookup(&object->rtree, pindex));
1264 * vm_page_find_least:
1266 * Returns the page associated with the object with least pindex
1267 * greater than or equal to the parameter pindex, or NULL.
1269 * The object must be locked.
1272 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1276 VM_OBJECT_ASSERT_LOCKED(object);
1277 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1278 m = vm_radix_lookup_ge(&object->rtree, pindex);
1283 * Returns the given page's successor (by pindex) within the object if it is
1284 * resident; if none is found, NULL is returned.
1286 * The object must be locked.
1289 vm_page_next(vm_page_t m)
1293 VM_OBJECT_ASSERT_WLOCKED(m->object);
1294 if ((next = TAILQ_NEXT(m, listq)) != NULL &&
1295 next->pindex != m->pindex + 1)
1301 * Returns the given page's predecessor (by pindex) within the object if it is
1302 * resident; if none is found, NULL is returned.
1304 * The object must be locked.
1307 vm_page_prev(vm_page_t m)
1311 VM_OBJECT_ASSERT_WLOCKED(m->object);
1312 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
1313 prev->pindex != m->pindex - 1)
1319 * Uses the page mnew as a replacement for an existing page at index
1320 * pindex which must be already present in the object.
1322 * The existing page must not be on a paging queue.
1325 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1329 VM_OBJECT_ASSERT_WLOCKED(object);
1330 KASSERT(mnew->object == NULL,
1331 ("vm_page_replace: page already in object"));
1334 * This function mostly follows vm_page_insert() and
1335 * vm_page_remove() without the radix, object count and vnode
1336 * dance. Double check such functions for more comments.
1339 mnew->object = object;
1340 mnew->pindex = pindex;
1341 mold = vm_radix_replace(&object->rtree, mnew);
1342 KASSERT(mold->queue == PQ_NONE,
1343 ("vm_page_replace: mold is on a paging queue"));
1345 /* Keep the resident page list in sorted order. */
1346 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1347 TAILQ_REMOVE(&object->memq, mold, listq);
1349 mold->object = NULL;
1350 vm_page_xunbusy(mold);
1353 * The object's resident_page_count does not change because we have
1354 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1356 if (pmap_page_is_write_mapped(mnew))
1357 vm_object_set_writeable_dirty(object);
1364 * Move the given memory entry from its
1365 * current object to the specified target object/offset.
1367 * Note: swap associated with the page must be invalidated by the move. We
1368 * have to do this for several reasons: (1) we aren't freeing the
1369 * page, (2) we are dirtying the page, (3) the VM system is probably
1370 * moving the page from object A to B, and will then later move
1371 * the backing store from A to B and we can't have a conflict.
1373 * Note: we *always* dirty the page. It is necessary both for the
1374 * fact that we moved it, and because we may be invalidating
1375 * swap. If the page is on the cache, we have to deactivate it
1376 * or vm_page_dirty() will panic. Dirty pages are not allowed
1379 * The objects must be locked.
1382 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1387 VM_OBJECT_ASSERT_WLOCKED(new_object);
1389 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1390 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1391 ("vm_page_rename: pindex already renamed"));
1394 * Create a custom version of vm_page_insert() which does not depend
1395 * by m_prev and can cheat on the implementation aspects of the
1399 m->pindex = new_pindex;
1400 if (vm_radix_insert(&new_object->rtree, m)) {
1406 * The operation cannot fail anymore. The removal must happen before
1407 * the listq iterator is tainted.
1413 /* Return back to the new pindex to complete vm_page_insert(). */
1414 m->pindex = new_pindex;
1415 m->object = new_object;
1417 vm_page_insert_radixdone(m, new_object, mpred);
1423 * Convert all of the given object's cached pages that have a
1424 * pindex within the given range into free pages. If the value
1425 * zero is given for "end", then the range's upper bound is
1426 * infinity. If the given object is backed by a vnode and it
1427 * transitions from having one or more cached pages to none, the
1428 * vnode's hold count is reduced.
1431 vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1436 mtx_lock(&vm_page_queue_free_mtx);
1437 if (__predict_false(vm_radix_is_empty(&object->cache))) {
1438 mtx_unlock(&vm_page_queue_free_mtx);
1441 while ((m = vm_radix_lookup_ge(&object->cache, start)) != NULL) {
1442 if (end != 0 && m->pindex >= end)
1444 vm_radix_remove(&object->cache, m->pindex);
1445 vm_page_cache_turn_free(m);
1447 empty = vm_radix_is_empty(&object->cache);
1448 mtx_unlock(&vm_page_queue_free_mtx);
1449 if (object->type == OBJT_VNODE && empty)
1450 vdrop(object->handle);
1454 * Returns the cached page that is associated with the given
1455 * object and offset. If, however, none exists, returns NULL.
1457 * The free page queue must be locked.
1459 static inline vm_page_t
1460 vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
1463 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1464 return (vm_radix_lookup(&object->cache, pindex));
1468 * Remove the given cached page from its containing object's
1469 * collection of cached pages.
1471 * The free page queue must be locked.
1474 vm_page_cache_remove(vm_page_t m)
1477 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1478 KASSERT((m->flags & PG_CACHED) != 0,
1479 ("vm_page_cache_remove: page %p is not cached", m));
1480 vm_radix_remove(&m->object->cache, m->pindex);
1482 vm_cnt.v_cache_count--;
1486 * Transfer all of the cached pages with offset greater than or
1487 * equal to 'offidxstart' from the original object's cache to the
1488 * new object's cache. However, any cached pages with offset
1489 * greater than or equal to the new object's size are kept in the
1490 * original object. Initially, the new object's cache must be
1491 * empty. Offset 'offidxstart' in the original object must
1492 * correspond to offset zero in the new object.
1494 * The new object must be locked.
1497 vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1498 vm_object_t new_object)
1503 * Insertion into an object's collection of cached pages
1504 * requires the object to be locked. In contrast, removal does
1507 VM_OBJECT_ASSERT_WLOCKED(new_object);
1508 KASSERT(vm_radix_is_empty(&new_object->cache),
1509 ("vm_page_cache_transfer: object %p has cached pages",
1511 mtx_lock(&vm_page_queue_free_mtx);
1512 while ((m = vm_radix_lookup_ge(&orig_object->cache,
1513 offidxstart)) != NULL) {
1515 * Transfer all of the pages with offset greater than or
1516 * equal to 'offidxstart' from the original object's
1517 * cache to the new object's cache.
1519 if ((m->pindex - offidxstart) >= new_object->size)
1521 vm_radix_remove(&orig_object->cache, m->pindex);
1522 /* Update the page's object and offset. */
1523 m->object = new_object;
1524 m->pindex -= offidxstart;
1525 if (vm_radix_insert(&new_object->cache, m))
1526 vm_page_cache_turn_free(m);
1528 mtx_unlock(&vm_page_queue_free_mtx);
1532 * Returns TRUE if a cached page is associated with the given object and
1533 * offset, and FALSE otherwise.
1535 * The object must be locked.
1538 vm_page_is_cached(vm_object_t object, vm_pindex_t pindex)
1543 * Insertion into an object's collection of cached pages requires the
1544 * object to be locked. Therefore, if the object is locked and the
1545 * object's collection is empty, there is no need to acquire the free
1546 * page queues lock in order to prove that the specified page doesn't
1549 VM_OBJECT_ASSERT_WLOCKED(object);
1550 if (__predict_true(vm_object_cache_is_empty(object)))
1552 mtx_lock(&vm_page_queue_free_mtx);
1553 m = vm_page_cache_lookup(object, pindex);
1554 mtx_unlock(&vm_page_queue_free_mtx);
1561 * Allocate and return a page that is associated with the specified
1562 * object and offset pair. By default, this page is exclusive busied.
1564 * The caller must always specify an allocation class.
1566 * allocation classes:
1567 * VM_ALLOC_NORMAL normal process request
1568 * VM_ALLOC_SYSTEM system *really* needs a page
1569 * VM_ALLOC_INTERRUPT interrupt time request
1571 * optional allocation flags:
1572 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1573 * intends to allocate
1574 * VM_ALLOC_IFCACHED return page only if it is cached
1575 * VM_ALLOC_IFNOTCACHED return NULL, do not reactivate if the page
1577 * VM_ALLOC_NOBUSY do not exclusive busy the page
1578 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1579 * VM_ALLOC_NOOBJ page is not associated with an object and
1580 * should not be exclusive busy
1581 * VM_ALLOC_SBUSY shared busy the allocated page
1582 * VM_ALLOC_WIRED wire the allocated page
1583 * VM_ALLOC_ZERO prefer a zeroed page
1585 * This routine may not sleep.
1588 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1590 struct vnode *vp = NULL;
1591 vm_object_t m_object;
1593 int flags, req_class;
1595 mpred = 0; /* XXX: pacify gcc */
1596 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1597 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1598 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1599 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1600 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1603 VM_OBJECT_ASSERT_WLOCKED(object);
1605 req_class = req & VM_ALLOC_CLASS_MASK;
1608 * The page daemon is allowed to dig deeper into the free page list.
1610 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1611 req_class = VM_ALLOC_SYSTEM;
1613 if (object != NULL) {
1614 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1615 KASSERT(mpred == NULL || mpred->pindex != pindex,
1616 ("vm_page_alloc: pindex already allocated"));
1620 * The page allocation request can came from consumers which already
1621 * hold the free page queue mutex, like vm_page_insert() in
1624 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
1625 if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
1626 (req_class == VM_ALLOC_SYSTEM &&
1627 vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
1628 (req_class == VM_ALLOC_INTERRUPT &&
1629 vm_cnt.v_free_count + vm_cnt.v_cache_count > 0)) {
1631 * Allocate from the free queue if the number of free pages
1632 * exceeds the minimum for the request class.
1634 if (object != NULL &&
1635 (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1636 if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1637 mtx_unlock(&vm_page_queue_free_mtx);
1640 if (vm_phys_unfree_page(m))
1641 vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1642 #if VM_NRESERVLEVEL > 0
1643 else if (!vm_reserv_reactivate_page(m))
1647 panic("vm_page_alloc: cache page %p is missing"
1648 " from the free queue", m);
1649 } else if ((req & VM_ALLOC_IFCACHED) != 0) {
1650 mtx_unlock(&vm_page_queue_free_mtx);
1652 #if VM_NRESERVLEVEL > 0
1653 } else if (object == NULL || (object->flags & (OBJ_COLORED |
1654 OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1655 vm_reserv_alloc_page(object, pindex, mpred)) == NULL) {
1659 m = vm_phys_alloc_pages(object != NULL ?
1660 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1661 #if VM_NRESERVLEVEL > 0
1662 if (m == NULL && vm_reserv_reclaim_inactive()) {
1663 m = vm_phys_alloc_pages(object != NULL ?
1664 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1671 * Not allocatable, give up.
1673 mtx_unlock(&vm_page_queue_free_mtx);
1674 atomic_add_int(&vm_pageout_deficit,
1675 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1676 pagedaemon_wakeup();
1681 * At this point we had better have found a good page.
1683 KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1684 KASSERT(m->queue == PQ_NONE,
1685 ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1686 KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1687 KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1688 KASSERT(!vm_page_sbusied(m),
1689 ("vm_page_alloc: page %p is busy", m));
1690 KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1691 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1692 ("vm_page_alloc: page %p has unexpected memattr %d", m,
1693 pmap_page_get_memattr(m)));
1694 if ((m->flags & PG_CACHED) != 0) {
1695 KASSERT((m->flags & PG_ZERO) == 0,
1696 ("vm_page_alloc: cached page %p is PG_ZERO", m));
1697 KASSERT(m->valid != 0,
1698 ("vm_page_alloc: cached page %p is invalid", m));
1699 if (m->object == object && m->pindex == pindex)
1700 vm_cnt.v_reactivated++;
1703 m_object = m->object;
1704 vm_page_cache_remove(m);
1705 if (m_object->type == OBJT_VNODE &&
1706 vm_object_cache_is_empty(m_object))
1707 vp = m_object->handle;
1709 KASSERT(m->valid == 0,
1710 ("vm_page_alloc: free page %p is valid", m));
1711 vm_phys_freecnt_adj(m, -1);
1712 if ((m->flags & PG_ZERO) != 0)
1713 vm_page_zero_count--;
1715 mtx_unlock(&vm_page_queue_free_mtx);
1718 * Initialize the page. Only the PG_ZERO flag is inherited.
1721 if ((req & VM_ALLOC_ZERO) != 0)
1724 if ((req & VM_ALLOC_NODUMP) != 0)
1728 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1730 m->busy_lock = VPB_UNBUSIED;
1731 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1732 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1733 if ((req & VM_ALLOC_SBUSY) != 0)
1734 m->busy_lock = VPB_SHARERS_WORD(1);
1735 if (req & VM_ALLOC_WIRED) {
1737 * The page lock is not required for wiring a page until that
1738 * page is inserted into the object.
1740 atomic_add_int(&vm_cnt.v_wire_count, 1);
1745 if (object != NULL) {
1746 if (vm_page_insert_after(m, object, pindex, mpred)) {
1747 /* See the comment below about hold count. */
1750 pagedaemon_wakeup();
1751 if (req & VM_ALLOC_WIRED) {
1752 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1756 m->oflags = VPO_UNMANAGED;
1761 /* Ignore device objects; the pager sets "memattr" for them. */
1762 if (object->memattr != VM_MEMATTR_DEFAULT &&
1763 (object->flags & OBJ_FICTITIOUS) == 0)
1764 pmap_page_set_memattr(m, object->memattr);
1769 * The following call to vdrop() must come after the above call
1770 * to vm_page_insert() in case both affect the same object and
1771 * vnode. Otherwise, the affected vnode's hold count could
1772 * temporarily become zero.
1778 * Don't wakeup too often - wakeup the pageout daemon when
1779 * we would be nearly out of memory.
1781 if (vm_paging_needed())
1782 pagedaemon_wakeup();
1788 vm_page_alloc_contig_vdrop(struct spglist *lst)
1791 while (!SLIST_EMPTY(lst)) {
1792 vdrop((struct vnode *)SLIST_FIRST(lst)-> plinks.s.pv);
1793 SLIST_REMOVE_HEAD(lst, plinks.s.ss);
1798 * vm_page_alloc_contig:
1800 * Allocate a contiguous set of physical pages of the given size "npages"
1801 * from the free lists. All of the physical pages must be at or above
1802 * the given physical address "low" and below the given physical address
1803 * "high". The given value "alignment" determines the alignment of the
1804 * first physical page in the set. If the given value "boundary" is
1805 * non-zero, then the set of physical pages cannot cross any physical
1806 * address boundary that is a multiple of that value. Both "alignment"
1807 * and "boundary" must be a power of two.
1809 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1810 * then the memory attribute setting for the physical pages is configured
1811 * to the object's memory attribute setting. Otherwise, the memory
1812 * attribute setting for the physical pages is configured to "memattr",
1813 * overriding the object's memory attribute setting. However, if the
1814 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1815 * memory attribute setting for the physical pages cannot be configured
1816 * to VM_MEMATTR_DEFAULT.
1818 * The caller must always specify an allocation class.
1820 * allocation classes:
1821 * VM_ALLOC_NORMAL normal process request
1822 * VM_ALLOC_SYSTEM system *really* needs a page
1823 * VM_ALLOC_INTERRUPT interrupt time request
1825 * optional allocation flags:
1826 * VM_ALLOC_NOBUSY do not exclusive busy the page
1827 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1828 * VM_ALLOC_NOOBJ page is not associated with an object and
1829 * should not be exclusive busy
1830 * VM_ALLOC_SBUSY shared busy the allocated page
1831 * VM_ALLOC_WIRED wire the allocated page
1832 * VM_ALLOC_ZERO prefer a zeroed page
1834 * This routine may not sleep.
1837 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1838 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1839 vm_paddr_t boundary, vm_memattr_t memattr)
1842 struct spglist deferred_vdrop_list;
1843 vm_page_t m, m_tmp, m_ret;
1847 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1848 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1849 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1850 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1851 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1853 if (object != NULL) {
1854 VM_OBJECT_ASSERT_WLOCKED(object);
1855 KASSERT(object->type == OBJT_PHYS,
1856 ("vm_page_alloc_contig: object %p isn't OBJT_PHYS",
1859 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1860 req_class = req & VM_ALLOC_CLASS_MASK;
1863 * The page daemon is allowed to dig deeper into the free page list.
1865 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1866 req_class = VM_ALLOC_SYSTEM;
1868 SLIST_INIT(&deferred_vdrop_list);
1869 mtx_lock(&vm_page_queue_free_mtx);
1870 if (vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1871 vm_cnt.v_free_reserved || (req_class == VM_ALLOC_SYSTEM &&
1872 vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1873 vm_cnt.v_interrupt_free_min) || (req_class == VM_ALLOC_INTERRUPT &&
1874 vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages)) {
1875 #if VM_NRESERVLEVEL > 0
1877 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1878 (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1879 low, high, alignment, boundary)) == NULL)
1881 m_ret = vm_phys_alloc_contig(npages, low, high,
1882 alignment, boundary);
1884 mtx_unlock(&vm_page_queue_free_mtx);
1885 atomic_add_int(&vm_pageout_deficit, npages);
1886 pagedaemon_wakeup();
1890 for (m = m_ret; m < &m_ret[npages]; m++) {
1891 drop = vm_page_alloc_init(m);
1894 * Enqueue the vnode for deferred vdrop().
1896 m->plinks.s.pv = drop;
1897 SLIST_INSERT_HEAD(&deferred_vdrop_list, m,
1902 #if VM_NRESERVLEVEL > 0
1903 if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1908 mtx_unlock(&vm_page_queue_free_mtx);
1913 * Initialize the pages. Only the PG_ZERO flag is inherited.
1916 if ((req & VM_ALLOC_ZERO) != 0)
1918 if ((req & VM_ALLOC_NODUMP) != 0)
1920 if ((req & VM_ALLOC_WIRED) != 0)
1921 atomic_add_int(&vm_cnt.v_wire_count, npages);
1922 if (object != NULL) {
1923 if (object->memattr != VM_MEMATTR_DEFAULT &&
1924 memattr == VM_MEMATTR_DEFAULT)
1925 memattr = object->memattr;
1927 for (m = m_ret; m < &m_ret[npages]; m++) {
1929 m->flags = (m->flags | PG_NODUMP) & flags;
1930 m->busy_lock = VPB_UNBUSIED;
1931 if (object != NULL) {
1932 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
1933 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1934 if ((req & VM_ALLOC_SBUSY) != 0)
1935 m->busy_lock = VPB_SHARERS_WORD(1);
1937 if ((req & VM_ALLOC_WIRED) != 0)
1939 /* Unmanaged pages don't use "act_count". */
1940 m->oflags = VPO_UNMANAGED;
1941 if (object != NULL) {
1942 if (vm_page_insert(m, object, pindex)) {
1943 vm_page_alloc_contig_vdrop(
1944 &deferred_vdrop_list);
1945 if (vm_paging_needed())
1946 pagedaemon_wakeup();
1947 if ((req & VM_ALLOC_WIRED) != 0)
1948 atomic_subtract_int(&vm_cnt.v_wire_count,
1950 for (m_tmp = m, m = m_ret;
1951 m < &m_ret[npages]; m++) {
1952 if ((req & VM_ALLOC_WIRED) != 0)
1962 if (memattr != VM_MEMATTR_DEFAULT)
1963 pmap_page_set_memattr(m, memattr);
1966 vm_page_alloc_contig_vdrop(&deferred_vdrop_list);
1967 if (vm_paging_needed())
1968 pagedaemon_wakeup();
1973 * Initialize a page that has been freshly dequeued from a freelist.
1974 * The caller has to drop the vnode returned, if it is not NULL.
1976 * This function may only be used to initialize unmanaged pages.
1978 * To be called with vm_page_queue_free_mtx held.
1980 static struct vnode *
1981 vm_page_alloc_init(vm_page_t m)
1984 vm_object_t m_object;
1986 KASSERT(m->queue == PQ_NONE,
1987 ("vm_page_alloc_init: page %p has unexpected queue %d",
1989 KASSERT(m->wire_count == 0,
1990 ("vm_page_alloc_init: page %p is wired", m));
1991 KASSERT(m->hold_count == 0,
1992 ("vm_page_alloc_init: page %p is held", m));
1993 KASSERT(!vm_page_sbusied(m),
1994 ("vm_page_alloc_init: page %p is busy", m));
1995 KASSERT(m->dirty == 0,
1996 ("vm_page_alloc_init: page %p is dirty", m));
1997 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1998 ("vm_page_alloc_init: page %p has unexpected memattr %d",
1999 m, pmap_page_get_memattr(m)));
2000 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2002 if ((m->flags & PG_CACHED) != 0) {
2003 KASSERT((m->flags & PG_ZERO) == 0,
2004 ("vm_page_alloc_init: cached page %p is PG_ZERO", m));
2006 m_object = m->object;
2007 vm_page_cache_remove(m);
2008 if (m_object->type == OBJT_VNODE &&
2009 vm_object_cache_is_empty(m_object))
2010 drop = m_object->handle;
2012 KASSERT(m->valid == 0,
2013 ("vm_page_alloc_init: free page %p is valid", m));
2014 vm_phys_freecnt_adj(m, -1);
2015 if ((m->flags & PG_ZERO) != 0)
2016 vm_page_zero_count--;
2022 * vm_page_alloc_freelist:
2024 * Allocate a physical page from the specified free page list.
2026 * The caller must always specify an allocation class.
2028 * allocation classes:
2029 * VM_ALLOC_NORMAL normal process request
2030 * VM_ALLOC_SYSTEM system *really* needs a page
2031 * VM_ALLOC_INTERRUPT interrupt time request
2033 * optional allocation flags:
2034 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2035 * intends to allocate
2036 * VM_ALLOC_WIRED wire the allocated page
2037 * VM_ALLOC_ZERO prefer a zeroed page
2039 * This routine may not sleep.
2042 vm_page_alloc_freelist(int flind, int req)
2049 req_class = req & VM_ALLOC_CLASS_MASK;
2052 * The page daemon is allowed to dig deeper into the free page list.
2054 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2055 req_class = VM_ALLOC_SYSTEM;
2058 * Do not allocate reserved pages unless the req has asked for it.
2060 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
2061 if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
2062 (req_class == VM_ALLOC_SYSTEM &&
2063 vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
2064 (req_class == VM_ALLOC_INTERRUPT &&
2065 vm_cnt.v_free_count + vm_cnt.v_cache_count > 0))
2066 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
2068 mtx_unlock(&vm_page_queue_free_mtx);
2069 atomic_add_int(&vm_pageout_deficit,
2070 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
2071 pagedaemon_wakeup();
2075 mtx_unlock(&vm_page_queue_free_mtx);
2078 drop = vm_page_alloc_init(m);
2079 mtx_unlock(&vm_page_queue_free_mtx);
2082 * Initialize the page. Only the PG_ZERO flag is inherited.
2086 if ((req & VM_ALLOC_ZERO) != 0)
2089 if ((req & VM_ALLOC_WIRED) != 0) {
2091 * The page lock is not required for wiring a page that does
2092 * not belong to an object.
2094 atomic_add_int(&vm_cnt.v_wire_count, 1);
2097 /* Unmanaged pages don't use "act_count". */
2098 m->oflags = VPO_UNMANAGED;
2101 if (vm_paging_needed())
2102 pagedaemon_wakeup();
2107 * vm_wait: (also see VM_WAIT macro)
2109 * Sleep until free pages are available for allocation.
2110 * - Called in various places before memory allocations.
2116 mtx_lock(&vm_page_queue_free_mtx);
2117 if (curproc == pageproc) {
2118 vm_pageout_pages_needed = 1;
2119 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
2120 PDROP | PSWP, "VMWait", 0);
2122 if (!vm_pages_needed) {
2123 vm_pages_needed = 1;
2124 wakeup(&vm_pages_needed);
2126 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
2132 * vm_waitpfault: (also see VM_WAITPFAULT macro)
2134 * Sleep until free pages are available for allocation.
2135 * - Called only in vm_fault so that processes page faulting
2136 * can be easily tracked.
2137 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2138 * processes will be able to grab memory first. Do not change
2139 * this balance without careful testing first.
2145 mtx_lock(&vm_page_queue_free_mtx);
2146 if (!vm_pages_needed) {
2147 vm_pages_needed = 1;
2148 wakeup(&vm_pages_needed);
2150 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
2154 struct vm_pagequeue *
2155 vm_page_pagequeue(vm_page_t m)
2158 return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2164 * Remove the given page from its current page queue.
2166 * The page must be locked.
2169 vm_page_dequeue(vm_page_t m)
2171 struct vm_pagequeue *pq;
2173 vm_page_assert_locked(m);
2174 KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
2176 pq = vm_page_pagequeue(m);
2177 vm_pagequeue_lock(pq);
2179 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2180 vm_pagequeue_cnt_dec(pq);
2181 vm_pagequeue_unlock(pq);
2185 * vm_page_dequeue_locked:
2187 * Remove the given page from its current page queue.
2189 * The page and page queue must be locked.
2192 vm_page_dequeue_locked(vm_page_t m)
2194 struct vm_pagequeue *pq;
2196 vm_page_lock_assert(m, MA_OWNED);
2197 pq = vm_page_pagequeue(m);
2198 vm_pagequeue_assert_locked(pq);
2200 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2201 vm_pagequeue_cnt_dec(pq);
2207 * Add the given page to the specified page queue.
2209 * The page must be locked.
2212 vm_page_enqueue(uint8_t queue, vm_page_t m)
2214 struct vm_pagequeue *pq;
2216 vm_page_lock_assert(m, MA_OWNED);
2217 KASSERT(queue < PQ_COUNT,
2218 ("vm_page_enqueue: invalid queue %u request for page %p",
2220 pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2221 vm_pagequeue_lock(pq);
2223 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2224 vm_pagequeue_cnt_inc(pq);
2225 vm_pagequeue_unlock(pq);
2231 * Move the given page to the tail of its current page queue.
2233 * The page must be locked.
2236 vm_page_requeue(vm_page_t m)
2238 struct vm_pagequeue *pq;
2240 vm_page_lock_assert(m, MA_OWNED);
2241 KASSERT(m->queue != PQ_NONE,
2242 ("vm_page_requeue: page %p is not queued", m));
2243 pq = vm_page_pagequeue(m);
2244 vm_pagequeue_lock(pq);
2245 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2246 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2247 vm_pagequeue_unlock(pq);
2251 * vm_page_requeue_locked:
2253 * Move the given page to the tail of its current page queue.
2255 * The page queue must be locked.
2258 vm_page_requeue_locked(vm_page_t m)
2260 struct vm_pagequeue *pq;
2262 KASSERT(m->queue != PQ_NONE,
2263 ("vm_page_requeue_locked: page %p is not queued", m));
2264 pq = vm_page_pagequeue(m);
2265 vm_pagequeue_assert_locked(pq);
2266 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2267 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2273 * Put the specified page on the active list (if appropriate).
2274 * Ensure that act_count is at least ACT_INIT but do not otherwise
2277 * The page must be locked.
2280 vm_page_activate(vm_page_t m)
2284 vm_page_lock_assert(m, MA_OWNED);
2285 if ((queue = m->queue) != PQ_ACTIVE) {
2286 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2287 if (m->act_count < ACT_INIT)
2288 m->act_count = ACT_INIT;
2289 if (queue != PQ_NONE)
2291 vm_page_enqueue(PQ_ACTIVE, m);
2293 KASSERT(queue == PQ_NONE,
2294 ("vm_page_activate: wired page %p is queued", m));
2296 if (m->act_count < ACT_INIT)
2297 m->act_count = ACT_INIT;
2302 * vm_page_free_wakeup:
2304 * Helper routine for vm_page_free_toq() and vm_page_cache(). This
2305 * routine is called when a page has been added to the cache or free
2308 * The page queues must be locked.
2311 vm_page_free_wakeup(void)
2314 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2316 * if pageout daemon needs pages, then tell it that there are
2319 if (vm_pageout_pages_needed &&
2320 vm_cnt.v_cache_count + vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
2321 wakeup(&vm_pageout_pages_needed);
2322 vm_pageout_pages_needed = 0;
2325 * wakeup processes that are waiting on memory if we hit a
2326 * high water mark. And wakeup scheduler process if we have
2327 * lots of memory. this process will swapin processes.
2329 if (vm_pages_needed && !vm_page_count_min()) {
2330 vm_pages_needed = 0;
2331 wakeup(&vm_cnt.v_free_count);
2336 * Turn a cached page into a free page, by changing its attributes.
2337 * Keep the statistics up-to-date.
2339 * The free page queue must be locked.
2342 vm_page_cache_turn_free(vm_page_t m)
2345 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2349 KASSERT((m->flags & PG_CACHED) != 0,
2350 ("vm_page_cache_turn_free: page %p is not cached", m));
2351 m->flags &= ~PG_CACHED;
2352 vm_cnt.v_cache_count--;
2353 vm_phys_freecnt_adj(m, 1);
2359 * Returns the given page to the free list,
2360 * disassociating it with any VM object.
2362 * The object must be locked. The page must be locked if it is managed.
2365 vm_page_free_toq(vm_page_t m)
2368 if ((m->oflags & VPO_UNMANAGED) == 0) {
2369 vm_page_lock_assert(m, MA_OWNED);
2370 KASSERT(!pmap_page_is_mapped(m),
2371 ("vm_page_free_toq: freeing mapped page %p", m));
2373 KASSERT(m->queue == PQ_NONE,
2374 ("vm_page_free_toq: unmanaged page %p is queued", m));
2375 PCPU_INC(cnt.v_tfree);
2377 if (vm_page_sbusied(m))
2378 panic("vm_page_free: freeing busy page %p", m);
2381 * Unqueue, then remove page. Note that we cannot destroy
2382 * the page here because we do not want to call the pager's
2383 * callback routine until after we've put the page on the
2384 * appropriate free queue.
2390 * If fictitious remove object association and
2391 * return, otherwise delay object association removal.
2393 if ((m->flags & PG_FICTITIOUS) != 0) {
2400 if (m->wire_count != 0)
2401 panic("vm_page_free: freeing wired page %p", m);
2402 if (m->hold_count != 0) {
2403 m->flags &= ~PG_ZERO;
2404 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2405 ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
2406 m->flags |= PG_UNHOLDFREE;
2409 * Restore the default memory attribute to the page.
2411 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2412 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2415 * Insert the page into the physical memory allocator's
2416 * cache/free page queues.
2418 mtx_lock(&vm_page_queue_free_mtx);
2419 vm_phys_freecnt_adj(m, 1);
2420 #if VM_NRESERVLEVEL > 0
2421 if (!vm_reserv_free_page(m))
2425 vm_phys_free_pages(m, 0);
2426 if ((m->flags & PG_ZERO) != 0)
2427 ++vm_page_zero_count;
2429 vm_page_zero_idle_wakeup();
2430 vm_page_free_wakeup();
2431 mtx_unlock(&vm_page_queue_free_mtx);
2438 * Mark this page as wired down by yet
2439 * another map, removing it from paging queues
2442 * If the page is fictitious, then its wire count must remain one.
2444 * The page must be locked.
2447 vm_page_wire(vm_page_t m)
2451 * Only bump the wire statistics if the page is not already wired,
2452 * and only unqueue the page if it is on some queue (if it is unmanaged
2453 * it is already off the queues).
2455 vm_page_lock_assert(m, MA_OWNED);
2456 if ((m->flags & PG_FICTITIOUS) != 0) {
2457 KASSERT(m->wire_count == 1,
2458 ("vm_page_wire: fictitious page %p's wire count isn't one",
2462 if (m->wire_count == 0) {
2463 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
2464 m->queue == PQ_NONE,
2465 ("vm_page_wire: unmanaged page %p is queued", m));
2467 atomic_add_int(&vm_cnt.v_wire_count, 1);
2470 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
2476 * Release one wiring of the specified page, potentially allowing it to be
2477 * paged out. Returns TRUE if the number of wirings transitions to zero and
2480 * Only managed pages belonging to an object can be paged out. If the number
2481 * of wirings transitions to zero and the page is eligible for page out, then
2482 * the page is added to the specified paging queue (unless PQ_NONE is
2485 * If a page is fictitious, then its wire count must always be one.
2487 * A managed page must be locked.
2490 vm_page_unwire(vm_page_t m, uint8_t queue)
2493 KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
2494 ("vm_page_unwire: invalid queue %u request for page %p",
2496 if ((m->oflags & VPO_UNMANAGED) == 0)
2497 vm_page_assert_locked(m);
2498 if ((m->flags & PG_FICTITIOUS) != 0) {
2499 KASSERT(m->wire_count == 1,
2500 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
2503 if (m->wire_count > 0) {
2505 if (m->wire_count == 0) {
2506 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2507 if ((m->oflags & VPO_UNMANAGED) == 0 &&
2508 m->object != NULL && queue != PQ_NONE) {
2509 if (queue == PQ_INACTIVE)
2510 m->flags &= ~PG_WINATCFLS;
2511 vm_page_enqueue(queue, m);
2517 panic("vm_page_unwire: page %p's wire count is zero", m);
2521 * Move the specified page to the inactive queue.
2523 * Many pages placed on the inactive queue should actually go
2524 * into the cache, but it is difficult to figure out which. What
2525 * we do instead, if the inactive target is well met, is to put
2526 * clean pages at the head of the inactive queue instead of the tail.
2527 * This will cause them to be moved to the cache more quickly and
2528 * if not actively re-referenced, reclaimed more quickly. If we just
2529 * stick these pages at the end of the inactive queue, heavy filesystem
2530 * meta-data accesses can cause an unnecessary paging load on memory bound
2531 * processes. This optimization causes one-time-use metadata to be
2532 * reused more quickly.
2534 * Normally noreuse is FALSE, resulting in LRU operation. noreuse is set
2535 * to TRUE if we want this page to be 'as if it were placed in the cache',
2536 * except without unmapping it from the process address space. In
2537 * practice this is implemented by inserting the page at the head of the
2538 * queue, using a marker page to guide FIFO insertion ordering.
2540 * The page must be locked.
2543 _vm_page_deactivate(vm_page_t m, boolean_t noreuse)
2545 struct vm_pagequeue *pq;
2548 vm_page_assert_locked(m);
2551 * Ignore if the page is already inactive, unless it is unlikely to be
2554 if ((queue = m->queue) == PQ_INACTIVE && !noreuse)
2556 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2557 pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
2558 /* Avoid multiple acquisitions of the inactive queue lock. */
2559 if (queue == PQ_INACTIVE) {
2560 vm_pagequeue_lock(pq);
2561 vm_page_dequeue_locked(m);
2563 if (queue != PQ_NONE)
2565 m->flags &= ~PG_WINATCFLS;
2566 vm_pagequeue_lock(pq);
2568 m->queue = PQ_INACTIVE;
2570 TAILQ_INSERT_BEFORE(&vm_phys_domain(m)->vmd_inacthead,
2573 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2574 vm_pagequeue_cnt_inc(pq);
2575 vm_pagequeue_unlock(pq);
2580 * Move the specified page to the inactive queue.
2582 * The page must be locked.
2585 vm_page_deactivate(vm_page_t m)
2588 _vm_page_deactivate(m, FALSE);
2592 * Move the specified page to the inactive queue with the expectation
2593 * that it is unlikely to be reused.
2595 * The page must be locked.
2598 vm_page_deactivate_noreuse(vm_page_t m)
2601 _vm_page_deactivate(m, TRUE);
2605 * vm_page_try_to_cache:
2607 * Returns 0 on failure, 1 on success
2610 vm_page_try_to_cache(vm_page_t m)
2613 vm_page_lock_assert(m, MA_OWNED);
2614 VM_OBJECT_ASSERT_WLOCKED(m->object);
2615 if (m->dirty || m->hold_count || m->wire_count ||
2616 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
2626 * vm_page_try_to_free()
2628 * Attempt to free the page. If we cannot free it, we do nothing.
2629 * 1 is returned on success, 0 on failure.
2632 vm_page_try_to_free(vm_page_t m)
2635 vm_page_lock_assert(m, MA_OWNED);
2636 if (m->object != NULL)
2637 VM_OBJECT_ASSERT_WLOCKED(m->object);
2638 if (m->dirty || m->hold_count || m->wire_count ||
2639 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
2651 * Put the specified page onto the page cache queue (if appropriate).
2653 * The object and page must be locked.
2656 vm_page_cache(vm_page_t m)
2659 boolean_t cache_was_empty;
2661 vm_page_lock_assert(m, MA_OWNED);
2663 VM_OBJECT_ASSERT_WLOCKED(object);
2664 if (vm_page_busied(m) || (m->oflags & VPO_UNMANAGED) ||
2665 m->hold_count || m->wire_count)
2666 panic("vm_page_cache: attempting to cache busy page");
2667 KASSERT(!pmap_page_is_mapped(m),
2668 ("vm_page_cache: page %p is mapped", m));
2669 KASSERT(m->dirty == 0, ("vm_page_cache: page %p is dirty", m));
2670 if (m->valid == 0 || object->type == OBJT_DEFAULT ||
2671 (object->type == OBJT_SWAP &&
2672 !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
2674 * Hypothesis: A cache-eligible page belonging to a
2675 * default object or swap object but without a backing
2676 * store must be zero filled.
2681 KASSERT((m->flags & PG_CACHED) == 0,
2682 ("vm_page_cache: page %p is already cached", m));
2685 * Remove the page from the paging queues.
2690 * Remove the page from the object's collection of resident
2693 vm_radix_remove(&object->rtree, m->pindex);
2694 TAILQ_REMOVE(&object->memq, m, listq);
2695 object->resident_page_count--;
2698 * Restore the default memory attribute to the page.
2700 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2701 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2704 * Insert the page into the object's collection of cached pages
2705 * and the physical memory allocator's cache/free page queues.
2707 m->flags &= ~PG_ZERO;
2708 mtx_lock(&vm_page_queue_free_mtx);
2709 cache_was_empty = vm_radix_is_empty(&object->cache);
2710 if (vm_radix_insert(&object->cache, m)) {
2711 mtx_unlock(&vm_page_queue_free_mtx);
2712 if (object->resident_page_count == 0)
2713 vdrop(object->handle);
2720 * The above call to vm_radix_insert() could reclaim the one pre-
2721 * existing cached page from this object, resulting in a call to
2724 if (!cache_was_empty)
2725 cache_was_empty = vm_radix_is_singleton(&object->cache);
2727 m->flags |= PG_CACHED;
2728 vm_cnt.v_cache_count++;
2729 PCPU_INC(cnt.v_tcached);
2730 #if VM_NRESERVLEVEL > 0
2731 if (!vm_reserv_free_page(m)) {
2735 vm_phys_free_pages(m, 0);
2737 vm_page_free_wakeup();
2738 mtx_unlock(&vm_page_queue_free_mtx);
2741 * Increment the vnode's hold count if this is the object's only
2742 * cached page. Decrement the vnode's hold count if this was
2743 * the object's only resident page.
2745 if (object->type == OBJT_VNODE) {
2746 if (cache_was_empty && object->resident_page_count != 0)
2747 vhold(object->handle);
2748 else if (!cache_was_empty && object->resident_page_count == 0)
2749 vdrop(object->handle);
2756 * Deactivate or do nothing, as appropriate.
2758 * The object and page must be locked.
2761 vm_page_advise(vm_page_t m, int advice)
2764 vm_page_assert_locked(m);
2765 VM_OBJECT_ASSERT_WLOCKED(m->object);
2766 if (advice == MADV_FREE)
2768 * Mark the page clean. This will allow the page to be freed
2769 * up by the system. However, such pages are often reused
2770 * quickly by malloc() so we do not do anything that would
2771 * cause a page fault if we can help it.
2773 * Specifically, we do not try to actually free the page now
2774 * nor do we try to put it in the cache (which would cause a
2775 * page fault on reuse).
2777 * But we do make the page as freeable as we can without
2778 * actually taking the step of unmapping it.
2781 else if (advice != MADV_DONTNEED)
2785 * Clear any references to the page. Otherwise, the page daemon will
2786 * immediately reactivate the page.
2788 vm_page_aflag_clear(m, PGA_REFERENCED);
2790 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
2794 * Place clean pages at the head of the inactive queue rather than the
2795 * tail, thus defeating the queue's LRU operation and ensuring that the
2796 * page will be reused quickly.
2798 _vm_page_deactivate(m, m->dirty == 0);
2802 * Grab a page, waiting until we are waken up due to the page
2803 * changing state. We keep on waiting, if the page continues
2804 * to be in the object. If the page doesn't exist, first allocate it
2805 * and then conditionally zero it.
2807 * This routine may sleep.
2809 * The object must be locked on entry. The lock will, however, be released
2810 * and reacquired if the routine sleeps.
2813 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
2818 VM_OBJECT_ASSERT_WLOCKED(object);
2819 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
2820 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
2821 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
2823 if ((m = vm_page_lookup(object, pindex)) != NULL) {
2824 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
2825 vm_page_xbusied(m) : vm_page_busied(m);
2827 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
2830 * Reference the page before unlocking and
2831 * sleeping so that the page daemon is less
2832 * likely to reclaim it.
2834 vm_page_aflag_set(m, PGA_REFERENCED);
2836 VM_OBJECT_WUNLOCK(object);
2837 vm_page_busy_sleep(m, "pgrbwt");
2838 VM_OBJECT_WLOCK(object);
2841 if ((allocflags & VM_ALLOC_WIRED) != 0) {
2847 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
2849 if ((allocflags & VM_ALLOC_SBUSY) != 0)
2854 m = vm_page_alloc(object, pindex, allocflags);
2856 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
2858 VM_OBJECT_WUNLOCK(object);
2860 VM_OBJECT_WLOCK(object);
2862 } else if (m->valid != 0)
2864 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
2870 * Mapping function for valid or dirty bits in a page.
2872 * Inputs are required to range within a page.
2875 vm_page_bits(int base, int size)
2881 base + size <= PAGE_SIZE,
2882 ("vm_page_bits: illegal base/size %d/%d", base, size)
2885 if (size == 0) /* handle degenerate case */
2888 first_bit = base >> DEV_BSHIFT;
2889 last_bit = (base + size - 1) >> DEV_BSHIFT;
2891 return (((vm_page_bits_t)2 << last_bit) -
2892 ((vm_page_bits_t)1 << first_bit));
2896 * vm_page_set_valid_range:
2898 * Sets portions of a page valid. The arguments are expected
2899 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2900 * of any partial chunks touched by the range. The invalid portion of
2901 * such chunks will be zeroed.
2903 * (base + size) must be less then or equal to PAGE_SIZE.
2906 vm_page_set_valid_range(vm_page_t m, int base, int size)
2910 VM_OBJECT_ASSERT_WLOCKED(m->object);
2911 if (size == 0) /* handle degenerate case */
2915 * If the base is not DEV_BSIZE aligned and the valid
2916 * bit is clear, we have to zero out a portion of the
2919 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2920 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2921 pmap_zero_page_area(m, frag, base - frag);
2924 * If the ending offset is not DEV_BSIZE aligned and the
2925 * valid bit is clear, we have to zero out a portion of
2928 endoff = base + size;
2929 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2930 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2931 pmap_zero_page_area(m, endoff,
2932 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2935 * Assert that no previously invalid block that is now being validated
2938 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
2939 ("vm_page_set_valid_range: page %p is dirty", m));
2942 * Set valid bits inclusive of any overlap.
2944 m->valid |= vm_page_bits(base, size);
2948 * Clear the given bits from the specified page's dirty field.
2950 static __inline void
2951 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
2954 #if PAGE_SIZE < 16384
2959 * If the object is locked and the page is neither exclusive busy nor
2960 * write mapped, then the page's dirty field cannot possibly be
2961 * set by a concurrent pmap operation.
2963 VM_OBJECT_ASSERT_WLOCKED(m->object);
2964 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
2965 m->dirty &= ~pagebits;
2968 * The pmap layer can call vm_page_dirty() without
2969 * holding a distinguished lock. The combination of
2970 * the object's lock and an atomic operation suffice
2971 * to guarantee consistency of the page dirty field.
2973 * For PAGE_SIZE == 32768 case, compiler already
2974 * properly aligns the dirty field, so no forcible
2975 * alignment is needed. Only require existence of
2976 * atomic_clear_64 when page size is 32768.
2978 addr = (uintptr_t)&m->dirty;
2979 #if PAGE_SIZE == 32768
2980 atomic_clear_64((uint64_t *)addr, pagebits);
2981 #elif PAGE_SIZE == 16384
2982 atomic_clear_32((uint32_t *)addr, pagebits);
2983 #else /* PAGE_SIZE <= 8192 */
2985 * Use a trick to perform a 32-bit atomic on the
2986 * containing aligned word, to not depend on the existence
2987 * of atomic_clear_{8, 16}.
2989 shift = addr & (sizeof(uint32_t) - 1);
2990 #if BYTE_ORDER == BIG_ENDIAN
2991 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
2995 addr &= ~(sizeof(uint32_t) - 1);
2996 atomic_clear_32((uint32_t *)addr, pagebits << shift);
2997 #endif /* PAGE_SIZE */
3002 * vm_page_set_validclean:
3004 * Sets portions of a page valid and clean. The arguments are expected
3005 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3006 * of any partial chunks touched by the range. The invalid portion of
3007 * such chunks will be zero'd.
3009 * (base + size) must be less then or equal to PAGE_SIZE.
3012 vm_page_set_validclean(vm_page_t m, int base, int size)
3014 vm_page_bits_t oldvalid, pagebits;
3017 VM_OBJECT_ASSERT_WLOCKED(m->object);
3018 if (size == 0) /* handle degenerate case */
3022 * If the base is not DEV_BSIZE aligned and the valid
3023 * bit is clear, we have to zero out a portion of the
3026 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
3027 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
3028 pmap_zero_page_area(m, frag, base - frag);
3031 * If the ending offset is not DEV_BSIZE aligned and the
3032 * valid bit is clear, we have to zero out a portion of
3035 endoff = base + size;
3036 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
3037 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
3038 pmap_zero_page_area(m, endoff,
3039 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3042 * Set valid, clear dirty bits. If validating the entire
3043 * page we can safely clear the pmap modify bit. We also
3044 * use this opportunity to clear the VPO_NOSYNC flag. If a process
3045 * takes a write fault on a MAP_NOSYNC memory area the flag will
3048 * We set valid bits inclusive of any overlap, but we can only
3049 * clear dirty bits for DEV_BSIZE chunks that are fully within
3052 oldvalid = m->valid;
3053 pagebits = vm_page_bits(base, size);
3054 m->valid |= pagebits;
3056 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
3057 frag = DEV_BSIZE - frag;
3063 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
3065 if (base == 0 && size == PAGE_SIZE) {
3067 * The page can only be modified within the pmap if it is
3068 * mapped, and it can only be mapped if it was previously
3071 if (oldvalid == VM_PAGE_BITS_ALL)
3073 * Perform the pmap_clear_modify() first. Otherwise,
3074 * a concurrent pmap operation, such as
3075 * pmap_protect(), could clear a modification in the
3076 * pmap and set the dirty field on the page before
3077 * pmap_clear_modify() had begun and after the dirty
3078 * field was cleared here.
3080 pmap_clear_modify(m);
3082 m->oflags &= ~VPO_NOSYNC;
3083 } else if (oldvalid != VM_PAGE_BITS_ALL)
3084 m->dirty &= ~pagebits;
3086 vm_page_clear_dirty_mask(m, pagebits);
3090 vm_page_clear_dirty(vm_page_t m, int base, int size)
3093 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
3097 * vm_page_set_invalid:
3099 * Invalidates DEV_BSIZE'd chunks within a page. Both the
3100 * valid and dirty bits for the effected areas are cleared.
3103 vm_page_set_invalid(vm_page_t m, int base, int size)
3105 vm_page_bits_t bits;
3109 VM_OBJECT_ASSERT_WLOCKED(object);
3110 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
3111 size >= object->un_pager.vnp.vnp_size)
3112 bits = VM_PAGE_BITS_ALL;
3114 bits = vm_page_bits(base, size);
3115 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
3118 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3119 !pmap_page_is_mapped(m),
3120 ("vm_page_set_invalid: page %p is mapped", m));
3126 * vm_page_zero_invalid()
3128 * The kernel assumes that the invalid portions of a page contain
3129 * garbage, but such pages can be mapped into memory by user code.
3130 * When this occurs, we must zero out the non-valid portions of the
3131 * page so user code sees what it expects.
3133 * Pages are most often semi-valid when the end of a file is mapped
3134 * into memory and the file's size is not page aligned.
3137 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3142 VM_OBJECT_ASSERT_WLOCKED(m->object);
3144 * Scan the valid bits looking for invalid sections that
3145 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
3146 * valid bit may be set ) have already been zeroed by
3147 * vm_page_set_validclean().
3149 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3150 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3151 (m->valid & ((vm_page_bits_t)1 << i))) {
3153 pmap_zero_page_area(m,
3154 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3161 * setvalid is TRUE when we can safely set the zero'd areas
3162 * as being valid. We can do this if there are no cache consistancy
3163 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3166 m->valid = VM_PAGE_BITS_ALL;
3172 * Is (partial) page valid? Note that the case where size == 0
3173 * will return FALSE in the degenerate case where the page is
3174 * entirely invalid, and TRUE otherwise.
3177 vm_page_is_valid(vm_page_t m, int base, int size)
3179 vm_page_bits_t bits;
3181 VM_OBJECT_ASSERT_LOCKED(m->object);
3182 bits = vm_page_bits(base, size);
3183 return (m->valid != 0 && (m->valid & bits) == bits);
3187 * vm_page_ps_is_valid:
3189 * Returns TRUE if the entire (super)page is valid and FALSE otherwise.
3192 vm_page_ps_is_valid(vm_page_t m)
3196 VM_OBJECT_ASSERT_LOCKED(m->object);
3197 npages = atop(pagesizes[m->psind]);
3200 * The physically contiguous pages that make up a superpage, i.e., a
3201 * page with a page size index ("psind") greater than zero, will
3202 * occupy adjacent entries in vm_page_array[].
3204 for (i = 0; i < npages; i++) {
3205 if (m[i].valid != VM_PAGE_BITS_ALL)
3212 * Set the page's dirty bits if the page is modified.
3215 vm_page_test_dirty(vm_page_t m)
3218 VM_OBJECT_ASSERT_WLOCKED(m->object);
3219 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3224 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3227 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3231 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3234 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3238 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3241 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3244 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3246 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3249 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3253 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3256 mtx_assert_(vm_page_lockptr(m), a, file, line);
3262 vm_page_object_lock_assert(vm_page_t m)
3266 * Certain of the page's fields may only be modified by the
3267 * holder of the containing object's lock or the exclusive busy.
3268 * holder. Unfortunately, the holder of the write busy is
3269 * not recorded, and thus cannot be checked here.
3271 if (m->object != NULL && !vm_page_xbusied(m))
3272 VM_OBJECT_ASSERT_WLOCKED(m->object);
3276 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3279 if ((bits & PGA_WRITEABLE) == 0)
3283 * The PGA_WRITEABLE flag can only be set if the page is
3284 * managed, is exclusively busied or the object is locked.
3285 * Currently, this flag is only set by pmap_enter().
3287 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3288 ("PGA_WRITEABLE on unmanaged page"));
3289 if (!vm_page_xbusied(m))
3290 VM_OBJECT_ASSERT_LOCKED(m->object);
3294 #include "opt_ddb.h"
3296 #include <sys/kernel.h>
3298 #include <ddb/ddb.h>
3300 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3302 db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
3303 db_printf("vm_cnt.v_cache_count: %d\n", vm_cnt.v_cache_count);
3304 db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
3305 db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
3306 db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
3307 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
3308 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
3309 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
3310 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
3313 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3317 db_printf("pq_free %d pq_cache %d\n",
3318 vm_cnt.v_free_count, vm_cnt.v_cache_count);
3319 for (dom = 0; dom < vm_ndomains; dom++) {
3321 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pass %d\n",
3323 vm_dom[dom].vmd_page_count,
3324 vm_dom[dom].vmd_free_count,
3325 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3326 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
3327 vm_dom[dom].vmd_pass);
3331 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3337 db_printf("show pginfo addr\n");
3341 phys = strchr(modif, 'p') != NULL;
3343 m = PHYS_TO_VM_PAGE(addr);
3345 m = (vm_page_t)addr;
3347 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3348 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3349 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3350 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3351 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);