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