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, 0,
131 "VM page statistics");
133 static counter_u64_t pqstate_commit_retries = EARLY_COUNTER;
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_t queue_ops = EARLY_COUNTER;
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_t queue_nops = EARLY_COUNTER;
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 counter_startup(void)
152 pqstate_commit_retries = counter_u64_alloc(M_WAITOK);
153 queue_ops = counter_u64_alloc(M_WAITOK);
154 queue_nops = counter_u64_alloc(M_WAITOK);
156 SYSINIT(page_counters, SI_SUB_CPU, SI_ORDER_ANY, counter_startup, NULL);
159 * bogus page -- for I/O to/from partially complete buffers,
160 * or for paging into sparsely invalid regions.
162 vm_page_t bogus_page;
164 vm_page_t vm_page_array;
165 long vm_page_array_size;
168 static TAILQ_HEAD(, vm_page) blacklist_head;
169 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
170 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
171 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
173 static uma_zone_t fakepg_zone;
175 static void vm_page_alloc_check(vm_page_t m);
176 static bool _vm_page_busy_sleep(vm_object_t obj, vm_page_t m,
177 const char *wmesg, bool nonshared, bool locked);
178 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
179 static void vm_page_enqueue(vm_page_t m, uint8_t queue);
180 static bool vm_page_free_prep(vm_page_t m);
181 static void vm_page_free_toq(vm_page_t m);
182 static void vm_page_init(void *dummy);
183 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
184 vm_pindex_t pindex, vm_page_t mpred);
185 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
187 static void vm_page_mvqueue(vm_page_t m, const uint8_t queue,
188 const uint16_t nflag);
189 static int vm_page_reclaim_run(int req_class, int domain, u_long npages,
190 vm_page_t m_run, vm_paddr_t high);
191 static void vm_page_release_toq(vm_page_t m, uint8_t nqueue, bool noreuse);
192 static int vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object,
194 static int vm_page_zone_import(void *arg, void **store, int cnt, int domain,
196 static void vm_page_zone_release(void *arg, void **store, int cnt);
198 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
201 vm_page_init(void *dummy)
204 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
205 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
206 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
207 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
211 * The cache page zone is initialized later since we need to be able to allocate
212 * pages before UMA is fully initialized.
215 vm_page_init_cache_zones(void *dummy __unused)
217 struct vm_domain *vmd;
218 struct vm_pgcache *pgcache;
219 int cache, domain, maxcache, pool;
222 TUNABLE_INT_FETCH("vm.pgcache_zone_max_pcpu", &maxcache);
223 maxcache *= mp_ncpus;
224 for (domain = 0; domain < vm_ndomains; domain++) {
225 vmd = VM_DOMAIN(domain);
226 for (pool = 0; pool < VM_NFREEPOOL; pool++) {
227 pgcache = &vmd->vmd_pgcache[pool];
228 pgcache->domain = domain;
229 pgcache->pool = pool;
230 pgcache->zone = uma_zcache_create("vm pgcache",
231 PAGE_SIZE, NULL, NULL, NULL, NULL,
232 vm_page_zone_import, vm_page_zone_release, pgcache,
236 * Limit each pool's zone to 0.1% of the pages in the
239 cache = maxcache != 0 ? maxcache :
240 vmd->vmd_page_count / 1000;
241 uma_zone_set_maxcache(pgcache->zone, cache);
245 SYSINIT(vm_page2, SI_SUB_VM_CONF, SI_ORDER_ANY, vm_page_init_cache_zones, NULL);
247 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
248 #if PAGE_SIZE == 32768
250 CTASSERT(sizeof(u_long) >= 8);
257 * Sets the page size, perhaps based upon the memory
258 * size. Must be called before any use of page-size
259 * dependent functions.
262 vm_set_page_size(void)
264 if (vm_cnt.v_page_size == 0)
265 vm_cnt.v_page_size = PAGE_SIZE;
266 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
267 panic("vm_set_page_size: page size not a power of two");
271 * vm_page_blacklist_next:
273 * Find the next entry in the provided string of blacklist
274 * addresses. Entries are separated by space, comma, or newline.
275 * If an invalid integer is encountered then the rest of the
276 * string is skipped. Updates the list pointer to the next
277 * character, or NULL if the string is exhausted or invalid.
280 vm_page_blacklist_next(char **list, char *end)
285 if (list == NULL || *list == NULL)
293 * If there's no end pointer then the buffer is coming from
294 * the kenv and we know it's null-terminated.
297 end = *list + strlen(*list);
299 /* Ensure that strtoq() won't walk off the end */
301 if (*end == '\n' || *end == ' ' || *end == ',')
304 printf("Blacklist not terminated, skipping\n");
310 for (pos = *list; *pos != '\0'; pos = cp) {
311 bad = strtoq(pos, &cp, 0);
312 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
321 if (*cp == '\0' || ++cp >= end)
325 return (trunc_page(bad));
327 printf("Garbage in RAM blacklist, skipping\n");
333 vm_page_blacklist_add(vm_paddr_t pa, bool verbose)
335 struct vm_domain *vmd;
339 m = vm_phys_paddr_to_vm_page(pa);
341 return (true); /* page does not exist, no failure */
343 vmd = vm_pagequeue_domain(m);
344 vm_domain_free_lock(vmd);
345 ret = vm_phys_unfree_page(m);
346 vm_domain_free_unlock(vmd);
348 vm_domain_freecnt_inc(vmd, -1);
349 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
351 printf("Skipping page with pa 0x%jx\n", (uintmax_t)pa);
357 * vm_page_blacklist_check:
359 * Iterate through the provided string of blacklist addresses, pulling
360 * each entry out of the physical allocator free list and putting it
361 * onto a list for reporting via the vm.page_blacklist sysctl.
364 vm_page_blacklist_check(char *list, char *end)
370 while (next != NULL) {
371 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
373 vm_page_blacklist_add(pa, bootverbose);
378 * vm_page_blacklist_load:
380 * Search for a special module named "ram_blacklist". It'll be a
381 * plain text file provided by the user via the loader directive
385 vm_page_blacklist_load(char **list, char **end)
394 mod = preload_search_by_type("ram_blacklist");
396 ptr = preload_fetch_addr(mod);
397 len = preload_fetch_size(mod);
408 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
415 error = sysctl_wire_old_buffer(req, 0);
418 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
419 TAILQ_FOREACH(m, &blacklist_head, listq) {
420 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
421 (uintmax_t)m->phys_addr);
424 error = sbuf_finish(&sbuf);
430 * Initialize a dummy page for use in scans of the specified paging queue.
431 * In principle, this function only needs to set the flag PG_MARKER.
432 * Nonetheless, it write busies the page as a safety precaution.
435 vm_page_init_marker(vm_page_t marker, int queue, uint16_t aflags)
438 bzero(marker, sizeof(*marker));
439 marker->flags = PG_MARKER;
440 marker->a.flags = aflags;
441 marker->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
442 marker->a.queue = queue;
446 vm_page_domain_init(int domain)
448 struct vm_domain *vmd;
449 struct vm_pagequeue *pq;
452 vmd = VM_DOMAIN(domain);
453 bzero(vmd, sizeof(*vmd));
454 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
455 "vm inactive pagequeue";
456 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
457 "vm active pagequeue";
458 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
459 "vm laundry pagequeue";
460 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_name) =
461 "vm unswappable pagequeue";
462 vmd->vmd_domain = domain;
463 vmd->vmd_page_count = 0;
464 vmd->vmd_free_count = 0;
466 vmd->vmd_oom = FALSE;
467 for (i = 0; i < PQ_COUNT; i++) {
468 pq = &vmd->vmd_pagequeues[i];
469 TAILQ_INIT(&pq->pq_pl);
470 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
471 MTX_DEF | MTX_DUPOK);
473 vm_page_init_marker(&vmd->vmd_markers[i], i, 0);
475 mtx_init(&vmd->vmd_free_mtx, "vm page free queue", NULL, MTX_DEF);
476 mtx_init(&vmd->vmd_pageout_mtx, "vm pageout lock", NULL, MTX_DEF);
477 snprintf(vmd->vmd_name, sizeof(vmd->vmd_name), "%d", domain);
480 * inacthead is used to provide FIFO ordering for LRU-bypassing
483 vm_page_init_marker(&vmd->vmd_inacthead, PQ_INACTIVE, PGA_ENQUEUED);
484 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_INACTIVE].pq_pl,
485 &vmd->vmd_inacthead, plinks.q);
488 * The clock pages are used to implement active queue scanning without
489 * requeues. Scans start at clock[0], which is advanced after the scan
490 * ends. When the two clock hands meet, they are reset and scanning
491 * resumes from the head of the queue.
493 vm_page_init_marker(&vmd->vmd_clock[0], PQ_ACTIVE, PGA_ENQUEUED);
494 vm_page_init_marker(&vmd->vmd_clock[1], PQ_ACTIVE, PGA_ENQUEUED);
495 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
496 &vmd->vmd_clock[0], plinks.q);
497 TAILQ_INSERT_TAIL(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
498 &vmd->vmd_clock[1], plinks.q);
502 * Initialize a physical page in preparation for adding it to the free
506 vm_page_init_page(vm_page_t m, vm_paddr_t pa, int segind)
511 m->busy_lock = VPB_FREED;
512 m->flags = m->a.flags = 0;
514 m->a.queue = PQ_NONE;
517 m->order = VM_NFREEORDER;
518 m->pool = VM_FREEPOOL_DEFAULT;
519 m->valid = m->dirty = 0;
523 #ifndef PMAP_HAS_PAGE_ARRAY
525 vm_page_array_alloc(vm_offset_t *vaddr, vm_paddr_t end, vm_paddr_t page_range)
530 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
531 * However, because this page is allocated from KVM, out-of-bounds
532 * accesses using the direct map will not be trapped.
537 * Allocate physical memory for the page structures, and map it.
539 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
540 vm_page_array = (vm_page_t)pmap_map(vaddr, new_end, end,
541 VM_PROT_READ | VM_PROT_WRITE);
542 vm_page_array_size = page_range;
551 * Initializes the resident memory module. Allocates physical memory for
552 * bootstrapping UMA and some data structures that are used to manage
553 * physical pages. Initializes these structures, and populates the free
557 vm_page_startup(vm_offset_t vaddr)
559 struct vm_phys_seg *seg;
561 char *list, *listend;
562 vm_paddr_t end, high_avail, low_avail, new_end, size;
563 vm_paddr_t page_range __unused;
564 vm_paddr_t last_pa, pa;
566 int biggestone, i, segind;
571 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
575 vaddr = round_page(vaddr);
577 vm_phys_early_startup();
578 biggestone = vm_phys_avail_largest();
579 end = phys_avail[biggestone+1];
582 * Initialize the page and queue locks.
584 mtx_init(&vm_domainset_lock, "vm domainset lock", NULL, MTX_DEF);
585 for (i = 0; i < PA_LOCK_COUNT; i++)
586 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
587 for (i = 0; i < vm_ndomains; i++)
588 vm_page_domain_init(i);
592 witness_size = round_page(witness_startup_count());
593 new_end -= witness_size;
594 mapped = pmap_map(&vaddr, new_end, new_end + witness_size,
595 VM_PROT_READ | VM_PROT_WRITE);
596 bzero((void *)mapped, witness_size);
597 witness_startup((void *)mapped);
600 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
601 defined(__i386__) || defined(__mips__) || defined(__riscv) || \
602 defined(__powerpc64__)
604 * Allocate a bitmap to indicate that a random physical page
605 * needs to be included in a minidump.
607 * The amd64 port needs this to indicate which direct map pages
608 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
610 * However, i386 still needs this workspace internally within the
611 * minidump code. In theory, they are not needed on i386, but are
612 * included should the sf_buf code decide to use them.
615 for (i = 0; dump_avail[i + 1] != 0; i += 2)
616 if (dump_avail[i + 1] > last_pa)
617 last_pa = dump_avail[i + 1];
618 page_range = last_pa / PAGE_SIZE;
619 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
620 new_end -= vm_page_dump_size;
621 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
622 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
623 bzero((void *)vm_page_dump, vm_page_dump_size);
627 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
628 defined(__riscv) || defined(__powerpc64__)
630 * Include the UMA bootstrap pages, witness pages and vm_page_dump
631 * in a crash dump. When pmap_map() uses the direct map, they are
632 * not automatically included.
634 for (pa = new_end; pa < end; pa += PAGE_SIZE)
637 phys_avail[biggestone + 1] = new_end;
640 * Request that the physical pages underlying the message buffer be
641 * included in a crash dump. Since the message buffer is accessed
642 * through the direct map, they are not automatically included.
644 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
645 last_pa = pa + round_page(msgbufsize);
646 while (pa < last_pa) {
652 * Compute the number of pages of memory that will be available for
653 * use, taking into account the overhead of a page structure per page.
654 * In other words, solve
655 * "available physical memory" - round_page(page_range *
656 * sizeof(struct vm_page)) = page_range * PAGE_SIZE
659 low_avail = phys_avail[0];
660 high_avail = phys_avail[1];
661 for (i = 0; i < vm_phys_nsegs; i++) {
662 if (vm_phys_segs[i].start < low_avail)
663 low_avail = vm_phys_segs[i].start;
664 if (vm_phys_segs[i].end > high_avail)
665 high_avail = vm_phys_segs[i].end;
667 /* Skip the first chunk. It is already accounted for. */
668 for (i = 2; phys_avail[i + 1] != 0; i += 2) {
669 if (phys_avail[i] < low_avail)
670 low_avail = phys_avail[i];
671 if (phys_avail[i + 1] > high_avail)
672 high_avail = phys_avail[i + 1];
674 first_page = low_avail / PAGE_SIZE;
675 #ifdef VM_PHYSSEG_SPARSE
677 for (i = 0; i < vm_phys_nsegs; i++)
678 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
679 for (i = 0; phys_avail[i + 1] != 0; i += 2)
680 size += phys_avail[i + 1] - phys_avail[i];
681 #elif defined(VM_PHYSSEG_DENSE)
682 size = high_avail - low_avail;
684 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
687 #ifdef PMAP_HAS_PAGE_ARRAY
688 pmap_page_array_startup(size / PAGE_SIZE);
689 biggestone = vm_phys_avail_largest();
690 end = new_end = phys_avail[biggestone + 1];
692 #ifdef VM_PHYSSEG_DENSE
694 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
695 * the overhead of a page structure per page only if vm_page_array is
696 * allocated from the last physical memory chunk. Otherwise, we must
697 * allocate page structures representing the physical memory
698 * underlying vm_page_array, even though they will not be used.
700 if (new_end != high_avail)
701 page_range = size / PAGE_SIZE;
705 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
708 * If the partial bytes remaining are large enough for
709 * a page (PAGE_SIZE) without a corresponding
710 * 'struct vm_page', then new_end will contain an
711 * extra page after subtracting the length of the VM
712 * page array. Compensate by subtracting an extra
715 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
716 if (new_end == high_avail)
717 high_avail -= PAGE_SIZE;
718 new_end -= PAGE_SIZE;
722 new_end = vm_page_array_alloc(&vaddr, end, page_range);
725 #if VM_NRESERVLEVEL > 0
727 * Allocate physical memory for the reservation management system's
728 * data structures, and map it.
730 new_end = vm_reserv_startup(&vaddr, new_end);
732 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
733 defined(__riscv) || defined(__powerpc64__)
735 * Include vm_page_array and vm_reserv_array in a crash dump.
737 for (pa = new_end; pa < end; pa += PAGE_SIZE)
740 phys_avail[biggestone + 1] = new_end;
743 * Add physical memory segments corresponding to the available
746 for (i = 0; phys_avail[i + 1] != 0; i += 2)
747 if (vm_phys_avail_size(i) != 0)
748 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
751 * Initialize the physical memory allocator.
756 * Initialize the page structures and add every available page to the
757 * physical memory allocator's free lists.
759 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
760 for (ii = 0; ii < vm_page_array_size; ii++) {
761 m = &vm_page_array[ii];
762 vm_page_init_page(m, (first_page + ii) << PAGE_SHIFT, 0);
763 m->flags = PG_FICTITIOUS;
766 vm_cnt.v_page_count = 0;
767 for (segind = 0; segind < vm_phys_nsegs; segind++) {
768 seg = &vm_phys_segs[segind];
769 for (m = seg->first_page, pa = seg->start; pa < seg->end;
770 m++, pa += PAGE_SIZE)
771 vm_page_init_page(m, pa, segind);
774 * Add the segment to the free lists only if it is covered by
775 * one of the ranges in phys_avail. Because we've added the
776 * ranges to the vm_phys_segs array, we can assume that each
777 * segment is either entirely contained in one of the ranges,
778 * or doesn't overlap any of them.
780 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
781 struct vm_domain *vmd;
783 if (seg->start < phys_avail[i] ||
784 seg->end > phys_avail[i + 1])
788 pagecount = (u_long)atop(seg->end - seg->start);
790 vmd = VM_DOMAIN(seg->domain);
791 vm_domain_free_lock(vmd);
792 vm_phys_enqueue_contig(m, pagecount);
793 vm_domain_free_unlock(vmd);
794 vm_domain_freecnt_inc(vmd, pagecount);
795 vm_cnt.v_page_count += (u_int)pagecount;
797 vmd = VM_DOMAIN(seg->domain);
798 vmd->vmd_page_count += (u_int)pagecount;
799 vmd->vmd_segs |= 1UL << m->segind;
805 * Remove blacklisted pages from the physical memory allocator.
807 TAILQ_INIT(&blacklist_head);
808 vm_page_blacklist_load(&list, &listend);
809 vm_page_blacklist_check(list, listend);
811 list = kern_getenv("vm.blacklist");
812 vm_page_blacklist_check(list, NULL);
815 #if VM_NRESERVLEVEL > 0
817 * Initialize the reservation management system.
826 vm_page_reference(vm_page_t m)
829 vm_page_aflag_set(m, PGA_REFERENCED);
833 vm_page_acquire_flags(vm_page_t m, int allocflags)
837 if ((allocflags & (VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY)) != 0)
838 locked = vm_page_trysbusy(m);
840 locked = vm_page_tryxbusy(m);
841 if (locked && (allocflags & VM_ALLOC_WIRED) != 0)
847 * vm_page_busy_sleep_flags
849 * Sleep for busy according to VM_ALLOC_ parameters.
852 vm_page_busy_sleep_flags(vm_object_t object, vm_page_t m, const char *wmesg,
856 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
859 * Reference the page before unlocking and
860 * sleeping so that the page daemon is less
861 * likely to reclaim it.
863 if ((allocflags & VM_ALLOC_NOCREAT) == 0)
864 vm_page_aflag_set(m, PGA_REFERENCED);
865 if (_vm_page_busy_sleep(object, m, wmesg, (allocflags &
866 VM_ALLOC_IGN_SBUSY) != 0, true))
867 VM_OBJECT_WLOCK(object);
868 if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
874 * vm_page_busy_acquire:
876 * Acquire the busy lock as described by VM_ALLOC_* flags. Will loop
877 * and drop the object lock if necessary.
880 vm_page_busy_acquire(vm_page_t m, int allocflags)
886 * The page-specific object must be cached because page
887 * identity can change during the sleep, causing the
888 * re-lock of a different object.
889 * It is assumed that a reference to the object is already
890 * held by the callers.
894 if (vm_page_acquire_flags(m, allocflags))
896 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
899 locked = VM_OBJECT_WOWNED(obj);
902 MPASS(locked || vm_page_wired(m));
903 if (_vm_page_busy_sleep(obj, m, "vmpba",
904 (allocflags & VM_ALLOC_SBUSY) != 0, locked))
905 VM_OBJECT_WLOCK(obj);
906 if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
908 KASSERT(m->object == obj || m->object == NULL,
909 ("vm_page_busy_acquire: page %p does not belong to %p",
915 * vm_page_busy_downgrade:
917 * Downgrade an exclusive busy page into a single shared busy page.
920 vm_page_busy_downgrade(vm_page_t m)
924 vm_page_assert_xbusied(m);
928 if (atomic_fcmpset_rel_int(&m->busy_lock,
929 &x, VPB_SHARERS_WORD(1)))
932 if ((x & VPB_BIT_WAITERS) != 0)
938 * vm_page_busy_tryupgrade:
940 * Attempt to upgrade a single shared busy into an exclusive busy.
943 vm_page_busy_tryupgrade(vm_page_t m)
947 vm_page_assert_sbusied(m);
950 ce = VPB_CURTHREAD_EXCLUSIVE;
952 if (VPB_SHARERS(x) > 1)
954 KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
955 ("vm_page_busy_tryupgrade: invalid lock state"));
956 if (!atomic_fcmpset_acq_int(&m->busy_lock, &x,
957 ce | (x & VPB_BIT_WAITERS)))
966 * Return a positive value if the page is shared busied, 0 otherwise.
969 vm_page_sbusied(vm_page_t m)
974 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
980 * Shared unbusy a page.
983 vm_page_sunbusy(vm_page_t m)
987 vm_page_assert_sbusied(m);
991 KASSERT(x != VPB_FREED,
992 ("vm_page_sunbusy: Unlocking freed page."));
993 if (VPB_SHARERS(x) > 1) {
994 if (atomic_fcmpset_int(&m->busy_lock, &x,
999 KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
1000 ("vm_page_sunbusy: invalid lock state"));
1001 if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
1003 if ((x & VPB_BIT_WAITERS) == 0)
1011 * vm_page_busy_sleep:
1013 * Sleep if the page is busy, using the page pointer as wchan.
1014 * This is used to implement the hard-path of busying mechanism.
1016 * If nonshared is true, sleep only if the page is xbusy.
1018 * The object lock must be held on entry and will be released on exit.
1021 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
1026 VM_OBJECT_ASSERT_LOCKED(obj);
1027 vm_page_lock_assert(m, MA_NOTOWNED);
1029 if (!_vm_page_busy_sleep(obj, m, wmesg, nonshared, true))
1030 VM_OBJECT_DROP(obj);
1034 * _vm_page_busy_sleep:
1036 * Internal busy sleep function.
1039 _vm_page_busy_sleep(vm_object_t obj, vm_page_t m, const char *wmesg,
1040 bool nonshared, bool locked)
1045 * If the object is busy we must wait for that to drain to zero
1046 * before trying the page again.
1048 if (obj != NULL && vm_object_busied(obj)) {
1050 VM_OBJECT_DROP(obj);
1051 vm_object_busy_wait(obj, wmesg);
1056 if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
1057 ((x & VPB_BIT_WAITERS) == 0 &&
1058 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
1063 VM_OBJECT_DROP(obj);
1065 sleepq_add(m, NULL, wmesg, 0, 0);
1066 sleepq_wait(m, PVM);
1074 * Try to shared busy a page.
1075 * If the operation succeeds 1 is returned otherwise 0.
1076 * The operation never sleeps.
1079 vm_page_trysbusy(vm_page_t m)
1087 if ((x & VPB_BIT_SHARED) == 0)
1090 * Reduce the window for transient busies that will trigger
1091 * false negatives in vm_page_ps_test().
1093 if (obj != NULL && vm_object_busied(obj))
1095 if (atomic_fcmpset_acq_int(&m->busy_lock, &x,
1096 x + VPB_ONE_SHARER))
1100 /* Refetch the object now that we're guaranteed that it is stable. */
1102 if (obj != NULL && vm_object_busied(obj)) {
1112 * Try to exclusive busy a page.
1113 * If the operation succeeds 1 is returned otherwise 0.
1114 * The operation never sleeps.
1117 vm_page_tryxbusy(vm_page_t m)
1121 if (atomic_cmpset_acq_int(&(m)->busy_lock, VPB_UNBUSIED,
1122 VPB_CURTHREAD_EXCLUSIVE) == 0)
1126 if (obj != NULL && vm_object_busied(obj)) {
1134 vm_page_xunbusy_hard_tail(vm_page_t m)
1136 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1137 /* Wake the waiter. */
1142 * vm_page_xunbusy_hard:
1144 * Called when unbusy has failed because there is a waiter.
1147 vm_page_xunbusy_hard(vm_page_t m)
1149 vm_page_assert_xbusied(m);
1150 vm_page_xunbusy_hard_tail(m);
1154 vm_page_xunbusy_hard_unchecked(vm_page_t m)
1156 vm_page_assert_xbusied_unchecked(m);
1157 vm_page_xunbusy_hard_tail(m);
1161 vm_page_busy_free(vm_page_t m)
1165 atomic_thread_fence_rel();
1166 x = atomic_swap_int(&m->busy_lock, VPB_FREED);
1167 if ((x & VPB_BIT_WAITERS) != 0)
1172 * vm_page_unhold_pages:
1174 * Unhold each of the pages that is referenced by the given array.
1177 vm_page_unhold_pages(vm_page_t *ma, int count)
1180 for (; count != 0; count--) {
1181 vm_page_unwire(*ma, PQ_ACTIVE);
1187 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1191 #ifdef VM_PHYSSEG_SPARSE
1192 m = vm_phys_paddr_to_vm_page(pa);
1194 m = vm_phys_fictitious_to_vm_page(pa);
1196 #elif defined(VM_PHYSSEG_DENSE)
1200 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1201 m = &vm_page_array[pi - first_page];
1204 return (vm_phys_fictitious_to_vm_page(pa));
1206 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1213 * Create a fictitious page with the specified physical address and
1214 * memory attribute. The memory attribute is the only the machine-
1215 * dependent aspect of a fictitious page that must be initialized.
1218 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1222 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1223 vm_page_initfake(m, paddr, memattr);
1228 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1231 if ((m->flags & PG_FICTITIOUS) != 0) {
1233 * The page's memattr might have changed since the
1234 * previous initialization. Update the pmap to the
1239 m->phys_addr = paddr;
1240 m->a.queue = PQ_NONE;
1241 /* Fictitious pages don't use "segind". */
1242 m->flags = PG_FICTITIOUS;
1243 /* Fictitious pages don't use "order" or "pool". */
1244 m->oflags = VPO_UNMANAGED;
1245 m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
1246 /* Fictitious pages are unevictable. */
1250 pmap_page_set_memattr(m, memattr);
1256 * Release a fictitious page.
1259 vm_page_putfake(vm_page_t m)
1262 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1263 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1264 ("vm_page_putfake: bad page %p", m));
1265 vm_page_assert_xbusied(m);
1266 vm_page_busy_free(m);
1267 uma_zfree(fakepg_zone, m);
1271 * vm_page_updatefake:
1273 * Update the given fictitious page to the specified physical address and
1277 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1280 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1281 ("vm_page_updatefake: bad page %p", m));
1282 m->phys_addr = paddr;
1283 pmap_page_set_memattr(m, memattr);
1292 vm_page_free(vm_page_t m)
1295 m->flags &= ~PG_ZERO;
1296 vm_page_free_toq(m);
1300 * vm_page_free_zero:
1302 * Free a page to the zerod-pages queue
1305 vm_page_free_zero(vm_page_t m)
1308 m->flags |= PG_ZERO;
1309 vm_page_free_toq(m);
1313 * Unbusy and handle the page queueing for a page from a getpages request that
1314 * was optionally read ahead or behind.
1317 vm_page_readahead_finish(vm_page_t m)
1320 /* We shouldn't put invalid pages on queues. */
1321 KASSERT(!vm_page_none_valid(m), ("%s: %p is invalid", __func__, m));
1324 * Since the page is not the actually needed one, whether it should
1325 * be activated or deactivated is not obvious. Empirical results
1326 * have shown that deactivating the page is usually the best choice,
1327 * unless the page is wanted by another thread.
1329 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1330 vm_page_activate(m);
1332 vm_page_deactivate(m);
1333 vm_page_xunbusy_unchecked(m);
1337 * vm_page_sleep_if_busy:
1339 * Sleep and release the object lock if the page is busied.
1340 * Returns TRUE if the thread slept.
1342 * The given page must be unlocked and object containing it must
1346 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1350 vm_page_lock_assert(m, MA_NOTOWNED);
1351 VM_OBJECT_ASSERT_WLOCKED(m->object);
1354 * The page-specific object must be cached because page
1355 * identity can change during the sleep, causing the
1356 * re-lock of a different object.
1357 * It is assumed that a reference to the object is already
1358 * held by the callers.
1361 if (vm_page_busied(m) || (obj != NULL && obj->busy)) {
1362 vm_page_busy_sleep(m, msg, false);
1363 VM_OBJECT_WLOCK(obj);
1370 * vm_page_sleep_if_xbusy:
1372 * Sleep and release the object lock if the page is xbusied.
1373 * Returns TRUE if the thread slept.
1375 * The given page must be unlocked and object containing it must
1379 vm_page_sleep_if_xbusy(vm_page_t m, const char *msg)
1383 vm_page_lock_assert(m, MA_NOTOWNED);
1384 VM_OBJECT_ASSERT_WLOCKED(m->object);
1387 * The page-specific object must be cached because page
1388 * identity can change during the sleep, causing the
1389 * re-lock of a different object.
1390 * It is assumed that a reference to the object is already
1391 * held by the callers.
1394 if (vm_page_xbusied(m) || (obj != NULL && obj->busy)) {
1395 vm_page_busy_sleep(m, msg, true);
1396 VM_OBJECT_WLOCK(obj);
1403 * vm_page_dirty_KBI: [ internal use only ]
1405 * Set all bits in the page's dirty field.
1407 * The object containing the specified page must be locked if the
1408 * call is made from the machine-independent layer.
1410 * See vm_page_clear_dirty_mask().
1412 * This function should only be called by vm_page_dirty().
1415 vm_page_dirty_KBI(vm_page_t m)
1418 /* Refer to this operation by its public name. */
1419 KASSERT(vm_page_all_valid(m), ("vm_page_dirty: page is invalid!"));
1420 m->dirty = VM_PAGE_BITS_ALL;
1424 * vm_page_insert: [ internal use only ]
1426 * Inserts the given mem entry into the object and object list.
1428 * The object must be locked.
1431 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1435 VM_OBJECT_ASSERT_WLOCKED(object);
1436 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1437 return (vm_page_insert_after(m, object, pindex, mpred));
1441 * vm_page_insert_after:
1443 * Inserts the page "m" into the specified object at offset "pindex".
1445 * The page "mpred" must immediately precede the offset "pindex" within
1446 * the specified object.
1448 * The object must be locked.
1451 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1456 VM_OBJECT_ASSERT_WLOCKED(object);
1457 KASSERT(m->object == NULL,
1458 ("vm_page_insert_after: page already inserted"));
1459 if (mpred != NULL) {
1460 KASSERT(mpred->object == object,
1461 ("vm_page_insert_after: object doesn't contain mpred"));
1462 KASSERT(mpred->pindex < pindex,
1463 ("vm_page_insert_after: mpred doesn't precede pindex"));
1464 msucc = TAILQ_NEXT(mpred, listq);
1466 msucc = TAILQ_FIRST(&object->memq);
1468 KASSERT(msucc->pindex > pindex,
1469 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1472 * Record the object/offset pair in this page.
1476 m->ref_count |= VPRC_OBJREF;
1479 * Now link into the object's ordered list of backed pages.
1481 if (vm_radix_insert(&object->rtree, m)) {
1484 m->ref_count &= ~VPRC_OBJREF;
1487 vm_page_insert_radixdone(m, object, mpred);
1492 * vm_page_insert_radixdone:
1494 * Complete page "m" insertion into the specified object after the
1495 * radix trie hooking.
1497 * The page "mpred" must precede the offset "m->pindex" within the
1500 * The object must be locked.
1503 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1506 VM_OBJECT_ASSERT_WLOCKED(object);
1507 KASSERT(object != NULL && m->object == object,
1508 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1509 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1510 ("vm_page_insert_radixdone: page %p is missing object ref", m));
1511 if (mpred != NULL) {
1512 KASSERT(mpred->object == object,
1513 ("vm_page_insert_radixdone: object doesn't contain mpred"));
1514 KASSERT(mpred->pindex < m->pindex,
1515 ("vm_page_insert_radixdone: mpred doesn't precede pindex"));
1519 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1521 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1524 * Show that the object has one more resident page.
1526 object->resident_page_count++;
1529 * Hold the vnode until the last page is released.
1531 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1532 vhold(object->handle);
1535 * Since we are inserting a new and possibly dirty page,
1536 * update the object's generation count.
1538 if (pmap_page_is_write_mapped(m))
1539 vm_object_set_writeable_dirty(object);
1543 * Do the work to remove a page from its object. The caller is responsible for
1544 * updating the page's fields to reflect this removal.
1547 vm_page_object_remove(vm_page_t m)
1552 vm_page_assert_xbusied(m);
1554 VM_OBJECT_ASSERT_WLOCKED(object);
1555 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1556 ("page %p is missing its object ref", m));
1558 /* Deferred free of swap space. */
1559 if ((m->a.flags & PGA_SWAP_FREE) != 0)
1560 vm_pager_page_unswapped(m);
1562 mrem = vm_radix_remove(&object->rtree, m->pindex);
1563 KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1566 * Now remove from the object's list of backed pages.
1568 TAILQ_REMOVE(&object->memq, m, listq);
1571 * And show that the object has one fewer resident page.
1573 object->resident_page_count--;
1576 * The vnode may now be recycled.
1578 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1579 vdrop(object->handle);
1585 * Removes the specified page from its containing object, but does not
1586 * invalidate any backing storage. Returns true if the object's reference
1587 * was the last reference to the page, and false otherwise.
1589 * The object must be locked and the page must be exclusively busied.
1590 * The exclusive busy will be released on return. If this is not the
1591 * final ref and the caller does not hold a wire reference it may not
1592 * continue to access the page.
1595 vm_page_remove(vm_page_t m)
1599 dropped = vm_page_remove_xbusy(m);
1606 * vm_page_remove_xbusy
1608 * Removes the page but leaves the xbusy held. Returns true if this
1609 * removed the final ref and false otherwise.
1612 vm_page_remove_xbusy(vm_page_t m)
1615 vm_page_object_remove(m);
1617 return (vm_page_drop(m, VPRC_OBJREF) == VPRC_OBJREF);
1623 * Returns the page associated with the object/offset
1624 * pair specified; if none is found, NULL is returned.
1626 * The object must be locked.
1629 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1632 VM_OBJECT_ASSERT_LOCKED(object);
1633 return (vm_radix_lookup(&object->rtree, pindex));
1637 * vm_page_find_least:
1639 * Returns the page associated with the object with least pindex
1640 * greater than or equal to the parameter pindex, or NULL.
1642 * The object must be locked.
1645 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1649 VM_OBJECT_ASSERT_LOCKED(object);
1650 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1651 m = vm_radix_lookup_ge(&object->rtree, pindex);
1656 * Returns the given page's successor (by pindex) within the object if it is
1657 * resident; if none is found, NULL is returned.
1659 * The object must be locked.
1662 vm_page_next(vm_page_t m)
1666 VM_OBJECT_ASSERT_LOCKED(m->object);
1667 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1668 MPASS(next->object == m->object);
1669 if (next->pindex != m->pindex + 1)
1676 * Returns the given page's predecessor (by pindex) within the object if it is
1677 * resident; if none is found, NULL is returned.
1679 * The object must be locked.
1682 vm_page_prev(vm_page_t m)
1686 VM_OBJECT_ASSERT_LOCKED(m->object);
1687 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1688 MPASS(prev->object == m->object);
1689 if (prev->pindex != m->pindex - 1)
1696 * Uses the page mnew as a replacement for an existing page at index
1697 * pindex which must be already present in the object.
1699 * Both pages must be exclusively busied on enter. The old page is
1702 * A return value of true means mold is now free. If this is not the
1703 * final ref and the caller does not hold a wire reference it may not
1704 * continue to access the page.
1707 vm_page_replace_hold(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1713 VM_OBJECT_ASSERT_WLOCKED(object);
1714 vm_page_assert_xbusied(mold);
1715 KASSERT(mnew->object == NULL && (mnew->ref_count & VPRC_OBJREF) == 0,
1716 ("vm_page_replace: page %p already in object", mnew));
1719 * This function mostly follows vm_page_insert() and
1720 * vm_page_remove() without the radix, object count and vnode
1721 * dance. Double check such functions for more comments.
1724 mnew->object = object;
1725 mnew->pindex = pindex;
1726 atomic_set_int(&mnew->ref_count, VPRC_OBJREF);
1727 mret = vm_radix_replace(&object->rtree, mnew);
1728 KASSERT(mret == mold,
1729 ("invalid page replacement, mold=%p, mret=%p", mold, mret));
1730 KASSERT((mold->oflags & VPO_UNMANAGED) ==
1731 (mnew->oflags & VPO_UNMANAGED),
1732 ("vm_page_replace: mismatched VPO_UNMANAGED"));
1734 /* Keep the resident page list in sorted order. */
1735 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1736 TAILQ_REMOVE(&object->memq, mold, listq);
1737 mold->object = NULL;
1740 * The object's resident_page_count does not change because we have
1741 * swapped one page for another, but the generation count should
1742 * change if the page is dirty.
1744 if (pmap_page_is_write_mapped(mnew))
1745 vm_object_set_writeable_dirty(object);
1746 dropped = vm_page_drop(mold, VPRC_OBJREF) == VPRC_OBJREF;
1747 vm_page_xunbusy(mold);
1753 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1757 vm_page_assert_xbusied(mnew);
1759 if (vm_page_replace_hold(mnew, object, pindex, mold))
1766 * Move the given memory entry from its
1767 * current object to the specified target object/offset.
1769 * Note: swap associated with the page must be invalidated by the move. We
1770 * have to do this for several reasons: (1) we aren't freeing the
1771 * page, (2) we are dirtying the page, (3) the VM system is probably
1772 * moving the page from object A to B, and will then later move
1773 * the backing store from A to B and we can't have a conflict.
1775 * Note: we *always* dirty the page. It is necessary both for the
1776 * fact that we moved it, and because we may be invalidating
1779 * The objects must be locked.
1782 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1787 VM_OBJECT_ASSERT_WLOCKED(new_object);
1789 KASSERT(m->ref_count != 0, ("vm_page_rename: page %p has no refs", m));
1790 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1791 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1792 ("vm_page_rename: pindex already renamed"));
1795 * Create a custom version of vm_page_insert() which does not depend
1796 * by m_prev and can cheat on the implementation aspects of the
1800 m->pindex = new_pindex;
1801 if (vm_radix_insert(&new_object->rtree, m)) {
1807 * The operation cannot fail anymore. The removal must happen before
1808 * the listq iterator is tainted.
1811 vm_page_object_remove(m);
1813 /* Return back to the new pindex to complete vm_page_insert(). */
1814 m->pindex = new_pindex;
1815 m->object = new_object;
1817 vm_page_insert_radixdone(m, new_object, mpred);
1825 * Allocate and return a page that is associated with the specified
1826 * object and offset pair. By default, this page is exclusive busied.
1828 * The caller must always specify an allocation class.
1830 * allocation classes:
1831 * VM_ALLOC_NORMAL normal process request
1832 * VM_ALLOC_SYSTEM system *really* needs a page
1833 * VM_ALLOC_INTERRUPT interrupt time request
1835 * optional allocation flags:
1836 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1837 * intends to allocate
1838 * VM_ALLOC_NOBUSY do not exclusive busy the page
1839 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1840 * VM_ALLOC_NOOBJ page is not associated with an object and
1841 * should not be exclusive busy
1842 * VM_ALLOC_SBUSY shared busy the allocated page
1843 * VM_ALLOC_WIRED wire the allocated page
1844 * VM_ALLOC_ZERO prefer a zeroed page
1847 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1850 return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1851 vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1855 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1859 return (vm_page_alloc_domain_after(object, pindex, domain, req,
1860 object != NULL ? vm_radix_lookup_le(&object->rtree, pindex) :
1865 * Allocate a page in the specified object with the given page index. To
1866 * optimize insertion of the page into the object, the caller must also specifiy
1867 * the resident page in the object with largest index smaller than the given
1868 * page index, or NULL if no such page exists.
1871 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1872 int req, vm_page_t mpred)
1874 struct vm_domainset_iter di;
1878 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1880 m = vm_page_alloc_domain_after(object, pindex, domain, req,
1884 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
1890 * Returns true if the number of free pages exceeds the minimum
1891 * for the request class and false otherwise.
1894 _vm_domain_allocate(struct vm_domain *vmd, int req_class, int npages)
1896 u_int limit, old, new;
1898 if (req_class == VM_ALLOC_INTERRUPT)
1900 else if (req_class == VM_ALLOC_SYSTEM)
1901 limit = vmd->vmd_interrupt_free_min;
1903 limit = vmd->vmd_free_reserved;
1906 * Attempt to reserve the pages. Fail if we're below the limit.
1909 old = vmd->vmd_free_count;
1914 } while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
1916 /* Wake the page daemon if we've crossed the threshold. */
1917 if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
1918 pagedaemon_wakeup(vmd->vmd_domain);
1920 /* Only update bitsets on transitions. */
1921 if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
1922 (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
1929 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
1934 * The page daemon is allowed to dig deeper into the free page list.
1936 req_class = req & VM_ALLOC_CLASS_MASK;
1937 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1938 req_class = VM_ALLOC_SYSTEM;
1939 return (_vm_domain_allocate(vmd, req_class, npages));
1943 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
1944 int req, vm_page_t mpred)
1946 struct vm_domain *vmd;
1950 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1951 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1952 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1953 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1954 ("inconsistent object(%p)/req(%x)", object, req));
1955 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1956 ("Can't sleep and retry object insertion."));
1957 KASSERT(mpred == NULL || mpred->pindex < pindex,
1958 ("mpred %p doesn't precede pindex 0x%jx", mpred,
1959 (uintmax_t)pindex));
1961 VM_OBJECT_ASSERT_WLOCKED(object);
1965 pool = object != NULL ? VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT;
1967 #if VM_NRESERVLEVEL > 0
1969 * Can we allocate the page from a reservation?
1971 if (vm_object_reserv(object) &&
1972 (m = vm_reserv_alloc_page(object, pindex, domain, req, mpred)) !=
1974 domain = vm_phys_domain(m);
1975 vmd = VM_DOMAIN(domain);
1979 vmd = VM_DOMAIN(domain);
1980 if (vmd->vmd_pgcache[pool].zone != NULL) {
1981 m = uma_zalloc(vmd->vmd_pgcache[pool].zone, M_NOWAIT);
1983 flags |= PG_PCPU_CACHE;
1987 if (vm_domain_allocate(vmd, req, 1)) {
1989 * If not, allocate it from the free page queues.
1991 vm_domain_free_lock(vmd);
1992 m = vm_phys_alloc_pages(domain, pool, 0);
1993 vm_domain_free_unlock(vmd);
1995 vm_domain_freecnt_inc(vmd, 1);
1996 #if VM_NRESERVLEVEL > 0
1997 if (vm_reserv_reclaim_inactive(domain))
2004 * Not allocatable, give up.
2006 if (vm_domain_alloc_fail(vmd, object, req))
2012 * At this point we had better have found a good page.
2016 vm_page_alloc_check(m);
2019 * Initialize the page. Only the PG_ZERO flag is inherited.
2021 if ((req & VM_ALLOC_ZERO) != 0)
2022 flags |= (m->flags & PG_ZERO);
2023 if ((req & VM_ALLOC_NODUMP) != 0)
2027 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2029 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2030 m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2031 else if ((req & VM_ALLOC_SBUSY) != 0)
2032 m->busy_lock = VPB_SHARERS_WORD(1);
2034 m->busy_lock = VPB_UNBUSIED;
2035 if (req & VM_ALLOC_WIRED) {
2041 if (object != NULL) {
2042 if (vm_page_insert_after(m, object, pindex, mpred)) {
2043 if (req & VM_ALLOC_WIRED) {
2047 KASSERT(m->object == NULL, ("page %p has object", m));
2048 m->oflags = VPO_UNMANAGED;
2049 m->busy_lock = VPB_UNBUSIED;
2050 /* Don't change PG_ZERO. */
2051 vm_page_free_toq(m);
2052 if (req & VM_ALLOC_WAITFAIL) {
2053 VM_OBJECT_WUNLOCK(object);
2055 VM_OBJECT_WLOCK(object);
2060 /* Ignore device objects; the pager sets "memattr" for them. */
2061 if (object->memattr != VM_MEMATTR_DEFAULT &&
2062 (object->flags & OBJ_FICTITIOUS) == 0)
2063 pmap_page_set_memattr(m, object->memattr);
2071 * vm_page_alloc_contig:
2073 * Allocate a contiguous set of physical pages of the given size "npages"
2074 * from the free lists. All of the physical pages must be at or above
2075 * the given physical address "low" and below the given physical address
2076 * "high". The given value "alignment" determines the alignment of the
2077 * first physical page in the set. If the given value "boundary" is
2078 * non-zero, then the set of physical pages cannot cross any physical
2079 * address boundary that is a multiple of that value. Both "alignment"
2080 * and "boundary" must be a power of two.
2082 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
2083 * then the memory attribute setting for the physical pages is configured
2084 * to the object's memory attribute setting. Otherwise, the memory
2085 * attribute setting for the physical pages is configured to "memattr",
2086 * overriding the object's memory attribute setting. However, if the
2087 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
2088 * memory attribute setting for the physical pages cannot be configured
2089 * to VM_MEMATTR_DEFAULT.
2091 * The specified object may not contain fictitious pages.
2093 * The caller must always specify an allocation class.
2095 * allocation classes:
2096 * VM_ALLOC_NORMAL normal process request
2097 * VM_ALLOC_SYSTEM system *really* needs a page
2098 * VM_ALLOC_INTERRUPT interrupt time request
2100 * optional allocation flags:
2101 * VM_ALLOC_NOBUSY do not exclusive busy the page
2102 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
2103 * VM_ALLOC_NOOBJ page is not associated with an object and
2104 * should not be exclusive busy
2105 * VM_ALLOC_SBUSY shared busy the allocated page
2106 * VM_ALLOC_WIRED wire the allocated page
2107 * VM_ALLOC_ZERO prefer a zeroed page
2110 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
2111 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2112 vm_paddr_t boundary, vm_memattr_t memattr)
2114 struct vm_domainset_iter di;
2118 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
2120 m = vm_page_alloc_contig_domain(object, pindex, domain, req,
2121 npages, low, high, alignment, boundary, memattr);
2124 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
2130 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
2131 int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2132 vm_paddr_t boundary, vm_memattr_t memattr)
2134 struct vm_domain *vmd;
2135 vm_page_t m, m_ret, mpred;
2136 u_int busy_lock, flags, oflags;
2138 mpred = NULL; /* XXX: pacify gcc */
2139 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
2140 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
2141 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2142 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2143 ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
2145 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2146 ("Can't sleep and retry object insertion."));
2147 if (object != NULL) {
2148 VM_OBJECT_ASSERT_WLOCKED(object);
2149 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2150 ("vm_page_alloc_contig: object %p has fictitious pages",
2153 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2155 if (object != NULL) {
2156 mpred = vm_radix_lookup_le(&object->rtree, pindex);
2157 KASSERT(mpred == NULL || mpred->pindex != pindex,
2158 ("vm_page_alloc_contig: pindex already allocated"));
2162 * Can we allocate the pages without the number of free pages falling
2163 * below the lower bound for the allocation class?
2167 #if VM_NRESERVLEVEL > 0
2169 * Can we allocate the pages from a reservation?
2171 if (vm_object_reserv(object) &&
2172 (m_ret = vm_reserv_alloc_contig(object, pindex, domain, req,
2173 mpred, npages, low, high, alignment, boundary)) != NULL) {
2174 domain = vm_phys_domain(m_ret);
2175 vmd = VM_DOMAIN(domain);
2179 vmd = VM_DOMAIN(domain);
2180 if (vm_domain_allocate(vmd, req, npages)) {
2182 * allocate them from the free page queues.
2184 vm_domain_free_lock(vmd);
2185 m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2186 alignment, boundary);
2187 vm_domain_free_unlock(vmd);
2188 if (m_ret == NULL) {
2189 vm_domain_freecnt_inc(vmd, npages);
2190 #if VM_NRESERVLEVEL > 0
2191 if (vm_reserv_reclaim_contig(domain, npages, low,
2192 high, alignment, boundary))
2197 if (m_ret == NULL) {
2198 if (vm_domain_alloc_fail(vmd, object, req))
2202 #if VM_NRESERVLEVEL > 0
2205 for (m = m_ret; m < &m_ret[npages]; m++) {
2207 vm_page_alloc_check(m);
2211 * Initialize the pages. Only the PG_ZERO flag is inherited.
2214 if ((req & VM_ALLOC_ZERO) != 0)
2216 if ((req & VM_ALLOC_NODUMP) != 0)
2218 oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2220 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2221 busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2222 else if ((req & VM_ALLOC_SBUSY) != 0)
2223 busy_lock = VPB_SHARERS_WORD(1);
2225 busy_lock = VPB_UNBUSIED;
2226 if ((req & VM_ALLOC_WIRED) != 0)
2227 vm_wire_add(npages);
2228 if (object != NULL) {
2229 if (object->memattr != VM_MEMATTR_DEFAULT &&
2230 memattr == VM_MEMATTR_DEFAULT)
2231 memattr = object->memattr;
2233 for (m = m_ret; m < &m_ret[npages]; m++) {
2235 m->flags = (m->flags | PG_NODUMP) & flags;
2236 m->busy_lock = busy_lock;
2237 if ((req & VM_ALLOC_WIRED) != 0)
2241 if (object != NULL) {
2242 if (vm_page_insert_after(m, object, pindex, mpred)) {
2243 if ((req & VM_ALLOC_WIRED) != 0)
2244 vm_wire_sub(npages);
2245 KASSERT(m->object == NULL,
2246 ("page %p has object", m));
2248 for (m = m_ret; m < &m_ret[npages]; m++) {
2250 (req & VM_ALLOC_WIRED) != 0)
2252 m->oflags = VPO_UNMANAGED;
2253 m->busy_lock = VPB_UNBUSIED;
2254 /* Don't change PG_ZERO. */
2255 vm_page_free_toq(m);
2257 if (req & VM_ALLOC_WAITFAIL) {
2258 VM_OBJECT_WUNLOCK(object);
2260 VM_OBJECT_WLOCK(object);
2267 if (memattr != VM_MEMATTR_DEFAULT)
2268 pmap_page_set_memattr(m, memattr);
2275 * Check a page that has been freshly dequeued from a freelist.
2278 vm_page_alloc_check(vm_page_t m)
2281 KASSERT(m->object == NULL, ("page %p has object", m));
2282 KASSERT(m->a.queue == PQ_NONE &&
2283 (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
2284 ("page %p has unexpected queue %d, flags %#x",
2285 m, m->a.queue, (m->a.flags & PGA_QUEUE_STATE_MASK)));
2286 KASSERT(m->ref_count == 0, ("page %p has references", m));
2287 KASSERT(vm_page_busy_freed(m), ("page %p is not freed", m));
2288 KASSERT(m->dirty == 0, ("page %p is dirty", m));
2289 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2290 ("page %p has unexpected memattr %d",
2291 m, pmap_page_get_memattr(m)));
2292 KASSERT(m->valid == 0, ("free page %p is valid", m));
2296 * vm_page_alloc_freelist:
2298 * Allocate a physical page from the specified free page list.
2300 * The caller must always specify an allocation class.
2302 * allocation classes:
2303 * VM_ALLOC_NORMAL normal process request
2304 * VM_ALLOC_SYSTEM system *really* needs a page
2305 * VM_ALLOC_INTERRUPT interrupt time request
2307 * optional allocation flags:
2308 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2309 * intends to allocate
2310 * VM_ALLOC_WIRED wire the allocated page
2311 * VM_ALLOC_ZERO prefer a zeroed page
2314 vm_page_alloc_freelist(int freelist, int req)
2316 struct vm_domainset_iter di;
2320 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2322 m = vm_page_alloc_freelist_domain(domain, freelist, req);
2325 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2331 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2333 struct vm_domain *vmd;
2338 vmd = VM_DOMAIN(domain);
2340 if (vm_domain_allocate(vmd, req, 1)) {
2341 vm_domain_free_lock(vmd);
2342 m = vm_phys_alloc_freelist_pages(domain, freelist,
2343 VM_FREEPOOL_DIRECT, 0);
2344 vm_domain_free_unlock(vmd);
2346 vm_domain_freecnt_inc(vmd, 1);
2349 if (vm_domain_alloc_fail(vmd, NULL, req))
2354 vm_page_alloc_check(m);
2357 * Initialize the page. Only the PG_ZERO flag is inherited.
2361 if ((req & VM_ALLOC_ZERO) != 0)
2364 if ((req & VM_ALLOC_WIRED) != 0) {
2368 /* Unmanaged pages don't use "act_count". */
2369 m->oflags = VPO_UNMANAGED;
2374 vm_page_zone_import(void *arg, void **store, int cnt, int domain, int flags)
2376 struct vm_domain *vmd;
2377 struct vm_pgcache *pgcache;
2381 vmd = VM_DOMAIN(pgcache->domain);
2384 * The page daemon should avoid creating extra memory pressure since its
2385 * main purpose is to replenish the store of free pages.
2387 if (vmd->vmd_severeset || curproc == pageproc ||
2388 !_vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2390 domain = vmd->vmd_domain;
2391 vm_domain_free_lock(vmd);
2392 i = vm_phys_alloc_npages(domain, pgcache->pool, cnt,
2393 (vm_page_t *)store);
2394 vm_domain_free_unlock(vmd);
2396 vm_domain_freecnt_inc(vmd, cnt - i);
2402 vm_page_zone_release(void *arg, void **store, int cnt)
2404 struct vm_domain *vmd;
2405 struct vm_pgcache *pgcache;
2410 vmd = VM_DOMAIN(pgcache->domain);
2411 vm_domain_free_lock(vmd);
2412 for (i = 0; i < cnt; i++) {
2413 m = (vm_page_t)store[i];
2414 vm_phys_free_pages(m, 0);
2416 vm_domain_free_unlock(vmd);
2417 vm_domain_freecnt_inc(vmd, cnt);
2420 #define VPSC_ANY 0 /* No restrictions. */
2421 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2422 #define VPSC_NOSUPER 2 /* Skip superpages. */
2425 * vm_page_scan_contig:
2427 * Scan vm_page_array[] between the specified entries "m_start" and
2428 * "m_end" for a run of contiguous physical pages that satisfy the
2429 * specified conditions, and return the lowest page in the run. The
2430 * specified "alignment" determines the alignment of the lowest physical
2431 * page in the run. If the specified "boundary" is non-zero, then the
2432 * run of physical pages cannot span a physical address that is a
2433 * multiple of "boundary".
2435 * "m_end" is never dereferenced, so it need not point to a vm_page
2436 * structure within vm_page_array[].
2438 * "npages" must be greater than zero. "m_start" and "m_end" must not
2439 * span a hole (or discontiguity) in the physical address space. Both
2440 * "alignment" and "boundary" must be a power of two.
2443 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2444 u_long alignment, vm_paddr_t boundary, int options)
2449 #if VM_NRESERVLEVEL > 0
2452 int m_inc, order, run_ext, run_len;
2454 KASSERT(npages > 0, ("npages is 0"));
2455 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2456 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2459 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2460 KASSERT((m->flags & PG_MARKER) == 0,
2461 ("page %p is PG_MARKER", m));
2462 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->ref_count >= 1,
2463 ("fictitious page %p has invalid ref count", m));
2466 * If the current page would be the start of a run, check its
2467 * physical address against the end, alignment, and boundary
2468 * conditions. If it doesn't satisfy these conditions, either
2469 * terminate the scan or advance to the next page that
2470 * satisfies the failed condition.
2473 KASSERT(m_run == NULL, ("m_run != NULL"));
2474 if (m + npages > m_end)
2476 pa = VM_PAGE_TO_PHYS(m);
2477 if ((pa & (alignment - 1)) != 0) {
2478 m_inc = atop(roundup2(pa, alignment) - pa);
2481 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2483 m_inc = atop(roundup2(pa, boundary) - pa);
2487 KASSERT(m_run != NULL, ("m_run == NULL"));
2491 if (vm_page_wired(m))
2493 #if VM_NRESERVLEVEL > 0
2494 else if ((level = vm_reserv_level(m)) >= 0 &&
2495 (options & VPSC_NORESERV) != 0) {
2497 /* Advance to the end of the reservation. */
2498 pa = VM_PAGE_TO_PHYS(m);
2499 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2503 else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2505 * The page is considered eligible for relocation if
2506 * and only if it could be laundered or reclaimed by
2509 VM_OBJECT_RLOCK(object);
2510 if (object != m->object) {
2511 VM_OBJECT_RUNLOCK(object);
2514 /* Don't care: PG_NODUMP, PG_ZERO. */
2515 if (object->type != OBJT_DEFAULT &&
2516 object->type != OBJT_SWAP &&
2517 object->type != OBJT_VNODE) {
2519 #if VM_NRESERVLEVEL > 0
2520 } else if ((options & VPSC_NOSUPER) != 0 &&
2521 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2523 /* Advance to the end of the superpage. */
2524 pa = VM_PAGE_TO_PHYS(m);
2525 m_inc = atop(roundup2(pa + 1,
2526 vm_reserv_size(level)) - pa);
2528 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2529 vm_page_queue(m) != PQ_NONE && !vm_page_busied(m)) {
2531 * The page is allocated but eligible for
2532 * relocation. Extend the current run by one
2535 KASSERT(pmap_page_get_memattr(m) ==
2537 ("page %p has an unexpected memattr", m));
2538 KASSERT((m->oflags & (VPO_SWAPINPROG |
2539 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2540 ("page %p has unexpected oflags", m));
2541 /* Don't care: PGA_NOSYNC. */
2545 VM_OBJECT_RUNLOCK(object);
2546 #if VM_NRESERVLEVEL > 0
2547 } else if (level >= 0) {
2549 * The page is reserved but not yet allocated. In
2550 * other words, it is still free. Extend the current
2555 } else if ((order = m->order) < VM_NFREEORDER) {
2557 * The page is enqueued in the physical memory
2558 * allocator's free page queues. Moreover, it is the
2559 * first page in a power-of-two-sized run of
2560 * contiguous free pages. Add these pages to the end
2561 * of the current run, and jump ahead.
2563 run_ext = 1 << order;
2567 * Skip the page for one of the following reasons: (1)
2568 * It is enqueued in the physical memory allocator's
2569 * free page queues. However, it is not the first
2570 * page in a run of contiguous free pages. (This case
2571 * rarely occurs because the scan is performed in
2572 * ascending order.) (2) It is not reserved, and it is
2573 * transitioning from free to allocated. (Conversely,
2574 * the transition from allocated to free for managed
2575 * pages is blocked by the page lock.) (3) It is
2576 * allocated but not contained by an object and not
2577 * wired, e.g., allocated by Xen's balloon driver.
2583 * Extend or reset the current run of pages.
2596 if (run_len >= npages)
2602 * vm_page_reclaim_run:
2604 * Try to relocate each of the allocated virtual pages within the
2605 * specified run of physical pages to a new physical address. Free the
2606 * physical pages underlying the relocated virtual pages. A virtual page
2607 * is relocatable if and only if it could be laundered or reclaimed by
2608 * the page daemon. Whenever possible, a virtual page is relocated to a
2609 * physical address above "high".
2611 * Returns 0 if every physical page within the run was already free or
2612 * just freed by a successful relocation. Otherwise, returns a non-zero
2613 * value indicating why the last attempt to relocate a virtual page was
2616 * "req_class" must be an allocation class.
2619 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2622 struct vm_domain *vmd;
2623 struct spglist free;
2626 vm_page_t m, m_end, m_new;
2627 int error, order, req;
2629 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2630 ("req_class is not an allocation class"));
2634 m_end = m_run + npages;
2635 for (; error == 0 && m < m_end; m++) {
2636 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2637 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2640 * Racily check for wirings. Races are handled once the object
2641 * lock is held and the page is unmapped.
2643 if (vm_page_wired(m))
2645 else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2647 * The page is relocated if and only if it could be
2648 * laundered or reclaimed by the page daemon.
2650 VM_OBJECT_WLOCK(object);
2651 /* Don't care: PG_NODUMP, PG_ZERO. */
2652 if (m->object != object ||
2653 (object->type != OBJT_DEFAULT &&
2654 object->type != OBJT_SWAP &&
2655 object->type != OBJT_VNODE))
2657 else if (object->memattr != VM_MEMATTR_DEFAULT)
2659 else if (vm_page_queue(m) != PQ_NONE &&
2660 vm_page_tryxbusy(m) != 0) {
2661 if (vm_page_wired(m)) {
2666 KASSERT(pmap_page_get_memattr(m) ==
2668 ("page %p has an unexpected memattr", m));
2669 KASSERT(m->oflags == 0,
2670 ("page %p has unexpected oflags", m));
2671 /* Don't care: PGA_NOSYNC. */
2672 if (!vm_page_none_valid(m)) {
2674 * First, try to allocate a new page
2675 * that is above "high". Failing
2676 * that, try to allocate a new page
2677 * that is below "m_run". Allocate
2678 * the new page between the end of
2679 * "m_run" and "high" only as a last
2682 req = req_class | VM_ALLOC_NOOBJ;
2683 if ((m->flags & PG_NODUMP) != 0)
2684 req |= VM_ALLOC_NODUMP;
2685 if (trunc_page(high) !=
2686 ~(vm_paddr_t)PAGE_MASK) {
2687 m_new = vm_page_alloc_contig(
2692 VM_MEMATTR_DEFAULT);
2695 if (m_new == NULL) {
2696 pa = VM_PAGE_TO_PHYS(m_run);
2697 m_new = vm_page_alloc_contig(
2699 0, pa - 1, PAGE_SIZE, 0,
2700 VM_MEMATTR_DEFAULT);
2702 if (m_new == NULL) {
2704 m_new = vm_page_alloc_contig(
2706 pa, high, PAGE_SIZE, 0,
2707 VM_MEMATTR_DEFAULT);
2709 if (m_new == NULL) {
2716 * Unmap the page and check for new
2717 * wirings that may have been acquired
2718 * through a pmap lookup.
2720 if (object->ref_count != 0 &&
2721 !vm_page_try_remove_all(m)) {
2723 vm_page_free(m_new);
2729 * Replace "m" with the new page. For
2730 * vm_page_replace(), "m" must be busy
2731 * and dequeued. Finally, change "m"
2732 * as if vm_page_free() was called.
2734 m_new->a.flags = m->a.flags &
2735 ~PGA_QUEUE_STATE_MASK;
2736 KASSERT(m_new->oflags == VPO_UNMANAGED,
2737 ("page %p is managed", m_new));
2739 pmap_copy_page(m, m_new);
2740 m_new->valid = m->valid;
2741 m_new->dirty = m->dirty;
2742 m->flags &= ~PG_ZERO;
2744 if (vm_page_replace_hold(m_new, object,
2746 vm_page_free_prep(m))
2747 SLIST_INSERT_HEAD(&free, m,
2751 * The new page must be deactivated
2752 * before the object is unlocked.
2754 vm_page_deactivate(m_new);
2756 m->flags &= ~PG_ZERO;
2758 if (vm_page_free_prep(m))
2759 SLIST_INSERT_HEAD(&free, m,
2761 KASSERT(m->dirty == 0,
2762 ("page %p is dirty", m));
2767 VM_OBJECT_WUNLOCK(object);
2769 MPASS(vm_phys_domain(m) == domain);
2770 vmd = VM_DOMAIN(domain);
2771 vm_domain_free_lock(vmd);
2773 if (order < VM_NFREEORDER) {
2775 * The page is enqueued in the physical memory
2776 * allocator's free page queues. Moreover, it
2777 * is the first page in a power-of-two-sized
2778 * run of contiguous free pages. Jump ahead
2779 * to the last page within that run, and
2780 * continue from there.
2782 m += (1 << order) - 1;
2784 #if VM_NRESERVLEVEL > 0
2785 else if (vm_reserv_is_page_free(m))
2788 vm_domain_free_unlock(vmd);
2789 if (order == VM_NFREEORDER)
2793 if ((m = SLIST_FIRST(&free)) != NULL) {
2796 vmd = VM_DOMAIN(domain);
2798 vm_domain_free_lock(vmd);
2800 MPASS(vm_phys_domain(m) == domain);
2801 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2802 vm_phys_free_pages(m, 0);
2804 } while ((m = SLIST_FIRST(&free)) != NULL);
2805 vm_domain_free_unlock(vmd);
2806 vm_domain_freecnt_inc(vmd, cnt);
2813 CTASSERT(powerof2(NRUNS));
2815 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2817 #define MIN_RECLAIM 8
2820 * vm_page_reclaim_contig:
2822 * Reclaim allocated, contiguous physical memory satisfying the specified
2823 * conditions by relocating the virtual pages using that physical memory.
2824 * Returns true if reclamation is successful and false otherwise. Since
2825 * relocation requires the allocation of physical pages, reclamation may
2826 * fail due to a shortage of free pages. When reclamation fails, callers
2827 * are expected to perform vm_wait() before retrying a failed allocation
2828 * operation, e.g., vm_page_alloc_contig().
2830 * The caller must always specify an allocation class through "req".
2832 * allocation classes:
2833 * VM_ALLOC_NORMAL normal process request
2834 * VM_ALLOC_SYSTEM system *really* needs a page
2835 * VM_ALLOC_INTERRUPT interrupt time request
2837 * The optional allocation flags are ignored.
2839 * "npages" must be greater than zero. Both "alignment" and "boundary"
2840 * must be a power of two.
2843 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
2844 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2846 struct vm_domain *vmd;
2847 vm_paddr_t curr_low;
2848 vm_page_t m_run, m_runs[NRUNS];
2849 u_long count, reclaimed;
2850 int error, i, options, req_class;
2852 KASSERT(npages > 0, ("npages is 0"));
2853 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2854 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2855 req_class = req & VM_ALLOC_CLASS_MASK;
2858 * The page daemon is allowed to dig deeper into the free page list.
2860 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2861 req_class = VM_ALLOC_SYSTEM;
2864 * Return if the number of free pages cannot satisfy the requested
2867 vmd = VM_DOMAIN(domain);
2868 count = vmd->vmd_free_count;
2869 if (count < npages + vmd->vmd_free_reserved || (count < npages +
2870 vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2871 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2875 * Scan up to three times, relaxing the restrictions ("options") on
2876 * the reclamation of reservations and superpages each time.
2878 for (options = VPSC_NORESERV;;) {
2880 * Find the highest runs that satisfy the given constraints
2881 * and restrictions, and record them in "m_runs".
2886 m_run = vm_phys_scan_contig(domain, npages, curr_low,
2887 high, alignment, boundary, options);
2890 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2891 m_runs[RUN_INDEX(count)] = m_run;
2896 * Reclaim the highest runs in LIFO (descending) order until
2897 * the number of reclaimed pages, "reclaimed", is at least
2898 * MIN_RECLAIM. Reset "reclaimed" each time because each
2899 * reclamation is idempotent, and runs will (likely) recur
2900 * from one scan to the next as restrictions are relaxed.
2903 for (i = 0; count > 0 && i < NRUNS; i++) {
2905 m_run = m_runs[RUN_INDEX(count)];
2906 error = vm_page_reclaim_run(req_class, domain, npages,
2909 reclaimed += npages;
2910 if (reclaimed >= MIN_RECLAIM)
2916 * Either relax the restrictions on the next scan or return if
2917 * the last scan had no restrictions.
2919 if (options == VPSC_NORESERV)
2920 options = VPSC_NOSUPER;
2921 else if (options == VPSC_NOSUPER)
2923 else if (options == VPSC_ANY)
2924 return (reclaimed != 0);
2929 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2930 u_long alignment, vm_paddr_t boundary)
2932 struct vm_domainset_iter di;
2936 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2938 ret = vm_page_reclaim_contig_domain(domain, req, npages, low,
2939 high, alignment, boundary);
2942 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2948 * Set the domain in the appropriate page level domainset.
2951 vm_domain_set(struct vm_domain *vmd)
2954 mtx_lock(&vm_domainset_lock);
2955 if (!vmd->vmd_minset && vm_paging_min(vmd)) {
2956 vmd->vmd_minset = 1;
2957 DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
2959 if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
2960 vmd->vmd_severeset = 1;
2961 DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
2963 mtx_unlock(&vm_domainset_lock);
2967 * Clear the domain from the appropriate page level domainset.
2970 vm_domain_clear(struct vm_domain *vmd)
2973 mtx_lock(&vm_domainset_lock);
2974 if (vmd->vmd_minset && !vm_paging_min(vmd)) {
2975 vmd->vmd_minset = 0;
2976 DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
2977 if (vm_min_waiters != 0) {
2979 wakeup(&vm_min_domains);
2982 if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
2983 vmd->vmd_severeset = 0;
2984 DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
2985 if (vm_severe_waiters != 0) {
2986 vm_severe_waiters = 0;
2987 wakeup(&vm_severe_domains);
2992 * If pageout daemon needs pages, then tell it that there are
2995 if (vmd->vmd_pageout_pages_needed &&
2996 vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
2997 wakeup(&vmd->vmd_pageout_pages_needed);
2998 vmd->vmd_pageout_pages_needed = 0;
3001 /* See comments in vm_wait_doms(). */
3002 if (vm_pageproc_waiters) {
3003 vm_pageproc_waiters = 0;
3004 wakeup(&vm_pageproc_waiters);
3006 mtx_unlock(&vm_domainset_lock);
3010 * Wait for free pages to exceed the min threshold globally.
3016 mtx_lock(&vm_domainset_lock);
3017 while (vm_page_count_min()) {
3019 msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
3021 mtx_unlock(&vm_domainset_lock);
3025 * Wait for free pages to exceed the severe threshold globally.
3028 vm_wait_severe(void)
3031 mtx_lock(&vm_domainset_lock);
3032 while (vm_page_count_severe()) {
3033 vm_severe_waiters++;
3034 msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
3037 mtx_unlock(&vm_domainset_lock);
3044 return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
3048 vm_wait_doms(const domainset_t *wdoms)
3052 * We use racey wakeup synchronization to avoid expensive global
3053 * locking for the pageproc when sleeping with a non-specific vm_wait.
3054 * To handle this, we only sleep for one tick in this instance. It
3055 * is expected that most allocations for the pageproc will come from
3056 * kmem or vm_page_grab* which will use the more specific and
3057 * race-free vm_wait_domain().
3059 if (curproc == pageproc) {
3060 mtx_lock(&vm_domainset_lock);
3061 vm_pageproc_waiters++;
3062 msleep(&vm_pageproc_waiters, &vm_domainset_lock, PVM | PDROP,
3066 * XXX Ideally we would wait only until the allocation could
3067 * be satisfied. This condition can cause new allocators to
3068 * consume all freed pages while old allocators wait.
3070 mtx_lock(&vm_domainset_lock);
3071 if (vm_page_count_min_set(wdoms)) {
3073 msleep(&vm_min_domains, &vm_domainset_lock,
3074 PVM | PDROP, "vmwait", 0);
3076 mtx_unlock(&vm_domainset_lock);
3083 * Sleep until free pages are available for allocation.
3084 * - Called in various places after failed memory allocations.
3087 vm_wait_domain(int domain)
3089 struct vm_domain *vmd;
3092 vmd = VM_DOMAIN(domain);
3093 vm_domain_free_assert_unlocked(vmd);
3095 if (curproc == pageproc) {
3096 mtx_lock(&vm_domainset_lock);
3097 if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
3098 vmd->vmd_pageout_pages_needed = 1;
3099 msleep(&vmd->vmd_pageout_pages_needed,
3100 &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
3102 mtx_unlock(&vm_domainset_lock);
3104 if (pageproc == NULL)
3105 panic("vm_wait in early boot");
3106 DOMAINSET_ZERO(&wdom);
3107 DOMAINSET_SET(vmd->vmd_domain, &wdom);
3108 vm_wait_doms(&wdom);
3115 * Sleep until free pages are available for allocation in the
3116 * affinity domains of the obj. If obj is NULL, the domain set
3117 * for the calling thread is used.
3118 * Called in various places after failed memory allocations.
3121 vm_wait(vm_object_t obj)
3123 struct domainset *d;
3128 * Carefully fetch pointers only once: the struct domainset
3129 * itself is ummutable but the pointer might change.
3132 d = obj->domain.dr_policy;
3134 d = curthread->td_domain.dr_policy;
3136 vm_wait_doms(&d->ds_mask);
3140 * vm_domain_alloc_fail:
3142 * Called when a page allocation function fails. Informs the
3143 * pagedaemon and performs the requested wait. Requires the
3144 * domain_free and object lock on entry. Returns with the
3145 * object lock held and free lock released. Returns an error when
3146 * retry is necessary.
3150 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3153 vm_domain_free_assert_unlocked(vmd);
3155 atomic_add_int(&vmd->vmd_pageout_deficit,
3156 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3157 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3159 VM_OBJECT_WUNLOCK(object);
3160 vm_wait_domain(vmd->vmd_domain);
3162 VM_OBJECT_WLOCK(object);
3163 if (req & VM_ALLOC_WAITOK)
3173 * Sleep until free pages are available for allocation.
3174 * - Called only in vm_fault so that processes page faulting
3175 * can be easily tracked.
3176 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3177 * processes will be able to grab memory first. Do not change
3178 * this balance without careful testing first.
3181 vm_waitpfault(struct domainset *dset, int timo)
3185 * XXX Ideally we would wait only until the allocation could
3186 * be satisfied. This condition can cause new allocators to
3187 * consume all freed pages while old allocators wait.
3189 mtx_lock(&vm_domainset_lock);
3190 if (vm_page_count_min_set(&dset->ds_mask)) {
3192 msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3195 mtx_unlock(&vm_domainset_lock);
3198 static struct vm_pagequeue *
3199 _vm_page_pagequeue(vm_page_t m, uint8_t queue)
3202 return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue]);
3206 static struct vm_pagequeue *
3207 vm_page_pagequeue(vm_page_t m)
3210 return (_vm_page_pagequeue(m, vm_page_astate_load(m).queue));
3214 static __always_inline bool
3215 vm_page_pqstate_fcmpset(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3217 vm_page_astate_t tmp;
3221 if (__predict_true(vm_page_astate_fcmpset(m, old, new)))
3223 counter_u64_add(pqstate_commit_retries, 1);
3224 } while (old->_bits == tmp._bits);
3230 * Do the work of committing a queue state update that moves the page out of
3231 * its current queue.
3234 _vm_page_pqstate_commit_dequeue(struct vm_pagequeue *pq, vm_page_t m,
3235 vm_page_astate_t *old, vm_page_astate_t new)
3239 vm_pagequeue_assert_locked(pq);
3240 KASSERT(vm_page_pagequeue(m) == pq,
3241 ("%s: queue %p does not match page %p", __func__, pq, m));
3242 KASSERT(old->queue != PQ_NONE && new.queue != old->queue,
3243 ("%s: invalid queue indices %d %d",
3244 __func__, old->queue, new.queue));
3247 * Once the queue index of the page changes there is nothing
3248 * synchronizing with further updates to the page's physical
3249 * queue state. Therefore we must speculatively remove the page
3250 * from the queue now and be prepared to roll back if the queue
3251 * state update fails. If the page is not physically enqueued then
3252 * we just update its queue index.
3254 if ((old->flags & PGA_ENQUEUED) != 0) {
3255 new.flags &= ~PGA_ENQUEUED;
3256 next = TAILQ_NEXT(m, plinks.q);
3257 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3258 vm_pagequeue_cnt_dec(pq);
3259 if (!vm_page_pqstate_fcmpset(m, old, new)) {
3261 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3263 TAILQ_INSERT_BEFORE(next, m, plinks.q);
3264 vm_pagequeue_cnt_inc(pq);
3270 return (vm_page_pqstate_fcmpset(m, old, new));
3275 vm_page_pqstate_commit_dequeue(vm_page_t m, vm_page_astate_t *old,
3276 vm_page_astate_t new)
3278 struct vm_pagequeue *pq;
3279 vm_page_astate_t as;
3282 pq = _vm_page_pagequeue(m, old->queue);
3285 * The queue field and PGA_ENQUEUED flag are stable only so long as the
3286 * corresponding page queue lock is held.
3288 vm_pagequeue_lock(pq);
3289 as = vm_page_astate_load(m);
3290 if (__predict_false(as._bits != old->_bits)) {
3294 ret = _vm_page_pqstate_commit_dequeue(pq, m, old, new);
3296 vm_pagequeue_unlock(pq);
3301 * Commit a queue state update that enqueues or requeues a page.
3304 _vm_page_pqstate_commit_requeue(struct vm_pagequeue *pq, vm_page_t m,
3305 vm_page_astate_t *old, vm_page_astate_t new)
3307 struct vm_domain *vmd;
3309 vm_pagequeue_assert_locked(pq);
3310 KASSERT(old->queue != PQ_NONE && new.queue == old->queue,
3311 ("%s: invalid queue indices %d %d",
3312 __func__, old->queue, new.queue));
3314 new.flags |= PGA_ENQUEUED;
3315 if (!vm_page_pqstate_fcmpset(m, old, new))
3318 if ((old->flags & PGA_ENQUEUED) != 0)
3319 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3321 vm_pagequeue_cnt_inc(pq);
3324 * Give PGA_REQUEUE_HEAD precedence over PGA_REQUEUE. In particular, if
3325 * both flags are set in close succession, only PGA_REQUEUE_HEAD will be
3326 * applied, even if it was set first.
3328 if ((old->flags & PGA_REQUEUE_HEAD) != 0) {
3329 vmd = vm_pagequeue_domain(m);
3330 KASSERT(pq == &vmd->vmd_pagequeues[PQ_INACTIVE],
3331 ("%s: invalid page queue for page %p", __func__, m));
3332 TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3334 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3340 * Commit a queue state update that encodes a request for a deferred queue
3344 vm_page_pqstate_commit_request(vm_page_t m, vm_page_astate_t *old,
3345 vm_page_astate_t new)
3348 KASSERT(old->queue == new.queue || new.queue != PQ_NONE,
3349 ("%s: invalid state, queue %d flags %x",
3350 __func__, new.queue, new.flags));
3352 if (old->_bits != new._bits &&
3353 !vm_page_pqstate_fcmpset(m, old, new))
3355 vm_page_pqbatch_submit(m, new.queue);
3360 * A generic queue state update function. This handles more cases than the
3361 * specialized functions above.
3364 vm_page_pqstate_commit(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3367 if (old->_bits == new._bits)
3370 if (old->queue != PQ_NONE && new.queue != old->queue) {
3371 if (!vm_page_pqstate_commit_dequeue(m, old, new))
3373 if (new.queue != PQ_NONE)
3374 vm_page_pqbatch_submit(m, new.queue);
3376 if (!vm_page_pqstate_fcmpset(m, old, new))
3378 if (new.queue != PQ_NONE &&
3379 ((new.flags & ~old->flags) & PGA_QUEUE_OP_MASK) != 0)
3380 vm_page_pqbatch_submit(m, new.queue);
3386 * Apply deferred queue state updates to a page.
3389 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m, uint8_t queue)
3391 vm_page_astate_t new, old;
3393 CRITICAL_ASSERT(curthread);
3394 vm_pagequeue_assert_locked(pq);
3395 KASSERT(queue < PQ_COUNT,
3396 ("%s: invalid queue index %d", __func__, queue));
3397 KASSERT(pq == _vm_page_pagequeue(m, queue),
3398 ("%s: page %p does not belong to queue %p", __func__, m, pq));
3400 for (old = vm_page_astate_load(m);;) {
3401 if (__predict_false(old.queue != queue ||
3402 (old.flags & PGA_QUEUE_OP_MASK) == 0)) {
3403 counter_u64_add(queue_nops, 1);
3406 KASSERT(old.queue != PQ_NONE || (old.flags & PGA_QUEUE_STATE_MASK) == 0,
3407 ("%s: page %p has unexpected queue state", __func__, m));
3410 if ((old.flags & PGA_DEQUEUE) != 0) {
3411 new.flags &= ~PGA_QUEUE_OP_MASK;
3412 new.queue = PQ_NONE;
3413 if (__predict_true(_vm_page_pqstate_commit_dequeue(pq,
3415 counter_u64_add(queue_ops, 1);
3419 new.flags &= ~(PGA_REQUEUE | PGA_REQUEUE_HEAD);
3420 if (__predict_true(_vm_page_pqstate_commit_requeue(pq,
3422 counter_u64_add(queue_ops, 1);
3430 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3435 for (i = 0; i < bq->bq_cnt; i++)
3436 vm_pqbatch_process_page(pq, bq->bq_pa[i], queue);
3437 vm_batchqueue_init(bq);
3441 * vm_page_pqbatch_submit: [ internal use only ]
3443 * Enqueue a page in the specified page queue's batched work queue.
3444 * The caller must have encoded the requested operation in the page
3445 * structure's a.flags field.
3448 vm_page_pqbatch_submit(vm_page_t m, uint8_t queue)
3450 struct vm_batchqueue *bq;
3451 struct vm_pagequeue *pq;
3454 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3455 ("page %p is unmanaged", m));
3456 KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3458 domain = vm_phys_domain(m);
3459 pq = &vm_pagequeue_domain(m)->vmd_pagequeues[queue];
3462 bq = DPCPU_PTR(pqbatch[domain][queue]);
3463 if (vm_batchqueue_insert(bq, m)) {
3468 vm_pagequeue_lock(pq);
3470 bq = DPCPU_PTR(pqbatch[domain][queue]);
3471 vm_pqbatch_process(pq, bq, queue);
3472 vm_pqbatch_process_page(pq, m, queue);
3473 vm_pagequeue_unlock(pq);
3478 * vm_page_pqbatch_drain: [ internal use only ]
3480 * Force all per-CPU page queue batch queues to be drained. This is
3481 * intended for use in severe memory shortages, to ensure that pages
3482 * do not remain stuck in the batch queues.
3485 vm_page_pqbatch_drain(void)
3488 struct vm_domain *vmd;
3489 struct vm_pagequeue *pq;
3490 int cpu, domain, queue;
3495 sched_bind(td, cpu);
3498 for (domain = 0; domain < vm_ndomains; domain++) {
3499 vmd = VM_DOMAIN(domain);
3500 for (queue = 0; queue < PQ_COUNT; queue++) {
3501 pq = &vmd->vmd_pagequeues[queue];
3502 vm_pagequeue_lock(pq);
3504 vm_pqbatch_process(pq,
3505 DPCPU_PTR(pqbatch[domain][queue]), queue);
3507 vm_pagequeue_unlock(pq);
3517 * vm_page_dequeue_deferred: [ internal use only ]
3519 * Request removal of the given page from its current page
3520 * queue. Physical removal from the queue may be deferred
3523 * The page must be locked.
3526 vm_page_dequeue_deferred(vm_page_t m)
3528 vm_page_astate_t new, old;
3530 old = vm_page_astate_load(m);
3532 if (old.queue == PQ_NONE) {
3533 KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3534 ("%s: page %p has unexpected queue state",
3539 new.flags |= PGA_DEQUEUE;
3540 } while (!vm_page_pqstate_commit_request(m, &old, new));
3546 * Remove the page from whichever page queue it's in, if any, before
3550 vm_page_dequeue(vm_page_t m)
3552 vm_page_astate_t new, old;
3554 old = vm_page_astate_load(m);
3556 if (old.queue == PQ_NONE) {
3557 KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3558 ("%s: page %p has unexpected queue state",
3563 new.flags &= ~PGA_QUEUE_OP_MASK;
3564 new.queue = PQ_NONE;
3565 } while (!vm_page_pqstate_commit_dequeue(m, &old, new));
3570 * Schedule the given page for insertion into the specified page queue.
3571 * Physical insertion of the page may be deferred indefinitely.
3574 vm_page_enqueue(vm_page_t m, uint8_t queue)
3577 KASSERT(m->a.queue == PQ_NONE &&
3578 (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
3579 ("%s: page %p is already enqueued", __func__, m));
3580 KASSERT(m->ref_count > 0,
3581 ("%s: page %p does not carry any references", __func__, m));
3584 if ((m->a.flags & PGA_REQUEUE) == 0)
3585 vm_page_aflag_set(m, PGA_REQUEUE);
3586 vm_page_pqbatch_submit(m, queue);
3590 * vm_page_free_prep:
3592 * Prepares the given page to be put on the free list,
3593 * disassociating it from any VM object. The caller may return
3594 * the page to the free list only if this function returns true.
3596 * The object must be locked. The page must be locked if it is
3600 vm_page_free_prep(vm_page_t m)
3604 * Synchronize with threads that have dropped a reference to this
3607 atomic_thread_fence_acq();
3609 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
3610 if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
3613 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3614 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
3615 KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
3616 m, i, (uintmax_t)*p));
3619 if ((m->oflags & VPO_UNMANAGED) == 0) {
3620 KASSERT(!pmap_page_is_mapped(m),
3621 ("vm_page_free_prep: freeing mapped page %p", m));
3622 KASSERT((m->a.flags & (PGA_EXECUTABLE | PGA_WRITEABLE)) == 0,
3623 ("vm_page_free_prep: mapping flags set in page %p", m));
3625 KASSERT(m->a.queue == PQ_NONE,
3626 ("vm_page_free_prep: unmanaged page %p is queued", m));
3628 VM_CNT_INC(v_tfree);
3630 if (m->object != NULL) {
3631 KASSERT(((m->oflags & VPO_UNMANAGED) != 0) ==
3632 ((m->object->flags & OBJ_UNMANAGED) != 0),
3633 ("vm_page_free_prep: managed flag mismatch for page %p",
3635 vm_page_assert_xbusied(m);
3638 * The object reference can be released without an atomic
3641 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
3642 m->ref_count == VPRC_OBJREF,
3643 ("vm_page_free_prep: page %p has unexpected ref_count %u",
3645 vm_page_object_remove(m);
3647 m->ref_count -= VPRC_OBJREF;
3649 vm_page_assert_unbusied(m);
3651 vm_page_busy_free(m);
3654 * If fictitious remove object association and
3657 if ((m->flags & PG_FICTITIOUS) != 0) {
3658 KASSERT(m->ref_count == 1,
3659 ("fictitious page %p is referenced", m));
3660 KASSERT(m->a.queue == PQ_NONE,
3661 ("fictitious page %p is queued", m));
3666 * Pages need not be dequeued before they are returned to the physical
3667 * memory allocator, but they must at least be marked for a deferred
3670 if ((m->oflags & VPO_UNMANAGED) == 0)
3671 vm_page_dequeue_deferred(m);
3676 if (m->ref_count != 0)
3677 panic("vm_page_free_prep: page %p has references", m);
3680 * Restore the default memory attribute to the page.
3682 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3683 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3685 #if VM_NRESERVLEVEL > 0
3687 * Determine whether the page belongs to a reservation. If the page was
3688 * allocated from a per-CPU cache, it cannot belong to a reservation, so
3689 * as an optimization, we avoid the check in that case.
3691 if ((m->flags & PG_PCPU_CACHE) == 0 && vm_reserv_free_page(m))
3701 * Returns the given page to the free list, disassociating it
3702 * from any VM object.
3704 * The object must be locked. The page must be locked if it is
3708 vm_page_free_toq(vm_page_t m)
3710 struct vm_domain *vmd;
3713 if (!vm_page_free_prep(m))
3716 vmd = vm_pagequeue_domain(m);
3717 zone = vmd->vmd_pgcache[m->pool].zone;
3718 if ((m->flags & PG_PCPU_CACHE) != 0 && zone != NULL) {
3722 vm_domain_free_lock(vmd);
3723 vm_phys_free_pages(m, 0);
3724 vm_domain_free_unlock(vmd);
3725 vm_domain_freecnt_inc(vmd, 1);
3729 * vm_page_free_pages_toq:
3731 * Returns a list of pages to the free list, disassociating it
3732 * from any VM object. In other words, this is equivalent to
3733 * calling vm_page_free_toq() for each page of a list of VM objects.
3735 * The objects must be locked. The pages must be locked if it is
3739 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
3744 if (SLIST_EMPTY(free))
3748 while ((m = SLIST_FIRST(free)) != NULL) {
3750 SLIST_REMOVE_HEAD(free, plinks.s.ss);
3751 vm_page_free_toq(m);
3754 if (update_wire_count)
3759 * Mark this page as wired down, preventing reclamation by the page daemon
3760 * or when the containing object is destroyed.
3763 vm_page_wire(vm_page_t m)
3767 KASSERT(m->object != NULL,
3768 ("vm_page_wire: page %p does not belong to an object", m));
3769 if (!vm_page_busied(m) && !vm_object_busied(m->object))
3770 VM_OBJECT_ASSERT_LOCKED(m->object);
3771 KASSERT((m->flags & PG_FICTITIOUS) == 0 ||
3772 VPRC_WIRE_COUNT(m->ref_count) >= 1,
3773 ("vm_page_wire: fictitious page %p has zero wirings", m));
3775 old = atomic_fetchadd_int(&m->ref_count, 1);
3776 KASSERT(VPRC_WIRE_COUNT(old) != VPRC_WIRE_COUNT_MAX,
3777 ("vm_page_wire: counter overflow for page %p", m));
3778 if (VPRC_WIRE_COUNT(old) == 0) {
3779 if ((m->oflags & VPO_UNMANAGED) == 0)
3780 vm_page_aflag_set(m, PGA_DEQUEUE);
3786 * Attempt to wire a mapped page following a pmap lookup of that page.
3787 * This may fail if a thread is concurrently tearing down mappings of the page.
3788 * The transient failure is acceptable because it translates to the
3789 * failure of the caller pmap_extract_and_hold(), which should be then
3790 * followed by the vm_fault() fallback, see e.g. vm_fault_quick_hold_pages().
3793 vm_page_wire_mapped(vm_page_t m)
3800 ("vm_page_wire_mapped: wiring unreferenced page %p", m));
3801 if ((old & VPRC_BLOCKED) != 0)
3803 } while (!atomic_fcmpset_int(&m->ref_count, &old, old + 1));
3805 if (VPRC_WIRE_COUNT(old) == 0) {
3806 if ((m->oflags & VPO_UNMANAGED) == 0)
3807 vm_page_aflag_set(m, PGA_DEQUEUE);
3814 * Release a wiring reference to a managed page. If the page still belongs to
3815 * an object, update its position in the page queues to reflect the reference.
3816 * If the wiring was the last reference to the page, free the page.
3819 vm_page_unwire_managed(vm_page_t m, uint8_t nqueue, bool noreuse)
3823 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3824 ("%s: page %p is unmanaged", __func__, m));
3827 * Update LRU state before releasing the wiring reference.
3828 * Use a release store when updating the reference count to
3829 * synchronize with vm_page_free_prep().
3833 KASSERT(VPRC_WIRE_COUNT(old) > 0,
3834 ("vm_page_unwire: wire count underflow for page %p", m));
3836 if (old > VPRC_OBJREF + 1) {
3838 * The page has at least one other wiring reference. An
3839 * earlier iteration of this loop may have called
3840 * vm_page_release_toq() and cleared PGA_DEQUEUE, so
3841 * re-set it if necessary.
3843 if ((vm_page_astate_load(m).flags & PGA_DEQUEUE) == 0)
3844 vm_page_aflag_set(m, PGA_DEQUEUE);
3845 } else if (old == VPRC_OBJREF + 1) {
3847 * This is the last wiring. Clear PGA_DEQUEUE and
3848 * update the page's queue state to reflect the
3849 * reference. If the page does not belong to an object
3850 * (i.e., the VPRC_OBJREF bit is clear), we only need to
3851 * clear leftover queue state.
3853 vm_page_release_toq(m, nqueue, false);
3854 } else if (old == 1) {
3855 vm_page_aflag_clear(m, PGA_DEQUEUE);
3857 } while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
3859 if (VPRC_WIRE_COUNT(old) == 1) {
3867 * Release one wiring of the specified page, potentially allowing it to be
3870 * Only managed pages belonging to an object can be paged out. If the number
3871 * of wirings transitions to zero and the page is eligible for page out, then
3872 * the page is added to the specified paging queue. If the released wiring
3873 * represented the last reference to the page, the page is freed.
3875 * A managed page must be locked.
3878 vm_page_unwire(vm_page_t m, uint8_t nqueue)
3881 KASSERT(nqueue < PQ_COUNT,
3882 ("vm_page_unwire: invalid queue %u request for page %p",
3885 if ((m->oflags & VPO_UNMANAGED) != 0) {
3886 if (vm_page_unwire_noq(m) && m->ref_count == 0)
3890 vm_page_unwire_managed(m, nqueue, false);
3894 * Unwire a page without (re-)inserting it into a page queue. It is up
3895 * to the caller to enqueue, requeue, or free the page as appropriate.
3896 * In most cases involving managed pages, vm_page_unwire() should be used
3900 vm_page_unwire_noq(vm_page_t m)
3904 old = vm_page_drop(m, 1);
3905 KASSERT(VPRC_WIRE_COUNT(old) != 0,
3906 ("vm_page_unref: counter underflow for page %p", m));
3907 KASSERT((m->flags & PG_FICTITIOUS) == 0 || VPRC_WIRE_COUNT(old) > 1,
3908 ("vm_page_unref: missing ref on fictitious page %p", m));
3910 if (VPRC_WIRE_COUNT(old) > 1)
3912 if ((m->oflags & VPO_UNMANAGED) == 0)
3913 vm_page_aflag_clear(m, PGA_DEQUEUE);
3919 * Ensure that the page ends up in the specified page queue. If the page is
3920 * active or being moved to the active queue, ensure that its act_count is
3921 * at least ACT_INIT but do not otherwise mess with it.
3923 * A managed page must be locked.
3925 static __always_inline void
3926 vm_page_mvqueue(vm_page_t m, const uint8_t nqueue, const uint16_t nflag)
3928 vm_page_astate_t old, new;
3930 KASSERT(m->ref_count > 0,
3931 ("%s: page %p does not carry any references", __func__, m));
3932 KASSERT(nflag == PGA_REQUEUE || nflag == PGA_REQUEUE_HEAD,
3933 ("%s: invalid flags %x", __func__, nflag));
3935 if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
3938 old = vm_page_astate_load(m);
3940 if ((old.flags & PGA_DEQUEUE) != 0)
3943 new.flags &= ~PGA_QUEUE_OP_MASK;
3944 if (nqueue == PQ_ACTIVE)
3945 new.act_count = max(old.act_count, ACT_INIT);
3946 if (old.queue == nqueue) {
3947 if (nqueue != PQ_ACTIVE)
3953 } while (!vm_page_pqstate_commit(m, &old, new));
3957 * Put the specified page on the active list (if appropriate).
3960 vm_page_activate(vm_page_t m)
3963 vm_page_mvqueue(m, PQ_ACTIVE, PGA_REQUEUE);
3967 * Move the specified page to the tail of the inactive queue, or requeue
3968 * the page if it is already in the inactive queue.
3971 vm_page_deactivate(vm_page_t m)
3974 vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE);
3978 vm_page_deactivate_noreuse(vm_page_t m)
3981 vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE_HEAD);
3985 * Put a page in the laundry, or requeue it if it is already there.
3988 vm_page_launder(vm_page_t m)
3991 vm_page_mvqueue(m, PQ_LAUNDRY, PGA_REQUEUE);
3995 * Put a page in the PQ_UNSWAPPABLE holding queue.
3998 vm_page_unswappable(vm_page_t m)
4001 KASSERT(!vm_page_wired(m) && (m->oflags & VPO_UNMANAGED) == 0,
4002 ("page %p already unswappable", m));
4005 vm_page_enqueue(m, PQ_UNSWAPPABLE);
4009 * Release a page back to the page queues in preparation for unwiring.
4012 vm_page_release_toq(vm_page_t m, uint8_t nqueue, const bool noreuse)
4014 vm_page_astate_t old, new;
4018 * Use a check of the valid bits to determine whether we should
4019 * accelerate reclamation of the page. The object lock might not be
4020 * held here, in which case the check is racy. At worst we will either
4021 * accelerate reclamation of a valid page and violate LRU, or
4022 * unnecessarily defer reclamation of an invalid page.
4024 * If we were asked to not cache the page, place it near the head of the
4025 * inactive queue so that is reclaimed sooner.
4027 if (noreuse || m->valid == 0) {
4028 nqueue = PQ_INACTIVE;
4029 nflag = PGA_REQUEUE_HEAD;
4031 nflag = PGA_REQUEUE;
4034 old = vm_page_astate_load(m);
4039 * If the page is already in the active queue and we are not
4040 * trying to accelerate reclamation, simply mark it as
4041 * referenced and avoid any queue operations.
4043 new.flags &= ~PGA_QUEUE_OP_MASK;
4044 if (nflag != PGA_REQUEUE_HEAD && old.queue == PQ_ACTIVE)
4045 new.flags |= PGA_REFERENCED;
4050 } while (!vm_page_pqstate_commit(m, &old, new));
4054 * Unwire a page and either attempt to free it or re-add it to the page queues.
4057 vm_page_release(vm_page_t m, int flags)
4061 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4062 ("vm_page_release: page %p is unmanaged", m));
4064 if ((flags & VPR_TRYFREE) != 0) {
4066 object = atomic_load_ptr(&m->object);
4069 /* Depends on type-stability. */
4070 if (vm_page_busied(m) || !VM_OBJECT_TRYWLOCK(object))
4072 if (object == m->object) {
4073 vm_page_release_locked(m, flags);
4074 VM_OBJECT_WUNLOCK(object);
4077 VM_OBJECT_WUNLOCK(object);
4080 vm_page_unwire_managed(m, PQ_INACTIVE, flags != 0);
4083 /* See vm_page_release(). */
4085 vm_page_release_locked(vm_page_t m, int flags)
4088 VM_OBJECT_ASSERT_WLOCKED(m->object);
4089 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4090 ("vm_page_release_locked: page %p is unmanaged", m));
4092 if (vm_page_unwire_noq(m)) {
4093 if ((flags & VPR_TRYFREE) != 0 &&
4094 (m->object->ref_count == 0 || !pmap_page_is_mapped(m)) &&
4095 m->dirty == 0 && vm_page_tryxbusy(m)) {
4098 vm_page_release_toq(m, PQ_INACTIVE, flags != 0);
4104 vm_page_try_blocked_op(vm_page_t m, void (*op)(vm_page_t))
4108 KASSERT(m->object != NULL && (m->oflags & VPO_UNMANAGED) == 0,
4109 ("vm_page_try_blocked_op: page %p has no object", m));
4110 KASSERT(vm_page_busied(m),
4111 ("vm_page_try_blocked_op: page %p is not busy", m));
4112 VM_OBJECT_ASSERT_LOCKED(m->object);
4117 ("vm_page_try_blocked_op: page %p has no references", m));
4118 if (VPRC_WIRE_COUNT(old) != 0)
4120 } while (!atomic_fcmpset_int(&m->ref_count, &old, old | VPRC_BLOCKED));
4125 * If the object is read-locked, new wirings may be created via an
4128 old = vm_page_drop(m, VPRC_BLOCKED);
4129 KASSERT(!VM_OBJECT_WOWNED(m->object) ||
4130 old == (VPRC_BLOCKED | VPRC_OBJREF),
4131 ("vm_page_try_blocked_op: unexpected refcount value %u for %p",
4137 * Atomically check for wirings and remove all mappings of the page.
4140 vm_page_try_remove_all(vm_page_t m)
4143 return (vm_page_try_blocked_op(m, pmap_remove_all));
4147 * Atomically check for wirings and remove all writeable mappings of the page.
4150 vm_page_try_remove_write(vm_page_t m)
4153 return (vm_page_try_blocked_op(m, pmap_remove_write));
4159 * Apply the specified advice to the given page.
4161 * The object and page must be locked.
4164 vm_page_advise(vm_page_t m, int advice)
4167 VM_OBJECT_ASSERT_WLOCKED(m->object);
4168 if (advice == MADV_FREE)
4170 * Mark the page clean. This will allow the page to be freed
4171 * without first paging it out. MADV_FREE pages are often
4172 * quickly reused by malloc(3), so we do not do anything that
4173 * would result in a page fault on a later access.
4176 else if (advice != MADV_DONTNEED) {
4177 if (advice == MADV_WILLNEED)
4178 vm_page_activate(m);
4182 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
4186 * Clear any references to the page. Otherwise, the page daemon will
4187 * immediately reactivate the page.
4189 vm_page_aflag_clear(m, PGA_REFERENCED);
4192 * Place clean pages near the head of the inactive queue rather than
4193 * the tail, thus defeating the queue's LRU operation and ensuring that
4194 * the page will be reused quickly. Dirty pages not already in the
4195 * laundry are moved there.
4198 vm_page_deactivate_noreuse(m);
4199 else if (!vm_page_in_laundry(m))
4204 vm_page_grab_pflags(int allocflags)
4208 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
4209 (allocflags & VM_ALLOC_WIRED) != 0,
4210 ("vm_page_grab_pflags: the pages must be busied or wired"));
4211 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4212 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4213 ("vm_page_grab_pflags: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY "
4215 pflags = allocflags &
4216 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL |
4218 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4219 pflags |= VM_ALLOC_WAITFAIL;
4220 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4221 pflags |= VM_ALLOC_SBUSY;
4227 * Grab a page, waiting until we are waken up due to the page
4228 * changing state. We keep on waiting, if the page continues
4229 * to be in the object. If the page doesn't exist, first allocate it
4230 * and then conditionally zero it.
4232 * This routine may sleep.
4234 * The object must be locked on entry. The lock will, however, be released
4235 * and reacquired if the routine sleeps.
4238 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
4243 VM_OBJECT_ASSERT_WLOCKED(object);
4244 pflags = vm_page_grab_pflags(allocflags);
4246 if ((m = vm_page_lookup(object, pindex)) != NULL) {
4247 if (!vm_page_acquire_flags(m, allocflags)) {
4248 if (vm_page_busy_sleep_flags(object, m, "pgrbwt",
4255 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4257 m = vm_page_alloc(object, pindex, pflags);
4259 if ((allocflags & (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL)) != 0)
4263 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
4267 if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4268 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4277 * Grab a page and make it valid, paging in if necessary. Pages missing from
4278 * their pager are zero filled and validated. If a VM_ALLOC_COUNT is supplied
4279 * and the page is not valid as many as VM_INITIAL_PAGEIN pages can be brought
4280 * in simultaneously. Additional pages will be left on a paging queue but
4281 * will neither be wired nor busy regardless of allocflags.
4284 vm_page_grab_valid(vm_page_t *mp, vm_object_t object, vm_pindex_t pindex, int allocflags)
4287 vm_page_t ma[VM_INITIAL_PAGEIN];
4289 int after, i, pflags, rv;
4291 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4292 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4293 ("vm_page_grab_valid: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4294 KASSERT((allocflags &
4295 (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4296 ("vm_page_grab_valid: Invalid flags 0x%X", allocflags));
4297 VM_OBJECT_ASSERT_WLOCKED(object);
4298 pflags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY);
4299 pflags |= VM_ALLOC_WAITFAIL;
4303 if ((m = vm_page_lookup(object, pindex)) != NULL) {
4305 * If the page is fully valid it can only become invalid
4306 * with the object lock held. If it is not valid it can
4307 * become valid with the busy lock held. Therefore, we
4308 * may unnecessarily lock the exclusive busy here if we
4309 * race with I/O completion not using the object lock.
4310 * However, we will not end up with an invalid page and a
4313 if (!vm_page_all_valid(m) ||
4314 (allocflags & (VM_ALLOC_IGN_SBUSY | VM_ALLOC_SBUSY)) == 0) {
4315 sleep = !vm_page_tryxbusy(m);
4318 sleep = !vm_page_trysbusy(m);
4320 (void)vm_page_busy_sleep_flags(object, m, "pgrbwt",
4324 if ((allocflags & VM_ALLOC_NOCREAT) != 0 &&
4325 !vm_page_all_valid(m)) {
4331 return (VM_PAGER_FAIL);
4333 if ((allocflags & VM_ALLOC_WIRED) != 0)
4335 if (vm_page_all_valid(m))
4337 } else if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4339 return (VM_PAGER_FAIL);
4340 } else if ((m = vm_page_alloc(object, pindex, pflags)) != NULL) {
4346 vm_page_assert_xbusied(m);
4348 if (vm_pager_has_page(object, pindex, NULL, &after)) {
4349 after = MIN(after, VM_INITIAL_PAGEIN);
4350 after = MIN(after, allocflags >> VM_ALLOC_COUNT_SHIFT);
4351 after = MAX(after, 1);
4353 for (i = 1; i < after; i++) {
4354 if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
4355 if (ma[i]->valid || !vm_page_tryxbusy(ma[i]))
4358 ma[i] = vm_page_alloc(object, m->pindex + i,
4365 vm_object_pip_add(object, after);
4366 VM_OBJECT_WUNLOCK(object);
4367 rv = vm_pager_get_pages(object, ma, after, NULL, NULL);
4368 VM_OBJECT_WLOCK(object);
4369 vm_object_pip_wakeupn(object, after);
4370 /* Pager may have replaced a page. */
4372 if (rv != VM_PAGER_OK) {
4373 if ((allocflags & VM_ALLOC_WIRED) != 0)
4374 vm_page_unwire_noq(m);
4375 for (i = 0; i < after; i++) {
4376 if (!vm_page_wired(ma[i]))
4377 vm_page_free(ma[i]);
4379 vm_page_xunbusy(ma[i]);
4384 for (i = 1; i < after; i++)
4385 vm_page_readahead_finish(ma[i]);
4386 MPASS(vm_page_all_valid(m));
4388 vm_page_zero_invalid(m, TRUE);
4391 if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4397 if ((allocflags & VM_ALLOC_SBUSY) != 0 && xbusy)
4398 vm_page_busy_downgrade(m);
4400 return (VM_PAGER_OK);
4404 * Return the specified range of pages from the given object. For each
4405 * page offset within the range, if a page already exists within the object
4406 * at that offset and it is busy, then wait for it to change state. If,
4407 * instead, the page doesn't exist, then allocate it.
4409 * The caller must always specify an allocation class.
4411 * allocation classes:
4412 * VM_ALLOC_NORMAL normal process request
4413 * VM_ALLOC_SYSTEM system *really* needs the pages
4415 * The caller must always specify that the pages are to be busied and/or
4418 * optional allocation flags:
4419 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
4420 * VM_ALLOC_NOBUSY do not exclusive busy the page
4421 * VM_ALLOC_NOWAIT do not sleep
4422 * VM_ALLOC_SBUSY set page to sbusy state
4423 * VM_ALLOC_WIRED wire the pages
4424 * VM_ALLOC_ZERO zero and validate any invalid pages
4426 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
4427 * may return a partial prefix of the requested range.
4430 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
4431 vm_page_t *ma, int count)
4437 VM_OBJECT_ASSERT_WLOCKED(object);
4438 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
4439 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
4441 pflags = vm_page_grab_pflags(allocflags);
4447 m = vm_radix_lookup_le(&object->rtree, pindex + i);
4448 if (m == NULL || m->pindex != pindex + i) {
4452 mpred = TAILQ_PREV(m, pglist, listq);
4453 for (; i < count; i++) {
4455 if (!vm_page_acquire_flags(m, allocflags)) {
4456 if (vm_page_busy_sleep_flags(object, m,
4457 "grbmaw", allocflags))
4462 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4464 m = vm_page_alloc_after(object, pindex + i,
4465 pflags | VM_ALLOC_COUNT(count - i), mpred);
4467 if ((allocflags & (VM_ALLOC_NOWAIT |
4468 VM_ALLOC_WAITFAIL)) != 0)
4473 if (vm_page_none_valid(m) &&
4474 (allocflags & VM_ALLOC_ZERO) != 0) {
4475 if ((m->flags & PG_ZERO) == 0)
4479 if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4480 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4486 m = vm_page_next(m);
4492 * Mapping function for valid or dirty bits in a page.
4494 * Inputs are required to range within a page.
4497 vm_page_bits(int base, int size)
4503 base + size <= PAGE_SIZE,
4504 ("vm_page_bits: illegal base/size %d/%d", base, size)
4507 if (size == 0) /* handle degenerate case */
4510 first_bit = base >> DEV_BSHIFT;
4511 last_bit = (base + size - 1) >> DEV_BSHIFT;
4513 return (((vm_page_bits_t)2 << last_bit) -
4514 ((vm_page_bits_t)1 << first_bit));
4518 vm_page_bits_set(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t set)
4521 #if PAGE_SIZE == 32768
4522 atomic_set_64((uint64_t *)bits, set);
4523 #elif PAGE_SIZE == 16384
4524 atomic_set_32((uint32_t *)bits, set);
4525 #elif (PAGE_SIZE == 8192) && defined(atomic_set_16)
4526 atomic_set_16((uint16_t *)bits, set);
4527 #elif (PAGE_SIZE == 4096) && defined(atomic_set_8)
4528 atomic_set_8((uint8_t *)bits, set);
4529 #else /* PAGE_SIZE <= 8192 */
4533 addr = (uintptr_t)bits;
4535 * Use a trick to perform a 32-bit atomic on the
4536 * containing aligned word, to not depend on the existence
4537 * of atomic_{set, clear}_{8, 16}.
4539 shift = addr & (sizeof(uint32_t) - 1);
4540 #if BYTE_ORDER == BIG_ENDIAN
4541 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4545 addr &= ~(sizeof(uint32_t) - 1);
4546 atomic_set_32((uint32_t *)addr, set << shift);
4547 #endif /* PAGE_SIZE */
4551 vm_page_bits_clear(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t clear)
4554 #if PAGE_SIZE == 32768
4555 atomic_clear_64((uint64_t *)bits, clear);
4556 #elif PAGE_SIZE == 16384
4557 atomic_clear_32((uint32_t *)bits, clear);
4558 #elif (PAGE_SIZE == 8192) && defined(atomic_clear_16)
4559 atomic_clear_16((uint16_t *)bits, clear);
4560 #elif (PAGE_SIZE == 4096) && defined(atomic_clear_8)
4561 atomic_clear_8((uint8_t *)bits, clear);
4562 #else /* PAGE_SIZE <= 8192 */
4566 addr = (uintptr_t)bits;
4568 * Use a trick to perform a 32-bit atomic on the
4569 * containing aligned word, to not depend on the existence
4570 * of atomic_{set, clear}_{8, 16}.
4572 shift = addr & (sizeof(uint32_t) - 1);
4573 #if BYTE_ORDER == BIG_ENDIAN
4574 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4578 addr &= ~(sizeof(uint32_t) - 1);
4579 atomic_clear_32((uint32_t *)addr, clear << shift);
4580 #endif /* PAGE_SIZE */
4583 static inline vm_page_bits_t
4584 vm_page_bits_swap(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t newbits)
4586 #if PAGE_SIZE == 32768
4590 while (atomic_fcmpset_64(bits, &old, newbits) == 0);
4592 #elif PAGE_SIZE == 16384
4596 while (atomic_fcmpset_32(bits, &old, newbits) == 0);
4598 #elif (PAGE_SIZE == 8192) && defined(atomic_fcmpset_16)
4602 while (atomic_fcmpset_16(bits, &old, newbits) == 0);
4604 #elif (PAGE_SIZE == 4096) && defined(atomic_fcmpset_8)
4608 while (atomic_fcmpset_8(bits, &old, newbits) == 0);
4610 #else /* PAGE_SIZE <= 4096*/
4612 uint32_t old, new, mask;
4615 addr = (uintptr_t)bits;
4617 * Use a trick to perform a 32-bit atomic on the
4618 * containing aligned word, to not depend on the existence
4619 * of atomic_{set, swap, clear}_{8, 16}.
4621 shift = addr & (sizeof(uint32_t) - 1);
4622 #if BYTE_ORDER == BIG_ENDIAN
4623 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4627 addr &= ~(sizeof(uint32_t) - 1);
4628 mask = VM_PAGE_BITS_ALL << shift;
4633 new |= newbits << shift;
4634 } while (atomic_fcmpset_32((uint32_t *)addr, &old, new) == 0);
4635 return (old >> shift);
4636 #endif /* PAGE_SIZE */
4640 * vm_page_set_valid_range:
4642 * Sets portions of a page valid. The arguments are expected
4643 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4644 * of any partial chunks touched by the range. The invalid portion of
4645 * such chunks will be zeroed.
4647 * (base + size) must be less then or equal to PAGE_SIZE.
4650 vm_page_set_valid_range(vm_page_t m, int base, int size)
4653 vm_page_bits_t pagebits;
4655 vm_page_assert_busied(m);
4656 if (size == 0) /* handle degenerate case */
4660 * If the base is not DEV_BSIZE aligned and the valid
4661 * bit is clear, we have to zero out a portion of the
4664 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4665 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
4666 pmap_zero_page_area(m, frag, base - frag);
4669 * If the ending offset is not DEV_BSIZE aligned and the
4670 * valid bit is clear, we have to zero out a portion of
4673 endoff = base + size;
4674 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4675 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
4676 pmap_zero_page_area(m, endoff,
4677 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4680 * Assert that no previously invalid block that is now being validated
4683 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
4684 ("vm_page_set_valid_range: page %p is dirty", m));
4687 * Set valid bits inclusive of any overlap.
4689 pagebits = vm_page_bits(base, size);
4690 if (vm_page_xbusied(m))
4691 m->valid |= pagebits;
4693 vm_page_bits_set(m, &m->valid, pagebits);
4697 * Set the page dirty bits and free the invalid swap space if
4698 * present. Returns the previous dirty bits.
4701 vm_page_set_dirty(vm_page_t m)
4705 VM_PAGE_OBJECT_BUSY_ASSERT(m);
4707 if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m)) {
4709 m->dirty = VM_PAGE_BITS_ALL;
4711 old = vm_page_bits_swap(m, &m->dirty, VM_PAGE_BITS_ALL);
4712 if (old == 0 && (m->a.flags & PGA_SWAP_SPACE) != 0)
4713 vm_pager_page_unswapped(m);
4719 * Clear the given bits from the specified page's dirty field.
4721 static __inline void
4722 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
4725 vm_page_assert_busied(m);
4728 * If the page is xbusied and not write mapped we are the
4729 * only thread that can modify dirty bits. Otherwise, The pmap
4730 * layer can call vm_page_dirty() without holding a distinguished
4731 * lock. The combination of page busy and atomic operations
4732 * suffice to guarantee consistency of the page dirty field.
4734 if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
4735 m->dirty &= ~pagebits;
4737 vm_page_bits_clear(m, &m->dirty, pagebits);
4741 * vm_page_set_validclean:
4743 * Sets portions of a page valid and clean. The arguments are expected
4744 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4745 * of any partial chunks touched by the range. The invalid portion of
4746 * such chunks will be zero'd.
4748 * (base + size) must be less then or equal to PAGE_SIZE.
4751 vm_page_set_validclean(vm_page_t m, int base, int size)
4753 vm_page_bits_t oldvalid, pagebits;
4756 vm_page_assert_busied(m);
4757 if (size == 0) /* handle degenerate case */
4761 * If the base is not DEV_BSIZE aligned and the valid
4762 * bit is clear, we have to zero out a portion of the
4765 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4766 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
4767 pmap_zero_page_area(m, frag, base - frag);
4770 * If the ending offset is not DEV_BSIZE aligned and the
4771 * valid bit is clear, we have to zero out a portion of
4774 endoff = base + size;
4775 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4776 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
4777 pmap_zero_page_area(m, endoff,
4778 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4781 * Set valid, clear dirty bits. If validating the entire
4782 * page we can safely clear the pmap modify bit. We also
4783 * use this opportunity to clear the PGA_NOSYNC flag. If a process
4784 * takes a write fault on a MAP_NOSYNC memory area the flag will
4787 * We set valid bits inclusive of any overlap, but we can only
4788 * clear dirty bits for DEV_BSIZE chunks that are fully within
4791 oldvalid = m->valid;
4792 pagebits = vm_page_bits(base, size);
4793 if (vm_page_xbusied(m))
4794 m->valid |= pagebits;
4796 vm_page_bits_set(m, &m->valid, pagebits);
4798 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
4799 frag = DEV_BSIZE - frag;
4805 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
4807 if (base == 0 && size == PAGE_SIZE) {
4809 * The page can only be modified within the pmap if it is
4810 * mapped, and it can only be mapped if it was previously
4813 if (oldvalid == VM_PAGE_BITS_ALL)
4815 * Perform the pmap_clear_modify() first. Otherwise,
4816 * a concurrent pmap operation, such as
4817 * pmap_protect(), could clear a modification in the
4818 * pmap and set the dirty field on the page before
4819 * pmap_clear_modify() had begun and after the dirty
4820 * field was cleared here.
4822 pmap_clear_modify(m);
4824 vm_page_aflag_clear(m, PGA_NOSYNC);
4825 } else if (oldvalid != VM_PAGE_BITS_ALL && vm_page_xbusied(m))
4826 m->dirty &= ~pagebits;
4828 vm_page_clear_dirty_mask(m, pagebits);
4832 vm_page_clear_dirty(vm_page_t m, int base, int size)
4835 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
4839 * vm_page_set_invalid:
4841 * Invalidates DEV_BSIZE'd chunks within a page. Both the
4842 * valid and dirty bits for the effected areas are cleared.
4845 vm_page_set_invalid(vm_page_t m, int base, int size)
4847 vm_page_bits_t bits;
4851 * The object lock is required so that pages can't be mapped
4852 * read-only while we're in the process of invalidating them.
4855 VM_OBJECT_ASSERT_WLOCKED(object);
4856 vm_page_assert_busied(m);
4858 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
4859 size >= object->un_pager.vnp.vnp_size)
4860 bits = VM_PAGE_BITS_ALL;
4862 bits = vm_page_bits(base, size);
4863 if (object->ref_count != 0 && vm_page_all_valid(m) && bits != 0)
4865 KASSERT((bits == 0 && vm_page_all_valid(m)) ||
4866 !pmap_page_is_mapped(m),
4867 ("vm_page_set_invalid: page %p is mapped", m));
4868 if (vm_page_xbusied(m)) {
4872 vm_page_bits_clear(m, &m->valid, bits);
4873 vm_page_bits_clear(m, &m->dirty, bits);
4880 * Invalidates the entire page. The page must be busy, unmapped, and
4881 * the enclosing object must be locked. The object locks protects
4882 * against concurrent read-only pmap enter which is done without
4886 vm_page_invalid(vm_page_t m)
4889 vm_page_assert_busied(m);
4890 VM_OBJECT_ASSERT_LOCKED(m->object);
4891 MPASS(!pmap_page_is_mapped(m));
4893 if (vm_page_xbusied(m))
4896 vm_page_bits_clear(m, &m->valid, VM_PAGE_BITS_ALL);
4900 * vm_page_zero_invalid()
4902 * The kernel assumes that the invalid portions of a page contain
4903 * garbage, but such pages can be mapped into memory by user code.
4904 * When this occurs, we must zero out the non-valid portions of the
4905 * page so user code sees what it expects.
4907 * Pages are most often semi-valid when the end of a file is mapped
4908 * into memory and the file's size is not page aligned.
4911 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
4917 * Scan the valid bits looking for invalid sections that
4918 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
4919 * valid bit may be set ) have already been zeroed by
4920 * vm_page_set_validclean().
4922 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
4923 if (i == (PAGE_SIZE / DEV_BSIZE) ||
4924 (m->valid & ((vm_page_bits_t)1 << i))) {
4926 pmap_zero_page_area(m,
4927 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
4934 * setvalid is TRUE when we can safely set the zero'd areas
4935 * as being valid. We can do this if there are no cache consistancy
4936 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
4945 * Is (partial) page valid? Note that the case where size == 0
4946 * will return FALSE in the degenerate case where the page is
4947 * entirely invalid, and TRUE otherwise.
4949 * Some callers envoke this routine without the busy lock held and
4950 * handle races via higher level locks. Typical callers should
4951 * hold a busy lock to prevent invalidation.
4954 vm_page_is_valid(vm_page_t m, int base, int size)
4956 vm_page_bits_t bits;
4958 bits = vm_page_bits(base, size);
4959 return (m->valid != 0 && (m->valid & bits) == bits);
4963 * Returns true if all of the specified predicates are true for the entire
4964 * (super)page and false otherwise.
4967 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
4973 if (skip_m != NULL && skip_m->object != object)
4975 VM_OBJECT_ASSERT_LOCKED(object);
4976 npages = atop(pagesizes[m->psind]);
4979 * The physically contiguous pages that make up a superpage, i.e., a
4980 * page with a page size index ("psind") greater than zero, will
4981 * occupy adjacent entries in vm_page_array[].
4983 for (i = 0; i < npages; i++) {
4984 /* Always test object consistency, including "skip_m". */
4985 if (m[i].object != object)
4987 if (&m[i] == skip_m)
4989 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
4991 if ((flags & PS_ALL_DIRTY) != 0) {
4993 * Calling vm_page_test_dirty() or pmap_is_modified()
4994 * might stop this case from spuriously returning
4995 * "false". However, that would require a write lock
4996 * on the object containing "m[i]".
4998 if (m[i].dirty != VM_PAGE_BITS_ALL)
5001 if ((flags & PS_ALL_VALID) != 0 &&
5002 m[i].valid != VM_PAGE_BITS_ALL)
5009 * Set the page's dirty bits if the page is modified.
5012 vm_page_test_dirty(vm_page_t m)
5015 vm_page_assert_busied(m);
5016 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
5021 vm_page_valid(vm_page_t m)
5024 vm_page_assert_busied(m);
5025 if (vm_page_xbusied(m))
5026 m->valid = VM_PAGE_BITS_ALL;
5028 vm_page_bits_set(m, &m->valid, VM_PAGE_BITS_ALL);
5032 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
5035 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
5039 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
5042 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
5046 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
5049 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
5052 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
5054 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
5057 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
5061 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
5064 mtx_assert_(vm_page_lockptr(m), a, file, line);
5070 vm_page_object_busy_assert(vm_page_t m)
5074 * Certain of the page's fields may only be modified by the
5075 * holder of a page or object busy.
5077 if (m->object != NULL && !vm_page_busied(m))
5078 VM_OBJECT_ASSERT_BUSY(m->object);
5082 vm_page_assert_pga_writeable(vm_page_t m, uint16_t bits)
5085 if ((bits & PGA_WRITEABLE) == 0)
5089 * The PGA_WRITEABLE flag can only be set if the page is
5090 * managed, is exclusively busied or the object is locked.
5091 * Currently, this flag is only set by pmap_enter().
5093 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5094 ("PGA_WRITEABLE on unmanaged page"));
5095 if (!vm_page_xbusied(m))
5096 VM_OBJECT_ASSERT_BUSY(m->object);
5100 #include "opt_ddb.h"
5102 #include <sys/kernel.h>
5104 #include <ddb/ddb.h>
5106 DB_SHOW_COMMAND(page, vm_page_print_page_info)
5109 db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
5110 db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
5111 db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
5112 db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
5113 db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
5114 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
5115 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
5116 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
5117 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
5120 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
5124 db_printf("pq_free %d\n", vm_free_count());
5125 for (dom = 0; dom < vm_ndomains; dom++) {
5127 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
5129 vm_dom[dom].vmd_page_count,
5130 vm_dom[dom].vmd_free_count,
5131 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
5132 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
5133 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
5134 vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
5138 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
5141 boolean_t phys, virt;
5144 db_printf("show pginfo addr\n");
5148 phys = strchr(modif, 'p') != NULL;
5149 virt = strchr(modif, 'v') != NULL;
5151 m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
5153 m = PHYS_TO_VM_PAGE(addr);
5155 m = (vm_page_t)addr;
5157 "page %p obj %p pidx 0x%jx phys 0x%jx q %d ref %u\n"
5158 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
5159 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
5160 m->a.queue, m->ref_count, m->a.flags, m->oflags,
5161 m->flags, m->a.act_count, m->busy_lock, m->valid, m->dirty);