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