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