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>
76 #include <sys/counter.h>
77 #include <sys/domainset.h>
78 #include <sys/kernel.h>
79 #include <sys/limits.h>
80 #include <sys/linker.h>
82 #include <sys/malloc.h>
84 #include <sys/msgbuf.h>
85 #include <sys/mutex.h>
87 #include <sys/rwlock.h>
88 #include <sys/sleepqueue.h>
90 #include <sys/sched.h>
92 #include <sys/sysctl.h>
93 #include <sys/vmmeter.h>
94 #include <sys/vnode.h>
98 #include <vm/vm_param.h>
99 #include <vm/vm_domainset.h>
100 #include <vm/vm_kern.h>
101 #include <vm/vm_map.h>
102 #include <vm/vm_object.h>
103 #include <vm/vm_page.h>
104 #include <vm/vm_pageout.h>
105 #include <vm/vm_phys.h>
106 #include <vm/vm_pagequeue.h>
107 #include <vm/vm_pager.h>
108 #include <vm/vm_radix.h>
109 #include <vm/vm_reserv.h>
110 #include <vm/vm_extern.h>
112 #include <vm/uma_int.h>
114 #include <machine/md_var.h>
116 extern int uma_startup_count(int);
117 extern void uma_startup(void *, int);
118 extern int vmem_startup_count(void);
120 struct vm_domain vm_dom[MAXMEMDOM];
122 DPCPU_DEFINE_STATIC(struct vm_batchqueue, pqbatch[MAXMEMDOM][PQ_COUNT]);
124 struct mtx_padalign __exclusive_cache_line pa_lock[PA_LOCK_COUNT];
126 struct mtx_padalign __exclusive_cache_line vm_domainset_lock;
127 /* The following fields are protected by the domainset lock. */
128 domainset_t __exclusive_cache_line vm_min_domains;
129 domainset_t __exclusive_cache_line vm_severe_domains;
130 static int vm_min_waiters;
131 static int vm_severe_waiters;
132 static int vm_pageproc_waiters;
134 static SYSCTL_NODE(_vm_stats, OID_AUTO, page, CTLFLAG_RD, 0,
135 "VM page statistics");
137 static counter_u64_t pqstate_commit_retries = EARLY_COUNTER;
138 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, pqstate_commit_retries,
139 CTLFLAG_RD, &pqstate_commit_retries,
140 "Number of failed per-page atomic queue state updates");
142 static counter_u64_t queue_ops = EARLY_COUNTER;
143 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, queue_ops,
144 CTLFLAG_RD, &queue_ops,
145 "Number of batched queue operations");
147 static counter_u64_t queue_nops = EARLY_COUNTER;
148 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, queue_nops,
149 CTLFLAG_RD, &queue_nops,
150 "Number of batched queue operations with no effects");
153 counter_startup(void)
156 pqstate_commit_retries = counter_u64_alloc(M_WAITOK);
157 queue_ops = counter_u64_alloc(M_WAITOK);
158 queue_nops = counter_u64_alloc(M_WAITOK);
160 SYSINIT(page_counters, SI_SUB_CPU, SI_ORDER_ANY, counter_startup, NULL);
163 * bogus page -- for I/O to/from partially complete buffers,
164 * or for paging into sparsely invalid regions.
166 vm_page_t bogus_page;
168 vm_page_t vm_page_array;
169 long vm_page_array_size;
172 static int boot_pages;
173 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
175 "number of pages allocated for bootstrapping the VM system");
177 static TAILQ_HEAD(, vm_page) blacklist_head;
178 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
179 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
180 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
182 static uma_zone_t fakepg_zone;
184 static void vm_page_alloc_check(vm_page_t m);
185 static bool _vm_page_busy_sleep(vm_object_t obj, vm_page_t m,
186 const char *wmesg, bool nonshared, bool locked);
187 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
188 static void vm_page_enqueue(vm_page_t m, uint8_t queue);
189 static bool vm_page_free_prep(vm_page_t m);
190 static void vm_page_free_toq(vm_page_t m);
191 static void vm_page_init(void *dummy);
192 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
193 vm_pindex_t pindex, vm_page_t mpred);
194 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
196 static void vm_page_mvqueue(vm_page_t m, const uint8_t queue,
197 const uint16_t nflag);
198 static int vm_page_reclaim_run(int req_class, int domain, u_long npages,
199 vm_page_t m_run, vm_paddr_t high);
200 static void vm_page_release_toq(vm_page_t m, uint8_t nqueue, bool noreuse);
201 static int vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object,
203 static int vm_page_zone_import(void *arg, void **store, int cnt, int domain,
205 static void vm_page_zone_release(void *arg, void **store, int cnt);
207 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
210 vm_page_init(void *dummy)
213 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
214 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
215 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
216 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
220 * The cache page zone is initialized later since we need to be able to allocate
221 * pages before UMA is fully initialized.
224 vm_page_init_cache_zones(void *dummy __unused)
226 struct vm_domain *vmd;
227 struct vm_pgcache *pgcache;
228 int cache, domain, maxcache, pool;
231 TUNABLE_INT_FETCH("vm.pgcache_zone_max", &maxcache);
232 for (domain = 0; domain < vm_ndomains; domain++) {
233 vmd = VM_DOMAIN(domain);
234 for (pool = 0; pool < VM_NFREEPOOL; pool++) {
235 pgcache = &vmd->vmd_pgcache[pool];
236 pgcache->domain = domain;
237 pgcache->pool = pool;
238 pgcache->zone = uma_zcache_create("vm pgcache",
239 PAGE_SIZE, NULL, NULL, NULL, NULL,
240 vm_page_zone_import, vm_page_zone_release, pgcache,
244 * Limit each pool's zone to 0.1% of the pages in the
247 cache = maxcache != 0 ? maxcache :
248 vmd->vmd_page_count / 1000;
249 uma_zone_set_maxcache(pgcache->zone, cache);
253 SYSINIT(vm_page2, SI_SUB_VM_CONF, SI_ORDER_ANY, vm_page_init_cache_zones, NULL);
255 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
256 #if PAGE_SIZE == 32768
258 CTASSERT(sizeof(u_long) >= 8);
265 * Sets the page size, perhaps based upon the memory
266 * size. Must be called before any use of page-size
267 * dependent functions.
270 vm_set_page_size(void)
272 if (vm_cnt.v_page_size == 0)
273 vm_cnt.v_page_size = PAGE_SIZE;
274 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
275 panic("vm_set_page_size: page size not a power of two");
279 * vm_page_blacklist_next:
281 * Find the next entry in the provided string of blacklist
282 * addresses. Entries are separated by space, comma, or newline.
283 * If an invalid integer is encountered then the rest of the
284 * string is skipped. Updates the list pointer to the next
285 * character, or NULL if the string is exhausted or invalid.
288 vm_page_blacklist_next(char **list, char *end)
293 if (list == NULL || *list == NULL)
301 * If there's no end pointer then the buffer is coming from
302 * the kenv and we know it's null-terminated.
305 end = *list + strlen(*list);
307 /* Ensure that strtoq() won't walk off the end */
309 if (*end == '\n' || *end == ' ' || *end == ',')
312 printf("Blacklist not terminated, skipping\n");
318 for (pos = *list; *pos != '\0'; pos = cp) {
319 bad = strtoq(pos, &cp, 0);
320 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
329 if (*cp == '\0' || ++cp >= end)
333 return (trunc_page(bad));
335 printf("Garbage in RAM blacklist, skipping\n");
341 vm_page_blacklist_add(vm_paddr_t pa, bool verbose)
343 struct vm_domain *vmd;
347 m = vm_phys_paddr_to_vm_page(pa);
349 return (true); /* page does not exist, no failure */
351 vmd = vm_pagequeue_domain(m);
352 vm_domain_free_lock(vmd);
353 ret = vm_phys_unfree_page(m);
354 vm_domain_free_unlock(vmd);
356 vm_domain_freecnt_inc(vmd, -1);
357 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
359 printf("Skipping page with pa 0x%jx\n", (uintmax_t)pa);
365 * vm_page_blacklist_check:
367 * Iterate through the provided string of blacklist addresses, pulling
368 * each entry out of the physical allocator free list and putting it
369 * onto a list for reporting via the vm.page_blacklist sysctl.
372 vm_page_blacklist_check(char *list, char *end)
378 while (next != NULL) {
379 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
381 vm_page_blacklist_add(pa, bootverbose);
386 * vm_page_blacklist_load:
388 * Search for a special module named "ram_blacklist". It'll be a
389 * plain text file provided by the user via the loader directive
393 vm_page_blacklist_load(char **list, char **end)
402 mod = preload_search_by_type("ram_blacklist");
404 ptr = preload_fetch_addr(mod);
405 len = preload_fetch_size(mod);
416 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
423 error = sysctl_wire_old_buffer(req, 0);
426 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
427 TAILQ_FOREACH(m, &blacklist_head, listq) {
428 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
429 (uintmax_t)m->phys_addr);
432 error = sbuf_finish(&sbuf);
438 * Initialize a dummy page for use in scans of the specified paging queue.
439 * In principle, this function only needs to set the flag PG_MARKER.
440 * Nonetheless, it write busies the page as a safety precaution.
443 vm_page_init_marker(vm_page_t marker, int queue, uint16_t aflags)
446 bzero(marker, sizeof(*marker));
447 marker->flags = PG_MARKER;
448 marker->a.flags = aflags;
449 marker->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
450 marker->a.queue = queue;
454 vm_page_domain_init(int domain)
456 struct vm_domain *vmd;
457 struct vm_pagequeue *pq;
460 vmd = VM_DOMAIN(domain);
461 bzero(vmd, sizeof(*vmd));
462 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
463 "vm inactive pagequeue";
464 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
465 "vm active pagequeue";
466 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
467 "vm laundry pagequeue";
468 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_name) =
469 "vm unswappable pagequeue";
470 vmd->vmd_domain = domain;
471 vmd->vmd_page_count = 0;
472 vmd->vmd_free_count = 0;
474 vmd->vmd_oom = FALSE;
475 for (i = 0; i < PQ_COUNT; i++) {
476 pq = &vmd->vmd_pagequeues[i];
477 TAILQ_INIT(&pq->pq_pl);
478 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
479 MTX_DEF | MTX_DUPOK);
481 vm_page_init_marker(&vmd->vmd_markers[i], i, 0);
483 mtx_init(&vmd->vmd_free_mtx, "vm page free queue", NULL, MTX_DEF);
484 mtx_init(&vmd->vmd_pageout_mtx, "vm pageout lock", NULL, MTX_DEF);
485 snprintf(vmd->vmd_name, sizeof(vmd->vmd_name), "%d", domain);
488 * inacthead is used to provide FIFO ordering for LRU-bypassing
491 vm_page_init_marker(&vmd->vmd_inacthead, PQ_INACTIVE, PGA_ENQUEUED);
492 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_INACTIVE].pq_pl,
493 &vmd->vmd_inacthead, plinks.q);
496 * The clock pages are used to implement active queue scanning without
497 * requeues. Scans start at clock[0], which is advanced after the scan
498 * ends. When the two clock hands meet, they are reset and scanning
499 * resumes from the head of the queue.
501 vm_page_init_marker(&vmd->vmd_clock[0], PQ_ACTIVE, PGA_ENQUEUED);
502 vm_page_init_marker(&vmd->vmd_clock[1], PQ_ACTIVE, PGA_ENQUEUED);
503 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
504 &vmd->vmd_clock[0], plinks.q);
505 TAILQ_INSERT_TAIL(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
506 &vmd->vmd_clock[1], plinks.q);
510 * Initialize a physical page in preparation for adding it to the free
514 vm_page_init_page(vm_page_t m, vm_paddr_t pa, int segind)
519 m->busy_lock = VPB_UNBUSIED;
520 m->flags = m->a.flags = 0;
522 m->a.queue = PQ_NONE;
525 m->order = VM_NFREEORDER;
526 m->pool = VM_FREEPOOL_DEFAULT;
527 m->valid = m->dirty = 0;
531 #ifndef PMAP_HAS_PAGE_ARRAY
533 vm_page_array_alloc(vm_offset_t *vaddr, vm_paddr_t end, vm_paddr_t page_range)
538 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
539 * However, because this page is allocated from KVM, out-of-bounds
540 * accesses using the direct map will not be trapped.
545 * Allocate physical memory for the page structures, and map it.
547 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
548 vm_page_array = (vm_page_t)pmap_map(vaddr, new_end, end,
549 VM_PROT_READ | VM_PROT_WRITE);
550 vm_page_array_size = page_range;
559 * Initializes the resident memory module. Allocates physical memory for
560 * bootstrapping UMA and some data structures that are used to manage
561 * physical pages. Initializes these structures, and populates the free
565 vm_page_startup(vm_offset_t vaddr)
567 struct vm_phys_seg *seg;
569 char *list, *listend;
571 vm_paddr_t end, high_avail, low_avail, new_end, size;
572 vm_paddr_t page_range __unused;
573 vm_paddr_t last_pa, pa;
575 int biggestone, i, segind;
579 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
583 vaddr = round_page(vaddr);
585 vm_phys_early_startup();
586 biggestone = vm_phys_avail_largest();
587 end = phys_avail[biggestone+1];
590 * Initialize the page and queue locks.
592 mtx_init(&vm_domainset_lock, "vm domainset lock", NULL, MTX_DEF);
593 for (i = 0; i < PA_LOCK_COUNT; i++)
594 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
595 for (i = 0; i < vm_ndomains; i++)
596 vm_page_domain_init(i);
599 * Allocate memory for use when boot strapping the kernel memory
600 * allocator. Tell UMA how many zones we are going to create
601 * before going fully functional. UMA will add its zones.
603 * VM startup zones: vmem, vmem_btag, VM OBJECT, RADIX NODE, MAP,
604 * KMAP ENTRY, MAP ENTRY, VMSPACE.
606 boot_pages = uma_startup_count(8);
608 #ifndef UMA_MD_SMALL_ALLOC
609 /* vmem_startup() calls uma_prealloc(). */
610 boot_pages += vmem_startup_count();
611 /* vm_map_startup() calls uma_prealloc(). */
612 boot_pages += howmany(MAX_KMAP,
613 slab_ipers(sizeof(struct vm_map), UMA_ALIGN_PTR));
616 * Before we are fully boot strapped we need to account for the
617 * following allocations:
619 * "KMAP ENTRY" from kmem_init()
620 * "vmem btag" from vmem_startup()
621 * "vmem" from vmem_create()
622 * "KMAP" from vm_map_startup()
624 * Each needs at least one page per-domain.
626 boot_pages += 4 * vm_ndomains;
629 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
630 * manually fetch the value.
632 TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
633 new_end = end - (boot_pages * UMA_SLAB_SIZE);
634 new_end = trunc_page(new_end);
635 mapped = pmap_map(&vaddr, new_end, end,
636 VM_PROT_READ | VM_PROT_WRITE);
637 bzero((void *)mapped, end - new_end);
638 uma_startup((void *)mapped, boot_pages);
641 witness_size = round_page(witness_startup_count());
642 new_end -= witness_size;
643 mapped = pmap_map(&vaddr, new_end, new_end + witness_size,
644 VM_PROT_READ | VM_PROT_WRITE);
645 bzero((void *)mapped, witness_size);
646 witness_startup((void *)mapped);
649 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
650 defined(__i386__) || defined(__mips__) || defined(__riscv) || \
651 defined(__powerpc64__)
653 * Allocate a bitmap to indicate that a random physical page
654 * needs to be included in a minidump.
656 * The amd64 port needs this to indicate which direct map pages
657 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
659 * However, i386 still needs this workspace internally within the
660 * minidump code. In theory, they are not needed on i386, but are
661 * included should the sf_buf code decide to use them.
664 for (i = 0; dump_avail[i + 1] != 0; i += 2)
665 if (dump_avail[i + 1] > last_pa)
666 last_pa = dump_avail[i + 1];
667 page_range = last_pa / PAGE_SIZE;
668 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
669 new_end -= vm_page_dump_size;
670 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
671 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
672 bzero((void *)vm_page_dump, vm_page_dump_size);
676 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
677 defined(__riscv) || defined(__powerpc64__)
679 * Include the UMA bootstrap pages, witness pages and vm_page_dump
680 * in a crash dump. When pmap_map() uses the direct map, they are
681 * not automatically included.
683 for (pa = new_end; pa < end; pa += PAGE_SIZE)
686 phys_avail[biggestone + 1] = new_end;
689 * Request that the physical pages underlying the message buffer be
690 * included in a crash dump. Since the message buffer is accessed
691 * through the direct map, they are not automatically included.
693 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
694 last_pa = pa + round_page(msgbufsize);
695 while (pa < last_pa) {
701 * Compute the number of pages of memory that will be available for
702 * use, taking into account the overhead of a page structure per page.
703 * In other words, solve
704 * "available physical memory" - round_page(page_range *
705 * sizeof(struct vm_page)) = page_range * PAGE_SIZE
708 low_avail = phys_avail[0];
709 high_avail = phys_avail[1];
710 for (i = 0; i < vm_phys_nsegs; i++) {
711 if (vm_phys_segs[i].start < low_avail)
712 low_avail = vm_phys_segs[i].start;
713 if (vm_phys_segs[i].end > high_avail)
714 high_avail = vm_phys_segs[i].end;
716 /* Skip the first chunk. It is already accounted for. */
717 for (i = 2; phys_avail[i + 1] != 0; i += 2) {
718 if (phys_avail[i] < low_avail)
719 low_avail = phys_avail[i];
720 if (phys_avail[i + 1] > high_avail)
721 high_avail = phys_avail[i + 1];
723 first_page = low_avail / PAGE_SIZE;
724 #ifdef VM_PHYSSEG_SPARSE
726 for (i = 0; i < vm_phys_nsegs; i++)
727 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
728 for (i = 0; phys_avail[i + 1] != 0; i += 2)
729 size += phys_avail[i + 1] - phys_avail[i];
730 #elif defined(VM_PHYSSEG_DENSE)
731 size = high_avail - low_avail;
733 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
736 #ifdef PMAP_HAS_PAGE_ARRAY
737 pmap_page_array_startup(size / PAGE_SIZE);
738 biggestone = vm_phys_avail_largest();
739 end = new_end = phys_avail[biggestone + 1];
741 #ifdef VM_PHYSSEG_DENSE
743 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
744 * the overhead of a page structure per page only if vm_page_array is
745 * allocated from the last physical memory chunk. Otherwise, we must
746 * allocate page structures representing the physical memory
747 * underlying vm_page_array, even though they will not be used.
749 if (new_end != high_avail)
750 page_range = size / PAGE_SIZE;
754 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
757 * If the partial bytes remaining are large enough for
758 * a page (PAGE_SIZE) without a corresponding
759 * 'struct vm_page', then new_end will contain an
760 * extra page after subtracting the length of the VM
761 * page array. Compensate by subtracting an extra
764 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
765 if (new_end == high_avail)
766 high_avail -= PAGE_SIZE;
767 new_end -= PAGE_SIZE;
771 new_end = vm_page_array_alloc(&vaddr, end, page_range);
774 #if VM_NRESERVLEVEL > 0
776 * Allocate physical memory for the reservation management system's
777 * data structures, and map it.
779 new_end = vm_reserv_startup(&vaddr, new_end);
781 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
782 defined(__riscv) || defined(__powerpc64__)
784 * Include vm_page_array and vm_reserv_array in a crash dump.
786 for (pa = new_end; pa < end; pa += PAGE_SIZE)
789 phys_avail[biggestone + 1] = new_end;
792 * Add physical memory segments corresponding to the available
795 for (i = 0; phys_avail[i + 1] != 0; i += 2)
796 if (vm_phys_avail_size(i) != 0)
797 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
800 * Initialize the physical memory allocator.
805 * Initialize the page structures and add every available page to the
806 * physical memory allocator's free lists.
808 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
809 for (ii = 0; ii < vm_page_array_size; ii++) {
810 m = &vm_page_array[ii];
811 vm_page_init_page(m, (first_page + ii) << PAGE_SHIFT, 0);
812 m->flags = PG_FICTITIOUS;
815 vm_cnt.v_page_count = 0;
816 for (segind = 0; segind < vm_phys_nsegs; segind++) {
817 seg = &vm_phys_segs[segind];
818 for (m = seg->first_page, pa = seg->start; pa < seg->end;
819 m++, pa += PAGE_SIZE)
820 vm_page_init_page(m, pa, segind);
823 * Add the segment to the free lists only if it is covered by
824 * one of the ranges in phys_avail. Because we've added the
825 * ranges to the vm_phys_segs array, we can assume that each
826 * segment is either entirely contained in one of the ranges,
827 * or doesn't overlap any of them.
829 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
830 struct vm_domain *vmd;
832 if (seg->start < phys_avail[i] ||
833 seg->end > phys_avail[i + 1])
837 pagecount = (u_long)atop(seg->end - seg->start);
839 vmd = VM_DOMAIN(seg->domain);
840 vm_domain_free_lock(vmd);
841 vm_phys_enqueue_contig(m, pagecount);
842 vm_domain_free_unlock(vmd);
843 vm_domain_freecnt_inc(vmd, pagecount);
844 vm_cnt.v_page_count += (u_int)pagecount;
846 vmd = VM_DOMAIN(seg->domain);
847 vmd->vmd_page_count += (u_int)pagecount;
848 vmd->vmd_segs |= 1UL << m->segind;
854 * Remove blacklisted pages from the physical memory allocator.
856 TAILQ_INIT(&blacklist_head);
857 vm_page_blacklist_load(&list, &listend);
858 vm_page_blacklist_check(list, listend);
860 list = kern_getenv("vm.blacklist");
861 vm_page_blacklist_check(list, NULL);
864 #if VM_NRESERVLEVEL > 0
866 * Initialize the reservation management system.
875 vm_page_reference(vm_page_t m)
878 vm_page_aflag_set(m, PGA_REFERENCED);
882 vm_page_acquire_flags(vm_page_t m, int allocflags)
886 if ((allocflags & (VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY)) != 0)
887 locked = vm_page_trysbusy(m);
889 locked = vm_page_tryxbusy(m);
890 if (locked && (allocflags & VM_ALLOC_WIRED) != 0)
896 * vm_page_busy_sleep_flags
898 * Sleep for busy according to VM_ALLOC_ parameters.
901 vm_page_busy_sleep_flags(vm_object_t object, vm_page_t m, const char *wmesg,
905 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
908 * Reference the page before unlocking and
909 * sleeping so that the page daemon is less
910 * likely to reclaim it.
912 if ((allocflags & VM_ALLOC_NOCREAT) == 0)
913 vm_page_aflag_set(m, PGA_REFERENCED);
914 if (_vm_page_busy_sleep(object, m, wmesg, (allocflags &
915 VM_ALLOC_IGN_SBUSY) != 0, true))
916 VM_OBJECT_WLOCK(object);
917 if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
923 * vm_page_busy_acquire:
925 * Acquire the busy lock as described by VM_ALLOC_* flags. Will loop
926 * and drop the object lock if necessary.
929 vm_page_busy_acquire(vm_page_t m, int allocflags)
935 * The page-specific object must be cached because page
936 * identity can change during the sleep, causing the
937 * re-lock of a different object.
938 * It is assumed that a reference to the object is already
939 * held by the callers.
943 if (vm_page_acquire_flags(m, allocflags))
945 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
948 locked = VM_OBJECT_WOWNED(obj);
951 MPASS(locked || vm_page_wired(m));
952 if (_vm_page_busy_sleep(obj, m, "vmpba",
953 (allocflags & VM_ALLOC_SBUSY) != 0, locked))
954 VM_OBJECT_WLOCK(obj);
955 if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
957 KASSERT(m->object == obj || m->object == NULL,
958 ("vm_page_busy_acquire: page %p does not belong to %p",
964 * vm_page_busy_downgrade:
966 * Downgrade an exclusive busy page into a single shared busy page.
969 vm_page_busy_downgrade(vm_page_t m)
973 vm_page_assert_xbusied(m);
977 if (atomic_fcmpset_rel_int(&m->busy_lock,
978 &x, VPB_SHARERS_WORD(1)))
981 if ((x & VPB_BIT_WAITERS) != 0)
987 * vm_page_busy_tryupgrade:
989 * Attempt to upgrade a single shared busy into an exclusive busy.
992 vm_page_busy_tryupgrade(vm_page_t m)
996 vm_page_assert_sbusied(m);
999 ce = VPB_CURTHREAD_EXCLUSIVE;
1001 if (VPB_SHARERS(x) > 1)
1003 KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
1004 ("vm_page_busy_tryupgrade: invalid lock state"));
1005 if (!atomic_fcmpset_acq_int(&m->busy_lock, &x,
1006 ce | (x & VPB_BIT_WAITERS)))
1015 * Return a positive value if the page is shared busied, 0 otherwise.
1018 vm_page_sbusied(vm_page_t m)
1023 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
1029 * Shared unbusy a page.
1032 vm_page_sunbusy(vm_page_t m)
1036 vm_page_assert_sbusied(m);
1040 if (VPB_SHARERS(x) > 1) {
1041 if (atomic_fcmpset_int(&m->busy_lock, &x,
1042 x - VPB_ONE_SHARER))
1046 KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
1047 ("vm_page_sunbusy: invalid lock state"));
1048 if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
1050 if ((x & VPB_BIT_WAITERS) == 0)
1058 * vm_page_busy_sleep:
1060 * Sleep if the page is busy, using the page pointer as wchan.
1061 * This is used to implement the hard-path of busying mechanism.
1063 * If nonshared is true, sleep only if the page is xbusy.
1065 * The object lock must be held on entry and will be released on exit.
1068 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
1073 VM_OBJECT_ASSERT_LOCKED(obj);
1074 vm_page_lock_assert(m, MA_NOTOWNED);
1076 if (!_vm_page_busy_sleep(obj, m, wmesg, nonshared, true))
1077 VM_OBJECT_DROP(obj);
1081 * _vm_page_busy_sleep:
1083 * Internal busy sleep function.
1086 _vm_page_busy_sleep(vm_object_t obj, vm_page_t m, const char *wmesg,
1087 bool nonshared, bool locked)
1092 * If the object is busy we must wait for that to drain to zero
1093 * before trying the page again.
1095 if (obj != NULL && vm_object_busied(obj)) {
1097 VM_OBJECT_DROP(obj);
1098 vm_object_busy_wait(obj, wmesg);
1103 if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
1104 ((x & VPB_BIT_WAITERS) == 0 &&
1105 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
1110 VM_OBJECT_DROP(obj);
1112 sleepq_add(m, NULL, wmesg, 0, 0);
1113 sleepq_wait(m, PVM);
1121 * Try to shared busy a page.
1122 * If the operation succeeds 1 is returned otherwise 0.
1123 * The operation never sleeps.
1126 vm_page_trysbusy(vm_page_t m)
1134 if ((x & VPB_BIT_SHARED) == 0)
1137 * Reduce the window for transient busies that will trigger
1138 * false negatives in vm_page_ps_test().
1140 if (obj != NULL && vm_object_busied(obj))
1142 if (atomic_fcmpset_acq_int(&m->busy_lock, &x,
1143 x + VPB_ONE_SHARER))
1147 /* Refetch the object now that we're guaranteed that it is stable. */
1149 if (obj != NULL && vm_object_busied(obj)) {
1159 * Try to exclusive busy a page.
1160 * If the operation succeeds 1 is returned otherwise 0.
1161 * The operation never sleeps.
1164 vm_page_tryxbusy(vm_page_t m)
1168 if (atomic_cmpset_acq_int(&(m)->busy_lock, VPB_UNBUSIED,
1169 VPB_CURTHREAD_EXCLUSIVE) == 0)
1173 if (obj != NULL && vm_object_busied(obj)) {
1181 vm_page_xunbusy_hard_tail(vm_page_t m)
1183 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1184 /* Wake the waiter. */
1189 * vm_page_xunbusy_hard:
1191 * Called when unbusy has failed because there is a waiter.
1194 vm_page_xunbusy_hard(vm_page_t m)
1196 vm_page_assert_xbusied(m);
1197 vm_page_xunbusy_hard_tail(m);
1201 vm_page_xunbusy_hard_unchecked(vm_page_t m)
1203 vm_page_assert_xbusied_unchecked(m);
1204 vm_page_xunbusy_hard_tail(m);
1208 * Avoid releasing and reacquiring the same page lock.
1211 vm_page_change_lock(vm_page_t m, struct mtx **mtx)
1215 mtx1 = vm_page_lockptr(m);
1225 * vm_page_unhold_pages:
1227 * Unhold each of the pages that is referenced by the given array.
1230 vm_page_unhold_pages(vm_page_t *ma, int count)
1233 for (; count != 0; count--) {
1234 vm_page_unwire(*ma, PQ_ACTIVE);
1240 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1244 #ifdef VM_PHYSSEG_SPARSE
1245 m = vm_phys_paddr_to_vm_page(pa);
1247 m = vm_phys_fictitious_to_vm_page(pa);
1249 #elif defined(VM_PHYSSEG_DENSE)
1253 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1254 m = &vm_page_array[pi - first_page];
1257 return (vm_phys_fictitious_to_vm_page(pa));
1259 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1266 * Create a fictitious page with the specified physical address and
1267 * memory attribute. The memory attribute is the only the machine-
1268 * dependent aspect of a fictitious page that must be initialized.
1271 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1275 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1276 vm_page_initfake(m, paddr, memattr);
1281 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1284 if ((m->flags & PG_FICTITIOUS) != 0) {
1286 * The page's memattr might have changed since the
1287 * previous initialization. Update the pmap to the
1292 m->phys_addr = paddr;
1293 m->a.queue = PQ_NONE;
1294 /* Fictitious pages don't use "segind". */
1295 m->flags = PG_FICTITIOUS;
1296 /* Fictitious pages don't use "order" or "pool". */
1297 m->oflags = VPO_UNMANAGED;
1298 m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
1299 /* Fictitious pages are unevictable. */
1303 pmap_page_set_memattr(m, memattr);
1309 * Release a fictitious page.
1312 vm_page_putfake(vm_page_t m)
1315 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1316 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1317 ("vm_page_putfake: bad page %p", m));
1319 uma_zfree(fakepg_zone, m);
1323 * vm_page_updatefake:
1325 * Update the given fictitious page to the specified physical address and
1329 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1332 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1333 ("vm_page_updatefake: bad page %p", m));
1334 m->phys_addr = paddr;
1335 pmap_page_set_memattr(m, memattr);
1344 vm_page_free(vm_page_t m)
1347 m->flags &= ~PG_ZERO;
1348 vm_page_free_toq(m);
1352 * vm_page_free_zero:
1354 * Free a page to the zerod-pages queue
1357 vm_page_free_zero(vm_page_t m)
1360 m->flags |= PG_ZERO;
1361 vm_page_free_toq(m);
1365 * Unbusy and handle the page queueing for a page from a getpages request that
1366 * was optionally read ahead or behind.
1369 vm_page_readahead_finish(vm_page_t m)
1372 /* We shouldn't put invalid pages on queues. */
1373 KASSERT(!vm_page_none_valid(m), ("%s: %p is invalid", __func__, m));
1376 * Since the page is not the actually needed one, whether it should
1377 * be activated or deactivated is not obvious. Empirical results
1378 * have shown that deactivating the page is usually the best choice,
1379 * unless the page is wanted by another thread.
1381 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1382 vm_page_activate(m);
1384 vm_page_deactivate(m);
1385 vm_page_xunbusy_unchecked(m);
1389 * vm_page_sleep_if_busy:
1391 * Sleep and release the object lock if the page is busied.
1392 * Returns TRUE if the thread slept.
1394 * The given page must be unlocked and object containing it must
1398 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1402 vm_page_lock_assert(m, MA_NOTOWNED);
1403 VM_OBJECT_ASSERT_WLOCKED(m->object);
1406 * The page-specific object must be cached because page
1407 * identity can change during the sleep, causing the
1408 * re-lock of a different object.
1409 * It is assumed that a reference to the object is already
1410 * held by the callers.
1413 if (vm_page_busied(m) || (obj != NULL && obj->busy)) {
1414 vm_page_busy_sleep(m, msg, false);
1415 VM_OBJECT_WLOCK(obj);
1422 * vm_page_sleep_if_xbusy:
1424 * Sleep and release the object lock if the page is xbusied.
1425 * Returns TRUE if the thread slept.
1427 * The given page must be unlocked and object containing it must
1431 vm_page_sleep_if_xbusy(vm_page_t m, const char *msg)
1435 vm_page_lock_assert(m, MA_NOTOWNED);
1436 VM_OBJECT_ASSERT_WLOCKED(m->object);
1439 * The page-specific object must be cached because page
1440 * identity can change during the sleep, causing the
1441 * re-lock of a different object.
1442 * It is assumed that a reference to the object is already
1443 * held by the callers.
1446 if (vm_page_xbusied(m) || (obj != NULL && obj->busy)) {
1447 vm_page_busy_sleep(m, msg, true);
1448 VM_OBJECT_WLOCK(obj);
1455 * vm_page_dirty_KBI: [ internal use only ]
1457 * Set all bits in the page's dirty field.
1459 * The object containing the specified page must be locked if the
1460 * call is made from the machine-independent layer.
1462 * See vm_page_clear_dirty_mask().
1464 * This function should only be called by vm_page_dirty().
1467 vm_page_dirty_KBI(vm_page_t m)
1470 /* Refer to this operation by its public name. */
1471 KASSERT(vm_page_all_valid(m), ("vm_page_dirty: page is invalid!"));
1472 m->dirty = VM_PAGE_BITS_ALL;
1476 * vm_page_insert: [ internal use only ]
1478 * Inserts the given mem entry into the object and object list.
1480 * The object must be locked.
1483 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1487 VM_OBJECT_ASSERT_WLOCKED(object);
1488 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1489 return (vm_page_insert_after(m, object, pindex, mpred));
1493 * vm_page_insert_after:
1495 * Inserts the page "m" into the specified object at offset "pindex".
1497 * The page "mpred" must immediately precede the offset "pindex" within
1498 * the specified object.
1500 * The object must be locked.
1503 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1508 VM_OBJECT_ASSERT_WLOCKED(object);
1509 KASSERT(m->object == NULL,
1510 ("vm_page_insert_after: page already inserted"));
1511 if (mpred != NULL) {
1512 KASSERT(mpred->object == object,
1513 ("vm_page_insert_after: object doesn't contain mpred"));
1514 KASSERT(mpred->pindex < pindex,
1515 ("vm_page_insert_after: mpred doesn't precede pindex"));
1516 msucc = TAILQ_NEXT(mpred, listq);
1518 msucc = TAILQ_FIRST(&object->memq);
1520 KASSERT(msucc->pindex > pindex,
1521 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1524 * Record the object/offset pair in this page.
1528 m->ref_count |= VPRC_OBJREF;
1531 * Now link into the object's ordered list of backed pages.
1533 if (vm_radix_insert(&object->rtree, m)) {
1536 m->ref_count &= ~VPRC_OBJREF;
1539 vm_page_insert_radixdone(m, object, mpred);
1544 * vm_page_insert_radixdone:
1546 * Complete page "m" insertion into the specified object after the
1547 * radix trie hooking.
1549 * The page "mpred" must precede the offset "m->pindex" within the
1552 * The object must be locked.
1555 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1558 VM_OBJECT_ASSERT_WLOCKED(object);
1559 KASSERT(object != NULL && m->object == object,
1560 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1561 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1562 ("vm_page_insert_radixdone: page %p is missing object ref", m));
1563 if (mpred != NULL) {
1564 KASSERT(mpred->object == object,
1565 ("vm_page_insert_radixdone: object doesn't contain mpred"));
1566 KASSERT(mpred->pindex < m->pindex,
1567 ("vm_page_insert_radixdone: mpred doesn't precede pindex"));
1571 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1573 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1576 * Show that the object has one more resident page.
1578 object->resident_page_count++;
1581 * Hold the vnode until the last page is released.
1583 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1584 vhold(object->handle);
1587 * Since we are inserting a new and possibly dirty page,
1588 * update the object's generation count.
1590 if (pmap_page_is_write_mapped(m))
1591 vm_object_set_writeable_dirty(object);
1595 * Do the work to remove a page from its object. The caller is responsible for
1596 * updating the page's fields to reflect this removal.
1599 vm_page_object_remove(vm_page_t m)
1604 vm_page_assert_xbusied(m);
1606 VM_OBJECT_ASSERT_WLOCKED(object);
1607 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1608 ("page %p is missing its object ref", m));
1610 /* Deferred free of swap space. */
1611 if ((m->a.flags & PGA_SWAP_FREE) != 0)
1612 vm_pager_page_unswapped(m);
1614 mrem = vm_radix_remove(&object->rtree, m->pindex);
1615 KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1618 * Now remove from the object's list of backed pages.
1620 TAILQ_REMOVE(&object->memq, m, listq);
1623 * And show that the object has one fewer resident page.
1625 object->resident_page_count--;
1628 * The vnode may now be recycled.
1630 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1631 vdrop(object->handle);
1637 * Removes the specified page from its containing object, but does not
1638 * invalidate any backing storage. Returns true if the object's reference
1639 * was the last reference to the page, and false otherwise.
1641 * The object must be locked and the page must be exclusively busied.
1642 * The exclusive busy will be released on return. If this is not the
1643 * final ref and the caller does not hold a wire reference it may not
1644 * continue to access the page.
1647 vm_page_remove(vm_page_t m)
1651 dropped = vm_page_remove_xbusy(m);
1658 * vm_page_remove_xbusy
1660 * Removes the page but leaves the xbusy held. Returns true if this
1661 * removed the final ref and false otherwise.
1664 vm_page_remove_xbusy(vm_page_t m)
1667 vm_page_object_remove(m);
1669 return (vm_page_drop(m, VPRC_OBJREF) == VPRC_OBJREF);
1675 * Returns the page associated with the object/offset
1676 * pair specified; if none is found, NULL is returned.
1678 * The object must be locked.
1681 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1684 VM_OBJECT_ASSERT_LOCKED(object);
1685 return (vm_radix_lookup(&object->rtree, pindex));
1689 * vm_page_find_least:
1691 * Returns the page associated with the object with least pindex
1692 * greater than or equal to the parameter pindex, or NULL.
1694 * The object must be locked.
1697 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1701 VM_OBJECT_ASSERT_LOCKED(object);
1702 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1703 m = vm_radix_lookup_ge(&object->rtree, pindex);
1708 * Returns the given page's successor (by pindex) within the object if it is
1709 * resident; if none is found, NULL is returned.
1711 * The object must be locked.
1714 vm_page_next(vm_page_t m)
1718 VM_OBJECT_ASSERT_LOCKED(m->object);
1719 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1720 MPASS(next->object == m->object);
1721 if (next->pindex != m->pindex + 1)
1728 * Returns the given page's predecessor (by pindex) within the object if it is
1729 * resident; if none is found, NULL is returned.
1731 * The object must be locked.
1734 vm_page_prev(vm_page_t m)
1738 VM_OBJECT_ASSERT_LOCKED(m->object);
1739 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1740 MPASS(prev->object == m->object);
1741 if (prev->pindex != m->pindex - 1)
1748 * Uses the page mnew as a replacement for an existing page at index
1749 * pindex which must be already present in the object.
1751 * Both pages must be exclusively busied on enter. The old page is
1754 * A return value of true means mold is now free. If this is not the
1755 * final ref and the caller does not hold a wire reference it may not
1756 * continue to access the page.
1759 vm_page_replace_hold(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1765 VM_OBJECT_ASSERT_WLOCKED(object);
1766 vm_page_assert_xbusied(mold);
1767 KASSERT(mnew->object == NULL && (mnew->ref_count & VPRC_OBJREF) == 0,
1768 ("vm_page_replace: page %p already in object", mnew));
1771 * This function mostly follows vm_page_insert() and
1772 * vm_page_remove() without the radix, object count and vnode
1773 * dance. Double check such functions for more comments.
1776 mnew->object = object;
1777 mnew->pindex = pindex;
1778 atomic_set_int(&mnew->ref_count, VPRC_OBJREF);
1779 mret = vm_radix_replace(&object->rtree, mnew);
1780 KASSERT(mret == mold,
1781 ("invalid page replacement, mold=%p, mret=%p", mold, mret));
1782 KASSERT((mold->oflags & VPO_UNMANAGED) ==
1783 (mnew->oflags & VPO_UNMANAGED),
1784 ("vm_page_replace: mismatched VPO_UNMANAGED"));
1786 /* Keep the resident page list in sorted order. */
1787 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1788 TAILQ_REMOVE(&object->memq, mold, listq);
1789 mold->object = NULL;
1792 * The object's resident_page_count does not change because we have
1793 * swapped one page for another, but the generation count should
1794 * change if the page is dirty.
1796 if (pmap_page_is_write_mapped(mnew))
1797 vm_object_set_writeable_dirty(object);
1798 dropped = vm_page_drop(mold, VPRC_OBJREF) == VPRC_OBJREF;
1799 vm_page_xunbusy(mold);
1805 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1809 vm_page_assert_xbusied(mnew);
1811 if (vm_page_replace_hold(mnew, object, pindex, mold))
1818 * Move the given memory entry from its
1819 * current object to the specified target object/offset.
1821 * Note: swap associated with the page must be invalidated by the move. We
1822 * have to do this for several reasons: (1) we aren't freeing the
1823 * page, (2) we are dirtying the page, (3) the VM system is probably
1824 * moving the page from object A to B, and will then later move
1825 * the backing store from A to B and we can't have a conflict.
1827 * Note: we *always* dirty the page. It is necessary both for the
1828 * fact that we moved it, and because we may be invalidating
1831 * The objects must be locked.
1834 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1839 VM_OBJECT_ASSERT_WLOCKED(new_object);
1841 KASSERT(m->ref_count != 0, ("vm_page_rename: page %p has no refs", m));
1842 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1843 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1844 ("vm_page_rename: pindex already renamed"));
1847 * Create a custom version of vm_page_insert() which does not depend
1848 * by m_prev and can cheat on the implementation aspects of the
1852 m->pindex = new_pindex;
1853 if (vm_radix_insert(&new_object->rtree, m)) {
1859 * The operation cannot fail anymore. The removal must happen before
1860 * the listq iterator is tainted.
1863 vm_page_object_remove(m);
1865 /* Return back to the new pindex to complete vm_page_insert(). */
1866 m->pindex = new_pindex;
1867 m->object = new_object;
1869 vm_page_insert_radixdone(m, new_object, mpred);
1877 * Allocate and return a page that is associated with the specified
1878 * object and offset pair. By default, this page is exclusive busied.
1880 * The caller must always specify an allocation class.
1882 * allocation classes:
1883 * VM_ALLOC_NORMAL normal process request
1884 * VM_ALLOC_SYSTEM system *really* needs a page
1885 * VM_ALLOC_INTERRUPT interrupt time request
1887 * optional allocation flags:
1888 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1889 * intends to allocate
1890 * VM_ALLOC_NOBUSY do not exclusive busy the page
1891 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1892 * VM_ALLOC_NOOBJ page is not associated with an object and
1893 * should not be exclusive busy
1894 * VM_ALLOC_SBUSY shared busy the allocated page
1895 * VM_ALLOC_WIRED wire the allocated page
1896 * VM_ALLOC_ZERO prefer a zeroed page
1899 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1902 return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1903 vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1907 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1911 return (vm_page_alloc_domain_after(object, pindex, domain, req,
1912 object != NULL ? vm_radix_lookup_le(&object->rtree, pindex) :
1917 * Allocate a page in the specified object with the given page index. To
1918 * optimize insertion of the page into the object, the caller must also specifiy
1919 * the resident page in the object with largest index smaller than the given
1920 * page index, or NULL if no such page exists.
1923 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1924 int req, vm_page_t mpred)
1926 struct vm_domainset_iter di;
1930 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1932 m = vm_page_alloc_domain_after(object, pindex, domain, req,
1936 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
1942 * Returns true if the number of free pages exceeds the minimum
1943 * for the request class and false otherwise.
1946 _vm_domain_allocate(struct vm_domain *vmd, int req_class, int npages)
1948 u_int limit, old, new;
1950 if (req_class == VM_ALLOC_INTERRUPT)
1952 else if (req_class == VM_ALLOC_SYSTEM)
1953 limit = vmd->vmd_interrupt_free_min;
1955 limit = vmd->vmd_free_reserved;
1958 * Attempt to reserve the pages. Fail if we're below the limit.
1961 old = vmd->vmd_free_count;
1966 } while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
1968 /* Wake the page daemon if we've crossed the threshold. */
1969 if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
1970 pagedaemon_wakeup(vmd->vmd_domain);
1972 /* Only update bitsets on transitions. */
1973 if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
1974 (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
1981 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
1986 * The page daemon is allowed to dig deeper into the free page list.
1988 req_class = req & VM_ALLOC_CLASS_MASK;
1989 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1990 req_class = VM_ALLOC_SYSTEM;
1991 return (_vm_domain_allocate(vmd, req_class, npages));
1995 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
1996 int req, vm_page_t mpred)
1998 struct vm_domain *vmd;
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 ("inconsistent object(%p)/req(%x)", object, req));
2007 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2008 ("Can't sleep and retry object insertion."));
2009 KASSERT(mpred == NULL || mpred->pindex < pindex,
2010 ("mpred %p doesn't precede pindex 0x%jx", mpred,
2011 (uintmax_t)pindex));
2013 VM_OBJECT_ASSERT_WLOCKED(object);
2017 pool = object != NULL ? VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT;
2019 #if VM_NRESERVLEVEL > 0
2021 * Can we allocate the page from a reservation?
2023 if (vm_object_reserv(object) &&
2024 (m = vm_reserv_alloc_page(object, pindex, domain, req, mpred)) !=
2026 domain = vm_phys_domain(m);
2027 vmd = VM_DOMAIN(domain);
2031 vmd = VM_DOMAIN(domain);
2032 if (vmd->vmd_pgcache[pool].zone != NULL) {
2033 m = uma_zalloc(vmd->vmd_pgcache[pool].zone, M_NOWAIT);
2035 flags |= PG_PCPU_CACHE;
2039 if (vm_domain_allocate(vmd, req, 1)) {
2041 * If not, allocate it from the free page queues.
2043 vm_domain_free_lock(vmd);
2044 m = vm_phys_alloc_pages(domain, pool, 0);
2045 vm_domain_free_unlock(vmd);
2047 vm_domain_freecnt_inc(vmd, 1);
2048 #if VM_NRESERVLEVEL > 0
2049 if (vm_reserv_reclaim_inactive(domain))
2056 * Not allocatable, give up.
2058 if (vm_domain_alloc_fail(vmd, object, req))
2064 * At this point we had better have found a good page.
2068 vm_page_alloc_check(m);
2071 * Initialize the page. Only the PG_ZERO flag is inherited.
2073 if ((req & VM_ALLOC_ZERO) != 0)
2074 flags |= (m->flags & PG_ZERO);
2075 if ((req & VM_ALLOC_NODUMP) != 0)
2079 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2081 m->busy_lock = VPB_UNBUSIED;
2082 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2083 m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2084 if ((req & VM_ALLOC_SBUSY) != 0)
2085 m->busy_lock = VPB_SHARERS_WORD(1);
2086 if (req & VM_ALLOC_WIRED) {
2092 if (object != NULL) {
2093 if (vm_page_insert_after(m, object, pindex, mpred)) {
2094 if (req & VM_ALLOC_WIRED) {
2098 KASSERT(m->object == NULL, ("page %p has object", m));
2099 m->oflags = VPO_UNMANAGED;
2100 m->busy_lock = VPB_UNBUSIED;
2101 /* Don't change PG_ZERO. */
2102 vm_page_free_toq(m);
2103 if (req & VM_ALLOC_WAITFAIL) {
2104 VM_OBJECT_WUNLOCK(object);
2106 VM_OBJECT_WLOCK(object);
2111 /* Ignore device objects; the pager sets "memattr" for them. */
2112 if (object->memattr != VM_MEMATTR_DEFAULT &&
2113 (object->flags & OBJ_FICTITIOUS) == 0)
2114 pmap_page_set_memattr(m, object->memattr);
2122 * vm_page_alloc_contig:
2124 * Allocate a contiguous set of physical pages of the given size "npages"
2125 * from the free lists. All of the physical pages must be at or above
2126 * the given physical address "low" and below the given physical address
2127 * "high". The given value "alignment" determines the alignment of the
2128 * first physical page in the set. If the given value "boundary" is
2129 * non-zero, then the set of physical pages cannot cross any physical
2130 * address boundary that is a multiple of that value. Both "alignment"
2131 * and "boundary" must be a power of two.
2133 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
2134 * then the memory attribute setting for the physical pages is configured
2135 * to the object's memory attribute setting. Otherwise, the memory
2136 * attribute setting for the physical pages is configured to "memattr",
2137 * overriding the object's memory attribute setting. However, if the
2138 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
2139 * memory attribute setting for the physical pages cannot be configured
2140 * to VM_MEMATTR_DEFAULT.
2142 * The specified object may not contain fictitious pages.
2144 * The caller must always specify an allocation class.
2146 * allocation classes:
2147 * VM_ALLOC_NORMAL normal process request
2148 * VM_ALLOC_SYSTEM system *really* needs a page
2149 * VM_ALLOC_INTERRUPT interrupt time request
2151 * optional allocation flags:
2152 * VM_ALLOC_NOBUSY do not exclusive busy the page
2153 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
2154 * VM_ALLOC_NOOBJ page is not associated with an object and
2155 * should not be exclusive busy
2156 * VM_ALLOC_SBUSY shared busy the allocated page
2157 * VM_ALLOC_WIRED wire the allocated page
2158 * VM_ALLOC_ZERO prefer a zeroed page
2161 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
2162 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2163 vm_paddr_t boundary, vm_memattr_t memattr)
2165 struct vm_domainset_iter di;
2169 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
2171 m = vm_page_alloc_contig_domain(object, pindex, domain, req,
2172 npages, low, high, alignment, boundary, memattr);
2175 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
2181 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
2182 int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2183 vm_paddr_t boundary, vm_memattr_t memattr)
2185 struct vm_domain *vmd;
2186 vm_page_t m, m_ret, mpred;
2187 u_int busy_lock, flags, oflags;
2189 mpred = NULL; /* XXX: pacify gcc */
2190 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
2191 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
2192 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2193 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2194 ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
2196 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2197 ("Can't sleep and retry object insertion."));
2198 if (object != NULL) {
2199 VM_OBJECT_ASSERT_WLOCKED(object);
2200 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2201 ("vm_page_alloc_contig: object %p has fictitious pages",
2204 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2206 if (object != NULL) {
2207 mpred = vm_radix_lookup_le(&object->rtree, pindex);
2208 KASSERT(mpred == NULL || mpred->pindex != pindex,
2209 ("vm_page_alloc_contig: pindex already allocated"));
2213 * Can we allocate the pages without the number of free pages falling
2214 * below the lower bound for the allocation class?
2218 #if VM_NRESERVLEVEL > 0
2220 * Can we allocate the pages from a reservation?
2222 if (vm_object_reserv(object) &&
2223 (m_ret = vm_reserv_alloc_contig(object, pindex, domain, req,
2224 mpred, npages, low, high, alignment, boundary)) != NULL) {
2225 domain = vm_phys_domain(m_ret);
2226 vmd = VM_DOMAIN(domain);
2230 vmd = VM_DOMAIN(domain);
2231 if (vm_domain_allocate(vmd, req, npages)) {
2233 * allocate them from the free page queues.
2235 vm_domain_free_lock(vmd);
2236 m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2237 alignment, boundary);
2238 vm_domain_free_unlock(vmd);
2239 if (m_ret == NULL) {
2240 vm_domain_freecnt_inc(vmd, npages);
2241 #if VM_NRESERVLEVEL > 0
2242 if (vm_reserv_reclaim_contig(domain, npages, low,
2243 high, alignment, boundary))
2248 if (m_ret == NULL) {
2249 if (vm_domain_alloc_fail(vmd, object, req))
2253 #if VM_NRESERVLEVEL > 0
2256 for (m = m_ret; m < &m_ret[npages]; m++) {
2258 vm_page_alloc_check(m);
2262 * Initialize the pages. Only the PG_ZERO flag is inherited.
2265 if ((req & VM_ALLOC_ZERO) != 0)
2267 if ((req & VM_ALLOC_NODUMP) != 0)
2269 oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2271 busy_lock = VPB_UNBUSIED;
2272 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2273 busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2274 if ((req & VM_ALLOC_SBUSY) != 0)
2275 busy_lock = VPB_SHARERS_WORD(1);
2276 if ((req & VM_ALLOC_WIRED) != 0)
2277 vm_wire_add(npages);
2278 if (object != NULL) {
2279 if (object->memattr != VM_MEMATTR_DEFAULT &&
2280 memattr == VM_MEMATTR_DEFAULT)
2281 memattr = object->memattr;
2283 for (m = m_ret; m < &m_ret[npages]; m++) {
2285 m->flags = (m->flags | PG_NODUMP) & flags;
2286 m->busy_lock = busy_lock;
2287 if ((req & VM_ALLOC_WIRED) != 0)
2291 if (object != NULL) {
2292 if (vm_page_insert_after(m, object, pindex, mpred)) {
2293 if ((req & VM_ALLOC_WIRED) != 0)
2294 vm_wire_sub(npages);
2295 KASSERT(m->object == NULL,
2296 ("page %p has object", m));
2298 for (m = m_ret; m < &m_ret[npages]; m++) {
2300 (req & VM_ALLOC_WIRED) != 0)
2302 m->oflags = VPO_UNMANAGED;
2303 m->busy_lock = VPB_UNBUSIED;
2304 /* Don't change PG_ZERO. */
2305 vm_page_free_toq(m);
2307 if (req & VM_ALLOC_WAITFAIL) {
2308 VM_OBJECT_WUNLOCK(object);
2310 VM_OBJECT_WLOCK(object);
2317 if (memattr != VM_MEMATTR_DEFAULT)
2318 pmap_page_set_memattr(m, memattr);
2325 * Check a page that has been freshly dequeued from a freelist.
2328 vm_page_alloc_check(vm_page_t m)
2331 KASSERT(m->object == NULL, ("page %p has object", m));
2332 KASSERT(m->a.queue == PQ_NONE &&
2333 (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
2334 ("page %p has unexpected queue %d, flags %#x",
2335 m, m->a.queue, (m->a.flags & PGA_QUEUE_STATE_MASK)));
2336 KASSERT(m->ref_count == 0, ("page %p has references", m));
2337 KASSERT(!vm_page_busied(m), ("page %p is busy", m));
2338 KASSERT(m->dirty == 0, ("page %p is dirty", m));
2339 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2340 ("page %p has unexpected memattr %d",
2341 m, pmap_page_get_memattr(m)));
2342 KASSERT(m->valid == 0, ("free page %p is valid", m));
2346 * vm_page_alloc_freelist:
2348 * Allocate a physical page from the specified free page list.
2350 * The caller must always specify an allocation class.
2352 * allocation classes:
2353 * VM_ALLOC_NORMAL normal process request
2354 * VM_ALLOC_SYSTEM system *really* needs a page
2355 * VM_ALLOC_INTERRUPT interrupt time request
2357 * optional allocation flags:
2358 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2359 * intends to allocate
2360 * VM_ALLOC_WIRED wire the allocated page
2361 * VM_ALLOC_ZERO prefer a zeroed page
2364 vm_page_alloc_freelist(int freelist, int req)
2366 struct vm_domainset_iter di;
2370 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2372 m = vm_page_alloc_freelist_domain(domain, freelist, req);
2375 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2381 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2383 struct vm_domain *vmd;
2388 vmd = VM_DOMAIN(domain);
2390 if (vm_domain_allocate(vmd, req, 1)) {
2391 vm_domain_free_lock(vmd);
2392 m = vm_phys_alloc_freelist_pages(domain, freelist,
2393 VM_FREEPOOL_DIRECT, 0);
2394 vm_domain_free_unlock(vmd);
2396 vm_domain_freecnt_inc(vmd, 1);
2399 if (vm_domain_alloc_fail(vmd, NULL, req))
2404 vm_page_alloc_check(m);
2407 * Initialize the page. Only the PG_ZERO flag is inherited.
2411 if ((req & VM_ALLOC_ZERO) != 0)
2414 if ((req & VM_ALLOC_WIRED) != 0) {
2418 /* Unmanaged pages don't use "act_count". */
2419 m->oflags = VPO_UNMANAGED;
2424 vm_page_zone_import(void *arg, void **store, int cnt, int domain, int flags)
2426 struct vm_domain *vmd;
2427 struct vm_pgcache *pgcache;
2431 vmd = VM_DOMAIN(pgcache->domain);
2434 * The page daemon should avoid creating extra memory pressure since its
2435 * main purpose is to replenish the store of free pages.
2437 if (vmd->vmd_severeset || curproc == pageproc ||
2438 !_vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2440 domain = vmd->vmd_domain;
2441 vm_domain_free_lock(vmd);
2442 i = vm_phys_alloc_npages(domain, pgcache->pool, cnt,
2443 (vm_page_t *)store);
2444 vm_domain_free_unlock(vmd);
2446 vm_domain_freecnt_inc(vmd, cnt - i);
2452 vm_page_zone_release(void *arg, void **store, int cnt)
2454 struct vm_domain *vmd;
2455 struct vm_pgcache *pgcache;
2460 vmd = VM_DOMAIN(pgcache->domain);
2461 vm_domain_free_lock(vmd);
2462 for (i = 0; i < cnt; i++) {
2463 m = (vm_page_t)store[i];
2464 vm_phys_free_pages(m, 0);
2466 vm_domain_free_unlock(vmd);
2467 vm_domain_freecnt_inc(vmd, cnt);
2470 #define VPSC_ANY 0 /* No restrictions. */
2471 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2472 #define VPSC_NOSUPER 2 /* Skip superpages. */
2475 * vm_page_scan_contig:
2477 * Scan vm_page_array[] between the specified entries "m_start" and
2478 * "m_end" for a run of contiguous physical pages that satisfy the
2479 * specified conditions, and return the lowest page in the run. The
2480 * specified "alignment" determines the alignment of the lowest physical
2481 * page in the run. If the specified "boundary" is non-zero, then the
2482 * run of physical pages cannot span a physical address that is a
2483 * multiple of "boundary".
2485 * "m_end" is never dereferenced, so it need not point to a vm_page
2486 * structure within vm_page_array[].
2488 * "npages" must be greater than zero. "m_start" and "m_end" must not
2489 * span a hole (or discontiguity) in the physical address space. Both
2490 * "alignment" and "boundary" must be a power of two.
2493 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2494 u_long alignment, vm_paddr_t boundary, int options)
2500 #if VM_NRESERVLEVEL > 0
2503 int m_inc, order, run_ext, run_len;
2505 KASSERT(npages > 0, ("npages is 0"));
2506 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2507 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2511 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2512 KASSERT((m->flags & PG_MARKER) == 0,
2513 ("page %p is PG_MARKER", m));
2514 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->ref_count >= 1,
2515 ("fictitious page %p has invalid ref count", m));
2518 * If the current page would be the start of a run, check its
2519 * physical address against the end, alignment, and boundary
2520 * conditions. If it doesn't satisfy these conditions, either
2521 * terminate the scan or advance to the next page that
2522 * satisfies the failed condition.
2525 KASSERT(m_run == NULL, ("m_run != NULL"));
2526 if (m + npages > m_end)
2528 pa = VM_PAGE_TO_PHYS(m);
2529 if ((pa & (alignment - 1)) != 0) {
2530 m_inc = atop(roundup2(pa, alignment) - pa);
2533 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2535 m_inc = atop(roundup2(pa, boundary) - pa);
2539 KASSERT(m_run != NULL, ("m_run == NULL"));
2541 vm_page_change_lock(m, &m_mtx);
2544 if (vm_page_wired(m))
2546 #if VM_NRESERVLEVEL > 0
2547 else if ((level = vm_reserv_level(m)) >= 0 &&
2548 (options & VPSC_NORESERV) != 0) {
2550 /* Advance to the end of the reservation. */
2551 pa = VM_PAGE_TO_PHYS(m);
2552 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2556 else if ((object = m->object) != NULL) {
2558 * The page is considered eligible for relocation if
2559 * and only if it could be laundered or reclaimed by
2562 if (!VM_OBJECT_TRYRLOCK(object)) {
2564 VM_OBJECT_RLOCK(object);
2566 if (m->object != object) {
2568 * The page may have been freed.
2570 VM_OBJECT_RUNLOCK(object);
2574 /* Don't care: PG_NODUMP, PG_ZERO. */
2575 if (object->type != OBJT_DEFAULT &&
2576 object->type != OBJT_SWAP &&
2577 object->type != OBJT_VNODE) {
2579 #if VM_NRESERVLEVEL > 0
2580 } else if ((options & VPSC_NOSUPER) != 0 &&
2581 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2583 /* Advance to the end of the superpage. */
2584 pa = VM_PAGE_TO_PHYS(m);
2585 m_inc = atop(roundup2(pa + 1,
2586 vm_reserv_size(level)) - pa);
2588 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2589 vm_page_queue(m) != PQ_NONE && !vm_page_busied(m) &&
2590 !vm_page_wired(m)) {
2592 * The page is allocated but eligible for
2593 * relocation. Extend the current run by one
2596 KASSERT(pmap_page_get_memattr(m) ==
2598 ("page %p has an unexpected memattr", m));
2599 KASSERT((m->oflags & (VPO_SWAPINPROG |
2600 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2601 ("page %p has unexpected oflags", m));
2602 /* Don't care: PGA_NOSYNC. */
2606 VM_OBJECT_RUNLOCK(object);
2607 #if VM_NRESERVLEVEL > 0
2608 } else if (level >= 0) {
2610 * The page is reserved but not yet allocated. In
2611 * other words, it is still free. Extend the current
2616 } else if ((order = m->order) < VM_NFREEORDER) {
2618 * The page is enqueued in the physical memory
2619 * allocator's free page queues. Moreover, it is the
2620 * first page in a power-of-two-sized run of
2621 * contiguous free pages. Add these pages to the end
2622 * of the current run, and jump ahead.
2624 run_ext = 1 << order;
2628 * Skip the page for one of the following reasons: (1)
2629 * It is enqueued in the physical memory allocator's
2630 * free page queues. However, it is not the first
2631 * page in a run of contiguous free pages. (This case
2632 * rarely occurs because the scan is performed in
2633 * ascending order.) (2) It is not reserved, and it is
2634 * transitioning from free to allocated. (Conversely,
2635 * the transition from allocated to free for managed
2636 * pages is blocked by the page lock.) (3) It is
2637 * allocated but not contained by an object and not
2638 * wired, e.g., allocated by Xen's balloon driver.
2644 * Extend or reset the current run of pages.
2659 if (run_len >= npages)
2665 * vm_page_reclaim_run:
2667 * Try to relocate each of the allocated virtual pages within the
2668 * specified run of physical pages to a new physical address. Free the
2669 * physical pages underlying the relocated virtual pages. A virtual page
2670 * is relocatable if and only if it could be laundered or reclaimed by
2671 * the page daemon. Whenever possible, a virtual page is relocated to a
2672 * physical address above "high".
2674 * Returns 0 if every physical page within the run was already free or
2675 * just freed by a successful relocation. Otherwise, returns a non-zero
2676 * value indicating why the last attempt to relocate a virtual page was
2679 * "req_class" must be an allocation class.
2682 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2685 struct vm_domain *vmd;
2687 struct spglist free;
2690 vm_page_t m, m_end, m_new;
2691 int error, order, req;
2693 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2694 ("req_class is not an allocation class"));
2698 m_end = m_run + npages;
2700 for (; error == 0 && m < m_end; m++) {
2701 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2702 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2705 * Avoid releasing and reacquiring the same page lock.
2707 vm_page_change_lock(m, &m_mtx);
2710 * Racily check for wirings. Races are handled below.
2712 if (vm_page_wired(m))
2714 else if ((object = m->object) != NULL) {
2716 * The page is relocated if and only if it could be
2717 * laundered or reclaimed by the page daemon.
2719 if (!VM_OBJECT_TRYWLOCK(object)) {
2721 VM_OBJECT_WLOCK(object);
2723 if (m->object != object) {
2725 * The page may have been freed.
2727 VM_OBJECT_WUNLOCK(object);
2731 /* Don't care: PG_NODUMP, PG_ZERO. */
2732 if (object->type != OBJT_DEFAULT &&
2733 object->type != OBJT_SWAP &&
2734 object->type != OBJT_VNODE)
2736 else if (object->memattr != VM_MEMATTR_DEFAULT)
2738 else if (vm_page_queue(m) != PQ_NONE &&
2739 vm_page_tryxbusy(m) != 0) {
2740 if (vm_page_wired(m)) {
2745 KASSERT(pmap_page_get_memattr(m) ==
2747 ("page %p has an unexpected memattr", m));
2748 KASSERT(m->oflags == 0,
2749 ("page %p has unexpected oflags", m));
2750 /* Don't care: PGA_NOSYNC. */
2751 if (!vm_page_none_valid(m)) {
2753 * First, try to allocate a new page
2754 * that is above "high". Failing
2755 * that, try to allocate a new page
2756 * that is below "m_run". Allocate
2757 * the new page between the end of
2758 * "m_run" and "high" only as a last
2761 req = req_class | VM_ALLOC_NOOBJ;
2762 if ((m->flags & PG_NODUMP) != 0)
2763 req |= VM_ALLOC_NODUMP;
2764 if (trunc_page(high) !=
2765 ~(vm_paddr_t)PAGE_MASK) {
2766 m_new = vm_page_alloc_contig(
2771 VM_MEMATTR_DEFAULT);
2774 if (m_new == NULL) {
2775 pa = VM_PAGE_TO_PHYS(m_run);
2776 m_new = vm_page_alloc_contig(
2778 0, pa - 1, PAGE_SIZE, 0,
2779 VM_MEMATTR_DEFAULT);
2781 if (m_new == NULL) {
2783 m_new = vm_page_alloc_contig(
2785 pa, high, PAGE_SIZE, 0,
2786 VM_MEMATTR_DEFAULT);
2788 if (m_new == NULL) {
2795 * Unmap the page and check for new
2796 * wirings that may have been acquired
2797 * through a pmap lookup.
2799 if (object->ref_count != 0 &&
2800 !vm_page_try_remove_all(m)) {
2802 vm_page_free(m_new);
2808 * Replace "m" with the new page. For
2809 * vm_page_replace(), "m" must be busy
2810 * and dequeued. Finally, change "m"
2811 * as if vm_page_free() was called.
2813 m_new->a.flags = m->a.flags &
2814 ~PGA_QUEUE_STATE_MASK;
2815 KASSERT(m_new->oflags == VPO_UNMANAGED,
2816 ("page %p is managed", m_new));
2818 pmap_copy_page(m, m_new);
2819 m_new->valid = m->valid;
2820 m_new->dirty = m->dirty;
2821 m->flags &= ~PG_ZERO;
2823 if (vm_page_replace_hold(m_new, object,
2825 vm_page_free_prep(m))
2826 SLIST_INSERT_HEAD(&free, m,
2830 * The new page must be deactivated
2831 * before the object is unlocked.
2833 vm_page_change_lock(m_new, &m_mtx);
2834 vm_page_deactivate(m_new);
2836 m->flags &= ~PG_ZERO;
2838 if (vm_page_free_prep(m))
2839 SLIST_INSERT_HEAD(&free, m,
2841 KASSERT(m->dirty == 0,
2842 ("page %p is dirty", m));
2847 VM_OBJECT_WUNLOCK(object);
2849 MPASS(vm_phys_domain(m) == domain);
2850 vmd = VM_DOMAIN(domain);
2851 vm_domain_free_lock(vmd);
2853 if (order < VM_NFREEORDER) {
2855 * The page is enqueued in the physical memory
2856 * allocator's free page queues. Moreover, it
2857 * is the first page in a power-of-two-sized
2858 * run of contiguous free pages. Jump ahead
2859 * to the last page within that run, and
2860 * continue from there.
2862 m += (1 << order) - 1;
2864 #if VM_NRESERVLEVEL > 0
2865 else if (vm_reserv_is_page_free(m))
2868 vm_domain_free_unlock(vmd);
2869 if (order == VM_NFREEORDER)
2875 if ((m = SLIST_FIRST(&free)) != NULL) {
2878 vmd = VM_DOMAIN(domain);
2880 vm_domain_free_lock(vmd);
2882 MPASS(vm_phys_domain(m) == domain);
2883 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2884 vm_phys_free_pages(m, 0);
2886 } while ((m = SLIST_FIRST(&free)) != NULL);
2887 vm_domain_free_unlock(vmd);
2888 vm_domain_freecnt_inc(vmd, cnt);
2895 CTASSERT(powerof2(NRUNS));
2897 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2899 #define MIN_RECLAIM 8
2902 * vm_page_reclaim_contig:
2904 * Reclaim allocated, contiguous physical memory satisfying the specified
2905 * conditions by relocating the virtual pages using that physical memory.
2906 * Returns true if reclamation is successful and false otherwise. Since
2907 * relocation requires the allocation of physical pages, reclamation may
2908 * fail due to a shortage of free pages. When reclamation fails, callers
2909 * are expected to perform vm_wait() before retrying a failed allocation
2910 * operation, e.g., vm_page_alloc_contig().
2912 * The caller must always specify an allocation class through "req".
2914 * allocation classes:
2915 * VM_ALLOC_NORMAL normal process request
2916 * VM_ALLOC_SYSTEM system *really* needs a page
2917 * VM_ALLOC_INTERRUPT interrupt time request
2919 * The optional allocation flags are ignored.
2921 * "npages" must be greater than zero. Both "alignment" and "boundary"
2922 * must be a power of two.
2925 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
2926 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2928 struct vm_domain *vmd;
2929 vm_paddr_t curr_low;
2930 vm_page_t m_run, m_runs[NRUNS];
2931 u_long count, reclaimed;
2932 int error, i, options, req_class;
2934 KASSERT(npages > 0, ("npages is 0"));
2935 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2936 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2937 req_class = req & VM_ALLOC_CLASS_MASK;
2940 * The page daemon is allowed to dig deeper into the free page list.
2942 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2943 req_class = VM_ALLOC_SYSTEM;
2946 * Return if the number of free pages cannot satisfy the requested
2949 vmd = VM_DOMAIN(domain);
2950 count = vmd->vmd_free_count;
2951 if (count < npages + vmd->vmd_free_reserved || (count < npages +
2952 vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2953 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2957 * Scan up to three times, relaxing the restrictions ("options") on
2958 * the reclamation of reservations and superpages each time.
2960 for (options = VPSC_NORESERV;;) {
2962 * Find the highest runs that satisfy the given constraints
2963 * and restrictions, and record them in "m_runs".
2968 m_run = vm_phys_scan_contig(domain, npages, curr_low,
2969 high, alignment, boundary, options);
2972 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2973 m_runs[RUN_INDEX(count)] = m_run;
2978 * Reclaim the highest runs in LIFO (descending) order until
2979 * the number of reclaimed pages, "reclaimed", is at least
2980 * MIN_RECLAIM. Reset "reclaimed" each time because each
2981 * reclamation is idempotent, and runs will (likely) recur
2982 * from one scan to the next as restrictions are relaxed.
2985 for (i = 0; count > 0 && i < NRUNS; i++) {
2987 m_run = m_runs[RUN_INDEX(count)];
2988 error = vm_page_reclaim_run(req_class, domain, npages,
2991 reclaimed += npages;
2992 if (reclaimed >= MIN_RECLAIM)
2998 * Either relax the restrictions on the next scan or return if
2999 * the last scan had no restrictions.
3001 if (options == VPSC_NORESERV)
3002 options = VPSC_NOSUPER;
3003 else if (options == VPSC_NOSUPER)
3005 else if (options == VPSC_ANY)
3006 return (reclaimed != 0);
3011 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
3012 u_long alignment, vm_paddr_t boundary)
3014 struct vm_domainset_iter di;
3018 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
3020 ret = vm_page_reclaim_contig_domain(domain, req, npages, low,
3021 high, alignment, boundary);
3024 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
3030 * Set the domain in the appropriate page level domainset.
3033 vm_domain_set(struct vm_domain *vmd)
3036 mtx_lock(&vm_domainset_lock);
3037 if (!vmd->vmd_minset && vm_paging_min(vmd)) {
3038 vmd->vmd_minset = 1;
3039 DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
3041 if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
3042 vmd->vmd_severeset = 1;
3043 DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
3045 mtx_unlock(&vm_domainset_lock);
3049 * Clear the domain from the appropriate page level domainset.
3052 vm_domain_clear(struct vm_domain *vmd)
3055 mtx_lock(&vm_domainset_lock);
3056 if (vmd->vmd_minset && !vm_paging_min(vmd)) {
3057 vmd->vmd_minset = 0;
3058 DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
3059 if (vm_min_waiters != 0) {
3061 wakeup(&vm_min_domains);
3064 if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
3065 vmd->vmd_severeset = 0;
3066 DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
3067 if (vm_severe_waiters != 0) {
3068 vm_severe_waiters = 0;
3069 wakeup(&vm_severe_domains);
3074 * If pageout daemon needs pages, then tell it that there are
3077 if (vmd->vmd_pageout_pages_needed &&
3078 vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
3079 wakeup(&vmd->vmd_pageout_pages_needed);
3080 vmd->vmd_pageout_pages_needed = 0;
3083 /* See comments in vm_wait_doms(). */
3084 if (vm_pageproc_waiters) {
3085 vm_pageproc_waiters = 0;
3086 wakeup(&vm_pageproc_waiters);
3088 mtx_unlock(&vm_domainset_lock);
3092 * Wait for free pages to exceed the min threshold globally.
3098 mtx_lock(&vm_domainset_lock);
3099 while (vm_page_count_min()) {
3101 msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
3103 mtx_unlock(&vm_domainset_lock);
3107 * Wait for free pages to exceed the severe threshold globally.
3110 vm_wait_severe(void)
3113 mtx_lock(&vm_domainset_lock);
3114 while (vm_page_count_severe()) {
3115 vm_severe_waiters++;
3116 msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
3119 mtx_unlock(&vm_domainset_lock);
3126 return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
3130 vm_wait_doms(const domainset_t *wdoms)
3134 * We use racey wakeup synchronization to avoid expensive global
3135 * locking for the pageproc when sleeping with a non-specific vm_wait.
3136 * To handle this, we only sleep for one tick in this instance. It
3137 * is expected that most allocations for the pageproc will come from
3138 * kmem or vm_page_grab* which will use the more specific and
3139 * race-free vm_wait_domain().
3141 if (curproc == pageproc) {
3142 mtx_lock(&vm_domainset_lock);
3143 vm_pageproc_waiters++;
3144 msleep(&vm_pageproc_waiters, &vm_domainset_lock, PVM | PDROP,
3148 * XXX Ideally we would wait only until the allocation could
3149 * be satisfied. This condition can cause new allocators to
3150 * consume all freed pages while old allocators wait.
3152 mtx_lock(&vm_domainset_lock);
3153 if (vm_page_count_min_set(wdoms)) {
3155 msleep(&vm_min_domains, &vm_domainset_lock,
3156 PVM | PDROP, "vmwait", 0);
3158 mtx_unlock(&vm_domainset_lock);
3165 * Sleep until free pages are available for allocation.
3166 * - Called in various places after failed memory allocations.
3169 vm_wait_domain(int domain)
3171 struct vm_domain *vmd;
3174 vmd = VM_DOMAIN(domain);
3175 vm_domain_free_assert_unlocked(vmd);
3177 if (curproc == pageproc) {
3178 mtx_lock(&vm_domainset_lock);
3179 if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
3180 vmd->vmd_pageout_pages_needed = 1;
3181 msleep(&vmd->vmd_pageout_pages_needed,
3182 &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
3184 mtx_unlock(&vm_domainset_lock);
3186 if (pageproc == NULL)
3187 panic("vm_wait in early boot");
3188 DOMAINSET_ZERO(&wdom);
3189 DOMAINSET_SET(vmd->vmd_domain, &wdom);
3190 vm_wait_doms(&wdom);
3197 * Sleep until free pages are available for allocation in the
3198 * affinity domains of the obj. If obj is NULL, the domain set
3199 * for the calling thread is used.
3200 * Called in various places after failed memory allocations.
3203 vm_wait(vm_object_t obj)
3205 struct domainset *d;
3210 * Carefully fetch pointers only once: the struct domainset
3211 * itself is ummutable but the pointer might change.
3214 d = obj->domain.dr_policy;
3216 d = curthread->td_domain.dr_policy;
3218 vm_wait_doms(&d->ds_mask);
3222 * vm_domain_alloc_fail:
3224 * Called when a page allocation function fails. Informs the
3225 * pagedaemon and performs the requested wait. Requires the
3226 * domain_free and object lock on entry. Returns with the
3227 * object lock held and free lock released. Returns an error when
3228 * retry is necessary.
3232 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3235 vm_domain_free_assert_unlocked(vmd);
3237 atomic_add_int(&vmd->vmd_pageout_deficit,
3238 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3239 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3241 VM_OBJECT_WUNLOCK(object);
3242 vm_wait_domain(vmd->vmd_domain);
3244 VM_OBJECT_WLOCK(object);
3245 if (req & VM_ALLOC_WAITOK)
3255 * Sleep until free pages are available for allocation.
3256 * - Called only in vm_fault so that processes page faulting
3257 * can be easily tracked.
3258 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3259 * processes will be able to grab memory first. Do not change
3260 * this balance without careful testing first.
3263 vm_waitpfault(struct domainset *dset, int timo)
3267 * XXX Ideally we would wait only until the allocation could
3268 * be satisfied. This condition can cause new allocators to
3269 * consume all freed pages while old allocators wait.
3271 mtx_lock(&vm_domainset_lock);
3272 if (vm_page_count_min_set(&dset->ds_mask)) {
3274 msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3277 mtx_unlock(&vm_domainset_lock);
3280 static struct vm_pagequeue *
3281 _vm_page_pagequeue(vm_page_t m, uint8_t queue)
3284 return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue]);
3288 static struct vm_pagequeue *
3289 vm_page_pagequeue(vm_page_t m)
3292 return (_vm_page_pagequeue(m, vm_page_astate_load(m).queue));
3296 static __always_inline bool
3297 vm_page_pqstate_fcmpset(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3299 vm_page_astate_t tmp;
3303 if (__predict_true(vm_page_astate_fcmpset(m, old, new)))
3305 counter_u64_add(pqstate_commit_retries, 1);
3306 } while (old->_bits == tmp._bits);
3312 * Do the work of committing a queue state update that moves the page out of
3313 * its current queue.
3316 _vm_page_pqstate_commit_dequeue(struct vm_pagequeue *pq, vm_page_t m,
3317 vm_page_astate_t *old, vm_page_astate_t new)
3321 vm_pagequeue_assert_locked(pq);
3322 KASSERT(vm_page_pagequeue(m) == pq,
3323 ("%s: queue %p does not match page %p", __func__, pq, m));
3324 KASSERT(old->queue != PQ_NONE && new.queue != old->queue,
3325 ("%s: invalid queue indices %d %d",
3326 __func__, old->queue, new.queue));
3329 * Once the queue index of the page changes there is nothing
3330 * synchronizing with further updates to the page's physical
3331 * queue state. Therefore we must speculatively remove the page
3332 * from the queue now and be prepared to roll back if the queue
3333 * state update fails. If the page is not physically enqueued then
3334 * we just update its queue index.
3336 if ((old->flags & PGA_ENQUEUED) != 0) {
3337 new.flags &= ~PGA_ENQUEUED;
3338 next = TAILQ_NEXT(m, plinks.q);
3339 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3340 vm_pagequeue_cnt_dec(pq);
3341 if (!vm_page_pqstate_fcmpset(m, old, new)) {
3343 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3345 TAILQ_INSERT_BEFORE(next, m, plinks.q);
3346 vm_pagequeue_cnt_inc(pq);
3352 return (vm_page_pqstate_fcmpset(m, old, new));
3357 vm_page_pqstate_commit_dequeue(vm_page_t m, vm_page_astate_t *old,
3358 vm_page_astate_t new)
3360 struct vm_pagequeue *pq;
3361 vm_page_astate_t as;
3364 pq = _vm_page_pagequeue(m, old->queue);
3367 * The queue field and PGA_ENQUEUED flag are stable only so long as the
3368 * corresponding page queue lock is held.
3370 vm_pagequeue_lock(pq);
3371 as = vm_page_astate_load(m);
3372 if (__predict_false(as._bits != old->_bits)) {
3376 ret = _vm_page_pqstate_commit_dequeue(pq, m, old, new);
3378 vm_pagequeue_unlock(pq);
3383 * Commit a queue state update that enqueues or requeues a page.
3386 _vm_page_pqstate_commit_requeue(struct vm_pagequeue *pq, vm_page_t m,
3387 vm_page_astate_t *old, vm_page_astate_t new)
3389 struct vm_domain *vmd;
3391 vm_pagequeue_assert_locked(pq);
3392 KASSERT(old->queue != PQ_NONE && new.queue == old->queue,
3393 ("%s: invalid queue indices %d %d",
3394 __func__, old->queue, new.queue));
3396 new.flags |= PGA_ENQUEUED;
3397 if (!vm_page_pqstate_fcmpset(m, old, new))
3400 if ((old->flags & PGA_ENQUEUED) != 0)
3401 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3403 vm_pagequeue_cnt_inc(pq);
3406 * Give PGA_REQUEUE_HEAD precedence over PGA_REQUEUE. In particular, if
3407 * both flags are set in close succession, only PGA_REQUEUE_HEAD will be
3408 * applied, even if it was set first.
3410 if ((old->flags & PGA_REQUEUE_HEAD) != 0) {
3411 vmd = vm_pagequeue_domain(m);
3412 KASSERT(pq == &vmd->vmd_pagequeues[PQ_INACTIVE],
3413 ("%s: invalid page queue for page %p", __func__, m));
3414 TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3416 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3422 * Commit a queue state update that encodes a request for a deferred queue
3426 vm_page_pqstate_commit_request(vm_page_t m, vm_page_astate_t *old,
3427 vm_page_astate_t new)
3430 KASSERT(old->queue == new.queue || new.queue != PQ_NONE,
3431 ("%s: invalid state, queue %d flags %x",
3432 __func__, new.queue, new.flags));
3434 if (old->_bits != new._bits &&
3435 !vm_page_pqstate_fcmpset(m, old, new))
3437 vm_page_pqbatch_submit(m, new.queue);
3442 * A generic queue state update function. This handles more cases than the
3443 * specialized functions above.
3446 vm_page_pqstate_commit(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3449 if (old->_bits == new._bits)
3452 if (old->queue != PQ_NONE && new.queue != old->queue) {
3453 if (!vm_page_pqstate_commit_dequeue(m, old, new))
3455 if (new.queue != PQ_NONE)
3456 vm_page_pqbatch_submit(m, new.queue);
3458 if (!vm_page_pqstate_fcmpset(m, old, new))
3460 if (new.queue != PQ_NONE &&
3461 ((new.flags & ~old->flags) & PGA_QUEUE_OP_MASK) != 0)
3462 vm_page_pqbatch_submit(m, new.queue);
3468 * Apply deferred queue state updates to a page.
3471 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m, uint8_t queue)
3473 vm_page_astate_t new, old;
3475 CRITICAL_ASSERT(curthread);
3476 vm_pagequeue_assert_locked(pq);
3477 KASSERT(queue < PQ_COUNT,
3478 ("%s: invalid queue index %d", __func__, queue));
3479 KASSERT(pq == _vm_page_pagequeue(m, queue),
3480 ("%s: page %p does not belong to queue %p", __func__, m, pq));
3482 for (old = vm_page_astate_load(m);;) {
3483 if (__predict_false(old.queue != queue ||
3484 (old.flags & PGA_QUEUE_OP_MASK) == 0)) {
3485 counter_u64_add(queue_nops, 1);
3488 KASSERT(old.queue != PQ_NONE || (old.flags & PGA_QUEUE_STATE_MASK) == 0,
3489 ("%s: page %p has unexpected queue state", __func__, m));
3492 if ((old.flags & PGA_DEQUEUE) != 0) {
3493 new.flags &= ~PGA_QUEUE_OP_MASK;
3494 new.queue = PQ_NONE;
3495 if (__predict_true(_vm_page_pqstate_commit_dequeue(pq,
3497 counter_u64_add(queue_ops, 1);
3501 new.flags &= ~(PGA_REQUEUE | PGA_REQUEUE_HEAD);
3502 if (__predict_true(_vm_page_pqstate_commit_requeue(pq,
3504 counter_u64_add(queue_ops, 1);
3512 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3517 for (i = 0; i < bq->bq_cnt; i++)
3518 vm_pqbatch_process_page(pq, bq->bq_pa[i], queue);
3519 vm_batchqueue_init(bq);
3523 * vm_page_pqbatch_submit: [ internal use only ]
3525 * Enqueue a page in the specified page queue's batched work queue.
3526 * The caller must have encoded the requested operation in the page
3527 * structure's a.flags field.
3530 vm_page_pqbatch_submit(vm_page_t m, uint8_t queue)
3532 struct vm_batchqueue *bq;
3533 struct vm_pagequeue *pq;
3536 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3537 ("page %p is unmanaged", m));
3538 KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3540 domain = vm_phys_domain(m);
3541 pq = &vm_pagequeue_domain(m)->vmd_pagequeues[queue];
3544 bq = DPCPU_PTR(pqbatch[domain][queue]);
3545 if (vm_batchqueue_insert(bq, m)) {
3550 vm_pagequeue_lock(pq);
3552 bq = DPCPU_PTR(pqbatch[domain][queue]);
3553 vm_pqbatch_process(pq, bq, queue);
3554 vm_pqbatch_process_page(pq, m, queue);
3555 vm_pagequeue_unlock(pq);
3560 * vm_page_pqbatch_drain: [ internal use only ]
3562 * Force all per-CPU page queue batch queues to be drained. This is
3563 * intended for use in severe memory shortages, to ensure that pages
3564 * do not remain stuck in the batch queues.
3567 vm_page_pqbatch_drain(void)
3570 struct vm_domain *vmd;
3571 struct vm_pagequeue *pq;
3572 int cpu, domain, queue;
3577 sched_bind(td, cpu);
3580 for (domain = 0; domain < vm_ndomains; domain++) {
3581 vmd = VM_DOMAIN(domain);
3582 for (queue = 0; queue < PQ_COUNT; queue++) {
3583 pq = &vmd->vmd_pagequeues[queue];
3584 vm_pagequeue_lock(pq);
3586 vm_pqbatch_process(pq,
3587 DPCPU_PTR(pqbatch[domain][queue]), queue);
3589 vm_pagequeue_unlock(pq);
3599 * vm_page_dequeue_deferred: [ internal use only ]
3601 * Request removal of the given page from its current page
3602 * queue. Physical removal from the queue may be deferred
3605 * The page must be locked.
3608 vm_page_dequeue_deferred(vm_page_t m)
3610 vm_page_astate_t new, old;
3612 old = vm_page_astate_load(m);
3614 if (old.queue == PQ_NONE) {
3615 KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3616 ("%s: page %p has unexpected queue state",
3621 new.flags |= PGA_DEQUEUE;
3622 } while (!vm_page_pqstate_commit_request(m, &old, new));
3628 * Remove the page from whichever page queue it's in, if any, before
3632 vm_page_dequeue(vm_page_t m)
3634 vm_page_astate_t new, old;
3636 old = vm_page_astate_load(m);
3638 if (old.queue == PQ_NONE) {
3639 KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3640 ("%s: page %p has unexpected queue state",
3645 new.flags &= ~PGA_QUEUE_OP_MASK;
3646 new.queue = PQ_NONE;
3647 } while (!vm_page_pqstate_commit_dequeue(m, &old, new));
3652 * Schedule the given page for insertion into the specified page queue.
3653 * Physical insertion of the page may be deferred indefinitely.
3656 vm_page_enqueue(vm_page_t m, uint8_t queue)
3659 KASSERT(m->a.queue == PQ_NONE &&
3660 (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
3661 ("%s: page %p is already enqueued", __func__, m));
3662 KASSERT(m->ref_count > 0,
3663 ("%s: page %p does not carry any references", __func__, m));
3666 if ((m->a.flags & PGA_REQUEUE) == 0)
3667 vm_page_aflag_set(m, PGA_REQUEUE);
3668 vm_page_pqbatch_submit(m, queue);
3672 * vm_page_free_prep:
3674 * Prepares the given page to be put on the free list,
3675 * disassociating it from any VM object. The caller may return
3676 * the page to the free list only if this function returns true.
3678 * The object must be locked. The page must be locked if it is
3682 vm_page_free_prep(vm_page_t m)
3686 * Synchronize with threads that have dropped a reference to this
3689 atomic_thread_fence_acq();
3691 if (vm_page_sbusied(m))
3692 panic("vm_page_free_prep: freeing shared busy page %p", m);
3694 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
3695 if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
3698 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3699 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
3700 KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
3701 m, i, (uintmax_t)*p));
3704 if ((m->oflags & VPO_UNMANAGED) == 0) {
3705 KASSERT(!pmap_page_is_mapped(m),
3706 ("vm_page_free_prep: freeing mapped page %p", m));
3707 KASSERT((m->a.flags & (PGA_EXECUTABLE | PGA_WRITEABLE)) == 0,
3708 ("vm_page_free_prep: mapping flags set in page %p", m));
3710 KASSERT(m->a.queue == PQ_NONE,
3711 ("vm_page_free_prep: unmanaged page %p is queued", m));
3713 VM_CNT_INC(v_tfree);
3715 if (m->object != NULL) {
3716 KASSERT(((m->oflags & VPO_UNMANAGED) != 0) ==
3717 ((m->object->flags & OBJ_UNMANAGED) != 0),
3718 ("vm_page_free_prep: managed flag mismatch for page %p",
3720 vm_page_object_remove(m);
3723 * The object reference can be released without an atomic
3726 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
3727 m->ref_count == VPRC_OBJREF,
3728 ("vm_page_free_prep: page %p has unexpected ref_count %u",
3731 m->ref_count -= VPRC_OBJREF;
3735 if (vm_page_xbusied(m))
3736 panic("vm_page_free_prep: freeing exclusive busy page %p", m);
3739 * If fictitious remove object association and
3742 if ((m->flags & PG_FICTITIOUS) != 0) {
3743 KASSERT(m->ref_count == 1,
3744 ("fictitious page %p is referenced", m));
3745 KASSERT(m->a.queue == PQ_NONE,
3746 ("fictitious page %p is queued", m));
3751 * Pages need not be dequeued before they are returned to the physical
3752 * memory allocator, but they must at least be marked for a deferred
3755 if ((m->oflags & VPO_UNMANAGED) == 0)
3756 vm_page_dequeue_deferred(m);
3761 if (m->ref_count != 0)
3762 panic("vm_page_free_prep: page %p has references", m);
3765 * Restore the default memory attribute to the page.
3767 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3768 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3770 #if VM_NRESERVLEVEL > 0
3772 * Determine whether the page belongs to a reservation. If the page was
3773 * allocated from a per-CPU cache, it cannot belong to a reservation, so
3774 * as an optimization, we avoid the check in that case.
3776 if ((m->flags & PG_PCPU_CACHE) == 0 && vm_reserv_free_page(m))
3786 * Returns the given page to the free list, disassociating it
3787 * from any VM object.
3789 * The object must be locked. The page must be locked if it is
3793 vm_page_free_toq(vm_page_t m)
3795 struct vm_domain *vmd;
3798 if (!vm_page_free_prep(m))
3801 vmd = vm_pagequeue_domain(m);
3802 zone = vmd->vmd_pgcache[m->pool].zone;
3803 if ((m->flags & PG_PCPU_CACHE) != 0 && zone != NULL) {
3807 vm_domain_free_lock(vmd);
3808 vm_phys_free_pages(m, 0);
3809 vm_domain_free_unlock(vmd);
3810 vm_domain_freecnt_inc(vmd, 1);
3814 * vm_page_free_pages_toq:
3816 * Returns a list of pages to the free list, disassociating it
3817 * from any VM object. In other words, this is equivalent to
3818 * calling vm_page_free_toq() for each page of a list of VM objects.
3820 * The objects must be locked. The pages must be locked if it is
3824 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
3829 if (SLIST_EMPTY(free))
3833 while ((m = SLIST_FIRST(free)) != NULL) {
3835 SLIST_REMOVE_HEAD(free, plinks.s.ss);
3836 vm_page_free_toq(m);
3839 if (update_wire_count)
3844 * Mark this page as wired down, preventing reclamation by the page daemon
3845 * or when the containing object is destroyed.
3848 vm_page_wire(vm_page_t m)
3852 KASSERT(m->object != NULL,
3853 ("vm_page_wire: page %p does not belong to an object", m));
3854 if (!vm_page_busied(m) && !vm_object_busied(m->object))
3855 VM_OBJECT_ASSERT_LOCKED(m->object);
3856 KASSERT((m->flags & PG_FICTITIOUS) == 0 ||
3857 VPRC_WIRE_COUNT(m->ref_count) >= 1,
3858 ("vm_page_wire: fictitious page %p has zero wirings", m));
3860 old = atomic_fetchadd_int(&m->ref_count, 1);
3861 KASSERT(VPRC_WIRE_COUNT(old) != VPRC_WIRE_COUNT_MAX,
3862 ("vm_page_wire: counter overflow for page %p", m));
3863 if (VPRC_WIRE_COUNT(old) == 0) {
3864 if ((m->oflags & VPO_UNMANAGED) == 0)
3865 vm_page_aflag_set(m, PGA_DEQUEUE);
3871 * Attempt to wire a mapped page following a pmap lookup of that page.
3872 * This may fail if a thread is concurrently tearing down mappings of the page.
3873 * The transient failure is acceptable because it translates to the
3874 * failure of the caller pmap_extract_and_hold(), which should be then
3875 * followed by the vm_fault() fallback, see e.g. vm_fault_quick_hold_pages().
3878 vm_page_wire_mapped(vm_page_t m)
3885 ("vm_page_wire_mapped: wiring unreferenced page %p", m));
3886 if ((old & VPRC_BLOCKED) != 0)
3888 } while (!atomic_fcmpset_int(&m->ref_count, &old, old + 1));
3890 if (VPRC_WIRE_COUNT(old) == 0) {
3891 if ((m->oflags & VPO_UNMANAGED) == 0)
3892 vm_page_aflag_set(m, PGA_DEQUEUE);
3899 * Release a wiring reference to a managed page. If the page still belongs to
3900 * an object, update its position in the page queues to reflect the reference.
3901 * If the wiring was the last reference to the page, free the page.
3904 vm_page_unwire_managed(vm_page_t m, uint8_t nqueue, bool noreuse)
3908 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3909 ("%s: page %p is unmanaged", __func__, m));
3912 * Update LRU state before releasing the wiring reference.
3913 * Use a release store when updating the reference count to
3914 * synchronize with vm_page_free_prep().
3918 KASSERT(VPRC_WIRE_COUNT(old) > 0,
3919 ("vm_page_unwire: wire count underflow for page %p", m));
3921 if (old > VPRC_OBJREF + 1) {
3923 * The page has at least one other wiring reference. An
3924 * earlier iteration of this loop may have called
3925 * vm_page_release_toq() and cleared PGA_DEQUEUE, so
3926 * re-set it if necessary.
3928 if ((vm_page_astate_load(m).flags & PGA_DEQUEUE) == 0)
3929 vm_page_aflag_set(m, PGA_DEQUEUE);
3930 } else if (old == VPRC_OBJREF + 1) {
3932 * This is the last wiring. Clear PGA_DEQUEUE and
3933 * update the page's queue state to reflect the
3934 * reference. If the page does not belong to an object
3935 * (i.e., the VPRC_OBJREF bit is clear), we only need to
3936 * clear leftover queue state.
3938 vm_page_release_toq(m, nqueue, false);
3939 } else if (old == 1) {
3940 vm_page_aflag_clear(m, PGA_DEQUEUE);
3942 } while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
3944 if (VPRC_WIRE_COUNT(old) == 1) {
3952 * Release one wiring of the specified page, potentially allowing it to be
3955 * Only managed pages belonging to an object can be paged out. If the number
3956 * of wirings transitions to zero and the page is eligible for page out, then
3957 * the page is added to the specified paging queue. If the released wiring
3958 * represented the last reference to the page, the page is freed.
3960 * A managed page must be locked.
3963 vm_page_unwire(vm_page_t m, uint8_t nqueue)
3966 KASSERT(nqueue < PQ_COUNT,
3967 ("vm_page_unwire: invalid queue %u request for page %p",
3970 if ((m->oflags & VPO_UNMANAGED) != 0) {
3971 if (vm_page_unwire_noq(m) && m->ref_count == 0)
3975 vm_page_unwire_managed(m, nqueue, false);
3979 * Unwire a page without (re-)inserting it into a page queue. It is up
3980 * to the caller to enqueue, requeue, or free the page as appropriate.
3981 * In most cases involving managed pages, vm_page_unwire() should be used
3985 vm_page_unwire_noq(vm_page_t m)
3989 old = vm_page_drop(m, 1);
3990 KASSERT(VPRC_WIRE_COUNT(old) != 0,
3991 ("vm_page_unref: counter underflow for page %p", m));
3992 KASSERT((m->flags & PG_FICTITIOUS) == 0 || VPRC_WIRE_COUNT(old) > 1,
3993 ("vm_page_unref: missing ref on fictitious page %p", m));
3995 if (VPRC_WIRE_COUNT(old) > 1)
3997 if ((m->oflags & VPO_UNMANAGED) == 0)
3998 vm_page_aflag_clear(m, PGA_DEQUEUE);
4004 * Ensure that the page ends up in the specified page queue. If the page is
4005 * active or being moved to the active queue, ensure that its act_count is
4006 * at least ACT_INIT but do not otherwise mess with it.
4008 * A managed page must be locked.
4010 static __always_inline void
4011 vm_page_mvqueue(vm_page_t m, const uint8_t nqueue, const uint16_t nflag)
4013 vm_page_astate_t old, new;
4015 KASSERT(m->ref_count > 0,
4016 ("%s: page %p does not carry any references", __func__, m));
4017 KASSERT(nflag == PGA_REQUEUE || nflag == PGA_REQUEUE_HEAD,
4018 ("%s: invalid flags %x", __func__, nflag));
4020 if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
4023 old = vm_page_astate_load(m);
4025 if ((old.flags & PGA_DEQUEUE) != 0)
4028 new.flags &= ~PGA_QUEUE_OP_MASK;
4029 if (nqueue == PQ_ACTIVE)
4030 new.act_count = max(old.act_count, ACT_INIT);
4031 if (old.queue == nqueue) {
4032 if (nqueue != PQ_ACTIVE)
4038 } while (!vm_page_pqstate_commit(m, &old, new));
4042 * Put the specified page on the active list (if appropriate).
4045 vm_page_activate(vm_page_t m)
4048 vm_page_mvqueue(m, PQ_ACTIVE, PGA_REQUEUE);
4052 * Move the specified page to the tail of the inactive queue, or requeue
4053 * the page if it is already in the inactive queue.
4056 vm_page_deactivate(vm_page_t m)
4059 vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE);
4063 vm_page_deactivate_noreuse(vm_page_t m)
4066 vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE_HEAD);
4070 * Put a page in the laundry, or requeue it if it is already there.
4073 vm_page_launder(vm_page_t m)
4076 vm_page_mvqueue(m, PQ_LAUNDRY, PGA_REQUEUE);
4080 * Put a page in the PQ_UNSWAPPABLE holding queue.
4083 vm_page_unswappable(vm_page_t m)
4086 KASSERT(!vm_page_wired(m) && (m->oflags & VPO_UNMANAGED) == 0,
4087 ("page %p already unswappable", m));
4090 vm_page_enqueue(m, PQ_UNSWAPPABLE);
4094 * Release a page back to the page queues in preparation for unwiring.
4097 vm_page_release_toq(vm_page_t m, uint8_t nqueue, const bool noreuse)
4099 vm_page_astate_t old, new;
4103 * Use a check of the valid bits to determine whether we should
4104 * accelerate reclamation of the page. The object lock might not be
4105 * held here, in which case the check is racy. At worst we will either
4106 * accelerate reclamation of a valid page and violate LRU, or
4107 * unnecessarily defer reclamation of an invalid page.
4109 * If we were asked to not cache the page, place it near the head of the
4110 * inactive queue so that is reclaimed sooner.
4112 if (noreuse || m->valid == 0) {
4113 nqueue = PQ_INACTIVE;
4114 nflag = PGA_REQUEUE_HEAD;
4116 nflag = PGA_REQUEUE;
4119 old = vm_page_astate_load(m);
4124 * If the page is already in the active queue and we are not
4125 * trying to accelerate reclamation, simply mark it as
4126 * referenced and avoid any queue operations.
4128 new.flags &= ~PGA_QUEUE_OP_MASK;
4129 if (nflag != PGA_REQUEUE_HEAD && old.queue == PQ_ACTIVE)
4130 new.flags |= PGA_REFERENCED;
4135 } while (!vm_page_pqstate_commit(m, &old, new));
4139 * Unwire a page and either attempt to free it or re-add it to the page queues.
4142 vm_page_release(vm_page_t m, int flags)
4146 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4147 ("vm_page_release: page %p is unmanaged", m));
4149 if ((flags & VPR_TRYFREE) != 0) {
4151 object = (vm_object_t)atomic_load_ptr(&m->object);
4154 /* Depends on type-stability. */
4155 if (vm_page_busied(m) || !VM_OBJECT_TRYWLOCK(object))
4157 if (object == m->object) {
4158 vm_page_release_locked(m, flags);
4159 VM_OBJECT_WUNLOCK(object);
4162 VM_OBJECT_WUNLOCK(object);
4165 vm_page_unwire_managed(m, PQ_INACTIVE, flags != 0);
4168 /* See vm_page_release(). */
4170 vm_page_release_locked(vm_page_t m, int flags)
4173 VM_OBJECT_ASSERT_WLOCKED(m->object);
4174 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4175 ("vm_page_release_locked: page %p is unmanaged", m));
4177 if (vm_page_unwire_noq(m)) {
4178 if ((flags & VPR_TRYFREE) != 0 &&
4179 (m->object->ref_count == 0 || !pmap_page_is_mapped(m)) &&
4180 m->dirty == 0 && vm_page_tryxbusy(m)) {
4183 vm_page_release_toq(m, PQ_INACTIVE, flags != 0);
4189 vm_page_try_blocked_op(vm_page_t m, void (*op)(vm_page_t))
4193 KASSERT(m->object != NULL && (m->oflags & VPO_UNMANAGED) == 0,
4194 ("vm_page_try_blocked_op: page %p has no object", m));
4195 KASSERT(vm_page_busied(m),
4196 ("vm_page_try_blocked_op: page %p is not busy", m));
4197 VM_OBJECT_ASSERT_LOCKED(m->object);
4202 ("vm_page_try_blocked_op: page %p has no references", m));
4203 if (VPRC_WIRE_COUNT(old) != 0)
4205 } while (!atomic_fcmpset_int(&m->ref_count, &old, old | VPRC_BLOCKED));
4210 * If the object is read-locked, new wirings may be created via an
4213 old = vm_page_drop(m, VPRC_BLOCKED);
4214 KASSERT(!VM_OBJECT_WOWNED(m->object) ||
4215 old == (VPRC_BLOCKED | VPRC_OBJREF),
4216 ("vm_page_try_blocked_op: unexpected refcount value %u for %p",
4222 * Atomically check for wirings and remove all mappings of the page.
4225 vm_page_try_remove_all(vm_page_t m)
4228 return (vm_page_try_blocked_op(m, pmap_remove_all));
4232 * Atomically check for wirings and remove all writeable mappings of the page.
4235 vm_page_try_remove_write(vm_page_t m)
4238 return (vm_page_try_blocked_op(m, pmap_remove_write));
4244 * Apply the specified advice to the given page.
4246 * The object and page must be locked.
4249 vm_page_advise(vm_page_t m, int advice)
4252 VM_OBJECT_ASSERT_WLOCKED(m->object);
4253 if (advice == MADV_FREE)
4255 * Mark the page clean. This will allow the page to be freed
4256 * without first paging it out. MADV_FREE pages are often
4257 * quickly reused by malloc(3), so we do not do anything that
4258 * would result in a page fault on a later access.
4261 else if (advice != MADV_DONTNEED) {
4262 if (advice == MADV_WILLNEED)
4263 vm_page_activate(m);
4267 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
4271 * Clear any references to the page. Otherwise, the page daemon will
4272 * immediately reactivate the page.
4274 vm_page_aflag_clear(m, PGA_REFERENCED);
4277 * Place clean pages near the head of the inactive queue rather than
4278 * the tail, thus defeating the queue's LRU operation and ensuring that
4279 * the page will be reused quickly. Dirty pages not already in the
4280 * laundry are moved there.
4283 vm_page_deactivate_noreuse(m);
4284 else if (!vm_page_in_laundry(m))
4289 vm_page_grab_pflags(int allocflags)
4293 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
4294 (allocflags & VM_ALLOC_WIRED) != 0,
4295 ("vm_page_grab_pflags: the pages must be busied or wired"));
4296 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4297 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4298 ("vm_page_grab_pflags: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY "
4300 pflags = allocflags &
4301 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL |
4303 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4304 pflags |= VM_ALLOC_WAITFAIL;
4305 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4306 pflags |= VM_ALLOC_SBUSY;
4312 * Grab a page, waiting until we are waken up due to the page
4313 * changing state. We keep on waiting, if the page continues
4314 * to be in the object. If the page doesn't exist, first allocate it
4315 * and then conditionally zero it.
4317 * This routine may sleep.
4319 * The object must be locked on entry. The lock will, however, be released
4320 * and reacquired if the routine sleeps.
4323 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
4328 VM_OBJECT_ASSERT_WLOCKED(object);
4329 pflags = vm_page_grab_pflags(allocflags);
4331 if ((m = vm_page_lookup(object, pindex)) != NULL) {
4332 if (!vm_page_acquire_flags(m, allocflags)) {
4333 if (vm_page_busy_sleep_flags(object, m, "pgrbwt",
4340 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4342 m = vm_page_alloc(object, pindex, pflags);
4344 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4348 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
4352 if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4353 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4362 * Grab a page and make it valid, paging in if necessary. Pages missing from
4363 * their pager are zero filled and validated. If a VM_ALLOC_COUNT is supplied
4364 * and the page is not valid as many as VM_INITIAL_PAGEIN pages can be brought
4365 * in simultaneously. Additional pages will be left on a paging queue but
4366 * will neither be wired nor busy regardless of allocflags.
4369 vm_page_grab_valid(vm_page_t *mp, vm_object_t object, vm_pindex_t pindex, int allocflags)
4372 vm_page_t ma[VM_INITIAL_PAGEIN];
4374 int after, i, pflags, rv;
4376 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4377 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4378 ("vm_page_grab_valid: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4379 KASSERT((allocflags &
4380 (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4381 ("vm_page_grab_valid: Invalid flags 0x%X", allocflags));
4382 VM_OBJECT_ASSERT_WLOCKED(object);
4383 pflags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY);
4384 pflags |= VM_ALLOC_WAITFAIL;
4388 if ((m = vm_page_lookup(object, pindex)) != NULL) {
4390 * If the page is fully valid it can only become invalid
4391 * with the object lock held. If it is not valid it can
4392 * become valid with the busy lock held. Therefore, we
4393 * may unnecessarily lock the exclusive busy here if we
4394 * race with I/O completion not using the object lock.
4395 * However, we will not end up with an invalid page and a
4398 if (!vm_page_all_valid(m) ||
4399 (allocflags & (VM_ALLOC_IGN_SBUSY | VM_ALLOC_SBUSY)) == 0) {
4400 sleep = !vm_page_tryxbusy(m);
4403 sleep = !vm_page_trysbusy(m);
4405 (void)vm_page_busy_sleep_flags(object, m, "pgrbwt",
4409 if ((allocflags & VM_ALLOC_NOCREAT) != 0 &&
4410 !vm_page_all_valid(m)) {
4416 return (VM_PAGER_FAIL);
4418 if ((allocflags & VM_ALLOC_WIRED) != 0)
4420 if (vm_page_all_valid(m))
4422 } else if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4424 return (VM_PAGER_FAIL);
4425 } else if ((m = vm_page_alloc(object, pindex, pflags)) != NULL) {
4431 vm_page_assert_xbusied(m);
4433 if (vm_pager_has_page(object, pindex, NULL, &after)) {
4434 after = MIN(after, VM_INITIAL_PAGEIN);
4435 after = MIN(after, allocflags >> VM_ALLOC_COUNT_SHIFT);
4436 after = MAX(after, 1);
4438 for (i = 1; i < after; i++) {
4439 if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
4440 if (ma[i]->valid || !vm_page_tryxbusy(ma[i]))
4443 ma[i] = vm_page_alloc(object, m->pindex + i,
4450 rv = vm_pager_get_pages(object, ma, after, NULL, NULL);
4451 /* Pager may have replaced a page. */
4453 if (rv != VM_PAGER_OK) {
4454 if ((allocflags & VM_ALLOC_WIRED) != 0)
4455 vm_page_unwire_noq(m);
4456 for (i = 0; i < after; i++) {
4457 if (!vm_page_wired(ma[i]))
4458 vm_page_free(ma[i]);
4460 vm_page_xunbusy(ma[i]);
4465 for (i = 1; i < after; i++)
4466 vm_page_readahead_finish(ma[i]);
4467 MPASS(vm_page_all_valid(m));
4469 vm_page_zero_invalid(m, TRUE);
4472 if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4478 if ((allocflags & VM_ALLOC_SBUSY) != 0 && xbusy)
4479 vm_page_busy_downgrade(m);
4481 return (VM_PAGER_OK);
4485 * Return the specified range of pages from the given object. For each
4486 * page offset within the range, if a page already exists within the object
4487 * at that offset and it is busy, then wait for it to change state. If,
4488 * instead, the page doesn't exist, then allocate it.
4490 * The caller must always specify an allocation class.
4492 * allocation classes:
4493 * VM_ALLOC_NORMAL normal process request
4494 * VM_ALLOC_SYSTEM system *really* needs the pages
4496 * The caller must always specify that the pages are to be busied and/or
4499 * optional allocation flags:
4500 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
4501 * VM_ALLOC_NOBUSY do not exclusive busy the page
4502 * VM_ALLOC_NOWAIT do not sleep
4503 * VM_ALLOC_SBUSY set page to sbusy state
4504 * VM_ALLOC_WIRED wire the pages
4505 * VM_ALLOC_ZERO zero and validate any invalid pages
4507 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
4508 * may return a partial prefix of the requested range.
4511 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
4512 vm_page_t *ma, int count)
4518 VM_OBJECT_ASSERT_WLOCKED(object);
4519 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
4520 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
4522 pflags = vm_page_grab_pflags(allocflags);
4528 m = vm_radix_lookup_le(&object->rtree, pindex + i);
4529 if (m == NULL || m->pindex != pindex + i) {
4533 mpred = TAILQ_PREV(m, pglist, listq);
4534 for (; i < count; i++) {
4536 if (!vm_page_acquire_flags(m, allocflags)) {
4537 if (vm_page_busy_sleep_flags(object, m,
4538 "grbmaw", allocflags))
4543 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4545 m = vm_page_alloc_after(object, pindex + i,
4546 pflags | VM_ALLOC_COUNT(count - i), mpred);
4548 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4553 if (vm_page_none_valid(m) &&
4554 (allocflags & VM_ALLOC_ZERO) != 0) {
4555 if ((m->flags & PG_ZERO) == 0)
4559 if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4560 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4566 m = vm_page_next(m);
4572 * Mapping function for valid or dirty bits in a page.
4574 * Inputs are required to range within a page.
4577 vm_page_bits(int base, int size)
4583 base + size <= PAGE_SIZE,
4584 ("vm_page_bits: illegal base/size %d/%d", base, size)
4587 if (size == 0) /* handle degenerate case */
4590 first_bit = base >> DEV_BSHIFT;
4591 last_bit = (base + size - 1) >> DEV_BSHIFT;
4593 return (((vm_page_bits_t)2 << last_bit) -
4594 ((vm_page_bits_t)1 << first_bit));
4598 vm_page_bits_set(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t set)
4601 #if PAGE_SIZE == 32768
4602 atomic_set_64((uint64_t *)bits, set);
4603 #elif PAGE_SIZE == 16384
4604 atomic_set_32((uint32_t *)bits, set);
4605 #elif (PAGE_SIZE == 8192) && defined(atomic_set_16)
4606 atomic_set_16((uint16_t *)bits, set);
4607 #elif (PAGE_SIZE == 4096) && defined(atomic_set_8)
4608 atomic_set_8((uint8_t *)bits, set);
4609 #else /* PAGE_SIZE <= 8192 */
4613 addr = (uintptr_t)bits;
4615 * Use a trick to perform a 32-bit atomic on the
4616 * containing aligned word, to not depend on the existence
4617 * of atomic_{set, clear}_{8, 16}.
4619 shift = addr & (sizeof(uint32_t) - 1);
4620 #if BYTE_ORDER == BIG_ENDIAN
4621 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4625 addr &= ~(sizeof(uint32_t) - 1);
4626 atomic_set_32((uint32_t *)addr, set << shift);
4627 #endif /* PAGE_SIZE */
4631 vm_page_bits_clear(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t clear)
4634 #if PAGE_SIZE == 32768
4635 atomic_clear_64((uint64_t *)bits, clear);
4636 #elif PAGE_SIZE == 16384
4637 atomic_clear_32((uint32_t *)bits, clear);
4638 #elif (PAGE_SIZE == 8192) && defined(atomic_clear_16)
4639 atomic_clear_16((uint16_t *)bits, clear);
4640 #elif (PAGE_SIZE == 4096) && defined(atomic_clear_8)
4641 atomic_clear_8((uint8_t *)bits, clear);
4642 #else /* PAGE_SIZE <= 8192 */
4646 addr = (uintptr_t)bits;
4648 * Use a trick to perform a 32-bit atomic on the
4649 * containing aligned word, to not depend on the existence
4650 * of atomic_{set, clear}_{8, 16}.
4652 shift = addr & (sizeof(uint32_t) - 1);
4653 #if BYTE_ORDER == BIG_ENDIAN
4654 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4658 addr &= ~(sizeof(uint32_t) - 1);
4659 atomic_clear_32((uint32_t *)addr, clear << shift);
4660 #endif /* PAGE_SIZE */
4663 static inline vm_page_bits_t
4664 vm_page_bits_swap(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t newbits)
4666 #if PAGE_SIZE == 32768
4670 while (atomic_fcmpset_64(bits, &old, newbits) == 0);
4672 #elif PAGE_SIZE == 16384
4676 while (atomic_fcmpset_32(bits, &old, newbits) == 0);
4678 #elif (PAGE_SIZE == 8192) && defined(atomic_fcmpset_16)
4682 while (atomic_fcmpset_16(bits, &old, newbits) == 0);
4684 #elif (PAGE_SIZE == 4096) && defined(atomic_fcmpset_8)
4688 while (atomic_fcmpset_8(bits, &old, newbits) == 0);
4690 #else /* PAGE_SIZE <= 4096*/
4692 uint32_t old, new, mask;
4695 addr = (uintptr_t)bits;
4697 * Use a trick to perform a 32-bit atomic on the
4698 * containing aligned word, to not depend on the existence
4699 * of atomic_{set, swap, clear}_{8, 16}.
4701 shift = addr & (sizeof(uint32_t) - 1);
4702 #if BYTE_ORDER == BIG_ENDIAN
4703 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4707 addr &= ~(sizeof(uint32_t) - 1);
4708 mask = VM_PAGE_BITS_ALL << shift;
4713 new |= newbits << shift;
4714 } while (atomic_fcmpset_32((uint32_t *)addr, &old, new) == 0);
4715 return (old >> shift);
4716 #endif /* PAGE_SIZE */
4720 * vm_page_set_valid_range:
4722 * Sets portions of a page valid. The arguments are expected
4723 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4724 * of any partial chunks touched by the range. The invalid portion of
4725 * such chunks will be zeroed.
4727 * (base + size) must be less then or equal to PAGE_SIZE.
4730 vm_page_set_valid_range(vm_page_t m, int base, int size)
4733 vm_page_bits_t pagebits;
4735 vm_page_assert_busied(m);
4736 if (size == 0) /* handle degenerate case */
4740 * If the base is not DEV_BSIZE aligned and the valid
4741 * bit is clear, we have to zero out a portion of the
4744 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4745 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
4746 pmap_zero_page_area(m, frag, base - frag);
4749 * If the ending offset is not DEV_BSIZE aligned and the
4750 * valid bit is clear, we have to zero out a portion of
4753 endoff = base + size;
4754 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4755 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
4756 pmap_zero_page_area(m, endoff,
4757 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4760 * Assert that no previously invalid block that is now being validated
4763 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
4764 ("vm_page_set_valid_range: page %p is dirty", m));
4767 * Set valid bits inclusive of any overlap.
4769 pagebits = vm_page_bits(base, size);
4770 if (vm_page_xbusied(m))
4771 m->valid |= pagebits;
4773 vm_page_bits_set(m, &m->valid, pagebits);
4777 * Set the page dirty bits and free the invalid swap space if
4778 * present. Returns the previous dirty bits.
4781 vm_page_set_dirty(vm_page_t m)
4785 VM_PAGE_OBJECT_BUSY_ASSERT(m);
4787 if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m)) {
4789 m->dirty = VM_PAGE_BITS_ALL;
4791 old = vm_page_bits_swap(m, &m->dirty, VM_PAGE_BITS_ALL);
4792 if (old == 0 && (m->a.flags & PGA_SWAP_SPACE) != 0)
4793 vm_pager_page_unswapped(m);
4799 * Clear the given bits from the specified page's dirty field.
4801 static __inline void
4802 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
4805 vm_page_assert_busied(m);
4808 * If the page is xbusied and not write mapped we are the
4809 * only thread that can modify dirty bits. Otherwise, The pmap
4810 * layer can call vm_page_dirty() without holding a distinguished
4811 * lock. The combination of page busy and atomic operations
4812 * suffice to guarantee consistency of the page dirty field.
4814 if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
4815 m->dirty &= ~pagebits;
4817 vm_page_bits_clear(m, &m->dirty, pagebits);
4821 * vm_page_set_validclean:
4823 * Sets portions of a page valid and clean. The arguments are expected
4824 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4825 * of any partial chunks touched by the range. The invalid portion of
4826 * such chunks will be zero'd.
4828 * (base + size) must be less then or equal to PAGE_SIZE.
4831 vm_page_set_validclean(vm_page_t m, int base, int size)
4833 vm_page_bits_t oldvalid, pagebits;
4836 vm_page_assert_busied(m);
4837 if (size == 0) /* handle degenerate case */
4841 * If the base is not DEV_BSIZE aligned and the valid
4842 * bit is clear, we have to zero out a portion of the
4845 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4846 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
4847 pmap_zero_page_area(m, frag, base - frag);
4850 * If the ending offset is not DEV_BSIZE aligned and the
4851 * valid bit is clear, we have to zero out a portion of
4854 endoff = base + size;
4855 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4856 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
4857 pmap_zero_page_area(m, endoff,
4858 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4861 * Set valid, clear dirty bits. If validating the entire
4862 * page we can safely clear the pmap modify bit. We also
4863 * use this opportunity to clear the PGA_NOSYNC flag. If a process
4864 * takes a write fault on a MAP_NOSYNC memory area the flag will
4867 * We set valid bits inclusive of any overlap, but we can only
4868 * clear dirty bits for DEV_BSIZE chunks that are fully within
4871 oldvalid = m->valid;
4872 pagebits = vm_page_bits(base, size);
4873 if (vm_page_xbusied(m))
4874 m->valid |= pagebits;
4876 vm_page_bits_set(m, &m->valid, pagebits);
4878 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
4879 frag = DEV_BSIZE - frag;
4885 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
4887 if (base == 0 && size == PAGE_SIZE) {
4889 * The page can only be modified within the pmap if it is
4890 * mapped, and it can only be mapped if it was previously
4893 if (oldvalid == VM_PAGE_BITS_ALL)
4895 * Perform the pmap_clear_modify() first. Otherwise,
4896 * a concurrent pmap operation, such as
4897 * pmap_protect(), could clear a modification in the
4898 * pmap and set the dirty field on the page before
4899 * pmap_clear_modify() had begun and after the dirty
4900 * field was cleared here.
4902 pmap_clear_modify(m);
4904 vm_page_aflag_clear(m, PGA_NOSYNC);
4905 } else if (oldvalid != VM_PAGE_BITS_ALL && vm_page_xbusied(m))
4906 m->dirty &= ~pagebits;
4908 vm_page_clear_dirty_mask(m, pagebits);
4912 vm_page_clear_dirty(vm_page_t m, int base, int size)
4915 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
4919 * vm_page_set_invalid:
4921 * Invalidates DEV_BSIZE'd chunks within a page. Both the
4922 * valid and dirty bits for the effected areas are cleared.
4925 vm_page_set_invalid(vm_page_t m, int base, int size)
4927 vm_page_bits_t bits;
4931 * The object lock is required so that pages can't be mapped
4932 * read-only while we're in the process of invalidating them.
4935 VM_OBJECT_ASSERT_WLOCKED(object);
4936 vm_page_assert_busied(m);
4938 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
4939 size >= object->un_pager.vnp.vnp_size)
4940 bits = VM_PAGE_BITS_ALL;
4942 bits = vm_page_bits(base, size);
4943 if (object->ref_count != 0 && vm_page_all_valid(m) && bits != 0)
4945 KASSERT((bits == 0 && vm_page_all_valid(m)) ||
4946 !pmap_page_is_mapped(m),
4947 ("vm_page_set_invalid: page %p is mapped", m));
4948 if (vm_page_xbusied(m)) {
4952 vm_page_bits_clear(m, &m->valid, bits);
4953 vm_page_bits_clear(m, &m->dirty, bits);
4960 * Invalidates the entire page. The page must be busy, unmapped, and
4961 * the enclosing object must be locked. The object locks protects
4962 * against concurrent read-only pmap enter which is done without
4966 vm_page_invalid(vm_page_t m)
4969 vm_page_assert_busied(m);
4970 VM_OBJECT_ASSERT_LOCKED(m->object);
4971 MPASS(!pmap_page_is_mapped(m));
4973 if (vm_page_xbusied(m))
4976 vm_page_bits_clear(m, &m->valid, VM_PAGE_BITS_ALL);
4980 * vm_page_zero_invalid()
4982 * The kernel assumes that the invalid portions of a page contain
4983 * garbage, but such pages can be mapped into memory by user code.
4984 * When this occurs, we must zero out the non-valid portions of the
4985 * page so user code sees what it expects.
4987 * Pages are most often semi-valid when the end of a file is mapped
4988 * into memory and the file's size is not page aligned.
4991 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
4997 * Scan the valid bits looking for invalid sections that
4998 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
4999 * valid bit may be set ) have already been zeroed by
5000 * vm_page_set_validclean().
5002 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
5003 if (i == (PAGE_SIZE / DEV_BSIZE) ||
5004 (m->valid & ((vm_page_bits_t)1 << i))) {
5006 pmap_zero_page_area(m,
5007 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
5014 * setvalid is TRUE when we can safely set the zero'd areas
5015 * as being valid. We can do this if there are no cache consistancy
5016 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
5025 * Is (partial) page valid? Note that the case where size == 0
5026 * will return FALSE in the degenerate case where the page is
5027 * entirely invalid, and TRUE otherwise.
5029 * Some callers envoke this routine without the busy lock held and
5030 * handle races via higher level locks. Typical callers should
5031 * hold a busy lock to prevent invalidation.
5034 vm_page_is_valid(vm_page_t m, int base, int size)
5036 vm_page_bits_t bits;
5038 bits = vm_page_bits(base, size);
5039 return (m->valid != 0 && (m->valid & bits) == bits);
5043 * Returns true if all of the specified predicates are true for the entire
5044 * (super)page and false otherwise.
5047 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
5053 if (skip_m != NULL && skip_m->object != object)
5055 VM_OBJECT_ASSERT_LOCKED(object);
5056 npages = atop(pagesizes[m->psind]);
5059 * The physically contiguous pages that make up a superpage, i.e., a
5060 * page with a page size index ("psind") greater than zero, will
5061 * occupy adjacent entries in vm_page_array[].
5063 for (i = 0; i < npages; i++) {
5064 /* Always test object consistency, including "skip_m". */
5065 if (m[i].object != object)
5067 if (&m[i] == skip_m)
5069 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
5071 if ((flags & PS_ALL_DIRTY) != 0) {
5073 * Calling vm_page_test_dirty() or pmap_is_modified()
5074 * might stop this case from spuriously returning
5075 * "false". However, that would require a write lock
5076 * on the object containing "m[i]".
5078 if (m[i].dirty != VM_PAGE_BITS_ALL)
5081 if ((flags & PS_ALL_VALID) != 0 &&
5082 m[i].valid != VM_PAGE_BITS_ALL)
5089 * Set the page's dirty bits if the page is modified.
5092 vm_page_test_dirty(vm_page_t m)
5095 vm_page_assert_busied(m);
5096 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
5101 vm_page_valid(vm_page_t m)
5104 vm_page_assert_busied(m);
5105 if (vm_page_xbusied(m))
5106 m->valid = VM_PAGE_BITS_ALL;
5108 vm_page_bits_set(m, &m->valid, VM_PAGE_BITS_ALL);
5112 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
5115 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
5119 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
5122 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
5126 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
5129 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
5132 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
5134 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
5137 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
5141 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
5144 mtx_assert_(vm_page_lockptr(m), a, file, line);
5150 vm_page_object_busy_assert(vm_page_t m)
5154 * Certain of the page's fields may only be modified by the
5155 * holder of a page or object busy.
5157 if (m->object != NULL && !vm_page_busied(m))
5158 VM_OBJECT_ASSERT_BUSY(m->object);
5162 vm_page_assert_pga_writeable(vm_page_t m, uint16_t bits)
5165 if ((bits & PGA_WRITEABLE) == 0)
5169 * The PGA_WRITEABLE flag can only be set if the page is
5170 * managed, is exclusively busied or the object is locked.
5171 * Currently, this flag is only set by pmap_enter().
5173 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5174 ("PGA_WRITEABLE on unmanaged page"));
5175 if (!vm_page_xbusied(m))
5176 VM_OBJECT_ASSERT_BUSY(m->object);
5180 #include "opt_ddb.h"
5182 #include <sys/kernel.h>
5184 #include <ddb/ddb.h>
5186 DB_SHOW_COMMAND(page, vm_page_print_page_info)
5189 db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
5190 db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
5191 db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
5192 db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
5193 db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
5194 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
5195 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
5196 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
5197 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
5200 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
5204 db_printf("pq_free %d\n", vm_free_count());
5205 for (dom = 0; dom < vm_ndomains; dom++) {
5207 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
5209 vm_dom[dom].vmd_page_count,
5210 vm_dom[dom].vmd_free_count,
5211 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
5212 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
5213 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
5214 vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
5218 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
5221 boolean_t phys, virt;
5224 db_printf("show pginfo addr\n");
5228 phys = strchr(modif, 'p') != NULL;
5229 virt = strchr(modif, 'v') != NULL;
5231 m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
5233 m = PHYS_TO_VM_PAGE(addr);
5235 m = (vm_page_t)addr;
5237 "page %p obj %p pidx 0x%jx phys 0x%jx q %d ref %u\n"
5238 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
5239 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
5240 m->a.queue, m->ref_count, m->a.flags, m->oflags,
5241 m->flags, m->a.act_count, m->busy_lock, m->valid, m->dirty);