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>
103 #include <sys/sysctl.h>
104 #include <sys/vmmeter.h>
105 #include <sys/vnode.h>
109 #include <vm/vm_param.h>
110 #include <vm/vm_kern.h>
111 #include <vm/vm_object.h>
112 #include <vm/vm_page.h>
113 #include <vm/vm_pageout.h>
114 #include <vm/vm_pager.h>
115 #include <vm/vm_phys.h>
116 #include <vm/vm_radix.h>
117 #include <vm/vm_reserv.h>
118 #include <vm/vm_extern.h>
120 #include <vm/uma_int.h>
122 #include <machine/md_var.h>
125 * Associated with page of user-allocatable memory is a
129 struct vm_domain vm_dom[MAXMEMDOM];
130 struct mtx_padalign vm_page_queue_free_mtx;
132 struct mtx_padalign pa_lock[PA_LOCK_COUNT];
134 vm_page_t vm_page_array;
135 long vm_page_array_size;
137 int vm_page_zero_count;
139 static int boot_pages = UMA_BOOT_PAGES;
140 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
142 "number of pages allocated for bootstrapping the VM system");
144 static int pa_tryrelock_restart;
145 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
146 &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
148 static TAILQ_HEAD(, vm_page) blacklist_head;
149 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
150 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
151 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
153 /* Is the page daemon waiting for free pages? */
154 static int vm_pageout_pages_needed;
156 static uma_zone_t fakepg_zone;
158 static struct vnode *vm_page_alloc_init(vm_page_t m);
159 static void vm_page_cache_turn_free(vm_page_t m);
160 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
161 static void vm_page_enqueue(uint8_t queue, vm_page_t m);
162 static void vm_page_free_wakeup(void);
163 static void vm_page_init_fakepg(void *dummy);
164 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
165 vm_pindex_t pindex, vm_page_t mpred);
166 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
168 static int vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
171 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init_fakepg, NULL);
174 vm_page_init_fakepg(void *dummy)
177 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
178 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
181 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
182 #if PAGE_SIZE == 32768
184 CTASSERT(sizeof(u_long) >= 8);
189 * Try to acquire a physical address lock while a pmap is locked. If we
190 * fail to trylock we unlock and lock the pmap directly and cache the
191 * locked pa in *locked. The caller should then restart their loop in case
192 * the virtual to physical mapping has changed.
195 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
202 PA_LOCK_ASSERT(lockpa, MA_OWNED);
203 if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
210 atomic_add_int(&pa_tryrelock_restart, 1);
219 * Sets the page size, perhaps based upon the memory
220 * size. Must be called before any use of page-size
221 * dependent functions.
224 vm_set_page_size(void)
226 if (vm_cnt.v_page_size == 0)
227 vm_cnt.v_page_size = PAGE_SIZE;
228 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
229 panic("vm_set_page_size: page size not a power of two");
233 * vm_page_blacklist_next:
235 * Find the next entry in the provided string of blacklist
236 * addresses. Entries are separated by space, comma, or newline.
237 * If an invalid integer is encountered then the rest of the
238 * string is skipped. Updates the list pointer to the next
239 * character, or NULL if the string is exhausted or invalid.
242 vm_page_blacklist_next(char **list, char *end)
247 if (list == NULL || *list == NULL)
255 * If there's no end pointer then the buffer is coming from
256 * the kenv and we know it's null-terminated.
259 end = *list + strlen(*list);
261 /* Ensure that strtoq() won't walk off the end */
263 if (*end == '\n' || *end == ' ' || *end == ',')
266 printf("Blacklist not terminated, skipping\n");
272 for (pos = *list; *pos != '\0'; pos = cp) {
273 bad = strtoq(pos, &cp, 0);
274 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
283 if (*cp == '\0' || ++cp >= end)
287 return (trunc_page(bad));
289 printf("Garbage in RAM blacklist, skipping\n");
295 * vm_page_blacklist_check:
297 * Iterate through the provided string of blacklist addresses, pulling
298 * each entry out of the physical allocator free list and putting it
299 * onto a list for reporting via the vm.page_blacklist sysctl.
302 vm_page_blacklist_check(char *list, char *end)
310 while (next != NULL) {
311 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
313 m = vm_phys_paddr_to_vm_page(pa);
316 mtx_lock(&vm_page_queue_free_mtx);
317 ret = vm_phys_unfree_page(m);
318 mtx_unlock(&vm_page_queue_free_mtx);
320 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
322 printf("Skipping page with pa 0x%jx\n",
329 * vm_page_blacklist_load:
331 * Search for a special module named "ram_blacklist". It'll be a
332 * plain text file provided by the user via the loader directive
336 vm_page_blacklist_load(char **list, char **end)
345 mod = preload_search_by_type("ram_blacklist");
347 ptr = preload_fetch_addr(mod);
348 len = preload_fetch_size(mod);
359 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
366 error = sysctl_wire_old_buffer(req, 0);
369 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
370 TAILQ_FOREACH(m, &blacklist_head, listq) {
371 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
372 (uintmax_t)m->phys_addr);
375 error = sbuf_finish(&sbuf);
381 vm_page_domain_init(struct vm_domain *vmd)
383 struct vm_pagequeue *pq;
386 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
387 "vm inactive pagequeue";
388 *__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_vcnt) =
389 &vm_cnt.v_inactive_count;
390 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
391 "vm active pagequeue";
392 *__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_vcnt) =
393 &vm_cnt.v_active_count;
394 vmd->vmd_page_count = 0;
395 vmd->vmd_free_count = 0;
397 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;
433 vaddr = round_page(vaddr);
435 for (i = 0; phys_avail[i + 1]; i += 2) {
436 phys_avail[i] = round_page(phys_avail[i]);
437 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
440 low_water = phys_avail[0];
441 high_water = phys_avail[1];
443 for (i = 0; i < vm_phys_nsegs; i++) {
444 if (vm_phys_segs[i].start < low_water)
445 low_water = vm_phys_segs[i].start;
446 if (vm_phys_segs[i].end > high_water)
447 high_water = vm_phys_segs[i].end;
449 for (i = 0; phys_avail[i + 1]; i += 2) {
450 vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
452 if (size > biggestsize) {
456 if (phys_avail[i] < low_water)
457 low_water = phys_avail[i];
458 if (phys_avail[i + 1] > high_water)
459 high_water = phys_avail[i + 1];
462 end = phys_avail[biggestone+1];
465 * Initialize the page and queue locks.
467 mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
468 for (i = 0; i < PA_LOCK_COUNT; i++)
469 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
470 for (i = 0; i < vm_ndomains; i++)
471 vm_page_domain_init(&vm_dom[i]);
474 * Almost all of the pages needed for boot strapping UMA are used
475 * for zone structures, so if the number of CPUs results in those
476 * structures taking more than one page each, we set aside more pages
477 * in proportion to the zone structure size.
479 pages_per_zone = howmany(sizeof(struct uma_zone) +
480 sizeof(struct uma_cache) * (mp_maxid + 1), UMA_SLAB_SIZE);
481 if (pages_per_zone > 1) {
482 /* Reserve more pages so that we don't run out. */
483 boot_pages = UMA_BOOT_PAGES_ZONES * pages_per_zone;
487 * Allocate memory for use when boot strapping the kernel memory
490 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
491 * manually fetch the value.
493 TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
494 new_end = end - (boot_pages * UMA_SLAB_SIZE);
495 new_end = trunc_page(new_end);
496 mapped = pmap_map(&vaddr, new_end, end,
497 VM_PROT_READ | VM_PROT_WRITE);
498 bzero((void *)mapped, end - new_end);
499 uma_startup((void *)mapped, boot_pages);
501 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
502 defined(__i386__) || defined(__mips__)
504 * Allocate a bitmap to indicate that a random physical page
505 * needs to be included in a minidump.
507 * The amd64 port needs this to indicate which direct map pages
508 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
510 * However, i386 still needs this workspace internally within the
511 * minidump code. In theory, they are not needed on i386, but are
512 * included should the sf_buf code decide to use them.
515 for (i = 0; dump_avail[i + 1] != 0; i += 2)
516 if (dump_avail[i + 1] > last_pa)
517 last_pa = dump_avail[i + 1];
518 page_range = last_pa / PAGE_SIZE;
519 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
520 new_end -= vm_page_dump_size;
521 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
522 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
523 bzero((void *)vm_page_dump, vm_page_dump_size);
527 * Request that the physical pages underlying the message buffer be
528 * included in a crash dump. Since the message buffer is accessed
529 * through the direct map, they are not automatically included.
531 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
532 last_pa = pa + round_page(msgbufsize);
533 while (pa < last_pa) {
539 * Compute the number of pages of memory that will be available for
540 * use (taking into account the overhead of a page structure per
543 first_page = low_water / PAGE_SIZE;
544 #ifdef VM_PHYSSEG_SPARSE
546 for (i = 0; i < vm_phys_nsegs; i++) {
547 page_range += atop(vm_phys_segs[i].end -
548 vm_phys_segs[i].start);
550 for (i = 0; phys_avail[i + 1] != 0; i += 2)
551 page_range += atop(phys_avail[i + 1] - phys_avail[i]);
552 #elif defined(VM_PHYSSEG_DENSE)
553 page_range = high_water / PAGE_SIZE - first_page;
555 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
560 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
565 * Initialize the mem entry structures now, and put them in the free
568 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
569 mapped = pmap_map(&vaddr, new_end, end,
570 VM_PROT_READ | VM_PROT_WRITE);
571 vm_page_array = (vm_page_t) mapped;
572 #if VM_NRESERVLEVEL > 0
574 * Allocate memory for the reservation management system's data
577 new_end = vm_reserv_startup(&vaddr, new_end, high_water);
579 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
581 * pmap_map on arm64, amd64, and mips can come out of the direct-map,
582 * not kvm like i386, so the pages must be tracked for a crashdump to
583 * include this data. This includes the vm_page_array and the early
584 * UMA bootstrap pages.
586 for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
589 phys_avail[biggestone + 1] = new_end;
592 * Add physical memory segments corresponding to the available
595 for (i = 0; phys_avail[i + 1] != 0; i += 2)
596 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
599 * Clear all of the page structures
601 bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
602 for (i = 0; i < page_range; i++)
603 vm_page_array[i].order = VM_NFREEORDER;
604 vm_page_array_size = page_range;
607 * Initialize the physical memory allocator.
612 * Add every available physical page that is not blacklisted to
615 vm_cnt.v_page_count = 0;
616 vm_cnt.v_free_count = 0;
617 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
619 last_pa = phys_avail[i + 1];
620 while (pa < last_pa) {
621 vm_phys_add_page(pa);
626 TAILQ_INIT(&blacklist_head);
627 vm_page_blacklist_load(&list, &listend);
628 vm_page_blacklist_check(list, listend);
630 list = kern_getenv("vm.blacklist");
631 vm_page_blacklist_check(list, NULL);
634 #if VM_NRESERVLEVEL > 0
636 * Initialize the reservation management system.
644 vm_page_reference(vm_page_t m)
647 vm_page_aflag_set(m, PGA_REFERENCED);
651 * vm_page_busy_downgrade:
653 * Downgrade an exclusive busy page into a single shared busy page.
656 vm_page_busy_downgrade(vm_page_t m)
661 vm_page_assert_xbusied(m);
662 locked = mtx_owned(vm_page_lockptr(m));
666 x &= VPB_BIT_WAITERS;
667 if (x != 0 && !locked)
669 if (atomic_cmpset_rel_int(&m->busy_lock,
670 VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1)))
672 if (x != 0 && !locked)
685 * Return a positive value if the page is shared busied, 0 otherwise.
688 vm_page_sbusied(vm_page_t m)
693 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
699 * Shared unbusy a page.
702 vm_page_sunbusy(vm_page_t m)
706 vm_page_assert_sbusied(m);
710 if (VPB_SHARERS(x) > 1) {
711 if (atomic_cmpset_int(&m->busy_lock, x,
716 if ((x & VPB_BIT_WAITERS) == 0) {
717 KASSERT(x == VPB_SHARERS_WORD(1),
718 ("vm_page_sunbusy: invalid lock state"));
719 if (atomic_cmpset_int(&m->busy_lock,
720 VPB_SHARERS_WORD(1), VPB_UNBUSIED))
724 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
725 ("vm_page_sunbusy: invalid lock state for waiters"));
728 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
739 * vm_page_busy_sleep:
741 * Sleep and release the page lock, using the page pointer as wchan.
742 * This is used to implement the hard-path of busying mechanism.
744 * The given page must be locked.
746 * If nonshared is true, sleep only if the page is xbusy.
749 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
753 vm_page_assert_locked(m);
756 if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
757 ((x & VPB_BIT_WAITERS) == 0 &&
758 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
762 msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
768 * Try to shared busy a page.
769 * If the operation succeeds 1 is returned otherwise 0.
770 * The operation never sleeps.
773 vm_page_trysbusy(vm_page_t m)
779 if ((x & VPB_BIT_SHARED) == 0)
781 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
787 vm_page_xunbusy_locked(vm_page_t m)
790 vm_page_assert_xbusied(m);
791 vm_page_assert_locked(m);
793 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
794 /* There is a waiter, do wakeup() instead of vm_page_flash(). */
799 vm_page_xunbusy_maybelocked(vm_page_t m)
803 vm_page_assert_xbusied(m);
806 * Fast path for unbusy. If it succeeds, we know that there
807 * are no waiters, so we do not need a wakeup.
809 if (atomic_cmpset_rel_int(&m->busy_lock, VPB_SINGLE_EXCLUSIVER,
813 lockacq = !mtx_owned(vm_page_lockptr(m));
816 vm_page_xunbusy_locked(m);
822 * vm_page_xunbusy_hard:
824 * Called after the first try the exclusive unbusy of a page failed.
825 * It is assumed that the waiters bit is on.
828 vm_page_xunbusy_hard(vm_page_t m)
831 vm_page_assert_xbusied(m);
834 vm_page_xunbusy_locked(m);
841 * Wakeup anyone waiting for the page.
842 * The ownership bits do not change.
844 * The given page must be locked.
847 vm_page_flash(vm_page_t m)
851 vm_page_lock_assert(m, MA_OWNED);
855 if ((x & VPB_BIT_WAITERS) == 0)
857 if (atomic_cmpset_int(&m->busy_lock, x,
858 x & (~VPB_BIT_WAITERS)))
865 * Keep page from being freed by the page daemon
866 * much of the same effect as wiring, except much lower
867 * overhead and should be used only for *very* temporary
868 * holding ("wiring").
871 vm_page_hold(vm_page_t mem)
874 vm_page_lock_assert(mem, MA_OWNED);
879 vm_page_unhold(vm_page_t mem)
882 vm_page_lock_assert(mem, MA_OWNED);
883 KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
885 if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
886 vm_page_free_toq(mem);
890 * vm_page_unhold_pages:
892 * Unhold each of the pages that is referenced by the given array.
895 vm_page_unhold_pages(vm_page_t *ma, int count)
897 struct mtx *mtx, *new_mtx;
900 for (; count != 0; count--) {
902 * Avoid releasing and reacquiring the same page lock.
904 new_mtx = vm_page_lockptr(*ma);
905 if (mtx != new_mtx) {
919 PHYS_TO_VM_PAGE(vm_paddr_t pa)
923 #ifdef VM_PHYSSEG_SPARSE
924 m = vm_phys_paddr_to_vm_page(pa);
926 m = vm_phys_fictitious_to_vm_page(pa);
928 #elif defined(VM_PHYSSEG_DENSE)
932 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
933 m = &vm_page_array[pi - first_page];
936 return (vm_phys_fictitious_to_vm_page(pa));
938 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
945 * Create a fictitious page with the specified physical address and
946 * memory attribute. The memory attribute is the only the machine-
947 * dependent aspect of a fictitious page that must be initialized.
950 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
954 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
955 vm_page_initfake(m, paddr, memattr);
960 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
963 if ((m->flags & PG_FICTITIOUS) != 0) {
965 * The page's memattr might have changed since the
966 * previous initialization. Update the pmap to the
971 m->phys_addr = paddr;
973 /* Fictitious pages don't use "segind". */
974 m->flags = PG_FICTITIOUS;
975 /* Fictitious pages don't use "order" or "pool". */
976 m->oflags = VPO_UNMANAGED;
977 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
981 pmap_page_set_memattr(m, memattr);
987 * Release a fictitious page.
990 vm_page_putfake(vm_page_t m)
993 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
994 KASSERT((m->flags & PG_FICTITIOUS) != 0,
995 ("vm_page_putfake: bad page %p", m));
996 uma_zfree(fakepg_zone, m);
1000 * vm_page_updatefake:
1002 * Update the given fictitious page to the specified physical address and
1006 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1009 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1010 ("vm_page_updatefake: bad page %p", m));
1011 m->phys_addr = paddr;
1012 pmap_page_set_memattr(m, memattr);
1021 vm_page_free(vm_page_t m)
1024 m->flags &= ~PG_ZERO;
1025 vm_page_free_toq(m);
1029 * vm_page_free_zero:
1031 * Free a page to the zerod-pages queue
1034 vm_page_free_zero(vm_page_t m)
1037 m->flags |= PG_ZERO;
1038 vm_page_free_toq(m);
1042 * Unbusy and handle the page queueing for a page from a getpages request that
1043 * was optionally read ahead or behind.
1046 vm_page_readahead_finish(vm_page_t m)
1049 /* We shouldn't put invalid pages on queues. */
1050 KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
1053 * Since the page is not the actually needed one, whether it should
1054 * be activated or deactivated is not obvious. Empirical results
1055 * have shown that deactivating the page is usually the best choice,
1056 * unless the page is wanted by another thread.
1059 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1060 vm_page_activate(m);
1062 vm_page_deactivate(m);
1068 * vm_page_sleep_if_busy:
1070 * Sleep and release the page queues lock if the page is busied.
1071 * Returns TRUE if the thread slept.
1073 * The given page must be unlocked and object containing it must
1077 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1081 vm_page_lock_assert(m, MA_NOTOWNED);
1082 VM_OBJECT_ASSERT_WLOCKED(m->object);
1084 if (vm_page_busied(m)) {
1086 * The page-specific object must be cached because page
1087 * identity can change during the sleep, causing the
1088 * re-lock of a different object.
1089 * It is assumed that a reference to the object is already
1090 * held by the callers.
1094 VM_OBJECT_WUNLOCK(obj);
1095 vm_page_busy_sleep(m, msg, false);
1096 VM_OBJECT_WLOCK(obj);
1103 * vm_page_dirty_KBI: [ internal use only ]
1105 * Set all bits in the page's dirty field.
1107 * The object containing the specified page must be locked if the
1108 * call is made from the machine-independent layer.
1110 * See vm_page_clear_dirty_mask().
1112 * This function should only be called by vm_page_dirty().
1115 vm_page_dirty_KBI(vm_page_t m)
1118 /* These assertions refer to this operation by its public name. */
1119 KASSERT((m->flags & PG_CACHED) == 0,
1120 ("vm_page_dirty: page in cache!"));
1121 KASSERT(m->valid == VM_PAGE_BITS_ALL,
1122 ("vm_page_dirty: page is invalid!"));
1123 m->dirty = VM_PAGE_BITS_ALL;
1127 * vm_page_insert: [ internal use only ]
1129 * Inserts the given mem entry into the object and object list.
1131 * The object must be locked.
1134 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1138 VM_OBJECT_ASSERT_WLOCKED(object);
1139 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1140 return (vm_page_insert_after(m, object, pindex, mpred));
1144 * vm_page_insert_after:
1146 * Inserts the page "m" into the specified object at offset "pindex".
1148 * The page "mpred" must immediately precede the offset "pindex" within
1149 * the specified object.
1151 * The object must be locked.
1154 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1159 VM_OBJECT_ASSERT_WLOCKED(object);
1160 KASSERT(m->object == NULL,
1161 ("vm_page_insert_after: page already inserted"));
1162 if (mpred != NULL) {
1163 KASSERT(mpred->object == object,
1164 ("vm_page_insert_after: object doesn't contain mpred"));
1165 KASSERT(mpred->pindex < pindex,
1166 ("vm_page_insert_after: mpred doesn't precede pindex"));
1167 msucc = TAILQ_NEXT(mpred, listq);
1169 msucc = TAILQ_FIRST(&object->memq);
1171 KASSERT(msucc->pindex > pindex,
1172 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1175 * Record the object/offset pair in this page
1181 * Now link into the object's ordered list of backed pages.
1183 if (vm_radix_insert(&object->rtree, m)) {
1188 vm_page_insert_radixdone(m, object, mpred);
1193 * vm_page_insert_radixdone:
1195 * Complete page "m" insertion into the specified object after the
1196 * radix trie hooking.
1198 * The page "mpred" must precede the offset "m->pindex" within the
1201 * The object must be locked.
1204 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1207 VM_OBJECT_ASSERT_WLOCKED(object);
1208 KASSERT(object != NULL && m->object == object,
1209 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1210 if (mpred != NULL) {
1211 KASSERT(mpred->object == object,
1212 ("vm_page_insert_after: object doesn't contain mpred"));
1213 KASSERT(mpred->pindex < m->pindex,
1214 ("vm_page_insert_after: mpred doesn't precede pindex"));
1218 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1220 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1223 * Show that the object has one more resident page.
1225 object->resident_page_count++;
1228 * Hold the vnode until the last page is released.
1230 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1231 vhold(object->handle);
1234 * Since we are inserting a new and possibly dirty page,
1235 * update the object's OBJ_MIGHTBEDIRTY flag.
1237 if (pmap_page_is_write_mapped(m))
1238 vm_object_set_writeable_dirty(object);
1244 * Removes the given mem entry from the object/offset-page
1245 * table and the object page list, but do not invalidate/terminate
1246 * the backing store.
1248 * The object must be locked. The page must be locked if it is managed.
1251 vm_page_remove(vm_page_t m)
1255 if ((m->oflags & VPO_UNMANAGED) == 0)
1256 vm_page_assert_locked(m);
1257 if ((object = m->object) == NULL)
1259 VM_OBJECT_ASSERT_WLOCKED(object);
1260 if (vm_page_xbusied(m))
1261 vm_page_xunbusy_maybelocked(m);
1264 * Now remove from the object's list of backed pages.
1266 vm_radix_remove(&object->rtree, m->pindex);
1267 TAILQ_REMOVE(&object->memq, m, listq);
1270 * And show that the object has one fewer resident page.
1272 object->resident_page_count--;
1275 * The vnode may now be recycled.
1277 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1278 vdrop(object->handle);
1286 * Returns the page associated with the object/offset
1287 * pair specified; if none is found, NULL is returned.
1289 * The object must be locked.
1292 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1295 VM_OBJECT_ASSERT_LOCKED(object);
1296 return (vm_radix_lookup(&object->rtree, pindex));
1300 * vm_page_find_least:
1302 * Returns the page associated with the object with least pindex
1303 * greater than or equal to the parameter pindex, or NULL.
1305 * The object must be locked.
1308 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1312 VM_OBJECT_ASSERT_LOCKED(object);
1313 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1314 m = vm_radix_lookup_ge(&object->rtree, pindex);
1319 * Returns the given page's successor (by pindex) within the object if it is
1320 * resident; if none is found, NULL is returned.
1322 * The object must be locked.
1325 vm_page_next(vm_page_t m)
1329 VM_OBJECT_ASSERT_LOCKED(m->object);
1330 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1331 MPASS(next->object == m->object);
1332 if (next->pindex != m->pindex + 1)
1339 * Returns the given page's predecessor (by pindex) within the object if it is
1340 * resident; if none is found, NULL is returned.
1342 * The object must be locked.
1345 vm_page_prev(vm_page_t m)
1349 VM_OBJECT_ASSERT_LOCKED(m->object);
1350 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1351 MPASS(prev->object == m->object);
1352 if (prev->pindex != m->pindex - 1)
1359 * Uses the page mnew as a replacement for an existing page at index
1360 * pindex which must be already present in the object.
1362 * The existing page must not be on a paging queue.
1365 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1369 VM_OBJECT_ASSERT_WLOCKED(object);
1370 KASSERT(mnew->object == NULL,
1371 ("vm_page_replace: page already in object"));
1374 * This function mostly follows vm_page_insert() and
1375 * vm_page_remove() without the radix, object count and vnode
1376 * dance. Double check such functions for more comments.
1379 mnew->object = object;
1380 mnew->pindex = pindex;
1381 mold = vm_radix_replace(&object->rtree, mnew);
1382 KASSERT(mold->queue == PQ_NONE,
1383 ("vm_page_replace: mold is on a paging queue"));
1385 /* Keep the resident page list in sorted order. */
1386 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1387 TAILQ_REMOVE(&object->memq, mold, listq);
1389 mold->object = NULL;
1390 vm_page_xunbusy_maybelocked(mold);
1393 * The object's resident_page_count does not change because we have
1394 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1396 if (pmap_page_is_write_mapped(mnew))
1397 vm_object_set_writeable_dirty(object);
1404 * Move the given memory entry from its
1405 * current object to the specified target object/offset.
1407 * Note: swap associated with the page must be invalidated by the move. We
1408 * have to do this for several reasons: (1) we aren't freeing the
1409 * page, (2) we are dirtying the page, (3) the VM system is probably
1410 * moving the page from object A to B, and will then later move
1411 * the backing store from A to B and we can't have a conflict.
1413 * Note: we *always* dirty the page. It is necessary both for the
1414 * fact that we moved it, and because we may be invalidating
1415 * swap. If the page is on the cache, we have to deactivate it
1416 * or vm_page_dirty() will panic. Dirty pages are not allowed
1419 * The objects must be locked.
1422 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1427 VM_OBJECT_ASSERT_WLOCKED(new_object);
1429 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1430 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1431 ("vm_page_rename: pindex already renamed"));
1434 * Create a custom version of vm_page_insert() which does not depend
1435 * by m_prev and can cheat on the implementation aspects of the
1439 m->pindex = new_pindex;
1440 if (vm_radix_insert(&new_object->rtree, m)) {
1446 * The operation cannot fail anymore. The removal must happen before
1447 * the listq iterator is tainted.
1453 /* Return back to the new pindex to complete vm_page_insert(). */
1454 m->pindex = new_pindex;
1455 m->object = new_object;
1457 vm_page_insert_radixdone(m, new_object, mpred);
1463 * Convert all of the given object's cached pages that have a
1464 * pindex within the given range into free pages. If the value
1465 * zero is given for "end", then the range's upper bound is
1466 * infinity. If the given object is backed by a vnode and it
1467 * transitions from having one or more cached pages to none, the
1468 * vnode's hold count is reduced.
1471 vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1476 mtx_lock(&vm_page_queue_free_mtx);
1477 if (__predict_false(vm_radix_is_empty(&object->cache))) {
1478 mtx_unlock(&vm_page_queue_free_mtx);
1481 while ((m = vm_radix_lookup_ge(&object->cache, start)) != NULL) {
1482 if (end != 0 && m->pindex >= end)
1484 vm_radix_remove(&object->cache, m->pindex);
1485 vm_page_cache_turn_free(m);
1487 empty = vm_radix_is_empty(&object->cache);
1488 mtx_unlock(&vm_page_queue_free_mtx);
1489 if (object->type == OBJT_VNODE && empty)
1490 vdrop(object->handle);
1494 * Returns the cached page that is associated with the given
1495 * object and offset. If, however, none exists, returns NULL.
1497 * The free page queue must be locked.
1499 static inline vm_page_t
1500 vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
1503 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1504 return (vm_radix_lookup(&object->cache, pindex));
1508 * Remove the given cached page from its containing object's
1509 * collection of cached pages.
1511 * The free page queue must be locked.
1514 vm_page_cache_remove(vm_page_t m)
1517 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1518 KASSERT((m->flags & PG_CACHED) != 0,
1519 ("vm_page_cache_remove: page %p is not cached", m));
1520 vm_radix_remove(&m->object->cache, m->pindex);
1522 vm_cnt.v_cache_count--;
1526 * Transfer all of the cached pages with offset greater than or
1527 * equal to 'offidxstart' from the original object's cache to the
1528 * new object's cache. However, any cached pages with offset
1529 * greater than or equal to the new object's size are kept in the
1530 * original object. Initially, the new object's cache must be
1531 * empty. Offset 'offidxstart' in the original object must
1532 * correspond to offset zero in the new object.
1534 * The new object must be locked.
1537 vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1538 vm_object_t new_object)
1543 * Insertion into an object's collection of cached pages
1544 * requires the object to be locked. In contrast, removal does
1547 VM_OBJECT_ASSERT_WLOCKED(new_object);
1548 KASSERT(vm_radix_is_empty(&new_object->cache),
1549 ("vm_page_cache_transfer: object %p has cached pages",
1551 mtx_lock(&vm_page_queue_free_mtx);
1552 while ((m = vm_radix_lookup_ge(&orig_object->cache,
1553 offidxstart)) != NULL) {
1555 * Transfer all of the pages with offset greater than or
1556 * equal to 'offidxstart' from the original object's
1557 * cache to the new object's cache.
1559 if ((m->pindex - offidxstart) >= new_object->size)
1561 vm_radix_remove(&orig_object->cache, m->pindex);
1562 /* Update the page's object and offset. */
1563 m->object = new_object;
1564 m->pindex -= offidxstart;
1565 if (vm_radix_insert(&new_object->cache, m))
1566 vm_page_cache_turn_free(m);
1568 mtx_unlock(&vm_page_queue_free_mtx);
1572 * Returns TRUE if a cached page is associated with the given object and
1573 * offset, and FALSE otherwise.
1575 * The object must be locked.
1578 vm_page_is_cached(vm_object_t object, vm_pindex_t pindex)
1583 * Insertion into an object's collection of cached pages requires the
1584 * object to be locked. Therefore, if the object is locked and the
1585 * object's collection is empty, there is no need to acquire the free
1586 * page queues lock in order to prove that the specified page doesn't
1589 VM_OBJECT_ASSERT_WLOCKED(object);
1590 if (__predict_true(vm_object_cache_is_empty(object)))
1592 mtx_lock(&vm_page_queue_free_mtx);
1593 m = vm_page_cache_lookup(object, pindex);
1594 mtx_unlock(&vm_page_queue_free_mtx);
1601 * Allocate and return a page that is associated with the specified
1602 * object and offset pair. By default, this page is exclusive busied.
1604 * The caller must always specify an allocation class.
1606 * allocation classes:
1607 * VM_ALLOC_NORMAL normal process request
1608 * VM_ALLOC_SYSTEM system *really* needs a page
1609 * VM_ALLOC_INTERRUPT interrupt time request
1611 * optional allocation flags:
1612 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1613 * intends to allocate
1614 * VM_ALLOC_IFCACHED return page only if it is cached
1615 * VM_ALLOC_IFNOTCACHED return NULL, do not reactivate if the page
1617 * VM_ALLOC_NOBUSY do not exclusive busy the page
1618 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1619 * VM_ALLOC_NOOBJ page is not associated with an object and
1620 * should not be exclusive busy
1621 * VM_ALLOC_SBUSY shared busy the allocated page
1622 * VM_ALLOC_WIRED wire the allocated page
1623 * VM_ALLOC_ZERO prefer a zeroed page
1625 * This routine may not sleep.
1628 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1630 struct vnode *vp = NULL;
1631 vm_object_t m_object;
1633 int flags, req_class;
1635 mpred = 0; /* XXX: pacify gcc */
1636 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1637 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1638 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1639 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1640 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1643 VM_OBJECT_ASSERT_WLOCKED(object);
1645 req_class = req & VM_ALLOC_CLASS_MASK;
1648 * The page daemon is allowed to dig deeper into the free page list.
1650 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1651 req_class = VM_ALLOC_SYSTEM;
1653 if (object != NULL) {
1654 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1655 KASSERT(mpred == NULL || mpred->pindex != pindex,
1656 ("vm_page_alloc: pindex already allocated"));
1660 * The page allocation request can came from consumers which already
1661 * hold the free page queue mutex, like vm_page_insert() in
1664 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
1665 if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
1666 (req_class == VM_ALLOC_SYSTEM &&
1667 vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
1668 (req_class == VM_ALLOC_INTERRUPT &&
1669 vm_cnt.v_free_count + vm_cnt.v_cache_count > 0)) {
1671 * Allocate from the free queue if the number of free pages
1672 * exceeds the minimum for the request class.
1674 if (object != NULL &&
1675 (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1676 if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1677 mtx_unlock(&vm_page_queue_free_mtx);
1680 if (vm_phys_unfree_page(m))
1681 vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1682 #if VM_NRESERVLEVEL > 0
1683 else if (!vm_reserv_reactivate_page(m))
1687 panic("vm_page_alloc: cache page %p is missing"
1688 " from the free queue", m);
1689 } else if ((req & VM_ALLOC_IFCACHED) != 0) {
1690 mtx_unlock(&vm_page_queue_free_mtx);
1692 #if VM_NRESERVLEVEL > 0
1693 } else if (object == NULL || (object->flags & (OBJ_COLORED |
1694 OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1695 vm_reserv_alloc_page(object, pindex, mpred)) == NULL) {
1699 m = vm_phys_alloc_pages(object != NULL ?
1700 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1701 #if VM_NRESERVLEVEL > 0
1702 if (m == NULL && vm_reserv_reclaim_inactive()) {
1703 m = vm_phys_alloc_pages(object != NULL ?
1704 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1711 * Not allocatable, give up.
1713 mtx_unlock(&vm_page_queue_free_mtx);
1714 atomic_add_int(&vm_pageout_deficit,
1715 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1716 pagedaemon_wakeup();
1721 * At this point we had better have found a good page.
1723 KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1724 KASSERT(m->queue == PQ_NONE,
1725 ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1726 KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1727 KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1728 KASSERT(!vm_page_busied(m), ("vm_page_alloc: page %p is busy", m));
1729 KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1730 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1731 ("vm_page_alloc: page %p has unexpected memattr %d", m,
1732 pmap_page_get_memattr(m)));
1733 if ((m->flags & PG_CACHED) != 0) {
1734 KASSERT((m->flags & PG_ZERO) == 0,
1735 ("vm_page_alloc: cached page %p is PG_ZERO", m));
1736 KASSERT(m->valid != 0,
1737 ("vm_page_alloc: cached page %p is invalid", m));
1738 if (m->object == object && m->pindex == pindex)
1739 vm_cnt.v_reactivated++;
1742 m_object = m->object;
1743 vm_page_cache_remove(m);
1744 if (m_object->type == OBJT_VNODE &&
1745 vm_object_cache_is_empty(m_object))
1746 vp = m_object->handle;
1748 KASSERT(m->valid == 0,
1749 ("vm_page_alloc: free page %p is valid", m));
1750 vm_phys_freecnt_adj(m, -1);
1751 if ((m->flags & PG_ZERO) != 0)
1752 vm_page_zero_count--;
1754 mtx_unlock(&vm_page_queue_free_mtx);
1757 * Initialize the page. Only the PG_ZERO flag is inherited.
1760 if ((req & VM_ALLOC_ZERO) != 0)
1763 if ((req & VM_ALLOC_NODUMP) != 0)
1767 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1769 m->busy_lock = VPB_UNBUSIED;
1770 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1771 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1772 if ((req & VM_ALLOC_SBUSY) != 0)
1773 m->busy_lock = VPB_SHARERS_WORD(1);
1774 if (req & VM_ALLOC_WIRED) {
1776 * The page lock is not required for wiring a page until that
1777 * page is inserted into the object.
1779 atomic_add_int(&vm_cnt.v_wire_count, 1);
1784 if (object != NULL) {
1785 if (vm_page_insert_after(m, object, pindex, mpred)) {
1786 /* See the comment below about hold count. */
1789 pagedaemon_wakeup();
1790 if (req & VM_ALLOC_WIRED) {
1791 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1795 m->oflags = VPO_UNMANAGED;
1796 m->busy_lock = VPB_UNBUSIED;
1801 /* Ignore device objects; the pager sets "memattr" for them. */
1802 if (object->memattr != VM_MEMATTR_DEFAULT &&
1803 (object->flags & OBJ_FICTITIOUS) == 0)
1804 pmap_page_set_memattr(m, object->memattr);
1809 * The following call to vdrop() must come after the above call
1810 * to vm_page_insert() in case both affect the same object and
1811 * vnode. Otherwise, the affected vnode's hold count could
1812 * temporarily become zero.
1818 * Don't wakeup too often - wakeup the pageout daemon when
1819 * we would be nearly out of memory.
1821 if (vm_paging_needed())
1822 pagedaemon_wakeup();
1828 vm_page_alloc_contig_vdrop(struct spglist *lst)
1831 while (!SLIST_EMPTY(lst)) {
1832 vdrop((struct vnode *)SLIST_FIRST(lst)-> plinks.s.pv);
1833 SLIST_REMOVE_HEAD(lst, plinks.s.ss);
1838 * vm_page_alloc_contig:
1840 * Allocate a contiguous set of physical pages of the given size "npages"
1841 * from the free lists. All of the physical pages must be at or above
1842 * the given physical address "low" and below the given physical address
1843 * "high". The given value "alignment" determines the alignment of the
1844 * first physical page in the set. If the given value "boundary" is
1845 * non-zero, then the set of physical pages cannot cross any physical
1846 * address boundary that is a multiple of that value. Both "alignment"
1847 * and "boundary" must be a power of two.
1849 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1850 * then the memory attribute setting for the physical pages is configured
1851 * to the object's memory attribute setting. Otherwise, the memory
1852 * attribute setting for the physical pages is configured to "memattr",
1853 * overriding the object's memory attribute setting. However, if the
1854 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1855 * memory attribute setting for the physical pages cannot be configured
1856 * to VM_MEMATTR_DEFAULT.
1858 * The caller must always specify an allocation class.
1860 * allocation classes:
1861 * VM_ALLOC_NORMAL normal process request
1862 * VM_ALLOC_SYSTEM system *really* needs a page
1863 * VM_ALLOC_INTERRUPT interrupt time request
1865 * optional allocation flags:
1866 * VM_ALLOC_NOBUSY do not exclusive busy the page
1867 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1868 * VM_ALLOC_NOOBJ page is not associated with an object and
1869 * should not be exclusive busy
1870 * VM_ALLOC_SBUSY shared busy the allocated page
1871 * VM_ALLOC_WIRED wire the allocated page
1872 * VM_ALLOC_ZERO prefer a zeroed page
1874 * This routine may not sleep.
1877 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1878 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1879 vm_paddr_t boundary, vm_memattr_t memattr)
1882 struct spglist deferred_vdrop_list;
1883 vm_page_t m, m_tmp, m_ret;
1887 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1888 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1889 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1890 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1891 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1893 if (object != NULL) {
1894 VM_OBJECT_ASSERT_WLOCKED(object);
1895 KASSERT(object->type == OBJT_PHYS,
1896 ("vm_page_alloc_contig: object %p isn't OBJT_PHYS",
1899 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1900 req_class = req & VM_ALLOC_CLASS_MASK;
1903 * The page daemon is allowed to dig deeper into the free page list.
1905 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1906 req_class = VM_ALLOC_SYSTEM;
1908 SLIST_INIT(&deferred_vdrop_list);
1909 mtx_lock(&vm_page_queue_free_mtx);
1910 if (vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1911 vm_cnt.v_free_reserved || (req_class == VM_ALLOC_SYSTEM &&
1912 vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1913 vm_cnt.v_interrupt_free_min) || (req_class == VM_ALLOC_INTERRUPT &&
1914 vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages)) {
1915 #if VM_NRESERVLEVEL > 0
1917 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1918 (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1919 low, high, alignment, boundary)) == NULL)
1921 m_ret = vm_phys_alloc_contig(npages, low, high,
1922 alignment, boundary);
1924 mtx_unlock(&vm_page_queue_free_mtx);
1925 atomic_add_int(&vm_pageout_deficit, npages);
1926 pagedaemon_wakeup();
1930 for (m = m_ret; m < &m_ret[npages]; m++) {
1931 drop = vm_page_alloc_init(m);
1934 * Enqueue the vnode for deferred vdrop().
1936 m->plinks.s.pv = drop;
1937 SLIST_INSERT_HEAD(&deferred_vdrop_list, m,
1942 #if VM_NRESERVLEVEL > 0
1943 if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1948 mtx_unlock(&vm_page_queue_free_mtx);
1953 * Initialize the pages. Only the PG_ZERO flag is inherited.
1956 if ((req & VM_ALLOC_ZERO) != 0)
1958 if ((req & VM_ALLOC_NODUMP) != 0)
1960 if ((req & VM_ALLOC_WIRED) != 0)
1961 atomic_add_int(&vm_cnt.v_wire_count, npages);
1962 if (object != NULL) {
1963 if (object->memattr != VM_MEMATTR_DEFAULT &&
1964 memattr == VM_MEMATTR_DEFAULT)
1965 memattr = object->memattr;
1967 for (m = m_ret; m < &m_ret[npages]; m++) {
1969 m->flags = (m->flags | PG_NODUMP) & flags;
1970 m->busy_lock = VPB_UNBUSIED;
1971 if (object != NULL) {
1972 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
1973 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1974 if ((req & VM_ALLOC_SBUSY) != 0)
1975 m->busy_lock = VPB_SHARERS_WORD(1);
1977 if ((req & VM_ALLOC_WIRED) != 0)
1979 /* Unmanaged pages don't use "act_count". */
1980 m->oflags = VPO_UNMANAGED;
1981 if (object != NULL) {
1982 if (vm_page_insert(m, object, pindex)) {
1983 vm_page_alloc_contig_vdrop(
1984 &deferred_vdrop_list);
1985 if (vm_paging_needed())
1986 pagedaemon_wakeup();
1987 if ((req & VM_ALLOC_WIRED) != 0)
1988 atomic_subtract_int(&vm_cnt.v_wire_count,
1990 for (m_tmp = m, m = m_ret;
1991 m < &m_ret[npages]; m++) {
1992 if ((req & VM_ALLOC_WIRED) != 0)
1996 m->oflags |= VPO_UNMANAGED;
1998 m->busy_lock = VPB_UNBUSIED;
2005 if (memattr != VM_MEMATTR_DEFAULT)
2006 pmap_page_set_memattr(m, memattr);
2009 vm_page_alloc_contig_vdrop(&deferred_vdrop_list);
2010 if (vm_paging_needed())
2011 pagedaemon_wakeup();
2016 * Initialize a page that has been freshly dequeued from a freelist.
2017 * The caller has to drop the vnode returned, if it is not NULL.
2019 * This function may only be used to initialize unmanaged pages.
2021 * To be called with vm_page_queue_free_mtx held.
2023 static struct vnode *
2024 vm_page_alloc_init(vm_page_t m)
2027 vm_object_t m_object;
2029 KASSERT(m->queue == PQ_NONE,
2030 ("vm_page_alloc_init: page %p has unexpected queue %d",
2032 KASSERT(m->wire_count == 0,
2033 ("vm_page_alloc_init: page %p is wired", m));
2034 KASSERT(m->hold_count == 0,
2035 ("vm_page_alloc_init: page %p is held", m));
2036 KASSERT(!vm_page_busied(m),
2037 ("vm_page_alloc_init: page %p is busy", m));
2038 KASSERT(m->dirty == 0,
2039 ("vm_page_alloc_init: page %p is dirty", m));
2040 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2041 ("vm_page_alloc_init: page %p has unexpected memattr %d",
2042 m, pmap_page_get_memattr(m)));
2043 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2045 if ((m->flags & PG_CACHED) != 0) {
2046 KASSERT((m->flags & PG_ZERO) == 0,
2047 ("vm_page_alloc_init: cached page %p is PG_ZERO", m));
2049 m_object = m->object;
2050 vm_page_cache_remove(m);
2051 if (m_object->type == OBJT_VNODE &&
2052 vm_object_cache_is_empty(m_object))
2053 drop = m_object->handle;
2055 KASSERT(m->valid == 0,
2056 ("vm_page_alloc_init: free page %p is valid", m));
2057 vm_phys_freecnt_adj(m, -1);
2058 if ((m->flags & PG_ZERO) != 0)
2059 vm_page_zero_count--;
2065 * vm_page_alloc_freelist:
2067 * Allocate a physical page from the specified free page list.
2069 * The caller must always specify an allocation class.
2071 * allocation classes:
2072 * VM_ALLOC_NORMAL normal process request
2073 * VM_ALLOC_SYSTEM system *really* needs a page
2074 * VM_ALLOC_INTERRUPT interrupt time request
2076 * optional allocation flags:
2077 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2078 * intends to allocate
2079 * VM_ALLOC_WIRED wire the allocated page
2080 * VM_ALLOC_ZERO prefer a zeroed page
2082 * This routine may not sleep.
2085 vm_page_alloc_freelist(int flind, int req)
2092 req_class = req & VM_ALLOC_CLASS_MASK;
2095 * The page daemon is allowed to dig deeper into the free page list.
2097 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2098 req_class = VM_ALLOC_SYSTEM;
2101 * Do not allocate reserved pages unless the req has asked for it.
2103 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
2104 if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
2105 (req_class == VM_ALLOC_SYSTEM &&
2106 vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
2107 (req_class == VM_ALLOC_INTERRUPT &&
2108 vm_cnt.v_free_count + vm_cnt.v_cache_count > 0))
2109 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
2111 mtx_unlock(&vm_page_queue_free_mtx);
2112 atomic_add_int(&vm_pageout_deficit,
2113 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
2114 pagedaemon_wakeup();
2118 mtx_unlock(&vm_page_queue_free_mtx);
2121 drop = vm_page_alloc_init(m);
2122 mtx_unlock(&vm_page_queue_free_mtx);
2125 * Initialize the page. Only the PG_ZERO flag is inherited.
2129 if ((req & VM_ALLOC_ZERO) != 0)
2132 if ((req & VM_ALLOC_WIRED) != 0) {
2134 * The page lock is not required for wiring a page that does
2135 * not belong to an object.
2137 atomic_add_int(&vm_cnt.v_wire_count, 1);
2140 /* Unmanaged pages don't use "act_count". */
2141 m->oflags = VPO_UNMANAGED;
2144 if (vm_paging_needed())
2145 pagedaemon_wakeup();
2149 #define VPSC_ANY 0 /* No restrictions. */
2150 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2151 #define VPSC_NOSUPER 2 /* Skip superpages. */
2154 * vm_page_scan_contig:
2156 * Scan vm_page_array[] between the specified entries "m_start" and
2157 * "m_end" for a run of contiguous physical pages that satisfy the
2158 * specified conditions, and return the lowest page in the run. The
2159 * specified "alignment" determines the alignment of the lowest physical
2160 * page in the run. If the specified "boundary" is non-zero, then the
2161 * run of physical pages cannot span a physical address that is a
2162 * multiple of "boundary".
2164 * "m_end" is never dereferenced, so it need not point to a vm_page
2165 * structure within vm_page_array[].
2167 * "npages" must be greater than zero. "m_start" and "m_end" must not
2168 * span a hole (or discontiguity) in the physical address space. Both
2169 * "alignment" and "boundary" must be a power of two.
2172 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2173 u_long alignment, vm_paddr_t boundary, int options)
2175 struct mtx *m_mtx, *new_mtx;
2179 #if VM_NRESERVLEVEL > 0
2182 int m_inc, order, run_ext, run_len;
2184 KASSERT(npages > 0, ("npages is 0"));
2185 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2186 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2190 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2191 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2192 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2195 * If the current page would be the start of a run, check its
2196 * physical address against the end, alignment, and boundary
2197 * conditions. If it doesn't satisfy these conditions, either
2198 * terminate the scan or advance to the next page that
2199 * satisfies the failed condition.
2202 KASSERT(m_run == NULL, ("m_run != NULL"));
2203 if (m + npages > m_end)
2205 pa = VM_PAGE_TO_PHYS(m);
2206 if ((pa & (alignment - 1)) != 0) {
2207 m_inc = atop(roundup2(pa, alignment) - pa);
2210 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2212 m_inc = atop(roundup2(pa, boundary) - pa);
2216 KASSERT(m_run != NULL, ("m_run == NULL"));
2219 * Avoid releasing and reacquiring the same page lock.
2221 new_mtx = vm_page_lockptr(m);
2222 if (m_mtx != new_mtx) {
2230 if (m->wire_count != 0 || m->hold_count != 0)
2232 #if VM_NRESERVLEVEL > 0
2233 else if ((level = vm_reserv_level(m)) >= 0 &&
2234 (options & VPSC_NORESERV) != 0) {
2236 /* Advance to the end of the reservation. */
2237 pa = VM_PAGE_TO_PHYS(m);
2238 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2242 else if ((object = m->object) != NULL) {
2244 * The page is considered eligible for relocation if
2245 * and only if it could be laundered or reclaimed by
2248 if (!VM_OBJECT_TRYRLOCK(object)) {
2250 VM_OBJECT_RLOCK(object);
2252 if (m->object != object) {
2254 * The page may have been freed.
2256 VM_OBJECT_RUNLOCK(object);
2258 } else if (m->wire_count != 0 ||
2259 m->hold_count != 0) {
2264 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2265 ("page %p is PG_UNHOLDFREE", m));
2266 /* Don't care: PG_NODUMP, PG_WINATCFLS, PG_ZERO. */
2267 if (object->type != OBJT_DEFAULT &&
2268 object->type != OBJT_SWAP &&
2269 object->type != OBJT_VNODE)
2271 else if ((m->flags & PG_CACHED) != 0 ||
2272 m != vm_page_lookup(object, m->pindex)) {
2274 * The page is cached or recently converted
2275 * from cached to free.
2277 #if VM_NRESERVLEVEL > 0
2280 * The page is reserved. Extend the
2281 * current run by one page.
2286 if ((order = m->order) < VM_NFREEORDER) {
2288 * The page is enqueued in the
2289 * physical memory allocator's cache/
2290 * free page queues. Moreover, it is
2291 * the first page in a power-of-two-
2292 * sized run of contiguous cache/free
2293 * pages. Add these pages to the end
2294 * of the current run, and jump
2297 run_ext = 1 << order;
2301 #if VM_NRESERVLEVEL > 0
2302 } else if ((options & VPSC_NOSUPER) != 0 &&
2303 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2305 /* Advance to the end of the superpage. */
2306 pa = VM_PAGE_TO_PHYS(m);
2307 m_inc = atop(roundup2(pa + 1,
2308 vm_reserv_size(level)) - pa);
2310 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2311 m->queue != PQ_NONE && !vm_page_busied(m)) {
2313 * The page is allocated but eligible for
2314 * relocation. Extend the current run by one
2317 KASSERT(pmap_page_get_memattr(m) ==
2319 ("page %p has an unexpected memattr", m));
2320 KASSERT((m->oflags & (VPO_SWAPINPROG |
2321 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2322 ("page %p has unexpected oflags", m));
2323 /* Don't care: VPO_NOSYNC. */
2328 VM_OBJECT_RUNLOCK(object);
2329 #if VM_NRESERVLEVEL > 0
2330 } else if (level >= 0) {
2332 * The page is reserved but not yet allocated. In
2333 * other words, it is still cached or free. Extend
2334 * the current run by one page.
2338 } else if ((order = m->order) < VM_NFREEORDER) {
2340 * The page is enqueued in the physical memory
2341 * allocator's cache/free page queues. Moreover, it
2342 * is the first page in a power-of-two-sized run of
2343 * contiguous cache/free pages. Add these pages to
2344 * the end of the current run, and jump ahead.
2346 run_ext = 1 << order;
2350 * Skip the page for one of the following reasons: (1)
2351 * It is enqueued in the physical memory allocator's
2352 * cache/free page queues. However, it is not the
2353 * first page in a run of contiguous cache/free pages.
2354 * (This case rarely occurs because the scan is
2355 * performed in ascending order.) (2) It is not
2356 * reserved, and it is transitioning from free to
2357 * allocated. (Conversely, the transition from
2358 * allocated to free for managed pages is blocked by
2359 * the page lock.) (3) It is allocated but not
2360 * contained by an object and not wired, e.g.,
2361 * allocated by Xen's balloon driver.
2367 * Extend or reset the current run of pages.
2382 if (run_len >= npages)
2388 * vm_page_reclaim_run:
2390 * Try to relocate each of the allocated virtual pages within the
2391 * specified run of physical pages to a new physical address. Free the
2392 * physical pages underlying the relocated virtual pages. A virtual page
2393 * is relocatable if and only if it could be laundered or reclaimed by
2394 * the page daemon. Whenever possible, a virtual page is relocated to a
2395 * physical address above "high".
2397 * Returns 0 if every physical page within the run was already free or
2398 * just freed by a successful relocation. Otherwise, returns a non-zero
2399 * value indicating why the last attempt to relocate a virtual page was
2402 * "req_class" must be an allocation class.
2405 vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
2408 struct mtx *m_mtx, *new_mtx;
2409 struct spglist free;
2412 vm_page_t m, m_end, m_new;
2413 int error, order, req;
2415 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2416 ("req_class is not an allocation class"));
2420 m_end = m_run + npages;
2422 for (; error == 0 && m < m_end; m++) {
2423 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2424 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2427 * Avoid releasing and reacquiring the same page lock.
2429 new_mtx = vm_page_lockptr(m);
2430 if (m_mtx != new_mtx) {
2437 if (m->wire_count != 0 || m->hold_count != 0)
2439 else if ((object = m->object) != NULL) {
2441 * The page is relocated if and only if it could be
2442 * laundered or reclaimed by the page daemon.
2444 if (!VM_OBJECT_TRYWLOCK(object)) {
2446 VM_OBJECT_WLOCK(object);
2448 if (m->object != object) {
2450 * The page may have been freed.
2452 VM_OBJECT_WUNLOCK(object);
2454 } else if (m->wire_count != 0 ||
2455 m->hold_count != 0) {
2460 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2461 ("page %p is PG_UNHOLDFREE", m));
2462 /* Don't care: PG_NODUMP, PG_WINATCFLS, PG_ZERO. */
2463 if (object->type != OBJT_DEFAULT &&
2464 object->type != OBJT_SWAP &&
2465 object->type != OBJT_VNODE)
2467 else if ((m->flags & PG_CACHED) != 0 ||
2468 m != vm_page_lookup(object, m->pindex)) {
2470 * The page is cached or recently converted
2471 * from cached to free.
2473 VM_OBJECT_WUNLOCK(object);
2475 } else if (object->memattr != VM_MEMATTR_DEFAULT)
2477 else if (m->queue != PQ_NONE && !vm_page_busied(m)) {
2478 KASSERT(pmap_page_get_memattr(m) ==
2480 ("page %p has an unexpected memattr", m));
2481 KASSERT((m->oflags & (VPO_SWAPINPROG |
2482 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2483 ("page %p has unexpected oflags", m));
2484 /* Don't care: VPO_NOSYNC. */
2485 if (m->valid != 0) {
2487 * First, try to allocate a new page
2488 * that is above "high". Failing
2489 * that, try to allocate a new page
2490 * that is below "m_run". Allocate
2491 * the new page between the end of
2492 * "m_run" and "high" only as a last
2495 req = req_class | VM_ALLOC_NOOBJ;
2496 if ((m->flags & PG_NODUMP) != 0)
2497 req |= VM_ALLOC_NODUMP;
2498 if (trunc_page(high) !=
2499 ~(vm_paddr_t)PAGE_MASK) {
2500 m_new = vm_page_alloc_contig(
2505 VM_MEMATTR_DEFAULT);
2508 if (m_new == NULL) {
2509 pa = VM_PAGE_TO_PHYS(m_run);
2510 m_new = vm_page_alloc_contig(
2512 0, pa - 1, PAGE_SIZE, 0,
2513 VM_MEMATTR_DEFAULT);
2515 if (m_new == NULL) {
2517 m_new = vm_page_alloc_contig(
2519 pa, high, PAGE_SIZE, 0,
2520 VM_MEMATTR_DEFAULT);
2522 if (m_new == NULL) {
2526 KASSERT(m_new->wire_count == 0,
2527 ("page %p is wired", m));
2530 * Replace "m" with the new page. For
2531 * vm_page_replace(), "m" must be busy
2532 * and dequeued. Finally, change "m"
2533 * as if vm_page_free() was called.
2535 if (object->ref_count != 0)
2537 m_new->aflags = m->aflags;
2538 KASSERT(m_new->oflags == VPO_UNMANAGED,
2539 ("page %p is managed", m));
2540 m_new->oflags = m->oflags & VPO_NOSYNC;
2541 pmap_copy_page(m, m_new);
2542 m_new->valid = m->valid;
2543 m_new->dirty = m->dirty;
2544 m->flags &= ~PG_ZERO;
2547 vm_page_replace_checked(m_new, object,
2553 * The new page must be deactivated
2554 * before the object is unlocked.
2556 new_mtx = vm_page_lockptr(m_new);
2557 if (m_mtx != new_mtx) {
2562 vm_page_deactivate(m_new);
2564 m->flags &= ~PG_ZERO;
2567 KASSERT(m->dirty == 0,
2568 ("page %p is dirty", m));
2570 SLIST_INSERT_HEAD(&free, m, plinks.s.ss);
2574 VM_OBJECT_WUNLOCK(object);
2577 mtx_lock(&vm_page_queue_free_mtx);
2579 if (order < VM_NFREEORDER) {
2581 * The page is enqueued in the physical memory
2582 * allocator's cache/free page queues.
2583 * Moreover, it is the first page in a power-
2584 * of-two-sized run of contiguous cache/free
2585 * pages. Jump ahead to the last page within
2586 * that run, and continue from there.
2588 m += (1 << order) - 1;
2590 #if VM_NRESERVLEVEL > 0
2591 else if (vm_reserv_is_page_free(m))
2594 mtx_unlock(&vm_page_queue_free_mtx);
2595 if (order == VM_NFREEORDER)
2601 if ((m = SLIST_FIRST(&free)) != NULL) {
2602 mtx_lock(&vm_page_queue_free_mtx);
2604 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2605 vm_phys_freecnt_adj(m, 1);
2606 #if VM_NRESERVLEVEL > 0
2607 if (!vm_reserv_free_page(m))
2611 vm_phys_free_pages(m, 0);
2612 } while ((m = SLIST_FIRST(&free)) != NULL);
2613 vm_page_zero_idle_wakeup();
2614 vm_page_free_wakeup();
2615 mtx_unlock(&vm_page_queue_free_mtx);
2622 CTASSERT(powerof2(NRUNS));
2624 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2626 #define MIN_RECLAIM 8
2629 * vm_page_reclaim_contig:
2631 * Reclaim allocated, contiguous physical memory satisfying the specified
2632 * conditions by relocating the virtual pages using that physical memory.
2633 * Returns true if reclamation is successful and false otherwise. Since
2634 * relocation requires the allocation of physical pages, reclamation may
2635 * fail due to a shortage of cache/free pages. When reclamation fails,
2636 * callers are expected to perform VM_WAIT before retrying a failed
2637 * allocation operation, e.g., vm_page_alloc_contig().
2639 * The caller must always specify an allocation class through "req".
2641 * allocation classes:
2642 * VM_ALLOC_NORMAL normal process request
2643 * VM_ALLOC_SYSTEM system *really* needs a page
2644 * VM_ALLOC_INTERRUPT interrupt time request
2646 * The optional allocation flags are ignored.
2648 * "npages" must be greater than zero. Both "alignment" and "boundary"
2649 * must be a power of two.
2652 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2653 u_long alignment, vm_paddr_t boundary)
2655 vm_paddr_t curr_low;
2656 vm_page_t m_run, m_runs[NRUNS];
2657 u_long count, reclaimed;
2658 int error, i, options, req_class;
2660 KASSERT(npages > 0, ("npages is 0"));
2661 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2662 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2663 req_class = req & VM_ALLOC_CLASS_MASK;
2666 * The page daemon is allowed to dig deeper into the free page list.
2668 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2669 req_class = VM_ALLOC_SYSTEM;
2672 * Return if the number of cached and free pages cannot satisfy the
2673 * requested allocation.
2675 count = vm_cnt.v_free_count + vm_cnt.v_cache_count;
2676 if (count < npages + vm_cnt.v_free_reserved || (count < npages +
2677 vm_cnt.v_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2678 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2682 * Scan up to three times, relaxing the restrictions ("options") on
2683 * the reclamation of reservations and superpages each time.
2685 for (options = VPSC_NORESERV;;) {
2687 * Find the highest runs that satisfy the given constraints
2688 * and restrictions, and record them in "m_runs".
2693 m_run = vm_phys_scan_contig(npages, curr_low, high,
2694 alignment, boundary, options);
2697 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2698 m_runs[RUN_INDEX(count)] = m_run;
2703 * Reclaim the highest runs in LIFO (descending) order until
2704 * the number of reclaimed pages, "reclaimed", is at least
2705 * MIN_RECLAIM. Reset "reclaimed" each time because each
2706 * reclamation is idempotent, and runs will (likely) recur
2707 * from one scan to the next as restrictions are relaxed.
2710 for (i = 0; count > 0 && i < NRUNS; i++) {
2712 m_run = m_runs[RUN_INDEX(count)];
2713 error = vm_page_reclaim_run(req_class, npages, m_run,
2716 reclaimed += npages;
2717 if (reclaimed >= MIN_RECLAIM)
2723 * Either relax the restrictions on the next scan or return if
2724 * the last scan had no restrictions.
2726 if (options == VPSC_NORESERV)
2727 options = VPSC_NOSUPER;
2728 else if (options == VPSC_NOSUPER)
2730 else if (options == VPSC_ANY)
2731 return (reclaimed != 0);
2736 * vm_wait: (also see VM_WAIT macro)
2738 * Sleep until free pages are available for allocation.
2739 * - Called in various places before memory allocations.
2745 mtx_lock(&vm_page_queue_free_mtx);
2746 if (curproc == pageproc) {
2747 vm_pageout_pages_needed = 1;
2748 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
2749 PDROP | PSWP, "VMWait", 0);
2751 if (__predict_false(pageproc == NULL))
2752 panic("vm_wait in early boot");
2753 if (!vm_pageout_wanted) {
2754 vm_pageout_wanted = true;
2755 wakeup(&vm_pageout_wanted);
2757 vm_pages_needed = true;
2758 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
2764 * vm_waitpfault: (also see VM_WAITPFAULT macro)
2766 * Sleep until free pages are available for allocation.
2767 * - Called only in vm_fault so that processes page faulting
2768 * can be easily tracked.
2769 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2770 * processes will be able to grab memory first. Do not change
2771 * this balance without careful testing first.
2777 mtx_lock(&vm_page_queue_free_mtx);
2778 if (!vm_pageout_wanted) {
2779 vm_pageout_wanted = true;
2780 wakeup(&vm_pageout_wanted);
2782 vm_pages_needed = true;
2783 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
2787 struct vm_pagequeue *
2788 vm_page_pagequeue(vm_page_t m)
2791 return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2797 * Remove the given page from its current page queue.
2799 * The page must be locked.
2802 vm_page_dequeue(vm_page_t m)
2804 struct vm_pagequeue *pq;
2806 vm_page_assert_locked(m);
2807 KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
2809 pq = vm_page_pagequeue(m);
2810 vm_pagequeue_lock(pq);
2812 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2813 vm_pagequeue_cnt_dec(pq);
2814 vm_pagequeue_unlock(pq);
2818 * vm_page_dequeue_locked:
2820 * Remove the given page from its current page queue.
2822 * The page and page queue must be locked.
2825 vm_page_dequeue_locked(vm_page_t m)
2827 struct vm_pagequeue *pq;
2829 vm_page_lock_assert(m, MA_OWNED);
2830 pq = vm_page_pagequeue(m);
2831 vm_pagequeue_assert_locked(pq);
2833 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2834 vm_pagequeue_cnt_dec(pq);
2840 * Add the given page to the specified page queue.
2842 * The page must be locked.
2845 vm_page_enqueue(uint8_t queue, vm_page_t m)
2847 struct vm_pagequeue *pq;
2849 vm_page_lock_assert(m, MA_OWNED);
2850 KASSERT(queue < PQ_COUNT,
2851 ("vm_page_enqueue: invalid queue %u request for page %p",
2853 pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2854 vm_pagequeue_lock(pq);
2856 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2857 vm_pagequeue_cnt_inc(pq);
2858 vm_pagequeue_unlock(pq);
2864 * Move the given page to the tail of its current page queue.
2866 * The page must be locked.
2869 vm_page_requeue(vm_page_t m)
2871 struct vm_pagequeue *pq;
2873 vm_page_lock_assert(m, MA_OWNED);
2874 KASSERT(m->queue != PQ_NONE,
2875 ("vm_page_requeue: page %p is not queued", m));
2876 pq = vm_page_pagequeue(m);
2877 vm_pagequeue_lock(pq);
2878 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2879 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2880 vm_pagequeue_unlock(pq);
2884 * vm_page_requeue_locked:
2886 * Move the given page to the tail of its current page queue.
2888 * The page queue must be locked.
2891 vm_page_requeue_locked(vm_page_t m)
2893 struct vm_pagequeue *pq;
2895 KASSERT(m->queue != PQ_NONE,
2896 ("vm_page_requeue_locked: page %p is not queued", m));
2897 pq = vm_page_pagequeue(m);
2898 vm_pagequeue_assert_locked(pq);
2899 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2900 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2906 * Put the specified page on the active list (if appropriate).
2907 * Ensure that act_count is at least ACT_INIT but do not otherwise
2910 * The page must be locked.
2913 vm_page_activate(vm_page_t m)
2917 vm_page_lock_assert(m, MA_OWNED);
2918 if ((queue = m->queue) != PQ_ACTIVE) {
2919 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2920 if (m->act_count < ACT_INIT)
2921 m->act_count = ACT_INIT;
2922 if (queue != PQ_NONE)
2924 vm_page_enqueue(PQ_ACTIVE, m);
2926 KASSERT(queue == PQ_NONE,
2927 ("vm_page_activate: wired page %p is queued", m));
2929 if (m->act_count < ACT_INIT)
2930 m->act_count = ACT_INIT;
2935 * vm_page_free_wakeup:
2937 * Helper routine for vm_page_free_toq() and vm_page_cache(). This
2938 * routine is called when a page has been added to the cache or free
2941 * The page queues must be locked.
2944 vm_page_free_wakeup(void)
2947 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2949 * if pageout daemon needs pages, then tell it that there are
2952 if (vm_pageout_pages_needed &&
2953 vm_cnt.v_cache_count + vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
2954 wakeup(&vm_pageout_pages_needed);
2955 vm_pageout_pages_needed = 0;
2958 * wakeup processes that are waiting on memory if we hit a
2959 * high water mark. And wakeup scheduler process if we have
2960 * lots of memory. this process will swapin processes.
2962 if (vm_pages_needed && !vm_page_count_min()) {
2963 vm_pages_needed = false;
2964 wakeup(&vm_cnt.v_free_count);
2969 * Turn a cached page into a free page, by changing its attributes.
2970 * Keep the statistics up-to-date.
2972 * The free page queue must be locked.
2975 vm_page_cache_turn_free(vm_page_t m)
2978 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2982 KASSERT((m->flags & PG_CACHED) != 0,
2983 ("vm_page_cache_turn_free: page %p is not cached", m));
2984 m->flags &= ~PG_CACHED;
2985 vm_cnt.v_cache_count--;
2986 vm_phys_freecnt_adj(m, 1);
2992 * Returns the given page to the free list,
2993 * disassociating it with any VM object.
2995 * The object must be locked. The page must be locked if it is managed.
2998 vm_page_free_toq(vm_page_t m)
3001 if ((m->oflags & VPO_UNMANAGED) == 0) {
3002 vm_page_lock_assert(m, MA_OWNED);
3003 KASSERT(!pmap_page_is_mapped(m),
3004 ("vm_page_free_toq: freeing mapped page %p", m));
3006 KASSERT(m->queue == PQ_NONE,
3007 ("vm_page_free_toq: unmanaged page %p is queued", m));
3008 PCPU_INC(cnt.v_tfree);
3010 if (vm_page_sbusied(m))
3011 panic("vm_page_free: freeing busy page %p", m);
3014 * Unqueue, then remove page. Note that we cannot destroy
3015 * the page here because we do not want to call the pager's
3016 * callback routine until after we've put the page on the
3017 * appropriate free queue.
3023 * If fictitious remove object association and
3024 * return, otherwise delay object association removal.
3026 if ((m->flags & PG_FICTITIOUS) != 0) {
3033 if (m->wire_count != 0)
3034 panic("vm_page_free: freeing wired page %p", m);
3035 if (m->hold_count != 0) {
3036 m->flags &= ~PG_ZERO;
3037 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
3038 ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
3039 m->flags |= PG_UNHOLDFREE;
3042 * Restore the default memory attribute to the page.
3044 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3045 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3048 * Insert the page into the physical memory allocator's
3049 * cache/free page queues.
3051 mtx_lock(&vm_page_queue_free_mtx);
3052 vm_phys_freecnt_adj(m, 1);
3053 #if VM_NRESERVLEVEL > 0
3054 if (!vm_reserv_free_page(m))
3058 vm_phys_free_pages(m, 0);
3059 if ((m->flags & PG_ZERO) != 0)
3060 ++vm_page_zero_count;
3062 vm_page_zero_idle_wakeup();
3063 vm_page_free_wakeup();
3064 mtx_unlock(&vm_page_queue_free_mtx);
3071 * Mark this page as wired down by yet
3072 * another map, removing it from paging queues
3075 * If the page is fictitious, then its wire count must remain one.
3077 * The page must be locked.
3080 vm_page_wire(vm_page_t m)
3084 * Only bump the wire statistics if the page is not already wired,
3085 * and only unqueue the page if it is on some queue (if it is unmanaged
3086 * it is already off the queues).
3088 vm_page_lock_assert(m, MA_OWNED);
3089 if ((m->flags & PG_FICTITIOUS) != 0) {
3090 KASSERT(m->wire_count == 1,
3091 ("vm_page_wire: fictitious page %p's wire count isn't one",
3095 if (m->wire_count == 0) {
3096 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
3097 m->queue == PQ_NONE,
3098 ("vm_page_wire: unmanaged page %p is queued", m));
3100 atomic_add_int(&vm_cnt.v_wire_count, 1);
3103 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
3109 * Release one wiring of the specified page, potentially allowing it to be
3110 * paged out. Returns TRUE if the number of wirings transitions to zero and
3113 * Only managed pages belonging to an object can be paged out. If the number
3114 * of wirings transitions to zero and the page is eligible for page out, then
3115 * the page is added to the specified paging queue (unless PQ_NONE is
3118 * If a page is fictitious, then its wire count must always be one.
3120 * A managed page must be locked.
3123 vm_page_unwire(vm_page_t m, uint8_t queue)
3126 KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
3127 ("vm_page_unwire: invalid queue %u request for page %p",
3129 if ((m->oflags & VPO_UNMANAGED) == 0)
3130 vm_page_assert_locked(m);
3131 if ((m->flags & PG_FICTITIOUS) != 0) {
3132 KASSERT(m->wire_count == 1,
3133 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
3136 if (m->wire_count > 0) {
3138 if (m->wire_count == 0) {
3139 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3140 if ((m->oflags & VPO_UNMANAGED) == 0 &&
3141 m->object != NULL && queue != PQ_NONE) {
3142 if (queue == PQ_INACTIVE)
3143 m->flags &= ~PG_WINATCFLS;
3144 vm_page_enqueue(queue, m);
3150 panic("vm_page_unwire: page %p's wire count is zero", m);
3154 * Move the specified page to the inactive queue.
3156 * Many pages placed on the inactive queue should actually go
3157 * into the cache, but it is difficult to figure out which. What
3158 * we do instead, if the inactive target is well met, is to put
3159 * clean pages at the head of the inactive queue instead of the tail.
3160 * This will cause them to be moved to the cache more quickly and
3161 * if not actively re-referenced, reclaimed more quickly. If we just
3162 * stick these pages at the end of the inactive queue, heavy filesystem
3163 * meta-data accesses can cause an unnecessary paging load on memory bound
3164 * processes. This optimization causes one-time-use metadata to be
3165 * reused more quickly.
3167 * Normally noreuse is FALSE, resulting in LRU operation. noreuse is set
3168 * to TRUE if we want this page to be 'as if it were placed in the cache',
3169 * except without unmapping it from the process address space. In
3170 * practice this is implemented by inserting the page at the head of the
3171 * queue, using a marker page to guide FIFO insertion ordering.
3173 * The page must be locked.
3176 _vm_page_deactivate(vm_page_t m, boolean_t noreuse)
3178 struct vm_pagequeue *pq;
3181 vm_page_assert_locked(m);
3184 * Ignore if the page is already inactive, unless it is unlikely to be
3187 if ((queue = m->queue) == PQ_INACTIVE && !noreuse)
3189 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
3190 pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
3191 /* Avoid multiple acquisitions of the inactive queue lock. */
3192 if (queue == PQ_INACTIVE) {
3193 vm_pagequeue_lock(pq);
3194 vm_page_dequeue_locked(m);
3196 if (queue != PQ_NONE)
3198 m->flags &= ~PG_WINATCFLS;
3199 vm_pagequeue_lock(pq);
3201 m->queue = PQ_INACTIVE;
3203 TAILQ_INSERT_BEFORE(&vm_phys_domain(m)->vmd_inacthead,
3206 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3207 vm_pagequeue_cnt_inc(pq);
3208 vm_pagequeue_unlock(pq);
3213 * Move the specified page to the inactive queue.
3215 * The page must be locked.
3218 vm_page_deactivate(vm_page_t m)
3221 _vm_page_deactivate(m, FALSE);
3225 * Move the specified page to the inactive queue with the expectation
3226 * that it is unlikely to be reused.
3228 * The page must be locked.
3231 vm_page_deactivate_noreuse(vm_page_t m)
3234 _vm_page_deactivate(m, TRUE);
3238 * vm_page_try_to_cache:
3240 * Returns 0 on failure, 1 on success
3243 vm_page_try_to_cache(vm_page_t m)
3246 vm_page_lock_assert(m, MA_OWNED);
3247 VM_OBJECT_ASSERT_WLOCKED(m->object);
3248 if (m->dirty || m->hold_count || m->wire_count ||
3249 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
3259 * vm_page_try_to_free()
3261 * Attempt to free the page. If we cannot free it, we do nothing.
3262 * 1 is returned on success, 0 on failure.
3265 vm_page_try_to_free(vm_page_t m)
3268 vm_page_lock_assert(m, MA_OWNED);
3269 if (m->object != NULL)
3270 VM_OBJECT_ASSERT_WLOCKED(m->object);
3271 if (m->dirty || m->hold_count || m->wire_count ||
3272 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
3284 * Put the specified page onto the page cache queue (if appropriate).
3286 * The object and page must be locked.
3289 vm_page_cache(vm_page_t m)
3292 boolean_t cache_was_empty;
3294 vm_page_lock_assert(m, MA_OWNED);
3296 VM_OBJECT_ASSERT_WLOCKED(object);
3297 if (vm_page_busied(m) || (m->oflags & VPO_UNMANAGED) ||
3298 m->hold_count || m->wire_count)
3299 panic("vm_page_cache: attempting to cache busy page");
3300 KASSERT(!pmap_page_is_mapped(m),
3301 ("vm_page_cache: page %p is mapped", m));
3302 KASSERT(m->dirty == 0, ("vm_page_cache: page %p is dirty", m));
3303 if (m->valid == 0 || object->type == OBJT_DEFAULT ||
3304 (object->type == OBJT_SWAP &&
3305 !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
3307 * Hypothesis: A cache-eligible page belonging to a
3308 * default object or swap object but without a backing
3309 * store must be zero filled.
3314 KASSERT((m->flags & PG_CACHED) == 0,
3315 ("vm_page_cache: page %p is already cached", m));
3318 * Remove the page from the paging queues.
3323 * Remove the page from the object's collection of resident
3326 vm_radix_remove(&object->rtree, m->pindex);
3327 TAILQ_REMOVE(&object->memq, m, listq);
3328 object->resident_page_count--;
3331 * Restore the default memory attribute to the page.
3333 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3334 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3337 * Insert the page into the object's collection of cached pages
3338 * and the physical memory allocator's cache/free page queues.
3340 m->flags &= ~PG_ZERO;
3341 mtx_lock(&vm_page_queue_free_mtx);
3342 cache_was_empty = vm_radix_is_empty(&object->cache);
3343 if (vm_radix_insert(&object->cache, m)) {
3344 mtx_unlock(&vm_page_queue_free_mtx);
3345 if (object->type == OBJT_VNODE &&
3346 object->resident_page_count == 0)
3347 vdrop(object->handle);
3354 * The above call to vm_radix_insert() could reclaim the one pre-
3355 * existing cached page from this object, resulting in a call to
3358 if (!cache_was_empty)
3359 cache_was_empty = vm_radix_is_singleton(&object->cache);
3361 m->flags |= PG_CACHED;
3362 vm_cnt.v_cache_count++;
3363 PCPU_INC(cnt.v_tcached);
3364 #if VM_NRESERVLEVEL > 0
3365 if (!vm_reserv_free_page(m)) {
3369 vm_phys_free_pages(m, 0);
3371 vm_page_free_wakeup();
3372 mtx_unlock(&vm_page_queue_free_mtx);
3375 * Increment the vnode's hold count if this is the object's only
3376 * cached page. Decrement the vnode's hold count if this was
3377 * the object's only resident page.
3379 if (object->type == OBJT_VNODE) {
3380 if (cache_was_empty && object->resident_page_count != 0)
3381 vhold(object->handle);
3382 else if (!cache_was_empty && object->resident_page_count == 0)
3383 vdrop(object->handle);
3390 * Deactivate or do nothing, as appropriate.
3392 * The object and page must be locked.
3395 vm_page_advise(vm_page_t m, int advice)
3398 vm_page_assert_locked(m);
3399 VM_OBJECT_ASSERT_WLOCKED(m->object);
3400 if (advice == MADV_FREE)
3402 * Mark the page clean. This will allow the page to be freed
3403 * up by the system. However, such pages are often reused
3404 * quickly by malloc() so we do not do anything that would
3405 * cause a page fault if we can help it.
3407 * Specifically, we do not try to actually free the page now
3408 * nor do we try to put it in the cache (which would cause a
3409 * page fault on reuse).
3411 * But we do make the page as freeable as we can without
3412 * actually taking the step of unmapping it.
3415 else if (advice != MADV_DONTNEED)
3419 * Clear any references to the page. Otherwise, the page daemon will
3420 * immediately reactivate the page.
3422 vm_page_aflag_clear(m, PGA_REFERENCED);
3424 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3428 * Place clean pages near the head of the inactive queue rather than
3429 * the tail, thus defeating the queue's LRU operation and ensuring that
3430 * the page will be reused quickly. Dirty pages are given a chance to
3431 * cycle once through the inactive queue before becoming eligible for
3434 _vm_page_deactivate(m, m->dirty == 0);
3438 * Grab a page, waiting until we are waken up due to the page
3439 * changing state. We keep on waiting, if the page continues
3440 * to be in the object. If the page doesn't exist, first allocate it
3441 * and then conditionally zero it.
3443 * This routine may sleep.
3445 * The object must be locked on entry. The lock will, however, be released
3446 * and reacquired if the routine sleeps.
3449 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3454 VM_OBJECT_ASSERT_WLOCKED(object);
3455 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3456 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3457 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3459 if ((m = vm_page_lookup(object, pindex)) != NULL) {
3460 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3461 vm_page_xbusied(m) : vm_page_busied(m);
3463 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3466 * Reference the page before unlocking and
3467 * sleeping so that the page daemon is less
3468 * likely to reclaim it.
3470 vm_page_aflag_set(m, PGA_REFERENCED);
3472 VM_OBJECT_WUNLOCK(object);
3473 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
3474 VM_ALLOC_IGN_SBUSY) != 0);
3475 VM_OBJECT_WLOCK(object);
3478 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3484 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3486 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3491 m = vm_page_alloc(object, pindex, allocflags);
3493 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3495 VM_OBJECT_WUNLOCK(object);
3497 VM_OBJECT_WLOCK(object);
3499 } else if (m->valid != 0)
3501 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3507 * Mapping function for valid or dirty bits in a page.
3509 * Inputs are required to range within a page.
3512 vm_page_bits(int base, int size)
3518 base + size <= PAGE_SIZE,
3519 ("vm_page_bits: illegal base/size %d/%d", base, size)
3522 if (size == 0) /* handle degenerate case */
3525 first_bit = base >> DEV_BSHIFT;
3526 last_bit = (base + size - 1) >> DEV_BSHIFT;
3528 return (((vm_page_bits_t)2 << last_bit) -
3529 ((vm_page_bits_t)1 << first_bit));
3533 * vm_page_set_valid_range:
3535 * Sets portions of a page valid. The arguments are expected
3536 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3537 * of any partial chunks touched by the range. The invalid portion of
3538 * such chunks will be zeroed.
3540 * (base + size) must be less then or equal to PAGE_SIZE.
3543 vm_page_set_valid_range(vm_page_t m, int base, int size)
3547 VM_OBJECT_ASSERT_WLOCKED(m->object);
3548 if (size == 0) /* handle degenerate case */
3552 * If the base is not DEV_BSIZE aligned and the valid
3553 * bit is clear, we have to zero out a portion of the
3556 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3557 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
3558 pmap_zero_page_area(m, frag, base - frag);
3561 * If the ending offset is not DEV_BSIZE aligned and the
3562 * valid bit is clear, we have to zero out a portion of
3565 endoff = base + size;
3566 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3567 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
3568 pmap_zero_page_area(m, endoff,
3569 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3572 * Assert that no previously invalid block that is now being validated
3575 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
3576 ("vm_page_set_valid_range: page %p is dirty", m));
3579 * Set valid bits inclusive of any overlap.
3581 m->valid |= vm_page_bits(base, size);
3585 * Clear the given bits from the specified page's dirty field.
3587 static __inline void
3588 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
3591 #if PAGE_SIZE < 16384
3596 * If the object is locked and the page is neither exclusive busy nor
3597 * write mapped, then the page's dirty field cannot possibly be
3598 * set by a concurrent pmap operation.
3600 VM_OBJECT_ASSERT_WLOCKED(m->object);
3601 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
3602 m->dirty &= ~pagebits;
3605 * The pmap layer can call vm_page_dirty() without
3606 * holding a distinguished lock. The combination of
3607 * the object's lock and an atomic operation suffice
3608 * to guarantee consistency of the page dirty field.
3610 * For PAGE_SIZE == 32768 case, compiler already
3611 * properly aligns the dirty field, so no forcible
3612 * alignment is needed. Only require existence of
3613 * atomic_clear_64 when page size is 32768.
3615 addr = (uintptr_t)&m->dirty;
3616 #if PAGE_SIZE == 32768
3617 atomic_clear_64((uint64_t *)addr, pagebits);
3618 #elif PAGE_SIZE == 16384
3619 atomic_clear_32((uint32_t *)addr, pagebits);
3620 #else /* PAGE_SIZE <= 8192 */
3622 * Use a trick to perform a 32-bit atomic on the
3623 * containing aligned word, to not depend on the existence
3624 * of atomic_clear_{8, 16}.
3626 shift = addr & (sizeof(uint32_t) - 1);
3627 #if BYTE_ORDER == BIG_ENDIAN
3628 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
3632 addr &= ~(sizeof(uint32_t) - 1);
3633 atomic_clear_32((uint32_t *)addr, pagebits << shift);
3634 #endif /* PAGE_SIZE */
3639 * vm_page_set_validclean:
3641 * Sets portions of a page valid and clean. The arguments are expected
3642 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3643 * of any partial chunks touched by the range. The invalid portion of
3644 * such chunks will be zero'd.
3646 * (base + size) must be less then or equal to PAGE_SIZE.
3649 vm_page_set_validclean(vm_page_t m, int base, int size)
3651 vm_page_bits_t oldvalid, pagebits;
3654 VM_OBJECT_ASSERT_WLOCKED(m->object);
3655 if (size == 0) /* handle degenerate case */
3659 * If the base is not DEV_BSIZE aligned and the valid
3660 * bit is clear, we have to zero out a portion of the
3663 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3664 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
3665 pmap_zero_page_area(m, frag, base - frag);
3668 * If the ending offset is not DEV_BSIZE aligned and the
3669 * valid bit is clear, we have to zero out a portion of
3672 endoff = base + size;
3673 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3674 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
3675 pmap_zero_page_area(m, endoff,
3676 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3679 * Set valid, clear dirty bits. If validating the entire
3680 * page we can safely clear the pmap modify bit. We also
3681 * use this opportunity to clear the VPO_NOSYNC flag. If a process
3682 * takes a write fault on a MAP_NOSYNC memory area the flag will
3685 * We set valid bits inclusive of any overlap, but we can only
3686 * clear dirty bits for DEV_BSIZE chunks that are fully within
3689 oldvalid = m->valid;
3690 pagebits = vm_page_bits(base, size);
3691 m->valid |= pagebits;
3693 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
3694 frag = DEV_BSIZE - frag;
3700 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
3702 if (base == 0 && size == PAGE_SIZE) {
3704 * The page can only be modified within the pmap if it is
3705 * mapped, and it can only be mapped if it was previously
3708 if (oldvalid == VM_PAGE_BITS_ALL)
3710 * Perform the pmap_clear_modify() first. Otherwise,
3711 * a concurrent pmap operation, such as
3712 * pmap_protect(), could clear a modification in the
3713 * pmap and set the dirty field on the page before
3714 * pmap_clear_modify() had begun and after the dirty
3715 * field was cleared here.
3717 pmap_clear_modify(m);
3719 m->oflags &= ~VPO_NOSYNC;
3720 } else if (oldvalid != VM_PAGE_BITS_ALL)
3721 m->dirty &= ~pagebits;
3723 vm_page_clear_dirty_mask(m, pagebits);
3727 vm_page_clear_dirty(vm_page_t m, int base, int size)
3730 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
3734 * vm_page_set_invalid:
3736 * Invalidates DEV_BSIZE'd chunks within a page. Both the
3737 * valid and dirty bits for the effected areas are cleared.
3740 vm_page_set_invalid(vm_page_t m, int base, int size)
3742 vm_page_bits_t bits;
3746 VM_OBJECT_ASSERT_WLOCKED(object);
3747 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
3748 size >= object->un_pager.vnp.vnp_size)
3749 bits = VM_PAGE_BITS_ALL;
3751 bits = vm_page_bits(base, size);
3752 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
3755 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3756 !pmap_page_is_mapped(m),
3757 ("vm_page_set_invalid: page %p is mapped", m));
3763 * vm_page_zero_invalid()
3765 * The kernel assumes that the invalid portions of a page contain
3766 * garbage, but such pages can be mapped into memory by user code.
3767 * When this occurs, we must zero out the non-valid portions of the
3768 * page so user code sees what it expects.
3770 * Pages are most often semi-valid when the end of a file is mapped
3771 * into memory and the file's size is not page aligned.
3774 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3779 VM_OBJECT_ASSERT_WLOCKED(m->object);
3781 * Scan the valid bits looking for invalid sections that
3782 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
3783 * valid bit may be set ) have already been zeroed by
3784 * vm_page_set_validclean().
3786 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3787 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3788 (m->valid & ((vm_page_bits_t)1 << i))) {
3790 pmap_zero_page_area(m,
3791 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3798 * setvalid is TRUE when we can safely set the zero'd areas
3799 * as being valid. We can do this if there are no cache consistancy
3800 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3803 m->valid = VM_PAGE_BITS_ALL;
3809 * Is (partial) page valid? Note that the case where size == 0
3810 * will return FALSE in the degenerate case where the page is
3811 * entirely invalid, and TRUE otherwise.
3814 vm_page_is_valid(vm_page_t m, int base, int size)
3816 vm_page_bits_t bits;
3818 VM_OBJECT_ASSERT_LOCKED(m->object);
3819 bits = vm_page_bits(base, size);
3820 return (m->valid != 0 && (m->valid & bits) == bits);
3824 * vm_page_ps_is_valid:
3826 * Returns TRUE if the entire (super)page is valid and FALSE otherwise.
3829 vm_page_ps_is_valid(vm_page_t m)
3833 VM_OBJECT_ASSERT_LOCKED(m->object);
3834 npages = atop(pagesizes[m->psind]);
3837 * The physically contiguous pages that make up a superpage, i.e., a
3838 * page with a page size index ("psind") greater than zero, will
3839 * occupy adjacent entries in vm_page_array[].
3841 for (i = 0; i < npages; i++) {
3842 if (m[i].valid != VM_PAGE_BITS_ALL)
3849 * Set the page's dirty bits if the page is modified.
3852 vm_page_test_dirty(vm_page_t m)
3855 VM_OBJECT_ASSERT_WLOCKED(m->object);
3856 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3861 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3864 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3868 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3871 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3875 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3878 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3881 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3883 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3886 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3890 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3893 mtx_assert_(vm_page_lockptr(m), a, file, line);
3899 vm_page_object_lock_assert(vm_page_t m)
3903 * Certain of the page's fields may only be modified by the
3904 * holder of the containing object's lock or the exclusive busy.
3905 * holder. Unfortunately, the holder of the write busy is
3906 * not recorded, and thus cannot be checked here.
3908 if (m->object != NULL && !vm_page_xbusied(m))
3909 VM_OBJECT_ASSERT_WLOCKED(m->object);
3913 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3916 if ((bits & PGA_WRITEABLE) == 0)
3920 * The PGA_WRITEABLE flag can only be set if the page is
3921 * managed, is exclusively busied or the object is locked.
3922 * Currently, this flag is only set by pmap_enter().
3924 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3925 ("PGA_WRITEABLE on unmanaged page"));
3926 if (!vm_page_xbusied(m))
3927 VM_OBJECT_ASSERT_LOCKED(m->object);
3931 #include "opt_ddb.h"
3933 #include <sys/kernel.h>
3935 #include <ddb/ddb.h>
3937 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3939 db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
3940 db_printf("vm_cnt.v_cache_count: %d\n", vm_cnt.v_cache_count);
3941 db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
3942 db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
3943 db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
3944 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
3945 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
3946 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
3947 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
3950 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3954 db_printf("pq_free %d pq_cache %d\n",
3955 vm_cnt.v_free_count, vm_cnt.v_cache_count);
3956 for (dom = 0; dom < vm_ndomains; dom++) {
3957 db_printf("dom %d page_cnt %d free %d pq_act %d pq_inact %d\n",
3959 vm_dom[dom].vmd_page_count,
3960 vm_dom[dom].vmd_free_count,
3961 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3962 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt);
3966 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3972 db_printf("show pginfo addr\n");
3976 phys = strchr(modif, 'p') != NULL;
3978 m = PHYS_TO_VM_PAGE(addr);
3980 m = (vm_page_t)addr;
3982 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3983 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3984 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3985 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3986 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);