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