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 queue_ops = EARLY_COUNTER;
138 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, queue_ops,
139 CTLFLAG_RD, &queue_ops,
140 "Number of batched queue operations");
142 static counter_u64_t queue_nops = EARLY_COUNTER;
143 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, queue_nops,
144 CTLFLAG_RD, &queue_nops,
145 "Number of batched queue operations with no effects");
148 counter_startup(void)
151 queue_ops = counter_u64_alloc(M_WAITOK);
152 queue_nops = counter_u64_alloc(M_WAITOK);
154 SYSINIT(page_counters, SI_SUB_CPU, SI_ORDER_ANY, counter_startup, NULL);
157 * bogus page -- for I/O to/from partially complete buffers,
158 * or for paging into sparsely invalid regions.
160 vm_page_t bogus_page;
162 vm_page_t vm_page_array;
163 long vm_page_array_size;
166 static int boot_pages;
167 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
169 "number of pages allocated for bootstrapping the VM system");
171 static TAILQ_HEAD(, vm_page) blacklist_head;
172 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
173 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
174 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
176 static uma_zone_t fakepg_zone;
178 static void vm_page_alloc_check(vm_page_t m);
179 static void _vm_page_busy_sleep(vm_object_t obj, vm_page_t m,
180 const char *wmesg, bool nonshared, bool locked);
181 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
182 static void vm_page_dequeue_complete(vm_page_t m);
183 static void vm_page_enqueue(vm_page_t m, uint8_t queue);
184 static void vm_page_init(void *dummy);
185 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
186 vm_pindex_t pindex, vm_page_t mpred);
187 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
189 static void vm_page_mvqueue(vm_page_t m, uint8_t queue);
190 static int vm_page_reclaim_run(int req_class, int domain, u_long npages,
191 vm_page_t m_run, vm_paddr_t high);
192 static int vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object,
194 static int vm_page_zone_import(void *arg, void **store, int cnt, int domain,
196 static void vm_page_zone_release(void *arg, void **store, int cnt);
198 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
201 vm_page_init(void *dummy)
204 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
205 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
206 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
207 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
211 * The cache page zone is initialized later since we need to be able to allocate
212 * pages before UMA is fully initialized.
215 vm_page_init_cache_zones(void *dummy __unused)
217 struct vm_domain *vmd;
218 struct vm_pgcache *pgcache;
219 int cache, domain, maxcache, pool;
222 TUNABLE_INT_FETCH("vm.pgcache_zone_max", &maxcache);
223 for (domain = 0; domain < vm_ndomains; domain++) {
224 vmd = VM_DOMAIN(domain);
225 for (pool = 0; pool < VM_NFREEPOOL; pool++) {
226 pgcache = &vmd->vmd_pgcache[pool];
227 pgcache->domain = domain;
228 pgcache->pool = pool;
229 pgcache->zone = uma_zcache_create("vm pgcache",
230 PAGE_SIZE, NULL, NULL, NULL, NULL,
231 vm_page_zone_import, vm_page_zone_release, pgcache,
235 * Limit each pool's zone to 0.1% of the pages in the
238 cache = maxcache != 0 ? maxcache :
239 vmd->vmd_page_count / 1000;
240 uma_zone_set_maxcache(pgcache->zone, cache);
244 SYSINIT(vm_page2, SI_SUB_VM_CONF, SI_ORDER_ANY, vm_page_init_cache_zones, NULL);
246 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
247 #if PAGE_SIZE == 32768
249 CTASSERT(sizeof(u_long) >= 8);
256 * Sets the page size, perhaps based upon the memory
257 * size. Must be called before any use of page-size
258 * dependent functions.
261 vm_set_page_size(void)
263 if (vm_cnt.v_page_size == 0)
264 vm_cnt.v_page_size = PAGE_SIZE;
265 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
266 panic("vm_set_page_size: page size not a power of two");
270 * vm_page_blacklist_next:
272 * Find the next entry in the provided string of blacklist
273 * addresses. Entries are separated by space, comma, or newline.
274 * If an invalid integer is encountered then the rest of the
275 * string is skipped. Updates the list pointer to the next
276 * character, or NULL if the string is exhausted or invalid.
279 vm_page_blacklist_next(char **list, char *end)
284 if (list == NULL || *list == NULL)
292 * If there's no end pointer then the buffer is coming from
293 * the kenv and we know it's null-terminated.
296 end = *list + strlen(*list);
298 /* Ensure that strtoq() won't walk off the end */
300 if (*end == '\n' || *end == ' ' || *end == ',')
303 printf("Blacklist not terminated, skipping\n");
309 for (pos = *list; *pos != '\0'; pos = cp) {
310 bad = strtoq(pos, &cp, 0);
311 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
320 if (*cp == '\0' || ++cp >= end)
324 return (trunc_page(bad));
326 printf("Garbage in RAM blacklist, skipping\n");
332 vm_page_blacklist_add(vm_paddr_t pa, bool verbose)
334 struct vm_domain *vmd;
338 m = vm_phys_paddr_to_vm_page(pa);
340 return (true); /* page does not exist, no failure */
342 vmd = vm_pagequeue_domain(m);
343 vm_domain_free_lock(vmd);
344 ret = vm_phys_unfree_page(m);
345 vm_domain_free_unlock(vmd);
347 vm_domain_freecnt_inc(vmd, -1);
348 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
350 printf("Skipping page with pa 0x%jx\n", (uintmax_t)pa);
356 * vm_page_blacklist_check:
358 * Iterate through the provided string of blacklist addresses, pulling
359 * each entry out of the physical allocator free list and putting it
360 * onto a list for reporting via the vm.page_blacklist sysctl.
363 vm_page_blacklist_check(char *list, char *end)
369 while (next != NULL) {
370 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
372 vm_page_blacklist_add(pa, bootverbose);
377 * vm_page_blacklist_load:
379 * Search for a special module named "ram_blacklist". It'll be a
380 * plain text file provided by the user via the loader directive
384 vm_page_blacklist_load(char **list, char **end)
393 mod = preload_search_by_type("ram_blacklist");
395 ptr = preload_fetch_addr(mod);
396 len = preload_fetch_size(mod);
407 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
414 error = sysctl_wire_old_buffer(req, 0);
417 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
418 TAILQ_FOREACH(m, &blacklist_head, listq) {
419 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
420 (uintmax_t)m->phys_addr);
423 error = sbuf_finish(&sbuf);
429 * Initialize a dummy page for use in scans of the specified paging queue.
430 * In principle, this function only needs to set the flag PG_MARKER.
431 * Nonetheless, it write busies the page as a safety precaution.
434 vm_page_init_marker(vm_page_t marker, int queue, uint16_t aflags)
437 bzero(marker, sizeof(*marker));
438 marker->flags = PG_MARKER;
439 marker->aflags = aflags;
440 marker->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
441 marker->queue = queue;
445 vm_page_domain_init(int domain)
447 struct vm_domain *vmd;
448 struct vm_pagequeue *pq;
451 vmd = VM_DOMAIN(domain);
452 bzero(vmd, sizeof(*vmd));
453 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
454 "vm inactive pagequeue";
455 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
456 "vm active pagequeue";
457 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
458 "vm laundry pagequeue";
459 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_name) =
460 "vm unswappable pagequeue";
461 vmd->vmd_domain = domain;
462 vmd->vmd_page_count = 0;
463 vmd->vmd_free_count = 0;
465 vmd->vmd_oom = FALSE;
466 for (i = 0; i < PQ_COUNT; i++) {
467 pq = &vmd->vmd_pagequeues[i];
468 TAILQ_INIT(&pq->pq_pl);
469 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
470 MTX_DEF | MTX_DUPOK);
472 vm_page_init_marker(&vmd->vmd_markers[i], i, 0);
474 mtx_init(&vmd->vmd_free_mtx, "vm page free queue", NULL, MTX_DEF);
475 mtx_init(&vmd->vmd_pageout_mtx, "vm pageout lock", NULL, MTX_DEF);
476 snprintf(vmd->vmd_name, sizeof(vmd->vmd_name), "%d", domain);
479 * inacthead is used to provide FIFO ordering for LRU-bypassing
482 vm_page_init_marker(&vmd->vmd_inacthead, PQ_INACTIVE, PGA_ENQUEUED);
483 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_INACTIVE].pq_pl,
484 &vmd->vmd_inacthead, plinks.q);
487 * The clock pages are used to implement active queue scanning without
488 * requeues. Scans start at clock[0], which is advanced after the scan
489 * ends. When the two clock hands meet, they are reset and scanning
490 * resumes from the head of the queue.
492 vm_page_init_marker(&vmd->vmd_clock[0], PQ_ACTIVE, PGA_ENQUEUED);
493 vm_page_init_marker(&vmd->vmd_clock[1], PQ_ACTIVE, PGA_ENQUEUED);
494 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
495 &vmd->vmd_clock[0], plinks.q);
496 TAILQ_INSERT_TAIL(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
497 &vmd->vmd_clock[1], plinks.q);
501 * Initialize a physical page in preparation for adding it to the free
505 vm_page_init_page(vm_page_t m, vm_paddr_t pa, int segind)
510 m->busy_lock = VPB_UNBUSIED;
511 m->flags = m->aflags = 0;
516 m->order = VM_NFREEORDER;
517 m->pool = VM_FREEPOOL_DEFAULT;
518 m->valid = m->dirty = 0;
522 #ifndef PMAP_HAS_PAGE_ARRAY
524 vm_page_array_alloc(vm_offset_t *vaddr, vm_paddr_t end, vm_paddr_t page_range)
529 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
530 * However, because this page is allocated from KVM, out-of-bounds
531 * accesses using the direct map will not be trapped.
536 * Allocate physical memory for the page structures, and map it.
538 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
539 vm_page_array = (vm_page_t)pmap_map(vaddr, new_end, end,
540 VM_PROT_READ | VM_PROT_WRITE);
541 vm_page_array_size = page_range;
550 * Initializes the resident memory module. Allocates physical memory for
551 * bootstrapping UMA and some data structures that are used to manage
552 * physical pages. Initializes these structures, and populates the free
556 vm_page_startup(vm_offset_t vaddr)
558 struct vm_phys_seg *seg;
560 char *list, *listend;
562 vm_paddr_t end, high_avail, low_avail, new_end, page_range, size;
563 vm_paddr_t last_pa, pa;
565 int biggestone, i, segind;
569 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
573 vaddr = round_page(vaddr);
575 vm_phys_early_startup();
576 biggestone = vm_phys_avail_largest();
577 end = phys_avail[biggestone+1];
580 * Initialize the page and queue locks.
582 mtx_init(&vm_domainset_lock, "vm domainset lock", NULL, MTX_DEF);
583 for (i = 0; i < PA_LOCK_COUNT; i++)
584 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
585 for (i = 0; i < vm_ndomains; i++)
586 vm_page_domain_init(i);
589 * Allocate memory for use when boot strapping the kernel memory
590 * allocator. Tell UMA how many zones we are going to create
591 * before going fully functional. UMA will add its zones.
593 * VM startup zones: vmem, vmem_btag, VM OBJECT, RADIX NODE, MAP,
594 * KMAP ENTRY, MAP ENTRY, VMSPACE.
596 boot_pages = uma_startup_count(8);
598 #ifndef UMA_MD_SMALL_ALLOC
599 /* vmem_startup() calls uma_prealloc(). */
600 boot_pages += vmem_startup_count();
601 /* vm_map_startup() calls uma_prealloc(). */
602 boot_pages += howmany(MAX_KMAP,
603 UMA_SLAB_SPACE / sizeof(struct vm_map));
606 * Before going fully functional kmem_init() does allocation
607 * from "KMAP ENTRY" and vmem_create() does allocation from "vmem".
612 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
613 * manually fetch the value.
615 TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
616 new_end = end - (boot_pages * UMA_SLAB_SIZE);
617 new_end = trunc_page(new_end);
618 mapped = pmap_map(&vaddr, new_end, end,
619 VM_PROT_READ | VM_PROT_WRITE);
620 bzero((void *)mapped, end - new_end);
621 uma_startup((void *)mapped, boot_pages);
624 witness_size = round_page(witness_startup_count());
625 new_end -= witness_size;
626 mapped = pmap_map(&vaddr, new_end, new_end + witness_size,
627 VM_PROT_READ | VM_PROT_WRITE);
628 bzero((void *)mapped, witness_size);
629 witness_startup((void *)mapped);
632 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
633 defined(__i386__) || defined(__mips__) || defined(__riscv) || \
634 defined(__powerpc64__)
636 * Allocate a bitmap to indicate that a random physical page
637 * needs to be included in a minidump.
639 * The amd64 port needs this to indicate which direct map pages
640 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
642 * However, i386 still needs this workspace internally within the
643 * minidump code. In theory, they are not needed on i386, but are
644 * included should the sf_buf code decide to use them.
647 for (i = 0; dump_avail[i + 1] != 0; i += 2)
648 if (dump_avail[i + 1] > last_pa)
649 last_pa = dump_avail[i + 1];
650 page_range = last_pa / PAGE_SIZE;
651 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
652 new_end -= vm_page_dump_size;
653 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
654 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
655 bzero((void *)vm_page_dump, vm_page_dump_size);
659 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
660 defined(__riscv) || defined(__powerpc64__)
662 * Include the UMA bootstrap pages, witness pages and vm_page_dump
663 * in a crash dump. When pmap_map() uses the direct map, they are
664 * not automatically included.
666 for (pa = new_end; pa < end; pa += PAGE_SIZE)
669 phys_avail[biggestone + 1] = new_end;
672 * Request that the physical pages underlying the message buffer be
673 * included in a crash dump. Since the message buffer is accessed
674 * through the direct map, they are not automatically included.
676 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
677 last_pa = pa + round_page(msgbufsize);
678 while (pa < last_pa) {
684 * Compute the number of pages of memory that will be available for
685 * use, taking into account the overhead of a page structure per page.
686 * In other words, solve
687 * "available physical memory" - round_page(page_range *
688 * sizeof(struct vm_page)) = page_range * PAGE_SIZE
691 low_avail = phys_avail[0];
692 high_avail = phys_avail[1];
693 for (i = 0; i < vm_phys_nsegs; i++) {
694 if (vm_phys_segs[i].start < low_avail)
695 low_avail = vm_phys_segs[i].start;
696 if (vm_phys_segs[i].end > high_avail)
697 high_avail = vm_phys_segs[i].end;
699 /* Skip the first chunk. It is already accounted for. */
700 for (i = 2; phys_avail[i + 1] != 0; i += 2) {
701 if (phys_avail[i] < low_avail)
702 low_avail = phys_avail[i];
703 if (phys_avail[i + 1] > high_avail)
704 high_avail = phys_avail[i + 1];
706 first_page = low_avail / PAGE_SIZE;
707 #ifdef VM_PHYSSEG_SPARSE
709 for (i = 0; i < vm_phys_nsegs; i++)
710 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
711 for (i = 0; phys_avail[i + 1] != 0; i += 2)
712 size += phys_avail[i + 1] - phys_avail[i];
713 #elif defined(VM_PHYSSEG_DENSE)
714 size = high_avail - low_avail;
716 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
719 #ifdef PMAP_HAS_PAGE_ARRAY
720 pmap_page_array_startup(size / PAGE_SIZE);
721 biggestone = vm_phys_avail_largest();
722 end = new_end = phys_avail[biggestone + 1];
724 #ifdef VM_PHYSSEG_DENSE
726 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
727 * the overhead of a page structure per page only if vm_page_array is
728 * allocated from the last physical memory chunk. Otherwise, we must
729 * allocate page structures representing the physical memory
730 * underlying vm_page_array, even though they will not be used.
732 if (new_end != high_avail)
733 page_range = size / PAGE_SIZE;
737 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
740 * If the partial bytes remaining are large enough for
741 * a page (PAGE_SIZE) without a corresponding
742 * 'struct vm_page', then new_end will contain an
743 * extra page after subtracting the length of the VM
744 * page array. Compensate by subtracting an extra
747 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
748 if (new_end == high_avail)
749 high_avail -= PAGE_SIZE;
750 new_end -= PAGE_SIZE;
754 new_end = vm_page_array_alloc(&vaddr, end, page_range);
757 #if VM_NRESERVLEVEL > 0
759 * Allocate physical memory for the reservation management system's
760 * data structures, and map it.
762 new_end = vm_reserv_startup(&vaddr, new_end);
764 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
765 defined(__riscv) || defined(__powerpc64__)
767 * Include vm_page_array and vm_reserv_array in a crash dump.
769 for (pa = new_end; pa < end; pa += PAGE_SIZE)
772 phys_avail[biggestone + 1] = new_end;
775 * Add physical memory segments corresponding to the available
778 for (i = 0; phys_avail[i + 1] != 0; i += 2)
779 if (vm_phys_avail_size(i) != 0)
780 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
783 * Initialize the physical memory allocator.
788 * Initialize the page structures and add every available page to the
789 * physical memory allocator's free lists.
791 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
792 for (ii = 0; ii < vm_page_array_size; ii++) {
793 m = &vm_page_array[ii];
794 vm_page_init_page(m, (first_page + ii) << PAGE_SHIFT, 0);
795 m->flags = PG_FICTITIOUS;
798 vm_cnt.v_page_count = 0;
799 for (segind = 0; segind < vm_phys_nsegs; segind++) {
800 seg = &vm_phys_segs[segind];
801 for (m = seg->first_page, pa = seg->start; pa < seg->end;
802 m++, pa += PAGE_SIZE)
803 vm_page_init_page(m, pa, segind);
806 * Add the segment to the free lists only if it is covered by
807 * one of the ranges in phys_avail. Because we've added the
808 * ranges to the vm_phys_segs array, we can assume that each
809 * segment is either entirely contained in one of the ranges,
810 * or doesn't overlap any of them.
812 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
813 struct vm_domain *vmd;
815 if (seg->start < phys_avail[i] ||
816 seg->end > phys_avail[i + 1])
820 pagecount = (u_long)atop(seg->end - seg->start);
822 vmd = VM_DOMAIN(seg->domain);
823 vm_domain_free_lock(vmd);
824 vm_phys_enqueue_contig(m, pagecount);
825 vm_domain_free_unlock(vmd);
826 vm_domain_freecnt_inc(vmd, pagecount);
827 vm_cnt.v_page_count += (u_int)pagecount;
829 vmd = VM_DOMAIN(seg->domain);
830 vmd->vmd_page_count += (u_int)pagecount;
831 vmd->vmd_segs |= 1UL << m->segind;
837 * Remove blacklisted pages from the physical memory allocator.
839 TAILQ_INIT(&blacklist_head);
840 vm_page_blacklist_load(&list, &listend);
841 vm_page_blacklist_check(list, listend);
843 list = kern_getenv("vm.blacklist");
844 vm_page_blacklist_check(list, NULL);
847 #if VM_NRESERVLEVEL > 0
849 * Initialize the reservation management system.
858 vm_page_reference(vm_page_t m)
861 vm_page_aflag_set(m, PGA_REFERENCED);
865 * vm_page_busy_acquire:
867 * Acquire the busy lock as described by VM_ALLOC_* flags. Will loop
868 * and drop the object lock if necessary.
871 vm_page_busy_acquire(vm_page_t m, int allocflags)
877 * The page-specific object must be cached because page
878 * identity can change during the sleep, causing the
879 * re-lock of a different object.
880 * It is assumed that a reference to the object is already
881 * held by the callers.
885 if ((allocflags & VM_ALLOC_SBUSY) == 0) {
886 if (vm_page_tryxbusy(m))
889 if (vm_page_trysbusy(m))
892 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
895 locked = VM_OBJECT_WOWNED(obj);
898 MPASS(locked || vm_page_wired(m));
899 _vm_page_busy_sleep(obj, m, "vmpba",
900 (allocflags & VM_ALLOC_SBUSY) != 0, locked);
902 VM_OBJECT_WLOCK(obj);
903 if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
905 KASSERT(m->object == obj || m->object == NULL,
906 ("vm_page_busy_acquire: page %p does not belong to %p",
912 * vm_page_busy_downgrade:
914 * Downgrade an exclusive busy page into a single shared busy page.
917 vm_page_busy_downgrade(vm_page_t m)
921 vm_page_assert_xbusied(m);
925 if (atomic_fcmpset_rel_int(&m->busy_lock,
926 &x, VPB_SHARERS_WORD(1)))
929 if ((x & VPB_BIT_WAITERS) != 0)
935 * vm_page_busy_tryupgrade:
937 * Attempt to upgrade a single shared busy into an exclusive busy.
940 vm_page_busy_tryupgrade(vm_page_t m)
944 vm_page_assert_sbusied(m);
947 ce = VPB_CURTHREAD_EXCLUSIVE;
949 if (VPB_SHARERS(x) > 1)
951 KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
952 ("vm_page_busy_tryupgrade: invalid lock state"));
953 if (!atomic_fcmpset_acq_int(&m->busy_lock, &x,
954 ce | (x & VPB_BIT_WAITERS)))
963 * Return a positive value if the page is shared busied, 0 otherwise.
966 vm_page_sbusied(vm_page_t m)
971 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
977 * Shared unbusy a page.
980 vm_page_sunbusy(vm_page_t m)
984 vm_page_assert_sbusied(m);
988 if (VPB_SHARERS(x) > 1) {
989 if (atomic_fcmpset_int(&m->busy_lock, &x,
994 KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
995 ("vm_page_sunbusy: invalid lock state"));
996 if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
998 if ((x & VPB_BIT_WAITERS) == 0)
1006 * vm_page_busy_sleep:
1008 * Sleep if the page is busy, using the page pointer as wchan.
1009 * This is used to implement the hard-path of busying mechanism.
1011 * If nonshared is true, sleep only if the page is xbusy.
1013 * The object lock must be held on entry and will be released on exit.
1016 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
1021 VM_OBJECT_ASSERT_LOCKED(obj);
1022 vm_page_lock_assert(m, MA_NOTOWNED);
1024 _vm_page_busy_sleep(obj, m, wmesg, nonshared, true);
1028 _vm_page_busy_sleep(vm_object_t obj, vm_page_t m, const char *wmesg,
1029 bool nonshared, bool locked)
1034 * If the object is busy we must wait for that to drain to zero
1035 * before trying the page again.
1037 if (obj != NULL && vm_object_busied(obj)) {
1039 VM_OBJECT_DROP(obj);
1040 vm_object_busy_wait(obj, wmesg);
1045 if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
1046 ((x & VPB_BIT_WAITERS) == 0 &&
1047 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
1049 VM_OBJECT_DROP(obj);
1054 VM_OBJECT_DROP(obj);
1056 sleepq_add(m, NULL, wmesg, 0, 0);
1057 sleepq_wait(m, PVM);
1064 * Try to shared busy a page.
1065 * If the operation succeeds 1 is returned otherwise 0.
1066 * The operation never sleeps.
1069 vm_page_trysbusy(vm_page_t m)
1077 if ((x & VPB_BIT_SHARED) == 0)
1080 * Reduce the window for transient busies that will trigger
1081 * false negatives in vm_page_ps_test().
1083 if (obj != NULL && vm_object_busied(obj))
1085 if (atomic_fcmpset_acq_int(&m->busy_lock, &x,
1086 x + VPB_ONE_SHARER))
1090 /* Refetch the object now that we're guaranteed that it is stable. */
1092 if (obj != NULL && vm_object_busied(obj)) {
1102 * Try to exclusive busy a page.
1103 * If the operation succeeds 1 is returned otherwise 0.
1104 * The operation never sleeps.
1107 vm_page_tryxbusy(vm_page_t m)
1111 if (atomic_cmpset_acq_int(&(m)->busy_lock, VPB_UNBUSIED,
1112 VPB_CURTHREAD_EXCLUSIVE) == 0)
1116 if (obj != NULL && vm_object_busied(obj)) {
1124 vm_page_xunbusy_hard_tail(vm_page_t m)
1126 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1127 /* Wake the waiter. */
1132 * vm_page_xunbusy_hard:
1134 * Called when unbusy has failed because there is a waiter.
1137 vm_page_xunbusy_hard(vm_page_t m)
1139 vm_page_assert_xbusied(m);
1140 vm_page_xunbusy_hard_tail(m);
1144 vm_page_xunbusy_hard_unchecked(vm_page_t m)
1146 vm_page_assert_xbusied_unchecked(m);
1147 vm_page_xunbusy_hard_tail(m);
1151 * Avoid releasing and reacquiring the same page lock.
1154 vm_page_change_lock(vm_page_t m, struct mtx **mtx)
1158 mtx1 = vm_page_lockptr(m);
1168 * vm_page_unhold_pages:
1170 * Unhold each of the pages that is referenced by the given array.
1173 vm_page_unhold_pages(vm_page_t *ma, int count)
1176 for (; count != 0; count--) {
1177 vm_page_unwire(*ma, PQ_ACTIVE);
1183 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1187 #ifdef VM_PHYSSEG_SPARSE
1188 m = vm_phys_paddr_to_vm_page(pa);
1190 m = vm_phys_fictitious_to_vm_page(pa);
1192 #elif defined(VM_PHYSSEG_DENSE)
1196 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1197 m = &vm_page_array[pi - first_page];
1200 return (vm_phys_fictitious_to_vm_page(pa));
1202 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1209 * Create a fictitious page with the specified physical address and
1210 * memory attribute. The memory attribute is the only the machine-
1211 * dependent aspect of a fictitious page that must be initialized.
1214 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1218 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1219 vm_page_initfake(m, paddr, memattr);
1224 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1227 if ((m->flags & PG_FICTITIOUS) != 0) {
1229 * The page's memattr might have changed since the
1230 * previous initialization. Update the pmap to the
1235 m->phys_addr = paddr;
1237 /* Fictitious pages don't use "segind". */
1238 m->flags = PG_FICTITIOUS;
1239 /* Fictitious pages don't use "order" or "pool". */
1240 m->oflags = VPO_UNMANAGED;
1241 m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
1242 /* Fictitious pages are unevictable. */
1246 pmap_page_set_memattr(m, memattr);
1252 * Release a fictitious page.
1255 vm_page_putfake(vm_page_t m)
1258 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1259 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1260 ("vm_page_putfake: bad page %p", m));
1261 if (vm_page_xbusied(m))
1263 uma_zfree(fakepg_zone, m);
1267 * vm_page_updatefake:
1269 * Update the given fictitious page to the specified physical address and
1273 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1276 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1277 ("vm_page_updatefake: bad page %p", m));
1278 m->phys_addr = paddr;
1279 pmap_page_set_memattr(m, memattr);
1288 vm_page_free(vm_page_t m)
1291 m->flags &= ~PG_ZERO;
1292 vm_page_free_toq(m);
1296 * vm_page_free_zero:
1298 * Free a page to the zerod-pages queue
1301 vm_page_free_zero(vm_page_t m)
1304 m->flags |= PG_ZERO;
1305 vm_page_free_toq(m);
1309 * Unbusy and handle the page queueing for a page from a getpages request that
1310 * was optionally read ahead or behind.
1313 vm_page_readahead_finish(vm_page_t m)
1316 /* We shouldn't put invalid pages on queues. */
1317 KASSERT(!vm_page_none_valid(m), ("%s: %p is invalid", __func__, m));
1320 * Since the page is not the actually needed one, whether it should
1321 * be activated or deactivated is not obvious. Empirical results
1322 * have shown that deactivating the page is usually the best choice,
1323 * unless the page is wanted by another thread.
1326 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1327 vm_page_activate(m);
1329 vm_page_deactivate(m);
1331 vm_page_xunbusy_unchecked(m);
1335 * vm_page_sleep_if_busy:
1337 * Sleep and release the object lock if the page is busied.
1338 * Returns TRUE if the thread slept.
1340 * The given page must be unlocked and object containing it must
1344 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1348 vm_page_lock_assert(m, MA_NOTOWNED);
1349 VM_OBJECT_ASSERT_WLOCKED(m->object);
1352 * The page-specific object must be cached because page
1353 * identity can change during the sleep, causing the
1354 * re-lock of a different object.
1355 * It is assumed that a reference to the object is already
1356 * held by the callers.
1359 if (vm_page_busied(m) || (obj != NULL && obj->busy)) {
1360 vm_page_busy_sleep(m, msg, false);
1361 VM_OBJECT_WLOCK(obj);
1368 * vm_page_sleep_if_xbusy:
1370 * Sleep and release the object lock if the page is xbusied.
1371 * Returns TRUE if the thread slept.
1373 * The given page must be unlocked and object containing it must
1377 vm_page_sleep_if_xbusy(vm_page_t m, const char *msg)
1381 vm_page_lock_assert(m, MA_NOTOWNED);
1382 VM_OBJECT_ASSERT_WLOCKED(m->object);
1385 * The page-specific object must be cached because page
1386 * identity can change during the sleep, causing the
1387 * re-lock of a different object.
1388 * It is assumed that a reference to the object is already
1389 * held by the callers.
1392 if (vm_page_xbusied(m) || (obj != NULL && obj->busy)) {
1393 vm_page_busy_sleep(m, msg, true);
1394 VM_OBJECT_WLOCK(obj);
1401 * vm_page_dirty_KBI: [ internal use only ]
1403 * Set all bits in the page's dirty field.
1405 * The object containing the specified page must be locked if the
1406 * call is made from the machine-independent layer.
1408 * See vm_page_clear_dirty_mask().
1410 * This function should only be called by vm_page_dirty().
1413 vm_page_dirty_KBI(vm_page_t m)
1416 /* Refer to this operation by its public name. */
1417 KASSERT(vm_page_all_valid(m), ("vm_page_dirty: page is invalid!"));
1418 m->dirty = VM_PAGE_BITS_ALL;
1422 * vm_page_insert: [ internal use only ]
1424 * Inserts the given mem entry into the object and object list.
1426 * The object must be locked.
1429 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1433 VM_OBJECT_ASSERT_WLOCKED(object);
1434 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1435 return (vm_page_insert_after(m, object, pindex, mpred));
1439 * vm_page_insert_after:
1441 * Inserts the page "m" into the specified object at offset "pindex".
1443 * The page "mpred" must immediately precede the offset "pindex" within
1444 * the specified object.
1446 * The object must be locked.
1449 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1454 VM_OBJECT_ASSERT_WLOCKED(object);
1455 KASSERT(m->object == NULL,
1456 ("vm_page_insert_after: page already inserted"));
1457 if (mpred != NULL) {
1458 KASSERT(mpred->object == object,
1459 ("vm_page_insert_after: object doesn't contain mpred"));
1460 KASSERT(mpred->pindex < pindex,
1461 ("vm_page_insert_after: mpred doesn't precede pindex"));
1462 msucc = TAILQ_NEXT(mpred, listq);
1464 msucc = TAILQ_FIRST(&object->memq);
1466 KASSERT(msucc->pindex > pindex,
1467 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1470 * Record the object/offset pair in this page.
1474 m->ref_count |= VPRC_OBJREF;
1477 * Now link into the object's ordered list of backed pages.
1479 if (vm_radix_insert(&object->rtree, m)) {
1482 m->ref_count &= ~VPRC_OBJREF;
1485 vm_page_insert_radixdone(m, object, mpred);
1490 * vm_page_insert_radixdone:
1492 * Complete page "m" insertion into the specified object after the
1493 * radix trie hooking.
1495 * The page "mpred" must precede the offset "m->pindex" within the
1498 * The object must be locked.
1501 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1504 VM_OBJECT_ASSERT_WLOCKED(object);
1505 KASSERT(object != NULL && m->object == object,
1506 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1507 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1508 ("vm_page_insert_radixdone: page %p is missing object ref", m));
1509 if (mpred != NULL) {
1510 KASSERT(mpred->object == object,
1511 ("vm_page_insert_radixdone: object doesn't contain mpred"));
1512 KASSERT(mpred->pindex < m->pindex,
1513 ("vm_page_insert_radixdone: mpred doesn't precede pindex"));
1517 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1519 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1522 * Show that the object has one more resident page.
1524 object->resident_page_count++;
1527 * Hold the vnode until the last page is released.
1529 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1530 vhold(object->handle);
1533 * Since we are inserting a new and possibly dirty page,
1534 * update the object's generation count.
1536 if (pmap_page_is_write_mapped(m))
1537 vm_object_set_writeable_dirty(object);
1541 * Do the work to remove a page from its object. The caller is responsible for
1542 * updating the page's fields to reflect this removal.
1545 vm_page_object_remove(vm_page_t m)
1551 VM_OBJECT_ASSERT_WLOCKED(object);
1552 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1553 ("page %p is missing its object ref", m));
1555 mrem = vm_radix_remove(&object->rtree, m->pindex);
1556 KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1559 * Now remove from the object's list of backed pages.
1561 TAILQ_REMOVE(&object->memq, m, listq);
1564 * And show that the object has one fewer resident page.
1566 object->resident_page_count--;
1569 * The vnode may now be recycled.
1571 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1572 vdrop(object->handle);
1578 * Removes the specified page from its containing object, but does not
1579 * invalidate any backing storage. Returns true if the object's reference
1580 * was the last reference to the page, and false otherwise.
1582 * The object must be locked.
1585 vm_page_remove(vm_page_t m)
1588 vm_page_object_remove(m);
1590 return (vm_page_drop(m, VPRC_OBJREF) == VPRC_OBJREF);
1596 * Returns the page associated with the object/offset
1597 * pair specified; if none is found, NULL is returned.
1599 * The object must be locked.
1602 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1605 VM_OBJECT_ASSERT_LOCKED(object);
1606 return (vm_radix_lookup(&object->rtree, pindex));
1610 * vm_page_find_least:
1612 * Returns the page associated with the object with least pindex
1613 * greater than or equal to the parameter pindex, or NULL.
1615 * The object must be locked.
1618 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1622 VM_OBJECT_ASSERT_LOCKED(object);
1623 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1624 m = vm_radix_lookup_ge(&object->rtree, pindex);
1629 * Returns the given page's successor (by pindex) within the object if it is
1630 * resident; if none is found, NULL is returned.
1632 * The object must be locked.
1635 vm_page_next(vm_page_t m)
1639 VM_OBJECT_ASSERT_LOCKED(m->object);
1640 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1641 MPASS(next->object == m->object);
1642 if (next->pindex != m->pindex + 1)
1649 * Returns the given page's predecessor (by pindex) within the object if it is
1650 * resident; if none is found, NULL is returned.
1652 * The object must be locked.
1655 vm_page_prev(vm_page_t m)
1659 VM_OBJECT_ASSERT_LOCKED(m->object);
1660 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1661 MPASS(prev->object == m->object);
1662 if (prev->pindex != m->pindex - 1)
1669 * Uses the page mnew as a replacement for an existing page at index
1670 * pindex which must be already present in the object.
1673 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1677 VM_OBJECT_ASSERT_WLOCKED(object);
1678 KASSERT(mnew->object == NULL && (mnew->ref_count & VPRC_OBJREF) == 0,
1679 ("vm_page_replace: page %p already in object", mnew));
1682 * This function mostly follows vm_page_insert() and
1683 * vm_page_remove() without the radix, object count and vnode
1684 * dance. Double check such functions for more comments.
1687 mnew->object = object;
1688 mnew->pindex = pindex;
1689 atomic_set_int(&mnew->ref_count, VPRC_OBJREF);
1690 mold = vm_radix_replace(&object->rtree, mnew);
1691 KASSERT(mold->queue == PQ_NONE,
1692 ("vm_page_replace: old page %p is on a paging queue", mold));
1694 /* Keep the resident page list in sorted order. */
1695 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1696 TAILQ_REMOVE(&object->memq, mold, listq);
1698 mold->object = NULL;
1699 atomic_clear_int(&mold->ref_count, VPRC_OBJREF);
1700 vm_page_xunbusy(mold);
1703 * The object's resident_page_count does not change because we have
1704 * swapped one page for another, but the generation count should
1705 * change if the page is dirty.
1707 if (pmap_page_is_write_mapped(mnew))
1708 vm_object_set_writeable_dirty(object);
1715 * Move the given memory entry from its
1716 * current object to the specified target object/offset.
1718 * Note: swap associated with the page must be invalidated by the move. We
1719 * have to do this for several reasons: (1) we aren't freeing the
1720 * page, (2) we are dirtying the page, (3) the VM system is probably
1721 * moving the page from object A to B, and will then later move
1722 * the backing store from A to B and we can't have a conflict.
1724 * Note: we *always* dirty the page. It is necessary both for the
1725 * fact that we moved it, and because we may be invalidating
1728 * The objects must be locked.
1731 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1736 VM_OBJECT_ASSERT_WLOCKED(new_object);
1738 KASSERT(m->ref_count != 0, ("vm_page_rename: page %p has no refs", m));
1739 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1740 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1741 ("vm_page_rename: pindex already renamed"));
1744 * Create a custom version of vm_page_insert() which does not depend
1745 * by m_prev and can cheat on the implementation aspects of the
1749 m->pindex = new_pindex;
1750 if (vm_radix_insert(&new_object->rtree, m)) {
1756 * The operation cannot fail anymore. The removal must happen before
1757 * the listq iterator is tainted.
1760 vm_page_object_remove(m);
1762 /* Return back to the new pindex to complete vm_page_insert(). */
1763 m->pindex = new_pindex;
1764 m->object = new_object;
1766 vm_page_insert_radixdone(m, new_object, mpred);
1774 * Allocate and return a page that is associated with the specified
1775 * object and offset pair. By default, this page is exclusive busied.
1777 * The caller must always specify an allocation class.
1779 * allocation classes:
1780 * VM_ALLOC_NORMAL normal process request
1781 * VM_ALLOC_SYSTEM system *really* needs a page
1782 * VM_ALLOC_INTERRUPT interrupt time request
1784 * optional allocation flags:
1785 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1786 * intends to allocate
1787 * VM_ALLOC_NOBUSY do not exclusive busy the page
1788 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1789 * VM_ALLOC_NOOBJ page is not associated with an object and
1790 * should not be exclusive busy
1791 * VM_ALLOC_SBUSY shared busy the allocated page
1792 * VM_ALLOC_WIRED wire the allocated page
1793 * VM_ALLOC_ZERO prefer a zeroed page
1796 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1799 return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1800 vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1804 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1808 return (vm_page_alloc_domain_after(object, pindex, domain, req,
1809 object != NULL ? vm_radix_lookup_le(&object->rtree, pindex) :
1814 * Allocate a page in the specified object with the given page index. To
1815 * optimize insertion of the page into the object, the caller must also specifiy
1816 * the resident page in the object with largest index smaller than the given
1817 * page index, or NULL if no such page exists.
1820 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1821 int req, vm_page_t mpred)
1823 struct vm_domainset_iter di;
1827 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1829 m = vm_page_alloc_domain_after(object, pindex, domain, req,
1833 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
1839 * Returns true if the number of free pages exceeds the minimum
1840 * for the request class and false otherwise.
1843 _vm_domain_allocate(struct vm_domain *vmd, int req_class, int npages)
1845 u_int limit, old, new;
1847 if (req_class == VM_ALLOC_INTERRUPT)
1849 else if (req_class == VM_ALLOC_SYSTEM)
1850 limit = vmd->vmd_interrupt_free_min;
1852 limit = vmd->vmd_free_reserved;
1855 * Attempt to reserve the pages. Fail if we're below the limit.
1858 old = vmd->vmd_free_count;
1863 } while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
1865 /* Wake the page daemon if we've crossed the threshold. */
1866 if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
1867 pagedaemon_wakeup(vmd->vmd_domain);
1869 /* Only update bitsets on transitions. */
1870 if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
1871 (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
1878 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
1883 * The page daemon is allowed to dig deeper into the free page list.
1885 req_class = req & VM_ALLOC_CLASS_MASK;
1886 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1887 req_class = VM_ALLOC_SYSTEM;
1888 return (_vm_domain_allocate(vmd, req_class, npages));
1892 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
1893 int req, vm_page_t mpred)
1895 struct vm_domain *vmd;
1899 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1900 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1901 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1902 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1903 ("inconsistent object(%p)/req(%x)", object, req));
1904 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1905 ("Can't sleep and retry object insertion."));
1906 KASSERT(mpred == NULL || mpred->pindex < pindex,
1907 ("mpred %p doesn't precede pindex 0x%jx", mpred,
1908 (uintmax_t)pindex));
1910 VM_OBJECT_ASSERT_WLOCKED(object);
1914 pool = object != NULL ? VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT;
1916 #if VM_NRESERVLEVEL > 0
1918 * Can we allocate the page from a reservation?
1920 if (vm_object_reserv(object) &&
1921 (m = vm_reserv_alloc_page(object, pindex, domain, req, mpred)) !=
1923 domain = vm_phys_domain(m);
1924 vmd = VM_DOMAIN(domain);
1928 vmd = VM_DOMAIN(domain);
1929 if (vmd->vmd_pgcache[pool].zone != NULL) {
1930 m = uma_zalloc(vmd->vmd_pgcache[pool].zone, M_NOWAIT);
1932 flags |= PG_PCPU_CACHE;
1936 if (vm_domain_allocate(vmd, req, 1)) {
1938 * If not, allocate it from the free page queues.
1940 vm_domain_free_lock(vmd);
1941 m = vm_phys_alloc_pages(domain, pool, 0);
1942 vm_domain_free_unlock(vmd);
1944 vm_domain_freecnt_inc(vmd, 1);
1945 #if VM_NRESERVLEVEL > 0
1946 if (vm_reserv_reclaim_inactive(domain))
1953 * Not allocatable, give up.
1955 if (vm_domain_alloc_fail(vmd, object, req))
1961 * At this point we had better have found a good page.
1965 vm_page_alloc_check(m);
1968 * Initialize the page. Only the PG_ZERO flag is inherited.
1970 if ((req & VM_ALLOC_ZERO) != 0)
1971 flags |= (m->flags & PG_ZERO);
1972 if ((req & VM_ALLOC_NODUMP) != 0)
1976 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1978 m->busy_lock = VPB_UNBUSIED;
1979 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1980 m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
1981 if ((req & VM_ALLOC_SBUSY) != 0)
1982 m->busy_lock = VPB_SHARERS_WORD(1);
1983 if (req & VM_ALLOC_WIRED) {
1985 * The page lock is not required for wiring a page until that
1986 * page is inserted into the object.
1993 if (object != NULL) {
1994 if (vm_page_insert_after(m, object, pindex, mpred)) {
1995 if (req & VM_ALLOC_WIRED) {
1999 KASSERT(m->object == NULL, ("page %p has object", m));
2000 m->oflags = VPO_UNMANAGED;
2001 m->busy_lock = VPB_UNBUSIED;
2002 /* Don't change PG_ZERO. */
2003 vm_page_free_toq(m);
2004 if (req & VM_ALLOC_WAITFAIL) {
2005 VM_OBJECT_WUNLOCK(object);
2007 VM_OBJECT_WLOCK(object);
2012 /* Ignore device objects; the pager sets "memattr" for them. */
2013 if (object->memattr != VM_MEMATTR_DEFAULT &&
2014 (object->flags & OBJ_FICTITIOUS) == 0)
2015 pmap_page_set_memattr(m, object->memattr);
2023 * vm_page_alloc_contig:
2025 * Allocate a contiguous set of physical pages of the given size "npages"
2026 * from the free lists. All of the physical pages must be at or above
2027 * the given physical address "low" and below the given physical address
2028 * "high". The given value "alignment" determines the alignment of the
2029 * first physical page in the set. If the given value "boundary" is
2030 * non-zero, then the set of physical pages cannot cross any physical
2031 * address boundary that is a multiple of that value. Both "alignment"
2032 * and "boundary" must be a power of two.
2034 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
2035 * then the memory attribute setting for the physical pages is configured
2036 * to the object's memory attribute setting. Otherwise, the memory
2037 * attribute setting for the physical pages is configured to "memattr",
2038 * overriding the object's memory attribute setting. However, if the
2039 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
2040 * memory attribute setting for the physical pages cannot be configured
2041 * to VM_MEMATTR_DEFAULT.
2043 * The specified object may not contain fictitious pages.
2045 * The caller must always specify an allocation class.
2047 * allocation classes:
2048 * VM_ALLOC_NORMAL normal process request
2049 * VM_ALLOC_SYSTEM system *really* needs a page
2050 * VM_ALLOC_INTERRUPT interrupt time request
2052 * optional allocation flags:
2053 * VM_ALLOC_NOBUSY do not exclusive busy the page
2054 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
2055 * VM_ALLOC_NOOBJ page is not associated with an object and
2056 * should not be exclusive busy
2057 * VM_ALLOC_SBUSY shared busy the allocated page
2058 * VM_ALLOC_WIRED wire the allocated page
2059 * VM_ALLOC_ZERO prefer a zeroed page
2062 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
2063 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2064 vm_paddr_t boundary, vm_memattr_t memattr)
2066 struct vm_domainset_iter di;
2070 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
2072 m = vm_page_alloc_contig_domain(object, pindex, domain, req,
2073 npages, low, high, alignment, boundary, memattr);
2076 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
2082 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
2083 int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2084 vm_paddr_t boundary, vm_memattr_t memattr)
2086 struct vm_domain *vmd;
2087 vm_page_t m, m_ret, mpred;
2088 u_int busy_lock, flags, oflags;
2090 mpred = NULL; /* XXX: pacify gcc */
2091 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
2092 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
2093 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2094 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2095 ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
2097 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2098 ("Can't sleep and retry object insertion."));
2099 if (object != NULL) {
2100 VM_OBJECT_ASSERT_WLOCKED(object);
2101 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2102 ("vm_page_alloc_contig: object %p has fictitious pages",
2105 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2107 if (object != NULL) {
2108 mpred = vm_radix_lookup_le(&object->rtree, pindex);
2109 KASSERT(mpred == NULL || mpred->pindex != pindex,
2110 ("vm_page_alloc_contig: pindex already allocated"));
2114 * Can we allocate the pages without the number of free pages falling
2115 * below the lower bound for the allocation class?
2119 #if VM_NRESERVLEVEL > 0
2121 * Can we allocate the pages from a reservation?
2123 if (vm_object_reserv(object) &&
2124 (m_ret = vm_reserv_alloc_contig(object, pindex, domain, req,
2125 mpred, npages, low, high, alignment, boundary)) != NULL) {
2126 domain = vm_phys_domain(m_ret);
2127 vmd = VM_DOMAIN(domain);
2131 vmd = VM_DOMAIN(domain);
2132 if (vm_domain_allocate(vmd, req, npages)) {
2134 * allocate them from the free page queues.
2136 vm_domain_free_lock(vmd);
2137 m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2138 alignment, boundary);
2139 vm_domain_free_unlock(vmd);
2140 if (m_ret == NULL) {
2141 vm_domain_freecnt_inc(vmd, npages);
2142 #if VM_NRESERVLEVEL > 0
2143 if (vm_reserv_reclaim_contig(domain, npages, low,
2144 high, alignment, boundary))
2149 if (m_ret == NULL) {
2150 if (vm_domain_alloc_fail(vmd, object, req))
2154 #if VM_NRESERVLEVEL > 0
2157 for (m = m_ret; m < &m_ret[npages]; m++) {
2159 vm_page_alloc_check(m);
2163 * Initialize the pages. Only the PG_ZERO flag is inherited.
2166 if ((req & VM_ALLOC_ZERO) != 0)
2168 if ((req & VM_ALLOC_NODUMP) != 0)
2170 oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2172 busy_lock = VPB_UNBUSIED;
2173 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2174 busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2175 if ((req & VM_ALLOC_SBUSY) != 0)
2176 busy_lock = VPB_SHARERS_WORD(1);
2177 if ((req & VM_ALLOC_WIRED) != 0)
2178 vm_wire_add(npages);
2179 if (object != NULL) {
2180 if (object->memattr != VM_MEMATTR_DEFAULT &&
2181 memattr == VM_MEMATTR_DEFAULT)
2182 memattr = object->memattr;
2184 for (m = m_ret; m < &m_ret[npages]; m++) {
2186 m->flags = (m->flags | PG_NODUMP) & flags;
2187 m->busy_lock = busy_lock;
2188 if ((req & VM_ALLOC_WIRED) != 0)
2192 if (object != NULL) {
2193 if (vm_page_insert_after(m, object, pindex, mpred)) {
2194 if ((req & VM_ALLOC_WIRED) != 0)
2195 vm_wire_sub(npages);
2196 KASSERT(m->object == NULL,
2197 ("page %p has object", m));
2199 for (m = m_ret; m < &m_ret[npages]; m++) {
2201 (req & VM_ALLOC_WIRED) != 0)
2203 m->oflags = VPO_UNMANAGED;
2204 m->busy_lock = VPB_UNBUSIED;
2205 /* Don't change PG_ZERO. */
2206 vm_page_free_toq(m);
2208 if (req & VM_ALLOC_WAITFAIL) {
2209 VM_OBJECT_WUNLOCK(object);
2211 VM_OBJECT_WLOCK(object);
2218 if (memattr != VM_MEMATTR_DEFAULT)
2219 pmap_page_set_memattr(m, memattr);
2226 * Check a page that has been freshly dequeued from a freelist.
2229 vm_page_alloc_check(vm_page_t m)
2232 KASSERT(m->object == NULL, ("page %p has object", m));
2233 KASSERT(m->queue == PQ_NONE && (m->aflags & PGA_QUEUE_STATE_MASK) == 0,
2234 ("page %p has unexpected queue %d, flags %#x",
2235 m, m->queue, (m->aflags & PGA_QUEUE_STATE_MASK)));
2236 KASSERT(m->ref_count == 0, ("page %p has references", m));
2237 KASSERT(!vm_page_busied(m), ("page %p is busy", m));
2238 KASSERT(m->dirty == 0, ("page %p is dirty", m));
2239 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2240 ("page %p has unexpected memattr %d",
2241 m, pmap_page_get_memattr(m)));
2242 KASSERT(m->valid == 0, ("free page %p is valid", m));
2246 * vm_page_alloc_freelist:
2248 * Allocate a physical page from the specified free page list.
2250 * The caller must always specify an allocation class.
2252 * allocation classes:
2253 * VM_ALLOC_NORMAL normal process request
2254 * VM_ALLOC_SYSTEM system *really* needs a page
2255 * VM_ALLOC_INTERRUPT interrupt time request
2257 * optional allocation flags:
2258 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2259 * intends to allocate
2260 * VM_ALLOC_WIRED wire the allocated page
2261 * VM_ALLOC_ZERO prefer a zeroed page
2264 vm_page_alloc_freelist(int freelist, int req)
2266 struct vm_domainset_iter di;
2270 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2272 m = vm_page_alloc_freelist_domain(domain, freelist, req);
2275 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2281 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2283 struct vm_domain *vmd;
2288 vmd = VM_DOMAIN(domain);
2290 if (vm_domain_allocate(vmd, req, 1)) {
2291 vm_domain_free_lock(vmd);
2292 m = vm_phys_alloc_freelist_pages(domain, freelist,
2293 VM_FREEPOOL_DIRECT, 0);
2294 vm_domain_free_unlock(vmd);
2296 vm_domain_freecnt_inc(vmd, 1);
2299 if (vm_domain_alloc_fail(vmd, NULL, req))
2304 vm_page_alloc_check(m);
2307 * Initialize the page. Only the PG_ZERO flag is inherited.
2311 if ((req & VM_ALLOC_ZERO) != 0)
2314 if ((req & VM_ALLOC_WIRED) != 0) {
2316 * The page lock is not required for wiring a page that does
2317 * not belong to an object.
2322 /* Unmanaged pages don't use "act_count". */
2323 m->oflags = VPO_UNMANAGED;
2328 vm_page_zone_import(void *arg, void **store, int cnt, int domain, int flags)
2330 struct vm_domain *vmd;
2331 struct vm_pgcache *pgcache;
2335 vmd = VM_DOMAIN(pgcache->domain);
2338 * The page daemon should avoid creating extra memory pressure since its
2339 * main purpose is to replenish the store of free pages.
2341 if (vmd->vmd_severeset || curproc == pageproc ||
2342 !_vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2344 domain = vmd->vmd_domain;
2345 vm_domain_free_lock(vmd);
2346 i = vm_phys_alloc_npages(domain, pgcache->pool, cnt,
2347 (vm_page_t *)store);
2348 vm_domain_free_unlock(vmd);
2350 vm_domain_freecnt_inc(vmd, cnt - i);
2356 vm_page_zone_release(void *arg, void **store, int cnt)
2358 struct vm_domain *vmd;
2359 struct vm_pgcache *pgcache;
2364 vmd = VM_DOMAIN(pgcache->domain);
2365 vm_domain_free_lock(vmd);
2366 for (i = 0; i < cnt; i++) {
2367 m = (vm_page_t)store[i];
2368 vm_phys_free_pages(m, 0);
2370 vm_domain_free_unlock(vmd);
2371 vm_domain_freecnt_inc(vmd, cnt);
2374 #define VPSC_ANY 0 /* No restrictions. */
2375 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2376 #define VPSC_NOSUPER 2 /* Skip superpages. */
2379 * vm_page_scan_contig:
2381 * Scan vm_page_array[] between the specified entries "m_start" and
2382 * "m_end" for a run of contiguous physical pages that satisfy the
2383 * specified conditions, and return the lowest page in the run. The
2384 * specified "alignment" determines the alignment of the lowest physical
2385 * page in the run. If the specified "boundary" is non-zero, then the
2386 * run of physical pages cannot span a physical address that is a
2387 * multiple of "boundary".
2389 * "m_end" is never dereferenced, so it need not point to a vm_page
2390 * structure within vm_page_array[].
2392 * "npages" must be greater than zero. "m_start" and "m_end" must not
2393 * span a hole (or discontiguity) in the physical address space. Both
2394 * "alignment" and "boundary" must be a power of two.
2397 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2398 u_long alignment, vm_paddr_t boundary, int options)
2404 #if VM_NRESERVLEVEL > 0
2407 int m_inc, order, run_ext, run_len;
2409 KASSERT(npages > 0, ("npages is 0"));
2410 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2411 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2415 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2416 KASSERT((m->flags & PG_MARKER) == 0,
2417 ("page %p is PG_MARKER", m));
2418 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->ref_count >= 1,
2419 ("fictitious page %p has invalid ref count", m));
2422 * If the current page would be the start of a run, check its
2423 * physical address against the end, alignment, and boundary
2424 * conditions. If it doesn't satisfy these conditions, either
2425 * terminate the scan or advance to the next page that
2426 * satisfies the failed condition.
2429 KASSERT(m_run == NULL, ("m_run != NULL"));
2430 if (m + npages > m_end)
2432 pa = VM_PAGE_TO_PHYS(m);
2433 if ((pa & (alignment - 1)) != 0) {
2434 m_inc = atop(roundup2(pa, alignment) - pa);
2437 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2439 m_inc = atop(roundup2(pa, boundary) - pa);
2443 KASSERT(m_run != NULL, ("m_run == NULL"));
2445 vm_page_change_lock(m, &m_mtx);
2448 if (vm_page_wired(m))
2450 #if VM_NRESERVLEVEL > 0
2451 else if ((level = vm_reserv_level(m)) >= 0 &&
2452 (options & VPSC_NORESERV) != 0) {
2454 /* Advance to the end of the reservation. */
2455 pa = VM_PAGE_TO_PHYS(m);
2456 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2460 else if ((object = m->object) != NULL) {
2462 * The page is considered eligible for relocation if
2463 * and only if it could be laundered or reclaimed by
2466 if (!VM_OBJECT_TRYRLOCK(object)) {
2468 VM_OBJECT_RLOCK(object);
2470 if (m->object != object) {
2472 * The page may have been freed.
2474 VM_OBJECT_RUNLOCK(object);
2478 /* Don't care: PG_NODUMP, PG_ZERO. */
2479 if (object->type != OBJT_DEFAULT &&
2480 object->type != OBJT_SWAP &&
2481 object->type != OBJT_VNODE) {
2483 #if VM_NRESERVLEVEL > 0
2484 } else if ((options & VPSC_NOSUPER) != 0 &&
2485 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2487 /* Advance to the end of the superpage. */
2488 pa = VM_PAGE_TO_PHYS(m);
2489 m_inc = atop(roundup2(pa + 1,
2490 vm_reserv_size(level)) - pa);
2492 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2493 vm_page_queue(m) != PQ_NONE && !vm_page_busied(m) &&
2494 !vm_page_wired(m)) {
2496 * The page is allocated but eligible for
2497 * relocation. Extend the current run by one
2500 KASSERT(pmap_page_get_memattr(m) ==
2502 ("page %p has an unexpected memattr", m));
2503 KASSERT((m->oflags & (VPO_SWAPINPROG |
2504 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2505 ("page %p has unexpected oflags", m));
2506 /* Don't care: PGA_NOSYNC. */
2510 VM_OBJECT_RUNLOCK(object);
2511 #if VM_NRESERVLEVEL > 0
2512 } else if (level >= 0) {
2514 * The page is reserved but not yet allocated. In
2515 * other words, it is still free. Extend the current
2520 } else if ((order = m->order) < VM_NFREEORDER) {
2522 * The page is enqueued in the physical memory
2523 * allocator's free page queues. Moreover, it is the
2524 * first page in a power-of-two-sized run of
2525 * contiguous free pages. Add these pages to the end
2526 * of the current run, and jump ahead.
2528 run_ext = 1 << order;
2532 * Skip the page for one of the following reasons: (1)
2533 * It is enqueued in the physical memory allocator's
2534 * free page queues. However, it is not the first
2535 * page in a run of contiguous free pages. (This case
2536 * rarely occurs because the scan is performed in
2537 * ascending order.) (2) It is not reserved, and it is
2538 * transitioning from free to allocated. (Conversely,
2539 * the transition from allocated to free for managed
2540 * pages is blocked by the page lock.) (3) It is
2541 * allocated but not contained by an object and not
2542 * wired, e.g., allocated by Xen's balloon driver.
2548 * Extend or reset the current run of pages.
2563 if (run_len >= npages)
2569 * vm_page_reclaim_run:
2571 * Try to relocate each of the allocated virtual pages within the
2572 * specified run of physical pages to a new physical address. Free the
2573 * physical pages underlying the relocated virtual pages. A virtual page
2574 * is relocatable if and only if it could be laundered or reclaimed by
2575 * the page daemon. Whenever possible, a virtual page is relocated to a
2576 * physical address above "high".
2578 * Returns 0 if every physical page within the run was already free or
2579 * just freed by a successful relocation. Otherwise, returns a non-zero
2580 * value indicating why the last attempt to relocate a virtual page was
2583 * "req_class" must be an allocation class.
2586 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2589 struct vm_domain *vmd;
2591 struct spglist free;
2594 vm_page_t m, m_end, m_new;
2595 int error, order, req;
2597 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2598 ("req_class is not an allocation class"));
2602 m_end = m_run + npages;
2604 for (; error == 0 && m < m_end; m++) {
2605 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2606 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2609 * Avoid releasing and reacquiring the same page lock.
2611 vm_page_change_lock(m, &m_mtx);
2614 * Racily check for wirings. Races are handled below.
2616 if (vm_page_wired(m))
2618 else if ((object = m->object) != NULL) {
2620 * The page is relocated if and only if it could be
2621 * laundered or reclaimed by the page daemon.
2623 if (!VM_OBJECT_TRYWLOCK(object)) {
2625 VM_OBJECT_WLOCK(object);
2627 if (m->object != object) {
2629 * The page may have been freed.
2631 VM_OBJECT_WUNLOCK(object);
2635 /* Don't care: PG_NODUMP, PG_ZERO. */
2636 if (object->type != OBJT_DEFAULT &&
2637 object->type != OBJT_SWAP &&
2638 object->type != OBJT_VNODE)
2640 else if (object->memattr != VM_MEMATTR_DEFAULT)
2642 else if (vm_page_queue(m) != PQ_NONE &&
2643 vm_page_tryxbusy(m) != 0) {
2644 if (vm_page_wired(m)) {
2649 KASSERT(pmap_page_get_memattr(m) ==
2651 ("page %p has an unexpected memattr", m));
2652 KASSERT((m->oflags & (VPO_SWAPINPROG |
2653 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2654 ("page %p has unexpected oflags", m));
2655 /* Don't care: PGA_NOSYNC. */
2656 if (!vm_page_none_valid(m)) {
2658 * First, try to allocate a new page
2659 * that is above "high". Failing
2660 * that, try to allocate a new page
2661 * that is below "m_run". Allocate
2662 * the new page between the end of
2663 * "m_run" and "high" only as a last
2666 req = req_class | VM_ALLOC_NOOBJ;
2667 if ((m->flags & PG_NODUMP) != 0)
2668 req |= VM_ALLOC_NODUMP;
2669 if (trunc_page(high) !=
2670 ~(vm_paddr_t)PAGE_MASK) {
2671 m_new = vm_page_alloc_contig(
2676 VM_MEMATTR_DEFAULT);
2679 if (m_new == NULL) {
2680 pa = VM_PAGE_TO_PHYS(m_run);
2681 m_new = vm_page_alloc_contig(
2683 0, pa - 1, PAGE_SIZE, 0,
2684 VM_MEMATTR_DEFAULT);
2686 if (m_new == NULL) {
2688 m_new = vm_page_alloc_contig(
2690 pa, high, PAGE_SIZE, 0,
2691 VM_MEMATTR_DEFAULT);
2693 if (m_new == NULL) {
2700 * Unmap the page and check for new
2701 * wirings that may have been acquired
2702 * through a pmap lookup.
2704 if (object->ref_count != 0 &&
2705 !vm_page_try_remove_all(m)) {
2706 vm_page_free(m_new);
2712 * Replace "m" with the new page. For
2713 * vm_page_replace(), "m" must be busy
2714 * and dequeued. Finally, change "m"
2715 * as if vm_page_free() was called.
2717 m_new->aflags = m->aflags &
2718 ~PGA_QUEUE_STATE_MASK;
2719 KASSERT(m_new->oflags == VPO_UNMANAGED,
2720 ("page %p is managed", m_new));
2721 pmap_copy_page(m, m_new);
2722 m_new->valid = m->valid;
2723 m_new->dirty = m->dirty;
2724 m->flags &= ~PG_ZERO;
2726 vm_page_replace_checked(m_new, object,
2728 if (vm_page_free_prep(m))
2729 SLIST_INSERT_HEAD(&free, m,
2733 * The new page must be deactivated
2734 * before the object is unlocked.
2736 vm_page_change_lock(m_new, &m_mtx);
2737 vm_page_deactivate(m_new);
2739 m->flags &= ~PG_ZERO;
2741 if (vm_page_free_prep(m))
2742 SLIST_INSERT_HEAD(&free, m,
2744 KASSERT(m->dirty == 0,
2745 ("page %p is dirty", m));
2750 VM_OBJECT_WUNLOCK(object);
2752 MPASS(vm_phys_domain(m) == domain);
2753 vmd = VM_DOMAIN(domain);
2754 vm_domain_free_lock(vmd);
2756 if (order < VM_NFREEORDER) {
2758 * The page is enqueued in the physical memory
2759 * allocator's free page queues. Moreover, it
2760 * is the first page in a power-of-two-sized
2761 * run of contiguous free pages. Jump ahead
2762 * to the last page within that run, and
2763 * continue from there.
2765 m += (1 << order) - 1;
2767 #if VM_NRESERVLEVEL > 0
2768 else if (vm_reserv_is_page_free(m))
2771 vm_domain_free_unlock(vmd);
2772 if (order == VM_NFREEORDER)
2778 if ((m = SLIST_FIRST(&free)) != NULL) {
2781 vmd = VM_DOMAIN(domain);
2783 vm_domain_free_lock(vmd);
2785 MPASS(vm_phys_domain(m) == domain);
2786 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2787 vm_phys_free_pages(m, 0);
2789 } while ((m = SLIST_FIRST(&free)) != NULL);
2790 vm_domain_free_unlock(vmd);
2791 vm_domain_freecnt_inc(vmd, cnt);
2798 CTASSERT(powerof2(NRUNS));
2800 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2802 #define MIN_RECLAIM 8
2805 * vm_page_reclaim_contig:
2807 * Reclaim allocated, contiguous physical memory satisfying the specified
2808 * conditions by relocating the virtual pages using that physical memory.
2809 * Returns true if reclamation is successful and false otherwise. Since
2810 * relocation requires the allocation of physical pages, reclamation may
2811 * fail due to a shortage of free pages. When reclamation fails, callers
2812 * are expected to perform vm_wait() before retrying a failed allocation
2813 * operation, e.g., vm_page_alloc_contig().
2815 * The caller must always specify an allocation class through "req".
2817 * allocation classes:
2818 * VM_ALLOC_NORMAL normal process request
2819 * VM_ALLOC_SYSTEM system *really* needs a page
2820 * VM_ALLOC_INTERRUPT interrupt time request
2822 * The optional allocation flags are ignored.
2824 * "npages" must be greater than zero. Both "alignment" and "boundary"
2825 * must be a power of two.
2828 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
2829 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2831 struct vm_domain *vmd;
2832 vm_paddr_t curr_low;
2833 vm_page_t m_run, m_runs[NRUNS];
2834 u_long count, reclaimed;
2835 int error, i, options, req_class;
2837 KASSERT(npages > 0, ("npages is 0"));
2838 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2839 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2840 req_class = req & VM_ALLOC_CLASS_MASK;
2843 * The page daemon is allowed to dig deeper into the free page list.
2845 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2846 req_class = VM_ALLOC_SYSTEM;
2849 * Return if the number of free pages cannot satisfy the requested
2852 vmd = VM_DOMAIN(domain);
2853 count = vmd->vmd_free_count;
2854 if (count < npages + vmd->vmd_free_reserved || (count < npages +
2855 vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2856 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2860 * Scan up to three times, relaxing the restrictions ("options") on
2861 * the reclamation of reservations and superpages each time.
2863 for (options = VPSC_NORESERV;;) {
2865 * Find the highest runs that satisfy the given constraints
2866 * and restrictions, and record them in "m_runs".
2871 m_run = vm_phys_scan_contig(domain, npages, curr_low,
2872 high, alignment, boundary, options);
2875 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2876 m_runs[RUN_INDEX(count)] = m_run;
2881 * Reclaim the highest runs in LIFO (descending) order until
2882 * the number of reclaimed pages, "reclaimed", is at least
2883 * MIN_RECLAIM. Reset "reclaimed" each time because each
2884 * reclamation is idempotent, and runs will (likely) recur
2885 * from one scan to the next as restrictions are relaxed.
2888 for (i = 0; count > 0 && i < NRUNS; i++) {
2890 m_run = m_runs[RUN_INDEX(count)];
2891 error = vm_page_reclaim_run(req_class, domain, npages,
2894 reclaimed += npages;
2895 if (reclaimed >= MIN_RECLAIM)
2901 * Either relax the restrictions on the next scan or return if
2902 * the last scan had no restrictions.
2904 if (options == VPSC_NORESERV)
2905 options = VPSC_NOSUPER;
2906 else if (options == VPSC_NOSUPER)
2908 else if (options == VPSC_ANY)
2909 return (reclaimed != 0);
2914 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2915 u_long alignment, vm_paddr_t boundary)
2917 struct vm_domainset_iter di;
2921 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2923 ret = vm_page_reclaim_contig_domain(domain, req, npages, low,
2924 high, alignment, boundary);
2927 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2933 * Set the domain in the appropriate page level domainset.
2936 vm_domain_set(struct vm_domain *vmd)
2939 mtx_lock(&vm_domainset_lock);
2940 if (!vmd->vmd_minset && vm_paging_min(vmd)) {
2941 vmd->vmd_minset = 1;
2942 DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
2944 if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
2945 vmd->vmd_severeset = 1;
2946 DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
2948 mtx_unlock(&vm_domainset_lock);
2952 * Clear the domain from the appropriate page level domainset.
2955 vm_domain_clear(struct vm_domain *vmd)
2958 mtx_lock(&vm_domainset_lock);
2959 if (vmd->vmd_minset && !vm_paging_min(vmd)) {
2960 vmd->vmd_minset = 0;
2961 DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
2962 if (vm_min_waiters != 0) {
2964 wakeup(&vm_min_domains);
2967 if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
2968 vmd->vmd_severeset = 0;
2969 DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
2970 if (vm_severe_waiters != 0) {
2971 vm_severe_waiters = 0;
2972 wakeup(&vm_severe_domains);
2977 * If pageout daemon needs pages, then tell it that there are
2980 if (vmd->vmd_pageout_pages_needed &&
2981 vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
2982 wakeup(&vmd->vmd_pageout_pages_needed);
2983 vmd->vmd_pageout_pages_needed = 0;
2986 /* See comments in vm_wait_doms(). */
2987 if (vm_pageproc_waiters) {
2988 vm_pageproc_waiters = 0;
2989 wakeup(&vm_pageproc_waiters);
2991 mtx_unlock(&vm_domainset_lock);
2995 * Wait for free pages to exceed the min threshold globally.
3001 mtx_lock(&vm_domainset_lock);
3002 while (vm_page_count_min()) {
3004 msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
3006 mtx_unlock(&vm_domainset_lock);
3010 * Wait for free pages to exceed the severe threshold globally.
3013 vm_wait_severe(void)
3016 mtx_lock(&vm_domainset_lock);
3017 while (vm_page_count_severe()) {
3018 vm_severe_waiters++;
3019 msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
3022 mtx_unlock(&vm_domainset_lock);
3029 return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
3033 vm_wait_doms(const domainset_t *wdoms)
3037 * We use racey wakeup synchronization to avoid expensive global
3038 * locking for the pageproc when sleeping with a non-specific vm_wait.
3039 * To handle this, we only sleep for one tick in this instance. It
3040 * is expected that most allocations for the pageproc will come from
3041 * kmem or vm_page_grab* which will use the more specific and
3042 * race-free vm_wait_domain().
3044 if (curproc == pageproc) {
3045 mtx_lock(&vm_domainset_lock);
3046 vm_pageproc_waiters++;
3047 msleep(&vm_pageproc_waiters, &vm_domainset_lock, PVM | PDROP,
3051 * XXX Ideally we would wait only until the allocation could
3052 * be satisfied. This condition can cause new allocators to
3053 * consume all freed pages while old allocators wait.
3055 mtx_lock(&vm_domainset_lock);
3056 if (vm_page_count_min_set(wdoms)) {
3058 msleep(&vm_min_domains, &vm_domainset_lock,
3059 PVM | PDROP, "vmwait", 0);
3061 mtx_unlock(&vm_domainset_lock);
3068 * Sleep until free pages are available for allocation.
3069 * - Called in various places after failed memory allocations.
3072 vm_wait_domain(int domain)
3074 struct vm_domain *vmd;
3077 vmd = VM_DOMAIN(domain);
3078 vm_domain_free_assert_unlocked(vmd);
3080 if (curproc == pageproc) {
3081 mtx_lock(&vm_domainset_lock);
3082 if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
3083 vmd->vmd_pageout_pages_needed = 1;
3084 msleep(&vmd->vmd_pageout_pages_needed,
3085 &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
3087 mtx_unlock(&vm_domainset_lock);
3089 if (pageproc == NULL)
3090 panic("vm_wait in early boot");
3091 DOMAINSET_ZERO(&wdom);
3092 DOMAINSET_SET(vmd->vmd_domain, &wdom);
3093 vm_wait_doms(&wdom);
3100 * Sleep until free pages are available for allocation in the
3101 * affinity domains of the obj. If obj is NULL, the domain set
3102 * for the calling thread is used.
3103 * Called in various places after failed memory allocations.
3106 vm_wait(vm_object_t obj)
3108 struct domainset *d;
3113 * Carefully fetch pointers only once: the struct domainset
3114 * itself is ummutable but the pointer might change.
3117 d = obj->domain.dr_policy;
3119 d = curthread->td_domain.dr_policy;
3121 vm_wait_doms(&d->ds_mask);
3125 * vm_domain_alloc_fail:
3127 * Called when a page allocation function fails. Informs the
3128 * pagedaemon and performs the requested wait. Requires the
3129 * domain_free and object lock on entry. Returns with the
3130 * object lock held and free lock released. Returns an error when
3131 * retry is necessary.
3135 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3138 vm_domain_free_assert_unlocked(vmd);
3140 atomic_add_int(&vmd->vmd_pageout_deficit,
3141 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3142 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3144 VM_OBJECT_WUNLOCK(object);
3145 vm_wait_domain(vmd->vmd_domain);
3147 VM_OBJECT_WLOCK(object);
3148 if (req & VM_ALLOC_WAITOK)
3158 * Sleep until free pages are available for allocation.
3159 * - Called only in vm_fault so that processes page faulting
3160 * can be easily tracked.
3161 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3162 * processes will be able to grab memory first. Do not change
3163 * this balance without careful testing first.
3166 vm_waitpfault(struct domainset *dset, int timo)
3170 * XXX Ideally we would wait only until the allocation could
3171 * be satisfied. This condition can cause new allocators to
3172 * consume all freed pages while old allocators wait.
3174 mtx_lock(&vm_domainset_lock);
3175 if (vm_page_count_min_set(&dset->ds_mask)) {
3177 msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3180 mtx_unlock(&vm_domainset_lock);
3183 static struct vm_pagequeue *
3184 vm_page_pagequeue(vm_page_t m)
3189 if ((queue = atomic_load_8(&m->queue)) == PQ_NONE)
3191 return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue]);
3195 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m)
3197 struct vm_domain *vmd;
3200 CRITICAL_ASSERT(curthread);
3201 vm_pagequeue_assert_locked(pq);
3204 * The page daemon is allowed to set m->queue = PQ_NONE without
3205 * the page queue lock held. In this case it is about to free the page,
3206 * which must not have any queue state.
3208 qflags = atomic_load_16(&m->aflags);
3209 KASSERT(pq == vm_page_pagequeue(m) ||
3210 (qflags & PGA_QUEUE_STATE_MASK) == 0,
3211 ("page %p doesn't belong to queue %p but has aflags %#x",
3214 if ((qflags & PGA_DEQUEUE) != 0) {
3215 if (__predict_true((qflags & PGA_ENQUEUED) != 0))
3216 vm_pagequeue_remove(pq, m);
3217 vm_page_dequeue_complete(m);
3218 counter_u64_add(queue_ops, 1);
3219 } else if ((qflags & (PGA_REQUEUE | PGA_REQUEUE_HEAD)) != 0) {
3220 if ((qflags & PGA_ENQUEUED) != 0)
3221 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3223 vm_pagequeue_cnt_inc(pq);
3224 vm_page_aflag_set(m, PGA_ENQUEUED);
3228 * Give PGA_REQUEUE_HEAD precedence over PGA_REQUEUE.
3229 * In particular, if both flags are set in close succession,
3230 * only PGA_REQUEUE_HEAD will be applied, even if it was set
3233 if ((qflags & PGA_REQUEUE_HEAD) != 0) {
3234 KASSERT(m->queue == PQ_INACTIVE,
3235 ("head enqueue not supported for page %p", m));
3236 vmd = vm_pagequeue_domain(m);
3237 TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3239 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3241 vm_page_aflag_clear(m, qflags & (PGA_REQUEUE |
3243 counter_u64_add(queue_ops, 1);
3245 counter_u64_add(queue_nops, 1);
3250 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3256 for (i = 0; i < bq->bq_cnt; i++) {
3258 if (__predict_false(m->queue != queue))
3260 vm_pqbatch_process_page(pq, m);
3262 vm_batchqueue_init(bq);
3266 * vm_page_pqbatch_submit: [ internal use only ]
3268 * Enqueue a page in the specified page queue's batched work queue.
3269 * The caller must have encoded the requested operation in the page
3270 * structure's aflags field.
3273 vm_page_pqbatch_submit(vm_page_t m, uint8_t queue)
3275 struct vm_batchqueue *bq;
3276 struct vm_pagequeue *pq;
3279 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3280 ("page %p is unmanaged", m));
3281 KASSERT(mtx_owned(vm_page_lockptr(m)) || m->object == NULL,
3282 ("missing synchronization for page %p", m));
3283 KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3285 domain = vm_phys_domain(m);
3286 pq = &vm_pagequeue_domain(m)->vmd_pagequeues[queue];
3289 bq = DPCPU_PTR(pqbatch[domain][queue]);
3290 if (vm_batchqueue_insert(bq, m)) {
3295 vm_pagequeue_lock(pq);
3297 bq = DPCPU_PTR(pqbatch[domain][queue]);
3298 vm_pqbatch_process(pq, bq, queue);
3301 * The page may have been logically dequeued before we acquired the
3302 * page queue lock. In this case, since we either hold the page lock
3303 * or the page is being freed, a different thread cannot be concurrently
3304 * enqueuing the page.
3306 if (__predict_true(m->queue == queue))
3307 vm_pqbatch_process_page(pq, m);
3309 KASSERT(m->queue == PQ_NONE,
3310 ("invalid queue transition for page %p", m));
3311 KASSERT((m->aflags & PGA_ENQUEUED) == 0,
3312 ("page %p is enqueued with invalid queue index", m));
3314 vm_pagequeue_unlock(pq);
3319 * vm_page_pqbatch_drain: [ internal use only ]
3321 * Force all per-CPU page queue batch queues to be drained. This is
3322 * intended for use in severe memory shortages, to ensure that pages
3323 * do not remain stuck in the batch queues.
3326 vm_page_pqbatch_drain(void)
3329 struct vm_domain *vmd;
3330 struct vm_pagequeue *pq;
3331 int cpu, domain, queue;
3336 sched_bind(td, cpu);
3339 for (domain = 0; domain < vm_ndomains; domain++) {
3340 vmd = VM_DOMAIN(domain);
3341 for (queue = 0; queue < PQ_COUNT; queue++) {
3342 pq = &vmd->vmd_pagequeues[queue];
3343 vm_pagequeue_lock(pq);
3345 vm_pqbatch_process(pq,
3346 DPCPU_PTR(pqbatch[domain][queue]), queue);
3348 vm_pagequeue_unlock(pq);
3358 * Complete the logical removal of a page from a page queue. We must be
3359 * careful to synchronize with the page daemon, which may be concurrently
3360 * examining the page with only the page lock held. The page must not be
3361 * in a state where it appears to be logically enqueued.
3364 vm_page_dequeue_complete(vm_page_t m)
3368 atomic_thread_fence_rel();
3369 vm_page_aflag_clear(m, PGA_QUEUE_STATE_MASK);
3373 * vm_page_dequeue_deferred: [ internal use only ]
3375 * Request removal of the given page from its current page
3376 * queue. Physical removal from the queue may be deferred
3379 * The page must be locked.
3382 vm_page_dequeue_deferred(vm_page_t m)
3386 vm_page_assert_locked(m);
3388 if ((queue = vm_page_queue(m)) == PQ_NONE)
3392 * Set PGA_DEQUEUE if it is not already set to handle a concurrent call
3393 * to vm_page_dequeue_deferred_free(). In particular, avoid modifying
3394 * the page's queue state once vm_page_dequeue_deferred_free() has been
3395 * called. In the event of a race, two batch queue entries for the page
3396 * will be created, but the second will have no effect.
3398 if (vm_page_pqstate_cmpset(m, queue, queue, PGA_DEQUEUE, PGA_DEQUEUE))
3399 vm_page_pqbatch_submit(m, queue);
3403 * A variant of vm_page_dequeue_deferred() that does not assert the page
3404 * lock and is only to be called from vm_page_free_prep(). Because the
3405 * page is being freed, we can assume that nothing other than the page
3406 * daemon is scheduling queue operations on this page, so we get for
3407 * free the mutual exclusion that is otherwise provided by the page lock.
3408 * To handle races, the page daemon must take care to atomically check
3409 * for PGA_DEQUEUE when updating queue state.
3412 vm_page_dequeue_deferred_free(vm_page_t m)
3416 KASSERT(m->ref_count == 0, ("page %p has references", m));
3419 if ((m->aflags & PGA_DEQUEUE) != 0)
3421 atomic_thread_fence_acq();
3422 if ((queue = atomic_load_8(&m->queue)) == PQ_NONE)
3424 if (vm_page_pqstate_cmpset(m, queue, queue, PGA_DEQUEUE,
3426 vm_page_pqbatch_submit(m, queue);
3435 * Remove the page from whichever page queue it's in, if any.
3436 * The page must either be locked or unallocated. This constraint
3437 * ensures that the queue state of the page will remain consistent
3438 * after this function returns.
3441 vm_page_dequeue(vm_page_t m)
3443 struct vm_pagequeue *pq, *pq1;
3446 KASSERT(mtx_owned(vm_page_lockptr(m)) || m->ref_count == 0,
3447 ("page %p is allocated and unlocked", m));
3449 for (pq = vm_page_pagequeue(m);; pq = pq1) {
3452 * A thread may be concurrently executing
3453 * vm_page_dequeue_complete(). Ensure that all queue
3454 * state is cleared before we return.
3456 aflags = atomic_load_16(&m->aflags);
3457 if ((aflags & PGA_QUEUE_STATE_MASK) == 0)
3459 KASSERT((aflags & PGA_DEQUEUE) != 0,
3460 ("page %p has unexpected queue state flags %#x",
3464 * Busy wait until the thread updating queue state is
3465 * finished. Such a thread must be executing in a
3469 pq1 = vm_page_pagequeue(m);
3472 vm_pagequeue_lock(pq);
3473 if ((pq1 = vm_page_pagequeue(m)) == pq)
3475 vm_pagequeue_unlock(pq);
3477 KASSERT(pq == vm_page_pagequeue(m),
3478 ("%s: page %p migrated directly between queues", __func__, m));
3479 KASSERT((m->aflags & PGA_DEQUEUE) != 0 ||
3480 mtx_owned(vm_page_lockptr(m)),
3481 ("%s: queued unlocked page %p", __func__, m));
3483 if ((m->aflags & PGA_ENQUEUED) != 0)
3484 vm_pagequeue_remove(pq, m);
3485 vm_page_dequeue_complete(m);
3486 vm_pagequeue_unlock(pq);
3490 * Schedule the given page for insertion into the specified page queue.
3491 * Physical insertion of the page may be deferred indefinitely.
3494 vm_page_enqueue(vm_page_t m, uint8_t queue)
3497 vm_page_assert_locked(m);
3498 KASSERT(m->queue == PQ_NONE && (m->aflags & PGA_QUEUE_STATE_MASK) == 0,
3499 ("%s: page %p is already enqueued", __func__, m));
3500 KASSERT(m->ref_count > 0,
3501 ("%s: page %p does not carry any references", __func__, m));
3504 if ((m->aflags & PGA_REQUEUE) == 0)
3505 vm_page_aflag_set(m, PGA_REQUEUE);
3506 vm_page_pqbatch_submit(m, queue);
3510 * vm_page_requeue: [ internal use only ]
3512 * Schedule a requeue of the given page.
3514 * The page must be locked.
3517 vm_page_requeue(vm_page_t m)
3520 vm_page_assert_locked(m);
3521 KASSERT(vm_page_queue(m) != PQ_NONE,
3522 ("%s: page %p is not logically enqueued", __func__, m));
3523 KASSERT(m->ref_count > 0,
3524 ("%s: page %p does not carry any references", __func__, m));
3526 if ((m->aflags & PGA_REQUEUE) == 0)
3527 vm_page_aflag_set(m, PGA_REQUEUE);
3528 vm_page_pqbatch_submit(m, atomic_load_8(&m->queue));
3532 * vm_page_swapqueue: [ internal use only ]
3534 * Move the page from one queue to another, or to the tail of its
3535 * current queue, in the face of a possible concurrent call to
3536 * vm_page_dequeue_deferred_free().
3539 vm_page_swapqueue(vm_page_t m, uint8_t oldq, uint8_t newq)
3541 struct vm_pagequeue *pq;
3545 KASSERT(oldq < PQ_COUNT && newq < PQ_COUNT && oldq != newq,
3546 ("vm_page_swapqueue: invalid queues (%d, %d)", oldq, newq));
3547 vm_page_assert_locked(m);
3549 pq = &vm_pagequeue_domain(m)->vmd_pagequeues[oldq];
3550 vm_pagequeue_lock(pq);
3553 * The physical queue state might change at any point before the page
3554 * queue lock is acquired, so we must verify that we hold the correct
3555 * lock before proceeding.
3557 if (__predict_false(m->queue != oldq)) {
3558 vm_pagequeue_unlock(pq);
3563 * Once the queue index of the page changes, there is nothing
3564 * synchronizing with further updates to the physical queue state.
3565 * Therefore we must remove the page from the queue now in anticipation
3566 * of a successful commit, and be prepared to roll back.
3568 if (__predict_true((m->aflags & PGA_ENQUEUED) != 0)) {
3569 next = TAILQ_NEXT(m, plinks.q);
3570 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3571 vm_page_aflag_clear(m, PGA_ENQUEUED);
3578 * Atomically update the queue field and set PGA_REQUEUE while
3579 * ensuring that PGA_DEQUEUE has not been set.
3581 if (__predict_false(!vm_page_pqstate_cmpset(m, oldq, newq, PGA_DEQUEUE,
3584 vm_page_aflag_set(m, PGA_ENQUEUED);
3586 TAILQ_INSERT_BEFORE(next, m, plinks.q);
3588 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3590 vm_pagequeue_unlock(pq);
3593 vm_pagequeue_cnt_dec(pq);
3594 vm_pagequeue_unlock(pq);
3595 vm_page_pqbatch_submit(m, newq);
3599 * vm_page_free_prep:
3601 * Prepares the given page to be put on the free list,
3602 * disassociating it from any VM object. The caller may return
3603 * the page to the free list only if this function returns true.
3605 * The object must be locked. The page must be locked if it is
3609 vm_page_free_prep(vm_page_t m)
3613 * Synchronize with threads that have dropped a reference to this
3616 atomic_thread_fence_acq();
3618 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
3619 if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
3622 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3623 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
3624 KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
3625 m, i, (uintmax_t)*p));
3628 if ((m->oflags & VPO_UNMANAGED) == 0) {
3629 KASSERT(!pmap_page_is_mapped(m),
3630 ("vm_page_free_prep: freeing mapped page %p", m));
3631 KASSERT((m->aflags & (PGA_EXECUTABLE | PGA_WRITEABLE)) == 0,
3632 ("vm_page_free_prep: mapping flags set in page %p", m));
3634 KASSERT(m->queue == PQ_NONE,
3635 ("vm_page_free_prep: unmanaged page %p is queued", m));
3637 VM_CNT_INC(v_tfree);
3639 if (vm_page_sbusied(m))
3640 panic("vm_page_free_prep: freeing shared busy page %p", m);
3642 if (m->object != NULL) {
3643 vm_page_object_remove(m);
3646 * The object reference can be released without an atomic
3649 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
3650 m->ref_count == VPRC_OBJREF,
3651 ("vm_page_free_prep: page %p has unexpected ref_count %u",
3654 m->ref_count -= VPRC_OBJREF;
3657 if (vm_page_xbusied(m))
3661 * If fictitious remove object association and
3664 if ((m->flags & PG_FICTITIOUS) != 0) {
3665 KASSERT(m->ref_count == 1,
3666 ("fictitious page %p is referenced", m));
3667 KASSERT(m->queue == PQ_NONE,
3668 ("fictitious page %p is queued", m));
3673 * Pages need not be dequeued before they are returned to the physical
3674 * memory allocator, but they must at least be marked for a deferred
3677 if ((m->oflags & VPO_UNMANAGED) == 0)
3678 vm_page_dequeue_deferred_free(m);
3683 if (m->ref_count != 0)
3684 panic("vm_page_free_prep: page %p has references", m);
3687 * Restore the default memory attribute to the page.
3689 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3690 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3692 #if VM_NRESERVLEVEL > 0
3694 * Determine whether the page belongs to a reservation. If the page was
3695 * allocated from a per-CPU cache, it cannot belong to a reservation, so
3696 * as an optimization, we avoid the check in that case.
3698 if ((m->flags & PG_PCPU_CACHE) == 0 && vm_reserv_free_page(m))
3708 * Returns the given page to the free list, disassociating it
3709 * from any VM object.
3711 * The object must be locked. The page must be locked if it is
3715 vm_page_free_toq(vm_page_t m)
3717 struct vm_domain *vmd;
3720 if (!vm_page_free_prep(m))
3723 vmd = vm_pagequeue_domain(m);
3724 zone = vmd->vmd_pgcache[m->pool].zone;
3725 if ((m->flags & PG_PCPU_CACHE) != 0 && zone != NULL) {
3729 vm_domain_free_lock(vmd);
3730 vm_phys_free_pages(m, 0);
3731 vm_domain_free_unlock(vmd);
3732 vm_domain_freecnt_inc(vmd, 1);
3736 * vm_page_free_pages_toq:
3738 * Returns a list of pages to the free list, disassociating it
3739 * from any VM object. In other words, this is equivalent to
3740 * calling vm_page_free_toq() for each page of a list of VM objects.
3742 * The objects must be locked. The pages must be locked if it is
3746 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
3751 if (SLIST_EMPTY(free))
3755 while ((m = SLIST_FIRST(free)) != NULL) {
3757 SLIST_REMOVE_HEAD(free, plinks.s.ss);
3758 vm_page_free_toq(m);
3761 if (update_wire_count)
3766 * Mark this page as wired down, preventing reclamation by the page daemon
3767 * or when the containing object is destroyed.
3770 vm_page_wire(vm_page_t m)
3774 KASSERT(m->object != NULL,
3775 ("vm_page_wire: page %p does not belong to an object", m));
3776 if (!vm_page_busied(m))
3777 VM_OBJECT_ASSERT_LOCKED(m->object);
3778 KASSERT((m->flags & PG_FICTITIOUS) == 0 ||
3779 VPRC_WIRE_COUNT(m->ref_count) >= 1,
3780 ("vm_page_wire: fictitious page %p has zero wirings", m));
3782 old = atomic_fetchadd_int(&m->ref_count, 1);
3783 KASSERT(VPRC_WIRE_COUNT(old) != VPRC_WIRE_COUNT_MAX,
3784 ("vm_page_wire: counter overflow for page %p", m));
3785 if (VPRC_WIRE_COUNT(old) == 0)
3790 * Attempt to wire a mapped page following a pmap lookup of that page.
3791 * This may fail if a thread is concurrently tearing down mappings of the page.
3792 * The transient failure is acceptable because it translates to the
3793 * failure of the caller pmap_extract_and_hold(), which should be then
3794 * followed by the vm_fault() fallback, see e.g. vm_fault_quick_hold_pages().
3797 vm_page_wire_mapped(vm_page_t m)
3804 ("vm_page_wire_mapped: wiring unreferenced page %p", m));
3805 if ((old & VPRC_BLOCKED) != 0)
3807 } while (!atomic_fcmpset_int(&m->ref_count, &old, old + 1));
3809 if (VPRC_WIRE_COUNT(old) == 0)
3815 * Release one wiring of the specified page, potentially allowing it to be
3818 * Only managed pages belonging to an object can be paged out. If the number
3819 * of wirings transitions to zero and the page is eligible for page out, then
3820 * the page is added to the specified paging queue. If the released wiring
3821 * represented the last reference to the page, the page is freed.
3823 * A managed page must be locked.
3826 vm_page_unwire(vm_page_t m, uint8_t queue)
3831 KASSERT(queue < PQ_COUNT,
3832 ("vm_page_unwire: invalid queue %u request for page %p", queue, m));
3834 if ((m->oflags & VPO_UNMANAGED) != 0) {
3835 if (vm_page_unwire_noq(m) && m->ref_count == 0)
3841 * Update LRU state before releasing the wiring reference.
3842 * We only need to do this once since we hold the page lock.
3843 * Use a release store when updating the reference count to
3844 * synchronize with vm_page_free_prep().
3849 KASSERT(VPRC_WIRE_COUNT(old) > 0,
3850 ("vm_page_unwire: wire count underflow for page %p", m));
3851 if (!locked && VPRC_WIRE_COUNT(old) == 1) {
3854 if (queue == PQ_ACTIVE && vm_page_queue(m) == PQ_ACTIVE)
3855 vm_page_reference(m);
3857 vm_page_mvqueue(m, queue);
3859 } while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
3862 * Release the lock only after the wiring is released, to ensure that
3863 * the page daemon does not encounter and dequeue the page while it is
3869 if (VPRC_WIRE_COUNT(old) == 1) {
3877 * Unwire a page without (re-)inserting it into a page queue. It is up
3878 * to the caller to enqueue, requeue, or free the page as appropriate.
3879 * In most cases involving managed pages, vm_page_unwire() should be used
3883 vm_page_unwire_noq(vm_page_t m)
3887 old = vm_page_drop(m, 1);
3888 KASSERT(VPRC_WIRE_COUNT(old) != 0,
3889 ("vm_page_unref: counter underflow for page %p", m));
3890 KASSERT((m->flags & PG_FICTITIOUS) == 0 || VPRC_WIRE_COUNT(old) > 1,
3891 ("vm_page_unref: missing ref on fictitious page %p", m));
3893 if (VPRC_WIRE_COUNT(old) > 1)
3900 * Ensure that the page is in the specified page queue. If the page is
3901 * active or being moved to the active queue, ensure that its act_count is
3902 * at least ACT_INIT but do not otherwise mess with it. Otherwise, ensure that
3903 * the page is at the tail of its page queue.
3905 * The page may be wired. The caller should release its wiring reference
3906 * before releasing the page lock, otherwise the page daemon may immediately
3909 * A managed page must be locked.
3911 static __always_inline void
3912 vm_page_mvqueue(vm_page_t m, const uint8_t nqueue)
3915 vm_page_assert_locked(m);
3916 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3917 ("vm_page_mvqueue: page %p is unmanaged", m));
3918 KASSERT(m->ref_count > 0,
3919 ("%s: page %p does not carry any references", __func__, m));
3921 if (vm_page_queue(m) != nqueue) {
3923 vm_page_enqueue(m, nqueue);
3924 } else if (nqueue != PQ_ACTIVE) {
3928 if (nqueue == PQ_ACTIVE && m->act_count < ACT_INIT)
3929 m->act_count = ACT_INIT;
3933 * Put the specified page on the active list (if appropriate).
3936 vm_page_activate(vm_page_t m)
3939 if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
3941 vm_page_mvqueue(m, PQ_ACTIVE);
3945 * Move the specified page to the tail of the inactive queue, or requeue
3946 * the page if it is already in the inactive queue.
3949 vm_page_deactivate(vm_page_t m)
3952 if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
3954 vm_page_mvqueue(m, PQ_INACTIVE);
3958 * Move the specified page close to the head of the inactive queue,
3959 * bypassing LRU. A marker page is used to maintain FIFO ordering.
3960 * As with regular enqueues, we use a per-CPU batch queue to reduce
3961 * contention on the page queue lock.
3964 _vm_page_deactivate_noreuse(vm_page_t m)
3967 vm_page_assert_locked(m);
3969 if (!vm_page_inactive(m)) {
3971 m->queue = PQ_INACTIVE;
3973 if ((m->aflags & PGA_REQUEUE_HEAD) == 0)
3974 vm_page_aflag_set(m, PGA_REQUEUE_HEAD);
3975 vm_page_pqbatch_submit(m, PQ_INACTIVE);
3979 vm_page_deactivate_noreuse(vm_page_t m)
3982 KASSERT(m->object != NULL,
3983 ("vm_page_deactivate_noreuse: page %p has no object", m));
3985 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_wired(m))
3986 _vm_page_deactivate_noreuse(m);
3990 * Put a page in the laundry, or requeue it if it is already there.
3993 vm_page_launder(vm_page_t m)
3996 if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
3998 vm_page_mvqueue(m, PQ_LAUNDRY);
4002 * Put a page in the PQ_UNSWAPPABLE holding queue.
4005 vm_page_unswappable(vm_page_t m)
4008 vm_page_assert_locked(m);
4009 KASSERT(!vm_page_wired(m) && (m->oflags & VPO_UNMANAGED) == 0,
4010 ("page %p already unswappable", m));
4013 vm_page_enqueue(m, PQ_UNSWAPPABLE);
4017 vm_page_release_toq(vm_page_t m, int flags)
4020 vm_page_assert_locked(m);
4023 * Use a check of the valid bits to determine whether we should
4024 * accelerate reclamation of the page. The object lock might not be
4025 * held here, in which case the check is racy. At worst we will either
4026 * accelerate reclamation of a valid page and violate LRU, or
4027 * unnecessarily defer reclamation of an invalid page.
4029 * If we were asked to not cache the page, place it near the head of the
4030 * inactive queue so that is reclaimed sooner.
4032 if ((flags & (VPR_TRYFREE | VPR_NOREUSE)) != 0 || m->valid == 0)
4033 _vm_page_deactivate_noreuse(m);
4034 else if (vm_page_active(m))
4035 vm_page_reference(m);
4037 vm_page_mvqueue(m, PQ_INACTIVE);
4041 * Unwire a page and either attempt to free it or re-add it to the page queues.
4044 vm_page_release(vm_page_t m, int flags)
4050 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4051 ("vm_page_release: page %p is unmanaged", m));
4053 if ((flags & VPR_TRYFREE) != 0) {
4055 object = (vm_object_t)atomic_load_ptr(&m->object);
4058 /* Depends on type-stability. */
4059 if (vm_page_busied(m) || !VM_OBJECT_TRYWLOCK(object)) {
4063 if (object == m->object)
4065 VM_OBJECT_WUNLOCK(object);
4067 if (__predict_true(object != NULL)) {
4068 vm_page_release_locked(m, flags);
4069 VM_OBJECT_WUNLOCK(object);
4075 * Update LRU state before releasing the wiring reference.
4076 * Use a release store when updating the reference count to
4077 * synchronize with vm_page_free_prep().
4082 KASSERT(VPRC_WIRE_COUNT(old) > 0,
4083 ("vm_page_unwire: wire count underflow for page %p", m));
4084 if (!locked && VPRC_WIRE_COUNT(old) == 1) {
4087 vm_page_release_toq(m, flags);
4089 } while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
4092 * Release the lock only after the wiring is released, to ensure that
4093 * the page daemon does not encounter and dequeue the page while it is
4099 if (VPRC_WIRE_COUNT(old) == 1) {
4106 /* See vm_page_release(). */
4108 vm_page_release_locked(vm_page_t m, int flags)
4111 VM_OBJECT_ASSERT_WLOCKED(m->object);
4112 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4113 ("vm_page_release_locked: page %p is unmanaged", m));
4115 if (vm_page_unwire_noq(m)) {
4116 if ((flags & VPR_TRYFREE) != 0 &&
4117 (m->object->ref_count == 0 || !pmap_page_is_mapped(m)) &&
4118 m->dirty == 0 && !vm_page_busied(m)) {
4122 vm_page_release_toq(m, flags);
4129 vm_page_try_blocked_op(vm_page_t m, void (*op)(vm_page_t))
4133 KASSERT(m->object != NULL && (m->oflags & VPO_UNMANAGED) == 0,
4134 ("vm_page_try_blocked_op: page %p has no object", m));
4135 KASSERT(vm_page_busied(m),
4136 ("vm_page_try_blocked_op: page %p is not busy", m));
4137 VM_OBJECT_ASSERT_LOCKED(m->object);
4142 ("vm_page_try_blocked_op: page %p has no references", m));
4143 if (VPRC_WIRE_COUNT(old) != 0)
4145 } while (!atomic_fcmpset_int(&m->ref_count, &old, old | VPRC_BLOCKED));
4150 * If the object is read-locked, new wirings may be created via an
4153 old = vm_page_drop(m, VPRC_BLOCKED);
4154 KASSERT(!VM_OBJECT_WOWNED(m->object) ||
4155 old == (VPRC_BLOCKED | VPRC_OBJREF),
4156 ("vm_page_try_blocked_op: unexpected refcount value %u for %p",
4162 * Atomically check for wirings and remove all mappings of the page.
4165 vm_page_try_remove_all(vm_page_t m)
4168 return (vm_page_try_blocked_op(m, pmap_remove_all));
4172 * Atomically check for wirings and remove all writeable mappings of the page.
4175 vm_page_try_remove_write(vm_page_t m)
4178 return (vm_page_try_blocked_op(m, pmap_remove_write));
4184 * Apply the specified advice to the given page.
4186 * The object and page must be locked.
4189 vm_page_advise(vm_page_t m, int advice)
4192 vm_page_assert_locked(m);
4193 VM_OBJECT_ASSERT_WLOCKED(m->object);
4194 if (advice == MADV_FREE)
4196 * Mark the page clean. This will allow the page to be freed
4197 * without first paging it out. MADV_FREE pages are often
4198 * quickly reused by malloc(3), so we do not do anything that
4199 * would result in a page fault on a later access.
4202 else if (advice != MADV_DONTNEED) {
4203 if (advice == MADV_WILLNEED)
4204 vm_page_activate(m);
4209 * Clear any references to the page. Otherwise, the page daemon will
4210 * immediately reactivate the page.
4212 vm_page_aflag_clear(m, PGA_REFERENCED);
4214 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
4218 * Place clean pages near the head of the inactive queue rather than
4219 * the tail, thus defeating the queue's LRU operation and ensuring that
4220 * the page will be reused quickly. Dirty pages not already in the
4221 * laundry are moved there.
4224 vm_page_deactivate_noreuse(m);
4225 else if (!vm_page_in_laundry(m))
4230 * Grab a page, waiting until we are waken up due to the page
4231 * changing state. We keep on waiting, if the page continues
4232 * to be in the object. If the page doesn't exist, first allocate it
4233 * and then conditionally zero it.
4235 * This routine may sleep.
4237 * The object must be locked on entry. The lock will, however, be released
4238 * and reacquired if the routine sleeps.
4241 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
4247 VM_OBJECT_ASSERT_WLOCKED(object);
4248 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4249 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4250 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4251 pflags = allocflags &
4252 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL |
4254 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4255 pflags |= VM_ALLOC_WAITFAIL;
4256 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4257 pflags |= VM_ALLOC_SBUSY;
4259 if ((m = vm_page_lookup(object, pindex)) != NULL) {
4260 if ((allocflags & (VM_ALLOC_IGN_SBUSY | VM_ALLOC_SBUSY)) != 0)
4261 sleep = !vm_page_trysbusy(m);
4263 sleep = !vm_page_tryxbusy(m);
4265 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4268 * Reference the page before unlocking and
4269 * sleeping so that the page daemon is less
4270 * likely to reclaim it.
4272 if ((allocflags & VM_ALLOC_NOCREAT) == 0)
4273 vm_page_aflag_set(m, PGA_REFERENCED);
4274 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
4275 VM_ALLOC_IGN_SBUSY) != 0);
4276 VM_OBJECT_WLOCK(object);
4277 if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
4281 if ((allocflags & VM_ALLOC_WIRED) != 0)
4286 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4288 m = vm_page_alloc(object, pindex, pflags);
4290 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4294 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
4298 if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4299 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4308 * Grab a page and make it valid, paging in if necessary. Pages missing from
4309 * their pager are zero filled and validated.
4312 vm_page_grab_valid(vm_page_t *mp, vm_object_t object, vm_pindex_t pindex, int allocflags)
4319 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4320 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4321 ("vm_page_grab_valid: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4322 KASSERT((allocflags &
4323 (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4324 ("vm_page_grab_valid: Invalid flags 0x%X", allocflags));
4325 VM_OBJECT_ASSERT_WLOCKED(object);
4326 pflags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY);
4327 pflags |= VM_ALLOC_WAITFAIL;
4331 if ((m = vm_page_lookup(object, pindex)) != NULL) {
4333 * If the page is fully valid it can only become invalid
4334 * with the object lock held. If it is not valid it can
4335 * become valid with the busy lock held. Therefore, we
4336 * may unnecessarily lock the exclusive busy here if we
4337 * race with I/O completion not using the object lock.
4338 * However, we will not end up with an invalid page and a
4341 if (!vm_page_all_valid(m) ||
4342 (allocflags & (VM_ALLOC_IGN_SBUSY | VM_ALLOC_SBUSY)) == 0) {
4343 sleep = !vm_page_tryxbusy(m);
4346 sleep = !vm_page_trysbusy(m);
4349 * Reference the page before unlocking and
4350 * sleeping so that the page daemon is less
4351 * likely to reclaim it.
4353 if ((allocflags & VM_ALLOC_NOCREAT) == 0)
4354 vm_page_aflag_set(m, PGA_REFERENCED);
4355 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
4356 VM_ALLOC_IGN_SBUSY) != 0);
4357 VM_OBJECT_WLOCK(object);
4360 if ((allocflags & VM_ALLOC_NOCREAT) != 0 &&
4361 !vm_page_all_valid(m)) {
4367 return (VM_PAGER_FAIL);
4369 if ((allocflags & VM_ALLOC_WIRED) != 0)
4371 if (vm_page_all_valid(m))
4373 } else if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4375 return (VM_PAGER_FAIL);
4376 } else if ((m = vm_page_alloc(object, pindex, pflags)) != NULL) {
4382 vm_page_assert_xbusied(m);
4384 if (vm_pager_has_page(object, pindex, NULL, NULL)) {
4385 rv = vm_pager_get_pages(object, &m, 1, NULL, NULL);
4386 if (rv != VM_PAGER_OK) {
4387 if (allocflags & VM_ALLOC_WIRED)
4388 vm_page_unwire_noq(m);
4393 MPASS(vm_page_all_valid(m));
4395 vm_page_zero_invalid(m, TRUE);
4398 if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4404 if ((allocflags & VM_ALLOC_SBUSY) != 0 && xbusy)
4405 vm_page_busy_downgrade(m);
4407 return (VM_PAGER_OK);
4411 * Return the specified range of pages from the given object. For each
4412 * page offset within the range, if a page already exists within the object
4413 * at that offset and it is busy, then wait for it to change state. If,
4414 * instead, the page doesn't exist, then allocate it.
4416 * The caller must always specify an allocation class.
4418 * allocation classes:
4419 * VM_ALLOC_NORMAL normal process request
4420 * VM_ALLOC_SYSTEM system *really* needs the pages
4422 * The caller must always specify that the pages are to be busied and/or
4425 * optional allocation flags:
4426 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
4427 * VM_ALLOC_NOBUSY do not exclusive busy the page
4428 * VM_ALLOC_NOWAIT do not sleep
4429 * VM_ALLOC_SBUSY set page to sbusy state
4430 * VM_ALLOC_WIRED wire the pages
4431 * VM_ALLOC_ZERO zero and validate any invalid pages
4433 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
4434 * may return a partial prefix of the requested range.
4437 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
4438 vm_page_t *ma, int count)
4445 VM_OBJECT_ASSERT_WLOCKED(object);
4446 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
4447 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
4448 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
4449 (allocflags & VM_ALLOC_WIRED) != 0,
4450 ("vm_page_grab_pages: the pages must be busied or wired"));
4451 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4452 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4453 ("vm_page_grab_pages: VM_ALLOC_SBUSY/IGN_SBUSY mismatch"));
4456 pflags = allocflags &
4457 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL |
4459 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4460 pflags |= VM_ALLOC_WAITFAIL;
4461 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4462 pflags |= VM_ALLOC_SBUSY;
4465 m = vm_radix_lookup_le(&object->rtree, pindex + i);
4466 if (m == NULL || m->pindex != pindex + i) {
4470 mpred = TAILQ_PREV(m, pglist, listq);
4471 for (; i < count; i++) {
4474 (VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY)) != 0)
4475 sleep = !vm_page_trysbusy(m);
4477 sleep = !vm_page_tryxbusy(m);
4479 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4482 * Reference the page before unlocking and
4483 * sleeping so that the page daemon is less
4484 * likely to reclaim it.
4486 if ((allocflags & VM_ALLOC_NOCREAT) == 0)
4487 vm_page_aflag_set(m, PGA_REFERENCED);
4488 vm_page_busy_sleep(m, "grbmaw", (allocflags &
4489 VM_ALLOC_IGN_SBUSY) != 0);
4490 VM_OBJECT_WLOCK(object);
4493 if ((allocflags & VM_ALLOC_WIRED) != 0)
4496 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4498 m = vm_page_alloc_after(object, pindex + i,
4499 pflags | VM_ALLOC_COUNT(count - i), mpred);
4501 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4506 if (vm_page_none_valid(m) &&
4507 (allocflags & VM_ALLOC_ZERO) != 0) {
4508 if ((m->flags & PG_ZERO) == 0)
4512 if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4513 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4519 m = vm_page_next(m);
4525 * Mapping function for valid or dirty bits in a page.
4527 * Inputs are required to range within a page.
4530 vm_page_bits(int base, int size)
4536 base + size <= PAGE_SIZE,
4537 ("vm_page_bits: illegal base/size %d/%d", base, size)
4540 if (size == 0) /* handle degenerate case */
4543 first_bit = base >> DEV_BSHIFT;
4544 last_bit = (base + size - 1) >> DEV_BSHIFT;
4546 return (((vm_page_bits_t)2 << last_bit) -
4547 ((vm_page_bits_t)1 << first_bit));
4551 vm_page_bits_set(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t set)
4554 #if PAGE_SIZE == 32768
4555 atomic_set_64((uint64_t *)bits, set);
4556 #elif PAGE_SIZE == 16384
4557 atomic_set_32((uint32_t *)bits, set);
4558 #elif (PAGE_SIZE == 8192) && defined(atomic_set_16)
4559 atomic_set_16((uint16_t *)bits, set);
4560 #elif (PAGE_SIZE == 4096) && defined(atomic_set_8)
4561 atomic_set_8((uint8_t *)bits, set);
4562 #else /* PAGE_SIZE <= 8192 */
4566 addr = (uintptr_t)bits;
4568 * Use a trick to perform a 32-bit atomic on the
4569 * containing aligned word, to not depend on the existence
4570 * of atomic_{set, clear}_{8, 16}.
4572 shift = addr & (sizeof(uint32_t) - 1);
4573 #if BYTE_ORDER == BIG_ENDIAN
4574 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4578 addr &= ~(sizeof(uint32_t) - 1);
4579 atomic_set_32((uint32_t *)addr, set << shift);
4580 #endif /* PAGE_SIZE */
4584 vm_page_bits_clear(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t clear)
4587 #if PAGE_SIZE == 32768
4588 atomic_clear_64((uint64_t *)bits, clear);
4589 #elif PAGE_SIZE == 16384
4590 atomic_clear_32((uint32_t *)bits, clear);
4591 #elif (PAGE_SIZE == 8192) && defined(atomic_clear_16)
4592 atomic_clear_16((uint16_t *)bits, clear);
4593 #elif (PAGE_SIZE == 4096) && defined(atomic_clear_8)
4594 atomic_clear_8((uint8_t *)bits, clear);
4595 #else /* PAGE_SIZE <= 8192 */
4599 addr = (uintptr_t)bits;
4601 * Use a trick to perform a 32-bit atomic on the
4602 * containing aligned word, to not depend on the existence
4603 * of atomic_{set, clear}_{8, 16}.
4605 shift = addr & (sizeof(uint32_t) - 1);
4606 #if BYTE_ORDER == BIG_ENDIAN
4607 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4611 addr &= ~(sizeof(uint32_t) - 1);
4612 atomic_clear_32((uint32_t *)addr, clear << shift);
4613 #endif /* PAGE_SIZE */
4617 * vm_page_set_valid_range:
4619 * Sets portions of a page valid. The arguments are expected
4620 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4621 * of any partial chunks touched by the range. The invalid portion of
4622 * such chunks will be zeroed.
4624 * (base + size) must be less then or equal to PAGE_SIZE.
4627 vm_page_set_valid_range(vm_page_t m, int base, int size)
4630 vm_page_bits_t pagebits;
4632 vm_page_assert_busied(m);
4633 if (size == 0) /* handle degenerate case */
4637 * If the base is not DEV_BSIZE aligned and the valid
4638 * bit is clear, we have to zero out a portion of the
4641 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4642 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
4643 pmap_zero_page_area(m, frag, base - frag);
4646 * If the ending offset is not DEV_BSIZE aligned and the
4647 * valid bit is clear, we have to zero out a portion of
4650 endoff = base + size;
4651 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4652 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
4653 pmap_zero_page_area(m, endoff,
4654 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4657 * Assert that no previously invalid block that is now being validated
4660 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
4661 ("vm_page_set_valid_range: page %p is dirty", m));
4664 * Set valid bits inclusive of any overlap.
4666 pagebits = vm_page_bits(base, size);
4667 if (vm_page_xbusied(m))
4668 m->valid |= pagebits;
4670 vm_page_bits_set(m, &m->valid, pagebits);
4674 * Clear the given bits from the specified page's dirty field.
4676 static __inline void
4677 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
4680 vm_page_assert_busied(m);
4683 * If the page is xbusied and not write mapped we are the
4684 * only thread that can modify dirty bits. Otherwise, The pmap
4685 * layer can call vm_page_dirty() without holding a distinguished
4686 * lock. The combination of page busy and atomic operations
4687 * suffice to guarantee consistency of the page dirty field.
4689 if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
4690 m->dirty &= ~pagebits;
4692 vm_page_bits_clear(m, &m->dirty, pagebits);
4696 * vm_page_set_validclean:
4698 * Sets portions of a page valid and clean. The arguments are expected
4699 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4700 * of any partial chunks touched by the range. The invalid portion of
4701 * such chunks will be zero'd.
4703 * (base + size) must be less then or equal to PAGE_SIZE.
4706 vm_page_set_validclean(vm_page_t m, int base, int size)
4708 vm_page_bits_t oldvalid, pagebits;
4711 vm_page_assert_busied(m);
4712 if (size == 0) /* handle degenerate case */
4716 * If the base is not DEV_BSIZE aligned and the valid
4717 * bit is clear, we have to zero out a portion of the
4720 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4721 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
4722 pmap_zero_page_area(m, frag, base - frag);
4725 * If the ending offset is not DEV_BSIZE aligned and the
4726 * valid bit is clear, we have to zero out a portion of
4729 endoff = base + size;
4730 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4731 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
4732 pmap_zero_page_area(m, endoff,
4733 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4736 * Set valid, clear dirty bits. If validating the entire
4737 * page we can safely clear the pmap modify bit. We also
4738 * use this opportunity to clear the PGA_NOSYNC flag. If a process
4739 * takes a write fault on a MAP_NOSYNC memory area the flag will
4742 * We set valid bits inclusive of any overlap, but we can only
4743 * clear dirty bits for DEV_BSIZE chunks that are fully within
4746 oldvalid = m->valid;
4747 pagebits = vm_page_bits(base, size);
4748 if (vm_page_xbusied(m))
4749 m->valid |= pagebits;
4751 vm_page_bits_set(m, &m->valid, pagebits);
4753 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
4754 frag = DEV_BSIZE - frag;
4760 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
4762 if (base == 0 && size == PAGE_SIZE) {
4764 * The page can only be modified within the pmap if it is
4765 * mapped, and it can only be mapped if it was previously
4768 if (oldvalid == VM_PAGE_BITS_ALL)
4770 * Perform the pmap_clear_modify() first. Otherwise,
4771 * a concurrent pmap operation, such as
4772 * pmap_protect(), could clear a modification in the
4773 * pmap and set the dirty field on the page before
4774 * pmap_clear_modify() had begun and after the dirty
4775 * field was cleared here.
4777 pmap_clear_modify(m);
4779 vm_page_aflag_clear(m, PGA_NOSYNC);
4780 } else if (oldvalid != VM_PAGE_BITS_ALL && vm_page_xbusied(m))
4781 m->dirty &= ~pagebits;
4783 vm_page_clear_dirty_mask(m, pagebits);
4787 vm_page_clear_dirty(vm_page_t m, int base, int size)
4790 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
4794 * vm_page_set_invalid:
4796 * Invalidates DEV_BSIZE'd chunks within a page. Both the
4797 * valid and dirty bits for the effected areas are cleared.
4800 vm_page_set_invalid(vm_page_t m, int base, int size)
4802 vm_page_bits_t bits;
4806 * The object lock is required so that pages can't be mapped
4807 * read-only while we're in the process of invalidating them.
4810 VM_OBJECT_ASSERT_WLOCKED(object);
4811 vm_page_assert_busied(m);
4813 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
4814 size >= object->un_pager.vnp.vnp_size)
4815 bits = VM_PAGE_BITS_ALL;
4817 bits = vm_page_bits(base, size);
4818 if (object->ref_count != 0 && vm_page_all_valid(m) && bits != 0)
4820 KASSERT((bits == 0 && vm_page_all_valid(m)) ||
4821 !pmap_page_is_mapped(m),
4822 ("vm_page_set_invalid: page %p is mapped", m));
4823 if (vm_page_xbusied(m)) {
4827 vm_page_bits_clear(m, &m->valid, bits);
4828 vm_page_bits_clear(m, &m->dirty, bits);
4835 * Invalidates the entire page. The page must be busy, unmapped, and
4836 * the enclosing object must be locked. The object locks protects
4837 * against concurrent read-only pmap enter which is done without
4841 vm_page_invalid(vm_page_t m)
4844 vm_page_assert_busied(m);
4845 VM_OBJECT_ASSERT_LOCKED(m->object);
4846 MPASS(!pmap_page_is_mapped(m));
4848 if (vm_page_xbusied(m))
4851 vm_page_bits_clear(m, &m->valid, VM_PAGE_BITS_ALL);
4855 * vm_page_zero_invalid()
4857 * The kernel assumes that the invalid portions of a page contain
4858 * garbage, but such pages can be mapped into memory by user code.
4859 * When this occurs, we must zero out the non-valid portions of the
4860 * page so user code sees what it expects.
4862 * Pages are most often semi-valid when the end of a file is mapped
4863 * into memory and the file's size is not page aligned.
4866 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
4872 * Scan the valid bits looking for invalid sections that
4873 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
4874 * valid bit may be set ) have already been zeroed by
4875 * vm_page_set_validclean().
4877 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
4878 if (i == (PAGE_SIZE / DEV_BSIZE) ||
4879 (m->valid & ((vm_page_bits_t)1 << i))) {
4881 pmap_zero_page_area(m,
4882 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
4889 * setvalid is TRUE when we can safely set the zero'd areas
4890 * as being valid. We can do this if there are no cache consistancy
4891 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
4900 * Is (partial) page valid? Note that the case where size == 0
4901 * will return FALSE in the degenerate case where the page is
4902 * entirely invalid, and TRUE otherwise.
4904 * Some callers envoke this routine without the busy lock held and
4905 * handle races via higher level locks. Typical callers should
4906 * hold a busy lock to prevent invalidation.
4909 vm_page_is_valid(vm_page_t m, int base, int size)
4911 vm_page_bits_t bits;
4913 bits = vm_page_bits(base, size);
4914 return (m->valid != 0 && (m->valid & bits) == bits);
4918 * Returns true if all of the specified predicates are true for the entire
4919 * (super)page and false otherwise.
4922 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
4928 if (skip_m != NULL && skip_m->object != object)
4930 VM_OBJECT_ASSERT_LOCKED(object);
4931 npages = atop(pagesizes[m->psind]);
4934 * The physically contiguous pages that make up a superpage, i.e., a
4935 * page with a page size index ("psind") greater than zero, will
4936 * occupy adjacent entries in vm_page_array[].
4938 for (i = 0; i < npages; i++) {
4939 /* Always test object consistency, including "skip_m". */
4940 if (m[i].object != object)
4942 if (&m[i] == skip_m)
4944 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
4946 if ((flags & PS_ALL_DIRTY) != 0) {
4948 * Calling vm_page_test_dirty() or pmap_is_modified()
4949 * might stop this case from spuriously returning
4950 * "false". However, that would require a write lock
4951 * on the object containing "m[i]".
4953 if (m[i].dirty != VM_PAGE_BITS_ALL)
4956 if ((flags & PS_ALL_VALID) != 0 &&
4957 m[i].valid != VM_PAGE_BITS_ALL)
4964 * Set the page's dirty bits if the page is modified.
4967 vm_page_test_dirty(vm_page_t m)
4970 vm_page_assert_busied(m);
4971 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
4976 vm_page_valid(vm_page_t m)
4979 vm_page_assert_busied(m);
4980 if (vm_page_xbusied(m))
4981 m->valid = VM_PAGE_BITS_ALL;
4983 vm_page_bits_set(m, &m->valid, VM_PAGE_BITS_ALL);
4987 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
4990 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
4994 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
4997 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
5001 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
5004 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
5007 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
5009 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
5012 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
5016 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
5019 mtx_assert_(vm_page_lockptr(m), a, file, line);
5025 vm_page_object_busy_assert(vm_page_t m)
5029 * Certain of the page's fields may only be modified by the
5030 * holder of a page or object busy.
5032 if (m->object != NULL && !vm_page_busied(m))
5033 VM_OBJECT_ASSERT_BUSY(m->object);
5037 vm_page_assert_pga_writeable(vm_page_t m, uint16_t bits)
5040 if ((bits & PGA_WRITEABLE) == 0)
5044 * The PGA_WRITEABLE flag can only be set if the page is
5045 * managed, is exclusively busied or the object is locked.
5046 * Currently, this flag is only set by pmap_enter().
5048 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5049 ("PGA_WRITEABLE on unmanaged page"));
5050 if (!vm_page_xbusied(m))
5051 VM_OBJECT_ASSERT_BUSY(m->object);
5055 #include "opt_ddb.h"
5057 #include <sys/kernel.h>
5059 #include <ddb/ddb.h>
5061 DB_SHOW_COMMAND(page, vm_page_print_page_info)
5064 db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
5065 db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
5066 db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
5067 db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
5068 db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
5069 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
5070 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
5071 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
5072 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
5075 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
5079 db_printf("pq_free %d\n", vm_free_count());
5080 for (dom = 0; dom < vm_ndomains; dom++) {
5082 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
5084 vm_dom[dom].vmd_page_count,
5085 vm_dom[dom].vmd_free_count,
5086 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
5087 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
5088 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
5089 vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
5093 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
5096 boolean_t phys, virt;
5099 db_printf("show pginfo addr\n");
5103 phys = strchr(modif, 'p') != NULL;
5104 virt = strchr(modif, 'v') != NULL;
5106 m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
5108 m = PHYS_TO_VM_PAGE(addr);
5110 m = (vm_page_t)addr;
5112 "page %p obj %p pidx 0x%jx phys 0x%jx q %d ref %u\n"
5113 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
5114 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
5115 m->queue, m->ref_count, m->aflags, m->oflags,
5116 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);