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