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