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