xref: /freebsd/sys/vm/vm_fault.c (revision f1b656f14464c2e3ec4ab2eeade3b00dce4bd459)
1 /*-
2  * SPDX-License-Identifier: (BSD-4-Clause AND MIT-CMU)
3  *
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * Copyright (c) 1994 John S. Dyson
7  * All rights reserved.
8  * Copyright (c) 1994 David Greenman
9  * All rights reserved.
10  *
11  *
12  * This code is derived from software contributed to Berkeley by
13  * The Mach Operating System project at Carnegie-Mellon University.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
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.
30  *
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
41  * SUCH DAMAGE.
42  *
43  *
44  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
45  * All rights reserved.
46  *
47  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
48  *
49  * Permission to use, copy, modify and distribute this software and
50  * its documentation is hereby granted, provided that both the copyright
51  * notice and this permission notice appear in all copies of the
52  * software, derivative works or modified versions, and any portions
53  * thereof, and that both notices appear in supporting documentation.
54  *
55  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
56  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
57  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
58  *
59  * Carnegie Mellon requests users of this software to return to
60  *
61  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
62  *  School of Computer Science
63  *  Carnegie Mellon University
64  *  Pittsburgh PA 15213-3890
65  *
66  * any improvements or extensions that they make and grant Carnegie the
67  * rights to redistribute these changes.
68  */
69 
70 /*
71  *	Page fault handling module.
72  */
73 
74 #include "opt_ktrace.h"
75 #include "opt_vm.h"
76 
77 #include <sys/systm.h>
78 #include <sys/kernel.h>
79 #include <sys/lock.h>
80 #include <sys/mman.h>
81 #include <sys/mutex.h>
82 #include <sys/pctrie.h>
83 #include <sys/proc.h>
84 #include <sys/racct.h>
85 #include <sys/refcount.h>
86 #include <sys/resourcevar.h>
87 #include <sys/rwlock.h>
88 #include <sys/signalvar.h>
89 #include <sys/sysctl.h>
90 #include <sys/sysent.h>
91 #include <sys/vmmeter.h>
92 #include <sys/vnode.h>
93 #ifdef KTRACE
94 #include <sys/ktrace.h>
95 #endif
96 
97 #include <vm/vm.h>
98 #include <vm/vm_param.h>
99 #include <vm/pmap.h>
100 #include <vm/vm_map.h>
101 #include <vm/vm_object.h>
102 #include <vm/vm_page.h>
103 #include <vm/vm_pageout.h>
104 #include <vm/vm_kern.h>
105 #include <vm/vm_pager.h>
106 #include <vm/vm_radix.h>
107 #include <vm/vm_extern.h>
108 #include <vm/vm_reserv.h>
109 
110 #define PFBAK 4
111 #define PFFOR 4
112 
113 #define	VM_FAULT_READ_DEFAULT	(1 + VM_FAULT_READ_AHEAD_INIT)
114 
115 #define	VM_FAULT_DONTNEED_MIN	1048576
116 
117 struct faultstate {
118 	/* Fault parameters. */
119 	vm_offset_t	vaddr;
120 	vm_page_t	*m_hold;
121 	vm_prot_t	fault_type;
122 	vm_prot_t	prot;
123 	int		fault_flags;
124 	boolean_t	wired;
125 
126 	/* Control state. */
127 	struct timeval	oom_start_time;
128 	bool		oom_started;
129 	int		nera;
130 	bool		can_read_lock;
131 
132 	/* Page reference for cow. */
133 	vm_page_t m_cow;
134 
135 	/* Current object. */
136 	vm_object_t	object;
137 	vm_pindex_t	pindex;
138 	vm_page_t	m;
139 
140 	/* Top-level map object. */
141 	vm_object_t	first_object;
142 	vm_pindex_t	first_pindex;
143 	vm_page_t	first_m;
144 
145 	/* Map state. */
146 	vm_map_t	map;
147 	vm_map_entry_t	entry;
148 	int		map_generation;
149 	bool		lookup_still_valid;
150 
151 	/* Vnode if locked. */
152 	struct vnode	*vp;
153 };
154 
155 /*
156  * Return codes for internal fault routines.
157  */
158 enum fault_status {
159 	FAULT_SUCCESS = 10000,	/* Return success to user. */
160 	FAULT_FAILURE,		/* Return failure to user. */
161 	FAULT_CONTINUE,		/* Continue faulting. */
162 	FAULT_RESTART,		/* Restart fault. */
163 	FAULT_OUT_OF_BOUNDS,	/* Invalid address for pager. */
164 	FAULT_HARD,		/* Performed I/O. */
165 	FAULT_SOFT,		/* Found valid page. */
166 	FAULT_PROTECTION_FAILURE, /* Invalid access. */
167 };
168 
169 enum fault_next_status {
170 	FAULT_NEXT_GOTOBJ = 1,
171 	FAULT_NEXT_NOOBJ,
172 	FAULT_NEXT_RESTART,
173 };
174 
175 static void vm_fault_dontneed(const struct faultstate *fs, vm_offset_t vaddr,
176 	    int ahead);
177 static void vm_fault_prefault(const struct faultstate *fs, vm_offset_t addra,
178 	    int backward, int forward, bool obj_locked);
179 
180 static int vm_pfault_oom_attempts = 3;
181 SYSCTL_INT(_vm, OID_AUTO, pfault_oom_attempts, CTLFLAG_RWTUN,
182     &vm_pfault_oom_attempts, 0,
183     "Number of page allocation attempts in page fault handler before it "
184     "triggers OOM handling");
185 
186 static int vm_pfault_oom_wait = 10;
187 SYSCTL_INT(_vm, OID_AUTO, pfault_oom_wait, CTLFLAG_RWTUN,
188     &vm_pfault_oom_wait, 0,
189     "Number of seconds to wait for free pages before retrying "
190     "the page fault handler");
191 
192 static inline void
vm_fault_page_release(vm_page_t * mp)193 vm_fault_page_release(vm_page_t *mp)
194 {
195 	vm_page_t m;
196 
197 	m = *mp;
198 	if (m != NULL) {
199 		/*
200 		 * We are likely to loop around again and attempt to busy
201 		 * this page.  Deactivating it leaves it available for
202 		 * pageout while optimizing fault restarts.
203 		 */
204 		vm_page_deactivate(m);
205 		if (vm_page_xbusied(m))
206 			vm_page_xunbusy(m);
207 		else
208 			vm_page_sunbusy(m);
209 		*mp = NULL;
210 	}
211 }
212 
213 static inline void
vm_fault_page_free(vm_page_t * mp)214 vm_fault_page_free(vm_page_t *mp)
215 {
216 	vm_page_t m;
217 
218 	m = *mp;
219 	if (m != NULL) {
220 		VM_OBJECT_ASSERT_WLOCKED(m->object);
221 		if (!vm_page_wired(m))
222 			vm_page_free(m);
223 		else
224 			vm_page_xunbusy(m);
225 		*mp = NULL;
226 	}
227 }
228 
229 /*
230  * Return true if a vm_pager_get_pages() call is needed in order to check
231  * whether the pager might have a particular page, false if it can be determined
232  * immediately that the pager can not have a copy.  For swap objects, this can
233  * be checked quickly.
234  */
235 static inline bool
vm_fault_object_needs_getpages(vm_object_t object)236 vm_fault_object_needs_getpages(vm_object_t object)
237 {
238 	VM_OBJECT_ASSERT_LOCKED(object);
239 
240 	return ((object->flags & OBJ_SWAP) == 0 ||
241 	    !pctrie_is_empty(&object->un_pager.swp.swp_blks));
242 }
243 
244 static inline void
vm_fault_unlock_map(struct faultstate * fs)245 vm_fault_unlock_map(struct faultstate *fs)
246 {
247 
248 	if (fs->lookup_still_valid) {
249 		vm_map_lookup_done(fs->map, fs->entry);
250 		fs->lookup_still_valid = false;
251 	}
252 }
253 
254 static void
vm_fault_unlock_vp(struct faultstate * fs)255 vm_fault_unlock_vp(struct faultstate *fs)
256 {
257 
258 	if (fs->vp != NULL) {
259 		vput(fs->vp);
260 		fs->vp = NULL;
261 	}
262 }
263 
264 static bool
vm_fault_might_be_cow(struct faultstate * fs)265 vm_fault_might_be_cow(struct faultstate *fs)
266 {
267 	return (fs->object != fs->first_object);
268 }
269 
270 static void
vm_fault_deallocate(struct faultstate * fs)271 vm_fault_deallocate(struct faultstate *fs)
272 {
273 
274 	vm_fault_page_release(&fs->m_cow);
275 	vm_fault_page_release(&fs->m);
276 	vm_object_pip_wakeup(fs->object);
277 	if (vm_fault_might_be_cow(fs)) {
278 		VM_OBJECT_WLOCK(fs->first_object);
279 		vm_fault_page_free(&fs->first_m);
280 		VM_OBJECT_WUNLOCK(fs->first_object);
281 		vm_object_pip_wakeup(fs->first_object);
282 	}
283 	vm_object_deallocate(fs->first_object);
284 	vm_fault_unlock_map(fs);
285 	vm_fault_unlock_vp(fs);
286 }
287 
288 static void
vm_fault_unlock_and_deallocate(struct faultstate * fs)289 vm_fault_unlock_and_deallocate(struct faultstate *fs)
290 {
291 
292 	VM_OBJECT_UNLOCK(fs->object);
293 	vm_fault_deallocate(fs);
294 }
295 
296 static void
vm_fault_dirty(struct faultstate * fs,vm_page_t m)297 vm_fault_dirty(struct faultstate *fs, vm_page_t m)
298 {
299 	bool need_dirty;
300 
301 	if (((fs->prot & VM_PROT_WRITE) == 0 &&
302 	    (fs->fault_flags & VM_FAULT_DIRTY) == 0) ||
303 	    (m->oflags & VPO_UNMANAGED) != 0)
304 		return;
305 
306 	VM_PAGE_OBJECT_BUSY_ASSERT(m);
307 
308 	need_dirty = ((fs->fault_type & VM_PROT_WRITE) != 0 &&
309 	    (fs->fault_flags & VM_FAULT_WIRE) == 0) ||
310 	    (fs->fault_flags & VM_FAULT_DIRTY) != 0;
311 
312 	vm_object_set_writeable_dirty(m->object);
313 
314 	/*
315 	 * If the fault is a write, we know that this page is being
316 	 * written NOW so dirty it explicitly to save on
317 	 * pmap_is_modified() calls later.
318 	 *
319 	 * Also, since the page is now dirty, we can possibly tell
320 	 * the pager to release any swap backing the page.
321 	 */
322 	if (need_dirty && vm_page_set_dirty(m) == 0) {
323 		/*
324 		 * If this is a NOSYNC mmap we do not want to set PGA_NOSYNC
325 		 * if the page is already dirty to prevent data written with
326 		 * the expectation of being synced from not being synced.
327 		 * Likewise if this entry does not request NOSYNC then make
328 		 * sure the page isn't marked NOSYNC.  Applications sharing
329 		 * data should use the same flags to avoid ping ponging.
330 		 */
331 		if ((fs->entry->eflags & MAP_ENTRY_NOSYNC) != 0)
332 			vm_page_aflag_set(m, PGA_NOSYNC);
333 		else
334 			vm_page_aflag_clear(m, PGA_NOSYNC);
335 	}
336 
337 }
338 
339 static bool
vm_fault_is_read(const struct faultstate * fs)340 vm_fault_is_read(const struct faultstate *fs)
341 {
342 	return ((fs->prot & VM_PROT_WRITE) == 0 &&
343 	    (fs->fault_type & (VM_PROT_COPY | VM_PROT_WRITE)) == 0);
344 }
345 
346 /*
347  * Unlocks fs.first_object and fs.map on success.
348  */
349 static enum fault_status
vm_fault_soft_fast(struct faultstate * fs)350 vm_fault_soft_fast(struct faultstate *fs)
351 {
352 	vm_page_t m, m_map;
353 #if VM_NRESERVLEVEL > 0
354 	vm_page_t m_super;
355 	int flags;
356 #endif
357 	int psind;
358 	vm_offset_t vaddr;
359 
360 	MPASS(fs->vp == NULL);
361 
362 	/*
363 	 * If we fail, vast majority of the time it is because the page is not
364 	 * there to begin with. Opportunistically perform the lookup and
365 	 * subsequent checks without the object lock, revalidate later.
366 	 *
367 	 * Note: a busy page can be mapped for read|execute access.
368 	 */
369 	m = vm_page_lookup_unlocked(fs->first_object, fs->first_pindex);
370 	if (m == NULL || !vm_page_all_valid(m) ||
371 	    ((fs->prot & VM_PROT_WRITE) != 0 && vm_page_busied(m))) {
372 		VM_OBJECT_WLOCK(fs->first_object);
373 		return (FAULT_FAILURE);
374 	}
375 
376 	vaddr = fs->vaddr;
377 
378 	VM_OBJECT_RLOCK(fs->first_object);
379 
380 	/*
381 	 * Now that we stabilized the state, revalidate the page is in the shape
382 	 * we encountered above.
383 	 */
384 
385 	if (m->object != fs->first_object || m->pindex != fs->first_pindex)
386 		goto fail;
387 
388 	vm_object_busy(fs->first_object);
389 
390 	if (!vm_page_all_valid(m) ||
391 	    ((fs->prot & VM_PROT_WRITE) != 0 && vm_page_busied(m)))
392 		goto fail_busy;
393 
394 	m_map = m;
395 	psind = 0;
396 #if VM_NRESERVLEVEL > 0
397 	if ((m->flags & PG_FICTITIOUS) == 0 &&
398 	    (m_super = vm_reserv_to_superpage(m)) != NULL) {
399 		psind = m_super->psind;
400 		KASSERT(psind > 0,
401 		    ("psind %d of m_super %p < 1", psind, m_super));
402 		flags = PS_ALL_VALID;
403 		if ((fs->prot & VM_PROT_WRITE) != 0) {
404 			/*
405 			 * Create a superpage mapping allowing write access
406 			 * only if none of the constituent pages are busy and
407 			 * all of them are already dirty (except possibly for
408 			 * the page that was faulted on).
409 			 */
410 			flags |= PS_NONE_BUSY;
411 			if ((fs->first_object->flags & OBJ_UNMANAGED) == 0)
412 				flags |= PS_ALL_DIRTY;
413 		}
414 		while (rounddown2(vaddr, pagesizes[psind]) < fs->entry->start ||
415 		    roundup2(vaddr + 1, pagesizes[psind]) > fs->entry->end ||
416 		    (vaddr & (pagesizes[psind] - 1)) !=
417 		    (VM_PAGE_TO_PHYS(m) & (pagesizes[psind] - 1)) ||
418 		    !vm_page_ps_test(m_super, psind, flags, m) ||
419 		    !pmap_ps_enabled(fs->map->pmap)) {
420 			psind--;
421 			if (psind == 0)
422 				break;
423 			m_super += rounddown2(m - m_super,
424 			    atop(pagesizes[psind]));
425 			KASSERT(m_super->psind >= psind,
426 			    ("psind %d of m_super %p < %d", m_super->psind,
427 			    m_super, psind));
428 		}
429 		if (psind > 0) {
430 			m_map = m_super;
431 			vaddr = rounddown2(vaddr, pagesizes[psind]);
432 			/* Preset the modified bit for dirty superpages. */
433 			if ((flags & PS_ALL_DIRTY) != 0)
434 				fs->fault_type |= VM_PROT_WRITE;
435 		}
436 	}
437 #endif
438 	if (pmap_enter(fs->map->pmap, vaddr, m_map, fs->prot, fs->fault_type |
439 	    PMAP_ENTER_NOSLEEP | (fs->wired ? PMAP_ENTER_WIRED : 0), psind) !=
440 	    KERN_SUCCESS)
441 		goto fail_busy;
442 	if (fs->m_hold != NULL) {
443 		(*fs->m_hold) = m;
444 		vm_page_wire(m);
445 	}
446 	if (psind == 0 && !fs->wired)
447 		vm_fault_prefault(fs, vaddr, PFBAK, PFFOR, true);
448 	VM_OBJECT_RUNLOCK(fs->first_object);
449 	vm_fault_dirty(fs, m);
450 	vm_object_unbusy(fs->first_object);
451 	vm_map_lookup_done(fs->map, fs->entry);
452 	curthread->td_ru.ru_minflt++;
453 	return (FAULT_SUCCESS);
454 fail_busy:
455 	vm_object_unbusy(fs->first_object);
456 fail:
457 	if (!VM_OBJECT_TRYUPGRADE(fs->first_object)) {
458 		VM_OBJECT_RUNLOCK(fs->first_object);
459 		VM_OBJECT_WLOCK(fs->first_object);
460 	}
461 	return (FAULT_FAILURE);
462 }
463 
464 static void
vm_fault_restore_map_lock(struct faultstate * fs)465 vm_fault_restore_map_lock(struct faultstate *fs)
466 {
467 
468 	VM_OBJECT_ASSERT_WLOCKED(fs->first_object);
469 	MPASS(blockcount_read(&fs->first_object->paging_in_progress) > 0);
470 
471 	if (!vm_map_trylock_read(fs->map)) {
472 		VM_OBJECT_WUNLOCK(fs->first_object);
473 		vm_map_lock_read(fs->map);
474 		VM_OBJECT_WLOCK(fs->first_object);
475 	}
476 	fs->lookup_still_valid = true;
477 }
478 
479 static void
vm_fault_populate_check_page(vm_page_t m)480 vm_fault_populate_check_page(vm_page_t m)
481 {
482 
483 	/*
484 	 * Check each page to ensure that the pager is obeying the
485 	 * interface: the page must be installed in the object, fully
486 	 * valid, and exclusively busied.
487 	 */
488 	MPASS(m != NULL);
489 	MPASS(vm_page_all_valid(m));
490 	MPASS(vm_page_xbusied(m));
491 }
492 
493 static void
vm_fault_populate_cleanup(vm_object_t object,vm_pindex_t first,vm_pindex_t last)494 vm_fault_populate_cleanup(vm_object_t object, vm_pindex_t first,
495     vm_pindex_t last)
496 {
497 	struct pctrie_iter pages;
498 	vm_page_t m;
499 
500 	VM_OBJECT_ASSERT_WLOCKED(object);
501 	MPASS(first <= last);
502 	vm_page_iter_limit_init(&pages, object, last + 1);
503 	VM_RADIX_FORALL_FROM(m, &pages, first) {
504 		vm_fault_populate_check_page(m);
505 		vm_page_deactivate(m);
506 		vm_page_xunbusy(m);
507 	}
508 	KASSERT(pages.index == last, ("%s: pindex mismatch", __func__));
509 }
510 
511 static enum fault_status
vm_fault_populate(struct faultstate * fs)512 vm_fault_populate(struct faultstate *fs)
513 {
514 	vm_offset_t vaddr;
515 	vm_page_t m;
516 	vm_pindex_t map_first, map_last, pager_first, pager_last, pidx;
517 	int bdry_idx, i, npages, psind, rv;
518 	enum fault_status res;
519 
520 	MPASS(fs->object == fs->first_object);
521 	VM_OBJECT_ASSERT_WLOCKED(fs->first_object);
522 	MPASS(blockcount_read(&fs->first_object->paging_in_progress) > 0);
523 	MPASS(fs->first_object->backing_object == NULL);
524 	MPASS(fs->lookup_still_valid);
525 
526 	pager_first = OFF_TO_IDX(fs->entry->offset);
527 	pager_last = pager_first + atop(fs->entry->end - fs->entry->start) - 1;
528 	vm_fault_unlock_map(fs);
529 	vm_fault_unlock_vp(fs);
530 
531 	res = FAULT_SUCCESS;
532 
533 	/*
534 	 * Call the pager (driver) populate() method.
535 	 *
536 	 * There is no guarantee that the method will be called again
537 	 * if the current fault is for read, and a future fault is
538 	 * for write.  Report the entry's maximum allowed protection
539 	 * to the driver.
540 	 */
541 	rv = vm_pager_populate(fs->first_object, fs->first_pindex,
542 	    fs->fault_type, fs->entry->max_protection, &pager_first,
543 	    &pager_last);
544 
545 	VM_OBJECT_ASSERT_WLOCKED(fs->first_object);
546 	if (rv == VM_PAGER_BAD) {
547 		/*
548 		 * VM_PAGER_BAD is the backdoor for a pager to request
549 		 * normal fault handling.
550 		 */
551 		vm_fault_restore_map_lock(fs);
552 		if (fs->map->timestamp != fs->map_generation)
553 			return (FAULT_RESTART);
554 		return (FAULT_CONTINUE);
555 	}
556 	if (rv != VM_PAGER_OK)
557 		return (FAULT_FAILURE); /* AKA SIGSEGV */
558 
559 	/* Ensure that the driver is obeying the interface. */
560 	MPASS(pager_first <= pager_last);
561 	MPASS(fs->first_pindex <= pager_last);
562 	MPASS(fs->first_pindex >= pager_first);
563 	MPASS(pager_last < fs->first_object->size);
564 
565 	vm_fault_restore_map_lock(fs);
566 	bdry_idx = MAP_ENTRY_SPLIT_BOUNDARY_INDEX(fs->entry);
567 	if (fs->map->timestamp != fs->map_generation) {
568 		if (bdry_idx == 0) {
569 			vm_fault_populate_cleanup(fs->first_object, pager_first,
570 			    pager_last);
571 		} else {
572 			m = vm_page_lookup(fs->first_object, pager_first);
573 			if (m != fs->m)
574 				vm_page_xunbusy(m);
575 		}
576 		return (FAULT_RESTART);
577 	}
578 
579 	/*
580 	 * The map is unchanged after our last unlock.  Process the fault.
581 	 *
582 	 * First, the special case of largepage mappings, where
583 	 * populate only busies the first page in superpage run.
584 	 */
585 	if (bdry_idx != 0) {
586 		KASSERT(PMAP_HAS_LARGEPAGES,
587 		    ("missing pmap support for large pages"));
588 		m = vm_page_lookup(fs->first_object, pager_first);
589 		vm_fault_populate_check_page(m);
590 		VM_OBJECT_WUNLOCK(fs->first_object);
591 		vaddr = fs->entry->start + IDX_TO_OFF(pager_first) -
592 		    fs->entry->offset;
593 		/* assert alignment for entry */
594 		KASSERT((vaddr & (pagesizes[bdry_idx] - 1)) == 0,
595     ("unaligned superpage start %#jx pager_first %#jx offset %#jx vaddr %#jx",
596 		    (uintmax_t)fs->entry->start, (uintmax_t)pager_first,
597 		    (uintmax_t)fs->entry->offset, (uintmax_t)vaddr));
598 		KASSERT((VM_PAGE_TO_PHYS(m) & (pagesizes[bdry_idx] - 1)) == 0,
599 		    ("unaligned superpage m %p %#jx", m,
600 		    (uintmax_t)VM_PAGE_TO_PHYS(m)));
601 		rv = pmap_enter(fs->map->pmap, vaddr, m, fs->prot,
602 		    fs->fault_type | (fs->wired ? PMAP_ENTER_WIRED : 0) |
603 		    PMAP_ENTER_LARGEPAGE, bdry_idx);
604 		VM_OBJECT_WLOCK(fs->first_object);
605 		vm_page_xunbusy(m);
606 		if (rv != KERN_SUCCESS) {
607 			res = FAULT_FAILURE;
608 			goto out;
609 		}
610 		if ((fs->fault_flags & VM_FAULT_WIRE) != 0) {
611 			for (i = 0; i < atop(pagesizes[bdry_idx]); i++)
612 				vm_page_wire(m + i);
613 		}
614 		if (fs->m_hold != NULL) {
615 			*fs->m_hold = m + (fs->first_pindex - pager_first);
616 			vm_page_wire(*fs->m_hold);
617 		}
618 		goto out;
619 	}
620 
621 	/*
622 	 * The range [pager_first, pager_last] that is given to the
623 	 * pager is only a hint.  The pager may populate any range
624 	 * within the object that includes the requested page index.
625 	 * In case the pager expanded the range, clip it to fit into
626 	 * the map entry.
627 	 */
628 	map_first = OFF_TO_IDX(fs->entry->offset);
629 	if (map_first > pager_first) {
630 		vm_fault_populate_cleanup(fs->first_object, pager_first,
631 		    map_first - 1);
632 		pager_first = map_first;
633 	}
634 	map_last = map_first + atop(fs->entry->end - fs->entry->start) - 1;
635 	if (map_last < pager_last) {
636 		vm_fault_populate_cleanup(fs->first_object, map_last + 1,
637 		    pager_last);
638 		pager_last = map_last;
639 	}
640 	for (pidx = pager_first; pidx <= pager_last; pidx += npages) {
641 		m = vm_page_lookup(fs->first_object, pidx);
642 		vaddr = fs->entry->start + IDX_TO_OFF(pidx) - fs->entry->offset;
643 		KASSERT(m != NULL && m->pindex == pidx,
644 		    ("%s: pindex mismatch", __func__));
645 		psind = m->psind;
646 		while (psind > 0 && ((vaddr & (pagesizes[psind] - 1)) != 0 ||
647 		    pidx + OFF_TO_IDX(pagesizes[psind]) - 1 > pager_last ||
648 		    !pmap_ps_enabled(fs->map->pmap)))
649 			psind--;
650 
651 		npages = atop(pagesizes[psind]);
652 		for (i = 0; i < npages; i++) {
653 			vm_fault_populate_check_page(&m[i]);
654 			vm_fault_dirty(fs, &m[i]);
655 		}
656 		VM_OBJECT_WUNLOCK(fs->first_object);
657 		rv = pmap_enter(fs->map->pmap, vaddr, m, fs->prot, fs->fault_type |
658 		    (fs->wired ? PMAP_ENTER_WIRED : 0), psind);
659 
660 		/*
661 		 * pmap_enter() may fail for a superpage mapping if additional
662 		 * protection policies prevent the full mapping.
663 		 * For example, this will happen on amd64 if the entire
664 		 * address range does not share the same userspace protection
665 		 * key.  Revert to single-page mappings if this happens.
666 		 */
667 		MPASS(rv == KERN_SUCCESS ||
668 		    (psind > 0 && rv == KERN_PROTECTION_FAILURE));
669 		if (__predict_false(psind > 0 &&
670 		    rv == KERN_PROTECTION_FAILURE)) {
671 			MPASS(!fs->wired);
672 			for (i = 0; i < npages; i++) {
673 				rv = pmap_enter(fs->map->pmap, vaddr + ptoa(i),
674 				    &m[i], fs->prot, fs->fault_type, 0);
675 				MPASS(rv == KERN_SUCCESS);
676 			}
677 		}
678 
679 		VM_OBJECT_WLOCK(fs->first_object);
680 		for (i = 0; i < npages; i++) {
681 			if ((fs->fault_flags & VM_FAULT_WIRE) != 0 &&
682 			    m[i].pindex == fs->first_pindex)
683 				vm_page_wire(&m[i]);
684 			else
685 				vm_page_activate(&m[i]);
686 			if (fs->m_hold != NULL &&
687 			    m[i].pindex == fs->first_pindex) {
688 				(*fs->m_hold) = &m[i];
689 				vm_page_wire(&m[i]);
690 			}
691 			vm_page_xunbusy(&m[i]);
692 		}
693 	}
694 out:
695 	curthread->td_ru.ru_majflt++;
696 	return (res);
697 }
698 
699 static int prot_fault_translation;
700 SYSCTL_INT(_machdep, OID_AUTO, prot_fault_translation, CTLFLAG_RWTUN,
701     &prot_fault_translation, 0,
702     "Control signal to deliver on protection fault");
703 
704 /* compat definition to keep common code for signal translation */
705 #define	UCODE_PAGEFLT	12
706 #ifdef T_PAGEFLT
707 _Static_assert(UCODE_PAGEFLT == T_PAGEFLT, "T_PAGEFLT");
708 #endif
709 
710 /*
711  *	vm_fault_trap:
712  *
713  *	Handle a page fault occurring at the given address,
714  *	requiring the given permissions, in the map specified.
715  *	If successful, the page is inserted into the
716  *	associated physical map.
717  *
718  *	NOTE: the given address should be truncated to the
719  *	proper page address.
720  *
721  *	KERN_SUCCESS is returned if the page fault is handled; otherwise,
722  *	a standard error specifying why the fault is fatal is returned.
723  *
724  *	The map in question must be referenced, and remains so.
725  *	Caller may hold no locks.
726  */
727 int
vm_fault_trap(vm_map_t map,vm_offset_t vaddr,vm_prot_t fault_type,int fault_flags,int * signo,int * ucode)728 vm_fault_trap(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
729     int fault_flags, int *signo, int *ucode)
730 {
731 	int result;
732 
733 	MPASS(signo == NULL || ucode != NULL);
734 #ifdef KTRACE
735 	if (map != kernel_map && KTRPOINT(curthread, KTR_FAULT))
736 		ktrfault(vaddr, fault_type);
737 #endif
738 	result = vm_fault(map, trunc_page(vaddr), fault_type, fault_flags,
739 	    NULL);
740 	KASSERT(result == KERN_SUCCESS || result == KERN_FAILURE ||
741 	    result == KERN_INVALID_ADDRESS ||
742 	    result == KERN_RESOURCE_SHORTAGE ||
743 	    result == KERN_PROTECTION_FAILURE ||
744 	    result == KERN_OUT_OF_BOUNDS,
745 	    ("Unexpected Mach error %d from vm_fault()", result));
746 #ifdef KTRACE
747 	if (map != kernel_map && KTRPOINT(curthread, KTR_FAULTEND))
748 		ktrfaultend(result);
749 #endif
750 	if (result != KERN_SUCCESS && signo != NULL) {
751 		switch (result) {
752 		case KERN_FAILURE:
753 		case KERN_INVALID_ADDRESS:
754 			*signo = SIGSEGV;
755 			*ucode = SEGV_MAPERR;
756 			break;
757 		case KERN_RESOURCE_SHORTAGE:
758 			*signo = SIGBUS;
759 			*ucode = BUS_OOMERR;
760 			break;
761 		case KERN_OUT_OF_BOUNDS:
762 			*signo = SIGBUS;
763 			*ucode = BUS_OBJERR;
764 			break;
765 		case KERN_PROTECTION_FAILURE:
766 			if (prot_fault_translation == 0) {
767 				/*
768 				 * Autodetect.  This check also covers
769 				 * the images without the ABI-tag ELF
770 				 * note.
771 				 */
772 				if (SV_CURPROC_ABI() == SV_ABI_FREEBSD &&
773 				    curproc->p_osrel >= P_OSREL_SIGSEGV) {
774 					*signo = SIGSEGV;
775 					*ucode = SEGV_ACCERR;
776 				} else {
777 					*signo = SIGBUS;
778 					*ucode = UCODE_PAGEFLT;
779 				}
780 			} else if (prot_fault_translation == 1) {
781 				/* Always compat mode. */
782 				*signo = SIGBUS;
783 				*ucode = UCODE_PAGEFLT;
784 			} else {
785 				/* Always SIGSEGV mode. */
786 				*signo = SIGSEGV;
787 				*ucode = SEGV_ACCERR;
788 			}
789 			break;
790 		default:
791 			KASSERT(0, ("Unexpected Mach error %d from vm_fault()",
792 			    result));
793 			break;
794 		}
795 	}
796 	return (result);
797 }
798 
799 static bool
vm_fault_object_ensure_wlocked(struct faultstate * fs)800 vm_fault_object_ensure_wlocked(struct faultstate *fs)
801 {
802 	if (fs->object == fs->first_object)
803 		VM_OBJECT_ASSERT_WLOCKED(fs->object);
804 
805 	if (!fs->can_read_lock)  {
806 		VM_OBJECT_ASSERT_WLOCKED(fs->object);
807 		return (true);
808 	}
809 
810 	if (VM_OBJECT_WOWNED(fs->object))
811 		return (true);
812 
813 	if (VM_OBJECT_TRYUPGRADE(fs->object))
814 		return (true);
815 
816 	return (false);
817 }
818 
819 static enum fault_status
vm_fault_lock_vnode(struct faultstate * fs,bool objlocked)820 vm_fault_lock_vnode(struct faultstate *fs, bool objlocked)
821 {
822 	struct vnode *vp;
823 	int error, locked;
824 
825 	if (fs->object->type != OBJT_VNODE)
826 		return (FAULT_CONTINUE);
827 	vp = fs->object->handle;
828 	if (vp == fs->vp) {
829 		ASSERT_VOP_LOCKED(vp, "saved vnode is not locked");
830 		return (FAULT_CONTINUE);
831 	}
832 
833 	/*
834 	 * Perform an unlock in case the desired vnode changed while
835 	 * the map was unlocked during a retry.
836 	 */
837 	vm_fault_unlock_vp(fs);
838 
839 	locked = VOP_ISLOCKED(vp);
840 	if (locked != LK_EXCLUSIVE)
841 		locked = LK_SHARED;
842 
843 	/*
844 	 * We must not sleep acquiring the vnode lock while we have
845 	 * the page exclusive busied or the object's
846 	 * paging-in-progress count incremented.  Otherwise, we could
847 	 * deadlock.
848 	 */
849 	error = vget(vp, locked | LK_CANRECURSE | LK_NOWAIT);
850 	if (error == 0) {
851 		fs->vp = vp;
852 		return (FAULT_CONTINUE);
853 	}
854 
855 	vhold(vp);
856 	if (objlocked)
857 		vm_fault_unlock_and_deallocate(fs);
858 	else
859 		vm_fault_deallocate(fs);
860 	error = vget(vp, locked | LK_RETRY | LK_CANRECURSE);
861 	vdrop(vp);
862 	fs->vp = vp;
863 	KASSERT(error == 0, ("vm_fault: vget failed %d", error));
864 	return (FAULT_RESTART);
865 }
866 
867 /*
868  * Calculate the desired readahead.  Handle drop-behind.
869  *
870  * Returns the number of readahead blocks to pass to the pager.
871  */
872 static int
vm_fault_readahead(struct faultstate * fs)873 vm_fault_readahead(struct faultstate *fs)
874 {
875 	int era, nera;
876 	u_char behavior;
877 
878 	KASSERT(fs->lookup_still_valid, ("map unlocked"));
879 	era = fs->entry->read_ahead;
880 	behavior = vm_map_entry_behavior(fs->entry);
881 	if (behavior == MAP_ENTRY_BEHAV_RANDOM) {
882 		nera = 0;
883 	} else if (behavior == MAP_ENTRY_BEHAV_SEQUENTIAL) {
884 		nera = VM_FAULT_READ_AHEAD_MAX;
885 		if (fs->vaddr == fs->entry->next_read)
886 			vm_fault_dontneed(fs, fs->vaddr, nera);
887 	} else if (fs->vaddr == fs->entry->next_read) {
888 		/*
889 		 * This is a sequential fault.  Arithmetically
890 		 * increase the requested number of pages in
891 		 * the read-ahead window.  The requested
892 		 * number of pages is "# of sequential faults
893 		 * x (read ahead min + 1) + read ahead min"
894 		 */
895 		nera = VM_FAULT_READ_AHEAD_MIN;
896 		if (era > 0) {
897 			nera += era + 1;
898 			if (nera > VM_FAULT_READ_AHEAD_MAX)
899 				nera = VM_FAULT_READ_AHEAD_MAX;
900 		}
901 		if (era == VM_FAULT_READ_AHEAD_MAX)
902 			vm_fault_dontneed(fs, fs->vaddr, nera);
903 	} else {
904 		/*
905 		 * This is a non-sequential fault.
906 		 */
907 		nera = 0;
908 	}
909 	if (era != nera) {
910 		/*
911 		 * A read lock on the map suffices to update
912 		 * the read ahead count safely.
913 		 */
914 		fs->entry->read_ahead = nera;
915 	}
916 
917 	return (nera);
918 }
919 
920 static int
vm_fault_lookup(struct faultstate * fs)921 vm_fault_lookup(struct faultstate *fs)
922 {
923 	int result;
924 
925 	KASSERT(!fs->lookup_still_valid,
926 	   ("vm_fault_lookup: Map already locked."));
927 	result = vm_map_lookup(&fs->map, fs->vaddr, fs->fault_type |
928 	    VM_PROT_FAULT_LOOKUP, &fs->entry, &fs->first_object,
929 	    &fs->first_pindex, &fs->prot, &fs->wired);
930 	if (result != KERN_SUCCESS) {
931 		vm_fault_unlock_vp(fs);
932 		return (result);
933 	}
934 
935 	fs->map_generation = fs->map->timestamp;
936 
937 	if (fs->entry->eflags & MAP_ENTRY_NOFAULT) {
938 		panic("%s: fault on nofault entry, addr: %#lx",
939 		    __func__, (u_long)fs->vaddr);
940 	}
941 
942 	if (fs->entry->eflags & MAP_ENTRY_IN_TRANSITION &&
943 	    fs->entry->wiring_thread != curthread) {
944 		vm_map_unlock_read(fs->map);
945 		vm_map_lock(fs->map);
946 		if (vm_map_lookup_entry(fs->map, fs->vaddr, &fs->entry) &&
947 		    (fs->entry->eflags & MAP_ENTRY_IN_TRANSITION)) {
948 			vm_fault_unlock_vp(fs);
949 			fs->entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
950 			vm_map_unlock_and_wait(fs->map, 0);
951 		} else
952 			vm_map_unlock(fs->map);
953 		return (KERN_RESOURCE_SHORTAGE);
954 	}
955 
956 	MPASS((fs->entry->eflags & MAP_ENTRY_GUARD) == 0);
957 
958 	if (fs->wired)
959 		fs->fault_type = fs->prot | (fs->fault_type & VM_PROT_COPY);
960 	else
961 		KASSERT((fs->fault_flags & VM_FAULT_WIRE) == 0,
962 		    ("!fs->wired && VM_FAULT_WIRE"));
963 	fs->lookup_still_valid = true;
964 
965 	return (KERN_SUCCESS);
966 }
967 
968 static int
vm_fault_relookup(struct faultstate * fs)969 vm_fault_relookup(struct faultstate *fs)
970 {
971 	vm_object_t retry_object;
972 	vm_pindex_t retry_pindex;
973 	vm_prot_t retry_prot;
974 	int result;
975 
976 	if (!vm_map_trylock_read(fs->map))
977 		return (KERN_RESTART);
978 
979 	fs->lookup_still_valid = true;
980 	if (fs->map->timestamp == fs->map_generation)
981 		return (KERN_SUCCESS);
982 
983 	result = vm_map_lookup_locked(&fs->map, fs->vaddr, fs->fault_type,
984 	    &fs->entry, &retry_object, &retry_pindex, &retry_prot,
985 	    &fs->wired);
986 	if (result != KERN_SUCCESS) {
987 		/*
988 		 * If retry of map lookup would have blocked then
989 		 * retry fault from start.
990 		 */
991 		if (result == KERN_FAILURE)
992 			return (KERN_RESTART);
993 		return (result);
994 	}
995 	if (retry_object != fs->first_object ||
996 	    retry_pindex != fs->first_pindex)
997 		return (KERN_RESTART);
998 
999 	/*
1000 	 * Check whether the protection has changed or the object has
1001 	 * been copied while we left the map unlocked. Changing from
1002 	 * read to write permission is OK - we leave the page
1003 	 * write-protected, and catch the write fault. Changing from
1004 	 * write to read permission means that we can't mark the page
1005 	 * write-enabled after all.
1006 	 */
1007 	fs->prot &= retry_prot;
1008 	fs->fault_type &= retry_prot;
1009 	if (fs->prot == 0)
1010 		return (KERN_RESTART);
1011 
1012 	/* Reassert because wired may have changed. */
1013 	KASSERT(fs->wired || (fs->fault_flags & VM_FAULT_WIRE) == 0,
1014 	    ("!wired && VM_FAULT_WIRE"));
1015 
1016 	return (KERN_SUCCESS);
1017 }
1018 
1019 static bool
vm_fault_can_cow_rename(struct faultstate * fs)1020 vm_fault_can_cow_rename(struct faultstate *fs)
1021 {
1022 	return (
1023 	    /* Only one shadow object and no other refs. */
1024 	    fs->object->shadow_count == 1 && fs->object->ref_count == 1 &&
1025 	    /* No other ways to look the object up. */
1026 	    fs->object->handle == NULL && (fs->object->flags & OBJ_ANON) != 0);
1027 }
1028 
1029 static void
vm_fault_cow(struct faultstate * fs)1030 vm_fault_cow(struct faultstate *fs)
1031 {
1032 	bool is_first_object_locked, rename_cow;
1033 
1034 	KASSERT(vm_fault_might_be_cow(fs),
1035 	    ("source and target COW objects are identical"));
1036 
1037 	/*
1038 	 * This allows pages to be virtually copied from a backing_object
1039 	 * into the first_object, where the backing object has no other
1040 	 * refs to it, and cannot gain any more refs.  Instead of a bcopy,
1041 	 * we just move the page from the backing object to the first
1042 	 * object.  Note that we must mark the page dirty in the first
1043 	 * object so that it will go out to swap when needed.
1044 	 */
1045 	is_first_object_locked = false;
1046 	rename_cow = false;
1047 
1048 	if (vm_fault_can_cow_rename(fs) && vm_page_xbusied(fs->m)) {
1049 		/*
1050 		 * Check that we don't chase down the shadow chain and
1051 		 * we can acquire locks.  Recheck the conditions for
1052 		 * rename after the shadow chain is stable after the
1053 		 * object locking.
1054 		 */
1055 		is_first_object_locked = VM_OBJECT_TRYWLOCK(fs->first_object);
1056 		if (is_first_object_locked &&
1057 		    fs->object == fs->first_object->backing_object) {
1058 			if (VM_OBJECT_TRYWLOCK(fs->object)) {
1059 				rename_cow = vm_fault_can_cow_rename(fs);
1060 				if (!rename_cow)
1061 					VM_OBJECT_WUNLOCK(fs->object);
1062 			}
1063 		}
1064 	}
1065 
1066 	if (rename_cow) {
1067 		vm_page_assert_xbusied(fs->m);
1068 
1069 		/*
1070 		 * Remove but keep xbusy for replace.  fs->m is moved into
1071 		 * fs->first_object and left busy while fs->first_m is
1072 		 * conditionally freed.
1073 		 */
1074 		vm_page_remove_xbusy(fs->m);
1075 		vm_page_replace(fs->m, fs->first_object, fs->first_pindex,
1076 		    fs->first_m);
1077 		vm_page_dirty(fs->m);
1078 #if VM_NRESERVLEVEL > 0
1079 		/*
1080 		 * Rename the reservation.
1081 		 */
1082 		vm_reserv_rename(fs->m, fs->first_object, fs->object,
1083 		    OFF_TO_IDX(fs->first_object->backing_object_offset));
1084 #endif
1085 		VM_OBJECT_WUNLOCK(fs->object);
1086 		VM_OBJECT_WUNLOCK(fs->first_object);
1087 		fs->first_m = fs->m;
1088 		fs->m = NULL;
1089 		VM_CNT_INC(v_cow_optim);
1090 	} else {
1091 		if (is_first_object_locked)
1092 			VM_OBJECT_WUNLOCK(fs->first_object);
1093 		/*
1094 		 * Oh, well, lets copy it.
1095 		 */
1096 		pmap_copy_page(fs->m, fs->first_m);
1097 		if (fs->wired && (fs->fault_flags & VM_FAULT_WIRE) == 0) {
1098 			vm_page_wire(fs->first_m);
1099 			vm_page_unwire(fs->m, PQ_INACTIVE);
1100 		}
1101 		/*
1102 		 * Save the COW page to be released after pmap_enter is
1103 		 * complete.  The new copy will be marked valid when we're ready
1104 		 * to map it.
1105 		 */
1106 		fs->m_cow = fs->m;
1107 		fs->m = NULL;
1108 
1109 		/*
1110 		 * Typically, the shadow object is either private to this
1111 		 * address space (OBJ_ONEMAPPING) or its pages are read only.
1112 		 * In the highly unusual case where the pages of a shadow object
1113 		 * are read/write shared between this and other address spaces,
1114 		 * we need to ensure that any pmap-level mappings to the
1115 		 * original, copy-on-write page from the backing object are
1116 		 * removed from those other address spaces.
1117 		 *
1118 		 * The flag check is racy, but this is tolerable: if
1119 		 * OBJ_ONEMAPPING is cleared after the check, the busy state
1120 		 * ensures that new mappings of m_cow can't be created.
1121 		 * pmap_enter() will replace an existing mapping in the current
1122 		 * address space.  If OBJ_ONEMAPPING is set after the check,
1123 		 * removing mappings will at worse trigger some unnecessary page
1124 		 * faults.
1125 		 *
1126 		 * In the fs->m shared busy case, the xbusy state of
1127 		 * fs->first_m prevents new mappings of fs->m from
1128 		 * being created because a parallel fault on this
1129 		 * shadow chain should wait for xbusy on fs->first_m.
1130 		 */
1131 		if ((fs->first_object->flags & OBJ_ONEMAPPING) == 0)
1132 			pmap_remove_all(fs->m_cow);
1133 	}
1134 
1135 	vm_object_pip_wakeup(fs->object);
1136 
1137 	/*
1138 	 * Only use the new page below...
1139 	 */
1140 	fs->object = fs->first_object;
1141 	fs->pindex = fs->first_pindex;
1142 	fs->m = fs->first_m;
1143 	VM_CNT_INC(v_cow_faults);
1144 	curthread->td_cow++;
1145 }
1146 
1147 static enum fault_next_status
vm_fault_next(struct faultstate * fs)1148 vm_fault_next(struct faultstate *fs)
1149 {
1150 	vm_object_t next_object;
1151 
1152 	if (fs->object == fs->first_object || !fs->can_read_lock)
1153 		VM_OBJECT_ASSERT_WLOCKED(fs->object);
1154 	else
1155 		VM_OBJECT_ASSERT_LOCKED(fs->object);
1156 
1157 	/*
1158 	 * The requested page does not exist at this object/
1159 	 * offset.  Remove the invalid page from the object,
1160 	 * waking up anyone waiting for it, and continue on to
1161 	 * the next object.  However, if this is the top-level
1162 	 * object, we must leave the busy page in place to
1163 	 * prevent another process from rushing past us, and
1164 	 * inserting the page in that object at the same time
1165 	 * that we are.
1166 	 */
1167 	if (fs->object == fs->first_object) {
1168 		fs->first_m = fs->m;
1169 		fs->m = NULL;
1170 	} else if (fs->m != NULL) {
1171 		if (!vm_fault_object_ensure_wlocked(fs)) {
1172 			fs->can_read_lock = false;
1173 			vm_fault_unlock_and_deallocate(fs);
1174 			return (FAULT_NEXT_RESTART);
1175 		}
1176 		vm_fault_page_free(&fs->m);
1177 	}
1178 
1179 	/*
1180 	 * Move on to the next object.  Lock the next object before
1181 	 * unlocking the current one.
1182 	 */
1183 	next_object = fs->object->backing_object;
1184 	if (next_object == NULL)
1185 		return (FAULT_NEXT_NOOBJ);
1186 	MPASS(fs->first_m != NULL);
1187 	KASSERT(fs->object != next_object, ("object loop %p", next_object));
1188 	if (fs->can_read_lock)
1189 		VM_OBJECT_RLOCK(next_object);
1190 	else
1191 		VM_OBJECT_WLOCK(next_object);
1192 	vm_object_pip_add(next_object, 1);
1193 	if (fs->object != fs->first_object)
1194 		vm_object_pip_wakeup(fs->object);
1195 	fs->pindex += OFF_TO_IDX(fs->object->backing_object_offset);
1196 	VM_OBJECT_UNLOCK(fs->object);
1197 	fs->object = next_object;
1198 
1199 	return (FAULT_NEXT_GOTOBJ);
1200 }
1201 
1202 static void
vm_fault_zerofill(struct faultstate * fs)1203 vm_fault_zerofill(struct faultstate *fs)
1204 {
1205 
1206 	/*
1207 	 * If there's no object left, fill the page in the top
1208 	 * object with zeros.
1209 	 */
1210 	if (vm_fault_might_be_cow(fs)) {
1211 		vm_object_pip_wakeup(fs->object);
1212 		fs->object = fs->first_object;
1213 		fs->pindex = fs->first_pindex;
1214 	}
1215 	MPASS(fs->first_m != NULL);
1216 	MPASS(fs->m == NULL);
1217 	fs->m = fs->first_m;
1218 	fs->first_m = NULL;
1219 
1220 	/*
1221 	 * Zero the page if necessary and mark it valid.
1222 	 */
1223 	if ((fs->m->flags & PG_ZERO) == 0) {
1224 		pmap_zero_page(fs->m);
1225 	} else {
1226 		VM_CNT_INC(v_ozfod);
1227 	}
1228 	VM_CNT_INC(v_zfod);
1229 	vm_page_valid(fs->m);
1230 }
1231 
1232 /*
1233  * Initiate page fault after timeout.  Returns true if caller should
1234  * do vm_waitpfault() after the call.
1235  */
1236 static bool
vm_fault_allocate_oom(struct faultstate * fs)1237 vm_fault_allocate_oom(struct faultstate *fs)
1238 {
1239 	struct timeval now;
1240 
1241 	vm_fault_unlock_and_deallocate(fs);
1242 	if (vm_pfault_oom_attempts < 0)
1243 		return (true);
1244 	if (!fs->oom_started) {
1245 		fs->oom_started = true;
1246 		getmicrotime(&fs->oom_start_time);
1247 		return (true);
1248 	}
1249 
1250 	getmicrotime(&now);
1251 	timevalsub(&now, &fs->oom_start_time);
1252 	if (now.tv_sec < vm_pfault_oom_attempts * vm_pfault_oom_wait)
1253 		return (true);
1254 
1255 	if (bootverbose)
1256 		printf(
1257 	    "proc %d (%s) failed to alloc page on fault, starting OOM\n",
1258 		    curproc->p_pid, curproc->p_comm);
1259 	vm_pageout_oom(VM_OOM_MEM_PF);
1260 	fs->oom_started = false;
1261 	return (false);
1262 }
1263 
1264 /*
1265  * Allocate a page directly or via the object populate method.
1266  */
1267 static enum fault_status
vm_fault_allocate(struct faultstate * fs,struct pctrie_iter * pages)1268 vm_fault_allocate(struct faultstate *fs, struct pctrie_iter *pages)
1269 {
1270 	struct domainset *dset;
1271 	enum fault_status res;
1272 
1273 	if ((fs->object->flags & OBJ_SIZEVNLOCK) != 0) {
1274 		res = vm_fault_lock_vnode(fs, true);
1275 		MPASS(res == FAULT_CONTINUE || res == FAULT_RESTART);
1276 		if (res == FAULT_RESTART)
1277 			return (res);
1278 	}
1279 
1280 	if (fs->pindex >= fs->object->size) {
1281 		vm_fault_unlock_and_deallocate(fs);
1282 		return (FAULT_OUT_OF_BOUNDS);
1283 	}
1284 
1285 	if (fs->object == fs->first_object &&
1286 	    (fs->first_object->flags & OBJ_POPULATE) != 0 &&
1287 	    fs->first_object->shadow_count == 0) {
1288 		res = vm_fault_populate(fs);
1289 		switch (res) {
1290 		case FAULT_SUCCESS:
1291 		case FAULT_FAILURE:
1292 		case FAULT_RESTART:
1293 			vm_fault_unlock_and_deallocate(fs);
1294 			return (res);
1295 		case FAULT_CONTINUE:
1296 			pctrie_iter_reset(pages);
1297 			/*
1298 			 * Pager's populate() method
1299 			 * returned VM_PAGER_BAD.
1300 			 */
1301 			break;
1302 		default:
1303 			panic("inconsistent return codes");
1304 		}
1305 	}
1306 
1307 	/*
1308 	 * Allocate a new page for this object/offset pair.
1309 	 *
1310 	 * If the process has a fatal signal pending, prioritize the allocation
1311 	 * with the expectation that the process will exit shortly and free some
1312 	 * pages.  In particular, the signal may have been posted by the page
1313 	 * daemon in an attempt to resolve an out-of-memory condition.
1314 	 *
1315 	 * The unlocked read of the p_flag is harmless.  At worst, the P_KILLED
1316 	 * might be not observed here, and allocation fails, causing a restart
1317 	 * and new reading of the p_flag.
1318 	 */
1319 	dset = fs->object->domain.dr_policy;
1320 	if (dset == NULL)
1321 		dset = curthread->td_domain.dr_policy;
1322 	if (!vm_page_count_severe_set(&dset->ds_mask) || P_KILLED(curproc)) {
1323 #if VM_NRESERVLEVEL > 0
1324 		vm_object_color(fs->object, atop(fs->vaddr) - fs->pindex);
1325 #endif
1326 		if (!vm_pager_can_alloc_page(fs->object, fs->pindex)) {
1327 			vm_fault_unlock_and_deallocate(fs);
1328 			return (FAULT_FAILURE);
1329 		}
1330 		fs->m = vm_page_alloc_iter(fs->object, fs->pindex,
1331 		    P_KILLED(curproc) ? VM_ALLOC_SYSTEM : 0, pages);
1332 	}
1333 	if (fs->m == NULL) {
1334 		if (vm_fault_allocate_oom(fs))
1335 			vm_waitpfault(dset, vm_pfault_oom_wait * hz);
1336 		return (FAULT_RESTART);
1337 	}
1338 	fs->oom_started = false;
1339 
1340 	return (FAULT_CONTINUE);
1341 }
1342 
1343 /*
1344  * Call the pager to retrieve the page if there is a chance
1345  * that the pager has it, and potentially retrieve additional
1346  * pages at the same time.
1347  */
1348 static enum fault_status
vm_fault_getpages(struct faultstate * fs,int * behindp,int * aheadp)1349 vm_fault_getpages(struct faultstate *fs, int *behindp, int *aheadp)
1350 {
1351 	vm_offset_t e_end, e_start;
1352 	int ahead, behind, cluster_offset, rv;
1353 	enum fault_status status;
1354 	u_char behavior;
1355 
1356 	/*
1357 	 * Prepare for unlocking the map.  Save the map
1358 	 * entry's start and end addresses, which are used to
1359 	 * optimize the size of the pager operation below.
1360 	 * Even if the map entry's addresses change after
1361 	 * unlocking the map, using the saved addresses is
1362 	 * safe.
1363 	 */
1364 	e_start = fs->entry->start;
1365 	e_end = fs->entry->end;
1366 	behavior = vm_map_entry_behavior(fs->entry);
1367 
1368 	/*
1369 	 * If the pager for the current object might have
1370 	 * the page, then determine the number of additional
1371 	 * pages to read and potentially reprioritize
1372 	 * previously read pages for earlier reclamation.
1373 	 * These operations should only be performed once per
1374 	 * page fault.  Even if the current pager doesn't
1375 	 * have the page, the number of additional pages to
1376 	 * read will apply to subsequent objects in the
1377 	 * shadow chain.
1378 	 */
1379 	if (fs->nera == -1 && !P_KILLED(curproc))
1380 		fs->nera = vm_fault_readahead(fs);
1381 
1382 	/*
1383 	 * Release the map lock before locking the vnode or
1384 	 * sleeping in the pager.  (If the current object has
1385 	 * a shadow, then an earlier iteration of this loop
1386 	 * may have already unlocked the map.)
1387 	 */
1388 	vm_fault_unlock_map(fs);
1389 
1390 	status = vm_fault_lock_vnode(fs, false);
1391 	MPASS(status == FAULT_CONTINUE || status == FAULT_RESTART);
1392 	if (status == FAULT_RESTART)
1393 		return (status);
1394 	KASSERT(fs->vp == NULL || !vm_map_is_system(fs->map),
1395 	    ("vm_fault: vnode-backed object mapped by system map"));
1396 
1397 	/*
1398 	 * Page in the requested page and hint the pager,
1399 	 * that it may bring up surrounding pages.
1400 	 */
1401 	if (fs->nera == -1 || behavior == MAP_ENTRY_BEHAV_RANDOM ||
1402 	    P_KILLED(curproc)) {
1403 		behind = 0;
1404 		ahead = 0;
1405 	} else {
1406 		/* Is this a sequential fault? */
1407 		if (fs->nera > 0) {
1408 			behind = 0;
1409 			ahead = fs->nera;
1410 		} else {
1411 			/*
1412 			 * Request a cluster of pages that is
1413 			 * aligned to a VM_FAULT_READ_DEFAULT
1414 			 * page offset boundary within the
1415 			 * object.  Alignment to a page offset
1416 			 * boundary is more likely to coincide
1417 			 * with the underlying file system
1418 			 * block than alignment to a virtual
1419 			 * address boundary.
1420 			 */
1421 			cluster_offset = fs->pindex % VM_FAULT_READ_DEFAULT;
1422 			behind = ulmin(cluster_offset,
1423 			    atop(fs->vaddr - e_start));
1424 			ahead = VM_FAULT_READ_DEFAULT - 1 - cluster_offset;
1425 		}
1426 		ahead = ulmin(ahead, atop(e_end - fs->vaddr) - 1);
1427 	}
1428 	*behindp = behind;
1429 	*aheadp = ahead;
1430 	rv = vm_pager_get_pages(fs->object, &fs->m, 1, behindp, aheadp);
1431 	if (rv == VM_PAGER_OK)
1432 		return (FAULT_HARD);
1433 	if (rv == VM_PAGER_ERROR)
1434 		printf("vm_fault: pager read error, pid %d (%s)\n",
1435 		    curproc->p_pid, curproc->p_comm);
1436 	/*
1437 	 * If an I/O error occurred or the requested page was
1438 	 * outside the range of the pager, clean up and return
1439 	 * an error.
1440 	 */
1441 	if (rv == VM_PAGER_ERROR || rv == VM_PAGER_BAD) {
1442 		VM_OBJECT_WLOCK(fs->object);
1443 		vm_fault_page_free(&fs->m);
1444 		vm_fault_unlock_and_deallocate(fs);
1445 		return (FAULT_OUT_OF_BOUNDS);
1446 	}
1447 	KASSERT(rv == VM_PAGER_FAIL,
1448 	    ("%s: unexpected pager error %d", __func__, rv));
1449 	return (FAULT_CONTINUE);
1450 }
1451 
1452 /*
1453  * Wait/Retry if the page is busy.  We have to do this if the page is
1454  * either exclusive or shared busy because the vm_pager may be using
1455  * read busy for pageouts (and even pageins if it is the vnode pager),
1456  * and we could end up trying to pagein and pageout the same page
1457  * simultaneously.
1458  *
1459  * We allow the busy case on a read fault if the page is valid.  We
1460  * cannot under any circumstances mess around with a shared busied
1461  * page except, perhaps, to pmap it.  This is controlled by the
1462  * VM_ALLOC_SBUSY bit in the allocflags argument.
1463  */
1464 static void
vm_fault_busy_sleep(struct faultstate * fs,int allocflags)1465 vm_fault_busy_sleep(struct faultstate *fs, int allocflags)
1466 {
1467 	/*
1468 	 * Reference the page before unlocking and
1469 	 * sleeping so that the page daemon is less
1470 	 * likely to reclaim it.
1471 	 */
1472 	vm_page_aflag_set(fs->m, PGA_REFERENCED);
1473 	if (vm_fault_might_be_cow(fs)) {
1474 		vm_fault_page_release(&fs->first_m);
1475 		vm_object_pip_wakeup(fs->first_object);
1476 	}
1477 	vm_object_pip_wakeup(fs->object);
1478 	vm_fault_unlock_map(fs);
1479 	if (!vm_page_busy_sleep(fs->m, "vmpfw", allocflags))
1480 		VM_OBJECT_UNLOCK(fs->object);
1481 	VM_CNT_INC(v_intrans);
1482 	vm_object_deallocate(fs->first_object);
1483 }
1484 
1485 /*
1486  * Handle page lookup, populate, allocate, page-in for the current
1487  * object.
1488  *
1489  * The object is locked on entry and will remain locked with a return
1490  * code of FAULT_CONTINUE so that fault may follow the shadow chain.
1491  * Otherwise, the object will be unlocked upon return.
1492  */
1493 static enum fault_status
vm_fault_object(struct faultstate * fs,int * behindp,int * aheadp)1494 vm_fault_object(struct faultstate *fs, int *behindp, int *aheadp)
1495 {
1496 	struct pctrie_iter pages;
1497 	enum fault_status res;
1498 	bool dead;
1499 
1500 	if (fs->object == fs->first_object || !fs->can_read_lock)
1501 		VM_OBJECT_ASSERT_WLOCKED(fs->object);
1502 	else
1503 		VM_OBJECT_ASSERT_LOCKED(fs->object);
1504 
1505 	/*
1506 	 * If the object is marked for imminent termination, we retry
1507 	 * here, since the collapse pass has raced with us.  Otherwise,
1508 	 * if we see terminally dead object, return fail.
1509 	 */
1510 	if ((fs->object->flags & OBJ_DEAD) != 0) {
1511 		dead = fs->object->type == OBJT_DEAD;
1512 		vm_fault_unlock_and_deallocate(fs);
1513 		if (dead)
1514 			return (FAULT_PROTECTION_FAILURE);
1515 		pause("vmf_de", 1);
1516 		return (FAULT_RESTART);
1517 	}
1518 
1519 	/*
1520 	 * See if the page is resident.
1521 	 */
1522 	vm_page_iter_init(&pages, fs->object);
1523 	fs->m = vm_radix_iter_lookup(&pages, fs->pindex);
1524 	if (fs->m != NULL) {
1525 		/*
1526 		 * If the found page is valid, will be either shadowed
1527 		 * or mapped read-only, and will not be renamed for
1528 		 * COW, then busy it in shared mode.  This allows
1529 		 * other faults needing this page to proceed in
1530 		 * parallel.
1531 		 *
1532 		 * Unlocked check for validity, rechecked after busy
1533 		 * is obtained.
1534 		 */
1535 		if (vm_page_all_valid(fs->m) &&
1536 		    /*
1537 		     * No write permissions for the new fs->m mapping,
1538 		     * or the first object has only one mapping, so
1539 		     * other writeable COW mappings of fs->m cannot
1540 		     * appear under us.
1541 		     */
1542 		    (vm_fault_is_read(fs) || vm_fault_might_be_cow(fs)) &&
1543 		    /*
1544 		     * fs->m cannot be renamed from object to
1545 		     * first_object.  These conditions will be
1546 		     * re-checked with proper synchronization in
1547 		     * vm_fault_cow().
1548 		     */
1549 		    (!vm_fault_can_cow_rename(fs) ||
1550 		    fs->object != fs->first_object->backing_object)) {
1551 			if (!vm_page_trysbusy(fs->m)) {
1552 				vm_fault_busy_sleep(fs, VM_ALLOC_SBUSY);
1553 				return (FAULT_RESTART);
1554 			}
1555 
1556 			/*
1557 			 * Now make sure that racily checked
1558 			 * conditions are still valid.
1559 			 */
1560 			if (__predict_true(vm_page_all_valid(fs->m) &&
1561 			    (vm_fault_is_read(fs) ||
1562 			    vm_fault_might_be_cow(fs)))) {
1563 				VM_OBJECT_UNLOCK(fs->object);
1564 				return (FAULT_SOFT);
1565 			}
1566 
1567 			vm_page_sunbusy(fs->m);
1568 		}
1569 
1570 		if (!vm_page_tryxbusy(fs->m)) {
1571 			vm_fault_busy_sleep(fs, 0);
1572 			return (FAULT_RESTART);
1573 		}
1574 
1575 		/*
1576 		 * The page is marked busy for other processes and the
1577 		 * pagedaemon.  If it is still completely valid we are
1578 		 * done.
1579 		 */
1580 		if (vm_page_all_valid(fs->m)) {
1581 			VM_OBJECT_UNLOCK(fs->object);
1582 			return (FAULT_SOFT);
1583 		}
1584 	}
1585 
1586 	/*
1587 	 * Page is not resident.  If the pager might contain the page
1588 	 * or this is the beginning of the search, allocate a new
1589 	 * page.
1590 	 */
1591 	if (fs->m == NULL && (vm_fault_object_needs_getpages(fs->object) ||
1592 	    fs->object == fs->first_object)) {
1593 		if (!vm_fault_object_ensure_wlocked(fs)) {
1594 			fs->can_read_lock = false;
1595 			vm_fault_unlock_and_deallocate(fs);
1596 			return (FAULT_RESTART);
1597 		}
1598 		res = vm_fault_allocate(fs, &pages);
1599 		if (res != FAULT_CONTINUE)
1600 			return (res);
1601 	}
1602 
1603 	/*
1604 	 * Check to see if the pager can possibly satisfy this fault.
1605 	 * If not, skip to the next object without dropping the lock to
1606 	 * preserve atomicity of shadow faults.
1607 	 */
1608 	if (vm_fault_object_needs_getpages(fs->object)) {
1609 		/*
1610 		 * At this point, we have either allocated a new page
1611 		 * or found an existing page that is only partially
1612 		 * valid.
1613 		 *
1614 		 * We hold a reference on the current object and the
1615 		 * page is exclusive busied.  The exclusive busy
1616 		 * prevents simultaneous faults and collapses while
1617 		 * the object lock is dropped.
1618 		 */
1619 		VM_OBJECT_UNLOCK(fs->object);
1620 		res = vm_fault_getpages(fs, behindp, aheadp);
1621 		if (res == FAULT_CONTINUE)
1622 			VM_OBJECT_WLOCK(fs->object);
1623 	} else {
1624 		res = FAULT_CONTINUE;
1625 	}
1626 	return (res);
1627 }
1628 
1629 int
vm_fault(vm_map_t map,vm_offset_t vaddr,vm_prot_t fault_type,int fault_flags,vm_page_t * m_hold)1630 vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
1631     int fault_flags, vm_page_t *m_hold)
1632 {
1633 	struct pctrie_iter pages;
1634 	struct faultstate fs;
1635 	int ahead, behind, faultcount, rv;
1636 	enum fault_status res;
1637 	enum fault_next_status res_next;
1638 	bool hardfault;
1639 
1640 	VM_CNT_INC(v_vm_faults);
1641 
1642 	if ((curthread->td_pflags & TDP_NOFAULTING) != 0)
1643 		return (KERN_PROTECTION_FAILURE);
1644 
1645 	fs.vp = NULL;
1646 	fs.vaddr = vaddr;
1647 	fs.m_hold = m_hold;
1648 	fs.fault_flags = fault_flags;
1649 	fs.map = map;
1650 	fs.lookup_still_valid = false;
1651 	fs.oom_started = false;
1652 	fs.nera = -1;
1653 	fs.can_read_lock = true;
1654 	faultcount = 0;
1655 	hardfault = false;
1656 
1657 RetryFault:
1658 	fs.fault_type = fault_type;
1659 
1660 	/*
1661 	 * Find the backing store object and offset into it to begin the
1662 	 * search.
1663 	 */
1664 	rv = vm_fault_lookup(&fs);
1665 	if (rv != KERN_SUCCESS) {
1666 		if (rv == KERN_RESOURCE_SHORTAGE)
1667 			goto RetryFault;
1668 		return (rv);
1669 	}
1670 
1671 	/*
1672 	 * Try to avoid lock contention on the top-level object through
1673 	 * special-case handling of some types of page faults, specifically,
1674 	 * those that are mapping an existing page from the top-level object.
1675 	 * Under this condition, a read lock on the object suffices, allowing
1676 	 * multiple page faults of a similar type to run in parallel.
1677 	 */
1678 	if (fs.vp == NULL /* avoid locked vnode leak */ &&
1679 	    (fs.entry->eflags & MAP_ENTRY_SPLIT_BOUNDARY_MASK) == 0 &&
1680 	    (fs.fault_flags & (VM_FAULT_WIRE | VM_FAULT_DIRTY)) == 0) {
1681 		res = vm_fault_soft_fast(&fs);
1682 		if (res == FAULT_SUCCESS) {
1683 			VM_OBJECT_ASSERT_UNLOCKED(fs.first_object);
1684 			return (KERN_SUCCESS);
1685 		}
1686 		VM_OBJECT_ASSERT_WLOCKED(fs.first_object);
1687 	} else {
1688 		vm_page_iter_init(&pages, fs.first_object);
1689 		VM_OBJECT_WLOCK(fs.first_object);
1690 	}
1691 
1692 	/*
1693 	 * Make a reference to this object to prevent its disposal while we
1694 	 * are messing with it.  Once we have the reference, the map is free
1695 	 * to be diddled.  Since objects reference their shadows (and copies),
1696 	 * they will stay around as well.
1697 	 *
1698 	 * Bump the paging-in-progress count to prevent size changes (e.g.
1699 	 * truncation operations) during I/O.
1700 	 */
1701 	vm_object_reference_locked(fs.first_object);
1702 	vm_object_pip_add(fs.first_object, 1);
1703 
1704 	fs.m_cow = fs.m = fs.first_m = NULL;
1705 
1706 	/*
1707 	 * Search for the page at object/offset.
1708 	 */
1709 	fs.object = fs.first_object;
1710 	fs.pindex = fs.first_pindex;
1711 
1712 	if ((fs.entry->eflags & MAP_ENTRY_SPLIT_BOUNDARY_MASK) != 0) {
1713 		res = vm_fault_allocate(&fs, &pages);
1714 		switch (res) {
1715 		case FAULT_RESTART:
1716 			goto RetryFault;
1717 		case FAULT_SUCCESS:
1718 			return (KERN_SUCCESS);
1719 		case FAULT_FAILURE:
1720 			return (KERN_FAILURE);
1721 		case FAULT_OUT_OF_BOUNDS:
1722 			return (KERN_OUT_OF_BOUNDS);
1723 		case FAULT_CONTINUE:
1724 			break;
1725 		default:
1726 			panic("vm_fault: Unhandled status %d", res);
1727 		}
1728 	}
1729 
1730 	while (TRUE) {
1731 		KASSERT(fs.m == NULL,
1732 		    ("page still set %p at loop start", fs.m));
1733 
1734 		res = vm_fault_object(&fs, &behind, &ahead);
1735 		switch (res) {
1736 		case FAULT_SOFT:
1737 			goto found;
1738 		case FAULT_HARD:
1739 			faultcount = behind + 1 + ahead;
1740 			hardfault = true;
1741 			goto found;
1742 		case FAULT_RESTART:
1743 			goto RetryFault;
1744 		case FAULT_SUCCESS:
1745 			return (KERN_SUCCESS);
1746 		case FAULT_FAILURE:
1747 			return (KERN_FAILURE);
1748 		case FAULT_OUT_OF_BOUNDS:
1749 			return (KERN_OUT_OF_BOUNDS);
1750 		case FAULT_PROTECTION_FAILURE:
1751 			return (KERN_PROTECTION_FAILURE);
1752 		case FAULT_CONTINUE:
1753 			break;
1754 		default:
1755 			panic("vm_fault: Unhandled status %d", res);
1756 		}
1757 
1758 		/*
1759 		 * The page was not found in the current object.  Try to
1760 		 * traverse into a backing object or zero fill if none is
1761 		 * found.
1762 		 */
1763 		res_next = vm_fault_next(&fs);
1764 		if (res_next == FAULT_NEXT_RESTART)
1765 			goto RetryFault;
1766 		else if (res_next == FAULT_NEXT_GOTOBJ)
1767 			continue;
1768 		MPASS(res_next == FAULT_NEXT_NOOBJ);
1769 		if ((fs.fault_flags & VM_FAULT_NOFILL) != 0) {
1770 			if (fs.first_object == fs.object)
1771 				vm_fault_page_free(&fs.first_m);
1772 			vm_fault_unlock_and_deallocate(&fs);
1773 			return (KERN_OUT_OF_BOUNDS);
1774 		}
1775 		VM_OBJECT_UNLOCK(fs.object);
1776 		vm_fault_zerofill(&fs);
1777 		/* Don't try to prefault neighboring pages. */
1778 		faultcount = 1;
1779 		break;
1780 	}
1781 
1782 found:
1783 	/*
1784 	 * A valid page has been found and busied.  The object lock
1785 	 * must no longer be held if the page was busied.
1786 	 *
1787 	 * Regardless of the busy state of fs.m, fs.first_m is always
1788 	 * exclusively busied after the first iteration of the loop
1789 	 * calling vm_fault_object().  This is an ordering point for
1790 	 * the parallel faults occuring in on the same page.
1791 	 */
1792 	vm_page_assert_busied(fs.m);
1793 	VM_OBJECT_ASSERT_UNLOCKED(fs.object);
1794 
1795 	/*
1796 	 * If the page is being written, but isn't already owned by the
1797 	 * top-level object, we have to copy it into a new page owned by the
1798 	 * top-level object.
1799 	 */
1800 	if (vm_fault_might_be_cow(&fs)) {
1801 		/*
1802 		 * We only really need to copy if we want to write it.
1803 		 */
1804 		if ((fs.fault_type & (VM_PROT_COPY | VM_PROT_WRITE)) != 0) {
1805 			vm_fault_cow(&fs);
1806 			/*
1807 			 * We only try to prefault read-only mappings to the
1808 			 * neighboring pages when this copy-on-write fault is
1809 			 * a hard fault.  In other cases, trying to prefault
1810 			 * is typically wasted effort.
1811 			 */
1812 			if (faultcount == 0)
1813 				faultcount = 1;
1814 
1815 		} else {
1816 			fs.prot &= ~VM_PROT_WRITE;
1817 		}
1818 	}
1819 
1820 	/*
1821 	 * We must verify that the maps have not changed since our last
1822 	 * lookup.
1823 	 */
1824 	if (!fs.lookup_still_valid) {
1825 		rv = vm_fault_relookup(&fs);
1826 		if (rv != KERN_SUCCESS) {
1827 			vm_fault_deallocate(&fs);
1828 			if (rv == KERN_RESTART)
1829 				goto RetryFault;
1830 			return (rv);
1831 		}
1832 	}
1833 	VM_OBJECT_ASSERT_UNLOCKED(fs.object);
1834 
1835 	/*
1836 	 * If the page was filled by a pager, save the virtual address that
1837 	 * should be faulted on next under a sequential access pattern to the
1838 	 * map entry.  A read lock on the map suffices to update this address
1839 	 * safely.
1840 	 */
1841 	if (hardfault)
1842 		fs.entry->next_read = vaddr + ptoa(ahead) + PAGE_SIZE;
1843 
1844 	/*
1845 	 * If the page to be mapped was copied from a backing object, we defer
1846 	 * marking it valid until here, where the fault handler is guaranteed to
1847 	 * succeed.  Otherwise we can end up with a shadowed, mapped page in the
1848 	 * backing object, which violates an invariant of vm_object_collapse()
1849 	 * that shadowed pages are not mapped.
1850 	 */
1851 	if (fs.m_cow != NULL) {
1852 		KASSERT(vm_page_none_valid(fs.m),
1853 		    ("vm_fault: page %p is already valid", fs.m_cow));
1854 		vm_page_valid(fs.m);
1855 	}
1856 
1857 	/*
1858 	 * Page must be completely valid or it is not fit to
1859 	 * map into user space.  vm_pager_get_pages() ensures this.
1860 	 */
1861 	vm_page_assert_busied(fs.m);
1862 	KASSERT(vm_page_all_valid(fs.m),
1863 	    ("vm_fault: page %p partially invalid", fs.m));
1864 
1865 	vm_fault_dirty(&fs, fs.m);
1866 
1867 	/*
1868 	 * Put this page into the physical map.  We had to do the unlock above
1869 	 * because pmap_enter() may sleep.  We don't put the page
1870 	 * back on the active queue until later so that the pageout daemon
1871 	 * won't find it (yet).
1872 	 */
1873 	pmap_enter(fs.map->pmap, vaddr, fs.m, fs.prot,
1874 	    fs.fault_type | (fs.wired ? PMAP_ENTER_WIRED : 0), 0);
1875 	if (faultcount != 1 && (fs.fault_flags & VM_FAULT_WIRE) == 0 &&
1876 	    fs.wired == 0)
1877 		vm_fault_prefault(&fs, vaddr,
1878 		    faultcount > 0 ? behind : PFBAK,
1879 		    faultcount > 0 ? ahead : PFFOR, false);
1880 
1881 	/*
1882 	 * If the page is not wired down, then put it where the pageout daemon
1883 	 * can find it.
1884 	 */
1885 	if ((fs.fault_flags & VM_FAULT_WIRE) != 0)
1886 		vm_page_wire(fs.m);
1887 	else
1888 		vm_page_activate(fs.m);
1889 	if (fs.m_hold != NULL) {
1890 		(*fs.m_hold) = fs.m;
1891 		vm_page_wire(fs.m);
1892 	}
1893 
1894 	KASSERT(fs.first_object == fs.object || vm_page_xbusied(fs.first_m),
1895 	    ("first_m must be xbusy"));
1896 	if (vm_page_xbusied(fs.m))
1897 		vm_page_xunbusy(fs.m);
1898 	else
1899 		vm_page_sunbusy(fs.m);
1900 	fs.m = NULL;
1901 
1902 	/*
1903 	 * Unlock everything, and return
1904 	 */
1905 	vm_fault_deallocate(&fs);
1906 	if (hardfault) {
1907 		VM_CNT_INC(v_io_faults);
1908 		curthread->td_ru.ru_majflt++;
1909 #ifdef RACCT
1910 		if (racct_enable && fs.object->type == OBJT_VNODE) {
1911 			PROC_LOCK(curproc);
1912 			if ((fs.fault_type & (VM_PROT_COPY | VM_PROT_WRITE)) != 0) {
1913 				racct_add_force(curproc, RACCT_WRITEBPS,
1914 				    PAGE_SIZE + behind * PAGE_SIZE);
1915 				racct_add_force(curproc, RACCT_WRITEIOPS, 1);
1916 			} else {
1917 				racct_add_force(curproc, RACCT_READBPS,
1918 				    PAGE_SIZE + ahead * PAGE_SIZE);
1919 				racct_add_force(curproc, RACCT_READIOPS, 1);
1920 			}
1921 			PROC_UNLOCK(curproc);
1922 		}
1923 #endif
1924 	} else
1925 		curthread->td_ru.ru_minflt++;
1926 
1927 	return (KERN_SUCCESS);
1928 }
1929 
1930 /*
1931  * Speed up the reclamation of pages that precede the faulting pindex within
1932  * the first object of the shadow chain.  Essentially, perform the equivalent
1933  * to madvise(..., MADV_DONTNEED) on a large cluster of pages that precedes
1934  * the faulting pindex by the cluster size when the pages read by vm_fault()
1935  * cross a cluster-size boundary.  The cluster size is the greater of the
1936  * smallest superpage size and VM_FAULT_DONTNEED_MIN.
1937  *
1938  * When "fs->first_object" is a shadow object, the pages in the backing object
1939  * that precede the faulting pindex are deactivated by vm_fault().  So, this
1940  * function must only be concerned with pages in the first object.
1941  */
1942 static void
vm_fault_dontneed(const struct faultstate * fs,vm_offset_t vaddr,int ahead)1943 vm_fault_dontneed(const struct faultstate *fs, vm_offset_t vaddr, int ahead)
1944 {
1945 	struct pctrie_iter pages;
1946 	vm_map_entry_t entry;
1947 	vm_object_t first_object;
1948 	vm_offset_t end, start;
1949 	vm_page_t m;
1950 	vm_size_t size;
1951 
1952 	VM_OBJECT_ASSERT_UNLOCKED(fs->object);
1953 	first_object = fs->first_object;
1954 	/* Neither fictitious nor unmanaged pages can be reclaimed. */
1955 	if ((first_object->flags & (OBJ_FICTITIOUS | OBJ_UNMANAGED)) == 0) {
1956 		VM_OBJECT_RLOCK(first_object);
1957 		size = VM_FAULT_DONTNEED_MIN;
1958 		if (MAXPAGESIZES > 1 && size < pagesizes[1])
1959 			size = pagesizes[1];
1960 		end = rounddown2(vaddr, size);
1961 		if (vaddr - end >= size - PAGE_SIZE - ptoa(ahead) &&
1962 		    (entry = fs->entry)->start < end) {
1963 			if (end - entry->start < size)
1964 				start = entry->start;
1965 			else
1966 				start = end - size;
1967 			pmap_advise(fs->map->pmap, start, end, MADV_DONTNEED);
1968 			vm_page_iter_limit_init(&pages, first_object,
1969 			    OFF_TO_IDX(entry->offset) +
1970 			    atop(end - entry->start));
1971 			VM_RADIX_FOREACH_FROM(m, &pages,
1972 			    OFF_TO_IDX(entry->offset) +
1973 			    atop(start - entry->start)) {
1974 				if (!vm_page_all_valid(m) ||
1975 				    vm_page_busied(m))
1976 					continue;
1977 
1978 				/*
1979 				 * Don't clear PGA_REFERENCED, since it would
1980 				 * likely represent a reference by a different
1981 				 * process.
1982 				 *
1983 				 * Typically, at this point, prefetched pages
1984 				 * are still in the inactive queue.  Only
1985 				 * pages that triggered page faults are in the
1986 				 * active queue.  The test for whether the page
1987 				 * is in the inactive queue is racy; in the
1988 				 * worst case we will requeue the page
1989 				 * unnecessarily.
1990 				 */
1991 				if (!vm_page_inactive(m))
1992 					vm_page_deactivate(m);
1993 			}
1994 		}
1995 		VM_OBJECT_RUNLOCK(first_object);
1996 	}
1997 }
1998 
1999 /*
2000  * vm_fault_prefault provides a quick way of clustering
2001  * pagefaults into a processes address space.  It is a "cousin"
2002  * of vm_map_pmap_enter, except it runs at page fault time instead
2003  * of mmap time.
2004  */
2005 static void
vm_fault_prefault(const struct faultstate * fs,vm_offset_t addra,int backward,int forward,bool obj_locked)2006 vm_fault_prefault(const struct faultstate *fs, vm_offset_t addra,
2007     int backward, int forward, bool obj_locked)
2008 {
2009 	pmap_t pmap;
2010 	vm_map_entry_t entry;
2011 	vm_object_t backing_object, lobject;
2012 	vm_offset_t addr, starta;
2013 	vm_pindex_t pindex;
2014 	vm_page_t m;
2015 	vm_prot_t prot;
2016 	int i;
2017 
2018 	pmap = fs->map->pmap;
2019 	if (pmap != vmspace_pmap(curthread->td_proc->p_vmspace))
2020 		return;
2021 
2022 	entry = fs->entry;
2023 
2024 	if (addra < backward * PAGE_SIZE) {
2025 		starta = entry->start;
2026 	} else {
2027 		starta = addra - backward * PAGE_SIZE;
2028 		if (starta < entry->start)
2029 			starta = entry->start;
2030 	}
2031 	prot = entry->protection;
2032 
2033 	/*
2034 	 * If pmap_enter() has enabled write access on a nearby mapping, then
2035 	 * don't attempt promotion, because it will fail.
2036 	 */
2037 	if ((fs->prot & VM_PROT_WRITE) != 0)
2038 		prot |= VM_PROT_NO_PROMOTE;
2039 
2040 	/*
2041 	 * Generate the sequence of virtual addresses that are candidates for
2042 	 * prefaulting in an outward spiral from the faulting virtual address,
2043 	 * "addra".  Specifically, the sequence is "addra - PAGE_SIZE", "addra
2044 	 * + PAGE_SIZE", "addra - 2 * PAGE_SIZE", "addra + 2 * PAGE_SIZE", ...
2045 	 * If the candidate address doesn't have a backing physical page, then
2046 	 * the loop immediately terminates.
2047 	 */
2048 	for (i = 0; i < 2 * imax(backward, forward); i++) {
2049 		addr = addra + ((i >> 1) + 1) * ((i & 1) == 0 ? -PAGE_SIZE :
2050 		    PAGE_SIZE);
2051 		if (addr > addra + forward * PAGE_SIZE)
2052 			addr = 0;
2053 
2054 		if (addr < starta || addr >= entry->end)
2055 			continue;
2056 
2057 		if (!pmap_is_prefaultable(pmap, addr))
2058 			continue;
2059 
2060 		pindex = ((addr - entry->start) + entry->offset) >> PAGE_SHIFT;
2061 		lobject = entry->object.vm_object;
2062 		if (!obj_locked)
2063 			VM_OBJECT_RLOCK(lobject);
2064 		while ((m = vm_page_lookup(lobject, pindex)) == NULL &&
2065 		    !vm_fault_object_needs_getpages(lobject) &&
2066 		    (backing_object = lobject->backing_object) != NULL) {
2067 			KASSERT((lobject->backing_object_offset & PAGE_MASK) ==
2068 			    0, ("vm_fault_prefault: unaligned object offset"));
2069 			pindex += lobject->backing_object_offset >> PAGE_SHIFT;
2070 			VM_OBJECT_RLOCK(backing_object);
2071 			if (!obj_locked || lobject != entry->object.vm_object)
2072 				VM_OBJECT_RUNLOCK(lobject);
2073 			lobject = backing_object;
2074 		}
2075 		if (m == NULL) {
2076 			if (!obj_locked || lobject != entry->object.vm_object)
2077 				VM_OBJECT_RUNLOCK(lobject);
2078 			break;
2079 		}
2080 		if (vm_page_all_valid(m) &&
2081 		    (m->flags & PG_FICTITIOUS) == 0)
2082 			pmap_enter_quick(pmap, addr, m, prot);
2083 		if (!obj_locked || lobject != entry->object.vm_object)
2084 			VM_OBJECT_RUNLOCK(lobject);
2085 	}
2086 }
2087 
2088 /*
2089  * Hold each of the physical pages that are mapped by the specified
2090  * range of virtual addresses, ["addr", "addr" + "len"), if those
2091  * mappings are valid and allow the specified types of access, "prot".
2092  * If all of the implied pages are successfully held, then the number
2093  * of held pages is assigned to *ppages_count, together with pointers
2094  * to those pages in the array "ma". The returned value is zero.
2095  *
2096  * However, if any of the pages cannot be held, an error is returned,
2097  * and no pages are held.
2098  * Error values:
2099  *   ENOMEM - the range is not valid
2100  *   EINVAL - the provided vm_page array is too small to hold all pages
2101  *   EAGAIN - a page was not mapped, and the thread is in nofaulting mode
2102  *   EFAULT - a page with requested permissions cannot be mapped
2103  *            (more detailed result from vm_fault() is lost)
2104  */
2105 int
vm_fault_hold_pages(vm_map_t map,vm_offset_t addr,vm_size_t len,vm_prot_t prot,vm_page_t * ma,int max_count,int * ppages_count)2106 vm_fault_hold_pages(vm_map_t map, vm_offset_t addr, vm_size_t len,
2107     vm_prot_t prot, vm_page_t *ma, int max_count, int *ppages_count)
2108 {
2109 	vm_offset_t end, va;
2110 	vm_page_t *mp;
2111 	int count, error;
2112 	boolean_t pmap_failed;
2113 
2114 	if (len == 0) {
2115 		*ppages_count = 0;
2116 		return (0);
2117 	}
2118 	end = round_page(addr + len);
2119 	addr = trunc_page(addr);
2120 
2121 	if (!vm_map_range_valid(map, addr, end))
2122 		return (ENOMEM);
2123 
2124 	if (atop(end - addr) > max_count)
2125 		return (EINVAL);
2126 	count = atop(end - addr);
2127 
2128 	/*
2129 	 * Most likely, the physical pages are resident in the pmap, so it is
2130 	 * faster to try pmap_extract_and_hold() first.
2131 	 */
2132 	pmap_failed = FALSE;
2133 	for (mp = ma, va = addr; va < end; mp++, va += PAGE_SIZE) {
2134 		*mp = pmap_extract_and_hold(map->pmap, va, prot);
2135 		if (*mp == NULL)
2136 			pmap_failed = TRUE;
2137 		else if ((prot & VM_PROT_WRITE) != 0 &&
2138 		    (*mp)->dirty != VM_PAGE_BITS_ALL) {
2139 			/*
2140 			 * Explicitly dirty the physical page.  Otherwise, the
2141 			 * caller's changes may go unnoticed because they are
2142 			 * performed through an unmanaged mapping or by a DMA
2143 			 * operation.
2144 			 *
2145 			 * The object lock is not held here.
2146 			 * See vm_page_clear_dirty_mask().
2147 			 */
2148 			vm_page_dirty(*mp);
2149 		}
2150 	}
2151 	if (pmap_failed) {
2152 		/*
2153 		 * One or more pages could not be held by the pmap.  Either no
2154 		 * page was mapped at the specified virtual address or that
2155 		 * mapping had insufficient permissions.  Attempt to fault in
2156 		 * and hold these pages.
2157 		 *
2158 		 * If vm_fault_disable_pagefaults() was called,
2159 		 * i.e., TDP_NOFAULTING is set, we must not sleep nor
2160 		 * acquire MD VM locks, which means we must not call
2161 		 * vm_fault().  Some (out of tree) callers mark
2162 		 * too wide a code area with vm_fault_disable_pagefaults()
2163 		 * already, use the VM_PROT_QUICK_NOFAULT flag to request
2164 		 * the proper behaviour explicitly.
2165 		 */
2166 		if ((prot & VM_PROT_QUICK_NOFAULT) != 0 &&
2167 		    (curthread->td_pflags & TDP_NOFAULTING) != 0) {
2168 			error = EAGAIN;
2169 			goto fail;
2170 		}
2171 		for (mp = ma, va = addr; va < end; mp++, va += PAGE_SIZE) {
2172 			if (*mp == NULL && vm_fault(map, va, prot,
2173 			    VM_FAULT_NORMAL, mp) != KERN_SUCCESS) {
2174 				error = EFAULT;
2175 				goto fail;
2176 			}
2177 		}
2178 	}
2179 	*ppages_count = count;
2180 	return (0);
2181 fail:
2182 	for (mp = ma; mp < ma + count; mp++)
2183 		if (*mp != NULL)
2184 			vm_page_unwire(*mp, PQ_INACTIVE);
2185 	return (error);
2186 }
2187 
2188  /*
2189  * Hold each of the physical pages that are mapped by the specified range of
2190  * virtual addresses, ["addr", "addr" + "len"), if those mappings are valid
2191  * and allow the specified types of access, "prot".  If all of the implied
2192  * pages are successfully held, then the number of held pages is returned
2193  * together with pointers to those pages in the array "ma".  However, if any
2194  * of the pages cannot be held, -1 is returned.
2195  */
2196 int
vm_fault_quick_hold_pages(vm_map_t map,vm_offset_t addr,vm_size_t len,vm_prot_t prot,vm_page_t * ma,int max_count)2197 vm_fault_quick_hold_pages(vm_map_t map, vm_offset_t addr, vm_size_t len,
2198     vm_prot_t prot, vm_page_t *ma, int max_count)
2199 {
2200 	int error, pages_count;
2201 
2202 	error = vm_fault_hold_pages(map, addr, len, prot, ma,
2203 	    max_count, &pages_count);
2204 	if (error != 0) {
2205 		if (error == EINVAL)
2206 			panic("vm_fault_quick_hold_pages: count > max_count");
2207 		return (-1);
2208 	}
2209 	return (pages_count);
2210 }
2211 
2212 /*
2213  *	Routine:
2214  *		vm_fault_copy_entry
2215  *	Function:
2216  *		Create new object backing dst_entry with private copy of all
2217  *		underlying pages. When src_entry is equal to dst_entry, function
2218  *		implements COW for wired-down map entry. Otherwise, it forks
2219  *		wired entry into dst_map.
2220  *
2221  *	In/out conditions:
2222  *		The source and destination maps must be locked for write.
2223  *		The source map entry must be wired down (or be a sharing map
2224  *		entry corresponding to a main map entry that is wired down).
2225  */
2226 void
vm_fault_copy_entry(vm_map_t dst_map,vm_map_t src_map __unused,vm_map_entry_t dst_entry,vm_map_entry_t src_entry,vm_ooffset_t * fork_charge)2227 vm_fault_copy_entry(vm_map_t dst_map, vm_map_t src_map __unused,
2228     vm_map_entry_t dst_entry, vm_map_entry_t src_entry,
2229     vm_ooffset_t *fork_charge)
2230 {
2231 	struct pctrie_iter pages;
2232 	vm_object_t backing_object, dst_object, object, src_object;
2233 	vm_pindex_t dst_pindex, pindex, src_pindex;
2234 	vm_prot_t access, prot;
2235 	vm_offset_t vaddr;
2236 	vm_page_t dst_m;
2237 	vm_page_t src_m;
2238 	bool upgrade;
2239 
2240 	upgrade = src_entry == dst_entry;
2241 	KASSERT(upgrade || dst_entry->object.vm_object == NULL,
2242 	    ("vm_fault_copy_entry: vm_object not NULL"));
2243 
2244 	/*
2245 	 * If not an upgrade, then enter the mappings in the pmap as
2246 	 * read and/or execute accesses.  Otherwise, enter them as
2247 	 * write accesses.
2248 	 *
2249 	 * A writeable large page mapping is only created if all of
2250 	 * the constituent small page mappings are modified. Marking
2251 	 * PTEs as modified on inception allows promotion to happen
2252 	 * without taking potentially large number of soft faults.
2253 	 */
2254 	access = prot = dst_entry->protection;
2255 	if (!upgrade)
2256 		access &= ~VM_PROT_WRITE;
2257 
2258 	src_object = src_entry->object.vm_object;
2259 	src_pindex = OFF_TO_IDX(src_entry->offset);
2260 
2261 	if (upgrade && (dst_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) {
2262 		dst_object = src_object;
2263 		vm_object_reference(dst_object);
2264 	} else {
2265 		/*
2266 		 * Create the top-level object for the destination entry.
2267 		 * Doesn't actually shadow anything - we copy the pages
2268 		 * directly.
2269 		 */
2270 		dst_object = vm_object_allocate_anon(atop(dst_entry->end -
2271 		    dst_entry->start), NULL, NULL, 0);
2272 #if VM_NRESERVLEVEL > 0
2273 		dst_object->flags |= OBJ_COLORED;
2274 		dst_object->pg_color = atop(dst_entry->start);
2275 #endif
2276 		dst_object->domain = src_object->domain;
2277 		dst_object->charge = dst_entry->end - dst_entry->start;
2278 
2279 		dst_entry->object.vm_object = dst_object;
2280 		dst_entry->offset = 0;
2281 		dst_entry->eflags &= ~MAP_ENTRY_VN_EXEC;
2282 	}
2283 
2284 	VM_OBJECT_WLOCK(dst_object);
2285 	if (fork_charge != NULL) {
2286 		KASSERT(dst_entry->cred == NULL,
2287 		    ("vm_fault_copy_entry: leaked swp charge"));
2288 		dst_object->cred = curthread->td_ucred;
2289 		crhold(dst_object->cred);
2290 		*fork_charge += dst_object->charge;
2291 	} else if ((dst_object->flags & OBJ_SWAP) != 0 &&
2292 	    dst_object->cred == NULL) {
2293 		KASSERT(dst_entry->cred != NULL, ("no cred for entry %p",
2294 		    dst_entry));
2295 		dst_object->cred = dst_entry->cred;
2296 		dst_entry->cred = NULL;
2297 	}
2298 
2299 	/*
2300 	 * Loop through all of the virtual pages within the entry's
2301 	 * range, copying each page from the source object to the
2302 	 * destination object.  Since the source is wired, those pages
2303 	 * must exist.  In contrast, the destination is pageable.
2304 	 * Since the destination object doesn't share any backing storage
2305 	 * with the source object, all of its pages must be dirtied,
2306 	 * regardless of whether they can be written.
2307 	 */
2308 	vm_page_iter_init(&pages, dst_object);
2309 	for (vaddr = dst_entry->start, dst_pindex = 0;
2310 	    vaddr < dst_entry->end;
2311 	    vaddr += PAGE_SIZE, dst_pindex++) {
2312 again:
2313 		/*
2314 		 * Find the page in the source object, and copy it in.
2315 		 * Because the source is wired down, the page will be
2316 		 * in memory.
2317 		 */
2318 		if (src_object != dst_object)
2319 			VM_OBJECT_RLOCK(src_object);
2320 		object = src_object;
2321 		pindex = src_pindex + dst_pindex;
2322 		while ((src_m = vm_page_lookup(object, pindex)) == NULL &&
2323 		    (backing_object = object->backing_object) != NULL) {
2324 			/*
2325 			 * Unless the source mapping is read-only or
2326 			 * it is presently being upgraded from
2327 			 * read-only, the first object in the shadow
2328 			 * chain should provide all of the pages.  In
2329 			 * other words, this loop body should never be
2330 			 * executed when the source mapping is already
2331 			 * read/write.
2332 			 */
2333 			KASSERT((src_entry->protection & VM_PROT_WRITE) == 0 ||
2334 			    upgrade,
2335 			    ("vm_fault_copy_entry: main object missing page"));
2336 
2337 			VM_OBJECT_RLOCK(backing_object);
2338 			pindex += OFF_TO_IDX(object->backing_object_offset);
2339 			if (object != dst_object)
2340 				VM_OBJECT_RUNLOCK(object);
2341 			object = backing_object;
2342 		}
2343 		KASSERT(src_m != NULL, ("vm_fault_copy_entry: page missing"));
2344 
2345 		if (object != dst_object) {
2346 			/*
2347 			 * Allocate a page in the destination object.
2348 			 */
2349 			pindex = (src_object == dst_object ? src_pindex : 0) +
2350 			    dst_pindex;
2351 			dst_m = vm_page_alloc_iter(dst_object, pindex,
2352 			    VM_ALLOC_NORMAL, &pages);
2353 			if (dst_m == NULL) {
2354 				VM_OBJECT_WUNLOCK(dst_object);
2355 				VM_OBJECT_RUNLOCK(object);
2356 				vm_wait(dst_object);
2357 				VM_OBJECT_WLOCK(dst_object);
2358 				pctrie_iter_reset(&pages);
2359 				goto again;
2360 			}
2361 
2362 			/*
2363 			 * See the comment in vm_fault_cow().
2364 			 */
2365 			if (src_object == dst_object &&
2366 			    (object->flags & OBJ_ONEMAPPING) == 0)
2367 				pmap_remove_all(src_m);
2368 			pmap_copy_page(src_m, dst_m);
2369 
2370 			/*
2371 			 * The object lock does not guarantee that "src_m" will
2372 			 * transition from invalid to valid, but it does ensure
2373 			 * that "src_m" will not transition from valid to
2374 			 * invalid.
2375 			 */
2376 			dst_m->dirty = dst_m->valid = src_m->valid;
2377 			VM_OBJECT_RUNLOCK(object);
2378 		} else {
2379 			dst_m = src_m;
2380 			if (vm_page_busy_acquire(
2381 			    dst_m, VM_ALLOC_WAITFAIL) == 0) {
2382 				pctrie_iter_reset(&pages);
2383 				goto again;
2384 			}
2385 			if (dst_m->pindex >= dst_object->size) {
2386 				/*
2387 				 * We are upgrading.  Index can occur
2388 				 * out of bounds if the object type is
2389 				 * vnode and the file was truncated.
2390 				 */
2391 				vm_page_xunbusy(dst_m);
2392 				break;
2393 			}
2394 		}
2395 
2396 		/*
2397 		 * Enter it in the pmap. If a wired, copy-on-write
2398 		 * mapping is being replaced by a write-enabled
2399 		 * mapping, then wire that new mapping.
2400 		 *
2401 		 * The page can be invalid if the user called
2402 		 * msync(MS_INVALIDATE) or truncated the backing vnode
2403 		 * or shared memory object.  In this case, do not
2404 		 * insert it into pmap, but still do the copy so that
2405 		 * all copies of the wired map entry have similar
2406 		 * backing pages.
2407 		 */
2408 		if (vm_page_all_valid(dst_m)) {
2409 			VM_OBJECT_WUNLOCK(dst_object);
2410 			pmap_enter(dst_map->pmap, vaddr, dst_m, prot,
2411 			    access | (upgrade ? PMAP_ENTER_WIRED : 0), 0);
2412 			VM_OBJECT_WLOCK(dst_object);
2413 		}
2414 
2415 		/*
2416 		 * Mark it no longer busy, and put it on the active list.
2417 		 */
2418 		if (upgrade) {
2419 			if (src_m != dst_m) {
2420 				vm_page_unwire(src_m, PQ_INACTIVE);
2421 				vm_page_wire(dst_m);
2422 			} else {
2423 				KASSERT(vm_page_wired(dst_m),
2424 				    ("dst_m %p is not wired", dst_m));
2425 			}
2426 		} else {
2427 			vm_page_activate(dst_m);
2428 		}
2429 		vm_page_xunbusy(dst_m);
2430 	}
2431 	VM_OBJECT_WUNLOCK(dst_object);
2432 	if (upgrade) {
2433 		dst_entry->eflags &= ~(MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY);
2434 		vm_object_deallocate(src_object);
2435 	}
2436 }
2437 
2438 /*
2439  * Block entry into the machine-independent layer's page fault handler by
2440  * the calling thread.  Subsequent calls to vm_fault() by that thread will
2441  * return KERN_PROTECTION_FAILURE.  Enable machine-dependent handling of
2442  * spurious page faults.
2443  */
2444 int
vm_fault_disable_pagefaults(void)2445 vm_fault_disable_pagefaults(void)
2446 {
2447 
2448 	return (curthread_pflags_set(TDP_NOFAULTING | TDP_RESETSPUR));
2449 }
2450 
2451 void
vm_fault_enable_pagefaults(int save)2452 vm_fault_enable_pagefaults(int save)
2453 {
2454 
2455 	curthread_pflags_restore(save);
2456 }
2457