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