]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/vm_fault.c
(fault 2/9) Move map lookup into a dedicated function.
[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 static int
751 vm_fault_lookup(struct faultstate *fs)
752 {
753         int result;
754
755         KASSERT(!fs->lookup_still_valid,
756            ("vm_fault_lookup: Map already locked."));
757         result = vm_map_lookup(&fs->map, fs->vaddr, fs->fault_type |
758             VM_PROT_FAULT_LOOKUP, &fs->entry, &fs->first_object,
759             &fs->first_pindex, &fs->prot, &fs->wired);
760         if (result != KERN_SUCCESS) {
761                 unlock_vp(fs);
762                 return (result);
763         }
764
765         fs->map_generation = fs->map->timestamp;
766
767         if (fs->entry->eflags & MAP_ENTRY_NOFAULT) {
768                 panic("%s: fault on nofault entry, addr: %#lx",
769                     __func__, (u_long)fs->vaddr);
770         }
771
772         if (fs->entry->eflags & MAP_ENTRY_IN_TRANSITION &&
773             fs->entry->wiring_thread != curthread) {
774                 vm_map_unlock_read(fs->map);
775                 vm_map_lock(fs->map);
776                 if (vm_map_lookup_entry(fs->map, fs->vaddr, &fs->entry) &&
777                     (fs->entry->eflags & MAP_ENTRY_IN_TRANSITION)) {
778                         unlock_vp(fs);
779                         fs->entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
780                         vm_map_unlock_and_wait(fs->map, 0);
781                 } else
782                         vm_map_unlock(fs->map);
783                 return (KERN_RESOURCE_SHORTAGE);
784         }
785
786         MPASS((fs->entry->eflags & MAP_ENTRY_GUARD) == 0);
787
788         if (fs->wired)
789                 fs->fault_type = fs->prot | (fs->fault_type & VM_PROT_COPY);
790         else
791                 KASSERT((fs->fault_flags & VM_FAULT_WIRE) == 0,
792                     ("!fs->wired && VM_FAULT_WIRE"));
793         fs->lookup_still_valid = true;
794
795         return (KERN_SUCCESS);
796 }
797
798 /*
799  * Wait/Retry if the page is busy.  We have to do this if the page is
800  * either exclusive or shared busy because the vm_pager may be using
801  * read busy for pageouts (and even pageins if it is the vnode pager),
802  * and we could end up trying to pagein and pageout the same page
803  * simultaneously.
804  *
805  * We can theoretically allow the busy case on a read fault if the page
806  * is marked valid, but since such pages are typically already pmap'd,
807  * putting that special case in might be more effort then it is worth.
808  * We cannot under any circumstances mess around with a shared busied
809  * page except, perhaps, to pmap it.
810  */
811 static void
812 vm_fault_busy_sleep(struct faultstate *fs)
813 {
814         /*
815          * Reference the page before unlocking and
816          * sleeping so that the page daemon is less
817          * likely to reclaim it.
818          */
819         vm_page_aflag_set(fs->m, PGA_REFERENCED);
820         if (fs->object != fs->first_object) {
821                 fault_page_release(&fs->first_m);
822                 vm_object_pip_wakeup(fs->first_object);
823         }
824         vm_object_pip_wakeup(fs->object);
825         unlock_map(fs);
826         if (fs->m == vm_page_lookup(fs->object, fs->pindex))
827                 vm_page_busy_sleep(fs->m, "vmpfw", false);
828         else
829                 VM_OBJECT_WUNLOCK(fs->object);
830         VM_CNT_INC(v_intrans);
831         vm_object_deallocate(fs->first_object);
832 }
833
834 int
835 vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
836     int fault_flags, vm_page_t *m_hold)
837 {
838         struct faultstate fs;
839         struct domainset *dset;
840         vm_object_t next_object, retry_object;
841         vm_offset_t e_end, e_start;
842         vm_pindex_t retry_pindex;
843         vm_prot_t retry_prot;
844         int ahead, alloc_req, behind, cluster_offset, faultcount;
845         int nera, oom, result, rv;
846         u_char behavior;
847         bool dead, hardfault, is_first_object_locked;
848
849         VM_CNT_INC(v_vm_faults);
850
851         if ((curthread->td_pflags & TDP_NOFAULTING) != 0)
852                 return (KERN_PROTECTION_FAILURE);
853
854         fs.vp = NULL;
855         fs.vaddr = vaddr;
856         fs.m_hold = m_hold;
857         fs.fault_flags = fault_flags;
858         fs.map = map;
859         fs.lookup_still_valid = false;
860         faultcount = 0;
861         nera = -1;
862         hardfault = false;
863
864 RetryFault:
865         oom = 0;
866 RetryFault_oom:
867         fs.fault_type = fault_type;
868
869         /*
870          * Find the backing store object and offset into it to begin the
871          * search.
872          */
873         result = vm_fault_lookup(&fs);
874         if (result != KERN_SUCCESS) {
875                 if (result == KERN_RESOURCE_SHORTAGE)
876                         goto RetryFault;
877                 return (result);
878         }
879
880         /*
881          * Try to avoid lock contention on the top-level object through
882          * special-case handling of some types of page faults, specifically,
883          * those that are mapping an existing page from the top-level object.
884          * Under this condition, a read lock on the object suffices, allowing
885          * multiple page faults of a similar type to run in parallel.
886          */
887         if (fs.vp == NULL /* avoid locked vnode leak */ &&
888             (fs.fault_flags & (VM_FAULT_WIRE | VM_FAULT_DIRTY)) == 0) {
889                 VM_OBJECT_RLOCK(fs.first_object);
890                 rv = vm_fault_soft_fast(&fs);
891                 if (rv == KERN_SUCCESS)
892                         return (rv);
893                 if (!VM_OBJECT_TRYUPGRADE(fs.first_object)) {
894                         VM_OBJECT_RUNLOCK(fs.first_object);
895                         VM_OBJECT_WLOCK(fs.first_object);
896                 }
897         } else {
898                 VM_OBJECT_WLOCK(fs.first_object);
899         }
900
901         /*
902          * Make a reference to this object to prevent its disposal while we
903          * are messing with it.  Once we have the reference, the map is free
904          * to be diddled.  Since objects reference their shadows (and copies),
905          * they will stay around as well.
906          *
907          * Bump the paging-in-progress count to prevent size changes (e.g. 
908          * truncation operations) during I/O.
909          */
910         vm_object_reference_locked(fs.first_object);
911         vm_object_pip_add(fs.first_object, 1);
912
913         fs.m_cow = fs.m = fs.first_m = NULL;
914
915         /*
916          * Search for the page at object/offset.
917          */
918         fs.object = fs.first_object;
919         fs.pindex = fs.first_pindex;
920         while (TRUE) {
921                 KASSERT(fs.m == NULL,
922                     ("page still set %p at loop start", fs.m));
923                 /*
924                  * If the object is marked for imminent termination,
925                  * we retry here, since the collapse pass has raced
926                  * with us.  Otherwise, if we see terminally dead
927                  * object, return fail.
928                  */
929                 if ((fs.object->flags & OBJ_DEAD) != 0) {
930                         dead = fs.object->type == OBJT_DEAD;
931                         unlock_and_deallocate(&fs);
932                         if (dead)
933                                 return (KERN_PROTECTION_FAILURE);
934                         pause("vmf_de", 1);
935                         goto RetryFault;
936                 }
937
938                 /*
939                  * See if page is resident
940                  */
941                 fs.m = vm_page_lookup(fs.object, fs.pindex);
942                 if (fs.m != NULL) {
943                         if (vm_page_tryxbusy(fs.m) == 0) {
944                                 vm_fault_busy_sleep(&fs);
945                                 goto RetryFault;
946                         }
947
948                         /*
949                          * The page is marked busy for other processes and the
950                          * pagedaemon.  If it still isn't completely valid
951                          * (readable), jump to readrest, else break-out ( we
952                          * found the page ).
953                          */
954                         if (!vm_page_all_valid(fs.m))
955                                 goto readrest;
956                         VM_OBJECT_WUNLOCK(fs.object);
957                         break; /* break to PAGE HAS BEEN FOUND. */
958                 }
959                 KASSERT(fs.m == NULL, ("fs.m should be NULL, not %p", fs.m));
960                 VM_OBJECT_ASSERT_WLOCKED(fs.object);
961
962                 /*
963                  * Page is not resident.  If the pager might contain the page
964                  * or this is the beginning of the search, allocate a new
965                  * page.  (Default objects are zero-fill, so there is no real
966                  * pager for them.)
967                  */
968                 if (fs.object->type != OBJT_DEFAULT ||
969                     fs.object == fs.first_object) {
970                         if ((fs.object->flags & OBJ_SIZEVNLOCK) != 0) {
971                                 rv = vm_fault_lock_vnode(&fs, true);
972                                 MPASS(rv == KERN_SUCCESS ||
973                                     rv == KERN_RESOURCE_SHORTAGE);
974                                 if (rv == KERN_RESOURCE_SHORTAGE)
975                                         goto RetryFault;
976                         }
977                         if (fs.pindex >= fs.object->size) {
978                                 unlock_and_deallocate(&fs);
979                                 return (KERN_OUT_OF_BOUNDS);
980                         }
981
982                         if (fs.object == fs.first_object &&
983                             (fs.first_object->flags & OBJ_POPULATE) != 0 &&
984                             fs.first_object->shadow_count == 0) {
985                                 rv = vm_fault_populate(&fs);
986                                 switch (rv) {
987                                 case KERN_SUCCESS:
988                                 case KERN_FAILURE:
989                                         unlock_and_deallocate(&fs);
990                                         return (rv);
991                                 case KERN_RESOURCE_SHORTAGE:
992                                         unlock_and_deallocate(&fs);
993                                         goto RetryFault;
994                                 case KERN_NOT_RECEIVER:
995                                         /*
996                                          * Pager's populate() method
997                                          * returned VM_PAGER_BAD.
998                                          */
999                                         break;
1000                                 default:
1001                                         panic("inconsistent return codes");
1002                                 }
1003                         }
1004
1005                         /*
1006                          * Allocate a new page for this object/offset pair.
1007                          *
1008                          * Unlocked read of the p_flag is harmless. At
1009                          * worst, the P_KILLED might be not observed
1010                          * there, and allocation can fail, causing
1011                          * restart and new reading of the p_flag.
1012                          */
1013                         dset = fs.object->domain.dr_policy;
1014                         if (dset == NULL)
1015                                 dset = curthread->td_domain.dr_policy;
1016                         if (!vm_page_count_severe_set(&dset->ds_mask) ||
1017                             P_KILLED(curproc)) {
1018 #if VM_NRESERVLEVEL > 0
1019                                 vm_object_color(fs.object, atop(vaddr) -
1020                                     fs.pindex);
1021 #endif
1022                                 alloc_req = P_KILLED(curproc) ?
1023                                     VM_ALLOC_SYSTEM : VM_ALLOC_NORMAL;
1024                                 if (fs.object->type != OBJT_VNODE &&
1025                                     fs.object->backing_object == NULL)
1026                                         alloc_req |= VM_ALLOC_ZERO;
1027                                 fs.m = vm_page_alloc(fs.object, fs.pindex,
1028                                     alloc_req);
1029                         }
1030                         if (fs.m == NULL) {
1031                                 unlock_and_deallocate(&fs);
1032                                 if (vm_pfault_oom_attempts < 0 ||
1033                                     oom < vm_pfault_oom_attempts) {
1034                                         oom++;
1035                                         vm_waitpfault(dset,
1036                                             vm_pfault_oom_wait * hz);
1037                                         goto RetryFault_oom;
1038                                 }
1039                                 if (bootverbose)
1040                                         printf(
1041         "proc %d (%s) failed to alloc page on fault, starting OOM\n",
1042                                             curproc->p_pid, curproc->p_comm);
1043                                 vm_pageout_oom(VM_OOM_MEM_PF);
1044                                 goto RetryFault;
1045                         }
1046                 }
1047
1048 readrest:
1049                 /*
1050                  * Default objects have no pager so no exclusive busy exists
1051                  * to protect this page in the chain.  Skip to the next
1052                  * object without dropping the lock to preserve atomicity of
1053                  * shadow faults.
1054                  */
1055                 if (fs.object->type == OBJT_DEFAULT)
1056                         goto next;
1057
1058                 /*
1059                  * At this point, we have either allocated a new page or found
1060                  * an existing page that is only partially valid.
1061                  *
1062                  * We hold a reference on the current object and the page is
1063                  * exclusive busied.  The exclusive busy prevents simultaneous
1064                  * faults and collapses while the object lock is dropped.
1065                  */
1066                 VM_OBJECT_WUNLOCK(fs.object);
1067
1068                 /*
1069                  * If the pager for the current object might have the page,
1070                  * then determine the number of additional pages to read and
1071                  * potentially reprioritize previously read pages for earlier
1072                  * reclamation.  These operations should only be performed
1073                  * once per page fault.  Even if the current pager doesn't
1074                  * have the page, the number of additional pages to read will
1075                  * apply to subsequent objects in the shadow chain.
1076                  */
1077                 if (nera == -1 && !P_KILLED(curproc)) {
1078                         nera = vm_fault_readahead(&fs);
1079                         /*
1080                          * Prepare for unlocking the map.  Save the map
1081                          * entry's start and end addresses, which are used to
1082                          * optimize the size of the pager operation below.
1083                          * Even if the map entry's addresses change after
1084                          * unlocking the map, using the saved addresses is
1085                          * safe.
1086                          */
1087                         e_start = fs.entry->start;
1088                         e_end = fs.entry->end;
1089                         behavior = vm_map_entry_behavior(fs.entry);
1090                 }
1091
1092                 /*
1093                  * Call the pager to retrieve the page if there is a chance
1094                  * that the pager has it, and potentially retrieve additional
1095                  * pages at the same time.
1096                  */
1097                 if (fs.object->type != OBJT_DEFAULT) {
1098                         /*
1099                          * Release the map lock before locking the vnode or
1100                          * sleeping in the pager.  (If the current object has
1101                          * a shadow, then an earlier iteration of this loop
1102                          * may have already unlocked the map.)
1103                          */
1104                         unlock_map(&fs);
1105
1106                         rv = vm_fault_lock_vnode(&fs, false);
1107                         MPASS(rv == KERN_SUCCESS ||
1108                             rv == KERN_RESOURCE_SHORTAGE);
1109                         if (rv == KERN_RESOURCE_SHORTAGE)
1110                                 goto RetryFault;
1111                         KASSERT(fs.vp == NULL || !fs.map->system_map,
1112                             ("vm_fault: vnode-backed object mapped by system map"));
1113
1114                         /*
1115                          * Page in the requested page and hint the pager,
1116                          * that it may bring up surrounding pages.
1117                          */
1118                         if (nera == -1 || behavior == MAP_ENTRY_BEHAV_RANDOM ||
1119                             P_KILLED(curproc)) {
1120                                 behind = 0;
1121                                 ahead = 0;
1122                         } else {
1123                                 /* Is this a sequential fault? */
1124                                 if (nera > 0) {
1125                                         behind = 0;
1126                                         ahead = nera;
1127                                 } else {
1128                                         /*
1129                                          * Request a cluster of pages that is
1130                                          * aligned to a VM_FAULT_READ_DEFAULT
1131                                          * page offset boundary within the
1132                                          * object.  Alignment to a page offset
1133                                          * boundary is more likely to coincide
1134                                          * with the underlying file system
1135                                          * block than alignment to a virtual
1136                                          * address boundary.
1137                                          */
1138                                         cluster_offset = fs.pindex %
1139                                             VM_FAULT_READ_DEFAULT;
1140                                         behind = ulmin(cluster_offset,
1141                                             atop(vaddr - e_start));
1142                                         ahead = VM_FAULT_READ_DEFAULT - 1 -
1143                                             cluster_offset;
1144                                 }
1145                                 ahead = ulmin(ahead, atop(e_end - vaddr) - 1);
1146                         }
1147                         rv = vm_pager_get_pages(fs.object, &fs.m, 1,
1148                             &behind, &ahead);
1149                         if (rv == VM_PAGER_OK) {
1150                                 faultcount = behind + 1 + ahead;
1151                                 hardfault = true;
1152                                 break; /* break to PAGE HAS BEEN FOUND. */
1153                         }
1154                         VM_OBJECT_WLOCK(fs.object);
1155                         if (rv == VM_PAGER_ERROR)
1156                                 printf("vm_fault: pager read error, pid %d (%s)\n",
1157                                     curproc->p_pid, curproc->p_comm);
1158
1159                         /*
1160                          * If an I/O error occurred or the requested page was
1161                          * outside the range of the pager, clean up and return
1162                          * an error.
1163                          */
1164                         if (rv == VM_PAGER_ERROR || rv == VM_PAGER_BAD) {
1165                                 fault_page_free(&fs.m);
1166                                 unlock_and_deallocate(&fs);
1167                                 return (KERN_OUT_OF_BOUNDS);
1168                         }
1169
1170                 }
1171
1172 next:
1173                 /*
1174                  * The requested page does not exist at this object/
1175                  * offset.  Remove the invalid page from the object,
1176                  * waking up anyone waiting for it, and continue on to
1177                  * the next object.  However, if this is the top-level
1178                  * object, we must leave the busy page in place to
1179                  * prevent another process from rushing past us, and
1180                  * inserting the page in that object at the same time
1181                  * that we are.
1182                  */
1183                 if (fs.object == fs.first_object) {
1184                         fs.first_m = fs.m;
1185                         fs.m = NULL;
1186                 } else
1187                         fault_page_free(&fs.m);
1188
1189                 /*
1190                  * Move on to the next object.  Lock the next object before
1191                  * unlocking the current one.
1192                  */
1193                 VM_OBJECT_ASSERT_WLOCKED(fs.object);
1194                 next_object = fs.object->backing_object;
1195                 if (next_object == NULL) {
1196                         /*
1197                          * If there's no object left, fill the page in the top
1198                          * object with zeros.
1199                          */
1200                         VM_OBJECT_WUNLOCK(fs.object);
1201                         if (fs.object != fs.first_object) {
1202                                 vm_object_pip_wakeup(fs.object);
1203                                 fs.object = fs.first_object;
1204                                 fs.pindex = fs.first_pindex;
1205                         }
1206                         MPASS(fs.first_m != NULL);
1207                         MPASS(fs.m == NULL);
1208                         fs.m = fs.first_m;
1209                         fs.first_m = NULL;
1210
1211                         /*
1212                          * Zero the page if necessary and mark it valid.
1213                          */
1214                         if ((fs.m->flags & PG_ZERO) == 0) {
1215                                 pmap_zero_page(fs.m);
1216                         } else {
1217                                 VM_CNT_INC(v_ozfod);
1218                         }
1219                         VM_CNT_INC(v_zfod);
1220                         vm_page_valid(fs.m);
1221                         /* Don't try to prefault neighboring pages. */
1222                         faultcount = 1;
1223                         break;  /* break to PAGE HAS BEEN FOUND. */
1224                 } else {
1225                         MPASS(fs.first_m != NULL);
1226                         KASSERT(fs.object != next_object,
1227                             ("object loop %p", next_object));
1228                         VM_OBJECT_WLOCK(next_object);
1229                         vm_object_pip_add(next_object, 1);
1230                         if (fs.object != fs.first_object)
1231                                 vm_object_pip_wakeup(fs.object);
1232                         fs.pindex +=
1233                             OFF_TO_IDX(fs.object->backing_object_offset);
1234                         VM_OBJECT_WUNLOCK(fs.object);
1235                         fs.object = next_object;
1236                 }
1237         }
1238
1239         /*
1240          * PAGE HAS BEEN FOUND.  A valid page has been found and exclusively
1241          * busied.  The object lock must no longer be held.
1242          */
1243         vm_page_assert_xbusied(fs.m);
1244         VM_OBJECT_ASSERT_UNLOCKED(fs.object);
1245
1246         /*
1247          * If the page is being written, but isn't already owned by the
1248          * top-level object, we have to copy it into a new page owned by the
1249          * top-level object.
1250          */
1251         if (fs.object != fs.first_object) {
1252                 /*
1253                  * We only really need to copy if we want to write it.
1254                  */
1255                 if ((fs.fault_type & (VM_PROT_COPY | VM_PROT_WRITE)) != 0) {
1256                         /*
1257                          * This allows pages to be virtually copied from a 
1258                          * backing_object into the first_object, where the 
1259                          * backing object has no other refs to it, and cannot
1260                          * gain any more refs.  Instead of a bcopy, we just 
1261                          * move the page from the backing object to the 
1262                          * first object.  Note that we must mark the page 
1263                          * dirty in the first object so that it will go out 
1264                          * to swap when needed.
1265                          */
1266                         is_first_object_locked = false;
1267                         if (
1268                             /*
1269                              * Only one shadow object
1270                              */
1271                             fs.object->shadow_count == 1 &&
1272                             /*
1273                              * No COW refs, except us
1274                              */
1275                             fs.object->ref_count == 1 &&
1276                             /*
1277                              * No one else can look this object up
1278                              */
1279                             fs.object->handle == NULL &&
1280                             /*
1281                              * No other ways to look the object up
1282                              */
1283                             (fs.object->flags & OBJ_ANON) != 0 &&
1284                             (is_first_object_locked = VM_OBJECT_TRYWLOCK(fs.first_object)) &&
1285                             /*
1286                              * We don't chase down the shadow chain
1287                              */
1288                             fs.object == fs.first_object->backing_object &&
1289                             VM_OBJECT_TRYWLOCK(fs.object)) {
1290
1291                                 /*
1292                                  * Remove but keep xbusy for replace.  fs.m is
1293                                  * moved into fs.first_object and left busy
1294                                  * while fs.first_m is conditionally freed.
1295                                  */
1296                                 vm_page_remove_xbusy(fs.m);
1297                                 vm_page_replace(fs.m, fs.first_object,
1298                                     fs.first_pindex, fs.first_m);
1299                                 vm_page_dirty(fs.m);
1300 #if VM_NRESERVLEVEL > 0
1301                                 /*
1302                                  * Rename the reservation.
1303                                  */
1304                                 vm_reserv_rename(fs.m, fs.first_object,
1305                                     fs.object, OFF_TO_IDX(
1306                                     fs.first_object->backing_object_offset));
1307 #endif
1308                                 VM_OBJECT_WUNLOCK(fs.object);
1309                                 VM_OBJECT_WUNLOCK(fs.first_object);
1310                                 fs.first_m = fs.m;
1311                                 fs.m = NULL;
1312                                 VM_CNT_INC(v_cow_optim);
1313                         } else {
1314                                 if (is_first_object_locked)
1315                                         VM_OBJECT_WUNLOCK(fs.first_object);
1316                                 /*
1317                                  * Oh, well, lets copy it.
1318                                  */
1319                                 pmap_copy_page(fs.m, fs.first_m);
1320                                 vm_page_valid(fs.first_m);
1321                                 if (fs.wired && (fs.fault_flags &
1322                                     VM_FAULT_WIRE) == 0) {
1323                                         vm_page_wire(fs.first_m);
1324                                         vm_page_unwire(fs.m, PQ_INACTIVE);
1325                                 }
1326                                 /*
1327                                  * Save the cow page to be released after
1328                                  * pmap_enter is complete.
1329                                  */
1330                                 fs.m_cow = fs.m;
1331                                 fs.m = NULL;
1332                         }
1333                         /*
1334                          * fs.object != fs.first_object due to above 
1335                          * conditional
1336                          */
1337                         vm_object_pip_wakeup(fs.object);
1338
1339                         /*
1340                          * We only try to prefault read-only mappings to the
1341                          * neighboring pages when this copy-on-write fault is
1342                          * a hard fault.  In other cases, trying to prefault
1343                          * is typically wasted effort.
1344                          */
1345                         if (faultcount == 0)
1346                                 faultcount = 1;
1347
1348                         /*
1349                          * Only use the new page below...
1350                          */
1351                         fs.object = fs.first_object;
1352                         fs.pindex = fs.first_pindex;
1353                         fs.m = fs.first_m;
1354                         VM_CNT_INC(v_cow_faults);
1355                         curthread->td_cow++;
1356                 } else {
1357                         fs.prot &= ~VM_PROT_WRITE;
1358                 }
1359         }
1360
1361         /*
1362          * We must verify that the maps have not changed since our last
1363          * lookup.
1364          */
1365         if (!fs.lookup_still_valid) {
1366                 if (!vm_map_trylock_read(fs.map)) {
1367                         fault_deallocate(&fs);
1368                         goto RetryFault;
1369                 }
1370                 fs.lookup_still_valid = true;
1371                 if (fs.map->timestamp != fs.map_generation) {
1372                         result = vm_map_lookup_locked(&fs.map, vaddr, fs.fault_type,
1373                             &fs.entry, &retry_object, &retry_pindex, &retry_prot,
1374                             &fs.wired);
1375
1376                         /*
1377                          * If we don't need the page any longer, put it on the inactive
1378                          * list (the easiest thing to do here).  If no one needs it,
1379                          * pageout will grab it eventually.
1380                          */
1381                         if (result != KERN_SUCCESS) {
1382                                 fault_deallocate(&fs);
1383
1384                                 /*
1385                                  * If retry of map lookup would have blocked then
1386                                  * retry fault from start.
1387                                  */
1388                                 if (result == KERN_FAILURE)
1389                                         goto RetryFault;
1390                                 return (result);
1391                         }
1392                         if ((retry_object != fs.first_object) ||
1393                             (retry_pindex != fs.first_pindex)) {
1394                                 fault_deallocate(&fs);
1395                                 goto RetryFault;
1396                         }
1397
1398                         /*
1399                          * Check whether the protection has changed or the object has
1400                          * been copied while we left the map unlocked. Changing from
1401                          * read to write permission is OK - we leave the page
1402                          * write-protected, and catch the write fault. Changing from
1403                          * write to read permission means that we can't mark the page
1404                          * write-enabled after all.
1405                          */
1406                         fs.prot &= retry_prot;
1407                         fs.fault_type &= retry_prot;
1408                         if (fs.prot == 0) {
1409                                 fault_deallocate(&fs);
1410                                 goto RetryFault;
1411                         }
1412
1413                         /* Reassert because wired may have changed. */
1414                         KASSERT(fs.wired || (fs.fault_flags & VM_FAULT_WIRE) == 0,
1415                             ("!wired && VM_FAULT_WIRE"));
1416                 }
1417         }
1418         VM_OBJECT_ASSERT_UNLOCKED(fs.object);
1419
1420         /*
1421          * If the page was filled by a pager, save the virtual address that
1422          * should be faulted on next under a sequential access pattern to the
1423          * map entry.  A read lock on the map suffices to update this address
1424          * safely.
1425          */
1426         if (hardfault)
1427                 fs.entry->next_read = vaddr + ptoa(ahead) + PAGE_SIZE;
1428
1429         /*
1430          * Page must be completely valid or it is not fit to
1431          * map into user space.  vm_pager_get_pages() ensures this.
1432          */
1433         vm_page_assert_xbusied(fs.m);
1434         KASSERT(vm_page_all_valid(fs.m),
1435             ("vm_fault: page %p partially invalid", fs.m));
1436
1437         vm_fault_dirty(&fs, fs.m);
1438
1439         /*
1440          * Put this page into the physical map.  We had to do the unlock above
1441          * because pmap_enter() may sleep.  We don't put the page
1442          * back on the active queue until later so that the pageout daemon
1443          * won't find it (yet).
1444          */
1445         pmap_enter(fs.map->pmap, vaddr, fs.m, fs.prot,
1446             fs.fault_type | (fs.wired ? PMAP_ENTER_WIRED : 0), 0);
1447         if (faultcount != 1 && (fs.fault_flags & VM_FAULT_WIRE) == 0 &&
1448             fs.wired == 0)
1449                 vm_fault_prefault(&fs, vaddr,
1450                     faultcount > 0 ? behind : PFBAK,
1451                     faultcount > 0 ? ahead : PFFOR, false);
1452
1453         /*
1454          * If the page is not wired down, then put it where the pageout daemon
1455          * can find it.
1456          */
1457         if ((fs.fault_flags & VM_FAULT_WIRE) != 0)
1458                 vm_page_wire(fs.m);
1459         else
1460                 vm_page_activate(fs.m);
1461         if (fs.m_hold != NULL) {
1462                 (*fs.m_hold) = fs.m;
1463                 vm_page_wire(fs.m);
1464         }
1465         vm_page_xunbusy(fs.m);
1466         fs.m = NULL;
1467
1468         /*
1469          * Unlock everything, and return
1470          */
1471         fault_deallocate(&fs);
1472         if (hardfault) {
1473                 VM_CNT_INC(v_io_faults);
1474                 curthread->td_ru.ru_majflt++;
1475 #ifdef RACCT
1476                 if (racct_enable && fs.object->type == OBJT_VNODE) {
1477                         PROC_LOCK(curproc);
1478                         if ((fs.fault_type & (VM_PROT_COPY | VM_PROT_WRITE)) != 0) {
1479                                 racct_add_force(curproc, RACCT_WRITEBPS,
1480                                     PAGE_SIZE + behind * PAGE_SIZE);
1481                                 racct_add_force(curproc, RACCT_WRITEIOPS, 1);
1482                         } else {
1483                                 racct_add_force(curproc, RACCT_READBPS,
1484                                     PAGE_SIZE + ahead * PAGE_SIZE);
1485                                 racct_add_force(curproc, RACCT_READIOPS, 1);
1486                         }
1487                         PROC_UNLOCK(curproc);
1488                 }
1489 #endif
1490         } else 
1491                 curthread->td_ru.ru_minflt++;
1492
1493         return (KERN_SUCCESS);
1494 }
1495
1496 /*
1497  * Speed up the reclamation of pages that precede the faulting pindex within
1498  * the first object of the shadow chain.  Essentially, perform the equivalent
1499  * to madvise(..., MADV_DONTNEED) on a large cluster of pages that precedes
1500  * the faulting pindex by the cluster size when the pages read by vm_fault()
1501  * cross a cluster-size boundary.  The cluster size is the greater of the
1502  * smallest superpage size and VM_FAULT_DONTNEED_MIN.
1503  *
1504  * When "fs->first_object" is a shadow object, the pages in the backing object
1505  * that precede the faulting pindex are deactivated by vm_fault().  So, this
1506  * function must only be concerned with pages in the first object.
1507  */
1508 static void
1509 vm_fault_dontneed(const struct faultstate *fs, vm_offset_t vaddr, int ahead)
1510 {
1511         vm_map_entry_t entry;
1512         vm_object_t first_object, object;
1513         vm_offset_t end, start;
1514         vm_page_t m, m_next;
1515         vm_pindex_t pend, pstart;
1516         vm_size_t size;
1517
1518         object = fs->object;
1519         VM_OBJECT_ASSERT_UNLOCKED(object);
1520         first_object = fs->first_object;
1521         /* Neither fictitious nor unmanaged pages can be reclaimed. */
1522         if ((first_object->flags & (OBJ_FICTITIOUS | OBJ_UNMANAGED)) == 0) {
1523                 VM_OBJECT_RLOCK(first_object);
1524                 size = VM_FAULT_DONTNEED_MIN;
1525                 if (MAXPAGESIZES > 1 && size < pagesizes[1])
1526                         size = pagesizes[1];
1527                 end = rounddown2(vaddr, size);
1528                 if (vaddr - end >= size - PAGE_SIZE - ptoa(ahead) &&
1529                     (entry = fs->entry)->start < end) {
1530                         if (end - entry->start < size)
1531                                 start = entry->start;
1532                         else
1533                                 start = end - size;
1534                         pmap_advise(fs->map->pmap, start, end, MADV_DONTNEED);
1535                         pstart = OFF_TO_IDX(entry->offset) + atop(start -
1536                             entry->start);
1537                         m_next = vm_page_find_least(first_object, pstart);
1538                         pend = OFF_TO_IDX(entry->offset) + atop(end -
1539                             entry->start);
1540                         while ((m = m_next) != NULL && m->pindex < pend) {
1541                                 m_next = TAILQ_NEXT(m, listq);
1542                                 if (!vm_page_all_valid(m) ||
1543                                     vm_page_busied(m))
1544                                         continue;
1545
1546                                 /*
1547                                  * Don't clear PGA_REFERENCED, since it would
1548                                  * likely represent a reference by a different
1549                                  * process.
1550                                  *
1551                                  * Typically, at this point, prefetched pages
1552                                  * are still in the inactive queue.  Only
1553                                  * pages that triggered page faults are in the
1554                                  * active queue.  The test for whether the page
1555                                  * is in the inactive queue is racy; in the
1556                                  * worst case we will requeue the page
1557                                  * unnecessarily.
1558                                  */
1559                                 if (!vm_page_inactive(m))
1560                                         vm_page_deactivate(m);
1561                         }
1562                 }
1563                 VM_OBJECT_RUNLOCK(first_object);
1564         }
1565 }
1566
1567 /*
1568  * vm_fault_prefault provides a quick way of clustering
1569  * pagefaults into a processes address space.  It is a "cousin"
1570  * of vm_map_pmap_enter, except it runs at page fault time instead
1571  * of mmap time.
1572  */
1573 static void
1574 vm_fault_prefault(const struct faultstate *fs, vm_offset_t addra,
1575     int backward, int forward, bool obj_locked)
1576 {
1577         pmap_t pmap;
1578         vm_map_entry_t entry;
1579         vm_object_t backing_object, lobject;
1580         vm_offset_t addr, starta;
1581         vm_pindex_t pindex;
1582         vm_page_t m;
1583         int i;
1584
1585         pmap = fs->map->pmap;
1586         if (pmap != vmspace_pmap(curthread->td_proc->p_vmspace))
1587                 return;
1588
1589         entry = fs->entry;
1590
1591         if (addra < backward * PAGE_SIZE) {
1592                 starta = entry->start;
1593         } else {
1594                 starta = addra - backward * PAGE_SIZE;
1595                 if (starta < entry->start)
1596                         starta = entry->start;
1597         }
1598
1599         /*
1600          * Generate the sequence of virtual addresses that are candidates for
1601          * prefaulting in an outward spiral from the faulting virtual address,
1602          * "addra".  Specifically, the sequence is "addra - PAGE_SIZE", "addra
1603          * + PAGE_SIZE", "addra - 2 * PAGE_SIZE", "addra + 2 * PAGE_SIZE", ...
1604          * If the candidate address doesn't have a backing physical page, then
1605          * the loop immediately terminates.
1606          */
1607         for (i = 0; i < 2 * imax(backward, forward); i++) {
1608                 addr = addra + ((i >> 1) + 1) * ((i & 1) == 0 ? -PAGE_SIZE :
1609                     PAGE_SIZE);
1610                 if (addr > addra + forward * PAGE_SIZE)
1611                         addr = 0;
1612
1613                 if (addr < starta || addr >= entry->end)
1614                         continue;
1615
1616                 if (!pmap_is_prefaultable(pmap, addr))
1617                         continue;
1618
1619                 pindex = ((addr - entry->start) + entry->offset) >> PAGE_SHIFT;
1620                 lobject = entry->object.vm_object;
1621                 if (!obj_locked)
1622                         VM_OBJECT_RLOCK(lobject);
1623                 while ((m = vm_page_lookup(lobject, pindex)) == NULL &&
1624                     lobject->type == OBJT_DEFAULT &&
1625                     (backing_object = lobject->backing_object) != NULL) {
1626                         KASSERT((lobject->backing_object_offset & PAGE_MASK) ==
1627                             0, ("vm_fault_prefault: unaligned object offset"));
1628                         pindex += lobject->backing_object_offset >> PAGE_SHIFT;
1629                         VM_OBJECT_RLOCK(backing_object);
1630                         if (!obj_locked || lobject != entry->object.vm_object)
1631                                 VM_OBJECT_RUNLOCK(lobject);
1632                         lobject = backing_object;
1633                 }
1634                 if (m == NULL) {
1635                         if (!obj_locked || lobject != entry->object.vm_object)
1636                                 VM_OBJECT_RUNLOCK(lobject);
1637                         break;
1638                 }
1639                 if (vm_page_all_valid(m) &&
1640                     (m->flags & PG_FICTITIOUS) == 0)
1641                         pmap_enter_quick(pmap, addr, m, entry->protection);
1642                 if (!obj_locked || lobject != entry->object.vm_object)
1643                         VM_OBJECT_RUNLOCK(lobject);
1644         }
1645 }
1646
1647 /*
1648  * Hold each of the physical pages that are mapped by the specified range of
1649  * virtual addresses, ["addr", "addr" + "len"), if those mappings are valid
1650  * and allow the specified types of access, "prot".  If all of the implied
1651  * pages are successfully held, then the number of held pages is returned
1652  * together with pointers to those pages in the array "ma".  However, if any
1653  * of the pages cannot be held, -1 is returned.
1654  */
1655 int
1656 vm_fault_quick_hold_pages(vm_map_t map, vm_offset_t addr, vm_size_t len,
1657     vm_prot_t prot, vm_page_t *ma, int max_count)
1658 {
1659         vm_offset_t end, va;
1660         vm_page_t *mp;
1661         int count;
1662         boolean_t pmap_failed;
1663
1664         if (len == 0)
1665                 return (0);
1666         end = round_page(addr + len);
1667         addr = trunc_page(addr);
1668
1669         /*
1670          * Check for illegal addresses.
1671          */
1672         if (addr < vm_map_min(map) || addr > end || end > vm_map_max(map))
1673                 return (-1);
1674
1675         if (atop(end - addr) > max_count)
1676                 panic("vm_fault_quick_hold_pages: count > max_count");
1677         count = atop(end - addr);
1678
1679         /*
1680          * Most likely, the physical pages are resident in the pmap, so it is
1681          * faster to try pmap_extract_and_hold() first.
1682          */
1683         pmap_failed = FALSE;
1684         for (mp = ma, va = addr; va < end; mp++, va += PAGE_SIZE) {
1685                 *mp = pmap_extract_and_hold(map->pmap, va, prot);
1686                 if (*mp == NULL)
1687                         pmap_failed = TRUE;
1688                 else if ((prot & VM_PROT_WRITE) != 0 &&
1689                     (*mp)->dirty != VM_PAGE_BITS_ALL) {
1690                         /*
1691                          * Explicitly dirty the physical page.  Otherwise, the
1692                          * caller's changes may go unnoticed because they are
1693                          * performed through an unmanaged mapping or by a DMA
1694                          * operation.
1695                          *
1696                          * The object lock is not held here.
1697                          * See vm_page_clear_dirty_mask().
1698                          */
1699                         vm_page_dirty(*mp);
1700                 }
1701         }
1702         if (pmap_failed) {
1703                 /*
1704                  * One or more pages could not be held by the pmap.  Either no
1705                  * page was mapped at the specified virtual address or that
1706                  * mapping had insufficient permissions.  Attempt to fault in
1707                  * and hold these pages.
1708                  *
1709                  * If vm_fault_disable_pagefaults() was called,
1710                  * i.e., TDP_NOFAULTING is set, we must not sleep nor
1711                  * acquire MD VM locks, which means we must not call
1712                  * vm_fault().  Some (out of tree) callers mark
1713                  * too wide a code area with vm_fault_disable_pagefaults()
1714                  * already, use the VM_PROT_QUICK_NOFAULT flag to request
1715                  * the proper behaviour explicitly.
1716                  */
1717                 if ((prot & VM_PROT_QUICK_NOFAULT) != 0 &&
1718                     (curthread->td_pflags & TDP_NOFAULTING) != 0)
1719                         goto error;
1720                 for (mp = ma, va = addr; va < end; mp++, va += PAGE_SIZE)
1721                         if (*mp == NULL && vm_fault(map, va, prot,
1722                             VM_FAULT_NORMAL, mp) != KERN_SUCCESS)
1723                                 goto error;
1724         }
1725         return (count);
1726 error:  
1727         for (mp = ma; mp < ma + count; mp++)
1728                 if (*mp != NULL)
1729                         vm_page_unwire(*mp, PQ_INACTIVE);
1730         return (-1);
1731 }
1732
1733 /*
1734  *      Routine:
1735  *              vm_fault_copy_entry
1736  *      Function:
1737  *              Create new shadow object backing dst_entry with private copy of
1738  *              all underlying pages. When src_entry is equal to dst_entry,
1739  *              function implements COW for wired-down map entry. Otherwise,
1740  *              it forks wired entry into dst_map.
1741  *
1742  *      In/out conditions:
1743  *              The source and destination maps must be locked for write.
1744  *              The source map entry must be wired down (or be a sharing map
1745  *              entry corresponding to a main map entry that is wired down).
1746  */
1747 void
1748 vm_fault_copy_entry(vm_map_t dst_map, vm_map_t src_map,
1749     vm_map_entry_t dst_entry, vm_map_entry_t src_entry,
1750     vm_ooffset_t *fork_charge)
1751 {
1752         vm_object_t backing_object, dst_object, object, src_object;
1753         vm_pindex_t dst_pindex, pindex, src_pindex;
1754         vm_prot_t access, prot;
1755         vm_offset_t vaddr;
1756         vm_page_t dst_m;
1757         vm_page_t src_m;
1758         boolean_t upgrade;
1759
1760 #ifdef  lint
1761         src_map++;
1762 #endif  /* lint */
1763
1764         upgrade = src_entry == dst_entry;
1765         access = prot = dst_entry->protection;
1766
1767         src_object = src_entry->object.vm_object;
1768         src_pindex = OFF_TO_IDX(src_entry->offset);
1769
1770         if (upgrade && (dst_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) {
1771                 dst_object = src_object;
1772                 vm_object_reference(dst_object);
1773         } else {
1774                 /*
1775                  * Create the top-level object for the destination entry.
1776                  * Doesn't actually shadow anything - we copy the pages
1777                  * directly.
1778                  */
1779                 dst_object = vm_object_allocate_anon(atop(dst_entry->end -
1780                     dst_entry->start), NULL, NULL, 0);
1781 #if VM_NRESERVLEVEL > 0
1782                 dst_object->flags |= OBJ_COLORED;
1783                 dst_object->pg_color = atop(dst_entry->start);
1784 #endif
1785                 dst_object->domain = src_object->domain;
1786                 dst_object->charge = dst_entry->end - dst_entry->start;
1787         }
1788
1789         VM_OBJECT_WLOCK(dst_object);
1790         KASSERT(upgrade || dst_entry->object.vm_object == NULL,
1791             ("vm_fault_copy_entry: vm_object not NULL"));
1792         if (src_object != dst_object) {
1793                 dst_entry->object.vm_object = dst_object;
1794                 dst_entry->offset = 0;
1795                 dst_entry->eflags &= ~MAP_ENTRY_VN_EXEC;
1796         }
1797         if (fork_charge != NULL) {
1798                 KASSERT(dst_entry->cred == NULL,
1799                     ("vm_fault_copy_entry: leaked swp charge"));
1800                 dst_object->cred = curthread->td_ucred;
1801                 crhold(dst_object->cred);
1802                 *fork_charge += dst_object->charge;
1803         } else if ((dst_object->type == OBJT_DEFAULT ||
1804             dst_object->type == OBJT_SWAP) &&
1805             dst_object->cred == NULL) {
1806                 KASSERT(dst_entry->cred != NULL, ("no cred for entry %p",
1807                     dst_entry));
1808                 dst_object->cred = dst_entry->cred;
1809                 dst_entry->cred = NULL;
1810         }
1811
1812         /*
1813          * If not an upgrade, then enter the mappings in the pmap as
1814          * read and/or execute accesses.  Otherwise, enter them as
1815          * write accesses.
1816          *
1817          * A writeable large page mapping is only created if all of
1818          * the constituent small page mappings are modified. Marking
1819          * PTEs as modified on inception allows promotion to happen
1820          * without taking potentially large number of soft faults.
1821          */
1822         if (!upgrade)
1823                 access &= ~VM_PROT_WRITE;
1824
1825         /*
1826          * Loop through all of the virtual pages within the entry's
1827          * range, copying each page from the source object to the
1828          * destination object.  Since the source is wired, those pages
1829          * must exist.  In contrast, the destination is pageable.
1830          * Since the destination object doesn't share any backing storage
1831          * with the source object, all of its pages must be dirtied,
1832          * regardless of whether they can be written.
1833          */
1834         for (vaddr = dst_entry->start, dst_pindex = 0;
1835             vaddr < dst_entry->end;
1836             vaddr += PAGE_SIZE, dst_pindex++) {
1837 again:
1838                 /*
1839                  * Find the page in the source object, and copy it in.
1840                  * Because the source is wired down, the page will be
1841                  * in memory.
1842                  */
1843                 if (src_object != dst_object)
1844                         VM_OBJECT_RLOCK(src_object);
1845                 object = src_object;
1846                 pindex = src_pindex + dst_pindex;
1847                 while ((src_m = vm_page_lookup(object, pindex)) == NULL &&
1848                     (backing_object = object->backing_object) != NULL) {
1849                         /*
1850                          * Unless the source mapping is read-only or
1851                          * it is presently being upgraded from
1852                          * read-only, the first object in the shadow
1853                          * chain should provide all of the pages.  In
1854                          * other words, this loop body should never be
1855                          * executed when the source mapping is already
1856                          * read/write.
1857                          */
1858                         KASSERT((src_entry->protection & VM_PROT_WRITE) == 0 ||
1859                             upgrade,
1860                             ("vm_fault_copy_entry: main object missing page"));
1861
1862                         VM_OBJECT_RLOCK(backing_object);
1863                         pindex += OFF_TO_IDX(object->backing_object_offset);
1864                         if (object != dst_object)
1865                                 VM_OBJECT_RUNLOCK(object);
1866                         object = backing_object;
1867                 }
1868                 KASSERT(src_m != NULL, ("vm_fault_copy_entry: page missing"));
1869
1870                 if (object != dst_object) {
1871                         /*
1872                          * Allocate a page in the destination object.
1873                          */
1874                         dst_m = vm_page_alloc(dst_object, (src_object ==
1875                             dst_object ? src_pindex : 0) + dst_pindex,
1876                             VM_ALLOC_NORMAL);
1877                         if (dst_m == NULL) {
1878                                 VM_OBJECT_WUNLOCK(dst_object);
1879                                 VM_OBJECT_RUNLOCK(object);
1880                                 vm_wait(dst_object);
1881                                 VM_OBJECT_WLOCK(dst_object);
1882                                 goto again;
1883                         }
1884                         pmap_copy_page(src_m, dst_m);
1885                         VM_OBJECT_RUNLOCK(object);
1886                         dst_m->dirty = dst_m->valid = src_m->valid;
1887                 } else {
1888                         dst_m = src_m;
1889                         if (vm_page_busy_acquire(dst_m, VM_ALLOC_WAITFAIL) == 0)
1890                                 goto again;
1891                         if (dst_m->pindex >= dst_object->size) {
1892                                 /*
1893                                  * We are upgrading.  Index can occur
1894                                  * out of bounds if the object type is
1895                                  * vnode and the file was truncated.
1896                                  */
1897                                 vm_page_xunbusy(dst_m);
1898                                 break;
1899                         }
1900                 }
1901                 VM_OBJECT_WUNLOCK(dst_object);
1902
1903                 /*
1904                  * Enter it in the pmap. If a wired, copy-on-write
1905                  * mapping is being replaced by a write-enabled
1906                  * mapping, then wire that new mapping.
1907                  *
1908                  * The page can be invalid if the user called
1909                  * msync(MS_INVALIDATE) or truncated the backing vnode
1910                  * or shared memory object.  In this case, do not
1911                  * insert it into pmap, but still do the copy so that
1912                  * all copies of the wired map entry have similar
1913                  * backing pages.
1914                  */
1915                 if (vm_page_all_valid(dst_m)) {
1916                         pmap_enter(dst_map->pmap, vaddr, dst_m, prot,
1917                             access | (upgrade ? PMAP_ENTER_WIRED : 0), 0);
1918                 }
1919
1920                 /*
1921                  * Mark it no longer busy, and put it on the active list.
1922                  */
1923                 VM_OBJECT_WLOCK(dst_object);
1924                 
1925                 if (upgrade) {
1926                         if (src_m != dst_m) {
1927                                 vm_page_unwire(src_m, PQ_INACTIVE);
1928                                 vm_page_wire(dst_m);
1929                         } else {
1930                                 KASSERT(vm_page_wired(dst_m),
1931                                     ("dst_m %p is not wired", dst_m));
1932                         }
1933                 } else {
1934                         vm_page_activate(dst_m);
1935                 }
1936                 vm_page_xunbusy(dst_m);
1937         }
1938         VM_OBJECT_WUNLOCK(dst_object);
1939         if (upgrade) {
1940                 dst_entry->eflags &= ~(MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY);
1941                 vm_object_deallocate(src_object);
1942         }
1943 }
1944
1945 /*
1946  * Block entry into the machine-independent layer's page fault handler by
1947  * the calling thread.  Subsequent calls to vm_fault() by that thread will
1948  * return KERN_PROTECTION_FAILURE.  Enable machine-dependent handling of
1949  * spurious page faults. 
1950  */
1951 int
1952 vm_fault_disable_pagefaults(void)
1953 {
1954
1955         return (curthread_pflags_set(TDP_NOFAULTING | TDP_RESETSPUR));
1956 }
1957
1958 void
1959 vm_fault_enable_pagefaults(int save)
1960 {
1961
1962         curthread_pflags_restore(save);
1963 }