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_free_wakeup(void);
162 static void vm_page_init_fakepg(void *dummy);
163 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
164 vm_pindex_t pindex, vm_page_t mpred);
165 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
167 static int vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
170 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init_fakepg, NULL);
173 vm_page_init_fakepg(void *dummy)
176 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
177 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
180 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
181 #if PAGE_SIZE == 32768
183 CTASSERT(sizeof(u_long) >= 8);
188 * Try to acquire a physical address lock while a pmap is locked. If we
189 * fail to trylock we unlock and lock the pmap directly and cache the
190 * locked pa in *locked. The caller should then restart their loop in case
191 * the virtual to physical mapping has changed.
194 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
201 PA_LOCK_ASSERT(lockpa, MA_OWNED);
202 if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
209 atomic_add_int(&pa_tryrelock_restart, 1);
218 * Sets the page size, perhaps based upon the memory
219 * size. Must be called before any use of page-size
220 * dependent functions.
223 vm_set_page_size(void)
225 if (vm_cnt.v_page_size == 0)
226 vm_cnt.v_page_size = PAGE_SIZE;
227 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
228 panic("vm_set_page_size: page size not a power of two");
232 * vm_page_blacklist_next:
234 * Find the next entry in the provided string of blacklist
235 * addresses. Entries are separated by space, comma, or newline.
236 * If an invalid integer is encountered then the rest of the
237 * string is skipped. Updates the list pointer to the next
238 * character, or NULL if the string is exhausted or invalid.
241 vm_page_blacklist_next(char **list, char *end)
246 if (list == NULL || *list == NULL)
254 * If there's no end pointer then the buffer is coming from
255 * the kenv and we know it's null-terminated.
258 end = *list + strlen(*list);
260 /* Ensure that strtoq() won't walk off the end */
262 if (*end == '\n' || *end == ' ' || *end == ',')
265 printf("Blacklist not terminated, skipping\n");
271 for (pos = *list; *pos != '\0'; pos = cp) {
272 bad = strtoq(pos, &cp, 0);
273 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
282 if (*cp == '\0' || ++cp >= end)
286 return (trunc_page(bad));
288 printf("Garbage in RAM blacklist, skipping\n");
294 * vm_page_blacklist_check:
296 * Iterate through the provided string of blacklist addresses, pulling
297 * each entry out of the physical allocator free list and putting it
298 * onto a list for reporting via the vm.page_blacklist sysctl.
301 vm_page_blacklist_check(char *list, char *end)
309 while (next != NULL) {
310 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
312 m = vm_phys_paddr_to_vm_page(pa);
315 mtx_lock(&vm_page_queue_free_mtx);
316 ret = vm_phys_unfree_page(m);
317 mtx_unlock(&vm_page_queue_free_mtx);
319 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
321 printf("Skipping page with pa 0x%jx\n",
328 * vm_page_blacklist_load:
330 * Search for a special module named "ram_blacklist". It'll be a
331 * plain text file provided by the user via the loader directive
335 vm_page_blacklist_load(char **list, char **end)
344 mod = preload_search_by_type("ram_blacklist");
346 ptr = preload_fetch_addr(mod);
347 len = preload_fetch_size(mod);
358 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
365 error = sysctl_wire_old_buffer(req, 0);
368 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
369 TAILQ_FOREACH(m, &blacklist_head, listq) {
370 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
371 (uintmax_t)m->phys_addr);
374 error = sbuf_finish(&sbuf);
380 vm_page_domain_init(struct vm_domain *vmd)
382 struct vm_pagequeue *pq;
385 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
386 "vm inactive pagequeue";
387 *__DECONST(int **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_vcnt) =
388 &vm_cnt.v_inactive_count;
389 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
390 "vm active pagequeue";
391 *__DECONST(int **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_vcnt) =
392 &vm_cnt.v_active_count;
393 vmd->vmd_page_count = 0;
394 vmd->vmd_free_count = 0;
396 vmd->vmd_oom = FALSE;
398 for (i = 0; i < PQ_COUNT; i++) {
399 pq = &vmd->vmd_pagequeues[i];
400 TAILQ_INIT(&pq->pq_pl);
401 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
402 MTX_DEF | MTX_DUPOK);
409 * Initializes the resident memory module.
411 * Allocates memory for the page cells, and
412 * for the object/offset-to-page hash table headers.
413 * Each page cell is initialized and placed on the free list.
416 vm_page_startup(vm_offset_t vaddr)
419 vm_paddr_t page_range;
424 char *list, *listend;
426 vm_paddr_t biggestsize;
427 vm_paddr_t low_water, high_water;
432 vaddr = round_page(vaddr);
434 for (i = 0; phys_avail[i + 1]; i += 2) {
435 phys_avail[i] = round_page(phys_avail[i]);
436 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
439 low_water = phys_avail[0];
440 high_water = phys_avail[1];
442 for (i = 0; i < vm_phys_nsegs; i++) {
443 if (vm_phys_segs[i].start < low_water)
444 low_water = vm_phys_segs[i].start;
445 if (vm_phys_segs[i].end > high_water)
446 high_water = vm_phys_segs[i].end;
448 for (i = 0; phys_avail[i + 1]; i += 2) {
449 vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
451 if (size > biggestsize) {
455 if (phys_avail[i] < low_water)
456 low_water = phys_avail[i];
457 if (phys_avail[i + 1] > high_water)
458 high_water = phys_avail[i + 1];
461 end = phys_avail[biggestone+1];
464 * Initialize the page and queue locks.
466 mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
467 for (i = 0; i < PA_LOCK_COUNT; i++)
468 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
469 for (i = 0; i < vm_ndomains; i++)
470 vm_page_domain_init(&vm_dom[i]);
473 * Allocate memory for use when boot strapping the kernel memory
476 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
477 * manually fetch the value.
479 TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
480 new_end = end - (boot_pages * UMA_SLAB_SIZE);
481 new_end = trunc_page(new_end);
482 mapped = pmap_map(&vaddr, new_end, end,
483 VM_PROT_READ | VM_PROT_WRITE);
484 bzero((void *)mapped, end - new_end);
485 uma_startup((void *)mapped, boot_pages);
487 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
488 defined(__i386__) || defined(__mips__)
490 * Allocate a bitmap to indicate that a random physical page
491 * needs to be included in a minidump.
493 * The amd64 port needs this to indicate which direct map pages
494 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
496 * However, i386 still needs this workspace internally within the
497 * minidump code. In theory, they are not needed on i386, but are
498 * included should the sf_buf code decide to use them.
501 for (i = 0; dump_avail[i + 1] != 0; i += 2)
502 if (dump_avail[i + 1] > last_pa)
503 last_pa = dump_avail[i + 1];
504 page_range = last_pa / PAGE_SIZE;
505 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
506 new_end -= vm_page_dump_size;
507 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
508 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
509 bzero((void *)vm_page_dump, vm_page_dump_size);
513 * Request that the physical pages underlying the message buffer be
514 * included in a crash dump. Since the message buffer is accessed
515 * through the direct map, they are not automatically included.
517 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
518 last_pa = pa + round_page(msgbufsize);
519 while (pa < last_pa) {
525 * Compute the number of pages of memory that will be available for
526 * use (taking into account the overhead of a page structure per
529 first_page = low_water / PAGE_SIZE;
530 #ifdef VM_PHYSSEG_SPARSE
532 for (i = 0; i < vm_phys_nsegs; i++) {
533 page_range += atop(vm_phys_segs[i].end -
534 vm_phys_segs[i].start);
536 for (i = 0; phys_avail[i + 1] != 0; i += 2)
537 page_range += atop(phys_avail[i + 1] - phys_avail[i]);
538 #elif defined(VM_PHYSSEG_DENSE)
539 page_range = high_water / PAGE_SIZE - first_page;
541 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
546 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
551 * Initialize the mem entry structures now, and put them in the free
554 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
555 mapped = pmap_map(&vaddr, new_end, end,
556 VM_PROT_READ | VM_PROT_WRITE);
557 vm_page_array = (vm_page_t) mapped;
558 #if VM_NRESERVLEVEL > 0
560 * Allocate memory for the reservation management system's data
563 new_end = vm_reserv_startup(&vaddr, new_end, high_water);
565 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
567 * pmap_map on arm64, amd64, and mips can come out of the direct-map,
568 * not kvm like i386, so the pages must be tracked for a crashdump to
569 * include this data. This includes the vm_page_array and the early
570 * UMA bootstrap pages.
572 for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
575 phys_avail[biggestone + 1] = new_end;
578 * Add physical memory segments corresponding to the available
581 for (i = 0; phys_avail[i + 1] != 0; i += 2)
582 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
585 * Clear all of the page structures
587 bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
588 for (i = 0; i < page_range; i++)
589 vm_page_array[i].order = VM_NFREEORDER;
590 vm_page_array_size = page_range;
593 * Initialize the physical memory allocator.
598 * Add every available physical page that is not blacklisted to
601 vm_cnt.v_page_count = 0;
602 vm_cnt.v_free_count = 0;
603 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
605 last_pa = phys_avail[i + 1];
606 while (pa < last_pa) {
607 vm_phys_add_page(pa);
612 TAILQ_INIT(&blacklist_head);
613 vm_page_blacklist_load(&list, &listend);
614 vm_page_blacklist_check(list, listend);
616 list = kern_getenv("vm.blacklist");
617 vm_page_blacklist_check(list, NULL);
620 #if VM_NRESERVLEVEL > 0
622 * Initialize the reservation management system.
630 vm_page_reference(vm_page_t m)
633 vm_page_aflag_set(m, PGA_REFERENCED);
637 * vm_page_busy_downgrade:
639 * Downgrade an exclusive busy page into a single shared busy page.
642 vm_page_busy_downgrade(vm_page_t m)
646 vm_page_assert_xbusied(m);
650 x &= VPB_BIT_WAITERS;
651 if (atomic_cmpset_rel_int(&m->busy_lock,
652 VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1) | x))
660 * Return a positive value if the page is shared busied, 0 otherwise.
663 vm_page_sbusied(vm_page_t m)
668 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
674 * Shared unbusy a page.
677 vm_page_sunbusy(vm_page_t m)
681 vm_page_assert_sbusied(m);
685 if (VPB_SHARERS(x) > 1) {
686 if (atomic_cmpset_int(&m->busy_lock, x,
691 if ((x & VPB_BIT_WAITERS) == 0) {
692 KASSERT(x == VPB_SHARERS_WORD(1),
693 ("vm_page_sunbusy: invalid lock state"));
694 if (atomic_cmpset_int(&m->busy_lock,
695 VPB_SHARERS_WORD(1), VPB_UNBUSIED))
699 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
700 ("vm_page_sunbusy: invalid lock state for waiters"));
703 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
714 * vm_page_busy_sleep:
716 * Sleep and release the page lock, using the page pointer as wchan.
717 * This is used to implement the hard-path of busying mechanism.
719 * The given page must be locked.
722 vm_page_busy_sleep(vm_page_t m, const char *wmesg)
726 vm_page_lock_assert(m, MA_OWNED);
729 if (x == VPB_UNBUSIED) {
733 if ((x & VPB_BIT_WAITERS) == 0 &&
734 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS)) {
738 msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
744 * Try to shared busy a page.
745 * If the operation succeeds 1 is returned otherwise 0.
746 * The operation never sleeps.
749 vm_page_trysbusy(vm_page_t m)
755 if ((x & VPB_BIT_SHARED) == 0)
757 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
763 * vm_page_xunbusy_hard:
765 * Called after the first try the exclusive unbusy of a page failed.
766 * It is assumed that the waiters bit is on.
769 vm_page_xunbusy_hard(vm_page_t m)
772 vm_page_assert_xbusied(m);
775 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
783 * Wakeup anyone waiting for the page.
784 * The ownership bits do not change.
786 * The given page must be locked.
789 vm_page_flash(vm_page_t m)
793 vm_page_lock_assert(m, MA_OWNED);
797 if ((x & VPB_BIT_WAITERS) == 0)
799 if (atomic_cmpset_int(&m->busy_lock, x,
800 x & (~VPB_BIT_WAITERS)))
807 * Keep page from being freed by the page daemon
808 * much of the same effect as wiring, except much lower
809 * overhead and should be used only for *very* temporary
810 * holding ("wiring").
813 vm_page_hold(vm_page_t mem)
816 vm_page_lock_assert(mem, MA_OWNED);
821 vm_page_unhold(vm_page_t mem)
824 vm_page_lock_assert(mem, MA_OWNED);
825 KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
827 if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
828 vm_page_free_toq(mem);
832 * vm_page_unhold_pages:
834 * Unhold each of the pages that is referenced by the given array.
837 vm_page_unhold_pages(vm_page_t *ma, int count)
839 struct mtx *mtx, *new_mtx;
842 for (; count != 0; count--) {
844 * Avoid releasing and reacquiring the same page lock.
846 new_mtx = vm_page_lockptr(*ma);
847 if (mtx != new_mtx) {
861 PHYS_TO_VM_PAGE(vm_paddr_t pa)
865 #ifdef VM_PHYSSEG_SPARSE
866 m = vm_phys_paddr_to_vm_page(pa);
868 m = vm_phys_fictitious_to_vm_page(pa);
870 #elif defined(VM_PHYSSEG_DENSE)
874 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
875 m = &vm_page_array[pi - first_page];
878 return (vm_phys_fictitious_to_vm_page(pa));
880 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
887 * Create a fictitious page with the specified physical address and
888 * memory attribute. The memory attribute is the only the machine-
889 * dependent aspect of a fictitious page that must be initialized.
892 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
896 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
897 vm_page_initfake(m, paddr, memattr);
902 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
905 if ((m->flags & PG_FICTITIOUS) != 0) {
907 * The page's memattr might have changed since the
908 * previous initialization. Update the pmap to the
913 m->phys_addr = paddr;
915 /* Fictitious pages don't use "segind". */
916 m->flags = PG_FICTITIOUS;
917 /* Fictitious pages don't use "order" or "pool". */
918 m->oflags = VPO_UNMANAGED;
919 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
923 pmap_page_set_memattr(m, memattr);
929 * Release a fictitious page.
932 vm_page_putfake(vm_page_t m)
935 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
936 KASSERT((m->flags & PG_FICTITIOUS) != 0,
937 ("vm_page_putfake: bad page %p", m));
938 uma_zfree(fakepg_zone, m);
942 * vm_page_updatefake:
944 * Update the given fictitious page to the specified physical address and
948 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
951 KASSERT((m->flags & PG_FICTITIOUS) != 0,
952 ("vm_page_updatefake: bad page %p", m));
953 m->phys_addr = paddr;
954 pmap_page_set_memattr(m, memattr);
963 vm_page_free(vm_page_t m)
966 m->flags &= ~PG_ZERO;
973 * Free a page to the zerod-pages queue
976 vm_page_free_zero(vm_page_t m)
984 * Unbusy and handle the page queueing for a page from the VOP_GETPAGES()
985 * array which was optionally read ahead or behind.
988 vm_page_readahead_finish(vm_page_t m)
991 /* We shouldn't put invalid pages on queues. */
992 KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
995 * Since the page is not the actually needed one, whether it should
996 * be activated or deactivated is not obvious. Empirical results
997 * have shown that deactivating the page is usually the best choice,
998 * unless the page is wanted by another thread.
1001 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1002 vm_page_activate(m);
1004 vm_page_deactivate(m);
1010 * vm_page_sleep_if_busy:
1012 * Sleep and release the page queues lock if the page is busied.
1013 * Returns TRUE if the thread slept.
1015 * The given page must be unlocked and object containing it must
1019 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1023 vm_page_lock_assert(m, MA_NOTOWNED);
1024 VM_OBJECT_ASSERT_WLOCKED(m->object);
1026 if (vm_page_busied(m)) {
1028 * The page-specific object must be cached because page
1029 * identity can change during the sleep, causing the
1030 * re-lock of a different object.
1031 * It is assumed that a reference to the object is already
1032 * held by the callers.
1036 VM_OBJECT_WUNLOCK(obj);
1037 vm_page_busy_sleep(m, msg);
1038 VM_OBJECT_WLOCK(obj);
1045 * vm_page_dirty_KBI: [ internal use only ]
1047 * Set all bits in the page's dirty field.
1049 * The object containing the specified page must be locked if the
1050 * call is made from the machine-independent layer.
1052 * See vm_page_clear_dirty_mask().
1054 * This function should only be called by vm_page_dirty().
1057 vm_page_dirty_KBI(vm_page_t m)
1060 /* These assertions refer to this operation by its public name. */
1061 KASSERT((m->flags & PG_CACHED) == 0,
1062 ("vm_page_dirty: page in cache!"));
1063 KASSERT(m->valid == VM_PAGE_BITS_ALL,
1064 ("vm_page_dirty: page is invalid!"));
1065 m->dirty = VM_PAGE_BITS_ALL;
1069 * vm_page_insert: [ internal use only ]
1071 * Inserts the given mem entry into the object and object list.
1073 * The object must be locked.
1076 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1080 VM_OBJECT_ASSERT_WLOCKED(object);
1081 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1082 return (vm_page_insert_after(m, object, pindex, mpred));
1086 * vm_page_insert_after:
1088 * Inserts the page "m" into the specified object at offset "pindex".
1090 * The page "mpred" must immediately precede the offset "pindex" within
1091 * the specified object.
1093 * The object must be locked.
1096 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1103 VM_OBJECT_ASSERT_WLOCKED(object);
1104 KASSERT(m->object == NULL,
1105 ("vm_page_insert_after: page already inserted"));
1106 if (mpred != NULL) {
1107 KASSERT(mpred->object == object,
1108 ("vm_page_insert_after: object doesn't contain mpred"));
1109 KASSERT(mpred->pindex < pindex,
1110 ("vm_page_insert_after: mpred doesn't precede pindex"));
1111 msucc = TAILQ_NEXT(mpred, listq);
1113 msucc = TAILQ_FIRST(&object->memq);
1115 KASSERT(msucc->pindex > pindex,
1116 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1119 * Record the object/offset pair in this page
1127 * Now link into the object's ordered list of backed pages.
1129 if (vm_radix_insert(&object->rtree, m)) {
1134 vm_page_insert_radixdone(m, object, mpred);
1139 * vm_page_insert_radixdone:
1141 * Complete page "m" insertion into the specified object after the
1142 * radix trie hooking.
1144 * The page "mpred" must precede the offset "m->pindex" within the
1147 * The object must be locked.
1150 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1153 VM_OBJECT_ASSERT_WLOCKED(object);
1154 KASSERT(object != NULL && m->object == object,
1155 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1156 if (mpred != NULL) {
1157 KASSERT(mpred->object == object,
1158 ("vm_page_insert_after: object doesn't contain mpred"));
1159 KASSERT(mpred->pindex < m->pindex,
1160 ("vm_page_insert_after: mpred doesn't precede pindex"));
1164 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1166 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1169 * Show that the object has one more resident page.
1171 object->resident_page_count++;
1174 * Hold the vnode until the last page is released.
1176 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1177 vhold(object->handle);
1180 * Since we are inserting a new and possibly dirty page,
1181 * update the object's OBJ_MIGHTBEDIRTY flag.
1183 if (pmap_page_is_write_mapped(m))
1184 vm_object_set_writeable_dirty(object);
1190 * Removes the given mem entry from the object/offset-page
1191 * table and the object page list, but do not invalidate/terminate
1192 * the backing store.
1194 * The object must be locked. The page must be locked if it is managed.
1197 vm_page_remove(vm_page_t m)
1202 if ((m->oflags & VPO_UNMANAGED) == 0)
1203 vm_page_lock_assert(m, MA_OWNED);
1204 if ((object = m->object) == NULL)
1206 VM_OBJECT_ASSERT_WLOCKED(object);
1207 if (vm_page_xbusied(m)) {
1209 if ((m->oflags & VPO_UNMANAGED) != 0 &&
1210 !mtx_owned(vm_page_lockptr(m))) {
1215 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1221 * Now remove from the object's list of backed pages.
1223 vm_radix_remove(&object->rtree, m->pindex);
1224 TAILQ_REMOVE(&object->memq, m, listq);
1227 * And show that the object has one fewer resident page.
1229 object->resident_page_count--;
1232 * The vnode may now be recycled.
1234 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1235 vdrop(object->handle);
1243 * Returns the page associated with the object/offset
1244 * pair specified; if none is found, NULL is returned.
1246 * The object must be locked.
1249 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1252 VM_OBJECT_ASSERT_LOCKED(object);
1253 return (vm_radix_lookup(&object->rtree, pindex));
1257 * vm_page_find_least:
1259 * Returns the page associated with the object with least pindex
1260 * greater than or equal to the parameter pindex, or NULL.
1262 * The object must be locked.
1265 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1269 VM_OBJECT_ASSERT_LOCKED(object);
1270 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1271 m = vm_radix_lookup_ge(&object->rtree, pindex);
1276 * Returns the given page's successor (by pindex) within the object if it is
1277 * resident; if none is found, NULL is returned.
1279 * The object must be locked.
1282 vm_page_next(vm_page_t m)
1286 VM_OBJECT_ASSERT_WLOCKED(m->object);
1287 if ((next = TAILQ_NEXT(m, listq)) != NULL &&
1288 next->pindex != m->pindex + 1)
1294 * Returns the given page's predecessor (by pindex) within the object if it is
1295 * resident; if none is found, NULL is returned.
1297 * The object must be locked.
1300 vm_page_prev(vm_page_t m)
1304 VM_OBJECT_ASSERT_WLOCKED(m->object);
1305 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
1306 prev->pindex != m->pindex - 1)
1312 * Uses the page mnew as a replacement for an existing page at index
1313 * pindex which must be already present in the object.
1315 * The existing page must not be on a paging queue.
1318 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1322 VM_OBJECT_ASSERT_WLOCKED(object);
1323 KASSERT(mnew->object == NULL,
1324 ("vm_page_replace: page already in object"));
1327 * This function mostly follows vm_page_insert() and
1328 * vm_page_remove() without the radix, object count and vnode
1329 * dance. Double check such functions for more comments.
1332 mnew->object = object;
1333 mnew->pindex = pindex;
1334 mold = vm_radix_replace(&object->rtree, mnew);
1335 KASSERT(mold->queue == PQ_NONE,
1336 ("vm_page_replace: mold is on a paging queue"));
1338 /* Keep the resident page list in sorted order. */
1339 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1340 TAILQ_REMOVE(&object->memq, mold, listq);
1342 mold->object = NULL;
1343 vm_page_xunbusy(mold);
1346 * The object's resident_page_count does not change because we have
1347 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1349 if (pmap_page_is_write_mapped(mnew))
1350 vm_object_set_writeable_dirty(object);
1357 * Move the given memory entry from its
1358 * current object to the specified target object/offset.
1360 * Note: swap associated with the page must be invalidated by the move. We
1361 * have to do this for several reasons: (1) we aren't freeing the
1362 * page, (2) we are dirtying the page, (3) the VM system is probably
1363 * moving the page from object A to B, and will then later move
1364 * the backing store from A to B and we can't have a conflict.
1366 * Note: we *always* dirty the page. It is necessary both for the
1367 * fact that we moved it, and because we may be invalidating
1368 * swap. If the page is on the cache, we have to deactivate it
1369 * or vm_page_dirty() will panic. Dirty pages are not allowed
1372 * The objects must be locked.
1375 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1380 VM_OBJECT_ASSERT_WLOCKED(new_object);
1382 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1383 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1384 ("vm_page_rename: pindex already renamed"));
1387 * Create a custom version of vm_page_insert() which does not depend
1388 * by m_prev and can cheat on the implementation aspects of the
1392 m->pindex = new_pindex;
1393 if (vm_radix_insert(&new_object->rtree, m)) {
1399 * The operation cannot fail anymore. The removal must happen before
1400 * the listq iterator is tainted.
1406 /* Return back to the new pindex to complete vm_page_insert(). */
1407 m->pindex = new_pindex;
1408 m->object = new_object;
1410 vm_page_insert_radixdone(m, new_object, mpred);
1416 * Convert all of the given object's cached pages that have a
1417 * pindex within the given range into free pages. If the value
1418 * zero is given for "end", then the range's upper bound is
1419 * infinity. If the given object is backed by a vnode and it
1420 * transitions from having one or more cached pages to none, the
1421 * vnode's hold count is reduced.
1424 vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1429 mtx_lock(&vm_page_queue_free_mtx);
1430 if (__predict_false(vm_radix_is_empty(&object->cache))) {
1431 mtx_unlock(&vm_page_queue_free_mtx);
1434 while ((m = vm_radix_lookup_ge(&object->cache, start)) != NULL) {
1435 if (end != 0 && m->pindex >= end)
1437 vm_radix_remove(&object->cache, m->pindex);
1438 vm_page_cache_turn_free(m);
1440 empty = vm_radix_is_empty(&object->cache);
1441 mtx_unlock(&vm_page_queue_free_mtx);
1442 if (object->type == OBJT_VNODE && empty)
1443 vdrop(object->handle);
1447 * Returns the cached page that is associated with the given
1448 * object and offset. If, however, none exists, returns NULL.
1450 * The free page queue must be locked.
1452 static inline vm_page_t
1453 vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
1456 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1457 return (vm_radix_lookup(&object->cache, pindex));
1461 * Remove the given cached page from its containing object's
1462 * collection of cached pages.
1464 * The free page queue must be locked.
1467 vm_page_cache_remove(vm_page_t m)
1470 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1471 KASSERT((m->flags & PG_CACHED) != 0,
1472 ("vm_page_cache_remove: page %p is not cached", m));
1473 vm_radix_remove(&m->object->cache, m->pindex);
1475 vm_cnt.v_cache_count--;
1479 * Transfer all of the cached pages with offset greater than or
1480 * equal to 'offidxstart' from the original object's cache to the
1481 * new object's cache. However, any cached pages with offset
1482 * greater than or equal to the new object's size are kept in the
1483 * original object. Initially, the new object's cache must be
1484 * empty. Offset 'offidxstart' in the original object must
1485 * correspond to offset zero in the new object.
1487 * The new object must be locked.
1490 vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1491 vm_object_t new_object)
1496 * Insertion into an object's collection of cached pages
1497 * requires the object to be locked. In contrast, removal does
1500 VM_OBJECT_ASSERT_WLOCKED(new_object);
1501 KASSERT(vm_radix_is_empty(&new_object->cache),
1502 ("vm_page_cache_transfer: object %p has cached pages",
1504 mtx_lock(&vm_page_queue_free_mtx);
1505 while ((m = vm_radix_lookup_ge(&orig_object->cache,
1506 offidxstart)) != NULL) {
1508 * Transfer all of the pages with offset greater than or
1509 * equal to 'offidxstart' from the original object's
1510 * cache to the new object's cache.
1512 if ((m->pindex - offidxstart) >= new_object->size)
1514 vm_radix_remove(&orig_object->cache, m->pindex);
1515 /* Update the page's object and offset. */
1516 m->object = new_object;
1517 m->pindex -= offidxstart;
1518 if (vm_radix_insert(&new_object->cache, m))
1519 vm_page_cache_turn_free(m);
1521 mtx_unlock(&vm_page_queue_free_mtx);
1525 * Returns TRUE if a cached page is associated with the given object and
1526 * offset, and FALSE otherwise.
1528 * The object must be locked.
1531 vm_page_is_cached(vm_object_t object, vm_pindex_t pindex)
1536 * Insertion into an object's collection of cached pages requires the
1537 * object to be locked. Therefore, if the object is locked and the
1538 * object's collection is empty, there is no need to acquire the free
1539 * page queues lock in order to prove that the specified page doesn't
1542 VM_OBJECT_ASSERT_WLOCKED(object);
1543 if (__predict_true(vm_object_cache_is_empty(object)))
1545 mtx_lock(&vm_page_queue_free_mtx);
1546 m = vm_page_cache_lookup(object, pindex);
1547 mtx_unlock(&vm_page_queue_free_mtx);
1554 * Allocate and return a page that is associated with the specified
1555 * object and offset pair. By default, this page is exclusive busied.
1557 * The caller must always specify an allocation class.
1559 * allocation classes:
1560 * VM_ALLOC_NORMAL normal process request
1561 * VM_ALLOC_SYSTEM system *really* needs a page
1562 * VM_ALLOC_INTERRUPT interrupt time request
1564 * optional allocation flags:
1565 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1566 * intends to allocate
1567 * VM_ALLOC_IFCACHED return page only if it is cached
1568 * VM_ALLOC_IFNOTCACHED return NULL, do not reactivate if the page
1570 * VM_ALLOC_NOBUSY do not exclusive busy the page
1571 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1572 * VM_ALLOC_NOOBJ page is not associated with an object and
1573 * should not be exclusive busy
1574 * VM_ALLOC_SBUSY shared busy the allocated page
1575 * VM_ALLOC_WIRED wire the allocated page
1576 * VM_ALLOC_ZERO prefer a zeroed page
1578 * This routine may not sleep.
1581 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1583 struct vnode *vp = NULL;
1584 vm_object_t m_object;
1586 int flags, req_class;
1588 mpred = 0; /* XXX: pacify gcc */
1589 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1590 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1591 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1592 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1593 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1596 VM_OBJECT_ASSERT_WLOCKED(object);
1598 req_class = req & VM_ALLOC_CLASS_MASK;
1601 * The page daemon is allowed to dig deeper into the free page list.
1603 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1604 req_class = VM_ALLOC_SYSTEM;
1606 if (object != NULL) {
1607 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1608 KASSERT(mpred == NULL || mpred->pindex != pindex,
1609 ("vm_page_alloc: pindex already allocated"));
1613 * The page allocation request can came from consumers which already
1614 * hold the free page queue mutex, like vm_page_insert() in
1617 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
1618 if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
1619 (req_class == VM_ALLOC_SYSTEM &&
1620 vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
1621 (req_class == VM_ALLOC_INTERRUPT &&
1622 vm_cnt.v_free_count + vm_cnt.v_cache_count > 0)) {
1624 * Allocate from the free queue if the number of free pages
1625 * exceeds the minimum for the request class.
1627 if (object != NULL &&
1628 (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1629 if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1630 mtx_unlock(&vm_page_queue_free_mtx);
1633 if (vm_phys_unfree_page(m))
1634 vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1635 #if VM_NRESERVLEVEL > 0
1636 else if (!vm_reserv_reactivate_page(m))
1640 panic("vm_page_alloc: cache page %p is missing"
1641 " from the free queue", m);
1642 } else if ((req & VM_ALLOC_IFCACHED) != 0) {
1643 mtx_unlock(&vm_page_queue_free_mtx);
1645 #if VM_NRESERVLEVEL > 0
1646 } else if (object == NULL || (object->flags & (OBJ_COLORED |
1647 OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1648 vm_reserv_alloc_page(object, pindex, mpred)) == NULL) {
1652 m = vm_phys_alloc_pages(object != NULL ?
1653 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1654 #if VM_NRESERVLEVEL > 0
1655 if (m == NULL && vm_reserv_reclaim_inactive()) {
1656 m = vm_phys_alloc_pages(object != NULL ?
1657 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1664 * Not allocatable, give up.
1666 mtx_unlock(&vm_page_queue_free_mtx);
1667 atomic_add_int(&vm_pageout_deficit,
1668 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1669 pagedaemon_wakeup();
1674 * At this point we had better have found a good page.
1676 KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1677 KASSERT(m->queue == PQ_NONE,
1678 ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1679 KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1680 KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1681 KASSERT(!vm_page_sbusied(m),
1682 ("vm_page_alloc: page %p is busy", m));
1683 KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1684 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1685 ("vm_page_alloc: page %p has unexpected memattr %d", m,
1686 pmap_page_get_memattr(m)));
1687 if ((m->flags & PG_CACHED) != 0) {
1688 KASSERT((m->flags & PG_ZERO) == 0,
1689 ("vm_page_alloc: cached page %p is PG_ZERO", m));
1690 KASSERT(m->valid != 0,
1691 ("vm_page_alloc: cached page %p is invalid", m));
1692 if (m->object == object && m->pindex == pindex)
1693 vm_cnt.v_reactivated++;
1696 m_object = m->object;
1697 vm_page_cache_remove(m);
1698 if (m_object->type == OBJT_VNODE &&
1699 vm_object_cache_is_empty(m_object))
1700 vp = m_object->handle;
1702 KASSERT(m->valid == 0,
1703 ("vm_page_alloc: free page %p is valid", m));
1704 vm_phys_freecnt_adj(m, -1);
1705 if ((m->flags & PG_ZERO) != 0)
1706 vm_page_zero_count--;
1708 mtx_unlock(&vm_page_queue_free_mtx);
1711 * Initialize the page. Only the PG_ZERO flag is inherited.
1714 if ((req & VM_ALLOC_ZERO) != 0)
1717 if ((req & VM_ALLOC_NODUMP) != 0)
1721 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1723 m->busy_lock = VPB_UNBUSIED;
1724 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1725 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1726 if ((req & VM_ALLOC_SBUSY) != 0)
1727 m->busy_lock = VPB_SHARERS_WORD(1);
1728 if (req & VM_ALLOC_WIRED) {
1730 * The page lock is not required for wiring a page until that
1731 * page is inserted into the object.
1733 atomic_add_int(&vm_cnt.v_wire_count, 1);
1738 if (object != NULL) {
1739 if (vm_page_insert_after(m, object, pindex, mpred)) {
1740 /* See the comment below about hold count. */
1743 pagedaemon_wakeup();
1744 if (req & VM_ALLOC_WIRED) {
1745 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1749 m->oflags = VPO_UNMANAGED;
1754 /* Ignore device objects; the pager sets "memattr" for them. */
1755 if (object->memattr != VM_MEMATTR_DEFAULT &&
1756 (object->flags & OBJ_FICTITIOUS) == 0)
1757 pmap_page_set_memattr(m, object->memattr);
1762 * The following call to vdrop() must come after the above call
1763 * to vm_page_insert() in case both affect the same object and
1764 * vnode. Otherwise, the affected vnode's hold count could
1765 * temporarily become zero.
1771 * Don't wakeup too often - wakeup the pageout daemon when
1772 * we would be nearly out of memory.
1774 if (vm_paging_needed())
1775 pagedaemon_wakeup();
1781 vm_page_alloc_contig_vdrop(struct spglist *lst)
1784 while (!SLIST_EMPTY(lst)) {
1785 vdrop((struct vnode *)SLIST_FIRST(lst)-> plinks.s.pv);
1786 SLIST_REMOVE_HEAD(lst, plinks.s.ss);
1791 * vm_page_alloc_contig:
1793 * Allocate a contiguous set of physical pages of the given size "npages"
1794 * from the free lists. All of the physical pages must be at or above
1795 * the given physical address "low" and below the given physical address
1796 * "high". The given value "alignment" determines the alignment of the
1797 * first physical page in the set. If the given value "boundary" is
1798 * non-zero, then the set of physical pages cannot cross any physical
1799 * address boundary that is a multiple of that value. Both "alignment"
1800 * and "boundary" must be a power of two.
1802 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1803 * then the memory attribute setting for the physical pages is configured
1804 * to the object's memory attribute setting. Otherwise, the memory
1805 * attribute setting for the physical pages is configured to "memattr",
1806 * overriding the object's memory attribute setting. However, if the
1807 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1808 * memory attribute setting for the physical pages cannot be configured
1809 * to VM_MEMATTR_DEFAULT.
1811 * The caller must always specify an allocation class.
1813 * allocation classes:
1814 * VM_ALLOC_NORMAL normal process request
1815 * VM_ALLOC_SYSTEM system *really* needs a page
1816 * VM_ALLOC_INTERRUPT interrupt time request
1818 * optional allocation flags:
1819 * VM_ALLOC_NOBUSY do not exclusive busy the page
1820 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1821 * VM_ALLOC_NOOBJ page is not associated with an object and
1822 * should not be exclusive busy
1823 * VM_ALLOC_SBUSY shared busy the allocated page
1824 * VM_ALLOC_WIRED wire the allocated page
1825 * VM_ALLOC_ZERO prefer a zeroed page
1827 * This routine may not sleep.
1830 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1831 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1832 vm_paddr_t boundary, vm_memattr_t memattr)
1835 struct spglist deferred_vdrop_list;
1836 vm_page_t m, m_tmp, m_ret;
1840 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1841 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1842 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1843 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1844 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1846 if (object != NULL) {
1847 VM_OBJECT_ASSERT_WLOCKED(object);
1848 KASSERT(object->type == OBJT_PHYS,
1849 ("vm_page_alloc_contig: object %p isn't OBJT_PHYS",
1852 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1853 req_class = req & VM_ALLOC_CLASS_MASK;
1856 * The page daemon is allowed to dig deeper into the free page list.
1858 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1859 req_class = VM_ALLOC_SYSTEM;
1861 SLIST_INIT(&deferred_vdrop_list);
1862 mtx_lock(&vm_page_queue_free_mtx);
1863 if (vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1864 vm_cnt.v_free_reserved || (req_class == VM_ALLOC_SYSTEM &&
1865 vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1866 vm_cnt.v_interrupt_free_min) || (req_class == VM_ALLOC_INTERRUPT &&
1867 vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages)) {
1868 #if VM_NRESERVLEVEL > 0
1870 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1871 (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1872 low, high, alignment, boundary)) == NULL)
1874 m_ret = vm_phys_alloc_contig(npages, low, high,
1875 alignment, boundary);
1877 mtx_unlock(&vm_page_queue_free_mtx);
1878 atomic_add_int(&vm_pageout_deficit, npages);
1879 pagedaemon_wakeup();
1883 for (m = m_ret; m < &m_ret[npages]; m++) {
1884 drop = vm_page_alloc_init(m);
1887 * Enqueue the vnode for deferred vdrop().
1889 m->plinks.s.pv = drop;
1890 SLIST_INSERT_HEAD(&deferred_vdrop_list, m,
1895 #if VM_NRESERVLEVEL > 0
1896 if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1901 mtx_unlock(&vm_page_queue_free_mtx);
1906 * Initialize the pages. Only the PG_ZERO flag is inherited.
1909 if ((req & VM_ALLOC_ZERO) != 0)
1911 if ((req & VM_ALLOC_NODUMP) != 0)
1913 if ((req & VM_ALLOC_WIRED) != 0)
1914 atomic_add_int(&vm_cnt.v_wire_count, npages);
1915 if (object != NULL) {
1916 if (object->memattr != VM_MEMATTR_DEFAULT &&
1917 memattr == VM_MEMATTR_DEFAULT)
1918 memattr = object->memattr;
1920 for (m = m_ret; m < &m_ret[npages]; m++) {
1922 m->flags = (m->flags | PG_NODUMP) & flags;
1923 m->busy_lock = VPB_UNBUSIED;
1924 if (object != NULL) {
1925 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
1926 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1927 if ((req & VM_ALLOC_SBUSY) != 0)
1928 m->busy_lock = VPB_SHARERS_WORD(1);
1930 if ((req & VM_ALLOC_WIRED) != 0)
1932 /* Unmanaged pages don't use "act_count". */
1933 m->oflags = VPO_UNMANAGED;
1934 if (object != NULL) {
1935 if (vm_page_insert(m, object, pindex)) {
1936 vm_page_alloc_contig_vdrop(
1937 &deferred_vdrop_list);
1938 if (vm_paging_needed())
1939 pagedaemon_wakeup();
1940 if ((req & VM_ALLOC_WIRED) != 0)
1941 atomic_subtract_int(&vm_cnt.v_wire_count,
1943 for (m_tmp = m, m = m_ret;
1944 m < &m_ret[npages]; m++) {
1945 if ((req & VM_ALLOC_WIRED) != 0)
1955 if (memattr != VM_MEMATTR_DEFAULT)
1956 pmap_page_set_memattr(m, memattr);
1959 vm_page_alloc_contig_vdrop(&deferred_vdrop_list);
1960 if (vm_paging_needed())
1961 pagedaemon_wakeup();
1966 * Initialize a page that has been freshly dequeued from a freelist.
1967 * The caller has to drop the vnode returned, if it is not NULL.
1969 * This function may only be used to initialize unmanaged pages.
1971 * To be called with vm_page_queue_free_mtx held.
1973 static struct vnode *
1974 vm_page_alloc_init(vm_page_t m)
1977 vm_object_t m_object;
1979 KASSERT(m->queue == PQ_NONE,
1980 ("vm_page_alloc_init: page %p has unexpected queue %d",
1982 KASSERT(m->wire_count == 0,
1983 ("vm_page_alloc_init: page %p is wired", m));
1984 KASSERT(m->hold_count == 0,
1985 ("vm_page_alloc_init: page %p is held", m));
1986 KASSERT(!vm_page_sbusied(m),
1987 ("vm_page_alloc_init: page %p is busy", m));
1988 KASSERT(m->dirty == 0,
1989 ("vm_page_alloc_init: page %p is dirty", m));
1990 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1991 ("vm_page_alloc_init: page %p has unexpected memattr %d",
1992 m, pmap_page_get_memattr(m)));
1993 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1995 if ((m->flags & PG_CACHED) != 0) {
1996 KASSERT((m->flags & PG_ZERO) == 0,
1997 ("vm_page_alloc_init: cached page %p is PG_ZERO", m));
1999 m_object = m->object;
2000 vm_page_cache_remove(m);
2001 if (m_object->type == OBJT_VNODE &&
2002 vm_object_cache_is_empty(m_object))
2003 drop = m_object->handle;
2005 KASSERT(m->valid == 0,
2006 ("vm_page_alloc_init: free page %p is valid", m));
2007 vm_phys_freecnt_adj(m, -1);
2008 if ((m->flags & PG_ZERO) != 0)
2009 vm_page_zero_count--;
2015 * vm_page_alloc_freelist:
2017 * Allocate a physical page from the specified free page list.
2019 * The caller must always specify an allocation class.
2021 * allocation classes:
2022 * VM_ALLOC_NORMAL normal process request
2023 * VM_ALLOC_SYSTEM system *really* needs a page
2024 * VM_ALLOC_INTERRUPT interrupt time request
2026 * optional allocation flags:
2027 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2028 * intends to allocate
2029 * VM_ALLOC_WIRED wire the allocated page
2030 * VM_ALLOC_ZERO prefer a zeroed page
2032 * This routine may not sleep.
2035 vm_page_alloc_freelist(int flind, int req)
2042 req_class = req & VM_ALLOC_CLASS_MASK;
2045 * The page daemon is allowed to dig deeper into the free page list.
2047 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2048 req_class = VM_ALLOC_SYSTEM;
2051 * Do not allocate reserved pages unless the req has asked for it.
2053 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
2054 if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
2055 (req_class == VM_ALLOC_SYSTEM &&
2056 vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
2057 (req_class == VM_ALLOC_INTERRUPT &&
2058 vm_cnt.v_free_count + vm_cnt.v_cache_count > 0))
2059 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
2061 mtx_unlock(&vm_page_queue_free_mtx);
2062 atomic_add_int(&vm_pageout_deficit,
2063 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
2064 pagedaemon_wakeup();
2068 mtx_unlock(&vm_page_queue_free_mtx);
2071 drop = vm_page_alloc_init(m);
2072 mtx_unlock(&vm_page_queue_free_mtx);
2075 * Initialize the page. Only the PG_ZERO flag is inherited.
2079 if ((req & VM_ALLOC_ZERO) != 0)
2082 if ((req & VM_ALLOC_WIRED) != 0) {
2084 * The page lock is not required for wiring a page that does
2085 * not belong to an object.
2087 atomic_add_int(&vm_cnt.v_wire_count, 1);
2090 /* Unmanaged pages don't use "act_count". */
2091 m->oflags = VPO_UNMANAGED;
2094 if (vm_paging_needed())
2095 pagedaemon_wakeup();
2099 #define VPSC_ANY 0 /* No restrictions. */
2100 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2101 #define VPSC_NOSUPER 2 /* Skip superpages. */
2104 * vm_page_scan_contig:
2106 * Scan vm_page_array[] between the specified entries "m_start" and
2107 * "m_end" for a run of contiguous physical pages that satisfy the
2108 * specified conditions, and return the lowest page in the run. The
2109 * specified "alignment" determines the alignment of the lowest physical
2110 * page in the run. If the specified "boundary" is non-zero, then the
2111 * run of physical pages cannot span a physical address that is a
2112 * multiple of "boundary".
2114 * "m_end" is never dereferenced, so it need not point to a vm_page
2115 * structure within vm_page_array[].
2117 * "npages" must be greater than zero. "m_start" and "m_end" must not
2118 * span a hole (or discontiguity) in the physical address space. Both
2119 * "alignment" and "boundary" must be a power of two.
2122 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2123 u_long alignment, vm_paddr_t boundary, int options)
2125 struct mtx *m_mtx, *new_mtx;
2129 #if VM_NRESERVLEVEL > 0
2132 int m_inc, order, run_ext, run_len;
2134 KASSERT(npages > 0, ("npages is 0"));
2135 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2136 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2140 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2141 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2142 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2145 * If the current page would be the start of a run, check its
2146 * physical address against the end, alignment, and boundary
2147 * conditions. If it doesn't satisfy these conditions, either
2148 * terminate the scan or advance to the next page that
2149 * satisfies the failed condition.
2152 KASSERT(m_run == NULL, ("m_run != NULL"));
2153 if (m + npages > m_end)
2155 pa = VM_PAGE_TO_PHYS(m);
2156 if ((pa & (alignment - 1)) != 0) {
2157 m_inc = atop(roundup2(pa, alignment) - pa);
2160 if (((pa ^ (pa + ptoa(npages) - 1)) & ~(boundary -
2162 m_inc = atop(roundup2(pa, boundary) - pa);
2166 KASSERT(m_run != NULL, ("m_run == NULL"));
2169 * Avoid releasing and reacquiring the same page lock.
2171 new_mtx = vm_page_lockptr(m);
2172 if (m_mtx != new_mtx) {
2180 if (m->wire_count != 0 || m->hold_count != 0)
2182 #if VM_NRESERVLEVEL > 0
2183 else if ((level = vm_reserv_level(m)) >= 0 &&
2184 (options & VPSC_NORESERV) != 0) {
2186 /* Advance to the end of the reservation. */
2187 pa = VM_PAGE_TO_PHYS(m);
2188 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2192 else if ((object = m->object) != NULL) {
2194 * The page is considered eligible for relocation if
2195 * and only if it could be laundered or reclaimed by
2198 if (!VM_OBJECT_TRYRLOCK(object)) {
2200 VM_OBJECT_RLOCK(object);
2202 if (m->object != object) {
2204 * The page may have been freed.
2206 VM_OBJECT_RUNLOCK(object);
2208 } else if (m->wire_count != 0 ||
2209 m->hold_count != 0) {
2214 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2215 ("page %p is PG_UNHOLDFREE", m));
2216 /* Don't care: PG_NODUMP, PG_WINATCFLS, PG_ZERO. */
2217 if (object->type != OBJT_DEFAULT &&
2218 object->type != OBJT_SWAP &&
2219 object->type != OBJT_VNODE)
2221 else if ((m->flags & PG_CACHED) != 0 ||
2222 m != vm_page_lookup(object, m->pindex)) {
2224 * The page is cached or recently converted
2225 * from cached to free.
2227 #if VM_NRESERVLEVEL > 0
2230 * The page is reserved. Extend the
2231 * current run by one page.
2236 if ((order = m->order) < VM_NFREEORDER) {
2238 * The page is enqueued in the
2239 * physical memory allocator's cache/
2240 * free page queues. Moreover, it is
2241 * the first page in a power-of-two-
2242 * sized run of contiguous cache/free
2243 * pages. Add these pages to the end
2244 * of the current run, and jump
2247 run_ext = 1 << order;
2251 #if VM_NRESERVLEVEL > 0
2252 } else if ((options & VPSC_NOSUPER) != 0 &&
2253 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2255 /* Advance to the end of the superpage. */
2256 pa = VM_PAGE_TO_PHYS(m);
2257 m_inc = atop(roundup2(pa + 1,
2258 vm_reserv_size(level)) - pa);
2260 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2261 m->queue != PQ_NONE && !vm_page_busied(m)) {
2263 * The page is allocated but eligible for
2264 * relocation. Extend the current run by one
2267 KASSERT(pmap_page_get_memattr(m) ==
2269 ("page %p has an unexpected memattr", m));
2270 KASSERT((m->oflags & (VPO_SWAPINPROG |
2271 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2272 ("page %p has unexpected oflags", m));
2273 /* Don't care: VPO_NOSYNC. */
2278 VM_OBJECT_RUNLOCK(object);
2279 #if VM_NRESERVLEVEL > 0
2280 } else if (level >= 0) {
2282 * The page is reserved but not yet allocated. In
2283 * other words, it is still cached or free. Extend
2284 * the current run by one page.
2288 } else if ((order = m->order) < VM_NFREEORDER) {
2290 * The page is enqueued in the physical memory
2291 * allocator's cache/free page queues. Moreover, it
2292 * is the first page in a power-of-two-sized run of
2293 * contiguous cache/free pages. Add these pages to
2294 * the end of the current run, and jump ahead.
2296 run_ext = 1 << order;
2300 * Skip the page for one of the following reasons: (1)
2301 * It is enqueued in the physical memory allocator's
2302 * cache/free page queues. However, it is not the
2303 * first page in a run of contiguous cache/free pages.
2304 * (This case rarely occurs because the scan is
2305 * performed in ascending order.) (2) It is not
2306 * reserved, and it is transitioning from free to
2307 * allocated. (Conversely, the transition from
2308 * allocated to free for managed pages is blocked by
2309 * the page lock.) (3) It is allocated but not
2310 * contained by an object and not wired, e.g.,
2311 * allocated by Xen's balloon driver.
2317 * Extend or reset the current run of pages.
2332 if (run_len >= npages)
2338 * vm_page_reclaim_run:
2340 * Try to relocate each of the allocated virtual pages within the
2341 * specified run of physical pages to a new physical address. Free the
2342 * physical pages underlying the relocated virtual pages. A virtual page
2343 * is relocatable if and only if it could be laundered or reclaimed by
2344 * the page daemon. Whenever possible, a virtual page is relocated to a
2345 * physical address above "high".
2347 * Returns 0 if every physical page within the run was already free or
2348 * just freed by a successful relocation. Otherwise, returns a non-zero
2349 * value indicating why the last attempt to relocate a virtual page was
2352 * "req_class" must be an allocation class.
2355 vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
2358 struct mtx *m_mtx, *new_mtx;
2359 struct spglist free;
2362 vm_page_t m, m_end, m_new;
2363 int error, order, req;
2365 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2366 ("req_class is not an allocation class"));
2370 m_end = m_run + npages;
2372 for (; error == 0 && m < m_end; m++) {
2373 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2374 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2377 * Avoid releasing and reacquiring the same page lock.
2379 new_mtx = vm_page_lockptr(m);
2380 if (m_mtx != new_mtx) {
2387 if (m->wire_count != 0 || m->hold_count != 0)
2389 else if ((object = m->object) != NULL) {
2391 * The page is relocated if and only if it could be
2392 * laundered or reclaimed by the page daemon.
2394 if (!VM_OBJECT_TRYWLOCK(object)) {
2396 VM_OBJECT_WLOCK(object);
2398 if (m->object != object) {
2400 * The page may have been freed.
2402 VM_OBJECT_WUNLOCK(object);
2404 } else if (m->wire_count != 0 ||
2405 m->hold_count != 0) {
2410 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2411 ("page %p is PG_UNHOLDFREE", m));
2412 /* Don't care: PG_NODUMP, PG_WINATCFLS, PG_ZERO. */
2413 if (object->type != OBJT_DEFAULT &&
2414 object->type != OBJT_SWAP &&
2415 object->type != OBJT_VNODE)
2417 else if ((m->flags & PG_CACHED) != 0 ||
2418 m != vm_page_lookup(object, m->pindex)) {
2420 * The page is cached or recently converted
2421 * from cached to free.
2423 VM_OBJECT_WUNLOCK(object);
2425 } else if (object->memattr != VM_MEMATTR_DEFAULT)
2427 else if (m->queue != PQ_NONE && !vm_page_busied(m)) {
2428 KASSERT(pmap_page_get_memattr(m) ==
2430 ("page %p has an unexpected memattr", m));
2431 KASSERT((m->oflags & (VPO_SWAPINPROG |
2432 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2433 ("page %p has unexpected oflags", m));
2434 /* Don't care: VPO_NOSYNC. */
2435 if (m->valid != 0) {
2437 * First, try to allocate a new page
2438 * that is above "high". Failing
2439 * that, try to allocate a new page
2440 * that is below "m_run". Allocate
2441 * the new page between the end of
2442 * "m_run" and "high" only as a last
2445 req = req_class | VM_ALLOC_NOOBJ;
2446 if ((m->flags & PG_NODUMP) != 0)
2447 req |= VM_ALLOC_NODUMP;
2448 if (trunc_page(high) !=
2449 ~(vm_paddr_t)PAGE_MASK) {
2450 m_new = vm_page_alloc_contig(
2455 VM_MEMATTR_DEFAULT);
2458 if (m_new == NULL) {
2459 pa = VM_PAGE_TO_PHYS(m_run);
2460 m_new = vm_page_alloc_contig(
2462 0, pa - 1, PAGE_SIZE, 0,
2463 VM_MEMATTR_DEFAULT);
2465 if (m_new == NULL) {
2467 m_new = vm_page_alloc_contig(
2469 pa, high, PAGE_SIZE, 0,
2470 VM_MEMATTR_DEFAULT);
2472 if (m_new == NULL) {
2476 KASSERT(m_new->wire_count == 0,
2477 ("page %p is wired", m));
2480 * Replace "m" with the new page. For
2481 * vm_page_replace(), "m" must be busy
2482 * and dequeued. Finally, change "m"
2483 * as if vm_page_free() was called.
2485 if (object->ref_count != 0)
2487 m_new->aflags = m->aflags;
2488 KASSERT(m_new->oflags == VPO_UNMANAGED,
2489 ("page %p is managed", m));
2490 m_new->oflags = m->oflags & VPO_NOSYNC;
2491 pmap_copy_page(m, m_new);
2492 m_new->valid = m->valid;
2493 m_new->dirty = m->dirty;
2494 m->flags &= ~PG_ZERO;
2497 vm_page_replace_checked(m_new, object,
2503 * The new page must be deactivated
2504 * before the object is unlocked.
2506 new_mtx = vm_page_lockptr(m_new);
2507 if (m_mtx != new_mtx) {
2512 vm_page_deactivate(m_new);
2514 m->flags &= ~PG_ZERO;
2517 KASSERT(m->dirty == 0,
2518 ("page %p is dirty", m));
2520 SLIST_INSERT_HEAD(&free, m, plinks.s.ss);
2524 VM_OBJECT_WUNLOCK(object);
2527 mtx_lock(&vm_page_queue_free_mtx);
2529 if (order < VM_NFREEORDER) {
2531 * The page is enqueued in the physical memory
2532 * allocator's cache/free page queues.
2533 * Moreover, it is the first page in a power-
2534 * of-two-sized run of contiguous cache/free
2535 * pages. Jump ahead to the last page within
2536 * that run, and continue from there.
2538 m += (1 << order) - 1;
2540 #if VM_NRESERVLEVEL > 0
2541 else if (vm_reserv_is_page_free(m))
2544 mtx_unlock(&vm_page_queue_free_mtx);
2545 if (order == VM_NFREEORDER)
2551 if ((m = SLIST_FIRST(&free)) != NULL) {
2552 mtx_lock(&vm_page_queue_free_mtx);
2554 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2555 vm_phys_freecnt_adj(m, 1);
2556 #if VM_NRESERVLEVEL > 0
2557 if (!vm_reserv_free_page(m))
2561 vm_phys_free_pages(m, 0);
2562 } while ((m = SLIST_FIRST(&free)) != NULL);
2563 vm_page_zero_idle_wakeup();
2564 vm_page_free_wakeup();
2565 mtx_unlock(&vm_page_queue_free_mtx);
2572 CTASSERT(powerof2(NRUNS));
2574 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2576 #define MIN_RECLAIM 8
2579 * vm_page_reclaim_contig:
2581 * Reclaim allocated, contiguous physical memory satisfying the specified
2582 * conditions by relocating the virtual pages using that physical memory.
2583 * Returns true if reclamation is successful and false otherwise. Since
2584 * relocation requires the allocation of physical pages, reclamation may
2585 * fail due to a shortage of cache/free pages. When reclamation fails,
2586 * callers are expected to perform VM_WAIT before retrying a failed
2587 * allocation operation, e.g., vm_page_alloc_contig().
2589 * The caller must always specify an allocation class through "req".
2591 * allocation classes:
2592 * VM_ALLOC_NORMAL normal process request
2593 * VM_ALLOC_SYSTEM system *really* needs a page
2594 * VM_ALLOC_INTERRUPT interrupt time request
2596 * The optional allocation flags are ignored.
2598 * "npages" must be greater than zero. Both "alignment" and "boundary"
2599 * must be a power of two.
2602 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2603 u_long alignment, vm_paddr_t boundary)
2605 vm_paddr_t curr_low;
2606 vm_page_t m_run, m_runs[NRUNS];
2607 u_long count, reclaimed;
2608 int error, i, options, req_class;
2610 KASSERT(npages > 0, ("npages is 0"));
2611 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2612 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2613 req_class = req & VM_ALLOC_CLASS_MASK;
2616 * The page daemon is allowed to dig deeper into the free page list.
2618 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2619 req_class = VM_ALLOC_SYSTEM;
2622 * Return if the number of cached and free pages cannot satisfy the
2623 * requested allocation.
2625 count = vm_cnt.v_free_count + vm_cnt.v_cache_count;
2626 if (count < npages + vm_cnt.v_free_reserved || (count < npages +
2627 vm_cnt.v_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2628 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2632 * Scan up to three times, relaxing the restrictions ("options") on
2633 * the reclamation of reservations and superpages each time.
2635 for (options = VPSC_NORESERV;;) {
2637 * Find the highest runs that satisfy the given constraints
2638 * and restrictions, and record them in "m_runs".
2643 m_run = vm_phys_scan_contig(npages, curr_low, high,
2644 alignment, boundary, options);
2647 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2648 m_runs[RUN_INDEX(count)] = m_run;
2653 * Reclaim the highest runs in LIFO (descending) order until
2654 * the number of reclaimed pages, "reclaimed", is at least
2655 * MIN_RECLAIM. Reset "reclaimed" each time because each
2656 * reclamation is idempotent, and runs will (likely) recur
2657 * from one scan to the next as restrictions are relaxed.
2660 for (i = 0; count > 0 && i < NRUNS; i++) {
2662 m_run = m_runs[RUN_INDEX(count)];
2663 error = vm_page_reclaim_run(req_class, npages, m_run,
2666 reclaimed += npages;
2667 if (reclaimed >= MIN_RECLAIM)
2673 * Either relax the restrictions on the next scan or return if
2674 * the last scan had no restrictions.
2676 if (options == VPSC_NORESERV)
2677 options = VPSC_NOSUPER;
2678 else if (options == VPSC_NOSUPER)
2680 else if (options == VPSC_ANY)
2681 return (reclaimed != 0);
2686 * vm_wait: (also see VM_WAIT macro)
2688 * Sleep until free pages are available for allocation.
2689 * - Called in various places before memory allocations.
2695 mtx_lock(&vm_page_queue_free_mtx);
2696 if (curproc == pageproc) {
2697 vm_pageout_pages_needed = 1;
2698 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
2699 PDROP | PSWP, "VMWait", 0);
2701 if (!vm_pages_needed) {
2702 vm_pages_needed = 1;
2703 wakeup(&vm_pages_needed);
2705 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
2711 * vm_waitpfault: (also see VM_WAITPFAULT macro)
2713 * Sleep until free pages are available for allocation.
2714 * - Called only in vm_fault so that processes page faulting
2715 * can be easily tracked.
2716 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2717 * processes will be able to grab memory first. Do not change
2718 * this balance without careful testing first.
2724 mtx_lock(&vm_page_queue_free_mtx);
2725 if (!vm_pages_needed) {
2726 vm_pages_needed = 1;
2727 wakeup(&vm_pages_needed);
2729 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
2733 struct vm_pagequeue *
2734 vm_page_pagequeue(vm_page_t m)
2737 return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2743 * Remove the given page from its current page queue.
2745 * The page must be locked.
2748 vm_page_dequeue(vm_page_t m)
2750 struct vm_pagequeue *pq;
2752 vm_page_assert_locked(m);
2753 KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
2755 pq = vm_page_pagequeue(m);
2756 vm_pagequeue_lock(pq);
2758 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2759 vm_pagequeue_cnt_dec(pq);
2760 vm_pagequeue_unlock(pq);
2764 * vm_page_dequeue_locked:
2766 * Remove the given page from its current page queue.
2768 * The page and page queue must be locked.
2771 vm_page_dequeue_locked(vm_page_t m)
2773 struct vm_pagequeue *pq;
2775 vm_page_lock_assert(m, MA_OWNED);
2776 pq = vm_page_pagequeue(m);
2777 vm_pagequeue_assert_locked(pq);
2779 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2780 vm_pagequeue_cnt_dec(pq);
2786 * Add the given page to the specified page queue.
2788 * The page must be locked.
2791 vm_page_enqueue(uint8_t queue, vm_page_t m)
2793 struct vm_pagequeue *pq;
2795 vm_page_lock_assert(m, MA_OWNED);
2796 KASSERT(queue < PQ_COUNT,
2797 ("vm_page_enqueue: invalid queue %u request for page %p",
2799 pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2800 vm_pagequeue_lock(pq);
2802 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2803 vm_pagequeue_cnt_inc(pq);
2804 vm_pagequeue_unlock(pq);
2810 * Move the given page to the tail of its current page queue.
2812 * The page must be locked.
2815 vm_page_requeue(vm_page_t m)
2817 struct vm_pagequeue *pq;
2819 vm_page_lock_assert(m, MA_OWNED);
2820 KASSERT(m->queue != PQ_NONE,
2821 ("vm_page_requeue: page %p is not queued", m));
2822 pq = vm_page_pagequeue(m);
2823 vm_pagequeue_lock(pq);
2824 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2825 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2826 vm_pagequeue_unlock(pq);
2830 * vm_page_requeue_locked:
2832 * Move the given page to the tail of its current page queue.
2834 * The page queue must be locked.
2837 vm_page_requeue_locked(vm_page_t m)
2839 struct vm_pagequeue *pq;
2841 KASSERT(m->queue != PQ_NONE,
2842 ("vm_page_requeue_locked: page %p is not queued", m));
2843 pq = vm_page_pagequeue(m);
2844 vm_pagequeue_assert_locked(pq);
2845 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2846 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2852 * Put the specified page on the active list (if appropriate).
2853 * Ensure that act_count is at least ACT_INIT but do not otherwise
2856 * The page must be locked.
2859 vm_page_activate(vm_page_t m)
2863 vm_page_lock_assert(m, MA_OWNED);
2864 if ((queue = m->queue) != PQ_ACTIVE) {
2865 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2866 if (m->act_count < ACT_INIT)
2867 m->act_count = ACT_INIT;
2868 if (queue != PQ_NONE)
2870 vm_page_enqueue(PQ_ACTIVE, m);
2872 KASSERT(queue == PQ_NONE,
2873 ("vm_page_activate: wired page %p is queued", m));
2875 if (m->act_count < ACT_INIT)
2876 m->act_count = ACT_INIT;
2881 * vm_page_free_wakeup:
2883 * Helper routine for vm_page_free_toq() and vm_page_cache(). This
2884 * routine is called when a page has been added to the cache or free
2887 * The page queues must be locked.
2890 vm_page_free_wakeup(void)
2893 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2895 * if pageout daemon needs pages, then tell it that there are
2898 if (vm_pageout_pages_needed &&
2899 vm_cnt.v_cache_count + vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
2900 wakeup(&vm_pageout_pages_needed);
2901 vm_pageout_pages_needed = 0;
2904 * wakeup processes that are waiting on memory if we hit a
2905 * high water mark. And wakeup scheduler process if we have
2906 * lots of memory. this process will swapin processes.
2908 if (vm_pages_needed && !vm_page_count_min()) {
2909 vm_pages_needed = 0;
2910 wakeup(&vm_cnt.v_free_count);
2915 * Turn a cached page into a free page, by changing its attributes.
2916 * Keep the statistics up-to-date.
2918 * The free page queue must be locked.
2921 vm_page_cache_turn_free(vm_page_t m)
2924 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2928 KASSERT((m->flags & PG_CACHED) != 0,
2929 ("vm_page_cache_turn_free: page %p is not cached", m));
2930 m->flags &= ~PG_CACHED;
2931 vm_cnt.v_cache_count--;
2932 vm_phys_freecnt_adj(m, 1);
2938 * Returns the given page to the free list,
2939 * disassociating it with any VM object.
2941 * The object must be locked. The page must be locked if it is managed.
2944 vm_page_free_toq(vm_page_t m)
2947 if ((m->oflags & VPO_UNMANAGED) == 0) {
2948 vm_page_lock_assert(m, MA_OWNED);
2949 KASSERT(!pmap_page_is_mapped(m),
2950 ("vm_page_free_toq: freeing mapped page %p", m));
2952 KASSERT(m->queue == PQ_NONE,
2953 ("vm_page_free_toq: unmanaged page %p is queued", m));
2954 PCPU_INC(cnt.v_tfree);
2956 if (vm_page_sbusied(m))
2957 panic("vm_page_free: freeing busy page %p", m);
2960 * Unqueue, then remove page. Note that we cannot destroy
2961 * the page here because we do not want to call the pager's
2962 * callback routine until after we've put the page on the
2963 * appropriate free queue.
2969 * If fictitious remove object association and
2970 * return, otherwise delay object association removal.
2972 if ((m->flags & PG_FICTITIOUS) != 0) {
2979 if (m->wire_count != 0)
2980 panic("vm_page_free: freeing wired page %p", m);
2981 if (m->hold_count != 0) {
2982 m->flags &= ~PG_ZERO;
2983 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2984 ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
2985 m->flags |= PG_UNHOLDFREE;
2988 * Restore the default memory attribute to the page.
2990 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2991 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2994 * Insert the page into the physical memory allocator's
2995 * cache/free page queues.
2997 mtx_lock(&vm_page_queue_free_mtx);
2998 vm_phys_freecnt_adj(m, 1);
2999 #if VM_NRESERVLEVEL > 0
3000 if (!vm_reserv_free_page(m))
3004 vm_phys_free_pages(m, 0);
3005 if ((m->flags & PG_ZERO) != 0)
3006 ++vm_page_zero_count;
3008 vm_page_zero_idle_wakeup();
3009 vm_page_free_wakeup();
3010 mtx_unlock(&vm_page_queue_free_mtx);
3017 * Mark this page as wired down by yet
3018 * another map, removing it from paging queues
3021 * If the page is fictitious, then its wire count must remain one.
3023 * The page must be locked.
3026 vm_page_wire(vm_page_t m)
3030 * Only bump the wire statistics if the page is not already wired,
3031 * and only unqueue the page if it is on some queue (if it is unmanaged
3032 * it is already off the queues).
3034 vm_page_lock_assert(m, MA_OWNED);
3035 if ((m->flags & PG_FICTITIOUS) != 0) {
3036 KASSERT(m->wire_count == 1,
3037 ("vm_page_wire: fictitious page %p's wire count isn't one",
3041 if (m->wire_count == 0) {
3042 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
3043 m->queue == PQ_NONE,
3044 ("vm_page_wire: unmanaged page %p is queued", m));
3046 atomic_add_int(&vm_cnt.v_wire_count, 1);
3049 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
3055 * Release one wiring of the specified page, potentially allowing it to be
3056 * paged out. Returns TRUE if the number of wirings transitions to zero and
3059 * Only managed pages belonging to an object can be paged out. If the number
3060 * of wirings transitions to zero and the page is eligible for page out, then
3061 * the page is added to the specified paging queue (unless PQ_NONE is
3064 * If a page is fictitious, then its wire count must always be one.
3066 * A managed page must be locked.
3069 vm_page_unwire(vm_page_t m, uint8_t queue)
3072 KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
3073 ("vm_page_unwire: invalid queue %u request for page %p",
3075 if ((m->oflags & VPO_UNMANAGED) == 0)
3076 vm_page_assert_locked(m);
3077 if ((m->flags & PG_FICTITIOUS) != 0) {
3078 KASSERT(m->wire_count == 1,
3079 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
3082 if (m->wire_count > 0) {
3084 if (m->wire_count == 0) {
3085 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3086 if ((m->oflags & VPO_UNMANAGED) == 0 &&
3087 m->object != NULL && queue != PQ_NONE) {
3088 if (queue == PQ_INACTIVE)
3089 m->flags &= ~PG_WINATCFLS;
3090 vm_page_enqueue(queue, m);
3096 panic("vm_page_unwire: page %p's wire count is zero", m);
3100 * Move the specified page to the inactive queue.
3102 * Many pages placed on the inactive queue should actually go
3103 * into the cache, but it is difficult to figure out which. What
3104 * we do instead, if the inactive target is well met, is to put
3105 * clean pages at the head of the inactive queue instead of the tail.
3106 * This will cause them to be moved to the cache more quickly and
3107 * if not actively re-referenced, reclaimed more quickly. If we just
3108 * stick these pages at the end of the inactive queue, heavy filesystem
3109 * meta-data accesses can cause an unnecessary paging load on memory bound
3110 * processes. This optimization causes one-time-use metadata to be
3111 * reused more quickly.
3113 * Normally noreuse is FALSE, resulting in LRU operation. noreuse is set
3114 * to TRUE if we want this page to be 'as if it were placed in the cache',
3115 * except without unmapping it from the process address space. In
3116 * practice this is implemented by inserting the page at the head of the
3117 * queue, using a marker page to guide FIFO insertion ordering.
3119 * The page must be locked.
3122 _vm_page_deactivate(vm_page_t m, boolean_t noreuse)
3124 struct vm_pagequeue *pq;
3127 vm_page_assert_locked(m);
3130 * Ignore if the page is already inactive, unless it is unlikely to be
3133 if ((queue = m->queue) == PQ_INACTIVE && !noreuse)
3135 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
3136 pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
3137 /* Avoid multiple acquisitions of the inactive queue lock. */
3138 if (queue == PQ_INACTIVE) {
3139 vm_pagequeue_lock(pq);
3140 vm_page_dequeue_locked(m);
3142 if (queue != PQ_NONE)
3144 m->flags &= ~PG_WINATCFLS;
3145 vm_pagequeue_lock(pq);
3147 m->queue = PQ_INACTIVE;
3149 TAILQ_INSERT_BEFORE(&vm_phys_domain(m)->vmd_inacthead,
3152 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3153 vm_pagequeue_cnt_inc(pq);
3154 vm_pagequeue_unlock(pq);
3159 * Move the specified page to the inactive queue.
3161 * The page must be locked.
3164 vm_page_deactivate(vm_page_t m)
3167 _vm_page_deactivate(m, FALSE);
3171 * Move the specified page to the inactive queue with the expectation
3172 * that it is unlikely to be reused.
3174 * The page must be locked.
3177 vm_page_deactivate_noreuse(vm_page_t m)
3180 _vm_page_deactivate(m, TRUE);
3184 * vm_page_try_to_cache:
3186 * Returns 0 on failure, 1 on success
3189 vm_page_try_to_cache(vm_page_t m)
3192 vm_page_lock_assert(m, MA_OWNED);
3193 VM_OBJECT_ASSERT_WLOCKED(m->object);
3194 if (m->dirty || m->hold_count || m->wire_count ||
3195 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
3205 * vm_page_try_to_free()
3207 * Attempt to free the page. If we cannot free it, we do nothing.
3208 * 1 is returned on success, 0 on failure.
3211 vm_page_try_to_free(vm_page_t m)
3214 vm_page_lock_assert(m, MA_OWNED);
3215 if (m->object != NULL)
3216 VM_OBJECT_ASSERT_WLOCKED(m->object);
3217 if (m->dirty || m->hold_count || m->wire_count ||
3218 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
3230 * Put the specified page onto the page cache queue (if appropriate).
3232 * The object and page must be locked.
3235 vm_page_cache(vm_page_t m)
3238 boolean_t cache_was_empty;
3240 vm_page_lock_assert(m, MA_OWNED);
3242 VM_OBJECT_ASSERT_WLOCKED(object);
3243 if (vm_page_busied(m) || (m->oflags & VPO_UNMANAGED) ||
3244 m->hold_count || m->wire_count)
3245 panic("vm_page_cache: attempting to cache busy page");
3246 KASSERT(!pmap_page_is_mapped(m),
3247 ("vm_page_cache: page %p is mapped", m));
3248 KASSERT(m->dirty == 0, ("vm_page_cache: page %p is dirty", m));
3249 if (m->valid == 0 || object->type == OBJT_DEFAULT ||
3250 (object->type == OBJT_SWAP &&
3251 !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
3253 * Hypothesis: A cache-eligible page belonging to a
3254 * default object or swap object but without a backing
3255 * store must be zero filled.
3260 KASSERT((m->flags & PG_CACHED) == 0,
3261 ("vm_page_cache: page %p is already cached", m));
3264 * Remove the page from the paging queues.
3269 * Remove the page from the object's collection of resident
3272 vm_radix_remove(&object->rtree, m->pindex);
3273 TAILQ_REMOVE(&object->memq, m, listq);
3274 object->resident_page_count--;
3277 * Restore the default memory attribute to the page.
3279 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3280 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3283 * Insert the page into the object's collection of cached pages
3284 * and the physical memory allocator's cache/free page queues.
3286 m->flags &= ~PG_ZERO;
3287 mtx_lock(&vm_page_queue_free_mtx);
3288 cache_was_empty = vm_radix_is_empty(&object->cache);
3289 if (vm_radix_insert(&object->cache, m)) {
3290 mtx_unlock(&vm_page_queue_free_mtx);
3291 if (object->resident_page_count == 0)
3292 vdrop(object->handle);
3299 * The above call to vm_radix_insert() could reclaim the one pre-
3300 * existing cached page from this object, resulting in a call to
3303 if (!cache_was_empty)
3304 cache_was_empty = vm_radix_is_singleton(&object->cache);
3306 m->flags |= PG_CACHED;
3307 vm_cnt.v_cache_count++;
3308 PCPU_INC(cnt.v_tcached);
3309 #if VM_NRESERVLEVEL > 0
3310 if (!vm_reserv_free_page(m)) {
3314 vm_phys_free_pages(m, 0);
3316 vm_page_free_wakeup();
3317 mtx_unlock(&vm_page_queue_free_mtx);
3320 * Increment the vnode's hold count if this is the object's only
3321 * cached page. Decrement the vnode's hold count if this was
3322 * the object's only resident page.
3324 if (object->type == OBJT_VNODE) {
3325 if (cache_was_empty && object->resident_page_count != 0)
3326 vhold(object->handle);
3327 else if (!cache_was_empty && object->resident_page_count == 0)
3328 vdrop(object->handle);
3335 * Deactivate or do nothing, as appropriate.
3337 * The object and page must be locked.
3340 vm_page_advise(vm_page_t m, int advice)
3343 vm_page_assert_locked(m);
3344 VM_OBJECT_ASSERT_WLOCKED(m->object);
3345 if (advice == MADV_FREE)
3347 * Mark the page clean. This will allow the page to be freed
3348 * up by the system. However, such pages are often reused
3349 * quickly by malloc() so we do not do anything that would
3350 * cause a page fault if we can help it.
3352 * Specifically, we do not try to actually free the page now
3353 * nor do we try to put it in the cache (which would cause a
3354 * page fault on reuse).
3356 * But we do make the page as freeable as we can without
3357 * actually taking the step of unmapping it.
3360 else if (advice != MADV_DONTNEED)
3364 * Clear any references to the page. Otherwise, the page daemon will
3365 * immediately reactivate the page.
3367 vm_page_aflag_clear(m, PGA_REFERENCED);
3369 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3373 * Place clean pages at the head of the inactive queue rather than the
3374 * tail, thus defeating the queue's LRU operation and ensuring that the
3375 * page will be reused quickly.
3377 _vm_page_deactivate(m, m->dirty == 0);
3381 * Grab a page, waiting until we are waken up due to the page
3382 * changing state. We keep on waiting, if the page continues
3383 * to be in the object. If the page doesn't exist, first allocate it
3384 * and then conditionally zero it.
3386 * This routine may sleep.
3388 * The object must be locked on entry. The lock will, however, be released
3389 * and reacquired if the routine sleeps.
3392 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3397 VM_OBJECT_ASSERT_WLOCKED(object);
3398 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3399 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3400 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3402 if ((m = vm_page_lookup(object, pindex)) != NULL) {
3403 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3404 vm_page_xbusied(m) : vm_page_busied(m);
3406 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3409 * Reference the page before unlocking and
3410 * sleeping so that the page daemon is less
3411 * likely to reclaim it.
3413 vm_page_aflag_set(m, PGA_REFERENCED);
3415 VM_OBJECT_WUNLOCK(object);
3416 vm_page_busy_sleep(m, "pgrbwt");
3417 VM_OBJECT_WLOCK(object);
3420 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3426 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3428 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3433 m = vm_page_alloc(object, pindex, allocflags);
3435 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3437 VM_OBJECT_WUNLOCK(object);
3439 VM_OBJECT_WLOCK(object);
3441 } else if (m->valid != 0)
3443 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3449 * Mapping function for valid or dirty bits in a page.
3451 * Inputs are required to range within a page.
3454 vm_page_bits(int base, int size)
3460 base + size <= PAGE_SIZE,
3461 ("vm_page_bits: illegal base/size %d/%d", base, size)
3464 if (size == 0) /* handle degenerate case */
3467 first_bit = base >> DEV_BSHIFT;
3468 last_bit = (base + size - 1) >> DEV_BSHIFT;
3470 return (((vm_page_bits_t)2 << last_bit) -
3471 ((vm_page_bits_t)1 << first_bit));
3475 * vm_page_set_valid_range:
3477 * Sets portions of a page valid. The arguments are expected
3478 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3479 * of any partial chunks touched by the range. The invalid portion of
3480 * such chunks will be zeroed.
3482 * (base + size) must be less then or equal to PAGE_SIZE.
3485 vm_page_set_valid_range(vm_page_t m, int base, int size)
3489 VM_OBJECT_ASSERT_WLOCKED(m->object);
3490 if (size == 0) /* handle degenerate case */
3494 * If the base is not DEV_BSIZE aligned and the valid
3495 * bit is clear, we have to zero out a portion of the
3498 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
3499 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
3500 pmap_zero_page_area(m, frag, base - frag);
3503 * If the ending offset is not DEV_BSIZE aligned and the
3504 * valid bit is clear, we have to zero out a portion of
3507 endoff = base + size;
3508 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
3509 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
3510 pmap_zero_page_area(m, endoff,
3511 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3514 * Assert that no previously invalid block that is now being validated
3517 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
3518 ("vm_page_set_valid_range: page %p is dirty", m));
3521 * Set valid bits inclusive of any overlap.
3523 m->valid |= vm_page_bits(base, size);
3527 * Clear the given bits from the specified page's dirty field.
3529 static __inline void
3530 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
3533 #if PAGE_SIZE < 16384
3538 * If the object is locked and the page is neither exclusive busy nor
3539 * write mapped, then the page's dirty field cannot possibly be
3540 * set by a concurrent pmap operation.
3542 VM_OBJECT_ASSERT_WLOCKED(m->object);
3543 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
3544 m->dirty &= ~pagebits;
3547 * The pmap layer can call vm_page_dirty() without
3548 * holding a distinguished lock. The combination of
3549 * the object's lock and an atomic operation suffice
3550 * to guarantee consistency of the page dirty field.
3552 * For PAGE_SIZE == 32768 case, compiler already
3553 * properly aligns the dirty field, so no forcible
3554 * alignment is needed. Only require existence of
3555 * atomic_clear_64 when page size is 32768.
3557 addr = (uintptr_t)&m->dirty;
3558 #if PAGE_SIZE == 32768
3559 atomic_clear_64((uint64_t *)addr, pagebits);
3560 #elif PAGE_SIZE == 16384
3561 atomic_clear_32((uint32_t *)addr, pagebits);
3562 #else /* PAGE_SIZE <= 8192 */
3564 * Use a trick to perform a 32-bit atomic on the
3565 * containing aligned word, to not depend on the existence
3566 * of atomic_clear_{8, 16}.
3568 shift = addr & (sizeof(uint32_t) - 1);
3569 #if BYTE_ORDER == BIG_ENDIAN
3570 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
3574 addr &= ~(sizeof(uint32_t) - 1);
3575 atomic_clear_32((uint32_t *)addr, pagebits << shift);
3576 #endif /* PAGE_SIZE */
3581 * vm_page_set_validclean:
3583 * Sets portions of a page valid and clean. The arguments are expected
3584 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3585 * of any partial chunks touched by the range. The invalid portion of
3586 * such chunks will be zero'd.
3588 * (base + size) must be less then or equal to PAGE_SIZE.
3591 vm_page_set_validclean(vm_page_t m, int base, int size)
3593 vm_page_bits_t oldvalid, pagebits;
3596 VM_OBJECT_ASSERT_WLOCKED(m->object);
3597 if (size == 0) /* handle degenerate case */
3601 * If the base is not DEV_BSIZE aligned and the valid
3602 * bit is clear, we have to zero out a portion of the
3605 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
3606 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
3607 pmap_zero_page_area(m, frag, base - frag);
3610 * If the ending offset is not DEV_BSIZE aligned and the
3611 * valid bit is clear, we have to zero out a portion of
3614 endoff = base + size;
3615 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
3616 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
3617 pmap_zero_page_area(m, endoff,
3618 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3621 * Set valid, clear dirty bits. If validating the entire
3622 * page we can safely clear the pmap modify bit. We also
3623 * use this opportunity to clear the VPO_NOSYNC flag. If a process
3624 * takes a write fault on a MAP_NOSYNC memory area the flag will
3627 * We set valid bits inclusive of any overlap, but we can only
3628 * clear dirty bits for DEV_BSIZE chunks that are fully within
3631 oldvalid = m->valid;
3632 pagebits = vm_page_bits(base, size);
3633 m->valid |= pagebits;
3635 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
3636 frag = DEV_BSIZE - frag;
3642 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
3644 if (base == 0 && size == PAGE_SIZE) {
3646 * The page can only be modified within the pmap if it is
3647 * mapped, and it can only be mapped if it was previously
3650 if (oldvalid == VM_PAGE_BITS_ALL)
3652 * Perform the pmap_clear_modify() first. Otherwise,
3653 * a concurrent pmap operation, such as
3654 * pmap_protect(), could clear a modification in the
3655 * pmap and set the dirty field on the page before
3656 * pmap_clear_modify() had begun and after the dirty
3657 * field was cleared here.
3659 pmap_clear_modify(m);
3661 m->oflags &= ~VPO_NOSYNC;
3662 } else if (oldvalid != VM_PAGE_BITS_ALL)
3663 m->dirty &= ~pagebits;
3665 vm_page_clear_dirty_mask(m, pagebits);
3669 vm_page_clear_dirty(vm_page_t m, int base, int size)
3672 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
3676 * vm_page_set_invalid:
3678 * Invalidates DEV_BSIZE'd chunks within a page. Both the
3679 * valid and dirty bits for the effected areas are cleared.
3682 vm_page_set_invalid(vm_page_t m, int base, int size)
3684 vm_page_bits_t bits;
3688 VM_OBJECT_ASSERT_WLOCKED(object);
3689 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
3690 size >= object->un_pager.vnp.vnp_size)
3691 bits = VM_PAGE_BITS_ALL;
3693 bits = vm_page_bits(base, size);
3694 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
3697 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3698 !pmap_page_is_mapped(m),
3699 ("vm_page_set_invalid: page %p is mapped", m));
3705 * vm_page_zero_invalid()
3707 * The kernel assumes that the invalid portions of a page contain
3708 * garbage, but such pages can be mapped into memory by user code.
3709 * When this occurs, we must zero out the non-valid portions of the
3710 * page so user code sees what it expects.
3712 * Pages are most often semi-valid when the end of a file is mapped
3713 * into memory and the file's size is not page aligned.
3716 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3721 VM_OBJECT_ASSERT_WLOCKED(m->object);
3723 * Scan the valid bits looking for invalid sections that
3724 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
3725 * valid bit may be set ) have already been zeroed by
3726 * vm_page_set_validclean().
3728 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3729 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3730 (m->valid & ((vm_page_bits_t)1 << i))) {
3732 pmap_zero_page_area(m,
3733 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3740 * setvalid is TRUE when we can safely set the zero'd areas
3741 * as being valid. We can do this if there are no cache consistancy
3742 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3745 m->valid = VM_PAGE_BITS_ALL;
3751 * Is (partial) page valid? Note that the case where size == 0
3752 * will return FALSE in the degenerate case where the page is
3753 * entirely invalid, and TRUE otherwise.
3756 vm_page_is_valid(vm_page_t m, int base, int size)
3758 vm_page_bits_t bits;
3760 VM_OBJECT_ASSERT_LOCKED(m->object);
3761 bits = vm_page_bits(base, size);
3762 return (m->valid != 0 && (m->valid & bits) == bits);
3766 * vm_page_ps_is_valid:
3768 * Returns TRUE if the entire (super)page is valid and FALSE otherwise.
3771 vm_page_ps_is_valid(vm_page_t m)
3775 VM_OBJECT_ASSERT_LOCKED(m->object);
3776 npages = atop(pagesizes[m->psind]);
3779 * The physically contiguous pages that make up a superpage, i.e., a
3780 * page with a page size index ("psind") greater than zero, will
3781 * occupy adjacent entries in vm_page_array[].
3783 for (i = 0; i < npages; i++) {
3784 if (m[i].valid != VM_PAGE_BITS_ALL)
3791 * Set the page's dirty bits if the page is modified.
3794 vm_page_test_dirty(vm_page_t m)
3797 VM_OBJECT_ASSERT_WLOCKED(m->object);
3798 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3803 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3806 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3810 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3813 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3817 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3820 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3823 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3825 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3828 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3832 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3835 mtx_assert_(vm_page_lockptr(m), a, file, line);
3841 vm_page_object_lock_assert(vm_page_t m)
3845 * Certain of the page's fields may only be modified by the
3846 * holder of the containing object's lock or the exclusive busy.
3847 * holder. Unfortunately, the holder of the write busy is
3848 * not recorded, and thus cannot be checked here.
3850 if (m->object != NULL && !vm_page_xbusied(m))
3851 VM_OBJECT_ASSERT_WLOCKED(m->object);
3855 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3858 if ((bits & PGA_WRITEABLE) == 0)
3862 * The PGA_WRITEABLE flag can only be set if the page is
3863 * managed, is exclusively busied or the object is locked.
3864 * Currently, this flag is only set by pmap_enter().
3866 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3867 ("PGA_WRITEABLE on unmanaged page"));
3868 if (!vm_page_xbusied(m))
3869 VM_OBJECT_ASSERT_LOCKED(m->object);
3873 #include "opt_ddb.h"
3875 #include <sys/kernel.h>
3877 #include <ddb/ddb.h>
3879 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3881 db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
3882 db_printf("vm_cnt.v_cache_count: %d\n", vm_cnt.v_cache_count);
3883 db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
3884 db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
3885 db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
3886 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
3887 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
3888 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
3889 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
3892 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3896 db_printf("pq_free %d pq_cache %d\n",
3897 vm_cnt.v_free_count, vm_cnt.v_cache_count);
3898 for (dom = 0; dom < vm_ndomains; dom++) {
3900 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pass %d\n",
3902 vm_dom[dom].vmd_page_count,
3903 vm_dom[dom].vmd_free_count,
3904 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3905 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
3906 vm_dom[dom].vmd_pass);
3910 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3916 db_printf("show pginfo addr\n");
3920 phys = strchr(modif, 'p') != NULL;
3922 m = PHYS_TO_VM_PAGE(addr);
3924 m = (vm_page_t)addr;
3926 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3927 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3928 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3929 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3930 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);