2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1991 Regents of the University of California.
6 * Copyright (c) 1998 Matthew Dillon. All Rights Reserved.
8 * This code is derived from software contributed to Berkeley by
9 * The Mach Operating System project at Carnegie-Mellon University.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * from: @(#)vm_page.c 7.4 (Berkeley) 5/7/91
39 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
40 * All rights reserved.
42 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
44 * Permission to use, copy, modify and distribute this software and
45 * its documentation is hereby granted, provided that both the copyright
46 * notice and this permission notice appear in all copies of the
47 * software, derivative works or modified versions, and any portions
48 * thereof, and that both notices appear in supporting documentation.
50 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
51 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
52 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
54 * Carnegie Mellon requests users of this software to return to
56 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
57 * School of Computer Science
58 * Carnegie Mellon University
59 * Pittsburgh PA 15213-3890
61 * any improvements or extensions that they make and grant Carnegie the
62 * rights to redistribute these changes.
66 * GENERAL RULES ON VM_PAGE MANIPULATION
68 * - A page queue lock is required when adding or removing a page from a
69 * page queue regardless of other locks or the busy state of a page.
71 * * In general, no thread besides the page daemon can acquire or
72 * hold more than one page queue lock at a time.
74 * * The page daemon can acquire and hold any pair of page queue
77 * - The object lock is required when inserting or removing
78 * pages from an object (vm_page_insert() or vm_page_remove()).
83 * Resident memory management module.
86 #include <sys/cdefs.h>
87 __FBSDID("$FreeBSD$");
91 #include <sys/param.h>
92 #include <sys/systm.h>
94 #include <sys/kernel.h>
95 #include <sys/limits.h>
96 #include <sys/linker.h>
97 #include <sys/malloc.h>
99 #include <sys/msgbuf.h>
100 #include <sys/mutex.h>
101 #include <sys/proc.h>
102 #include <sys/rwlock.h>
103 #include <sys/sbuf.h>
105 #include <sys/sysctl.h>
106 #include <sys/vmmeter.h>
107 #include <sys/vnode.h>
111 #include <vm/vm_param.h>
112 #include <vm/vm_kern.h>
113 #include <vm/vm_object.h>
114 #include <vm/vm_page.h>
115 #include <vm/vm_pageout.h>
116 #include <vm/vm_pager.h>
117 #include <vm/vm_phys.h>
118 #include <vm/vm_radix.h>
119 #include <vm/vm_reserv.h>
120 #include <vm/vm_extern.h>
122 #include <vm/uma_int.h>
124 #include <machine/md_var.h>
127 * Associated with page of user-allocatable memory is a
131 struct vm_domain vm_dom[MAXMEMDOM];
132 struct mtx_padalign __exclusive_cache_line vm_page_queue_free_mtx;
134 struct mtx_padalign __exclusive_cache_line pa_lock[PA_LOCK_COUNT];
137 * bogus page -- for I/O to/from partially complete buffers,
138 * or for paging into sparsely invalid regions.
140 vm_page_t bogus_page;
142 vm_page_t vm_page_array;
143 long vm_page_array_size;
146 static int boot_pages = UMA_BOOT_PAGES;
147 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
149 "number of pages allocated for bootstrapping the VM system");
151 static int pa_tryrelock_restart;
152 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
153 &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
155 static TAILQ_HEAD(, vm_page) blacklist_head;
156 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
157 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
158 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
160 /* Is the page daemon waiting for free pages? */
161 static int vm_pageout_pages_needed;
163 static uma_zone_t fakepg_zone;
165 static void vm_page_alloc_check(vm_page_t m);
166 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
167 static void vm_page_enqueue(uint8_t queue, vm_page_t m);
168 static void vm_page_free_phys(vm_page_t m);
169 static void vm_page_free_wakeup(void);
170 static void vm_page_init(void *dummy);
171 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
172 vm_pindex_t pindex, vm_page_t mpred);
173 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
175 static int vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
177 static int vm_page_alloc_fail(vm_object_t object, int req);
179 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
182 vm_page_init(void *dummy)
185 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
186 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
187 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
188 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
191 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
192 #if PAGE_SIZE == 32768
194 CTASSERT(sizeof(u_long) >= 8);
199 * Try to acquire a physical address lock while a pmap is locked. If we
200 * fail to trylock we unlock and lock the pmap directly and cache the
201 * locked pa in *locked. The caller should then restart their loop in case
202 * the virtual to physical mapping has changed.
205 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
212 PA_LOCK_ASSERT(lockpa, MA_OWNED);
213 if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
220 atomic_add_int(&pa_tryrelock_restart, 1);
229 * Sets the page size, perhaps based upon the memory
230 * size. Must be called before any use of page-size
231 * dependent functions.
234 vm_set_page_size(void)
236 if (vm_cnt.v_page_size == 0)
237 vm_cnt.v_page_size = PAGE_SIZE;
238 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
239 panic("vm_set_page_size: page size not a power of two");
243 * vm_page_blacklist_next:
245 * Find the next entry in the provided string of blacklist
246 * addresses. Entries are separated by space, comma, or newline.
247 * If an invalid integer is encountered then the rest of the
248 * string is skipped. Updates the list pointer to the next
249 * character, or NULL if the string is exhausted or invalid.
252 vm_page_blacklist_next(char **list, char *end)
257 if (list == NULL || *list == NULL)
265 * If there's no end pointer then the buffer is coming from
266 * the kenv and we know it's null-terminated.
269 end = *list + strlen(*list);
271 /* Ensure that strtoq() won't walk off the end */
273 if (*end == '\n' || *end == ' ' || *end == ',')
276 printf("Blacklist not terminated, skipping\n");
282 for (pos = *list; *pos != '\0'; pos = cp) {
283 bad = strtoq(pos, &cp, 0);
284 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
293 if (*cp == '\0' || ++cp >= end)
297 return (trunc_page(bad));
299 printf("Garbage in RAM blacklist, skipping\n");
305 * vm_page_blacklist_check:
307 * Iterate through the provided string of blacklist addresses, pulling
308 * each entry out of the physical allocator free list and putting it
309 * onto a list for reporting via the vm.page_blacklist sysctl.
312 vm_page_blacklist_check(char *list, char *end)
320 while (next != NULL) {
321 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
323 m = vm_phys_paddr_to_vm_page(pa);
326 mtx_lock(&vm_page_queue_free_mtx);
327 ret = vm_phys_unfree_page(m);
328 mtx_unlock(&vm_page_queue_free_mtx);
330 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
332 printf("Skipping page with pa 0x%jx\n",
339 * vm_page_blacklist_load:
341 * Search for a special module named "ram_blacklist". It'll be a
342 * plain text file provided by the user via the loader directive
346 vm_page_blacklist_load(char **list, char **end)
355 mod = preload_search_by_type("ram_blacklist");
357 ptr = preload_fetch_addr(mod);
358 len = preload_fetch_size(mod);
369 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
376 error = sysctl_wire_old_buffer(req, 0);
379 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
380 TAILQ_FOREACH(m, &blacklist_head, listq) {
381 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
382 (uintmax_t)m->phys_addr);
385 error = sbuf_finish(&sbuf);
391 vm_page_domain_init(struct vm_domain *vmd)
393 struct vm_pagequeue *pq;
396 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
397 "vm inactive pagequeue";
398 *__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_vcnt) =
399 &vm_cnt.v_inactive_count;
400 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
401 "vm active pagequeue";
402 *__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_vcnt) =
403 &vm_cnt.v_active_count;
404 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
405 "vm laundry pagequeue";
406 *__DECONST(int **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_vcnt) =
407 &vm_cnt.v_laundry_count;
408 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_name) =
409 "vm unswappable pagequeue";
410 /* Unswappable dirty pages are counted as being in the laundry. */
411 *__DECONST(int **, &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_vcnt) =
412 &vm_cnt.v_laundry_count;
413 vmd->vmd_page_count = 0;
414 vmd->vmd_free_count = 0;
416 vmd->vmd_oom = FALSE;
417 for (i = 0; i < PQ_COUNT; i++) {
418 pq = &vmd->vmd_pagequeues[i];
419 TAILQ_INIT(&pq->pq_pl);
420 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
421 MTX_DEF | MTX_DUPOK);
428 * Initializes the resident memory module. Allocates physical memory for
429 * bootstrapping UMA and some data structures that are used to manage
430 * physical pages. Initializes these structures, and populates the free
434 vm_page_startup(vm_offset_t vaddr)
436 struct vm_domain *vmd;
437 struct vm_phys_seg *seg;
439 char *list, *listend;
441 vm_paddr_t end, high_avail, low_avail, new_end, page_range, size;
442 vm_paddr_t biggestsize, last_pa, pa;
444 int biggestone, i, pages_per_zone, segind;
448 vaddr = round_page(vaddr);
450 for (i = 0; phys_avail[i + 1]; i += 2) {
451 phys_avail[i] = round_page(phys_avail[i]);
452 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
454 for (i = 0; phys_avail[i + 1]; i += 2) {
455 size = phys_avail[i + 1] - phys_avail[i];
456 if (size > biggestsize) {
462 end = phys_avail[biggestone+1];
465 * Initialize the page and queue locks.
467 mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
468 for (i = 0; i < PA_LOCK_COUNT; i++)
469 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
470 for (i = 0; i < vm_ndomains; i++)
471 vm_page_domain_init(&vm_dom[i]);
474 * Almost all of the pages needed for bootstrapping UMA are used
475 * for zone structures, so if the number of CPUs results in those
476 * structures taking more than one page each, we set aside more pages
477 * in proportion to the zone structure size.
479 pages_per_zone = howmany(sizeof(struct uma_zone) +
480 sizeof(struct uma_cache) * (mp_maxid + 1) +
481 roundup2(sizeof(struct uma_slab), sizeof(void *)), UMA_SLAB_SIZE);
482 if (pages_per_zone > 1) {
483 /* Reserve more pages so that we don't run out. */
484 boot_pages = UMA_BOOT_PAGES_ZONES * pages_per_zone;
488 * Allocate memory for use when boot strapping the kernel memory
491 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
492 * manually fetch the value.
494 TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
495 new_end = end - (boot_pages * UMA_SLAB_SIZE);
496 new_end = trunc_page(new_end);
497 mapped = pmap_map(&vaddr, new_end, end,
498 VM_PROT_READ | VM_PROT_WRITE);
499 bzero((void *)mapped, end - new_end);
500 uma_startup((void *)mapped, boot_pages);
502 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
503 defined(__i386__) || defined(__mips__)
505 * Allocate a bitmap to indicate that a random physical page
506 * needs to be included in a minidump.
508 * The amd64 port needs this to indicate which direct map pages
509 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
511 * However, i386 still needs this workspace internally within the
512 * minidump code. In theory, they are not needed on i386, but are
513 * included should the sf_buf code decide to use them.
516 for (i = 0; dump_avail[i + 1] != 0; i += 2)
517 if (dump_avail[i + 1] > last_pa)
518 last_pa = dump_avail[i + 1];
519 page_range = last_pa / PAGE_SIZE;
520 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
521 new_end -= vm_page_dump_size;
522 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
523 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
524 bzero((void *)vm_page_dump, vm_page_dump_size);
528 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
530 * Include the UMA bootstrap pages and vm_page_dump in a crash dump.
531 * When pmap_map() uses the direct map, they are not automatically
534 for (pa = new_end; pa < end; pa += PAGE_SIZE)
537 phys_avail[biggestone + 1] = new_end;
540 * Request that the physical pages underlying the message buffer be
541 * included in a crash dump. Since the message buffer is accessed
542 * through the direct map, they are not automatically included.
544 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
545 last_pa = pa + round_page(msgbufsize);
546 while (pa < last_pa) {
552 * Compute the number of pages of memory that will be available for
553 * use, taking into account the overhead of a page structure per page.
554 * In other words, solve
555 * "available physical memory" - round_page(page_range *
556 * sizeof(struct vm_page)) = page_range * PAGE_SIZE
559 low_avail = phys_avail[0];
560 high_avail = phys_avail[1];
561 for (i = 0; i < vm_phys_nsegs; i++) {
562 if (vm_phys_segs[i].start < low_avail)
563 low_avail = vm_phys_segs[i].start;
564 if (vm_phys_segs[i].end > high_avail)
565 high_avail = vm_phys_segs[i].end;
567 /* Skip the first chunk. It is already accounted for. */
568 for (i = 2; phys_avail[i + 1] != 0; i += 2) {
569 if (phys_avail[i] < low_avail)
570 low_avail = phys_avail[i];
571 if (phys_avail[i + 1] > high_avail)
572 high_avail = phys_avail[i + 1];
574 first_page = low_avail / PAGE_SIZE;
575 #ifdef VM_PHYSSEG_SPARSE
577 for (i = 0; i < vm_phys_nsegs; i++)
578 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
579 for (i = 0; phys_avail[i + 1] != 0; i += 2)
580 size += phys_avail[i + 1] - phys_avail[i];
581 #elif defined(VM_PHYSSEG_DENSE)
582 size = high_avail - low_avail;
584 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
587 #ifdef VM_PHYSSEG_DENSE
589 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
590 * the overhead of a page structure per page only if vm_page_array is
591 * allocated from the last physical memory chunk. Otherwise, we must
592 * allocate page structures representing the physical memory
593 * underlying vm_page_array, even though they will not be used.
595 if (new_end != high_avail)
596 page_range = size / PAGE_SIZE;
600 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
603 * If the partial bytes remaining are large enough for
604 * a page (PAGE_SIZE) without a corresponding
605 * 'struct vm_page', then new_end will contain an
606 * extra page after subtracting the length of the VM
607 * page array. Compensate by subtracting an extra
610 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
611 if (new_end == high_avail)
612 high_avail -= PAGE_SIZE;
613 new_end -= PAGE_SIZE;
619 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
620 * However, because this page is allocated from KVM, out-of-bounds
621 * accesses using the direct map will not be trapped.
626 * Allocate physical memory for the page structures, and map it.
628 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
629 mapped = pmap_map(&vaddr, new_end, end,
630 VM_PROT_READ | VM_PROT_WRITE);
631 vm_page_array = (vm_page_t)mapped;
632 vm_page_array_size = page_range;
634 #if VM_NRESERVLEVEL > 0
636 * Allocate physical memory for the reservation management system's
637 * data structures, and map it.
639 if (high_avail == end)
640 high_avail = new_end;
641 new_end = vm_reserv_startup(&vaddr, new_end, high_avail);
643 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
645 * Include vm_page_array and vm_reserv_array in a crash dump.
647 for (pa = new_end; pa < end; pa += PAGE_SIZE)
650 phys_avail[biggestone + 1] = new_end;
653 * Add physical memory segments corresponding to the available
656 for (i = 0; phys_avail[i + 1] != 0; i += 2)
657 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
660 * Initialize the physical memory allocator.
665 * Initialize the page structures and add every available page to the
666 * physical memory allocator's free lists.
668 vm_cnt.v_page_count = 0;
669 vm_cnt.v_free_count = 0;
670 for (segind = 0; segind < vm_phys_nsegs; segind++) {
671 seg = &vm_phys_segs[segind];
672 for (pa = seg->start; pa < seg->end; pa += PAGE_SIZE)
673 vm_phys_init_page(pa);
676 * Add the segment to the free lists only if it is covered by
677 * one of the ranges in phys_avail. Because we've added the
678 * ranges to the vm_phys_segs array, we can assume that each
679 * segment is either entirely contained in one of the ranges,
680 * or doesn't overlap any of them.
682 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
683 if (seg->start < phys_avail[i] ||
684 seg->end > phys_avail[i + 1])
688 pagecount = (u_long)atop(seg->end - seg->start);
690 mtx_lock(&vm_page_queue_free_mtx);
691 vm_phys_free_contig(m, pagecount);
692 vm_phys_freecnt_adj(m, (int)pagecount);
693 mtx_unlock(&vm_page_queue_free_mtx);
694 vm_cnt.v_page_count += (u_int)pagecount;
696 vmd = &vm_dom[seg->domain];
697 vmd->vmd_page_count += (u_int)pagecount;
698 vmd->vmd_segs |= 1UL << m->segind;
704 * Remove blacklisted pages from the physical memory allocator.
706 TAILQ_INIT(&blacklist_head);
707 vm_page_blacklist_load(&list, &listend);
708 vm_page_blacklist_check(list, listend);
710 list = kern_getenv("vm.blacklist");
711 vm_page_blacklist_check(list, NULL);
714 #if VM_NRESERVLEVEL > 0
716 * Initialize the reservation management system.
724 vm_page_reference(vm_page_t m)
727 vm_page_aflag_set(m, PGA_REFERENCED);
731 * vm_page_busy_downgrade:
733 * Downgrade an exclusive busy page into a single shared busy page.
736 vm_page_busy_downgrade(vm_page_t m)
741 vm_page_assert_xbusied(m);
742 locked = mtx_owned(vm_page_lockptr(m));
746 x &= VPB_BIT_WAITERS;
747 if (x != 0 && !locked)
749 if (atomic_cmpset_rel_int(&m->busy_lock,
750 VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1)))
752 if (x != 0 && !locked)
765 * Return a positive value if the page is shared busied, 0 otherwise.
768 vm_page_sbusied(vm_page_t m)
773 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
779 * Shared unbusy a page.
782 vm_page_sunbusy(vm_page_t m)
786 vm_page_lock_assert(m, MA_NOTOWNED);
787 vm_page_assert_sbusied(m);
791 if (VPB_SHARERS(x) > 1) {
792 if (atomic_cmpset_int(&m->busy_lock, x,
797 if ((x & VPB_BIT_WAITERS) == 0) {
798 KASSERT(x == VPB_SHARERS_WORD(1),
799 ("vm_page_sunbusy: invalid lock state"));
800 if (atomic_cmpset_int(&m->busy_lock,
801 VPB_SHARERS_WORD(1), VPB_UNBUSIED))
805 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
806 ("vm_page_sunbusy: invalid lock state for waiters"));
809 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
820 * vm_page_busy_sleep:
822 * Sleep and release the page lock, using the page pointer as wchan.
823 * This is used to implement the hard-path of busying mechanism.
825 * The given page must be locked.
827 * If nonshared is true, sleep only if the page is xbusy.
830 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
834 vm_page_assert_locked(m);
837 if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
838 ((x & VPB_BIT_WAITERS) == 0 &&
839 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
843 msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
849 * Try to shared busy a page.
850 * If the operation succeeds 1 is returned otherwise 0.
851 * The operation never sleeps.
854 vm_page_trysbusy(vm_page_t m)
860 if ((x & VPB_BIT_SHARED) == 0)
862 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
868 vm_page_xunbusy_locked(vm_page_t m)
871 vm_page_assert_xbusied(m);
872 vm_page_assert_locked(m);
874 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
875 /* There is a waiter, do wakeup() instead of vm_page_flash(). */
880 vm_page_xunbusy_maybelocked(vm_page_t m)
884 vm_page_assert_xbusied(m);
887 * Fast path for unbusy. If it succeeds, we know that there
888 * are no waiters, so we do not need a wakeup.
890 if (atomic_cmpset_rel_int(&m->busy_lock, VPB_SINGLE_EXCLUSIVER,
894 lockacq = !mtx_owned(vm_page_lockptr(m));
897 vm_page_xunbusy_locked(m);
903 * vm_page_xunbusy_hard:
905 * Called after the first try the exclusive unbusy of a page failed.
906 * It is assumed that the waiters bit is on.
909 vm_page_xunbusy_hard(vm_page_t m)
912 vm_page_assert_xbusied(m);
915 vm_page_xunbusy_locked(m);
922 * Wakeup anyone waiting for the page.
923 * The ownership bits do not change.
925 * The given page must be locked.
928 vm_page_flash(vm_page_t m)
932 vm_page_lock_assert(m, MA_OWNED);
936 if ((x & VPB_BIT_WAITERS) == 0)
938 if (atomic_cmpset_int(&m->busy_lock, x,
939 x & (~VPB_BIT_WAITERS)))
946 * Avoid releasing and reacquiring the same page lock.
949 vm_page_change_lock(vm_page_t m, struct mtx **mtx)
953 mtx1 = vm_page_lockptr(m);
963 * Keep page from being freed by the page daemon
964 * much of the same effect as wiring, except much lower
965 * overhead and should be used only for *very* temporary
966 * holding ("wiring").
969 vm_page_hold(vm_page_t mem)
972 vm_page_lock_assert(mem, MA_OWNED);
977 vm_page_unhold(vm_page_t mem)
980 vm_page_lock_assert(mem, MA_OWNED);
981 KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
983 if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
984 vm_page_free_toq(mem);
988 * vm_page_unhold_pages:
990 * Unhold each of the pages that is referenced by the given array.
993 vm_page_unhold_pages(vm_page_t *ma, int count)
998 for (; count != 0; count--) {
999 vm_page_change_lock(*ma, &mtx);
1000 vm_page_unhold(*ma);
1008 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1012 #ifdef VM_PHYSSEG_SPARSE
1013 m = vm_phys_paddr_to_vm_page(pa);
1015 m = vm_phys_fictitious_to_vm_page(pa);
1017 #elif defined(VM_PHYSSEG_DENSE)
1021 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1022 m = &vm_page_array[pi - first_page];
1025 return (vm_phys_fictitious_to_vm_page(pa));
1027 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1034 * Create a fictitious page with the specified physical address and
1035 * memory attribute. The memory attribute is the only the machine-
1036 * dependent aspect of a fictitious page that must be initialized.
1039 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1043 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1044 vm_page_initfake(m, paddr, memattr);
1049 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1052 if ((m->flags & PG_FICTITIOUS) != 0) {
1054 * The page's memattr might have changed since the
1055 * previous initialization. Update the pmap to the
1060 m->phys_addr = paddr;
1062 /* Fictitious pages don't use "segind". */
1063 m->flags = PG_FICTITIOUS;
1064 /* Fictitious pages don't use "order" or "pool". */
1065 m->oflags = VPO_UNMANAGED;
1066 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1070 pmap_page_set_memattr(m, memattr);
1076 * Release a fictitious page.
1079 vm_page_putfake(vm_page_t m)
1082 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1083 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1084 ("vm_page_putfake: bad page %p", m));
1085 uma_zfree(fakepg_zone, m);
1089 * vm_page_updatefake:
1091 * Update the given fictitious page to the specified physical address and
1095 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1098 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1099 ("vm_page_updatefake: bad page %p", m));
1100 m->phys_addr = paddr;
1101 pmap_page_set_memattr(m, memattr);
1110 vm_page_free(vm_page_t m)
1113 m->flags &= ~PG_ZERO;
1114 vm_page_free_toq(m);
1118 * vm_page_free_zero:
1120 * Free a page to the zerod-pages queue
1123 vm_page_free_zero(vm_page_t m)
1126 m->flags |= PG_ZERO;
1127 vm_page_free_toq(m);
1131 * Unbusy and handle the page queueing for a page from a getpages request that
1132 * was optionally read ahead or behind.
1135 vm_page_readahead_finish(vm_page_t m)
1138 /* We shouldn't put invalid pages on queues. */
1139 KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
1142 * Since the page is not the actually needed one, whether it should
1143 * be activated or deactivated is not obvious. Empirical results
1144 * have shown that deactivating the page is usually the best choice,
1145 * unless the page is wanted by another thread.
1148 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1149 vm_page_activate(m);
1151 vm_page_deactivate(m);
1157 * vm_page_sleep_if_busy:
1159 * Sleep and release the page queues lock if the page is busied.
1160 * Returns TRUE if the thread slept.
1162 * The given page must be unlocked and object containing it must
1166 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1170 vm_page_lock_assert(m, MA_NOTOWNED);
1171 VM_OBJECT_ASSERT_WLOCKED(m->object);
1173 if (vm_page_busied(m)) {
1175 * The page-specific object must be cached because page
1176 * identity can change during the sleep, causing the
1177 * re-lock of a different object.
1178 * It is assumed that a reference to the object is already
1179 * held by the callers.
1183 VM_OBJECT_WUNLOCK(obj);
1184 vm_page_busy_sleep(m, msg, false);
1185 VM_OBJECT_WLOCK(obj);
1192 * vm_page_dirty_KBI: [ internal use only ]
1194 * Set all bits in the page's dirty field.
1196 * The object containing the specified page must be locked if the
1197 * call is made from the machine-independent layer.
1199 * See vm_page_clear_dirty_mask().
1201 * This function should only be called by vm_page_dirty().
1204 vm_page_dirty_KBI(vm_page_t m)
1207 /* Refer to this operation by its public name. */
1208 KASSERT(m->valid == VM_PAGE_BITS_ALL,
1209 ("vm_page_dirty: page is invalid!"));
1210 m->dirty = VM_PAGE_BITS_ALL;
1214 * vm_page_insert: [ internal use only ]
1216 * Inserts the given mem entry into the object and object list.
1218 * The object must be locked.
1221 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1225 VM_OBJECT_ASSERT_WLOCKED(object);
1226 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1227 return (vm_page_insert_after(m, object, pindex, mpred));
1231 * vm_page_insert_after:
1233 * Inserts the page "m" into the specified object at offset "pindex".
1235 * The page "mpred" must immediately precede the offset "pindex" within
1236 * the specified object.
1238 * The object must be locked.
1241 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1246 VM_OBJECT_ASSERT_WLOCKED(object);
1247 KASSERT(m->object == NULL,
1248 ("vm_page_insert_after: page already inserted"));
1249 if (mpred != NULL) {
1250 KASSERT(mpred->object == object,
1251 ("vm_page_insert_after: object doesn't contain mpred"));
1252 KASSERT(mpred->pindex < pindex,
1253 ("vm_page_insert_after: mpred doesn't precede pindex"));
1254 msucc = TAILQ_NEXT(mpred, listq);
1256 msucc = TAILQ_FIRST(&object->memq);
1258 KASSERT(msucc->pindex > pindex,
1259 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1262 * Record the object/offset pair in this page
1268 * Now link into the object's ordered list of backed pages.
1270 if (vm_radix_insert(&object->rtree, m)) {
1275 vm_page_insert_radixdone(m, object, mpred);
1280 * vm_page_insert_radixdone:
1282 * Complete page "m" insertion into the specified object after the
1283 * radix trie hooking.
1285 * The page "mpred" must precede the offset "m->pindex" within the
1288 * The object must be locked.
1291 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1294 VM_OBJECT_ASSERT_WLOCKED(object);
1295 KASSERT(object != NULL && m->object == object,
1296 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1297 if (mpred != NULL) {
1298 KASSERT(mpred->object == object,
1299 ("vm_page_insert_after: object doesn't contain mpred"));
1300 KASSERT(mpred->pindex < m->pindex,
1301 ("vm_page_insert_after: mpred doesn't precede pindex"));
1305 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1307 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1310 * Show that the object has one more resident page.
1312 object->resident_page_count++;
1315 * Hold the vnode until the last page is released.
1317 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1318 vhold(object->handle);
1321 * Since we are inserting a new and possibly dirty page,
1322 * update the object's OBJ_MIGHTBEDIRTY flag.
1324 if (pmap_page_is_write_mapped(m))
1325 vm_object_set_writeable_dirty(object);
1331 * Removes the specified page from its containing object, but does not
1332 * invalidate any backing storage.
1334 * The object must be locked. The page must be locked if it is managed.
1337 vm_page_remove(vm_page_t m)
1342 if ((m->oflags & VPO_UNMANAGED) == 0)
1343 vm_page_assert_locked(m);
1344 if ((object = m->object) == NULL)
1346 VM_OBJECT_ASSERT_WLOCKED(object);
1347 if (vm_page_xbusied(m))
1348 vm_page_xunbusy_maybelocked(m);
1349 mrem = vm_radix_remove(&object->rtree, m->pindex);
1350 KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1353 * Now remove from the object's list of backed pages.
1355 TAILQ_REMOVE(&object->memq, m, listq);
1358 * And show that the object has one fewer resident page.
1360 object->resident_page_count--;
1363 * The vnode may now be recycled.
1365 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1366 vdrop(object->handle);
1374 * Returns the page associated with the object/offset
1375 * pair specified; if none is found, NULL is returned.
1377 * The object must be locked.
1380 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1383 VM_OBJECT_ASSERT_LOCKED(object);
1384 return (vm_radix_lookup(&object->rtree, pindex));
1388 * vm_page_find_least:
1390 * Returns the page associated with the object with least pindex
1391 * greater than or equal to the parameter pindex, or NULL.
1393 * The object must be locked.
1396 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1400 VM_OBJECT_ASSERT_LOCKED(object);
1401 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1402 m = vm_radix_lookup_ge(&object->rtree, pindex);
1407 * Returns the given page's successor (by pindex) within the object if it is
1408 * resident; if none is found, NULL is returned.
1410 * The object must be locked.
1413 vm_page_next(vm_page_t m)
1417 VM_OBJECT_ASSERT_LOCKED(m->object);
1418 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1419 MPASS(next->object == m->object);
1420 if (next->pindex != m->pindex + 1)
1427 * Returns the given page's predecessor (by pindex) within the object if it is
1428 * resident; if none is found, NULL is returned.
1430 * The object must be locked.
1433 vm_page_prev(vm_page_t m)
1437 VM_OBJECT_ASSERT_LOCKED(m->object);
1438 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1439 MPASS(prev->object == m->object);
1440 if (prev->pindex != m->pindex - 1)
1447 * Uses the page mnew as a replacement for an existing page at index
1448 * pindex which must be already present in the object.
1450 * The existing page must not be on a paging queue.
1453 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1457 VM_OBJECT_ASSERT_WLOCKED(object);
1458 KASSERT(mnew->object == NULL,
1459 ("vm_page_replace: page already in object"));
1462 * This function mostly follows vm_page_insert() and
1463 * vm_page_remove() without the radix, object count and vnode
1464 * dance. Double check such functions for more comments.
1467 mnew->object = object;
1468 mnew->pindex = pindex;
1469 mold = vm_radix_replace(&object->rtree, mnew);
1470 KASSERT(mold->queue == PQ_NONE,
1471 ("vm_page_replace: mold is on a paging queue"));
1473 /* Keep the resident page list in sorted order. */
1474 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1475 TAILQ_REMOVE(&object->memq, mold, listq);
1477 mold->object = NULL;
1478 vm_page_xunbusy_maybelocked(mold);
1481 * The object's resident_page_count does not change because we have
1482 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1484 if (pmap_page_is_write_mapped(mnew))
1485 vm_object_set_writeable_dirty(object);
1492 * Move the given memory entry from its
1493 * current object to the specified target object/offset.
1495 * Note: swap associated with the page must be invalidated by the move. We
1496 * have to do this for several reasons: (1) we aren't freeing the
1497 * page, (2) we are dirtying the page, (3) the VM system is probably
1498 * moving the page from object A to B, and will then later move
1499 * the backing store from A to B and we can't have a conflict.
1501 * Note: we *always* dirty the page. It is necessary both for the
1502 * fact that we moved it, and because we may be invalidating
1505 * The objects must be locked.
1508 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1513 VM_OBJECT_ASSERT_WLOCKED(new_object);
1515 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1516 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1517 ("vm_page_rename: pindex already renamed"));
1520 * Create a custom version of vm_page_insert() which does not depend
1521 * by m_prev and can cheat on the implementation aspects of the
1525 m->pindex = new_pindex;
1526 if (vm_radix_insert(&new_object->rtree, m)) {
1532 * The operation cannot fail anymore. The removal must happen before
1533 * the listq iterator is tainted.
1539 /* Return back to the new pindex to complete vm_page_insert(). */
1540 m->pindex = new_pindex;
1541 m->object = new_object;
1543 vm_page_insert_radixdone(m, new_object, mpred);
1551 * Allocate and return a page that is associated with the specified
1552 * object and offset pair. By default, this page is exclusive busied.
1554 * The caller must always specify an allocation class.
1556 * allocation classes:
1557 * VM_ALLOC_NORMAL normal process request
1558 * VM_ALLOC_SYSTEM system *really* needs a page
1559 * VM_ALLOC_INTERRUPT interrupt time request
1561 * optional allocation flags:
1562 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1563 * intends to allocate
1564 * VM_ALLOC_NOBUSY do not exclusive busy the page
1565 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1566 * VM_ALLOC_NOOBJ page is not associated with an object and
1567 * should not be exclusive busy
1568 * VM_ALLOC_SBUSY shared busy the allocated page
1569 * VM_ALLOC_WIRED wire the allocated page
1570 * VM_ALLOC_ZERO prefer a zeroed page
1572 * This routine may not sleep.
1575 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1578 return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1579 vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1583 * Allocate a page in the specified object with the given page index. To
1584 * optimize insertion of the page into the object, the caller must also specifiy
1585 * the resident page in the object with largest index smaller than the given
1586 * page index, or NULL if no such page exists.
1589 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex, int req,
1593 int flags, req_class;
1596 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1597 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1598 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1599 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1600 ("inconsistent object(%p)/req(%x)", object, req));
1601 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1602 ("Can't sleep and retry object insertion."));
1603 KASSERT(mpred == NULL || mpred->pindex < pindex,
1604 ("mpred %p doesn't precede pindex 0x%jx", mpred,
1605 (uintmax_t)pindex));
1607 VM_OBJECT_ASSERT_WLOCKED(object);
1609 req_class = req & VM_ALLOC_CLASS_MASK;
1612 * The page daemon is allowed to dig deeper into the free page list.
1614 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1615 req_class = VM_ALLOC_SYSTEM;
1618 * Allocate a page if the number of free pages exceeds the minimum
1619 * for the request class.
1622 mtx_lock(&vm_page_queue_free_mtx);
1623 if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
1624 (req_class == VM_ALLOC_SYSTEM &&
1625 vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
1626 (req_class == VM_ALLOC_INTERRUPT &&
1627 vm_cnt.v_free_count > 0)) {
1629 * Can we allocate the page from a reservation?
1631 #if VM_NRESERVLEVEL > 0
1632 if (object == NULL || (object->flags & (OBJ_COLORED |
1633 OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1634 vm_reserv_alloc_page(object, pindex, mpred)) == NULL)
1638 * If not, allocate it from the free page queues.
1640 m = vm_phys_alloc_pages(object != NULL ?
1641 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1642 #if VM_NRESERVLEVEL > 0
1643 if (m == NULL && vm_reserv_reclaim_inactive()) {
1644 m = vm_phys_alloc_pages(object != NULL ?
1645 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1652 * Not allocatable, give up.
1654 if (vm_page_alloc_fail(object, req))
1660 * At this point we had better have found a good page.
1662 KASSERT(m != NULL, ("missing page"));
1663 free_count = vm_phys_freecnt_adj(m, -1);
1664 mtx_unlock(&vm_page_queue_free_mtx);
1665 vm_page_alloc_check(m);
1668 * Initialize the page. Only the PG_ZERO flag is inherited.
1671 if ((req & VM_ALLOC_ZERO) != 0)
1674 if ((req & VM_ALLOC_NODUMP) != 0)
1678 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1680 m->busy_lock = VPB_UNBUSIED;
1681 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1682 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1683 if ((req & VM_ALLOC_SBUSY) != 0)
1684 m->busy_lock = VPB_SHARERS_WORD(1);
1685 if (req & VM_ALLOC_WIRED) {
1687 * The page lock is not required for wiring a page until that
1688 * page is inserted into the object.
1690 atomic_add_int(&vm_cnt.v_wire_count, 1);
1695 if (object != NULL) {
1696 if (vm_page_insert_after(m, object, pindex, mpred)) {
1697 pagedaemon_wakeup();
1698 if (req & VM_ALLOC_WIRED) {
1699 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1702 KASSERT(m->object == NULL, ("page %p has object", m));
1703 m->oflags = VPO_UNMANAGED;
1704 m->busy_lock = VPB_UNBUSIED;
1705 /* Don't change PG_ZERO. */
1706 vm_page_free_toq(m);
1707 if (req & VM_ALLOC_WAITFAIL) {
1708 VM_OBJECT_WUNLOCK(object);
1710 VM_OBJECT_WLOCK(object);
1715 /* Ignore device objects; the pager sets "memattr" for them. */
1716 if (object->memattr != VM_MEMATTR_DEFAULT &&
1717 (object->flags & OBJ_FICTITIOUS) == 0)
1718 pmap_page_set_memattr(m, object->memattr);
1723 * Don't wakeup too often - wakeup the pageout daemon when
1724 * we would be nearly out of memory.
1726 if (vm_paging_needed(free_count))
1727 pagedaemon_wakeup();
1733 * vm_page_alloc_contig:
1735 * Allocate a contiguous set of physical pages of the given size "npages"
1736 * from the free lists. All of the physical pages must be at or above
1737 * the given physical address "low" and below the given physical address
1738 * "high". The given value "alignment" determines the alignment of the
1739 * first physical page in the set. If the given value "boundary" is
1740 * non-zero, then the set of physical pages cannot cross any physical
1741 * address boundary that is a multiple of that value. Both "alignment"
1742 * and "boundary" must be a power of two.
1744 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1745 * then the memory attribute setting for the physical pages is configured
1746 * to the object's memory attribute setting. Otherwise, the memory
1747 * attribute setting for the physical pages is configured to "memattr",
1748 * overriding the object's memory attribute setting. However, if the
1749 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1750 * memory attribute setting for the physical pages cannot be configured
1751 * to VM_MEMATTR_DEFAULT.
1753 * The specified object may not contain fictitious pages.
1755 * The caller must always specify an allocation class.
1757 * allocation classes:
1758 * VM_ALLOC_NORMAL normal process request
1759 * VM_ALLOC_SYSTEM system *really* needs a page
1760 * VM_ALLOC_INTERRUPT interrupt time request
1762 * optional allocation flags:
1763 * VM_ALLOC_NOBUSY do not exclusive busy the page
1764 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1765 * VM_ALLOC_NOOBJ page is not associated with an object and
1766 * should not be exclusive busy
1767 * VM_ALLOC_SBUSY shared busy the allocated page
1768 * VM_ALLOC_WIRED wire the allocated page
1769 * VM_ALLOC_ZERO prefer a zeroed page
1771 * This routine may not sleep.
1774 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1775 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1776 vm_paddr_t boundary, vm_memattr_t memattr)
1778 vm_page_t m, m_ret, mpred;
1779 u_int busy_lock, flags, oflags;
1782 mpred = NULL; /* XXX: pacify gcc */
1783 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1784 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1785 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1786 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1787 ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
1789 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1790 ("Can't sleep and retry object insertion."));
1791 if (object != NULL) {
1792 VM_OBJECT_ASSERT_WLOCKED(object);
1793 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
1794 ("vm_page_alloc_contig: object %p has fictitious pages",
1797 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1798 req_class = req & VM_ALLOC_CLASS_MASK;
1801 * The page daemon is allowed to dig deeper into the free page list.
1803 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1804 req_class = VM_ALLOC_SYSTEM;
1806 if (object != NULL) {
1807 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1808 KASSERT(mpred == NULL || mpred->pindex != pindex,
1809 ("vm_page_alloc_contig: pindex already allocated"));
1813 * Can we allocate the pages without the number of free pages falling
1814 * below the lower bound for the allocation class?
1817 mtx_lock(&vm_page_queue_free_mtx);
1818 if (vm_cnt.v_free_count >= npages + vm_cnt.v_free_reserved ||
1819 (req_class == VM_ALLOC_SYSTEM &&
1820 vm_cnt.v_free_count >= npages + vm_cnt.v_interrupt_free_min) ||
1821 (req_class == VM_ALLOC_INTERRUPT &&
1822 vm_cnt.v_free_count >= npages)) {
1824 * Can we allocate the pages from a reservation?
1826 #if VM_NRESERVLEVEL > 0
1828 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1829 (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1830 low, high, alignment, boundary, mpred)) == NULL)
1833 * If not, allocate them from the free page queues.
1835 m_ret = vm_phys_alloc_contig(npages, low, high,
1836 alignment, boundary);
1838 if (vm_page_alloc_fail(object, req))
1843 vm_phys_freecnt_adj(m_ret, -npages);
1845 #if VM_NRESERVLEVEL > 0
1846 if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1851 mtx_unlock(&vm_page_queue_free_mtx);
1854 for (m = m_ret; m < &m_ret[npages]; m++)
1855 vm_page_alloc_check(m);
1858 * Initialize the pages. Only the PG_ZERO flag is inherited.
1861 if ((req & VM_ALLOC_ZERO) != 0)
1863 if ((req & VM_ALLOC_NODUMP) != 0)
1865 oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1867 busy_lock = VPB_UNBUSIED;
1868 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1869 busy_lock = VPB_SINGLE_EXCLUSIVER;
1870 if ((req & VM_ALLOC_SBUSY) != 0)
1871 busy_lock = VPB_SHARERS_WORD(1);
1872 if ((req & VM_ALLOC_WIRED) != 0)
1873 atomic_add_int(&vm_cnt.v_wire_count, npages);
1874 if (object != NULL) {
1875 if (object->memattr != VM_MEMATTR_DEFAULT &&
1876 memattr == VM_MEMATTR_DEFAULT)
1877 memattr = object->memattr;
1879 for (m = m_ret; m < &m_ret[npages]; m++) {
1881 m->flags = (m->flags | PG_NODUMP) & flags;
1882 m->busy_lock = busy_lock;
1883 if ((req & VM_ALLOC_WIRED) != 0)
1887 if (object != NULL) {
1888 if (vm_page_insert_after(m, object, pindex, mpred)) {
1889 pagedaemon_wakeup();
1890 if ((req & VM_ALLOC_WIRED) != 0)
1891 atomic_subtract_int(
1892 &vm_cnt.v_wire_count, npages);
1893 KASSERT(m->object == NULL,
1894 ("page %p has object", m));
1896 for (m = m_ret; m < &m_ret[npages]; m++) {
1898 (req & VM_ALLOC_WIRED) != 0)
1900 m->oflags = VPO_UNMANAGED;
1901 m->busy_lock = VPB_UNBUSIED;
1902 /* Don't change PG_ZERO. */
1903 vm_page_free_toq(m);
1905 if (req & VM_ALLOC_WAITFAIL) {
1906 VM_OBJECT_WUNLOCK(object);
1908 VM_OBJECT_WLOCK(object);
1915 if (memattr != VM_MEMATTR_DEFAULT)
1916 pmap_page_set_memattr(m, memattr);
1919 if (vm_paging_needed(vm_cnt.v_free_count))
1920 pagedaemon_wakeup();
1925 * Check a page that has been freshly dequeued from a freelist.
1928 vm_page_alloc_check(vm_page_t m)
1931 KASSERT(m->object == NULL, ("page %p has object", m));
1932 KASSERT(m->queue == PQ_NONE,
1933 ("page %p has unexpected queue %d", m, m->queue));
1934 KASSERT(m->wire_count == 0, ("page %p is wired", m));
1935 KASSERT(m->hold_count == 0, ("page %p is held", m));
1936 KASSERT(!vm_page_busied(m), ("page %p is busy", m));
1937 KASSERT(m->dirty == 0, ("page %p is dirty", m));
1938 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1939 ("page %p has unexpected memattr %d",
1940 m, pmap_page_get_memattr(m)));
1941 KASSERT(m->valid == 0, ("free page %p is valid", m));
1945 * vm_page_alloc_freelist:
1947 * Allocate a physical page from the specified free page list.
1949 * The caller must always specify an allocation class.
1951 * allocation classes:
1952 * VM_ALLOC_NORMAL normal process request
1953 * VM_ALLOC_SYSTEM system *really* needs a page
1954 * VM_ALLOC_INTERRUPT interrupt time request
1956 * optional allocation flags:
1957 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1958 * intends to allocate
1959 * VM_ALLOC_WIRED wire the allocated page
1960 * VM_ALLOC_ZERO prefer a zeroed page
1962 * This routine may not sleep.
1965 vm_page_alloc_freelist(int flind, int req)
1968 u_int flags, free_count;
1971 req_class = req & VM_ALLOC_CLASS_MASK;
1974 * The page daemon is allowed to dig deeper into the free page list.
1976 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1977 req_class = VM_ALLOC_SYSTEM;
1980 * Do not allocate reserved pages unless the req has asked for it.
1983 mtx_lock(&vm_page_queue_free_mtx);
1984 if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
1985 (req_class == VM_ALLOC_SYSTEM &&
1986 vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
1987 (req_class == VM_ALLOC_INTERRUPT &&
1988 vm_cnt.v_free_count > 0)) {
1989 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
1991 if (vm_page_alloc_fail(NULL, req))
1996 mtx_unlock(&vm_page_queue_free_mtx);
1999 free_count = vm_phys_freecnt_adj(m, -1);
2000 mtx_unlock(&vm_page_queue_free_mtx);
2001 vm_page_alloc_check(m);
2004 * Initialize the page. Only the PG_ZERO flag is inherited.
2008 if ((req & VM_ALLOC_ZERO) != 0)
2011 if ((req & VM_ALLOC_WIRED) != 0) {
2013 * The page lock is not required for wiring a page that does
2014 * not belong to an object.
2016 atomic_add_int(&vm_cnt.v_wire_count, 1);
2019 /* Unmanaged pages don't use "act_count". */
2020 m->oflags = VPO_UNMANAGED;
2021 if (vm_paging_needed(free_count))
2022 pagedaemon_wakeup();
2026 #define VPSC_ANY 0 /* No restrictions. */
2027 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2028 #define VPSC_NOSUPER 2 /* Skip superpages. */
2031 * vm_page_scan_contig:
2033 * Scan vm_page_array[] between the specified entries "m_start" and
2034 * "m_end" for a run of contiguous physical pages that satisfy the
2035 * specified conditions, and return the lowest page in the run. The
2036 * specified "alignment" determines the alignment of the lowest physical
2037 * page in the run. If the specified "boundary" is non-zero, then the
2038 * run of physical pages cannot span a physical address that is a
2039 * multiple of "boundary".
2041 * "m_end" is never dereferenced, so it need not point to a vm_page
2042 * structure within vm_page_array[].
2044 * "npages" must be greater than zero. "m_start" and "m_end" must not
2045 * span a hole (or discontiguity) in the physical address space. Both
2046 * "alignment" and "boundary" must be a power of two.
2049 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2050 u_long alignment, vm_paddr_t boundary, int options)
2056 #if VM_NRESERVLEVEL > 0
2059 int m_inc, order, run_ext, run_len;
2061 KASSERT(npages > 0, ("npages is 0"));
2062 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2063 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2067 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2068 KASSERT((m->flags & PG_MARKER) == 0,
2069 ("page %p is PG_MARKER", m));
2070 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->wire_count == 1,
2071 ("fictitious page %p has invalid wire count", m));
2074 * If the current page would be the start of a run, check its
2075 * physical address against the end, alignment, and boundary
2076 * conditions. If it doesn't satisfy these conditions, either
2077 * terminate the scan or advance to the next page that
2078 * satisfies the failed condition.
2081 KASSERT(m_run == NULL, ("m_run != NULL"));
2082 if (m + npages > m_end)
2084 pa = VM_PAGE_TO_PHYS(m);
2085 if ((pa & (alignment - 1)) != 0) {
2086 m_inc = atop(roundup2(pa, alignment) - pa);
2089 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2091 m_inc = atop(roundup2(pa, boundary) - pa);
2095 KASSERT(m_run != NULL, ("m_run == NULL"));
2097 vm_page_change_lock(m, &m_mtx);
2100 if (m->wire_count != 0 || m->hold_count != 0)
2102 #if VM_NRESERVLEVEL > 0
2103 else if ((level = vm_reserv_level(m)) >= 0 &&
2104 (options & VPSC_NORESERV) != 0) {
2106 /* Advance to the end of the reservation. */
2107 pa = VM_PAGE_TO_PHYS(m);
2108 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2112 else if ((object = m->object) != NULL) {
2114 * The page is considered eligible for relocation if
2115 * and only if it could be laundered or reclaimed by
2118 if (!VM_OBJECT_TRYRLOCK(object)) {
2120 VM_OBJECT_RLOCK(object);
2122 if (m->object != object) {
2124 * The page may have been freed.
2126 VM_OBJECT_RUNLOCK(object);
2128 } else if (m->wire_count != 0 ||
2129 m->hold_count != 0) {
2134 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2135 ("page %p is PG_UNHOLDFREE", m));
2136 /* Don't care: PG_NODUMP, PG_ZERO. */
2137 if (object->type != OBJT_DEFAULT &&
2138 object->type != OBJT_SWAP &&
2139 object->type != OBJT_VNODE) {
2141 #if VM_NRESERVLEVEL > 0
2142 } else if ((options & VPSC_NOSUPER) != 0 &&
2143 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2145 /* Advance to the end of the superpage. */
2146 pa = VM_PAGE_TO_PHYS(m);
2147 m_inc = atop(roundup2(pa + 1,
2148 vm_reserv_size(level)) - pa);
2150 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2151 m->queue != PQ_NONE && !vm_page_busied(m)) {
2153 * The page is allocated but eligible for
2154 * relocation. Extend the current run by one
2157 KASSERT(pmap_page_get_memattr(m) ==
2159 ("page %p has an unexpected memattr", m));
2160 KASSERT((m->oflags & (VPO_SWAPINPROG |
2161 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2162 ("page %p has unexpected oflags", m));
2163 /* Don't care: VPO_NOSYNC. */
2168 VM_OBJECT_RUNLOCK(object);
2169 #if VM_NRESERVLEVEL > 0
2170 } else if (level >= 0) {
2172 * The page is reserved but not yet allocated. In
2173 * other words, it is still free. Extend the current
2178 } else if ((order = m->order) < VM_NFREEORDER) {
2180 * The page is enqueued in the physical memory
2181 * allocator's free page queues. Moreover, it is the
2182 * first page in a power-of-two-sized run of
2183 * contiguous free pages. Add these pages to the end
2184 * of the current run, and jump ahead.
2186 run_ext = 1 << order;
2190 * Skip the page for one of the following reasons: (1)
2191 * It is enqueued in the physical memory allocator's
2192 * free page queues. However, it is not the first
2193 * page in a run of contiguous free pages. (This case
2194 * rarely occurs because the scan is performed in
2195 * ascending order.) (2) It is not reserved, and it is
2196 * transitioning from free to allocated. (Conversely,
2197 * the transition from allocated to free for managed
2198 * pages is blocked by the page lock.) (3) It is
2199 * allocated but not contained by an object and not
2200 * wired, e.g., allocated by Xen's balloon driver.
2206 * Extend or reset the current run of pages.
2221 if (run_len >= npages)
2227 * vm_page_reclaim_run:
2229 * Try to relocate each of the allocated virtual pages within the
2230 * specified run of physical pages to a new physical address. Free the
2231 * physical pages underlying the relocated virtual pages. A virtual page
2232 * is relocatable if and only if it could be laundered or reclaimed by
2233 * the page daemon. Whenever possible, a virtual page is relocated to a
2234 * physical address above "high".
2236 * Returns 0 if every physical page within the run was already free or
2237 * just freed by a successful relocation. Otherwise, returns a non-zero
2238 * value indicating why the last attempt to relocate a virtual page was
2241 * "req_class" must be an allocation class.
2244 vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
2248 struct spglist free;
2251 vm_page_t m, m_end, m_new;
2252 int error, order, req;
2254 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2255 ("req_class is not an allocation class"));
2259 m_end = m_run + npages;
2261 for (; error == 0 && m < m_end; m++) {
2262 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2263 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2266 * Avoid releasing and reacquiring the same page lock.
2268 vm_page_change_lock(m, &m_mtx);
2270 if (m->wire_count != 0 || m->hold_count != 0)
2272 else if ((object = m->object) != NULL) {
2274 * The page is relocated if and only if it could be
2275 * laundered or reclaimed by the page daemon.
2277 if (!VM_OBJECT_TRYWLOCK(object)) {
2279 VM_OBJECT_WLOCK(object);
2281 if (m->object != object) {
2283 * The page may have been freed.
2285 VM_OBJECT_WUNLOCK(object);
2287 } else if (m->wire_count != 0 ||
2288 m->hold_count != 0) {
2293 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2294 ("page %p is PG_UNHOLDFREE", m));
2295 /* Don't care: PG_NODUMP, PG_ZERO. */
2296 if (object->type != OBJT_DEFAULT &&
2297 object->type != OBJT_SWAP &&
2298 object->type != OBJT_VNODE)
2300 else if (object->memattr != VM_MEMATTR_DEFAULT)
2302 else if (m->queue != PQ_NONE && !vm_page_busied(m)) {
2303 KASSERT(pmap_page_get_memattr(m) ==
2305 ("page %p has an unexpected memattr", m));
2306 KASSERT((m->oflags & (VPO_SWAPINPROG |
2307 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2308 ("page %p has unexpected oflags", m));
2309 /* Don't care: VPO_NOSYNC. */
2310 if (m->valid != 0) {
2312 * First, try to allocate a new page
2313 * that is above "high". Failing
2314 * that, try to allocate a new page
2315 * that is below "m_run". Allocate
2316 * the new page between the end of
2317 * "m_run" and "high" only as a last
2320 req = req_class | VM_ALLOC_NOOBJ;
2321 if ((m->flags & PG_NODUMP) != 0)
2322 req |= VM_ALLOC_NODUMP;
2323 if (trunc_page(high) !=
2324 ~(vm_paddr_t)PAGE_MASK) {
2325 m_new = vm_page_alloc_contig(
2330 VM_MEMATTR_DEFAULT);
2333 if (m_new == NULL) {
2334 pa = VM_PAGE_TO_PHYS(m_run);
2335 m_new = vm_page_alloc_contig(
2337 0, pa - 1, PAGE_SIZE, 0,
2338 VM_MEMATTR_DEFAULT);
2340 if (m_new == NULL) {
2342 m_new = vm_page_alloc_contig(
2344 pa, high, PAGE_SIZE, 0,
2345 VM_MEMATTR_DEFAULT);
2347 if (m_new == NULL) {
2351 KASSERT(m_new->wire_count == 0,
2352 ("page %p is wired", m));
2355 * Replace "m" with the new page. For
2356 * vm_page_replace(), "m" must be busy
2357 * and dequeued. Finally, change "m"
2358 * as if vm_page_free() was called.
2360 if (object->ref_count != 0)
2362 m_new->aflags = m->aflags;
2363 KASSERT(m_new->oflags == VPO_UNMANAGED,
2364 ("page %p is managed", m));
2365 m_new->oflags = m->oflags & VPO_NOSYNC;
2366 pmap_copy_page(m, m_new);
2367 m_new->valid = m->valid;
2368 m_new->dirty = m->dirty;
2369 m->flags &= ~PG_ZERO;
2372 vm_page_replace_checked(m_new, object,
2378 * The new page must be deactivated
2379 * before the object is unlocked.
2381 vm_page_change_lock(m_new, &m_mtx);
2382 vm_page_deactivate(m_new);
2384 m->flags &= ~PG_ZERO;
2387 KASSERT(m->dirty == 0,
2388 ("page %p is dirty", m));
2390 SLIST_INSERT_HEAD(&free, m, plinks.s.ss);
2394 VM_OBJECT_WUNLOCK(object);
2396 mtx_lock(&vm_page_queue_free_mtx);
2398 if (order < VM_NFREEORDER) {
2400 * The page is enqueued in the physical memory
2401 * allocator's free page queues. Moreover, it
2402 * is the first page in a power-of-two-sized
2403 * run of contiguous free pages. Jump ahead
2404 * to the last page within that run, and
2405 * continue from there.
2407 m += (1 << order) - 1;
2409 #if VM_NRESERVLEVEL > 0
2410 else if (vm_reserv_is_page_free(m))
2413 mtx_unlock(&vm_page_queue_free_mtx);
2414 if (order == VM_NFREEORDER)
2420 if ((m = SLIST_FIRST(&free)) != NULL) {
2421 mtx_lock(&vm_page_queue_free_mtx);
2423 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2424 vm_page_free_phys(m);
2425 } while ((m = SLIST_FIRST(&free)) != NULL);
2426 vm_page_free_wakeup();
2427 mtx_unlock(&vm_page_queue_free_mtx);
2434 CTASSERT(powerof2(NRUNS));
2436 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2438 #define MIN_RECLAIM 8
2441 * vm_page_reclaim_contig:
2443 * Reclaim allocated, contiguous physical memory satisfying the specified
2444 * conditions by relocating the virtual pages using that physical memory.
2445 * Returns true if reclamation is successful and false otherwise. Since
2446 * relocation requires the allocation of physical pages, reclamation may
2447 * fail due to a shortage of free pages. When reclamation fails, callers
2448 * are expected to perform VM_WAIT before retrying a failed allocation
2449 * operation, e.g., vm_page_alloc_contig().
2451 * The caller must always specify an allocation class through "req".
2453 * allocation classes:
2454 * VM_ALLOC_NORMAL normal process request
2455 * VM_ALLOC_SYSTEM system *really* needs a page
2456 * VM_ALLOC_INTERRUPT interrupt time request
2458 * The optional allocation flags are ignored.
2460 * "npages" must be greater than zero. Both "alignment" and "boundary"
2461 * must be a power of two.
2464 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2465 u_long alignment, vm_paddr_t boundary)
2467 vm_paddr_t curr_low;
2468 vm_page_t m_run, m_runs[NRUNS];
2469 u_long count, reclaimed;
2470 int error, i, options, req_class;
2472 KASSERT(npages > 0, ("npages is 0"));
2473 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2474 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2475 req_class = req & VM_ALLOC_CLASS_MASK;
2478 * The page daemon is allowed to dig deeper into the free page list.
2480 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2481 req_class = VM_ALLOC_SYSTEM;
2484 * Return if the number of free pages cannot satisfy the requested
2487 count = vm_cnt.v_free_count;
2488 if (count < npages + vm_cnt.v_free_reserved || (count < npages +
2489 vm_cnt.v_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2490 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2494 * Scan up to three times, relaxing the restrictions ("options") on
2495 * the reclamation of reservations and superpages each time.
2497 for (options = VPSC_NORESERV;;) {
2499 * Find the highest runs that satisfy the given constraints
2500 * and restrictions, and record them in "m_runs".
2505 m_run = vm_phys_scan_contig(npages, curr_low, high,
2506 alignment, boundary, options);
2509 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2510 m_runs[RUN_INDEX(count)] = m_run;
2515 * Reclaim the highest runs in LIFO (descending) order until
2516 * the number of reclaimed pages, "reclaimed", is at least
2517 * MIN_RECLAIM. Reset "reclaimed" each time because each
2518 * reclamation is idempotent, and runs will (likely) recur
2519 * from one scan to the next as restrictions are relaxed.
2522 for (i = 0; count > 0 && i < NRUNS; i++) {
2524 m_run = m_runs[RUN_INDEX(count)];
2525 error = vm_page_reclaim_run(req_class, npages, m_run,
2528 reclaimed += npages;
2529 if (reclaimed >= MIN_RECLAIM)
2535 * Either relax the restrictions on the next scan or return if
2536 * the last scan had no restrictions.
2538 if (options == VPSC_NORESERV)
2539 options = VPSC_NOSUPER;
2540 else if (options == VPSC_NOSUPER)
2542 else if (options == VPSC_ANY)
2543 return (reclaimed != 0);
2548 * vm_wait: (also see VM_WAIT macro)
2550 * Sleep until free pages are available for allocation.
2551 * - Called in various places before memory allocations.
2557 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2558 if (curproc == pageproc) {
2559 vm_pageout_pages_needed = 1;
2560 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
2561 PDROP | PSWP, "VMWait", 0);
2563 if (__predict_false(pageproc == NULL))
2564 panic("vm_wait in early boot");
2565 if (!vm_pageout_wanted) {
2566 vm_pageout_wanted = true;
2567 wakeup(&vm_pageout_wanted);
2569 vm_pages_needed = true;
2570 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
2579 mtx_lock(&vm_page_queue_free_mtx);
2584 * vm_page_alloc_fail:
2586 * Called when a page allocation function fails. Informs the
2587 * pagedaemon and performs the requested wait. Requires the
2588 * page_queue_free and object lock on entry. Returns with the
2589 * object lock held and free lock released. Returns an error when
2590 * retry is necessary.
2594 vm_page_alloc_fail(vm_object_t object, int req)
2597 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2599 atomic_add_int(&vm_pageout_deficit,
2600 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
2601 pagedaemon_wakeup();
2602 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
2604 VM_OBJECT_WUNLOCK(object);
2607 VM_OBJECT_WLOCK(object);
2608 if (req & VM_ALLOC_WAITOK)
2611 mtx_unlock(&vm_page_queue_free_mtx);
2616 * vm_waitpfault: (also see VM_WAITPFAULT macro)
2618 * Sleep until free pages are available for allocation.
2619 * - Called only in vm_fault so that processes page faulting
2620 * can be easily tracked.
2621 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2622 * processes will be able to grab memory first. Do not change
2623 * this balance without careful testing first.
2629 mtx_lock(&vm_page_queue_free_mtx);
2630 if (!vm_pageout_wanted) {
2631 vm_pageout_wanted = true;
2632 wakeup(&vm_pageout_wanted);
2634 vm_pages_needed = true;
2635 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
2639 struct vm_pagequeue *
2640 vm_page_pagequeue(vm_page_t m)
2643 if (vm_page_in_laundry(m))
2644 return (&vm_dom[0].vmd_pagequeues[m->queue]);
2646 return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2652 * Remove the given page from its current page queue.
2654 * The page must be locked.
2657 vm_page_dequeue(vm_page_t m)
2659 struct vm_pagequeue *pq;
2661 vm_page_assert_locked(m);
2662 KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
2664 pq = vm_page_pagequeue(m);
2665 vm_pagequeue_lock(pq);
2667 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2668 vm_pagequeue_cnt_dec(pq);
2669 vm_pagequeue_unlock(pq);
2673 * vm_page_dequeue_locked:
2675 * Remove the given page from its current page queue.
2677 * The page and page queue must be locked.
2680 vm_page_dequeue_locked(vm_page_t m)
2682 struct vm_pagequeue *pq;
2684 vm_page_lock_assert(m, MA_OWNED);
2685 pq = vm_page_pagequeue(m);
2686 vm_pagequeue_assert_locked(pq);
2688 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2689 vm_pagequeue_cnt_dec(pq);
2695 * Add the given page to the specified page queue.
2697 * The page must be locked.
2700 vm_page_enqueue(uint8_t queue, vm_page_t m)
2702 struct vm_pagequeue *pq;
2704 vm_page_lock_assert(m, MA_OWNED);
2705 KASSERT(queue < PQ_COUNT,
2706 ("vm_page_enqueue: invalid queue %u request for page %p",
2708 if (queue == PQ_LAUNDRY || queue == PQ_UNSWAPPABLE)
2709 pq = &vm_dom[0].vmd_pagequeues[queue];
2711 pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2712 vm_pagequeue_lock(pq);
2714 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2715 vm_pagequeue_cnt_inc(pq);
2716 vm_pagequeue_unlock(pq);
2722 * Move the given page to the tail of its current page queue.
2724 * The page must be locked.
2727 vm_page_requeue(vm_page_t m)
2729 struct vm_pagequeue *pq;
2731 vm_page_lock_assert(m, MA_OWNED);
2732 KASSERT(m->queue != PQ_NONE,
2733 ("vm_page_requeue: page %p is not queued", m));
2734 pq = vm_page_pagequeue(m);
2735 vm_pagequeue_lock(pq);
2736 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2737 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2738 vm_pagequeue_unlock(pq);
2742 * vm_page_requeue_locked:
2744 * Move the given page to the tail of its current page queue.
2746 * The page queue must be locked.
2749 vm_page_requeue_locked(vm_page_t m)
2751 struct vm_pagequeue *pq;
2753 KASSERT(m->queue != PQ_NONE,
2754 ("vm_page_requeue_locked: page %p is not queued", m));
2755 pq = vm_page_pagequeue(m);
2756 vm_pagequeue_assert_locked(pq);
2757 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2758 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2764 * Put the specified page on the active list (if appropriate).
2765 * Ensure that act_count is at least ACT_INIT but do not otherwise
2768 * The page must be locked.
2771 vm_page_activate(vm_page_t m)
2775 vm_page_lock_assert(m, MA_OWNED);
2776 if ((queue = m->queue) != PQ_ACTIVE) {
2777 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2778 if (m->act_count < ACT_INIT)
2779 m->act_count = ACT_INIT;
2780 if (queue != PQ_NONE)
2782 vm_page_enqueue(PQ_ACTIVE, m);
2784 KASSERT(queue == PQ_NONE,
2785 ("vm_page_activate: wired page %p is queued", m));
2787 if (m->act_count < ACT_INIT)
2788 m->act_count = ACT_INIT;
2793 * vm_page_free_wakeup:
2795 * Helper routine for vm_page_free_toq(). This routine is called
2796 * when a page is added to the free queues.
2798 * The page queues must be locked.
2801 vm_page_free_wakeup(void)
2804 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2806 * if pageout daemon needs pages, then tell it that there are
2809 if (vm_pageout_pages_needed &&
2810 vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
2811 wakeup(&vm_pageout_pages_needed);
2812 vm_pageout_pages_needed = 0;
2815 * wakeup processes that are waiting on memory if we hit a
2816 * high water mark. And wakeup scheduler process if we have
2817 * lots of memory. this process will swapin processes.
2819 if (vm_pages_needed && !vm_page_count_min()) {
2820 vm_pages_needed = false;
2821 wakeup(&vm_cnt.v_free_count);
2826 * vm_page_free_prep:
2828 * Prepares the given page to be put on the free list,
2829 * disassociating it from any VM object. The caller may return
2830 * the page to the free list only if this function returns true.
2832 * The object must be locked. The page must be locked if it is
2833 * managed. For a queued managed page, the pagequeue_locked
2834 * argument specifies whether the page queue is already locked.
2837 vm_page_free_prep(vm_page_t m, bool pagequeue_locked)
2840 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
2841 if ((m->flags & PG_ZERO) != 0) {
2844 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
2845 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
2846 KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
2847 m, i, (uintmax_t)*p));
2850 if ((m->oflags & VPO_UNMANAGED) == 0) {
2851 vm_page_lock_assert(m, MA_OWNED);
2852 KASSERT(!pmap_page_is_mapped(m),
2853 ("vm_page_free_toq: freeing mapped page %p", m));
2855 KASSERT(m->queue == PQ_NONE,
2856 ("vm_page_free_toq: unmanaged page %p is queued", m));
2857 VM_CNT_INC(v_tfree);
2859 if (vm_page_sbusied(m))
2860 panic("vm_page_free: freeing busy page %p", m);
2865 * If fictitious remove object association and
2868 if ((m->flags & PG_FICTITIOUS) != 0) {
2869 KASSERT(m->wire_count == 1,
2870 ("fictitious page %p is not wired", m));
2871 KASSERT(m->queue == PQ_NONE,
2872 ("fictitious page %p is queued", m));
2876 if (m->queue != PQ_NONE) {
2877 if (pagequeue_locked)
2878 vm_page_dequeue_locked(m);
2885 if (m->wire_count != 0)
2886 panic("vm_page_free: freeing wired page %p", m);
2887 if (m->hold_count != 0) {
2888 m->flags &= ~PG_ZERO;
2889 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2890 ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
2891 m->flags |= PG_UNHOLDFREE;
2896 * Restore the default memory attribute to the page.
2898 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2899 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2905 * Insert the page into the physical memory allocator's free page
2906 * queues. This is the last step to free a page.
2909 vm_page_free_phys(vm_page_t m)
2912 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2914 vm_phys_freecnt_adj(m, 1);
2915 #if VM_NRESERVLEVEL > 0
2916 if (!vm_reserv_free_page(m))
2918 vm_phys_free_pages(m, 0);
2922 vm_page_free_phys_pglist(struct pglist *tq)
2926 if (TAILQ_EMPTY(tq))
2928 mtx_lock(&vm_page_queue_free_mtx);
2929 TAILQ_FOREACH(m, tq, listq)
2930 vm_page_free_phys(m);
2931 vm_page_free_wakeup();
2932 mtx_unlock(&vm_page_queue_free_mtx);
2938 * Returns the given page to the free list, disassociating it
2939 * from any VM object.
2941 * The object must be locked. The page must be locked if it is
2945 vm_page_free_toq(vm_page_t m)
2948 if (!vm_page_free_prep(m, false))
2950 mtx_lock(&vm_page_queue_free_mtx);
2951 vm_page_free_phys(m);
2952 vm_page_free_wakeup();
2953 mtx_unlock(&vm_page_queue_free_mtx);
2959 * Mark this page as wired down by yet
2960 * another map, removing it from paging queues
2963 * If the page is fictitious, then its wire count must remain one.
2965 * The page must be locked.
2968 vm_page_wire(vm_page_t m)
2972 * Only bump the wire statistics if the page is not already wired,
2973 * and only unqueue the page if it is on some queue (if it is unmanaged
2974 * it is already off the queues).
2976 vm_page_lock_assert(m, MA_OWNED);
2977 if ((m->flags & PG_FICTITIOUS) != 0) {
2978 KASSERT(m->wire_count == 1,
2979 ("vm_page_wire: fictitious page %p's wire count isn't one",
2983 if (m->wire_count == 0) {
2984 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
2985 m->queue == PQ_NONE,
2986 ("vm_page_wire: unmanaged page %p is queued", m));
2988 atomic_add_int(&vm_cnt.v_wire_count, 1);
2991 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
2997 * Release one wiring of the specified page, potentially allowing it to be
2998 * paged out. Returns TRUE if the number of wirings transitions to zero and
3001 * Only managed pages belonging to an object can be paged out. If the number
3002 * of wirings transitions to zero and the page is eligible for page out, then
3003 * the page is added to the specified paging queue (unless PQ_NONE is
3006 * If a page is fictitious, then its wire count must always be one.
3008 * A managed page must be locked.
3011 vm_page_unwire(vm_page_t m, uint8_t queue)
3014 KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
3015 ("vm_page_unwire: invalid queue %u request for page %p",
3017 if ((m->oflags & VPO_UNMANAGED) == 0)
3018 vm_page_assert_locked(m);
3019 if ((m->flags & PG_FICTITIOUS) != 0) {
3020 KASSERT(m->wire_count == 1,
3021 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
3024 if (m->wire_count > 0) {
3026 if (m->wire_count == 0) {
3027 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3028 if ((m->oflags & VPO_UNMANAGED) == 0 &&
3029 m->object != NULL && queue != PQ_NONE)
3030 vm_page_enqueue(queue, m);
3035 panic("vm_page_unwire: page %p's wire count is zero", m);
3039 * Move the specified page to the inactive queue.
3041 * Normally, "noreuse" is FALSE, resulting in LRU ordering of the inactive
3042 * queue. However, setting "noreuse" to TRUE will accelerate the specified
3043 * page's reclamation, but it will not unmap the page from any address space.
3044 * This is implemented by inserting the page near the head of the inactive
3045 * queue, using a marker page to guide FIFO insertion ordering.
3047 * The page must be locked.
3050 _vm_page_deactivate(vm_page_t m, boolean_t noreuse)
3052 struct vm_pagequeue *pq;
3055 vm_page_assert_locked(m);
3058 * Ignore if the page is already inactive, unless it is unlikely to be
3061 if ((queue = m->queue) == PQ_INACTIVE && !noreuse)
3063 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
3064 pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
3065 /* Avoid multiple acquisitions of the inactive queue lock. */
3066 if (queue == PQ_INACTIVE) {
3067 vm_pagequeue_lock(pq);
3068 vm_page_dequeue_locked(m);
3070 if (queue != PQ_NONE)
3072 vm_pagequeue_lock(pq);
3074 m->queue = PQ_INACTIVE;
3076 TAILQ_INSERT_BEFORE(&vm_phys_domain(m)->vmd_inacthead,
3079 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3080 vm_pagequeue_cnt_inc(pq);
3081 vm_pagequeue_unlock(pq);
3086 * Move the specified page to the inactive queue.
3088 * The page must be locked.
3091 vm_page_deactivate(vm_page_t m)
3094 _vm_page_deactivate(m, FALSE);
3098 * Move the specified page to the inactive queue with the expectation
3099 * that it is unlikely to be reused.
3101 * The page must be locked.
3104 vm_page_deactivate_noreuse(vm_page_t m)
3107 _vm_page_deactivate(m, TRUE);
3113 * Put a page in the laundry.
3116 vm_page_launder(vm_page_t m)
3120 vm_page_assert_locked(m);
3121 if ((queue = m->queue) != PQ_LAUNDRY) {
3122 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
3123 if (queue != PQ_NONE)
3125 vm_page_enqueue(PQ_LAUNDRY, m);
3127 KASSERT(queue == PQ_NONE,
3128 ("wired page %p is queued", m));
3133 * vm_page_unswappable
3135 * Put a page in the PQ_UNSWAPPABLE holding queue.
3138 vm_page_unswappable(vm_page_t m)
3141 vm_page_assert_locked(m);
3142 KASSERT(m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0,
3143 ("page %p already unswappable", m));
3144 if (m->queue != PQ_NONE)
3146 vm_page_enqueue(PQ_UNSWAPPABLE, m);
3150 * Attempt to free the page. If it cannot be freed, do nothing. Returns true
3151 * if the page is freed and false otherwise.
3153 * The page must be managed. The page and its containing object must be
3157 vm_page_try_to_free(vm_page_t m)
3160 vm_page_assert_locked(m);
3161 VM_OBJECT_ASSERT_WLOCKED(m->object);
3162 KASSERT((m->oflags & VPO_UNMANAGED) == 0, ("page %p is unmanaged", m));
3163 if (m->dirty != 0 || m->hold_count != 0 || m->wire_count != 0 ||
3166 if (m->object->ref_count != 0) {
3178 * Apply the specified advice to the given page.
3180 * The object and page must be locked.
3183 vm_page_advise(vm_page_t m, int advice)
3186 vm_page_assert_locked(m);
3187 VM_OBJECT_ASSERT_WLOCKED(m->object);
3188 if (advice == MADV_FREE)
3190 * Mark the page clean. This will allow the page to be freed
3191 * without first paging it out. MADV_FREE pages are often
3192 * quickly reused by malloc(3), so we do not do anything that
3193 * would result in a page fault on a later access.
3196 else if (advice != MADV_DONTNEED) {
3197 if (advice == MADV_WILLNEED)
3198 vm_page_activate(m);
3203 * Clear any references to the page. Otherwise, the page daemon will
3204 * immediately reactivate the page.
3206 vm_page_aflag_clear(m, PGA_REFERENCED);
3208 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3212 * Place clean pages near the head of the inactive queue rather than
3213 * the tail, thus defeating the queue's LRU operation and ensuring that
3214 * the page will be reused quickly. Dirty pages not already in the
3215 * laundry are moved there.
3218 vm_page_deactivate_noreuse(m);
3224 * Grab a page, waiting until we are waken up due to the page
3225 * changing state. We keep on waiting, if the page continues
3226 * to be in the object. If the page doesn't exist, first allocate it
3227 * and then conditionally zero it.
3229 * This routine may sleep.
3231 * The object must be locked on entry. The lock will, however, be released
3232 * and reacquired if the routine sleeps.
3235 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3241 VM_OBJECT_ASSERT_WLOCKED(object);
3242 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3243 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3244 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3245 pflags = allocflags &
3246 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
3247 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3248 pflags |= VM_ALLOC_WAITFAIL;
3250 if ((m = vm_page_lookup(object, pindex)) != NULL) {
3251 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3252 vm_page_xbusied(m) : vm_page_busied(m);
3254 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3257 * Reference the page before unlocking and
3258 * sleeping so that the page daemon is less
3259 * likely to reclaim it.
3261 vm_page_aflag_set(m, PGA_REFERENCED);
3263 VM_OBJECT_WUNLOCK(object);
3264 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
3265 VM_ALLOC_IGN_SBUSY) != 0);
3266 VM_OBJECT_WLOCK(object);
3269 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3275 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3277 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3282 m = vm_page_alloc(object, pindex, pflags);
3284 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3288 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3294 * Return the specified range of pages from the given object. For each
3295 * page offset within the range, if a page already exists within the object
3296 * at that offset and it is busy, then wait for it to change state. If,
3297 * instead, the page doesn't exist, then allocate it.
3299 * The caller must always specify an allocation class.
3301 * allocation classes:
3302 * VM_ALLOC_NORMAL normal process request
3303 * VM_ALLOC_SYSTEM system *really* needs the pages
3305 * The caller must always specify that the pages are to be busied and/or
3308 * optional allocation flags:
3309 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
3310 * VM_ALLOC_NOBUSY do not exclusive busy the page
3311 * VM_ALLOC_NOWAIT do not sleep
3312 * VM_ALLOC_SBUSY set page to sbusy state
3313 * VM_ALLOC_WIRED wire the pages
3314 * VM_ALLOC_ZERO zero and validate any invalid pages
3316 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
3317 * may return a partial prefix of the requested range.
3320 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
3321 vm_page_t *ma, int count)
3328 VM_OBJECT_ASSERT_WLOCKED(object);
3329 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
3330 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
3331 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
3332 (allocflags & VM_ALLOC_WIRED) != 0,
3333 ("vm_page_grab_pages: the pages must be busied or wired"));
3334 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3335 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3336 ("vm_page_grab_pages: VM_ALLOC_SBUSY/IGN_SBUSY mismatch"));
3339 pflags = allocflags & ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK |
3340 VM_ALLOC_WAITFAIL | VM_ALLOC_IGN_SBUSY);
3341 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3342 pflags |= VM_ALLOC_WAITFAIL;
3345 m = vm_radix_lookup_le(&object->rtree, pindex + i);
3346 if (m == NULL || m->pindex != pindex + i) {
3350 mpred = TAILQ_PREV(m, pglist, listq);
3351 for (; i < count; i++) {
3353 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3354 vm_page_xbusied(m) : vm_page_busied(m);
3356 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3359 * Reference the page before unlocking and
3360 * sleeping so that the page daemon is less
3361 * likely to reclaim it.
3363 vm_page_aflag_set(m, PGA_REFERENCED);
3365 VM_OBJECT_WUNLOCK(object);
3366 vm_page_busy_sleep(m, "grbmaw", (allocflags &
3367 VM_ALLOC_IGN_SBUSY) != 0);
3368 VM_OBJECT_WLOCK(object);
3371 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3376 if ((allocflags & (VM_ALLOC_NOBUSY |
3377 VM_ALLOC_SBUSY)) == 0)
3379 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3382 m = vm_page_alloc_after(object, pindex + i,
3383 pflags | VM_ALLOC_COUNT(count - i), mpred);
3385 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3390 if (m->valid == 0 && (allocflags & VM_ALLOC_ZERO) != 0) {
3391 if ((m->flags & PG_ZERO) == 0)
3393 m->valid = VM_PAGE_BITS_ALL;
3396 m = vm_page_next(m);
3402 * Mapping function for valid or dirty bits in a page.
3404 * Inputs are required to range within a page.
3407 vm_page_bits(int base, int size)
3413 base + size <= PAGE_SIZE,
3414 ("vm_page_bits: illegal base/size %d/%d", base, size)
3417 if (size == 0) /* handle degenerate case */
3420 first_bit = base >> DEV_BSHIFT;
3421 last_bit = (base + size - 1) >> DEV_BSHIFT;
3423 return (((vm_page_bits_t)2 << last_bit) -
3424 ((vm_page_bits_t)1 << first_bit));
3428 * vm_page_set_valid_range:
3430 * Sets portions of a page valid. The arguments are expected
3431 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3432 * of any partial chunks touched by the range. The invalid portion of
3433 * such chunks will be zeroed.
3435 * (base + size) must be less then or equal to PAGE_SIZE.
3438 vm_page_set_valid_range(vm_page_t m, int base, int size)
3442 VM_OBJECT_ASSERT_WLOCKED(m->object);
3443 if (size == 0) /* handle degenerate case */
3447 * If the base is not DEV_BSIZE aligned and the valid
3448 * bit is clear, we have to zero out a portion of the
3451 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3452 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
3453 pmap_zero_page_area(m, frag, base - frag);
3456 * If the ending offset is not DEV_BSIZE aligned and the
3457 * valid bit is clear, we have to zero out a portion of
3460 endoff = base + size;
3461 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3462 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
3463 pmap_zero_page_area(m, endoff,
3464 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3467 * Assert that no previously invalid block that is now being validated
3470 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
3471 ("vm_page_set_valid_range: page %p is dirty", m));
3474 * Set valid bits inclusive of any overlap.
3476 m->valid |= vm_page_bits(base, size);
3480 * Clear the given bits from the specified page's dirty field.
3482 static __inline void
3483 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
3486 #if PAGE_SIZE < 16384
3491 * If the object is locked and the page is neither exclusive busy nor
3492 * write mapped, then the page's dirty field cannot possibly be
3493 * set by a concurrent pmap operation.
3495 VM_OBJECT_ASSERT_WLOCKED(m->object);
3496 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
3497 m->dirty &= ~pagebits;
3500 * The pmap layer can call vm_page_dirty() without
3501 * holding a distinguished lock. The combination of
3502 * the object's lock and an atomic operation suffice
3503 * to guarantee consistency of the page dirty field.
3505 * For PAGE_SIZE == 32768 case, compiler already
3506 * properly aligns the dirty field, so no forcible
3507 * alignment is needed. Only require existence of
3508 * atomic_clear_64 when page size is 32768.
3510 addr = (uintptr_t)&m->dirty;
3511 #if PAGE_SIZE == 32768
3512 atomic_clear_64((uint64_t *)addr, pagebits);
3513 #elif PAGE_SIZE == 16384
3514 atomic_clear_32((uint32_t *)addr, pagebits);
3515 #else /* PAGE_SIZE <= 8192 */
3517 * Use a trick to perform a 32-bit atomic on the
3518 * containing aligned word, to not depend on the existence
3519 * of atomic_clear_{8, 16}.
3521 shift = addr & (sizeof(uint32_t) - 1);
3522 #if BYTE_ORDER == BIG_ENDIAN
3523 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
3527 addr &= ~(sizeof(uint32_t) - 1);
3528 atomic_clear_32((uint32_t *)addr, pagebits << shift);
3529 #endif /* PAGE_SIZE */
3534 * vm_page_set_validclean:
3536 * Sets portions of a page valid and clean. The arguments are expected
3537 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3538 * of any partial chunks touched by the range. The invalid portion of
3539 * such chunks will be zero'd.
3541 * (base + size) must be less then or equal to PAGE_SIZE.
3544 vm_page_set_validclean(vm_page_t m, int base, int size)
3546 vm_page_bits_t oldvalid, pagebits;
3549 VM_OBJECT_ASSERT_WLOCKED(m->object);
3550 if (size == 0) /* handle degenerate case */
3554 * If the base is not DEV_BSIZE aligned and the valid
3555 * bit is clear, we have to zero out a portion of the
3558 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3559 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
3560 pmap_zero_page_area(m, frag, base - frag);
3563 * If the ending offset is not DEV_BSIZE aligned and the
3564 * valid bit is clear, we have to zero out a portion of
3567 endoff = base + size;
3568 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3569 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
3570 pmap_zero_page_area(m, endoff,
3571 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3574 * Set valid, clear dirty bits. If validating the entire
3575 * page we can safely clear the pmap modify bit. We also
3576 * use this opportunity to clear the VPO_NOSYNC flag. If a process
3577 * takes a write fault on a MAP_NOSYNC memory area the flag will
3580 * We set valid bits inclusive of any overlap, but we can only
3581 * clear dirty bits for DEV_BSIZE chunks that are fully within
3584 oldvalid = m->valid;
3585 pagebits = vm_page_bits(base, size);
3586 m->valid |= pagebits;
3588 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
3589 frag = DEV_BSIZE - frag;
3595 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
3597 if (base == 0 && size == PAGE_SIZE) {
3599 * The page can only be modified within the pmap if it is
3600 * mapped, and it can only be mapped if it was previously
3603 if (oldvalid == VM_PAGE_BITS_ALL)
3605 * Perform the pmap_clear_modify() first. Otherwise,
3606 * a concurrent pmap operation, such as
3607 * pmap_protect(), could clear a modification in the
3608 * pmap and set the dirty field on the page before
3609 * pmap_clear_modify() had begun and after the dirty
3610 * field was cleared here.
3612 pmap_clear_modify(m);
3614 m->oflags &= ~VPO_NOSYNC;
3615 } else if (oldvalid != VM_PAGE_BITS_ALL)
3616 m->dirty &= ~pagebits;
3618 vm_page_clear_dirty_mask(m, pagebits);
3622 vm_page_clear_dirty(vm_page_t m, int base, int size)
3625 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
3629 * vm_page_set_invalid:
3631 * Invalidates DEV_BSIZE'd chunks within a page. Both the
3632 * valid and dirty bits for the effected areas are cleared.
3635 vm_page_set_invalid(vm_page_t m, int base, int size)
3637 vm_page_bits_t bits;
3641 VM_OBJECT_ASSERT_WLOCKED(object);
3642 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
3643 size >= object->un_pager.vnp.vnp_size)
3644 bits = VM_PAGE_BITS_ALL;
3646 bits = vm_page_bits(base, size);
3647 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
3650 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3651 !pmap_page_is_mapped(m),
3652 ("vm_page_set_invalid: page %p is mapped", m));
3658 * vm_page_zero_invalid()
3660 * The kernel assumes that the invalid portions of a page contain
3661 * garbage, but such pages can be mapped into memory by user code.
3662 * When this occurs, we must zero out the non-valid portions of the
3663 * page so user code sees what it expects.
3665 * Pages are most often semi-valid when the end of a file is mapped
3666 * into memory and the file's size is not page aligned.
3669 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3674 VM_OBJECT_ASSERT_WLOCKED(m->object);
3676 * Scan the valid bits looking for invalid sections that
3677 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
3678 * valid bit may be set ) have already been zeroed by
3679 * vm_page_set_validclean().
3681 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3682 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3683 (m->valid & ((vm_page_bits_t)1 << i))) {
3685 pmap_zero_page_area(m,
3686 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3693 * setvalid is TRUE when we can safely set the zero'd areas
3694 * as being valid. We can do this if there are no cache consistancy
3695 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3698 m->valid = VM_PAGE_BITS_ALL;
3704 * Is (partial) page valid? Note that the case where size == 0
3705 * will return FALSE in the degenerate case where the page is
3706 * entirely invalid, and TRUE otherwise.
3709 vm_page_is_valid(vm_page_t m, int base, int size)
3711 vm_page_bits_t bits;
3713 VM_OBJECT_ASSERT_LOCKED(m->object);
3714 bits = vm_page_bits(base, size);
3715 return (m->valid != 0 && (m->valid & bits) == bits);
3719 * Returns true if all of the specified predicates are true for the entire
3720 * (super)page and false otherwise.
3723 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
3729 VM_OBJECT_ASSERT_LOCKED(object);
3730 npages = atop(pagesizes[m->psind]);
3733 * The physically contiguous pages that make up a superpage, i.e., a
3734 * page with a page size index ("psind") greater than zero, will
3735 * occupy adjacent entries in vm_page_array[].
3737 for (i = 0; i < npages; i++) {
3738 /* Always test object consistency, including "skip_m". */
3739 if (m[i].object != object)
3741 if (&m[i] == skip_m)
3743 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
3745 if ((flags & PS_ALL_DIRTY) != 0) {
3747 * Calling vm_page_test_dirty() or pmap_is_modified()
3748 * might stop this case from spuriously returning
3749 * "false". However, that would require a write lock
3750 * on the object containing "m[i]".
3752 if (m[i].dirty != VM_PAGE_BITS_ALL)
3755 if ((flags & PS_ALL_VALID) != 0 &&
3756 m[i].valid != VM_PAGE_BITS_ALL)
3763 * Set the page's dirty bits if the page is modified.
3766 vm_page_test_dirty(vm_page_t m)
3769 VM_OBJECT_ASSERT_WLOCKED(m->object);
3770 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3775 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3778 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3782 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3785 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3789 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3792 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3795 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3797 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3800 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3804 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3807 mtx_assert_(vm_page_lockptr(m), a, file, line);
3813 vm_page_object_lock_assert(vm_page_t m)
3817 * Certain of the page's fields may only be modified by the
3818 * holder of the containing object's lock or the exclusive busy.
3819 * holder. Unfortunately, the holder of the write busy is
3820 * not recorded, and thus cannot be checked here.
3822 if (m->object != NULL && !vm_page_xbusied(m))
3823 VM_OBJECT_ASSERT_WLOCKED(m->object);
3827 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3830 if ((bits & PGA_WRITEABLE) == 0)
3834 * The PGA_WRITEABLE flag can only be set if the page is
3835 * managed, is exclusively busied or the object is locked.
3836 * Currently, this flag is only set by pmap_enter().
3838 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3839 ("PGA_WRITEABLE on unmanaged page"));
3840 if (!vm_page_xbusied(m))
3841 VM_OBJECT_ASSERT_LOCKED(m->object);
3845 #include "opt_ddb.h"
3847 #include <sys/kernel.h>
3849 #include <ddb/ddb.h>
3851 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3854 db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
3855 db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
3856 db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
3857 db_printf("vm_cnt.v_laundry_count: %d\n", vm_cnt.v_laundry_count);
3858 db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
3859 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
3860 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
3861 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
3862 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
3865 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3869 db_printf("pq_free %d\n", vm_cnt.v_free_count);
3870 for (dom = 0; dom < vm_ndomains; dom++) {
3872 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
3874 vm_dom[dom].vmd_page_count,
3875 vm_dom[dom].vmd_free_count,
3876 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3877 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
3878 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
3879 vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
3883 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3889 db_printf("show pginfo addr\n");
3893 phys = strchr(modif, 'p') != NULL;
3895 m = PHYS_TO_VM_PAGE(addr);
3897 m = (vm_page_t)addr;
3899 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3900 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3901 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3902 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3903 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);