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 static TAILQ_HEAD(, vm_page) blacklist_head;
159 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
160 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
161 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
163 static uma_zone_t fakepg_zone;
165 static void vm_page_alloc_check(vm_page_t m);
166 static bool _vm_page_busy_sleep(vm_object_t obj, vm_page_t m,
167 vm_pindex_t pindex, const char *wmesg, int allocflags, bool locked);
168 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
169 static void vm_page_enqueue(vm_page_t m, uint8_t queue);
170 static bool vm_page_free_prep(vm_page_t m);
171 static void vm_page_free_toq(vm_page_t m);
172 static void vm_page_init(void *dummy);
173 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
174 vm_pindex_t pindex, vm_page_t mpred);
175 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
177 static void vm_page_mvqueue(vm_page_t m, const uint8_t queue,
178 const uint16_t nflag);
179 static int vm_page_reclaim_run(int req_class, int domain, u_long npages,
180 vm_page_t m_run, vm_paddr_t high);
181 static void vm_page_release_toq(vm_page_t m, uint8_t nqueue, bool noreuse);
182 static int vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object,
184 static int vm_page_zone_import(void *arg, void **store, int cnt, int domain,
186 static void vm_page_zone_release(void *arg, void **store, int cnt);
188 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
191 vm_page_init(void *dummy)
194 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
195 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
196 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
197 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
201 * The cache page zone is initialized later since we need to be able to allocate
202 * pages before UMA is fully initialized.
205 vm_page_init_cache_zones(void *dummy __unused)
207 struct vm_domain *vmd;
208 struct vm_pgcache *pgcache;
209 int cache, domain, maxcache, pool;
212 TUNABLE_INT_FETCH("vm.pgcache_zone_max_pcpu", &maxcache);
213 maxcache *= mp_ncpus;
214 for (domain = 0; domain < vm_ndomains; domain++) {
215 vmd = VM_DOMAIN(domain);
216 for (pool = 0; pool < VM_NFREEPOOL; pool++) {
217 pgcache = &vmd->vmd_pgcache[pool];
218 pgcache->domain = domain;
219 pgcache->pool = pool;
220 pgcache->zone = uma_zcache_create("vm pgcache",
221 PAGE_SIZE, NULL, NULL, NULL, NULL,
222 vm_page_zone_import, vm_page_zone_release, pgcache,
226 * Limit each pool's zone to 0.1% of the pages in the
229 cache = maxcache != 0 ? maxcache :
230 vmd->vmd_page_count / 1000;
231 uma_zone_set_maxcache(pgcache->zone, cache);
235 SYSINIT(vm_page2, SI_SUB_VM_CONF, SI_ORDER_ANY, vm_page_init_cache_zones, NULL);
237 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
238 #if PAGE_SIZE == 32768
240 CTASSERT(sizeof(u_long) >= 8);
247 * Sets the page size, perhaps based upon the memory
248 * size. Must be called before any use of page-size
249 * dependent functions.
252 vm_set_page_size(void)
254 if (vm_cnt.v_page_size == 0)
255 vm_cnt.v_page_size = PAGE_SIZE;
256 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
257 panic("vm_set_page_size: page size not a power of two");
261 * vm_page_blacklist_next:
263 * Find the next entry in the provided string of blacklist
264 * addresses. Entries are separated by space, comma, or newline.
265 * If an invalid integer is encountered then the rest of the
266 * string is skipped. Updates the list pointer to the next
267 * character, or NULL if the string is exhausted or invalid.
270 vm_page_blacklist_next(char **list, char *end)
275 if (list == NULL || *list == NULL)
283 * If there's no end pointer then the buffer is coming from
284 * the kenv and we know it's null-terminated.
287 end = *list + strlen(*list);
289 /* Ensure that strtoq() won't walk off the end */
291 if (*end == '\n' || *end == ' ' || *end == ',')
294 printf("Blacklist not terminated, skipping\n");
300 for (pos = *list; *pos != '\0'; pos = cp) {
301 bad = strtoq(pos, &cp, 0);
302 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
311 if (*cp == '\0' || ++cp >= end)
315 return (trunc_page(bad));
317 printf("Garbage in RAM blacklist, skipping\n");
323 vm_page_blacklist_add(vm_paddr_t pa, bool verbose)
325 struct vm_domain *vmd;
329 m = vm_phys_paddr_to_vm_page(pa);
331 return (true); /* page does not exist, no failure */
333 vmd = vm_pagequeue_domain(m);
334 vm_domain_free_lock(vmd);
335 ret = vm_phys_unfree_page(m);
336 vm_domain_free_unlock(vmd);
338 vm_domain_freecnt_inc(vmd, -1);
339 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
341 printf("Skipping page with pa 0x%jx\n", (uintmax_t)pa);
347 * vm_page_blacklist_check:
349 * Iterate through the provided string of blacklist addresses, pulling
350 * each entry out of the physical allocator free list and putting it
351 * onto a list for reporting via the vm.page_blacklist sysctl.
354 vm_page_blacklist_check(char *list, char *end)
360 while (next != NULL) {
361 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
363 vm_page_blacklist_add(pa, bootverbose);
368 * vm_page_blacklist_load:
370 * Search for a special module named "ram_blacklist". It'll be a
371 * plain text file provided by the user via the loader directive
375 vm_page_blacklist_load(char **list, char **end)
384 mod = preload_search_by_type("ram_blacklist");
386 ptr = preload_fetch_addr(mod);
387 len = preload_fetch_size(mod);
398 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
405 error = sysctl_wire_old_buffer(req, 0);
408 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
409 TAILQ_FOREACH(m, &blacklist_head, listq) {
410 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
411 (uintmax_t)m->phys_addr);
414 error = sbuf_finish(&sbuf);
420 * Initialize a dummy page for use in scans of the specified paging queue.
421 * In principle, this function only needs to set the flag PG_MARKER.
422 * Nonetheless, it write busies the page as a safety precaution.
425 vm_page_init_marker(vm_page_t marker, int queue, uint16_t aflags)
428 bzero(marker, sizeof(*marker));
429 marker->flags = PG_MARKER;
430 marker->a.flags = aflags;
431 marker->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
432 marker->a.queue = queue;
436 vm_page_domain_init(int domain)
438 struct vm_domain *vmd;
439 struct vm_pagequeue *pq;
442 vmd = VM_DOMAIN(domain);
443 bzero(vmd, sizeof(*vmd));
444 *__DECONST(const char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
445 "vm inactive pagequeue";
446 *__DECONST(const char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
447 "vm active pagequeue";
448 *__DECONST(const char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
449 "vm laundry pagequeue";
450 *__DECONST(const char **,
451 &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_name) =
452 "vm unswappable pagequeue";
453 vmd->vmd_domain = domain;
454 vmd->vmd_page_count = 0;
455 vmd->vmd_free_count = 0;
457 vmd->vmd_oom = FALSE;
458 for (i = 0; i < PQ_COUNT; i++) {
459 pq = &vmd->vmd_pagequeues[i];
460 TAILQ_INIT(&pq->pq_pl);
461 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
462 MTX_DEF | MTX_DUPOK);
464 vm_page_init_marker(&vmd->vmd_markers[i], i, 0);
466 mtx_init(&vmd->vmd_free_mtx, "vm page free queue", NULL, MTX_DEF);
467 mtx_init(&vmd->vmd_pageout_mtx, "vm pageout lock", NULL, MTX_DEF);
468 snprintf(vmd->vmd_name, sizeof(vmd->vmd_name), "%d", domain);
471 * inacthead is used to provide FIFO ordering for LRU-bypassing
474 vm_page_init_marker(&vmd->vmd_inacthead, PQ_INACTIVE, PGA_ENQUEUED);
475 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_INACTIVE].pq_pl,
476 &vmd->vmd_inacthead, plinks.q);
479 * The clock pages are used to implement active queue scanning without
480 * requeues. Scans start at clock[0], which is advanced after the scan
481 * ends. When the two clock hands meet, they are reset and scanning
482 * resumes from the head of the queue.
484 vm_page_init_marker(&vmd->vmd_clock[0], PQ_ACTIVE, PGA_ENQUEUED);
485 vm_page_init_marker(&vmd->vmd_clock[1], PQ_ACTIVE, PGA_ENQUEUED);
486 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
487 &vmd->vmd_clock[0], plinks.q);
488 TAILQ_INSERT_TAIL(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
489 &vmd->vmd_clock[1], plinks.q);
493 * Initialize a physical page in preparation for adding it to the free
497 vm_page_init_page(vm_page_t m, vm_paddr_t pa, int segind)
502 m->busy_lock = VPB_FREED;
503 m->flags = m->a.flags = 0;
505 m->a.queue = PQ_NONE;
508 m->order = VM_NFREEORDER;
509 m->pool = VM_FREEPOOL_DEFAULT;
510 m->valid = m->dirty = 0;
514 #ifndef PMAP_HAS_PAGE_ARRAY
516 vm_page_array_alloc(vm_offset_t *vaddr, vm_paddr_t end, vm_paddr_t page_range)
521 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
522 * However, because this page is allocated from KVM, out-of-bounds
523 * accesses using the direct map will not be trapped.
528 * Allocate physical memory for the page structures, and map it.
530 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
531 vm_page_array = (vm_page_t)pmap_map(vaddr, new_end, end,
532 VM_PROT_READ | VM_PROT_WRITE);
533 vm_page_array_size = page_range;
542 * Initializes the resident memory module. Allocates physical memory for
543 * bootstrapping UMA and some data structures that are used to manage
544 * physical pages. Initializes these structures, and populates the free
548 vm_page_startup(vm_offset_t vaddr)
550 struct vm_phys_seg *seg;
552 char *list, *listend;
553 vm_paddr_t end, high_avail, low_avail, new_end, size;
554 vm_paddr_t page_range __unused;
555 vm_paddr_t last_pa, pa;
557 int biggestone, i, segind;
562 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
566 vaddr = round_page(vaddr);
568 vm_phys_early_startup();
569 biggestone = vm_phys_avail_largest();
570 end = phys_avail[biggestone+1];
573 * Initialize the page and queue locks.
575 mtx_init(&vm_domainset_lock, "vm domainset lock", NULL, MTX_DEF);
576 for (i = 0; i < PA_LOCK_COUNT; i++)
577 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
578 for (i = 0; i < vm_ndomains; i++)
579 vm_page_domain_init(i);
583 witness_size = round_page(witness_startup_count());
584 new_end -= witness_size;
585 mapped = pmap_map(&vaddr, new_end, new_end + witness_size,
586 VM_PROT_READ | VM_PROT_WRITE);
587 bzero((void *)mapped, witness_size);
588 witness_startup((void *)mapped);
591 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
592 defined(__i386__) || defined(__mips__) || defined(__riscv) || \
593 defined(__powerpc64__)
595 * Allocate a bitmap to indicate that a random physical page
596 * needs to be included in a minidump.
598 * The amd64 port needs this to indicate which direct map pages
599 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
601 * However, i386 still needs this workspace internally within the
602 * minidump code. In theory, they are not needed on i386, but are
603 * included should the sf_buf code decide to use them.
606 for (i = 0; dump_avail[i + 1] != 0; i += 2)
607 if (dump_avail[i + 1] > last_pa)
608 last_pa = dump_avail[i + 1];
609 page_range = last_pa / PAGE_SIZE;
610 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
611 new_end -= vm_page_dump_size;
612 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
613 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
614 bzero((void *)vm_page_dump, vm_page_dump_size);
618 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
619 defined(__riscv) || defined(__powerpc64__)
621 * Include the UMA bootstrap pages, witness pages and vm_page_dump
622 * in a crash dump. When pmap_map() uses the direct map, they are
623 * not automatically included.
625 for (pa = new_end; pa < end; pa += PAGE_SIZE)
628 phys_avail[biggestone + 1] = new_end;
631 * Request that the physical pages underlying the message buffer be
632 * included in a crash dump. Since the message buffer is accessed
633 * through the direct map, they are not automatically included.
635 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
636 last_pa = pa + round_page(msgbufsize);
637 while (pa < last_pa) {
643 * Compute the number of pages of memory that will be available for
644 * use, taking into account the overhead of a page structure per page.
645 * In other words, solve
646 * "available physical memory" - round_page(page_range *
647 * sizeof(struct vm_page)) = page_range * PAGE_SIZE
650 low_avail = phys_avail[0];
651 high_avail = phys_avail[1];
652 for (i = 0; i < vm_phys_nsegs; i++) {
653 if (vm_phys_segs[i].start < low_avail)
654 low_avail = vm_phys_segs[i].start;
655 if (vm_phys_segs[i].end > high_avail)
656 high_avail = vm_phys_segs[i].end;
658 /* Skip the first chunk. It is already accounted for. */
659 for (i = 2; phys_avail[i + 1] != 0; i += 2) {
660 if (phys_avail[i] < low_avail)
661 low_avail = phys_avail[i];
662 if (phys_avail[i + 1] > high_avail)
663 high_avail = phys_avail[i + 1];
665 first_page = low_avail / PAGE_SIZE;
666 #ifdef VM_PHYSSEG_SPARSE
668 for (i = 0; i < vm_phys_nsegs; i++)
669 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
670 for (i = 0; phys_avail[i + 1] != 0; i += 2)
671 size += phys_avail[i + 1] - phys_avail[i];
672 #elif defined(VM_PHYSSEG_DENSE)
673 size = high_avail - low_avail;
675 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
678 #ifdef PMAP_HAS_PAGE_ARRAY
679 pmap_page_array_startup(size / PAGE_SIZE);
680 biggestone = vm_phys_avail_largest();
681 end = new_end = phys_avail[biggestone + 1];
683 #ifdef VM_PHYSSEG_DENSE
685 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
686 * the overhead of a page structure per page only if vm_page_array is
687 * allocated from the last physical memory chunk. Otherwise, we must
688 * allocate page structures representing the physical memory
689 * underlying vm_page_array, even though they will not be used.
691 if (new_end != high_avail)
692 page_range = size / PAGE_SIZE;
696 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
699 * If the partial bytes remaining are large enough for
700 * a page (PAGE_SIZE) without a corresponding
701 * 'struct vm_page', then new_end will contain an
702 * extra page after subtracting the length of the VM
703 * page array. Compensate by subtracting an extra
706 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
707 if (new_end == high_avail)
708 high_avail -= PAGE_SIZE;
709 new_end -= PAGE_SIZE;
713 new_end = vm_page_array_alloc(&vaddr, end, page_range);
716 #if VM_NRESERVLEVEL > 0
718 * Allocate physical memory for the reservation management system's
719 * data structures, and map it.
721 new_end = vm_reserv_startup(&vaddr, new_end);
723 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
724 defined(__riscv) || defined(__powerpc64__)
726 * Include vm_page_array and vm_reserv_array in a crash dump.
728 for (pa = new_end; pa < end; pa += PAGE_SIZE)
731 phys_avail[biggestone + 1] = new_end;
734 * Add physical memory segments corresponding to the available
737 for (i = 0; phys_avail[i + 1] != 0; i += 2)
738 if (vm_phys_avail_size(i) != 0)
739 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
742 * Initialize the physical memory allocator.
747 * Initialize the page structures and add every available page to the
748 * physical memory allocator's free lists.
750 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
751 for (ii = 0; ii < vm_page_array_size; ii++) {
752 m = &vm_page_array[ii];
753 vm_page_init_page(m, (first_page + ii) << PAGE_SHIFT, 0);
754 m->flags = PG_FICTITIOUS;
757 vm_cnt.v_page_count = 0;
758 for (segind = 0; segind < vm_phys_nsegs; segind++) {
759 seg = &vm_phys_segs[segind];
760 for (m = seg->first_page, pa = seg->start; pa < seg->end;
761 m++, pa += PAGE_SIZE)
762 vm_page_init_page(m, pa, segind);
765 * Add the segment to the free lists only if it is covered by
766 * one of the ranges in phys_avail. Because we've added the
767 * ranges to the vm_phys_segs array, we can assume that each
768 * segment is either entirely contained in one of the ranges,
769 * or doesn't overlap any of them.
771 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
772 struct vm_domain *vmd;
774 if (seg->start < phys_avail[i] ||
775 seg->end > phys_avail[i + 1])
779 pagecount = (u_long)atop(seg->end - seg->start);
781 vmd = VM_DOMAIN(seg->domain);
782 vm_domain_free_lock(vmd);
783 vm_phys_enqueue_contig(m, pagecount);
784 vm_domain_free_unlock(vmd);
785 vm_domain_freecnt_inc(vmd, pagecount);
786 vm_cnt.v_page_count += (u_int)pagecount;
788 vmd = VM_DOMAIN(seg->domain);
789 vmd->vmd_page_count += (u_int)pagecount;
790 vmd->vmd_segs |= 1UL << m->segind;
796 * Remove blacklisted pages from the physical memory allocator.
798 TAILQ_INIT(&blacklist_head);
799 vm_page_blacklist_load(&list, &listend);
800 vm_page_blacklist_check(list, listend);
802 list = kern_getenv("vm.blacklist");
803 vm_page_blacklist_check(list, NULL);
806 #if VM_NRESERVLEVEL > 0
808 * Initialize the reservation management system.
817 vm_page_reference(vm_page_t m)
820 vm_page_aflag_set(m, PGA_REFERENCED);
826 * Helper routine for grab functions to trylock busy.
828 * Returns true on success and false on failure.
831 vm_page_trybusy(vm_page_t m, int allocflags)
834 if ((allocflags & (VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY)) != 0)
835 return (vm_page_trysbusy(m));
837 return (vm_page_tryxbusy(m));
843 * Helper routine for grab functions to trylock busy and wire.
845 * Returns true on success and false on failure.
848 vm_page_tryacquire(vm_page_t m, int allocflags)
852 locked = vm_page_trybusy(m, allocflags);
853 if (locked && (allocflags & VM_ALLOC_WIRED) != 0)
859 * vm_page_busy_acquire:
861 * Acquire the busy lock as described by VM_ALLOC_* flags. Will loop
862 * and drop the object lock if necessary.
865 vm_page_busy_acquire(vm_page_t m, int allocflags)
871 * The page-specific object must be cached because page
872 * identity can change during the sleep, causing the
873 * re-lock of a different object.
874 * It is assumed that a reference to the object is already
875 * held by the callers.
879 if (vm_page_tryacquire(m, allocflags))
881 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
884 locked = VM_OBJECT_WOWNED(obj);
887 MPASS(locked || vm_page_wired(m));
888 if (_vm_page_busy_sleep(obj, m, m->pindex, "vmpba", allocflags,
890 VM_OBJECT_WLOCK(obj);
891 if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
893 KASSERT(m->object == obj || m->object == NULL,
894 ("vm_page_busy_acquire: page %p does not belong to %p",
900 * vm_page_busy_downgrade:
902 * Downgrade an exclusive busy page into a single shared busy page.
905 vm_page_busy_downgrade(vm_page_t m)
909 vm_page_assert_xbusied(m);
913 if (atomic_fcmpset_rel_int(&m->busy_lock,
914 &x, VPB_SHARERS_WORD(1)))
917 if ((x & VPB_BIT_WAITERS) != 0)
923 * vm_page_busy_tryupgrade:
925 * Attempt to upgrade a single shared busy into an exclusive busy.
928 vm_page_busy_tryupgrade(vm_page_t m)
932 vm_page_assert_sbusied(m);
935 ce = VPB_CURTHREAD_EXCLUSIVE;
937 if (VPB_SHARERS(x) > 1)
939 KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
940 ("vm_page_busy_tryupgrade: invalid lock state"));
941 if (!atomic_fcmpset_acq_int(&m->busy_lock, &x,
942 ce | (x & VPB_BIT_WAITERS)))
951 * Return a positive value if the page is shared busied, 0 otherwise.
954 vm_page_sbusied(vm_page_t m)
959 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
965 * Shared unbusy a page.
968 vm_page_sunbusy(vm_page_t m)
972 vm_page_assert_sbusied(m);
976 KASSERT(x != VPB_FREED,
977 ("vm_page_sunbusy: Unlocking freed page."));
978 if (VPB_SHARERS(x) > 1) {
979 if (atomic_fcmpset_int(&m->busy_lock, &x,
984 KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
985 ("vm_page_sunbusy: invalid lock state"));
986 if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
988 if ((x & VPB_BIT_WAITERS) == 0)
996 * vm_page_busy_sleep:
998 * Sleep if the page is busy, using the page pointer as wchan.
999 * This is used to implement the hard-path of busying mechanism.
1001 * If nonshared is true, sleep only if the page is xbusy.
1003 * The object lock must be held on entry and will be released on exit.
1006 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
1011 VM_OBJECT_ASSERT_LOCKED(obj);
1012 vm_page_lock_assert(m, MA_NOTOWNED);
1014 if (!_vm_page_busy_sleep(obj, m, m->pindex, wmesg,
1015 nonshared ? VM_ALLOC_SBUSY : 0 , true))
1016 VM_OBJECT_DROP(obj);
1020 * vm_page_busy_sleep_unlocked:
1022 * Sleep if the page is busy, using the page pointer as wchan.
1023 * This is used to implement the hard-path of busying mechanism.
1025 * If nonshared is true, sleep only if the page is xbusy.
1027 * The object lock must not be held on entry. The operation will
1028 * return if the page changes identity.
1031 vm_page_busy_sleep_unlocked(vm_object_t obj, vm_page_t m, vm_pindex_t pindex,
1032 const char *wmesg, bool nonshared)
1035 VM_OBJECT_ASSERT_UNLOCKED(obj);
1036 vm_page_lock_assert(m, MA_NOTOWNED);
1038 _vm_page_busy_sleep(obj, m, pindex, wmesg,
1039 nonshared ? VM_ALLOC_SBUSY : 0, false);
1043 * _vm_page_busy_sleep:
1045 * Internal busy sleep function. Verifies the page identity and
1046 * lockstate against parameters. Returns true if it sleeps and
1049 * If locked is true the lock will be dropped for any true returns
1050 * and held for any false returns.
1053 _vm_page_busy_sleep(vm_object_t obj, vm_page_t m, vm_pindex_t pindex,
1054 const char *wmesg, int allocflags, bool locked)
1060 * If the object is busy we must wait for that to drain to zero
1061 * before trying the page again.
1063 if (obj != NULL && vm_object_busied(obj)) {
1065 VM_OBJECT_DROP(obj);
1066 vm_object_busy_wait(obj, wmesg);
1070 if (!vm_page_busied(m))
1073 xsleep = (allocflags & (VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY)) != 0;
1075 x = atomic_load_int(&m->busy_lock);
1078 * If the page changes objects or becomes unlocked we can
1081 if (x == VPB_UNBUSIED ||
1082 (xsleep && (x & VPB_BIT_SHARED) != 0) ||
1083 m->object != obj || m->pindex != pindex) {
1087 if ((x & VPB_BIT_WAITERS) != 0)
1089 } while (!atomic_fcmpset_int(&m->busy_lock, &x, x | VPB_BIT_WAITERS));
1091 VM_OBJECT_DROP(obj);
1093 sleepq_add(m, NULL, wmesg, 0, 0);
1094 sleepq_wait(m, PVM);
1102 * Try to shared busy a page.
1103 * If the operation succeeds 1 is returned otherwise 0.
1104 * The operation never sleeps.
1107 vm_page_trysbusy(vm_page_t m)
1115 if ((x & VPB_BIT_SHARED) == 0)
1118 * Reduce the window for transient busies that will trigger
1119 * false negatives in vm_page_ps_test().
1121 if (obj != NULL && vm_object_busied(obj))
1123 if (atomic_fcmpset_acq_int(&m->busy_lock, &x,
1124 x + VPB_ONE_SHARER))
1128 /* Refetch the object now that we're guaranteed that it is stable. */
1130 if (obj != NULL && vm_object_busied(obj)) {
1140 * Try to exclusive busy a page.
1141 * If the operation succeeds 1 is returned otherwise 0.
1142 * The operation never sleeps.
1145 vm_page_tryxbusy(vm_page_t m)
1149 if (atomic_cmpset_acq_int(&(m)->busy_lock, VPB_UNBUSIED,
1150 VPB_CURTHREAD_EXCLUSIVE) == 0)
1154 if (obj != NULL && vm_object_busied(obj)) {
1162 vm_page_xunbusy_hard_tail(vm_page_t m)
1164 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1165 /* Wake the waiter. */
1170 * vm_page_xunbusy_hard:
1172 * Called when unbusy has failed because there is a waiter.
1175 vm_page_xunbusy_hard(vm_page_t m)
1177 vm_page_assert_xbusied(m);
1178 vm_page_xunbusy_hard_tail(m);
1182 vm_page_xunbusy_hard_unchecked(vm_page_t m)
1184 vm_page_assert_xbusied_unchecked(m);
1185 vm_page_xunbusy_hard_tail(m);
1189 vm_page_busy_free(vm_page_t m)
1193 atomic_thread_fence_rel();
1194 x = atomic_swap_int(&m->busy_lock, VPB_FREED);
1195 if ((x & VPB_BIT_WAITERS) != 0)
1200 * vm_page_unhold_pages:
1202 * Unhold each of the pages that is referenced by the given array.
1205 vm_page_unhold_pages(vm_page_t *ma, int count)
1208 for (; count != 0; count--) {
1209 vm_page_unwire(*ma, PQ_ACTIVE);
1215 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1219 #ifdef VM_PHYSSEG_SPARSE
1220 m = vm_phys_paddr_to_vm_page(pa);
1222 m = vm_phys_fictitious_to_vm_page(pa);
1224 #elif defined(VM_PHYSSEG_DENSE)
1228 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1229 m = &vm_page_array[pi - first_page];
1232 return (vm_phys_fictitious_to_vm_page(pa));
1234 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1241 * Create a fictitious page with the specified physical address and
1242 * memory attribute. The memory attribute is the only the machine-
1243 * dependent aspect of a fictitious page that must be initialized.
1246 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1250 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1251 vm_page_initfake(m, paddr, memattr);
1256 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1259 if ((m->flags & PG_FICTITIOUS) != 0) {
1261 * The page's memattr might have changed since the
1262 * previous initialization. Update the pmap to the
1267 m->phys_addr = paddr;
1268 m->a.queue = PQ_NONE;
1269 /* Fictitious pages don't use "segind". */
1270 m->flags = PG_FICTITIOUS;
1271 /* Fictitious pages don't use "order" or "pool". */
1272 m->oflags = VPO_UNMANAGED;
1273 m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
1274 /* Fictitious pages are unevictable. */
1278 pmap_page_set_memattr(m, memattr);
1284 * Release a fictitious page.
1287 vm_page_putfake(vm_page_t m)
1290 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1291 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1292 ("vm_page_putfake: bad page %p", m));
1293 vm_page_assert_xbusied(m);
1294 vm_page_busy_free(m);
1295 uma_zfree(fakepg_zone, m);
1299 * vm_page_updatefake:
1301 * Update the given fictitious page to the specified physical address and
1305 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1308 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1309 ("vm_page_updatefake: bad page %p", m));
1310 m->phys_addr = paddr;
1311 pmap_page_set_memattr(m, memattr);
1320 vm_page_free(vm_page_t m)
1323 m->flags &= ~PG_ZERO;
1324 vm_page_free_toq(m);
1328 * vm_page_free_zero:
1330 * Free a page to the zerod-pages queue
1333 vm_page_free_zero(vm_page_t m)
1336 m->flags |= PG_ZERO;
1337 vm_page_free_toq(m);
1341 * Unbusy and handle the page queueing for a page from a getpages request that
1342 * was optionally read ahead or behind.
1345 vm_page_readahead_finish(vm_page_t m)
1348 /* We shouldn't put invalid pages on queues. */
1349 KASSERT(!vm_page_none_valid(m), ("%s: %p is invalid", __func__, m));
1352 * Since the page is not the actually needed one, whether it should
1353 * be activated or deactivated is not obvious. Empirical results
1354 * have shown that deactivating the page is usually the best choice,
1355 * unless the page is wanted by another thread.
1357 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1358 vm_page_activate(m);
1360 vm_page_deactivate(m);
1361 vm_page_xunbusy_unchecked(m);
1365 * vm_page_sleep_if_busy:
1367 * Sleep and release the object lock if the page is busied.
1368 * Returns TRUE if the thread slept.
1370 * The given page must be unlocked and object containing it must
1374 vm_page_sleep_if_busy(vm_page_t m, const char *wmesg)
1378 vm_page_lock_assert(m, MA_NOTOWNED);
1379 VM_OBJECT_ASSERT_WLOCKED(m->object);
1382 * The page-specific object must be cached because page
1383 * identity can change during the sleep, causing the
1384 * re-lock of a different object.
1385 * It is assumed that a reference to the object is already
1386 * held by the callers.
1389 if (_vm_page_busy_sleep(obj, m, m->pindex, wmesg, 0, true)) {
1390 VM_OBJECT_WLOCK(obj);
1397 * vm_page_sleep_if_xbusy:
1399 * Sleep and release the object lock if the page is xbusied.
1400 * Returns TRUE if the thread slept.
1402 * The given page must be unlocked and object containing it must
1406 vm_page_sleep_if_xbusy(vm_page_t m, const char *wmesg)
1410 vm_page_lock_assert(m, MA_NOTOWNED);
1411 VM_OBJECT_ASSERT_WLOCKED(m->object);
1414 * The page-specific object must be cached because page
1415 * identity can change during the sleep, causing the
1416 * re-lock of a different object.
1417 * It is assumed that a reference to the object is already
1418 * held by the callers.
1421 if (_vm_page_busy_sleep(obj, m, m->pindex, wmesg, VM_ALLOC_SBUSY,
1423 VM_OBJECT_WLOCK(obj);
1430 * vm_page_dirty_KBI: [ internal use only ]
1432 * Set all bits in the page's dirty field.
1434 * The object containing the specified page must be locked if the
1435 * call is made from the machine-independent layer.
1437 * See vm_page_clear_dirty_mask().
1439 * This function should only be called by vm_page_dirty().
1442 vm_page_dirty_KBI(vm_page_t m)
1445 /* Refer to this operation by its public name. */
1446 KASSERT(vm_page_all_valid(m), ("vm_page_dirty: page is invalid!"));
1447 m->dirty = VM_PAGE_BITS_ALL;
1451 * vm_page_insert: [ internal use only ]
1453 * Inserts the given mem entry into the object and object list.
1455 * The object must be locked.
1458 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1462 VM_OBJECT_ASSERT_WLOCKED(object);
1463 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1464 return (vm_page_insert_after(m, object, pindex, mpred));
1468 * vm_page_insert_after:
1470 * Inserts the page "m" into the specified object at offset "pindex".
1472 * The page "mpred" must immediately precede the offset "pindex" within
1473 * the specified object.
1475 * The object must be locked.
1478 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1483 VM_OBJECT_ASSERT_WLOCKED(object);
1484 KASSERT(m->object == NULL,
1485 ("vm_page_insert_after: page already inserted"));
1486 if (mpred != NULL) {
1487 KASSERT(mpred->object == object,
1488 ("vm_page_insert_after: object doesn't contain mpred"));
1489 KASSERT(mpred->pindex < pindex,
1490 ("vm_page_insert_after: mpred doesn't precede pindex"));
1491 msucc = TAILQ_NEXT(mpred, listq);
1493 msucc = TAILQ_FIRST(&object->memq);
1495 KASSERT(msucc->pindex > pindex,
1496 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1499 * Record the object/offset pair in this page.
1503 m->ref_count |= VPRC_OBJREF;
1506 * Now link into the object's ordered list of backed pages.
1508 if (vm_radix_insert(&object->rtree, m)) {
1511 m->ref_count &= ~VPRC_OBJREF;
1514 vm_page_insert_radixdone(m, object, mpred);
1519 * vm_page_insert_radixdone:
1521 * Complete page "m" insertion into the specified object after the
1522 * radix trie hooking.
1524 * The page "mpred" must precede the offset "m->pindex" within the
1527 * The object must be locked.
1530 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1533 VM_OBJECT_ASSERT_WLOCKED(object);
1534 KASSERT(object != NULL && m->object == object,
1535 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1536 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1537 ("vm_page_insert_radixdone: page %p is missing object ref", m));
1538 if (mpred != NULL) {
1539 KASSERT(mpred->object == object,
1540 ("vm_page_insert_radixdone: object doesn't contain mpred"));
1541 KASSERT(mpred->pindex < m->pindex,
1542 ("vm_page_insert_radixdone: mpred doesn't precede pindex"));
1546 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1548 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1551 * Show that the object has one more resident page.
1553 object->resident_page_count++;
1556 * Hold the vnode until the last page is released.
1558 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1559 vhold(object->handle);
1562 * Since we are inserting a new and possibly dirty page,
1563 * update the object's generation count.
1565 if (pmap_page_is_write_mapped(m))
1566 vm_object_set_writeable_dirty(object);
1570 * Do the work to remove a page from its object. The caller is responsible for
1571 * updating the page's fields to reflect this removal.
1574 vm_page_object_remove(vm_page_t m)
1579 vm_page_assert_xbusied(m);
1581 VM_OBJECT_ASSERT_WLOCKED(object);
1582 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1583 ("page %p is missing its object ref", m));
1585 /* Deferred free of swap space. */
1586 if ((m->a.flags & PGA_SWAP_FREE) != 0)
1587 vm_pager_page_unswapped(m);
1590 mrem = vm_radix_remove(&object->rtree, m->pindex);
1591 KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1594 * Now remove from the object's list of backed pages.
1596 TAILQ_REMOVE(&object->memq, m, listq);
1599 * And show that the object has one fewer resident page.
1601 object->resident_page_count--;
1604 * The vnode may now be recycled.
1606 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1607 vdrop(object->handle);
1613 * Removes the specified page from its containing object, but does not
1614 * invalidate any backing storage. Returns true if the object's reference
1615 * was the last reference to the page, and false otherwise.
1617 * The object must be locked and the page must be exclusively busied.
1618 * The exclusive busy will be released on return. If this is not the
1619 * final ref and the caller does not hold a wire reference it may not
1620 * continue to access the page.
1623 vm_page_remove(vm_page_t m)
1627 dropped = vm_page_remove_xbusy(m);
1634 * vm_page_remove_xbusy
1636 * Removes the page but leaves the xbusy held. Returns true if this
1637 * removed the final ref and false otherwise.
1640 vm_page_remove_xbusy(vm_page_t m)
1643 vm_page_object_remove(m);
1644 return (vm_page_drop(m, VPRC_OBJREF) == VPRC_OBJREF);
1650 * Returns the page associated with the object/offset
1651 * pair specified; if none is found, NULL is returned.
1653 * The object must be locked.
1656 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1659 VM_OBJECT_ASSERT_LOCKED(object);
1660 return (vm_radix_lookup(&object->rtree, pindex));
1666 * Returns a page that must already have been busied by
1667 * the caller. Used for bogus page replacement.
1670 vm_page_relookup(vm_object_t object, vm_pindex_t pindex)
1674 m = vm_radix_lookup_unlocked(&object->rtree, pindex);
1675 KASSERT(m != NULL && (vm_page_busied(m) || vm_page_wired(m)) &&
1676 m->object == object && m->pindex == pindex,
1677 ("vm_page_relookup: Invalid page %p", m));
1682 * This should only be used by lockless functions for releasing transient
1683 * incorrect acquires. The page may have been freed after we acquired a
1684 * busy lock. In this case busy_lock == VPB_FREED and we have nothing
1688 vm_page_busy_release(vm_page_t m)
1692 x = atomic_load_int(&m->busy_lock);
1696 if ((x & VPB_BIT_SHARED) != 0 && VPB_SHARERS(x) > 1) {
1697 if (atomic_fcmpset_int(&m->busy_lock, &x,
1698 x - VPB_ONE_SHARER))
1702 KASSERT((x & VPB_BIT_SHARED) != 0 ||
1703 (x & ~VPB_BIT_WAITERS) == VPB_CURTHREAD_EXCLUSIVE,
1704 ("vm_page_busy_release: %p xbusy not owned.", m));
1705 if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
1707 if ((x & VPB_BIT_WAITERS) != 0)
1714 * vm_page_find_least:
1716 * Returns the page associated with the object with least pindex
1717 * greater than or equal to the parameter pindex, or NULL.
1719 * The object must be locked.
1722 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1726 VM_OBJECT_ASSERT_LOCKED(object);
1727 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1728 m = vm_radix_lookup_ge(&object->rtree, pindex);
1733 * Returns the given page's successor (by pindex) within the object if it is
1734 * resident; if none is found, NULL is returned.
1736 * The object must be locked.
1739 vm_page_next(vm_page_t m)
1743 VM_OBJECT_ASSERT_LOCKED(m->object);
1744 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1745 MPASS(next->object == m->object);
1746 if (next->pindex != m->pindex + 1)
1753 * Returns the given page's predecessor (by pindex) within the object if it is
1754 * resident; if none is found, NULL is returned.
1756 * The object must be locked.
1759 vm_page_prev(vm_page_t m)
1763 VM_OBJECT_ASSERT_LOCKED(m->object);
1764 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1765 MPASS(prev->object == m->object);
1766 if (prev->pindex != m->pindex - 1)
1773 * Uses the page mnew as a replacement for an existing page at index
1774 * pindex which must be already present in the object.
1776 * Both pages must be exclusively busied on enter. The old page is
1779 * A return value of true means mold is now free. If this is not the
1780 * final ref and the caller does not hold a wire reference it may not
1781 * continue to access the page.
1784 vm_page_replace_hold(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1790 VM_OBJECT_ASSERT_WLOCKED(object);
1791 vm_page_assert_xbusied(mold);
1792 KASSERT(mnew->object == NULL && (mnew->ref_count & VPRC_OBJREF) == 0,
1793 ("vm_page_replace: page %p already in object", mnew));
1796 * This function mostly follows vm_page_insert() and
1797 * vm_page_remove() without the radix, object count and vnode
1798 * dance. Double check such functions for more comments.
1801 mnew->object = object;
1802 mnew->pindex = pindex;
1803 atomic_set_int(&mnew->ref_count, VPRC_OBJREF);
1804 mret = vm_radix_replace(&object->rtree, mnew);
1805 KASSERT(mret == mold,
1806 ("invalid page replacement, mold=%p, mret=%p", mold, mret));
1807 KASSERT((mold->oflags & VPO_UNMANAGED) ==
1808 (mnew->oflags & VPO_UNMANAGED),
1809 ("vm_page_replace: mismatched VPO_UNMANAGED"));
1811 /* Keep the resident page list in sorted order. */
1812 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1813 TAILQ_REMOVE(&object->memq, mold, listq);
1814 mold->object = NULL;
1817 * The object's resident_page_count does not change because we have
1818 * swapped one page for another, but the generation count should
1819 * change if the page is dirty.
1821 if (pmap_page_is_write_mapped(mnew))
1822 vm_object_set_writeable_dirty(object);
1823 dropped = vm_page_drop(mold, VPRC_OBJREF) == VPRC_OBJREF;
1824 vm_page_xunbusy(mold);
1830 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1834 vm_page_assert_xbusied(mnew);
1836 if (vm_page_replace_hold(mnew, object, pindex, mold))
1843 * Move the given memory entry from its
1844 * current object to the specified target object/offset.
1846 * Note: swap associated with the page must be invalidated by the move. We
1847 * have to do this for several reasons: (1) we aren't freeing the
1848 * page, (2) we are dirtying the page, (3) the VM system is probably
1849 * moving the page from object A to B, and will then later move
1850 * the backing store from A to B and we can't have a conflict.
1852 * Note: we *always* dirty the page. It is necessary both for the
1853 * fact that we moved it, and because we may be invalidating
1856 * The objects must be locked.
1859 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1864 VM_OBJECT_ASSERT_WLOCKED(new_object);
1866 KASSERT(m->ref_count != 0, ("vm_page_rename: page %p has no refs", m));
1867 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1868 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1869 ("vm_page_rename: pindex already renamed"));
1872 * Create a custom version of vm_page_insert() which does not depend
1873 * by m_prev and can cheat on the implementation aspects of the
1877 m->pindex = new_pindex;
1878 if (vm_radix_insert(&new_object->rtree, m)) {
1884 * The operation cannot fail anymore. The removal must happen before
1885 * the listq iterator is tainted.
1888 vm_page_object_remove(m);
1890 /* Return back to the new pindex to complete vm_page_insert(). */
1891 m->pindex = new_pindex;
1892 m->object = new_object;
1894 vm_page_insert_radixdone(m, new_object, mpred);
1902 * Allocate and return a page that is associated with the specified
1903 * object and offset pair. By default, this page is exclusive busied.
1905 * The caller must always specify an allocation class.
1907 * allocation classes:
1908 * VM_ALLOC_NORMAL normal process request
1909 * VM_ALLOC_SYSTEM system *really* needs a page
1910 * VM_ALLOC_INTERRUPT interrupt time request
1912 * optional allocation flags:
1913 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1914 * intends to allocate
1915 * VM_ALLOC_NOBUSY do not exclusive busy the page
1916 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1917 * VM_ALLOC_NOOBJ page is not associated with an object and
1918 * should not be exclusive busy
1919 * VM_ALLOC_SBUSY shared busy the allocated page
1920 * VM_ALLOC_WIRED wire the allocated page
1921 * VM_ALLOC_ZERO prefer a zeroed page
1924 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1927 return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1928 vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1932 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1936 return (vm_page_alloc_domain_after(object, pindex, domain, req,
1937 object != NULL ? vm_radix_lookup_le(&object->rtree, pindex) :
1942 * Allocate a page in the specified object with the given page index. To
1943 * optimize insertion of the page into the object, the caller must also specifiy
1944 * the resident page in the object with largest index smaller than the given
1945 * page index, or NULL if no such page exists.
1948 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1949 int req, vm_page_t mpred)
1951 struct vm_domainset_iter di;
1955 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1957 m = vm_page_alloc_domain_after(object, pindex, domain, req,
1961 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
1967 * Returns true if the number of free pages exceeds the minimum
1968 * for the request class and false otherwise.
1971 _vm_domain_allocate(struct vm_domain *vmd, int req_class, int npages)
1973 u_int limit, old, new;
1975 if (req_class == VM_ALLOC_INTERRUPT)
1977 else if (req_class == VM_ALLOC_SYSTEM)
1978 limit = vmd->vmd_interrupt_free_min;
1980 limit = vmd->vmd_free_reserved;
1983 * Attempt to reserve the pages. Fail if we're below the limit.
1986 old = vmd->vmd_free_count;
1991 } while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
1993 /* Wake the page daemon if we've crossed the threshold. */
1994 if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
1995 pagedaemon_wakeup(vmd->vmd_domain);
1997 /* Only update bitsets on transitions. */
1998 if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
1999 (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
2006 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
2011 * The page daemon is allowed to dig deeper into the free page list.
2013 req_class = req & VM_ALLOC_CLASS_MASK;
2014 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2015 req_class = VM_ALLOC_SYSTEM;
2016 return (_vm_domain_allocate(vmd, req_class, npages));
2020 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
2021 int req, vm_page_t mpred)
2023 struct vm_domain *vmd;
2027 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
2028 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
2029 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2030 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2031 ("inconsistent object(%p)/req(%x)", object, req));
2032 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2033 ("Can't sleep and retry object insertion."));
2034 KASSERT(mpred == NULL || mpred->pindex < pindex,
2035 ("mpred %p doesn't precede pindex 0x%jx", mpred,
2036 (uintmax_t)pindex));
2038 VM_OBJECT_ASSERT_WLOCKED(object);
2042 pool = object != NULL ? VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT;
2044 #if VM_NRESERVLEVEL > 0
2046 * Can we allocate the page from a reservation?
2048 if (vm_object_reserv(object) &&
2049 (m = vm_reserv_alloc_page(object, pindex, domain, req, mpred)) !=
2051 domain = vm_phys_domain(m);
2052 vmd = VM_DOMAIN(domain);
2056 vmd = VM_DOMAIN(domain);
2057 if (vmd->vmd_pgcache[pool].zone != NULL) {
2058 m = uma_zalloc(vmd->vmd_pgcache[pool].zone, M_NOWAIT | M_NOVM);
2060 flags |= PG_PCPU_CACHE;
2064 if (vm_domain_allocate(vmd, req, 1)) {
2066 * If not, allocate it from the free page queues.
2068 vm_domain_free_lock(vmd);
2069 m = vm_phys_alloc_pages(domain, pool, 0);
2070 vm_domain_free_unlock(vmd);
2072 vm_domain_freecnt_inc(vmd, 1);
2073 #if VM_NRESERVLEVEL > 0
2074 if (vm_reserv_reclaim_inactive(domain))
2081 * Not allocatable, give up.
2083 if (vm_domain_alloc_fail(vmd, object, req))
2089 * At this point we had better have found a good page.
2093 vm_page_alloc_check(m);
2096 * Initialize the page. Only the PG_ZERO flag is inherited.
2098 if ((req & VM_ALLOC_ZERO) != 0)
2099 flags |= (m->flags & PG_ZERO);
2100 if ((req & VM_ALLOC_NODUMP) != 0)
2104 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2106 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2107 m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2108 else if ((req & VM_ALLOC_SBUSY) != 0)
2109 m->busy_lock = VPB_SHARERS_WORD(1);
2111 m->busy_lock = VPB_UNBUSIED;
2112 if (req & VM_ALLOC_WIRED) {
2118 if (object != NULL) {
2119 if (vm_page_insert_after(m, object, pindex, mpred)) {
2120 if (req & VM_ALLOC_WIRED) {
2124 KASSERT(m->object == NULL, ("page %p has object", m));
2125 m->oflags = VPO_UNMANAGED;
2126 m->busy_lock = VPB_UNBUSIED;
2127 /* Don't change PG_ZERO. */
2128 vm_page_free_toq(m);
2129 if (req & VM_ALLOC_WAITFAIL) {
2130 VM_OBJECT_WUNLOCK(object);
2132 VM_OBJECT_WLOCK(object);
2137 /* Ignore device objects; the pager sets "memattr" for them. */
2138 if (object->memattr != VM_MEMATTR_DEFAULT &&
2139 (object->flags & OBJ_FICTITIOUS) == 0)
2140 pmap_page_set_memattr(m, object->memattr);
2148 * vm_page_alloc_contig:
2150 * Allocate a contiguous set of physical pages of the given size "npages"
2151 * from the free lists. All of the physical pages must be at or above
2152 * the given physical address "low" and below the given physical address
2153 * "high". The given value "alignment" determines the alignment of the
2154 * first physical page in the set. If the given value "boundary" is
2155 * non-zero, then the set of physical pages cannot cross any physical
2156 * address boundary that is a multiple of that value. Both "alignment"
2157 * and "boundary" must be a power of two.
2159 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
2160 * then the memory attribute setting for the physical pages is configured
2161 * to the object's memory attribute setting. Otherwise, the memory
2162 * attribute setting for the physical pages is configured to "memattr",
2163 * overriding the object's memory attribute setting. However, if the
2164 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
2165 * memory attribute setting for the physical pages cannot be configured
2166 * to VM_MEMATTR_DEFAULT.
2168 * The specified object may not contain fictitious pages.
2170 * The caller must always specify an allocation class.
2172 * allocation classes:
2173 * VM_ALLOC_NORMAL normal process request
2174 * VM_ALLOC_SYSTEM system *really* needs a page
2175 * VM_ALLOC_INTERRUPT interrupt time request
2177 * optional allocation flags:
2178 * VM_ALLOC_NOBUSY do not exclusive busy the page
2179 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
2180 * VM_ALLOC_NOOBJ page is not associated with an object and
2181 * should not be exclusive busy
2182 * VM_ALLOC_SBUSY shared busy the allocated page
2183 * VM_ALLOC_WIRED wire the allocated page
2184 * VM_ALLOC_ZERO prefer a zeroed page
2187 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
2188 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2189 vm_paddr_t boundary, vm_memattr_t memattr)
2191 struct vm_domainset_iter di;
2195 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
2197 m = vm_page_alloc_contig_domain(object, pindex, domain, req,
2198 npages, low, high, alignment, boundary, memattr);
2201 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
2207 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
2208 int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2209 vm_paddr_t boundary, vm_memattr_t memattr)
2211 struct vm_domain *vmd;
2212 vm_page_t m, m_ret, mpred;
2213 u_int busy_lock, flags, oflags;
2215 mpred = NULL; /* XXX: pacify gcc */
2216 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
2217 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
2218 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2219 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2220 ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
2222 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2223 ("Can't sleep and retry object insertion."));
2224 if (object != NULL) {
2225 VM_OBJECT_ASSERT_WLOCKED(object);
2226 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2227 ("vm_page_alloc_contig: object %p has fictitious pages",
2230 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2232 if (object != NULL) {
2233 mpred = vm_radix_lookup_le(&object->rtree, pindex);
2234 KASSERT(mpred == NULL || mpred->pindex != pindex,
2235 ("vm_page_alloc_contig: pindex already allocated"));
2239 * Can we allocate the pages without the number of free pages falling
2240 * below the lower bound for the allocation class?
2244 #if VM_NRESERVLEVEL > 0
2246 * Can we allocate the pages from a reservation?
2248 if (vm_object_reserv(object) &&
2249 (m_ret = vm_reserv_alloc_contig(object, pindex, domain, req,
2250 mpred, npages, low, high, alignment, boundary)) != NULL) {
2251 domain = vm_phys_domain(m_ret);
2252 vmd = VM_DOMAIN(domain);
2256 vmd = VM_DOMAIN(domain);
2257 if (vm_domain_allocate(vmd, req, npages)) {
2259 * allocate them from the free page queues.
2261 vm_domain_free_lock(vmd);
2262 m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2263 alignment, boundary);
2264 vm_domain_free_unlock(vmd);
2265 if (m_ret == NULL) {
2266 vm_domain_freecnt_inc(vmd, npages);
2267 #if VM_NRESERVLEVEL > 0
2268 if (vm_reserv_reclaim_contig(domain, npages, low,
2269 high, alignment, boundary))
2274 if (m_ret == NULL) {
2275 if (vm_domain_alloc_fail(vmd, object, req))
2279 #if VM_NRESERVLEVEL > 0
2282 for (m = m_ret; m < &m_ret[npages]; m++) {
2284 vm_page_alloc_check(m);
2288 * Initialize the pages. Only the PG_ZERO flag is inherited.
2291 if ((req & VM_ALLOC_ZERO) != 0)
2293 if ((req & VM_ALLOC_NODUMP) != 0)
2295 oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2297 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2298 busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2299 else if ((req & VM_ALLOC_SBUSY) != 0)
2300 busy_lock = VPB_SHARERS_WORD(1);
2302 busy_lock = VPB_UNBUSIED;
2303 if ((req & VM_ALLOC_WIRED) != 0)
2304 vm_wire_add(npages);
2305 if (object != NULL) {
2306 if (object->memattr != VM_MEMATTR_DEFAULT &&
2307 memattr == VM_MEMATTR_DEFAULT)
2308 memattr = object->memattr;
2310 for (m = m_ret; m < &m_ret[npages]; m++) {
2312 m->flags = (m->flags | PG_NODUMP) & flags;
2313 m->busy_lock = busy_lock;
2314 if ((req & VM_ALLOC_WIRED) != 0)
2318 if (object != NULL) {
2319 if (vm_page_insert_after(m, object, pindex, mpred)) {
2320 if ((req & VM_ALLOC_WIRED) != 0)
2321 vm_wire_sub(npages);
2322 KASSERT(m->object == NULL,
2323 ("page %p has object", m));
2325 for (m = m_ret; m < &m_ret[npages]; m++) {
2327 (req & VM_ALLOC_WIRED) != 0)
2329 m->oflags = VPO_UNMANAGED;
2330 m->busy_lock = VPB_UNBUSIED;
2331 /* Don't change PG_ZERO. */
2332 vm_page_free_toq(m);
2334 if (req & VM_ALLOC_WAITFAIL) {
2335 VM_OBJECT_WUNLOCK(object);
2337 VM_OBJECT_WLOCK(object);
2344 if (memattr != VM_MEMATTR_DEFAULT)
2345 pmap_page_set_memattr(m, memattr);
2352 * Check a page that has been freshly dequeued from a freelist.
2355 vm_page_alloc_check(vm_page_t m)
2358 KASSERT(m->object == NULL, ("page %p has object", m));
2359 KASSERT(m->a.queue == PQ_NONE &&
2360 (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
2361 ("page %p has unexpected queue %d, flags %#x",
2362 m, m->a.queue, (m->a.flags & PGA_QUEUE_STATE_MASK)));
2363 KASSERT(m->ref_count == 0, ("page %p has references", m));
2364 KASSERT(vm_page_busy_freed(m), ("page %p is not freed", m));
2365 KASSERT(m->dirty == 0, ("page %p is dirty", m));
2366 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2367 ("page %p has unexpected memattr %d",
2368 m, pmap_page_get_memattr(m)));
2369 KASSERT(m->valid == 0, ("free page %p is valid", m));
2373 * vm_page_alloc_freelist:
2375 * Allocate a physical page from the specified free page list.
2377 * The caller must always specify an allocation class.
2379 * allocation classes:
2380 * VM_ALLOC_NORMAL normal process request
2381 * VM_ALLOC_SYSTEM system *really* needs a page
2382 * VM_ALLOC_INTERRUPT interrupt time request
2384 * optional allocation flags:
2385 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2386 * intends to allocate
2387 * VM_ALLOC_WIRED wire the allocated page
2388 * VM_ALLOC_ZERO prefer a zeroed page
2391 vm_page_alloc_freelist(int freelist, int req)
2393 struct vm_domainset_iter di;
2397 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2399 m = vm_page_alloc_freelist_domain(domain, freelist, req);
2402 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2408 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2410 struct vm_domain *vmd;
2415 vmd = VM_DOMAIN(domain);
2417 if (vm_domain_allocate(vmd, req, 1)) {
2418 vm_domain_free_lock(vmd);
2419 m = vm_phys_alloc_freelist_pages(domain, freelist,
2420 VM_FREEPOOL_DIRECT, 0);
2421 vm_domain_free_unlock(vmd);
2423 vm_domain_freecnt_inc(vmd, 1);
2426 if (vm_domain_alloc_fail(vmd, NULL, req))
2431 vm_page_alloc_check(m);
2434 * Initialize the page. Only the PG_ZERO flag is inherited.
2438 if ((req & VM_ALLOC_ZERO) != 0)
2441 if ((req & VM_ALLOC_WIRED) != 0) {
2445 /* Unmanaged pages don't use "act_count". */
2446 m->oflags = VPO_UNMANAGED;
2451 vm_page_zone_import(void *arg, void **store, int cnt, int domain, int flags)
2453 struct vm_domain *vmd;
2454 struct vm_pgcache *pgcache;
2458 vmd = VM_DOMAIN(pgcache->domain);
2461 * The page daemon should avoid creating extra memory pressure since its
2462 * main purpose is to replenish the store of free pages.
2464 if (vmd->vmd_severeset || curproc == pageproc ||
2465 !_vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2467 domain = vmd->vmd_domain;
2468 vm_domain_free_lock(vmd);
2469 i = vm_phys_alloc_npages(domain, pgcache->pool, cnt,
2470 (vm_page_t *)store);
2471 vm_domain_free_unlock(vmd);
2473 vm_domain_freecnt_inc(vmd, cnt - i);
2479 vm_page_zone_release(void *arg, void **store, int cnt)
2481 struct vm_domain *vmd;
2482 struct vm_pgcache *pgcache;
2487 vmd = VM_DOMAIN(pgcache->domain);
2488 vm_domain_free_lock(vmd);
2489 for (i = 0; i < cnt; i++) {
2490 m = (vm_page_t)store[i];
2491 vm_phys_free_pages(m, 0);
2493 vm_domain_free_unlock(vmd);
2494 vm_domain_freecnt_inc(vmd, cnt);
2497 #define VPSC_ANY 0 /* No restrictions. */
2498 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2499 #define VPSC_NOSUPER 2 /* Skip superpages. */
2502 * vm_page_scan_contig:
2504 * Scan vm_page_array[] between the specified entries "m_start" and
2505 * "m_end" for a run of contiguous physical pages that satisfy the
2506 * specified conditions, and return the lowest page in the run. The
2507 * specified "alignment" determines the alignment of the lowest physical
2508 * page in the run. If the specified "boundary" is non-zero, then the
2509 * run of physical pages cannot span a physical address that is a
2510 * multiple of "boundary".
2512 * "m_end" is never dereferenced, so it need not point to a vm_page
2513 * structure within vm_page_array[].
2515 * "npages" must be greater than zero. "m_start" and "m_end" must not
2516 * span a hole (or discontiguity) in the physical address space. Both
2517 * "alignment" and "boundary" must be a power of two.
2520 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2521 u_long alignment, vm_paddr_t boundary, int options)
2526 #if VM_NRESERVLEVEL > 0
2529 int m_inc, order, run_ext, run_len;
2531 KASSERT(npages > 0, ("npages is 0"));
2532 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2533 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2536 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2537 KASSERT((m->flags & PG_MARKER) == 0,
2538 ("page %p is PG_MARKER", m));
2539 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->ref_count >= 1,
2540 ("fictitious page %p has invalid ref count", m));
2543 * If the current page would be the start of a run, check its
2544 * physical address against the end, alignment, and boundary
2545 * conditions. If it doesn't satisfy these conditions, either
2546 * terminate the scan or advance to the next page that
2547 * satisfies the failed condition.
2550 KASSERT(m_run == NULL, ("m_run != NULL"));
2551 if (m + npages > m_end)
2553 pa = VM_PAGE_TO_PHYS(m);
2554 if ((pa & (alignment - 1)) != 0) {
2555 m_inc = atop(roundup2(pa, alignment) - pa);
2558 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2560 m_inc = atop(roundup2(pa, boundary) - pa);
2564 KASSERT(m_run != NULL, ("m_run == NULL"));
2568 if (vm_page_wired(m))
2570 #if VM_NRESERVLEVEL > 0
2571 else if ((level = vm_reserv_level(m)) >= 0 &&
2572 (options & VPSC_NORESERV) != 0) {
2574 /* Advance to the end of the reservation. */
2575 pa = VM_PAGE_TO_PHYS(m);
2576 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2580 else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2582 * The page is considered eligible for relocation if
2583 * and only if it could be laundered or reclaimed by
2586 VM_OBJECT_RLOCK(object);
2587 if (object != m->object) {
2588 VM_OBJECT_RUNLOCK(object);
2591 /* Don't care: PG_NODUMP, PG_ZERO. */
2592 if (object->type != OBJT_DEFAULT &&
2593 object->type != OBJT_SWAP &&
2594 object->type != OBJT_VNODE) {
2596 #if VM_NRESERVLEVEL > 0
2597 } else if ((options & VPSC_NOSUPER) != 0 &&
2598 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2600 /* Advance to the end of the superpage. */
2601 pa = VM_PAGE_TO_PHYS(m);
2602 m_inc = atop(roundup2(pa + 1,
2603 vm_reserv_size(level)) - pa);
2605 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2606 vm_page_queue(m) != PQ_NONE && !vm_page_busied(m)) {
2608 * The page is allocated but eligible for
2609 * relocation. Extend the current run by one
2612 KASSERT(pmap_page_get_memattr(m) ==
2614 ("page %p has an unexpected memattr", m));
2615 KASSERT((m->oflags & (VPO_SWAPINPROG |
2616 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2617 ("page %p has unexpected oflags", m));
2618 /* Don't care: PGA_NOSYNC. */
2622 VM_OBJECT_RUNLOCK(object);
2623 #if VM_NRESERVLEVEL > 0
2624 } else if (level >= 0) {
2626 * The page is reserved but not yet allocated. In
2627 * other words, it is still free. Extend the current
2632 } else if ((order = m->order) < VM_NFREEORDER) {
2634 * The page is enqueued in the physical memory
2635 * allocator's free page queues. Moreover, it is the
2636 * first page in a power-of-two-sized run of
2637 * contiguous free pages. Add these pages to the end
2638 * of the current run, and jump ahead.
2640 run_ext = 1 << order;
2644 * Skip the page for one of the following reasons: (1)
2645 * It is enqueued in the physical memory allocator's
2646 * free page queues. However, it is not the first
2647 * page in a run of contiguous free pages. (This case
2648 * rarely occurs because the scan is performed in
2649 * ascending order.) (2) It is not reserved, and it is
2650 * transitioning from free to allocated. (Conversely,
2651 * the transition from allocated to free for managed
2652 * pages is blocked by the page lock.) (3) It is
2653 * allocated but not contained by an object and not
2654 * wired, e.g., allocated by Xen's balloon driver.
2660 * Extend or reset the current run of pages.
2673 if (run_len >= npages)
2679 * vm_page_reclaim_run:
2681 * Try to relocate each of the allocated virtual pages within the
2682 * specified run of physical pages to a new physical address. Free the
2683 * physical pages underlying the relocated virtual pages. A virtual page
2684 * is relocatable if and only if it could be laundered or reclaimed by
2685 * the page daemon. Whenever possible, a virtual page is relocated to a
2686 * physical address above "high".
2688 * Returns 0 if every physical page within the run was already free or
2689 * just freed by a successful relocation. Otherwise, returns a non-zero
2690 * value indicating why the last attempt to relocate a virtual page was
2693 * "req_class" must be an allocation class.
2696 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2699 struct vm_domain *vmd;
2700 struct spglist free;
2703 vm_page_t m, m_end, m_new;
2704 int error, order, req;
2706 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2707 ("req_class is not an allocation class"));
2711 m_end = m_run + npages;
2712 for (; error == 0 && m < m_end; m++) {
2713 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2714 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2717 * Racily check for wirings. Races are handled once the object
2718 * lock is held and the page is unmapped.
2720 if (vm_page_wired(m))
2722 else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2724 * The page is relocated if and only if it could be
2725 * laundered or reclaimed by the page daemon.
2727 VM_OBJECT_WLOCK(object);
2728 /* Don't care: PG_NODUMP, PG_ZERO. */
2729 if (m->object != object ||
2730 (object->type != OBJT_DEFAULT &&
2731 object->type != OBJT_SWAP &&
2732 object->type != OBJT_VNODE))
2734 else if (object->memattr != VM_MEMATTR_DEFAULT)
2736 else if (vm_page_queue(m) != PQ_NONE &&
2737 vm_page_tryxbusy(m) != 0) {
2738 if (vm_page_wired(m)) {
2743 KASSERT(pmap_page_get_memattr(m) ==
2745 ("page %p has an unexpected memattr", m));
2746 KASSERT(m->oflags == 0,
2747 ("page %p has unexpected oflags", m));
2748 /* Don't care: PGA_NOSYNC. */
2749 if (!vm_page_none_valid(m)) {
2751 * First, try to allocate a new page
2752 * that is above "high". Failing
2753 * that, try to allocate a new page
2754 * that is below "m_run". Allocate
2755 * the new page between the end of
2756 * "m_run" and "high" only as a last
2759 req = req_class | VM_ALLOC_NOOBJ;
2760 if ((m->flags & PG_NODUMP) != 0)
2761 req |= VM_ALLOC_NODUMP;
2762 if (trunc_page(high) !=
2763 ~(vm_paddr_t)PAGE_MASK) {
2764 m_new = vm_page_alloc_contig(
2769 VM_MEMATTR_DEFAULT);
2772 if (m_new == NULL) {
2773 pa = VM_PAGE_TO_PHYS(m_run);
2774 m_new = vm_page_alloc_contig(
2776 0, pa - 1, PAGE_SIZE, 0,
2777 VM_MEMATTR_DEFAULT);
2779 if (m_new == NULL) {
2781 m_new = vm_page_alloc_contig(
2783 pa, high, PAGE_SIZE, 0,
2784 VM_MEMATTR_DEFAULT);
2786 if (m_new == NULL) {
2793 * Unmap the page and check for new
2794 * wirings that may have been acquired
2795 * through a pmap lookup.
2797 if (object->ref_count != 0 &&
2798 !vm_page_try_remove_all(m)) {
2800 vm_page_free(m_new);
2806 * Replace "m" with the new page. For
2807 * vm_page_replace(), "m" must be busy
2808 * and dequeued. Finally, change "m"
2809 * as if vm_page_free() was called.
2811 m_new->a.flags = m->a.flags &
2812 ~PGA_QUEUE_STATE_MASK;
2813 KASSERT(m_new->oflags == VPO_UNMANAGED,
2814 ("page %p is managed", m_new));
2816 pmap_copy_page(m, m_new);
2817 m_new->valid = m->valid;
2818 m_new->dirty = m->dirty;
2819 m->flags &= ~PG_ZERO;
2821 if (vm_page_replace_hold(m_new, object,
2823 vm_page_free_prep(m))
2824 SLIST_INSERT_HEAD(&free, m,
2828 * The new page must be deactivated
2829 * before the object is unlocked.
2831 vm_page_deactivate(m_new);
2833 m->flags &= ~PG_ZERO;
2835 if (vm_page_free_prep(m))
2836 SLIST_INSERT_HEAD(&free, m,
2838 KASSERT(m->dirty == 0,
2839 ("page %p is dirty", m));
2844 VM_OBJECT_WUNLOCK(object);
2846 MPASS(vm_phys_domain(m) == domain);
2847 vmd = VM_DOMAIN(domain);
2848 vm_domain_free_lock(vmd);
2850 if (order < VM_NFREEORDER) {
2852 * The page is enqueued in the physical memory
2853 * allocator's free page queues. Moreover, it
2854 * is the first page in a power-of-two-sized
2855 * run of contiguous free pages. Jump ahead
2856 * to the last page within that run, and
2857 * continue from there.
2859 m += (1 << order) - 1;
2861 #if VM_NRESERVLEVEL > 0
2862 else if (vm_reserv_is_page_free(m))
2865 vm_domain_free_unlock(vmd);
2866 if (order == VM_NFREEORDER)
2870 if ((m = SLIST_FIRST(&free)) != NULL) {
2873 vmd = VM_DOMAIN(domain);
2875 vm_domain_free_lock(vmd);
2877 MPASS(vm_phys_domain(m) == domain);
2878 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2879 vm_phys_free_pages(m, 0);
2881 } while ((m = SLIST_FIRST(&free)) != NULL);
2882 vm_domain_free_unlock(vmd);
2883 vm_domain_freecnt_inc(vmd, cnt);
2890 CTASSERT(powerof2(NRUNS));
2892 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2894 #define MIN_RECLAIM 8
2897 * vm_page_reclaim_contig:
2899 * Reclaim allocated, contiguous physical memory satisfying the specified
2900 * conditions by relocating the virtual pages using that physical memory.
2901 * Returns true if reclamation is successful and false otherwise. Since
2902 * relocation requires the allocation of physical pages, reclamation may
2903 * fail due to a shortage of free pages. When reclamation fails, callers
2904 * are expected to perform vm_wait() before retrying a failed allocation
2905 * operation, e.g., vm_page_alloc_contig().
2907 * The caller must always specify an allocation class through "req".
2909 * allocation classes:
2910 * VM_ALLOC_NORMAL normal process request
2911 * VM_ALLOC_SYSTEM system *really* needs a page
2912 * VM_ALLOC_INTERRUPT interrupt time request
2914 * The optional allocation flags are ignored.
2916 * "npages" must be greater than zero. Both "alignment" and "boundary"
2917 * must be a power of two.
2920 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
2921 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2923 struct vm_domain *vmd;
2924 vm_paddr_t curr_low;
2925 vm_page_t m_run, m_runs[NRUNS];
2926 u_long count, reclaimed;
2927 int error, i, options, req_class;
2929 KASSERT(npages > 0, ("npages is 0"));
2930 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2931 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2932 req_class = req & VM_ALLOC_CLASS_MASK;
2935 * The page daemon is allowed to dig deeper into the free page list.
2937 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2938 req_class = VM_ALLOC_SYSTEM;
2941 * Return if the number of free pages cannot satisfy the requested
2944 vmd = VM_DOMAIN(domain);
2945 count = vmd->vmd_free_count;
2946 if (count < npages + vmd->vmd_free_reserved || (count < npages +
2947 vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2948 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2952 * Scan up to three times, relaxing the restrictions ("options") on
2953 * the reclamation of reservations and superpages each time.
2955 for (options = VPSC_NORESERV;;) {
2957 * Find the highest runs that satisfy the given constraints
2958 * and restrictions, and record them in "m_runs".
2963 m_run = vm_phys_scan_contig(domain, npages, curr_low,
2964 high, alignment, boundary, options);
2967 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2968 m_runs[RUN_INDEX(count)] = m_run;
2973 * Reclaim the highest runs in LIFO (descending) order until
2974 * the number of reclaimed pages, "reclaimed", is at least
2975 * MIN_RECLAIM. Reset "reclaimed" each time because each
2976 * reclamation is idempotent, and runs will (likely) recur
2977 * from one scan to the next as restrictions are relaxed.
2980 for (i = 0; count > 0 && i < NRUNS; i++) {
2982 m_run = m_runs[RUN_INDEX(count)];
2983 error = vm_page_reclaim_run(req_class, domain, npages,
2986 reclaimed += npages;
2987 if (reclaimed >= MIN_RECLAIM)
2993 * Either relax the restrictions on the next scan or return if
2994 * the last scan had no restrictions.
2996 if (options == VPSC_NORESERV)
2997 options = VPSC_NOSUPER;
2998 else if (options == VPSC_NOSUPER)
3000 else if (options == VPSC_ANY)
3001 return (reclaimed != 0);
3006 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
3007 u_long alignment, vm_paddr_t boundary)
3009 struct vm_domainset_iter di;
3013 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
3015 ret = vm_page_reclaim_contig_domain(domain, req, npages, low,
3016 high, alignment, boundary);
3019 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
3025 * Set the domain in the appropriate page level domainset.
3028 vm_domain_set(struct vm_domain *vmd)
3031 mtx_lock(&vm_domainset_lock);
3032 if (!vmd->vmd_minset && vm_paging_min(vmd)) {
3033 vmd->vmd_minset = 1;
3034 DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
3036 if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
3037 vmd->vmd_severeset = 1;
3038 DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
3040 mtx_unlock(&vm_domainset_lock);
3044 * Clear the domain from the appropriate page level domainset.
3047 vm_domain_clear(struct vm_domain *vmd)
3050 mtx_lock(&vm_domainset_lock);
3051 if (vmd->vmd_minset && !vm_paging_min(vmd)) {
3052 vmd->vmd_minset = 0;
3053 DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
3054 if (vm_min_waiters != 0) {
3056 wakeup(&vm_min_domains);
3059 if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
3060 vmd->vmd_severeset = 0;
3061 DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
3062 if (vm_severe_waiters != 0) {
3063 vm_severe_waiters = 0;
3064 wakeup(&vm_severe_domains);
3069 * If pageout daemon needs pages, then tell it that there are
3072 if (vmd->vmd_pageout_pages_needed &&
3073 vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
3074 wakeup(&vmd->vmd_pageout_pages_needed);
3075 vmd->vmd_pageout_pages_needed = 0;
3078 /* See comments in vm_wait_doms(). */
3079 if (vm_pageproc_waiters) {
3080 vm_pageproc_waiters = 0;
3081 wakeup(&vm_pageproc_waiters);
3083 mtx_unlock(&vm_domainset_lock);
3087 * Wait for free pages to exceed the min threshold globally.
3093 mtx_lock(&vm_domainset_lock);
3094 while (vm_page_count_min()) {
3096 msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
3098 mtx_unlock(&vm_domainset_lock);
3102 * Wait for free pages to exceed the severe threshold globally.
3105 vm_wait_severe(void)
3108 mtx_lock(&vm_domainset_lock);
3109 while (vm_page_count_severe()) {
3110 vm_severe_waiters++;
3111 msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
3114 mtx_unlock(&vm_domainset_lock);
3121 return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
3125 vm_wait_doms(const domainset_t *wdoms)
3129 * We use racey wakeup synchronization to avoid expensive global
3130 * locking for the pageproc when sleeping with a non-specific vm_wait.
3131 * To handle this, we only sleep for one tick in this instance. It
3132 * is expected that most allocations for the pageproc will come from
3133 * kmem or vm_page_grab* which will use the more specific and
3134 * race-free vm_wait_domain().
3136 if (curproc == pageproc) {
3137 mtx_lock(&vm_domainset_lock);
3138 vm_pageproc_waiters++;
3139 msleep(&vm_pageproc_waiters, &vm_domainset_lock, PVM | PDROP,
3143 * XXX Ideally we would wait only until the allocation could
3144 * be satisfied. This condition can cause new allocators to
3145 * consume all freed pages while old allocators wait.
3147 mtx_lock(&vm_domainset_lock);
3148 if (vm_page_count_min_set(wdoms)) {
3150 msleep(&vm_min_domains, &vm_domainset_lock,
3151 PVM | PDROP, "vmwait", 0);
3153 mtx_unlock(&vm_domainset_lock);
3160 * Sleep until free pages are available for allocation.
3161 * - Called in various places after failed memory allocations.
3164 vm_wait_domain(int domain)
3166 struct vm_domain *vmd;
3169 vmd = VM_DOMAIN(domain);
3170 vm_domain_free_assert_unlocked(vmd);
3172 if (curproc == pageproc) {
3173 mtx_lock(&vm_domainset_lock);
3174 if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
3175 vmd->vmd_pageout_pages_needed = 1;
3176 msleep(&vmd->vmd_pageout_pages_needed,
3177 &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
3179 mtx_unlock(&vm_domainset_lock);
3181 if (pageproc == NULL)
3182 panic("vm_wait in early boot");
3183 DOMAINSET_ZERO(&wdom);
3184 DOMAINSET_SET(vmd->vmd_domain, &wdom);
3185 vm_wait_doms(&wdom);
3192 * Sleep until free pages are available for allocation in the
3193 * affinity domains of the obj. If obj is NULL, the domain set
3194 * for the calling thread is used.
3195 * Called in various places after failed memory allocations.
3198 vm_wait(vm_object_t obj)
3200 struct domainset *d;
3205 * Carefully fetch pointers only once: the struct domainset
3206 * itself is ummutable but the pointer might change.
3209 d = obj->domain.dr_policy;
3211 d = curthread->td_domain.dr_policy;
3213 vm_wait_doms(&d->ds_mask);
3217 * vm_domain_alloc_fail:
3219 * Called when a page allocation function fails. Informs the
3220 * pagedaemon and performs the requested wait. Requires the
3221 * domain_free and object lock on entry. Returns with the
3222 * object lock held and free lock released. Returns an error when
3223 * retry is necessary.
3227 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3230 vm_domain_free_assert_unlocked(vmd);
3232 atomic_add_int(&vmd->vmd_pageout_deficit,
3233 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3234 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3236 VM_OBJECT_WUNLOCK(object);
3237 vm_wait_domain(vmd->vmd_domain);
3239 VM_OBJECT_WLOCK(object);
3240 if (req & VM_ALLOC_WAITOK)
3250 * Sleep until free pages are available for allocation.
3251 * - Called only in vm_fault so that processes page faulting
3252 * can be easily tracked.
3253 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3254 * processes will be able to grab memory first. Do not change
3255 * this balance without careful testing first.
3258 vm_waitpfault(struct domainset *dset, int timo)
3262 * XXX Ideally we would wait only until the allocation could
3263 * be satisfied. This condition can cause new allocators to
3264 * consume all freed pages while old allocators wait.
3266 mtx_lock(&vm_domainset_lock);
3267 if (vm_page_count_min_set(&dset->ds_mask)) {
3269 msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3272 mtx_unlock(&vm_domainset_lock);
3275 static struct vm_pagequeue *
3276 _vm_page_pagequeue(vm_page_t m, uint8_t queue)
3279 return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue]);
3283 static struct vm_pagequeue *
3284 vm_page_pagequeue(vm_page_t m)
3287 return (_vm_page_pagequeue(m, vm_page_astate_load(m).queue));
3291 static __always_inline bool
3292 vm_page_pqstate_fcmpset(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3294 vm_page_astate_t tmp;
3298 if (__predict_true(vm_page_astate_fcmpset(m, old, new)))
3300 counter_u64_add(pqstate_commit_retries, 1);
3301 } while (old->_bits == tmp._bits);
3307 * Do the work of committing a queue state update that moves the page out of
3308 * its current queue.
3311 _vm_page_pqstate_commit_dequeue(struct vm_pagequeue *pq, vm_page_t m,
3312 vm_page_astate_t *old, vm_page_astate_t new)
3316 vm_pagequeue_assert_locked(pq);
3317 KASSERT(vm_page_pagequeue(m) == pq,
3318 ("%s: queue %p does not match page %p", __func__, pq, m));
3319 KASSERT(old->queue != PQ_NONE && new.queue != old->queue,
3320 ("%s: invalid queue indices %d %d",
3321 __func__, old->queue, new.queue));
3324 * Once the queue index of the page changes there is nothing
3325 * synchronizing with further updates to the page's physical
3326 * queue state. Therefore we must speculatively remove the page
3327 * from the queue now and be prepared to roll back if the queue
3328 * state update fails. If the page is not physically enqueued then
3329 * we just update its queue index.
3331 if ((old->flags & PGA_ENQUEUED) != 0) {
3332 new.flags &= ~PGA_ENQUEUED;
3333 next = TAILQ_NEXT(m, plinks.q);
3334 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3335 vm_pagequeue_cnt_dec(pq);
3336 if (!vm_page_pqstate_fcmpset(m, old, new)) {
3338 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3340 TAILQ_INSERT_BEFORE(next, m, plinks.q);
3341 vm_pagequeue_cnt_inc(pq);
3347 return (vm_page_pqstate_fcmpset(m, old, new));
3352 vm_page_pqstate_commit_dequeue(vm_page_t m, vm_page_astate_t *old,
3353 vm_page_astate_t new)
3355 struct vm_pagequeue *pq;
3356 vm_page_astate_t as;
3359 pq = _vm_page_pagequeue(m, old->queue);
3362 * The queue field and PGA_ENQUEUED flag are stable only so long as the
3363 * corresponding page queue lock is held.
3365 vm_pagequeue_lock(pq);
3366 as = vm_page_astate_load(m);
3367 if (__predict_false(as._bits != old->_bits)) {
3371 ret = _vm_page_pqstate_commit_dequeue(pq, m, old, new);
3373 vm_pagequeue_unlock(pq);
3378 * Commit a queue state update that enqueues or requeues a page.
3381 _vm_page_pqstate_commit_requeue(struct vm_pagequeue *pq, vm_page_t m,
3382 vm_page_astate_t *old, vm_page_astate_t new)
3384 struct vm_domain *vmd;
3386 vm_pagequeue_assert_locked(pq);
3387 KASSERT(old->queue != PQ_NONE && new.queue == old->queue,
3388 ("%s: invalid queue indices %d %d",
3389 __func__, old->queue, new.queue));
3391 new.flags |= PGA_ENQUEUED;
3392 if (!vm_page_pqstate_fcmpset(m, old, new))
3395 if ((old->flags & PGA_ENQUEUED) != 0)
3396 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3398 vm_pagequeue_cnt_inc(pq);
3401 * Give PGA_REQUEUE_HEAD precedence over PGA_REQUEUE. In particular, if
3402 * both flags are set in close succession, only PGA_REQUEUE_HEAD will be
3403 * applied, even if it was set first.
3405 if ((old->flags & PGA_REQUEUE_HEAD) != 0) {
3406 vmd = vm_pagequeue_domain(m);
3407 KASSERT(pq == &vmd->vmd_pagequeues[PQ_INACTIVE],
3408 ("%s: invalid page queue for page %p", __func__, m));
3409 TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3411 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3417 * Commit a queue state update that encodes a request for a deferred queue
3421 vm_page_pqstate_commit_request(vm_page_t m, vm_page_astate_t *old,
3422 vm_page_astate_t new)
3425 KASSERT(old->queue == new.queue || new.queue != PQ_NONE,
3426 ("%s: invalid state, queue %d flags %x",
3427 __func__, new.queue, new.flags));
3429 if (old->_bits != new._bits &&
3430 !vm_page_pqstate_fcmpset(m, old, new))
3432 vm_page_pqbatch_submit(m, new.queue);
3437 * A generic queue state update function. This handles more cases than the
3438 * specialized functions above.
3441 vm_page_pqstate_commit(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3444 if (old->_bits == new._bits)
3447 if (old->queue != PQ_NONE && new.queue != old->queue) {
3448 if (!vm_page_pqstate_commit_dequeue(m, old, new))
3450 if (new.queue != PQ_NONE)
3451 vm_page_pqbatch_submit(m, new.queue);
3453 if (!vm_page_pqstate_fcmpset(m, old, new))
3455 if (new.queue != PQ_NONE &&
3456 ((new.flags & ~old->flags) & PGA_QUEUE_OP_MASK) != 0)
3457 vm_page_pqbatch_submit(m, new.queue);
3463 * Apply deferred queue state updates to a page.
3466 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m, uint8_t queue)
3468 vm_page_astate_t new, old;
3470 CRITICAL_ASSERT(curthread);
3471 vm_pagequeue_assert_locked(pq);
3472 KASSERT(queue < PQ_COUNT,
3473 ("%s: invalid queue index %d", __func__, queue));
3474 KASSERT(pq == _vm_page_pagequeue(m, queue),
3475 ("%s: page %p does not belong to queue %p", __func__, m, pq));
3477 for (old = vm_page_astate_load(m);;) {
3478 if (__predict_false(old.queue != queue ||
3479 (old.flags & PGA_QUEUE_OP_MASK) == 0)) {
3480 counter_u64_add(queue_nops, 1);
3483 KASSERT(old.queue != PQ_NONE || (old.flags & PGA_QUEUE_STATE_MASK) == 0,
3484 ("%s: page %p has unexpected queue state", __func__, m));
3487 if ((old.flags & PGA_DEQUEUE) != 0) {
3488 new.flags &= ~PGA_QUEUE_OP_MASK;
3489 new.queue = PQ_NONE;
3490 if (__predict_true(_vm_page_pqstate_commit_dequeue(pq,
3492 counter_u64_add(queue_ops, 1);
3496 new.flags &= ~(PGA_REQUEUE | PGA_REQUEUE_HEAD);
3497 if (__predict_true(_vm_page_pqstate_commit_requeue(pq,
3499 counter_u64_add(queue_ops, 1);
3507 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3512 for (i = 0; i < bq->bq_cnt; i++)
3513 vm_pqbatch_process_page(pq, bq->bq_pa[i], queue);
3514 vm_batchqueue_init(bq);
3518 * vm_page_pqbatch_submit: [ internal use only ]
3520 * Enqueue a page in the specified page queue's batched work queue.
3521 * The caller must have encoded the requested operation in the page
3522 * structure's a.flags field.
3525 vm_page_pqbatch_submit(vm_page_t m, uint8_t queue)
3527 struct vm_batchqueue *bq;
3528 struct vm_pagequeue *pq;
3531 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3532 ("page %p is unmanaged", m));
3533 KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3535 domain = vm_phys_domain(m);
3536 pq = &vm_pagequeue_domain(m)->vmd_pagequeues[queue];
3539 bq = DPCPU_PTR(pqbatch[domain][queue]);
3540 if (vm_batchqueue_insert(bq, m)) {
3545 vm_pagequeue_lock(pq);
3547 bq = DPCPU_PTR(pqbatch[domain][queue]);
3548 vm_pqbatch_process(pq, bq, queue);
3549 vm_pqbatch_process_page(pq, m, queue);
3550 vm_pagequeue_unlock(pq);
3555 * vm_page_pqbatch_drain: [ internal use only ]
3557 * Force all per-CPU page queue batch queues to be drained. This is
3558 * intended for use in severe memory shortages, to ensure that pages
3559 * do not remain stuck in the batch queues.
3562 vm_page_pqbatch_drain(void)
3565 struct vm_domain *vmd;
3566 struct vm_pagequeue *pq;
3567 int cpu, domain, queue;
3572 sched_bind(td, cpu);
3575 for (domain = 0; domain < vm_ndomains; domain++) {
3576 vmd = VM_DOMAIN(domain);
3577 for (queue = 0; queue < PQ_COUNT; queue++) {
3578 pq = &vmd->vmd_pagequeues[queue];
3579 vm_pagequeue_lock(pq);
3581 vm_pqbatch_process(pq,
3582 DPCPU_PTR(pqbatch[domain][queue]), queue);
3584 vm_pagequeue_unlock(pq);
3594 * vm_page_dequeue_deferred: [ internal use only ]
3596 * Request removal of the given page from its current page
3597 * queue. Physical removal from the queue may be deferred
3600 * The page must be locked.
3603 vm_page_dequeue_deferred(vm_page_t m)
3605 vm_page_astate_t new, old;
3607 old = vm_page_astate_load(m);
3609 if (old.queue == PQ_NONE) {
3610 KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3611 ("%s: page %p has unexpected queue state",
3616 new.flags |= PGA_DEQUEUE;
3617 } while (!vm_page_pqstate_commit_request(m, &old, new));
3623 * Remove the page from whichever page queue it's in, if any, before
3627 vm_page_dequeue(vm_page_t m)
3629 vm_page_astate_t new, old;
3631 old = vm_page_astate_load(m);
3633 if (old.queue == PQ_NONE) {
3634 KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3635 ("%s: page %p has unexpected queue state",
3640 new.flags &= ~PGA_QUEUE_OP_MASK;
3641 new.queue = PQ_NONE;
3642 } while (!vm_page_pqstate_commit_dequeue(m, &old, new));
3647 * Schedule the given page for insertion into the specified page queue.
3648 * Physical insertion of the page may be deferred indefinitely.
3651 vm_page_enqueue(vm_page_t m, uint8_t queue)
3654 KASSERT(m->a.queue == PQ_NONE &&
3655 (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
3656 ("%s: page %p is already enqueued", __func__, m));
3657 KASSERT(m->ref_count > 0,
3658 ("%s: page %p does not carry any references", __func__, m));
3661 if ((m->a.flags & PGA_REQUEUE) == 0)
3662 vm_page_aflag_set(m, PGA_REQUEUE);
3663 vm_page_pqbatch_submit(m, queue);
3667 * vm_page_free_prep:
3669 * Prepares the given page to be put on the free list,
3670 * disassociating it from any VM object. The caller may return
3671 * the page to the free list only if this function returns true.
3673 * The object must be locked. The page must be locked if it is
3677 vm_page_free_prep(vm_page_t m)
3681 * Synchronize with threads that have dropped a reference to this
3684 atomic_thread_fence_acq();
3686 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
3687 if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
3690 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3691 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
3692 KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
3693 m, i, (uintmax_t)*p));
3696 if ((m->oflags & VPO_UNMANAGED) == 0) {
3697 KASSERT(!pmap_page_is_mapped(m),
3698 ("vm_page_free_prep: freeing mapped page %p", m));
3699 KASSERT((m->a.flags & (PGA_EXECUTABLE | PGA_WRITEABLE)) == 0,
3700 ("vm_page_free_prep: mapping flags set in page %p", m));
3702 KASSERT(m->a.queue == PQ_NONE,
3703 ("vm_page_free_prep: unmanaged page %p is queued", m));
3705 VM_CNT_INC(v_tfree);
3707 if (m->object != NULL) {
3708 KASSERT(((m->oflags & VPO_UNMANAGED) != 0) ==
3709 ((m->object->flags & OBJ_UNMANAGED) != 0),
3710 ("vm_page_free_prep: managed flag mismatch for page %p",
3712 vm_page_assert_xbusied(m);
3715 * The object reference can be released without an atomic
3718 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
3719 m->ref_count == VPRC_OBJREF,
3720 ("vm_page_free_prep: page %p has unexpected ref_count %u",
3722 vm_page_object_remove(m);
3723 m->ref_count -= VPRC_OBJREF;
3725 vm_page_assert_unbusied(m);
3727 vm_page_busy_free(m);
3730 * If fictitious remove object association and
3733 if ((m->flags & PG_FICTITIOUS) != 0) {
3734 KASSERT(m->ref_count == 1,
3735 ("fictitious page %p is referenced", m));
3736 KASSERT(m->a.queue == PQ_NONE,
3737 ("fictitious page %p is queued", m));
3742 * Pages need not be dequeued before they are returned to the physical
3743 * memory allocator, but they must at least be marked for a deferred
3746 if ((m->oflags & VPO_UNMANAGED) == 0)
3747 vm_page_dequeue_deferred(m);
3752 if (m->ref_count != 0)
3753 panic("vm_page_free_prep: page %p has references", m);
3756 * Restore the default memory attribute to the page.
3758 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3759 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3761 #if VM_NRESERVLEVEL > 0
3763 * Determine whether the page belongs to a reservation. If the page was
3764 * allocated from a per-CPU cache, it cannot belong to a reservation, so
3765 * as an optimization, we avoid the check in that case.
3767 if ((m->flags & PG_PCPU_CACHE) == 0 && vm_reserv_free_page(m))
3777 * Returns the given page to the free list, disassociating it
3778 * from any VM object.
3780 * The object must be locked. The page must be locked if it is
3784 vm_page_free_toq(vm_page_t m)
3786 struct vm_domain *vmd;
3789 if (!vm_page_free_prep(m))
3792 vmd = vm_pagequeue_domain(m);
3793 zone = vmd->vmd_pgcache[m->pool].zone;
3794 if ((m->flags & PG_PCPU_CACHE) != 0 && zone != NULL) {
3798 vm_domain_free_lock(vmd);
3799 vm_phys_free_pages(m, 0);
3800 vm_domain_free_unlock(vmd);
3801 vm_domain_freecnt_inc(vmd, 1);
3805 * vm_page_free_pages_toq:
3807 * Returns a list of pages to the free list, disassociating it
3808 * from any VM object. In other words, this is equivalent to
3809 * calling vm_page_free_toq() for each page of a list of VM objects.
3811 * The objects must be locked. The pages must be locked if it is
3815 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
3820 if (SLIST_EMPTY(free))
3824 while ((m = SLIST_FIRST(free)) != NULL) {
3826 SLIST_REMOVE_HEAD(free, plinks.s.ss);
3827 vm_page_free_toq(m);
3830 if (update_wire_count)
3835 * Mark this page as wired down, preventing reclamation by the page daemon
3836 * or when the containing object is destroyed.
3839 vm_page_wire(vm_page_t m)
3843 KASSERT(m->object != NULL,
3844 ("vm_page_wire: page %p does not belong to an object", m));
3845 if (!vm_page_busied(m) && !vm_object_busied(m->object))
3846 VM_OBJECT_ASSERT_LOCKED(m->object);
3847 KASSERT((m->flags & PG_FICTITIOUS) == 0 ||
3848 VPRC_WIRE_COUNT(m->ref_count) >= 1,
3849 ("vm_page_wire: fictitious page %p has zero wirings", m));
3851 old = atomic_fetchadd_int(&m->ref_count, 1);
3852 KASSERT(VPRC_WIRE_COUNT(old) != VPRC_WIRE_COUNT_MAX,
3853 ("vm_page_wire: counter overflow for page %p", m));
3854 if (VPRC_WIRE_COUNT(old) == 0) {
3855 if ((m->oflags & VPO_UNMANAGED) == 0)
3856 vm_page_aflag_set(m, PGA_DEQUEUE);
3862 * Attempt to wire a mapped page following a pmap lookup of that page.
3863 * This may fail if a thread is concurrently tearing down mappings of the page.
3864 * The transient failure is acceptable because it translates to the
3865 * failure of the caller pmap_extract_and_hold(), which should be then
3866 * followed by the vm_fault() fallback, see e.g. vm_fault_quick_hold_pages().
3869 vm_page_wire_mapped(vm_page_t m)
3876 ("vm_page_wire_mapped: wiring unreferenced page %p", m));
3877 if ((old & VPRC_BLOCKED) != 0)
3879 } while (!atomic_fcmpset_int(&m->ref_count, &old, old + 1));
3881 if (VPRC_WIRE_COUNT(old) == 0) {
3882 if ((m->oflags & VPO_UNMANAGED) == 0)
3883 vm_page_aflag_set(m, PGA_DEQUEUE);
3890 * Release a wiring reference to a managed page. If the page still belongs to
3891 * an object, update its position in the page queues to reflect the reference.
3892 * If the wiring was the last reference to the page, free the page.
3895 vm_page_unwire_managed(vm_page_t m, uint8_t nqueue, bool noreuse)
3899 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3900 ("%s: page %p is unmanaged", __func__, m));
3903 * Update LRU state before releasing the wiring reference.
3904 * Use a release store when updating the reference count to
3905 * synchronize with vm_page_free_prep().
3909 KASSERT(VPRC_WIRE_COUNT(old) > 0,
3910 ("vm_page_unwire: wire count underflow for page %p", m));
3912 if (old > VPRC_OBJREF + 1) {
3914 * The page has at least one other wiring reference. An
3915 * earlier iteration of this loop may have called
3916 * vm_page_release_toq() and cleared PGA_DEQUEUE, so
3917 * re-set it if necessary.
3919 if ((vm_page_astate_load(m).flags & PGA_DEQUEUE) == 0)
3920 vm_page_aflag_set(m, PGA_DEQUEUE);
3921 } else if (old == VPRC_OBJREF + 1) {
3923 * This is the last wiring. Clear PGA_DEQUEUE and
3924 * update the page's queue state to reflect the
3925 * reference. If the page does not belong to an object
3926 * (i.e., the VPRC_OBJREF bit is clear), we only need to
3927 * clear leftover queue state.
3929 vm_page_release_toq(m, nqueue, false);
3930 } else if (old == 1) {
3931 vm_page_aflag_clear(m, PGA_DEQUEUE);
3933 } while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
3935 if (VPRC_WIRE_COUNT(old) == 1) {
3943 * Release one wiring of the specified page, potentially allowing it to be
3946 * Only managed pages belonging to an object can be paged out. If the number
3947 * of wirings transitions to zero and the page is eligible for page out, then
3948 * the page is added to the specified paging queue. If the released wiring
3949 * represented the last reference to the page, the page is freed.
3951 * A managed page must be locked.
3954 vm_page_unwire(vm_page_t m, uint8_t nqueue)
3957 KASSERT(nqueue < PQ_COUNT,
3958 ("vm_page_unwire: invalid queue %u request for page %p",
3961 if ((m->oflags & VPO_UNMANAGED) != 0) {
3962 if (vm_page_unwire_noq(m) && m->ref_count == 0)
3966 vm_page_unwire_managed(m, nqueue, false);
3970 * Unwire a page without (re-)inserting it into a page queue. It is up
3971 * to the caller to enqueue, requeue, or free the page as appropriate.
3972 * In most cases involving managed pages, vm_page_unwire() should be used
3976 vm_page_unwire_noq(vm_page_t m)
3980 old = vm_page_drop(m, 1);
3981 KASSERT(VPRC_WIRE_COUNT(old) != 0,
3982 ("vm_page_unref: counter underflow for page %p", m));
3983 KASSERT((m->flags & PG_FICTITIOUS) == 0 || VPRC_WIRE_COUNT(old) > 1,
3984 ("vm_page_unref: missing ref on fictitious page %p", m));
3986 if (VPRC_WIRE_COUNT(old) > 1)
3988 if ((m->oflags & VPO_UNMANAGED) == 0)
3989 vm_page_aflag_clear(m, PGA_DEQUEUE);
3995 * Ensure that the page ends up in the specified page queue. If the page is
3996 * active or being moved to the active queue, ensure that its act_count is
3997 * at least ACT_INIT but do not otherwise mess with it.
3999 * A managed page must be locked.
4001 static __always_inline void
4002 vm_page_mvqueue(vm_page_t m, const uint8_t nqueue, const uint16_t nflag)
4004 vm_page_astate_t old, new;
4006 KASSERT(m->ref_count > 0,
4007 ("%s: page %p does not carry any references", __func__, m));
4008 KASSERT(nflag == PGA_REQUEUE || nflag == PGA_REQUEUE_HEAD,
4009 ("%s: invalid flags %x", __func__, nflag));
4011 if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
4014 old = vm_page_astate_load(m);
4016 if ((old.flags & PGA_DEQUEUE) != 0)
4019 new.flags &= ~PGA_QUEUE_OP_MASK;
4020 if (nqueue == PQ_ACTIVE)
4021 new.act_count = max(old.act_count, ACT_INIT);
4022 if (old.queue == nqueue) {
4023 if (nqueue != PQ_ACTIVE)
4029 } while (!vm_page_pqstate_commit(m, &old, new));
4033 * Put the specified page on the active list (if appropriate).
4036 vm_page_activate(vm_page_t m)
4039 vm_page_mvqueue(m, PQ_ACTIVE, PGA_REQUEUE);
4043 * Move the specified page to the tail of the inactive queue, or requeue
4044 * the page if it is already in the inactive queue.
4047 vm_page_deactivate(vm_page_t m)
4050 vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE);
4054 vm_page_deactivate_noreuse(vm_page_t m)
4057 vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE_HEAD);
4061 * Put a page in the laundry, or requeue it if it is already there.
4064 vm_page_launder(vm_page_t m)
4067 vm_page_mvqueue(m, PQ_LAUNDRY, PGA_REQUEUE);
4071 * Put a page in the PQ_UNSWAPPABLE holding queue.
4074 vm_page_unswappable(vm_page_t m)
4077 KASSERT(!vm_page_wired(m) && (m->oflags & VPO_UNMANAGED) == 0,
4078 ("page %p already unswappable", m));
4081 vm_page_enqueue(m, PQ_UNSWAPPABLE);
4085 * Release a page back to the page queues in preparation for unwiring.
4088 vm_page_release_toq(vm_page_t m, uint8_t nqueue, const bool noreuse)
4090 vm_page_astate_t old, new;
4094 * Use a check of the valid bits to determine whether we should
4095 * accelerate reclamation of the page. The object lock might not be
4096 * held here, in which case the check is racy. At worst we will either
4097 * accelerate reclamation of a valid page and violate LRU, or
4098 * unnecessarily defer reclamation of an invalid page.
4100 * If we were asked to not cache the page, place it near the head of the
4101 * inactive queue so that is reclaimed sooner.
4103 if (noreuse || m->valid == 0) {
4104 nqueue = PQ_INACTIVE;
4105 nflag = PGA_REQUEUE_HEAD;
4107 nflag = PGA_REQUEUE;
4110 old = vm_page_astate_load(m);
4115 * If the page is already in the active queue and we are not
4116 * trying to accelerate reclamation, simply mark it as
4117 * referenced and avoid any queue operations.
4119 new.flags &= ~PGA_QUEUE_OP_MASK;
4120 if (nflag != PGA_REQUEUE_HEAD && old.queue == PQ_ACTIVE)
4121 new.flags |= PGA_REFERENCED;
4126 } while (!vm_page_pqstate_commit(m, &old, new));
4130 * Unwire a page and either attempt to free it or re-add it to the page queues.
4133 vm_page_release(vm_page_t m, int flags)
4137 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4138 ("vm_page_release: page %p is unmanaged", m));
4140 if ((flags & VPR_TRYFREE) != 0) {
4142 object = atomic_load_ptr(&m->object);
4145 /* Depends on type-stability. */
4146 if (vm_page_busied(m) || !VM_OBJECT_TRYWLOCK(object))
4148 if (object == m->object) {
4149 vm_page_release_locked(m, flags);
4150 VM_OBJECT_WUNLOCK(object);
4153 VM_OBJECT_WUNLOCK(object);
4156 vm_page_unwire_managed(m, PQ_INACTIVE, flags != 0);
4159 /* See vm_page_release(). */
4161 vm_page_release_locked(vm_page_t m, int flags)
4164 VM_OBJECT_ASSERT_WLOCKED(m->object);
4165 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4166 ("vm_page_release_locked: page %p is unmanaged", m));
4168 if (vm_page_unwire_noq(m)) {
4169 if ((flags & VPR_TRYFREE) != 0 &&
4170 (m->object->ref_count == 0 || !pmap_page_is_mapped(m)) &&
4171 m->dirty == 0 && vm_page_tryxbusy(m)) {
4174 vm_page_release_toq(m, PQ_INACTIVE, flags != 0);
4180 vm_page_try_blocked_op(vm_page_t m, void (*op)(vm_page_t))
4184 KASSERT(m->object != NULL && (m->oflags & VPO_UNMANAGED) == 0,
4185 ("vm_page_try_blocked_op: page %p has no object", m));
4186 KASSERT(vm_page_busied(m),
4187 ("vm_page_try_blocked_op: page %p is not busy", m));
4188 VM_OBJECT_ASSERT_LOCKED(m->object);
4193 ("vm_page_try_blocked_op: page %p has no references", m));
4194 if (VPRC_WIRE_COUNT(old) != 0)
4196 } while (!atomic_fcmpset_int(&m->ref_count, &old, old | VPRC_BLOCKED));
4201 * If the object is read-locked, new wirings may be created via an
4204 old = vm_page_drop(m, VPRC_BLOCKED);
4205 KASSERT(!VM_OBJECT_WOWNED(m->object) ||
4206 old == (VPRC_BLOCKED | VPRC_OBJREF),
4207 ("vm_page_try_blocked_op: unexpected refcount value %u for %p",
4213 * Atomically check for wirings and remove all mappings of the page.
4216 vm_page_try_remove_all(vm_page_t m)
4219 return (vm_page_try_blocked_op(m, pmap_remove_all));
4223 * Atomically check for wirings and remove all writeable mappings of the page.
4226 vm_page_try_remove_write(vm_page_t m)
4229 return (vm_page_try_blocked_op(m, pmap_remove_write));
4235 * Apply the specified advice to the given page.
4237 * The object and page must be locked.
4240 vm_page_advise(vm_page_t m, int advice)
4243 VM_OBJECT_ASSERT_WLOCKED(m->object);
4244 if (advice == MADV_FREE)
4246 * Mark the page clean. This will allow the page to be freed
4247 * without first paging it out. MADV_FREE pages are often
4248 * quickly reused by malloc(3), so we do not do anything that
4249 * would result in a page fault on a later access.
4252 else if (advice != MADV_DONTNEED) {
4253 if (advice == MADV_WILLNEED)
4254 vm_page_activate(m);
4258 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
4262 * Clear any references to the page. Otherwise, the page daemon will
4263 * immediately reactivate the page.
4265 vm_page_aflag_clear(m, PGA_REFERENCED);
4268 * Place clean pages near the head of the inactive queue rather than
4269 * the tail, thus defeating the queue's LRU operation and ensuring that
4270 * the page will be reused quickly. Dirty pages not already in the
4271 * laundry are moved there.
4274 vm_page_deactivate_noreuse(m);
4275 else if (!vm_page_in_laundry(m))
4280 * vm_page_grab_release
4282 * Helper routine for grab functions to release busy on return.
4285 vm_page_grab_release(vm_page_t m, int allocflags)
4288 if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4289 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4297 * vm_page_grab_sleep
4299 * Sleep for busy according to VM_ALLOC_ parameters. Returns true
4300 * if the caller should retry and false otherwise.
4302 * If the object is locked on entry the object will be unlocked with
4303 * false returns and still locked but possibly having been dropped
4304 * with true returns.
4307 vm_page_grab_sleep(vm_object_t object, vm_page_t m, vm_pindex_t pindex,
4308 const char *wmesg, int allocflags, bool locked)
4311 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4315 * Reference the page before unlocking and sleeping so that
4316 * the page daemon is less likely to reclaim it.
4318 if (locked && (allocflags & VM_ALLOC_NOCREAT) == 0)
4319 vm_page_reference(m);
4321 if (_vm_page_busy_sleep(object, m, m->pindex, wmesg, allocflags,
4323 VM_OBJECT_WLOCK(object);
4324 if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
4331 * Assert that the grab flags are valid.
4334 vm_page_grab_check(int allocflags)
4337 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
4338 (allocflags & VM_ALLOC_WIRED) != 0,
4339 ("vm_page_grab*: the pages must be busied or wired"));
4341 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4342 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4343 ("vm_page_grab*: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4347 * Calculate the page allocation flags for grab.
4350 vm_page_grab_pflags(int allocflags)
4354 pflags = allocflags &
4355 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL |
4357 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4358 pflags |= VM_ALLOC_WAITFAIL;
4359 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4360 pflags |= VM_ALLOC_SBUSY;
4366 * Grab a page, waiting until we are waken up due to the page
4367 * changing state. We keep on waiting, if the page continues
4368 * to be in the object. If the page doesn't exist, first allocate it
4369 * and then conditionally zero it.
4371 * This routine may sleep.
4373 * The object must be locked on entry. The lock will, however, be released
4374 * and reacquired if the routine sleeps.
4377 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
4381 VM_OBJECT_ASSERT_WLOCKED(object);
4382 vm_page_grab_check(allocflags);
4385 if ((m = vm_page_lookup(object, pindex)) != NULL) {
4386 if (!vm_page_tryacquire(m, allocflags)) {
4387 if (vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4394 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4396 m = vm_page_alloc(object, pindex, vm_page_grab_pflags(allocflags));
4398 if ((allocflags & (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL)) != 0)
4402 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
4406 vm_page_grab_release(m, allocflags);
4412 * Locklessly attempt to acquire a page given a (object, pindex) tuple
4413 * and an optional previous page to avoid the radix lookup. The resulting
4414 * page will be validated against the identity tuple and busied or wired
4415 * as requested. A NULL *mp return guarantees that the page was not in
4416 * radix at the time of the call but callers must perform higher level
4417 * synchronization or retry the operation under a lock if they require
4418 * an atomic answer. This is the only lock free validation routine,
4419 * other routines can depend on the resulting page state.
4421 * The return value indicates whether the operation failed due to caller
4422 * flags. The return is tri-state with mp:
4424 * (true, *mp != NULL) - The operation was successful.
4425 * (true, *mp == NULL) - The page was not found in tree.
4426 * (false, *mp == NULL) - WAITFAIL or NOWAIT prevented acquisition.
4429 vm_page_acquire_unlocked(vm_object_t object, vm_pindex_t pindex,
4430 vm_page_t prev, vm_page_t *mp, int allocflags)
4434 vm_page_grab_check(allocflags);
4435 MPASS(prev == NULL || vm_page_busied(prev) || vm_page_wired(prev));
4440 * We may see a false NULL here because the previous page
4441 * has been removed or just inserted and the list is loaded
4442 * without barriers. Switch to radix to verify.
4444 if (prev == NULL || (m = TAILQ_NEXT(prev, listq)) == NULL ||
4445 m->pindex != pindex ||
4446 atomic_load_ptr(&m->object) != object) {
4449 * This guarantees the result is instantaneously
4452 m = vm_radix_lookup_unlocked(&object->rtree, pindex);
4456 if (vm_page_trybusy(m, allocflags)) {
4457 if (m->object == object && m->pindex == pindex)
4460 vm_page_busy_release(m);
4464 if (!vm_page_grab_sleep(object, m, pindex, "pgnslp",
4468 if ((allocflags & VM_ALLOC_WIRED) != 0)
4470 vm_page_grab_release(m, allocflags);
4476 * Try to locklessly grab a page and fall back to the object lock if NOCREAT
4480 vm_page_grab_unlocked(vm_object_t object, vm_pindex_t pindex, int allocflags)
4484 vm_page_grab_check(allocflags);
4486 if (!vm_page_acquire_unlocked(object, pindex, NULL, &m, allocflags))
4492 * The radix lockless lookup should never return a false negative
4493 * errors. If the user specifies NOCREAT they are guaranteed there
4494 * was no page present at the instant of the call. A NOCREAT caller
4495 * must handle create races gracefully.
4497 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4500 VM_OBJECT_WLOCK(object);
4501 m = vm_page_grab(object, pindex, allocflags);
4502 VM_OBJECT_WUNLOCK(object);
4508 * Grab a page and make it valid, paging in if necessary. Pages missing from
4509 * their pager are zero filled and validated. If a VM_ALLOC_COUNT is supplied
4510 * and the page is not valid as many as VM_INITIAL_PAGEIN pages can be brought
4511 * in simultaneously. Additional pages will be left on a paging queue but
4512 * will neither be wired nor busy regardless of allocflags.
4515 vm_page_grab_valid(vm_page_t *mp, vm_object_t object, vm_pindex_t pindex, int allocflags)
4518 vm_page_t ma[VM_INITIAL_PAGEIN];
4519 int after, i, pflags, rv;
4521 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4522 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4523 ("vm_page_grab_valid: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4524 KASSERT((allocflags &
4525 (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4526 ("vm_page_grab_valid: Invalid flags 0x%X", allocflags));
4527 VM_OBJECT_ASSERT_WLOCKED(object);
4528 pflags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY |
4530 pflags |= VM_ALLOC_WAITFAIL;
4533 if ((m = vm_page_lookup(object, pindex)) != NULL) {
4535 * If the page is fully valid it can only become invalid
4536 * with the object lock held. If it is not valid it can
4537 * become valid with the busy lock held. Therefore, we
4538 * may unnecessarily lock the exclusive busy here if we
4539 * race with I/O completion not using the object lock.
4540 * However, we will not end up with an invalid page and a
4543 if (!vm_page_trybusy(m,
4544 vm_page_all_valid(m) ? allocflags : 0)) {
4545 (void)vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4549 if (vm_page_all_valid(m))
4551 if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4552 vm_page_busy_release(m);
4554 return (VM_PAGER_FAIL);
4556 } else if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4558 return (VM_PAGER_FAIL);
4559 } else if ((m = vm_page_alloc(object, pindex, pflags)) == NULL) {
4563 vm_page_assert_xbusied(m);
4564 if (vm_pager_has_page(object, pindex, NULL, &after)) {
4565 after = MIN(after, VM_INITIAL_PAGEIN);
4566 after = MIN(after, allocflags >> VM_ALLOC_COUNT_SHIFT);
4567 after = MAX(after, 1);
4569 for (i = 1; i < after; i++) {
4570 if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
4571 if (ma[i]->valid || !vm_page_tryxbusy(ma[i]))
4574 ma[i] = vm_page_alloc(object, m->pindex + i,
4581 vm_object_pip_add(object, after);
4582 VM_OBJECT_WUNLOCK(object);
4583 rv = vm_pager_get_pages(object, ma, after, NULL, NULL);
4584 VM_OBJECT_WLOCK(object);
4585 vm_object_pip_wakeupn(object, after);
4586 /* Pager may have replaced a page. */
4588 if (rv != VM_PAGER_OK) {
4589 for (i = 0; i < after; i++) {
4590 if (!vm_page_wired(ma[i]))
4591 vm_page_free(ma[i]);
4593 vm_page_xunbusy(ma[i]);
4598 for (i = 1; i < after; i++)
4599 vm_page_readahead_finish(ma[i]);
4600 MPASS(vm_page_all_valid(m));
4602 vm_page_zero_invalid(m, TRUE);
4605 if ((allocflags & VM_ALLOC_WIRED) != 0)
4607 if ((allocflags & VM_ALLOC_SBUSY) != 0 && vm_page_xbusied(m))
4608 vm_page_busy_downgrade(m);
4609 else if ((allocflags & VM_ALLOC_NOBUSY) != 0)
4610 vm_page_busy_release(m);
4612 return (VM_PAGER_OK);
4616 * Locklessly grab a valid page. If the page is not valid or not yet
4617 * allocated this will fall back to the object lock method.
4620 vm_page_grab_valid_unlocked(vm_page_t *mp, vm_object_t object,
4621 vm_pindex_t pindex, int allocflags)
4627 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4628 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4629 ("vm_page_grab_valid_unlocked: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY "
4631 KASSERT((allocflags &
4632 (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4633 ("vm_page_grab_valid_unlocked: Invalid flags 0x%X", allocflags));
4636 * Attempt a lockless lookup and busy. We need at least an sbusy
4637 * before we can inspect the valid field and return a wired page.
4639 flags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
4640 if (!vm_page_acquire_unlocked(object, pindex, NULL, mp, flags))
4641 return (VM_PAGER_FAIL);
4642 if ((m = *mp) != NULL) {
4643 if (vm_page_all_valid(m)) {
4644 if ((allocflags & VM_ALLOC_WIRED) != 0)
4646 vm_page_grab_release(m, allocflags);
4647 return (VM_PAGER_OK);
4649 vm_page_busy_release(m);
4651 if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4653 return (VM_PAGER_FAIL);
4655 VM_OBJECT_WLOCK(object);
4656 error = vm_page_grab_valid(mp, object, pindex, allocflags);
4657 VM_OBJECT_WUNLOCK(object);
4663 * Return the specified range of pages from the given object. For each
4664 * page offset within the range, if a page already exists within the object
4665 * at that offset and it is busy, then wait for it to change state. If,
4666 * instead, the page doesn't exist, then allocate it.
4668 * The caller must always specify an allocation class.
4670 * allocation classes:
4671 * VM_ALLOC_NORMAL normal process request
4672 * VM_ALLOC_SYSTEM system *really* needs the pages
4674 * The caller must always specify that the pages are to be busied and/or
4677 * optional allocation flags:
4678 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
4679 * VM_ALLOC_NOBUSY do not exclusive busy the page
4680 * VM_ALLOC_NOWAIT do not sleep
4681 * VM_ALLOC_SBUSY set page to sbusy state
4682 * VM_ALLOC_WIRED wire the pages
4683 * VM_ALLOC_ZERO zero and validate any invalid pages
4685 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
4686 * may return a partial prefix of the requested range.
4689 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
4690 vm_page_t *ma, int count)
4696 VM_OBJECT_ASSERT_WLOCKED(object);
4697 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
4698 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
4699 vm_page_grab_check(allocflags);
4701 pflags = vm_page_grab_pflags(allocflags);
4707 m = vm_radix_lookup_le(&object->rtree, pindex + i);
4708 if (m == NULL || m->pindex != pindex + i) {
4712 mpred = TAILQ_PREV(m, pglist, listq);
4713 for (; i < count; i++) {
4715 if (!vm_page_tryacquire(m, allocflags)) {
4716 if (vm_page_grab_sleep(object, m, pindex,
4717 "grbmaw", allocflags, true))
4722 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4724 m = vm_page_alloc_after(object, pindex + i,
4725 pflags | VM_ALLOC_COUNT(count - i), mpred);
4727 if ((allocflags & (VM_ALLOC_NOWAIT |
4728 VM_ALLOC_WAITFAIL)) != 0)
4733 if (vm_page_none_valid(m) &&
4734 (allocflags & VM_ALLOC_ZERO) != 0) {
4735 if ((m->flags & PG_ZERO) == 0)
4739 vm_page_grab_release(m, allocflags);
4741 m = vm_page_next(m);
4747 * Unlocked variant of vm_page_grab_pages(). This accepts the same flags
4748 * and will fall back to the locked variant to handle allocation.
4751 vm_page_grab_pages_unlocked(vm_object_t object, vm_pindex_t pindex,
4752 int allocflags, vm_page_t *ma, int count)
4758 vm_page_grab_check(allocflags);
4761 * Modify flags for lockless acquire to hold the page until we
4762 * set it valid if necessary.
4764 flags = allocflags & ~VM_ALLOC_NOBUSY;
4766 for (i = 0; i < count; i++, pindex++) {
4767 if (!vm_page_acquire_unlocked(object, pindex, pred, &m, flags))
4771 if ((flags & VM_ALLOC_ZERO) != 0 && vm_page_none_valid(m)) {
4772 if ((m->flags & PG_ZERO) == 0)
4776 /* m will still be wired or busy according to flags. */
4777 vm_page_grab_release(m, allocflags);
4780 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4783 VM_OBJECT_WLOCK(object);
4784 i += vm_page_grab_pages(object, pindex, allocflags, &ma[i], count);
4785 VM_OBJECT_WUNLOCK(object);
4791 * Mapping function for valid or dirty bits in a page.
4793 * Inputs are required to range within a page.
4796 vm_page_bits(int base, int size)
4802 base + size <= PAGE_SIZE,
4803 ("vm_page_bits: illegal base/size %d/%d", base, size)
4806 if (size == 0) /* handle degenerate case */
4809 first_bit = base >> DEV_BSHIFT;
4810 last_bit = (base + size - 1) >> DEV_BSHIFT;
4812 return (((vm_page_bits_t)2 << last_bit) -
4813 ((vm_page_bits_t)1 << first_bit));
4817 vm_page_bits_set(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t set)
4820 #if PAGE_SIZE == 32768
4821 atomic_set_64((uint64_t *)bits, set);
4822 #elif PAGE_SIZE == 16384
4823 atomic_set_32((uint32_t *)bits, set);
4824 #elif (PAGE_SIZE == 8192) && defined(atomic_set_16)
4825 atomic_set_16((uint16_t *)bits, set);
4826 #elif (PAGE_SIZE == 4096) && defined(atomic_set_8)
4827 atomic_set_8((uint8_t *)bits, set);
4828 #else /* PAGE_SIZE <= 8192 */
4832 addr = (uintptr_t)bits;
4834 * Use a trick to perform a 32-bit atomic on the
4835 * containing aligned word, to not depend on the existence
4836 * of atomic_{set, clear}_{8, 16}.
4838 shift = addr & (sizeof(uint32_t) - 1);
4839 #if BYTE_ORDER == BIG_ENDIAN
4840 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4844 addr &= ~(sizeof(uint32_t) - 1);
4845 atomic_set_32((uint32_t *)addr, set << shift);
4846 #endif /* PAGE_SIZE */
4850 vm_page_bits_clear(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t clear)
4853 #if PAGE_SIZE == 32768
4854 atomic_clear_64((uint64_t *)bits, clear);
4855 #elif PAGE_SIZE == 16384
4856 atomic_clear_32((uint32_t *)bits, clear);
4857 #elif (PAGE_SIZE == 8192) && defined(atomic_clear_16)
4858 atomic_clear_16((uint16_t *)bits, clear);
4859 #elif (PAGE_SIZE == 4096) && defined(atomic_clear_8)
4860 atomic_clear_8((uint8_t *)bits, clear);
4861 #else /* PAGE_SIZE <= 8192 */
4865 addr = (uintptr_t)bits;
4867 * Use a trick to perform a 32-bit atomic on the
4868 * containing aligned word, to not depend on the existence
4869 * of atomic_{set, clear}_{8, 16}.
4871 shift = addr & (sizeof(uint32_t) - 1);
4872 #if BYTE_ORDER == BIG_ENDIAN
4873 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4877 addr &= ~(sizeof(uint32_t) - 1);
4878 atomic_clear_32((uint32_t *)addr, clear << shift);
4879 #endif /* PAGE_SIZE */
4882 static inline vm_page_bits_t
4883 vm_page_bits_swap(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t newbits)
4885 #if PAGE_SIZE == 32768
4889 while (atomic_fcmpset_64(bits, &old, newbits) == 0);
4891 #elif PAGE_SIZE == 16384
4895 while (atomic_fcmpset_32(bits, &old, newbits) == 0);
4897 #elif (PAGE_SIZE == 8192) && defined(atomic_fcmpset_16)
4901 while (atomic_fcmpset_16(bits, &old, newbits) == 0);
4903 #elif (PAGE_SIZE == 4096) && defined(atomic_fcmpset_8)
4907 while (atomic_fcmpset_8(bits, &old, newbits) == 0);
4909 #else /* PAGE_SIZE <= 4096*/
4911 uint32_t old, new, mask;
4914 addr = (uintptr_t)bits;
4916 * Use a trick to perform a 32-bit atomic on the
4917 * containing aligned word, to not depend on the existence
4918 * of atomic_{set, swap, clear}_{8, 16}.
4920 shift = addr & (sizeof(uint32_t) - 1);
4921 #if BYTE_ORDER == BIG_ENDIAN
4922 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4926 addr &= ~(sizeof(uint32_t) - 1);
4927 mask = VM_PAGE_BITS_ALL << shift;
4932 new |= newbits << shift;
4933 } while (atomic_fcmpset_32((uint32_t *)addr, &old, new) == 0);
4934 return (old >> shift);
4935 #endif /* PAGE_SIZE */
4939 * vm_page_set_valid_range:
4941 * Sets portions of a page valid. The arguments are expected
4942 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4943 * of any partial chunks touched by the range. The invalid portion of
4944 * such chunks will be zeroed.
4946 * (base + size) must be less then or equal to PAGE_SIZE.
4949 vm_page_set_valid_range(vm_page_t m, int base, int size)
4952 vm_page_bits_t pagebits;
4954 vm_page_assert_busied(m);
4955 if (size == 0) /* handle degenerate case */
4959 * If the base is not DEV_BSIZE aligned and the valid
4960 * bit is clear, we have to zero out a portion of the
4963 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4964 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
4965 pmap_zero_page_area(m, frag, base - frag);
4968 * If the ending offset is not DEV_BSIZE aligned and the
4969 * valid bit is clear, we have to zero out a portion of
4972 endoff = base + size;
4973 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4974 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
4975 pmap_zero_page_area(m, endoff,
4976 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4979 * Assert that no previously invalid block that is now being validated
4982 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
4983 ("vm_page_set_valid_range: page %p is dirty", m));
4986 * Set valid bits inclusive of any overlap.
4988 pagebits = vm_page_bits(base, size);
4989 if (vm_page_xbusied(m))
4990 m->valid |= pagebits;
4992 vm_page_bits_set(m, &m->valid, pagebits);
4996 * Set the page dirty bits and free the invalid swap space if
4997 * present. Returns the previous dirty bits.
5000 vm_page_set_dirty(vm_page_t m)
5004 VM_PAGE_OBJECT_BUSY_ASSERT(m);
5006 if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m)) {
5008 m->dirty = VM_PAGE_BITS_ALL;
5010 old = vm_page_bits_swap(m, &m->dirty, VM_PAGE_BITS_ALL);
5011 if (old == 0 && (m->a.flags & PGA_SWAP_SPACE) != 0)
5012 vm_pager_page_unswapped(m);
5018 * Clear the given bits from the specified page's dirty field.
5020 static __inline void
5021 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
5024 vm_page_assert_busied(m);
5027 * If the page is xbusied and not write mapped we are the
5028 * only thread that can modify dirty bits. Otherwise, The pmap
5029 * layer can call vm_page_dirty() without holding a distinguished
5030 * lock. The combination of page busy and atomic operations
5031 * suffice to guarantee consistency of the page dirty field.
5033 if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
5034 m->dirty &= ~pagebits;
5036 vm_page_bits_clear(m, &m->dirty, pagebits);
5040 * vm_page_set_validclean:
5042 * Sets portions of a page valid and clean. The arguments are expected
5043 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
5044 * of any partial chunks touched by the range. The invalid portion of
5045 * such chunks will be zero'd.
5047 * (base + size) must be less then or equal to PAGE_SIZE.
5050 vm_page_set_validclean(vm_page_t m, int base, int size)
5052 vm_page_bits_t oldvalid, pagebits;
5055 vm_page_assert_busied(m);
5056 if (size == 0) /* handle degenerate case */
5060 * If the base is not DEV_BSIZE aligned and the valid
5061 * bit is clear, we have to zero out a portion of the
5064 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5065 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
5066 pmap_zero_page_area(m, frag, base - frag);
5069 * If the ending offset is not DEV_BSIZE aligned and the
5070 * valid bit is clear, we have to zero out a portion of
5073 endoff = base + size;
5074 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5075 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
5076 pmap_zero_page_area(m, endoff,
5077 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5080 * Set valid, clear dirty bits. If validating the entire
5081 * page we can safely clear the pmap modify bit. We also
5082 * use this opportunity to clear the PGA_NOSYNC flag. If a process
5083 * takes a write fault on a MAP_NOSYNC memory area the flag will
5086 * We set valid bits inclusive of any overlap, but we can only
5087 * clear dirty bits for DEV_BSIZE chunks that are fully within
5090 oldvalid = m->valid;
5091 pagebits = vm_page_bits(base, size);
5092 if (vm_page_xbusied(m))
5093 m->valid |= pagebits;
5095 vm_page_bits_set(m, &m->valid, pagebits);
5097 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
5098 frag = DEV_BSIZE - frag;
5104 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
5106 if (base == 0 && size == PAGE_SIZE) {
5108 * The page can only be modified within the pmap if it is
5109 * mapped, and it can only be mapped if it was previously
5112 if (oldvalid == VM_PAGE_BITS_ALL)
5114 * Perform the pmap_clear_modify() first. Otherwise,
5115 * a concurrent pmap operation, such as
5116 * pmap_protect(), could clear a modification in the
5117 * pmap and set the dirty field on the page before
5118 * pmap_clear_modify() had begun and after the dirty
5119 * field was cleared here.
5121 pmap_clear_modify(m);
5123 vm_page_aflag_clear(m, PGA_NOSYNC);
5124 } else if (oldvalid != VM_PAGE_BITS_ALL && vm_page_xbusied(m))
5125 m->dirty &= ~pagebits;
5127 vm_page_clear_dirty_mask(m, pagebits);
5131 vm_page_clear_dirty(vm_page_t m, int base, int size)
5134 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
5138 * vm_page_set_invalid:
5140 * Invalidates DEV_BSIZE'd chunks within a page. Both the
5141 * valid and dirty bits for the effected areas are cleared.
5144 vm_page_set_invalid(vm_page_t m, int base, int size)
5146 vm_page_bits_t bits;
5150 * The object lock is required so that pages can't be mapped
5151 * read-only while we're in the process of invalidating them.
5154 VM_OBJECT_ASSERT_WLOCKED(object);
5155 vm_page_assert_busied(m);
5157 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
5158 size >= object->un_pager.vnp.vnp_size)
5159 bits = VM_PAGE_BITS_ALL;
5161 bits = vm_page_bits(base, size);
5162 if (object->ref_count != 0 && vm_page_all_valid(m) && bits != 0)
5164 KASSERT((bits == 0 && vm_page_all_valid(m)) ||
5165 !pmap_page_is_mapped(m),
5166 ("vm_page_set_invalid: page %p is mapped", m));
5167 if (vm_page_xbusied(m)) {
5171 vm_page_bits_clear(m, &m->valid, bits);
5172 vm_page_bits_clear(m, &m->dirty, bits);
5179 * Invalidates the entire page. The page must be busy, unmapped, and
5180 * the enclosing object must be locked. The object locks protects
5181 * against concurrent read-only pmap enter which is done without
5185 vm_page_invalid(vm_page_t m)
5188 vm_page_assert_busied(m);
5189 VM_OBJECT_ASSERT_LOCKED(m->object);
5190 MPASS(!pmap_page_is_mapped(m));
5192 if (vm_page_xbusied(m))
5195 vm_page_bits_clear(m, &m->valid, VM_PAGE_BITS_ALL);
5199 * vm_page_zero_invalid()
5201 * The kernel assumes that the invalid portions of a page contain
5202 * garbage, but such pages can be mapped into memory by user code.
5203 * When this occurs, we must zero out the non-valid portions of the
5204 * page so user code sees what it expects.
5206 * Pages are most often semi-valid when the end of a file is mapped
5207 * into memory and the file's size is not page aligned.
5210 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
5216 * Scan the valid bits looking for invalid sections that
5217 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
5218 * valid bit may be set ) have already been zeroed by
5219 * vm_page_set_validclean().
5221 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
5222 if (i == (PAGE_SIZE / DEV_BSIZE) ||
5223 (m->valid & ((vm_page_bits_t)1 << i))) {
5225 pmap_zero_page_area(m,
5226 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
5233 * setvalid is TRUE when we can safely set the zero'd areas
5234 * as being valid. We can do this if there are no cache consistancy
5235 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
5244 * Is (partial) page valid? Note that the case where size == 0
5245 * will return FALSE in the degenerate case where the page is
5246 * entirely invalid, and TRUE otherwise.
5248 * Some callers envoke this routine without the busy lock held and
5249 * handle races via higher level locks. Typical callers should
5250 * hold a busy lock to prevent invalidation.
5253 vm_page_is_valid(vm_page_t m, int base, int size)
5255 vm_page_bits_t bits;
5257 bits = vm_page_bits(base, size);
5258 return (m->valid != 0 && (m->valid & bits) == bits);
5262 * Returns true if all of the specified predicates are true for the entire
5263 * (super)page and false otherwise.
5266 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
5272 if (skip_m != NULL && skip_m->object != object)
5274 VM_OBJECT_ASSERT_LOCKED(object);
5275 npages = atop(pagesizes[m->psind]);
5278 * The physically contiguous pages that make up a superpage, i.e., a
5279 * page with a page size index ("psind") greater than zero, will
5280 * occupy adjacent entries in vm_page_array[].
5282 for (i = 0; i < npages; i++) {
5283 /* Always test object consistency, including "skip_m". */
5284 if (m[i].object != object)
5286 if (&m[i] == skip_m)
5288 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
5290 if ((flags & PS_ALL_DIRTY) != 0) {
5292 * Calling vm_page_test_dirty() or pmap_is_modified()
5293 * might stop this case from spuriously returning
5294 * "false". However, that would require a write lock
5295 * on the object containing "m[i]".
5297 if (m[i].dirty != VM_PAGE_BITS_ALL)
5300 if ((flags & PS_ALL_VALID) != 0 &&
5301 m[i].valid != VM_PAGE_BITS_ALL)
5308 * Set the page's dirty bits if the page is modified.
5311 vm_page_test_dirty(vm_page_t m)
5314 vm_page_assert_busied(m);
5315 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
5320 vm_page_valid(vm_page_t m)
5323 vm_page_assert_busied(m);
5324 if (vm_page_xbusied(m))
5325 m->valid = VM_PAGE_BITS_ALL;
5327 vm_page_bits_set(m, &m->valid, VM_PAGE_BITS_ALL);
5331 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
5334 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
5338 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
5341 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
5345 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
5348 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
5351 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
5353 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
5356 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
5360 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
5363 mtx_assert_(vm_page_lockptr(m), a, file, line);
5369 vm_page_object_busy_assert(vm_page_t m)
5373 * Certain of the page's fields may only be modified by the
5374 * holder of a page or object busy.
5376 if (m->object != NULL && !vm_page_busied(m))
5377 VM_OBJECT_ASSERT_BUSY(m->object);
5381 vm_page_assert_pga_writeable(vm_page_t m, uint16_t bits)
5384 if ((bits & PGA_WRITEABLE) == 0)
5388 * The PGA_WRITEABLE flag can only be set if the page is
5389 * managed, is exclusively busied or the object is locked.
5390 * Currently, this flag is only set by pmap_enter().
5392 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5393 ("PGA_WRITEABLE on unmanaged page"));
5394 if (!vm_page_xbusied(m))
5395 VM_OBJECT_ASSERT_BUSY(m->object);
5399 #include "opt_ddb.h"
5401 #include <sys/kernel.h>
5403 #include <ddb/ddb.h>
5405 DB_SHOW_COMMAND(page, vm_page_print_page_info)
5408 db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
5409 db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
5410 db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
5411 db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
5412 db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
5413 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
5414 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
5415 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
5416 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
5419 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
5423 db_printf("pq_free %d\n", vm_free_count());
5424 for (dom = 0; dom < vm_ndomains; dom++) {
5426 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
5428 vm_dom[dom].vmd_page_count,
5429 vm_dom[dom].vmd_free_count,
5430 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
5431 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
5432 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
5433 vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
5437 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
5440 boolean_t phys, virt;
5443 db_printf("show pginfo addr\n");
5447 phys = strchr(modif, 'p') != NULL;
5448 virt = strchr(modif, 'v') != NULL;
5450 m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
5452 m = PHYS_TO_VM_PAGE(addr);
5454 m = (vm_page_t)addr;
5456 "page %p obj %p pidx 0x%jx phys 0x%jx q %d ref %u\n"
5457 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
5458 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
5459 m->a.queue, m->ref_count, m->a.flags, m->oflags,
5460 m->flags, m->a.act_count, m->busy_lock, m->valid, m->dirty);