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