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 __exclusive_cache_line vm_page_queue_free_mtx;
132 struct mtx_padalign __exclusive_cache_line 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,
170 static int vm_page_alloc_fail(vm_object_t object, int req);
172 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init_fakepg, NULL);
175 vm_page_init_fakepg(void *dummy)
178 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
179 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
182 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
183 #if PAGE_SIZE == 32768
185 CTASSERT(sizeof(u_long) >= 8);
190 * Try to acquire a physical address lock while a pmap is locked. If we
191 * fail to trylock we unlock and lock the pmap directly and cache the
192 * locked pa in *locked. The caller should then restart their loop in case
193 * the virtual to physical mapping has changed.
196 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
203 PA_LOCK_ASSERT(lockpa, MA_OWNED);
204 if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
211 atomic_add_int(&pa_tryrelock_restart, 1);
220 * Sets the page size, perhaps based upon the memory
221 * size. Must be called before any use of page-size
222 * dependent functions.
225 vm_set_page_size(void)
227 if (vm_cnt.v_page_size == 0)
228 vm_cnt.v_page_size = PAGE_SIZE;
229 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
230 panic("vm_set_page_size: page size not a power of two");
234 * vm_page_blacklist_next:
236 * Find the next entry in the provided string of blacklist
237 * addresses. Entries are separated by space, comma, or newline.
238 * If an invalid integer is encountered then the rest of the
239 * string is skipped. Updates the list pointer to the next
240 * character, or NULL if the string is exhausted or invalid.
243 vm_page_blacklist_next(char **list, char *end)
248 if (list == NULL || *list == NULL)
256 * If there's no end pointer then the buffer is coming from
257 * the kenv and we know it's null-terminated.
260 end = *list + strlen(*list);
262 /* Ensure that strtoq() won't walk off the end */
264 if (*end == '\n' || *end == ' ' || *end == ',')
267 printf("Blacklist not terminated, skipping\n");
273 for (pos = *list; *pos != '\0'; pos = cp) {
274 bad = strtoq(pos, &cp, 0);
275 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
284 if (*cp == '\0' || ++cp >= end)
288 return (trunc_page(bad));
290 printf("Garbage in RAM blacklist, skipping\n");
296 * vm_page_blacklist_check:
298 * Iterate through the provided string of blacklist addresses, pulling
299 * each entry out of the physical allocator free list and putting it
300 * onto a list for reporting via the vm.page_blacklist sysctl.
303 vm_page_blacklist_check(char *list, char *end)
311 while (next != NULL) {
312 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
314 m = vm_phys_paddr_to_vm_page(pa);
317 mtx_lock(&vm_page_queue_free_mtx);
318 ret = vm_phys_unfree_page(m);
319 mtx_unlock(&vm_page_queue_free_mtx);
321 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
323 printf("Skipping page with pa 0x%jx\n",
330 * vm_page_blacklist_load:
332 * Search for a special module named "ram_blacklist". It'll be a
333 * plain text file provided by the user via the loader directive
337 vm_page_blacklist_load(char **list, char **end)
346 mod = preload_search_by_type("ram_blacklist");
348 ptr = preload_fetch_addr(mod);
349 len = preload_fetch_size(mod);
360 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
367 error = sysctl_wire_old_buffer(req, 0);
370 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
371 TAILQ_FOREACH(m, &blacklist_head, listq) {
372 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
373 (uintmax_t)m->phys_addr);
376 error = sbuf_finish(&sbuf);
382 vm_page_domain_init(struct vm_domain *vmd)
384 struct vm_pagequeue *pq;
387 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
388 "vm inactive pagequeue";
389 *__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_vcnt) =
390 &vm_cnt.v_inactive_count;
391 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
392 "vm active pagequeue";
393 *__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_vcnt) =
394 &vm_cnt.v_active_count;
395 *__DECONST(char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
396 "vm laundry pagequeue";
397 *__DECONST(int **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_vcnt) =
398 &vm_cnt.v_laundry_count;
399 vmd->vmd_page_count = 0;
400 vmd->vmd_free_count = 0;
402 vmd->vmd_oom = FALSE;
403 for (i = 0; i < PQ_COUNT; i++) {
404 pq = &vmd->vmd_pagequeues[i];
405 TAILQ_INIT(&pq->pq_pl);
406 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
407 MTX_DEF | MTX_DUPOK);
412 * Initialize a physical page in preparation for adding it to the free
416 vm_page_init_page(vm_page_t m, vm_paddr_t pa, int segind)
421 m->busy_lock = VPB_UNBUSIED;
428 m->order = VM_NFREEORDER;
429 m->pool = VM_FREEPOOL_DEFAULT;
430 m->valid = m->dirty = 0;
437 * Initializes the resident memory module. Allocates physical memory for
438 * bootstrapping UMA and some data structures that are used to manage
439 * physical pages. Initializes these structures, and populates the free
443 vm_page_startup(vm_offset_t vaddr)
445 struct vm_domain *vmd;
446 struct vm_phys_seg *seg;
448 char *list, *listend;
450 vm_paddr_t end, high_avail, low_avail, new_end, page_range, size;
451 vm_paddr_t biggestsize, last_pa, pa;
453 int biggestone, i, pages_per_zone, segind;
457 vaddr = round_page(vaddr);
459 for (i = 0; phys_avail[i + 1]; i += 2) {
460 phys_avail[i] = round_page(phys_avail[i]);
461 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
463 for (i = 0; phys_avail[i + 1]; i += 2) {
464 size = phys_avail[i + 1] - phys_avail[i];
465 if (size > biggestsize) {
471 end = phys_avail[biggestone+1];
474 * Initialize the page and queue locks.
476 mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
477 for (i = 0; i < PA_LOCK_COUNT; i++)
478 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
479 for (i = 0; i < vm_ndomains; i++)
480 vm_page_domain_init(&vm_dom[i]);
483 * Almost all of the pages needed for bootstrapping UMA are used
484 * for zone structures, so if the number of CPUs results in those
485 * structures taking more than one page each, we set aside more pages
486 * in proportion to the zone structure size.
488 pages_per_zone = howmany(sizeof(struct uma_zone) +
489 sizeof(struct uma_cache) * (mp_maxid + 1) +
490 roundup2(sizeof(struct uma_slab), sizeof(void *)), UMA_SLAB_SIZE);
491 if (pages_per_zone > 1) {
492 /* Reserve more pages so that we don't run out. */
493 boot_pages = UMA_BOOT_PAGES_ZONES * pages_per_zone;
497 * Allocate memory for use when boot strapping the kernel memory
500 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
501 * manually fetch the value.
503 TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
504 new_end = end - (boot_pages * UMA_SLAB_SIZE);
505 new_end = trunc_page(new_end);
506 mapped = pmap_map(&vaddr, new_end, end,
507 VM_PROT_READ | VM_PROT_WRITE);
508 bzero((void *)mapped, end - new_end);
509 uma_startup((void *)mapped, boot_pages);
511 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
512 defined(__i386__) || defined(__mips__)
514 * Allocate a bitmap to indicate that a random physical page
515 * needs to be included in a minidump.
517 * The amd64 port needs this to indicate which direct map pages
518 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
520 * However, i386 still needs this workspace internally within the
521 * minidump code. In theory, they are not needed on i386, but are
522 * included should the sf_buf code decide to use them.
525 for (i = 0; dump_avail[i + 1] != 0; i += 2)
526 if (dump_avail[i + 1] > last_pa)
527 last_pa = dump_avail[i + 1];
528 page_range = last_pa / PAGE_SIZE;
529 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
530 new_end -= vm_page_dump_size;
531 vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
532 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
533 bzero((void *)vm_page_dump, vm_page_dump_size);
537 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
539 * Include the UMA bootstrap pages and vm_page_dump in a crash dump.
540 * When pmap_map() uses the direct map, they are not automatically
543 for (pa = new_end; pa < end; pa += PAGE_SIZE)
546 phys_avail[biggestone + 1] = new_end;
549 * Request that the physical pages underlying the message buffer be
550 * included in a crash dump. Since the message buffer is accessed
551 * through the direct map, they are not automatically included.
553 pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
554 last_pa = pa + round_page(msgbufsize);
555 while (pa < last_pa) {
561 * Compute the number of pages of memory that will be available for
562 * use, taking into account the overhead of a page structure per page.
563 * In other words, solve
564 * "available physical memory" - round_page(page_range *
565 * sizeof(struct vm_page)) = page_range * PAGE_SIZE
568 low_avail = phys_avail[0];
569 high_avail = phys_avail[1];
570 for (i = 0; i < vm_phys_nsegs; i++) {
571 if (vm_phys_segs[i].start < low_avail)
572 low_avail = vm_phys_segs[i].start;
573 if (vm_phys_segs[i].end > high_avail)
574 high_avail = vm_phys_segs[i].end;
576 /* Skip the first chunk. It is already accounted for. */
577 for (i = 2; phys_avail[i + 1] != 0; i += 2) {
578 if (phys_avail[i] < low_avail)
579 low_avail = phys_avail[i];
580 if (phys_avail[i + 1] > high_avail)
581 high_avail = phys_avail[i + 1];
583 first_page = low_avail / PAGE_SIZE;
584 #ifdef VM_PHYSSEG_SPARSE
586 for (i = 0; i < vm_phys_nsegs; i++)
587 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
588 for (i = 0; phys_avail[i + 1] != 0; i += 2)
589 size += phys_avail[i + 1] - phys_avail[i];
590 #elif defined(VM_PHYSSEG_DENSE)
591 size = high_avail - low_avail;
593 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
596 #ifdef VM_PHYSSEG_DENSE
598 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
599 * the overhead of a page structure per page only if vm_page_array is
600 * allocated from the last physical memory chunk. Otherwise, we must
601 * allocate page structures representing the physical memory
602 * underlying vm_page_array, even though they will not be used.
604 if (new_end != high_avail)
605 page_range = size / PAGE_SIZE;
609 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
612 * If the partial bytes remaining are large enough for
613 * a page (PAGE_SIZE) without a corresponding
614 * 'struct vm_page', then new_end will contain an
615 * extra page after subtracting the length of the VM
616 * page array. Compensate by subtracting an extra
619 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
620 if (new_end == high_avail)
621 high_avail -= PAGE_SIZE;
622 new_end -= PAGE_SIZE;
628 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
629 * However, because this page is allocated from KVM, out-of-bounds
630 * accesses using the direct map will not be trapped.
635 * Allocate physical memory for the page structures, and map it.
637 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
638 mapped = pmap_map(&vaddr, new_end, end,
639 VM_PROT_READ | VM_PROT_WRITE);
640 vm_page_array = (vm_page_t)mapped;
641 vm_page_array_size = page_range;
643 #if VM_NRESERVLEVEL > 0
645 * Allocate physical memory for the reservation management system's
646 * data structures, and map it.
648 if (high_avail == end)
649 high_avail = new_end;
650 new_end = vm_reserv_startup(&vaddr, new_end, high_avail);
652 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
654 * Include vm_page_array and vm_reserv_array in a crash dump.
656 for (pa = new_end; pa < end; pa += PAGE_SIZE)
659 phys_avail[biggestone + 1] = new_end;
662 * Add physical memory segments corresponding to the available
665 for (i = 0; phys_avail[i + 1] != 0; i += 2)
666 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
669 * Initialize the physical memory allocator.
674 * Initialize the page structures and add every available page to the
675 * physical memory allocator's free lists.
677 vm_cnt.v_page_count = 0;
678 vm_cnt.v_free_count = 0;
679 for (segind = 0; segind < vm_phys_nsegs; segind++) {
680 seg = &vm_phys_segs[segind];
681 for (m = seg->first_page, pa = seg->start; pa < seg->end;
682 m++, pa += PAGE_SIZE)
683 vm_page_init_page(m, pa, segind);
686 * Add the segment to the free lists only if it is covered by
687 * one of the ranges in phys_avail. Because we've added the
688 * ranges to the vm_phys_segs array, we can assume that each
689 * segment is either entirely contained in one of the ranges,
690 * or doesn't overlap any of them.
692 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
693 if (seg->start < phys_avail[i] ||
694 seg->end > phys_avail[i + 1])
698 pagecount = (u_long)atop(seg->end - seg->start);
700 mtx_lock(&vm_page_queue_free_mtx);
701 vm_phys_free_contig(m, pagecount);
702 vm_phys_freecnt_adj(m, (int)pagecount);
703 mtx_unlock(&vm_page_queue_free_mtx);
704 vm_cnt.v_page_count += (u_int)pagecount;
706 vmd = &vm_dom[seg->domain];
707 vmd->vmd_page_count += (u_int)pagecount;
708 vmd->vmd_segs |= 1UL << m->segind;
714 * Remove blacklisted pages from the physical memory allocator.
716 TAILQ_INIT(&blacklist_head);
717 vm_page_blacklist_load(&list, &listend);
718 vm_page_blacklist_check(list, listend);
720 list = kern_getenv("vm.blacklist");
721 vm_page_blacklist_check(list, NULL);
724 #if VM_NRESERVLEVEL > 0
726 * Initialize the reservation management system.
734 vm_page_reference(vm_page_t m)
737 vm_page_aflag_set(m, PGA_REFERENCED);
741 * vm_page_busy_downgrade:
743 * Downgrade an exclusive busy page into a single shared busy page.
746 vm_page_busy_downgrade(vm_page_t m)
751 vm_page_assert_xbusied(m);
752 locked = mtx_owned(vm_page_lockptr(m));
756 x &= VPB_BIT_WAITERS;
757 if (x != 0 && !locked)
759 if (atomic_cmpset_rel_int(&m->busy_lock,
760 VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1)))
762 if (x != 0 && !locked)
775 * Return a positive value if the page is shared busied, 0 otherwise.
778 vm_page_sbusied(vm_page_t m)
783 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
789 * Shared unbusy a page.
792 vm_page_sunbusy(vm_page_t m)
796 vm_page_lock_assert(m, MA_NOTOWNED);
797 vm_page_assert_sbusied(m);
801 if (VPB_SHARERS(x) > 1) {
802 if (atomic_cmpset_int(&m->busy_lock, x,
807 if ((x & VPB_BIT_WAITERS) == 0) {
808 KASSERT(x == VPB_SHARERS_WORD(1),
809 ("vm_page_sunbusy: invalid lock state"));
810 if (atomic_cmpset_int(&m->busy_lock,
811 VPB_SHARERS_WORD(1), VPB_UNBUSIED))
815 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
816 ("vm_page_sunbusy: invalid lock state for waiters"));
819 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
830 * vm_page_busy_sleep:
832 * Sleep and release the page lock, using the page pointer as wchan.
833 * This is used to implement the hard-path of busying mechanism.
835 * The given page must be locked.
837 * If nonshared is true, sleep only if the page is xbusy.
840 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
844 vm_page_assert_locked(m);
847 if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
848 ((x & VPB_BIT_WAITERS) == 0 &&
849 !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
853 msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
859 * Try to shared busy a page.
860 * If the operation succeeds 1 is returned otherwise 0.
861 * The operation never sleeps.
864 vm_page_trysbusy(vm_page_t m)
870 if ((x & VPB_BIT_SHARED) == 0)
872 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
878 vm_page_xunbusy_locked(vm_page_t m)
881 vm_page_assert_xbusied(m);
882 vm_page_assert_locked(m);
884 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
885 /* There is a waiter, do wakeup() instead of vm_page_flash(). */
890 vm_page_xunbusy_maybelocked(vm_page_t m)
894 vm_page_assert_xbusied(m);
897 * Fast path for unbusy. If it succeeds, we know that there
898 * are no waiters, so we do not need a wakeup.
900 if (atomic_cmpset_rel_int(&m->busy_lock, VPB_SINGLE_EXCLUSIVER,
904 lockacq = !mtx_owned(vm_page_lockptr(m));
907 vm_page_xunbusy_locked(m);
913 * vm_page_xunbusy_hard:
915 * Called after the first try the exclusive unbusy of a page failed.
916 * It is assumed that the waiters bit is on.
919 vm_page_xunbusy_hard(vm_page_t m)
922 vm_page_assert_xbusied(m);
925 vm_page_xunbusy_locked(m);
932 * Wakeup anyone waiting for the page.
933 * The ownership bits do not change.
935 * The given page must be locked.
938 vm_page_flash(vm_page_t m)
942 vm_page_lock_assert(m, MA_OWNED);
946 if ((x & VPB_BIT_WAITERS) == 0)
948 if (atomic_cmpset_int(&m->busy_lock, x,
949 x & (~VPB_BIT_WAITERS)))
956 * Avoid releasing and reacquiring the same page lock.
959 vm_page_change_lock(vm_page_t m, struct mtx **mtx)
963 mtx1 = vm_page_lockptr(m);
973 * Keep page from being freed by the page daemon
974 * much of the same effect as wiring, except much lower
975 * overhead and should be used only for *very* temporary
976 * holding ("wiring").
979 vm_page_hold(vm_page_t mem)
982 vm_page_lock_assert(mem, MA_OWNED);
987 vm_page_unhold(vm_page_t mem)
990 vm_page_lock_assert(mem, MA_OWNED);
991 KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
993 if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
994 vm_page_free_toq(mem);
998 * vm_page_unhold_pages:
1000 * Unhold each of the pages that is referenced by the given array.
1003 vm_page_unhold_pages(vm_page_t *ma, int count)
1008 for (; count != 0; count--) {
1009 vm_page_change_lock(*ma, &mtx);
1010 vm_page_unhold(*ma);
1018 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1022 #ifdef VM_PHYSSEG_SPARSE
1023 m = vm_phys_paddr_to_vm_page(pa);
1025 m = vm_phys_fictitious_to_vm_page(pa);
1027 #elif defined(VM_PHYSSEG_DENSE)
1031 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1032 m = &vm_page_array[pi - first_page];
1035 return (vm_phys_fictitious_to_vm_page(pa));
1037 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1044 * Create a fictitious page with the specified physical address and
1045 * memory attribute. The memory attribute is the only the machine-
1046 * dependent aspect of a fictitious page that must be initialized.
1049 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1053 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1054 vm_page_initfake(m, paddr, memattr);
1059 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1062 if ((m->flags & PG_FICTITIOUS) != 0) {
1064 * The page's memattr might have changed since the
1065 * previous initialization. Update the pmap to the
1070 m->phys_addr = paddr;
1072 /* Fictitious pages don't use "segind". */
1073 m->flags = PG_FICTITIOUS;
1074 /* Fictitious pages don't use "order" or "pool". */
1075 m->oflags = VPO_UNMANAGED;
1076 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1080 pmap_page_set_memattr(m, memattr);
1086 * Release a fictitious page.
1089 vm_page_putfake(vm_page_t m)
1092 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1093 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1094 ("vm_page_putfake: bad page %p", m));
1095 uma_zfree(fakepg_zone, m);
1099 * vm_page_updatefake:
1101 * Update the given fictitious page to the specified physical address and
1105 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1108 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1109 ("vm_page_updatefake: bad page %p", m));
1110 m->phys_addr = paddr;
1111 pmap_page_set_memattr(m, memattr);
1120 vm_page_free(vm_page_t m)
1123 m->flags &= ~PG_ZERO;
1124 vm_page_free_toq(m);
1128 * vm_page_free_zero:
1130 * Free a page to the zerod-pages queue
1133 vm_page_free_zero(vm_page_t m)
1136 m->flags |= PG_ZERO;
1137 vm_page_free_toq(m);
1141 * Unbusy and handle the page queueing for a page from a getpages request that
1142 * was optionally read ahead or behind.
1145 vm_page_readahead_finish(vm_page_t m)
1148 /* We shouldn't put invalid pages on queues. */
1149 KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
1152 * Since the page is not the actually needed one, whether it should
1153 * be activated or deactivated is not obvious. Empirical results
1154 * have shown that deactivating the page is usually the best choice,
1155 * unless the page is wanted by another thread.
1158 if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1159 vm_page_activate(m);
1161 vm_page_deactivate(m);
1167 * vm_page_sleep_if_busy:
1169 * Sleep and release the page queues lock if the page is busied.
1170 * Returns TRUE if the thread slept.
1172 * The given page must be unlocked and object containing it must
1176 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1180 vm_page_lock_assert(m, MA_NOTOWNED);
1181 VM_OBJECT_ASSERT_WLOCKED(m->object);
1183 if (vm_page_busied(m)) {
1185 * The page-specific object must be cached because page
1186 * identity can change during the sleep, causing the
1187 * re-lock of a different object.
1188 * It is assumed that a reference to the object is already
1189 * held by the callers.
1193 VM_OBJECT_WUNLOCK(obj);
1194 vm_page_busy_sleep(m, msg, false);
1195 VM_OBJECT_WLOCK(obj);
1202 * vm_page_dirty_KBI: [ internal use only ]
1204 * Set all bits in the page's dirty field.
1206 * The object containing the specified page must be locked if the
1207 * call is made from the machine-independent layer.
1209 * See vm_page_clear_dirty_mask().
1211 * This function should only be called by vm_page_dirty().
1214 vm_page_dirty_KBI(vm_page_t m)
1217 /* Refer to this operation by its public name. */
1218 KASSERT(m->valid == VM_PAGE_BITS_ALL,
1219 ("vm_page_dirty: page is invalid!"));
1220 m->dirty = VM_PAGE_BITS_ALL;
1224 * vm_page_insert: [ internal use only ]
1226 * Inserts the given mem entry into the object and object list.
1228 * The object must be locked.
1231 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1235 VM_OBJECT_ASSERT_WLOCKED(object);
1236 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1237 return (vm_page_insert_after(m, object, pindex, mpred));
1241 * vm_page_insert_after:
1243 * Inserts the page "m" into the specified object at offset "pindex".
1245 * The page "mpred" must immediately precede the offset "pindex" within
1246 * the specified object.
1248 * The object must be locked.
1251 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1256 VM_OBJECT_ASSERT_WLOCKED(object);
1257 KASSERT(m->object == NULL,
1258 ("vm_page_insert_after: page already inserted"));
1259 if (mpred != NULL) {
1260 KASSERT(mpred->object == object,
1261 ("vm_page_insert_after: object doesn't contain mpred"));
1262 KASSERT(mpred->pindex < pindex,
1263 ("vm_page_insert_after: mpred doesn't precede pindex"));
1264 msucc = TAILQ_NEXT(mpred, listq);
1266 msucc = TAILQ_FIRST(&object->memq);
1268 KASSERT(msucc->pindex > pindex,
1269 ("vm_page_insert_after: msucc doesn't succeed pindex"));
1272 * Record the object/offset pair in this page
1278 * Now link into the object's ordered list of backed pages.
1280 if (vm_radix_insert(&object->rtree, m)) {
1285 vm_page_insert_radixdone(m, object, mpred);
1290 * vm_page_insert_radixdone:
1292 * Complete page "m" insertion into the specified object after the
1293 * radix trie hooking.
1295 * The page "mpred" must precede the offset "m->pindex" within the
1298 * The object must be locked.
1301 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1304 VM_OBJECT_ASSERT_WLOCKED(object);
1305 KASSERT(object != NULL && m->object == object,
1306 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1307 if (mpred != NULL) {
1308 KASSERT(mpred->object == object,
1309 ("vm_page_insert_after: object doesn't contain mpred"));
1310 KASSERT(mpred->pindex < m->pindex,
1311 ("vm_page_insert_after: mpred doesn't precede pindex"));
1315 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1317 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1320 * Show that the object has one more resident page.
1322 object->resident_page_count++;
1325 * Hold the vnode until the last page is released.
1327 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1328 vhold(object->handle);
1331 * Since we are inserting a new and possibly dirty page,
1332 * update the object's OBJ_MIGHTBEDIRTY flag.
1334 if (pmap_page_is_write_mapped(m))
1335 vm_object_set_writeable_dirty(object);
1341 * Removes the specified page from its containing object, but does not
1342 * invalidate any backing storage.
1344 * The object must be locked. The page must be locked if it is managed.
1347 vm_page_remove(vm_page_t m)
1352 if ((m->oflags & VPO_UNMANAGED) == 0)
1353 vm_page_assert_locked(m);
1354 if ((object = m->object) == NULL)
1356 VM_OBJECT_ASSERT_WLOCKED(object);
1357 if (vm_page_xbusied(m))
1358 vm_page_xunbusy_maybelocked(m);
1359 mrem = vm_radix_remove(&object->rtree, m->pindex);
1360 KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1363 * Now remove from the object's list of backed pages.
1365 TAILQ_REMOVE(&object->memq, m, listq);
1368 * And show that the object has one fewer resident page.
1370 object->resident_page_count--;
1373 * The vnode may now be recycled.
1375 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1376 vdrop(object->handle);
1384 * Returns the page associated with the object/offset
1385 * pair specified; if none is found, NULL is returned.
1387 * The object must be locked.
1390 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1393 VM_OBJECT_ASSERT_LOCKED(object);
1394 return (vm_radix_lookup(&object->rtree, pindex));
1398 * vm_page_find_least:
1400 * Returns the page associated with the object with least pindex
1401 * greater than or equal to the parameter pindex, or NULL.
1403 * The object must be locked.
1406 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1410 VM_OBJECT_ASSERT_LOCKED(object);
1411 if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1412 m = vm_radix_lookup_ge(&object->rtree, pindex);
1417 * Returns the given page's successor (by pindex) within the object if it is
1418 * resident; if none is found, NULL is returned.
1420 * The object must be locked.
1423 vm_page_next(vm_page_t m)
1427 VM_OBJECT_ASSERT_LOCKED(m->object);
1428 if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1429 MPASS(next->object == m->object);
1430 if (next->pindex != m->pindex + 1)
1437 * Returns the given page's predecessor (by pindex) within the object if it is
1438 * resident; if none is found, NULL is returned.
1440 * The object must be locked.
1443 vm_page_prev(vm_page_t m)
1447 VM_OBJECT_ASSERT_LOCKED(m->object);
1448 if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1449 MPASS(prev->object == m->object);
1450 if (prev->pindex != m->pindex - 1)
1457 * Uses the page mnew as a replacement for an existing page at index
1458 * pindex which must be already present in the object.
1460 * The existing page must not be on a paging queue.
1463 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1467 VM_OBJECT_ASSERT_WLOCKED(object);
1468 KASSERT(mnew->object == NULL,
1469 ("vm_page_replace: page already in object"));
1472 * This function mostly follows vm_page_insert() and
1473 * vm_page_remove() without the radix, object count and vnode
1474 * dance. Double check such functions for more comments.
1477 mnew->object = object;
1478 mnew->pindex = pindex;
1479 mold = vm_radix_replace(&object->rtree, mnew);
1480 KASSERT(mold->queue == PQ_NONE,
1481 ("vm_page_replace: mold is on a paging queue"));
1483 /* Keep the resident page list in sorted order. */
1484 TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1485 TAILQ_REMOVE(&object->memq, mold, listq);
1487 mold->object = NULL;
1488 vm_page_xunbusy_maybelocked(mold);
1491 * The object's resident_page_count does not change because we have
1492 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1494 if (pmap_page_is_write_mapped(mnew))
1495 vm_object_set_writeable_dirty(object);
1502 * Move the given memory entry from its
1503 * current object to the specified target object/offset.
1505 * Note: swap associated with the page must be invalidated by the move. We
1506 * have to do this for several reasons: (1) we aren't freeing the
1507 * page, (2) we are dirtying the page, (3) the VM system is probably
1508 * moving the page from object A to B, and will then later move
1509 * the backing store from A to B and we can't have a conflict.
1511 * Note: we *always* dirty the page. It is necessary both for the
1512 * fact that we moved it, and because we may be invalidating
1515 * The objects must be locked.
1518 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1523 VM_OBJECT_ASSERT_WLOCKED(new_object);
1525 mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1526 KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1527 ("vm_page_rename: pindex already renamed"));
1530 * Create a custom version of vm_page_insert() which does not depend
1531 * by m_prev and can cheat on the implementation aspects of the
1535 m->pindex = new_pindex;
1536 if (vm_radix_insert(&new_object->rtree, m)) {
1542 * The operation cannot fail anymore. The removal must happen before
1543 * the listq iterator is tainted.
1549 /* Return back to the new pindex to complete vm_page_insert(). */
1550 m->pindex = new_pindex;
1551 m->object = new_object;
1553 vm_page_insert_radixdone(m, new_object, mpred);
1561 * Allocate and return a page that is associated with the specified
1562 * object and offset pair. By default, this page is exclusive busied.
1564 * The caller must always specify an allocation class.
1566 * allocation classes:
1567 * VM_ALLOC_NORMAL normal process request
1568 * VM_ALLOC_SYSTEM system *really* needs a page
1569 * VM_ALLOC_INTERRUPT interrupt time request
1571 * optional allocation flags:
1572 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1573 * intends to allocate
1574 * VM_ALLOC_NOBUSY do not exclusive busy the page
1575 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1576 * VM_ALLOC_NOOBJ page is not associated with an object and
1577 * should not be exclusive busy
1578 * VM_ALLOC_SBUSY shared busy the allocated page
1579 * VM_ALLOC_WIRED wire the allocated page
1580 * VM_ALLOC_ZERO prefer a zeroed page
1582 * This routine may not sleep.
1585 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1588 return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1589 vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1593 * Allocate a page in the specified object with the given page index. To
1594 * optimize insertion of the page into the object, the caller must also specifiy
1595 * the resident page in the object with largest index smaller than the given
1596 * page index, or NULL if no such page exists.
1599 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex, int req,
1603 int flags, req_class;
1605 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1606 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1607 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1608 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1609 ("inconsistent object(%p)/req(%x)", object, req));
1610 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1611 ("Can't sleep and retry object insertion."));
1612 KASSERT(mpred == NULL || mpred->pindex < pindex,
1613 ("mpred %p doesn't precede pindex 0x%jx", mpred,
1614 (uintmax_t)pindex));
1616 VM_OBJECT_ASSERT_WLOCKED(object);
1618 if (__predict_false((req & VM_ALLOC_IFCACHED) != 0))
1621 req_class = req & VM_ALLOC_CLASS_MASK;
1624 * The page daemon is allowed to dig deeper into the free page list.
1626 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1627 req_class = VM_ALLOC_SYSTEM;
1630 * Allocate a page if the number of free pages exceeds the minimum
1631 * for the request class.
1634 mtx_lock(&vm_page_queue_free_mtx);
1635 if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
1636 (req_class == VM_ALLOC_SYSTEM &&
1637 vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
1638 (req_class == VM_ALLOC_INTERRUPT &&
1639 vm_cnt.v_free_count > 0)) {
1641 * Can we allocate the page from a reservation?
1643 #if VM_NRESERVLEVEL > 0
1644 if (object == NULL || (object->flags & (OBJ_COLORED |
1645 OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1646 vm_reserv_alloc_page(object, pindex, mpred)) == NULL)
1650 * If not, allocate it from the free page queues.
1652 m = vm_phys_alloc_pages(object != NULL ?
1653 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1654 #if VM_NRESERVLEVEL > 0
1655 if (m == NULL && vm_reserv_reclaim_inactive()) {
1656 m = vm_phys_alloc_pages(object != NULL ?
1657 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1664 * Not allocatable, give up.
1666 if (vm_page_alloc_fail(object, req))
1672 * At this point we had better have found a good page.
1674 KASSERT(m != NULL, ("missing page"));
1675 vm_phys_freecnt_adj(m, -1);
1676 if ((m->flags & PG_ZERO) != 0)
1677 vm_page_zero_count--;
1678 mtx_unlock(&vm_page_queue_free_mtx);
1679 vm_page_alloc_check(m);
1682 * Initialize the page. Only the PG_ZERO flag is inherited.
1685 if ((req & VM_ALLOC_ZERO) != 0)
1688 if ((req & VM_ALLOC_NODUMP) != 0)
1692 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1694 m->busy_lock = VPB_UNBUSIED;
1695 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1696 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1697 if ((req & VM_ALLOC_SBUSY) != 0)
1698 m->busy_lock = VPB_SHARERS_WORD(1);
1699 if (req & VM_ALLOC_WIRED) {
1701 * The page lock is not required for wiring a page until that
1702 * page is inserted into the object.
1704 atomic_add_int(&vm_cnt.v_wire_count, 1);
1709 if (object != NULL) {
1710 if (vm_page_insert_after(m, object, pindex, mpred)) {
1711 pagedaemon_wakeup();
1712 if (req & VM_ALLOC_WIRED) {
1713 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1716 KASSERT(m->object == NULL, ("page %p has object", m));
1717 m->oflags = VPO_UNMANAGED;
1718 m->busy_lock = VPB_UNBUSIED;
1719 /* Don't change PG_ZERO. */
1720 vm_page_free_toq(m);
1721 if (req & VM_ALLOC_WAITFAIL) {
1722 VM_OBJECT_WUNLOCK(object);
1724 VM_OBJECT_WLOCK(object);
1729 /* Ignore device objects; the pager sets "memattr" for them. */
1730 if (object->memattr != VM_MEMATTR_DEFAULT &&
1731 (object->flags & OBJ_FICTITIOUS) == 0)
1732 pmap_page_set_memattr(m, object->memattr);
1737 * Don't wakeup too often - wakeup the pageout daemon when
1738 * we would be nearly out of memory.
1740 if (vm_paging_needed())
1741 pagedaemon_wakeup();
1747 * vm_page_alloc_contig:
1749 * Allocate a contiguous set of physical pages of the given size "npages"
1750 * from the free lists. All of the physical pages must be at or above
1751 * the given physical address "low" and below the given physical address
1752 * "high". The given value "alignment" determines the alignment of the
1753 * first physical page in the set. If the given value "boundary" is
1754 * non-zero, then the set of physical pages cannot cross any physical
1755 * address boundary that is a multiple of that value. Both "alignment"
1756 * and "boundary" must be a power of two.
1758 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1759 * then the memory attribute setting for the physical pages is configured
1760 * to the object's memory attribute setting. Otherwise, the memory
1761 * attribute setting for the physical pages is configured to "memattr",
1762 * overriding the object's memory attribute setting. However, if the
1763 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1764 * memory attribute setting for the physical pages cannot be configured
1765 * to VM_MEMATTR_DEFAULT.
1767 * The specified object may not contain fictitious pages.
1769 * The caller must always specify an allocation class.
1771 * allocation classes:
1772 * VM_ALLOC_NORMAL normal process request
1773 * VM_ALLOC_SYSTEM system *really* needs a page
1774 * VM_ALLOC_INTERRUPT interrupt time request
1776 * optional allocation flags:
1777 * VM_ALLOC_NOBUSY do not exclusive busy the page
1778 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1779 * VM_ALLOC_NOOBJ page is not associated with an object and
1780 * should not be exclusive busy
1781 * VM_ALLOC_SBUSY shared busy the allocated page
1782 * VM_ALLOC_WIRED wire the allocated page
1783 * VM_ALLOC_ZERO prefer a zeroed page
1785 * This routine may not sleep.
1788 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1789 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1790 vm_paddr_t boundary, vm_memattr_t memattr)
1792 vm_page_t m, m_ret, mpred;
1793 u_int busy_lock, flags, oflags;
1796 mpred = NULL; /* XXX: pacify gcc */
1797 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1798 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1799 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1800 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1801 ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
1803 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1804 ("Can't sleep and retry object insertion."));
1805 if (object != NULL) {
1806 VM_OBJECT_ASSERT_WLOCKED(object);
1807 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
1808 ("vm_page_alloc_contig: object %p has fictitious pages",
1811 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1812 req_class = req & VM_ALLOC_CLASS_MASK;
1815 * The page daemon is allowed to dig deeper into the free page list.
1817 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1818 req_class = VM_ALLOC_SYSTEM;
1820 if (object != NULL) {
1821 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1822 KASSERT(mpred == NULL || mpred->pindex != pindex,
1823 ("vm_page_alloc_contig: pindex already allocated"));
1827 * Can we allocate the pages without the number of free pages falling
1828 * below the lower bound for the allocation class?
1831 mtx_lock(&vm_page_queue_free_mtx);
1832 if (vm_cnt.v_free_count >= npages + vm_cnt.v_free_reserved ||
1833 (req_class == VM_ALLOC_SYSTEM &&
1834 vm_cnt.v_free_count >= npages + vm_cnt.v_interrupt_free_min) ||
1835 (req_class == VM_ALLOC_INTERRUPT &&
1836 vm_cnt.v_free_count >= npages)) {
1838 * Can we allocate the pages from a reservation?
1840 #if VM_NRESERVLEVEL > 0
1842 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1843 (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1844 low, high, alignment, boundary, mpred)) == NULL)
1847 * If not, allocate them from the free page queues.
1849 m_ret = vm_phys_alloc_contig(npages, low, high,
1850 alignment, boundary);
1852 if (vm_page_alloc_fail(object, req))
1856 if (m_ret != NULL) {
1857 vm_phys_freecnt_adj(m_ret, -npages);
1858 for (m = m_ret; m < &m_ret[npages]; m++)
1859 if ((m->flags & PG_ZERO) != 0)
1860 vm_page_zero_count--;
1862 #if VM_NRESERVLEVEL > 0
1863 if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1868 mtx_unlock(&vm_page_queue_free_mtx);
1871 for (m = m_ret; m < &m_ret[npages]; m++)
1872 vm_page_alloc_check(m);
1875 * Initialize the pages. Only the PG_ZERO flag is inherited.
1878 if ((req & VM_ALLOC_ZERO) != 0)
1880 if ((req & VM_ALLOC_NODUMP) != 0)
1882 oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1884 busy_lock = VPB_UNBUSIED;
1885 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1886 busy_lock = VPB_SINGLE_EXCLUSIVER;
1887 if ((req & VM_ALLOC_SBUSY) != 0)
1888 busy_lock = VPB_SHARERS_WORD(1);
1889 if ((req & VM_ALLOC_WIRED) != 0)
1890 atomic_add_int(&vm_cnt.v_wire_count, npages);
1891 if (object != NULL) {
1892 if (object->memattr != VM_MEMATTR_DEFAULT &&
1893 memattr == VM_MEMATTR_DEFAULT)
1894 memattr = object->memattr;
1896 for (m = m_ret; m < &m_ret[npages]; m++) {
1898 m->flags = (m->flags | PG_NODUMP) & flags;
1899 m->busy_lock = busy_lock;
1900 if ((req & VM_ALLOC_WIRED) != 0)
1904 if (object != NULL) {
1905 if (vm_page_insert_after(m, object, pindex, mpred)) {
1906 pagedaemon_wakeup();
1907 if ((req & VM_ALLOC_WIRED) != 0)
1908 atomic_subtract_int(
1909 &vm_cnt.v_wire_count, npages);
1910 KASSERT(m->object == NULL,
1911 ("page %p has object", m));
1913 for (m = m_ret; m < &m_ret[npages]; m++) {
1915 (req & VM_ALLOC_WIRED) != 0)
1917 m->oflags = VPO_UNMANAGED;
1918 m->busy_lock = VPB_UNBUSIED;
1919 /* Don't change PG_ZERO. */
1920 vm_page_free_toq(m);
1922 if (req & VM_ALLOC_WAITFAIL) {
1923 VM_OBJECT_WUNLOCK(object);
1925 VM_OBJECT_WLOCK(object);
1932 if (memattr != VM_MEMATTR_DEFAULT)
1933 pmap_page_set_memattr(m, memattr);
1936 if (vm_paging_needed())
1937 pagedaemon_wakeup();
1942 * Check a page that has been freshly dequeued from a freelist.
1945 vm_page_alloc_check(vm_page_t m)
1948 KASSERT(m->object == NULL, ("page %p has object", m));
1949 KASSERT(m->queue == PQ_NONE,
1950 ("page %p has unexpected queue %d", m, m->queue));
1951 KASSERT(m->wire_count == 0, ("page %p is wired", m));
1952 KASSERT(m->hold_count == 0, ("page %p is held", m));
1953 KASSERT(!vm_page_busied(m), ("page %p is busy", m));
1954 KASSERT(m->dirty == 0, ("page %p is dirty", m));
1955 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1956 ("page %p has unexpected memattr %d",
1957 m, pmap_page_get_memattr(m)));
1958 KASSERT(m->valid == 0, ("free page %p is valid", m));
1962 * vm_page_alloc_freelist:
1964 * Allocate a physical page from the specified free page list.
1966 * The caller must always specify an allocation class.
1968 * allocation classes:
1969 * VM_ALLOC_NORMAL normal process request
1970 * VM_ALLOC_SYSTEM system *really* needs a page
1971 * VM_ALLOC_INTERRUPT interrupt time request
1973 * optional allocation flags:
1974 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1975 * intends to allocate
1976 * VM_ALLOC_WIRED wire the allocated page
1977 * VM_ALLOC_ZERO prefer a zeroed page
1979 * This routine may not sleep.
1982 vm_page_alloc_freelist(int flind, int req)
1988 req_class = req & VM_ALLOC_CLASS_MASK;
1991 * The page daemon is allowed to dig deeper into the free page list.
1993 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1994 req_class = VM_ALLOC_SYSTEM;
1997 * Do not allocate reserved pages unless the req has asked for it.
2000 mtx_lock(&vm_page_queue_free_mtx);
2001 if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
2002 (req_class == VM_ALLOC_SYSTEM &&
2003 vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
2004 (req_class == VM_ALLOC_INTERRUPT &&
2005 vm_cnt.v_free_count > 0)) {
2006 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
2008 if (vm_page_alloc_fail(NULL, req))
2013 mtx_unlock(&vm_page_queue_free_mtx);
2016 vm_phys_freecnt_adj(m, -1);
2017 if ((m->flags & PG_ZERO) != 0)
2018 vm_page_zero_count--;
2019 mtx_unlock(&vm_page_queue_free_mtx);
2020 vm_page_alloc_check(m);
2023 * Initialize the page. Only the PG_ZERO flag is inherited.
2027 if ((req & VM_ALLOC_ZERO) != 0)
2030 if ((req & VM_ALLOC_WIRED) != 0) {
2032 * The page lock is not required for wiring a page that does
2033 * not belong to an object.
2035 atomic_add_int(&vm_cnt.v_wire_count, 1);
2038 /* Unmanaged pages don't use "act_count". */
2039 m->oflags = VPO_UNMANAGED;
2040 if (vm_paging_needed())
2041 pagedaemon_wakeup();
2045 #define VPSC_ANY 0 /* No restrictions. */
2046 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2047 #define VPSC_NOSUPER 2 /* Skip superpages. */
2050 * vm_page_scan_contig:
2052 * Scan vm_page_array[] between the specified entries "m_start" and
2053 * "m_end" for a run of contiguous physical pages that satisfy the
2054 * specified conditions, and return the lowest page in the run. The
2055 * specified "alignment" determines the alignment of the lowest physical
2056 * page in the run. If the specified "boundary" is non-zero, then the
2057 * run of physical pages cannot span a physical address that is a
2058 * multiple of "boundary".
2060 * "m_end" is never dereferenced, so it need not point to a vm_page
2061 * structure within vm_page_array[].
2063 * "npages" must be greater than zero. "m_start" and "m_end" must not
2064 * span a hole (or discontiguity) in the physical address space. Both
2065 * "alignment" and "boundary" must be a power of two.
2068 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2069 u_long alignment, vm_paddr_t boundary, int options)
2075 #if VM_NRESERVLEVEL > 0
2078 int m_inc, order, run_ext, run_len;
2080 KASSERT(npages > 0, ("npages is 0"));
2081 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2082 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2086 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2087 KASSERT((m->flags & PG_MARKER) == 0,
2088 ("page %p is PG_MARKER", m));
2089 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->wire_count == 1,
2090 ("fictitious page %p has invalid wire count", m));
2093 * If the current page would be the start of a run, check its
2094 * physical address against the end, alignment, and boundary
2095 * conditions. If it doesn't satisfy these conditions, either
2096 * terminate the scan or advance to the next page that
2097 * satisfies the failed condition.
2100 KASSERT(m_run == NULL, ("m_run != NULL"));
2101 if (m + npages > m_end)
2103 pa = VM_PAGE_TO_PHYS(m);
2104 if ((pa & (alignment - 1)) != 0) {
2105 m_inc = atop(roundup2(pa, alignment) - pa);
2108 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2110 m_inc = atop(roundup2(pa, boundary) - pa);
2114 KASSERT(m_run != NULL, ("m_run == NULL"));
2116 vm_page_change_lock(m, &m_mtx);
2119 if (m->wire_count != 0 || m->hold_count != 0)
2121 #if VM_NRESERVLEVEL > 0
2122 else if ((level = vm_reserv_level(m)) >= 0 &&
2123 (options & VPSC_NORESERV) != 0) {
2125 /* Advance to the end of the reservation. */
2126 pa = VM_PAGE_TO_PHYS(m);
2127 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2131 else if ((object = m->object) != NULL) {
2133 * The page is considered eligible for relocation if
2134 * and only if it could be laundered or reclaimed by
2137 if (!VM_OBJECT_TRYRLOCK(object)) {
2139 VM_OBJECT_RLOCK(object);
2141 if (m->object != object) {
2143 * The page may have been freed.
2145 VM_OBJECT_RUNLOCK(object);
2147 } else if (m->wire_count != 0 ||
2148 m->hold_count != 0) {
2153 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2154 ("page %p is PG_UNHOLDFREE", m));
2155 /* Don't care: PG_NODUMP, PG_ZERO. */
2156 if (object->type != OBJT_DEFAULT &&
2157 object->type != OBJT_SWAP &&
2158 object->type != OBJT_VNODE) {
2160 #if VM_NRESERVLEVEL > 0
2161 } else if ((options & VPSC_NOSUPER) != 0 &&
2162 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2164 /* Advance to the end of the superpage. */
2165 pa = VM_PAGE_TO_PHYS(m);
2166 m_inc = atop(roundup2(pa + 1,
2167 vm_reserv_size(level)) - pa);
2169 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2170 m->queue != PQ_NONE && !vm_page_busied(m)) {
2172 * The page is allocated but eligible for
2173 * relocation. Extend the current run by one
2176 KASSERT(pmap_page_get_memattr(m) ==
2178 ("page %p has an unexpected memattr", m));
2179 KASSERT((m->oflags & (VPO_SWAPINPROG |
2180 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2181 ("page %p has unexpected oflags", m));
2182 /* Don't care: VPO_NOSYNC. */
2187 VM_OBJECT_RUNLOCK(object);
2188 #if VM_NRESERVLEVEL > 0
2189 } else if (level >= 0) {
2191 * The page is reserved but not yet allocated. In
2192 * other words, it is still free. Extend the current
2197 } else if ((order = m->order) < VM_NFREEORDER) {
2199 * The page is enqueued in the physical memory
2200 * allocator's free page queues. Moreover, it is the
2201 * first page in a power-of-two-sized run of
2202 * contiguous free pages. Add these pages to the end
2203 * of the current run, and jump ahead.
2205 run_ext = 1 << order;
2209 * Skip the page for one of the following reasons: (1)
2210 * It is enqueued in the physical memory allocator's
2211 * free page queues. However, it is not the first
2212 * page in a run of contiguous free pages. (This case
2213 * rarely occurs because the scan is performed in
2214 * ascending order.) (2) It is not reserved, and it is
2215 * transitioning from free to allocated. (Conversely,
2216 * the transition from allocated to free for managed
2217 * pages is blocked by the page lock.) (3) It is
2218 * allocated but not contained by an object and not
2219 * wired, e.g., allocated by Xen's balloon driver.
2225 * Extend or reset the current run of pages.
2240 if (run_len >= npages)
2246 * vm_page_reclaim_run:
2248 * Try to relocate each of the allocated virtual pages within the
2249 * specified run of physical pages to a new physical address. Free the
2250 * physical pages underlying the relocated virtual pages. A virtual page
2251 * is relocatable if and only if it could be laundered or reclaimed by
2252 * the page daemon. Whenever possible, a virtual page is relocated to a
2253 * physical address above "high".
2255 * Returns 0 if every physical page within the run was already free or
2256 * just freed by a successful relocation. Otherwise, returns a non-zero
2257 * value indicating why the last attempt to relocate a virtual page was
2260 * "req_class" must be an allocation class.
2263 vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
2267 struct spglist free;
2270 vm_page_t m, m_end, m_new;
2271 int error, order, req;
2273 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2274 ("req_class is not an allocation class"));
2278 m_end = m_run + npages;
2280 for (; error == 0 && m < m_end; m++) {
2281 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2282 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2285 * Avoid releasing and reacquiring the same page lock.
2287 vm_page_change_lock(m, &m_mtx);
2289 if (m->wire_count != 0 || m->hold_count != 0)
2291 else if ((object = m->object) != NULL) {
2293 * The page is relocated if and only if it could be
2294 * laundered or reclaimed by the page daemon.
2296 if (!VM_OBJECT_TRYWLOCK(object)) {
2298 VM_OBJECT_WLOCK(object);
2300 if (m->object != object) {
2302 * The page may have been freed.
2304 VM_OBJECT_WUNLOCK(object);
2306 } else if (m->wire_count != 0 ||
2307 m->hold_count != 0) {
2312 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2313 ("page %p is PG_UNHOLDFREE", m));
2314 /* Don't care: PG_NODUMP, PG_ZERO. */
2315 if (object->type != OBJT_DEFAULT &&
2316 object->type != OBJT_SWAP &&
2317 object->type != OBJT_VNODE)
2319 else if (object->memattr != VM_MEMATTR_DEFAULT)
2321 else if (m->queue != PQ_NONE && !vm_page_busied(m)) {
2322 KASSERT(pmap_page_get_memattr(m) ==
2324 ("page %p has an unexpected memattr", m));
2325 KASSERT((m->oflags & (VPO_SWAPINPROG |
2326 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2327 ("page %p has unexpected oflags", m));
2328 /* Don't care: VPO_NOSYNC. */
2329 if (m->valid != 0) {
2331 * First, try to allocate a new page
2332 * that is above "high". Failing
2333 * that, try to allocate a new page
2334 * that is below "m_run". Allocate
2335 * the new page between the end of
2336 * "m_run" and "high" only as a last
2339 req = req_class | VM_ALLOC_NOOBJ;
2340 if ((m->flags & PG_NODUMP) != 0)
2341 req |= VM_ALLOC_NODUMP;
2342 if (trunc_page(high) !=
2343 ~(vm_paddr_t)PAGE_MASK) {
2344 m_new = vm_page_alloc_contig(
2349 VM_MEMATTR_DEFAULT);
2352 if (m_new == NULL) {
2353 pa = VM_PAGE_TO_PHYS(m_run);
2354 m_new = vm_page_alloc_contig(
2356 0, pa - 1, PAGE_SIZE, 0,
2357 VM_MEMATTR_DEFAULT);
2359 if (m_new == NULL) {
2361 m_new = vm_page_alloc_contig(
2363 pa, high, PAGE_SIZE, 0,
2364 VM_MEMATTR_DEFAULT);
2366 if (m_new == NULL) {
2370 KASSERT(m_new->wire_count == 0,
2371 ("page %p is wired", m));
2374 * Replace "m" with the new page. For
2375 * vm_page_replace(), "m" must be busy
2376 * and dequeued. Finally, change "m"
2377 * as if vm_page_free() was called.
2379 if (object->ref_count != 0)
2381 m_new->aflags = m->aflags;
2382 KASSERT(m_new->oflags == VPO_UNMANAGED,
2383 ("page %p is managed", m));
2384 m_new->oflags = m->oflags & VPO_NOSYNC;
2385 pmap_copy_page(m, m_new);
2386 m_new->valid = m->valid;
2387 m_new->dirty = m->dirty;
2388 m->flags &= ~PG_ZERO;
2391 vm_page_replace_checked(m_new, object,
2397 * The new page must be deactivated
2398 * before the object is unlocked.
2400 vm_page_change_lock(m_new, &m_mtx);
2401 vm_page_deactivate(m_new);
2403 m->flags &= ~PG_ZERO;
2406 KASSERT(m->dirty == 0,
2407 ("page %p is dirty", m));
2409 SLIST_INSERT_HEAD(&free, m, plinks.s.ss);
2413 VM_OBJECT_WUNLOCK(object);
2415 mtx_lock(&vm_page_queue_free_mtx);
2417 if (order < VM_NFREEORDER) {
2419 * The page is enqueued in the physical memory
2420 * allocator's free page queues. Moreover, it
2421 * is the first page in a power-of-two-sized
2422 * run of contiguous free pages. Jump ahead
2423 * to the last page within that run, and
2424 * continue from there.
2426 m += (1 << order) - 1;
2428 #if VM_NRESERVLEVEL > 0
2429 else if (vm_reserv_is_page_free(m))
2432 mtx_unlock(&vm_page_queue_free_mtx);
2433 if (order == VM_NFREEORDER)
2439 if ((m = SLIST_FIRST(&free)) != NULL) {
2440 mtx_lock(&vm_page_queue_free_mtx);
2442 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2443 vm_page_free_phys(m);
2444 } while ((m = SLIST_FIRST(&free)) != NULL);
2445 vm_page_zero_idle_wakeup();
2446 vm_page_free_wakeup();
2447 mtx_unlock(&vm_page_queue_free_mtx);
2454 CTASSERT(powerof2(NRUNS));
2456 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2458 #define MIN_RECLAIM 8
2461 * vm_page_reclaim_contig:
2463 * Reclaim allocated, contiguous physical memory satisfying the specified
2464 * conditions by relocating the virtual pages using that physical memory.
2465 * Returns true if reclamation is successful and false otherwise. Since
2466 * relocation requires the allocation of physical pages, reclamation may
2467 * fail due to a shortage of free pages. When reclamation fails, callers
2468 * are expected to perform VM_WAIT before retrying a failed allocation
2469 * operation, e.g., vm_page_alloc_contig().
2471 * The caller must always specify an allocation class through "req".
2473 * allocation classes:
2474 * VM_ALLOC_NORMAL normal process request
2475 * VM_ALLOC_SYSTEM system *really* needs a page
2476 * VM_ALLOC_INTERRUPT interrupt time request
2478 * The optional allocation flags are ignored.
2480 * "npages" must be greater than zero. Both "alignment" and "boundary"
2481 * must be a power of two.
2484 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2485 u_long alignment, vm_paddr_t boundary)
2487 vm_paddr_t curr_low;
2488 vm_page_t m_run, m_runs[NRUNS];
2489 u_long count, reclaimed;
2490 int error, i, options, req_class;
2492 KASSERT(npages > 0, ("npages is 0"));
2493 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2494 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2495 req_class = req & VM_ALLOC_CLASS_MASK;
2498 * The page daemon is allowed to dig deeper into the free page list.
2500 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2501 req_class = VM_ALLOC_SYSTEM;
2504 * Return if the number of free pages cannot satisfy the requested
2507 count = vm_cnt.v_free_count;
2508 if (count < npages + vm_cnt.v_free_reserved || (count < npages +
2509 vm_cnt.v_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2510 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2514 * Scan up to three times, relaxing the restrictions ("options") on
2515 * the reclamation of reservations and superpages each time.
2517 for (options = VPSC_NORESERV;;) {
2519 * Find the highest runs that satisfy the given constraints
2520 * and restrictions, and record them in "m_runs".
2525 m_run = vm_phys_scan_contig(npages, curr_low, high,
2526 alignment, boundary, options);
2529 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2530 m_runs[RUN_INDEX(count)] = m_run;
2535 * Reclaim the highest runs in LIFO (descending) order until
2536 * the number of reclaimed pages, "reclaimed", is at least
2537 * MIN_RECLAIM. Reset "reclaimed" each time because each
2538 * reclamation is idempotent, and runs will (likely) recur
2539 * from one scan to the next as restrictions are relaxed.
2542 for (i = 0; count > 0 && i < NRUNS; i++) {
2544 m_run = m_runs[RUN_INDEX(count)];
2545 error = vm_page_reclaim_run(req_class, npages, m_run,
2548 reclaimed += npages;
2549 if (reclaimed >= MIN_RECLAIM)
2555 * Either relax the restrictions on the next scan or return if
2556 * the last scan had no restrictions.
2558 if (options == VPSC_NORESERV)
2559 options = VPSC_NOSUPER;
2560 else if (options == VPSC_NOSUPER)
2562 else if (options == VPSC_ANY)
2563 return (reclaimed != 0);
2568 * vm_wait: (also see VM_WAIT macro)
2570 * Sleep until free pages are available for allocation.
2571 * - Called in various places before memory allocations.
2577 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2578 if (curproc == pageproc) {
2579 vm_pageout_pages_needed = 1;
2580 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
2581 PDROP | PSWP, "VMWait", 0);
2583 if (pageproc == NULL)
2584 panic("vm_wait in early boot");
2585 pagedaemon_wait(PVM, "vmwait");
2593 mtx_lock(&vm_page_queue_free_mtx);
2598 * vm_page_alloc_fail:
2600 * Called when a page allocation function fails. Informs the
2601 * pagedaemon and performs the requested wait. Requires the
2602 * page_queue_free and object lock on entry. Returns with the
2603 * object lock held and free lock released. Returns an error when
2604 * retry is necessary.
2608 vm_page_alloc_fail(vm_object_t object, int req)
2611 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2613 atomic_add_int(&vm_pageout_deficit,
2614 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
2615 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
2617 VM_OBJECT_WUNLOCK(object);
2620 VM_OBJECT_WLOCK(object);
2621 if (req & VM_ALLOC_WAITOK)
2624 mtx_unlock(&vm_page_queue_free_mtx);
2625 pagedaemon_wakeup();
2631 * vm_waitpfault: (also see VM_WAITPFAULT macro)
2633 * Sleep until free pages are available for allocation.
2634 * - Called only in vm_fault so that processes page faulting
2635 * can be easily tracked.
2636 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2637 * processes will be able to grab memory first. Do not change
2638 * this balance without careful testing first.
2644 mtx_lock(&vm_page_queue_free_mtx);
2645 pagedaemon_wait(PUSER, "pfault");
2648 struct vm_pagequeue *
2649 vm_page_pagequeue(vm_page_t m)
2652 if (vm_page_in_laundry(m))
2653 return (&vm_dom[0].vmd_pagequeues[m->queue]);
2655 return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2661 * Remove the given page from its current page queue.
2663 * The page must be locked.
2666 vm_page_dequeue(vm_page_t m)
2668 struct vm_pagequeue *pq;
2670 vm_page_assert_locked(m);
2671 KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
2673 pq = vm_page_pagequeue(m);
2674 vm_pagequeue_lock(pq);
2676 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2677 vm_pagequeue_cnt_dec(pq);
2678 vm_pagequeue_unlock(pq);
2682 * vm_page_dequeue_locked:
2684 * Remove the given page from its current page queue.
2686 * The page and page queue must be locked.
2689 vm_page_dequeue_locked(vm_page_t m)
2691 struct vm_pagequeue *pq;
2693 vm_page_lock_assert(m, MA_OWNED);
2694 pq = vm_page_pagequeue(m);
2695 vm_pagequeue_assert_locked(pq);
2697 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2698 vm_pagequeue_cnt_dec(pq);
2704 * Add the given page to the specified page queue.
2706 * The page must be locked.
2709 vm_page_enqueue(uint8_t queue, vm_page_t m)
2711 struct vm_pagequeue *pq;
2713 vm_page_lock_assert(m, MA_OWNED);
2714 KASSERT(queue < PQ_COUNT,
2715 ("vm_page_enqueue: invalid queue %u request for page %p",
2717 if (queue == PQ_LAUNDRY)
2718 pq = &vm_dom[0].vmd_pagequeues[queue];
2720 pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2721 vm_pagequeue_lock(pq);
2723 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2724 vm_pagequeue_cnt_inc(pq);
2725 vm_pagequeue_unlock(pq);
2731 * Move the given page to the tail of its current page queue.
2733 * The page must be locked.
2736 vm_page_requeue(vm_page_t m)
2738 struct vm_pagequeue *pq;
2740 vm_page_lock_assert(m, MA_OWNED);
2741 KASSERT(m->queue != PQ_NONE,
2742 ("vm_page_requeue: page %p is not queued", m));
2743 pq = vm_page_pagequeue(m);
2744 vm_pagequeue_lock(pq);
2745 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2746 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2747 vm_pagequeue_unlock(pq);
2751 * vm_page_requeue_locked:
2753 * Move the given page to the tail of its current page queue.
2755 * The page queue must be locked.
2758 vm_page_requeue_locked(vm_page_t m)
2760 struct vm_pagequeue *pq;
2762 KASSERT(m->queue != PQ_NONE,
2763 ("vm_page_requeue_locked: page %p is not queued", m));
2764 pq = vm_page_pagequeue(m);
2765 vm_pagequeue_assert_locked(pq);
2766 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2767 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2773 * Put the specified page on the active list (if appropriate).
2774 * Ensure that act_count is at least ACT_INIT but do not otherwise
2777 * The page must be locked.
2780 vm_page_activate(vm_page_t m)
2784 vm_page_lock_assert(m, MA_OWNED);
2785 if ((queue = m->queue) != PQ_ACTIVE) {
2786 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2787 if (m->act_count < ACT_INIT)
2788 m->act_count = ACT_INIT;
2789 if (queue != PQ_NONE)
2791 vm_page_enqueue(PQ_ACTIVE, m);
2793 KASSERT(queue == PQ_NONE,
2794 ("vm_page_activate: wired page %p is queued", m));
2796 if (m->act_count < ACT_INIT)
2797 m->act_count = ACT_INIT;
2802 * vm_page_free_wakeup:
2804 * Helper routine for vm_page_free_toq(). This routine is called
2805 * when a page is added to the free queues.
2807 * The page queues must be locked.
2810 vm_page_free_wakeup(void)
2813 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2815 * if pageout daemon needs pages, then tell it that there are
2818 if (vm_pageout_pages_needed &&
2819 vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
2820 wakeup(&vm_pageout_pages_needed);
2821 vm_pageout_pages_needed = 0;
2824 * wakeup processes that are waiting on memory if we hit a
2825 * high water mark. And wakeup scheduler process if we have
2826 * lots of memory. this process will swapin processes.
2828 if (vm_pages_needed && !vm_page_count_min()) {
2829 vm_pages_needed = false;
2830 wakeup(&vm_cnt.v_free_count);
2835 * vm_page_free_prep:
2837 * Prepares the given page to be put on the free list,
2838 * disassociating it from any VM object. The caller may return
2839 * the page to the free list only if this function returns true.
2841 * The object must be locked. The page must be locked if it is
2842 * managed. For a queued managed page, the pagequeue_locked
2843 * argument specifies whether the page queue is already locked.
2846 vm_page_free_prep(vm_page_t m, bool pagequeue_locked)
2849 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
2850 if ((m->flags & PG_ZERO) != 0) {
2853 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
2854 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
2855 KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
2856 m, i, (uintmax_t)*p));
2859 if ((m->oflags & VPO_UNMANAGED) == 0) {
2860 vm_page_lock_assert(m, MA_OWNED);
2861 KASSERT(!pmap_page_is_mapped(m),
2862 ("vm_page_free_toq: freeing mapped page %p", m));
2864 KASSERT(m->queue == PQ_NONE,
2865 ("vm_page_free_toq: unmanaged page %p is queued", m));
2866 PCPU_INC(cnt.v_tfree);
2868 if (vm_page_sbusied(m))
2869 panic("vm_page_free: freeing busy page %p", m);
2872 * Unqueue, then remove page. Note that we cannot destroy
2873 * the page here because we do not want to call the pager's
2874 * callback routine until after we've put the page on the
2875 * appropriate free queue.
2877 if (m->queue != PQ_NONE) {
2878 if (pagequeue_locked)
2879 vm_page_dequeue_locked(m);
2886 * If fictitious remove object association and
2887 * return, otherwise delay object association removal.
2889 if ((m->flags & PG_FICTITIOUS) != 0)
2895 if (m->wire_count != 0)
2896 panic("vm_page_free: freeing wired page %p", m);
2897 if (m->hold_count != 0) {
2898 m->flags &= ~PG_ZERO;
2899 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2900 ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
2901 m->flags |= PG_UNHOLDFREE;
2906 * Restore the default memory attribute to the page.
2908 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2909 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2915 * Insert the page into the physical memory allocator's free page
2916 * queues. This is the last step to free a page.
2919 vm_page_free_phys(vm_page_t m)
2922 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2924 vm_phys_freecnt_adj(m, 1);
2925 #if VM_NRESERVLEVEL > 0
2926 if (!vm_reserv_free_page(m))
2928 vm_phys_free_pages(m, 0);
2929 if ((m->flags & PG_ZERO) != 0)
2930 ++vm_page_zero_count;
2932 vm_page_zero_idle_wakeup();
2936 vm_page_free_phys_pglist(struct pglist *tq)
2940 if (TAILQ_EMPTY(tq))
2942 mtx_lock(&vm_page_queue_free_mtx);
2943 TAILQ_FOREACH(m, tq, listq)
2944 vm_page_free_phys(m);
2945 vm_page_free_wakeup();
2946 mtx_unlock(&vm_page_queue_free_mtx);
2952 * Returns the given page to the free list, disassociating it
2953 * from any VM object.
2955 * The object must be locked. The page must be locked if it is
2959 vm_page_free_toq(vm_page_t m)
2962 if (!vm_page_free_prep(m, false))
2964 mtx_lock(&vm_page_queue_free_mtx);
2965 vm_page_free_phys(m);
2966 vm_page_free_wakeup();
2967 mtx_unlock(&vm_page_queue_free_mtx);
2973 * Mark this page as wired down by yet
2974 * another map, removing it from paging queues
2977 * If the page is fictitious, then its wire count must remain one.
2979 * The page must be locked.
2982 vm_page_wire(vm_page_t m)
2986 * Only bump the wire statistics if the page is not already wired,
2987 * and only unqueue the page if it is on some queue (if it is unmanaged
2988 * it is already off the queues).
2990 vm_page_lock_assert(m, MA_OWNED);
2991 if ((m->flags & PG_FICTITIOUS) != 0) {
2992 KASSERT(m->wire_count == 1,
2993 ("vm_page_wire: fictitious page %p's wire count isn't one",
2997 if (m->wire_count == 0) {
2998 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
2999 m->queue == PQ_NONE,
3000 ("vm_page_wire: unmanaged page %p is queued", m));
3002 atomic_add_int(&vm_cnt.v_wire_count, 1);
3005 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
3011 * Release one wiring of the specified page, potentially allowing it to be
3012 * paged out. Returns TRUE if the number of wirings transitions to zero and
3015 * Only managed pages belonging to an object can be paged out. If the number
3016 * of wirings transitions to zero and the page is eligible for page out, then
3017 * the page is added to the specified paging queue (unless PQ_NONE is
3020 * If a page is fictitious, then its wire count must always be one.
3022 * A managed page must be locked.
3025 vm_page_unwire(vm_page_t m, uint8_t queue)
3028 KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
3029 ("vm_page_unwire: invalid queue %u request for page %p",
3031 if ((m->oflags & VPO_UNMANAGED) == 0)
3032 vm_page_assert_locked(m);
3033 if ((m->flags & PG_FICTITIOUS) != 0) {
3034 KASSERT(m->wire_count == 1,
3035 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
3038 if (m->wire_count > 0) {
3040 if (m->wire_count == 0) {
3041 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3042 if ((m->oflags & VPO_UNMANAGED) == 0 &&
3043 m->object != NULL && queue != PQ_NONE)
3044 vm_page_enqueue(queue, m);
3049 panic("vm_page_unwire: page %p's wire count is zero", m);
3053 * Move the specified page to the inactive queue.
3055 * Normally, "noreuse" is FALSE, resulting in LRU ordering of the inactive
3056 * queue. However, setting "noreuse" to TRUE will accelerate the specified
3057 * page's reclamation, but it will not unmap the page from any address space.
3058 * This is implemented by inserting the page near the head of the inactive
3059 * queue, using a marker page to guide FIFO insertion ordering.
3061 * The page must be locked.
3064 _vm_page_deactivate(vm_page_t m, boolean_t noreuse)
3066 struct vm_pagequeue *pq;
3069 vm_page_assert_locked(m);
3072 * Ignore if the page is already inactive, unless it is unlikely to be
3075 if ((queue = m->queue) == PQ_INACTIVE && !noreuse)
3077 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
3078 pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
3079 /* Avoid multiple acquisitions of the inactive queue lock. */
3080 if (queue == PQ_INACTIVE) {
3081 vm_pagequeue_lock(pq);
3082 vm_page_dequeue_locked(m);
3084 if (queue != PQ_NONE)
3086 vm_pagequeue_lock(pq);
3088 m->queue = PQ_INACTIVE;
3090 TAILQ_INSERT_BEFORE(&vm_phys_domain(m)->vmd_inacthead,
3093 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3094 vm_pagequeue_cnt_inc(pq);
3095 vm_pagequeue_unlock(pq);
3100 * Move the specified page to the inactive queue.
3102 * The page must be locked.
3105 vm_page_deactivate(vm_page_t m)
3108 _vm_page_deactivate(m, FALSE);
3112 * Move the specified page to the inactive queue with the expectation
3113 * that it is unlikely to be reused.
3115 * The page must be locked.
3118 vm_page_deactivate_noreuse(vm_page_t m)
3121 _vm_page_deactivate(m, TRUE);
3127 * Put a page in the laundry.
3130 vm_page_launder(vm_page_t m)
3134 vm_page_assert_locked(m);
3135 if ((queue = m->queue) != PQ_LAUNDRY) {
3136 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
3137 if (queue != PQ_NONE)
3139 vm_page_enqueue(PQ_LAUNDRY, m);
3141 KASSERT(queue == PQ_NONE,
3142 ("wired page %p is queued", m));
3147 * vm_page_try_to_free()
3149 * Attempt to free the page. If we cannot free it, we do nothing.
3150 * true is returned on success, false on failure.
3153 vm_page_try_to_free(vm_page_t m)
3156 vm_page_assert_locked(m);
3157 if (m->object != NULL)
3158 VM_OBJECT_ASSERT_WLOCKED(m->object);
3159 if (m->dirty != 0 || m->hold_count != 0 || m->wire_count != 0 ||
3160 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
3162 if (m->object != NULL && m->object->ref_count != 0) {
3174 * Apply the specified advice to the given page.
3176 * The object and page must be locked.
3179 vm_page_advise(vm_page_t m, int advice)
3182 vm_page_assert_locked(m);
3183 VM_OBJECT_ASSERT_WLOCKED(m->object);
3184 if (advice == MADV_FREE)
3186 * Mark the page clean. This will allow the page to be freed
3187 * without first paging it out. MADV_FREE pages are often
3188 * quickly reused by malloc(3), so we do not do anything that
3189 * would result in a page fault on a later access.
3192 else if (advice != MADV_DONTNEED) {
3193 if (advice == MADV_WILLNEED)
3194 vm_page_activate(m);
3199 * Clear any references to the page. Otherwise, the page daemon will
3200 * immediately reactivate the page.
3202 vm_page_aflag_clear(m, PGA_REFERENCED);
3204 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3208 * Place clean pages near the head of the inactive queue rather than
3209 * the tail, thus defeating the queue's LRU operation and ensuring that
3210 * the page will be reused quickly. Dirty pages not already in the
3211 * laundry are moved there.
3214 vm_page_deactivate_noreuse(m);
3220 * Grab a page, waiting until we are waken up due to the page
3221 * changing state. We keep on waiting, if the page continues
3222 * to be in the object. If the page doesn't exist, first allocate it
3223 * and then conditionally zero it.
3225 * This routine may sleep.
3227 * The object must be locked on entry. The lock will, however, be released
3228 * and reacquired if the routine sleeps.
3231 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3237 VM_OBJECT_ASSERT_WLOCKED(object);
3238 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3239 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3240 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3241 pflags = allocflags &
3242 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
3243 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3244 pflags |= VM_ALLOC_WAITFAIL;
3246 if ((m = vm_page_lookup(object, pindex)) != NULL) {
3247 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3248 vm_page_xbusied(m) : vm_page_busied(m);
3250 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3253 * Reference the page before unlocking and
3254 * sleeping so that the page daemon is less
3255 * likely to reclaim it.
3257 vm_page_aflag_set(m, PGA_REFERENCED);
3259 VM_OBJECT_WUNLOCK(object);
3260 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
3261 VM_ALLOC_IGN_SBUSY) != 0);
3262 VM_OBJECT_WLOCK(object);
3265 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3271 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3273 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3278 m = vm_page_alloc(object, pindex, pflags);
3280 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3284 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3290 * Return the specified range of pages from the given object. For each
3291 * page offset within the range, if a page already exists within the object
3292 * at that offset and it is busy, then wait for it to change state. If,
3293 * instead, the page doesn't exist, then allocate it.
3295 * The caller must always specify an allocation class.
3297 * allocation classes:
3298 * VM_ALLOC_NORMAL normal process request
3299 * VM_ALLOC_SYSTEM system *really* needs the pages
3301 * The caller must always specify that the pages are to be busied and/or
3304 * optional allocation flags:
3305 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
3306 * VM_ALLOC_NOBUSY do not exclusive busy the page
3307 * VM_ALLOC_NOWAIT do not sleep
3308 * VM_ALLOC_SBUSY set page to sbusy state
3309 * VM_ALLOC_WIRED wire the pages
3310 * VM_ALLOC_ZERO zero and validate any invalid pages
3312 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
3313 * may return a partial prefix of the requested range.
3316 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
3317 vm_page_t *ma, int count)
3324 VM_OBJECT_ASSERT_WLOCKED(object);
3325 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
3326 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
3327 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
3328 (allocflags & VM_ALLOC_WIRED) != 0,
3329 ("vm_page_grab_pages: the pages must be busied or wired"));
3330 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3331 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3332 ("vm_page_grab_pages: VM_ALLOC_SBUSY/IGN_SBUSY mismatch"));
3335 pflags = allocflags & ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK |
3336 VM_ALLOC_WAITFAIL | VM_ALLOC_IGN_SBUSY);
3337 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3338 pflags |= VM_ALLOC_WAITFAIL;
3341 m = vm_radix_lookup_le(&object->rtree, pindex + i);
3342 if (m == NULL || m->pindex != pindex + i) {
3346 mpred = TAILQ_PREV(m, pglist, listq);
3347 for (; i < count; i++) {
3349 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3350 vm_page_xbusied(m) : vm_page_busied(m);
3352 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3355 * Reference the page before unlocking and
3356 * sleeping so that the page daemon is less
3357 * likely to reclaim it.
3359 vm_page_aflag_set(m, PGA_REFERENCED);
3361 VM_OBJECT_WUNLOCK(object);
3362 vm_page_busy_sleep(m, "grbmaw", (allocflags &
3363 VM_ALLOC_IGN_SBUSY) != 0);
3364 VM_OBJECT_WLOCK(object);
3367 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3372 if ((allocflags & (VM_ALLOC_NOBUSY |
3373 VM_ALLOC_SBUSY)) == 0)
3375 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3378 m = vm_page_alloc_after(object, pindex + i,
3379 pflags | VM_ALLOC_COUNT(count - i), mpred);
3381 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3386 if (m->valid == 0 && (allocflags & VM_ALLOC_ZERO) != 0) {
3387 if ((m->flags & PG_ZERO) == 0)
3389 m->valid = VM_PAGE_BITS_ALL;
3392 m = vm_page_next(m);
3398 * Mapping function for valid or dirty bits in a page.
3400 * Inputs are required to range within a page.
3403 vm_page_bits(int base, int size)
3409 base + size <= PAGE_SIZE,
3410 ("vm_page_bits: illegal base/size %d/%d", base, size)
3413 if (size == 0) /* handle degenerate case */
3416 first_bit = base >> DEV_BSHIFT;
3417 last_bit = (base + size - 1) >> DEV_BSHIFT;
3419 return (((vm_page_bits_t)2 << last_bit) -
3420 ((vm_page_bits_t)1 << first_bit));
3424 * vm_page_set_valid_range:
3426 * Sets portions of a page valid. The arguments are expected
3427 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3428 * of any partial chunks touched by the range. The invalid portion of
3429 * such chunks will be zeroed.
3431 * (base + size) must be less then or equal to PAGE_SIZE.
3434 vm_page_set_valid_range(vm_page_t m, int base, int size)
3438 VM_OBJECT_ASSERT_WLOCKED(m->object);
3439 if (size == 0) /* handle degenerate case */
3443 * If the base is not DEV_BSIZE aligned and the valid
3444 * bit is clear, we have to zero out a portion of the
3447 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3448 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
3449 pmap_zero_page_area(m, frag, base - frag);
3452 * If the ending offset is not DEV_BSIZE aligned and the
3453 * valid bit is clear, we have to zero out a portion of
3456 endoff = base + size;
3457 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3458 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
3459 pmap_zero_page_area(m, endoff,
3460 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3463 * Assert that no previously invalid block that is now being validated
3466 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
3467 ("vm_page_set_valid_range: page %p is dirty", m));
3470 * Set valid bits inclusive of any overlap.
3472 m->valid |= vm_page_bits(base, size);
3476 * Clear the given bits from the specified page's dirty field.
3478 static __inline void
3479 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
3482 #if PAGE_SIZE < 16384
3487 * If the object is locked and the page is neither exclusive busy nor
3488 * write mapped, then the page's dirty field cannot possibly be
3489 * set by a concurrent pmap operation.
3491 VM_OBJECT_ASSERT_WLOCKED(m->object);
3492 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
3493 m->dirty &= ~pagebits;
3496 * The pmap layer can call vm_page_dirty() without
3497 * holding a distinguished lock. The combination of
3498 * the object's lock and an atomic operation suffice
3499 * to guarantee consistency of the page dirty field.
3501 * For PAGE_SIZE == 32768 case, compiler already
3502 * properly aligns the dirty field, so no forcible
3503 * alignment is needed. Only require existence of
3504 * atomic_clear_64 when page size is 32768.
3506 addr = (uintptr_t)&m->dirty;
3507 #if PAGE_SIZE == 32768
3508 atomic_clear_64((uint64_t *)addr, pagebits);
3509 #elif PAGE_SIZE == 16384
3510 atomic_clear_32((uint32_t *)addr, pagebits);
3511 #else /* PAGE_SIZE <= 8192 */
3513 * Use a trick to perform a 32-bit atomic on the
3514 * containing aligned word, to not depend on the existence
3515 * of atomic_clear_{8, 16}.
3517 shift = addr & (sizeof(uint32_t) - 1);
3518 #if BYTE_ORDER == BIG_ENDIAN
3519 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
3523 addr &= ~(sizeof(uint32_t) - 1);
3524 atomic_clear_32((uint32_t *)addr, pagebits << shift);
3525 #endif /* PAGE_SIZE */
3530 * vm_page_set_validclean:
3532 * Sets portions of a page valid and clean. The arguments are expected
3533 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3534 * of any partial chunks touched by the range. The invalid portion of
3535 * such chunks will be zero'd.
3537 * (base + size) must be less then or equal to PAGE_SIZE.
3540 vm_page_set_validclean(vm_page_t m, int base, int size)
3542 vm_page_bits_t oldvalid, pagebits;
3545 VM_OBJECT_ASSERT_WLOCKED(m->object);
3546 if (size == 0) /* handle degenerate case */
3550 * If the base is not DEV_BSIZE aligned and the valid
3551 * bit is clear, we have to zero out a portion of the
3554 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3555 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
3556 pmap_zero_page_area(m, frag, base - frag);
3559 * If the ending offset is not DEV_BSIZE aligned and the
3560 * valid bit is clear, we have to zero out a portion of
3563 endoff = base + size;
3564 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3565 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
3566 pmap_zero_page_area(m, endoff,
3567 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3570 * Set valid, clear dirty bits. If validating the entire
3571 * page we can safely clear the pmap modify bit. We also
3572 * use this opportunity to clear the VPO_NOSYNC flag. If a process
3573 * takes a write fault on a MAP_NOSYNC memory area the flag will
3576 * We set valid bits inclusive of any overlap, but we can only
3577 * clear dirty bits for DEV_BSIZE chunks that are fully within
3580 oldvalid = m->valid;
3581 pagebits = vm_page_bits(base, size);
3582 m->valid |= pagebits;
3584 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
3585 frag = DEV_BSIZE - frag;
3591 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
3593 if (base == 0 && size == PAGE_SIZE) {
3595 * The page can only be modified within the pmap if it is
3596 * mapped, and it can only be mapped if it was previously
3599 if (oldvalid == VM_PAGE_BITS_ALL)
3601 * Perform the pmap_clear_modify() first. Otherwise,
3602 * a concurrent pmap operation, such as
3603 * pmap_protect(), could clear a modification in the
3604 * pmap and set the dirty field on the page before
3605 * pmap_clear_modify() had begun and after the dirty
3606 * field was cleared here.
3608 pmap_clear_modify(m);
3610 m->oflags &= ~VPO_NOSYNC;
3611 } else if (oldvalid != VM_PAGE_BITS_ALL)
3612 m->dirty &= ~pagebits;
3614 vm_page_clear_dirty_mask(m, pagebits);
3618 vm_page_clear_dirty(vm_page_t m, int base, int size)
3621 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
3625 * vm_page_set_invalid:
3627 * Invalidates DEV_BSIZE'd chunks within a page. Both the
3628 * valid and dirty bits for the effected areas are cleared.
3631 vm_page_set_invalid(vm_page_t m, int base, int size)
3633 vm_page_bits_t bits;
3637 VM_OBJECT_ASSERT_WLOCKED(object);
3638 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
3639 size >= object->un_pager.vnp.vnp_size)
3640 bits = VM_PAGE_BITS_ALL;
3642 bits = vm_page_bits(base, size);
3643 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
3646 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3647 !pmap_page_is_mapped(m),
3648 ("vm_page_set_invalid: page %p is mapped", m));
3654 * vm_page_zero_invalid()
3656 * The kernel assumes that the invalid portions of a page contain
3657 * garbage, but such pages can be mapped into memory by user code.
3658 * When this occurs, we must zero out the non-valid portions of the
3659 * page so user code sees what it expects.
3661 * Pages are most often semi-valid when the end of a file is mapped
3662 * into memory and the file's size is not page aligned.
3665 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3670 VM_OBJECT_ASSERT_WLOCKED(m->object);
3672 * Scan the valid bits looking for invalid sections that
3673 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
3674 * valid bit may be set ) have already been zeroed by
3675 * vm_page_set_validclean().
3677 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3678 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3679 (m->valid & ((vm_page_bits_t)1 << i))) {
3681 pmap_zero_page_area(m,
3682 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3689 * setvalid is TRUE when we can safely set the zero'd areas
3690 * as being valid. We can do this if there are no cache consistancy
3691 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3694 m->valid = VM_PAGE_BITS_ALL;
3700 * Is (partial) page valid? Note that the case where size == 0
3701 * will return FALSE in the degenerate case where the page is
3702 * entirely invalid, and TRUE otherwise.
3705 vm_page_is_valid(vm_page_t m, int base, int size)
3707 vm_page_bits_t bits;
3709 VM_OBJECT_ASSERT_LOCKED(m->object);
3710 bits = vm_page_bits(base, size);
3711 return (m->valid != 0 && (m->valid & bits) == bits);
3715 * Returns true if all of the specified predicates are true for the entire
3716 * (super)page and false otherwise.
3719 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
3725 VM_OBJECT_ASSERT_LOCKED(object);
3726 npages = atop(pagesizes[m->psind]);
3729 * The physically contiguous pages that make up a superpage, i.e., a
3730 * page with a page size index ("psind") greater than zero, will
3731 * occupy adjacent entries in vm_page_array[].
3733 for (i = 0; i < npages; i++) {
3734 /* Always test object consistency, including "skip_m". */
3735 if (m[i].object != object)
3737 if (&m[i] == skip_m)
3739 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
3741 if ((flags & PS_ALL_DIRTY) != 0) {
3743 * Calling vm_page_test_dirty() or pmap_is_modified()
3744 * might stop this case from spuriously returning
3745 * "false". However, that would require a write lock
3746 * on the object containing "m[i]".
3748 if (m[i].dirty != VM_PAGE_BITS_ALL)
3751 if ((flags & PS_ALL_VALID) != 0 &&
3752 m[i].valid != VM_PAGE_BITS_ALL)
3759 * Set the page's dirty bits if the page is modified.
3762 vm_page_test_dirty(vm_page_t m)
3765 VM_OBJECT_ASSERT_WLOCKED(m->object);
3766 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3771 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3774 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3778 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3781 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3785 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3788 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3791 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3793 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3796 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3800 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3803 mtx_assert_(vm_page_lockptr(m), a, file, line);
3809 vm_page_object_lock_assert(vm_page_t m)
3813 * Certain of the page's fields may only be modified by the
3814 * holder of the containing object's lock or the exclusive busy.
3815 * holder. Unfortunately, the holder of the write busy is
3816 * not recorded, and thus cannot be checked here.
3818 if (m->object != NULL && !vm_page_xbusied(m))
3819 VM_OBJECT_ASSERT_WLOCKED(m->object);
3823 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3826 if ((bits & PGA_WRITEABLE) == 0)
3830 * The PGA_WRITEABLE flag can only be set if the page is
3831 * managed, is exclusively busied or the object is locked.
3832 * Currently, this flag is only set by pmap_enter().
3834 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3835 ("PGA_WRITEABLE on unmanaged page"));
3836 if (!vm_page_xbusied(m))
3837 VM_OBJECT_ASSERT_LOCKED(m->object);
3841 #include "opt_ddb.h"
3843 #include <sys/kernel.h>
3845 #include <ddb/ddb.h>
3847 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3850 db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
3851 db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
3852 db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
3853 db_printf("vm_cnt.v_laundry_count: %d\n", vm_cnt.v_laundry_count);
3854 db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
3855 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
3856 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
3857 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
3858 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
3861 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3865 db_printf("pq_free %d\n", vm_cnt.v_free_count);
3866 for (dom = 0; dom < vm_ndomains; dom++) {
3868 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d\n",
3870 vm_dom[dom].vmd_page_count,
3871 vm_dom[dom].vmd_free_count,
3872 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3873 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
3874 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt);
3878 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3884 db_printf("show pginfo addr\n");
3888 phys = strchr(modif, 'p') != NULL;
3890 m = PHYS_TO_VM_PAGE(addr);
3892 m = (vm_page_t)addr;
3894 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3895 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3896 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3897 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3898 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);