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>
77 #include <sys/domainset.h>
78 #include <sys/kernel.h>
79 #include <sys/limits.h>
80 #include <sys/linker.h>
81 #include <sys/malloc.h>
83 #include <sys/msgbuf.h>
84 #include <sys/mutex.h>
86 #include <sys/rwlock.h>
87 #include <sys/sleepqueue.h>
89 #include <sys/sched.h>
91 #include <sys/sysctl.h>
92 #include <sys/vmmeter.h>
93 #include <sys/vnode.h>
97 #include <vm/vm_param.h>
98 #include <vm/vm_domainset.h>
99 #include <vm/vm_kern.h>
100 #include <vm/vm_map.h>
101 #include <vm/vm_object.h>
102 #include <vm/vm_page.h>
103 #include <vm/vm_pageout.h>
104 #include <vm/vm_phys.h>
105 #include <vm/vm_pagequeue.h>
106 #include <vm/vm_pager.h>
107 #include <vm/vm_radix.h>
108 #include <vm/vm_reserv.h>
109 #include <vm/vm_extern.h>
111 #include <vm/uma_int.h>
113 #include <machine/md_var.h>
115 extern int uma_startup_count(int);
116 extern void uma_startup(void *, int);
117 extern int vmem_startup_count(void);
119 struct vm_domain vm_dom[MAXMEMDOM];
121 DPCPU_DEFINE_STATIC(struct vm_batchqueue, pqbatch[MAXMEMDOM][PQ_COUNT]);
123 struct mtx_padalign __exclusive_cache_line pa_lock[PA_LOCK_COUNT];
125 struct mtx_padalign __exclusive_cache_line vm_domainset_lock;
126 /* The following fields are protected by the domainset lock. */
127 domainset_t __exclusive_cache_line vm_min_domains;
128 domainset_t __exclusive_cache_line vm_severe_domains;
129 static int vm_min_waiters;
130 static int vm_severe_waiters;
131 static int vm_pageproc_waiters;
134 * bogus page -- for I/O to/from partially complete buffers,
135 * or for paging into sparsely invalid regions.
137 vm_page_t bogus_page;
139 vm_page_t vm_page_array;
140 long vm_page_array_size;
143 static int boot_pages;
144 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
146 "number of pages allocated for bootstrapping the VM system");
148 static int pa_tryrelock_restart;
149 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
150 &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
152 static TAILQ_HEAD(, vm_page) blacklist_head;
153 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
154 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
155 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
157 static uma_zone_t fakepg_zone;
159 static void vm_page_alloc_check(vm_page_t m);
160 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
161 static void vm_page_dequeue_complete(vm_page_t m);
162 static void vm_page_enqueue(vm_page_t m, uint8_t queue);
163 static void vm_page_init(void *dummy);
164 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
165 vm_pindex_t pindex, vm_page_t mpred);
166 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
168 static void vm_page_mvqueue(vm_page_t m, uint8_t queue);
169 static int vm_page_reclaim_run(int req_class, int domain, u_long npages,
170 vm_page_t m_run, vm_paddr_t high);
171 static int vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object,
173 static int vm_page_zone_import(void *arg, void **store, int cnt, int domain,
175 static void vm_page_zone_release(void *arg, void **store, int cnt);
177 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
180 vm_page_init(void *dummy)
183 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
184 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
185 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
186 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
190 * The cache page zone is initialized later since we need to be able to allocate
191 * pages before UMA is fully initialized.
194 vm_page_init_cache_zones(void *dummy __unused)
196 struct vm_domain *vmd;
197 struct vm_pgcache *pgcache;
200 for (domain = 0; domain < vm_ndomains; domain++) {
201 vmd = VM_DOMAIN(domain);
204 * Don't allow the page caches to take up more than .25% of
207 if (vmd->vmd_page_count / 400 < 256 * mp_ncpus * VM_NFREEPOOL)
209 for (pool = 0; pool < VM_NFREEPOOL; pool++) {
210 pgcache = &vmd->vmd_pgcache[pool];
211 pgcache->domain = domain;
212 pgcache->pool = pool;
213 pgcache->zone = uma_zcache_create("vm pgcache",
214 sizeof(struct vm_page), NULL, NULL, NULL, NULL,
215 vm_page_zone_import, vm_page_zone_release, pgcache,
216 UMA_ZONE_MAXBUCKET | UMA_ZONE_VM);
217 (void)uma_zone_set_maxcache(pgcache->zone, 0);
221 SYSINIT(vm_page2, SI_SUB_VM_CONF, SI_ORDER_ANY, vm_page_init_cache_zones, NULL);
223 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
224 #if PAGE_SIZE == 32768
226 CTASSERT(sizeof(u_long) >= 8);
231 * Try to acquire a physical address lock while a pmap is locked. If we
232 * fail to trylock we unlock and lock the pmap directly and cache the
233 * locked pa in *locked. The caller should then restart their loop in case
234 * the virtual to physical mapping has changed.
237 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
244 PA_LOCK_ASSERT(lockpa, MA_OWNED);
245 if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
252 atomic_add_int(&pa_tryrelock_restart, 1);
261 * Sets the page size, perhaps based upon the memory
262 * size. Must be called before any use of page-size
263 * dependent functions.
266 vm_set_page_size(void)
268 if (vm_cnt.v_page_size == 0)
269 vm_cnt.v_page_size = PAGE_SIZE;
270 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
271 panic("vm_set_page_size: page size not a power of two");
275 * vm_page_blacklist_next:
277 * Find the next entry in the provided string of blacklist
278 * addresses. Entries are separated by space, comma, or newline.
279 * If an invalid integer is encountered then the rest of the
280 * string is skipped. Updates the list pointer to the next
281 * character, or NULL if the string is exhausted or invalid.
284 vm_page_blacklist_next(char **list, char *end)
289 if (list == NULL || *list == NULL)
297 * If there's no end pointer then the buffer is coming from
298 * the kenv and we know it's null-terminated.
301 end = *list + strlen(*list);
303 /* Ensure that strtoq() won't walk off the end */
305 if (*end == '\n' || *end == ' ' || *end == ',')
308 printf("Blacklist not terminated, skipping\n");
314 for (pos = *list; *pos != '\0'; pos = cp) {
315 bad = strtoq(pos, &cp, 0);
316 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
325 if (*cp == '\0' || ++cp >= end)
329 return (trunc_page(bad));
331 printf("Garbage in RAM blacklist, skipping\n");
337 vm_page_blacklist_add(vm_paddr_t pa, bool verbose)
339 struct vm_domain *vmd;
343 m = vm_phys_paddr_to_vm_page(pa);
345 return (true); /* page does not exist, no failure */
347 vmd = vm_pagequeue_domain(m);
348 vm_domain_free_lock(vmd);
349 ret = vm_phys_unfree_page(m);
350 vm_domain_free_unlock(vmd);
352 vm_domain_freecnt_inc(vmd, -1);
353 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
355 printf("Skipping page with pa 0x%jx\n", (uintmax_t)pa);
361 * vm_page_blacklist_check:
363 * Iterate through the provided string of blacklist addresses, pulling
364 * each entry out of the physical allocator free list and putting it
365 * onto a list for reporting via the vm.page_blacklist sysctl.
368 vm_page_blacklist_check(char *list, char *end)
374 while (next != NULL) {
375 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
377 vm_page_blacklist_add(pa, bootverbose);
382 * vm_page_blacklist_load:
384 * Search for a special module named "ram_blacklist". It'll be a
385 * plain text file provided by the user via the loader directive
389 vm_page_blacklist_load(char **list, char **end)
398 mod = preload_search_by_type("ram_blacklist");
400 ptr = preload_fetch_addr(mod);
401 len = preload_fetch_size(mod);
412 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
419 error = sysctl_wire_old_buffer(req, 0);
422 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
423 TAILQ_FOREACH(m, &blacklist_head, listq) {
424 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
425 (uintmax_t)m->phys_addr);
428 error = sbuf_finish(&sbuf);
434 * Initialize a dummy page for use in scans of the specified paging queue.
435 * In principle, this function only needs to set the flag PG_MARKER.
436 * Nonetheless, it write busies the page as a safety precaution.
439 vm_page_init_marker(vm_page_t marker, int queue, uint8_t aflags)
442 bzero(marker, sizeof(*marker));
443 marker->flags = PG_MARKER;
444 marker->aflags = aflags;
445 marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
446 marker->queue = queue;
450 vm_page_domain_init(int domain)
452 struct vm_domain *vmd;
453 struct vm_pagequeue *pq;
456 vmd = VM_DOMAIN(domain);
457 bzero(vmd, sizeof(*vmd));
458 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
459 "vm inactive pagequeue";
460 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
461 "vm active pagequeue";
462 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
463 "vm laundry pagequeue";
464 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_name) =
465 "vm unswappable pagequeue";
466 vmd->vmd_domain = domain;
467 vmd->vmd_page_count = 0;
468 vmd->vmd_free_count = 0;
470 vmd->vmd_oom = FALSE;
471 for (i = 0; i < PQ_COUNT; i++) {
472 pq = &vmd->vmd_pagequeues[i];
473 TAILQ_INIT(&pq->pq_pl);
474 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
475 MTX_DEF | MTX_DUPOK);
477 vm_page_init_marker(&vmd->vmd_markers[i], i, 0);
479 mtx_init(&vmd->vmd_free_mtx, "vm page free queue", NULL, MTX_DEF);
480 mtx_init(&vmd->vmd_pageout_mtx, "vm pageout lock", NULL, MTX_DEF);
481 snprintf(vmd->vmd_name, sizeof(vmd->vmd_name), "%d", domain);
484 * inacthead is used to provide FIFO ordering for LRU-bypassing
487 vm_page_init_marker(&vmd->vmd_inacthead, PQ_INACTIVE, PGA_ENQUEUED);
488 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_INACTIVE].pq_pl,
489 &vmd->vmd_inacthead, plinks.q);
492 * The clock pages are used to implement active queue scanning without
493 * requeues. Scans start at clock[0], which is advanced after the scan
494 * ends. When the two clock hands meet, they are reset and scanning
495 * resumes from the head of the queue.
497 vm_page_init_marker(&vmd->vmd_clock[0], PQ_ACTIVE, PGA_ENQUEUED);
498 vm_page_init_marker(&vmd->vmd_clock[1], PQ_ACTIVE, PGA_ENQUEUED);
499 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
500 &vmd->vmd_clock[0], plinks.q);
501 TAILQ_INSERT_TAIL(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
502 &vmd->vmd_clock[1], plinks.q);
506 * Initialize a physical page in preparation for adding it to the free
510 vm_page_init_page(vm_page_t m, vm_paddr_t pa, int segind)
515 m->busy_lock = VPB_UNBUSIED;
516 m->flags = m->aflags = 0;
521 m->order = VM_NFREEORDER;
522 m->pool = VM_FREEPOOL_DEFAULT;
523 m->valid = m->dirty = 0;
527 #ifndef PMAP_HAS_PAGE_ARRAY
529 vm_page_array_alloc(vm_offset_t *vaddr, vm_paddr_t end, vm_paddr_t page_range)
534 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
535 * However, because this page is allocated from KVM, out-of-bounds
536 * accesses using the direct map will not be trapped.
541 * Allocate physical memory for the page structures, and map it.
543 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
544 vm_page_array = (vm_page_t)pmap_map(vaddr, new_end, end,
545 VM_PROT_READ | VM_PROT_WRITE);
546 vm_page_array_size = page_range;
555 * Initializes the resident memory module. Allocates physical memory for
556 * bootstrapping UMA and some data structures that are used to manage
557 * physical pages. Initializes these structures, and populates the free
561 vm_page_startup(vm_offset_t vaddr)
563 struct vm_phys_seg *seg;
565 char *list, *listend;
567 vm_paddr_t end, high_avail, low_avail, new_end, page_range, size;
568 vm_paddr_t last_pa, pa;
570 int biggestone, i, segind;
574 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
578 vaddr = round_page(vaddr);
580 vm_phys_early_startup();
581 biggestone = vm_phys_avail_largest();
582 end = phys_avail[biggestone+1];
585 * Initialize the page and queue locks.
587 mtx_init(&vm_domainset_lock, "vm domainset lock", NULL, MTX_DEF);
588 for (i = 0; i < PA_LOCK_COUNT; i++)
589 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
590 for (i = 0; i < vm_ndomains; i++)
591 vm_page_domain_init(i);
594 * Allocate memory for use when boot strapping the kernel memory
595 * allocator. Tell UMA how many zones we are going to create
596 * before going fully functional. UMA will add its zones.
598 * VM startup zones: vmem, vmem_btag, VM OBJECT, RADIX NODE, MAP,
599 * KMAP ENTRY, MAP ENTRY, VMSPACE.
601 boot_pages = uma_startup_count(8);
603 #ifndef UMA_MD_SMALL_ALLOC
604 /* vmem_startup() calls uma_prealloc(). */
605 boot_pages += vmem_startup_count();
606 /* vm_map_startup() calls uma_prealloc(). */
607 boot_pages += howmany(MAX_KMAP,
608 UMA_SLAB_SPACE / sizeof(struct vm_map));
611 * Before going fully functional kmem_init() does allocation
612 * from "KMAP ENTRY" and vmem_create() does allocation from "vmem".
617 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
618 * manually fetch the value.
620 TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
621 new_end = end - (boot_pages * UMA_SLAB_SIZE);
622 new_end = trunc_page(new_end);
623 mapped = pmap_map(&vaddr, new_end, end,
624 VM_PROT_READ | VM_PROT_WRITE);
625 bzero((void *)mapped, end - new_end);
626 uma_startup((void *)mapped, boot_pages);
629 witness_size = round_page(witness_startup_count());
630 new_end -= witness_size;
631 mapped = pmap_map(&vaddr, new_end, new_end + witness_size,
632 VM_PROT_READ | VM_PROT_WRITE);
633 bzero((void *)mapped, witness_size);
634 witness_startup((void *)mapped);
637 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
638 defined(__i386__) || defined(__mips__) || defined(__riscv)
640 * Allocate a bitmap to indicate that a random physical page
641 * needs to be included in a minidump.
643 * The amd64 port needs this to indicate which direct map pages
644 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
646 * However, i386 still needs this workspace internally within the
647 * minidump code. In theory, they are not needed on i386, but are
648 * included should the sf_buf code decide to use them.
651 for (i = 0; dump_avail[i + 1] != 0; i += 2)
652 if (dump_avail[i + 1] > last_pa)
653 last_pa = dump_avail[i + 1];
654 page_range = last_pa / PAGE_SIZE;
655 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
656 new_end -= vm_page_dump_size;
657 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
658 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
659 bzero((void *)vm_page_dump, vm_page_dump_size);
663 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
666 * Include the UMA bootstrap pages, witness pages and vm_page_dump
667 * in a crash dump. When pmap_map() uses the direct map, they are
668 * not automatically included.
670 for (pa = new_end; pa < end; pa += PAGE_SIZE)
673 phys_avail[biggestone + 1] = new_end;
676 * Request that the physical pages underlying the message buffer be
677 * included in a crash dump. Since the message buffer is accessed
678 * through the direct map, they are not automatically included.
680 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
681 last_pa = pa + round_page(msgbufsize);
682 while (pa < last_pa) {
688 * Compute the number of pages of memory that will be available for
689 * use, taking into account the overhead of a page structure per page.
690 * In other words, solve
691 * "available physical memory" - round_page(page_range *
692 * sizeof(struct vm_page)) = page_range * PAGE_SIZE
695 low_avail = phys_avail[0];
696 high_avail = phys_avail[1];
697 for (i = 0; i < vm_phys_nsegs; i++) {
698 if (vm_phys_segs[i].start < low_avail)
699 low_avail = vm_phys_segs[i].start;
700 if (vm_phys_segs[i].end > high_avail)
701 high_avail = vm_phys_segs[i].end;
703 /* Skip the first chunk. It is already accounted for. */
704 for (i = 2; phys_avail[i + 1] != 0; i += 2) {
705 if (phys_avail[i] < low_avail)
706 low_avail = phys_avail[i];
707 if (phys_avail[i + 1] > high_avail)
708 high_avail = phys_avail[i + 1];
710 first_page = low_avail / PAGE_SIZE;
711 #ifdef VM_PHYSSEG_SPARSE
713 for (i = 0; i < vm_phys_nsegs; i++)
714 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
715 for (i = 0; phys_avail[i + 1] != 0; i += 2)
716 size += phys_avail[i + 1] - phys_avail[i];
717 #elif defined(VM_PHYSSEG_DENSE)
718 size = high_avail - low_avail;
720 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
723 #ifdef PMAP_HAS_PAGE_ARRAY
724 pmap_page_array_startup(size / PAGE_SIZE);
725 biggestone = vm_phys_avail_largest();
726 end = new_end = phys_avail[biggestone + 1];
728 #ifdef VM_PHYSSEG_DENSE
730 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
731 * the overhead of a page structure per page only if vm_page_array is
732 * allocated from the last physical memory chunk. Otherwise, we must
733 * allocate page structures representing the physical memory
734 * underlying vm_page_array, even though they will not be used.
736 if (new_end != high_avail)
737 page_range = size / PAGE_SIZE;
741 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
744 * If the partial bytes remaining are large enough for
745 * a page (PAGE_SIZE) without a corresponding
746 * 'struct vm_page', then new_end will contain an
747 * extra page after subtracting the length of the VM
748 * page array. Compensate by subtracting an extra
751 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
752 if (new_end == high_avail)
753 high_avail -= PAGE_SIZE;
754 new_end -= PAGE_SIZE;
758 new_end = vm_page_array_alloc(&vaddr, end, page_range);
761 #if VM_NRESERVLEVEL > 0
763 * Allocate physical memory for the reservation management system's
764 * data structures, and map it.
766 new_end = vm_reserv_startup(&vaddr, new_end);
768 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
771 * Include vm_page_array and vm_reserv_array in a crash dump.
773 for (pa = new_end; pa < end; pa += PAGE_SIZE)
776 phys_avail[biggestone + 1] = new_end;
779 * Add physical memory segments corresponding to the available
782 for (i = 0; phys_avail[i + 1] != 0; i += 2)
783 if (vm_phys_avail_size(i) != 0)
784 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
787 * Initialize the physical memory allocator.
792 * Initialize the page structures and add every available page to the
793 * physical memory allocator's free lists.
795 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
796 for (ii = 0; ii < vm_page_array_size; ii++) {
797 m = &vm_page_array[ii];
798 vm_page_init_page(m, (first_page + ii) << PAGE_SHIFT, 0);
799 m->flags = PG_FICTITIOUS;
802 vm_cnt.v_page_count = 0;
803 for (segind = 0; segind < vm_phys_nsegs; segind++) {
804 seg = &vm_phys_segs[segind];
805 for (m = seg->first_page, pa = seg->start; pa < seg->end;
806 m++, pa += PAGE_SIZE)
807 vm_page_init_page(m, pa, segind);
810 * Add the segment to the free lists only if it is covered by
811 * one of the ranges in phys_avail. Because we've added the
812 * ranges to the vm_phys_segs array, we can assume that each
813 * segment is either entirely contained in one of the ranges,
814 * or doesn't overlap any of them.
816 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
817 struct vm_domain *vmd;
819 if (seg->start < phys_avail[i] ||
820 seg->end > phys_avail[i + 1])
824 pagecount = (u_long)atop(seg->end - seg->start);
826 vmd = VM_DOMAIN(seg->domain);
827 vm_domain_free_lock(vmd);
828 vm_phys_enqueue_contig(m, pagecount);
829 vm_domain_free_unlock(vmd);
830 vm_domain_freecnt_inc(vmd, pagecount);
831 vm_cnt.v_page_count += (u_int)pagecount;
833 vmd = VM_DOMAIN(seg->domain);
834 vmd->vmd_page_count += (u_int)pagecount;
835 vmd->vmd_segs |= 1UL << m->segind;
841 * Remove blacklisted pages from the physical memory allocator.
843 TAILQ_INIT(&blacklist_head);
844 vm_page_blacklist_load(&list, &listend);
845 vm_page_blacklist_check(list, listend);
847 list = kern_getenv("vm.blacklist");
848 vm_page_blacklist_check(list, NULL);
851 #if VM_NRESERVLEVEL > 0
853 * Initialize the reservation management system.
862 vm_page_reference(vm_page_t m)
865 vm_page_aflag_set(m, PGA_REFERENCED);
869 * vm_page_busy_downgrade:
871 * Downgrade an exclusive busy page into a single shared busy page.
874 vm_page_busy_downgrade(vm_page_t m)
878 vm_page_assert_xbusied(m);
882 if (atomic_fcmpset_rel_int(&m->busy_lock,
883 &x, VPB_SHARERS_WORD(1)))
886 if ((x & VPB_BIT_WAITERS) != 0)
893 * Return a positive value if the page is shared busied, 0 otherwise.
896 vm_page_sbusied(vm_page_t m)
901 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
907 * Shared unbusy a page.
910 vm_page_sunbusy(vm_page_t m)
914 vm_page_assert_sbusied(m);
918 if (VPB_SHARERS(x) > 1) {
919 if (atomic_fcmpset_int(&m->busy_lock, &x,
924 KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
925 ("vm_page_sunbusy: invalid lock state"));
926 if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
928 if ((x & VPB_BIT_WAITERS) == 0)
936 * vm_page_busy_sleep:
938 * Sleep if the page is busy, using the page pointer as wchan.
939 * This is used to implement the hard-path of busying mechanism.
941 * If nonshared is true, sleep only if the page is xbusy.
943 * The object lock must be held on entry and will be released on exit.
946 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
952 vm_page_lock_assert(m, MA_NOTOWNED);
953 VM_OBJECT_ASSERT_LOCKED(obj);
957 if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
958 ((x & VPB_BIT_WAITERS) == 0 &&
959 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
965 sleepq_add(m, NULL, wmesg, 0, 0);
972 * Try to shared busy a page.
973 * If the operation succeeds 1 is returned otherwise 0.
974 * The operation never sleeps.
977 vm_page_trysbusy(vm_page_t m)
983 if ((x & VPB_BIT_SHARED) == 0)
985 if (atomic_fcmpset_acq_int(&m->busy_lock, &x,
992 * vm_page_xunbusy_hard:
994 * Called when unbusy has failed because there is a waiter.
997 vm_page_xunbusy_hard(vm_page_t m)
1000 vm_page_assert_xbusied(m);
1005 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1010 * Avoid releasing and reacquiring the same page lock.
1013 vm_page_change_lock(vm_page_t m, struct mtx **mtx)
1017 mtx1 = vm_page_lockptr(m);
1027 * vm_page_unhold_pages:
1029 * Unhold each of the pages that is referenced by the given array.
1032 vm_page_unhold_pages(vm_page_t *ma, int count)
1035 for (; count != 0; count--) {
1036 vm_page_unwire(*ma, PQ_ACTIVE);
1042 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1046 #ifdef VM_PHYSSEG_SPARSE
1047 m = vm_phys_paddr_to_vm_page(pa);
1049 m = vm_phys_fictitious_to_vm_page(pa);
1051 #elif defined(VM_PHYSSEG_DENSE)
1055 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1056 m = &vm_page_array[pi - first_page];
1059 return (vm_phys_fictitious_to_vm_page(pa));
1061 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1068 * Create a fictitious page with the specified physical address and
1069 * memory attribute. The memory attribute is the only the machine-
1070 * dependent aspect of a fictitious page that must be initialized.
1073 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1077 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1078 vm_page_initfake(m, paddr, memattr);
1083 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1086 if ((m->flags & PG_FICTITIOUS) != 0) {
1088 * The page's memattr might have changed since the
1089 * previous initialization. Update the pmap to the
1094 m->phys_addr = paddr;
1096 /* Fictitious pages don't use "segind". */
1097 m->flags = PG_FICTITIOUS;
1098 /* Fictitious pages don't use "order" or "pool". */
1099 m->oflags = VPO_UNMANAGED;
1100 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1101 /* Fictitious pages are unevictable. */
1105 pmap_page_set_memattr(m, memattr);
1111 * Release a fictitious page.
1114 vm_page_putfake(vm_page_t m)
1117 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1118 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1119 ("vm_page_putfake: bad page %p", m));
1120 uma_zfree(fakepg_zone, m);
1124 * vm_page_updatefake:
1126 * Update the given fictitious page to the specified physical address and
1130 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1133 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1134 ("vm_page_updatefake: bad page %p", m));
1135 m->phys_addr = paddr;
1136 pmap_page_set_memattr(m, memattr);
1145 vm_page_free(vm_page_t m)
1148 m->flags &= ~PG_ZERO;
1149 vm_page_free_toq(m);
1153 * vm_page_free_zero:
1155 * Free a page to the zerod-pages queue
1158 vm_page_free_zero(vm_page_t m)
1161 m->flags |= PG_ZERO;
1162 vm_page_free_toq(m);
1166 * Unbusy and handle the page queueing for a page from a getpages request that
1167 * was optionally read ahead or behind.
1170 vm_page_readahead_finish(vm_page_t m)
1173 /* We shouldn't put invalid pages on queues. */
1174 KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
1177 * Since the page is not the actually needed one, whether it should
1178 * be activated or deactivated is not obvious. Empirical results
1179 * have shown that deactivating the page is usually the best choice,
1180 * unless the page is wanted by another thread.
1183 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1184 vm_page_activate(m);
1186 vm_page_deactivate(m);
1192 * vm_page_sleep_if_busy:
1194 * Sleep and release the object lock if the page is busied.
1195 * Returns TRUE if the thread slept.
1197 * The given page must be unlocked and object containing it must
1201 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1205 vm_page_lock_assert(m, MA_NOTOWNED);
1206 VM_OBJECT_ASSERT_WLOCKED(m->object);
1208 if (vm_page_busied(m)) {
1210 * The page-specific object must be cached because page
1211 * identity can change during the sleep, causing the
1212 * re-lock of a different object.
1213 * It is assumed that a reference to the object is already
1214 * held by the callers.
1217 vm_page_busy_sleep(m, msg, false);
1218 VM_OBJECT_WLOCK(obj);
1225 * vm_page_sleep_if_xbusy:
1227 * Sleep and release the object lock if the page is xbusied.
1228 * Returns TRUE if the thread slept.
1230 * The given page must be unlocked and object containing it must
1234 vm_page_sleep_if_xbusy(vm_page_t m, const char *msg)
1238 vm_page_lock_assert(m, MA_NOTOWNED);
1239 VM_OBJECT_ASSERT_WLOCKED(m->object);
1241 if (vm_page_xbusied(m)) {
1243 * The page-specific object must be cached because page
1244 * identity can change during the sleep, causing the
1245 * re-lock of a different object.
1246 * It is assumed that a reference to the object is already
1247 * held by the callers.
1250 vm_page_busy_sleep(m, msg, true);
1251 VM_OBJECT_WLOCK(obj);
1258 * vm_page_dirty_KBI: [ internal use only ]
1260 * Set all bits in the page's dirty field.
1262 * The object containing the specified page must be locked if the
1263 * call is made from the machine-independent layer.
1265 * See vm_page_clear_dirty_mask().
1267 * This function should only be called by vm_page_dirty().
1270 vm_page_dirty_KBI(vm_page_t m)
1273 /* Refer to this operation by its public name. */
1274 KASSERT(m->valid == VM_PAGE_BITS_ALL,
1275 ("vm_page_dirty: page is invalid!"));
1276 m->dirty = VM_PAGE_BITS_ALL;
1280 * vm_page_insert: [ internal use only ]
1282 * Inserts the given mem entry into the object and object list.
1284 * The object must be locked.
1287 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1291 VM_OBJECT_ASSERT_WLOCKED(object);
1292 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1293 return (vm_page_insert_after(m, object, pindex, mpred));
1297 * vm_page_insert_after:
1299 * Inserts the page "m" into the specified object at offset "pindex".
1301 * The page "mpred" must immediately precede the offset "pindex" within
1302 * the specified object.
1304 * The object must be locked.
1307 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1312 VM_OBJECT_ASSERT_WLOCKED(object);
1313 KASSERT(m->object == NULL,
1314 ("vm_page_insert_after: page already inserted"));
1315 if (mpred != NULL) {
1316 KASSERT(mpred->object == object,
1317 ("vm_page_insert_after: object doesn't contain mpred"));
1318 KASSERT(mpred->pindex < pindex,
1319 ("vm_page_insert_after: mpred doesn't precede pindex"));
1320 msucc = TAILQ_NEXT(mpred, listq);
1322 msucc = TAILQ_FIRST(&object->memq);
1324 KASSERT(msucc->pindex > pindex,
1325 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1328 * Record the object/offset pair in this page.
1332 m->ref_count |= VPRC_OBJREF;
1335 * Now link into the object's ordered list of backed pages.
1337 if (vm_radix_insert(&object->rtree, m)) {
1340 m->ref_count &= ~VPRC_OBJREF;
1343 vm_page_insert_radixdone(m, object, mpred);
1348 * vm_page_insert_radixdone:
1350 * Complete page "m" insertion into the specified object after the
1351 * radix trie hooking.
1353 * The page "mpred" must precede the offset "m->pindex" within the
1356 * The object must be locked.
1359 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1362 VM_OBJECT_ASSERT_WLOCKED(object);
1363 KASSERT(object != NULL && m->object == object,
1364 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1365 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1366 ("vm_page_insert_radixdone: page %p is missing object ref", m));
1367 if (mpred != NULL) {
1368 KASSERT(mpred->object == object,
1369 ("vm_page_insert_radixdone: object doesn't contain mpred"));
1370 KASSERT(mpred->pindex < m->pindex,
1371 ("vm_page_insert_radixdone: mpred doesn't precede pindex"));
1375 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1377 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1380 * Show that the object has one more resident page.
1382 object->resident_page_count++;
1385 * Hold the vnode until the last page is released.
1387 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1388 vhold(object->handle);
1391 * Since we are inserting a new and possibly dirty page,
1392 * update the object's OBJ_MIGHTBEDIRTY flag.
1394 if (pmap_page_is_write_mapped(m))
1395 vm_object_set_writeable_dirty(object);
1399 * Do the work to remove a page from its object. The caller is responsible for
1400 * updating the page's fields to reflect this removal.
1403 vm_page_object_remove(vm_page_t m)
1409 VM_OBJECT_ASSERT_WLOCKED(object);
1410 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1411 ("page %p is missing its object ref", m));
1412 if (vm_page_xbusied(m))
1414 mrem = vm_radix_remove(&object->rtree, m->pindex);
1415 KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1418 * Now remove from the object's list of backed pages.
1420 TAILQ_REMOVE(&object->memq, m, listq);
1423 * And show that the object has one fewer resident page.
1425 object->resident_page_count--;
1428 * The vnode may now be recycled.
1430 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1431 vdrop(object->handle);
1437 * Removes the specified page from its containing object, but does not
1438 * invalidate any backing storage. Returns true if the object's reference
1439 * was the last reference to the page, and false otherwise.
1441 * The object must be locked.
1444 vm_page_remove(vm_page_t m)
1447 vm_page_object_remove(m);
1449 return (vm_page_drop(m, VPRC_OBJREF) == VPRC_OBJREF);
1455 * Returns the page associated with the object/offset
1456 * pair specified; if none is found, NULL is returned.
1458 * The object must be locked.
1461 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1464 VM_OBJECT_ASSERT_LOCKED(object);
1465 return (vm_radix_lookup(&object->rtree, pindex));
1469 * vm_page_find_least:
1471 * Returns the page associated with the object with least pindex
1472 * greater than or equal to the parameter pindex, or NULL.
1474 * The object must be locked.
1477 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1481 VM_OBJECT_ASSERT_LOCKED(object);
1482 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1483 m = vm_radix_lookup_ge(&object->rtree, pindex);
1488 * Returns the given page's successor (by pindex) within the object if it is
1489 * resident; if none is found, NULL is returned.
1491 * The object must be locked.
1494 vm_page_next(vm_page_t m)
1498 VM_OBJECT_ASSERT_LOCKED(m->object);
1499 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1500 MPASS(next->object == m->object);
1501 if (next->pindex != m->pindex + 1)
1508 * Returns the given page's predecessor (by pindex) within the object if it is
1509 * resident; if none is found, NULL is returned.
1511 * The object must be locked.
1514 vm_page_prev(vm_page_t m)
1518 VM_OBJECT_ASSERT_LOCKED(m->object);
1519 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1520 MPASS(prev->object == m->object);
1521 if (prev->pindex != m->pindex - 1)
1528 * Uses the page mnew as a replacement for an existing page at index
1529 * pindex which must be already present in the object.
1532 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1536 VM_OBJECT_ASSERT_WLOCKED(object);
1537 KASSERT(mnew->object == NULL && (mnew->ref_count & VPRC_OBJREF) == 0,
1538 ("vm_page_replace: page %p already in object", mnew));
1541 * This function mostly follows vm_page_insert() and
1542 * vm_page_remove() without the radix, object count and vnode
1543 * dance. Double check such functions for more comments.
1546 mnew->object = object;
1547 mnew->pindex = pindex;
1548 atomic_set_int(&mnew->ref_count, VPRC_OBJREF);
1549 mold = vm_radix_replace(&object->rtree, mnew);
1550 KASSERT(mold->queue == PQ_NONE,
1551 ("vm_page_replace: old page %p is on a paging queue", mold));
1553 /* Keep the resident page list in sorted order. */
1554 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1555 TAILQ_REMOVE(&object->memq, mold, listq);
1557 mold->object = NULL;
1558 atomic_clear_int(&mold->ref_count, VPRC_OBJREF);
1559 vm_page_xunbusy(mold);
1562 * The object's resident_page_count does not change because we have
1563 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1565 if (pmap_page_is_write_mapped(mnew))
1566 vm_object_set_writeable_dirty(object);
1573 * Move the given memory entry from its
1574 * current object to the specified target object/offset.
1576 * Note: swap associated with the page must be invalidated by the move. We
1577 * have to do this for several reasons: (1) we aren't freeing the
1578 * page, (2) we are dirtying the page, (3) the VM system is probably
1579 * moving the page from object A to B, and will then later move
1580 * the backing store from A to B and we can't have a conflict.
1582 * Note: we *always* dirty the page. It is necessary both for the
1583 * fact that we moved it, and because we may be invalidating
1586 * The objects must be locked.
1589 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1594 VM_OBJECT_ASSERT_WLOCKED(new_object);
1596 KASSERT(m->ref_count != 0, ("vm_page_rename: page %p has no refs", m));
1597 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1598 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1599 ("vm_page_rename: pindex already renamed"));
1602 * Create a custom version of vm_page_insert() which does not depend
1603 * by m_prev and can cheat on the implementation aspects of the
1607 m->pindex = new_pindex;
1608 if (vm_radix_insert(&new_object->rtree, m)) {
1614 * The operation cannot fail anymore. The removal must happen before
1615 * the listq iterator is tainted.
1618 vm_page_object_remove(m);
1620 /* Return back to the new pindex to complete vm_page_insert(). */
1621 m->pindex = new_pindex;
1622 m->object = new_object;
1624 vm_page_insert_radixdone(m, new_object, mpred);
1632 * Allocate and return a page that is associated with the specified
1633 * object and offset pair. By default, this page is exclusive busied.
1635 * The caller must always specify an allocation class.
1637 * allocation classes:
1638 * VM_ALLOC_NORMAL normal process request
1639 * VM_ALLOC_SYSTEM system *really* needs a page
1640 * VM_ALLOC_INTERRUPT interrupt time request
1642 * optional allocation flags:
1643 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1644 * intends to allocate
1645 * VM_ALLOC_NOBUSY do not exclusive busy the page
1646 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1647 * VM_ALLOC_NOOBJ page is not associated with an object and
1648 * should not be exclusive busy
1649 * VM_ALLOC_SBUSY shared busy the allocated page
1650 * VM_ALLOC_WIRED wire the allocated page
1651 * VM_ALLOC_ZERO prefer a zeroed page
1654 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1657 return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1658 vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1662 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1666 return (vm_page_alloc_domain_after(object, pindex, domain, req,
1667 object != NULL ? vm_radix_lookup_le(&object->rtree, pindex) :
1672 * Allocate a page in the specified object with the given page index. To
1673 * optimize insertion of the page into the object, the caller must also specifiy
1674 * the resident page in the object with largest index smaller than the given
1675 * page index, or NULL if no such page exists.
1678 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1679 int req, vm_page_t mpred)
1681 struct vm_domainset_iter di;
1685 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1687 m = vm_page_alloc_domain_after(object, pindex, domain, req,
1691 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
1697 * Returns true if the number of free pages exceeds the minimum
1698 * for the request class and false otherwise.
1701 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
1703 u_int limit, old, new;
1705 req = req & VM_ALLOC_CLASS_MASK;
1708 * The page daemon is allowed to dig deeper into the free page list.
1710 if (curproc == pageproc && req != VM_ALLOC_INTERRUPT)
1711 req = VM_ALLOC_SYSTEM;
1712 if (req == VM_ALLOC_INTERRUPT)
1714 else if (req == VM_ALLOC_SYSTEM)
1715 limit = vmd->vmd_interrupt_free_min;
1717 limit = vmd->vmd_free_reserved;
1720 * Attempt to reserve the pages. Fail if we're below the limit.
1723 old = vmd->vmd_free_count;
1728 } while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
1730 /* Wake the page daemon if we've crossed the threshold. */
1731 if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
1732 pagedaemon_wakeup(vmd->vmd_domain);
1734 /* Only update bitsets on transitions. */
1735 if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
1736 (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
1743 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
1744 int req, vm_page_t mpred)
1746 struct vm_domain *vmd;
1750 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1751 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1752 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1753 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1754 ("inconsistent object(%p)/req(%x)", object, req));
1755 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1756 ("Can't sleep and retry object insertion."));
1757 KASSERT(mpred == NULL || mpred->pindex < pindex,
1758 ("mpred %p doesn't precede pindex 0x%jx", mpred,
1759 (uintmax_t)pindex));
1761 VM_OBJECT_ASSERT_WLOCKED(object);
1765 pool = object != NULL ? VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT;
1767 #if VM_NRESERVLEVEL > 0
1769 * Can we allocate the page from a reservation?
1771 if (vm_object_reserv(object) &&
1772 (m = vm_reserv_alloc_page(object, pindex, domain, req, mpred)) !=
1774 domain = vm_phys_domain(m);
1775 vmd = VM_DOMAIN(domain);
1779 vmd = VM_DOMAIN(domain);
1780 if (vmd->vmd_pgcache[pool].zone != NULL) {
1781 m = uma_zalloc(vmd->vmd_pgcache[pool].zone, M_NOWAIT);
1783 flags |= PG_PCPU_CACHE;
1787 if (vm_domain_allocate(vmd, req, 1)) {
1789 * If not, allocate it from the free page queues.
1791 vm_domain_free_lock(vmd);
1792 m = vm_phys_alloc_pages(domain, pool, 0);
1793 vm_domain_free_unlock(vmd);
1795 vm_domain_freecnt_inc(vmd, 1);
1796 #if VM_NRESERVLEVEL > 0
1797 if (vm_reserv_reclaim_inactive(domain))
1804 * Not allocatable, give up.
1806 if (vm_domain_alloc_fail(vmd, object, req))
1812 * At this point we had better have found a good page.
1816 vm_page_alloc_check(m);
1819 * Initialize the page. Only the PG_ZERO flag is inherited.
1821 if ((req & VM_ALLOC_ZERO) != 0)
1822 flags |= (m->flags & PG_ZERO);
1823 if ((req & VM_ALLOC_NODUMP) != 0)
1827 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1829 m->busy_lock = VPB_UNBUSIED;
1830 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1831 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1832 if ((req & VM_ALLOC_SBUSY) != 0)
1833 m->busy_lock = VPB_SHARERS_WORD(1);
1834 if (req & VM_ALLOC_WIRED) {
1836 * The page lock is not required for wiring a page until that
1837 * page is inserted into the object.
1844 if (object != NULL) {
1845 if (vm_page_insert_after(m, object, pindex, mpred)) {
1846 if (req & VM_ALLOC_WIRED) {
1850 KASSERT(m->object == NULL, ("page %p has object", m));
1851 m->oflags = VPO_UNMANAGED;
1852 m->busy_lock = VPB_UNBUSIED;
1853 /* Don't change PG_ZERO. */
1854 vm_page_free_toq(m);
1855 if (req & VM_ALLOC_WAITFAIL) {
1856 VM_OBJECT_WUNLOCK(object);
1858 VM_OBJECT_WLOCK(object);
1863 /* Ignore device objects; the pager sets "memattr" for them. */
1864 if (object->memattr != VM_MEMATTR_DEFAULT &&
1865 (object->flags & OBJ_FICTITIOUS) == 0)
1866 pmap_page_set_memattr(m, object->memattr);
1874 * vm_page_alloc_contig:
1876 * Allocate a contiguous set of physical pages of the given size "npages"
1877 * from the free lists. All of the physical pages must be at or above
1878 * the given physical address "low" and below the given physical address
1879 * "high". The given value "alignment" determines the alignment of the
1880 * first physical page in the set. If the given value "boundary" is
1881 * non-zero, then the set of physical pages cannot cross any physical
1882 * address boundary that is a multiple of that value. Both "alignment"
1883 * and "boundary" must be a power of two.
1885 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1886 * then the memory attribute setting for the physical pages is configured
1887 * to the object's memory attribute setting. Otherwise, the memory
1888 * attribute setting for the physical pages is configured to "memattr",
1889 * overriding the object's memory attribute setting. However, if the
1890 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1891 * memory attribute setting for the physical pages cannot be configured
1892 * to VM_MEMATTR_DEFAULT.
1894 * The specified object may not contain fictitious pages.
1896 * The caller must always specify an allocation class.
1898 * allocation classes:
1899 * VM_ALLOC_NORMAL normal process request
1900 * VM_ALLOC_SYSTEM system *really* needs a page
1901 * VM_ALLOC_INTERRUPT interrupt time request
1903 * optional allocation flags:
1904 * VM_ALLOC_NOBUSY do not exclusive busy the page
1905 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1906 * VM_ALLOC_NOOBJ page is not associated with an object and
1907 * should not be exclusive busy
1908 * VM_ALLOC_SBUSY shared busy the allocated page
1909 * VM_ALLOC_WIRED wire the allocated page
1910 * VM_ALLOC_ZERO prefer a zeroed page
1913 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1914 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1915 vm_paddr_t boundary, vm_memattr_t memattr)
1917 struct vm_domainset_iter di;
1921 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1923 m = vm_page_alloc_contig_domain(object, pindex, domain, req,
1924 npages, low, high, alignment, boundary, memattr);
1927 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
1933 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1934 int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1935 vm_paddr_t boundary, vm_memattr_t memattr)
1937 struct vm_domain *vmd;
1938 vm_page_t m, m_ret, mpred;
1939 u_int busy_lock, flags, oflags;
1941 mpred = NULL; /* XXX: pacify gcc */
1942 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1943 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1944 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1945 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1946 ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
1948 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1949 ("Can't sleep and retry object insertion."));
1950 if (object != NULL) {
1951 VM_OBJECT_ASSERT_WLOCKED(object);
1952 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
1953 ("vm_page_alloc_contig: object %p has fictitious pages",
1956 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1958 if (object != NULL) {
1959 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1960 KASSERT(mpred == NULL || mpred->pindex != pindex,
1961 ("vm_page_alloc_contig: pindex already allocated"));
1965 * Can we allocate the pages without the number of free pages falling
1966 * below the lower bound for the allocation class?
1970 #if VM_NRESERVLEVEL > 0
1972 * Can we allocate the pages from a reservation?
1974 if (vm_object_reserv(object) &&
1975 (m_ret = vm_reserv_alloc_contig(object, pindex, domain, req,
1976 mpred, npages, low, high, alignment, boundary)) != NULL) {
1977 domain = vm_phys_domain(m_ret);
1978 vmd = VM_DOMAIN(domain);
1982 vmd = VM_DOMAIN(domain);
1983 if (vm_domain_allocate(vmd, req, npages)) {
1985 * allocate them from the free page queues.
1987 vm_domain_free_lock(vmd);
1988 m_ret = vm_phys_alloc_contig(domain, npages, low, high,
1989 alignment, boundary);
1990 vm_domain_free_unlock(vmd);
1991 if (m_ret == NULL) {
1992 vm_domain_freecnt_inc(vmd, npages);
1993 #if VM_NRESERVLEVEL > 0
1994 if (vm_reserv_reclaim_contig(domain, npages, low,
1995 high, alignment, boundary))
2000 if (m_ret == NULL) {
2001 if (vm_domain_alloc_fail(vmd, object, req))
2005 #if VM_NRESERVLEVEL > 0
2008 for (m = m_ret; m < &m_ret[npages]; m++) {
2010 vm_page_alloc_check(m);
2014 * Initialize the pages. Only the PG_ZERO flag is inherited.
2017 if ((req & VM_ALLOC_ZERO) != 0)
2019 if ((req & VM_ALLOC_NODUMP) != 0)
2021 oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2023 busy_lock = VPB_UNBUSIED;
2024 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2025 busy_lock = VPB_SINGLE_EXCLUSIVER;
2026 if ((req & VM_ALLOC_SBUSY) != 0)
2027 busy_lock = VPB_SHARERS_WORD(1);
2028 if ((req & VM_ALLOC_WIRED) != 0)
2029 vm_wire_add(npages);
2030 if (object != NULL) {
2031 if (object->memattr != VM_MEMATTR_DEFAULT &&
2032 memattr == VM_MEMATTR_DEFAULT)
2033 memattr = object->memattr;
2035 for (m = m_ret; m < &m_ret[npages]; m++) {
2037 m->flags = (m->flags | PG_NODUMP) & flags;
2038 m->busy_lock = busy_lock;
2039 if ((req & VM_ALLOC_WIRED) != 0)
2043 if (object != NULL) {
2044 if (vm_page_insert_after(m, object, pindex, mpred)) {
2045 if ((req & VM_ALLOC_WIRED) != 0)
2046 vm_wire_sub(npages);
2047 KASSERT(m->object == NULL,
2048 ("page %p has object", m));
2050 for (m = m_ret; m < &m_ret[npages]; m++) {
2052 (req & VM_ALLOC_WIRED) != 0)
2054 m->oflags = VPO_UNMANAGED;
2055 m->busy_lock = VPB_UNBUSIED;
2056 /* Don't change PG_ZERO. */
2057 vm_page_free_toq(m);
2059 if (req & VM_ALLOC_WAITFAIL) {
2060 VM_OBJECT_WUNLOCK(object);
2062 VM_OBJECT_WLOCK(object);
2069 if (memattr != VM_MEMATTR_DEFAULT)
2070 pmap_page_set_memattr(m, memattr);
2077 * Check a page that has been freshly dequeued from a freelist.
2080 vm_page_alloc_check(vm_page_t m)
2083 KASSERT(m->object == NULL, ("page %p has object", m));
2084 KASSERT(m->queue == PQ_NONE && (m->aflags & PGA_QUEUE_STATE_MASK) == 0,
2085 ("page %p has unexpected queue %d, flags %#x",
2086 m, m->queue, (m->aflags & PGA_QUEUE_STATE_MASK)));
2087 KASSERT(m->ref_count == 0, ("page %p has references", m));
2088 KASSERT(!vm_page_busied(m), ("page %p is busy", m));
2089 KASSERT(m->dirty == 0, ("page %p is dirty", m));
2090 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2091 ("page %p has unexpected memattr %d",
2092 m, pmap_page_get_memattr(m)));
2093 KASSERT(m->valid == 0, ("free page %p is valid", m));
2097 * vm_page_alloc_freelist:
2099 * Allocate a physical page from the specified free page list.
2101 * The caller must always specify an allocation class.
2103 * allocation classes:
2104 * VM_ALLOC_NORMAL normal process request
2105 * VM_ALLOC_SYSTEM system *really* needs a page
2106 * VM_ALLOC_INTERRUPT interrupt time request
2108 * optional allocation flags:
2109 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2110 * intends to allocate
2111 * VM_ALLOC_WIRED wire the allocated page
2112 * VM_ALLOC_ZERO prefer a zeroed page
2115 vm_page_alloc_freelist(int freelist, int req)
2117 struct vm_domainset_iter di;
2121 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2123 m = vm_page_alloc_freelist_domain(domain, freelist, req);
2126 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2132 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2134 struct vm_domain *vmd;
2139 vmd = VM_DOMAIN(domain);
2141 if (vm_domain_allocate(vmd, req, 1)) {
2142 vm_domain_free_lock(vmd);
2143 m = vm_phys_alloc_freelist_pages(domain, freelist,
2144 VM_FREEPOOL_DIRECT, 0);
2145 vm_domain_free_unlock(vmd);
2147 vm_domain_freecnt_inc(vmd, 1);
2150 if (vm_domain_alloc_fail(vmd, NULL, req))
2155 vm_page_alloc_check(m);
2158 * Initialize the page. Only the PG_ZERO flag is inherited.
2162 if ((req & VM_ALLOC_ZERO) != 0)
2165 if ((req & VM_ALLOC_WIRED) != 0) {
2167 * The page lock is not required for wiring a page that does
2168 * not belong to an object.
2173 /* Unmanaged pages don't use "act_count". */
2174 m->oflags = VPO_UNMANAGED;
2179 vm_page_zone_import(void *arg, void **store, int cnt, int domain, int flags)
2181 struct vm_domain *vmd;
2182 struct vm_pgcache *pgcache;
2186 vmd = VM_DOMAIN(pgcache->domain);
2187 /* Only import if we can bring in a full bucket. */
2188 if (cnt == 1 || !vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2190 domain = vmd->vmd_domain;
2191 vm_domain_free_lock(vmd);
2192 i = vm_phys_alloc_npages(domain, pgcache->pool, cnt,
2193 (vm_page_t *)store);
2194 vm_domain_free_unlock(vmd);
2196 vm_domain_freecnt_inc(vmd, cnt - i);
2202 vm_page_zone_release(void *arg, void **store, int cnt)
2204 struct vm_domain *vmd;
2205 struct vm_pgcache *pgcache;
2210 vmd = VM_DOMAIN(pgcache->domain);
2211 vm_domain_free_lock(vmd);
2212 for (i = 0; i < cnt; i++) {
2213 m = (vm_page_t)store[i];
2214 vm_phys_free_pages(m, 0);
2216 vm_domain_free_unlock(vmd);
2217 vm_domain_freecnt_inc(vmd, cnt);
2220 #define VPSC_ANY 0 /* No restrictions. */
2221 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2222 #define VPSC_NOSUPER 2 /* Skip superpages. */
2225 * vm_page_scan_contig:
2227 * Scan vm_page_array[] between the specified entries "m_start" and
2228 * "m_end" for a run of contiguous physical pages that satisfy the
2229 * specified conditions, and return the lowest page in the run. The
2230 * specified "alignment" determines the alignment of the lowest physical
2231 * page in the run. If the specified "boundary" is non-zero, then the
2232 * run of physical pages cannot span a physical address that is a
2233 * multiple of "boundary".
2235 * "m_end" is never dereferenced, so it need not point to a vm_page
2236 * structure within vm_page_array[].
2238 * "npages" must be greater than zero. "m_start" and "m_end" must not
2239 * span a hole (or discontiguity) in the physical address space. Both
2240 * "alignment" and "boundary" must be a power of two.
2243 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2244 u_long alignment, vm_paddr_t boundary, int options)
2250 #if VM_NRESERVLEVEL > 0
2253 int m_inc, order, run_ext, run_len;
2255 KASSERT(npages > 0, ("npages is 0"));
2256 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2257 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2261 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2262 KASSERT((m->flags & PG_MARKER) == 0,
2263 ("page %p is PG_MARKER", m));
2264 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->ref_count >= 1,
2265 ("fictitious page %p has invalid ref count", m));
2268 * If the current page would be the start of a run, check its
2269 * physical address against the end, alignment, and boundary
2270 * conditions. If it doesn't satisfy these conditions, either
2271 * terminate the scan or advance to the next page that
2272 * satisfies the failed condition.
2275 KASSERT(m_run == NULL, ("m_run != NULL"));
2276 if (m + npages > m_end)
2278 pa = VM_PAGE_TO_PHYS(m);
2279 if ((pa & (alignment - 1)) != 0) {
2280 m_inc = atop(roundup2(pa, alignment) - pa);
2283 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2285 m_inc = atop(roundup2(pa, boundary) - pa);
2289 KASSERT(m_run != NULL, ("m_run == NULL"));
2291 vm_page_change_lock(m, &m_mtx);
2294 if (vm_page_wired(m))
2296 #if VM_NRESERVLEVEL > 0
2297 else if ((level = vm_reserv_level(m)) >= 0 &&
2298 (options & VPSC_NORESERV) != 0) {
2300 /* Advance to the end of the reservation. */
2301 pa = VM_PAGE_TO_PHYS(m);
2302 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2306 else if ((object = m->object) != NULL) {
2308 * The page is considered eligible for relocation if
2309 * and only if it could be laundered or reclaimed by
2312 if (!VM_OBJECT_TRYRLOCK(object)) {
2314 VM_OBJECT_RLOCK(object);
2316 if (m->object != object) {
2318 * The page may have been freed.
2320 VM_OBJECT_RUNLOCK(object);
2324 /* Don't care: PG_NODUMP, PG_ZERO. */
2325 if (object->type != OBJT_DEFAULT &&
2326 object->type != OBJT_SWAP &&
2327 object->type != OBJT_VNODE) {
2329 #if VM_NRESERVLEVEL > 0
2330 } else if ((options & VPSC_NOSUPER) != 0 &&
2331 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2333 /* Advance to the end of the superpage. */
2334 pa = VM_PAGE_TO_PHYS(m);
2335 m_inc = atop(roundup2(pa + 1,
2336 vm_reserv_size(level)) - pa);
2338 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2339 vm_page_queue(m) != PQ_NONE && !vm_page_busied(m) &&
2340 !vm_page_wired(m)) {
2342 * The page is allocated but eligible for
2343 * relocation. Extend the current run by one
2346 KASSERT(pmap_page_get_memattr(m) ==
2348 ("page %p has an unexpected memattr", m));
2349 KASSERT((m->oflags & (VPO_SWAPINPROG |
2350 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2351 ("page %p has unexpected oflags", m));
2352 /* Don't care: VPO_NOSYNC. */
2356 VM_OBJECT_RUNLOCK(object);
2357 #if VM_NRESERVLEVEL > 0
2358 } else if (level >= 0) {
2360 * The page is reserved but not yet allocated. In
2361 * other words, it is still free. Extend the current
2366 } else if ((order = m->order) < VM_NFREEORDER) {
2368 * The page is enqueued in the physical memory
2369 * allocator's free page queues. Moreover, it is the
2370 * first page in a power-of-two-sized run of
2371 * contiguous free pages. Add these pages to the end
2372 * of the current run, and jump ahead.
2374 run_ext = 1 << order;
2378 * Skip the page for one of the following reasons: (1)
2379 * It is enqueued in the physical memory allocator's
2380 * free page queues. However, it is not the first
2381 * page in a run of contiguous free pages. (This case
2382 * rarely occurs because the scan is performed in
2383 * ascending order.) (2) It is not reserved, and it is
2384 * transitioning from free to allocated. (Conversely,
2385 * the transition from allocated to free for managed
2386 * pages is blocked by the page lock.) (3) It is
2387 * allocated but not contained by an object and not
2388 * wired, e.g., allocated by Xen's balloon driver.
2394 * Extend or reset the current run of pages.
2409 if (run_len >= npages)
2415 * vm_page_reclaim_run:
2417 * Try to relocate each of the allocated virtual pages within the
2418 * specified run of physical pages to a new physical address. Free the
2419 * physical pages underlying the relocated virtual pages. A virtual page
2420 * is relocatable if and only if it could be laundered or reclaimed by
2421 * the page daemon. Whenever possible, a virtual page is relocated to a
2422 * physical address above "high".
2424 * Returns 0 if every physical page within the run was already free or
2425 * just freed by a successful relocation. Otherwise, returns a non-zero
2426 * value indicating why the last attempt to relocate a virtual page was
2429 * "req_class" must be an allocation class.
2432 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2435 struct vm_domain *vmd;
2437 struct spglist free;
2440 vm_page_t m, m_end, m_new;
2441 int error, order, req;
2443 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2444 ("req_class is not an allocation class"));
2448 m_end = m_run + npages;
2450 for (; error == 0 && m < m_end; m++) {
2451 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2452 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2455 * Avoid releasing and reacquiring the same page lock.
2457 vm_page_change_lock(m, &m_mtx);
2460 * Racily check for wirings. Races are handled below.
2462 if (vm_page_wired(m))
2464 else if ((object = m->object) != NULL) {
2466 * The page is relocated if and only if it could be
2467 * laundered or reclaimed by the page daemon.
2469 if (!VM_OBJECT_TRYWLOCK(object)) {
2471 VM_OBJECT_WLOCK(object);
2473 if (m->object != object) {
2475 * The page may have been freed.
2477 VM_OBJECT_WUNLOCK(object);
2481 /* Don't care: PG_NODUMP, PG_ZERO. */
2482 if (object->type != OBJT_DEFAULT &&
2483 object->type != OBJT_SWAP &&
2484 object->type != OBJT_VNODE)
2486 else if (object->memattr != VM_MEMATTR_DEFAULT)
2488 else if (vm_page_queue(m) != PQ_NONE &&
2489 !vm_page_busied(m) && !vm_page_wired(m)) {
2490 KASSERT(pmap_page_get_memattr(m) ==
2492 ("page %p has an unexpected memattr", m));
2493 KASSERT((m->oflags & (VPO_SWAPINPROG |
2494 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2495 ("page %p has unexpected oflags", m));
2496 /* Don't care: VPO_NOSYNC. */
2497 if (m->valid != 0) {
2499 * First, try to allocate a new page
2500 * that is above "high". Failing
2501 * that, try to allocate a new page
2502 * that is below "m_run". Allocate
2503 * the new page between the end of
2504 * "m_run" and "high" only as a last
2507 req = req_class | VM_ALLOC_NOOBJ;
2508 if ((m->flags & PG_NODUMP) != 0)
2509 req |= VM_ALLOC_NODUMP;
2510 if (trunc_page(high) !=
2511 ~(vm_paddr_t)PAGE_MASK) {
2512 m_new = vm_page_alloc_contig(
2517 VM_MEMATTR_DEFAULT);
2520 if (m_new == NULL) {
2521 pa = VM_PAGE_TO_PHYS(m_run);
2522 m_new = vm_page_alloc_contig(
2524 0, pa - 1, PAGE_SIZE, 0,
2525 VM_MEMATTR_DEFAULT);
2527 if (m_new == NULL) {
2529 m_new = vm_page_alloc_contig(
2531 pa, high, PAGE_SIZE, 0,
2532 VM_MEMATTR_DEFAULT);
2534 if (m_new == NULL) {
2540 * Replace "m" with the new page. For
2541 * vm_page_replace(), "m" must be busy
2542 * and dequeued. Finally, change "m"
2543 * as if vm_page_free() was called.
2545 if (object->ref_count != 0 &&
2546 !vm_page_try_remove_all(m)) {
2550 m_new->aflags = m->aflags &
2551 ~PGA_QUEUE_STATE_MASK;
2552 KASSERT(m_new->oflags == VPO_UNMANAGED,
2553 ("page %p is managed", m_new));
2554 m_new->oflags = m->oflags & VPO_NOSYNC;
2555 pmap_copy_page(m, m_new);
2556 m_new->valid = m->valid;
2557 m_new->dirty = m->dirty;
2558 m->flags &= ~PG_ZERO;
2561 vm_page_replace_checked(m_new, object,
2563 if (vm_page_free_prep(m))
2564 SLIST_INSERT_HEAD(&free, m,
2568 * The new page must be deactivated
2569 * before the object is unlocked.
2571 vm_page_change_lock(m_new, &m_mtx);
2572 vm_page_deactivate(m_new);
2574 m->flags &= ~PG_ZERO;
2576 if (vm_page_free_prep(m))
2577 SLIST_INSERT_HEAD(&free, m,
2579 KASSERT(m->dirty == 0,
2580 ("page %p is dirty", m));
2585 VM_OBJECT_WUNLOCK(object);
2587 MPASS(vm_phys_domain(m) == domain);
2588 vmd = VM_DOMAIN(domain);
2589 vm_domain_free_lock(vmd);
2591 if (order < VM_NFREEORDER) {
2593 * The page is enqueued in the physical memory
2594 * allocator's free page queues. Moreover, it
2595 * is the first page in a power-of-two-sized
2596 * run of contiguous free pages. Jump ahead
2597 * to the last page within that run, and
2598 * continue from there.
2600 m += (1 << order) - 1;
2602 #if VM_NRESERVLEVEL > 0
2603 else if (vm_reserv_is_page_free(m))
2606 vm_domain_free_unlock(vmd);
2607 if (order == VM_NFREEORDER)
2613 if ((m = SLIST_FIRST(&free)) != NULL) {
2616 vmd = VM_DOMAIN(domain);
2618 vm_domain_free_lock(vmd);
2620 MPASS(vm_phys_domain(m) == domain);
2621 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2622 vm_phys_free_pages(m, 0);
2624 } while ((m = SLIST_FIRST(&free)) != NULL);
2625 vm_domain_free_unlock(vmd);
2626 vm_domain_freecnt_inc(vmd, cnt);
2633 CTASSERT(powerof2(NRUNS));
2635 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2637 #define MIN_RECLAIM 8
2640 * vm_page_reclaim_contig:
2642 * Reclaim allocated, contiguous physical memory satisfying the specified
2643 * conditions by relocating the virtual pages using that physical memory.
2644 * Returns true if reclamation is successful and false otherwise. Since
2645 * relocation requires the allocation of physical pages, reclamation may
2646 * fail due to a shortage of free pages. When reclamation fails, callers
2647 * are expected to perform vm_wait() before retrying a failed allocation
2648 * operation, e.g., vm_page_alloc_contig().
2650 * The caller must always specify an allocation class through "req".
2652 * allocation classes:
2653 * VM_ALLOC_NORMAL normal process request
2654 * VM_ALLOC_SYSTEM system *really* needs a page
2655 * VM_ALLOC_INTERRUPT interrupt time request
2657 * The optional allocation flags are ignored.
2659 * "npages" must be greater than zero. Both "alignment" and "boundary"
2660 * must be a power of two.
2663 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
2664 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2666 struct vm_domain *vmd;
2667 vm_paddr_t curr_low;
2668 vm_page_t m_run, m_runs[NRUNS];
2669 u_long count, reclaimed;
2670 int error, i, options, req_class;
2672 KASSERT(npages > 0, ("npages is 0"));
2673 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2674 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2675 req_class = req & VM_ALLOC_CLASS_MASK;
2678 * The page daemon is allowed to dig deeper into the free page list.
2680 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2681 req_class = VM_ALLOC_SYSTEM;
2684 * Return if the number of free pages cannot satisfy the requested
2687 vmd = VM_DOMAIN(domain);
2688 count = vmd->vmd_free_count;
2689 if (count < npages + vmd->vmd_free_reserved || (count < npages +
2690 vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2691 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2695 * Scan up to three times, relaxing the restrictions ("options") on
2696 * the reclamation of reservations and superpages each time.
2698 for (options = VPSC_NORESERV;;) {
2700 * Find the highest runs that satisfy the given constraints
2701 * and restrictions, and record them in "m_runs".
2706 m_run = vm_phys_scan_contig(domain, npages, curr_low,
2707 high, alignment, boundary, options);
2710 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2711 m_runs[RUN_INDEX(count)] = m_run;
2716 * Reclaim the highest runs in LIFO (descending) order until
2717 * the number of reclaimed pages, "reclaimed", is at least
2718 * MIN_RECLAIM. Reset "reclaimed" each time because each
2719 * reclamation is idempotent, and runs will (likely) recur
2720 * from one scan to the next as restrictions are relaxed.
2723 for (i = 0; count > 0 && i < NRUNS; i++) {
2725 m_run = m_runs[RUN_INDEX(count)];
2726 error = vm_page_reclaim_run(req_class, domain, npages,
2729 reclaimed += npages;
2730 if (reclaimed >= MIN_RECLAIM)
2736 * Either relax the restrictions on the next scan or return if
2737 * the last scan had no restrictions.
2739 if (options == VPSC_NORESERV)
2740 options = VPSC_NOSUPER;
2741 else if (options == VPSC_NOSUPER)
2743 else if (options == VPSC_ANY)
2744 return (reclaimed != 0);
2749 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2750 u_long alignment, vm_paddr_t boundary)
2752 struct vm_domainset_iter di;
2756 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2758 ret = vm_page_reclaim_contig_domain(domain, req, npages, low,
2759 high, alignment, boundary);
2762 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2768 * Set the domain in the appropriate page level domainset.
2771 vm_domain_set(struct vm_domain *vmd)
2774 mtx_lock(&vm_domainset_lock);
2775 if (!vmd->vmd_minset && vm_paging_min(vmd)) {
2776 vmd->vmd_minset = 1;
2777 DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
2779 if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
2780 vmd->vmd_severeset = 1;
2781 DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
2783 mtx_unlock(&vm_domainset_lock);
2787 * Clear the domain from the appropriate page level domainset.
2790 vm_domain_clear(struct vm_domain *vmd)
2793 mtx_lock(&vm_domainset_lock);
2794 if (vmd->vmd_minset && !vm_paging_min(vmd)) {
2795 vmd->vmd_minset = 0;
2796 DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
2797 if (vm_min_waiters != 0) {
2799 wakeup(&vm_min_domains);
2802 if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
2803 vmd->vmd_severeset = 0;
2804 DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
2805 if (vm_severe_waiters != 0) {
2806 vm_severe_waiters = 0;
2807 wakeup(&vm_severe_domains);
2812 * If pageout daemon needs pages, then tell it that there are
2815 if (vmd->vmd_pageout_pages_needed &&
2816 vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
2817 wakeup(&vmd->vmd_pageout_pages_needed);
2818 vmd->vmd_pageout_pages_needed = 0;
2821 /* See comments in vm_wait_doms(). */
2822 if (vm_pageproc_waiters) {
2823 vm_pageproc_waiters = 0;
2824 wakeup(&vm_pageproc_waiters);
2826 mtx_unlock(&vm_domainset_lock);
2830 * Wait for free pages to exceed the min threshold globally.
2836 mtx_lock(&vm_domainset_lock);
2837 while (vm_page_count_min()) {
2839 msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
2841 mtx_unlock(&vm_domainset_lock);
2845 * Wait for free pages to exceed the severe threshold globally.
2848 vm_wait_severe(void)
2851 mtx_lock(&vm_domainset_lock);
2852 while (vm_page_count_severe()) {
2853 vm_severe_waiters++;
2854 msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
2857 mtx_unlock(&vm_domainset_lock);
2864 return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
2868 vm_wait_doms(const domainset_t *wdoms)
2872 * We use racey wakeup synchronization to avoid expensive global
2873 * locking for the pageproc when sleeping with a non-specific vm_wait.
2874 * To handle this, we only sleep for one tick in this instance. It
2875 * is expected that most allocations for the pageproc will come from
2876 * kmem or vm_page_grab* which will use the more specific and
2877 * race-free vm_wait_domain().
2879 if (curproc == pageproc) {
2880 mtx_lock(&vm_domainset_lock);
2881 vm_pageproc_waiters++;
2882 msleep(&vm_pageproc_waiters, &vm_domainset_lock, PVM | PDROP,
2886 * XXX Ideally we would wait only until the allocation could
2887 * be satisfied. This condition can cause new allocators to
2888 * consume all freed pages while old allocators wait.
2890 mtx_lock(&vm_domainset_lock);
2891 if (vm_page_count_min_set(wdoms)) {
2893 msleep(&vm_min_domains, &vm_domainset_lock,
2894 PVM | PDROP, "vmwait", 0);
2896 mtx_unlock(&vm_domainset_lock);
2903 * Sleep until free pages are available for allocation.
2904 * - Called in various places after failed memory allocations.
2907 vm_wait_domain(int domain)
2909 struct vm_domain *vmd;
2912 vmd = VM_DOMAIN(domain);
2913 vm_domain_free_assert_unlocked(vmd);
2915 if (curproc == pageproc) {
2916 mtx_lock(&vm_domainset_lock);
2917 if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
2918 vmd->vmd_pageout_pages_needed = 1;
2919 msleep(&vmd->vmd_pageout_pages_needed,
2920 &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
2922 mtx_unlock(&vm_domainset_lock);
2924 if (pageproc == NULL)
2925 panic("vm_wait in early boot");
2926 DOMAINSET_ZERO(&wdom);
2927 DOMAINSET_SET(vmd->vmd_domain, &wdom);
2928 vm_wait_doms(&wdom);
2935 * Sleep until free pages are available for allocation in the
2936 * affinity domains of the obj. If obj is NULL, the domain set
2937 * for the calling thread is used.
2938 * Called in various places after failed memory allocations.
2941 vm_wait(vm_object_t obj)
2943 struct domainset *d;
2948 * Carefully fetch pointers only once: the struct domainset
2949 * itself is ummutable but the pointer might change.
2952 d = obj->domain.dr_policy;
2954 d = curthread->td_domain.dr_policy;
2956 vm_wait_doms(&d->ds_mask);
2960 * vm_domain_alloc_fail:
2962 * Called when a page allocation function fails. Informs the
2963 * pagedaemon and performs the requested wait. Requires the
2964 * domain_free and object lock on entry. Returns with the
2965 * object lock held and free lock released. Returns an error when
2966 * retry is necessary.
2970 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
2973 vm_domain_free_assert_unlocked(vmd);
2975 atomic_add_int(&vmd->vmd_pageout_deficit,
2976 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
2977 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
2979 VM_OBJECT_WUNLOCK(object);
2980 vm_wait_domain(vmd->vmd_domain);
2982 VM_OBJECT_WLOCK(object);
2983 if (req & VM_ALLOC_WAITOK)
2993 * Sleep until free pages are available for allocation.
2994 * - Called only in vm_fault so that processes page faulting
2995 * can be easily tracked.
2996 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2997 * processes will be able to grab memory first. Do not change
2998 * this balance without careful testing first.
3001 vm_waitpfault(struct domainset *dset, int timo)
3005 * XXX Ideally we would wait only until the allocation could
3006 * be satisfied. This condition can cause new allocators to
3007 * consume all freed pages while old allocators wait.
3009 mtx_lock(&vm_domainset_lock);
3010 if (vm_page_count_min_set(&dset->ds_mask)) {
3012 msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3015 mtx_unlock(&vm_domainset_lock);
3018 static struct vm_pagequeue *
3019 vm_page_pagequeue(vm_page_t m)
3024 if ((queue = atomic_load_8(&m->queue)) == PQ_NONE)
3026 return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue]);
3030 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m)
3032 struct vm_domain *vmd;
3035 CRITICAL_ASSERT(curthread);
3036 vm_pagequeue_assert_locked(pq);
3039 * The page daemon is allowed to set m->queue = PQ_NONE without
3040 * the page queue lock held. In this case it is about to free the page,
3041 * which must not have any queue state.
3043 qflags = atomic_load_8(&m->aflags);
3044 KASSERT(pq == vm_page_pagequeue(m) ||
3045 (qflags & PGA_QUEUE_STATE_MASK) == 0,
3046 ("page %p doesn't belong to queue %p but has aflags %#x",
3049 if ((qflags & PGA_DEQUEUE) != 0) {
3050 if (__predict_true((qflags & PGA_ENQUEUED) != 0))
3051 vm_pagequeue_remove(pq, m);
3052 vm_page_dequeue_complete(m);
3053 } else if ((qflags & (PGA_REQUEUE | PGA_REQUEUE_HEAD)) != 0) {
3054 if ((qflags & PGA_ENQUEUED) != 0)
3055 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3057 vm_pagequeue_cnt_inc(pq);
3058 vm_page_aflag_set(m, PGA_ENQUEUED);
3062 * Give PGA_REQUEUE_HEAD precedence over PGA_REQUEUE.
3063 * In particular, if both flags are set in close succession,
3064 * only PGA_REQUEUE_HEAD will be applied, even if it was set
3067 if ((qflags & PGA_REQUEUE_HEAD) != 0) {
3068 KASSERT(m->queue == PQ_INACTIVE,
3069 ("head enqueue not supported for page %p", m));
3070 vmd = vm_pagequeue_domain(m);
3071 TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3073 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3075 vm_page_aflag_clear(m, qflags & (PGA_REQUEUE |
3081 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3087 for (i = 0; i < bq->bq_cnt; i++) {
3089 if (__predict_false(m->queue != queue))
3091 vm_pqbatch_process_page(pq, m);
3093 vm_batchqueue_init(bq);
3097 * vm_page_pqbatch_submit: [ internal use only ]
3099 * Enqueue a page in the specified page queue's batched work queue.
3100 * The caller must have encoded the requested operation in the page
3101 * structure's aflags field.
3104 vm_page_pqbatch_submit(vm_page_t m, uint8_t queue)
3106 struct vm_batchqueue *bq;
3107 struct vm_pagequeue *pq;
3110 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3111 ("page %p is unmanaged", m));
3112 KASSERT(mtx_owned(vm_page_lockptr(m)) || m->object == NULL,
3113 ("missing synchronization for page %p", m));
3114 KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3116 domain = vm_phys_domain(m);
3117 pq = &vm_pagequeue_domain(m)->vmd_pagequeues[queue];
3120 bq = DPCPU_PTR(pqbatch[domain][queue]);
3121 if (vm_batchqueue_insert(bq, m)) {
3125 if (!vm_pagequeue_trylock(pq)) {
3127 vm_pagequeue_lock(pq);
3129 bq = DPCPU_PTR(pqbatch[domain][queue]);
3131 vm_pqbatch_process(pq, bq, queue);
3134 * The page may have been logically dequeued before we acquired the
3135 * page queue lock. In this case, since we either hold the page lock
3136 * or the page is being freed, a different thread cannot be concurrently
3137 * enqueuing the page.
3139 if (__predict_true(m->queue == queue))
3140 vm_pqbatch_process_page(pq, m);
3142 KASSERT(m->queue == PQ_NONE,
3143 ("invalid queue transition for page %p", m));
3144 KASSERT((m->aflags & PGA_ENQUEUED) == 0,
3145 ("page %p is enqueued with invalid queue index", m));
3147 vm_pagequeue_unlock(pq);
3152 * vm_page_pqbatch_drain: [ internal use only ]
3154 * Force all per-CPU page queue batch queues to be drained. This is
3155 * intended for use in severe memory shortages, to ensure that pages
3156 * do not remain stuck in the batch queues.
3159 vm_page_pqbatch_drain(void)
3162 struct vm_domain *vmd;
3163 struct vm_pagequeue *pq;
3164 int cpu, domain, queue;
3169 sched_bind(td, cpu);
3172 for (domain = 0; domain < vm_ndomains; domain++) {
3173 vmd = VM_DOMAIN(domain);
3174 for (queue = 0; queue < PQ_COUNT; queue++) {
3175 pq = &vmd->vmd_pagequeues[queue];
3176 vm_pagequeue_lock(pq);
3178 vm_pqbatch_process(pq,
3179 DPCPU_PTR(pqbatch[domain][queue]), queue);
3181 vm_pagequeue_unlock(pq);
3191 * Complete the logical removal of a page from a page queue. We must be
3192 * careful to synchronize with the page daemon, which may be concurrently
3193 * examining the page with only the page lock held. The page must not be
3194 * in a state where it appears to be logically enqueued.
3197 vm_page_dequeue_complete(vm_page_t m)
3201 atomic_thread_fence_rel();
3202 vm_page_aflag_clear(m, PGA_QUEUE_STATE_MASK);
3206 * vm_page_dequeue_deferred: [ internal use only ]
3208 * Request removal of the given page from its current page
3209 * queue. Physical removal from the queue may be deferred
3212 * The page must be locked.
3215 vm_page_dequeue_deferred(vm_page_t m)
3219 vm_page_assert_locked(m);
3221 if ((queue = vm_page_queue(m)) == PQ_NONE)
3225 * Set PGA_DEQUEUE if it is not already set to handle a concurrent call
3226 * to vm_page_dequeue_deferred_free(). In particular, avoid modifying
3227 * the page's queue state once vm_page_dequeue_deferred_free() has been
3228 * called. In the event of a race, two batch queue entries for the page
3229 * will be created, but the second will have no effect.
3231 if (vm_page_pqstate_cmpset(m, queue, queue, PGA_DEQUEUE, PGA_DEQUEUE))
3232 vm_page_pqbatch_submit(m, queue);
3236 * A variant of vm_page_dequeue_deferred() that does not assert the page
3237 * lock and is only to be called from vm_page_free_prep(). Because the
3238 * page is being freed, we can assume that nothing other than the page
3239 * daemon is scheduling queue operations on this page, so we get for
3240 * free the mutual exclusion that is otherwise provided by the page lock.
3241 * To handle races, the page daemon must take care to atomically check
3242 * for PGA_DEQUEUE when updating queue state.
3245 vm_page_dequeue_deferred_free(vm_page_t m)
3249 KASSERT(m->ref_count == 0, ("page %p has references", m));
3251 if ((m->aflags & PGA_DEQUEUE) != 0)
3253 atomic_thread_fence_acq();
3254 if ((queue = m->queue) == PQ_NONE)
3256 vm_page_aflag_set(m, PGA_DEQUEUE);
3257 vm_page_pqbatch_submit(m, queue);
3263 * Remove the page from whichever page queue it's in, if any.
3264 * The page must either be locked or unallocated. This constraint
3265 * ensures that the queue state of the page will remain consistent
3266 * after this function returns.
3269 vm_page_dequeue(vm_page_t m)
3271 struct vm_pagequeue *pq, *pq1;
3274 KASSERT(mtx_owned(vm_page_lockptr(m)) || m->object == NULL,
3275 ("page %p is allocated and unlocked", m));
3277 for (pq = vm_page_pagequeue(m);; pq = pq1) {
3280 * A thread may be concurrently executing
3281 * vm_page_dequeue_complete(). Ensure that all queue
3282 * state is cleared before we return.
3284 aflags = atomic_load_8(&m->aflags);
3285 if ((aflags & PGA_QUEUE_STATE_MASK) == 0)
3287 KASSERT((aflags & PGA_DEQUEUE) != 0,
3288 ("page %p has unexpected queue state flags %#x",
3292 * Busy wait until the thread updating queue state is
3293 * finished. Such a thread must be executing in a
3297 pq1 = vm_page_pagequeue(m);
3300 vm_pagequeue_lock(pq);
3301 if ((pq1 = vm_page_pagequeue(m)) == pq)
3303 vm_pagequeue_unlock(pq);
3305 KASSERT(pq == vm_page_pagequeue(m),
3306 ("%s: page %p migrated directly between queues", __func__, m));
3307 KASSERT((m->aflags & PGA_DEQUEUE) != 0 ||
3308 mtx_owned(vm_page_lockptr(m)),
3309 ("%s: queued unlocked page %p", __func__, m));
3311 if ((m->aflags & PGA_ENQUEUED) != 0)
3312 vm_pagequeue_remove(pq, m);
3313 vm_page_dequeue_complete(m);
3314 vm_pagequeue_unlock(pq);
3318 * Schedule the given page for insertion into the specified page queue.
3319 * Physical insertion of the page may be deferred indefinitely.
3322 vm_page_enqueue(vm_page_t m, uint8_t queue)
3325 vm_page_assert_locked(m);
3326 KASSERT(m->queue == PQ_NONE && (m->aflags & PGA_QUEUE_STATE_MASK) == 0,
3327 ("%s: page %p is already enqueued", __func__, m));
3330 if ((m->aflags & PGA_REQUEUE) == 0)
3331 vm_page_aflag_set(m, PGA_REQUEUE);
3332 vm_page_pqbatch_submit(m, queue);
3336 * vm_page_requeue: [ internal use only ]
3338 * Schedule a requeue of the given page.
3340 * The page must be locked.
3343 vm_page_requeue(vm_page_t m)
3346 vm_page_assert_locked(m);
3347 KASSERT(vm_page_queue(m) != PQ_NONE,
3348 ("%s: page %p is not logically enqueued", __func__, m));
3350 if ((m->aflags & PGA_REQUEUE) == 0)
3351 vm_page_aflag_set(m, PGA_REQUEUE);
3352 vm_page_pqbatch_submit(m, atomic_load_8(&m->queue));
3356 * vm_page_swapqueue: [ internal use only ]
3358 * Move the page from one queue to another, or to the tail of its
3359 * current queue, in the face of a possible concurrent call to
3360 * vm_page_dequeue_deferred_free().
3363 vm_page_swapqueue(vm_page_t m, uint8_t oldq, uint8_t newq)
3365 struct vm_pagequeue *pq;
3367 KASSERT(oldq < PQ_COUNT && newq < PQ_COUNT && oldq != newq,
3368 ("vm_page_swapqueue: invalid queues (%d, %d)", oldq, newq));
3369 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3370 ("vm_page_swapqueue: page %p is unmanaged", m));
3371 vm_page_assert_locked(m);
3374 * Atomically update the queue field and set PGA_REQUEUE while
3375 * ensuring that PGA_DEQUEUE has not been set.
3377 pq = &vm_pagequeue_domain(m)->vmd_pagequeues[oldq];
3378 vm_pagequeue_lock(pq);
3379 if (!vm_page_pqstate_cmpset(m, oldq, newq, PGA_DEQUEUE, PGA_REQUEUE)) {
3380 vm_pagequeue_unlock(pq);
3383 if ((m->aflags & PGA_ENQUEUED) != 0) {
3384 vm_pagequeue_remove(pq, m);
3385 vm_page_aflag_clear(m, PGA_ENQUEUED);
3387 vm_pagequeue_unlock(pq);
3388 vm_page_pqbatch_submit(m, newq);
3392 * vm_page_free_prep:
3394 * Prepares the given page to be put on the free list,
3395 * disassociating it from any VM object. The caller may return
3396 * the page to the free list only if this function returns true.
3398 * The object must be locked. The page must be locked if it is
3402 vm_page_free_prep(vm_page_t m)
3406 * Synchronize with threads that have dropped a reference to this
3409 atomic_thread_fence_acq();
3411 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
3412 if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
3415 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3416 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
3417 KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
3418 m, i, (uintmax_t)*p));
3421 if ((m->oflags & VPO_UNMANAGED) == 0)
3422 KASSERT(!pmap_page_is_mapped(m),
3423 ("vm_page_free_prep: freeing mapped page %p", m));
3425 KASSERT(m->queue == PQ_NONE,
3426 ("vm_page_free_prep: unmanaged page %p is queued", m));
3427 VM_CNT_INC(v_tfree);
3429 if (vm_page_sbusied(m))
3430 panic("vm_page_free_prep: freeing busy page %p", m);
3432 if (m->object != NULL) {
3433 vm_page_object_remove(m);
3436 * The object reference can be released without an atomic
3439 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
3440 m->ref_count == VPRC_OBJREF,
3441 ("vm_page_free_prep: page %p has unexpected ref_count %u",
3444 m->ref_count -= VPRC_OBJREF;
3448 * If fictitious remove object association and
3451 if ((m->flags & PG_FICTITIOUS) != 0) {
3452 KASSERT(m->ref_count == 1,
3453 ("fictitious page %p is referenced", m));
3454 KASSERT(m->queue == PQ_NONE,
3455 ("fictitious page %p is queued", m));
3460 * Pages need not be dequeued before they are returned to the physical
3461 * memory allocator, but they must at least be marked for a deferred
3464 if ((m->oflags & VPO_UNMANAGED) == 0)
3465 vm_page_dequeue_deferred_free(m);
3470 if (m->ref_count != 0)
3471 panic("vm_page_free_prep: page %p has references", m);
3474 * Restore the default memory attribute to the page.
3476 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3477 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3479 #if VM_NRESERVLEVEL > 0
3481 * Determine whether the page belongs to a reservation. If the page was
3482 * allocated from a per-CPU cache, it cannot belong to a reservation, so
3483 * as an optimization, we avoid the check in that case.
3485 if ((m->flags & PG_PCPU_CACHE) == 0 && vm_reserv_free_page(m))
3495 * Returns the given page to the free list, disassociating it
3496 * from any VM object.
3498 * The object must be locked. The page must be locked if it is
3502 vm_page_free_toq(vm_page_t m)
3504 struct vm_domain *vmd;
3507 if (!vm_page_free_prep(m))
3510 vmd = vm_pagequeue_domain(m);
3511 zone = vmd->vmd_pgcache[m->pool].zone;
3512 if ((m->flags & PG_PCPU_CACHE) != 0 && zone != NULL) {
3516 vm_domain_free_lock(vmd);
3517 vm_phys_free_pages(m, 0);
3518 vm_domain_free_unlock(vmd);
3519 vm_domain_freecnt_inc(vmd, 1);
3523 * vm_page_free_pages_toq:
3525 * Returns a list of pages to the free list, disassociating it
3526 * from any VM object. In other words, this is equivalent to
3527 * calling vm_page_free_toq() for each page of a list of VM objects.
3529 * The objects must be locked. The pages must be locked if it is
3533 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
3538 if (SLIST_EMPTY(free))
3542 while ((m = SLIST_FIRST(free)) != NULL) {
3544 SLIST_REMOVE_HEAD(free, plinks.s.ss);
3545 vm_page_free_toq(m);
3548 if (update_wire_count)
3553 * Mark this page as wired down, preventing reclamation by the page daemon
3554 * or when the containing object is destroyed.
3557 vm_page_wire(vm_page_t m)
3561 KASSERT(m->object != NULL,
3562 ("vm_page_wire: page %p does not belong to an object", m));
3563 if (!vm_page_busied(m))
3564 VM_OBJECT_ASSERT_LOCKED(m->object);
3565 KASSERT((m->flags & PG_FICTITIOUS) == 0 ||
3566 VPRC_WIRE_COUNT(m->ref_count) >= 1,
3567 ("vm_page_wire: fictitious page %p has zero wirings", m));
3569 old = atomic_fetchadd_int(&m->ref_count, 1);
3570 KASSERT(VPRC_WIRE_COUNT(old) != VPRC_WIRE_COUNT_MAX,
3571 ("vm_page_wire: counter overflow for page %p", m));
3572 if (VPRC_WIRE_COUNT(old) == 0)
3577 * Attempt to wire a mapped page following a pmap lookup of that page.
3578 * This may fail if a thread is concurrently tearing down mappings of the page.
3581 vm_page_wire_mapped(vm_page_t m)
3588 ("vm_page_wire_mapped: wiring unreferenced page %p", m));
3589 if ((old & VPRC_BLOCKED) != 0)
3591 } while (!atomic_fcmpset_int(&m->ref_count, &old, old + 1));
3593 if (VPRC_WIRE_COUNT(old) == 0)
3599 * Release one wiring of the specified page, potentially allowing it to be
3602 * Only managed pages belonging to an object can be paged out. If the number
3603 * of wirings transitions to zero and the page is eligible for page out, then
3604 * the page is added to the specified paging queue. If the released wiring
3605 * represented the last reference to the page, the page is freed.
3607 * A managed page must be locked.
3610 vm_page_unwire(vm_page_t m, uint8_t queue)
3615 KASSERT(queue < PQ_COUNT,
3616 ("vm_page_unwire: invalid queue %u request for page %p", queue, m));
3618 if ((m->oflags & VPO_UNMANAGED) != 0) {
3619 if (vm_page_unwire_noq(m) && m->ref_count == 0)
3625 * Update LRU state before releasing the wiring reference.
3626 * We only need to do this once since we hold the page lock.
3627 * Use a release store when updating the reference count to
3628 * synchronize with vm_page_free_prep().
3633 KASSERT(VPRC_WIRE_COUNT(old) > 0,
3634 ("vm_page_unwire: wire count underflow for page %p", m));
3635 if (!locked && VPRC_WIRE_COUNT(old) == 1) {
3638 if (queue == PQ_ACTIVE && vm_page_queue(m) == PQ_ACTIVE)
3639 vm_page_reference(m);
3641 vm_page_mvqueue(m, queue);
3643 } while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
3646 * Release the lock only after the wiring is released, to ensure that
3647 * the page daemon does not encounter and dequeue the page while it is
3653 if (VPRC_WIRE_COUNT(old) == 1) {
3661 * Unwire a page without (re-)inserting it into a page queue. It is up
3662 * to the caller to enqueue, requeue, or free the page as appropriate.
3663 * In most cases involving managed pages, vm_page_unwire() should be used
3667 vm_page_unwire_noq(vm_page_t m)
3671 old = vm_page_drop(m, 1);
3672 KASSERT(VPRC_WIRE_COUNT(old) != 0,
3673 ("vm_page_unref: counter underflow for page %p", m));
3674 KASSERT((m->flags & PG_FICTITIOUS) == 0 || VPRC_WIRE_COUNT(old) > 1,
3675 ("vm_page_unref: missing ref on fictitious page %p", m));
3677 if (VPRC_WIRE_COUNT(old) > 1)
3684 * Ensure that the page is in the specified page queue. If the page is
3685 * active or being moved to the active queue, ensure that its act_count is
3686 * at least ACT_INIT but do not otherwise mess with it. Otherwise, ensure that
3687 * the page is at the tail of its page queue.
3689 * The page may be wired. The caller should release its wiring reference
3690 * before releasing the page lock, otherwise the page daemon may immediately
3693 * A managed page must be locked.
3695 static __always_inline void
3696 vm_page_mvqueue(vm_page_t m, const uint8_t nqueue)
3699 vm_page_assert_locked(m);
3700 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3701 ("vm_page_mvqueue: page %p is unmanaged", m));
3703 if (vm_page_queue(m) != nqueue) {
3705 vm_page_enqueue(m, nqueue);
3706 } else if (nqueue != PQ_ACTIVE) {
3710 if (nqueue == PQ_ACTIVE && m->act_count < ACT_INIT)
3711 m->act_count = ACT_INIT;
3715 * Put the specified page on the active list (if appropriate).
3718 vm_page_activate(vm_page_t m)
3721 if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
3723 vm_page_mvqueue(m, PQ_ACTIVE);
3727 * Move the specified page to the tail of the inactive queue, or requeue
3728 * the page if it is already in the inactive queue.
3731 vm_page_deactivate(vm_page_t m)
3734 if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
3736 vm_page_mvqueue(m, PQ_INACTIVE);
3740 * Move the specified page close to the head of the inactive queue,
3741 * bypassing LRU. A marker page is used to maintain FIFO ordering.
3742 * As with regular enqueues, we use a per-CPU batch queue to reduce
3743 * contention on the page queue lock.
3746 _vm_page_deactivate_noreuse(vm_page_t m)
3749 vm_page_assert_locked(m);
3751 if (!vm_page_inactive(m)) {
3753 m->queue = PQ_INACTIVE;
3755 if ((m->aflags & PGA_REQUEUE_HEAD) == 0)
3756 vm_page_aflag_set(m, PGA_REQUEUE_HEAD);
3757 vm_page_pqbatch_submit(m, PQ_INACTIVE);
3761 vm_page_deactivate_noreuse(vm_page_t m)
3764 KASSERT(m->object != NULL,
3765 ("vm_page_deactivate_noreuse: page %p has no object", m));
3767 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_wired(m))
3768 _vm_page_deactivate_noreuse(m);
3772 * Put a page in the laundry, or requeue it if it is already there.
3775 vm_page_launder(vm_page_t m)
3778 if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
3780 vm_page_mvqueue(m, PQ_LAUNDRY);
3784 * Put a page in the PQ_UNSWAPPABLE holding queue.
3787 vm_page_unswappable(vm_page_t m)
3790 vm_page_assert_locked(m);
3791 KASSERT(!vm_page_wired(m) && (m->oflags & VPO_UNMANAGED) == 0,
3792 ("page %p already unswappable", m));
3795 vm_page_enqueue(m, PQ_UNSWAPPABLE);
3799 vm_page_release_toq(vm_page_t m, int flags)
3802 vm_page_assert_locked(m);
3805 * Use a check of the valid bits to determine whether we should
3806 * accelerate reclamation of the page. The object lock might not be
3807 * held here, in which case the check is racy. At worst we will either
3808 * accelerate reclamation of a valid page and violate LRU, or
3809 * unnecessarily defer reclamation of an invalid page.
3811 * If we were asked to not cache the page, place it near the head of the
3812 * inactive queue so that is reclaimed sooner.
3814 if ((flags & (VPR_TRYFREE | VPR_NOREUSE)) != 0 || m->valid == 0)
3815 _vm_page_deactivate_noreuse(m);
3816 else if (vm_page_active(m))
3817 vm_page_reference(m);
3819 vm_page_mvqueue(m, PQ_INACTIVE);
3823 * Unwire a page and either attempt to free it or re-add it to the page queues.
3826 vm_page_release(vm_page_t m, int flags)
3832 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3833 ("vm_page_release: page %p is unmanaged", m));
3835 if ((flags & VPR_TRYFREE) != 0) {
3837 object = (vm_object_t)atomic_load_ptr(&m->object);
3840 /* Depends on type-stability. */
3841 if (vm_page_busied(m) || !VM_OBJECT_TRYWLOCK(object)) {
3845 if (object == m->object)
3847 VM_OBJECT_WUNLOCK(object);
3849 if (__predict_true(object != NULL)) {
3850 vm_page_release_locked(m, flags);
3851 VM_OBJECT_WUNLOCK(object);
3857 * Update LRU state before releasing the wiring reference.
3858 * Use a release store when updating the reference count to
3859 * synchronize with vm_page_free_prep().
3864 KASSERT(VPRC_WIRE_COUNT(old) > 0,
3865 ("vm_page_unwire: wire count underflow for page %p", m));
3866 if (!locked && VPRC_WIRE_COUNT(old) == 1) {
3869 vm_page_release_toq(m, flags);
3871 } while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
3874 * Release the lock only after the wiring is released, to ensure that
3875 * the page daemon does not encounter and dequeue the page while it is
3881 if (VPRC_WIRE_COUNT(old) == 1) {
3888 /* See vm_page_release(). */
3890 vm_page_release_locked(vm_page_t m, int flags)
3893 VM_OBJECT_ASSERT_WLOCKED(m->object);
3894 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3895 ("vm_page_release_locked: page %p is unmanaged", m));
3897 if (vm_page_unwire_noq(m)) {
3898 if ((flags & VPR_TRYFREE) != 0 &&
3899 (m->object->ref_count == 0 || !pmap_page_is_mapped(m)) &&
3900 m->dirty == 0 && !vm_page_busied(m)) {
3904 vm_page_release_toq(m, flags);
3911 vm_page_try_blocked_op(vm_page_t m, void (*op)(vm_page_t))
3915 KASSERT(m->object != NULL && (m->oflags & VPO_UNMANAGED) == 0,
3916 ("vm_page_try_blocked_op: page %p has no object", m));
3917 KASSERT(!vm_page_busied(m),
3918 ("vm_page_try_blocked_op: page %p is busy", m));
3919 VM_OBJECT_ASSERT_LOCKED(m->object);
3924 ("vm_page_try_blocked_op: page %p has no references", m));
3925 if (VPRC_WIRE_COUNT(old) != 0)
3927 } while (!atomic_fcmpset_int(&m->ref_count, &old, old | VPRC_BLOCKED));
3932 * If the object is read-locked, new wirings may be created via an
3935 old = vm_page_drop(m, VPRC_BLOCKED);
3936 KASSERT(!VM_OBJECT_WOWNED(m->object) ||
3937 old == (VPRC_BLOCKED | VPRC_OBJREF),
3938 ("vm_page_try_blocked_op: unexpected refcount value %u for %p",
3944 * Atomically check for wirings and remove all mappings of the page.
3947 vm_page_try_remove_all(vm_page_t m)
3950 return (vm_page_try_blocked_op(m, pmap_remove_all));
3954 * Atomically check for wirings and remove all writeable mappings of the page.
3957 vm_page_try_remove_write(vm_page_t m)
3960 return (vm_page_try_blocked_op(m, pmap_remove_write));
3966 * Apply the specified advice to the given page.
3968 * The object and page must be locked.
3971 vm_page_advise(vm_page_t m, int advice)
3974 vm_page_assert_locked(m);
3975 VM_OBJECT_ASSERT_WLOCKED(m->object);
3976 if (advice == MADV_FREE)
3978 * Mark the page clean. This will allow the page to be freed
3979 * without first paging it out. MADV_FREE pages are often
3980 * quickly reused by malloc(3), so we do not do anything that
3981 * would result in a page fault on a later access.
3984 else if (advice != MADV_DONTNEED) {
3985 if (advice == MADV_WILLNEED)
3986 vm_page_activate(m);
3991 * Clear any references to the page. Otherwise, the page daemon will
3992 * immediately reactivate the page.
3994 vm_page_aflag_clear(m, PGA_REFERENCED);
3996 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
4000 * Place clean pages near the head of the inactive queue rather than
4001 * the tail, thus defeating the queue's LRU operation and ensuring that
4002 * the page will be reused quickly. Dirty pages not already in the
4003 * laundry are moved there.
4006 vm_page_deactivate_noreuse(m);
4007 else if (!vm_page_in_laundry(m))
4012 * Grab a page, waiting until we are waken up due to the page
4013 * changing state. We keep on waiting, if the page continues
4014 * to be in the object. If the page doesn't exist, first allocate it
4015 * and then conditionally zero it.
4017 * This routine may sleep.
4019 * The object must be locked on entry. The lock will, however, be released
4020 * and reacquired if the routine sleeps.
4023 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
4029 VM_OBJECT_ASSERT_WLOCKED(object);
4030 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4031 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4032 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4033 pflags = allocflags &
4034 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
4035 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4036 pflags |= VM_ALLOC_WAITFAIL;
4038 if ((m = vm_page_lookup(object, pindex)) != NULL) {
4039 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
4040 vm_page_xbusied(m) : vm_page_busied(m);
4042 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4045 * Reference the page before unlocking and
4046 * sleeping so that the page daemon is less
4047 * likely to reclaim it.
4049 vm_page_aflag_set(m, PGA_REFERENCED);
4050 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
4051 VM_ALLOC_IGN_SBUSY) != 0);
4052 VM_OBJECT_WLOCK(object);
4055 if ((allocflags & VM_ALLOC_WIRED) != 0)
4058 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
4060 if ((allocflags & VM_ALLOC_SBUSY) != 0)
4065 m = vm_page_alloc(object, pindex, pflags);
4067 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4071 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
4077 * Return the specified range of pages from the given object. For each
4078 * page offset within the range, if a page already exists within the object
4079 * at that offset and it is busy, then wait for it to change state. If,
4080 * instead, the page doesn't exist, then allocate it.
4082 * The caller must always specify an allocation class.
4084 * allocation classes:
4085 * VM_ALLOC_NORMAL normal process request
4086 * VM_ALLOC_SYSTEM system *really* needs the pages
4088 * The caller must always specify that the pages are to be busied and/or
4091 * optional allocation flags:
4092 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
4093 * VM_ALLOC_NOBUSY do not exclusive busy the page
4094 * VM_ALLOC_NOWAIT do not sleep
4095 * VM_ALLOC_SBUSY set page to sbusy state
4096 * VM_ALLOC_WIRED wire the pages
4097 * VM_ALLOC_ZERO zero and validate any invalid pages
4099 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
4100 * may return a partial prefix of the requested range.
4103 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
4104 vm_page_t *ma, int count)
4111 VM_OBJECT_ASSERT_WLOCKED(object);
4112 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
4113 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
4114 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
4115 (allocflags & VM_ALLOC_WIRED) != 0,
4116 ("vm_page_grab_pages: the pages must be busied or wired"));
4117 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4118 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4119 ("vm_page_grab_pages: VM_ALLOC_SBUSY/IGN_SBUSY mismatch"));
4122 pflags = allocflags & ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK |
4123 VM_ALLOC_WAITFAIL | VM_ALLOC_IGN_SBUSY);
4124 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4125 pflags |= VM_ALLOC_WAITFAIL;
4128 m = vm_radix_lookup_le(&object->rtree, pindex + i);
4129 if (m == NULL || m->pindex != pindex + i) {
4133 mpred = TAILQ_PREV(m, pglist, listq);
4134 for (; i < count; i++) {
4136 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
4137 vm_page_xbusied(m) : vm_page_busied(m);
4139 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4142 * Reference the page before unlocking and
4143 * sleeping so that the page daemon is less
4144 * likely to reclaim it.
4146 vm_page_aflag_set(m, PGA_REFERENCED);
4147 vm_page_busy_sleep(m, "grbmaw", (allocflags &
4148 VM_ALLOC_IGN_SBUSY) != 0);
4149 VM_OBJECT_WLOCK(object);
4152 if ((allocflags & VM_ALLOC_WIRED) != 0)
4154 if ((allocflags & (VM_ALLOC_NOBUSY |
4155 VM_ALLOC_SBUSY)) == 0)
4157 if ((allocflags & VM_ALLOC_SBUSY) != 0)
4160 m = vm_page_alloc_after(object, pindex + i,
4161 pflags | VM_ALLOC_COUNT(count - i), mpred);
4163 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4168 if (m->valid == 0 && (allocflags & VM_ALLOC_ZERO) != 0) {
4169 if ((m->flags & PG_ZERO) == 0)
4171 m->valid = VM_PAGE_BITS_ALL;
4174 m = vm_page_next(m);
4180 * Mapping function for valid or dirty bits in a page.
4182 * Inputs are required to range within a page.
4185 vm_page_bits(int base, int size)
4191 base + size <= PAGE_SIZE,
4192 ("vm_page_bits: illegal base/size %d/%d", base, size)
4195 if (size == 0) /* handle degenerate case */
4198 first_bit = base >> DEV_BSHIFT;
4199 last_bit = (base + size - 1) >> DEV_BSHIFT;
4201 return (((vm_page_bits_t)2 << last_bit) -
4202 ((vm_page_bits_t)1 << first_bit));
4206 * vm_page_set_valid_range:
4208 * Sets portions of a page valid. The arguments are expected
4209 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4210 * of any partial chunks touched by the range. The invalid portion of
4211 * such chunks will be zeroed.
4213 * (base + size) must be less then or equal to PAGE_SIZE.
4216 vm_page_set_valid_range(vm_page_t m, int base, int size)
4220 VM_OBJECT_ASSERT_WLOCKED(m->object);
4221 if (size == 0) /* handle degenerate case */
4225 * If the base is not DEV_BSIZE aligned and the valid
4226 * bit is clear, we have to zero out a portion of the
4229 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4230 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
4231 pmap_zero_page_area(m, frag, base - frag);
4234 * If the ending offset is not DEV_BSIZE aligned and the
4235 * valid bit is clear, we have to zero out a portion of
4238 endoff = base + size;
4239 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4240 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
4241 pmap_zero_page_area(m, endoff,
4242 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4245 * Assert that no previously invalid block that is now being validated
4248 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
4249 ("vm_page_set_valid_range: page %p is dirty", m));
4252 * Set valid bits inclusive of any overlap.
4254 m->valid |= vm_page_bits(base, size);
4258 * Clear the given bits from the specified page's dirty field.
4260 static __inline void
4261 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
4264 #if PAGE_SIZE < 16384
4269 * If the object is locked and the page is neither exclusive busy nor
4270 * write mapped, then the page's dirty field cannot possibly be
4271 * set by a concurrent pmap operation.
4273 VM_OBJECT_ASSERT_WLOCKED(m->object);
4274 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
4275 m->dirty &= ~pagebits;
4278 * The pmap layer can call vm_page_dirty() without
4279 * holding a distinguished lock. The combination of
4280 * the object's lock and an atomic operation suffice
4281 * to guarantee consistency of the page dirty field.
4283 * For PAGE_SIZE == 32768 case, compiler already
4284 * properly aligns the dirty field, so no forcible
4285 * alignment is needed. Only require existence of
4286 * atomic_clear_64 when page size is 32768.
4288 addr = (uintptr_t)&m->dirty;
4289 #if PAGE_SIZE == 32768
4290 atomic_clear_64((uint64_t *)addr, pagebits);
4291 #elif PAGE_SIZE == 16384
4292 atomic_clear_32((uint32_t *)addr, pagebits);
4293 #else /* PAGE_SIZE <= 8192 */
4295 * Use a trick to perform a 32-bit atomic on the
4296 * containing aligned word, to not depend on the existence
4297 * of atomic_clear_{8, 16}.
4299 shift = addr & (sizeof(uint32_t) - 1);
4300 #if BYTE_ORDER == BIG_ENDIAN
4301 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
4305 addr &= ~(sizeof(uint32_t) - 1);
4306 atomic_clear_32((uint32_t *)addr, pagebits << shift);
4307 #endif /* PAGE_SIZE */
4312 * vm_page_set_validclean:
4314 * Sets portions of a page valid and clean. The arguments are expected
4315 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4316 * of any partial chunks touched by the range. The invalid portion of
4317 * such chunks will be zero'd.
4319 * (base + size) must be less then or equal to PAGE_SIZE.
4322 vm_page_set_validclean(vm_page_t m, int base, int size)
4324 vm_page_bits_t oldvalid, pagebits;
4327 VM_OBJECT_ASSERT_WLOCKED(m->object);
4328 if (size == 0) /* handle degenerate case */
4332 * If the base is not DEV_BSIZE aligned and the valid
4333 * bit is clear, we have to zero out a portion of the
4336 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4337 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
4338 pmap_zero_page_area(m, frag, base - frag);
4341 * If the ending offset is not DEV_BSIZE aligned and the
4342 * valid bit is clear, we have to zero out a portion of
4345 endoff = base + size;
4346 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4347 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
4348 pmap_zero_page_area(m, endoff,
4349 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4352 * Set valid, clear dirty bits. If validating the entire
4353 * page we can safely clear the pmap modify bit. We also
4354 * use this opportunity to clear the VPO_NOSYNC flag. If a process
4355 * takes a write fault on a MAP_NOSYNC memory area the flag will
4358 * We set valid bits inclusive of any overlap, but we can only
4359 * clear dirty bits for DEV_BSIZE chunks that are fully within
4362 oldvalid = m->valid;
4363 pagebits = vm_page_bits(base, size);
4364 m->valid |= pagebits;
4366 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
4367 frag = DEV_BSIZE - frag;
4373 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
4375 if (base == 0 && size == PAGE_SIZE) {
4377 * The page can only be modified within the pmap if it is
4378 * mapped, and it can only be mapped if it was previously
4381 if (oldvalid == VM_PAGE_BITS_ALL)
4383 * Perform the pmap_clear_modify() first. Otherwise,
4384 * a concurrent pmap operation, such as
4385 * pmap_protect(), could clear a modification in the
4386 * pmap and set the dirty field on the page before
4387 * pmap_clear_modify() had begun and after the dirty
4388 * field was cleared here.
4390 pmap_clear_modify(m);
4392 m->oflags &= ~VPO_NOSYNC;
4393 } else if (oldvalid != VM_PAGE_BITS_ALL)
4394 m->dirty &= ~pagebits;
4396 vm_page_clear_dirty_mask(m, pagebits);
4400 vm_page_clear_dirty(vm_page_t m, int base, int size)
4403 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
4407 * vm_page_set_invalid:
4409 * Invalidates DEV_BSIZE'd chunks within a page. Both the
4410 * valid and dirty bits for the effected areas are cleared.
4413 vm_page_set_invalid(vm_page_t m, int base, int size)
4415 vm_page_bits_t bits;
4419 VM_OBJECT_ASSERT_WLOCKED(object);
4420 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
4421 size >= object->un_pager.vnp.vnp_size)
4422 bits = VM_PAGE_BITS_ALL;
4424 bits = vm_page_bits(base, size);
4425 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
4428 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
4429 !pmap_page_is_mapped(m),
4430 ("vm_page_set_invalid: page %p is mapped", m));
4436 * vm_page_zero_invalid()
4438 * The kernel assumes that the invalid portions of a page contain
4439 * garbage, but such pages can be mapped into memory by user code.
4440 * When this occurs, we must zero out the non-valid portions of the
4441 * page so user code sees what it expects.
4443 * Pages are most often semi-valid when the end of a file is mapped
4444 * into memory and the file's size is not page aligned.
4447 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
4452 VM_OBJECT_ASSERT_WLOCKED(m->object);
4454 * Scan the valid bits looking for invalid sections that
4455 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
4456 * valid bit may be set ) have already been zeroed by
4457 * vm_page_set_validclean().
4459 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
4460 if (i == (PAGE_SIZE / DEV_BSIZE) ||
4461 (m->valid & ((vm_page_bits_t)1 << i))) {
4463 pmap_zero_page_area(m,
4464 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
4471 * setvalid is TRUE when we can safely set the zero'd areas
4472 * as being valid. We can do this if there are no cache consistancy
4473 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
4476 m->valid = VM_PAGE_BITS_ALL;
4482 * Is (partial) page valid? Note that the case where size == 0
4483 * will return FALSE in the degenerate case where the page is
4484 * entirely invalid, and TRUE otherwise.
4487 vm_page_is_valid(vm_page_t m, int base, int size)
4489 vm_page_bits_t bits;
4491 VM_OBJECT_ASSERT_LOCKED(m->object);
4492 bits = vm_page_bits(base, size);
4493 return (m->valid != 0 && (m->valid & bits) == bits);
4497 * Returns true if all of the specified predicates are true for the entire
4498 * (super)page and false otherwise.
4501 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
4507 if (skip_m != NULL && skip_m->object != object)
4509 VM_OBJECT_ASSERT_LOCKED(object);
4510 npages = atop(pagesizes[m->psind]);
4513 * The physically contiguous pages that make up a superpage, i.e., a
4514 * page with a page size index ("psind") greater than zero, will
4515 * occupy adjacent entries in vm_page_array[].
4517 for (i = 0; i < npages; i++) {
4518 /* Always test object consistency, including "skip_m". */
4519 if (m[i].object != object)
4521 if (&m[i] == skip_m)
4523 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
4525 if ((flags & PS_ALL_DIRTY) != 0) {
4527 * Calling vm_page_test_dirty() or pmap_is_modified()
4528 * might stop this case from spuriously returning
4529 * "false". However, that would require a write lock
4530 * on the object containing "m[i]".
4532 if (m[i].dirty != VM_PAGE_BITS_ALL)
4535 if ((flags & PS_ALL_VALID) != 0 &&
4536 m[i].valid != VM_PAGE_BITS_ALL)
4543 * Set the page's dirty bits if the page is modified.
4546 vm_page_test_dirty(vm_page_t m)
4549 VM_OBJECT_ASSERT_WLOCKED(m->object);
4550 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
4555 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
4558 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
4562 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
4565 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
4569 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
4572 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
4575 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
4577 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
4580 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
4584 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
4587 mtx_assert_(vm_page_lockptr(m), a, file, line);
4593 vm_page_object_lock_assert(vm_page_t m)
4597 * Certain of the page's fields may only be modified by the
4598 * holder of the containing object's lock or the exclusive busy.
4599 * holder. Unfortunately, the holder of the write busy is
4600 * not recorded, and thus cannot be checked here.
4602 if (m->object != NULL && !vm_page_xbusied(m))
4603 VM_OBJECT_ASSERT_WLOCKED(m->object);
4607 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
4610 if ((bits & PGA_WRITEABLE) == 0)
4614 * The PGA_WRITEABLE flag can only be set if the page is
4615 * managed, is exclusively busied or the object is locked.
4616 * Currently, this flag is only set by pmap_enter().
4618 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4619 ("PGA_WRITEABLE on unmanaged page"));
4620 if (!vm_page_xbusied(m))
4621 VM_OBJECT_ASSERT_LOCKED(m->object);
4625 #include "opt_ddb.h"
4627 #include <sys/kernel.h>
4629 #include <ddb/ddb.h>
4631 DB_SHOW_COMMAND(page, vm_page_print_page_info)
4634 db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
4635 db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
4636 db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
4637 db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
4638 db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
4639 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
4640 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
4641 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
4642 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
4645 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
4649 db_printf("pq_free %d\n", vm_free_count());
4650 for (dom = 0; dom < vm_ndomains; dom++) {
4652 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
4654 vm_dom[dom].vmd_page_count,
4655 vm_dom[dom].vmd_free_count,
4656 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
4657 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
4658 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
4659 vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
4663 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
4666 boolean_t phys, virt;
4669 db_printf("show pginfo addr\n");
4673 phys = strchr(modif, 'p') != NULL;
4674 virt = strchr(modif, 'v') != NULL;
4676 m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
4678 m = PHYS_TO_VM_PAGE(addr);
4680 m = (vm_page_t)addr;
4682 "page %p obj %p pidx 0x%jx phys 0x%jx q %d ref %u\n"
4683 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
4684 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
4685 m->queue, m->ref_count, m->aflags, m->oflags,
4686 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);