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>
88 #include <sys/sched.h>
90 #include <sys/sysctl.h>
91 #include <sys/vmmeter.h>
92 #include <sys/vnode.h>
96 #include <vm/vm_param.h>
97 #include <vm/vm_domainset.h>
98 #include <vm/vm_kern.h>
99 #include <vm/vm_map.h>
100 #include <vm/vm_object.h>
101 #include <vm/vm_page.h>
102 #include <vm/vm_pageout.h>
103 #include <vm/vm_phys.h>
104 #include <vm/vm_pagequeue.h>
105 #include <vm/vm_pager.h>
106 #include <vm/vm_radix.h>
107 #include <vm/vm_reserv.h>
108 #include <vm/vm_extern.h>
110 #include <vm/uma_int.h>
112 #include <machine/md_var.h>
114 extern int uma_startup_count(int);
115 extern void uma_startup(void *, int);
116 extern int vmem_startup_count(void);
118 struct vm_domain vm_dom[MAXMEMDOM];
120 DPCPU_DEFINE_STATIC(struct vm_batchqueue, pqbatch[MAXMEMDOM][PQ_COUNT]);
122 struct mtx_padalign __exclusive_cache_line pa_lock[PA_LOCK_COUNT];
124 struct mtx_padalign __exclusive_cache_line vm_domainset_lock;
125 /* The following fields are protected by the domainset lock. */
126 domainset_t __exclusive_cache_line vm_min_domains;
127 domainset_t __exclusive_cache_line vm_severe_domains;
128 static int vm_min_waiters;
129 static int vm_severe_waiters;
130 static int vm_pageproc_waiters;
133 * bogus page -- for I/O to/from partially complete buffers,
134 * or for paging into sparsely invalid regions.
136 vm_page_t bogus_page;
138 vm_page_t vm_page_array;
139 long vm_page_array_size;
142 static int boot_pages;
143 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
145 "number of pages allocated for bootstrapping the VM system");
147 static int pa_tryrelock_restart;
148 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
149 &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
151 static TAILQ_HEAD(, vm_page) blacklist_head;
152 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
153 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
154 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
156 static uma_zone_t fakepg_zone;
158 static void vm_page_alloc_check(vm_page_t m);
159 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
160 static void vm_page_dequeue_complete(vm_page_t m);
161 static void vm_page_enqueue(vm_page_t m, uint8_t queue);
162 static void vm_page_init(void *dummy);
163 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
164 vm_pindex_t pindex, vm_page_t mpred);
165 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
167 static int vm_page_reclaim_run(int req_class, int domain, u_long npages,
168 vm_page_t m_run, vm_paddr_t high);
169 static int vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object,
171 static int vm_page_import(void *arg, void **store, int cnt, int domain,
173 static void vm_page_release(void *arg, void **store, int cnt);
175 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
178 vm_page_init(void *dummy)
181 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
182 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
183 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
184 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
188 * The cache page zone is initialized later since we need to be able to allocate
189 * pages before UMA is fully initialized.
192 vm_page_init_cache_zones(void *dummy __unused)
194 struct vm_domain *vmd;
197 for (i = 0; i < vm_ndomains; i++) {
200 * Don't allow the page cache to take up more than .25% of
203 if (vmd->vmd_page_count / 400 < 256 * mp_ncpus)
205 vmd->vmd_pgcache = uma_zcache_create("vm pgcache",
206 sizeof(struct vm_page), NULL, NULL, NULL, NULL,
207 vm_page_import, vm_page_release, vmd,
208 UMA_ZONE_MAXBUCKET | UMA_ZONE_VM);
209 (void )uma_zone_set_maxcache(vmd->vmd_pgcache, 0);
212 SYSINIT(vm_page2, SI_SUB_VM_CONF, SI_ORDER_ANY, vm_page_init_cache_zones, NULL);
214 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
215 #if PAGE_SIZE == 32768
217 CTASSERT(sizeof(u_long) >= 8);
222 * Try to acquire a physical address lock while a pmap is locked. If we
223 * fail to trylock we unlock and lock the pmap directly and cache the
224 * locked pa in *locked. The caller should then restart their loop in case
225 * the virtual to physical mapping has changed.
228 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
235 PA_LOCK_ASSERT(lockpa, MA_OWNED);
236 if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
243 atomic_add_int(&pa_tryrelock_restart, 1);
252 * Sets the page size, perhaps based upon the memory
253 * size. Must be called before any use of page-size
254 * dependent functions.
257 vm_set_page_size(void)
259 if (vm_cnt.v_page_size == 0)
260 vm_cnt.v_page_size = PAGE_SIZE;
261 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
262 panic("vm_set_page_size: page size not a power of two");
266 * vm_page_blacklist_next:
268 * Find the next entry in the provided string of blacklist
269 * addresses. Entries are separated by space, comma, or newline.
270 * If an invalid integer is encountered then the rest of the
271 * string is skipped. Updates the list pointer to the next
272 * character, or NULL if the string is exhausted or invalid.
275 vm_page_blacklist_next(char **list, char *end)
280 if (list == NULL || *list == NULL)
288 * If there's no end pointer then the buffer is coming from
289 * the kenv and we know it's null-terminated.
292 end = *list + strlen(*list);
294 /* Ensure that strtoq() won't walk off the end */
296 if (*end == '\n' || *end == ' ' || *end == ',')
299 printf("Blacklist not terminated, skipping\n");
305 for (pos = *list; *pos != '\0'; pos = cp) {
306 bad = strtoq(pos, &cp, 0);
307 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
316 if (*cp == '\0' || ++cp >= end)
320 return (trunc_page(bad));
322 printf("Garbage in RAM blacklist, skipping\n");
328 vm_page_blacklist_add(vm_paddr_t pa, bool verbose)
330 struct vm_domain *vmd;
334 m = vm_phys_paddr_to_vm_page(pa);
336 return (true); /* page does not exist, no failure */
338 vmd = vm_pagequeue_domain(m);
339 vm_domain_free_lock(vmd);
340 ret = vm_phys_unfree_page(m);
341 vm_domain_free_unlock(vmd);
343 vm_domain_freecnt_inc(vmd, -1);
344 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
346 printf("Skipping page with pa 0x%jx\n", (uintmax_t)pa);
352 * vm_page_blacklist_check:
354 * Iterate through the provided string of blacklist addresses, pulling
355 * each entry out of the physical allocator free list and putting it
356 * onto a list for reporting via the vm.page_blacklist sysctl.
359 vm_page_blacklist_check(char *list, char *end)
365 while (next != NULL) {
366 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
368 vm_page_blacklist_add(pa, bootverbose);
373 * vm_page_blacklist_load:
375 * Search for a special module named "ram_blacklist". It'll be a
376 * plain text file provided by the user via the loader directive
380 vm_page_blacklist_load(char **list, char **end)
389 mod = preload_search_by_type("ram_blacklist");
391 ptr = preload_fetch_addr(mod);
392 len = preload_fetch_size(mod);
403 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
410 error = sysctl_wire_old_buffer(req, 0);
413 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
414 TAILQ_FOREACH(m, &blacklist_head, listq) {
415 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
416 (uintmax_t)m->phys_addr);
419 error = sbuf_finish(&sbuf);
425 * Initialize a dummy page for use in scans of the specified paging queue.
426 * In principle, this function only needs to set the flag PG_MARKER.
427 * Nonetheless, it write busies and initializes the hold count to one as
428 * safety precautions.
431 vm_page_init_marker(vm_page_t marker, int queue, uint8_t aflags)
434 bzero(marker, sizeof(*marker));
435 marker->flags = PG_MARKER;
436 marker->aflags = aflags;
437 marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
438 marker->queue = queue;
439 marker->hold_count = 1;
443 vm_page_domain_init(int domain)
445 struct vm_domain *vmd;
446 struct vm_pagequeue *pq;
449 vmd = VM_DOMAIN(domain);
450 bzero(vmd, sizeof(*vmd));
451 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
452 "vm inactive pagequeue";
453 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
454 "vm active pagequeue";
455 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
456 "vm laundry pagequeue";
457 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_name) =
458 "vm unswappable pagequeue";
459 vmd->vmd_domain = domain;
460 vmd->vmd_page_count = 0;
461 vmd->vmd_free_count = 0;
463 vmd->vmd_oom = FALSE;
464 for (i = 0; i < PQ_COUNT; i++) {
465 pq = &vmd->vmd_pagequeues[i];
466 TAILQ_INIT(&pq->pq_pl);
467 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
468 MTX_DEF | MTX_DUPOK);
470 vm_page_init_marker(&vmd->vmd_markers[i], i, 0);
472 mtx_init(&vmd->vmd_free_mtx, "vm page free queue", NULL, MTX_DEF);
473 mtx_init(&vmd->vmd_pageout_mtx, "vm pageout lock", NULL, MTX_DEF);
474 snprintf(vmd->vmd_name, sizeof(vmd->vmd_name), "%d", domain);
477 * inacthead is used to provide FIFO ordering for LRU-bypassing
480 vm_page_init_marker(&vmd->vmd_inacthead, PQ_INACTIVE, PGA_ENQUEUED);
481 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_INACTIVE].pq_pl,
482 &vmd->vmd_inacthead, plinks.q);
485 * The clock pages are used to implement active queue scanning without
486 * requeues. Scans start at clock[0], which is advanced after the scan
487 * ends. When the two clock hands meet, they are reset and scanning
488 * resumes from the head of the queue.
490 vm_page_init_marker(&vmd->vmd_clock[0], PQ_ACTIVE, PGA_ENQUEUED);
491 vm_page_init_marker(&vmd->vmd_clock[1], PQ_ACTIVE, PGA_ENQUEUED);
492 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
493 &vmd->vmd_clock[0], plinks.q);
494 TAILQ_INSERT_TAIL(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
495 &vmd->vmd_clock[1], plinks.q);
499 * Initialize a physical page in preparation for adding it to the free
503 vm_page_init_page(vm_page_t m, vm_paddr_t pa, int segind)
508 m->busy_lock = VPB_UNBUSIED;
510 m->flags = m->aflags = 0;
515 m->order = VM_NFREEORDER;
516 m->pool = VM_FREEPOOL_DEFAULT;
517 m->valid = m->dirty = 0;
524 * Initializes the resident memory module. Allocates physical memory for
525 * bootstrapping UMA and some data structures that are used to manage
526 * physical pages. Initializes these structures, and populates the free
530 vm_page_startup(vm_offset_t vaddr)
532 struct vm_phys_seg *seg;
534 char *list, *listend;
536 vm_paddr_t end, high_avail, low_avail, new_end, page_range, size;
537 vm_paddr_t biggestsize, last_pa, pa;
539 int biggestone, i, segind;
543 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
549 vaddr = round_page(vaddr);
551 for (i = 0; phys_avail[i + 1]; i += 2) {
552 phys_avail[i] = round_page(phys_avail[i]);
553 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
555 for (i = 0; phys_avail[i + 1]; i += 2) {
556 size = phys_avail[i + 1] - phys_avail[i];
557 if (size > biggestsize) {
563 end = phys_avail[biggestone+1];
566 * Initialize the page and queue locks.
568 mtx_init(&vm_domainset_lock, "vm domainset lock", NULL, MTX_DEF);
569 for (i = 0; i < PA_LOCK_COUNT; i++)
570 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
571 for (i = 0; i < vm_ndomains; i++)
572 vm_page_domain_init(i);
575 * Allocate memory for use when boot strapping the kernel memory
576 * allocator. Tell UMA how many zones we are going to create
577 * before going fully functional. UMA will add its zones.
579 * VM startup zones: vmem, vmem_btag, VM OBJECT, RADIX NODE, MAP,
580 * KMAP ENTRY, MAP ENTRY, VMSPACE.
582 boot_pages = uma_startup_count(8);
584 #ifndef UMA_MD_SMALL_ALLOC
585 /* vmem_startup() calls uma_prealloc(). */
586 boot_pages += vmem_startup_count();
587 /* vm_map_startup() calls uma_prealloc(). */
588 boot_pages += howmany(MAX_KMAP,
589 UMA_SLAB_SPACE / sizeof(struct vm_map));
592 * Before going fully functional kmem_init() does allocation
593 * from "KMAP ENTRY" and vmem_create() does allocation from "vmem".
598 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
599 * manually fetch the value.
601 TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
602 new_end = end - (boot_pages * UMA_SLAB_SIZE);
603 new_end = trunc_page(new_end);
604 mapped = pmap_map(&vaddr, new_end, end,
605 VM_PROT_READ | VM_PROT_WRITE);
606 bzero((void *)mapped, end - new_end);
607 uma_startup((void *)mapped, boot_pages);
610 witness_size = round_page(witness_startup_count());
611 new_end -= witness_size;
612 mapped = pmap_map(&vaddr, new_end, new_end + witness_size,
613 VM_PROT_READ | VM_PROT_WRITE);
614 bzero((void *)mapped, witness_size);
615 witness_startup((void *)mapped);
618 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
619 defined(__i386__) || defined(__mips__) || defined(__riscv)
621 * Allocate a bitmap to indicate that a random physical page
622 * needs to be included in a minidump.
624 * The amd64 port needs this to indicate which direct map pages
625 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
627 * However, i386 still needs this workspace internally within the
628 * minidump code. In theory, they are not needed on i386, but are
629 * included should the sf_buf code decide to use them.
632 for (i = 0; dump_avail[i + 1] != 0; i += 2)
633 if (dump_avail[i + 1] > last_pa)
634 last_pa = dump_avail[i + 1];
635 page_range = last_pa / PAGE_SIZE;
636 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
637 new_end -= vm_page_dump_size;
638 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
639 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
640 bzero((void *)vm_page_dump, vm_page_dump_size);
644 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
647 * Include the UMA bootstrap pages, witness pages and vm_page_dump
648 * in a crash dump. When pmap_map() uses the direct map, they are
649 * not automatically included.
651 for (pa = new_end; pa < end; pa += PAGE_SIZE)
654 phys_avail[biggestone + 1] = new_end;
657 * Request that the physical pages underlying the message buffer be
658 * included in a crash dump. Since the message buffer is accessed
659 * through the direct map, they are not automatically included.
661 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
662 last_pa = pa + round_page(msgbufsize);
663 while (pa < last_pa) {
669 * Compute the number of pages of memory that will be available for
670 * use, taking into account the overhead of a page structure per page.
671 * In other words, solve
672 * "available physical memory" - round_page(page_range *
673 * sizeof(struct vm_page)) = page_range * PAGE_SIZE
676 low_avail = phys_avail[0];
677 high_avail = phys_avail[1];
678 for (i = 0; i < vm_phys_nsegs; i++) {
679 if (vm_phys_segs[i].start < low_avail)
680 low_avail = vm_phys_segs[i].start;
681 if (vm_phys_segs[i].end > high_avail)
682 high_avail = vm_phys_segs[i].end;
684 /* Skip the first chunk. It is already accounted for. */
685 for (i = 2; phys_avail[i + 1] != 0; i += 2) {
686 if (phys_avail[i] < low_avail)
687 low_avail = phys_avail[i];
688 if (phys_avail[i + 1] > high_avail)
689 high_avail = phys_avail[i + 1];
691 first_page = low_avail / PAGE_SIZE;
692 #ifdef VM_PHYSSEG_SPARSE
694 for (i = 0; i < vm_phys_nsegs; i++)
695 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
696 for (i = 0; phys_avail[i + 1] != 0; i += 2)
697 size += phys_avail[i + 1] - phys_avail[i];
698 #elif defined(VM_PHYSSEG_DENSE)
699 size = high_avail - low_avail;
701 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
704 #ifdef VM_PHYSSEG_DENSE
706 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
707 * the overhead of a page structure per page only if vm_page_array is
708 * allocated from the last physical memory chunk. Otherwise, we must
709 * allocate page structures representing the physical memory
710 * underlying vm_page_array, even though they will not be used.
712 if (new_end != high_avail)
713 page_range = size / PAGE_SIZE;
717 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
720 * If the partial bytes remaining are large enough for
721 * a page (PAGE_SIZE) without a corresponding
722 * 'struct vm_page', then new_end will contain an
723 * extra page after subtracting the length of the VM
724 * page array. Compensate by subtracting an extra
727 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
728 if (new_end == high_avail)
729 high_avail -= PAGE_SIZE;
730 new_end -= PAGE_SIZE;
736 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
737 * However, because this page is allocated from KVM, out-of-bounds
738 * accesses using the direct map will not be trapped.
743 * Allocate physical memory for the page structures, and map it.
745 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
746 mapped = pmap_map(&vaddr, new_end, end,
747 VM_PROT_READ | VM_PROT_WRITE);
748 vm_page_array = (vm_page_t)mapped;
749 vm_page_array_size = page_range;
751 #if VM_NRESERVLEVEL > 0
753 * Allocate physical memory for the reservation management system's
754 * data structures, and map it.
756 if (high_avail == end)
757 high_avail = new_end;
758 new_end = vm_reserv_startup(&vaddr, new_end, high_avail);
760 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
763 * Include vm_page_array and vm_reserv_array in a crash dump.
765 for (pa = new_end; pa < end; pa += PAGE_SIZE)
768 phys_avail[biggestone + 1] = new_end;
771 * Add physical memory segments corresponding to the available
774 for (i = 0; phys_avail[i + 1] != 0; i += 2)
775 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
778 * Initialize the physical memory allocator.
783 * Initialize the page structures and add every available page to the
784 * physical memory allocator's free lists.
786 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
787 for (ii = 0; ii < vm_page_array_size; ii++) {
788 m = &vm_page_array[ii];
789 vm_page_init_page(m, (first_page + ii) << PAGE_SHIFT, 0);
790 m->flags = PG_FICTITIOUS;
793 vm_cnt.v_page_count = 0;
794 for (segind = 0; segind < vm_phys_nsegs; segind++) {
795 seg = &vm_phys_segs[segind];
796 for (m = seg->first_page, pa = seg->start; pa < seg->end;
797 m++, pa += PAGE_SIZE)
798 vm_page_init_page(m, pa, segind);
801 * Add the segment to the free lists only if it is covered by
802 * one of the ranges in phys_avail. Because we've added the
803 * ranges to the vm_phys_segs array, we can assume that each
804 * segment is either entirely contained in one of the ranges,
805 * or doesn't overlap any of them.
807 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
808 struct vm_domain *vmd;
810 if (seg->start < phys_avail[i] ||
811 seg->end > phys_avail[i + 1])
815 pagecount = (u_long)atop(seg->end - seg->start);
817 vmd = VM_DOMAIN(seg->domain);
818 vm_domain_free_lock(vmd);
819 vm_phys_enqueue_contig(m, pagecount);
820 vm_domain_free_unlock(vmd);
821 vm_domain_freecnt_inc(vmd, pagecount);
822 vm_cnt.v_page_count += (u_int)pagecount;
824 vmd = VM_DOMAIN(seg->domain);
825 vmd->vmd_page_count += (u_int)pagecount;
826 vmd->vmd_segs |= 1UL << m->segind;
832 * Remove blacklisted pages from the physical memory allocator.
834 TAILQ_INIT(&blacklist_head);
835 vm_page_blacklist_load(&list, &listend);
836 vm_page_blacklist_check(list, listend);
838 list = kern_getenv("vm.blacklist");
839 vm_page_blacklist_check(list, NULL);
842 #if VM_NRESERVLEVEL > 0
844 * Initialize the reservation management system.
853 vm_page_reference(vm_page_t m)
856 vm_page_aflag_set(m, PGA_REFERENCED);
860 * vm_page_busy_downgrade:
862 * Downgrade an exclusive busy page into a single shared busy page.
865 vm_page_busy_downgrade(vm_page_t m)
870 vm_page_assert_xbusied(m);
871 locked = mtx_owned(vm_page_lockptr(m));
875 x &= VPB_BIT_WAITERS;
876 if (x != 0 && !locked)
878 if (atomic_cmpset_rel_int(&m->busy_lock,
879 VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1)))
881 if (x != 0 && !locked)
894 * Return a positive value if the page is shared busied, 0 otherwise.
897 vm_page_sbusied(vm_page_t m)
902 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
908 * Shared unbusy a page.
911 vm_page_sunbusy(vm_page_t m)
915 vm_page_lock_assert(m, MA_NOTOWNED);
916 vm_page_assert_sbusied(m);
920 if (VPB_SHARERS(x) > 1) {
921 if (atomic_cmpset_int(&m->busy_lock, x,
926 if ((x & VPB_BIT_WAITERS) == 0) {
927 KASSERT(x == VPB_SHARERS_WORD(1),
928 ("vm_page_sunbusy: invalid lock state"));
929 if (atomic_cmpset_int(&m->busy_lock,
930 VPB_SHARERS_WORD(1), VPB_UNBUSIED))
934 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
935 ("vm_page_sunbusy: invalid lock state for waiters"));
938 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
949 * vm_page_busy_sleep:
951 * Sleep and release the page lock, using the page pointer as wchan.
952 * This is used to implement the hard-path of busying mechanism.
954 * The given page must be locked.
956 * If nonshared is true, sleep only if the page is xbusy.
959 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
963 vm_page_assert_locked(m);
966 if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
967 ((x & VPB_BIT_WAITERS) == 0 &&
968 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
972 msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
978 * Try to shared busy a page.
979 * If the operation succeeds 1 is returned otherwise 0.
980 * The operation never sleeps.
983 vm_page_trysbusy(vm_page_t m)
989 if ((x & VPB_BIT_SHARED) == 0)
991 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
997 vm_page_xunbusy_locked(vm_page_t m)
1000 vm_page_assert_xbusied(m);
1001 vm_page_assert_locked(m);
1003 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1004 /* There is a waiter, do wakeup() instead of vm_page_flash(). */
1009 vm_page_xunbusy_maybelocked(vm_page_t m)
1013 vm_page_assert_xbusied(m);
1016 * Fast path for unbusy. If it succeeds, we know that there
1017 * are no waiters, so we do not need a wakeup.
1019 if (atomic_cmpset_rel_int(&m->busy_lock, VPB_SINGLE_EXCLUSIVER,
1023 lockacq = !mtx_owned(vm_page_lockptr(m));
1026 vm_page_xunbusy_locked(m);
1032 * vm_page_xunbusy_hard:
1034 * Called after the first try the exclusive unbusy of a page failed.
1035 * It is assumed that the waiters bit is on.
1038 vm_page_xunbusy_hard(vm_page_t m)
1041 vm_page_assert_xbusied(m);
1044 vm_page_xunbusy_locked(m);
1051 * Wakeup anyone waiting for the page.
1052 * The ownership bits do not change.
1054 * The given page must be locked.
1057 vm_page_flash(vm_page_t m)
1061 vm_page_lock_assert(m, MA_OWNED);
1065 if ((x & VPB_BIT_WAITERS) == 0)
1067 if (atomic_cmpset_int(&m->busy_lock, x,
1068 x & (~VPB_BIT_WAITERS)))
1075 * Avoid releasing and reacquiring the same page lock.
1078 vm_page_change_lock(vm_page_t m, struct mtx **mtx)
1082 mtx1 = vm_page_lockptr(m);
1092 * Keep page from being freed by the page daemon
1093 * much of the same effect as wiring, except much lower
1094 * overhead and should be used only for *very* temporary
1095 * holding ("wiring").
1098 vm_page_hold(vm_page_t mem)
1101 vm_page_lock_assert(mem, MA_OWNED);
1106 vm_page_unhold(vm_page_t mem)
1109 vm_page_lock_assert(mem, MA_OWNED);
1110 KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
1112 if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
1113 vm_page_free_toq(mem);
1117 * vm_page_unhold_pages:
1119 * Unhold each of the pages that is referenced by the given array.
1122 vm_page_unhold_pages(vm_page_t *ma, int count)
1127 for (; count != 0; count--) {
1128 vm_page_change_lock(*ma, &mtx);
1129 vm_page_unhold(*ma);
1137 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1141 #ifdef VM_PHYSSEG_SPARSE
1142 m = vm_phys_paddr_to_vm_page(pa);
1144 m = vm_phys_fictitious_to_vm_page(pa);
1146 #elif defined(VM_PHYSSEG_DENSE)
1150 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1151 m = &vm_page_array[pi - first_page];
1154 return (vm_phys_fictitious_to_vm_page(pa));
1156 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1163 * Create a fictitious page with the specified physical address and
1164 * memory attribute. The memory attribute is the only the machine-
1165 * dependent aspect of a fictitious page that must be initialized.
1168 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1172 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1173 vm_page_initfake(m, paddr, memattr);
1178 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1181 if ((m->flags & PG_FICTITIOUS) != 0) {
1183 * The page's memattr might have changed since the
1184 * previous initialization. Update the pmap to the
1189 m->phys_addr = paddr;
1191 /* Fictitious pages don't use "segind". */
1192 m->flags = PG_FICTITIOUS;
1193 /* Fictitious pages don't use "order" or "pool". */
1194 m->oflags = VPO_UNMANAGED;
1195 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1199 pmap_page_set_memattr(m, memattr);
1205 * Release a fictitious page.
1208 vm_page_putfake(vm_page_t m)
1211 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1212 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1213 ("vm_page_putfake: bad page %p", m));
1214 uma_zfree(fakepg_zone, m);
1218 * vm_page_updatefake:
1220 * Update the given fictitious page to the specified physical address and
1224 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1227 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1228 ("vm_page_updatefake: bad page %p", m));
1229 m->phys_addr = paddr;
1230 pmap_page_set_memattr(m, memattr);
1239 vm_page_free(vm_page_t m)
1242 m->flags &= ~PG_ZERO;
1243 vm_page_free_toq(m);
1247 * vm_page_free_zero:
1249 * Free a page to the zerod-pages queue
1252 vm_page_free_zero(vm_page_t m)
1255 m->flags |= PG_ZERO;
1256 vm_page_free_toq(m);
1260 * Unbusy and handle the page queueing for a page from a getpages request that
1261 * was optionally read ahead or behind.
1264 vm_page_readahead_finish(vm_page_t m)
1267 /* We shouldn't put invalid pages on queues. */
1268 KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
1271 * Since the page is not the actually needed one, whether it should
1272 * be activated or deactivated is not obvious. Empirical results
1273 * have shown that deactivating the page is usually the best choice,
1274 * unless the page is wanted by another thread.
1277 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1278 vm_page_activate(m);
1280 vm_page_deactivate(m);
1286 * vm_page_sleep_if_busy:
1288 * Sleep and release the page queues lock if the page is busied.
1289 * Returns TRUE if the thread slept.
1291 * The given page must be unlocked and object containing it must
1295 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1299 vm_page_lock_assert(m, MA_NOTOWNED);
1300 VM_OBJECT_ASSERT_WLOCKED(m->object);
1302 if (vm_page_busied(m)) {
1304 * The page-specific object must be cached because page
1305 * identity can change during the sleep, causing the
1306 * re-lock of a different object.
1307 * It is assumed that a reference to the object is already
1308 * held by the callers.
1312 VM_OBJECT_WUNLOCK(obj);
1313 vm_page_busy_sleep(m, msg, false);
1314 VM_OBJECT_WLOCK(obj);
1321 * vm_page_dirty_KBI: [ internal use only ]
1323 * Set all bits in the page's dirty field.
1325 * The object containing the specified page must be locked if the
1326 * call is made from the machine-independent layer.
1328 * See vm_page_clear_dirty_mask().
1330 * This function should only be called by vm_page_dirty().
1333 vm_page_dirty_KBI(vm_page_t m)
1336 /* Refer to this operation by its public name. */
1337 KASSERT(m->valid == VM_PAGE_BITS_ALL,
1338 ("vm_page_dirty: page is invalid!"));
1339 m->dirty = VM_PAGE_BITS_ALL;
1343 * vm_page_insert: [ internal use only ]
1345 * Inserts the given mem entry into the object and object list.
1347 * The object must be locked.
1350 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1354 VM_OBJECT_ASSERT_WLOCKED(object);
1355 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1356 return (vm_page_insert_after(m, object, pindex, mpred));
1360 * vm_page_insert_after:
1362 * Inserts the page "m" into the specified object at offset "pindex".
1364 * The page "mpred" must immediately precede the offset "pindex" within
1365 * the specified object.
1367 * The object must be locked.
1370 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1375 VM_OBJECT_ASSERT_WLOCKED(object);
1376 KASSERT(m->object == NULL,
1377 ("vm_page_insert_after: page already inserted"));
1378 if (mpred != NULL) {
1379 KASSERT(mpred->object == object,
1380 ("vm_page_insert_after: object doesn't contain mpred"));
1381 KASSERT(mpred->pindex < pindex,
1382 ("vm_page_insert_after: mpred doesn't precede pindex"));
1383 msucc = TAILQ_NEXT(mpred, listq);
1385 msucc = TAILQ_FIRST(&object->memq);
1387 KASSERT(msucc->pindex > pindex,
1388 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1391 * Record the object/offset pair in this page
1397 * Now link into the object's ordered list of backed pages.
1399 if (vm_radix_insert(&object->rtree, m)) {
1404 vm_page_insert_radixdone(m, object, mpred);
1409 * vm_page_insert_radixdone:
1411 * Complete page "m" insertion into the specified object after the
1412 * radix trie hooking.
1414 * The page "mpred" must precede the offset "m->pindex" within the
1417 * The object must be locked.
1420 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1423 VM_OBJECT_ASSERT_WLOCKED(object);
1424 KASSERT(object != NULL && m->object == object,
1425 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1426 if (mpred != NULL) {
1427 KASSERT(mpred->object == object,
1428 ("vm_page_insert_after: object doesn't contain mpred"));
1429 KASSERT(mpred->pindex < m->pindex,
1430 ("vm_page_insert_after: mpred doesn't precede pindex"));
1434 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1436 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1439 * Show that the object has one more resident page.
1441 object->resident_page_count++;
1444 * Hold the vnode until the last page is released.
1446 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1447 vhold(object->handle);
1450 * Since we are inserting a new and possibly dirty page,
1451 * update the object's OBJ_MIGHTBEDIRTY flag.
1453 if (pmap_page_is_write_mapped(m))
1454 vm_object_set_writeable_dirty(object);
1460 * Removes the specified page from its containing object, but does not
1461 * invalidate any backing storage. Return true if the page may be safely
1462 * freed and false otherwise.
1464 * The object must be locked. The page must be locked if it is managed.
1467 vm_page_remove(vm_page_t m)
1474 if ((m->oflags & VPO_UNMANAGED) == 0)
1475 vm_page_assert_locked(m);
1476 VM_OBJECT_ASSERT_WLOCKED(object);
1477 if (vm_page_xbusied(m))
1478 vm_page_xunbusy_maybelocked(m);
1479 mrem = vm_radix_remove(&object->rtree, m->pindex);
1480 KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1483 * Now remove from the object's list of backed pages.
1485 TAILQ_REMOVE(&object->memq, m, listq);
1488 * And show that the object has one fewer resident page.
1490 object->resident_page_count--;
1493 * The vnode may now be recycled.
1495 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1496 vdrop(object->handle);
1499 return (!vm_page_wired(m));
1505 * Returns the page associated with the object/offset
1506 * pair specified; if none is found, NULL is returned.
1508 * The object must be locked.
1511 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1514 VM_OBJECT_ASSERT_LOCKED(object);
1515 return (vm_radix_lookup(&object->rtree, pindex));
1519 * vm_page_find_least:
1521 * Returns the page associated with the object with least pindex
1522 * greater than or equal to the parameter pindex, or NULL.
1524 * The object must be locked.
1527 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1531 VM_OBJECT_ASSERT_LOCKED(object);
1532 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1533 m = vm_radix_lookup_ge(&object->rtree, pindex);
1538 * Returns the given page's successor (by pindex) within the object if it is
1539 * resident; if none is found, NULL is returned.
1541 * The object must be locked.
1544 vm_page_next(vm_page_t m)
1548 VM_OBJECT_ASSERT_LOCKED(m->object);
1549 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1550 MPASS(next->object == m->object);
1551 if (next->pindex != m->pindex + 1)
1558 * Returns the given page's predecessor (by pindex) within the object if it is
1559 * resident; if none is found, NULL is returned.
1561 * The object must be locked.
1564 vm_page_prev(vm_page_t m)
1568 VM_OBJECT_ASSERT_LOCKED(m->object);
1569 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1570 MPASS(prev->object == m->object);
1571 if (prev->pindex != m->pindex - 1)
1578 * Uses the page mnew as a replacement for an existing page at index
1579 * pindex which must be already present in the object.
1581 * The existing page must not be on a paging queue.
1584 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1588 VM_OBJECT_ASSERT_WLOCKED(object);
1589 KASSERT(mnew->object == NULL,
1590 ("vm_page_replace: page %p already in object", mnew));
1591 KASSERT(mnew->queue == PQ_NONE,
1592 ("vm_page_replace: new page %p is on a paging queue", mnew));
1595 * This function mostly follows vm_page_insert() and
1596 * vm_page_remove() without the radix, object count and vnode
1597 * dance. Double check such functions for more comments.
1600 mnew->object = object;
1601 mnew->pindex = pindex;
1602 mold = vm_radix_replace(&object->rtree, mnew);
1603 KASSERT(mold->queue == PQ_NONE,
1604 ("vm_page_replace: old page %p is on a paging queue", mold));
1606 /* Keep the resident page list in sorted order. */
1607 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1608 TAILQ_REMOVE(&object->memq, mold, listq);
1610 mold->object = NULL;
1611 vm_page_xunbusy_maybelocked(mold);
1614 * The object's resident_page_count does not change because we have
1615 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1617 if (pmap_page_is_write_mapped(mnew))
1618 vm_object_set_writeable_dirty(object);
1625 * Move the given memory entry from its
1626 * current object to the specified target object/offset.
1628 * Note: swap associated with the page must be invalidated by the move. We
1629 * have to do this for several reasons: (1) we aren't freeing the
1630 * page, (2) we are dirtying the page, (3) the VM system is probably
1631 * moving the page from object A to B, and will then later move
1632 * the backing store from A to B and we can't have a conflict.
1634 * Note: we *always* dirty the page. It is necessary both for the
1635 * fact that we moved it, and because we may be invalidating
1638 * The objects must be locked.
1641 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1646 VM_OBJECT_ASSERT_WLOCKED(new_object);
1648 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1649 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1650 ("vm_page_rename: pindex already renamed"));
1653 * Create a custom version of vm_page_insert() which does not depend
1654 * by m_prev and can cheat on the implementation aspects of the
1658 m->pindex = new_pindex;
1659 if (vm_radix_insert(&new_object->rtree, m)) {
1665 * The operation cannot fail anymore. The removal must happen before
1666 * the listq iterator is tainted.
1670 (void)vm_page_remove(m);
1672 /* Return back to the new pindex to complete vm_page_insert(). */
1673 m->pindex = new_pindex;
1674 m->object = new_object;
1676 vm_page_insert_radixdone(m, new_object, mpred);
1684 * Allocate and return a page that is associated with the specified
1685 * object and offset pair. By default, this page is exclusive busied.
1687 * The caller must always specify an allocation class.
1689 * allocation classes:
1690 * VM_ALLOC_NORMAL normal process request
1691 * VM_ALLOC_SYSTEM system *really* needs a page
1692 * VM_ALLOC_INTERRUPT interrupt time request
1694 * optional allocation flags:
1695 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1696 * intends to allocate
1697 * VM_ALLOC_NOBUSY do not exclusive busy the page
1698 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1699 * VM_ALLOC_NOOBJ page is not associated with an object and
1700 * should not be exclusive busy
1701 * VM_ALLOC_SBUSY shared busy the allocated page
1702 * VM_ALLOC_WIRED wire the allocated page
1703 * VM_ALLOC_ZERO prefer a zeroed page
1706 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1709 return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1710 vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1714 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1718 return (vm_page_alloc_domain_after(object, pindex, domain, req,
1719 object != NULL ? vm_radix_lookup_le(&object->rtree, pindex) :
1724 * Allocate a page in the specified object with the given page index. To
1725 * optimize insertion of the page into the object, the caller must also specifiy
1726 * the resident page in the object with largest index smaller than the given
1727 * page index, or NULL if no such page exists.
1730 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1731 int req, vm_page_t mpred)
1733 struct vm_domainset_iter di;
1737 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1739 m = vm_page_alloc_domain_after(object, pindex, domain, req,
1743 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
1749 * Returns true if the number of free pages exceeds the minimum
1750 * for the request class and false otherwise.
1753 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
1755 u_int limit, old, new;
1757 req = req & VM_ALLOC_CLASS_MASK;
1760 * The page daemon is allowed to dig deeper into the free page list.
1762 if (curproc == pageproc && req != VM_ALLOC_INTERRUPT)
1763 req = VM_ALLOC_SYSTEM;
1764 if (req == VM_ALLOC_INTERRUPT)
1766 else if (req == VM_ALLOC_SYSTEM)
1767 limit = vmd->vmd_interrupt_free_min;
1769 limit = vmd->vmd_free_reserved;
1772 * Attempt to reserve the pages. Fail if we're below the limit.
1775 old = vmd->vmd_free_count;
1780 } while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
1782 /* Wake the page daemon if we've crossed the threshold. */
1783 if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
1784 pagedaemon_wakeup(vmd->vmd_domain);
1786 /* Only update bitsets on transitions. */
1787 if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
1788 (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
1795 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
1796 int req, vm_page_t mpred)
1798 struct vm_domain *vmd;
1802 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1803 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1804 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1805 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1806 ("inconsistent object(%p)/req(%x)", object, req));
1807 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1808 ("Can't sleep and retry object insertion."));
1809 KASSERT(mpred == NULL || mpred->pindex < pindex,
1810 ("mpred %p doesn't precede pindex 0x%jx", mpred,
1811 (uintmax_t)pindex));
1813 VM_OBJECT_ASSERT_WLOCKED(object);
1818 #if VM_NRESERVLEVEL > 0
1820 * Can we allocate the page from a reservation?
1822 if (vm_object_reserv(object) &&
1823 (m = vm_reserv_alloc_page(object, pindex, domain, req, mpred)) !=
1825 domain = vm_phys_domain(m);
1826 vmd = VM_DOMAIN(domain);
1830 vmd = VM_DOMAIN(domain);
1831 if (object != NULL && vmd->vmd_pgcache != NULL) {
1832 m = uma_zalloc(vmd->vmd_pgcache, M_NOWAIT);
1834 flags |= PG_PCPU_CACHE;
1838 if (vm_domain_allocate(vmd, req, 1)) {
1840 * If not, allocate it from the free page queues.
1842 vm_domain_free_lock(vmd);
1843 m = vm_phys_alloc_pages(domain, object != NULL ?
1844 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1845 vm_domain_free_unlock(vmd);
1847 vm_domain_freecnt_inc(vmd, 1);
1848 #if VM_NRESERVLEVEL > 0
1849 if (vm_reserv_reclaim_inactive(domain))
1856 * Not allocatable, give up.
1858 if (vm_domain_alloc_fail(vmd, object, req))
1864 * At this point we had better have found a good page.
1868 vm_page_alloc_check(m);
1871 * Initialize the page. Only the PG_ZERO flag is inherited.
1873 if ((req & VM_ALLOC_ZERO) != 0)
1874 flags |= (m->flags & PG_ZERO);
1875 if ((req & VM_ALLOC_NODUMP) != 0)
1879 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1881 m->busy_lock = VPB_UNBUSIED;
1882 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1883 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1884 if ((req & VM_ALLOC_SBUSY) != 0)
1885 m->busy_lock = VPB_SHARERS_WORD(1);
1886 if (req & VM_ALLOC_WIRED) {
1888 * The page lock is not required for wiring a page until that
1889 * page is inserted into the object.
1896 if (object != NULL) {
1897 if (vm_page_insert_after(m, object, pindex, mpred)) {
1898 if (req & VM_ALLOC_WIRED) {
1902 KASSERT(m->object == NULL, ("page %p has object", m));
1903 m->oflags = VPO_UNMANAGED;
1904 m->busy_lock = VPB_UNBUSIED;
1905 /* Don't change PG_ZERO. */
1906 vm_page_free_toq(m);
1907 if (req & VM_ALLOC_WAITFAIL) {
1908 VM_OBJECT_WUNLOCK(object);
1910 VM_OBJECT_WLOCK(object);
1915 /* Ignore device objects; the pager sets "memattr" for them. */
1916 if (object->memattr != VM_MEMATTR_DEFAULT &&
1917 (object->flags & OBJ_FICTITIOUS) == 0)
1918 pmap_page_set_memattr(m, object->memattr);
1926 * vm_page_alloc_contig:
1928 * Allocate a contiguous set of physical pages of the given size "npages"
1929 * from the free lists. All of the physical pages must be at or above
1930 * the given physical address "low" and below the given physical address
1931 * "high". The given value "alignment" determines the alignment of the
1932 * first physical page in the set. If the given value "boundary" is
1933 * non-zero, then the set of physical pages cannot cross any physical
1934 * address boundary that is a multiple of that value. Both "alignment"
1935 * and "boundary" must be a power of two.
1937 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1938 * then the memory attribute setting for the physical pages is configured
1939 * to the object's memory attribute setting. Otherwise, the memory
1940 * attribute setting for the physical pages is configured to "memattr",
1941 * overriding the object's memory attribute setting. However, if the
1942 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1943 * memory attribute setting for the physical pages cannot be configured
1944 * to VM_MEMATTR_DEFAULT.
1946 * The specified object may not contain fictitious pages.
1948 * The caller must always specify an allocation class.
1950 * allocation classes:
1951 * VM_ALLOC_NORMAL normal process request
1952 * VM_ALLOC_SYSTEM system *really* needs a page
1953 * VM_ALLOC_INTERRUPT interrupt time request
1955 * optional allocation flags:
1956 * VM_ALLOC_NOBUSY do not exclusive busy the page
1957 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1958 * VM_ALLOC_NOOBJ page is not associated with an object and
1959 * should not be exclusive busy
1960 * VM_ALLOC_SBUSY shared busy the allocated page
1961 * VM_ALLOC_WIRED wire the allocated page
1962 * VM_ALLOC_ZERO prefer a zeroed page
1965 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1966 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1967 vm_paddr_t boundary, vm_memattr_t memattr)
1969 struct vm_domainset_iter di;
1973 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1975 m = vm_page_alloc_contig_domain(object, pindex, domain, req,
1976 npages, low, high, alignment, boundary, memattr);
1979 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
1985 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1986 int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1987 vm_paddr_t boundary, vm_memattr_t memattr)
1989 struct vm_domain *vmd;
1990 vm_page_t m, m_ret, mpred;
1991 u_int busy_lock, flags, oflags;
1993 mpred = NULL; /* XXX: pacify gcc */
1994 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1995 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1996 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1997 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1998 ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
2000 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2001 ("Can't sleep and retry object insertion."));
2002 if (object != NULL) {
2003 VM_OBJECT_ASSERT_WLOCKED(object);
2004 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2005 ("vm_page_alloc_contig: object %p has fictitious pages",
2008 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2010 if (object != NULL) {
2011 mpred = vm_radix_lookup_le(&object->rtree, pindex);
2012 KASSERT(mpred == NULL || mpred->pindex != pindex,
2013 ("vm_page_alloc_contig: pindex already allocated"));
2017 * Can we allocate the pages without the number of free pages falling
2018 * below the lower bound for the allocation class?
2022 #if VM_NRESERVLEVEL > 0
2024 * Can we allocate the pages from a reservation?
2026 if (vm_object_reserv(object) &&
2027 (m_ret = vm_reserv_alloc_contig(object, pindex, domain, req,
2028 mpred, npages, low, high, alignment, boundary)) != NULL) {
2029 domain = vm_phys_domain(m_ret);
2030 vmd = VM_DOMAIN(domain);
2034 vmd = VM_DOMAIN(domain);
2035 if (vm_domain_allocate(vmd, req, npages)) {
2037 * allocate them from the free page queues.
2039 vm_domain_free_lock(vmd);
2040 m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2041 alignment, boundary);
2042 vm_domain_free_unlock(vmd);
2043 if (m_ret == NULL) {
2044 vm_domain_freecnt_inc(vmd, npages);
2045 #if VM_NRESERVLEVEL > 0
2046 if (vm_reserv_reclaim_contig(domain, npages, low,
2047 high, alignment, boundary))
2052 if (m_ret == NULL) {
2053 if (vm_domain_alloc_fail(vmd, object, req))
2057 #if VM_NRESERVLEVEL > 0
2060 for (m = m_ret; m < &m_ret[npages]; m++) {
2062 vm_page_alloc_check(m);
2066 * Initialize the pages. Only the PG_ZERO flag is inherited.
2069 if ((req & VM_ALLOC_ZERO) != 0)
2071 if ((req & VM_ALLOC_NODUMP) != 0)
2073 oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2075 busy_lock = VPB_UNBUSIED;
2076 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2077 busy_lock = VPB_SINGLE_EXCLUSIVER;
2078 if ((req & VM_ALLOC_SBUSY) != 0)
2079 busy_lock = VPB_SHARERS_WORD(1);
2080 if ((req & VM_ALLOC_WIRED) != 0)
2081 vm_wire_add(npages);
2082 if (object != NULL) {
2083 if (object->memattr != VM_MEMATTR_DEFAULT &&
2084 memattr == VM_MEMATTR_DEFAULT)
2085 memattr = object->memattr;
2087 for (m = m_ret; m < &m_ret[npages]; m++) {
2089 m->flags = (m->flags | PG_NODUMP) & flags;
2090 m->busy_lock = busy_lock;
2091 if ((req & VM_ALLOC_WIRED) != 0)
2095 if (object != NULL) {
2096 if (vm_page_insert_after(m, object, pindex, mpred)) {
2097 if ((req & VM_ALLOC_WIRED) != 0)
2098 vm_wire_sub(npages);
2099 KASSERT(m->object == NULL,
2100 ("page %p has object", m));
2102 for (m = m_ret; m < &m_ret[npages]; m++) {
2104 (req & VM_ALLOC_WIRED) != 0)
2106 m->oflags = VPO_UNMANAGED;
2107 m->busy_lock = VPB_UNBUSIED;
2108 /* Don't change PG_ZERO. */
2109 vm_page_free_toq(m);
2111 if (req & VM_ALLOC_WAITFAIL) {
2112 VM_OBJECT_WUNLOCK(object);
2114 VM_OBJECT_WLOCK(object);
2121 if (memattr != VM_MEMATTR_DEFAULT)
2122 pmap_page_set_memattr(m, memattr);
2129 * Check a page that has been freshly dequeued from a freelist.
2132 vm_page_alloc_check(vm_page_t m)
2135 KASSERT(m->object == NULL, ("page %p has object", m));
2136 KASSERT(m->queue == PQ_NONE && (m->aflags & PGA_QUEUE_STATE_MASK) == 0,
2137 ("page %p has unexpected queue %d, flags %#x",
2138 m, m->queue, (m->aflags & PGA_QUEUE_STATE_MASK)));
2139 KASSERT(!vm_page_held(m), ("page %p is held", m));
2140 KASSERT(!vm_page_busied(m), ("page %p is busy", m));
2141 KASSERT(m->dirty == 0, ("page %p is dirty", m));
2142 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2143 ("page %p has unexpected memattr %d",
2144 m, pmap_page_get_memattr(m)));
2145 KASSERT(m->valid == 0, ("free page %p is valid", m));
2149 * vm_page_alloc_freelist:
2151 * Allocate a physical page from the specified free page list.
2153 * The caller must always specify an allocation class.
2155 * allocation classes:
2156 * VM_ALLOC_NORMAL normal process request
2157 * VM_ALLOC_SYSTEM system *really* needs a page
2158 * VM_ALLOC_INTERRUPT interrupt time request
2160 * optional allocation flags:
2161 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2162 * intends to allocate
2163 * VM_ALLOC_WIRED wire the allocated page
2164 * VM_ALLOC_ZERO prefer a zeroed page
2167 vm_page_alloc_freelist(int freelist, int req)
2169 struct vm_domainset_iter di;
2173 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2175 m = vm_page_alloc_freelist_domain(domain, freelist, req);
2178 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2184 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2186 struct vm_domain *vmd;
2191 vmd = VM_DOMAIN(domain);
2193 if (vm_domain_allocate(vmd, req, 1)) {
2194 vm_domain_free_lock(vmd);
2195 m = vm_phys_alloc_freelist_pages(domain, freelist,
2196 VM_FREEPOOL_DIRECT, 0);
2197 vm_domain_free_unlock(vmd);
2199 vm_domain_freecnt_inc(vmd, 1);
2202 if (vm_domain_alloc_fail(vmd, NULL, req))
2207 vm_page_alloc_check(m);
2210 * Initialize the page. Only the PG_ZERO flag is inherited.
2214 if ((req & VM_ALLOC_ZERO) != 0)
2217 if ((req & VM_ALLOC_WIRED) != 0) {
2219 * The page lock is not required for wiring a page that does
2220 * not belong to an object.
2225 /* Unmanaged pages don't use "act_count". */
2226 m->oflags = VPO_UNMANAGED;
2231 vm_page_import(void *arg, void **store, int cnt, int domain, int flags)
2233 struct vm_domain *vmd;
2237 /* Only import if we can bring in a full bucket. */
2238 if (cnt == 1 || !vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2240 domain = vmd->vmd_domain;
2241 vm_domain_free_lock(vmd);
2242 i = vm_phys_alloc_npages(domain, VM_FREEPOOL_DEFAULT, cnt,
2243 (vm_page_t *)store);
2244 vm_domain_free_unlock(vmd);
2246 vm_domain_freecnt_inc(vmd, cnt - i);
2252 vm_page_release(void *arg, void **store, int cnt)
2254 struct vm_domain *vmd;
2259 vm_domain_free_lock(vmd);
2260 for (i = 0; i < cnt; i++) {
2261 m = (vm_page_t)store[i];
2262 vm_phys_free_pages(m, 0);
2264 vm_domain_free_unlock(vmd);
2265 vm_domain_freecnt_inc(vmd, cnt);
2268 #define VPSC_ANY 0 /* No restrictions. */
2269 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2270 #define VPSC_NOSUPER 2 /* Skip superpages. */
2273 * vm_page_scan_contig:
2275 * Scan vm_page_array[] between the specified entries "m_start" and
2276 * "m_end" for a run of contiguous physical pages that satisfy the
2277 * specified conditions, and return the lowest page in the run. The
2278 * specified "alignment" determines the alignment of the lowest physical
2279 * page in the run. If the specified "boundary" is non-zero, then the
2280 * run of physical pages cannot span a physical address that is a
2281 * multiple of "boundary".
2283 * "m_end" is never dereferenced, so it need not point to a vm_page
2284 * structure within vm_page_array[].
2286 * "npages" must be greater than zero. "m_start" and "m_end" must not
2287 * span a hole (or discontiguity) in the physical address space. Both
2288 * "alignment" and "boundary" must be a power of two.
2291 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2292 u_long alignment, vm_paddr_t boundary, int options)
2298 #if VM_NRESERVLEVEL > 0
2301 int m_inc, order, run_ext, run_len;
2303 KASSERT(npages > 0, ("npages is 0"));
2304 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2305 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2309 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2310 KASSERT((m->flags & PG_MARKER) == 0,
2311 ("page %p is PG_MARKER", m));
2312 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->wire_count == 1,
2313 ("fictitious page %p has invalid wire count", m));
2316 * If the current page would be the start of a run, check its
2317 * physical address against the end, alignment, and boundary
2318 * conditions. If it doesn't satisfy these conditions, either
2319 * terminate the scan or advance to the next page that
2320 * satisfies the failed condition.
2323 KASSERT(m_run == NULL, ("m_run != NULL"));
2324 if (m + npages > m_end)
2326 pa = VM_PAGE_TO_PHYS(m);
2327 if ((pa & (alignment - 1)) != 0) {
2328 m_inc = atop(roundup2(pa, alignment) - pa);
2331 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2333 m_inc = atop(roundup2(pa, boundary) - pa);
2337 KASSERT(m_run != NULL, ("m_run == NULL"));
2339 vm_page_change_lock(m, &m_mtx);
2342 if (vm_page_held(m))
2344 #if VM_NRESERVLEVEL > 0
2345 else if ((level = vm_reserv_level(m)) >= 0 &&
2346 (options & VPSC_NORESERV) != 0) {
2348 /* Advance to the end of the reservation. */
2349 pa = VM_PAGE_TO_PHYS(m);
2350 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2354 else if ((object = m->object) != NULL) {
2356 * The page is considered eligible for relocation if
2357 * and only if it could be laundered or reclaimed by
2360 if (!VM_OBJECT_TRYRLOCK(object)) {
2362 VM_OBJECT_RLOCK(object);
2364 if (m->object != object) {
2366 * The page may have been freed.
2368 VM_OBJECT_RUNLOCK(object);
2370 } else if (vm_page_held(m)) {
2375 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2376 ("page %p is PG_UNHOLDFREE", m));
2377 /* Don't care: PG_NODUMP, PG_ZERO. */
2378 if (object->type != OBJT_DEFAULT &&
2379 object->type != OBJT_SWAP &&
2380 object->type != OBJT_VNODE) {
2382 #if VM_NRESERVLEVEL > 0
2383 } else if ((options & VPSC_NOSUPER) != 0 &&
2384 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2386 /* Advance to the end of the superpage. */
2387 pa = VM_PAGE_TO_PHYS(m);
2388 m_inc = atop(roundup2(pa + 1,
2389 vm_reserv_size(level)) - pa);
2391 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2392 vm_page_queue(m) != PQ_NONE && !vm_page_busied(m)) {
2394 * The page is allocated but eligible for
2395 * relocation. Extend the current run by one
2398 KASSERT(pmap_page_get_memattr(m) ==
2400 ("page %p has an unexpected memattr", m));
2401 KASSERT((m->oflags & (VPO_SWAPINPROG |
2402 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2403 ("page %p has unexpected oflags", m));
2404 /* Don't care: VPO_NOSYNC. */
2409 VM_OBJECT_RUNLOCK(object);
2410 #if VM_NRESERVLEVEL > 0
2411 } else if (level >= 0) {
2413 * The page is reserved but not yet allocated. In
2414 * other words, it is still free. Extend the current
2419 } else if ((order = m->order) < VM_NFREEORDER) {
2421 * The page is enqueued in the physical memory
2422 * allocator's free page queues. Moreover, it is the
2423 * first page in a power-of-two-sized run of
2424 * contiguous free pages. Add these pages to the end
2425 * of the current run, and jump ahead.
2427 run_ext = 1 << order;
2431 * Skip the page for one of the following reasons: (1)
2432 * It is enqueued in the physical memory allocator's
2433 * free page queues. However, it is not the first
2434 * page in a run of contiguous free pages. (This case
2435 * rarely occurs because the scan is performed in
2436 * ascending order.) (2) It is not reserved, and it is
2437 * transitioning from free to allocated. (Conversely,
2438 * the transition from allocated to free for managed
2439 * pages is blocked by the page lock.) (3) It is
2440 * allocated but not contained by an object and not
2441 * wired, e.g., allocated by Xen's balloon driver.
2447 * Extend or reset the current run of pages.
2462 if (run_len >= npages)
2468 * vm_page_reclaim_run:
2470 * Try to relocate each of the allocated virtual pages within the
2471 * specified run of physical pages to a new physical address. Free the
2472 * physical pages underlying the relocated virtual pages. A virtual page
2473 * is relocatable if and only if it could be laundered or reclaimed by
2474 * the page daemon. Whenever possible, a virtual page is relocated to a
2475 * physical address above "high".
2477 * Returns 0 if every physical page within the run was already free or
2478 * just freed by a successful relocation. Otherwise, returns a non-zero
2479 * value indicating why the last attempt to relocate a virtual page was
2482 * "req_class" must be an allocation class.
2485 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2488 struct vm_domain *vmd;
2490 struct spglist free;
2493 vm_page_t m, m_end, m_new;
2494 int error, order, req;
2496 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2497 ("req_class is not an allocation class"));
2501 m_end = m_run + npages;
2503 for (; error == 0 && m < m_end; m++) {
2504 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2505 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2508 * Avoid releasing and reacquiring the same page lock.
2510 vm_page_change_lock(m, &m_mtx);
2512 if (vm_page_held(m))
2514 else if ((object = m->object) != NULL) {
2516 * The page is relocated if and only if it could be
2517 * laundered or reclaimed by the page daemon.
2519 if (!VM_OBJECT_TRYWLOCK(object)) {
2521 VM_OBJECT_WLOCK(object);
2523 if (m->object != object) {
2525 * The page may have been freed.
2527 VM_OBJECT_WUNLOCK(object);
2529 } else if (vm_page_held(m)) {
2534 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2535 ("page %p is PG_UNHOLDFREE", m));
2536 /* Don't care: PG_NODUMP, PG_ZERO. */
2537 if (object->type != OBJT_DEFAULT &&
2538 object->type != OBJT_SWAP &&
2539 object->type != OBJT_VNODE)
2541 else if (object->memattr != VM_MEMATTR_DEFAULT)
2543 else if (vm_page_queue(m) != PQ_NONE &&
2544 !vm_page_busied(m)) {
2545 KASSERT(pmap_page_get_memattr(m) ==
2547 ("page %p has an unexpected memattr", m));
2548 KASSERT((m->oflags & (VPO_SWAPINPROG |
2549 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2550 ("page %p has unexpected oflags", m));
2551 /* Don't care: VPO_NOSYNC. */
2552 if (m->valid != 0) {
2554 * First, try to allocate a new page
2555 * that is above "high". Failing
2556 * that, try to allocate a new page
2557 * that is below "m_run". Allocate
2558 * the new page between the end of
2559 * "m_run" and "high" only as a last
2562 req = req_class | VM_ALLOC_NOOBJ;
2563 if ((m->flags & PG_NODUMP) != 0)
2564 req |= VM_ALLOC_NODUMP;
2565 if (trunc_page(high) !=
2566 ~(vm_paddr_t)PAGE_MASK) {
2567 m_new = vm_page_alloc_contig(
2572 VM_MEMATTR_DEFAULT);
2575 if (m_new == NULL) {
2576 pa = VM_PAGE_TO_PHYS(m_run);
2577 m_new = vm_page_alloc_contig(
2579 0, pa - 1, PAGE_SIZE, 0,
2580 VM_MEMATTR_DEFAULT);
2582 if (m_new == NULL) {
2584 m_new = vm_page_alloc_contig(
2586 pa, high, PAGE_SIZE, 0,
2587 VM_MEMATTR_DEFAULT);
2589 if (m_new == NULL) {
2593 KASSERT(!vm_page_wired(m_new),
2594 ("page %p is wired", m_new));
2597 * Replace "m" with the new page. For
2598 * vm_page_replace(), "m" must be busy
2599 * and dequeued. Finally, change "m"
2600 * as if vm_page_free() was called.
2602 if (object->ref_count != 0)
2604 m_new->aflags = m->aflags &
2605 ~PGA_QUEUE_STATE_MASK;
2606 KASSERT(m_new->oflags == VPO_UNMANAGED,
2607 ("page %p is managed", m_new));
2608 m_new->oflags = m->oflags & VPO_NOSYNC;
2609 pmap_copy_page(m, m_new);
2610 m_new->valid = m->valid;
2611 m_new->dirty = m->dirty;
2612 m->flags &= ~PG_ZERO;
2615 vm_page_replace_checked(m_new, object,
2617 if (vm_page_free_prep(m))
2618 SLIST_INSERT_HEAD(&free, m,
2622 * The new page must be deactivated
2623 * before the object is unlocked.
2625 vm_page_change_lock(m_new, &m_mtx);
2626 vm_page_deactivate(m_new);
2628 m->flags &= ~PG_ZERO;
2630 if (vm_page_free_prep(m))
2631 SLIST_INSERT_HEAD(&free, m,
2633 KASSERT(m->dirty == 0,
2634 ("page %p is dirty", m));
2639 VM_OBJECT_WUNLOCK(object);
2641 MPASS(vm_phys_domain(m) == domain);
2642 vmd = VM_DOMAIN(domain);
2643 vm_domain_free_lock(vmd);
2645 if (order < VM_NFREEORDER) {
2647 * The page is enqueued in the physical memory
2648 * allocator's free page queues. Moreover, it
2649 * is the first page in a power-of-two-sized
2650 * run of contiguous free pages. Jump ahead
2651 * to the last page within that run, and
2652 * continue from there.
2654 m += (1 << order) - 1;
2656 #if VM_NRESERVLEVEL > 0
2657 else if (vm_reserv_is_page_free(m))
2660 vm_domain_free_unlock(vmd);
2661 if (order == VM_NFREEORDER)
2667 if ((m = SLIST_FIRST(&free)) != NULL) {
2670 vmd = VM_DOMAIN(domain);
2672 vm_domain_free_lock(vmd);
2674 MPASS(vm_phys_domain(m) == domain);
2675 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2676 vm_phys_free_pages(m, 0);
2678 } while ((m = SLIST_FIRST(&free)) != NULL);
2679 vm_domain_free_unlock(vmd);
2680 vm_domain_freecnt_inc(vmd, cnt);
2687 CTASSERT(powerof2(NRUNS));
2689 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2691 #define MIN_RECLAIM 8
2694 * vm_page_reclaim_contig:
2696 * Reclaim allocated, contiguous physical memory satisfying the specified
2697 * conditions by relocating the virtual pages using that physical memory.
2698 * Returns true if reclamation is successful and false otherwise. Since
2699 * relocation requires the allocation of physical pages, reclamation may
2700 * fail due to a shortage of free pages. When reclamation fails, callers
2701 * are expected to perform vm_wait() before retrying a failed allocation
2702 * operation, e.g., vm_page_alloc_contig().
2704 * The caller must always specify an allocation class through "req".
2706 * allocation classes:
2707 * VM_ALLOC_NORMAL normal process request
2708 * VM_ALLOC_SYSTEM system *really* needs a page
2709 * VM_ALLOC_INTERRUPT interrupt time request
2711 * The optional allocation flags are ignored.
2713 * "npages" must be greater than zero. Both "alignment" and "boundary"
2714 * must be a power of two.
2717 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
2718 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2720 struct vm_domain *vmd;
2721 vm_paddr_t curr_low;
2722 vm_page_t m_run, m_runs[NRUNS];
2723 u_long count, reclaimed;
2724 int error, i, options, req_class;
2726 KASSERT(npages > 0, ("npages is 0"));
2727 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2728 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2729 req_class = req & VM_ALLOC_CLASS_MASK;
2732 * The page daemon is allowed to dig deeper into the free page list.
2734 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2735 req_class = VM_ALLOC_SYSTEM;
2738 * Return if the number of free pages cannot satisfy the requested
2741 vmd = VM_DOMAIN(domain);
2742 count = vmd->vmd_free_count;
2743 if (count < npages + vmd->vmd_free_reserved || (count < npages +
2744 vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2745 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2749 * Scan up to three times, relaxing the restrictions ("options") on
2750 * the reclamation of reservations and superpages each time.
2752 for (options = VPSC_NORESERV;;) {
2754 * Find the highest runs that satisfy the given constraints
2755 * and restrictions, and record them in "m_runs".
2760 m_run = vm_phys_scan_contig(domain, npages, curr_low,
2761 high, alignment, boundary, options);
2764 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2765 m_runs[RUN_INDEX(count)] = m_run;
2770 * Reclaim the highest runs in LIFO (descending) order until
2771 * the number of reclaimed pages, "reclaimed", is at least
2772 * MIN_RECLAIM. Reset "reclaimed" each time because each
2773 * reclamation is idempotent, and runs will (likely) recur
2774 * from one scan to the next as restrictions are relaxed.
2777 for (i = 0; count > 0 && i < NRUNS; i++) {
2779 m_run = m_runs[RUN_INDEX(count)];
2780 error = vm_page_reclaim_run(req_class, domain, npages,
2783 reclaimed += npages;
2784 if (reclaimed >= MIN_RECLAIM)
2790 * Either relax the restrictions on the next scan or return if
2791 * the last scan had no restrictions.
2793 if (options == VPSC_NORESERV)
2794 options = VPSC_NOSUPER;
2795 else if (options == VPSC_NOSUPER)
2797 else if (options == VPSC_ANY)
2798 return (reclaimed != 0);
2803 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2804 u_long alignment, vm_paddr_t boundary)
2806 struct vm_domainset_iter di;
2810 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2812 ret = vm_page_reclaim_contig_domain(domain, req, npages, low,
2813 high, alignment, boundary);
2816 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2822 * Set the domain in the appropriate page level domainset.
2825 vm_domain_set(struct vm_domain *vmd)
2828 mtx_lock(&vm_domainset_lock);
2829 if (!vmd->vmd_minset && vm_paging_min(vmd)) {
2830 vmd->vmd_minset = 1;
2831 DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
2833 if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
2834 vmd->vmd_severeset = 1;
2835 DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
2837 mtx_unlock(&vm_domainset_lock);
2841 * Clear the domain from the appropriate page level domainset.
2844 vm_domain_clear(struct vm_domain *vmd)
2847 mtx_lock(&vm_domainset_lock);
2848 if (vmd->vmd_minset && !vm_paging_min(vmd)) {
2849 vmd->vmd_minset = 0;
2850 DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
2851 if (vm_min_waiters != 0) {
2853 wakeup(&vm_min_domains);
2856 if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
2857 vmd->vmd_severeset = 0;
2858 DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
2859 if (vm_severe_waiters != 0) {
2860 vm_severe_waiters = 0;
2861 wakeup(&vm_severe_domains);
2866 * If pageout daemon needs pages, then tell it that there are
2869 if (vmd->vmd_pageout_pages_needed &&
2870 vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
2871 wakeup(&vmd->vmd_pageout_pages_needed);
2872 vmd->vmd_pageout_pages_needed = 0;
2875 /* See comments in vm_wait_doms(). */
2876 if (vm_pageproc_waiters) {
2877 vm_pageproc_waiters = 0;
2878 wakeup(&vm_pageproc_waiters);
2880 mtx_unlock(&vm_domainset_lock);
2884 * Wait for free pages to exceed the min threshold globally.
2890 mtx_lock(&vm_domainset_lock);
2891 while (vm_page_count_min()) {
2893 msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
2895 mtx_unlock(&vm_domainset_lock);
2899 * Wait for free pages to exceed the severe threshold globally.
2902 vm_wait_severe(void)
2905 mtx_lock(&vm_domainset_lock);
2906 while (vm_page_count_severe()) {
2907 vm_severe_waiters++;
2908 msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
2911 mtx_unlock(&vm_domainset_lock);
2918 return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
2922 vm_wait_doms(const domainset_t *wdoms)
2926 * We use racey wakeup synchronization to avoid expensive global
2927 * locking for the pageproc when sleeping with a non-specific vm_wait.
2928 * To handle this, we only sleep for one tick in this instance. It
2929 * is expected that most allocations for the pageproc will come from
2930 * kmem or vm_page_grab* which will use the more specific and
2931 * race-free vm_wait_domain().
2933 if (curproc == pageproc) {
2934 mtx_lock(&vm_domainset_lock);
2935 vm_pageproc_waiters++;
2936 msleep(&vm_pageproc_waiters, &vm_domainset_lock, PVM | PDROP,
2940 * XXX Ideally we would wait only until the allocation could
2941 * be satisfied. This condition can cause new allocators to
2942 * consume all freed pages while old allocators wait.
2944 mtx_lock(&vm_domainset_lock);
2945 if (vm_page_count_min_set(wdoms)) {
2947 msleep(&vm_min_domains, &vm_domainset_lock,
2948 PVM | PDROP, "vmwait", 0);
2950 mtx_unlock(&vm_domainset_lock);
2957 * Sleep until free pages are available for allocation.
2958 * - Called in various places after failed memory allocations.
2961 vm_wait_domain(int domain)
2963 struct vm_domain *vmd;
2966 vmd = VM_DOMAIN(domain);
2967 vm_domain_free_assert_unlocked(vmd);
2969 if (curproc == pageproc) {
2970 mtx_lock(&vm_domainset_lock);
2971 if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
2972 vmd->vmd_pageout_pages_needed = 1;
2973 msleep(&vmd->vmd_pageout_pages_needed,
2974 &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
2976 mtx_unlock(&vm_domainset_lock);
2978 if (pageproc == NULL)
2979 panic("vm_wait in early boot");
2980 DOMAINSET_ZERO(&wdom);
2981 DOMAINSET_SET(vmd->vmd_domain, &wdom);
2982 vm_wait_doms(&wdom);
2989 * Sleep until free pages are available for allocation in the
2990 * affinity domains of the obj. If obj is NULL, the domain set
2991 * for the calling thread is used.
2992 * Called in various places after failed memory allocations.
2995 vm_wait(vm_object_t obj)
2997 struct domainset *d;
3002 * Carefully fetch pointers only once: the struct domainset
3003 * itself is ummutable but the pointer might change.
3006 d = obj->domain.dr_policy;
3008 d = curthread->td_domain.dr_policy;
3010 vm_wait_doms(&d->ds_mask);
3014 * vm_domain_alloc_fail:
3016 * Called when a page allocation function fails. Informs the
3017 * pagedaemon and performs the requested wait. Requires the
3018 * domain_free and object lock on entry. Returns with the
3019 * object lock held and free lock released. Returns an error when
3020 * retry is necessary.
3024 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3027 vm_domain_free_assert_unlocked(vmd);
3029 atomic_add_int(&vmd->vmd_pageout_deficit,
3030 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3031 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3033 VM_OBJECT_WUNLOCK(object);
3034 vm_wait_domain(vmd->vmd_domain);
3036 VM_OBJECT_WLOCK(object);
3037 if (req & VM_ALLOC_WAITOK)
3047 * Sleep until free pages are available for allocation.
3048 * - Called only in vm_fault so that processes page faulting
3049 * can be easily tracked.
3050 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3051 * processes will be able to grab memory first. Do not change
3052 * this balance without careful testing first.
3055 vm_waitpfault(struct domainset *dset)
3059 * XXX Ideally we would wait only until the allocation could
3060 * be satisfied. This condition can cause new allocators to
3061 * consume all freed pages while old allocators wait.
3063 mtx_lock(&vm_domainset_lock);
3064 if (vm_page_count_min_set(&dset->ds_mask)) {
3066 msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3069 mtx_unlock(&vm_domainset_lock);
3072 struct vm_pagequeue *
3073 vm_page_pagequeue(vm_page_t m)
3076 return (&vm_pagequeue_domain(m)->vmd_pagequeues[m->queue]);
3080 vm_page_pagequeue_lockptr(vm_page_t m)
3084 if ((queue = atomic_load_8(&m->queue)) == PQ_NONE)
3086 return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue].pq_mutex);
3090 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m)
3092 struct vm_domain *vmd;
3095 CRITICAL_ASSERT(curthread);
3096 vm_pagequeue_assert_locked(pq);
3099 * The page daemon is allowed to set m->queue = PQ_NONE without
3100 * the page queue lock held. In this case it is about to free the page,
3101 * which must not have any queue state.
3103 qflags = atomic_load_8(&m->aflags) & PGA_QUEUE_STATE_MASK;
3104 KASSERT(pq == vm_page_pagequeue(m) || qflags == 0,
3105 ("page %p doesn't belong to queue %p but has queue state %#x",
3108 if ((qflags & PGA_DEQUEUE) != 0) {
3109 if (__predict_true((qflags & PGA_ENQUEUED) != 0)) {
3110 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3111 vm_pagequeue_cnt_dec(pq);
3113 vm_page_dequeue_complete(m);
3114 } else if ((qflags & (PGA_REQUEUE | PGA_REQUEUE_HEAD)) != 0) {
3115 if ((qflags & PGA_ENQUEUED) != 0)
3116 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3118 vm_pagequeue_cnt_inc(pq);
3119 vm_page_aflag_set(m, PGA_ENQUEUED);
3121 if ((qflags & PGA_REQUEUE_HEAD) != 0) {
3122 KASSERT(m->queue == PQ_INACTIVE,
3123 ("head enqueue not supported for page %p", m));
3124 vmd = vm_pagequeue_domain(m);
3125 TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3127 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3130 * PGA_REQUEUE and PGA_REQUEUE_HEAD must be cleared after
3131 * setting PGA_ENQUEUED in order to synchronize with the
3134 vm_page_aflag_clear(m, PGA_REQUEUE | PGA_REQUEUE_HEAD);
3139 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3145 for (i = 0; i < bq->bq_cnt; i++) {
3147 if (__predict_false(m->queue != queue))
3149 vm_pqbatch_process_page(pq, m);
3151 vm_batchqueue_init(bq);
3155 vm_pqbatch_submit_page(vm_page_t m, uint8_t queue)
3157 struct vm_batchqueue *bq;
3158 struct vm_pagequeue *pq;
3161 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3162 ("page %p is unmanaged", m));
3163 KASSERT(mtx_owned(vm_page_lockptr(m)) ||
3164 (m->object == NULL && (m->aflags & PGA_DEQUEUE) != 0),
3165 ("missing synchronization for page %p", m));
3166 KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3168 domain = vm_phys_domain(m);
3169 pq = &vm_pagequeue_domain(m)->vmd_pagequeues[queue];
3172 bq = DPCPU_PTR(pqbatch[domain][queue]);
3173 if (vm_batchqueue_insert(bq, m)) {
3177 if (!vm_pagequeue_trylock(pq)) {
3179 vm_pagequeue_lock(pq);
3181 bq = DPCPU_PTR(pqbatch[domain][queue]);
3183 vm_pqbatch_process(pq, bq, queue);
3186 * The page may have been logically dequeued before we acquired the
3187 * page queue lock. In this case, since we either hold the page lock
3188 * or the page is being freed, a different thread cannot be concurrently
3189 * enqueuing the page.
3191 if (__predict_true(m->queue == queue))
3192 vm_pqbatch_process_page(pq, m);
3194 KASSERT(m->queue == PQ_NONE,
3195 ("invalid queue transition for page %p", m));
3196 KASSERT((m->aflags & PGA_ENQUEUED) == 0,
3197 ("page %p is enqueued with invalid queue index", m));
3198 vm_page_aflag_clear(m, PGA_QUEUE_STATE_MASK);
3200 vm_pagequeue_unlock(pq);
3205 * vm_page_drain_pqbatch: [ internal use only ]
3207 * Force all per-CPU page queue batch queues to be drained. This is
3208 * intended for use in severe memory shortages, to ensure that pages
3209 * do not remain stuck in the batch queues.
3212 vm_page_drain_pqbatch(void)
3215 struct vm_domain *vmd;
3216 struct vm_pagequeue *pq;
3217 int cpu, domain, queue;
3222 sched_bind(td, cpu);
3225 for (domain = 0; domain < vm_ndomains; domain++) {
3226 vmd = VM_DOMAIN(domain);
3227 for (queue = 0; queue < PQ_COUNT; queue++) {
3228 pq = &vmd->vmd_pagequeues[queue];
3229 vm_pagequeue_lock(pq);
3231 vm_pqbatch_process(pq,
3232 DPCPU_PTR(pqbatch[domain][queue]), queue);
3234 vm_pagequeue_unlock(pq);
3244 * Complete the logical removal of a page from a page queue. We must be
3245 * careful to synchronize with the page daemon, which may be concurrently
3246 * examining the page with only the page lock held. The page must not be
3247 * in a state where it appears to be logically enqueued.
3250 vm_page_dequeue_complete(vm_page_t m)
3254 atomic_thread_fence_rel();
3255 vm_page_aflag_clear(m, PGA_QUEUE_STATE_MASK);
3259 * vm_page_dequeue_deferred: [ internal use only ]
3261 * Request removal of the given page from its current page
3262 * queue. Physical removal from the queue may be deferred
3265 * The page must be locked.
3268 vm_page_dequeue_deferred(vm_page_t m)
3272 vm_page_assert_locked(m);
3274 if ((queue = vm_page_queue(m)) == PQ_NONE)
3276 vm_page_aflag_set(m, PGA_DEQUEUE);
3277 vm_pqbatch_submit_page(m, queue);
3281 * A variant of vm_page_dequeue_deferred() that does not assert the page
3282 * lock and is only to be called from vm_page_free_prep(). It is just an
3283 * open-coded implementation of vm_page_dequeue_deferred(). Because the
3284 * page is being freed, we can assume that nothing else is scheduling queue
3285 * operations on this page, so we get for free the mutual exclusion that
3286 * is otherwise provided by the page lock.
3289 vm_page_dequeue_deferred_free(vm_page_t m)
3293 KASSERT(m->object == NULL, ("page %p has an object reference", m));
3295 if ((m->aflags & PGA_DEQUEUE) != 0)
3297 atomic_thread_fence_acq();
3298 if ((queue = m->queue) == PQ_NONE)
3300 vm_page_aflag_set(m, PGA_DEQUEUE);
3301 vm_pqbatch_submit_page(m, queue);
3307 * Remove the page from whichever page queue it's in, if any.
3308 * The page must either be locked or unallocated. This constraint
3309 * ensures that the queue state of the page will remain consistent
3310 * after this function returns.
3313 vm_page_dequeue(vm_page_t m)
3315 struct mtx *lock, *lock1;
3316 struct vm_pagequeue *pq;
3319 KASSERT(mtx_owned(vm_page_lockptr(m)) || m->order == VM_NFREEORDER,
3320 ("page %p is allocated and unlocked", m));
3323 lock = vm_page_pagequeue_lockptr(m);
3326 * A thread may be concurrently executing
3327 * vm_page_dequeue_complete(). Ensure that all queue
3328 * state is cleared before we return.
3330 aflags = atomic_load_8(&m->aflags);
3331 if ((aflags & PGA_QUEUE_STATE_MASK) == 0)
3333 KASSERT((aflags & PGA_DEQUEUE) != 0,
3334 ("page %p has unexpected queue state flags %#x",
3338 * Busy wait until the thread updating queue state is
3339 * finished. Such a thread must be executing in a
3346 if ((lock1 = vm_page_pagequeue_lockptr(m)) == lock)
3351 KASSERT(lock == vm_page_pagequeue_lockptr(m),
3352 ("%s: page %p migrated directly between queues", __func__, m));
3353 KASSERT((m->aflags & PGA_DEQUEUE) != 0 ||
3354 mtx_owned(vm_page_lockptr(m)),
3355 ("%s: queued unlocked page %p", __func__, m));
3357 if ((m->aflags & PGA_ENQUEUED) != 0) {
3358 pq = vm_page_pagequeue(m);
3359 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3360 vm_pagequeue_cnt_dec(pq);
3362 vm_page_dequeue_complete(m);
3367 * Schedule the given page for insertion into the specified page queue.
3368 * Physical insertion of the page may be deferred indefinitely.
3371 vm_page_enqueue(vm_page_t m, uint8_t queue)
3374 vm_page_assert_locked(m);
3375 KASSERT(m->queue == PQ_NONE && (m->aflags & PGA_QUEUE_STATE_MASK) == 0,
3376 ("%s: page %p is already enqueued", __func__, m));
3379 if ((m->aflags & PGA_REQUEUE) == 0)
3380 vm_page_aflag_set(m, PGA_REQUEUE);
3381 vm_pqbatch_submit_page(m, queue);
3385 * vm_page_requeue: [ internal use only ]
3387 * Schedule a requeue of the given page.
3389 * The page must be locked.
3392 vm_page_requeue(vm_page_t m)
3395 vm_page_assert_locked(m);
3396 KASSERT(vm_page_queue(m) != PQ_NONE,
3397 ("%s: page %p is not logically enqueued", __func__, m));
3399 if ((m->aflags & PGA_REQUEUE) == 0)
3400 vm_page_aflag_set(m, PGA_REQUEUE);
3401 vm_pqbatch_submit_page(m, atomic_load_8(&m->queue));
3405 * vm_page_free_prep:
3407 * Prepares the given page to be put on the free list,
3408 * disassociating it from any VM object. The caller may return
3409 * the page to the free list only if this function returns true.
3411 * The object must be locked. The page must be locked if it is
3415 vm_page_free_prep(vm_page_t m)
3418 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
3419 if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
3422 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3423 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
3424 KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
3425 m, i, (uintmax_t)*p));
3428 if ((m->oflags & VPO_UNMANAGED) == 0) {
3429 vm_page_lock_assert(m, MA_OWNED);
3430 KASSERT(!pmap_page_is_mapped(m),
3431 ("vm_page_free_prep: freeing mapped page %p", m));
3433 KASSERT(m->queue == PQ_NONE,
3434 ("vm_page_free_prep: unmanaged page %p is queued", m));
3435 VM_CNT_INC(v_tfree);
3437 if (vm_page_sbusied(m))
3438 panic("vm_page_free_prep: freeing busy page %p", m);
3440 if (m->object != NULL)
3441 (void)vm_page_remove(m);
3444 * If fictitious remove object association and
3447 if ((m->flags & PG_FICTITIOUS) != 0) {
3448 KASSERT(m->wire_count == 1,
3449 ("fictitious page %p is not wired", m));
3450 KASSERT(m->queue == PQ_NONE,
3451 ("fictitious page %p is queued", m));
3456 * Pages need not be dequeued before they are returned to the physical
3457 * memory allocator, but they must at least be marked for a deferred
3460 if ((m->oflags & VPO_UNMANAGED) == 0)
3461 vm_page_dequeue_deferred_free(m);
3466 if (vm_page_wired(m) != 0)
3467 panic("vm_page_free_prep: freeing wired page %p", m);
3468 if (m->hold_count != 0) {
3469 m->flags &= ~PG_ZERO;
3470 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
3471 ("vm_page_free_prep: freeing PG_UNHOLDFREE page %p", m));
3472 m->flags |= PG_UNHOLDFREE;
3477 * Restore the default memory attribute to the page.
3479 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3480 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3482 #if VM_NRESERVLEVEL > 0
3483 if (vm_reserv_free_page(m))
3493 * Returns the given page to the free list, disassociating it
3494 * from any VM object.
3496 * The object must be locked. The page must be locked if it is
3500 vm_page_free_toq(vm_page_t m)
3502 struct vm_domain *vmd;
3504 if (!vm_page_free_prep(m))
3507 vmd = vm_pagequeue_domain(m);
3508 if ((m->flags & PG_PCPU_CACHE) != 0 && vmd->vmd_pgcache != NULL) {
3509 uma_zfree(vmd->vmd_pgcache, m);
3512 vm_domain_free_lock(vmd);
3513 vm_phys_free_pages(m, 0);
3514 vm_domain_free_unlock(vmd);
3515 vm_domain_freecnt_inc(vmd, 1);
3519 * vm_page_free_pages_toq:
3521 * Returns a list of pages to the free list, disassociating it
3522 * from any VM object. In other words, this is equivalent to
3523 * calling vm_page_free_toq() for each page of a list of VM objects.
3525 * The objects must be locked. The pages must be locked if it is
3529 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
3534 if (SLIST_EMPTY(free))
3538 while ((m = SLIST_FIRST(free)) != NULL) {
3540 SLIST_REMOVE_HEAD(free, plinks.s.ss);
3541 vm_page_free_toq(m);
3544 if (update_wire_count)
3551 * Mark this page as wired down. If the page is fictitious, then
3552 * its wire count must remain one.
3554 * The page must be locked.
3557 vm_page_wire(vm_page_t m)
3560 vm_page_assert_locked(m);
3561 if ((m->flags & PG_FICTITIOUS) != 0) {
3562 KASSERT(m->wire_count == 1,
3563 ("vm_page_wire: fictitious page %p's wire count isn't one",
3567 if (!vm_page_wired(m)) {
3568 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
3569 m->queue == PQ_NONE,
3570 ("vm_page_wire: unmanaged page %p is queued", m));
3574 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
3580 * Release one wiring of the specified page, potentially allowing it to be
3581 * paged out. Returns TRUE if the number of wirings transitions to zero and
3584 * Only managed pages belonging to an object can be paged out. If the number
3585 * of wirings transitions to zero and the page is eligible for page out, then
3586 * the page is added to the specified paging queue (unless PQ_NONE is
3587 * specified, in which case the page is dequeued if it belongs to a paging
3590 * If a page is fictitious, then its wire count must always be one.
3592 * A managed page must be locked.
3595 vm_page_unwire(vm_page_t m, uint8_t queue)
3599 KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
3600 ("vm_page_unwire: invalid queue %u request for page %p",
3602 if ((m->oflags & VPO_UNMANAGED) == 0)
3603 vm_page_assert_locked(m);
3605 unwired = vm_page_unwire_noq(m);
3606 if (!unwired || (m->oflags & VPO_UNMANAGED) != 0 || m->object == NULL)
3609 if (vm_page_queue(m) == queue) {
3610 if (queue == PQ_ACTIVE)
3611 vm_page_reference(m);
3612 else if (queue != PQ_NONE)
3616 if (queue != PQ_NONE) {
3617 vm_page_enqueue(m, queue);
3618 if (queue == PQ_ACTIVE)
3619 /* Initialize act_count. */
3620 vm_page_activate(m);
3628 * vm_page_unwire_noq:
3630 * Unwire a page without (re-)inserting it into a page queue. It is up
3631 * to the caller to enqueue, requeue, or free the page as appropriate.
3632 * In most cases, vm_page_unwire() should be used instead.
3635 vm_page_unwire_noq(vm_page_t m)
3638 if ((m->oflags & VPO_UNMANAGED) == 0)
3639 vm_page_assert_locked(m);
3640 if ((m->flags & PG_FICTITIOUS) != 0) {
3641 KASSERT(m->wire_count == 1,
3642 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
3645 if (!vm_page_wired(m))
3646 panic("vm_page_unwire: page %p's wire count is zero", m);
3648 if (m->wire_count == 0) {
3658 * Put the specified page on the active list (if appropriate).
3659 * Ensure that act_count is at least ACT_INIT but do not otherwise
3662 * The page must be locked.
3665 vm_page_activate(vm_page_t m)
3668 vm_page_assert_locked(m);
3670 if (vm_page_wired(m) || (m->oflags & VPO_UNMANAGED) != 0)
3672 if (vm_page_queue(m) == PQ_ACTIVE) {
3673 if (m->act_count < ACT_INIT)
3674 m->act_count = ACT_INIT;
3679 if (m->act_count < ACT_INIT)
3680 m->act_count = ACT_INIT;
3681 vm_page_enqueue(m, PQ_ACTIVE);
3685 * Move the specified page to the tail of the inactive queue, or requeue
3686 * the page if it is already in the inactive queue.
3688 * The page must be locked.
3691 vm_page_deactivate(vm_page_t m)
3694 vm_page_assert_locked(m);
3696 if (vm_page_wired(m) || (m->oflags & VPO_UNMANAGED) != 0)
3699 if (!vm_page_inactive(m)) {
3701 vm_page_enqueue(m, PQ_INACTIVE);
3707 * Move the specified page close to the head of the inactive queue,
3708 * bypassing LRU. A marker page is used to maintain FIFO ordering.
3709 * As with regular enqueues, we use a per-CPU batch queue to reduce
3710 * contention on the page queue lock.
3712 * The page must be locked.
3715 vm_page_deactivate_noreuse(vm_page_t m)
3718 vm_page_assert_locked(m);
3720 if (vm_page_wired(m) || (m->oflags & VPO_UNMANAGED) != 0)
3723 if (!vm_page_inactive(m)) {
3725 m->queue = PQ_INACTIVE;
3727 if ((m->aflags & PGA_REQUEUE_HEAD) == 0)
3728 vm_page_aflag_set(m, PGA_REQUEUE_HEAD);
3729 vm_pqbatch_submit_page(m, PQ_INACTIVE);
3735 * Put a page in the laundry, or requeue it if it is already there.
3738 vm_page_launder(vm_page_t m)
3741 vm_page_assert_locked(m);
3742 if (vm_page_wired(m) || (m->oflags & VPO_UNMANAGED) != 0)
3745 if (vm_page_in_laundry(m))
3749 vm_page_enqueue(m, PQ_LAUNDRY);
3754 * vm_page_unswappable
3756 * Put a page in the PQ_UNSWAPPABLE holding queue.
3759 vm_page_unswappable(vm_page_t m)
3762 vm_page_assert_locked(m);
3763 KASSERT(!vm_page_wired(m) && (m->oflags & VPO_UNMANAGED) == 0,
3764 ("page %p already unswappable", m));
3767 vm_page_enqueue(m, PQ_UNSWAPPABLE);
3771 * Attempt to free the page. If it cannot be freed, do nothing. Returns true
3772 * if the page is freed and false otherwise.
3774 * The page must be managed. The page and its containing object must be
3778 vm_page_try_to_free(vm_page_t m)
3781 vm_page_assert_locked(m);
3782 VM_OBJECT_ASSERT_WLOCKED(m->object);
3783 KASSERT((m->oflags & VPO_UNMANAGED) == 0, ("page %p is unmanaged", m));
3784 if (m->dirty != 0 || vm_page_held(m) || vm_page_busied(m))
3786 if (m->object->ref_count != 0) {
3798 * Apply the specified advice to the given page.
3800 * The object and page must be locked.
3803 vm_page_advise(vm_page_t m, int advice)
3806 vm_page_assert_locked(m);
3807 VM_OBJECT_ASSERT_WLOCKED(m->object);
3808 if (advice == MADV_FREE)
3810 * Mark the page clean. This will allow the page to be freed
3811 * without first paging it out. MADV_FREE pages are often
3812 * quickly reused by malloc(3), so we do not do anything that
3813 * would result in a page fault on a later access.
3816 else if (advice != MADV_DONTNEED) {
3817 if (advice == MADV_WILLNEED)
3818 vm_page_activate(m);
3823 * Clear any references to the page. Otherwise, the page daemon will
3824 * immediately reactivate the page.
3826 vm_page_aflag_clear(m, PGA_REFERENCED);
3828 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3832 * Place clean pages near the head of the inactive queue rather than
3833 * the tail, thus defeating the queue's LRU operation and ensuring that
3834 * the page will be reused quickly. Dirty pages not already in the
3835 * laundry are moved there.
3838 vm_page_deactivate_noreuse(m);
3839 else if (!vm_page_in_laundry(m))
3844 * Grab a page, waiting until we are waken up due to the page
3845 * changing state. We keep on waiting, if the page continues
3846 * to be in the object. If the page doesn't exist, first allocate it
3847 * and then conditionally zero it.
3849 * This routine may sleep.
3851 * The object must be locked on entry. The lock will, however, be released
3852 * and reacquired if the routine sleeps.
3855 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3861 VM_OBJECT_ASSERT_WLOCKED(object);
3862 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3863 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3864 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3865 pflags = allocflags &
3866 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
3867 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3868 pflags |= VM_ALLOC_WAITFAIL;
3870 if ((m = vm_page_lookup(object, pindex)) != NULL) {
3871 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3872 vm_page_xbusied(m) : vm_page_busied(m);
3874 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3877 * Reference the page before unlocking and
3878 * sleeping so that the page daemon is less
3879 * likely to reclaim it.
3881 vm_page_aflag_set(m, PGA_REFERENCED);
3883 VM_OBJECT_WUNLOCK(object);
3884 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
3885 VM_ALLOC_IGN_SBUSY) != 0);
3886 VM_OBJECT_WLOCK(object);
3889 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3895 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3897 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3902 m = vm_page_alloc(object, pindex, pflags);
3904 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3908 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3914 * Return the specified range of pages from the given object. For each
3915 * page offset within the range, if a page already exists within the object
3916 * at that offset and it is busy, then wait for it to change state. If,
3917 * instead, the page doesn't exist, then allocate it.
3919 * The caller must always specify an allocation class.
3921 * allocation classes:
3922 * VM_ALLOC_NORMAL normal process request
3923 * VM_ALLOC_SYSTEM system *really* needs the pages
3925 * The caller must always specify that the pages are to be busied and/or
3928 * optional allocation flags:
3929 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
3930 * VM_ALLOC_NOBUSY do not exclusive busy the page
3931 * VM_ALLOC_NOWAIT do not sleep
3932 * VM_ALLOC_SBUSY set page to sbusy state
3933 * VM_ALLOC_WIRED wire the pages
3934 * VM_ALLOC_ZERO zero and validate any invalid pages
3936 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
3937 * may return a partial prefix of the requested range.
3940 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
3941 vm_page_t *ma, int count)
3948 VM_OBJECT_ASSERT_WLOCKED(object);
3949 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
3950 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
3951 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
3952 (allocflags & VM_ALLOC_WIRED) != 0,
3953 ("vm_page_grab_pages: the pages must be busied or wired"));
3954 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3955 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3956 ("vm_page_grab_pages: VM_ALLOC_SBUSY/IGN_SBUSY mismatch"));
3959 pflags = allocflags & ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK |
3960 VM_ALLOC_WAITFAIL | VM_ALLOC_IGN_SBUSY);
3961 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3962 pflags |= VM_ALLOC_WAITFAIL;
3965 m = vm_radix_lookup_le(&object->rtree, pindex + i);
3966 if (m == NULL || m->pindex != pindex + i) {
3970 mpred = TAILQ_PREV(m, pglist, listq);
3971 for (; i < count; i++) {
3973 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3974 vm_page_xbusied(m) : vm_page_busied(m);
3976 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3979 * Reference the page before unlocking and
3980 * sleeping so that the page daemon is less
3981 * likely to reclaim it.
3983 vm_page_aflag_set(m, PGA_REFERENCED);
3985 VM_OBJECT_WUNLOCK(object);
3986 vm_page_busy_sleep(m, "grbmaw", (allocflags &
3987 VM_ALLOC_IGN_SBUSY) != 0);
3988 VM_OBJECT_WLOCK(object);
3991 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3996 if ((allocflags & (VM_ALLOC_NOBUSY |
3997 VM_ALLOC_SBUSY)) == 0)
3999 if ((allocflags & VM_ALLOC_SBUSY) != 0)
4002 m = vm_page_alloc_after(object, pindex + i,
4003 pflags | VM_ALLOC_COUNT(count - i), mpred);
4005 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4010 if (m->valid == 0 && (allocflags & VM_ALLOC_ZERO) != 0) {
4011 if ((m->flags & PG_ZERO) == 0)
4013 m->valid = VM_PAGE_BITS_ALL;
4016 m = vm_page_next(m);
4022 * Mapping function for valid or dirty bits in a page.
4024 * Inputs are required to range within a page.
4027 vm_page_bits(int base, int size)
4033 base + size <= PAGE_SIZE,
4034 ("vm_page_bits: illegal base/size %d/%d", base, size)
4037 if (size == 0) /* handle degenerate case */
4040 first_bit = base >> DEV_BSHIFT;
4041 last_bit = (base + size - 1) >> DEV_BSHIFT;
4043 return (((vm_page_bits_t)2 << last_bit) -
4044 ((vm_page_bits_t)1 << first_bit));
4048 * vm_page_set_valid_range:
4050 * Sets portions of a page valid. The arguments are expected
4051 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4052 * of any partial chunks touched by the range. The invalid portion of
4053 * such chunks will be zeroed.
4055 * (base + size) must be less then or equal to PAGE_SIZE.
4058 vm_page_set_valid_range(vm_page_t m, int base, int size)
4062 VM_OBJECT_ASSERT_WLOCKED(m->object);
4063 if (size == 0) /* handle degenerate case */
4067 * If the base is not DEV_BSIZE aligned and the valid
4068 * bit is clear, we have to zero out a portion of the
4071 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4072 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
4073 pmap_zero_page_area(m, frag, base - frag);
4076 * If the ending offset is not DEV_BSIZE aligned and the
4077 * valid bit is clear, we have to zero out a portion of
4080 endoff = base + size;
4081 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4082 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
4083 pmap_zero_page_area(m, endoff,
4084 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4087 * Assert that no previously invalid block that is now being validated
4090 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
4091 ("vm_page_set_valid_range: page %p is dirty", m));
4094 * Set valid bits inclusive of any overlap.
4096 m->valid |= vm_page_bits(base, size);
4100 * Clear the given bits from the specified page's dirty field.
4102 static __inline void
4103 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
4106 #if PAGE_SIZE < 16384
4111 * If the object is locked and the page is neither exclusive busy nor
4112 * write mapped, then the page's dirty field cannot possibly be
4113 * set by a concurrent pmap operation.
4115 VM_OBJECT_ASSERT_WLOCKED(m->object);
4116 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
4117 m->dirty &= ~pagebits;
4120 * The pmap layer can call vm_page_dirty() without
4121 * holding a distinguished lock. The combination of
4122 * the object's lock and an atomic operation suffice
4123 * to guarantee consistency of the page dirty field.
4125 * For PAGE_SIZE == 32768 case, compiler already
4126 * properly aligns the dirty field, so no forcible
4127 * alignment is needed. Only require existence of
4128 * atomic_clear_64 when page size is 32768.
4130 addr = (uintptr_t)&m->dirty;
4131 #if PAGE_SIZE == 32768
4132 atomic_clear_64((uint64_t *)addr, pagebits);
4133 #elif PAGE_SIZE == 16384
4134 atomic_clear_32((uint32_t *)addr, pagebits);
4135 #else /* PAGE_SIZE <= 8192 */
4137 * Use a trick to perform a 32-bit atomic on the
4138 * containing aligned word, to not depend on the existence
4139 * of atomic_clear_{8, 16}.
4141 shift = addr & (sizeof(uint32_t) - 1);
4142 #if BYTE_ORDER == BIG_ENDIAN
4143 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
4147 addr &= ~(sizeof(uint32_t) - 1);
4148 atomic_clear_32((uint32_t *)addr, pagebits << shift);
4149 #endif /* PAGE_SIZE */
4154 * vm_page_set_validclean:
4156 * Sets portions of a page valid and clean. The arguments are expected
4157 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4158 * of any partial chunks touched by the range. The invalid portion of
4159 * such chunks will be zero'd.
4161 * (base + size) must be less then or equal to PAGE_SIZE.
4164 vm_page_set_validclean(vm_page_t m, int base, int size)
4166 vm_page_bits_t oldvalid, pagebits;
4169 VM_OBJECT_ASSERT_WLOCKED(m->object);
4170 if (size == 0) /* handle degenerate case */
4174 * If the base is not DEV_BSIZE aligned and the valid
4175 * bit is clear, we have to zero out a portion of the
4178 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4179 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
4180 pmap_zero_page_area(m, frag, base - frag);
4183 * If the ending offset is not DEV_BSIZE aligned and the
4184 * valid bit is clear, we have to zero out a portion of
4187 endoff = base + size;
4188 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4189 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
4190 pmap_zero_page_area(m, endoff,
4191 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4194 * Set valid, clear dirty bits. If validating the entire
4195 * page we can safely clear the pmap modify bit. We also
4196 * use this opportunity to clear the VPO_NOSYNC flag. If a process
4197 * takes a write fault on a MAP_NOSYNC memory area the flag will
4200 * We set valid bits inclusive of any overlap, but we can only
4201 * clear dirty bits for DEV_BSIZE chunks that are fully within
4204 oldvalid = m->valid;
4205 pagebits = vm_page_bits(base, size);
4206 m->valid |= pagebits;
4208 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
4209 frag = DEV_BSIZE - frag;
4215 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
4217 if (base == 0 && size == PAGE_SIZE) {
4219 * The page can only be modified within the pmap if it is
4220 * mapped, and it can only be mapped if it was previously
4223 if (oldvalid == VM_PAGE_BITS_ALL)
4225 * Perform the pmap_clear_modify() first. Otherwise,
4226 * a concurrent pmap operation, such as
4227 * pmap_protect(), could clear a modification in the
4228 * pmap and set the dirty field on the page before
4229 * pmap_clear_modify() had begun and after the dirty
4230 * field was cleared here.
4232 pmap_clear_modify(m);
4234 m->oflags &= ~VPO_NOSYNC;
4235 } else if (oldvalid != VM_PAGE_BITS_ALL)
4236 m->dirty &= ~pagebits;
4238 vm_page_clear_dirty_mask(m, pagebits);
4242 vm_page_clear_dirty(vm_page_t m, int base, int size)
4245 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
4249 * vm_page_set_invalid:
4251 * Invalidates DEV_BSIZE'd chunks within a page. Both the
4252 * valid and dirty bits for the effected areas are cleared.
4255 vm_page_set_invalid(vm_page_t m, int base, int size)
4257 vm_page_bits_t bits;
4261 VM_OBJECT_ASSERT_WLOCKED(object);
4262 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
4263 size >= object->un_pager.vnp.vnp_size)
4264 bits = VM_PAGE_BITS_ALL;
4266 bits = vm_page_bits(base, size);
4267 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
4270 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
4271 !pmap_page_is_mapped(m),
4272 ("vm_page_set_invalid: page %p is mapped", m));
4278 * vm_page_zero_invalid()
4280 * The kernel assumes that the invalid portions of a page contain
4281 * garbage, but such pages can be mapped into memory by user code.
4282 * When this occurs, we must zero out the non-valid portions of the
4283 * page so user code sees what it expects.
4285 * Pages are most often semi-valid when the end of a file is mapped
4286 * into memory and the file's size is not page aligned.
4289 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
4294 VM_OBJECT_ASSERT_WLOCKED(m->object);
4296 * Scan the valid bits looking for invalid sections that
4297 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
4298 * valid bit may be set ) have already been zeroed by
4299 * vm_page_set_validclean().
4301 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
4302 if (i == (PAGE_SIZE / DEV_BSIZE) ||
4303 (m->valid & ((vm_page_bits_t)1 << i))) {
4305 pmap_zero_page_area(m,
4306 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
4313 * setvalid is TRUE when we can safely set the zero'd areas
4314 * as being valid. We can do this if there are no cache consistancy
4315 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
4318 m->valid = VM_PAGE_BITS_ALL;
4324 * Is (partial) page valid? Note that the case where size == 0
4325 * will return FALSE in the degenerate case where the page is
4326 * entirely invalid, and TRUE otherwise.
4329 vm_page_is_valid(vm_page_t m, int base, int size)
4331 vm_page_bits_t bits;
4333 VM_OBJECT_ASSERT_LOCKED(m->object);
4334 bits = vm_page_bits(base, size);
4335 return (m->valid != 0 && (m->valid & bits) == bits);
4339 * Returns true if all of the specified predicates are true for the entire
4340 * (super)page and false otherwise.
4343 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
4349 if (skip_m != NULL && skip_m->object != object)
4351 VM_OBJECT_ASSERT_LOCKED(object);
4352 npages = atop(pagesizes[m->psind]);
4355 * The physically contiguous pages that make up a superpage, i.e., a
4356 * page with a page size index ("psind") greater than zero, will
4357 * occupy adjacent entries in vm_page_array[].
4359 for (i = 0; i < npages; i++) {
4360 /* Always test object consistency, including "skip_m". */
4361 if (m[i].object != object)
4363 if (&m[i] == skip_m)
4365 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
4367 if ((flags & PS_ALL_DIRTY) != 0) {
4369 * Calling vm_page_test_dirty() or pmap_is_modified()
4370 * might stop this case from spuriously returning
4371 * "false". However, that would require a write lock
4372 * on the object containing "m[i]".
4374 if (m[i].dirty != VM_PAGE_BITS_ALL)
4377 if ((flags & PS_ALL_VALID) != 0 &&
4378 m[i].valid != VM_PAGE_BITS_ALL)
4385 * Set the page's dirty bits if the page is modified.
4388 vm_page_test_dirty(vm_page_t m)
4391 VM_OBJECT_ASSERT_WLOCKED(m->object);
4392 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
4397 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
4400 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
4404 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
4407 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
4411 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
4414 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
4417 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
4419 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
4422 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
4426 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
4429 mtx_assert_(vm_page_lockptr(m), a, file, line);
4435 vm_page_object_lock_assert(vm_page_t m)
4439 * Certain of the page's fields may only be modified by the
4440 * holder of the containing object's lock or the exclusive busy.
4441 * holder. Unfortunately, the holder of the write busy is
4442 * not recorded, and thus cannot be checked here.
4444 if (m->object != NULL && !vm_page_xbusied(m))
4445 VM_OBJECT_ASSERT_WLOCKED(m->object);
4449 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
4452 if ((bits & PGA_WRITEABLE) == 0)
4456 * The PGA_WRITEABLE flag can only be set if the page is
4457 * managed, is exclusively busied or the object is locked.
4458 * Currently, this flag is only set by pmap_enter().
4460 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4461 ("PGA_WRITEABLE on unmanaged page"));
4462 if (!vm_page_xbusied(m))
4463 VM_OBJECT_ASSERT_LOCKED(m->object);
4467 #include "opt_ddb.h"
4469 #include <sys/kernel.h>
4471 #include <ddb/ddb.h>
4473 DB_SHOW_COMMAND(page, vm_page_print_page_info)
4476 db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
4477 db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
4478 db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
4479 db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
4480 db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
4481 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
4482 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
4483 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
4484 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
4487 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
4491 db_printf("pq_free %d\n", vm_free_count());
4492 for (dom = 0; dom < vm_ndomains; dom++) {
4494 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
4496 vm_dom[dom].vmd_page_count,
4497 vm_dom[dom].vmd_free_count,
4498 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
4499 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
4500 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
4501 vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
4505 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
4508 boolean_t phys, virt;
4511 db_printf("show pginfo addr\n");
4515 phys = strchr(modif, 'p') != NULL;
4516 virt = strchr(modif, 'v') != NULL;
4518 m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
4520 m = PHYS_TO_VM_PAGE(addr);
4522 m = (vm_page_t)addr;
4524 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
4525 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
4526 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
4527 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
4528 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);