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