2 * Copyright (c) 1991 Regents of the University of California.
4 * Copyright (c) 1998 Matthew Dillon. All Rights Reserved.
6 * This code is derived from software contributed to Berkeley by
7 * The Mach Operating System project at Carnegie-Mellon University.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * from: @(#)vm_page.c 7.4 (Berkeley) 5/7/91
37 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38 * All rights reserved.
40 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
42 * Permission to use, copy, modify and distribute this software and
43 * its documentation is hereby granted, provided that both the copyright
44 * notice and this permission notice appear in all copies of the
45 * software, derivative works or modified versions, and any portions
46 * thereof, and that both notices appear in supporting documentation.
48 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
52 * Carnegie Mellon requests users of this software to return to
54 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
55 * School of Computer Science
56 * Carnegie Mellon University
57 * Pittsburgh PA 15213-3890
59 * any improvements or extensions that they make and grant Carnegie the
60 * rights to redistribute these changes.
64 * GENERAL RULES ON VM_PAGE MANIPULATION
66 * - A page queue lock is required when adding or removing a page from a
67 * page queue regardless of other locks or the busy state of a page.
69 * * In general, no thread besides the page daemon can acquire or
70 * hold more than one page queue lock at a time.
72 * * The page daemon can acquire and hold any pair of page queue
75 * - The object lock is required when inserting or removing
76 * pages from an object (vm_page_insert() or vm_page_remove()).
81 * Resident memory management module.
84 #include <sys/cdefs.h>
85 __FBSDID("$FreeBSD$");
89 #include <sys/param.h>
90 #include <sys/systm.h>
92 #include <sys/kernel.h>
93 #include <sys/limits.h>
94 #include <sys/linker.h>
95 #include <sys/malloc.h>
97 #include <sys/msgbuf.h>
98 #include <sys/mutex.h>
100 #include <sys/rwlock.h>
101 #include <sys/sbuf.h>
103 #include <sys/sysctl.h>
104 #include <sys/vmmeter.h>
105 #include <sys/vnode.h>
109 #include <vm/vm_param.h>
110 #include <vm/vm_kern.h>
111 #include <vm/vm_object.h>
112 #include <vm/vm_page.h>
113 #include <vm/vm_pageout.h>
114 #include <vm/vm_pager.h>
115 #include <vm/vm_phys.h>
116 #include <vm/vm_radix.h>
117 #include <vm/vm_reserv.h>
118 #include <vm/vm_extern.h>
120 #include <vm/uma_int.h>
122 #include <machine/md_var.h>
125 * Associated with page of user-allocatable memory is a
129 struct vm_domain vm_dom[MAXMEMDOM];
130 struct mtx_padalign vm_page_queue_free_mtx;
132 struct mtx_padalign pa_lock[PA_LOCK_COUNT];
134 vm_page_t vm_page_array;
135 long vm_page_array_size;
137 int vm_page_zero_count;
139 static int boot_pages = UMA_BOOT_PAGES;
140 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
142 "number of pages allocated for bootstrapping the VM system");
144 static int pa_tryrelock_restart;
145 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
146 &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
148 static TAILQ_HEAD(, vm_page) blacklist_head;
149 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
150 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
151 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
153 /* Is the page daemon waiting for free pages? */
154 static int vm_pageout_pages_needed;
156 static uma_zone_t fakepg_zone;
158 static void vm_page_alloc_check(vm_page_t m);
159 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
160 static void vm_page_enqueue(uint8_t queue, vm_page_t m);
161 static void vm_page_free_phys(vm_page_t m);
162 static void vm_page_free_wakeup(void);
163 static void vm_page_init_fakepg(void *dummy);
164 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
165 vm_pindex_t pindex, vm_page_t mpred);
166 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
168 static int vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
171 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init_fakepg, NULL);
174 vm_page_init_fakepg(void *dummy)
177 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
178 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
181 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
182 #if PAGE_SIZE == 32768
184 CTASSERT(sizeof(u_long) >= 8);
189 * Try to acquire a physical address lock while a pmap is locked. If we
190 * fail to trylock we unlock and lock the pmap directly and cache the
191 * locked pa in *locked. The caller should then restart their loop in case
192 * the virtual to physical mapping has changed.
195 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
202 PA_LOCK_ASSERT(lockpa, MA_OWNED);
203 if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
210 atomic_add_int(&pa_tryrelock_restart, 1);
219 * Sets the page size, perhaps based upon the memory
220 * size. Must be called before any use of page-size
221 * dependent functions.
224 vm_set_page_size(void)
226 if (vm_cnt.v_page_size == 0)
227 vm_cnt.v_page_size = PAGE_SIZE;
228 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
229 panic("vm_set_page_size: page size not a power of two");
233 * vm_page_blacklist_next:
235 * Find the next entry in the provided string of blacklist
236 * addresses. Entries are separated by space, comma, or newline.
237 * If an invalid integer is encountered then the rest of the
238 * string is skipped. Updates the list pointer to the next
239 * character, or NULL if the string is exhausted or invalid.
242 vm_page_blacklist_next(char **list, char *end)
247 if (list == NULL || *list == NULL)
255 * If there's no end pointer then the buffer is coming from
256 * the kenv and we know it's null-terminated.
259 end = *list + strlen(*list);
261 /* Ensure that strtoq() won't walk off the end */
263 if (*end == '\n' || *end == ' ' || *end == ',')
266 printf("Blacklist not terminated, skipping\n");
272 for (pos = *list; *pos != '\0'; pos = cp) {
273 bad = strtoq(pos, &cp, 0);
274 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
283 if (*cp == '\0' || ++cp >= end)
287 return (trunc_page(bad));
289 printf("Garbage in RAM blacklist, skipping\n");
295 * vm_page_blacklist_check:
297 * Iterate through the provided string of blacklist addresses, pulling
298 * each entry out of the physical allocator free list and putting it
299 * onto a list for reporting via the vm.page_blacklist sysctl.
302 vm_page_blacklist_check(char *list, char *end)
310 while (next != NULL) {
311 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
313 m = vm_phys_paddr_to_vm_page(pa);
316 mtx_lock(&vm_page_queue_free_mtx);
317 ret = vm_phys_unfree_page(m);
318 mtx_unlock(&vm_page_queue_free_mtx);
320 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
322 printf("Skipping page with pa 0x%jx\n",
329 * vm_page_blacklist_load:
331 * Search for a special module named "ram_blacklist". It'll be a
332 * plain text file provided by the user via the loader directive
336 vm_page_blacklist_load(char **list, char **end)
345 mod = preload_search_by_type("ram_blacklist");
347 ptr = preload_fetch_addr(mod);
348 len = preload_fetch_size(mod);
359 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
366 error = sysctl_wire_old_buffer(req, 0);
369 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
370 TAILQ_FOREACH(m, &blacklist_head, listq) {
371 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
372 (uintmax_t)m->phys_addr);
375 error = sbuf_finish(&sbuf);
381 vm_page_domain_init(struct vm_domain *vmd)
383 struct vm_pagequeue *pq;
386 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
387 "vm inactive pagequeue";
388 *__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_vcnt) =
389 &vm_cnt.v_inactive_count;
390 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
391 "vm active pagequeue";
392 *__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_vcnt) =
393 &vm_cnt.v_active_count;
394 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
395 "vm laundry pagequeue";
396 *__DECONST(int **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_vcnt) =
397 &vm_cnt.v_laundry_count;
398 vmd->vmd_page_count = 0;
399 vmd->vmd_free_count = 0;
401 vmd->vmd_oom = FALSE;
402 for (i = 0; i < PQ_COUNT; i++) {
403 pq = &vmd->vmd_pagequeues[i];
404 TAILQ_INIT(&pq->pq_pl);
405 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
406 MTX_DEF | MTX_DUPOK);
413 * Initializes the resident memory module. Allocates physical memory for
414 * bootstrapping UMA and some data structures that are used to manage
415 * physical pages. Initializes these structures, and populates the free
419 vm_page_startup(vm_offset_t vaddr)
422 vm_paddr_t high_avail, low_avail, page_range, size;
427 char *list, *listend;
429 vm_paddr_t biggestsize;
435 vaddr = round_page(vaddr);
437 for (i = 0; phys_avail[i + 1]; i += 2) {
438 phys_avail[i] = round_page(phys_avail[i]);
439 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
441 for (i = 0; phys_avail[i + 1]; i += 2) {
442 size = phys_avail[i + 1] - phys_avail[i];
443 if (size > biggestsize) {
449 end = phys_avail[biggestone+1];
452 * Initialize the page and queue locks.
454 mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
455 for (i = 0; i < PA_LOCK_COUNT; i++)
456 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
457 for (i = 0; i < vm_ndomains; i++)
458 vm_page_domain_init(&vm_dom[i]);
461 * Almost all of the pages needed for bootstrapping UMA are used
462 * for zone structures, so if the number of CPUs results in those
463 * structures taking more than one page each, we set aside more pages
464 * in proportion to the zone structure size.
466 pages_per_zone = howmany(sizeof(struct uma_zone) +
467 sizeof(struct uma_cache) * (mp_maxid + 1), UMA_SLAB_SIZE);
468 if (pages_per_zone > 1) {
469 /* Reserve more pages so that we don't run out. */
470 boot_pages = UMA_BOOT_PAGES_ZONES * pages_per_zone;
474 * Allocate memory for use when boot strapping the kernel memory
477 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
478 * manually fetch the value.
480 TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
481 new_end = end - (boot_pages * UMA_SLAB_SIZE);
482 new_end = trunc_page(new_end);
483 mapped = pmap_map(&vaddr, new_end, end,
484 VM_PROT_READ | VM_PROT_WRITE);
485 bzero((void *)mapped, end - new_end);
486 uma_startup((void *)mapped, boot_pages);
488 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
489 defined(__i386__) || defined(__mips__)
491 * Allocate a bitmap to indicate that a random physical page
492 * needs to be included in a minidump.
494 * The amd64 port needs this to indicate which direct map pages
495 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
497 * However, i386 still needs this workspace internally within the
498 * minidump code. In theory, they are not needed on i386, but are
499 * included should the sf_buf code decide to use them.
502 for (i = 0; dump_avail[i + 1] != 0; i += 2)
503 if (dump_avail[i + 1] > last_pa)
504 last_pa = dump_avail[i + 1];
505 page_range = last_pa / PAGE_SIZE;
506 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
507 new_end -= vm_page_dump_size;
508 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
509 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
510 bzero((void *)vm_page_dump, vm_page_dump_size);
512 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
514 * Include the UMA bootstrap pages and vm_page_dump in a crash dump.
515 * When pmap_map() uses the direct map, they are not automatically
518 for (pa = new_end; pa < end; pa += PAGE_SIZE)
521 phys_avail[biggestone + 1] = new_end;
524 * Request that the physical pages underlying the message buffer be
525 * included in a crash dump. Since the message buffer is accessed
526 * through the direct map, they are not automatically included.
528 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
529 last_pa = pa + round_page(msgbufsize);
530 while (pa < last_pa) {
536 * Compute the number of pages of memory that will be available for
537 * use, taking into account the overhead of a page structure per page.
538 * In other words, solve
539 * "available physical memory" - round_page(page_range *
540 * sizeof(struct vm_page)) = page_range * PAGE_SIZE
543 low_avail = phys_avail[0];
544 high_avail = phys_avail[1];
545 for (i = 0; i < vm_phys_nsegs; i++) {
546 if (vm_phys_segs[i].start < low_avail)
547 low_avail = vm_phys_segs[i].start;
548 if (vm_phys_segs[i].end > high_avail)
549 high_avail = vm_phys_segs[i].end;
551 /* Skip the first chunk. It is already accounted for. */
552 for (i = 2; phys_avail[i + 1] != 0; i += 2) {
553 if (phys_avail[i] < low_avail)
554 low_avail = phys_avail[i];
555 if (phys_avail[i + 1] > high_avail)
556 high_avail = phys_avail[i + 1];
558 first_page = low_avail / PAGE_SIZE;
559 #ifdef VM_PHYSSEG_SPARSE
561 for (i = 0; i < vm_phys_nsegs; i++)
562 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
563 for (i = 0; phys_avail[i + 1] != 0; i += 2)
564 size += phys_avail[i + 1] - phys_avail[i];
565 #elif defined(VM_PHYSSEG_DENSE)
566 size = high_avail - low_avail;
568 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
571 #ifdef VM_PHYSSEG_DENSE
573 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
574 * the overhead of a page structure per page only if vm_page_array is
575 * allocated from the last physical memory chunk. Otherwise, we must
576 * allocate page structures representing the physical memory
577 * underlying vm_page_array, even though they will not be used.
579 if (new_end != high_avail)
580 page_range = size / PAGE_SIZE;
584 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
587 * If the partial bytes remaining are large enough for
588 * a page (PAGE_SIZE) without a corresponding
589 * 'struct vm_page', then new_end will contain an
590 * extra page after subtracting the length of the VM
591 * page array. Compensate by subtracting an extra
594 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
595 if (new_end == high_avail)
596 high_avail -= PAGE_SIZE;
597 new_end -= PAGE_SIZE;
603 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
604 * However, because this page is allocated from KVM, out-of-bounds
605 * accesses using the direct map will not be trapped.
610 * Allocate physical memory for the page structures, and map it.
612 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
613 mapped = pmap_map(&vaddr, new_end, end,
614 VM_PROT_READ | VM_PROT_WRITE);
615 vm_page_array = (vm_page_t) mapped;
616 #if VM_NRESERVLEVEL > 0
618 * Allocate physical memory for the reservation management system's
619 * data structures, and map it.
621 if (high_avail == end)
622 high_avail = new_end;
623 new_end = vm_reserv_startup(&vaddr, new_end, high_avail);
625 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
627 * Include vm_page_array and vm_reserv_array in a crash dump.
629 for (pa = new_end; pa < end; pa += PAGE_SIZE)
632 phys_avail[biggestone + 1] = new_end;
635 * Add physical memory segments corresponding to the available
638 for (i = 0; phys_avail[i + 1] != 0; i += 2)
639 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
642 * Clear all of the page structures
644 bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
645 for (i = 0; i < page_range; i++)
646 vm_page_array[i].order = VM_NFREEORDER;
647 vm_page_array_size = page_range;
650 * Initialize the physical memory allocator.
655 * Add every available physical page that is not blacklisted to
658 vm_cnt.v_page_count = 0;
659 vm_cnt.v_free_count = 0;
660 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
662 last_pa = phys_avail[i + 1];
663 while (pa < last_pa) {
664 vm_phys_add_page(pa);
669 TAILQ_INIT(&blacklist_head);
670 vm_page_blacklist_load(&list, &listend);
671 vm_page_blacklist_check(list, listend);
673 list = kern_getenv("vm.blacklist");
674 vm_page_blacklist_check(list, NULL);
677 #if VM_NRESERVLEVEL > 0
679 * Initialize the reservation management system.
687 vm_page_reference(vm_page_t m)
690 vm_page_aflag_set(m, PGA_REFERENCED);
694 * vm_page_busy_downgrade:
696 * Downgrade an exclusive busy page into a single shared busy page.
699 vm_page_busy_downgrade(vm_page_t m)
704 vm_page_assert_xbusied(m);
705 locked = mtx_owned(vm_page_lockptr(m));
709 x &= VPB_BIT_WAITERS;
710 if (x != 0 && !locked)
712 if (atomic_cmpset_rel_int(&m->busy_lock,
713 VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1)))
715 if (x != 0 && !locked)
728 * Return a positive value if the page is shared busied, 0 otherwise.
731 vm_page_sbusied(vm_page_t m)
736 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
742 * Shared unbusy a page.
745 vm_page_sunbusy(vm_page_t m)
749 vm_page_lock_assert(m, MA_NOTOWNED);
750 vm_page_assert_sbusied(m);
754 if (VPB_SHARERS(x) > 1) {
755 if (atomic_cmpset_int(&m->busy_lock, x,
760 if ((x & VPB_BIT_WAITERS) == 0) {
761 KASSERT(x == VPB_SHARERS_WORD(1),
762 ("vm_page_sunbusy: invalid lock state"));
763 if (atomic_cmpset_int(&m->busy_lock,
764 VPB_SHARERS_WORD(1), VPB_UNBUSIED))
768 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
769 ("vm_page_sunbusy: invalid lock state for waiters"));
772 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
783 * vm_page_busy_sleep:
785 * Sleep and release the page lock, using the page pointer as wchan.
786 * This is used to implement the hard-path of busying mechanism.
788 * The given page must be locked.
790 * If nonshared is true, sleep only if the page is xbusy.
793 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
797 vm_page_assert_locked(m);
800 if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
801 ((x & VPB_BIT_WAITERS) == 0 &&
802 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
806 msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
812 * Try to shared busy a page.
813 * If the operation succeeds 1 is returned otherwise 0.
814 * The operation never sleeps.
817 vm_page_trysbusy(vm_page_t m)
823 if ((x & VPB_BIT_SHARED) == 0)
825 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
831 vm_page_xunbusy_locked(vm_page_t m)
834 vm_page_assert_xbusied(m);
835 vm_page_assert_locked(m);
837 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
838 /* There is a waiter, do wakeup() instead of vm_page_flash(). */
843 vm_page_xunbusy_maybelocked(vm_page_t m)
847 vm_page_assert_xbusied(m);
850 * Fast path for unbusy. If it succeeds, we know that there
851 * are no waiters, so we do not need a wakeup.
853 if (atomic_cmpset_rel_int(&m->busy_lock, VPB_SINGLE_EXCLUSIVER,
857 lockacq = !mtx_owned(vm_page_lockptr(m));
860 vm_page_xunbusy_locked(m);
866 * vm_page_xunbusy_hard:
868 * Called after the first try the exclusive unbusy of a page failed.
869 * It is assumed that the waiters bit is on.
872 vm_page_xunbusy_hard(vm_page_t m)
875 vm_page_assert_xbusied(m);
878 vm_page_xunbusy_locked(m);
885 * Wakeup anyone waiting for the page.
886 * The ownership bits do not change.
888 * The given page must be locked.
891 vm_page_flash(vm_page_t m)
895 vm_page_lock_assert(m, MA_OWNED);
899 if ((x & VPB_BIT_WAITERS) == 0)
901 if (atomic_cmpset_int(&m->busy_lock, x,
902 x & (~VPB_BIT_WAITERS)))
909 * Avoid releasing and reacquiring the same page lock.
912 vm_page_change_lock(vm_page_t m, struct mtx **mtx)
916 mtx1 = vm_page_lockptr(m);
926 * Keep page from being freed by the page daemon
927 * much of the same effect as wiring, except much lower
928 * overhead and should be used only for *very* temporary
929 * holding ("wiring").
932 vm_page_hold(vm_page_t mem)
935 vm_page_lock_assert(mem, MA_OWNED);
940 vm_page_unhold(vm_page_t mem)
943 vm_page_lock_assert(mem, MA_OWNED);
944 KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
946 if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
947 vm_page_free_toq(mem);
951 * vm_page_unhold_pages:
953 * Unhold each of the pages that is referenced by the given array.
956 vm_page_unhold_pages(vm_page_t *ma, int count)
961 for (; count != 0; count--) {
962 vm_page_change_lock(*ma, &mtx);
971 PHYS_TO_VM_PAGE(vm_paddr_t pa)
975 #ifdef VM_PHYSSEG_SPARSE
976 m = vm_phys_paddr_to_vm_page(pa);
978 m = vm_phys_fictitious_to_vm_page(pa);
980 #elif defined(VM_PHYSSEG_DENSE)
984 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
985 m = &vm_page_array[pi - first_page];
988 return (vm_phys_fictitious_to_vm_page(pa));
990 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
997 * Create a fictitious page with the specified physical address and
998 * memory attribute. The memory attribute is the only the machine-
999 * dependent aspect of a fictitious page that must be initialized.
1002 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1006 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1007 vm_page_initfake(m, paddr, memattr);
1012 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1015 if ((m->flags & PG_FICTITIOUS) != 0) {
1017 * The page's memattr might have changed since the
1018 * previous initialization. Update the pmap to the
1023 m->phys_addr = paddr;
1025 /* Fictitious pages don't use "segind". */
1026 m->flags = PG_FICTITIOUS;
1027 /* Fictitious pages don't use "order" or "pool". */
1028 m->oflags = VPO_UNMANAGED;
1029 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1033 pmap_page_set_memattr(m, memattr);
1039 * Release a fictitious page.
1042 vm_page_putfake(vm_page_t m)
1045 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1046 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1047 ("vm_page_putfake: bad page %p", m));
1048 uma_zfree(fakepg_zone, m);
1052 * vm_page_updatefake:
1054 * Update the given fictitious page to the specified physical address and
1058 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1061 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1062 ("vm_page_updatefake: bad page %p", m));
1063 m->phys_addr = paddr;
1064 pmap_page_set_memattr(m, memattr);
1073 vm_page_free(vm_page_t m)
1076 m->flags &= ~PG_ZERO;
1077 vm_page_free_toq(m);
1081 * vm_page_free_zero:
1083 * Free a page to the zerod-pages queue
1086 vm_page_free_zero(vm_page_t m)
1089 m->flags |= PG_ZERO;
1090 vm_page_free_toq(m);
1094 * Unbusy and handle the page queueing for a page from a getpages request that
1095 * was optionally read ahead or behind.
1098 vm_page_readahead_finish(vm_page_t m)
1101 /* We shouldn't put invalid pages on queues. */
1102 KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
1105 * Since the page is not the actually needed one, whether it should
1106 * be activated or deactivated is not obvious. Empirical results
1107 * have shown that deactivating the page is usually the best choice,
1108 * unless the page is wanted by another thread.
1111 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1112 vm_page_activate(m);
1114 vm_page_deactivate(m);
1120 * vm_page_sleep_if_busy:
1122 * Sleep and release the page queues lock if the page is busied.
1123 * Returns TRUE if the thread slept.
1125 * The given page must be unlocked and object containing it must
1129 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1133 vm_page_lock_assert(m, MA_NOTOWNED);
1134 VM_OBJECT_ASSERT_WLOCKED(m->object);
1136 if (vm_page_busied(m)) {
1138 * The page-specific object must be cached because page
1139 * identity can change during the sleep, causing the
1140 * re-lock of a different object.
1141 * It is assumed that a reference to the object is already
1142 * held by the callers.
1146 VM_OBJECT_WUNLOCK(obj);
1147 vm_page_busy_sleep(m, msg, false);
1148 VM_OBJECT_WLOCK(obj);
1155 * vm_page_dirty_KBI: [ internal use only ]
1157 * Set all bits in the page's dirty field.
1159 * The object containing the specified page must be locked if the
1160 * call is made from the machine-independent layer.
1162 * See vm_page_clear_dirty_mask().
1164 * This function should only be called by vm_page_dirty().
1167 vm_page_dirty_KBI(vm_page_t m)
1170 /* Refer to this operation by its public name. */
1171 KASSERT(m->valid == VM_PAGE_BITS_ALL,
1172 ("vm_page_dirty: page is invalid!"));
1173 m->dirty = VM_PAGE_BITS_ALL;
1177 * vm_page_insert: [ internal use only ]
1179 * Inserts the given mem entry into the object and object list.
1181 * The object must be locked.
1184 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1188 VM_OBJECT_ASSERT_WLOCKED(object);
1189 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1190 return (vm_page_insert_after(m, object, pindex, mpred));
1194 * vm_page_insert_after:
1196 * Inserts the page "m" into the specified object at offset "pindex".
1198 * The page "mpred" must immediately precede the offset "pindex" within
1199 * the specified object.
1201 * The object must be locked.
1204 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1209 VM_OBJECT_ASSERT_WLOCKED(object);
1210 KASSERT(m->object == NULL,
1211 ("vm_page_insert_after: page already inserted"));
1212 if (mpred != NULL) {
1213 KASSERT(mpred->object == object,
1214 ("vm_page_insert_after: object doesn't contain mpred"));
1215 KASSERT(mpred->pindex < pindex,
1216 ("vm_page_insert_after: mpred doesn't precede pindex"));
1217 msucc = TAILQ_NEXT(mpred, listq);
1219 msucc = TAILQ_FIRST(&object->memq);
1221 KASSERT(msucc->pindex > pindex,
1222 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1225 * Record the object/offset pair in this page
1231 * Now link into the object's ordered list of backed pages.
1233 if (vm_radix_insert(&object->rtree, m)) {
1238 vm_page_insert_radixdone(m, object, mpred);
1243 * vm_page_insert_radixdone:
1245 * Complete page "m" insertion into the specified object after the
1246 * radix trie hooking.
1248 * The page "mpred" must precede the offset "m->pindex" within the
1251 * The object must be locked.
1254 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1257 VM_OBJECT_ASSERT_WLOCKED(object);
1258 KASSERT(object != NULL && m->object == object,
1259 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1260 if (mpred != NULL) {
1261 KASSERT(mpred->object == object,
1262 ("vm_page_insert_after: object doesn't contain mpred"));
1263 KASSERT(mpred->pindex < m->pindex,
1264 ("vm_page_insert_after: mpred doesn't precede pindex"));
1268 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1270 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1273 * Show that the object has one more resident page.
1275 object->resident_page_count++;
1278 * Hold the vnode until the last page is released.
1280 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1281 vhold(object->handle);
1284 * Since we are inserting a new and possibly dirty page,
1285 * update the object's OBJ_MIGHTBEDIRTY flag.
1287 if (pmap_page_is_write_mapped(m))
1288 vm_object_set_writeable_dirty(object);
1294 * Removes the specified page from its containing object, but does not
1295 * invalidate any backing storage.
1297 * The object must be locked. The page must be locked if it is managed.
1300 vm_page_remove(vm_page_t m)
1305 if ((m->oflags & VPO_UNMANAGED) == 0)
1306 vm_page_assert_locked(m);
1307 if ((object = m->object) == NULL)
1309 VM_OBJECT_ASSERT_WLOCKED(object);
1310 if (vm_page_xbusied(m))
1311 vm_page_xunbusy_maybelocked(m);
1312 mrem = vm_radix_remove(&object->rtree, m->pindex);
1313 KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1316 * Now remove from the object's list of backed pages.
1318 TAILQ_REMOVE(&object->memq, m, listq);
1321 * And show that the object has one fewer resident page.
1323 object->resident_page_count--;
1326 * The vnode may now be recycled.
1328 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1329 vdrop(object->handle);
1337 * Returns the page associated with the object/offset
1338 * pair specified; if none is found, NULL is returned.
1340 * The object must be locked.
1343 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1346 VM_OBJECT_ASSERT_LOCKED(object);
1347 return (vm_radix_lookup(&object->rtree, pindex));
1351 * vm_page_find_least:
1353 * Returns the page associated with the object with least pindex
1354 * greater than or equal to the parameter pindex, or NULL.
1356 * The object must be locked.
1359 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1363 VM_OBJECT_ASSERT_LOCKED(object);
1364 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1365 m = vm_radix_lookup_ge(&object->rtree, pindex);
1370 * Returns the given page's successor (by pindex) within the object if it is
1371 * resident; if none is found, NULL is returned.
1373 * The object must be locked.
1376 vm_page_next(vm_page_t m)
1380 VM_OBJECT_ASSERT_LOCKED(m->object);
1381 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1382 MPASS(next->object == m->object);
1383 if (next->pindex != m->pindex + 1)
1390 * Returns the given page's predecessor (by pindex) within the object if it is
1391 * resident; if none is found, NULL is returned.
1393 * The object must be locked.
1396 vm_page_prev(vm_page_t m)
1400 VM_OBJECT_ASSERT_LOCKED(m->object);
1401 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1402 MPASS(prev->object == m->object);
1403 if (prev->pindex != m->pindex - 1)
1410 * Uses the page mnew as a replacement for an existing page at index
1411 * pindex which must be already present in the object.
1413 * The existing page must not be on a paging queue.
1416 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1420 VM_OBJECT_ASSERT_WLOCKED(object);
1421 KASSERT(mnew->object == NULL,
1422 ("vm_page_replace: page already in object"));
1425 * This function mostly follows vm_page_insert() and
1426 * vm_page_remove() without the radix, object count and vnode
1427 * dance. Double check such functions for more comments.
1430 mnew->object = object;
1431 mnew->pindex = pindex;
1432 mold = vm_radix_replace(&object->rtree, mnew);
1433 KASSERT(mold->queue == PQ_NONE,
1434 ("vm_page_replace: mold is on a paging queue"));
1436 /* Keep the resident page list in sorted order. */
1437 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1438 TAILQ_REMOVE(&object->memq, mold, listq);
1440 mold->object = NULL;
1441 vm_page_xunbusy_maybelocked(mold);
1444 * The object's resident_page_count does not change because we have
1445 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1447 if (pmap_page_is_write_mapped(mnew))
1448 vm_object_set_writeable_dirty(object);
1455 * Move the given memory entry from its
1456 * current object to the specified target object/offset.
1458 * Note: swap associated with the page must be invalidated by the move. We
1459 * have to do this for several reasons: (1) we aren't freeing the
1460 * page, (2) we are dirtying the page, (3) the VM system is probably
1461 * moving the page from object A to B, and will then later move
1462 * the backing store from A to B and we can't have a conflict.
1464 * Note: we *always* dirty the page. It is necessary both for the
1465 * fact that we moved it, and because we may be invalidating
1468 * The objects must be locked.
1471 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1476 VM_OBJECT_ASSERT_WLOCKED(new_object);
1478 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1479 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1480 ("vm_page_rename: pindex already renamed"));
1483 * Create a custom version of vm_page_insert() which does not depend
1484 * by m_prev and can cheat on the implementation aspects of the
1488 m->pindex = new_pindex;
1489 if (vm_radix_insert(&new_object->rtree, m)) {
1495 * The operation cannot fail anymore. The removal must happen before
1496 * the listq iterator is tainted.
1502 /* Return back to the new pindex to complete vm_page_insert(). */
1503 m->pindex = new_pindex;
1504 m->object = new_object;
1506 vm_page_insert_radixdone(m, new_object, mpred);
1514 * Allocate and return a page that is associated with the specified
1515 * object and offset pair. By default, this page is exclusive busied.
1517 * The caller must always specify an allocation class.
1519 * allocation classes:
1520 * VM_ALLOC_NORMAL normal process request
1521 * VM_ALLOC_SYSTEM system *really* needs a page
1522 * VM_ALLOC_INTERRUPT interrupt time request
1524 * optional allocation flags:
1525 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1526 * intends to allocate
1527 * VM_ALLOC_NOBUSY do not exclusive busy the page
1528 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1529 * VM_ALLOC_NOOBJ page is not associated with an object and
1530 * should not be exclusive busy
1531 * VM_ALLOC_SBUSY shared busy the allocated page
1532 * VM_ALLOC_WIRED wire the allocated page
1533 * VM_ALLOC_ZERO prefer a zeroed page
1535 * This routine may not sleep.
1538 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1541 int flags, req_class;
1543 mpred = NULL; /* XXX: pacify gcc */
1544 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1545 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1546 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1547 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1548 ("vm_page_alloc: inconsistent object(%p)/req(%x)", object, req));
1550 VM_OBJECT_ASSERT_WLOCKED(object);
1552 if (__predict_false((req & VM_ALLOC_IFCACHED) != 0))
1555 req_class = req & VM_ALLOC_CLASS_MASK;
1558 * The page daemon is allowed to dig deeper into the free page list.
1560 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1561 req_class = VM_ALLOC_SYSTEM;
1563 if (object != NULL) {
1564 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1565 KASSERT(mpred == NULL || mpred->pindex != pindex,
1566 ("vm_page_alloc: pindex already allocated"));
1570 * Allocate a page if the number of free pages exceeds the minimum
1571 * for the request class.
1573 mtx_lock(&vm_page_queue_free_mtx);
1574 if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
1575 (req_class == VM_ALLOC_SYSTEM &&
1576 vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
1577 (req_class == VM_ALLOC_INTERRUPT &&
1578 vm_cnt.v_free_count > 0)) {
1580 * Can we allocate the page from a reservation?
1582 #if VM_NRESERVLEVEL > 0
1583 if (object == NULL || (object->flags & (OBJ_COLORED |
1584 OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1585 vm_reserv_alloc_page(object, pindex, mpred)) == NULL)
1589 * If not, allocate it from the free page queues.
1591 m = vm_phys_alloc_pages(object != NULL ?
1592 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1593 #if VM_NRESERVLEVEL > 0
1594 if (m == NULL && vm_reserv_reclaim_inactive()) {
1595 m = vm_phys_alloc_pages(object != NULL ?
1596 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1603 * Not allocatable, give up.
1605 mtx_unlock(&vm_page_queue_free_mtx);
1606 atomic_add_int(&vm_pageout_deficit,
1607 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1608 pagedaemon_wakeup();
1613 * At this point we had better have found a good page.
1615 KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1616 vm_phys_freecnt_adj(m, -1);
1617 if ((m->flags & PG_ZERO) != 0)
1618 vm_page_zero_count--;
1619 mtx_unlock(&vm_page_queue_free_mtx);
1620 vm_page_alloc_check(m);
1623 * Initialize the page. Only the PG_ZERO flag is inherited.
1626 if ((req & VM_ALLOC_ZERO) != 0)
1629 if ((req & VM_ALLOC_NODUMP) != 0)
1633 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1635 m->busy_lock = VPB_UNBUSIED;
1636 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1637 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1638 if ((req & VM_ALLOC_SBUSY) != 0)
1639 m->busy_lock = VPB_SHARERS_WORD(1);
1640 if (req & VM_ALLOC_WIRED) {
1642 * The page lock is not required for wiring a page until that
1643 * page is inserted into the object.
1645 atomic_add_int(&vm_cnt.v_wire_count, 1);
1650 if (object != NULL) {
1651 if (vm_page_insert_after(m, object, pindex, mpred)) {
1652 pagedaemon_wakeup();
1653 if (req & VM_ALLOC_WIRED) {
1654 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1657 KASSERT(m->object == NULL, ("page %p has object", m));
1658 m->oflags = VPO_UNMANAGED;
1659 m->busy_lock = VPB_UNBUSIED;
1660 /* Don't change PG_ZERO. */
1661 vm_page_free_toq(m);
1665 /* Ignore device objects; the pager sets "memattr" for them. */
1666 if (object->memattr != VM_MEMATTR_DEFAULT &&
1667 (object->flags & OBJ_FICTITIOUS) == 0)
1668 pmap_page_set_memattr(m, object->memattr);
1673 * Don't wakeup too often - wakeup the pageout daemon when
1674 * we would be nearly out of memory.
1676 if (vm_paging_needed())
1677 pagedaemon_wakeup();
1683 * vm_page_alloc_contig:
1685 * Allocate a contiguous set of physical pages of the given size "npages"
1686 * from the free lists. All of the physical pages must be at or above
1687 * the given physical address "low" and below the given physical address
1688 * "high". The given value "alignment" determines the alignment of the
1689 * first physical page in the set. If the given value "boundary" is
1690 * non-zero, then the set of physical pages cannot cross any physical
1691 * address boundary that is a multiple of that value. Both "alignment"
1692 * and "boundary" must be a power of two.
1694 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1695 * then the memory attribute setting for the physical pages is configured
1696 * to the object's memory attribute setting. Otherwise, the memory
1697 * attribute setting for the physical pages is configured to "memattr",
1698 * overriding the object's memory attribute setting. However, if the
1699 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1700 * memory attribute setting for the physical pages cannot be configured
1701 * to VM_MEMATTR_DEFAULT.
1703 * The specified object may not contain fictitious pages.
1705 * The caller must always specify an allocation class.
1707 * allocation classes:
1708 * VM_ALLOC_NORMAL normal process request
1709 * VM_ALLOC_SYSTEM system *really* needs a page
1710 * VM_ALLOC_INTERRUPT interrupt time request
1712 * optional allocation flags:
1713 * VM_ALLOC_NOBUSY do not exclusive busy the page
1714 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1715 * VM_ALLOC_NOOBJ page is not associated with an object and
1716 * should not be exclusive busy
1717 * VM_ALLOC_SBUSY shared busy the allocated page
1718 * VM_ALLOC_WIRED wire the allocated page
1719 * VM_ALLOC_ZERO prefer a zeroed page
1721 * This routine may not sleep.
1724 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1725 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1726 vm_paddr_t boundary, vm_memattr_t memattr)
1728 vm_page_t m, m_ret, mpred;
1729 u_int busy_lock, flags, oflags;
1732 mpred = NULL; /* XXX: pacify gcc */
1733 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1734 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1735 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1736 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1737 ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
1739 if (object != NULL) {
1740 VM_OBJECT_ASSERT_WLOCKED(object);
1741 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
1742 ("vm_page_alloc_contig: object %p has fictitious pages",
1745 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1746 req_class = req & VM_ALLOC_CLASS_MASK;
1749 * The page daemon is allowed to dig deeper into the free page list.
1751 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1752 req_class = VM_ALLOC_SYSTEM;
1754 if (object != NULL) {
1755 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1756 KASSERT(mpred == NULL || mpred->pindex != pindex,
1757 ("vm_page_alloc_contig: pindex already allocated"));
1761 * Can we allocate the pages without the number of free pages falling
1762 * below the lower bound for the allocation class?
1764 mtx_lock(&vm_page_queue_free_mtx);
1765 if (vm_cnt.v_free_count >= npages + vm_cnt.v_free_reserved ||
1766 (req_class == VM_ALLOC_SYSTEM &&
1767 vm_cnt.v_free_count >= npages + vm_cnt.v_interrupt_free_min) ||
1768 (req_class == VM_ALLOC_INTERRUPT &&
1769 vm_cnt.v_free_count >= npages)) {
1771 * Can we allocate the pages from a reservation?
1773 #if VM_NRESERVLEVEL > 0
1775 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1776 (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1777 low, high, alignment, boundary, mpred)) == NULL)
1780 * If not, allocate them from the free page queues.
1782 m_ret = vm_phys_alloc_contig(npages, low, high,
1783 alignment, boundary);
1785 mtx_unlock(&vm_page_queue_free_mtx);
1786 atomic_add_int(&vm_pageout_deficit, npages);
1787 pagedaemon_wakeup();
1790 if (m_ret != NULL) {
1791 vm_phys_freecnt_adj(m_ret, -npages);
1792 for (m = m_ret; m < &m_ret[npages]; m++)
1793 if ((m->flags & PG_ZERO) != 0)
1794 vm_page_zero_count--;
1796 #if VM_NRESERVLEVEL > 0
1797 if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1802 mtx_unlock(&vm_page_queue_free_mtx);
1805 for (m = m_ret; m < &m_ret[npages]; m++)
1806 vm_page_alloc_check(m);
1809 * Initialize the pages. Only the PG_ZERO flag is inherited.
1812 if ((req & VM_ALLOC_ZERO) != 0)
1814 if ((req & VM_ALLOC_NODUMP) != 0)
1816 oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1818 busy_lock = VPB_UNBUSIED;
1819 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1820 busy_lock = VPB_SINGLE_EXCLUSIVER;
1821 if ((req & VM_ALLOC_SBUSY) != 0)
1822 busy_lock = VPB_SHARERS_WORD(1);
1823 if ((req & VM_ALLOC_WIRED) != 0)
1824 atomic_add_int(&vm_cnt.v_wire_count, npages);
1825 if (object != NULL) {
1826 if (object->memattr != VM_MEMATTR_DEFAULT &&
1827 memattr == VM_MEMATTR_DEFAULT)
1828 memattr = object->memattr;
1830 for (m = m_ret; m < &m_ret[npages]; m++) {
1832 m->flags = (m->flags | PG_NODUMP) & flags;
1833 m->busy_lock = busy_lock;
1834 if ((req & VM_ALLOC_WIRED) != 0)
1838 if (object != NULL) {
1839 if (vm_page_insert_after(m, object, pindex, mpred)) {
1840 pagedaemon_wakeup();
1841 if ((req & VM_ALLOC_WIRED) != 0)
1842 atomic_subtract_int(
1843 &vm_cnt.v_wire_count, npages);
1844 KASSERT(m->object == NULL,
1845 ("page %p has object", m));
1847 for (m = m_ret; m < &m_ret[npages]; m++) {
1849 (req & VM_ALLOC_WIRED) != 0)
1851 m->oflags = VPO_UNMANAGED;
1852 m->busy_lock = VPB_UNBUSIED;
1853 /* Don't change PG_ZERO. */
1854 vm_page_free_toq(m);
1861 if (memattr != VM_MEMATTR_DEFAULT)
1862 pmap_page_set_memattr(m, memattr);
1865 if (vm_paging_needed())
1866 pagedaemon_wakeup();
1871 * Check a page that has been freshly dequeued from a freelist.
1874 vm_page_alloc_check(vm_page_t m)
1877 KASSERT(m->object == NULL, ("page %p has object", m));
1878 KASSERT(m->queue == PQ_NONE,
1879 ("page %p has unexpected queue %d", m, m->queue));
1880 KASSERT(m->wire_count == 0, ("page %p is wired", m));
1881 KASSERT(m->hold_count == 0, ("page %p is held", m));
1882 KASSERT(!vm_page_busied(m), ("page %p is busy", m));
1883 KASSERT(m->dirty == 0, ("page %p is dirty", m));
1884 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1885 ("page %p has unexpected memattr %d",
1886 m, pmap_page_get_memattr(m)));
1887 KASSERT(m->valid == 0, ("free page %p is valid", m));
1891 * vm_page_alloc_freelist:
1893 * Allocate a physical page from the specified free page list.
1895 * The caller must always specify an allocation class.
1897 * allocation classes:
1898 * VM_ALLOC_NORMAL normal process request
1899 * VM_ALLOC_SYSTEM system *really* needs a page
1900 * VM_ALLOC_INTERRUPT interrupt time request
1902 * optional allocation flags:
1903 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1904 * intends to allocate
1905 * VM_ALLOC_WIRED wire the allocated page
1906 * VM_ALLOC_ZERO prefer a zeroed page
1908 * This routine may not sleep.
1911 vm_page_alloc_freelist(int flind, int req)
1917 req_class = req & VM_ALLOC_CLASS_MASK;
1920 * The page daemon is allowed to dig deeper into the free page list.
1922 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1923 req_class = VM_ALLOC_SYSTEM;
1926 * Do not allocate reserved pages unless the req has asked for it.
1928 mtx_lock(&vm_page_queue_free_mtx);
1929 if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
1930 (req_class == VM_ALLOC_SYSTEM &&
1931 vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
1932 (req_class == VM_ALLOC_INTERRUPT &&
1933 vm_cnt.v_free_count > 0))
1934 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
1936 mtx_unlock(&vm_page_queue_free_mtx);
1937 atomic_add_int(&vm_pageout_deficit,
1938 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1939 pagedaemon_wakeup();
1943 mtx_unlock(&vm_page_queue_free_mtx);
1946 vm_phys_freecnt_adj(m, -1);
1947 if ((m->flags & PG_ZERO) != 0)
1948 vm_page_zero_count--;
1949 mtx_unlock(&vm_page_queue_free_mtx);
1950 vm_page_alloc_check(m);
1953 * Initialize the page. Only the PG_ZERO flag is inherited.
1957 if ((req & VM_ALLOC_ZERO) != 0)
1960 if ((req & VM_ALLOC_WIRED) != 0) {
1962 * The page lock is not required for wiring a page that does
1963 * not belong to an object.
1965 atomic_add_int(&vm_cnt.v_wire_count, 1);
1968 /* Unmanaged pages don't use "act_count". */
1969 m->oflags = VPO_UNMANAGED;
1970 if (vm_paging_needed())
1971 pagedaemon_wakeup();
1975 #define VPSC_ANY 0 /* No restrictions. */
1976 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
1977 #define VPSC_NOSUPER 2 /* Skip superpages. */
1980 * vm_page_scan_contig:
1982 * Scan vm_page_array[] between the specified entries "m_start" and
1983 * "m_end" for a run of contiguous physical pages that satisfy the
1984 * specified conditions, and return the lowest page in the run. The
1985 * specified "alignment" determines the alignment of the lowest physical
1986 * page in the run. If the specified "boundary" is non-zero, then the
1987 * run of physical pages cannot span a physical address that is a
1988 * multiple of "boundary".
1990 * "m_end" is never dereferenced, so it need not point to a vm_page
1991 * structure within vm_page_array[].
1993 * "npages" must be greater than zero. "m_start" and "m_end" must not
1994 * span a hole (or discontiguity) in the physical address space. Both
1995 * "alignment" and "boundary" must be a power of two.
1998 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
1999 u_long alignment, vm_paddr_t boundary, int options)
2005 #if VM_NRESERVLEVEL > 0
2008 int m_inc, order, run_ext, run_len;
2010 KASSERT(npages > 0, ("npages is 0"));
2011 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2012 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2016 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2017 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2018 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2021 * If the current page would be the start of a run, check its
2022 * physical address against the end, alignment, and boundary
2023 * conditions. If it doesn't satisfy these conditions, either
2024 * terminate the scan or advance to the next page that
2025 * satisfies the failed condition.
2028 KASSERT(m_run == NULL, ("m_run != NULL"));
2029 if (m + npages > m_end)
2031 pa = VM_PAGE_TO_PHYS(m);
2032 if ((pa & (alignment - 1)) != 0) {
2033 m_inc = atop(roundup2(pa, alignment) - pa);
2036 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2038 m_inc = atop(roundup2(pa, boundary) - pa);
2042 KASSERT(m_run != NULL, ("m_run == NULL"));
2044 vm_page_change_lock(m, &m_mtx);
2047 if (m->wire_count != 0 || m->hold_count != 0)
2049 #if VM_NRESERVLEVEL > 0
2050 else if ((level = vm_reserv_level(m)) >= 0 &&
2051 (options & VPSC_NORESERV) != 0) {
2053 /* Advance to the end of the reservation. */
2054 pa = VM_PAGE_TO_PHYS(m);
2055 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2059 else if ((object = m->object) != NULL) {
2061 * The page is considered eligible for relocation if
2062 * and only if it could be laundered or reclaimed by
2065 if (!VM_OBJECT_TRYRLOCK(object)) {
2067 VM_OBJECT_RLOCK(object);
2069 if (m->object != object) {
2071 * The page may have been freed.
2073 VM_OBJECT_RUNLOCK(object);
2075 } else if (m->wire_count != 0 ||
2076 m->hold_count != 0) {
2081 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2082 ("page %p is PG_UNHOLDFREE", m));
2083 /* Don't care: PG_NODUMP, PG_ZERO. */
2084 if (object->type != OBJT_DEFAULT &&
2085 object->type != OBJT_SWAP &&
2086 object->type != OBJT_VNODE) {
2088 #if VM_NRESERVLEVEL > 0
2089 } else if ((options & VPSC_NOSUPER) != 0 &&
2090 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2092 /* Advance to the end of the superpage. */
2093 pa = VM_PAGE_TO_PHYS(m);
2094 m_inc = atop(roundup2(pa + 1,
2095 vm_reserv_size(level)) - pa);
2097 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2098 m->queue != PQ_NONE && !vm_page_busied(m)) {
2100 * The page is allocated but eligible for
2101 * relocation. Extend the current run by one
2104 KASSERT(pmap_page_get_memattr(m) ==
2106 ("page %p has an unexpected memattr", m));
2107 KASSERT((m->oflags & (VPO_SWAPINPROG |
2108 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2109 ("page %p has unexpected oflags", m));
2110 /* Don't care: VPO_NOSYNC. */
2115 VM_OBJECT_RUNLOCK(object);
2116 #if VM_NRESERVLEVEL > 0
2117 } else if (level >= 0) {
2119 * The page is reserved but not yet allocated. In
2120 * other words, it is still free. Extend the current
2125 } else if ((order = m->order) < VM_NFREEORDER) {
2127 * The page is enqueued in the physical memory
2128 * allocator's free page queues. Moreover, it is the
2129 * first page in a power-of-two-sized run of
2130 * contiguous free pages. Add these pages to the end
2131 * of the current run, and jump ahead.
2133 run_ext = 1 << order;
2137 * Skip the page for one of the following reasons: (1)
2138 * It is enqueued in the physical memory allocator's
2139 * free page queues. However, it is not the first
2140 * page in a run of contiguous free pages. (This case
2141 * rarely occurs because the scan is performed in
2142 * ascending order.) (2) It is not reserved, and it is
2143 * transitioning from free to allocated. (Conversely,
2144 * the transition from allocated to free for managed
2145 * pages is blocked by the page lock.) (3) It is
2146 * allocated but not contained by an object and not
2147 * wired, e.g., allocated by Xen's balloon driver.
2153 * Extend or reset the current run of pages.
2168 if (run_len >= npages)
2174 * vm_page_reclaim_run:
2176 * Try to relocate each of the allocated virtual pages within the
2177 * specified run of physical pages to a new physical address. Free the
2178 * physical pages underlying the relocated virtual pages. A virtual page
2179 * is relocatable if and only if it could be laundered or reclaimed by
2180 * the page daemon. Whenever possible, a virtual page is relocated to a
2181 * physical address above "high".
2183 * Returns 0 if every physical page within the run was already free or
2184 * just freed by a successful relocation. Otherwise, returns a non-zero
2185 * value indicating why the last attempt to relocate a virtual page was
2188 * "req_class" must be an allocation class.
2191 vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
2195 struct spglist free;
2198 vm_page_t m, m_end, m_new;
2199 int error, order, req;
2201 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2202 ("req_class is not an allocation class"));
2206 m_end = m_run + npages;
2208 for (; error == 0 && m < m_end; m++) {
2209 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2210 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2213 * Avoid releasing and reacquiring the same page lock.
2215 vm_page_change_lock(m, &m_mtx);
2217 if (m->wire_count != 0 || m->hold_count != 0)
2219 else if ((object = m->object) != NULL) {
2221 * The page is relocated if and only if it could be
2222 * laundered or reclaimed by the page daemon.
2224 if (!VM_OBJECT_TRYWLOCK(object)) {
2226 VM_OBJECT_WLOCK(object);
2228 if (m->object != object) {
2230 * The page may have been freed.
2232 VM_OBJECT_WUNLOCK(object);
2234 } else if (m->wire_count != 0 ||
2235 m->hold_count != 0) {
2240 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2241 ("page %p is PG_UNHOLDFREE", m));
2242 /* Don't care: PG_NODUMP, PG_ZERO. */
2243 if (object->type != OBJT_DEFAULT &&
2244 object->type != OBJT_SWAP &&
2245 object->type != OBJT_VNODE)
2247 else if (object->memattr != VM_MEMATTR_DEFAULT)
2249 else if (m->queue != PQ_NONE && !vm_page_busied(m)) {
2250 KASSERT(pmap_page_get_memattr(m) ==
2252 ("page %p has an unexpected memattr", m));
2253 KASSERT((m->oflags & (VPO_SWAPINPROG |
2254 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2255 ("page %p has unexpected oflags", m));
2256 /* Don't care: VPO_NOSYNC. */
2257 if (m->valid != 0) {
2259 * First, try to allocate a new page
2260 * that is above "high". Failing
2261 * that, try to allocate a new page
2262 * that is below "m_run". Allocate
2263 * the new page between the end of
2264 * "m_run" and "high" only as a last
2267 req = req_class | VM_ALLOC_NOOBJ;
2268 if ((m->flags & PG_NODUMP) != 0)
2269 req |= VM_ALLOC_NODUMP;
2270 if (trunc_page(high) !=
2271 ~(vm_paddr_t)PAGE_MASK) {
2272 m_new = vm_page_alloc_contig(
2277 VM_MEMATTR_DEFAULT);
2280 if (m_new == NULL) {
2281 pa = VM_PAGE_TO_PHYS(m_run);
2282 m_new = vm_page_alloc_contig(
2284 0, pa - 1, PAGE_SIZE, 0,
2285 VM_MEMATTR_DEFAULT);
2287 if (m_new == NULL) {
2289 m_new = vm_page_alloc_contig(
2291 pa, high, PAGE_SIZE, 0,
2292 VM_MEMATTR_DEFAULT);
2294 if (m_new == NULL) {
2298 KASSERT(m_new->wire_count == 0,
2299 ("page %p is wired", m));
2302 * Replace "m" with the new page. For
2303 * vm_page_replace(), "m" must be busy
2304 * and dequeued. Finally, change "m"
2305 * as if vm_page_free() was called.
2307 if (object->ref_count != 0)
2309 m_new->aflags = m->aflags;
2310 KASSERT(m_new->oflags == VPO_UNMANAGED,
2311 ("page %p is managed", m));
2312 m_new->oflags = m->oflags & VPO_NOSYNC;
2313 pmap_copy_page(m, m_new);
2314 m_new->valid = m->valid;
2315 m_new->dirty = m->dirty;
2316 m->flags &= ~PG_ZERO;
2319 vm_page_replace_checked(m_new, object,
2325 * The new page must be deactivated
2326 * before the object is unlocked.
2328 vm_page_change_lock(m_new, &m_mtx);
2329 vm_page_deactivate(m_new);
2331 m->flags &= ~PG_ZERO;
2334 KASSERT(m->dirty == 0,
2335 ("page %p is dirty", m));
2337 SLIST_INSERT_HEAD(&free, m, plinks.s.ss);
2341 VM_OBJECT_WUNLOCK(object);
2343 mtx_lock(&vm_page_queue_free_mtx);
2345 if (order < VM_NFREEORDER) {
2347 * The page is enqueued in the physical memory
2348 * allocator's free page queues. Moreover, it
2349 * is the first page in a power-of-two-sized
2350 * run of contiguous free pages. Jump ahead
2351 * to the last page within that run, and
2352 * continue from there.
2354 m += (1 << order) - 1;
2356 #if VM_NRESERVLEVEL > 0
2357 else if (vm_reserv_is_page_free(m))
2360 mtx_unlock(&vm_page_queue_free_mtx);
2361 if (order == VM_NFREEORDER)
2367 if ((m = SLIST_FIRST(&free)) != NULL) {
2368 mtx_lock(&vm_page_queue_free_mtx);
2370 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2371 vm_page_free_phys(m);
2372 } while ((m = SLIST_FIRST(&free)) != NULL);
2373 vm_page_zero_idle_wakeup();
2374 vm_page_free_wakeup();
2375 mtx_unlock(&vm_page_queue_free_mtx);
2382 CTASSERT(powerof2(NRUNS));
2384 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2386 #define MIN_RECLAIM 8
2389 * vm_page_reclaim_contig:
2391 * Reclaim allocated, contiguous physical memory satisfying the specified
2392 * conditions by relocating the virtual pages using that physical memory.
2393 * Returns true if reclamation is successful and false otherwise. Since
2394 * relocation requires the allocation of physical pages, reclamation may
2395 * fail due to a shortage of free pages. When reclamation fails, callers
2396 * are expected to perform VM_WAIT before retrying a failed allocation
2397 * operation, e.g., vm_page_alloc_contig().
2399 * The caller must always specify an allocation class through "req".
2401 * allocation classes:
2402 * VM_ALLOC_NORMAL normal process request
2403 * VM_ALLOC_SYSTEM system *really* needs a page
2404 * VM_ALLOC_INTERRUPT interrupt time request
2406 * The optional allocation flags are ignored.
2408 * "npages" must be greater than zero. Both "alignment" and "boundary"
2409 * must be a power of two.
2412 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2413 u_long alignment, vm_paddr_t boundary)
2415 vm_paddr_t curr_low;
2416 vm_page_t m_run, m_runs[NRUNS];
2417 u_long count, reclaimed;
2418 int error, i, options, req_class;
2420 KASSERT(npages > 0, ("npages is 0"));
2421 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2422 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2423 req_class = req & VM_ALLOC_CLASS_MASK;
2426 * The page daemon is allowed to dig deeper into the free page list.
2428 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2429 req_class = VM_ALLOC_SYSTEM;
2432 * Return if the number of free pages cannot satisfy the requested
2435 count = vm_cnt.v_free_count;
2436 if (count < npages + vm_cnt.v_free_reserved || (count < npages +
2437 vm_cnt.v_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2438 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2442 * Scan up to three times, relaxing the restrictions ("options") on
2443 * the reclamation of reservations and superpages each time.
2445 for (options = VPSC_NORESERV;;) {
2447 * Find the highest runs that satisfy the given constraints
2448 * and restrictions, and record them in "m_runs".
2453 m_run = vm_phys_scan_contig(npages, curr_low, high,
2454 alignment, boundary, options);
2457 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2458 m_runs[RUN_INDEX(count)] = m_run;
2463 * Reclaim the highest runs in LIFO (descending) order until
2464 * the number of reclaimed pages, "reclaimed", is at least
2465 * MIN_RECLAIM. Reset "reclaimed" each time because each
2466 * reclamation is idempotent, and runs will (likely) recur
2467 * from one scan to the next as restrictions are relaxed.
2470 for (i = 0; count > 0 && i < NRUNS; i++) {
2472 m_run = m_runs[RUN_INDEX(count)];
2473 error = vm_page_reclaim_run(req_class, npages, m_run,
2476 reclaimed += npages;
2477 if (reclaimed >= MIN_RECLAIM)
2483 * Either relax the restrictions on the next scan or return if
2484 * the last scan had no restrictions.
2486 if (options == VPSC_NORESERV)
2487 options = VPSC_NOSUPER;
2488 else if (options == VPSC_NOSUPER)
2490 else if (options == VPSC_ANY)
2491 return (reclaimed != 0);
2496 * vm_wait: (also see VM_WAIT macro)
2498 * Sleep until free pages are available for allocation.
2499 * - Called in various places before memory allocations.
2505 mtx_lock(&vm_page_queue_free_mtx);
2506 if (curproc == pageproc) {
2507 vm_pageout_pages_needed = 1;
2508 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
2509 PDROP | PSWP, "VMWait", 0);
2511 if (__predict_false(pageproc == NULL))
2512 panic("vm_wait in early boot");
2513 if (!vm_pageout_wanted) {
2514 vm_pageout_wanted = true;
2515 wakeup(&vm_pageout_wanted);
2517 vm_pages_needed = true;
2518 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
2524 * vm_waitpfault: (also see VM_WAITPFAULT macro)
2526 * Sleep until free pages are available for allocation.
2527 * - Called only in vm_fault so that processes page faulting
2528 * can be easily tracked.
2529 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2530 * processes will be able to grab memory first. Do not change
2531 * this balance without careful testing first.
2537 mtx_lock(&vm_page_queue_free_mtx);
2538 if (!vm_pageout_wanted) {
2539 vm_pageout_wanted = true;
2540 wakeup(&vm_pageout_wanted);
2542 vm_pages_needed = true;
2543 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
2547 struct vm_pagequeue *
2548 vm_page_pagequeue(vm_page_t m)
2551 if (vm_page_in_laundry(m))
2552 return (&vm_dom[0].vmd_pagequeues[m->queue]);
2554 return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2560 * Remove the given page from its current page queue.
2562 * The page must be locked.
2565 vm_page_dequeue(vm_page_t m)
2567 struct vm_pagequeue *pq;
2569 vm_page_assert_locked(m);
2570 KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
2572 pq = vm_page_pagequeue(m);
2573 vm_pagequeue_lock(pq);
2575 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2576 vm_pagequeue_cnt_dec(pq);
2577 vm_pagequeue_unlock(pq);
2581 * vm_page_dequeue_locked:
2583 * Remove the given page from its current page queue.
2585 * The page and page queue must be locked.
2588 vm_page_dequeue_locked(vm_page_t m)
2590 struct vm_pagequeue *pq;
2592 vm_page_lock_assert(m, MA_OWNED);
2593 pq = vm_page_pagequeue(m);
2594 vm_pagequeue_assert_locked(pq);
2596 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2597 vm_pagequeue_cnt_dec(pq);
2603 * Add the given page to the specified page queue.
2605 * The page must be locked.
2608 vm_page_enqueue(uint8_t queue, vm_page_t m)
2610 struct vm_pagequeue *pq;
2612 vm_page_lock_assert(m, MA_OWNED);
2613 KASSERT(queue < PQ_COUNT,
2614 ("vm_page_enqueue: invalid queue %u request for page %p",
2616 if (queue == PQ_LAUNDRY)
2617 pq = &vm_dom[0].vmd_pagequeues[queue];
2619 pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2620 vm_pagequeue_lock(pq);
2622 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2623 vm_pagequeue_cnt_inc(pq);
2624 vm_pagequeue_unlock(pq);
2630 * Move the given page to the tail of its current page queue.
2632 * The page must be locked.
2635 vm_page_requeue(vm_page_t m)
2637 struct vm_pagequeue *pq;
2639 vm_page_lock_assert(m, MA_OWNED);
2640 KASSERT(m->queue != PQ_NONE,
2641 ("vm_page_requeue: page %p is not queued", m));
2642 pq = vm_page_pagequeue(m);
2643 vm_pagequeue_lock(pq);
2644 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2645 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2646 vm_pagequeue_unlock(pq);
2650 * vm_page_requeue_locked:
2652 * Move the given page to the tail of its current page queue.
2654 * The page queue must be locked.
2657 vm_page_requeue_locked(vm_page_t m)
2659 struct vm_pagequeue *pq;
2661 KASSERT(m->queue != PQ_NONE,
2662 ("vm_page_requeue_locked: page %p is not queued", m));
2663 pq = vm_page_pagequeue(m);
2664 vm_pagequeue_assert_locked(pq);
2665 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2666 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2672 * Put the specified page on the active list (if appropriate).
2673 * Ensure that act_count is at least ACT_INIT but do not otherwise
2676 * The page must be locked.
2679 vm_page_activate(vm_page_t m)
2683 vm_page_lock_assert(m, MA_OWNED);
2684 if ((queue = m->queue) != PQ_ACTIVE) {
2685 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2686 if (m->act_count < ACT_INIT)
2687 m->act_count = ACT_INIT;
2688 if (queue != PQ_NONE)
2690 vm_page_enqueue(PQ_ACTIVE, m);
2692 KASSERT(queue == PQ_NONE,
2693 ("vm_page_activate: wired page %p is queued", m));
2695 if (m->act_count < ACT_INIT)
2696 m->act_count = ACT_INIT;
2701 * vm_page_free_wakeup:
2703 * Helper routine for vm_page_free_toq(). This routine is called
2704 * when a page is added to the free queues.
2706 * The page queues must be locked.
2709 vm_page_free_wakeup(void)
2712 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2714 * if pageout daemon needs pages, then tell it that there are
2717 if (vm_pageout_pages_needed &&
2718 vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
2719 wakeup(&vm_pageout_pages_needed);
2720 vm_pageout_pages_needed = 0;
2723 * wakeup processes that are waiting on memory if we hit a
2724 * high water mark. And wakeup scheduler process if we have
2725 * lots of memory. this process will swapin processes.
2727 if (vm_pages_needed && !vm_page_count_min()) {
2728 vm_pages_needed = false;
2729 wakeup(&vm_cnt.v_free_count);
2734 * vm_page_free_prep:
2736 * Prepares the given page to be put on the free list,
2737 * disassociating it from any VM object. The caller may return
2738 * the page to the free list only if this function returns true.
2740 * The object must be locked. The page must be locked if it is
2741 * managed. For a queued managed page, the pagequeue_locked
2742 * argument specifies whether the page queue is already locked.
2745 vm_page_free_prep(vm_page_t m, bool pagequeue_locked)
2748 if ((m->oflags & VPO_UNMANAGED) == 0) {
2749 vm_page_lock_assert(m, MA_OWNED);
2750 KASSERT(!pmap_page_is_mapped(m),
2751 ("vm_page_free_toq: freeing mapped page %p", m));
2753 KASSERT(m->queue == PQ_NONE,
2754 ("vm_page_free_toq: unmanaged page %p is queued", m));
2755 PCPU_INC(cnt.v_tfree);
2757 if (vm_page_sbusied(m))
2758 panic("vm_page_free: freeing busy page %p", m);
2761 * Unqueue, then remove page. Note that we cannot destroy
2762 * the page here because we do not want to call the pager's
2763 * callback routine until after we've put the page on the
2764 * appropriate free queue.
2766 if (m->queue != PQ_NONE) {
2767 if (pagequeue_locked)
2768 vm_page_dequeue_locked(m);
2775 * If fictitious remove object association and
2776 * return, otherwise delay object association removal.
2778 if ((m->flags & PG_FICTITIOUS) != 0)
2784 if (m->wire_count != 0)
2785 panic("vm_page_free: freeing wired page %p", m);
2786 if (m->hold_count != 0) {
2787 m->flags &= ~PG_ZERO;
2788 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2789 ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
2790 m->flags |= PG_UNHOLDFREE;
2795 * Restore the default memory attribute to the page.
2797 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2798 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2804 * Insert the page into the physical memory allocator's free page
2805 * queues. This is the last step to free a page.
2808 vm_page_free_phys(vm_page_t m)
2811 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2813 vm_phys_freecnt_adj(m, 1);
2814 #if VM_NRESERVLEVEL > 0
2815 if (!vm_reserv_free_page(m))
2817 vm_phys_free_pages(m, 0);
2818 if ((m->flags & PG_ZERO) != 0)
2819 ++vm_page_zero_count;
2821 vm_page_zero_idle_wakeup();
2825 vm_page_free_phys_pglist(struct pglist *tq)
2829 mtx_lock(&vm_page_queue_free_mtx);
2830 TAILQ_FOREACH(m, tq, listq)
2831 vm_page_free_phys(m);
2832 vm_page_free_wakeup();
2833 mtx_unlock(&vm_page_queue_free_mtx);
2839 * Returns the given page to the free list, disassociating it
2840 * from any VM object.
2842 * The object must be locked. The page must be locked if it is
2846 vm_page_free_toq(vm_page_t m)
2849 if (!vm_page_free_prep(m, false))
2851 mtx_lock(&vm_page_queue_free_mtx);
2852 vm_page_free_phys(m);
2853 vm_page_free_wakeup();
2854 mtx_unlock(&vm_page_queue_free_mtx);
2860 * Mark this page as wired down by yet
2861 * another map, removing it from paging queues
2864 * If the page is fictitious, then its wire count must remain one.
2866 * The page must be locked.
2869 vm_page_wire(vm_page_t m)
2873 * Only bump the wire statistics if the page is not already wired,
2874 * and only unqueue the page if it is on some queue (if it is unmanaged
2875 * it is already off the queues).
2877 vm_page_lock_assert(m, MA_OWNED);
2878 if ((m->flags & PG_FICTITIOUS) != 0) {
2879 KASSERT(m->wire_count == 1,
2880 ("vm_page_wire: fictitious page %p's wire count isn't one",
2884 if (m->wire_count == 0) {
2885 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
2886 m->queue == PQ_NONE,
2887 ("vm_page_wire: unmanaged page %p is queued", m));
2889 atomic_add_int(&vm_cnt.v_wire_count, 1);
2892 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
2898 * Release one wiring of the specified page, potentially allowing it to be
2899 * paged out. Returns TRUE if the number of wirings transitions to zero and
2902 * Only managed pages belonging to an object can be paged out. If the number
2903 * of wirings transitions to zero and the page is eligible for page out, then
2904 * the page is added to the specified paging queue (unless PQ_NONE is
2907 * If a page is fictitious, then its wire count must always be one.
2909 * A managed page must be locked.
2912 vm_page_unwire(vm_page_t m, uint8_t queue)
2915 KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
2916 ("vm_page_unwire: invalid queue %u request for page %p",
2918 if ((m->oflags & VPO_UNMANAGED) == 0)
2919 vm_page_assert_locked(m);
2920 if ((m->flags & PG_FICTITIOUS) != 0) {
2921 KASSERT(m->wire_count == 1,
2922 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
2925 if (m->wire_count > 0) {
2927 if (m->wire_count == 0) {
2928 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2929 if ((m->oflags & VPO_UNMANAGED) == 0 &&
2930 m->object != NULL && queue != PQ_NONE)
2931 vm_page_enqueue(queue, m);
2936 panic("vm_page_unwire: page %p's wire count is zero", m);
2940 * Move the specified page to the inactive queue.
2942 * Normally, "noreuse" is FALSE, resulting in LRU ordering of the inactive
2943 * queue. However, setting "noreuse" to TRUE will accelerate the specified
2944 * page's reclamation, but it will not unmap the page from any address space.
2945 * This is implemented by inserting the page near the head of the inactive
2946 * queue, using a marker page to guide FIFO insertion ordering.
2948 * The page must be locked.
2951 _vm_page_deactivate(vm_page_t m, boolean_t noreuse)
2953 struct vm_pagequeue *pq;
2956 vm_page_assert_locked(m);
2959 * Ignore if the page is already inactive, unless it is unlikely to be
2962 if ((queue = m->queue) == PQ_INACTIVE && !noreuse)
2964 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2965 pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
2966 /* Avoid multiple acquisitions of the inactive queue lock. */
2967 if (queue == PQ_INACTIVE) {
2968 vm_pagequeue_lock(pq);
2969 vm_page_dequeue_locked(m);
2971 if (queue != PQ_NONE)
2973 vm_pagequeue_lock(pq);
2975 m->queue = PQ_INACTIVE;
2977 TAILQ_INSERT_BEFORE(&vm_phys_domain(m)->vmd_inacthead,
2980 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2981 vm_pagequeue_cnt_inc(pq);
2982 vm_pagequeue_unlock(pq);
2987 * Move the specified page to the inactive queue.
2989 * The page must be locked.
2992 vm_page_deactivate(vm_page_t m)
2995 _vm_page_deactivate(m, FALSE);
2999 * Move the specified page to the inactive queue with the expectation
3000 * that it is unlikely to be reused.
3002 * The page must be locked.
3005 vm_page_deactivate_noreuse(vm_page_t m)
3008 _vm_page_deactivate(m, TRUE);
3014 * Put a page in the laundry.
3017 vm_page_launder(vm_page_t m)
3021 vm_page_assert_locked(m);
3022 if ((queue = m->queue) != PQ_LAUNDRY) {
3023 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
3024 if (queue != PQ_NONE)
3026 vm_page_enqueue(PQ_LAUNDRY, m);
3028 KASSERT(queue == PQ_NONE,
3029 ("wired page %p is queued", m));
3034 * vm_page_try_to_free()
3036 * Attempt to free the page. If we cannot free it, we do nothing.
3037 * 1 is returned on success, 0 on failure.
3040 vm_page_try_to_free(vm_page_t m)
3043 vm_page_lock_assert(m, MA_OWNED);
3044 if (m->object != NULL)
3045 VM_OBJECT_ASSERT_WLOCKED(m->object);
3046 if (m->dirty || m->hold_count || m->wire_count ||
3047 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
3059 * Apply the specified advice to the given page.
3061 * The object and page must be locked.
3064 vm_page_advise(vm_page_t m, int advice)
3067 vm_page_assert_locked(m);
3068 VM_OBJECT_ASSERT_WLOCKED(m->object);
3069 if (advice == MADV_FREE)
3071 * Mark the page clean. This will allow the page to be freed
3072 * without first paging it out. MADV_FREE pages are often
3073 * quickly reused by malloc(3), so we do not do anything that
3074 * would result in a page fault on a later access.
3077 else if (advice != MADV_DONTNEED) {
3078 if (advice == MADV_WILLNEED)
3079 vm_page_activate(m);
3084 * Clear any references to the page. Otherwise, the page daemon will
3085 * immediately reactivate the page.
3087 vm_page_aflag_clear(m, PGA_REFERENCED);
3089 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3093 * Place clean pages near the head of the inactive queue rather than
3094 * the tail, thus defeating the queue's LRU operation and ensuring that
3095 * the page will be reused quickly. Dirty pages not already in the
3096 * laundry are moved there.
3099 vm_page_deactivate_noreuse(m);
3105 * Grab a page, waiting until we are waken up due to the page
3106 * changing state. We keep on waiting, if the page continues
3107 * to be in the object. If the page doesn't exist, first allocate it
3108 * and then conditionally zero it.
3110 * This routine may sleep.
3112 * The object must be locked on entry. The lock will, however, be released
3113 * and reacquired if the routine sleeps.
3116 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3121 VM_OBJECT_ASSERT_WLOCKED(object);
3122 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3123 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3124 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3126 if ((m = vm_page_lookup(object, pindex)) != NULL) {
3127 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3128 vm_page_xbusied(m) : vm_page_busied(m);
3130 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3133 * Reference the page before unlocking and
3134 * sleeping so that the page daemon is less
3135 * likely to reclaim it.
3137 vm_page_aflag_set(m, PGA_REFERENCED);
3139 VM_OBJECT_WUNLOCK(object);
3140 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
3141 VM_ALLOC_IGN_SBUSY) != 0);
3142 VM_OBJECT_WLOCK(object);
3145 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3151 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3153 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3158 m = vm_page_alloc(object, pindex, allocflags);
3160 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3162 VM_OBJECT_WUNLOCK(object);
3164 VM_OBJECT_WLOCK(object);
3167 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3173 * Return the specified range of pages from the given object. For each
3174 * page offset within the range, if a page already exists within the object
3175 * at that offset and it is busy, then wait for it to change state. If,
3176 * instead, the page doesn't exist, then allocate it.
3178 * The caller must always specify an allocation class.
3180 * allocation classes:
3181 * VM_ALLOC_NORMAL normal process request
3182 * VM_ALLOC_SYSTEM system *really* needs the pages
3184 * The caller must always specify that the pages are to be busied and/or
3187 * optional allocation flags:
3188 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
3189 * VM_ALLOC_NOBUSY do not exclusive busy the page
3190 * VM_ALLOC_NOWAIT do not sleep
3191 * VM_ALLOC_SBUSY set page to sbusy state
3192 * VM_ALLOC_WIRED wire the pages
3193 * VM_ALLOC_ZERO zero and validate any invalid pages
3195 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
3196 * may return a partial prefix of the requested range.
3199 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
3200 vm_page_t *ma, int count)
3206 VM_OBJECT_ASSERT_WLOCKED(object);
3207 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
3208 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
3209 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
3210 (allocflags & VM_ALLOC_WIRED) != 0,
3211 ("vm_page_grab_pages: the pages must be busied or wired"));
3212 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3213 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3214 ("vm_page_grab_pages: VM_ALLOC_SBUSY/IGN_SBUSY mismatch"));
3219 m = vm_page_lookup(object, pindex + i);
3220 for (; i < count; i++) {
3222 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3223 vm_page_xbusied(m) : vm_page_busied(m);
3225 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3228 * Reference the page before unlocking and
3229 * sleeping so that the page daemon is less
3230 * likely to reclaim it.
3232 vm_page_aflag_set(m, PGA_REFERENCED);
3234 VM_OBJECT_WUNLOCK(object);
3235 vm_page_busy_sleep(m, "grbmaw", (allocflags &
3236 VM_ALLOC_IGN_SBUSY) != 0);
3237 VM_OBJECT_WLOCK(object);
3240 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3245 if ((allocflags & (VM_ALLOC_NOBUSY |
3246 VM_ALLOC_SBUSY)) == 0)
3248 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3251 m = vm_page_alloc(object, pindex + i, (allocflags &
3252 ~VM_ALLOC_IGN_SBUSY) | VM_ALLOC_COUNT(count - i));
3254 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3256 VM_OBJECT_WUNLOCK(object);
3258 VM_OBJECT_WLOCK(object);
3262 if (m->valid == 0 && (allocflags & VM_ALLOC_ZERO) != 0) {
3263 if ((m->flags & PG_ZERO) == 0)
3265 m->valid = VM_PAGE_BITS_ALL;
3268 m = vm_page_next(m);
3274 * Mapping function for valid or dirty bits in a page.
3276 * Inputs are required to range within a page.
3279 vm_page_bits(int base, int size)
3285 base + size <= PAGE_SIZE,
3286 ("vm_page_bits: illegal base/size %d/%d", base, size)
3289 if (size == 0) /* handle degenerate case */
3292 first_bit = base >> DEV_BSHIFT;
3293 last_bit = (base + size - 1) >> DEV_BSHIFT;
3295 return (((vm_page_bits_t)2 << last_bit) -
3296 ((vm_page_bits_t)1 << first_bit));
3300 * vm_page_set_valid_range:
3302 * Sets portions of a page valid. The arguments are expected
3303 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3304 * of any partial chunks touched by the range. The invalid portion of
3305 * such chunks will be zeroed.
3307 * (base + size) must be less then or equal to PAGE_SIZE.
3310 vm_page_set_valid_range(vm_page_t m, int base, int size)
3314 VM_OBJECT_ASSERT_WLOCKED(m->object);
3315 if (size == 0) /* handle degenerate case */
3319 * If the base is not DEV_BSIZE aligned and the valid
3320 * bit is clear, we have to zero out a portion of the
3323 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3324 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
3325 pmap_zero_page_area(m, frag, base - frag);
3328 * If the ending offset is not DEV_BSIZE aligned and the
3329 * valid bit is clear, we have to zero out a portion of
3332 endoff = base + size;
3333 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3334 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
3335 pmap_zero_page_area(m, endoff,
3336 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3339 * Assert that no previously invalid block that is now being validated
3342 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
3343 ("vm_page_set_valid_range: page %p is dirty", m));
3346 * Set valid bits inclusive of any overlap.
3348 m->valid |= vm_page_bits(base, size);
3352 * Clear the given bits from the specified page's dirty field.
3354 static __inline void
3355 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
3358 #if PAGE_SIZE < 16384
3363 * If the object is locked and the page is neither exclusive busy nor
3364 * write mapped, then the page's dirty field cannot possibly be
3365 * set by a concurrent pmap operation.
3367 VM_OBJECT_ASSERT_WLOCKED(m->object);
3368 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
3369 m->dirty &= ~pagebits;
3372 * The pmap layer can call vm_page_dirty() without
3373 * holding a distinguished lock. The combination of
3374 * the object's lock and an atomic operation suffice
3375 * to guarantee consistency of the page dirty field.
3377 * For PAGE_SIZE == 32768 case, compiler already
3378 * properly aligns the dirty field, so no forcible
3379 * alignment is needed. Only require existence of
3380 * atomic_clear_64 when page size is 32768.
3382 addr = (uintptr_t)&m->dirty;
3383 #if PAGE_SIZE == 32768
3384 atomic_clear_64((uint64_t *)addr, pagebits);
3385 #elif PAGE_SIZE == 16384
3386 atomic_clear_32((uint32_t *)addr, pagebits);
3387 #else /* PAGE_SIZE <= 8192 */
3389 * Use a trick to perform a 32-bit atomic on the
3390 * containing aligned word, to not depend on the existence
3391 * of atomic_clear_{8, 16}.
3393 shift = addr & (sizeof(uint32_t) - 1);
3394 #if BYTE_ORDER == BIG_ENDIAN
3395 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
3399 addr &= ~(sizeof(uint32_t) - 1);
3400 atomic_clear_32((uint32_t *)addr, pagebits << shift);
3401 #endif /* PAGE_SIZE */
3406 * vm_page_set_validclean:
3408 * Sets portions of a page valid and clean. The arguments are expected
3409 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3410 * of any partial chunks touched by the range. The invalid portion of
3411 * such chunks will be zero'd.
3413 * (base + size) must be less then or equal to PAGE_SIZE.
3416 vm_page_set_validclean(vm_page_t m, int base, int size)
3418 vm_page_bits_t oldvalid, pagebits;
3421 VM_OBJECT_ASSERT_WLOCKED(m->object);
3422 if (size == 0) /* handle degenerate case */
3426 * If the base is not DEV_BSIZE aligned and the valid
3427 * bit is clear, we have to zero out a portion of the
3430 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3431 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
3432 pmap_zero_page_area(m, frag, base - frag);
3435 * If the ending offset is not DEV_BSIZE aligned and the
3436 * valid bit is clear, we have to zero out a portion of
3439 endoff = base + size;
3440 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3441 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
3442 pmap_zero_page_area(m, endoff,
3443 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3446 * Set valid, clear dirty bits. If validating the entire
3447 * page we can safely clear the pmap modify bit. We also
3448 * use this opportunity to clear the VPO_NOSYNC flag. If a process
3449 * takes a write fault on a MAP_NOSYNC memory area the flag will
3452 * We set valid bits inclusive of any overlap, but we can only
3453 * clear dirty bits for DEV_BSIZE chunks that are fully within
3456 oldvalid = m->valid;
3457 pagebits = vm_page_bits(base, size);
3458 m->valid |= pagebits;
3460 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
3461 frag = DEV_BSIZE - frag;
3467 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
3469 if (base == 0 && size == PAGE_SIZE) {
3471 * The page can only be modified within the pmap if it is
3472 * mapped, and it can only be mapped if it was previously
3475 if (oldvalid == VM_PAGE_BITS_ALL)
3477 * Perform the pmap_clear_modify() first. Otherwise,
3478 * a concurrent pmap operation, such as
3479 * pmap_protect(), could clear a modification in the
3480 * pmap and set the dirty field on the page before
3481 * pmap_clear_modify() had begun and after the dirty
3482 * field was cleared here.
3484 pmap_clear_modify(m);
3486 m->oflags &= ~VPO_NOSYNC;
3487 } else if (oldvalid != VM_PAGE_BITS_ALL)
3488 m->dirty &= ~pagebits;
3490 vm_page_clear_dirty_mask(m, pagebits);
3494 vm_page_clear_dirty(vm_page_t m, int base, int size)
3497 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
3501 * vm_page_set_invalid:
3503 * Invalidates DEV_BSIZE'd chunks within a page. Both the
3504 * valid and dirty bits for the effected areas are cleared.
3507 vm_page_set_invalid(vm_page_t m, int base, int size)
3509 vm_page_bits_t bits;
3513 VM_OBJECT_ASSERT_WLOCKED(object);
3514 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
3515 size >= object->un_pager.vnp.vnp_size)
3516 bits = VM_PAGE_BITS_ALL;
3518 bits = vm_page_bits(base, size);
3519 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
3522 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3523 !pmap_page_is_mapped(m),
3524 ("vm_page_set_invalid: page %p is mapped", m));
3530 * vm_page_zero_invalid()
3532 * The kernel assumes that the invalid portions of a page contain
3533 * garbage, but such pages can be mapped into memory by user code.
3534 * When this occurs, we must zero out the non-valid portions of the
3535 * page so user code sees what it expects.
3537 * Pages are most often semi-valid when the end of a file is mapped
3538 * into memory and the file's size is not page aligned.
3541 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3546 VM_OBJECT_ASSERT_WLOCKED(m->object);
3548 * Scan the valid bits looking for invalid sections that
3549 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
3550 * valid bit may be set ) have already been zeroed by
3551 * vm_page_set_validclean().
3553 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3554 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3555 (m->valid & ((vm_page_bits_t)1 << i))) {
3557 pmap_zero_page_area(m,
3558 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3565 * setvalid is TRUE when we can safely set the zero'd areas
3566 * as being valid. We can do this if there are no cache consistancy
3567 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3570 m->valid = VM_PAGE_BITS_ALL;
3576 * Is (partial) page valid? Note that the case where size == 0
3577 * will return FALSE in the degenerate case where the page is
3578 * entirely invalid, and TRUE otherwise.
3581 vm_page_is_valid(vm_page_t m, int base, int size)
3583 vm_page_bits_t bits;
3585 VM_OBJECT_ASSERT_LOCKED(m->object);
3586 bits = vm_page_bits(base, size);
3587 return (m->valid != 0 && (m->valid & bits) == bits);
3591 * vm_page_ps_is_valid:
3593 * Returns TRUE if the entire (super)page is valid and FALSE otherwise.
3596 vm_page_ps_is_valid(vm_page_t m)
3600 VM_OBJECT_ASSERT_LOCKED(m->object);
3601 npages = atop(pagesizes[m->psind]);
3604 * The physically contiguous pages that make up a superpage, i.e., a
3605 * page with a page size index ("psind") greater than zero, will
3606 * occupy adjacent entries in vm_page_array[].
3608 for (i = 0; i < npages; i++) {
3609 if (m[i].valid != VM_PAGE_BITS_ALL)
3616 * Set the page's dirty bits if the page is modified.
3619 vm_page_test_dirty(vm_page_t m)
3622 VM_OBJECT_ASSERT_WLOCKED(m->object);
3623 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3628 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3631 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3635 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3638 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3642 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3645 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3648 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3650 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3653 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3657 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3660 mtx_assert_(vm_page_lockptr(m), a, file, line);
3666 vm_page_object_lock_assert(vm_page_t m)
3670 * Certain of the page's fields may only be modified by the
3671 * holder of the containing object's lock or the exclusive busy.
3672 * holder. Unfortunately, the holder of the write busy is
3673 * not recorded, and thus cannot be checked here.
3675 if (m->object != NULL && !vm_page_xbusied(m))
3676 VM_OBJECT_ASSERT_WLOCKED(m->object);
3680 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3683 if ((bits & PGA_WRITEABLE) == 0)
3687 * The PGA_WRITEABLE flag can only be set if the page is
3688 * managed, is exclusively busied or the object is locked.
3689 * Currently, this flag is only set by pmap_enter().
3691 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3692 ("PGA_WRITEABLE on unmanaged page"));
3693 if (!vm_page_xbusied(m))
3694 VM_OBJECT_ASSERT_LOCKED(m->object);
3698 #include "opt_ddb.h"
3700 #include <sys/kernel.h>
3702 #include <ddb/ddb.h>
3704 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3707 db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
3708 db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
3709 db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
3710 db_printf("vm_cnt.v_laundry_count: %d\n", vm_cnt.v_laundry_count);
3711 db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
3712 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
3713 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
3714 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
3715 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
3718 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3722 db_printf("pq_free %d\n", vm_cnt.v_free_count);
3723 for (dom = 0; dom < vm_ndomains; dom++) {
3725 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d\n",
3727 vm_dom[dom].vmd_page_count,
3728 vm_dom[dom].vmd_free_count,
3729 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3730 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
3731 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt);
3735 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3741 db_printf("show pginfo addr\n");
3745 phys = strchr(modif, 'p') != NULL;
3747 m = PHYS_TO_VM_PAGE(addr);
3749 m = (vm_page_t)addr;
3751 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3752 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3753 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3754 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3755 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);