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