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