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