xref: /dragonfly/sys/vm/vm_fault.c (revision dbeb2594)
1 /*
2  * Copyright (c) 2003-2014 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * ---
35  *
36  * Copyright (c) 1991, 1993
37  *	The Regents of the University of California.  All rights reserved.
38  * Copyright (c) 1994 John S. Dyson
39  * All rights reserved.
40  * Copyright (c) 1994 David Greenman
41  * All rights reserved.
42  *
43  *
44  * This code is derived from software contributed to Berkeley by
45  * The Mach Operating System project at Carnegie-Mellon University.
46  *
47  * Redistribution and use in source and binary forms, with or without
48  * modification, are permitted provided that the following conditions
49  * are met:
50  * 1. Redistributions of source code must retain the above copyright
51  *    notice, this list of conditions and the following disclaimer.
52  * 2. Redistributions in binary form must reproduce the above copyright
53  *    notice, this list of conditions and the following disclaimer in the
54  *    documentation and/or other materials provided with the distribution.
55  * 3. Neither the name of the University nor the names of its contributors
56  *    may be used to endorse or promote products derived from this software
57  *    without specific prior written permission.
58  *
59  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69  * SUCH DAMAGE.
70  *
71  * ---
72  *
73  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
74  * All rights reserved.
75  *
76  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
77  *
78  * Permission to use, copy, modify and distribute this software and
79  * its documentation is hereby granted, provided that both the copyright
80  * notice and this permission notice appear in all copies of the
81  * software, derivative works or modified versions, and any portions
82  * thereof, and that both notices appear in supporting documentation.
83  *
84  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
85  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
86  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
87  *
88  * Carnegie Mellon requests users of this software to return to
89  *
90  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
91  *  School of Computer Science
92  *  Carnegie Mellon University
93  *  Pittsburgh PA 15213-3890
94  *
95  * any improvements or extensions that they make and grant Carnegie the
96  * rights to redistribute these changes.
97  */
98 
99 /*
100  *	Page fault handling module.
101  */
102 
103 #include <sys/param.h>
104 #include <sys/systm.h>
105 #include <sys/kernel.h>
106 #include <sys/proc.h>
107 #include <sys/vnode.h>
108 #include <sys/resourcevar.h>
109 #include <sys/vmmeter.h>
110 #include <sys/vkernel.h>
111 #include <sys/lock.h>
112 #include <sys/sysctl.h>
113 
114 #include <cpu/lwbuf.h>
115 
116 #include <vm/vm.h>
117 #include <vm/vm_param.h>
118 #include <vm/pmap.h>
119 #include <vm/vm_map.h>
120 #include <vm/vm_object.h>
121 #include <vm/vm_page.h>
122 #include <vm/vm_pageout.h>
123 #include <vm/vm_kern.h>
124 #include <vm/vm_pager.h>
125 #include <vm/vnode_pager.h>
126 #include <vm/vm_extern.h>
127 
128 #include <sys/thread2.h>
129 #include <vm/vm_page2.h>
130 
131 struct faultstate {
132 	vm_page_t m;
133 	vm_object_t object;
134 	vm_pindex_t pindex;
135 	vm_prot_t prot;
136 	vm_page_t first_m;
137 	vm_object_t first_object;
138 	vm_prot_t first_prot;
139 	vm_map_t map;
140 	vm_map_entry_t entry;
141 	int lookup_still_valid;
142 	int hardfault;
143 	int fault_flags;
144 	int map_generation;
145 	int shared;
146 	int first_shared;
147 	boolean_t wired;
148 	struct vnode *vp;
149 };
150 
151 static int debug_fault = 0;
152 SYSCTL_INT(_vm, OID_AUTO, debug_fault, CTLFLAG_RW, &debug_fault, 0, "");
153 static int debug_cluster = 0;
154 SYSCTL_INT(_vm, OID_AUTO, debug_cluster, CTLFLAG_RW, &debug_cluster, 0, "");
155 int vm_shared_fault = 1;
156 TUNABLE_INT("vm.shared_fault", &vm_shared_fault);
157 SYSCTL_INT(_vm, OID_AUTO, shared_fault, CTLFLAG_RW, &vm_shared_fault, 0,
158 	   "Allow shared token on vm_object");
159 
160 static int vm_fault_object(struct faultstate *, vm_pindex_t, vm_prot_t, int);
161 static int vm_fault_vpagetable(struct faultstate *, vm_pindex_t *,
162 			vpte_t, int, int);
163 #if 0
164 static int vm_fault_additional_pages (vm_page_t, int, int, vm_page_t *, int *);
165 #endif
166 static void vm_set_nosync(vm_page_t m, vm_map_entry_t entry);
167 static void vm_prefault(pmap_t pmap, vm_offset_t addra,
168 			vm_map_entry_t entry, int prot, int fault_flags);
169 static void vm_prefault_quick(pmap_t pmap, vm_offset_t addra,
170 			vm_map_entry_t entry, int prot, int fault_flags);
171 
172 static __inline void
173 release_page(struct faultstate *fs)
174 {
175 	vm_page_deactivate(fs->m);
176 	vm_page_wakeup(fs->m);
177 	fs->m = NULL;
178 }
179 
180 /*
181  * NOTE: Once unlocked any cached fs->entry becomes invalid, any reuse
182  *	 requires relocking and then checking the timestamp.
183  *
184  * NOTE: vm_map_lock_read() does not bump fs->map->timestamp so we do
185  *	 not have to update fs->map_generation here.
186  *
187  * NOTE: This function can fail due to a deadlock against the caller's
188  *	 holding of a vm_page BUSY.
189  */
190 static __inline int
191 relock_map(struct faultstate *fs)
192 {
193 	int error;
194 
195 	if (fs->lookup_still_valid == FALSE && fs->map) {
196 		error = vm_map_lock_read_to(fs->map);
197 		if (error == 0)
198 			fs->lookup_still_valid = TRUE;
199 	} else {
200 		error = 0;
201 	}
202 	return error;
203 }
204 
205 static __inline void
206 unlock_map(struct faultstate *fs)
207 {
208 	if (fs->lookup_still_valid && fs->map) {
209 		vm_map_lookup_done(fs->map, fs->entry, 0);
210 		fs->lookup_still_valid = FALSE;
211 	}
212 }
213 
214 /*
215  * Clean up after a successful call to vm_fault_object() so another call
216  * to vm_fault_object() can be made.
217  */
218 static void
219 _cleanup_successful_fault(struct faultstate *fs, int relock)
220 {
221 	/*
222 	 * We allocated a junk page for a COW operation that did
223 	 * not occur, the page must be freed.
224 	 */
225 	if (fs->object != fs->first_object) {
226 		KKASSERT(fs->first_shared == 0);
227 		vm_page_free(fs->first_m);
228 		vm_object_pip_wakeup(fs->object);
229 		fs->first_m = NULL;
230 	}
231 
232 	/*
233 	 * Reset fs->object.
234 	 */
235 	fs->object = fs->first_object;
236 	if (relock && fs->lookup_still_valid == FALSE) {
237 		if (fs->map)
238 			vm_map_lock_read(fs->map);
239 		fs->lookup_still_valid = TRUE;
240 	}
241 }
242 
243 static void
244 _unlock_things(struct faultstate *fs, int dealloc)
245 {
246 	_cleanup_successful_fault(fs, 0);
247 	if (dealloc) {
248 		/*vm_object_deallocate(fs->first_object);*/
249 		/*fs->first_object = NULL; drop used later on */
250 	}
251 	unlock_map(fs);
252 	if (fs->vp != NULL) {
253 		vput(fs->vp);
254 		fs->vp = NULL;
255 	}
256 }
257 
258 #define unlock_things(fs) _unlock_things(fs, 0)
259 #define unlock_and_deallocate(fs) _unlock_things(fs, 1)
260 #define cleanup_successful_fault(fs) _cleanup_successful_fault(fs, 1)
261 
262 /*
263  * TRYPAGER
264  *
265  * Determine if the pager for the current object *might* contain the page.
266  *
267  * We only need to try the pager if this is not a default object (default
268  * objects are zero-fill and have no real pager), and if we are not taking
269  * a wiring fault or if the FS entry is wired.
270  */
271 #define TRYPAGER(fs)	\
272 		(fs->object->type != OBJT_DEFAULT && \
273 		(((fs->fault_flags & VM_FAULT_WIRE_MASK) == 0) || fs->wired))
274 
275 /*
276  * vm_fault:
277  *
278  * Handle a page fault occuring at the given address, requiring the given
279  * permissions, in the map specified.  If successful, the page is inserted
280  * into the associated physical map.
281  *
282  * NOTE: The given address should be truncated to the proper page address.
283  *
284  * KERN_SUCCESS is returned if the page fault is handled; otherwise,
285  * a standard error specifying why the fault is fatal is returned.
286  *
287  * The map in question must be referenced, and remains so.
288  * The caller may hold no locks.
289  * No other requirements.
290  */
291 int
292 vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type, int fault_flags)
293 {
294 	int result;
295 	vm_pindex_t first_pindex;
296 	struct faultstate fs;
297 	struct lwp *lp;
298 	struct proc *p;
299 	thread_t td;
300 	int growstack;
301 	int retry = 0;
302 	int inherit_prot;
303 
304 	inherit_prot = fault_type & VM_PROT_NOSYNC;
305 	fs.hardfault = 0;
306 	fs.fault_flags = fault_flags;
307 	fs.vp = NULL;
308 	fs.shared = vm_shared_fault;
309 	fs.first_shared = vm_shared_fault;
310 	growstack = 1;
311 
312 	/*
313 	 * vm_map interactions
314 	 */
315 	td = curthread;
316 	if ((lp = td->td_lwp) != NULL)
317 		lp->lwp_flags |= LWP_PAGING;
318 	lwkt_gettoken(&map->token);
319 
320 RetryFault:
321 	/*
322 	 * Find the vm_map_entry representing the backing store and resolve
323 	 * the top level object and page index.  This may have the side
324 	 * effect of executing a copy-on-write on the map entry and/or
325 	 * creating a shadow object, but will not COW any actual VM pages.
326 	 *
327 	 * On success fs.map is left read-locked and various other fields
328 	 * are initialized but not otherwise referenced or locked.
329 	 *
330 	 * NOTE!  vm_map_lookup will try to upgrade the fault_type to
331 	 * VM_FAULT_WRITE if the map entry is a virtual page table and also
332 	 * writable, so we can set the 'A'accessed bit in the virtual page
333 	 * table entry.
334 	 */
335 	fs.map = map;
336 	result = vm_map_lookup(&fs.map, vaddr, fault_type,
337 			       &fs.entry, &fs.first_object,
338 			       &first_pindex, &fs.first_prot, &fs.wired);
339 
340 	/*
341 	 * If the lookup failed or the map protections are incompatible,
342 	 * the fault generally fails.
343 	 *
344 	 * The failure could be due to TDF_NOFAULT if vm_map_lookup()
345 	 * tried to do a COW fault.
346 	 *
347 	 * If the caller is trying to do a user wiring we have more work
348 	 * to do.
349 	 */
350 	if (result != KERN_SUCCESS) {
351 		if (result == KERN_FAILURE_NOFAULT) {
352 			result = KERN_FAILURE;
353 			goto done;
354 		}
355 		if (result != KERN_PROTECTION_FAILURE ||
356 		    (fs.fault_flags & VM_FAULT_WIRE_MASK) != VM_FAULT_USER_WIRE)
357 		{
358 			if (result == KERN_INVALID_ADDRESS && growstack &&
359 			    map != &kernel_map && curproc != NULL) {
360 				result = vm_map_growstack(curproc, vaddr);
361 				if (result == KERN_SUCCESS) {
362 					growstack = 0;
363 					++retry;
364 					goto RetryFault;
365 				}
366 				result = KERN_FAILURE;
367 			}
368 			goto done;
369 		}
370 
371 		/*
372    		 * If we are user-wiring a r/w segment, and it is COW, then
373    		 * we need to do the COW operation.  Note that we don't
374 		 * currently COW RO sections now, because it is NOT desirable
375    		 * to COW .text.  We simply keep .text from ever being COW'ed
376    		 * and take the heat that one cannot debug wired .text sections.
377    		 */
378 		result = vm_map_lookup(&fs.map, vaddr,
379 				       VM_PROT_READ|VM_PROT_WRITE|
380 				        VM_PROT_OVERRIDE_WRITE,
381 				       &fs.entry, &fs.first_object,
382 				       &first_pindex, &fs.first_prot,
383 				       &fs.wired);
384 		if (result != KERN_SUCCESS) {
385 			/* could also be KERN_FAILURE_NOFAULT */
386 			result = KERN_FAILURE;
387 			goto done;
388 		}
389 
390 		/*
391 		 * If we don't COW now, on a user wire, the user will never
392 		 * be able to write to the mapping.  If we don't make this
393 		 * restriction, the bookkeeping would be nearly impossible.
394 		 *
395 		 * XXX We have a shared lock, this will have a MP race but
396 		 * I don't see how it can hurt anything.
397 		 */
398 		if ((fs.entry->protection & VM_PROT_WRITE) == 0)
399 			fs.entry->max_protection &= ~VM_PROT_WRITE;
400 	}
401 
402 	/*
403 	 * fs.map is read-locked
404 	 *
405 	 * Misc checks.  Save the map generation number to detect races.
406 	 */
407 	fs.map_generation = fs.map->timestamp;
408 	fs.lookup_still_valid = TRUE;
409 	fs.first_m = NULL;
410 	fs.object = fs.first_object;	/* so unlock_and_deallocate works */
411 	fs.prot = fs.first_prot;	/* default (used by uksmap) */
412 
413 	if (fs.entry->eflags & (MAP_ENTRY_NOFAULT | MAP_ENTRY_KSTACK)) {
414 		if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
415 			panic("vm_fault: fault on nofault entry, addr: %p",
416 			      (void *)vaddr);
417 		}
418 		if ((fs.entry->eflags & MAP_ENTRY_KSTACK) &&
419 		    vaddr >= fs.entry->start &&
420 		    vaddr < fs.entry->start + PAGE_SIZE) {
421 			panic("vm_fault: fault on stack guard, addr: %p",
422 			      (void *)vaddr);
423 		}
424 	}
425 
426 	/*
427 	 * A user-kernel shared map has no VM object and bypasses
428 	 * everything.  We execute the uksmap function with a temporary
429 	 * fictitious vm_page.  The address is directly mapped with no
430 	 * management.
431 	 */
432 	if (fs.entry->maptype == VM_MAPTYPE_UKSMAP) {
433 		struct vm_page fakem;
434 
435 		bzero(&fakem, sizeof(fakem));
436 		fakem.pindex = first_pindex;
437 		fakem.flags = PG_BUSY | PG_FICTITIOUS | PG_UNMANAGED;
438 		fakem.valid = VM_PAGE_BITS_ALL;
439 		fakem.pat_mode = VM_MEMATTR_DEFAULT;
440 		if (fs.entry->object.uksmap(fs.entry->aux.dev, &fakem)) {
441 			result = KERN_FAILURE;
442 			unlock_things(&fs);
443 			goto done2;
444 		}
445 		pmap_enter(fs.map->pmap, vaddr, &fakem, fs.prot | inherit_prot,
446 			   fs.wired, fs.entry);
447 		goto done_success;
448 	}
449 
450 	/*
451 	 * A system map entry may return a NULL object.  No object means
452 	 * no pager means an unrecoverable kernel fault.
453 	 */
454 	if (fs.first_object == NULL) {
455 		panic("vm_fault: unrecoverable fault at %p in entry %p",
456 			(void *)vaddr, fs.entry);
457 	}
458 
459 	/*
460 	 * Fail here if not a trivial anonymous page fault and TDF_NOFAULT
461 	 * is set.
462 	 *
463 	 * Unfortunately a deadlock can occur if we are forced to page-in
464 	 * from swap, but diving all the way into the vm_pager_get_page()
465 	 * function to find out is too much.  Just check the object type.
466 	 *
467 	 * The deadlock is a CAM deadlock on a busy VM page when trying
468 	 * to finish an I/O if another process gets stuck in
469 	 * vop_helper_read_shortcut() due to a swap fault.
470 	 */
471 	if ((td->td_flags & TDF_NOFAULT) &&
472 	    (retry ||
473 	     fs.first_object->type == OBJT_VNODE ||
474 	     fs.first_object->type == OBJT_SWAP ||
475 	     fs.first_object->backing_object)) {
476 		result = KERN_FAILURE;
477 		unlock_things(&fs);
478 		goto done2;
479 	}
480 
481 	/*
482 	 * If the entry is wired we cannot change the page protection.
483 	 */
484 	if (fs.wired)
485 		fault_type = fs.first_prot;
486 
487 	/*
488 	 * We generally want to avoid unnecessary exclusive modes on backing
489 	 * and terminal objects because this can seriously interfere with
490 	 * heavily fork()'d processes (particularly /bin/sh scripts).
491 	 *
492 	 * However, we also want to avoid unnecessary retries due to needed
493 	 * shared->exclusive promotion for common faults.  Exclusive mode is
494 	 * always needed if any page insertion, rename, or free occurs in an
495 	 * object (and also indirectly if any I/O is done).
496 	 *
497 	 * The main issue here is going to be fs.first_shared.  If the
498 	 * first_object has a backing object which isn't shadowed and the
499 	 * process is single-threaded we might as well use an exclusive
500 	 * lock/chain right off the bat.
501 	 */
502 	if (fs.first_shared && fs.first_object->backing_object &&
503 	    LIST_EMPTY(&fs.first_object->shadow_head) &&
504 	    td->td_proc && td->td_proc->p_nthreads == 1) {
505 		fs.first_shared = 0;
506 	}
507 
508 	/*
509 	 * swap_pager_unswapped() needs an exclusive object
510 	 */
511 	if (fault_flags & (VM_FAULT_UNSWAP | VM_FAULT_DIRTY)) {
512 		fs.first_shared = 0;
513 	}
514 
515 	/*
516 	 * Obtain a top-level object lock, shared or exclusive depending
517 	 * on fs.first_shared.  If a shared lock winds up being insufficient
518 	 * we will retry with an exclusive lock.
519 	 *
520 	 * The vnode pager lock is always shared.
521 	 */
522 	if (fs.first_shared)
523 		vm_object_hold_shared(fs.first_object);
524 	else
525 		vm_object_hold(fs.first_object);
526 	if (fs.vp == NULL)
527 		fs.vp = vnode_pager_lock(fs.first_object);
528 
529 	/*
530 	 * The page we want is at (first_object, first_pindex), but if the
531 	 * vm_map_entry is VM_MAPTYPE_VPAGETABLE we have to traverse the
532 	 * page table to figure out the actual pindex.
533 	 *
534 	 * NOTE!  DEVELOPMENT IN PROGRESS, THIS IS AN INITIAL IMPLEMENTATION
535 	 * ONLY
536 	 */
537 	if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
538 		result = vm_fault_vpagetable(&fs, &first_pindex,
539 					     fs.entry->aux.master_pde,
540 					     fault_type, 1);
541 		if (result == KERN_TRY_AGAIN) {
542 			vm_object_drop(fs.first_object);
543 			++retry;
544 			goto RetryFault;
545 		}
546 		if (result != KERN_SUCCESS)
547 			goto done;
548 	}
549 
550 	/*
551 	 * Now we have the actual (object, pindex), fault in the page.  If
552 	 * vm_fault_object() fails it will unlock and deallocate the FS
553 	 * data.   If it succeeds everything remains locked and fs->object
554 	 * will have an additional PIP count if it is not equal to
555 	 * fs->first_object
556 	 *
557 	 * vm_fault_object will set fs->prot for the pmap operation.  It is
558 	 * allowed to set VM_PROT_WRITE if fault_type == VM_PROT_READ if the
559 	 * page can be safely written.  However, it will force a read-only
560 	 * mapping for a read fault if the memory is managed by a virtual
561 	 * page table.
562 	 *
563 	 * If the fault code uses the shared object lock shortcut
564 	 * we must not try to burst (we can't allocate VM pages).
565 	 */
566 	result = vm_fault_object(&fs, first_pindex, fault_type, 1);
567 
568 	if (debug_fault > 0) {
569 		--debug_fault;
570 		kprintf("VM_FAULT result %d addr=%jx type=%02x flags=%02x "
571 			"fs.m=%p fs.prot=%02x fs.wired=%02x fs.entry=%p\n",
572 			result, (intmax_t)vaddr, fault_type, fault_flags,
573 			fs.m, fs.prot, fs.wired, fs.entry);
574 	}
575 
576 	if (result == KERN_TRY_AGAIN) {
577 		vm_object_drop(fs.first_object);
578 		++retry;
579 		goto RetryFault;
580 	}
581 	if (result != KERN_SUCCESS)
582 		goto done;
583 
584 	/*
585 	 * On success vm_fault_object() does not unlock or deallocate, and fs.m
586 	 * will contain a busied page.
587 	 *
588 	 * Enter the page into the pmap and do pmap-related adjustments.
589 	 */
590 	KKASSERT(fs.lookup_still_valid == TRUE);
591 	vm_page_flag_set(fs.m, PG_REFERENCED);
592 	pmap_enter(fs.map->pmap, vaddr, fs.m, fs.prot | inherit_prot,
593 		   fs.wired, fs.entry);
594 
595 	/*KKASSERT(fs.m->queue == PQ_NONE); page-in op may deactivate page */
596 	KKASSERT(fs.m->flags & PG_BUSY);
597 
598 	/*
599 	 * If the page is not wired down, then put it where the pageout daemon
600 	 * can find it.
601 	 */
602 	if (fs.fault_flags & VM_FAULT_WIRE_MASK) {
603 		if (fs.wired)
604 			vm_page_wire(fs.m);
605 		else
606 			vm_page_unwire(fs.m, 1);
607 	} else {
608 		vm_page_activate(fs.m);
609 	}
610 	vm_page_wakeup(fs.m);
611 
612 	/*
613 	 * Burst in a few more pages if possible.  The fs.map should still
614 	 * be locked.  To avoid interlocking against a vnode->getblk
615 	 * operation we had to be sure to unbusy our primary vm_page above
616 	 * first.
617 	 *
618 	 * A normal burst can continue down backing store, only execute
619 	 * if we are holding an exclusive lock, otherwise the exclusive
620 	 * locks the burst code gets might cause excessive SMP collisions.
621 	 *
622 	 * A quick burst can be utilized when there is no backing object
623 	 * (i.e. a shared file mmap).
624 	 */
625 	if ((fault_flags & VM_FAULT_BURST) &&
626 	    (fs.fault_flags & VM_FAULT_WIRE_MASK) == 0 &&
627 	    fs.wired == 0) {
628 		if (fs.first_shared == 0 && fs.shared == 0) {
629 			vm_prefault(fs.map->pmap, vaddr,
630 				    fs.entry, fs.prot, fault_flags);
631 		} else {
632 			vm_prefault_quick(fs.map->pmap, vaddr,
633 					  fs.entry, fs.prot, fault_flags);
634 		}
635 	}
636 
637 done_success:
638 	mycpu->gd_cnt.v_vm_faults++;
639 	if (td->td_lwp)
640 		++td->td_lwp->lwp_ru.ru_minflt;
641 
642 	/*
643 	 * Unlock everything, and return
644 	 */
645 	unlock_things(&fs);
646 
647 	if (td->td_lwp) {
648 		if (fs.hardfault) {
649 			td->td_lwp->lwp_ru.ru_majflt++;
650 		} else {
651 			td->td_lwp->lwp_ru.ru_minflt++;
652 		}
653 	}
654 
655 	/*vm_object_deallocate(fs.first_object);*/
656 	/*fs.m = NULL; */
657 	/*fs.first_object = NULL; must still drop later */
658 
659 	result = KERN_SUCCESS;
660 done:
661 	if (fs.first_object)
662 		vm_object_drop(fs.first_object);
663 done2:
664 	lwkt_reltoken(&map->token);
665 	if (lp)
666 		lp->lwp_flags &= ~LWP_PAGING;
667 
668 #if !defined(NO_SWAPPING)
669 	/*
670 	 * Check the process RSS limit and force deactivation and
671 	 * (asynchronous) paging if necessary.  This is a complex operation,
672 	 * only do it for direct user-mode faults, for now.
673 	 *
674 	 * To reduce overhead implement approximately a ~16MB hysteresis.
675 	 */
676 	p = td->td_proc;
677 	if ((fault_flags & VM_FAULT_USERMODE) && lp &&
678 	    p->p_limit && map->pmap && vm_pageout_memuse_mode >= 1 &&
679 	    map != &kernel_map) {
680 		vm_pindex_t limit;
681 		vm_pindex_t size;
682 
683 		limit = OFF_TO_IDX(qmin(p->p_rlimit[RLIMIT_RSS].rlim_cur,
684 					p->p_rlimit[RLIMIT_RSS].rlim_max));
685 		size = pmap_resident_tlnw_count(map->pmap);
686 		if (limit >= 0 && size > 4096 && size - 4096 >= limit) {
687 			vm_pageout_map_deactivate_pages(map, limit);
688 		}
689 	}
690 #endif
691 
692 	return (result);
693 }
694 
695 /*
696  * Fault in the specified virtual address in the current process map,
697  * returning a held VM page or NULL.  See vm_fault_page() for more
698  * information.
699  *
700  * No requirements.
701  */
702 vm_page_t
703 vm_fault_page_quick(vm_offset_t va, vm_prot_t fault_type, int *errorp)
704 {
705 	struct lwp *lp = curthread->td_lwp;
706 	vm_page_t m;
707 
708 	m = vm_fault_page(&lp->lwp_vmspace->vm_map, va,
709 			  fault_type, VM_FAULT_NORMAL, errorp);
710 	return(m);
711 }
712 
713 /*
714  * Fault in the specified virtual address in the specified map, doing all
715  * necessary manipulation of the object store and all necessary I/O.  Return
716  * a held VM page or NULL, and set *errorp.  The related pmap is not
717  * updated.
718  *
719  * The returned page will be properly dirtied if VM_PROT_WRITE was specified,
720  * and marked PG_REFERENCED as well.
721  *
722  * If the page cannot be faulted writable and VM_PROT_WRITE was specified, an
723  * error will be returned.
724  *
725  * No requirements.
726  */
727 vm_page_t
728 vm_fault_page(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
729 	      int fault_flags, int *errorp)
730 {
731 	vm_pindex_t first_pindex;
732 	struct faultstate fs;
733 	int result;
734 	int retry = 0;
735 	vm_prot_t orig_fault_type = fault_type;
736 
737 	fs.hardfault = 0;
738 	fs.fault_flags = fault_flags;
739 	KKASSERT((fault_flags & VM_FAULT_WIRE_MASK) == 0);
740 
741 	/*
742 	 * Dive the pmap (concurrency possible).  If we find the
743 	 * appropriate page we can terminate early and quickly.
744 	 */
745 	fs.m = pmap_fault_page_quick(map->pmap, vaddr, fault_type);
746 	if (fs.m) {
747 		*errorp = 0;
748 		return(fs.m);
749 	}
750 
751 	/*
752 	 * Otherwise take a concurrency hit and do a formal page
753 	 * fault.
754 	 */
755 	fs.shared = vm_shared_fault;
756 	fs.first_shared = vm_shared_fault;
757 	fs.vp = NULL;
758 	lwkt_gettoken(&map->token);
759 
760 	/*
761 	 * swap_pager_unswapped() needs an exclusive object
762 	 */
763 	if (fault_flags & (VM_FAULT_UNSWAP | VM_FAULT_DIRTY)) {
764 		fs.first_shared = 0;
765 	}
766 
767 RetryFault:
768 	/*
769 	 * Find the vm_map_entry representing the backing store and resolve
770 	 * the top level object and page index.  This may have the side
771 	 * effect of executing a copy-on-write on the map entry and/or
772 	 * creating a shadow object, but will not COW any actual VM pages.
773 	 *
774 	 * On success fs.map is left read-locked and various other fields
775 	 * are initialized but not otherwise referenced or locked.
776 	 *
777 	 * NOTE!  vm_map_lookup will upgrade the fault_type to VM_FAULT_WRITE
778 	 * if the map entry is a virtual page table and also writable,
779 	 * so we can set the 'A'accessed bit in the virtual page table entry.
780 	 */
781 	fs.map = map;
782 	result = vm_map_lookup(&fs.map, vaddr, fault_type,
783 			       &fs.entry, &fs.first_object,
784 			       &first_pindex, &fs.first_prot, &fs.wired);
785 
786 	if (result != KERN_SUCCESS) {
787 		*errorp = result;
788 		fs.m = NULL;
789 		goto done;
790 	}
791 
792 	/*
793 	 * fs.map is read-locked
794 	 *
795 	 * Misc checks.  Save the map generation number to detect races.
796 	 */
797 	fs.map_generation = fs.map->timestamp;
798 	fs.lookup_still_valid = TRUE;
799 	fs.first_m = NULL;
800 	fs.object = fs.first_object;	/* so unlock_and_deallocate works */
801 
802 	if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
803 		panic("vm_fault: fault on nofault entry, addr: %lx",
804 		    (u_long)vaddr);
805 	}
806 
807 	/*
808 	 * A user-kernel shared map has no VM object and bypasses
809 	 * everything.  We execute the uksmap function with a temporary
810 	 * fictitious vm_page.  The address is directly mapped with no
811 	 * management.
812 	 */
813 	if (fs.entry->maptype == VM_MAPTYPE_UKSMAP) {
814 		struct vm_page fakem;
815 
816 		bzero(&fakem, sizeof(fakem));
817 		fakem.pindex = first_pindex;
818 		fakem.flags = PG_BUSY | PG_FICTITIOUS | PG_UNMANAGED;
819 		fakem.valid = VM_PAGE_BITS_ALL;
820 		fakem.pat_mode = VM_MEMATTR_DEFAULT;
821 		if (fs.entry->object.uksmap(fs.entry->aux.dev, &fakem)) {
822 			*errorp = KERN_FAILURE;
823 			fs.m = NULL;
824 			unlock_things(&fs);
825 			goto done2;
826 		}
827 		fs.m = PHYS_TO_VM_PAGE(fakem.phys_addr);
828 		vm_page_hold(fs.m);
829 
830 		unlock_things(&fs);
831 		*errorp = 0;
832 		goto done;
833 	}
834 
835 
836 	/*
837 	 * A system map entry may return a NULL object.  No object means
838 	 * no pager means an unrecoverable kernel fault.
839 	 */
840 	if (fs.first_object == NULL) {
841 		panic("vm_fault: unrecoverable fault at %p in entry %p",
842 			(void *)vaddr, fs.entry);
843 	}
844 
845 	/*
846 	 * Fail here if not a trivial anonymous page fault and TDF_NOFAULT
847 	 * is set.
848 	 *
849 	 * Unfortunately a deadlock can occur if we are forced to page-in
850 	 * from swap, but diving all the way into the vm_pager_get_page()
851 	 * function to find out is too much.  Just check the object type.
852 	 */
853 	if ((curthread->td_flags & TDF_NOFAULT) &&
854 	    (retry ||
855 	     fs.first_object->type == OBJT_VNODE ||
856 	     fs.first_object->type == OBJT_SWAP ||
857 	     fs.first_object->backing_object)) {
858 		*errorp = KERN_FAILURE;
859 		unlock_things(&fs);
860 		goto done2;
861 	}
862 
863 	/*
864 	 * If the entry is wired we cannot change the page protection.
865 	 */
866 	if (fs.wired)
867 		fault_type = fs.first_prot;
868 
869 	/*
870 	 * Make a reference to this object to prevent its disposal while we
871 	 * are messing with it.  Once we have the reference, the map is free
872 	 * to be diddled.  Since objects reference their shadows (and copies),
873 	 * they will stay around as well.
874 	 *
875 	 * The reference should also prevent an unexpected collapse of the
876 	 * parent that might move pages from the current object into the
877 	 * parent unexpectedly, resulting in corruption.
878 	 *
879 	 * Bump the paging-in-progress count to prevent size changes (e.g.
880 	 * truncation operations) during I/O.  This must be done after
881 	 * obtaining the vnode lock in order to avoid possible deadlocks.
882 	 */
883 	if (fs.first_shared)
884 		vm_object_hold_shared(fs.first_object);
885 	else
886 		vm_object_hold(fs.first_object);
887 	if (fs.vp == NULL)
888 		fs.vp = vnode_pager_lock(fs.first_object);	/* shared */
889 
890 	/*
891 	 * The page we want is at (first_object, first_pindex), but if the
892 	 * vm_map_entry is VM_MAPTYPE_VPAGETABLE we have to traverse the
893 	 * page table to figure out the actual pindex.
894 	 *
895 	 * NOTE!  DEVELOPMENT IN PROGRESS, THIS IS AN INITIAL IMPLEMENTATION
896 	 * ONLY
897 	 */
898 	if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
899 		result = vm_fault_vpagetable(&fs, &first_pindex,
900 					     fs.entry->aux.master_pde,
901 					     fault_type, 1);
902 		if (result == KERN_TRY_AGAIN) {
903 			vm_object_drop(fs.first_object);
904 			++retry;
905 			goto RetryFault;
906 		}
907 		if (result != KERN_SUCCESS) {
908 			*errorp = result;
909 			fs.m = NULL;
910 			goto done;
911 		}
912 	}
913 
914 	/*
915 	 * Now we have the actual (object, pindex), fault in the page.  If
916 	 * vm_fault_object() fails it will unlock and deallocate the FS
917 	 * data.   If it succeeds everything remains locked and fs->object
918 	 * will have an additinal PIP count if it is not equal to
919 	 * fs->first_object
920 	 */
921 	fs.m = NULL;
922 	result = vm_fault_object(&fs, first_pindex, fault_type, 1);
923 
924 	if (result == KERN_TRY_AGAIN) {
925 		vm_object_drop(fs.first_object);
926 		++retry;
927 		goto RetryFault;
928 	}
929 	if (result != KERN_SUCCESS) {
930 		*errorp = result;
931 		fs.m = NULL;
932 		goto done;
933 	}
934 
935 	if ((orig_fault_type & VM_PROT_WRITE) &&
936 	    (fs.prot & VM_PROT_WRITE) == 0) {
937 		*errorp = KERN_PROTECTION_FAILURE;
938 		unlock_and_deallocate(&fs);
939 		fs.m = NULL;
940 		goto done;
941 	}
942 
943 	/*
944 	 * DO NOT UPDATE THE PMAP!!!  This function may be called for
945 	 * a pmap unrelated to the current process pmap, in which case
946 	 * the current cpu core will not be listed in the pmap's pm_active
947 	 * mask.  Thus invalidation interlocks will fail to work properly.
948 	 *
949 	 * (for example, 'ps' uses procfs to read program arguments from
950 	 * each process's stack).
951 	 *
952 	 * In addition to the above this function will be called to acquire
953 	 * a page that might already be faulted in, re-faulting it
954 	 * continuously is a waste of time.
955 	 *
956 	 * XXX could this have been the cause of our random seg-fault
957 	 *     issues?  procfs accesses user stacks.
958 	 */
959 	vm_page_flag_set(fs.m, PG_REFERENCED);
960 #if 0
961 	pmap_enter(fs.map->pmap, vaddr, fs.m, fs.prot, fs.wired, NULL);
962 	mycpu->gd_cnt.v_vm_faults++;
963 	if (curthread->td_lwp)
964 		++curthread->td_lwp->lwp_ru.ru_minflt;
965 #endif
966 
967 	/*
968 	 * On success vm_fault_object() does not unlock or deallocate, and fs.m
969 	 * will contain a busied page.  So we must unlock here after having
970 	 * messed with the pmap.
971 	 */
972 	unlock_things(&fs);
973 
974 	/*
975 	 * Return a held page.  We are not doing any pmap manipulation so do
976 	 * not set PG_MAPPED.  However, adjust the page flags according to
977 	 * the fault type because the caller may not use a managed pmapping
978 	 * (so we don't want to lose the fact that the page will be dirtied
979 	 * if a write fault was specified).
980 	 */
981 	vm_page_hold(fs.m);
982 	vm_page_activate(fs.m);
983 	if (fault_type & VM_PROT_WRITE)
984 		vm_page_dirty(fs.m);
985 
986 	if (curthread->td_lwp) {
987 		if (fs.hardfault) {
988 			curthread->td_lwp->lwp_ru.ru_majflt++;
989 		} else {
990 			curthread->td_lwp->lwp_ru.ru_minflt++;
991 		}
992 	}
993 
994 	/*
995 	 * Unlock everything, and return the held page.
996 	 */
997 	vm_page_wakeup(fs.m);
998 	/*vm_object_deallocate(fs.first_object);*/
999 	/*fs.first_object = NULL; */
1000 	*errorp = 0;
1001 
1002 done:
1003 	if (fs.first_object)
1004 		vm_object_drop(fs.first_object);
1005 done2:
1006 	lwkt_reltoken(&map->token);
1007 	return(fs.m);
1008 }
1009 
1010 /*
1011  * Fault in the specified (object,offset), dirty the returned page as
1012  * needed.  If the requested fault_type cannot be done NULL and an
1013  * error is returned.
1014  *
1015  * A held (but not busied) page is returned.
1016  *
1017  * The passed in object must be held as specified by the shared
1018  * argument.
1019  */
1020 vm_page_t
1021 vm_fault_object_page(vm_object_t object, vm_ooffset_t offset,
1022 		     vm_prot_t fault_type, int fault_flags,
1023 		     int *sharedp, int *errorp)
1024 {
1025 	int result;
1026 	vm_pindex_t first_pindex;
1027 	struct faultstate fs;
1028 	struct vm_map_entry entry;
1029 
1030 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1031 	bzero(&entry, sizeof(entry));
1032 	entry.object.vm_object = object;
1033 	entry.maptype = VM_MAPTYPE_NORMAL;
1034 	entry.protection = entry.max_protection = fault_type;
1035 
1036 	fs.hardfault = 0;
1037 	fs.fault_flags = fault_flags;
1038 	fs.map = NULL;
1039 	fs.shared = vm_shared_fault;
1040 	fs.first_shared = *sharedp;
1041 	fs.vp = NULL;
1042 	KKASSERT((fault_flags & VM_FAULT_WIRE_MASK) == 0);
1043 
1044 	/*
1045 	 * Might require swap block adjustments
1046 	 */
1047 	if (fs.first_shared && (fault_flags & (VM_FAULT_UNSWAP | VM_FAULT_DIRTY))) {
1048 		fs.first_shared = 0;
1049 		vm_object_upgrade(object);
1050 	}
1051 
1052 	/*
1053 	 * Retry loop as needed (typically for shared->exclusive transitions)
1054 	 */
1055 RetryFault:
1056 	*sharedp = fs.first_shared;
1057 	first_pindex = OFF_TO_IDX(offset);
1058 	fs.first_object = object;
1059 	fs.entry = &entry;
1060 	fs.first_prot = fault_type;
1061 	fs.wired = 0;
1062 	/*fs.map_generation = 0; unused */
1063 
1064 	/*
1065 	 * Make a reference to this object to prevent its disposal while we
1066 	 * are messing with it.  Once we have the reference, the map is free
1067 	 * to be diddled.  Since objects reference their shadows (and copies),
1068 	 * they will stay around as well.
1069 	 *
1070 	 * The reference should also prevent an unexpected collapse of the
1071 	 * parent that might move pages from the current object into the
1072 	 * parent unexpectedly, resulting in corruption.
1073 	 *
1074 	 * Bump the paging-in-progress count to prevent size changes (e.g.
1075 	 * truncation operations) during I/O.  This must be done after
1076 	 * obtaining the vnode lock in order to avoid possible deadlocks.
1077 	 */
1078 	if (fs.vp == NULL)
1079 		fs.vp = vnode_pager_lock(fs.first_object);
1080 
1081 	fs.lookup_still_valid = TRUE;
1082 	fs.first_m = NULL;
1083 	fs.object = fs.first_object;	/* so unlock_and_deallocate works */
1084 
1085 #if 0
1086 	/* XXX future - ability to operate on VM object using vpagetable */
1087 	if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
1088 		result = vm_fault_vpagetable(&fs, &first_pindex,
1089 					     fs.entry->aux.master_pde,
1090 					     fault_type, 0);
1091 		if (result == KERN_TRY_AGAIN) {
1092 			if (fs.first_shared == 0 && *sharedp)
1093 				vm_object_upgrade(object);
1094 			goto RetryFault;
1095 		}
1096 		if (result != KERN_SUCCESS) {
1097 			*errorp = result;
1098 			return (NULL);
1099 		}
1100 	}
1101 #endif
1102 
1103 	/*
1104 	 * Now we have the actual (object, pindex), fault in the page.  If
1105 	 * vm_fault_object() fails it will unlock and deallocate the FS
1106 	 * data.   If it succeeds everything remains locked and fs->object
1107 	 * will have an additinal PIP count if it is not equal to
1108 	 * fs->first_object
1109 	 *
1110 	 * On KERN_TRY_AGAIN vm_fault_object() leaves fs.first_object intact.
1111 	 * We may have to upgrade its lock to handle the requested fault.
1112 	 */
1113 	result = vm_fault_object(&fs, first_pindex, fault_type, 0);
1114 
1115 	if (result == KERN_TRY_AGAIN) {
1116 		if (fs.first_shared == 0 && *sharedp)
1117 			vm_object_upgrade(object);
1118 		goto RetryFault;
1119 	}
1120 	if (result != KERN_SUCCESS) {
1121 		*errorp = result;
1122 		return(NULL);
1123 	}
1124 
1125 	if ((fault_type & VM_PROT_WRITE) && (fs.prot & VM_PROT_WRITE) == 0) {
1126 		*errorp = KERN_PROTECTION_FAILURE;
1127 		unlock_and_deallocate(&fs);
1128 		return(NULL);
1129 	}
1130 
1131 	/*
1132 	 * On success vm_fault_object() does not unlock or deallocate, so we
1133 	 * do it here.  Note that the returned fs.m will be busied.
1134 	 */
1135 	unlock_things(&fs);
1136 
1137 	/*
1138 	 * Return a held page.  We are not doing any pmap manipulation so do
1139 	 * not set PG_MAPPED.  However, adjust the page flags according to
1140 	 * the fault type because the caller may not use a managed pmapping
1141 	 * (so we don't want to lose the fact that the page will be dirtied
1142 	 * if a write fault was specified).
1143 	 */
1144 	vm_page_hold(fs.m);
1145 	vm_page_activate(fs.m);
1146 	if ((fault_type & VM_PROT_WRITE) || (fault_flags & VM_FAULT_DIRTY))
1147 		vm_page_dirty(fs.m);
1148 	if (fault_flags & VM_FAULT_UNSWAP)
1149 		swap_pager_unswapped(fs.m);
1150 
1151 	/*
1152 	 * Indicate that the page was accessed.
1153 	 */
1154 	vm_page_flag_set(fs.m, PG_REFERENCED);
1155 
1156 	if (curthread->td_lwp) {
1157 		if (fs.hardfault) {
1158 			curthread->td_lwp->lwp_ru.ru_majflt++;
1159 		} else {
1160 			curthread->td_lwp->lwp_ru.ru_minflt++;
1161 		}
1162 	}
1163 
1164 	/*
1165 	 * Unlock everything, and return the held page.
1166 	 */
1167 	vm_page_wakeup(fs.m);
1168 	/*vm_object_deallocate(fs.first_object);*/
1169 	/*fs.first_object = NULL; */
1170 
1171 	*errorp = 0;
1172 	return(fs.m);
1173 }
1174 
1175 /*
1176  * Translate the virtual page number (first_pindex) that is relative
1177  * to the address space into a logical page number that is relative to the
1178  * backing object.  Use the virtual page table pointed to by (vpte).
1179  *
1180  * This implements an N-level page table.  Any level can terminate the
1181  * scan by setting VPTE_PS.   A linear mapping is accomplished by setting
1182  * VPTE_PS in the master page directory entry set via mcontrol(MADV_SETMAP).
1183  */
1184 static
1185 int
1186 vm_fault_vpagetable(struct faultstate *fs, vm_pindex_t *pindex,
1187 		    vpte_t vpte, int fault_type, int allow_nofault)
1188 {
1189 	struct lwbuf *lwb;
1190 	struct lwbuf lwb_cache;
1191 	int vshift = VPTE_FRAME_END - PAGE_SHIFT; /* index bits remaining */
1192 	int result = KERN_SUCCESS;
1193 	vpte_t *ptep;
1194 
1195 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(fs->first_object));
1196 	for (;;) {
1197 		/*
1198 		 * We cannot proceed if the vpte is not valid, not readable
1199 		 * for a read fault, or not writable for a write fault.
1200 		 */
1201 		if ((vpte & VPTE_V) == 0) {
1202 			unlock_and_deallocate(fs);
1203 			return (KERN_FAILURE);
1204 		}
1205 		if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_RW) == 0) {
1206 			unlock_and_deallocate(fs);
1207 			return (KERN_FAILURE);
1208 		}
1209 		if ((vpte & VPTE_PS) || vshift == 0)
1210 			break;
1211 		KKASSERT(vshift >= VPTE_PAGE_BITS);
1212 
1213 		/*
1214 		 * Get the page table page.  Nominally we only read the page
1215 		 * table, but since we are actively setting VPTE_M and VPTE_A,
1216 		 * tell vm_fault_object() that we are writing it.
1217 		 *
1218 		 * There is currently no real need to optimize this.
1219 		 */
1220 		result = vm_fault_object(fs, (vpte & VPTE_FRAME) >> PAGE_SHIFT,
1221 					 VM_PROT_READ|VM_PROT_WRITE,
1222 					 allow_nofault);
1223 		if (result != KERN_SUCCESS)
1224 			return (result);
1225 
1226 		/*
1227 		 * Process the returned fs.m and look up the page table
1228 		 * entry in the page table page.
1229 		 */
1230 		vshift -= VPTE_PAGE_BITS;
1231 		lwb = lwbuf_alloc(fs->m, &lwb_cache);
1232 		ptep = ((vpte_t *)lwbuf_kva(lwb) +
1233 		        ((*pindex >> vshift) & VPTE_PAGE_MASK));
1234 		vpte = *ptep;
1235 
1236 		/*
1237 		 * Page table write-back.  If the vpte is valid for the
1238 		 * requested operation, do a write-back to the page table.
1239 		 *
1240 		 * XXX VPTE_M is not set properly for page directory pages.
1241 		 * It doesn't get set in the page directory if the page table
1242 		 * is modified during a read access.
1243 		 */
1244 		vm_page_activate(fs->m);
1245 		if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_V) &&
1246 		    (vpte & VPTE_RW)) {
1247 			if ((vpte & (VPTE_M|VPTE_A)) != (VPTE_M|VPTE_A)) {
1248 				atomic_set_long(ptep, VPTE_M | VPTE_A);
1249 				vm_page_dirty(fs->m);
1250 			}
1251 		}
1252 		if ((fault_type & VM_PROT_READ) && (vpte & VPTE_V)) {
1253 			if ((vpte & VPTE_A) == 0) {
1254 				atomic_set_long(ptep, VPTE_A);
1255 				vm_page_dirty(fs->m);
1256 			}
1257 		}
1258 		lwbuf_free(lwb);
1259 		vm_page_flag_set(fs->m, PG_REFERENCED);
1260 		vm_page_wakeup(fs->m);
1261 		fs->m = NULL;
1262 		cleanup_successful_fault(fs);
1263 	}
1264 	/*
1265 	 * Combine remaining address bits with the vpte.
1266 	 */
1267 	/* JG how many bits from each? */
1268 	*pindex = ((vpte & VPTE_FRAME) >> PAGE_SHIFT) +
1269 		  (*pindex & ((1L << vshift) - 1));
1270 	return (KERN_SUCCESS);
1271 }
1272 
1273 
1274 /*
1275  * This is the core of the vm_fault code.
1276  *
1277  * Do all operations required to fault-in (fs.first_object, pindex).  Run
1278  * through the shadow chain as necessary and do required COW or virtual
1279  * copy operations.  The caller has already fully resolved the vm_map_entry
1280  * and, if appropriate, has created a copy-on-write layer.  All we need to
1281  * do is iterate the object chain.
1282  *
1283  * On failure (fs) is unlocked and deallocated and the caller may return or
1284  * retry depending on the failure code.  On success (fs) is NOT unlocked or
1285  * deallocated, fs.m will contained a resolved, busied page, and fs.object
1286  * will have an additional PIP count if it is not equal to fs.first_object.
1287  *
1288  * If locks based on fs->first_shared or fs->shared are insufficient,
1289  * clear the appropriate field(s) and return RETRY.  COWs require that
1290  * first_shared be 0, while page allocations (or frees) require that
1291  * shared be 0.  Renames require that both be 0.
1292  *
1293  * fs->first_object must be held on call.
1294  */
1295 static
1296 int
1297 vm_fault_object(struct faultstate *fs, vm_pindex_t first_pindex,
1298 		vm_prot_t fault_type, int allow_nofault)
1299 {
1300 	vm_object_t next_object;
1301 	vm_pindex_t pindex;
1302 	int error;
1303 
1304 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(fs->first_object));
1305 	fs->prot = fs->first_prot;
1306 	fs->object = fs->first_object;
1307 	pindex = first_pindex;
1308 
1309 	vm_object_chain_acquire(fs->first_object, fs->shared);
1310 	vm_object_pip_add(fs->first_object, 1);
1311 
1312 	/*
1313 	 * If a read fault occurs we try to make the page writable if
1314 	 * possible.  There are three cases where we cannot make the
1315 	 * page mapping writable:
1316 	 *
1317 	 * (1) The mapping is read-only or the VM object is read-only,
1318 	 *     fs->prot above will simply not have VM_PROT_WRITE set.
1319 	 *
1320 	 * (2) If the mapping is a virtual page table we need to be able
1321 	 *     to detect writes so we can set VPTE_M in the virtual page
1322 	 *     table.
1323 	 *
1324 	 * (3) If the VM page is read-only or copy-on-write, upgrading would
1325 	 *     just result in an unnecessary COW fault.
1326 	 *
1327 	 * VM_PROT_VPAGED is set if faulting via a virtual page table and
1328 	 * causes adjustments to the 'M'odify bit to also turn off write
1329 	 * access to force a re-fault.
1330 	 */
1331 	if (fs->entry->maptype == VM_MAPTYPE_VPAGETABLE) {
1332 		if ((fault_type & VM_PROT_WRITE) == 0)
1333 			fs->prot &= ~VM_PROT_WRITE;
1334 	}
1335 
1336 	if (curthread->td_lwp && curthread->td_lwp->lwp_vmspace &&
1337 	    pmap_emulate_ad_bits(&curthread->td_lwp->lwp_vmspace->vm_pmap)) {
1338 		if ((fault_type & VM_PROT_WRITE) == 0)
1339 			fs->prot &= ~VM_PROT_WRITE;
1340 	}
1341 
1342 	/* vm_object_hold(fs->object); implied b/c object == first_object */
1343 
1344 	for (;;) {
1345 		/*
1346 		 * The entire backing chain from first_object to object
1347 		 * inclusive is chainlocked.
1348 		 *
1349 		 * If the object is dead, we stop here
1350 		 */
1351 		if (fs->object->flags & OBJ_DEAD) {
1352 			vm_object_pip_wakeup(fs->first_object);
1353 			vm_object_chain_release_all(fs->first_object,
1354 						    fs->object);
1355 			if (fs->object != fs->first_object)
1356 				vm_object_drop(fs->object);
1357 			unlock_and_deallocate(fs);
1358 			return (KERN_PROTECTION_FAILURE);
1359 		}
1360 
1361 		/*
1362 		 * See if the page is resident.  Wait/Retry if the page is
1363 		 * busy (lots of stuff may have changed so we can't continue
1364 		 * in that case).
1365 		 *
1366 		 * We can theoretically allow the soft-busy case on a read
1367 		 * fault if the page is marked valid, but since such
1368 		 * pages are typically already pmap'd, putting that
1369 		 * special case in might be more effort then it is
1370 		 * worth.  We cannot under any circumstances mess
1371 		 * around with a vm_page_t->busy page except, perhaps,
1372 		 * to pmap it.
1373 		 */
1374 		fs->m = vm_page_lookup_busy_try(fs->object, pindex,
1375 						TRUE, &error);
1376 		if (error) {
1377 			vm_object_pip_wakeup(fs->first_object);
1378 			vm_object_chain_release_all(fs->first_object,
1379 						    fs->object);
1380 			if (fs->object != fs->first_object)
1381 				vm_object_drop(fs->object);
1382 			unlock_things(fs);
1383 			vm_page_sleep_busy(fs->m, TRUE, "vmpfw");
1384 			mycpu->gd_cnt.v_intrans++;
1385 			/*vm_object_deallocate(fs->first_object);*/
1386 			/*fs->first_object = NULL;*/
1387 			fs->m = NULL;
1388 			return (KERN_TRY_AGAIN);
1389 		}
1390 		if (fs->m) {
1391 			/*
1392 			 * The page is busied for us.
1393 			 *
1394 			 * If reactivating a page from PQ_CACHE we may have
1395 			 * to rate-limit.
1396 			 */
1397 			int queue = fs->m->queue;
1398 			vm_page_unqueue_nowakeup(fs->m);
1399 
1400 			if ((queue - fs->m->pc) == PQ_CACHE &&
1401 			    vm_page_count_severe()) {
1402 				vm_page_activate(fs->m);
1403 				vm_page_wakeup(fs->m);
1404 				fs->m = NULL;
1405 				vm_object_pip_wakeup(fs->first_object);
1406 				vm_object_chain_release_all(fs->first_object,
1407 							    fs->object);
1408 				if (fs->object != fs->first_object)
1409 					vm_object_drop(fs->object);
1410 				unlock_and_deallocate(fs);
1411 				if (allow_nofault == 0 ||
1412 				    (curthread->td_flags & TDF_NOFAULT) == 0) {
1413 					thread_t td;
1414 
1415 					vm_wait_pfault();
1416 					td = curthread;
1417 					if (td->td_proc && (td->td_proc->p_flags & P_LOWMEMKILL))
1418 						return (KERN_PROTECTION_FAILURE);
1419 				}
1420 				return (KERN_TRY_AGAIN);
1421 			}
1422 
1423 			/*
1424 			 * If it still isn't completely valid (readable),
1425 			 * or if a read-ahead-mark is set on the VM page,
1426 			 * jump to readrest, else we found the page and
1427 			 * can return.
1428 			 *
1429 			 * We can release the spl once we have marked the
1430 			 * page busy.
1431 			 */
1432 			if (fs->m->object != &kernel_object) {
1433 				if ((fs->m->valid & VM_PAGE_BITS_ALL) !=
1434 				    VM_PAGE_BITS_ALL) {
1435 					goto readrest;
1436 				}
1437 				if (fs->m->flags & PG_RAM) {
1438 					if (debug_cluster)
1439 						kprintf("R");
1440 					vm_page_flag_clear(fs->m, PG_RAM);
1441 					goto readrest;
1442 				}
1443 			}
1444 			break; /* break to PAGE HAS BEEN FOUND */
1445 		}
1446 
1447 		/*
1448 		 * Page is not resident, If this is the search termination
1449 		 * or the pager might contain the page, allocate a new page.
1450 		 */
1451 		if (TRYPAGER(fs) || fs->object == fs->first_object) {
1452 			/*
1453 			 * Allocating, must be exclusive.
1454 			 */
1455 			if (fs->object == fs->first_object &&
1456 			    fs->first_shared) {
1457 				fs->first_shared = 0;
1458 				vm_object_pip_wakeup(fs->first_object);
1459 				vm_object_chain_release_all(fs->first_object,
1460 							    fs->object);
1461 				if (fs->object != fs->first_object)
1462 					vm_object_drop(fs->object);
1463 				unlock_and_deallocate(fs);
1464 				return (KERN_TRY_AGAIN);
1465 			}
1466 			if (fs->object != fs->first_object &&
1467 			    fs->shared) {
1468 				fs->first_shared = 0;
1469 				fs->shared = 0;
1470 				vm_object_pip_wakeup(fs->first_object);
1471 				vm_object_chain_release_all(fs->first_object,
1472 							    fs->object);
1473 				if (fs->object != fs->first_object)
1474 					vm_object_drop(fs->object);
1475 				unlock_and_deallocate(fs);
1476 				return (KERN_TRY_AGAIN);
1477 			}
1478 
1479 			/*
1480 			 * If the page is beyond the object size we fail
1481 			 */
1482 			if (pindex >= fs->object->size) {
1483 				vm_object_pip_wakeup(fs->first_object);
1484 				vm_object_chain_release_all(fs->first_object,
1485 							    fs->object);
1486 				if (fs->object != fs->first_object)
1487 					vm_object_drop(fs->object);
1488 				unlock_and_deallocate(fs);
1489 				return (KERN_PROTECTION_FAILURE);
1490 			}
1491 
1492 			/*
1493 			 * Allocate a new page for this object/offset pair.
1494 			 *
1495 			 * It is possible for the allocation to race, so
1496 			 * handle the case.
1497 			 */
1498 			fs->m = NULL;
1499 			if (!vm_page_count_severe()) {
1500 				fs->m = vm_page_alloc(fs->object, pindex,
1501 				    ((fs->vp || fs->object->backing_object) ?
1502 					VM_ALLOC_NULL_OK | VM_ALLOC_NORMAL :
1503 					VM_ALLOC_NULL_OK | VM_ALLOC_NORMAL |
1504 					VM_ALLOC_USE_GD | VM_ALLOC_ZERO));
1505 			}
1506 			if (fs->m == NULL) {
1507 				vm_object_pip_wakeup(fs->first_object);
1508 				vm_object_chain_release_all(fs->first_object,
1509 							    fs->object);
1510 				if (fs->object != fs->first_object)
1511 					vm_object_drop(fs->object);
1512 				unlock_and_deallocate(fs);
1513 				if (allow_nofault == 0 ||
1514 				    (curthread->td_flags & TDF_NOFAULT) == 0) {
1515 					thread_t td;
1516 
1517 					vm_wait_pfault();
1518 					td = curthread;
1519 					if (td->td_proc && (td->td_proc->p_flags & P_LOWMEMKILL))
1520 						return (KERN_PROTECTION_FAILURE);
1521 				}
1522 				return (KERN_TRY_AGAIN);
1523 			}
1524 
1525 			/*
1526 			 * Fall through to readrest.  We have a new page which
1527 			 * will have to be paged (since m->valid will be 0).
1528 			 */
1529 		}
1530 
1531 readrest:
1532 		/*
1533 		 * We have found an invalid or partially valid page, a
1534 		 * page with a read-ahead mark which might be partially or
1535 		 * fully valid (and maybe dirty too), or we have allocated
1536 		 * a new page.
1537 		 *
1538 		 * Attempt to fault-in the page if there is a chance that the
1539 		 * pager has it, and potentially fault in additional pages
1540 		 * at the same time.
1541 		 *
1542 		 * If TRYPAGER is true then fs.m will be non-NULL and busied
1543 		 * for us.
1544 		 */
1545 		if (TRYPAGER(fs)) {
1546 			int rv;
1547 			int seqaccess;
1548 			u_char behavior = vm_map_entry_behavior(fs->entry);
1549 
1550 			if (behavior == MAP_ENTRY_BEHAV_RANDOM)
1551 				seqaccess = 0;
1552 			else
1553 				seqaccess = -1;
1554 
1555 			/*
1556 			 * Doing I/O may synchronously insert additional
1557 			 * pages so we can't be shared at this point either.
1558 			 *
1559 			 * NOTE: We can't free fs->m here in the allocated
1560 			 *	 case (fs->object != fs->first_object) as
1561 			 *	 this would require an exclusively locked
1562 			 *	 VM object.
1563 			 */
1564 			if (fs->object == fs->first_object &&
1565 			    fs->first_shared) {
1566 				vm_page_deactivate(fs->m);
1567 				vm_page_wakeup(fs->m);
1568 				fs->m = NULL;
1569 				fs->first_shared = 0;
1570 				vm_object_pip_wakeup(fs->first_object);
1571 				vm_object_chain_release_all(fs->first_object,
1572 							    fs->object);
1573 				if (fs->object != fs->first_object)
1574 					vm_object_drop(fs->object);
1575 				unlock_and_deallocate(fs);
1576 				return (KERN_TRY_AGAIN);
1577 			}
1578 			if (fs->object != fs->first_object &&
1579 			    fs->shared) {
1580 				vm_page_deactivate(fs->m);
1581 				vm_page_wakeup(fs->m);
1582 				fs->m = NULL;
1583 				fs->first_shared = 0;
1584 				fs->shared = 0;
1585 				vm_object_pip_wakeup(fs->first_object);
1586 				vm_object_chain_release_all(fs->first_object,
1587 							    fs->object);
1588 				if (fs->object != fs->first_object)
1589 					vm_object_drop(fs->object);
1590 				unlock_and_deallocate(fs);
1591 				return (KERN_TRY_AGAIN);
1592 			}
1593 
1594 			/*
1595 			 * Avoid deadlocking against the map when doing I/O.
1596 			 * fs.object and the page is PG_BUSY'd.
1597 			 *
1598 			 * NOTE: Once unlocked, fs->entry can become stale
1599 			 *	 so this will NULL it out.
1600 			 *
1601 			 * NOTE: fs->entry is invalid until we relock the
1602 			 *	 map and verify that the timestamp has not
1603 			 *	 changed.
1604 			 */
1605 			unlock_map(fs);
1606 
1607 			/*
1608 			 * Acquire the page data.  We still hold a ref on
1609 			 * fs.object and the page has been PG_BUSY's.
1610 			 *
1611 			 * The pager may replace the page (for example, in
1612 			 * order to enter a fictitious page into the
1613 			 * object).  If it does so it is responsible for
1614 			 * cleaning up the passed page and properly setting
1615 			 * the new page PG_BUSY.
1616 			 *
1617 			 * If we got here through a PG_RAM read-ahead
1618 			 * mark the page may be partially dirty and thus
1619 			 * not freeable.  Don't bother checking to see
1620 			 * if the pager has the page because we can't free
1621 			 * it anyway.  We have to depend on the get_page
1622 			 * operation filling in any gaps whether there is
1623 			 * backing store or not.
1624 			 */
1625 			rv = vm_pager_get_page(fs->object, &fs->m, seqaccess);
1626 
1627 			if (rv == VM_PAGER_OK) {
1628 				/*
1629 				 * Relookup in case pager changed page. Pager
1630 				 * is responsible for disposition of old page
1631 				 * if moved.
1632 				 *
1633 				 * XXX other code segments do relookups too.
1634 				 * It's a bad abstraction that needs to be
1635 				 * fixed/removed.
1636 				 */
1637 				fs->m = vm_page_lookup(fs->object, pindex);
1638 				if (fs->m == NULL) {
1639 					vm_object_pip_wakeup(fs->first_object);
1640 					vm_object_chain_release_all(
1641 						fs->first_object, fs->object);
1642 					if (fs->object != fs->first_object)
1643 						vm_object_drop(fs->object);
1644 					unlock_and_deallocate(fs);
1645 					return (KERN_TRY_AGAIN);
1646 				}
1647 				++fs->hardfault;
1648 				break; /* break to PAGE HAS BEEN FOUND */
1649 			}
1650 
1651 			/*
1652 			 * Remove the bogus page (which does not exist at this
1653 			 * object/offset); before doing so, we must get back
1654 			 * our object lock to preserve our invariant.
1655 			 *
1656 			 * Also wake up any other process that may want to bring
1657 			 * in this page.
1658 			 *
1659 			 * If this is the top-level object, we must leave the
1660 			 * busy page to prevent another process from rushing
1661 			 * past us, and inserting the page in that object at
1662 			 * the same time that we are.
1663 			 */
1664 			if (rv == VM_PAGER_ERROR) {
1665 				if (curproc) {
1666 					kprintf("vm_fault: pager read error, "
1667 						"pid %d (%s)\n",
1668 						curproc->p_pid,
1669 						curproc->p_comm);
1670 				} else {
1671 					kprintf("vm_fault: pager read error, "
1672 						"thread %p (%s)\n",
1673 						curthread,
1674 						curproc->p_comm);
1675 				}
1676 			}
1677 
1678 			/*
1679 			 * Data outside the range of the pager or an I/O error
1680 			 *
1681 			 * The page may have been wired during the pagein,
1682 			 * e.g. by the buffer cache, and cannot simply be
1683 			 * freed.  Call vnode_pager_freepage() to deal with it.
1684 			 *
1685 			 * Also note that we cannot free the page if we are
1686 			 * holding the related object shared. XXX not sure
1687 			 * what to do in that case.
1688 			 */
1689 			if (fs->object != fs->first_object) {
1690 				vnode_pager_freepage(fs->m);
1691 				fs->m = NULL;
1692 				/*
1693 				 * XXX - we cannot just fall out at this
1694 				 * point, m has been freed and is invalid!
1695 				 */
1696 			}
1697 			/*
1698 			 * XXX - the check for kernel_map is a kludge to work
1699 			 * around having the machine panic on a kernel space
1700 			 * fault w/ I/O error.
1701 			 */
1702 			if (((fs->map != &kernel_map) &&
1703 			    (rv == VM_PAGER_ERROR)) || (rv == VM_PAGER_BAD)) {
1704 				if (fs->m) {
1705 					if (fs->first_shared) {
1706 						vm_page_deactivate(fs->m);
1707 						vm_page_wakeup(fs->m);
1708 					} else {
1709 						vnode_pager_freepage(fs->m);
1710 					}
1711 					fs->m = NULL;
1712 				}
1713 				vm_object_pip_wakeup(fs->first_object);
1714 				vm_object_chain_release_all(fs->first_object,
1715 							    fs->object);
1716 				if (fs->object != fs->first_object)
1717 					vm_object_drop(fs->object);
1718 				unlock_and_deallocate(fs);
1719 				if (rv == VM_PAGER_ERROR)
1720 					return (KERN_FAILURE);
1721 				else
1722 					return (KERN_PROTECTION_FAILURE);
1723 				/* NOT REACHED */
1724 			}
1725 		}
1726 
1727 		/*
1728 		 * We get here if the object has a default pager (or unwiring)
1729 		 * or the pager doesn't have the page.
1730 		 *
1731 		 * fs->first_m will be used for the COW unless we find a
1732 		 * deeper page to be mapped read-only, in which case the
1733 		 * unlock*(fs) will free first_m.
1734 		 */
1735 		if (fs->object == fs->first_object)
1736 			fs->first_m = fs->m;
1737 
1738 		/*
1739 		 * Move on to the next object.  The chain lock should prevent
1740 		 * the backing_object from getting ripped out from under us.
1741 		 *
1742 		 * The object lock for the next object is governed by
1743 		 * fs->shared.
1744 		 */
1745 		if ((next_object = fs->object->backing_object) != NULL) {
1746 			if (fs->shared)
1747 				vm_object_hold_shared(next_object);
1748 			else
1749 				vm_object_hold(next_object);
1750 			vm_object_chain_acquire(next_object, fs->shared);
1751 			KKASSERT(next_object == fs->object->backing_object);
1752 			pindex += OFF_TO_IDX(fs->object->backing_object_offset);
1753 		}
1754 
1755 		if (next_object == NULL) {
1756 			/*
1757 			 * If there's no object left, fill the page in the top
1758 			 * object with zeros.
1759 			 */
1760 			if (fs->object != fs->first_object) {
1761 #if 0
1762 				if (fs->first_object->backing_object !=
1763 				    fs->object) {
1764 					vm_object_hold(fs->first_object->backing_object);
1765 				}
1766 #endif
1767 				vm_object_chain_release_all(
1768 					fs->first_object->backing_object,
1769 					fs->object);
1770 #if 0
1771 				if (fs->first_object->backing_object !=
1772 				    fs->object) {
1773 					vm_object_drop(fs->first_object->backing_object);
1774 				}
1775 #endif
1776 				vm_object_pip_wakeup(fs->object);
1777 				vm_object_drop(fs->object);
1778 				fs->object = fs->first_object;
1779 				pindex = first_pindex;
1780 				fs->m = fs->first_m;
1781 			}
1782 			fs->first_m = NULL;
1783 
1784 			/*
1785 			 * Zero the page and mark it valid.
1786 			 */
1787 			vm_page_zero_fill(fs->m);
1788 			mycpu->gd_cnt.v_zfod++;
1789 			fs->m->valid = VM_PAGE_BITS_ALL;
1790 			break;	/* break to PAGE HAS BEEN FOUND */
1791 		}
1792 		if (fs->object != fs->first_object) {
1793 			vm_object_pip_wakeup(fs->object);
1794 			vm_object_lock_swap();
1795 			vm_object_drop(fs->object);
1796 		}
1797 		KASSERT(fs->object != next_object,
1798 			("object loop %p", next_object));
1799 		fs->object = next_object;
1800 		vm_object_pip_add(fs->object, 1);
1801 	}
1802 
1803 	/*
1804 	 * PAGE HAS BEEN FOUND. [Loop invariant still holds -- the object lock
1805 	 * is held.]
1806 	 *
1807 	 * object still held.
1808 	 *
1809 	 * local shared variable may be different from fs->shared.
1810 	 *
1811 	 * If the page is being written, but isn't already owned by the
1812 	 * top-level object, we have to copy it into a new page owned by the
1813 	 * top-level object.
1814 	 */
1815 	KASSERT((fs->m->flags & PG_BUSY) != 0,
1816 		("vm_fault: not busy after main loop"));
1817 
1818 	if (fs->object != fs->first_object) {
1819 		/*
1820 		 * We only really need to copy if we want to write it.
1821 		 */
1822 		if (fault_type & VM_PROT_WRITE) {
1823 			/*
1824 			 * This allows pages to be virtually copied from a
1825 			 * backing_object into the first_object, where the
1826 			 * backing object has no other refs to it, and cannot
1827 			 * gain any more refs.  Instead of a bcopy, we just
1828 			 * move the page from the backing object to the
1829 			 * first object.  Note that we must mark the page
1830 			 * dirty in the first object so that it will go out
1831 			 * to swap when needed.
1832 			 */
1833 			if (
1834 				/*
1835 				 * Must be holding exclusive locks
1836 				 */
1837 				fs->first_shared == 0 &&
1838 				fs->shared == 0 &&
1839 				/*
1840 				 * Map, if present, has not changed
1841 				 */
1842 				(fs->map == NULL ||
1843 				fs->map_generation == fs->map->timestamp) &&
1844 				/*
1845 				 * Only one shadow object
1846 				 */
1847 				(fs->object->shadow_count == 1) &&
1848 				/*
1849 				 * No COW refs, except us
1850 				 */
1851 				(fs->object->ref_count == 1) &&
1852 				/*
1853 				 * No one else can look this object up
1854 				 */
1855 				(fs->object->handle == NULL) &&
1856 				/*
1857 				 * No other ways to look the object up
1858 				 */
1859 				((fs->object->type == OBJT_DEFAULT) ||
1860 				 (fs->object->type == OBJT_SWAP)) &&
1861 				/*
1862 				 * We don't chase down the shadow chain
1863 				 */
1864 				(fs->object == fs->first_object->backing_object) &&
1865 
1866 				/*
1867 				 * grab the lock if we need to
1868 				 */
1869 				(fs->lookup_still_valid ||
1870 				 fs->map == NULL ||
1871 				 lockmgr(&fs->map->lock, LK_EXCLUSIVE|LK_NOWAIT) == 0)
1872 			    ) {
1873 				/*
1874 				 * (first_m) and (m) are both busied.  We have
1875 				 * move (m) into (first_m)'s object/pindex
1876 				 * in an atomic fashion, then free (first_m).
1877 				 *
1878 				 * first_object is held so second remove
1879 				 * followed by the rename should wind
1880 				 * up being atomic.  vm_page_free() might
1881 				 * block so we don't do it until after the
1882 				 * rename.
1883 				 */
1884 				fs->lookup_still_valid = 1;
1885 				vm_page_protect(fs->first_m, VM_PROT_NONE);
1886 				vm_page_remove(fs->first_m);
1887 				vm_page_rename(fs->m, fs->first_object,
1888 					       first_pindex);
1889 				vm_page_free(fs->first_m);
1890 				fs->first_m = fs->m;
1891 				fs->m = NULL;
1892 				mycpu->gd_cnt.v_cow_optim++;
1893 			} else {
1894 				/*
1895 				 * Oh, well, lets copy it.
1896 				 *
1897 				 * Why are we unmapping the original page
1898 				 * here?  Well, in short, not all accessors
1899 				 * of user memory go through the pmap.  The
1900 				 * procfs code doesn't have access user memory
1901 				 * via a local pmap, so vm_fault_page*()
1902 				 * can't call pmap_enter().  And the umtx*()
1903 				 * code may modify the COW'd page via a DMAP
1904 				 * or kernel mapping and not via the pmap,
1905 				 * leaving the original page still mapped
1906 				 * read-only into the pmap.
1907 				 *
1908 				 * So we have to remove the page from at
1909 				 * least the current pmap if it is in it.
1910 				 * Just remove it from all pmaps.
1911 				 */
1912 				KKASSERT(fs->first_shared == 0);
1913 				vm_page_copy(fs->m, fs->first_m);
1914 				vm_page_protect(fs->m, VM_PROT_NONE);
1915 				vm_page_event(fs->m, VMEVENT_COW);
1916 			}
1917 
1918 			/*
1919 			 * We no longer need the old page or object.
1920 			 */
1921 			if (fs->m)
1922 				release_page(fs);
1923 
1924 			/*
1925 			 * We intend to revert to first_object, undo the
1926 			 * chain lock through to that.
1927 			 */
1928 #if 0
1929 			if (fs->first_object->backing_object != fs->object)
1930 				vm_object_hold(fs->first_object->backing_object);
1931 #endif
1932 			vm_object_chain_release_all(
1933 					fs->first_object->backing_object,
1934 					fs->object);
1935 #if 0
1936 			if (fs->first_object->backing_object != fs->object)
1937 				vm_object_drop(fs->first_object->backing_object);
1938 #endif
1939 
1940 			/*
1941 			 * fs->object != fs->first_object due to above
1942 			 * conditional
1943 			 */
1944 			vm_object_pip_wakeup(fs->object);
1945 			vm_object_drop(fs->object);
1946 
1947 			/*
1948 			 * Only use the new page below...
1949 			 */
1950 			mycpu->gd_cnt.v_cow_faults++;
1951 			fs->m = fs->first_m;
1952 			fs->object = fs->first_object;
1953 			pindex = first_pindex;
1954 		} else {
1955 			/*
1956 			 * If it wasn't a write fault avoid having to copy
1957 			 * the page by mapping it read-only.
1958 			 */
1959 			fs->prot &= ~VM_PROT_WRITE;
1960 		}
1961 	}
1962 
1963 	/*
1964 	 * Relock the map if necessary, then check the generation count.
1965 	 * relock_map() will update fs->timestamp to account for the
1966 	 * relocking if necessary.
1967 	 *
1968 	 * If the count has changed after relocking then all sorts of
1969 	 * crap may have happened and we have to retry.
1970 	 *
1971 	 * NOTE: The relock_map() can fail due to a deadlock against
1972 	 *	 the vm_page we are holding BUSY.
1973 	 */
1974 	if (fs->lookup_still_valid == FALSE && fs->map) {
1975 		if (relock_map(fs) ||
1976 		    fs->map->timestamp != fs->map_generation) {
1977 			release_page(fs);
1978 			vm_object_pip_wakeup(fs->first_object);
1979 			vm_object_chain_release_all(fs->first_object,
1980 						    fs->object);
1981 			if (fs->object != fs->first_object)
1982 				vm_object_drop(fs->object);
1983 			unlock_and_deallocate(fs);
1984 			return (KERN_TRY_AGAIN);
1985 		}
1986 	}
1987 
1988 	/*
1989 	 * If the fault is a write, we know that this page is being
1990 	 * written NOW so dirty it explicitly to save on pmap_is_modified()
1991 	 * calls later.
1992 	 *
1993 	 * If this is a NOSYNC mmap we do not want to set PG_NOSYNC
1994 	 * if the page is already dirty to prevent data written with
1995 	 * the expectation of being synced from not being synced.
1996 	 * Likewise if this entry does not request NOSYNC then make
1997 	 * sure the page isn't marked NOSYNC.  Applications sharing
1998 	 * data should use the same flags to avoid ping ponging.
1999 	 *
2000 	 * Also tell the backing pager, if any, that it should remove
2001 	 * any swap backing since the page is now dirty.
2002 	 */
2003 	vm_page_activate(fs->m);
2004 	if (fs->prot & VM_PROT_WRITE) {
2005 		vm_object_set_writeable_dirty(fs->m->object);
2006 		vm_set_nosync(fs->m, fs->entry);
2007 		if (fs->fault_flags & VM_FAULT_DIRTY) {
2008 			vm_page_dirty(fs->m);
2009 			swap_pager_unswapped(fs->m);
2010 		}
2011 	}
2012 
2013 	vm_object_pip_wakeup(fs->first_object);
2014 	vm_object_chain_release_all(fs->first_object, fs->object);
2015 	if (fs->object != fs->first_object)
2016 		vm_object_drop(fs->object);
2017 
2018 	/*
2019 	 * Page had better still be busy.  We are still locked up and
2020 	 * fs->object will have another PIP reference if it is not equal
2021 	 * to fs->first_object.
2022 	 */
2023 	KASSERT(fs->m->flags & PG_BUSY,
2024 		("vm_fault: page %p not busy!", fs->m));
2025 
2026 	/*
2027 	 * Sanity check: page must be completely valid or it is not fit to
2028 	 * map into user space.  vm_pager_get_pages() ensures this.
2029 	 */
2030 	if (fs->m->valid != VM_PAGE_BITS_ALL) {
2031 		vm_page_zero_invalid(fs->m, TRUE);
2032 		kprintf("Warning: page %p partially invalid on fault\n", fs->m);
2033 	}
2034 
2035 	return (KERN_SUCCESS);
2036 }
2037 
2038 /*
2039  * Hold each of the physical pages that are mapped by the specified range of
2040  * virtual addresses, ["addr", "addr" + "len"), if those mappings are valid
2041  * and allow the specified types of access, "prot".  If all of the implied
2042  * pages are successfully held, then the number of held pages is returned
2043  * together with pointers to those pages in the array "ma".  However, if any
2044  * of the pages cannot be held, -1 is returned.
2045  */
2046 int
2047 vm_fault_quick_hold_pages(vm_map_t map, vm_offset_t addr, vm_size_t len,
2048     vm_prot_t prot, vm_page_t *ma, int max_count)
2049 {
2050 	vm_offset_t start, end;
2051 	int i, npages, error;
2052 
2053 	start = trunc_page(addr);
2054 	end = round_page(addr + len);
2055 
2056 	npages = howmany(end - start, PAGE_SIZE);
2057 
2058 	if (npages > max_count)
2059 		return -1;
2060 
2061 	for (i = 0; i < npages; i++) {
2062 		// XXX error handling
2063 		ma[i] = vm_fault_page_quick(start + (i * PAGE_SIZE),
2064 			prot,
2065 			&error);
2066 	}
2067 
2068 	return npages;
2069 }
2070 
2071 /*
2072  * Wire down a range of virtual addresses in a map.  The entry in question
2073  * should be marked in-transition and the map must be locked.  We must
2074  * release the map temporarily while faulting-in the page to avoid a
2075  * deadlock.  Note that the entry may be clipped while we are blocked but
2076  * will never be freed.
2077  *
2078  * No requirements.
2079  */
2080 int
2081 vm_fault_wire(vm_map_t map, vm_map_entry_t entry,
2082 	      boolean_t user_wire, int kmflags)
2083 {
2084 	boolean_t fictitious;
2085 	vm_offset_t start;
2086 	vm_offset_t end;
2087 	vm_offset_t va;
2088 	vm_paddr_t pa;
2089 	vm_page_t m;
2090 	pmap_t pmap;
2091 	int rv;
2092 	int wire_prot;
2093 	int fault_flags;
2094 
2095 	lwkt_gettoken(&map->token);
2096 
2097 	if (user_wire) {
2098 		wire_prot = VM_PROT_READ;
2099 		fault_flags = VM_FAULT_USER_WIRE;
2100 	} else {
2101 		wire_prot = VM_PROT_READ | VM_PROT_WRITE;
2102 		fault_flags = VM_FAULT_CHANGE_WIRING;
2103 	}
2104 	if (kmflags & KM_NOTLBSYNC)
2105 		wire_prot |= VM_PROT_NOSYNC;
2106 
2107 	pmap = vm_map_pmap(map);
2108 	start = entry->start;
2109 	end = entry->end;
2110 	switch(entry->maptype) {
2111 	case VM_MAPTYPE_NORMAL:
2112 	case VM_MAPTYPE_VPAGETABLE:
2113 		fictitious = entry->object.vm_object &&
2114 			    ((entry->object.vm_object->type == OBJT_DEVICE) ||
2115 			     (entry->object.vm_object->type == OBJT_MGTDEVICE));
2116 		break;
2117 	case VM_MAPTYPE_UKSMAP:
2118 		fictitious = TRUE;
2119 		break;
2120 	default:
2121 		fictitious = FALSE;
2122 		break;
2123 	}
2124 
2125 	if (entry->eflags & MAP_ENTRY_KSTACK)
2126 		start += PAGE_SIZE;
2127 	map->timestamp++;
2128 	vm_map_unlock(map);
2129 
2130 	/*
2131 	 * We simulate a fault to get the page and enter it in the physical
2132 	 * map.
2133 	 */
2134 	for (va = start; va < end; va += PAGE_SIZE) {
2135 		rv = vm_fault(map, va, wire_prot, fault_flags);
2136 		if (rv) {
2137 			while (va > start) {
2138 				va -= PAGE_SIZE;
2139 				if ((pa = pmap_extract(pmap, va)) == 0)
2140 					continue;
2141 				pmap_change_wiring(pmap, va, FALSE, entry);
2142 				if (!fictitious) {
2143 					m = PHYS_TO_VM_PAGE(pa);
2144 					vm_page_busy_wait(m, FALSE, "vmwrpg");
2145 					vm_page_unwire(m, 1);
2146 					vm_page_wakeup(m);
2147 				}
2148 			}
2149 			goto done;
2150 		}
2151 	}
2152 	rv = KERN_SUCCESS;
2153 done:
2154 	vm_map_lock(map);
2155 	lwkt_reltoken(&map->token);
2156 	return (rv);
2157 }
2158 
2159 /*
2160  * Unwire a range of virtual addresses in a map.  The map should be
2161  * locked.
2162  */
2163 void
2164 vm_fault_unwire(vm_map_t map, vm_map_entry_t entry)
2165 {
2166 	boolean_t fictitious;
2167 	vm_offset_t start;
2168 	vm_offset_t end;
2169 	vm_offset_t va;
2170 	vm_paddr_t pa;
2171 	vm_page_t m;
2172 	pmap_t pmap;
2173 
2174 	lwkt_gettoken(&map->token);
2175 
2176 	pmap = vm_map_pmap(map);
2177 	start = entry->start;
2178 	end = entry->end;
2179 	fictitious = entry->object.vm_object &&
2180 			((entry->object.vm_object->type == OBJT_DEVICE) ||
2181 			 (entry->object.vm_object->type == OBJT_MGTDEVICE));
2182 	if (entry->eflags & MAP_ENTRY_KSTACK)
2183 		start += PAGE_SIZE;
2184 
2185 	/*
2186 	 * Since the pages are wired down, we must be able to get their
2187 	 * mappings from the physical map system.
2188 	 */
2189 	for (va = start; va < end; va += PAGE_SIZE) {
2190 		pa = pmap_extract(pmap, va);
2191 		if (pa != 0) {
2192 			pmap_change_wiring(pmap, va, FALSE, entry);
2193 			if (!fictitious) {
2194 				m = PHYS_TO_VM_PAGE(pa);
2195 				vm_page_busy_wait(m, FALSE, "vmwupg");
2196 				vm_page_unwire(m, 1);
2197 				vm_page_wakeup(m);
2198 			}
2199 		}
2200 	}
2201 	lwkt_reltoken(&map->token);
2202 }
2203 
2204 /*
2205  * Copy all of the pages from a wired-down map entry to another.
2206  *
2207  * The source and destination maps must be locked for write.
2208  * The source and destination maps token must be held
2209  * The source map entry must be wired down (or be a sharing map
2210  * entry corresponding to a main map entry that is wired down).
2211  *
2212  * No other requirements.
2213  *
2214  * XXX do segment optimization
2215  */
2216 void
2217 vm_fault_copy_entry(vm_map_t dst_map, vm_map_t src_map,
2218 		    vm_map_entry_t dst_entry, vm_map_entry_t src_entry)
2219 {
2220 	vm_object_t dst_object;
2221 	vm_object_t src_object;
2222 	vm_ooffset_t dst_offset;
2223 	vm_ooffset_t src_offset;
2224 	vm_prot_t prot;
2225 	vm_offset_t vaddr;
2226 	vm_page_t dst_m;
2227 	vm_page_t src_m;
2228 
2229 	src_object = src_entry->object.vm_object;
2230 	src_offset = src_entry->offset;
2231 
2232 	/*
2233 	 * Create the top-level object for the destination entry. (Doesn't
2234 	 * actually shadow anything - we copy the pages directly.)
2235 	 */
2236 	vm_map_entry_allocate_object(dst_entry);
2237 	dst_object = dst_entry->object.vm_object;
2238 
2239 	prot = dst_entry->max_protection;
2240 
2241 	/*
2242 	 * Loop through all of the pages in the entry's range, copying each
2243 	 * one from the source object (it should be there) to the destination
2244 	 * object.
2245 	 */
2246 	vm_object_hold(src_object);
2247 	vm_object_hold(dst_object);
2248 	for (vaddr = dst_entry->start, dst_offset = 0;
2249 	    vaddr < dst_entry->end;
2250 	    vaddr += PAGE_SIZE, dst_offset += PAGE_SIZE) {
2251 
2252 		/*
2253 		 * Allocate a page in the destination object
2254 		 */
2255 		do {
2256 			dst_m = vm_page_alloc(dst_object,
2257 					      OFF_TO_IDX(dst_offset),
2258 					      VM_ALLOC_NORMAL);
2259 			if (dst_m == NULL) {
2260 				vm_wait(0);
2261 			}
2262 		} while (dst_m == NULL);
2263 
2264 		/*
2265 		 * Find the page in the source object, and copy it in.
2266 		 * (Because the source is wired down, the page will be in
2267 		 * memory.)
2268 		 */
2269 		src_m = vm_page_lookup(src_object,
2270 				       OFF_TO_IDX(dst_offset + src_offset));
2271 		if (src_m == NULL)
2272 			panic("vm_fault_copy_wired: page missing");
2273 
2274 		vm_page_copy(src_m, dst_m);
2275 		vm_page_event(src_m, VMEVENT_COW);
2276 
2277 		/*
2278 		 * Enter it in the pmap...
2279 		 */
2280 		pmap_enter(dst_map->pmap, vaddr, dst_m, prot, FALSE, dst_entry);
2281 
2282 		/*
2283 		 * Mark it no longer busy, and put it on the active list.
2284 		 */
2285 		vm_page_activate(dst_m);
2286 		vm_page_wakeup(dst_m);
2287 	}
2288 	vm_object_drop(dst_object);
2289 	vm_object_drop(src_object);
2290 }
2291 
2292 #if 0
2293 
2294 /*
2295  * This routine checks around the requested page for other pages that
2296  * might be able to be faulted in.  This routine brackets the viable
2297  * pages for the pages to be paged in.
2298  *
2299  * Inputs:
2300  *	m, rbehind, rahead
2301  *
2302  * Outputs:
2303  *  marray (array of vm_page_t), reqpage (index of requested page)
2304  *
2305  * Return value:
2306  *  number of pages in marray
2307  */
2308 static int
2309 vm_fault_additional_pages(vm_page_t m, int rbehind, int rahead,
2310 			  vm_page_t *marray, int *reqpage)
2311 {
2312 	int i,j;
2313 	vm_object_t object;
2314 	vm_pindex_t pindex, startpindex, endpindex, tpindex;
2315 	vm_page_t rtm;
2316 	int cbehind, cahead;
2317 
2318 	object = m->object;
2319 	pindex = m->pindex;
2320 
2321 	/*
2322 	 * we don't fault-ahead for device pager
2323 	 */
2324 	if ((object->type == OBJT_DEVICE) ||
2325 	    (object->type == OBJT_MGTDEVICE)) {
2326 		*reqpage = 0;
2327 		marray[0] = m;
2328 		return 1;
2329 	}
2330 
2331 	/*
2332 	 * if the requested page is not available, then give up now
2333 	 */
2334 	if (!vm_pager_has_page(object, pindex, &cbehind, &cahead)) {
2335 		*reqpage = 0;	/* not used by caller, fix compiler warn */
2336 		return 0;
2337 	}
2338 
2339 	if ((cbehind == 0) && (cahead == 0)) {
2340 		*reqpage = 0;
2341 		marray[0] = m;
2342 		return 1;
2343 	}
2344 
2345 	if (rahead > cahead) {
2346 		rahead = cahead;
2347 	}
2348 
2349 	if (rbehind > cbehind) {
2350 		rbehind = cbehind;
2351 	}
2352 
2353 	/*
2354 	 * Do not do any readahead if we have insufficient free memory.
2355 	 *
2356 	 * XXX code was broken disabled before and has instability
2357 	 * with this conditonal fixed, so shortcut for now.
2358 	 */
2359 	if (burst_fault == 0 || vm_page_count_severe()) {
2360 		marray[0] = m;
2361 		*reqpage = 0;
2362 		return 1;
2363 	}
2364 
2365 	/*
2366 	 * scan backward for the read behind pages -- in memory
2367 	 *
2368 	 * Assume that if the page is not found an interrupt will not
2369 	 * create it.  Theoretically interrupts can only remove (busy)
2370 	 * pages, not create new associations.
2371 	 */
2372 	if (pindex > 0) {
2373 		if (rbehind > pindex) {
2374 			rbehind = pindex;
2375 			startpindex = 0;
2376 		} else {
2377 			startpindex = pindex - rbehind;
2378 		}
2379 
2380 		vm_object_hold(object);
2381 		for (tpindex = pindex; tpindex > startpindex; --tpindex) {
2382 			if (vm_page_lookup(object, tpindex - 1))
2383 				break;
2384 		}
2385 
2386 		i = 0;
2387 		while (tpindex < pindex) {
2388 			rtm = vm_page_alloc(object, tpindex, VM_ALLOC_SYSTEM |
2389 							     VM_ALLOC_NULL_OK);
2390 			if (rtm == NULL) {
2391 				for (j = 0; j < i; j++) {
2392 					vm_page_free(marray[j]);
2393 				}
2394 				vm_object_drop(object);
2395 				marray[0] = m;
2396 				*reqpage = 0;
2397 				return 1;
2398 			}
2399 			marray[i] = rtm;
2400 			++i;
2401 			++tpindex;
2402 		}
2403 		vm_object_drop(object);
2404 	} else {
2405 		i = 0;
2406 	}
2407 
2408 	/*
2409 	 * Assign requested page
2410 	 */
2411 	marray[i] = m;
2412 	*reqpage = i;
2413 	++i;
2414 
2415 	/*
2416 	 * Scan forwards for read-ahead pages
2417 	 */
2418 	tpindex = pindex + 1;
2419 	endpindex = tpindex + rahead;
2420 	if (endpindex > object->size)
2421 		endpindex = object->size;
2422 
2423 	vm_object_hold(object);
2424 	while (tpindex < endpindex) {
2425 		if (vm_page_lookup(object, tpindex))
2426 			break;
2427 		rtm = vm_page_alloc(object, tpindex, VM_ALLOC_SYSTEM |
2428 						     VM_ALLOC_NULL_OK);
2429 		if (rtm == NULL)
2430 			break;
2431 		marray[i] = rtm;
2432 		++i;
2433 		++tpindex;
2434 	}
2435 	vm_object_drop(object);
2436 
2437 	return (i);
2438 }
2439 
2440 #endif
2441 
2442 /*
2443  * vm_prefault() provides a quick way of clustering pagefaults into a
2444  * processes address space.  It is a "cousin" of pmap_object_init_pt,
2445  * except it runs at page fault time instead of mmap time.
2446  *
2447  * vm.fast_fault	Enables pre-faulting zero-fill pages
2448  *
2449  * vm.prefault_pages	Number of pages (1/2 negative, 1/2 positive) to
2450  *			prefault.  Scan stops in either direction when
2451  *			a page is found to already exist.
2452  *
2453  * This code used to be per-platform pmap_prefault().  It is now
2454  * machine-independent and enhanced to also pre-fault zero-fill pages
2455  * (see vm.fast_fault) as well as make them writable, which greatly
2456  * reduces the number of page faults programs incur.
2457  *
2458  * Application performance when pre-faulting zero-fill pages is heavily
2459  * dependent on the application.  Very tiny applications like /bin/echo
2460  * lose a little performance while applications of any appreciable size
2461  * gain performance.  Prefaulting multiple pages also reduces SMP
2462  * congestion and can improve SMP performance significantly.
2463  *
2464  * NOTE!  prot may allow writing but this only applies to the top level
2465  *	  object.  If we wind up mapping a page extracted from a backing
2466  *	  object we have to make sure it is read-only.
2467  *
2468  * NOTE!  The caller has already handled any COW operations on the
2469  *	  vm_map_entry via the normal fault code.  Do NOT call this
2470  *	  shortcut unless the normal fault code has run on this entry.
2471  *
2472  * The related map must be locked.
2473  * No other requirements.
2474  */
2475 static int vm_prefault_pages = 8;
2476 SYSCTL_INT(_vm, OID_AUTO, prefault_pages, CTLFLAG_RW, &vm_prefault_pages, 0,
2477 	   "Maximum number of pages to pre-fault");
2478 static int vm_fast_fault = 1;
2479 SYSCTL_INT(_vm, OID_AUTO, fast_fault, CTLFLAG_RW, &vm_fast_fault, 0,
2480 	   "Burst fault zero-fill regions");
2481 
2482 /*
2483  * Set PG_NOSYNC if the map entry indicates so, but only if the page
2484  * is not already dirty by other means.  This will prevent passive
2485  * filesystem syncing as well as 'sync' from writing out the page.
2486  */
2487 static void
2488 vm_set_nosync(vm_page_t m, vm_map_entry_t entry)
2489 {
2490 	if (entry->eflags & MAP_ENTRY_NOSYNC) {
2491 		if (m->dirty == 0)
2492 			vm_page_flag_set(m, PG_NOSYNC);
2493 	} else {
2494 		vm_page_flag_clear(m, PG_NOSYNC);
2495 	}
2496 }
2497 
2498 static void
2499 vm_prefault(pmap_t pmap, vm_offset_t addra, vm_map_entry_t entry, int prot,
2500 	    int fault_flags)
2501 {
2502 	struct lwp *lp;
2503 	vm_page_t m;
2504 	vm_offset_t addr;
2505 	vm_pindex_t index;
2506 	vm_pindex_t pindex;
2507 	vm_object_t object;
2508 	int pprot;
2509 	int i;
2510 	int noneg;
2511 	int nopos;
2512 	int maxpages;
2513 
2514 	/*
2515 	 * Get stable max count value, disabled if set to 0
2516 	 */
2517 	maxpages = vm_prefault_pages;
2518 	cpu_ccfence();
2519 	if (maxpages <= 0)
2520 		return;
2521 
2522 	/*
2523 	 * We do not currently prefault mappings that use virtual page
2524 	 * tables.  We do not prefault foreign pmaps.
2525 	 */
2526 	if (entry->maptype != VM_MAPTYPE_NORMAL)
2527 		return;
2528 	lp = curthread->td_lwp;
2529 	if (lp == NULL || (pmap != vmspace_pmap(lp->lwp_vmspace)))
2530 		return;
2531 
2532 	/*
2533 	 * Limit pre-fault count to 1024 pages.
2534 	 */
2535 	if (maxpages > 1024)
2536 		maxpages = 1024;
2537 
2538 	object = entry->object.vm_object;
2539 	KKASSERT(object != NULL);
2540 	KKASSERT(object == entry->object.vm_object);
2541 	vm_object_hold(object);
2542 	vm_object_chain_acquire(object, 0);
2543 
2544 	noneg = 0;
2545 	nopos = 0;
2546 	for (i = 0; i < maxpages; ++i) {
2547 		vm_object_t lobject;
2548 		vm_object_t nobject;
2549 		int allocated = 0;
2550 		int error;
2551 
2552 		/*
2553 		 * This can eat a lot of time on a heavily contended
2554 		 * machine so yield on the tick if needed.
2555 		 */
2556 		if ((i & 7) == 7)
2557 			lwkt_yield();
2558 
2559 		/*
2560 		 * Calculate the page to pre-fault, stopping the scan in
2561 		 * each direction separately if the limit is reached.
2562 		 */
2563 		if (i & 1) {
2564 			if (noneg)
2565 				continue;
2566 			addr = addra - ((i + 1) >> 1) * PAGE_SIZE;
2567 		} else {
2568 			if (nopos)
2569 				continue;
2570 			addr = addra + ((i + 2) >> 1) * PAGE_SIZE;
2571 		}
2572 		if (addr < entry->start) {
2573 			noneg = 1;
2574 			if (noneg && nopos)
2575 				break;
2576 			continue;
2577 		}
2578 		if (addr >= entry->end) {
2579 			nopos = 1;
2580 			if (noneg && nopos)
2581 				break;
2582 			continue;
2583 		}
2584 
2585 		/*
2586 		 * Skip pages already mapped, and stop scanning in that
2587 		 * direction.  When the scan terminates in both directions
2588 		 * we are done.
2589 		 */
2590 		if (pmap_prefault_ok(pmap, addr) == 0) {
2591 			if (i & 1)
2592 				noneg = 1;
2593 			else
2594 				nopos = 1;
2595 			if (noneg && nopos)
2596 				break;
2597 			continue;
2598 		}
2599 
2600 		/*
2601 		 * Follow the VM object chain to obtain the page to be mapped
2602 		 * into the pmap.
2603 		 *
2604 		 * If we reach the terminal object without finding a page
2605 		 * and we determine it would be advantageous, then allocate
2606 		 * a zero-fill page for the base object.  The base object
2607 		 * is guaranteed to be OBJT_DEFAULT for this case.
2608 		 *
2609 		 * In order to not have to check the pager via *haspage*()
2610 		 * we stop if any non-default object is encountered.  e.g.
2611 		 * a vnode or swap object would stop the loop.
2612 		 */
2613 		index = ((addr - entry->start) + entry->offset) >> PAGE_SHIFT;
2614 		lobject = object;
2615 		pindex = index;
2616 		pprot = prot;
2617 
2618 		KKASSERT(lobject == entry->object.vm_object);
2619 		/*vm_object_hold(lobject); implied */
2620 
2621 		while ((m = vm_page_lookup_busy_try(lobject, pindex,
2622 						    TRUE, &error)) == NULL) {
2623 			if (lobject->type != OBJT_DEFAULT)
2624 				break;
2625 			if (lobject->backing_object == NULL) {
2626 				if (vm_fast_fault == 0)
2627 					break;
2628 				if ((prot & VM_PROT_WRITE) == 0 ||
2629 				    vm_page_count_min(0)) {
2630 					break;
2631 				}
2632 
2633 				/*
2634 				 * NOTE: Allocated from base object
2635 				 */
2636 				m = vm_page_alloc(object, index,
2637 						  VM_ALLOC_NORMAL |
2638 						  VM_ALLOC_ZERO |
2639 						  VM_ALLOC_USE_GD |
2640 						  VM_ALLOC_NULL_OK);
2641 				if (m == NULL)
2642 					break;
2643 				allocated = 1;
2644 				pprot = prot;
2645 				/* lobject = object .. not needed */
2646 				break;
2647 			}
2648 			if (lobject->backing_object_offset & PAGE_MASK)
2649 				break;
2650 			nobject = lobject->backing_object;
2651 			vm_object_hold(nobject);
2652 			KKASSERT(nobject == lobject->backing_object);
2653 			pindex += lobject->backing_object_offset >> PAGE_SHIFT;
2654 			if (lobject != object) {
2655 				vm_object_lock_swap();
2656 				vm_object_drop(lobject);
2657 			}
2658 			lobject = nobject;
2659 			pprot &= ~VM_PROT_WRITE;
2660 			vm_object_chain_acquire(lobject, 0);
2661 		}
2662 
2663 		/*
2664 		 * NOTE: A non-NULL (m) will be associated with lobject if
2665 		 *	 it was found there, otherwise it is probably a
2666 		 *	 zero-fill page associated with the base object.
2667 		 *
2668 		 * Give-up if no page is available.
2669 		 */
2670 		if (m == NULL) {
2671 			if (lobject != object) {
2672 #if 0
2673 				if (object->backing_object != lobject)
2674 					vm_object_hold(object->backing_object);
2675 #endif
2676 				vm_object_chain_release_all(
2677 					object->backing_object, lobject);
2678 #if 0
2679 				if (object->backing_object != lobject)
2680 					vm_object_drop(object->backing_object);
2681 #endif
2682 				vm_object_drop(lobject);
2683 			}
2684 			break;
2685 		}
2686 
2687 		/*
2688 		 * The object must be marked dirty if we are mapping a
2689 		 * writable page.  m->object is either lobject or object,
2690 		 * both of which are still held.  Do this before we
2691 		 * potentially drop the object.
2692 		 */
2693 		if (pprot & VM_PROT_WRITE)
2694 			vm_object_set_writeable_dirty(m->object);
2695 
2696 		/*
2697 		 * Do not conditionalize on PG_RAM.  If pages are present in
2698 		 * the VM system we assume optimal caching.  If caching is
2699 		 * not optimal the I/O gravy train will be restarted when we
2700 		 * hit an unavailable page.  We do not want to try to restart
2701 		 * the gravy train now because we really don't know how much
2702 		 * of the object has been cached.  The cost for restarting
2703 		 * the gravy train should be low (since accesses will likely
2704 		 * be I/O bound anyway).
2705 		 */
2706 		if (lobject != object) {
2707 #if 0
2708 			if (object->backing_object != lobject)
2709 				vm_object_hold(object->backing_object);
2710 #endif
2711 			vm_object_chain_release_all(object->backing_object,
2712 						    lobject);
2713 #if 0
2714 			if (object->backing_object != lobject)
2715 				vm_object_drop(object->backing_object);
2716 #endif
2717 			vm_object_drop(lobject);
2718 		}
2719 
2720 		/*
2721 		 * Enter the page into the pmap if appropriate.  If we had
2722 		 * allocated the page we have to place it on a queue.  If not
2723 		 * we just have to make sure it isn't on the cache queue
2724 		 * (pages on the cache queue are not allowed to be mapped).
2725 		 */
2726 		if (allocated) {
2727 			/*
2728 			 * Page must be zerod.
2729 			 */
2730 			vm_page_zero_fill(m);
2731 			mycpu->gd_cnt.v_zfod++;
2732 			m->valid = VM_PAGE_BITS_ALL;
2733 
2734 			/*
2735 			 * Handle dirty page case
2736 			 */
2737 			if (pprot & VM_PROT_WRITE)
2738 				vm_set_nosync(m, entry);
2739 			pmap_enter(pmap, addr, m, pprot, 0, entry);
2740 			mycpu->gd_cnt.v_vm_faults++;
2741 			if (curthread->td_lwp)
2742 				++curthread->td_lwp->lwp_ru.ru_minflt;
2743 			vm_page_deactivate(m);
2744 			if (pprot & VM_PROT_WRITE) {
2745 				/*vm_object_set_writeable_dirty(m->object);*/
2746 				vm_set_nosync(m, entry);
2747 				if (fault_flags & VM_FAULT_DIRTY) {
2748 					vm_page_dirty(m);
2749 					/*XXX*/
2750 					swap_pager_unswapped(m);
2751 				}
2752 			}
2753 			vm_page_wakeup(m);
2754 		} else if (error) {
2755 			/* couldn't busy page, no wakeup */
2756 		} else if (
2757 		    ((m->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
2758 		    (m->flags & PG_FICTITIOUS) == 0) {
2759 			/*
2760 			 * A fully valid page not undergoing soft I/O can
2761 			 * be immediately entered into the pmap.
2762 			 */
2763 			if ((m->queue - m->pc) == PQ_CACHE)
2764 				vm_page_deactivate(m);
2765 			if (pprot & VM_PROT_WRITE) {
2766 				/*vm_object_set_writeable_dirty(m->object);*/
2767 				vm_set_nosync(m, entry);
2768 				if (fault_flags & VM_FAULT_DIRTY) {
2769 					vm_page_dirty(m);
2770 					/*XXX*/
2771 					swap_pager_unswapped(m);
2772 				}
2773 			}
2774 			if (pprot & VM_PROT_WRITE)
2775 				vm_set_nosync(m, entry);
2776 			pmap_enter(pmap, addr, m, pprot, 0, entry);
2777 			mycpu->gd_cnt.v_vm_faults++;
2778 			if (curthread->td_lwp)
2779 				++curthread->td_lwp->lwp_ru.ru_minflt;
2780 			vm_page_wakeup(m);
2781 		} else {
2782 			vm_page_wakeup(m);
2783 		}
2784 	}
2785 	vm_object_chain_release(object);
2786 	vm_object_drop(object);
2787 }
2788 
2789 /*
2790  * Object can be held shared
2791  */
2792 static void
2793 vm_prefault_quick(pmap_t pmap, vm_offset_t addra,
2794 		  vm_map_entry_t entry, int prot, int fault_flags)
2795 {
2796 	struct lwp *lp;
2797 	vm_page_t m;
2798 	vm_offset_t addr;
2799 	vm_pindex_t pindex;
2800 	vm_object_t object;
2801 	int i;
2802 	int noneg;
2803 	int nopos;
2804 	int maxpages;
2805 
2806 	/*
2807 	 * Get stable max count value, disabled if set to 0
2808 	 */
2809 	maxpages = vm_prefault_pages;
2810 	cpu_ccfence();
2811 	if (maxpages <= 0)
2812 		return;
2813 
2814 	/*
2815 	 * We do not currently prefault mappings that use virtual page
2816 	 * tables.  We do not prefault foreign pmaps.
2817 	 */
2818 	if (entry->maptype != VM_MAPTYPE_NORMAL)
2819 		return;
2820 	lp = curthread->td_lwp;
2821 	if (lp == NULL || (pmap != vmspace_pmap(lp->lwp_vmspace)))
2822 		return;
2823 	object = entry->object.vm_object;
2824 	if (object->backing_object != NULL)
2825 		return;
2826 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
2827 
2828 	/*
2829 	 * Limit pre-fault count to 1024 pages.
2830 	 */
2831 	if (maxpages > 1024)
2832 		maxpages = 1024;
2833 
2834 	noneg = 0;
2835 	nopos = 0;
2836 	for (i = 0; i < maxpages; ++i) {
2837 		int error;
2838 
2839 		/*
2840 		 * Calculate the page to pre-fault, stopping the scan in
2841 		 * each direction separately if the limit is reached.
2842 		 */
2843 		if (i & 1) {
2844 			if (noneg)
2845 				continue;
2846 			addr = addra - ((i + 1) >> 1) * PAGE_SIZE;
2847 		} else {
2848 			if (nopos)
2849 				continue;
2850 			addr = addra + ((i + 2) >> 1) * PAGE_SIZE;
2851 		}
2852 		if (addr < entry->start) {
2853 			noneg = 1;
2854 			if (noneg && nopos)
2855 				break;
2856 			continue;
2857 		}
2858 		if (addr >= entry->end) {
2859 			nopos = 1;
2860 			if (noneg && nopos)
2861 				break;
2862 			continue;
2863 		}
2864 
2865 		/*
2866 		 * Follow the VM object chain to obtain the page to be mapped
2867 		 * into the pmap.  This version of the prefault code only
2868 		 * works with terminal objects.
2869 		 *
2870 		 * The page must already exist.  If we encounter a problem
2871 		 * we stop here.
2872 		 *
2873 		 * WARNING!  We cannot call swap_pager_unswapped() or insert
2874 		 *	     a new vm_page with a shared token.
2875 		 */
2876 		pindex = ((addr - entry->start) + entry->offset) >> PAGE_SHIFT;
2877 
2878 		m = vm_page_lookup_busy_try(object, pindex, TRUE, &error);
2879 		if (m == NULL || error)
2880 			break;
2881 
2882 		/*
2883 		 * Skip pages already mapped, and stop scanning in that
2884 		 * direction.  When the scan terminates in both directions
2885 		 * we are done.
2886 		 */
2887 		if (pmap_prefault_ok(pmap, addr) == 0) {
2888 			vm_page_wakeup(m);
2889 			if (i & 1)
2890 				noneg = 1;
2891 			else
2892 				nopos = 1;
2893 			if (noneg && nopos)
2894 				break;
2895 			continue;
2896 		}
2897 
2898 		/*
2899 		 * Stop if the page cannot be trivially entered into the
2900 		 * pmap.
2901 		 */
2902 		if (((m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) ||
2903 		    (m->flags & PG_FICTITIOUS) ||
2904 		    ((m->flags & PG_SWAPPED) &&
2905 		     (prot & VM_PROT_WRITE) &&
2906 		     (fault_flags & VM_FAULT_DIRTY))) {
2907 			vm_page_wakeup(m);
2908 			break;
2909 		}
2910 
2911 		/*
2912 		 * Enter the page into the pmap.  The object might be held
2913 		 * shared so we can't do any (serious) modifying operation
2914 		 * on it.
2915 		 */
2916 		if ((m->queue - m->pc) == PQ_CACHE)
2917 			vm_page_deactivate(m);
2918 		if (prot & VM_PROT_WRITE) {
2919 			vm_object_set_writeable_dirty(m->object);
2920 			vm_set_nosync(m, entry);
2921 			if (fault_flags & VM_FAULT_DIRTY) {
2922 				vm_page_dirty(m);
2923 				/* can't happeen due to conditional above */
2924 				/* swap_pager_unswapped(m); */
2925 			}
2926 		}
2927 		pmap_enter(pmap, addr, m, prot, 0, entry);
2928 		mycpu->gd_cnt.v_vm_faults++;
2929 		if (curthread->td_lwp)
2930 			++curthread->td_lwp->lwp_ru.ru_minflt;
2931 		vm_page_wakeup(m);
2932 	}
2933 }
2934