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;
136 /* Page reference for cow. */
139 /* Current object. */
144 /* Top-level map object. */
145 vm_object_t first_object;
146 vm_pindex_t first_pindex;
151 vm_map_entry_t entry;
153 bool lookup_still_valid;
155 /* Vnode if locked. */
160 * Return codes for internal fault routines.
163 FAULT_SUCCESS = 1, /* Return success to user. */
164 FAULT_FAILURE, /* Return failure to user. */
165 FAULT_CONTINUE, /* Continue faulting. */
166 FAULT_RESTART, /* Restart fault. */
167 FAULT_OUT_OF_BOUNDS, /* Invalid address for pager. */
168 FAULT_HARD, /* Performed I/O. */
169 FAULT_SOFT, /* Found valid page. */
170 FAULT_PROTECTION_FAILURE, /* Invalid access. */
173 static void vm_fault_dontneed(const struct faultstate *fs, vm_offset_t vaddr,
175 static void vm_fault_prefault(const struct faultstate *fs, vm_offset_t addra,
176 int backward, int forward, bool obj_locked);
178 static int vm_pfault_oom_attempts = 3;
179 SYSCTL_INT(_vm, OID_AUTO, pfault_oom_attempts, CTLFLAG_RWTUN,
180 &vm_pfault_oom_attempts, 0,
181 "Number of page allocation attempts in page fault handler before it "
182 "triggers OOM handling");
184 static int vm_pfault_oom_wait = 10;
185 SYSCTL_INT(_vm, OID_AUTO, pfault_oom_wait, CTLFLAG_RWTUN,
186 &vm_pfault_oom_wait, 0,
187 "Number of seconds to wait for free pages before retrying "
188 "the page fault handler");
191 fault_page_release(vm_page_t *mp)
198 * We are likely to loop around again and attempt to busy
199 * this page. Deactivating it leaves it available for
200 * pageout while optimizing fault restarts.
202 vm_page_deactivate(m);
209 fault_page_free(vm_page_t *mp)
215 VM_OBJECT_ASSERT_WLOCKED(m->object);
216 if (!vm_page_wired(m))
225 * Return true if a vm_pager_get_pages() call is needed in order to check
226 * whether the pager might have a particular page, false if it can be determined
227 * immediately that the pager can not have a copy. For swap objects, this can
228 * be checked quickly.
231 fault_object_needs_getpages(vm_object_t object)
233 VM_OBJECT_ASSERT_LOCKED(object);
235 return ((object->flags & OBJ_SWAP) == 0 ||
236 !pctrie_is_empty(&object->un_pager.swp.swp_blks));
240 unlock_map(struct faultstate *fs)
243 if (fs->lookup_still_valid) {
244 vm_map_lookup_done(fs->map, fs->entry);
245 fs->lookup_still_valid = false;
250 unlock_vp(struct faultstate *fs)
253 if (fs->vp != NULL) {
260 fault_deallocate(struct faultstate *fs)
263 fault_page_release(&fs->m_cow);
264 fault_page_release(&fs->m);
265 vm_object_pip_wakeup(fs->object);
266 if (fs->object != fs->first_object) {
267 VM_OBJECT_WLOCK(fs->first_object);
268 fault_page_free(&fs->first_m);
269 VM_OBJECT_WUNLOCK(fs->first_object);
270 vm_object_pip_wakeup(fs->first_object);
272 vm_object_deallocate(fs->first_object);
278 unlock_and_deallocate(struct faultstate *fs)
281 VM_OBJECT_WUNLOCK(fs->object);
282 fault_deallocate(fs);
286 vm_fault_dirty(struct faultstate *fs, vm_page_t m)
290 if (((fs->prot & VM_PROT_WRITE) == 0 &&
291 (fs->fault_flags & VM_FAULT_DIRTY) == 0) ||
292 (m->oflags & VPO_UNMANAGED) != 0)
295 VM_PAGE_OBJECT_BUSY_ASSERT(m);
297 need_dirty = ((fs->fault_type & VM_PROT_WRITE) != 0 &&
298 (fs->fault_flags & VM_FAULT_WIRE) == 0) ||
299 (fs->fault_flags & VM_FAULT_DIRTY) != 0;
301 vm_object_set_writeable_dirty(m->object);
304 * If the fault is a write, we know that this page is being
305 * written NOW so dirty it explicitly to save on
306 * pmap_is_modified() calls later.
308 * Also, since the page is now dirty, we can possibly tell
309 * the pager to release any swap backing the page.
311 if (need_dirty && vm_page_set_dirty(m) == 0) {
313 * If this is a NOSYNC mmap we do not want to set PGA_NOSYNC
314 * if the page is already dirty to prevent data written with
315 * the expectation of being synced from not being synced.
316 * Likewise if this entry does not request NOSYNC then make
317 * sure the page isn't marked NOSYNC. Applications sharing
318 * data should use the same flags to avoid ping ponging.
320 if ((fs->entry->eflags & MAP_ENTRY_NOSYNC) != 0)
321 vm_page_aflag_set(m, PGA_NOSYNC);
323 vm_page_aflag_clear(m, PGA_NOSYNC);
329 * Unlocks fs.first_object and fs.map on success.
331 static enum fault_status
332 vm_fault_soft_fast(struct faultstate *fs)
335 #if VM_NRESERVLEVEL > 0
341 enum fault_status res;
343 MPASS(fs->vp == NULL);
347 vm_object_busy(fs->first_object);
348 m = vm_page_lookup(fs->first_object, fs->first_pindex);
349 /* A busy page can be mapped for read|execute access. */
350 if (m == NULL || ((fs->prot & VM_PROT_WRITE) != 0 &&
351 vm_page_busied(m)) || !vm_page_all_valid(m)) {
357 #if VM_NRESERVLEVEL > 0
358 if ((m->flags & PG_FICTITIOUS) == 0 &&
359 (m_super = vm_reserv_to_superpage(m)) != NULL &&
360 rounddown2(vaddr, pagesizes[m_super->psind]) >= fs->entry->start &&
361 roundup2(vaddr + 1, pagesizes[m_super->psind]) <= fs->entry->end &&
362 (vaddr & (pagesizes[m_super->psind] - 1)) == (VM_PAGE_TO_PHYS(m) &
363 (pagesizes[m_super->psind] - 1)) && !fs->wired &&
364 pmap_ps_enabled(fs->map->pmap)) {
365 flags = PS_ALL_VALID;
366 if ((fs->prot & VM_PROT_WRITE) != 0) {
368 * Create a superpage mapping allowing write access
369 * only if none of the constituent pages are busy and
370 * all of them are already dirty (except possibly for
371 * the page that was faulted on).
373 flags |= PS_NONE_BUSY;
374 if ((fs->first_object->flags & OBJ_UNMANAGED) == 0)
375 flags |= PS_ALL_DIRTY;
377 if (vm_page_ps_test(m_super, flags, m)) {
379 psind = m_super->psind;
380 vaddr = rounddown2(vaddr, pagesizes[psind]);
381 /* Preset the modified bit for dirty superpages. */
382 if ((flags & PS_ALL_DIRTY) != 0)
383 fs->fault_type |= VM_PROT_WRITE;
387 if (pmap_enter(fs->map->pmap, vaddr, m_map, fs->prot, fs->fault_type |
388 PMAP_ENTER_NOSLEEP | (fs->wired ? PMAP_ENTER_WIRED : 0), psind) !=
393 if (fs->m_hold != NULL) {
397 if (psind == 0 && !fs->wired)
398 vm_fault_prefault(fs, vaddr, PFBAK, PFFOR, true);
399 VM_OBJECT_RUNLOCK(fs->first_object);
400 vm_fault_dirty(fs, m);
401 vm_map_lookup_done(fs->map, fs->entry);
402 curthread->td_ru.ru_minflt++;
405 vm_object_unbusy(fs->first_object);
410 vm_fault_restore_map_lock(struct faultstate *fs)
413 VM_OBJECT_ASSERT_WLOCKED(fs->first_object);
414 MPASS(blockcount_read(&fs->first_object->paging_in_progress) > 0);
416 if (!vm_map_trylock_read(fs->map)) {
417 VM_OBJECT_WUNLOCK(fs->first_object);
418 vm_map_lock_read(fs->map);
419 VM_OBJECT_WLOCK(fs->first_object);
421 fs->lookup_still_valid = true;
425 vm_fault_populate_check_page(vm_page_t m)
429 * Check each page to ensure that the pager is obeying the
430 * interface: the page must be installed in the object, fully
431 * valid, and exclusively busied.
434 MPASS(vm_page_all_valid(m));
435 MPASS(vm_page_xbusied(m));
439 vm_fault_populate_cleanup(vm_object_t object, vm_pindex_t first,
445 VM_OBJECT_ASSERT_WLOCKED(object);
446 MPASS(first <= last);
447 for (pidx = first, m = vm_page_lookup(object, pidx);
448 pidx <= last; pidx++, m = vm_page_next(m)) {
449 vm_fault_populate_check_page(m);
450 vm_page_deactivate(m);
455 static enum fault_status
456 vm_fault_populate(struct faultstate *fs)
460 vm_pindex_t map_first, map_last, pager_first, pager_last, pidx;
461 int bdry_idx, i, npages, psind, rv;
462 enum fault_status res;
464 MPASS(fs->object == fs->first_object);
465 VM_OBJECT_ASSERT_WLOCKED(fs->first_object);
466 MPASS(blockcount_read(&fs->first_object->paging_in_progress) > 0);
467 MPASS(fs->first_object->backing_object == NULL);
468 MPASS(fs->lookup_still_valid);
470 pager_first = OFF_TO_IDX(fs->entry->offset);
471 pager_last = pager_first + atop(fs->entry->end - fs->entry->start) - 1;
478 * Call the pager (driver) populate() method.
480 * There is no guarantee that the method will be called again
481 * if the current fault is for read, and a future fault is
482 * for write. Report the entry's maximum allowed protection
485 rv = vm_pager_populate(fs->first_object, fs->first_pindex,
486 fs->fault_type, fs->entry->max_protection, &pager_first,
489 VM_OBJECT_ASSERT_WLOCKED(fs->first_object);
490 if (rv == VM_PAGER_BAD) {
492 * VM_PAGER_BAD is the backdoor for a pager to request
493 * normal fault handling.
495 vm_fault_restore_map_lock(fs);
496 if (fs->map->timestamp != fs->map_generation)
497 return (FAULT_RESTART);
498 return (FAULT_CONTINUE);
500 if (rv != VM_PAGER_OK)
501 return (FAULT_FAILURE); /* AKA SIGSEGV */
503 /* Ensure that the driver is obeying the interface. */
504 MPASS(pager_first <= pager_last);
505 MPASS(fs->first_pindex <= pager_last);
506 MPASS(fs->first_pindex >= pager_first);
507 MPASS(pager_last < fs->first_object->size);
509 vm_fault_restore_map_lock(fs);
510 bdry_idx = (fs->entry->eflags & MAP_ENTRY_SPLIT_BOUNDARY_MASK) >>
511 MAP_ENTRY_SPLIT_BOUNDARY_SHIFT;
512 if (fs->map->timestamp != fs->map_generation) {
514 vm_fault_populate_cleanup(fs->first_object, pager_first,
517 m = vm_page_lookup(fs->first_object, pager_first);
521 return (FAULT_RESTART);
525 * The map is unchanged after our last unlock. Process the fault.
527 * First, the special case of largepage mappings, where
528 * populate only busies the first page in superpage run.
531 KASSERT(PMAP_HAS_LARGEPAGES,
532 ("missing pmap support for large pages"));
533 m = vm_page_lookup(fs->first_object, pager_first);
534 vm_fault_populate_check_page(m);
535 VM_OBJECT_WUNLOCK(fs->first_object);
536 vaddr = fs->entry->start + IDX_TO_OFF(pager_first) -
538 /* assert alignment for entry */
539 KASSERT((vaddr & (pagesizes[bdry_idx] - 1)) == 0,
540 ("unaligned superpage start %#jx pager_first %#jx offset %#jx vaddr %#jx",
541 (uintmax_t)fs->entry->start, (uintmax_t)pager_first,
542 (uintmax_t)fs->entry->offset, (uintmax_t)vaddr));
543 KASSERT((VM_PAGE_TO_PHYS(m) & (pagesizes[bdry_idx] - 1)) == 0,
544 ("unaligned superpage m %p %#jx", m,
545 (uintmax_t)VM_PAGE_TO_PHYS(m)));
546 rv = pmap_enter(fs->map->pmap, vaddr, m, fs->prot,
547 fs->fault_type | (fs->wired ? PMAP_ENTER_WIRED : 0) |
548 PMAP_ENTER_LARGEPAGE, bdry_idx);
549 VM_OBJECT_WLOCK(fs->first_object);
551 if (rv != KERN_SUCCESS) {
555 if ((fs->fault_flags & VM_FAULT_WIRE) != 0) {
556 for (i = 0; i < atop(pagesizes[bdry_idx]); i++)
559 if (fs->m_hold != NULL) {
560 *fs->m_hold = m + (fs->first_pindex - pager_first);
561 vm_page_wire(*fs->m_hold);
567 * The range [pager_first, pager_last] that is given to the
568 * pager is only a hint. The pager may populate any range
569 * within the object that includes the requested page index.
570 * In case the pager expanded the range, clip it to fit into
573 map_first = OFF_TO_IDX(fs->entry->offset);
574 if (map_first > pager_first) {
575 vm_fault_populate_cleanup(fs->first_object, pager_first,
577 pager_first = map_first;
579 map_last = map_first + atop(fs->entry->end - fs->entry->start) - 1;
580 if (map_last < pager_last) {
581 vm_fault_populate_cleanup(fs->first_object, map_last + 1,
583 pager_last = map_last;
585 for (pidx = pager_first, m = vm_page_lookup(fs->first_object, pidx);
587 pidx += npages, m = vm_page_next(&m[npages - 1])) {
588 vaddr = fs->entry->start + IDX_TO_OFF(pidx) - fs->entry->offset;
591 if (psind > 0 && ((vaddr & (pagesizes[psind] - 1)) != 0 ||
592 pidx + OFF_TO_IDX(pagesizes[psind]) - 1 > pager_last ||
593 !pmap_ps_enabled(fs->map->pmap) || fs->wired))
596 npages = atop(pagesizes[psind]);
597 for (i = 0; i < npages; i++) {
598 vm_fault_populate_check_page(&m[i]);
599 vm_fault_dirty(fs, &m[i]);
601 VM_OBJECT_WUNLOCK(fs->first_object);
602 rv = pmap_enter(fs->map->pmap, vaddr, m, fs->prot, fs->fault_type |
603 (fs->wired ? PMAP_ENTER_WIRED : 0), psind);
606 * pmap_enter() may fail for a superpage mapping if additional
607 * protection policies prevent the full mapping.
608 * For example, this will happen on amd64 if the entire
609 * address range does not share the same userspace protection
610 * key. Revert to single-page mappings if this happens.
612 MPASS(rv == KERN_SUCCESS ||
613 (psind > 0 && rv == KERN_PROTECTION_FAILURE));
614 if (__predict_false(psind > 0 &&
615 rv == KERN_PROTECTION_FAILURE)) {
617 for (i = 0; i < npages; i++) {
618 rv = pmap_enter(fs->map->pmap, vaddr + ptoa(i),
619 &m[i], fs->prot, fs->fault_type, 0);
620 MPASS(rv == KERN_SUCCESS);
624 VM_OBJECT_WLOCK(fs->first_object);
625 for (i = 0; i < npages; i++) {
626 if ((fs->fault_flags & VM_FAULT_WIRE) != 0 &&
627 m[i].pindex == fs->first_pindex)
630 vm_page_activate(&m[i]);
631 if (fs->m_hold != NULL &&
632 m[i].pindex == fs->first_pindex) {
633 (*fs->m_hold) = &m[i];
636 vm_page_xunbusy(&m[i]);
640 curthread->td_ru.ru_majflt++;
644 static int prot_fault_translation;
645 SYSCTL_INT(_machdep, OID_AUTO, prot_fault_translation, CTLFLAG_RWTUN,
646 &prot_fault_translation, 0,
647 "Control signal to deliver on protection fault");
649 /* compat definition to keep common code for signal translation */
650 #define UCODE_PAGEFLT 12
652 _Static_assert(UCODE_PAGEFLT == T_PAGEFLT, "T_PAGEFLT");
658 * Handle a page fault occurring at the given address,
659 * requiring the given permissions, in the map specified.
660 * If successful, the page is inserted into the
661 * associated physical map.
663 * NOTE: the given address should be truncated to the
664 * proper page address.
666 * KERN_SUCCESS is returned if the page fault is handled; otherwise,
667 * a standard error specifying why the fault is fatal is returned.
669 * The map in question must be referenced, and remains so.
670 * Caller may hold no locks.
673 vm_fault_trap(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
674 int fault_flags, int *signo, int *ucode)
678 MPASS(signo == NULL || ucode != NULL);
680 if (map != kernel_map && KTRPOINT(curthread, KTR_FAULT))
681 ktrfault(vaddr, fault_type);
683 result = vm_fault(map, trunc_page(vaddr), fault_type, fault_flags,
685 KASSERT(result == KERN_SUCCESS || result == KERN_FAILURE ||
686 result == KERN_INVALID_ADDRESS ||
687 result == KERN_RESOURCE_SHORTAGE ||
688 result == KERN_PROTECTION_FAILURE ||
689 result == KERN_OUT_OF_BOUNDS,
690 ("Unexpected Mach error %d from vm_fault()", result));
692 if (map != kernel_map && KTRPOINT(curthread, KTR_FAULTEND))
695 if (result != KERN_SUCCESS && signo != NULL) {
698 case KERN_INVALID_ADDRESS:
700 *ucode = SEGV_MAPERR;
702 case KERN_RESOURCE_SHORTAGE:
706 case KERN_OUT_OF_BOUNDS:
710 case KERN_PROTECTION_FAILURE:
711 if (prot_fault_translation == 0) {
713 * Autodetect. This check also covers
714 * the images without the ABI-tag ELF
717 if (SV_CURPROC_ABI() == SV_ABI_FREEBSD &&
718 curproc->p_osrel >= P_OSREL_SIGSEGV) {
720 *ucode = SEGV_ACCERR;
723 *ucode = UCODE_PAGEFLT;
725 } else if (prot_fault_translation == 1) {
726 /* Always compat mode. */
728 *ucode = UCODE_PAGEFLT;
730 /* Always SIGSEGV mode. */
732 *ucode = SEGV_ACCERR;
736 KASSERT(0, ("Unexpected Mach error %d from vm_fault()",
744 static enum fault_status
745 vm_fault_lock_vnode(struct faultstate *fs, bool objlocked)
750 if (fs->object->type != OBJT_VNODE)
751 return (FAULT_CONTINUE);
752 vp = fs->object->handle;
754 ASSERT_VOP_LOCKED(vp, "saved vnode is not locked");
755 return (FAULT_CONTINUE);
759 * Perform an unlock in case the desired vnode changed while
760 * the map was unlocked during a retry.
764 locked = VOP_ISLOCKED(vp);
765 if (locked != LK_EXCLUSIVE)
769 * We must not sleep acquiring the vnode lock while we have
770 * the page exclusive busied or the object's
771 * paging-in-progress count incremented. Otherwise, we could
774 error = vget(vp, locked | LK_CANRECURSE | LK_NOWAIT);
777 return (FAULT_CONTINUE);
782 unlock_and_deallocate(fs);
784 fault_deallocate(fs);
785 error = vget(vp, locked | LK_RETRY | LK_CANRECURSE);
788 KASSERT(error == 0, ("vm_fault: vget failed %d", error));
789 return (FAULT_RESTART);
793 * Calculate the desired readahead. Handle drop-behind.
795 * Returns the number of readahead blocks to pass to the pager.
798 vm_fault_readahead(struct faultstate *fs)
803 KASSERT(fs->lookup_still_valid, ("map unlocked"));
804 era = fs->entry->read_ahead;
805 behavior = vm_map_entry_behavior(fs->entry);
806 if (behavior == MAP_ENTRY_BEHAV_RANDOM) {
808 } else if (behavior == MAP_ENTRY_BEHAV_SEQUENTIAL) {
809 nera = VM_FAULT_READ_AHEAD_MAX;
810 if (fs->vaddr == fs->entry->next_read)
811 vm_fault_dontneed(fs, fs->vaddr, nera);
812 } else if (fs->vaddr == fs->entry->next_read) {
814 * This is a sequential fault. Arithmetically
815 * increase the requested number of pages in
816 * the read-ahead window. The requested
817 * number of pages is "# of sequential faults
818 * x (read ahead min + 1) + read ahead min"
820 nera = VM_FAULT_READ_AHEAD_MIN;
823 if (nera > VM_FAULT_READ_AHEAD_MAX)
824 nera = VM_FAULT_READ_AHEAD_MAX;
826 if (era == VM_FAULT_READ_AHEAD_MAX)
827 vm_fault_dontneed(fs, fs->vaddr, nera);
830 * This is a non-sequential fault.
836 * A read lock on the map suffices to update
837 * the read ahead count safely.
839 fs->entry->read_ahead = nera;
846 vm_fault_lookup(struct faultstate *fs)
850 KASSERT(!fs->lookup_still_valid,
851 ("vm_fault_lookup: Map already locked."));
852 result = vm_map_lookup(&fs->map, fs->vaddr, fs->fault_type |
853 VM_PROT_FAULT_LOOKUP, &fs->entry, &fs->first_object,
854 &fs->first_pindex, &fs->prot, &fs->wired);
855 if (result != KERN_SUCCESS) {
860 fs->map_generation = fs->map->timestamp;
862 if (fs->entry->eflags & MAP_ENTRY_NOFAULT) {
863 panic("%s: fault on nofault entry, addr: %#lx",
864 __func__, (u_long)fs->vaddr);
867 if (fs->entry->eflags & MAP_ENTRY_IN_TRANSITION &&
868 fs->entry->wiring_thread != curthread) {
869 vm_map_unlock_read(fs->map);
870 vm_map_lock(fs->map);
871 if (vm_map_lookup_entry(fs->map, fs->vaddr, &fs->entry) &&
872 (fs->entry->eflags & MAP_ENTRY_IN_TRANSITION)) {
874 fs->entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
875 vm_map_unlock_and_wait(fs->map, 0);
877 vm_map_unlock(fs->map);
878 return (KERN_RESOURCE_SHORTAGE);
881 MPASS((fs->entry->eflags & MAP_ENTRY_GUARD) == 0);
884 fs->fault_type = fs->prot | (fs->fault_type & VM_PROT_COPY);
886 KASSERT((fs->fault_flags & VM_FAULT_WIRE) == 0,
887 ("!fs->wired && VM_FAULT_WIRE"));
888 fs->lookup_still_valid = true;
890 return (KERN_SUCCESS);
894 vm_fault_relookup(struct faultstate *fs)
896 vm_object_t retry_object;
897 vm_pindex_t retry_pindex;
898 vm_prot_t retry_prot;
901 if (!vm_map_trylock_read(fs->map))
902 return (KERN_RESTART);
904 fs->lookup_still_valid = true;
905 if (fs->map->timestamp == fs->map_generation)
906 return (KERN_SUCCESS);
908 result = vm_map_lookup_locked(&fs->map, fs->vaddr, fs->fault_type,
909 &fs->entry, &retry_object, &retry_pindex, &retry_prot,
911 if (result != KERN_SUCCESS) {
913 * If retry of map lookup would have blocked then
914 * retry fault from start.
916 if (result == KERN_FAILURE)
917 return (KERN_RESTART);
920 if (retry_object != fs->first_object ||
921 retry_pindex != fs->first_pindex)
922 return (KERN_RESTART);
925 * Check whether the protection has changed or the object has
926 * been copied while we left the map unlocked. Changing from
927 * read to write permission is OK - we leave the page
928 * write-protected, and catch the write fault. Changing from
929 * write to read permission means that we can't mark the page
930 * write-enabled after all.
932 fs->prot &= retry_prot;
933 fs->fault_type &= retry_prot;
935 return (KERN_RESTART);
937 /* Reassert because wired may have changed. */
938 KASSERT(fs->wired || (fs->fault_flags & VM_FAULT_WIRE) == 0,
939 ("!wired && VM_FAULT_WIRE"));
941 return (KERN_SUCCESS);
945 vm_fault_cow(struct faultstate *fs)
947 bool is_first_object_locked;
949 KASSERT(fs->object != fs->first_object,
950 ("source and target COW objects are identical"));
953 * This allows pages to be virtually copied from a backing_object
954 * into the first_object, where the backing object has no other
955 * refs to it, and cannot gain any more refs. Instead of a bcopy,
956 * we just move the page from the backing object to the first
957 * object. Note that we must mark the page dirty in the first
958 * object so that it will go out to swap when needed.
960 is_first_object_locked = false;
963 * Only one shadow object and no other refs.
965 fs->object->shadow_count == 1 && fs->object->ref_count == 1 &&
967 * No other ways to look the object up
969 fs->object->handle == NULL && (fs->object->flags & OBJ_ANON) != 0 &&
971 * We don't chase down the shadow chain and we can acquire locks.
973 (is_first_object_locked = VM_OBJECT_TRYWLOCK(fs->first_object)) &&
974 fs->object == fs->first_object->backing_object &&
975 VM_OBJECT_TRYWLOCK(fs->object)) {
977 * Remove but keep xbusy for replace. fs->m is moved into
978 * fs->first_object and left busy while fs->first_m is
979 * conditionally freed.
981 vm_page_remove_xbusy(fs->m);
982 vm_page_replace(fs->m, fs->first_object, fs->first_pindex,
984 vm_page_dirty(fs->m);
985 #if VM_NRESERVLEVEL > 0
987 * Rename the reservation.
989 vm_reserv_rename(fs->m, fs->first_object, fs->object,
990 OFF_TO_IDX(fs->first_object->backing_object_offset));
992 VM_OBJECT_WUNLOCK(fs->object);
993 VM_OBJECT_WUNLOCK(fs->first_object);
996 VM_CNT_INC(v_cow_optim);
998 if (is_first_object_locked)
999 VM_OBJECT_WUNLOCK(fs->first_object);
1001 * Oh, well, lets copy it.
1003 pmap_copy_page(fs->m, fs->first_m);
1004 vm_page_valid(fs->first_m);
1005 if (fs->wired && (fs->fault_flags & VM_FAULT_WIRE) == 0) {
1006 vm_page_wire(fs->first_m);
1007 vm_page_unwire(fs->m, PQ_INACTIVE);
1010 * Save the cow page to be released after
1011 * pmap_enter is complete.
1017 * Typically, the shadow object is either private to this
1018 * address space (OBJ_ONEMAPPING) or its pages are read only.
1019 * In the highly unusual case where the pages of a shadow object
1020 * are read/write shared between this and other address spaces,
1021 * we need to ensure that any pmap-level mappings to the
1022 * original, copy-on-write page from the backing object are
1023 * removed from those other address spaces.
1025 * The flag check is racy, but this is tolerable: if
1026 * OBJ_ONEMAPPING is cleared after the check, the busy state
1027 * ensures that new mappings of m_cow can't be created.
1028 * pmap_enter() will replace an existing mapping in the current
1029 * address space. If OBJ_ONEMAPPING is set after the check,
1030 * removing mappings will at worse trigger some unnecessary page
1033 vm_page_assert_xbusied(fs->m_cow);
1034 if ((fs->first_object->flags & OBJ_ONEMAPPING) == 0)
1035 pmap_remove_all(fs->m_cow);
1038 vm_object_pip_wakeup(fs->object);
1041 * Only use the new page below...
1043 fs->object = fs->first_object;
1044 fs->pindex = fs->first_pindex;
1045 fs->m = fs->first_m;
1046 VM_CNT_INC(v_cow_faults);
1047 curthread->td_cow++;
1051 vm_fault_next(struct faultstate *fs)
1053 vm_object_t next_object;
1056 * The requested page does not exist at this object/
1057 * offset. Remove the invalid page from the object,
1058 * waking up anyone waiting for it, and continue on to
1059 * the next object. However, if this is the top-level
1060 * object, we must leave the busy page in place to
1061 * prevent another process from rushing past us, and
1062 * inserting the page in that object at the same time
1065 if (fs->object == fs->first_object) {
1066 fs->first_m = fs->m;
1069 fault_page_free(&fs->m);
1072 * Move on to the next object. Lock the next object before
1073 * unlocking the current one.
1075 VM_OBJECT_ASSERT_WLOCKED(fs->object);
1076 next_object = fs->object->backing_object;
1077 if (next_object == NULL)
1079 MPASS(fs->first_m != NULL);
1080 KASSERT(fs->object != next_object, ("object loop %p", next_object));
1081 VM_OBJECT_WLOCK(next_object);
1082 vm_object_pip_add(next_object, 1);
1083 if (fs->object != fs->first_object)
1084 vm_object_pip_wakeup(fs->object);
1085 fs->pindex += OFF_TO_IDX(fs->object->backing_object_offset);
1086 VM_OBJECT_WUNLOCK(fs->object);
1087 fs->object = next_object;
1093 vm_fault_zerofill(struct faultstate *fs)
1097 * If there's no object left, fill the page in the top
1098 * object with zeros.
1100 if (fs->object != fs->first_object) {
1101 vm_object_pip_wakeup(fs->object);
1102 fs->object = fs->first_object;
1103 fs->pindex = fs->first_pindex;
1105 MPASS(fs->first_m != NULL);
1106 MPASS(fs->m == NULL);
1107 fs->m = fs->first_m;
1111 * Zero the page if necessary and mark it valid.
1113 if ((fs->m->flags & PG_ZERO) == 0) {
1114 pmap_zero_page(fs->m);
1116 VM_CNT_INC(v_ozfod);
1119 vm_page_valid(fs->m);
1123 * Initiate page fault after timeout. Returns true if caller should
1124 * do vm_waitpfault() after the call.
1127 vm_fault_allocate_oom(struct faultstate *fs)
1131 unlock_and_deallocate(fs);
1132 if (vm_pfault_oom_attempts < 0)
1134 if (!fs->oom_started) {
1135 fs->oom_started = true;
1136 getmicrotime(&fs->oom_start_time);
1141 timevalsub(&now, &fs->oom_start_time);
1142 if (now.tv_sec < vm_pfault_oom_attempts * vm_pfault_oom_wait)
1147 "proc %d (%s) failed to alloc page on fault, starting OOM\n",
1148 curproc->p_pid, curproc->p_comm);
1149 vm_pageout_oom(VM_OOM_MEM_PF);
1150 fs->oom_started = false;
1155 * Allocate a page directly or via the object populate method.
1157 static enum fault_status
1158 vm_fault_allocate(struct faultstate *fs)
1160 struct domainset *dset;
1161 enum fault_status res;
1163 if ((fs->object->flags & OBJ_SIZEVNLOCK) != 0) {
1164 res = vm_fault_lock_vnode(fs, true);
1165 MPASS(res == FAULT_CONTINUE || res == FAULT_RESTART);
1166 if (res == FAULT_RESTART)
1170 if (fs->pindex >= fs->object->size) {
1171 unlock_and_deallocate(fs);
1172 return (FAULT_OUT_OF_BOUNDS);
1175 if (fs->object == fs->first_object &&
1176 (fs->first_object->flags & OBJ_POPULATE) != 0 &&
1177 fs->first_object->shadow_count == 0) {
1178 res = vm_fault_populate(fs);
1183 unlock_and_deallocate(fs);
1185 case FAULT_CONTINUE:
1187 * Pager's populate() method
1188 * returned VM_PAGER_BAD.
1192 panic("inconsistent return codes");
1197 * Allocate a new page for this object/offset pair.
1199 * If the process has a fatal signal pending, prioritize the allocation
1200 * with the expectation that the process will exit shortly and free some
1201 * pages. In particular, the signal may have been posted by the page
1202 * daemon in an attempt to resolve an out-of-memory condition.
1204 * The unlocked read of the p_flag is harmless. At worst, the P_KILLED
1205 * might be not observed here, and allocation fails, causing a restart
1206 * and new reading of the p_flag.
1208 dset = fs->object->domain.dr_policy;
1210 dset = curthread->td_domain.dr_policy;
1211 if (!vm_page_count_severe_set(&dset->ds_mask) || P_KILLED(curproc)) {
1212 #if VM_NRESERVLEVEL > 0
1213 vm_object_color(fs->object, atop(fs->vaddr) - fs->pindex);
1215 fs->m = vm_page_alloc(fs->object, fs->pindex,
1216 P_KILLED(curproc) ? VM_ALLOC_SYSTEM : 0);
1218 if (fs->m == NULL) {
1219 if (vm_fault_allocate_oom(fs))
1220 vm_waitpfault(dset, vm_pfault_oom_wait * hz);
1221 return (FAULT_RESTART);
1223 fs->oom_started = false;
1225 return (FAULT_CONTINUE);
1229 * Call the pager to retrieve the page if there is a chance
1230 * that the pager has it, and potentially retrieve additional
1231 * pages at the same time.
1233 static enum fault_status
1234 vm_fault_getpages(struct faultstate *fs, int *behindp, int *aheadp)
1236 vm_offset_t e_end, e_start;
1237 int ahead, behind, cluster_offset, rv;
1238 enum fault_status status;
1242 * Prepare for unlocking the map. Save the map
1243 * entry's start and end addresses, which are used to
1244 * optimize the size of the pager operation below.
1245 * Even if the map entry's addresses change after
1246 * unlocking the map, using the saved addresses is
1249 e_start = fs->entry->start;
1250 e_end = fs->entry->end;
1251 behavior = vm_map_entry_behavior(fs->entry);
1254 * If the pager for the current object might have
1255 * the page, then determine the number of additional
1256 * pages to read and potentially reprioritize
1257 * previously read pages for earlier reclamation.
1258 * These operations should only be performed once per
1259 * page fault. Even if the current pager doesn't
1260 * have the page, the number of additional pages to
1261 * read will apply to subsequent objects in the
1264 if (fs->nera == -1 && !P_KILLED(curproc))
1265 fs->nera = vm_fault_readahead(fs);
1268 * Release the map lock before locking the vnode or
1269 * sleeping in the pager. (If the current object has
1270 * a shadow, then an earlier iteration of this loop
1271 * may have already unlocked the map.)
1275 status = vm_fault_lock_vnode(fs, false);
1276 MPASS(status == FAULT_CONTINUE || status == FAULT_RESTART);
1277 if (status == FAULT_RESTART)
1279 KASSERT(fs->vp == NULL || !fs->map->system_map,
1280 ("vm_fault: vnode-backed object mapped by system map"));
1283 * Page in the requested page and hint the pager,
1284 * that it may bring up surrounding pages.
1286 if (fs->nera == -1 || behavior == MAP_ENTRY_BEHAV_RANDOM ||
1287 P_KILLED(curproc)) {
1291 /* Is this a sequential fault? */
1297 * Request a cluster of pages that is
1298 * aligned to a VM_FAULT_READ_DEFAULT
1299 * page offset boundary within the
1300 * object. Alignment to a page offset
1301 * boundary is more likely to coincide
1302 * with the underlying file system
1303 * block than alignment to a virtual
1306 cluster_offset = fs->pindex % VM_FAULT_READ_DEFAULT;
1307 behind = ulmin(cluster_offset,
1308 atop(fs->vaddr - e_start));
1309 ahead = VM_FAULT_READ_DEFAULT - 1 - cluster_offset;
1311 ahead = ulmin(ahead, atop(e_end - fs->vaddr) - 1);
1315 rv = vm_pager_get_pages(fs->object, &fs->m, 1, behindp, aheadp);
1316 if (rv == VM_PAGER_OK)
1317 return (FAULT_HARD);
1318 if (rv == VM_PAGER_ERROR)
1319 printf("vm_fault: pager read error, pid %d (%s)\n",
1320 curproc->p_pid, curproc->p_comm);
1322 * If an I/O error occurred or the requested page was
1323 * outside the range of the pager, clean up and return
1326 if (rv == VM_PAGER_ERROR || rv == VM_PAGER_BAD) {
1327 VM_OBJECT_WLOCK(fs->object);
1328 fault_page_free(&fs->m);
1329 unlock_and_deallocate(fs);
1330 return (FAULT_OUT_OF_BOUNDS);
1332 KASSERT(rv == VM_PAGER_FAIL,
1333 ("%s: unexpected pager error %d", __func__, rv));
1334 return (FAULT_CONTINUE);
1338 * Wait/Retry if the page is busy. We have to do this if the page is
1339 * either exclusive or shared busy because the vm_pager may be using
1340 * read busy for pageouts (and even pageins if it is the vnode pager),
1341 * and we could end up trying to pagein and pageout the same page
1344 * We can theoretically allow the busy case on a read fault if the page
1345 * is marked valid, but since such pages are typically already pmap'd,
1346 * putting that special case in might be more effort then it is worth.
1347 * We cannot under any circumstances mess around with a shared busied
1348 * page except, perhaps, to pmap it.
1351 vm_fault_busy_sleep(struct faultstate *fs)
1354 * Reference the page before unlocking and
1355 * sleeping so that the page daemon is less
1356 * likely to reclaim it.
1358 vm_page_aflag_set(fs->m, PGA_REFERENCED);
1359 if (fs->object != fs->first_object) {
1360 fault_page_release(&fs->first_m);
1361 vm_object_pip_wakeup(fs->first_object);
1363 vm_object_pip_wakeup(fs->object);
1365 if (fs->m != vm_page_lookup(fs->object, fs->pindex) ||
1366 !vm_page_busy_sleep(fs->m, "vmpfw", 0))
1367 VM_OBJECT_WUNLOCK(fs->object);
1368 VM_CNT_INC(v_intrans);
1369 vm_object_deallocate(fs->first_object);
1373 * Handle page lookup, populate, allocate, page-in for the current
1376 * The object is locked on entry and will remain locked with a return
1377 * code of FAULT_CONTINUE so that fault may follow the shadow chain.
1378 * Otherwise, the object will be unlocked upon return.
1380 static enum fault_status
1381 vm_fault_object(struct faultstate *fs, int *behindp, int *aheadp)
1383 enum fault_status res;
1387 * If the object is marked for imminent termination, we retry
1388 * here, since the collapse pass has raced with us. Otherwise,
1389 * if we see terminally dead object, return fail.
1391 if ((fs->object->flags & OBJ_DEAD) != 0) {
1392 dead = fs->object->type == OBJT_DEAD;
1393 unlock_and_deallocate(fs);
1395 return (FAULT_PROTECTION_FAILURE);
1397 return (FAULT_RESTART);
1401 * See if the page is resident.
1403 fs->m = vm_page_lookup(fs->object, fs->pindex);
1404 if (fs->m != NULL) {
1405 if (!vm_page_tryxbusy(fs->m)) {
1406 vm_fault_busy_sleep(fs);
1407 return (FAULT_RESTART);
1411 * The page is marked busy for other processes and the
1412 * pagedaemon. If it is still completely valid we are
1415 if (vm_page_all_valid(fs->m)) {
1416 VM_OBJECT_WUNLOCK(fs->object);
1417 return (FAULT_SOFT);
1420 VM_OBJECT_ASSERT_WLOCKED(fs->object);
1423 * Page is not resident. If the pager might contain the page
1424 * or this is the beginning of the search, allocate a new
1427 if (fs->m == NULL && (fault_object_needs_getpages(fs->object) ||
1428 fs->object == fs->first_object)) {
1429 res = vm_fault_allocate(fs);
1430 if (res != FAULT_CONTINUE)
1435 * Default objects have no pager so no exclusive busy exists
1436 * to protect this page in the chain. Skip to the next
1437 * object without dropping the lock to preserve atomicity of
1440 if (fault_object_needs_getpages(fs->object)) {
1442 * At this point, we have either allocated a new page
1443 * or found an existing page that is only partially
1446 * We hold a reference on the current object and the
1447 * page is exclusive busied. The exclusive busy
1448 * prevents simultaneous faults and collapses while
1449 * the object lock is dropped.
1451 VM_OBJECT_WUNLOCK(fs->object);
1452 res = vm_fault_getpages(fs, behindp, aheadp);
1453 if (res == FAULT_CONTINUE)
1454 VM_OBJECT_WLOCK(fs->object);
1456 res = FAULT_CONTINUE;
1462 vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
1463 int fault_flags, vm_page_t *m_hold)
1465 struct faultstate fs;
1466 int ahead, behind, faultcount, rv;
1467 enum fault_status res;
1470 VM_CNT_INC(v_vm_faults);
1472 if ((curthread->td_pflags & TDP_NOFAULTING) != 0)
1473 return (KERN_PROTECTION_FAILURE);
1478 fs.fault_flags = fault_flags;
1480 fs.lookup_still_valid = false;
1481 fs.oom_started = false;
1487 fs.fault_type = fault_type;
1490 * Find the backing store object and offset into it to begin the
1493 rv = vm_fault_lookup(&fs);
1494 if (rv != KERN_SUCCESS) {
1495 if (rv == KERN_RESOURCE_SHORTAGE)
1501 * Try to avoid lock contention on the top-level object through
1502 * special-case handling of some types of page faults, specifically,
1503 * those that are mapping an existing page from the top-level object.
1504 * Under this condition, a read lock on the object suffices, allowing
1505 * multiple page faults of a similar type to run in parallel.
1507 if (fs.vp == NULL /* avoid locked vnode leak */ &&
1508 (fs.entry->eflags & MAP_ENTRY_SPLIT_BOUNDARY_MASK) == 0 &&
1509 (fs.fault_flags & (VM_FAULT_WIRE | VM_FAULT_DIRTY)) == 0) {
1510 VM_OBJECT_RLOCK(fs.first_object);
1511 res = vm_fault_soft_fast(&fs);
1512 if (res == FAULT_SUCCESS)
1513 return (KERN_SUCCESS);
1514 if (!VM_OBJECT_TRYUPGRADE(fs.first_object)) {
1515 VM_OBJECT_RUNLOCK(fs.first_object);
1516 VM_OBJECT_WLOCK(fs.first_object);
1519 VM_OBJECT_WLOCK(fs.first_object);
1523 * Make a reference to this object to prevent its disposal while we
1524 * are messing with it. Once we have the reference, the map is free
1525 * to be diddled. Since objects reference their shadows (and copies),
1526 * they will stay around as well.
1528 * Bump the paging-in-progress count to prevent size changes (e.g.
1529 * truncation operations) during I/O.
1531 vm_object_reference_locked(fs.first_object);
1532 vm_object_pip_add(fs.first_object, 1);
1534 fs.m_cow = fs.m = fs.first_m = NULL;
1537 * Search for the page at object/offset.
1539 fs.object = fs.first_object;
1540 fs.pindex = fs.first_pindex;
1542 if ((fs.entry->eflags & MAP_ENTRY_SPLIT_BOUNDARY_MASK) != 0) {
1543 res = vm_fault_allocate(&fs);
1548 return (KERN_SUCCESS);
1550 return (KERN_FAILURE);
1551 case FAULT_OUT_OF_BOUNDS:
1552 return (KERN_OUT_OF_BOUNDS);
1553 case FAULT_CONTINUE:
1556 panic("vm_fault: Unhandled status %d", res);
1561 KASSERT(fs.m == NULL,
1562 ("page still set %p at loop start", fs.m));
1564 res = vm_fault_object(&fs, &behind, &ahead);
1569 faultcount = behind + 1 + ahead;
1575 return (KERN_SUCCESS);
1577 return (KERN_FAILURE);
1578 case FAULT_OUT_OF_BOUNDS:
1579 return (KERN_OUT_OF_BOUNDS);
1580 case FAULT_PROTECTION_FAILURE:
1581 return (KERN_PROTECTION_FAILURE);
1582 case FAULT_CONTINUE:
1585 panic("vm_fault: Unhandled status %d", res);
1589 * The page was not found in the current object. Try to
1590 * traverse into a backing object or zero fill if none is
1593 if (vm_fault_next(&fs))
1595 if ((fs.fault_flags & VM_FAULT_NOFILL) != 0) {
1596 if (fs.first_object == fs.object)
1597 fault_page_free(&fs.first_m);
1598 unlock_and_deallocate(&fs);
1599 return (KERN_OUT_OF_BOUNDS);
1601 VM_OBJECT_WUNLOCK(fs.object);
1602 vm_fault_zerofill(&fs);
1603 /* Don't try to prefault neighboring pages. */
1610 * A valid page has been found and exclusively busied. The
1611 * object lock must no longer be held.
1613 vm_page_assert_xbusied(fs.m);
1614 VM_OBJECT_ASSERT_UNLOCKED(fs.object);
1617 * If the page is being written, but isn't already owned by the
1618 * top-level object, we have to copy it into a new page owned by the
1621 if (fs.object != fs.first_object) {
1623 * We only really need to copy if we want to write it.
1625 if ((fs.fault_type & (VM_PROT_COPY | VM_PROT_WRITE)) != 0) {
1628 * We only try to prefault read-only mappings to the
1629 * neighboring pages when this copy-on-write fault is
1630 * a hard fault. In other cases, trying to prefault
1631 * is typically wasted effort.
1633 if (faultcount == 0)
1637 fs.prot &= ~VM_PROT_WRITE;
1642 * We must verify that the maps have not changed since our last
1645 if (!fs.lookup_still_valid) {
1646 rv = vm_fault_relookup(&fs);
1647 if (rv != KERN_SUCCESS) {
1648 fault_deallocate(&fs);
1649 if (rv == KERN_RESTART)
1654 VM_OBJECT_ASSERT_UNLOCKED(fs.object);
1657 * If the page was filled by a pager, save the virtual address that
1658 * should be faulted on next under a sequential access pattern to the
1659 * map entry. A read lock on the map suffices to update this address
1663 fs.entry->next_read = vaddr + ptoa(ahead) + PAGE_SIZE;
1666 * Page must be completely valid or it is not fit to
1667 * map into user space. vm_pager_get_pages() ensures this.
1669 vm_page_assert_xbusied(fs.m);
1670 KASSERT(vm_page_all_valid(fs.m),
1671 ("vm_fault: page %p partially invalid", fs.m));
1673 vm_fault_dirty(&fs, fs.m);
1676 * Put this page into the physical map. We had to do the unlock above
1677 * because pmap_enter() may sleep. We don't put the page
1678 * back on the active queue until later so that the pageout daemon
1679 * won't find it (yet).
1681 pmap_enter(fs.map->pmap, vaddr, fs.m, fs.prot,
1682 fs.fault_type | (fs.wired ? PMAP_ENTER_WIRED : 0), 0);
1683 if (faultcount != 1 && (fs.fault_flags & VM_FAULT_WIRE) == 0 &&
1685 vm_fault_prefault(&fs, vaddr,
1686 faultcount > 0 ? behind : PFBAK,
1687 faultcount > 0 ? ahead : PFFOR, false);
1690 * If the page is not wired down, then put it where the pageout daemon
1693 if ((fs.fault_flags & VM_FAULT_WIRE) != 0)
1696 vm_page_activate(fs.m);
1697 if (fs.m_hold != NULL) {
1698 (*fs.m_hold) = fs.m;
1701 vm_page_xunbusy(fs.m);
1705 * Unlock everything, and return
1707 fault_deallocate(&fs);
1709 VM_CNT_INC(v_io_faults);
1710 curthread->td_ru.ru_majflt++;
1712 if (racct_enable && fs.object->type == OBJT_VNODE) {
1714 if ((fs.fault_type & (VM_PROT_COPY | VM_PROT_WRITE)) != 0) {
1715 racct_add_force(curproc, RACCT_WRITEBPS,
1716 PAGE_SIZE + behind * PAGE_SIZE);
1717 racct_add_force(curproc, RACCT_WRITEIOPS, 1);
1719 racct_add_force(curproc, RACCT_READBPS,
1720 PAGE_SIZE + ahead * PAGE_SIZE);
1721 racct_add_force(curproc, RACCT_READIOPS, 1);
1723 PROC_UNLOCK(curproc);
1727 curthread->td_ru.ru_minflt++;
1729 return (KERN_SUCCESS);
1733 * Speed up the reclamation of pages that precede the faulting pindex within
1734 * the first object of the shadow chain. Essentially, perform the equivalent
1735 * to madvise(..., MADV_DONTNEED) on a large cluster of pages that precedes
1736 * the faulting pindex by the cluster size when the pages read by vm_fault()
1737 * cross a cluster-size boundary. The cluster size is the greater of the
1738 * smallest superpage size and VM_FAULT_DONTNEED_MIN.
1740 * When "fs->first_object" is a shadow object, the pages in the backing object
1741 * that precede the faulting pindex are deactivated by vm_fault(). So, this
1742 * function must only be concerned with pages in the first object.
1745 vm_fault_dontneed(const struct faultstate *fs, vm_offset_t vaddr, int ahead)
1747 vm_map_entry_t entry;
1748 vm_object_t first_object;
1749 vm_offset_t end, start;
1750 vm_page_t m, m_next;
1751 vm_pindex_t pend, pstart;
1754 VM_OBJECT_ASSERT_UNLOCKED(fs->object);
1755 first_object = fs->first_object;
1756 /* Neither fictitious nor unmanaged pages can be reclaimed. */
1757 if ((first_object->flags & (OBJ_FICTITIOUS | OBJ_UNMANAGED)) == 0) {
1758 VM_OBJECT_RLOCK(first_object);
1759 size = VM_FAULT_DONTNEED_MIN;
1760 if (MAXPAGESIZES > 1 && size < pagesizes[1])
1761 size = pagesizes[1];
1762 end = rounddown2(vaddr, size);
1763 if (vaddr - end >= size - PAGE_SIZE - ptoa(ahead) &&
1764 (entry = fs->entry)->start < end) {
1765 if (end - entry->start < size)
1766 start = entry->start;
1769 pmap_advise(fs->map->pmap, start, end, MADV_DONTNEED);
1770 pstart = OFF_TO_IDX(entry->offset) + atop(start -
1772 m_next = vm_page_find_least(first_object, pstart);
1773 pend = OFF_TO_IDX(entry->offset) + atop(end -
1775 while ((m = m_next) != NULL && m->pindex < pend) {
1776 m_next = TAILQ_NEXT(m, listq);
1777 if (!vm_page_all_valid(m) ||
1782 * Don't clear PGA_REFERENCED, since it would
1783 * likely represent a reference by a different
1786 * Typically, at this point, prefetched pages
1787 * are still in the inactive queue. Only
1788 * pages that triggered page faults are in the
1789 * active queue. The test for whether the page
1790 * is in the inactive queue is racy; in the
1791 * worst case we will requeue the page
1794 if (!vm_page_inactive(m))
1795 vm_page_deactivate(m);
1798 VM_OBJECT_RUNLOCK(first_object);
1803 * vm_fault_prefault provides a quick way of clustering
1804 * pagefaults into a processes address space. It is a "cousin"
1805 * of vm_map_pmap_enter, except it runs at page fault time instead
1809 vm_fault_prefault(const struct faultstate *fs, vm_offset_t addra,
1810 int backward, int forward, bool obj_locked)
1813 vm_map_entry_t entry;
1814 vm_object_t backing_object, lobject;
1815 vm_offset_t addr, starta;
1820 pmap = fs->map->pmap;
1821 if (pmap != vmspace_pmap(curthread->td_proc->p_vmspace))
1826 if (addra < backward * PAGE_SIZE) {
1827 starta = entry->start;
1829 starta = addra - backward * PAGE_SIZE;
1830 if (starta < entry->start)
1831 starta = entry->start;
1835 * Generate the sequence of virtual addresses that are candidates for
1836 * prefaulting in an outward spiral from the faulting virtual address,
1837 * "addra". Specifically, the sequence is "addra - PAGE_SIZE", "addra
1838 * + PAGE_SIZE", "addra - 2 * PAGE_SIZE", "addra + 2 * PAGE_SIZE", ...
1839 * If the candidate address doesn't have a backing physical page, then
1840 * the loop immediately terminates.
1842 for (i = 0; i < 2 * imax(backward, forward); i++) {
1843 addr = addra + ((i >> 1) + 1) * ((i & 1) == 0 ? -PAGE_SIZE :
1845 if (addr > addra + forward * PAGE_SIZE)
1848 if (addr < starta || addr >= entry->end)
1851 if (!pmap_is_prefaultable(pmap, addr))
1854 pindex = ((addr - entry->start) + entry->offset) >> PAGE_SHIFT;
1855 lobject = entry->object.vm_object;
1857 VM_OBJECT_RLOCK(lobject);
1858 while ((m = vm_page_lookup(lobject, pindex)) == NULL &&
1859 !fault_object_needs_getpages(lobject) &&
1860 (backing_object = lobject->backing_object) != NULL) {
1861 KASSERT((lobject->backing_object_offset & PAGE_MASK) ==
1862 0, ("vm_fault_prefault: unaligned object offset"));
1863 pindex += lobject->backing_object_offset >> PAGE_SHIFT;
1864 VM_OBJECT_RLOCK(backing_object);
1865 if (!obj_locked || lobject != entry->object.vm_object)
1866 VM_OBJECT_RUNLOCK(lobject);
1867 lobject = backing_object;
1870 if (!obj_locked || lobject != entry->object.vm_object)
1871 VM_OBJECT_RUNLOCK(lobject);
1874 if (vm_page_all_valid(m) &&
1875 (m->flags & PG_FICTITIOUS) == 0)
1876 pmap_enter_quick(pmap, addr, m, entry->protection);
1877 if (!obj_locked || lobject != entry->object.vm_object)
1878 VM_OBJECT_RUNLOCK(lobject);
1883 * Hold each of the physical pages that are mapped by the specified range of
1884 * virtual addresses, ["addr", "addr" + "len"), if those mappings are valid
1885 * and allow the specified types of access, "prot". If all of the implied
1886 * pages are successfully held, then the number of held pages is returned
1887 * together with pointers to those pages in the array "ma". However, if any
1888 * of the pages cannot be held, -1 is returned.
1891 vm_fault_quick_hold_pages(vm_map_t map, vm_offset_t addr, vm_size_t len,
1892 vm_prot_t prot, vm_page_t *ma, int max_count)
1894 vm_offset_t end, va;
1897 boolean_t pmap_failed;
1901 end = round_page(addr + len);
1902 addr = trunc_page(addr);
1904 if (!vm_map_range_valid(map, addr, end))
1907 if (atop(end - addr) > max_count)
1908 panic("vm_fault_quick_hold_pages: count > max_count");
1909 count = atop(end - addr);
1912 * Most likely, the physical pages are resident in the pmap, so it is
1913 * faster to try pmap_extract_and_hold() first.
1915 pmap_failed = FALSE;
1916 for (mp = ma, va = addr; va < end; mp++, va += PAGE_SIZE) {
1917 *mp = pmap_extract_and_hold(map->pmap, va, prot);
1920 else if ((prot & VM_PROT_WRITE) != 0 &&
1921 (*mp)->dirty != VM_PAGE_BITS_ALL) {
1923 * Explicitly dirty the physical page. Otherwise, the
1924 * caller's changes may go unnoticed because they are
1925 * performed through an unmanaged mapping or by a DMA
1928 * The object lock is not held here.
1929 * See vm_page_clear_dirty_mask().
1936 * One or more pages could not be held by the pmap. Either no
1937 * page was mapped at the specified virtual address or that
1938 * mapping had insufficient permissions. Attempt to fault in
1939 * and hold these pages.
1941 * If vm_fault_disable_pagefaults() was called,
1942 * i.e., TDP_NOFAULTING is set, we must not sleep nor
1943 * acquire MD VM locks, which means we must not call
1944 * vm_fault(). Some (out of tree) callers mark
1945 * too wide a code area with vm_fault_disable_pagefaults()
1946 * already, use the VM_PROT_QUICK_NOFAULT flag to request
1947 * the proper behaviour explicitly.
1949 if ((prot & VM_PROT_QUICK_NOFAULT) != 0 &&
1950 (curthread->td_pflags & TDP_NOFAULTING) != 0)
1952 for (mp = ma, va = addr; va < end; mp++, va += PAGE_SIZE)
1953 if (*mp == NULL && vm_fault(map, va, prot,
1954 VM_FAULT_NORMAL, mp) != KERN_SUCCESS)
1959 for (mp = ma; mp < ma + count; mp++)
1961 vm_page_unwire(*mp, PQ_INACTIVE);
1967 * vm_fault_copy_entry
1969 * Create new object backing dst_entry with private copy of all
1970 * underlying pages. When src_entry is equal to dst_entry, function
1971 * implements COW for wired-down map entry. Otherwise, it forks
1972 * wired entry into dst_map.
1974 * In/out conditions:
1975 * The source and destination maps must be locked for write.
1976 * The source map entry must be wired down (or be a sharing map
1977 * entry corresponding to a main map entry that is wired down).
1980 vm_fault_copy_entry(vm_map_t dst_map, vm_map_t src_map __unused,
1981 vm_map_entry_t dst_entry, vm_map_entry_t src_entry,
1982 vm_ooffset_t *fork_charge)
1984 vm_object_t backing_object, dst_object, object, src_object;
1985 vm_pindex_t dst_pindex, pindex, src_pindex;
1986 vm_prot_t access, prot;
1992 upgrade = src_entry == dst_entry;
1993 KASSERT(upgrade || dst_entry->object.vm_object == NULL,
1994 ("vm_fault_copy_entry: vm_object not NULL"));
1997 * If not an upgrade, then enter the mappings in the pmap as
1998 * read and/or execute accesses. Otherwise, enter them as
2001 * A writeable large page mapping is only created if all of
2002 * the constituent small page mappings are modified. Marking
2003 * PTEs as modified on inception allows promotion to happen
2004 * without taking potentially large number of soft faults.
2006 access = prot = dst_entry->protection;
2008 access &= ~VM_PROT_WRITE;
2010 src_object = src_entry->object.vm_object;
2011 src_pindex = OFF_TO_IDX(src_entry->offset);
2013 if (upgrade && (dst_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) {
2014 dst_object = src_object;
2015 vm_object_reference(dst_object);
2018 * Create the top-level object for the destination entry.
2019 * Doesn't actually shadow anything - we copy the pages
2022 dst_object = vm_object_allocate_anon(atop(dst_entry->end -
2023 dst_entry->start), NULL, NULL, 0);
2024 #if VM_NRESERVLEVEL > 0
2025 dst_object->flags |= OBJ_COLORED;
2026 dst_object->pg_color = atop(dst_entry->start);
2028 dst_object->domain = src_object->domain;
2029 dst_object->charge = dst_entry->end - dst_entry->start;
2031 dst_entry->object.vm_object = dst_object;
2032 dst_entry->offset = 0;
2033 dst_entry->eflags &= ~MAP_ENTRY_VN_EXEC;
2036 VM_OBJECT_WLOCK(dst_object);
2037 if (fork_charge != NULL) {
2038 KASSERT(dst_entry->cred == NULL,
2039 ("vm_fault_copy_entry: leaked swp charge"));
2040 dst_object->cred = curthread->td_ucred;
2041 crhold(dst_object->cred);
2042 *fork_charge += dst_object->charge;
2043 } else if ((dst_object->flags & OBJ_SWAP) != 0 &&
2044 dst_object->cred == NULL) {
2045 KASSERT(dst_entry->cred != NULL, ("no cred for entry %p",
2047 dst_object->cred = dst_entry->cred;
2048 dst_entry->cred = NULL;
2052 * Loop through all of the virtual pages within the entry's
2053 * range, copying each page from the source object to the
2054 * destination object. Since the source is wired, those pages
2055 * must exist. In contrast, the destination is pageable.
2056 * Since the destination object doesn't share any backing storage
2057 * with the source object, all of its pages must be dirtied,
2058 * regardless of whether they can be written.
2060 for (vaddr = dst_entry->start, dst_pindex = 0;
2061 vaddr < dst_entry->end;
2062 vaddr += PAGE_SIZE, dst_pindex++) {
2065 * Find the page in the source object, and copy it in.
2066 * Because the source is wired down, the page will be
2069 if (src_object != dst_object)
2070 VM_OBJECT_RLOCK(src_object);
2071 object = src_object;
2072 pindex = src_pindex + dst_pindex;
2073 while ((src_m = vm_page_lookup(object, pindex)) == NULL &&
2074 (backing_object = object->backing_object) != NULL) {
2076 * Unless the source mapping is read-only or
2077 * it is presently being upgraded from
2078 * read-only, the first object in the shadow
2079 * chain should provide all of the pages. In
2080 * other words, this loop body should never be
2081 * executed when the source mapping is already
2084 KASSERT((src_entry->protection & VM_PROT_WRITE) == 0 ||
2086 ("vm_fault_copy_entry: main object missing page"));
2088 VM_OBJECT_RLOCK(backing_object);
2089 pindex += OFF_TO_IDX(object->backing_object_offset);
2090 if (object != dst_object)
2091 VM_OBJECT_RUNLOCK(object);
2092 object = backing_object;
2094 KASSERT(src_m != NULL, ("vm_fault_copy_entry: page missing"));
2096 if (object != dst_object) {
2098 * Allocate a page in the destination object.
2100 dst_m = vm_page_alloc(dst_object, (src_object ==
2101 dst_object ? src_pindex : 0) + dst_pindex,
2103 if (dst_m == NULL) {
2104 VM_OBJECT_WUNLOCK(dst_object);
2105 VM_OBJECT_RUNLOCK(object);
2106 vm_wait(dst_object);
2107 VM_OBJECT_WLOCK(dst_object);
2110 pmap_copy_page(src_m, dst_m);
2113 * The object lock does not guarantee that "src_m" will
2114 * transition from invalid to valid, but it does ensure
2115 * that "src_m" will not transition from valid to
2118 dst_m->dirty = dst_m->valid = src_m->valid;
2119 VM_OBJECT_RUNLOCK(object);
2122 if (vm_page_busy_acquire(dst_m, VM_ALLOC_WAITFAIL) == 0)
2124 if (dst_m->pindex >= dst_object->size) {
2126 * We are upgrading. Index can occur
2127 * out of bounds if the object type is
2128 * vnode and the file was truncated.
2130 vm_page_xunbusy(dst_m);
2136 * Enter it in the pmap. If a wired, copy-on-write
2137 * mapping is being replaced by a write-enabled
2138 * mapping, then wire that new mapping.
2140 * The page can be invalid if the user called
2141 * msync(MS_INVALIDATE) or truncated the backing vnode
2142 * or shared memory object. In this case, do not
2143 * insert it into pmap, but still do the copy so that
2144 * all copies of the wired map entry have similar
2147 if (vm_page_all_valid(dst_m)) {
2148 VM_OBJECT_WUNLOCK(dst_object);
2149 pmap_enter(dst_map->pmap, vaddr, dst_m, prot,
2150 access | (upgrade ? PMAP_ENTER_WIRED : 0), 0);
2151 VM_OBJECT_WLOCK(dst_object);
2155 * Mark it no longer busy, and put it on the active list.
2158 if (src_m != dst_m) {
2159 vm_page_unwire(src_m, PQ_INACTIVE);
2160 vm_page_wire(dst_m);
2162 KASSERT(vm_page_wired(dst_m),
2163 ("dst_m %p is not wired", dst_m));
2166 vm_page_activate(dst_m);
2168 vm_page_xunbusy(dst_m);
2170 VM_OBJECT_WUNLOCK(dst_object);
2172 dst_entry->eflags &= ~(MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY);
2173 vm_object_deallocate(src_object);
2178 * Block entry into the machine-independent layer's page fault handler by
2179 * the calling thread. Subsequent calls to vm_fault() by that thread will
2180 * return KERN_PROTECTION_FAILURE. Enable machine-dependent handling of
2181 * spurious page faults.
2184 vm_fault_disable_pagefaults(void)
2187 return (curthread_pflags_set(TDP_NOFAULTING | TDP_RESETSPUR));
2191 vm_fault_enable_pagefaults(int save)
2194 curthread_pflags_restore(save);