Initial import from FreeBSD RELENG_4:
[dragonfly.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  * $FreeBSD: src/sys/vm/vm_fault.c,v 1.108.2.8 2002/02/26 05:49:27 silby Exp $
70  */
71
72 /*
73  *      Page fault handling module.
74  */
75
76 #include <sys/param.h>
77 #include <sys/systm.h>
78 #include <sys/proc.h>
79 #include <sys/vnode.h>
80 #include <sys/resourcevar.h>
81 #include <sys/vmmeter.h>
82
83 #include <vm/vm.h>
84 #include <vm/vm_param.h>
85 #include <sys/lock.h>
86 #include <vm/pmap.h>
87 #include <vm/vm_map.h>
88 #include <vm/vm_object.h>
89 #include <vm/vm_page.h>
90 #include <vm/vm_pageout.h>
91 #include <vm/vm_kern.h>
92 #include <vm/vm_pager.h>
93 #include <vm/vnode_pager.h>
94 #include <vm/vm_extern.h>
95
96 static int vm_fault_additional_pages __P((vm_page_t, int,
97                                           int, vm_page_t *, int *));
98
99 #define VM_FAULT_READ_AHEAD 8
100 #define VM_FAULT_READ_BEHIND 7
101 #define VM_FAULT_READ (VM_FAULT_READ_AHEAD+VM_FAULT_READ_BEHIND+1)
102
103 struct faultstate {
104         vm_page_t m;
105         vm_object_t object;
106         vm_pindex_t pindex;
107         vm_page_t first_m;
108         vm_object_t     first_object;
109         vm_pindex_t first_pindex;
110         vm_map_t map;
111         vm_map_entry_t entry;
112         int lookup_still_valid;
113         struct vnode *vp;
114 };
115
116 static __inline void
117 release_page(struct faultstate *fs)
118 {
119         vm_page_wakeup(fs->m);
120         vm_page_deactivate(fs->m);
121         fs->m = NULL;
122 }
123
124 static __inline void
125 unlock_map(struct faultstate *fs)
126 {
127         if (fs->lookup_still_valid) {
128                 vm_map_lookup_done(fs->map, fs->entry);
129                 fs->lookup_still_valid = FALSE;
130         }
131 }
132
133 static void
134 _unlock_things(struct faultstate *fs, int dealloc)
135 {
136         vm_object_pip_wakeup(fs->object);
137         if (fs->object != fs->first_object) {
138                 vm_page_free(fs->first_m);
139                 vm_object_pip_wakeup(fs->first_object);
140                 fs->first_m = NULL;
141         }
142         if (dealloc) {
143                 vm_object_deallocate(fs->first_object);
144         }
145         unlock_map(fs); 
146         if (fs->vp != NULL) { 
147                 vput(fs->vp);
148                 fs->vp = NULL;
149         }
150 }
151
152 #define unlock_things(fs) _unlock_things(fs, 0)
153 #define unlock_and_deallocate(fs) _unlock_things(fs, 1)
154
155 /*
156  * TRYPAGER - used by vm_fault to calculate whether the pager for the
157  *            current object *might* contain the page.
158  *
159  *            default objects are zero-fill, there is no real pager.
160  */
161
162 #define TRYPAGER        (fs.object->type != OBJT_DEFAULT && \
163                         (((fault_flags & VM_FAULT_WIRE_MASK) == 0) || wired))
164
165 /*
166  *      vm_fault:
167  *
168  *      Handle a page fault occurring at the given address,
169  *      requiring the given permissions, in the map specified.
170  *      If successful, the page is inserted into the
171  *      associated physical map.
172  *
173  *      NOTE: the given address should be truncated to the
174  *      proper page address.
175  *
176  *      KERN_SUCCESS is returned if the page fault is handled; otherwise,
177  *      a standard error specifying why the fault is fatal is returned.
178  *
179  *
180  *      The map in question must be referenced, and remains so.
181  *      Caller may hold no locks.
182  */
183 int
184 vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type, int fault_flags)
185 {
186         vm_prot_t prot;
187         int result;
188         boolean_t wired;
189         int map_generation;
190         vm_object_t next_object;
191         vm_page_t marray[VM_FAULT_READ];
192         int hardfault;
193         int faultcount;
194         struct faultstate fs;
195
196         cnt.v_vm_faults++;      /* needs lock XXX */
197         hardfault = 0;
198
199 RetryFault:;
200
201         /*
202          * Find the backing store object and offset into it to begin the
203          * search.
204          */
205         fs.map = map;
206         if ((result = vm_map_lookup(&fs.map, vaddr,
207                 fault_type, &fs.entry, &fs.first_object,
208                 &fs.first_pindex, &prot, &wired)) != KERN_SUCCESS) {
209                 if ((result != KERN_PROTECTION_FAILURE) ||
210                         ((fault_flags & VM_FAULT_WIRE_MASK) != VM_FAULT_USER_WIRE)) {
211                         return result;
212                 }
213
214                 /*
215                  * If we are user-wiring a r/w segment, and it is COW, then
216                  * we need to do the COW operation.  Note that we don't COW
217                  * currently RO sections now, because it is NOT desirable
218                  * to COW .text.  We simply keep .text from ever being COW'ed
219                  * and take the heat that one cannot debug wired .text sections.
220                  */
221                 result = vm_map_lookup(&fs.map, vaddr,
222                         VM_PROT_READ|VM_PROT_WRITE|VM_PROT_OVERRIDE_WRITE,
223                         &fs.entry, &fs.first_object, &fs.first_pindex, &prot, &wired);
224                 if (result != KERN_SUCCESS) {
225                         return result;
226                 }
227
228                 /*
229                  * If we don't COW now, on a user wire, the user will never
230                  * be able to write to the mapping.  If we don't make this
231                  * restriction, the bookkeeping would be nearly impossible.
232                  */
233                 if ((fs.entry->protection & VM_PROT_WRITE) == 0)
234                         fs.entry->max_protection &= ~VM_PROT_WRITE;
235         }
236
237         map_generation = fs.map->timestamp;
238
239         if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
240                 panic("vm_fault: fault on nofault entry, addr: %lx",
241                     (u_long)vaddr);
242         }
243
244         /*
245          * Make a reference to this object to prevent its disposal while we
246          * are messing with it.  Once we have the reference, the map is free
247          * to be diddled.  Since objects reference their shadows (and copies),
248          * they will stay around as well.
249          *
250          * Bump the paging-in-progress count to prevent size changes (e.g.
251          * truncation operations) during I/O.  This must be done after
252          * obtaining the vnode lock in order to avoid possible deadlocks.
253          */
254         vm_object_reference(fs.first_object);
255         fs.vp = vnode_pager_lock(fs.first_object);
256         vm_object_pip_add(fs.first_object, 1);
257
258         if ((fault_type & VM_PROT_WRITE) &&
259                 (fs.first_object->type == OBJT_VNODE)) {
260                 vm_freeze_copyopts(fs.first_object,
261                         fs.first_pindex, fs.first_pindex + 1);
262         }
263
264         fs.lookup_still_valid = TRUE;
265
266         if (wired)
267                 fault_type = prot;
268
269         fs.first_m = NULL;
270
271         /*
272          * Search for the page at object/offset.
273          */
274
275         fs.object = fs.first_object;
276         fs.pindex = fs.first_pindex;
277
278         while (TRUE) {
279                 /*
280                  * If the object is dead, we stop here
281                  */
282
283                 if (fs.object->flags & OBJ_DEAD) {
284                         unlock_and_deallocate(&fs);
285                         return (KERN_PROTECTION_FAILURE);
286                 }
287
288                 /*
289                  * See if page is resident
290                  */
291                         
292                 fs.m = vm_page_lookup(fs.object, fs.pindex);
293                 if (fs.m != NULL) {
294                         int queue, s;
295                         /*
296                          * Wait/Retry if the page is busy.  We have to do this
297                          * if the page is busy via either PG_BUSY or 
298                          * vm_page_t->busy because the vm_pager may be using
299                          * vm_page_t->busy for pageouts ( and even pageins if
300                          * it is the vnode pager ), and we could end up trying
301                          * to pagein and pageout the same page simultaneously.
302                          *
303                          * We can theoretically allow the busy case on a read
304                          * fault if the page is marked valid, but since such
305                          * pages are typically already pmap'd, putting that
306                          * special case in might be more effort then it is 
307                          * worth.  We cannot under any circumstances mess
308                          * around with a vm_page_t->busy page except, perhaps,
309                          * to pmap it.
310                          */
311                         if ((fs.m->flags & PG_BUSY) || fs.m->busy) {
312                                 unlock_things(&fs);
313                                 (void)vm_page_sleep_busy(fs.m, TRUE, "vmpfw");
314                                 cnt.v_intrans++;
315                                 vm_object_deallocate(fs.first_object);
316                                 goto RetryFault;
317                         }
318
319                         queue = fs.m->queue;
320                         s = splvm();
321                         vm_page_unqueue_nowakeup(fs.m);
322                         splx(s);
323
324                         if ((queue - fs.m->pc) == PQ_CACHE && vm_page_count_severe()) {
325                                 vm_page_activate(fs.m);
326                                 unlock_and_deallocate(&fs);
327                                 VM_WAITPFAULT;
328                                 goto RetryFault;
329                         }
330
331                         /*
332                          * Mark page busy for other processes, and the 
333                          * pagedaemon.  If it still isn't completely valid
334                          * (readable), jump to readrest, else break-out ( we
335                          * found the page ).
336                          */
337
338                         vm_page_busy(fs.m);
339                         if (((fs.m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) &&
340                                 fs.m->object != kernel_object && fs.m->object != kmem_object) {
341                                 goto readrest;
342                         }
343
344                         break;
345                 }
346
347                 /*
348                  * Page is not resident, If this is the search termination
349                  * or the pager might contain the page, allocate a new page.
350                  */
351
352                 if (TRYPAGER || fs.object == fs.first_object) {
353                         if (fs.pindex >= fs.object->size) {
354                                 unlock_and_deallocate(&fs);
355                                 return (KERN_PROTECTION_FAILURE);
356                         }
357
358                         /*
359                          * Allocate a new page for this object/offset pair.
360                          */
361                         fs.m = NULL;
362                         if (!vm_page_count_severe()) {
363                                 fs.m = vm_page_alloc(fs.object, fs.pindex,
364                                     (fs.vp || fs.object->backing_object)? VM_ALLOC_NORMAL: VM_ALLOC_ZERO);
365                         }
366                         if (fs.m == NULL) {
367                                 unlock_and_deallocate(&fs);
368                                 VM_WAITPFAULT;
369                                 goto RetryFault;
370                         }
371                 }
372
373 readrest:
374                 /*
375                  * We have found a valid page or we have allocated a new page.
376                  * The page thus may not be valid or may not be entirely 
377                  * valid.
378                  *
379                  * Attempt to fault-in the page if there is a chance that the
380                  * pager has it, and potentially fault in additional pages
381                  * at the same time.
382                  */
383
384                 if (TRYPAGER) {
385                         int rv;
386                         int reqpage;
387                         int ahead, behind;
388                         u_char behavior = vm_map_entry_behavior(fs.entry);
389
390                         if (behavior == MAP_ENTRY_BEHAV_RANDOM) {
391                                 ahead = 0;
392                                 behind = 0;
393                         } else {
394                                 behind = (vaddr - fs.entry->start) >> PAGE_SHIFT;
395                                 if (behind > VM_FAULT_READ_BEHIND)
396                                         behind = VM_FAULT_READ_BEHIND;
397
398                                 ahead = ((fs.entry->end - vaddr) >> PAGE_SHIFT) - 1;
399                                 if (ahead > VM_FAULT_READ_AHEAD)
400                                         ahead = VM_FAULT_READ_AHEAD;
401                         }
402
403                         if ((fs.first_object->type != OBJT_DEVICE) &&
404                             (behavior == MAP_ENTRY_BEHAV_SEQUENTIAL ||
405                                 (behavior != MAP_ENTRY_BEHAV_RANDOM &&
406                                 fs.pindex >= fs.entry->lastr &&
407                                 fs.pindex < fs.entry->lastr + VM_FAULT_READ))
408                         ) {
409                                 vm_pindex_t firstpindex, tmppindex;
410
411                                 if (fs.first_pindex < 2 * VM_FAULT_READ)
412                                         firstpindex = 0;
413                                 else
414                                         firstpindex = fs.first_pindex - 2 * VM_FAULT_READ;
415
416                                 /*
417                                  * note: partially valid pages cannot be 
418                                  * included in the lookahead - NFS piecemeal
419                                  * writes will barf on it badly.
420                                  */
421
422                                 for(tmppindex = fs.first_pindex - 1;
423                                         tmppindex >= firstpindex;
424                                         --tmppindex) {
425                                         vm_page_t mt;
426                                         mt = vm_page_lookup( fs.first_object, tmppindex);
427                                         if (mt == NULL || (mt->valid != VM_PAGE_BITS_ALL))
428                                                 break;
429                                         if (mt->busy ||
430                                                 (mt->flags & (PG_BUSY | PG_FICTITIOUS | PG_UNMANAGED)) ||
431                                                 mt->hold_count ||
432                                                 mt->wire_count) 
433                                                 continue;
434                                         if (mt->dirty == 0)
435                                                 vm_page_test_dirty(mt);
436                                         if (mt->dirty) {
437                                                 vm_page_protect(mt, VM_PROT_NONE);
438                                                 vm_page_deactivate(mt);
439                                         } else {
440                                                 vm_page_cache(mt);
441                                         }
442                                 }
443
444                                 ahead += behind;
445                                 behind = 0;
446                         }
447
448                         /*
449                          * now we find out if any other pages should be paged
450                          * in at this time this routine checks to see if the
451                          * pages surrounding this fault reside in the same
452                          * object as the page for this fault.  If they do,
453                          * then they are faulted in also into the object.  The
454                          * array "marray" returned contains an array of
455                          * vm_page_t structs where one of them is the
456                          * vm_page_t passed to the routine.  The reqpage
457                          * return value is the index into the marray for the
458                          * vm_page_t passed to the routine.
459                          *
460                          * fs.m plus the additional pages are PG_BUSY'd.
461                          */
462                         faultcount = vm_fault_additional_pages(
463                             fs.m, behind, ahead, marray, &reqpage);
464
465                         /*
466                          * update lastr imperfectly (we do not know how much
467                          * getpages will actually read), but good enough.
468                          */
469                         fs.entry->lastr = fs.pindex + faultcount - behind;
470
471                         /*
472                          * Call the pager to retrieve the data, if any, after
473                          * releasing the lock on the map.  We hold a ref on
474                          * fs.object and the pages are PG_BUSY'd.
475                          */
476                         unlock_map(&fs);
477
478                         rv = faultcount ?
479                             vm_pager_get_pages(fs.object, marray, faultcount,
480                                 reqpage) : VM_PAGER_FAIL;
481
482                         if (rv == VM_PAGER_OK) {
483                                 /*
484                                  * Found the page. Leave it busy while we play
485                                  * with it.
486                                  */
487
488                                 /*
489                                  * Relookup in case pager changed page. Pager
490                                  * is responsible for disposition of old page
491                                  * if moved.
492                                  */
493                                 fs.m = vm_page_lookup(fs.object, fs.pindex);
494                                 if(!fs.m) {
495                                         unlock_and_deallocate(&fs);
496                                         goto RetryFault;
497                                 }
498
499                                 hardfault++;
500                                 break; /* break to PAGE HAS BEEN FOUND */
501                         }
502                         /*
503                          * Remove the bogus page (which does not exist at this
504                          * object/offset); before doing so, we must get back
505                          * our object lock to preserve our invariant.
506                          *
507                          * Also wake up any other process that may want to bring
508                          * in this page.
509                          *
510                          * If this is the top-level object, we must leave the
511                          * busy page to prevent another process from rushing
512                          * past us, and inserting the page in that object at
513                          * the same time that we are.
514                          */
515
516                         if (rv == VM_PAGER_ERROR)
517                                 printf("vm_fault: pager read error, pid %d (%s)\n",
518                                     curproc->p_pid, curproc->p_comm);
519                         /*
520                          * Data outside the range of the pager or an I/O error
521                          */
522                         /*
523                          * XXX - the check for kernel_map is a kludge to work
524                          * around having the machine panic on a kernel space
525                          * fault w/ I/O error.
526                          */
527                         if (((fs.map != kernel_map) && (rv == VM_PAGER_ERROR)) ||
528                                 (rv == VM_PAGER_BAD)) {
529                                 vm_page_free(fs.m);
530                                 fs.m = NULL;
531                                 unlock_and_deallocate(&fs);
532                                 return ((rv == VM_PAGER_ERROR) ? KERN_FAILURE : KERN_PROTECTION_FAILURE);
533                         }
534                         if (fs.object != fs.first_object) {
535                                 vm_page_free(fs.m);
536                                 fs.m = NULL;
537                                 /*
538                                  * XXX - we cannot just fall out at this
539                                  * point, m has been freed and is invalid!
540                                  */
541                         }
542                 }
543
544                 /*
545                  * We get here if the object has default pager (or unwiring) 
546                  * or the pager doesn't have the page.
547                  */
548                 if (fs.object == fs.first_object)
549                         fs.first_m = fs.m;
550
551                 /*
552                  * Move on to the next object.  Lock the next object before
553                  * unlocking the current one.
554                  */
555
556                 fs.pindex += OFF_TO_IDX(fs.object->backing_object_offset);
557                 next_object = fs.object->backing_object;
558                 if (next_object == NULL) {
559                         /*
560                          * If there's no object left, fill the page in the top
561                          * object with zeros.
562                          */
563                         if (fs.object != fs.first_object) {
564                                 vm_object_pip_wakeup(fs.object);
565
566                                 fs.object = fs.first_object;
567                                 fs.pindex = fs.first_pindex;
568                                 fs.m = fs.first_m;
569                         }
570                         fs.first_m = NULL;
571
572                         /*
573                          * Zero the page if necessary and mark it valid.
574                          */
575                         if ((fs.m->flags & PG_ZERO) == 0) {
576                                 vm_page_zero_fill(fs.m);
577                         } else {
578                                 cnt.v_ozfod++;
579                         }
580                         cnt.v_zfod++;
581                         fs.m->valid = VM_PAGE_BITS_ALL;
582                         break;  /* break to PAGE HAS BEEN FOUND */
583                 } else {
584                         if (fs.object != fs.first_object) {
585                                 vm_object_pip_wakeup(fs.object);
586                         }
587                         KASSERT(fs.object != next_object, ("object loop %p", next_object));
588                         fs.object = next_object;
589                         vm_object_pip_add(fs.object, 1);
590                 }
591         }
592
593         KASSERT((fs.m->flags & PG_BUSY) != 0,
594             ("vm_fault: not busy after main loop"));
595
596         /*
597          * PAGE HAS BEEN FOUND. [Loop invariant still holds -- the object lock
598          * is held.]
599          */
600
601         /*
602          * If the page is being written, but isn't already owned by the
603          * top-level object, we have to copy it into a new page owned by the
604          * top-level object.
605          */
606
607         if (fs.object != fs.first_object) {
608                 /*
609                  * We only really need to copy if we want to write it.
610                  */
611
612                 if (fault_type & VM_PROT_WRITE) {
613                         /*
614                          * This allows pages to be virtually copied from a 
615                          * backing_object into the first_object, where the 
616                          * backing object has no other refs to it, and cannot
617                          * gain any more refs.  Instead of a bcopy, we just 
618                          * move the page from the backing object to the 
619                          * first object.  Note that we must mark the page 
620                          * dirty in the first object so that it will go out 
621                          * to swap when needed.
622                          */
623                         if (map_generation == fs.map->timestamp &&
624                                 /*
625                                  * Only one shadow object
626                                  */
627                                 (fs.object->shadow_count == 1) &&
628                                 /*
629                                  * No COW refs, except us
630                                  */
631                                 (fs.object->ref_count == 1) &&
632                                 /*
633                                  * No one else can look this object up
634                                  */
635                                 (fs.object->handle == NULL) &&
636                                 /*
637                                  * No other ways to look the object up
638                                  */
639                                 ((fs.object->type == OBJT_DEFAULT) ||
640                                  (fs.object->type == OBJT_SWAP)) &&
641                                 /*
642                                  * We don't chase down the shadow chain
643                                  */
644                                 (fs.object == fs.first_object->backing_object) &&
645
646                                 /*
647                                  * grab the lock if we need to
648                                  */
649                                 (fs.lookup_still_valid ||
650                                  lockmgr(&fs.map->lock, LK_EXCLUSIVE|LK_NOWAIT, (void *)0, curproc) == 0)
651                             ) {
652                                 
653                                 fs.lookup_still_valid = 1;
654                                 /*
655                                  * get rid of the unnecessary page
656                                  */
657                                 vm_page_protect(fs.first_m, VM_PROT_NONE);
658                                 vm_page_free(fs.first_m);
659                                 fs.first_m = NULL;
660
661                                 /*
662                                  * grab the page and put it into the 
663                                  * process'es object.  The page is 
664                                  * automatically made dirty.
665                                  */
666                                 vm_page_rename(fs.m, fs.first_object, fs.first_pindex);
667                                 fs.first_m = fs.m;
668                                 vm_page_busy(fs.first_m);
669                                 fs.m = NULL;
670                                 cnt.v_cow_optim++;
671                         } else {
672                                 /*
673                                  * Oh, well, lets copy it.
674                                  */
675                                 vm_page_copy(fs.m, fs.first_m);
676                         }
677
678                         if (fs.m) {
679                                 /*
680                                  * We no longer need the old page or object.
681                                  */
682                                 release_page(&fs);
683                         }
684
685                         /*
686                          * fs.object != fs.first_object due to above 
687                          * conditional
688                          */
689
690                         vm_object_pip_wakeup(fs.object);
691
692                         /*
693                          * Only use the new page below...
694                          */
695
696                         cnt.v_cow_faults++;
697                         fs.m = fs.first_m;
698                         fs.object = fs.first_object;
699                         fs.pindex = fs.first_pindex;
700
701                 } else {
702                         prot &= ~VM_PROT_WRITE;
703                 }
704         }
705
706         /*
707          * We must verify that the maps have not changed since our last
708          * lookup.
709          */
710
711         if (!fs.lookup_still_valid &&
712                 (fs.map->timestamp != map_generation)) {
713                 vm_object_t retry_object;
714                 vm_pindex_t retry_pindex;
715                 vm_prot_t retry_prot;
716
717                 /*
718                  * Since map entries may be pageable, make sure we can take a
719                  * page fault on them.
720                  */
721
722                 /*
723                  * Unlock vnode before the lookup to avoid deadlock.   E.G.
724                  * avoid a deadlock between the inode and exec_map that can
725                  * occur due to locks being obtained in different orders.
726                  */
727
728                 if (fs.vp != NULL) {
729                         vput(fs.vp);
730                         fs.vp = NULL;
731                 }
732                 
733                 if (fs.map->infork) {
734                         release_page(&fs);
735                         unlock_and_deallocate(&fs);
736                         goto RetryFault;
737                 }
738
739                 /*
740                  * To avoid trying to write_lock the map while another process
741                  * has it read_locked (in vm_map_pageable), we do not try for
742                  * write permission.  If the page is still writable, we will
743                  * get write permission.  If it is not, or has been marked
744                  * needs_copy, we enter the mapping without write permission,
745                  * and will merely take another fault.
746                  */
747                 result = vm_map_lookup(&fs.map, vaddr, fault_type & ~VM_PROT_WRITE,
748                     &fs.entry, &retry_object, &retry_pindex, &retry_prot, &wired);
749                 map_generation = fs.map->timestamp;
750
751                 /*
752                  * If we don't need the page any longer, put it on the active
753                  * list (the easiest thing to do here).  If no one needs it,
754                  * pageout will grab it eventually.
755                  */
756
757                 if (result != KERN_SUCCESS) {
758                         release_page(&fs);
759                         unlock_and_deallocate(&fs);
760                         return (result);
761                 }
762                 fs.lookup_still_valid = TRUE;
763
764                 if ((retry_object != fs.first_object) ||
765                     (retry_pindex != fs.first_pindex)) {
766                         release_page(&fs);
767                         unlock_and_deallocate(&fs);
768                         goto RetryFault;
769                 }
770                 /*
771                  * Check whether the protection has changed or the object has
772                  * been copied while we left the map unlocked. Changing from
773                  * read to write permission is OK - we leave the page
774                  * write-protected, and catch the write fault. Changing from
775                  * write to read permission means that we can't mark the page
776                  * write-enabled after all.
777                  */
778                 prot &= retry_prot;
779         }
780
781         /*
782          * Put this page into the physical map. We had to do the unlock above
783          * because pmap_enter may cause other faults.   We don't put the page
784          * back on the active queue until later so that the page-out daemon
785          * won't find us (yet).
786          */
787
788         if (prot & VM_PROT_WRITE) {
789                 vm_page_flag_set(fs.m, PG_WRITEABLE);
790                 vm_object_set_writeable_dirty(fs.m->object);
791
792                 /*
793                  * If the fault is a write, we know that this page is being
794                  * written NOW so dirty it explicitly to save on 
795                  * pmap_is_modified() calls later.
796                  *
797                  * If this is a NOSYNC mmap we do not want to set PG_NOSYNC
798                  * if the page is already dirty to prevent data written with
799                  * the expectation of being synced from not being synced.
800                  * Likewise if this entry does not request NOSYNC then make
801                  * sure the page isn't marked NOSYNC.  Applications sharing
802                  * data should use the same flags to avoid ping ponging.
803                  *
804                  * Also tell the backing pager, if any, that it should remove
805                  * any swap backing since the page is now dirty.
806                  */
807                 if (fs.entry->eflags & MAP_ENTRY_NOSYNC) {
808                         if (fs.m->dirty == 0)
809                                 vm_page_flag_set(fs.m, PG_NOSYNC);
810                 } else {
811                         vm_page_flag_clear(fs.m, PG_NOSYNC);
812                 }
813                 if (fault_flags & VM_FAULT_DIRTY) {
814                         int s;
815                         vm_page_dirty(fs.m);
816                         s = splvm();
817                         vm_pager_page_unswapped(fs.m);
818                         splx(s);
819                 }
820         }
821
822         /*
823          * Page had better still be busy
824          */
825
826         KASSERT(fs.m->flags & PG_BUSY,
827                 ("vm_fault: page %p not busy!", fs.m));
828
829         unlock_things(&fs);
830
831         /*
832          * Sanity check: page must be completely valid or it is not fit to
833          * map into user space.  vm_pager_get_pages() ensures this.
834          */
835
836         if (fs.m->valid != VM_PAGE_BITS_ALL) {
837                 vm_page_zero_invalid(fs.m, TRUE);
838                 printf("Warning: page %p partially invalid on fault\n", fs.m);
839         }
840
841         pmap_enter(fs.map->pmap, vaddr, fs.m, prot, wired);
842
843         if (((fault_flags & VM_FAULT_WIRE_MASK) == 0) && (wired == 0)) {
844                 pmap_prefault(fs.map->pmap, vaddr, fs.entry);
845         }
846
847         vm_page_flag_clear(fs.m, PG_ZERO);
848         vm_page_flag_set(fs.m, PG_MAPPED|PG_REFERENCED);
849         if (fault_flags & VM_FAULT_HOLD)
850                 vm_page_hold(fs.m);
851
852         /*
853          * If the page is not wired down, then put it where the pageout daemon
854          * can find it.
855          */
856
857         if (fault_flags & VM_FAULT_WIRE_MASK) {
858                 if (wired)
859                         vm_page_wire(fs.m);
860                 else
861                         vm_page_unwire(fs.m, 1);
862         } else {
863                 vm_page_activate(fs.m);
864         }
865
866         if (curproc && (curproc->p_flag & P_INMEM) && curproc->p_stats) {
867                 if (hardfault) {
868                         curproc->p_stats->p_ru.ru_majflt++;
869                 } else {
870                         curproc->p_stats->p_ru.ru_minflt++;
871                 }
872         }
873
874         /*
875          * Unlock everything, and return
876          */
877
878         vm_page_wakeup(fs.m);
879         vm_object_deallocate(fs.first_object);
880
881         return (KERN_SUCCESS);
882
883 }
884
885 /*
886  *      vm_fault_wire:
887  *
888  *      Wire down a range of virtual addresses in a map.
889  */
890 int
891 vm_fault_wire(map, start, end)
892         vm_map_t map;
893         vm_offset_t start, end;
894 {
895
896         register vm_offset_t va;
897         register pmap_t pmap;
898         int rv;
899
900         pmap = vm_map_pmap(map);
901
902         /*
903          * Inform the physical mapping system that the range of addresses may
904          * not fault, so that page tables and such can be locked down as well.
905          */
906
907         pmap_pageable(pmap, start, end, FALSE);
908
909         /*
910          * We simulate a fault to get the page and enter it in the physical
911          * map.
912          */
913
914         for (va = start; va < end; va += PAGE_SIZE) {
915                 rv = vm_fault(map, va, VM_PROT_READ|VM_PROT_WRITE,
916                         VM_FAULT_CHANGE_WIRING);
917                 if (rv) {
918                         if (va != start)
919                                 vm_fault_unwire(map, start, va);
920                         return (rv);
921                 }
922         }
923         return (KERN_SUCCESS);
924 }
925
926 /*
927  *      vm_fault_user_wire:
928  *
929  *      Wire down a range of virtual addresses in a map.  This
930  *      is for user mode though, so we only ask for read access
931  *      on currently read only sections.
932  */
933 int
934 vm_fault_user_wire(map, start, end)
935         vm_map_t map;
936         vm_offset_t start, end;
937 {
938
939         register vm_offset_t va;
940         register pmap_t pmap;
941         int rv;
942
943         pmap = vm_map_pmap(map);
944
945         /*
946          * Inform the physical mapping system that the range of addresses may
947          * not fault, so that page tables and such can be locked down as well.
948          */
949
950         pmap_pageable(pmap, start, end, FALSE);
951
952         /*
953          * We simulate a fault to get the page and enter it in the physical
954          * map.
955          */
956         for (va = start; va < end; va += PAGE_SIZE) {
957                 rv = vm_fault(map, va, VM_PROT_READ, VM_FAULT_USER_WIRE);
958                 if (rv) {
959                         if (va != start)
960                                 vm_fault_unwire(map, start, va);
961                         return (rv);
962                 }
963         }
964         return (KERN_SUCCESS);
965 }
966
967
968 /*
969  *      vm_fault_unwire:
970  *
971  *      Unwire a range of virtual addresses in a map.
972  */
973 void
974 vm_fault_unwire(map, start, end)
975         vm_map_t map;
976         vm_offset_t start, end;
977 {
978
979         register vm_offset_t va, pa;
980         register pmap_t pmap;
981
982         pmap = vm_map_pmap(map);
983
984         /*
985          * Since the pages are wired down, we must be able to get their
986          * mappings from the physical map system.
987          */
988
989         for (va = start; va < end; va += PAGE_SIZE) {
990                 pa = pmap_extract(pmap, va);
991                 if (pa != (vm_offset_t) 0) {
992                         pmap_change_wiring(pmap, va, FALSE);
993                         vm_page_unwire(PHYS_TO_VM_PAGE(pa), 1);
994                 }
995         }
996
997         /*
998          * Inform the physical mapping system that the range of addresses may
999          * fault, so that page tables and such may be unwired themselves.
1000          */
1001
1002         pmap_pageable(pmap, start, end, TRUE);
1003
1004 }
1005
1006 /*
1007  *      Routine:
1008  *              vm_fault_copy_entry
1009  *      Function:
1010  *              Copy all of the pages from a wired-down map entry to another.
1011  *
1012  *      In/out conditions:
1013  *              The source and destination maps must be locked for write.
1014  *              The source map entry must be wired down (or be a sharing map
1015  *              entry corresponding to a main map entry that is wired down).
1016  */
1017
1018 void
1019 vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry)
1020         vm_map_t dst_map;
1021         vm_map_t src_map;
1022         vm_map_entry_t dst_entry;
1023         vm_map_entry_t src_entry;
1024 {
1025         vm_object_t dst_object;
1026         vm_object_t src_object;
1027         vm_ooffset_t dst_offset;
1028         vm_ooffset_t src_offset;
1029         vm_prot_t prot;
1030         vm_offset_t vaddr;
1031         vm_page_t dst_m;
1032         vm_page_t src_m;
1033
1034 #ifdef  lint
1035         src_map++;
1036 #endif  /* lint */
1037
1038         src_object = src_entry->object.vm_object;
1039         src_offset = src_entry->offset;
1040
1041         /*
1042          * Create the top-level object for the destination entry. (Doesn't
1043          * actually shadow anything - we copy the pages directly.)
1044          */
1045         dst_object = vm_object_allocate(OBJT_DEFAULT,
1046             (vm_size_t) OFF_TO_IDX(dst_entry->end - dst_entry->start));
1047
1048         dst_entry->object.vm_object = dst_object;
1049         dst_entry->offset = 0;
1050
1051         prot = dst_entry->max_protection;
1052
1053         /*
1054          * Loop through all of the pages in the entry's range, copying each
1055          * one from the source object (it should be there) to the destination
1056          * object.
1057          */
1058         for (vaddr = dst_entry->start, dst_offset = 0;
1059             vaddr < dst_entry->end;
1060             vaddr += PAGE_SIZE, dst_offset += PAGE_SIZE) {
1061
1062                 /*
1063                  * Allocate a page in the destination object
1064                  */
1065                 do {
1066                         dst_m = vm_page_alloc(dst_object,
1067                                 OFF_TO_IDX(dst_offset), VM_ALLOC_NORMAL);
1068                         if (dst_m == NULL) {
1069                                 VM_WAIT;
1070                         }
1071                 } while (dst_m == NULL);
1072
1073                 /*
1074                  * Find the page in the source object, and copy it in.
1075                  * (Because the source is wired down, the page will be in
1076                  * memory.)
1077                  */
1078                 src_m = vm_page_lookup(src_object,
1079                         OFF_TO_IDX(dst_offset + src_offset));
1080                 if (src_m == NULL)
1081                         panic("vm_fault_copy_wired: page missing");
1082
1083                 vm_page_copy(src_m, dst_m);
1084
1085                 /*
1086                  * Enter it in the pmap...
1087                  */
1088
1089                 vm_page_flag_clear(dst_m, PG_ZERO);
1090                 pmap_enter(dst_map->pmap, vaddr, dst_m, prot, FALSE);
1091                 vm_page_flag_set(dst_m, PG_WRITEABLE|PG_MAPPED);
1092
1093                 /*
1094                  * Mark it no longer busy, and put it on the active list.
1095                  */
1096                 vm_page_activate(dst_m);
1097                 vm_page_wakeup(dst_m);
1098         }
1099 }
1100
1101
1102 /*
1103  * This routine checks around the requested page for other pages that
1104  * might be able to be faulted in.  This routine brackets the viable
1105  * pages for the pages to be paged in.
1106  *
1107  * Inputs:
1108  *      m, rbehind, rahead
1109  *
1110  * Outputs:
1111  *  marray (array of vm_page_t), reqpage (index of requested page)
1112  *
1113  * Return value:
1114  *  number of pages in marray
1115  */
1116 static int
1117 vm_fault_additional_pages(m, rbehind, rahead, marray, reqpage)
1118         vm_page_t m;
1119         int rbehind;
1120         int rahead;
1121         vm_page_t *marray;
1122         int *reqpage;
1123 {
1124         int i,j;
1125         vm_object_t object;
1126         vm_pindex_t pindex, startpindex, endpindex, tpindex;
1127         vm_page_t rtm;
1128         int cbehind, cahead;
1129
1130         object = m->object;
1131         pindex = m->pindex;
1132
1133         /*
1134          * we don't fault-ahead for device pager
1135          */
1136         if (object->type == OBJT_DEVICE) {
1137                 *reqpage = 0;
1138                 marray[0] = m;
1139                 return 1;
1140         }
1141
1142         /*
1143          * if the requested page is not available, then give up now
1144          */
1145
1146         if (!vm_pager_has_page(object, pindex, &cbehind, &cahead)) {
1147                 return 0;
1148         }
1149
1150         if ((cbehind == 0) && (cahead == 0)) {
1151                 *reqpage = 0;
1152                 marray[0] = m;
1153                 return 1;
1154         }
1155
1156         if (rahead > cahead) {
1157                 rahead = cahead;
1158         }
1159
1160         if (rbehind > cbehind) {
1161                 rbehind = cbehind;
1162         }
1163
1164         /*
1165          * try to do any readahead that we might have free pages for.
1166          */
1167         if ((rahead + rbehind) >
1168                 ((cnt.v_free_count + cnt.v_cache_count) - cnt.v_free_reserved)) {
1169                 pagedaemon_wakeup();
1170                 marray[0] = m;
1171                 *reqpage = 0;
1172                 return 1;
1173         }
1174
1175         /*
1176          * scan backward for the read behind pages -- in memory 
1177          */
1178         if (pindex > 0) {
1179                 if (rbehind > pindex) {
1180                         rbehind = pindex;
1181                         startpindex = 0;
1182                 } else {
1183                         startpindex = pindex - rbehind;
1184                 }
1185
1186                 for ( tpindex = pindex - 1; tpindex >= startpindex; tpindex -= 1) {
1187                         if (vm_page_lookup( object, tpindex)) {
1188                                 startpindex = tpindex + 1;
1189                                 break;
1190                         }
1191                         if (tpindex == 0)
1192                                 break;
1193                 }
1194
1195                 for(i = 0, tpindex = startpindex; tpindex < pindex; i++, tpindex++) {
1196
1197                         rtm = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL);
1198                         if (rtm == NULL) {
1199                                 for (j = 0; j < i; j++) {
1200                                         vm_page_free(marray[j]);
1201                                 }
1202                                 marray[0] = m;
1203                                 *reqpage = 0;
1204                                 return 1;
1205                         }
1206
1207                         marray[i] = rtm;
1208                 }
1209         } else {
1210                 startpindex = 0;
1211                 i = 0;
1212         }
1213
1214         marray[i] = m;
1215         /* page offset of the required page */
1216         *reqpage = i;
1217
1218         tpindex = pindex + 1;
1219         i++;
1220
1221         /*
1222          * scan forward for the read ahead pages
1223          */
1224         endpindex = tpindex + rahead;
1225         if (endpindex > object->size)
1226                 endpindex = object->size;
1227
1228         for( ; tpindex < endpindex; i++, tpindex++) {
1229
1230                 if (vm_page_lookup(object, tpindex)) {
1231                         break;
1232                 }
1233
1234                 rtm = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL);
1235                 if (rtm == NULL) {
1236                         break;
1237                 }
1238
1239                 marray[i] = rtm;
1240         }
1241
1242         /* return number of bytes of pages */
1243         return i;
1244 }