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 * GENERAL RULES ON VM_PAGE MANIPULATION
68 * - A page queue lock is required when adding or removing a page from a
69 * page queue regardless of other locks or the busy state of a page.
71 * * In general, no thread besides the page daemon can acquire or
72 * hold more than one page queue lock at a time.
74 * * The page daemon can acquire and hold any pair of page queue
77 * - The object lock is required when inserting or removing
78 * pages from an object (vm_page_insert() or vm_page_remove()).
83 * Resident memory management module.
86 #include <sys/cdefs.h>
87 __FBSDID("$FreeBSD$");
91 #include <sys/param.h>
92 #include <sys/systm.h>
94 #include <sys/domainset.h>
95 #include <sys/kernel.h>
96 #include <sys/limits.h>
97 #include <sys/linker.h>
98 #include <sys/malloc.h>
100 #include <sys/msgbuf.h>
101 #include <sys/mutex.h>
102 #include <sys/proc.h>
103 #include <sys/rwlock.h>
104 #include <sys/sbuf.h>
105 #include <sys/sched.h>
107 #include <sys/sysctl.h>
108 #include <sys/vmmeter.h>
109 #include <sys/vnode.h>
113 #include <vm/vm_param.h>
114 #include <vm/vm_domainset.h>
115 #include <vm/vm_kern.h>
116 #include <vm/vm_map.h>
117 #include <vm/vm_object.h>
118 #include <vm/vm_page.h>
119 #include <vm/vm_pageout.h>
120 #include <vm/vm_phys.h>
121 #include <vm/vm_pagequeue.h>
122 #include <vm/vm_pager.h>
123 #include <vm/vm_radix.h>
124 #include <vm/vm_reserv.h>
125 #include <vm/vm_extern.h>
127 #include <vm/uma_int.h>
129 #include <machine/md_var.h>
131 extern int uma_startup_count(int);
132 extern void uma_startup(void *, int);
133 extern int vmem_startup_count(void);
135 struct vm_domain vm_dom[MAXMEMDOM];
137 DPCPU_DEFINE_STATIC(struct vm_batchqueue, pqbatch[MAXMEMDOM][PQ_COUNT]);
139 struct mtx_padalign __exclusive_cache_line pa_lock[PA_LOCK_COUNT];
141 struct mtx_padalign __exclusive_cache_line vm_domainset_lock;
142 /* The following fields are protected by the domainset lock. */
143 domainset_t __exclusive_cache_line vm_min_domains;
144 domainset_t __exclusive_cache_line vm_severe_domains;
145 static int vm_min_waiters;
146 static int vm_severe_waiters;
147 static int vm_pageproc_waiters;
150 * bogus page -- for I/O to/from partially complete buffers,
151 * or for paging into sparsely invalid regions.
153 vm_page_t bogus_page;
155 vm_page_t vm_page_array;
156 long vm_page_array_size;
159 static int boot_pages;
160 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
162 "number of pages allocated for bootstrapping the VM system");
164 static int pa_tryrelock_restart;
165 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
166 &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
168 static TAILQ_HEAD(, vm_page) blacklist_head;
169 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
170 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
171 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
173 static uma_zone_t fakepg_zone;
175 static void vm_page_alloc_check(vm_page_t m);
176 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
177 static void vm_page_dequeue_complete(vm_page_t m);
178 static void vm_page_enqueue(vm_page_t m, uint8_t queue);
179 static void vm_page_init(void *dummy);
180 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
181 vm_pindex_t pindex, vm_page_t mpred);
182 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
184 static int vm_page_reclaim_run(int req_class, int domain, u_long npages,
185 vm_page_t m_run, vm_paddr_t high);
186 static int vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object,
188 static int vm_page_import(void *arg, void **store, int cnt, int domain,
190 static void vm_page_release(void *arg, void **store, int cnt);
192 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
195 vm_page_init(void *dummy)
198 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
199 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
200 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
201 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
205 * The cache page zone is initialized later since we need to be able to allocate
206 * pages before UMA is fully initialized.
209 vm_page_init_cache_zones(void *dummy __unused)
211 struct vm_domain *vmd;
214 for (i = 0; i < vm_ndomains; i++) {
217 * Don't allow the page cache to take up more than .25% of
220 if (vmd->vmd_page_count / 400 < 256 * mp_ncpus)
222 vmd->vmd_pgcache = uma_zcache_create("vm pgcache",
223 sizeof(struct vm_page), NULL, NULL, NULL, NULL,
224 vm_page_import, vm_page_release, vmd,
225 UMA_ZONE_NOBUCKETCACHE | UMA_ZONE_MAXBUCKET | UMA_ZONE_VM);
228 SYSINIT(vm_page2, SI_SUB_VM_CONF, SI_ORDER_ANY, vm_page_init_cache_zones, NULL);
230 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
231 #if PAGE_SIZE == 32768
233 CTASSERT(sizeof(u_long) >= 8);
238 * Try to acquire a physical address lock while a pmap is locked. If we
239 * fail to trylock we unlock and lock the pmap directly and cache the
240 * locked pa in *locked. The caller should then restart their loop in case
241 * the virtual to physical mapping has changed.
244 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
251 PA_LOCK_ASSERT(lockpa, MA_OWNED);
252 if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
259 atomic_add_int(&pa_tryrelock_restart, 1);
268 * Sets the page size, perhaps based upon the memory
269 * size. Must be called before any use of page-size
270 * dependent functions.
273 vm_set_page_size(void)
275 if (vm_cnt.v_page_size == 0)
276 vm_cnt.v_page_size = PAGE_SIZE;
277 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
278 panic("vm_set_page_size: page size not a power of two");
282 * vm_page_blacklist_next:
284 * Find the next entry in the provided string of blacklist
285 * addresses. Entries are separated by space, comma, or newline.
286 * If an invalid integer is encountered then the rest of the
287 * string is skipped. Updates the list pointer to the next
288 * character, or NULL if the string is exhausted or invalid.
291 vm_page_blacklist_next(char **list, char *end)
296 if (list == NULL || *list == NULL)
304 * If there's no end pointer then the buffer is coming from
305 * the kenv and we know it's null-terminated.
308 end = *list + strlen(*list);
310 /* Ensure that strtoq() won't walk off the end */
312 if (*end == '\n' || *end == ' ' || *end == ',')
315 printf("Blacklist not terminated, skipping\n");
321 for (pos = *list; *pos != '\0'; pos = cp) {
322 bad = strtoq(pos, &cp, 0);
323 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
332 if (*cp == '\0' || ++cp >= end)
336 return (trunc_page(bad));
338 printf("Garbage in RAM blacklist, skipping\n");
344 vm_page_blacklist_add(vm_paddr_t pa, bool verbose)
346 struct vm_domain *vmd;
350 m = vm_phys_paddr_to_vm_page(pa);
352 return (true); /* page does not exist, no failure */
354 vmd = vm_pagequeue_domain(m);
355 vm_domain_free_lock(vmd);
356 ret = vm_phys_unfree_page(m);
357 vm_domain_free_unlock(vmd);
359 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
361 printf("Skipping page with pa 0x%jx\n", (uintmax_t)pa);
367 * vm_page_blacklist_check:
369 * Iterate through the provided string of blacklist addresses, pulling
370 * each entry out of the physical allocator free list and putting it
371 * onto a list for reporting via the vm.page_blacklist sysctl.
374 vm_page_blacklist_check(char *list, char *end)
380 while (next != NULL) {
381 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
383 vm_page_blacklist_add(pa, bootverbose);
388 * vm_page_blacklist_load:
390 * Search for a special module named "ram_blacklist". It'll be a
391 * plain text file provided by the user via the loader directive
395 vm_page_blacklist_load(char **list, char **end)
404 mod = preload_search_by_type("ram_blacklist");
406 ptr = preload_fetch_addr(mod);
407 len = preload_fetch_size(mod);
418 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
425 error = sysctl_wire_old_buffer(req, 0);
428 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
429 TAILQ_FOREACH(m, &blacklist_head, listq) {
430 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
431 (uintmax_t)m->phys_addr);
434 error = sbuf_finish(&sbuf);
440 * Initialize a dummy page for use in scans of the specified paging queue.
441 * In principle, this function only needs to set the flag PG_MARKER.
442 * Nonetheless, it write busies and initializes the hold count to one as
443 * safety precautions.
446 vm_page_init_marker(vm_page_t marker, int queue, uint8_t aflags)
449 bzero(marker, sizeof(*marker));
450 marker->flags = PG_MARKER;
451 marker->aflags = aflags;
452 marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
453 marker->queue = queue;
454 marker->hold_count = 1;
458 vm_page_domain_init(int domain)
460 struct vm_domain *vmd;
461 struct vm_pagequeue *pq;
464 vmd = VM_DOMAIN(domain);
465 bzero(vmd, sizeof(*vmd));
466 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
467 "vm inactive pagequeue";
468 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
469 "vm active pagequeue";
470 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
471 "vm laundry pagequeue";
472 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_name) =
473 "vm unswappable pagequeue";
474 vmd->vmd_domain = domain;
475 vmd->vmd_page_count = 0;
476 vmd->vmd_free_count = 0;
478 vmd->vmd_oom = FALSE;
479 for (i = 0; i < PQ_COUNT; i++) {
480 pq = &vmd->vmd_pagequeues[i];
481 TAILQ_INIT(&pq->pq_pl);
482 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
483 MTX_DEF | MTX_DUPOK);
484 vm_page_init_marker(&vmd->vmd_markers[i], i, 0);
486 mtx_init(&vmd->vmd_free_mtx, "vm page free queue", NULL, MTX_DEF);
487 mtx_init(&vmd->vmd_pageout_mtx, "vm pageout lock", NULL, MTX_DEF);
488 snprintf(vmd->vmd_name, sizeof(vmd->vmd_name), "%d", domain);
491 * inacthead is used to provide FIFO ordering for LRU-bypassing
494 vm_page_init_marker(&vmd->vmd_inacthead, PQ_INACTIVE, PGA_ENQUEUED);
495 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_INACTIVE].pq_pl,
496 &vmd->vmd_inacthead, plinks.q);
499 * The clock pages are used to implement active queue scanning without
500 * requeues. Scans start at clock[0], which is advanced after the scan
501 * ends. When the two clock hands meet, they are reset and scanning
502 * resumes from the head of the queue.
504 vm_page_init_marker(&vmd->vmd_clock[0], PQ_ACTIVE, PGA_ENQUEUED);
505 vm_page_init_marker(&vmd->vmd_clock[1], PQ_ACTIVE, PGA_ENQUEUED);
506 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
507 &vmd->vmd_clock[0], plinks.q);
508 TAILQ_INSERT_TAIL(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
509 &vmd->vmd_clock[1], plinks.q);
513 * Initialize a physical page in preparation for adding it to the free
517 vm_page_init_page(vm_page_t m, vm_paddr_t pa, int segind)
522 m->busy_lock = VPB_UNBUSIED;
529 m->order = VM_NFREEORDER;
530 m->pool = VM_FREEPOOL_DEFAULT;
531 m->valid = m->dirty = 0;
538 * Initializes the resident memory module. Allocates physical memory for
539 * bootstrapping UMA and some data structures that are used to manage
540 * physical pages. Initializes these structures, and populates the free
544 vm_page_startup(vm_offset_t vaddr)
546 struct vm_phys_seg *seg;
548 char *list, *listend;
550 vm_paddr_t end, high_avail, low_avail, new_end, page_range, size;
551 vm_paddr_t biggestsize, last_pa, pa;
553 int biggestone, i, segind;
554 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
560 vaddr = round_page(vaddr);
562 for (i = 0; phys_avail[i + 1]; i += 2) {
563 phys_avail[i] = round_page(phys_avail[i]);
564 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
566 for (i = 0; phys_avail[i + 1]; i += 2) {
567 size = phys_avail[i + 1] - phys_avail[i];
568 if (size > biggestsize) {
574 end = phys_avail[biggestone+1];
577 * Initialize the page and queue locks.
579 mtx_init(&vm_domainset_lock, "vm domainset lock", NULL, MTX_DEF);
580 for (i = 0; i < PA_LOCK_COUNT; i++)
581 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
582 for (i = 0; i < vm_ndomains; i++)
583 vm_page_domain_init(i);
586 * Allocate memory for use when boot strapping the kernel memory
587 * allocator. Tell UMA how many zones we are going to create
588 * before going fully functional. UMA will add its zones.
590 * VM startup zones: vmem, vmem_btag, VM OBJECT, RADIX NODE, MAP,
591 * KMAP ENTRY, MAP ENTRY, VMSPACE.
593 boot_pages = uma_startup_count(8);
595 #ifndef UMA_MD_SMALL_ALLOC
596 /* vmem_startup() calls uma_prealloc(). */
597 boot_pages += vmem_startup_count();
598 /* vm_map_startup() calls uma_prealloc(). */
599 boot_pages += howmany(MAX_KMAP,
600 UMA_SLAB_SPACE / sizeof(struct vm_map));
603 * Before going fully functional kmem_init() does allocation
604 * from "KMAP ENTRY" and vmem_create() does allocation from "vmem".
609 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
610 * manually fetch the value.
612 TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
613 new_end = end - (boot_pages * UMA_SLAB_SIZE);
614 new_end = trunc_page(new_end);
615 mapped = pmap_map(&vaddr, new_end, end,
616 VM_PROT_READ | VM_PROT_WRITE);
617 bzero((void *)mapped, end - new_end);
618 uma_startup((void *)mapped, boot_pages);
622 new_end = end - round_page(witness_startup_count());
623 mapped = pmap_map(&vaddr, new_end, end,
624 VM_PROT_READ | VM_PROT_WRITE);
625 bzero((void *)mapped, end - new_end);
626 witness_startup((void *)mapped);
629 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
630 defined(__i386__) || defined(__mips__)
632 * Allocate a bitmap to indicate that a random physical page
633 * needs to be included in a minidump.
635 * The amd64 port needs this to indicate which direct map pages
636 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
638 * However, i386 still needs this workspace internally within the
639 * minidump code. In theory, they are not needed on i386, but are
640 * included should the sf_buf code decide to use them.
643 for (i = 0; dump_avail[i + 1] != 0; i += 2)
644 if (dump_avail[i + 1] > last_pa)
645 last_pa = dump_avail[i + 1];
646 page_range = last_pa / PAGE_SIZE;
647 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
648 new_end -= vm_page_dump_size;
649 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
650 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
651 bzero((void *)vm_page_dump, vm_page_dump_size);
655 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
657 * Include the UMA bootstrap pages and vm_page_dump in a crash dump.
658 * When pmap_map() uses the direct map, they are not automatically
661 for (pa = new_end; pa < end; pa += PAGE_SIZE)
664 phys_avail[biggestone + 1] = new_end;
667 * Request that the physical pages underlying the message buffer be
668 * included in a crash dump. Since the message buffer is accessed
669 * through the direct map, they are not automatically included.
671 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
672 last_pa = pa + round_page(msgbufsize);
673 while (pa < last_pa) {
679 * Compute the number of pages of memory that will be available for
680 * use, taking into account the overhead of a page structure per page.
681 * In other words, solve
682 * "available physical memory" - round_page(page_range *
683 * sizeof(struct vm_page)) = page_range * PAGE_SIZE
686 low_avail = phys_avail[0];
687 high_avail = phys_avail[1];
688 for (i = 0; i < vm_phys_nsegs; i++) {
689 if (vm_phys_segs[i].start < low_avail)
690 low_avail = vm_phys_segs[i].start;
691 if (vm_phys_segs[i].end > high_avail)
692 high_avail = vm_phys_segs[i].end;
694 /* Skip the first chunk. It is already accounted for. */
695 for (i = 2; phys_avail[i + 1] != 0; i += 2) {
696 if (phys_avail[i] < low_avail)
697 low_avail = phys_avail[i];
698 if (phys_avail[i + 1] > high_avail)
699 high_avail = phys_avail[i + 1];
701 first_page = low_avail / PAGE_SIZE;
702 #ifdef VM_PHYSSEG_SPARSE
704 for (i = 0; i < vm_phys_nsegs; i++)
705 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
706 for (i = 0; phys_avail[i + 1] != 0; i += 2)
707 size += phys_avail[i + 1] - phys_avail[i];
708 #elif defined(VM_PHYSSEG_DENSE)
709 size = high_avail - low_avail;
711 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
714 #ifdef VM_PHYSSEG_DENSE
716 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
717 * the overhead of a page structure per page only if vm_page_array is
718 * allocated from the last physical memory chunk. Otherwise, we must
719 * allocate page structures representing the physical memory
720 * underlying vm_page_array, even though they will not be used.
722 if (new_end != high_avail)
723 page_range = size / PAGE_SIZE;
727 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
730 * If the partial bytes remaining are large enough for
731 * a page (PAGE_SIZE) without a corresponding
732 * 'struct vm_page', then new_end will contain an
733 * extra page after subtracting the length of the VM
734 * page array. Compensate by subtracting an extra
737 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
738 if (new_end == high_avail)
739 high_avail -= PAGE_SIZE;
740 new_end -= PAGE_SIZE;
746 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
747 * However, because this page is allocated from KVM, out-of-bounds
748 * accesses using the direct map will not be trapped.
753 * Allocate physical memory for the page structures, and map it.
755 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
756 mapped = pmap_map(&vaddr, new_end, end,
757 VM_PROT_READ | VM_PROT_WRITE);
758 vm_page_array = (vm_page_t)mapped;
759 vm_page_array_size = page_range;
761 #if VM_NRESERVLEVEL > 0
763 * Allocate physical memory for the reservation management system's
764 * data structures, and map it.
766 if (high_avail == end)
767 high_avail = new_end;
768 new_end = vm_reserv_startup(&vaddr, new_end, high_avail);
770 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
772 * Include vm_page_array and vm_reserv_array in a crash dump.
774 for (pa = new_end; pa < end; pa += PAGE_SIZE)
777 phys_avail[biggestone + 1] = new_end;
780 * Add physical memory segments corresponding to the available
783 for (i = 0; phys_avail[i + 1] != 0; i += 2)
784 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
787 * Initialize the physical memory allocator.
792 * Initialize the page structures and add every available page to the
793 * physical memory allocator's free lists.
795 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
796 for (ii = 0; ii < vm_page_array_size; ii++) {
797 m = &vm_page_array[ii];
798 vm_page_init_page(m, (first_page + ii) << PAGE_SHIFT, 0);
799 m->flags = PG_FICTITIOUS;
802 vm_cnt.v_page_count = 0;
803 for (segind = 0; segind < vm_phys_nsegs; segind++) {
804 seg = &vm_phys_segs[segind];
805 for (m = seg->first_page, pa = seg->start; pa < seg->end;
806 m++, pa += PAGE_SIZE)
807 vm_page_init_page(m, pa, segind);
810 * Add the segment to the free lists only if it is covered by
811 * one of the ranges in phys_avail. Because we've added the
812 * ranges to the vm_phys_segs array, we can assume that each
813 * segment is either entirely contained in one of the ranges,
814 * or doesn't overlap any of them.
816 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
817 struct vm_domain *vmd;
819 if (seg->start < phys_avail[i] ||
820 seg->end > phys_avail[i + 1])
824 pagecount = (u_long)atop(seg->end - seg->start);
826 vmd = VM_DOMAIN(seg->domain);
827 vm_domain_free_lock(vmd);
828 vm_phys_free_contig(m, pagecount);
829 vm_domain_free_unlock(vmd);
830 vm_domain_freecnt_inc(vmd, pagecount);
831 vm_cnt.v_page_count += (u_int)pagecount;
833 vmd = VM_DOMAIN(seg->domain);
834 vmd->vmd_page_count += (u_int)pagecount;
835 vmd->vmd_segs |= 1UL << m->segind;
841 * Remove blacklisted pages from the physical memory allocator.
843 TAILQ_INIT(&blacklist_head);
844 vm_page_blacklist_load(&list, &listend);
845 vm_page_blacklist_check(list, listend);
847 list = kern_getenv("vm.blacklist");
848 vm_page_blacklist_check(list, NULL);
851 #if VM_NRESERVLEVEL > 0
853 * Initialize the reservation management system.
858 * Set an initial domain policy for thread0 so that allocations
867 vm_page_reference(vm_page_t m)
870 vm_page_aflag_set(m, PGA_REFERENCED);
874 * vm_page_busy_downgrade:
876 * Downgrade an exclusive busy page into a single shared busy page.
879 vm_page_busy_downgrade(vm_page_t m)
884 vm_page_assert_xbusied(m);
885 locked = mtx_owned(vm_page_lockptr(m));
889 x &= VPB_BIT_WAITERS;
890 if (x != 0 && !locked)
892 if (atomic_cmpset_rel_int(&m->busy_lock,
893 VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1)))
895 if (x != 0 && !locked)
908 * Return a positive value if the page is shared busied, 0 otherwise.
911 vm_page_sbusied(vm_page_t m)
916 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
922 * Shared unbusy a page.
925 vm_page_sunbusy(vm_page_t m)
929 vm_page_lock_assert(m, MA_NOTOWNED);
930 vm_page_assert_sbusied(m);
934 if (VPB_SHARERS(x) > 1) {
935 if (atomic_cmpset_int(&m->busy_lock, x,
940 if ((x & VPB_BIT_WAITERS) == 0) {
941 KASSERT(x == VPB_SHARERS_WORD(1),
942 ("vm_page_sunbusy: invalid lock state"));
943 if (atomic_cmpset_int(&m->busy_lock,
944 VPB_SHARERS_WORD(1), VPB_UNBUSIED))
948 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
949 ("vm_page_sunbusy: invalid lock state for waiters"));
952 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
963 * vm_page_busy_sleep:
965 * Sleep and release the page lock, using the page pointer as wchan.
966 * This is used to implement the hard-path of busying mechanism.
968 * The given page must be locked.
970 * If nonshared is true, sleep only if the page is xbusy.
973 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
977 vm_page_assert_locked(m);
980 if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
981 ((x & VPB_BIT_WAITERS) == 0 &&
982 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
986 msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
992 * Try to shared busy a page.
993 * If the operation succeeds 1 is returned otherwise 0.
994 * The operation never sleeps.
997 vm_page_trysbusy(vm_page_t m)
1003 if ((x & VPB_BIT_SHARED) == 0)
1005 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
1011 vm_page_xunbusy_locked(vm_page_t m)
1014 vm_page_assert_xbusied(m);
1015 vm_page_assert_locked(m);
1017 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1018 /* There is a waiter, do wakeup() instead of vm_page_flash(). */
1023 vm_page_xunbusy_maybelocked(vm_page_t m)
1027 vm_page_assert_xbusied(m);
1030 * Fast path for unbusy. If it succeeds, we know that there
1031 * are no waiters, so we do not need a wakeup.
1033 if (atomic_cmpset_rel_int(&m->busy_lock, VPB_SINGLE_EXCLUSIVER,
1037 lockacq = !mtx_owned(vm_page_lockptr(m));
1040 vm_page_xunbusy_locked(m);
1046 * vm_page_xunbusy_hard:
1048 * Called after the first try the exclusive unbusy of a page failed.
1049 * It is assumed that the waiters bit is on.
1052 vm_page_xunbusy_hard(vm_page_t m)
1055 vm_page_assert_xbusied(m);
1058 vm_page_xunbusy_locked(m);
1065 * Wakeup anyone waiting for the page.
1066 * The ownership bits do not change.
1068 * The given page must be locked.
1071 vm_page_flash(vm_page_t m)
1075 vm_page_lock_assert(m, MA_OWNED);
1079 if ((x & VPB_BIT_WAITERS) == 0)
1081 if (atomic_cmpset_int(&m->busy_lock, x,
1082 x & (~VPB_BIT_WAITERS)))
1089 * Avoid releasing and reacquiring the same page lock.
1092 vm_page_change_lock(vm_page_t m, struct mtx **mtx)
1096 mtx1 = vm_page_lockptr(m);
1106 * Keep page from being freed by the page daemon
1107 * much of the same effect as wiring, except much lower
1108 * overhead and should be used only for *very* temporary
1109 * holding ("wiring").
1112 vm_page_hold(vm_page_t mem)
1115 vm_page_lock_assert(mem, MA_OWNED);
1120 vm_page_unhold(vm_page_t mem)
1123 vm_page_lock_assert(mem, MA_OWNED);
1124 KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
1126 if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
1127 vm_page_free_toq(mem);
1131 * vm_page_unhold_pages:
1133 * Unhold each of the pages that is referenced by the given array.
1136 vm_page_unhold_pages(vm_page_t *ma, int count)
1141 for (; count != 0; count--) {
1142 vm_page_change_lock(*ma, &mtx);
1143 vm_page_unhold(*ma);
1151 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1155 #ifdef VM_PHYSSEG_SPARSE
1156 m = vm_phys_paddr_to_vm_page(pa);
1158 m = vm_phys_fictitious_to_vm_page(pa);
1160 #elif defined(VM_PHYSSEG_DENSE)
1164 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1165 m = &vm_page_array[pi - first_page];
1168 return (vm_phys_fictitious_to_vm_page(pa));
1170 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1177 * Create a fictitious page with the specified physical address and
1178 * memory attribute. The memory attribute is the only the machine-
1179 * dependent aspect of a fictitious page that must be initialized.
1182 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1186 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1187 vm_page_initfake(m, paddr, memattr);
1192 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1195 if ((m->flags & PG_FICTITIOUS) != 0) {
1197 * The page's memattr might have changed since the
1198 * previous initialization. Update the pmap to the
1203 m->phys_addr = paddr;
1205 /* Fictitious pages don't use "segind". */
1206 m->flags = PG_FICTITIOUS;
1207 /* Fictitious pages don't use "order" or "pool". */
1208 m->oflags = VPO_UNMANAGED;
1209 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1213 pmap_page_set_memattr(m, memattr);
1219 * Release a fictitious page.
1222 vm_page_putfake(vm_page_t m)
1225 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1226 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1227 ("vm_page_putfake: bad page %p", m));
1228 uma_zfree(fakepg_zone, m);
1232 * vm_page_updatefake:
1234 * Update the given fictitious page to the specified physical address and
1238 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1241 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1242 ("vm_page_updatefake: bad page %p", m));
1243 m->phys_addr = paddr;
1244 pmap_page_set_memattr(m, memattr);
1253 vm_page_free(vm_page_t m)
1256 m->flags &= ~PG_ZERO;
1257 vm_page_free_toq(m);
1261 * vm_page_free_zero:
1263 * Free a page to the zerod-pages queue
1266 vm_page_free_zero(vm_page_t m)
1269 m->flags |= PG_ZERO;
1270 vm_page_free_toq(m);
1274 * Unbusy and handle the page queueing for a page from a getpages request that
1275 * was optionally read ahead or behind.
1278 vm_page_readahead_finish(vm_page_t m)
1281 /* We shouldn't put invalid pages on queues. */
1282 KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
1285 * Since the page is not the actually needed one, whether it should
1286 * be activated or deactivated is not obvious. Empirical results
1287 * have shown that deactivating the page is usually the best choice,
1288 * unless the page is wanted by another thread.
1291 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1292 vm_page_activate(m);
1294 vm_page_deactivate(m);
1300 * vm_page_sleep_if_busy:
1302 * Sleep and release the page queues lock if the page is busied.
1303 * Returns TRUE if the thread slept.
1305 * The given page must be unlocked and object containing it must
1309 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1313 vm_page_lock_assert(m, MA_NOTOWNED);
1314 VM_OBJECT_ASSERT_WLOCKED(m->object);
1316 if (vm_page_busied(m)) {
1318 * The page-specific object must be cached because page
1319 * identity can change during the sleep, causing the
1320 * re-lock of a different object.
1321 * It is assumed that a reference to the object is already
1322 * held by the callers.
1326 VM_OBJECT_WUNLOCK(obj);
1327 vm_page_busy_sleep(m, msg, false);
1328 VM_OBJECT_WLOCK(obj);
1335 * vm_page_dirty_KBI: [ internal use only ]
1337 * Set all bits in the page's dirty field.
1339 * The object containing the specified page must be locked if the
1340 * call is made from the machine-independent layer.
1342 * See vm_page_clear_dirty_mask().
1344 * This function should only be called by vm_page_dirty().
1347 vm_page_dirty_KBI(vm_page_t m)
1350 /* Refer to this operation by its public name. */
1351 KASSERT(m->valid == VM_PAGE_BITS_ALL,
1352 ("vm_page_dirty: page is invalid!"));
1353 m->dirty = VM_PAGE_BITS_ALL;
1357 * vm_page_insert: [ internal use only ]
1359 * Inserts the given mem entry into the object and object list.
1361 * The object must be locked.
1364 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1368 VM_OBJECT_ASSERT_WLOCKED(object);
1369 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1370 return (vm_page_insert_after(m, object, pindex, mpred));
1374 * vm_page_insert_after:
1376 * Inserts the page "m" into the specified object at offset "pindex".
1378 * The page "mpred" must immediately precede the offset "pindex" within
1379 * the specified object.
1381 * The object must be locked.
1384 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1389 VM_OBJECT_ASSERT_WLOCKED(object);
1390 KASSERT(m->object == NULL,
1391 ("vm_page_insert_after: page already inserted"));
1392 if (mpred != NULL) {
1393 KASSERT(mpred->object == object,
1394 ("vm_page_insert_after: object doesn't contain mpred"));
1395 KASSERT(mpred->pindex < pindex,
1396 ("vm_page_insert_after: mpred doesn't precede pindex"));
1397 msucc = TAILQ_NEXT(mpred, listq);
1399 msucc = TAILQ_FIRST(&object->memq);
1401 KASSERT(msucc->pindex > pindex,
1402 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1405 * Record the object/offset pair in this page
1411 * Now link into the object's ordered list of backed pages.
1413 if (vm_radix_insert(&object->rtree, m)) {
1418 vm_page_insert_radixdone(m, object, mpred);
1423 * vm_page_insert_radixdone:
1425 * Complete page "m" insertion into the specified object after the
1426 * radix trie hooking.
1428 * The page "mpred" must precede the offset "m->pindex" within the
1431 * The object must be locked.
1434 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1437 VM_OBJECT_ASSERT_WLOCKED(object);
1438 KASSERT(object != NULL && m->object == object,
1439 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1440 if (mpred != NULL) {
1441 KASSERT(mpred->object == object,
1442 ("vm_page_insert_after: object doesn't contain mpred"));
1443 KASSERT(mpred->pindex < m->pindex,
1444 ("vm_page_insert_after: mpred doesn't precede pindex"));
1448 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1450 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1453 * Show that the object has one more resident page.
1455 object->resident_page_count++;
1458 * Hold the vnode until the last page is released.
1460 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1461 vhold(object->handle);
1464 * Since we are inserting a new and possibly dirty page,
1465 * update the object's OBJ_MIGHTBEDIRTY flag.
1467 if (pmap_page_is_write_mapped(m))
1468 vm_object_set_writeable_dirty(object);
1474 * Removes the specified page from its containing object, but does not
1475 * invalidate any backing storage.
1477 * The object must be locked. The page must be locked if it is managed.
1480 vm_page_remove(vm_page_t m)
1485 if ((m->oflags & VPO_UNMANAGED) == 0)
1486 vm_page_assert_locked(m);
1487 if ((object = m->object) == NULL)
1489 VM_OBJECT_ASSERT_WLOCKED(object);
1490 if (vm_page_xbusied(m))
1491 vm_page_xunbusy_maybelocked(m);
1492 mrem = vm_radix_remove(&object->rtree, m->pindex);
1493 KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1496 * Now remove from the object's list of backed pages.
1498 TAILQ_REMOVE(&object->memq, m, listq);
1501 * And show that the object has one fewer resident page.
1503 object->resident_page_count--;
1506 * The vnode may now be recycled.
1508 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1509 vdrop(object->handle);
1517 * Returns the page associated with the object/offset
1518 * pair specified; if none is found, NULL is returned.
1520 * The object must be locked.
1523 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1526 VM_OBJECT_ASSERT_LOCKED(object);
1527 return (vm_radix_lookup(&object->rtree, pindex));
1531 * vm_page_find_least:
1533 * Returns the page associated with the object with least pindex
1534 * greater than or equal to the parameter pindex, or NULL.
1536 * The object must be locked.
1539 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1543 VM_OBJECT_ASSERT_LOCKED(object);
1544 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1545 m = vm_radix_lookup_ge(&object->rtree, pindex);
1550 * Returns the given page's successor (by pindex) within the object if it is
1551 * resident; if none is found, NULL is returned.
1553 * The object must be locked.
1556 vm_page_next(vm_page_t m)
1560 VM_OBJECT_ASSERT_LOCKED(m->object);
1561 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1562 MPASS(next->object == m->object);
1563 if (next->pindex != m->pindex + 1)
1570 * Returns the given page's predecessor (by pindex) within the object if it is
1571 * resident; if none is found, NULL is returned.
1573 * The object must be locked.
1576 vm_page_prev(vm_page_t m)
1580 VM_OBJECT_ASSERT_LOCKED(m->object);
1581 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1582 MPASS(prev->object == m->object);
1583 if (prev->pindex != m->pindex - 1)
1590 * Uses the page mnew as a replacement for an existing page at index
1591 * pindex which must be already present in the object.
1593 * The existing page must not be on a paging queue.
1596 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1600 VM_OBJECT_ASSERT_WLOCKED(object);
1601 KASSERT(mnew->object == NULL,
1602 ("vm_page_replace: page %p already in object", mnew));
1603 KASSERT(mnew->queue == PQ_NONE,
1604 ("vm_page_replace: new page %p is on a paging queue", mnew));
1607 * This function mostly follows vm_page_insert() and
1608 * vm_page_remove() without the radix, object count and vnode
1609 * dance. Double check such functions for more comments.
1612 mnew->object = object;
1613 mnew->pindex = pindex;
1614 mold = vm_radix_replace(&object->rtree, mnew);
1615 KASSERT(mold->queue == PQ_NONE,
1616 ("vm_page_replace: old page %p is on a paging queue", mold));
1618 /* Keep the resident page list in sorted order. */
1619 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1620 TAILQ_REMOVE(&object->memq, mold, listq);
1622 mold->object = NULL;
1623 vm_page_xunbusy_maybelocked(mold);
1626 * The object's resident_page_count does not change because we have
1627 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1629 if (pmap_page_is_write_mapped(mnew))
1630 vm_object_set_writeable_dirty(object);
1637 * Move the given memory entry from its
1638 * current object to the specified target object/offset.
1640 * Note: swap associated with the page must be invalidated by the move. We
1641 * have to do this for several reasons: (1) we aren't freeing the
1642 * page, (2) we are dirtying the page, (3) the VM system is probably
1643 * moving the page from object A to B, and will then later move
1644 * the backing store from A to B and we can't have a conflict.
1646 * Note: we *always* dirty the page. It is necessary both for the
1647 * fact that we moved it, and because we may be invalidating
1650 * The objects must be locked.
1653 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1658 VM_OBJECT_ASSERT_WLOCKED(new_object);
1660 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1661 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1662 ("vm_page_rename: pindex already renamed"));
1665 * Create a custom version of vm_page_insert() which does not depend
1666 * by m_prev and can cheat on the implementation aspects of the
1670 m->pindex = new_pindex;
1671 if (vm_radix_insert(&new_object->rtree, m)) {
1677 * The operation cannot fail anymore. The removal must happen before
1678 * the listq iterator is tainted.
1684 /* Return back to the new pindex to complete vm_page_insert(). */
1685 m->pindex = new_pindex;
1686 m->object = new_object;
1688 vm_page_insert_radixdone(m, new_object, mpred);
1696 * Allocate and return a page that is associated with the specified
1697 * object and offset pair. By default, this page is exclusive busied.
1699 * The caller must always specify an allocation class.
1701 * allocation classes:
1702 * VM_ALLOC_NORMAL normal process request
1703 * VM_ALLOC_SYSTEM system *really* needs a page
1704 * VM_ALLOC_INTERRUPT interrupt time request
1706 * optional allocation flags:
1707 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1708 * intends to allocate
1709 * VM_ALLOC_NOBUSY do not exclusive busy the page
1710 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1711 * VM_ALLOC_NOOBJ page is not associated with an object and
1712 * should not be exclusive busy
1713 * VM_ALLOC_SBUSY shared busy the allocated page
1714 * VM_ALLOC_WIRED wire the allocated page
1715 * VM_ALLOC_ZERO prefer a zeroed page
1718 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1721 return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1722 vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1726 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1730 return (vm_page_alloc_domain_after(object, pindex, domain, req,
1731 object != NULL ? vm_radix_lookup_le(&object->rtree, pindex) :
1736 * Allocate a page in the specified object with the given page index. To
1737 * optimize insertion of the page into the object, the caller must also specifiy
1738 * the resident page in the object with largest index smaller than the given
1739 * page index, or NULL if no such page exists.
1742 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1743 int req, vm_page_t mpred)
1745 struct vm_domainset_iter di;
1749 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1751 m = vm_page_alloc_domain_after(object, pindex, domain, req,
1755 } while (vm_domainset_iter_page(&di, &domain, &req) == 0);
1761 * Returns true if the number of free pages exceeds the minimum
1762 * for the request class and false otherwise.
1765 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
1767 u_int limit, old, new;
1769 req = req & VM_ALLOC_CLASS_MASK;
1772 * The page daemon is allowed to dig deeper into the free page list.
1774 if (curproc == pageproc && req != VM_ALLOC_INTERRUPT)
1775 req = VM_ALLOC_SYSTEM;
1776 if (req == VM_ALLOC_INTERRUPT)
1778 else if (req == VM_ALLOC_SYSTEM)
1779 limit = vmd->vmd_interrupt_free_min;
1781 limit = vmd->vmd_free_reserved;
1784 * Attempt to reserve the pages. Fail if we're below the limit.
1787 old = vmd->vmd_free_count;
1792 } while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
1794 /* Wake the page daemon if we've crossed the threshold. */
1795 if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
1796 pagedaemon_wakeup(vmd->vmd_domain);
1798 /* Only update bitsets on transitions. */
1799 if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
1800 (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
1807 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
1808 int req, vm_page_t mpred)
1810 struct vm_domain *vmd;
1814 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1815 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1816 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1817 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1818 ("inconsistent object(%p)/req(%x)", object, req));
1819 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1820 ("Can't sleep and retry object insertion."));
1821 KASSERT(mpred == NULL || mpred->pindex < pindex,
1822 ("mpred %p doesn't precede pindex 0x%jx", mpred,
1823 (uintmax_t)pindex));
1825 VM_OBJECT_ASSERT_WLOCKED(object);
1829 #if VM_NRESERVLEVEL > 0
1831 * Can we allocate the page from a reservation?
1833 if (vm_object_reserv(object) &&
1834 ((m = vm_reserv_extend(req, object, pindex, domain, mpred)) != NULL ||
1835 (m = vm_reserv_alloc_page(req, object, pindex, domain, mpred)) != NULL)) {
1836 domain = vm_phys_domain(m);
1837 vmd = VM_DOMAIN(domain);
1841 vmd = VM_DOMAIN(domain);
1842 if (object != NULL && vmd->vmd_pgcache != NULL) {
1843 m = uma_zalloc(vmd->vmd_pgcache, M_NOWAIT);
1847 if (vm_domain_allocate(vmd, req, 1)) {
1849 * If not, allocate it from the free page queues.
1851 vm_domain_free_lock(vmd);
1852 m = vm_phys_alloc_pages(domain, object != NULL ?
1853 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1854 vm_domain_free_unlock(vmd);
1856 vm_domain_freecnt_inc(vmd, 1);
1857 #if VM_NRESERVLEVEL > 0
1858 if (vm_reserv_reclaim_inactive(domain))
1865 * Not allocatable, give up.
1867 if (vm_domain_alloc_fail(vmd, object, req))
1873 * At this point we had better have found a good page.
1875 KASSERT(m != NULL, ("missing page"));
1879 vm_page_alloc_check(m);
1882 * Initialize the page. Only the PG_ZERO flag is inherited.
1885 if ((req & VM_ALLOC_ZERO) != 0)
1888 if ((req & VM_ALLOC_NODUMP) != 0)
1892 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1894 m->busy_lock = VPB_UNBUSIED;
1895 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1896 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1897 if ((req & VM_ALLOC_SBUSY) != 0)
1898 m->busy_lock = VPB_SHARERS_WORD(1);
1899 if (req & VM_ALLOC_WIRED) {
1901 * The page lock is not required for wiring a page until that
1902 * page is inserted into the object.
1909 if (object != NULL) {
1910 if (vm_page_insert_after(m, object, pindex, mpred)) {
1911 if (req & VM_ALLOC_WIRED) {
1915 KASSERT(m->object == NULL, ("page %p has object", m));
1916 m->oflags = VPO_UNMANAGED;
1917 m->busy_lock = VPB_UNBUSIED;
1918 /* Don't change PG_ZERO. */
1919 vm_page_free_toq(m);
1920 if (req & VM_ALLOC_WAITFAIL) {
1921 VM_OBJECT_WUNLOCK(object);
1923 VM_OBJECT_WLOCK(object);
1928 /* Ignore device objects; the pager sets "memattr" for them. */
1929 if (object->memattr != VM_MEMATTR_DEFAULT &&
1930 (object->flags & OBJ_FICTITIOUS) == 0)
1931 pmap_page_set_memattr(m, object->memattr);
1939 * vm_page_alloc_contig:
1941 * Allocate a contiguous set of physical pages of the given size "npages"
1942 * from the free lists. All of the physical pages must be at or above
1943 * the given physical address "low" and below the given physical address
1944 * "high". The given value "alignment" determines the alignment of the
1945 * first physical page in the set. If the given value "boundary" is
1946 * non-zero, then the set of physical pages cannot cross any physical
1947 * address boundary that is a multiple of that value. Both "alignment"
1948 * and "boundary" must be a power of two.
1950 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1951 * then the memory attribute setting for the physical pages is configured
1952 * to the object's memory attribute setting. Otherwise, the memory
1953 * attribute setting for the physical pages is configured to "memattr",
1954 * overriding the object's memory attribute setting. However, if the
1955 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1956 * memory attribute setting for the physical pages cannot be configured
1957 * to VM_MEMATTR_DEFAULT.
1959 * The specified object may not contain fictitious pages.
1961 * The caller must always specify an allocation class.
1963 * allocation classes:
1964 * VM_ALLOC_NORMAL normal process request
1965 * VM_ALLOC_SYSTEM system *really* needs a page
1966 * VM_ALLOC_INTERRUPT interrupt time request
1968 * optional allocation flags:
1969 * VM_ALLOC_NOBUSY do not exclusive busy the page
1970 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1971 * VM_ALLOC_NOOBJ page is not associated with an object and
1972 * should not be exclusive busy
1973 * VM_ALLOC_SBUSY shared busy the allocated page
1974 * VM_ALLOC_WIRED wire the allocated page
1975 * VM_ALLOC_ZERO prefer a zeroed page
1978 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1979 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1980 vm_paddr_t boundary, vm_memattr_t memattr)
1982 struct vm_domainset_iter di;
1986 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1988 m = vm_page_alloc_contig_domain(object, pindex, domain, req,
1989 npages, low, high, alignment, boundary, memattr);
1992 } while (vm_domainset_iter_page(&di, &domain, &req) == 0);
1998 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1999 int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2000 vm_paddr_t boundary, vm_memattr_t memattr)
2002 struct vm_domain *vmd;
2003 vm_page_t m, m_ret, mpred;
2004 u_int busy_lock, flags, oflags;
2006 mpred = NULL; /* XXX: pacify gcc */
2007 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
2008 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
2009 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2010 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2011 ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
2013 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2014 ("Can't sleep and retry object insertion."));
2015 if (object != NULL) {
2016 VM_OBJECT_ASSERT_WLOCKED(object);
2017 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2018 ("vm_page_alloc_contig: object %p has fictitious pages",
2021 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2023 if (object != NULL) {
2024 mpred = vm_radix_lookup_le(&object->rtree, pindex);
2025 KASSERT(mpred == NULL || mpred->pindex != pindex,
2026 ("vm_page_alloc_contig: pindex already allocated"));
2030 * Can we allocate the pages without the number of free pages falling
2031 * below the lower bound for the allocation class?
2034 #if VM_NRESERVLEVEL > 0
2036 * Can we allocate the pages from a reservation?
2038 if (vm_object_reserv(object) &&
2039 ((m_ret = vm_reserv_extend_contig(req, object, pindex, domain,
2040 npages, low, high, alignment, boundary, mpred)) != NULL ||
2041 (m_ret = vm_reserv_alloc_contig(req, object, pindex, domain,
2042 npages, low, high, alignment, boundary, mpred)) != NULL)) {
2043 domain = vm_phys_domain(m_ret);
2044 vmd = VM_DOMAIN(domain);
2049 vmd = VM_DOMAIN(domain);
2050 if (vm_domain_allocate(vmd, req, npages)) {
2052 * allocate them from the free page queues.
2054 vm_domain_free_lock(vmd);
2055 m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2056 alignment, boundary);
2057 vm_domain_free_unlock(vmd);
2058 if (m_ret == NULL) {
2059 vm_domain_freecnt_inc(vmd, npages);
2060 #if VM_NRESERVLEVEL > 0
2061 if (vm_reserv_reclaim_contig(domain, npages, low,
2062 high, alignment, boundary))
2067 if (m_ret == NULL) {
2068 if (vm_domain_alloc_fail(vmd, object, req))
2072 #if VM_NRESERVLEVEL > 0
2075 for (m = m_ret; m < &m_ret[npages]; m++) {
2077 vm_page_alloc_check(m);
2081 * Initialize the pages. Only the PG_ZERO flag is inherited.
2084 if ((req & VM_ALLOC_ZERO) != 0)
2086 if ((req & VM_ALLOC_NODUMP) != 0)
2088 oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2090 busy_lock = VPB_UNBUSIED;
2091 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2092 busy_lock = VPB_SINGLE_EXCLUSIVER;
2093 if ((req & VM_ALLOC_SBUSY) != 0)
2094 busy_lock = VPB_SHARERS_WORD(1);
2095 if ((req & VM_ALLOC_WIRED) != 0)
2096 vm_wire_add(npages);
2097 if (object != NULL) {
2098 if (object->memattr != VM_MEMATTR_DEFAULT &&
2099 memattr == VM_MEMATTR_DEFAULT)
2100 memattr = object->memattr;
2102 for (m = m_ret; m < &m_ret[npages]; m++) {
2104 m->flags = (m->flags | PG_NODUMP) & flags;
2105 m->busy_lock = busy_lock;
2106 if ((req & VM_ALLOC_WIRED) != 0)
2110 if (object != NULL) {
2111 if (vm_page_insert_after(m, object, pindex, mpred)) {
2112 if ((req & VM_ALLOC_WIRED) != 0)
2113 vm_wire_sub(npages);
2114 KASSERT(m->object == NULL,
2115 ("page %p has object", m));
2117 for (m = m_ret; m < &m_ret[npages]; m++) {
2119 (req & VM_ALLOC_WIRED) != 0)
2121 m->oflags = VPO_UNMANAGED;
2122 m->busy_lock = VPB_UNBUSIED;
2123 /* Don't change PG_ZERO. */
2124 vm_page_free_toq(m);
2126 if (req & VM_ALLOC_WAITFAIL) {
2127 VM_OBJECT_WUNLOCK(object);
2129 VM_OBJECT_WLOCK(object);
2136 if (memattr != VM_MEMATTR_DEFAULT)
2137 pmap_page_set_memattr(m, memattr);
2144 * Check a page that has been freshly dequeued from a freelist.
2147 vm_page_alloc_check(vm_page_t m)
2150 KASSERT(m->object == NULL, ("page %p has object", m));
2151 KASSERT(m->queue == PQ_NONE,
2152 ("page %p has unexpected queue %d", m, m->queue));
2153 KASSERT(!vm_page_held(m), ("page %p is held", m));
2154 KASSERT(!vm_page_busied(m), ("page %p is busy", m));
2155 KASSERT(m->dirty == 0, ("page %p is dirty", m));
2156 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2157 ("page %p has unexpected memattr %d",
2158 m, pmap_page_get_memattr(m)));
2159 KASSERT(m->valid == 0, ("free page %p is valid", m));
2163 * vm_page_alloc_freelist:
2165 * Allocate a physical page from the specified free page list.
2167 * The caller must always specify an allocation class.
2169 * allocation classes:
2170 * VM_ALLOC_NORMAL normal process request
2171 * VM_ALLOC_SYSTEM system *really* needs a page
2172 * VM_ALLOC_INTERRUPT interrupt time request
2174 * optional allocation flags:
2175 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2176 * intends to allocate
2177 * VM_ALLOC_WIRED wire the allocated page
2178 * VM_ALLOC_ZERO prefer a zeroed page
2181 vm_page_alloc_freelist(int freelist, int req)
2183 struct vm_domainset_iter di;
2187 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2189 m = vm_page_alloc_freelist_domain(domain, freelist, req);
2192 } while (vm_domainset_iter_page(&di, &domain, &req) == 0);
2198 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2200 struct vm_domain *vmd;
2205 vmd = VM_DOMAIN(domain);
2207 if (vm_domain_allocate(vmd, req, 1)) {
2208 vm_domain_free_lock(vmd);
2209 m = vm_phys_alloc_freelist_pages(domain, freelist,
2210 VM_FREEPOOL_DIRECT, 0);
2211 vm_domain_free_unlock(vmd);
2213 vm_domain_freecnt_inc(vmd, 1);
2216 if (vm_domain_alloc_fail(vmd, NULL, req))
2221 vm_page_alloc_check(m);
2224 * Initialize the page. Only the PG_ZERO flag is inherited.
2228 if ((req & VM_ALLOC_ZERO) != 0)
2231 if ((req & VM_ALLOC_WIRED) != 0) {
2233 * The page lock is not required for wiring a page that does
2234 * not belong to an object.
2239 /* Unmanaged pages don't use "act_count". */
2240 m->oflags = VPO_UNMANAGED;
2245 vm_page_import(void *arg, void **store, int cnt, int domain, int flags)
2247 struct vm_domain *vmd;
2251 /* Only import if we can bring in a full bucket. */
2252 if (cnt == 1 || !vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2254 domain = vmd->vmd_domain;
2255 vm_domain_free_lock(vmd);
2256 i = vm_phys_alloc_npages(domain, VM_FREEPOOL_DEFAULT, cnt,
2257 (vm_page_t *)store);
2258 vm_domain_free_unlock(vmd);
2260 vm_domain_freecnt_inc(vmd, cnt - i);
2266 vm_page_release(void *arg, void **store, int cnt)
2268 struct vm_domain *vmd;
2273 vm_domain_free_lock(vmd);
2274 for (i = 0; i < cnt; i++) {
2275 m = (vm_page_t)store[i];
2276 vm_phys_free_pages(m, 0);
2278 vm_domain_free_unlock(vmd);
2279 vm_domain_freecnt_inc(vmd, cnt);
2282 #define VPSC_ANY 0 /* No restrictions. */
2283 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2284 #define VPSC_NOSUPER 2 /* Skip superpages. */
2287 * vm_page_scan_contig:
2289 * Scan vm_page_array[] between the specified entries "m_start" and
2290 * "m_end" for a run of contiguous physical pages that satisfy the
2291 * specified conditions, and return the lowest page in the run. The
2292 * specified "alignment" determines the alignment of the lowest physical
2293 * page in the run. If the specified "boundary" is non-zero, then the
2294 * run of physical pages cannot span a physical address that is a
2295 * multiple of "boundary".
2297 * "m_end" is never dereferenced, so it need not point to a vm_page
2298 * structure within vm_page_array[].
2300 * "npages" must be greater than zero. "m_start" and "m_end" must not
2301 * span a hole (or discontiguity) in the physical address space. Both
2302 * "alignment" and "boundary" must be a power of two.
2305 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2306 u_long alignment, vm_paddr_t boundary, int options)
2312 #if VM_NRESERVLEVEL > 0
2315 int m_inc, order, run_ext, run_len;
2317 KASSERT(npages > 0, ("npages is 0"));
2318 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2319 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2323 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2324 KASSERT((m->flags & PG_MARKER) == 0,
2325 ("page %p is PG_MARKER", m));
2326 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->wire_count == 1,
2327 ("fictitious page %p has invalid wire count", m));
2330 * If the current page would be the start of a run, check its
2331 * physical address against the end, alignment, and boundary
2332 * conditions. If it doesn't satisfy these conditions, either
2333 * terminate the scan or advance to the next page that
2334 * satisfies the failed condition.
2337 KASSERT(m_run == NULL, ("m_run != NULL"));
2338 if (m + npages > m_end)
2340 pa = VM_PAGE_TO_PHYS(m);
2341 if ((pa & (alignment - 1)) != 0) {
2342 m_inc = atop(roundup2(pa, alignment) - pa);
2345 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2347 m_inc = atop(roundup2(pa, boundary) - pa);
2351 KASSERT(m_run != NULL, ("m_run == NULL"));
2353 vm_page_change_lock(m, &m_mtx);
2356 if (vm_page_held(m))
2358 #if VM_NRESERVLEVEL > 0
2359 else if ((level = vm_reserv_level(m)) >= 0 &&
2360 (options & VPSC_NORESERV) != 0) {
2362 /* Advance to the end of the reservation. */
2363 pa = VM_PAGE_TO_PHYS(m);
2364 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2368 else if ((object = m->object) != NULL) {
2370 * The page is considered eligible for relocation if
2371 * and only if it could be laundered or reclaimed by
2374 if (!VM_OBJECT_TRYRLOCK(object)) {
2376 VM_OBJECT_RLOCK(object);
2378 if (m->object != object) {
2380 * The page may have been freed.
2382 VM_OBJECT_RUNLOCK(object);
2384 } else if (vm_page_held(m)) {
2389 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2390 ("page %p is PG_UNHOLDFREE", m));
2391 /* Don't care: PG_NODUMP, PG_ZERO. */
2392 if (object->type != OBJT_DEFAULT &&
2393 object->type != OBJT_SWAP &&
2394 object->type != OBJT_VNODE) {
2396 #if VM_NRESERVLEVEL > 0
2397 } else if ((options & VPSC_NOSUPER) != 0 &&
2398 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2400 /* Advance to the end of the superpage. */
2401 pa = VM_PAGE_TO_PHYS(m);
2402 m_inc = atop(roundup2(pa + 1,
2403 vm_reserv_size(level)) - pa);
2405 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2406 vm_page_queue(m) != PQ_NONE && !vm_page_busied(m)) {
2408 * The page is allocated but eligible for
2409 * relocation. Extend the current run by one
2412 KASSERT(pmap_page_get_memattr(m) ==
2414 ("page %p has an unexpected memattr", m));
2415 KASSERT((m->oflags & (VPO_SWAPINPROG |
2416 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2417 ("page %p has unexpected oflags", m));
2418 /* Don't care: VPO_NOSYNC. */
2423 VM_OBJECT_RUNLOCK(object);
2424 #if VM_NRESERVLEVEL > 0
2425 } else if (level >= 0) {
2427 * The page is reserved but not yet allocated. In
2428 * other words, it is still free. Extend the current
2433 } else if ((order = m->order) < VM_NFREEORDER) {
2435 * The page is enqueued in the physical memory
2436 * allocator's free page queues. Moreover, it is the
2437 * first page in a power-of-two-sized run of
2438 * contiguous free pages. Add these pages to the end
2439 * of the current run, and jump ahead.
2441 run_ext = 1 << order;
2445 * Skip the page for one of the following reasons: (1)
2446 * It is enqueued in the physical memory allocator's
2447 * free page queues. However, it is not the first
2448 * page in a run of contiguous free pages. (This case
2449 * rarely occurs because the scan is performed in
2450 * ascending order.) (2) It is not reserved, and it is
2451 * transitioning from free to allocated. (Conversely,
2452 * the transition from allocated to free for managed
2453 * pages is blocked by the page lock.) (3) It is
2454 * allocated but not contained by an object and not
2455 * wired, e.g., allocated by Xen's balloon driver.
2461 * Extend or reset the current run of pages.
2476 if (run_len >= npages)
2482 * vm_page_reclaim_run:
2484 * Try to relocate each of the allocated virtual pages within the
2485 * specified run of physical pages to a new physical address. Free the
2486 * physical pages underlying the relocated virtual pages. A virtual page
2487 * is relocatable if and only if it could be laundered or reclaimed by
2488 * the page daemon. Whenever possible, a virtual page is relocated to a
2489 * physical address above "high".
2491 * Returns 0 if every physical page within the run was already free or
2492 * just freed by a successful relocation. Otherwise, returns a non-zero
2493 * value indicating why the last attempt to relocate a virtual page was
2496 * "req_class" must be an allocation class.
2499 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2502 struct vm_domain *vmd;
2504 struct spglist free;
2507 vm_page_t m, m_end, m_new;
2508 int error, order, req;
2510 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2511 ("req_class is not an allocation class"));
2515 m_end = m_run + npages;
2517 for (; error == 0 && m < m_end; m++) {
2518 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2519 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2522 * Avoid releasing and reacquiring the same page lock.
2524 vm_page_change_lock(m, &m_mtx);
2526 if (vm_page_held(m))
2528 else if ((object = m->object) != NULL) {
2530 * The page is relocated if and only if it could be
2531 * laundered or reclaimed by the page daemon.
2533 if (!VM_OBJECT_TRYWLOCK(object)) {
2535 VM_OBJECT_WLOCK(object);
2537 if (m->object != object) {
2539 * The page may have been freed.
2541 VM_OBJECT_WUNLOCK(object);
2543 } else if (vm_page_held(m)) {
2548 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2549 ("page %p is PG_UNHOLDFREE", m));
2550 /* Don't care: PG_NODUMP, PG_ZERO. */
2551 if (object->type != OBJT_DEFAULT &&
2552 object->type != OBJT_SWAP &&
2553 object->type != OBJT_VNODE)
2555 else if (object->memattr != VM_MEMATTR_DEFAULT)
2557 else if (vm_page_queue(m) != PQ_NONE &&
2558 !vm_page_busied(m)) {
2559 KASSERT(pmap_page_get_memattr(m) ==
2561 ("page %p has an unexpected memattr", m));
2562 KASSERT((m->oflags & (VPO_SWAPINPROG |
2563 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2564 ("page %p has unexpected oflags", m));
2565 /* Don't care: VPO_NOSYNC. */
2566 if (m->valid != 0) {
2568 * First, try to allocate a new page
2569 * that is above "high". Failing
2570 * that, try to allocate a new page
2571 * that is below "m_run". Allocate
2572 * the new page between the end of
2573 * "m_run" and "high" only as a last
2576 req = req_class | VM_ALLOC_NOOBJ;
2577 if ((m->flags & PG_NODUMP) != 0)
2578 req |= VM_ALLOC_NODUMP;
2579 if (trunc_page(high) !=
2580 ~(vm_paddr_t)PAGE_MASK) {
2581 m_new = vm_page_alloc_contig(
2586 VM_MEMATTR_DEFAULT);
2589 if (m_new == NULL) {
2590 pa = VM_PAGE_TO_PHYS(m_run);
2591 m_new = vm_page_alloc_contig(
2593 0, pa - 1, PAGE_SIZE, 0,
2594 VM_MEMATTR_DEFAULT);
2596 if (m_new == NULL) {
2598 m_new = vm_page_alloc_contig(
2600 pa, high, PAGE_SIZE, 0,
2601 VM_MEMATTR_DEFAULT);
2603 if (m_new == NULL) {
2607 KASSERT(m_new->wire_count == 0,
2608 ("page %p is wired", m_new));
2611 * Replace "m" with the new page. For
2612 * vm_page_replace(), "m" must be busy
2613 * and dequeued. Finally, change "m"
2614 * as if vm_page_free() was called.
2616 if (object->ref_count != 0)
2618 m_new->aflags = m->aflags &
2619 ~PGA_QUEUE_STATE_MASK;
2620 KASSERT(m_new->oflags == VPO_UNMANAGED,
2621 ("page %p is managed", m_new));
2622 m_new->oflags = m->oflags & VPO_NOSYNC;
2623 pmap_copy_page(m, m_new);
2624 m_new->valid = m->valid;
2625 m_new->dirty = m->dirty;
2626 m->flags &= ~PG_ZERO;
2629 vm_page_replace_checked(m_new, object,
2631 if (vm_page_free_prep(m))
2632 SLIST_INSERT_HEAD(&free, m,
2636 * The new page must be deactivated
2637 * before the object is unlocked.
2639 vm_page_change_lock(m_new, &m_mtx);
2640 vm_page_deactivate(m_new);
2642 m->flags &= ~PG_ZERO;
2645 if (vm_page_free_prep(m))
2646 SLIST_INSERT_HEAD(&free, m,
2648 KASSERT(m->dirty == 0,
2649 ("page %p is dirty", m));
2654 VM_OBJECT_WUNLOCK(object);
2656 MPASS(vm_phys_domain(m) == domain);
2657 vmd = VM_DOMAIN(domain);
2658 vm_domain_free_lock(vmd);
2660 if (order < VM_NFREEORDER) {
2662 * The page is enqueued in the physical memory
2663 * allocator's free page queues. Moreover, it
2664 * is the first page in a power-of-two-sized
2665 * run of contiguous free pages. Jump ahead
2666 * to the last page within that run, and
2667 * continue from there.
2669 m += (1 << order) - 1;
2671 #if VM_NRESERVLEVEL > 0
2672 else if (vm_reserv_is_page_free(m))
2675 vm_domain_free_unlock(vmd);
2676 if (order == VM_NFREEORDER)
2682 if ((m = SLIST_FIRST(&free)) != NULL) {
2685 vmd = VM_DOMAIN(domain);
2687 vm_domain_free_lock(vmd);
2689 MPASS(vm_phys_domain(m) == domain);
2690 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2691 vm_phys_free_pages(m, 0);
2693 } while ((m = SLIST_FIRST(&free)) != NULL);
2694 vm_domain_free_unlock(vmd);
2695 vm_domain_freecnt_inc(vmd, cnt);
2702 CTASSERT(powerof2(NRUNS));
2704 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2706 #define MIN_RECLAIM 8
2709 * vm_page_reclaim_contig:
2711 * Reclaim allocated, contiguous physical memory satisfying the specified
2712 * conditions by relocating the virtual pages using that physical memory.
2713 * Returns true if reclamation is successful and false otherwise. Since
2714 * relocation requires the allocation of physical pages, reclamation may
2715 * fail due to a shortage of free pages. When reclamation fails, callers
2716 * are expected to perform vm_wait() before retrying a failed allocation
2717 * operation, e.g., vm_page_alloc_contig().
2719 * The caller must always specify an allocation class through "req".
2721 * allocation classes:
2722 * VM_ALLOC_NORMAL normal process request
2723 * VM_ALLOC_SYSTEM system *really* needs a page
2724 * VM_ALLOC_INTERRUPT interrupt time request
2726 * The optional allocation flags are ignored.
2728 * "npages" must be greater than zero. Both "alignment" and "boundary"
2729 * must be a power of two.
2732 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
2733 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2735 struct vm_domain *vmd;
2736 vm_paddr_t curr_low;
2737 vm_page_t m_run, m_runs[NRUNS];
2738 u_long count, reclaimed;
2739 int error, i, options, req_class;
2741 KASSERT(npages > 0, ("npages is 0"));
2742 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2743 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2744 req_class = req & VM_ALLOC_CLASS_MASK;
2747 * The page daemon is allowed to dig deeper into the free page list.
2749 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2750 req_class = VM_ALLOC_SYSTEM;
2753 * Return if the number of free pages cannot satisfy the requested
2756 vmd = VM_DOMAIN(domain);
2757 count = vmd->vmd_free_count;
2758 if (count < npages + vmd->vmd_free_reserved || (count < npages +
2759 vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2760 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2764 * Scan up to three times, relaxing the restrictions ("options") on
2765 * the reclamation of reservations and superpages each time.
2767 for (options = VPSC_NORESERV;;) {
2769 * Find the highest runs that satisfy the given constraints
2770 * and restrictions, and record them in "m_runs".
2775 m_run = vm_phys_scan_contig(domain, npages, curr_low,
2776 high, alignment, boundary, options);
2779 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2780 m_runs[RUN_INDEX(count)] = m_run;
2785 * Reclaim the highest runs in LIFO (descending) order until
2786 * the number of reclaimed pages, "reclaimed", is at least
2787 * MIN_RECLAIM. Reset "reclaimed" each time because each
2788 * reclamation is idempotent, and runs will (likely) recur
2789 * from one scan to the next as restrictions are relaxed.
2792 for (i = 0; count > 0 && i < NRUNS; i++) {
2794 m_run = m_runs[RUN_INDEX(count)];
2795 error = vm_page_reclaim_run(req_class, domain, npages,
2798 reclaimed += npages;
2799 if (reclaimed >= MIN_RECLAIM)
2805 * Either relax the restrictions on the next scan or return if
2806 * the last scan had no restrictions.
2808 if (options == VPSC_NORESERV)
2809 options = VPSC_NOSUPER;
2810 else if (options == VPSC_NOSUPER)
2812 else if (options == VPSC_ANY)
2813 return (reclaimed != 0);
2818 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2819 u_long alignment, vm_paddr_t boundary)
2821 struct vm_domainset_iter di;
2825 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2827 ret = vm_page_reclaim_contig_domain(domain, req, npages, low,
2828 high, alignment, boundary);
2831 } while (vm_domainset_iter_page(&di, &domain, &req) == 0);
2837 * Set the domain in the appropriate page level domainset.
2840 vm_domain_set(struct vm_domain *vmd)
2843 mtx_lock(&vm_domainset_lock);
2844 if (!vmd->vmd_minset && vm_paging_min(vmd)) {
2845 vmd->vmd_minset = 1;
2846 DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
2848 if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
2849 vmd->vmd_severeset = 1;
2850 DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
2852 mtx_unlock(&vm_domainset_lock);
2856 * Clear the domain from the appropriate page level domainset.
2859 vm_domain_clear(struct vm_domain *vmd)
2862 mtx_lock(&vm_domainset_lock);
2863 if (vmd->vmd_minset && !vm_paging_min(vmd)) {
2864 vmd->vmd_minset = 0;
2865 DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
2866 if (vm_min_waiters != 0) {
2868 wakeup(&vm_min_domains);
2871 if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
2872 vmd->vmd_severeset = 0;
2873 DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
2874 if (vm_severe_waiters != 0) {
2875 vm_severe_waiters = 0;
2876 wakeup(&vm_severe_domains);
2881 * If pageout daemon needs pages, then tell it that there are
2884 if (vmd->vmd_pageout_pages_needed &&
2885 vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
2886 wakeup(&vmd->vmd_pageout_pages_needed);
2887 vmd->vmd_pageout_pages_needed = 0;
2890 /* See comments in vm_wait_doms(). */
2891 if (vm_pageproc_waiters) {
2892 vm_pageproc_waiters = 0;
2893 wakeup(&vm_pageproc_waiters);
2895 mtx_unlock(&vm_domainset_lock);
2899 * Wait for free pages to exceed the min threshold globally.
2905 mtx_lock(&vm_domainset_lock);
2906 while (vm_page_count_min()) {
2908 msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
2910 mtx_unlock(&vm_domainset_lock);
2914 * Wait for free pages to exceed the severe threshold globally.
2917 vm_wait_severe(void)
2920 mtx_lock(&vm_domainset_lock);
2921 while (vm_page_count_severe()) {
2922 vm_severe_waiters++;
2923 msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
2926 mtx_unlock(&vm_domainset_lock);
2933 return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
2937 vm_wait_doms(const domainset_t *wdoms)
2941 * We use racey wakeup synchronization to avoid expensive global
2942 * locking for the pageproc when sleeping with a non-specific vm_wait.
2943 * To handle this, we only sleep for one tick in this instance. It
2944 * is expected that most allocations for the pageproc will come from
2945 * kmem or vm_page_grab* which will use the more specific and
2946 * race-free vm_wait_domain().
2948 if (curproc == pageproc) {
2949 mtx_lock(&vm_domainset_lock);
2950 vm_pageproc_waiters++;
2951 msleep(&vm_pageproc_waiters, &vm_domainset_lock, PVM | PDROP,
2955 * XXX Ideally we would wait only until the allocation could
2956 * be satisfied. This condition can cause new allocators to
2957 * consume all freed pages while old allocators wait.
2959 mtx_lock(&vm_domainset_lock);
2960 if (DOMAINSET_SUBSET(&vm_min_domains, wdoms)) {
2962 msleep(&vm_min_domains, &vm_domainset_lock, PVM,
2965 mtx_unlock(&vm_domainset_lock);
2972 * Sleep until free pages are available for allocation.
2973 * - Called in various places after failed memory allocations.
2976 vm_wait_domain(int domain)
2978 struct vm_domain *vmd;
2981 vmd = VM_DOMAIN(domain);
2982 vm_domain_free_assert_unlocked(vmd);
2984 if (curproc == pageproc) {
2985 mtx_lock(&vm_domainset_lock);
2986 if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
2987 vmd->vmd_pageout_pages_needed = 1;
2988 msleep(&vmd->vmd_pageout_pages_needed,
2989 &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
2991 mtx_unlock(&vm_domainset_lock);
2993 if (pageproc == NULL)
2994 panic("vm_wait in early boot");
2995 DOMAINSET_ZERO(&wdom);
2996 DOMAINSET_SET(vmd->vmd_domain, &wdom);
2997 vm_wait_doms(&wdom);
3004 * Sleep until free pages are available for allocation in the
3005 * affinity domains of the obj. If obj is NULL, the domain set
3006 * for the calling thread is used.
3007 * Called in various places after failed memory allocations.
3010 vm_wait(vm_object_t obj)
3012 struct domainset *d;
3017 * Carefully fetch pointers only once: the struct domainset
3018 * itself is ummutable but the pointer might change.
3021 d = obj->domain.dr_policy;
3023 d = curthread->td_domain.dr_policy;
3025 vm_wait_doms(&d->ds_mask);
3029 * vm_domain_alloc_fail:
3031 * Called when a page allocation function fails. Informs the
3032 * pagedaemon and performs the requested wait. Requires the
3033 * domain_free and object lock on entry. Returns with the
3034 * object lock held and free lock released. Returns an error when
3035 * retry is necessary.
3039 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3042 vm_domain_free_assert_unlocked(vmd);
3044 atomic_add_int(&vmd->vmd_pageout_deficit,
3045 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3046 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3048 VM_OBJECT_WUNLOCK(object);
3049 vm_wait_domain(vmd->vmd_domain);
3051 VM_OBJECT_WLOCK(object);
3052 if (req & VM_ALLOC_WAITOK)
3062 * Sleep until free pages are available for allocation.
3063 * - Called only in vm_fault so that processes page faulting
3064 * can be easily tracked.
3065 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3066 * processes will be able to grab memory first. Do not change
3067 * this balance without careful testing first.
3073 mtx_lock(&vm_domainset_lock);
3074 if (vm_page_count_min()) {
3076 msleep(&vm_min_domains, &vm_domainset_lock, PUSER, "pfault", 0);
3078 mtx_unlock(&vm_domainset_lock);
3081 struct vm_pagequeue *
3082 vm_page_pagequeue(vm_page_t m)
3085 return (&vm_pagequeue_domain(m)->vmd_pagequeues[m->queue]);
3089 vm_page_pagequeue_lockptr(vm_page_t m)
3093 if ((queue = m->queue) == PQ_NONE)
3095 return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue].pq_mutex);
3099 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m)
3101 struct vm_domain *vmd;
3104 vm_pagequeue_assert_locked(pq);
3105 KASSERT(pq == vm_page_pagequeue(m),
3106 ("page %p doesn't belong to %p", m, pq));
3109 if ((aflags & PGA_DEQUEUE) != 0) {
3110 if (__predict_true((aflags & PGA_ENQUEUED) != 0)) {
3111 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3112 vm_pagequeue_cnt_dec(pq);
3114 vm_page_dequeue_complete(m);
3115 } else if ((aflags & (PGA_REQUEUE | PGA_REQUEUE_HEAD)) != 0) {
3116 if ((aflags & PGA_ENQUEUED) != 0)
3117 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3119 vm_pagequeue_cnt_inc(pq);
3120 vm_page_aflag_set(m, PGA_ENQUEUED);
3122 if ((aflags & PGA_REQUEUE_HEAD) != 0) {
3123 KASSERT(m->queue == PQ_INACTIVE,
3124 ("head enqueue not supported for page %p", m));
3125 vmd = vm_pagequeue_domain(m);
3126 TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3128 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3131 * PGA_REQUEUE and PGA_REQUEUE_HEAD must be cleared after
3132 * setting PGA_ENQUEUED in order to synchronize with the
3135 vm_page_aflag_clear(m, PGA_REQUEUE | PGA_REQUEUE_HEAD);
3140 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3146 for (i = 0; i < bq->bq_cnt; i++) {
3148 if (__predict_false(m->queue != queue))
3150 vm_pqbatch_process_page(pq, m);
3152 vm_batchqueue_init(bq);
3156 vm_pqbatch_submit_page(vm_page_t m, uint8_t queue)
3158 struct vm_batchqueue *bq;
3159 struct vm_pagequeue *pq;
3162 vm_page_assert_locked(m);
3163 KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3165 domain = vm_phys_domain(m);
3166 pq = &vm_pagequeue_domain(m)->vmd_pagequeues[queue];
3169 bq = DPCPU_PTR(pqbatch[domain][queue]);
3170 if (vm_batchqueue_insert(bq, m)) {
3174 if (!vm_pagequeue_trylock(pq)) {
3176 vm_pagequeue_lock(pq);
3178 bq = DPCPU_PTR(pqbatch[domain][queue]);
3180 vm_pqbatch_process(pq, bq, queue);
3183 * The page may have been logically dequeued before we acquired the
3184 * page queue lock. In this case, the page lock prevents the page
3185 * from being logically enqueued elsewhere.
3187 if (__predict_true(m->queue == queue))
3188 vm_pqbatch_process_page(pq, m);
3190 KASSERT(m->queue == PQ_NONE,
3191 ("invalid queue transition for page %p", m));
3192 KASSERT((m->aflags & PGA_ENQUEUED) == 0,
3193 ("page %p is enqueued with invalid queue index", m));
3194 vm_page_aflag_clear(m, PGA_QUEUE_STATE_MASK);
3196 vm_pagequeue_unlock(pq);
3201 * vm_page_drain_pqbatch: [ internal use only ]
3203 * Force all per-CPU page queue batch queues to be drained. This is
3204 * intended for use in severe memory shortages, to ensure that pages
3205 * do not remain stuck in the batch queues.
3208 vm_page_drain_pqbatch(void)
3211 struct vm_domain *vmd;
3212 struct vm_pagequeue *pq;
3213 int cpu, domain, queue;
3218 sched_bind(td, cpu);
3221 for (domain = 0; domain < vm_ndomains; domain++) {
3222 vmd = VM_DOMAIN(domain);
3223 for (queue = 0; queue < PQ_COUNT; queue++) {
3224 pq = &vmd->vmd_pagequeues[queue];
3225 vm_pagequeue_lock(pq);
3227 vm_pqbatch_process(pq,
3228 DPCPU_PTR(pqbatch[domain][queue]), queue);
3230 vm_pagequeue_unlock(pq);
3240 * Complete the logical removal of a page from a page queue. We must be
3241 * careful to synchronize with the page daemon, which may be concurrently
3242 * examining the page with only the page lock held. The page must not be
3243 * in a state where it appears to be logically enqueued.
3246 vm_page_dequeue_complete(vm_page_t m)
3250 atomic_thread_fence_rel();
3251 vm_page_aflag_clear(m, PGA_QUEUE_STATE_MASK);
3255 * vm_page_dequeue_deferred: [ internal use only ]
3257 * Request removal of the given page from its current page
3258 * queue. Physical removal from the queue may be deferred
3261 * The page must be locked.
3264 vm_page_dequeue_deferred(vm_page_t m)
3268 vm_page_assert_locked(m);
3271 if (queue == PQ_NONE) {
3272 KASSERT((m->aflags & PGA_QUEUE_STATE_MASK) == 0,
3273 ("page %p has queue state", m));
3276 if ((m->aflags & PGA_DEQUEUE) == 0)
3277 vm_page_aflag_set(m, PGA_DEQUEUE);
3278 vm_pqbatch_submit_page(m, queue);
3282 * vm_page_dequeue_locked:
3284 * Remove the page from its page queue, which must be locked.
3285 * If the page lock is not held, there is no guarantee that the
3286 * page will not be enqueued by another thread before this function
3287 * returns. In this case, it is up to the caller to ensure that
3288 * no other threads hold a reference to the page.
3290 * The page queue lock must be held. If the page is not already
3291 * logically dequeued, the page lock must be held as well.
3294 vm_page_dequeue_locked(vm_page_t m)
3296 struct vm_pagequeue *pq;
3298 pq = vm_page_pagequeue(m);
3300 KASSERT(m->queue != PQ_NONE,
3301 ("%s: page %p queue field is PQ_NONE", __func__, m));
3302 vm_pagequeue_assert_locked(pq);
3303 KASSERT((m->aflags & PGA_DEQUEUE) != 0 ||
3304 mtx_owned(vm_page_lockptr(m)),
3305 ("%s: queued unlocked page %p", __func__, m));
3307 if ((m->aflags & PGA_ENQUEUED) != 0) {
3308 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3309 vm_pagequeue_cnt_dec(pq);
3311 vm_page_dequeue_complete(m);
3317 * Remove the page from whichever page queue it's in, if any.
3318 * If the page lock is not held, there is no guarantee that the
3319 * page will not be enqueued by another thread before this function
3320 * returns. In this case, it is up to the caller to ensure that
3321 * no other threads hold a reference to the page.
3324 vm_page_dequeue(vm_page_t m)
3326 struct mtx *lock, *lock1;
3328 lock = vm_page_pagequeue_lockptr(m);
3333 if ((lock1 = vm_page_pagequeue_lockptr(m)) == lock)
3338 KASSERT(lock == vm_page_pagequeue_lockptr(m),
3339 ("%s: page %p migrated directly between queues", __func__, m));
3340 vm_page_dequeue_locked(m);
3345 * Schedule the given page for insertion into the specified page queue.
3346 * Physical insertion of the page may be deferred indefinitely.
3349 vm_page_enqueue(vm_page_t m, uint8_t queue)
3352 vm_page_assert_locked(m);
3353 KASSERT(m->queue == PQ_NONE && (m->aflags & PGA_QUEUE_STATE_MASK) == 0,
3354 ("%s: page %p is already enqueued", __func__, m));
3357 if ((m->aflags & PGA_REQUEUE) == 0)
3358 vm_page_aflag_set(m, PGA_REQUEUE);
3359 vm_pqbatch_submit_page(m, queue);
3363 * vm_page_requeue: [ internal use only ]
3365 * Schedule a requeue of the given page.
3367 * The page must be locked.
3370 vm_page_requeue(vm_page_t m)
3373 vm_page_assert_locked(m);
3374 KASSERT(m->queue != PQ_NONE,
3375 ("%s: page %p is not logically enqueued", __func__, m));
3377 if ((m->aflags & PGA_REQUEUE) == 0)
3378 vm_page_aflag_set(m, PGA_REQUEUE);
3379 vm_pqbatch_submit_page(m, m->queue);
3385 * Put the specified page on the active list (if appropriate).
3386 * Ensure that act_count is at least ACT_INIT but do not otherwise
3389 * The page must be locked.
3392 vm_page_activate(vm_page_t m)
3396 vm_page_assert_locked(m);
3398 if ((queue = vm_page_queue(m)) == PQ_ACTIVE || m->wire_count > 0 ||
3399 (m->oflags & VPO_UNMANAGED) != 0) {
3400 if (queue == PQ_ACTIVE && m->act_count < ACT_INIT)
3401 m->act_count = ACT_INIT;
3406 if (m->act_count < ACT_INIT)
3407 m->act_count = ACT_INIT;
3408 vm_page_enqueue(m, PQ_ACTIVE);
3412 * vm_page_free_prep:
3414 * Prepares the given page to be put on the free list,
3415 * disassociating it from any VM object. The caller may return
3416 * the page to the free list only if this function returns true.
3418 * The object must be locked. The page must be locked if it is
3422 vm_page_free_prep(vm_page_t m)
3425 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
3426 if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
3429 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3430 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
3431 KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
3432 m, i, (uintmax_t)*p));
3435 if ((m->oflags & VPO_UNMANAGED) == 0) {
3436 vm_page_lock_assert(m, MA_OWNED);
3437 KASSERT(!pmap_page_is_mapped(m),
3438 ("vm_page_free_prep: freeing mapped page %p", m));
3440 KASSERT(m->queue == PQ_NONE,
3441 ("vm_page_free_prep: unmanaged page %p is queued", m));
3442 VM_CNT_INC(v_tfree);
3444 if (vm_page_sbusied(m))
3445 panic("vm_page_free_prep: freeing busy page %p", m);
3450 * If fictitious remove object association and
3453 if ((m->flags & PG_FICTITIOUS) != 0) {
3454 KASSERT(m->wire_count == 1,
3455 ("fictitious page %p is not wired", m));
3456 KASSERT(m->queue == PQ_NONE,
3457 ("fictitious page %p is queued", m));
3462 * Pages need not be dequeued before they are returned to the physical
3463 * memory allocator, but they must at least be marked for a deferred
3466 if ((m->oflags & VPO_UNMANAGED) == 0)
3467 vm_page_dequeue_deferred(m);
3472 if (m->wire_count != 0)
3473 panic("vm_page_free_prep: freeing wired page %p", m);
3474 if (m->hold_count != 0) {
3475 m->flags &= ~PG_ZERO;
3476 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
3477 ("vm_page_free_prep: freeing PG_UNHOLDFREE page %p", m));
3478 m->flags |= PG_UNHOLDFREE;
3483 * Restore the default memory attribute to the page.
3485 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3486 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3488 #if VM_NRESERVLEVEL > 0
3489 if (vm_reserv_free_page(m))
3499 * Returns the given page to the free list, disassociating it
3500 * from any VM object.
3502 * The object must be locked. The page must be locked if it is
3506 vm_page_free_toq(vm_page_t m)
3508 struct vm_domain *vmd;
3510 if (!vm_page_free_prep(m))
3513 vmd = vm_pagequeue_domain(m);
3514 if (m->pool == VM_FREEPOOL_DEFAULT && vmd->vmd_pgcache != NULL) {
3515 uma_zfree(vmd->vmd_pgcache, m);
3518 vm_domain_free_lock(vmd);
3519 vm_phys_free_pages(m, 0);
3520 vm_domain_free_unlock(vmd);
3521 vm_domain_freecnt_inc(vmd, 1);
3525 * vm_page_free_pages_toq:
3527 * Returns a list of pages to the free list, disassociating it
3528 * from any VM object. In other words, this is equivalent to
3529 * calling vm_page_free_toq() for each page of a list of VM objects.
3531 * The objects must be locked. The pages must be locked if it is
3535 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
3540 if (SLIST_EMPTY(free))
3544 while ((m = SLIST_FIRST(free)) != NULL) {
3546 SLIST_REMOVE_HEAD(free, plinks.s.ss);
3547 vm_page_free_toq(m);
3550 if (update_wire_count)
3557 * Mark this page as wired down. If the page is fictitious, then
3558 * its wire count must remain one.
3560 * The page must be locked.
3563 vm_page_wire(vm_page_t m)
3566 vm_page_assert_locked(m);
3567 if ((m->flags & PG_FICTITIOUS) != 0) {
3568 KASSERT(m->wire_count == 1,
3569 ("vm_page_wire: fictitious page %p's wire count isn't one",
3573 if (m->wire_count == 0) {
3574 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
3575 m->queue == PQ_NONE,
3576 ("vm_page_wire: unmanaged page %p is queued", m));
3580 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
3586 * Release one wiring of the specified page, potentially allowing it to be
3587 * paged out. Returns TRUE if the number of wirings transitions to zero and
3590 * Only managed pages belonging to an object can be paged out. If the number
3591 * of wirings transitions to zero and the page is eligible for page out, then
3592 * the page is added to the specified paging queue (unless PQ_NONE is
3593 * specified, in which case the page is dequeued if it belongs to a paging
3596 * If a page is fictitious, then its wire count must always be one.
3598 * A managed page must be locked.
3601 vm_page_unwire(vm_page_t m, uint8_t queue)
3605 KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
3606 ("vm_page_unwire: invalid queue %u request for page %p",
3608 if ((m->oflags & VPO_UNMANAGED) == 0)
3609 vm_page_assert_locked(m);
3611 unwired = vm_page_unwire_noq(m);
3612 if (!unwired || (m->oflags & VPO_UNMANAGED) != 0 || m->object == NULL)
3615 if (vm_page_queue(m) == queue) {
3616 if (queue == PQ_ACTIVE)
3617 vm_page_reference(m);
3618 else if (queue != PQ_NONE)
3622 if (queue != PQ_NONE) {
3623 vm_page_enqueue(m, queue);
3624 if (queue == PQ_ACTIVE)
3625 /* Initialize act_count. */
3626 vm_page_activate(m);
3634 * vm_page_unwire_noq:
3636 * Unwire a page without (re-)inserting it into a page queue. It is up
3637 * to the caller to enqueue, requeue, or free the page as appropriate.
3638 * In most cases, vm_page_unwire() should be used instead.
3641 vm_page_unwire_noq(vm_page_t m)
3644 if ((m->oflags & VPO_UNMANAGED) == 0)
3645 vm_page_assert_locked(m);
3646 if ((m->flags & PG_FICTITIOUS) != 0) {
3647 KASSERT(m->wire_count == 1,
3648 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
3651 if (m->wire_count == 0)
3652 panic("vm_page_unwire: page %p's wire count is zero", m);
3654 if (m->wire_count == 0) {
3662 * Move the specified page to the tail of the inactive queue, or requeue
3663 * the page if it is already in the inactive queue.
3665 * The page must be locked.
3668 vm_page_deactivate(vm_page_t m)
3671 vm_page_assert_locked(m);
3673 if (m->wire_count > 0 || (m->oflags & VPO_UNMANAGED) != 0)
3676 if (!vm_page_inactive(m)) {
3678 vm_page_enqueue(m, PQ_INACTIVE);
3684 * Move the specified page close to the head of the inactive queue,
3685 * bypassing LRU. A marker page is used to maintain FIFO ordering.
3686 * As with regular enqueues, we use a per-CPU batch queue to reduce
3687 * contention on the page queue lock.
3689 * The page must be locked.
3692 vm_page_deactivate_noreuse(vm_page_t m)
3695 vm_page_assert_locked(m);
3697 if (m->wire_count > 0 || (m->oflags & VPO_UNMANAGED) != 0)
3700 if (!vm_page_inactive(m))
3702 m->queue = PQ_INACTIVE;
3703 if ((m->aflags & PGA_REQUEUE_HEAD) == 0)
3704 vm_page_aflag_set(m, PGA_REQUEUE_HEAD);
3705 vm_pqbatch_submit_page(m, PQ_INACTIVE);
3711 * Put a page in the laundry, or requeue it if it is already there.
3714 vm_page_launder(vm_page_t m)
3717 vm_page_assert_locked(m);
3718 if (m->wire_count > 0 || (m->oflags & VPO_UNMANAGED) != 0)
3721 if (vm_page_in_laundry(m))
3725 vm_page_enqueue(m, PQ_LAUNDRY);
3730 * vm_page_unswappable
3732 * Put a page in the PQ_UNSWAPPABLE holding queue.
3735 vm_page_unswappable(vm_page_t m)
3738 vm_page_assert_locked(m);
3739 KASSERT(m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0,
3740 ("page %p already unswappable", m));
3743 vm_page_enqueue(m, PQ_UNSWAPPABLE);
3747 * Attempt to free the page. If it cannot be freed, do nothing. Returns true
3748 * if the page is freed and false otherwise.
3750 * The page must be managed. The page and its containing object must be
3754 vm_page_try_to_free(vm_page_t m)
3757 vm_page_assert_locked(m);
3758 VM_OBJECT_ASSERT_WLOCKED(m->object);
3759 KASSERT((m->oflags & VPO_UNMANAGED) == 0, ("page %p is unmanaged", m));
3760 if (m->dirty != 0 || vm_page_held(m) || vm_page_busied(m))
3762 if (m->object->ref_count != 0) {
3774 * Apply the specified advice to the given page.
3776 * The object and page must be locked.
3779 vm_page_advise(vm_page_t m, int advice)
3782 vm_page_assert_locked(m);
3783 VM_OBJECT_ASSERT_WLOCKED(m->object);
3784 if (advice == MADV_FREE)
3786 * Mark the page clean. This will allow the page to be freed
3787 * without first paging it out. MADV_FREE pages are often
3788 * quickly reused by malloc(3), so we do not do anything that
3789 * would result in a page fault on a later access.
3792 else if (advice != MADV_DONTNEED) {
3793 if (advice == MADV_WILLNEED)
3794 vm_page_activate(m);
3799 * Clear any references to the page. Otherwise, the page daemon will
3800 * immediately reactivate the page.
3802 vm_page_aflag_clear(m, PGA_REFERENCED);
3804 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3808 * Place clean pages near the head of the inactive queue rather than
3809 * the tail, thus defeating the queue's LRU operation and ensuring that
3810 * the page will be reused quickly. Dirty pages not already in the
3811 * laundry are moved there.
3814 vm_page_deactivate_noreuse(m);
3815 else if (!vm_page_in_laundry(m))
3820 * Grab a page, waiting until we are waken up due to the page
3821 * changing state. We keep on waiting, if the page continues
3822 * to be in the object. If the page doesn't exist, first allocate it
3823 * and then conditionally zero it.
3825 * This routine may sleep.
3827 * The object must be locked on entry. The lock will, however, be released
3828 * and reacquired if the routine sleeps.
3831 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3837 VM_OBJECT_ASSERT_WLOCKED(object);
3838 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3839 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3840 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3841 pflags = allocflags &
3842 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
3843 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3844 pflags |= VM_ALLOC_WAITFAIL;
3846 if ((m = vm_page_lookup(object, pindex)) != NULL) {
3847 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3848 vm_page_xbusied(m) : vm_page_busied(m);
3850 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3853 * Reference the page before unlocking and
3854 * sleeping so that the page daemon is less
3855 * likely to reclaim it.
3857 vm_page_aflag_set(m, PGA_REFERENCED);
3859 VM_OBJECT_WUNLOCK(object);
3860 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
3861 VM_ALLOC_IGN_SBUSY) != 0);
3862 VM_OBJECT_WLOCK(object);
3865 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3871 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3873 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3878 m = vm_page_alloc(object, pindex, pflags);
3880 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3884 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3890 * Return the specified range of pages from the given object. For each
3891 * page offset within the range, if a page already exists within the object
3892 * at that offset and it is busy, then wait for it to change state. If,
3893 * instead, the page doesn't exist, then allocate it.
3895 * The caller must always specify an allocation class.
3897 * allocation classes:
3898 * VM_ALLOC_NORMAL normal process request
3899 * VM_ALLOC_SYSTEM system *really* needs the pages
3901 * The caller must always specify that the pages are to be busied and/or
3904 * optional allocation flags:
3905 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
3906 * VM_ALLOC_NOBUSY do not exclusive busy the page
3907 * VM_ALLOC_NOWAIT do not sleep
3908 * VM_ALLOC_SBUSY set page to sbusy state
3909 * VM_ALLOC_WIRED wire the pages
3910 * VM_ALLOC_ZERO zero and validate any invalid pages
3912 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
3913 * may return a partial prefix of the requested range.
3916 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
3917 vm_page_t *ma, int count)
3924 VM_OBJECT_ASSERT_WLOCKED(object);
3925 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
3926 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
3927 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
3928 (allocflags & VM_ALLOC_WIRED) != 0,
3929 ("vm_page_grab_pages: the pages must be busied or wired"));
3930 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3931 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3932 ("vm_page_grab_pages: VM_ALLOC_SBUSY/IGN_SBUSY mismatch"));
3935 pflags = allocflags & ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK |
3936 VM_ALLOC_WAITFAIL | VM_ALLOC_IGN_SBUSY);
3937 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3938 pflags |= VM_ALLOC_WAITFAIL;
3941 m = vm_radix_lookup_le(&object->rtree, pindex + i);
3942 if (m == NULL || m->pindex != pindex + i) {
3946 mpred = TAILQ_PREV(m, pglist, listq);
3947 for (; i < count; i++) {
3949 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3950 vm_page_xbusied(m) : vm_page_busied(m);
3952 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3955 * Reference the page before unlocking and
3956 * sleeping so that the page daemon is less
3957 * likely to reclaim it.
3959 vm_page_aflag_set(m, PGA_REFERENCED);
3961 VM_OBJECT_WUNLOCK(object);
3962 vm_page_busy_sleep(m, "grbmaw", (allocflags &
3963 VM_ALLOC_IGN_SBUSY) != 0);
3964 VM_OBJECT_WLOCK(object);
3967 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3972 if ((allocflags & (VM_ALLOC_NOBUSY |
3973 VM_ALLOC_SBUSY)) == 0)
3975 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3978 m = vm_page_alloc_after(object, pindex + i,
3979 pflags | VM_ALLOC_COUNT(count - i), mpred);
3981 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3986 if (m->valid == 0 && (allocflags & VM_ALLOC_ZERO) != 0) {
3987 if ((m->flags & PG_ZERO) == 0)
3989 m->valid = VM_PAGE_BITS_ALL;
3992 m = vm_page_next(m);
3998 * Mapping function for valid or dirty bits in a page.
4000 * Inputs are required to range within a page.
4003 vm_page_bits(int base, int size)
4009 base + size <= PAGE_SIZE,
4010 ("vm_page_bits: illegal base/size %d/%d", base, size)
4013 if (size == 0) /* handle degenerate case */
4016 first_bit = base >> DEV_BSHIFT;
4017 last_bit = (base + size - 1) >> DEV_BSHIFT;
4019 return (((vm_page_bits_t)2 << last_bit) -
4020 ((vm_page_bits_t)1 << first_bit));
4024 * vm_page_set_valid_range:
4026 * Sets portions of a page valid. The arguments are expected
4027 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4028 * of any partial chunks touched by the range. The invalid portion of
4029 * such chunks will be zeroed.
4031 * (base + size) must be less then or equal to PAGE_SIZE.
4034 vm_page_set_valid_range(vm_page_t m, int base, int size)
4038 VM_OBJECT_ASSERT_WLOCKED(m->object);
4039 if (size == 0) /* handle degenerate case */
4043 * If the base is not DEV_BSIZE aligned and the valid
4044 * bit is clear, we have to zero out a portion of the
4047 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4048 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
4049 pmap_zero_page_area(m, frag, base - frag);
4052 * If the ending offset is not DEV_BSIZE aligned and the
4053 * valid bit is clear, we have to zero out a portion of
4056 endoff = base + size;
4057 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4058 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
4059 pmap_zero_page_area(m, endoff,
4060 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4063 * Assert that no previously invalid block that is now being validated
4066 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
4067 ("vm_page_set_valid_range: page %p is dirty", m));
4070 * Set valid bits inclusive of any overlap.
4072 m->valid |= vm_page_bits(base, size);
4076 * Clear the given bits from the specified page's dirty field.
4078 static __inline void
4079 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
4082 #if PAGE_SIZE < 16384
4087 * If the object is locked and the page is neither exclusive busy nor
4088 * write mapped, then the page's dirty field cannot possibly be
4089 * set by a concurrent pmap operation.
4091 VM_OBJECT_ASSERT_WLOCKED(m->object);
4092 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
4093 m->dirty &= ~pagebits;
4096 * The pmap layer can call vm_page_dirty() without
4097 * holding a distinguished lock. The combination of
4098 * the object's lock and an atomic operation suffice
4099 * to guarantee consistency of the page dirty field.
4101 * For PAGE_SIZE == 32768 case, compiler already
4102 * properly aligns the dirty field, so no forcible
4103 * alignment is needed. Only require existence of
4104 * atomic_clear_64 when page size is 32768.
4106 addr = (uintptr_t)&m->dirty;
4107 #if PAGE_SIZE == 32768
4108 atomic_clear_64((uint64_t *)addr, pagebits);
4109 #elif PAGE_SIZE == 16384
4110 atomic_clear_32((uint32_t *)addr, pagebits);
4111 #else /* PAGE_SIZE <= 8192 */
4113 * Use a trick to perform a 32-bit atomic on the
4114 * containing aligned word, to not depend on the existence
4115 * of atomic_clear_{8, 16}.
4117 shift = addr & (sizeof(uint32_t) - 1);
4118 #if BYTE_ORDER == BIG_ENDIAN
4119 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
4123 addr &= ~(sizeof(uint32_t) - 1);
4124 atomic_clear_32((uint32_t *)addr, pagebits << shift);
4125 #endif /* PAGE_SIZE */
4130 * vm_page_set_validclean:
4132 * Sets portions of a page valid and clean. The arguments are expected
4133 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4134 * of any partial chunks touched by the range. The invalid portion of
4135 * such chunks will be zero'd.
4137 * (base + size) must be less then or equal to PAGE_SIZE.
4140 vm_page_set_validclean(vm_page_t m, int base, int size)
4142 vm_page_bits_t oldvalid, pagebits;
4145 VM_OBJECT_ASSERT_WLOCKED(m->object);
4146 if (size == 0) /* handle degenerate case */
4150 * If the base is not DEV_BSIZE aligned and the valid
4151 * bit is clear, we have to zero out a portion of the
4154 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4155 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
4156 pmap_zero_page_area(m, frag, base - frag);
4159 * If the ending offset is not DEV_BSIZE aligned and the
4160 * valid bit is clear, we have to zero out a portion of
4163 endoff = base + size;
4164 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4165 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
4166 pmap_zero_page_area(m, endoff,
4167 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4170 * Set valid, clear dirty bits. If validating the entire
4171 * page we can safely clear the pmap modify bit. We also
4172 * use this opportunity to clear the VPO_NOSYNC flag. If a process
4173 * takes a write fault on a MAP_NOSYNC memory area the flag will
4176 * We set valid bits inclusive of any overlap, but we can only
4177 * clear dirty bits for DEV_BSIZE chunks that are fully within
4180 oldvalid = m->valid;
4181 pagebits = vm_page_bits(base, size);
4182 m->valid |= pagebits;
4184 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
4185 frag = DEV_BSIZE - frag;
4191 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
4193 if (base == 0 && size == PAGE_SIZE) {
4195 * The page can only be modified within the pmap if it is
4196 * mapped, and it can only be mapped if it was previously
4199 if (oldvalid == VM_PAGE_BITS_ALL)
4201 * Perform the pmap_clear_modify() first. Otherwise,
4202 * a concurrent pmap operation, such as
4203 * pmap_protect(), could clear a modification in the
4204 * pmap and set the dirty field on the page before
4205 * pmap_clear_modify() had begun and after the dirty
4206 * field was cleared here.
4208 pmap_clear_modify(m);
4210 m->oflags &= ~VPO_NOSYNC;
4211 } else if (oldvalid != VM_PAGE_BITS_ALL)
4212 m->dirty &= ~pagebits;
4214 vm_page_clear_dirty_mask(m, pagebits);
4218 vm_page_clear_dirty(vm_page_t m, int base, int size)
4221 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
4225 * vm_page_set_invalid:
4227 * Invalidates DEV_BSIZE'd chunks within a page. Both the
4228 * valid and dirty bits for the effected areas are cleared.
4231 vm_page_set_invalid(vm_page_t m, int base, int size)
4233 vm_page_bits_t bits;
4237 VM_OBJECT_ASSERT_WLOCKED(object);
4238 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
4239 size >= object->un_pager.vnp.vnp_size)
4240 bits = VM_PAGE_BITS_ALL;
4242 bits = vm_page_bits(base, size);
4243 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
4246 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
4247 !pmap_page_is_mapped(m),
4248 ("vm_page_set_invalid: page %p is mapped", m));
4254 * vm_page_zero_invalid()
4256 * The kernel assumes that the invalid portions of a page contain
4257 * garbage, but such pages can be mapped into memory by user code.
4258 * When this occurs, we must zero out the non-valid portions of the
4259 * page so user code sees what it expects.
4261 * Pages are most often semi-valid when the end of a file is mapped
4262 * into memory and the file's size is not page aligned.
4265 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
4270 VM_OBJECT_ASSERT_WLOCKED(m->object);
4272 * Scan the valid bits looking for invalid sections that
4273 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
4274 * valid bit may be set ) have already been zeroed by
4275 * vm_page_set_validclean().
4277 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
4278 if (i == (PAGE_SIZE / DEV_BSIZE) ||
4279 (m->valid & ((vm_page_bits_t)1 << i))) {
4281 pmap_zero_page_area(m,
4282 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
4289 * setvalid is TRUE when we can safely set the zero'd areas
4290 * as being valid. We can do this if there are no cache consistancy
4291 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
4294 m->valid = VM_PAGE_BITS_ALL;
4300 * Is (partial) page valid? Note that the case where size == 0
4301 * will return FALSE in the degenerate case where the page is
4302 * entirely invalid, and TRUE otherwise.
4305 vm_page_is_valid(vm_page_t m, int base, int size)
4307 vm_page_bits_t bits;
4309 VM_OBJECT_ASSERT_LOCKED(m->object);
4310 bits = vm_page_bits(base, size);
4311 return (m->valid != 0 && (m->valid & bits) == bits);
4315 * Returns true if all of the specified predicates are true for the entire
4316 * (super)page and false otherwise.
4319 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
4325 if (skip_m != NULL && skip_m->object != object)
4327 VM_OBJECT_ASSERT_LOCKED(object);
4328 npages = atop(pagesizes[m->psind]);
4331 * The physically contiguous pages that make up a superpage, i.e., a
4332 * page with a page size index ("psind") greater than zero, will
4333 * occupy adjacent entries in vm_page_array[].
4335 for (i = 0; i < npages; i++) {
4336 /* Always test object consistency, including "skip_m". */
4337 if (m[i].object != object)
4339 if (&m[i] == skip_m)
4341 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
4343 if ((flags & PS_ALL_DIRTY) != 0) {
4345 * Calling vm_page_test_dirty() or pmap_is_modified()
4346 * might stop this case from spuriously returning
4347 * "false". However, that would require a write lock
4348 * on the object containing "m[i]".
4350 if (m[i].dirty != VM_PAGE_BITS_ALL)
4353 if ((flags & PS_ALL_VALID) != 0 &&
4354 m[i].valid != VM_PAGE_BITS_ALL)
4361 * Set the page's dirty bits if the page is modified.
4364 vm_page_test_dirty(vm_page_t m)
4367 VM_OBJECT_ASSERT_WLOCKED(m->object);
4368 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
4373 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
4376 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
4380 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
4383 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
4387 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
4390 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
4393 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
4395 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
4398 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
4402 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
4405 mtx_assert_(vm_page_lockptr(m), a, file, line);
4411 vm_page_object_lock_assert(vm_page_t m)
4415 * Certain of the page's fields may only be modified by the
4416 * holder of the containing object's lock or the exclusive busy.
4417 * holder. Unfortunately, the holder of the write busy is
4418 * not recorded, and thus cannot be checked here.
4420 if (m->object != NULL && !vm_page_xbusied(m))
4421 VM_OBJECT_ASSERT_WLOCKED(m->object);
4425 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
4428 if ((bits & PGA_WRITEABLE) == 0)
4432 * The PGA_WRITEABLE flag can only be set if the page is
4433 * managed, is exclusively busied or the object is locked.
4434 * Currently, this flag is only set by pmap_enter().
4436 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4437 ("PGA_WRITEABLE on unmanaged page"));
4438 if (!vm_page_xbusied(m))
4439 VM_OBJECT_ASSERT_LOCKED(m->object);
4443 #include "opt_ddb.h"
4445 #include <sys/kernel.h>
4447 #include <ddb/ddb.h>
4449 DB_SHOW_COMMAND(page, vm_page_print_page_info)
4452 db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
4453 db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
4454 db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
4455 db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
4456 db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
4457 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
4458 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
4459 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
4460 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
4463 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
4467 db_printf("pq_free %d\n", vm_free_count());
4468 for (dom = 0; dom < vm_ndomains; dom++) {
4470 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
4472 vm_dom[dom].vmd_page_count,
4473 vm_dom[dom].vmd_free_count,
4474 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
4475 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
4476 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
4477 vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
4481 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
4487 db_printf("show pginfo addr\n");
4491 phys = strchr(modif, 'p') != NULL;
4493 m = PHYS_TO_VM_PAGE(addr);
4495 m = (vm_page_t)addr;
4497 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
4498 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
4499 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
4500 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
4501 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);