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;
1606 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1607 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1608 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1609 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1610 ("inconsistent object(%p)/req(%x)", object, req));
1611 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1612 ("Can't sleep and retry object insertion."));
1613 KASSERT(mpred == NULL || mpred->pindex < pindex,
1614 ("mpred %p doesn't precede pindex 0x%jx", mpred,
1615 (uintmax_t)pindex));
1617 VM_OBJECT_ASSERT_WLOCKED(object);
1619 if (__predict_false((req & VM_ALLOC_IFCACHED) != 0))
1622 req_class = req & VM_ALLOC_CLASS_MASK;
1625 * The page daemon is allowed to dig deeper into the free page list.
1627 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1628 req_class = VM_ALLOC_SYSTEM;
1631 * Allocate a page if the number of free pages exceeds the minimum
1632 * for the request class.
1635 mtx_lock(&vm_page_queue_free_mtx);
1636 if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
1637 (req_class == VM_ALLOC_SYSTEM &&
1638 vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
1639 (req_class == VM_ALLOC_INTERRUPT &&
1640 vm_cnt.v_free_count > 0)) {
1642 * Can we allocate the page from a reservation?
1644 #if VM_NRESERVLEVEL > 0
1645 if (object == NULL || (object->flags & (OBJ_COLORED |
1646 OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1647 vm_reserv_alloc_page(object, pindex, mpred)) == NULL)
1651 * If not, allocate it from the free page queues.
1653 m = vm_phys_alloc_pages(object != NULL ?
1654 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1655 #if VM_NRESERVLEVEL > 0
1656 if (m == NULL && vm_reserv_reclaim_inactive()) {
1657 m = vm_phys_alloc_pages(object != NULL ?
1658 VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1665 * Not allocatable, give up.
1667 if (vm_page_alloc_fail(object, req))
1673 * At this point we had better have found a good page.
1675 KASSERT(m != NULL, ("missing page"));
1676 free_count = vm_phys_freecnt_adj(m, -1);
1677 if ((m->flags & PG_ZERO) != 0)
1678 vm_page_zero_count--;
1679 mtx_unlock(&vm_page_queue_free_mtx);
1680 vm_page_alloc_check(m);
1683 * Initialize the page. Only the PG_ZERO flag is inherited.
1686 if ((req & VM_ALLOC_ZERO) != 0)
1689 if ((req & VM_ALLOC_NODUMP) != 0)
1693 m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1695 m->busy_lock = VPB_UNBUSIED;
1696 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1697 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1698 if ((req & VM_ALLOC_SBUSY) != 0)
1699 m->busy_lock = VPB_SHARERS_WORD(1);
1700 if (req & VM_ALLOC_WIRED) {
1702 * The page lock is not required for wiring a page until that
1703 * page is inserted into the object.
1705 atomic_add_int(&vm_cnt.v_wire_count, 1);
1710 if (object != NULL) {
1711 if (vm_page_insert_after(m, object, pindex, mpred)) {
1712 pagedaemon_wakeup();
1713 if (req & VM_ALLOC_WIRED) {
1714 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1717 KASSERT(m->object == NULL, ("page %p has object", m));
1718 m->oflags = VPO_UNMANAGED;
1719 m->busy_lock = VPB_UNBUSIED;
1720 /* Don't change PG_ZERO. */
1721 vm_page_free_toq(m);
1722 if (req & VM_ALLOC_WAITFAIL) {
1723 VM_OBJECT_WUNLOCK(object);
1725 VM_OBJECT_WLOCK(object);
1730 /* Ignore device objects; the pager sets "memattr" for them. */
1731 if (object->memattr != VM_MEMATTR_DEFAULT &&
1732 (object->flags & OBJ_FICTITIOUS) == 0)
1733 pmap_page_set_memattr(m, object->memattr);
1738 * Don't wakeup too often - wakeup the pageout daemon when
1739 * we would be nearly out of memory.
1741 if (vm_paging_needed(free_count))
1742 pagedaemon_wakeup();
1748 * vm_page_alloc_contig:
1750 * Allocate a contiguous set of physical pages of the given size "npages"
1751 * from the free lists. All of the physical pages must be at or above
1752 * the given physical address "low" and below the given physical address
1753 * "high". The given value "alignment" determines the alignment of the
1754 * first physical page in the set. If the given value "boundary" is
1755 * non-zero, then the set of physical pages cannot cross any physical
1756 * address boundary that is a multiple of that value. Both "alignment"
1757 * and "boundary" must be a power of two.
1759 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1760 * then the memory attribute setting for the physical pages is configured
1761 * to the object's memory attribute setting. Otherwise, the memory
1762 * attribute setting for the physical pages is configured to "memattr",
1763 * overriding the object's memory attribute setting. However, if the
1764 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1765 * memory attribute setting for the physical pages cannot be configured
1766 * to VM_MEMATTR_DEFAULT.
1768 * The specified object may not contain fictitious pages.
1770 * The caller must always specify an allocation class.
1772 * allocation classes:
1773 * VM_ALLOC_NORMAL normal process request
1774 * VM_ALLOC_SYSTEM system *really* needs a page
1775 * VM_ALLOC_INTERRUPT interrupt time request
1777 * optional allocation flags:
1778 * VM_ALLOC_NOBUSY do not exclusive busy the page
1779 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
1780 * VM_ALLOC_NOOBJ page is not associated with an object and
1781 * should not be exclusive busy
1782 * VM_ALLOC_SBUSY shared busy the allocated page
1783 * VM_ALLOC_WIRED wire the allocated page
1784 * VM_ALLOC_ZERO prefer a zeroed page
1786 * This routine may not sleep.
1789 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1790 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1791 vm_paddr_t boundary, vm_memattr_t memattr)
1793 vm_page_t m, m_ret, mpred;
1794 u_int busy_lock, flags, oflags;
1797 mpred = NULL; /* XXX: pacify gcc */
1798 KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1799 (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1800 ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1801 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1802 ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
1804 KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1805 ("Can't sleep and retry object insertion."));
1806 if (object != NULL) {
1807 VM_OBJECT_ASSERT_WLOCKED(object);
1808 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
1809 ("vm_page_alloc_contig: object %p has fictitious pages",
1812 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1813 req_class = req & VM_ALLOC_CLASS_MASK;
1816 * The page daemon is allowed to dig deeper into the free page list.
1818 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1819 req_class = VM_ALLOC_SYSTEM;
1821 if (object != NULL) {
1822 mpred = vm_radix_lookup_le(&object->rtree, pindex);
1823 KASSERT(mpred == NULL || mpred->pindex != pindex,
1824 ("vm_page_alloc_contig: pindex already allocated"));
1828 * Can we allocate the pages without the number of free pages falling
1829 * below the lower bound for the allocation class?
1832 mtx_lock(&vm_page_queue_free_mtx);
1833 if (vm_cnt.v_free_count >= npages + vm_cnt.v_free_reserved ||
1834 (req_class == VM_ALLOC_SYSTEM &&
1835 vm_cnt.v_free_count >= npages + vm_cnt.v_interrupt_free_min) ||
1836 (req_class == VM_ALLOC_INTERRUPT &&
1837 vm_cnt.v_free_count >= npages)) {
1839 * Can we allocate the pages from a reservation?
1841 #if VM_NRESERVLEVEL > 0
1843 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1844 (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1845 low, high, alignment, boundary, mpred)) == NULL)
1848 * If not, allocate them from the free page queues.
1850 m_ret = vm_phys_alloc_contig(npages, low, high,
1851 alignment, boundary);
1853 if (vm_page_alloc_fail(object, req))
1857 if (m_ret != NULL) {
1858 vm_phys_freecnt_adj(m_ret, -npages);
1859 for (m = m_ret; m < &m_ret[npages]; m++)
1860 if ((m->flags & PG_ZERO) != 0)
1861 vm_page_zero_count--;
1863 #if VM_NRESERVLEVEL > 0
1864 if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1869 mtx_unlock(&vm_page_queue_free_mtx);
1872 for (m = m_ret; m < &m_ret[npages]; m++)
1873 vm_page_alloc_check(m);
1876 * Initialize the pages. Only the PG_ZERO flag is inherited.
1879 if ((req & VM_ALLOC_ZERO) != 0)
1881 if ((req & VM_ALLOC_NODUMP) != 0)
1883 oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1885 busy_lock = VPB_UNBUSIED;
1886 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1887 busy_lock = VPB_SINGLE_EXCLUSIVER;
1888 if ((req & VM_ALLOC_SBUSY) != 0)
1889 busy_lock = VPB_SHARERS_WORD(1);
1890 if ((req & VM_ALLOC_WIRED) != 0)
1891 atomic_add_int(&vm_cnt.v_wire_count, npages);
1892 if (object != NULL) {
1893 if (object->memattr != VM_MEMATTR_DEFAULT &&
1894 memattr == VM_MEMATTR_DEFAULT)
1895 memattr = object->memattr;
1897 for (m = m_ret; m < &m_ret[npages]; m++) {
1899 m->flags = (m->flags | PG_NODUMP) & flags;
1900 m->busy_lock = busy_lock;
1901 if ((req & VM_ALLOC_WIRED) != 0)
1905 if (object != NULL) {
1906 if (vm_page_insert_after(m, object, pindex, mpred)) {
1907 pagedaemon_wakeup();
1908 if ((req & VM_ALLOC_WIRED) != 0)
1909 atomic_subtract_int(
1910 &vm_cnt.v_wire_count, npages);
1911 KASSERT(m->object == NULL,
1912 ("page %p has object", m));
1914 for (m = m_ret; m < &m_ret[npages]; m++) {
1916 (req & VM_ALLOC_WIRED) != 0)
1918 m->oflags = VPO_UNMANAGED;
1919 m->busy_lock = VPB_UNBUSIED;
1920 /* Don't change PG_ZERO. */
1921 vm_page_free_toq(m);
1923 if (req & VM_ALLOC_WAITFAIL) {
1924 VM_OBJECT_WUNLOCK(object);
1926 VM_OBJECT_WLOCK(object);
1933 if (memattr != VM_MEMATTR_DEFAULT)
1934 pmap_page_set_memattr(m, memattr);
1937 if (vm_paging_needed(vm_cnt.v_free_count))
1938 pagedaemon_wakeup();
1943 * Check a page that has been freshly dequeued from a freelist.
1946 vm_page_alloc_check(vm_page_t m)
1949 KASSERT(m->object == NULL, ("page %p has object", m));
1950 KASSERT(m->queue == PQ_NONE,
1951 ("page %p has unexpected queue %d", m, m->queue));
1952 KASSERT(m->wire_count == 0, ("page %p is wired", m));
1953 KASSERT(m->hold_count == 0, ("page %p is held", m));
1954 KASSERT(!vm_page_busied(m), ("page %p is busy", m));
1955 KASSERT(m->dirty == 0, ("page %p is dirty", m));
1956 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1957 ("page %p has unexpected memattr %d",
1958 m, pmap_page_get_memattr(m)));
1959 KASSERT(m->valid == 0, ("free page %p is valid", m));
1963 * vm_page_alloc_freelist:
1965 * Allocate a physical page from the specified free page list.
1967 * The caller must always specify an allocation class.
1969 * allocation classes:
1970 * VM_ALLOC_NORMAL normal process request
1971 * VM_ALLOC_SYSTEM system *really* needs a page
1972 * VM_ALLOC_INTERRUPT interrupt time request
1974 * optional allocation flags:
1975 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
1976 * intends to allocate
1977 * VM_ALLOC_WIRED wire the allocated page
1978 * VM_ALLOC_ZERO prefer a zeroed page
1980 * This routine may not sleep.
1983 vm_page_alloc_freelist(int flind, int req)
1986 u_int flags, free_count;
1989 req_class = req & VM_ALLOC_CLASS_MASK;
1992 * The page daemon is allowed to dig deeper into the free page list.
1994 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1995 req_class = VM_ALLOC_SYSTEM;
1998 * Do not allocate reserved pages unless the req has asked for it.
2001 mtx_lock(&vm_page_queue_free_mtx);
2002 if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
2003 (req_class == VM_ALLOC_SYSTEM &&
2004 vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
2005 (req_class == VM_ALLOC_INTERRUPT &&
2006 vm_cnt.v_free_count > 0)) {
2007 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
2009 if (vm_page_alloc_fail(NULL, req))
2014 mtx_unlock(&vm_page_queue_free_mtx);
2017 free_count = vm_phys_freecnt_adj(m, -1);
2018 if ((m->flags & PG_ZERO) != 0)
2019 vm_page_zero_count--;
2020 mtx_unlock(&vm_page_queue_free_mtx);
2021 vm_page_alloc_check(m);
2024 * Initialize the page. Only the PG_ZERO flag is inherited.
2028 if ((req & VM_ALLOC_ZERO) != 0)
2031 if ((req & VM_ALLOC_WIRED) != 0) {
2033 * The page lock is not required for wiring a page that does
2034 * not belong to an object.
2036 atomic_add_int(&vm_cnt.v_wire_count, 1);
2039 /* Unmanaged pages don't use "act_count". */
2040 m->oflags = VPO_UNMANAGED;
2041 if (vm_paging_needed(free_count))
2042 pagedaemon_wakeup();
2046 #define VPSC_ANY 0 /* No restrictions. */
2047 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2048 #define VPSC_NOSUPER 2 /* Skip superpages. */
2051 * vm_page_scan_contig:
2053 * Scan vm_page_array[] between the specified entries "m_start" and
2054 * "m_end" for a run of contiguous physical pages that satisfy the
2055 * specified conditions, and return the lowest page in the run. The
2056 * specified "alignment" determines the alignment of the lowest physical
2057 * page in the run. If the specified "boundary" is non-zero, then the
2058 * run of physical pages cannot span a physical address that is a
2059 * multiple of "boundary".
2061 * "m_end" is never dereferenced, so it need not point to a vm_page
2062 * structure within vm_page_array[].
2064 * "npages" must be greater than zero. "m_start" and "m_end" must not
2065 * span a hole (or discontiguity) in the physical address space. Both
2066 * "alignment" and "boundary" must be a power of two.
2069 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2070 u_long alignment, vm_paddr_t boundary, int options)
2076 #if VM_NRESERVLEVEL > 0
2079 int m_inc, order, run_ext, run_len;
2081 KASSERT(npages > 0, ("npages is 0"));
2082 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2083 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2087 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2088 KASSERT((m->flags & PG_MARKER) == 0,
2089 ("page %p is PG_MARKER", m));
2090 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->wire_count == 1,
2091 ("fictitious page %p has invalid wire count", m));
2094 * If the current page would be the start of a run, check its
2095 * physical address against the end, alignment, and boundary
2096 * conditions. If it doesn't satisfy these conditions, either
2097 * terminate the scan or advance to the next page that
2098 * satisfies the failed condition.
2101 KASSERT(m_run == NULL, ("m_run != NULL"));
2102 if (m + npages > m_end)
2104 pa = VM_PAGE_TO_PHYS(m);
2105 if ((pa & (alignment - 1)) != 0) {
2106 m_inc = atop(roundup2(pa, alignment) - pa);
2109 if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2111 m_inc = atop(roundup2(pa, boundary) - pa);
2115 KASSERT(m_run != NULL, ("m_run == NULL"));
2117 vm_page_change_lock(m, &m_mtx);
2120 if (m->wire_count != 0 || m->hold_count != 0)
2122 #if VM_NRESERVLEVEL > 0
2123 else if ((level = vm_reserv_level(m)) >= 0 &&
2124 (options & VPSC_NORESERV) != 0) {
2126 /* Advance to the end of the reservation. */
2127 pa = VM_PAGE_TO_PHYS(m);
2128 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2132 else if ((object = m->object) != NULL) {
2134 * The page is considered eligible for relocation if
2135 * and only if it could be laundered or reclaimed by
2138 if (!VM_OBJECT_TRYRLOCK(object)) {
2140 VM_OBJECT_RLOCK(object);
2142 if (m->object != object) {
2144 * The page may have been freed.
2146 VM_OBJECT_RUNLOCK(object);
2148 } else if (m->wire_count != 0 ||
2149 m->hold_count != 0) {
2154 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2155 ("page %p is PG_UNHOLDFREE", m));
2156 /* Don't care: PG_NODUMP, PG_ZERO. */
2157 if (object->type != OBJT_DEFAULT &&
2158 object->type != OBJT_SWAP &&
2159 object->type != OBJT_VNODE) {
2161 #if VM_NRESERVLEVEL > 0
2162 } else if ((options & VPSC_NOSUPER) != 0 &&
2163 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2165 /* Advance to the end of the superpage. */
2166 pa = VM_PAGE_TO_PHYS(m);
2167 m_inc = atop(roundup2(pa + 1,
2168 vm_reserv_size(level)) - pa);
2170 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2171 m->queue != PQ_NONE && !vm_page_busied(m)) {
2173 * The page is allocated but eligible for
2174 * relocation. Extend the current run by one
2177 KASSERT(pmap_page_get_memattr(m) ==
2179 ("page %p has an unexpected memattr", m));
2180 KASSERT((m->oflags & (VPO_SWAPINPROG |
2181 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2182 ("page %p has unexpected oflags", m));
2183 /* Don't care: VPO_NOSYNC. */
2188 VM_OBJECT_RUNLOCK(object);
2189 #if VM_NRESERVLEVEL > 0
2190 } else if (level >= 0) {
2192 * The page is reserved but not yet allocated. In
2193 * other words, it is still free. Extend the current
2198 } else if ((order = m->order) < VM_NFREEORDER) {
2200 * The page is enqueued in the physical memory
2201 * allocator's free page queues. Moreover, it is the
2202 * first page in a power-of-two-sized run of
2203 * contiguous free pages. Add these pages to the end
2204 * of the current run, and jump ahead.
2206 run_ext = 1 << order;
2210 * Skip the page for one of the following reasons: (1)
2211 * It is enqueued in the physical memory allocator's
2212 * free page queues. However, it is not the first
2213 * page in a run of contiguous free pages. (This case
2214 * rarely occurs because the scan is performed in
2215 * ascending order.) (2) It is not reserved, and it is
2216 * transitioning from free to allocated. (Conversely,
2217 * the transition from allocated to free for managed
2218 * pages is blocked by the page lock.) (3) It is
2219 * allocated but not contained by an object and not
2220 * wired, e.g., allocated by Xen's balloon driver.
2226 * Extend or reset the current run of pages.
2241 if (run_len >= npages)
2247 * vm_page_reclaim_run:
2249 * Try to relocate each of the allocated virtual pages within the
2250 * specified run of physical pages to a new physical address. Free the
2251 * physical pages underlying the relocated virtual pages. A virtual page
2252 * is relocatable if and only if it could be laundered or reclaimed by
2253 * the page daemon. Whenever possible, a virtual page is relocated to a
2254 * physical address above "high".
2256 * Returns 0 if every physical page within the run was already free or
2257 * just freed by a successful relocation. Otherwise, returns a non-zero
2258 * value indicating why the last attempt to relocate a virtual page was
2261 * "req_class" must be an allocation class.
2264 vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
2268 struct spglist free;
2271 vm_page_t m, m_end, m_new;
2272 int error, order, req;
2274 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2275 ("req_class is not an allocation class"));
2279 m_end = m_run + npages;
2281 for (; error == 0 && m < m_end; m++) {
2282 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2283 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2286 * Avoid releasing and reacquiring the same page lock.
2288 vm_page_change_lock(m, &m_mtx);
2290 if (m->wire_count != 0 || m->hold_count != 0)
2292 else if ((object = m->object) != NULL) {
2294 * The page is relocated if and only if it could be
2295 * laundered or reclaimed by the page daemon.
2297 if (!VM_OBJECT_TRYWLOCK(object)) {
2299 VM_OBJECT_WLOCK(object);
2301 if (m->object != object) {
2303 * The page may have been freed.
2305 VM_OBJECT_WUNLOCK(object);
2307 } else if (m->wire_count != 0 ||
2308 m->hold_count != 0) {
2313 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2314 ("page %p is PG_UNHOLDFREE", m));
2315 /* Don't care: PG_NODUMP, PG_ZERO. */
2316 if (object->type != OBJT_DEFAULT &&
2317 object->type != OBJT_SWAP &&
2318 object->type != OBJT_VNODE)
2320 else if (object->memattr != VM_MEMATTR_DEFAULT)
2322 else if (m->queue != PQ_NONE && !vm_page_busied(m)) {
2323 KASSERT(pmap_page_get_memattr(m) ==
2325 ("page %p has an unexpected memattr", m));
2326 KASSERT((m->oflags & (VPO_SWAPINPROG |
2327 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2328 ("page %p has unexpected oflags", m));
2329 /* Don't care: VPO_NOSYNC. */
2330 if (m->valid != 0) {
2332 * First, try to allocate a new page
2333 * that is above "high". Failing
2334 * that, try to allocate a new page
2335 * that is below "m_run". Allocate
2336 * the new page between the end of
2337 * "m_run" and "high" only as a last
2340 req = req_class | VM_ALLOC_NOOBJ;
2341 if ((m->flags & PG_NODUMP) != 0)
2342 req |= VM_ALLOC_NODUMP;
2343 if (trunc_page(high) !=
2344 ~(vm_paddr_t)PAGE_MASK) {
2345 m_new = vm_page_alloc_contig(
2350 VM_MEMATTR_DEFAULT);
2353 if (m_new == NULL) {
2354 pa = VM_PAGE_TO_PHYS(m_run);
2355 m_new = vm_page_alloc_contig(
2357 0, pa - 1, PAGE_SIZE, 0,
2358 VM_MEMATTR_DEFAULT);
2360 if (m_new == NULL) {
2362 m_new = vm_page_alloc_contig(
2364 pa, high, PAGE_SIZE, 0,
2365 VM_MEMATTR_DEFAULT);
2367 if (m_new == NULL) {
2371 KASSERT(m_new->wire_count == 0,
2372 ("page %p is wired", m));
2375 * Replace "m" with the new page. For
2376 * vm_page_replace(), "m" must be busy
2377 * and dequeued. Finally, change "m"
2378 * as if vm_page_free() was called.
2380 if (object->ref_count != 0)
2382 m_new->aflags = m->aflags;
2383 KASSERT(m_new->oflags == VPO_UNMANAGED,
2384 ("page %p is managed", m));
2385 m_new->oflags = m->oflags & VPO_NOSYNC;
2386 pmap_copy_page(m, m_new);
2387 m_new->valid = m->valid;
2388 m_new->dirty = m->dirty;
2389 m->flags &= ~PG_ZERO;
2392 vm_page_replace_checked(m_new, object,
2398 * The new page must be deactivated
2399 * before the object is unlocked.
2401 vm_page_change_lock(m_new, &m_mtx);
2402 vm_page_deactivate(m_new);
2404 m->flags &= ~PG_ZERO;
2407 KASSERT(m->dirty == 0,
2408 ("page %p is dirty", m));
2410 SLIST_INSERT_HEAD(&free, m, plinks.s.ss);
2414 VM_OBJECT_WUNLOCK(object);
2416 mtx_lock(&vm_page_queue_free_mtx);
2418 if (order < VM_NFREEORDER) {
2420 * The page is enqueued in the physical memory
2421 * allocator's free page queues. Moreover, it
2422 * is the first page in a power-of-two-sized
2423 * run of contiguous free pages. Jump ahead
2424 * to the last page within that run, and
2425 * continue from there.
2427 m += (1 << order) - 1;
2429 #if VM_NRESERVLEVEL > 0
2430 else if (vm_reserv_is_page_free(m))
2433 mtx_unlock(&vm_page_queue_free_mtx);
2434 if (order == VM_NFREEORDER)
2440 if ((m = SLIST_FIRST(&free)) != NULL) {
2441 mtx_lock(&vm_page_queue_free_mtx);
2443 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2444 vm_page_free_phys(m);
2445 } while ((m = SLIST_FIRST(&free)) != NULL);
2446 vm_page_zero_idle_wakeup();
2447 vm_page_free_wakeup();
2448 mtx_unlock(&vm_page_queue_free_mtx);
2455 CTASSERT(powerof2(NRUNS));
2457 #define RUN_INDEX(count) ((count) & (NRUNS - 1))
2459 #define MIN_RECLAIM 8
2462 * vm_page_reclaim_contig:
2464 * Reclaim allocated, contiguous physical memory satisfying the specified
2465 * conditions by relocating the virtual pages using that physical memory.
2466 * Returns true if reclamation is successful and false otherwise. Since
2467 * relocation requires the allocation of physical pages, reclamation may
2468 * fail due to a shortage of free pages. When reclamation fails, callers
2469 * are expected to perform VM_WAIT before retrying a failed allocation
2470 * operation, e.g., vm_page_alloc_contig().
2472 * The caller must always specify an allocation class through "req".
2474 * allocation classes:
2475 * VM_ALLOC_NORMAL normal process request
2476 * VM_ALLOC_SYSTEM system *really* needs a page
2477 * VM_ALLOC_INTERRUPT interrupt time request
2479 * The optional allocation flags are ignored.
2481 * "npages" must be greater than zero. Both "alignment" and "boundary"
2482 * must be a power of two.
2485 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2486 u_long alignment, vm_paddr_t boundary)
2488 vm_paddr_t curr_low;
2489 vm_page_t m_run, m_runs[NRUNS];
2490 u_long count, reclaimed;
2491 int error, i, options, req_class;
2493 KASSERT(npages > 0, ("npages is 0"));
2494 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2495 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2496 req_class = req & VM_ALLOC_CLASS_MASK;
2499 * The page daemon is allowed to dig deeper into the free page list.
2501 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2502 req_class = VM_ALLOC_SYSTEM;
2505 * Return if the number of free pages cannot satisfy the requested
2508 count = vm_cnt.v_free_count;
2509 if (count < npages + vm_cnt.v_free_reserved || (count < npages +
2510 vm_cnt.v_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2511 (count < npages && req_class == VM_ALLOC_INTERRUPT))
2515 * Scan up to three times, relaxing the restrictions ("options") on
2516 * the reclamation of reservations and superpages each time.
2518 for (options = VPSC_NORESERV;;) {
2520 * Find the highest runs that satisfy the given constraints
2521 * and restrictions, and record them in "m_runs".
2526 m_run = vm_phys_scan_contig(npages, curr_low, high,
2527 alignment, boundary, options);
2530 curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2531 m_runs[RUN_INDEX(count)] = m_run;
2536 * Reclaim the highest runs in LIFO (descending) order until
2537 * the number of reclaimed pages, "reclaimed", is at least
2538 * MIN_RECLAIM. Reset "reclaimed" each time because each
2539 * reclamation is idempotent, and runs will (likely) recur
2540 * from one scan to the next as restrictions are relaxed.
2543 for (i = 0; count > 0 && i < NRUNS; i++) {
2545 m_run = m_runs[RUN_INDEX(count)];
2546 error = vm_page_reclaim_run(req_class, npages, m_run,
2549 reclaimed += npages;
2550 if (reclaimed >= MIN_RECLAIM)
2556 * Either relax the restrictions on the next scan or return if
2557 * the last scan had no restrictions.
2559 if (options == VPSC_NORESERV)
2560 options = VPSC_NOSUPER;
2561 else if (options == VPSC_NOSUPER)
2563 else if (options == VPSC_ANY)
2564 return (reclaimed != 0);
2569 * vm_wait: (also see VM_WAIT macro)
2571 * Sleep until free pages are available for allocation.
2572 * - Called in various places before memory allocations.
2578 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2579 if (curproc == pageproc) {
2580 vm_pageout_pages_needed = 1;
2581 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
2582 PDROP | PSWP, "VMWait", 0);
2584 if (pageproc == NULL)
2585 panic("vm_wait in early boot");
2586 pagedaemon_wait(PVM, "vmwait");
2594 mtx_lock(&vm_page_queue_free_mtx);
2599 * vm_page_alloc_fail:
2601 * Called when a page allocation function fails. Informs the
2602 * pagedaemon and performs the requested wait. Requires the
2603 * page_queue_free and object lock on entry. Returns with the
2604 * object lock held and free lock released. Returns an error when
2605 * retry is necessary.
2609 vm_page_alloc_fail(vm_object_t object, int req)
2612 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2614 atomic_add_int(&vm_pageout_deficit,
2615 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
2616 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
2618 VM_OBJECT_WUNLOCK(object);
2621 VM_OBJECT_WLOCK(object);
2622 if (req & VM_ALLOC_WAITOK)
2625 mtx_unlock(&vm_page_queue_free_mtx);
2626 pagedaemon_wakeup();
2632 * vm_waitpfault: (also see VM_WAITPFAULT macro)
2634 * Sleep until free pages are available for allocation.
2635 * - Called only in vm_fault so that processes page faulting
2636 * can be easily tracked.
2637 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2638 * processes will be able to grab memory first. Do not change
2639 * this balance without careful testing first.
2645 mtx_lock(&vm_page_queue_free_mtx);
2646 pagedaemon_wait(PUSER, "pfault");
2649 struct vm_pagequeue *
2650 vm_page_pagequeue(vm_page_t m)
2653 if (vm_page_in_laundry(m))
2654 return (&vm_dom[0].vmd_pagequeues[m->queue]);
2656 return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2662 * Remove the given page from its current page queue.
2664 * The page must be locked.
2667 vm_page_dequeue(vm_page_t m)
2669 struct vm_pagequeue *pq;
2671 vm_page_assert_locked(m);
2672 KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
2674 pq = vm_page_pagequeue(m);
2675 vm_pagequeue_lock(pq);
2677 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2678 vm_pagequeue_cnt_dec(pq);
2679 vm_pagequeue_unlock(pq);
2683 * vm_page_dequeue_locked:
2685 * Remove the given page from its current page queue.
2687 * The page and page queue must be locked.
2690 vm_page_dequeue_locked(vm_page_t m)
2692 struct vm_pagequeue *pq;
2694 vm_page_lock_assert(m, MA_OWNED);
2695 pq = vm_page_pagequeue(m);
2696 vm_pagequeue_assert_locked(pq);
2698 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2699 vm_pagequeue_cnt_dec(pq);
2705 * Add the given page to the specified page queue.
2707 * The page must be locked.
2710 vm_page_enqueue(uint8_t queue, vm_page_t m)
2712 struct vm_pagequeue *pq;
2714 vm_page_lock_assert(m, MA_OWNED);
2715 KASSERT(queue < PQ_COUNT,
2716 ("vm_page_enqueue: invalid queue %u request for page %p",
2718 if (queue == PQ_LAUNDRY)
2719 pq = &vm_dom[0].vmd_pagequeues[queue];
2721 pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2722 vm_pagequeue_lock(pq);
2724 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2725 vm_pagequeue_cnt_inc(pq);
2726 vm_pagequeue_unlock(pq);
2732 * Move the given page to the tail of its current page queue.
2734 * The page must be locked.
2737 vm_page_requeue(vm_page_t m)
2739 struct vm_pagequeue *pq;
2741 vm_page_lock_assert(m, MA_OWNED);
2742 KASSERT(m->queue != PQ_NONE,
2743 ("vm_page_requeue: page %p is not queued", m));
2744 pq = vm_page_pagequeue(m);
2745 vm_pagequeue_lock(pq);
2746 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2747 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2748 vm_pagequeue_unlock(pq);
2752 * vm_page_requeue_locked:
2754 * Move the given page to the tail of its current page queue.
2756 * The page queue must be locked.
2759 vm_page_requeue_locked(vm_page_t m)
2761 struct vm_pagequeue *pq;
2763 KASSERT(m->queue != PQ_NONE,
2764 ("vm_page_requeue_locked: page %p is not queued", m));
2765 pq = vm_page_pagequeue(m);
2766 vm_pagequeue_assert_locked(pq);
2767 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2768 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2774 * Put the specified page on the active list (if appropriate).
2775 * Ensure that act_count is at least ACT_INIT but do not otherwise
2778 * The page must be locked.
2781 vm_page_activate(vm_page_t m)
2785 vm_page_lock_assert(m, MA_OWNED);
2786 if ((queue = m->queue) != PQ_ACTIVE) {
2787 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2788 if (m->act_count < ACT_INIT)
2789 m->act_count = ACT_INIT;
2790 if (queue != PQ_NONE)
2792 vm_page_enqueue(PQ_ACTIVE, m);
2794 KASSERT(queue == PQ_NONE,
2795 ("vm_page_activate: wired page %p is queued", m));
2797 if (m->act_count < ACT_INIT)
2798 m->act_count = ACT_INIT;
2803 * vm_page_free_wakeup:
2805 * Helper routine for vm_page_free_toq(). This routine is called
2806 * when a page is added to the free queues.
2808 * The page queues must be locked.
2811 vm_page_free_wakeup(void)
2814 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2816 * if pageout daemon needs pages, then tell it that there are
2819 if (vm_pageout_pages_needed &&
2820 vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
2821 wakeup(&vm_pageout_pages_needed);
2822 vm_pageout_pages_needed = 0;
2825 * wakeup processes that are waiting on memory if we hit a
2826 * high water mark. And wakeup scheduler process if we have
2827 * lots of memory. this process will swapin processes.
2829 if (vm_pages_needed && !vm_page_count_min()) {
2830 vm_pages_needed = false;
2831 wakeup(&vm_cnt.v_free_count);
2836 * vm_page_free_prep:
2838 * Prepares the given page to be put on the free list,
2839 * disassociating it from any VM object. The caller may return
2840 * the page to the free list only if this function returns true.
2842 * The object must be locked. The page must be locked if it is
2843 * managed. For a queued managed page, the pagequeue_locked
2844 * argument specifies whether the page queue is already locked.
2847 vm_page_free_prep(vm_page_t m, bool pagequeue_locked)
2850 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
2851 if ((m->flags & PG_ZERO) != 0) {
2854 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
2855 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
2856 KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
2857 m, i, (uintmax_t)*p));
2860 if ((m->oflags & VPO_UNMANAGED) == 0) {
2861 vm_page_lock_assert(m, MA_OWNED);
2862 KASSERT(!pmap_page_is_mapped(m),
2863 ("vm_page_free_toq: freeing mapped page %p", m));
2865 KASSERT(m->queue == PQ_NONE,
2866 ("vm_page_free_toq: unmanaged page %p is queued", m));
2867 PCPU_INC(cnt.v_tfree);
2869 if (vm_page_sbusied(m))
2870 panic("vm_page_free: freeing busy page %p", m);
2873 * Unqueue, then remove page. Note that we cannot destroy
2874 * the page here because we do not want to call the pager's
2875 * callback routine until after we've put the page on the
2876 * appropriate free queue.
2878 if (m->queue != PQ_NONE) {
2879 if (pagequeue_locked)
2880 vm_page_dequeue_locked(m);
2887 * If fictitious remove object association and
2888 * return, otherwise delay object association removal.
2890 if ((m->flags & PG_FICTITIOUS) != 0)
2896 if (m->wire_count != 0)
2897 panic("vm_page_free: freeing wired page %p", m);
2898 if (m->hold_count != 0) {
2899 m->flags &= ~PG_ZERO;
2900 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2901 ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
2902 m->flags |= PG_UNHOLDFREE;
2907 * Restore the default memory attribute to the page.
2909 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2910 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2916 * Insert the page into the physical memory allocator's free page
2917 * queues. This is the last step to free a page.
2920 vm_page_free_phys(vm_page_t m)
2923 mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2925 vm_phys_freecnt_adj(m, 1);
2926 #if VM_NRESERVLEVEL > 0
2927 if (!vm_reserv_free_page(m))
2929 vm_phys_free_pages(m, 0);
2930 if ((m->flags & PG_ZERO) != 0)
2931 ++vm_page_zero_count;
2933 vm_page_zero_idle_wakeup();
2937 vm_page_free_phys_pglist(struct pglist *tq)
2941 if (TAILQ_EMPTY(tq))
2943 mtx_lock(&vm_page_queue_free_mtx);
2944 TAILQ_FOREACH(m, tq, listq)
2945 vm_page_free_phys(m);
2946 vm_page_free_wakeup();
2947 mtx_unlock(&vm_page_queue_free_mtx);
2953 * Returns the given page to the free list, disassociating it
2954 * from any VM object.
2956 * The object must be locked. The page must be locked if it is
2960 vm_page_free_toq(vm_page_t m)
2963 if (!vm_page_free_prep(m, false))
2965 mtx_lock(&vm_page_queue_free_mtx);
2966 vm_page_free_phys(m);
2967 vm_page_free_wakeup();
2968 mtx_unlock(&vm_page_queue_free_mtx);
2974 * Mark this page as wired down by yet
2975 * another map, removing it from paging queues
2978 * If the page is fictitious, then its wire count must remain one.
2980 * The page must be locked.
2983 vm_page_wire(vm_page_t m)
2987 * Only bump the wire statistics if the page is not already wired,
2988 * and only unqueue the page if it is on some queue (if it is unmanaged
2989 * it is already off the queues).
2991 vm_page_lock_assert(m, MA_OWNED);
2992 if ((m->flags & PG_FICTITIOUS) != 0) {
2993 KASSERT(m->wire_count == 1,
2994 ("vm_page_wire: fictitious page %p's wire count isn't one",
2998 if (m->wire_count == 0) {
2999 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
3000 m->queue == PQ_NONE,
3001 ("vm_page_wire: unmanaged page %p is queued", m));
3003 atomic_add_int(&vm_cnt.v_wire_count, 1);
3006 KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
3012 * Release one wiring of the specified page, potentially allowing it to be
3013 * paged out. Returns TRUE if the number of wirings transitions to zero and
3016 * Only managed pages belonging to an object can be paged out. If the number
3017 * of wirings transitions to zero and the page is eligible for page out, then
3018 * the page is added to the specified paging queue (unless PQ_NONE is
3021 * If a page is fictitious, then its wire count must always be one.
3023 * A managed page must be locked.
3026 vm_page_unwire(vm_page_t m, uint8_t queue)
3029 KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
3030 ("vm_page_unwire: invalid queue %u request for page %p",
3032 if ((m->oflags & VPO_UNMANAGED) == 0)
3033 vm_page_assert_locked(m);
3034 if ((m->flags & PG_FICTITIOUS) != 0) {
3035 KASSERT(m->wire_count == 1,
3036 ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
3039 if (m->wire_count > 0) {
3041 if (m->wire_count == 0) {
3042 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3043 if ((m->oflags & VPO_UNMANAGED) == 0 &&
3044 m->object != NULL && queue != PQ_NONE)
3045 vm_page_enqueue(queue, m);
3050 panic("vm_page_unwire: page %p's wire count is zero", m);
3054 * Move the specified page to the inactive queue.
3056 * Normally, "noreuse" is FALSE, resulting in LRU ordering of the inactive
3057 * queue. However, setting "noreuse" to TRUE will accelerate the specified
3058 * page's reclamation, but it will not unmap the page from any address space.
3059 * This is implemented by inserting the page near the head of the inactive
3060 * queue, using a marker page to guide FIFO insertion ordering.
3062 * The page must be locked.
3065 _vm_page_deactivate(vm_page_t m, boolean_t noreuse)
3067 struct vm_pagequeue *pq;
3070 vm_page_assert_locked(m);
3073 * Ignore if the page is already inactive, unless it is unlikely to be
3076 if ((queue = m->queue) == PQ_INACTIVE && !noreuse)
3078 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
3079 pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
3080 /* Avoid multiple acquisitions of the inactive queue lock. */
3081 if (queue == PQ_INACTIVE) {
3082 vm_pagequeue_lock(pq);
3083 vm_page_dequeue_locked(m);
3085 if (queue != PQ_NONE)
3087 vm_pagequeue_lock(pq);
3089 m->queue = PQ_INACTIVE;
3091 TAILQ_INSERT_BEFORE(&vm_phys_domain(m)->vmd_inacthead,
3094 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3095 vm_pagequeue_cnt_inc(pq);
3096 vm_pagequeue_unlock(pq);
3101 * Move the specified page to the inactive queue.
3103 * The page must be locked.
3106 vm_page_deactivate(vm_page_t m)
3109 _vm_page_deactivate(m, FALSE);
3113 * Move the specified page to the inactive queue with the expectation
3114 * that it is unlikely to be reused.
3116 * The page must be locked.
3119 vm_page_deactivate_noreuse(vm_page_t m)
3122 _vm_page_deactivate(m, TRUE);
3128 * Put a page in the laundry.
3131 vm_page_launder(vm_page_t m)
3135 vm_page_assert_locked(m);
3136 if ((queue = m->queue) != PQ_LAUNDRY) {
3137 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
3138 if (queue != PQ_NONE)
3140 vm_page_enqueue(PQ_LAUNDRY, m);
3142 KASSERT(queue == PQ_NONE,
3143 ("wired page %p is queued", m));
3148 * vm_page_try_to_free()
3150 * Attempt to free the page. If we cannot free it, we do nothing.
3151 * true is returned on success, false on failure.
3154 vm_page_try_to_free(vm_page_t m)
3157 vm_page_assert_locked(m);
3158 if (m->object != NULL)
3159 VM_OBJECT_ASSERT_WLOCKED(m->object);
3160 if (m->dirty != 0 || m->hold_count != 0 || m->wire_count != 0 ||
3161 (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
3163 if (m->object != NULL && m->object->ref_count != 0) {
3175 * Apply the specified advice to the given page.
3177 * The object and page must be locked.
3180 vm_page_advise(vm_page_t m, int advice)
3183 vm_page_assert_locked(m);
3184 VM_OBJECT_ASSERT_WLOCKED(m->object);
3185 if (advice == MADV_FREE)
3187 * Mark the page clean. This will allow the page to be freed
3188 * without first paging it out. MADV_FREE pages are often
3189 * quickly reused by malloc(3), so we do not do anything that
3190 * would result in a page fault on a later access.
3193 else if (advice != MADV_DONTNEED) {
3194 if (advice == MADV_WILLNEED)
3195 vm_page_activate(m);
3200 * Clear any references to the page. Otherwise, the page daemon will
3201 * immediately reactivate the page.
3203 vm_page_aflag_clear(m, PGA_REFERENCED);
3205 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3209 * Place clean pages near the head of the inactive queue rather than
3210 * the tail, thus defeating the queue's LRU operation and ensuring that
3211 * the page will be reused quickly. Dirty pages not already in the
3212 * laundry are moved there.
3215 vm_page_deactivate_noreuse(m);
3221 * Grab a page, waiting until we are waken up due to the page
3222 * changing state. We keep on waiting, if the page continues
3223 * to be in the object. If the page doesn't exist, first allocate it
3224 * and then conditionally zero it.
3226 * This routine may sleep.
3228 * The object must be locked on entry. The lock will, however, be released
3229 * and reacquired if the routine sleeps.
3232 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3238 VM_OBJECT_ASSERT_WLOCKED(object);
3239 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3240 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3241 ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3242 pflags = allocflags &
3243 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
3244 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3245 pflags |= VM_ALLOC_WAITFAIL;
3247 if ((m = vm_page_lookup(object, pindex)) != NULL) {
3248 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3249 vm_page_xbusied(m) : vm_page_busied(m);
3251 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3254 * Reference the page before unlocking and
3255 * sleeping so that the page daemon is less
3256 * likely to reclaim it.
3258 vm_page_aflag_set(m, PGA_REFERENCED);
3260 VM_OBJECT_WUNLOCK(object);
3261 vm_page_busy_sleep(m, "pgrbwt", (allocflags &
3262 VM_ALLOC_IGN_SBUSY) != 0);
3263 VM_OBJECT_WLOCK(object);
3266 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3272 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3274 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3279 m = vm_page_alloc(object, pindex, pflags);
3281 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3285 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3291 * Return the specified range of pages from the given object. For each
3292 * page offset within the range, if a page already exists within the object
3293 * at that offset and it is busy, then wait for it to change state. If,
3294 * instead, the page doesn't exist, then allocate it.
3296 * The caller must always specify an allocation class.
3298 * allocation classes:
3299 * VM_ALLOC_NORMAL normal process request
3300 * VM_ALLOC_SYSTEM system *really* needs the pages
3302 * The caller must always specify that the pages are to be busied and/or
3305 * optional allocation flags:
3306 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
3307 * VM_ALLOC_NOBUSY do not exclusive busy the page
3308 * VM_ALLOC_NOWAIT do not sleep
3309 * VM_ALLOC_SBUSY set page to sbusy state
3310 * VM_ALLOC_WIRED wire the pages
3311 * VM_ALLOC_ZERO zero and validate any invalid pages
3313 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
3314 * may return a partial prefix of the requested range.
3317 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
3318 vm_page_t *ma, int count)
3325 VM_OBJECT_ASSERT_WLOCKED(object);
3326 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
3327 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
3328 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
3329 (allocflags & VM_ALLOC_WIRED) != 0,
3330 ("vm_page_grab_pages: the pages must be busied or wired"));
3331 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3332 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3333 ("vm_page_grab_pages: VM_ALLOC_SBUSY/IGN_SBUSY mismatch"));
3336 pflags = allocflags & ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK |
3337 VM_ALLOC_WAITFAIL | VM_ALLOC_IGN_SBUSY);
3338 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3339 pflags |= VM_ALLOC_WAITFAIL;
3342 m = vm_radix_lookup_le(&object->rtree, pindex + i);
3343 if (m == NULL || m->pindex != pindex + i) {
3347 mpred = TAILQ_PREV(m, pglist, listq);
3348 for (; i < count; i++) {
3350 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3351 vm_page_xbusied(m) : vm_page_busied(m);
3353 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3356 * Reference the page before unlocking and
3357 * sleeping so that the page daemon is less
3358 * likely to reclaim it.
3360 vm_page_aflag_set(m, PGA_REFERENCED);
3362 VM_OBJECT_WUNLOCK(object);
3363 vm_page_busy_sleep(m, "grbmaw", (allocflags &
3364 VM_ALLOC_IGN_SBUSY) != 0);
3365 VM_OBJECT_WLOCK(object);
3368 if ((allocflags & VM_ALLOC_WIRED) != 0) {
3373 if ((allocflags & (VM_ALLOC_NOBUSY |
3374 VM_ALLOC_SBUSY)) == 0)
3376 if ((allocflags & VM_ALLOC_SBUSY) != 0)
3379 m = vm_page_alloc_after(object, pindex + i,
3380 pflags | VM_ALLOC_COUNT(count - i), mpred);
3382 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3387 if (m->valid == 0 && (allocflags & VM_ALLOC_ZERO) != 0) {
3388 if ((m->flags & PG_ZERO) == 0)
3390 m->valid = VM_PAGE_BITS_ALL;
3393 m = vm_page_next(m);
3399 * Mapping function for valid or dirty bits in a page.
3401 * Inputs are required to range within a page.
3404 vm_page_bits(int base, int size)
3410 base + size <= PAGE_SIZE,
3411 ("vm_page_bits: illegal base/size %d/%d", base, size)
3414 if (size == 0) /* handle degenerate case */
3417 first_bit = base >> DEV_BSHIFT;
3418 last_bit = (base + size - 1) >> DEV_BSHIFT;
3420 return (((vm_page_bits_t)2 << last_bit) -
3421 ((vm_page_bits_t)1 << first_bit));
3425 * vm_page_set_valid_range:
3427 * Sets portions of a page valid. The arguments are expected
3428 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3429 * of any partial chunks touched by the range. The invalid portion of
3430 * such chunks will be zeroed.
3432 * (base + size) must be less then or equal to PAGE_SIZE.
3435 vm_page_set_valid_range(vm_page_t m, int base, int size)
3439 VM_OBJECT_ASSERT_WLOCKED(m->object);
3440 if (size == 0) /* handle degenerate case */
3444 * If the base is not DEV_BSIZE aligned and the valid
3445 * bit is clear, we have to zero out a portion of the
3448 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3449 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
3450 pmap_zero_page_area(m, frag, base - frag);
3453 * If the ending offset is not DEV_BSIZE aligned and the
3454 * valid bit is clear, we have to zero out a portion of
3457 endoff = base + size;
3458 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3459 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
3460 pmap_zero_page_area(m, endoff,
3461 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3464 * Assert that no previously invalid block that is now being validated
3467 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
3468 ("vm_page_set_valid_range: page %p is dirty", m));
3471 * Set valid bits inclusive of any overlap.
3473 m->valid |= vm_page_bits(base, size);
3477 * Clear the given bits from the specified page's dirty field.
3479 static __inline void
3480 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
3483 #if PAGE_SIZE < 16384
3488 * If the object is locked and the page is neither exclusive busy nor
3489 * write mapped, then the page's dirty field cannot possibly be
3490 * set by a concurrent pmap operation.
3492 VM_OBJECT_ASSERT_WLOCKED(m->object);
3493 if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
3494 m->dirty &= ~pagebits;
3497 * The pmap layer can call vm_page_dirty() without
3498 * holding a distinguished lock. The combination of
3499 * the object's lock and an atomic operation suffice
3500 * to guarantee consistency of the page dirty field.
3502 * For PAGE_SIZE == 32768 case, compiler already
3503 * properly aligns the dirty field, so no forcible
3504 * alignment is needed. Only require existence of
3505 * atomic_clear_64 when page size is 32768.
3507 addr = (uintptr_t)&m->dirty;
3508 #if PAGE_SIZE == 32768
3509 atomic_clear_64((uint64_t *)addr, pagebits);
3510 #elif PAGE_SIZE == 16384
3511 atomic_clear_32((uint32_t *)addr, pagebits);
3512 #else /* PAGE_SIZE <= 8192 */
3514 * Use a trick to perform a 32-bit atomic on the
3515 * containing aligned word, to not depend on the existence
3516 * of atomic_clear_{8, 16}.
3518 shift = addr & (sizeof(uint32_t) - 1);
3519 #if BYTE_ORDER == BIG_ENDIAN
3520 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
3524 addr &= ~(sizeof(uint32_t) - 1);
3525 atomic_clear_32((uint32_t *)addr, pagebits << shift);
3526 #endif /* PAGE_SIZE */
3531 * vm_page_set_validclean:
3533 * Sets portions of a page valid and clean. The arguments are expected
3534 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3535 * of any partial chunks touched by the range. The invalid portion of
3536 * such chunks will be zero'd.
3538 * (base + size) must be less then or equal to PAGE_SIZE.
3541 vm_page_set_validclean(vm_page_t m, int base, int size)
3543 vm_page_bits_t oldvalid, pagebits;
3546 VM_OBJECT_ASSERT_WLOCKED(m->object);
3547 if (size == 0) /* handle degenerate case */
3551 * If the base is not DEV_BSIZE aligned and the valid
3552 * bit is clear, we have to zero out a portion of the
3555 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3556 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
3557 pmap_zero_page_area(m, frag, base - frag);
3560 * If the ending offset is not DEV_BSIZE aligned and the
3561 * valid bit is clear, we have to zero out a portion of
3564 endoff = base + size;
3565 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3566 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
3567 pmap_zero_page_area(m, endoff,
3568 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3571 * Set valid, clear dirty bits. If validating the entire
3572 * page we can safely clear the pmap modify bit. We also
3573 * use this opportunity to clear the VPO_NOSYNC flag. If a process
3574 * takes a write fault on a MAP_NOSYNC memory area the flag will
3577 * We set valid bits inclusive of any overlap, but we can only
3578 * clear dirty bits for DEV_BSIZE chunks that are fully within
3581 oldvalid = m->valid;
3582 pagebits = vm_page_bits(base, size);
3583 m->valid |= pagebits;
3585 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
3586 frag = DEV_BSIZE - frag;
3592 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
3594 if (base == 0 && size == PAGE_SIZE) {
3596 * The page can only be modified within the pmap if it is
3597 * mapped, and it can only be mapped if it was previously
3600 if (oldvalid == VM_PAGE_BITS_ALL)
3602 * Perform the pmap_clear_modify() first. Otherwise,
3603 * a concurrent pmap operation, such as
3604 * pmap_protect(), could clear a modification in the
3605 * pmap and set the dirty field on the page before
3606 * pmap_clear_modify() had begun and after the dirty
3607 * field was cleared here.
3609 pmap_clear_modify(m);
3611 m->oflags &= ~VPO_NOSYNC;
3612 } else if (oldvalid != VM_PAGE_BITS_ALL)
3613 m->dirty &= ~pagebits;
3615 vm_page_clear_dirty_mask(m, pagebits);
3619 vm_page_clear_dirty(vm_page_t m, int base, int size)
3622 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
3626 * vm_page_set_invalid:
3628 * Invalidates DEV_BSIZE'd chunks within a page. Both the
3629 * valid and dirty bits for the effected areas are cleared.
3632 vm_page_set_invalid(vm_page_t m, int base, int size)
3634 vm_page_bits_t bits;
3638 VM_OBJECT_ASSERT_WLOCKED(object);
3639 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
3640 size >= object->un_pager.vnp.vnp_size)
3641 bits = VM_PAGE_BITS_ALL;
3643 bits = vm_page_bits(base, size);
3644 if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
3647 KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3648 !pmap_page_is_mapped(m),
3649 ("vm_page_set_invalid: page %p is mapped", m));
3655 * vm_page_zero_invalid()
3657 * The kernel assumes that the invalid portions of a page contain
3658 * garbage, but such pages can be mapped into memory by user code.
3659 * When this occurs, we must zero out the non-valid portions of the
3660 * page so user code sees what it expects.
3662 * Pages are most often semi-valid when the end of a file is mapped
3663 * into memory and the file's size is not page aligned.
3666 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3671 VM_OBJECT_ASSERT_WLOCKED(m->object);
3673 * Scan the valid bits looking for invalid sections that
3674 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
3675 * valid bit may be set ) have already been zeroed by
3676 * vm_page_set_validclean().
3678 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3679 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3680 (m->valid & ((vm_page_bits_t)1 << i))) {
3682 pmap_zero_page_area(m,
3683 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3690 * setvalid is TRUE when we can safely set the zero'd areas
3691 * as being valid. We can do this if there are no cache consistancy
3692 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3695 m->valid = VM_PAGE_BITS_ALL;
3701 * Is (partial) page valid? Note that the case where size == 0
3702 * will return FALSE in the degenerate case where the page is
3703 * entirely invalid, and TRUE otherwise.
3706 vm_page_is_valid(vm_page_t m, int base, int size)
3708 vm_page_bits_t bits;
3710 VM_OBJECT_ASSERT_LOCKED(m->object);
3711 bits = vm_page_bits(base, size);
3712 return (m->valid != 0 && (m->valid & bits) == bits);
3716 * Returns true if all of the specified predicates are true for the entire
3717 * (super)page and false otherwise.
3720 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
3726 VM_OBJECT_ASSERT_LOCKED(object);
3727 npages = atop(pagesizes[m->psind]);
3730 * The physically contiguous pages that make up a superpage, i.e., a
3731 * page with a page size index ("psind") greater than zero, will
3732 * occupy adjacent entries in vm_page_array[].
3734 for (i = 0; i < npages; i++) {
3735 /* Always test object consistency, including "skip_m". */
3736 if (m[i].object != object)
3738 if (&m[i] == skip_m)
3740 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
3742 if ((flags & PS_ALL_DIRTY) != 0) {
3744 * Calling vm_page_test_dirty() or pmap_is_modified()
3745 * might stop this case from spuriously returning
3746 * "false". However, that would require a write lock
3747 * on the object containing "m[i]".
3749 if (m[i].dirty != VM_PAGE_BITS_ALL)
3752 if ((flags & PS_ALL_VALID) != 0 &&
3753 m[i].valid != VM_PAGE_BITS_ALL)
3760 * Set the page's dirty bits if the page is modified.
3763 vm_page_test_dirty(vm_page_t m)
3766 VM_OBJECT_ASSERT_WLOCKED(m->object);
3767 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3772 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3775 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3779 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3782 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3786 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3789 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3792 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3794 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3797 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3801 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3804 mtx_assert_(vm_page_lockptr(m), a, file, line);
3810 vm_page_object_lock_assert(vm_page_t m)
3814 * Certain of the page's fields may only be modified by the
3815 * holder of the containing object's lock or the exclusive busy.
3816 * holder. Unfortunately, the holder of the write busy is
3817 * not recorded, and thus cannot be checked here.
3819 if (m->object != NULL && !vm_page_xbusied(m))
3820 VM_OBJECT_ASSERT_WLOCKED(m->object);
3824 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3827 if ((bits & PGA_WRITEABLE) == 0)
3831 * The PGA_WRITEABLE flag can only be set if the page is
3832 * managed, is exclusively busied or the object is locked.
3833 * Currently, this flag is only set by pmap_enter().
3835 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3836 ("PGA_WRITEABLE on unmanaged page"));
3837 if (!vm_page_xbusied(m))
3838 VM_OBJECT_ASSERT_LOCKED(m->object);
3842 #include "opt_ddb.h"
3844 #include <sys/kernel.h>
3846 #include <ddb/ddb.h>
3848 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3851 db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
3852 db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
3853 db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
3854 db_printf("vm_cnt.v_laundry_count: %d\n", vm_cnt.v_laundry_count);
3855 db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
3856 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
3857 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
3858 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
3859 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
3862 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3866 db_printf("pq_free %d\n", vm_cnt.v_free_count);
3867 for (dom = 0; dom < vm_ndomains; dom++) {
3869 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d\n",
3871 vm_dom[dom].vmd_page_count,
3872 vm_dom[dom].vmd_free_count,
3873 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3874 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
3875 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt);
3879 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3885 db_printf("show pginfo addr\n");
3889 phys = strchr(modif, 'p') != NULL;
3891 m = PHYS_TO_VM_PAGE(addr);
3893 m = (vm_page_t)addr;
3895 "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3896 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3897 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3898 m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3899 m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);