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