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)
421 struct vm_domain *vmd;
422 struct vm_phys_seg *seg;
424 char *list, *listend;
426 vm_paddr_t end, high_avail, low_avail, new_end, page_range, size;
427 vm_paddr_t biggestsize, last_pa, pa;
429 int biggestone, i, pages_per_zone, segind;
433 vaddr = round_page(vaddr);
435 for (i = 0; phys_avail[i + 1]; i += 2) {
436 phys_avail[i] = round_page(phys_avail[i]);
437 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
439 for (i = 0; phys_avail[i + 1]; i += 2) {
440 size = phys_avail[i + 1] - phys_avail[i];
441 if (size > biggestsize) {
447 end = phys_avail[biggestone+1];
450 * Initialize the page and queue locks.
452 mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
453 for (i = 0; i < PA_LOCK_COUNT; i++)
454 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
455 for (i = 0; i < vm_ndomains; i++)
456 vm_page_domain_init(&vm_dom[i]);
459 * Almost all of the pages needed for bootstrapping UMA are used
460 * for zone structures, so if the number of CPUs results in those
461 * structures taking more than one page each, we set aside more pages
462 * in proportion to the zone structure size.
464 pages_per_zone = howmany(sizeof(struct uma_zone) +
465 sizeof(struct uma_cache) * (mp_maxid + 1) +
466 roundup2(sizeof(struct uma_slab), sizeof(void *)), UMA_SLAB_SIZE);
467 if (pages_per_zone > 1) {
468 /* Reserve more pages so that we don't run out. */
469 boot_pages = UMA_BOOT_PAGES_ZONES * pages_per_zone;
473 * Allocate memory for use when boot strapping the kernel memory
476 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
477 * manually fetch the value.
479 TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
480 new_end = end - (boot_pages * UMA_SLAB_SIZE);
481 new_end = trunc_page(new_end);
482 mapped = pmap_map(&vaddr, new_end, end,
483 VM_PROT_READ | VM_PROT_WRITE);
484 bzero((void *)mapped, end - new_end);
485 uma_startup((void *)mapped, boot_pages);
487 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
488 defined(__i386__) || defined(__mips__)
490 * Allocate a bitmap to indicate that a random physical page
491 * needs to be included in a minidump.
493 * The amd64 port needs this to indicate which direct map pages
494 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
496 * However, i386 still needs this workspace internally within the
497 * minidump code. In theory, they are not needed on i386, but are
498 * included should the sf_buf code decide to use them.
501 for (i = 0; dump_avail[i + 1] != 0; i += 2)
502 if (dump_avail[i + 1] > last_pa)
503 last_pa = dump_avail[i + 1];
504 page_range = last_pa / PAGE_SIZE;
505 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
506 new_end -= vm_page_dump_size;
507 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
508 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
509 bzero((void *)vm_page_dump, vm_page_dump_size);
513 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
515 * Include the UMA bootstrap pages and vm_page_dump in a crash dump.
516 * When pmap_map() uses the direct map, they are not automatically
519 for (pa = new_end; pa < end; pa += PAGE_SIZE)
522 phys_avail[biggestone + 1] = new_end;
525 * Request that the physical pages underlying the message buffer be
526 * included in a crash dump. Since the message buffer is accessed
527 * through the direct map, they are not automatically included.
529 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
530 last_pa = pa + round_page(msgbufsize);
531 while (pa < last_pa) {
537 * Compute the number of pages of memory that will be available for
538 * use, taking into account the overhead of a page structure per page.
539 * In other words, solve
540 * "available physical memory" - round_page(page_range *
541 * sizeof(struct vm_page)) = page_range * PAGE_SIZE
544 low_avail = phys_avail[0];
545 high_avail = phys_avail[1];
546 for (i = 0; i < vm_phys_nsegs; i++) {
547 if (vm_phys_segs[i].start < low_avail)
548 low_avail = vm_phys_segs[i].start;
549 if (vm_phys_segs[i].end > high_avail)
550 high_avail = vm_phys_segs[i].end;
552 /* Skip the first chunk. It is already accounted for. */
553 for (i = 2; phys_avail[i + 1] != 0; i += 2) {
554 if (phys_avail[i] < low_avail)
555 low_avail = phys_avail[i];
556 if (phys_avail[i + 1] > high_avail)
557 high_avail = phys_avail[i + 1];
559 first_page = low_avail / PAGE_SIZE;
560 #ifdef VM_PHYSSEG_SPARSE
562 for (i = 0; i < vm_phys_nsegs; i++)
563 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
564 for (i = 0; phys_avail[i + 1] != 0; i += 2)
565 size += phys_avail[i + 1] - phys_avail[i];
566 #elif defined(VM_PHYSSEG_DENSE)
567 size = high_avail - low_avail;
569 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
572 #ifdef VM_PHYSSEG_DENSE
574 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
575 * the overhead of a page structure per page only if vm_page_array is
576 * allocated from the last physical memory chunk. Otherwise, we must
577 * allocate page structures representing the physical memory
578 * underlying vm_page_array, even though they will not be used.
580 if (new_end != high_avail)
581 page_range = size / PAGE_SIZE;
585 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
588 * If the partial bytes remaining are large enough for
589 * a page (PAGE_SIZE) without a corresponding
590 * 'struct vm_page', then new_end will contain an
591 * extra page after subtracting the length of the VM
592 * page array. Compensate by subtracting an extra
595 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
596 if (new_end == high_avail)
597 high_avail -= PAGE_SIZE;
598 new_end -= PAGE_SIZE;
604 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
605 * However, because this page is allocated from KVM, out-of-bounds
606 * accesses using the direct map will not be trapped.
611 * Allocate physical memory for the page structures, and map it.
613 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
614 mapped = pmap_map(&vaddr, new_end, end,
615 VM_PROT_READ | VM_PROT_WRITE);
616 vm_page_array = (vm_page_t)mapped;
617 vm_page_array_size = page_range;
619 #if VM_NRESERVLEVEL > 0
621 * Allocate physical memory for the reservation management system's
622 * data structures, and map it.
624 if (high_avail == end)
625 high_avail = new_end;
626 new_end = vm_reserv_startup(&vaddr, new_end, high_avail);
628 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
630 * Include vm_page_array and vm_reserv_array in a crash dump.
632 for (pa = new_end; pa < end; pa += PAGE_SIZE)
635 phys_avail[biggestone + 1] = new_end;
638 * Add physical memory segments corresponding to the available
641 for (i = 0; phys_avail[i + 1] != 0; i += 2)
642 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
645 * Initialize the physical memory allocator.
650 * Initialize the page structures and add every available page to the
651 * physical memory allocator's free lists.
653 vm_cnt.v_page_count = 0;
654 vm_cnt.v_free_count = 0;
655 for (segind = 0; segind < vm_phys_nsegs; segind++) {
656 seg = &vm_phys_segs[segind];
657 for (pa = seg->start; pa < seg->end; pa += PAGE_SIZE)
658 vm_phys_init_page(pa);
661 * Add the segment to the free lists only if it is covered by
662 * one of the ranges in phys_avail. Because we've added the
663 * ranges to the vm_phys_segs array, we can assume that each
664 * segment is either entirely contained in one of the ranges,
665 * or doesn't overlap any of them.
667 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
668 if (seg->start < phys_avail[i] ||
669 seg->end > phys_avail[i + 1])
673 pagecount = (u_long)atop(seg->end - seg->start);
675 mtx_lock(&vm_page_queue_free_mtx);
676 vm_phys_free_contig(m, pagecount);
677 vm_phys_freecnt_adj(m, (int)pagecount);
678 mtx_unlock(&vm_page_queue_free_mtx);
679 vm_cnt.v_page_count += (u_int)pagecount;
681 vmd = &vm_dom[seg->domain];
682 vmd->vmd_page_count += (u_int)pagecount;
683 vmd->vmd_segs |= 1UL << m->segind;
689 * Remove blacklisted pages from the physical memory allocator.
691 TAILQ_INIT(&blacklist_head);
692 vm_page_blacklist_load(&list, &listend);
693 vm_page_blacklist_check(list, listend);
695 list = kern_getenv("vm.blacklist");
696 vm_page_blacklist_check(list, NULL);
699 #if VM_NRESERVLEVEL > 0
701 * Initialize the reservation management system.
709 vm_page_reference(vm_page_t m)
712 vm_page_aflag_set(m, PGA_REFERENCED);
716 * vm_page_busy_downgrade:
718 * Downgrade an exclusive busy page into a single shared busy page.
721 vm_page_busy_downgrade(vm_page_t m)
726 vm_page_assert_xbusied(m);
727 locked = mtx_owned(vm_page_lockptr(m));
731 x &= VPB_BIT_WAITERS;
732 if (x != 0 && !locked)
734 if (atomic_cmpset_rel_int(&m->busy_lock,
735 VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1)))
737 if (x != 0 && !locked)
750 * Return a positive value if the page is shared busied, 0 otherwise.
753 vm_page_sbusied(vm_page_t m)
758 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
764 * Shared unbusy a page.
767 vm_page_sunbusy(vm_page_t m)
771 vm_page_lock_assert(m, MA_NOTOWNED);
772 vm_page_assert_sbusied(m);
776 if (VPB_SHARERS(x) > 1) {
777 if (atomic_cmpset_int(&m->busy_lock, x,
782 if ((x & VPB_BIT_WAITERS) == 0) {
783 KASSERT(x == VPB_SHARERS_WORD(1),
784 ("vm_page_sunbusy: invalid lock state"));
785 if (atomic_cmpset_int(&m->busy_lock,
786 VPB_SHARERS_WORD(1), VPB_UNBUSIED))
790 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
791 ("vm_page_sunbusy: invalid lock state for waiters"));
794 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
805 * vm_page_busy_sleep:
807 * Sleep and release the page lock, using the page pointer as wchan.
808 * This is used to implement the hard-path of busying mechanism.
810 * The given page must be locked.
812 * If nonshared is true, sleep only if the page is xbusy.
815 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
819 vm_page_assert_locked(m);
822 if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
823 ((x & VPB_BIT_WAITERS) == 0 &&
824 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
828 msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
834 * Try to shared busy a page.
835 * If the operation succeeds 1 is returned otherwise 0.
836 * The operation never sleeps.
839 vm_page_trysbusy(vm_page_t m)
845 if ((x & VPB_BIT_SHARED) == 0)
847 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
853 vm_page_xunbusy_locked(vm_page_t m)
856 vm_page_assert_xbusied(m);
857 vm_page_assert_locked(m);
859 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
860 /* There is a waiter, do wakeup() instead of vm_page_flash(). */
865 vm_page_xunbusy_maybelocked(vm_page_t m)
869 vm_page_assert_xbusied(m);
872 * Fast path for unbusy. If it succeeds, we know that there
873 * are no waiters, so we do not need a wakeup.
875 if (atomic_cmpset_rel_int(&m->busy_lock, VPB_SINGLE_EXCLUSIVER,
879 lockacq = !mtx_owned(vm_page_lockptr(m));
882 vm_page_xunbusy_locked(m);
888 * vm_page_xunbusy_hard:
890 * Called after the first try the exclusive unbusy of a page failed.
891 * It is assumed that the waiters bit is on.
894 vm_page_xunbusy_hard(vm_page_t m)
897 vm_page_assert_xbusied(m);
900 vm_page_xunbusy_locked(m);
907 * Wakeup anyone waiting for the page.
908 * The ownership bits do not change.
910 * The given page must be locked.
913 vm_page_flash(vm_page_t m)
917 vm_page_lock_assert(m, MA_OWNED);
921 if ((x & VPB_BIT_WAITERS) == 0)
923 if (atomic_cmpset_int(&m->busy_lock, x,
924 x & (~VPB_BIT_WAITERS)))
931 * Avoid releasing and reacquiring the same page lock.
934 vm_page_change_lock(vm_page_t m, struct mtx **mtx)
938 mtx1 = vm_page_lockptr(m);
948 * Keep page from being freed by the page daemon
949 * much of the same effect as wiring, except much lower
950 * overhead and should be used only for *very* temporary
951 * holding ("wiring").
954 vm_page_hold(vm_page_t mem)
957 vm_page_lock_assert(mem, MA_OWNED);
962 vm_page_unhold(vm_page_t mem)
965 vm_page_lock_assert(mem, MA_OWNED);
966 KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
968 if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
969 vm_page_free_toq(mem);
973 * vm_page_unhold_pages:
975 * Unhold each of the pages that is referenced by the given array.
978 vm_page_unhold_pages(vm_page_t *ma, int count)
983 for (; count != 0; count--) {
984 vm_page_change_lock(*ma, &mtx);
993 PHYS_TO_VM_PAGE(vm_paddr_t pa)
997 #ifdef VM_PHYSSEG_SPARSE
998 m = vm_phys_paddr_to_vm_page(pa);
1000 m = vm_phys_fictitious_to_vm_page(pa);
1002 #elif defined(VM_PHYSSEG_DENSE)
1006 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1007 m = &vm_page_array[pi - first_page];
1010 return (vm_phys_fictitious_to_vm_page(pa));
1012 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1019 * Create a fictitious page with the specified physical address and
1020 * memory attribute. The memory attribute is the only the machine-
1021 * dependent aspect of a fictitious page that must be initialized.
1024 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1028 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1029 vm_page_initfake(m, paddr, memattr);
1034 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1037 if ((m->flags & PG_FICTITIOUS) != 0) {
1039 * The page's memattr might have changed since the
1040 * previous initialization. Update the pmap to the
1045 m->phys_addr = paddr;
1047 /* Fictitious pages don't use "segind". */
1048 m->flags = PG_FICTITIOUS;
1049 /* Fictitious pages don't use "order" or "pool". */
1050 m->oflags = VPO_UNMANAGED;
1051 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1055 pmap_page_set_memattr(m, memattr);
1061 * Release a fictitious page.
1064 vm_page_putfake(vm_page_t m)
1067 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1068 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1069 ("vm_page_putfake: bad page %p", m));
1070 uma_zfree(fakepg_zone, m);
1074 * vm_page_updatefake:
1076 * Update the given fictitious page to the specified physical address and
1080 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1083 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1084 ("vm_page_updatefake: bad page %p", m));
1085 m->phys_addr = paddr;
1086 pmap_page_set_memattr(m, memattr);
1095 vm_page_free(vm_page_t m)
1098 m->flags &= ~PG_ZERO;
1099 vm_page_free_toq(m);
1103 * vm_page_free_zero:
1105 * Free a page to the zerod-pages queue
1108 vm_page_free_zero(vm_page_t m)
1111 m->flags |= PG_ZERO;
1112 vm_page_free_toq(m);
1116 * Unbusy and handle the page queueing for a page from a getpages request that
1117 * was optionally read ahead or behind.
1120 vm_page_readahead_finish(vm_page_t m)
1123 /* We shouldn't put invalid pages on queues. */
1124 KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
1127 * Since the page is not the actually needed one, whether it should
1128 * be activated or deactivated is not obvious. Empirical results
1129 * have shown that deactivating the page is usually the best choice,
1130 * unless the page is wanted by another thread.
1133 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1134 vm_page_activate(m);
1136 vm_page_deactivate(m);
1142 * vm_page_sleep_if_busy:
1144 * Sleep and release the page queues lock if the page is busied.
1145 * Returns TRUE if the thread slept.
1147 * The given page must be unlocked and object containing it must
1151 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1155 vm_page_lock_assert(m, MA_NOTOWNED);
1156 VM_OBJECT_ASSERT_WLOCKED(m->object);
1158 if (vm_page_busied(m)) {
1160 * The page-specific object must be cached because page
1161 * identity can change during the sleep, causing the
1162 * re-lock of a different object.
1163 * It is assumed that a reference to the object is already
1164 * held by the callers.
1168 VM_OBJECT_WUNLOCK(obj);
1169 vm_page_busy_sleep(m, msg, false);
1170 VM_OBJECT_WLOCK(obj);
1177 * vm_page_dirty_KBI: [ internal use only ]
1179 * Set all bits in the page's dirty field.
1181 * The object containing the specified page must be locked if the
1182 * call is made from the machine-independent layer.
1184 * See vm_page_clear_dirty_mask().
1186 * This function should only be called by vm_page_dirty().
1189 vm_page_dirty_KBI(vm_page_t m)
1192 /* Refer to this operation by its public name. */
1193 KASSERT(m->valid == VM_PAGE_BITS_ALL,
1194 ("vm_page_dirty: page is invalid!"));
1195 m->dirty = VM_PAGE_BITS_ALL;
1199 * vm_page_insert: [ internal use only ]
1201 * Inserts the given mem entry into the object and object list.
1203 * The object must be locked.
1206 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1210 VM_OBJECT_ASSERT_WLOCKED(object);
1211 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1212 return (vm_page_insert_after(m, object, pindex, mpred));
1216 * vm_page_insert_after:
1218 * Inserts the page "m" into the specified object at offset "pindex".
1220 * The page "mpred" must immediately precede the offset "pindex" within
1221 * the specified object.
1223 * The object must be locked.
1226 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1231 VM_OBJECT_ASSERT_WLOCKED(object);
1232 KASSERT(m->object == NULL,
1233 ("vm_page_insert_after: page already inserted"));
1234 if (mpred != NULL) {
1235 KASSERT(mpred->object == object,
1236 ("vm_page_insert_after: object doesn't contain mpred"));
1237 KASSERT(mpred->pindex < pindex,
1238 ("vm_page_insert_after: mpred doesn't precede pindex"));
1239 msucc = TAILQ_NEXT(mpred, listq);
1241 msucc = TAILQ_FIRST(&object->memq);
1243 KASSERT(msucc->pindex > pindex,
1244 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1247 * Record the object/offset pair in this page
1253 * Now link into the object's ordered list of backed pages.
1255 if (vm_radix_insert(&object->rtree, m)) {
1260 vm_page_insert_radixdone(m, object, mpred);
1265 * vm_page_insert_radixdone:
1267 * Complete page "m" insertion into the specified object after the
1268 * radix trie hooking.
1270 * The page "mpred" must precede the offset "m->pindex" within the
1273 * The object must be locked.
1276 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1279 VM_OBJECT_ASSERT_WLOCKED(object);
1280 KASSERT(object != NULL && m->object == object,
1281 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1282 if (mpred != NULL) {
1283 KASSERT(mpred->object == object,
1284 ("vm_page_insert_after: object doesn't contain mpred"));
1285 KASSERT(mpred->pindex < m->pindex,
1286 ("vm_page_insert_after: mpred doesn't precede pindex"));
1290 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1292 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1295 * Show that the object has one more resident page.
1297 object->resident_page_count++;
1300 * Hold the vnode until the last page is released.
1302 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1303 vhold(object->handle);
1306 * Since we are inserting a new and possibly dirty page,
1307 * update the object's OBJ_MIGHTBEDIRTY flag.
1309 if (pmap_page_is_write_mapped(m))
1310 vm_object_set_writeable_dirty(object);
1316 * Removes the specified page from its containing object, but does not
1317 * invalidate any backing storage.
1319 * The object must be locked. The page must be locked if it is managed.
1322 vm_page_remove(vm_page_t m)
1327 if ((m->oflags & VPO_UNMANAGED) == 0)
1328 vm_page_assert_locked(m);
1329 if ((object = m->object) == NULL)
1331 VM_OBJECT_ASSERT_WLOCKED(object);
1332 if (vm_page_xbusied(m))
1333 vm_page_xunbusy_maybelocked(m);
1334 mrem = vm_radix_remove(&object->rtree, m->pindex);
1335 KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1338 * Now remove from the object's list of backed pages.
1340 TAILQ_REMOVE(&object->memq, m, listq);
1343 * And show that the object has one fewer resident page.
1345 object->resident_page_count--;
1348 * The vnode may now be recycled.
1350 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1351 vdrop(object->handle);
1359 * Returns the page associated with the object/offset
1360 * pair specified; if none is found, NULL is returned.
1362 * The object must be locked.
1365 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1368 VM_OBJECT_ASSERT_LOCKED(object);
1369 return (vm_radix_lookup(&object->rtree, pindex));
1373 * vm_page_find_least:
1375 * Returns the page associated with the object with least pindex
1376 * greater than or equal to the parameter pindex, or NULL.
1378 * The object must be locked.
1381 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1385 VM_OBJECT_ASSERT_LOCKED(object);
1386 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1387 m = vm_radix_lookup_ge(&object->rtree, pindex);
1392 * Returns the given page's successor (by pindex) within the object if it is
1393 * resident; if none is found, NULL is returned.
1395 * The object must be locked.
1398 vm_page_next(vm_page_t m)
1402 VM_OBJECT_ASSERT_LOCKED(m->object);
1403 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1404 MPASS(next->object == m->object);
1405 if (next->pindex != m->pindex + 1)
1412 * Returns the given page's predecessor (by pindex) within the object if it is
1413 * resident; if none is found, NULL is returned.
1415 * The object must be locked.
1418 vm_page_prev(vm_page_t m)
1422 VM_OBJECT_ASSERT_LOCKED(m->object);
1423 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1424 MPASS(prev->object == m->object);
1425 if (prev->pindex != m->pindex - 1)
1432 * Uses the page mnew as a replacement for an existing page at index
1433 * pindex which must be already present in the object.
1435 * The existing page must not be on a paging queue.
1438 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1442 VM_OBJECT_ASSERT_WLOCKED(object);
1443 KASSERT(mnew->object == NULL,
1444 ("vm_page_replace: page already in object"));
1447 * This function mostly follows vm_page_insert() and
1448 * vm_page_remove() without the radix, object count and vnode
1449 * dance. Double check such functions for more comments.
1452 mnew->object = object;
1453 mnew->pindex = pindex;
1454 mold = vm_radix_replace(&object->rtree, mnew);
1455 KASSERT(mold->queue == PQ_NONE,
1456 ("vm_page_replace: mold is on a paging queue"));
1458 /* Keep the resident page list in sorted order. */
1459 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1460 TAILQ_REMOVE(&object->memq, mold, listq);
1462 mold->object = NULL;
1463 vm_page_xunbusy_maybelocked(mold);
1466 * The object's resident_page_count does not change because we have
1467 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1469 if (pmap_page_is_write_mapped(mnew))
1470 vm_object_set_writeable_dirty(object);
1477 * Move the given memory entry from its
1478 * current object to the specified target object/offset.
1480 * Note: swap associated with the page must be invalidated by the move. We
1481 * have to do this for several reasons: (1) we aren't freeing the
1482 * page, (2) we are dirtying the page, (3) the VM system is probably
1483 * moving the page from object A to B, and will then later move
1484 * the backing store from A to B and we can't have a conflict.
1486 * Note: we *always* dirty the page. It is necessary both for the
1487 * fact that we moved it, and because we may be invalidating
1490 * The objects must be locked.
1493 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1498 VM_OBJECT_ASSERT_WLOCKED(new_object);
1500 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1501 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1502 ("vm_page_rename: pindex already renamed"));
1505 * Create a custom version of vm_page_insert() which does not depend
1506 * by m_prev and can cheat on the implementation aspects of the
1510 m->pindex = new_pindex;
1511 if (vm_radix_insert(&new_object->rtree, m)) {
1517 * The operation cannot fail anymore. The removal must happen before
1518 * the listq iterator is tainted.
1524 /* Return back to the new pindex to complete vm_page_insert(). */
1525 m->pindex = new_pindex;
1526 m->object = new_object;
1528 vm_page_insert_radixdone(m, new_object, mpred);
1536 * Allocate and return a page that is associated with the specified
1537 * object and offset pair. By default, this page is exclusive busied.
1539 * The caller must always specify an allocation class.
1541 * allocation classes:
1542 * VM_ALLOC_NORMAL normal process request
1543 * VM_ALLOC_SYSTEM system *really* needs a page
1544 * VM_ALLOC_INTERRUPT interrupt time request
1546 * optional allocation flags:
1547 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1548 * intends to allocate
1549 * VM_ALLOC_NOBUSY do not exclusive busy the page
1550 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1551 * VM_ALLOC_NOOBJ page is not associated with an object and
1552 * should not be exclusive busy
1553 * VM_ALLOC_SBUSY shared busy the allocated page
1554 * VM_ALLOC_WIRED wire the allocated page
1555 * VM_ALLOC_ZERO prefer a zeroed page
1557 * This routine may not sleep.
1560 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1563 int flags, req_class;
1565 mpred = NULL; /* XXX: pacify gcc */
1566 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1567 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1568 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1569 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1570 ("vm_page_alloc: inconsistent object(%p)/req(%x)", object, req));
1572 VM_OBJECT_ASSERT_WLOCKED(object);
1574 if (__predict_false((req & VM_ALLOC_IFCACHED) != 0))
1577 req_class = req & VM_ALLOC_CLASS_MASK;
1580 * The page daemon is allowed to dig deeper into the free page list.
1582 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1583 req_class = VM_ALLOC_SYSTEM;
1585 if (object != NULL) {
1586 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1587 KASSERT(mpred == NULL || mpred->pindex != pindex,
1588 ("vm_page_alloc: pindex already allocated"));
1592 * Allocate a page if the number of free pages exceeds the minimum
1593 * for the request class.
1595 mtx_lock(&vm_page_queue_free_mtx);
1596 if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
1597 (req_class == VM_ALLOC_SYSTEM &&
1598 vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
1599 (req_class == VM_ALLOC_INTERRUPT &&
1600 vm_cnt.v_free_count > 0)) {
1602 * Can we allocate the page from a reservation?
1604 #if VM_NRESERVLEVEL > 0
1605 if (object == NULL || (object->flags & (OBJ_COLORED |
1606 OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1607 vm_reserv_alloc_page(object, pindex, mpred)) == NULL)
1611 * If not, allocate it from the free page queues.
1613 m = vm_phys_alloc_pages(object != NULL ?
1614 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1615 #if VM_NRESERVLEVEL > 0
1616 if (m == NULL && vm_reserv_reclaim_inactive()) {
1617 m = vm_phys_alloc_pages(object != NULL ?
1618 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1625 * Not allocatable, give up.
1627 mtx_unlock(&vm_page_queue_free_mtx);
1628 atomic_add_int(&vm_pageout_deficit,
1629 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1630 pagedaemon_wakeup();
1635 * At this point we had better have found a good page.
1637 KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1638 vm_phys_freecnt_adj(m, -1);
1639 if ((m->flags & PG_ZERO) != 0)
1640 vm_page_zero_count--;
1641 mtx_unlock(&vm_page_queue_free_mtx);
1642 vm_page_alloc_check(m);
1645 * Initialize the page. Only the PG_ZERO flag is inherited.
1648 if ((req & VM_ALLOC_ZERO) != 0)
1651 if ((req & VM_ALLOC_NODUMP) != 0)
1655 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1657 m->busy_lock = VPB_UNBUSIED;
1658 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1659 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1660 if ((req & VM_ALLOC_SBUSY) != 0)
1661 m->busy_lock = VPB_SHARERS_WORD(1);
1662 if (req & VM_ALLOC_WIRED) {
1664 * The page lock is not required for wiring a page until that
1665 * page is inserted into the object.
1667 atomic_add_int(&vm_cnt.v_wire_count, 1);
1672 if (object != NULL) {
1673 if (vm_page_insert_after(m, object, pindex, mpred)) {
1674 pagedaemon_wakeup();
1675 if (req & VM_ALLOC_WIRED) {
1676 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1679 KASSERT(m->object == NULL, ("page %p has object", m));
1680 m->oflags = VPO_UNMANAGED;
1681 m->busy_lock = VPB_UNBUSIED;
1682 /* Don't change PG_ZERO. */
1683 vm_page_free_toq(m);
1687 /* Ignore device objects; the pager sets "memattr" for them. */
1688 if (object->memattr != VM_MEMATTR_DEFAULT &&
1689 (object->flags & OBJ_FICTITIOUS) == 0)
1690 pmap_page_set_memattr(m, object->memattr);
1695 * Don't wakeup too often - wakeup the pageout daemon when
1696 * we would be nearly out of memory.
1698 if (vm_paging_needed())
1699 pagedaemon_wakeup();
1705 * vm_page_alloc_contig:
1707 * Allocate a contiguous set of physical pages of the given size "npages"
1708 * from the free lists. All of the physical pages must be at or above
1709 * the given physical address "low" and below the given physical address
1710 * "high". The given value "alignment" determines the alignment of the
1711 * first physical page in the set. If the given value "boundary" is
1712 * non-zero, then the set of physical pages cannot cross any physical
1713 * address boundary that is a multiple of that value. Both "alignment"
1714 * and "boundary" must be a power of two.
1716 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1717 * then the memory attribute setting for the physical pages is configured
1718 * to the object's memory attribute setting. Otherwise, the memory
1719 * attribute setting for the physical pages is configured to "memattr",
1720 * overriding the object's memory attribute setting. However, if the
1721 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1722 * memory attribute setting for the physical pages cannot be configured
1723 * to VM_MEMATTR_DEFAULT.
1725 * The specified object may not contain fictitious pages.
1727 * The caller must always specify an allocation class.
1729 * allocation classes:
1730 * VM_ALLOC_NORMAL normal process request
1731 * VM_ALLOC_SYSTEM system *really* needs a page
1732 * VM_ALLOC_INTERRUPT interrupt time request
1734 * optional allocation flags:
1735 * VM_ALLOC_NOBUSY do not exclusive busy the page
1736 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1737 * VM_ALLOC_NOOBJ page is not associated with an object and
1738 * should not be exclusive busy
1739 * VM_ALLOC_SBUSY shared busy the allocated page
1740 * VM_ALLOC_WIRED wire the allocated page
1741 * VM_ALLOC_ZERO prefer a zeroed page
1743 * This routine may not sleep.
1746 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1747 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1748 vm_paddr_t boundary, vm_memattr_t memattr)
1750 vm_page_t m, m_ret, mpred;
1751 u_int busy_lock, flags, oflags;
1754 mpred = NULL; /* XXX: pacify gcc */
1755 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1756 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1757 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1758 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1759 ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
1761 if (object != NULL) {
1762 VM_OBJECT_ASSERT_WLOCKED(object);
1763 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
1764 ("vm_page_alloc_contig: object %p has fictitious pages",
1767 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1768 req_class = req & VM_ALLOC_CLASS_MASK;
1771 * The page daemon is allowed to dig deeper into the free page list.
1773 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1774 req_class = VM_ALLOC_SYSTEM;
1776 if (object != NULL) {
1777 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1778 KASSERT(mpred == NULL || mpred->pindex != pindex,
1779 ("vm_page_alloc_contig: pindex already allocated"));
1783 * Can we allocate the pages without the number of free pages falling
1784 * below the lower bound for the allocation class?
1786 mtx_lock(&vm_page_queue_free_mtx);
1787 if (vm_cnt.v_free_count >= npages + vm_cnt.v_free_reserved ||
1788 (req_class == VM_ALLOC_SYSTEM &&
1789 vm_cnt.v_free_count >= npages + vm_cnt.v_interrupt_free_min) ||
1790 (req_class == VM_ALLOC_INTERRUPT &&
1791 vm_cnt.v_free_count >= npages)) {
1793 * Can we allocate the pages from a reservation?
1795 #if VM_NRESERVLEVEL > 0
1797 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1798 (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1799 low, high, alignment, boundary, mpred)) == NULL)
1802 * If not, allocate them from the free page queues.
1804 m_ret = vm_phys_alloc_contig(npages, low, high,
1805 alignment, boundary);
1807 mtx_unlock(&vm_page_queue_free_mtx);
1808 atomic_add_int(&vm_pageout_deficit, npages);
1809 pagedaemon_wakeup();
1812 if (m_ret != NULL) {
1813 vm_phys_freecnt_adj(m_ret, -npages);
1814 for (m = m_ret; m < &m_ret[npages]; m++)
1815 if ((m->flags & PG_ZERO) != 0)
1816 vm_page_zero_count--;
1818 #if VM_NRESERVLEVEL > 0
1819 if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1824 mtx_unlock(&vm_page_queue_free_mtx);
1827 for (m = m_ret; m < &m_ret[npages]; m++)
1828 vm_page_alloc_check(m);
1831 * Initialize the pages. Only the PG_ZERO flag is inherited.
1834 if ((req & VM_ALLOC_ZERO) != 0)
1836 if ((req & VM_ALLOC_NODUMP) != 0)
1838 oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1840 busy_lock = VPB_UNBUSIED;
1841 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1842 busy_lock = VPB_SINGLE_EXCLUSIVER;
1843 if ((req & VM_ALLOC_SBUSY) != 0)
1844 busy_lock = VPB_SHARERS_WORD(1);
1845 if ((req & VM_ALLOC_WIRED) != 0)
1846 atomic_add_int(&vm_cnt.v_wire_count, npages);
1847 if (object != NULL) {
1848 if (object->memattr != VM_MEMATTR_DEFAULT &&
1849 memattr == VM_MEMATTR_DEFAULT)
1850 memattr = object->memattr;
1852 for (m = m_ret; m < &m_ret[npages]; m++) {
1854 m->flags = (m->flags | PG_NODUMP) & flags;
1855 m->busy_lock = busy_lock;
1856 if ((req & VM_ALLOC_WIRED) != 0)
1860 if (object != NULL) {
1861 if (vm_page_insert_after(m, object, pindex, mpred)) {
1862 pagedaemon_wakeup();
1863 if ((req & VM_ALLOC_WIRED) != 0)
1864 atomic_subtract_int(
1865 &vm_cnt.v_wire_count, npages);
1866 KASSERT(m->object == NULL,
1867 ("page %p has object", m));
1869 for (m = m_ret; m < &m_ret[npages]; m++) {
1871 (req & VM_ALLOC_WIRED) != 0)
1873 m->oflags = VPO_UNMANAGED;
1874 m->busy_lock = VPB_UNBUSIED;
1875 /* Don't change PG_ZERO. */
1876 vm_page_free_toq(m);
1883 if (memattr != VM_MEMATTR_DEFAULT)
1884 pmap_page_set_memattr(m, memattr);
1887 if (vm_paging_needed())
1888 pagedaemon_wakeup();
1893 * Check a page that has been freshly dequeued from a freelist.
1896 vm_page_alloc_check(vm_page_t m)
1899 KASSERT(m->object == NULL, ("page %p has object", m));
1900 KASSERT(m->queue == PQ_NONE,
1901 ("page %p has unexpected queue %d", m, m->queue));
1902 KASSERT(m->wire_count == 0, ("page %p is wired", m));
1903 KASSERT(m->hold_count == 0, ("page %p is held", m));
1904 KASSERT(!vm_page_busied(m), ("page %p is busy", m));
1905 KASSERT(m->dirty == 0, ("page %p is dirty", m));
1906 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1907 ("page %p has unexpected memattr %d",
1908 m, pmap_page_get_memattr(m)));
1909 KASSERT(m->valid == 0, ("free page %p is valid", m));
1913 * vm_page_alloc_freelist:
1915 * Allocate a physical page from the specified free page list.
1917 * The caller must always specify an allocation class.
1919 * allocation classes:
1920 * VM_ALLOC_NORMAL normal process request
1921 * VM_ALLOC_SYSTEM system *really* needs a page
1922 * VM_ALLOC_INTERRUPT interrupt time request
1924 * optional allocation flags:
1925 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1926 * intends to allocate
1927 * VM_ALLOC_WIRED wire the allocated page
1928 * VM_ALLOC_ZERO prefer a zeroed page
1930 * This routine may not sleep.
1933 vm_page_alloc_freelist(int flind, int req)
1939 req_class = req & VM_ALLOC_CLASS_MASK;
1942 * The page daemon is allowed to dig deeper into the free page list.
1944 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1945 req_class = VM_ALLOC_SYSTEM;
1948 * Do not allocate reserved pages unless the req has asked for it.
1950 mtx_lock(&vm_page_queue_free_mtx);
1951 if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
1952 (req_class == VM_ALLOC_SYSTEM &&
1953 vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
1954 (req_class == VM_ALLOC_INTERRUPT &&
1955 vm_cnt.v_free_count > 0))
1956 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
1958 mtx_unlock(&vm_page_queue_free_mtx);
1959 atomic_add_int(&vm_pageout_deficit,
1960 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1961 pagedaemon_wakeup();
1965 mtx_unlock(&vm_page_queue_free_mtx);
1968 vm_phys_freecnt_adj(m, -1);
1969 if ((m->flags & PG_ZERO) != 0)
1970 vm_page_zero_count--;
1971 mtx_unlock(&vm_page_queue_free_mtx);
1972 vm_page_alloc_check(m);
1975 * Initialize the page. Only the PG_ZERO flag is inherited.
1979 if ((req & VM_ALLOC_ZERO) != 0)
1982 if ((req & VM_ALLOC_WIRED) != 0) {
1984 * The page lock is not required for wiring a page that does
1985 * not belong to an object.
1987 atomic_add_int(&vm_cnt.v_wire_count, 1);
1990 /* Unmanaged pages don't use "act_count". */
1991 m->oflags = VPO_UNMANAGED;
1992 if (vm_paging_needed())
1993 pagedaemon_wakeup();
1997 #define VPSC_ANY 0 /* No restrictions. */
1998 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
1999 #define VPSC_NOSUPER 2 /* Skip superpages. */
2002 * vm_page_scan_contig:
2004 * Scan vm_page_array[] between the specified entries "m_start" and
2005 * "m_end" for a run of contiguous physical pages that satisfy the
2006 * specified conditions, and return the lowest page in the run. The
2007 * specified "alignment" determines the alignment of the lowest physical
2008 * page in the run. If the specified "boundary" is non-zero, then the
2009 * run of physical pages cannot span a physical address that is a
2010 * multiple of "boundary".
2012 * "m_end" is never dereferenced, so it need not point to a vm_page
2013 * structure within vm_page_array[].
2015 * "npages" must be greater than zero. "m_start" and "m_end" must not
2016 * span a hole (or discontiguity) in the physical address space. Both
2017 * "alignment" and "boundary" must be a power of two.
2020 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2021 u_long alignment, vm_paddr_t boundary, int options)
2027 #if VM_NRESERVLEVEL > 0
2030 int m_inc, order, run_ext, run_len;
2032 KASSERT(npages > 0, ("npages is 0"));
2033 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2034 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2038 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2039 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2040 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2043 * If the current page would be the start of a run, check its
2044 * physical address against the end, alignment, and boundary
2045 * conditions. If it doesn't satisfy these conditions, either
2046 * terminate the scan or advance to the next page that
2047 * satisfies the failed condition.
2050 KASSERT(m_run == NULL, ("m_run != NULL"));
2051 if (m + npages > m_end)
2053 pa = VM_PAGE_TO_PHYS(m);
2054 if ((pa & (alignment - 1)) != 0) {
2055 m_inc = atop(roundup2(pa, alignment) - pa);
2058 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2060 m_inc = atop(roundup2(pa, boundary) - pa);
2064 KASSERT(m_run != NULL, ("m_run == NULL"));
2066 vm_page_change_lock(m, &m_mtx);
2069 if (m->wire_count != 0 || m->hold_count != 0)
2071 #if VM_NRESERVLEVEL > 0
2072 else if ((level = vm_reserv_level(m)) >= 0 &&
2073 (options & VPSC_NORESERV) != 0) {
2075 /* Advance to the end of the reservation. */
2076 pa = VM_PAGE_TO_PHYS(m);
2077 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2081 else if ((object = m->object) != NULL) {
2083 * The page is considered eligible for relocation if
2084 * and only if it could be laundered or reclaimed by
2087 if (!VM_OBJECT_TRYRLOCK(object)) {
2089 VM_OBJECT_RLOCK(object);
2091 if (m->object != object) {
2093 * The page may have been freed.
2095 VM_OBJECT_RUNLOCK(object);
2097 } else if (m->wire_count != 0 ||
2098 m->hold_count != 0) {
2103 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2104 ("page %p is PG_UNHOLDFREE", m));
2105 /* Don't care: PG_NODUMP, PG_ZERO. */
2106 if (object->type != OBJT_DEFAULT &&
2107 object->type != OBJT_SWAP &&
2108 object->type != OBJT_VNODE) {
2110 #if VM_NRESERVLEVEL > 0
2111 } else if ((options & VPSC_NOSUPER) != 0 &&
2112 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2114 /* Advance to the end of the superpage. */
2115 pa = VM_PAGE_TO_PHYS(m);
2116 m_inc = atop(roundup2(pa + 1,
2117 vm_reserv_size(level)) - pa);
2119 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2120 m->queue != PQ_NONE && !vm_page_busied(m)) {
2122 * The page is allocated but eligible for
2123 * relocation. Extend the current run by one
2126 KASSERT(pmap_page_get_memattr(m) ==
2128 ("page %p has an unexpected memattr", m));
2129 KASSERT((m->oflags & (VPO_SWAPINPROG |
2130 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2131 ("page %p has unexpected oflags", m));
2132 /* Don't care: VPO_NOSYNC. */
2137 VM_OBJECT_RUNLOCK(object);
2138 #if VM_NRESERVLEVEL > 0
2139 } else if (level >= 0) {
2141 * The page is reserved but not yet allocated. In
2142 * other words, it is still free. Extend the current
2147 } else if ((order = m->order) < VM_NFREEORDER) {
2149 * The page is enqueued in the physical memory
2150 * allocator's free page queues. Moreover, it is the
2151 * first page in a power-of-two-sized run of
2152 * contiguous free pages. Add these pages to the end
2153 * of the current run, and jump ahead.
2155 run_ext = 1 << order;
2159 * Skip the page for one of the following reasons: (1)
2160 * It is enqueued in the physical memory allocator's
2161 * free page queues. However, it is not the first
2162 * page in a run of contiguous free pages. (This case
2163 * rarely occurs because the scan is performed in
2164 * ascending order.) (2) It is not reserved, and it is
2165 * transitioning from free to allocated. (Conversely,
2166 * the transition from allocated to free for managed
2167 * pages is blocked by the page lock.) (3) It is
2168 * allocated but not contained by an object and not
2169 * wired, e.g., allocated by Xen's balloon driver.
2175 * Extend or reset the current run of pages.
2190 if (run_len >= npages)
2196 * vm_page_reclaim_run:
2198 * Try to relocate each of the allocated virtual pages within the
2199 * specified run of physical pages to a new physical address. Free the
2200 * physical pages underlying the relocated virtual pages. A virtual page
2201 * is relocatable if and only if it could be laundered or reclaimed by
2202 * the page daemon. Whenever possible, a virtual page is relocated to a
2203 * physical address above "high".
2205 * Returns 0 if every physical page within the run was already free or
2206 * just freed by a successful relocation. Otherwise, returns a non-zero
2207 * value indicating why the last attempt to relocate a virtual page was
2210 * "req_class" must be an allocation class.
2213 vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
2217 struct spglist free;
2220 vm_page_t m, m_end, m_new;
2221 int error, order, req;
2223 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2224 ("req_class is not an allocation class"));
2228 m_end = m_run + npages;
2230 for (; error == 0 && m < m_end; m++) {
2231 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2232 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2235 * Avoid releasing and reacquiring the same page lock.
2237 vm_page_change_lock(m, &m_mtx);
2239 if (m->wire_count != 0 || m->hold_count != 0)
2241 else if ((object = m->object) != NULL) {
2243 * The page is relocated if and only if it could be
2244 * laundered or reclaimed by the page daemon.
2246 if (!VM_OBJECT_TRYWLOCK(object)) {
2248 VM_OBJECT_WLOCK(object);
2250 if (m->object != object) {
2252 * The page may have been freed.
2254 VM_OBJECT_WUNLOCK(object);
2256 } else if (m->wire_count != 0 ||
2257 m->hold_count != 0) {
2262 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2263 ("page %p is PG_UNHOLDFREE", m));
2264 /* Don't care: PG_NODUMP, PG_ZERO. */
2265 if (object->type != OBJT_DEFAULT &&
2266 object->type != OBJT_SWAP &&
2267 object->type != OBJT_VNODE)
2269 else if (object->memattr != VM_MEMATTR_DEFAULT)
2271 else if (m->queue != PQ_NONE && !vm_page_busied(m)) {
2272 KASSERT(pmap_page_get_memattr(m) ==
2274 ("page %p has an unexpected memattr", m));
2275 KASSERT((m->oflags & (VPO_SWAPINPROG |
2276 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2277 ("page %p has unexpected oflags", m));
2278 /* Don't care: VPO_NOSYNC. */
2279 if (m->valid != 0) {
2281 * First, try to allocate a new page
2282 * that is above "high". Failing
2283 * that, try to allocate a new page
2284 * that is below "m_run". Allocate
2285 * the new page between the end of
2286 * "m_run" and "high" only as a last
2289 req = req_class | VM_ALLOC_NOOBJ;
2290 if ((m->flags & PG_NODUMP) != 0)
2291 req |= VM_ALLOC_NODUMP;
2292 if (trunc_page(high) !=
2293 ~(vm_paddr_t)PAGE_MASK) {
2294 m_new = vm_page_alloc_contig(
2299 VM_MEMATTR_DEFAULT);
2302 if (m_new == NULL) {
2303 pa = VM_PAGE_TO_PHYS(m_run);
2304 m_new = vm_page_alloc_contig(
2306 0, pa - 1, PAGE_SIZE, 0,
2307 VM_MEMATTR_DEFAULT);
2309 if (m_new == NULL) {
2311 m_new = vm_page_alloc_contig(
2313 pa, high, PAGE_SIZE, 0,
2314 VM_MEMATTR_DEFAULT);
2316 if (m_new == NULL) {
2320 KASSERT(m_new->wire_count == 0,
2321 ("page %p is wired", m));
2324 * Replace "m" with the new page. For
2325 * vm_page_replace(), "m" must be busy
2326 * and dequeued. Finally, change "m"
2327 * as if vm_page_free() was called.
2329 if (object->ref_count != 0)
2331 m_new->aflags = m->aflags;
2332 KASSERT(m_new->oflags == VPO_UNMANAGED,
2333 ("page %p is managed", m));
2334 m_new->oflags = m->oflags & VPO_NOSYNC;
2335 pmap_copy_page(m, m_new);
2336 m_new->valid = m->valid;
2337 m_new->dirty = m->dirty;
2338 m->flags &= ~PG_ZERO;
2341 vm_page_replace_checked(m_new, object,
2347 * The new page must be deactivated
2348 * before the object is unlocked.
2350 vm_page_change_lock(m_new, &m_mtx);
2351 vm_page_deactivate(m_new);
2353 m->flags &= ~PG_ZERO;
2356 KASSERT(m->dirty == 0,
2357 ("page %p is dirty", m));
2359 SLIST_INSERT_HEAD(&free, m, plinks.s.ss);
2363 VM_OBJECT_WUNLOCK(object);
2365 mtx_lock(&vm_page_queue_free_mtx);
2367 if (order < VM_NFREEORDER) {
2369 * The page is enqueued in the physical memory
2370 * allocator's free page queues. Moreover, it
2371 * is the first page in a power-of-two-sized
2372 * run of contiguous free pages. Jump ahead
2373 * to the last page within that run, and
2374 * continue from there.
2376 m += (1 << order) - 1;
2378 #if VM_NRESERVLEVEL > 0
2379 else if (vm_reserv_is_page_free(m))
2382 mtx_unlock(&vm_page_queue_free_mtx);
2383 if (order == VM_NFREEORDER)
2389 if ((m = SLIST_FIRST(&free)) != NULL) {
2390 mtx_lock(&vm_page_queue_free_mtx);
2392 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2393 vm_page_free_phys(m);
2394 } while ((m = SLIST_FIRST(&free)) != NULL);
2395 vm_page_zero_idle_wakeup();
2396 vm_page_free_wakeup();
2397 mtx_unlock(&vm_page_queue_free_mtx);
2404 CTASSERT(powerof2(NRUNS));
2406 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2408 #define MIN_RECLAIM 8
2411 * vm_page_reclaim_contig:
2413 * Reclaim allocated, contiguous physical memory satisfying the specified
2414 * conditions by relocating the virtual pages using that physical memory.
2415 * Returns true if reclamation is successful and false otherwise. Since
2416 * relocation requires the allocation of physical pages, reclamation may
2417 * fail due to a shortage of free pages. When reclamation fails, callers
2418 * are expected to perform VM_WAIT before retrying a failed allocation
2419 * operation, e.g., vm_page_alloc_contig().
2421 * The caller must always specify an allocation class through "req".
2423 * allocation classes:
2424 * VM_ALLOC_NORMAL normal process request
2425 * VM_ALLOC_SYSTEM system *really* needs a page
2426 * VM_ALLOC_INTERRUPT interrupt time request
2428 * The optional allocation flags are ignored.
2430 * "npages" must be greater than zero. Both "alignment" and "boundary"
2431 * must be a power of two.
2434 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2435 u_long alignment, vm_paddr_t boundary)
2437 vm_paddr_t curr_low;
2438 vm_page_t m_run, m_runs[NRUNS];
2439 u_long count, reclaimed;
2440 int error, i, options, req_class;
2442 KASSERT(npages > 0, ("npages is 0"));
2443 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2444 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2445 req_class = req & VM_ALLOC_CLASS_MASK;
2448 * The page daemon is allowed to dig deeper into the free page list.
2450 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2451 req_class = VM_ALLOC_SYSTEM;
2454 * Return if the number of free pages cannot satisfy the requested
2457 count = vm_cnt.v_free_count;
2458 if (count < npages + vm_cnt.v_free_reserved || (count < npages +
2459 vm_cnt.v_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2460 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2464 * Scan up to three times, relaxing the restrictions ("options") on
2465 * the reclamation of reservations and superpages each time.
2467 for (options = VPSC_NORESERV;;) {
2469 * Find the highest runs that satisfy the given constraints
2470 * and restrictions, and record them in "m_runs".
2475 m_run = vm_phys_scan_contig(npages, curr_low, high,
2476 alignment, boundary, options);
2479 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2480 m_runs[RUN_INDEX(count)] = m_run;
2485 * Reclaim the highest runs in LIFO (descending) order until
2486 * the number of reclaimed pages, "reclaimed", is at least
2487 * MIN_RECLAIM. Reset "reclaimed" each time because each
2488 * reclamation is idempotent, and runs will (likely) recur
2489 * from one scan to the next as restrictions are relaxed.
2492 for (i = 0; count > 0 && i < NRUNS; i++) {
2494 m_run = m_runs[RUN_INDEX(count)];
2495 error = vm_page_reclaim_run(req_class, npages, m_run,
2498 reclaimed += npages;
2499 if (reclaimed >= MIN_RECLAIM)
2505 * Either relax the restrictions on the next scan or return if
2506 * the last scan had no restrictions.
2508 if (options == VPSC_NORESERV)
2509 options = VPSC_NOSUPER;
2510 else if (options == VPSC_NOSUPER)
2512 else if (options == VPSC_ANY)
2513 return (reclaimed != 0);
2518 * vm_wait: (also see VM_WAIT macro)
2520 * Sleep until free pages are available for allocation.
2521 * - Called in various places before memory allocations.
2527 mtx_lock(&vm_page_queue_free_mtx);
2528 if (curproc == pageproc) {
2529 vm_pageout_pages_needed = 1;
2530 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
2531 PDROP | PSWP, "VMWait", 0);
2533 if (__predict_false(pageproc == NULL))
2534 panic("vm_wait in early boot");
2535 if (!vm_pageout_wanted) {
2536 vm_pageout_wanted = true;
2537 wakeup(&vm_pageout_wanted);
2539 vm_pages_needed = true;
2540 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
2546 * vm_waitpfault: (also see VM_WAITPFAULT macro)
2548 * Sleep until free pages are available for allocation.
2549 * - Called only in vm_fault so that processes page faulting
2550 * can be easily tracked.
2551 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2552 * processes will be able to grab memory first. Do not change
2553 * this balance without careful testing first.
2559 mtx_lock(&vm_page_queue_free_mtx);
2560 if (!vm_pageout_wanted) {
2561 vm_pageout_wanted = true;
2562 wakeup(&vm_pageout_wanted);
2564 vm_pages_needed = true;
2565 msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
2569 struct vm_pagequeue *
2570 vm_page_pagequeue(vm_page_t m)
2573 if (vm_page_in_laundry(m))
2574 return (&vm_dom[0].vmd_pagequeues[m->queue]);
2576 return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2582 * Remove the given page from its current page queue.
2584 * The page must be locked.
2587 vm_page_dequeue(vm_page_t m)
2589 struct vm_pagequeue *pq;
2591 vm_page_assert_locked(m);
2592 KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
2594 pq = vm_page_pagequeue(m);
2595 vm_pagequeue_lock(pq);
2597 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2598 vm_pagequeue_cnt_dec(pq);
2599 vm_pagequeue_unlock(pq);
2603 * vm_page_dequeue_locked:
2605 * Remove the given page from its current page queue.
2607 * The page and page queue must be locked.
2610 vm_page_dequeue_locked(vm_page_t m)
2612 struct vm_pagequeue *pq;
2614 vm_page_lock_assert(m, MA_OWNED);
2615 pq = vm_page_pagequeue(m);
2616 vm_pagequeue_assert_locked(pq);
2618 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2619 vm_pagequeue_cnt_dec(pq);
2625 * Add the given page to the specified page queue.
2627 * The page must be locked.
2630 vm_page_enqueue(uint8_t queue, vm_page_t m)
2632 struct vm_pagequeue *pq;
2634 vm_page_lock_assert(m, MA_OWNED);
2635 KASSERT(queue < PQ_COUNT,
2636 ("vm_page_enqueue: invalid queue %u request for page %p",
2638 if (queue == PQ_LAUNDRY)
2639 pq = &vm_dom[0].vmd_pagequeues[queue];
2641 pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2642 vm_pagequeue_lock(pq);
2644 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2645 vm_pagequeue_cnt_inc(pq);
2646 vm_pagequeue_unlock(pq);
2652 * Move the given page to the tail of its current page queue.
2654 * The page must be locked.
2657 vm_page_requeue(vm_page_t m)
2659 struct vm_pagequeue *pq;
2661 vm_page_lock_assert(m, MA_OWNED);
2662 KASSERT(m->queue != PQ_NONE,
2663 ("vm_page_requeue: page %p is not queued", m));
2664 pq = vm_page_pagequeue(m);
2665 vm_pagequeue_lock(pq);
2666 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2667 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2668 vm_pagequeue_unlock(pq);
2672 * vm_page_requeue_locked:
2674 * Move the given page to the tail of its current page queue.
2676 * The page queue must be locked.
2679 vm_page_requeue_locked(vm_page_t m)
2681 struct vm_pagequeue *pq;
2683 KASSERT(m->queue != PQ_NONE,
2684 ("vm_page_requeue_locked: page %p is not queued", m));
2685 pq = vm_page_pagequeue(m);
2686 vm_pagequeue_assert_locked(pq);
2687 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2688 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2694 * Put the specified page on the active list (if appropriate).
2695 * Ensure that act_count is at least ACT_INIT but do not otherwise
2698 * The page must be locked.
2701 vm_page_activate(vm_page_t m)
2705 vm_page_lock_assert(m, MA_OWNED);
2706 if ((queue = m->queue) != PQ_ACTIVE) {
2707 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2708 if (m->act_count < ACT_INIT)
2709 m->act_count = ACT_INIT;
2710 if (queue != PQ_NONE)
2712 vm_page_enqueue(PQ_ACTIVE, m);
2714 KASSERT(queue == PQ_NONE,
2715 ("vm_page_activate: wired page %p is queued", m));
2717 if (m->act_count < ACT_INIT)
2718 m->act_count = ACT_INIT;
2723 * vm_page_free_wakeup:
2725 * Helper routine for vm_page_free_toq(). This routine is called
2726 * when a page is added to the free queues.
2728 * The page queues must be locked.
2731 vm_page_free_wakeup(void)
2734 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2736 * if pageout daemon needs pages, then tell it that there are
2739 if (vm_pageout_pages_needed &&
2740 vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
2741 wakeup(&vm_pageout_pages_needed);
2742 vm_pageout_pages_needed = 0;
2745 * wakeup processes that are waiting on memory if we hit a
2746 * high water mark. And wakeup scheduler process if we have
2747 * lots of memory. this process will swapin processes.
2749 if (vm_pages_needed && !vm_page_count_min()) {
2750 vm_pages_needed = false;
2751 wakeup(&vm_cnt.v_free_count);
2756 * vm_page_free_prep:
2758 * Prepares the given page to be put on the free list,
2759 * disassociating it from any VM object. The caller may return
2760 * the page to the free list only if this function returns true.
2762 * The object must be locked. The page must be locked if it is
2763 * managed. For a queued managed page, the pagequeue_locked
2764 * argument specifies whether the page queue is already locked.
2767 vm_page_free_prep(vm_page_t m, bool pagequeue_locked)
2770 if ((m->oflags & VPO_UNMANAGED) == 0) {
2771 vm_page_lock_assert(m, MA_OWNED);
2772 KASSERT(!pmap_page_is_mapped(m),
2773 ("vm_page_free_toq: freeing mapped page %p", m));
2775 KASSERT(m->queue == PQ_NONE,
2776 ("vm_page_free_toq: unmanaged page %p is queued", m));
2777 PCPU_INC(cnt.v_tfree);
2779 if (vm_page_sbusied(m))
2780 panic("vm_page_free: freeing busy page %p", m);
2783 * Unqueue, then remove page. Note that we cannot destroy
2784 * the page here because we do not want to call the pager's
2785 * callback routine until after we've put the page on the
2786 * appropriate free queue.
2788 if (m->queue != PQ_NONE) {
2789 if (pagequeue_locked)
2790 vm_page_dequeue_locked(m);
2797 * If fictitious remove object association and
2798 * return, otherwise delay object association removal.
2800 if ((m->flags & PG_FICTITIOUS) != 0)
2806 if (m->wire_count != 0)
2807 panic("vm_page_free: freeing wired page %p", m);
2808 if (m->hold_count != 0) {
2809 m->flags &= ~PG_ZERO;
2810 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2811 ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
2812 m->flags |= PG_UNHOLDFREE;
2817 * Restore the default memory attribute to the page.
2819 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2820 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2826 * Insert the page into the physical memory allocator's free page
2827 * queues. This is the last step to free a page.
2830 vm_page_free_phys(vm_page_t m)
2833 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2835 vm_phys_freecnt_adj(m, 1);
2836 #if VM_NRESERVLEVEL > 0
2837 if (!vm_reserv_free_page(m))
2839 vm_phys_free_pages(m, 0);
2840 if ((m->flags & PG_ZERO) != 0)
2841 ++vm_page_zero_count;
2843 vm_page_zero_idle_wakeup();
2847 vm_page_free_phys_pglist(struct pglist *tq)
2851 if (TAILQ_EMPTY(tq))
2853 mtx_lock(&vm_page_queue_free_mtx);
2854 TAILQ_FOREACH(m, tq, listq)
2855 vm_page_free_phys(m);
2856 vm_page_free_wakeup();
2857 mtx_unlock(&vm_page_queue_free_mtx);
2863 * Returns the given page to the free list, disassociating it
2864 * from any VM object.
2866 * The object must be locked. The page must be locked if it is
2870 vm_page_free_toq(vm_page_t m)
2873 if (!vm_page_free_prep(m, false))
2875 mtx_lock(&vm_page_queue_free_mtx);
2876 vm_page_free_phys(m);
2877 vm_page_free_wakeup();
2878 mtx_unlock(&vm_page_queue_free_mtx);
2884 * Mark this page as wired down by yet
2885 * another map, removing it from paging queues
2888 * If the page is fictitious, then its wire count must remain one.
2890 * The page must be locked.
2893 vm_page_wire(vm_page_t m)
2897 * Only bump the wire statistics if the page is not already wired,
2898 * and only unqueue the page if it is on some queue (if it is unmanaged
2899 * it is already off the queues).
2901 vm_page_lock_assert(m, MA_OWNED);
2902 if ((m->flags & PG_FICTITIOUS) != 0) {
2903 KASSERT(m->wire_count == 1,
2904 ("vm_page_wire: fictitious page %p's wire count isn't one",
2908 if (m->wire_count == 0) {
2909 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
2910 m->queue == PQ_NONE,
2911 ("vm_page_wire: unmanaged page %p is queued", m));
2913 atomic_add_int(&vm_cnt.v_wire_count, 1);
2916 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
2922 * Release one wiring of the specified page, potentially allowing it to be
2923 * paged out. Returns TRUE if the number of wirings transitions to zero and
2926 * Only managed pages belonging to an object can be paged out. If the number
2927 * of wirings transitions to zero and the page is eligible for page out, then
2928 * the page is added to the specified paging queue (unless PQ_NONE is
2931 * If a page is fictitious, then its wire count must always be one.
2933 * A managed page must be locked.
2936 vm_page_unwire(vm_page_t m, uint8_t queue)
2939 KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
2940 ("vm_page_unwire: invalid queue %u request for page %p",
2942 if ((m->oflags & VPO_UNMANAGED) == 0)
2943 vm_page_assert_locked(m);
2944 if ((m->flags & PG_FICTITIOUS) != 0) {
2945 KASSERT(m->wire_count == 1,
2946 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
2949 if (m->wire_count > 0) {
2951 if (m->wire_count == 0) {
2952 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2953 if ((m->oflags & VPO_UNMANAGED) == 0 &&
2954 m->object != NULL && queue != PQ_NONE)
2955 vm_page_enqueue(queue, m);
2960 panic("vm_page_unwire: page %p's wire count is zero", m);
2964 * Move the specified page to the inactive queue.
2966 * Normally, "noreuse" is FALSE, resulting in LRU ordering of the inactive
2967 * queue. However, setting "noreuse" to TRUE will accelerate the specified
2968 * page's reclamation, but it will not unmap the page from any address space.
2969 * This is implemented by inserting the page near the head of the inactive
2970 * queue, using a marker page to guide FIFO insertion ordering.
2972 * The page must be locked.
2975 _vm_page_deactivate(vm_page_t m, boolean_t noreuse)
2977 struct vm_pagequeue *pq;
2980 vm_page_assert_locked(m);
2983 * Ignore if the page is already inactive, unless it is unlikely to be
2986 if ((queue = m->queue) == PQ_INACTIVE && !noreuse)
2988 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2989 pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
2990 /* Avoid multiple acquisitions of the inactive queue lock. */
2991 if (queue == PQ_INACTIVE) {
2992 vm_pagequeue_lock(pq);
2993 vm_page_dequeue_locked(m);
2995 if (queue != PQ_NONE)
2997 vm_pagequeue_lock(pq);
2999 m->queue = PQ_INACTIVE;
3001 TAILQ_INSERT_BEFORE(&vm_phys_domain(m)->vmd_inacthead,
3004 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3005 vm_pagequeue_cnt_inc(pq);
3006 vm_pagequeue_unlock(pq);
3011 * Move the specified page to the inactive queue.
3013 * The page must be locked.
3016 vm_page_deactivate(vm_page_t m)
3019 _vm_page_deactivate(m, FALSE);
3023 * Move the specified page to the inactive queue with the expectation
3024 * that it is unlikely to be reused.
3026 * The page must be locked.
3029 vm_page_deactivate_noreuse(vm_page_t m)
3032 _vm_page_deactivate(m, TRUE);
3038 * Put a page in the laundry.
3041 vm_page_launder(vm_page_t m)
3045 vm_page_assert_locked(m);
3046 if ((queue = m->queue) != PQ_LAUNDRY) {
3047 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
3048 if (queue != PQ_NONE)
3050 vm_page_enqueue(PQ_LAUNDRY, m);
3052 KASSERT(queue == PQ_NONE,
3053 ("wired page %p is queued", m));
3058 * vm_page_try_to_free()
3060 * Attempt to free the page. If we cannot free it, we do nothing.
3061 * true is returned on success, false on failure.
3064 vm_page_try_to_free(vm_page_t m)
3067 vm_page_assert_locked(m);
3068 if (m->object != NULL)
3069 VM_OBJECT_ASSERT_WLOCKED(m->object);
3070 if (m->dirty != 0 || m->hold_count != 0 || m->wire_count != 0 ||
3071 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
3073 if (m->object != NULL && m->object->ref_count != 0) {
3085 * Apply the specified advice to the given page.
3087 * The object and page must be locked.
3090 vm_page_advise(vm_page_t m, int advice)
3093 vm_page_assert_locked(m);
3094 VM_OBJECT_ASSERT_WLOCKED(m->object);
3095 if (advice == MADV_FREE)
3097 * Mark the page clean. This will allow the page to be freed
3098 * without first paging it out. MADV_FREE pages are often
3099 * quickly reused by malloc(3), so we do not do anything that
3100 * would result in a page fault on a later access.
3103 else if (advice != MADV_DONTNEED) {
3104 if (advice == MADV_WILLNEED)
3105 vm_page_activate(m);
3110 * Clear any references to the page. Otherwise, the page daemon will
3111 * immediately reactivate the page.
3113 vm_page_aflag_clear(m, PGA_REFERENCED);
3115 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3119 * Place clean pages near the head of the inactive queue rather than
3120 * the tail, thus defeating the queue's LRU operation and ensuring that
3121 * the page will be reused quickly. Dirty pages not already in the
3122 * laundry are moved there.
3125 vm_page_deactivate_noreuse(m);
3131 * Grab a page, waiting until we are waken up due to the page
3132 * changing state. We keep on waiting, if the page continues
3133 * to be in the object. If the page doesn't exist, first allocate it
3134 * and then conditionally zero it.
3136 * This routine may sleep.
3138 * The object must be locked on entry. The lock will, however, be released
3139 * and reacquired if the routine sleeps.
3142 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3147 VM_OBJECT_ASSERT_WLOCKED(object);
3148 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3149 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3150 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3152 if ((m = vm_page_lookup(object, pindex)) != NULL) {
3153 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3154 vm_page_xbusied(m) : vm_page_busied(m);
3156 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3159 * Reference the page before unlocking and
3160 * sleeping so that the page daemon is less
3161 * likely to reclaim it.
3163 vm_page_aflag_set(m, PGA_REFERENCED);
3165 VM_OBJECT_WUNLOCK(object);
3166 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
3167 VM_ALLOC_IGN_SBUSY) != 0);
3168 VM_OBJECT_WLOCK(object);
3171 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3177 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3179 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3184 m = vm_page_alloc(object, pindex, allocflags);
3186 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3188 VM_OBJECT_WUNLOCK(object);
3190 VM_OBJECT_WLOCK(object);
3193 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3199 * Return the specified range of pages from the given object. For each
3200 * page offset within the range, if a page already exists within the object
3201 * at that offset and it is busy, then wait for it to change state. If,
3202 * instead, the page doesn't exist, then allocate it.
3204 * The caller must always specify an allocation class.
3206 * allocation classes:
3207 * VM_ALLOC_NORMAL normal process request
3208 * VM_ALLOC_SYSTEM system *really* needs the pages
3210 * The caller must always specify that the pages are to be busied and/or
3213 * optional allocation flags:
3214 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
3215 * VM_ALLOC_NOBUSY do not exclusive busy the page
3216 * VM_ALLOC_NOWAIT do not sleep
3217 * VM_ALLOC_SBUSY set page to sbusy state
3218 * VM_ALLOC_WIRED wire the pages
3219 * VM_ALLOC_ZERO zero and validate any invalid pages
3221 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
3222 * may return a partial prefix of the requested range.
3225 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
3226 vm_page_t *ma, int count)
3232 VM_OBJECT_ASSERT_WLOCKED(object);
3233 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
3234 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
3235 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
3236 (allocflags & VM_ALLOC_WIRED) != 0,
3237 ("vm_page_grab_pages: the pages must be busied or wired"));
3238 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3239 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3240 ("vm_page_grab_pages: VM_ALLOC_SBUSY/IGN_SBUSY mismatch"));
3245 m = vm_page_lookup(object, pindex + i);
3246 for (; i < count; i++) {
3248 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3249 vm_page_xbusied(m) : vm_page_busied(m);
3251 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3254 * Reference the page before unlocking and
3255 * sleeping so that the page daemon is less
3256 * likely to reclaim it.
3258 vm_page_aflag_set(m, PGA_REFERENCED);
3260 VM_OBJECT_WUNLOCK(object);
3261 vm_page_busy_sleep(m, "grbmaw", (allocflags &
3262 VM_ALLOC_IGN_SBUSY) != 0);
3263 VM_OBJECT_WLOCK(object);
3266 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3271 if ((allocflags & (VM_ALLOC_NOBUSY |
3272 VM_ALLOC_SBUSY)) == 0)
3274 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3277 m = vm_page_alloc(object, pindex + i, (allocflags &
3278 ~VM_ALLOC_IGN_SBUSY) | VM_ALLOC_COUNT(count - i));
3280 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3282 VM_OBJECT_WUNLOCK(object);
3284 VM_OBJECT_WLOCK(object);
3288 if (m->valid == 0 && (allocflags & VM_ALLOC_ZERO) != 0) {
3289 if ((m->flags & PG_ZERO) == 0)
3291 m->valid = VM_PAGE_BITS_ALL;
3294 m = vm_page_next(m);
3300 * Mapping function for valid or dirty bits in a page.
3302 * Inputs are required to range within a page.
3305 vm_page_bits(int base, int size)
3311 base + size <= PAGE_SIZE,
3312 ("vm_page_bits: illegal base/size %d/%d", base, size)
3315 if (size == 0) /* handle degenerate case */
3318 first_bit = base >> DEV_BSHIFT;
3319 last_bit = (base + size - 1) >> DEV_BSHIFT;
3321 return (((vm_page_bits_t)2 << last_bit) -
3322 ((vm_page_bits_t)1 << first_bit));
3326 * vm_page_set_valid_range:
3328 * Sets portions of a page valid. The arguments are expected
3329 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3330 * of any partial chunks touched by the range. The invalid portion of
3331 * such chunks will be zeroed.
3333 * (base + size) must be less then or equal to PAGE_SIZE.
3336 vm_page_set_valid_range(vm_page_t m, int base, int size)
3340 VM_OBJECT_ASSERT_WLOCKED(m->object);
3341 if (size == 0) /* handle degenerate case */
3345 * If the base is not DEV_BSIZE aligned and the valid
3346 * bit is clear, we have to zero out a portion of the
3349 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3350 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
3351 pmap_zero_page_area(m, frag, base - frag);
3354 * If the ending offset is not DEV_BSIZE aligned and the
3355 * valid bit is clear, we have to zero out a portion of
3358 endoff = base + size;
3359 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3360 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
3361 pmap_zero_page_area(m, endoff,
3362 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3365 * Assert that no previously invalid block that is now being validated
3368 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
3369 ("vm_page_set_valid_range: page %p is dirty", m));
3372 * Set valid bits inclusive of any overlap.
3374 m->valid |= vm_page_bits(base, size);
3378 * Clear the given bits from the specified page's dirty field.
3380 static __inline void
3381 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
3384 #if PAGE_SIZE < 16384
3389 * If the object is locked and the page is neither exclusive busy nor
3390 * write mapped, then the page's dirty field cannot possibly be
3391 * set by a concurrent pmap operation.
3393 VM_OBJECT_ASSERT_WLOCKED(m->object);
3394 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
3395 m->dirty &= ~pagebits;
3398 * The pmap layer can call vm_page_dirty() without
3399 * holding a distinguished lock. The combination of
3400 * the object's lock and an atomic operation suffice
3401 * to guarantee consistency of the page dirty field.
3403 * For PAGE_SIZE == 32768 case, compiler already
3404 * properly aligns the dirty field, so no forcible
3405 * alignment is needed. Only require existence of
3406 * atomic_clear_64 when page size is 32768.
3408 addr = (uintptr_t)&m->dirty;
3409 #if PAGE_SIZE == 32768
3410 atomic_clear_64((uint64_t *)addr, pagebits);
3411 #elif PAGE_SIZE == 16384
3412 atomic_clear_32((uint32_t *)addr, pagebits);
3413 #else /* PAGE_SIZE <= 8192 */
3415 * Use a trick to perform a 32-bit atomic on the
3416 * containing aligned word, to not depend on the existence
3417 * of atomic_clear_{8, 16}.
3419 shift = addr & (sizeof(uint32_t) - 1);
3420 #if BYTE_ORDER == BIG_ENDIAN
3421 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
3425 addr &= ~(sizeof(uint32_t) - 1);
3426 atomic_clear_32((uint32_t *)addr, pagebits << shift);
3427 #endif /* PAGE_SIZE */
3432 * vm_page_set_validclean:
3434 * Sets portions of a page valid and clean. The arguments are expected
3435 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3436 * of any partial chunks touched by the range. The invalid portion of
3437 * such chunks will be zero'd.
3439 * (base + size) must be less then or equal to PAGE_SIZE.
3442 vm_page_set_validclean(vm_page_t m, int base, int size)
3444 vm_page_bits_t oldvalid, pagebits;
3447 VM_OBJECT_ASSERT_WLOCKED(m->object);
3448 if (size == 0) /* handle degenerate case */
3452 * If the base is not DEV_BSIZE aligned and the valid
3453 * bit is clear, we have to zero out a portion of the
3456 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3457 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
3458 pmap_zero_page_area(m, frag, base - frag);
3461 * If the ending offset is not DEV_BSIZE aligned and the
3462 * valid bit is clear, we have to zero out a portion of
3465 endoff = base + size;
3466 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3467 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
3468 pmap_zero_page_area(m, endoff,
3469 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3472 * Set valid, clear dirty bits. If validating the entire
3473 * page we can safely clear the pmap modify bit. We also
3474 * use this opportunity to clear the VPO_NOSYNC flag. If a process
3475 * takes a write fault on a MAP_NOSYNC memory area the flag will
3478 * We set valid bits inclusive of any overlap, but we can only
3479 * clear dirty bits for DEV_BSIZE chunks that are fully within
3482 oldvalid = m->valid;
3483 pagebits = vm_page_bits(base, size);
3484 m->valid |= pagebits;
3486 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
3487 frag = DEV_BSIZE - frag;
3493 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
3495 if (base == 0 && size == PAGE_SIZE) {
3497 * The page can only be modified within the pmap if it is
3498 * mapped, and it can only be mapped if it was previously
3501 if (oldvalid == VM_PAGE_BITS_ALL)
3503 * Perform the pmap_clear_modify() first. Otherwise,
3504 * a concurrent pmap operation, such as
3505 * pmap_protect(), could clear a modification in the
3506 * pmap and set the dirty field on the page before
3507 * pmap_clear_modify() had begun and after the dirty
3508 * field was cleared here.
3510 pmap_clear_modify(m);
3512 m->oflags &= ~VPO_NOSYNC;
3513 } else if (oldvalid != VM_PAGE_BITS_ALL)
3514 m->dirty &= ~pagebits;
3516 vm_page_clear_dirty_mask(m, pagebits);
3520 vm_page_clear_dirty(vm_page_t m, int base, int size)
3523 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
3527 * vm_page_set_invalid:
3529 * Invalidates DEV_BSIZE'd chunks within a page. Both the
3530 * valid and dirty bits for the effected areas are cleared.
3533 vm_page_set_invalid(vm_page_t m, int base, int size)
3535 vm_page_bits_t bits;
3539 VM_OBJECT_ASSERT_WLOCKED(object);
3540 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
3541 size >= object->un_pager.vnp.vnp_size)
3542 bits = VM_PAGE_BITS_ALL;
3544 bits = vm_page_bits(base, size);
3545 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
3548 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3549 !pmap_page_is_mapped(m),
3550 ("vm_page_set_invalid: page %p is mapped", m));
3556 * vm_page_zero_invalid()
3558 * The kernel assumes that the invalid portions of a page contain
3559 * garbage, but such pages can be mapped into memory by user code.
3560 * When this occurs, we must zero out the non-valid portions of the
3561 * page so user code sees what it expects.
3563 * Pages are most often semi-valid when the end of a file is mapped
3564 * into memory and the file's size is not page aligned.
3567 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3572 VM_OBJECT_ASSERT_WLOCKED(m->object);
3574 * Scan the valid bits looking for invalid sections that
3575 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
3576 * valid bit may be set ) have already been zeroed by
3577 * vm_page_set_validclean().
3579 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3580 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3581 (m->valid & ((vm_page_bits_t)1 << i))) {
3583 pmap_zero_page_area(m,
3584 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3591 * setvalid is TRUE when we can safely set the zero'd areas
3592 * as being valid. We can do this if there are no cache consistancy
3593 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3596 m->valid = VM_PAGE_BITS_ALL;
3602 * Is (partial) page valid? Note that the case where size == 0
3603 * will return FALSE in the degenerate case where the page is
3604 * entirely invalid, and TRUE otherwise.
3607 vm_page_is_valid(vm_page_t m, int base, int size)
3609 vm_page_bits_t bits;
3611 VM_OBJECT_ASSERT_LOCKED(m->object);
3612 bits = vm_page_bits(base, size);
3613 return (m->valid != 0 && (m->valid & bits) == bits);
3617 * Returns true if all of the specified predicates are true for the entire
3618 * (super)page and false otherwise.
3621 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
3627 VM_OBJECT_ASSERT_LOCKED(object);
3628 npages = atop(pagesizes[m->psind]);
3631 * The physically contiguous pages that make up a superpage, i.e., a
3632 * page with a page size index ("psind") greater than zero, will
3633 * occupy adjacent entries in vm_page_array[].
3635 for (i = 0; i < npages; i++) {
3636 /* Always test object consistency, including "skip_m". */
3637 if (m[i].object != object)
3639 if (&m[i] == skip_m)
3641 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
3643 if ((flags & PS_ALL_DIRTY) != 0) {
3645 * Calling vm_page_test_dirty() or pmap_is_modified()
3646 * might stop this case from spuriously returning
3647 * "false". However, that would require a write lock
3648 * on the object containing "m[i]".
3650 if (m[i].dirty != VM_PAGE_BITS_ALL)
3653 if ((flags & PS_ALL_VALID) != 0 &&
3654 m[i].valid != VM_PAGE_BITS_ALL)
3661 * Set the page's dirty bits if the page is modified.
3664 vm_page_test_dirty(vm_page_t m)
3667 VM_OBJECT_ASSERT_WLOCKED(m->object);
3668 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3673 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3676 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3680 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3683 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3687 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3690 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3693 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3695 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3698 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3702 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3705 mtx_assert_(vm_page_lockptr(m), a, file, line);
3711 vm_page_object_lock_assert(vm_page_t m)
3715 * Certain of the page's fields may only be modified by the
3716 * holder of the containing object's lock or the exclusive busy.
3717 * holder. Unfortunately, the holder of the write busy is
3718 * not recorded, and thus cannot be checked here.
3720 if (m->object != NULL && !vm_page_xbusied(m))
3721 VM_OBJECT_ASSERT_WLOCKED(m->object);
3725 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3728 if ((bits & PGA_WRITEABLE) == 0)
3732 * The PGA_WRITEABLE flag can only be set if the page is
3733 * managed, is exclusively busied or the object is locked.
3734 * Currently, this flag is only set by pmap_enter().
3736 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3737 ("PGA_WRITEABLE on unmanaged page"));
3738 if (!vm_page_xbusied(m))
3739 VM_OBJECT_ASSERT_LOCKED(m->object);
3743 #include "opt_ddb.h"
3745 #include <sys/kernel.h>
3747 #include <ddb/ddb.h>
3749 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3752 db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
3753 db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
3754 db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
3755 db_printf("vm_cnt.v_laundry_count: %d\n", vm_cnt.v_laundry_count);
3756 db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
3757 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
3758 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
3759 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
3760 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
3763 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3767 db_printf("pq_free %d\n", vm_cnt.v_free_count);
3768 for (dom = 0; dom < vm_ndomains; dom++) {
3770 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d\n",
3772 vm_dom[dom].vmd_page_count,
3773 vm_dom[dom].vmd_free_count,
3774 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3775 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
3776 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt);
3780 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3786 db_printf("show pginfo addr\n");
3790 phys = strchr(modif, 'p') != NULL;
3792 m = PHYS_TO_VM_PAGE(addr);
3794 m = (vm_page_t)addr;
3796 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3797 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3798 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3799 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3800 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);