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;
399 for (i = 0; i < PQ_COUNT; i++) {
400 pq = &vmd->vmd_pagequeues[i];
401 TAILQ_INIT(&pq->pq_pl);
402 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
403 MTX_DEF | MTX_DUPOK);
410 * Initializes the resident memory module.
412 * Allocates memory for the page cells, and
413 * for the object/offset-to-page hash table headers.
414 * Each page cell is initialized and placed on the free list.
417 vm_page_startup(vm_offset_t vaddr)
420 vm_paddr_t page_range;
425 char *list, *listend;
427 vm_paddr_t biggestsize;
428 vm_paddr_t low_water, high_water;
434 vaddr = round_page(vaddr);
436 for (i = 0; phys_avail[i + 1]; i += 2) {
437 phys_avail[i] = round_page(phys_avail[i]);
438 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
441 low_water = phys_avail[0];
442 high_water = phys_avail[1];
444 for (i = 0; i < vm_phys_nsegs; i++) {
445 if (vm_phys_segs[i].start < low_water)
446 low_water = vm_phys_segs[i].start;
447 if (vm_phys_segs[i].end > high_water)
448 high_water = vm_phys_segs[i].end;
450 for (i = 0; phys_avail[i + 1]; i += 2) {
451 vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
453 if (size > biggestsize) {
457 if (phys_avail[i] < low_water)
458 low_water = phys_avail[i];
459 if (phys_avail[i + 1] > high_water)
460 high_water = phys_avail[i + 1];
463 end = phys_avail[biggestone+1];
466 * Initialize the page and queue locks.
468 mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
469 for (i = 0; i < PA_LOCK_COUNT; i++)
470 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
471 for (i = 0; i < vm_ndomains; i++)
472 vm_page_domain_init(&vm_dom[i]);
475 * Almost all of the pages needed for boot strapping UMA are used
476 * for zone structures, so if the number of CPUs results in those
477 * structures taking more than one page each, we set aside more pages
478 * in proportion to the zone structure size.
480 pages_per_zone = howmany(sizeof(struct uma_zone) +
481 sizeof(struct uma_cache) * (mp_maxid + 1), UMA_SLAB_SIZE);
482 if (pages_per_zone > 1) {
483 /* Reserve more pages so that we don't run out. */
484 boot_pages = UMA_BOOT_PAGES_ZONES * pages_per_zone;
488 * Allocate memory for use when boot strapping the kernel memory
491 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
492 * manually fetch the value.
494 TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
495 new_end = end - (boot_pages * UMA_SLAB_SIZE);
496 new_end = trunc_page(new_end);
497 mapped = pmap_map(&vaddr, new_end, end,
498 VM_PROT_READ | VM_PROT_WRITE);
499 bzero((void *)mapped, end - new_end);
500 uma_startup((void *)mapped, boot_pages);
502 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
503 defined(__i386__) || defined(__mips__)
505 * Allocate a bitmap to indicate that a random physical page
506 * needs to be included in a minidump.
508 * The amd64 port needs this to indicate which direct map pages
509 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
511 * However, i386 still needs this workspace internally within the
512 * minidump code. In theory, they are not needed on i386, but are
513 * included should the sf_buf code decide to use them.
516 for (i = 0; dump_avail[i + 1] != 0; i += 2)
517 if (dump_avail[i + 1] > last_pa)
518 last_pa = dump_avail[i + 1];
519 page_range = last_pa / PAGE_SIZE;
520 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
521 new_end -= vm_page_dump_size;
522 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
523 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
524 bzero((void *)vm_page_dump, vm_page_dump_size);
528 * Request that the physical pages underlying the message buffer be
529 * included in a crash dump. Since the message buffer is accessed
530 * through the direct map, they are not automatically included.
532 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
533 last_pa = pa + round_page(msgbufsize);
534 while (pa < last_pa) {
540 * Compute the number of pages of memory that will be available for
541 * use (taking into account the overhead of a page structure per
544 first_page = low_water / PAGE_SIZE;
545 #ifdef VM_PHYSSEG_SPARSE
547 for (i = 0; i < vm_phys_nsegs; i++) {
548 page_range += atop(vm_phys_segs[i].end -
549 vm_phys_segs[i].start);
551 for (i = 0; phys_avail[i + 1] != 0; i += 2)
552 page_range += atop(phys_avail[i + 1] - phys_avail[i]);
553 #elif defined(VM_PHYSSEG_DENSE)
554 page_range = high_water / PAGE_SIZE - first_page;
556 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
561 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
566 * Initialize the mem entry structures now, and put them in the free
569 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
570 mapped = pmap_map(&vaddr, new_end, end,
571 VM_PROT_READ | VM_PROT_WRITE);
572 vm_page_array = (vm_page_t) mapped;
573 #if VM_NRESERVLEVEL > 0
575 * Allocate memory for the reservation management system's data
578 new_end = vm_reserv_startup(&vaddr, new_end, high_water);
580 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
582 * pmap_map on arm64, amd64, and mips can come out of the direct-map,
583 * not kvm like i386, so the pages must be tracked for a crashdump to
584 * include this data. This includes the vm_page_array and the early
585 * UMA bootstrap pages.
587 for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
590 phys_avail[biggestone + 1] = new_end;
593 * Add physical memory segments corresponding to the available
596 for (i = 0; phys_avail[i + 1] != 0; i += 2)
597 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
600 * Clear all of the page structures
602 bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
603 for (i = 0; i < page_range; i++)
604 vm_page_array[i].order = VM_NFREEORDER;
605 vm_page_array_size = page_range;
608 * Initialize the physical memory allocator.
613 * Add every available physical page that is not blacklisted to
616 vm_cnt.v_page_count = 0;
617 vm_cnt.v_free_count = 0;
618 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
620 last_pa = phys_avail[i + 1];
621 while (pa < last_pa) {
622 vm_phys_add_page(pa);
627 TAILQ_INIT(&blacklist_head);
628 vm_page_blacklist_load(&list, &listend);
629 vm_page_blacklist_check(list, listend);
631 list = kern_getenv("vm.blacklist");
632 vm_page_blacklist_check(list, NULL);
635 #if VM_NRESERVLEVEL > 0
637 * Initialize the reservation management system.
645 vm_page_reference(vm_page_t m)
648 vm_page_aflag_set(m, PGA_REFERENCED);
652 * vm_page_busy_downgrade:
654 * Downgrade an exclusive busy page into a single shared busy page.
657 vm_page_busy_downgrade(vm_page_t m)
662 vm_page_assert_xbusied(m);
663 locked = mtx_owned(vm_page_lockptr(m));
667 x &= VPB_BIT_WAITERS;
668 if (x != 0 && !locked)
670 if (atomic_cmpset_rel_int(&m->busy_lock,
671 VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1)))
673 if (x != 0 && !locked)
686 * Return a positive value if the page is shared busied, 0 otherwise.
689 vm_page_sbusied(vm_page_t m)
694 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
700 * Shared unbusy a page.
703 vm_page_sunbusy(vm_page_t m)
707 vm_page_assert_sbusied(m);
711 if (VPB_SHARERS(x) > 1) {
712 if (atomic_cmpset_int(&m->busy_lock, x,
717 if ((x & VPB_BIT_WAITERS) == 0) {
718 KASSERT(x == VPB_SHARERS_WORD(1),
719 ("vm_page_sunbusy: invalid lock state"));
720 if (atomic_cmpset_int(&m->busy_lock,
721 VPB_SHARERS_WORD(1), VPB_UNBUSIED))
725 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
726 ("vm_page_sunbusy: invalid lock state for waiters"));
729 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
740 * vm_page_busy_sleep:
742 * Sleep and release the page lock, using the page pointer as wchan.
743 * This is used to implement the hard-path of busying mechanism.
745 * The given page must be locked.
747 * If nonshared is true, sleep only if the page is xbusy.
750 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
754 vm_page_assert_locked(m);
757 if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
758 ((x & VPB_BIT_WAITERS) == 0 &&
759 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
763 msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
769 * Try to shared busy a page.
770 * If the operation succeeds 1 is returned otherwise 0.
771 * The operation never sleeps.
774 vm_page_trysbusy(vm_page_t m)
780 if ((x & VPB_BIT_SHARED) == 0)
782 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
788 vm_page_xunbusy_locked(vm_page_t m)
791 vm_page_assert_xbusied(m);
792 vm_page_assert_locked(m);
794 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
795 /* There is a waiter, do wakeup() instead of vm_page_flash(). */
800 vm_page_xunbusy_maybelocked(vm_page_t m)
804 vm_page_assert_xbusied(m);
807 * Fast path for unbusy. If it succeeds, we know that there
808 * are no waiters, so we do not need a wakeup.
810 if (atomic_cmpset_rel_int(&m->busy_lock, VPB_SINGLE_EXCLUSIVER,
814 lockacq = !mtx_owned(vm_page_lockptr(m));
817 vm_page_xunbusy_locked(m);
823 * vm_page_xunbusy_hard:
825 * Called after the first try the exclusive unbusy of a page failed.
826 * It is assumed that the waiters bit is on.
829 vm_page_xunbusy_hard(vm_page_t m)
832 vm_page_assert_xbusied(m);
835 vm_page_xunbusy_locked(m);
842 * Wakeup anyone waiting for the page.
843 * The ownership bits do not change.
845 * The given page must be locked.
848 vm_page_flash(vm_page_t m)
852 vm_page_lock_assert(m, MA_OWNED);
856 if ((x & VPB_BIT_WAITERS) == 0)
858 if (atomic_cmpset_int(&m->busy_lock, x,
859 x & (~VPB_BIT_WAITERS)))
866 * Keep page from being freed by the page daemon
867 * much of the same effect as wiring, except much lower
868 * overhead and should be used only for *very* temporary
869 * holding ("wiring").
872 vm_page_hold(vm_page_t mem)
875 vm_page_lock_assert(mem, MA_OWNED);
880 vm_page_unhold(vm_page_t mem)
883 vm_page_lock_assert(mem, MA_OWNED);
884 KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
886 if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
887 vm_page_free_toq(mem);
891 * vm_page_unhold_pages:
893 * Unhold each of the pages that is referenced by the given array.
896 vm_page_unhold_pages(vm_page_t *ma, int count)
898 struct mtx *mtx, *new_mtx;
901 for (; count != 0; count--) {
903 * Avoid releasing and reacquiring the same page lock.
905 new_mtx = vm_page_lockptr(*ma);
906 if (mtx != new_mtx) {
920 PHYS_TO_VM_PAGE(vm_paddr_t pa)
924 #ifdef VM_PHYSSEG_SPARSE
925 m = vm_phys_paddr_to_vm_page(pa);
927 m = vm_phys_fictitious_to_vm_page(pa);
929 #elif defined(VM_PHYSSEG_DENSE)
933 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
934 m = &vm_page_array[pi - first_page];
937 return (vm_phys_fictitious_to_vm_page(pa));
939 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
946 * Create a fictitious page with the specified physical address and
947 * memory attribute. The memory attribute is the only the machine-
948 * dependent aspect of a fictitious page that must be initialized.
951 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
955 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
956 vm_page_initfake(m, paddr, memattr);
961 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
964 if ((m->flags & PG_FICTITIOUS) != 0) {
966 * The page's memattr might have changed since the
967 * previous initialization. Update the pmap to the
972 m->phys_addr = paddr;
974 /* Fictitious pages don't use "segind". */
975 m->flags = PG_FICTITIOUS;
976 /* Fictitious pages don't use "order" or "pool". */
977 m->oflags = VPO_UNMANAGED;
978 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
982 pmap_page_set_memattr(m, memattr);
988 * Release a fictitious page.
991 vm_page_putfake(vm_page_t m)
994 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
995 KASSERT((m->flags & PG_FICTITIOUS) != 0,
996 ("vm_page_putfake: bad page %p", m));
997 uma_zfree(fakepg_zone, m);
1001 * vm_page_updatefake:
1003 * Update the given fictitious page to the specified physical address and
1007 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1010 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1011 ("vm_page_updatefake: bad page %p", m));
1012 m->phys_addr = paddr;
1013 pmap_page_set_memattr(m, memattr);
1022 vm_page_free(vm_page_t m)
1025 m->flags &= ~PG_ZERO;
1026 vm_page_free_toq(m);
1030 * vm_page_free_zero:
1032 * Free a page to the zerod-pages queue
1035 vm_page_free_zero(vm_page_t m)
1038 m->flags |= PG_ZERO;
1039 vm_page_free_toq(m);
1043 * Unbusy and handle the page queueing for a page from a getpages request that
1044 * was optionally read ahead or behind.
1047 vm_page_readahead_finish(vm_page_t m)
1050 /* We shouldn't put invalid pages on queues. */
1051 KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
1054 * Since the page is not the actually needed one, whether it should
1055 * be activated or deactivated is not obvious. Empirical results
1056 * have shown that deactivating the page is usually the best choice,
1057 * unless the page is wanted by another thread.
1060 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1061 vm_page_activate(m);
1063 vm_page_deactivate(m);
1069 * vm_page_sleep_if_busy:
1071 * Sleep and release the page queues lock if the page is busied.
1072 * Returns TRUE if the thread slept.
1074 * The given page must be unlocked and object containing it must
1078 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1082 vm_page_lock_assert(m, MA_NOTOWNED);
1083 VM_OBJECT_ASSERT_WLOCKED(m->object);
1085 if (vm_page_busied(m)) {
1087 * The page-specific object must be cached because page
1088 * identity can change during the sleep, causing the
1089 * re-lock of a different object.
1090 * It is assumed that a reference to the object is already
1091 * held by the callers.
1095 VM_OBJECT_WUNLOCK(obj);
1096 vm_page_busy_sleep(m, msg, false);
1097 VM_OBJECT_WLOCK(obj);
1104 * vm_page_dirty_KBI: [ internal use only ]
1106 * Set all bits in the page's dirty field.
1108 * The object containing the specified page must be locked if the
1109 * call is made from the machine-independent layer.
1111 * See vm_page_clear_dirty_mask().
1113 * This function should only be called by vm_page_dirty().
1116 vm_page_dirty_KBI(vm_page_t m)
1119 /* These assertions refer to this operation by its public name. */
1120 KASSERT((m->flags & PG_CACHED) == 0,
1121 ("vm_page_dirty: page in cache!"));
1122 KASSERT(m->valid == VM_PAGE_BITS_ALL,
1123 ("vm_page_dirty: page is invalid!"));
1124 m->dirty = VM_PAGE_BITS_ALL;
1128 * vm_page_insert: [ internal use only ]
1130 * Inserts the given mem entry into the object and object list.
1132 * The object must be locked.
1135 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1139 VM_OBJECT_ASSERT_WLOCKED(object);
1140 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1141 return (vm_page_insert_after(m, object, pindex, mpred));
1145 * vm_page_insert_after:
1147 * Inserts the page "m" into the specified object at offset "pindex".
1149 * The page "mpred" must immediately precede the offset "pindex" within
1150 * the specified object.
1152 * The object must be locked.
1155 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1160 VM_OBJECT_ASSERT_WLOCKED(object);
1161 KASSERT(m->object == NULL,
1162 ("vm_page_insert_after: page already inserted"));
1163 if (mpred != NULL) {
1164 KASSERT(mpred->object == object,
1165 ("vm_page_insert_after: object doesn't contain mpred"));
1166 KASSERT(mpred->pindex < pindex,
1167 ("vm_page_insert_after: mpred doesn't precede pindex"));
1168 msucc = TAILQ_NEXT(mpred, listq);
1170 msucc = TAILQ_FIRST(&object->memq);
1172 KASSERT(msucc->pindex > pindex,
1173 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1176 * Record the object/offset pair in this page
1182 * Now link into the object's ordered list of backed pages.
1184 if (vm_radix_insert(&object->rtree, m)) {
1189 vm_page_insert_radixdone(m, object, mpred);
1194 * vm_page_insert_radixdone:
1196 * Complete page "m" insertion into the specified object after the
1197 * radix trie hooking.
1199 * The page "mpred" must precede the offset "m->pindex" within the
1202 * The object must be locked.
1205 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1208 VM_OBJECT_ASSERT_WLOCKED(object);
1209 KASSERT(object != NULL && m->object == object,
1210 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1211 if (mpred != NULL) {
1212 KASSERT(mpred->object == object,
1213 ("vm_page_insert_after: object doesn't contain mpred"));
1214 KASSERT(mpred->pindex < m->pindex,
1215 ("vm_page_insert_after: mpred doesn't precede pindex"));
1219 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1221 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1224 * Show that the object has one more resident page.
1226 object->resident_page_count++;
1229 * Hold the vnode until the last page is released.
1231 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1232 vhold(object->handle);
1235 * Since we are inserting a new and possibly dirty page,
1236 * update the object's OBJ_MIGHTBEDIRTY flag.
1238 if (pmap_page_is_write_mapped(m))
1239 vm_object_set_writeable_dirty(object);
1245 * Removes the given mem entry from the object/offset-page
1246 * table and the object page list, but do not invalidate/terminate
1247 * the backing store.
1249 * The object must be locked. The page must be locked if it is managed.
1252 vm_page_remove(vm_page_t m)
1256 if ((m->oflags & VPO_UNMANAGED) == 0)
1257 vm_page_assert_locked(m);
1258 if ((object = m->object) == NULL)
1260 VM_OBJECT_ASSERT_WLOCKED(object);
1261 if (vm_page_xbusied(m))
1262 vm_page_xunbusy_maybelocked(m);
1265 * Now remove from the object's list of backed pages.
1267 vm_radix_remove(&object->rtree, m->pindex);
1268 TAILQ_REMOVE(&object->memq, m, listq);
1271 * And show that the object has one fewer resident page.
1273 object->resident_page_count--;
1276 * The vnode may now be recycled.
1278 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1279 vdrop(object->handle);
1287 * Returns the page associated with the object/offset
1288 * pair specified; if none is found, NULL is returned.
1290 * The object must be locked.
1293 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1296 VM_OBJECT_ASSERT_LOCKED(object);
1297 return (vm_radix_lookup(&object->rtree, pindex));
1301 * vm_page_find_least:
1303 * Returns the page associated with the object with least pindex
1304 * greater than or equal to the parameter pindex, or NULL.
1306 * The object must be locked.
1309 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1313 VM_OBJECT_ASSERT_LOCKED(object);
1314 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1315 m = vm_radix_lookup_ge(&object->rtree, pindex);
1320 * Returns the given page's successor (by pindex) within the object if it is
1321 * resident; if none is found, NULL is returned.
1323 * The object must be locked.
1326 vm_page_next(vm_page_t m)
1330 VM_OBJECT_ASSERT_LOCKED(m->object);
1331 if ((next = TAILQ_NEXT(m, listq)) != NULL &&
1332 next->pindex != m->pindex + 1)
1338 * Returns the given page's predecessor (by pindex) within the object if it is
1339 * resident; if none is found, NULL is returned.
1341 * The object must be locked.
1344 vm_page_prev(vm_page_t m)
1348 VM_OBJECT_ASSERT_LOCKED(m->object);
1349 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
1350 prev->pindex != m->pindex - 1)
1356 * Uses the page mnew as a replacement for an existing page at index
1357 * pindex which must be already present in the object.
1359 * The existing page must not be on a paging queue.
1362 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1366 VM_OBJECT_ASSERT_WLOCKED(object);
1367 KASSERT(mnew->object == NULL,
1368 ("vm_page_replace: page already in object"));
1371 * This function mostly follows vm_page_insert() and
1372 * vm_page_remove() without the radix, object count and vnode
1373 * dance. Double check such functions for more comments.
1376 mnew->object = object;
1377 mnew->pindex = pindex;
1378 mold = vm_radix_replace(&object->rtree, mnew);
1379 KASSERT(mold->queue == PQ_NONE,
1380 ("vm_page_replace: mold is on a paging queue"));
1382 /* Keep the resident page list in sorted order. */
1383 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1384 TAILQ_REMOVE(&object->memq, mold, listq);
1386 mold->object = NULL;
1387 vm_page_xunbusy_maybelocked(mold);
1390 * The object's resident_page_count does not change because we have
1391 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1393 if (pmap_page_is_write_mapped(mnew))
1394 vm_object_set_writeable_dirty(object);
1401 * Move the given memory entry from its
1402 * current object to the specified target object/offset.
1404 * Note: swap associated with the page must be invalidated by the move. We
1405 * have to do this for several reasons: (1) we aren't freeing the
1406 * page, (2) we are dirtying the page, (3) the VM system is probably
1407 * moving the page from object A to B, and will then later move
1408 * the backing store from A to B and we can't have a conflict.
1410 * Note: we *always* dirty the page. It is necessary both for the
1411 * fact that we moved it, and because we may be invalidating
1412 * swap. If the page is on the cache, we have to deactivate it
1413 * or vm_page_dirty() will panic. Dirty pages are not allowed
1416 * The objects must be locked.
1419 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1424 VM_OBJECT_ASSERT_WLOCKED(new_object);
1426 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1427 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1428 ("vm_page_rename: pindex already renamed"));
1431 * Create a custom version of vm_page_insert() which does not depend
1432 * by m_prev and can cheat on the implementation aspects of the
1436 m->pindex = new_pindex;
1437 if (vm_radix_insert(&new_object->rtree, m)) {
1443 * The operation cannot fail anymore. The removal must happen before
1444 * the listq iterator is tainted.
1450 /* Return back to the new pindex to complete vm_page_insert(). */
1451 m->pindex = new_pindex;
1452 m->object = new_object;
1454 vm_page_insert_radixdone(m, new_object, mpred);
1460 * Convert all of the given object's cached pages that have a
1461 * pindex within the given range into free pages. If the value
1462 * zero is given for "end", then the range's upper bound is
1463 * infinity. If the given object is backed by a vnode and it
1464 * transitions from having one or more cached pages to none, the
1465 * vnode's hold count is reduced.
1468 vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1473 mtx_lock(&vm_page_queue_free_mtx);
1474 if (__predict_false(vm_radix_is_empty(&object->cache))) {
1475 mtx_unlock(&vm_page_queue_free_mtx);
1478 while ((m = vm_radix_lookup_ge(&object->cache, start)) != NULL) {
1479 if (end != 0 && m->pindex >= end)
1481 vm_radix_remove(&object->cache, m->pindex);
1482 vm_page_cache_turn_free(m);
1484 empty = vm_radix_is_empty(&object->cache);
1485 mtx_unlock(&vm_page_queue_free_mtx);
1486 if (object->type == OBJT_VNODE && empty)
1487 vdrop(object->handle);
1491 * Returns the cached page that is associated with the given
1492 * object and offset. If, however, none exists, returns NULL.
1494 * The free page queue must be locked.
1496 static inline vm_page_t
1497 vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
1500 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1501 return (vm_radix_lookup(&object->cache, pindex));
1505 * Remove the given cached page from its containing object's
1506 * collection of cached pages.
1508 * The free page queue must be locked.
1511 vm_page_cache_remove(vm_page_t m)
1514 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1515 KASSERT((m->flags & PG_CACHED) != 0,
1516 ("vm_page_cache_remove: page %p is not cached", m));
1517 vm_radix_remove(&m->object->cache, m->pindex);
1519 vm_cnt.v_cache_count--;
1523 * Transfer all of the cached pages with offset greater than or
1524 * equal to 'offidxstart' from the original object's cache to the
1525 * new object's cache. However, any cached pages with offset
1526 * greater than or equal to the new object's size are kept in the
1527 * original object. Initially, the new object's cache must be
1528 * empty. Offset 'offidxstart' in the original object must
1529 * correspond to offset zero in the new object.
1531 * The new object must be locked.
1534 vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1535 vm_object_t new_object)
1540 * Insertion into an object's collection of cached pages
1541 * requires the object to be locked. In contrast, removal does
1544 VM_OBJECT_ASSERT_WLOCKED(new_object);
1545 KASSERT(vm_radix_is_empty(&new_object->cache),
1546 ("vm_page_cache_transfer: object %p has cached pages",
1548 mtx_lock(&vm_page_queue_free_mtx);
1549 while ((m = vm_radix_lookup_ge(&orig_object->cache,
1550 offidxstart)) != NULL) {
1552 * Transfer all of the pages with offset greater than or
1553 * equal to 'offidxstart' from the original object's
1554 * cache to the new object's cache.
1556 if ((m->pindex - offidxstart) >= new_object->size)
1558 vm_radix_remove(&orig_object->cache, m->pindex);
1559 /* Update the page's object and offset. */
1560 m->object = new_object;
1561 m->pindex -= offidxstart;
1562 if (vm_radix_insert(&new_object->cache, m))
1563 vm_page_cache_turn_free(m);
1565 mtx_unlock(&vm_page_queue_free_mtx);
1569 * Returns TRUE if a cached page is associated with the given object and
1570 * offset, and FALSE otherwise.
1572 * The object must be locked.
1575 vm_page_is_cached(vm_object_t object, vm_pindex_t pindex)
1580 * Insertion into an object's collection of cached pages requires the
1581 * object to be locked. Therefore, if the object is locked and the
1582 * object's collection is empty, there is no need to acquire the free
1583 * page queues lock in order to prove that the specified page doesn't
1586 VM_OBJECT_ASSERT_WLOCKED(object);
1587 if (__predict_true(vm_object_cache_is_empty(object)))
1589 mtx_lock(&vm_page_queue_free_mtx);
1590 m = vm_page_cache_lookup(object, pindex);
1591 mtx_unlock(&vm_page_queue_free_mtx);
1598 * Allocate and return a page that is associated with the specified
1599 * object and offset pair. By default, this page is exclusive busied.
1601 * The caller must always specify an allocation class.
1603 * allocation classes:
1604 * VM_ALLOC_NORMAL normal process request
1605 * VM_ALLOC_SYSTEM system *really* needs a page
1606 * VM_ALLOC_INTERRUPT interrupt time request
1608 * optional allocation flags:
1609 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1610 * intends to allocate
1611 * VM_ALLOC_IFCACHED return page only if it is cached
1612 * VM_ALLOC_IFNOTCACHED return NULL, do not reactivate if the page
1614 * VM_ALLOC_NOBUSY do not exclusive busy the page
1615 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1616 * VM_ALLOC_NOOBJ page is not associated with an object and
1617 * should not be exclusive busy
1618 * VM_ALLOC_SBUSY shared busy the allocated page
1619 * VM_ALLOC_WIRED wire the allocated page
1620 * VM_ALLOC_ZERO prefer a zeroed page
1622 * This routine may not sleep.
1625 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1627 struct vnode *vp = NULL;
1628 vm_object_t m_object;
1630 int flags, req_class;
1632 mpred = 0; /* XXX: pacify gcc */
1633 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1634 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1635 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1636 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1637 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1640 VM_OBJECT_ASSERT_WLOCKED(object);
1642 req_class = req & VM_ALLOC_CLASS_MASK;
1645 * The page daemon is allowed to dig deeper into the free page list.
1647 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1648 req_class = VM_ALLOC_SYSTEM;
1650 if (object != NULL) {
1651 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1652 KASSERT(mpred == NULL || mpred->pindex != pindex,
1653 ("vm_page_alloc: pindex already allocated"));
1657 * The page allocation request can came from consumers which already
1658 * hold the free page queue mutex, like vm_page_insert() in
1661 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
1662 if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
1663 (req_class == VM_ALLOC_SYSTEM &&
1664 vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
1665 (req_class == VM_ALLOC_INTERRUPT &&
1666 vm_cnt.v_free_count + vm_cnt.v_cache_count > 0)) {
1668 * Allocate from the free queue if the number of free pages
1669 * exceeds the minimum for the request class.
1671 if (object != NULL &&
1672 (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1673 if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1674 mtx_unlock(&vm_page_queue_free_mtx);
1677 if (vm_phys_unfree_page(m))
1678 vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1679 #if VM_NRESERVLEVEL > 0
1680 else if (!vm_reserv_reactivate_page(m))
1684 panic("vm_page_alloc: cache page %p is missing"
1685 " from the free queue", m);
1686 } else if ((req & VM_ALLOC_IFCACHED) != 0) {
1687 mtx_unlock(&vm_page_queue_free_mtx);
1689 #if VM_NRESERVLEVEL > 0
1690 } else if (object == NULL || (object->flags & (OBJ_COLORED |
1691 OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1692 vm_reserv_alloc_page(object, pindex, mpred)) == NULL) {
1696 m = vm_phys_alloc_pages(object != NULL ?
1697 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1698 #if VM_NRESERVLEVEL > 0
1699 if (m == NULL && vm_reserv_reclaim_inactive()) {
1700 m = vm_phys_alloc_pages(object != NULL ?
1701 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1708 * Not allocatable, give up.
1710 mtx_unlock(&vm_page_queue_free_mtx);
1711 atomic_add_int(&vm_pageout_deficit,
1712 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1713 pagedaemon_wakeup();
1718 * At this point we had better have found a good page.
1720 KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1721 KASSERT(m->queue == PQ_NONE,
1722 ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1723 KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1724 KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1725 KASSERT(!vm_page_busied(m), ("vm_page_alloc: page %p is busy", m));
1726 KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1727 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1728 ("vm_page_alloc: page %p has unexpected memattr %d", m,
1729 pmap_page_get_memattr(m)));
1730 if ((m->flags & PG_CACHED) != 0) {
1731 KASSERT((m->flags & PG_ZERO) == 0,
1732 ("vm_page_alloc: cached page %p is PG_ZERO", m));
1733 KASSERT(m->valid != 0,
1734 ("vm_page_alloc: cached page %p is invalid", m));
1735 if (m->object == object && m->pindex == pindex)
1736 vm_cnt.v_reactivated++;
1739 m_object = m->object;
1740 vm_page_cache_remove(m);
1741 if (m_object->type == OBJT_VNODE &&
1742 vm_object_cache_is_empty(m_object))
1743 vp = m_object->handle;
1745 KASSERT(m->valid == 0,
1746 ("vm_page_alloc: free page %p is valid", m));
1747 vm_phys_freecnt_adj(m, -1);
1748 if ((m->flags & PG_ZERO) != 0)
1749 vm_page_zero_count--;
1751 mtx_unlock(&vm_page_queue_free_mtx);
1754 * Initialize the page. Only the PG_ZERO flag is inherited.
1757 if ((req & VM_ALLOC_ZERO) != 0)
1760 if ((req & VM_ALLOC_NODUMP) != 0)
1764 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1766 m->busy_lock = VPB_UNBUSIED;
1767 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1768 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1769 if ((req & VM_ALLOC_SBUSY) != 0)
1770 m->busy_lock = VPB_SHARERS_WORD(1);
1771 if (req & VM_ALLOC_WIRED) {
1773 * The page lock is not required for wiring a page until that
1774 * page is inserted into the object.
1776 atomic_add_int(&vm_cnt.v_wire_count, 1);
1781 if (object != NULL) {
1782 if (vm_page_insert_after(m, object, pindex, mpred)) {
1783 /* See the comment below about hold count. */
1786 pagedaemon_wakeup();
1787 if (req & VM_ALLOC_WIRED) {
1788 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1792 m->oflags = VPO_UNMANAGED;
1793 m->busy_lock = VPB_UNBUSIED;
1798 /* Ignore device objects; the pager sets "memattr" for them. */
1799 if (object->memattr != VM_MEMATTR_DEFAULT &&
1800 (object->flags & OBJ_FICTITIOUS) == 0)
1801 pmap_page_set_memattr(m, object->memattr);
1806 * The following call to vdrop() must come after the above call
1807 * to vm_page_insert() in case both affect the same object and
1808 * vnode. Otherwise, the affected vnode's hold count could
1809 * temporarily become zero.
1815 * Don't wakeup too often - wakeup the pageout daemon when
1816 * we would be nearly out of memory.
1818 if (vm_paging_needed())
1819 pagedaemon_wakeup();
1825 vm_page_alloc_contig_vdrop(struct spglist *lst)
1828 while (!SLIST_EMPTY(lst)) {
1829 vdrop((struct vnode *)SLIST_FIRST(lst)-> plinks.s.pv);
1830 SLIST_REMOVE_HEAD(lst, plinks.s.ss);
1835 * vm_page_alloc_contig:
1837 * Allocate a contiguous set of physical pages of the given size "npages"
1838 * from the free lists. All of the physical pages must be at or above
1839 * the given physical address "low" and below the given physical address
1840 * "high". The given value "alignment" determines the alignment of the
1841 * first physical page in the set. If the given value "boundary" is
1842 * non-zero, then the set of physical pages cannot cross any physical
1843 * address boundary that is a multiple of that value. Both "alignment"
1844 * and "boundary" must be a power of two.
1846 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1847 * then the memory attribute setting for the physical pages is configured
1848 * to the object's memory attribute setting. Otherwise, the memory
1849 * attribute setting for the physical pages is configured to "memattr",
1850 * overriding the object's memory attribute setting. However, if the
1851 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1852 * memory attribute setting for the physical pages cannot be configured
1853 * to VM_MEMATTR_DEFAULT.
1855 * The caller must always specify an allocation class.
1857 * allocation classes:
1858 * VM_ALLOC_NORMAL normal process request
1859 * VM_ALLOC_SYSTEM system *really* needs a page
1860 * VM_ALLOC_INTERRUPT interrupt time request
1862 * optional allocation flags:
1863 * VM_ALLOC_NOBUSY do not exclusive busy the page
1864 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1865 * VM_ALLOC_NOOBJ page is not associated with an object and
1866 * should not be exclusive busy
1867 * VM_ALLOC_SBUSY shared busy the allocated page
1868 * VM_ALLOC_WIRED wire the allocated page
1869 * VM_ALLOC_ZERO prefer a zeroed page
1871 * This routine may not sleep.
1874 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1875 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1876 vm_paddr_t boundary, vm_memattr_t memattr)
1879 struct spglist deferred_vdrop_list;
1880 vm_page_t m, m_tmp, m_ret;
1884 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1885 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1886 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1887 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1888 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1890 if (object != NULL) {
1891 VM_OBJECT_ASSERT_WLOCKED(object);
1892 KASSERT(object->type == OBJT_PHYS,
1893 ("vm_page_alloc_contig: object %p isn't OBJT_PHYS",
1896 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1897 req_class = req & VM_ALLOC_CLASS_MASK;
1900 * The page daemon is allowed to dig deeper into the free page list.
1902 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1903 req_class = VM_ALLOC_SYSTEM;
1905 SLIST_INIT(&deferred_vdrop_list);
1906 mtx_lock(&vm_page_queue_free_mtx);
1907 if (vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1908 vm_cnt.v_free_reserved || (req_class == VM_ALLOC_SYSTEM &&
1909 vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1910 vm_cnt.v_interrupt_free_min) || (req_class == VM_ALLOC_INTERRUPT &&
1911 vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages)) {
1912 #if VM_NRESERVLEVEL > 0
1914 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1915 (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1916 low, high, alignment, boundary)) == NULL)
1918 m_ret = vm_phys_alloc_contig(npages, low, high,
1919 alignment, boundary);
1921 mtx_unlock(&vm_page_queue_free_mtx);
1922 atomic_add_int(&vm_pageout_deficit, npages);
1923 pagedaemon_wakeup();
1927 for (m = m_ret; m < &m_ret[npages]; m++) {
1928 drop = vm_page_alloc_init(m);
1931 * Enqueue the vnode for deferred vdrop().
1933 m->plinks.s.pv = drop;
1934 SLIST_INSERT_HEAD(&deferred_vdrop_list, m,
1939 #if VM_NRESERVLEVEL > 0
1940 if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1945 mtx_unlock(&vm_page_queue_free_mtx);
1950 * Initialize the pages. Only the PG_ZERO flag is inherited.
1953 if ((req & VM_ALLOC_ZERO) != 0)
1955 if ((req & VM_ALLOC_NODUMP) != 0)
1957 if ((req & VM_ALLOC_WIRED) != 0)
1958 atomic_add_int(&vm_cnt.v_wire_count, npages);
1959 if (object != NULL) {
1960 if (object->memattr != VM_MEMATTR_DEFAULT &&
1961 memattr == VM_MEMATTR_DEFAULT)
1962 memattr = object->memattr;
1964 for (m = m_ret; m < &m_ret[npages]; m++) {
1966 m->flags = (m->flags | PG_NODUMP) & flags;
1967 m->busy_lock = VPB_UNBUSIED;
1968 if (object != NULL) {
1969 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
1970 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1971 if ((req & VM_ALLOC_SBUSY) != 0)
1972 m->busy_lock = VPB_SHARERS_WORD(1);
1974 if ((req & VM_ALLOC_WIRED) != 0)
1976 /* Unmanaged pages don't use "act_count". */
1977 m->oflags = VPO_UNMANAGED;
1978 if (object != NULL) {
1979 if (vm_page_insert(m, object, pindex)) {
1980 vm_page_alloc_contig_vdrop(
1981 &deferred_vdrop_list);
1982 if (vm_paging_needed())
1983 pagedaemon_wakeup();
1984 if ((req & VM_ALLOC_WIRED) != 0)
1985 atomic_subtract_int(&vm_cnt.v_wire_count,
1987 for (m_tmp = m, m = m_ret;
1988 m < &m_ret[npages]; m++) {
1989 if ((req & VM_ALLOC_WIRED) != 0)
1993 m->oflags |= VPO_UNMANAGED;
1995 m->busy_lock = VPB_UNBUSIED;
2002 if (memattr != VM_MEMATTR_DEFAULT)
2003 pmap_page_set_memattr(m, memattr);
2006 vm_page_alloc_contig_vdrop(&deferred_vdrop_list);
2007 if (vm_paging_needed())
2008 pagedaemon_wakeup();
2013 * Initialize a page that has been freshly dequeued from a freelist.
2014 * The caller has to drop the vnode returned, if it is not NULL.
2016 * This function may only be used to initialize unmanaged pages.
2018 * To be called with vm_page_queue_free_mtx held.
2020 static struct vnode *
2021 vm_page_alloc_init(vm_page_t m)
2024 vm_object_t m_object;
2026 KASSERT(m->queue == PQ_NONE,
2027 ("vm_page_alloc_init: page %p has unexpected queue %d",
2029 KASSERT(m->wire_count == 0,
2030 ("vm_page_alloc_init: page %p is wired", m));
2031 KASSERT(m->hold_count == 0,
2032 ("vm_page_alloc_init: page %p is held", m));
2033 KASSERT(!vm_page_busied(m),
2034 ("vm_page_alloc_init: page %p is busy", m));
2035 KASSERT(m->dirty == 0,
2036 ("vm_page_alloc_init: page %p is dirty", m));
2037 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2038 ("vm_page_alloc_init: page %p has unexpected memattr %d",
2039 m, pmap_page_get_memattr(m)));
2040 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2042 if ((m->flags & PG_CACHED) != 0) {
2043 KASSERT((m->flags & PG_ZERO) == 0,
2044 ("vm_page_alloc_init: cached page %p is PG_ZERO", m));
2046 m_object = m->object;
2047 vm_page_cache_remove(m);
2048 if (m_object->type == OBJT_VNODE &&
2049 vm_object_cache_is_empty(m_object))
2050 drop = m_object->handle;
2052 KASSERT(m->valid == 0,
2053 ("vm_page_alloc_init: free page %p is valid", m));
2054 vm_phys_freecnt_adj(m, -1);
2055 if ((m->flags & PG_ZERO) != 0)
2056 vm_page_zero_count--;
2062 * vm_page_alloc_freelist:
2064 * Allocate a physical page from the specified free page list.
2066 * The caller must always specify an allocation class.
2068 * allocation classes:
2069 * VM_ALLOC_NORMAL normal process request
2070 * VM_ALLOC_SYSTEM system *really* needs a page
2071 * VM_ALLOC_INTERRUPT interrupt time request
2073 * optional allocation flags:
2074 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2075 * intends to allocate
2076 * VM_ALLOC_WIRED wire the allocated page
2077 * VM_ALLOC_ZERO prefer a zeroed page
2079 * This routine may not sleep.
2082 vm_page_alloc_freelist(int flind, int req)
2089 req_class = req & VM_ALLOC_CLASS_MASK;
2092 * The page daemon is allowed to dig deeper into the free page list.
2094 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2095 req_class = VM_ALLOC_SYSTEM;
2098 * Do not allocate reserved pages unless the req has asked for it.
2100 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
2101 if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
2102 (req_class == VM_ALLOC_SYSTEM &&
2103 vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
2104 (req_class == VM_ALLOC_INTERRUPT &&
2105 vm_cnt.v_free_count + vm_cnt.v_cache_count > 0))
2106 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
2108 mtx_unlock(&vm_page_queue_free_mtx);
2109 atomic_add_int(&vm_pageout_deficit,
2110 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
2111 pagedaemon_wakeup();
2115 mtx_unlock(&vm_page_queue_free_mtx);
2118 drop = vm_page_alloc_init(m);
2119 mtx_unlock(&vm_page_queue_free_mtx);
2122 * Initialize the page. Only the PG_ZERO flag is inherited.
2126 if ((req & VM_ALLOC_ZERO) != 0)
2129 if ((req & VM_ALLOC_WIRED) != 0) {
2131 * The page lock is not required for wiring a page that does
2132 * not belong to an object.
2134 atomic_add_int(&vm_cnt.v_wire_count, 1);
2137 /* Unmanaged pages don't use "act_count". */
2138 m->oflags = VPO_UNMANAGED;
2141 if (vm_paging_needed())
2142 pagedaemon_wakeup();
2146 #define VPSC_ANY 0 /* No restrictions. */
2147 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2148 #define VPSC_NOSUPER 2 /* Skip superpages. */
2151 * vm_page_scan_contig:
2153 * Scan vm_page_array[] between the specified entries "m_start" and
2154 * "m_end" for a run of contiguous physical pages that satisfy the
2155 * specified conditions, and return the lowest page in the run. The
2156 * specified "alignment" determines the alignment of the lowest physical
2157 * page in the run. If the specified "boundary" is non-zero, then the
2158 * run of physical pages cannot span a physical address that is a
2159 * multiple of "boundary".
2161 * "m_end" is never dereferenced, so it need not point to a vm_page
2162 * structure within vm_page_array[].
2164 * "npages" must be greater than zero. "m_start" and "m_end" must not
2165 * span a hole (or discontiguity) in the physical address space. Both
2166 * "alignment" and "boundary" must be a power of two.
2169 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2170 u_long alignment, vm_paddr_t boundary, int options)
2172 struct mtx *m_mtx, *new_mtx;
2176 #if VM_NRESERVLEVEL > 0
2179 int m_inc, order, run_ext, run_len;
2181 KASSERT(npages > 0, ("npages is 0"));
2182 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2183 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2187 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2188 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2189 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2192 * If the current page would be the start of a run, check its
2193 * physical address against the end, alignment, and boundary
2194 * conditions. If it doesn't satisfy these conditions, either
2195 * terminate the scan or advance to the next page that
2196 * satisfies the failed condition.
2199 KASSERT(m_run == NULL, ("m_run != NULL"));
2200 if (m + npages > m_end)
2202 pa = VM_PAGE_TO_PHYS(m);
2203 if ((pa & (alignment - 1)) != 0) {
2204 m_inc = atop(roundup2(pa, alignment) - pa);
2207 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2209 m_inc = atop(roundup2(pa, boundary) - pa);
2213 KASSERT(m_run != NULL, ("m_run == NULL"));
2216 * Avoid releasing and reacquiring the same page lock.
2218 new_mtx = vm_page_lockptr(m);
2219 if (m_mtx != new_mtx) {
2227 if (m->wire_count != 0 || m->hold_count != 0)
2229 #if VM_NRESERVLEVEL > 0
2230 else if ((level = vm_reserv_level(m)) >= 0 &&
2231 (options & VPSC_NORESERV) != 0) {
2233 /* Advance to the end of the reservation. */
2234 pa = VM_PAGE_TO_PHYS(m);
2235 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2239 else if ((object = m->object) != NULL) {
2241 * The page is considered eligible for relocation if
2242 * and only if it could be laundered or reclaimed by
2245 if (!VM_OBJECT_TRYRLOCK(object)) {
2247 VM_OBJECT_RLOCK(object);
2249 if (m->object != object) {
2251 * The page may have been freed.
2253 VM_OBJECT_RUNLOCK(object);
2255 } else if (m->wire_count != 0 ||
2256 m->hold_count != 0) {
2261 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2262 ("page %p is PG_UNHOLDFREE", m));
2263 /* Don't care: PG_NODUMP, PG_WINATCFLS, PG_ZERO. */
2264 if (object->type != OBJT_DEFAULT &&
2265 object->type != OBJT_SWAP &&
2266 object->type != OBJT_VNODE)
2268 else if ((m->flags & PG_CACHED) != 0 ||
2269 m != vm_page_lookup(object, m->pindex)) {
2271 * The page is cached or recently converted
2272 * from cached to free.
2274 #if VM_NRESERVLEVEL > 0
2277 * The page is reserved. Extend the
2278 * current run by one page.
2283 if ((order = m->order) < VM_NFREEORDER) {
2285 * The page is enqueued in the
2286 * physical memory allocator's cache/
2287 * free page queues. Moreover, it is
2288 * the first page in a power-of-two-
2289 * sized run of contiguous cache/free
2290 * pages. Add these pages to the end
2291 * of the current run, and jump
2294 run_ext = 1 << order;
2298 #if VM_NRESERVLEVEL > 0
2299 } else if ((options & VPSC_NOSUPER) != 0 &&
2300 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2302 /* Advance to the end of the superpage. */
2303 pa = VM_PAGE_TO_PHYS(m);
2304 m_inc = atop(roundup2(pa + 1,
2305 vm_reserv_size(level)) - pa);
2307 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2308 m->queue != PQ_NONE && !vm_page_busied(m)) {
2310 * The page is allocated but eligible for
2311 * relocation. Extend the current run by one
2314 KASSERT(pmap_page_get_memattr(m) ==
2316 ("page %p has an unexpected memattr", m));
2317 KASSERT((m->oflags & (VPO_SWAPINPROG |
2318 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2319 ("page %p has unexpected oflags", m));
2320 /* Don't care: VPO_NOSYNC. */
2325 VM_OBJECT_RUNLOCK(object);
2326 #if VM_NRESERVLEVEL > 0
2327 } else if (level >= 0) {
2329 * The page is reserved but not yet allocated. In
2330 * other words, it is still cached or free. Extend
2331 * the current run by one page.
2335 } else if ((order = m->order) < VM_NFREEORDER) {
2337 * The page is enqueued in the physical memory
2338 * allocator's cache/free page queues. Moreover, it
2339 * is the first page in a power-of-two-sized run of
2340 * contiguous cache/free pages. Add these pages to
2341 * the end of the current run, and jump ahead.
2343 run_ext = 1 << order;
2347 * Skip the page for one of the following reasons: (1)
2348 * It is enqueued in the physical memory allocator's
2349 * cache/free page queues. However, it is not the
2350 * first page in a run of contiguous cache/free pages.
2351 * (This case rarely occurs because the scan is
2352 * performed in ascending order.) (2) It is not
2353 * reserved, and it is transitioning from free to
2354 * allocated. (Conversely, the transition from
2355 * allocated to free for managed pages is blocked by
2356 * the page lock.) (3) It is allocated but not
2357 * contained by an object and not wired, e.g.,
2358 * allocated by Xen's balloon driver.
2364 * Extend or reset the current run of pages.
2379 if (run_len >= npages)
2385 * vm_page_reclaim_run:
2387 * Try to relocate each of the allocated virtual pages within the
2388 * specified run of physical pages to a new physical address. Free the
2389 * physical pages underlying the relocated virtual pages. A virtual page
2390 * is relocatable if and only if it could be laundered or reclaimed by
2391 * the page daemon. Whenever possible, a virtual page is relocated to a
2392 * physical address above "high".
2394 * Returns 0 if every physical page within the run was already free or
2395 * just freed by a successful relocation. Otherwise, returns a non-zero
2396 * value indicating why the last attempt to relocate a virtual page was
2399 * "req_class" must be an allocation class.
2402 vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
2405 struct mtx *m_mtx, *new_mtx;
2406 struct spglist free;
2409 vm_page_t m, m_end, m_new;
2410 int error, order, req;
2412 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2413 ("req_class is not an allocation class"));
2417 m_end = m_run + npages;
2419 for (; error == 0 && m < m_end; m++) {
2420 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2421 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2424 * Avoid releasing and reacquiring the same page lock.
2426 new_mtx = vm_page_lockptr(m);
2427 if (m_mtx != new_mtx) {
2434 if (m->wire_count != 0 || m->hold_count != 0)
2436 else if ((object = m->object) != NULL) {
2438 * The page is relocated if and only if it could be
2439 * laundered or reclaimed by the page daemon.
2441 if (!VM_OBJECT_TRYWLOCK(object)) {
2443 VM_OBJECT_WLOCK(object);
2445 if (m->object != object) {
2447 * The page may have been freed.
2449 VM_OBJECT_WUNLOCK(object);
2451 } else if (m->wire_count != 0 ||
2452 m->hold_count != 0) {
2457 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2458 ("page %p is PG_UNHOLDFREE", m));
2459 /* Don't care: PG_NODUMP, PG_WINATCFLS, PG_ZERO. */
2460 if (object->type != OBJT_DEFAULT &&
2461 object->type != OBJT_SWAP &&
2462 object->type != OBJT_VNODE)
2464 else if ((m->flags & PG_CACHED) != 0 ||
2465 m != vm_page_lookup(object, m->pindex)) {
2467 * The page is cached or recently converted
2468 * from cached to free.
2470 VM_OBJECT_WUNLOCK(object);
2472 } else if (object->memattr != VM_MEMATTR_DEFAULT)
2474 else if (m->queue != PQ_NONE && !vm_page_busied(m)) {
2475 KASSERT(pmap_page_get_memattr(m) ==
2477 ("page %p has an unexpected memattr", m));
2478 KASSERT((m->oflags & (VPO_SWAPINPROG |
2479 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2480 ("page %p has unexpected oflags", m));
2481 /* Don't care: VPO_NOSYNC. */
2482 if (m->valid != 0) {
2484 * First, try to allocate a new page
2485 * that is above "high". Failing
2486 * that, try to allocate a new page
2487 * that is below "m_run". Allocate
2488 * the new page between the end of
2489 * "m_run" and "high" only as a last
2492 req = req_class | VM_ALLOC_NOOBJ;
2493 if ((m->flags & PG_NODUMP) != 0)
2494 req |= VM_ALLOC_NODUMP;
2495 if (trunc_page(high) !=
2496 ~(vm_paddr_t)PAGE_MASK) {
2497 m_new = vm_page_alloc_contig(
2502 VM_MEMATTR_DEFAULT);
2505 if (m_new == NULL) {
2506 pa = VM_PAGE_TO_PHYS(m_run);
2507 m_new = vm_page_alloc_contig(
2509 0, pa - 1, PAGE_SIZE, 0,
2510 VM_MEMATTR_DEFAULT);
2512 if (m_new == NULL) {
2514 m_new = vm_page_alloc_contig(
2516 pa, high, PAGE_SIZE, 0,
2517 VM_MEMATTR_DEFAULT);
2519 if (m_new == NULL) {
2523 KASSERT(m_new->wire_count == 0,
2524 ("page %p is wired", m));
2527 * Replace "m" with the new page. For
2528 * vm_page_replace(), "m" must be busy
2529 * and dequeued. Finally, change "m"
2530 * as if vm_page_free() was called.
2532 if (object->ref_count != 0)
2534 m_new->aflags = m->aflags;
2535 KASSERT(m_new->oflags == VPO_UNMANAGED,
2536 ("page %p is managed", m));
2537 m_new->oflags = m->oflags & VPO_NOSYNC;
2538 pmap_copy_page(m, m_new);
2539 m_new->valid = m->valid;
2540 m_new->dirty = m->dirty;
2541 m->flags &= ~PG_ZERO;
2544 vm_page_replace_checked(m_new, object,
2550 * The new page must be deactivated
2551 * before the object is unlocked.
2553 new_mtx = vm_page_lockptr(m_new);
2554 if (m_mtx != new_mtx) {
2559 vm_page_deactivate(m_new);
2561 m->flags &= ~PG_ZERO;
2564 KASSERT(m->dirty == 0,
2565 ("page %p is dirty", m));
2567 SLIST_INSERT_HEAD(&free, m, plinks.s.ss);
2571 VM_OBJECT_WUNLOCK(object);
2574 mtx_lock(&vm_page_queue_free_mtx);
2576 if (order < VM_NFREEORDER) {
2578 * The page is enqueued in the physical memory
2579 * allocator's cache/free page queues.
2580 * Moreover, it is the first page in a power-
2581 * of-two-sized run of contiguous cache/free
2582 * pages. Jump ahead to the last page within
2583 * that run, and continue from there.
2585 m += (1 << order) - 1;
2587 #if VM_NRESERVLEVEL > 0
2588 else if (vm_reserv_is_page_free(m))
2591 mtx_unlock(&vm_page_queue_free_mtx);
2592 if (order == VM_NFREEORDER)
2598 if ((m = SLIST_FIRST(&free)) != NULL) {
2599 mtx_lock(&vm_page_queue_free_mtx);
2601 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2602 vm_phys_freecnt_adj(m, 1);
2603 #if VM_NRESERVLEVEL > 0
2604 if (!vm_reserv_free_page(m))
2608 vm_phys_free_pages(m, 0);
2609 } while ((m = SLIST_FIRST(&free)) != NULL);
2610 vm_page_zero_idle_wakeup();
2611 vm_page_free_wakeup();
2612 mtx_unlock(&vm_page_queue_free_mtx);
2619 CTASSERT(powerof2(NRUNS));
2621 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2623 #define MIN_RECLAIM 8
2626 * vm_page_reclaim_contig:
2628 * Reclaim allocated, contiguous physical memory satisfying the specified
2629 * conditions by relocating the virtual pages using that physical memory.
2630 * Returns true if reclamation is successful and false otherwise. Since
2631 * relocation requires the allocation of physical pages, reclamation may
2632 * fail due to a shortage of cache/free pages. When reclamation fails,
2633 * callers are expected to perform VM_WAIT before retrying a failed
2634 * allocation operation, e.g., vm_page_alloc_contig().
2636 * The caller must always specify an allocation class through "req".
2638 * allocation classes:
2639 * VM_ALLOC_NORMAL normal process request
2640 * VM_ALLOC_SYSTEM system *really* needs a page
2641 * VM_ALLOC_INTERRUPT interrupt time request
2643 * The optional allocation flags are ignored.
2645 * "npages" must be greater than zero. Both "alignment" and "boundary"
2646 * must be a power of two.
2649 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2650 u_long alignment, vm_paddr_t boundary)
2652 vm_paddr_t curr_low;
2653 vm_page_t m_run, m_runs[NRUNS];
2654 u_long count, reclaimed;
2655 int error, i, options, req_class;
2657 KASSERT(npages > 0, ("npages is 0"));
2658 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2659 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2660 req_class = req & VM_ALLOC_CLASS_MASK;
2663 * The page daemon is allowed to dig deeper into the free page list.
2665 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2666 req_class = VM_ALLOC_SYSTEM;
2669 * Return if the number of cached and free pages cannot satisfy the
2670 * requested allocation.
2672 count = vm_cnt.v_free_count + vm_cnt.v_cache_count;
2673 if (count < npages + vm_cnt.v_free_reserved || (count < npages +
2674 vm_cnt.v_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2675 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2679 * Scan up to three times, relaxing the restrictions ("options") on
2680 * the reclamation of reservations and superpages each time.
2682 for (options = VPSC_NORESERV;;) {
2684 * Find the highest runs that satisfy the given constraints
2685 * and restrictions, and record them in "m_runs".
2690 m_run = vm_phys_scan_contig(npages, curr_low, high,
2691 alignment, boundary, options);
2694 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2695 m_runs[RUN_INDEX(count)] = m_run;
2700 * Reclaim the highest runs in LIFO (descending) order until
2701 * the number of reclaimed pages, "reclaimed", is at least
2702 * MIN_RECLAIM. Reset "reclaimed" each time because each
2703 * reclamation is idempotent, and runs will (likely) recur
2704 * from one scan to the next as restrictions are relaxed.
2707 for (i = 0; count > 0 && i < NRUNS; i++) {
2709 m_run = m_runs[RUN_INDEX(count)];
2710 error = vm_page_reclaim_run(req_class, npages, m_run,
2713 reclaimed += npages;
2714 if (reclaimed >= MIN_RECLAIM)
2720 * Either relax the restrictions on the next scan or return if
2721 * the last scan had no restrictions.
2723 if (options == VPSC_NORESERV)
2724 options = VPSC_NOSUPER;
2725 else if (options == VPSC_NOSUPER)
2727 else if (options == VPSC_ANY)
2728 return (reclaimed != 0);
2733 * vm_wait: (also see VM_WAIT macro)
2735 * Sleep until free pages are available for allocation.
2736 * - Called in various places before memory allocations.
2742 mtx_lock(&vm_page_queue_free_mtx);
2743 if (curproc == pageproc) {
2744 vm_pageout_pages_needed = 1;
2745 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
2746 PDROP | PSWP, "VMWait", 0);
2748 if (!vm_pageout_wanted) {
2749 vm_pageout_wanted = true;
2750 wakeup(&vm_pageout_wanted);
2752 vm_pages_needed = true;
2753 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
2759 * vm_waitpfault: (also see VM_WAITPFAULT macro)
2761 * Sleep until free pages are available for allocation.
2762 * - Called only in vm_fault so that processes page faulting
2763 * can be easily tracked.
2764 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2765 * processes will be able to grab memory first. Do not change
2766 * this balance without careful testing first.
2772 mtx_lock(&vm_page_queue_free_mtx);
2773 if (!vm_pageout_wanted) {
2774 vm_pageout_wanted = true;
2775 wakeup(&vm_pageout_wanted);
2777 vm_pages_needed = true;
2778 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
2782 struct vm_pagequeue *
2783 vm_page_pagequeue(vm_page_t m)
2786 return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2792 * Remove the given page from its current page queue.
2794 * The page must be locked.
2797 vm_page_dequeue(vm_page_t m)
2799 struct vm_pagequeue *pq;
2801 vm_page_assert_locked(m);
2802 KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
2804 pq = vm_page_pagequeue(m);
2805 vm_pagequeue_lock(pq);
2807 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2808 vm_pagequeue_cnt_dec(pq);
2809 vm_pagequeue_unlock(pq);
2813 * vm_page_dequeue_locked:
2815 * Remove the given page from its current page queue.
2817 * The page and page queue must be locked.
2820 vm_page_dequeue_locked(vm_page_t m)
2822 struct vm_pagequeue *pq;
2824 vm_page_lock_assert(m, MA_OWNED);
2825 pq = vm_page_pagequeue(m);
2826 vm_pagequeue_assert_locked(pq);
2828 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2829 vm_pagequeue_cnt_dec(pq);
2835 * Add the given page to the specified page queue.
2837 * The page must be locked.
2840 vm_page_enqueue(uint8_t queue, vm_page_t m)
2842 struct vm_pagequeue *pq;
2844 vm_page_lock_assert(m, MA_OWNED);
2845 KASSERT(queue < PQ_COUNT,
2846 ("vm_page_enqueue: invalid queue %u request for page %p",
2848 pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2849 vm_pagequeue_lock(pq);
2851 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2852 vm_pagequeue_cnt_inc(pq);
2853 vm_pagequeue_unlock(pq);
2859 * Move the given page to the tail of its current page queue.
2861 * The page must be locked.
2864 vm_page_requeue(vm_page_t m)
2866 struct vm_pagequeue *pq;
2868 vm_page_lock_assert(m, MA_OWNED);
2869 KASSERT(m->queue != PQ_NONE,
2870 ("vm_page_requeue: page %p is not queued", m));
2871 pq = vm_page_pagequeue(m);
2872 vm_pagequeue_lock(pq);
2873 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2874 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2875 vm_pagequeue_unlock(pq);
2879 * vm_page_requeue_locked:
2881 * Move the given page to the tail of its current page queue.
2883 * The page queue must be locked.
2886 vm_page_requeue_locked(vm_page_t m)
2888 struct vm_pagequeue *pq;
2890 KASSERT(m->queue != PQ_NONE,
2891 ("vm_page_requeue_locked: page %p is not queued", m));
2892 pq = vm_page_pagequeue(m);
2893 vm_pagequeue_assert_locked(pq);
2894 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2895 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2901 * Put the specified page on the active list (if appropriate).
2902 * Ensure that act_count is at least ACT_INIT but do not otherwise
2905 * The page must be locked.
2908 vm_page_activate(vm_page_t m)
2912 vm_page_lock_assert(m, MA_OWNED);
2913 if ((queue = m->queue) != PQ_ACTIVE) {
2914 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2915 if (m->act_count < ACT_INIT)
2916 m->act_count = ACT_INIT;
2917 if (queue != PQ_NONE)
2919 vm_page_enqueue(PQ_ACTIVE, m);
2921 KASSERT(queue == PQ_NONE,
2922 ("vm_page_activate: wired page %p is queued", m));
2924 if (m->act_count < ACT_INIT)
2925 m->act_count = ACT_INIT;
2930 * vm_page_free_wakeup:
2932 * Helper routine for vm_page_free_toq() and vm_page_cache(). This
2933 * routine is called when a page has been added to the cache or free
2936 * The page queues must be locked.
2939 vm_page_free_wakeup(void)
2942 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2944 * if pageout daemon needs pages, then tell it that there are
2947 if (vm_pageout_pages_needed &&
2948 vm_cnt.v_cache_count + vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
2949 wakeup(&vm_pageout_pages_needed);
2950 vm_pageout_pages_needed = 0;
2953 * wakeup processes that are waiting on memory if we hit a
2954 * high water mark. And wakeup scheduler process if we have
2955 * lots of memory. this process will swapin processes.
2957 if (vm_pages_needed && !vm_page_count_min()) {
2958 vm_pages_needed = false;
2959 wakeup(&vm_cnt.v_free_count);
2964 * Turn a cached page into a free page, by changing its attributes.
2965 * Keep the statistics up-to-date.
2967 * The free page queue must be locked.
2970 vm_page_cache_turn_free(vm_page_t m)
2973 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2977 KASSERT((m->flags & PG_CACHED) != 0,
2978 ("vm_page_cache_turn_free: page %p is not cached", m));
2979 m->flags &= ~PG_CACHED;
2980 vm_cnt.v_cache_count--;
2981 vm_phys_freecnt_adj(m, 1);
2987 * Returns the given page to the free list,
2988 * disassociating it with any VM object.
2990 * The object must be locked. The page must be locked if it is managed.
2993 vm_page_free_toq(vm_page_t m)
2996 if ((m->oflags & VPO_UNMANAGED) == 0) {
2997 vm_page_lock_assert(m, MA_OWNED);
2998 KASSERT(!pmap_page_is_mapped(m),
2999 ("vm_page_free_toq: freeing mapped page %p", m));
3001 KASSERT(m->queue == PQ_NONE,
3002 ("vm_page_free_toq: unmanaged page %p is queued", m));
3003 PCPU_INC(cnt.v_tfree);
3005 if (vm_page_sbusied(m))
3006 panic("vm_page_free: freeing busy page %p", m);
3009 * Unqueue, then remove page. Note that we cannot destroy
3010 * the page here because we do not want to call the pager's
3011 * callback routine until after we've put the page on the
3012 * appropriate free queue.
3018 * If fictitious remove object association and
3019 * return, otherwise delay object association removal.
3021 if ((m->flags & PG_FICTITIOUS) != 0) {
3028 if (m->wire_count != 0)
3029 panic("vm_page_free: freeing wired page %p", m);
3030 if (m->hold_count != 0) {
3031 m->flags &= ~PG_ZERO;
3032 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
3033 ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
3034 m->flags |= PG_UNHOLDFREE;
3037 * Restore the default memory attribute to the page.
3039 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3040 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3043 * Insert the page into the physical memory allocator's
3044 * cache/free page queues.
3046 mtx_lock(&vm_page_queue_free_mtx);
3047 vm_phys_freecnt_adj(m, 1);
3048 #if VM_NRESERVLEVEL > 0
3049 if (!vm_reserv_free_page(m))
3053 vm_phys_free_pages(m, 0);
3054 if ((m->flags & PG_ZERO) != 0)
3055 ++vm_page_zero_count;
3057 vm_page_zero_idle_wakeup();
3058 vm_page_free_wakeup();
3059 mtx_unlock(&vm_page_queue_free_mtx);
3066 * Mark this page as wired down by yet
3067 * another map, removing it from paging queues
3070 * If the page is fictitious, then its wire count must remain one.
3072 * The page must be locked.
3075 vm_page_wire(vm_page_t m)
3079 * Only bump the wire statistics if the page is not already wired,
3080 * and only unqueue the page if it is on some queue (if it is unmanaged
3081 * it is already off the queues).
3083 vm_page_lock_assert(m, MA_OWNED);
3084 if ((m->flags & PG_FICTITIOUS) != 0) {
3085 KASSERT(m->wire_count == 1,
3086 ("vm_page_wire: fictitious page %p's wire count isn't one",
3090 if (m->wire_count == 0) {
3091 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
3092 m->queue == PQ_NONE,
3093 ("vm_page_wire: unmanaged page %p is queued", m));
3095 atomic_add_int(&vm_cnt.v_wire_count, 1);
3098 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
3104 * Release one wiring of the specified page, potentially allowing it to be
3105 * paged out. Returns TRUE if the number of wirings transitions to zero and
3108 * Only managed pages belonging to an object can be paged out. If the number
3109 * of wirings transitions to zero and the page is eligible for page out, then
3110 * the page is added to the specified paging queue (unless PQ_NONE is
3113 * If a page is fictitious, then its wire count must always be one.
3115 * A managed page must be locked.
3118 vm_page_unwire(vm_page_t m, uint8_t queue)
3121 KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
3122 ("vm_page_unwire: invalid queue %u request for page %p",
3124 if ((m->oflags & VPO_UNMANAGED) == 0)
3125 vm_page_assert_locked(m);
3126 if ((m->flags & PG_FICTITIOUS) != 0) {
3127 KASSERT(m->wire_count == 1,
3128 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
3131 if (m->wire_count > 0) {
3133 if (m->wire_count == 0) {
3134 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3135 if ((m->oflags & VPO_UNMANAGED) == 0 &&
3136 m->object != NULL && queue != PQ_NONE) {
3137 if (queue == PQ_INACTIVE)
3138 m->flags &= ~PG_WINATCFLS;
3139 vm_page_enqueue(queue, m);
3145 panic("vm_page_unwire: page %p's wire count is zero", m);
3149 * Move the specified page to the inactive queue.
3151 * Many pages placed on the inactive queue should actually go
3152 * into the cache, but it is difficult to figure out which. What
3153 * we do instead, if the inactive target is well met, is to put
3154 * clean pages at the head of the inactive queue instead of the tail.
3155 * This will cause them to be moved to the cache more quickly and
3156 * if not actively re-referenced, reclaimed more quickly. If we just
3157 * stick these pages at the end of the inactive queue, heavy filesystem
3158 * meta-data accesses can cause an unnecessary paging load on memory bound
3159 * processes. This optimization causes one-time-use metadata to be
3160 * reused more quickly.
3162 * Normally noreuse is FALSE, resulting in LRU operation. noreuse is set
3163 * to TRUE if we want this page to be 'as if it were placed in the cache',
3164 * except without unmapping it from the process address space. In
3165 * practice this is implemented by inserting the page at the head of the
3166 * queue, using a marker page to guide FIFO insertion ordering.
3168 * The page must be locked.
3171 _vm_page_deactivate(vm_page_t m, boolean_t noreuse)
3173 struct vm_pagequeue *pq;
3176 vm_page_assert_locked(m);
3179 * Ignore if the page is already inactive, unless it is unlikely to be
3182 if ((queue = m->queue) == PQ_INACTIVE && !noreuse)
3184 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
3185 pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
3186 /* Avoid multiple acquisitions of the inactive queue lock. */
3187 if (queue == PQ_INACTIVE) {
3188 vm_pagequeue_lock(pq);
3189 vm_page_dequeue_locked(m);
3191 if (queue != PQ_NONE)
3193 m->flags &= ~PG_WINATCFLS;
3194 vm_pagequeue_lock(pq);
3196 m->queue = PQ_INACTIVE;
3198 TAILQ_INSERT_BEFORE(&vm_phys_domain(m)->vmd_inacthead,
3201 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3202 vm_pagequeue_cnt_inc(pq);
3203 vm_pagequeue_unlock(pq);
3208 * Move the specified page to the inactive queue.
3210 * The page must be locked.
3213 vm_page_deactivate(vm_page_t m)
3216 _vm_page_deactivate(m, FALSE);
3220 * Move the specified page to the inactive queue with the expectation
3221 * that it is unlikely to be reused.
3223 * The page must be locked.
3226 vm_page_deactivate_noreuse(vm_page_t m)
3229 _vm_page_deactivate(m, TRUE);
3233 * vm_page_try_to_cache:
3235 * Returns 0 on failure, 1 on success
3238 vm_page_try_to_cache(vm_page_t m)
3241 vm_page_lock_assert(m, MA_OWNED);
3242 VM_OBJECT_ASSERT_WLOCKED(m->object);
3243 if (m->dirty || m->hold_count || m->wire_count ||
3244 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
3254 * vm_page_try_to_free()
3256 * Attempt to free the page. If we cannot free it, we do nothing.
3257 * 1 is returned on success, 0 on failure.
3260 vm_page_try_to_free(vm_page_t m)
3263 vm_page_lock_assert(m, MA_OWNED);
3264 if (m->object != NULL)
3265 VM_OBJECT_ASSERT_WLOCKED(m->object);
3266 if (m->dirty || m->hold_count || m->wire_count ||
3267 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
3279 * Put the specified page onto the page cache queue (if appropriate).
3281 * The object and page must be locked.
3284 vm_page_cache(vm_page_t m)
3287 boolean_t cache_was_empty;
3289 vm_page_lock_assert(m, MA_OWNED);
3291 VM_OBJECT_ASSERT_WLOCKED(object);
3292 if (vm_page_busied(m) || (m->oflags & VPO_UNMANAGED) ||
3293 m->hold_count || m->wire_count)
3294 panic("vm_page_cache: attempting to cache busy page");
3295 KASSERT(!pmap_page_is_mapped(m),
3296 ("vm_page_cache: page %p is mapped", m));
3297 KASSERT(m->dirty == 0, ("vm_page_cache: page %p is dirty", m));
3298 if (m->valid == 0 || object->type == OBJT_DEFAULT ||
3299 (object->type == OBJT_SWAP &&
3300 !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
3302 * Hypothesis: A cache-eligible page belonging to a
3303 * default object or swap object but without a backing
3304 * store must be zero filled.
3309 KASSERT((m->flags & PG_CACHED) == 0,
3310 ("vm_page_cache: page %p is already cached", m));
3313 * Remove the page from the paging queues.
3318 * Remove the page from the object's collection of resident
3321 vm_radix_remove(&object->rtree, m->pindex);
3322 TAILQ_REMOVE(&object->memq, m, listq);
3323 object->resident_page_count--;
3326 * Restore the default memory attribute to the page.
3328 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3329 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3332 * Insert the page into the object's collection of cached pages
3333 * and the physical memory allocator's cache/free page queues.
3335 m->flags &= ~PG_ZERO;
3336 mtx_lock(&vm_page_queue_free_mtx);
3337 cache_was_empty = vm_radix_is_empty(&object->cache);
3338 if (vm_radix_insert(&object->cache, m)) {
3339 mtx_unlock(&vm_page_queue_free_mtx);
3340 if (object->type == OBJT_VNODE &&
3341 object->resident_page_count == 0)
3342 vdrop(object->handle);
3349 * The above call to vm_radix_insert() could reclaim the one pre-
3350 * existing cached page from this object, resulting in a call to
3353 if (!cache_was_empty)
3354 cache_was_empty = vm_radix_is_singleton(&object->cache);
3356 m->flags |= PG_CACHED;
3357 vm_cnt.v_cache_count++;
3358 PCPU_INC(cnt.v_tcached);
3359 #if VM_NRESERVLEVEL > 0
3360 if (!vm_reserv_free_page(m)) {
3364 vm_phys_free_pages(m, 0);
3366 vm_page_free_wakeup();
3367 mtx_unlock(&vm_page_queue_free_mtx);
3370 * Increment the vnode's hold count if this is the object's only
3371 * cached page. Decrement the vnode's hold count if this was
3372 * the object's only resident page.
3374 if (object->type == OBJT_VNODE) {
3375 if (cache_was_empty && object->resident_page_count != 0)
3376 vhold(object->handle);
3377 else if (!cache_was_empty && object->resident_page_count == 0)
3378 vdrop(object->handle);
3385 * Deactivate or do nothing, as appropriate.
3387 * The object and page must be locked.
3390 vm_page_advise(vm_page_t m, int advice)
3393 vm_page_assert_locked(m);
3394 VM_OBJECT_ASSERT_WLOCKED(m->object);
3395 if (advice == MADV_FREE)
3397 * Mark the page clean. This will allow the page to be freed
3398 * up by the system. However, such pages are often reused
3399 * quickly by malloc() so we do not do anything that would
3400 * cause a page fault if we can help it.
3402 * Specifically, we do not try to actually free the page now
3403 * nor do we try to put it in the cache (which would cause a
3404 * page fault on reuse).
3406 * But we do make the page as freeable as we can without
3407 * actually taking the step of unmapping it.
3410 else if (advice != MADV_DONTNEED)
3414 * Clear any references to the page. Otherwise, the page daemon will
3415 * immediately reactivate the page.
3417 vm_page_aflag_clear(m, PGA_REFERENCED);
3419 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3423 * Place clean pages near the head of the inactive queue rather than
3424 * the tail, thus defeating the queue's LRU operation and ensuring that
3425 * the page will be reused quickly. Dirty pages are given a chance to
3426 * cycle once through the inactive queue before becoming eligible for
3429 _vm_page_deactivate(m, m->dirty == 0);
3433 * Grab a page, waiting until we are waken up due to the page
3434 * changing state. We keep on waiting, if the page continues
3435 * to be in the object. If the page doesn't exist, first allocate it
3436 * and then conditionally zero it.
3438 * This routine may sleep.
3440 * The object must be locked on entry. The lock will, however, be released
3441 * and reacquired if the routine sleeps.
3444 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3449 VM_OBJECT_ASSERT_WLOCKED(object);
3450 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3451 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3452 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3454 if ((m = vm_page_lookup(object, pindex)) != NULL) {
3455 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3456 vm_page_xbusied(m) : vm_page_busied(m);
3458 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3461 * Reference the page before unlocking and
3462 * sleeping so that the page daemon is less
3463 * likely to reclaim it.
3465 vm_page_aflag_set(m, PGA_REFERENCED);
3467 VM_OBJECT_WUNLOCK(object);
3468 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
3469 VM_ALLOC_IGN_SBUSY) != 0);
3470 VM_OBJECT_WLOCK(object);
3473 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3479 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3481 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3486 m = vm_page_alloc(object, pindex, allocflags);
3488 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3490 VM_OBJECT_WUNLOCK(object);
3492 VM_OBJECT_WLOCK(object);
3494 } else if (m->valid != 0)
3496 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3502 * Mapping function for valid or dirty bits in a page.
3504 * Inputs are required to range within a page.
3507 vm_page_bits(int base, int size)
3513 base + size <= PAGE_SIZE,
3514 ("vm_page_bits: illegal base/size %d/%d", base, size)
3517 if (size == 0) /* handle degenerate case */
3520 first_bit = base >> DEV_BSHIFT;
3521 last_bit = (base + size - 1) >> DEV_BSHIFT;
3523 return (((vm_page_bits_t)2 << last_bit) -
3524 ((vm_page_bits_t)1 << first_bit));
3528 * vm_page_set_valid_range:
3530 * Sets portions of a page valid. The arguments are expected
3531 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3532 * of any partial chunks touched by the range. The invalid portion of
3533 * such chunks will be zeroed.
3535 * (base + size) must be less then or equal to PAGE_SIZE.
3538 vm_page_set_valid_range(vm_page_t m, int base, int size)
3542 VM_OBJECT_ASSERT_WLOCKED(m->object);
3543 if (size == 0) /* handle degenerate case */
3547 * If the base is not DEV_BSIZE aligned and the valid
3548 * bit is clear, we have to zero out a portion of the
3551 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3552 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
3553 pmap_zero_page_area(m, frag, base - frag);
3556 * If the ending offset is not DEV_BSIZE aligned and the
3557 * valid bit is clear, we have to zero out a portion of
3560 endoff = base + size;
3561 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3562 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
3563 pmap_zero_page_area(m, endoff,
3564 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3567 * Assert that no previously invalid block that is now being validated
3570 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
3571 ("vm_page_set_valid_range: page %p is dirty", m));
3574 * Set valid bits inclusive of any overlap.
3576 m->valid |= vm_page_bits(base, size);
3580 * Clear the given bits from the specified page's dirty field.
3582 static __inline void
3583 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
3586 #if PAGE_SIZE < 16384
3591 * If the object is locked and the page is neither exclusive busy nor
3592 * write mapped, then the page's dirty field cannot possibly be
3593 * set by a concurrent pmap operation.
3595 VM_OBJECT_ASSERT_WLOCKED(m->object);
3596 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
3597 m->dirty &= ~pagebits;
3600 * The pmap layer can call vm_page_dirty() without
3601 * holding a distinguished lock. The combination of
3602 * the object's lock and an atomic operation suffice
3603 * to guarantee consistency of the page dirty field.
3605 * For PAGE_SIZE == 32768 case, compiler already
3606 * properly aligns the dirty field, so no forcible
3607 * alignment is needed. Only require existence of
3608 * atomic_clear_64 when page size is 32768.
3610 addr = (uintptr_t)&m->dirty;
3611 #if PAGE_SIZE == 32768
3612 atomic_clear_64((uint64_t *)addr, pagebits);
3613 #elif PAGE_SIZE == 16384
3614 atomic_clear_32((uint32_t *)addr, pagebits);
3615 #else /* PAGE_SIZE <= 8192 */
3617 * Use a trick to perform a 32-bit atomic on the
3618 * containing aligned word, to not depend on the existence
3619 * of atomic_clear_{8, 16}.
3621 shift = addr & (sizeof(uint32_t) - 1);
3622 #if BYTE_ORDER == BIG_ENDIAN
3623 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
3627 addr &= ~(sizeof(uint32_t) - 1);
3628 atomic_clear_32((uint32_t *)addr, pagebits << shift);
3629 #endif /* PAGE_SIZE */
3634 * vm_page_set_validclean:
3636 * Sets portions of a page valid and clean. The arguments are expected
3637 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3638 * of any partial chunks touched by the range. The invalid portion of
3639 * such chunks will be zero'd.
3641 * (base + size) must be less then or equal to PAGE_SIZE.
3644 vm_page_set_validclean(vm_page_t m, int base, int size)
3646 vm_page_bits_t oldvalid, pagebits;
3649 VM_OBJECT_ASSERT_WLOCKED(m->object);
3650 if (size == 0) /* handle degenerate case */
3654 * If the base is not DEV_BSIZE aligned and the valid
3655 * bit is clear, we have to zero out a portion of the
3658 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3659 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
3660 pmap_zero_page_area(m, frag, base - frag);
3663 * If the ending offset is not DEV_BSIZE aligned and the
3664 * valid bit is clear, we have to zero out a portion of
3667 endoff = base + size;
3668 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3669 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
3670 pmap_zero_page_area(m, endoff,
3671 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3674 * Set valid, clear dirty bits. If validating the entire
3675 * page we can safely clear the pmap modify bit. We also
3676 * use this opportunity to clear the VPO_NOSYNC flag. If a process
3677 * takes a write fault on a MAP_NOSYNC memory area the flag will
3680 * We set valid bits inclusive of any overlap, but we can only
3681 * clear dirty bits for DEV_BSIZE chunks that are fully within
3684 oldvalid = m->valid;
3685 pagebits = vm_page_bits(base, size);
3686 m->valid |= pagebits;
3688 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
3689 frag = DEV_BSIZE - frag;
3695 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
3697 if (base == 0 && size == PAGE_SIZE) {
3699 * The page can only be modified within the pmap if it is
3700 * mapped, and it can only be mapped if it was previously
3703 if (oldvalid == VM_PAGE_BITS_ALL)
3705 * Perform the pmap_clear_modify() first. Otherwise,
3706 * a concurrent pmap operation, such as
3707 * pmap_protect(), could clear a modification in the
3708 * pmap and set the dirty field on the page before
3709 * pmap_clear_modify() had begun and after the dirty
3710 * field was cleared here.
3712 pmap_clear_modify(m);
3714 m->oflags &= ~VPO_NOSYNC;
3715 } else if (oldvalid != VM_PAGE_BITS_ALL)
3716 m->dirty &= ~pagebits;
3718 vm_page_clear_dirty_mask(m, pagebits);
3722 vm_page_clear_dirty(vm_page_t m, int base, int size)
3725 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
3729 * vm_page_set_invalid:
3731 * Invalidates DEV_BSIZE'd chunks within a page. Both the
3732 * valid and dirty bits for the effected areas are cleared.
3735 vm_page_set_invalid(vm_page_t m, int base, int size)
3737 vm_page_bits_t bits;
3741 VM_OBJECT_ASSERT_WLOCKED(object);
3742 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
3743 size >= object->un_pager.vnp.vnp_size)
3744 bits = VM_PAGE_BITS_ALL;
3746 bits = vm_page_bits(base, size);
3747 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
3750 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3751 !pmap_page_is_mapped(m),
3752 ("vm_page_set_invalid: page %p is mapped", m));
3758 * vm_page_zero_invalid()
3760 * The kernel assumes that the invalid portions of a page contain
3761 * garbage, but such pages can be mapped into memory by user code.
3762 * When this occurs, we must zero out the non-valid portions of the
3763 * page so user code sees what it expects.
3765 * Pages are most often semi-valid when the end of a file is mapped
3766 * into memory and the file's size is not page aligned.
3769 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3774 VM_OBJECT_ASSERT_WLOCKED(m->object);
3776 * Scan the valid bits looking for invalid sections that
3777 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
3778 * valid bit may be set ) have already been zeroed by
3779 * vm_page_set_validclean().
3781 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3782 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3783 (m->valid & ((vm_page_bits_t)1 << i))) {
3785 pmap_zero_page_area(m,
3786 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3793 * setvalid is TRUE when we can safely set the zero'd areas
3794 * as being valid. We can do this if there are no cache consistancy
3795 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3798 m->valid = VM_PAGE_BITS_ALL;
3804 * Is (partial) page valid? Note that the case where size == 0
3805 * will return FALSE in the degenerate case where the page is
3806 * entirely invalid, and TRUE otherwise.
3809 vm_page_is_valid(vm_page_t m, int base, int size)
3811 vm_page_bits_t bits;
3813 VM_OBJECT_ASSERT_LOCKED(m->object);
3814 bits = vm_page_bits(base, size);
3815 return (m->valid != 0 && (m->valid & bits) == bits);
3819 * vm_page_ps_is_valid:
3821 * Returns TRUE if the entire (super)page is valid and FALSE otherwise.
3824 vm_page_ps_is_valid(vm_page_t m)
3828 VM_OBJECT_ASSERT_LOCKED(m->object);
3829 npages = atop(pagesizes[m->psind]);
3832 * The physically contiguous pages that make up a superpage, i.e., a
3833 * page with a page size index ("psind") greater than zero, will
3834 * occupy adjacent entries in vm_page_array[].
3836 for (i = 0; i < npages; i++) {
3837 if (m[i].valid != VM_PAGE_BITS_ALL)
3844 * Set the page's dirty bits if the page is modified.
3847 vm_page_test_dirty(vm_page_t m)
3850 VM_OBJECT_ASSERT_WLOCKED(m->object);
3851 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3856 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3859 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3863 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3866 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3870 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3873 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3876 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3878 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3881 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3885 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3888 mtx_assert_(vm_page_lockptr(m), a, file, line);
3894 vm_page_object_lock_assert(vm_page_t m)
3898 * Certain of the page's fields may only be modified by the
3899 * holder of the containing object's lock or the exclusive busy.
3900 * holder. Unfortunately, the holder of the write busy is
3901 * not recorded, and thus cannot be checked here.
3903 if (m->object != NULL && !vm_page_xbusied(m))
3904 VM_OBJECT_ASSERT_WLOCKED(m->object);
3908 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3911 if ((bits & PGA_WRITEABLE) == 0)
3915 * The PGA_WRITEABLE flag can only be set if the page is
3916 * managed, is exclusively busied or the object is locked.
3917 * Currently, this flag is only set by pmap_enter().
3919 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3920 ("PGA_WRITEABLE on unmanaged page"));
3921 if (!vm_page_xbusied(m))
3922 VM_OBJECT_ASSERT_LOCKED(m->object);
3926 #include "opt_ddb.h"
3928 #include <sys/kernel.h>
3930 #include <ddb/ddb.h>
3932 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3934 db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
3935 db_printf("vm_cnt.v_cache_count: %d\n", vm_cnt.v_cache_count);
3936 db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
3937 db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
3938 db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
3939 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
3940 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
3941 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
3942 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
3945 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3949 db_printf("pq_free %d pq_cache %d\n",
3950 vm_cnt.v_free_count, vm_cnt.v_cache_count);
3951 for (dom = 0; dom < vm_ndomains; dom++) {
3953 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pass %d\n",
3955 vm_dom[dom].vmd_page_count,
3956 vm_dom[dom].vmd_free_count,
3957 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3958 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
3959 vm_dom[dom].vmd_pass);
3963 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3969 db_printf("show pginfo addr\n");
3973 phys = strchr(modif, 'p') != NULL;
3975 m = PHYS_TO_VM_PAGE(addr);
3977 m = (vm_page_t)addr;
3979 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3980 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3981 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3982 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3983 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);