2 * SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)
4 * Copyright (c) 1991 Regents of the University of California.
6 * Copyright (c) 1998 Matthew Dillon. All Rights Reserved.
8 * This code is derived from software contributed to Berkeley by
9 * The Mach Operating System project at Carnegie-Mellon University.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * from: @(#)vm_page.c 7.4 (Berkeley) 5/7/91
39 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
40 * All rights reserved.
42 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
44 * Permission to use, copy, modify and distribute this software and
45 * its documentation is hereby granted, provided that both the copyright
46 * notice and this permission notice appear in all copies of the
47 * software, derivative works or modified versions, and any portions
48 * thereof, and that both notices appear in supporting documentation.
50 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
51 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
52 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
54 * Carnegie Mellon requests users of this software to return to
56 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
57 * School of Computer Science
58 * Carnegie Mellon University
59 * Pittsburgh PA 15213-3890
61 * any improvements or extensions that they make and grant Carnegie the
62 * rights to redistribute these changes.
66 * Resident memory management module.
69 #include <sys/cdefs.h>
70 __FBSDID("$FreeBSD$");
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/counter.h>
77 #include <sys/domainset.h>
78 #include <sys/kernel.h>
79 #include <sys/limits.h>
80 #include <sys/linker.h>
82 #include <sys/malloc.h>
84 #include <sys/msgbuf.h>
85 #include <sys/mutex.h>
87 #include <sys/rwlock.h>
88 #include <sys/sleepqueue.h>
90 #include <sys/sched.h>
92 #include <sys/sysctl.h>
93 #include <sys/vmmeter.h>
94 #include <sys/vnode.h>
98 #include <vm/vm_param.h>
99 #include <vm/vm_domainset.h>
100 #include <vm/vm_kern.h>
101 #include <vm/vm_map.h>
102 #include <vm/vm_object.h>
103 #include <vm/vm_page.h>
104 #include <vm/vm_pageout.h>
105 #include <vm/vm_phys.h>
106 #include <vm/vm_pagequeue.h>
107 #include <vm/vm_pager.h>
108 #include <vm/vm_radix.h>
109 #include <vm/vm_reserv.h>
110 #include <vm/vm_extern.h>
112 #include <vm/uma_int.h>
114 #include <machine/md_var.h>
116 struct vm_domain vm_dom[MAXMEMDOM];
118 DPCPU_DEFINE_STATIC(struct vm_batchqueue, pqbatch[MAXMEMDOM][PQ_COUNT]);
120 struct mtx_padalign __exclusive_cache_line pa_lock[PA_LOCK_COUNT];
122 struct mtx_padalign __exclusive_cache_line vm_domainset_lock;
123 /* The following fields are protected by the domainset lock. */
124 domainset_t __exclusive_cache_line vm_min_domains;
125 domainset_t __exclusive_cache_line vm_severe_domains;
126 static int vm_min_waiters;
127 static int vm_severe_waiters;
128 static int vm_pageproc_waiters;
130 static SYSCTL_NODE(_vm_stats, OID_AUTO, page, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
131 "VM page statistics");
133 static COUNTER_U64_DEFINE_EARLY(pqstate_commit_retries);
134 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, pqstate_commit_retries,
135 CTLFLAG_RD, &pqstate_commit_retries,
136 "Number of failed per-page atomic queue state updates");
138 static COUNTER_U64_DEFINE_EARLY(queue_ops);
139 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, queue_ops,
140 CTLFLAG_RD, &queue_ops,
141 "Number of batched queue operations");
143 static COUNTER_U64_DEFINE_EARLY(queue_nops);
144 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, queue_nops,
145 CTLFLAG_RD, &queue_nops,
146 "Number of batched queue operations with no effects");
149 * bogus page -- for I/O to/from partially complete buffers,
150 * or for paging into sparsely invalid regions.
152 vm_page_t bogus_page;
154 vm_page_t vm_page_array;
155 long vm_page_array_size;
158 struct bitset *vm_page_dump;
159 long vm_page_dump_pages;
161 static TAILQ_HEAD(, vm_page) blacklist_head;
162 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
163 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
164 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
166 static uma_zone_t fakepg_zone;
168 static void vm_page_alloc_check(vm_page_t m);
169 static bool _vm_page_busy_sleep(vm_object_t obj, vm_page_t m,
170 vm_pindex_t pindex, const char *wmesg, int allocflags, bool locked);
171 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
172 static void vm_page_enqueue(vm_page_t m, uint8_t queue);
173 static bool vm_page_free_prep(vm_page_t m);
174 static void vm_page_free_toq(vm_page_t m);
175 static void vm_page_init(void *dummy);
176 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
177 vm_pindex_t pindex, vm_page_t mpred);
178 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
180 static void vm_page_mvqueue(vm_page_t m, const uint8_t queue,
181 const uint16_t nflag);
182 static int vm_page_reclaim_run(int req_class, int domain, u_long npages,
183 vm_page_t m_run, vm_paddr_t high);
184 static void vm_page_release_toq(vm_page_t m, uint8_t nqueue, bool noreuse);
185 static int vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object,
187 static int vm_page_zone_import(void *arg, void **store, int cnt, int domain,
189 static void vm_page_zone_release(void *arg, void **store, int cnt);
191 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
194 vm_page_init(void *dummy)
197 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
198 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
199 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
200 VM_ALLOC_NORMAL | 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;
555 char *list, *listend;
556 vm_paddr_t end, high_avail, low_avail, new_end, size;
557 vm_paddr_t page_range __unused;
558 vm_paddr_t last_pa, pa;
560 #if MINIDUMP_PAGE_TRACKING
561 u_long vm_page_dump_size;
563 int biggestone, i, segind;
568 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
572 vaddr = round_page(vaddr);
574 vm_phys_early_startup();
575 biggestone = vm_phys_avail_largest();
576 end = phys_avail[biggestone+1];
579 * Initialize the page and queue locks.
581 mtx_init(&vm_domainset_lock, "vm domainset lock", NULL, MTX_DEF);
582 for (i = 0; i < PA_LOCK_COUNT; i++)
583 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
584 for (i = 0; i < vm_ndomains; i++)
585 vm_page_domain_init(i);
589 witness_size = round_page(witness_startup_count());
590 new_end -= witness_size;
591 mapped = pmap_map(&vaddr, new_end, new_end + witness_size,
592 VM_PROT_READ | VM_PROT_WRITE);
593 bzero((void *)mapped, witness_size);
594 witness_startup((void *)mapped);
597 #if MINIDUMP_PAGE_TRACKING
599 * Allocate a bitmap to indicate that a random physical page
600 * needs to be included in a minidump.
602 * The amd64 port needs this to indicate which direct map pages
603 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
605 * However, i386 still needs this workspace internally within the
606 * minidump code. In theory, they are not needed on i386, but are
607 * included should the sf_buf code decide to use them.
610 vm_page_dump_pages = 0;
611 for (i = 0; dump_avail[i + 1] != 0; i += 2) {
612 vm_page_dump_pages += howmany(dump_avail[i + 1], PAGE_SIZE) -
613 dump_avail[i] / PAGE_SIZE;
614 if (dump_avail[i + 1] > last_pa)
615 last_pa = dump_avail[i + 1];
617 vm_page_dump_size = round_page(BITSET_SIZE(vm_page_dump_pages));
618 new_end -= vm_page_dump_size;
619 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
620 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
621 bzero((void *)vm_page_dump, vm_page_dump_size);
625 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
626 defined(__riscv) || defined(__powerpc64__)
628 * Include the UMA bootstrap pages, witness pages and vm_page_dump
629 * in a crash dump. When pmap_map() uses the direct map, they are
630 * not automatically included.
632 for (pa = new_end; pa < end; pa += PAGE_SIZE)
635 phys_avail[biggestone + 1] = new_end;
638 * Request that the physical pages underlying the message buffer be
639 * included in a crash dump. Since the message buffer is accessed
640 * through the direct map, they are not automatically included.
642 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
643 last_pa = pa + round_page(msgbufsize);
644 while (pa < last_pa) {
650 * Compute the number of pages of memory that will be available for
651 * use, taking into account the overhead of a page structure per page.
652 * In other words, solve
653 * "available physical memory" - round_page(page_range *
654 * sizeof(struct vm_page)) = page_range * PAGE_SIZE
657 low_avail = phys_avail[0];
658 high_avail = phys_avail[1];
659 for (i = 0; i < vm_phys_nsegs; i++) {
660 if (vm_phys_segs[i].start < low_avail)
661 low_avail = vm_phys_segs[i].start;
662 if (vm_phys_segs[i].end > high_avail)
663 high_avail = vm_phys_segs[i].end;
665 /* Skip the first chunk. It is already accounted for. */
666 for (i = 2; phys_avail[i + 1] != 0; i += 2) {
667 if (phys_avail[i] < low_avail)
668 low_avail = phys_avail[i];
669 if (phys_avail[i + 1] > high_avail)
670 high_avail = phys_avail[i + 1];
672 first_page = low_avail / PAGE_SIZE;
673 #ifdef VM_PHYSSEG_SPARSE
675 for (i = 0; i < vm_phys_nsegs; i++)
676 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
677 for (i = 0; phys_avail[i + 1] != 0; i += 2)
678 size += phys_avail[i + 1] - phys_avail[i];
679 #elif defined(VM_PHYSSEG_DENSE)
680 size = high_avail - low_avail;
682 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
685 #ifdef PMAP_HAS_PAGE_ARRAY
686 pmap_page_array_startup(size / PAGE_SIZE);
687 biggestone = vm_phys_avail_largest();
688 end = new_end = phys_avail[biggestone + 1];
690 #ifdef VM_PHYSSEG_DENSE
692 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
693 * the overhead of a page structure per page only if vm_page_array is
694 * allocated from the last physical memory chunk. Otherwise, we must
695 * allocate page structures representing the physical memory
696 * underlying vm_page_array, even though they will not be used.
698 if (new_end != high_avail)
699 page_range = size / PAGE_SIZE;
703 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
706 * If the partial bytes remaining are large enough for
707 * a page (PAGE_SIZE) without a corresponding
708 * 'struct vm_page', then new_end will contain an
709 * extra page after subtracting the length of the VM
710 * page array. Compensate by subtracting an extra
713 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
714 if (new_end == high_avail)
715 high_avail -= PAGE_SIZE;
716 new_end -= PAGE_SIZE;
720 new_end = vm_page_array_alloc(&vaddr, end, page_range);
723 #if VM_NRESERVLEVEL > 0
725 * Allocate physical memory for the reservation management system's
726 * data structures, and map it.
728 new_end = vm_reserv_startup(&vaddr, new_end);
730 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
731 defined(__riscv) || defined(__powerpc64__)
733 * Include vm_page_array and vm_reserv_array in a crash dump.
735 for (pa = new_end; pa < end; pa += PAGE_SIZE)
738 phys_avail[biggestone + 1] = new_end;
741 * Add physical memory segments corresponding to the available
744 for (i = 0; phys_avail[i + 1] != 0; i += 2)
745 if (vm_phys_avail_size(i) != 0)
746 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
749 * Initialize the physical memory allocator.
754 * Initialize the page structures and add every available page to the
755 * physical memory allocator's free lists.
757 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
758 for (ii = 0; ii < vm_page_array_size; ii++) {
759 m = &vm_page_array[ii];
760 vm_page_init_page(m, (first_page + ii) << PAGE_SHIFT, 0);
761 m->flags = PG_FICTITIOUS;
764 vm_cnt.v_page_count = 0;
765 for (segind = 0; segind < vm_phys_nsegs; segind++) {
766 seg = &vm_phys_segs[segind];
767 for (m = seg->first_page, pa = seg->start; pa < seg->end;
768 m++, pa += PAGE_SIZE)
769 vm_page_init_page(m, pa, segind);
772 * Add the segment to the free lists only if it is covered by
773 * one of the ranges in phys_avail. Because we've added the
774 * ranges to the vm_phys_segs array, we can assume that each
775 * segment is either entirely contained in one of the ranges,
776 * or doesn't overlap any of them.
778 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
779 struct vm_domain *vmd;
781 if (seg->start < phys_avail[i] ||
782 seg->end > phys_avail[i + 1])
786 pagecount = (u_long)atop(seg->end - 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;
795 vmd = VM_DOMAIN(seg->domain);
796 vmd->vmd_page_count += (u_int)pagecount;
797 vmd->vmd_segs |= 1UL << m->segind;
803 * Remove blacklisted pages from the physical memory allocator.
805 TAILQ_INIT(&blacklist_head);
806 vm_page_blacklist_load(&list, &listend);
807 vm_page_blacklist_check(list, listend);
809 list = kern_getenv("vm.blacklist");
810 vm_page_blacklist_check(list, NULL);
813 #if VM_NRESERVLEVEL > 0
815 * Initialize the reservation management system.
824 vm_page_reference(vm_page_t m)
827 vm_page_aflag_set(m, PGA_REFERENCED);
833 * Helper routine for grab functions to trylock busy.
835 * Returns true on success and false on failure.
838 vm_page_trybusy(vm_page_t m, int allocflags)
841 if ((allocflags & (VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY)) != 0)
842 return (vm_page_trysbusy(m));
844 return (vm_page_tryxbusy(m));
850 * Helper routine for grab functions to trylock busy and wire.
852 * Returns true on success and false on failure.
855 vm_page_tryacquire(vm_page_t m, int allocflags)
859 locked = vm_page_trybusy(m, allocflags);
860 if (locked && (allocflags & VM_ALLOC_WIRED) != 0)
866 * vm_page_busy_acquire:
868 * Acquire the busy lock as described by VM_ALLOC_* flags. Will loop
869 * and drop the object lock if necessary.
872 vm_page_busy_acquire(vm_page_t m, int allocflags)
878 * The page-specific object must be cached because page
879 * identity can change during the sleep, causing the
880 * re-lock of a different object.
881 * It is assumed that a reference to the object is already
882 * held by the callers.
886 if (vm_page_tryacquire(m, allocflags))
888 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
891 locked = VM_OBJECT_WOWNED(obj);
894 MPASS(locked || vm_page_wired(m));
895 if (_vm_page_busy_sleep(obj, m, m->pindex, "vmpba", allocflags,
897 VM_OBJECT_WLOCK(obj);
898 if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
900 KASSERT(m->object == obj || m->object == NULL,
901 ("vm_page_busy_acquire: page %p does not belong to %p",
907 * vm_page_busy_downgrade:
909 * Downgrade an exclusive busy page into a single shared busy page.
912 vm_page_busy_downgrade(vm_page_t m)
916 vm_page_assert_xbusied(m);
918 x = vm_page_busy_fetch(m);
920 if (atomic_fcmpset_rel_int(&m->busy_lock,
921 &x, VPB_SHARERS_WORD(1)))
924 if ((x & VPB_BIT_WAITERS) != 0)
930 * vm_page_busy_tryupgrade:
932 * Attempt to upgrade a single shared busy into an exclusive busy.
935 vm_page_busy_tryupgrade(vm_page_t m)
939 vm_page_assert_sbusied(m);
941 x = vm_page_busy_fetch(m);
942 ce = VPB_CURTHREAD_EXCLUSIVE;
944 if (VPB_SHARERS(x) > 1)
946 KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
947 ("vm_page_busy_tryupgrade: invalid lock state"));
948 if (!atomic_fcmpset_acq_int(&m->busy_lock, &x,
949 ce | (x & VPB_BIT_WAITERS)))
958 * Return a positive value if the page is shared busied, 0 otherwise.
961 vm_page_sbusied(vm_page_t m)
965 x = vm_page_busy_fetch(m);
966 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
972 * Shared unbusy a page.
975 vm_page_sunbusy(vm_page_t m)
979 vm_page_assert_sbusied(m);
981 x = vm_page_busy_fetch(m);
983 KASSERT(x != VPB_FREED,
984 ("vm_page_sunbusy: Unlocking freed page."));
985 if (VPB_SHARERS(x) > 1) {
986 if (atomic_fcmpset_int(&m->busy_lock, &x,
991 KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
992 ("vm_page_sunbusy: invalid lock state"));
993 if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
995 if ((x & VPB_BIT_WAITERS) == 0)
1003 * vm_page_busy_sleep:
1005 * Sleep if the page is busy, using the page pointer as wchan.
1006 * This is used to implement the hard-path of busying mechanism.
1008 * If nonshared is true, sleep only if the page is xbusy.
1010 * The object lock must be held on entry and will be released on exit.
1013 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
1018 VM_OBJECT_ASSERT_LOCKED(obj);
1019 vm_page_lock_assert(m, MA_NOTOWNED);
1021 if (!_vm_page_busy_sleep(obj, m, m->pindex, wmesg,
1022 nonshared ? VM_ALLOC_SBUSY : 0 , true))
1023 VM_OBJECT_DROP(obj);
1027 * vm_page_busy_sleep_unlocked:
1029 * Sleep if the page is busy, using the page pointer as wchan.
1030 * This is used to implement the hard-path of busying mechanism.
1032 * If nonshared is true, sleep only if the page is xbusy.
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, bool nonshared)
1042 VM_OBJECT_ASSERT_UNLOCKED(obj);
1043 vm_page_lock_assert(m, MA_NOTOWNED);
1045 _vm_page_busy_sleep(obj, m, pindex, wmesg,
1046 nonshared ? VM_ALLOC_SBUSY : 0, false);
1050 * _vm_page_busy_sleep:
1052 * Internal busy sleep function. Verifies the page identity and
1053 * lockstate against parameters. Returns true if it sleeps and
1056 * If locked is true the lock will be dropped for any true returns
1057 * and held for any false returns.
1060 _vm_page_busy_sleep(vm_object_t obj, vm_page_t m, vm_pindex_t pindex,
1061 const char *wmesg, int allocflags, bool locked)
1067 * If the object is busy we must wait for that to drain to zero
1068 * before trying the page again.
1070 if (obj != NULL && vm_object_busied(obj)) {
1072 VM_OBJECT_DROP(obj);
1073 vm_object_busy_wait(obj, wmesg);
1077 if (!vm_page_busied(m))
1080 xsleep = (allocflags & (VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY)) != 0;
1082 x = vm_page_busy_fetch(m);
1085 * If the page changes objects or becomes unlocked we can
1088 if (x == VPB_UNBUSIED ||
1089 (xsleep && (x & VPB_BIT_SHARED) != 0) ||
1090 m->object != obj || m->pindex != pindex) {
1094 if ((x & VPB_BIT_WAITERS) != 0)
1096 } while (!atomic_fcmpset_int(&m->busy_lock, &x, x | VPB_BIT_WAITERS));
1098 VM_OBJECT_DROP(obj);
1100 sleepq_add(m, NULL, wmesg, 0, 0);
1101 sleepq_wait(m, PVM);
1109 * Try to shared busy a page.
1110 * If the operation succeeds 1 is returned otherwise 0.
1111 * The operation never sleeps.
1114 vm_page_trysbusy(vm_page_t m)
1120 x = vm_page_busy_fetch(m);
1122 if ((x & VPB_BIT_SHARED) == 0)
1125 * Reduce the window for transient busies that will trigger
1126 * false negatives in vm_page_ps_test().
1128 if (obj != NULL && vm_object_busied(obj))
1130 if (atomic_fcmpset_acq_int(&m->busy_lock, &x,
1131 x + VPB_ONE_SHARER))
1135 /* Refetch the object now that we're guaranteed that it is stable. */
1137 if (obj != NULL && vm_object_busied(obj)) {
1147 * Try to exclusive busy a page.
1148 * If the operation succeeds 1 is returned otherwise 0.
1149 * The operation never sleeps.
1152 vm_page_tryxbusy(vm_page_t m)
1156 if (atomic_cmpset_acq_int(&m->busy_lock, VPB_UNBUSIED,
1157 VPB_CURTHREAD_EXCLUSIVE) == 0)
1161 if (obj != NULL && vm_object_busied(obj)) {
1169 vm_page_xunbusy_hard_tail(vm_page_t m)
1171 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1172 /* Wake the waiter. */
1177 * vm_page_xunbusy_hard:
1179 * Called when unbusy has failed because there is a waiter.
1182 vm_page_xunbusy_hard(vm_page_t m)
1184 vm_page_assert_xbusied(m);
1185 vm_page_xunbusy_hard_tail(m);
1189 vm_page_xunbusy_hard_unchecked(vm_page_t m)
1191 vm_page_assert_xbusied_unchecked(m);
1192 vm_page_xunbusy_hard_tail(m);
1196 vm_page_busy_free(vm_page_t m)
1200 atomic_thread_fence_rel();
1201 x = atomic_swap_int(&m->busy_lock, VPB_FREED);
1202 if ((x & VPB_BIT_WAITERS) != 0)
1207 * vm_page_unhold_pages:
1209 * Unhold each of the pages that is referenced by the given array.
1212 vm_page_unhold_pages(vm_page_t *ma, int count)
1215 for (; count != 0; count--) {
1216 vm_page_unwire(*ma, PQ_ACTIVE);
1222 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1226 #ifdef VM_PHYSSEG_SPARSE
1227 m = vm_phys_paddr_to_vm_page(pa);
1229 m = vm_phys_fictitious_to_vm_page(pa);
1231 #elif defined(VM_PHYSSEG_DENSE)
1235 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1236 m = &vm_page_array[pi - first_page];
1239 return (vm_phys_fictitious_to_vm_page(pa));
1241 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1248 * Create a fictitious page with the specified physical address and
1249 * memory attribute. The memory attribute is the only the machine-
1250 * dependent aspect of a fictitious page that must be initialized.
1253 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1257 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1258 vm_page_initfake(m, paddr, memattr);
1263 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1266 if ((m->flags & PG_FICTITIOUS) != 0) {
1268 * The page's memattr might have changed since the
1269 * previous initialization. Update the pmap to the
1274 m->phys_addr = paddr;
1275 m->a.queue = PQ_NONE;
1276 /* Fictitious pages don't use "segind". */
1277 m->flags = PG_FICTITIOUS;
1278 /* Fictitious pages don't use "order" or "pool". */
1279 m->oflags = VPO_UNMANAGED;
1280 m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
1281 /* Fictitious pages are unevictable. */
1285 pmap_page_set_memattr(m, memattr);
1291 * Release a fictitious page.
1294 vm_page_putfake(vm_page_t m)
1297 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1298 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1299 ("vm_page_putfake: bad page %p", m));
1300 vm_page_assert_xbusied(m);
1301 vm_page_busy_free(m);
1302 uma_zfree(fakepg_zone, m);
1306 * vm_page_updatefake:
1308 * Update the given fictitious page to the specified physical address and
1312 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1315 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1316 ("vm_page_updatefake: bad page %p", m));
1317 m->phys_addr = paddr;
1318 pmap_page_set_memattr(m, memattr);
1327 vm_page_free(vm_page_t m)
1330 m->flags &= ~PG_ZERO;
1331 vm_page_free_toq(m);
1335 * vm_page_free_zero:
1337 * Free a page to the zerod-pages queue
1340 vm_page_free_zero(vm_page_t m)
1343 m->flags |= PG_ZERO;
1344 vm_page_free_toq(m);
1348 * Unbusy and handle the page queueing for a page from a getpages request that
1349 * was optionally read ahead or behind.
1352 vm_page_readahead_finish(vm_page_t m)
1355 /* We shouldn't put invalid pages on queues. */
1356 KASSERT(!vm_page_none_valid(m), ("%s: %p is invalid", __func__, m));
1359 * Since the page is not the actually needed one, whether it should
1360 * be activated or deactivated is not obvious. Empirical results
1361 * have shown that deactivating the page is usually the best choice,
1362 * unless the page is wanted by another thread.
1364 if ((vm_page_busy_fetch(m) & VPB_BIT_WAITERS) != 0)
1365 vm_page_activate(m);
1367 vm_page_deactivate(m);
1368 vm_page_xunbusy_unchecked(m);
1372 * Destroy the identity of an invalid page and free it if possible.
1373 * This is intended to be used when reading a page from backing store fails.
1376 vm_page_free_invalid(vm_page_t m)
1379 KASSERT(vm_page_none_valid(m), ("page %p is valid", m));
1380 KASSERT(!pmap_page_is_mapped(m), ("page %p is mapped", m));
1381 KASSERT(m->object != NULL, ("page %p has no object", m));
1382 VM_OBJECT_ASSERT_WLOCKED(m->object);
1385 * We may be attempting to free the page as part of the handling for an
1386 * I/O error, in which case the page was xbusied by a different thread.
1388 vm_page_xbusy_claim(m);
1391 * If someone has wired this page while the object lock
1392 * was not held, then the thread that unwires is responsible
1393 * for freeing the page. Otherwise just free the page now.
1394 * The wire count of this unmapped page cannot change while
1395 * we have the page xbusy and the page's object wlocked.
1397 if (vm_page_remove(m))
1402 * vm_page_sleep_if_busy:
1404 * Sleep and release the object lock if the page is busied.
1405 * Returns TRUE if the thread slept.
1407 * The given page must be unlocked and object containing it must
1411 vm_page_sleep_if_busy(vm_page_t m, const char *wmesg)
1415 vm_page_lock_assert(m, MA_NOTOWNED);
1416 VM_OBJECT_ASSERT_WLOCKED(m->object);
1419 * The page-specific object must be cached because page
1420 * identity can change during the sleep, causing the
1421 * re-lock of a different object.
1422 * It is assumed that a reference to the object is already
1423 * held by the callers.
1426 if (_vm_page_busy_sleep(obj, m, m->pindex, wmesg, 0, true)) {
1427 VM_OBJECT_WLOCK(obj);
1434 * vm_page_sleep_if_xbusy:
1436 * Sleep and release the object lock if the page is xbusied.
1437 * Returns TRUE if the thread slept.
1439 * The given page must be unlocked and object containing it must
1443 vm_page_sleep_if_xbusy(vm_page_t m, const char *wmesg)
1447 vm_page_lock_assert(m, MA_NOTOWNED);
1448 VM_OBJECT_ASSERT_WLOCKED(m->object);
1451 * The page-specific object must be cached because page
1452 * identity can change during the sleep, causing the
1453 * re-lock of a different object.
1454 * It is assumed that a reference to the object is already
1455 * held by the callers.
1458 if (_vm_page_busy_sleep(obj, m, m->pindex, wmesg, VM_ALLOC_SBUSY,
1460 VM_OBJECT_WLOCK(obj);
1467 * vm_page_dirty_KBI: [ internal use only ]
1469 * Set all bits in the page's dirty field.
1471 * The object containing the specified page must be locked if the
1472 * call is made from the machine-independent layer.
1474 * See vm_page_clear_dirty_mask().
1476 * This function should only be called by vm_page_dirty().
1479 vm_page_dirty_KBI(vm_page_t m)
1482 /* Refer to this operation by its public name. */
1483 KASSERT(vm_page_all_valid(m), ("vm_page_dirty: page is invalid!"));
1484 m->dirty = VM_PAGE_BITS_ALL;
1488 * vm_page_insert: [ internal use only ]
1490 * Inserts the given mem entry into the object and object list.
1492 * The object must be locked.
1495 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1499 VM_OBJECT_ASSERT_WLOCKED(object);
1500 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1501 return (vm_page_insert_after(m, object, pindex, mpred));
1505 * vm_page_insert_after:
1507 * Inserts the page "m" into the specified object at offset "pindex".
1509 * The page "mpred" must immediately precede the offset "pindex" within
1510 * the specified object.
1512 * The object must be locked.
1515 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1520 VM_OBJECT_ASSERT_WLOCKED(object);
1521 KASSERT(m->object == NULL,
1522 ("vm_page_insert_after: page already inserted"));
1523 if (mpred != NULL) {
1524 KASSERT(mpred->object == object,
1525 ("vm_page_insert_after: object doesn't contain mpred"));
1526 KASSERT(mpred->pindex < pindex,
1527 ("vm_page_insert_after: mpred doesn't precede pindex"));
1528 msucc = TAILQ_NEXT(mpred, listq);
1530 msucc = TAILQ_FIRST(&object->memq);
1532 KASSERT(msucc->pindex > pindex,
1533 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1536 * Record the object/offset pair in this page.
1540 m->ref_count |= VPRC_OBJREF;
1543 * Now link into the object's ordered list of backed pages.
1545 if (vm_radix_insert(&object->rtree, m)) {
1548 m->ref_count &= ~VPRC_OBJREF;
1551 vm_page_insert_radixdone(m, object, mpred);
1556 * vm_page_insert_radixdone:
1558 * Complete page "m" insertion into the specified object after the
1559 * radix trie hooking.
1561 * The page "mpred" must precede the offset "m->pindex" within the
1564 * The object must be locked.
1567 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1570 VM_OBJECT_ASSERT_WLOCKED(object);
1571 KASSERT(object != NULL && m->object == object,
1572 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1573 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1574 ("vm_page_insert_radixdone: page %p is missing object ref", m));
1575 if (mpred != NULL) {
1576 KASSERT(mpred->object == object,
1577 ("vm_page_insert_radixdone: object doesn't contain mpred"));
1578 KASSERT(mpred->pindex < m->pindex,
1579 ("vm_page_insert_radixdone: mpred doesn't precede pindex"));
1583 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1585 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1588 * Show that the object has one more resident page.
1590 object->resident_page_count++;
1593 * Hold the vnode until the last page is released.
1595 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1596 vhold(object->handle);
1599 * Since we are inserting a new and possibly dirty page,
1600 * update the object's generation count.
1602 if (pmap_page_is_write_mapped(m))
1603 vm_object_set_writeable_dirty(object);
1607 * Do the work to remove a page from its object. The caller is responsible for
1608 * updating the page's fields to reflect this removal.
1611 vm_page_object_remove(vm_page_t m)
1616 vm_page_assert_xbusied(m);
1618 VM_OBJECT_ASSERT_WLOCKED(object);
1619 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1620 ("page %p is missing its object ref", m));
1622 /* Deferred free of swap space. */
1623 if ((m->a.flags & PGA_SWAP_FREE) != 0)
1624 vm_pager_page_unswapped(m);
1627 mrem = vm_radix_remove(&object->rtree, m->pindex);
1628 KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1631 * Now remove from the object's list of backed pages.
1633 TAILQ_REMOVE(&object->memq, m, listq);
1636 * And show that the object has one fewer resident page.
1638 object->resident_page_count--;
1641 * The vnode may now be recycled.
1643 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1644 vdrop(object->handle);
1650 * Removes the specified page from its containing object, but does not
1651 * invalidate any backing storage. Returns true if the object's reference
1652 * was the last reference to the page, and false otherwise.
1654 * The object must be locked and the page must be exclusively busied.
1655 * The exclusive busy will be released on return. If this is not the
1656 * final ref and the caller does not hold a wire reference it may not
1657 * continue to access the page.
1660 vm_page_remove(vm_page_t m)
1664 dropped = vm_page_remove_xbusy(m);
1671 * vm_page_remove_xbusy
1673 * Removes the page but leaves the xbusy held. Returns true if this
1674 * removed the final ref and false otherwise.
1677 vm_page_remove_xbusy(vm_page_t m)
1680 vm_page_object_remove(m);
1681 return (vm_page_drop(m, VPRC_OBJREF) == VPRC_OBJREF);
1687 * Returns the page associated with the object/offset
1688 * pair specified; if none is found, NULL is returned.
1690 * The object must be locked.
1693 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1696 VM_OBJECT_ASSERT_LOCKED(object);
1697 return (vm_radix_lookup(&object->rtree, pindex));
1703 * Returns a page that must already have been busied by
1704 * the caller. Used for bogus page replacement.
1707 vm_page_relookup(vm_object_t object, vm_pindex_t pindex)
1711 m = vm_radix_lookup_unlocked(&object->rtree, pindex);
1712 KASSERT(m != NULL && (vm_page_busied(m) || vm_page_wired(m)) &&
1713 m->object == object && m->pindex == pindex,
1714 ("vm_page_relookup: Invalid page %p", m));
1719 * This should only be used by lockless functions for releasing transient
1720 * incorrect acquires. The page may have been freed after we acquired a
1721 * busy lock. In this case busy_lock == VPB_FREED and we have nothing
1725 vm_page_busy_release(vm_page_t m)
1729 x = vm_page_busy_fetch(m);
1733 if ((x & VPB_BIT_SHARED) != 0 && VPB_SHARERS(x) > 1) {
1734 if (atomic_fcmpset_int(&m->busy_lock, &x,
1735 x - VPB_ONE_SHARER))
1739 KASSERT((x & VPB_BIT_SHARED) != 0 ||
1740 (x & ~VPB_BIT_WAITERS) == VPB_CURTHREAD_EXCLUSIVE,
1741 ("vm_page_busy_release: %p xbusy not owned.", m));
1742 if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
1744 if ((x & VPB_BIT_WAITERS) != 0)
1751 * vm_page_find_least:
1753 * Returns the page associated with the object with least pindex
1754 * greater than or equal to the parameter pindex, or NULL.
1756 * The object must be locked.
1759 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1763 VM_OBJECT_ASSERT_LOCKED(object);
1764 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1765 m = vm_radix_lookup_ge(&object->rtree, pindex);
1770 * Returns the given page's successor (by pindex) within the object if it is
1771 * resident; if none is found, NULL is returned.
1773 * The object must be locked.
1776 vm_page_next(vm_page_t m)
1780 VM_OBJECT_ASSERT_LOCKED(m->object);
1781 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1782 MPASS(next->object == m->object);
1783 if (next->pindex != m->pindex + 1)
1790 * Returns the given page's predecessor (by pindex) within the object if it is
1791 * resident; if none is found, NULL is returned.
1793 * The object must be locked.
1796 vm_page_prev(vm_page_t m)
1800 VM_OBJECT_ASSERT_LOCKED(m->object);
1801 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1802 MPASS(prev->object == m->object);
1803 if (prev->pindex != m->pindex - 1)
1810 * Uses the page mnew as a replacement for an existing page at index
1811 * pindex which must be already present in the object.
1813 * Both pages must be exclusively busied on enter. The old page is
1816 * A return value of true means mold is now free. If this is not the
1817 * final ref and the caller does not hold a wire reference it may not
1818 * continue to access the page.
1821 vm_page_replace_hold(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1827 VM_OBJECT_ASSERT_WLOCKED(object);
1828 vm_page_assert_xbusied(mold);
1829 KASSERT(mnew->object == NULL && (mnew->ref_count & VPRC_OBJREF) == 0,
1830 ("vm_page_replace: page %p already in object", mnew));
1833 * This function mostly follows vm_page_insert() and
1834 * vm_page_remove() without the radix, object count and vnode
1835 * dance. Double check such functions for more comments.
1838 mnew->object = object;
1839 mnew->pindex = pindex;
1840 atomic_set_int(&mnew->ref_count, VPRC_OBJREF);
1841 mret = vm_radix_replace(&object->rtree, mnew);
1842 KASSERT(mret == mold,
1843 ("invalid page replacement, mold=%p, mret=%p", mold, mret));
1844 KASSERT((mold->oflags & VPO_UNMANAGED) ==
1845 (mnew->oflags & VPO_UNMANAGED),
1846 ("vm_page_replace: mismatched VPO_UNMANAGED"));
1848 /* Keep the resident page list in sorted order. */
1849 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1850 TAILQ_REMOVE(&object->memq, mold, listq);
1851 mold->object = NULL;
1854 * The object's resident_page_count does not change because we have
1855 * swapped one page for another, but the generation count should
1856 * change if the page is dirty.
1858 if (pmap_page_is_write_mapped(mnew))
1859 vm_object_set_writeable_dirty(object);
1860 dropped = vm_page_drop(mold, VPRC_OBJREF) == VPRC_OBJREF;
1861 vm_page_xunbusy(mold);
1867 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1871 vm_page_assert_xbusied(mnew);
1873 if (vm_page_replace_hold(mnew, object, pindex, mold))
1880 * Move the given memory entry from its
1881 * current object to the specified target object/offset.
1883 * Note: swap associated with the page must be invalidated by the move. We
1884 * have to do this for several reasons: (1) we aren't freeing the
1885 * page, (2) we are dirtying the page, (3) the VM system is probably
1886 * moving the page from object A to B, and will then later move
1887 * the backing store from A to B and we can't have a conflict.
1889 * Note: we *always* dirty the page. It is necessary both for the
1890 * fact that we moved it, and because we may be invalidating
1893 * The objects must be locked.
1896 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1901 VM_OBJECT_ASSERT_WLOCKED(new_object);
1903 KASSERT(m->ref_count != 0, ("vm_page_rename: page %p has no refs", m));
1904 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1905 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1906 ("vm_page_rename: pindex already renamed"));
1909 * Create a custom version of vm_page_insert() which does not depend
1910 * by m_prev and can cheat on the implementation aspects of the
1914 m->pindex = new_pindex;
1915 if (vm_radix_insert(&new_object->rtree, m)) {
1921 * The operation cannot fail anymore. The removal must happen before
1922 * the listq iterator is tainted.
1925 vm_page_object_remove(m);
1927 /* Return back to the new pindex to complete vm_page_insert(). */
1928 m->pindex = new_pindex;
1929 m->object = new_object;
1931 vm_page_insert_radixdone(m, new_object, mpred);
1939 * Allocate and return a page that is associated with the specified
1940 * object and offset pair. By default, this page is exclusive busied.
1942 * The caller must always specify an allocation class.
1944 * allocation classes:
1945 * VM_ALLOC_NORMAL normal process request
1946 * VM_ALLOC_SYSTEM system *really* needs a page
1947 * VM_ALLOC_INTERRUPT interrupt time request
1949 * optional allocation flags:
1950 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1951 * intends to allocate
1952 * VM_ALLOC_NOBUSY do not exclusive busy the page
1953 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1954 * VM_ALLOC_NOOBJ page is not associated with an object and
1955 * should not be exclusive busy
1956 * VM_ALLOC_SBUSY shared busy the allocated page
1957 * VM_ALLOC_WIRED wire the allocated page
1958 * VM_ALLOC_ZERO prefer a zeroed page
1961 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1964 return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1965 vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1969 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1973 return (vm_page_alloc_domain_after(object, pindex, domain, req,
1974 object != NULL ? vm_radix_lookup_le(&object->rtree, pindex) :
1979 * Allocate a page in the specified object with the given page index. To
1980 * optimize insertion of the page into the object, the caller must also specifiy
1981 * the resident page in the object with largest index smaller than the given
1982 * page index, or NULL if no such page exists.
1985 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1986 int req, vm_page_t mpred)
1988 struct vm_domainset_iter di;
1992 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1994 m = vm_page_alloc_domain_after(object, pindex, domain, req,
1998 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
2004 * Returns true if the number of free pages exceeds the minimum
2005 * for the request class and false otherwise.
2008 _vm_domain_allocate(struct vm_domain *vmd, int req_class, int npages)
2010 u_int limit, old, new;
2012 if (req_class == VM_ALLOC_INTERRUPT)
2014 else if (req_class == VM_ALLOC_SYSTEM)
2015 limit = vmd->vmd_interrupt_free_min;
2017 limit = vmd->vmd_free_reserved;
2020 * Attempt to reserve the pages. Fail if we're below the limit.
2023 old = vmd->vmd_free_count;
2028 } while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
2030 /* Wake the page daemon if we've crossed the threshold. */
2031 if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
2032 pagedaemon_wakeup(vmd->vmd_domain);
2034 /* Only update bitsets on transitions. */
2035 if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
2036 (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
2043 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
2048 * The page daemon is allowed to dig deeper into the free page list.
2050 req_class = req & VM_ALLOC_CLASS_MASK;
2051 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2052 req_class = VM_ALLOC_SYSTEM;
2053 return (_vm_domain_allocate(vmd, req_class, npages));
2057 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
2058 int req, vm_page_t mpred)
2060 struct vm_domain *vmd;
2064 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
2065 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
2066 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2067 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2068 ("inconsistent object(%p)/req(%x)", object, req));
2069 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2070 ("Can't sleep and retry object insertion."));
2071 KASSERT(mpred == NULL || mpred->pindex < pindex,
2072 ("mpred %p doesn't precede pindex 0x%jx", mpred,
2073 (uintmax_t)pindex));
2075 VM_OBJECT_ASSERT_WLOCKED(object);
2079 pool = object != NULL ? VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT;
2081 #if VM_NRESERVLEVEL > 0
2083 * Can we allocate the page from a reservation?
2085 if (vm_object_reserv(object) &&
2086 (m = vm_reserv_alloc_page(object, pindex, domain, req, mpred)) !=
2091 vmd = VM_DOMAIN(domain);
2092 if (vmd->vmd_pgcache[pool].zone != NULL) {
2093 m = uma_zalloc(vmd->vmd_pgcache[pool].zone, M_NOWAIT | M_NOVM);
2095 flags |= PG_PCPU_CACHE;
2099 if (vm_domain_allocate(vmd, req, 1)) {
2101 * If not, allocate it from the free page queues.
2103 vm_domain_free_lock(vmd);
2104 m = vm_phys_alloc_pages(domain, pool, 0);
2105 vm_domain_free_unlock(vmd);
2107 vm_domain_freecnt_inc(vmd, 1);
2108 #if VM_NRESERVLEVEL > 0
2109 if (vm_reserv_reclaim_inactive(domain))
2116 * Not allocatable, give up.
2118 if (vm_domain_alloc_fail(vmd, object, req))
2124 * At this point we had better have found a good page.
2128 vm_page_alloc_check(m);
2131 * Initialize the page. Only the PG_ZERO flag is inherited.
2133 if ((req & VM_ALLOC_ZERO) != 0)
2134 flags |= (m->flags & PG_ZERO);
2135 if ((req & VM_ALLOC_NODUMP) != 0)
2139 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2141 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2142 m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2143 else if ((req & VM_ALLOC_SBUSY) != 0)
2144 m->busy_lock = VPB_SHARERS_WORD(1);
2146 m->busy_lock = VPB_UNBUSIED;
2147 if (req & VM_ALLOC_WIRED) {
2153 if (object != NULL) {
2154 if (vm_page_insert_after(m, object, pindex, mpred)) {
2155 if (req & VM_ALLOC_WIRED) {
2159 KASSERT(m->object == NULL, ("page %p has object", m));
2160 m->oflags = VPO_UNMANAGED;
2161 m->busy_lock = VPB_UNBUSIED;
2162 /* Don't change PG_ZERO. */
2163 vm_page_free_toq(m);
2164 if (req & VM_ALLOC_WAITFAIL) {
2165 VM_OBJECT_WUNLOCK(object);
2167 VM_OBJECT_WLOCK(object);
2172 /* Ignore device objects; the pager sets "memattr" for them. */
2173 if (object->memattr != VM_MEMATTR_DEFAULT &&
2174 (object->flags & OBJ_FICTITIOUS) == 0)
2175 pmap_page_set_memattr(m, object->memattr);
2183 * vm_page_alloc_contig:
2185 * Allocate a contiguous set of physical pages of the given size "npages"
2186 * from the free lists. All of the physical pages must be at or above
2187 * the given physical address "low" and below the given physical address
2188 * "high". The given value "alignment" determines the alignment of the
2189 * first physical page in the set. If the given value "boundary" is
2190 * non-zero, then the set of physical pages cannot cross any physical
2191 * address boundary that is a multiple of that value. Both "alignment"
2192 * and "boundary" must be a power of two.
2194 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
2195 * then the memory attribute setting for the physical pages is configured
2196 * to the object's memory attribute setting. Otherwise, the memory
2197 * attribute setting for the physical pages is configured to "memattr",
2198 * overriding the object's memory attribute setting. However, if the
2199 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
2200 * memory attribute setting for the physical pages cannot be configured
2201 * to VM_MEMATTR_DEFAULT.
2203 * The specified object may not contain fictitious pages.
2205 * The caller must always specify an allocation class.
2207 * allocation classes:
2208 * VM_ALLOC_NORMAL normal process request
2209 * VM_ALLOC_SYSTEM system *really* needs a page
2210 * VM_ALLOC_INTERRUPT interrupt time request
2212 * optional allocation flags:
2213 * VM_ALLOC_NOBUSY do not exclusive busy the page
2214 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
2215 * VM_ALLOC_NOOBJ page is not associated with an object and
2216 * should not be exclusive busy
2217 * VM_ALLOC_SBUSY shared busy the allocated page
2218 * VM_ALLOC_WIRED wire the allocated page
2219 * VM_ALLOC_ZERO prefer a zeroed page
2222 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
2223 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2224 vm_paddr_t boundary, vm_memattr_t memattr)
2226 struct vm_domainset_iter di;
2230 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
2232 m = vm_page_alloc_contig_domain(object, pindex, domain, req,
2233 npages, low, high, alignment, boundary, memattr);
2236 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
2242 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
2243 int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2244 vm_paddr_t boundary, vm_memattr_t memattr)
2246 struct vm_domain *vmd;
2247 vm_page_t m, m_ret, mpred;
2248 u_int busy_lock, flags, oflags;
2250 mpred = NULL; /* XXX: pacify gcc */
2251 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
2252 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
2253 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2254 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2255 ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
2257 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2258 ("Can't sleep and retry object insertion."));
2259 if (object != NULL) {
2260 VM_OBJECT_ASSERT_WLOCKED(object);
2261 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2262 ("vm_page_alloc_contig: object %p has fictitious pages",
2265 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2267 if (object != NULL) {
2268 mpred = vm_radix_lookup_le(&object->rtree, pindex);
2269 KASSERT(mpred == NULL || mpred->pindex != pindex,
2270 ("vm_page_alloc_contig: pindex already allocated"));
2274 * Can we allocate the pages without the number of free pages falling
2275 * below the lower bound for the allocation class?
2279 #if VM_NRESERVLEVEL > 0
2281 * Can we allocate the pages from a reservation?
2283 if (vm_object_reserv(object) &&
2284 (m_ret = vm_reserv_alloc_contig(object, pindex, domain, req,
2285 mpred, npages, low, high, alignment, boundary)) != NULL) {
2289 vmd = VM_DOMAIN(domain);
2290 if (vm_domain_allocate(vmd, req, npages)) {
2292 * allocate them from the free page queues.
2294 vm_domain_free_lock(vmd);
2295 m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2296 alignment, boundary);
2297 vm_domain_free_unlock(vmd);
2298 if (m_ret == NULL) {
2299 vm_domain_freecnt_inc(vmd, npages);
2300 #if VM_NRESERVLEVEL > 0
2301 if (vm_reserv_reclaim_contig(domain, npages, low,
2302 high, alignment, boundary))
2307 if (m_ret == NULL) {
2308 if (vm_domain_alloc_fail(vmd, object, req))
2312 #if VM_NRESERVLEVEL > 0
2315 for (m = m_ret; m < &m_ret[npages]; m++) {
2317 vm_page_alloc_check(m);
2321 * Initialize the pages. Only the PG_ZERO flag is inherited.
2324 if ((req & VM_ALLOC_ZERO) != 0)
2326 if ((req & VM_ALLOC_NODUMP) != 0)
2328 oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2330 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2331 busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2332 else if ((req & VM_ALLOC_SBUSY) != 0)
2333 busy_lock = VPB_SHARERS_WORD(1);
2335 busy_lock = VPB_UNBUSIED;
2336 if ((req & VM_ALLOC_WIRED) != 0)
2337 vm_wire_add(npages);
2338 if (object != NULL) {
2339 if (object->memattr != VM_MEMATTR_DEFAULT &&
2340 memattr == VM_MEMATTR_DEFAULT)
2341 memattr = object->memattr;
2343 for (m = m_ret; m < &m_ret[npages]; m++) {
2345 m->flags = (m->flags | PG_NODUMP) & flags;
2346 m->busy_lock = busy_lock;
2347 if ((req & VM_ALLOC_WIRED) != 0)
2351 if (object != NULL) {
2352 if (vm_page_insert_after(m, object, pindex, mpred)) {
2353 if ((req & VM_ALLOC_WIRED) != 0)
2354 vm_wire_sub(npages);
2355 KASSERT(m->object == NULL,
2356 ("page %p has object", m));
2358 for (m = m_ret; m < &m_ret[npages]; m++) {
2360 (req & VM_ALLOC_WIRED) != 0)
2362 m->oflags = VPO_UNMANAGED;
2363 m->busy_lock = VPB_UNBUSIED;
2364 /* Don't change PG_ZERO. */
2365 vm_page_free_toq(m);
2367 if (req & VM_ALLOC_WAITFAIL) {
2368 VM_OBJECT_WUNLOCK(object);
2370 VM_OBJECT_WLOCK(object);
2377 if (memattr != VM_MEMATTR_DEFAULT)
2378 pmap_page_set_memattr(m, memattr);
2385 * Check a page that has been freshly dequeued from a freelist.
2388 vm_page_alloc_check(vm_page_t m)
2391 KASSERT(m->object == NULL, ("page %p has object", m));
2392 KASSERT(m->a.queue == PQ_NONE &&
2393 (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
2394 ("page %p has unexpected queue %d, flags %#x",
2395 m, m->a.queue, (m->a.flags & PGA_QUEUE_STATE_MASK)));
2396 KASSERT(m->ref_count == 0, ("page %p has references", m));
2397 KASSERT(vm_page_busy_freed(m), ("page %p is not freed", m));
2398 KASSERT(m->dirty == 0, ("page %p is dirty", m));
2399 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2400 ("page %p has unexpected memattr %d",
2401 m, pmap_page_get_memattr(m)));
2402 KASSERT(m->valid == 0, ("free page %p is valid", m));
2406 * vm_page_alloc_freelist:
2408 * Allocate a physical page from the specified free page list.
2410 * The caller must always specify an allocation class.
2412 * allocation classes:
2413 * VM_ALLOC_NORMAL normal process request
2414 * VM_ALLOC_SYSTEM system *really* needs a page
2415 * VM_ALLOC_INTERRUPT interrupt time request
2417 * optional allocation flags:
2418 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2419 * intends to allocate
2420 * VM_ALLOC_WIRED wire the allocated page
2421 * VM_ALLOC_ZERO prefer a zeroed page
2424 vm_page_alloc_freelist(int freelist, int req)
2426 struct vm_domainset_iter di;
2430 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2432 m = vm_page_alloc_freelist_domain(domain, freelist, req);
2435 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2441 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2443 struct vm_domain *vmd;
2448 vmd = VM_DOMAIN(domain);
2450 if (vm_domain_allocate(vmd, req, 1)) {
2451 vm_domain_free_lock(vmd);
2452 m = vm_phys_alloc_freelist_pages(domain, freelist,
2453 VM_FREEPOOL_DIRECT, 0);
2454 vm_domain_free_unlock(vmd);
2456 vm_domain_freecnt_inc(vmd, 1);
2459 if (vm_domain_alloc_fail(vmd, NULL, req))
2464 vm_page_alloc_check(m);
2467 * Initialize the page. Only the PG_ZERO flag is inherited.
2471 if ((req & VM_ALLOC_ZERO) != 0)
2474 if ((req & VM_ALLOC_WIRED) != 0) {
2478 /* Unmanaged pages don't use "act_count". */
2479 m->oflags = VPO_UNMANAGED;
2484 vm_page_zone_import(void *arg, void **store, int cnt, int domain, int flags)
2486 struct vm_domain *vmd;
2487 struct vm_pgcache *pgcache;
2491 vmd = VM_DOMAIN(pgcache->domain);
2494 * The page daemon should avoid creating extra memory pressure since its
2495 * main purpose is to replenish the store of free pages.
2497 if (vmd->vmd_severeset || curproc == pageproc ||
2498 !_vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2500 domain = vmd->vmd_domain;
2501 vm_domain_free_lock(vmd);
2502 i = vm_phys_alloc_npages(domain, pgcache->pool, cnt,
2503 (vm_page_t *)store);
2504 vm_domain_free_unlock(vmd);
2506 vm_domain_freecnt_inc(vmd, cnt - i);
2512 vm_page_zone_release(void *arg, void **store, int cnt)
2514 struct vm_domain *vmd;
2515 struct vm_pgcache *pgcache;
2520 vmd = VM_DOMAIN(pgcache->domain);
2521 vm_domain_free_lock(vmd);
2522 for (i = 0; i < cnt; i++) {
2523 m = (vm_page_t)store[i];
2524 vm_phys_free_pages(m, 0);
2526 vm_domain_free_unlock(vmd);
2527 vm_domain_freecnt_inc(vmd, cnt);
2530 #define VPSC_ANY 0 /* No restrictions. */
2531 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2532 #define VPSC_NOSUPER 2 /* Skip superpages. */
2535 * vm_page_scan_contig:
2537 * Scan vm_page_array[] between the specified entries "m_start" and
2538 * "m_end" for a run of contiguous physical pages that satisfy the
2539 * specified conditions, and return the lowest page in the run. The
2540 * specified "alignment" determines the alignment of the lowest physical
2541 * page in the run. If the specified "boundary" is non-zero, then the
2542 * run of physical pages cannot span a physical address that is a
2543 * multiple of "boundary".
2545 * "m_end" is never dereferenced, so it need not point to a vm_page
2546 * structure within vm_page_array[].
2548 * "npages" must be greater than zero. "m_start" and "m_end" must not
2549 * span a hole (or discontiguity) in the physical address space. Both
2550 * "alignment" and "boundary" must be a power of two.
2553 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2554 u_long alignment, vm_paddr_t boundary, int options)
2559 #if VM_NRESERVLEVEL > 0
2562 int m_inc, order, run_ext, run_len;
2564 KASSERT(npages > 0, ("npages is 0"));
2565 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2566 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2569 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2570 KASSERT((m->flags & PG_MARKER) == 0,
2571 ("page %p is PG_MARKER", m));
2572 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->ref_count >= 1,
2573 ("fictitious page %p has invalid ref count", m));
2576 * If the current page would be the start of a run, check its
2577 * physical address against the end, alignment, and boundary
2578 * conditions. If it doesn't satisfy these conditions, either
2579 * terminate the scan or advance to the next page that
2580 * satisfies the failed condition.
2583 KASSERT(m_run == NULL, ("m_run != NULL"));
2584 if (m + npages > m_end)
2586 pa = VM_PAGE_TO_PHYS(m);
2587 if ((pa & (alignment - 1)) != 0) {
2588 m_inc = atop(roundup2(pa, alignment) - pa);
2591 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2593 m_inc = atop(roundup2(pa, boundary) - pa);
2597 KASSERT(m_run != NULL, ("m_run == NULL"));
2601 if (vm_page_wired(m))
2603 #if VM_NRESERVLEVEL > 0
2604 else if ((level = vm_reserv_level(m)) >= 0 &&
2605 (options & VPSC_NORESERV) != 0) {
2607 /* Advance to the end of the reservation. */
2608 pa = VM_PAGE_TO_PHYS(m);
2609 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2613 else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2615 * The page is considered eligible for relocation if
2616 * and only if it could be laundered or reclaimed by
2619 VM_OBJECT_RLOCK(object);
2620 if (object != m->object) {
2621 VM_OBJECT_RUNLOCK(object);
2624 /* Don't care: PG_NODUMP, PG_ZERO. */
2625 if (object->type != OBJT_DEFAULT &&
2626 object->type != OBJT_SWAP &&
2627 object->type != OBJT_VNODE) {
2629 #if VM_NRESERVLEVEL > 0
2630 } else if ((options & VPSC_NOSUPER) != 0 &&
2631 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2633 /* Advance to the end of the superpage. */
2634 pa = VM_PAGE_TO_PHYS(m);
2635 m_inc = atop(roundup2(pa + 1,
2636 vm_reserv_size(level)) - pa);
2638 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2639 vm_page_queue(m) != PQ_NONE && !vm_page_busied(m)) {
2641 * The page is allocated but eligible for
2642 * relocation. Extend the current run by one
2645 KASSERT(pmap_page_get_memattr(m) ==
2647 ("page %p has an unexpected memattr", m));
2648 KASSERT((m->oflags & (VPO_SWAPINPROG |
2649 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2650 ("page %p has unexpected oflags", m));
2651 /* Don't care: PGA_NOSYNC. */
2655 VM_OBJECT_RUNLOCK(object);
2656 #if VM_NRESERVLEVEL > 0
2657 } else if (level >= 0) {
2659 * The page is reserved but not yet allocated. In
2660 * other words, it is still free. Extend the current
2665 } else if ((order = m->order) < VM_NFREEORDER) {
2667 * The page is enqueued in the physical memory
2668 * allocator's free page queues. Moreover, it is the
2669 * first page in a power-of-two-sized run of
2670 * contiguous free pages. Add these pages to the end
2671 * of the current run, and jump ahead.
2673 run_ext = 1 << order;
2677 * Skip the page for one of the following reasons: (1)
2678 * It is enqueued in the physical memory allocator's
2679 * free page queues. However, it is not the first
2680 * page in a run of contiguous free pages. (This case
2681 * rarely occurs because the scan is performed in
2682 * ascending order.) (2) It is not reserved, and it is
2683 * transitioning from free to allocated. (Conversely,
2684 * the transition from allocated to free for managed
2685 * pages is blocked by the page busy lock.) (3) It is
2686 * allocated but not contained by an object and not
2687 * wired, e.g., allocated by Xen's balloon driver.
2693 * Extend or reset the current run of pages.
2706 if (run_len >= npages)
2712 * vm_page_reclaim_run:
2714 * Try to relocate each of the allocated virtual pages within the
2715 * specified run of physical pages to a new physical address. Free the
2716 * physical pages underlying the relocated virtual pages. A virtual page
2717 * is relocatable if and only if it could be laundered or reclaimed by
2718 * the page daemon. Whenever possible, a virtual page is relocated to a
2719 * physical address above "high".
2721 * Returns 0 if every physical page within the run was already free or
2722 * just freed by a successful relocation. Otherwise, returns a non-zero
2723 * value indicating why the last attempt to relocate a virtual page was
2726 * "req_class" must be an allocation class.
2729 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2732 struct vm_domain *vmd;
2733 struct spglist free;
2736 vm_page_t m, m_end, m_new;
2737 int error, order, req;
2739 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2740 ("req_class is not an allocation class"));
2744 m_end = m_run + npages;
2745 for (; error == 0 && m < m_end; m++) {
2746 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2747 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2750 * Racily check for wirings. Races are handled once the object
2751 * lock is held and the page is unmapped.
2753 if (vm_page_wired(m))
2755 else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2757 * The page is relocated if and only if it could be
2758 * laundered or reclaimed by the page daemon.
2760 VM_OBJECT_WLOCK(object);
2761 /* Don't care: PG_NODUMP, PG_ZERO. */
2762 if (m->object != object ||
2763 (object->type != OBJT_DEFAULT &&
2764 object->type != OBJT_SWAP &&
2765 object->type != OBJT_VNODE))
2767 else if (object->memattr != VM_MEMATTR_DEFAULT)
2769 else if (vm_page_queue(m) != PQ_NONE &&
2770 vm_page_tryxbusy(m) != 0) {
2771 if (vm_page_wired(m)) {
2776 KASSERT(pmap_page_get_memattr(m) ==
2778 ("page %p has an unexpected memattr", m));
2779 KASSERT(m->oflags == 0,
2780 ("page %p has unexpected oflags", m));
2781 /* Don't care: PGA_NOSYNC. */
2782 if (!vm_page_none_valid(m)) {
2784 * First, try to allocate a new page
2785 * that is above "high". Failing
2786 * that, try to allocate a new page
2787 * that is below "m_run". Allocate
2788 * the new page between the end of
2789 * "m_run" and "high" only as a last
2792 req = req_class | VM_ALLOC_NOOBJ;
2793 if ((m->flags & PG_NODUMP) != 0)
2794 req |= VM_ALLOC_NODUMP;
2795 if (trunc_page(high) !=
2796 ~(vm_paddr_t)PAGE_MASK) {
2797 m_new = vm_page_alloc_contig(
2802 VM_MEMATTR_DEFAULT);
2805 if (m_new == NULL) {
2806 pa = VM_PAGE_TO_PHYS(m_run);
2807 m_new = vm_page_alloc_contig(
2809 0, pa - 1, PAGE_SIZE, 0,
2810 VM_MEMATTR_DEFAULT);
2812 if (m_new == NULL) {
2814 m_new = vm_page_alloc_contig(
2816 pa, high, PAGE_SIZE, 0,
2817 VM_MEMATTR_DEFAULT);
2819 if (m_new == NULL) {
2826 * Unmap the page and check for new
2827 * wirings that may have been acquired
2828 * through a pmap lookup.
2830 if (object->ref_count != 0 &&
2831 !vm_page_try_remove_all(m)) {
2833 vm_page_free(m_new);
2839 * Replace "m" with the new page. For
2840 * vm_page_replace(), "m" must be busy
2841 * and dequeued. Finally, change "m"
2842 * as if vm_page_free() was called.
2844 m_new->a.flags = m->a.flags &
2845 ~PGA_QUEUE_STATE_MASK;
2846 KASSERT(m_new->oflags == VPO_UNMANAGED,
2847 ("page %p is managed", m_new));
2849 pmap_copy_page(m, m_new);
2850 m_new->valid = m->valid;
2851 m_new->dirty = m->dirty;
2852 m->flags &= ~PG_ZERO;
2854 if (vm_page_replace_hold(m_new, object,
2856 vm_page_free_prep(m))
2857 SLIST_INSERT_HEAD(&free, m,
2861 * The new page must be deactivated
2862 * before the object is unlocked.
2864 vm_page_deactivate(m_new);
2866 m->flags &= ~PG_ZERO;
2868 if (vm_page_free_prep(m))
2869 SLIST_INSERT_HEAD(&free, m,
2871 KASSERT(m->dirty == 0,
2872 ("page %p is dirty", m));
2877 VM_OBJECT_WUNLOCK(object);
2879 MPASS(vm_phys_domain(m) == domain);
2880 vmd = VM_DOMAIN(domain);
2881 vm_domain_free_lock(vmd);
2883 if (order < VM_NFREEORDER) {
2885 * The page is enqueued in the physical memory
2886 * allocator's free page queues. Moreover, it
2887 * is the first page in a power-of-two-sized
2888 * run of contiguous free pages. Jump ahead
2889 * to the last page within that run, and
2890 * continue from there.
2892 m += (1 << order) - 1;
2894 #if VM_NRESERVLEVEL > 0
2895 else if (vm_reserv_is_page_free(m))
2898 vm_domain_free_unlock(vmd);
2899 if (order == VM_NFREEORDER)
2903 if ((m = SLIST_FIRST(&free)) != NULL) {
2906 vmd = VM_DOMAIN(domain);
2908 vm_domain_free_lock(vmd);
2910 MPASS(vm_phys_domain(m) == domain);
2911 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2912 vm_phys_free_pages(m, 0);
2914 } while ((m = SLIST_FIRST(&free)) != NULL);
2915 vm_domain_free_unlock(vmd);
2916 vm_domain_freecnt_inc(vmd, cnt);
2923 CTASSERT(powerof2(NRUNS));
2925 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2927 #define MIN_RECLAIM 8
2930 * vm_page_reclaim_contig:
2932 * Reclaim allocated, contiguous physical memory satisfying the specified
2933 * conditions by relocating the virtual pages using that physical memory.
2934 * Returns true if reclamation is successful and false otherwise. Since
2935 * relocation requires the allocation of physical pages, reclamation may
2936 * fail due to a shortage of free pages. When reclamation fails, callers
2937 * are expected to perform vm_wait() before retrying a failed allocation
2938 * operation, e.g., vm_page_alloc_contig().
2940 * The caller must always specify an allocation class through "req".
2942 * allocation classes:
2943 * VM_ALLOC_NORMAL normal process request
2944 * VM_ALLOC_SYSTEM system *really* needs a page
2945 * VM_ALLOC_INTERRUPT interrupt time request
2947 * The optional allocation flags are ignored.
2949 * "npages" must be greater than zero. Both "alignment" and "boundary"
2950 * must be a power of two.
2953 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
2954 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2956 struct vm_domain *vmd;
2957 vm_paddr_t curr_low;
2958 vm_page_t m_run, m_runs[NRUNS];
2959 u_long count, reclaimed;
2960 int error, i, options, req_class;
2962 KASSERT(npages > 0, ("npages is 0"));
2963 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2964 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2965 req_class = req & VM_ALLOC_CLASS_MASK;
2968 * The page daemon is allowed to dig deeper into the free page list.
2970 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2971 req_class = VM_ALLOC_SYSTEM;
2974 * Return if the number of free pages cannot satisfy the requested
2977 vmd = VM_DOMAIN(domain);
2978 count = vmd->vmd_free_count;
2979 if (count < npages + vmd->vmd_free_reserved || (count < npages +
2980 vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2981 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2985 * Scan up to three times, relaxing the restrictions ("options") on
2986 * the reclamation of reservations and superpages each time.
2988 for (options = VPSC_NORESERV;;) {
2990 * Find the highest runs that satisfy the given constraints
2991 * and restrictions, and record them in "m_runs".
2996 m_run = vm_phys_scan_contig(domain, npages, curr_low,
2997 high, alignment, boundary, options);
3000 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
3001 m_runs[RUN_INDEX(count)] = m_run;
3006 * Reclaim the highest runs in LIFO (descending) order until
3007 * the number of reclaimed pages, "reclaimed", is at least
3008 * MIN_RECLAIM. Reset "reclaimed" each time because each
3009 * reclamation is idempotent, and runs will (likely) recur
3010 * from one scan to the next as restrictions are relaxed.
3013 for (i = 0; count > 0 && i < NRUNS; i++) {
3015 m_run = m_runs[RUN_INDEX(count)];
3016 error = vm_page_reclaim_run(req_class, domain, npages,
3019 reclaimed += npages;
3020 if (reclaimed >= MIN_RECLAIM)
3026 * Either relax the restrictions on the next scan or return if
3027 * the last scan had no restrictions.
3029 if (options == VPSC_NORESERV)
3030 options = VPSC_NOSUPER;
3031 else if (options == VPSC_NOSUPER)
3033 else if (options == VPSC_ANY)
3034 return (reclaimed != 0);
3039 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
3040 u_long alignment, vm_paddr_t boundary)
3042 struct vm_domainset_iter di;
3046 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
3048 ret = vm_page_reclaim_contig_domain(domain, req, npages, low,
3049 high, alignment, boundary);
3052 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
3058 * Set the domain in the appropriate page level domainset.
3061 vm_domain_set(struct vm_domain *vmd)
3064 mtx_lock(&vm_domainset_lock);
3065 if (!vmd->vmd_minset && vm_paging_min(vmd)) {
3066 vmd->vmd_minset = 1;
3067 DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
3069 if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
3070 vmd->vmd_severeset = 1;
3071 DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
3073 mtx_unlock(&vm_domainset_lock);
3077 * Clear the domain from the appropriate page level domainset.
3080 vm_domain_clear(struct vm_domain *vmd)
3083 mtx_lock(&vm_domainset_lock);
3084 if (vmd->vmd_minset && !vm_paging_min(vmd)) {
3085 vmd->vmd_minset = 0;
3086 DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
3087 if (vm_min_waiters != 0) {
3089 wakeup(&vm_min_domains);
3092 if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
3093 vmd->vmd_severeset = 0;
3094 DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
3095 if (vm_severe_waiters != 0) {
3096 vm_severe_waiters = 0;
3097 wakeup(&vm_severe_domains);
3102 * If pageout daemon needs pages, then tell it that there are
3105 if (vmd->vmd_pageout_pages_needed &&
3106 vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
3107 wakeup(&vmd->vmd_pageout_pages_needed);
3108 vmd->vmd_pageout_pages_needed = 0;
3111 /* See comments in vm_wait_doms(). */
3112 if (vm_pageproc_waiters) {
3113 vm_pageproc_waiters = 0;
3114 wakeup(&vm_pageproc_waiters);
3116 mtx_unlock(&vm_domainset_lock);
3120 * Wait for free pages to exceed the min threshold globally.
3126 mtx_lock(&vm_domainset_lock);
3127 while (vm_page_count_min()) {
3129 msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
3131 mtx_unlock(&vm_domainset_lock);
3135 * Wait for free pages to exceed the severe threshold globally.
3138 vm_wait_severe(void)
3141 mtx_lock(&vm_domainset_lock);
3142 while (vm_page_count_severe()) {
3143 vm_severe_waiters++;
3144 msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
3147 mtx_unlock(&vm_domainset_lock);
3154 return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
3158 vm_wait_doms(const domainset_t *wdoms, int mflags)
3165 * We use racey wakeup synchronization to avoid expensive global
3166 * locking for the pageproc when sleeping with a non-specific vm_wait.
3167 * To handle this, we only sleep for one tick in this instance. It
3168 * is expected that most allocations for the pageproc will come from
3169 * kmem or vm_page_grab* which will use the more specific and
3170 * race-free vm_wait_domain().
3172 if (curproc == pageproc) {
3173 mtx_lock(&vm_domainset_lock);
3174 vm_pageproc_waiters++;
3175 error = msleep(&vm_pageproc_waiters, &vm_domainset_lock,
3176 PVM | PDROP | mflags, "pageprocwait", 1);
3179 * XXX Ideally we would wait only until the allocation could
3180 * be satisfied. This condition can cause new allocators to
3181 * consume all freed pages while old allocators wait.
3183 mtx_lock(&vm_domainset_lock);
3184 if (vm_page_count_min_set(wdoms)) {
3186 error = msleep(&vm_min_domains, &vm_domainset_lock,
3187 PVM | PDROP | mflags, "vmwait", 0);
3189 mtx_unlock(&vm_domainset_lock);
3197 * Sleep until free pages are available for allocation.
3198 * - Called in various places after failed memory allocations.
3201 vm_wait_domain(int domain)
3203 struct vm_domain *vmd;
3206 vmd = VM_DOMAIN(domain);
3207 vm_domain_free_assert_unlocked(vmd);
3209 if (curproc == pageproc) {
3210 mtx_lock(&vm_domainset_lock);
3211 if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
3212 vmd->vmd_pageout_pages_needed = 1;
3213 msleep(&vmd->vmd_pageout_pages_needed,
3214 &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
3216 mtx_unlock(&vm_domainset_lock);
3218 if (pageproc == NULL)
3219 panic("vm_wait in early boot");
3220 DOMAINSET_ZERO(&wdom);
3221 DOMAINSET_SET(vmd->vmd_domain, &wdom);
3222 vm_wait_doms(&wdom, 0);
3227 vm_wait_flags(vm_object_t obj, int mflags)
3229 struct domainset *d;
3234 * Carefully fetch pointers only once: the struct domainset
3235 * itself is ummutable but the pointer might change.
3238 d = obj->domain.dr_policy;
3240 d = curthread->td_domain.dr_policy;
3242 return (vm_wait_doms(&d->ds_mask, mflags));
3248 * Sleep until free pages are available for allocation in the
3249 * affinity domains of the obj. If obj is NULL, the domain set
3250 * for the calling thread is used.
3251 * Called in various places after failed memory allocations.
3254 vm_wait(vm_object_t obj)
3256 (void)vm_wait_flags(obj, 0);
3260 vm_wait_intr(vm_object_t obj)
3262 return (vm_wait_flags(obj, PCATCH));
3266 * vm_domain_alloc_fail:
3268 * Called when a page allocation function fails. Informs the
3269 * pagedaemon and performs the requested wait. Requires the
3270 * domain_free and object lock on entry. Returns with the
3271 * object lock held and free lock released. Returns an error when
3272 * retry is necessary.
3276 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3279 vm_domain_free_assert_unlocked(vmd);
3281 atomic_add_int(&vmd->vmd_pageout_deficit,
3282 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3283 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3285 VM_OBJECT_WUNLOCK(object);
3286 vm_wait_domain(vmd->vmd_domain);
3288 VM_OBJECT_WLOCK(object);
3289 if (req & VM_ALLOC_WAITOK)
3299 * Sleep until free pages are available for allocation.
3300 * - Called only in vm_fault so that processes page faulting
3301 * can be easily tracked.
3302 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3303 * processes will be able to grab memory first. Do not change
3304 * this balance without careful testing first.
3307 vm_waitpfault(struct domainset *dset, int timo)
3311 * XXX Ideally we would wait only until the allocation could
3312 * be satisfied. This condition can cause new allocators to
3313 * consume all freed pages while old allocators wait.
3315 mtx_lock(&vm_domainset_lock);
3316 if (vm_page_count_min_set(&dset->ds_mask)) {
3318 msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3321 mtx_unlock(&vm_domainset_lock);
3324 static struct vm_pagequeue *
3325 _vm_page_pagequeue(vm_page_t m, uint8_t queue)
3328 return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue]);
3332 static struct vm_pagequeue *
3333 vm_page_pagequeue(vm_page_t m)
3336 return (_vm_page_pagequeue(m, vm_page_astate_load(m).queue));
3340 static __always_inline bool
3341 vm_page_pqstate_fcmpset(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3343 vm_page_astate_t tmp;
3347 if (__predict_true(vm_page_astate_fcmpset(m, old, new)))
3349 counter_u64_add(pqstate_commit_retries, 1);
3350 } while (old->_bits == tmp._bits);
3356 * Do the work of committing a queue state update that moves the page out of
3357 * its current queue.
3360 _vm_page_pqstate_commit_dequeue(struct vm_pagequeue *pq, vm_page_t m,
3361 vm_page_astate_t *old, vm_page_astate_t new)
3365 vm_pagequeue_assert_locked(pq);
3366 KASSERT(vm_page_pagequeue(m) == pq,
3367 ("%s: queue %p does not match page %p", __func__, pq, m));
3368 KASSERT(old->queue != PQ_NONE && new.queue != old->queue,
3369 ("%s: invalid queue indices %d %d",
3370 __func__, old->queue, new.queue));
3373 * Once the queue index of the page changes there is nothing
3374 * synchronizing with further updates to the page's physical
3375 * queue state. Therefore we must speculatively remove the page
3376 * from the queue now and be prepared to roll back if the queue
3377 * state update fails. If the page is not physically enqueued then
3378 * we just update its queue index.
3380 if ((old->flags & PGA_ENQUEUED) != 0) {
3381 new.flags &= ~PGA_ENQUEUED;
3382 next = TAILQ_NEXT(m, plinks.q);
3383 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3384 vm_pagequeue_cnt_dec(pq);
3385 if (!vm_page_pqstate_fcmpset(m, old, new)) {
3387 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3389 TAILQ_INSERT_BEFORE(next, m, plinks.q);
3390 vm_pagequeue_cnt_inc(pq);
3396 return (vm_page_pqstate_fcmpset(m, old, new));
3401 vm_page_pqstate_commit_dequeue(vm_page_t m, vm_page_astate_t *old,
3402 vm_page_astate_t new)
3404 struct vm_pagequeue *pq;
3405 vm_page_astate_t as;
3408 pq = _vm_page_pagequeue(m, old->queue);
3411 * The queue field and PGA_ENQUEUED flag are stable only so long as the
3412 * corresponding page queue lock is held.
3414 vm_pagequeue_lock(pq);
3415 as = vm_page_astate_load(m);
3416 if (__predict_false(as._bits != old->_bits)) {
3420 ret = _vm_page_pqstate_commit_dequeue(pq, m, old, new);
3422 vm_pagequeue_unlock(pq);
3427 * Commit a queue state update that enqueues or requeues a page.
3430 _vm_page_pqstate_commit_requeue(struct vm_pagequeue *pq, vm_page_t m,
3431 vm_page_astate_t *old, vm_page_astate_t new)
3433 struct vm_domain *vmd;
3435 vm_pagequeue_assert_locked(pq);
3436 KASSERT(old->queue != PQ_NONE && new.queue == old->queue,
3437 ("%s: invalid queue indices %d %d",
3438 __func__, old->queue, new.queue));
3440 new.flags |= PGA_ENQUEUED;
3441 if (!vm_page_pqstate_fcmpset(m, old, new))
3444 if ((old->flags & PGA_ENQUEUED) != 0)
3445 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3447 vm_pagequeue_cnt_inc(pq);
3450 * Give PGA_REQUEUE_HEAD precedence over PGA_REQUEUE. In particular, if
3451 * both flags are set in close succession, only PGA_REQUEUE_HEAD will be
3452 * applied, even if it was set first.
3454 if ((old->flags & PGA_REQUEUE_HEAD) != 0) {
3455 vmd = vm_pagequeue_domain(m);
3456 KASSERT(pq == &vmd->vmd_pagequeues[PQ_INACTIVE],
3457 ("%s: invalid page queue for page %p", __func__, m));
3458 TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3460 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3466 * Commit a queue state update that encodes a request for a deferred queue
3470 vm_page_pqstate_commit_request(vm_page_t m, vm_page_astate_t *old,
3471 vm_page_astate_t new)
3474 KASSERT(old->queue == new.queue || new.queue != PQ_NONE,
3475 ("%s: invalid state, queue %d flags %x",
3476 __func__, new.queue, new.flags));
3478 if (old->_bits != new._bits &&
3479 !vm_page_pqstate_fcmpset(m, old, new))
3481 vm_page_pqbatch_submit(m, new.queue);
3486 * A generic queue state update function. This handles more cases than the
3487 * specialized functions above.
3490 vm_page_pqstate_commit(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3493 if (old->_bits == new._bits)
3496 if (old->queue != PQ_NONE && new.queue != old->queue) {
3497 if (!vm_page_pqstate_commit_dequeue(m, old, new))
3499 if (new.queue != PQ_NONE)
3500 vm_page_pqbatch_submit(m, new.queue);
3502 if (!vm_page_pqstate_fcmpset(m, old, new))
3504 if (new.queue != PQ_NONE &&
3505 ((new.flags & ~old->flags) & PGA_QUEUE_OP_MASK) != 0)
3506 vm_page_pqbatch_submit(m, new.queue);
3512 * Apply deferred queue state updates to a page.
3515 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m, uint8_t queue)
3517 vm_page_astate_t new, old;
3519 CRITICAL_ASSERT(curthread);
3520 vm_pagequeue_assert_locked(pq);
3521 KASSERT(queue < PQ_COUNT,
3522 ("%s: invalid queue index %d", __func__, queue));
3523 KASSERT(pq == _vm_page_pagequeue(m, queue),
3524 ("%s: page %p does not belong to queue %p", __func__, m, pq));
3526 for (old = vm_page_astate_load(m);;) {
3527 if (__predict_false(old.queue != queue ||
3528 (old.flags & PGA_QUEUE_OP_MASK) == 0)) {
3529 counter_u64_add(queue_nops, 1);
3532 KASSERT(old.queue != PQ_NONE || (old.flags & PGA_QUEUE_STATE_MASK) == 0,
3533 ("%s: page %p has unexpected queue state", __func__, m));
3536 if ((old.flags & PGA_DEQUEUE) != 0) {
3537 new.flags &= ~PGA_QUEUE_OP_MASK;
3538 new.queue = PQ_NONE;
3539 if (__predict_true(_vm_page_pqstate_commit_dequeue(pq,
3541 counter_u64_add(queue_ops, 1);
3545 new.flags &= ~(PGA_REQUEUE | PGA_REQUEUE_HEAD);
3546 if (__predict_true(_vm_page_pqstate_commit_requeue(pq,
3548 counter_u64_add(queue_ops, 1);
3556 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3561 for (i = 0; i < bq->bq_cnt; i++)
3562 vm_pqbatch_process_page(pq, bq->bq_pa[i], queue);
3563 vm_batchqueue_init(bq);
3567 * vm_page_pqbatch_submit: [ internal use only ]
3569 * Enqueue a page in the specified page queue's batched work queue.
3570 * The caller must have encoded the requested operation in the page
3571 * structure's a.flags field.
3574 vm_page_pqbatch_submit(vm_page_t m, uint8_t queue)
3576 struct vm_batchqueue *bq;
3577 struct vm_pagequeue *pq;
3580 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3581 ("page %p is unmanaged", m));
3582 KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3584 domain = vm_phys_domain(m);
3585 pq = &vm_pagequeue_domain(m)->vmd_pagequeues[queue];
3588 bq = DPCPU_PTR(pqbatch[domain][queue]);
3589 if (vm_batchqueue_insert(bq, m)) {
3594 vm_pagequeue_lock(pq);
3596 bq = DPCPU_PTR(pqbatch[domain][queue]);
3597 vm_pqbatch_process(pq, bq, queue);
3598 vm_pqbatch_process_page(pq, m, queue);
3599 vm_pagequeue_unlock(pq);
3604 * vm_page_pqbatch_drain: [ internal use only ]
3606 * Force all per-CPU page queue batch queues to be drained. This is
3607 * intended for use in severe memory shortages, to ensure that pages
3608 * do not remain stuck in the batch queues.
3611 vm_page_pqbatch_drain(void)
3614 struct vm_domain *vmd;
3615 struct vm_pagequeue *pq;
3616 int cpu, domain, queue;
3621 sched_bind(td, cpu);
3624 for (domain = 0; domain < vm_ndomains; domain++) {
3625 vmd = VM_DOMAIN(domain);
3626 for (queue = 0; queue < PQ_COUNT; queue++) {
3627 pq = &vmd->vmd_pagequeues[queue];
3628 vm_pagequeue_lock(pq);
3630 vm_pqbatch_process(pq,
3631 DPCPU_PTR(pqbatch[domain][queue]), queue);
3633 vm_pagequeue_unlock(pq);
3643 * vm_page_dequeue_deferred: [ internal use only ]
3645 * Request removal of the given page from its current page
3646 * queue. Physical removal from the queue may be deferred
3650 vm_page_dequeue_deferred(vm_page_t m)
3652 vm_page_astate_t new, old;
3654 old = vm_page_astate_load(m);
3656 if (old.queue == PQ_NONE) {
3657 KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3658 ("%s: page %p has unexpected queue state",
3663 new.flags |= PGA_DEQUEUE;
3664 } while (!vm_page_pqstate_commit_request(m, &old, new));
3670 * Remove the page from whichever page queue it's in, if any, before
3674 vm_page_dequeue(vm_page_t m)
3676 vm_page_astate_t new, old;
3678 old = vm_page_astate_load(m);
3680 if (old.queue == PQ_NONE) {
3681 KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3682 ("%s: page %p has unexpected queue state",
3687 new.flags &= ~PGA_QUEUE_OP_MASK;
3688 new.queue = PQ_NONE;
3689 } while (!vm_page_pqstate_commit_dequeue(m, &old, new));
3694 * Schedule the given page for insertion into the specified page queue.
3695 * Physical insertion of the page may be deferred indefinitely.
3698 vm_page_enqueue(vm_page_t m, uint8_t queue)
3701 KASSERT(m->a.queue == PQ_NONE &&
3702 (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
3703 ("%s: page %p is already enqueued", __func__, m));
3704 KASSERT(m->ref_count > 0,
3705 ("%s: page %p does not carry any references", __func__, m));
3708 if ((m->a.flags & PGA_REQUEUE) == 0)
3709 vm_page_aflag_set(m, PGA_REQUEUE);
3710 vm_page_pqbatch_submit(m, queue);
3714 * vm_page_free_prep:
3716 * Prepares the given page to be put on the free list,
3717 * disassociating it from any VM object. The caller may return
3718 * the page to the free list only if this function returns true.
3720 * The object, if it exists, must be locked, and then the page must
3721 * be xbusy. Otherwise the page must be not busied. A managed
3722 * page must be unmapped.
3725 vm_page_free_prep(vm_page_t m)
3729 * Synchronize with threads that have dropped a reference to this
3732 atomic_thread_fence_acq();
3734 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
3735 if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
3738 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3739 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
3740 KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
3741 m, i, (uintmax_t)*p));
3744 if ((m->oflags & VPO_UNMANAGED) == 0) {
3745 KASSERT(!pmap_page_is_mapped(m),
3746 ("vm_page_free_prep: freeing mapped page %p", m));
3747 KASSERT((m->a.flags & (PGA_EXECUTABLE | PGA_WRITEABLE)) == 0,
3748 ("vm_page_free_prep: mapping flags set in page %p", m));
3750 KASSERT(m->a.queue == PQ_NONE,
3751 ("vm_page_free_prep: unmanaged page %p is queued", m));
3753 VM_CNT_INC(v_tfree);
3755 if (m->object != NULL) {
3756 KASSERT(((m->oflags & VPO_UNMANAGED) != 0) ==
3757 ((m->object->flags & OBJ_UNMANAGED) != 0),
3758 ("vm_page_free_prep: managed flag mismatch for page %p",
3760 vm_page_assert_xbusied(m);
3763 * The object reference can be released without an atomic
3766 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
3767 m->ref_count == VPRC_OBJREF,
3768 ("vm_page_free_prep: page %p has unexpected ref_count %u",
3770 vm_page_object_remove(m);
3771 m->ref_count -= VPRC_OBJREF;
3773 vm_page_assert_unbusied(m);
3775 vm_page_busy_free(m);
3778 * If fictitious remove object association and
3781 if ((m->flags & PG_FICTITIOUS) != 0) {
3782 KASSERT(m->ref_count == 1,
3783 ("fictitious page %p is referenced", m));
3784 KASSERT(m->a.queue == PQ_NONE,
3785 ("fictitious page %p is queued", m));
3790 * Pages need not be dequeued before they are returned to the physical
3791 * memory allocator, but they must at least be marked for a deferred
3794 if ((m->oflags & VPO_UNMANAGED) == 0)
3795 vm_page_dequeue_deferred(m);
3800 if (m->ref_count != 0)
3801 panic("vm_page_free_prep: page %p has references", m);
3804 * Restore the default memory attribute to the page.
3806 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3807 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3809 #if VM_NRESERVLEVEL > 0
3811 * Determine whether the page belongs to a reservation. If the page was
3812 * allocated from a per-CPU cache, it cannot belong to a reservation, so
3813 * as an optimization, we avoid the check in that case.
3815 if ((m->flags & PG_PCPU_CACHE) == 0 && vm_reserv_free_page(m))
3825 * Returns the given page to the free list, disassociating it
3826 * from any VM object.
3828 * The object must be locked. The page must be exclusively busied if it
3829 * belongs to an object.
3832 vm_page_free_toq(vm_page_t m)
3834 struct vm_domain *vmd;
3837 if (!vm_page_free_prep(m))
3840 vmd = vm_pagequeue_domain(m);
3841 zone = vmd->vmd_pgcache[m->pool].zone;
3842 if ((m->flags & PG_PCPU_CACHE) != 0 && zone != NULL) {
3846 vm_domain_free_lock(vmd);
3847 vm_phys_free_pages(m, 0);
3848 vm_domain_free_unlock(vmd);
3849 vm_domain_freecnt_inc(vmd, 1);
3853 * vm_page_free_pages_toq:
3855 * Returns a list of pages to the free list, disassociating it
3856 * from any VM object. In other words, this is equivalent to
3857 * calling vm_page_free_toq() for each page of a list of VM objects.
3860 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
3865 if (SLIST_EMPTY(free))
3869 while ((m = SLIST_FIRST(free)) != NULL) {
3871 SLIST_REMOVE_HEAD(free, plinks.s.ss);
3872 vm_page_free_toq(m);
3875 if (update_wire_count)
3880 * Mark this page as wired down. For managed pages, this prevents reclamation
3881 * by the page daemon, or when the containing object, if any, is destroyed.
3884 vm_page_wire(vm_page_t m)
3889 if (m->object != NULL && !vm_page_busied(m) &&
3890 !vm_object_busied(m->object))
3891 VM_OBJECT_ASSERT_LOCKED(m->object);
3893 KASSERT((m->flags & PG_FICTITIOUS) == 0 ||
3894 VPRC_WIRE_COUNT(m->ref_count) >= 1,
3895 ("vm_page_wire: fictitious page %p has zero wirings", m));
3897 old = atomic_fetchadd_int(&m->ref_count, 1);
3898 KASSERT(VPRC_WIRE_COUNT(old) != VPRC_WIRE_COUNT_MAX,
3899 ("vm_page_wire: counter overflow for page %p", m));
3900 if (VPRC_WIRE_COUNT(old) == 0) {
3901 if ((m->oflags & VPO_UNMANAGED) == 0)
3902 vm_page_aflag_set(m, PGA_DEQUEUE);
3908 * Attempt to wire a mapped page following a pmap lookup of that page.
3909 * This may fail if a thread is concurrently tearing down mappings of the page.
3910 * The transient failure is acceptable because it translates to the
3911 * failure of the caller pmap_extract_and_hold(), which should be then
3912 * followed by the vm_fault() fallback, see e.g. vm_fault_quick_hold_pages().
3915 vm_page_wire_mapped(vm_page_t m)
3922 ("vm_page_wire_mapped: wiring unreferenced page %p", m));
3923 if ((old & VPRC_BLOCKED) != 0)
3925 } while (!atomic_fcmpset_int(&m->ref_count, &old, old + 1));
3927 if (VPRC_WIRE_COUNT(old) == 0) {
3928 if ((m->oflags & VPO_UNMANAGED) == 0)
3929 vm_page_aflag_set(m, PGA_DEQUEUE);
3936 * Release a wiring reference to a managed page. If the page still belongs to
3937 * an object, update its position in the page queues to reflect the reference.
3938 * If the wiring was the last reference to the page, free the page.
3941 vm_page_unwire_managed(vm_page_t m, uint8_t nqueue, bool noreuse)
3945 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3946 ("%s: page %p is unmanaged", __func__, m));
3949 * Update LRU state before releasing the wiring reference.
3950 * Use a release store when updating the reference count to
3951 * synchronize with vm_page_free_prep().
3955 KASSERT(VPRC_WIRE_COUNT(old) > 0,
3956 ("vm_page_unwire: wire count underflow for page %p", m));
3958 if (old > VPRC_OBJREF + 1) {
3960 * The page has at least one other wiring reference. An
3961 * earlier iteration of this loop may have called
3962 * vm_page_release_toq() and cleared PGA_DEQUEUE, so
3963 * re-set it if necessary.
3965 if ((vm_page_astate_load(m).flags & PGA_DEQUEUE) == 0)
3966 vm_page_aflag_set(m, PGA_DEQUEUE);
3967 } else if (old == VPRC_OBJREF + 1) {
3969 * This is the last wiring. Clear PGA_DEQUEUE and
3970 * update the page's queue state to reflect the
3971 * reference. If the page does not belong to an object
3972 * (i.e., the VPRC_OBJREF bit is clear), we only need to
3973 * clear leftover queue state.
3975 vm_page_release_toq(m, nqueue, false);
3976 } else if (old == 1) {
3977 vm_page_aflag_clear(m, PGA_DEQUEUE);
3979 } while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
3981 if (VPRC_WIRE_COUNT(old) == 1) {
3989 * Release one wiring of the specified page, potentially allowing it to be
3992 * Only managed pages belonging to an object can be paged out. If the number
3993 * of wirings transitions to zero and the page is eligible for page out, then
3994 * the page is added to the specified paging queue. If the released wiring
3995 * represented the last reference to the page, the page is freed.
3998 vm_page_unwire(vm_page_t m, uint8_t nqueue)
4001 KASSERT(nqueue < PQ_COUNT,
4002 ("vm_page_unwire: invalid queue %u request for page %p",
4005 if ((m->oflags & VPO_UNMANAGED) != 0) {
4006 if (vm_page_unwire_noq(m) && m->ref_count == 0)
4010 vm_page_unwire_managed(m, nqueue, false);
4014 * Unwire a page without (re-)inserting it into a page queue. It is up
4015 * to the caller to enqueue, requeue, or free the page as appropriate.
4016 * In most cases involving managed pages, vm_page_unwire() should be used
4020 vm_page_unwire_noq(vm_page_t m)
4024 old = vm_page_drop(m, 1);
4025 KASSERT(VPRC_WIRE_COUNT(old) != 0,
4026 ("vm_page_unref: counter underflow for page %p", m));
4027 KASSERT((m->flags & PG_FICTITIOUS) == 0 || VPRC_WIRE_COUNT(old) > 1,
4028 ("vm_page_unref: missing ref on fictitious page %p", m));
4030 if (VPRC_WIRE_COUNT(old) > 1)
4032 if ((m->oflags & VPO_UNMANAGED) == 0)
4033 vm_page_aflag_clear(m, PGA_DEQUEUE);
4039 * Ensure that the page ends up in the specified page queue. If the page is
4040 * active or being moved to the active queue, ensure that its act_count is
4041 * at least ACT_INIT but do not otherwise mess with it.
4043 static __always_inline void
4044 vm_page_mvqueue(vm_page_t m, const uint8_t nqueue, const uint16_t nflag)
4046 vm_page_astate_t old, new;
4048 KASSERT(m->ref_count > 0,
4049 ("%s: page %p does not carry any references", __func__, m));
4050 KASSERT(nflag == PGA_REQUEUE || nflag == PGA_REQUEUE_HEAD,
4051 ("%s: invalid flags %x", __func__, nflag));
4053 if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
4056 old = vm_page_astate_load(m);
4058 if ((old.flags & PGA_DEQUEUE) != 0)
4061 new.flags &= ~PGA_QUEUE_OP_MASK;
4062 if (nqueue == PQ_ACTIVE)
4063 new.act_count = max(old.act_count, ACT_INIT);
4064 if (old.queue == nqueue) {
4065 if (nqueue != PQ_ACTIVE)
4071 } while (!vm_page_pqstate_commit(m, &old, new));
4075 * Put the specified page on the active list (if appropriate).
4078 vm_page_activate(vm_page_t m)
4081 vm_page_mvqueue(m, PQ_ACTIVE, PGA_REQUEUE);
4085 * Move the specified page to the tail of the inactive queue, or requeue
4086 * the page if it is already in the inactive queue.
4089 vm_page_deactivate(vm_page_t m)
4092 vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE);
4096 vm_page_deactivate_noreuse(vm_page_t m)
4099 vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE_HEAD);
4103 * Put a page in the laundry, or requeue it if it is already there.
4106 vm_page_launder(vm_page_t m)
4109 vm_page_mvqueue(m, PQ_LAUNDRY, PGA_REQUEUE);
4113 * Put a page in the PQ_UNSWAPPABLE holding queue.
4116 vm_page_unswappable(vm_page_t m)
4119 KASSERT(!vm_page_wired(m) && (m->oflags & VPO_UNMANAGED) == 0,
4120 ("page %p already unswappable", m));
4123 vm_page_enqueue(m, PQ_UNSWAPPABLE);
4127 * Release a page back to the page queues in preparation for unwiring.
4130 vm_page_release_toq(vm_page_t m, uint8_t nqueue, const bool noreuse)
4132 vm_page_astate_t old, new;
4136 * Use a check of the valid bits to determine whether we should
4137 * accelerate reclamation of the page. The object lock might not be
4138 * held here, in which case the check is racy. At worst we will either
4139 * accelerate reclamation of a valid page and violate LRU, or
4140 * unnecessarily defer reclamation of an invalid page.
4142 * If we were asked to not cache the page, place it near the head of the
4143 * inactive queue so that is reclaimed sooner.
4145 if (noreuse || m->valid == 0) {
4146 nqueue = PQ_INACTIVE;
4147 nflag = PGA_REQUEUE_HEAD;
4149 nflag = PGA_REQUEUE;
4152 old = vm_page_astate_load(m);
4157 * If the page is already in the active queue and we are not
4158 * trying to accelerate reclamation, simply mark it as
4159 * referenced and avoid any queue operations.
4161 new.flags &= ~PGA_QUEUE_OP_MASK;
4162 if (nflag != PGA_REQUEUE_HEAD && old.queue == PQ_ACTIVE)
4163 new.flags |= PGA_REFERENCED;
4168 } while (!vm_page_pqstate_commit(m, &old, new));
4172 * Unwire a page and either attempt to free it or re-add it to the page queues.
4175 vm_page_release(vm_page_t m, int flags)
4179 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4180 ("vm_page_release: page %p is unmanaged", m));
4182 if ((flags & VPR_TRYFREE) != 0) {
4184 object = atomic_load_ptr(&m->object);
4187 /* Depends on type-stability. */
4188 if (vm_page_busied(m) || !VM_OBJECT_TRYWLOCK(object))
4190 if (object == m->object) {
4191 vm_page_release_locked(m, flags);
4192 VM_OBJECT_WUNLOCK(object);
4195 VM_OBJECT_WUNLOCK(object);
4198 vm_page_unwire_managed(m, PQ_INACTIVE, flags != 0);
4201 /* See vm_page_release(). */
4203 vm_page_release_locked(vm_page_t m, int flags)
4206 VM_OBJECT_ASSERT_WLOCKED(m->object);
4207 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4208 ("vm_page_release_locked: page %p is unmanaged", m));
4210 if (vm_page_unwire_noq(m)) {
4211 if ((flags & VPR_TRYFREE) != 0 &&
4212 (m->object->ref_count == 0 || !pmap_page_is_mapped(m)) &&
4213 m->dirty == 0 && vm_page_tryxbusy(m)) {
4215 * An unlocked lookup may have wired the page before the
4216 * busy lock was acquired, in which case the page must
4219 if (__predict_true(!vm_page_wired(m))) {
4225 vm_page_release_toq(m, PQ_INACTIVE, flags != 0);
4231 vm_page_try_blocked_op(vm_page_t m, void (*op)(vm_page_t))
4235 KASSERT(m->object != NULL && (m->oflags & VPO_UNMANAGED) == 0,
4236 ("vm_page_try_blocked_op: page %p has no object", m));
4237 KASSERT(vm_page_busied(m),
4238 ("vm_page_try_blocked_op: page %p is not busy", m));
4239 VM_OBJECT_ASSERT_LOCKED(m->object);
4244 ("vm_page_try_blocked_op: page %p has no references", m));
4245 if (VPRC_WIRE_COUNT(old) != 0)
4247 } while (!atomic_fcmpset_int(&m->ref_count, &old, old | VPRC_BLOCKED));
4252 * If the object is read-locked, new wirings may be created via an
4255 old = vm_page_drop(m, VPRC_BLOCKED);
4256 KASSERT(!VM_OBJECT_WOWNED(m->object) ||
4257 old == (VPRC_BLOCKED | VPRC_OBJREF),
4258 ("vm_page_try_blocked_op: unexpected refcount value %u for %p",
4264 * Atomically check for wirings and remove all mappings of the page.
4267 vm_page_try_remove_all(vm_page_t m)
4270 return (vm_page_try_blocked_op(m, pmap_remove_all));
4274 * Atomically check for wirings and remove all writeable mappings of the page.
4277 vm_page_try_remove_write(vm_page_t m)
4280 return (vm_page_try_blocked_op(m, pmap_remove_write));
4286 * Apply the specified advice to the given page.
4289 vm_page_advise(vm_page_t m, int advice)
4292 VM_OBJECT_ASSERT_WLOCKED(m->object);
4293 vm_page_assert_xbusied(m);
4295 if (advice == MADV_FREE)
4297 * Mark the page clean. This will allow the page to be freed
4298 * without first paging it out. MADV_FREE pages are often
4299 * quickly reused by malloc(3), so we do not do anything that
4300 * would result in a page fault on a later access.
4303 else if (advice != MADV_DONTNEED) {
4304 if (advice == MADV_WILLNEED)
4305 vm_page_activate(m);
4309 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
4313 * Clear any references to the page. Otherwise, the page daemon will
4314 * immediately reactivate the page.
4316 vm_page_aflag_clear(m, PGA_REFERENCED);
4319 * Place clean pages near the head of the inactive queue rather than
4320 * the tail, thus defeating the queue's LRU operation and ensuring that
4321 * the page will be reused quickly. Dirty pages not already in the
4322 * laundry are moved there.
4325 vm_page_deactivate_noreuse(m);
4326 else if (!vm_page_in_laundry(m))
4331 * vm_page_grab_release
4333 * Helper routine for grab functions to release busy on return.
4336 vm_page_grab_release(vm_page_t m, int allocflags)
4339 if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4340 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4348 * vm_page_grab_sleep
4350 * Sleep for busy according to VM_ALLOC_ parameters. Returns true
4351 * if the caller should retry and false otherwise.
4353 * If the object is locked on entry the object will be unlocked with
4354 * false returns and still locked but possibly having been dropped
4355 * with true returns.
4358 vm_page_grab_sleep(vm_object_t object, vm_page_t m, vm_pindex_t pindex,
4359 const char *wmesg, int allocflags, bool locked)
4362 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4366 * Reference the page before unlocking and sleeping so that
4367 * the page daemon is less likely to reclaim it.
4369 if (locked && (allocflags & VM_ALLOC_NOCREAT) == 0)
4370 vm_page_reference(m);
4372 if (_vm_page_busy_sleep(object, m, m->pindex, wmesg, allocflags,
4374 VM_OBJECT_WLOCK(object);
4375 if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
4382 * Assert that the grab flags are valid.
4385 vm_page_grab_check(int allocflags)
4388 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
4389 (allocflags & VM_ALLOC_WIRED) != 0,
4390 ("vm_page_grab*: the pages must be busied or wired"));
4392 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4393 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4394 ("vm_page_grab*: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4398 * Calculate the page allocation flags for grab.
4401 vm_page_grab_pflags(int allocflags)
4405 pflags = allocflags &
4406 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL |
4408 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4409 pflags |= VM_ALLOC_WAITFAIL;
4410 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4411 pflags |= VM_ALLOC_SBUSY;
4417 * Grab a page, waiting until we are waken up due to the page
4418 * changing state. We keep on waiting, if the page continues
4419 * to be in the object. If the page doesn't exist, first allocate it
4420 * and then conditionally zero it.
4422 * This routine may sleep.
4424 * The object must be locked on entry. The lock will, however, be released
4425 * and reacquired if the routine sleeps.
4428 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
4432 VM_OBJECT_ASSERT_WLOCKED(object);
4433 vm_page_grab_check(allocflags);
4436 if ((m = vm_page_lookup(object, pindex)) != NULL) {
4437 if (!vm_page_tryacquire(m, allocflags)) {
4438 if (vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4445 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4447 m = vm_page_alloc(object, pindex, vm_page_grab_pflags(allocflags));
4449 if ((allocflags & (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL)) != 0)
4453 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
4457 vm_page_grab_release(m, allocflags);
4463 * Locklessly attempt to acquire a page given a (object, pindex) tuple
4464 * and an optional previous page to avoid the radix lookup. The resulting
4465 * page will be validated against the identity tuple and busied or wired
4466 * as requested. A NULL *mp return guarantees that the page was not in
4467 * radix at the time of the call but callers must perform higher level
4468 * synchronization or retry the operation under a lock if they require
4469 * an atomic answer. This is the only lock free validation routine,
4470 * other routines can depend on the resulting page state.
4472 * The return value indicates whether the operation failed due to caller
4473 * flags. The return is tri-state with mp:
4475 * (true, *mp != NULL) - The operation was successful.
4476 * (true, *mp == NULL) - The page was not found in tree.
4477 * (false, *mp == NULL) - WAITFAIL or NOWAIT prevented acquisition.
4480 vm_page_acquire_unlocked(vm_object_t object, vm_pindex_t pindex,
4481 vm_page_t prev, vm_page_t *mp, int allocflags)
4485 vm_page_grab_check(allocflags);
4486 MPASS(prev == NULL || vm_page_busied(prev) || vm_page_wired(prev));
4491 * We may see a false NULL here because the previous page
4492 * has been removed or just inserted and the list is loaded
4493 * without barriers. Switch to radix to verify.
4495 if (prev == NULL || (m = TAILQ_NEXT(prev, listq)) == NULL ||
4496 QMD_IS_TRASHED(m) || m->pindex != pindex ||
4497 atomic_load_ptr(&m->object) != object) {
4500 * This guarantees the result is instantaneously
4503 m = vm_radix_lookup_unlocked(&object->rtree, pindex);
4507 if (vm_page_trybusy(m, allocflags)) {
4508 if (m->object == object && m->pindex == pindex)
4511 vm_page_busy_release(m);
4515 if (!vm_page_grab_sleep(object, m, pindex, "pgnslp",
4519 if ((allocflags & VM_ALLOC_WIRED) != 0)
4521 vm_page_grab_release(m, allocflags);
4527 * Try to locklessly grab a page and fall back to the object lock if NOCREAT
4531 vm_page_grab_unlocked(vm_object_t object, vm_pindex_t pindex, int allocflags)
4535 vm_page_grab_check(allocflags);
4537 if (!vm_page_acquire_unlocked(object, pindex, NULL, &m, allocflags))
4543 * The radix lockless lookup should never return a false negative
4544 * errors. If the user specifies NOCREAT they are guaranteed there
4545 * was no page present at the instant of the call. A NOCREAT caller
4546 * must handle create races gracefully.
4548 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4551 VM_OBJECT_WLOCK(object);
4552 m = vm_page_grab(object, pindex, allocflags);
4553 VM_OBJECT_WUNLOCK(object);
4559 * Grab a page and make it valid, paging in if necessary. Pages missing from
4560 * their pager are zero filled and validated. If a VM_ALLOC_COUNT is supplied
4561 * and the page is not valid as many as VM_INITIAL_PAGEIN pages can be brought
4562 * in simultaneously. Additional pages will be left on a paging queue but
4563 * will neither be wired nor busy regardless of allocflags.
4566 vm_page_grab_valid(vm_page_t *mp, vm_object_t object, vm_pindex_t pindex, int allocflags)
4569 vm_page_t ma[VM_INITIAL_PAGEIN];
4570 int after, i, pflags, rv;
4572 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4573 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4574 ("vm_page_grab_valid: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4575 KASSERT((allocflags &
4576 (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4577 ("vm_page_grab_valid: Invalid flags 0x%X", allocflags));
4578 VM_OBJECT_ASSERT_WLOCKED(object);
4579 pflags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY |
4581 pflags |= VM_ALLOC_WAITFAIL;
4584 if ((m = vm_page_lookup(object, pindex)) != NULL) {
4586 * If the page is fully valid it can only become invalid
4587 * with the object lock held. If it is not valid it can
4588 * become valid with the busy lock held. Therefore, we
4589 * may unnecessarily lock the exclusive busy here if we
4590 * race with I/O completion not using the object lock.
4591 * However, we will not end up with an invalid page and a
4594 if (!vm_page_trybusy(m,
4595 vm_page_all_valid(m) ? allocflags : 0)) {
4596 (void)vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4600 if (vm_page_all_valid(m))
4602 if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4603 vm_page_busy_release(m);
4605 return (VM_PAGER_FAIL);
4607 } else if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4609 return (VM_PAGER_FAIL);
4610 } else if ((m = vm_page_alloc(object, pindex, pflags)) == NULL) {
4614 vm_page_assert_xbusied(m);
4615 if (vm_pager_has_page(object, pindex, NULL, &after)) {
4616 after = MIN(after, VM_INITIAL_PAGEIN);
4617 after = MIN(after, allocflags >> VM_ALLOC_COUNT_SHIFT);
4618 after = MAX(after, 1);
4620 for (i = 1; i < after; i++) {
4621 if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
4622 if (ma[i]->valid || !vm_page_tryxbusy(ma[i]))
4625 ma[i] = vm_page_alloc(object, m->pindex + i,
4632 vm_object_pip_add(object, after);
4633 VM_OBJECT_WUNLOCK(object);
4634 rv = vm_pager_get_pages(object, ma, after, NULL, NULL);
4635 VM_OBJECT_WLOCK(object);
4636 vm_object_pip_wakeupn(object, after);
4637 /* Pager may have replaced a page. */
4639 if (rv != VM_PAGER_OK) {
4640 for (i = 0; i < after; i++) {
4641 if (!vm_page_wired(ma[i]))
4642 vm_page_free(ma[i]);
4644 vm_page_xunbusy(ma[i]);
4649 for (i = 1; i < after; i++)
4650 vm_page_readahead_finish(ma[i]);
4651 MPASS(vm_page_all_valid(m));
4653 vm_page_zero_invalid(m, TRUE);
4656 if ((allocflags & VM_ALLOC_WIRED) != 0)
4658 if ((allocflags & VM_ALLOC_SBUSY) != 0 && vm_page_xbusied(m))
4659 vm_page_busy_downgrade(m);
4660 else if ((allocflags & VM_ALLOC_NOBUSY) != 0)
4661 vm_page_busy_release(m);
4663 return (VM_PAGER_OK);
4667 * Locklessly grab a valid page. If the page is not valid or not yet
4668 * allocated this will fall back to the object lock method.
4671 vm_page_grab_valid_unlocked(vm_page_t *mp, vm_object_t object,
4672 vm_pindex_t pindex, int allocflags)
4678 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4679 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4680 ("vm_page_grab_valid_unlocked: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY "
4682 KASSERT((allocflags &
4683 (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4684 ("vm_page_grab_valid_unlocked: Invalid flags 0x%X", allocflags));
4687 * Attempt a lockless lookup and busy. We need at least an sbusy
4688 * before we can inspect the valid field and return a wired page.
4690 flags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
4691 if (!vm_page_acquire_unlocked(object, pindex, NULL, mp, flags))
4692 return (VM_PAGER_FAIL);
4693 if ((m = *mp) != NULL) {
4694 if (vm_page_all_valid(m)) {
4695 if ((allocflags & VM_ALLOC_WIRED) != 0)
4697 vm_page_grab_release(m, allocflags);
4698 return (VM_PAGER_OK);
4700 vm_page_busy_release(m);
4702 if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4704 return (VM_PAGER_FAIL);
4706 VM_OBJECT_WLOCK(object);
4707 error = vm_page_grab_valid(mp, object, pindex, allocflags);
4708 VM_OBJECT_WUNLOCK(object);
4714 * Return the specified range of pages from the given object. For each
4715 * page offset within the range, if a page already exists within the object
4716 * at that offset and it is busy, then wait for it to change state. If,
4717 * instead, the page doesn't exist, then allocate it.
4719 * The caller must always specify an allocation class.
4721 * allocation classes:
4722 * VM_ALLOC_NORMAL normal process request
4723 * VM_ALLOC_SYSTEM system *really* needs the pages
4725 * The caller must always specify that the pages are to be busied and/or
4728 * optional allocation flags:
4729 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
4730 * VM_ALLOC_NOBUSY do not exclusive busy the page
4731 * VM_ALLOC_NOWAIT do not sleep
4732 * VM_ALLOC_SBUSY set page to sbusy state
4733 * VM_ALLOC_WIRED wire the pages
4734 * VM_ALLOC_ZERO zero and validate any invalid pages
4736 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
4737 * may return a partial prefix of the requested range.
4740 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
4741 vm_page_t *ma, int count)
4747 VM_OBJECT_ASSERT_WLOCKED(object);
4748 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
4749 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
4751 ("vm_page_grab_pages: invalid page count %d", count));
4752 vm_page_grab_check(allocflags);
4754 pflags = vm_page_grab_pflags(allocflags);
4757 m = vm_radix_lookup_le(&object->rtree, pindex + i);
4758 if (m == NULL || m->pindex != pindex + i) {
4762 mpred = TAILQ_PREV(m, pglist, listq);
4763 for (; i < count; i++) {
4765 if (!vm_page_tryacquire(m, allocflags)) {
4766 if (vm_page_grab_sleep(object, m, pindex,
4767 "grbmaw", allocflags, true))
4772 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4774 m = vm_page_alloc_after(object, pindex + i,
4775 pflags | VM_ALLOC_COUNT(count - i), mpred);
4777 if ((allocflags & (VM_ALLOC_NOWAIT |
4778 VM_ALLOC_WAITFAIL)) != 0)
4783 if (vm_page_none_valid(m) &&
4784 (allocflags & VM_ALLOC_ZERO) != 0) {
4785 if ((m->flags & PG_ZERO) == 0)
4789 vm_page_grab_release(m, allocflags);
4791 m = vm_page_next(m);
4797 * Unlocked variant of vm_page_grab_pages(). This accepts the same flags
4798 * and will fall back to the locked variant to handle allocation.
4801 vm_page_grab_pages_unlocked(vm_object_t object, vm_pindex_t pindex,
4802 int allocflags, vm_page_t *ma, int count)
4809 ("vm_page_grab_pages_unlocked: invalid page count %d", count));
4810 vm_page_grab_check(allocflags);
4813 * Modify flags for lockless acquire to hold the page until we
4814 * set it valid if necessary.
4816 flags = allocflags & ~VM_ALLOC_NOBUSY;
4818 for (i = 0; i < count; i++, pindex++) {
4819 if (!vm_page_acquire_unlocked(object, pindex, pred, &m, flags))
4823 if ((flags & VM_ALLOC_ZERO) != 0 && vm_page_none_valid(m)) {
4824 if ((m->flags & PG_ZERO) == 0)
4828 /* m will still be wired or busy according to flags. */
4829 vm_page_grab_release(m, allocflags);
4832 if (i == count || (allocflags & VM_ALLOC_NOCREAT) != 0)
4835 VM_OBJECT_WLOCK(object);
4836 i += vm_page_grab_pages(object, pindex, allocflags, &ma[i], count);
4837 VM_OBJECT_WUNLOCK(object);
4843 * Mapping function for valid or dirty bits in a page.
4845 * Inputs are required to range within a page.
4848 vm_page_bits(int base, int size)
4854 base + size <= PAGE_SIZE,
4855 ("vm_page_bits: illegal base/size %d/%d", base, size)
4858 if (size == 0) /* handle degenerate case */
4861 first_bit = base >> DEV_BSHIFT;
4862 last_bit = (base + size - 1) >> DEV_BSHIFT;
4864 return (((vm_page_bits_t)2 << last_bit) -
4865 ((vm_page_bits_t)1 << first_bit));
4869 vm_page_bits_set(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t set)
4872 #if PAGE_SIZE == 32768
4873 atomic_set_64((uint64_t *)bits, set);
4874 #elif PAGE_SIZE == 16384
4875 atomic_set_32((uint32_t *)bits, set);
4876 #elif (PAGE_SIZE == 8192) && defined(atomic_set_16)
4877 atomic_set_16((uint16_t *)bits, set);
4878 #elif (PAGE_SIZE == 4096) && defined(atomic_set_8)
4879 atomic_set_8((uint8_t *)bits, set);
4880 #else /* PAGE_SIZE <= 8192 */
4884 addr = (uintptr_t)bits;
4886 * Use a trick to perform a 32-bit atomic on the
4887 * containing aligned word, to not depend on the existence
4888 * of atomic_{set, clear}_{8, 16}.
4890 shift = addr & (sizeof(uint32_t) - 1);
4891 #if BYTE_ORDER == BIG_ENDIAN
4892 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4896 addr &= ~(sizeof(uint32_t) - 1);
4897 atomic_set_32((uint32_t *)addr, set << shift);
4898 #endif /* PAGE_SIZE */
4902 vm_page_bits_clear(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t clear)
4905 #if PAGE_SIZE == 32768
4906 atomic_clear_64((uint64_t *)bits, clear);
4907 #elif PAGE_SIZE == 16384
4908 atomic_clear_32((uint32_t *)bits, clear);
4909 #elif (PAGE_SIZE == 8192) && defined(atomic_clear_16)
4910 atomic_clear_16((uint16_t *)bits, clear);
4911 #elif (PAGE_SIZE == 4096) && defined(atomic_clear_8)
4912 atomic_clear_8((uint8_t *)bits, clear);
4913 #else /* PAGE_SIZE <= 8192 */
4917 addr = (uintptr_t)bits;
4919 * Use a trick to perform a 32-bit atomic on the
4920 * containing aligned word, to not depend on the existence
4921 * of atomic_{set, clear}_{8, 16}.
4923 shift = addr & (sizeof(uint32_t) - 1);
4924 #if BYTE_ORDER == BIG_ENDIAN
4925 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4929 addr &= ~(sizeof(uint32_t) - 1);
4930 atomic_clear_32((uint32_t *)addr, clear << shift);
4931 #endif /* PAGE_SIZE */
4934 static inline vm_page_bits_t
4935 vm_page_bits_swap(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t newbits)
4937 #if PAGE_SIZE == 32768
4941 while (atomic_fcmpset_64(bits, &old, newbits) == 0);
4943 #elif PAGE_SIZE == 16384
4947 while (atomic_fcmpset_32(bits, &old, newbits) == 0);
4949 #elif (PAGE_SIZE == 8192) && defined(atomic_fcmpset_16)
4953 while (atomic_fcmpset_16(bits, &old, newbits) == 0);
4955 #elif (PAGE_SIZE == 4096) && defined(atomic_fcmpset_8)
4959 while (atomic_fcmpset_8(bits, &old, newbits) == 0);
4961 #else /* PAGE_SIZE <= 4096*/
4963 uint32_t old, new, mask;
4966 addr = (uintptr_t)bits;
4968 * Use a trick to perform a 32-bit atomic on the
4969 * containing aligned word, to not depend on the existence
4970 * of atomic_{set, swap, clear}_{8, 16}.
4972 shift = addr & (sizeof(uint32_t) - 1);
4973 #if BYTE_ORDER == BIG_ENDIAN
4974 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4978 addr &= ~(sizeof(uint32_t) - 1);
4979 mask = VM_PAGE_BITS_ALL << shift;
4984 new |= newbits << shift;
4985 } while (atomic_fcmpset_32((uint32_t *)addr, &old, new) == 0);
4986 return (old >> shift);
4987 #endif /* PAGE_SIZE */
4991 * vm_page_set_valid_range:
4993 * Sets portions of a page valid. The arguments are expected
4994 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4995 * of any partial chunks touched by the range. The invalid portion of
4996 * such chunks will be zeroed.
4998 * (base + size) must be less then or equal to PAGE_SIZE.
5001 vm_page_set_valid_range(vm_page_t m, int base, int size)
5004 vm_page_bits_t pagebits;
5006 vm_page_assert_busied(m);
5007 if (size == 0) /* handle degenerate case */
5011 * If the base is not DEV_BSIZE aligned and the valid
5012 * bit is clear, we have to zero out a portion of the
5015 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5016 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
5017 pmap_zero_page_area(m, frag, base - frag);
5020 * If the ending offset is not DEV_BSIZE aligned and the
5021 * valid bit is clear, we have to zero out a portion of
5024 endoff = base + size;
5025 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5026 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
5027 pmap_zero_page_area(m, endoff,
5028 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5031 * Assert that no previously invalid block that is now being validated
5034 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
5035 ("vm_page_set_valid_range: page %p is dirty", m));
5038 * Set valid bits inclusive of any overlap.
5040 pagebits = vm_page_bits(base, size);
5041 if (vm_page_xbusied(m))
5042 m->valid |= pagebits;
5044 vm_page_bits_set(m, &m->valid, pagebits);
5048 * Set the page dirty bits and free the invalid swap space if
5049 * present. Returns the previous dirty bits.
5052 vm_page_set_dirty(vm_page_t m)
5056 VM_PAGE_OBJECT_BUSY_ASSERT(m);
5058 if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m)) {
5060 m->dirty = VM_PAGE_BITS_ALL;
5062 old = vm_page_bits_swap(m, &m->dirty, VM_PAGE_BITS_ALL);
5063 if (old == 0 && (m->a.flags & PGA_SWAP_SPACE) != 0)
5064 vm_pager_page_unswapped(m);
5070 * Clear the given bits from the specified page's dirty field.
5072 static __inline void
5073 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
5076 vm_page_assert_busied(m);
5079 * If the page is xbusied and not write mapped we are the
5080 * only thread that can modify dirty bits. Otherwise, The pmap
5081 * layer can call vm_page_dirty() without holding a distinguished
5082 * lock. The combination of page busy and atomic operations
5083 * suffice to guarantee consistency of the page dirty field.
5085 if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
5086 m->dirty &= ~pagebits;
5088 vm_page_bits_clear(m, &m->dirty, pagebits);
5092 * vm_page_set_validclean:
5094 * Sets portions of a page valid and clean. The arguments are expected
5095 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
5096 * of any partial chunks touched by the range. The invalid portion of
5097 * such chunks will be zero'd.
5099 * (base + size) must be less then or equal to PAGE_SIZE.
5102 vm_page_set_validclean(vm_page_t m, int base, int size)
5104 vm_page_bits_t oldvalid, pagebits;
5107 vm_page_assert_busied(m);
5108 if (size == 0) /* handle degenerate case */
5112 * If the base is not DEV_BSIZE aligned and the valid
5113 * bit is clear, we have to zero out a portion of the
5116 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5117 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
5118 pmap_zero_page_area(m, frag, base - frag);
5121 * If the ending offset is not DEV_BSIZE aligned and the
5122 * valid bit is clear, we have to zero out a portion of
5125 endoff = base + size;
5126 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5127 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
5128 pmap_zero_page_area(m, endoff,
5129 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5132 * Set valid, clear dirty bits. If validating the entire
5133 * page we can safely clear the pmap modify bit. We also
5134 * use this opportunity to clear the PGA_NOSYNC flag. If a process
5135 * takes a write fault on a MAP_NOSYNC memory area the flag will
5138 * We set valid bits inclusive of any overlap, but we can only
5139 * clear dirty bits for DEV_BSIZE chunks that are fully within
5142 oldvalid = m->valid;
5143 pagebits = vm_page_bits(base, size);
5144 if (vm_page_xbusied(m))
5145 m->valid |= pagebits;
5147 vm_page_bits_set(m, &m->valid, pagebits);
5149 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
5150 frag = DEV_BSIZE - frag;
5156 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
5158 if (base == 0 && size == PAGE_SIZE) {
5160 * The page can only be modified within the pmap if it is
5161 * mapped, and it can only be mapped if it was previously
5164 if (oldvalid == VM_PAGE_BITS_ALL)
5166 * Perform the pmap_clear_modify() first. Otherwise,
5167 * a concurrent pmap operation, such as
5168 * pmap_protect(), could clear a modification in the
5169 * pmap and set the dirty field on the page before
5170 * pmap_clear_modify() had begun and after the dirty
5171 * field was cleared here.
5173 pmap_clear_modify(m);
5175 vm_page_aflag_clear(m, PGA_NOSYNC);
5176 } else if (oldvalid != VM_PAGE_BITS_ALL && vm_page_xbusied(m))
5177 m->dirty &= ~pagebits;
5179 vm_page_clear_dirty_mask(m, pagebits);
5183 vm_page_clear_dirty(vm_page_t m, int base, int size)
5186 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
5190 * vm_page_set_invalid:
5192 * Invalidates DEV_BSIZE'd chunks within a page. Both the
5193 * valid and dirty bits for the effected areas are cleared.
5196 vm_page_set_invalid(vm_page_t m, int base, int size)
5198 vm_page_bits_t bits;
5202 * The object lock is required so that pages can't be mapped
5203 * read-only while we're in the process of invalidating them.
5206 VM_OBJECT_ASSERT_WLOCKED(object);
5207 vm_page_assert_busied(m);
5209 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
5210 size >= object->un_pager.vnp.vnp_size)
5211 bits = VM_PAGE_BITS_ALL;
5213 bits = vm_page_bits(base, size);
5214 if (object->ref_count != 0 && vm_page_all_valid(m) && bits != 0)
5216 KASSERT((bits == 0 && vm_page_all_valid(m)) ||
5217 !pmap_page_is_mapped(m),
5218 ("vm_page_set_invalid: page %p is mapped", m));
5219 if (vm_page_xbusied(m)) {
5223 vm_page_bits_clear(m, &m->valid, bits);
5224 vm_page_bits_clear(m, &m->dirty, bits);
5231 * Invalidates the entire page. The page must be busy, unmapped, and
5232 * the enclosing object must be locked. The object locks protects
5233 * against concurrent read-only pmap enter which is done without
5237 vm_page_invalid(vm_page_t m)
5240 vm_page_assert_busied(m);
5241 VM_OBJECT_ASSERT_LOCKED(m->object);
5242 MPASS(!pmap_page_is_mapped(m));
5244 if (vm_page_xbusied(m))
5247 vm_page_bits_clear(m, &m->valid, VM_PAGE_BITS_ALL);
5251 * vm_page_zero_invalid()
5253 * The kernel assumes that the invalid portions of a page contain
5254 * garbage, but such pages can be mapped into memory by user code.
5255 * When this occurs, we must zero out the non-valid portions of the
5256 * page so user code sees what it expects.
5258 * Pages are most often semi-valid when the end of a file is mapped
5259 * into memory and the file's size is not page aligned.
5262 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
5268 * Scan the valid bits looking for invalid sections that
5269 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
5270 * valid bit may be set ) have already been zeroed by
5271 * vm_page_set_validclean().
5273 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
5274 if (i == (PAGE_SIZE / DEV_BSIZE) ||
5275 (m->valid & ((vm_page_bits_t)1 << i))) {
5277 pmap_zero_page_area(m,
5278 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
5285 * setvalid is TRUE when we can safely set the zero'd areas
5286 * as being valid. We can do this if there are no cache consistancy
5287 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
5296 * Is (partial) page valid? Note that the case where size == 0
5297 * will return FALSE in the degenerate case where the page is
5298 * entirely invalid, and TRUE otherwise.
5300 * Some callers envoke this routine without the busy lock held and
5301 * handle races via higher level locks. Typical callers should
5302 * hold a busy lock to prevent invalidation.
5305 vm_page_is_valid(vm_page_t m, int base, int size)
5307 vm_page_bits_t bits;
5309 bits = vm_page_bits(base, size);
5310 return (m->valid != 0 && (m->valid & bits) == bits);
5314 * Returns true if all of the specified predicates are true for the entire
5315 * (super)page and false otherwise.
5318 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
5324 if (skip_m != NULL && skip_m->object != object)
5326 VM_OBJECT_ASSERT_LOCKED(object);
5327 npages = atop(pagesizes[m->psind]);
5330 * The physically contiguous pages that make up a superpage, i.e., a
5331 * page with a page size index ("psind") greater than zero, will
5332 * occupy adjacent entries in vm_page_array[].
5334 for (i = 0; i < npages; i++) {
5335 /* Always test object consistency, including "skip_m". */
5336 if (m[i].object != object)
5338 if (&m[i] == skip_m)
5340 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
5342 if ((flags & PS_ALL_DIRTY) != 0) {
5344 * Calling vm_page_test_dirty() or pmap_is_modified()
5345 * might stop this case from spuriously returning
5346 * "false". However, that would require a write lock
5347 * on the object containing "m[i]".
5349 if (m[i].dirty != VM_PAGE_BITS_ALL)
5352 if ((flags & PS_ALL_VALID) != 0 &&
5353 m[i].valid != VM_PAGE_BITS_ALL)
5360 * Set the page's dirty bits if the page is modified.
5363 vm_page_test_dirty(vm_page_t m)
5366 vm_page_assert_busied(m);
5367 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
5372 vm_page_valid(vm_page_t m)
5375 vm_page_assert_busied(m);
5376 if (vm_page_xbusied(m))
5377 m->valid = VM_PAGE_BITS_ALL;
5379 vm_page_bits_set(m, &m->valid, VM_PAGE_BITS_ALL);
5383 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
5386 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
5390 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
5393 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
5397 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
5400 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
5403 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
5405 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
5408 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
5412 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
5415 mtx_assert_(vm_page_lockptr(m), a, file, line);
5421 vm_page_object_busy_assert(vm_page_t m)
5425 * Certain of the page's fields may only be modified by the
5426 * holder of a page or object busy.
5428 if (m->object != NULL && !vm_page_busied(m))
5429 VM_OBJECT_ASSERT_BUSY(m->object);
5433 vm_page_assert_pga_writeable(vm_page_t m, uint16_t bits)
5436 if ((bits & PGA_WRITEABLE) == 0)
5440 * The PGA_WRITEABLE flag can only be set if the page is
5441 * managed, is exclusively busied or the object is locked.
5442 * Currently, this flag is only set by pmap_enter().
5444 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5445 ("PGA_WRITEABLE on unmanaged page"));
5446 if (!vm_page_xbusied(m))
5447 VM_OBJECT_ASSERT_BUSY(m->object);
5451 #include "opt_ddb.h"
5453 #include <sys/kernel.h>
5455 #include <ddb/ddb.h>
5457 DB_SHOW_COMMAND(page, vm_page_print_page_info)
5460 db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
5461 db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
5462 db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
5463 db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
5464 db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
5465 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
5466 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
5467 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
5468 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
5471 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
5475 db_printf("pq_free %d\n", vm_free_count());
5476 for (dom = 0; dom < vm_ndomains; dom++) {
5478 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
5480 vm_dom[dom].vmd_page_count,
5481 vm_dom[dom].vmd_free_count,
5482 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
5483 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
5484 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
5485 vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
5489 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
5492 boolean_t phys, virt;
5495 db_printf("show pginfo addr\n");
5499 phys = strchr(modif, 'p') != NULL;
5500 virt = strchr(modif, 'v') != NULL;
5502 m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
5504 m = PHYS_TO_VM_PAGE(addr);
5506 m = (vm_page_t)addr;
5508 "page %p obj %p pidx 0x%jx phys 0x%jx q %d ref 0x%x\n"
5509 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
5510 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
5511 m->a.queue, m->ref_count, m->a.flags, m->oflags,
5512 m->flags, m->a.act_count, m->busy_lock, m->valid, m->dirty);