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;
138 static int boot_pages = UMA_BOOT_PAGES;
139 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
141 "number of pages allocated for bootstrapping the VM system");
143 static int pa_tryrelock_restart;
144 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
145 &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
147 static TAILQ_HEAD(, vm_page) blacklist_head;
148 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
149 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
150 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
152 /* Is the page daemon waiting for free pages? */
153 static int vm_pageout_pages_needed;
155 static uma_zone_t fakepg_zone;
157 static struct vnode *vm_page_alloc_init(vm_page_t m);
158 static void vm_page_cache_turn_free(vm_page_t m);
159 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
160 static void vm_page_enqueue(uint8_t queue, vm_page_t m);
161 static void vm_page_free_wakeup(void);
162 static void vm_page_init_fakepg(void *dummy);
163 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
164 vm_pindex_t pindex, vm_page_t mpred);
165 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
167 static int vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
170 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init_fakepg, NULL);
173 vm_page_init_fakepg(void *dummy)
176 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
177 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
180 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
181 #if PAGE_SIZE == 32768
183 CTASSERT(sizeof(u_long) >= 8);
188 * Try to acquire a physical address lock while a pmap is locked. If we
189 * fail to trylock we unlock and lock the pmap directly and cache the
190 * locked pa in *locked. The caller should then restart their loop in case
191 * the virtual to physical mapping has changed.
194 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
201 PA_LOCK_ASSERT(lockpa, MA_OWNED);
202 if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
209 atomic_add_int(&pa_tryrelock_restart, 1);
218 * Sets the page size, perhaps based upon the memory
219 * size. Must be called before any use of page-size
220 * dependent functions.
223 vm_set_page_size(void)
225 if (vm_cnt.v_page_size == 0)
226 vm_cnt.v_page_size = PAGE_SIZE;
227 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
228 panic("vm_set_page_size: page size not a power of two");
232 * vm_page_blacklist_next:
234 * Find the next entry in the provided string of blacklist
235 * addresses. Entries are separated by space, comma, or newline.
236 * If an invalid integer is encountered then the rest of the
237 * string is skipped. Updates the list pointer to the next
238 * character, or NULL if the string is exhausted or invalid.
241 vm_page_blacklist_next(char **list, char *end)
246 if (list == NULL || *list == NULL)
254 * If there's no end pointer then the buffer is coming from
255 * the kenv and we know it's null-terminated.
258 end = *list + strlen(*list);
260 /* Ensure that strtoq() won't walk off the end */
262 if (*end == '\n' || *end == ' ' || *end == ',')
265 printf("Blacklist not terminated, skipping\n");
271 for (pos = *list; *pos != '\0'; pos = cp) {
272 bad = strtoq(pos, &cp, 0);
273 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
282 if (*cp == '\0' || ++cp >= end)
286 return (trunc_page(bad));
288 printf("Garbage in RAM blacklist, skipping\n");
294 * vm_page_blacklist_check:
296 * Iterate through the provided string of blacklist addresses, pulling
297 * each entry out of the physical allocator free list and putting it
298 * onto a list for reporting via the vm.page_blacklist sysctl.
301 vm_page_blacklist_check(char *list, char *end)
309 while (next != NULL) {
310 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
312 m = vm_phys_paddr_to_vm_page(pa);
315 mtx_lock(&vm_page_queue_free_mtx);
316 ret = vm_phys_unfree_page(m);
317 mtx_unlock(&vm_page_queue_free_mtx);
319 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
321 printf("Skipping page with pa 0x%jx\n",
328 * vm_page_blacklist_load:
330 * Search for a special module named "ram_blacklist". It'll be a
331 * plain text file provided by the user via the loader directive
335 vm_page_blacklist_load(char **list, char **end)
344 mod = preload_search_by_type("ram_blacklist");
346 ptr = preload_fetch_addr(mod);
347 len = preload_fetch_size(mod);
358 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
365 error = sysctl_wire_old_buffer(req, 0);
368 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
369 TAILQ_FOREACH(m, &blacklist_head, listq) {
370 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
371 (uintmax_t)m->phys_addr);
374 error = sbuf_finish(&sbuf);
380 vm_page_domain_init(struct vm_domain *vmd)
382 struct vm_pagequeue *pq;
385 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
386 "vm inactive pagequeue";
387 *__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_vcnt) =
388 &vm_cnt.v_inactive_count;
389 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
390 "vm active pagequeue";
391 *__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_vcnt) =
392 &vm_cnt.v_active_count;
393 vmd->vmd_page_count = 0;
394 vmd->vmd_free_count = 0;
396 vmd->vmd_oom = FALSE;
397 for (i = 0; i < PQ_COUNT; i++) {
398 pq = &vmd->vmd_pagequeues[i];
399 TAILQ_INIT(&pq->pq_pl);
400 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
401 MTX_DEF | MTX_DUPOK);
408 * Initializes the resident memory module.
410 * Allocates memory for the page cells, and
411 * for the object/offset-to-page hash table headers.
412 * Each page cell is initialized and placed on the free list.
415 vm_page_startup(vm_offset_t vaddr)
418 vm_paddr_t page_range;
423 char *list, *listend;
425 vm_paddr_t biggestsize;
426 vm_paddr_t low_water, high_water;
432 vaddr = round_page(vaddr);
434 for (i = 0; phys_avail[i + 1]; i += 2) {
435 phys_avail[i] = round_page(phys_avail[i]);
436 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
439 low_water = phys_avail[0];
440 high_water = phys_avail[1];
442 for (i = 0; i < vm_phys_nsegs; i++) {
443 if (vm_phys_segs[i].start < low_water)
444 low_water = vm_phys_segs[i].start;
445 if (vm_phys_segs[i].end > high_water)
446 high_water = vm_phys_segs[i].end;
448 for (i = 0; phys_avail[i + 1]; i += 2) {
449 vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
451 if (size > biggestsize) {
455 if (phys_avail[i] < low_water)
456 low_water = phys_avail[i];
457 if (phys_avail[i + 1] > high_water)
458 high_water = phys_avail[i + 1];
461 end = phys_avail[biggestone+1];
464 * Initialize the page and queue locks.
466 mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
467 for (i = 0; i < PA_LOCK_COUNT; i++)
468 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
469 for (i = 0; i < vm_ndomains; i++)
470 vm_page_domain_init(&vm_dom[i]);
473 * Almost all of the pages needed for boot strapping UMA are used
474 * for zone structures, so if the number of CPUs results in those
475 * structures taking more than one page each, we set aside more pages
476 * in proportion to the zone structure size.
478 pages_per_zone = howmany(sizeof(struct uma_zone) +
479 sizeof(struct uma_cache) * (mp_maxid + 1), UMA_SLAB_SIZE);
480 if (pages_per_zone > 1) {
481 /* Reserve more pages so that we don't run out. */
482 boot_pages = UMA_BOOT_PAGES_ZONES * pages_per_zone;
486 * Allocate memory for use when boot strapping the kernel memory
489 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
490 * manually fetch the value.
492 TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
493 new_end = end - (boot_pages * UMA_SLAB_SIZE);
494 new_end = trunc_page(new_end);
495 mapped = pmap_map(&vaddr, new_end, end,
496 VM_PROT_READ | VM_PROT_WRITE);
497 bzero((void *)mapped, end - new_end);
498 uma_startup((void *)mapped, boot_pages);
500 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
501 defined(__i386__) || defined(__mips__)
503 * Allocate a bitmap to indicate that a random physical page
504 * needs to be included in a minidump.
506 * The amd64 port needs this to indicate which direct map pages
507 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
509 * However, i386 still needs this workspace internally within the
510 * minidump code. In theory, they are not needed on i386, but are
511 * included should the sf_buf code decide to use them.
514 for (i = 0; dump_avail[i + 1] != 0; i += 2)
515 if (dump_avail[i + 1] > last_pa)
516 last_pa = dump_avail[i + 1];
517 page_range = last_pa / PAGE_SIZE;
518 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
519 new_end -= vm_page_dump_size;
520 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
521 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
522 bzero((void *)vm_page_dump, vm_page_dump_size);
526 * Request that the physical pages underlying the message buffer be
527 * included in a crash dump. Since the message buffer is accessed
528 * through the direct map, they are not automatically included.
530 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
531 last_pa = pa + round_page(msgbufsize);
532 while (pa < last_pa) {
538 * Compute the number of pages of memory that will be available for
539 * use (taking into account the overhead of a page structure per
542 first_page = low_water / PAGE_SIZE;
543 #ifdef VM_PHYSSEG_SPARSE
545 for (i = 0; i < vm_phys_nsegs; i++) {
546 page_range += atop(vm_phys_segs[i].end -
547 vm_phys_segs[i].start);
549 for (i = 0; phys_avail[i + 1] != 0; i += 2)
550 page_range += atop(phys_avail[i + 1] - phys_avail[i]);
551 #elif defined(VM_PHYSSEG_DENSE)
552 page_range = high_water / PAGE_SIZE - first_page;
554 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
559 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
564 * Initialize the mem entry structures now, and put them in the free
567 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
568 mapped = pmap_map(&vaddr, new_end, end,
569 VM_PROT_READ | VM_PROT_WRITE);
570 vm_page_array = (vm_page_t) mapped;
571 #if VM_NRESERVLEVEL > 0
573 * Allocate memory for the reservation management system's data
576 new_end = vm_reserv_startup(&vaddr, new_end, high_water);
578 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
580 * pmap_map on arm64, amd64, and mips can come out of the direct-map,
581 * not kvm like i386, so the pages must be tracked for a crashdump to
582 * include this data. This includes the vm_page_array and the early
583 * UMA bootstrap pages.
585 for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
588 phys_avail[biggestone + 1] = new_end;
591 * Add physical memory segments corresponding to the available
594 for (i = 0; phys_avail[i + 1] != 0; i += 2)
595 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
598 * Clear all of the page structures
600 bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
601 for (i = 0; i < page_range; i++)
602 vm_page_array[i].order = VM_NFREEORDER;
603 vm_page_array_size = page_range;
606 * Initialize the physical memory allocator.
611 * Add every available physical page that is not blacklisted to
614 vm_cnt.v_page_count = 0;
615 vm_cnt.v_free_count = 0;
616 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
618 last_pa = phys_avail[i + 1];
619 while (pa < last_pa) {
620 vm_phys_add_page(pa);
625 TAILQ_INIT(&blacklist_head);
626 vm_page_blacklist_load(&list, &listend);
627 vm_page_blacklist_check(list, listend);
629 list = kern_getenv("vm.blacklist");
630 vm_page_blacklist_check(list, NULL);
633 #if VM_NRESERVLEVEL > 0
635 * Initialize the reservation management system.
643 vm_page_reference(vm_page_t m)
646 vm_page_aflag_set(m, PGA_REFERENCED);
650 * vm_page_busy_downgrade:
652 * Downgrade an exclusive busy page into a single shared busy page.
655 vm_page_busy_downgrade(vm_page_t m)
660 vm_page_assert_xbusied(m);
661 locked = mtx_owned(vm_page_lockptr(m));
665 x &= VPB_BIT_WAITERS;
666 if (x != 0 && !locked)
668 if (atomic_cmpset_rel_int(&m->busy_lock,
669 VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1)))
671 if (x != 0 && !locked)
684 * Return a positive value if the page is shared busied, 0 otherwise.
687 vm_page_sbusied(vm_page_t m)
692 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
698 * Shared unbusy a page.
701 vm_page_sunbusy(vm_page_t m)
705 vm_page_assert_sbusied(m);
709 if (VPB_SHARERS(x) > 1) {
710 if (atomic_cmpset_int(&m->busy_lock, x,
715 if ((x & VPB_BIT_WAITERS) == 0) {
716 KASSERT(x == VPB_SHARERS_WORD(1),
717 ("vm_page_sunbusy: invalid lock state"));
718 if (atomic_cmpset_int(&m->busy_lock,
719 VPB_SHARERS_WORD(1), VPB_UNBUSIED))
723 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
724 ("vm_page_sunbusy: invalid lock state for waiters"));
727 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
738 * vm_page_busy_sleep:
740 * Sleep and release the page lock, using the page pointer as wchan.
741 * This is used to implement the hard-path of busying mechanism.
743 * The given page must be locked.
745 * If nonshared is true, sleep only if the page is xbusy.
748 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
752 vm_page_assert_locked(m);
755 if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
756 ((x & VPB_BIT_WAITERS) == 0 &&
757 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
761 msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
767 * Try to shared busy a page.
768 * If the operation succeeds 1 is returned otherwise 0.
769 * The operation never sleeps.
772 vm_page_trysbusy(vm_page_t m)
778 if ((x & VPB_BIT_SHARED) == 0)
780 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
786 vm_page_xunbusy_locked(vm_page_t m)
789 vm_page_assert_xbusied(m);
790 vm_page_assert_locked(m);
792 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
793 /* There is a waiter, do wakeup() instead of vm_page_flash(). */
798 vm_page_xunbusy_maybelocked(vm_page_t m)
802 vm_page_assert_xbusied(m);
805 * Fast path for unbusy. If it succeeds, we know that there
806 * are no waiters, so we do not need a wakeup.
808 if (atomic_cmpset_rel_int(&m->busy_lock, VPB_SINGLE_EXCLUSIVER,
812 lockacq = !mtx_owned(vm_page_lockptr(m));
815 vm_page_xunbusy_locked(m);
821 * vm_page_xunbusy_hard:
823 * Called after the first try the exclusive unbusy of a page failed.
824 * It is assumed that the waiters bit is on.
827 vm_page_xunbusy_hard(vm_page_t m)
830 vm_page_assert_xbusied(m);
833 vm_page_xunbusy_locked(m);
840 * Wakeup anyone waiting for the page.
841 * The ownership bits do not change.
843 * The given page must be locked.
846 vm_page_flash(vm_page_t m)
850 vm_page_lock_assert(m, MA_OWNED);
854 if ((x & VPB_BIT_WAITERS) == 0)
856 if (atomic_cmpset_int(&m->busy_lock, x,
857 x & (~VPB_BIT_WAITERS)))
864 * Keep page from being freed by the page daemon
865 * much of the same effect as wiring, except much lower
866 * overhead and should be used only for *very* temporary
867 * holding ("wiring").
870 vm_page_hold(vm_page_t mem)
873 vm_page_lock_assert(mem, MA_OWNED);
878 vm_page_unhold(vm_page_t mem)
881 vm_page_lock_assert(mem, MA_OWNED);
882 KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
884 if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
885 vm_page_free_toq(mem);
889 * vm_page_unhold_pages:
891 * Unhold each of the pages that is referenced by the given array.
894 vm_page_unhold_pages(vm_page_t *ma, int count)
896 struct mtx *mtx, *new_mtx;
899 for (; count != 0; count--) {
901 * Avoid releasing and reacquiring the same page lock.
903 new_mtx = vm_page_lockptr(*ma);
904 if (mtx != new_mtx) {
918 PHYS_TO_VM_PAGE(vm_paddr_t pa)
922 #ifdef VM_PHYSSEG_SPARSE
923 m = vm_phys_paddr_to_vm_page(pa);
925 m = vm_phys_fictitious_to_vm_page(pa);
927 #elif defined(VM_PHYSSEG_DENSE)
931 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
932 m = &vm_page_array[pi - first_page];
935 return (vm_phys_fictitious_to_vm_page(pa));
937 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
944 * Create a fictitious page with the specified physical address and
945 * memory attribute. The memory attribute is the only the machine-
946 * dependent aspect of a fictitious page that must be initialized.
949 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
953 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
954 vm_page_initfake(m, paddr, memattr);
959 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
962 if ((m->flags & PG_FICTITIOUS) != 0) {
964 * The page's memattr might have changed since the
965 * previous initialization. Update the pmap to the
970 m->phys_addr = paddr;
972 /* Fictitious pages don't use "segind". */
973 m->flags = PG_FICTITIOUS;
974 /* Fictitious pages don't use "order" or "pool". */
975 m->oflags = VPO_UNMANAGED;
976 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
980 pmap_page_set_memattr(m, memattr);
986 * Release a fictitious page.
989 vm_page_putfake(vm_page_t m)
992 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
993 KASSERT((m->flags & PG_FICTITIOUS) != 0,
994 ("vm_page_putfake: bad page %p", m));
995 uma_zfree(fakepg_zone, m);
999 * vm_page_updatefake:
1001 * Update the given fictitious page to the specified physical address and
1005 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1008 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1009 ("vm_page_updatefake: bad page %p", m));
1010 m->phys_addr = paddr;
1011 pmap_page_set_memattr(m, memattr);
1020 vm_page_free(vm_page_t m)
1023 m->flags &= ~PG_ZERO;
1024 vm_page_free_toq(m);
1028 * vm_page_free_zero:
1030 * Free a page to the zerod-pages queue
1033 vm_page_free_zero(vm_page_t m)
1036 m->flags |= PG_ZERO;
1037 vm_page_free_toq(m);
1041 * Unbusy and handle the page queueing for a page from a getpages request that
1042 * was optionally read ahead or behind.
1045 vm_page_readahead_finish(vm_page_t m)
1048 /* We shouldn't put invalid pages on queues. */
1049 KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
1052 * Since the page is not the actually needed one, whether it should
1053 * be activated or deactivated is not obvious. Empirical results
1054 * have shown that deactivating the page is usually the best choice,
1055 * unless the page is wanted by another thread.
1058 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1059 vm_page_activate(m);
1061 vm_page_deactivate(m);
1067 * vm_page_sleep_if_busy:
1069 * Sleep and release the page queues lock if the page is busied.
1070 * Returns TRUE if the thread slept.
1072 * The given page must be unlocked and object containing it must
1076 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1080 vm_page_lock_assert(m, MA_NOTOWNED);
1081 VM_OBJECT_ASSERT_WLOCKED(m->object);
1083 if (vm_page_busied(m)) {
1085 * The page-specific object must be cached because page
1086 * identity can change during the sleep, causing the
1087 * re-lock of a different object.
1088 * It is assumed that a reference to the object is already
1089 * held by the callers.
1093 VM_OBJECT_WUNLOCK(obj);
1094 vm_page_busy_sleep(m, msg, false);
1095 VM_OBJECT_WLOCK(obj);
1102 * vm_page_dirty_KBI: [ internal use only ]
1104 * Set all bits in the page's dirty field.
1106 * The object containing the specified page must be locked if the
1107 * call is made from the machine-independent layer.
1109 * See vm_page_clear_dirty_mask().
1111 * This function should only be called by vm_page_dirty().
1114 vm_page_dirty_KBI(vm_page_t m)
1117 /* These assertions refer to this operation by its public name. */
1118 KASSERT((m->flags & PG_CACHED) == 0,
1119 ("vm_page_dirty: page in cache!"));
1120 KASSERT(m->valid == VM_PAGE_BITS_ALL,
1121 ("vm_page_dirty: page is invalid!"));
1122 m->dirty = VM_PAGE_BITS_ALL;
1126 * vm_page_insert: [ internal use only ]
1128 * Inserts the given mem entry into the object and object list.
1130 * The object must be locked.
1133 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1137 VM_OBJECT_ASSERT_WLOCKED(object);
1138 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1139 return (vm_page_insert_after(m, object, pindex, mpred));
1143 * vm_page_insert_after:
1145 * Inserts the page "m" into the specified object at offset "pindex".
1147 * The page "mpred" must immediately precede the offset "pindex" within
1148 * the specified object.
1150 * The object must be locked.
1153 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1158 VM_OBJECT_ASSERT_WLOCKED(object);
1159 KASSERT(m->object == NULL,
1160 ("vm_page_insert_after: page already inserted"));
1161 if (mpred != NULL) {
1162 KASSERT(mpred->object == object,
1163 ("vm_page_insert_after: object doesn't contain mpred"));
1164 KASSERT(mpred->pindex < pindex,
1165 ("vm_page_insert_after: mpred doesn't precede pindex"));
1166 msucc = TAILQ_NEXT(mpred, listq);
1168 msucc = TAILQ_FIRST(&object->memq);
1170 KASSERT(msucc->pindex > pindex,
1171 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1174 * Record the object/offset pair in this page
1180 * Now link into the object's ordered list of backed pages.
1182 if (vm_radix_insert(&object->rtree, m)) {
1187 vm_page_insert_radixdone(m, object, mpred);
1192 * vm_page_insert_radixdone:
1194 * Complete page "m" insertion into the specified object after the
1195 * radix trie hooking.
1197 * The page "mpred" must precede the offset "m->pindex" within the
1200 * The object must be locked.
1203 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1206 VM_OBJECT_ASSERT_WLOCKED(object);
1207 KASSERT(object != NULL && m->object == object,
1208 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1209 if (mpred != NULL) {
1210 KASSERT(mpred->object == object,
1211 ("vm_page_insert_after: object doesn't contain mpred"));
1212 KASSERT(mpred->pindex < m->pindex,
1213 ("vm_page_insert_after: mpred doesn't precede pindex"));
1217 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1219 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1222 * Show that the object has one more resident page.
1224 object->resident_page_count++;
1227 * Hold the vnode until the last page is released.
1229 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1230 vhold(object->handle);
1233 * Since we are inserting a new and possibly dirty page,
1234 * update the object's OBJ_MIGHTBEDIRTY flag.
1236 if (pmap_page_is_write_mapped(m))
1237 vm_object_set_writeable_dirty(object);
1243 * Removes the given mem entry from the object/offset-page
1244 * table and the object page list, but do not invalidate/terminate
1245 * the backing store.
1247 * The object must be locked. The page must be locked if it is managed.
1250 vm_page_remove(vm_page_t m)
1254 if ((m->oflags & VPO_UNMANAGED) == 0)
1255 vm_page_assert_locked(m);
1256 if ((object = m->object) == NULL)
1258 VM_OBJECT_ASSERT_WLOCKED(object);
1259 if (vm_page_xbusied(m))
1260 vm_page_xunbusy_maybelocked(m);
1263 * Now remove from the object's list of backed pages.
1265 vm_radix_remove(&object->rtree, m->pindex);
1266 TAILQ_REMOVE(&object->memq, m, listq);
1269 * And show that the object has one fewer resident page.
1271 object->resident_page_count--;
1274 * The vnode may now be recycled.
1276 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1277 vdrop(object->handle);
1285 * Returns the page associated with the object/offset
1286 * pair specified; if none is found, NULL is returned.
1288 * The object must be locked.
1291 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1294 VM_OBJECT_ASSERT_LOCKED(object);
1295 return (vm_radix_lookup(&object->rtree, pindex));
1299 * vm_page_find_least:
1301 * Returns the page associated with the object with least pindex
1302 * greater than or equal to the parameter pindex, or NULL.
1304 * The object must be locked.
1307 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1311 VM_OBJECT_ASSERT_LOCKED(object);
1312 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1313 m = vm_radix_lookup_ge(&object->rtree, pindex);
1318 * Returns the given page's successor (by pindex) within the object if it is
1319 * resident; if none is found, NULL is returned.
1321 * The object must be locked.
1324 vm_page_next(vm_page_t m)
1328 VM_OBJECT_ASSERT_LOCKED(m->object);
1329 if ((next = TAILQ_NEXT(m, listq)) != NULL &&
1330 next->pindex != m->pindex + 1)
1336 * Returns the given page's predecessor (by pindex) within the object if it is
1337 * resident; if none is found, NULL is returned.
1339 * The object must be locked.
1342 vm_page_prev(vm_page_t m)
1346 VM_OBJECT_ASSERT_LOCKED(m->object);
1347 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
1348 prev->pindex != m->pindex - 1)
1354 * Uses the page mnew as a replacement for an existing page at index
1355 * pindex which must be already present in the object.
1357 * The existing page must not be on a paging queue.
1360 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1364 VM_OBJECT_ASSERT_WLOCKED(object);
1365 KASSERT(mnew->object == NULL,
1366 ("vm_page_replace: page already in object"));
1369 * This function mostly follows vm_page_insert() and
1370 * vm_page_remove() without the radix, object count and vnode
1371 * dance. Double check such functions for more comments.
1374 mnew->object = object;
1375 mnew->pindex = pindex;
1376 mold = vm_radix_replace(&object->rtree, mnew);
1377 KASSERT(mold->queue == PQ_NONE,
1378 ("vm_page_replace: mold is on a paging queue"));
1380 /* Keep the resident page list in sorted order. */
1381 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1382 TAILQ_REMOVE(&object->memq, mold, listq);
1384 mold->object = NULL;
1385 vm_page_xunbusy_maybelocked(mold);
1388 * The object's resident_page_count does not change because we have
1389 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1391 if (pmap_page_is_write_mapped(mnew))
1392 vm_object_set_writeable_dirty(object);
1399 * Move the given memory entry from its
1400 * current object to the specified target object/offset.
1402 * Note: swap associated with the page must be invalidated by the move. We
1403 * have to do this for several reasons: (1) we aren't freeing the
1404 * page, (2) we are dirtying the page, (3) the VM system is probably
1405 * moving the page from object A to B, and will then later move
1406 * the backing store from A to B and we can't have a conflict.
1408 * Note: we *always* dirty the page. It is necessary both for the
1409 * fact that we moved it, and because we may be invalidating
1410 * swap. If the page is on the cache, we have to deactivate it
1411 * or vm_page_dirty() will panic. Dirty pages are not allowed
1414 * The objects must be locked.
1417 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1422 VM_OBJECT_ASSERT_WLOCKED(new_object);
1424 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1425 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1426 ("vm_page_rename: pindex already renamed"));
1429 * Create a custom version of vm_page_insert() which does not depend
1430 * by m_prev and can cheat on the implementation aspects of the
1434 m->pindex = new_pindex;
1435 if (vm_radix_insert(&new_object->rtree, m)) {
1441 * The operation cannot fail anymore. The removal must happen before
1442 * the listq iterator is tainted.
1448 /* Return back to the new pindex to complete vm_page_insert(). */
1449 m->pindex = new_pindex;
1450 m->object = new_object;
1452 vm_page_insert_radixdone(m, new_object, mpred);
1458 * Convert all of the given object's cached pages that have a
1459 * pindex within the given range into free pages. If the value
1460 * zero is given for "end", then the range's upper bound is
1461 * infinity. If the given object is backed by a vnode and it
1462 * transitions from having one or more cached pages to none, the
1463 * vnode's hold count is reduced.
1466 vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1471 mtx_lock(&vm_page_queue_free_mtx);
1472 if (__predict_false(vm_radix_is_empty(&object->cache))) {
1473 mtx_unlock(&vm_page_queue_free_mtx);
1476 while ((m = vm_radix_lookup_ge(&object->cache, start)) != NULL) {
1477 if (end != 0 && m->pindex >= end)
1479 vm_radix_remove(&object->cache, m->pindex);
1480 vm_page_cache_turn_free(m);
1482 empty = vm_radix_is_empty(&object->cache);
1483 mtx_unlock(&vm_page_queue_free_mtx);
1484 if (object->type == OBJT_VNODE && empty)
1485 vdrop(object->handle);
1489 * Returns the cached page that is associated with the given
1490 * object and offset. If, however, none exists, returns NULL.
1492 * The free page queue must be locked.
1494 static inline vm_page_t
1495 vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
1498 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1499 return (vm_radix_lookup(&object->cache, pindex));
1503 * Remove the given cached page from its containing object's
1504 * collection of cached pages.
1506 * The free page queue must be locked.
1509 vm_page_cache_remove(vm_page_t m)
1512 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1513 KASSERT((m->flags & PG_CACHED) != 0,
1514 ("vm_page_cache_remove: page %p is not cached", m));
1515 vm_radix_remove(&m->object->cache, m->pindex);
1517 vm_cnt.v_cache_count--;
1521 * Transfer all of the cached pages with offset greater than or
1522 * equal to 'offidxstart' from the original object's cache to the
1523 * new object's cache. However, any cached pages with offset
1524 * greater than or equal to the new object's size are kept in the
1525 * original object. Initially, the new object's cache must be
1526 * empty. Offset 'offidxstart' in the original object must
1527 * correspond to offset zero in the new object.
1529 * The new object must be locked.
1532 vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1533 vm_object_t new_object)
1538 * Insertion into an object's collection of cached pages
1539 * requires the object to be locked. In contrast, removal does
1542 VM_OBJECT_ASSERT_WLOCKED(new_object);
1543 KASSERT(vm_radix_is_empty(&new_object->cache),
1544 ("vm_page_cache_transfer: object %p has cached pages",
1546 mtx_lock(&vm_page_queue_free_mtx);
1547 while ((m = vm_radix_lookup_ge(&orig_object->cache,
1548 offidxstart)) != NULL) {
1550 * Transfer all of the pages with offset greater than or
1551 * equal to 'offidxstart' from the original object's
1552 * cache to the new object's cache.
1554 if ((m->pindex - offidxstart) >= new_object->size)
1556 vm_radix_remove(&orig_object->cache, m->pindex);
1557 /* Update the page's object and offset. */
1558 m->object = new_object;
1559 m->pindex -= offidxstart;
1560 if (vm_radix_insert(&new_object->cache, m))
1561 vm_page_cache_turn_free(m);
1563 mtx_unlock(&vm_page_queue_free_mtx);
1567 * Returns TRUE if a cached page is associated with the given object and
1568 * offset, and FALSE otherwise.
1570 * The object must be locked.
1573 vm_page_is_cached(vm_object_t object, vm_pindex_t pindex)
1578 * Insertion into an object's collection of cached pages requires the
1579 * object to be locked. Therefore, if the object is locked and the
1580 * object's collection is empty, there is no need to acquire the free
1581 * page queues lock in order to prove that the specified page doesn't
1584 VM_OBJECT_ASSERT_WLOCKED(object);
1585 if (__predict_true(vm_object_cache_is_empty(object)))
1587 mtx_lock(&vm_page_queue_free_mtx);
1588 m = vm_page_cache_lookup(object, pindex);
1589 mtx_unlock(&vm_page_queue_free_mtx);
1596 * Allocate and return a page that is associated with the specified
1597 * object and offset pair. By default, this page is exclusive busied.
1599 * The caller must always specify an allocation class.
1601 * allocation classes:
1602 * VM_ALLOC_NORMAL normal process request
1603 * VM_ALLOC_SYSTEM system *really* needs a page
1604 * VM_ALLOC_INTERRUPT interrupt time request
1606 * optional allocation flags:
1607 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1608 * intends to allocate
1609 * VM_ALLOC_IFCACHED return page only if it is cached
1610 * VM_ALLOC_IFNOTCACHED return NULL, do not reactivate if the page
1612 * VM_ALLOC_NOBUSY do not exclusive busy the page
1613 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1614 * VM_ALLOC_NOOBJ page is not associated with an object and
1615 * should not be exclusive busy
1616 * VM_ALLOC_SBUSY shared busy the allocated page
1617 * VM_ALLOC_WIRED wire the allocated page
1618 * VM_ALLOC_ZERO prefer a zeroed page
1620 * This routine may not sleep.
1623 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1625 struct vnode *vp = NULL;
1626 vm_object_t m_object;
1628 int flags, req_class;
1630 mpred = 0; /* XXX: pacify gcc */
1631 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1632 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1633 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1634 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1635 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1638 VM_OBJECT_ASSERT_WLOCKED(object);
1640 req_class = req & VM_ALLOC_CLASS_MASK;
1643 * The page daemon is allowed to dig deeper into the free page list.
1645 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1646 req_class = VM_ALLOC_SYSTEM;
1648 if (object != NULL) {
1649 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1650 KASSERT(mpred == NULL || mpred->pindex != pindex,
1651 ("vm_page_alloc: pindex already allocated"));
1655 * The page allocation request can came from consumers which already
1656 * hold the free page queue mutex, like vm_page_insert() in
1659 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
1660 if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
1661 (req_class == VM_ALLOC_SYSTEM &&
1662 vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
1663 (req_class == VM_ALLOC_INTERRUPT &&
1664 vm_cnt.v_free_count + vm_cnt.v_cache_count > 0)) {
1666 * Allocate from the free queue if the number of free pages
1667 * exceeds the minimum for the request class.
1669 if (object != NULL &&
1670 (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1671 if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1672 mtx_unlock(&vm_page_queue_free_mtx);
1675 if (vm_phys_unfree_page(m))
1676 vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1677 #if VM_NRESERVLEVEL > 0
1678 else if (!vm_reserv_reactivate_page(m))
1682 panic("vm_page_alloc: cache page %p is missing"
1683 " from the free queue", m);
1684 } else if ((req & VM_ALLOC_IFCACHED) != 0) {
1685 mtx_unlock(&vm_page_queue_free_mtx);
1687 #if VM_NRESERVLEVEL > 0
1688 } else if (object == NULL || (object->flags & (OBJ_COLORED |
1689 OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1690 vm_reserv_alloc_page(object, pindex, mpred)) == NULL) {
1694 m = vm_phys_alloc_pages(object != NULL ?
1695 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1696 #if VM_NRESERVLEVEL > 0
1697 if (m == NULL && vm_reserv_reclaim_inactive()) {
1698 m = vm_phys_alloc_pages(object != NULL ?
1699 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1706 * Not allocatable, give up.
1708 mtx_unlock(&vm_page_queue_free_mtx);
1709 atomic_add_int(&vm_pageout_deficit,
1710 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1711 pagedaemon_wakeup();
1716 * At this point we had better have found a good page.
1718 KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1719 KASSERT(m->queue == PQ_NONE,
1720 ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1721 KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1722 KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1723 KASSERT(!vm_page_busied(m), ("vm_page_alloc: page %p is busy", m));
1724 KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1725 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1726 ("vm_page_alloc: page %p has unexpected memattr %d", m,
1727 pmap_page_get_memattr(m)));
1728 if ((m->flags & PG_CACHED) != 0) {
1729 KASSERT((m->flags & PG_ZERO) == 0,
1730 ("vm_page_alloc: cached page %p is PG_ZERO", m));
1731 KASSERT(m->valid != 0,
1732 ("vm_page_alloc: cached page %p is invalid", m));
1733 if (m->object == object && m->pindex == pindex)
1734 vm_cnt.v_reactivated++;
1737 m_object = m->object;
1738 vm_page_cache_remove(m);
1739 if (m_object->type == OBJT_VNODE &&
1740 vm_object_cache_is_empty(m_object))
1741 vp = m_object->handle;
1743 KASSERT(m->valid == 0,
1744 ("vm_page_alloc: free page %p is valid", m));
1745 vm_phys_freecnt_adj(m, -1);
1747 mtx_unlock(&vm_page_queue_free_mtx);
1750 * Initialize the page. Only the PG_ZERO flag is inherited.
1753 if ((req & VM_ALLOC_ZERO) != 0)
1756 if ((req & VM_ALLOC_NODUMP) != 0)
1760 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1762 m->busy_lock = VPB_UNBUSIED;
1763 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1764 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1765 if ((req & VM_ALLOC_SBUSY) != 0)
1766 m->busy_lock = VPB_SHARERS_WORD(1);
1767 if (req & VM_ALLOC_WIRED) {
1769 * The page lock is not required for wiring a page until that
1770 * page is inserted into the object.
1772 atomic_add_int(&vm_cnt.v_wire_count, 1);
1777 if (object != NULL) {
1778 if (vm_page_insert_after(m, object, pindex, mpred)) {
1779 /* See the comment below about hold count. */
1782 pagedaemon_wakeup();
1783 if (req & VM_ALLOC_WIRED) {
1784 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1788 m->oflags = VPO_UNMANAGED;
1789 m->busy_lock = VPB_UNBUSIED;
1794 /* Ignore device objects; the pager sets "memattr" for them. */
1795 if (object->memattr != VM_MEMATTR_DEFAULT &&
1796 (object->flags & OBJ_FICTITIOUS) == 0)
1797 pmap_page_set_memattr(m, object->memattr);
1802 * The following call to vdrop() must come after the above call
1803 * to vm_page_insert() in case both affect the same object and
1804 * vnode. Otherwise, the affected vnode's hold count could
1805 * temporarily become zero.
1811 * Don't wakeup too often - wakeup the pageout daemon when
1812 * we would be nearly out of memory.
1814 if (vm_paging_needed())
1815 pagedaemon_wakeup();
1821 vm_page_alloc_contig_vdrop(struct spglist *lst)
1824 while (!SLIST_EMPTY(lst)) {
1825 vdrop((struct vnode *)SLIST_FIRST(lst)-> plinks.s.pv);
1826 SLIST_REMOVE_HEAD(lst, plinks.s.ss);
1831 * vm_page_alloc_contig:
1833 * Allocate a contiguous set of physical pages of the given size "npages"
1834 * from the free lists. All of the physical pages must be at or above
1835 * the given physical address "low" and below the given physical address
1836 * "high". The given value "alignment" determines the alignment of the
1837 * first physical page in the set. If the given value "boundary" is
1838 * non-zero, then the set of physical pages cannot cross any physical
1839 * address boundary that is a multiple of that value. Both "alignment"
1840 * and "boundary" must be a power of two.
1842 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1843 * then the memory attribute setting for the physical pages is configured
1844 * to the object's memory attribute setting. Otherwise, the memory
1845 * attribute setting for the physical pages is configured to "memattr",
1846 * overriding the object's memory attribute setting. However, if the
1847 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1848 * memory attribute setting for the physical pages cannot be configured
1849 * to VM_MEMATTR_DEFAULT.
1851 * The caller must always specify an allocation class.
1853 * allocation classes:
1854 * VM_ALLOC_NORMAL normal process request
1855 * VM_ALLOC_SYSTEM system *really* needs a page
1856 * VM_ALLOC_INTERRUPT interrupt time request
1858 * optional allocation flags:
1859 * VM_ALLOC_NOBUSY do not exclusive busy the page
1860 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1861 * VM_ALLOC_NOOBJ page is not associated with an object and
1862 * should not be exclusive busy
1863 * VM_ALLOC_SBUSY shared busy the allocated page
1864 * VM_ALLOC_WIRED wire the allocated page
1865 * VM_ALLOC_ZERO prefer a zeroed page
1867 * This routine may not sleep.
1870 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1871 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1872 vm_paddr_t boundary, vm_memattr_t memattr)
1875 struct spglist deferred_vdrop_list;
1876 vm_page_t m, m_tmp, m_ret;
1880 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1881 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1882 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1883 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1884 ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1886 if (object != NULL) {
1887 VM_OBJECT_ASSERT_WLOCKED(object);
1888 KASSERT(object->type == OBJT_PHYS,
1889 ("vm_page_alloc_contig: object %p isn't OBJT_PHYS",
1892 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1893 req_class = req & VM_ALLOC_CLASS_MASK;
1896 * The page daemon is allowed to dig deeper into the free page list.
1898 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1899 req_class = VM_ALLOC_SYSTEM;
1901 SLIST_INIT(&deferred_vdrop_list);
1902 mtx_lock(&vm_page_queue_free_mtx);
1903 if (vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1904 vm_cnt.v_free_reserved || (req_class == VM_ALLOC_SYSTEM &&
1905 vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1906 vm_cnt.v_interrupt_free_min) || (req_class == VM_ALLOC_INTERRUPT &&
1907 vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages)) {
1908 #if VM_NRESERVLEVEL > 0
1910 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1911 (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1912 low, high, alignment, boundary)) == NULL)
1914 m_ret = vm_phys_alloc_contig(npages, low, high,
1915 alignment, boundary);
1917 mtx_unlock(&vm_page_queue_free_mtx);
1918 atomic_add_int(&vm_pageout_deficit, npages);
1919 pagedaemon_wakeup();
1923 for (m = m_ret; m < &m_ret[npages]; m++) {
1924 drop = vm_page_alloc_init(m);
1927 * Enqueue the vnode for deferred vdrop().
1929 m->plinks.s.pv = drop;
1930 SLIST_INSERT_HEAD(&deferred_vdrop_list, m,
1935 #if VM_NRESERVLEVEL > 0
1936 if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1941 mtx_unlock(&vm_page_queue_free_mtx);
1946 * Initialize the pages. Only the PG_ZERO flag is inherited.
1949 if ((req & VM_ALLOC_ZERO) != 0)
1951 if ((req & VM_ALLOC_NODUMP) != 0)
1953 if ((req & VM_ALLOC_WIRED) != 0)
1954 atomic_add_int(&vm_cnt.v_wire_count, npages);
1955 if (object != NULL) {
1956 if (object->memattr != VM_MEMATTR_DEFAULT &&
1957 memattr == VM_MEMATTR_DEFAULT)
1958 memattr = object->memattr;
1960 for (m = m_ret; m < &m_ret[npages]; m++) {
1962 m->flags = (m->flags | PG_NODUMP) & flags;
1963 m->busy_lock = VPB_UNBUSIED;
1964 if (object != NULL) {
1965 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
1966 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1967 if ((req & VM_ALLOC_SBUSY) != 0)
1968 m->busy_lock = VPB_SHARERS_WORD(1);
1970 if ((req & VM_ALLOC_WIRED) != 0)
1972 /* Unmanaged pages don't use "act_count". */
1973 m->oflags = VPO_UNMANAGED;
1974 if (object != NULL) {
1975 if (vm_page_insert(m, object, pindex)) {
1976 vm_page_alloc_contig_vdrop(
1977 &deferred_vdrop_list);
1978 if (vm_paging_needed())
1979 pagedaemon_wakeup();
1980 if ((req & VM_ALLOC_WIRED) != 0)
1981 atomic_subtract_int(&vm_cnt.v_wire_count,
1983 for (m_tmp = m, m = m_ret;
1984 m < &m_ret[npages]; m++) {
1985 if ((req & VM_ALLOC_WIRED) != 0)
1989 m->oflags |= VPO_UNMANAGED;
1991 m->busy_lock = VPB_UNBUSIED;
1998 if (memattr != VM_MEMATTR_DEFAULT)
1999 pmap_page_set_memattr(m, memattr);
2002 vm_page_alloc_contig_vdrop(&deferred_vdrop_list);
2003 if (vm_paging_needed())
2004 pagedaemon_wakeup();
2009 * Initialize a page that has been freshly dequeued from a freelist.
2010 * The caller has to drop the vnode returned, if it is not NULL.
2012 * This function may only be used to initialize unmanaged pages.
2014 * To be called with vm_page_queue_free_mtx held.
2016 static struct vnode *
2017 vm_page_alloc_init(vm_page_t m)
2020 vm_object_t m_object;
2022 KASSERT(m->queue == PQ_NONE,
2023 ("vm_page_alloc_init: page %p has unexpected queue %d",
2025 KASSERT(m->wire_count == 0,
2026 ("vm_page_alloc_init: page %p is wired", m));
2027 KASSERT(m->hold_count == 0,
2028 ("vm_page_alloc_init: page %p is held", m));
2029 KASSERT(!vm_page_busied(m),
2030 ("vm_page_alloc_init: page %p is busy", m));
2031 KASSERT(m->dirty == 0,
2032 ("vm_page_alloc_init: page %p is dirty", m));
2033 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2034 ("vm_page_alloc_init: page %p has unexpected memattr %d",
2035 m, pmap_page_get_memattr(m)));
2036 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2038 if ((m->flags & PG_CACHED) != 0) {
2039 KASSERT((m->flags & PG_ZERO) == 0,
2040 ("vm_page_alloc_init: cached page %p is PG_ZERO", m));
2042 m_object = m->object;
2043 vm_page_cache_remove(m);
2044 if (m_object->type == OBJT_VNODE &&
2045 vm_object_cache_is_empty(m_object))
2046 drop = m_object->handle;
2048 KASSERT(m->valid == 0,
2049 ("vm_page_alloc_init: free page %p is valid", m));
2050 vm_phys_freecnt_adj(m, -1);
2056 * vm_page_alloc_freelist:
2058 * Allocate a physical page from the specified free page list.
2060 * The caller must always specify an allocation class.
2062 * allocation classes:
2063 * VM_ALLOC_NORMAL normal process request
2064 * VM_ALLOC_SYSTEM system *really* needs a page
2065 * VM_ALLOC_INTERRUPT interrupt time request
2067 * optional allocation flags:
2068 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2069 * intends to allocate
2070 * VM_ALLOC_WIRED wire the allocated page
2071 * VM_ALLOC_ZERO prefer a zeroed page
2073 * This routine may not sleep.
2076 vm_page_alloc_freelist(int flind, int req)
2083 req_class = req & VM_ALLOC_CLASS_MASK;
2086 * The page daemon is allowed to dig deeper into the free page list.
2088 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2089 req_class = VM_ALLOC_SYSTEM;
2092 * Do not allocate reserved pages unless the req has asked for it.
2094 mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
2095 if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
2096 (req_class == VM_ALLOC_SYSTEM &&
2097 vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
2098 (req_class == VM_ALLOC_INTERRUPT &&
2099 vm_cnt.v_free_count + vm_cnt.v_cache_count > 0))
2100 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
2102 mtx_unlock(&vm_page_queue_free_mtx);
2103 atomic_add_int(&vm_pageout_deficit,
2104 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
2105 pagedaemon_wakeup();
2109 mtx_unlock(&vm_page_queue_free_mtx);
2112 drop = vm_page_alloc_init(m);
2113 mtx_unlock(&vm_page_queue_free_mtx);
2116 * Initialize the page. Only the PG_ZERO flag is inherited.
2120 if ((req & VM_ALLOC_ZERO) != 0)
2123 if ((req & VM_ALLOC_WIRED) != 0) {
2125 * The page lock is not required for wiring a page that does
2126 * not belong to an object.
2128 atomic_add_int(&vm_cnt.v_wire_count, 1);
2131 /* Unmanaged pages don't use "act_count". */
2132 m->oflags = VPO_UNMANAGED;
2135 if (vm_paging_needed())
2136 pagedaemon_wakeup();
2140 #define VPSC_ANY 0 /* No restrictions. */
2141 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2142 #define VPSC_NOSUPER 2 /* Skip superpages. */
2145 * vm_page_scan_contig:
2147 * Scan vm_page_array[] between the specified entries "m_start" and
2148 * "m_end" for a run of contiguous physical pages that satisfy the
2149 * specified conditions, and return the lowest page in the run. The
2150 * specified "alignment" determines the alignment of the lowest physical
2151 * page in the run. If the specified "boundary" is non-zero, then the
2152 * run of physical pages cannot span a physical address that is a
2153 * multiple of "boundary".
2155 * "m_end" is never dereferenced, so it need not point to a vm_page
2156 * structure within vm_page_array[].
2158 * "npages" must be greater than zero. "m_start" and "m_end" must not
2159 * span a hole (or discontiguity) in the physical address space. Both
2160 * "alignment" and "boundary" must be a power of two.
2163 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2164 u_long alignment, vm_paddr_t boundary, int options)
2166 struct mtx *m_mtx, *new_mtx;
2170 #if VM_NRESERVLEVEL > 0
2173 int m_inc, order, run_ext, run_len;
2175 KASSERT(npages > 0, ("npages is 0"));
2176 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2177 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2181 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2182 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2183 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2186 * If the current page would be the start of a run, check its
2187 * physical address against the end, alignment, and boundary
2188 * conditions. If it doesn't satisfy these conditions, either
2189 * terminate the scan or advance to the next page that
2190 * satisfies the failed condition.
2193 KASSERT(m_run == NULL, ("m_run != NULL"));
2194 if (m + npages > m_end)
2196 pa = VM_PAGE_TO_PHYS(m);
2197 if ((pa & (alignment - 1)) != 0) {
2198 m_inc = atop(roundup2(pa, alignment) - pa);
2201 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2203 m_inc = atop(roundup2(pa, boundary) - pa);
2207 KASSERT(m_run != NULL, ("m_run == NULL"));
2210 * Avoid releasing and reacquiring the same page lock.
2212 new_mtx = vm_page_lockptr(m);
2213 if (m_mtx != new_mtx) {
2221 if (m->wire_count != 0 || m->hold_count != 0)
2223 #if VM_NRESERVLEVEL > 0
2224 else if ((level = vm_reserv_level(m)) >= 0 &&
2225 (options & VPSC_NORESERV) != 0) {
2227 /* Advance to the end of the reservation. */
2228 pa = VM_PAGE_TO_PHYS(m);
2229 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2233 else if ((object = m->object) != NULL) {
2235 * The page is considered eligible for relocation if
2236 * and only if it could be laundered or reclaimed by
2239 if (!VM_OBJECT_TRYRLOCK(object)) {
2241 VM_OBJECT_RLOCK(object);
2243 if (m->object != object) {
2245 * The page may have been freed.
2247 VM_OBJECT_RUNLOCK(object);
2249 } else if (m->wire_count != 0 ||
2250 m->hold_count != 0) {
2255 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2256 ("page %p is PG_UNHOLDFREE", m));
2257 /* Don't care: PG_NODUMP, PG_WINATCFLS, PG_ZERO. */
2258 if (object->type != OBJT_DEFAULT &&
2259 object->type != OBJT_SWAP &&
2260 object->type != OBJT_VNODE)
2262 else if ((m->flags & PG_CACHED) != 0 ||
2263 m != vm_page_lookup(object, m->pindex)) {
2265 * The page is cached or recently converted
2266 * from cached to free.
2268 #if VM_NRESERVLEVEL > 0
2271 * The page is reserved. Extend the
2272 * current run by one page.
2277 if ((order = m->order) < VM_NFREEORDER) {
2279 * The page is enqueued in the
2280 * physical memory allocator's cache/
2281 * free page queues. Moreover, it is
2282 * the first page in a power-of-two-
2283 * sized run of contiguous cache/free
2284 * pages. Add these pages to the end
2285 * of the current run, and jump
2288 run_ext = 1 << order;
2292 #if VM_NRESERVLEVEL > 0
2293 } else if ((options & VPSC_NOSUPER) != 0 &&
2294 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2296 /* Advance to the end of the superpage. */
2297 pa = VM_PAGE_TO_PHYS(m);
2298 m_inc = atop(roundup2(pa + 1,
2299 vm_reserv_size(level)) - pa);
2301 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2302 m->queue != PQ_NONE && !vm_page_busied(m)) {
2304 * The page is allocated but eligible for
2305 * relocation. Extend the current run by one
2308 KASSERT(pmap_page_get_memattr(m) ==
2310 ("page %p has an unexpected memattr", m));
2311 KASSERT((m->oflags & (VPO_SWAPINPROG |
2312 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2313 ("page %p has unexpected oflags", m));
2314 /* Don't care: VPO_NOSYNC. */
2319 VM_OBJECT_RUNLOCK(object);
2320 #if VM_NRESERVLEVEL > 0
2321 } else if (level >= 0) {
2323 * The page is reserved but not yet allocated. In
2324 * other words, it is still cached or free. Extend
2325 * the current run by one page.
2329 } else if ((order = m->order) < VM_NFREEORDER) {
2331 * The page is enqueued in the physical memory
2332 * allocator's cache/free page queues. Moreover, it
2333 * is the first page in a power-of-two-sized run of
2334 * contiguous cache/free pages. Add these pages to
2335 * the end of the current run, and jump ahead.
2337 run_ext = 1 << order;
2341 * Skip the page for one of the following reasons: (1)
2342 * It is enqueued in the physical memory allocator's
2343 * cache/free page queues. However, it is not the
2344 * first page in a run of contiguous cache/free pages.
2345 * (This case rarely occurs because the scan is
2346 * performed in ascending order.) (2) It is not
2347 * reserved, and it is transitioning from free to
2348 * allocated. (Conversely, the transition from
2349 * allocated to free for managed pages is blocked by
2350 * the page lock.) (3) It is allocated but not
2351 * contained by an object and not wired, e.g.,
2352 * allocated by Xen's balloon driver.
2358 * Extend or reset the current run of pages.
2373 if (run_len >= npages)
2379 * vm_page_reclaim_run:
2381 * Try to relocate each of the allocated virtual pages within the
2382 * specified run of physical pages to a new physical address. Free the
2383 * physical pages underlying the relocated virtual pages. A virtual page
2384 * is relocatable if and only if it could be laundered or reclaimed by
2385 * the page daemon. Whenever possible, a virtual page is relocated to a
2386 * physical address above "high".
2388 * Returns 0 if every physical page within the run was already free or
2389 * just freed by a successful relocation. Otherwise, returns a non-zero
2390 * value indicating why the last attempt to relocate a virtual page was
2393 * "req_class" must be an allocation class.
2396 vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
2399 struct mtx *m_mtx, *new_mtx;
2400 struct spglist free;
2403 vm_page_t m, m_end, m_new;
2404 int error, order, req;
2406 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2407 ("req_class is not an allocation class"));
2411 m_end = m_run + npages;
2413 for (; error == 0 && m < m_end; m++) {
2414 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2415 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2418 * Avoid releasing and reacquiring the same page lock.
2420 new_mtx = vm_page_lockptr(m);
2421 if (m_mtx != new_mtx) {
2428 if (m->wire_count != 0 || m->hold_count != 0)
2430 else if ((object = m->object) != NULL) {
2432 * The page is relocated if and only if it could be
2433 * laundered or reclaimed by the page daemon.
2435 if (!VM_OBJECT_TRYWLOCK(object)) {
2437 VM_OBJECT_WLOCK(object);
2439 if (m->object != object) {
2441 * The page may have been freed.
2443 VM_OBJECT_WUNLOCK(object);
2445 } else if (m->wire_count != 0 ||
2446 m->hold_count != 0) {
2451 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2452 ("page %p is PG_UNHOLDFREE", m));
2453 /* Don't care: PG_NODUMP, PG_WINATCFLS, PG_ZERO. */
2454 if (object->type != OBJT_DEFAULT &&
2455 object->type != OBJT_SWAP &&
2456 object->type != OBJT_VNODE)
2458 else if ((m->flags & PG_CACHED) != 0 ||
2459 m != vm_page_lookup(object, m->pindex)) {
2461 * The page is cached or recently converted
2462 * from cached to free.
2464 VM_OBJECT_WUNLOCK(object);
2466 } else if (object->memattr != VM_MEMATTR_DEFAULT)
2468 else if (m->queue != PQ_NONE && !vm_page_busied(m)) {
2469 KASSERT(pmap_page_get_memattr(m) ==
2471 ("page %p has an unexpected memattr", m));
2472 KASSERT((m->oflags & (VPO_SWAPINPROG |
2473 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2474 ("page %p has unexpected oflags", m));
2475 /* Don't care: VPO_NOSYNC. */
2476 if (m->valid != 0) {
2478 * First, try to allocate a new page
2479 * that is above "high". Failing
2480 * that, try to allocate a new page
2481 * that is below "m_run". Allocate
2482 * the new page between the end of
2483 * "m_run" and "high" only as a last
2486 req = req_class | VM_ALLOC_NOOBJ;
2487 if ((m->flags & PG_NODUMP) != 0)
2488 req |= VM_ALLOC_NODUMP;
2489 if (trunc_page(high) !=
2490 ~(vm_paddr_t)PAGE_MASK) {
2491 m_new = vm_page_alloc_contig(
2496 VM_MEMATTR_DEFAULT);
2499 if (m_new == NULL) {
2500 pa = VM_PAGE_TO_PHYS(m_run);
2501 m_new = vm_page_alloc_contig(
2503 0, pa - 1, PAGE_SIZE, 0,
2504 VM_MEMATTR_DEFAULT);
2506 if (m_new == NULL) {
2508 m_new = vm_page_alloc_contig(
2510 pa, high, PAGE_SIZE, 0,
2511 VM_MEMATTR_DEFAULT);
2513 if (m_new == NULL) {
2517 KASSERT(m_new->wire_count == 0,
2518 ("page %p is wired", m));
2521 * Replace "m" with the new page. For
2522 * vm_page_replace(), "m" must be busy
2523 * and dequeued. Finally, change "m"
2524 * as if vm_page_free() was called.
2526 if (object->ref_count != 0)
2528 m_new->aflags = m->aflags;
2529 KASSERT(m_new->oflags == VPO_UNMANAGED,
2530 ("page %p is managed", m));
2531 m_new->oflags = m->oflags & VPO_NOSYNC;
2532 pmap_copy_page(m, m_new);
2533 m_new->valid = m->valid;
2534 m_new->dirty = m->dirty;
2535 m->flags &= ~PG_ZERO;
2538 vm_page_replace_checked(m_new, object,
2544 * The new page must be deactivated
2545 * before the object is unlocked.
2547 new_mtx = vm_page_lockptr(m_new);
2548 if (m_mtx != new_mtx) {
2553 vm_page_deactivate(m_new);
2555 m->flags &= ~PG_ZERO;
2558 KASSERT(m->dirty == 0,
2559 ("page %p is dirty", m));
2561 SLIST_INSERT_HEAD(&free, m, plinks.s.ss);
2565 VM_OBJECT_WUNLOCK(object);
2568 mtx_lock(&vm_page_queue_free_mtx);
2570 if (order < VM_NFREEORDER) {
2572 * The page is enqueued in the physical memory
2573 * allocator's cache/free page queues.
2574 * Moreover, it is the first page in a power-
2575 * of-two-sized run of contiguous cache/free
2576 * pages. Jump ahead to the last page within
2577 * that run, and continue from there.
2579 m += (1 << order) - 1;
2581 #if VM_NRESERVLEVEL > 0
2582 else if (vm_reserv_is_page_free(m))
2585 mtx_unlock(&vm_page_queue_free_mtx);
2586 if (order == VM_NFREEORDER)
2592 if ((m = SLIST_FIRST(&free)) != NULL) {
2593 mtx_lock(&vm_page_queue_free_mtx);
2595 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2596 vm_phys_freecnt_adj(m, 1);
2597 #if VM_NRESERVLEVEL > 0
2598 if (!vm_reserv_free_page(m))
2602 vm_phys_free_pages(m, 0);
2603 } while ((m = SLIST_FIRST(&free)) != NULL);
2604 vm_page_free_wakeup();
2605 mtx_unlock(&vm_page_queue_free_mtx);
2612 CTASSERT(powerof2(NRUNS));
2614 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2616 #define MIN_RECLAIM 8
2619 * vm_page_reclaim_contig:
2621 * Reclaim allocated, contiguous physical memory satisfying the specified
2622 * conditions by relocating the virtual pages using that physical memory.
2623 * Returns true if reclamation is successful and false otherwise. Since
2624 * relocation requires the allocation of physical pages, reclamation may
2625 * fail due to a shortage of cache/free pages. When reclamation fails,
2626 * callers are expected to perform VM_WAIT before retrying a failed
2627 * allocation operation, e.g., vm_page_alloc_contig().
2629 * The caller must always specify an allocation class through "req".
2631 * allocation classes:
2632 * VM_ALLOC_NORMAL normal process request
2633 * VM_ALLOC_SYSTEM system *really* needs a page
2634 * VM_ALLOC_INTERRUPT interrupt time request
2636 * The optional allocation flags are ignored.
2638 * "npages" must be greater than zero. Both "alignment" and "boundary"
2639 * must be a power of two.
2642 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2643 u_long alignment, vm_paddr_t boundary)
2645 vm_paddr_t curr_low;
2646 vm_page_t m_run, m_runs[NRUNS];
2647 u_long count, reclaimed;
2648 int error, i, options, req_class;
2650 KASSERT(npages > 0, ("npages is 0"));
2651 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2652 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2653 req_class = req & VM_ALLOC_CLASS_MASK;
2656 * The page daemon is allowed to dig deeper into the free page list.
2658 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2659 req_class = VM_ALLOC_SYSTEM;
2662 * Return if the number of cached and free pages cannot satisfy the
2663 * requested allocation.
2665 count = vm_cnt.v_free_count + vm_cnt.v_cache_count;
2666 if (count < npages + vm_cnt.v_free_reserved || (count < npages +
2667 vm_cnt.v_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2668 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2672 * Scan up to three times, relaxing the restrictions ("options") on
2673 * the reclamation of reservations and superpages each time.
2675 for (options = VPSC_NORESERV;;) {
2677 * Find the highest runs that satisfy the given constraints
2678 * and restrictions, and record them in "m_runs".
2683 m_run = vm_phys_scan_contig(npages, curr_low, high,
2684 alignment, boundary, options);
2687 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2688 m_runs[RUN_INDEX(count)] = m_run;
2693 * Reclaim the highest runs in LIFO (descending) order until
2694 * the number of reclaimed pages, "reclaimed", is at least
2695 * MIN_RECLAIM. Reset "reclaimed" each time because each
2696 * reclamation is idempotent, and runs will (likely) recur
2697 * from one scan to the next as restrictions are relaxed.
2700 for (i = 0; count > 0 && i < NRUNS; i++) {
2702 m_run = m_runs[RUN_INDEX(count)];
2703 error = vm_page_reclaim_run(req_class, npages, m_run,
2706 reclaimed += npages;
2707 if (reclaimed >= MIN_RECLAIM)
2713 * Either relax the restrictions on the next scan or return if
2714 * the last scan had no restrictions.
2716 if (options == VPSC_NORESERV)
2717 options = VPSC_NOSUPER;
2718 else if (options == VPSC_NOSUPER)
2720 else if (options == VPSC_ANY)
2721 return (reclaimed != 0);
2726 * vm_wait: (also see VM_WAIT macro)
2728 * Sleep until free pages are available for allocation.
2729 * - Called in various places before memory allocations.
2735 mtx_lock(&vm_page_queue_free_mtx);
2736 if (curproc == pageproc) {
2737 vm_pageout_pages_needed = 1;
2738 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
2739 PDROP | PSWP, "VMWait", 0);
2741 if (!vm_pageout_wanted) {
2742 vm_pageout_wanted = true;
2743 wakeup(&vm_pageout_wanted);
2745 vm_pages_needed = true;
2746 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
2752 * vm_waitpfault: (also see VM_WAITPFAULT macro)
2754 * Sleep until free pages are available for allocation.
2755 * - Called only in vm_fault so that processes page faulting
2756 * can be easily tracked.
2757 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2758 * processes will be able to grab memory first. Do not change
2759 * this balance without careful testing first.
2765 mtx_lock(&vm_page_queue_free_mtx);
2766 if (!vm_pageout_wanted) {
2767 vm_pageout_wanted = true;
2768 wakeup(&vm_pageout_wanted);
2770 vm_pages_needed = true;
2771 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
2775 struct vm_pagequeue *
2776 vm_page_pagequeue(vm_page_t m)
2779 return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2785 * Remove the given page from its current page queue.
2787 * The page must be locked.
2790 vm_page_dequeue(vm_page_t m)
2792 struct vm_pagequeue *pq;
2794 vm_page_assert_locked(m);
2795 KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
2797 pq = vm_page_pagequeue(m);
2798 vm_pagequeue_lock(pq);
2800 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2801 vm_pagequeue_cnt_dec(pq);
2802 vm_pagequeue_unlock(pq);
2806 * vm_page_dequeue_locked:
2808 * Remove the given page from its current page queue.
2810 * The page and page queue must be locked.
2813 vm_page_dequeue_locked(vm_page_t m)
2815 struct vm_pagequeue *pq;
2817 vm_page_lock_assert(m, MA_OWNED);
2818 pq = vm_page_pagequeue(m);
2819 vm_pagequeue_assert_locked(pq);
2821 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2822 vm_pagequeue_cnt_dec(pq);
2828 * Add the given page to the specified page queue.
2830 * The page must be locked.
2833 vm_page_enqueue(uint8_t queue, vm_page_t m)
2835 struct vm_pagequeue *pq;
2837 vm_page_lock_assert(m, MA_OWNED);
2838 KASSERT(queue < PQ_COUNT,
2839 ("vm_page_enqueue: invalid queue %u request for page %p",
2841 pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2842 vm_pagequeue_lock(pq);
2844 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2845 vm_pagequeue_cnt_inc(pq);
2846 vm_pagequeue_unlock(pq);
2852 * Move the given page to the tail of its current page queue.
2854 * The page must be locked.
2857 vm_page_requeue(vm_page_t m)
2859 struct vm_pagequeue *pq;
2861 vm_page_lock_assert(m, MA_OWNED);
2862 KASSERT(m->queue != PQ_NONE,
2863 ("vm_page_requeue: page %p is not queued", m));
2864 pq = vm_page_pagequeue(m);
2865 vm_pagequeue_lock(pq);
2866 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2867 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2868 vm_pagequeue_unlock(pq);
2872 * vm_page_requeue_locked:
2874 * Move the given page to the tail of its current page queue.
2876 * The page queue must be locked.
2879 vm_page_requeue_locked(vm_page_t m)
2881 struct vm_pagequeue *pq;
2883 KASSERT(m->queue != PQ_NONE,
2884 ("vm_page_requeue_locked: page %p is not queued", m));
2885 pq = vm_page_pagequeue(m);
2886 vm_pagequeue_assert_locked(pq);
2887 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2888 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2894 * Put the specified page on the active list (if appropriate).
2895 * Ensure that act_count is at least ACT_INIT but do not otherwise
2898 * The page must be locked.
2901 vm_page_activate(vm_page_t m)
2905 vm_page_lock_assert(m, MA_OWNED);
2906 if ((queue = m->queue) != PQ_ACTIVE) {
2907 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2908 if (m->act_count < ACT_INIT)
2909 m->act_count = ACT_INIT;
2910 if (queue != PQ_NONE)
2912 vm_page_enqueue(PQ_ACTIVE, m);
2914 KASSERT(queue == PQ_NONE,
2915 ("vm_page_activate: wired page %p is queued", m));
2917 if (m->act_count < ACT_INIT)
2918 m->act_count = ACT_INIT;
2923 * vm_page_free_wakeup:
2925 * Helper routine for vm_page_free_toq() and vm_page_cache(). This
2926 * routine is called when a page has been added to the cache or free
2929 * The page queues must be locked.
2932 vm_page_free_wakeup(void)
2935 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2937 * if pageout daemon needs pages, then tell it that there are
2940 if (vm_pageout_pages_needed &&
2941 vm_cnt.v_cache_count + vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
2942 wakeup(&vm_pageout_pages_needed);
2943 vm_pageout_pages_needed = 0;
2946 * wakeup processes that are waiting on memory if we hit a
2947 * high water mark. And wakeup scheduler process if we have
2948 * lots of memory. this process will swapin processes.
2950 if (vm_pages_needed && !vm_page_count_min()) {
2951 vm_pages_needed = false;
2952 wakeup(&vm_cnt.v_free_count);
2957 * Turn a cached page into a free page, by changing its attributes.
2958 * Keep the statistics up-to-date.
2960 * The free page queue must be locked.
2963 vm_page_cache_turn_free(vm_page_t m)
2966 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2970 KASSERT((m->flags & PG_CACHED) != 0,
2971 ("vm_page_cache_turn_free: page %p is not cached", m));
2972 m->flags &= ~PG_CACHED;
2973 vm_cnt.v_cache_count--;
2974 vm_phys_freecnt_adj(m, 1);
2980 * Returns the given page to the free list,
2981 * disassociating it with any VM object.
2983 * The object must be locked. The page must be locked if it is managed.
2986 vm_page_free_toq(vm_page_t m)
2989 if ((m->oflags & VPO_UNMANAGED) == 0) {
2990 vm_page_lock_assert(m, MA_OWNED);
2991 KASSERT(!pmap_page_is_mapped(m),
2992 ("vm_page_free_toq: freeing mapped page %p", m));
2994 KASSERT(m->queue == PQ_NONE,
2995 ("vm_page_free_toq: unmanaged page %p is queued", m));
2996 PCPU_INC(cnt.v_tfree);
2998 if (vm_page_sbusied(m))
2999 panic("vm_page_free: freeing busy page %p", m);
3002 * Unqueue, then remove page. Note that we cannot destroy
3003 * the page here because we do not want to call the pager's
3004 * callback routine until after we've put the page on the
3005 * appropriate free queue.
3011 * If fictitious remove object association and
3012 * return, otherwise delay object association removal.
3014 if ((m->flags & PG_FICTITIOUS) != 0) {
3021 if (m->wire_count != 0)
3022 panic("vm_page_free: freeing wired page %p", m);
3023 if (m->hold_count != 0) {
3024 m->flags &= ~PG_ZERO;
3025 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
3026 ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
3027 m->flags |= PG_UNHOLDFREE;
3030 * Restore the default memory attribute to the page.
3032 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3033 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3036 * Insert the page into the physical memory allocator's
3037 * cache/free page queues.
3039 mtx_lock(&vm_page_queue_free_mtx);
3040 vm_phys_freecnt_adj(m, 1);
3041 #if VM_NRESERVLEVEL > 0
3042 if (!vm_reserv_free_page(m))
3046 vm_phys_free_pages(m, 0);
3047 vm_page_free_wakeup();
3048 mtx_unlock(&vm_page_queue_free_mtx);
3055 * Mark this page as wired down by yet
3056 * another map, removing it from paging queues
3059 * If the page is fictitious, then its wire count must remain one.
3061 * The page must be locked.
3064 vm_page_wire(vm_page_t m)
3068 * Only bump the wire statistics if the page is not already wired,
3069 * and only unqueue the page if it is on some queue (if it is unmanaged
3070 * it is already off the queues).
3072 vm_page_lock_assert(m, MA_OWNED);
3073 if ((m->flags & PG_FICTITIOUS) != 0) {
3074 KASSERT(m->wire_count == 1,
3075 ("vm_page_wire: fictitious page %p's wire count isn't one",
3079 if (m->wire_count == 0) {
3080 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
3081 m->queue == PQ_NONE,
3082 ("vm_page_wire: unmanaged page %p is queued", m));
3084 atomic_add_int(&vm_cnt.v_wire_count, 1);
3087 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
3093 * Release one wiring of the specified page, potentially allowing it to be
3094 * paged out. Returns TRUE if the number of wirings transitions to zero and
3097 * Only managed pages belonging to an object can be paged out. If the number
3098 * of wirings transitions to zero and the page is eligible for page out, then
3099 * the page is added to the specified paging queue (unless PQ_NONE is
3102 * If a page is fictitious, then its wire count must always be one.
3104 * A managed page must be locked.
3107 vm_page_unwire(vm_page_t m, uint8_t queue)
3110 KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
3111 ("vm_page_unwire: invalid queue %u request for page %p",
3113 if ((m->oflags & VPO_UNMANAGED) == 0)
3114 vm_page_assert_locked(m);
3115 if ((m->flags & PG_FICTITIOUS) != 0) {
3116 KASSERT(m->wire_count == 1,
3117 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
3120 if (m->wire_count > 0) {
3122 if (m->wire_count == 0) {
3123 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3124 if ((m->oflags & VPO_UNMANAGED) == 0 &&
3125 m->object != NULL && queue != PQ_NONE) {
3126 if (queue == PQ_INACTIVE)
3127 m->flags &= ~PG_WINATCFLS;
3128 vm_page_enqueue(queue, m);
3134 panic("vm_page_unwire: page %p's wire count is zero", m);
3138 * Move the specified page to the inactive queue.
3140 * Many pages placed on the inactive queue should actually go
3141 * into the cache, but it is difficult to figure out which. What
3142 * we do instead, if the inactive target is well met, is to put
3143 * clean pages at the head of the inactive queue instead of the tail.
3144 * This will cause them to be moved to the cache more quickly and
3145 * if not actively re-referenced, reclaimed more quickly. If we just
3146 * stick these pages at the end of the inactive queue, heavy filesystem
3147 * meta-data accesses can cause an unnecessary paging load on memory bound
3148 * processes. This optimization causes one-time-use metadata to be
3149 * reused more quickly.
3151 * Normally noreuse is FALSE, resulting in LRU operation. noreuse is set
3152 * to TRUE if we want this page to be 'as if it were placed in the cache',
3153 * except without unmapping it from the process address space. In
3154 * practice this is implemented by inserting the page at the head of the
3155 * queue, using a marker page to guide FIFO insertion ordering.
3157 * The page must be locked.
3160 _vm_page_deactivate(vm_page_t m, boolean_t noreuse)
3162 struct vm_pagequeue *pq;
3165 vm_page_assert_locked(m);
3168 * Ignore if the page is already inactive, unless it is unlikely to be
3171 if ((queue = m->queue) == PQ_INACTIVE && !noreuse)
3173 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
3174 pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
3175 /* Avoid multiple acquisitions of the inactive queue lock. */
3176 if (queue == PQ_INACTIVE) {
3177 vm_pagequeue_lock(pq);
3178 vm_page_dequeue_locked(m);
3180 if (queue != PQ_NONE)
3182 m->flags &= ~PG_WINATCFLS;
3183 vm_pagequeue_lock(pq);
3185 m->queue = PQ_INACTIVE;
3187 TAILQ_INSERT_BEFORE(&vm_phys_domain(m)->vmd_inacthead,
3190 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3191 vm_pagequeue_cnt_inc(pq);
3192 vm_pagequeue_unlock(pq);
3197 * Move the specified page to the inactive queue.
3199 * The page must be locked.
3202 vm_page_deactivate(vm_page_t m)
3205 _vm_page_deactivate(m, FALSE);
3209 * Move the specified page to the inactive queue with the expectation
3210 * that it is unlikely to be reused.
3212 * The page must be locked.
3215 vm_page_deactivate_noreuse(vm_page_t m)
3218 _vm_page_deactivate(m, TRUE);
3222 * vm_page_try_to_cache:
3224 * Returns 0 on failure, 1 on success
3227 vm_page_try_to_cache(vm_page_t m)
3230 vm_page_lock_assert(m, MA_OWNED);
3231 VM_OBJECT_ASSERT_WLOCKED(m->object);
3232 if (m->dirty || m->hold_count || m->wire_count ||
3233 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
3243 * vm_page_try_to_free()
3245 * Attempt to free the page. If we cannot free it, we do nothing.
3246 * 1 is returned on success, 0 on failure.
3249 vm_page_try_to_free(vm_page_t m)
3252 vm_page_lock_assert(m, MA_OWNED);
3253 if (m->object != NULL)
3254 VM_OBJECT_ASSERT_WLOCKED(m->object);
3255 if (m->dirty || m->hold_count || m->wire_count ||
3256 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
3268 * Put the specified page onto the page cache queue (if appropriate).
3270 * The object and page must be locked.
3273 vm_page_cache(vm_page_t m)
3276 boolean_t cache_was_empty;
3278 vm_page_lock_assert(m, MA_OWNED);
3280 VM_OBJECT_ASSERT_WLOCKED(object);
3281 if (vm_page_busied(m) || (m->oflags & VPO_UNMANAGED) ||
3282 m->hold_count || m->wire_count)
3283 panic("vm_page_cache: attempting to cache busy page");
3284 KASSERT(!pmap_page_is_mapped(m),
3285 ("vm_page_cache: page %p is mapped", m));
3286 KASSERT(m->dirty == 0, ("vm_page_cache: page %p is dirty", m));
3287 if (m->valid == 0 || object->type == OBJT_DEFAULT ||
3288 (object->type == OBJT_SWAP &&
3289 !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
3291 * Hypothesis: A cache-eligible page belonging to a
3292 * default object or swap object but without a backing
3293 * store must be zero filled.
3298 KASSERT((m->flags & PG_CACHED) == 0,
3299 ("vm_page_cache: page %p is already cached", m));
3302 * Remove the page from the paging queues.
3307 * Remove the page from the object's collection of resident
3310 vm_radix_remove(&object->rtree, m->pindex);
3311 TAILQ_REMOVE(&object->memq, m, listq);
3312 object->resident_page_count--;
3315 * Restore the default memory attribute to the page.
3317 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3318 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3321 * Insert the page into the object's collection of cached pages
3322 * and the physical memory allocator's cache/free page queues.
3324 m->flags &= ~PG_ZERO;
3325 mtx_lock(&vm_page_queue_free_mtx);
3326 cache_was_empty = vm_radix_is_empty(&object->cache);
3327 if (vm_radix_insert(&object->cache, m)) {
3328 mtx_unlock(&vm_page_queue_free_mtx);
3329 if (object->type == OBJT_VNODE &&
3330 object->resident_page_count == 0)
3331 vdrop(object->handle);
3338 * The above call to vm_radix_insert() could reclaim the one pre-
3339 * existing cached page from this object, resulting in a call to
3342 if (!cache_was_empty)
3343 cache_was_empty = vm_radix_is_singleton(&object->cache);
3345 m->flags |= PG_CACHED;
3346 vm_cnt.v_cache_count++;
3347 PCPU_INC(cnt.v_tcached);
3348 #if VM_NRESERVLEVEL > 0
3349 if (!vm_reserv_free_page(m)) {
3353 vm_phys_free_pages(m, 0);
3355 vm_page_free_wakeup();
3356 mtx_unlock(&vm_page_queue_free_mtx);
3359 * Increment the vnode's hold count if this is the object's only
3360 * cached page. Decrement the vnode's hold count if this was
3361 * the object's only resident page.
3363 if (object->type == OBJT_VNODE) {
3364 if (cache_was_empty && object->resident_page_count != 0)
3365 vhold(object->handle);
3366 else if (!cache_was_empty && object->resident_page_count == 0)
3367 vdrop(object->handle);
3374 * Deactivate or do nothing, as appropriate.
3376 * The object and page must be locked.
3379 vm_page_advise(vm_page_t m, int advice)
3382 vm_page_assert_locked(m);
3383 VM_OBJECT_ASSERT_WLOCKED(m->object);
3384 if (advice == MADV_FREE)
3386 * Mark the page clean. This will allow the page to be freed
3387 * up by the system. However, such pages are often reused
3388 * quickly by malloc() so we do not do anything that would
3389 * cause a page fault if we can help it.
3391 * Specifically, we do not try to actually free the page now
3392 * nor do we try to put it in the cache (which would cause a
3393 * page fault on reuse).
3395 * But we do make the page as freeable as we can without
3396 * actually taking the step of unmapping it.
3399 else if (advice != MADV_DONTNEED)
3403 * Clear any references to the page. Otherwise, the page daemon will
3404 * immediately reactivate the page.
3406 vm_page_aflag_clear(m, PGA_REFERENCED);
3408 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3412 * Place clean pages near the head of the inactive queue rather than
3413 * the tail, thus defeating the queue's LRU operation and ensuring that
3414 * the page will be reused quickly. Dirty pages are given a chance to
3415 * cycle once through the inactive queue before becoming eligible for
3418 _vm_page_deactivate(m, m->dirty == 0);
3422 * Grab a page, waiting until we are waken up due to the page
3423 * changing state. We keep on waiting, if the page continues
3424 * to be in the object. If the page doesn't exist, first allocate it
3425 * and then conditionally zero it.
3427 * This routine may sleep.
3429 * The object must be locked on entry. The lock will, however, be released
3430 * and reacquired if the routine sleeps.
3433 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3438 VM_OBJECT_ASSERT_WLOCKED(object);
3439 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3440 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3441 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3443 if ((m = vm_page_lookup(object, pindex)) != NULL) {
3444 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3445 vm_page_xbusied(m) : vm_page_busied(m);
3447 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3450 * Reference the page before unlocking and
3451 * sleeping so that the page daemon is less
3452 * likely to reclaim it.
3454 vm_page_aflag_set(m, PGA_REFERENCED);
3456 VM_OBJECT_WUNLOCK(object);
3457 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
3458 VM_ALLOC_IGN_SBUSY) != 0);
3459 VM_OBJECT_WLOCK(object);
3462 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3468 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3470 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3475 m = vm_page_alloc(object, pindex, allocflags);
3477 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3479 VM_OBJECT_WUNLOCK(object);
3481 VM_OBJECT_WLOCK(object);
3483 } else if (m->valid != 0)
3485 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3491 * Mapping function for valid or dirty bits in a page.
3493 * Inputs are required to range within a page.
3496 vm_page_bits(int base, int size)
3502 base + size <= PAGE_SIZE,
3503 ("vm_page_bits: illegal base/size %d/%d", base, size)
3506 if (size == 0) /* handle degenerate case */
3509 first_bit = base >> DEV_BSHIFT;
3510 last_bit = (base + size - 1) >> DEV_BSHIFT;
3512 return (((vm_page_bits_t)2 << last_bit) -
3513 ((vm_page_bits_t)1 << first_bit));
3517 * vm_page_set_valid_range:
3519 * Sets portions of a page valid. The arguments are expected
3520 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3521 * of any partial chunks touched by the range. The invalid portion of
3522 * such chunks will be zeroed.
3524 * (base + size) must be less then or equal to PAGE_SIZE.
3527 vm_page_set_valid_range(vm_page_t m, int base, int size)
3531 VM_OBJECT_ASSERT_WLOCKED(m->object);
3532 if (size == 0) /* handle degenerate case */
3536 * If the base is not DEV_BSIZE aligned and the valid
3537 * bit is clear, we have to zero out a portion of the
3540 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3541 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
3542 pmap_zero_page_area(m, frag, base - frag);
3545 * If the ending offset is not DEV_BSIZE aligned and the
3546 * valid bit is clear, we have to zero out a portion of
3549 endoff = base + size;
3550 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3551 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
3552 pmap_zero_page_area(m, endoff,
3553 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3556 * Assert that no previously invalid block that is now being validated
3559 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
3560 ("vm_page_set_valid_range: page %p is dirty", m));
3563 * Set valid bits inclusive of any overlap.
3565 m->valid |= vm_page_bits(base, size);
3569 * Clear the given bits from the specified page's dirty field.
3571 static __inline void
3572 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
3575 #if PAGE_SIZE < 16384
3580 * If the object is locked and the page is neither exclusive busy nor
3581 * write mapped, then the page's dirty field cannot possibly be
3582 * set by a concurrent pmap operation.
3584 VM_OBJECT_ASSERT_WLOCKED(m->object);
3585 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
3586 m->dirty &= ~pagebits;
3589 * The pmap layer can call vm_page_dirty() without
3590 * holding a distinguished lock. The combination of
3591 * the object's lock and an atomic operation suffice
3592 * to guarantee consistency of the page dirty field.
3594 * For PAGE_SIZE == 32768 case, compiler already
3595 * properly aligns the dirty field, so no forcible
3596 * alignment is needed. Only require existence of
3597 * atomic_clear_64 when page size is 32768.
3599 addr = (uintptr_t)&m->dirty;
3600 #if PAGE_SIZE == 32768
3601 atomic_clear_64((uint64_t *)addr, pagebits);
3602 #elif PAGE_SIZE == 16384
3603 atomic_clear_32((uint32_t *)addr, pagebits);
3604 #else /* PAGE_SIZE <= 8192 */
3606 * Use a trick to perform a 32-bit atomic on the
3607 * containing aligned word, to not depend on the existence
3608 * of atomic_clear_{8, 16}.
3610 shift = addr & (sizeof(uint32_t) - 1);
3611 #if BYTE_ORDER == BIG_ENDIAN
3612 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
3616 addr &= ~(sizeof(uint32_t) - 1);
3617 atomic_clear_32((uint32_t *)addr, pagebits << shift);
3618 #endif /* PAGE_SIZE */
3623 * vm_page_set_validclean:
3625 * Sets portions of a page valid and clean. The arguments are expected
3626 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3627 * of any partial chunks touched by the range. The invalid portion of
3628 * such chunks will be zero'd.
3630 * (base + size) must be less then or equal to PAGE_SIZE.
3633 vm_page_set_validclean(vm_page_t m, int base, int size)
3635 vm_page_bits_t oldvalid, pagebits;
3638 VM_OBJECT_ASSERT_WLOCKED(m->object);
3639 if (size == 0) /* handle degenerate case */
3643 * If the base is not DEV_BSIZE aligned and the valid
3644 * bit is clear, we have to zero out a portion of the
3647 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3648 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
3649 pmap_zero_page_area(m, frag, base - frag);
3652 * If the ending offset is not DEV_BSIZE aligned and the
3653 * valid bit is clear, we have to zero out a portion of
3656 endoff = base + size;
3657 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3658 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
3659 pmap_zero_page_area(m, endoff,
3660 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3663 * Set valid, clear dirty bits. If validating the entire
3664 * page we can safely clear the pmap modify bit. We also
3665 * use this opportunity to clear the VPO_NOSYNC flag. If a process
3666 * takes a write fault on a MAP_NOSYNC memory area the flag will
3669 * We set valid bits inclusive of any overlap, but we can only
3670 * clear dirty bits for DEV_BSIZE chunks that are fully within
3673 oldvalid = m->valid;
3674 pagebits = vm_page_bits(base, size);
3675 m->valid |= pagebits;
3677 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
3678 frag = DEV_BSIZE - frag;
3684 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
3686 if (base == 0 && size == PAGE_SIZE) {
3688 * The page can only be modified within the pmap if it is
3689 * mapped, and it can only be mapped if it was previously
3692 if (oldvalid == VM_PAGE_BITS_ALL)
3694 * Perform the pmap_clear_modify() first. Otherwise,
3695 * a concurrent pmap operation, such as
3696 * pmap_protect(), could clear a modification in the
3697 * pmap and set the dirty field on the page before
3698 * pmap_clear_modify() had begun and after the dirty
3699 * field was cleared here.
3701 pmap_clear_modify(m);
3703 m->oflags &= ~VPO_NOSYNC;
3704 } else if (oldvalid != VM_PAGE_BITS_ALL)
3705 m->dirty &= ~pagebits;
3707 vm_page_clear_dirty_mask(m, pagebits);
3711 vm_page_clear_dirty(vm_page_t m, int base, int size)
3714 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
3718 * vm_page_set_invalid:
3720 * Invalidates DEV_BSIZE'd chunks within a page. Both the
3721 * valid and dirty bits for the effected areas are cleared.
3724 vm_page_set_invalid(vm_page_t m, int base, int size)
3726 vm_page_bits_t bits;
3730 VM_OBJECT_ASSERT_WLOCKED(object);
3731 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
3732 size >= object->un_pager.vnp.vnp_size)
3733 bits = VM_PAGE_BITS_ALL;
3735 bits = vm_page_bits(base, size);
3736 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
3739 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3740 !pmap_page_is_mapped(m),
3741 ("vm_page_set_invalid: page %p is mapped", m));
3747 * vm_page_zero_invalid()
3749 * The kernel assumes that the invalid portions of a page contain
3750 * garbage, but such pages can be mapped into memory by user code.
3751 * When this occurs, we must zero out the non-valid portions of the
3752 * page so user code sees what it expects.
3754 * Pages are most often semi-valid when the end of a file is mapped
3755 * into memory and the file's size is not page aligned.
3758 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3763 VM_OBJECT_ASSERT_WLOCKED(m->object);
3765 * Scan the valid bits looking for invalid sections that
3766 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
3767 * valid bit may be set ) have already been zeroed by
3768 * vm_page_set_validclean().
3770 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3771 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3772 (m->valid & ((vm_page_bits_t)1 << i))) {
3774 pmap_zero_page_area(m,
3775 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3782 * setvalid is TRUE when we can safely set the zero'd areas
3783 * as being valid. We can do this if there are no cache consistancy
3784 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3787 m->valid = VM_PAGE_BITS_ALL;
3793 * Is (partial) page valid? Note that the case where size == 0
3794 * will return FALSE in the degenerate case where the page is
3795 * entirely invalid, and TRUE otherwise.
3798 vm_page_is_valid(vm_page_t m, int base, int size)
3800 vm_page_bits_t bits;
3802 VM_OBJECT_ASSERT_LOCKED(m->object);
3803 bits = vm_page_bits(base, size);
3804 return (m->valid != 0 && (m->valid & bits) == bits);
3808 * vm_page_ps_is_valid:
3810 * Returns TRUE if the entire (super)page is valid and FALSE otherwise.
3813 vm_page_ps_is_valid(vm_page_t m)
3817 VM_OBJECT_ASSERT_LOCKED(m->object);
3818 npages = atop(pagesizes[m->psind]);
3821 * The physically contiguous pages that make up a superpage, i.e., a
3822 * page with a page size index ("psind") greater than zero, will
3823 * occupy adjacent entries in vm_page_array[].
3825 for (i = 0; i < npages; i++) {
3826 if (m[i].valid != VM_PAGE_BITS_ALL)
3833 * Set the page's dirty bits if the page is modified.
3836 vm_page_test_dirty(vm_page_t m)
3839 VM_OBJECT_ASSERT_WLOCKED(m->object);
3840 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3845 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3848 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3852 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3855 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3859 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3862 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3865 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3867 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3870 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3874 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3877 mtx_assert_(vm_page_lockptr(m), a, file, line);
3883 vm_page_object_lock_assert(vm_page_t m)
3887 * Certain of the page's fields may only be modified by the
3888 * holder of the containing object's lock or the exclusive busy.
3889 * holder. Unfortunately, the holder of the write busy is
3890 * not recorded, and thus cannot be checked here.
3892 if (m->object != NULL && !vm_page_xbusied(m))
3893 VM_OBJECT_ASSERT_WLOCKED(m->object);
3897 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3900 if ((bits & PGA_WRITEABLE) == 0)
3904 * The PGA_WRITEABLE flag can only be set if the page is
3905 * managed, is exclusively busied or the object is locked.
3906 * Currently, this flag is only set by pmap_enter().
3908 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3909 ("PGA_WRITEABLE on unmanaged page"));
3910 if (!vm_page_xbusied(m))
3911 VM_OBJECT_ASSERT_LOCKED(m->object);
3915 #include "opt_ddb.h"
3917 #include <sys/kernel.h>
3919 #include <ddb/ddb.h>
3921 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3923 db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
3924 db_printf("vm_cnt.v_cache_count: %d\n", vm_cnt.v_cache_count);
3925 db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
3926 db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
3927 db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
3928 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
3929 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
3930 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
3931 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
3934 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3938 db_printf("pq_free %d pq_cache %d\n",
3939 vm_cnt.v_free_count, vm_cnt.v_cache_count);
3940 for (dom = 0; dom < vm_ndomains; dom++) {
3941 db_printf("dom %d page_cnt %d free %d pq_act %d pq_inact %d\n",
3943 vm_dom[dom].vmd_page_count,
3944 vm_dom[dom].vmd_free_count,
3945 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3946 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt);
3950 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3956 db_printf("show pginfo addr\n");
3960 phys = strchr(modif, 'p') != NULL;
3962 m = PHYS_TO_VM_PAGE(addr);
3964 m = (vm_page_t)addr;
3966 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3967 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3968 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3969 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3970 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);