2 * SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)
4 * Copyright (c) 1991 Regents of the University of California.
6 * Copyright (c) 1998 Matthew Dillon. All Rights Reserved.
8 * This code is derived from software contributed to Berkeley by
9 * The Mach Operating System project at Carnegie-Mellon University.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * from: @(#)vm_page.c 7.4 (Berkeley) 5/7/91
39 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
40 * All rights reserved.
42 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
44 * Permission to use, copy, modify and distribute this software and
45 * its documentation is hereby granted, provided that both the copyright
46 * notice and this permission notice appear in all copies of the
47 * software, derivative works or modified versions, and any portions
48 * thereof, and that both notices appear in supporting documentation.
50 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
51 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
52 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
54 * Carnegie Mellon requests users of this software to return to
56 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
57 * School of Computer Science
58 * Carnegie Mellon University
59 * Pittsburgh PA 15213-3890
61 * any improvements or extensions that they make and grant Carnegie the
62 * rights to redistribute these changes.
66 * Resident memory management module.
69 #include <sys/cdefs.h>
70 __FBSDID("$FreeBSD$");
74 #include <sys/param.h>
75 #include <sys/systm.h>
77 #include <sys/domainset.h>
78 #include <sys/kernel.h>
79 #include <sys/limits.h>
80 #include <sys/linker.h>
81 #include <sys/malloc.h>
83 #include <sys/msgbuf.h>
84 #include <sys/mutex.h>
86 #include <sys/rwlock.h>
87 #include <sys/sleepqueue.h>
89 #include <sys/sched.h>
91 #include <sys/sysctl.h>
92 #include <sys/vmmeter.h>
93 #include <sys/vnode.h>
97 #include <vm/vm_param.h>
98 #include <vm/vm_domainset.h>
99 #include <vm/vm_kern.h>
100 #include <vm/vm_map.h>
101 #include <vm/vm_object.h>
102 #include <vm/vm_page.h>
103 #include <vm/vm_pageout.h>
104 #include <vm/vm_phys.h>
105 #include <vm/vm_pagequeue.h>
106 #include <vm/vm_pager.h>
107 #include <vm/vm_radix.h>
108 #include <vm/vm_reserv.h>
109 #include <vm/vm_extern.h>
111 #include <vm/uma_int.h>
113 #include <machine/md_var.h>
115 extern int uma_startup_count(int);
116 extern void uma_startup(void *, int);
117 extern int vmem_startup_count(void);
119 struct vm_domain vm_dom[MAXMEMDOM];
121 DPCPU_DEFINE_STATIC(struct vm_batchqueue, pqbatch[MAXMEMDOM][PQ_COUNT]);
123 struct mtx_padalign __exclusive_cache_line pa_lock[PA_LOCK_COUNT];
125 struct mtx_padalign __exclusive_cache_line vm_domainset_lock;
126 /* The following fields are protected by the domainset lock. */
127 domainset_t __exclusive_cache_line vm_min_domains;
128 domainset_t __exclusive_cache_line vm_severe_domains;
129 static int vm_min_waiters;
130 static int vm_severe_waiters;
131 static int vm_pageproc_waiters;
134 * bogus page -- for I/O to/from partially complete buffers,
135 * or for paging into sparsely invalid regions.
137 vm_page_t bogus_page;
139 vm_page_t vm_page_array;
140 long vm_page_array_size;
143 static int boot_pages;
144 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
146 "number of pages allocated for bootstrapping the VM system");
148 static int pa_tryrelock_restart;
149 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
150 &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
152 static TAILQ_HEAD(, vm_page) blacklist_head;
153 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
154 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
155 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
157 static uma_zone_t fakepg_zone;
159 static void vm_page_alloc_check(vm_page_t m);
160 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
161 static void vm_page_dequeue_complete(vm_page_t m);
162 static void vm_page_enqueue(vm_page_t m, uint8_t queue);
163 static void vm_page_init(void *dummy);
164 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
165 vm_pindex_t pindex, vm_page_t mpred);
166 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
168 static void vm_page_mvqueue(vm_page_t m, uint8_t queue);
169 static int vm_page_reclaim_run(int req_class, int domain, u_long npages,
170 vm_page_t m_run, vm_paddr_t high);
171 static int vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object,
173 static int vm_page_zone_import(void *arg, void **store, int cnt, int domain,
175 static void vm_page_zone_release(void *arg, void **store, int cnt);
177 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
180 vm_page_init(void *dummy)
183 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
184 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
185 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
186 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
190 * The cache page zone is initialized later since we need to be able to allocate
191 * pages before UMA is fully initialized.
194 vm_page_init_cache_zones(void *dummy __unused)
196 struct vm_domain *vmd;
197 struct vm_pgcache *pgcache;
200 for (domain = 0; domain < vm_ndomains; domain++) {
201 vmd = VM_DOMAIN(domain);
204 * Don't allow the page caches to take up more than .25% of
207 if (vmd->vmd_page_count / 400 < 256 * mp_ncpus * VM_NFREEPOOL)
209 for (pool = 0; pool < VM_NFREEPOOL; pool++) {
210 pgcache = &vmd->vmd_pgcache[pool];
211 pgcache->domain = domain;
212 pgcache->pool = pool;
213 pgcache->zone = uma_zcache_create("vm pgcache",
214 sizeof(struct vm_page), NULL, NULL, NULL, NULL,
215 vm_page_zone_import, vm_page_zone_release, pgcache,
216 UMA_ZONE_MAXBUCKET | UMA_ZONE_VM);
217 (void)uma_zone_set_maxcache(pgcache->zone, 0);
221 SYSINIT(vm_page2, SI_SUB_VM_CONF, SI_ORDER_ANY, vm_page_init_cache_zones, NULL);
223 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
224 #if PAGE_SIZE == 32768
226 CTASSERT(sizeof(u_long) >= 8);
231 * Try to acquire a physical address lock while a pmap is locked. If we
232 * fail to trylock we unlock and lock the pmap directly and cache the
233 * locked pa in *locked. The caller should then restart their loop in case
234 * the virtual to physical mapping has changed.
237 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
244 PA_LOCK_ASSERT(lockpa, MA_OWNED);
245 if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
252 atomic_add_int(&pa_tryrelock_restart, 1);
261 * Sets the page size, perhaps based upon the memory
262 * size. Must be called before any use of page-size
263 * dependent functions.
266 vm_set_page_size(void)
268 if (vm_cnt.v_page_size == 0)
269 vm_cnt.v_page_size = PAGE_SIZE;
270 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
271 panic("vm_set_page_size: page size not a power of two");
275 * vm_page_blacklist_next:
277 * Find the next entry in the provided string of blacklist
278 * addresses. Entries are separated by space, comma, or newline.
279 * If an invalid integer is encountered then the rest of the
280 * string is skipped. Updates the list pointer to the next
281 * character, or NULL if the string is exhausted or invalid.
284 vm_page_blacklist_next(char **list, char *end)
289 if (list == NULL || *list == NULL)
297 * If there's no end pointer then the buffer is coming from
298 * the kenv and we know it's null-terminated.
301 end = *list + strlen(*list);
303 /* Ensure that strtoq() won't walk off the end */
305 if (*end == '\n' || *end == ' ' || *end == ',')
308 printf("Blacklist not terminated, skipping\n");
314 for (pos = *list; *pos != '\0'; pos = cp) {
315 bad = strtoq(pos, &cp, 0);
316 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
325 if (*cp == '\0' || ++cp >= end)
329 return (trunc_page(bad));
331 printf("Garbage in RAM blacklist, skipping\n");
337 vm_page_blacklist_add(vm_paddr_t pa, bool verbose)
339 struct vm_domain *vmd;
343 m = vm_phys_paddr_to_vm_page(pa);
345 return (true); /* page does not exist, no failure */
347 vmd = vm_pagequeue_domain(m);
348 vm_domain_free_lock(vmd);
349 ret = vm_phys_unfree_page(m);
350 vm_domain_free_unlock(vmd);
352 vm_domain_freecnt_inc(vmd, -1);
353 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
355 printf("Skipping page with pa 0x%jx\n", (uintmax_t)pa);
361 * vm_page_blacklist_check:
363 * Iterate through the provided string of blacklist addresses, pulling
364 * each entry out of the physical allocator free list and putting it
365 * onto a list for reporting via the vm.page_blacklist sysctl.
368 vm_page_blacklist_check(char *list, char *end)
374 while (next != NULL) {
375 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
377 vm_page_blacklist_add(pa, bootverbose);
382 * vm_page_blacklist_load:
384 * Search for a special module named "ram_blacklist". It'll be a
385 * plain text file provided by the user via the loader directive
389 vm_page_blacklist_load(char **list, char **end)
398 mod = preload_search_by_type("ram_blacklist");
400 ptr = preload_fetch_addr(mod);
401 len = preload_fetch_size(mod);
412 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
419 error = sysctl_wire_old_buffer(req, 0);
422 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
423 TAILQ_FOREACH(m, &blacklist_head, listq) {
424 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
425 (uintmax_t)m->phys_addr);
428 error = sbuf_finish(&sbuf);
434 * Initialize a dummy page for use in scans of the specified paging queue.
435 * In principle, this function only needs to set the flag PG_MARKER.
436 * Nonetheless, it write busies the page as a safety precaution.
439 vm_page_init_marker(vm_page_t marker, int queue, uint8_t aflags)
442 bzero(marker, sizeof(*marker));
443 marker->flags = PG_MARKER;
444 marker->aflags = aflags;
445 marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
446 marker->queue = queue;
450 vm_page_domain_init(int domain)
452 struct vm_domain *vmd;
453 struct vm_pagequeue *pq;
456 vmd = VM_DOMAIN(domain);
457 bzero(vmd, sizeof(*vmd));
458 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
459 "vm inactive pagequeue";
460 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
461 "vm active pagequeue";
462 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
463 "vm laundry pagequeue";
464 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_name) =
465 "vm unswappable pagequeue";
466 vmd->vmd_domain = domain;
467 vmd->vmd_page_count = 0;
468 vmd->vmd_free_count = 0;
470 vmd->vmd_oom = FALSE;
471 for (i = 0; i < PQ_COUNT; i++) {
472 pq = &vmd->vmd_pagequeues[i];
473 TAILQ_INIT(&pq->pq_pl);
474 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
475 MTX_DEF | MTX_DUPOK);
477 vm_page_init_marker(&vmd->vmd_markers[i], i, 0);
479 mtx_init(&vmd->vmd_free_mtx, "vm page free queue", NULL, MTX_DEF);
480 mtx_init(&vmd->vmd_pageout_mtx, "vm pageout lock", NULL, MTX_DEF);
481 snprintf(vmd->vmd_name, sizeof(vmd->vmd_name), "%d", domain);
484 * inacthead is used to provide FIFO ordering for LRU-bypassing
487 vm_page_init_marker(&vmd->vmd_inacthead, PQ_INACTIVE, PGA_ENQUEUED);
488 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_INACTIVE].pq_pl,
489 &vmd->vmd_inacthead, plinks.q);
492 * The clock pages are used to implement active queue scanning without
493 * requeues. Scans start at clock[0], which is advanced after the scan
494 * ends. When the two clock hands meet, they are reset and scanning
495 * resumes from the head of the queue.
497 vm_page_init_marker(&vmd->vmd_clock[0], PQ_ACTIVE, PGA_ENQUEUED);
498 vm_page_init_marker(&vmd->vmd_clock[1], PQ_ACTIVE, PGA_ENQUEUED);
499 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
500 &vmd->vmd_clock[0], plinks.q);
501 TAILQ_INSERT_TAIL(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
502 &vmd->vmd_clock[1], plinks.q);
506 * Initialize a physical page in preparation for adding it to the free
510 vm_page_init_page(vm_page_t m, vm_paddr_t pa, int segind)
515 m->busy_lock = VPB_UNBUSIED;
516 m->flags = m->aflags = 0;
521 m->order = VM_NFREEORDER;
522 m->pool = VM_FREEPOOL_DEFAULT;
523 m->valid = m->dirty = 0;
527 #ifndef PMAP_HAS_PAGE_ARRAY
529 vm_page_array_alloc(vm_offset_t *vaddr, vm_paddr_t end, vm_paddr_t page_range)
534 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
535 * However, because this page is allocated from KVM, out-of-bounds
536 * accesses using the direct map will not be trapped.
541 * Allocate physical memory for the page structures, and map it.
543 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
544 vm_page_array = (vm_page_t)pmap_map(vaddr, new_end, end,
545 VM_PROT_READ | VM_PROT_WRITE);
546 vm_page_array_size = page_range;
555 * Initializes the resident memory module. Allocates physical memory for
556 * bootstrapping UMA and some data structures that are used to manage
557 * physical pages. Initializes these structures, and populates the free
561 vm_page_startup(vm_offset_t vaddr)
563 struct vm_phys_seg *seg;
565 char *list, *listend;
567 vm_paddr_t end, high_avail, low_avail, new_end, page_range, size;
568 vm_paddr_t last_pa, pa;
570 int biggestone, i, segind;
574 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
578 vaddr = round_page(vaddr);
580 vm_phys_early_startup();
581 biggestone = vm_phys_avail_largest();
582 end = phys_avail[biggestone+1];
585 * Initialize the page and queue locks.
587 mtx_init(&vm_domainset_lock, "vm domainset lock", NULL, MTX_DEF);
588 for (i = 0; i < PA_LOCK_COUNT; i++)
589 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
590 for (i = 0; i < vm_ndomains; i++)
591 vm_page_domain_init(i);
594 * Allocate memory for use when boot strapping the kernel memory
595 * allocator. Tell UMA how many zones we are going to create
596 * before going fully functional. UMA will add its zones.
598 * VM startup zones: vmem, vmem_btag, VM OBJECT, RADIX NODE, MAP,
599 * KMAP ENTRY, MAP ENTRY, VMSPACE.
601 boot_pages = uma_startup_count(8);
603 #ifndef UMA_MD_SMALL_ALLOC
604 /* vmem_startup() calls uma_prealloc(). */
605 boot_pages += vmem_startup_count();
606 /* vm_map_startup() calls uma_prealloc(). */
607 boot_pages += howmany(MAX_KMAP,
608 UMA_SLAB_SPACE / sizeof(struct vm_map));
611 * Before going fully functional kmem_init() does allocation
612 * from "KMAP ENTRY" and vmem_create() does allocation from "vmem".
617 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
618 * manually fetch the value.
620 TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
621 new_end = end - (boot_pages * UMA_SLAB_SIZE);
622 new_end = trunc_page(new_end);
623 mapped = pmap_map(&vaddr, new_end, end,
624 VM_PROT_READ | VM_PROT_WRITE);
625 bzero((void *)mapped, end - new_end);
626 uma_startup((void *)mapped, boot_pages);
629 witness_size = round_page(witness_startup_count());
630 new_end -= witness_size;
631 mapped = pmap_map(&vaddr, new_end, new_end + witness_size,
632 VM_PROT_READ | VM_PROT_WRITE);
633 bzero((void *)mapped, witness_size);
634 witness_startup((void *)mapped);
637 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
638 defined(__i386__) || defined(__mips__) || defined(__riscv)
640 * Allocate a bitmap to indicate that a random physical page
641 * needs to be included in a minidump.
643 * The amd64 port needs this to indicate which direct map pages
644 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
646 * However, i386 still needs this workspace internally within the
647 * minidump code. In theory, they are not needed on i386, but are
648 * included should the sf_buf code decide to use them.
651 for (i = 0; dump_avail[i + 1] != 0; i += 2)
652 if (dump_avail[i + 1] > last_pa)
653 last_pa = dump_avail[i + 1];
654 page_range = last_pa / PAGE_SIZE;
655 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
656 new_end -= vm_page_dump_size;
657 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
658 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
659 bzero((void *)vm_page_dump, vm_page_dump_size);
663 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
666 * Include the UMA bootstrap pages, witness pages and vm_page_dump
667 * in a crash dump. When pmap_map() uses the direct map, they are
668 * not automatically included.
670 for (pa = new_end; pa < end; pa += PAGE_SIZE)
673 phys_avail[biggestone + 1] = new_end;
676 * Request that the physical pages underlying the message buffer be
677 * included in a crash dump. Since the message buffer is accessed
678 * through the direct map, they are not automatically included.
680 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
681 last_pa = pa + round_page(msgbufsize);
682 while (pa < last_pa) {
688 * Compute the number of pages of memory that will be available for
689 * use, taking into account the overhead of a page structure per page.
690 * In other words, solve
691 * "available physical memory" - round_page(page_range *
692 * sizeof(struct vm_page)) = page_range * PAGE_SIZE
695 low_avail = phys_avail[0];
696 high_avail = phys_avail[1];
697 for (i = 0; i < vm_phys_nsegs; i++) {
698 if (vm_phys_segs[i].start < low_avail)
699 low_avail = vm_phys_segs[i].start;
700 if (vm_phys_segs[i].end > high_avail)
701 high_avail = vm_phys_segs[i].end;
703 /* Skip the first chunk. It is already accounted for. */
704 for (i = 2; phys_avail[i + 1] != 0; i += 2) {
705 if (phys_avail[i] < low_avail)
706 low_avail = phys_avail[i];
707 if (phys_avail[i + 1] > high_avail)
708 high_avail = phys_avail[i + 1];
710 first_page = low_avail / PAGE_SIZE;
711 #ifdef VM_PHYSSEG_SPARSE
713 for (i = 0; i < vm_phys_nsegs; i++)
714 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
715 for (i = 0; phys_avail[i + 1] != 0; i += 2)
716 size += phys_avail[i + 1] - phys_avail[i];
717 #elif defined(VM_PHYSSEG_DENSE)
718 size = high_avail - low_avail;
720 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
723 #ifdef PMAP_HAS_PAGE_ARRAY
724 pmap_page_array_startup(size / PAGE_SIZE);
725 biggestone = vm_phys_avail_largest();
726 end = new_end = phys_avail[biggestone + 1];
728 #ifdef VM_PHYSSEG_DENSE
730 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
731 * the overhead of a page structure per page only if vm_page_array is
732 * allocated from the last physical memory chunk. Otherwise, we must
733 * allocate page structures representing the physical memory
734 * underlying vm_page_array, even though they will not be used.
736 if (new_end != high_avail)
737 page_range = size / PAGE_SIZE;
741 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
744 * If the partial bytes remaining are large enough for
745 * a page (PAGE_SIZE) without a corresponding
746 * 'struct vm_page', then new_end will contain an
747 * extra page after subtracting the length of the VM
748 * page array. Compensate by subtracting an extra
751 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
752 if (new_end == high_avail)
753 high_avail -= PAGE_SIZE;
754 new_end -= PAGE_SIZE;
758 new_end = vm_page_array_alloc(&vaddr, end, page_range);
761 #if VM_NRESERVLEVEL > 0
763 * Allocate physical memory for the reservation management system's
764 * data structures, and map it.
766 new_end = vm_reserv_startup(&vaddr, new_end);
768 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
771 * Include vm_page_array and vm_reserv_array in a crash dump.
773 for (pa = new_end; pa < end; pa += PAGE_SIZE)
776 phys_avail[biggestone + 1] = new_end;
779 * Add physical memory segments corresponding to the available
782 for (i = 0; phys_avail[i + 1] != 0; i += 2)
783 if (vm_phys_avail_size(i) != 0)
784 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
787 * Initialize the physical memory allocator.
792 * Initialize the page structures and add every available page to the
793 * physical memory allocator's free lists.
795 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
796 for (ii = 0; ii < vm_page_array_size; ii++) {
797 m = &vm_page_array[ii];
798 vm_page_init_page(m, (first_page + ii) << PAGE_SHIFT, 0);
799 m->flags = PG_FICTITIOUS;
802 vm_cnt.v_page_count = 0;
803 for (segind = 0; segind < vm_phys_nsegs; segind++) {
804 seg = &vm_phys_segs[segind];
805 for (m = seg->first_page, pa = seg->start; pa < seg->end;
806 m++, pa += PAGE_SIZE)
807 vm_page_init_page(m, pa, segind);
810 * Add the segment to the free lists only if it is covered by
811 * one of the ranges in phys_avail. Because we've added the
812 * ranges to the vm_phys_segs array, we can assume that each
813 * segment is either entirely contained in one of the ranges,
814 * or doesn't overlap any of them.
816 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
817 struct vm_domain *vmd;
819 if (seg->start < phys_avail[i] ||
820 seg->end > phys_avail[i + 1])
824 pagecount = (u_long)atop(seg->end - seg->start);
826 vmd = VM_DOMAIN(seg->domain);
827 vm_domain_free_lock(vmd);
828 vm_phys_enqueue_contig(m, pagecount);
829 vm_domain_free_unlock(vmd);
830 vm_domain_freecnt_inc(vmd, pagecount);
831 vm_cnt.v_page_count += (u_int)pagecount;
833 vmd = VM_DOMAIN(seg->domain);
834 vmd->vmd_page_count += (u_int)pagecount;
835 vmd->vmd_segs |= 1UL << m->segind;
841 * Remove blacklisted pages from the physical memory allocator.
843 TAILQ_INIT(&blacklist_head);
844 vm_page_blacklist_load(&list, &listend);
845 vm_page_blacklist_check(list, listend);
847 list = kern_getenv("vm.blacklist");
848 vm_page_blacklist_check(list, NULL);
851 #if VM_NRESERVLEVEL > 0
853 * Initialize the reservation management system.
862 vm_page_reference(vm_page_t m)
865 vm_page_aflag_set(m, PGA_REFERENCED);
869 * vm_page_busy_acquire:
871 * Acquire the busy lock as described by VM_ALLOC_* flags. Will loop
872 * and drop the object lock if necessary.
875 vm_page_busy_acquire(vm_page_t m, int allocflags)
882 * The page-specific object must be cached because page
883 * identity can change during the sleep, causing the
884 * re-lock of a different object.
885 * It is assumed that a reference to the object is already
886 * held by the callers.
890 if ((allocflags & VM_ALLOC_SBUSY) == 0) {
891 if (vm_page_tryxbusy(m))
894 if (vm_page_trysbusy(m))
897 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
900 locked = VM_OBJECT_WOWNED(obj);
902 MPASS(vm_page_wired(m));
907 if (x == VPB_UNBUSIED ||
908 ((allocflags & VM_ALLOC_SBUSY) != 0 &&
909 (x & VPB_BIT_SHARED) != 0) ||
910 ((x & VPB_BIT_WAITERS) == 0 &&
911 !atomic_cmpset_int(&m->busy_lock, x,
912 x | VPB_BIT_WAITERS))) {
917 VM_OBJECT_WUNLOCK(obj);
918 sleepq_add(m, NULL, "vmpba", 0, 0);
921 VM_OBJECT_WLOCK(obj);
922 MPASS(m->object == obj || m->object == NULL);
923 if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
929 * vm_page_busy_downgrade:
931 * Downgrade an exclusive busy page into a single shared busy page.
934 vm_page_busy_downgrade(vm_page_t m)
938 vm_page_assert_xbusied(m);
942 if (atomic_fcmpset_rel_int(&m->busy_lock,
943 &x, VPB_SHARERS_WORD(1)))
946 if ((x & VPB_BIT_WAITERS) != 0)
953 * Return a positive value if the page is shared busied, 0 otherwise.
956 vm_page_sbusied(vm_page_t m)
961 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
967 * Shared unbusy a page.
970 vm_page_sunbusy(vm_page_t m)
974 vm_page_assert_sbusied(m);
978 if (VPB_SHARERS(x) > 1) {
979 if (atomic_fcmpset_int(&m->busy_lock, &x,
984 KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
985 ("vm_page_sunbusy: invalid lock state"));
986 if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
988 if ((x & VPB_BIT_WAITERS) == 0)
996 * vm_page_busy_sleep:
998 * Sleep if the page is busy, using the page pointer as wchan.
999 * This is used to implement the hard-path of busying mechanism.
1001 * If nonshared is true, sleep only if the page is xbusy.
1003 * The object lock must be held on entry and will be released on exit.
1006 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
1012 vm_page_lock_assert(m, MA_NOTOWNED);
1013 VM_OBJECT_ASSERT_LOCKED(obj);
1017 if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
1018 ((x & VPB_BIT_WAITERS) == 0 &&
1019 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
1020 VM_OBJECT_DROP(obj);
1024 VM_OBJECT_DROP(obj);
1025 sleepq_add(m, NULL, wmesg, 0, 0);
1026 sleepq_wait(m, PVM);
1032 * Try to shared busy a page.
1033 * If the operation succeeds 1 is returned otherwise 0.
1034 * The operation never sleeps.
1037 vm_page_trysbusy(vm_page_t m)
1043 if ((x & VPB_BIT_SHARED) == 0)
1045 if (atomic_fcmpset_acq_int(&m->busy_lock, &x,
1046 x + VPB_ONE_SHARER))
1052 * vm_page_xunbusy_hard:
1054 * Called when unbusy has failed because there is a waiter.
1057 vm_page_xunbusy_hard(vm_page_t m)
1060 vm_page_assert_xbusied(m);
1065 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1070 * Avoid releasing and reacquiring the same page lock.
1073 vm_page_change_lock(vm_page_t m, struct mtx **mtx)
1077 mtx1 = vm_page_lockptr(m);
1087 * vm_page_unhold_pages:
1089 * Unhold each of the pages that is referenced by the given array.
1092 vm_page_unhold_pages(vm_page_t *ma, int count)
1095 for (; count != 0; count--) {
1096 vm_page_unwire(*ma, PQ_ACTIVE);
1102 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1106 #ifdef VM_PHYSSEG_SPARSE
1107 m = vm_phys_paddr_to_vm_page(pa);
1109 m = vm_phys_fictitious_to_vm_page(pa);
1111 #elif defined(VM_PHYSSEG_DENSE)
1115 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1116 m = &vm_page_array[pi - first_page];
1119 return (vm_phys_fictitious_to_vm_page(pa));
1121 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1128 * Create a fictitious page with the specified physical address and
1129 * memory attribute. The memory attribute is the only the machine-
1130 * dependent aspect of a fictitious page that must be initialized.
1133 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1137 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1138 vm_page_initfake(m, paddr, memattr);
1143 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1146 if ((m->flags & PG_FICTITIOUS) != 0) {
1148 * The page's memattr might have changed since the
1149 * previous initialization. Update the pmap to the
1154 m->phys_addr = paddr;
1156 /* Fictitious pages don't use "segind". */
1157 m->flags = PG_FICTITIOUS;
1158 /* Fictitious pages don't use "order" or "pool". */
1159 m->oflags = VPO_UNMANAGED;
1160 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1161 /* Fictitious pages are unevictable. */
1165 pmap_page_set_memattr(m, memattr);
1171 * Release a fictitious page.
1174 vm_page_putfake(vm_page_t m)
1177 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1178 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1179 ("vm_page_putfake: bad page %p", m));
1180 uma_zfree(fakepg_zone, m);
1184 * vm_page_updatefake:
1186 * Update the given fictitious page to the specified physical address and
1190 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1193 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1194 ("vm_page_updatefake: bad page %p", m));
1195 m->phys_addr = paddr;
1196 pmap_page_set_memattr(m, memattr);
1205 vm_page_free(vm_page_t m)
1208 m->flags &= ~PG_ZERO;
1209 vm_page_free_toq(m);
1213 * vm_page_free_zero:
1215 * Free a page to the zerod-pages queue
1218 vm_page_free_zero(vm_page_t m)
1221 m->flags |= PG_ZERO;
1222 vm_page_free_toq(m);
1226 * Unbusy and handle the page queueing for a page from a getpages request that
1227 * was optionally read ahead or behind.
1230 vm_page_readahead_finish(vm_page_t m)
1233 /* We shouldn't put invalid pages on queues. */
1234 KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
1237 * Since the page is not the actually needed one, whether it should
1238 * be activated or deactivated is not obvious. Empirical results
1239 * have shown that deactivating the page is usually the best choice,
1240 * unless the page is wanted by another thread.
1243 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1244 vm_page_activate(m);
1246 vm_page_deactivate(m);
1252 * vm_page_sleep_if_busy:
1254 * Sleep and release the object lock if the page is busied.
1255 * Returns TRUE if the thread slept.
1257 * The given page must be unlocked and object containing it must
1261 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1265 vm_page_lock_assert(m, MA_NOTOWNED);
1266 VM_OBJECT_ASSERT_WLOCKED(m->object);
1268 if (vm_page_busied(m)) {
1270 * The page-specific object must be cached because page
1271 * identity can change during the sleep, causing the
1272 * re-lock of a different object.
1273 * It is assumed that a reference to the object is already
1274 * held by the callers.
1277 vm_page_busy_sleep(m, msg, false);
1278 VM_OBJECT_WLOCK(obj);
1285 * vm_page_sleep_if_xbusy:
1287 * Sleep and release the object lock if the page is xbusied.
1288 * Returns TRUE if the thread slept.
1290 * The given page must be unlocked and object containing it must
1294 vm_page_sleep_if_xbusy(vm_page_t m, const char *msg)
1298 vm_page_lock_assert(m, MA_NOTOWNED);
1299 VM_OBJECT_ASSERT_WLOCKED(m->object);
1301 if (vm_page_xbusied(m)) {
1303 * The page-specific object must be cached because page
1304 * identity can change during the sleep, causing the
1305 * re-lock of a different object.
1306 * It is assumed that a reference to the object is already
1307 * held by the callers.
1310 vm_page_busy_sleep(m, msg, true);
1311 VM_OBJECT_WLOCK(obj);
1318 * vm_page_dirty_KBI: [ internal use only ]
1320 * Set all bits in the page's dirty field.
1322 * The object containing the specified page must be locked if the
1323 * call is made from the machine-independent layer.
1325 * See vm_page_clear_dirty_mask().
1327 * This function should only be called by vm_page_dirty().
1330 vm_page_dirty_KBI(vm_page_t m)
1333 /* Refer to this operation by its public name. */
1334 KASSERT(m->valid == VM_PAGE_BITS_ALL,
1335 ("vm_page_dirty: page is invalid!"));
1336 m->dirty = VM_PAGE_BITS_ALL;
1340 * vm_page_insert: [ internal use only ]
1342 * Inserts the given mem entry into the object and object list.
1344 * The object must be locked.
1347 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1351 VM_OBJECT_ASSERT_WLOCKED(object);
1352 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1353 return (vm_page_insert_after(m, object, pindex, mpred));
1357 * vm_page_insert_after:
1359 * Inserts the page "m" into the specified object at offset "pindex".
1361 * The page "mpred" must immediately precede the offset "pindex" within
1362 * the specified object.
1364 * The object must be locked.
1367 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1372 VM_OBJECT_ASSERT_WLOCKED(object);
1373 KASSERT(m->object == NULL,
1374 ("vm_page_insert_after: page already inserted"));
1375 if (mpred != NULL) {
1376 KASSERT(mpred->object == object,
1377 ("vm_page_insert_after: object doesn't contain mpred"));
1378 KASSERT(mpred->pindex < pindex,
1379 ("vm_page_insert_after: mpred doesn't precede pindex"));
1380 msucc = TAILQ_NEXT(mpred, listq);
1382 msucc = TAILQ_FIRST(&object->memq);
1384 KASSERT(msucc->pindex > pindex,
1385 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1388 * Record the object/offset pair in this page.
1392 m->ref_count |= VPRC_OBJREF;
1395 * Now link into the object's ordered list of backed pages.
1397 if (vm_radix_insert(&object->rtree, m)) {
1400 m->ref_count &= ~VPRC_OBJREF;
1403 vm_page_insert_radixdone(m, object, mpred);
1408 * vm_page_insert_radixdone:
1410 * Complete page "m" insertion into the specified object after the
1411 * radix trie hooking.
1413 * The page "mpred" must precede the offset "m->pindex" within the
1416 * The object must be locked.
1419 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1422 VM_OBJECT_ASSERT_WLOCKED(object);
1423 KASSERT(object != NULL && m->object == object,
1424 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1425 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1426 ("vm_page_insert_radixdone: page %p is missing object ref", m));
1427 if (mpred != NULL) {
1428 KASSERT(mpred->object == object,
1429 ("vm_page_insert_radixdone: object doesn't contain mpred"));
1430 KASSERT(mpred->pindex < m->pindex,
1431 ("vm_page_insert_radixdone: mpred doesn't precede pindex"));
1435 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1437 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1440 * Show that the object has one more resident page.
1442 object->resident_page_count++;
1445 * Hold the vnode until the last page is released.
1447 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1448 vhold(object->handle);
1451 * Since we are inserting a new and possibly dirty page,
1452 * update the object's OBJ_MIGHTBEDIRTY flag.
1454 if (pmap_page_is_write_mapped(m))
1455 vm_object_set_writeable_dirty(object);
1459 * Do the work to remove a page from its object. The caller is responsible for
1460 * updating the page's fields to reflect this removal.
1463 vm_page_object_remove(vm_page_t m)
1469 VM_OBJECT_ASSERT_WLOCKED(object);
1470 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1471 ("page %p is missing its object ref", m));
1472 if (vm_page_xbusied(m))
1474 mrem = vm_radix_remove(&object->rtree, m->pindex);
1475 KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1478 * Now remove from the object's list of backed pages.
1480 TAILQ_REMOVE(&object->memq, m, listq);
1483 * And show that the object has one fewer resident page.
1485 object->resident_page_count--;
1488 * The vnode may now be recycled.
1490 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1491 vdrop(object->handle);
1497 * Removes the specified page from its containing object, but does not
1498 * invalidate any backing storage. Returns true if the object's reference
1499 * was the last reference to the page, and false otherwise.
1501 * The object must be locked.
1504 vm_page_remove(vm_page_t m)
1507 vm_page_object_remove(m);
1509 return (vm_page_drop(m, VPRC_OBJREF) == VPRC_OBJREF);
1515 * Returns the page associated with the object/offset
1516 * pair specified; if none is found, NULL is returned.
1518 * The object must be locked.
1521 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1524 VM_OBJECT_ASSERT_LOCKED(object);
1525 return (vm_radix_lookup(&object->rtree, pindex));
1529 * vm_page_find_least:
1531 * Returns the page associated with the object with least pindex
1532 * greater than or equal to the parameter pindex, or NULL.
1534 * The object must be locked.
1537 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1541 VM_OBJECT_ASSERT_LOCKED(object);
1542 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1543 m = vm_radix_lookup_ge(&object->rtree, pindex);
1548 * Returns the given page's successor (by pindex) within the object if it is
1549 * resident; if none is found, NULL is returned.
1551 * The object must be locked.
1554 vm_page_next(vm_page_t m)
1558 VM_OBJECT_ASSERT_LOCKED(m->object);
1559 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1560 MPASS(next->object == m->object);
1561 if (next->pindex != m->pindex + 1)
1568 * Returns the given page's predecessor (by pindex) within the object if it is
1569 * resident; if none is found, NULL is returned.
1571 * The object must be locked.
1574 vm_page_prev(vm_page_t m)
1578 VM_OBJECT_ASSERT_LOCKED(m->object);
1579 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1580 MPASS(prev->object == m->object);
1581 if (prev->pindex != m->pindex - 1)
1588 * Uses the page mnew as a replacement for an existing page at index
1589 * pindex which must be already present in the object.
1592 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1596 VM_OBJECT_ASSERT_WLOCKED(object);
1597 KASSERT(mnew->object == NULL && (mnew->ref_count & VPRC_OBJREF) == 0,
1598 ("vm_page_replace: page %p already in object", mnew));
1601 * This function mostly follows vm_page_insert() and
1602 * vm_page_remove() without the radix, object count and vnode
1603 * dance. Double check such functions for more comments.
1606 mnew->object = object;
1607 mnew->pindex = pindex;
1608 atomic_set_int(&mnew->ref_count, VPRC_OBJREF);
1609 mold = vm_radix_replace(&object->rtree, mnew);
1610 KASSERT(mold->queue == PQ_NONE,
1611 ("vm_page_replace: old page %p is on a paging queue", mold));
1613 /* Keep the resident page list in sorted order. */
1614 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1615 TAILQ_REMOVE(&object->memq, mold, listq);
1617 mold->object = NULL;
1618 atomic_clear_int(&mold->ref_count, VPRC_OBJREF);
1619 vm_page_xunbusy(mold);
1622 * The object's resident_page_count does not change because we have
1623 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1625 if (pmap_page_is_write_mapped(mnew))
1626 vm_object_set_writeable_dirty(object);
1633 * Move the given memory entry from its
1634 * current object to the specified target object/offset.
1636 * Note: swap associated with the page must be invalidated by the move. We
1637 * have to do this for several reasons: (1) we aren't freeing the
1638 * page, (2) we are dirtying the page, (3) the VM system is probably
1639 * moving the page from object A to B, and will then later move
1640 * the backing store from A to B and we can't have a conflict.
1642 * Note: we *always* dirty the page. It is necessary both for the
1643 * fact that we moved it, and because we may be invalidating
1646 * The objects must be locked.
1649 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1654 VM_OBJECT_ASSERT_WLOCKED(new_object);
1656 KASSERT(m->ref_count != 0, ("vm_page_rename: page %p has no refs", m));
1657 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1658 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1659 ("vm_page_rename: pindex already renamed"));
1662 * Create a custom version of vm_page_insert() which does not depend
1663 * by m_prev and can cheat on the implementation aspects of the
1667 m->pindex = new_pindex;
1668 if (vm_radix_insert(&new_object->rtree, m)) {
1674 * The operation cannot fail anymore. The removal must happen before
1675 * the listq iterator is tainted.
1678 vm_page_object_remove(m);
1680 /* Return back to the new pindex to complete vm_page_insert(). */
1681 m->pindex = new_pindex;
1682 m->object = new_object;
1684 vm_page_insert_radixdone(m, new_object, mpred);
1692 * Allocate and return a page that is associated with the specified
1693 * object and offset pair. By default, this page is exclusive busied.
1695 * The caller must always specify an allocation class.
1697 * allocation classes:
1698 * VM_ALLOC_NORMAL normal process request
1699 * VM_ALLOC_SYSTEM system *really* needs a page
1700 * VM_ALLOC_INTERRUPT interrupt time request
1702 * optional allocation flags:
1703 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1704 * intends to allocate
1705 * VM_ALLOC_NOBUSY do not exclusive busy the page
1706 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1707 * VM_ALLOC_NOOBJ page is not associated with an object and
1708 * should not be exclusive busy
1709 * VM_ALLOC_SBUSY shared busy the allocated page
1710 * VM_ALLOC_WIRED wire the allocated page
1711 * VM_ALLOC_ZERO prefer a zeroed page
1714 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1717 return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1718 vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1722 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1726 return (vm_page_alloc_domain_after(object, pindex, domain, req,
1727 object != NULL ? vm_radix_lookup_le(&object->rtree, pindex) :
1732 * Allocate a page in the specified object with the given page index. To
1733 * optimize insertion of the page into the object, the caller must also specifiy
1734 * the resident page in the object with largest index smaller than the given
1735 * page index, or NULL if no such page exists.
1738 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1739 int req, vm_page_t mpred)
1741 struct vm_domainset_iter di;
1745 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1747 m = vm_page_alloc_domain_after(object, pindex, domain, req,
1751 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
1757 * Returns true if the number of free pages exceeds the minimum
1758 * for the request class and false otherwise.
1761 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
1763 u_int limit, old, new;
1765 req = req & VM_ALLOC_CLASS_MASK;
1768 * The page daemon is allowed to dig deeper into the free page list.
1770 if (curproc == pageproc && req != VM_ALLOC_INTERRUPT)
1771 req = VM_ALLOC_SYSTEM;
1772 if (req == VM_ALLOC_INTERRUPT)
1774 else if (req == VM_ALLOC_SYSTEM)
1775 limit = vmd->vmd_interrupt_free_min;
1777 limit = vmd->vmd_free_reserved;
1780 * Attempt to reserve the pages. Fail if we're below the limit.
1783 old = vmd->vmd_free_count;
1788 } while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
1790 /* Wake the page daemon if we've crossed the threshold. */
1791 if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
1792 pagedaemon_wakeup(vmd->vmd_domain);
1794 /* Only update bitsets on transitions. */
1795 if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
1796 (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
1803 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
1804 int req, vm_page_t mpred)
1806 struct vm_domain *vmd;
1810 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1811 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1812 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1813 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1814 ("inconsistent object(%p)/req(%x)", object, req));
1815 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1816 ("Can't sleep and retry object insertion."));
1817 KASSERT(mpred == NULL || mpred->pindex < pindex,
1818 ("mpred %p doesn't precede pindex 0x%jx", mpred,
1819 (uintmax_t)pindex));
1821 VM_OBJECT_ASSERT_WLOCKED(object);
1825 pool = object != NULL ? VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT;
1827 #if VM_NRESERVLEVEL > 0
1829 * Can we allocate the page from a reservation?
1831 if (vm_object_reserv(object) &&
1832 (m = vm_reserv_alloc_page(object, pindex, domain, req, mpred)) !=
1834 domain = vm_phys_domain(m);
1835 vmd = VM_DOMAIN(domain);
1839 vmd = VM_DOMAIN(domain);
1840 if (vmd->vmd_pgcache[pool].zone != NULL) {
1841 m = uma_zalloc(vmd->vmd_pgcache[pool].zone, M_NOWAIT);
1843 flags |= PG_PCPU_CACHE;
1847 if (vm_domain_allocate(vmd, req, 1)) {
1849 * If not, allocate it from the free page queues.
1851 vm_domain_free_lock(vmd);
1852 m = vm_phys_alloc_pages(domain, pool, 0);
1853 vm_domain_free_unlock(vmd);
1855 vm_domain_freecnt_inc(vmd, 1);
1856 #if VM_NRESERVLEVEL > 0
1857 if (vm_reserv_reclaim_inactive(domain))
1864 * Not allocatable, give up.
1866 if (vm_domain_alloc_fail(vmd, object, req))
1872 * At this point we had better have found a good page.
1876 vm_page_alloc_check(m);
1879 * Initialize the page. Only the PG_ZERO flag is inherited.
1881 if ((req & VM_ALLOC_ZERO) != 0)
1882 flags |= (m->flags & PG_ZERO);
1883 if ((req & VM_ALLOC_NODUMP) != 0)
1887 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1889 m->busy_lock = VPB_UNBUSIED;
1890 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1891 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1892 if ((req & VM_ALLOC_SBUSY) != 0)
1893 m->busy_lock = VPB_SHARERS_WORD(1);
1894 if (req & VM_ALLOC_WIRED) {
1896 * The page lock is not required for wiring a page until that
1897 * page is inserted into the object.
1904 if (object != NULL) {
1905 if (vm_page_insert_after(m, object, pindex, mpred)) {
1906 if (req & VM_ALLOC_WIRED) {
1910 KASSERT(m->object == NULL, ("page %p has object", m));
1911 m->oflags = VPO_UNMANAGED;
1912 m->busy_lock = VPB_UNBUSIED;
1913 /* Don't change PG_ZERO. */
1914 vm_page_free_toq(m);
1915 if (req & VM_ALLOC_WAITFAIL) {
1916 VM_OBJECT_WUNLOCK(object);
1918 VM_OBJECT_WLOCK(object);
1923 /* Ignore device objects; the pager sets "memattr" for them. */
1924 if (object->memattr != VM_MEMATTR_DEFAULT &&
1925 (object->flags & OBJ_FICTITIOUS) == 0)
1926 pmap_page_set_memattr(m, object->memattr);
1934 * vm_page_alloc_contig:
1936 * Allocate a contiguous set of physical pages of the given size "npages"
1937 * from the free lists. All of the physical pages must be at or above
1938 * the given physical address "low" and below the given physical address
1939 * "high". The given value "alignment" determines the alignment of the
1940 * first physical page in the set. If the given value "boundary" is
1941 * non-zero, then the set of physical pages cannot cross any physical
1942 * address boundary that is a multiple of that value. Both "alignment"
1943 * and "boundary" must be a power of two.
1945 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1946 * then the memory attribute setting for the physical pages is configured
1947 * to the object's memory attribute setting. Otherwise, the memory
1948 * attribute setting for the physical pages is configured to "memattr",
1949 * overriding the object's memory attribute setting. However, if the
1950 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1951 * memory attribute setting for the physical pages cannot be configured
1952 * to VM_MEMATTR_DEFAULT.
1954 * The specified object may not contain fictitious pages.
1956 * The caller must always specify an allocation class.
1958 * allocation classes:
1959 * VM_ALLOC_NORMAL normal process request
1960 * VM_ALLOC_SYSTEM system *really* needs a page
1961 * VM_ALLOC_INTERRUPT interrupt time request
1963 * optional allocation flags:
1964 * VM_ALLOC_NOBUSY do not exclusive busy the page
1965 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1966 * VM_ALLOC_NOOBJ page is not associated with an object and
1967 * should not be exclusive busy
1968 * VM_ALLOC_SBUSY shared busy the allocated page
1969 * VM_ALLOC_WIRED wire the allocated page
1970 * VM_ALLOC_ZERO prefer a zeroed page
1973 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1974 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1975 vm_paddr_t boundary, vm_memattr_t memattr)
1977 struct vm_domainset_iter di;
1981 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1983 m = vm_page_alloc_contig_domain(object, pindex, domain, req,
1984 npages, low, high, alignment, boundary, memattr);
1987 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
1993 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1994 int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1995 vm_paddr_t boundary, vm_memattr_t memattr)
1997 struct vm_domain *vmd;
1998 vm_page_t m, m_ret, mpred;
1999 u_int busy_lock, flags, oflags;
2001 mpred = NULL; /* XXX: pacify gcc */
2002 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
2003 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
2004 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2005 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2006 ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
2008 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2009 ("Can't sleep and retry object insertion."));
2010 if (object != NULL) {
2011 VM_OBJECT_ASSERT_WLOCKED(object);
2012 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2013 ("vm_page_alloc_contig: object %p has fictitious pages",
2016 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2018 if (object != NULL) {
2019 mpred = vm_radix_lookup_le(&object->rtree, pindex);
2020 KASSERT(mpred == NULL || mpred->pindex != pindex,
2021 ("vm_page_alloc_contig: pindex already allocated"));
2025 * Can we allocate the pages without the number of free pages falling
2026 * below the lower bound for the allocation class?
2030 #if VM_NRESERVLEVEL > 0
2032 * Can we allocate the pages from a reservation?
2034 if (vm_object_reserv(object) &&
2035 (m_ret = vm_reserv_alloc_contig(object, pindex, domain, req,
2036 mpred, npages, low, high, alignment, boundary)) != NULL) {
2037 domain = vm_phys_domain(m_ret);
2038 vmd = VM_DOMAIN(domain);
2042 vmd = VM_DOMAIN(domain);
2043 if (vm_domain_allocate(vmd, req, npages)) {
2045 * allocate them from the free page queues.
2047 vm_domain_free_lock(vmd);
2048 m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2049 alignment, boundary);
2050 vm_domain_free_unlock(vmd);
2051 if (m_ret == NULL) {
2052 vm_domain_freecnt_inc(vmd, npages);
2053 #if VM_NRESERVLEVEL > 0
2054 if (vm_reserv_reclaim_contig(domain, npages, low,
2055 high, alignment, boundary))
2060 if (m_ret == NULL) {
2061 if (vm_domain_alloc_fail(vmd, object, req))
2065 #if VM_NRESERVLEVEL > 0
2068 for (m = m_ret; m < &m_ret[npages]; m++) {
2070 vm_page_alloc_check(m);
2074 * Initialize the pages. Only the PG_ZERO flag is inherited.
2077 if ((req & VM_ALLOC_ZERO) != 0)
2079 if ((req & VM_ALLOC_NODUMP) != 0)
2081 oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2083 busy_lock = VPB_UNBUSIED;
2084 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2085 busy_lock = VPB_SINGLE_EXCLUSIVER;
2086 if ((req & VM_ALLOC_SBUSY) != 0)
2087 busy_lock = VPB_SHARERS_WORD(1);
2088 if ((req & VM_ALLOC_WIRED) != 0)
2089 vm_wire_add(npages);
2090 if (object != NULL) {
2091 if (object->memattr != VM_MEMATTR_DEFAULT &&
2092 memattr == VM_MEMATTR_DEFAULT)
2093 memattr = object->memattr;
2095 for (m = m_ret; m < &m_ret[npages]; m++) {
2097 m->flags = (m->flags | PG_NODUMP) & flags;
2098 m->busy_lock = busy_lock;
2099 if ((req & VM_ALLOC_WIRED) != 0)
2103 if (object != NULL) {
2104 if (vm_page_insert_after(m, object, pindex, mpred)) {
2105 if ((req & VM_ALLOC_WIRED) != 0)
2106 vm_wire_sub(npages);
2107 KASSERT(m->object == NULL,
2108 ("page %p has object", m));
2110 for (m = m_ret; m < &m_ret[npages]; m++) {
2112 (req & VM_ALLOC_WIRED) != 0)
2114 m->oflags = VPO_UNMANAGED;
2115 m->busy_lock = VPB_UNBUSIED;
2116 /* Don't change PG_ZERO. */
2117 vm_page_free_toq(m);
2119 if (req & VM_ALLOC_WAITFAIL) {
2120 VM_OBJECT_WUNLOCK(object);
2122 VM_OBJECT_WLOCK(object);
2129 if (memattr != VM_MEMATTR_DEFAULT)
2130 pmap_page_set_memattr(m, memattr);
2137 * Check a page that has been freshly dequeued from a freelist.
2140 vm_page_alloc_check(vm_page_t m)
2143 KASSERT(m->object == NULL, ("page %p has object", m));
2144 KASSERT(m->queue == PQ_NONE && (m->aflags & PGA_QUEUE_STATE_MASK) == 0,
2145 ("page %p has unexpected queue %d, flags %#x",
2146 m, m->queue, (m->aflags & PGA_QUEUE_STATE_MASK)));
2147 KASSERT(m->ref_count == 0, ("page %p has references", m));
2148 KASSERT(!vm_page_busied(m), ("page %p is busy", m));
2149 KASSERT(m->dirty == 0, ("page %p is dirty", m));
2150 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2151 ("page %p has unexpected memattr %d",
2152 m, pmap_page_get_memattr(m)));
2153 KASSERT(m->valid == 0, ("free page %p is valid", m));
2157 * vm_page_alloc_freelist:
2159 * Allocate a physical page from the specified free page list.
2161 * The caller must always specify an allocation class.
2163 * allocation classes:
2164 * VM_ALLOC_NORMAL normal process request
2165 * VM_ALLOC_SYSTEM system *really* needs a page
2166 * VM_ALLOC_INTERRUPT interrupt time request
2168 * optional allocation flags:
2169 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2170 * intends to allocate
2171 * VM_ALLOC_WIRED wire the allocated page
2172 * VM_ALLOC_ZERO prefer a zeroed page
2175 vm_page_alloc_freelist(int freelist, int req)
2177 struct vm_domainset_iter di;
2181 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2183 m = vm_page_alloc_freelist_domain(domain, freelist, req);
2186 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2192 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2194 struct vm_domain *vmd;
2199 vmd = VM_DOMAIN(domain);
2201 if (vm_domain_allocate(vmd, req, 1)) {
2202 vm_domain_free_lock(vmd);
2203 m = vm_phys_alloc_freelist_pages(domain, freelist,
2204 VM_FREEPOOL_DIRECT, 0);
2205 vm_domain_free_unlock(vmd);
2207 vm_domain_freecnt_inc(vmd, 1);
2210 if (vm_domain_alloc_fail(vmd, NULL, req))
2215 vm_page_alloc_check(m);
2218 * Initialize the page. Only the PG_ZERO flag is inherited.
2222 if ((req & VM_ALLOC_ZERO) != 0)
2225 if ((req & VM_ALLOC_WIRED) != 0) {
2227 * The page lock is not required for wiring a page that does
2228 * not belong to an object.
2233 /* Unmanaged pages don't use "act_count". */
2234 m->oflags = VPO_UNMANAGED;
2239 vm_page_zone_import(void *arg, void **store, int cnt, int domain, int flags)
2241 struct vm_domain *vmd;
2242 struct vm_pgcache *pgcache;
2246 vmd = VM_DOMAIN(pgcache->domain);
2247 /* Only import if we can bring in a full bucket. */
2248 if (cnt == 1 || !vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2250 domain = vmd->vmd_domain;
2251 vm_domain_free_lock(vmd);
2252 i = vm_phys_alloc_npages(domain, pgcache->pool, cnt,
2253 (vm_page_t *)store);
2254 vm_domain_free_unlock(vmd);
2256 vm_domain_freecnt_inc(vmd, cnt - i);
2262 vm_page_zone_release(void *arg, void **store, int cnt)
2264 struct vm_domain *vmd;
2265 struct vm_pgcache *pgcache;
2270 vmd = VM_DOMAIN(pgcache->domain);
2271 vm_domain_free_lock(vmd);
2272 for (i = 0; i < cnt; i++) {
2273 m = (vm_page_t)store[i];
2274 vm_phys_free_pages(m, 0);
2276 vm_domain_free_unlock(vmd);
2277 vm_domain_freecnt_inc(vmd, cnt);
2280 #define VPSC_ANY 0 /* No restrictions. */
2281 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2282 #define VPSC_NOSUPER 2 /* Skip superpages. */
2285 * vm_page_scan_contig:
2287 * Scan vm_page_array[] between the specified entries "m_start" and
2288 * "m_end" for a run of contiguous physical pages that satisfy the
2289 * specified conditions, and return the lowest page in the run. The
2290 * specified "alignment" determines the alignment of the lowest physical
2291 * page in the run. If the specified "boundary" is non-zero, then the
2292 * run of physical pages cannot span a physical address that is a
2293 * multiple of "boundary".
2295 * "m_end" is never dereferenced, so it need not point to a vm_page
2296 * structure within vm_page_array[].
2298 * "npages" must be greater than zero. "m_start" and "m_end" must not
2299 * span a hole (or discontiguity) in the physical address space. Both
2300 * "alignment" and "boundary" must be a power of two.
2303 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2304 u_long alignment, vm_paddr_t boundary, int options)
2310 #if VM_NRESERVLEVEL > 0
2313 int m_inc, order, run_ext, run_len;
2315 KASSERT(npages > 0, ("npages is 0"));
2316 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2317 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2321 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2322 KASSERT((m->flags & PG_MARKER) == 0,
2323 ("page %p is PG_MARKER", m));
2324 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->ref_count >= 1,
2325 ("fictitious page %p has invalid ref count", m));
2328 * If the current page would be the start of a run, check its
2329 * physical address against the end, alignment, and boundary
2330 * conditions. If it doesn't satisfy these conditions, either
2331 * terminate the scan or advance to the next page that
2332 * satisfies the failed condition.
2335 KASSERT(m_run == NULL, ("m_run != NULL"));
2336 if (m + npages > m_end)
2338 pa = VM_PAGE_TO_PHYS(m);
2339 if ((pa & (alignment - 1)) != 0) {
2340 m_inc = atop(roundup2(pa, alignment) - pa);
2343 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2345 m_inc = atop(roundup2(pa, boundary) - pa);
2349 KASSERT(m_run != NULL, ("m_run == NULL"));
2351 vm_page_change_lock(m, &m_mtx);
2354 if (vm_page_wired(m))
2356 #if VM_NRESERVLEVEL > 0
2357 else if ((level = vm_reserv_level(m)) >= 0 &&
2358 (options & VPSC_NORESERV) != 0) {
2360 /* Advance to the end of the reservation. */
2361 pa = VM_PAGE_TO_PHYS(m);
2362 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2366 else if ((object = m->object) != NULL) {
2368 * The page is considered eligible for relocation if
2369 * and only if it could be laundered or reclaimed by
2372 if (!VM_OBJECT_TRYRLOCK(object)) {
2374 VM_OBJECT_RLOCK(object);
2376 if (m->object != object) {
2378 * The page may have been freed.
2380 VM_OBJECT_RUNLOCK(object);
2384 /* Don't care: PG_NODUMP, PG_ZERO. */
2385 if (object->type != OBJT_DEFAULT &&
2386 object->type != OBJT_SWAP &&
2387 object->type != OBJT_VNODE) {
2389 #if VM_NRESERVLEVEL > 0
2390 } else if ((options & VPSC_NOSUPER) != 0 &&
2391 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2393 /* Advance to the end of the superpage. */
2394 pa = VM_PAGE_TO_PHYS(m);
2395 m_inc = atop(roundup2(pa + 1,
2396 vm_reserv_size(level)) - pa);
2398 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2399 vm_page_queue(m) != PQ_NONE && !vm_page_busied(m) &&
2400 !vm_page_wired(m)) {
2402 * The page is allocated but eligible for
2403 * relocation. Extend the current run by one
2406 KASSERT(pmap_page_get_memattr(m) ==
2408 ("page %p has an unexpected memattr", m));
2409 KASSERT((m->oflags & (VPO_SWAPINPROG |
2410 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2411 ("page %p has unexpected oflags", m));
2412 /* Don't care: VPO_NOSYNC. */
2416 VM_OBJECT_RUNLOCK(object);
2417 #if VM_NRESERVLEVEL > 0
2418 } else if (level >= 0) {
2420 * The page is reserved but not yet allocated. In
2421 * other words, it is still free. Extend the current
2426 } else if ((order = m->order) < VM_NFREEORDER) {
2428 * The page is enqueued in the physical memory
2429 * allocator's free page queues. Moreover, it is the
2430 * first page in a power-of-two-sized run of
2431 * contiguous free pages. Add these pages to the end
2432 * of the current run, and jump ahead.
2434 run_ext = 1 << order;
2438 * Skip the page for one of the following reasons: (1)
2439 * It is enqueued in the physical memory allocator's
2440 * free page queues. However, it is not the first
2441 * page in a run of contiguous free pages. (This case
2442 * rarely occurs because the scan is performed in
2443 * ascending order.) (2) It is not reserved, and it is
2444 * transitioning from free to allocated. (Conversely,
2445 * the transition from allocated to free for managed
2446 * pages is blocked by the page lock.) (3) It is
2447 * allocated but not contained by an object and not
2448 * wired, e.g., allocated by Xen's balloon driver.
2454 * Extend or reset the current run of pages.
2469 if (run_len >= npages)
2475 * vm_page_reclaim_run:
2477 * Try to relocate each of the allocated virtual pages within the
2478 * specified run of physical pages to a new physical address. Free the
2479 * physical pages underlying the relocated virtual pages. A virtual page
2480 * is relocatable if and only if it could be laundered or reclaimed by
2481 * the page daemon. Whenever possible, a virtual page is relocated to a
2482 * physical address above "high".
2484 * Returns 0 if every physical page within the run was already free or
2485 * just freed by a successful relocation. Otherwise, returns a non-zero
2486 * value indicating why the last attempt to relocate a virtual page was
2489 * "req_class" must be an allocation class.
2492 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2495 struct vm_domain *vmd;
2497 struct spglist free;
2500 vm_page_t m, m_end, m_new;
2501 int error, order, req;
2503 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2504 ("req_class is not an allocation class"));
2508 m_end = m_run + npages;
2510 for (; error == 0 && m < m_end; m++) {
2511 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2512 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2515 * Avoid releasing and reacquiring the same page lock.
2517 vm_page_change_lock(m, &m_mtx);
2520 * Racily check for wirings. Races are handled below.
2522 if (vm_page_wired(m))
2524 else if ((object = m->object) != NULL) {
2526 * The page is relocated if and only if it could be
2527 * laundered or reclaimed by the page daemon.
2529 if (!VM_OBJECT_TRYWLOCK(object)) {
2531 VM_OBJECT_WLOCK(object);
2533 if (m->object != object) {
2535 * The page may have been freed.
2537 VM_OBJECT_WUNLOCK(object);
2541 /* Don't care: PG_NODUMP, PG_ZERO. */
2542 if (object->type != OBJT_DEFAULT &&
2543 object->type != OBJT_SWAP &&
2544 object->type != OBJT_VNODE)
2546 else if (object->memattr != VM_MEMATTR_DEFAULT)
2548 else if (vm_page_queue(m) != PQ_NONE &&
2549 !vm_page_busied(m) && !vm_page_wired(m)) {
2550 KASSERT(pmap_page_get_memattr(m) ==
2552 ("page %p has an unexpected memattr", m));
2553 KASSERT((m->oflags & (VPO_SWAPINPROG |
2554 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2555 ("page %p has unexpected oflags", m));
2556 /* Don't care: VPO_NOSYNC. */
2557 if (m->valid != 0) {
2559 * First, try to allocate a new page
2560 * that is above "high". Failing
2561 * that, try to allocate a new page
2562 * that is below "m_run". Allocate
2563 * the new page between the end of
2564 * "m_run" and "high" only as a last
2567 req = req_class | VM_ALLOC_NOOBJ;
2568 if ((m->flags & PG_NODUMP) != 0)
2569 req |= VM_ALLOC_NODUMP;
2570 if (trunc_page(high) !=
2571 ~(vm_paddr_t)PAGE_MASK) {
2572 m_new = vm_page_alloc_contig(
2577 VM_MEMATTR_DEFAULT);
2580 if (m_new == NULL) {
2581 pa = VM_PAGE_TO_PHYS(m_run);
2582 m_new = vm_page_alloc_contig(
2584 0, pa - 1, PAGE_SIZE, 0,
2585 VM_MEMATTR_DEFAULT);
2587 if (m_new == NULL) {
2589 m_new = vm_page_alloc_contig(
2591 pa, high, PAGE_SIZE, 0,
2592 VM_MEMATTR_DEFAULT);
2594 if (m_new == NULL) {
2600 * Unmap the page and check for new
2601 * wirings that may have been acquired
2602 * through a pmap lookup.
2604 if (object->ref_count != 0 &&
2605 !vm_page_try_remove_all(m)) {
2606 vm_page_free(m_new);
2612 * Replace "m" with the new page. For
2613 * vm_page_replace(), "m" must be busy
2614 * and dequeued. Finally, change "m"
2615 * as if vm_page_free() was called.
2617 m_new->aflags = m->aflags &
2618 ~PGA_QUEUE_STATE_MASK;
2619 KASSERT(m_new->oflags == VPO_UNMANAGED,
2620 ("page %p is managed", m_new));
2621 m_new->oflags = m->oflags & VPO_NOSYNC;
2622 pmap_copy_page(m, m_new);
2623 m_new->valid = m->valid;
2624 m_new->dirty = m->dirty;
2625 m->flags &= ~PG_ZERO;
2628 vm_page_replace_checked(m_new, object,
2630 if (vm_page_free_prep(m))
2631 SLIST_INSERT_HEAD(&free, m,
2635 * The new page must be deactivated
2636 * before the object is unlocked.
2638 vm_page_change_lock(m_new, &m_mtx);
2639 vm_page_deactivate(m_new);
2641 m->flags &= ~PG_ZERO;
2643 if (vm_page_free_prep(m))
2644 SLIST_INSERT_HEAD(&free, m,
2646 KASSERT(m->dirty == 0,
2647 ("page %p is dirty", m));
2652 VM_OBJECT_WUNLOCK(object);
2654 MPASS(vm_phys_domain(m) == domain);
2655 vmd = VM_DOMAIN(domain);
2656 vm_domain_free_lock(vmd);
2658 if (order < VM_NFREEORDER) {
2660 * The page is enqueued in the physical memory
2661 * allocator's free page queues. Moreover, it
2662 * is the first page in a power-of-two-sized
2663 * run of contiguous free pages. Jump ahead
2664 * to the last page within that run, and
2665 * continue from there.
2667 m += (1 << order) - 1;
2669 #if VM_NRESERVLEVEL > 0
2670 else if (vm_reserv_is_page_free(m))
2673 vm_domain_free_unlock(vmd);
2674 if (order == VM_NFREEORDER)
2680 if ((m = SLIST_FIRST(&free)) != NULL) {
2683 vmd = VM_DOMAIN(domain);
2685 vm_domain_free_lock(vmd);
2687 MPASS(vm_phys_domain(m) == domain);
2688 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2689 vm_phys_free_pages(m, 0);
2691 } while ((m = SLIST_FIRST(&free)) != NULL);
2692 vm_domain_free_unlock(vmd);
2693 vm_domain_freecnt_inc(vmd, cnt);
2700 CTASSERT(powerof2(NRUNS));
2702 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2704 #define MIN_RECLAIM 8
2707 * vm_page_reclaim_contig:
2709 * Reclaim allocated, contiguous physical memory satisfying the specified
2710 * conditions by relocating the virtual pages using that physical memory.
2711 * Returns true if reclamation is successful and false otherwise. Since
2712 * relocation requires the allocation of physical pages, reclamation may
2713 * fail due to a shortage of free pages. When reclamation fails, callers
2714 * are expected to perform vm_wait() before retrying a failed allocation
2715 * operation, e.g., vm_page_alloc_contig().
2717 * The caller must always specify an allocation class through "req".
2719 * allocation classes:
2720 * VM_ALLOC_NORMAL normal process request
2721 * VM_ALLOC_SYSTEM system *really* needs a page
2722 * VM_ALLOC_INTERRUPT interrupt time request
2724 * The optional allocation flags are ignored.
2726 * "npages" must be greater than zero. Both "alignment" and "boundary"
2727 * must be a power of two.
2730 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
2731 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2733 struct vm_domain *vmd;
2734 vm_paddr_t curr_low;
2735 vm_page_t m_run, m_runs[NRUNS];
2736 u_long count, reclaimed;
2737 int error, i, options, req_class;
2739 KASSERT(npages > 0, ("npages is 0"));
2740 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2741 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2742 req_class = req & VM_ALLOC_CLASS_MASK;
2745 * The page daemon is allowed to dig deeper into the free page list.
2747 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2748 req_class = VM_ALLOC_SYSTEM;
2751 * Return if the number of free pages cannot satisfy the requested
2754 vmd = VM_DOMAIN(domain);
2755 count = vmd->vmd_free_count;
2756 if (count < npages + vmd->vmd_free_reserved || (count < npages +
2757 vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2758 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2762 * Scan up to three times, relaxing the restrictions ("options") on
2763 * the reclamation of reservations and superpages each time.
2765 for (options = VPSC_NORESERV;;) {
2767 * Find the highest runs that satisfy the given constraints
2768 * and restrictions, and record them in "m_runs".
2773 m_run = vm_phys_scan_contig(domain, npages, curr_low,
2774 high, alignment, boundary, options);
2777 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2778 m_runs[RUN_INDEX(count)] = m_run;
2783 * Reclaim the highest runs in LIFO (descending) order until
2784 * the number of reclaimed pages, "reclaimed", is at least
2785 * MIN_RECLAIM. Reset "reclaimed" each time because each
2786 * reclamation is idempotent, and runs will (likely) recur
2787 * from one scan to the next as restrictions are relaxed.
2790 for (i = 0; count > 0 && i < NRUNS; i++) {
2792 m_run = m_runs[RUN_INDEX(count)];
2793 error = vm_page_reclaim_run(req_class, domain, npages,
2796 reclaimed += npages;
2797 if (reclaimed >= MIN_RECLAIM)
2803 * Either relax the restrictions on the next scan or return if
2804 * the last scan had no restrictions.
2806 if (options == VPSC_NORESERV)
2807 options = VPSC_NOSUPER;
2808 else if (options == VPSC_NOSUPER)
2810 else if (options == VPSC_ANY)
2811 return (reclaimed != 0);
2816 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2817 u_long alignment, vm_paddr_t boundary)
2819 struct vm_domainset_iter di;
2823 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2825 ret = vm_page_reclaim_contig_domain(domain, req, npages, low,
2826 high, alignment, boundary);
2829 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2835 * Set the domain in the appropriate page level domainset.
2838 vm_domain_set(struct vm_domain *vmd)
2841 mtx_lock(&vm_domainset_lock);
2842 if (!vmd->vmd_minset && vm_paging_min(vmd)) {
2843 vmd->vmd_minset = 1;
2844 DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
2846 if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
2847 vmd->vmd_severeset = 1;
2848 DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
2850 mtx_unlock(&vm_domainset_lock);
2854 * Clear the domain from the appropriate page level domainset.
2857 vm_domain_clear(struct vm_domain *vmd)
2860 mtx_lock(&vm_domainset_lock);
2861 if (vmd->vmd_minset && !vm_paging_min(vmd)) {
2862 vmd->vmd_minset = 0;
2863 DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
2864 if (vm_min_waiters != 0) {
2866 wakeup(&vm_min_domains);
2869 if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
2870 vmd->vmd_severeset = 0;
2871 DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
2872 if (vm_severe_waiters != 0) {
2873 vm_severe_waiters = 0;
2874 wakeup(&vm_severe_domains);
2879 * If pageout daemon needs pages, then tell it that there are
2882 if (vmd->vmd_pageout_pages_needed &&
2883 vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
2884 wakeup(&vmd->vmd_pageout_pages_needed);
2885 vmd->vmd_pageout_pages_needed = 0;
2888 /* See comments in vm_wait_doms(). */
2889 if (vm_pageproc_waiters) {
2890 vm_pageproc_waiters = 0;
2891 wakeup(&vm_pageproc_waiters);
2893 mtx_unlock(&vm_domainset_lock);
2897 * Wait for free pages to exceed the min threshold globally.
2903 mtx_lock(&vm_domainset_lock);
2904 while (vm_page_count_min()) {
2906 msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
2908 mtx_unlock(&vm_domainset_lock);
2912 * Wait for free pages to exceed the severe threshold globally.
2915 vm_wait_severe(void)
2918 mtx_lock(&vm_domainset_lock);
2919 while (vm_page_count_severe()) {
2920 vm_severe_waiters++;
2921 msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
2924 mtx_unlock(&vm_domainset_lock);
2931 return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
2935 vm_wait_doms(const domainset_t *wdoms)
2939 * We use racey wakeup synchronization to avoid expensive global
2940 * locking for the pageproc when sleeping with a non-specific vm_wait.
2941 * To handle this, we only sleep for one tick in this instance. It
2942 * is expected that most allocations for the pageproc will come from
2943 * kmem or vm_page_grab* which will use the more specific and
2944 * race-free vm_wait_domain().
2946 if (curproc == pageproc) {
2947 mtx_lock(&vm_domainset_lock);
2948 vm_pageproc_waiters++;
2949 msleep(&vm_pageproc_waiters, &vm_domainset_lock, PVM | PDROP,
2953 * XXX Ideally we would wait only until the allocation could
2954 * be satisfied. This condition can cause new allocators to
2955 * consume all freed pages while old allocators wait.
2957 mtx_lock(&vm_domainset_lock);
2958 if (vm_page_count_min_set(wdoms)) {
2960 msleep(&vm_min_domains, &vm_domainset_lock,
2961 PVM | PDROP, "vmwait", 0);
2963 mtx_unlock(&vm_domainset_lock);
2970 * Sleep until free pages are available for allocation.
2971 * - Called in various places after failed memory allocations.
2974 vm_wait_domain(int domain)
2976 struct vm_domain *vmd;
2979 vmd = VM_DOMAIN(domain);
2980 vm_domain_free_assert_unlocked(vmd);
2982 if (curproc == pageproc) {
2983 mtx_lock(&vm_domainset_lock);
2984 if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
2985 vmd->vmd_pageout_pages_needed = 1;
2986 msleep(&vmd->vmd_pageout_pages_needed,
2987 &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
2989 mtx_unlock(&vm_domainset_lock);
2991 if (pageproc == NULL)
2992 panic("vm_wait in early boot");
2993 DOMAINSET_ZERO(&wdom);
2994 DOMAINSET_SET(vmd->vmd_domain, &wdom);
2995 vm_wait_doms(&wdom);
3002 * Sleep until free pages are available for allocation in the
3003 * affinity domains of the obj. If obj is NULL, the domain set
3004 * for the calling thread is used.
3005 * Called in various places after failed memory allocations.
3008 vm_wait(vm_object_t obj)
3010 struct domainset *d;
3015 * Carefully fetch pointers only once: the struct domainset
3016 * itself is ummutable but the pointer might change.
3019 d = obj->domain.dr_policy;
3021 d = curthread->td_domain.dr_policy;
3023 vm_wait_doms(&d->ds_mask);
3027 * vm_domain_alloc_fail:
3029 * Called when a page allocation function fails. Informs the
3030 * pagedaemon and performs the requested wait. Requires the
3031 * domain_free and object lock on entry. Returns with the
3032 * object lock held and free lock released. Returns an error when
3033 * retry is necessary.
3037 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3040 vm_domain_free_assert_unlocked(vmd);
3042 atomic_add_int(&vmd->vmd_pageout_deficit,
3043 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3044 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3046 VM_OBJECT_WUNLOCK(object);
3047 vm_wait_domain(vmd->vmd_domain);
3049 VM_OBJECT_WLOCK(object);
3050 if (req & VM_ALLOC_WAITOK)
3060 * Sleep until free pages are available for allocation.
3061 * - Called only in vm_fault so that processes page faulting
3062 * can be easily tracked.
3063 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3064 * processes will be able to grab memory first. Do not change
3065 * this balance without careful testing first.
3068 vm_waitpfault(struct domainset *dset, int timo)
3072 * XXX Ideally we would wait only until the allocation could
3073 * be satisfied. This condition can cause new allocators to
3074 * consume all freed pages while old allocators wait.
3076 mtx_lock(&vm_domainset_lock);
3077 if (vm_page_count_min_set(&dset->ds_mask)) {
3079 msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3082 mtx_unlock(&vm_domainset_lock);
3085 static struct vm_pagequeue *
3086 vm_page_pagequeue(vm_page_t m)
3091 if ((queue = atomic_load_8(&m->queue)) == PQ_NONE)
3093 return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue]);
3097 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m)
3099 struct vm_domain *vmd;
3102 CRITICAL_ASSERT(curthread);
3103 vm_pagequeue_assert_locked(pq);
3106 * The page daemon is allowed to set m->queue = PQ_NONE without
3107 * the page queue lock held. In this case it is about to free the page,
3108 * which must not have any queue state.
3110 qflags = atomic_load_8(&m->aflags);
3111 KASSERT(pq == vm_page_pagequeue(m) ||
3112 (qflags & PGA_QUEUE_STATE_MASK) == 0,
3113 ("page %p doesn't belong to queue %p but has aflags %#x",
3116 if ((qflags & PGA_DEQUEUE) != 0) {
3117 if (__predict_true((qflags & PGA_ENQUEUED) != 0))
3118 vm_pagequeue_remove(pq, m);
3119 vm_page_dequeue_complete(m);
3120 } else if ((qflags & (PGA_REQUEUE | PGA_REQUEUE_HEAD)) != 0) {
3121 if ((qflags & PGA_ENQUEUED) != 0)
3122 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3124 vm_pagequeue_cnt_inc(pq);
3125 vm_page_aflag_set(m, PGA_ENQUEUED);
3129 * Give PGA_REQUEUE_HEAD precedence over PGA_REQUEUE.
3130 * In particular, if both flags are set in close succession,
3131 * only PGA_REQUEUE_HEAD will be applied, even if it was set
3134 if ((qflags & PGA_REQUEUE_HEAD) != 0) {
3135 KASSERT(m->queue == PQ_INACTIVE,
3136 ("head enqueue not supported for page %p", m));
3137 vmd = vm_pagequeue_domain(m);
3138 TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3140 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3142 vm_page_aflag_clear(m, qflags & (PGA_REQUEUE |
3148 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3154 for (i = 0; i < bq->bq_cnt; i++) {
3156 if (__predict_false(m->queue != queue))
3158 vm_pqbatch_process_page(pq, m);
3160 vm_batchqueue_init(bq);
3164 * vm_page_pqbatch_submit: [ internal use only ]
3166 * Enqueue a page in the specified page queue's batched work queue.
3167 * The caller must have encoded the requested operation in the page
3168 * structure's aflags field.
3171 vm_page_pqbatch_submit(vm_page_t m, uint8_t queue)
3173 struct vm_batchqueue *bq;
3174 struct vm_pagequeue *pq;
3177 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3178 ("page %p is unmanaged", m));
3179 KASSERT(mtx_owned(vm_page_lockptr(m)) || m->object == NULL,
3180 ("missing synchronization for page %p", m));
3181 KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3183 domain = vm_phys_domain(m);
3184 pq = &vm_pagequeue_domain(m)->vmd_pagequeues[queue];
3187 bq = DPCPU_PTR(pqbatch[domain][queue]);
3188 if (vm_batchqueue_insert(bq, m)) {
3192 if (!vm_pagequeue_trylock(pq)) {
3194 vm_pagequeue_lock(pq);
3196 bq = DPCPU_PTR(pqbatch[domain][queue]);
3198 vm_pqbatch_process(pq, bq, queue);
3201 * The page may have been logically dequeued before we acquired the
3202 * page queue lock. In this case, since we either hold the page lock
3203 * or the page is being freed, a different thread cannot be concurrently
3204 * enqueuing the page.
3206 if (__predict_true(m->queue == queue))
3207 vm_pqbatch_process_page(pq, m);
3209 KASSERT(m->queue == PQ_NONE,
3210 ("invalid queue transition for page %p", m));
3211 KASSERT((m->aflags & PGA_ENQUEUED) == 0,
3212 ("page %p is enqueued with invalid queue index", m));
3214 vm_pagequeue_unlock(pq);
3219 * vm_page_pqbatch_drain: [ internal use only ]
3221 * Force all per-CPU page queue batch queues to be drained. This is
3222 * intended for use in severe memory shortages, to ensure that pages
3223 * do not remain stuck in the batch queues.
3226 vm_page_pqbatch_drain(void)
3229 struct vm_domain *vmd;
3230 struct vm_pagequeue *pq;
3231 int cpu, domain, queue;
3236 sched_bind(td, cpu);
3239 for (domain = 0; domain < vm_ndomains; domain++) {
3240 vmd = VM_DOMAIN(domain);
3241 for (queue = 0; queue < PQ_COUNT; queue++) {
3242 pq = &vmd->vmd_pagequeues[queue];
3243 vm_pagequeue_lock(pq);
3245 vm_pqbatch_process(pq,
3246 DPCPU_PTR(pqbatch[domain][queue]), queue);
3248 vm_pagequeue_unlock(pq);
3258 * Complete the logical removal of a page from a page queue. We must be
3259 * careful to synchronize with the page daemon, which may be concurrently
3260 * examining the page with only the page lock held. The page must not be
3261 * in a state where it appears to be logically enqueued.
3264 vm_page_dequeue_complete(vm_page_t m)
3268 atomic_thread_fence_rel();
3269 vm_page_aflag_clear(m, PGA_QUEUE_STATE_MASK);
3273 * vm_page_dequeue_deferred: [ internal use only ]
3275 * Request removal of the given page from its current page
3276 * queue. Physical removal from the queue may be deferred
3279 * The page must be locked.
3282 vm_page_dequeue_deferred(vm_page_t m)
3286 vm_page_assert_locked(m);
3288 if ((queue = vm_page_queue(m)) == PQ_NONE)
3292 * Set PGA_DEQUEUE if it is not already set to handle a concurrent call
3293 * to vm_page_dequeue_deferred_free(). In particular, avoid modifying
3294 * the page's queue state once vm_page_dequeue_deferred_free() has been
3295 * called. In the event of a race, two batch queue entries for the page
3296 * will be created, but the second will have no effect.
3298 if (vm_page_pqstate_cmpset(m, queue, queue, PGA_DEQUEUE, PGA_DEQUEUE))
3299 vm_page_pqbatch_submit(m, queue);
3303 * A variant of vm_page_dequeue_deferred() that does not assert the page
3304 * lock and is only to be called from vm_page_free_prep(). Because the
3305 * page is being freed, we can assume that nothing other than the page
3306 * daemon is scheduling queue operations on this page, so we get for
3307 * free the mutual exclusion that is otherwise provided by the page lock.
3308 * To handle races, the page daemon must take care to atomically check
3309 * for PGA_DEQUEUE when updating queue state.
3312 vm_page_dequeue_deferred_free(vm_page_t m)
3316 KASSERT(m->ref_count == 0, ("page %p has references", m));
3319 if ((m->aflags & PGA_DEQUEUE) != 0)
3321 atomic_thread_fence_acq();
3322 if ((queue = atomic_load_8(&m->queue)) == PQ_NONE)
3324 if (vm_page_pqstate_cmpset(m, queue, queue, PGA_DEQUEUE,
3326 vm_page_pqbatch_submit(m, queue);
3335 * Remove the page from whichever page queue it's in, if any.
3336 * The page must either be locked or unallocated. This constraint
3337 * ensures that the queue state of the page will remain consistent
3338 * after this function returns.
3341 vm_page_dequeue(vm_page_t m)
3343 struct vm_pagequeue *pq, *pq1;
3346 KASSERT(mtx_owned(vm_page_lockptr(m)) || m->object == NULL,
3347 ("page %p is allocated and unlocked", m));
3349 for (pq = vm_page_pagequeue(m);; pq = pq1) {
3352 * A thread may be concurrently executing
3353 * vm_page_dequeue_complete(). Ensure that all queue
3354 * state is cleared before we return.
3356 aflags = atomic_load_8(&m->aflags);
3357 if ((aflags & PGA_QUEUE_STATE_MASK) == 0)
3359 KASSERT((aflags & PGA_DEQUEUE) != 0,
3360 ("page %p has unexpected queue state flags %#x",
3364 * Busy wait until the thread updating queue state is
3365 * finished. Such a thread must be executing in a
3369 pq1 = vm_page_pagequeue(m);
3372 vm_pagequeue_lock(pq);
3373 if ((pq1 = vm_page_pagequeue(m)) == pq)
3375 vm_pagequeue_unlock(pq);
3377 KASSERT(pq == vm_page_pagequeue(m),
3378 ("%s: page %p migrated directly between queues", __func__, m));
3379 KASSERT((m->aflags & PGA_DEQUEUE) != 0 ||
3380 mtx_owned(vm_page_lockptr(m)),
3381 ("%s: queued unlocked page %p", __func__, m));
3383 if ((m->aflags & PGA_ENQUEUED) != 0)
3384 vm_pagequeue_remove(pq, m);
3385 vm_page_dequeue_complete(m);
3386 vm_pagequeue_unlock(pq);
3390 * Schedule the given page for insertion into the specified page queue.
3391 * Physical insertion of the page may be deferred indefinitely.
3394 vm_page_enqueue(vm_page_t m, uint8_t queue)
3397 vm_page_assert_locked(m);
3398 KASSERT(m->queue == PQ_NONE && (m->aflags & PGA_QUEUE_STATE_MASK) == 0,
3399 ("%s: page %p is already enqueued", __func__, m));
3402 if ((m->aflags & PGA_REQUEUE) == 0)
3403 vm_page_aflag_set(m, PGA_REQUEUE);
3404 vm_page_pqbatch_submit(m, queue);
3408 * vm_page_requeue: [ internal use only ]
3410 * Schedule a requeue of the given page.
3412 * The page must be locked.
3415 vm_page_requeue(vm_page_t m)
3418 vm_page_assert_locked(m);
3419 KASSERT(vm_page_queue(m) != PQ_NONE,
3420 ("%s: page %p is not logically enqueued", __func__, m));
3422 if ((m->aflags & PGA_REQUEUE) == 0)
3423 vm_page_aflag_set(m, PGA_REQUEUE);
3424 vm_page_pqbatch_submit(m, atomic_load_8(&m->queue));
3428 * vm_page_swapqueue: [ internal use only ]
3430 * Move the page from one queue to another, or to the tail of its
3431 * current queue, in the face of a possible concurrent call to
3432 * vm_page_dequeue_deferred_free().
3435 vm_page_swapqueue(vm_page_t m, uint8_t oldq, uint8_t newq)
3437 struct vm_pagequeue *pq;
3439 KASSERT(oldq < PQ_COUNT && newq < PQ_COUNT && oldq != newq,
3440 ("vm_page_swapqueue: invalid queues (%d, %d)", oldq, newq));
3441 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3442 ("vm_page_swapqueue: page %p is unmanaged", m));
3443 vm_page_assert_locked(m);
3446 * Atomically update the queue field and set PGA_REQUEUE while
3447 * ensuring that PGA_DEQUEUE has not been set.
3449 pq = &vm_pagequeue_domain(m)->vmd_pagequeues[oldq];
3450 vm_pagequeue_lock(pq);
3451 if (!vm_page_pqstate_cmpset(m, oldq, newq, PGA_DEQUEUE, PGA_REQUEUE)) {
3452 vm_pagequeue_unlock(pq);
3455 if ((m->aflags & PGA_ENQUEUED) != 0) {
3456 vm_pagequeue_remove(pq, m);
3457 vm_page_aflag_clear(m, PGA_ENQUEUED);
3459 vm_pagequeue_unlock(pq);
3460 vm_page_pqbatch_submit(m, newq);
3464 * vm_page_free_prep:
3466 * Prepares the given page to be put on the free list,
3467 * disassociating it from any VM object. The caller may return
3468 * the page to the free list only if this function returns true.
3470 * The object must be locked. The page must be locked if it is
3474 vm_page_free_prep(vm_page_t m)
3478 * Synchronize with threads that have dropped a reference to this
3481 atomic_thread_fence_acq();
3483 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
3484 if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
3487 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3488 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
3489 KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
3490 m, i, (uintmax_t)*p));
3493 if ((m->oflags & VPO_UNMANAGED) == 0)
3494 KASSERT(!pmap_page_is_mapped(m),
3495 ("vm_page_free_prep: freeing mapped page %p", m));
3497 KASSERT(m->queue == PQ_NONE,
3498 ("vm_page_free_prep: unmanaged page %p is queued", m));
3499 VM_CNT_INC(v_tfree);
3501 if (vm_page_sbusied(m))
3502 panic("vm_page_free_prep: freeing busy page %p", m);
3504 if (m->object != NULL) {
3505 vm_page_object_remove(m);
3508 * The object reference can be released without an atomic
3511 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
3512 m->ref_count == VPRC_OBJREF,
3513 ("vm_page_free_prep: page %p has unexpected ref_count %u",
3516 m->ref_count -= VPRC_OBJREF;
3520 * If fictitious remove object association and
3523 if ((m->flags & PG_FICTITIOUS) != 0) {
3524 KASSERT(m->ref_count == 1,
3525 ("fictitious page %p is referenced", m));
3526 KASSERT(m->queue == PQ_NONE,
3527 ("fictitious page %p is queued", m));
3532 * Pages need not be dequeued before they are returned to the physical
3533 * memory allocator, but they must at least be marked for a deferred
3536 if ((m->oflags & VPO_UNMANAGED) == 0)
3537 vm_page_dequeue_deferred_free(m);
3542 if (m->ref_count != 0)
3543 panic("vm_page_free_prep: page %p has references", m);
3546 * Restore the default memory attribute to the page.
3548 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3549 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3551 #if VM_NRESERVLEVEL > 0
3553 * Determine whether the page belongs to a reservation. If the page was
3554 * allocated from a per-CPU cache, it cannot belong to a reservation, so
3555 * as an optimization, we avoid the check in that case.
3557 if ((m->flags & PG_PCPU_CACHE) == 0 && vm_reserv_free_page(m))
3567 * Returns the given page to the free list, disassociating it
3568 * from any VM object.
3570 * The object must be locked. The page must be locked if it is
3574 vm_page_free_toq(vm_page_t m)
3576 struct vm_domain *vmd;
3579 if (!vm_page_free_prep(m))
3582 vmd = vm_pagequeue_domain(m);
3583 zone = vmd->vmd_pgcache[m->pool].zone;
3584 if ((m->flags & PG_PCPU_CACHE) != 0 && zone != NULL) {
3588 vm_domain_free_lock(vmd);
3589 vm_phys_free_pages(m, 0);
3590 vm_domain_free_unlock(vmd);
3591 vm_domain_freecnt_inc(vmd, 1);
3595 * vm_page_free_pages_toq:
3597 * Returns a list of pages to the free list, disassociating it
3598 * from any VM object. In other words, this is equivalent to
3599 * calling vm_page_free_toq() for each page of a list of VM objects.
3601 * The objects must be locked. The pages must be locked if it is
3605 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
3610 if (SLIST_EMPTY(free))
3614 while ((m = SLIST_FIRST(free)) != NULL) {
3616 SLIST_REMOVE_HEAD(free, plinks.s.ss);
3617 vm_page_free_toq(m);
3620 if (update_wire_count)
3625 * Mark this page as wired down, preventing reclamation by the page daemon
3626 * or when the containing object is destroyed.
3629 vm_page_wire(vm_page_t m)
3633 KASSERT(m->object != NULL,
3634 ("vm_page_wire: page %p does not belong to an object", m));
3635 if (!vm_page_busied(m))
3636 VM_OBJECT_ASSERT_LOCKED(m->object);
3637 KASSERT((m->flags & PG_FICTITIOUS) == 0 ||
3638 VPRC_WIRE_COUNT(m->ref_count) >= 1,
3639 ("vm_page_wire: fictitious page %p has zero wirings", m));
3641 old = atomic_fetchadd_int(&m->ref_count, 1);
3642 KASSERT(VPRC_WIRE_COUNT(old) != VPRC_WIRE_COUNT_MAX,
3643 ("vm_page_wire: counter overflow for page %p", m));
3644 if (VPRC_WIRE_COUNT(old) == 0)
3649 * Attempt to wire a mapped page following a pmap lookup of that page.
3650 * This may fail if a thread is concurrently tearing down mappings of the page.
3653 vm_page_wire_mapped(vm_page_t m)
3660 ("vm_page_wire_mapped: wiring unreferenced page %p", m));
3661 if ((old & VPRC_BLOCKED) != 0)
3663 } while (!atomic_fcmpset_int(&m->ref_count, &old, old + 1));
3665 if (VPRC_WIRE_COUNT(old) == 0)
3671 * Release one wiring of the specified page, potentially allowing it to be
3674 * Only managed pages belonging to an object can be paged out. If the number
3675 * of wirings transitions to zero and the page is eligible for page out, then
3676 * the page is added to the specified paging queue. If the released wiring
3677 * represented the last reference to the page, the page is freed.
3679 * A managed page must be locked.
3682 vm_page_unwire(vm_page_t m, uint8_t queue)
3687 KASSERT(queue < PQ_COUNT,
3688 ("vm_page_unwire: invalid queue %u request for page %p", queue, m));
3690 if ((m->oflags & VPO_UNMANAGED) != 0) {
3691 if (vm_page_unwire_noq(m) && m->ref_count == 0)
3697 * Update LRU state before releasing the wiring reference.
3698 * We only need to do this once since we hold the page lock.
3699 * Use a release store when updating the reference count to
3700 * synchronize with vm_page_free_prep().
3705 KASSERT(VPRC_WIRE_COUNT(old) > 0,
3706 ("vm_page_unwire: wire count underflow for page %p", m));
3707 if (!locked && VPRC_WIRE_COUNT(old) == 1) {
3710 if (queue == PQ_ACTIVE && vm_page_queue(m) == PQ_ACTIVE)
3711 vm_page_reference(m);
3713 vm_page_mvqueue(m, queue);
3715 } while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
3718 * Release the lock only after the wiring is released, to ensure that
3719 * the page daemon does not encounter and dequeue the page while it is
3725 if (VPRC_WIRE_COUNT(old) == 1) {
3733 * Unwire a page without (re-)inserting it into a page queue. It is up
3734 * to the caller to enqueue, requeue, or free the page as appropriate.
3735 * In most cases involving managed pages, vm_page_unwire() should be used
3739 vm_page_unwire_noq(vm_page_t m)
3743 old = vm_page_drop(m, 1);
3744 KASSERT(VPRC_WIRE_COUNT(old) != 0,
3745 ("vm_page_unref: counter underflow for page %p", m));
3746 KASSERT((m->flags & PG_FICTITIOUS) == 0 || VPRC_WIRE_COUNT(old) > 1,
3747 ("vm_page_unref: missing ref on fictitious page %p", m));
3749 if (VPRC_WIRE_COUNT(old) > 1)
3756 * Ensure that the page is in the specified page queue. If the page is
3757 * active or being moved to the active queue, ensure that its act_count is
3758 * at least ACT_INIT but do not otherwise mess with it. Otherwise, ensure that
3759 * the page is at the tail of its page queue.
3761 * The page may be wired. The caller should release its wiring reference
3762 * before releasing the page lock, otherwise the page daemon may immediately
3765 * A managed page must be locked.
3767 static __always_inline void
3768 vm_page_mvqueue(vm_page_t m, const uint8_t nqueue)
3771 vm_page_assert_locked(m);
3772 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3773 ("vm_page_mvqueue: page %p is unmanaged", m));
3775 if (vm_page_queue(m) != nqueue) {
3777 vm_page_enqueue(m, nqueue);
3778 } else if (nqueue != PQ_ACTIVE) {
3782 if (nqueue == PQ_ACTIVE && m->act_count < ACT_INIT)
3783 m->act_count = ACT_INIT;
3787 * Put the specified page on the active list (if appropriate).
3790 vm_page_activate(vm_page_t m)
3793 if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
3795 vm_page_mvqueue(m, PQ_ACTIVE);
3799 * Move the specified page to the tail of the inactive queue, or requeue
3800 * the page if it is already in the inactive queue.
3803 vm_page_deactivate(vm_page_t m)
3806 if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
3808 vm_page_mvqueue(m, PQ_INACTIVE);
3812 * Move the specified page close to the head of the inactive queue,
3813 * bypassing LRU. A marker page is used to maintain FIFO ordering.
3814 * As with regular enqueues, we use a per-CPU batch queue to reduce
3815 * contention on the page queue lock.
3818 _vm_page_deactivate_noreuse(vm_page_t m)
3821 vm_page_assert_locked(m);
3823 if (!vm_page_inactive(m)) {
3825 m->queue = PQ_INACTIVE;
3827 if ((m->aflags & PGA_REQUEUE_HEAD) == 0)
3828 vm_page_aflag_set(m, PGA_REQUEUE_HEAD);
3829 vm_page_pqbatch_submit(m, PQ_INACTIVE);
3833 vm_page_deactivate_noreuse(vm_page_t m)
3836 KASSERT(m->object != NULL,
3837 ("vm_page_deactivate_noreuse: page %p has no object", m));
3839 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_wired(m))
3840 _vm_page_deactivate_noreuse(m);
3844 * Put a page in the laundry, or requeue it if it is already there.
3847 vm_page_launder(vm_page_t m)
3850 if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
3852 vm_page_mvqueue(m, PQ_LAUNDRY);
3856 * Put a page in the PQ_UNSWAPPABLE holding queue.
3859 vm_page_unswappable(vm_page_t m)
3862 vm_page_assert_locked(m);
3863 KASSERT(!vm_page_wired(m) && (m->oflags & VPO_UNMANAGED) == 0,
3864 ("page %p already unswappable", m));
3867 vm_page_enqueue(m, PQ_UNSWAPPABLE);
3871 vm_page_release_toq(vm_page_t m, int flags)
3874 vm_page_assert_locked(m);
3877 * Use a check of the valid bits to determine whether we should
3878 * accelerate reclamation of the page. The object lock might not be
3879 * held here, in which case the check is racy. At worst we will either
3880 * accelerate reclamation of a valid page and violate LRU, or
3881 * unnecessarily defer reclamation of an invalid page.
3883 * If we were asked to not cache the page, place it near the head of the
3884 * inactive queue so that is reclaimed sooner.
3886 if ((flags & (VPR_TRYFREE | VPR_NOREUSE)) != 0 || m->valid == 0)
3887 _vm_page_deactivate_noreuse(m);
3888 else if (vm_page_active(m))
3889 vm_page_reference(m);
3891 vm_page_mvqueue(m, PQ_INACTIVE);
3895 * Unwire a page and either attempt to free it or re-add it to the page queues.
3898 vm_page_release(vm_page_t m, int flags)
3904 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3905 ("vm_page_release: page %p is unmanaged", m));
3907 if ((flags & VPR_TRYFREE) != 0) {
3909 object = (vm_object_t)atomic_load_ptr(&m->object);
3912 /* Depends on type-stability. */
3913 if (vm_page_busied(m) || !VM_OBJECT_TRYWLOCK(object)) {
3917 if (object == m->object)
3919 VM_OBJECT_WUNLOCK(object);
3921 if (__predict_true(object != NULL)) {
3922 vm_page_release_locked(m, flags);
3923 VM_OBJECT_WUNLOCK(object);
3929 * Update LRU state before releasing the wiring reference.
3930 * Use a release store when updating the reference count to
3931 * synchronize with vm_page_free_prep().
3936 KASSERT(VPRC_WIRE_COUNT(old) > 0,
3937 ("vm_page_unwire: wire count underflow for page %p", m));
3938 if (!locked && VPRC_WIRE_COUNT(old) == 1) {
3941 vm_page_release_toq(m, flags);
3943 } while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
3946 * Release the lock only after the wiring is released, to ensure that
3947 * the page daemon does not encounter and dequeue the page while it is
3953 if (VPRC_WIRE_COUNT(old) == 1) {
3960 /* See vm_page_release(). */
3962 vm_page_release_locked(vm_page_t m, int flags)
3965 VM_OBJECT_ASSERT_WLOCKED(m->object);
3966 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3967 ("vm_page_release_locked: page %p is unmanaged", m));
3969 if (vm_page_unwire_noq(m)) {
3970 if ((flags & VPR_TRYFREE) != 0 &&
3971 (m->object->ref_count == 0 || !pmap_page_is_mapped(m)) &&
3972 m->dirty == 0 && !vm_page_busied(m)) {
3976 vm_page_release_toq(m, flags);
3983 vm_page_try_blocked_op(vm_page_t m, void (*op)(vm_page_t))
3987 KASSERT(m->object != NULL && (m->oflags & VPO_UNMANAGED) == 0,
3988 ("vm_page_try_blocked_op: page %p has no object", m));
3989 KASSERT(!vm_page_busied(m),
3990 ("vm_page_try_blocked_op: page %p is busy", m));
3991 VM_OBJECT_ASSERT_LOCKED(m->object);
3996 ("vm_page_try_blocked_op: page %p has no references", m));
3997 if (VPRC_WIRE_COUNT(old) != 0)
3999 } while (!atomic_fcmpset_int(&m->ref_count, &old, old | VPRC_BLOCKED));
4004 * If the object is read-locked, new wirings may be created via an
4007 old = vm_page_drop(m, VPRC_BLOCKED);
4008 KASSERT(!VM_OBJECT_WOWNED(m->object) ||
4009 old == (VPRC_BLOCKED | VPRC_OBJREF),
4010 ("vm_page_try_blocked_op: unexpected refcount value %u for %p",
4016 * Atomically check for wirings and remove all mappings of the page.
4019 vm_page_try_remove_all(vm_page_t m)
4022 return (vm_page_try_blocked_op(m, pmap_remove_all));
4026 * Atomically check for wirings and remove all writeable mappings of the page.
4029 vm_page_try_remove_write(vm_page_t m)
4032 return (vm_page_try_blocked_op(m, pmap_remove_write));
4038 * Apply the specified advice to the given page.
4040 * The object and page must be locked.
4043 vm_page_advise(vm_page_t m, int advice)
4046 vm_page_assert_locked(m);
4047 VM_OBJECT_ASSERT_WLOCKED(m->object);
4048 if (advice == MADV_FREE)
4050 * Mark the page clean. This will allow the page to be freed
4051 * without first paging it out. MADV_FREE pages are often
4052 * quickly reused by malloc(3), so we do not do anything that
4053 * would result in a page fault on a later access.
4056 else if (advice != MADV_DONTNEED) {
4057 if (advice == MADV_WILLNEED)
4058 vm_page_activate(m);
4063 * Clear any references to the page. Otherwise, the page daemon will
4064 * immediately reactivate the page.
4066 vm_page_aflag_clear(m, PGA_REFERENCED);
4068 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
4072 * Place clean pages near the head of the inactive queue rather than
4073 * the tail, thus defeating the queue's LRU operation and ensuring that
4074 * the page will be reused quickly. Dirty pages not already in the
4075 * laundry are moved there.
4078 vm_page_deactivate_noreuse(m);
4079 else if (!vm_page_in_laundry(m))
4084 * Grab a page, waiting until we are waken up due to the page
4085 * changing state. We keep on waiting, if the page continues
4086 * to be in the object. If the page doesn't exist, first allocate it
4087 * and then conditionally zero it.
4089 * This routine may sleep.
4091 * The object must be locked on entry. The lock will, however, be released
4092 * and reacquired if the routine sleeps.
4095 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
4101 VM_OBJECT_ASSERT_WLOCKED(object);
4102 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4103 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4104 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4105 pflags = allocflags &
4106 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
4107 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4108 pflags |= VM_ALLOC_WAITFAIL;
4110 if ((m = vm_page_lookup(object, pindex)) != NULL) {
4111 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
4112 vm_page_xbusied(m) : vm_page_busied(m);
4114 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4117 * Reference the page before unlocking and
4118 * sleeping so that the page daemon is less
4119 * likely to reclaim it.
4121 if ((allocflags & VM_ALLOC_NOCREAT) == 0)
4122 vm_page_aflag_set(m, PGA_REFERENCED);
4123 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
4124 VM_ALLOC_IGN_SBUSY) != 0);
4125 VM_OBJECT_WLOCK(object);
4126 if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
4130 if ((allocflags & VM_ALLOC_WIRED) != 0)
4133 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
4135 else if ((allocflags & VM_ALLOC_SBUSY) != 0)
4140 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4142 m = vm_page_alloc(object, pindex, pflags);
4144 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4148 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
4154 * Grab a page and make it valid, paging in if necessary. Pages missing from
4155 * their pager are zero filled and validated.
4158 vm_page_grab_valid(vm_page_t *mp, vm_object_t object, vm_pindex_t pindex, int allocflags)
4165 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4166 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4167 ("vm_page_grab_valid: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4168 KASSERT((allocflags &
4169 (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4170 ("vm_page_grab_valid: Invalid flags 0x%X", allocflags));
4171 VM_OBJECT_ASSERT_WLOCKED(object);
4172 pflags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY);
4173 pflags |= VM_ALLOC_WAITFAIL;
4177 if ((m = vm_page_lookup(object, pindex)) != NULL) {
4179 * If the page is fully valid it can only become invalid
4180 * with the object lock held. If it is not valid it can
4181 * become valid with the busy lock held. Therefore, we
4182 * may unnecessarily lock the exclusive busy here if we
4183 * race with I/O completion not using the object lock.
4184 * However, we will not end up with an invalid page and a
4187 if (m->valid != VM_PAGE_BITS_ALL ||
4188 (allocflags & (VM_ALLOC_IGN_SBUSY | VM_ALLOC_SBUSY)) == 0) {
4189 sleep = !vm_page_tryxbusy(m);
4192 sleep = !vm_page_trysbusy(m);
4195 * Reference the page before unlocking and
4196 * sleeping so that the page daemon is less
4197 * likely to reclaim it.
4199 if ((allocflags & VM_ALLOC_NOCREAT) == 0)
4200 vm_page_aflag_set(m, PGA_REFERENCED);
4201 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
4202 VM_ALLOC_IGN_SBUSY) != 0);
4203 VM_OBJECT_WLOCK(object);
4206 if ((allocflags & VM_ALLOC_NOCREAT) != 0 &&
4207 m->valid != VM_PAGE_BITS_ALL) {
4213 return (VM_PAGER_FAIL);
4215 if ((allocflags & VM_ALLOC_WIRED) != 0)
4217 if (m->valid == VM_PAGE_BITS_ALL)
4219 } else if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4221 return (VM_PAGER_FAIL);
4222 } else if ((m = vm_page_alloc(object, pindex, pflags)) != NULL) {
4228 vm_page_assert_xbusied(m);
4230 if (vm_pager_has_page(object, pindex, NULL, NULL)) {
4231 rv = vm_pager_get_pages(object, &m, 1, NULL, NULL);
4232 if (rv != VM_PAGER_OK) {
4233 if (allocflags & VM_ALLOC_WIRED)
4234 vm_page_unwire_noq(m);
4239 MPASS(m->valid == VM_PAGE_BITS_ALL);
4241 vm_page_zero_invalid(m, TRUE);
4244 if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4250 if ((allocflags & VM_ALLOC_SBUSY) != 0 && xbusy)
4251 vm_page_busy_downgrade(m);
4253 return (VM_PAGER_OK);
4257 * Return the specified range of pages from the given object. For each
4258 * page offset within the range, if a page already exists within the object
4259 * at that offset and it is busy, then wait for it to change state. If,
4260 * instead, the page doesn't exist, then allocate it.
4262 * The caller must always specify an allocation class.
4264 * allocation classes:
4265 * VM_ALLOC_NORMAL normal process request
4266 * VM_ALLOC_SYSTEM system *really* needs the pages
4268 * The caller must always specify that the pages are to be busied and/or
4271 * optional allocation flags:
4272 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
4273 * VM_ALLOC_NOBUSY do not exclusive busy the page
4274 * VM_ALLOC_NOWAIT do not sleep
4275 * VM_ALLOC_SBUSY set page to sbusy state
4276 * VM_ALLOC_WIRED wire the pages
4277 * VM_ALLOC_ZERO zero and validate any invalid pages
4279 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
4280 * may return a partial prefix of the requested range.
4283 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
4284 vm_page_t *ma, int count)
4291 VM_OBJECT_ASSERT_WLOCKED(object);
4292 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
4293 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
4294 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
4295 (allocflags & VM_ALLOC_WIRED) != 0,
4296 ("vm_page_grab_pages: the pages must be busied or wired"));
4297 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4298 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4299 ("vm_page_grab_pages: VM_ALLOC_SBUSY/IGN_SBUSY mismatch"));
4302 pflags = allocflags & ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK |
4303 VM_ALLOC_WAITFAIL | VM_ALLOC_IGN_SBUSY);
4304 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4305 pflags |= VM_ALLOC_WAITFAIL;
4308 m = vm_radix_lookup_le(&object->rtree, pindex + i);
4309 if (m == NULL || m->pindex != pindex + i) {
4313 mpred = TAILQ_PREV(m, pglist, listq);
4314 for (; i < count; i++) {
4316 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
4317 vm_page_xbusied(m) : vm_page_busied(m);
4319 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4322 * Reference the page before unlocking and
4323 * sleeping so that the page daemon is less
4324 * likely to reclaim it.
4326 if ((allocflags & VM_ALLOC_NOCREAT) == 0)
4327 vm_page_aflag_set(m, PGA_REFERENCED);
4328 vm_page_busy_sleep(m, "grbmaw", (allocflags &
4329 VM_ALLOC_IGN_SBUSY) != 0);
4330 VM_OBJECT_WLOCK(object);
4333 if ((allocflags & VM_ALLOC_WIRED) != 0)
4335 if ((allocflags & (VM_ALLOC_NOBUSY |
4336 VM_ALLOC_SBUSY)) == 0)
4338 if ((allocflags & VM_ALLOC_SBUSY) != 0)
4341 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4343 m = vm_page_alloc_after(object, pindex + i,
4344 pflags | VM_ALLOC_COUNT(count - i), mpred);
4346 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4351 if (m->valid == 0 && (allocflags & VM_ALLOC_ZERO) != 0) {
4352 if ((m->flags & PG_ZERO) == 0)
4354 m->valid = VM_PAGE_BITS_ALL;
4357 m = vm_page_next(m);
4363 * Mapping function for valid or dirty bits in a page.
4365 * Inputs are required to range within a page.
4368 vm_page_bits(int base, int size)
4374 base + size <= PAGE_SIZE,
4375 ("vm_page_bits: illegal base/size %d/%d", base, size)
4378 if (size == 0) /* handle degenerate case */
4381 first_bit = base >> DEV_BSHIFT;
4382 last_bit = (base + size - 1) >> DEV_BSHIFT;
4384 return (((vm_page_bits_t)2 << last_bit) -
4385 ((vm_page_bits_t)1 << first_bit));
4389 * vm_page_set_valid_range:
4391 * Sets portions of a page valid. The arguments are expected
4392 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4393 * of any partial chunks touched by the range. The invalid portion of
4394 * such chunks will be zeroed.
4396 * (base + size) must be less then or equal to PAGE_SIZE.
4399 vm_page_set_valid_range(vm_page_t m, int base, int size)
4403 VM_OBJECT_ASSERT_WLOCKED(m->object);
4404 if (size == 0) /* handle degenerate case */
4408 * If the base is not DEV_BSIZE aligned and the valid
4409 * bit is clear, we have to zero out a portion of the
4412 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4413 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
4414 pmap_zero_page_area(m, frag, base - frag);
4417 * If the ending offset is not DEV_BSIZE aligned and the
4418 * valid bit is clear, we have to zero out a portion of
4421 endoff = base + size;
4422 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4423 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
4424 pmap_zero_page_area(m, endoff,
4425 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4428 * Assert that no previously invalid block that is now being validated
4431 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
4432 ("vm_page_set_valid_range: page %p is dirty", m));
4435 * Set valid bits inclusive of any overlap.
4437 m->valid |= vm_page_bits(base, size);
4441 * Clear the given bits from the specified page's dirty field.
4443 static __inline void
4444 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
4447 #if PAGE_SIZE < 16384
4452 * If the object is locked and the page is neither exclusive busy nor
4453 * write mapped, then the page's dirty field cannot possibly be
4454 * set by a concurrent pmap operation.
4456 VM_OBJECT_ASSERT_WLOCKED(m->object);
4457 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
4458 m->dirty &= ~pagebits;
4461 * The pmap layer can call vm_page_dirty() without
4462 * holding a distinguished lock. The combination of
4463 * the object's lock and an atomic operation suffice
4464 * to guarantee consistency of the page dirty field.
4466 * For PAGE_SIZE == 32768 case, compiler already
4467 * properly aligns the dirty field, so no forcible
4468 * alignment is needed. Only require existence of
4469 * atomic_clear_64 when page size is 32768.
4471 addr = (uintptr_t)&m->dirty;
4472 #if PAGE_SIZE == 32768
4473 atomic_clear_64((uint64_t *)addr, pagebits);
4474 #elif PAGE_SIZE == 16384
4475 atomic_clear_32((uint32_t *)addr, pagebits);
4476 #else /* PAGE_SIZE <= 8192 */
4478 * Use a trick to perform a 32-bit atomic on the
4479 * containing aligned word, to not depend on the existence
4480 * of atomic_clear_{8, 16}.
4482 shift = addr & (sizeof(uint32_t) - 1);
4483 #if BYTE_ORDER == BIG_ENDIAN
4484 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
4488 addr &= ~(sizeof(uint32_t) - 1);
4489 atomic_clear_32((uint32_t *)addr, pagebits << shift);
4490 #endif /* PAGE_SIZE */
4495 * vm_page_set_validclean:
4497 * Sets portions of a page valid and clean. The arguments are expected
4498 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4499 * of any partial chunks touched by the range. The invalid portion of
4500 * such chunks will be zero'd.
4502 * (base + size) must be less then or equal to PAGE_SIZE.
4505 vm_page_set_validclean(vm_page_t m, int base, int size)
4507 vm_page_bits_t oldvalid, pagebits;
4510 VM_OBJECT_ASSERT_WLOCKED(m->object);
4511 if (size == 0) /* handle degenerate case */
4515 * If the base is not DEV_BSIZE aligned and the valid
4516 * bit is clear, we have to zero out a portion of the
4519 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4520 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
4521 pmap_zero_page_area(m, frag, base - frag);
4524 * If the ending offset is not DEV_BSIZE aligned and the
4525 * valid bit is clear, we have to zero out a portion of
4528 endoff = base + size;
4529 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4530 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
4531 pmap_zero_page_area(m, endoff,
4532 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4535 * Set valid, clear dirty bits. If validating the entire
4536 * page we can safely clear the pmap modify bit. We also
4537 * use this opportunity to clear the VPO_NOSYNC flag. If a process
4538 * takes a write fault on a MAP_NOSYNC memory area the flag will
4541 * We set valid bits inclusive of any overlap, but we can only
4542 * clear dirty bits for DEV_BSIZE chunks that are fully within
4545 oldvalid = m->valid;
4546 pagebits = vm_page_bits(base, size);
4547 m->valid |= pagebits;
4549 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
4550 frag = DEV_BSIZE - frag;
4556 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
4558 if (base == 0 && size == PAGE_SIZE) {
4560 * The page can only be modified within the pmap if it is
4561 * mapped, and it can only be mapped if it was previously
4564 if (oldvalid == VM_PAGE_BITS_ALL)
4566 * Perform the pmap_clear_modify() first. Otherwise,
4567 * a concurrent pmap operation, such as
4568 * pmap_protect(), could clear a modification in the
4569 * pmap and set the dirty field on the page before
4570 * pmap_clear_modify() had begun and after the dirty
4571 * field was cleared here.
4573 pmap_clear_modify(m);
4575 m->oflags &= ~VPO_NOSYNC;
4576 } else if (oldvalid != VM_PAGE_BITS_ALL)
4577 m->dirty &= ~pagebits;
4579 vm_page_clear_dirty_mask(m, pagebits);
4583 vm_page_clear_dirty(vm_page_t m, int base, int size)
4586 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
4590 * vm_page_set_invalid:
4592 * Invalidates DEV_BSIZE'd chunks within a page. Both the
4593 * valid and dirty bits for the effected areas are cleared.
4596 vm_page_set_invalid(vm_page_t m, int base, int size)
4598 vm_page_bits_t bits;
4602 VM_OBJECT_ASSERT_WLOCKED(object);
4603 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
4604 size >= object->un_pager.vnp.vnp_size)
4605 bits = VM_PAGE_BITS_ALL;
4607 bits = vm_page_bits(base, size);
4608 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
4611 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
4612 !pmap_page_is_mapped(m),
4613 ("vm_page_set_invalid: page %p is mapped", m));
4619 * vm_page_zero_invalid()
4621 * The kernel assumes that the invalid portions of a page contain
4622 * garbage, but such pages can be mapped into memory by user code.
4623 * When this occurs, we must zero out the non-valid portions of the
4624 * page so user code sees what it expects.
4626 * Pages are most often semi-valid when the end of a file is mapped
4627 * into memory and the file's size is not page aligned.
4630 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
4635 VM_OBJECT_ASSERT_WLOCKED(m->object);
4637 * Scan the valid bits looking for invalid sections that
4638 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
4639 * valid bit may be set ) have already been zeroed by
4640 * vm_page_set_validclean().
4642 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
4643 if (i == (PAGE_SIZE / DEV_BSIZE) ||
4644 (m->valid & ((vm_page_bits_t)1 << i))) {
4646 pmap_zero_page_area(m,
4647 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
4654 * setvalid is TRUE when we can safely set the zero'd areas
4655 * as being valid. We can do this if there are no cache consistancy
4656 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
4659 m->valid = VM_PAGE_BITS_ALL;
4665 * Is (partial) page valid? Note that the case where size == 0
4666 * will return FALSE in the degenerate case where the page is
4667 * entirely invalid, and TRUE otherwise.
4670 vm_page_is_valid(vm_page_t m, int base, int size)
4672 vm_page_bits_t bits;
4674 VM_OBJECT_ASSERT_LOCKED(m->object);
4675 bits = vm_page_bits(base, size);
4676 return (m->valid != 0 && (m->valid & bits) == bits);
4680 * Returns true if all of the specified predicates are true for the entire
4681 * (super)page and false otherwise.
4684 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
4690 if (skip_m != NULL && skip_m->object != object)
4692 VM_OBJECT_ASSERT_LOCKED(object);
4693 npages = atop(pagesizes[m->psind]);
4696 * The physically contiguous pages that make up a superpage, i.e., a
4697 * page with a page size index ("psind") greater than zero, will
4698 * occupy adjacent entries in vm_page_array[].
4700 for (i = 0; i < npages; i++) {
4701 /* Always test object consistency, including "skip_m". */
4702 if (m[i].object != object)
4704 if (&m[i] == skip_m)
4706 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
4708 if ((flags & PS_ALL_DIRTY) != 0) {
4710 * Calling vm_page_test_dirty() or pmap_is_modified()
4711 * might stop this case from spuriously returning
4712 * "false". However, that would require a write lock
4713 * on the object containing "m[i]".
4715 if (m[i].dirty != VM_PAGE_BITS_ALL)
4718 if ((flags & PS_ALL_VALID) != 0 &&
4719 m[i].valid != VM_PAGE_BITS_ALL)
4726 * Set the page's dirty bits if the page is modified.
4729 vm_page_test_dirty(vm_page_t m)
4732 VM_OBJECT_ASSERT_WLOCKED(m->object);
4733 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
4738 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
4741 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
4745 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
4748 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
4752 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
4755 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
4758 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
4760 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
4763 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
4767 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
4770 mtx_assert_(vm_page_lockptr(m), a, file, line);
4776 vm_page_object_lock_assert(vm_page_t m)
4780 * Certain of the page's fields may only be modified by the
4781 * holder of the containing object's lock or the exclusive busy.
4782 * holder. Unfortunately, the holder of the write busy is
4783 * not recorded, and thus cannot be checked here.
4785 if (m->object != NULL && !vm_page_xbusied(m))
4786 VM_OBJECT_ASSERT_WLOCKED(m->object);
4790 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
4793 if ((bits & PGA_WRITEABLE) == 0)
4797 * The PGA_WRITEABLE flag can only be set if the page is
4798 * managed, is exclusively busied or the object is locked.
4799 * Currently, this flag is only set by pmap_enter().
4801 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4802 ("PGA_WRITEABLE on unmanaged page"));
4803 if (!vm_page_xbusied(m))
4804 VM_OBJECT_ASSERT_LOCKED(m->object);
4808 #include "opt_ddb.h"
4810 #include <sys/kernel.h>
4812 #include <ddb/ddb.h>
4814 DB_SHOW_COMMAND(page, vm_page_print_page_info)
4817 db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
4818 db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
4819 db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
4820 db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
4821 db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
4822 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
4823 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
4824 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
4825 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
4828 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
4832 db_printf("pq_free %d\n", vm_free_count());
4833 for (dom = 0; dom < vm_ndomains; dom++) {
4835 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
4837 vm_dom[dom].vmd_page_count,
4838 vm_dom[dom].vmd_free_count,
4839 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
4840 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
4841 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
4842 vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
4846 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
4849 boolean_t phys, virt;
4852 db_printf("show pginfo addr\n");
4856 phys = strchr(modif, 'p') != NULL;
4857 virt = strchr(modif, 'v') != NULL;
4859 m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
4861 m = PHYS_TO_VM_PAGE(addr);
4863 m = (vm_page_t)addr;
4865 "page %p obj %p pidx 0x%jx phys 0x%jx q %d ref %u\n"
4866 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
4867 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
4868 m->queue, m->ref_count, m->aflags, m->oflags,
4869 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);