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