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