2 * SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)
4 * Copyright (c) 1991 Regents of the University of California.
6 * Copyright (c) 1998 Matthew Dillon. All Rights Reserved.
8 * This code is derived from software contributed to Berkeley by
9 * The Mach Operating System project at Carnegie-Mellon University.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * from: @(#)vm_page.c 7.4 (Berkeley) 5/7/91
39 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
40 * All rights reserved.
42 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
44 * Permission to use, copy, modify and distribute this software and
45 * its documentation is hereby granted, provided that both the copyright
46 * notice and this permission notice appear in all copies of the
47 * software, derivative works or modified versions, and any portions
48 * thereof, and that both notices appear in supporting documentation.
50 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
51 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
52 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
54 * Carnegie Mellon requests users of this software to return to
56 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
57 * School of Computer Science
58 * Carnegie Mellon University
59 * Pittsburgh PA 15213-3890
61 * any improvements or extensions that they make and grant Carnegie the
62 * rights to redistribute these changes.
66 * GENERAL RULES ON VM_PAGE MANIPULATION
68 * - A page queue lock is required when adding or removing a page from a
69 * page queue regardless of other locks or the busy state of a page.
71 * * In general, no thread besides the page daemon can acquire or
72 * hold more than one page queue lock at a time.
74 * * The page daemon can acquire and hold any pair of page queue
77 * - The object lock is required when inserting or removing
78 * pages from an object (vm_page_insert() or vm_page_remove()).
83 * Resident memory management module.
86 #include <sys/cdefs.h>
87 __FBSDID("$FreeBSD$");
91 #include <sys/param.h>
92 #include <sys/systm.h>
94 #include <sys/domainset.h>
95 #include <sys/kernel.h>
96 #include <sys/limits.h>
97 #include <sys/linker.h>
98 #include <sys/malloc.h>
100 #include <sys/msgbuf.h>
101 #include <sys/mutex.h>
102 #include <sys/proc.h>
103 #include <sys/rwlock.h>
104 #include <sys/sbuf.h>
106 #include <sys/sysctl.h>
107 #include <sys/vmmeter.h>
108 #include <sys/vnode.h>
112 #include <vm/vm_param.h>
113 #include <vm/vm_domainset.h>
114 #include <vm/vm_kern.h>
115 #include <vm/vm_object.h>
116 #include <vm/vm_page.h>
117 #include <vm/vm_pageout.h>
118 #include <vm/vm_pager.h>
119 #include <vm/vm_phys.h>
120 #include <vm/vm_radix.h>
121 #include <vm/vm_reserv.h>
122 #include <vm/vm_extern.h>
124 #include <vm/uma_int.h>
126 #include <machine/md_var.h>
129 * Associated with page of user-allocatable memory is a
133 struct vm_domain vm_dom[MAXMEMDOM];
134 struct mtx_padalign __exclusive_cache_line vm_page_queue_free_mtx;
136 struct mtx_padalign __exclusive_cache_line pa_lock[PA_LOCK_COUNT];
139 * bogus page -- for I/O to/from partially complete buffers,
140 * or for paging into sparsely invalid regions.
142 vm_page_t bogus_page;
144 vm_page_t vm_page_array;
145 long vm_page_array_size;
148 static int boot_pages = UMA_BOOT_PAGES;
149 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
151 "number of pages allocated for bootstrapping the VM system");
153 static int pa_tryrelock_restart;
154 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
155 &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
157 static TAILQ_HEAD(, vm_page) blacklist_head;
158 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
159 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
160 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
162 /* Is the page daemon waiting for free pages? */
163 static int vm_pageout_pages_needed;
165 static uma_zone_t fakepg_zone;
167 static void vm_page_alloc_check(vm_page_t m);
168 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
169 static void vm_page_enqueue(uint8_t queue, vm_page_t m);
170 static void vm_page_free_phys(vm_page_t m);
171 static void vm_page_free_wakeup(void);
172 static void vm_page_init(void *dummy);
173 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
174 vm_pindex_t pindex, vm_page_t mpred);
175 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
177 static int vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
179 static int vm_page_alloc_fail(vm_object_t object, int req);
181 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
184 vm_page_init(void *dummy)
187 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
188 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
189 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
190 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
193 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
194 #if PAGE_SIZE == 32768
196 CTASSERT(sizeof(u_long) >= 8);
201 * Try to acquire a physical address lock while a pmap is locked. If we
202 * fail to trylock we unlock and lock the pmap directly and cache the
203 * locked pa in *locked. The caller should then restart their loop in case
204 * the virtual to physical mapping has changed.
207 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
214 PA_LOCK_ASSERT(lockpa, MA_OWNED);
215 if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
222 atomic_add_int(&pa_tryrelock_restart, 1);
231 * Sets the page size, perhaps based upon the memory
232 * size. Must be called before any use of page-size
233 * dependent functions.
236 vm_set_page_size(void)
238 if (vm_cnt.v_page_size == 0)
239 vm_cnt.v_page_size = PAGE_SIZE;
240 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
241 panic("vm_set_page_size: page size not a power of two");
245 * vm_page_blacklist_next:
247 * Find the next entry in the provided string of blacklist
248 * addresses. Entries are separated by space, comma, or newline.
249 * If an invalid integer is encountered then the rest of the
250 * string is skipped. Updates the list pointer to the next
251 * character, or NULL if the string is exhausted or invalid.
254 vm_page_blacklist_next(char **list, char *end)
259 if (list == NULL || *list == NULL)
267 * If there's no end pointer then the buffer is coming from
268 * the kenv and we know it's null-terminated.
271 end = *list + strlen(*list);
273 /* Ensure that strtoq() won't walk off the end */
275 if (*end == '\n' || *end == ' ' || *end == ',')
278 printf("Blacklist not terminated, skipping\n");
284 for (pos = *list; *pos != '\0'; pos = cp) {
285 bad = strtoq(pos, &cp, 0);
286 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
295 if (*cp == '\0' || ++cp >= end)
299 return (trunc_page(bad));
301 printf("Garbage in RAM blacklist, skipping\n");
307 * vm_page_blacklist_check:
309 * Iterate through the provided string of blacklist addresses, pulling
310 * each entry out of the physical allocator free list and putting it
311 * onto a list for reporting via the vm.page_blacklist sysctl.
314 vm_page_blacklist_check(char *list, char *end)
322 while (next != NULL) {
323 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
325 m = vm_phys_paddr_to_vm_page(pa);
328 mtx_lock(&vm_page_queue_free_mtx);
329 ret = vm_phys_unfree_page(m);
330 mtx_unlock(&vm_page_queue_free_mtx);
332 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
334 printf("Skipping page with pa 0x%jx\n",
341 * vm_page_blacklist_load:
343 * Search for a special module named "ram_blacklist". It'll be a
344 * plain text file provided by the user via the loader directive
348 vm_page_blacklist_load(char **list, char **end)
357 mod = preload_search_by_type("ram_blacklist");
359 ptr = preload_fetch_addr(mod);
360 len = preload_fetch_size(mod);
371 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
378 error = sysctl_wire_old_buffer(req, 0);
381 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
382 TAILQ_FOREACH(m, &blacklist_head, listq) {
383 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
384 (uintmax_t)m->phys_addr);
387 error = sbuf_finish(&sbuf);
393 vm_page_domain_init(struct vm_domain *vmd)
395 struct vm_pagequeue *pq;
398 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
399 "vm inactive pagequeue";
400 *__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_vcnt) =
401 &vm_cnt.v_inactive_count;
402 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
403 "vm active pagequeue";
404 *__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_vcnt) =
405 &vm_cnt.v_active_count;
406 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
407 "vm laundry pagequeue";
408 *__DECONST(int **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_vcnt) =
409 &vm_cnt.v_laundry_count;
410 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_name) =
411 "vm unswappable pagequeue";
412 /* Unswappable dirty pages are counted as being in the laundry. */
413 *__DECONST(int **, &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_vcnt) =
414 &vm_cnt.v_laundry_count;
415 vmd->vmd_page_count = 0;
416 vmd->vmd_free_count = 0;
418 vmd->vmd_oom = FALSE;
419 for (i = 0; i < PQ_COUNT; i++) {
420 pq = &vmd->vmd_pagequeues[i];
421 TAILQ_INIT(&pq->pq_pl);
422 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
423 MTX_DEF | MTX_DUPOK);
428 * Initialize a physical page in preparation for adding it to the free
432 vm_page_init_page(vm_page_t m, vm_paddr_t pa, int segind)
437 m->busy_lock = VPB_UNBUSIED;
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 (m = seg->first_page, pa = seg->start; pa < seg->end;
698 m++, pa += PAGE_SIZE)
699 vm_page_init_page(m, pa, segind);
702 * Add the segment to the free lists only if it is covered by
703 * one of the ranges in phys_avail. Because we've added the
704 * ranges to the vm_phys_segs array, we can assume that each
705 * segment is either entirely contained in one of the ranges,
706 * or doesn't overlap any of them.
708 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
709 if (seg->start < phys_avail[i] ||
710 seg->end > phys_avail[i + 1])
714 pagecount = (u_long)atop(seg->end - seg->start);
716 mtx_lock(&vm_page_queue_free_mtx);
717 vm_phys_free_contig(m, pagecount);
718 vm_phys_freecnt_adj(m, (int)pagecount);
719 mtx_unlock(&vm_page_queue_free_mtx);
720 vm_cnt.v_page_count += (u_int)pagecount;
722 vmd = &vm_dom[seg->domain];
723 vmd->vmd_page_count += (u_int)pagecount;
724 vmd->vmd_segs |= 1UL << m->segind;
730 * Remove blacklisted pages from the physical memory allocator.
732 TAILQ_INIT(&blacklist_head);
733 vm_page_blacklist_load(&list, &listend);
734 vm_page_blacklist_check(list, listend);
736 list = kern_getenv("vm.blacklist");
737 vm_page_blacklist_check(list, NULL);
740 #if VM_NRESERVLEVEL > 0
742 * Initialize the reservation management system.
747 * Set an initial domain policy for thread0 so that allocations
756 vm_page_reference(vm_page_t m)
759 vm_page_aflag_set(m, PGA_REFERENCED);
763 * vm_page_busy_downgrade:
765 * Downgrade an exclusive busy page into a single shared busy page.
768 vm_page_busy_downgrade(vm_page_t m)
773 vm_page_assert_xbusied(m);
774 locked = mtx_owned(vm_page_lockptr(m));
778 x &= VPB_BIT_WAITERS;
779 if (x != 0 && !locked)
781 if (atomic_cmpset_rel_int(&m->busy_lock,
782 VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1)))
784 if (x != 0 && !locked)
797 * Return a positive value if the page is shared busied, 0 otherwise.
800 vm_page_sbusied(vm_page_t m)
805 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
811 * Shared unbusy a page.
814 vm_page_sunbusy(vm_page_t m)
818 vm_page_lock_assert(m, MA_NOTOWNED);
819 vm_page_assert_sbusied(m);
823 if (VPB_SHARERS(x) > 1) {
824 if (atomic_cmpset_int(&m->busy_lock, x,
829 if ((x & VPB_BIT_WAITERS) == 0) {
830 KASSERT(x == VPB_SHARERS_WORD(1),
831 ("vm_page_sunbusy: invalid lock state"));
832 if (atomic_cmpset_int(&m->busy_lock,
833 VPB_SHARERS_WORD(1), VPB_UNBUSIED))
837 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
838 ("vm_page_sunbusy: invalid lock state for waiters"));
841 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
852 * vm_page_busy_sleep:
854 * Sleep and release the page lock, using the page pointer as wchan.
855 * This is used to implement the hard-path of busying mechanism.
857 * The given page must be locked.
859 * If nonshared is true, sleep only if the page is xbusy.
862 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
866 vm_page_assert_locked(m);
869 if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
870 ((x & VPB_BIT_WAITERS) == 0 &&
871 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
875 msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
881 * Try to shared busy a page.
882 * If the operation succeeds 1 is returned otherwise 0.
883 * The operation never sleeps.
886 vm_page_trysbusy(vm_page_t m)
892 if ((x & VPB_BIT_SHARED) == 0)
894 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
900 vm_page_xunbusy_locked(vm_page_t m)
903 vm_page_assert_xbusied(m);
904 vm_page_assert_locked(m);
906 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
907 /* There is a waiter, do wakeup() instead of vm_page_flash(). */
912 vm_page_xunbusy_maybelocked(vm_page_t m)
916 vm_page_assert_xbusied(m);
919 * Fast path for unbusy. If it succeeds, we know that there
920 * are no waiters, so we do not need a wakeup.
922 if (atomic_cmpset_rel_int(&m->busy_lock, VPB_SINGLE_EXCLUSIVER,
926 lockacq = !mtx_owned(vm_page_lockptr(m));
929 vm_page_xunbusy_locked(m);
935 * vm_page_xunbusy_hard:
937 * Called after the first try the exclusive unbusy of a page failed.
938 * It is assumed that the waiters bit is on.
941 vm_page_xunbusy_hard(vm_page_t m)
944 vm_page_assert_xbusied(m);
947 vm_page_xunbusy_locked(m);
954 * Wakeup anyone waiting for the page.
955 * The ownership bits do not change.
957 * The given page must be locked.
960 vm_page_flash(vm_page_t m)
964 vm_page_lock_assert(m, MA_OWNED);
968 if ((x & VPB_BIT_WAITERS) == 0)
970 if (atomic_cmpset_int(&m->busy_lock, x,
971 x & (~VPB_BIT_WAITERS)))
978 * Avoid releasing and reacquiring the same page lock.
981 vm_page_change_lock(vm_page_t m, struct mtx **mtx)
985 mtx1 = vm_page_lockptr(m);
995 * Keep page from being freed by the page daemon
996 * much of the same effect as wiring, except much lower
997 * overhead and should be used only for *very* temporary
998 * holding ("wiring").
1001 vm_page_hold(vm_page_t mem)
1004 vm_page_lock_assert(mem, MA_OWNED);
1009 vm_page_unhold(vm_page_t mem)
1012 vm_page_lock_assert(mem, MA_OWNED);
1013 KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
1015 if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
1016 vm_page_free_toq(mem);
1020 * vm_page_unhold_pages:
1022 * Unhold each of the pages that is referenced by the given array.
1025 vm_page_unhold_pages(vm_page_t *ma, int count)
1030 for (; count != 0; count--) {
1031 vm_page_change_lock(*ma, &mtx);
1032 vm_page_unhold(*ma);
1040 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1044 #ifdef VM_PHYSSEG_SPARSE
1045 m = vm_phys_paddr_to_vm_page(pa);
1047 m = vm_phys_fictitious_to_vm_page(pa);
1049 #elif defined(VM_PHYSSEG_DENSE)
1053 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1054 m = &vm_page_array[pi - first_page];
1057 return (vm_phys_fictitious_to_vm_page(pa));
1059 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1066 * Create a fictitious page with the specified physical address and
1067 * memory attribute. The memory attribute is the only the machine-
1068 * dependent aspect of a fictitious page that must be initialized.
1071 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1075 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1076 vm_page_initfake(m, paddr, memattr);
1081 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1084 if ((m->flags & PG_FICTITIOUS) != 0) {
1086 * The page's memattr might have changed since the
1087 * previous initialization. Update the pmap to the
1092 m->phys_addr = paddr;
1094 /* Fictitious pages don't use "segind". */
1095 m->flags = PG_FICTITIOUS;
1096 /* Fictitious pages don't use "order" or "pool". */
1097 m->oflags = VPO_UNMANAGED;
1098 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1102 pmap_page_set_memattr(m, memattr);
1108 * Release a fictitious page.
1111 vm_page_putfake(vm_page_t m)
1114 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1115 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1116 ("vm_page_putfake: bad page %p", m));
1117 uma_zfree(fakepg_zone, m);
1121 * vm_page_updatefake:
1123 * Update the given fictitious page to the specified physical address and
1127 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1130 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1131 ("vm_page_updatefake: bad page %p", m));
1132 m->phys_addr = paddr;
1133 pmap_page_set_memattr(m, memattr);
1142 vm_page_free(vm_page_t m)
1145 m->flags &= ~PG_ZERO;
1146 vm_page_free_toq(m);
1150 * vm_page_free_zero:
1152 * Free a page to the zerod-pages queue
1155 vm_page_free_zero(vm_page_t m)
1158 m->flags |= PG_ZERO;
1159 vm_page_free_toq(m);
1163 * Unbusy and handle the page queueing for a page from a getpages request that
1164 * was optionally read ahead or behind.
1167 vm_page_readahead_finish(vm_page_t m)
1170 /* We shouldn't put invalid pages on queues. */
1171 KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
1174 * Since the page is not the actually needed one, whether it should
1175 * be activated or deactivated is not obvious. Empirical results
1176 * have shown that deactivating the page is usually the best choice,
1177 * unless the page is wanted by another thread.
1180 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1181 vm_page_activate(m);
1183 vm_page_deactivate(m);
1189 * vm_page_sleep_if_busy:
1191 * Sleep and release the page queues lock if the page is busied.
1192 * Returns TRUE if the thread slept.
1194 * The given page must be unlocked and object containing it must
1198 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1202 vm_page_lock_assert(m, MA_NOTOWNED);
1203 VM_OBJECT_ASSERT_WLOCKED(m->object);
1205 if (vm_page_busied(m)) {
1207 * The page-specific object must be cached because page
1208 * identity can change during the sleep, causing the
1209 * re-lock of a different object.
1210 * It is assumed that a reference to the object is already
1211 * held by the callers.
1215 VM_OBJECT_WUNLOCK(obj);
1216 vm_page_busy_sleep(m, msg, false);
1217 VM_OBJECT_WLOCK(obj);
1224 * vm_page_dirty_KBI: [ internal use only ]
1226 * Set all bits in the page's dirty field.
1228 * The object containing the specified page must be locked if the
1229 * call is made from the machine-independent layer.
1231 * See vm_page_clear_dirty_mask().
1233 * This function should only be called by vm_page_dirty().
1236 vm_page_dirty_KBI(vm_page_t m)
1239 /* Refer to this operation by its public name. */
1240 KASSERT(m->valid == VM_PAGE_BITS_ALL,
1241 ("vm_page_dirty: page is invalid!"));
1242 m->dirty = VM_PAGE_BITS_ALL;
1246 * vm_page_insert: [ internal use only ]
1248 * Inserts the given mem entry into the object and object list.
1250 * The object must be locked.
1253 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1257 VM_OBJECT_ASSERT_WLOCKED(object);
1258 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1259 return (vm_page_insert_after(m, object, pindex, mpred));
1263 * vm_page_insert_after:
1265 * Inserts the page "m" into the specified object at offset "pindex".
1267 * The page "mpred" must immediately precede the offset "pindex" within
1268 * the specified object.
1270 * The object must be locked.
1273 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1278 VM_OBJECT_ASSERT_WLOCKED(object);
1279 KASSERT(m->object == NULL,
1280 ("vm_page_insert_after: page already inserted"));
1281 if (mpred != NULL) {
1282 KASSERT(mpred->object == object,
1283 ("vm_page_insert_after: object doesn't contain mpred"));
1284 KASSERT(mpred->pindex < pindex,
1285 ("vm_page_insert_after: mpred doesn't precede pindex"));
1286 msucc = TAILQ_NEXT(mpred, listq);
1288 msucc = TAILQ_FIRST(&object->memq);
1290 KASSERT(msucc->pindex > pindex,
1291 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1294 * Record the object/offset pair in this page
1300 * Now link into the object's ordered list of backed pages.
1302 if (vm_radix_insert(&object->rtree, m)) {
1307 vm_page_insert_radixdone(m, object, mpred);
1312 * vm_page_insert_radixdone:
1314 * Complete page "m" insertion into the specified object after the
1315 * radix trie hooking.
1317 * The page "mpred" must precede the offset "m->pindex" within the
1320 * The object must be locked.
1323 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1326 VM_OBJECT_ASSERT_WLOCKED(object);
1327 KASSERT(object != NULL && m->object == object,
1328 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1329 if (mpred != NULL) {
1330 KASSERT(mpred->object == object,
1331 ("vm_page_insert_after: object doesn't contain mpred"));
1332 KASSERT(mpred->pindex < m->pindex,
1333 ("vm_page_insert_after: mpred doesn't precede pindex"));
1337 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1339 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1342 * Show that the object has one more resident page.
1344 object->resident_page_count++;
1347 * Hold the vnode until the last page is released.
1349 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1350 vhold(object->handle);
1353 * Since we are inserting a new and possibly dirty page,
1354 * update the object's OBJ_MIGHTBEDIRTY flag.
1356 if (pmap_page_is_write_mapped(m))
1357 vm_object_set_writeable_dirty(object);
1363 * Removes the specified page from its containing object, but does not
1364 * invalidate any backing storage.
1366 * The object must be locked. The page must be locked if it is managed.
1369 vm_page_remove(vm_page_t m)
1374 if ((m->oflags & VPO_UNMANAGED) == 0)
1375 vm_page_assert_locked(m);
1376 if ((object = m->object) == NULL)
1378 VM_OBJECT_ASSERT_WLOCKED(object);
1379 if (vm_page_xbusied(m))
1380 vm_page_xunbusy_maybelocked(m);
1381 mrem = vm_radix_remove(&object->rtree, m->pindex);
1382 KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1385 * Now remove from the object's list of backed pages.
1387 TAILQ_REMOVE(&object->memq, m, listq);
1390 * And show that the object has one fewer resident page.
1392 object->resident_page_count--;
1395 * The vnode may now be recycled.
1397 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1398 vdrop(object->handle);
1406 * Returns the page associated with the object/offset
1407 * pair specified; if none is found, NULL is returned.
1409 * The object must be locked.
1412 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1415 VM_OBJECT_ASSERT_LOCKED(object);
1416 return (vm_radix_lookup(&object->rtree, pindex));
1420 * vm_page_find_least:
1422 * Returns the page associated with the object with least pindex
1423 * greater than or equal to the parameter pindex, or NULL.
1425 * The object must be locked.
1428 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1432 VM_OBJECT_ASSERT_LOCKED(object);
1433 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1434 m = vm_radix_lookup_ge(&object->rtree, pindex);
1439 * Returns the given page's successor (by pindex) within the object if it is
1440 * resident; if none is found, NULL is returned.
1442 * The object must be locked.
1445 vm_page_next(vm_page_t m)
1449 VM_OBJECT_ASSERT_LOCKED(m->object);
1450 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1451 MPASS(next->object == m->object);
1452 if (next->pindex != m->pindex + 1)
1459 * Returns the given page's predecessor (by pindex) within the object if it is
1460 * resident; if none is found, NULL is returned.
1462 * The object must be locked.
1465 vm_page_prev(vm_page_t m)
1469 VM_OBJECT_ASSERT_LOCKED(m->object);
1470 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1471 MPASS(prev->object == m->object);
1472 if (prev->pindex != m->pindex - 1)
1479 * Uses the page mnew as a replacement for an existing page at index
1480 * pindex which must be already present in the object.
1482 * The existing page must not be on a paging queue.
1485 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1489 VM_OBJECT_ASSERT_WLOCKED(object);
1490 KASSERT(mnew->object == NULL,
1491 ("vm_page_replace: page already in object"));
1494 * This function mostly follows vm_page_insert() and
1495 * vm_page_remove() without the radix, object count and vnode
1496 * dance. Double check such functions for more comments.
1499 mnew->object = object;
1500 mnew->pindex = pindex;
1501 mold = vm_radix_replace(&object->rtree, mnew);
1502 KASSERT(mold->queue == PQ_NONE,
1503 ("vm_page_replace: mold is on a paging queue"));
1505 /* Keep the resident page list in sorted order. */
1506 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1507 TAILQ_REMOVE(&object->memq, mold, listq);
1509 mold->object = NULL;
1510 vm_page_xunbusy_maybelocked(mold);
1513 * The object's resident_page_count does not change because we have
1514 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1516 if (pmap_page_is_write_mapped(mnew))
1517 vm_object_set_writeable_dirty(object);
1524 * Move the given memory entry from its
1525 * current object to the specified target object/offset.
1527 * Note: swap associated with the page must be invalidated by the move. We
1528 * have to do this for several reasons: (1) we aren't freeing the
1529 * page, (2) we are dirtying the page, (3) the VM system is probably
1530 * moving the page from object A to B, and will then later move
1531 * the backing store from A to B and we can't have a conflict.
1533 * Note: we *always* dirty the page. It is necessary both for the
1534 * fact that we moved it, and because we may be invalidating
1537 * The objects must be locked.
1540 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1545 VM_OBJECT_ASSERT_WLOCKED(new_object);
1547 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1548 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1549 ("vm_page_rename: pindex already renamed"));
1552 * Create a custom version of vm_page_insert() which does not depend
1553 * by m_prev and can cheat on the implementation aspects of the
1557 m->pindex = new_pindex;
1558 if (vm_radix_insert(&new_object->rtree, m)) {
1564 * The operation cannot fail anymore. The removal must happen before
1565 * the listq iterator is tainted.
1571 /* Return back to the new pindex to complete vm_page_insert(). */
1572 m->pindex = new_pindex;
1573 m->object = new_object;
1575 vm_page_insert_radixdone(m, new_object, mpred);
1583 * Allocate and return a page that is associated with the specified
1584 * object and offset pair. By default, this page is exclusive busied.
1586 * The caller must always specify an allocation class.
1588 * allocation classes:
1589 * VM_ALLOC_NORMAL normal process request
1590 * VM_ALLOC_SYSTEM system *really* needs a page
1591 * VM_ALLOC_INTERRUPT interrupt time request
1593 * optional allocation flags:
1594 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1595 * intends to allocate
1596 * VM_ALLOC_NOBUSY do not exclusive busy the page
1597 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1598 * VM_ALLOC_NOOBJ page is not associated with an object and
1599 * should not be exclusive busy
1600 * VM_ALLOC_SBUSY shared busy the allocated page
1601 * VM_ALLOC_WIRED wire the allocated page
1602 * VM_ALLOC_ZERO prefer a zeroed page
1605 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1608 return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1609 vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1613 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1617 return (vm_page_alloc_domain_after(object, pindex, domain, req,
1618 object != NULL ? vm_radix_lookup_le(&object->rtree, pindex) :
1623 * Allocate a page in the specified object with the given page index. To
1624 * optimize insertion of the page into the object, the caller must also specifiy
1625 * the resident page in the object with largest index smaller than the given
1626 * page index, or NULL if no such page exists.
1629 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1630 int req, vm_page_t mpred)
1632 struct vm_domainset_iter di;
1636 vm_domainset_iter_page_init(&di, object, &domain, &req);
1638 m = vm_page_alloc_domain_after(object, pindex, domain, req,
1642 } while (vm_domainset_iter_page(&di, &domain, &req) == 0);
1648 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
1649 int req, vm_page_t mpred)
1652 int flags, req_class;
1655 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1656 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1657 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1658 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1659 ("inconsistent object(%p)/req(%x)", object, req));
1660 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1661 ("Can't sleep and retry object insertion."));
1662 KASSERT(mpred == NULL || mpred->pindex < pindex,
1663 ("mpred %p doesn't precede pindex 0x%jx", mpred,
1664 (uintmax_t)pindex));
1666 VM_OBJECT_ASSERT_WLOCKED(object);
1668 req_class = req & VM_ALLOC_CLASS_MASK;
1671 * The page daemon is allowed to dig deeper into the free page list.
1673 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1674 req_class = VM_ALLOC_SYSTEM;
1677 * Allocate a page if the number of free pages exceeds the minimum
1678 * for the request class.
1682 mtx_lock(&vm_page_queue_free_mtx);
1683 if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
1684 (req_class == VM_ALLOC_SYSTEM &&
1685 vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
1686 (req_class == VM_ALLOC_INTERRUPT &&
1687 vm_cnt.v_free_count > 0)) {
1689 * Can we allocate the page from a reservation?
1691 #if VM_NRESERVLEVEL > 0
1692 if (object == NULL || (object->flags & (OBJ_COLORED |
1693 OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1694 vm_reserv_alloc_page(object, pindex, domain,
1699 * If not, allocate it from the free page queues.
1701 m = vm_phys_alloc_pages(domain, object != NULL ?
1702 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1703 #if VM_NRESERVLEVEL > 0
1704 if (m == NULL && vm_reserv_reclaim_inactive(domain)) {
1705 m = vm_phys_alloc_pages(domain,
1707 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1715 * Not allocatable, give up.
1717 if (vm_page_alloc_fail(object, req))
1723 * At this point we had better have found a good page.
1725 KASSERT(m != NULL, ("missing page"));
1726 free_count = vm_phys_freecnt_adj(m, -1);
1727 mtx_unlock(&vm_page_queue_free_mtx);
1728 vm_page_alloc_check(m);
1731 * Initialize the page. Only the PG_ZERO flag is inherited.
1734 if ((req & VM_ALLOC_ZERO) != 0)
1737 if ((req & VM_ALLOC_NODUMP) != 0)
1741 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1743 m->busy_lock = VPB_UNBUSIED;
1744 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1745 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1746 if ((req & VM_ALLOC_SBUSY) != 0)
1747 m->busy_lock = VPB_SHARERS_WORD(1);
1748 if (req & VM_ALLOC_WIRED) {
1750 * The page lock is not required for wiring a page until that
1751 * page is inserted into the object.
1753 atomic_add_int(&vm_cnt.v_wire_count, 1);
1758 if (object != NULL) {
1759 if (vm_page_insert_after(m, object, pindex, mpred)) {
1760 pagedaemon_wakeup();
1761 if (req & VM_ALLOC_WIRED) {
1762 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1765 KASSERT(m->object == NULL, ("page %p has object", m));
1766 m->oflags = VPO_UNMANAGED;
1767 m->busy_lock = VPB_UNBUSIED;
1768 /* Don't change PG_ZERO. */
1769 vm_page_free_toq(m);
1770 if (req & VM_ALLOC_WAITFAIL) {
1771 VM_OBJECT_WUNLOCK(object);
1773 VM_OBJECT_WLOCK(object);
1778 /* Ignore device objects; the pager sets "memattr" for them. */
1779 if (object->memattr != VM_MEMATTR_DEFAULT &&
1780 (object->flags & OBJ_FICTITIOUS) == 0)
1781 pmap_page_set_memattr(m, object->memattr);
1786 * Don't wakeup too often - wakeup the pageout daemon when
1787 * we would be nearly out of memory.
1789 if (vm_paging_needed(free_count))
1790 pagedaemon_wakeup();
1796 * vm_page_alloc_contig:
1798 * Allocate a contiguous set of physical pages of the given size "npages"
1799 * from the free lists. All of the physical pages must be at or above
1800 * the given physical address "low" and below the given physical address
1801 * "high". The given value "alignment" determines the alignment of the
1802 * first physical page in the set. If the given value "boundary" is
1803 * non-zero, then the set of physical pages cannot cross any physical
1804 * address boundary that is a multiple of that value. Both "alignment"
1805 * and "boundary" must be a power of two.
1807 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1808 * then the memory attribute setting for the physical pages is configured
1809 * to the object's memory attribute setting. Otherwise, the memory
1810 * attribute setting for the physical pages is configured to "memattr",
1811 * overriding the object's memory attribute setting. However, if the
1812 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1813 * memory attribute setting for the physical pages cannot be configured
1814 * to VM_MEMATTR_DEFAULT.
1816 * The specified object may not contain fictitious pages.
1818 * The caller must always specify an allocation class.
1820 * allocation classes:
1821 * VM_ALLOC_NORMAL normal process request
1822 * VM_ALLOC_SYSTEM system *really* needs a page
1823 * VM_ALLOC_INTERRUPT interrupt time request
1825 * optional allocation flags:
1826 * VM_ALLOC_NOBUSY do not exclusive busy the page
1827 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1828 * VM_ALLOC_NOOBJ page is not associated with an object and
1829 * should not be exclusive busy
1830 * VM_ALLOC_SBUSY shared busy the allocated page
1831 * VM_ALLOC_WIRED wire the allocated page
1832 * VM_ALLOC_ZERO prefer a zeroed page
1835 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1836 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1837 vm_paddr_t boundary, vm_memattr_t memattr)
1839 struct vm_domainset_iter di;
1843 vm_domainset_iter_page_init(&di, object, &domain, &req);
1845 m = vm_page_alloc_contig_domain(object, pindex, domain, req,
1846 npages, low, high, alignment, boundary, memattr);
1849 } while (vm_domainset_iter_page(&di, &domain, &req) == 0);
1855 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1856 int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1857 vm_paddr_t boundary, vm_memattr_t memattr)
1859 vm_page_t m, m_ret, mpred;
1860 u_int busy_lock, flags, oflags;
1863 mpred = NULL; /* XXX: pacify gcc */
1864 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1865 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1866 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1867 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1868 ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
1870 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1871 ("Can't sleep and retry object insertion."));
1872 if (object != NULL) {
1873 VM_OBJECT_ASSERT_WLOCKED(object);
1874 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
1875 ("vm_page_alloc_contig: object %p has fictitious pages",
1878 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1879 req_class = req & VM_ALLOC_CLASS_MASK;
1882 * The page daemon is allowed to dig deeper into the free page list.
1884 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1885 req_class = VM_ALLOC_SYSTEM;
1887 if (object != NULL) {
1888 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1889 KASSERT(mpred == NULL || mpred->pindex != pindex,
1890 ("vm_page_alloc_contig: pindex already allocated"));
1894 * Can we allocate the pages without the number of free pages falling
1895 * below the lower bound for the allocation class?
1899 mtx_lock(&vm_page_queue_free_mtx);
1900 if (vm_cnt.v_free_count >= npages + vm_cnt.v_free_reserved ||
1901 (req_class == VM_ALLOC_SYSTEM &&
1902 vm_cnt.v_free_count >= npages + vm_cnt.v_interrupt_free_min) ||
1903 (req_class == VM_ALLOC_INTERRUPT &&
1904 vm_cnt.v_free_count >= npages)) {
1906 * Can we allocate the pages from a reservation?
1908 #if VM_NRESERVLEVEL > 0
1910 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1911 (m_ret = vm_reserv_alloc_contig(object, pindex, domain,
1912 npages, low, high, alignment, boundary, mpred)) == NULL)
1915 * If not, allocate them from the free page queues.
1917 m_ret = vm_phys_alloc_contig(domain, npages, low, high,
1918 alignment, boundary);
1919 #if VM_NRESERVLEVEL > 0
1920 if (m_ret == NULL && vm_reserv_reclaim_contig(
1921 domain, npages, low, high, alignment, boundary))
1925 if (m_ret == NULL) {
1926 if (vm_page_alloc_fail(object, req))
1930 vm_phys_freecnt_adj(m_ret, -npages);
1931 mtx_unlock(&vm_page_queue_free_mtx);
1932 for (m = m_ret; m < &m_ret[npages]; m++)
1933 vm_page_alloc_check(m);
1936 * Initialize the pages. Only the PG_ZERO flag is inherited.
1939 if ((req & VM_ALLOC_ZERO) != 0)
1941 if ((req & VM_ALLOC_NODUMP) != 0)
1943 oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1945 busy_lock = VPB_UNBUSIED;
1946 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1947 busy_lock = VPB_SINGLE_EXCLUSIVER;
1948 if ((req & VM_ALLOC_SBUSY) != 0)
1949 busy_lock = VPB_SHARERS_WORD(1);
1950 if ((req & VM_ALLOC_WIRED) != 0)
1951 atomic_add_int(&vm_cnt.v_wire_count, npages);
1952 if (object != NULL) {
1953 if (object->memattr != VM_MEMATTR_DEFAULT &&
1954 memattr == VM_MEMATTR_DEFAULT)
1955 memattr = object->memattr;
1957 for (m = m_ret; m < &m_ret[npages]; m++) {
1959 m->flags = (m->flags | PG_NODUMP) & flags;
1960 m->busy_lock = busy_lock;
1961 if ((req & VM_ALLOC_WIRED) != 0)
1965 if (object != NULL) {
1966 if (vm_page_insert_after(m, object, pindex, mpred)) {
1967 pagedaemon_wakeup();
1968 if ((req & VM_ALLOC_WIRED) != 0)
1969 atomic_subtract_int(
1970 &vm_cnt.v_wire_count, npages);
1971 KASSERT(m->object == NULL,
1972 ("page %p has object", m));
1974 for (m = m_ret; m < &m_ret[npages]; m++) {
1976 (req & VM_ALLOC_WIRED) != 0)
1978 m->oflags = VPO_UNMANAGED;
1979 m->busy_lock = VPB_UNBUSIED;
1980 /* Don't change PG_ZERO. */
1981 vm_page_free_toq(m);
1983 if (req & VM_ALLOC_WAITFAIL) {
1984 VM_OBJECT_WUNLOCK(object);
1986 VM_OBJECT_WLOCK(object);
1993 if (memattr != VM_MEMATTR_DEFAULT)
1994 pmap_page_set_memattr(m, memattr);
1997 if (vm_paging_needed(vm_cnt.v_free_count))
1998 pagedaemon_wakeup();
2003 * Check a page that has been freshly dequeued from a freelist.
2006 vm_page_alloc_check(vm_page_t m)
2009 KASSERT(m->object == NULL, ("page %p has object", m));
2010 KASSERT(m->queue == PQ_NONE,
2011 ("page %p has unexpected queue %d", m, m->queue));
2012 KASSERT(m->wire_count == 0, ("page %p is wired", m));
2013 KASSERT(m->hold_count == 0, ("page %p is held", m));
2014 KASSERT(!vm_page_busied(m), ("page %p is busy", m));
2015 KASSERT(m->dirty == 0, ("page %p is dirty", m));
2016 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2017 ("page %p has unexpected memattr %d",
2018 m, pmap_page_get_memattr(m)));
2019 KASSERT(m->valid == 0, ("free page %p is valid", m));
2023 * vm_page_alloc_freelist:
2025 * Allocate a physical page from the specified free page list.
2027 * The caller must always specify an allocation class.
2029 * allocation classes:
2030 * VM_ALLOC_NORMAL normal process request
2031 * VM_ALLOC_SYSTEM system *really* needs a page
2032 * VM_ALLOC_INTERRUPT interrupt time request
2034 * optional allocation flags:
2035 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2036 * intends to allocate
2037 * VM_ALLOC_WIRED wire the allocated page
2038 * VM_ALLOC_ZERO prefer a zeroed page
2041 vm_page_alloc_freelist(int freelist, int req)
2043 struct vm_domainset_iter di;
2047 vm_domainset_iter_page_init(&di, kernel_object, &domain, &req);
2049 m = vm_page_alloc_freelist_domain(domain, freelist, req);
2052 } while (vm_domainset_iter_page(&di, &domain, &req) == 0);
2058 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2061 u_int flags, free_count;
2064 req_class = req & VM_ALLOC_CLASS_MASK;
2067 * The page daemon is allowed to dig deeper into the free page list.
2069 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2070 req_class = VM_ALLOC_SYSTEM;
2073 * Do not allocate reserved pages unless the req has asked for it.
2076 mtx_lock(&vm_page_queue_free_mtx);
2077 if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
2078 (req_class == VM_ALLOC_SYSTEM &&
2079 vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
2080 (req_class == VM_ALLOC_INTERRUPT &&
2081 vm_cnt.v_free_count > 0))
2082 m = vm_phys_alloc_freelist_pages(domain, freelist,
2083 VM_FREEPOOL_DIRECT, 0);
2085 if (vm_page_alloc_fail(NULL, req))
2089 free_count = vm_phys_freecnt_adj(m, -1);
2090 mtx_unlock(&vm_page_queue_free_mtx);
2091 vm_page_alloc_check(m);
2094 * Initialize the page. Only the PG_ZERO flag is inherited.
2098 if ((req & VM_ALLOC_ZERO) != 0)
2101 if ((req & VM_ALLOC_WIRED) != 0) {
2103 * The page lock is not required for wiring a page that does
2104 * not belong to an object.
2106 atomic_add_int(&vm_cnt.v_wire_count, 1);
2109 /* Unmanaged pages don't use "act_count". */
2110 m->oflags = VPO_UNMANAGED;
2111 if (vm_paging_needed(free_count))
2112 pagedaemon_wakeup();
2116 #define VPSC_ANY 0 /* No restrictions. */
2117 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2118 #define VPSC_NOSUPER 2 /* Skip superpages. */
2121 * vm_page_scan_contig:
2123 * Scan vm_page_array[] between the specified entries "m_start" and
2124 * "m_end" for a run of contiguous physical pages that satisfy the
2125 * specified conditions, and return the lowest page in the run. The
2126 * specified "alignment" determines the alignment of the lowest physical
2127 * page in the run. If the specified "boundary" is non-zero, then the
2128 * run of physical pages cannot span a physical address that is a
2129 * multiple of "boundary".
2131 * "m_end" is never dereferenced, so it need not point to a vm_page
2132 * structure within vm_page_array[].
2134 * "npages" must be greater than zero. "m_start" and "m_end" must not
2135 * span a hole (or discontiguity) in the physical address space. Both
2136 * "alignment" and "boundary" must be a power of two.
2139 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2140 u_long alignment, vm_paddr_t boundary, int options)
2146 #if VM_NRESERVLEVEL > 0
2149 int m_inc, order, run_ext, run_len;
2151 KASSERT(npages > 0, ("npages is 0"));
2152 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2153 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2157 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2158 KASSERT((m->flags & PG_MARKER) == 0,
2159 ("page %p is PG_MARKER", m));
2160 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->wire_count == 1,
2161 ("fictitious page %p has invalid wire count", m));
2164 * If the current page would be the start of a run, check its
2165 * physical address against the end, alignment, and boundary
2166 * conditions. If it doesn't satisfy these conditions, either
2167 * terminate the scan or advance to the next page that
2168 * satisfies the failed condition.
2171 KASSERT(m_run == NULL, ("m_run != NULL"));
2172 if (m + npages > m_end)
2174 pa = VM_PAGE_TO_PHYS(m);
2175 if ((pa & (alignment - 1)) != 0) {
2176 m_inc = atop(roundup2(pa, alignment) - pa);
2179 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2181 m_inc = atop(roundup2(pa, boundary) - pa);
2185 KASSERT(m_run != NULL, ("m_run == NULL"));
2187 vm_page_change_lock(m, &m_mtx);
2190 if (m->wire_count != 0 || m->hold_count != 0)
2192 #if VM_NRESERVLEVEL > 0
2193 else if ((level = vm_reserv_level(m)) >= 0 &&
2194 (options & VPSC_NORESERV) != 0) {
2196 /* Advance to the end of the reservation. */
2197 pa = VM_PAGE_TO_PHYS(m);
2198 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2202 else if ((object = m->object) != NULL) {
2204 * The page is considered eligible for relocation if
2205 * and only if it could be laundered or reclaimed by
2208 if (!VM_OBJECT_TRYRLOCK(object)) {
2210 VM_OBJECT_RLOCK(object);
2212 if (m->object != object) {
2214 * The page may have been freed.
2216 VM_OBJECT_RUNLOCK(object);
2218 } else if (m->wire_count != 0 ||
2219 m->hold_count != 0) {
2224 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2225 ("page %p is PG_UNHOLDFREE", m));
2226 /* Don't care: PG_NODUMP, PG_ZERO. */
2227 if (object->type != OBJT_DEFAULT &&
2228 object->type != OBJT_SWAP &&
2229 object->type != OBJT_VNODE) {
2231 #if VM_NRESERVLEVEL > 0
2232 } else if ((options & VPSC_NOSUPER) != 0 &&
2233 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2235 /* Advance to the end of the superpage. */
2236 pa = VM_PAGE_TO_PHYS(m);
2237 m_inc = atop(roundup2(pa + 1,
2238 vm_reserv_size(level)) - pa);
2240 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2241 m->queue != PQ_NONE && !vm_page_busied(m)) {
2243 * The page is allocated but eligible for
2244 * relocation. Extend the current run by one
2247 KASSERT(pmap_page_get_memattr(m) ==
2249 ("page %p has an unexpected memattr", m));
2250 KASSERT((m->oflags & (VPO_SWAPINPROG |
2251 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2252 ("page %p has unexpected oflags", m));
2253 /* Don't care: VPO_NOSYNC. */
2258 VM_OBJECT_RUNLOCK(object);
2259 #if VM_NRESERVLEVEL > 0
2260 } else if (level >= 0) {
2262 * The page is reserved but not yet allocated. In
2263 * other words, it is still free. Extend the current
2268 } else if ((order = m->order) < VM_NFREEORDER) {
2270 * The page is enqueued in the physical memory
2271 * allocator's free page queues. Moreover, it is the
2272 * first page in a power-of-two-sized run of
2273 * contiguous free pages. Add these pages to the end
2274 * of the current run, and jump ahead.
2276 run_ext = 1 << order;
2280 * Skip the page for one of the following reasons: (1)
2281 * It is enqueued in the physical memory allocator's
2282 * free page queues. However, it is not the first
2283 * page in a run of contiguous free pages. (This case
2284 * rarely occurs because the scan is performed in
2285 * ascending order.) (2) It is not reserved, and it is
2286 * transitioning from free to allocated. (Conversely,
2287 * the transition from allocated to free for managed
2288 * pages is blocked by the page lock.) (3) It is
2289 * allocated but not contained by an object and not
2290 * wired, e.g., allocated by Xen's balloon driver.
2296 * Extend or reset the current run of pages.
2311 if (run_len >= npages)
2317 * vm_page_reclaim_run:
2319 * Try to relocate each of the allocated virtual pages within the
2320 * specified run of physical pages to a new physical address. Free the
2321 * physical pages underlying the relocated virtual pages. A virtual page
2322 * is relocatable if and only if it could be laundered or reclaimed by
2323 * the page daemon. Whenever possible, a virtual page is relocated to a
2324 * physical address above "high".
2326 * Returns 0 if every physical page within the run was already free or
2327 * just freed by a successful relocation. Otherwise, returns a non-zero
2328 * value indicating why the last attempt to relocate a virtual page was
2331 * "req_class" must be an allocation class.
2334 vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
2338 struct spglist free;
2341 vm_page_t m, m_end, m_new;
2342 int error, order, req;
2344 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2345 ("req_class is not an allocation class"));
2349 m_end = m_run + npages;
2351 for (; error == 0 && m < m_end; m++) {
2352 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2353 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2356 * Avoid releasing and reacquiring the same page lock.
2358 vm_page_change_lock(m, &m_mtx);
2360 if (m->wire_count != 0 || m->hold_count != 0)
2362 else if ((object = m->object) != NULL) {
2364 * The page is relocated if and only if it could be
2365 * laundered or reclaimed by the page daemon.
2367 if (!VM_OBJECT_TRYWLOCK(object)) {
2369 VM_OBJECT_WLOCK(object);
2371 if (m->object != object) {
2373 * The page may have been freed.
2375 VM_OBJECT_WUNLOCK(object);
2377 } else if (m->wire_count != 0 ||
2378 m->hold_count != 0) {
2383 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2384 ("page %p is PG_UNHOLDFREE", m));
2385 /* Don't care: PG_NODUMP, PG_ZERO. */
2386 if (object->type != OBJT_DEFAULT &&
2387 object->type != OBJT_SWAP &&
2388 object->type != OBJT_VNODE)
2390 else if (object->memattr != VM_MEMATTR_DEFAULT)
2392 else if (m->queue != PQ_NONE && !vm_page_busied(m)) {
2393 KASSERT(pmap_page_get_memattr(m) ==
2395 ("page %p has an unexpected memattr", m));
2396 KASSERT((m->oflags & (VPO_SWAPINPROG |
2397 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2398 ("page %p has unexpected oflags", m));
2399 /* Don't care: VPO_NOSYNC. */
2400 if (m->valid != 0) {
2402 * First, try to allocate a new page
2403 * that is above "high". Failing
2404 * that, try to allocate a new page
2405 * that is below "m_run". Allocate
2406 * the new page between the end of
2407 * "m_run" and "high" only as a last
2410 req = req_class | VM_ALLOC_NOOBJ;
2411 if ((m->flags & PG_NODUMP) != 0)
2412 req |= VM_ALLOC_NODUMP;
2413 if (trunc_page(high) !=
2414 ~(vm_paddr_t)PAGE_MASK) {
2415 m_new = vm_page_alloc_contig(
2420 VM_MEMATTR_DEFAULT);
2423 if (m_new == NULL) {
2424 pa = VM_PAGE_TO_PHYS(m_run);
2425 m_new = vm_page_alloc_contig(
2427 0, pa - 1, PAGE_SIZE, 0,
2428 VM_MEMATTR_DEFAULT);
2430 if (m_new == NULL) {
2432 m_new = vm_page_alloc_contig(
2434 pa, high, PAGE_SIZE, 0,
2435 VM_MEMATTR_DEFAULT);
2437 if (m_new == NULL) {
2441 KASSERT(m_new->wire_count == 0,
2442 ("page %p is wired", m));
2445 * Replace "m" with the new page. For
2446 * vm_page_replace(), "m" must be busy
2447 * and dequeued. Finally, change "m"
2448 * as if vm_page_free() was called.
2450 if (object->ref_count != 0)
2452 m_new->aflags = m->aflags;
2453 KASSERT(m_new->oflags == VPO_UNMANAGED,
2454 ("page %p is managed", m));
2455 m_new->oflags = m->oflags & VPO_NOSYNC;
2456 pmap_copy_page(m, m_new);
2457 m_new->valid = m->valid;
2458 m_new->dirty = m->dirty;
2459 m->flags &= ~PG_ZERO;
2462 vm_page_replace_checked(m_new, object,
2468 * The new page must be deactivated
2469 * before the object is unlocked.
2471 vm_page_change_lock(m_new, &m_mtx);
2472 vm_page_deactivate(m_new);
2474 m->flags &= ~PG_ZERO;
2477 KASSERT(m->dirty == 0,
2478 ("page %p is dirty", m));
2480 SLIST_INSERT_HEAD(&free, m, plinks.s.ss);
2484 VM_OBJECT_WUNLOCK(object);
2486 mtx_lock(&vm_page_queue_free_mtx);
2488 if (order < VM_NFREEORDER) {
2490 * The page is enqueued in the physical memory
2491 * allocator's free page queues. Moreover, it
2492 * is the first page in a power-of-two-sized
2493 * run of contiguous free pages. Jump ahead
2494 * to the last page within that run, and
2495 * continue from there.
2497 m += (1 << order) - 1;
2499 #if VM_NRESERVLEVEL > 0
2500 else if (vm_reserv_is_page_free(m))
2503 mtx_unlock(&vm_page_queue_free_mtx);
2504 if (order == VM_NFREEORDER)
2510 if ((m = SLIST_FIRST(&free)) != NULL) {
2511 mtx_lock(&vm_page_queue_free_mtx);
2513 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2514 vm_page_free_phys(m);
2515 } while ((m = SLIST_FIRST(&free)) != NULL);
2516 vm_page_free_wakeup();
2517 mtx_unlock(&vm_page_queue_free_mtx);
2524 CTASSERT(powerof2(NRUNS));
2526 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2528 #define MIN_RECLAIM 8
2531 * vm_page_reclaim_contig:
2533 * Reclaim allocated, contiguous physical memory satisfying the specified
2534 * conditions by relocating the virtual pages using that physical memory.
2535 * Returns true if reclamation is successful and false otherwise. Since
2536 * relocation requires the allocation of physical pages, reclamation may
2537 * fail due to a shortage of free pages. When reclamation fails, callers
2538 * are expected to perform VM_WAIT before retrying a failed allocation
2539 * operation, e.g., vm_page_alloc_contig().
2541 * The caller must always specify an allocation class through "req".
2543 * allocation classes:
2544 * VM_ALLOC_NORMAL normal process request
2545 * VM_ALLOC_SYSTEM system *really* needs a page
2546 * VM_ALLOC_INTERRUPT interrupt time request
2548 * The optional allocation flags are ignored.
2550 * "npages" must be greater than zero. Both "alignment" and "boundary"
2551 * must be a power of two.
2554 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
2555 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2557 vm_paddr_t curr_low;
2558 vm_page_t m_run, m_runs[NRUNS];
2559 u_long count, reclaimed;
2560 int error, i, options, req_class;
2562 KASSERT(npages > 0, ("npages is 0"));
2563 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2564 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2565 req_class = req & VM_ALLOC_CLASS_MASK;
2568 * The page daemon is allowed to dig deeper into the free page list.
2570 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2571 req_class = VM_ALLOC_SYSTEM;
2574 * Return if the number of free pages cannot satisfy the requested
2577 count = vm_cnt.v_free_count;
2578 if (count < npages + vm_cnt.v_free_reserved || (count < npages +
2579 vm_cnt.v_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2580 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2584 * Scan up to three times, relaxing the restrictions ("options") on
2585 * the reclamation of reservations and superpages each time.
2587 for (options = VPSC_NORESERV;;) {
2589 * Find the highest runs that satisfy the given constraints
2590 * and restrictions, and record them in "m_runs".
2595 m_run = vm_phys_scan_contig(domain, npages, curr_low,
2596 high, alignment, boundary, options);
2599 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2600 m_runs[RUN_INDEX(count)] = m_run;
2605 * Reclaim the highest runs in LIFO (descending) order until
2606 * the number of reclaimed pages, "reclaimed", is at least
2607 * MIN_RECLAIM. Reset "reclaimed" each time because each
2608 * reclamation is idempotent, and runs will (likely) recur
2609 * from one scan to the next as restrictions are relaxed.
2612 for (i = 0; count > 0 && i < NRUNS; i++) {
2614 m_run = m_runs[RUN_INDEX(count)];
2615 error = vm_page_reclaim_run(req_class, npages, m_run,
2618 reclaimed += npages;
2619 if (reclaimed >= MIN_RECLAIM)
2625 * Either relax the restrictions on the next scan or return if
2626 * the last scan had no restrictions.
2628 if (options == VPSC_NORESERV)
2629 options = VPSC_NOSUPER;
2630 else if (options == VPSC_NOSUPER)
2632 else if (options == VPSC_ANY)
2633 return (reclaimed != 0);
2638 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2639 u_long alignment, vm_paddr_t boundary)
2641 struct vm_domainset_iter di;
2645 vm_domainset_iter_page_init(&di, kernel_object, &domain, &req);
2647 ret = vm_page_reclaim_contig_domain(domain, req, npages, low,
2648 high, alignment, boundary);
2651 } while (vm_domainset_iter_page(&di, &domain, &req) == 0);
2658 * vm_wait: (also see VM_WAIT macro)
2660 * Sleep until free pages are available for allocation.
2661 * - Called in various places before memory allocations.
2667 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2668 if (curproc == pageproc) {
2669 vm_pageout_pages_needed = 1;
2670 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
2671 PDROP | PSWP, "VMWait", 0);
2673 if (pageproc == NULL)
2674 panic("vm_wait in early boot");
2675 pagedaemon_wait(PVM, "vmwait");
2683 mtx_lock(&vm_page_queue_free_mtx);
2688 * vm_page_alloc_fail:
2690 * Called when a page allocation function fails. Informs the
2691 * pagedaemon and performs the requested wait. Requires the
2692 * page_queue_free and object lock on entry. Returns with the
2693 * object lock held and free lock released. Returns an error when
2694 * retry is necessary.
2698 vm_page_alloc_fail(vm_object_t object, int req)
2701 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2703 atomic_add_int(&vm_pageout_deficit,
2704 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
2705 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
2707 VM_OBJECT_WUNLOCK(object);
2710 VM_OBJECT_WLOCK(object);
2711 if (req & VM_ALLOC_WAITOK)
2714 mtx_unlock(&vm_page_queue_free_mtx);
2715 pagedaemon_wakeup();
2721 * vm_waitpfault: (also see VM_WAITPFAULT macro)
2723 * Sleep until free pages are available for allocation.
2724 * - Called only in vm_fault so that processes page faulting
2725 * can be easily tracked.
2726 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2727 * processes will be able to grab memory first. Do not change
2728 * this balance without careful testing first.
2734 mtx_lock(&vm_page_queue_free_mtx);
2735 pagedaemon_wait(PUSER, "pfault");
2738 struct vm_pagequeue *
2739 vm_page_pagequeue(vm_page_t m)
2742 if (vm_page_in_laundry(m))
2743 return (&vm_dom[0].vmd_pagequeues[m->queue]);
2745 return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2751 * Remove the given page from its current page queue.
2753 * The page must be locked.
2756 vm_page_dequeue(vm_page_t m)
2758 struct vm_pagequeue *pq;
2760 vm_page_assert_locked(m);
2761 KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
2763 pq = vm_page_pagequeue(m);
2764 vm_pagequeue_lock(pq);
2766 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2767 vm_pagequeue_cnt_dec(pq);
2768 vm_pagequeue_unlock(pq);
2772 * vm_page_dequeue_locked:
2774 * Remove the given page from its current page queue.
2776 * The page and page queue must be locked.
2779 vm_page_dequeue_locked(vm_page_t m)
2781 struct vm_pagequeue *pq;
2783 vm_page_lock_assert(m, MA_OWNED);
2784 pq = vm_page_pagequeue(m);
2785 vm_pagequeue_assert_locked(pq);
2787 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2788 vm_pagequeue_cnt_dec(pq);
2794 * Add the given page to the specified page queue.
2796 * The page must be locked.
2799 vm_page_enqueue(uint8_t queue, vm_page_t m)
2801 struct vm_pagequeue *pq;
2803 vm_page_lock_assert(m, MA_OWNED);
2804 KASSERT(queue < PQ_COUNT,
2805 ("vm_page_enqueue: invalid queue %u request for page %p",
2807 if (queue == PQ_LAUNDRY || queue == PQ_UNSWAPPABLE)
2808 pq = &vm_dom[0].vmd_pagequeues[queue];
2810 pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2811 vm_pagequeue_lock(pq);
2813 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2814 vm_pagequeue_cnt_inc(pq);
2815 vm_pagequeue_unlock(pq);
2821 * Move the given page to the tail of its current page queue.
2823 * The page must be locked.
2826 vm_page_requeue(vm_page_t m)
2828 struct vm_pagequeue *pq;
2830 vm_page_lock_assert(m, MA_OWNED);
2831 KASSERT(m->queue != PQ_NONE,
2832 ("vm_page_requeue: page %p is not queued", m));
2833 pq = vm_page_pagequeue(m);
2834 vm_pagequeue_lock(pq);
2835 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2836 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2837 vm_pagequeue_unlock(pq);
2841 * vm_page_requeue_locked:
2843 * Move the given page to the tail of its current page queue.
2845 * The page queue must be locked.
2848 vm_page_requeue_locked(vm_page_t m)
2850 struct vm_pagequeue *pq;
2852 KASSERT(m->queue != PQ_NONE,
2853 ("vm_page_requeue_locked: page %p is not queued", m));
2854 pq = vm_page_pagequeue(m);
2855 vm_pagequeue_assert_locked(pq);
2856 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2857 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2863 * Put the specified page on the active list (if appropriate).
2864 * Ensure that act_count is at least ACT_INIT but do not otherwise
2867 * The page must be locked.
2870 vm_page_activate(vm_page_t m)
2874 vm_page_lock_assert(m, MA_OWNED);
2875 if ((queue = m->queue) != PQ_ACTIVE) {
2876 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2877 if (m->act_count < ACT_INIT)
2878 m->act_count = ACT_INIT;
2879 if (queue != PQ_NONE)
2881 vm_page_enqueue(PQ_ACTIVE, m);
2883 KASSERT(queue == PQ_NONE,
2884 ("vm_page_activate: wired page %p is queued", m));
2886 if (m->act_count < ACT_INIT)
2887 m->act_count = ACT_INIT;
2892 * vm_page_free_wakeup:
2894 * Helper routine for vm_page_free_toq(). This routine is called
2895 * when a page is added to the free queues.
2897 * The page queues must be locked.
2900 vm_page_free_wakeup(void)
2903 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2905 * if pageout daemon needs pages, then tell it that there are
2908 if (vm_pageout_pages_needed &&
2909 vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
2910 wakeup(&vm_pageout_pages_needed);
2911 vm_pageout_pages_needed = 0;
2914 * wakeup processes that are waiting on memory if we hit a
2915 * high water mark. And wakeup scheduler process if we have
2916 * lots of memory. this process will swapin processes.
2918 if (vm_pages_needed && !vm_page_count_min()) {
2919 vm_pages_needed = false;
2920 wakeup(&vm_cnt.v_free_count);
2925 * vm_page_free_prep:
2927 * Prepares the given page to be put on the free list,
2928 * disassociating it from any VM object. The caller may return
2929 * the page to the free list only if this function returns true.
2931 * The object must be locked. The page must be locked if it is
2932 * managed. For a queued managed page, the pagequeue_locked
2933 * argument specifies whether the page queue is already locked.
2936 vm_page_free_prep(vm_page_t m, bool pagequeue_locked)
2939 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
2940 if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
2943 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
2944 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
2945 KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
2946 m, i, (uintmax_t)*p));
2949 if ((m->oflags & VPO_UNMANAGED) == 0) {
2950 vm_page_lock_assert(m, MA_OWNED);
2951 KASSERT(!pmap_page_is_mapped(m),
2952 ("vm_page_free_toq: freeing mapped page %p", m));
2954 KASSERT(m->queue == PQ_NONE,
2955 ("vm_page_free_toq: unmanaged page %p is queued", m));
2956 VM_CNT_INC(v_tfree);
2958 if (vm_page_sbusied(m))
2959 panic("vm_page_free: freeing busy page %p", m);
2964 * If fictitious remove object association and
2967 if ((m->flags & PG_FICTITIOUS) != 0) {
2968 KASSERT(m->wire_count == 1,
2969 ("fictitious page %p is not wired", m));
2970 KASSERT(m->queue == PQ_NONE,
2971 ("fictitious page %p is queued", m));
2975 if (m->queue != PQ_NONE) {
2976 if (pagequeue_locked)
2977 vm_page_dequeue_locked(m);
2984 if (m->wire_count != 0)
2985 panic("vm_page_free: freeing wired page %p", m);
2986 if (m->hold_count != 0) {
2987 m->flags &= ~PG_ZERO;
2988 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2989 ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
2990 m->flags |= PG_UNHOLDFREE;
2995 * Restore the default memory attribute to the page.
2997 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2998 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3004 * Insert the page into the physical memory allocator's free page
3005 * queues. This is the last step to free a page.
3008 vm_page_free_phys(vm_page_t m)
3011 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
3013 vm_phys_freecnt_adj(m, 1);
3014 #if VM_NRESERVLEVEL > 0
3015 if (!vm_reserv_free_page(m))
3017 vm_phys_free_pages(m, 0);
3021 vm_page_free_phys_pglist(struct pglist *tq)
3025 if (TAILQ_EMPTY(tq))
3027 mtx_lock(&vm_page_queue_free_mtx);
3028 TAILQ_FOREACH(m, tq, listq)
3029 vm_page_free_phys(m);
3030 vm_page_free_wakeup();
3031 mtx_unlock(&vm_page_queue_free_mtx);
3037 * Returns the given page to the free list, disassociating it
3038 * from any VM object.
3040 * The object must be locked. The page must be locked if it is
3044 vm_page_free_toq(vm_page_t m)
3047 if (!vm_page_free_prep(m, false))
3049 mtx_lock(&vm_page_queue_free_mtx);
3050 vm_page_free_phys(m);
3051 vm_page_free_wakeup();
3052 mtx_unlock(&vm_page_queue_free_mtx);
3058 * Mark this page as wired down by yet
3059 * another map, removing it from paging queues
3062 * If the page is fictitious, then its wire count must remain one.
3064 * The page must be locked.
3067 vm_page_wire(vm_page_t m)
3071 * Only bump the wire statistics if the page is not already wired,
3072 * and only unqueue the page if it is on some queue (if it is unmanaged
3073 * it is already off the queues).
3075 vm_page_lock_assert(m, MA_OWNED);
3076 if ((m->flags & PG_FICTITIOUS) != 0) {
3077 KASSERT(m->wire_count == 1,
3078 ("vm_page_wire: fictitious page %p's wire count isn't one",
3082 if (m->wire_count == 0) {
3083 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
3084 m->queue == PQ_NONE,
3085 ("vm_page_wire: unmanaged page %p is queued", m));
3087 atomic_add_int(&vm_cnt.v_wire_count, 1);
3090 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
3096 * Release one wiring of the specified page, potentially allowing it to be
3097 * paged out. Returns TRUE if the number of wirings transitions to zero and
3100 * Only managed pages belonging to an object can be paged out. If the number
3101 * of wirings transitions to zero and the page is eligible for page out, then
3102 * the page is added to the specified paging queue (unless PQ_NONE is
3105 * If a page is fictitious, then its wire count must always be one.
3107 * A managed page must be locked.
3110 vm_page_unwire(vm_page_t m, uint8_t queue)
3113 KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
3114 ("vm_page_unwire: invalid queue %u request for page %p",
3116 if ((m->oflags & VPO_UNMANAGED) == 0)
3117 vm_page_assert_locked(m);
3118 if ((m->flags & PG_FICTITIOUS) != 0) {
3119 KASSERT(m->wire_count == 1,
3120 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
3123 if (m->wire_count > 0) {
3125 if (m->wire_count == 0) {
3126 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3127 if ((m->oflags & VPO_UNMANAGED) == 0 &&
3128 m->object != NULL && queue != PQ_NONE)
3129 vm_page_enqueue(queue, m);
3134 panic("vm_page_unwire: page %p's wire count is zero", m);
3138 * Move the specified page to the inactive queue.
3140 * Normally, "noreuse" is FALSE, resulting in LRU ordering of the inactive
3141 * queue. However, setting "noreuse" to TRUE will accelerate the specified
3142 * page's reclamation, but it will not unmap the page from any address space.
3143 * This is implemented by inserting the page near the head of the inactive
3144 * queue, using a marker page to guide FIFO insertion ordering.
3146 * The page must be locked.
3149 _vm_page_deactivate(vm_page_t m, boolean_t noreuse)
3151 struct vm_pagequeue *pq;
3154 vm_page_assert_locked(m);
3157 * Ignore if the page is already inactive, unless it is unlikely to be
3160 if ((queue = m->queue) == PQ_INACTIVE && !noreuse)
3162 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
3163 pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
3164 /* Avoid multiple acquisitions of the inactive queue lock. */
3165 if (queue == PQ_INACTIVE) {
3166 vm_pagequeue_lock(pq);
3167 vm_page_dequeue_locked(m);
3169 if (queue != PQ_NONE)
3171 vm_pagequeue_lock(pq);
3173 m->queue = PQ_INACTIVE;
3175 TAILQ_INSERT_BEFORE(&vm_phys_domain(m)->vmd_inacthead,
3178 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3179 vm_pagequeue_cnt_inc(pq);
3180 vm_pagequeue_unlock(pq);
3185 * Move the specified page to the inactive queue.
3187 * The page must be locked.
3190 vm_page_deactivate(vm_page_t m)
3193 _vm_page_deactivate(m, FALSE);
3197 * Move the specified page to the inactive queue with the expectation
3198 * that it is unlikely to be reused.
3200 * The page must be locked.
3203 vm_page_deactivate_noreuse(vm_page_t m)
3206 _vm_page_deactivate(m, TRUE);
3212 * Put a page in the laundry.
3215 vm_page_launder(vm_page_t m)
3219 vm_page_assert_locked(m);
3220 if ((queue = m->queue) != PQ_LAUNDRY) {
3221 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
3222 if (queue != PQ_NONE)
3224 vm_page_enqueue(PQ_LAUNDRY, m);
3226 KASSERT(queue == PQ_NONE,
3227 ("wired page %p is queued", m));
3232 * vm_page_unswappable
3234 * Put a page in the PQ_UNSWAPPABLE holding queue.
3237 vm_page_unswappable(vm_page_t m)
3240 vm_page_assert_locked(m);
3241 KASSERT(m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0,
3242 ("page %p already unswappable", m));
3243 if (m->queue != PQ_NONE)
3245 vm_page_enqueue(PQ_UNSWAPPABLE, m);
3249 * Attempt to free the page. If it cannot be freed, do nothing. Returns true
3250 * if the page is freed and false otherwise.
3252 * The page must be managed. The page and its containing object must be
3256 vm_page_try_to_free(vm_page_t m)
3259 vm_page_assert_locked(m);
3260 VM_OBJECT_ASSERT_WLOCKED(m->object);
3261 KASSERT((m->oflags & VPO_UNMANAGED) == 0, ("page %p is unmanaged", m));
3262 if (m->dirty != 0 || m->hold_count != 0 || m->wire_count != 0 ||
3265 if (m->object->ref_count != 0) {
3277 * Apply the specified advice to the given page.
3279 * The object and page must be locked.
3282 vm_page_advise(vm_page_t m, int advice)
3285 vm_page_assert_locked(m);
3286 VM_OBJECT_ASSERT_WLOCKED(m->object);
3287 if (advice == MADV_FREE)
3289 * Mark the page clean. This will allow the page to be freed
3290 * without first paging it out. MADV_FREE pages are often
3291 * quickly reused by malloc(3), so we do not do anything that
3292 * would result in a page fault on a later access.
3295 else if (advice != MADV_DONTNEED) {
3296 if (advice == MADV_WILLNEED)
3297 vm_page_activate(m);
3302 * Clear any references to the page. Otherwise, the page daemon will
3303 * immediately reactivate the page.
3305 vm_page_aflag_clear(m, PGA_REFERENCED);
3307 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3311 * Place clean pages near the head of the inactive queue rather than
3312 * the tail, thus defeating the queue's LRU operation and ensuring that
3313 * the page will be reused quickly. Dirty pages not already in the
3314 * laundry are moved there.
3317 vm_page_deactivate_noreuse(m);
3323 * Grab a page, waiting until we are waken up due to the page
3324 * changing state. We keep on waiting, if the page continues
3325 * to be in the object. If the page doesn't exist, first allocate it
3326 * and then conditionally zero it.
3328 * This routine may sleep.
3330 * The object must be locked on entry. The lock will, however, be released
3331 * and reacquired if the routine sleeps.
3334 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3340 VM_OBJECT_ASSERT_WLOCKED(object);
3341 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3342 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3343 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3344 pflags = allocflags &
3345 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
3346 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3347 pflags |= VM_ALLOC_WAITFAIL;
3349 if ((m = vm_page_lookup(object, pindex)) != NULL) {
3350 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3351 vm_page_xbusied(m) : vm_page_busied(m);
3353 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3356 * Reference the page before unlocking and
3357 * sleeping so that the page daemon is less
3358 * likely to reclaim it.
3360 vm_page_aflag_set(m, PGA_REFERENCED);
3362 VM_OBJECT_WUNLOCK(object);
3363 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
3364 VM_ALLOC_IGN_SBUSY) != 0);
3365 VM_OBJECT_WLOCK(object);
3368 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3374 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3376 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3381 m = vm_page_alloc(object, pindex, pflags);
3383 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3387 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3393 * Return the specified range of pages from the given object. For each
3394 * page offset within the range, if a page already exists within the object
3395 * at that offset and it is busy, then wait for it to change state. If,
3396 * instead, the page doesn't exist, then allocate it.
3398 * The caller must always specify an allocation class.
3400 * allocation classes:
3401 * VM_ALLOC_NORMAL normal process request
3402 * VM_ALLOC_SYSTEM system *really* needs the pages
3404 * The caller must always specify that the pages are to be busied and/or
3407 * optional allocation flags:
3408 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
3409 * VM_ALLOC_NOBUSY do not exclusive busy the page
3410 * VM_ALLOC_NOWAIT do not sleep
3411 * VM_ALLOC_SBUSY set page to sbusy state
3412 * VM_ALLOC_WIRED wire the pages
3413 * VM_ALLOC_ZERO zero and validate any invalid pages
3415 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
3416 * may return a partial prefix of the requested range.
3419 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
3420 vm_page_t *ma, int count)
3427 VM_OBJECT_ASSERT_WLOCKED(object);
3428 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
3429 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
3430 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
3431 (allocflags & VM_ALLOC_WIRED) != 0,
3432 ("vm_page_grab_pages: the pages must be busied or wired"));
3433 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3434 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3435 ("vm_page_grab_pages: VM_ALLOC_SBUSY/IGN_SBUSY mismatch"));
3438 pflags = allocflags & ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK |
3439 VM_ALLOC_WAITFAIL | VM_ALLOC_IGN_SBUSY);
3440 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3441 pflags |= VM_ALLOC_WAITFAIL;
3444 m = vm_radix_lookup_le(&object->rtree, pindex + i);
3445 if (m == NULL || m->pindex != pindex + i) {
3449 mpred = TAILQ_PREV(m, pglist, listq);
3450 for (; i < count; i++) {
3452 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3453 vm_page_xbusied(m) : vm_page_busied(m);
3455 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3458 * Reference the page before unlocking and
3459 * sleeping so that the page daemon is less
3460 * likely to reclaim it.
3462 vm_page_aflag_set(m, PGA_REFERENCED);
3464 VM_OBJECT_WUNLOCK(object);
3465 vm_page_busy_sleep(m, "grbmaw", (allocflags &
3466 VM_ALLOC_IGN_SBUSY) != 0);
3467 VM_OBJECT_WLOCK(object);
3470 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3475 if ((allocflags & (VM_ALLOC_NOBUSY |
3476 VM_ALLOC_SBUSY)) == 0)
3478 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3481 m = vm_page_alloc_after(object, pindex + i,
3482 pflags | VM_ALLOC_COUNT(count - i), mpred);
3484 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3489 if (m->valid == 0 && (allocflags & VM_ALLOC_ZERO) != 0) {
3490 if ((m->flags & PG_ZERO) == 0)
3492 m->valid = VM_PAGE_BITS_ALL;
3495 m = vm_page_next(m);
3501 * Mapping function for valid or dirty bits in a page.
3503 * Inputs are required to range within a page.
3506 vm_page_bits(int base, int size)
3512 base + size <= PAGE_SIZE,
3513 ("vm_page_bits: illegal base/size %d/%d", base, size)
3516 if (size == 0) /* handle degenerate case */
3519 first_bit = base >> DEV_BSHIFT;
3520 last_bit = (base + size - 1) >> DEV_BSHIFT;
3522 return (((vm_page_bits_t)2 << last_bit) -
3523 ((vm_page_bits_t)1 << first_bit));
3527 * vm_page_set_valid_range:
3529 * Sets portions of a page valid. The arguments are expected
3530 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3531 * of any partial chunks touched by the range. The invalid portion of
3532 * such chunks will be zeroed.
3534 * (base + size) must be less then or equal to PAGE_SIZE.
3537 vm_page_set_valid_range(vm_page_t m, int base, int size)
3541 VM_OBJECT_ASSERT_WLOCKED(m->object);
3542 if (size == 0) /* handle degenerate case */
3546 * If the base is not DEV_BSIZE aligned and the valid
3547 * bit is clear, we have to zero out a portion of the
3550 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3551 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
3552 pmap_zero_page_area(m, frag, base - frag);
3555 * If the ending offset is not DEV_BSIZE aligned and the
3556 * valid bit is clear, we have to zero out a portion of
3559 endoff = base + size;
3560 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3561 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
3562 pmap_zero_page_area(m, endoff,
3563 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3566 * Assert that no previously invalid block that is now being validated
3569 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
3570 ("vm_page_set_valid_range: page %p is dirty", m));
3573 * Set valid bits inclusive of any overlap.
3575 m->valid |= vm_page_bits(base, size);
3579 * Clear the given bits from the specified page's dirty field.
3581 static __inline void
3582 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
3585 #if PAGE_SIZE < 16384
3590 * If the object is locked and the page is neither exclusive busy nor
3591 * write mapped, then the page's dirty field cannot possibly be
3592 * set by a concurrent pmap operation.
3594 VM_OBJECT_ASSERT_WLOCKED(m->object);
3595 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
3596 m->dirty &= ~pagebits;
3599 * The pmap layer can call vm_page_dirty() without
3600 * holding a distinguished lock. The combination of
3601 * the object's lock and an atomic operation suffice
3602 * to guarantee consistency of the page dirty field.
3604 * For PAGE_SIZE == 32768 case, compiler already
3605 * properly aligns the dirty field, so no forcible
3606 * alignment is needed. Only require existence of
3607 * atomic_clear_64 when page size is 32768.
3609 addr = (uintptr_t)&m->dirty;
3610 #if PAGE_SIZE == 32768
3611 atomic_clear_64((uint64_t *)addr, pagebits);
3612 #elif PAGE_SIZE == 16384
3613 atomic_clear_32((uint32_t *)addr, pagebits);
3614 #else /* PAGE_SIZE <= 8192 */
3616 * Use a trick to perform a 32-bit atomic on the
3617 * containing aligned word, to not depend on the existence
3618 * of atomic_clear_{8, 16}.
3620 shift = addr & (sizeof(uint32_t) - 1);
3621 #if BYTE_ORDER == BIG_ENDIAN
3622 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
3626 addr &= ~(sizeof(uint32_t) - 1);
3627 atomic_clear_32((uint32_t *)addr, pagebits << shift);
3628 #endif /* PAGE_SIZE */
3633 * vm_page_set_validclean:
3635 * Sets portions of a page valid and clean. The arguments are expected
3636 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3637 * of any partial chunks touched by the range. The invalid portion of
3638 * such chunks will be zero'd.
3640 * (base + size) must be less then or equal to PAGE_SIZE.
3643 vm_page_set_validclean(vm_page_t m, int base, int size)
3645 vm_page_bits_t oldvalid, pagebits;
3648 VM_OBJECT_ASSERT_WLOCKED(m->object);
3649 if (size == 0) /* handle degenerate case */
3653 * If the base is not DEV_BSIZE aligned and the valid
3654 * bit is clear, we have to zero out a portion of the
3657 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3658 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
3659 pmap_zero_page_area(m, frag, base - frag);
3662 * If the ending offset is not DEV_BSIZE aligned and the
3663 * valid bit is clear, we have to zero out a portion of
3666 endoff = base + size;
3667 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3668 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
3669 pmap_zero_page_area(m, endoff,
3670 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3673 * Set valid, clear dirty bits. If validating the entire
3674 * page we can safely clear the pmap modify bit. We also
3675 * use this opportunity to clear the VPO_NOSYNC flag. If a process
3676 * takes a write fault on a MAP_NOSYNC memory area the flag will
3679 * We set valid bits inclusive of any overlap, but we can only
3680 * clear dirty bits for DEV_BSIZE chunks that are fully within
3683 oldvalid = m->valid;
3684 pagebits = vm_page_bits(base, size);
3685 m->valid |= pagebits;
3687 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
3688 frag = DEV_BSIZE - frag;
3694 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
3696 if (base == 0 && size == PAGE_SIZE) {
3698 * The page can only be modified within the pmap if it is
3699 * mapped, and it can only be mapped if it was previously
3702 if (oldvalid == VM_PAGE_BITS_ALL)
3704 * Perform the pmap_clear_modify() first. Otherwise,
3705 * a concurrent pmap operation, such as
3706 * pmap_protect(), could clear a modification in the
3707 * pmap and set the dirty field on the page before
3708 * pmap_clear_modify() had begun and after the dirty
3709 * field was cleared here.
3711 pmap_clear_modify(m);
3713 m->oflags &= ~VPO_NOSYNC;
3714 } else if (oldvalid != VM_PAGE_BITS_ALL)
3715 m->dirty &= ~pagebits;
3717 vm_page_clear_dirty_mask(m, pagebits);
3721 vm_page_clear_dirty(vm_page_t m, int base, int size)
3724 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
3728 * vm_page_set_invalid:
3730 * Invalidates DEV_BSIZE'd chunks within a page. Both the
3731 * valid and dirty bits for the effected areas are cleared.
3734 vm_page_set_invalid(vm_page_t m, int base, int size)
3736 vm_page_bits_t bits;
3740 VM_OBJECT_ASSERT_WLOCKED(object);
3741 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
3742 size >= object->un_pager.vnp.vnp_size)
3743 bits = VM_PAGE_BITS_ALL;
3745 bits = vm_page_bits(base, size);
3746 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
3749 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3750 !pmap_page_is_mapped(m),
3751 ("vm_page_set_invalid: page %p is mapped", m));
3757 * vm_page_zero_invalid()
3759 * The kernel assumes that the invalid portions of a page contain
3760 * garbage, but such pages can be mapped into memory by user code.
3761 * When this occurs, we must zero out the non-valid portions of the
3762 * page so user code sees what it expects.
3764 * Pages are most often semi-valid when the end of a file is mapped
3765 * into memory and the file's size is not page aligned.
3768 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3773 VM_OBJECT_ASSERT_WLOCKED(m->object);
3775 * Scan the valid bits looking for invalid sections that
3776 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
3777 * valid bit may be set ) have already been zeroed by
3778 * vm_page_set_validclean().
3780 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3781 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3782 (m->valid & ((vm_page_bits_t)1 << i))) {
3784 pmap_zero_page_area(m,
3785 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3792 * setvalid is TRUE when we can safely set the zero'd areas
3793 * as being valid. We can do this if there are no cache consistancy
3794 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3797 m->valid = VM_PAGE_BITS_ALL;
3803 * Is (partial) page valid? Note that the case where size == 0
3804 * will return FALSE in the degenerate case where the page is
3805 * entirely invalid, and TRUE otherwise.
3808 vm_page_is_valid(vm_page_t m, int base, int size)
3810 vm_page_bits_t bits;
3812 VM_OBJECT_ASSERT_LOCKED(m->object);
3813 bits = vm_page_bits(base, size);
3814 return (m->valid != 0 && (m->valid & bits) == bits);
3818 * Returns true if all of the specified predicates are true for the entire
3819 * (super)page and false otherwise.
3822 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
3828 VM_OBJECT_ASSERT_LOCKED(object);
3829 npages = atop(pagesizes[m->psind]);
3832 * The physically contiguous pages that make up a superpage, i.e., a
3833 * page with a page size index ("psind") greater than zero, will
3834 * occupy adjacent entries in vm_page_array[].
3836 for (i = 0; i < npages; i++) {
3837 /* Always test object consistency, including "skip_m". */
3838 if (m[i].object != object)
3840 if (&m[i] == skip_m)
3842 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
3844 if ((flags & PS_ALL_DIRTY) != 0) {
3846 * Calling vm_page_test_dirty() or pmap_is_modified()
3847 * might stop this case from spuriously returning
3848 * "false". However, that would require a write lock
3849 * on the object containing "m[i]".
3851 if (m[i].dirty != VM_PAGE_BITS_ALL)
3854 if ((flags & PS_ALL_VALID) != 0 &&
3855 m[i].valid != VM_PAGE_BITS_ALL)
3862 * Set the page's dirty bits if the page is modified.
3865 vm_page_test_dirty(vm_page_t m)
3868 VM_OBJECT_ASSERT_WLOCKED(m->object);
3869 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3874 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3877 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3881 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3884 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3888 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3891 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3894 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3896 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3899 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3903 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3906 mtx_assert_(vm_page_lockptr(m), a, file, line);
3912 vm_page_object_lock_assert(vm_page_t m)
3916 * Certain of the page's fields may only be modified by the
3917 * holder of the containing object's lock or the exclusive busy.
3918 * holder. Unfortunately, the holder of the write busy is
3919 * not recorded, and thus cannot be checked here.
3921 if (m->object != NULL && !vm_page_xbusied(m))
3922 VM_OBJECT_ASSERT_WLOCKED(m->object);
3926 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3929 if ((bits & PGA_WRITEABLE) == 0)
3933 * The PGA_WRITEABLE flag can only be set if the page is
3934 * managed, is exclusively busied or the object is locked.
3935 * Currently, this flag is only set by pmap_enter().
3937 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3938 ("PGA_WRITEABLE on unmanaged page"));
3939 if (!vm_page_xbusied(m))
3940 VM_OBJECT_ASSERT_LOCKED(m->object);
3944 #include "opt_ddb.h"
3946 #include <sys/kernel.h>
3948 #include <ddb/ddb.h>
3950 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3953 db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
3954 db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
3955 db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
3956 db_printf("vm_cnt.v_laundry_count: %d\n", vm_cnt.v_laundry_count);
3957 db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
3958 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
3959 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
3960 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
3961 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
3964 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3968 db_printf("pq_free %d\n", vm_cnt.v_free_count);
3969 for (dom = 0; dom < vm_ndomains; dom++) {
3971 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
3973 vm_dom[dom].vmd_page_count,
3974 vm_dom[dom].vmd_free_count,
3975 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3976 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
3977 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
3978 vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
3982 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3988 db_printf("show pginfo addr\n");
3992 phys = strchr(modif, 'p') != NULL;
3994 m = PHYS_TO_VM_PAGE(addr);
3996 m = (vm_page_t)addr;
3998 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3999 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
4000 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
4001 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
4002 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);