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