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>
111 #include <vm/vm_dumpset.h>
113 #include <vm/uma_int.h>
115 #include <machine/md_var.h>
117 struct vm_domain vm_dom[MAXMEMDOM];
119 DPCPU_DEFINE_STATIC(struct vm_batchqueue, pqbatch[MAXMEMDOM][PQ_COUNT]);
121 struct mtx_padalign __exclusive_cache_line pa_lock[PA_LOCK_COUNT];
123 struct mtx_padalign __exclusive_cache_line vm_domainset_lock;
124 /* The following fields are protected by the domainset lock. */
125 domainset_t __exclusive_cache_line vm_min_domains;
126 domainset_t __exclusive_cache_line vm_severe_domains;
127 static int vm_min_waiters;
128 static int vm_severe_waiters;
129 static int vm_pageproc_waiters;
131 static SYSCTL_NODE(_vm_stats, OID_AUTO, page, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
132 "VM page statistics");
134 static COUNTER_U64_DEFINE_EARLY(pqstate_commit_retries);
135 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, pqstate_commit_retries,
136 CTLFLAG_RD, &pqstate_commit_retries,
137 "Number of failed per-page atomic queue state updates");
139 static COUNTER_U64_DEFINE_EARLY(queue_ops);
140 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, queue_ops,
141 CTLFLAG_RD, &queue_ops,
142 "Number of batched queue operations");
144 static COUNTER_U64_DEFINE_EARLY(queue_nops);
145 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, queue_nops,
146 CTLFLAG_RD, &queue_nops,
147 "Number of batched queue operations with no effects");
150 * bogus page -- for I/O to/from partially complete buffers,
151 * or for paging into sparsely invalid regions.
153 vm_page_t bogus_page;
155 vm_page_t vm_page_array;
156 long vm_page_array_size;
159 struct bitset *vm_page_dump;
160 long vm_page_dump_pages;
162 static TAILQ_HEAD(, vm_page) blacklist_head;
163 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
164 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
165 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
167 static uma_zone_t fakepg_zone;
169 static void vm_page_alloc_check(vm_page_t m);
170 static bool _vm_page_busy_sleep(vm_object_t obj, vm_page_t m,
171 vm_pindex_t pindex, const char *wmesg, int allocflags, bool locked);
172 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
173 static void vm_page_enqueue(vm_page_t m, uint8_t queue);
174 static bool vm_page_free_prep(vm_page_t m);
175 static void vm_page_free_toq(vm_page_t m);
176 static void vm_page_init(void *dummy);
177 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
178 vm_pindex_t pindex, vm_page_t mpred);
179 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
181 static void vm_page_mvqueue(vm_page_t m, const uint8_t queue,
182 const uint16_t nflag);
183 static int vm_page_reclaim_run(int req_class, int domain, u_long npages,
184 vm_page_t m_run, vm_paddr_t high);
185 static void vm_page_release_toq(vm_page_t m, uint8_t nqueue, bool noreuse);
186 static int vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object,
188 static int vm_page_zone_import(void *arg, void **store, int cnt, int domain,
190 static void vm_page_zone_release(void *arg, void **store, int cnt);
192 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
195 vm_page_init(void *dummy)
198 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
199 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
200 bogus_page = vm_page_alloc_noobj(VM_ALLOC_WIRED);
204 * The cache page zone is initialized later since we need to be able to allocate
205 * pages before UMA is fully initialized.
208 vm_page_init_cache_zones(void *dummy __unused)
210 struct vm_domain *vmd;
211 struct vm_pgcache *pgcache;
212 int cache, domain, maxcache, pool;
215 TUNABLE_INT_FETCH("vm.pgcache_zone_max_pcpu", &maxcache);
216 maxcache *= mp_ncpus;
217 for (domain = 0; domain < vm_ndomains; domain++) {
218 vmd = VM_DOMAIN(domain);
219 for (pool = 0; pool < VM_NFREEPOOL; pool++) {
220 pgcache = &vmd->vmd_pgcache[pool];
221 pgcache->domain = domain;
222 pgcache->pool = pool;
223 pgcache->zone = uma_zcache_create("vm pgcache",
224 PAGE_SIZE, NULL, NULL, NULL, NULL,
225 vm_page_zone_import, vm_page_zone_release, pgcache,
229 * Limit each pool's zone to 0.1% of the pages in the
232 cache = maxcache != 0 ? maxcache :
233 vmd->vmd_page_count / 1000;
234 uma_zone_set_maxcache(pgcache->zone, cache);
238 SYSINIT(vm_page2, SI_SUB_VM_CONF, SI_ORDER_ANY, vm_page_init_cache_zones, NULL);
240 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
241 #if PAGE_SIZE == 32768
243 CTASSERT(sizeof(u_long) >= 8);
250 * Sets the page size, perhaps based upon the memory
251 * size. Must be called before any use of page-size
252 * dependent functions.
255 vm_set_page_size(void)
257 if (vm_cnt.v_page_size == 0)
258 vm_cnt.v_page_size = PAGE_SIZE;
259 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
260 panic("vm_set_page_size: page size not a power of two");
264 * vm_page_blacklist_next:
266 * Find the next entry in the provided string of blacklist
267 * addresses. Entries are separated by space, comma, or newline.
268 * If an invalid integer is encountered then the rest of the
269 * string is skipped. Updates the list pointer to the next
270 * character, or NULL if the string is exhausted or invalid.
273 vm_page_blacklist_next(char **list, char *end)
278 if (list == NULL || *list == NULL)
286 * If there's no end pointer then the buffer is coming from
287 * the kenv and we know it's null-terminated.
290 end = *list + strlen(*list);
292 /* Ensure that strtoq() won't walk off the end */
294 if (*end == '\n' || *end == ' ' || *end == ',')
297 printf("Blacklist not terminated, skipping\n");
303 for (pos = *list; *pos != '\0'; pos = cp) {
304 bad = strtoq(pos, &cp, 0);
305 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
314 if (*cp == '\0' || ++cp >= end)
318 return (trunc_page(bad));
320 printf("Garbage in RAM blacklist, skipping\n");
326 vm_page_blacklist_add(vm_paddr_t pa, bool verbose)
328 struct vm_domain *vmd;
332 m = vm_phys_paddr_to_vm_page(pa);
334 return (true); /* page does not exist, no failure */
336 vmd = vm_pagequeue_domain(m);
337 vm_domain_free_lock(vmd);
338 ret = vm_phys_unfree_page(m);
339 vm_domain_free_unlock(vmd);
341 vm_domain_freecnt_inc(vmd, -1);
342 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
344 printf("Skipping page with pa 0x%jx\n", (uintmax_t)pa);
350 * vm_page_blacklist_check:
352 * Iterate through the provided string of blacklist addresses, pulling
353 * each entry out of the physical allocator free list and putting it
354 * onto a list for reporting via the vm.page_blacklist sysctl.
357 vm_page_blacklist_check(char *list, char *end)
363 while (next != NULL) {
364 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
366 vm_page_blacklist_add(pa, bootverbose);
371 * vm_page_blacklist_load:
373 * Search for a special module named "ram_blacklist". It'll be a
374 * plain text file provided by the user via the loader directive
378 vm_page_blacklist_load(char **list, char **end)
387 mod = preload_search_by_type("ram_blacklist");
389 ptr = preload_fetch_addr(mod);
390 len = preload_fetch_size(mod);
401 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
408 error = sysctl_wire_old_buffer(req, 0);
411 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
412 TAILQ_FOREACH(m, &blacklist_head, listq) {
413 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
414 (uintmax_t)m->phys_addr);
417 error = sbuf_finish(&sbuf);
423 * Initialize a dummy page for use in scans of the specified paging queue.
424 * In principle, this function only needs to set the flag PG_MARKER.
425 * Nonetheless, it write busies the page as a safety precaution.
428 vm_page_init_marker(vm_page_t marker, int queue, uint16_t aflags)
431 bzero(marker, sizeof(*marker));
432 marker->flags = PG_MARKER;
433 marker->a.flags = aflags;
434 marker->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
435 marker->a.queue = queue;
439 vm_page_domain_init(int domain)
441 struct vm_domain *vmd;
442 struct vm_pagequeue *pq;
445 vmd = VM_DOMAIN(domain);
446 bzero(vmd, sizeof(*vmd));
447 *__DECONST(const char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
448 "vm inactive pagequeue";
449 *__DECONST(const char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
450 "vm active pagequeue";
451 *__DECONST(const char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
452 "vm laundry pagequeue";
453 *__DECONST(const char **,
454 &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_name) =
455 "vm unswappable pagequeue";
456 vmd->vmd_domain = domain;
457 vmd->vmd_page_count = 0;
458 vmd->vmd_free_count = 0;
460 vmd->vmd_oom = FALSE;
461 for (i = 0; i < PQ_COUNT; i++) {
462 pq = &vmd->vmd_pagequeues[i];
463 TAILQ_INIT(&pq->pq_pl);
464 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
465 MTX_DEF | MTX_DUPOK);
467 vm_page_init_marker(&vmd->vmd_markers[i], i, 0);
469 mtx_init(&vmd->vmd_free_mtx, "vm page free queue", NULL, MTX_DEF);
470 mtx_init(&vmd->vmd_pageout_mtx, "vm pageout lock", NULL, MTX_DEF);
471 snprintf(vmd->vmd_name, sizeof(vmd->vmd_name), "%d", domain);
474 * inacthead is used to provide FIFO ordering for LRU-bypassing
477 vm_page_init_marker(&vmd->vmd_inacthead, PQ_INACTIVE, PGA_ENQUEUED);
478 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_INACTIVE].pq_pl,
479 &vmd->vmd_inacthead, plinks.q);
482 * The clock pages are used to implement active queue scanning without
483 * requeues. Scans start at clock[0], which is advanced after the scan
484 * ends. When the two clock hands meet, they are reset and scanning
485 * resumes from the head of the queue.
487 vm_page_init_marker(&vmd->vmd_clock[0], PQ_ACTIVE, PGA_ENQUEUED);
488 vm_page_init_marker(&vmd->vmd_clock[1], PQ_ACTIVE, PGA_ENQUEUED);
489 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
490 &vmd->vmd_clock[0], plinks.q);
491 TAILQ_INSERT_TAIL(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
492 &vmd->vmd_clock[1], plinks.q);
496 * Initialize a physical page in preparation for adding it to the free
500 vm_page_init_page(vm_page_t m, vm_paddr_t pa, int segind)
505 m->busy_lock = VPB_FREED;
506 m->flags = m->a.flags = 0;
508 m->a.queue = PQ_NONE;
511 m->order = VM_NFREEORDER;
512 m->pool = VM_FREEPOOL_DEFAULT;
513 m->valid = m->dirty = 0;
517 #ifndef PMAP_HAS_PAGE_ARRAY
519 vm_page_array_alloc(vm_offset_t *vaddr, vm_paddr_t end, vm_paddr_t page_range)
524 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
525 * However, because this page is allocated from KVM, out-of-bounds
526 * accesses using the direct map will not be trapped.
531 * Allocate physical memory for the page structures, and map it.
533 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
534 vm_page_array = (vm_page_t)pmap_map(vaddr, new_end, end,
535 VM_PROT_READ | VM_PROT_WRITE);
536 vm_page_array_size = page_range;
545 * Initializes the resident memory module. Allocates physical memory for
546 * bootstrapping UMA and some data structures that are used to manage
547 * physical pages. Initializes these structures, and populates the free
551 vm_page_startup(vm_offset_t vaddr)
553 struct vm_phys_seg *seg;
554 struct vm_domain *vmd;
556 char *list, *listend;
557 vm_paddr_t end, high_avail, low_avail, new_end, size;
558 vm_paddr_t page_range __unused;
559 vm_paddr_t last_pa, pa, startp, endp;
561 #if MINIDUMP_PAGE_TRACKING
562 u_long vm_page_dump_size;
564 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);
590 witness_size = round_page(witness_startup_count());
591 new_end -= witness_size;
592 mapped = pmap_map(&vaddr, new_end, new_end + witness_size,
593 VM_PROT_READ | VM_PROT_WRITE);
594 bzero((void *)mapped, witness_size);
595 witness_startup((void *)mapped);
598 #if MINIDUMP_PAGE_TRACKING
600 * Allocate a bitmap to indicate that a random physical page
601 * needs to be included in a minidump.
603 * The amd64 port needs this to indicate which direct map pages
604 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
606 * However, i386 still needs this workspace internally within the
607 * minidump code. In theory, they are not needed on i386, but are
608 * included should the sf_buf code decide to use them.
611 vm_page_dump_pages = 0;
612 for (i = 0; dump_avail[i + 1] != 0; i += 2) {
613 vm_page_dump_pages += howmany(dump_avail[i + 1], PAGE_SIZE) -
614 dump_avail[i] / PAGE_SIZE;
615 if (dump_avail[i + 1] > last_pa)
616 last_pa = dump_avail[i + 1];
618 vm_page_dump_size = round_page(BITSET_SIZE(vm_page_dump_pages));
619 new_end -= vm_page_dump_size;
620 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
621 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
622 bzero((void *)vm_page_dump, vm_page_dump_size);
626 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
627 defined(__riscv) || defined(__powerpc64__)
629 * Include the UMA bootstrap pages, witness pages and vm_page_dump
630 * in a crash dump. When pmap_map() uses the direct map, they are
631 * not automatically included.
633 for (pa = new_end; pa < end; pa += PAGE_SIZE)
636 phys_avail[biggestone + 1] = new_end;
639 * Request that the physical pages underlying the message buffer be
640 * included in a crash dump. Since the message buffer is accessed
641 * through the direct map, they are not automatically included.
643 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
644 last_pa = pa + round_page(msgbufsize);
645 while (pa < last_pa) {
651 * Compute the number of pages of memory that will be available for
652 * use, taking into account the overhead of a page structure per page.
653 * In other words, solve
654 * "available physical memory" - round_page(page_range *
655 * sizeof(struct vm_page)) = page_range * PAGE_SIZE
658 low_avail = phys_avail[0];
659 high_avail = phys_avail[1];
660 for (i = 0; i < vm_phys_nsegs; i++) {
661 if (vm_phys_segs[i].start < low_avail)
662 low_avail = vm_phys_segs[i].start;
663 if (vm_phys_segs[i].end > high_avail)
664 high_avail = vm_phys_segs[i].end;
666 /* Skip the first chunk. It is already accounted for. */
667 for (i = 2; phys_avail[i + 1] != 0; i += 2) {
668 if (phys_avail[i] < low_avail)
669 low_avail = phys_avail[i];
670 if (phys_avail[i + 1] > high_avail)
671 high_avail = phys_avail[i + 1];
673 first_page = low_avail / PAGE_SIZE;
674 #ifdef VM_PHYSSEG_SPARSE
676 for (i = 0; i < vm_phys_nsegs; i++)
677 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
678 for (i = 0; phys_avail[i + 1] != 0; i += 2)
679 size += phys_avail[i + 1] - phys_avail[i];
680 #elif defined(VM_PHYSSEG_DENSE)
681 size = high_avail - low_avail;
683 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
686 #ifdef PMAP_HAS_PAGE_ARRAY
687 pmap_page_array_startup(size / PAGE_SIZE);
688 biggestone = vm_phys_avail_largest();
689 end = new_end = phys_avail[biggestone + 1];
691 #ifdef VM_PHYSSEG_DENSE
693 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
694 * the overhead of a page structure per page only if vm_page_array is
695 * allocated from the last physical memory chunk. Otherwise, we must
696 * allocate page structures representing the physical memory
697 * underlying vm_page_array, even though they will not be used.
699 if (new_end != high_avail)
700 page_range = size / PAGE_SIZE;
704 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
707 * If the partial bytes remaining are large enough for
708 * a page (PAGE_SIZE) without a corresponding
709 * 'struct vm_page', then new_end will contain an
710 * extra page after subtracting the length of the VM
711 * page array. Compensate by subtracting an extra
714 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
715 if (new_end == high_avail)
716 high_avail -= PAGE_SIZE;
717 new_end -= PAGE_SIZE;
721 new_end = vm_page_array_alloc(&vaddr, end, page_range);
724 #if VM_NRESERVLEVEL > 0
726 * Allocate physical memory for the reservation management system's
727 * data structures, and map it.
729 new_end = vm_reserv_startup(&vaddr, new_end);
731 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
732 defined(__riscv) || defined(__powerpc64__)
734 * Include vm_page_array and vm_reserv_array in a crash dump.
736 for (pa = new_end; pa < end; pa += PAGE_SIZE)
739 phys_avail[biggestone + 1] = new_end;
742 * Add physical memory segments corresponding to the available
745 for (i = 0; phys_avail[i + 1] != 0; i += 2)
746 if (vm_phys_avail_size(i) != 0)
747 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
750 * Initialize the physical memory allocator.
755 * Initialize the page structures and add every available page to the
756 * physical memory allocator's free lists.
758 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
759 for (ii = 0; ii < vm_page_array_size; ii++) {
760 m = &vm_page_array[ii];
761 vm_page_init_page(m, (first_page + ii) << PAGE_SHIFT, 0);
762 m->flags = PG_FICTITIOUS;
765 vm_cnt.v_page_count = 0;
766 for (segind = 0; segind < vm_phys_nsegs; segind++) {
767 seg = &vm_phys_segs[segind];
768 for (m = seg->first_page, pa = seg->start; pa < seg->end;
769 m++, pa += PAGE_SIZE)
770 vm_page_init_page(m, pa, segind);
773 * Add the segment's pages that are covered by one of
774 * phys_avail's ranges to the free lists.
776 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
777 if (seg->end <= phys_avail[i] ||
778 seg->start >= phys_avail[i + 1])
781 startp = MAX(seg->start, phys_avail[i]);
782 endp = MIN(seg->end, phys_avail[i + 1]);
783 pagecount = (u_long)atop(endp - startp);
787 m = seg->first_page + atop(startp - seg->start);
788 vmd = VM_DOMAIN(seg->domain);
789 vm_domain_free_lock(vmd);
790 vm_phys_enqueue_contig(m, pagecount);
791 vm_domain_free_unlock(vmd);
792 vm_domain_freecnt_inc(vmd, pagecount);
793 vm_cnt.v_page_count += (u_int)pagecount;
794 vmd->vmd_page_count += (u_int)pagecount;
795 vmd->vmd_segs |= 1UL << segind;
800 * Remove blacklisted pages from the physical memory allocator.
802 TAILQ_INIT(&blacklist_head);
803 vm_page_blacklist_load(&list, &listend);
804 vm_page_blacklist_check(list, listend);
806 list = kern_getenv("vm.blacklist");
807 vm_page_blacklist_check(list, NULL);
810 #if VM_NRESERVLEVEL > 0
812 * Initialize the reservation management system.
821 vm_page_reference(vm_page_t m)
824 vm_page_aflag_set(m, PGA_REFERENCED);
830 * Helper routine for grab functions to trylock busy.
832 * Returns true on success and false on failure.
835 vm_page_trybusy(vm_page_t m, int allocflags)
838 if ((allocflags & (VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY)) != 0)
839 return (vm_page_trysbusy(m));
841 return (vm_page_tryxbusy(m));
847 * Helper routine for grab functions to trylock busy and wire.
849 * Returns true on success and false on failure.
852 vm_page_tryacquire(vm_page_t m, int allocflags)
856 locked = vm_page_trybusy(m, allocflags);
857 if (locked && (allocflags & VM_ALLOC_WIRED) != 0)
863 * vm_page_busy_acquire:
865 * Acquire the busy lock as described by VM_ALLOC_* flags. Will loop
866 * and drop the object lock if necessary.
869 vm_page_busy_acquire(vm_page_t m, int allocflags)
875 * The page-specific object must be cached because page
876 * identity can change during the sleep, causing the
877 * re-lock of a different object.
878 * It is assumed that a reference to the object is already
879 * held by the callers.
881 obj = atomic_load_ptr(&m->object);
883 if (vm_page_tryacquire(m, allocflags))
885 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
888 locked = VM_OBJECT_WOWNED(obj);
891 MPASS(locked || vm_page_wired(m));
892 if (_vm_page_busy_sleep(obj, m, m->pindex, "vmpba", allocflags,
894 VM_OBJECT_WLOCK(obj);
895 if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
897 KASSERT(m->object == obj || m->object == NULL,
898 ("vm_page_busy_acquire: page %p does not belong to %p",
904 * vm_page_busy_downgrade:
906 * Downgrade an exclusive busy page into a single shared busy page.
909 vm_page_busy_downgrade(vm_page_t m)
913 vm_page_assert_xbusied(m);
915 x = vm_page_busy_fetch(m);
917 if (atomic_fcmpset_rel_int(&m->busy_lock,
918 &x, VPB_SHARERS_WORD(1)))
921 if ((x & VPB_BIT_WAITERS) != 0)
927 * vm_page_busy_tryupgrade:
929 * Attempt to upgrade a single shared busy into an exclusive busy.
932 vm_page_busy_tryupgrade(vm_page_t m)
936 vm_page_assert_sbusied(m);
938 x = vm_page_busy_fetch(m);
939 ce = VPB_CURTHREAD_EXCLUSIVE;
941 if (VPB_SHARERS(x) > 1)
943 KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
944 ("vm_page_busy_tryupgrade: invalid lock state"));
945 if (!atomic_fcmpset_acq_int(&m->busy_lock, &x,
946 ce | (x & VPB_BIT_WAITERS)))
955 * Return a positive value if the page is shared busied, 0 otherwise.
958 vm_page_sbusied(vm_page_t m)
962 x = vm_page_busy_fetch(m);
963 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
969 * Shared unbusy a page.
972 vm_page_sunbusy(vm_page_t m)
976 vm_page_assert_sbusied(m);
978 x = vm_page_busy_fetch(m);
980 KASSERT(x != VPB_FREED,
981 ("vm_page_sunbusy: Unlocking freed page."));
982 if (VPB_SHARERS(x) > 1) {
983 if (atomic_fcmpset_int(&m->busy_lock, &x,
988 KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
989 ("vm_page_sunbusy: invalid lock state"));
990 if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
992 if ((x & VPB_BIT_WAITERS) == 0)
1000 * vm_page_busy_sleep:
1002 * Sleep if the page is busy, using the page pointer as wchan.
1003 * This is used to implement the hard-path of the busying mechanism.
1005 * If VM_ALLOC_IGN_SBUSY is specified in allocflags, the function
1006 * will not sleep if the page is shared-busy.
1008 * The object lock must be held on entry.
1010 * Returns true if it slept and dropped the object lock, or false
1011 * if there was no sleep and the lock is still held.
1014 vm_page_busy_sleep(vm_page_t m, const char *wmesg, int allocflags)
1019 VM_OBJECT_ASSERT_LOCKED(obj);
1021 return (_vm_page_busy_sleep(obj, m, m->pindex, wmesg, allocflags,
1026 * vm_page_busy_sleep_unlocked:
1028 * Sleep if the page is busy, using the page pointer as wchan.
1029 * This is used to implement the hard-path of busying mechanism.
1031 * If VM_ALLOC_IGN_SBUSY is specified in allocflags, the function
1032 * will not sleep if the page is shared-busy.
1034 * The object lock must not be held on entry. The operation will
1035 * return if the page changes identity.
1038 vm_page_busy_sleep_unlocked(vm_object_t obj, vm_page_t m, vm_pindex_t pindex,
1039 const char *wmesg, int allocflags)
1041 VM_OBJECT_ASSERT_UNLOCKED(obj);
1043 (void)_vm_page_busy_sleep(obj, m, pindex, wmesg, allocflags, false);
1047 * _vm_page_busy_sleep:
1049 * Internal busy sleep function. Verifies the page identity and
1050 * lockstate against parameters. Returns true if it sleeps and
1053 * allocflags uses VM_ALLOC_* flags to specify the lock required.
1055 * If locked is true the lock will be dropped for any true returns
1056 * and held for any false returns.
1059 _vm_page_busy_sleep(vm_object_t obj, vm_page_t m, vm_pindex_t pindex,
1060 const char *wmesg, int allocflags, bool locked)
1066 * If the object is busy we must wait for that to drain to zero
1067 * before trying the page again.
1069 if (obj != NULL && vm_object_busied(obj)) {
1071 VM_OBJECT_DROP(obj);
1072 vm_object_busy_wait(obj, wmesg);
1076 if (!vm_page_busied(m))
1079 xsleep = (allocflags & (VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY)) != 0;
1081 x = vm_page_busy_fetch(m);
1084 * If the page changes objects or becomes unlocked we can
1087 if (x == VPB_UNBUSIED ||
1088 (xsleep && (x & VPB_BIT_SHARED) != 0) ||
1089 m->object != obj || m->pindex != pindex) {
1093 if ((x & VPB_BIT_WAITERS) != 0)
1095 } while (!atomic_fcmpset_int(&m->busy_lock, &x, x | VPB_BIT_WAITERS));
1097 VM_OBJECT_DROP(obj);
1099 sleepq_add(m, NULL, wmesg, 0, 0);
1100 sleepq_wait(m, PVM);
1108 * Try to shared busy a page.
1109 * If the operation succeeds 1 is returned otherwise 0.
1110 * The operation never sleeps.
1113 vm_page_trysbusy(vm_page_t m)
1119 x = vm_page_busy_fetch(m);
1121 if ((x & VPB_BIT_SHARED) == 0)
1124 * Reduce the window for transient busies that will trigger
1125 * false negatives in vm_page_ps_test().
1127 if (obj != NULL && vm_object_busied(obj))
1129 if (atomic_fcmpset_acq_int(&m->busy_lock, &x,
1130 x + VPB_ONE_SHARER))
1134 /* Refetch the object now that we're guaranteed that it is stable. */
1136 if (obj != NULL && vm_object_busied(obj)) {
1146 * Try to exclusive busy a page.
1147 * If the operation succeeds 1 is returned otherwise 0.
1148 * The operation never sleeps.
1151 vm_page_tryxbusy(vm_page_t m)
1155 if (atomic_cmpset_acq_int(&m->busy_lock, VPB_UNBUSIED,
1156 VPB_CURTHREAD_EXCLUSIVE) == 0)
1160 if (obj != NULL && vm_object_busied(obj)) {
1168 vm_page_xunbusy_hard_tail(vm_page_t m)
1170 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1171 /* Wake the waiter. */
1176 * vm_page_xunbusy_hard:
1178 * Called when unbusy has failed because there is a waiter.
1181 vm_page_xunbusy_hard(vm_page_t m)
1183 vm_page_assert_xbusied(m);
1184 vm_page_xunbusy_hard_tail(m);
1188 vm_page_xunbusy_hard_unchecked(vm_page_t m)
1190 vm_page_assert_xbusied_unchecked(m);
1191 vm_page_xunbusy_hard_tail(m);
1195 vm_page_busy_free(vm_page_t m)
1199 atomic_thread_fence_rel();
1200 x = atomic_swap_int(&m->busy_lock, VPB_FREED);
1201 if ((x & VPB_BIT_WAITERS) != 0)
1206 * vm_page_unhold_pages:
1208 * Unhold each of the pages that is referenced by the given array.
1211 vm_page_unhold_pages(vm_page_t *ma, int count)
1214 for (; count != 0; count--) {
1215 vm_page_unwire(*ma, PQ_ACTIVE);
1221 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1225 #ifdef VM_PHYSSEG_SPARSE
1226 m = vm_phys_paddr_to_vm_page(pa);
1228 m = vm_phys_fictitious_to_vm_page(pa);
1230 #elif defined(VM_PHYSSEG_DENSE)
1234 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1235 m = &vm_page_array[pi - first_page];
1238 return (vm_phys_fictitious_to_vm_page(pa));
1240 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1247 * Create a fictitious page with the specified physical address and
1248 * memory attribute. The memory attribute is the only the machine-
1249 * dependent aspect of a fictitious page that must be initialized.
1252 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1256 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1257 vm_page_initfake(m, paddr, memattr);
1262 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1265 if ((m->flags & PG_FICTITIOUS) != 0) {
1267 * The page's memattr might have changed since the
1268 * previous initialization. Update the pmap to the
1273 m->phys_addr = paddr;
1274 m->a.queue = PQ_NONE;
1275 /* Fictitious pages don't use "segind". */
1276 m->flags = PG_FICTITIOUS;
1277 /* Fictitious pages don't use "order" or "pool". */
1278 m->oflags = VPO_UNMANAGED;
1279 m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
1280 /* Fictitious pages are unevictable. */
1284 pmap_page_set_memattr(m, memattr);
1290 * Release a fictitious page.
1293 vm_page_putfake(vm_page_t m)
1296 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1297 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1298 ("vm_page_putfake: bad page %p", m));
1299 vm_page_assert_xbusied(m);
1300 vm_page_busy_free(m);
1301 uma_zfree(fakepg_zone, m);
1305 * vm_page_updatefake:
1307 * Update the given fictitious page to the specified physical address and
1311 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1314 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1315 ("vm_page_updatefake: bad page %p", m));
1316 m->phys_addr = paddr;
1317 pmap_page_set_memattr(m, memattr);
1326 vm_page_free(vm_page_t m)
1329 m->flags &= ~PG_ZERO;
1330 vm_page_free_toq(m);
1334 * vm_page_free_zero:
1336 * Free a page to the zerod-pages queue
1339 vm_page_free_zero(vm_page_t m)
1342 m->flags |= PG_ZERO;
1343 vm_page_free_toq(m);
1347 * Unbusy and handle the page queueing for a page from a getpages request that
1348 * was optionally read ahead or behind.
1351 vm_page_readahead_finish(vm_page_t m)
1354 /* We shouldn't put invalid pages on queues. */
1355 KASSERT(!vm_page_none_valid(m), ("%s: %p is invalid", __func__, m));
1358 * Since the page is not the actually needed one, whether it should
1359 * be activated or deactivated is not obvious. Empirical results
1360 * have shown that deactivating the page is usually the best choice,
1361 * unless the page is wanted by another thread.
1363 if ((vm_page_busy_fetch(m) & VPB_BIT_WAITERS) != 0)
1364 vm_page_activate(m);
1366 vm_page_deactivate(m);
1367 vm_page_xunbusy_unchecked(m);
1371 * Destroy the identity of an invalid page and free it if possible.
1372 * This is intended to be used when reading a page from backing store fails.
1375 vm_page_free_invalid(vm_page_t m)
1378 KASSERT(vm_page_none_valid(m), ("page %p is valid", m));
1379 KASSERT(!pmap_page_is_mapped(m), ("page %p is mapped", m));
1380 KASSERT(m->object != NULL, ("page %p has no object", m));
1381 VM_OBJECT_ASSERT_WLOCKED(m->object);
1384 * We may be attempting to free the page as part of the handling for an
1385 * I/O error, in which case the page was xbusied by a different thread.
1387 vm_page_xbusy_claim(m);
1390 * If someone has wired this page while the object lock
1391 * was not held, then the thread that unwires is responsible
1392 * for freeing the page. Otherwise just free the page now.
1393 * The wire count of this unmapped page cannot change while
1394 * we have the page xbusy and the page's object wlocked.
1396 if (vm_page_remove(m))
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)
1550 vm_page_assert_xbusied(m);
1552 VM_OBJECT_ASSERT_WLOCKED(object);
1553 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1554 ("page %p is missing its object ref", m));
1556 /* Deferred free of swap space. */
1557 if ((m->a.flags & PGA_SWAP_FREE) != 0)
1558 vm_pager_page_unswapped(m);
1561 mrem = vm_radix_remove(&object->rtree, m->pindex);
1562 KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1565 * Now remove from the object's list of backed pages.
1567 TAILQ_REMOVE(&object->memq, m, listq);
1570 * And show that the object has one fewer resident page.
1572 object->resident_page_count--;
1575 * The vnode may now be recycled.
1577 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1578 vdrop(object->handle);
1584 * Removes the specified page from its containing object, but does not
1585 * invalidate any backing storage. Returns true if the object's reference
1586 * was the last reference to the page, and false otherwise.
1588 * The object must be locked and the page must be exclusively busied.
1589 * The exclusive busy will be released on return. If this is not the
1590 * final ref and the caller does not hold a wire reference it may not
1591 * continue to access the page.
1594 vm_page_remove(vm_page_t m)
1598 dropped = vm_page_remove_xbusy(m);
1605 * vm_page_remove_xbusy
1607 * Removes the page but leaves the xbusy held. Returns true if this
1608 * removed the final ref and false otherwise.
1611 vm_page_remove_xbusy(vm_page_t m)
1614 vm_page_object_remove(m);
1615 return (vm_page_drop(m, VPRC_OBJREF) == VPRC_OBJREF);
1621 * Returns the page associated with the object/offset
1622 * pair specified; if none is found, NULL is returned.
1624 * The object must be locked.
1627 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1630 VM_OBJECT_ASSERT_LOCKED(object);
1631 return (vm_radix_lookup(&object->rtree, pindex));
1635 * vm_page_lookup_unlocked:
1637 * Returns the page associated with the object/offset pair specified;
1638 * if none is found, NULL is returned. The page may be no longer be
1639 * present in the object at the time that this function returns. Only
1640 * useful for opportunistic checks such as inmem().
1643 vm_page_lookup_unlocked(vm_object_t object, vm_pindex_t pindex)
1646 return (vm_radix_lookup_unlocked(&object->rtree, pindex));
1652 * Returns a page that must already have been busied by
1653 * the caller. Used for bogus page replacement.
1656 vm_page_relookup(vm_object_t object, vm_pindex_t pindex)
1660 m = vm_radix_lookup_unlocked(&object->rtree, pindex);
1661 KASSERT(m != NULL && (vm_page_busied(m) || vm_page_wired(m)) &&
1662 m->object == object && m->pindex == pindex,
1663 ("vm_page_relookup: Invalid page %p", m));
1668 * This should only be used by lockless functions for releasing transient
1669 * incorrect acquires. The page may have been freed after we acquired a
1670 * busy lock. In this case busy_lock == VPB_FREED and we have nothing
1674 vm_page_busy_release(vm_page_t m)
1678 x = vm_page_busy_fetch(m);
1682 if ((x & VPB_BIT_SHARED) != 0 && VPB_SHARERS(x) > 1) {
1683 if (atomic_fcmpset_int(&m->busy_lock, &x,
1684 x - VPB_ONE_SHARER))
1688 KASSERT((x & VPB_BIT_SHARED) != 0 ||
1689 (x & ~VPB_BIT_WAITERS) == VPB_CURTHREAD_EXCLUSIVE,
1690 ("vm_page_busy_release: %p xbusy not owned.", m));
1691 if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
1693 if ((x & VPB_BIT_WAITERS) != 0)
1700 * vm_page_find_least:
1702 * Returns the page associated with the object with least pindex
1703 * greater than or equal to the parameter pindex, or NULL.
1705 * The object must be locked.
1708 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1712 VM_OBJECT_ASSERT_LOCKED(object);
1713 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1714 m = vm_radix_lookup_ge(&object->rtree, pindex);
1719 * Returns the given page's successor (by pindex) within the object if it is
1720 * resident; if none is found, NULL is returned.
1722 * The object must be locked.
1725 vm_page_next(vm_page_t m)
1729 VM_OBJECT_ASSERT_LOCKED(m->object);
1730 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1731 MPASS(next->object == m->object);
1732 if (next->pindex != m->pindex + 1)
1739 * Returns the given page's predecessor (by pindex) within the object if it is
1740 * resident; if none is found, NULL is returned.
1742 * The object must be locked.
1745 vm_page_prev(vm_page_t m)
1749 VM_OBJECT_ASSERT_LOCKED(m->object);
1750 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1751 MPASS(prev->object == m->object);
1752 if (prev->pindex != m->pindex - 1)
1759 * Uses the page mnew as a replacement for an existing page at index
1760 * pindex which must be already present in the object.
1762 * Both pages must be exclusively busied on enter. The old page is
1765 * A return value of true means mold is now free. If this is not the
1766 * final ref and the caller does not hold a wire reference it may not
1767 * continue to access the page.
1770 vm_page_replace_hold(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1776 VM_OBJECT_ASSERT_WLOCKED(object);
1777 vm_page_assert_xbusied(mold);
1778 KASSERT(mnew->object == NULL && (mnew->ref_count & VPRC_OBJREF) == 0,
1779 ("vm_page_replace: page %p already in object", mnew));
1782 * This function mostly follows vm_page_insert() and
1783 * vm_page_remove() without the radix, object count and vnode
1784 * dance. Double check such functions for more comments.
1787 mnew->object = object;
1788 mnew->pindex = pindex;
1789 atomic_set_int(&mnew->ref_count, VPRC_OBJREF);
1790 mret = vm_radix_replace(&object->rtree, mnew);
1791 KASSERT(mret == mold,
1792 ("invalid page replacement, mold=%p, mret=%p", mold, mret));
1793 KASSERT((mold->oflags & VPO_UNMANAGED) ==
1794 (mnew->oflags & VPO_UNMANAGED),
1795 ("vm_page_replace: mismatched VPO_UNMANAGED"));
1797 /* Keep the resident page list in sorted order. */
1798 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1799 TAILQ_REMOVE(&object->memq, mold, listq);
1800 mold->object = NULL;
1803 * The object's resident_page_count does not change because we have
1804 * swapped one page for another, but the generation count should
1805 * change if the page is dirty.
1807 if (pmap_page_is_write_mapped(mnew))
1808 vm_object_set_writeable_dirty(object);
1809 dropped = vm_page_drop(mold, VPRC_OBJREF) == VPRC_OBJREF;
1810 vm_page_xunbusy(mold);
1816 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1820 vm_page_assert_xbusied(mnew);
1822 if (vm_page_replace_hold(mnew, object, pindex, mold))
1829 * Move the given memory entry from its
1830 * current object to the specified target object/offset.
1832 * Note: swap associated with the page must be invalidated by the move. We
1833 * have to do this for several reasons: (1) we aren't freeing the
1834 * page, (2) we are dirtying the page, (3) the VM system is probably
1835 * moving the page from object A to B, and will then later move
1836 * the backing store from A to B and we can't have a conflict.
1838 * Note: we *always* dirty the page. It is necessary both for the
1839 * fact that we moved it, and because we may be invalidating
1842 * The objects must be locked.
1845 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1850 VM_OBJECT_ASSERT_WLOCKED(new_object);
1852 KASSERT(m->ref_count != 0, ("vm_page_rename: page %p has no refs", m));
1853 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1854 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1855 ("vm_page_rename: pindex already renamed"));
1858 * Create a custom version of vm_page_insert() which does not depend
1859 * by m_prev and can cheat on the implementation aspects of the
1863 m->pindex = new_pindex;
1864 if (vm_radix_insert(&new_object->rtree, m)) {
1870 * The operation cannot fail anymore. The removal must happen before
1871 * the listq iterator is tainted.
1874 vm_page_object_remove(m);
1876 /* Return back to the new pindex to complete vm_page_insert(). */
1877 m->pindex = new_pindex;
1878 m->object = new_object;
1880 vm_page_insert_radixdone(m, new_object, mpred);
1888 * Allocate and return a page that is associated with the specified
1889 * object and offset pair. By default, this page is exclusive busied.
1891 * The caller must always specify an allocation class.
1893 * allocation classes:
1894 * VM_ALLOC_NORMAL normal process request
1895 * VM_ALLOC_SYSTEM system *really* needs a page
1896 * VM_ALLOC_INTERRUPT interrupt time request
1898 * optional allocation flags:
1899 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1900 * intends to allocate
1901 * VM_ALLOC_NOBUSY do not exclusive busy the page
1902 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1903 * VM_ALLOC_SBUSY shared busy the allocated page
1904 * VM_ALLOC_WIRED wire the allocated page
1905 * VM_ALLOC_ZERO prefer a zeroed page
1908 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1911 return (vm_page_alloc_after(object, pindex, req,
1912 vm_radix_lookup_le(&object->rtree, pindex)));
1916 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1920 return (vm_page_alloc_domain_after(object, pindex, domain, req,
1921 vm_radix_lookup_le(&object->rtree, pindex)));
1925 * Allocate a page in the specified object with the given page index. To
1926 * optimize insertion of the page into the object, the caller must also specifiy
1927 * the resident page in the object with largest index smaller than the given
1928 * page index, or NULL if no such page exists.
1931 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1932 int req, vm_page_t mpred)
1934 struct vm_domainset_iter di;
1938 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1940 m = vm_page_alloc_domain_after(object, pindex, domain, req,
1944 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
1950 * Returns true if the number of free pages exceeds the minimum
1951 * for the request class and false otherwise.
1954 _vm_domain_allocate(struct vm_domain *vmd, int req_class, int npages)
1956 u_int limit, old, new;
1958 if (req_class == VM_ALLOC_INTERRUPT)
1960 else if (req_class == VM_ALLOC_SYSTEM)
1961 limit = vmd->vmd_interrupt_free_min;
1963 limit = vmd->vmd_free_reserved;
1966 * Attempt to reserve the pages. Fail if we're below the limit.
1969 old = vmd->vmd_free_count;
1974 } while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
1976 /* Wake the page daemon if we've crossed the threshold. */
1977 if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
1978 pagedaemon_wakeup(vmd->vmd_domain);
1980 /* Only update bitsets on transitions. */
1981 if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
1982 (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
1989 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
1994 * The page daemon is allowed to dig deeper into the free page list.
1996 req_class = req & VM_ALLOC_CLASS_MASK;
1997 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1998 req_class = VM_ALLOC_SYSTEM;
1999 return (_vm_domain_allocate(vmd, req_class, npages));
2003 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
2004 int req, vm_page_t mpred)
2006 struct vm_domain *vmd;
2010 #define VPA_FLAGS (VM_ALLOC_CLASS_MASK | VM_ALLOC_WAITFAIL | \
2011 VM_ALLOC_NOWAIT | VM_ALLOC_NOBUSY | \
2012 VM_ALLOC_SBUSY | VM_ALLOC_WIRED | \
2013 VM_ALLOC_NODUMP | VM_ALLOC_ZERO | VM_ALLOC_COUNT_MASK)
2014 KASSERT((req & ~VPA_FLAGS) == 0,
2015 ("invalid request %#x", req));
2016 KASSERT(((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2017 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2018 ("invalid request %#x", req));
2019 KASSERT(mpred == NULL || mpred->pindex < pindex,
2020 ("mpred %p doesn't precede pindex 0x%jx", mpred,
2021 (uintmax_t)pindex));
2022 VM_OBJECT_ASSERT_WLOCKED(object);
2027 #if VM_NRESERVLEVEL > 0
2029 * Can we allocate the page from a reservation?
2031 if (vm_object_reserv(object) &&
2032 (m = vm_reserv_alloc_page(object, pindex, domain, req, mpred)) !=
2037 vmd = VM_DOMAIN(domain);
2038 if (vmd->vmd_pgcache[VM_FREEPOOL_DEFAULT].zone != NULL) {
2039 m = uma_zalloc(vmd->vmd_pgcache[VM_FREEPOOL_DEFAULT].zone,
2042 flags |= PG_PCPU_CACHE;
2046 if (vm_domain_allocate(vmd, req, 1)) {
2048 * If not, allocate it from the free page queues.
2050 vm_domain_free_lock(vmd);
2051 m = vm_phys_alloc_pages(domain, VM_FREEPOOL_DEFAULT, 0);
2052 vm_domain_free_unlock(vmd);
2054 vm_domain_freecnt_inc(vmd, 1);
2055 #if VM_NRESERVLEVEL > 0
2056 if (vm_reserv_reclaim_inactive(domain))
2063 * Not allocatable, give up.
2065 if (vm_domain_alloc_fail(vmd, object, req))
2071 * At this point we had better have found a good page.
2075 vm_page_alloc_check(m);
2078 * Initialize the page. Only the PG_ZERO flag is inherited.
2080 flags |= m->flags & PG_ZERO;
2081 if ((req & VM_ALLOC_NODUMP) != 0)
2085 m->oflags = (object->flags & OBJ_UNMANAGED) != 0 ? VPO_UNMANAGED : 0;
2086 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
2087 m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2088 else if ((req & VM_ALLOC_SBUSY) != 0)
2089 m->busy_lock = VPB_SHARERS_WORD(1);
2091 m->busy_lock = VPB_UNBUSIED;
2092 if (req & VM_ALLOC_WIRED) {
2098 if (vm_page_insert_after(m, object, pindex, mpred)) {
2099 if (req & VM_ALLOC_WIRED) {
2103 KASSERT(m->object == NULL, ("page %p has object", m));
2104 m->oflags = VPO_UNMANAGED;
2105 m->busy_lock = VPB_UNBUSIED;
2106 /* Don't change PG_ZERO. */
2107 vm_page_free_toq(m);
2108 if (req & VM_ALLOC_WAITFAIL) {
2109 VM_OBJECT_WUNLOCK(object);
2111 VM_OBJECT_WLOCK(object);
2116 /* Ignore device objects; the pager sets "memattr" for them. */
2117 if (object->memattr != VM_MEMATTR_DEFAULT &&
2118 (object->flags & OBJ_FICTITIOUS) == 0)
2119 pmap_page_set_memattr(m, object->memattr);
2125 * vm_page_alloc_contig:
2127 * Allocate a contiguous set of physical pages of the given size "npages"
2128 * from the free lists. All of the physical pages must be at or above
2129 * the given physical address "low" and below the given physical address
2130 * "high". The given value "alignment" determines the alignment of the
2131 * first physical page in the set. If the given value "boundary" is
2132 * non-zero, then the set of physical pages cannot cross any physical
2133 * address boundary that is a multiple of that value. Both "alignment"
2134 * and "boundary" must be a power of two.
2136 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
2137 * then the memory attribute setting for the physical pages is configured
2138 * to the object's memory attribute setting. Otherwise, the memory
2139 * attribute setting for the physical pages is configured to "memattr",
2140 * overriding the object's memory attribute setting. However, if the
2141 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
2142 * memory attribute setting for the physical pages cannot be configured
2143 * to VM_MEMATTR_DEFAULT.
2145 * The specified object may not contain fictitious pages.
2147 * The caller must always specify an allocation class.
2149 * allocation classes:
2150 * VM_ALLOC_NORMAL normal process request
2151 * VM_ALLOC_SYSTEM system *really* needs a page
2152 * VM_ALLOC_INTERRUPT interrupt time request
2154 * optional allocation flags:
2155 * VM_ALLOC_NOBUSY do not exclusive busy the page
2156 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
2157 * VM_ALLOC_SBUSY shared busy the allocated page
2158 * VM_ALLOC_WIRED wire the allocated page
2159 * VM_ALLOC_ZERO prefer a zeroed page
2162 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
2163 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2164 vm_paddr_t boundary, vm_memattr_t memattr)
2166 struct vm_domainset_iter di;
2170 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
2172 m = vm_page_alloc_contig_domain(object, pindex, domain, req,
2173 npages, low, high, alignment, boundary, memattr);
2176 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
2182 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
2183 int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2184 vm_paddr_t boundary, vm_memattr_t memattr)
2186 struct vm_domain *vmd;
2187 vm_page_t m, m_ret, mpred;
2188 u_int busy_lock, flags, oflags;
2190 #define VPAC_FLAGS (VPA_FLAGS | VM_ALLOC_NORECLAIM)
2191 KASSERT((req & ~VPAC_FLAGS) == 0,
2192 ("invalid request %#x", req));
2193 KASSERT(((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2194 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2195 ("invalid request %#x", req));
2196 KASSERT((req & (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM)) !=
2197 (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM),
2198 ("invalid request %#x", req));
2199 VM_OBJECT_ASSERT_WLOCKED(object);
2200 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2201 ("vm_page_alloc_contig: object %p has fictitious pages",
2203 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2205 mpred = vm_radix_lookup_le(&object->rtree, pindex);
2206 KASSERT(mpred == NULL || mpred->pindex != pindex,
2207 ("vm_page_alloc_contig: pindex already allocated"));
2210 * Can we allocate the pages without the number of free pages falling
2211 * below the lower bound for the allocation class?
2215 #if VM_NRESERVLEVEL > 0
2217 * Can we allocate the pages from a reservation?
2219 if (vm_object_reserv(object) &&
2220 (m_ret = vm_reserv_alloc_contig(object, pindex, domain, req,
2221 mpred, npages, low, high, alignment, boundary)) != NULL) {
2225 vmd = VM_DOMAIN(domain);
2226 if (vm_domain_allocate(vmd, req, npages)) {
2228 * allocate them from the free page queues.
2230 vm_domain_free_lock(vmd);
2231 m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2232 alignment, boundary);
2233 vm_domain_free_unlock(vmd);
2234 if (m_ret == NULL) {
2235 vm_domain_freecnt_inc(vmd, npages);
2236 #if VM_NRESERVLEVEL > 0
2237 if ((req & VM_ALLOC_NORECLAIM) == 0 &&
2238 vm_reserv_reclaim_contig(domain, npages, low,
2239 high, alignment, boundary))
2244 if (m_ret == NULL) {
2245 if (vm_domain_alloc_fail(vmd, object, req))
2249 #if VM_NRESERVLEVEL > 0
2252 for (m = m_ret; m < &m_ret[npages]; m++) {
2254 vm_page_alloc_check(m);
2258 * Initialize the pages. Only the PG_ZERO flag is inherited.
2261 if ((req & VM_ALLOC_NODUMP) != 0)
2263 oflags = (object->flags & OBJ_UNMANAGED) != 0 ? VPO_UNMANAGED : 0;
2264 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
2265 busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2266 else if ((req & VM_ALLOC_SBUSY) != 0)
2267 busy_lock = VPB_SHARERS_WORD(1);
2269 busy_lock = VPB_UNBUSIED;
2270 if ((req & VM_ALLOC_WIRED) != 0)
2271 vm_wire_add(npages);
2272 if (object->memattr != VM_MEMATTR_DEFAULT &&
2273 memattr == VM_MEMATTR_DEFAULT)
2274 memattr = object->memattr;
2275 for (m = m_ret; m < &m_ret[npages]; m++) {
2277 m->flags = (m->flags | PG_NODUMP) & flags;
2278 m->busy_lock = busy_lock;
2279 if ((req & VM_ALLOC_WIRED) != 0)
2283 if (vm_page_insert_after(m, object, pindex, mpred)) {
2284 if ((req & VM_ALLOC_WIRED) != 0)
2285 vm_wire_sub(npages);
2286 KASSERT(m->object == NULL,
2287 ("page %p has object", m));
2289 for (m = m_ret; m < &m_ret[npages]; m++) {
2291 (req & VM_ALLOC_WIRED) != 0)
2293 m->oflags = VPO_UNMANAGED;
2294 m->busy_lock = VPB_UNBUSIED;
2295 /* Don't change PG_ZERO. */
2296 vm_page_free_toq(m);
2298 if (req & VM_ALLOC_WAITFAIL) {
2299 VM_OBJECT_WUNLOCK(object);
2301 VM_OBJECT_WLOCK(object);
2306 if (memattr != VM_MEMATTR_DEFAULT)
2307 pmap_page_set_memattr(m, memattr);
2314 * Allocate a physical page that is not intended to be inserted into a VM
2315 * object. If the "freelist" parameter is not equal to VM_NFREELIST, then only
2316 * pages from the specified vm_phys freelist will be returned.
2318 static __always_inline vm_page_t
2319 _vm_page_alloc_noobj_domain(int domain, const int freelist, int req)
2321 struct vm_domain *vmd;
2325 #define VPAN_FLAGS (VM_ALLOC_CLASS_MASK | VM_ALLOC_WAITFAIL | \
2326 VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | \
2327 VM_ALLOC_NOBUSY | VM_ALLOC_WIRED | \
2328 VM_ALLOC_NODUMP | VM_ALLOC_ZERO | VM_ALLOC_COUNT_MASK)
2329 KASSERT((req & ~VPAN_FLAGS) == 0,
2330 ("invalid request %#x", req));
2332 flags = (req & VM_ALLOC_NODUMP) != 0 ? PG_NODUMP : 0;
2333 vmd = VM_DOMAIN(domain);
2335 if (freelist == VM_NFREELIST &&
2336 vmd->vmd_pgcache[VM_FREEPOOL_DIRECT].zone != NULL) {
2337 m = uma_zalloc(vmd->vmd_pgcache[VM_FREEPOOL_DIRECT].zone,
2340 flags |= PG_PCPU_CACHE;
2345 if (vm_domain_allocate(vmd, req, 1)) {
2346 vm_domain_free_lock(vmd);
2347 if (freelist == VM_NFREELIST)
2348 m = vm_phys_alloc_pages(domain, VM_FREEPOOL_DIRECT, 0);
2350 m = vm_phys_alloc_freelist_pages(domain, freelist,
2351 VM_FREEPOOL_DIRECT, 0);
2352 vm_domain_free_unlock(vmd);
2354 vm_domain_freecnt_inc(vmd, 1);
2355 #if VM_NRESERVLEVEL > 0
2356 if (freelist == VM_NFREELIST &&
2357 vm_reserv_reclaim_inactive(domain))
2363 if (vm_domain_alloc_fail(vmd, NULL, req))
2370 vm_page_alloc_check(m);
2373 * Consumers should not rely on a useful default pindex value.
2375 m->pindex = 0xdeadc0dedeadc0de;
2376 m->flags = (m->flags & PG_ZERO) | flags;
2378 m->oflags = VPO_UNMANAGED;
2379 m->busy_lock = VPB_UNBUSIED;
2380 if ((req & VM_ALLOC_WIRED) != 0) {
2385 if ((req & VM_ALLOC_ZERO) != 0 && (m->flags & PG_ZERO) == 0)
2392 vm_page_alloc_freelist(int freelist, int req)
2394 struct vm_domainset_iter di;
2398 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2400 m = vm_page_alloc_freelist_domain(domain, freelist, req);
2403 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2409 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2411 KASSERT(freelist >= 0 && freelist < VM_NFREELIST,
2412 ("%s: invalid freelist %d", __func__, freelist));
2414 return (_vm_page_alloc_noobj_domain(domain, freelist, req));
2418 vm_page_alloc_noobj(int req)
2420 struct vm_domainset_iter di;
2424 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2426 m = vm_page_alloc_noobj_domain(domain, req);
2429 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2435 vm_page_alloc_noobj_domain(int domain, int req)
2437 return (_vm_page_alloc_noobj_domain(domain, VM_NFREELIST, req));
2441 vm_page_alloc_noobj_contig(int req, u_long npages, vm_paddr_t low,
2442 vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
2443 vm_memattr_t memattr)
2445 struct vm_domainset_iter di;
2449 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2451 m = vm_page_alloc_noobj_contig_domain(domain, req, npages, low,
2452 high, alignment, boundary, memattr);
2455 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2461 vm_page_alloc_noobj_contig_domain(int domain, int req, u_long npages,
2462 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
2463 vm_memattr_t memattr)
2465 struct vm_domain *vmd;
2469 #define VPANC_FLAGS (VPAN_FLAGS | VM_ALLOC_NORECLAIM)
2470 KASSERT((req & ~VPANC_FLAGS) == 0,
2471 ("invalid request %#x", req));
2472 KASSERT((req & (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM)) !=
2473 (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM),
2474 ("invalid request %#x", req));
2475 KASSERT(((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2476 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2477 ("invalid request %#x", req));
2478 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2482 vmd = VM_DOMAIN(domain);
2483 if (vm_domain_allocate(vmd, req, npages)) {
2485 * allocate them from the free page queues.
2487 vm_domain_free_lock(vmd);
2488 m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2489 alignment, boundary);
2490 vm_domain_free_unlock(vmd);
2491 if (m_ret == NULL) {
2492 vm_domain_freecnt_inc(vmd, npages);
2493 #if VM_NRESERVLEVEL > 0
2494 if ((req & VM_ALLOC_NORECLAIM) == 0 &&
2495 vm_reserv_reclaim_contig(domain, npages, low,
2496 high, alignment, boundary))
2501 if (m_ret == NULL) {
2502 if (vm_domain_alloc_fail(vmd, NULL, req))
2508 * Initialize the pages. Only the PG_ZERO flag is inherited.
2511 if ((req & VM_ALLOC_NODUMP) != 0)
2513 if ((req & VM_ALLOC_WIRED) != 0)
2514 vm_wire_add(npages);
2515 for (m = m_ret; m < &m_ret[npages]; m++) {
2517 vm_page_alloc_check(m);
2520 * Consumers should not rely on a useful default pindex value.
2522 m->pindex = 0xdeadc0dedeadc0de;
2524 m->flags = (m->flags | PG_NODUMP) & flags;
2525 m->busy_lock = VPB_UNBUSIED;
2526 if ((req & VM_ALLOC_WIRED) != 0)
2529 m->oflags = VPO_UNMANAGED;
2532 * Zero the page before updating any mappings since the page is
2533 * not yet shared with any devices which might require the
2534 * non-default memory attribute. pmap_page_set_memattr()
2535 * flushes data caches before returning.
2537 if ((req & VM_ALLOC_ZERO) != 0 && (m->flags & PG_ZERO) == 0)
2539 if (memattr != VM_MEMATTR_DEFAULT)
2540 pmap_page_set_memattr(m, memattr);
2546 * Check a page that has been freshly dequeued from a freelist.
2549 vm_page_alloc_check(vm_page_t m)
2552 KASSERT(m->object == NULL, ("page %p has object", m));
2553 KASSERT(m->a.queue == PQ_NONE &&
2554 (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
2555 ("page %p has unexpected queue %d, flags %#x",
2556 m, m->a.queue, (m->a.flags & PGA_QUEUE_STATE_MASK)));
2557 KASSERT(m->ref_count == 0, ("page %p has references", m));
2558 KASSERT(vm_page_busy_freed(m), ("page %p is not freed", m));
2559 KASSERT(m->dirty == 0, ("page %p is dirty", m));
2560 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2561 ("page %p has unexpected memattr %d",
2562 m, pmap_page_get_memattr(m)));
2563 KASSERT(m->valid == 0, ("free page %p is valid", m));
2564 pmap_vm_page_alloc_check(m);
2568 vm_page_zone_import(void *arg, void **store, int cnt, int domain, int flags)
2570 struct vm_domain *vmd;
2571 struct vm_pgcache *pgcache;
2575 vmd = VM_DOMAIN(pgcache->domain);
2578 * The page daemon should avoid creating extra memory pressure since its
2579 * main purpose is to replenish the store of free pages.
2581 if (vmd->vmd_severeset || curproc == pageproc ||
2582 !_vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2584 domain = vmd->vmd_domain;
2585 vm_domain_free_lock(vmd);
2586 i = vm_phys_alloc_npages(domain, pgcache->pool, cnt,
2587 (vm_page_t *)store);
2588 vm_domain_free_unlock(vmd);
2590 vm_domain_freecnt_inc(vmd, cnt - i);
2596 vm_page_zone_release(void *arg, void **store, int cnt)
2598 struct vm_domain *vmd;
2599 struct vm_pgcache *pgcache;
2604 vmd = VM_DOMAIN(pgcache->domain);
2605 vm_domain_free_lock(vmd);
2606 for (i = 0; i < cnt; i++) {
2607 m = (vm_page_t)store[i];
2608 vm_phys_free_pages(m, 0);
2610 vm_domain_free_unlock(vmd);
2611 vm_domain_freecnt_inc(vmd, cnt);
2614 #define VPSC_ANY 0 /* No restrictions. */
2615 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2616 #define VPSC_NOSUPER 2 /* Skip superpages. */
2619 * vm_page_scan_contig:
2621 * Scan vm_page_array[] between the specified entries "m_start" and
2622 * "m_end" for a run of contiguous physical pages that satisfy the
2623 * specified conditions, and return the lowest page in the run. The
2624 * specified "alignment" determines the alignment of the lowest physical
2625 * page in the run. If the specified "boundary" is non-zero, then the
2626 * run of physical pages cannot span a physical address that is a
2627 * multiple of "boundary".
2629 * "m_end" is never dereferenced, so it need not point to a vm_page
2630 * structure within vm_page_array[].
2632 * "npages" must be greater than zero. "m_start" and "m_end" must not
2633 * span a hole (or discontiguity) in the physical address space. Both
2634 * "alignment" and "boundary" must be a power of two.
2637 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2638 u_long alignment, vm_paddr_t boundary, int options)
2643 #if VM_NRESERVLEVEL > 0
2646 int m_inc, order, run_ext, run_len;
2648 KASSERT(npages > 0, ("npages is 0"));
2649 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2650 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2653 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2654 KASSERT((m->flags & PG_MARKER) == 0,
2655 ("page %p is PG_MARKER", m));
2656 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->ref_count >= 1,
2657 ("fictitious page %p has invalid ref count", m));
2660 * If the current page would be the start of a run, check its
2661 * physical address against the end, alignment, and boundary
2662 * conditions. If it doesn't satisfy these conditions, either
2663 * terminate the scan or advance to the next page that
2664 * satisfies the failed condition.
2667 KASSERT(m_run == NULL, ("m_run != NULL"));
2668 if (m + npages > m_end)
2670 pa = VM_PAGE_TO_PHYS(m);
2671 if ((pa & (alignment - 1)) != 0) {
2672 m_inc = atop(roundup2(pa, alignment) - pa);
2675 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2677 m_inc = atop(roundup2(pa, boundary) - pa);
2681 KASSERT(m_run != NULL, ("m_run == NULL"));
2685 if (vm_page_wired(m))
2687 #if VM_NRESERVLEVEL > 0
2688 else if ((level = vm_reserv_level(m)) >= 0 &&
2689 (options & VPSC_NORESERV) != 0) {
2691 /* Advance to the end of the reservation. */
2692 pa = VM_PAGE_TO_PHYS(m);
2693 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2697 else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2699 * The page is considered eligible for relocation if
2700 * and only if it could be laundered or reclaimed by
2703 VM_OBJECT_RLOCK(object);
2704 if (object != m->object) {
2705 VM_OBJECT_RUNLOCK(object);
2708 /* Don't care: PG_NODUMP, PG_ZERO. */
2709 if (object->type != OBJT_DEFAULT &&
2710 (object->flags & OBJ_SWAP) == 0 &&
2711 object->type != OBJT_VNODE) {
2713 #if VM_NRESERVLEVEL > 0
2714 } else if ((options & VPSC_NOSUPER) != 0 &&
2715 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2717 /* Advance to the end of the superpage. */
2718 pa = VM_PAGE_TO_PHYS(m);
2719 m_inc = atop(roundup2(pa + 1,
2720 vm_reserv_size(level)) - pa);
2722 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2723 vm_page_queue(m) != PQ_NONE && !vm_page_busied(m)) {
2725 * The page is allocated but eligible for
2726 * relocation. Extend the current run by one
2729 KASSERT(pmap_page_get_memattr(m) ==
2731 ("page %p has an unexpected memattr", m));
2732 KASSERT((m->oflags & (VPO_SWAPINPROG |
2733 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2734 ("page %p has unexpected oflags", m));
2735 /* Don't care: PGA_NOSYNC. */
2739 VM_OBJECT_RUNLOCK(object);
2740 #if VM_NRESERVLEVEL > 0
2741 } else if (level >= 0) {
2743 * The page is reserved but not yet allocated. In
2744 * other words, it is still free. Extend the current
2749 } else if ((order = m->order) < VM_NFREEORDER) {
2751 * The page is enqueued in the physical memory
2752 * allocator's free page queues. Moreover, it is the
2753 * first page in a power-of-two-sized run of
2754 * contiguous free pages. Add these pages to the end
2755 * of the current run, and jump ahead.
2757 run_ext = 1 << order;
2761 * Skip the page for one of the following reasons: (1)
2762 * It is enqueued in the physical memory allocator's
2763 * free page queues. However, it is not the first
2764 * page in a run of contiguous free pages. (This case
2765 * rarely occurs because the scan is performed in
2766 * ascending order.) (2) It is not reserved, and it is
2767 * transitioning from free to allocated. (Conversely,
2768 * the transition from allocated to free for managed
2769 * pages is blocked by the page busy lock.) (3) It is
2770 * allocated but not contained by an object and not
2771 * wired, e.g., allocated by Xen's balloon driver.
2777 * Extend or reset the current run of pages.
2790 if (run_len >= npages)
2796 * vm_page_reclaim_run:
2798 * Try to relocate each of the allocated virtual pages within the
2799 * specified run of physical pages to a new physical address. Free the
2800 * physical pages underlying the relocated virtual pages. A virtual page
2801 * is relocatable if and only if it could be laundered or reclaimed by
2802 * the page daemon. Whenever possible, a virtual page is relocated to a
2803 * physical address above "high".
2805 * Returns 0 if every physical page within the run was already free or
2806 * just freed by a successful relocation. Otherwise, returns a non-zero
2807 * value indicating why the last attempt to relocate a virtual page was
2810 * "req_class" must be an allocation class.
2813 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2816 struct vm_domain *vmd;
2817 struct spglist free;
2820 vm_page_t m, m_end, m_new;
2821 int error, order, req;
2823 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2824 ("req_class is not an allocation class"));
2828 m_end = m_run + npages;
2829 for (; error == 0 && m < m_end; m++) {
2830 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2831 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2834 * Racily check for wirings. Races are handled once the object
2835 * lock is held and the page is unmapped.
2837 if (vm_page_wired(m))
2839 else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2841 * The page is relocated if and only if it could be
2842 * laundered or reclaimed by the page daemon.
2844 VM_OBJECT_WLOCK(object);
2845 /* Don't care: PG_NODUMP, PG_ZERO. */
2846 if (m->object != object ||
2847 (object->type != OBJT_DEFAULT &&
2848 (object->flags & OBJ_SWAP) == 0 &&
2849 object->type != OBJT_VNODE))
2851 else if (object->memattr != VM_MEMATTR_DEFAULT)
2853 else if (vm_page_queue(m) != PQ_NONE &&
2854 vm_page_tryxbusy(m) != 0) {
2855 if (vm_page_wired(m)) {
2860 KASSERT(pmap_page_get_memattr(m) ==
2862 ("page %p has an unexpected memattr", m));
2863 KASSERT(m->oflags == 0,
2864 ("page %p has unexpected oflags", m));
2865 /* Don't care: PGA_NOSYNC. */
2866 if (!vm_page_none_valid(m)) {
2868 * First, try to allocate a new page
2869 * that is above "high". Failing
2870 * that, try to allocate a new page
2871 * that is below "m_run". Allocate
2872 * the new page between the end of
2873 * "m_run" and "high" only as a last
2877 if ((m->flags & PG_NODUMP) != 0)
2878 req |= VM_ALLOC_NODUMP;
2879 if (trunc_page(high) !=
2880 ~(vm_paddr_t)PAGE_MASK) {
2882 vm_page_alloc_noobj_contig(
2883 req, 1, round_page(high),
2884 ~(vm_paddr_t)0, PAGE_SIZE,
2885 0, VM_MEMATTR_DEFAULT);
2888 if (m_new == NULL) {
2889 pa = VM_PAGE_TO_PHYS(m_run);
2891 vm_page_alloc_noobj_contig(
2894 VM_MEMATTR_DEFAULT);
2896 if (m_new == NULL) {
2899 vm_page_alloc_noobj_contig(
2900 req, 1, pa, high, PAGE_SIZE,
2901 0, VM_MEMATTR_DEFAULT);
2903 if (m_new == NULL) {
2910 * Unmap the page and check for new
2911 * wirings that may have been acquired
2912 * through a pmap lookup.
2914 if (object->ref_count != 0 &&
2915 !vm_page_try_remove_all(m)) {
2917 vm_page_free(m_new);
2923 * Replace "m" with the new page. For
2924 * vm_page_replace(), "m" must be busy
2925 * and dequeued. Finally, change "m"
2926 * as if vm_page_free() was called.
2928 m_new->a.flags = m->a.flags &
2929 ~PGA_QUEUE_STATE_MASK;
2930 KASSERT(m_new->oflags == VPO_UNMANAGED,
2931 ("page %p is managed", m_new));
2933 pmap_copy_page(m, m_new);
2934 m_new->valid = m->valid;
2935 m_new->dirty = m->dirty;
2936 m->flags &= ~PG_ZERO;
2938 if (vm_page_replace_hold(m_new, object,
2940 vm_page_free_prep(m))
2941 SLIST_INSERT_HEAD(&free, m,
2945 * The new page must be deactivated
2946 * before the object is unlocked.
2948 vm_page_deactivate(m_new);
2950 m->flags &= ~PG_ZERO;
2952 if (vm_page_free_prep(m))
2953 SLIST_INSERT_HEAD(&free, m,
2955 KASSERT(m->dirty == 0,
2956 ("page %p is dirty", m));
2961 VM_OBJECT_WUNLOCK(object);
2963 MPASS(vm_page_domain(m) == domain);
2964 vmd = VM_DOMAIN(domain);
2965 vm_domain_free_lock(vmd);
2967 if (order < VM_NFREEORDER) {
2969 * The page is enqueued in the physical memory
2970 * allocator's free page queues. Moreover, it
2971 * is the first page in a power-of-two-sized
2972 * run of contiguous free pages. Jump ahead
2973 * to the last page within that run, and
2974 * continue from there.
2976 m += (1 << order) - 1;
2978 #if VM_NRESERVLEVEL > 0
2979 else if (vm_reserv_is_page_free(m))
2982 vm_domain_free_unlock(vmd);
2983 if (order == VM_NFREEORDER)
2987 if ((m = SLIST_FIRST(&free)) != NULL) {
2990 vmd = VM_DOMAIN(domain);
2992 vm_domain_free_lock(vmd);
2994 MPASS(vm_page_domain(m) == domain);
2995 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2996 vm_phys_free_pages(m, 0);
2998 } while ((m = SLIST_FIRST(&free)) != NULL);
2999 vm_domain_free_unlock(vmd);
3000 vm_domain_freecnt_inc(vmd, cnt);
3007 CTASSERT(powerof2(NRUNS));
3009 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
3011 #define MIN_RECLAIM 8
3014 * vm_page_reclaim_contig:
3016 * Reclaim allocated, contiguous physical memory satisfying the specified
3017 * conditions by relocating the virtual pages using that physical memory.
3018 * Returns true if reclamation is successful and false otherwise. Since
3019 * relocation requires the allocation of physical pages, reclamation may
3020 * fail due to a shortage of free pages. When reclamation fails, callers
3021 * are expected to perform vm_wait() before retrying a failed allocation
3022 * operation, e.g., vm_page_alloc_contig().
3024 * The caller must always specify an allocation class through "req".
3026 * allocation classes:
3027 * VM_ALLOC_NORMAL normal process request
3028 * VM_ALLOC_SYSTEM system *really* needs a page
3029 * VM_ALLOC_INTERRUPT interrupt time request
3031 * The optional allocation flags are ignored.
3033 * "npages" must be greater than zero. Both "alignment" and "boundary"
3034 * must be a power of two.
3037 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
3038 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
3040 struct vm_domain *vmd;
3041 vm_paddr_t curr_low;
3042 vm_page_t m_run, m_runs[NRUNS];
3043 u_long count, minalign, reclaimed;
3044 int error, i, options, req_class;
3046 KASSERT(npages > 0, ("npages is 0"));
3047 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
3048 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
3051 * The caller will attempt an allocation after some runs have been
3052 * reclaimed and added to the vm_phys buddy lists. Due to limitations
3053 * of vm_phys_alloc_contig(), round up the requested length to the next
3054 * power of two or maximum chunk size, and ensure that each run is
3057 minalign = 1ul << imin(flsl(npages - 1), VM_NFREEORDER - 1);
3058 npages = roundup2(npages, minalign);
3059 if (alignment < ptoa(minalign))
3060 alignment = ptoa(minalign);
3063 * The page daemon is allowed to dig deeper into the free page list.
3065 req_class = req & VM_ALLOC_CLASS_MASK;
3066 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
3067 req_class = VM_ALLOC_SYSTEM;
3070 * Return if the number of free pages cannot satisfy the requested
3073 vmd = VM_DOMAIN(domain);
3074 count = vmd->vmd_free_count;
3075 if (count < npages + vmd->vmd_free_reserved || (count < npages +
3076 vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
3077 (count < npages && req_class == VM_ALLOC_INTERRUPT))
3081 * Scan up to three times, relaxing the restrictions ("options") on
3082 * the reclamation of reservations and superpages each time.
3084 for (options = VPSC_NORESERV;;) {
3086 * Find the highest runs that satisfy the given constraints
3087 * and restrictions, and record them in "m_runs".
3092 m_run = vm_phys_scan_contig(domain, npages, curr_low,
3093 high, alignment, boundary, options);
3096 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
3097 m_runs[RUN_INDEX(count)] = m_run;
3102 * Reclaim the highest runs in LIFO (descending) order until
3103 * the number of reclaimed pages, "reclaimed", is at least
3104 * MIN_RECLAIM. Reset "reclaimed" each time because each
3105 * reclamation is idempotent, and runs will (likely) recur
3106 * from one scan to the next as restrictions are relaxed.
3109 for (i = 0; count > 0 && i < NRUNS; i++) {
3111 m_run = m_runs[RUN_INDEX(count)];
3112 error = vm_page_reclaim_run(req_class, domain, npages,
3115 reclaimed += npages;
3116 if (reclaimed >= MIN_RECLAIM)
3122 * Either relax the restrictions on the next scan or return if
3123 * the last scan had no restrictions.
3125 if (options == VPSC_NORESERV)
3126 options = VPSC_NOSUPER;
3127 else if (options == VPSC_NOSUPER)
3129 else if (options == VPSC_ANY)
3130 return (reclaimed != 0);
3135 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
3136 u_long alignment, vm_paddr_t boundary)
3138 struct vm_domainset_iter di;
3142 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
3144 ret = vm_page_reclaim_contig_domain(domain, req, npages, low,
3145 high, alignment, boundary);
3148 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
3154 * Set the domain in the appropriate page level domainset.
3157 vm_domain_set(struct vm_domain *vmd)
3160 mtx_lock(&vm_domainset_lock);
3161 if (!vmd->vmd_minset && vm_paging_min(vmd)) {
3162 vmd->vmd_minset = 1;
3163 DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
3165 if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
3166 vmd->vmd_severeset = 1;
3167 DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
3169 mtx_unlock(&vm_domainset_lock);
3173 * Clear the domain from the appropriate page level domainset.
3176 vm_domain_clear(struct vm_domain *vmd)
3179 mtx_lock(&vm_domainset_lock);
3180 if (vmd->vmd_minset && !vm_paging_min(vmd)) {
3181 vmd->vmd_minset = 0;
3182 DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
3183 if (vm_min_waiters != 0) {
3185 wakeup(&vm_min_domains);
3188 if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
3189 vmd->vmd_severeset = 0;
3190 DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
3191 if (vm_severe_waiters != 0) {
3192 vm_severe_waiters = 0;
3193 wakeup(&vm_severe_domains);
3198 * If pageout daemon needs pages, then tell it that there are
3201 if (vmd->vmd_pageout_pages_needed &&
3202 vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
3203 wakeup(&vmd->vmd_pageout_pages_needed);
3204 vmd->vmd_pageout_pages_needed = 0;
3207 /* See comments in vm_wait_doms(). */
3208 if (vm_pageproc_waiters) {
3209 vm_pageproc_waiters = 0;
3210 wakeup(&vm_pageproc_waiters);
3212 mtx_unlock(&vm_domainset_lock);
3216 * Wait for free pages to exceed the min threshold globally.
3222 mtx_lock(&vm_domainset_lock);
3223 while (vm_page_count_min()) {
3225 msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
3227 mtx_unlock(&vm_domainset_lock);
3231 * Wait for free pages to exceed the severe threshold globally.
3234 vm_wait_severe(void)
3237 mtx_lock(&vm_domainset_lock);
3238 while (vm_page_count_severe()) {
3239 vm_severe_waiters++;
3240 msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
3243 mtx_unlock(&vm_domainset_lock);
3250 return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
3254 vm_wait_doms(const domainset_t *wdoms, int mflags)
3261 * We use racey wakeup synchronization to avoid expensive global
3262 * locking for the pageproc when sleeping with a non-specific vm_wait.
3263 * To handle this, we only sleep for one tick in this instance. It
3264 * is expected that most allocations for the pageproc will come from
3265 * kmem or vm_page_grab* which will use the more specific and
3266 * race-free vm_wait_domain().
3268 if (curproc == pageproc) {
3269 mtx_lock(&vm_domainset_lock);
3270 vm_pageproc_waiters++;
3271 error = msleep(&vm_pageproc_waiters, &vm_domainset_lock,
3272 PVM | PDROP | mflags, "pageprocwait", 1);
3275 * XXX Ideally we would wait only until the allocation could
3276 * be satisfied. This condition can cause new allocators to
3277 * consume all freed pages while old allocators wait.
3279 mtx_lock(&vm_domainset_lock);
3280 if (vm_page_count_min_set(wdoms)) {
3282 error = msleep(&vm_min_domains, &vm_domainset_lock,
3283 PVM | PDROP | mflags, "vmwait", 0);
3285 mtx_unlock(&vm_domainset_lock);
3293 * Sleep until free pages are available for allocation.
3294 * - Called in various places after failed memory allocations.
3297 vm_wait_domain(int domain)
3299 struct vm_domain *vmd;
3302 vmd = VM_DOMAIN(domain);
3303 vm_domain_free_assert_unlocked(vmd);
3305 if (curproc == pageproc) {
3306 mtx_lock(&vm_domainset_lock);
3307 if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
3308 vmd->vmd_pageout_pages_needed = 1;
3309 msleep(&vmd->vmd_pageout_pages_needed,
3310 &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
3312 mtx_unlock(&vm_domainset_lock);
3314 if (pageproc == NULL)
3315 panic("vm_wait in early boot");
3316 DOMAINSET_ZERO(&wdom);
3317 DOMAINSET_SET(vmd->vmd_domain, &wdom);
3318 vm_wait_doms(&wdom, 0);
3323 vm_wait_flags(vm_object_t obj, int mflags)
3325 struct domainset *d;
3330 * Carefully fetch pointers only once: the struct domainset
3331 * itself is ummutable but the pointer might change.
3334 d = obj->domain.dr_policy;
3336 d = curthread->td_domain.dr_policy;
3338 return (vm_wait_doms(&d->ds_mask, mflags));
3344 * Sleep until free pages are available for allocation in the
3345 * affinity domains of the obj. If obj is NULL, the domain set
3346 * for the calling thread is used.
3347 * Called in various places after failed memory allocations.
3350 vm_wait(vm_object_t obj)
3352 (void)vm_wait_flags(obj, 0);
3356 vm_wait_intr(vm_object_t obj)
3358 return (vm_wait_flags(obj, PCATCH));
3362 * vm_domain_alloc_fail:
3364 * Called when a page allocation function fails. Informs the
3365 * pagedaemon and performs the requested wait. Requires the
3366 * domain_free and object lock on entry. Returns with the
3367 * object lock held and free lock released. Returns an error when
3368 * retry is necessary.
3372 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3375 vm_domain_free_assert_unlocked(vmd);
3377 atomic_add_int(&vmd->vmd_pageout_deficit,
3378 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3379 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3381 VM_OBJECT_WUNLOCK(object);
3382 vm_wait_domain(vmd->vmd_domain);
3384 VM_OBJECT_WLOCK(object);
3385 if (req & VM_ALLOC_WAITOK)
3395 * Sleep until free pages are available for allocation.
3396 * - Called only in vm_fault so that processes page faulting
3397 * can be easily tracked.
3398 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3399 * processes will be able to grab memory first. Do not change
3400 * this balance without careful testing first.
3403 vm_waitpfault(struct domainset *dset, int timo)
3407 * XXX Ideally we would wait only until the allocation could
3408 * be satisfied. This condition can cause new allocators to
3409 * consume all freed pages while old allocators wait.
3411 mtx_lock(&vm_domainset_lock);
3412 if (vm_page_count_min_set(&dset->ds_mask)) {
3414 msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3417 mtx_unlock(&vm_domainset_lock);
3420 static struct vm_pagequeue *
3421 _vm_page_pagequeue(vm_page_t m, uint8_t queue)
3424 return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue]);
3428 static struct vm_pagequeue *
3429 vm_page_pagequeue(vm_page_t m)
3432 return (_vm_page_pagequeue(m, vm_page_astate_load(m).queue));
3436 static __always_inline bool
3437 vm_page_pqstate_fcmpset(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3439 vm_page_astate_t tmp;
3443 if (__predict_true(vm_page_astate_fcmpset(m, old, new)))
3445 counter_u64_add(pqstate_commit_retries, 1);
3446 } while (old->_bits == tmp._bits);
3452 * Do the work of committing a queue state update that moves the page out of
3453 * its current queue.
3456 _vm_page_pqstate_commit_dequeue(struct vm_pagequeue *pq, vm_page_t m,
3457 vm_page_astate_t *old, vm_page_astate_t new)
3461 vm_pagequeue_assert_locked(pq);
3462 KASSERT(vm_page_pagequeue(m) == pq,
3463 ("%s: queue %p does not match page %p", __func__, pq, m));
3464 KASSERT(old->queue != PQ_NONE && new.queue != old->queue,
3465 ("%s: invalid queue indices %d %d",
3466 __func__, old->queue, new.queue));
3469 * Once the queue index of the page changes there is nothing
3470 * synchronizing with further updates to the page's physical
3471 * queue state. Therefore we must speculatively remove the page
3472 * from the queue now and be prepared to roll back if the queue
3473 * state update fails. If the page is not physically enqueued then
3474 * we just update its queue index.
3476 if ((old->flags & PGA_ENQUEUED) != 0) {
3477 new.flags &= ~PGA_ENQUEUED;
3478 next = TAILQ_NEXT(m, plinks.q);
3479 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3480 vm_pagequeue_cnt_dec(pq);
3481 if (!vm_page_pqstate_fcmpset(m, old, new)) {
3483 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3485 TAILQ_INSERT_BEFORE(next, m, plinks.q);
3486 vm_pagequeue_cnt_inc(pq);
3492 return (vm_page_pqstate_fcmpset(m, old, new));
3497 vm_page_pqstate_commit_dequeue(vm_page_t m, vm_page_astate_t *old,
3498 vm_page_astate_t new)
3500 struct vm_pagequeue *pq;
3501 vm_page_astate_t as;
3504 pq = _vm_page_pagequeue(m, old->queue);
3507 * The queue field and PGA_ENQUEUED flag are stable only so long as the
3508 * corresponding page queue lock is held.
3510 vm_pagequeue_lock(pq);
3511 as = vm_page_astate_load(m);
3512 if (__predict_false(as._bits != old->_bits)) {
3516 ret = _vm_page_pqstate_commit_dequeue(pq, m, old, new);
3518 vm_pagequeue_unlock(pq);
3523 * Commit a queue state update that enqueues or requeues a page.
3526 _vm_page_pqstate_commit_requeue(struct vm_pagequeue *pq, vm_page_t m,
3527 vm_page_astate_t *old, vm_page_astate_t new)
3529 struct vm_domain *vmd;
3531 vm_pagequeue_assert_locked(pq);
3532 KASSERT(old->queue != PQ_NONE && new.queue == old->queue,
3533 ("%s: invalid queue indices %d %d",
3534 __func__, old->queue, new.queue));
3536 new.flags |= PGA_ENQUEUED;
3537 if (!vm_page_pqstate_fcmpset(m, old, new))
3540 if ((old->flags & PGA_ENQUEUED) != 0)
3541 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3543 vm_pagequeue_cnt_inc(pq);
3546 * Give PGA_REQUEUE_HEAD precedence over PGA_REQUEUE. In particular, if
3547 * both flags are set in close succession, only PGA_REQUEUE_HEAD will be
3548 * applied, even if it was set first.
3550 if ((old->flags & PGA_REQUEUE_HEAD) != 0) {
3551 vmd = vm_pagequeue_domain(m);
3552 KASSERT(pq == &vmd->vmd_pagequeues[PQ_INACTIVE],
3553 ("%s: invalid page queue for page %p", __func__, m));
3554 TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3556 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3562 * Commit a queue state update that encodes a request for a deferred queue
3566 vm_page_pqstate_commit_request(vm_page_t m, vm_page_astate_t *old,
3567 vm_page_astate_t new)
3570 KASSERT(old->queue == new.queue || new.queue != PQ_NONE,
3571 ("%s: invalid state, queue %d flags %x",
3572 __func__, new.queue, new.flags));
3574 if (old->_bits != new._bits &&
3575 !vm_page_pqstate_fcmpset(m, old, new))
3577 vm_page_pqbatch_submit(m, new.queue);
3582 * A generic queue state update function. This handles more cases than the
3583 * specialized functions above.
3586 vm_page_pqstate_commit(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3589 if (old->_bits == new._bits)
3592 if (old->queue != PQ_NONE && new.queue != old->queue) {
3593 if (!vm_page_pqstate_commit_dequeue(m, old, new))
3595 if (new.queue != PQ_NONE)
3596 vm_page_pqbatch_submit(m, new.queue);
3598 if (!vm_page_pqstate_fcmpset(m, old, new))
3600 if (new.queue != PQ_NONE &&
3601 ((new.flags & ~old->flags) & PGA_QUEUE_OP_MASK) != 0)
3602 vm_page_pqbatch_submit(m, new.queue);
3608 * Apply deferred queue state updates to a page.
3611 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m, uint8_t queue)
3613 vm_page_astate_t new, old;
3615 CRITICAL_ASSERT(curthread);
3616 vm_pagequeue_assert_locked(pq);
3617 KASSERT(queue < PQ_COUNT,
3618 ("%s: invalid queue index %d", __func__, queue));
3619 KASSERT(pq == _vm_page_pagequeue(m, queue),
3620 ("%s: page %p does not belong to queue %p", __func__, m, pq));
3622 for (old = vm_page_astate_load(m);;) {
3623 if (__predict_false(old.queue != queue ||
3624 (old.flags & PGA_QUEUE_OP_MASK) == 0)) {
3625 counter_u64_add(queue_nops, 1);
3628 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3629 ("%s: page %p is unmanaged", __func__, m));
3632 if ((old.flags & PGA_DEQUEUE) != 0) {
3633 new.flags &= ~PGA_QUEUE_OP_MASK;
3634 new.queue = PQ_NONE;
3635 if (__predict_true(_vm_page_pqstate_commit_dequeue(pq,
3637 counter_u64_add(queue_ops, 1);
3641 new.flags &= ~(PGA_REQUEUE | PGA_REQUEUE_HEAD);
3642 if (__predict_true(_vm_page_pqstate_commit_requeue(pq,
3644 counter_u64_add(queue_ops, 1);
3652 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3657 for (i = 0; i < bq->bq_cnt; i++)
3658 vm_pqbatch_process_page(pq, bq->bq_pa[i], queue);
3659 vm_batchqueue_init(bq);
3663 * vm_page_pqbatch_submit: [ internal use only ]
3665 * Enqueue a page in the specified page queue's batched work queue.
3666 * The caller must have encoded the requested operation in the page
3667 * structure's a.flags field.
3670 vm_page_pqbatch_submit(vm_page_t m, uint8_t queue)
3672 struct vm_batchqueue *bq;
3673 struct vm_pagequeue *pq;
3676 KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3678 domain = vm_page_domain(m);
3680 bq = DPCPU_PTR(pqbatch[domain][queue]);
3681 if (vm_batchqueue_insert(bq, m)) {
3687 pq = &VM_DOMAIN(domain)->vmd_pagequeues[queue];
3688 vm_pagequeue_lock(pq);
3690 bq = DPCPU_PTR(pqbatch[domain][queue]);
3691 vm_pqbatch_process(pq, bq, queue);
3692 vm_pqbatch_process_page(pq, m, queue);
3693 vm_pagequeue_unlock(pq);
3698 * vm_page_pqbatch_drain: [ internal use only ]
3700 * Force all per-CPU page queue batch queues to be drained. This is
3701 * intended for use in severe memory shortages, to ensure that pages
3702 * do not remain stuck in the batch queues.
3705 vm_page_pqbatch_drain(void)
3708 struct vm_domain *vmd;
3709 struct vm_pagequeue *pq;
3710 int cpu, domain, queue;
3715 sched_bind(td, cpu);
3718 for (domain = 0; domain < vm_ndomains; domain++) {
3719 vmd = VM_DOMAIN(domain);
3720 for (queue = 0; queue < PQ_COUNT; queue++) {
3721 pq = &vmd->vmd_pagequeues[queue];
3722 vm_pagequeue_lock(pq);
3724 vm_pqbatch_process(pq,
3725 DPCPU_PTR(pqbatch[domain][queue]), queue);
3727 vm_pagequeue_unlock(pq);
3737 * vm_page_dequeue_deferred: [ internal use only ]
3739 * Request removal of the given page from its current page
3740 * queue. Physical removal from the queue may be deferred
3744 vm_page_dequeue_deferred(vm_page_t m)
3746 vm_page_astate_t new, old;
3748 old = vm_page_astate_load(m);
3750 if (old.queue == PQ_NONE) {
3751 KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3752 ("%s: page %p has unexpected queue state",
3757 new.flags |= PGA_DEQUEUE;
3758 } while (!vm_page_pqstate_commit_request(m, &old, new));
3764 * Remove the page from whichever page queue it's in, if any, before
3768 vm_page_dequeue(vm_page_t m)
3770 vm_page_astate_t new, old;
3772 old = vm_page_astate_load(m);
3774 if (old.queue == PQ_NONE) {
3775 KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3776 ("%s: page %p has unexpected queue state",
3781 new.flags &= ~PGA_QUEUE_OP_MASK;
3782 new.queue = PQ_NONE;
3783 } while (!vm_page_pqstate_commit_dequeue(m, &old, new));
3788 * Schedule the given page for insertion into the specified page queue.
3789 * Physical insertion of the page may be deferred indefinitely.
3792 vm_page_enqueue(vm_page_t m, uint8_t queue)
3795 KASSERT(m->a.queue == PQ_NONE &&
3796 (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
3797 ("%s: page %p is already enqueued", __func__, m));
3798 KASSERT(m->ref_count > 0,
3799 ("%s: page %p does not carry any references", __func__, m));
3802 if ((m->a.flags & PGA_REQUEUE) == 0)
3803 vm_page_aflag_set(m, PGA_REQUEUE);
3804 vm_page_pqbatch_submit(m, queue);
3808 * vm_page_free_prep:
3810 * Prepares the given page to be put on the free list,
3811 * disassociating it from any VM object. The caller may return
3812 * the page to the free list only if this function returns true.
3814 * The object, if it exists, must be locked, and then the page must
3815 * be xbusy. Otherwise the page must be not busied. A managed
3816 * page must be unmapped.
3819 vm_page_free_prep(vm_page_t m)
3823 * Synchronize with threads that have dropped a reference to this
3826 atomic_thread_fence_acq();
3828 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
3829 if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
3832 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3833 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
3834 KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
3835 m, i, (uintmax_t)*p));
3838 if ((m->oflags & VPO_UNMANAGED) == 0) {
3839 KASSERT(!pmap_page_is_mapped(m),
3840 ("vm_page_free_prep: freeing mapped page %p", m));
3841 KASSERT((m->a.flags & (PGA_EXECUTABLE | PGA_WRITEABLE)) == 0,
3842 ("vm_page_free_prep: mapping flags set in page %p", m));
3844 KASSERT(m->a.queue == PQ_NONE,
3845 ("vm_page_free_prep: unmanaged page %p is queued", m));
3847 VM_CNT_INC(v_tfree);
3849 if (m->object != NULL) {
3850 KASSERT(((m->oflags & VPO_UNMANAGED) != 0) ==
3851 ((m->object->flags & OBJ_UNMANAGED) != 0),
3852 ("vm_page_free_prep: managed flag mismatch for page %p",
3854 vm_page_assert_xbusied(m);
3857 * The object reference can be released without an atomic
3860 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
3861 m->ref_count == VPRC_OBJREF,
3862 ("vm_page_free_prep: page %p has unexpected ref_count %u",
3864 vm_page_object_remove(m);
3865 m->ref_count -= VPRC_OBJREF;
3867 vm_page_assert_unbusied(m);
3869 vm_page_busy_free(m);
3872 * If fictitious remove object association and
3875 if ((m->flags & PG_FICTITIOUS) != 0) {
3876 KASSERT(m->ref_count == 1,
3877 ("fictitious page %p is referenced", m));
3878 KASSERT(m->a.queue == PQ_NONE,
3879 ("fictitious page %p is queued", m));
3884 * Pages need not be dequeued before they are returned to the physical
3885 * memory allocator, but they must at least be marked for a deferred
3888 if ((m->oflags & VPO_UNMANAGED) == 0)
3889 vm_page_dequeue_deferred(m);
3894 if (m->ref_count != 0)
3895 panic("vm_page_free_prep: page %p has references", m);
3898 * Restore the default memory attribute to the page.
3900 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3901 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3903 #if VM_NRESERVLEVEL > 0
3905 * Determine whether the page belongs to a reservation. If the page was
3906 * allocated from a per-CPU cache, it cannot belong to a reservation, so
3907 * as an optimization, we avoid the check in that case.
3909 if ((m->flags & PG_PCPU_CACHE) == 0 && vm_reserv_free_page(m))
3919 * Returns the given page to the free list, disassociating it
3920 * from any VM object.
3922 * The object must be locked. The page must be exclusively busied if it
3923 * belongs to an object.
3926 vm_page_free_toq(vm_page_t m)
3928 struct vm_domain *vmd;
3931 if (!vm_page_free_prep(m))
3934 vmd = vm_pagequeue_domain(m);
3935 zone = vmd->vmd_pgcache[m->pool].zone;
3936 if ((m->flags & PG_PCPU_CACHE) != 0 && zone != NULL) {
3940 vm_domain_free_lock(vmd);
3941 vm_phys_free_pages(m, 0);
3942 vm_domain_free_unlock(vmd);
3943 vm_domain_freecnt_inc(vmd, 1);
3947 * vm_page_free_pages_toq:
3949 * Returns a list of pages to the free list, disassociating it
3950 * from any VM object. In other words, this is equivalent to
3951 * calling vm_page_free_toq() for each page of a list of VM objects.
3954 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
3959 if (SLIST_EMPTY(free))
3963 while ((m = SLIST_FIRST(free)) != NULL) {
3965 SLIST_REMOVE_HEAD(free, plinks.s.ss);
3966 vm_page_free_toq(m);
3969 if (update_wire_count)
3974 * Mark this page as wired down. For managed pages, this prevents reclamation
3975 * by the page daemon, or when the containing object, if any, is destroyed.
3978 vm_page_wire(vm_page_t m)
3983 if (m->object != NULL && !vm_page_busied(m) &&
3984 !vm_object_busied(m->object))
3985 VM_OBJECT_ASSERT_LOCKED(m->object);
3987 KASSERT((m->flags & PG_FICTITIOUS) == 0 ||
3988 VPRC_WIRE_COUNT(m->ref_count) >= 1,
3989 ("vm_page_wire: fictitious page %p has zero wirings", m));
3991 old = atomic_fetchadd_int(&m->ref_count, 1);
3992 KASSERT(VPRC_WIRE_COUNT(old) != VPRC_WIRE_COUNT_MAX,
3993 ("vm_page_wire: counter overflow for page %p", m));
3994 if (VPRC_WIRE_COUNT(old) == 0) {
3995 if ((m->oflags & VPO_UNMANAGED) == 0)
3996 vm_page_aflag_set(m, PGA_DEQUEUE);
4002 * Attempt to wire a mapped page following a pmap lookup of that page.
4003 * This may fail if a thread is concurrently tearing down mappings of the page.
4004 * The transient failure is acceptable because it translates to the
4005 * failure of the caller pmap_extract_and_hold(), which should be then
4006 * followed by the vm_fault() fallback, see e.g. vm_fault_quick_hold_pages().
4009 vm_page_wire_mapped(vm_page_t m)
4016 ("vm_page_wire_mapped: wiring unreferenced page %p", m));
4017 if ((old & VPRC_BLOCKED) != 0)
4019 } while (!atomic_fcmpset_int(&m->ref_count, &old, old + 1));
4021 if (VPRC_WIRE_COUNT(old) == 0) {
4022 if ((m->oflags & VPO_UNMANAGED) == 0)
4023 vm_page_aflag_set(m, PGA_DEQUEUE);
4030 * Release a wiring reference to a managed page. If the page still belongs to
4031 * an object, update its position in the page queues to reflect the reference.
4032 * If the wiring was the last reference to the page, free the page.
4035 vm_page_unwire_managed(vm_page_t m, uint8_t nqueue, bool noreuse)
4039 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4040 ("%s: page %p is unmanaged", __func__, m));
4043 * Update LRU state before releasing the wiring reference.
4044 * Use a release store when updating the reference count to
4045 * synchronize with vm_page_free_prep().
4049 KASSERT(VPRC_WIRE_COUNT(old) > 0,
4050 ("vm_page_unwire: wire count underflow for page %p", m));
4052 if (old > VPRC_OBJREF + 1) {
4054 * The page has at least one other wiring reference. An
4055 * earlier iteration of this loop may have called
4056 * vm_page_release_toq() and cleared PGA_DEQUEUE, so
4057 * re-set it if necessary.
4059 if ((vm_page_astate_load(m).flags & PGA_DEQUEUE) == 0)
4060 vm_page_aflag_set(m, PGA_DEQUEUE);
4061 } else if (old == VPRC_OBJREF + 1) {
4063 * This is the last wiring. Clear PGA_DEQUEUE and
4064 * update the page's queue state to reflect the
4065 * reference. If the page does not belong to an object
4066 * (i.e., the VPRC_OBJREF bit is clear), we only need to
4067 * clear leftover queue state.
4069 vm_page_release_toq(m, nqueue, noreuse);
4070 } else if (old == 1) {
4071 vm_page_aflag_clear(m, PGA_DEQUEUE);
4073 } while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
4075 if (VPRC_WIRE_COUNT(old) == 1) {
4083 * Release one wiring of the specified page, potentially allowing it to be
4086 * Only managed pages belonging to an object can be paged out. If the number
4087 * of wirings transitions to zero and the page is eligible for page out, then
4088 * the page is added to the specified paging queue. If the released wiring
4089 * represented the last reference to the page, the page is freed.
4092 vm_page_unwire(vm_page_t m, uint8_t nqueue)
4095 KASSERT(nqueue < PQ_COUNT,
4096 ("vm_page_unwire: invalid queue %u request for page %p",
4099 if ((m->oflags & VPO_UNMANAGED) != 0) {
4100 if (vm_page_unwire_noq(m) && m->ref_count == 0)
4104 vm_page_unwire_managed(m, nqueue, false);
4108 * Unwire a page without (re-)inserting it into a page queue. It is up
4109 * to the caller to enqueue, requeue, or free the page as appropriate.
4110 * In most cases involving managed pages, vm_page_unwire() should be used
4114 vm_page_unwire_noq(vm_page_t m)
4118 old = vm_page_drop(m, 1);
4119 KASSERT(VPRC_WIRE_COUNT(old) != 0,
4120 ("%s: counter underflow for page %p", __func__, m));
4121 KASSERT((m->flags & PG_FICTITIOUS) == 0 || VPRC_WIRE_COUNT(old) > 1,
4122 ("%s: missing ref on fictitious page %p", __func__, m));
4124 if (VPRC_WIRE_COUNT(old) > 1)
4126 if ((m->oflags & VPO_UNMANAGED) == 0)
4127 vm_page_aflag_clear(m, PGA_DEQUEUE);
4133 * Ensure that the page ends up in the specified page queue. If the page is
4134 * active or being moved to the active queue, ensure that its act_count is
4135 * at least ACT_INIT but do not otherwise mess with it.
4137 static __always_inline void
4138 vm_page_mvqueue(vm_page_t m, const uint8_t nqueue, const uint16_t nflag)
4140 vm_page_astate_t old, new;
4142 KASSERT(m->ref_count > 0,
4143 ("%s: page %p does not carry any references", __func__, m));
4144 KASSERT(nflag == PGA_REQUEUE || nflag == PGA_REQUEUE_HEAD,
4145 ("%s: invalid flags %x", __func__, nflag));
4147 if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
4150 old = vm_page_astate_load(m);
4152 if ((old.flags & PGA_DEQUEUE) != 0)
4155 new.flags &= ~PGA_QUEUE_OP_MASK;
4156 if (nqueue == PQ_ACTIVE)
4157 new.act_count = max(old.act_count, ACT_INIT);
4158 if (old.queue == nqueue) {
4159 if (nqueue != PQ_ACTIVE)
4165 } while (!vm_page_pqstate_commit(m, &old, new));
4169 * Put the specified page on the active list (if appropriate).
4172 vm_page_activate(vm_page_t m)
4175 vm_page_mvqueue(m, PQ_ACTIVE, PGA_REQUEUE);
4179 * Move the specified page to the tail of the inactive queue, or requeue
4180 * the page if it is already in the inactive queue.
4183 vm_page_deactivate(vm_page_t m)
4186 vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE);
4190 vm_page_deactivate_noreuse(vm_page_t m)
4193 vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE_HEAD);
4197 * Put a page in the laundry, or requeue it if it is already there.
4200 vm_page_launder(vm_page_t m)
4203 vm_page_mvqueue(m, PQ_LAUNDRY, PGA_REQUEUE);
4207 * Put a page in the PQ_UNSWAPPABLE holding queue.
4210 vm_page_unswappable(vm_page_t m)
4213 KASSERT(!vm_page_wired(m) && (m->oflags & VPO_UNMANAGED) == 0,
4214 ("page %p already unswappable", m));
4217 vm_page_enqueue(m, PQ_UNSWAPPABLE);
4221 * Release a page back to the page queues in preparation for unwiring.
4224 vm_page_release_toq(vm_page_t m, uint8_t nqueue, const bool noreuse)
4226 vm_page_astate_t old, new;
4230 * Use a check of the valid bits to determine whether we should
4231 * accelerate reclamation of the page. The object lock might not be
4232 * held here, in which case the check is racy. At worst we will either
4233 * accelerate reclamation of a valid page and violate LRU, or
4234 * unnecessarily defer reclamation of an invalid page.
4236 * If we were asked to not cache the page, place it near the head of the
4237 * inactive queue so that is reclaimed sooner.
4239 if (noreuse || m->valid == 0) {
4240 nqueue = PQ_INACTIVE;
4241 nflag = PGA_REQUEUE_HEAD;
4243 nflag = PGA_REQUEUE;
4246 old = vm_page_astate_load(m);
4251 * If the page is already in the active queue and we are not
4252 * trying to accelerate reclamation, simply mark it as
4253 * referenced and avoid any queue operations.
4255 new.flags &= ~PGA_QUEUE_OP_MASK;
4256 if (nflag != PGA_REQUEUE_HEAD && old.queue == PQ_ACTIVE)
4257 new.flags |= PGA_REFERENCED;
4262 } while (!vm_page_pqstate_commit(m, &old, new));
4266 * Unwire a page and either attempt to free it or re-add it to the page queues.
4269 vm_page_release(vm_page_t m, int flags)
4273 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4274 ("vm_page_release: page %p is unmanaged", m));
4276 if ((flags & VPR_TRYFREE) != 0) {
4278 object = atomic_load_ptr(&m->object);
4281 /* Depends on type-stability. */
4282 if (vm_page_busied(m) || !VM_OBJECT_TRYWLOCK(object))
4284 if (object == m->object) {
4285 vm_page_release_locked(m, flags);
4286 VM_OBJECT_WUNLOCK(object);
4289 VM_OBJECT_WUNLOCK(object);
4292 vm_page_unwire_managed(m, PQ_INACTIVE, flags != 0);
4295 /* See vm_page_release(). */
4297 vm_page_release_locked(vm_page_t m, int flags)
4300 VM_OBJECT_ASSERT_WLOCKED(m->object);
4301 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4302 ("vm_page_release_locked: page %p is unmanaged", m));
4304 if (vm_page_unwire_noq(m)) {
4305 if ((flags & VPR_TRYFREE) != 0 &&
4306 (m->object->ref_count == 0 || !pmap_page_is_mapped(m)) &&
4307 m->dirty == 0 && vm_page_tryxbusy(m)) {
4309 * An unlocked lookup may have wired the page before the
4310 * busy lock was acquired, in which case the page must
4313 if (__predict_true(!vm_page_wired(m))) {
4319 vm_page_release_toq(m, PQ_INACTIVE, flags != 0);
4325 vm_page_try_blocked_op(vm_page_t m, void (*op)(vm_page_t))
4329 KASSERT(m->object != NULL && (m->oflags & VPO_UNMANAGED) == 0,
4330 ("vm_page_try_blocked_op: page %p has no object", m));
4331 KASSERT(vm_page_busied(m),
4332 ("vm_page_try_blocked_op: page %p is not busy", m));
4333 VM_OBJECT_ASSERT_LOCKED(m->object);
4338 ("vm_page_try_blocked_op: page %p has no references", m));
4339 if (VPRC_WIRE_COUNT(old) != 0)
4341 } while (!atomic_fcmpset_int(&m->ref_count, &old, old | VPRC_BLOCKED));
4346 * If the object is read-locked, new wirings may be created via an
4349 old = vm_page_drop(m, VPRC_BLOCKED);
4350 KASSERT(!VM_OBJECT_WOWNED(m->object) ||
4351 old == (VPRC_BLOCKED | VPRC_OBJREF),
4352 ("vm_page_try_blocked_op: unexpected refcount value %u for %p",
4358 * Atomically check for wirings and remove all mappings of the page.
4361 vm_page_try_remove_all(vm_page_t m)
4364 return (vm_page_try_blocked_op(m, pmap_remove_all));
4368 * Atomically check for wirings and remove all writeable mappings of the page.
4371 vm_page_try_remove_write(vm_page_t m)
4374 return (vm_page_try_blocked_op(m, pmap_remove_write));
4380 * Apply the specified advice to the given page.
4383 vm_page_advise(vm_page_t m, int advice)
4386 VM_OBJECT_ASSERT_WLOCKED(m->object);
4387 vm_page_assert_xbusied(m);
4389 if (advice == MADV_FREE)
4391 * Mark the page clean. This will allow the page to be freed
4392 * without first paging it out. MADV_FREE pages are often
4393 * quickly reused by malloc(3), so we do not do anything that
4394 * would result in a page fault on a later access.
4397 else if (advice != MADV_DONTNEED) {
4398 if (advice == MADV_WILLNEED)
4399 vm_page_activate(m);
4403 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
4407 * Clear any references to the page. Otherwise, the page daemon will
4408 * immediately reactivate the page.
4410 vm_page_aflag_clear(m, PGA_REFERENCED);
4413 * Place clean pages near the head of the inactive queue rather than
4414 * the tail, thus defeating the queue's LRU operation and ensuring that
4415 * the page will be reused quickly. Dirty pages not already in the
4416 * laundry are moved there.
4419 vm_page_deactivate_noreuse(m);
4420 else if (!vm_page_in_laundry(m))
4425 * vm_page_grab_release
4427 * Helper routine for grab functions to release busy on return.
4430 vm_page_grab_release(vm_page_t m, int allocflags)
4433 if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4434 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4442 * vm_page_grab_sleep
4444 * Sleep for busy according to VM_ALLOC_ parameters. Returns true
4445 * if the caller should retry and false otherwise.
4447 * If the object is locked on entry the object will be unlocked with
4448 * false returns and still locked but possibly having been dropped
4449 * with true returns.
4452 vm_page_grab_sleep(vm_object_t object, vm_page_t m, vm_pindex_t pindex,
4453 const char *wmesg, int allocflags, bool locked)
4456 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4460 * Reference the page before unlocking and sleeping so that
4461 * the page daemon is less likely to reclaim it.
4463 if (locked && (allocflags & VM_ALLOC_NOCREAT) == 0)
4464 vm_page_reference(m);
4466 if (_vm_page_busy_sleep(object, m, pindex, wmesg, allocflags, locked) &&
4468 VM_OBJECT_WLOCK(object);
4469 if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
4476 * Assert that the grab flags are valid.
4479 vm_page_grab_check(int allocflags)
4482 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
4483 (allocflags & VM_ALLOC_WIRED) != 0,
4484 ("vm_page_grab*: the pages must be busied or wired"));
4486 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4487 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4488 ("vm_page_grab*: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4492 * Calculate the page allocation flags for grab.
4495 vm_page_grab_pflags(int allocflags)
4499 pflags = allocflags &
4500 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL |
4501 VM_ALLOC_NOBUSY | VM_ALLOC_IGN_SBUSY);
4502 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4503 pflags |= VM_ALLOC_WAITFAIL;
4504 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4505 pflags |= VM_ALLOC_SBUSY;
4511 * Grab a page, waiting until we are waken up due to the page
4512 * changing state. We keep on waiting, if the page continues
4513 * to be in the object. If the page doesn't exist, first allocate it
4514 * and then conditionally zero it.
4516 * This routine may sleep.
4518 * The object must be locked on entry. The lock will, however, be released
4519 * and reacquired if the routine sleeps.
4522 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
4526 VM_OBJECT_ASSERT_WLOCKED(object);
4527 vm_page_grab_check(allocflags);
4530 if ((m = vm_page_lookup(object, pindex)) != NULL) {
4531 if (!vm_page_tryacquire(m, allocflags)) {
4532 if (vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4539 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4541 m = vm_page_alloc(object, pindex, vm_page_grab_pflags(allocflags));
4543 if ((allocflags & (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL)) != 0)
4547 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
4551 vm_page_grab_release(m, allocflags);
4557 * Locklessly attempt to acquire a page given a (object, pindex) tuple
4558 * and an optional previous page to avoid the radix lookup. The resulting
4559 * page will be validated against the identity tuple and busied or wired
4560 * as requested. A NULL *mp return guarantees that the page was not in
4561 * radix at the time of the call but callers must perform higher level
4562 * synchronization or retry the operation under a lock if they require
4563 * an atomic answer. This is the only lock free validation routine,
4564 * other routines can depend on the resulting page state.
4566 * The return value indicates whether the operation failed due to caller
4567 * flags. The return is tri-state with mp:
4569 * (true, *mp != NULL) - The operation was successful.
4570 * (true, *mp == NULL) - The page was not found in tree.
4571 * (false, *mp == NULL) - WAITFAIL or NOWAIT prevented acquisition.
4574 vm_page_acquire_unlocked(vm_object_t object, vm_pindex_t pindex,
4575 vm_page_t prev, vm_page_t *mp, int allocflags)
4579 vm_page_grab_check(allocflags);
4580 MPASS(prev == NULL || vm_page_busied(prev) || vm_page_wired(prev));
4585 * We may see a false NULL here because the previous page
4586 * has been removed or just inserted and the list is loaded
4587 * without barriers. Switch to radix to verify.
4589 if (prev == NULL || (m = TAILQ_NEXT(prev, listq)) == NULL ||
4590 QMD_IS_TRASHED(m) || m->pindex != pindex ||
4591 atomic_load_ptr(&m->object) != object) {
4594 * This guarantees the result is instantaneously
4597 m = vm_radix_lookup_unlocked(&object->rtree, pindex);
4601 if (vm_page_trybusy(m, allocflags)) {
4602 if (m->object == object && m->pindex == pindex)
4605 vm_page_busy_release(m);
4609 if (!vm_page_grab_sleep(object, m, pindex, "pgnslp",
4613 if ((allocflags & VM_ALLOC_WIRED) != 0)
4615 vm_page_grab_release(m, allocflags);
4621 * Try to locklessly grab a page and fall back to the object lock if NOCREAT
4625 vm_page_grab_unlocked(vm_object_t object, vm_pindex_t pindex, int allocflags)
4629 vm_page_grab_check(allocflags);
4631 if (!vm_page_acquire_unlocked(object, pindex, NULL, &m, allocflags))
4637 * The radix lockless lookup should never return a false negative
4638 * errors. If the user specifies NOCREAT they are guaranteed there
4639 * was no page present at the instant of the call. A NOCREAT caller
4640 * must handle create races gracefully.
4642 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4645 VM_OBJECT_WLOCK(object);
4646 m = vm_page_grab(object, pindex, allocflags);
4647 VM_OBJECT_WUNLOCK(object);
4653 * Grab a page and make it valid, paging in if necessary. Pages missing from
4654 * their pager are zero filled and validated. If a VM_ALLOC_COUNT is supplied
4655 * and the page is not valid as many as VM_INITIAL_PAGEIN pages can be brought
4656 * in simultaneously. Additional pages will be left on a paging queue but
4657 * will neither be wired nor busy regardless of allocflags.
4660 vm_page_grab_valid(vm_page_t *mp, vm_object_t object, vm_pindex_t pindex, int allocflags)
4663 vm_page_t ma[VM_INITIAL_PAGEIN];
4664 int after, i, pflags, rv;
4666 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4667 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4668 ("vm_page_grab_valid: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4669 KASSERT((allocflags &
4670 (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4671 ("vm_page_grab_valid: Invalid flags 0x%X", allocflags));
4672 VM_OBJECT_ASSERT_WLOCKED(object);
4673 pflags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY |
4674 VM_ALLOC_WIRED | VM_ALLOC_IGN_SBUSY);
4675 pflags |= VM_ALLOC_WAITFAIL;
4678 if ((m = vm_page_lookup(object, pindex)) != NULL) {
4680 * If the page is fully valid it can only become invalid
4681 * with the object lock held. If it is not valid it can
4682 * become valid with the busy lock held. Therefore, we
4683 * may unnecessarily lock the exclusive busy here if we
4684 * race with I/O completion not using the object lock.
4685 * However, we will not end up with an invalid page and a
4688 if (!vm_page_trybusy(m,
4689 vm_page_all_valid(m) ? allocflags : 0)) {
4690 (void)vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4694 if (vm_page_all_valid(m))
4696 if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4697 vm_page_busy_release(m);
4699 return (VM_PAGER_FAIL);
4701 } else if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4703 return (VM_PAGER_FAIL);
4704 } else if ((m = vm_page_alloc(object, pindex, pflags)) == NULL) {
4708 vm_page_assert_xbusied(m);
4709 if (vm_pager_has_page(object, pindex, NULL, &after)) {
4710 after = MIN(after, VM_INITIAL_PAGEIN);
4711 after = MIN(after, allocflags >> VM_ALLOC_COUNT_SHIFT);
4712 after = MAX(after, 1);
4714 for (i = 1; i < after; i++) {
4715 if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
4716 if (ma[i]->valid || !vm_page_tryxbusy(ma[i]))
4719 ma[i] = vm_page_alloc(object, m->pindex + i,
4726 vm_object_pip_add(object, after);
4727 VM_OBJECT_WUNLOCK(object);
4728 rv = vm_pager_get_pages(object, ma, after, NULL, NULL);
4729 VM_OBJECT_WLOCK(object);
4730 vm_object_pip_wakeupn(object, after);
4731 /* Pager may have replaced a page. */
4733 if (rv != VM_PAGER_OK) {
4734 for (i = 0; i < after; i++) {
4735 if (!vm_page_wired(ma[i]))
4736 vm_page_free(ma[i]);
4738 vm_page_xunbusy(ma[i]);
4743 for (i = 1; i < after; i++)
4744 vm_page_readahead_finish(ma[i]);
4745 MPASS(vm_page_all_valid(m));
4747 vm_page_zero_invalid(m, TRUE);
4750 if ((allocflags & VM_ALLOC_WIRED) != 0)
4752 if ((allocflags & VM_ALLOC_SBUSY) != 0 && vm_page_xbusied(m))
4753 vm_page_busy_downgrade(m);
4754 else if ((allocflags & VM_ALLOC_NOBUSY) != 0)
4755 vm_page_busy_release(m);
4757 return (VM_PAGER_OK);
4761 * Locklessly grab a valid page. If the page is not valid or not yet
4762 * allocated this will fall back to the object lock method.
4765 vm_page_grab_valid_unlocked(vm_page_t *mp, vm_object_t object,
4766 vm_pindex_t pindex, int allocflags)
4772 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4773 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4774 ("vm_page_grab_valid_unlocked: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY "
4776 KASSERT((allocflags &
4777 (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4778 ("vm_page_grab_valid_unlocked: Invalid flags 0x%X", allocflags));
4781 * Attempt a lockless lookup and busy. We need at least an sbusy
4782 * before we can inspect the valid field and return a wired page.
4784 flags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
4785 if (!vm_page_acquire_unlocked(object, pindex, NULL, mp, flags))
4786 return (VM_PAGER_FAIL);
4787 if ((m = *mp) != NULL) {
4788 if (vm_page_all_valid(m)) {
4789 if ((allocflags & VM_ALLOC_WIRED) != 0)
4791 vm_page_grab_release(m, allocflags);
4792 return (VM_PAGER_OK);
4794 vm_page_busy_release(m);
4796 if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4798 return (VM_PAGER_FAIL);
4800 VM_OBJECT_WLOCK(object);
4801 error = vm_page_grab_valid(mp, object, pindex, allocflags);
4802 VM_OBJECT_WUNLOCK(object);
4808 * Return the specified range of pages from the given object. For each
4809 * page offset within the range, if a page already exists within the object
4810 * at that offset and it is busy, then wait for it to change state. If,
4811 * instead, the page doesn't exist, then allocate it.
4813 * The caller must always specify an allocation class.
4815 * allocation classes:
4816 * VM_ALLOC_NORMAL normal process request
4817 * VM_ALLOC_SYSTEM system *really* needs the pages
4819 * The caller must always specify that the pages are to be busied and/or
4822 * optional allocation flags:
4823 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
4824 * VM_ALLOC_NOBUSY do not exclusive busy the page
4825 * VM_ALLOC_NOWAIT do not sleep
4826 * VM_ALLOC_SBUSY set page to sbusy state
4827 * VM_ALLOC_WIRED wire the pages
4828 * VM_ALLOC_ZERO zero and validate any invalid pages
4830 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
4831 * may return a partial prefix of the requested range.
4834 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
4835 vm_page_t *ma, int count)
4841 VM_OBJECT_ASSERT_WLOCKED(object);
4842 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
4843 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
4845 ("vm_page_grab_pages: invalid page count %d", count));
4846 vm_page_grab_check(allocflags);
4848 pflags = vm_page_grab_pflags(allocflags);
4851 m = vm_radix_lookup_le(&object->rtree, pindex + i);
4852 if (m == NULL || m->pindex != pindex + i) {
4856 mpred = TAILQ_PREV(m, pglist, listq);
4857 for (; i < count; i++) {
4859 if (!vm_page_tryacquire(m, allocflags)) {
4860 if (vm_page_grab_sleep(object, m, pindex + i,
4861 "grbmaw", allocflags, true))
4866 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4868 m = vm_page_alloc_after(object, pindex + i,
4869 pflags | VM_ALLOC_COUNT(count - i), mpred);
4871 if ((allocflags & (VM_ALLOC_NOWAIT |
4872 VM_ALLOC_WAITFAIL)) != 0)
4877 if (vm_page_none_valid(m) &&
4878 (allocflags & VM_ALLOC_ZERO) != 0) {
4879 if ((m->flags & PG_ZERO) == 0)
4883 vm_page_grab_release(m, allocflags);
4885 m = vm_page_next(m);
4891 * Unlocked variant of vm_page_grab_pages(). This accepts the same flags
4892 * and will fall back to the locked variant to handle allocation.
4895 vm_page_grab_pages_unlocked(vm_object_t object, vm_pindex_t pindex,
4896 int allocflags, vm_page_t *ma, int count)
4903 ("vm_page_grab_pages_unlocked: invalid page count %d", count));
4904 vm_page_grab_check(allocflags);
4907 * Modify flags for lockless acquire to hold the page until we
4908 * set it valid if necessary.
4910 flags = allocflags & ~VM_ALLOC_NOBUSY;
4912 for (i = 0; i < count; i++, pindex++) {
4913 if (!vm_page_acquire_unlocked(object, pindex, pred, &m, flags))
4917 if ((flags & VM_ALLOC_ZERO) != 0 && vm_page_none_valid(m)) {
4918 if ((m->flags & PG_ZERO) == 0)
4922 /* m will still be wired or busy according to flags. */
4923 vm_page_grab_release(m, allocflags);
4926 if (i == count || (allocflags & VM_ALLOC_NOCREAT) != 0)
4929 VM_OBJECT_WLOCK(object);
4930 i += vm_page_grab_pages(object, pindex, allocflags, &ma[i], count);
4931 VM_OBJECT_WUNLOCK(object);
4937 * Mapping function for valid or dirty bits in a page.
4939 * Inputs are required to range within a page.
4942 vm_page_bits(int base, int size)
4948 base + size <= PAGE_SIZE,
4949 ("vm_page_bits: illegal base/size %d/%d", base, size)
4952 if (size == 0) /* handle degenerate case */
4955 first_bit = base >> DEV_BSHIFT;
4956 last_bit = (base + size - 1) >> DEV_BSHIFT;
4958 return (((vm_page_bits_t)2 << last_bit) -
4959 ((vm_page_bits_t)1 << first_bit));
4963 vm_page_bits_set(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t set)
4966 #if PAGE_SIZE == 32768
4967 atomic_set_64((uint64_t *)bits, set);
4968 #elif PAGE_SIZE == 16384
4969 atomic_set_32((uint32_t *)bits, set);
4970 #elif (PAGE_SIZE == 8192) && defined(atomic_set_16)
4971 atomic_set_16((uint16_t *)bits, set);
4972 #elif (PAGE_SIZE == 4096) && defined(atomic_set_8)
4973 atomic_set_8((uint8_t *)bits, set);
4974 #else /* PAGE_SIZE <= 8192 */
4978 addr = (uintptr_t)bits;
4980 * Use a trick to perform a 32-bit atomic on the
4981 * containing aligned word, to not depend on the existence
4982 * of atomic_{set, clear}_{8, 16}.
4984 shift = addr & (sizeof(uint32_t) - 1);
4985 #if BYTE_ORDER == BIG_ENDIAN
4986 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4990 addr &= ~(sizeof(uint32_t) - 1);
4991 atomic_set_32((uint32_t *)addr, set << shift);
4992 #endif /* PAGE_SIZE */
4996 vm_page_bits_clear(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t clear)
4999 #if PAGE_SIZE == 32768
5000 atomic_clear_64((uint64_t *)bits, clear);
5001 #elif PAGE_SIZE == 16384
5002 atomic_clear_32((uint32_t *)bits, clear);
5003 #elif (PAGE_SIZE == 8192) && defined(atomic_clear_16)
5004 atomic_clear_16((uint16_t *)bits, clear);
5005 #elif (PAGE_SIZE == 4096) && defined(atomic_clear_8)
5006 atomic_clear_8((uint8_t *)bits, clear);
5007 #else /* PAGE_SIZE <= 8192 */
5011 addr = (uintptr_t)bits;
5013 * Use a trick to perform a 32-bit atomic on the
5014 * containing aligned word, to not depend on the existence
5015 * of atomic_{set, clear}_{8, 16}.
5017 shift = addr & (sizeof(uint32_t) - 1);
5018 #if BYTE_ORDER == BIG_ENDIAN
5019 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
5023 addr &= ~(sizeof(uint32_t) - 1);
5024 atomic_clear_32((uint32_t *)addr, clear << shift);
5025 #endif /* PAGE_SIZE */
5028 static inline vm_page_bits_t
5029 vm_page_bits_swap(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t newbits)
5031 #if PAGE_SIZE == 32768
5035 while (atomic_fcmpset_64(bits, &old, newbits) == 0);
5037 #elif PAGE_SIZE == 16384
5041 while (atomic_fcmpset_32(bits, &old, newbits) == 0);
5043 #elif (PAGE_SIZE == 8192) && defined(atomic_fcmpset_16)
5047 while (atomic_fcmpset_16(bits, &old, newbits) == 0);
5049 #elif (PAGE_SIZE == 4096) && defined(atomic_fcmpset_8)
5053 while (atomic_fcmpset_8(bits, &old, newbits) == 0);
5055 #else /* PAGE_SIZE <= 4096*/
5057 uint32_t old, new, mask;
5060 addr = (uintptr_t)bits;
5062 * Use a trick to perform a 32-bit atomic on the
5063 * containing aligned word, to not depend on the existence
5064 * of atomic_{set, swap, clear}_{8, 16}.
5066 shift = addr & (sizeof(uint32_t) - 1);
5067 #if BYTE_ORDER == BIG_ENDIAN
5068 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
5072 addr &= ~(sizeof(uint32_t) - 1);
5073 mask = VM_PAGE_BITS_ALL << shift;
5078 new |= newbits << shift;
5079 } while (atomic_fcmpset_32((uint32_t *)addr, &old, new) == 0);
5080 return (old >> shift);
5081 #endif /* PAGE_SIZE */
5085 * vm_page_set_valid_range:
5087 * Sets portions of a page valid. The arguments are expected
5088 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
5089 * of any partial chunks touched by the range. The invalid portion of
5090 * such chunks will be zeroed.
5092 * (base + size) must be less then or equal to PAGE_SIZE.
5095 vm_page_set_valid_range(vm_page_t m, int base, int size)
5098 vm_page_bits_t pagebits;
5100 vm_page_assert_busied(m);
5101 if (size == 0) /* handle degenerate case */
5105 * If the base is not DEV_BSIZE aligned and the valid
5106 * bit is clear, we have to zero out a portion of the
5109 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5110 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
5111 pmap_zero_page_area(m, frag, base - frag);
5114 * If the ending offset is not DEV_BSIZE aligned and the
5115 * valid bit is clear, we have to zero out a portion of
5118 endoff = base + size;
5119 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5120 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
5121 pmap_zero_page_area(m, endoff,
5122 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5125 * Assert that no previously invalid block that is now being validated
5128 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
5129 ("vm_page_set_valid_range: page %p is dirty", m));
5132 * Set valid bits inclusive of any overlap.
5134 pagebits = vm_page_bits(base, size);
5135 if (vm_page_xbusied(m))
5136 m->valid |= pagebits;
5138 vm_page_bits_set(m, &m->valid, pagebits);
5142 * Set the page dirty bits and free the invalid swap space if
5143 * present. Returns the previous dirty bits.
5146 vm_page_set_dirty(vm_page_t m)
5150 VM_PAGE_OBJECT_BUSY_ASSERT(m);
5152 if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m)) {
5154 m->dirty = VM_PAGE_BITS_ALL;
5156 old = vm_page_bits_swap(m, &m->dirty, VM_PAGE_BITS_ALL);
5157 if (old == 0 && (m->a.flags & PGA_SWAP_SPACE) != 0)
5158 vm_pager_page_unswapped(m);
5164 * Clear the given bits from the specified page's dirty field.
5166 static __inline void
5167 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
5170 vm_page_assert_busied(m);
5173 * If the page is xbusied and not write mapped we are the
5174 * only thread that can modify dirty bits. Otherwise, The pmap
5175 * layer can call vm_page_dirty() without holding a distinguished
5176 * lock. The combination of page busy and atomic operations
5177 * suffice to guarantee consistency of the page dirty field.
5179 if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
5180 m->dirty &= ~pagebits;
5182 vm_page_bits_clear(m, &m->dirty, pagebits);
5186 * vm_page_set_validclean:
5188 * Sets portions of a page valid and clean. The arguments are expected
5189 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
5190 * of any partial chunks touched by the range. The invalid portion of
5191 * such chunks will be zero'd.
5193 * (base + size) must be less then or equal to PAGE_SIZE.
5196 vm_page_set_validclean(vm_page_t m, int base, int size)
5198 vm_page_bits_t oldvalid, pagebits;
5201 vm_page_assert_busied(m);
5202 if (size == 0) /* handle degenerate case */
5206 * If the base is not DEV_BSIZE aligned and the valid
5207 * bit is clear, we have to zero out a portion of the
5210 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5211 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
5212 pmap_zero_page_area(m, frag, base - frag);
5215 * If the ending offset is not DEV_BSIZE aligned and the
5216 * valid bit is clear, we have to zero out a portion of
5219 endoff = base + size;
5220 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5221 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
5222 pmap_zero_page_area(m, endoff,
5223 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5226 * Set valid, clear dirty bits. If validating the entire
5227 * page we can safely clear the pmap modify bit. We also
5228 * use this opportunity to clear the PGA_NOSYNC flag. If a process
5229 * takes a write fault on a MAP_NOSYNC memory area the flag will
5232 * We set valid bits inclusive of any overlap, but we can only
5233 * clear dirty bits for DEV_BSIZE chunks that are fully within
5236 oldvalid = m->valid;
5237 pagebits = vm_page_bits(base, size);
5238 if (vm_page_xbusied(m))
5239 m->valid |= pagebits;
5241 vm_page_bits_set(m, &m->valid, pagebits);
5243 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
5244 frag = DEV_BSIZE - frag;
5250 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
5252 if (base == 0 && size == PAGE_SIZE) {
5254 * The page can only be modified within the pmap if it is
5255 * mapped, and it can only be mapped if it was previously
5258 if (oldvalid == VM_PAGE_BITS_ALL)
5260 * Perform the pmap_clear_modify() first. Otherwise,
5261 * a concurrent pmap operation, such as
5262 * pmap_protect(), could clear a modification in the
5263 * pmap and set the dirty field on the page before
5264 * pmap_clear_modify() had begun and after the dirty
5265 * field was cleared here.
5267 pmap_clear_modify(m);
5269 vm_page_aflag_clear(m, PGA_NOSYNC);
5270 } else if (oldvalid != VM_PAGE_BITS_ALL && vm_page_xbusied(m))
5271 m->dirty &= ~pagebits;
5273 vm_page_clear_dirty_mask(m, pagebits);
5277 vm_page_clear_dirty(vm_page_t m, int base, int size)
5280 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
5284 * vm_page_set_invalid:
5286 * Invalidates DEV_BSIZE'd chunks within a page. Both the
5287 * valid and dirty bits for the effected areas are cleared.
5290 vm_page_set_invalid(vm_page_t m, int base, int size)
5292 vm_page_bits_t bits;
5296 * The object lock is required so that pages can't be mapped
5297 * read-only while we're in the process of invalidating them.
5300 VM_OBJECT_ASSERT_WLOCKED(object);
5301 vm_page_assert_busied(m);
5303 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
5304 size >= object->un_pager.vnp.vnp_size)
5305 bits = VM_PAGE_BITS_ALL;
5307 bits = vm_page_bits(base, size);
5308 if (object->ref_count != 0 && vm_page_all_valid(m) && bits != 0)
5310 KASSERT((bits == 0 && vm_page_all_valid(m)) ||
5311 !pmap_page_is_mapped(m),
5312 ("vm_page_set_invalid: page %p is mapped", m));
5313 if (vm_page_xbusied(m)) {
5317 vm_page_bits_clear(m, &m->valid, bits);
5318 vm_page_bits_clear(m, &m->dirty, bits);
5325 * Invalidates the entire page. The page must be busy, unmapped, and
5326 * the enclosing object must be locked. The object locks protects
5327 * against concurrent read-only pmap enter which is done without
5331 vm_page_invalid(vm_page_t m)
5334 vm_page_assert_busied(m);
5335 VM_OBJECT_ASSERT_LOCKED(m->object);
5336 MPASS(!pmap_page_is_mapped(m));
5338 if (vm_page_xbusied(m))
5341 vm_page_bits_clear(m, &m->valid, VM_PAGE_BITS_ALL);
5345 * vm_page_zero_invalid()
5347 * The kernel assumes that the invalid portions of a page contain
5348 * garbage, but such pages can be mapped into memory by user code.
5349 * When this occurs, we must zero out the non-valid portions of the
5350 * page so user code sees what it expects.
5352 * Pages are most often semi-valid when the end of a file is mapped
5353 * into memory and the file's size is not page aligned.
5356 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
5362 * Scan the valid bits looking for invalid sections that
5363 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
5364 * valid bit may be set ) have already been zeroed by
5365 * vm_page_set_validclean().
5367 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
5368 if (i == (PAGE_SIZE / DEV_BSIZE) ||
5369 (m->valid & ((vm_page_bits_t)1 << i))) {
5371 pmap_zero_page_area(m,
5372 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
5379 * setvalid is TRUE when we can safely set the zero'd areas
5380 * as being valid. We can do this if there are no cache consistancy
5381 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
5390 * Is (partial) page valid? Note that the case where size == 0
5391 * will return FALSE in the degenerate case where the page is
5392 * entirely invalid, and TRUE otherwise.
5394 * Some callers envoke this routine without the busy lock held and
5395 * handle races via higher level locks. Typical callers should
5396 * hold a busy lock to prevent invalidation.
5399 vm_page_is_valid(vm_page_t m, int base, int size)
5401 vm_page_bits_t bits;
5403 bits = vm_page_bits(base, size);
5404 return (m->valid != 0 && (m->valid & bits) == bits);
5408 * Returns true if all of the specified predicates are true for the entire
5409 * (super)page and false otherwise.
5412 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
5418 if (skip_m != NULL && skip_m->object != object)
5420 VM_OBJECT_ASSERT_LOCKED(object);
5421 npages = atop(pagesizes[m->psind]);
5424 * The physically contiguous pages that make up a superpage, i.e., a
5425 * page with a page size index ("psind") greater than zero, will
5426 * occupy adjacent entries in vm_page_array[].
5428 for (i = 0; i < npages; i++) {
5429 /* Always test object consistency, including "skip_m". */
5430 if (m[i].object != object)
5432 if (&m[i] == skip_m)
5434 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
5436 if ((flags & PS_ALL_DIRTY) != 0) {
5438 * Calling vm_page_test_dirty() or pmap_is_modified()
5439 * might stop this case from spuriously returning
5440 * "false". However, that would require a write lock
5441 * on the object containing "m[i]".
5443 if (m[i].dirty != VM_PAGE_BITS_ALL)
5446 if ((flags & PS_ALL_VALID) != 0 &&
5447 m[i].valid != VM_PAGE_BITS_ALL)
5454 * Set the page's dirty bits if the page is modified.
5457 vm_page_test_dirty(vm_page_t m)
5460 vm_page_assert_busied(m);
5461 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
5466 vm_page_valid(vm_page_t m)
5469 vm_page_assert_busied(m);
5470 if (vm_page_xbusied(m))
5471 m->valid = VM_PAGE_BITS_ALL;
5473 vm_page_bits_set(m, &m->valid, VM_PAGE_BITS_ALL);
5477 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
5480 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
5484 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
5487 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
5491 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
5494 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
5497 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
5499 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
5502 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
5506 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
5509 mtx_assert_(vm_page_lockptr(m), a, file, line);
5515 vm_page_object_busy_assert(vm_page_t m)
5519 * Certain of the page's fields may only be modified by the
5520 * holder of a page or object busy.
5522 if (m->object != NULL && !vm_page_busied(m))
5523 VM_OBJECT_ASSERT_BUSY(m->object);
5527 vm_page_assert_pga_writeable(vm_page_t m, uint16_t bits)
5530 if ((bits & PGA_WRITEABLE) == 0)
5534 * The PGA_WRITEABLE flag can only be set if the page is
5535 * managed, is exclusively busied or the object is locked.
5536 * Currently, this flag is only set by pmap_enter().
5538 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5539 ("PGA_WRITEABLE on unmanaged page"));
5540 if (!vm_page_xbusied(m))
5541 VM_OBJECT_ASSERT_BUSY(m->object);
5545 #include "opt_ddb.h"
5547 #include <sys/kernel.h>
5549 #include <ddb/ddb.h>
5551 DB_SHOW_COMMAND(page, vm_page_print_page_info)
5554 db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
5555 db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
5556 db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
5557 db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
5558 db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
5559 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
5560 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
5561 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
5562 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
5565 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
5569 db_printf("pq_free %d\n", vm_free_count());
5570 for (dom = 0; dom < vm_ndomains; dom++) {
5572 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
5574 vm_dom[dom].vmd_page_count,
5575 vm_dom[dom].vmd_free_count,
5576 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
5577 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
5578 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
5579 vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
5583 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
5586 boolean_t phys, virt;
5589 db_printf("show pginfo addr\n");
5593 phys = strchr(modif, 'p') != NULL;
5594 virt = strchr(modif, 'v') != NULL;
5596 m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
5598 m = PHYS_TO_VM_PAGE(addr);
5600 m = (vm_page_t)addr;
5602 "page %p obj %p pidx 0x%jx phys 0x%jx q %d ref 0x%x\n"
5603 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
5604 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
5605 m->a.queue, m->ref_count, m->a.flags, m->oflags,
5606 m->flags, m->a.act_count, m->busy_lock, m->valid, m->dirty);