2 * SPDX-License-Identifier: (BSD-4-Clause AND MIT-CMU)
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 * Copyright (c) 1994 John S. Dyson
8 * Copyright (c) 1994 David Greenman
12 * This code is derived from software contributed to Berkeley by
13 * The Mach Operating System project at Carnegie-Mellon University.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
23 * 3. All advertising materials mentioning features or use of this software
24 * must display the following acknowledgement:
25 * This product includes software developed by the University of
26 * California, Berkeley and its contributors.
27 * 4. Neither the name of the University nor the names of its contributors
28 * may be used to endorse or promote products derived from this software
29 * without specific prior written permission.
31 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
32 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
35 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
39 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
40 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43 * from: @(#)vm_fault.c 8.4 (Berkeley) 1/12/94
46 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
47 * All rights reserved.
49 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
51 * Permission to use, copy, modify and distribute this software and
52 * its documentation is hereby granted, provided that both the copyright
53 * notice and this permission notice appear in all copies of the
54 * software, derivative works or modified versions, and any portions
55 * thereof, and that both notices appear in supporting documentation.
57 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
58 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
59 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
61 * Carnegie Mellon requests users of this software to return to
63 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
64 * School of Computer Science
65 * Carnegie Mellon University
66 * Pittsburgh PA 15213-3890
68 * any improvements or extensions that they make and grant Carnegie the
69 * rights to redistribute these changes.
73 * Page fault handling module.
76 #include <sys/cdefs.h>
77 __FBSDID("$FreeBSD$");
79 #include "opt_ktrace.h"
82 #include <sys/param.h>
83 #include <sys/systm.h>
84 #include <sys/kernel.h>
87 #include <sys/mutex.h>
88 #include <sys/pctrie.h>
90 #include <sys/racct.h>
91 #include <sys/refcount.h>
92 #include <sys/resourcevar.h>
93 #include <sys/rwlock.h>
94 #include <sys/signalvar.h>
95 #include <sys/sysctl.h>
96 #include <sys/sysent.h>
97 #include <sys/vmmeter.h>
98 #include <sys/vnode.h>
100 #include <sys/ktrace.h>
104 #include <vm/vm_param.h>
106 #include <vm/vm_map.h>
107 #include <vm/vm_object.h>
108 #include <vm/vm_page.h>
109 #include <vm/vm_pageout.h>
110 #include <vm/vm_kern.h>
111 #include <vm/vm_pager.h>
112 #include <vm/vm_extern.h>
113 #include <vm/vm_reserv.h>
118 #define VM_FAULT_READ_DEFAULT (1 + VM_FAULT_READ_AHEAD_INIT)
120 #define VM_FAULT_DONTNEED_MIN 1048576
123 /* Fault parameters. */
126 vm_prot_t fault_type;
132 struct timeval oom_start_time;
137 /* Page reference for cow. */
140 /* Current object. */
145 /* Top-level map object. */
146 vm_object_t first_object;
147 vm_pindex_t first_pindex;
152 vm_map_entry_t entry;
154 bool lookup_still_valid;
156 /* Vnode if locked. */
161 * Return codes for internal fault routines.
164 FAULT_SUCCESS = 10000, /* Return success to user. */
165 FAULT_FAILURE, /* Return failure to user. */
166 FAULT_CONTINUE, /* Continue faulting. */
167 FAULT_RESTART, /* Restart fault. */
168 FAULT_OUT_OF_BOUNDS, /* Invalid address for pager. */
169 FAULT_HARD, /* Performed I/O. */
170 FAULT_SOFT, /* Found valid page. */
171 FAULT_PROTECTION_FAILURE, /* Invalid access. */
174 enum fault_next_status {
175 FAULT_NEXT_GOTOBJ = 1,
180 static void vm_fault_dontneed(const struct faultstate *fs, vm_offset_t vaddr,
182 static void vm_fault_prefault(const struct faultstate *fs, vm_offset_t addra,
183 int backward, int forward, bool obj_locked);
185 static int vm_pfault_oom_attempts = 3;
186 SYSCTL_INT(_vm, OID_AUTO, pfault_oom_attempts, CTLFLAG_RWTUN,
187 &vm_pfault_oom_attempts, 0,
188 "Number of page allocation attempts in page fault handler before it "
189 "triggers OOM handling");
191 static int vm_pfault_oom_wait = 10;
192 SYSCTL_INT(_vm, OID_AUTO, pfault_oom_wait, CTLFLAG_RWTUN,
193 &vm_pfault_oom_wait, 0,
194 "Number of seconds to wait for free pages before retrying "
195 "the page fault handler");
198 vm_fault_page_release(vm_page_t *mp)
205 * We are likely to loop around again and attempt to busy
206 * this page. Deactivating it leaves it available for
207 * pageout while optimizing fault restarts.
209 vm_page_deactivate(m);
216 vm_fault_page_free(vm_page_t *mp)
222 VM_OBJECT_ASSERT_WLOCKED(m->object);
223 if (!vm_page_wired(m))
232 * Return true if a vm_pager_get_pages() call is needed in order to check
233 * whether the pager might have a particular page, false if it can be determined
234 * immediately that the pager can not have a copy. For swap objects, this can
235 * be checked quickly.
238 vm_fault_object_needs_getpages(vm_object_t object)
240 VM_OBJECT_ASSERT_LOCKED(object);
242 return ((object->flags & OBJ_SWAP) == 0 ||
243 !pctrie_is_empty(&object->un_pager.swp.swp_blks));
247 vm_fault_unlock_map(struct faultstate *fs)
250 if (fs->lookup_still_valid) {
251 vm_map_lookup_done(fs->map, fs->entry);
252 fs->lookup_still_valid = false;
257 vm_fault_unlock_vp(struct faultstate *fs)
260 if (fs->vp != NULL) {
267 vm_fault_deallocate(struct faultstate *fs)
270 vm_fault_page_release(&fs->m_cow);
271 vm_fault_page_release(&fs->m);
272 vm_object_pip_wakeup(fs->object);
273 if (fs->object != fs->first_object) {
274 VM_OBJECT_WLOCK(fs->first_object);
275 vm_fault_page_free(&fs->first_m);
276 VM_OBJECT_WUNLOCK(fs->first_object);
277 vm_object_pip_wakeup(fs->first_object);
279 vm_object_deallocate(fs->first_object);
280 vm_fault_unlock_map(fs);
281 vm_fault_unlock_vp(fs);
285 vm_fault_unlock_and_deallocate(struct faultstate *fs)
288 VM_OBJECT_UNLOCK(fs->object);
289 vm_fault_deallocate(fs);
293 vm_fault_dirty(struct faultstate *fs, vm_page_t m)
297 if (((fs->prot & VM_PROT_WRITE) == 0 &&
298 (fs->fault_flags & VM_FAULT_DIRTY) == 0) ||
299 (m->oflags & VPO_UNMANAGED) != 0)
302 VM_PAGE_OBJECT_BUSY_ASSERT(m);
304 need_dirty = ((fs->fault_type & VM_PROT_WRITE) != 0 &&
305 (fs->fault_flags & VM_FAULT_WIRE) == 0) ||
306 (fs->fault_flags & VM_FAULT_DIRTY) != 0;
308 vm_object_set_writeable_dirty(m->object);
311 * If the fault is a write, we know that this page is being
312 * written NOW so dirty it explicitly to save on
313 * pmap_is_modified() calls later.
315 * Also, since the page is now dirty, we can possibly tell
316 * the pager to release any swap backing the page.
318 if (need_dirty && vm_page_set_dirty(m) == 0) {
320 * If this is a NOSYNC mmap we do not want to set PGA_NOSYNC
321 * if the page is already dirty to prevent data written with
322 * the expectation of being synced from not being synced.
323 * Likewise if this entry does not request NOSYNC then make
324 * sure the page isn't marked NOSYNC. Applications sharing
325 * data should use the same flags to avoid ping ponging.
327 if ((fs->entry->eflags & MAP_ENTRY_NOSYNC) != 0)
328 vm_page_aflag_set(m, PGA_NOSYNC);
330 vm_page_aflag_clear(m, PGA_NOSYNC);
336 * Unlocks fs.first_object and fs.map on success.
338 static enum fault_status
339 vm_fault_soft_fast(struct faultstate *fs)
342 #if VM_NRESERVLEVEL > 0
349 MPASS(fs->vp == NULL);
352 * If we fail, vast majority of the time it is because the page is not
353 * there to begin with. Opportunistically perform the lookup and
354 * subsequent checks without the object lock, revalidate later.
356 * Note: a busy page can be mapped for read|execute access.
358 m = vm_page_lookup_unlocked(fs->first_object, fs->first_pindex);
359 if (m == NULL || !vm_page_all_valid(m) ||
360 ((fs->prot & VM_PROT_WRITE) != 0 && vm_page_busied(m))) {
361 VM_OBJECT_WLOCK(fs->first_object);
362 return (FAULT_FAILURE);
367 VM_OBJECT_RLOCK(fs->first_object);
370 * Now that we stabilized the state, revalidate the page is in the shape
371 * we encountered above.
374 if (m->object != fs->first_object || m->pindex != fs->first_pindex)
377 vm_object_busy(fs->first_object);
379 if (!vm_page_all_valid(m) ||
380 ((fs->prot & VM_PROT_WRITE) != 0 && vm_page_busied(m)))
385 #if VM_NRESERVLEVEL > 0
386 if ((m->flags & PG_FICTITIOUS) == 0 &&
387 (m_super = vm_reserv_to_superpage(m)) != NULL &&
388 rounddown2(vaddr, pagesizes[m_super->psind]) >= fs->entry->start &&
389 roundup2(vaddr + 1, pagesizes[m_super->psind]) <= fs->entry->end &&
390 (vaddr & (pagesizes[m_super->psind] - 1)) == (VM_PAGE_TO_PHYS(m) &
391 (pagesizes[m_super->psind] - 1)) && !fs->wired &&
392 pmap_ps_enabled(fs->map->pmap)) {
393 flags = PS_ALL_VALID;
394 if ((fs->prot & VM_PROT_WRITE) != 0) {
396 * Create a superpage mapping allowing write access
397 * only if none of the constituent pages are busy and
398 * all of them are already dirty (except possibly for
399 * the page that was faulted on).
401 flags |= PS_NONE_BUSY;
402 if ((fs->first_object->flags & OBJ_UNMANAGED) == 0)
403 flags |= PS_ALL_DIRTY;
405 if (vm_page_ps_test(m_super, flags, m)) {
407 psind = m_super->psind;
408 vaddr = rounddown2(vaddr, pagesizes[psind]);
409 /* Preset the modified bit for dirty superpages. */
410 if ((flags & PS_ALL_DIRTY) != 0)
411 fs->fault_type |= VM_PROT_WRITE;
415 if (pmap_enter(fs->map->pmap, vaddr, m_map, fs->prot, fs->fault_type |
416 PMAP_ENTER_NOSLEEP | (fs->wired ? PMAP_ENTER_WIRED : 0), psind) !=
419 if (fs->m_hold != NULL) {
423 if (psind == 0 && !fs->wired)
424 vm_fault_prefault(fs, vaddr, PFBAK, PFFOR, true);
425 VM_OBJECT_RUNLOCK(fs->first_object);
426 vm_fault_dirty(fs, m);
427 vm_object_unbusy(fs->first_object);
428 vm_map_lookup_done(fs->map, fs->entry);
429 curthread->td_ru.ru_minflt++;
430 return (FAULT_SUCCESS);
432 vm_object_unbusy(fs->first_object);
434 if (!VM_OBJECT_TRYUPGRADE(fs->first_object)) {
435 VM_OBJECT_RUNLOCK(fs->first_object);
436 VM_OBJECT_WLOCK(fs->first_object);
438 return (FAULT_FAILURE);
442 vm_fault_restore_map_lock(struct faultstate *fs)
445 VM_OBJECT_ASSERT_WLOCKED(fs->first_object);
446 MPASS(blockcount_read(&fs->first_object->paging_in_progress) > 0);
448 if (!vm_map_trylock_read(fs->map)) {
449 VM_OBJECT_WUNLOCK(fs->first_object);
450 vm_map_lock_read(fs->map);
451 VM_OBJECT_WLOCK(fs->first_object);
453 fs->lookup_still_valid = true;
457 vm_fault_populate_check_page(vm_page_t m)
461 * Check each page to ensure that the pager is obeying the
462 * interface: the page must be installed in the object, fully
463 * valid, and exclusively busied.
466 MPASS(vm_page_all_valid(m));
467 MPASS(vm_page_xbusied(m));
471 vm_fault_populate_cleanup(vm_object_t object, vm_pindex_t first,
477 VM_OBJECT_ASSERT_WLOCKED(object);
478 MPASS(first <= last);
479 for (pidx = first, m = vm_page_lookup(object, pidx);
480 pidx <= last; pidx++, m = vm_page_next(m)) {
481 vm_fault_populate_check_page(m);
482 vm_page_deactivate(m);
487 static enum fault_status
488 vm_fault_populate(struct faultstate *fs)
492 vm_pindex_t map_first, map_last, pager_first, pager_last, pidx;
493 int bdry_idx, i, npages, psind, rv;
494 enum fault_status res;
496 MPASS(fs->object == fs->first_object);
497 VM_OBJECT_ASSERT_WLOCKED(fs->first_object);
498 MPASS(blockcount_read(&fs->first_object->paging_in_progress) > 0);
499 MPASS(fs->first_object->backing_object == NULL);
500 MPASS(fs->lookup_still_valid);
502 pager_first = OFF_TO_IDX(fs->entry->offset);
503 pager_last = pager_first + atop(fs->entry->end - fs->entry->start) - 1;
504 vm_fault_unlock_map(fs);
505 vm_fault_unlock_vp(fs);
510 * Call the pager (driver) populate() method.
512 * There is no guarantee that the method will be called again
513 * if the current fault is for read, and a future fault is
514 * for write. Report the entry's maximum allowed protection
517 rv = vm_pager_populate(fs->first_object, fs->first_pindex,
518 fs->fault_type, fs->entry->max_protection, &pager_first,
521 VM_OBJECT_ASSERT_WLOCKED(fs->first_object);
522 if (rv == VM_PAGER_BAD) {
524 * VM_PAGER_BAD is the backdoor for a pager to request
525 * normal fault handling.
527 vm_fault_restore_map_lock(fs);
528 if (fs->map->timestamp != fs->map_generation)
529 return (FAULT_RESTART);
530 return (FAULT_CONTINUE);
532 if (rv != VM_PAGER_OK)
533 return (FAULT_FAILURE); /* AKA SIGSEGV */
535 /* Ensure that the driver is obeying the interface. */
536 MPASS(pager_first <= pager_last);
537 MPASS(fs->first_pindex <= pager_last);
538 MPASS(fs->first_pindex >= pager_first);
539 MPASS(pager_last < fs->first_object->size);
541 vm_fault_restore_map_lock(fs);
542 bdry_idx = MAP_ENTRY_SPLIT_BOUNDARY_INDEX(fs->entry);
543 if (fs->map->timestamp != fs->map_generation) {
545 vm_fault_populate_cleanup(fs->first_object, pager_first,
548 m = vm_page_lookup(fs->first_object, pager_first);
552 return (FAULT_RESTART);
556 * The map is unchanged after our last unlock. Process the fault.
558 * First, the special case of largepage mappings, where
559 * populate only busies the first page in superpage run.
562 KASSERT(PMAP_HAS_LARGEPAGES,
563 ("missing pmap support for large pages"));
564 m = vm_page_lookup(fs->first_object, pager_first);
565 vm_fault_populate_check_page(m);
566 VM_OBJECT_WUNLOCK(fs->first_object);
567 vaddr = fs->entry->start + IDX_TO_OFF(pager_first) -
569 /* assert alignment for entry */
570 KASSERT((vaddr & (pagesizes[bdry_idx] - 1)) == 0,
571 ("unaligned superpage start %#jx pager_first %#jx offset %#jx vaddr %#jx",
572 (uintmax_t)fs->entry->start, (uintmax_t)pager_first,
573 (uintmax_t)fs->entry->offset, (uintmax_t)vaddr));
574 KASSERT((VM_PAGE_TO_PHYS(m) & (pagesizes[bdry_idx] - 1)) == 0,
575 ("unaligned superpage m %p %#jx", m,
576 (uintmax_t)VM_PAGE_TO_PHYS(m)));
577 rv = pmap_enter(fs->map->pmap, vaddr, m, fs->prot,
578 fs->fault_type | (fs->wired ? PMAP_ENTER_WIRED : 0) |
579 PMAP_ENTER_LARGEPAGE, bdry_idx);
580 VM_OBJECT_WLOCK(fs->first_object);
582 if (rv != KERN_SUCCESS) {
586 if ((fs->fault_flags & VM_FAULT_WIRE) != 0) {
587 for (i = 0; i < atop(pagesizes[bdry_idx]); i++)
590 if (fs->m_hold != NULL) {
591 *fs->m_hold = m + (fs->first_pindex - pager_first);
592 vm_page_wire(*fs->m_hold);
598 * The range [pager_first, pager_last] that is given to the
599 * pager is only a hint. The pager may populate any range
600 * within the object that includes the requested page index.
601 * In case the pager expanded the range, clip it to fit into
604 map_first = OFF_TO_IDX(fs->entry->offset);
605 if (map_first > pager_first) {
606 vm_fault_populate_cleanup(fs->first_object, pager_first,
608 pager_first = map_first;
610 map_last = map_first + atop(fs->entry->end - fs->entry->start) - 1;
611 if (map_last < pager_last) {
612 vm_fault_populate_cleanup(fs->first_object, map_last + 1,
614 pager_last = map_last;
616 for (pidx = pager_first, m = vm_page_lookup(fs->first_object, pidx);
618 pidx += npages, m = vm_page_next(&m[npages - 1])) {
619 vaddr = fs->entry->start + IDX_TO_OFF(pidx) - fs->entry->offset;
622 if (psind > 0 && ((vaddr & (pagesizes[psind] - 1)) != 0 ||
623 pidx + OFF_TO_IDX(pagesizes[psind]) - 1 > pager_last ||
624 !pmap_ps_enabled(fs->map->pmap) || fs->wired))
627 npages = atop(pagesizes[psind]);
628 for (i = 0; i < npages; i++) {
629 vm_fault_populate_check_page(&m[i]);
630 vm_fault_dirty(fs, &m[i]);
632 VM_OBJECT_WUNLOCK(fs->first_object);
633 rv = pmap_enter(fs->map->pmap, vaddr, m, fs->prot, fs->fault_type |
634 (fs->wired ? PMAP_ENTER_WIRED : 0), psind);
637 * pmap_enter() may fail for a superpage mapping if additional
638 * protection policies prevent the full mapping.
639 * For example, this will happen on amd64 if the entire
640 * address range does not share the same userspace protection
641 * key. Revert to single-page mappings if this happens.
643 MPASS(rv == KERN_SUCCESS ||
644 (psind > 0 && rv == KERN_PROTECTION_FAILURE));
645 if (__predict_false(psind > 0 &&
646 rv == KERN_PROTECTION_FAILURE)) {
648 for (i = 0; i < npages; i++) {
649 rv = pmap_enter(fs->map->pmap, vaddr + ptoa(i),
650 &m[i], fs->prot, fs->fault_type, 0);
651 MPASS(rv == KERN_SUCCESS);
655 VM_OBJECT_WLOCK(fs->first_object);
656 for (i = 0; i < npages; i++) {
657 if ((fs->fault_flags & VM_FAULT_WIRE) != 0 &&
658 m[i].pindex == fs->first_pindex)
661 vm_page_activate(&m[i]);
662 if (fs->m_hold != NULL &&
663 m[i].pindex == fs->first_pindex) {
664 (*fs->m_hold) = &m[i];
667 vm_page_xunbusy(&m[i]);
671 curthread->td_ru.ru_majflt++;
675 static int prot_fault_translation;
676 SYSCTL_INT(_machdep, OID_AUTO, prot_fault_translation, CTLFLAG_RWTUN,
677 &prot_fault_translation, 0,
678 "Control signal to deliver on protection fault");
680 /* compat definition to keep common code for signal translation */
681 #define UCODE_PAGEFLT 12
683 _Static_assert(UCODE_PAGEFLT == T_PAGEFLT, "T_PAGEFLT");
689 * Handle a page fault occurring at the given address,
690 * requiring the given permissions, in the map specified.
691 * If successful, the page is inserted into the
692 * associated physical map.
694 * NOTE: the given address should be truncated to the
695 * proper page address.
697 * KERN_SUCCESS is returned if the page fault is handled; otherwise,
698 * a standard error specifying why the fault is fatal is returned.
700 * The map in question must be referenced, and remains so.
701 * Caller may hold no locks.
704 vm_fault_trap(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
705 int fault_flags, int *signo, int *ucode)
709 MPASS(signo == NULL || ucode != NULL);
711 if (map != kernel_map && KTRPOINT(curthread, KTR_FAULT))
712 ktrfault(vaddr, fault_type);
714 result = vm_fault(map, trunc_page(vaddr), fault_type, fault_flags,
716 KASSERT(result == KERN_SUCCESS || result == KERN_FAILURE ||
717 result == KERN_INVALID_ADDRESS ||
718 result == KERN_RESOURCE_SHORTAGE ||
719 result == KERN_PROTECTION_FAILURE ||
720 result == KERN_OUT_OF_BOUNDS,
721 ("Unexpected Mach error %d from vm_fault()", result));
723 if (map != kernel_map && KTRPOINT(curthread, KTR_FAULTEND))
726 if (result != KERN_SUCCESS && signo != NULL) {
729 case KERN_INVALID_ADDRESS:
731 *ucode = SEGV_MAPERR;
733 case KERN_RESOURCE_SHORTAGE:
737 case KERN_OUT_OF_BOUNDS:
741 case KERN_PROTECTION_FAILURE:
742 if (prot_fault_translation == 0) {
744 * Autodetect. This check also covers
745 * the images without the ABI-tag ELF
748 if (SV_CURPROC_ABI() == SV_ABI_FREEBSD &&
749 curproc->p_osrel >= P_OSREL_SIGSEGV) {
751 *ucode = SEGV_ACCERR;
754 *ucode = UCODE_PAGEFLT;
756 } else if (prot_fault_translation == 1) {
757 /* Always compat mode. */
759 *ucode = UCODE_PAGEFLT;
761 /* Always SIGSEGV mode. */
763 *ucode = SEGV_ACCERR;
767 KASSERT(0, ("Unexpected Mach error %d from vm_fault()",
776 vm_fault_object_ensure_wlocked(struct faultstate *fs)
778 if (fs->object == fs->first_object)
779 VM_OBJECT_ASSERT_WLOCKED(fs->object);
781 if (!fs->can_read_lock) {
782 VM_OBJECT_ASSERT_WLOCKED(fs->object);
786 if (VM_OBJECT_WOWNED(fs->object))
789 if (VM_OBJECT_TRYUPGRADE(fs->object))
795 static enum fault_status
796 vm_fault_lock_vnode(struct faultstate *fs, bool objlocked)
801 if (fs->object->type != OBJT_VNODE)
802 return (FAULT_CONTINUE);
803 vp = fs->object->handle;
805 ASSERT_VOP_LOCKED(vp, "saved vnode is not locked");
806 return (FAULT_CONTINUE);
810 * Perform an unlock in case the desired vnode changed while
811 * the map was unlocked during a retry.
813 vm_fault_unlock_vp(fs);
815 locked = VOP_ISLOCKED(vp);
816 if (locked != LK_EXCLUSIVE)
820 * We must not sleep acquiring the vnode lock while we have
821 * the page exclusive busied or the object's
822 * paging-in-progress count incremented. Otherwise, we could
825 error = vget(vp, locked | LK_CANRECURSE | LK_NOWAIT);
828 return (FAULT_CONTINUE);
833 vm_fault_unlock_and_deallocate(fs);
835 vm_fault_deallocate(fs);
836 error = vget(vp, locked | LK_RETRY | LK_CANRECURSE);
839 KASSERT(error == 0, ("vm_fault: vget failed %d", error));
840 return (FAULT_RESTART);
844 * Calculate the desired readahead. Handle drop-behind.
846 * Returns the number of readahead blocks to pass to the pager.
849 vm_fault_readahead(struct faultstate *fs)
854 KASSERT(fs->lookup_still_valid, ("map unlocked"));
855 era = fs->entry->read_ahead;
856 behavior = vm_map_entry_behavior(fs->entry);
857 if (behavior == MAP_ENTRY_BEHAV_RANDOM) {
859 } else if (behavior == MAP_ENTRY_BEHAV_SEQUENTIAL) {
860 nera = VM_FAULT_READ_AHEAD_MAX;
861 if (fs->vaddr == fs->entry->next_read)
862 vm_fault_dontneed(fs, fs->vaddr, nera);
863 } else if (fs->vaddr == fs->entry->next_read) {
865 * This is a sequential fault. Arithmetically
866 * increase the requested number of pages in
867 * the read-ahead window. The requested
868 * number of pages is "# of sequential faults
869 * x (read ahead min + 1) + read ahead min"
871 nera = VM_FAULT_READ_AHEAD_MIN;
874 if (nera > VM_FAULT_READ_AHEAD_MAX)
875 nera = VM_FAULT_READ_AHEAD_MAX;
877 if (era == VM_FAULT_READ_AHEAD_MAX)
878 vm_fault_dontneed(fs, fs->vaddr, nera);
881 * This is a non-sequential fault.
887 * A read lock on the map suffices to update
888 * the read ahead count safely.
890 fs->entry->read_ahead = nera;
897 vm_fault_lookup(struct faultstate *fs)
901 KASSERT(!fs->lookup_still_valid,
902 ("vm_fault_lookup: Map already locked."));
903 result = vm_map_lookup(&fs->map, fs->vaddr, fs->fault_type |
904 VM_PROT_FAULT_LOOKUP, &fs->entry, &fs->first_object,
905 &fs->first_pindex, &fs->prot, &fs->wired);
906 if (result != KERN_SUCCESS) {
907 vm_fault_unlock_vp(fs);
911 fs->map_generation = fs->map->timestamp;
913 if (fs->entry->eflags & MAP_ENTRY_NOFAULT) {
914 panic("%s: fault on nofault entry, addr: %#lx",
915 __func__, (u_long)fs->vaddr);
918 if (fs->entry->eflags & MAP_ENTRY_IN_TRANSITION &&
919 fs->entry->wiring_thread != curthread) {
920 vm_map_unlock_read(fs->map);
921 vm_map_lock(fs->map);
922 if (vm_map_lookup_entry(fs->map, fs->vaddr, &fs->entry) &&
923 (fs->entry->eflags & MAP_ENTRY_IN_TRANSITION)) {
924 vm_fault_unlock_vp(fs);
925 fs->entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
926 vm_map_unlock_and_wait(fs->map, 0);
928 vm_map_unlock(fs->map);
929 return (KERN_RESOURCE_SHORTAGE);
932 MPASS((fs->entry->eflags & MAP_ENTRY_GUARD) == 0);
935 fs->fault_type = fs->prot | (fs->fault_type & VM_PROT_COPY);
937 KASSERT((fs->fault_flags & VM_FAULT_WIRE) == 0,
938 ("!fs->wired && VM_FAULT_WIRE"));
939 fs->lookup_still_valid = true;
941 return (KERN_SUCCESS);
945 vm_fault_relookup(struct faultstate *fs)
947 vm_object_t retry_object;
948 vm_pindex_t retry_pindex;
949 vm_prot_t retry_prot;
952 if (!vm_map_trylock_read(fs->map))
953 return (KERN_RESTART);
955 fs->lookup_still_valid = true;
956 if (fs->map->timestamp == fs->map_generation)
957 return (KERN_SUCCESS);
959 result = vm_map_lookup_locked(&fs->map, fs->vaddr, fs->fault_type,
960 &fs->entry, &retry_object, &retry_pindex, &retry_prot,
962 if (result != KERN_SUCCESS) {
964 * If retry of map lookup would have blocked then
965 * retry fault from start.
967 if (result == KERN_FAILURE)
968 return (KERN_RESTART);
971 if (retry_object != fs->first_object ||
972 retry_pindex != fs->first_pindex)
973 return (KERN_RESTART);
976 * Check whether the protection has changed or the object has
977 * been copied while we left the map unlocked. Changing from
978 * read to write permission is OK - we leave the page
979 * write-protected, and catch the write fault. Changing from
980 * write to read permission means that we can't mark the page
981 * write-enabled after all.
983 fs->prot &= retry_prot;
984 fs->fault_type &= retry_prot;
986 return (KERN_RESTART);
988 /* Reassert because wired may have changed. */
989 KASSERT(fs->wired || (fs->fault_flags & VM_FAULT_WIRE) == 0,
990 ("!wired && VM_FAULT_WIRE"));
992 return (KERN_SUCCESS);
996 vm_fault_cow(struct faultstate *fs)
998 bool is_first_object_locked;
1000 KASSERT(fs->object != fs->first_object,
1001 ("source and target COW objects are identical"));
1004 * This allows pages to be virtually copied from a backing_object
1005 * into the first_object, where the backing object has no other
1006 * refs to it, and cannot gain any more refs. Instead of a bcopy,
1007 * we just move the page from the backing object to the first
1008 * object. Note that we must mark the page dirty in the first
1009 * object so that it will go out to swap when needed.
1011 is_first_object_locked = false;
1014 * Only one shadow object and no other refs.
1016 fs->object->shadow_count == 1 && fs->object->ref_count == 1 &&
1018 * No other ways to look the object up
1020 fs->object->handle == NULL && (fs->object->flags & OBJ_ANON) != 0 &&
1022 * We don't chase down the shadow chain and we can acquire locks.
1024 (is_first_object_locked = VM_OBJECT_TRYWLOCK(fs->first_object)) &&
1025 fs->object == fs->first_object->backing_object &&
1026 VM_OBJECT_TRYWLOCK(fs->object)) {
1028 * Remove but keep xbusy for replace. fs->m is moved into
1029 * fs->first_object and left busy while fs->first_m is
1030 * conditionally freed.
1032 vm_page_remove_xbusy(fs->m);
1033 vm_page_replace(fs->m, fs->first_object, fs->first_pindex,
1035 vm_page_dirty(fs->m);
1036 #if VM_NRESERVLEVEL > 0
1038 * Rename the reservation.
1040 vm_reserv_rename(fs->m, fs->first_object, fs->object,
1041 OFF_TO_IDX(fs->first_object->backing_object_offset));
1043 VM_OBJECT_WUNLOCK(fs->object);
1044 VM_OBJECT_WUNLOCK(fs->first_object);
1045 fs->first_m = fs->m;
1047 VM_CNT_INC(v_cow_optim);
1049 if (is_first_object_locked)
1050 VM_OBJECT_WUNLOCK(fs->first_object);
1052 * Oh, well, lets copy it.
1054 pmap_copy_page(fs->m, fs->first_m);
1055 vm_page_valid(fs->first_m);
1056 if (fs->wired && (fs->fault_flags & VM_FAULT_WIRE) == 0) {
1057 vm_page_wire(fs->first_m);
1058 vm_page_unwire(fs->m, PQ_INACTIVE);
1061 * Save the cow page to be released after
1062 * pmap_enter is complete.
1068 * Typically, the shadow object is either private to this
1069 * address space (OBJ_ONEMAPPING) or its pages are read only.
1070 * In the highly unusual case where the pages of a shadow object
1071 * are read/write shared between this and other address spaces,
1072 * we need to ensure that any pmap-level mappings to the
1073 * original, copy-on-write page from the backing object are
1074 * removed from those other address spaces.
1076 * The flag check is racy, but this is tolerable: if
1077 * OBJ_ONEMAPPING is cleared after the check, the busy state
1078 * ensures that new mappings of m_cow can't be created.
1079 * pmap_enter() will replace an existing mapping in the current
1080 * address space. If OBJ_ONEMAPPING is set after the check,
1081 * removing mappings will at worse trigger some unnecessary page
1084 vm_page_assert_xbusied(fs->m_cow);
1085 if ((fs->first_object->flags & OBJ_ONEMAPPING) == 0)
1086 pmap_remove_all(fs->m_cow);
1089 vm_object_pip_wakeup(fs->object);
1092 * Only use the new page below...
1094 fs->object = fs->first_object;
1095 fs->pindex = fs->first_pindex;
1096 fs->m = fs->first_m;
1097 VM_CNT_INC(v_cow_faults);
1098 curthread->td_cow++;
1101 static enum fault_next_status
1102 vm_fault_next(struct faultstate *fs)
1104 vm_object_t next_object;
1106 if (fs->object == fs->first_object || !fs->can_read_lock)
1107 VM_OBJECT_ASSERT_WLOCKED(fs->object);
1109 VM_OBJECT_ASSERT_LOCKED(fs->object);
1112 * The requested page does not exist at this object/
1113 * offset. Remove the invalid page from the object,
1114 * waking up anyone waiting for it, and continue on to
1115 * the next object. However, if this is the top-level
1116 * object, we must leave the busy page in place to
1117 * prevent another process from rushing past us, and
1118 * inserting the page in that object at the same time
1121 if (fs->object == fs->first_object) {
1122 fs->first_m = fs->m;
1124 } else if (fs->m != NULL) {
1125 if (!vm_fault_object_ensure_wlocked(fs)) {
1126 fs->can_read_lock = false;
1127 vm_fault_unlock_and_deallocate(fs);
1128 return (FAULT_NEXT_RESTART);
1130 vm_fault_page_free(&fs->m);
1134 * Move on to the next object. Lock the next object before
1135 * unlocking the current one.
1137 next_object = fs->object->backing_object;
1138 if (next_object == NULL)
1139 return (FAULT_NEXT_NOOBJ);
1140 MPASS(fs->first_m != NULL);
1141 KASSERT(fs->object != next_object, ("object loop %p", next_object));
1142 if (fs->can_read_lock)
1143 VM_OBJECT_RLOCK(next_object);
1145 VM_OBJECT_WLOCK(next_object);
1146 vm_object_pip_add(next_object, 1);
1147 if (fs->object != fs->first_object)
1148 vm_object_pip_wakeup(fs->object);
1149 fs->pindex += OFF_TO_IDX(fs->object->backing_object_offset);
1150 VM_OBJECT_UNLOCK(fs->object);
1151 fs->object = next_object;
1153 return (FAULT_NEXT_GOTOBJ);
1157 vm_fault_zerofill(struct faultstate *fs)
1161 * If there's no object left, fill the page in the top
1162 * object with zeros.
1164 if (fs->object != fs->first_object) {
1165 vm_object_pip_wakeup(fs->object);
1166 fs->object = fs->first_object;
1167 fs->pindex = fs->first_pindex;
1169 MPASS(fs->first_m != NULL);
1170 MPASS(fs->m == NULL);
1171 fs->m = fs->first_m;
1175 * Zero the page if necessary and mark it valid.
1177 if ((fs->m->flags & PG_ZERO) == 0) {
1178 pmap_zero_page(fs->m);
1180 VM_CNT_INC(v_ozfod);
1183 vm_page_valid(fs->m);
1187 * Initiate page fault after timeout. Returns true if caller should
1188 * do vm_waitpfault() after the call.
1191 vm_fault_allocate_oom(struct faultstate *fs)
1195 vm_fault_unlock_and_deallocate(fs);
1196 if (vm_pfault_oom_attempts < 0)
1198 if (!fs->oom_started) {
1199 fs->oom_started = true;
1200 getmicrotime(&fs->oom_start_time);
1205 timevalsub(&now, &fs->oom_start_time);
1206 if (now.tv_sec < vm_pfault_oom_attempts * vm_pfault_oom_wait)
1211 "proc %d (%s) failed to alloc page on fault, starting OOM\n",
1212 curproc->p_pid, curproc->p_comm);
1213 vm_pageout_oom(VM_OOM_MEM_PF);
1214 fs->oom_started = false;
1219 * Allocate a page directly or via the object populate method.
1221 static enum fault_status
1222 vm_fault_allocate(struct faultstate *fs)
1224 struct domainset *dset;
1225 enum fault_status res;
1227 if ((fs->object->flags & OBJ_SIZEVNLOCK) != 0) {
1228 res = vm_fault_lock_vnode(fs, true);
1229 MPASS(res == FAULT_CONTINUE || res == FAULT_RESTART);
1230 if (res == FAULT_RESTART)
1234 if (fs->pindex >= fs->object->size) {
1235 vm_fault_unlock_and_deallocate(fs);
1236 return (FAULT_OUT_OF_BOUNDS);
1239 if (fs->object == fs->first_object &&
1240 (fs->first_object->flags & OBJ_POPULATE) != 0 &&
1241 fs->first_object->shadow_count == 0) {
1242 res = vm_fault_populate(fs);
1247 vm_fault_unlock_and_deallocate(fs);
1249 case FAULT_CONTINUE:
1251 * Pager's populate() method
1252 * returned VM_PAGER_BAD.
1256 panic("inconsistent return codes");
1261 * Allocate a new page for this object/offset pair.
1263 * If the process has a fatal signal pending, prioritize the allocation
1264 * with the expectation that the process will exit shortly and free some
1265 * pages. In particular, the signal may have been posted by the page
1266 * daemon in an attempt to resolve an out-of-memory condition.
1268 * The unlocked read of the p_flag is harmless. At worst, the P_KILLED
1269 * might be not observed here, and allocation fails, causing a restart
1270 * and new reading of the p_flag.
1272 dset = fs->object->domain.dr_policy;
1274 dset = curthread->td_domain.dr_policy;
1275 if (!vm_page_count_severe_set(&dset->ds_mask) || P_KILLED(curproc)) {
1276 #if VM_NRESERVLEVEL > 0
1277 vm_object_color(fs->object, atop(fs->vaddr) - fs->pindex);
1279 if (!vm_pager_can_alloc_page(fs->object, fs->pindex)) {
1280 vm_fault_unlock_and_deallocate(fs);
1281 return (FAULT_FAILURE);
1283 fs->m = vm_page_alloc(fs->object, fs->pindex,
1284 P_KILLED(curproc) ? VM_ALLOC_SYSTEM : 0);
1286 if (fs->m == NULL) {
1287 if (vm_fault_allocate_oom(fs))
1288 vm_waitpfault(dset, vm_pfault_oom_wait * hz);
1289 return (FAULT_RESTART);
1291 fs->oom_started = false;
1293 return (FAULT_CONTINUE);
1297 * Call the pager to retrieve the page if there is a chance
1298 * that the pager has it, and potentially retrieve additional
1299 * pages at the same time.
1301 static enum fault_status
1302 vm_fault_getpages(struct faultstate *fs, int *behindp, int *aheadp)
1304 vm_offset_t e_end, e_start;
1305 int ahead, behind, cluster_offset, rv;
1306 enum fault_status status;
1310 * Prepare for unlocking the map. Save the map
1311 * entry's start and end addresses, which are used to
1312 * optimize the size of the pager operation below.
1313 * Even if the map entry's addresses change after
1314 * unlocking the map, using the saved addresses is
1317 e_start = fs->entry->start;
1318 e_end = fs->entry->end;
1319 behavior = vm_map_entry_behavior(fs->entry);
1322 * If the pager for the current object might have
1323 * the page, then determine the number of additional
1324 * pages to read and potentially reprioritize
1325 * previously read pages for earlier reclamation.
1326 * These operations should only be performed once per
1327 * page fault. Even if the current pager doesn't
1328 * have the page, the number of additional pages to
1329 * read will apply to subsequent objects in the
1332 if (fs->nera == -1 && !P_KILLED(curproc))
1333 fs->nera = vm_fault_readahead(fs);
1336 * Release the map lock before locking the vnode or
1337 * sleeping in the pager. (If the current object has
1338 * a shadow, then an earlier iteration of this loop
1339 * may have already unlocked the map.)
1341 vm_fault_unlock_map(fs);
1343 status = vm_fault_lock_vnode(fs, false);
1344 MPASS(status == FAULT_CONTINUE || status == FAULT_RESTART);
1345 if (status == FAULT_RESTART)
1347 KASSERT(fs->vp == NULL || !fs->map->system_map,
1348 ("vm_fault: vnode-backed object mapped by system map"));
1351 * Page in the requested page and hint the pager,
1352 * that it may bring up surrounding pages.
1354 if (fs->nera == -1 || behavior == MAP_ENTRY_BEHAV_RANDOM ||
1355 P_KILLED(curproc)) {
1359 /* Is this a sequential fault? */
1365 * Request a cluster of pages that is
1366 * aligned to a VM_FAULT_READ_DEFAULT
1367 * page offset boundary within the
1368 * object. Alignment to a page offset
1369 * boundary is more likely to coincide
1370 * with the underlying file system
1371 * block than alignment to a virtual
1374 cluster_offset = fs->pindex % VM_FAULT_READ_DEFAULT;
1375 behind = ulmin(cluster_offset,
1376 atop(fs->vaddr - e_start));
1377 ahead = VM_FAULT_READ_DEFAULT - 1 - cluster_offset;
1379 ahead = ulmin(ahead, atop(e_end - fs->vaddr) - 1);
1383 rv = vm_pager_get_pages(fs->object, &fs->m, 1, behindp, aheadp);
1384 if (rv == VM_PAGER_OK)
1385 return (FAULT_HARD);
1386 if (rv == VM_PAGER_ERROR)
1387 printf("vm_fault: pager read error, pid %d (%s)\n",
1388 curproc->p_pid, curproc->p_comm);
1390 * If an I/O error occurred or the requested page was
1391 * outside the range of the pager, clean up and return
1394 if (rv == VM_PAGER_ERROR || rv == VM_PAGER_BAD) {
1395 VM_OBJECT_WLOCK(fs->object);
1396 vm_fault_page_free(&fs->m);
1397 vm_fault_unlock_and_deallocate(fs);
1398 return (FAULT_OUT_OF_BOUNDS);
1400 KASSERT(rv == VM_PAGER_FAIL,
1401 ("%s: unexpected pager error %d", __func__, rv));
1402 return (FAULT_CONTINUE);
1406 * Wait/Retry if the page is busy. We have to do this if the page is
1407 * either exclusive or shared busy because the vm_pager may be using
1408 * read busy for pageouts (and even pageins if it is the vnode pager),
1409 * and we could end up trying to pagein and pageout the same page
1412 * We can theoretically allow the busy case on a read fault if the page
1413 * is marked valid, but since such pages are typically already pmap'd,
1414 * putting that special case in might be more effort then it is worth.
1415 * We cannot under any circumstances mess around with a shared busied
1416 * page except, perhaps, to pmap it.
1419 vm_fault_busy_sleep(struct faultstate *fs)
1422 * Reference the page before unlocking and
1423 * sleeping so that the page daemon is less
1424 * likely to reclaim it.
1426 vm_page_aflag_set(fs->m, PGA_REFERENCED);
1427 if (fs->object != fs->first_object) {
1428 vm_fault_page_release(&fs->first_m);
1429 vm_object_pip_wakeup(fs->first_object);
1431 vm_object_pip_wakeup(fs->object);
1432 vm_fault_unlock_map(fs);
1433 if (fs->m != vm_page_lookup(fs->object, fs->pindex) ||
1434 !vm_page_busy_sleep(fs->m, "vmpfw", 0))
1435 VM_OBJECT_UNLOCK(fs->object);
1436 VM_CNT_INC(v_intrans);
1437 vm_object_deallocate(fs->first_object);
1441 * Handle page lookup, populate, allocate, page-in for the current
1444 * The object is locked on entry and will remain locked with a return
1445 * code of FAULT_CONTINUE so that fault may follow the shadow chain.
1446 * Otherwise, the object will be unlocked upon return.
1448 static enum fault_status
1449 vm_fault_object(struct faultstate *fs, int *behindp, int *aheadp)
1451 enum fault_status res;
1454 if (fs->object == fs->first_object || !fs->can_read_lock)
1455 VM_OBJECT_ASSERT_WLOCKED(fs->object);
1457 VM_OBJECT_ASSERT_LOCKED(fs->object);
1460 * If the object is marked for imminent termination, we retry
1461 * here, since the collapse pass has raced with us. Otherwise,
1462 * if we see terminally dead object, return fail.
1464 if ((fs->object->flags & OBJ_DEAD) != 0) {
1465 dead = fs->object->type == OBJT_DEAD;
1466 vm_fault_unlock_and_deallocate(fs);
1468 return (FAULT_PROTECTION_FAILURE);
1470 return (FAULT_RESTART);
1474 * See if the page is resident.
1476 fs->m = vm_page_lookup(fs->object, fs->pindex);
1477 if (fs->m != NULL) {
1478 if (!vm_page_tryxbusy(fs->m)) {
1479 vm_fault_busy_sleep(fs);
1480 return (FAULT_RESTART);
1484 * The page is marked busy for other processes and the
1485 * pagedaemon. If it is still completely valid we are
1488 if (vm_page_all_valid(fs->m)) {
1489 VM_OBJECT_UNLOCK(fs->object);
1490 return (FAULT_SOFT);
1495 * Page is not resident. If the pager might contain the page
1496 * or this is the beginning of the search, allocate a new
1499 if (fs->m == NULL && (vm_fault_object_needs_getpages(fs->object) ||
1500 fs->object == fs->first_object)) {
1501 if (!vm_fault_object_ensure_wlocked(fs)) {
1502 fs->can_read_lock = false;
1503 vm_fault_unlock_and_deallocate(fs);
1504 return (FAULT_RESTART);
1506 res = vm_fault_allocate(fs);
1507 if (res != FAULT_CONTINUE)
1512 * Check to see if the pager can possibly satisfy this fault.
1513 * If not, skip to the next object without dropping the lock to
1514 * preserve atomicity of shadow faults.
1516 if (vm_fault_object_needs_getpages(fs->object)) {
1518 * At this point, we have either allocated a new page
1519 * or found an existing page that is only partially
1522 * We hold a reference on the current object and the
1523 * page is exclusive busied. The exclusive busy
1524 * prevents simultaneous faults and collapses while
1525 * the object lock is dropped.
1527 VM_OBJECT_UNLOCK(fs->object);
1528 res = vm_fault_getpages(fs, behindp, aheadp);
1529 if (res == FAULT_CONTINUE)
1530 VM_OBJECT_WLOCK(fs->object);
1532 res = FAULT_CONTINUE;
1538 vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
1539 int fault_flags, vm_page_t *m_hold)
1541 struct faultstate fs;
1542 int ahead, behind, faultcount, rv;
1543 enum fault_status res;
1544 enum fault_next_status res_next;
1547 VM_CNT_INC(v_vm_faults);
1549 if ((curthread->td_pflags & TDP_NOFAULTING) != 0)
1550 return (KERN_PROTECTION_FAILURE);
1555 fs.fault_flags = fault_flags;
1557 fs.lookup_still_valid = false;
1558 fs.oom_started = false;
1560 fs.can_read_lock = true;
1565 fs.fault_type = fault_type;
1568 * Find the backing store object and offset into it to begin the
1571 rv = vm_fault_lookup(&fs);
1572 if (rv != KERN_SUCCESS) {
1573 if (rv == KERN_RESOURCE_SHORTAGE)
1579 * Try to avoid lock contention on the top-level object through
1580 * special-case handling of some types of page faults, specifically,
1581 * those that are mapping an existing page from the top-level object.
1582 * Under this condition, a read lock on the object suffices, allowing
1583 * multiple page faults of a similar type to run in parallel.
1585 if (fs.vp == NULL /* avoid locked vnode leak */ &&
1586 (fs.entry->eflags & MAP_ENTRY_SPLIT_BOUNDARY_MASK) == 0 &&
1587 (fs.fault_flags & (VM_FAULT_WIRE | VM_FAULT_DIRTY)) == 0) {
1588 res = vm_fault_soft_fast(&fs);
1589 if (res == FAULT_SUCCESS) {
1590 VM_OBJECT_ASSERT_UNLOCKED(fs.first_object);
1591 return (KERN_SUCCESS);
1593 VM_OBJECT_ASSERT_WLOCKED(fs.first_object);
1595 VM_OBJECT_WLOCK(fs.first_object);
1599 * Make a reference to this object to prevent its disposal while we
1600 * are messing with it. Once we have the reference, the map is free
1601 * to be diddled. Since objects reference their shadows (and copies),
1602 * they will stay around as well.
1604 * Bump the paging-in-progress count to prevent size changes (e.g.
1605 * truncation operations) during I/O.
1607 vm_object_reference_locked(fs.first_object);
1608 vm_object_pip_add(fs.first_object, 1);
1610 fs.m_cow = fs.m = fs.first_m = NULL;
1613 * Search for the page at object/offset.
1615 fs.object = fs.first_object;
1616 fs.pindex = fs.first_pindex;
1618 if ((fs.entry->eflags & MAP_ENTRY_SPLIT_BOUNDARY_MASK) != 0) {
1619 res = vm_fault_allocate(&fs);
1624 return (KERN_SUCCESS);
1626 return (KERN_FAILURE);
1627 case FAULT_OUT_OF_BOUNDS:
1628 return (KERN_OUT_OF_BOUNDS);
1629 case FAULT_CONTINUE:
1632 panic("vm_fault: Unhandled status %d", res);
1637 KASSERT(fs.m == NULL,
1638 ("page still set %p at loop start", fs.m));
1640 res = vm_fault_object(&fs, &behind, &ahead);
1645 faultcount = behind + 1 + ahead;
1651 return (KERN_SUCCESS);
1653 return (KERN_FAILURE);
1654 case FAULT_OUT_OF_BOUNDS:
1655 return (KERN_OUT_OF_BOUNDS);
1656 case FAULT_PROTECTION_FAILURE:
1657 return (KERN_PROTECTION_FAILURE);
1658 case FAULT_CONTINUE:
1661 panic("vm_fault: Unhandled status %d", res);
1665 * The page was not found in the current object. Try to
1666 * traverse into a backing object or zero fill if none is
1669 res_next = vm_fault_next(&fs);
1670 if (res_next == FAULT_NEXT_RESTART)
1672 else if (res_next == FAULT_NEXT_GOTOBJ)
1674 MPASS(res_next == FAULT_NEXT_NOOBJ);
1675 if ((fs.fault_flags & VM_FAULT_NOFILL) != 0) {
1676 if (fs.first_object == fs.object)
1677 vm_fault_page_free(&fs.first_m);
1678 vm_fault_unlock_and_deallocate(&fs);
1679 return (KERN_OUT_OF_BOUNDS);
1681 VM_OBJECT_UNLOCK(fs.object);
1682 vm_fault_zerofill(&fs);
1683 /* Don't try to prefault neighboring pages. */
1690 * A valid page has been found and exclusively busied. The
1691 * object lock must no longer be held.
1693 vm_page_assert_xbusied(fs.m);
1694 VM_OBJECT_ASSERT_UNLOCKED(fs.object);
1697 * If the page is being written, but isn't already owned by the
1698 * top-level object, we have to copy it into a new page owned by the
1701 if (fs.object != fs.first_object) {
1703 * We only really need to copy if we want to write it.
1705 if ((fs.fault_type & (VM_PROT_COPY | VM_PROT_WRITE)) != 0) {
1708 * We only try to prefault read-only mappings to the
1709 * neighboring pages when this copy-on-write fault is
1710 * a hard fault. In other cases, trying to prefault
1711 * is typically wasted effort.
1713 if (faultcount == 0)
1717 fs.prot &= ~VM_PROT_WRITE;
1722 * We must verify that the maps have not changed since our last
1725 if (!fs.lookup_still_valid) {
1726 rv = vm_fault_relookup(&fs);
1727 if (rv != KERN_SUCCESS) {
1728 vm_fault_deallocate(&fs);
1729 if (rv == KERN_RESTART)
1734 VM_OBJECT_ASSERT_UNLOCKED(fs.object);
1737 * If the page was filled by a pager, save the virtual address that
1738 * should be faulted on next under a sequential access pattern to the
1739 * map entry. A read lock on the map suffices to update this address
1743 fs.entry->next_read = vaddr + ptoa(ahead) + PAGE_SIZE;
1746 * Page must be completely valid or it is not fit to
1747 * map into user space. vm_pager_get_pages() ensures this.
1749 vm_page_assert_xbusied(fs.m);
1750 KASSERT(vm_page_all_valid(fs.m),
1751 ("vm_fault: page %p partially invalid", fs.m));
1753 vm_fault_dirty(&fs, fs.m);
1756 * Put this page into the physical map. We had to do the unlock above
1757 * because pmap_enter() may sleep. We don't put the page
1758 * back on the active queue until later so that the pageout daemon
1759 * won't find it (yet).
1761 pmap_enter(fs.map->pmap, vaddr, fs.m, fs.prot,
1762 fs.fault_type | (fs.wired ? PMAP_ENTER_WIRED : 0), 0);
1763 if (faultcount != 1 && (fs.fault_flags & VM_FAULT_WIRE) == 0 &&
1765 vm_fault_prefault(&fs, vaddr,
1766 faultcount > 0 ? behind : PFBAK,
1767 faultcount > 0 ? ahead : PFFOR, false);
1770 * If the page is not wired down, then put it where the pageout daemon
1773 if ((fs.fault_flags & VM_FAULT_WIRE) != 0)
1776 vm_page_activate(fs.m);
1777 if (fs.m_hold != NULL) {
1778 (*fs.m_hold) = fs.m;
1781 vm_page_xunbusy(fs.m);
1785 * Unlock everything, and return
1787 vm_fault_deallocate(&fs);
1789 VM_CNT_INC(v_io_faults);
1790 curthread->td_ru.ru_majflt++;
1792 if (racct_enable && fs.object->type == OBJT_VNODE) {
1794 if ((fs.fault_type & (VM_PROT_COPY | VM_PROT_WRITE)) != 0) {
1795 racct_add_force(curproc, RACCT_WRITEBPS,
1796 PAGE_SIZE + behind * PAGE_SIZE);
1797 racct_add_force(curproc, RACCT_WRITEIOPS, 1);
1799 racct_add_force(curproc, RACCT_READBPS,
1800 PAGE_SIZE + ahead * PAGE_SIZE);
1801 racct_add_force(curproc, RACCT_READIOPS, 1);
1803 PROC_UNLOCK(curproc);
1807 curthread->td_ru.ru_minflt++;
1809 return (KERN_SUCCESS);
1813 * Speed up the reclamation of pages that precede the faulting pindex within
1814 * the first object of the shadow chain. Essentially, perform the equivalent
1815 * to madvise(..., MADV_DONTNEED) on a large cluster of pages that precedes
1816 * the faulting pindex by the cluster size when the pages read by vm_fault()
1817 * cross a cluster-size boundary. The cluster size is the greater of the
1818 * smallest superpage size and VM_FAULT_DONTNEED_MIN.
1820 * When "fs->first_object" is a shadow object, the pages in the backing object
1821 * that precede the faulting pindex are deactivated by vm_fault(). So, this
1822 * function must only be concerned with pages in the first object.
1825 vm_fault_dontneed(const struct faultstate *fs, vm_offset_t vaddr, int ahead)
1827 vm_map_entry_t entry;
1828 vm_object_t first_object;
1829 vm_offset_t end, start;
1830 vm_page_t m, m_next;
1831 vm_pindex_t pend, pstart;
1834 VM_OBJECT_ASSERT_UNLOCKED(fs->object);
1835 first_object = fs->first_object;
1836 /* Neither fictitious nor unmanaged pages can be reclaimed. */
1837 if ((first_object->flags & (OBJ_FICTITIOUS | OBJ_UNMANAGED)) == 0) {
1838 VM_OBJECT_RLOCK(first_object);
1839 size = VM_FAULT_DONTNEED_MIN;
1840 if (MAXPAGESIZES > 1 && size < pagesizes[1])
1841 size = pagesizes[1];
1842 end = rounddown2(vaddr, size);
1843 if (vaddr - end >= size - PAGE_SIZE - ptoa(ahead) &&
1844 (entry = fs->entry)->start < end) {
1845 if (end - entry->start < size)
1846 start = entry->start;
1849 pmap_advise(fs->map->pmap, start, end, MADV_DONTNEED);
1850 pstart = OFF_TO_IDX(entry->offset) + atop(start -
1852 m_next = vm_page_find_least(first_object, pstart);
1853 pend = OFF_TO_IDX(entry->offset) + atop(end -
1855 while ((m = m_next) != NULL && m->pindex < pend) {
1856 m_next = TAILQ_NEXT(m, listq);
1857 if (!vm_page_all_valid(m) ||
1862 * Don't clear PGA_REFERENCED, since it would
1863 * likely represent a reference by a different
1866 * Typically, at this point, prefetched pages
1867 * are still in the inactive queue. Only
1868 * pages that triggered page faults are in the
1869 * active queue. The test for whether the page
1870 * is in the inactive queue is racy; in the
1871 * worst case we will requeue the page
1874 if (!vm_page_inactive(m))
1875 vm_page_deactivate(m);
1878 VM_OBJECT_RUNLOCK(first_object);
1883 * vm_fault_prefault provides a quick way of clustering
1884 * pagefaults into a processes address space. It is a "cousin"
1885 * of vm_map_pmap_enter, except it runs at page fault time instead
1889 vm_fault_prefault(const struct faultstate *fs, vm_offset_t addra,
1890 int backward, int forward, bool obj_locked)
1893 vm_map_entry_t entry;
1894 vm_object_t backing_object, lobject;
1895 vm_offset_t addr, starta;
1900 pmap = fs->map->pmap;
1901 if (pmap != vmspace_pmap(curthread->td_proc->p_vmspace))
1906 if (addra < backward * PAGE_SIZE) {
1907 starta = entry->start;
1909 starta = addra - backward * PAGE_SIZE;
1910 if (starta < entry->start)
1911 starta = entry->start;
1915 * Generate the sequence of virtual addresses that are candidates for
1916 * prefaulting in an outward spiral from the faulting virtual address,
1917 * "addra". Specifically, the sequence is "addra - PAGE_SIZE", "addra
1918 * + PAGE_SIZE", "addra - 2 * PAGE_SIZE", "addra + 2 * PAGE_SIZE", ...
1919 * If the candidate address doesn't have a backing physical page, then
1920 * the loop immediately terminates.
1922 for (i = 0; i < 2 * imax(backward, forward); i++) {
1923 addr = addra + ((i >> 1) + 1) * ((i & 1) == 0 ? -PAGE_SIZE :
1925 if (addr > addra + forward * PAGE_SIZE)
1928 if (addr < starta || addr >= entry->end)
1931 if (!pmap_is_prefaultable(pmap, addr))
1934 pindex = ((addr - entry->start) + entry->offset) >> PAGE_SHIFT;
1935 lobject = entry->object.vm_object;
1937 VM_OBJECT_RLOCK(lobject);
1938 while ((m = vm_page_lookup(lobject, pindex)) == NULL &&
1939 !vm_fault_object_needs_getpages(lobject) &&
1940 (backing_object = lobject->backing_object) != NULL) {
1941 KASSERT((lobject->backing_object_offset & PAGE_MASK) ==
1942 0, ("vm_fault_prefault: unaligned object offset"));
1943 pindex += lobject->backing_object_offset >> PAGE_SHIFT;
1944 VM_OBJECT_RLOCK(backing_object);
1945 if (!obj_locked || lobject != entry->object.vm_object)
1946 VM_OBJECT_RUNLOCK(lobject);
1947 lobject = backing_object;
1950 if (!obj_locked || lobject != entry->object.vm_object)
1951 VM_OBJECT_RUNLOCK(lobject);
1954 if (vm_page_all_valid(m) &&
1955 (m->flags & PG_FICTITIOUS) == 0)
1956 pmap_enter_quick(pmap, addr, m, entry->protection);
1957 if (!obj_locked || lobject != entry->object.vm_object)
1958 VM_OBJECT_RUNLOCK(lobject);
1963 * Hold each of the physical pages that are mapped by the specified range of
1964 * virtual addresses, ["addr", "addr" + "len"), if those mappings are valid
1965 * and allow the specified types of access, "prot". If all of the implied
1966 * pages are successfully held, then the number of held pages is returned
1967 * together with pointers to those pages in the array "ma". However, if any
1968 * of the pages cannot be held, -1 is returned.
1971 vm_fault_quick_hold_pages(vm_map_t map, vm_offset_t addr, vm_size_t len,
1972 vm_prot_t prot, vm_page_t *ma, int max_count)
1974 vm_offset_t end, va;
1977 boolean_t pmap_failed;
1981 end = round_page(addr + len);
1982 addr = trunc_page(addr);
1984 if (!vm_map_range_valid(map, addr, end))
1987 if (atop(end - addr) > max_count)
1988 panic("vm_fault_quick_hold_pages: count > max_count");
1989 count = atop(end - addr);
1992 * Most likely, the physical pages are resident in the pmap, so it is
1993 * faster to try pmap_extract_and_hold() first.
1995 pmap_failed = FALSE;
1996 for (mp = ma, va = addr; va < end; mp++, va += PAGE_SIZE) {
1997 *mp = pmap_extract_and_hold(map->pmap, va, prot);
2000 else if ((prot & VM_PROT_WRITE) != 0 &&
2001 (*mp)->dirty != VM_PAGE_BITS_ALL) {
2003 * Explicitly dirty the physical page. Otherwise, the
2004 * caller's changes may go unnoticed because they are
2005 * performed through an unmanaged mapping or by a DMA
2008 * The object lock is not held here.
2009 * See vm_page_clear_dirty_mask().
2016 * One or more pages could not be held by the pmap. Either no
2017 * page was mapped at the specified virtual address or that
2018 * mapping had insufficient permissions. Attempt to fault in
2019 * and hold these pages.
2021 * If vm_fault_disable_pagefaults() was called,
2022 * i.e., TDP_NOFAULTING is set, we must not sleep nor
2023 * acquire MD VM locks, which means we must not call
2024 * vm_fault(). Some (out of tree) callers mark
2025 * too wide a code area with vm_fault_disable_pagefaults()
2026 * already, use the VM_PROT_QUICK_NOFAULT flag to request
2027 * the proper behaviour explicitly.
2029 if ((prot & VM_PROT_QUICK_NOFAULT) != 0 &&
2030 (curthread->td_pflags & TDP_NOFAULTING) != 0)
2032 for (mp = ma, va = addr; va < end; mp++, va += PAGE_SIZE)
2033 if (*mp == NULL && vm_fault(map, va, prot,
2034 VM_FAULT_NORMAL, mp) != KERN_SUCCESS)
2039 for (mp = ma; mp < ma + count; mp++)
2041 vm_page_unwire(*mp, PQ_INACTIVE);
2047 * vm_fault_copy_entry
2049 * Create new object backing dst_entry with private copy of all
2050 * underlying pages. When src_entry is equal to dst_entry, function
2051 * implements COW for wired-down map entry. Otherwise, it forks
2052 * wired entry into dst_map.
2054 * In/out conditions:
2055 * The source and destination maps must be locked for write.
2056 * The source map entry must be wired down (or be a sharing map
2057 * entry corresponding to a main map entry that is wired down).
2060 vm_fault_copy_entry(vm_map_t dst_map, vm_map_t src_map __unused,
2061 vm_map_entry_t dst_entry, vm_map_entry_t src_entry,
2062 vm_ooffset_t *fork_charge)
2064 vm_object_t backing_object, dst_object, object, src_object;
2065 vm_pindex_t dst_pindex, pindex, src_pindex;
2066 vm_prot_t access, prot;
2072 upgrade = src_entry == dst_entry;
2073 KASSERT(upgrade || dst_entry->object.vm_object == NULL,
2074 ("vm_fault_copy_entry: vm_object not NULL"));
2077 * If not an upgrade, then enter the mappings in the pmap as
2078 * read and/or execute accesses. Otherwise, enter them as
2081 * A writeable large page mapping is only created if all of
2082 * the constituent small page mappings are modified. Marking
2083 * PTEs as modified on inception allows promotion to happen
2084 * without taking potentially large number of soft faults.
2086 access = prot = dst_entry->protection;
2088 access &= ~VM_PROT_WRITE;
2090 src_object = src_entry->object.vm_object;
2091 src_pindex = OFF_TO_IDX(src_entry->offset);
2093 if (upgrade && (dst_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) {
2094 dst_object = src_object;
2095 vm_object_reference(dst_object);
2098 * Create the top-level object for the destination entry.
2099 * Doesn't actually shadow anything - we copy the pages
2102 dst_object = vm_object_allocate_anon(atop(dst_entry->end -
2103 dst_entry->start), NULL, NULL, 0);
2104 #if VM_NRESERVLEVEL > 0
2105 dst_object->flags |= OBJ_COLORED;
2106 dst_object->pg_color = atop(dst_entry->start);
2108 dst_object->domain = src_object->domain;
2109 dst_object->charge = dst_entry->end - dst_entry->start;
2111 dst_entry->object.vm_object = dst_object;
2112 dst_entry->offset = 0;
2113 dst_entry->eflags &= ~MAP_ENTRY_VN_EXEC;
2116 VM_OBJECT_WLOCK(dst_object);
2117 if (fork_charge != NULL) {
2118 KASSERT(dst_entry->cred == NULL,
2119 ("vm_fault_copy_entry: leaked swp charge"));
2120 dst_object->cred = curthread->td_ucred;
2121 crhold(dst_object->cred);
2122 *fork_charge += dst_object->charge;
2123 } else if ((dst_object->flags & OBJ_SWAP) != 0 &&
2124 dst_object->cred == NULL) {
2125 KASSERT(dst_entry->cred != NULL, ("no cred for entry %p",
2127 dst_object->cred = dst_entry->cred;
2128 dst_entry->cred = NULL;
2132 * Loop through all of the virtual pages within the entry's
2133 * range, copying each page from the source object to the
2134 * destination object. Since the source is wired, those pages
2135 * must exist. In contrast, the destination is pageable.
2136 * Since the destination object doesn't share any backing storage
2137 * with the source object, all of its pages must be dirtied,
2138 * regardless of whether they can be written.
2140 for (vaddr = dst_entry->start, dst_pindex = 0;
2141 vaddr < dst_entry->end;
2142 vaddr += PAGE_SIZE, dst_pindex++) {
2145 * Find the page in the source object, and copy it in.
2146 * Because the source is wired down, the page will be
2149 if (src_object != dst_object)
2150 VM_OBJECT_RLOCK(src_object);
2151 object = src_object;
2152 pindex = src_pindex + dst_pindex;
2153 while ((src_m = vm_page_lookup(object, pindex)) == NULL &&
2154 (backing_object = object->backing_object) != NULL) {
2156 * Unless the source mapping is read-only or
2157 * it is presently being upgraded from
2158 * read-only, the first object in the shadow
2159 * chain should provide all of the pages. In
2160 * other words, this loop body should never be
2161 * executed when the source mapping is already
2164 KASSERT((src_entry->protection & VM_PROT_WRITE) == 0 ||
2166 ("vm_fault_copy_entry: main object missing page"));
2168 VM_OBJECT_RLOCK(backing_object);
2169 pindex += OFF_TO_IDX(object->backing_object_offset);
2170 if (object != dst_object)
2171 VM_OBJECT_RUNLOCK(object);
2172 object = backing_object;
2174 KASSERT(src_m != NULL, ("vm_fault_copy_entry: page missing"));
2176 if (object != dst_object) {
2178 * Allocate a page in the destination object.
2180 dst_m = vm_page_alloc(dst_object, (src_object ==
2181 dst_object ? src_pindex : 0) + dst_pindex,
2183 if (dst_m == NULL) {
2184 VM_OBJECT_WUNLOCK(dst_object);
2185 VM_OBJECT_RUNLOCK(object);
2186 vm_wait(dst_object);
2187 VM_OBJECT_WLOCK(dst_object);
2192 * See the comment in vm_fault_cow().
2194 if (src_object == dst_object &&
2195 (object->flags & OBJ_ONEMAPPING) == 0)
2196 pmap_remove_all(src_m);
2197 pmap_copy_page(src_m, dst_m);
2200 * The object lock does not guarantee that "src_m" will
2201 * transition from invalid to valid, but it does ensure
2202 * that "src_m" will not transition from valid to
2205 dst_m->dirty = dst_m->valid = src_m->valid;
2206 VM_OBJECT_RUNLOCK(object);
2209 if (vm_page_busy_acquire(dst_m, VM_ALLOC_WAITFAIL) == 0)
2211 if (dst_m->pindex >= dst_object->size) {
2213 * We are upgrading. Index can occur
2214 * out of bounds if the object type is
2215 * vnode and the file was truncated.
2217 vm_page_xunbusy(dst_m);
2223 * Enter it in the pmap. If a wired, copy-on-write
2224 * mapping is being replaced by a write-enabled
2225 * mapping, then wire that new mapping.
2227 * The page can be invalid if the user called
2228 * msync(MS_INVALIDATE) or truncated the backing vnode
2229 * or shared memory object. In this case, do not
2230 * insert it into pmap, but still do the copy so that
2231 * all copies of the wired map entry have similar
2234 if (vm_page_all_valid(dst_m)) {
2235 VM_OBJECT_WUNLOCK(dst_object);
2236 pmap_enter(dst_map->pmap, vaddr, dst_m, prot,
2237 access | (upgrade ? PMAP_ENTER_WIRED : 0), 0);
2238 VM_OBJECT_WLOCK(dst_object);
2242 * Mark it no longer busy, and put it on the active list.
2245 if (src_m != dst_m) {
2246 vm_page_unwire(src_m, PQ_INACTIVE);
2247 vm_page_wire(dst_m);
2249 KASSERT(vm_page_wired(dst_m),
2250 ("dst_m %p is not wired", dst_m));
2253 vm_page_activate(dst_m);
2255 vm_page_xunbusy(dst_m);
2257 VM_OBJECT_WUNLOCK(dst_object);
2259 dst_entry->eflags &= ~(MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY);
2260 vm_object_deallocate(src_object);
2265 * Block entry into the machine-independent layer's page fault handler by
2266 * the calling thread. Subsequent calls to vm_fault() by that thread will
2267 * return KERN_PROTECTION_FAILURE. Enable machine-dependent handling of
2268 * spurious page faults.
2271 vm_fault_disable_pagefaults(void)
2274 return (curthread_pflags_set(TDP_NOFAULTING | TDP_RESETSPUR));
2278 vm_fault_enable_pagefaults(int save)
2281 curthread_pflags_restore(save);