2 * SPDX-License-Identifier: BSD-3-Clause
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/kernel.h>
95 #include <sys/limits.h>
96 #include <sys/linker.h>
97 #include <sys/malloc.h>
99 #include <sys/msgbuf.h>
100 #include <sys/mutex.h>
101 #include <sys/proc.h>
102 #include <sys/rwlock.h>
103 #include <sys/sbuf.h>
105 #include <sys/sysctl.h>
106 #include <sys/vmmeter.h>
107 #include <sys/vnode.h>
111 #include <vm/vm_param.h>
112 #include <vm/vm_kern.h>
113 #include <vm/vm_object.h>
114 #include <vm/vm_page.h>
115 #include <vm/vm_pageout.h>
116 #include <vm/vm_pager.h>
117 #include <vm/vm_phys.h>
118 #include <vm/vm_radix.h>
119 #include <vm/vm_reserv.h>
120 #include <vm/vm_extern.h>
122 #include <vm/uma_int.h>
124 #include <machine/md_var.h>
127 * Associated with page of user-allocatable memory is a
131 struct vm_domain vm_dom[MAXMEMDOM];
132 struct mtx_padalign __exclusive_cache_line vm_page_queue_free_mtx;
134 struct mtx_padalign __exclusive_cache_line pa_lock[PA_LOCK_COUNT];
137 * bogus page -- for I/O to/from partially complete buffers,
138 * or for paging into sparsely invalid regions.
140 vm_page_t bogus_page;
142 vm_page_t vm_page_array;
143 long vm_page_array_size;
146 static int boot_pages = UMA_BOOT_PAGES;
147 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
149 "number of pages allocated for bootstrapping the VM system");
151 static int pa_tryrelock_restart;
152 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
153 &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
155 static TAILQ_HEAD(, vm_page) blacklist_head;
156 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
157 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
158 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
160 /* Is the page daemon waiting for free pages? */
161 static int vm_pageout_pages_needed;
163 static uma_zone_t fakepg_zone;
165 static void vm_page_alloc_check(vm_page_t m);
166 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
167 static void vm_page_enqueue(uint8_t queue, vm_page_t m);
168 static void vm_page_free_phys(vm_page_t m);
169 static void vm_page_free_wakeup(void);
170 static void vm_page_init(void *dummy);
171 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
172 vm_pindex_t pindex, vm_page_t mpred);
173 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
175 static int vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
177 static int vm_page_alloc_fail(vm_object_t object, int req);
179 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
182 vm_page_init(void *dummy)
185 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
186 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
187 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
188 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
191 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
192 #if PAGE_SIZE == 32768
194 CTASSERT(sizeof(u_long) >= 8);
199 * Try to acquire a physical address lock while a pmap is locked. If we
200 * fail to trylock we unlock and lock the pmap directly and cache the
201 * locked pa in *locked. The caller should then restart their loop in case
202 * the virtual to physical mapping has changed.
205 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
212 PA_LOCK_ASSERT(lockpa, MA_OWNED);
213 if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
220 atomic_add_int(&pa_tryrelock_restart, 1);
229 * Sets the page size, perhaps based upon the memory
230 * size. Must be called before any use of page-size
231 * dependent functions.
234 vm_set_page_size(void)
236 if (vm_cnt.v_page_size == 0)
237 vm_cnt.v_page_size = PAGE_SIZE;
238 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
239 panic("vm_set_page_size: page size not a power of two");
243 * vm_page_blacklist_next:
245 * Find the next entry in the provided string of blacklist
246 * addresses. Entries are separated by space, comma, or newline.
247 * If an invalid integer is encountered then the rest of the
248 * string is skipped. Updates the list pointer to the next
249 * character, or NULL if the string is exhausted or invalid.
252 vm_page_blacklist_next(char **list, char *end)
257 if (list == NULL || *list == NULL)
265 * If there's no end pointer then the buffer is coming from
266 * the kenv and we know it's null-terminated.
269 end = *list + strlen(*list);
271 /* Ensure that strtoq() won't walk off the end */
273 if (*end == '\n' || *end == ' ' || *end == ',')
276 printf("Blacklist not terminated, skipping\n");
282 for (pos = *list; *pos != '\0'; pos = cp) {
283 bad = strtoq(pos, &cp, 0);
284 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
293 if (*cp == '\0' || ++cp >= end)
297 return (trunc_page(bad));
299 printf("Garbage in RAM blacklist, skipping\n");
305 * vm_page_blacklist_check:
307 * Iterate through the provided string of blacklist addresses, pulling
308 * each entry out of the physical allocator free list and putting it
309 * onto a list for reporting via the vm.page_blacklist sysctl.
312 vm_page_blacklist_check(char *list, char *end)
320 while (next != NULL) {
321 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
323 m = vm_phys_paddr_to_vm_page(pa);
326 mtx_lock(&vm_page_queue_free_mtx);
327 ret = vm_phys_unfree_page(m);
328 mtx_unlock(&vm_page_queue_free_mtx);
330 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
332 printf("Skipping page with pa 0x%jx\n",
339 * vm_page_blacklist_load:
341 * Search for a special module named "ram_blacklist". It'll be a
342 * plain text file provided by the user via the loader directive
346 vm_page_blacklist_load(char **list, char **end)
355 mod = preload_search_by_type("ram_blacklist");
357 ptr = preload_fetch_addr(mod);
358 len = preload_fetch_size(mod);
369 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
376 error = sysctl_wire_old_buffer(req, 0);
379 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
380 TAILQ_FOREACH(m, &blacklist_head, listq) {
381 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
382 (uintmax_t)m->phys_addr);
385 error = sbuf_finish(&sbuf);
391 vm_page_domain_init(struct vm_domain *vmd)
393 struct vm_pagequeue *pq;
396 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
397 "vm inactive pagequeue";
398 *__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_vcnt) =
399 &vm_cnt.v_inactive_count;
400 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
401 "vm active pagequeue";
402 *__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_vcnt) =
403 &vm_cnt.v_active_count;
404 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
405 "vm laundry pagequeue";
406 *__DECONST(int **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_vcnt) =
407 &vm_cnt.v_laundry_count;
408 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_name) =
409 "vm unswappable pagequeue";
410 /* Unswappable dirty pages are counted as being in the laundry. */
411 *__DECONST(int **, &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_vcnt) =
412 &vm_cnt.v_laundry_count;
413 vmd->vmd_page_count = 0;
414 vmd->vmd_free_count = 0;
416 vmd->vmd_oom = FALSE;
417 for (i = 0; i < PQ_COUNT; i++) {
418 pq = &vmd->vmd_pagequeues[i];
419 TAILQ_INIT(&pq->pq_pl);
420 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
421 MTX_DEF | MTX_DUPOK);
426 * Initialize a physical page in preparation for adding it to the free
430 vm_page_init_page(vm_paddr_t pa)
434 m = vm_phys_paddr_to_vm_page(pa);
437 m->busy_lock = VPB_UNBUSIED;
443 m->segind = vm_phys_paddr_to_segind(pa);
444 m->order = VM_NFREEORDER;
445 m->pool = VM_FREEPOOL_DEFAULT;
446 m->valid = m->dirty = 0;
453 * Initializes the resident memory module. Allocates physical memory for
454 * bootstrapping UMA and some data structures that are used to manage
455 * physical pages. Initializes these structures, and populates the free
459 vm_page_startup(vm_offset_t vaddr)
461 struct vm_domain *vmd;
462 struct vm_phys_seg *seg;
464 char *list, *listend;
466 vm_paddr_t end, high_avail, low_avail, new_end, page_range, size;
467 vm_paddr_t biggestsize, last_pa, pa;
469 int biggestone, i, pages_per_zone, segind;
473 vaddr = round_page(vaddr);
475 for (i = 0; phys_avail[i + 1]; i += 2) {
476 phys_avail[i] = round_page(phys_avail[i]);
477 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
479 for (i = 0; phys_avail[i + 1]; i += 2) {
480 size = phys_avail[i + 1] - phys_avail[i];
481 if (size > biggestsize) {
487 end = phys_avail[biggestone+1];
490 * Initialize the page and queue locks.
492 mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
493 for (i = 0; i < PA_LOCK_COUNT; i++)
494 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
495 for (i = 0; i < vm_ndomains; i++)
496 vm_page_domain_init(&vm_dom[i]);
499 * Almost all of the pages needed for bootstrapping UMA are used
500 * for zone structures, so if the number of CPUs results in those
501 * structures taking more than one page each, we set aside more pages
502 * in proportion to the zone structure size.
504 pages_per_zone = howmany(sizeof(struct uma_zone) +
505 sizeof(struct uma_cache) * (mp_maxid + 1) +
506 roundup2(sizeof(struct uma_slab), sizeof(void *)), UMA_SLAB_SIZE);
507 if (pages_per_zone > 1) {
508 /* Reserve more pages so that we don't run out. */
509 boot_pages = UMA_BOOT_PAGES_ZONES * pages_per_zone;
513 * Allocate memory for use when boot strapping the kernel memory
516 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
517 * manually fetch the value.
519 TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
520 new_end = end - (boot_pages * UMA_SLAB_SIZE);
521 new_end = trunc_page(new_end);
522 mapped = pmap_map(&vaddr, new_end, end,
523 VM_PROT_READ | VM_PROT_WRITE);
524 bzero((void *)mapped, end - new_end);
525 uma_startup((void *)mapped, boot_pages);
527 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
528 defined(__i386__) || defined(__mips__)
530 * Allocate a bitmap to indicate that a random physical page
531 * needs to be included in a minidump.
533 * The amd64 port needs this to indicate which direct map pages
534 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
536 * However, i386 still needs this workspace internally within the
537 * minidump code. In theory, they are not needed on i386, but are
538 * included should the sf_buf code decide to use them.
541 for (i = 0; dump_avail[i + 1] != 0; i += 2)
542 if (dump_avail[i + 1] > last_pa)
543 last_pa = dump_avail[i + 1];
544 page_range = last_pa / PAGE_SIZE;
545 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
546 new_end -= vm_page_dump_size;
547 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
548 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
549 bzero((void *)vm_page_dump, vm_page_dump_size);
553 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
555 * Include the UMA bootstrap pages and vm_page_dump in a crash dump.
556 * When pmap_map() uses the direct map, they are not automatically
559 for (pa = new_end; pa < end; pa += PAGE_SIZE)
562 phys_avail[biggestone + 1] = new_end;
565 * Request that the physical pages underlying the message buffer be
566 * included in a crash dump. Since the message buffer is accessed
567 * through the direct map, they are not automatically included.
569 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
570 last_pa = pa + round_page(msgbufsize);
571 while (pa < last_pa) {
577 * Compute the number of pages of memory that will be available for
578 * use, taking into account the overhead of a page structure per page.
579 * In other words, solve
580 * "available physical memory" - round_page(page_range *
581 * sizeof(struct vm_page)) = page_range * PAGE_SIZE
584 low_avail = phys_avail[0];
585 high_avail = phys_avail[1];
586 for (i = 0; i < vm_phys_nsegs; i++) {
587 if (vm_phys_segs[i].start < low_avail)
588 low_avail = vm_phys_segs[i].start;
589 if (vm_phys_segs[i].end > high_avail)
590 high_avail = vm_phys_segs[i].end;
592 /* Skip the first chunk. It is already accounted for. */
593 for (i = 2; phys_avail[i + 1] != 0; i += 2) {
594 if (phys_avail[i] < low_avail)
595 low_avail = phys_avail[i];
596 if (phys_avail[i + 1] > high_avail)
597 high_avail = phys_avail[i + 1];
599 first_page = low_avail / PAGE_SIZE;
600 #ifdef VM_PHYSSEG_SPARSE
602 for (i = 0; i < vm_phys_nsegs; i++)
603 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
604 for (i = 0; phys_avail[i + 1] != 0; i += 2)
605 size += phys_avail[i + 1] - phys_avail[i];
606 #elif defined(VM_PHYSSEG_DENSE)
607 size = high_avail - low_avail;
609 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
612 #ifdef VM_PHYSSEG_DENSE
614 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
615 * the overhead of a page structure per page only if vm_page_array is
616 * allocated from the last physical memory chunk. Otherwise, we must
617 * allocate page structures representing the physical memory
618 * underlying vm_page_array, even though they will not be used.
620 if (new_end != high_avail)
621 page_range = size / PAGE_SIZE;
625 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
628 * If the partial bytes remaining are large enough for
629 * a page (PAGE_SIZE) without a corresponding
630 * 'struct vm_page', then new_end will contain an
631 * extra page after subtracting the length of the VM
632 * page array. Compensate by subtracting an extra
635 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
636 if (new_end == high_avail)
637 high_avail -= PAGE_SIZE;
638 new_end -= PAGE_SIZE;
644 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
645 * However, because this page is allocated from KVM, out-of-bounds
646 * accesses using the direct map will not be trapped.
651 * Allocate physical memory for the page structures, and map it.
653 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
654 mapped = pmap_map(&vaddr, new_end, end,
655 VM_PROT_READ | VM_PROT_WRITE);
656 vm_page_array = (vm_page_t)mapped;
657 vm_page_array_size = page_range;
659 #if VM_NRESERVLEVEL > 0
661 * Allocate physical memory for the reservation management system's
662 * data structures, and map it.
664 if (high_avail == end)
665 high_avail = new_end;
666 new_end = vm_reserv_startup(&vaddr, new_end, high_avail);
668 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
670 * Include vm_page_array and vm_reserv_array in a crash dump.
672 for (pa = new_end; pa < end; pa += PAGE_SIZE)
675 phys_avail[biggestone + 1] = new_end;
678 * Add physical memory segments corresponding to the available
681 for (i = 0; phys_avail[i + 1] != 0; i += 2)
682 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
685 * Initialize the physical memory allocator.
690 * Initialize the page structures and add every available page to the
691 * physical memory allocator's free lists.
693 vm_cnt.v_page_count = 0;
694 vm_cnt.v_free_count = 0;
695 for (segind = 0; segind < vm_phys_nsegs; segind++) {
696 seg = &vm_phys_segs[segind];
697 for (pa = seg->start; pa < seg->end; pa += PAGE_SIZE)
698 vm_page_init_page(pa);
701 * Add the segment to the free lists only if it is covered by
702 * one of the ranges in phys_avail. Because we've added the
703 * ranges to the vm_phys_segs array, we can assume that each
704 * segment is either entirely contained in one of the ranges,
705 * or doesn't overlap any of them.
707 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
708 if (seg->start < phys_avail[i] ||
709 seg->end > phys_avail[i + 1])
713 pagecount = (u_long)atop(seg->end - seg->start);
715 mtx_lock(&vm_page_queue_free_mtx);
716 vm_phys_free_contig(m, pagecount);
717 vm_phys_freecnt_adj(m, (int)pagecount);
718 mtx_unlock(&vm_page_queue_free_mtx);
719 vm_cnt.v_page_count += (u_int)pagecount;
721 vmd = &vm_dom[seg->domain];
722 vmd->vmd_page_count += (u_int)pagecount;
723 vmd->vmd_segs |= 1UL << m->segind;
729 * Remove blacklisted pages from the physical memory allocator.
731 TAILQ_INIT(&blacklist_head);
732 vm_page_blacklist_load(&list, &listend);
733 vm_page_blacklist_check(list, listend);
735 list = kern_getenv("vm.blacklist");
736 vm_page_blacklist_check(list, NULL);
739 #if VM_NRESERVLEVEL > 0
741 * Initialize the reservation management system.
749 vm_page_reference(vm_page_t m)
752 vm_page_aflag_set(m, PGA_REFERENCED);
756 * vm_page_busy_downgrade:
758 * Downgrade an exclusive busy page into a single shared busy page.
761 vm_page_busy_downgrade(vm_page_t m)
766 vm_page_assert_xbusied(m);
767 locked = mtx_owned(vm_page_lockptr(m));
771 x &= VPB_BIT_WAITERS;
772 if (x != 0 && !locked)
774 if (atomic_cmpset_rel_int(&m->busy_lock,
775 VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1)))
777 if (x != 0 && !locked)
790 * Return a positive value if the page is shared busied, 0 otherwise.
793 vm_page_sbusied(vm_page_t m)
798 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
804 * Shared unbusy a page.
807 vm_page_sunbusy(vm_page_t m)
811 vm_page_lock_assert(m, MA_NOTOWNED);
812 vm_page_assert_sbusied(m);
816 if (VPB_SHARERS(x) > 1) {
817 if (atomic_cmpset_int(&m->busy_lock, x,
822 if ((x & VPB_BIT_WAITERS) == 0) {
823 KASSERT(x == VPB_SHARERS_WORD(1),
824 ("vm_page_sunbusy: invalid lock state"));
825 if (atomic_cmpset_int(&m->busy_lock,
826 VPB_SHARERS_WORD(1), VPB_UNBUSIED))
830 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
831 ("vm_page_sunbusy: invalid lock state for waiters"));
834 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
845 * vm_page_busy_sleep:
847 * Sleep and release the page lock, using the page pointer as wchan.
848 * This is used to implement the hard-path of busying mechanism.
850 * The given page must be locked.
852 * If nonshared is true, sleep only if the page is xbusy.
855 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
859 vm_page_assert_locked(m);
862 if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
863 ((x & VPB_BIT_WAITERS) == 0 &&
864 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
868 msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
874 * Try to shared busy a page.
875 * If the operation succeeds 1 is returned otherwise 0.
876 * The operation never sleeps.
879 vm_page_trysbusy(vm_page_t m)
885 if ((x & VPB_BIT_SHARED) == 0)
887 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
893 vm_page_xunbusy_locked(vm_page_t m)
896 vm_page_assert_xbusied(m);
897 vm_page_assert_locked(m);
899 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
900 /* There is a waiter, do wakeup() instead of vm_page_flash(). */
905 vm_page_xunbusy_maybelocked(vm_page_t m)
909 vm_page_assert_xbusied(m);
912 * Fast path for unbusy. If it succeeds, we know that there
913 * are no waiters, so we do not need a wakeup.
915 if (atomic_cmpset_rel_int(&m->busy_lock, VPB_SINGLE_EXCLUSIVER,
919 lockacq = !mtx_owned(vm_page_lockptr(m));
922 vm_page_xunbusy_locked(m);
928 * vm_page_xunbusy_hard:
930 * Called after the first try the exclusive unbusy of a page failed.
931 * It is assumed that the waiters bit is on.
934 vm_page_xunbusy_hard(vm_page_t m)
937 vm_page_assert_xbusied(m);
940 vm_page_xunbusy_locked(m);
947 * Wakeup anyone waiting for the page.
948 * The ownership bits do not change.
950 * The given page must be locked.
953 vm_page_flash(vm_page_t m)
957 vm_page_lock_assert(m, MA_OWNED);
961 if ((x & VPB_BIT_WAITERS) == 0)
963 if (atomic_cmpset_int(&m->busy_lock, x,
964 x & (~VPB_BIT_WAITERS)))
971 * Avoid releasing and reacquiring the same page lock.
974 vm_page_change_lock(vm_page_t m, struct mtx **mtx)
978 mtx1 = vm_page_lockptr(m);
988 * Keep page from being freed by the page daemon
989 * much of the same effect as wiring, except much lower
990 * overhead and should be used only for *very* temporary
991 * holding ("wiring").
994 vm_page_hold(vm_page_t mem)
997 vm_page_lock_assert(mem, MA_OWNED);
1002 vm_page_unhold(vm_page_t mem)
1005 vm_page_lock_assert(mem, MA_OWNED);
1006 KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
1008 if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
1009 vm_page_free_toq(mem);
1013 * vm_page_unhold_pages:
1015 * Unhold each of the pages that is referenced by the given array.
1018 vm_page_unhold_pages(vm_page_t *ma, int count)
1023 for (; count != 0; count--) {
1024 vm_page_change_lock(*ma, &mtx);
1025 vm_page_unhold(*ma);
1033 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1037 #ifdef VM_PHYSSEG_SPARSE
1038 m = vm_phys_paddr_to_vm_page(pa);
1040 m = vm_phys_fictitious_to_vm_page(pa);
1042 #elif defined(VM_PHYSSEG_DENSE)
1046 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1047 m = &vm_page_array[pi - first_page];
1050 return (vm_phys_fictitious_to_vm_page(pa));
1052 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1059 * Create a fictitious page with the specified physical address and
1060 * memory attribute. The memory attribute is the only the machine-
1061 * dependent aspect of a fictitious page that must be initialized.
1064 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1068 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1069 vm_page_initfake(m, paddr, memattr);
1074 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1077 if ((m->flags & PG_FICTITIOUS) != 0) {
1079 * The page's memattr might have changed since the
1080 * previous initialization. Update the pmap to the
1085 m->phys_addr = paddr;
1087 /* Fictitious pages don't use "segind". */
1088 m->flags = PG_FICTITIOUS;
1089 /* Fictitious pages don't use "order" or "pool". */
1090 m->oflags = VPO_UNMANAGED;
1091 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1095 pmap_page_set_memattr(m, memattr);
1101 * Release a fictitious page.
1104 vm_page_putfake(vm_page_t m)
1107 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1108 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1109 ("vm_page_putfake: bad page %p", m));
1110 uma_zfree(fakepg_zone, m);
1114 * vm_page_updatefake:
1116 * Update the given fictitious page to the specified physical address and
1120 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1123 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1124 ("vm_page_updatefake: bad page %p", m));
1125 m->phys_addr = paddr;
1126 pmap_page_set_memattr(m, memattr);
1135 vm_page_free(vm_page_t m)
1138 m->flags &= ~PG_ZERO;
1139 vm_page_free_toq(m);
1143 * vm_page_free_zero:
1145 * Free a page to the zerod-pages queue
1148 vm_page_free_zero(vm_page_t m)
1151 m->flags |= PG_ZERO;
1152 vm_page_free_toq(m);
1156 * Unbusy and handle the page queueing for a page from a getpages request that
1157 * was optionally read ahead or behind.
1160 vm_page_readahead_finish(vm_page_t m)
1163 /* We shouldn't put invalid pages on queues. */
1164 KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
1167 * Since the page is not the actually needed one, whether it should
1168 * be activated or deactivated is not obvious. Empirical results
1169 * have shown that deactivating the page is usually the best choice,
1170 * unless the page is wanted by another thread.
1173 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1174 vm_page_activate(m);
1176 vm_page_deactivate(m);
1182 * vm_page_sleep_if_busy:
1184 * Sleep and release the page queues lock if the page is busied.
1185 * Returns TRUE if the thread slept.
1187 * The given page must be unlocked and object containing it must
1191 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1195 vm_page_lock_assert(m, MA_NOTOWNED);
1196 VM_OBJECT_ASSERT_WLOCKED(m->object);
1198 if (vm_page_busied(m)) {
1200 * The page-specific object must be cached because page
1201 * identity can change during the sleep, causing the
1202 * re-lock of a different object.
1203 * It is assumed that a reference to the object is already
1204 * held by the callers.
1208 VM_OBJECT_WUNLOCK(obj);
1209 vm_page_busy_sleep(m, msg, false);
1210 VM_OBJECT_WLOCK(obj);
1217 * vm_page_dirty_KBI: [ internal use only ]
1219 * Set all bits in the page's dirty field.
1221 * The object containing the specified page must be locked if the
1222 * call is made from the machine-independent layer.
1224 * See vm_page_clear_dirty_mask().
1226 * This function should only be called by vm_page_dirty().
1229 vm_page_dirty_KBI(vm_page_t m)
1232 /* Refer to this operation by its public name. */
1233 KASSERT(m->valid == VM_PAGE_BITS_ALL,
1234 ("vm_page_dirty: page is invalid!"));
1235 m->dirty = VM_PAGE_BITS_ALL;
1239 * vm_page_insert: [ internal use only ]
1241 * Inserts the given mem entry into the object and object list.
1243 * The object must be locked.
1246 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1250 VM_OBJECT_ASSERT_WLOCKED(object);
1251 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1252 return (vm_page_insert_after(m, object, pindex, mpred));
1256 * vm_page_insert_after:
1258 * Inserts the page "m" into the specified object at offset "pindex".
1260 * The page "mpred" must immediately precede the offset "pindex" within
1261 * the specified object.
1263 * The object must be locked.
1266 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1271 VM_OBJECT_ASSERT_WLOCKED(object);
1272 KASSERT(m->object == NULL,
1273 ("vm_page_insert_after: page already inserted"));
1274 if (mpred != NULL) {
1275 KASSERT(mpred->object == object,
1276 ("vm_page_insert_after: object doesn't contain mpred"));
1277 KASSERT(mpred->pindex < pindex,
1278 ("vm_page_insert_after: mpred doesn't precede pindex"));
1279 msucc = TAILQ_NEXT(mpred, listq);
1281 msucc = TAILQ_FIRST(&object->memq);
1283 KASSERT(msucc->pindex > pindex,
1284 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1287 * Record the object/offset pair in this page
1293 * Now link into the object's ordered list of backed pages.
1295 if (vm_radix_insert(&object->rtree, m)) {
1300 vm_page_insert_radixdone(m, object, mpred);
1305 * vm_page_insert_radixdone:
1307 * Complete page "m" insertion into the specified object after the
1308 * radix trie hooking.
1310 * The page "mpred" must precede the offset "m->pindex" within the
1313 * The object must be locked.
1316 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1319 VM_OBJECT_ASSERT_WLOCKED(object);
1320 KASSERT(object != NULL && m->object == object,
1321 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1322 if (mpred != NULL) {
1323 KASSERT(mpred->object == object,
1324 ("vm_page_insert_after: object doesn't contain mpred"));
1325 KASSERT(mpred->pindex < m->pindex,
1326 ("vm_page_insert_after: mpred doesn't precede pindex"));
1330 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1332 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1335 * Show that the object has one more resident page.
1337 object->resident_page_count++;
1340 * Hold the vnode until the last page is released.
1342 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1343 vhold(object->handle);
1346 * Since we are inserting a new and possibly dirty page,
1347 * update the object's OBJ_MIGHTBEDIRTY flag.
1349 if (pmap_page_is_write_mapped(m))
1350 vm_object_set_writeable_dirty(object);
1356 * Removes the specified page from its containing object, but does not
1357 * invalidate any backing storage.
1359 * The object must be locked. The page must be locked if it is managed.
1362 vm_page_remove(vm_page_t m)
1367 if ((m->oflags & VPO_UNMANAGED) == 0)
1368 vm_page_assert_locked(m);
1369 if ((object = m->object) == NULL)
1371 VM_OBJECT_ASSERT_WLOCKED(object);
1372 if (vm_page_xbusied(m))
1373 vm_page_xunbusy_maybelocked(m);
1374 mrem = vm_radix_remove(&object->rtree, m->pindex);
1375 KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1378 * Now remove from the object's list of backed pages.
1380 TAILQ_REMOVE(&object->memq, m, listq);
1383 * And show that the object has one fewer resident page.
1385 object->resident_page_count--;
1388 * The vnode may now be recycled.
1390 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1391 vdrop(object->handle);
1399 * Returns the page associated with the object/offset
1400 * pair specified; if none is found, NULL is returned.
1402 * The object must be locked.
1405 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1408 VM_OBJECT_ASSERT_LOCKED(object);
1409 return (vm_radix_lookup(&object->rtree, pindex));
1413 * vm_page_find_least:
1415 * Returns the page associated with the object with least pindex
1416 * greater than or equal to the parameter pindex, or NULL.
1418 * The object must be locked.
1421 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1425 VM_OBJECT_ASSERT_LOCKED(object);
1426 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1427 m = vm_radix_lookup_ge(&object->rtree, pindex);
1432 * Returns the given page's successor (by pindex) within the object if it is
1433 * resident; if none is found, NULL is returned.
1435 * The object must be locked.
1438 vm_page_next(vm_page_t m)
1442 VM_OBJECT_ASSERT_LOCKED(m->object);
1443 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1444 MPASS(next->object == m->object);
1445 if (next->pindex != m->pindex + 1)
1452 * Returns the given page's predecessor (by pindex) within the object if it is
1453 * resident; if none is found, NULL is returned.
1455 * The object must be locked.
1458 vm_page_prev(vm_page_t m)
1462 VM_OBJECT_ASSERT_LOCKED(m->object);
1463 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1464 MPASS(prev->object == m->object);
1465 if (prev->pindex != m->pindex - 1)
1472 * Uses the page mnew as a replacement for an existing page at index
1473 * pindex which must be already present in the object.
1475 * The existing page must not be on a paging queue.
1478 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1482 VM_OBJECT_ASSERT_WLOCKED(object);
1483 KASSERT(mnew->object == NULL,
1484 ("vm_page_replace: page already in object"));
1487 * This function mostly follows vm_page_insert() and
1488 * vm_page_remove() without the radix, object count and vnode
1489 * dance. Double check such functions for more comments.
1492 mnew->object = object;
1493 mnew->pindex = pindex;
1494 mold = vm_radix_replace(&object->rtree, mnew);
1495 KASSERT(mold->queue == PQ_NONE,
1496 ("vm_page_replace: mold is on a paging queue"));
1498 /* Keep the resident page list in sorted order. */
1499 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1500 TAILQ_REMOVE(&object->memq, mold, listq);
1502 mold->object = NULL;
1503 vm_page_xunbusy_maybelocked(mold);
1506 * The object's resident_page_count does not change because we have
1507 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1509 if (pmap_page_is_write_mapped(mnew))
1510 vm_object_set_writeable_dirty(object);
1517 * Move the given memory entry from its
1518 * current object to the specified target object/offset.
1520 * Note: swap associated with the page must be invalidated by the move. We
1521 * have to do this for several reasons: (1) we aren't freeing the
1522 * page, (2) we are dirtying the page, (3) the VM system is probably
1523 * moving the page from object A to B, and will then later move
1524 * the backing store from A to B and we can't have a conflict.
1526 * Note: we *always* dirty the page. It is necessary both for the
1527 * fact that we moved it, and because we may be invalidating
1530 * The objects must be locked.
1533 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1538 VM_OBJECT_ASSERT_WLOCKED(new_object);
1540 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1541 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1542 ("vm_page_rename: pindex already renamed"));
1545 * Create a custom version of vm_page_insert() which does not depend
1546 * by m_prev and can cheat on the implementation aspects of the
1550 m->pindex = new_pindex;
1551 if (vm_radix_insert(&new_object->rtree, m)) {
1557 * The operation cannot fail anymore. The removal must happen before
1558 * the listq iterator is tainted.
1564 /* Return back to the new pindex to complete vm_page_insert(). */
1565 m->pindex = new_pindex;
1566 m->object = new_object;
1568 vm_page_insert_radixdone(m, new_object, mpred);
1576 * Allocate and return a page that is associated with the specified
1577 * object and offset pair. By default, this page is exclusive busied.
1579 * The caller must always specify an allocation class.
1581 * allocation classes:
1582 * VM_ALLOC_NORMAL normal process request
1583 * VM_ALLOC_SYSTEM system *really* needs a page
1584 * VM_ALLOC_INTERRUPT interrupt time request
1586 * optional allocation flags:
1587 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1588 * intends to allocate
1589 * VM_ALLOC_NOBUSY do not exclusive busy the page
1590 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1591 * VM_ALLOC_NOOBJ page is not associated with an object and
1592 * should not be exclusive busy
1593 * VM_ALLOC_SBUSY shared busy the allocated page
1594 * VM_ALLOC_WIRED wire the allocated page
1595 * VM_ALLOC_ZERO prefer a zeroed page
1597 * This routine may not sleep.
1600 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1603 return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1604 vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1608 * Allocate a page in the specified object with the given page index. To
1609 * optimize insertion of the page into the object, the caller must also specifiy
1610 * the resident page in the object with largest index smaller than the given
1611 * page index, or NULL if no such page exists.
1614 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex, int req,
1618 int flags, req_class;
1621 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1622 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1623 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1624 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1625 ("inconsistent object(%p)/req(%x)", object, req));
1626 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1627 ("Can't sleep and retry object insertion."));
1628 KASSERT(mpred == NULL || mpred->pindex < pindex,
1629 ("mpred %p doesn't precede pindex 0x%jx", mpred,
1630 (uintmax_t)pindex));
1632 VM_OBJECT_ASSERT_WLOCKED(object);
1634 req_class = req & VM_ALLOC_CLASS_MASK;
1637 * The page daemon is allowed to dig deeper into the free page list.
1639 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1640 req_class = VM_ALLOC_SYSTEM;
1643 * Allocate a page if the number of free pages exceeds the minimum
1644 * for the request class.
1647 mtx_lock(&vm_page_queue_free_mtx);
1648 if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
1649 (req_class == VM_ALLOC_SYSTEM &&
1650 vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
1651 (req_class == VM_ALLOC_INTERRUPT &&
1652 vm_cnt.v_free_count > 0)) {
1654 * Can we allocate the page from a reservation?
1656 #if VM_NRESERVLEVEL > 0
1657 if (object == NULL || (object->flags & (OBJ_COLORED |
1658 OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1659 vm_reserv_alloc_page(object, pindex, mpred)) == NULL)
1663 * If not, allocate it from the free page queues.
1665 m = vm_phys_alloc_pages(object != NULL ?
1666 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1667 #if VM_NRESERVLEVEL > 0
1668 if (m == NULL && vm_reserv_reclaim_inactive()) {
1669 m = vm_phys_alloc_pages(object != NULL ?
1670 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1677 * Not allocatable, give up.
1679 if (vm_page_alloc_fail(object, req))
1685 * At this point we had better have found a good page.
1687 KASSERT(m != NULL, ("missing page"));
1688 free_count = vm_phys_freecnt_adj(m, -1);
1689 mtx_unlock(&vm_page_queue_free_mtx);
1690 vm_page_alloc_check(m);
1693 * Initialize the page. Only the PG_ZERO flag is inherited.
1696 if ((req & VM_ALLOC_ZERO) != 0)
1699 if ((req & VM_ALLOC_NODUMP) != 0)
1703 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1705 m->busy_lock = VPB_UNBUSIED;
1706 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1707 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1708 if ((req & VM_ALLOC_SBUSY) != 0)
1709 m->busy_lock = VPB_SHARERS_WORD(1);
1710 if (req & VM_ALLOC_WIRED) {
1712 * The page lock is not required for wiring a page until that
1713 * page is inserted into the object.
1715 atomic_add_int(&vm_cnt.v_wire_count, 1);
1720 if (object != NULL) {
1721 if (vm_page_insert_after(m, object, pindex, mpred)) {
1722 pagedaemon_wakeup();
1723 if (req & VM_ALLOC_WIRED) {
1724 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1727 KASSERT(m->object == NULL, ("page %p has object", m));
1728 m->oflags = VPO_UNMANAGED;
1729 m->busy_lock = VPB_UNBUSIED;
1730 /* Don't change PG_ZERO. */
1731 vm_page_free_toq(m);
1732 if (req & VM_ALLOC_WAITFAIL) {
1733 VM_OBJECT_WUNLOCK(object);
1735 VM_OBJECT_WLOCK(object);
1740 /* Ignore device objects; the pager sets "memattr" for them. */
1741 if (object->memattr != VM_MEMATTR_DEFAULT &&
1742 (object->flags & OBJ_FICTITIOUS) == 0)
1743 pmap_page_set_memattr(m, object->memattr);
1748 * Don't wakeup too often - wakeup the pageout daemon when
1749 * we would be nearly out of memory.
1751 if (vm_paging_needed(free_count))
1752 pagedaemon_wakeup();
1758 * vm_page_alloc_contig:
1760 * Allocate a contiguous set of physical pages of the given size "npages"
1761 * from the free lists. All of the physical pages must be at or above
1762 * the given physical address "low" and below the given physical address
1763 * "high". The given value "alignment" determines the alignment of the
1764 * first physical page in the set. If the given value "boundary" is
1765 * non-zero, then the set of physical pages cannot cross any physical
1766 * address boundary that is a multiple of that value. Both "alignment"
1767 * and "boundary" must be a power of two.
1769 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1770 * then the memory attribute setting for the physical pages is configured
1771 * to the object's memory attribute setting. Otherwise, the memory
1772 * attribute setting for the physical pages is configured to "memattr",
1773 * overriding the object's memory attribute setting. However, if the
1774 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1775 * memory attribute setting for the physical pages cannot be configured
1776 * to VM_MEMATTR_DEFAULT.
1778 * The specified object may not contain fictitious pages.
1780 * The caller must always specify an allocation class.
1782 * allocation classes:
1783 * VM_ALLOC_NORMAL normal process request
1784 * VM_ALLOC_SYSTEM system *really* needs a page
1785 * VM_ALLOC_INTERRUPT interrupt time request
1787 * optional allocation flags:
1788 * VM_ALLOC_NOBUSY do not exclusive busy the page
1789 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1790 * VM_ALLOC_NOOBJ page is not associated with an object and
1791 * should not be exclusive busy
1792 * VM_ALLOC_SBUSY shared busy the allocated page
1793 * VM_ALLOC_WIRED wire the allocated page
1794 * VM_ALLOC_ZERO prefer a zeroed page
1796 * This routine may not sleep.
1799 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1800 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1801 vm_paddr_t boundary, vm_memattr_t memattr)
1803 vm_page_t m, m_ret, mpred;
1804 u_int busy_lock, flags, oflags;
1807 mpred = NULL; /* XXX: pacify gcc */
1808 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1809 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1810 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1811 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1812 ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
1814 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1815 ("Can't sleep and retry object insertion."));
1816 if (object != NULL) {
1817 VM_OBJECT_ASSERT_WLOCKED(object);
1818 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
1819 ("vm_page_alloc_contig: object %p has fictitious pages",
1822 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1823 req_class = req & VM_ALLOC_CLASS_MASK;
1826 * The page daemon is allowed to dig deeper into the free page list.
1828 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1829 req_class = VM_ALLOC_SYSTEM;
1831 if (object != NULL) {
1832 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1833 KASSERT(mpred == NULL || mpred->pindex != pindex,
1834 ("vm_page_alloc_contig: pindex already allocated"));
1838 * Can we allocate the pages without the number of free pages falling
1839 * below the lower bound for the allocation class?
1842 mtx_lock(&vm_page_queue_free_mtx);
1843 if (vm_cnt.v_free_count >= npages + vm_cnt.v_free_reserved ||
1844 (req_class == VM_ALLOC_SYSTEM &&
1845 vm_cnt.v_free_count >= npages + vm_cnt.v_interrupt_free_min) ||
1846 (req_class == VM_ALLOC_INTERRUPT &&
1847 vm_cnt.v_free_count >= npages)) {
1849 * Can we allocate the pages from a reservation?
1851 #if VM_NRESERVLEVEL > 0
1853 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1854 (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1855 low, high, alignment, boundary, mpred)) == NULL)
1858 * If not, allocate them from the free page queues.
1860 m_ret = vm_phys_alloc_contig(npages, low, high,
1861 alignment, boundary);
1863 if (vm_page_alloc_fail(object, req))
1868 vm_phys_freecnt_adj(m_ret, -npages);
1870 #if VM_NRESERVLEVEL > 0
1871 if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1876 mtx_unlock(&vm_page_queue_free_mtx);
1879 for (m = m_ret; m < &m_ret[npages]; m++)
1880 vm_page_alloc_check(m);
1883 * Initialize the pages. Only the PG_ZERO flag is inherited.
1886 if ((req & VM_ALLOC_ZERO) != 0)
1888 if ((req & VM_ALLOC_NODUMP) != 0)
1890 oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1892 busy_lock = VPB_UNBUSIED;
1893 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1894 busy_lock = VPB_SINGLE_EXCLUSIVER;
1895 if ((req & VM_ALLOC_SBUSY) != 0)
1896 busy_lock = VPB_SHARERS_WORD(1);
1897 if ((req & VM_ALLOC_WIRED) != 0)
1898 atomic_add_int(&vm_cnt.v_wire_count, npages);
1899 if (object != NULL) {
1900 if (object->memattr != VM_MEMATTR_DEFAULT &&
1901 memattr == VM_MEMATTR_DEFAULT)
1902 memattr = object->memattr;
1904 for (m = m_ret; m < &m_ret[npages]; m++) {
1906 m->flags = (m->flags | PG_NODUMP) & flags;
1907 m->busy_lock = busy_lock;
1908 if ((req & VM_ALLOC_WIRED) != 0)
1912 if (object != NULL) {
1913 if (vm_page_insert_after(m, object, pindex, mpred)) {
1914 pagedaemon_wakeup();
1915 if ((req & VM_ALLOC_WIRED) != 0)
1916 atomic_subtract_int(
1917 &vm_cnt.v_wire_count, npages);
1918 KASSERT(m->object == NULL,
1919 ("page %p has object", m));
1921 for (m = m_ret; m < &m_ret[npages]; m++) {
1923 (req & VM_ALLOC_WIRED) != 0)
1925 m->oflags = VPO_UNMANAGED;
1926 m->busy_lock = VPB_UNBUSIED;
1927 /* Don't change PG_ZERO. */
1928 vm_page_free_toq(m);
1930 if (req & VM_ALLOC_WAITFAIL) {
1931 VM_OBJECT_WUNLOCK(object);
1933 VM_OBJECT_WLOCK(object);
1940 if (memattr != VM_MEMATTR_DEFAULT)
1941 pmap_page_set_memattr(m, memattr);
1944 if (vm_paging_needed(vm_cnt.v_free_count))
1945 pagedaemon_wakeup();
1950 * Check a page that has been freshly dequeued from a freelist.
1953 vm_page_alloc_check(vm_page_t m)
1956 KASSERT(m->object == NULL, ("page %p has object", m));
1957 KASSERT(m->queue == PQ_NONE,
1958 ("page %p has unexpected queue %d", m, m->queue));
1959 KASSERT(m->wire_count == 0, ("page %p is wired", m));
1960 KASSERT(m->hold_count == 0, ("page %p is held", m));
1961 KASSERT(!vm_page_busied(m), ("page %p is busy", m));
1962 KASSERT(m->dirty == 0, ("page %p is dirty", m));
1963 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1964 ("page %p has unexpected memattr %d",
1965 m, pmap_page_get_memattr(m)));
1966 KASSERT(m->valid == 0, ("free page %p is valid", m));
1970 * vm_page_alloc_freelist:
1972 * Allocate a physical page from the specified free page list.
1974 * The caller must always specify an allocation class.
1976 * allocation classes:
1977 * VM_ALLOC_NORMAL normal process request
1978 * VM_ALLOC_SYSTEM system *really* needs a page
1979 * VM_ALLOC_INTERRUPT interrupt time request
1981 * optional allocation flags:
1982 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1983 * intends to allocate
1984 * VM_ALLOC_WIRED wire the allocated page
1985 * VM_ALLOC_ZERO prefer a zeroed page
1987 * This routine may not sleep.
1990 vm_page_alloc_freelist(int flind, int req)
1993 u_int flags, free_count;
1996 req_class = req & VM_ALLOC_CLASS_MASK;
1999 * The page daemon is allowed to dig deeper into the free page list.
2001 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2002 req_class = VM_ALLOC_SYSTEM;
2005 * Do not allocate reserved pages unless the req has asked for it.
2008 mtx_lock(&vm_page_queue_free_mtx);
2009 if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
2010 (req_class == VM_ALLOC_SYSTEM &&
2011 vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
2012 (req_class == VM_ALLOC_INTERRUPT &&
2013 vm_cnt.v_free_count > 0)) {
2014 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
2016 if (vm_page_alloc_fail(NULL, req))
2021 mtx_unlock(&vm_page_queue_free_mtx);
2024 free_count = vm_phys_freecnt_adj(m, -1);
2025 mtx_unlock(&vm_page_queue_free_mtx);
2026 vm_page_alloc_check(m);
2029 * Initialize the page. Only the PG_ZERO flag is inherited.
2033 if ((req & VM_ALLOC_ZERO) != 0)
2036 if ((req & VM_ALLOC_WIRED) != 0) {
2038 * The page lock is not required for wiring a page that does
2039 * not belong to an object.
2041 atomic_add_int(&vm_cnt.v_wire_count, 1);
2044 /* Unmanaged pages don't use "act_count". */
2045 m->oflags = VPO_UNMANAGED;
2046 if (vm_paging_needed(free_count))
2047 pagedaemon_wakeup();
2051 #define VPSC_ANY 0 /* No restrictions. */
2052 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2053 #define VPSC_NOSUPER 2 /* Skip superpages. */
2056 * vm_page_scan_contig:
2058 * Scan vm_page_array[] between the specified entries "m_start" and
2059 * "m_end" for a run of contiguous physical pages that satisfy the
2060 * specified conditions, and return the lowest page in the run. The
2061 * specified "alignment" determines the alignment of the lowest physical
2062 * page in the run. If the specified "boundary" is non-zero, then the
2063 * run of physical pages cannot span a physical address that is a
2064 * multiple of "boundary".
2066 * "m_end" is never dereferenced, so it need not point to a vm_page
2067 * structure within vm_page_array[].
2069 * "npages" must be greater than zero. "m_start" and "m_end" must not
2070 * span a hole (or discontiguity) in the physical address space. Both
2071 * "alignment" and "boundary" must be a power of two.
2074 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2075 u_long alignment, vm_paddr_t boundary, int options)
2081 #if VM_NRESERVLEVEL > 0
2084 int m_inc, order, run_ext, run_len;
2086 KASSERT(npages > 0, ("npages is 0"));
2087 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2088 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2092 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2093 KASSERT((m->flags & PG_MARKER) == 0,
2094 ("page %p is PG_MARKER", m));
2095 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->wire_count == 1,
2096 ("fictitious page %p has invalid wire count", m));
2099 * If the current page would be the start of a run, check its
2100 * physical address against the end, alignment, and boundary
2101 * conditions. If it doesn't satisfy these conditions, either
2102 * terminate the scan or advance to the next page that
2103 * satisfies the failed condition.
2106 KASSERT(m_run == NULL, ("m_run != NULL"));
2107 if (m + npages > m_end)
2109 pa = VM_PAGE_TO_PHYS(m);
2110 if ((pa & (alignment - 1)) != 0) {
2111 m_inc = atop(roundup2(pa, alignment) - pa);
2114 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2116 m_inc = atop(roundup2(pa, boundary) - pa);
2120 KASSERT(m_run != NULL, ("m_run == NULL"));
2122 vm_page_change_lock(m, &m_mtx);
2125 if (m->wire_count != 0 || m->hold_count != 0)
2127 #if VM_NRESERVLEVEL > 0
2128 else if ((level = vm_reserv_level(m)) >= 0 &&
2129 (options & VPSC_NORESERV) != 0) {
2131 /* Advance to the end of the reservation. */
2132 pa = VM_PAGE_TO_PHYS(m);
2133 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2137 else if ((object = m->object) != NULL) {
2139 * The page is considered eligible for relocation if
2140 * and only if it could be laundered or reclaimed by
2143 if (!VM_OBJECT_TRYRLOCK(object)) {
2145 VM_OBJECT_RLOCK(object);
2147 if (m->object != object) {
2149 * The page may have been freed.
2151 VM_OBJECT_RUNLOCK(object);
2153 } else if (m->wire_count != 0 ||
2154 m->hold_count != 0) {
2159 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2160 ("page %p is PG_UNHOLDFREE", m));
2161 /* Don't care: PG_NODUMP, PG_ZERO. */
2162 if (object->type != OBJT_DEFAULT &&
2163 object->type != OBJT_SWAP &&
2164 object->type != OBJT_VNODE) {
2166 #if VM_NRESERVLEVEL > 0
2167 } else if ((options & VPSC_NOSUPER) != 0 &&
2168 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2170 /* Advance to the end of the superpage. */
2171 pa = VM_PAGE_TO_PHYS(m);
2172 m_inc = atop(roundup2(pa + 1,
2173 vm_reserv_size(level)) - pa);
2175 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2176 m->queue != PQ_NONE && !vm_page_busied(m)) {
2178 * The page is allocated but eligible for
2179 * relocation. Extend the current run by one
2182 KASSERT(pmap_page_get_memattr(m) ==
2184 ("page %p has an unexpected memattr", m));
2185 KASSERT((m->oflags & (VPO_SWAPINPROG |
2186 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2187 ("page %p has unexpected oflags", m));
2188 /* Don't care: VPO_NOSYNC. */
2193 VM_OBJECT_RUNLOCK(object);
2194 #if VM_NRESERVLEVEL > 0
2195 } else if (level >= 0) {
2197 * The page is reserved but not yet allocated. In
2198 * other words, it is still free. Extend the current
2203 } else if ((order = m->order) < VM_NFREEORDER) {
2205 * The page is enqueued in the physical memory
2206 * allocator's free page queues. Moreover, it is the
2207 * first page in a power-of-two-sized run of
2208 * contiguous free pages. Add these pages to the end
2209 * of the current run, and jump ahead.
2211 run_ext = 1 << order;
2215 * Skip the page for one of the following reasons: (1)
2216 * It is enqueued in the physical memory allocator's
2217 * free page queues. However, it is not the first
2218 * page in a run of contiguous free pages. (This case
2219 * rarely occurs because the scan is performed in
2220 * ascending order.) (2) It is not reserved, and it is
2221 * transitioning from free to allocated. (Conversely,
2222 * the transition from allocated to free for managed
2223 * pages is blocked by the page lock.) (3) It is
2224 * allocated but not contained by an object and not
2225 * wired, e.g., allocated by Xen's balloon driver.
2231 * Extend or reset the current run of pages.
2246 if (run_len >= npages)
2252 * vm_page_reclaim_run:
2254 * Try to relocate each of the allocated virtual pages within the
2255 * specified run of physical pages to a new physical address. Free the
2256 * physical pages underlying the relocated virtual pages. A virtual page
2257 * is relocatable if and only if it could be laundered or reclaimed by
2258 * the page daemon. Whenever possible, a virtual page is relocated to a
2259 * physical address above "high".
2261 * Returns 0 if every physical page within the run was already free or
2262 * just freed by a successful relocation. Otherwise, returns a non-zero
2263 * value indicating why the last attempt to relocate a virtual page was
2266 * "req_class" must be an allocation class.
2269 vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
2273 struct spglist free;
2276 vm_page_t m, m_end, m_new;
2277 int error, order, req;
2279 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2280 ("req_class is not an allocation class"));
2284 m_end = m_run + npages;
2286 for (; error == 0 && m < m_end; m++) {
2287 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2288 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2291 * Avoid releasing and reacquiring the same page lock.
2293 vm_page_change_lock(m, &m_mtx);
2295 if (m->wire_count != 0 || m->hold_count != 0)
2297 else if ((object = m->object) != NULL) {
2299 * The page is relocated if and only if it could be
2300 * laundered or reclaimed by the page daemon.
2302 if (!VM_OBJECT_TRYWLOCK(object)) {
2304 VM_OBJECT_WLOCK(object);
2306 if (m->object != object) {
2308 * The page may have been freed.
2310 VM_OBJECT_WUNLOCK(object);
2312 } else if (m->wire_count != 0 ||
2313 m->hold_count != 0) {
2318 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2319 ("page %p is PG_UNHOLDFREE", m));
2320 /* Don't care: PG_NODUMP, PG_ZERO. */
2321 if (object->type != OBJT_DEFAULT &&
2322 object->type != OBJT_SWAP &&
2323 object->type != OBJT_VNODE)
2325 else if (object->memattr != VM_MEMATTR_DEFAULT)
2327 else if (m->queue != PQ_NONE && !vm_page_busied(m)) {
2328 KASSERT(pmap_page_get_memattr(m) ==
2330 ("page %p has an unexpected memattr", m));
2331 KASSERT((m->oflags & (VPO_SWAPINPROG |
2332 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2333 ("page %p has unexpected oflags", m));
2334 /* Don't care: VPO_NOSYNC. */
2335 if (m->valid != 0) {
2337 * First, try to allocate a new page
2338 * that is above "high". Failing
2339 * that, try to allocate a new page
2340 * that is below "m_run". Allocate
2341 * the new page between the end of
2342 * "m_run" and "high" only as a last
2345 req = req_class | VM_ALLOC_NOOBJ;
2346 if ((m->flags & PG_NODUMP) != 0)
2347 req |= VM_ALLOC_NODUMP;
2348 if (trunc_page(high) !=
2349 ~(vm_paddr_t)PAGE_MASK) {
2350 m_new = vm_page_alloc_contig(
2355 VM_MEMATTR_DEFAULT);
2358 if (m_new == NULL) {
2359 pa = VM_PAGE_TO_PHYS(m_run);
2360 m_new = vm_page_alloc_contig(
2362 0, pa - 1, PAGE_SIZE, 0,
2363 VM_MEMATTR_DEFAULT);
2365 if (m_new == NULL) {
2367 m_new = vm_page_alloc_contig(
2369 pa, high, PAGE_SIZE, 0,
2370 VM_MEMATTR_DEFAULT);
2372 if (m_new == NULL) {
2376 KASSERT(m_new->wire_count == 0,
2377 ("page %p is wired", m));
2380 * Replace "m" with the new page. For
2381 * vm_page_replace(), "m" must be busy
2382 * and dequeued. Finally, change "m"
2383 * as if vm_page_free() was called.
2385 if (object->ref_count != 0)
2387 m_new->aflags = m->aflags;
2388 KASSERT(m_new->oflags == VPO_UNMANAGED,
2389 ("page %p is managed", m));
2390 m_new->oflags = m->oflags & VPO_NOSYNC;
2391 pmap_copy_page(m, m_new);
2392 m_new->valid = m->valid;
2393 m_new->dirty = m->dirty;
2394 m->flags &= ~PG_ZERO;
2397 vm_page_replace_checked(m_new, object,
2403 * The new page must be deactivated
2404 * before the object is unlocked.
2406 vm_page_change_lock(m_new, &m_mtx);
2407 vm_page_deactivate(m_new);
2409 m->flags &= ~PG_ZERO;
2412 KASSERT(m->dirty == 0,
2413 ("page %p is dirty", m));
2415 SLIST_INSERT_HEAD(&free, m, plinks.s.ss);
2419 VM_OBJECT_WUNLOCK(object);
2421 mtx_lock(&vm_page_queue_free_mtx);
2423 if (order < VM_NFREEORDER) {
2425 * The page is enqueued in the physical memory
2426 * allocator's free page queues. Moreover, it
2427 * is the first page in a power-of-two-sized
2428 * run of contiguous free pages. Jump ahead
2429 * to the last page within that run, and
2430 * continue from there.
2432 m += (1 << order) - 1;
2434 #if VM_NRESERVLEVEL > 0
2435 else if (vm_reserv_is_page_free(m))
2438 mtx_unlock(&vm_page_queue_free_mtx);
2439 if (order == VM_NFREEORDER)
2445 if ((m = SLIST_FIRST(&free)) != NULL) {
2446 mtx_lock(&vm_page_queue_free_mtx);
2448 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2449 vm_page_free_phys(m);
2450 } while ((m = SLIST_FIRST(&free)) != NULL);
2451 vm_page_free_wakeup();
2452 mtx_unlock(&vm_page_queue_free_mtx);
2459 CTASSERT(powerof2(NRUNS));
2461 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2463 #define MIN_RECLAIM 8
2466 * vm_page_reclaim_contig:
2468 * Reclaim allocated, contiguous physical memory satisfying the specified
2469 * conditions by relocating the virtual pages using that physical memory.
2470 * Returns true if reclamation is successful and false otherwise. Since
2471 * relocation requires the allocation of physical pages, reclamation may
2472 * fail due to a shortage of free pages. When reclamation fails, callers
2473 * are expected to perform VM_WAIT before retrying a failed allocation
2474 * operation, e.g., vm_page_alloc_contig().
2476 * The caller must always specify an allocation class through "req".
2478 * allocation classes:
2479 * VM_ALLOC_NORMAL normal process request
2480 * VM_ALLOC_SYSTEM system *really* needs a page
2481 * VM_ALLOC_INTERRUPT interrupt time request
2483 * The optional allocation flags are ignored.
2485 * "npages" must be greater than zero. Both "alignment" and "boundary"
2486 * must be a power of two.
2489 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2490 u_long alignment, vm_paddr_t boundary)
2492 vm_paddr_t curr_low;
2493 vm_page_t m_run, m_runs[NRUNS];
2494 u_long count, reclaimed;
2495 int error, i, options, req_class;
2497 KASSERT(npages > 0, ("npages is 0"));
2498 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2499 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2500 req_class = req & VM_ALLOC_CLASS_MASK;
2503 * The page daemon is allowed to dig deeper into the free page list.
2505 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2506 req_class = VM_ALLOC_SYSTEM;
2509 * Return if the number of free pages cannot satisfy the requested
2512 count = vm_cnt.v_free_count;
2513 if (count < npages + vm_cnt.v_free_reserved || (count < npages +
2514 vm_cnt.v_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2515 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2519 * Scan up to three times, relaxing the restrictions ("options") on
2520 * the reclamation of reservations and superpages each time.
2522 for (options = VPSC_NORESERV;;) {
2524 * Find the highest runs that satisfy the given constraints
2525 * and restrictions, and record them in "m_runs".
2530 m_run = vm_phys_scan_contig(npages, curr_low, high,
2531 alignment, boundary, options);
2534 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2535 m_runs[RUN_INDEX(count)] = m_run;
2540 * Reclaim the highest runs in LIFO (descending) order until
2541 * the number of reclaimed pages, "reclaimed", is at least
2542 * MIN_RECLAIM. Reset "reclaimed" each time because each
2543 * reclamation is idempotent, and runs will (likely) recur
2544 * from one scan to the next as restrictions are relaxed.
2547 for (i = 0; count > 0 && i < NRUNS; i++) {
2549 m_run = m_runs[RUN_INDEX(count)];
2550 error = vm_page_reclaim_run(req_class, npages, m_run,
2553 reclaimed += npages;
2554 if (reclaimed >= MIN_RECLAIM)
2560 * Either relax the restrictions on the next scan or return if
2561 * the last scan had no restrictions.
2563 if (options == VPSC_NORESERV)
2564 options = VPSC_NOSUPER;
2565 else if (options == VPSC_NOSUPER)
2567 else if (options == VPSC_ANY)
2568 return (reclaimed != 0);
2573 * vm_wait: (also see VM_WAIT macro)
2575 * Sleep until free pages are available for allocation.
2576 * - Called in various places before memory allocations.
2582 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2583 if (curproc == pageproc) {
2584 vm_pageout_pages_needed = 1;
2585 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
2586 PDROP | PSWP, "VMWait", 0);
2588 if (__predict_false(pageproc == NULL))
2589 panic("vm_wait in early boot");
2590 if (!vm_pageout_wanted) {
2591 vm_pageout_wanted = true;
2592 wakeup(&vm_pageout_wanted);
2594 vm_pages_needed = true;
2595 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
2604 mtx_lock(&vm_page_queue_free_mtx);
2609 * vm_page_alloc_fail:
2611 * Called when a page allocation function fails. Informs the
2612 * pagedaemon and performs the requested wait. Requires the
2613 * page_queue_free and object lock on entry. Returns with the
2614 * object lock held and free lock released. Returns an error when
2615 * retry is necessary.
2619 vm_page_alloc_fail(vm_object_t object, int req)
2622 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2624 atomic_add_int(&vm_pageout_deficit,
2625 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
2626 pagedaemon_wakeup();
2627 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
2629 VM_OBJECT_WUNLOCK(object);
2632 VM_OBJECT_WLOCK(object);
2633 if (req & VM_ALLOC_WAITOK)
2636 mtx_unlock(&vm_page_queue_free_mtx);
2641 * vm_waitpfault: (also see VM_WAITPFAULT macro)
2643 * Sleep until free pages are available for allocation.
2644 * - Called only in vm_fault so that processes page faulting
2645 * can be easily tracked.
2646 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2647 * processes will be able to grab memory first. Do not change
2648 * this balance without careful testing first.
2654 mtx_lock(&vm_page_queue_free_mtx);
2655 if (!vm_pageout_wanted) {
2656 vm_pageout_wanted = true;
2657 wakeup(&vm_pageout_wanted);
2659 vm_pages_needed = true;
2660 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
2664 struct vm_pagequeue *
2665 vm_page_pagequeue(vm_page_t m)
2668 if (vm_page_in_laundry(m))
2669 return (&vm_dom[0].vmd_pagequeues[m->queue]);
2671 return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2677 * Remove the given page from its current page queue.
2679 * The page must be locked.
2682 vm_page_dequeue(vm_page_t m)
2684 struct vm_pagequeue *pq;
2686 vm_page_assert_locked(m);
2687 KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
2689 pq = vm_page_pagequeue(m);
2690 vm_pagequeue_lock(pq);
2692 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2693 vm_pagequeue_cnt_dec(pq);
2694 vm_pagequeue_unlock(pq);
2698 * vm_page_dequeue_locked:
2700 * Remove the given page from its current page queue.
2702 * The page and page queue must be locked.
2705 vm_page_dequeue_locked(vm_page_t m)
2707 struct vm_pagequeue *pq;
2709 vm_page_lock_assert(m, MA_OWNED);
2710 pq = vm_page_pagequeue(m);
2711 vm_pagequeue_assert_locked(pq);
2713 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2714 vm_pagequeue_cnt_dec(pq);
2720 * Add the given page to the specified page queue.
2722 * The page must be locked.
2725 vm_page_enqueue(uint8_t queue, vm_page_t m)
2727 struct vm_pagequeue *pq;
2729 vm_page_lock_assert(m, MA_OWNED);
2730 KASSERT(queue < PQ_COUNT,
2731 ("vm_page_enqueue: invalid queue %u request for page %p",
2733 if (queue == PQ_LAUNDRY || queue == PQ_UNSWAPPABLE)
2734 pq = &vm_dom[0].vmd_pagequeues[queue];
2736 pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2737 vm_pagequeue_lock(pq);
2739 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2740 vm_pagequeue_cnt_inc(pq);
2741 vm_pagequeue_unlock(pq);
2747 * Move the given page to the tail of its current page queue.
2749 * The page must be locked.
2752 vm_page_requeue(vm_page_t m)
2754 struct vm_pagequeue *pq;
2756 vm_page_lock_assert(m, MA_OWNED);
2757 KASSERT(m->queue != PQ_NONE,
2758 ("vm_page_requeue: page %p is not queued", m));
2759 pq = vm_page_pagequeue(m);
2760 vm_pagequeue_lock(pq);
2761 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2762 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2763 vm_pagequeue_unlock(pq);
2767 * vm_page_requeue_locked:
2769 * Move the given page to the tail of its current page queue.
2771 * The page queue must be locked.
2774 vm_page_requeue_locked(vm_page_t m)
2776 struct vm_pagequeue *pq;
2778 KASSERT(m->queue != PQ_NONE,
2779 ("vm_page_requeue_locked: page %p is not queued", m));
2780 pq = vm_page_pagequeue(m);
2781 vm_pagequeue_assert_locked(pq);
2782 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2783 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2789 * Put the specified page on the active list (if appropriate).
2790 * Ensure that act_count is at least ACT_INIT but do not otherwise
2793 * The page must be locked.
2796 vm_page_activate(vm_page_t m)
2800 vm_page_lock_assert(m, MA_OWNED);
2801 if ((queue = m->queue) != PQ_ACTIVE) {
2802 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2803 if (m->act_count < ACT_INIT)
2804 m->act_count = ACT_INIT;
2805 if (queue != PQ_NONE)
2807 vm_page_enqueue(PQ_ACTIVE, m);
2809 KASSERT(queue == PQ_NONE,
2810 ("vm_page_activate: wired page %p is queued", m));
2812 if (m->act_count < ACT_INIT)
2813 m->act_count = ACT_INIT;
2818 * vm_page_free_wakeup:
2820 * Helper routine for vm_page_free_toq(). This routine is called
2821 * when a page is added to the free queues.
2823 * The page queues must be locked.
2826 vm_page_free_wakeup(void)
2829 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2831 * if pageout daemon needs pages, then tell it that there are
2834 if (vm_pageout_pages_needed &&
2835 vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
2836 wakeup(&vm_pageout_pages_needed);
2837 vm_pageout_pages_needed = 0;
2840 * wakeup processes that are waiting on memory if we hit a
2841 * high water mark. And wakeup scheduler process if we have
2842 * lots of memory. this process will swapin processes.
2844 if (vm_pages_needed && !vm_page_count_min()) {
2845 vm_pages_needed = false;
2846 wakeup(&vm_cnt.v_free_count);
2851 * vm_page_free_prep:
2853 * Prepares the given page to be put on the free list,
2854 * disassociating it from any VM object. The caller may return
2855 * the page to the free list only if this function returns true.
2857 * The object must be locked. The page must be locked if it is
2858 * managed. For a queued managed page, the pagequeue_locked
2859 * argument specifies whether the page queue is already locked.
2862 vm_page_free_prep(vm_page_t m, bool pagequeue_locked)
2865 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
2866 if ((m->flags & PG_ZERO) != 0) {
2869 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
2870 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
2871 KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
2872 m, i, (uintmax_t)*p));
2875 if ((m->oflags & VPO_UNMANAGED) == 0) {
2876 vm_page_lock_assert(m, MA_OWNED);
2877 KASSERT(!pmap_page_is_mapped(m),
2878 ("vm_page_free_toq: freeing mapped page %p", m));
2880 KASSERT(m->queue == PQ_NONE,
2881 ("vm_page_free_toq: unmanaged page %p is queued", m));
2882 VM_CNT_INC(v_tfree);
2884 if (vm_page_sbusied(m))
2885 panic("vm_page_free: freeing busy page %p", m);
2890 * If fictitious remove object association and
2893 if ((m->flags & PG_FICTITIOUS) != 0) {
2894 KASSERT(m->wire_count == 1,
2895 ("fictitious page %p is not wired", m));
2896 KASSERT(m->queue == PQ_NONE,
2897 ("fictitious page %p is queued", m));
2901 if (m->queue != PQ_NONE) {
2902 if (pagequeue_locked)
2903 vm_page_dequeue_locked(m);
2910 if (m->wire_count != 0)
2911 panic("vm_page_free: freeing wired page %p", m);
2912 if (m->hold_count != 0) {
2913 m->flags &= ~PG_ZERO;
2914 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2915 ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
2916 m->flags |= PG_UNHOLDFREE;
2921 * Restore the default memory attribute to the page.
2923 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2924 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2930 * Insert the page into the physical memory allocator's free page
2931 * queues. This is the last step to free a page.
2934 vm_page_free_phys(vm_page_t m)
2937 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2939 vm_phys_freecnt_adj(m, 1);
2940 #if VM_NRESERVLEVEL > 0
2941 if (!vm_reserv_free_page(m))
2943 vm_phys_free_pages(m, 0);
2947 vm_page_free_phys_pglist(struct pglist *tq)
2951 if (TAILQ_EMPTY(tq))
2953 mtx_lock(&vm_page_queue_free_mtx);
2954 TAILQ_FOREACH(m, tq, listq)
2955 vm_page_free_phys(m);
2956 vm_page_free_wakeup();
2957 mtx_unlock(&vm_page_queue_free_mtx);
2963 * Returns the given page to the free list, disassociating it
2964 * from any VM object.
2966 * The object must be locked. The page must be locked if it is
2970 vm_page_free_toq(vm_page_t m)
2973 if (!vm_page_free_prep(m, false))
2975 mtx_lock(&vm_page_queue_free_mtx);
2976 vm_page_free_phys(m);
2977 vm_page_free_wakeup();
2978 mtx_unlock(&vm_page_queue_free_mtx);
2984 * Mark this page as wired down by yet
2985 * another map, removing it from paging queues
2988 * If the page is fictitious, then its wire count must remain one.
2990 * The page must be locked.
2993 vm_page_wire(vm_page_t m)
2997 * Only bump the wire statistics if the page is not already wired,
2998 * and only unqueue the page if it is on some queue (if it is unmanaged
2999 * it is already off the queues).
3001 vm_page_lock_assert(m, MA_OWNED);
3002 if ((m->flags & PG_FICTITIOUS) != 0) {
3003 KASSERT(m->wire_count == 1,
3004 ("vm_page_wire: fictitious page %p's wire count isn't one",
3008 if (m->wire_count == 0) {
3009 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
3010 m->queue == PQ_NONE,
3011 ("vm_page_wire: unmanaged page %p is queued", m));
3013 atomic_add_int(&vm_cnt.v_wire_count, 1);
3016 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
3022 * Release one wiring of the specified page, potentially allowing it to be
3023 * paged out. Returns TRUE if the number of wirings transitions to zero and
3026 * Only managed pages belonging to an object can be paged out. If the number
3027 * of wirings transitions to zero and the page is eligible for page out, then
3028 * the page is added to the specified paging queue (unless PQ_NONE is
3031 * If a page is fictitious, then its wire count must always be one.
3033 * A managed page must be locked.
3036 vm_page_unwire(vm_page_t m, uint8_t queue)
3039 KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
3040 ("vm_page_unwire: invalid queue %u request for page %p",
3042 if ((m->oflags & VPO_UNMANAGED) == 0)
3043 vm_page_assert_locked(m);
3044 if ((m->flags & PG_FICTITIOUS) != 0) {
3045 KASSERT(m->wire_count == 1,
3046 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
3049 if (m->wire_count > 0) {
3051 if (m->wire_count == 0) {
3052 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3053 if ((m->oflags & VPO_UNMANAGED) == 0 &&
3054 m->object != NULL && queue != PQ_NONE)
3055 vm_page_enqueue(queue, m);
3060 panic("vm_page_unwire: page %p's wire count is zero", m);
3064 * Move the specified page to the inactive queue.
3066 * Normally, "noreuse" is FALSE, resulting in LRU ordering of the inactive
3067 * queue. However, setting "noreuse" to TRUE will accelerate the specified
3068 * page's reclamation, but it will not unmap the page from any address space.
3069 * This is implemented by inserting the page near the head of the inactive
3070 * queue, using a marker page to guide FIFO insertion ordering.
3072 * The page must be locked.
3075 _vm_page_deactivate(vm_page_t m, boolean_t noreuse)
3077 struct vm_pagequeue *pq;
3080 vm_page_assert_locked(m);
3083 * Ignore if the page is already inactive, unless it is unlikely to be
3086 if ((queue = m->queue) == PQ_INACTIVE && !noreuse)
3088 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
3089 pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
3090 /* Avoid multiple acquisitions of the inactive queue lock. */
3091 if (queue == PQ_INACTIVE) {
3092 vm_pagequeue_lock(pq);
3093 vm_page_dequeue_locked(m);
3095 if (queue != PQ_NONE)
3097 vm_pagequeue_lock(pq);
3099 m->queue = PQ_INACTIVE;
3101 TAILQ_INSERT_BEFORE(&vm_phys_domain(m)->vmd_inacthead,
3104 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3105 vm_pagequeue_cnt_inc(pq);
3106 vm_pagequeue_unlock(pq);
3111 * Move the specified page to the inactive queue.
3113 * The page must be locked.
3116 vm_page_deactivate(vm_page_t m)
3119 _vm_page_deactivate(m, FALSE);
3123 * Move the specified page to the inactive queue with the expectation
3124 * that it is unlikely to be reused.
3126 * The page must be locked.
3129 vm_page_deactivate_noreuse(vm_page_t m)
3132 _vm_page_deactivate(m, TRUE);
3138 * Put a page in the laundry.
3141 vm_page_launder(vm_page_t m)
3145 vm_page_assert_locked(m);
3146 if ((queue = m->queue) != PQ_LAUNDRY) {
3147 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
3148 if (queue != PQ_NONE)
3150 vm_page_enqueue(PQ_LAUNDRY, m);
3152 KASSERT(queue == PQ_NONE,
3153 ("wired page %p is queued", m));
3158 * vm_page_unswappable
3160 * Put a page in the PQ_UNSWAPPABLE holding queue.
3163 vm_page_unswappable(vm_page_t m)
3166 vm_page_assert_locked(m);
3167 KASSERT(m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0,
3168 ("page %p already unswappable", m));
3169 if (m->queue != PQ_NONE)
3171 vm_page_enqueue(PQ_UNSWAPPABLE, m);
3175 * Attempt to free the page. If it cannot be freed, do nothing. Returns true
3176 * if the page is freed and false otherwise.
3178 * The page must be managed. The page and its containing object must be
3182 vm_page_try_to_free(vm_page_t m)
3185 vm_page_assert_locked(m);
3186 VM_OBJECT_ASSERT_WLOCKED(m->object);
3187 KASSERT((m->oflags & VPO_UNMANAGED) == 0, ("page %p is unmanaged", m));
3188 if (m->dirty != 0 || m->hold_count != 0 || m->wire_count != 0 ||
3191 if (m->object->ref_count != 0) {
3203 * Apply the specified advice to the given page.
3205 * The object and page must be locked.
3208 vm_page_advise(vm_page_t m, int advice)
3211 vm_page_assert_locked(m);
3212 VM_OBJECT_ASSERT_WLOCKED(m->object);
3213 if (advice == MADV_FREE)
3215 * Mark the page clean. This will allow the page to be freed
3216 * without first paging it out. MADV_FREE pages are often
3217 * quickly reused by malloc(3), so we do not do anything that
3218 * would result in a page fault on a later access.
3221 else if (advice != MADV_DONTNEED) {
3222 if (advice == MADV_WILLNEED)
3223 vm_page_activate(m);
3228 * Clear any references to the page. Otherwise, the page daemon will
3229 * immediately reactivate the page.
3231 vm_page_aflag_clear(m, PGA_REFERENCED);
3233 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3237 * Place clean pages near the head of the inactive queue rather than
3238 * the tail, thus defeating the queue's LRU operation and ensuring that
3239 * the page will be reused quickly. Dirty pages not already in the
3240 * laundry are moved there.
3243 vm_page_deactivate_noreuse(m);
3249 * Grab a page, waiting until we are waken up due to the page
3250 * changing state. We keep on waiting, if the page continues
3251 * to be in the object. If the page doesn't exist, first allocate it
3252 * and then conditionally zero it.
3254 * This routine may sleep.
3256 * The object must be locked on entry. The lock will, however, be released
3257 * and reacquired if the routine sleeps.
3260 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3266 VM_OBJECT_ASSERT_WLOCKED(object);
3267 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3268 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3269 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3270 pflags = allocflags &
3271 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
3272 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3273 pflags |= VM_ALLOC_WAITFAIL;
3275 if ((m = vm_page_lookup(object, pindex)) != NULL) {
3276 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3277 vm_page_xbusied(m) : vm_page_busied(m);
3279 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3282 * Reference the page before unlocking and
3283 * sleeping so that the page daemon is less
3284 * likely to reclaim it.
3286 vm_page_aflag_set(m, PGA_REFERENCED);
3288 VM_OBJECT_WUNLOCK(object);
3289 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
3290 VM_ALLOC_IGN_SBUSY) != 0);
3291 VM_OBJECT_WLOCK(object);
3294 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3300 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3302 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3307 m = vm_page_alloc(object, pindex, pflags);
3309 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3313 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3319 * Return the specified range of pages from the given object. For each
3320 * page offset within the range, if a page already exists within the object
3321 * at that offset and it is busy, then wait for it to change state. If,
3322 * instead, the page doesn't exist, then allocate it.
3324 * The caller must always specify an allocation class.
3326 * allocation classes:
3327 * VM_ALLOC_NORMAL normal process request
3328 * VM_ALLOC_SYSTEM system *really* needs the pages
3330 * The caller must always specify that the pages are to be busied and/or
3333 * optional allocation flags:
3334 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
3335 * VM_ALLOC_NOBUSY do not exclusive busy the page
3336 * VM_ALLOC_NOWAIT do not sleep
3337 * VM_ALLOC_SBUSY set page to sbusy state
3338 * VM_ALLOC_WIRED wire the pages
3339 * VM_ALLOC_ZERO zero and validate any invalid pages
3341 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
3342 * may return a partial prefix of the requested range.
3345 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
3346 vm_page_t *ma, int count)
3353 VM_OBJECT_ASSERT_WLOCKED(object);
3354 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
3355 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
3356 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
3357 (allocflags & VM_ALLOC_WIRED) != 0,
3358 ("vm_page_grab_pages: the pages must be busied or wired"));
3359 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3360 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3361 ("vm_page_grab_pages: VM_ALLOC_SBUSY/IGN_SBUSY mismatch"));
3364 pflags = allocflags & ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK |
3365 VM_ALLOC_WAITFAIL | VM_ALLOC_IGN_SBUSY);
3366 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3367 pflags |= VM_ALLOC_WAITFAIL;
3370 m = vm_radix_lookup_le(&object->rtree, pindex + i);
3371 if (m == NULL || m->pindex != pindex + i) {
3375 mpred = TAILQ_PREV(m, pglist, listq);
3376 for (; i < count; i++) {
3378 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3379 vm_page_xbusied(m) : vm_page_busied(m);
3381 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3384 * Reference the page before unlocking and
3385 * sleeping so that the page daemon is less
3386 * likely to reclaim it.
3388 vm_page_aflag_set(m, PGA_REFERENCED);
3390 VM_OBJECT_WUNLOCK(object);
3391 vm_page_busy_sleep(m, "grbmaw", (allocflags &
3392 VM_ALLOC_IGN_SBUSY) != 0);
3393 VM_OBJECT_WLOCK(object);
3396 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3401 if ((allocflags & (VM_ALLOC_NOBUSY |
3402 VM_ALLOC_SBUSY)) == 0)
3404 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3407 m = vm_page_alloc_after(object, pindex + i,
3408 pflags | VM_ALLOC_COUNT(count - i), mpred);
3410 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3415 if (m->valid == 0 && (allocflags & VM_ALLOC_ZERO) != 0) {
3416 if ((m->flags & PG_ZERO) == 0)
3418 m->valid = VM_PAGE_BITS_ALL;
3421 m = vm_page_next(m);
3427 * Mapping function for valid or dirty bits in a page.
3429 * Inputs are required to range within a page.
3432 vm_page_bits(int base, int size)
3438 base + size <= PAGE_SIZE,
3439 ("vm_page_bits: illegal base/size %d/%d", base, size)
3442 if (size == 0) /* handle degenerate case */
3445 first_bit = base >> DEV_BSHIFT;
3446 last_bit = (base + size - 1) >> DEV_BSHIFT;
3448 return (((vm_page_bits_t)2 << last_bit) -
3449 ((vm_page_bits_t)1 << first_bit));
3453 * vm_page_set_valid_range:
3455 * Sets portions of a page valid. The arguments are expected
3456 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3457 * of any partial chunks touched by the range. The invalid portion of
3458 * such chunks will be zeroed.
3460 * (base + size) must be less then or equal to PAGE_SIZE.
3463 vm_page_set_valid_range(vm_page_t m, int base, int size)
3467 VM_OBJECT_ASSERT_WLOCKED(m->object);
3468 if (size == 0) /* handle degenerate case */
3472 * If the base is not DEV_BSIZE aligned and the valid
3473 * bit is clear, we have to zero out a portion of the
3476 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3477 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
3478 pmap_zero_page_area(m, frag, base - frag);
3481 * If the ending offset is not DEV_BSIZE aligned and the
3482 * valid bit is clear, we have to zero out a portion of
3485 endoff = base + size;
3486 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3487 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
3488 pmap_zero_page_area(m, endoff,
3489 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3492 * Assert that no previously invalid block that is now being validated
3495 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
3496 ("vm_page_set_valid_range: page %p is dirty", m));
3499 * Set valid bits inclusive of any overlap.
3501 m->valid |= vm_page_bits(base, size);
3505 * Clear the given bits from the specified page's dirty field.
3507 static __inline void
3508 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
3511 #if PAGE_SIZE < 16384
3516 * If the object is locked and the page is neither exclusive busy nor
3517 * write mapped, then the page's dirty field cannot possibly be
3518 * set by a concurrent pmap operation.
3520 VM_OBJECT_ASSERT_WLOCKED(m->object);
3521 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
3522 m->dirty &= ~pagebits;
3525 * The pmap layer can call vm_page_dirty() without
3526 * holding a distinguished lock. The combination of
3527 * the object's lock and an atomic operation suffice
3528 * to guarantee consistency of the page dirty field.
3530 * For PAGE_SIZE == 32768 case, compiler already
3531 * properly aligns the dirty field, so no forcible
3532 * alignment is needed. Only require existence of
3533 * atomic_clear_64 when page size is 32768.
3535 addr = (uintptr_t)&m->dirty;
3536 #if PAGE_SIZE == 32768
3537 atomic_clear_64((uint64_t *)addr, pagebits);
3538 #elif PAGE_SIZE == 16384
3539 atomic_clear_32((uint32_t *)addr, pagebits);
3540 #else /* PAGE_SIZE <= 8192 */
3542 * Use a trick to perform a 32-bit atomic on the
3543 * containing aligned word, to not depend on the existence
3544 * of atomic_clear_{8, 16}.
3546 shift = addr & (sizeof(uint32_t) - 1);
3547 #if BYTE_ORDER == BIG_ENDIAN
3548 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
3552 addr &= ~(sizeof(uint32_t) - 1);
3553 atomic_clear_32((uint32_t *)addr, pagebits << shift);
3554 #endif /* PAGE_SIZE */
3559 * vm_page_set_validclean:
3561 * Sets portions of a page valid and clean. The arguments are expected
3562 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3563 * of any partial chunks touched by the range. The invalid portion of
3564 * such chunks will be zero'd.
3566 * (base + size) must be less then or equal to PAGE_SIZE.
3569 vm_page_set_validclean(vm_page_t m, int base, int size)
3571 vm_page_bits_t oldvalid, pagebits;
3574 VM_OBJECT_ASSERT_WLOCKED(m->object);
3575 if (size == 0) /* handle degenerate case */
3579 * If the base is not DEV_BSIZE aligned and the valid
3580 * bit is clear, we have to zero out a portion of the
3583 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3584 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
3585 pmap_zero_page_area(m, frag, base - frag);
3588 * If the ending offset is not DEV_BSIZE aligned and the
3589 * valid bit is clear, we have to zero out a portion of
3592 endoff = base + size;
3593 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3594 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
3595 pmap_zero_page_area(m, endoff,
3596 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3599 * Set valid, clear dirty bits. If validating the entire
3600 * page we can safely clear the pmap modify bit. We also
3601 * use this opportunity to clear the VPO_NOSYNC flag. If a process
3602 * takes a write fault on a MAP_NOSYNC memory area the flag will
3605 * We set valid bits inclusive of any overlap, but we can only
3606 * clear dirty bits for DEV_BSIZE chunks that are fully within
3609 oldvalid = m->valid;
3610 pagebits = vm_page_bits(base, size);
3611 m->valid |= pagebits;
3613 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
3614 frag = DEV_BSIZE - frag;
3620 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
3622 if (base == 0 && size == PAGE_SIZE) {
3624 * The page can only be modified within the pmap if it is
3625 * mapped, and it can only be mapped if it was previously
3628 if (oldvalid == VM_PAGE_BITS_ALL)
3630 * Perform the pmap_clear_modify() first. Otherwise,
3631 * a concurrent pmap operation, such as
3632 * pmap_protect(), could clear a modification in the
3633 * pmap and set the dirty field on the page before
3634 * pmap_clear_modify() had begun and after the dirty
3635 * field was cleared here.
3637 pmap_clear_modify(m);
3639 m->oflags &= ~VPO_NOSYNC;
3640 } else if (oldvalid != VM_PAGE_BITS_ALL)
3641 m->dirty &= ~pagebits;
3643 vm_page_clear_dirty_mask(m, pagebits);
3647 vm_page_clear_dirty(vm_page_t m, int base, int size)
3650 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
3654 * vm_page_set_invalid:
3656 * Invalidates DEV_BSIZE'd chunks within a page. Both the
3657 * valid and dirty bits for the effected areas are cleared.
3660 vm_page_set_invalid(vm_page_t m, int base, int size)
3662 vm_page_bits_t bits;
3666 VM_OBJECT_ASSERT_WLOCKED(object);
3667 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
3668 size >= object->un_pager.vnp.vnp_size)
3669 bits = VM_PAGE_BITS_ALL;
3671 bits = vm_page_bits(base, size);
3672 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
3675 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3676 !pmap_page_is_mapped(m),
3677 ("vm_page_set_invalid: page %p is mapped", m));
3683 * vm_page_zero_invalid()
3685 * The kernel assumes that the invalid portions of a page contain
3686 * garbage, but such pages can be mapped into memory by user code.
3687 * When this occurs, we must zero out the non-valid portions of the
3688 * page so user code sees what it expects.
3690 * Pages are most often semi-valid when the end of a file is mapped
3691 * into memory and the file's size is not page aligned.
3694 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3699 VM_OBJECT_ASSERT_WLOCKED(m->object);
3701 * Scan the valid bits looking for invalid sections that
3702 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
3703 * valid bit may be set ) have already been zeroed by
3704 * vm_page_set_validclean().
3706 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3707 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3708 (m->valid & ((vm_page_bits_t)1 << i))) {
3710 pmap_zero_page_area(m,
3711 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3718 * setvalid is TRUE when we can safely set the zero'd areas
3719 * as being valid. We can do this if there are no cache consistancy
3720 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3723 m->valid = VM_PAGE_BITS_ALL;
3729 * Is (partial) page valid? Note that the case where size == 0
3730 * will return FALSE in the degenerate case where the page is
3731 * entirely invalid, and TRUE otherwise.
3734 vm_page_is_valid(vm_page_t m, int base, int size)
3736 vm_page_bits_t bits;
3738 VM_OBJECT_ASSERT_LOCKED(m->object);
3739 bits = vm_page_bits(base, size);
3740 return (m->valid != 0 && (m->valid & bits) == bits);
3744 * Returns true if all of the specified predicates are true for the entire
3745 * (super)page and false otherwise.
3748 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
3754 VM_OBJECT_ASSERT_LOCKED(object);
3755 npages = atop(pagesizes[m->psind]);
3758 * The physically contiguous pages that make up a superpage, i.e., a
3759 * page with a page size index ("psind") greater than zero, will
3760 * occupy adjacent entries in vm_page_array[].
3762 for (i = 0; i < npages; i++) {
3763 /* Always test object consistency, including "skip_m". */
3764 if (m[i].object != object)
3766 if (&m[i] == skip_m)
3768 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
3770 if ((flags & PS_ALL_DIRTY) != 0) {
3772 * Calling vm_page_test_dirty() or pmap_is_modified()
3773 * might stop this case from spuriously returning
3774 * "false". However, that would require a write lock
3775 * on the object containing "m[i]".
3777 if (m[i].dirty != VM_PAGE_BITS_ALL)
3780 if ((flags & PS_ALL_VALID) != 0 &&
3781 m[i].valid != VM_PAGE_BITS_ALL)
3788 * Set the page's dirty bits if the page is modified.
3791 vm_page_test_dirty(vm_page_t m)
3794 VM_OBJECT_ASSERT_WLOCKED(m->object);
3795 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3800 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3803 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3807 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3810 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3814 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3817 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3820 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3822 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3825 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3829 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3832 mtx_assert_(vm_page_lockptr(m), a, file, line);
3838 vm_page_object_lock_assert(vm_page_t m)
3842 * Certain of the page's fields may only be modified by the
3843 * holder of the containing object's lock or the exclusive busy.
3844 * holder. Unfortunately, the holder of the write busy is
3845 * not recorded, and thus cannot be checked here.
3847 if (m->object != NULL && !vm_page_xbusied(m))
3848 VM_OBJECT_ASSERT_WLOCKED(m->object);
3852 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3855 if ((bits & PGA_WRITEABLE) == 0)
3859 * The PGA_WRITEABLE flag can only be set if the page is
3860 * managed, is exclusively busied or the object is locked.
3861 * Currently, this flag is only set by pmap_enter().
3863 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3864 ("PGA_WRITEABLE on unmanaged page"));
3865 if (!vm_page_xbusied(m))
3866 VM_OBJECT_ASSERT_LOCKED(m->object);
3870 #include "opt_ddb.h"
3872 #include <sys/kernel.h>
3874 #include <ddb/ddb.h>
3876 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3879 db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
3880 db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
3881 db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
3882 db_printf("vm_cnt.v_laundry_count: %d\n", vm_cnt.v_laundry_count);
3883 db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
3884 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
3885 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
3886 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
3887 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
3890 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3894 db_printf("pq_free %d\n", vm_cnt.v_free_count);
3895 for (dom = 0; dom < vm_ndomains; dom++) {
3897 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
3899 vm_dom[dom].vmd_page_count,
3900 vm_dom[dom].vmd_free_count,
3901 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3902 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
3903 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
3904 vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
3908 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3914 db_printf("show pginfo addr\n");
3918 phys = strchr(modif, 'p') != NULL;
3920 m = PHYS_TO_VM_PAGE(addr);
3922 m = (vm_page_t)addr;
3924 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3925 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3926 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3927 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3928 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);