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