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