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.
1463 * The object must be locked. The page must be locked if it is managed.
1466 vm_page_remove(vm_page_t m)
1471 if ((m->oflags & VPO_UNMANAGED) == 0)
1472 vm_page_assert_locked(m);
1473 if ((object = m->object) == NULL)
1475 VM_OBJECT_ASSERT_WLOCKED(object);
1476 if (vm_page_xbusied(m))
1477 vm_page_xunbusy_maybelocked(m);
1478 mrem = vm_radix_remove(&object->rtree, m->pindex);
1479 KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1482 * Now remove from the object's list of backed pages.
1484 TAILQ_REMOVE(&object->memq, m, listq);
1487 * And show that the object has one fewer resident page.
1489 object->resident_page_count--;
1492 * The vnode may now be recycled.
1494 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1495 vdrop(object->handle);
1503 * Returns the page associated with the object/offset
1504 * pair specified; if none is found, NULL is returned.
1506 * The object must be locked.
1509 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1512 VM_OBJECT_ASSERT_LOCKED(object);
1513 return (vm_radix_lookup(&object->rtree, pindex));
1517 * vm_page_find_least:
1519 * Returns the page associated with the object with least pindex
1520 * greater than or equal to the parameter pindex, or NULL.
1522 * The object must be locked.
1525 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1529 VM_OBJECT_ASSERT_LOCKED(object);
1530 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1531 m = vm_radix_lookup_ge(&object->rtree, pindex);
1536 * Returns the given page's successor (by pindex) within the object if it is
1537 * resident; if none is found, NULL is returned.
1539 * The object must be locked.
1542 vm_page_next(vm_page_t m)
1546 VM_OBJECT_ASSERT_LOCKED(m->object);
1547 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1548 MPASS(next->object == m->object);
1549 if (next->pindex != m->pindex + 1)
1556 * Returns the given page's predecessor (by pindex) within the object if it is
1557 * resident; if none is found, NULL is returned.
1559 * The object must be locked.
1562 vm_page_prev(vm_page_t m)
1566 VM_OBJECT_ASSERT_LOCKED(m->object);
1567 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1568 MPASS(prev->object == m->object);
1569 if (prev->pindex != m->pindex - 1)
1576 * Uses the page mnew as a replacement for an existing page at index
1577 * pindex which must be already present in the object.
1579 * The existing page must not be on a paging queue.
1582 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1586 VM_OBJECT_ASSERT_WLOCKED(object);
1587 KASSERT(mnew->object == NULL,
1588 ("vm_page_replace: page %p already in object", mnew));
1589 KASSERT(mnew->queue == PQ_NONE,
1590 ("vm_page_replace: new page %p is on a paging queue", mnew));
1593 * This function mostly follows vm_page_insert() and
1594 * vm_page_remove() without the radix, object count and vnode
1595 * dance. Double check such functions for more comments.
1598 mnew->object = object;
1599 mnew->pindex = pindex;
1600 mold = vm_radix_replace(&object->rtree, mnew);
1601 KASSERT(mold->queue == PQ_NONE,
1602 ("vm_page_replace: old page %p is on a paging queue", mold));
1604 /* Keep the resident page list in sorted order. */
1605 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1606 TAILQ_REMOVE(&object->memq, mold, listq);
1608 mold->object = NULL;
1609 vm_page_xunbusy_maybelocked(mold);
1612 * The object's resident_page_count does not change because we have
1613 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1615 if (pmap_page_is_write_mapped(mnew))
1616 vm_object_set_writeable_dirty(object);
1623 * Move the given memory entry from its
1624 * current object to the specified target object/offset.
1626 * Note: swap associated with the page must be invalidated by the move. We
1627 * have to do this for several reasons: (1) we aren't freeing the
1628 * page, (2) we are dirtying the page, (3) the VM system is probably
1629 * moving the page from object A to B, and will then later move
1630 * the backing store from A to B and we can't have a conflict.
1632 * Note: we *always* dirty the page. It is necessary both for the
1633 * fact that we moved it, and because we may be invalidating
1636 * The objects must be locked.
1639 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1644 VM_OBJECT_ASSERT_WLOCKED(new_object);
1646 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1647 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1648 ("vm_page_rename: pindex already renamed"));
1651 * Create a custom version of vm_page_insert() which does not depend
1652 * by m_prev and can cheat on the implementation aspects of the
1656 m->pindex = new_pindex;
1657 if (vm_radix_insert(&new_object->rtree, m)) {
1663 * The operation cannot fail anymore. The removal must happen before
1664 * the listq iterator is tainted.
1670 /* Return back to the new pindex to complete vm_page_insert(). */
1671 m->pindex = new_pindex;
1672 m->object = new_object;
1674 vm_page_insert_radixdone(m, new_object, mpred);
1682 * Allocate and return a page that is associated with the specified
1683 * object and offset pair. By default, this page is exclusive busied.
1685 * The caller must always specify an allocation class.
1687 * allocation classes:
1688 * VM_ALLOC_NORMAL normal process request
1689 * VM_ALLOC_SYSTEM system *really* needs a page
1690 * VM_ALLOC_INTERRUPT interrupt time request
1692 * optional allocation flags:
1693 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1694 * intends to allocate
1695 * VM_ALLOC_NOBUSY do not exclusive busy the page
1696 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1697 * VM_ALLOC_NOOBJ page is not associated with an object and
1698 * should not be exclusive busy
1699 * VM_ALLOC_SBUSY shared busy the allocated page
1700 * VM_ALLOC_WIRED wire the allocated page
1701 * VM_ALLOC_ZERO prefer a zeroed page
1704 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1707 return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1708 vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1712 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1716 return (vm_page_alloc_domain_after(object, pindex, domain, req,
1717 object != NULL ? vm_radix_lookup_le(&object->rtree, pindex) :
1722 * Allocate a page in the specified object with the given page index. To
1723 * optimize insertion of the page into the object, the caller must also specifiy
1724 * the resident page in the object with largest index smaller than the given
1725 * page index, or NULL if no such page exists.
1728 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1729 int req, vm_page_t mpred)
1731 struct vm_domainset_iter di;
1735 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1737 m = vm_page_alloc_domain_after(object, pindex, domain, req,
1741 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
1747 * Returns true if the number of free pages exceeds the minimum
1748 * for the request class and false otherwise.
1751 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
1753 u_int limit, old, new;
1755 req = req & VM_ALLOC_CLASS_MASK;
1758 * The page daemon is allowed to dig deeper into the free page list.
1760 if (curproc == pageproc && req != VM_ALLOC_INTERRUPT)
1761 req = VM_ALLOC_SYSTEM;
1762 if (req == VM_ALLOC_INTERRUPT)
1764 else if (req == VM_ALLOC_SYSTEM)
1765 limit = vmd->vmd_interrupt_free_min;
1767 limit = vmd->vmd_free_reserved;
1770 * Attempt to reserve the pages. Fail if we're below the limit.
1773 old = vmd->vmd_free_count;
1778 } while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
1780 /* Wake the page daemon if we've crossed the threshold. */
1781 if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
1782 pagedaemon_wakeup(vmd->vmd_domain);
1784 /* Only update bitsets on transitions. */
1785 if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
1786 (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
1793 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
1794 int req, vm_page_t mpred)
1796 struct vm_domain *vmd;
1800 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1801 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1802 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1803 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1804 ("inconsistent object(%p)/req(%x)", object, req));
1805 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1806 ("Can't sleep and retry object insertion."));
1807 KASSERT(mpred == NULL || mpred->pindex < pindex,
1808 ("mpred %p doesn't precede pindex 0x%jx", mpred,
1809 (uintmax_t)pindex));
1811 VM_OBJECT_ASSERT_WLOCKED(object);
1815 #if VM_NRESERVLEVEL > 0
1817 * Can we allocate the page from a reservation?
1819 if (vm_object_reserv(object) &&
1820 (m = vm_reserv_alloc_page(object, pindex, domain, req, mpred)) !=
1822 domain = vm_phys_domain(m);
1823 vmd = VM_DOMAIN(domain);
1827 vmd = VM_DOMAIN(domain);
1828 if (object != NULL && vmd->vmd_pgcache != NULL) {
1829 m = uma_zalloc(vmd->vmd_pgcache, M_NOWAIT);
1833 if (vm_domain_allocate(vmd, req, 1)) {
1835 * If not, allocate it from the free page queues.
1837 vm_domain_free_lock(vmd);
1838 m = vm_phys_alloc_pages(domain, object != NULL ?
1839 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1840 vm_domain_free_unlock(vmd);
1842 vm_domain_freecnt_inc(vmd, 1);
1843 #if VM_NRESERVLEVEL > 0
1844 if (vm_reserv_reclaim_inactive(domain))
1851 * Not allocatable, give up.
1853 if (vm_domain_alloc_fail(vmd, object, req))
1859 * At this point we had better have found a good page.
1861 KASSERT(m != NULL, ("missing page"));
1865 vm_page_alloc_check(m);
1868 * Initialize the page. Only the PG_ZERO flag is inherited.
1871 if ((req & VM_ALLOC_ZERO) != 0)
1874 if ((req & VM_ALLOC_NODUMP) != 0)
1878 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1880 m->busy_lock = VPB_UNBUSIED;
1881 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1882 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1883 if ((req & VM_ALLOC_SBUSY) != 0)
1884 m->busy_lock = VPB_SHARERS_WORD(1);
1885 if (req & VM_ALLOC_WIRED) {
1887 * The page lock is not required for wiring a page until that
1888 * page is inserted into the object.
1895 if (object != NULL) {
1896 if (vm_page_insert_after(m, object, pindex, mpred)) {
1897 if (req & VM_ALLOC_WIRED) {
1901 KASSERT(m->object == NULL, ("page %p has object", m));
1902 m->oflags = VPO_UNMANAGED;
1903 m->busy_lock = VPB_UNBUSIED;
1904 /* Don't change PG_ZERO. */
1905 vm_page_free_toq(m);
1906 if (req & VM_ALLOC_WAITFAIL) {
1907 VM_OBJECT_WUNLOCK(object);
1909 VM_OBJECT_WLOCK(object);
1914 /* Ignore device objects; the pager sets "memattr" for them. */
1915 if (object->memattr != VM_MEMATTR_DEFAULT &&
1916 (object->flags & OBJ_FICTITIOUS) == 0)
1917 pmap_page_set_memattr(m, object->memattr);
1925 * vm_page_alloc_contig:
1927 * Allocate a contiguous set of physical pages of the given size "npages"
1928 * from the free lists. All of the physical pages must be at or above
1929 * the given physical address "low" and below the given physical address
1930 * "high". The given value "alignment" determines the alignment of the
1931 * first physical page in the set. If the given value "boundary" is
1932 * non-zero, then the set of physical pages cannot cross any physical
1933 * address boundary that is a multiple of that value. Both "alignment"
1934 * and "boundary" must be a power of two.
1936 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1937 * then the memory attribute setting for the physical pages is configured
1938 * to the object's memory attribute setting. Otherwise, the memory
1939 * attribute setting for the physical pages is configured to "memattr",
1940 * overriding the object's memory attribute setting. However, if the
1941 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1942 * memory attribute setting for the physical pages cannot be configured
1943 * to VM_MEMATTR_DEFAULT.
1945 * The specified object may not contain fictitious pages.
1947 * The caller must always specify an allocation class.
1949 * allocation classes:
1950 * VM_ALLOC_NORMAL normal process request
1951 * VM_ALLOC_SYSTEM system *really* needs a page
1952 * VM_ALLOC_INTERRUPT interrupt time request
1954 * optional allocation flags:
1955 * VM_ALLOC_NOBUSY do not exclusive busy the page
1956 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1957 * VM_ALLOC_NOOBJ page is not associated with an object and
1958 * should not be exclusive busy
1959 * VM_ALLOC_SBUSY shared busy the allocated page
1960 * VM_ALLOC_WIRED wire the allocated page
1961 * VM_ALLOC_ZERO prefer a zeroed page
1964 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1965 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1966 vm_paddr_t boundary, vm_memattr_t memattr)
1968 struct vm_domainset_iter di;
1972 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1974 m = vm_page_alloc_contig_domain(object, pindex, domain, req,
1975 npages, low, high, alignment, boundary, memattr);
1978 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
1984 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1985 int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1986 vm_paddr_t boundary, vm_memattr_t memattr)
1988 struct vm_domain *vmd;
1989 vm_page_t m, m_ret, mpred;
1990 u_int busy_lock, flags, oflags;
1992 mpred = NULL; /* XXX: pacify gcc */
1993 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1994 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1995 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1996 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1997 ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
1999 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2000 ("Can't sleep and retry object insertion."));
2001 if (object != NULL) {
2002 VM_OBJECT_ASSERT_WLOCKED(object);
2003 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2004 ("vm_page_alloc_contig: object %p has fictitious pages",
2007 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2009 if (object != NULL) {
2010 mpred = vm_radix_lookup_le(&object->rtree, pindex);
2011 KASSERT(mpred == NULL || mpred->pindex != pindex,
2012 ("vm_page_alloc_contig: pindex already allocated"));
2016 * Can we allocate the pages without the number of free pages falling
2017 * below the lower bound for the allocation class?
2020 #if VM_NRESERVLEVEL > 0
2022 * Can we allocate the pages from a reservation?
2024 if (vm_object_reserv(object) &&
2025 (m_ret = vm_reserv_alloc_contig(object, pindex, domain, req,
2026 mpred, npages, low, high, alignment, boundary)) != NULL) {
2027 domain = vm_phys_domain(m_ret);
2028 vmd = VM_DOMAIN(domain);
2033 vmd = VM_DOMAIN(domain);
2034 if (vm_domain_allocate(vmd, req, npages)) {
2036 * allocate them from the free page queues.
2038 vm_domain_free_lock(vmd);
2039 m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2040 alignment, boundary);
2041 vm_domain_free_unlock(vmd);
2042 if (m_ret == NULL) {
2043 vm_domain_freecnt_inc(vmd, npages);
2044 #if VM_NRESERVLEVEL > 0
2045 if (vm_reserv_reclaim_contig(domain, npages, low,
2046 high, alignment, boundary))
2051 if (m_ret == NULL) {
2052 if (vm_domain_alloc_fail(vmd, object, req))
2056 #if VM_NRESERVLEVEL > 0
2059 for (m = m_ret; m < &m_ret[npages]; m++) {
2061 vm_page_alloc_check(m);
2065 * Initialize the pages. Only the PG_ZERO flag is inherited.
2068 if ((req & VM_ALLOC_ZERO) != 0)
2070 if ((req & VM_ALLOC_NODUMP) != 0)
2072 oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2074 busy_lock = VPB_UNBUSIED;
2075 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2076 busy_lock = VPB_SINGLE_EXCLUSIVER;
2077 if ((req & VM_ALLOC_SBUSY) != 0)
2078 busy_lock = VPB_SHARERS_WORD(1);
2079 if ((req & VM_ALLOC_WIRED) != 0)
2080 vm_wire_add(npages);
2081 if (object != NULL) {
2082 if (object->memattr != VM_MEMATTR_DEFAULT &&
2083 memattr == VM_MEMATTR_DEFAULT)
2084 memattr = object->memattr;
2086 for (m = m_ret; m < &m_ret[npages]; m++) {
2088 m->flags = (m->flags | PG_NODUMP) & flags;
2089 m->busy_lock = busy_lock;
2090 if ((req & VM_ALLOC_WIRED) != 0)
2094 if (object != NULL) {
2095 if (vm_page_insert_after(m, object, pindex, mpred)) {
2096 if ((req & VM_ALLOC_WIRED) != 0)
2097 vm_wire_sub(npages);
2098 KASSERT(m->object == NULL,
2099 ("page %p has object", m));
2101 for (m = m_ret; m < &m_ret[npages]; m++) {
2103 (req & VM_ALLOC_WIRED) != 0)
2105 m->oflags = VPO_UNMANAGED;
2106 m->busy_lock = VPB_UNBUSIED;
2107 /* Don't change PG_ZERO. */
2108 vm_page_free_toq(m);
2110 if (req & VM_ALLOC_WAITFAIL) {
2111 VM_OBJECT_WUNLOCK(object);
2113 VM_OBJECT_WLOCK(object);
2120 if (memattr != VM_MEMATTR_DEFAULT)
2121 pmap_page_set_memattr(m, memattr);
2128 * Check a page that has been freshly dequeued from a freelist.
2131 vm_page_alloc_check(vm_page_t m)
2134 KASSERT(m->object == NULL, ("page %p has object", m));
2135 KASSERT(m->queue == PQ_NONE && (m->aflags & PGA_QUEUE_STATE_MASK) == 0,
2136 ("page %p has unexpected queue %d, flags %#x",
2137 m, m->queue, (m->aflags & PGA_QUEUE_STATE_MASK)));
2138 KASSERT(!vm_page_held(m), ("page %p is held", m));
2139 KASSERT(!vm_page_busied(m), ("page %p is busy", m));
2140 KASSERT(m->dirty == 0, ("page %p is dirty", m));
2141 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2142 ("page %p has unexpected memattr %d",
2143 m, pmap_page_get_memattr(m)));
2144 KASSERT(m->valid == 0, ("free page %p is valid", m));
2148 * vm_page_alloc_freelist:
2150 * Allocate a physical page from the specified free page list.
2152 * The caller must always specify an allocation class.
2154 * allocation classes:
2155 * VM_ALLOC_NORMAL normal process request
2156 * VM_ALLOC_SYSTEM system *really* needs a page
2157 * VM_ALLOC_INTERRUPT interrupt time request
2159 * optional allocation flags:
2160 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2161 * intends to allocate
2162 * VM_ALLOC_WIRED wire the allocated page
2163 * VM_ALLOC_ZERO prefer a zeroed page
2166 vm_page_alloc_freelist(int freelist, int req)
2168 struct vm_domainset_iter di;
2172 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2174 m = vm_page_alloc_freelist_domain(domain, freelist, req);
2177 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2183 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2185 struct vm_domain *vmd;
2190 vmd = VM_DOMAIN(domain);
2192 if (vm_domain_allocate(vmd, req, 1)) {
2193 vm_domain_free_lock(vmd);
2194 m = vm_phys_alloc_freelist_pages(domain, freelist,
2195 VM_FREEPOOL_DIRECT, 0);
2196 vm_domain_free_unlock(vmd);
2198 vm_domain_freecnt_inc(vmd, 1);
2201 if (vm_domain_alloc_fail(vmd, NULL, req))
2206 vm_page_alloc_check(m);
2209 * Initialize the page. Only the PG_ZERO flag is inherited.
2213 if ((req & VM_ALLOC_ZERO) != 0)
2216 if ((req & VM_ALLOC_WIRED) != 0) {
2218 * The page lock is not required for wiring a page that does
2219 * not belong to an object.
2224 /* Unmanaged pages don't use "act_count". */
2225 m->oflags = VPO_UNMANAGED;
2230 vm_page_import(void *arg, void **store, int cnt, int domain, int flags)
2232 struct vm_domain *vmd;
2236 /* Only import if we can bring in a full bucket. */
2237 if (cnt == 1 || !vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2239 domain = vmd->vmd_domain;
2240 vm_domain_free_lock(vmd);
2241 i = vm_phys_alloc_npages(domain, VM_FREEPOOL_DEFAULT, cnt,
2242 (vm_page_t *)store);
2243 vm_domain_free_unlock(vmd);
2245 vm_domain_freecnt_inc(vmd, cnt - i);
2251 vm_page_release(void *arg, void **store, int cnt)
2253 struct vm_domain *vmd;
2258 vm_domain_free_lock(vmd);
2259 for (i = 0; i < cnt; i++) {
2260 m = (vm_page_t)store[i];
2261 vm_phys_free_pages(m, 0);
2263 vm_domain_free_unlock(vmd);
2264 vm_domain_freecnt_inc(vmd, cnt);
2267 #define VPSC_ANY 0 /* No restrictions. */
2268 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2269 #define VPSC_NOSUPER 2 /* Skip superpages. */
2272 * vm_page_scan_contig:
2274 * Scan vm_page_array[] between the specified entries "m_start" and
2275 * "m_end" for a run of contiguous physical pages that satisfy the
2276 * specified conditions, and return the lowest page in the run. The
2277 * specified "alignment" determines the alignment of the lowest physical
2278 * page in the run. If the specified "boundary" is non-zero, then the
2279 * run of physical pages cannot span a physical address that is a
2280 * multiple of "boundary".
2282 * "m_end" is never dereferenced, so it need not point to a vm_page
2283 * structure within vm_page_array[].
2285 * "npages" must be greater than zero. "m_start" and "m_end" must not
2286 * span a hole (or discontiguity) in the physical address space. Both
2287 * "alignment" and "boundary" must be a power of two.
2290 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2291 u_long alignment, vm_paddr_t boundary, int options)
2297 #if VM_NRESERVLEVEL > 0
2300 int m_inc, order, run_ext, run_len;
2302 KASSERT(npages > 0, ("npages is 0"));
2303 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2304 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2308 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2309 KASSERT((m->flags & PG_MARKER) == 0,
2310 ("page %p is PG_MARKER", m));
2311 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->wire_count == 1,
2312 ("fictitious page %p has invalid wire count", m));
2315 * If the current page would be the start of a run, check its
2316 * physical address against the end, alignment, and boundary
2317 * conditions. If it doesn't satisfy these conditions, either
2318 * terminate the scan or advance to the next page that
2319 * satisfies the failed condition.
2322 KASSERT(m_run == NULL, ("m_run != NULL"));
2323 if (m + npages > m_end)
2325 pa = VM_PAGE_TO_PHYS(m);
2326 if ((pa & (alignment - 1)) != 0) {
2327 m_inc = atop(roundup2(pa, alignment) - pa);
2330 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2332 m_inc = atop(roundup2(pa, boundary) - pa);
2336 KASSERT(m_run != NULL, ("m_run == NULL"));
2338 vm_page_change_lock(m, &m_mtx);
2341 if (vm_page_held(m))
2343 #if VM_NRESERVLEVEL > 0
2344 else if ((level = vm_reserv_level(m)) >= 0 &&
2345 (options & VPSC_NORESERV) != 0) {
2347 /* Advance to the end of the reservation. */
2348 pa = VM_PAGE_TO_PHYS(m);
2349 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2353 else if ((object = m->object) != NULL) {
2355 * The page is considered eligible for relocation if
2356 * and only if it could be laundered or reclaimed by
2359 if (!VM_OBJECT_TRYRLOCK(object)) {
2361 VM_OBJECT_RLOCK(object);
2363 if (m->object != object) {
2365 * The page may have been freed.
2367 VM_OBJECT_RUNLOCK(object);
2369 } else if (vm_page_held(m)) {
2374 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2375 ("page %p is PG_UNHOLDFREE", m));
2376 /* Don't care: PG_NODUMP, PG_ZERO. */
2377 if (object->type != OBJT_DEFAULT &&
2378 object->type != OBJT_SWAP &&
2379 object->type != OBJT_VNODE) {
2381 #if VM_NRESERVLEVEL > 0
2382 } else if ((options & VPSC_NOSUPER) != 0 &&
2383 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2385 /* Advance to the end of the superpage. */
2386 pa = VM_PAGE_TO_PHYS(m);
2387 m_inc = atop(roundup2(pa + 1,
2388 vm_reserv_size(level)) - pa);
2390 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2391 vm_page_queue(m) != PQ_NONE && !vm_page_busied(m)) {
2393 * The page is allocated but eligible for
2394 * relocation. Extend the current run by one
2397 KASSERT(pmap_page_get_memattr(m) ==
2399 ("page %p has an unexpected memattr", m));
2400 KASSERT((m->oflags & (VPO_SWAPINPROG |
2401 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2402 ("page %p has unexpected oflags", m));
2403 /* Don't care: VPO_NOSYNC. */
2408 VM_OBJECT_RUNLOCK(object);
2409 #if VM_NRESERVLEVEL > 0
2410 } else if (level >= 0) {
2412 * The page is reserved but not yet allocated. In
2413 * other words, it is still free. Extend the current
2418 } else if ((order = m->order) < VM_NFREEORDER) {
2420 * The page is enqueued in the physical memory
2421 * allocator's free page queues. Moreover, it is the
2422 * first page in a power-of-two-sized run of
2423 * contiguous free pages. Add these pages to the end
2424 * of the current run, and jump ahead.
2426 run_ext = 1 << order;
2430 * Skip the page for one of the following reasons: (1)
2431 * It is enqueued in the physical memory allocator's
2432 * free page queues. However, it is not the first
2433 * page in a run of contiguous free pages. (This case
2434 * rarely occurs because the scan is performed in
2435 * ascending order.) (2) It is not reserved, and it is
2436 * transitioning from free to allocated. (Conversely,
2437 * the transition from allocated to free for managed
2438 * pages is blocked by the page lock.) (3) It is
2439 * allocated but not contained by an object and not
2440 * wired, e.g., allocated by Xen's balloon driver.
2446 * Extend or reset the current run of pages.
2461 if (run_len >= npages)
2467 * vm_page_reclaim_run:
2469 * Try to relocate each of the allocated virtual pages within the
2470 * specified run of physical pages to a new physical address. Free the
2471 * physical pages underlying the relocated virtual pages. A virtual page
2472 * is relocatable if and only if it could be laundered or reclaimed by
2473 * the page daemon. Whenever possible, a virtual page is relocated to a
2474 * physical address above "high".
2476 * Returns 0 if every physical page within the run was already free or
2477 * just freed by a successful relocation. Otherwise, returns a non-zero
2478 * value indicating why the last attempt to relocate a virtual page was
2481 * "req_class" must be an allocation class.
2484 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2487 struct vm_domain *vmd;
2489 struct spglist free;
2492 vm_page_t m, m_end, m_new;
2493 int error, order, req;
2495 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2496 ("req_class is not an allocation class"));
2500 m_end = m_run + npages;
2502 for (; error == 0 && m < m_end; m++) {
2503 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2504 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2507 * Avoid releasing and reacquiring the same page lock.
2509 vm_page_change_lock(m, &m_mtx);
2511 if (vm_page_held(m))
2513 else if ((object = m->object) != NULL) {
2515 * The page is relocated if and only if it could be
2516 * laundered or reclaimed by the page daemon.
2518 if (!VM_OBJECT_TRYWLOCK(object)) {
2520 VM_OBJECT_WLOCK(object);
2522 if (m->object != object) {
2524 * The page may have been freed.
2526 VM_OBJECT_WUNLOCK(object);
2528 } else if (vm_page_held(m)) {
2533 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2534 ("page %p is PG_UNHOLDFREE", m));
2535 /* Don't care: PG_NODUMP, PG_ZERO. */
2536 if (object->type != OBJT_DEFAULT &&
2537 object->type != OBJT_SWAP &&
2538 object->type != OBJT_VNODE)
2540 else if (object->memattr != VM_MEMATTR_DEFAULT)
2542 else if (vm_page_queue(m) != PQ_NONE &&
2543 !vm_page_busied(m)) {
2544 KASSERT(pmap_page_get_memattr(m) ==
2546 ("page %p has an unexpected memattr", m));
2547 KASSERT((m->oflags & (VPO_SWAPINPROG |
2548 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2549 ("page %p has unexpected oflags", m));
2550 /* Don't care: VPO_NOSYNC. */
2551 if (m->valid != 0) {
2553 * First, try to allocate a new page
2554 * that is above "high". Failing
2555 * that, try to allocate a new page
2556 * that is below "m_run". Allocate
2557 * the new page between the end of
2558 * "m_run" and "high" only as a last
2561 req = req_class | VM_ALLOC_NOOBJ;
2562 if ((m->flags & PG_NODUMP) != 0)
2563 req |= VM_ALLOC_NODUMP;
2564 if (trunc_page(high) !=
2565 ~(vm_paddr_t)PAGE_MASK) {
2566 m_new = vm_page_alloc_contig(
2571 VM_MEMATTR_DEFAULT);
2574 if (m_new == NULL) {
2575 pa = VM_PAGE_TO_PHYS(m_run);
2576 m_new = vm_page_alloc_contig(
2578 0, pa - 1, PAGE_SIZE, 0,
2579 VM_MEMATTR_DEFAULT);
2581 if (m_new == NULL) {
2583 m_new = vm_page_alloc_contig(
2585 pa, high, PAGE_SIZE, 0,
2586 VM_MEMATTR_DEFAULT);
2588 if (m_new == NULL) {
2592 KASSERT(!vm_page_wired(m_new),
2593 ("page %p is wired", m_new));
2596 * Replace "m" with the new page. For
2597 * vm_page_replace(), "m" must be busy
2598 * and dequeued. Finally, change "m"
2599 * as if vm_page_free() was called.
2601 if (object->ref_count != 0)
2603 m_new->aflags = m->aflags &
2604 ~PGA_QUEUE_STATE_MASK;
2605 KASSERT(m_new->oflags == VPO_UNMANAGED,
2606 ("page %p is managed", m_new));
2607 m_new->oflags = m->oflags & VPO_NOSYNC;
2608 pmap_copy_page(m, m_new);
2609 m_new->valid = m->valid;
2610 m_new->dirty = m->dirty;
2611 m->flags &= ~PG_ZERO;
2614 vm_page_replace_checked(m_new, object,
2616 if (vm_page_free_prep(m))
2617 SLIST_INSERT_HEAD(&free, m,
2621 * The new page must be deactivated
2622 * before the object is unlocked.
2624 vm_page_change_lock(m_new, &m_mtx);
2625 vm_page_deactivate(m_new);
2627 m->flags &= ~PG_ZERO;
2629 if (vm_page_free_prep(m))
2630 SLIST_INSERT_HEAD(&free, m,
2632 KASSERT(m->dirty == 0,
2633 ("page %p is dirty", m));
2638 VM_OBJECT_WUNLOCK(object);
2640 MPASS(vm_phys_domain(m) == domain);
2641 vmd = VM_DOMAIN(domain);
2642 vm_domain_free_lock(vmd);
2644 if (order < VM_NFREEORDER) {
2646 * The page is enqueued in the physical memory
2647 * allocator's free page queues. Moreover, it
2648 * is the first page in a power-of-two-sized
2649 * run of contiguous free pages. Jump ahead
2650 * to the last page within that run, and
2651 * continue from there.
2653 m += (1 << order) - 1;
2655 #if VM_NRESERVLEVEL > 0
2656 else if (vm_reserv_is_page_free(m))
2659 vm_domain_free_unlock(vmd);
2660 if (order == VM_NFREEORDER)
2666 if ((m = SLIST_FIRST(&free)) != NULL) {
2669 vmd = VM_DOMAIN(domain);
2671 vm_domain_free_lock(vmd);
2673 MPASS(vm_phys_domain(m) == domain);
2674 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2675 vm_phys_free_pages(m, 0);
2677 } while ((m = SLIST_FIRST(&free)) != NULL);
2678 vm_domain_free_unlock(vmd);
2679 vm_domain_freecnt_inc(vmd, cnt);
2686 CTASSERT(powerof2(NRUNS));
2688 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2690 #define MIN_RECLAIM 8
2693 * vm_page_reclaim_contig:
2695 * Reclaim allocated, contiguous physical memory satisfying the specified
2696 * conditions by relocating the virtual pages using that physical memory.
2697 * Returns true if reclamation is successful and false otherwise. Since
2698 * relocation requires the allocation of physical pages, reclamation may
2699 * fail due to a shortage of free pages. When reclamation fails, callers
2700 * are expected to perform vm_wait() before retrying a failed allocation
2701 * operation, e.g., vm_page_alloc_contig().
2703 * The caller must always specify an allocation class through "req".
2705 * allocation classes:
2706 * VM_ALLOC_NORMAL normal process request
2707 * VM_ALLOC_SYSTEM system *really* needs a page
2708 * VM_ALLOC_INTERRUPT interrupt time request
2710 * The optional allocation flags are ignored.
2712 * "npages" must be greater than zero. Both "alignment" and "boundary"
2713 * must be a power of two.
2716 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
2717 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2719 struct vm_domain *vmd;
2720 vm_paddr_t curr_low;
2721 vm_page_t m_run, m_runs[NRUNS];
2722 u_long count, reclaimed;
2723 int error, i, options, req_class;
2725 KASSERT(npages > 0, ("npages is 0"));
2726 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2727 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2728 req_class = req & VM_ALLOC_CLASS_MASK;
2731 * The page daemon is allowed to dig deeper into the free page list.
2733 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2734 req_class = VM_ALLOC_SYSTEM;
2737 * Return if the number of free pages cannot satisfy the requested
2740 vmd = VM_DOMAIN(domain);
2741 count = vmd->vmd_free_count;
2742 if (count < npages + vmd->vmd_free_reserved || (count < npages +
2743 vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2744 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2748 * Scan up to three times, relaxing the restrictions ("options") on
2749 * the reclamation of reservations and superpages each time.
2751 for (options = VPSC_NORESERV;;) {
2753 * Find the highest runs that satisfy the given constraints
2754 * and restrictions, and record them in "m_runs".
2759 m_run = vm_phys_scan_contig(domain, npages, curr_low,
2760 high, alignment, boundary, options);
2763 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2764 m_runs[RUN_INDEX(count)] = m_run;
2769 * Reclaim the highest runs in LIFO (descending) order until
2770 * the number of reclaimed pages, "reclaimed", is at least
2771 * MIN_RECLAIM. Reset "reclaimed" each time because each
2772 * reclamation is idempotent, and runs will (likely) recur
2773 * from one scan to the next as restrictions are relaxed.
2776 for (i = 0; count > 0 && i < NRUNS; i++) {
2778 m_run = m_runs[RUN_INDEX(count)];
2779 error = vm_page_reclaim_run(req_class, domain, npages,
2782 reclaimed += npages;
2783 if (reclaimed >= MIN_RECLAIM)
2789 * Either relax the restrictions on the next scan or return if
2790 * the last scan had no restrictions.
2792 if (options == VPSC_NORESERV)
2793 options = VPSC_NOSUPER;
2794 else if (options == VPSC_NOSUPER)
2796 else if (options == VPSC_ANY)
2797 return (reclaimed != 0);
2802 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2803 u_long alignment, vm_paddr_t boundary)
2805 struct vm_domainset_iter di;
2809 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2811 ret = vm_page_reclaim_contig_domain(domain, req, npages, low,
2812 high, alignment, boundary);
2815 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2821 * Set the domain in the appropriate page level domainset.
2824 vm_domain_set(struct vm_domain *vmd)
2827 mtx_lock(&vm_domainset_lock);
2828 if (!vmd->vmd_minset && vm_paging_min(vmd)) {
2829 vmd->vmd_minset = 1;
2830 DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
2832 if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
2833 vmd->vmd_severeset = 1;
2834 DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
2836 mtx_unlock(&vm_domainset_lock);
2840 * Clear the domain from the appropriate page level domainset.
2843 vm_domain_clear(struct vm_domain *vmd)
2846 mtx_lock(&vm_domainset_lock);
2847 if (vmd->vmd_minset && !vm_paging_min(vmd)) {
2848 vmd->vmd_minset = 0;
2849 DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
2850 if (vm_min_waiters != 0) {
2852 wakeup(&vm_min_domains);
2855 if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
2856 vmd->vmd_severeset = 0;
2857 DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
2858 if (vm_severe_waiters != 0) {
2859 vm_severe_waiters = 0;
2860 wakeup(&vm_severe_domains);
2865 * If pageout daemon needs pages, then tell it that there are
2868 if (vmd->vmd_pageout_pages_needed &&
2869 vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
2870 wakeup(&vmd->vmd_pageout_pages_needed);
2871 vmd->vmd_pageout_pages_needed = 0;
2874 /* See comments in vm_wait_doms(). */
2875 if (vm_pageproc_waiters) {
2876 vm_pageproc_waiters = 0;
2877 wakeup(&vm_pageproc_waiters);
2879 mtx_unlock(&vm_domainset_lock);
2883 * Wait for free pages to exceed the min threshold globally.
2889 mtx_lock(&vm_domainset_lock);
2890 while (vm_page_count_min()) {
2892 msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
2894 mtx_unlock(&vm_domainset_lock);
2898 * Wait for free pages to exceed the severe threshold globally.
2901 vm_wait_severe(void)
2904 mtx_lock(&vm_domainset_lock);
2905 while (vm_page_count_severe()) {
2906 vm_severe_waiters++;
2907 msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
2910 mtx_unlock(&vm_domainset_lock);
2917 return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
2921 vm_wait_doms(const domainset_t *wdoms)
2925 * We use racey wakeup synchronization to avoid expensive global
2926 * locking for the pageproc when sleeping with a non-specific vm_wait.
2927 * To handle this, we only sleep for one tick in this instance. It
2928 * is expected that most allocations for the pageproc will come from
2929 * kmem or vm_page_grab* which will use the more specific and
2930 * race-free vm_wait_domain().
2932 if (curproc == pageproc) {
2933 mtx_lock(&vm_domainset_lock);
2934 vm_pageproc_waiters++;
2935 msleep(&vm_pageproc_waiters, &vm_domainset_lock, PVM | PDROP,
2939 * XXX Ideally we would wait only until the allocation could
2940 * be satisfied. This condition can cause new allocators to
2941 * consume all freed pages while old allocators wait.
2943 mtx_lock(&vm_domainset_lock);
2944 if (vm_page_count_min_set(wdoms)) {
2946 msleep(&vm_min_domains, &vm_domainset_lock,
2947 PVM | PDROP, "vmwait", 0);
2949 mtx_unlock(&vm_domainset_lock);
2956 * Sleep until free pages are available for allocation.
2957 * - Called in various places after failed memory allocations.
2960 vm_wait_domain(int domain)
2962 struct vm_domain *vmd;
2965 vmd = VM_DOMAIN(domain);
2966 vm_domain_free_assert_unlocked(vmd);
2968 if (curproc == pageproc) {
2969 mtx_lock(&vm_domainset_lock);
2970 if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
2971 vmd->vmd_pageout_pages_needed = 1;
2972 msleep(&vmd->vmd_pageout_pages_needed,
2973 &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
2975 mtx_unlock(&vm_domainset_lock);
2977 if (pageproc == NULL)
2978 panic("vm_wait in early boot");
2979 DOMAINSET_ZERO(&wdom);
2980 DOMAINSET_SET(vmd->vmd_domain, &wdom);
2981 vm_wait_doms(&wdom);
2988 * Sleep until free pages are available for allocation in the
2989 * affinity domains of the obj. If obj is NULL, the domain set
2990 * for the calling thread is used.
2991 * Called in various places after failed memory allocations.
2994 vm_wait(vm_object_t obj)
2996 struct domainset *d;
3001 * Carefully fetch pointers only once: the struct domainset
3002 * itself is ummutable but the pointer might change.
3005 d = obj->domain.dr_policy;
3007 d = curthread->td_domain.dr_policy;
3009 vm_wait_doms(&d->ds_mask);
3013 * vm_domain_alloc_fail:
3015 * Called when a page allocation function fails. Informs the
3016 * pagedaemon and performs the requested wait. Requires the
3017 * domain_free and object lock on entry. Returns with the
3018 * object lock held and free lock released. Returns an error when
3019 * retry is necessary.
3023 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3026 vm_domain_free_assert_unlocked(vmd);
3028 atomic_add_int(&vmd->vmd_pageout_deficit,
3029 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3030 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3032 VM_OBJECT_WUNLOCK(object);
3033 vm_wait_domain(vmd->vmd_domain);
3035 VM_OBJECT_WLOCK(object);
3036 if (req & VM_ALLOC_WAITOK)
3046 * Sleep until free pages are available for allocation.
3047 * - Called only in vm_fault so that processes page faulting
3048 * can be easily tracked.
3049 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3050 * processes will be able to grab memory first. Do not change
3051 * this balance without careful testing first.
3054 vm_waitpfault(struct domainset *dset)
3058 * XXX Ideally we would wait only until the allocation could
3059 * be satisfied. This condition can cause new allocators to
3060 * consume all freed pages while old allocators wait.
3062 mtx_lock(&vm_domainset_lock);
3063 if (vm_page_count_min_set(&dset->ds_mask)) {
3065 msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3068 mtx_unlock(&vm_domainset_lock);
3071 struct vm_pagequeue *
3072 vm_page_pagequeue(vm_page_t m)
3075 return (&vm_pagequeue_domain(m)->vmd_pagequeues[m->queue]);
3079 vm_page_pagequeue_lockptr(vm_page_t m)
3083 if ((queue = atomic_load_8(&m->queue)) == PQ_NONE)
3085 return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue].pq_mutex);
3089 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m)
3091 struct vm_domain *vmd;
3094 CRITICAL_ASSERT(curthread);
3095 vm_pagequeue_assert_locked(pq);
3098 * The page daemon is allowed to set m->queue = PQ_NONE without
3099 * the page queue lock held. In this case it is about to free the page,
3100 * which must not have any queue state.
3102 qflags = atomic_load_8(&m->aflags) & PGA_QUEUE_STATE_MASK;
3103 KASSERT(pq == vm_page_pagequeue(m) || qflags == 0,
3104 ("page %p doesn't belong to queue %p but has queue state %#x",
3107 if ((qflags & PGA_DEQUEUE) != 0) {
3108 if (__predict_true((qflags & PGA_ENQUEUED) != 0)) {
3109 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3110 vm_pagequeue_cnt_dec(pq);
3112 vm_page_dequeue_complete(m);
3113 } else if ((qflags & (PGA_REQUEUE | PGA_REQUEUE_HEAD)) != 0) {
3114 if ((qflags & PGA_ENQUEUED) != 0)
3115 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3117 vm_pagequeue_cnt_inc(pq);
3118 vm_page_aflag_set(m, PGA_ENQUEUED);
3120 if ((qflags & PGA_REQUEUE_HEAD) != 0) {
3121 KASSERT(m->queue == PQ_INACTIVE,
3122 ("head enqueue not supported for page %p", m));
3123 vmd = vm_pagequeue_domain(m);
3124 TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3126 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3129 * PGA_REQUEUE and PGA_REQUEUE_HEAD must be cleared after
3130 * setting PGA_ENQUEUED in order to synchronize with the
3133 vm_page_aflag_clear(m, PGA_REQUEUE | PGA_REQUEUE_HEAD);
3138 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3144 for (i = 0; i < bq->bq_cnt; i++) {
3146 if (__predict_false(m->queue != queue))
3148 vm_pqbatch_process_page(pq, m);
3150 vm_batchqueue_init(bq);
3154 vm_pqbatch_submit_page(vm_page_t m, uint8_t queue)
3156 struct vm_batchqueue *bq;
3157 struct vm_pagequeue *pq;
3160 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3161 ("page %p is unmanaged", m));
3162 KASSERT(mtx_owned(vm_page_lockptr(m)) ||
3163 (m->object == NULL && (m->aflags & PGA_DEQUEUE) != 0),
3164 ("missing synchronization for page %p", m));
3165 KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3167 domain = vm_phys_domain(m);
3168 pq = &vm_pagequeue_domain(m)->vmd_pagequeues[queue];
3171 bq = DPCPU_PTR(pqbatch[domain][queue]);
3172 if (vm_batchqueue_insert(bq, m)) {
3176 if (!vm_pagequeue_trylock(pq)) {
3178 vm_pagequeue_lock(pq);
3180 bq = DPCPU_PTR(pqbatch[domain][queue]);
3182 vm_pqbatch_process(pq, bq, queue);
3185 * The page may have been logically dequeued before we acquired the
3186 * page queue lock. In this case, since we either hold the page lock
3187 * or the page is being freed, a different thread cannot be concurrently
3188 * enqueuing the page.
3190 if (__predict_true(m->queue == queue))
3191 vm_pqbatch_process_page(pq, m);
3193 KASSERT(m->queue == PQ_NONE,
3194 ("invalid queue transition for page %p", m));
3195 KASSERT((m->aflags & PGA_ENQUEUED) == 0,
3196 ("page %p is enqueued with invalid queue index", m));
3197 vm_page_aflag_clear(m, PGA_QUEUE_STATE_MASK);
3199 vm_pagequeue_unlock(pq);
3204 * vm_page_drain_pqbatch: [ internal use only ]
3206 * Force all per-CPU page queue batch queues to be drained. This is
3207 * intended for use in severe memory shortages, to ensure that pages
3208 * do not remain stuck in the batch queues.
3211 vm_page_drain_pqbatch(void)
3214 struct vm_domain *vmd;
3215 struct vm_pagequeue *pq;
3216 int cpu, domain, queue;
3221 sched_bind(td, cpu);
3224 for (domain = 0; domain < vm_ndomains; domain++) {
3225 vmd = VM_DOMAIN(domain);
3226 for (queue = 0; queue < PQ_COUNT; queue++) {
3227 pq = &vmd->vmd_pagequeues[queue];
3228 vm_pagequeue_lock(pq);
3230 vm_pqbatch_process(pq,
3231 DPCPU_PTR(pqbatch[domain][queue]), queue);
3233 vm_pagequeue_unlock(pq);
3243 * Complete the logical removal of a page from a page queue. We must be
3244 * careful to synchronize with the page daemon, which may be concurrently
3245 * examining the page with only the page lock held. The page must not be
3246 * in a state where it appears to be logically enqueued.
3249 vm_page_dequeue_complete(vm_page_t m)
3253 atomic_thread_fence_rel();
3254 vm_page_aflag_clear(m, PGA_QUEUE_STATE_MASK);
3258 * vm_page_dequeue_deferred: [ internal use only ]
3260 * Request removal of the given page from its current page
3261 * queue. Physical removal from the queue may be deferred
3264 * The page must be locked.
3267 vm_page_dequeue_deferred(vm_page_t m)
3271 vm_page_assert_locked(m);
3273 if ((queue = vm_page_queue(m)) == PQ_NONE)
3275 vm_page_aflag_set(m, PGA_DEQUEUE);
3276 vm_pqbatch_submit_page(m, queue);
3280 * A variant of vm_page_dequeue_deferred() that does not assert the page
3281 * lock and is only to be called from vm_page_free_prep(). It is just an
3282 * open-coded implementation of vm_page_dequeue_deferred(). Because the
3283 * page is being freed, we can assume that nothing else is scheduling queue
3284 * operations on this page, so we get for free the mutual exclusion that
3285 * is otherwise provided by the page lock.
3288 vm_page_dequeue_deferred_free(vm_page_t m)
3292 KASSERT(m->object == NULL, ("page %p has an object reference", m));
3294 if ((m->aflags & PGA_DEQUEUE) != 0)
3296 atomic_thread_fence_acq();
3297 if ((queue = m->queue) == PQ_NONE)
3299 vm_page_aflag_set(m, PGA_DEQUEUE);
3300 vm_pqbatch_submit_page(m, queue);
3306 * Remove the page from whichever page queue it's in, if any.
3307 * The page must either be locked or unallocated. This constraint
3308 * ensures that the queue state of the page will remain consistent
3309 * after this function returns.
3312 vm_page_dequeue(vm_page_t m)
3314 struct mtx *lock, *lock1;
3315 struct vm_pagequeue *pq;
3318 KASSERT(mtx_owned(vm_page_lockptr(m)) || m->order == VM_NFREEORDER,
3319 ("page %p is allocated and unlocked", m));
3322 lock = vm_page_pagequeue_lockptr(m);
3325 * A thread may be concurrently executing
3326 * vm_page_dequeue_complete(). Ensure that all queue
3327 * state is cleared before we return.
3329 aflags = atomic_load_8(&m->aflags);
3330 if ((aflags & PGA_QUEUE_STATE_MASK) == 0)
3332 KASSERT((aflags & PGA_DEQUEUE) != 0,
3333 ("page %p has unexpected queue state flags %#x",
3337 * Busy wait until the thread updating queue state is
3338 * finished. Such a thread must be executing in a
3345 if ((lock1 = vm_page_pagequeue_lockptr(m)) == lock)
3350 KASSERT(lock == vm_page_pagequeue_lockptr(m),
3351 ("%s: page %p migrated directly between queues", __func__, m));
3352 KASSERT((m->aflags & PGA_DEQUEUE) != 0 ||
3353 mtx_owned(vm_page_lockptr(m)),
3354 ("%s: queued unlocked page %p", __func__, m));
3356 if ((m->aflags & PGA_ENQUEUED) != 0) {
3357 pq = vm_page_pagequeue(m);
3358 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3359 vm_pagequeue_cnt_dec(pq);
3361 vm_page_dequeue_complete(m);
3366 * Schedule the given page for insertion into the specified page queue.
3367 * Physical insertion of the page may be deferred indefinitely.
3370 vm_page_enqueue(vm_page_t m, uint8_t queue)
3373 vm_page_assert_locked(m);
3374 KASSERT(m->queue == PQ_NONE && (m->aflags & PGA_QUEUE_STATE_MASK) == 0,
3375 ("%s: page %p is already enqueued", __func__, m));
3378 if ((m->aflags & PGA_REQUEUE) == 0)
3379 vm_page_aflag_set(m, PGA_REQUEUE);
3380 vm_pqbatch_submit_page(m, queue);
3384 * vm_page_requeue: [ internal use only ]
3386 * Schedule a requeue of the given page.
3388 * The page must be locked.
3391 vm_page_requeue(vm_page_t m)
3394 vm_page_assert_locked(m);
3395 KASSERT(vm_page_queue(m) != PQ_NONE,
3396 ("%s: page %p is not logically enqueued", __func__, m));
3398 if ((m->aflags & PGA_REQUEUE) == 0)
3399 vm_page_aflag_set(m, PGA_REQUEUE);
3400 vm_pqbatch_submit_page(m, atomic_load_8(&m->queue));
3406 * Put the specified page on the active list (if appropriate).
3407 * Ensure that act_count is at least ACT_INIT but do not otherwise
3410 * The page must be locked.
3413 vm_page_activate(vm_page_t m)
3416 vm_page_assert_locked(m);
3418 if (vm_page_wired(m) || (m->oflags & VPO_UNMANAGED) != 0)
3420 if (vm_page_queue(m) == PQ_ACTIVE) {
3421 if (m->act_count < ACT_INIT)
3422 m->act_count = ACT_INIT;
3427 if (m->act_count < ACT_INIT)
3428 m->act_count = ACT_INIT;
3429 vm_page_enqueue(m, PQ_ACTIVE);
3433 * vm_page_free_prep:
3435 * Prepares the given page to be put on the free list,
3436 * disassociating it from any VM object. The caller may return
3437 * the page to the free list only if this function returns true.
3439 * The object must be locked. The page must be locked if it is
3443 vm_page_free_prep(vm_page_t m)
3446 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
3447 if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
3450 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3451 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
3452 KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
3453 m, i, (uintmax_t)*p));
3456 if ((m->oflags & VPO_UNMANAGED) == 0) {
3457 vm_page_lock_assert(m, MA_OWNED);
3458 KASSERT(!pmap_page_is_mapped(m),
3459 ("vm_page_free_prep: freeing mapped page %p", m));
3461 KASSERT(m->queue == PQ_NONE,
3462 ("vm_page_free_prep: unmanaged page %p is queued", m));
3463 VM_CNT_INC(v_tfree);
3465 if (vm_page_sbusied(m))
3466 panic("vm_page_free_prep: freeing busy page %p", m);
3471 * If fictitious remove object association and
3474 if ((m->flags & PG_FICTITIOUS) != 0) {
3475 KASSERT(m->wire_count == 1,
3476 ("fictitious page %p is not wired", m));
3477 KASSERT(m->queue == PQ_NONE,
3478 ("fictitious page %p is queued", m));
3483 * Pages need not be dequeued before they are returned to the physical
3484 * memory allocator, but they must at least be marked for a deferred
3487 if ((m->oflags & VPO_UNMANAGED) == 0)
3488 vm_page_dequeue_deferred_free(m);
3493 if (vm_page_wired(m) != 0)
3494 panic("vm_page_free_prep: freeing wired page %p", m);
3495 if (m->hold_count != 0) {
3496 m->flags &= ~PG_ZERO;
3497 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
3498 ("vm_page_free_prep: freeing PG_UNHOLDFREE page %p", m));
3499 m->flags |= PG_UNHOLDFREE;
3504 * Restore the default memory attribute to the page.
3506 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3507 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3509 #if VM_NRESERVLEVEL > 0
3510 if (vm_reserv_free_page(m))
3520 * Returns the given page to the free list, disassociating it
3521 * from any VM object.
3523 * The object must be locked. The page must be locked if it is
3527 vm_page_free_toq(vm_page_t m)
3529 struct vm_domain *vmd;
3531 if (!vm_page_free_prep(m))
3534 vmd = vm_pagequeue_domain(m);
3535 if (m->pool == VM_FREEPOOL_DEFAULT && vmd->vmd_pgcache != NULL) {
3536 uma_zfree(vmd->vmd_pgcache, m);
3539 vm_domain_free_lock(vmd);
3540 vm_phys_free_pages(m, 0);
3541 vm_domain_free_unlock(vmd);
3542 vm_domain_freecnt_inc(vmd, 1);
3546 * vm_page_free_pages_toq:
3548 * Returns a list of pages to the free list, disassociating it
3549 * from any VM object. In other words, this is equivalent to
3550 * calling vm_page_free_toq() for each page of a list of VM objects.
3552 * The objects must be locked. The pages must be locked if it is
3556 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
3561 if (SLIST_EMPTY(free))
3565 while ((m = SLIST_FIRST(free)) != NULL) {
3567 SLIST_REMOVE_HEAD(free, plinks.s.ss);
3568 vm_page_free_toq(m);
3571 if (update_wire_count)
3578 * Mark this page as wired down. If the page is fictitious, then
3579 * its wire count must remain one.
3581 * The page must be locked.
3584 vm_page_wire(vm_page_t m)
3587 vm_page_assert_locked(m);
3588 if ((m->flags & PG_FICTITIOUS) != 0) {
3589 KASSERT(m->wire_count == 1,
3590 ("vm_page_wire: fictitious page %p's wire count isn't one",
3594 if (!vm_page_wired(m)) {
3595 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
3596 m->queue == PQ_NONE,
3597 ("vm_page_wire: unmanaged page %p is queued", m));
3601 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
3607 * Release one wiring of the specified page, potentially allowing it to be
3608 * paged out. Returns TRUE if the number of wirings transitions to zero and
3611 * Only managed pages belonging to an object can be paged out. If the number
3612 * of wirings transitions to zero and the page is eligible for page out, then
3613 * the page is added to the specified paging queue (unless PQ_NONE is
3614 * specified, in which case the page is dequeued if it belongs to a paging
3617 * If a page is fictitious, then its wire count must always be one.
3619 * A managed page must be locked.
3622 vm_page_unwire(vm_page_t m, uint8_t queue)
3626 KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
3627 ("vm_page_unwire: invalid queue %u request for page %p",
3629 if ((m->oflags & VPO_UNMANAGED) == 0)
3630 vm_page_assert_locked(m);
3632 unwired = vm_page_unwire_noq(m);
3633 if (!unwired || (m->oflags & VPO_UNMANAGED) != 0 || m->object == NULL)
3636 if (vm_page_queue(m) == queue) {
3637 if (queue == PQ_ACTIVE)
3638 vm_page_reference(m);
3639 else if (queue != PQ_NONE)
3643 if (queue != PQ_NONE) {
3644 vm_page_enqueue(m, queue);
3645 if (queue == PQ_ACTIVE)
3646 /* Initialize act_count. */
3647 vm_page_activate(m);
3655 * vm_page_unwire_noq:
3657 * Unwire a page without (re-)inserting it into a page queue. It is up
3658 * to the caller to enqueue, requeue, or free the page as appropriate.
3659 * In most cases, vm_page_unwire() should be used instead.
3662 vm_page_unwire_noq(vm_page_t m)
3665 if ((m->oflags & VPO_UNMANAGED) == 0)
3666 vm_page_assert_locked(m);
3667 if ((m->flags & PG_FICTITIOUS) != 0) {
3668 KASSERT(m->wire_count == 1,
3669 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
3672 if (!vm_page_wired(m))
3673 panic("vm_page_unwire: page %p's wire count is zero", m);
3675 if (m->wire_count == 0) {
3683 * Move the specified page to the tail of the inactive queue, or requeue
3684 * the page if it is already in the inactive queue.
3686 * The page must be locked.
3689 vm_page_deactivate(vm_page_t m)
3692 vm_page_assert_locked(m);
3694 if (vm_page_wired(m) || (m->oflags & VPO_UNMANAGED) != 0)
3697 if (!vm_page_inactive(m)) {
3699 vm_page_enqueue(m, PQ_INACTIVE);
3705 * Move the specified page close to the head of the inactive queue,
3706 * bypassing LRU. A marker page is used to maintain FIFO ordering.
3707 * As with regular enqueues, we use a per-CPU batch queue to reduce
3708 * contention on the page queue lock.
3710 * The page must be locked.
3713 vm_page_deactivate_noreuse(vm_page_t m)
3716 vm_page_assert_locked(m);
3718 if (vm_page_wired(m) || (m->oflags & VPO_UNMANAGED) != 0)
3721 if (!vm_page_inactive(m)) {
3723 m->queue = PQ_INACTIVE;
3725 if ((m->aflags & PGA_REQUEUE_HEAD) == 0)
3726 vm_page_aflag_set(m, PGA_REQUEUE_HEAD);
3727 vm_pqbatch_submit_page(m, PQ_INACTIVE);
3733 * Put a page in the laundry, or requeue it if it is already there.
3736 vm_page_launder(vm_page_t m)
3739 vm_page_assert_locked(m);
3740 if (vm_page_wired(m) || (m->oflags & VPO_UNMANAGED) != 0)
3743 if (vm_page_in_laundry(m))
3747 vm_page_enqueue(m, PQ_LAUNDRY);
3752 * vm_page_unswappable
3754 * Put a page in the PQ_UNSWAPPABLE holding queue.
3757 vm_page_unswappable(vm_page_t m)
3760 vm_page_assert_locked(m);
3761 KASSERT(!vm_page_wired(m) && (m->oflags & VPO_UNMANAGED) == 0,
3762 ("page %p already unswappable", m));
3765 vm_page_enqueue(m, PQ_UNSWAPPABLE);
3769 * Attempt to free the page. If it cannot be freed, do nothing. Returns true
3770 * if the page is freed and false otherwise.
3772 * The page must be managed. The page and its containing object must be
3776 vm_page_try_to_free(vm_page_t m)
3779 vm_page_assert_locked(m);
3780 VM_OBJECT_ASSERT_WLOCKED(m->object);
3781 KASSERT((m->oflags & VPO_UNMANAGED) == 0, ("page %p is unmanaged", m));
3782 if (m->dirty != 0 || vm_page_held(m) || vm_page_busied(m))
3784 if (m->object->ref_count != 0) {
3796 * Apply the specified advice to the given page.
3798 * The object and page must be locked.
3801 vm_page_advise(vm_page_t m, int advice)
3804 vm_page_assert_locked(m);
3805 VM_OBJECT_ASSERT_WLOCKED(m->object);
3806 if (advice == MADV_FREE)
3808 * Mark the page clean. This will allow the page to be freed
3809 * without first paging it out. MADV_FREE pages are often
3810 * quickly reused by malloc(3), so we do not do anything that
3811 * would result in a page fault on a later access.
3814 else if (advice != MADV_DONTNEED) {
3815 if (advice == MADV_WILLNEED)
3816 vm_page_activate(m);
3821 * Clear any references to the page. Otherwise, the page daemon will
3822 * immediately reactivate the page.
3824 vm_page_aflag_clear(m, PGA_REFERENCED);
3826 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3830 * Place clean pages near the head of the inactive queue rather than
3831 * the tail, thus defeating the queue's LRU operation and ensuring that
3832 * the page will be reused quickly. Dirty pages not already in the
3833 * laundry are moved there.
3836 vm_page_deactivate_noreuse(m);
3837 else if (!vm_page_in_laundry(m))
3842 * Grab a page, waiting until we are waken up due to the page
3843 * changing state. We keep on waiting, if the page continues
3844 * to be in the object. If the page doesn't exist, first allocate it
3845 * and then conditionally zero it.
3847 * This routine may sleep.
3849 * The object must be locked on entry. The lock will, however, be released
3850 * and reacquired if the routine sleeps.
3853 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3859 VM_OBJECT_ASSERT_WLOCKED(object);
3860 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3861 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3862 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3863 pflags = allocflags &
3864 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
3865 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3866 pflags |= VM_ALLOC_WAITFAIL;
3868 if ((m = vm_page_lookup(object, pindex)) != NULL) {
3869 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3870 vm_page_xbusied(m) : vm_page_busied(m);
3872 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3875 * Reference the page before unlocking and
3876 * sleeping so that the page daemon is less
3877 * likely to reclaim it.
3879 vm_page_aflag_set(m, PGA_REFERENCED);
3881 VM_OBJECT_WUNLOCK(object);
3882 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
3883 VM_ALLOC_IGN_SBUSY) != 0);
3884 VM_OBJECT_WLOCK(object);
3887 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3893 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3895 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3900 m = vm_page_alloc(object, pindex, pflags);
3902 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3906 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3912 * Return the specified range of pages from the given object. For each
3913 * page offset within the range, if a page already exists within the object
3914 * at that offset and it is busy, then wait for it to change state. If,
3915 * instead, the page doesn't exist, then allocate it.
3917 * The caller must always specify an allocation class.
3919 * allocation classes:
3920 * VM_ALLOC_NORMAL normal process request
3921 * VM_ALLOC_SYSTEM system *really* needs the pages
3923 * The caller must always specify that the pages are to be busied and/or
3926 * optional allocation flags:
3927 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
3928 * VM_ALLOC_NOBUSY do not exclusive busy the page
3929 * VM_ALLOC_NOWAIT do not sleep
3930 * VM_ALLOC_SBUSY set page to sbusy state
3931 * VM_ALLOC_WIRED wire the pages
3932 * VM_ALLOC_ZERO zero and validate any invalid pages
3934 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
3935 * may return a partial prefix of the requested range.
3938 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
3939 vm_page_t *ma, int count)
3946 VM_OBJECT_ASSERT_WLOCKED(object);
3947 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
3948 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
3949 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
3950 (allocflags & VM_ALLOC_WIRED) != 0,
3951 ("vm_page_grab_pages: the pages must be busied or wired"));
3952 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3953 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3954 ("vm_page_grab_pages: VM_ALLOC_SBUSY/IGN_SBUSY mismatch"));
3957 pflags = allocflags & ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK |
3958 VM_ALLOC_WAITFAIL | VM_ALLOC_IGN_SBUSY);
3959 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3960 pflags |= VM_ALLOC_WAITFAIL;
3963 m = vm_radix_lookup_le(&object->rtree, pindex + i);
3964 if (m == NULL || m->pindex != pindex + i) {
3968 mpred = TAILQ_PREV(m, pglist, listq);
3969 for (; i < count; i++) {
3971 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3972 vm_page_xbusied(m) : vm_page_busied(m);
3974 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3977 * Reference the page before unlocking and
3978 * sleeping so that the page daemon is less
3979 * likely to reclaim it.
3981 vm_page_aflag_set(m, PGA_REFERENCED);
3983 VM_OBJECT_WUNLOCK(object);
3984 vm_page_busy_sleep(m, "grbmaw", (allocflags &
3985 VM_ALLOC_IGN_SBUSY) != 0);
3986 VM_OBJECT_WLOCK(object);
3989 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3994 if ((allocflags & (VM_ALLOC_NOBUSY |
3995 VM_ALLOC_SBUSY)) == 0)
3997 if ((allocflags & VM_ALLOC_SBUSY) != 0)
4000 m = vm_page_alloc_after(object, pindex + i,
4001 pflags | VM_ALLOC_COUNT(count - i), mpred);
4003 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4008 if (m->valid == 0 && (allocflags & VM_ALLOC_ZERO) != 0) {
4009 if ((m->flags & PG_ZERO) == 0)
4011 m->valid = VM_PAGE_BITS_ALL;
4014 m = vm_page_next(m);
4020 * Mapping function for valid or dirty bits in a page.
4022 * Inputs are required to range within a page.
4025 vm_page_bits(int base, int size)
4031 base + size <= PAGE_SIZE,
4032 ("vm_page_bits: illegal base/size %d/%d", base, size)
4035 if (size == 0) /* handle degenerate case */
4038 first_bit = base >> DEV_BSHIFT;
4039 last_bit = (base + size - 1) >> DEV_BSHIFT;
4041 return (((vm_page_bits_t)2 << last_bit) -
4042 ((vm_page_bits_t)1 << first_bit));
4046 * vm_page_set_valid_range:
4048 * Sets portions of a page valid. The arguments are expected
4049 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4050 * of any partial chunks touched by the range. The invalid portion of
4051 * such chunks will be zeroed.
4053 * (base + size) must be less then or equal to PAGE_SIZE.
4056 vm_page_set_valid_range(vm_page_t m, int base, int size)
4060 VM_OBJECT_ASSERT_WLOCKED(m->object);
4061 if (size == 0) /* handle degenerate case */
4065 * If the base is not DEV_BSIZE aligned and the valid
4066 * bit is clear, we have to zero out a portion of the
4069 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4070 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
4071 pmap_zero_page_area(m, frag, base - frag);
4074 * If the ending offset is not DEV_BSIZE aligned and the
4075 * valid bit is clear, we have to zero out a portion of
4078 endoff = base + size;
4079 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4080 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
4081 pmap_zero_page_area(m, endoff,
4082 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4085 * Assert that no previously invalid block that is now being validated
4088 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
4089 ("vm_page_set_valid_range: page %p is dirty", m));
4092 * Set valid bits inclusive of any overlap.
4094 m->valid |= vm_page_bits(base, size);
4098 * Clear the given bits from the specified page's dirty field.
4100 static __inline void
4101 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
4104 #if PAGE_SIZE < 16384
4109 * If the object is locked and the page is neither exclusive busy nor
4110 * write mapped, then the page's dirty field cannot possibly be
4111 * set by a concurrent pmap operation.
4113 VM_OBJECT_ASSERT_WLOCKED(m->object);
4114 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
4115 m->dirty &= ~pagebits;
4118 * The pmap layer can call vm_page_dirty() without
4119 * holding a distinguished lock. The combination of
4120 * the object's lock and an atomic operation suffice
4121 * to guarantee consistency of the page dirty field.
4123 * For PAGE_SIZE == 32768 case, compiler already
4124 * properly aligns the dirty field, so no forcible
4125 * alignment is needed. Only require existence of
4126 * atomic_clear_64 when page size is 32768.
4128 addr = (uintptr_t)&m->dirty;
4129 #if PAGE_SIZE == 32768
4130 atomic_clear_64((uint64_t *)addr, pagebits);
4131 #elif PAGE_SIZE == 16384
4132 atomic_clear_32((uint32_t *)addr, pagebits);
4133 #else /* PAGE_SIZE <= 8192 */
4135 * Use a trick to perform a 32-bit atomic on the
4136 * containing aligned word, to not depend on the existence
4137 * of atomic_clear_{8, 16}.
4139 shift = addr & (sizeof(uint32_t) - 1);
4140 #if BYTE_ORDER == BIG_ENDIAN
4141 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
4145 addr &= ~(sizeof(uint32_t) - 1);
4146 atomic_clear_32((uint32_t *)addr, pagebits << shift);
4147 #endif /* PAGE_SIZE */
4152 * vm_page_set_validclean:
4154 * Sets portions of a page valid and clean. The arguments are expected
4155 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4156 * of any partial chunks touched by the range. The invalid portion of
4157 * such chunks will be zero'd.
4159 * (base + size) must be less then or equal to PAGE_SIZE.
4162 vm_page_set_validclean(vm_page_t m, int base, int size)
4164 vm_page_bits_t oldvalid, pagebits;
4167 VM_OBJECT_ASSERT_WLOCKED(m->object);
4168 if (size == 0) /* handle degenerate case */
4172 * If the base is not DEV_BSIZE aligned and the valid
4173 * bit is clear, we have to zero out a portion of the
4176 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4177 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
4178 pmap_zero_page_area(m, frag, base - frag);
4181 * If the ending offset is not DEV_BSIZE aligned and the
4182 * valid bit is clear, we have to zero out a portion of
4185 endoff = base + size;
4186 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4187 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
4188 pmap_zero_page_area(m, endoff,
4189 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4192 * Set valid, clear dirty bits. If validating the entire
4193 * page we can safely clear the pmap modify bit. We also
4194 * use this opportunity to clear the VPO_NOSYNC flag. If a process
4195 * takes a write fault on a MAP_NOSYNC memory area the flag will
4198 * We set valid bits inclusive of any overlap, but we can only
4199 * clear dirty bits for DEV_BSIZE chunks that are fully within
4202 oldvalid = m->valid;
4203 pagebits = vm_page_bits(base, size);
4204 m->valid |= pagebits;
4206 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
4207 frag = DEV_BSIZE - frag;
4213 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
4215 if (base == 0 && size == PAGE_SIZE) {
4217 * The page can only be modified within the pmap if it is
4218 * mapped, and it can only be mapped if it was previously
4221 if (oldvalid == VM_PAGE_BITS_ALL)
4223 * Perform the pmap_clear_modify() first. Otherwise,
4224 * a concurrent pmap operation, such as
4225 * pmap_protect(), could clear a modification in the
4226 * pmap and set the dirty field on the page before
4227 * pmap_clear_modify() had begun and after the dirty
4228 * field was cleared here.
4230 pmap_clear_modify(m);
4232 m->oflags &= ~VPO_NOSYNC;
4233 } else if (oldvalid != VM_PAGE_BITS_ALL)
4234 m->dirty &= ~pagebits;
4236 vm_page_clear_dirty_mask(m, pagebits);
4240 vm_page_clear_dirty(vm_page_t m, int base, int size)
4243 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
4247 * vm_page_set_invalid:
4249 * Invalidates DEV_BSIZE'd chunks within a page. Both the
4250 * valid and dirty bits for the effected areas are cleared.
4253 vm_page_set_invalid(vm_page_t m, int base, int size)
4255 vm_page_bits_t bits;
4259 VM_OBJECT_ASSERT_WLOCKED(object);
4260 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
4261 size >= object->un_pager.vnp.vnp_size)
4262 bits = VM_PAGE_BITS_ALL;
4264 bits = vm_page_bits(base, size);
4265 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
4268 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
4269 !pmap_page_is_mapped(m),
4270 ("vm_page_set_invalid: page %p is mapped", m));
4276 * vm_page_zero_invalid()
4278 * The kernel assumes that the invalid portions of a page contain
4279 * garbage, but such pages can be mapped into memory by user code.
4280 * When this occurs, we must zero out the non-valid portions of the
4281 * page so user code sees what it expects.
4283 * Pages are most often semi-valid when the end of a file is mapped
4284 * into memory and the file's size is not page aligned.
4287 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
4292 VM_OBJECT_ASSERT_WLOCKED(m->object);
4294 * Scan the valid bits looking for invalid sections that
4295 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
4296 * valid bit may be set ) have already been zeroed by
4297 * vm_page_set_validclean().
4299 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
4300 if (i == (PAGE_SIZE / DEV_BSIZE) ||
4301 (m->valid & ((vm_page_bits_t)1 << i))) {
4303 pmap_zero_page_area(m,
4304 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
4311 * setvalid is TRUE when we can safely set the zero'd areas
4312 * as being valid. We can do this if there are no cache consistancy
4313 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
4316 m->valid = VM_PAGE_BITS_ALL;
4322 * Is (partial) page valid? Note that the case where size == 0
4323 * will return FALSE in the degenerate case where the page is
4324 * entirely invalid, and TRUE otherwise.
4327 vm_page_is_valid(vm_page_t m, int base, int size)
4329 vm_page_bits_t bits;
4331 VM_OBJECT_ASSERT_LOCKED(m->object);
4332 bits = vm_page_bits(base, size);
4333 return (m->valid != 0 && (m->valid & bits) == bits);
4337 * Returns true if all of the specified predicates are true for the entire
4338 * (super)page and false otherwise.
4341 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
4347 if (skip_m != NULL && skip_m->object != object)
4349 VM_OBJECT_ASSERT_LOCKED(object);
4350 npages = atop(pagesizes[m->psind]);
4353 * The physically contiguous pages that make up a superpage, i.e., a
4354 * page with a page size index ("psind") greater than zero, will
4355 * occupy adjacent entries in vm_page_array[].
4357 for (i = 0; i < npages; i++) {
4358 /* Always test object consistency, including "skip_m". */
4359 if (m[i].object != object)
4361 if (&m[i] == skip_m)
4363 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
4365 if ((flags & PS_ALL_DIRTY) != 0) {
4367 * Calling vm_page_test_dirty() or pmap_is_modified()
4368 * might stop this case from spuriously returning
4369 * "false". However, that would require a write lock
4370 * on the object containing "m[i]".
4372 if (m[i].dirty != VM_PAGE_BITS_ALL)
4375 if ((flags & PS_ALL_VALID) != 0 &&
4376 m[i].valid != VM_PAGE_BITS_ALL)
4383 * Set the page's dirty bits if the page is modified.
4386 vm_page_test_dirty(vm_page_t m)
4389 VM_OBJECT_ASSERT_WLOCKED(m->object);
4390 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
4395 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
4398 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
4402 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
4405 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
4409 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
4412 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
4415 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
4417 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
4420 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
4424 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
4427 mtx_assert_(vm_page_lockptr(m), a, file, line);
4433 vm_page_object_lock_assert(vm_page_t m)
4437 * Certain of the page's fields may only be modified by the
4438 * holder of the containing object's lock or the exclusive busy.
4439 * holder. Unfortunately, the holder of the write busy is
4440 * not recorded, and thus cannot be checked here.
4442 if (m->object != NULL && !vm_page_xbusied(m))
4443 VM_OBJECT_ASSERT_WLOCKED(m->object);
4447 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
4450 if ((bits & PGA_WRITEABLE) == 0)
4454 * The PGA_WRITEABLE flag can only be set if the page is
4455 * managed, is exclusively busied or the object is locked.
4456 * Currently, this flag is only set by pmap_enter().
4458 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4459 ("PGA_WRITEABLE on unmanaged page"));
4460 if (!vm_page_xbusied(m))
4461 VM_OBJECT_ASSERT_LOCKED(m->object);
4465 #include "opt_ddb.h"
4467 #include <sys/kernel.h>
4469 #include <ddb/ddb.h>
4471 DB_SHOW_COMMAND(page, vm_page_print_page_info)
4474 db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
4475 db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
4476 db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
4477 db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
4478 db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
4479 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
4480 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
4481 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
4482 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
4485 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
4489 db_printf("pq_free %d\n", vm_free_count());
4490 for (dom = 0; dom < vm_ndomains; dom++) {
4492 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
4494 vm_dom[dom].vmd_page_count,
4495 vm_dom[dom].vmd_free_count,
4496 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
4497 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
4498 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
4499 vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
4503 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
4506 boolean_t phys, virt;
4509 db_printf("show pginfo addr\n");
4513 phys = strchr(modif, 'p') != NULL;
4514 virt = strchr(modif, 'v') != NULL;
4516 m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
4518 m = PHYS_TO_VM_PAGE(addr);
4520 m = (vm_page_t)addr;
4522 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
4523 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
4524 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
4525 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
4526 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);