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