]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/vm_fault.c
This commit was generated by cvs2svn to compensate for changes in r75107,
[FreeBSD/FreeBSD.git] / sys / vm / vm_fault.c
1 /*
2  * Copyright (c) 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1994 John S. Dyson
5  * All rights reserved.
6  * Copyright (c) 1994 David Greenman
7  * All rights reserved.
8  *
9  *
10  * This code is derived from software contributed to Berkeley by
11  * The Mach Operating System project at Carnegie-Mellon University.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *      This product includes software developed by the University of
24  *      California, Berkeley and its contributors.
25  * 4. Neither the name of the University nor the names of its contributors
26  *    may be used to endorse or promote products derived from this software
27  *    without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39  * SUCH DAMAGE.
40  *
41  *      from: @(#)vm_fault.c    8.4 (Berkeley) 1/12/94
42  *
43  *
44  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
45  * All rights reserved.
46  *
47  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
48  *
49  * Permission to use, copy, modify and distribute this software and
50  * its documentation is hereby granted, provided that both the copyright
51  * notice and this permission notice appear in all copies of the
52  * software, derivative works or modified versions, and any portions
53  * thereof, and that both notices appear in supporting documentation.
54  *
55  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
56  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
57  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
58  *
59  * Carnegie Mellon requests users of this software to return to
60  *
61  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
62  *  School of Computer Science
63  *  Carnegie Mellon University
64  *  Pittsburgh PA 15213-3890
65  *
66  * any improvements or extensions that they make and grant Carnegie the
67  * rights to redistribute these changes.
68  *
69  * $FreeBSD$
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         vm_object_reference(fs.first_object);
251         vm_object_pip_add(fs.first_object, 1);
252
253         fs.vp = vnode_pager_lock(fs.first_object);
254         if ((fault_type & VM_PROT_WRITE) &&
255                 (fs.first_object->type == OBJT_VNODE)) {
256                 vm_freeze_copyopts(fs.first_object,
257                         fs.first_pindex, fs.first_pindex + 1);
258         }
259
260         fs.lookup_still_valid = TRUE;
261
262         if (wired)
263                 fault_type = prot;
264
265         fs.first_m = NULL;
266
267         /*
268          * Search for the page at object/offset.
269          */
270
271         fs.object = fs.first_object;
272         fs.pindex = fs.first_pindex;
273
274         while (TRUE) {
275                 /*
276                  * If the object is dead, we stop here
277                  */
278
279                 if (fs.object->flags & OBJ_DEAD) {
280                         unlock_and_deallocate(&fs);
281                         return (KERN_PROTECTION_FAILURE);
282                 }
283
284                 /*
285                  * See if page is resident
286                  */
287                         
288                 fs.m = vm_page_lookup(fs.object, fs.pindex);
289                 if (fs.m != NULL) {
290                         int queue, s;
291                         /*
292                          * Wait/Retry if the page is busy.  We have to do this
293                          * if the page is busy via either PG_BUSY or 
294                          * vm_page_t->busy because the vm_pager may be using
295                          * vm_page_t->busy for pageouts ( and even pageins if
296                          * it is the vnode pager ), and we could end up trying
297                          * to pagein and pageout the same page simultaneously.
298                          *
299                          * We can theoretically allow the busy case on a read
300                          * fault if the page is marked valid, but since such
301                          * pages are typically already pmap'd, putting that
302                          * special case in might be more effort then it is 
303                          * worth.  We cannot under any circumstances mess
304                          * around with a vm_page_t->busy page except, perhaps,
305                          * to pmap it.
306                          */
307                         if ((fs.m->flags & PG_BUSY) || fs.m->busy) {
308                                 unlock_things(&fs);
309                                 (void)vm_page_sleep_busy(fs.m, TRUE, "vmpfw");
310                                 cnt.v_intrans++;
311                                 vm_object_deallocate(fs.first_object);
312                                 goto RetryFault;
313                         }
314
315                         queue = fs.m->queue;
316                         s = splvm();
317                         vm_page_unqueue_nowakeup(fs.m);
318                         splx(s);
319
320                         if ((queue - fs.m->pc) == PQ_CACHE && vm_page_count_severe()) {
321                                 vm_page_activate(fs.m);
322                                 unlock_and_deallocate(&fs);
323                                 VM_WAIT;
324                                 goto RetryFault;
325                         }
326
327                         /*
328                          * Mark page busy for other processes, and the 
329                          * pagedaemon.  If it still isn't completely valid
330                          * (readable), jump to readrest, else break-out ( we
331                          * found the page ).
332                          */
333
334                         vm_page_busy(fs.m);
335                         if (((fs.m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) &&
336                                 fs.m->object != kernel_object && fs.m->object != kmem_object) {
337                                 goto readrest;
338                         }
339
340                         break;
341                 }
342
343                 /*
344                  * Page is not resident, If this is the search termination
345                  * or the pager might contain the page, allocate a new page.
346                  */
347
348                 if (TRYPAGER || fs.object == fs.first_object) {
349                         if (fs.pindex >= fs.object->size) {
350                                 unlock_and_deallocate(&fs);
351                                 return (KERN_PROTECTION_FAILURE);
352                         }
353
354                         /*
355                          * Allocate a new page for this object/offset pair.
356                          */
357                         fs.m = NULL;
358                         if (!vm_page_count_severe()) {
359                                 fs.m = vm_page_alloc(fs.object, fs.pindex,
360                                     (fs.vp || fs.object->backing_object)? VM_ALLOC_NORMAL: VM_ALLOC_ZERO);
361                         }
362                         if (fs.m == NULL) {
363                                 unlock_and_deallocate(&fs);
364                                 VM_WAIT;
365                                 goto RetryFault;
366                         }
367                 }
368
369 readrest:
370                 /*
371                  * We have found a valid page or we have allocated a new page.
372                  * The page thus may not be valid or may not be entirely 
373                  * valid.
374                  *
375                  * Attempt to fault-in the page if there is a chance that the
376                  * pager has it, and potentially fault in additional pages
377                  * at the same time.
378                  */
379
380                 if (TRYPAGER) {
381                         int rv;
382                         int reqpage;
383                         int ahead, behind;
384                         u_char behavior = vm_map_entry_behavior(fs.entry);
385
386                         if (behavior == MAP_ENTRY_BEHAV_RANDOM) {
387                                 ahead = 0;
388                                 behind = 0;
389                         } else {
390                                 behind = (vaddr - fs.entry->start) >> PAGE_SHIFT;
391                                 if (behind > VM_FAULT_READ_BEHIND)
392                                         behind = VM_FAULT_READ_BEHIND;
393
394                                 ahead = ((fs.entry->end - vaddr) >> PAGE_SHIFT) - 1;
395                                 if (ahead > VM_FAULT_READ_AHEAD)
396                                         ahead = VM_FAULT_READ_AHEAD;
397                         }
398
399                         if ((fs.first_object->type != OBJT_DEVICE) &&
400                             (behavior == MAP_ENTRY_BEHAV_SEQUENTIAL ||
401                                 (behavior != MAP_ENTRY_BEHAV_RANDOM &&
402                                 fs.pindex >= fs.entry->lastr &&
403                                 fs.pindex < fs.entry->lastr + VM_FAULT_READ))
404                         ) {
405                                 vm_pindex_t firstpindex, tmppindex;
406
407                                 if (fs.first_pindex < 2 * VM_FAULT_READ)
408                                         firstpindex = 0;
409                                 else
410                                         firstpindex = fs.first_pindex - 2 * VM_FAULT_READ;
411
412                                 /*
413                                  * note: partially valid pages cannot be 
414                                  * included in the lookahead - NFS piecemeal
415                                  * writes will barf on it badly.
416                                  */
417
418                                 for(tmppindex = fs.first_pindex - 1;
419                                         tmppindex >= firstpindex;
420                                         --tmppindex) {
421                                         vm_page_t mt;
422                                         mt = vm_page_lookup( fs.first_object, tmppindex);
423                                         if (mt == NULL || (mt->valid != VM_PAGE_BITS_ALL))
424                                                 break;
425                                         if (mt->busy ||
426                                                 (mt->flags & (PG_BUSY | PG_FICTITIOUS | PG_UNMANAGED)) ||
427                                                 mt->hold_count ||
428                                                 mt->wire_count) 
429                                                 continue;
430                                         if (mt->dirty == 0)
431                                                 vm_page_test_dirty(mt);
432                                         if (mt->dirty) {
433                                                 vm_page_protect(mt, VM_PROT_NONE);
434                                                 vm_page_deactivate(mt);
435                                         } else {
436                                                 vm_page_cache(mt);
437                                         }
438                                 }
439
440                                 ahead += behind;
441                                 behind = 0;
442                         }
443
444                         /*
445                          * now we find out if any other pages should be paged
446                          * in at this time this routine checks to see if the
447                          * pages surrounding this fault reside in the same
448                          * object as the page for this fault.  If they do,
449                          * then they are faulted in also into the object.  The
450                          * array "marray" returned contains an array of
451                          * vm_page_t structs where one of them is the
452                          * vm_page_t passed to the routine.  The reqpage
453                          * return value is the index into the marray for the
454                          * vm_page_t passed to the routine.
455                          *
456                          * fs.m plus the additional pages are PG_BUSY'd.
457                          */
458                         faultcount = vm_fault_additional_pages(
459                             fs.m, behind, ahead, marray, &reqpage);
460
461                         /*
462                          * update lastr imperfectly (we do not know how much
463                          * getpages will actually read), but good enough.
464                          */
465                         fs.entry->lastr = fs.pindex + faultcount - behind;
466
467                         /*
468                          * Call the pager to retrieve the data, if any, after
469                          * releasing the lock on the map.  We hold a ref on
470                          * fs.object and the pages are PG_BUSY'd.
471                          */
472                         unlock_map(&fs);
473
474                         rv = faultcount ?
475                             vm_pager_get_pages(fs.object, marray, faultcount,
476                                 reqpage) : VM_PAGER_FAIL;
477
478                         if (rv == VM_PAGER_OK) {
479                                 /*
480                                  * Found the page. Leave it busy while we play
481                                  * with it.
482                                  */
483
484                                 /*
485                                  * Relookup in case pager changed page. Pager
486                                  * is responsible for disposition of old page
487                                  * if moved.
488                                  */
489                                 fs.m = vm_page_lookup(fs.object, fs.pindex);
490                                 if(!fs.m) {
491                                         unlock_and_deallocate(&fs);
492                                         goto RetryFault;
493                                 }
494
495                                 hardfault++;
496                                 break; /* break to PAGE HAS BEEN FOUND */
497                         }
498                         /*
499                          * Remove the bogus page (which does not exist at this
500                          * object/offset); before doing so, we must get back
501                          * our object lock to preserve our invariant.
502                          *
503                          * Also wake up any other process that may want to bring
504                          * in this page.
505                          *
506                          * If this is the top-level object, we must leave the
507                          * busy page to prevent another process from rushing
508                          * past us, and inserting the page in that object at
509                          * the same time that we are.
510                          */
511
512                         if (rv == VM_PAGER_ERROR)
513                                 printf("vm_fault: pager read error, pid %d (%s)\n",
514                                     curproc->p_pid, curproc->p_comm);
515                         /*
516                          * Data outside the range of the pager or an I/O error
517                          */
518                         /*
519                          * XXX - the check for kernel_map is a kludge to work
520                          * around having the machine panic on a kernel space
521                          * fault w/ I/O error.
522                          */
523                         if (((fs.map != kernel_map) && (rv == VM_PAGER_ERROR)) ||
524                                 (rv == VM_PAGER_BAD)) {
525                                 vm_page_free(fs.m);
526                                 fs.m = NULL;
527                                 unlock_and_deallocate(&fs);
528                                 return ((rv == VM_PAGER_ERROR) ? KERN_FAILURE : KERN_PROTECTION_FAILURE);
529                         }
530                         if (fs.object != fs.first_object) {
531                                 vm_page_free(fs.m);
532                                 fs.m = NULL;
533                                 /*
534                                  * XXX - we cannot just fall out at this
535                                  * point, m has been freed and is invalid!
536                                  */
537                         }
538                 }
539
540                 /*
541                  * We get here if the object has default pager (or unwiring) 
542                  * or the pager doesn't have the page.
543                  */
544                 if (fs.object == fs.first_object)
545                         fs.first_m = fs.m;
546
547                 /*
548                  * Move on to the next object.  Lock the next object before
549                  * unlocking the current one.
550                  */
551
552                 fs.pindex += OFF_TO_IDX(fs.object->backing_object_offset);
553                 next_object = fs.object->backing_object;
554                 if (next_object == NULL) {
555                         /*
556                          * If there's no object left, fill the page in the top
557                          * object with zeros.
558                          */
559                         if (fs.object != fs.first_object) {
560                                 vm_object_pip_wakeup(fs.object);
561
562                                 fs.object = fs.first_object;
563                                 fs.pindex = fs.first_pindex;
564                                 fs.m = fs.first_m;
565                         }
566                         fs.first_m = NULL;
567
568                         /*
569                          * Zero the page if necessary and mark it valid.
570                          */
571                         if ((fs.m->flags & PG_ZERO) == 0) {
572                                 vm_page_zero_fill(fs.m);
573                         } else {
574                                 cnt.v_ozfod++;
575                         }
576                         cnt.v_zfod++;
577                         fs.m->valid = VM_PAGE_BITS_ALL;
578                         break;  /* break to PAGE HAS BEEN FOUND */
579                 } else {
580                         if (fs.object != fs.first_object) {
581                                 vm_object_pip_wakeup(fs.object);
582                         }
583                         KASSERT(fs.object != next_object, ("object loop %p", next_object));
584                         fs.object = next_object;
585                         vm_object_pip_add(fs.object, 1);
586                 }
587         }
588
589         KASSERT((fs.m->flags & PG_BUSY) != 0,
590             ("vm_fault: not busy after main loop"));
591
592         /*
593          * PAGE HAS BEEN FOUND. [Loop invariant still holds -- the object lock
594          * is held.]
595          */
596
597         /*
598          * If the page is being written, but isn't already owned by the
599          * top-level object, we have to copy it into a new page owned by the
600          * top-level object.
601          */
602
603         if (fs.object != fs.first_object) {
604                 /*
605                  * We only really need to copy if we want to write it.
606                  */
607
608                 if (fault_type & VM_PROT_WRITE) {
609                         /*
610                          * This allows pages to be virtually copied from a 
611                          * backing_object into the first_object, where the 
612                          * backing object has no other refs to it, and cannot
613                          * gain any more refs.  Instead of a bcopy, we just 
614                          * move the page from the backing object to the 
615                          * first object.  Note that we must mark the page 
616                          * dirty in the first object so that it will go out 
617                          * to swap when needed.
618                          */
619                         if (map_generation == fs.map->timestamp &&
620                                 /*
621                                  * Only one shadow object
622                                  */
623                                 (fs.object->shadow_count == 1) &&
624                                 /*
625                                  * No COW refs, except us
626                                  */
627                                 (fs.object->ref_count == 1) &&
628                                 /*
629                                  * No one else can look this object up
630                                  */
631                                 (fs.object->handle == NULL) &&
632                                 /*
633                                  * No other ways to look the object up
634                                  */
635                                 ((fs.object->type == OBJT_DEFAULT) ||
636                                  (fs.object->type == OBJT_SWAP)) &&
637                                 /*
638                                  * We don't chase down the shadow chain
639                                  */
640                                 (fs.object == fs.first_object->backing_object) &&
641
642                                 /*
643                                  * grab the lock if we need to
644                                  */
645                                 (fs.lookup_still_valid ||
646                                  lockmgr(&fs.map->lock, LK_EXCLUSIVE|LK_NOWAIT, (void *)0, curproc) == 0)
647                             ) {
648                                 
649                                 fs.lookup_still_valid = 1;
650                                 /*
651                                  * get rid of the unnecessary page
652                                  */
653                                 vm_page_protect(fs.first_m, VM_PROT_NONE);
654                                 vm_page_free(fs.first_m);
655                                 fs.first_m = NULL;
656
657                                 /*
658                                  * grab the page and put it into the 
659                                  * process'es object.  The page is 
660                                  * automatically made dirty.
661                                  */
662                                 vm_page_rename(fs.m, fs.first_object, fs.first_pindex);
663                                 fs.first_m = fs.m;
664                                 vm_page_busy(fs.first_m);
665                                 fs.m = NULL;
666                                 cnt.v_cow_optim++;
667                         } else {
668                                 /*
669                                  * Oh, well, lets copy it.
670                                  */
671                                 vm_page_copy(fs.m, fs.first_m);
672                         }
673
674                         if (fs.m) {
675                                 /*
676                                  * We no longer need the old page or object.
677                                  */
678                                 release_page(&fs);
679                         }
680
681                         /*
682                          * fs.object != fs.first_object due to above 
683                          * conditional
684                          */
685
686                         vm_object_pip_wakeup(fs.object);
687
688                         /*
689                          * Only use the new page below...
690                          */
691
692                         cnt.v_cow_faults++;
693                         fs.m = fs.first_m;
694                         fs.object = fs.first_object;
695                         fs.pindex = fs.first_pindex;
696
697                 } else {
698                         prot &= ~VM_PROT_WRITE;
699                 }
700         }
701
702         /*
703          * We must verify that the maps have not changed since our last
704          * lookup.
705          */
706
707         if (!fs.lookup_still_valid &&
708                 (fs.map->timestamp != map_generation)) {
709                 vm_object_t retry_object;
710                 vm_pindex_t retry_pindex;
711                 vm_prot_t retry_prot;
712
713                 /*
714                  * Since map entries may be pageable, make sure we can take a
715                  * page fault on them.
716                  */
717
718                 /*
719                  * Unlock vnode before the lookup to avoid deadlock.   E.G.
720                  * avoid a deadlock between the inode and exec_map that can
721                  * occur due to locks being obtained in different orders.
722                  */
723
724                 if (fs.vp != NULL) {
725                         vput(fs.vp);
726                         fs.vp = NULL;
727                 }
728                 
729                 if (fs.map->infork) {
730                         release_page(&fs);
731                         unlock_and_deallocate(&fs);
732                         goto RetryFault;
733                 }
734
735                 /*
736                  * To avoid trying to write_lock the map while another process
737                  * has it read_locked (in vm_map_pageable), we do not try for
738                  * write permission.  If the page is still writable, we will
739                  * get write permission.  If it is not, or has been marked
740                  * needs_copy, we enter the mapping without write permission,
741                  * and will merely take another fault.
742                  */
743                 result = vm_map_lookup(&fs.map, vaddr, fault_type & ~VM_PROT_WRITE,
744                     &fs.entry, &retry_object, &retry_pindex, &retry_prot, &wired);
745                 map_generation = fs.map->timestamp;
746
747                 /*
748                  * If we don't need the page any longer, put it on the active
749                  * list (the easiest thing to do here).  If no one needs it,
750                  * pageout will grab it eventually.
751                  */
752
753                 if (result != KERN_SUCCESS) {
754                         release_page(&fs);
755                         unlock_and_deallocate(&fs);
756                         return (result);
757                 }
758                 fs.lookup_still_valid = TRUE;
759
760                 if ((retry_object != fs.first_object) ||
761                     (retry_pindex != fs.first_pindex)) {
762                         release_page(&fs);
763                         unlock_and_deallocate(&fs);
764                         goto RetryFault;
765                 }
766                 /*
767                  * Check whether the protection has changed or the object has
768                  * been copied while we left the map unlocked. Changing from
769                  * read to write permission is OK - we leave the page
770                  * write-protected, and catch the write fault. Changing from
771                  * write to read permission means that we can't mark the page
772                  * write-enabled after all.
773                  */
774                 prot &= retry_prot;
775         }
776
777         /*
778          * Put this page into the physical map. We had to do the unlock above
779          * because pmap_enter may cause other faults.   We don't put the page
780          * back on the active queue until later so that the page-out daemon
781          * won't find us (yet).
782          */
783
784         if (prot & VM_PROT_WRITE) {
785                 vm_page_flag_set(fs.m, PG_WRITEABLE);
786                 vm_object_set_flag(fs.m->object,
787                                    OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY);
788
789                 /*
790                  * If the fault is a write, we know that this page is being
791                  * written NOW so dirty it explicitly to save on 
792                  * pmap_is_modified() calls later.
793                  *
794                  * If this is a NOSYNC mmap we do not want to set PG_NOSYNC
795                  * if the page is already dirty to prevent data written with
796                  * the expectation of being synced from not being synced.
797                  * Likewise if this entry does not request NOSYNC then make
798                  * sure the page isn't marked NOSYNC.  Applications sharing
799                  * data should use the same flags to avoid ping ponging.
800                  *
801                  * Also tell the backing pager, if any, that it should remove
802                  * any swap backing since the page is now dirty.
803                  */
804                 if (fs.entry->eflags & MAP_ENTRY_NOSYNC) {
805                         if (fs.m->dirty == 0)
806                                 vm_page_flag_set(fs.m, PG_NOSYNC);
807                 } else {
808                         vm_page_flag_clear(fs.m, PG_NOSYNC);
809                 }
810                 if (fault_flags & VM_FAULT_DIRTY) {
811                         int s;
812                         vm_page_dirty(fs.m);
813                         s = splvm();
814                         vm_pager_page_unswapped(fs.m);
815                         splx(s);
816                 }
817         }
818
819         /*
820          * Page had better still be busy
821          */
822
823         KASSERT(fs.m->flags & PG_BUSY,
824                 ("vm_fault: page %p not busy!", fs.m));
825
826         unlock_things(&fs);
827
828         /*
829          * Sanity check: page must be completely valid or it is not fit to
830          * map into user space.  vm_pager_get_pages() ensures this.
831          */
832
833         if (fs.m->valid != VM_PAGE_BITS_ALL) {
834                 vm_page_zero_invalid(fs.m, TRUE);
835                 printf("Warning: page %p partially invalid on fault\n", fs.m);
836         }
837
838         pmap_enter(fs.map->pmap, vaddr, fs.m, prot, wired);
839
840         if (((fault_flags & VM_FAULT_WIRE_MASK) == 0) && (wired == 0)) {
841                 pmap_prefault(fs.map->pmap, vaddr, fs.entry);
842         }
843
844         vm_page_flag_clear(fs.m, PG_ZERO);
845         vm_page_flag_set(fs.m, PG_MAPPED|PG_REFERENCED);
846         if (fault_flags & VM_FAULT_HOLD)
847                 vm_page_hold(fs.m);
848
849         /*
850          * If the page is not wired down, then put it where the pageout daemon
851          * can find it.
852          */
853
854         if (fault_flags & VM_FAULT_WIRE_MASK) {
855                 if (wired)
856                         vm_page_wire(fs.m);
857                 else
858                         vm_page_unwire(fs.m, 1);
859         } else {
860                 vm_page_activate(fs.m);
861         }
862
863         mtx_lock_spin(&sched_lock);
864         if (curproc && (curproc->p_sflag & PS_INMEM) && curproc->p_stats) {
865                 if (hardfault) {
866                         curproc->p_stats->p_ru.ru_majflt++;
867                 } else {
868                         curproc->p_stats->p_ru.ru_minflt++;
869                 }
870         }
871         mtx_unlock_spin(&sched_lock);
872
873         /*
874          * Unlock everything, and return
875          */
876
877         vm_page_wakeup(fs.m);
878         vm_object_deallocate(fs.first_object);
879
880         return (KERN_SUCCESS);
881
882 }
883
884 /*
885  *      vm_fault_wire:
886  *
887  *      Wire down a range of virtual addresses in a map.
888  */
889 int
890 vm_fault_wire(map, start, end)
891         vm_map_t map;
892         vm_offset_t start, end;
893 {
894
895         register vm_offset_t va;
896         register pmap_t pmap;
897         int rv;
898
899         pmap = vm_map_pmap(map);
900
901         /*
902          * Inform the physical mapping system that the range of addresses may
903          * not fault, so that page tables and such can be locked down as well.
904          */
905
906         pmap_pageable(pmap, start, end, FALSE);
907
908         /*
909          * We simulate a fault to get the page and enter it in the physical
910          * map.
911          */
912
913         for (va = start; va < end; va += PAGE_SIZE) {
914                 rv = vm_fault(map, va, VM_PROT_READ|VM_PROT_WRITE,
915                         VM_FAULT_CHANGE_WIRING);
916                 if (rv) {
917                         if (va != start)
918                                 vm_fault_unwire(map, start, va);
919                         return (rv);
920                 }
921         }
922         return (KERN_SUCCESS);
923 }
924
925 /*
926  *      vm_fault_user_wire:
927  *
928  *      Wire down a range of virtual addresses in a map.  This
929  *      is for user mode though, so we only ask for read access
930  *      on currently read only sections.
931  */
932 int
933 vm_fault_user_wire(map, start, end)
934         vm_map_t map;
935         vm_offset_t start, end;
936 {
937
938         register vm_offset_t va;
939         register pmap_t pmap;
940         int rv;
941
942         pmap = vm_map_pmap(map);
943
944         /*
945          * Inform the physical mapping system that the range of addresses may
946          * not fault, so that page tables and such can be locked down as well.
947          */
948
949         pmap_pageable(pmap, start, end, FALSE);
950
951         /*
952          * We simulate a fault to get the page and enter it in the physical
953          * map.
954          */
955         for (va = start; va < end; va += PAGE_SIZE) {
956                 rv = vm_fault(map, va, VM_PROT_READ, VM_FAULT_USER_WIRE);
957                 if (rv) {
958                         if (va != start)
959                                 vm_fault_unwire(map, start, va);
960                         return (rv);
961                 }
962         }
963         return (KERN_SUCCESS);
964 }
965
966
967 /*
968  *      vm_fault_unwire:
969  *
970  *      Unwire a range of virtual addresses in a map.
971  */
972 void
973 vm_fault_unwire(map, start, end)
974         vm_map_t map;
975         vm_offset_t start, end;
976 {
977
978         register vm_offset_t va, pa;
979         register pmap_t pmap;
980
981         pmap = vm_map_pmap(map);
982
983         /*
984          * Since the pages are wired down, we must be able to get their
985          * mappings from the physical map system.
986          */
987
988         for (va = start; va < end; va += PAGE_SIZE) {
989                 pa = pmap_extract(pmap, va);
990                 if (pa != (vm_offset_t) 0) {
991                         pmap_change_wiring(pmap, va, FALSE);
992                         vm_page_unwire(PHYS_TO_VM_PAGE(pa), 1);
993                 }
994         }
995
996         /*
997          * Inform the physical mapping system that the range of addresses may
998          * fault, so that page tables and such may be unwired themselves.
999          */
1000
1001         pmap_pageable(pmap, start, end, TRUE);
1002
1003 }
1004
1005 /*
1006  *      Routine:
1007  *              vm_fault_copy_entry
1008  *      Function:
1009  *              Copy all of the pages from a wired-down map entry to another.
1010  *
1011  *      In/out conditions:
1012  *              The source and destination maps must be locked for write.
1013  *              The source map entry must be wired down (or be a sharing map
1014  *              entry corresponding to a main map entry that is wired down).
1015  */
1016
1017 void
1018 vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry)
1019         vm_map_t dst_map;
1020         vm_map_t src_map;
1021         vm_map_entry_t dst_entry;
1022         vm_map_entry_t src_entry;
1023 {
1024         vm_object_t dst_object;
1025         vm_object_t src_object;
1026         vm_ooffset_t dst_offset;
1027         vm_ooffset_t src_offset;
1028         vm_prot_t prot;
1029         vm_offset_t vaddr;
1030         vm_page_t dst_m;
1031         vm_page_t src_m;
1032
1033 #ifdef  lint
1034         src_map++;
1035 #endif  /* lint */
1036
1037         src_object = src_entry->object.vm_object;
1038         src_offset = src_entry->offset;
1039
1040         /*
1041          * Create the top-level object for the destination entry. (Doesn't
1042          * actually shadow anything - we copy the pages directly.)
1043          */
1044         dst_object = vm_object_allocate(OBJT_DEFAULT,
1045             (vm_size_t) OFF_TO_IDX(dst_entry->end - dst_entry->start));
1046
1047         dst_entry->object.vm_object = dst_object;
1048         dst_entry->offset = 0;
1049
1050         prot = dst_entry->max_protection;
1051
1052         /*
1053          * Loop through all of the pages in the entry's range, copying each
1054          * one from the source object (it should be there) to the destination
1055          * object.
1056          */
1057         for (vaddr = dst_entry->start, dst_offset = 0;
1058             vaddr < dst_entry->end;
1059             vaddr += PAGE_SIZE, dst_offset += PAGE_SIZE) {
1060
1061                 /*
1062                  * Allocate a page in the destination object
1063                  */
1064                 do {
1065                         dst_m = vm_page_alloc(dst_object,
1066                                 OFF_TO_IDX(dst_offset), VM_ALLOC_NORMAL);
1067                         if (dst_m == NULL) {
1068                                 VM_WAIT;
1069                         }
1070                 } while (dst_m == NULL);
1071
1072                 /*
1073                  * Find the page in the source object, and copy it in.
1074                  * (Because the source is wired down, the page will be in
1075                  * memory.)
1076                  */
1077                 src_m = vm_page_lookup(src_object,
1078                         OFF_TO_IDX(dst_offset + src_offset));
1079                 if (src_m == NULL)
1080                         panic("vm_fault_copy_wired: page missing");
1081
1082                 vm_page_copy(src_m, dst_m);
1083
1084                 /*
1085                  * Enter it in the pmap...
1086                  */
1087
1088                 vm_page_flag_clear(dst_m, PG_ZERO);
1089                 pmap_enter(dst_map->pmap, vaddr, dst_m, prot, FALSE);
1090                 vm_page_flag_set(dst_m, PG_WRITEABLE|PG_MAPPED);
1091
1092                 /*
1093                  * Mark it no longer busy, and put it on the active list.
1094                  */
1095                 vm_page_activate(dst_m);
1096                 vm_page_wakeup(dst_m);
1097         }
1098 }
1099
1100
1101 /*
1102  * This routine checks around the requested page for other pages that
1103  * might be able to be faulted in.  This routine brackets the viable
1104  * pages for the pages to be paged in.
1105  *
1106  * Inputs:
1107  *      m, rbehind, rahead
1108  *
1109  * Outputs:
1110  *  marray (array of vm_page_t), reqpage (index of requested page)
1111  *
1112  * Return value:
1113  *  number of pages in marray
1114  */
1115 static int
1116 vm_fault_additional_pages(m, rbehind, rahead, marray, reqpage)
1117         vm_page_t m;
1118         int rbehind;
1119         int rahead;
1120         vm_page_t *marray;
1121         int *reqpage;
1122 {
1123         int i,j;
1124         vm_object_t object;
1125         vm_pindex_t pindex, startpindex, endpindex, tpindex;
1126         vm_page_t rtm;
1127         int cbehind, cahead;
1128
1129         object = m->object;
1130         pindex = m->pindex;
1131
1132         /*
1133          * we don't fault-ahead for device pager
1134          */
1135         if (object->type == OBJT_DEVICE) {
1136                 *reqpage = 0;
1137                 marray[0] = m;
1138                 return 1;
1139         }
1140
1141         /*
1142          * if the requested page is not available, then give up now
1143          */
1144
1145         if (!vm_pager_has_page(object, pindex, &cbehind, &cahead)) {
1146                 return 0;
1147         }
1148
1149         if ((cbehind == 0) && (cahead == 0)) {
1150                 *reqpage = 0;
1151                 marray[0] = m;
1152                 return 1;
1153         }
1154
1155         if (rahead > cahead) {
1156                 rahead = cahead;
1157         }
1158
1159         if (rbehind > cbehind) {
1160                 rbehind = cbehind;
1161         }
1162
1163         /*
1164          * try to do any readahead that we might have free pages for.
1165          */
1166         if ((rahead + rbehind) >
1167                 ((cnt.v_free_count + cnt.v_cache_count) - cnt.v_free_reserved)) {
1168                 pagedaemon_wakeup();
1169                 marray[0] = m;
1170                 *reqpage = 0;
1171                 return 1;
1172         }
1173
1174         /*
1175          * scan backward for the read behind pages -- in memory 
1176          */
1177         if (pindex > 0) {
1178                 if (rbehind > pindex) {
1179                         rbehind = pindex;
1180                         startpindex = 0;
1181                 } else {
1182                         startpindex = pindex - rbehind;
1183                 }
1184
1185                 for ( tpindex = pindex - 1; tpindex >= startpindex; tpindex -= 1) {
1186                         if (vm_page_lookup( object, tpindex)) {
1187                                 startpindex = tpindex + 1;
1188                                 break;
1189                         }
1190                         if (tpindex == 0)
1191                                 break;
1192                 }
1193
1194                 for(i = 0, tpindex = startpindex; tpindex < pindex; i++, tpindex++) {
1195
1196                         rtm = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL);
1197                         if (rtm == NULL) {
1198                                 for (j = 0; j < i; j++) {
1199                                         vm_page_free(marray[j]);
1200                                 }
1201                                 marray[0] = m;
1202                                 *reqpage = 0;
1203                                 return 1;
1204                         }
1205
1206                         marray[i] = rtm;
1207                 }
1208         } else {
1209                 startpindex = 0;
1210                 i = 0;
1211         }
1212
1213         marray[i] = m;
1214         /* page offset of the required page */
1215         *reqpage = i;
1216
1217         tpindex = pindex + 1;
1218         i++;
1219
1220         /*
1221          * scan forward for the read ahead pages
1222          */
1223         endpindex = tpindex + rahead;
1224         if (endpindex > object->size)
1225                 endpindex = object->size;
1226
1227         for( ; tpindex < endpindex; i++, tpindex++) {
1228
1229                 if (vm_page_lookup(object, tpindex)) {
1230                         break;
1231                 }
1232
1233                 rtm = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL);
1234                 if (rtm == NULL) {
1235                         break;
1236                 }
1237
1238                 marray[i] = rtm;
1239         }
1240
1241         /* return number of bytes of pages */
1242         return i;
1243 }