xref: /freebsd-12.1/sys/vm/vm_fault.c (revision 736e60c9)
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  *	from: @(#)vm_fault.c	8.4 (Berkeley) 1/12/94
44  *
45  *
46  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
47  * All rights reserved.
48  *
49  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
50  *
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.
56  *
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.
60  *
61  * Carnegie Mellon requests users of this software to return to
62  *
63  *  Software Distribution Coordinator  or  [email protected]
64  *  School of Computer Science
65  *  Carnegie Mellon University
66  *  Pittsburgh PA 15213-3890
67  *
68  * any improvements or extensions that they make and grant Carnegie the
69  * rights to redistribute these changes.
70  */
71 
72 /*
73  *	Page fault handling module.
74  */
75 
76 #include <sys/cdefs.h>
77 __FBSDID("$FreeBSD$");
78 
79 #include "opt_ktrace.h"
80 #include "opt_vm.h"
81 
82 #include <sys/param.h>
83 #include <sys/systm.h>
84 #include <sys/kernel.h>
85 #include <sys/lock.h>
86 #include <sys/mman.h>
87 #include <sys/proc.h>
88 #include <sys/racct.h>
89 #include <sys/resourcevar.h>
90 #include <sys/rwlock.h>
91 #include <sys/sysctl.h>
92 #include <sys/vmmeter.h>
93 #include <sys/vnode.h>
94 #ifdef KTRACE
95 #include <sys/ktrace.h>
96 #endif
97 
98 #include <vm/vm.h>
99 #include <vm/vm_param.h>
100 #include <vm/pmap.h>
101 #include <vm/vm_map.h>
102 #include <vm/vm_object.h>
103 #include <vm/vm_page.h>
104 #include <vm/vm_pageout.h>
105 #include <vm/vm_kern.h>
106 #include <vm/vm_pager.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 #define	VM_FAULT_READ_MAX	(1 + VM_FAULT_READ_AHEAD_MAX)
115 
116 #define	VM_FAULT_DONTNEED_MIN	1048576
117 
118 struct faultstate {
119 	vm_page_t m;
120 	vm_object_t object;
121 	vm_pindex_t pindex;
122 	vm_page_t first_m;
123 	vm_object_t	first_object;
124 	vm_pindex_t first_pindex;
125 	vm_map_t map;
126 	vm_map_entry_t entry;
127 	int map_generation;
128 	bool lookup_still_valid;
129 	struct vnode *vp;
130 };
131 
132 static void vm_fault_dontneed(const struct faultstate *fs, vm_offset_t vaddr,
133 	    int ahead);
134 static void vm_fault_prefault(const struct faultstate *fs, vm_offset_t addra,
135 	    int backward, int forward, bool obj_locked);
136 
137 static int vm_pfault_oom_attempts = 3;
138 SYSCTL_INT(_vm, OID_AUTO, pfault_oom_attempts, CTLFLAG_RWTUN,
139     &vm_pfault_oom_attempts, 0,
140     "Number of page allocation attempts in page fault handler before it "
141     "triggers OOM handling");
142 
143 static int vm_pfault_oom_wait = 10;
144 SYSCTL_INT(_vm, OID_AUTO, pfault_oom_wait, CTLFLAG_RWTUN,
145     &vm_pfault_oom_wait, 0,
146     "Number of seconds to wait for free pages before retrying "
147     "the page fault handler");
148 
149 static inline void
release_page(struct faultstate * fs)150 release_page(struct faultstate *fs)
151 {
152 
153 	vm_page_xunbusy(fs->m);
154 	vm_page_lock(fs->m);
155 	vm_page_deactivate(fs->m);
156 	vm_page_unlock(fs->m);
157 	fs->m = NULL;
158 }
159 
160 static inline void
unlock_map(struct faultstate * fs)161 unlock_map(struct faultstate *fs)
162 {
163 
164 	if (fs->lookup_still_valid) {
165 		vm_map_lookup_done(fs->map, fs->entry);
166 		fs->lookup_still_valid = false;
167 	}
168 }
169 
170 static void
unlock_vp(struct faultstate * fs)171 unlock_vp(struct faultstate *fs)
172 {
173 
174 	if (fs->vp != NULL) {
175 		vput(fs->vp);
176 		fs->vp = NULL;
177 	}
178 }
179 
180 static void
unlock_and_deallocate(struct faultstate * fs)181 unlock_and_deallocate(struct faultstate *fs)
182 {
183 
184 	vm_object_pip_wakeup(fs->object);
185 	VM_OBJECT_WUNLOCK(fs->object);
186 	if (fs->object != fs->first_object) {
187 		VM_OBJECT_WLOCK(fs->first_object);
188 		vm_page_lock(fs->first_m);
189 		vm_page_free(fs->first_m);
190 		vm_page_unlock(fs->first_m);
191 		vm_object_pip_wakeup(fs->first_object);
192 		VM_OBJECT_WUNLOCK(fs->first_object);
193 		fs->first_m = NULL;
194 	}
195 	vm_object_deallocate(fs->first_object);
196 	unlock_map(fs);
197 	unlock_vp(fs);
198 }
199 
200 static void
vm_fault_dirty(vm_map_entry_t entry,vm_page_t m,vm_prot_t prot,vm_prot_t fault_type,int fault_flags,bool set_wd)201 vm_fault_dirty(vm_map_entry_t entry, vm_page_t m, vm_prot_t prot,
202     vm_prot_t fault_type, int fault_flags, bool set_wd)
203 {
204 	bool need_dirty;
205 
206 	if (((prot & VM_PROT_WRITE) == 0 &&
207 	    (fault_flags & VM_FAULT_DIRTY) == 0) ||
208 	    (m->oflags & VPO_UNMANAGED) != 0)
209 		return;
210 
211 	VM_OBJECT_ASSERT_LOCKED(m->object);
212 
213 	need_dirty = ((fault_type & VM_PROT_WRITE) != 0 &&
214 	    (fault_flags & VM_FAULT_WIRE) == 0) ||
215 	    (fault_flags & VM_FAULT_DIRTY) != 0;
216 
217 	if (set_wd)
218 		vm_object_set_writeable_dirty(m->object);
219 	else
220 		/*
221 		 * If two callers of vm_fault_dirty() with set_wd ==
222 		 * FALSE, one for the map entry with MAP_ENTRY_NOSYNC
223 		 * flag set, other with flag clear, race, it is
224 		 * possible for the no-NOSYNC thread to see m->dirty
225 		 * != 0 and not clear VPO_NOSYNC.  Take vm_page lock
226 		 * around manipulation of VPO_NOSYNC and
227 		 * vm_page_dirty() call, to avoid the race and keep
228 		 * m->oflags consistent.
229 		 */
230 		vm_page_lock(m);
231 
232 	/*
233 	 * If this is a NOSYNC mmap we do not want to set VPO_NOSYNC
234 	 * if the page is already dirty to prevent data written with
235 	 * the expectation of being synced from not being synced.
236 	 * Likewise if this entry does not request NOSYNC then make
237 	 * sure the page isn't marked NOSYNC.  Applications sharing
238 	 * data should use the same flags to avoid ping ponging.
239 	 */
240 	if ((entry->eflags & MAP_ENTRY_NOSYNC) != 0) {
241 		if (m->dirty == 0) {
242 			m->oflags |= VPO_NOSYNC;
243 		}
244 	} else {
245 		m->oflags &= ~VPO_NOSYNC;
246 	}
247 
248 	/*
249 	 * If the fault is a write, we know that this page is being
250 	 * written NOW so dirty it explicitly to save on
251 	 * pmap_is_modified() calls later.
252 	 *
253 	 * Also, since the page is now dirty, we can possibly tell
254 	 * the pager to release any swap backing the page.  Calling
255 	 * the pager requires a write lock on the object.
256 	 */
257 	if (need_dirty)
258 		vm_page_dirty(m);
259 	if (!set_wd)
260 		vm_page_unlock(m);
261 	else if (need_dirty)
262 		vm_pager_page_unswapped(m);
263 }
264 
265 static void
vm_fault_fill_hold(vm_page_t * m_hold,vm_page_t m)266 vm_fault_fill_hold(vm_page_t *m_hold, vm_page_t m)
267 {
268 
269 	if (m_hold != NULL) {
270 		*m_hold = m;
271 		vm_page_lock(m);
272 		vm_page_hold(m);
273 		vm_page_unlock(m);
274 	}
275 }
276 
277 /*
278  * Unlocks fs.first_object and fs.map on success.
279  */
280 static int
vm_fault_soft_fast(struct faultstate * fs,vm_offset_t vaddr,vm_prot_t prot,int fault_type,int fault_flags,boolean_t wired,vm_page_t * m_hold)281 vm_fault_soft_fast(struct faultstate *fs, vm_offset_t vaddr, vm_prot_t prot,
282     int fault_type, int fault_flags, boolean_t wired, vm_page_t *m_hold)
283 {
284 	vm_page_t m, m_map;
285 #if (defined(__aarch64__) || defined(__amd64__) || (defined(__arm__) && \
286     __ARM_ARCH >= 6) || defined(__i386__) || defined(__riscv)) && \
287     VM_NRESERVLEVEL > 0
288 	vm_page_t m_super;
289 	int flags;
290 #endif
291 	int psind, rv;
292 
293 	MPASS(fs->vp == NULL);
294 	m = vm_page_lookup(fs->first_object, fs->first_pindex);
295 	/* A busy page can be mapped for read|execute access. */
296 	if (m == NULL || ((prot & VM_PROT_WRITE) != 0 &&
297 	    vm_page_busied(m)) || m->valid != VM_PAGE_BITS_ALL)
298 		return (KERN_FAILURE);
299 	m_map = m;
300 	psind = 0;
301 #if (defined(__aarch64__) || defined(__amd64__) || (defined(__arm__) && \
302     __ARM_ARCH >= 6) || defined(__i386__) || defined(__riscv)) && \
303     VM_NRESERVLEVEL > 0
304 	if ((m->flags & PG_FICTITIOUS) == 0 &&
305 	    (m_super = vm_reserv_to_superpage(m)) != NULL &&
306 	    rounddown2(vaddr, pagesizes[m_super->psind]) >= fs->entry->start &&
307 	    roundup2(vaddr + 1, pagesizes[m_super->psind]) <= fs->entry->end &&
308 	    (vaddr & (pagesizes[m_super->psind] - 1)) == (VM_PAGE_TO_PHYS(m) &
309 	    (pagesizes[m_super->psind] - 1)) &&
310 	    pmap_ps_enabled(fs->map->pmap)) {
311 		flags = PS_ALL_VALID;
312 		if ((prot & VM_PROT_WRITE) != 0) {
313 			/*
314 			 * Create a superpage mapping allowing write access
315 			 * only if none of the constituent pages are busy and
316 			 * all of them are already dirty (except possibly for
317 			 * the page that was faulted on).
318 			 */
319 			flags |= PS_NONE_BUSY;
320 			if ((fs->first_object->flags & OBJ_UNMANAGED) == 0)
321 				flags |= PS_ALL_DIRTY;
322 		}
323 		if (vm_page_ps_test(m_super, flags, m)) {
324 			m_map = m_super;
325 			psind = m_super->psind;
326 			vaddr = rounddown2(vaddr, pagesizes[psind]);
327 			/* Preset the modified bit for dirty superpages. */
328 			if ((flags & PS_ALL_DIRTY) != 0)
329 				fault_type |= VM_PROT_WRITE;
330 		}
331 	}
332 #endif
333 	rv = pmap_enter(fs->map->pmap, vaddr, m_map, prot, fault_type |
334 	    PMAP_ENTER_NOSLEEP | (wired ? PMAP_ENTER_WIRED : 0), psind);
335 	if (rv != KERN_SUCCESS)
336 		return (rv);
337 	vm_fault_fill_hold(m_hold, m);
338 	vm_fault_dirty(fs->entry, m, prot, fault_type, fault_flags, false);
339 	if (psind == 0 && !wired)
340 		vm_fault_prefault(fs, vaddr, PFBAK, PFFOR, true);
341 	VM_OBJECT_RUNLOCK(fs->first_object);
342 	vm_map_lookup_done(fs->map, fs->entry);
343 	curthread->td_ru.ru_minflt++;
344 	return (KERN_SUCCESS);
345 }
346 
347 static void
vm_fault_restore_map_lock(struct faultstate * fs)348 vm_fault_restore_map_lock(struct faultstate *fs)
349 {
350 
351 	VM_OBJECT_ASSERT_WLOCKED(fs->first_object);
352 	MPASS(fs->first_object->paging_in_progress > 0);
353 
354 	if (!vm_map_trylock_read(fs->map)) {
355 		VM_OBJECT_WUNLOCK(fs->first_object);
356 		vm_map_lock_read(fs->map);
357 		VM_OBJECT_WLOCK(fs->first_object);
358 	}
359 	fs->lookup_still_valid = true;
360 }
361 
362 static void
vm_fault_populate_check_page(vm_page_t m)363 vm_fault_populate_check_page(vm_page_t m)
364 {
365 
366 	/*
367 	 * Check each page to ensure that the pager is obeying the
368 	 * interface: the page must be installed in the object, fully
369 	 * valid, and exclusively busied.
370 	 */
371 	MPASS(m != NULL);
372 	MPASS(m->valid == VM_PAGE_BITS_ALL);
373 	MPASS(vm_page_xbusied(m));
374 }
375 
376 static void
vm_fault_populate_cleanup(vm_object_t object,vm_pindex_t first,vm_pindex_t last)377 vm_fault_populate_cleanup(vm_object_t object, vm_pindex_t first,
378     vm_pindex_t last)
379 {
380 	vm_page_t m;
381 	vm_pindex_t pidx;
382 
383 	VM_OBJECT_ASSERT_WLOCKED(object);
384 	MPASS(first <= last);
385 	for (pidx = first, m = vm_page_lookup(object, pidx);
386 	    pidx <= last; pidx++, m = vm_page_next(m)) {
387 		vm_fault_populate_check_page(m);
388 		vm_page_lock(m);
389 		vm_page_deactivate(m);
390 		vm_page_unlock(m);
391 		vm_page_xunbusy(m);
392 	}
393 }
394 
395 static int
vm_fault_populate(struct faultstate * fs,vm_prot_t prot,int fault_type,int fault_flags,boolean_t wired,vm_page_t * m_hold)396 vm_fault_populate(struct faultstate *fs, vm_prot_t prot, int fault_type,
397     int fault_flags, boolean_t wired, vm_page_t *m_hold)
398 {
399 	struct mtx *m_mtx;
400 	vm_offset_t vaddr;
401 	vm_page_t m;
402 	vm_pindex_t map_first, map_last, pager_first, pager_last, pidx;
403 	int i, npages, psind, rv;
404 
405 	MPASS(fs->object == fs->first_object);
406 	VM_OBJECT_ASSERT_WLOCKED(fs->first_object);
407 	MPASS(fs->first_object->paging_in_progress > 0);
408 	MPASS(fs->first_object->backing_object == NULL);
409 	MPASS(fs->lookup_still_valid);
410 
411 	pager_first = OFF_TO_IDX(fs->entry->offset);
412 	pager_last = pager_first + atop(fs->entry->end - fs->entry->start) - 1;
413 	unlock_map(fs);
414 	unlock_vp(fs);
415 
416 	/*
417 	 * Call the pager (driver) populate() method.
418 	 *
419 	 * There is no guarantee that the method will be called again
420 	 * if the current fault is for read, and a future fault is
421 	 * for write.  Report the entry's maximum allowed protection
422 	 * to the driver.
423 	 */
424 	rv = vm_pager_populate(fs->first_object, fs->first_pindex,
425 	    fault_type, fs->entry->max_protection, &pager_first, &pager_last);
426 
427 	VM_OBJECT_ASSERT_WLOCKED(fs->first_object);
428 	if (rv == VM_PAGER_BAD) {
429 		/*
430 		 * VM_PAGER_BAD is the backdoor for a pager to request
431 		 * normal fault handling.
432 		 */
433 		vm_fault_restore_map_lock(fs);
434 		if (fs->map->timestamp != fs->map_generation)
435 			return (KERN_RESOURCE_SHORTAGE); /* RetryFault */
436 		return (KERN_NOT_RECEIVER);
437 	}
438 	if (rv != VM_PAGER_OK)
439 		return (KERN_FAILURE); /* AKA SIGSEGV */
440 
441 	/* Ensure that the driver is obeying the interface. */
442 	MPASS(pager_first <= pager_last);
443 	MPASS(fs->first_pindex <= pager_last);
444 	MPASS(fs->first_pindex >= pager_first);
445 	MPASS(pager_last < fs->first_object->size);
446 
447 	vm_fault_restore_map_lock(fs);
448 	if (fs->map->timestamp != fs->map_generation) {
449 		vm_fault_populate_cleanup(fs->first_object, pager_first,
450 		    pager_last);
451 		return (KERN_RESOURCE_SHORTAGE); /* RetryFault */
452 	}
453 
454 	/*
455 	 * The map is unchanged after our last unlock.  Process the fault.
456 	 *
457 	 * The range [pager_first, pager_last] that is given to the
458 	 * pager is only a hint.  The pager may populate any range
459 	 * within the object that includes the requested page index.
460 	 * In case the pager expanded the range, clip it to fit into
461 	 * the map entry.
462 	 */
463 	map_first = OFF_TO_IDX(fs->entry->offset);
464 	if (map_first > pager_first) {
465 		vm_fault_populate_cleanup(fs->first_object, pager_first,
466 		    map_first - 1);
467 		pager_first = map_first;
468 	}
469 	map_last = map_first + atop(fs->entry->end - fs->entry->start) - 1;
470 	if (map_last < pager_last) {
471 		vm_fault_populate_cleanup(fs->first_object, map_last + 1,
472 		    pager_last);
473 		pager_last = map_last;
474 	}
475 	for (pidx = pager_first, m = vm_page_lookup(fs->first_object, pidx);
476 	    pidx <= pager_last;
477 	    pidx += npages, m = vm_page_next(&m[npages - 1])) {
478 		vaddr = fs->entry->start + IDX_TO_OFF(pidx) - fs->entry->offset;
479 #if defined(__aarch64__) || defined(__amd64__) || (defined(__arm__) && \
480     __ARM_ARCH >= 6) || defined(__i386__) || defined(__riscv)
481 		psind = m->psind;
482 		if (psind > 0 && ((vaddr & (pagesizes[psind] - 1)) != 0 ||
483 		    pidx + OFF_TO_IDX(pagesizes[psind]) - 1 > pager_last ||
484 		    !pmap_ps_enabled(fs->map->pmap)))
485 			psind = 0;
486 #else
487 		psind = 0;
488 #endif
489 		npages = atop(pagesizes[psind]);
490 		for (i = 0; i < npages; i++) {
491 			vm_fault_populate_check_page(&m[i]);
492 			vm_fault_dirty(fs->entry, &m[i], prot, fault_type,
493 			    fault_flags, true);
494 		}
495 		VM_OBJECT_WUNLOCK(fs->first_object);
496 		rv = pmap_enter(fs->map->pmap, vaddr, m, prot, fault_type |
497 		    (wired ? PMAP_ENTER_WIRED : 0), psind);
498 #if defined(__amd64__)
499 		if (psind > 0 && rv == KERN_FAILURE) {
500 			for (i = 0; i < npages; i++) {
501 				rv = pmap_enter(fs->map->pmap, vaddr + ptoa(i),
502 				    &m[i], prot, fault_type |
503 				    (wired ? PMAP_ENTER_WIRED : 0), 0);
504 				MPASS(rv == KERN_SUCCESS);
505 			}
506 		}
507 #else
508 		MPASS(rv == KERN_SUCCESS);
509 #endif
510 		VM_OBJECT_WLOCK(fs->first_object);
511 		m_mtx = NULL;
512 		for (i = 0; i < npages; i++) {
513 			vm_page_change_lock(&m[i], &m_mtx);
514 			if ((fault_flags & VM_FAULT_WIRE) != 0)
515 				vm_page_wire(&m[i]);
516 			else
517 				vm_page_activate(&m[i]);
518 			if (m_hold != NULL && m[i].pindex == fs->first_pindex) {
519 				*m_hold = &m[i];
520 				vm_page_hold(&m[i]);
521 			}
522 			vm_page_xunbusy_maybelocked(&m[i]);
523 		}
524 		if (m_mtx != NULL)
525 			mtx_unlock(m_mtx);
526 	}
527 	curthread->td_ru.ru_majflt++;
528 	return (KERN_SUCCESS);
529 }
530 
531 /*
532  *	vm_fault:
533  *
534  *	Handle a page fault occurring at the given address,
535  *	requiring the given permissions, in the map specified.
536  *	If successful, the page is inserted into the
537  *	associated physical map.
538  *
539  *	NOTE: the given address should be truncated to the
540  *	proper page address.
541  *
542  *	KERN_SUCCESS is returned if the page fault is handled; otherwise,
543  *	a standard error specifying why the fault is fatal is returned.
544  *
545  *	The map in question must be referenced, and remains so.
546  *	Caller may hold no locks.
547  */
548 int
vm_fault(vm_map_t map,vm_offset_t vaddr,vm_prot_t fault_type,int fault_flags)549 vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
550     int fault_flags)
551 {
552 	struct thread *td;
553 	int result;
554 
555 	td = curthread;
556 	if ((td->td_pflags & TDP_NOFAULTING) != 0)
557 		return (KERN_PROTECTION_FAILURE);
558 #ifdef KTRACE
559 	if (map != kernel_map && KTRPOINT(td, KTR_FAULT))
560 		ktrfault(vaddr, fault_type);
561 #endif
562 	result = vm_fault_hold(map, trunc_page(vaddr), fault_type, fault_flags,
563 	    NULL);
564 #ifdef KTRACE
565 	if (map != kernel_map && KTRPOINT(td, KTR_FAULTEND))
566 		ktrfaultend(result);
567 #endif
568 	return (result);
569 }
570 
571 int
vm_fault_hold(vm_map_t map,vm_offset_t vaddr,vm_prot_t fault_type,int fault_flags,vm_page_t * m_hold)572 vm_fault_hold(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
573     int fault_flags, vm_page_t *m_hold)
574 {
575 	struct faultstate fs;
576 	struct vnode *vp;
577 	struct domainset *dset;
578 	vm_object_t next_object, retry_object;
579 	vm_offset_t e_end, e_start;
580 	vm_pindex_t retry_pindex;
581 	vm_prot_t prot, retry_prot;
582 	int ahead, alloc_req, behind, cluster_offset, error, era, faultcount;
583 	int locked, nera, oom, result, rv;
584 	u_char behavior;
585 	boolean_t wired;	/* Passed by reference. */
586 	bool dead, hardfault, is_first_object_locked;
587 
588 	VM_CNT_INC(v_vm_faults);
589 	fs.vp = NULL;
590 	faultcount = 0;
591 	nera = -1;
592 	hardfault = false;
593 
594 RetryFault:
595 	oom = 0;
596 RetryFault_oom:
597 
598 	/*
599 	 * Find the backing store object and offset into it to begin the
600 	 * search.
601 	 */
602 	fs.map = map;
603 	result = vm_map_lookup(&fs.map, vaddr, fault_type |
604 	    VM_PROT_FAULT_LOOKUP, &fs.entry, &fs.first_object,
605 	    &fs.first_pindex, &prot, &wired);
606 	if (result != KERN_SUCCESS) {
607 		unlock_vp(&fs);
608 		return (result);
609 	}
610 
611 	fs.map_generation = fs.map->timestamp;
612 
613 	if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
614 		panic("%s: fault on nofault entry, addr: %#lx",
615 		    __func__, (u_long)vaddr);
616 	}
617 
618 	if (fs.entry->eflags & MAP_ENTRY_IN_TRANSITION &&
619 	    fs.entry->wiring_thread != curthread) {
620 		vm_map_unlock_read(fs.map);
621 		vm_map_lock(fs.map);
622 		if (vm_map_lookup_entry(fs.map, vaddr, &fs.entry) &&
623 		    (fs.entry->eflags & MAP_ENTRY_IN_TRANSITION)) {
624 			unlock_vp(&fs);
625 			fs.entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
626 			vm_map_unlock_and_wait(fs.map, 0);
627 		} else
628 			vm_map_unlock(fs.map);
629 		goto RetryFault;
630 	}
631 
632 	MPASS((fs.entry->eflags & MAP_ENTRY_GUARD) == 0);
633 
634 	if (wired)
635 		fault_type = prot | (fault_type & VM_PROT_COPY);
636 	else
637 		KASSERT((fault_flags & VM_FAULT_WIRE) == 0,
638 		    ("!wired && VM_FAULT_WIRE"));
639 
640 	/*
641 	 * Try to avoid lock contention on the top-level object through
642 	 * special-case handling of some types of page faults, specifically,
643 	 * those that are both (1) mapping an existing page from the top-
644 	 * level object and (2) not having to mark that object as containing
645 	 * dirty pages.  Under these conditions, a read lock on the top-level
646 	 * object suffices, allowing multiple page faults of a similar type to
647 	 * run in parallel on the same top-level object.
648 	 */
649 	if (fs.vp == NULL /* avoid locked vnode leak */ &&
650 	    (fault_flags & (VM_FAULT_WIRE | VM_FAULT_DIRTY)) == 0 &&
651 	    /* avoid calling vm_object_set_writeable_dirty() */
652 	    ((prot & VM_PROT_WRITE) == 0 ||
653 	    (fs.first_object->type != OBJT_VNODE &&
654 	    (fs.first_object->flags & OBJ_TMPFS_NODE) == 0) ||
655 	    (fs.first_object->flags & OBJ_MIGHTBEDIRTY) != 0)) {
656 		VM_OBJECT_RLOCK(fs.first_object);
657 		if ((prot & VM_PROT_WRITE) == 0 ||
658 		    (fs.first_object->type != OBJT_VNODE &&
659 		    (fs.first_object->flags & OBJ_TMPFS_NODE) == 0) ||
660 		    (fs.first_object->flags & OBJ_MIGHTBEDIRTY) != 0) {
661 			rv = vm_fault_soft_fast(&fs, vaddr, prot, fault_type,
662 			    fault_flags, wired, m_hold);
663 			if (rv == KERN_SUCCESS)
664 				return (rv);
665 		}
666 		if (!VM_OBJECT_TRYUPGRADE(fs.first_object)) {
667 			VM_OBJECT_RUNLOCK(fs.first_object);
668 			VM_OBJECT_WLOCK(fs.first_object);
669 		}
670 	} else {
671 		VM_OBJECT_WLOCK(fs.first_object);
672 	}
673 
674 	/*
675 	 * Make a reference to this object to prevent its disposal while we
676 	 * are messing with it.  Once we have the reference, the map is free
677 	 * to be diddled.  Since objects reference their shadows (and copies),
678 	 * they will stay around as well.
679 	 *
680 	 * Bump the paging-in-progress count to prevent size changes (e.g.
681 	 * truncation operations) during I/O.
682 	 */
683 	vm_object_reference_locked(fs.first_object);
684 	vm_object_pip_add(fs.first_object, 1);
685 
686 	fs.lookup_still_valid = true;
687 
688 	fs.first_m = NULL;
689 
690 	/*
691 	 * Search for the page at object/offset.
692 	 */
693 	fs.object = fs.first_object;
694 	fs.pindex = fs.first_pindex;
695 	while (TRUE) {
696 		/*
697 		 * If the object is marked for imminent termination,
698 		 * we retry here, since the collapse pass has raced
699 		 * with us.  Otherwise, if we see terminally dead
700 		 * object, return fail.
701 		 */
702 		if ((fs.object->flags & OBJ_DEAD) != 0) {
703 			dead = fs.object->type == OBJT_DEAD;
704 			unlock_and_deallocate(&fs);
705 			if (dead)
706 				return (KERN_PROTECTION_FAILURE);
707 			pause("vmf_de", 1);
708 			goto RetryFault;
709 		}
710 
711 		/*
712 		 * See if page is resident
713 		 */
714 		fs.m = vm_page_lookup(fs.object, fs.pindex);
715 		if (fs.m != NULL) {
716 			/*
717 			 * Wait/Retry if the page is busy.  We have to do this
718 			 * if the page is either exclusive or shared busy
719 			 * because the vm_pager may be using read busy for
720 			 * pageouts (and even pageins if it is the vnode
721 			 * pager), and we could end up trying to pagein and
722 			 * pageout the same page simultaneously.
723 			 *
724 			 * We can theoretically allow the busy case on a read
725 			 * fault if the page is marked valid, but since such
726 			 * pages are typically already pmap'd, putting that
727 			 * special case in might be more effort then it is
728 			 * worth.  We cannot under any circumstances mess
729 			 * around with a shared busied page except, perhaps,
730 			 * to pmap it.
731 			 */
732 			if (vm_page_busied(fs.m)) {
733 				/*
734 				 * Reference the page before unlocking and
735 				 * sleeping so that the page daemon is less
736 				 * likely to reclaim it.
737 				 */
738 				vm_page_aflag_set(fs.m, PGA_REFERENCED);
739 				if (fs.object != fs.first_object) {
740 					if (!VM_OBJECT_TRYWLOCK(
741 					    fs.first_object)) {
742 						VM_OBJECT_WUNLOCK(fs.object);
743 						VM_OBJECT_WLOCK(fs.first_object);
744 						VM_OBJECT_WLOCK(fs.object);
745 					}
746 					vm_page_lock(fs.first_m);
747 					vm_page_free(fs.first_m);
748 					vm_page_unlock(fs.first_m);
749 					vm_object_pip_wakeup(fs.first_object);
750 					VM_OBJECT_WUNLOCK(fs.first_object);
751 					fs.first_m = NULL;
752 				}
753 				unlock_map(&fs);
754 				if (fs.m == vm_page_lookup(fs.object,
755 				    fs.pindex)) {
756 					vm_page_sleep_if_busy(fs.m, "vmpfw");
757 				}
758 				vm_object_pip_wakeup(fs.object);
759 				VM_OBJECT_WUNLOCK(fs.object);
760 				VM_CNT_INC(v_intrans);
761 				vm_object_deallocate(fs.first_object);
762 				goto RetryFault;
763 			}
764 
765 			/*
766 			 * Mark page busy for other processes, and the
767 			 * pagedaemon.  If it still isn't completely valid
768 			 * (readable), jump to readrest, else break-out ( we
769 			 * found the page ).
770 			 */
771 			vm_page_xbusy(fs.m);
772 			if (fs.m->valid != VM_PAGE_BITS_ALL)
773 				goto readrest;
774 			break; /* break to PAGE HAS BEEN FOUND */
775 		}
776 		KASSERT(fs.m == NULL, ("fs.m should be NULL, not %p", fs.m));
777 
778 		/*
779 		 * Page is not resident.  If the pager might contain the page
780 		 * or this is the beginning of the search, allocate a new
781 		 * page.  (Default objects are zero-fill, so there is no real
782 		 * pager for them.)
783 		 */
784 		if (fs.object->type != OBJT_DEFAULT ||
785 		    fs.object == fs.first_object) {
786 			if (fs.pindex >= fs.object->size) {
787 				unlock_and_deallocate(&fs);
788 				return (KERN_PROTECTION_FAILURE);
789 			}
790 
791 			if (fs.object == fs.first_object &&
792 			    (fs.first_object->flags & OBJ_POPULATE) != 0 &&
793 			    fs.first_object->shadow_count == 0) {
794 				rv = vm_fault_populate(&fs, prot, fault_type,
795 				    fault_flags, wired, m_hold);
796 				switch (rv) {
797 				case KERN_SUCCESS:
798 				case KERN_FAILURE:
799 					unlock_and_deallocate(&fs);
800 					return (rv);
801 				case KERN_RESOURCE_SHORTAGE:
802 					unlock_and_deallocate(&fs);
803 					goto RetryFault;
804 				case KERN_NOT_RECEIVER:
805 					/*
806 					 * Pager's populate() method
807 					 * returned VM_PAGER_BAD.
808 					 */
809 					break;
810 				default:
811 					panic("inconsistent return codes");
812 				}
813 			}
814 
815 			/*
816 			 * Allocate a new page for this object/offset pair.
817 			 *
818 			 * Unlocked read of the p_flag is harmless. At
819 			 * worst, the P_KILLED might be not observed
820 			 * there, and allocation can fail, causing
821 			 * restart and new reading of the p_flag.
822 			 */
823 			dset = fs.object->domain.dr_policy;
824 			if (dset == NULL)
825 				dset = curthread->td_domain.dr_policy;
826 			if (!vm_page_count_severe_set(&dset->ds_mask) ||
827 			    P_KILLED(curproc)) {
828 #if VM_NRESERVLEVEL > 0
829 				vm_object_color(fs.object, atop(vaddr) -
830 				    fs.pindex);
831 #endif
832 				alloc_req = P_KILLED(curproc) ?
833 				    VM_ALLOC_SYSTEM : VM_ALLOC_NORMAL;
834 				if (fs.object->type != OBJT_VNODE &&
835 				    fs.object->backing_object == NULL)
836 					alloc_req |= VM_ALLOC_ZERO;
837 				fs.m = vm_page_alloc(fs.object, fs.pindex,
838 				    alloc_req);
839 			}
840 			if (fs.m == NULL) {
841 				unlock_and_deallocate(&fs);
842 				if (vm_pfault_oom_attempts < 0 ||
843 				    oom < vm_pfault_oom_attempts) {
844 					oom++;
845 					vm_waitpfault(dset,
846 					    vm_pfault_oom_wait * hz);
847 					goto RetryFault_oom;
848 				}
849 				if (bootverbose)
850 					printf(
851 	"proc %d (%s) failed to alloc page on fault, starting OOM\n",
852 					    curproc->p_pid, curproc->p_comm);
853 				vm_pageout_oom(VM_OOM_MEM_PF);
854 				goto RetryFault;
855 			}
856 		}
857 
858 readrest:
859 		/*
860 		 * At this point, we have either allocated a new page or found
861 		 * an existing page that is only partially valid.
862 		 *
863 		 * We hold a reference on the current object and the page is
864 		 * exclusive busied.
865 		 */
866 
867 		/*
868 		 * If the pager for the current object might have the page,
869 		 * then determine the number of additional pages to read and
870 		 * potentially reprioritize previously read pages for earlier
871 		 * reclamation.  These operations should only be performed
872 		 * once per page fault.  Even if the current pager doesn't
873 		 * have the page, the number of additional pages to read will
874 		 * apply to subsequent objects in the shadow chain.
875 		 */
876 		if (fs.object->type != OBJT_DEFAULT && nera == -1 &&
877 		    !P_KILLED(curproc)) {
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 (vaddr == fs.entry->next_read)
886 					vm_fault_dontneed(&fs, vaddr, nera);
887 			} else if (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, 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 			/*
918 			 * Prepare for unlocking the map.  Save the map
919 			 * entry's start and end addresses, which are used to
920 			 * optimize the size of the pager operation below.
921 			 * Even if the map entry's addresses change after
922 			 * unlocking the map, using the saved addresses is
923 			 * safe.
924 			 */
925 			e_start = fs.entry->start;
926 			e_end = fs.entry->end;
927 		}
928 
929 		/*
930 		 * Call the pager to retrieve the page if there is a chance
931 		 * that the pager has it, and potentially retrieve additional
932 		 * pages at the same time.
933 		 */
934 		if (fs.object->type != OBJT_DEFAULT) {
935 			/*
936 			 * Release the map lock before locking the vnode or
937 			 * sleeping in the pager.  (If the current object has
938 			 * a shadow, then an earlier iteration of this loop
939 			 * may have already unlocked the map.)
940 			 */
941 			unlock_map(&fs);
942 
943 			if (fs.object->type == OBJT_VNODE &&
944 			    (vp = fs.object->handle) != fs.vp) {
945 				/*
946 				 * Perform an unlock in case the desired vnode
947 				 * changed while the map was unlocked during a
948 				 * retry.
949 				 */
950 				unlock_vp(&fs);
951 
952 				locked = VOP_ISLOCKED(vp);
953 				if (locked != LK_EXCLUSIVE)
954 					locked = LK_SHARED;
955 
956 				/*
957 				 * We must not sleep acquiring the vnode lock
958 				 * while we have the page exclusive busied or
959 				 * the object's paging-in-progress count
960 				 * incremented.  Otherwise, we could deadlock.
961 				 */
962 				error = vget(vp, locked | LK_CANRECURSE |
963 				    LK_NOWAIT, curthread);
964 				if (error != 0) {
965 					vhold(vp);
966 					release_page(&fs);
967 					unlock_and_deallocate(&fs);
968 					error = vget(vp, locked | LK_RETRY |
969 					    LK_CANRECURSE, curthread);
970 					vdrop(vp);
971 					fs.vp = vp;
972 					KASSERT(error == 0,
973 					    ("vm_fault: vget failed"));
974 					goto RetryFault;
975 				}
976 				fs.vp = vp;
977 			}
978 			KASSERT(fs.vp == NULL || !fs.map->system_map,
979 			    ("vm_fault: vnode-backed object mapped by system map"));
980 
981 			/*
982 			 * Page in the requested page and hint the pager,
983 			 * that it may bring up surrounding pages.
984 			 */
985 			if (nera == -1 || behavior == MAP_ENTRY_BEHAV_RANDOM ||
986 			    P_KILLED(curproc)) {
987 				behind = 0;
988 				ahead = 0;
989 			} else {
990 				/* Is this a sequential fault? */
991 				if (nera > 0) {
992 					behind = 0;
993 					ahead = nera;
994 				} else {
995 					/*
996 					 * Request a cluster of pages that is
997 					 * aligned to a VM_FAULT_READ_DEFAULT
998 					 * page offset boundary within the
999 					 * object.  Alignment to a page offset
1000 					 * boundary is more likely to coincide
1001 					 * with the underlying file system
1002 					 * block than alignment to a virtual
1003 					 * address boundary.
1004 					 */
1005 					cluster_offset = fs.pindex %
1006 					    VM_FAULT_READ_DEFAULT;
1007 					behind = ulmin(cluster_offset,
1008 					    atop(vaddr - e_start));
1009 					ahead = VM_FAULT_READ_DEFAULT - 1 -
1010 					    cluster_offset;
1011 				}
1012 				ahead = ulmin(ahead, atop(e_end - vaddr) - 1);
1013 			}
1014 			rv = vm_pager_get_pages(fs.object, &fs.m, 1,
1015 			    &behind, &ahead);
1016 			if (rv == VM_PAGER_OK) {
1017 				faultcount = behind + 1 + ahead;
1018 				hardfault = true;
1019 				break; /* break to PAGE HAS BEEN FOUND */
1020 			}
1021 			if (rv == VM_PAGER_ERROR)
1022 				printf("vm_fault: pager read error, pid %d (%s)\n",
1023 				    curproc->p_pid, curproc->p_comm);
1024 
1025 			/*
1026 			 * If an I/O error occurred or the requested page was
1027 			 * outside the range of the pager, clean up and return
1028 			 * an error.
1029 			 */
1030 			if (rv == VM_PAGER_ERROR || rv == VM_PAGER_BAD) {
1031 				vm_page_lock(fs.m);
1032 				if (!vm_page_wired(fs.m))
1033 					vm_page_free(fs.m);
1034 				else
1035 					vm_page_xunbusy_maybelocked(fs.m);
1036 				vm_page_unlock(fs.m);
1037 				fs.m = NULL;
1038 				unlock_and_deallocate(&fs);
1039 				return (rv == VM_PAGER_ERROR ? KERN_FAILURE :
1040 				    KERN_PROTECTION_FAILURE);
1041 			}
1042 
1043 			/*
1044 			 * The requested page does not exist at this object/
1045 			 * offset.  Remove the invalid page from the object,
1046 			 * waking up anyone waiting for it, and continue on to
1047 			 * the next object.  However, if this is the top-level
1048 			 * object, we must leave the busy page in place to
1049 			 * prevent another process from rushing past us, and
1050 			 * inserting the page in that object at the same time
1051 			 * that we are.
1052 			 */
1053 			if (fs.object != fs.first_object) {
1054 				vm_page_lock(fs.m);
1055 				if (!vm_page_wired(fs.m))
1056 					vm_page_free(fs.m);
1057 				else
1058 					vm_page_xunbusy_maybelocked(fs.m);
1059 				vm_page_unlock(fs.m);
1060 				fs.m = NULL;
1061 			}
1062 		}
1063 
1064 		/*
1065 		 * We get here if the object has default pager (or unwiring)
1066 		 * or the pager doesn't have the page.
1067 		 */
1068 		if (fs.object == fs.first_object)
1069 			fs.first_m = fs.m;
1070 
1071 		/*
1072 		 * Move on to the next object.  Lock the next object before
1073 		 * unlocking the current one.
1074 		 */
1075 		next_object = fs.object->backing_object;
1076 		if (next_object == NULL) {
1077 			/*
1078 			 * If there's no object left, fill the page in the top
1079 			 * object with zeros.
1080 			 */
1081 			if (fs.object != fs.first_object) {
1082 				vm_object_pip_wakeup(fs.object);
1083 				VM_OBJECT_WUNLOCK(fs.object);
1084 
1085 				fs.object = fs.first_object;
1086 				fs.pindex = fs.first_pindex;
1087 				fs.m = fs.first_m;
1088 				VM_OBJECT_WLOCK(fs.object);
1089 			}
1090 			fs.first_m = NULL;
1091 
1092 			/*
1093 			 * Zero the page if necessary and mark it valid.
1094 			 */
1095 			if ((fs.m->flags & PG_ZERO) == 0) {
1096 				pmap_zero_page(fs.m);
1097 			} else {
1098 				VM_CNT_INC(v_ozfod);
1099 			}
1100 			VM_CNT_INC(v_zfod);
1101 			fs.m->valid = VM_PAGE_BITS_ALL;
1102 			/* Don't try to prefault neighboring pages. */
1103 			faultcount = 1;
1104 			break;	/* break to PAGE HAS BEEN FOUND */
1105 		} else {
1106 			KASSERT(fs.object != next_object,
1107 			    ("object loop %p", next_object));
1108 			VM_OBJECT_WLOCK(next_object);
1109 			vm_object_pip_add(next_object, 1);
1110 			if (fs.object != fs.first_object)
1111 				vm_object_pip_wakeup(fs.object);
1112 			fs.pindex +=
1113 			    OFF_TO_IDX(fs.object->backing_object_offset);
1114 			VM_OBJECT_WUNLOCK(fs.object);
1115 			fs.object = next_object;
1116 		}
1117 	}
1118 
1119 	vm_page_assert_xbusied(fs.m);
1120 
1121 	/*
1122 	 * PAGE HAS BEEN FOUND. [Loop invariant still holds -- the object lock
1123 	 * is held.]
1124 	 */
1125 
1126 	/*
1127 	 * If the page is being written, but isn't already owned by the
1128 	 * top-level object, we have to copy it into a new page owned by the
1129 	 * top-level object.
1130 	 */
1131 	if (fs.object != fs.first_object) {
1132 		/*
1133 		 * We only really need to copy if we want to write it.
1134 		 */
1135 		if ((fault_type & (VM_PROT_COPY | VM_PROT_WRITE)) != 0) {
1136 			/*
1137 			 * This allows pages to be virtually copied from a
1138 			 * backing_object into the first_object, where the
1139 			 * backing object has no other refs to it, and cannot
1140 			 * gain any more refs.  Instead of a bcopy, we just
1141 			 * move the page from the backing object to the
1142 			 * first object.  Note that we must mark the page
1143 			 * dirty in the first object so that it will go out
1144 			 * to swap when needed.
1145 			 */
1146 			is_first_object_locked = false;
1147 			if (
1148 				/*
1149 				 * Only one shadow object
1150 				 */
1151 				(fs.object->shadow_count == 1) &&
1152 				/*
1153 				 * No COW refs, except us
1154 				 */
1155 				(fs.object->ref_count == 1) &&
1156 				/*
1157 				 * No one else can look this object up
1158 				 */
1159 				(fs.object->handle == NULL) &&
1160 				/*
1161 				 * No other ways to look the object up
1162 				 */
1163 				((fs.object->type == OBJT_DEFAULT) ||
1164 				 (fs.object->type == OBJT_SWAP)) &&
1165 			    (is_first_object_locked = VM_OBJECT_TRYWLOCK(fs.first_object)) &&
1166 				/*
1167 				 * We don't chase down the shadow chain
1168 				 */
1169 			    fs.object == fs.first_object->backing_object) {
1170 				vm_page_lock(fs.m);
1171 				vm_page_dequeue(fs.m);
1172 				(void)vm_page_remove(fs.m);
1173 				vm_page_unlock(fs.m);
1174 				vm_page_lock(fs.first_m);
1175 				vm_page_replace_checked(fs.m, fs.first_object,
1176 				    fs.first_pindex, fs.first_m);
1177 				vm_page_free(fs.first_m);
1178 				vm_page_unlock(fs.first_m);
1179 				vm_page_dirty(fs.m);
1180 #if VM_NRESERVLEVEL > 0
1181 				/*
1182 				 * Rename the reservation.
1183 				 */
1184 				vm_reserv_rename(fs.m, fs.first_object,
1185 				    fs.object, OFF_TO_IDX(
1186 				    fs.first_object->backing_object_offset));
1187 #endif
1188 				/*
1189 				 * Removing the page from the backing object
1190 				 * unbusied it.
1191 				 */
1192 				vm_page_xbusy(fs.m);
1193 				fs.first_m = fs.m;
1194 				fs.m = NULL;
1195 				VM_CNT_INC(v_cow_optim);
1196 			} else {
1197 				/*
1198 				 * Oh, well, lets copy it.
1199 				 */
1200 				pmap_copy_page(fs.m, fs.first_m);
1201 				fs.first_m->valid = VM_PAGE_BITS_ALL;
1202 				if (wired && (fault_flags &
1203 				    VM_FAULT_WIRE) == 0) {
1204 					vm_page_lock(fs.first_m);
1205 					vm_page_wire(fs.first_m);
1206 					vm_page_unlock(fs.first_m);
1207 
1208 					vm_page_lock(fs.m);
1209 					vm_page_unwire(fs.m, PQ_INACTIVE);
1210 					vm_page_unlock(fs.m);
1211 				}
1212 				/*
1213 				 * We no longer need the old page or object.
1214 				 */
1215 				release_page(&fs);
1216 			}
1217 			/*
1218 			 * fs.object != fs.first_object due to above
1219 			 * conditional
1220 			 */
1221 			vm_object_pip_wakeup(fs.object);
1222 			VM_OBJECT_WUNLOCK(fs.object);
1223 			/*
1224 			 * Only use the new page below...
1225 			 */
1226 			fs.object = fs.first_object;
1227 			fs.pindex = fs.first_pindex;
1228 			fs.m = fs.first_m;
1229 			if (!is_first_object_locked)
1230 				VM_OBJECT_WLOCK(fs.object);
1231 			VM_CNT_INC(v_cow_faults);
1232 			curthread->td_cow++;
1233 		} else {
1234 			prot &= ~VM_PROT_WRITE;
1235 		}
1236 	}
1237 
1238 	/*
1239 	 * We must verify that the maps have not changed since our last
1240 	 * lookup.
1241 	 */
1242 	if (!fs.lookup_still_valid) {
1243 		if (!vm_map_trylock_read(fs.map)) {
1244 			release_page(&fs);
1245 			unlock_and_deallocate(&fs);
1246 			goto RetryFault;
1247 		}
1248 		fs.lookup_still_valid = true;
1249 		if (fs.map->timestamp != fs.map_generation) {
1250 			result = vm_map_lookup_locked(&fs.map, vaddr, fault_type,
1251 			    &fs.entry, &retry_object, &retry_pindex, &retry_prot, &wired);
1252 
1253 			/*
1254 			 * If we don't need the page any longer, put it on the inactive
1255 			 * list (the easiest thing to do here).  If no one needs it,
1256 			 * pageout will grab it eventually.
1257 			 */
1258 			if (result != KERN_SUCCESS) {
1259 				release_page(&fs);
1260 				unlock_and_deallocate(&fs);
1261 
1262 				/*
1263 				 * If retry of map lookup would have blocked then
1264 				 * retry fault from start.
1265 				 */
1266 				if (result == KERN_FAILURE)
1267 					goto RetryFault;
1268 				return (result);
1269 			}
1270 			if ((retry_object != fs.first_object) ||
1271 			    (retry_pindex != fs.first_pindex)) {
1272 				release_page(&fs);
1273 				unlock_and_deallocate(&fs);
1274 				goto RetryFault;
1275 			}
1276 
1277 			/*
1278 			 * Check whether the protection has changed or the object has
1279 			 * been copied while we left the map unlocked. Changing from
1280 			 * read to write permission is OK - we leave the page
1281 			 * write-protected, and catch the write fault. Changing from
1282 			 * write to read permission means that we can't mark the page
1283 			 * write-enabled after all.
1284 			 */
1285 			prot &= retry_prot;
1286 			fault_type &= retry_prot;
1287 			if (prot == 0) {
1288 				release_page(&fs);
1289 				unlock_and_deallocate(&fs);
1290 				goto RetryFault;
1291 			}
1292 
1293 			/* Reassert because wired may have changed. */
1294 			KASSERT(wired || (fault_flags & VM_FAULT_WIRE) == 0,
1295 			    ("!wired && VM_FAULT_WIRE"));
1296 		}
1297 	}
1298 
1299 	/*
1300 	 * If the page was filled by a pager, save the virtual address that
1301 	 * should be faulted on next under a sequential access pattern to the
1302 	 * map entry.  A read lock on the map suffices to update this address
1303 	 * safely.
1304 	 */
1305 	if (hardfault)
1306 		fs.entry->next_read = vaddr + ptoa(ahead) + PAGE_SIZE;
1307 
1308 	vm_fault_dirty(fs.entry, fs.m, prot, fault_type, fault_flags, true);
1309 	vm_page_assert_xbusied(fs.m);
1310 
1311 	/*
1312 	 * Page must be completely valid or it is not fit to
1313 	 * map into user space.  vm_pager_get_pages() ensures this.
1314 	 */
1315 	KASSERT(fs.m->valid == VM_PAGE_BITS_ALL,
1316 	    ("vm_fault: page %p partially invalid", fs.m));
1317 	VM_OBJECT_WUNLOCK(fs.object);
1318 
1319 	/*
1320 	 * Put this page into the physical map.  We had to do the unlock above
1321 	 * because pmap_enter() may sleep.  We don't put the page
1322 	 * back on the active queue until later so that the pageout daemon
1323 	 * won't find it (yet).
1324 	 */
1325 	pmap_enter(fs.map->pmap, vaddr, fs.m, prot,
1326 	    fault_type | (wired ? PMAP_ENTER_WIRED : 0), 0);
1327 	if (faultcount != 1 && (fault_flags & VM_FAULT_WIRE) == 0 &&
1328 	    wired == 0)
1329 		vm_fault_prefault(&fs, vaddr,
1330 		    faultcount > 0 ? behind : PFBAK,
1331 		    faultcount > 0 ? ahead : PFFOR, false);
1332 	VM_OBJECT_WLOCK(fs.object);
1333 	vm_page_lock(fs.m);
1334 
1335 	/*
1336 	 * If the page is not wired down, then put it where the pageout daemon
1337 	 * can find it.
1338 	 */
1339 	if ((fault_flags & VM_FAULT_WIRE) != 0)
1340 		vm_page_wire(fs.m);
1341 	else
1342 		vm_page_activate(fs.m);
1343 	if (m_hold != NULL) {
1344 		*m_hold = fs.m;
1345 		vm_page_hold(fs.m);
1346 	}
1347 	vm_page_unlock(fs.m);
1348 	vm_page_xunbusy(fs.m);
1349 
1350 	/*
1351 	 * Unlock everything, and return
1352 	 */
1353 	unlock_and_deallocate(&fs);
1354 	if (hardfault) {
1355 		VM_CNT_INC(v_io_faults);
1356 		curthread->td_ru.ru_majflt++;
1357 #ifdef RACCT
1358 		if (racct_enable && fs.object->type == OBJT_VNODE) {
1359 			PROC_LOCK(curproc);
1360 			if ((fault_type & (VM_PROT_COPY | VM_PROT_WRITE)) != 0) {
1361 				racct_add_force(curproc, RACCT_WRITEBPS,
1362 				    PAGE_SIZE + behind * PAGE_SIZE);
1363 				racct_add_force(curproc, RACCT_WRITEIOPS, 1);
1364 			} else {
1365 				racct_add_force(curproc, RACCT_READBPS,
1366 				    PAGE_SIZE + ahead * PAGE_SIZE);
1367 				racct_add_force(curproc, RACCT_READIOPS, 1);
1368 			}
1369 			PROC_UNLOCK(curproc);
1370 		}
1371 #endif
1372 	} else
1373 		curthread->td_ru.ru_minflt++;
1374 
1375 	return (KERN_SUCCESS);
1376 }
1377 
1378 /*
1379  * Speed up the reclamation of pages that precede the faulting pindex within
1380  * the first object of the shadow chain.  Essentially, perform the equivalent
1381  * to madvise(..., MADV_DONTNEED) on a large cluster of pages that precedes
1382  * the faulting pindex by the cluster size when the pages read by vm_fault()
1383  * cross a cluster-size boundary.  The cluster size is the greater of the
1384  * smallest superpage size and VM_FAULT_DONTNEED_MIN.
1385  *
1386  * When "fs->first_object" is a shadow object, the pages in the backing object
1387  * that precede the faulting pindex are deactivated by vm_fault().  So, this
1388  * function must only be concerned with pages in the first object.
1389  */
1390 static void
vm_fault_dontneed(const struct faultstate * fs,vm_offset_t vaddr,int ahead)1391 vm_fault_dontneed(const struct faultstate *fs, vm_offset_t vaddr, int ahead)
1392 {
1393 	vm_map_entry_t entry;
1394 	vm_object_t first_object, object;
1395 	vm_offset_t end, start;
1396 	vm_page_t m, m_next;
1397 	vm_pindex_t pend, pstart;
1398 	vm_size_t size;
1399 
1400 	object = fs->object;
1401 	VM_OBJECT_ASSERT_WLOCKED(object);
1402 	first_object = fs->first_object;
1403 	if (first_object != object) {
1404 		if (!VM_OBJECT_TRYWLOCK(first_object)) {
1405 			VM_OBJECT_WUNLOCK(object);
1406 			VM_OBJECT_WLOCK(first_object);
1407 			VM_OBJECT_WLOCK(object);
1408 		}
1409 	}
1410 	/* Neither fictitious nor unmanaged pages can be reclaimed. */
1411 	if ((first_object->flags & (OBJ_FICTITIOUS | OBJ_UNMANAGED)) == 0) {
1412 		size = VM_FAULT_DONTNEED_MIN;
1413 		if (MAXPAGESIZES > 1 && size < pagesizes[1])
1414 			size = pagesizes[1];
1415 		end = rounddown2(vaddr, size);
1416 		if (vaddr - end >= size - PAGE_SIZE - ptoa(ahead) &&
1417 		    (entry = fs->entry)->start < end) {
1418 			if (end - entry->start < size)
1419 				start = entry->start;
1420 			else
1421 				start = end - size;
1422 			pmap_advise(fs->map->pmap, start, end, MADV_DONTNEED);
1423 			pstart = OFF_TO_IDX(entry->offset) + atop(start -
1424 			    entry->start);
1425 			m_next = vm_page_find_least(first_object, pstart);
1426 			pend = OFF_TO_IDX(entry->offset) + atop(end -
1427 			    entry->start);
1428 			while ((m = m_next) != NULL && m->pindex < pend) {
1429 				m_next = TAILQ_NEXT(m, listq);
1430 				if (m->valid != VM_PAGE_BITS_ALL ||
1431 				    vm_page_busied(m))
1432 					continue;
1433 
1434 				/*
1435 				 * Don't clear PGA_REFERENCED, since it would
1436 				 * likely represent a reference by a different
1437 				 * process.
1438 				 *
1439 				 * Typically, at this point, prefetched pages
1440 				 * are still in the inactive queue.  Only
1441 				 * pages that triggered page faults are in the
1442 				 * active queue.
1443 				 */
1444 				vm_page_lock(m);
1445 				if (!vm_page_inactive(m))
1446 					vm_page_deactivate(m);
1447 				vm_page_unlock(m);
1448 			}
1449 		}
1450 	}
1451 	if (first_object != object)
1452 		VM_OBJECT_WUNLOCK(first_object);
1453 }
1454 
1455 /*
1456  * vm_fault_prefault provides a quick way of clustering
1457  * pagefaults into a processes address space.  It is a "cousin"
1458  * of vm_map_pmap_enter, except it runs at page fault time instead
1459  * of mmap time.
1460  */
1461 static void
vm_fault_prefault(const struct faultstate * fs,vm_offset_t addra,int backward,int forward,bool obj_locked)1462 vm_fault_prefault(const struct faultstate *fs, vm_offset_t addra,
1463     int backward, int forward, bool obj_locked)
1464 {
1465 	pmap_t pmap;
1466 	vm_map_entry_t entry;
1467 	vm_object_t backing_object, lobject;
1468 	vm_offset_t addr, starta;
1469 	vm_pindex_t pindex;
1470 	vm_page_t m;
1471 	int i;
1472 
1473 	pmap = fs->map->pmap;
1474 	if (pmap != vmspace_pmap(curthread->td_proc->p_vmspace))
1475 		return;
1476 
1477 	entry = fs->entry;
1478 
1479 	if (addra < backward * PAGE_SIZE) {
1480 		starta = entry->start;
1481 	} else {
1482 		starta = addra - backward * PAGE_SIZE;
1483 		if (starta < entry->start)
1484 			starta = entry->start;
1485 	}
1486 
1487 	/*
1488 	 * Generate the sequence of virtual addresses that are candidates for
1489 	 * prefaulting in an outward spiral from the faulting virtual address,
1490 	 * "addra".  Specifically, the sequence is "addra - PAGE_SIZE", "addra
1491 	 * + PAGE_SIZE", "addra - 2 * PAGE_SIZE", "addra + 2 * PAGE_SIZE", ...
1492 	 * If the candidate address doesn't have a backing physical page, then
1493 	 * the loop immediately terminates.
1494 	 */
1495 	for (i = 0; i < 2 * imax(backward, forward); i++) {
1496 		addr = addra + ((i >> 1) + 1) * ((i & 1) == 0 ? -PAGE_SIZE :
1497 		    PAGE_SIZE);
1498 		if (addr > addra + forward * PAGE_SIZE)
1499 			addr = 0;
1500 
1501 		if (addr < starta || addr >= entry->end)
1502 			continue;
1503 
1504 		if (!pmap_is_prefaultable(pmap, addr))
1505 			continue;
1506 
1507 		pindex = ((addr - entry->start) + entry->offset) >> PAGE_SHIFT;
1508 		lobject = entry->object.vm_object;
1509 		if (!obj_locked)
1510 			VM_OBJECT_RLOCK(lobject);
1511 		while ((m = vm_page_lookup(lobject, pindex)) == NULL &&
1512 		    lobject->type == OBJT_DEFAULT &&
1513 		    (backing_object = lobject->backing_object) != NULL) {
1514 			KASSERT((lobject->backing_object_offset & PAGE_MASK) ==
1515 			    0, ("vm_fault_prefault: unaligned object offset"));
1516 			pindex += lobject->backing_object_offset >> PAGE_SHIFT;
1517 			VM_OBJECT_RLOCK(backing_object);
1518 			if (!obj_locked || lobject != entry->object.vm_object)
1519 				VM_OBJECT_RUNLOCK(lobject);
1520 			lobject = backing_object;
1521 		}
1522 		if (m == NULL) {
1523 			if (!obj_locked || lobject != entry->object.vm_object)
1524 				VM_OBJECT_RUNLOCK(lobject);
1525 			break;
1526 		}
1527 		if (m->valid == VM_PAGE_BITS_ALL &&
1528 		    (m->flags & PG_FICTITIOUS) == 0)
1529 			pmap_enter_quick(pmap, addr, m, entry->protection);
1530 		if (!obj_locked || lobject != entry->object.vm_object)
1531 			VM_OBJECT_RUNLOCK(lobject);
1532 	}
1533 }
1534 
1535 /*
1536  * Hold each of the physical pages that are mapped by the specified range of
1537  * virtual addresses, ["addr", "addr" + "len"), if those mappings are valid
1538  * and allow the specified types of access, "prot".  If all of the implied
1539  * pages are successfully held, then the number of held pages is returned
1540  * together with pointers to those pages in the array "ma".  However, if any
1541  * of the pages cannot be held, -1 is returned.
1542  */
1543 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)1544 vm_fault_quick_hold_pages(vm_map_t map, vm_offset_t addr, vm_size_t len,
1545     vm_prot_t prot, vm_page_t *ma, int max_count)
1546 {
1547 	vm_offset_t end, va;
1548 	vm_page_t *mp;
1549 	int count;
1550 	boolean_t pmap_failed;
1551 
1552 	if (len == 0)
1553 		return (0);
1554 	end = round_page(addr + len);
1555 	addr = trunc_page(addr);
1556 
1557 	/*
1558 	 * Check for illegal addresses.
1559 	 */
1560 	if (addr < vm_map_min(map) || addr > end || end > vm_map_max(map))
1561 		return (-1);
1562 
1563 	if (atop(end - addr) > max_count)
1564 		panic("vm_fault_quick_hold_pages: count > max_count");
1565 	count = atop(end - addr);
1566 
1567 	/*
1568 	 * Most likely, the physical pages are resident in the pmap, so it is
1569 	 * faster to try pmap_extract_and_hold() first.
1570 	 */
1571 	pmap_failed = FALSE;
1572 	for (mp = ma, va = addr; va < end; mp++, va += PAGE_SIZE) {
1573 		*mp = pmap_extract_and_hold(map->pmap, va, prot);
1574 		if (*mp == NULL)
1575 			pmap_failed = TRUE;
1576 		else if ((prot & VM_PROT_WRITE) != 0 &&
1577 		    (*mp)->dirty != VM_PAGE_BITS_ALL) {
1578 			/*
1579 			 * Explicitly dirty the physical page.  Otherwise, the
1580 			 * caller's changes may go unnoticed because they are
1581 			 * performed through an unmanaged mapping or by a DMA
1582 			 * operation.
1583 			 *
1584 			 * The object lock is not held here.
1585 			 * See vm_page_clear_dirty_mask().
1586 			 */
1587 			vm_page_dirty(*mp);
1588 		}
1589 	}
1590 	if (pmap_failed) {
1591 		/*
1592 		 * One or more pages could not be held by the pmap.  Either no
1593 		 * page was mapped at the specified virtual address or that
1594 		 * mapping had insufficient permissions.  Attempt to fault in
1595 		 * and hold these pages.
1596 		 *
1597 		 * If vm_fault_disable_pagefaults() was called,
1598 		 * i.e., TDP_NOFAULTING is set, we must not sleep nor
1599 		 * acquire MD VM locks, which means we must not call
1600 		 * vm_fault_hold().  Some (out of tree) callers mark
1601 		 * too wide a code area with vm_fault_disable_pagefaults()
1602 		 * already, use the VM_PROT_QUICK_NOFAULT flag to request
1603 		 * the proper behaviour explicitly.
1604 		 */
1605 		if ((prot & VM_PROT_QUICK_NOFAULT) != 0 &&
1606 		    (curthread->td_pflags & TDP_NOFAULTING) != 0)
1607 			goto error;
1608 		for (mp = ma, va = addr; va < end; mp++, va += PAGE_SIZE)
1609 			if (*mp == NULL && vm_fault_hold(map, va, prot,
1610 			    VM_FAULT_NORMAL, mp) != KERN_SUCCESS)
1611 				goto error;
1612 	}
1613 	return (count);
1614 error:
1615 	for (mp = ma; mp < ma + count; mp++)
1616 		if (*mp != NULL) {
1617 			vm_page_lock(*mp);
1618 			vm_page_unhold(*mp);
1619 			vm_page_unlock(*mp);
1620 		}
1621 	return (-1);
1622 }
1623 
1624 /*
1625  *	Routine:
1626  *		vm_fault_copy_entry
1627  *	Function:
1628  *		Create new shadow object backing dst_entry with private copy of
1629  *		all underlying pages. When src_entry is equal to dst_entry,
1630  *		function implements COW for wired-down map entry. Otherwise,
1631  *		it forks wired entry into dst_map.
1632  *
1633  *	In/out conditions:
1634  *		The source and destination maps must be locked for write.
1635  *		The source map entry must be wired down (or be a sharing map
1636  *		entry corresponding to a main map entry that is wired down).
1637  */
1638 void
vm_fault_copy_entry(vm_map_t dst_map,vm_map_t src_map,vm_map_entry_t dst_entry,vm_map_entry_t src_entry,vm_ooffset_t * fork_charge)1639 vm_fault_copy_entry(vm_map_t dst_map, vm_map_t src_map,
1640     vm_map_entry_t dst_entry, vm_map_entry_t src_entry,
1641     vm_ooffset_t *fork_charge)
1642 {
1643 	vm_object_t backing_object, dst_object, object, src_object;
1644 	vm_pindex_t dst_pindex, pindex, src_pindex;
1645 	vm_prot_t access, prot;
1646 	vm_offset_t vaddr;
1647 	vm_page_t dst_m;
1648 	vm_page_t src_m;
1649 	boolean_t upgrade;
1650 
1651 #ifdef	lint
1652 	src_map++;
1653 #endif	/* lint */
1654 
1655 	upgrade = src_entry == dst_entry;
1656 	access = prot = dst_entry->protection;
1657 
1658 	src_object = src_entry->object.vm_object;
1659 	src_pindex = OFF_TO_IDX(src_entry->offset);
1660 
1661 	if (upgrade && (dst_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) {
1662 		dst_object = src_object;
1663 		vm_object_reference(dst_object);
1664 	} else {
1665 		/*
1666 		 * Create the top-level object for the destination entry. (Doesn't
1667 		 * actually shadow anything - we copy the pages directly.)
1668 		 */
1669 		dst_object = vm_object_allocate(OBJT_DEFAULT,
1670 		    atop(dst_entry->end - dst_entry->start));
1671 #if VM_NRESERVLEVEL > 0
1672 		dst_object->flags |= OBJ_COLORED;
1673 		dst_object->pg_color = atop(dst_entry->start);
1674 #endif
1675 		dst_object->domain = src_object->domain;
1676 		dst_object->charge = dst_entry->end - dst_entry->start;
1677 	}
1678 
1679 	VM_OBJECT_WLOCK(dst_object);
1680 	KASSERT(upgrade || dst_entry->object.vm_object == NULL,
1681 	    ("vm_fault_copy_entry: vm_object not NULL"));
1682 	if (src_object != dst_object) {
1683 		dst_entry->object.vm_object = dst_object;
1684 		dst_entry->offset = 0;
1685 		dst_entry->eflags &= ~MAP_ENTRY_VN_EXEC;
1686 	}
1687 	if (fork_charge != NULL) {
1688 		KASSERT(dst_entry->cred == NULL,
1689 		    ("vm_fault_copy_entry: leaked swp charge"));
1690 		dst_object->cred = curthread->td_ucred;
1691 		crhold(dst_object->cred);
1692 		*fork_charge += dst_object->charge;
1693 	} else if ((dst_object->type == OBJT_DEFAULT ||
1694 	    dst_object->type == OBJT_SWAP) &&
1695 	    dst_object->cred == NULL) {
1696 		KASSERT(dst_entry->cred != NULL, ("no cred for entry %p",
1697 		    dst_entry));
1698 		dst_object->cred = dst_entry->cred;
1699 		dst_entry->cred = NULL;
1700 	}
1701 
1702 	/*
1703 	 * If not an upgrade, then enter the mappings in the pmap as
1704 	 * read and/or execute accesses.  Otherwise, enter them as
1705 	 * write accesses.
1706 	 *
1707 	 * A writeable large page mapping is only created if all of
1708 	 * the constituent small page mappings are modified. Marking
1709 	 * PTEs as modified on inception allows promotion to happen
1710 	 * without taking potentially large number of soft faults.
1711 	 */
1712 	if (!upgrade)
1713 		access &= ~VM_PROT_WRITE;
1714 
1715 	/*
1716 	 * Loop through all of the virtual pages within the entry's
1717 	 * range, copying each page from the source object to the
1718 	 * destination object.  Since the source is wired, those pages
1719 	 * must exist.  In contrast, the destination is pageable.
1720 	 * Since the destination object doesn't share any backing storage
1721 	 * with the source object, all of its pages must be dirtied,
1722 	 * regardless of whether they can be written.
1723 	 */
1724 	for (vaddr = dst_entry->start, dst_pindex = 0;
1725 	    vaddr < dst_entry->end;
1726 	    vaddr += PAGE_SIZE, dst_pindex++) {
1727 again:
1728 		/*
1729 		 * Find the page in the source object, and copy it in.
1730 		 * Because the source is wired down, the page will be
1731 		 * in memory.
1732 		 */
1733 		if (src_object != dst_object)
1734 			VM_OBJECT_RLOCK(src_object);
1735 		object = src_object;
1736 		pindex = src_pindex + dst_pindex;
1737 		while ((src_m = vm_page_lookup(object, pindex)) == NULL &&
1738 		    (backing_object = object->backing_object) != NULL) {
1739 			/*
1740 			 * Unless the source mapping is read-only or
1741 			 * it is presently being upgraded from
1742 			 * read-only, the first object in the shadow
1743 			 * chain should provide all of the pages.  In
1744 			 * other words, this loop body should never be
1745 			 * executed when the source mapping is already
1746 			 * read/write.
1747 			 */
1748 			KASSERT((src_entry->protection & VM_PROT_WRITE) == 0 ||
1749 			    upgrade,
1750 			    ("vm_fault_copy_entry: main object missing page"));
1751 
1752 			VM_OBJECT_RLOCK(backing_object);
1753 			pindex += OFF_TO_IDX(object->backing_object_offset);
1754 			if (object != dst_object)
1755 				VM_OBJECT_RUNLOCK(object);
1756 			object = backing_object;
1757 		}
1758 		KASSERT(src_m != NULL, ("vm_fault_copy_entry: page missing"));
1759 
1760 		if (object != dst_object) {
1761 			/*
1762 			 * Allocate a page in the destination object.
1763 			 */
1764 			dst_m = vm_page_alloc(dst_object, (src_object ==
1765 			    dst_object ? src_pindex : 0) + dst_pindex,
1766 			    VM_ALLOC_NORMAL);
1767 			if (dst_m == NULL) {
1768 				VM_OBJECT_WUNLOCK(dst_object);
1769 				VM_OBJECT_RUNLOCK(object);
1770 				vm_wait(dst_object);
1771 				VM_OBJECT_WLOCK(dst_object);
1772 				goto again;
1773 			}
1774 			pmap_copy_page(src_m, dst_m);
1775 			VM_OBJECT_RUNLOCK(object);
1776 			dst_m->dirty = dst_m->valid = src_m->valid;
1777 		} else {
1778 			dst_m = src_m;
1779 			if (vm_page_sleep_if_busy(dst_m, "fltupg"))
1780 				goto again;
1781 			if (dst_m->pindex >= dst_object->size)
1782 				/*
1783 				 * We are upgrading.  Index can occur
1784 				 * out of bounds if the object type is
1785 				 * vnode and the file was truncated.
1786 				 */
1787 				break;
1788 			vm_page_xbusy(dst_m);
1789 		}
1790 		VM_OBJECT_WUNLOCK(dst_object);
1791 
1792 		/*
1793 		 * Enter it in the pmap. If a wired, copy-on-write
1794 		 * mapping is being replaced by a write-enabled
1795 		 * mapping, then wire that new mapping.
1796 		 *
1797 		 * The page can be invalid if the user called
1798 		 * msync(MS_INVALIDATE) or truncated the backing vnode
1799 		 * or shared memory object.  In this case, do not
1800 		 * insert it into pmap, but still do the copy so that
1801 		 * all copies of the wired map entry have similar
1802 		 * backing pages.
1803 		 */
1804 		if (dst_m->valid == VM_PAGE_BITS_ALL) {
1805 			pmap_enter(dst_map->pmap, vaddr, dst_m, prot,
1806 			    access | (upgrade ? PMAP_ENTER_WIRED : 0), 0);
1807 		}
1808 
1809 		/*
1810 		 * Mark it no longer busy, and put it on the active list.
1811 		 */
1812 		VM_OBJECT_WLOCK(dst_object);
1813 
1814 		if (upgrade) {
1815 			if (src_m != dst_m) {
1816 				vm_page_lock(src_m);
1817 				vm_page_unwire(src_m, PQ_INACTIVE);
1818 				vm_page_unlock(src_m);
1819 				vm_page_lock(dst_m);
1820 				vm_page_wire(dst_m);
1821 				vm_page_unlock(dst_m);
1822 			} else {
1823 				KASSERT(vm_page_wired(dst_m),
1824 				    ("dst_m %p is not wired", dst_m));
1825 			}
1826 		} else {
1827 			vm_page_lock(dst_m);
1828 			vm_page_activate(dst_m);
1829 			vm_page_unlock(dst_m);
1830 		}
1831 		vm_page_xunbusy(dst_m);
1832 	}
1833 	VM_OBJECT_WUNLOCK(dst_object);
1834 	if (upgrade) {
1835 		dst_entry->eflags &= ~(MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY);
1836 		vm_object_deallocate(src_object);
1837 	}
1838 }
1839 
1840 /*
1841  * Block entry into the machine-independent layer's page fault handler by
1842  * the calling thread.  Subsequent calls to vm_fault() by that thread will
1843  * return KERN_PROTECTION_FAILURE.  Enable machine-dependent handling of
1844  * spurious page faults.
1845  */
1846 int
vm_fault_disable_pagefaults(void)1847 vm_fault_disable_pagefaults(void)
1848 {
1849 
1850 	return (curthread_pflags_set(TDP_NOFAULTING | TDP_RESETSPUR));
1851 }
1852 
1853 void
vm_fault_enable_pagefaults(int save)1854 vm_fault_enable_pagefaults(int save)
1855 {
1856 
1857 	curthread_pflags_restore(save);
1858 }
1859