xref: /dragonfly/sys/vm/vm_fault.c (revision c9c5aa9e)
1 /*
2  * Copyright (c) 2003-2020 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/swap_pager.h>
127 #include <vm/vm_extern.h>
128 
129 #include <vm/vm_page2.h>
130 
131 #define VM_FAULT_MAX_QUICK	16
132 
133 struct faultstate {
134 	vm_page_t mary[VM_FAULT_MAX_QUICK];
135 	vm_map_backing_t ba;
136 	vm_prot_t prot;
137 	vm_page_t first_m;
138 	vm_map_backing_t first_ba;
139 	vm_prot_t first_prot;
140 	vm_map_t map;
141 	vm_map_entry_t entry;
142 	int lookup_still_valid;	/* 0=inv 1=valid/rel -1=valid/atomic */
143 	int hardfault;
144 	int fault_flags;
145 	int shared;
146 	int msoftonly;
147 	int first_shared;
148 	int wflags;
149 	int first_ba_held;	/* 0=unlocked 1=locked/rel -1=lock/atomic */
150 	struct vnode *vp;
151 };
152 
153 __read_mostly static int debug_fault = 0;
154 SYSCTL_INT(_vm, OID_AUTO, debug_fault, CTLFLAG_RW, &debug_fault, 0, "");
155 __read_mostly static int debug_cluster = 0;
156 SYSCTL_INT(_vm, OID_AUTO, debug_cluster, CTLFLAG_RW, &debug_cluster, 0, "");
157 #if 0
158 static int virtual_copy_enable = 1;
159 SYSCTL_INT(_vm, OID_AUTO, virtual_copy_enable, CTLFLAG_RW,
160 		&virtual_copy_enable, 0, "");
161 #endif
162 __read_mostly int vm_shared_fault = 1;
163 TUNABLE_INT("vm.shared_fault", &vm_shared_fault);
164 SYSCTL_INT(_vm, OID_AUTO, shared_fault, CTLFLAG_RW,
165 		&vm_shared_fault, 0, "Allow shared token on vm_object");
166 __read_mostly static int vm_fault_bypass_count = 1;
167 TUNABLE_INT("vm.fault_bypass", &vm_fault_bypass_count);
168 SYSCTL_INT(_vm, OID_AUTO, fault_bypass, CTLFLAG_RW,
169 		&vm_fault_bypass_count, 0, "Allow fast vm_fault shortcut");
170 
171 /*
172  * Define here for debugging ioctls.  Note that these are globals, so
173  * they were cause a ton of cache line bouncing.  Only use for debugging
174  * purposes.
175  */
176 /*#define VM_FAULT_QUICK_DEBUG */
177 #ifdef VM_FAULT_QUICK_DEBUG
178 static long vm_fault_bypass_success_count = 0;
179 SYSCTL_LONG(_vm, OID_AUTO, fault_bypass_success_count, CTLFLAG_RW,
180 		&vm_fault_bypass_success_count, 0, "");
181 static long vm_fault_bypass_failure_count1 = 0;
182 SYSCTL_LONG(_vm, OID_AUTO, fault_bypass_failure_count1, CTLFLAG_RW,
183 		&vm_fault_bypass_failure_count1, 0, "");
184 static long vm_fault_bypass_failure_count2 = 0;
185 SYSCTL_LONG(_vm, OID_AUTO, fault_bypass_failure_count2, CTLFLAG_RW,
186 		&vm_fault_bypass_failure_count2, 0, "");
187 static long vm_fault_bypass_failure_count3 = 0;
188 SYSCTL_LONG(_vm, OID_AUTO, fault_bypass_failure_count3, CTLFLAG_RW,
189 		&vm_fault_bypass_failure_count3, 0, "");
190 static long vm_fault_bypass_failure_count4 = 0;
191 SYSCTL_LONG(_vm, OID_AUTO, fault_bypass_failure_count4, CTLFLAG_RW,
192 		&vm_fault_bypass_failure_count4, 0, "");
193 #endif
194 
195 static int vm_fault_bypass(struct faultstate *fs, vm_pindex_t first_pindex,
196 			vm_pindex_t first_count, int *mextcountp,
197 			vm_prot_t fault_type);
198 static int vm_fault_object(struct faultstate *, vm_pindex_t, vm_prot_t, int);
199 static int vm_fault_vpagetable(struct faultstate *, vm_pindex_t *,
200 			vpte_t, int, int);
201 #if 0
202 static int vm_fault_additional_pages (vm_page_t, int, int, vm_page_t *, int *);
203 #endif
204 static void vm_set_nosync(vm_page_t m, vm_map_entry_t entry);
205 static void vm_prefault(pmap_t pmap, vm_offset_t addra,
206 			vm_map_entry_t entry, int prot, int fault_flags);
207 static void vm_prefault_quick(pmap_t pmap, vm_offset_t addra,
208 			vm_map_entry_t entry, int prot, int fault_flags);
209 
210 static __inline void
211 release_page(struct faultstate *fs)
212 {
213 	vm_page_deactivate(fs->mary[0]);
214 	vm_page_wakeup(fs->mary[0]);
215 	fs->mary[0] = NULL;
216 }
217 
218 static __inline void
219 unlock_map(struct faultstate *fs)
220 {
221 	if (fs->ba != fs->first_ba)
222 		vm_object_drop(fs->ba->object);
223 	if (fs->first_ba && fs->first_ba_held == 1) {
224 		vm_object_drop(fs->first_ba->object);
225 		fs->first_ba_held = 0;
226 		fs->first_ba = NULL;
227 	}
228 	fs->ba = NULL;
229 
230 	/*
231 	 * NOTE: If lookup_still_valid == -1 the map is assumed to be locked
232 	 *	 and caller expects it to remain locked atomically.
233 	 */
234 	if (fs->lookup_still_valid == 1 && fs->map) {
235 		vm_map_lookup_done(fs->map, fs->entry, 0);
236 		fs->lookup_still_valid = 0;
237 		fs->entry = NULL;
238 	}
239 }
240 
241 /*
242  * Clean up after a successful call to vm_fault_object() so another call
243  * to vm_fault_object() can be made.
244  */
245 static void
246 cleanup_fault(struct faultstate *fs)
247 {
248 	/*
249 	 * We allocated a junk page for a COW operation that did
250 	 * not occur, the page must be freed.
251 	 */
252 	if (fs->ba != fs->first_ba) {
253 		KKASSERT(fs->first_shared == 0);
254 
255 		/*
256 		 * first_m could be completely valid and we got here
257 		 * because of a PG_RAM, don't mistakenly free it!
258 		 */
259 		if ((fs->first_m->valid & VM_PAGE_BITS_ALL) ==
260 		    VM_PAGE_BITS_ALL) {
261 			vm_page_wakeup(fs->first_m);
262 		} else {
263 			vm_page_free(fs->first_m);
264 		}
265 		vm_object_pip_wakeup(fs->ba->object);
266 		fs->first_m = NULL;
267 
268 		/*
269 		 * Reset fs->ba (used by vm_fault_vpagetahble() without
270 		 * calling unlock_map(), so we need a little duplication.
271 		 */
272 		vm_object_drop(fs->ba->object);
273 		fs->ba = fs->first_ba;
274 	}
275 }
276 
277 static void
278 unlock_things(struct faultstate *fs)
279 {
280 	cleanup_fault(fs);
281 	unlock_map(fs);
282 	if (fs->vp != NULL) {
283 		vput(fs->vp);
284 		fs->vp = NULL;
285 	}
286 }
287 
288 #if 0
289 /*
290  * Virtual copy tests.   Used by the fault code to determine if a
291  * page can be moved from an orphan vm_object into its shadow
292  * instead of copying its contents.
293  */
294 static __inline int
295 virtual_copy_test(struct faultstate *fs)
296 {
297 	/*
298 	 * Must be holding exclusive locks
299 	 */
300 	if (fs->first_shared || fs->shared || virtual_copy_enable == 0)
301 		return 0;
302 
303 	/*
304 	 * Map, if present, has not changed
305 	 */
306 	if (fs->map && fs->map_generation != fs->map->timestamp)
307 		return 0;
308 
309 	/*
310 	 * No refs, except us
311 	 */
312 	if (fs->ba->object->ref_count != 1)
313 		return 0;
314 
315 	/*
316 	 * No one else can look this object up
317 	 */
318 	if (fs->ba->object->handle != NULL)
319 		return 0;
320 
321 	/*
322 	 * No other ways to look the object up
323 	 */
324 	if (fs->ba->object->type != OBJT_DEFAULT &&
325 	    fs->ba->object->type != OBJT_SWAP)
326 		return 0;
327 
328 	/*
329 	 * We don't chase down the shadow chain
330 	 */
331 	if (fs->ba != fs->first_ba->backing_ba)
332 		return 0;
333 
334 	return 1;
335 }
336 
337 static __inline int
338 virtual_copy_ok(struct faultstate *fs)
339 {
340 	if (virtual_copy_test(fs)) {
341 		/*
342 		 * Grab the lock and re-test changeable items.
343 		 */
344 		if (fs->lookup_still_valid == 0 && fs->map) {
345 			if (lockmgr(&fs->map->lock, LK_EXCLUSIVE|LK_NOWAIT))
346 				return 0;
347 			fs->lookup_still_valid = 1;
348 			if (virtual_copy_test(fs)) {
349 				fs->map_generation = ++fs->map->timestamp;
350 				return 1;
351 			}
352 			fs->lookup_still_valid = 0;
353 			lockmgr(&fs->map->lock, LK_RELEASE);
354 		}
355 	}
356 	return 0;
357 }
358 #endif
359 
360 /*
361  * TRYPAGER
362  *
363  * Determine if the pager for the current object *might* contain the page.
364  *
365  * We only need to try the pager if this is not a default object (default
366  * objects are zero-fill and have no real pager), and if we are not taking
367  * a wiring fault or if the FS entry is wired.
368  */
369 #define TRYPAGER(fs)	\
370 		(fs->ba->object->type != OBJT_DEFAULT &&		\
371 		(((fs->fault_flags & VM_FAULT_WIRE_MASK) == 0) ||	\
372 		 (fs->wflags & FW_WIRED)))
373 
374 /*
375  * vm_fault:
376  *
377  * Handle a page fault occuring at the given address, requiring the given
378  * permissions, in the map specified.  If successful, the page is inserted
379  * into the associated physical map.
380  *
381  * NOTE: The given address should be truncated to the proper page address.
382  *
383  * KERN_SUCCESS is returned if the page fault is handled; otherwise,
384  * a standard error specifying why the fault is fatal is returned.
385  *
386  * The map in question must be referenced, and remains so.
387  * The caller may hold no locks.
388  * No other requirements.
389  */
390 int
391 vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type, int fault_flags)
392 {
393 	vm_pindex_t first_pindex;
394 	vm_pindex_t first_count;
395 	struct faultstate fs;
396 	struct lwp *lp;
397 	struct proc *p;
398 	thread_t td;
399 	struct vm_map_ilock ilock;
400 	int mextcount;
401 	int didilock;
402 	int growstack;
403 	int retry = 0;
404 	int inherit_prot;
405 	int result;
406 	int n;
407 
408 	inherit_prot = fault_type & VM_PROT_NOSYNC;
409 	fs.hardfault = 0;
410 	fs.fault_flags = fault_flags;
411 	fs.vp = NULL;
412 	fs.shared = vm_shared_fault;
413 	fs.first_shared = vm_shared_fault;
414 	growstack = 1;
415 
416 	/*
417 	 * vm_map interactions
418 	 */
419 	td = curthread;
420 	if ((lp = td->td_lwp) != NULL)
421 		lp->lwp_flags |= LWP_PAGING;
422 
423 RetryFault:
424 	/*
425 	 * vm_fault_bypass() can shortcut us.
426 	 */
427 	fs.msoftonly = 0;
428 	fs.first_ba_held = 0;
429 	mextcount = 1;
430 
431 	/*
432 	 * Find the vm_map_entry representing the backing store and resolve
433 	 * the top level object and page index.  This may have the side
434 	 * effect of executing a copy-on-write on the map entry,
435 	 * creating a shadow object, or splitting an anonymous entry for
436 	 * performance, but will not COW any actual VM pages.
437 	 *
438 	 * On success fs.map is left read-locked and various other fields
439 	 * are initialized but not otherwise referenced or locked.
440 	 *
441 	 * NOTE!  vm_map_lookup will try to upgrade the fault_type to
442 	 *	  VM_FAULT_WRITE if the map entry is a virtual page table
443 	 *	  and also writable, so we can set the 'A'accessed bit in
444 	 *	  the virtual page table entry.
445 	 */
446 	fs.map = map;
447 	result = vm_map_lookup(&fs.map, vaddr, fault_type,
448 			       &fs.entry, &fs.first_ba,
449 			       &first_pindex, &first_count,
450 			       &fs.first_prot, &fs.wflags);
451 
452 	/*
453 	 * If the lookup failed or the map protections are incompatible,
454 	 * the fault generally fails.
455 	 *
456 	 * The failure could be due to TDF_NOFAULT if vm_map_lookup()
457 	 * tried to do a COW fault.
458 	 *
459 	 * If the caller is trying to do a user wiring we have more work
460 	 * to do.
461 	 */
462 	if (result != KERN_SUCCESS) {
463 		if (result == KERN_FAILURE_NOFAULT) {
464 			result = KERN_FAILURE;
465 			goto done;
466 		}
467 		if (result != KERN_PROTECTION_FAILURE ||
468 		    (fs.fault_flags & VM_FAULT_WIRE_MASK) != VM_FAULT_USER_WIRE)
469 		{
470 			if (result == KERN_INVALID_ADDRESS && growstack &&
471 			    map != &kernel_map && curproc != NULL) {
472 				result = vm_map_growstack(map, vaddr);
473 				if (result == KERN_SUCCESS) {
474 					growstack = 0;
475 					++retry;
476 					goto RetryFault;
477 				}
478 				result = KERN_FAILURE;
479 			}
480 			goto done;
481 		}
482 
483 		/*
484 		 * If we are user-wiring a r/w segment, and it is COW, then
485 		 * we need to do the COW operation.  Note that we don't
486 		 * currently COW RO sections now, because it is NOT desirable
487 		 * to COW .text.  We simply keep .text from ever being COW'ed
488 		 * and take the heat that one cannot debug wired .text sections.
489 		 *
490 		 * XXX Try to allow the above by specifying OVERRIDE_WRITE.
491 		 */
492 		result = vm_map_lookup(&fs.map, vaddr,
493 				       VM_PROT_READ|VM_PROT_WRITE|
494 				        VM_PROT_OVERRIDE_WRITE,
495 				       &fs.entry, &fs.first_ba,
496 				       &first_pindex, &first_count,
497 				       &fs.first_prot, &fs.wflags);
498 		if (result != KERN_SUCCESS) {
499 			/* could also be KERN_FAILURE_NOFAULT */
500 			result = KERN_FAILURE;
501 			goto done;
502 		}
503 
504 		/*
505 		 * If we don't COW now, on a user wire, the user will never
506 		 * be able to write to the mapping.  If we don't make this
507 		 * restriction, the bookkeeping would be nearly impossible.
508 		 *
509 		 * XXX We have a shared lock, this will have a MP race but
510 		 * I don't see how it can hurt anything.
511 		 */
512 		if ((fs.entry->protection & VM_PROT_WRITE) == 0) {
513 			atomic_clear_char(&fs.entry->max_protection,
514 					  VM_PROT_WRITE);
515 		}
516 	}
517 
518 	/*
519 	 * fs.map is read-locked
520 	 *
521 	 * Misc checks.  Save the map generation number to detect races.
522 	 */
523 	fs.lookup_still_valid = 1;
524 	fs.first_m = NULL;
525 	fs.ba = fs.first_ba;		/* so unlock_things() works */
526 	fs.prot = fs.first_prot;	/* default (used by uksmap) */
527 
528 	if (fs.entry->eflags & (MAP_ENTRY_NOFAULT | MAP_ENTRY_KSTACK)) {
529 		if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
530 			panic("vm_fault: fault on nofault entry, addr: %p",
531 			      (void *)vaddr);
532 		}
533 		if ((fs.entry->eflags & MAP_ENTRY_KSTACK) &&
534 		    vaddr >= fs.entry->ba.start &&
535 		    vaddr < fs.entry->ba.start + PAGE_SIZE) {
536 			panic("vm_fault: fault on stack guard, addr: %p",
537 			      (void *)vaddr);
538 		}
539 	}
540 
541 	/*
542 	 * A user-kernel shared map has no VM object and bypasses
543 	 * everything.  We execute the uksmap function with a temporary
544 	 * fictitious vm_page.  The address is directly mapped with no
545 	 * management.
546 	 */
547 	if (fs.entry->maptype == VM_MAPTYPE_UKSMAP) {
548 		struct vm_page fakem;
549 
550 		bzero(&fakem, sizeof(fakem));
551 		fakem.pindex = first_pindex;
552 		fakem.flags = PG_FICTITIOUS | PG_UNQUEUED;
553 		fakem.busy_count = PBUSY_LOCKED;
554 		fakem.valid = VM_PAGE_BITS_ALL;
555 		fakem.pat_mode = VM_MEMATTR_DEFAULT;
556 		if (fs.entry->ba.uksmap(&fs.entry->ba, UKSMAPOP_FAULT,
557 					fs.entry->aux.dev, &fakem)) {
558 			result = KERN_FAILURE;
559 			unlock_things(&fs);
560 			goto done2;
561 		}
562 		pmap_enter(fs.map->pmap, vaddr, &fakem, fs.prot | inherit_prot,
563 			   (fs.wflags & FW_WIRED), fs.entry);
564 		goto done_success;
565 	}
566 
567 	/*
568 	 * A system map entry may return a NULL object.  No object means
569 	 * no pager means an unrecoverable kernel fault.
570 	 */
571 	if (fs.first_ba == NULL) {
572 		panic("vm_fault: unrecoverable fault at %p in entry %p",
573 			(void *)vaddr, fs.entry);
574 	}
575 
576 	/*
577 	 * Fail here if not a trivial anonymous page fault and TDF_NOFAULT
578 	 * is set.
579 	 *
580 	 * Unfortunately a deadlock can occur if we are forced to page-in
581 	 * from swap, but diving all the way into the vm_pager_get_page()
582 	 * function to find out is too much.  Just check the object type.
583 	 *
584 	 * The deadlock is a CAM deadlock on a busy VM page when trying
585 	 * to finish an I/O if another process gets stuck in
586 	 * vop_helper_read_shortcut() due to a swap fault.
587 	 */
588 	if ((td->td_flags & TDF_NOFAULT) &&
589 	    (retry ||
590 	     fs.first_ba->object->type == OBJT_VNODE ||
591 	     fs.first_ba->object->type == OBJT_SWAP ||
592 	     fs.first_ba->backing_ba)) {
593 		result = KERN_FAILURE;
594 		unlock_things(&fs);
595 		goto done2;
596 	}
597 
598 	/*
599 	 * If the entry is wired we cannot change the page protection.
600 	 */
601 	if (fs.wflags & FW_WIRED)
602 		fault_type = fs.first_prot;
603 
604 	/*
605 	 * We generally want to avoid unnecessary exclusive modes on backing
606 	 * and terminal objects because this can seriously interfere with
607 	 * heavily fork()'d processes (particularly /bin/sh scripts).
608 	 *
609 	 * However, we also want to avoid unnecessary retries due to needed
610 	 * shared->exclusive promotion for common faults.  Exclusive mode is
611 	 * always needed if any page insertion, rename, or free occurs in an
612 	 * object (and also indirectly if any I/O is done).
613 	 *
614 	 * The main issue here is going to be fs.first_shared.  If the
615 	 * first_object has a backing object which isn't shadowed and the
616 	 * process is single-threaded we might as well use an exclusive
617 	 * lock/chain right off the bat.
618 	 */
619 #if 0
620 	/* WORK IN PROGRESS, CODE REMOVED */
621 	if (fs.first_shared && fs.first_object->backing_object &&
622 	    LIST_EMPTY(&fs.first_object->shadow_head) &&
623 	    td->td_proc && td->td_proc->p_nthreads == 1) {
624 		fs.first_shared = 0;
625 	}
626 #endif
627 
628 	/*
629 	 * VM_FAULT_UNSWAP - swap_pager_unswapped() needs an exclusive object
630 	 * VM_FAULT_DIRTY  - may require swap_pager_unswapped() later, but
631 	 *		     we can try shared first.
632 	 */
633 	if (fault_flags & VM_FAULT_UNSWAP)
634 		fs.first_shared = 0;
635 
636 	/*
637 	 * Try to shortcut the entire mess and run the fault lockless.
638 	 * This will burst in multiple pages via fs->mary[].
639 	 */
640 	if (vm_fault_bypass_count &&
641 	    vm_fault_bypass(&fs, first_pindex, first_count,
642 			   &mextcount, fault_type) == KERN_SUCCESS) {
643 		didilock = 0;
644 		fault_flags &= ~VM_FAULT_BURST;
645 		goto success;
646 	}
647 
648 	/*
649 	 * Exclusive heuristic (alloc page vs page exists)
650 	 */
651 	if (fs.first_ba->flags & VM_MAP_BACK_EXCL_HEUR)
652 		fs.first_shared = 0;
653 
654 	/*
655 	 * Obtain a top-level object lock, shared or exclusive depending
656 	 * on fs.first_shared.  If a shared lock winds up being insufficient
657 	 * we will retry with an exclusive lock.
658 	 *
659 	 * The vnode pager lock is always shared.
660 	 */
661 	if (fs.first_shared)
662 		vm_object_hold_shared(fs.first_ba->object);
663 	else
664 		vm_object_hold(fs.first_ba->object);
665 	if (fs.vp == NULL)
666 		fs.vp = vnode_pager_lock(fs.first_ba);
667 	fs.first_ba_held = 1;
668 
669 	/*
670 	 * The page we want is at (first_object, first_pindex), but if the
671 	 * vm_map_entry is VM_MAPTYPE_VPAGETABLE we have to traverse the
672 	 * page table to figure out the actual pindex.
673 	 *
674 	 * NOTE!  DEVELOPMENT IN PROGRESS, THIS IS AN INITIAL IMPLEMENTATION
675 	 * ONLY
676 	 */
677 	didilock = 0;
678 	if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
679 		vm_map_interlock(fs.map, &ilock, vaddr, vaddr + PAGE_SIZE);
680 		didilock = 1;
681 		result = vm_fault_vpagetable(&fs, &first_pindex,
682 					     fs.entry->aux.master_pde,
683 					     fault_type, 1);
684 		if (result == KERN_TRY_AGAIN) {
685 			vm_map_deinterlock(fs.map, &ilock);
686 			++retry;
687 			goto RetryFault;
688 		}
689 		if (result != KERN_SUCCESS) {
690 			vm_map_deinterlock(fs.map, &ilock);
691 			goto done;
692 		}
693 	}
694 
695 	/*
696 	 * Now we have the actual (object, pindex), fault in the page.  If
697 	 * vm_fault_object() fails it will unlock and deallocate the FS
698 	 * data.   If it succeeds everything remains locked and fs->ba->object
699 	 * will have an additional PIP count if fs->ba != fs->first_ba.
700 	 *
701 	 * vm_fault_object will set fs->prot for the pmap operation.  It is
702 	 * allowed to set VM_PROT_WRITE if fault_type == VM_PROT_READ if the
703 	 * page can be safely written.  However, it will force a read-only
704 	 * mapping for a read fault if the memory is managed by a virtual
705 	 * page table.
706 	 *
707 	 * If the fault code uses the shared object lock shortcut
708 	 * we must not try to burst (we can't allocate VM pages).
709 	 */
710 	result = vm_fault_object(&fs, first_pindex, fault_type, 1);
711 
712 	if (debug_fault > 0) {
713 		--debug_fault;
714 		kprintf("VM_FAULT result %d addr=%jx type=%02x flags=%02x "
715 			"fs.m=%p fs.prot=%02x fs.wflags=%02x fs.entry=%p\n",
716 			result, (intmax_t)vaddr, fault_type, fault_flags,
717 			fs.mary[0], fs.prot, fs.wflags, fs.entry);
718 	}
719 
720 	if (result == KERN_TRY_AGAIN) {
721 		if (didilock)
722 			vm_map_deinterlock(fs.map, &ilock);
723 		++retry;
724 		goto RetryFault;
725 	}
726 	if (result != KERN_SUCCESS) {
727 		if (didilock)
728 			vm_map_deinterlock(fs.map, &ilock);
729 		goto done;
730 	}
731 
732 success:
733 	/*
734 	 * On success vm_fault_object() does not unlock or deallocate, and fs.m
735 	 * will contain a busied page.  It does drop fs->ba if appropriate.
736 	 *
737 	 * Enter the page into the pmap and do pmap-related adjustments.
738 	 *
739 	 * WARNING! Soft-busied fs.m's can only be manipulated in limited
740 	 *	    ways.
741 	 */
742 	KKASSERT(fs.lookup_still_valid != 0);
743 	vm_page_flag_set(fs.mary[0], PG_REFERENCED);
744 
745 	for (n = 0; n < mextcount; ++n) {
746 		pmap_enter(fs.map->pmap, vaddr + (n << PAGE_SHIFT),
747 			   fs.mary[n], fs.prot | inherit_prot,
748 			   fs.wflags & FW_WIRED, fs.entry);
749 	}
750 
751 	if (didilock)
752 		vm_map_deinterlock(fs.map, &ilock);
753 
754 	/*
755 	 * If the page is not wired down, then put it where the pageout daemon
756 	 * can find it.
757 	 *
758 	 * NOTE: We cannot safely wire, unwire, or adjust queues for a
759 	 *	 soft-busied page.
760 	 */
761 	for (n = 0; n < mextcount; ++n) {
762 		if (fs.msoftonly) {
763 			KKASSERT(fs.mary[n]->busy_count & PBUSY_MASK);
764 			KKASSERT((fs.fault_flags & VM_FAULT_WIRE_MASK) == 0);
765 			vm_page_sbusy_drop(fs.mary[n]);
766 		} else {
767 			if (fs.fault_flags & VM_FAULT_WIRE_MASK) {
768 				if (fs.wflags & FW_WIRED)
769 					vm_page_wire(fs.mary[n]);
770 				else
771 					vm_page_unwire(fs.mary[n], 1);
772 			} else {
773 				vm_page_activate(fs.mary[n]);
774 			}
775 			KKASSERT(fs.mary[n]->busy_count & PBUSY_LOCKED);
776 			vm_page_wakeup(fs.mary[n]);
777 		}
778 	}
779 
780 	/*
781 	 * Burst in a few more pages if possible.  The fs.map should still
782 	 * be locked.  To avoid interlocking against a vnode->getblk
783 	 * operation we had to be sure to unbusy our primary vm_page above
784 	 * first.
785 	 *
786 	 * A normal burst can continue down backing store, only execute
787 	 * if we are holding an exclusive lock, otherwise the exclusive
788 	 * locks the burst code gets might cause excessive SMP collisions.
789 	 *
790 	 * A quick burst can be utilized when there is no backing object
791 	 * (i.e. a shared file mmap).
792 	 */
793 	if ((fault_flags & VM_FAULT_BURST) &&
794 	    (fs.fault_flags & VM_FAULT_WIRE_MASK) == 0 &&
795 	    (fs.wflags & FW_WIRED) == 0) {
796 		if (fs.first_shared == 0 && fs.shared == 0) {
797 			vm_prefault(fs.map->pmap, vaddr,
798 				    fs.entry, fs.prot, fault_flags);
799 		} else {
800 			vm_prefault_quick(fs.map->pmap, vaddr,
801 					  fs.entry, fs.prot, fault_flags);
802 		}
803 	}
804 
805 done_success:
806 	/*
807 	 * Unlock everything, and return
808 	 */
809 	unlock_things(&fs);
810 
811 	mycpu->gd_cnt.v_vm_faults++;
812 	if (td->td_lwp) {
813 		if (fs.hardfault) {
814 			++td->td_lwp->lwp_ru.ru_majflt;
815 		} else {
816 			++td->td_lwp->lwp_ru.ru_minflt;
817 		}
818 	}
819 
820 	/*vm_object_deallocate(fs.first_ba->object);*/
821 	/*fs.m = NULL; */
822 
823 	result = KERN_SUCCESS;
824 done:
825 	if (fs.first_ba && fs.first_ba->object && fs.first_ba_held == 1) {
826 		vm_object_drop(fs.first_ba->object);
827 		fs.first_ba_held = 0;
828 	}
829 done2:
830 	if (lp)
831 		lp->lwp_flags &= ~LWP_PAGING;
832 
833 #if !defined(NO_SWAPPING)
834 	/*
835 	 * Check the process RSS limit and force deactivation and
836 	 * (asynchronous) paging if necessary.  This is a complex operation,
837 	 * only do it for direct user-mode faults, for now.
838 	 *
839 	 * To reduce overhead implement approximately a ~16MB hysteresis.
840 	 */
841 	p = td->td_proc;
842 	if ((fault_flags & VM_FAULT_USERMODE) && lp &&
843 	    p->p_limit && map->pmap && vm_pageout_memuse_mode >= 1 &&
844 	    map != &kernel_map) {
845 		vm_pindex_t limit;
846 		vm_pindex_t size;
847 
848 		limit = OFF_TO_IDX(qmin(p->p_rlimit[RLIMIT_RSS].rlim_cur,
849 					p->p_rlimit[RLIMIT_RSS].rlim_max));
850 		size = pmap_resident_tlnw_count(map->pmap);
851 		if (limit >= 0 && size > 4096 && size - 4096 >= limit) {
852 			vm_pageout_map_deactivate_pages(map, limit);
853 		}
854 	}
855 #endif
856 
857 	if (result != KERN_SUCCESS && debug_fault < 0) {
858 		kprintf("VM_FAULT %d:%d (%s) result %d "
859 			"addr=%jx type=%02x flags=%02x "
860 			"fs.m=%p fs.prot=%02x fs.wflags=%02x fs.entry=%p\n",
861 			(curthread->td_proc ? curthread->td_proc->p_pid : -1),
862 			(curthread->td_lwp ? curthread->td_lwp->lwp_tid : -1),
863 			curthread->td_comm,
864 			result,
865 			(intmax_t)vaddr, fault_type, fault_flags,
866 			fs.mary[0], fs.prot, fs.wflags, fs.entry);
867 		while (debug_fault < 0 && (debug_fault & 1))
868 			tsleep(&debug_fault, 0, "DEBUG", hz);
869 	}
870 
871 	return (result);
872 }
873 
874 /*
875  * Attempt a lockless vm_fault() shortcut.  The stars have to align for this
876  * to work.  But if it does we can get our page only soft-busied and not
877  * have to touch the vm_object or vnode locks at all.
878  */
879 static
880 int
881 vm_fault_bypass(struct faultstate *fs, vm_pindex_t first_pindex,
882 	       vm_pindex_t first_count, int *mextcountp,
883 	       vm_prot_t fault_type)
884 {
885 	vm_page_t m;
886 	vm_object_t obj;	/* NOT LOCKED */
887 	int n;
888 	int nlim;
889 
890 	/*
891 	 * Don't waste time if the object is only being used by one vm_map.
892 	 */
893 	obj = fs->first_ba->object;
894 #if 0
895 	if (obj->flags & OBJ_ONEMAPPING)
896 		return KERN_FAILURE;
897 #endif
898 
899 	/*
900 	 * This will try to wire/unwire a page, which can't be done with
901 	 * a soft-busied page.
902 	 */
903 	if (fs->fault_flags & VM_FAULT_WIRE_MASK)
904 		return KERN_FAILURE;
905 
906 	/*
907 	 * Ick, can't handle this
908 	 */
909 	if (fs->entry->maptype == VM_MAPTYPE_VPAGETABLE) {
910 #ifdef VM_FAULT_QUICK_DEBUG
911 		++vm_fault_bypass_failure_count1;
912 #endif
913 		return KERN_FAILURE;
914 	}
915 
916 	/*
917 	 * Ok, try to get the vm_page quickly via the hash table.  The
918 	 * page will be soft-busied on success (NOT hard-busied).
919 	 */
920 	m = vm_page_hash_get(obj, first_pindex);
921 	if (m == NULL) {
922 #ifdef VM_FAULT_QUICK_DEBUG
923 		++vm_fault_bypass_failure_count2;
924 #endif
925 		return KERN_FAILURE;
926 	}
927 	if ((obj->flags & OBJ_DEAD) ||
928 	    m->valid != VM_PAGE_BITS_ALL ||
929 	    m->queue - m->pc != PQ_ACTIVE ||
930 	    (m->flags & PG_SWAPPED)) {
931 		vm_page_sbusy_drop(m);
932 #ifdef VM_FAULT_QUICK_DEBUG
933 		++vm_fault_bypass_failure_count3;
934 #endif
935 		return KERN_FAILURE;
936 	}
937 
938 	/*
939 	 * The page is already fully valid, ACTIVE, and is not PG_SWAPPED.
940 	 *
941 	 * Don't map the page writable when emulating the dirty bit, a
942 	 * fault must be taken for proper emulation (vkernel).
943 	 */
944 	if (curthread->td_lwp && curthread->td_lwp->lwp_vmspace &&
945 	    pmap_emulate_ad_bits(&curthread->td_lwp->lwp_vmspace->vm_pmap)) {
946 		if ((fault_type & VM_PROT_WRITE) == 0)
947 			fs->prot &= ~VM_PROT_WRITE;
948 	}
949 
950 	/*
951 	 * If this is a write fault the object and the page must already
952 	 * be writable.  Since we don't hold an object lock and only a
953 	 * soft-busy on the page, we cannot manipulate the object or
954 	 * the page state (other than the page queue).
955 	 */
956 	if (fs->prot & VM_PROT_WRITE) {
957 		if ((obj->flags & (OBJ_WRITEABLE | OBJ_MIGHTBEDIRTY)) !=
958 		    (OBJ_WRITEABLE | OBJ_MIGHTBEDIRTY) ||
959 		    m->dirty != VM_PAGE_BITS_ALL) {
960 			vm_page_sbusy_drop(m);
961 #ifdef VM_FAULT_QUICK_DEBUG
962 			++vm_fault_bypass_failure_count4;
963 #endif
964 			return KERN_FAILURE;
965 		}
966 		vm_set_nosync(m, fs->entry);
967 	}
968 
969 	/*
970 	 * Set page and potentially burst in more
971 	 *
972 	 * Even though we are only soft-busied we can still move pages
973 	 * around in the normal queue(s).  The soft-busy prevents the
974 	 * page from being removed from the object, etc (normal operation).
975 	 *
976 	 * However, in this fast path it is excessively important to avoid
977 	 * any hard locks, so we use a special passive version of activate.
978 	 */
979 	fs->msoftonly = 1;
980 	fs->mary[0] = m;
981 	vm_page_soft_activate(m);
982 
983 	if (vm_fault_bypass_count > 1) {
984 		nlim = vm_fault_bypass_count;
985 		if (nlim > VM_FAULT_MAX_QUICK)		/* array limit(+1) */
986 			nlim = VM_FAULT_MAX_QUICK;
987 		if (nlim > first_count)			/* user limit */
988 			nlim = first_count;
989 
990 		for (n = 1; n < nlim; ++n) {
991 			m = vm_page_hash_get(obj, first_pindex + n);
992 			if (m == NULL)
993 				break;
994 			if (m->valid != VM_PAGE_BITS_ALL ||
995 			    m->queue - m->pc != PQ_ACTIVE ||
996 			    (m->flags & PG_SWAPPED)) {
997 				vm_page_sbusy_drop(m);
998 				break;
999 			}
1000 			if (fs->prot & VM_PROT_WRITE) {
1001 				if ((obj->flags & (OBJ_WRITEABLE |
1002 						   OBJ_MIGHTBEDIRTY)) !=
1003 				    (OBJ_WRITEABLE | OBJ_MIGHTBEDIRTY) ||
1004 				    m->dirty != VM_PAGE_BITS_ALL) {
1005 					vm_page_sbusy_drop(m);
1006 					break;
1007 				}
1008 			}
1009 			vm_page_soft_activate(m);
1010 			fs->mary[n] = m;
1011 		}
1012 		*mextcountp = n;
1013 	}
1014 
1015 #ifdef VM_FAULT_QUICK_DEBUG
1016 	++vm_fault_bypass_success_count;
1017 #endif
1018 
1019 	return KERN_SUCCESS;
1020 }
1021 
1022 /*
1023  * Fault in the specified virtual address in the current process map,
1024  * returning a held VM page or NULL.  See vm_fault_page() for more
1025  * information.
1026  *
1027  * No requirements.
1028  */
1029 vm_page_t
1030 vm_fault_page_quick(vm_offset_t va, vm_prot_t fault_type,
1031 		    int *errorp, int *busyp)
1032 {
1033 	struct lwp *lp = curthread->td_lwp;
1034 	vm_page_t m;
1035 
1036 	m = vm_fault_page(&lp->lwp_vmspace->vm_map, va,
1037 			  fault_type, VM_FAULT_NORMAL,
1038 			  errorp, busyp);
1039 	return(m);
1040 }
1041 
1042 /*
1043  * Fault in the specified virtual address in the specified map, doing all
1044  * necessary manipulation of the object store and all necessary I/O.  Return
1045  * a held VM page or NULL, and set *errorp.  The related pmap is not
1046  * updated.
1047  *
1048  * If busyp is not NULL then *busyp will be set to TRUE if this routine
1049  * decides to return a busied page (aka VM_PROT_WRITE), or FALSE if it
1050  * does not (VM_PROT_WRITE not specified or busyp is NULL).  If busyp is
1051  * NULL the returned page is only held.
1052  *
1053  * If the caller has no intention of writing to the page's contents, busyp
1054  * can be passed as NULL along with VM_PROT_WRITE to force a COW operation
1055  * without busying the page.
1056  *
1057  * The returned page will also be marked PG_REFERENCED.
1058  *
1059  * If the page cannot be faulted writable and VM_PROT_WRITE was specified, an
1060  * error will be returned.
1061  *
1062  * No requirements.
1063  */
1064 vm_page_t
1065 vm_fault_page(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
1066 	      int fault_flags, int *errorp, int *busyp)
1067 {
1068 	vm_pindex_t first_pindex;
1069 	vm_pindex_t first_count;
1070 	struct faultstate fs;
1071 	int result;
1072 	int retry;
1073 	int growstack;
1074 	int didcow;
1075 	vm_prot_t orig_fault_type = fault_type;
1076 
1077 	retry = 0;
1078 	didcow = 0;
1079 	fs.hardfault = 0;
1080 	fs.fault_flags = fault_flags;
1081 	KKASSERT((fault_flags & VM_FAULT_WIRE_MASK) == 0);
1082 
1083 	/*
1084 	 * Dive the pmap (concurrency possible).  If we find the
1085 	 * appropriate page we can terminate early and quickly.
1086 	 *
1087 	 * This works great for normal programs but will always return
1088 	 * NULL for host lookups of vkernel maps in VMM mode.
1089 	 *
1090 	 * NOTE: pmap_fault_page_quick() might not busy the page.  If
1091 	 *	 VM_PROT_WRITE is set in fault_type and pmap_fault_page_quick()
1092 	 *	 returns non-NULL, it will safely dirty the returned vm_page_t
1093 	 *	 for us.  We cannot safely dirty it here (it might not be
1094 	 *	 busy).
1095 	 */
1096 	fs.mary[0] = pmap_fault_page_quick(map->pmap, vaddr, fault_type, busyp);
1097 	if (fs.mary[0]) {
1098 		*errorp = 0;
1099 		return(fs.mary[0]);
1100 	}
1101 
1102 	/*
1103 	 * Otherwise take a concurrency hit and do a formal page
1104 	 * fault.
1105 	 */
1106 	fs.vp = NULL;
1107 	fs.shared = vm_shared_fault;
1108 	fs.first_shared = vm_shared_fault;
1109 	fs.msoftonly = 0;
1110 	growstack = 1;
1111 
1112 	/*
1113 	 * VM_FAULT_UNSWAP - swap_pager_unswapped() needs an exclusive object
1114 	 * VM_FAULT_DIRTY  - may require swap_pager_unswapped() later, but
1115 	 *		     we can try shared first.
1116 	 */
1117 	if (fault_flags & VM_FAULT_UNSWAP) {
1118 		fs.first_shared = 0;
1119 	}
1120 
1121 RetryFault:
1122 	/*
1123 	 * Find the vm_map_entry representing the backing store and resolve
1124 	 * the top level object and page index.  This may have the side
1125 	 * effect of executing a copy-on-write on the map entry and/or
1126 	 * creating a shadow object, but will not COW any actual VM pages.
1127 	 *
1128 	 * On success fs.map is left read-locked and various other fields
1129 	 * are initialized but not otherwise referenced or locked.
1130 	 *
1131 	 * NOTE!  vm_map_lookup will upgrade the fault_type to VM_FAULT_WRITE
1132 	 *	  if the map entry is a virtual page table and also writable,
1133 	 *	  so we can set the 'A'accessed bit in the virtual page table
1134 	 *	  entry.
1135 	 */
1136 	fs.map = map;
1137 	fs.first_ba_held = 0;
1138 	result = vm_map_lookup(&fs.map, vaddr, fault_type,
1139 			       &fs.entry, &fs.first_ba,
1140 			       &first_pindex, &first_count,
1141 			       &fs.first_prot, &fs.wflags);
1142 
1143 	if (result != KERN_SUCCESS) {
1144 		if (result == KERN_FAILURE_NOFAULT) {
1145 			*errorp = KERN_FAILURE;
1146 			fs.mary[0] = NULL;
1147 			goto done;
1148 		}
1149 		if (result != KERN_PROTECTION_FAILURE ||
1150 		    (fs.fault_flags & VM_FAULT_WIRE_MASK) != VM_FAULT_USER_WIRE)
1151 		{
1152 			if (result == KERN_INVALID_ADDRESS && growstack &&
1153 			    map != &kernel_map && curproc != NULL) {
1154 				result = vm_map_growstack(map, vaddr);
1155 				if (result == KERN_SUCCESS) {
1156 					growstack = 0;
1157 					++retry;
1158 					goto RetryFault;
1159 				}
1160 				result = KERN_FAILURE;
1161 			}
1162 			fs.mary[0] = NULL;
1163 			*errorp = result;
1164 			goto done;
1165 		}
1166 
1167 		/*
1168 		 * If we are user-wiring a r/w segment, and it is COW, then
1169 		 * we need to do the COW operation.  Note that we don't
1170 		 * currently COW RO sections now, because it is NOT desirable
1171 		 * to COW .text.  We simply keep .text from ever being COW'ed
1172 		 * and take the heat that one cannot debug wired .text sections.
1173 		 */
1174 		result = vm_map_lookup(&fs.map, vaddr,
1175 				       VM_PROT_READ|VM_PROT_WRITE|
1176 				        VM_PROT_OVERRIDE_WRITE,
1177 				       &fs.entry, &fs.first_ba,
1178 				       &first_pindex, &first_count,
1179 				       &fs.first_prot, &fs.wflags);
1180 		if (result != KERN_SUCCESS) {
1181 			/* could also be KERN_FAILURE_NOFAULT */
1182 			*errorp = KERN_FAILURE;
1183 			fs.mary[0] = NULL;
1184 			goto done;
1185 		}
1186 
1187 		/*
1188 		 * If we don't COW now, on a user wire, the user will never
1189 		 * be able to write to the mapping.  If we don't make this
1190 		 * restriction, the bookkeeping would be nearly impossible.
1191 		 *
1192 		 * XXX We have a shared lock, this will have a MP race but
1193 		 * I don't see how it can hurt anything.
1194 		 */
1195 		if ((fs.entry->protection & VM_PROT_WRITE) == 0) {
1196 			atomic_clear_char(&fs.entry->max_protection,
1197 					  VM_PROT_WRITE);
1198 		}
1199 	}
1200 
1201 	/*
1202 	 * fs.map is read-locked
1203 	 *
1204 	 * Misc checks.  Save the map generation number to detect races.
1205 	 */
1206 	fs.lookup_still_valid = 1;
1207 	fs.first_m = NULL;
1208 	fs.ba = fs.first_ba;
1209 
1210 	if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
1211 		panic("vm_fault: fault on nofault entry, addr: %lx",
1212 		    (u_long)vaddr);
1213 	}
1214 
1215 	/*
1216 	 * A user-kernel shared map has no VM object and bypasses
1217 	 * everything.  We execute the uksmap function with a temporary
1218 	 * fictitious vm_page.  The address is directly mapped with no
1219 	 * management.
1220 	 */
1221 	if (fs.entry->maptype == VM_MAPTYPE_UKSMAP) {
1222 		struct vm_page fakem;
1223 
1224 		bzero(&fakem, sizeof(fakem));
1225 		fakem.pindex = first_pindex;
1226 		fakem.flags = PG_FICTITIOUS | PG_UNQUEUED;
1227 		fakem.busy_count = PBUSY_LOCKED;
1228 		fakem.valid = VM_PAGE_BITS_ALL;
1229 		fakem.pat_mode = VM_MEMATTR_DEFAULT;
1230 		if (fs.entry->ba.uksmap(&fs.entry->ba, UKSMAPOP_FAULT,
1231 					fs.entry->aux.dev, &fakem)) {
1232 			*errorp = KERN_FAILURE;
1233 			fs.mary[0] = NULL;
1234 			unlock_things(&fs);
1235 			goto done2;
1236 		}
1237 		fs.mary[0] = PHYS_TO_VM_PAGE(fakem.phys_addr);
1238 		vm_page_hold(fs.mary[0]);
1239 		if (busyp)
1240 			*busyp = 0;	/* don't need to busy R or W */
1241 		unlock_things(&fs);
1242 		*errorp = 0;
1243 		goto done;
1244 	}
1245 
1246 
1247 	/*
1248 	 * A system map entry may return a NULL object.  No object means
1249 	 * no pager means an unrecoverable kernel fault.
1250 	 */
1251 	if (fs.first_ba == NULL) {
1252 		panic("vm_fault: unrecoverable fault at %p in entry %p",
1253 			(void *)vaddr, fs.entry);
1254 	}
1255 
1256 	/*
1257 	 * Fail here if not a trivial anonymous page fault and TDF_NOFAULT
1258 	 * is set.
1259 	 *
1260 	 * Unfortunately a deadlock can occur if we are forced to page-in
1261 	 * from swap, but diving all the way into the vm_pager_get_page()
1262 	 * function to find out is too much.  Just check the object type.
1263 	 */
1264 	if ((curthread->td_flags & TDF_NOFAULT) &&
1265 	    (retry ||
1266 	     fs.first_ba->object->type == OBJT_VNODE ||
1267 	     fs.first_ba->object->type == OBJT_SWAP ||
1268 	     fs.first_ba->backing_ba)) {
1269 		*errorp = KERN_FAILURE;
1270 		unlock_things(&fs);
1271 		fs.mary[0] = NULL;
1272 		goto done2;
1273 	}
1274 
1275 	/*
1276 	 * If the entry is wired we cannot change the page protection.
1277 	 */
1278 	if (fs.wflags & FW_WIRED)
1279 		fault_type = fs.first_prot;
1280 
1281 	/*
1282 	 * Make a reference to this object to prevent its disposal while we
1283 	 * are messing with it.  Once we have the reference, the map is free
1284 	 * to be diddled.  Since objects reference their shadows (and copies),
1285 	 * they will stay around as well.
1286 	 *
1287 	 * The reference should also prevent an unexpected collapse of the
1288 	 * parent that might move pages from the current object into the
1289 	 * parent unexpectedly, resulting in corruption.
1290 	 *
1291 	 * Bump the paging-in-progress count to prevent size changes (e.g.
1292 	 * truncation operations) during I/O.  This must be done after
1293 	 * obtaining the vnode lock in order to avoid possible deadlocks.
1294 	 */
1295 	if (fs.first_ba->flags & VM_MAP_BACK_EXCL_HEUR)
1296 		fs.first_shared = 0;
1297 
1298 	if (fs.first_shared)
1299 		vm_object_hold_shared(fs.first_ba->object);
1300 	else
1301 		vm_object_hold(fs.first_ba->object);
1302 	fs.first_ba_held = 1;
1303 	if (fs.vp == NULL)
1304 		fs.vp = vnode_pager_lock(fs.first_ba);	/* shared */
1305 
1306 	/*
1307 	 * The page we want is at (first_object, first_pindex), but if the
1308 	 * vm_map_entry is VM_MAPTYPE_VPAGETABLE we have to traverse the
1309 	 * page table to figure out the actual pindex.
1310 	 *
1311 	 * NOTE!  DEVELOPMENT IN PROGRESS, THIS IS AN INITIAL IMPLEMENTATION
1312 	 * ONLY
1313 	 */
1314 	if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
1315 		result = vm_fault_vpagetable(&fs, &first_pindex,
1316 					     fs.entry->aux.master_pde,
1317 					     fault_type, 1);
1318 		first_count = 1;
1319 		if (result == KERN_TRY_AGAIN) {
1320 			++retry;
1321 			goto RetryFault;
1322 		}
1323 		if (result != KERN_SUCCESS) {
1324 			*errorp = result;
1325 			fs.mary[0] = NULL;
1326 			goto done;
1327 		}
1328 	}
1329 
1330 	/*
1331 	 * Now we have the actual (object, pindex), fault in the page.  If
1332 	 * vm_fault_object() fails it will unlock and deallocate the FS
1333 	 * data.   If it succeeds everything remains locked and fs->ba->object
1334 	 * will have an additinal PIP count if fs->ba != fs->first_ba.
1335 	 */
1336 	fs.mary[0] = NULL;
1337 	result = vm_fault_object(&fs, first_pindex, fault_type, 1);
1338 
1339 	if (result == KERN_TRY_AGAIN) {
1340 		KKASSERT(fs.first_ba_held == 0);
1341 		++retry;
1342 		didcow |= fs.wflags & FW_DIDCOW;
1343 		goto RetryFault;
1344 	}
1345 	if (result != KERN_SUCCESS) {
1346 		*errorp = result;
1347 		fs.mary[0] = NULL;
1348 		goto done;
1349 	}
1350 
1351 	if ((orig_fault_type & VM_PROT_WRITE) &&
1352 	    (fs.prot & VM_PROT_WRITE) == 0) {
1353 		*errorp = KERN_PROTECTION_FAILURE;
1354 		unlock_things(&fs);
1355 		fs.mary[0] = NULL;
1356 		goto done;
1357 	}
1358 
1359 	/*
1360 	 * Generally speaking we don't want to update the pmap because
1361 	 * this routine can be called many times for situations that do
1362 	 * not require updating the pmap, not to mention the page might
1363 	 * already be in the pmap.
1364 	 *
1365 	 * However, if our vm_map_lookup() results in a COW, we need to
1366 	 * at least remove the pte from the pmap to guarantee proper
1367 	 * visibility of modifications made to the process.  For example,
1368 	 * modifications made by vkernel uiocopy/related routines and
1369 	 * modifications made by ptrace().
1370 	 */
1371 	vm_page_flag_set(fs.mary[0], PG_REFERENCED);
1372 #if 0
1373 	pmap_enter(fs.map->pmap, vaddr, fs.mary[0], fs.prot,
1374 		   fs.wflags & FW_WIRED, NULL);
1375 	mycpu->gd_cnt.v_vm_faults++;
1376 	if (curthread->td_lwp)
1377 		++curthread->td_lwp->lwp_ru.ru_minflt;
1378 #endif
1379 	if ((fs.wflags | didcow) | FW_DIDCOW) {
1380 		pmap_remove(fs.map->pmap,
1381 			    vaddr & ~PAGE_MASK,
1382 			    (vaddr & ~PAGE_MASK) + PAGE_SIZE);
1383 	}
1384 
1385 	/*
1386 	 * On success vm_fault_object() does not unlock or deallocate, and
1387 	 * fs.mary[0] will contain a busied page.  So we must unlock here
1388 	 * after having messed with the pmap.
1389 	 */
1390 	unlock_things(&fs);
1391 
1392 	/*
1393 	 * Return a held page.  We are not doing any pmap manipulation so do
1394 	 * not set PG_MAPPED.  However, adjust the page flags according to
1395 	 * the fault type because the caller may not use a managed pmapping
1396 	 * (so we don't want to lose the fact that the page will be dirtied
1397 	 * if a write fault was specified).
1398 	 */
1399 	if (fault_type & VM_PROT_WRITE)
1400 		vm_page_dirty(fs.mary[0]);
1401 	vm_page_activate(fs.mary[0]);
1402 
1403 	if (curthread->td_lwp) {
1404 		if (fs.hardfault) {
1405 			curthread->td_lwp->lwp_ru.ru_majflt++;
1406 		} else {
1407 			curthread->td_lwp->lwp_ru.ru_minflt++;
1408 		}
1409 	}
1410 
1411 	/*
1412 	 * Unlock everything, and return the held or busied page.
1413 	 */
1414 	if (busyp) {
1415 		if (fault_type & VM_PROT_WRITE) {
1416 			vm_page_dirty(fs.mary[0]);
1417 			*busyp = 1;
1418 		} else {
1419 			*busyp = 0;
1420 			vm_page_hold(fs.mary[0]);
1421 			vm_page_wakeup(fs.mary[0]);
1422 		}
1423 	} else {
1424 		vm_page_hold(fs.mary[0]);
1425 		vm_page_wakeup(fs.mary[0]);
1426 	}
1427 	/*vm_object_deallocate(fs.first_ba->object);*/
1428 	*errorp = 0;
1429 
1430 done:
1431 	KKASSERT(fs.first_ba_held == 0);
1432 done2:
1433 	return(fs.mary[0]);
1434 }
1435 
1436 /*
1437  * Fault in the specified (object,offset), dirty the returned page as
1438  * needed.  If the requested fault_type cannot be done NULL and an
1439  * error is returned.
1440  *
1441  * A held (but not busied) page is returned.
1442  *
1443  * The passed in object must be held as specified by the shared
1444  * argument.
1445  */
1446 vm_page_t
1447 vm_fault_object_page(vm_object_t object, vm_ooffset_t offset,
1448 		     vm_prot_t fault_type, int fault_flags,
1449 		     int *sharedp, int *errorp)
1450 {
1451 	int result;
1452 	vm_pindex_t first_pindex;
1453 	vm_pindex_t first_count;
1454 	struct faultstate fs;
1455 	struct vm_map_entry entry;
1456 
1457 	/*
1458 	 * Since we aren't actually faulting the page into a
1459 	 * pmap we can just fake the entry.ba.
1460 	 */
1461 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1462 	bzero(&entry, sizeof(entry));
1463 	entry.maptype = VM_MAPTYPE_NORMAL;
1464 	entry.protection = entry.max_protection = fault_type;
1465 	entry.ba.backing_ba = NULL;
1466 	entry.ba.object = object;
1467 	entry.ba.offset = 0;
1468 
1469 	fs.hardfault = 0;
1470 	fs.fault_flags = fault_flags;
1471 	fs.map = NULL;
1472 	fs.shared = vm_shared_fault;
1473 	fs.first_shared = *sharedp;
1474 	fs.msoftonly = 0;
1475 	fs.vp = NULL;
1476 	fs.first_ba_held = -1;	/* object held across call, prevent drop */
1477 	KKASSERT((fault_flags & VM_FAULT_WIRE_MASK) == 0);
1478 
1479 	/*
1480 	 * VM_FAULT_UNSWAP - swap_pager_unswapped() needs an exclusive object
1481 	 * VM_FAULT_DIRTY  - may require swap_pager_unswapped() later, but
1482 	 *		     we can try shared first.
1483 	 */
1484 	if (fs.first_shared && (fault_flags & VM_FAULT_UNSWAP)) {
1485 		fs.first_shared = 0;
1486 		vm_object_upgrade(object);
1487 	}
1488 
1489 	/*
1490 	 * Retry loop as needed (typically for shared->exclusive transitions)
1491 	 */
1492 RetryFault:
1493 	*sharedp = fs.first_shared;
1494 	first_pindex = OFF_TO_IDX(offset);
1495 	first_count = 1;
1496 	fs.first_ba = &entry.ba;
1497 	fs.ba = fs.first_ba;
1498 	fs.entry = &entry;
1499 	fs.first_prot = fault_type;
1500 	fs.wflags = 0;
1501 
1502 	/*
1503 	 * Make a reference to this object to prevent its disposal while we
1504 	 * are messing with it.  Once we have the reference, the map is free
1505 	 * to be diddled.  Since objects reference their shadows (and copies),
1506 	 * they will stay around as well.
1507 	 *
1508 	 * The reference should also prevent an unexpected collapse of the
1509 	 * parent that might move pages from the current object into the
1510 	 * parent unexpectedly, resulting in corruption.
1511 	 *
1512 	 * Bump the paging-in-progress count to prevent size changes (e.g.
1513 	 * truncation operations) during I/O.  This must be done after
1514 	 * obtaining the vnode lock in order to avoid possible deadlocks.
1515 	 */
1516 	if (fs.vp == NULL)
1517 		fs.vp = vnode_pager_lock(fs.first_ba);
1518 
1519 	fs.lookup_still_valid = 1;
1520 	fs.first_m = NULL;
1521 
1522 #if 0
1523 	/* XXX future - ability to operate on VM object using vpagetable */
1524 	if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
1525 		result = vm_fault_vpagetable(&fs, &first_pindex,
1526 					     fs.entry->aux.master_pde,
1527 					     fault_type, 0);
1528 		if (result == KERN_TRY_AGAIN) {
1529 			if (fs.first_shared == 0 && *sharedp)
1530 				vm_object_upgrade(object);
1531 			goto RetryFault;
1532 		}
1533 		if (result != KERN_SUCCESS) {
1534 			*errorp = result;
1535 			return (NULL);
1536 		}
1537 	}
1538 #endif
1539 
1540 	/*
1541 	 * Now we have the actual (object, pindex), fault in the page.  If
1542 	 * vm_fault_object() fails it will unlock and deallocate the FS
1543 	 * data.   If it succeeds everything remains locked and fs->ba->object
1544 	 * will have an additinal PIP count if fs->ba != fs->first_ba.
1545 	 *
1546 	 * On KERN_TRY_AGAIN vm_fault_object() leaves fs.first_ba intact.
1547 	 * We may have to upgrade its lock to handle the requested fault.
1548 	 */
1549 	result = vm_fault_object(&fs, first_pindex, fault_type, 0);
1550 
1551 	if (result == KERN_TRY_AGAIN) {
1552 		if (fs.first_shared == 0 && *sharedp)
1553 			vm_object_upgrade(object);
1554 		goto RetryFault;
1555 	}
1556 	if (result != KERN_SUCCESS) {
1557 		*errorp = result;
1558 		return(NULL);
1559 	}
1560 
1561 	if ((fault_type & VM_PROT_WRITE) && (fs.prot & VM_PROT_WRITE) == 0) {
1562 		*errorp = KERN_PROTECTION_FAILURE;
1563 		unlock_things(&fs);
1564 		return(NULL);
1565 	}
1566 
1567 	/*
1568 	 * On success vm_fault_object() does not unlock or deallocate, so we
1569 	 * do it here.  Note that the returned fs.m will be busied.
1570 	 */
1571 	unlock_things(&fs);
1572 
1573 	/*
1574 	 * Return a held page.  We are not doing any pmap manipulation so do
1575 	 * not set PG_MAPPED.  However, adjust the page flags according to
1576 	 * the fault type because the caller may not use a managed pmapping
1577 	 * (so we don't want to lose the fact that the page will be dirtied
1578 	 * if a write fault was specified).
1579 	 */
1580 	vm_page_hold(fs.mary[0]);
1581 	vm_page_activate(fs.mary[0]);
1582 	if ((fault_type & VM_PROT_WRITE) || (fault_flags & VM_FAULT_DIRTY))
1583 		vm_page_dirty(fs.mary[0]);
1584 	if (fault_flags & VM_FAULT_UNSWAP)
1585 		swap_pager_unswapped(fs.mary[0]);
1586 
1587 	/*
1588 	 * Indicate that the page was accessed.
1589 	 */
1590 	vm_page_flag_set(fs.mary[0], PG_REFERENCED);
1591 
1592 	if (curthread->td_lwp) {
1593 		if (fs.hardfault) {
1594 			curthread->td_lwp->lwp_ru.ru_majflt++;
1595 		} else {
1596 			curthread->td_lwp->lwp_ru.ru_minflt++;
1597 		}
1598 	}
1599 
1600 	/*
1601 	 * Unlock everything, and return the held page.
1602 	 */
1603 	vm_page_wakeup(fs.mary[0]);
1604 	/*vm_object_deallocate(fs.first_ba->object);*/
1605 
1606 	*errorp = 0;
1607 	return(fs.mary[0]);
1608 }
1609 
1610 /*
1611  * Translate the virtual page number (first_pindex) that is relative
1612  * to the address space into a logical page number that is relative to the
1613  * backing object.  Use the virtual page table pointed to by (vpte).
1614  *
1615  * Possibly downgrade the protection based on the vpte bits.
1616  *
1617  * This implements an N-level page table.  Any level can terminate the
1618  * scan by setting VPTE_PS.   A linear mapping is accomplished by setting
1619  * VPTE_PS in the master page directory entry set via mcontrol(MADV_SETMAP).
1620  */
1621 static
1622 int
1623 vm_fault_vpagetable(struct faultstate *fs, vm_pindex_t *pindex,
1624 		    vpte_t vpte, int fault_type, int allow_nofault)
1625 {
1626 	struct lwbuf *lwb;
1627 	struct lwbuf lwb_cache;
1628 	int vshift = VPTE_FRAME_END - PAGE_SHIFT; /* index bits remaining */
1629 	int result;
1630 	vpte_t *ptep;
1631 
1632 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(fs->first_ba->object));
1633 	for (;;) {
1634 		/*
1635 		 * We cannot proceed if the vpte is not valid, not readable
1636 		 * for a read fault, not writable for a write fault, or
1637 		 * not executable for an instruction execution fault.
1638 		 */
1639 		if ((vpte & VPTE_V) == 0) {
1640 			unlock_things(fs);
1641 			return (KERN_FAILURE);
1642 		}
1643 		if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_RW) == 0) {
1644 			unlock_things(fs);
1645 			return (KERN_FAILURE);
1646 		}
1647 		if ((fault_type & VM_PROT_EXECUTE) && (vpte & VPTE_NX)) {
1648 			unlock_things(fs);
1649 			return (KERN_FAILURE);
1650 		}
1651 		if ((vpte & VPTE_PS) || vshift == 0)
1652 			break;
1653 
1654 		/*
1655 		 * Get the page table page.  Nominally we only read the page
1656 		 * table, but since we are actively setting VPTE_M and VPTE_A,
1657 		 * tell vm_fault_object() that we are writing it.
1658 		 *
1659 		 * There is currently no real need to optimize this.
1660 		 */
1661 		result = vm_fault_object(fs, (vpte & VPTE_FRAME) >> PAGE_SHIFT,
1662 					 VM_PROT_READ|VM_PROT_WRITE,
1663 					 allow_nofault);
1664 		if (result != KERN_SUCCESS)
1665 			return (result);
1666 
1667 		/*
1668 		 * Process the returned fs.mary[0] and look up the page table
1669 		 * entry in the page table page.
1670 		 */
1671 		vshift -= VPTE_PAGE_BITS;
1672 		lwb = lwbuf_alloc(fs->mary[0], &lwb_cache);
1673 		ptep = ((vpte_t *)lwbuf_kva(lwb) +
1674 		        ((*pindex >> vshift) & VPTE_PAGE_MASK));
1675 		vm_page_activate(fs->mary[0]);
1676 
1677 		/*
1678 		 * Page table write-back - entire operation including
1679 		 * validation of the pte must be atomic to avoid races
1680 		 * against the vkernel changing the pte.
1681 		 *
1682 		 * If the vpte is valid for the* requested operation, do
1683 		 * a write-back to the page table.
1684 		 *
1685 		 * XXX VPTE_M is not set properly for page directory pages.
1686 		 * It doesn't get set in the page directory if the page table
1687 		 * is modified during a read access.
1688 		 */
1689 		for (;;) {
1690 			vpte_t nvpte;
1691 
1692 			/*
1693 			 * Reload for the cmpset, but make sure the pte is
1694 			 * still valid.
1695 			 */
1696 			vpte = *ptep;
1697 			cpu_ccfence();
1698 			nvpte = vpte;
1699 
1700 			if ((vpte & VPTE_V) == 0)
1701 				break;
1702 
1703 			if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_RW))
1704 				nvpte |= VPTE_M | VPTE_A;
1705 			if (fault_type & (VM_PROT_READ | VM_PROT_EXECUTE))
1706 				nvpte |= VPTE_A;
1707 			if (vpte == nvpte)
1708 				break;
1709 			if (atomic_cmpset_long(ptep, vpte, nvpte)) {
1710 				vm_page_dirty(fs->mary[0]);
1711 				break;
1712 			}
1713 		}
1714 		lwbuf_free(lwb);
1715 		vm_page_flag_set(fs->mary[0], PG_REFERENCED);
1716 		vm_page_wakeup(fs->mary[0]);
1717 		fs->mary[0] = NULL;
1718 		cleanup_fault(fs);
1719 	}
1720 
1721 	/*
1722 	 * When the vkernel sets VPTE_RW it expects the real kernel to
1723 	 * reflect VPTE_M back when the page is modified via the mapping.
1724 	 * In order to accomplish this the real kernel must map the page
1725 	 * read-only for read faults and use write faults to reflect VPTE_M
1726 	 * back.
1727 	 *
1728 	 * Once VPTE_M has been set, the real kernel's pte allows writing.
1729 	 * If the vkernel clears VPTE_M the vkernel must be sure to
1730 	 * MADV_INVAL the real kernel's mappings to force the real kernel
1731 	 * to re-fault on the next write so oit can set VPTE_M again.
1732 	 */
1733 	if ((fault_type & VM_PROT_WRITE) == 0 &&
1734 	    (vpte & (VPTE_RW | VPTE_M)) != (VPTE_RW | VPTE_M)) {
1735 		fs->first_prot &= ~VM_PROT_WRITE;
1736 	}
1737 
1738 	/*
1739 	 * Disable EXECUTE perms if NX bit is set.
1740 	 */
1741 	if (vpte & VPTE_NX)
1742 		fs->first_prot &= ~VM_PROT_EXECUTE;
1743 
1744 	/*
1745 	 * Combine remaining address bits with the vpte.
1746 	 */
1747 	*pindex = ((vpte & VPTE_FRAME) >> PAGE_SHIFT) +
1748 		  (*pindex & ((1L << vshift) - 1));
1749 	return (KERN_SUCCESS);
1750 }
1751 
1752 
1753 /*
1754  * This is the core of the vm_fault code.
1755  *
1756  * Do all operations required to fault-in (fs.first_ba->object, pindex).
1757  * Run through the backing store as necessary and do required COW or virtual
1758  * copy operations.  The caller has already fully resolved the vm_map_entry
1759  * and, if appropriate, has created a copy-on-write layer.  All we need to
1760  * do is iterate the object chain.
1761  *
1762  * On failure (fs) is unlocked and deallocated and the caller may return or
1763  * retry depending on the failure code.  On success (fs) is NOT unlocked or
1764  * deallocated, fs.mary[0] will contained a resolved, busied page, and fs.ba's
1765  * object will have an additional PIP count if it is not equal to
1766  * fs.first_ba.
1767  *
1768  * If locks based on fs->first_shared or fs->shared are insufficient,
1769  * clear the appropriate field(s) and return RETRY.  COWs require that
1770  * first_shared be 0, while page allocations (or frees) require that
1771  * shared be 0.  Renames require that both be 0.
1772  *
1773  * NOTE! fs->[first_]shared might be set with VM_FAULT_DIRTY also set.
1774  *	 we will have to retry with it exclusive if the vm_page is
1775  *	 PG_SWAPPED.
1776  *
1777  * fs->first_ba->object must be held on call.
1778  */
1779 static
1780 int
1781 vm_fault_object(struct faultstate *fs, vm_pindex_t first_pindex,
1782 		vm_prot_t fault_type, int allow_nofault)
1783 {
1784 	vm_map_backing_t next_ba;
1785 	vm_pindex_t pindex;
1786 	int error;
1787 
1788 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(fs->first_ba->object));
1789 	fs->prot = fs->first_prot;
1790 	pindex = first_pindex;
1791 	KKASSERT(fs->ba == fs->first_ba);
1792 
1793 	vm_object_pip_add(fs->first_ba->object, 1);
1794 
1795 	/*
1796 	 * If a read fault occurs we try to upgrade the page protection
1797 	 * and make it also writable if possible.  There are three cases
1798 	 * where we cannot make the page mapping writable:
1799 	 *
1800 	 * (1) The mapping is read-only or the VM object is read-only,
1801 	 *     fs->prot above will simply not have VM_PROT_WRITE set.
1802 	 *
1803 	 * (2) If the mapping is a virtual page table fs->first_prot will
1804 	 *     have already been properly adjusted by vm_fault_vpagetable().
1805 	 *     to detect writes so we can set VPTE_M in the virtual page
1806 	 *     table.  Used by vkernels.
1807 	 *
1808 	 * (3) If the VM page is read-only or copy-on-write, upgrading would
1809 	 *     just result in an unnecessary COW fault.
1810 	 *
1811 	 * (4) If the pmap specifically requests A/M bit emulation, downgrade
1812 	 *     here.
1813 	 */
1814 #if 0
1815 	/* see vpagetable code */
1816 	if (fs->entry->maptype == VM_MAPTYPE_VPAGETABLE) {
1817 		if ((fault_type & VM_PROT_WRITE) == 0)
1818 			fs->prot &= ~VM_PROT_WRITE;
1819 	}
1820 #endif
1821 
1822 	if (curthread->td_lwp && curthread->td_lwp->lwp_vmspace &&
1823 	    pmap_emulate_ad_bits(&curthread->td_lwp->lwp_vmspace->vm_pmap)) {
1824 		if ((fault_type & VM_PROT_WRITE) == 0)
1825 			fs->prot &= ~VM_PROT_WRITE;
1826 	}
1827 
1828 	/* vm_object_hold(fs->ba->object); implied b/c ba == first_ba */
1829 
1830 	for (;;) {
1831 		/*
1832 		 * If the object is dead, we stop here
1833 		 */
1834 		if (fs->ba->object->flags & OBJ_DEAD) {
1835 			vm_object_pip_wakeup(fs->first_ba->object);
1836 			unlock_things(fs);
1837 			return (KERN_PROTECTION_FAILURE);
1838 		}
1839 
1840 		/*
1841 		 * See if the page is resident.  Wait/Retry if the page is
1842 		 * busy (lots of stuff may have changed so we can't continue
1843 		 * in that case).
1844 		 *
1845 		 * We can theoretically allow the soft-busy case on a read
1846 		 * fault if the page is marked valid, but since such
1847 		 * pages are typically already pmap'd, putting that
1848 		 * special case in might be more effort then it is
1849 		 * worth.  We cannot under any circumstances mess
1850 		 * around with a vm_page_t->busy page except, perhaps,
1851 		 * to pmap it.
1852 		 */
1853 		fs->mary[0] = vm_page_lookup_busy_try(fs->ba->object, pindex,
1854 						      TRUE, &error);
1855 		if (error) {
1856 			vm_object_pip_wakeup(fs->first_ba->object);
1857 			unlock_things(fs);
1858 			vm_page_sleep_busy(fs->mary[0], TRUE, "vmpfw");
1859 			mycpu->gd_cnt.v_intrans++;
1860 			fs->mary[0] = NULL;
1861 			return (KERN_TRY_AGAIN);
1862 		}
1863 		if (fs->mary[0]) {
1864 			/*
1865 			 * The page is busied for us.
1866 			 *
1867 			 * If reactivating a page from PQ_CACHE we may have
1868 			 * to rate-limit.
1869 			 */
1870 			int queue = fs->mary[0]->queue;
1871 			vm_page_unqueue_nowakeup(fs->mary[0]);
1872 
1873 			if ((queue - fs->mary[0]->pc) == PQ_CACHE &&
1874 			    vm_page_count_severe()) {
1875 				vm_page_activate(fs->mary[0]);
1876 				vm_page_wakeup(fs->mary[0]);
1877 				fs->mary[0] = NULL;
1878 				vm_object_pip_wakeup(fs->first_ba->object);
1879 				unlock_things(fs);
1880 				if (allow_nofault == 0 ||
1881 				    (curthread->td_flags & TDF_NOFAULT) == 0) {
1882 					thread_t td;
1883 
1884 					vm_wait_pfault();
1885 					td = curthread;
1886 					if (td->td_proc && (td->td_proc->p_flags & P_LOWMEMKILL))
1887 						return (KERN_PROTECTION_FAILURE);
1888 				}
1889 				return (KERN_TRY_AGAIN);
1890 			}
1891 
1892 			/*
1893 			 * If it still isn't completely valid (readable),
1894 			 * or if a read-ahead-mark is set on the VM page,
1895 			 * jump to readrest, else we found the page and
1896 			 * can return.
1897 			 *
1898 			 * We can release the spl once we have marked the
1899 			 * page busy.
1900 			 */
1901 			if (fs->mary[0]->object != &kernel_object) {
1902 				if ((fs->mary[0]->valid & VM_PAGE_BITS_ALL) !=
1903 				    VM_PAGE_BITS_ALL) {
1904 					goto readrest;
1905 				}
1906 				if (fs->mary[0]->flags & PG_RAM) {
1907 					if (debug_cluster)
1908 						kprintf("R");
1909 					vm_page_flag_clear(fs->mary[0], PG_RAM);
1910 					goto readrest;
1911 				}
1912 			}
1913 			atomic_clear_int(&fs->first_ba->flags,
1914 					 VM_MAP_BACK_EXCL_HEUR);
1915 			break; /* break to PAGE HAS BEEN FOUND */
1916 		}
1917 
1918 		/*
1919 		 * Page is not resident, If this is the search termination
1920 		 * or the pager might contain the page, allocate a new page.
1921 		 */
1922 		if (TRYPAGER(fs) || fs->ba == fs->first_ba) {
1923 			/*
1924 			 * If this is a SWAP object we can use the shared
1925 			 * lock to check existence of a swap block.  If
1926 			 * there isn't one we can skip to the next object.
1927 			 *
1928 			 * However, if this is the first object we allocate
1929 			 * a page now just in case we need to copy to it
1930 			 * later.
1931 			 */
1932 			if (fs->ba != fs->first_ba &&
1933 			    fs->ba->object->type == OBJT_SWAP) {
1934 				if (swap_pager_haspage_locked(fs->ba->object,
1935 							      pindex) == 0) {
1936 					goto next;
1937 				}
1938 			}
1939 
1940 			/*
1941 			 * Allocating, must be exclusive.
1942 			 */
1943 			atomic_set_int(&fs->first_ba->flags,
1944 				       VM_MAP_BACK_EXCL_HEUR);
1945 			if (fs->ba == fs->first_ba && fs->first_shared) {
1946 				fs->first_shared = 0;
1947 				vm_object_pip_wakeup(fs->first_ba->object);
1948 				unlock_things(fs);
1949 				return (KERN_TRY_AGAIN);
1950 			}
1951 			if (fs->ba != fs->first_ba && fs->shared) {
1952 				fs->first_shared = 0;
1953 				fs->shared = 0;
1954 				vm_object_pip_wakeup(fs->first_ba->object);
1955 				unlock_things(fs);
1956 				return (KERN_TRY_AGAIN);
1957 			}
1958 
1959 			/*
1960 			 * If the page is beyond the object size we fail
1961 			 */
1962 			if (pindex >= fs->ba->object->size) {
1963 				vm_object_pip_wakeup(fs->first_ba->object);
1964 				unlock_things(fs);
1965 				return (KERN_PROTECTION_FAILURE);
1966 			}
1967 
1968 			/*
1969 			 * Allocate a new page for this object/offset pair.
1970 			 *
1971 			 * It is possible for the allocation to race, so
1972 			 * handle the case.
1973 			 *
1974 			 * Does not apply to OBJT_MGTDEVICE (e.g. gpu / drm
1975 			 * subsystem).  For OBJT_MGTDEVICE the pages are not
1976 			 * indexed in the VM object at all but instead directly
1977 			 * entered into the pmap.
1978 			 */
1979 			fs->mary[0] = NULL;
1980 			if (fs->ba->object->type == OBJT_MGTDEVICE)
1981 				goto readrest;
1982 
1983 			if (!vm_page_count_severe()) {
1984 				fs->mary[0] = vm_page_alloc(fs->ba->object,
1985 				    pindex,
1986 				    ((fs->vp || fs->ba->backing_ba) ?
1987 					VM_ALLOC_NULL_OK | VM_ALLOC_NORMAL :
1988 					VM_ALLOC_NULL_OK | VM_ALLOC_NORMAL |
1989 					VM_ALLOC_USE_GD | VM_ALLOC_ZERO));
1990 			}
1991 			if (fs->mary[0] == NULL) {
1992 				vm_object_pip_wakeup(fs->first_ba->object);
1993 				unlock_things(fs);
1994 				if (allow_nofault == 0 ||
1995 				    (curthread->td_flags & TDF_NOFAULT) == 0) {
1996 					thread_t td;
1997 
1998 					vm_wait_pfault();
1999 					td = curthread;
2000 					if (td->td_proc && (td->td_proc->p_flags & P_LOWMEMKILL))
2001 						return (KERN_PROTECTION_FAILURE);
2002 				}
2003 				return (KERN_TRY_AGAIN);
2004 			}
2005 
2006 			/*
2007 			 * Fall through to readrest.  We have a new page which
2008 			 * will have to be paged (since m->valid will be 0).
2009 			 */
2010 		}
2011 
2012 readrest:
2013 		/*
2014 		 * We have found an invalid or partially valid page, a
2015 		 * page with a read-ahead mark which might be partially or
2016 		 * fully valid (and maybe dirty too), or we have allocated
2017 		 * a new page.
2018 		 *
2019 		 * Attempt to fault-in the page if there is a chance that the
2020 		 * pager has it, and potentially fault in additional pages
2021 		 * at the same time.
2022 		 *
2023 		 * If TRYPAGER is true then fs.mary[0] will be non-NULL and
2024 		 * busied for us.
2025 		 */
2026 		if (TRYPAGER(fs)) {
2027 			u_char behavior = vm_map_entry_behavior(fs->entry);
2028 			vm_object_t object;
2029 			vm_page_t first_m;
2030 			int seqaccess;
2031 			int rv;
2032 
2033 			if (behavior == MAP_ENTRY_BEHAV_RANDOM)
2034 				seqaccess = 0;
2035 			else
2036 				seqaccess = -1;
2037 
2038 			/*
2039 			 * Doing I/O may synchronously insert additional
2040 			 * pages so we can't be shared at this point either.
2041 			 *
2042 			 * NOTE: We can't free fs->mary[0] here in the
2043 			 *	 allocated case (fs->ba != fs->first_ba) as
2044 			 *	 this would require an exclusively locked
2045 			 *	 VM object.
2046 			 */
2047 			if (fs->ba == fs->first_ba && fs->first_shared) {
2048 				if (fs->mary[0]) {
2049 					vm_page_deactivate(fs->mary[0]);
2050 					vm_page_wakeup(fs->mary[0]);
2051 					fs->mary[0]= NULL;
2052 				}
2053 				fs->first_shared = 0;
2054 				vm_object_pip_wakeup(fs->first_ba->object);
2055 				unlock_things(fs);
2056 				return (KERN_TRY_AGAIN);
2057 			}
2058 			if (fs->ba != fs->first_ba && fs->shared) {
2059 				if (fs->mary[0]) {
2060 					vm_page_deactivate(fs->mary[0]);
2061 					vm_page_wakeup(fs->mary[0]);
2062 					fs->mary[0] = NULL;
2063 				}
2064 				fs->first_shared = 0;
2065 				fs->shared = 0;
2066 				vm_object_pip_wakeup(fs->first_ba->object);
2067 				unlock_things(fs);
2068 				return (KERN_TRY_AGAIN);
2069 			}
2070 
2071 			object = fs->ba->object;
2072 			first_m = NULL;
2073 
2074 			/* object is held, no more access to entry or ba's */
2075 
2076 			/*
2077 			 * Acquire the page data.  We still hold object
2078 			 * and the page has been BUSY's.
2079 			 *
2080 			 * We own the page, but we must re-issue the lookup
2081 			 * because the pager may have replaced it (for example,
2082 			 * in order to enter a fictitious page into the
2083 			 * object).  In this situation the pager will have
2084 			 * cleaned up the old page and left the new one
2085 			 * busy for us.
2086 			 *
2087 			 * If we got here through a PG_RAM read-ahead
2088 			 * mark the page may be partially dirty and thus
2089 			 * not freeable.  Don't bother checking to see
2090 			 * if the pager has the page because we can't free
2091 			 * it anyway.  We have to depend on the get_page
2092 			 * operation filling in any gaps whether there is
2093 			 * backing store or not.
2094 			 *
2095 			 * We must dispose of the page (fs->mary[0]) and also
2096 			 * possibly first_m (the fronting layer).  If
2097 			 * this is a write fault leave the page intact
2098 			 * because we will probably have to copy fs->mary[0]
2099 			 * to fs->first_m on the retry.  If this is a
2100 			 * read fault we probably won't need the page.
2101 			 *
2102 			 * For OBJT_MGTDEVICE (and eventually all types),
2103 			 * fs->mary[0] is not pre-allocated and may be set
2104 			 * to a vm_page (busied for us) without being inserted
2105 			 * into the object.  In this case we want to return
2106 			 * the vm_page directly so the caller can issue the
2107 			 * pmap_enter().
2108 			 */
2109 			rv = vm_pager_get_page(object, pindex,
2110 					       &fs->mary[0], seqaccess);
2111 
2112 			if (rv == VM_PAGER_OK) {
2113 				++fs->hardfault;
2114 				if (object->type == OBJT_MGTDEVICE) {
2115 					break;
2116 				}
2117 
2118 				fs->mary[0] = vm_page_lookup(object, pindex);
2119 				if (fs->mary[0]) {
2120 					vm_page_activate(fs->mary[0]);
2121 					vm_page_wakeup(fs->mary[0]);
2122 					fs->mary[0] = NULL;
2123 				}
2124 
2125 				if (fs->mary[0]) {
2126 					/* NOT REACHED */
2127 					/* have page */
2128 					break;
2129 				}
2130 				vm_object_pip_wakeup(fs->first_ba->object);
2131 				unlock_things(fs);
2132 				return (KERN_TRY_AGAIN);
2133 			}
2134 
2135 			/*
2136 			 * If the pager doesn't have the page, continue on
2137 			 * to the next object.  Retain the vm_page if this
2138 			 * is the first object, we may need to copy into
2139 			 * it later.
2140 			 */
2141 			if (rv == VM_PAGER_FAIL) {
2142 				if (fs->ba != fs->first_ba) {
2143 					if (fs->mary[0]) {
2144 						vm_page_free(fs->mary[0]);
2145 						fs->mary[0] = NULL;
2146 					}
2147 				}
2148 				goto next;
2149 			}
2150 
2151 			/*
2152 			 * Remove the bogus page (which does not exist at this
2153 			 * object/offset).
2154 			 *
2155 			 * Also wake up any other process that may want to bring
2156 			 * in this page.
2157 			 *
2158 			 * If this is the top-level object, we must leave the
2159 			 * busy page to prevent another process from rushing
2160 			 * past us, and inserting the page in that object at
2161 			 * the same time that we are.
2162 			 */
2163 			if (rv == VM_PAGER_ERROR) {
2164 				if (curproc) {
2165 					kprintf("vm_fault: pager read error, "
2166 						"pid %d (%s)\n",
2167 						curproc->p_pid,
2168 						curproc->p_comm);
2169 				} else {
2170 					kprintf("vm_fault: pager read error, "
2171 						"thread %p (%s)\n",
2172 						curthread,
2173 						curthread->td_comm);
2174 				}
2175 			}
2176 
2177 			/*
2178 			 * I/O error or data outside pager's range.
2179 			 */
2180 			if (fs->mary[0]) {
2181 				vnode_pager_freepage(fs->mary[0]);
2182 				fs->mary[0] = NULL;
2183 			}
2184 			if (first_m) {
2185 				vm_page_free(first_m);
2186 				first_m = NULL;		/* safety */
2187 			}
2188 			vm_object_pip_wakeup(object);
2189 			unlock_things(fs);
2190 
2191 			switch(rv) {
2192 			case VM_PAGER_ERROR:
2193 				return (KERN_FAILURE);
2194 			case VM_PAGER_BAD:
2195 				return (KERN_PROTECTION_FAILURE);
2196 			default:
2197 				return (KERN_PROTECTION_FAILURE);
2198 			}
2199 
2200 #if 0
2201 			/*
2202 			 * Data outside the range of the pager or an I/O error
2203 			 *
2204 			 * The page may have been wired during the pagein,
2205 			 * e.g. by the buffer cache, and cannot simply be
2206 			 * freed.  Call vnode_pager_freepage() to deal with it.
2207 			 *
2208 			 * The object is not held shared so we can safely
2209 			 * free the page.
2210 			 */
2211 			if (fs->ba != fs->first_ba) {
2212 
2213 				/*
2214 				 * XXX - we cannot just fall out at this
2215 				 * point, m has been freed and is invalid!
2216 				 */
2217 			}
2218 
2219 			/*
2220 			 * XXX - the check for kernel_map is a kludge to work
2221 			 * around having the machine panic on a kernel space
2222 			 * fault w/ I/O error.
2223 			 */
2224 			if (((fs->map != &kernel_map) &&
2225 			    (rv == VM_PAGER_ERROR)) || (rv == VM_PAGER_BAD)) {
2226 				if (fs->m) {
2227 					/* from just above */
2228 					KKASSERT(fs->first_shared == 0);
2229 					vnode_pager_freepage(fs->m);
2230 					fs->m = NULL;
2231 				}
2232 				/* NOT REACHED */
2233 			}
2234 #endif
2235 		}
2236 
2237 next:
2238 		/*
2239 		 * We get here if the object has a default pager (or unwiring)
2240 		 * or the pager doesn't have the page.
2241 		 *
2242 		 * fs->first_m will be used for the COW unless we find a
2243 		 * deeper page to be mapped read-only, in which case the
2244 		 * unlock*(fs) will free first_m.
2245 		 */
2246 		if (fs->ba == fs->first_ba)
2247 			fs->first_m = fs->mary[0];
2248 
2249 		/*
2250 		 * Move on to the next object.  The chain lock should prevent
2251 		 * the backing_object from getting ripped out from under us.
2252 		 *
2253 		 * The object lock for the next object is governed by
2254 		 * fs->shared.
2255 		 */
2256 		next_ba = fs->ba->backing_ba;
2257 		if (next_ba == NULL) {
2258 			/*
2259 			 * If there's no object left, fill the page in the top
2260 			 * object with zeros.
2261 			 */
2262 			if (fs->ba != fs->first_ba) {
2263 				vm_object_pip_wakeup(fs->ba->object);
2264 				vm_object_drop(fs->ba->object);
2265 				fs->ba = fs->first_ba;
2266 				pindex = first_pindex;
2267 				fs->mary[0] = fs->first_m;
2268 			}
2269 			fs->first_m = NULL;
2270 
2271 			/*
2272 			 * Zero the page and mark it valid.
2273 			 */
2274 			vm_page_zero_fill(fs->mary[0]);
2275 			mycpu->gd_cnt.v_zfod++;
2276 			fs->mary[0]->valid = VM_PAGE_BITS_ALL;
2277 			break;	/* break to PAGE HAS BEEN FOUND */
2278 		}
2279 
2280 		if (fs->shared)
2281 			vm_object_hold_shared(next_ba->object);
2282 		else
2283 			vm_object_hold(next_ba->object);
2284 		KKASSERT(next_ba == fs->ba->backing_ba);
2285 		pindex -= OFF_TO_IDX(fs->ba->offset);
2286 		pindex += OFF_TO_IDX(next_ba->offset);
2287 
2288 		if (fs->ba != fs->first_ba) {
2289 			vm_object_pip_wakeup(fs->ba->object);
2290 			vm_object_lock_swap();	/* flip ba/next_ba */
2291 			vm_object_drop(fs->ba->object);
2292 		}
2293 		fs->ba = next_ba;
2294 		vm_object_pip_add(next_ba->object, 1);
2295 	}
2296 
2297 	/*
2298 	 * PAGE HAS BEEN FOUND. [Loop invariant still holds -- the object lock
2299 	 * is held.]
2300 	 *
2301 	 * object still held.
2302 	 * vm_map may not be locked (determined by fs->lookup_still_valid)
2303 	 *
2304 	 * local shared variable may be different from fs->shared.
2305 	 *
2306 	 * If the page is being written, but isn't already owned by the
2307 	 * top-level object, we have to copy it into a new page owned by the
2308 	 * top-level object.
2309 	 */
2310 	KASSERT((fs->mary[0]->busy_count & PBUSY_LOCKED) != 0,
2311 		("vm_fault: not busy after main loop"));
2312 
2313 	if (fs->ba != fs->first_ba) {
2314 		/*
2315 		 * We only really need to copy if we want to write it.
2316 		 */
2317 		if (fault_type & VM_PROT_WRITE) {
2318 #if 0
2319 			/* CODE REFACTOR IN PROGRESS, REMOVE OPTIMIZATION */
2320 			/*
2321 			 * This allows pages to be virtually copied from a
2322 			 * backing_object into the first_object, where the
2323 			 * backing object has no other refs to it, and cannot
2324 			 * gain any more refs.  Instead of a bcopy, we just
2325 			 * move the page from the backing object to the
2326 			 * first object.  Note that we must mark the page
2327 			 * dirty in the first object so that it will go out
2328 			 * to swap when needed.
2329 			 */
2330 			if (virtual_copy_ok(fs)) {
2331 				/*
2332 				 * (first_m) and (m) are both busied.  We have
2333 				 * move (m) into (first_m)'s object/pindex
2334 				 * in an atomic fashion, then free (first_m).
2335 				 *
2336 				 * first_object is held so second remove
2337 				 * followed by the rename should wind
2338 				 * up being atomic.  vm_page_free() might
2339 				 * block so we don't do it until after the
2340 				 * rename.
2341 				 */
2342 				vm_page_protect(fs->first_m, VM_PROT_NONE);
2343 				vm_page_remove(fs->first_m);
2344 				vm_page_rename(fs->mary[0],
2345 					       fs->first_ba->object,
2346 					       first_pindex);
2347 				vm_page_free(fs->first_m);
2348 				fs->first_m = fs->mary[0];
2349 				fs->mary[0] = NULL;
2350 				mycpu->gd_cnt.v_cow_optim++;
2351 			} else
2352 #endif
2353 			{
2354 				/*
2355 				 * Oh, well, lets copy it.
2356 				 *
2357 				 * We used to unmap the original page here
2358 				 * because vm_fault_page() didn't and this
2359 				 * would cause havoc for the umtx*() code
2360 				 * and the procfs code.
2361 				 *
2362 				 * This is no longer necessary.  The
2363 				 * vm_fault_page() routine will now unmap the
2364 				 * page after a COW, and the umtx code will
2365 				 * recover on its own.
2366 				 */
2367 				/*
2368 				 * NOTE: Since fs->mary[0] is a backing page,
2369 				 *	 it is read-only, so there isn't any
2370 				 *	 copy race vs writers.
2371 				 */
2372 				KKASSERT(fs->first_shared == 0);
2373 				vm_page_copy(fs->mary[0], fs->first_m);
2374 				/* pmap_remove_specific(
2375 				    &curthread->td_lwp->lwp_vmspace->vm_pmap,
2376 				    fs->mary[0]); */
2377 			}
2378 
2379 			/*
2380 			 * We no longer need the old page or object.
2381 			 */
2382 			if (fs->mary[0])
2383 				release_page(fs);
2384 
2385 			/*
2386 			 * fs->ba != fs->first_ba due to above conditional
2387 			 */
2388 			vm_object_pip_wakeup(fs->ba->object);
2389 			vm_object_drop(fs->ba->object);
2390 			fs->ba = fs->first_ba;
2391 
2392 			/*
2393 			 * Only use the new page below...
2394 			 */
2395 			mycpu->gd_cnt.v_cow_faults++;
2396 			fs->mary[0] = fs->first_m;
2397 			pindex = first_pindex;
2398 		} else {
2399 			/*
2400 			 * If it wasn't a write fault avoid having to copy
2401 			 * the page by mapping it read-only from backing
2402 			 * store.  The process is not allowed to modify
2403 			 * backing pages.
2404 			 */
2405 			fs->prot &= ~VM_PROT_WRITE;
2406 		}
2407 	}
2408 
2409 	/*
2410 	 * Relock the map if necessary, then check the generation count.
2411 	 * relock_map() will update fs->timestamp to account for the
2412 	 * relocking if necessary.
2413 	 *
2414 	 * If the count has changed after relocking then all sorts of
2415 	 * crap may have happened and we have to retry.
2416 	 *
2417 	 * NOTE: The relock_map() can fail due to a deadlock against
2418 	 *	 the vm_page we are holding BUSY.
2419 	 */
2420 	KKASSERT(fs->lookup_still_valid != 0);
2421 #if 0
2422 	if (fs->lookup_still_valid == 0 && fs->map) {
2423 		if (relock_map(fs) ||
2424 		    fs->map->timestamp != fs->map_generation) {
2425 			release_page(fs);
2426 			vm_object_pip_wakeup(fs->first_ba->object);
2427 			unlock_things(fs);
2428 			return (KERN_TRY_AGAIN);
2429 		}
2430 	}
2431 #endif
2432 
2433 	/*
2434 	 * If the fault is a write, we know that this page is being
2435 	 * written NOW so dirty it explicitly to save on pmap_is_modified()
2436 	 * calls later.
2437 	 *
2438 	 * If this is a NOSYNC mmap we do not want to set PG_NOSYNC
2439 	 * if the page is already dirty to prevent data written with
2440 	 * the expectation of being synced from not being synced.
2441 	 * Likewise if this entry does not request NOSYNC then make
2442 	 * sure the page isn't marked NOSYNC.  Applications sharing
2443 	 * data should use the same flags to avoid ping ponging.
2444 	 *
2445 	 * Also tell the backing pager, if any, that it should remove
2446 	 * any swap backing since the page is now dirty.
2447 	 */
2448 	vm_page_activate(fs->mary[0]);
2449 	if (fs->prot & VM_PROT_WRITE) {
2450 		vm_object_set_writeable_dirty(fs->first_ba->object);
2451 		vm_set_nosync(fs->mary[0], fs->entry);
2452 		if (fs->fault_flags & VM_FAULT_DIRTY) {
2453 			vm_page_dirty(fs->mary[0]);
2454 			if (fs->mary[0]->flags & PG_SWAPPED) {
2455 				/*
2456 				 * If the page is swapped out we have to call
2457 				 * swap_pager_unswapped() which requires an
2458 				 * exclusive object lock.  If we are shared,
2459 				 * we must clear the shared flag and retry.
2460 				 */
2461 				if ((fs->ba == fs->first_ba &&
2462 				     fs->first_shared) ||
2463 				    (fs->ba != fs->first_ba && fs->shared)) {
2464 					vm_page_wakeup(fs->mary[0]);
2465 					fs->mary[0] = NULL;
2466 					if (fs->ba == fs->first_ba)
2467 						fs->first_shared = 0;
2468 					else
2469 						fs->shared = 0;
2470 					vm_object_pip_wakeup(
2471 							fs->first_ba->object);
2472 					unlock_things(fs);
2473 					return (KERN_TRY_AGAIN);
2474 				}
2475 				swap_pager_unswapped(fs->mary[0]);
2476 			}
2477 		}
2478 	}
2479 
2480 	/*
2481 	 * We found our page at backing layer ba.  Leave the layer state
2482 	 * intact.
2483 	 */
2484 
2485 	vm_object_pip_wakeup(fs->first_ba->object);
2486 #if 0
2487 	if (fs->ba != fs->first_ba)
2488 		vm_object_drop(fs->ba->object);
2489 #endif
2490 
2491 	/*
2492 	 * Page had better still be busy.  We are still locked up and
2493 	 * fs->ba->object will have another PIP reference for the case
2494 	 * where fs->ba != fs->first_ba.
2495 	 */
2496 	KASSERT(fs->mary[0]->busy_count & PBUSY_LOCKED,
2497 		("vm_fault: page %p not busy!", fs->mary[0]));
2498 
2499 	/*
2500 	 * Sanity check: page must be completely valid or it is not fit to
2501 	 * map into user space.  vm_pager_get_pages() ensures this.
2502 	 */
2503 	if (fs->mary[0]->valid != VM_PAGE_BITS_ALL) {
2504 		vm_page_zero_invalid(fs->mary[0], TRUE);
2505 		kprintf("Warning: page %p partially invalid on fault\n",
2506 			fs->mary[0]);
2507 	}
2508 
2509 	return (KERN_SUCCESS);
2510 }
2511 
2512 /*
2513  * Wire down a range of virtual addresses in a map.  The entry in question
2514  * should be marked in-transition and the map must be locked.  We must
2515  * release the map temporarily while faulting-in the page to avoid a
2516  * deadlock.  Note that the entry may be clipped while we are blocked but
2517  * will never be freed.
2518  *
2519  * map must be locked on entry.
2520  */
2521 int
2522 vm_fault_wire(vm_map_t map, vm_map_entry_t entry,
2523 	      boolean_t user_wire, int kmflags)
2524 {
2525 	boolean_t fictitious;
2526 	vm_offset_t start;
2527 	vm_offset_t end;
2528 	vm_offset_t va;
2529 	pmap_t pmap;
2530 	int rv;
2531 	int wire_prot;
2532 	int fault_flags;
2533 	vm_page_t m;
2534 
2535 	if (user_wire) {
2536 		wire_prot = VM_PROT_READ;
2537 		fault_flags = VM_FAULT_USER_WIRE;
2538 	} else {
2539 		wire_prot = VM_PROT_READ | VM_PROT_WRITE;
2540 		fault_flags = VM_FAULT_CHANGE_WIRING;
2541 	}
2542 	if (kmflags & KM_NOTLBSYNC)
2543 		wire_prot |= VM_PROT_NOSYNC;
2544 
2545 	pmap = vm_map_pmap(map);
2546 	start = entry->ba.start;
2547 	end = entry->ba.end;
2548 
2549 	switch(entry->maptype) {
2550 	case VM_MAPTYPE_NORMAL:
2551 	case VM_MAPTYPE_VPAGETABLE:
2552 		fictitious = entry->ba.object &&
2553 			    ((entry->ba.object->type == OBJT_DEVICE) ||
2554 			     (entry->ba.object->type == OBJT_MGTDEVICE));
2555 		break;
2556 	case VM_MAPTYPE_UKSMAP:
2557 		fictitious = TRUE;
2558 		break;
2559 	default:
2560 		fictitious = FALSE;
2561 		break;
2562 	}
2563 
2564 	if (entry->eflags & MAP_ENTRY_KSTACK)
2565 		start += PAGE_SIZE;
2566 	map->timestamp++;
2567 	vm_map_unlock(map);
2568 
2569 	/*
2570 	 * We simulate a fault to get the page and enter it in the physical
2571 	 * map.
2572 	 */
2573 	for (va = start; va < end; va += PAGE_SIZE) {
2574 		rv = vm_fault(map, va, wire_prot, fault_flags);
2575 		if (rv) {
2576 			while (va > start) {
2577 				va -= PAGE_SIZE;
2578 				m = pmap_unwire(pmap, va);
2579 				if (m && !fictitious) {
2580 					vm_page_busy_wait(m, FALSE, "vmwrpg");
2581 					vm_page_unwire(m, 1);
2582 					vm_page_wakeup(m);
2583 				}
2584 			}
2585 			goto done;
2586 		}
2587 	}
2588 	rv = KERN_SUCCESS;
2589 done:
2590 	vm_map_lock(map);
2591 
2592 	return (rv);
2593 }
2594 
2595 /*
2596  * Unwire a range of virtual addresses in a map.  The map should be
2597  * locked.
2598  */
2599 void
2600 vm_fault_unwire(vm_map_t map, vm_map_entry_t entry)
2601 {
2602 	boolean_t fictitious;
2603 	vm_offset_t start;
2604 	vm_offset_t end;
2605 	vm_offset_t va;
2606 	pmap_t pmap;
2607 	vm_page_t m;
2608 
2609 	pmap = vm_map_pmap(map);
2610 	start = entry->ba.start;
2611 	end = entry->ba.end;
2612 	fictitious = entry->ba.object &&
2613 			((entry->ba.object->type == OBJT_DEVICE) ||
2614 			 (entry->ba.object->type == OBJT_MGTDEVICE));
2615 	if (entry->eflags & MAP_ENTRY_KSTACK)
2616 		start += PAGE_SIZE;
2617 
2618 	/*
2619 	 * Since the pages are wired down, we must be able to get their
2620 	 * mappings from the physical map system.
2621 	 */
2622 	for (va = start; va < end; va += PAGE_SIZE) {
2623 		m = pmap_unwire(pmap, va);
2624 		if (m && !fictitious) {
2625 			vm_page_busy_wait(m, FALSE, "vmwrpg");
2626 			vm_page_unwire(m, 1);
2627 			vm_page_wakeup(m);
2628 		}
2629 	}
2630 }
2631 
2632 /*
2633  * Simulate write faults to bring all data into the head object, return
2634  * KERN_SUCCESS on success (which should be always unless the system runs
2635  * out of memory).
2636  *
2637  * The caller will handle destroying the backing_ba's.
2638  */
2639 int
2640 vm_fault_collapse(vm_map_t map, vm_map_entry_t entry)
2641 {
2642 	struct faultstate fs;
2643 	vm_ooffset_t scan;
2644 	vm_pindex_t pindex;
2645 	vm_object_t object;
2646 	int rv;
2647 	int all_shadowed;
2648 
2649 	bzero(&fs, sizeof(fs));
2650 	object = entry->ba.object;
2651 
2652 	fs.first_prot = entry->max_protection |	/* optional VM_PROT_EXECUTE */
2653 			VM_PROT_READ | VM_PROT_WRITE | VM_PROT_OVERRIDE_WRITE;
2654 	fs.fault_flags = VM_FAULT_NORMAL;
2655 	fs.map = map;
2656 	fs.entry = entry;
2657 	fs.lookup_still_valid = -1;	/* leave map atomically locked */
2658 	fs.first_ba = &entry->ba;
2659 	fs.first_ba_held = -1;		/* leave object held */
2660 
2661 	/* fs.hardfault */
2662 
2663 	vm_object_hold(object);
2664 	rv = KERN_SUCCESS;
2665 
2666 	scan = entry->ba.start;
2667 	all_shadowed = 1;
2668 
2669 	while (scan < entry->ba.end) {
2670 		pindex = OFF_TO_IDX(entry->ba.offset + (scan - entry->ba.start));
2671 
2672 		if (vm_page_lookup(object, pindex)) {
2673 			scan += PAGE_SIZE;
2674 			continue;
2675 		}
2676 
2677 		all_shadowed = 0;
2678 		fs.ba = fs.first_ba;
2679 		fs.prot = fs.first_prot;
2680 
2681 		rv = vm_fault_object(&fs, pindex, fs.first_prot, 1);
2682 		if (rv == KERN_TRY_AGAIN)
2683 			continue;
2684 		if (rv != KERN_SUCCESS)
2685 			break;
2686 		vm_page_flag_set(fs.mary[0], PG_REFERENCED);
2687 		vm_page_activate(fs.mary[0]);
2688 		vm_page_wakeup(fs.mary[0]);
2689 		scan += PAGE_SIZE;
2690 	}
2691 	KKASSERT(entry->ba.object == object);
2692 	vm_object_drop(object);
2693 
2694 	/*
2695 	 * If the fronting object did not have every page we have to clear
2696 	 * the pmap range due to the pages being changed so we can fault-in
2697 	 * the proper pages.
2698 	 */
2699 	if (all_shadowed == 0)
2700 		pmap_remove(map->pmap, entry->ba.start, entry->ba.end);
2701 
2702 	return rv;
2703 }
2704 
2705 /*
2706  * Copy all of the pages from one map entry to another.  If the source
2707  * is wired down we just use vm_page_lookup().  If not we use
2708  * vm_fault_object().
2709  *
2710  * The source and destination maps must be locked for write.
2711  * The source and destination maps token must be held
2712  *
2713  * No other requirements.
2714  *
2715  * XXX do segment optimization
2716  */
2717 void
2718 vm_fault_copy_entry(vm_map_t dst_map, vm_map_t src_map,
2719 		    vm_map_entry_t dst_entry, vm_map_entry_t src_entry)
2720 {
2721 	vm_object_t dst_object;
2722 	vm_object_t src_object;
2723 	vm_ooffset_t dst_offset;
2724 	vm_ooffset_t src_offset;
2725 	vm_prot_t prot;
2726 	vm_offset_t vaddr;
2727 	vm_page_t dst_m;
2728 	vm_page_t src_m;
2729 
2730 	src_object = src_entry->ba.object;
2731 	src_offset = src_entry->ba.offset;
2732 
2733 	/*
2734 	 * Create the top-level object for the destination entry. (Doesn't
2735 	 * actually shadow anything - we copy the pages directly.)
2736 	 */
2737 	vm_map_entry_allocate_object(dst_entry);
2738 	dst_object = dst_entry->ba.object;
2739 
2740 	prot = dst_entry->max_protection;
2741 
2742 	/*
2743 	 * Loop through all of the pages in the entry's range, copying each
2744 	 * one from the source object (it should be there) to the destination
2745 	 * object.
2746 	 */
2747 	vm_object_hold(src_object);
2748 	vm_object_hold(dst_object);
2749 
2750 	for (vaddr = dst_entry->ba.start, dst_offset = 0;
2751 	     vaddr < dst_entry->ba.end;
2752 	     vaddr += PAGE_SIZE, dst_offset += PAGE_SIZE) {
2753 
2754 		/*
2755 		 * Allocate a page in the destination object
2756 		 */
2757 		do {
2758 			dst_m = vm_page_alloc(dst_object,
2759 					      OFF_TO_IDX(dst_offset),
2760 					      VM_ALLOC_NORMAL);
2761 			if (dst_m == NULL) {
2762 				vm_wait(0);
2763 			}
2764 		} while (dst_m == NULL);
2765 
2766 		/*
2767 		 * Find the page in the source object, and copy it in.
2768 		 * (Because the source is wired down, the page will be in
2769 		 * memory.)
2770 		 */
2771 		src_m = vm_page_lookup(src_object,
2772 				       OFF_TO_IDX(dst_offset + src_offset));
2773 		if (src_m == NULL)
2774 			panic("vm_fault_copy_wired: page missing");
2775 
2776 		vm_page_copy(src_m, dst_m);
2777 
2778 		/*
2779 		 * Enter it in the pmap...
2780 		 */
2781 		pmap_enter(dst_map->pmap, vaddr, dst_m, prot, FALSE, dst_entry);
2782 
2783 		/*
2784 		 * Mark it no longer busy, and put it on the active list.
2785 		 */
2786 		vm_page_activate(dst_m);
2787 		vm_page_wakeup(dst_m);
2788 	}
2789 	vm_object_drop(dst_object);
2790 	vm_object_drop(src_object);
2791 }
2792 
2793 #if 0
2794 
2795 /*
2796  * This routine checks around the requested page for other pages that
2797  * might be able to be faulted in.  This routine brackets the viable
2798  * pages for the pages to be paged in.
2799  *
2800  * Inputs:
2801  *	m, rbehind, rahead
2802  *
2803  * Outputs:
2804  *  marray (array of vm_page_t), reqpage (index of requested page)
2805  *
2806  * Return value:
2807  *  number of pages in marray
2808  */
2809 static int
2810 vm_fault_additional_pages(vm_page_t m, int rbehind, int rahead,
2811 			  vm_page_t *marray, int *reqpage)
2812 {
2813 	int i,j;
2814 	vm_object_t object;
2815 	vm_pindex_t pindex, startpindex, endpindex, tpindex;
2816 	vm_page_t rtm;
2817 	int cbehind, cahead;
2818 
2819 	object = m->object;
2820 	pindex = m->pindex;
2821 
2822 	/*
2823 	 * we don't fault-ahead for device pager
2824 	 */
2825 	if ((object->type == OBJT_DEVICE) ||
2826 	    (object->type == OBJT_MGTDEVICE)) {
2827 		*reqpage = 0;
2828 		marray[0] = m;
2829 		return 1;
2830 	}
2831 
2832 	/*
2833 	 * if the requested page is not available, then give up now
2834 	 */
2835 	if (!vm_pager_has_page(object, pindex, &cbehind, &cahead)) {
2836 		*reqpage = 0;	/* not used by caller, fix compiler warn */
2837 		return 0;
2838 	}
2839 
2840 	if ((cbehind == 0) && (cahead == 0)) {
2841 		*reqpage = 0;
2842 		marray[0] = m;
2843 		return 1;
2844 	}
2845 
2846 	if (rahead > cahead) {
2847 		rahead = cahead;
2848 	}
2849 
2850 	if (rbehind > cbehind) {
2851 		rbehind = cbehind;
2852 	}
2853 
2854 	/*
2855 	 * Do not do any readahead if we have insufficient free memory.
2856 	 *
2857 	 * XXX code was broken disabled before and has instability
2858 	 * with this conditonal fixed, so shortcut for now.
2859 	 */
2860 	if (burst_fault == 0 || vm_page_count_severe()) {
2861 		marray[0] = m;
2862 		*reqpage = 0;
2863 		return 1;
2864 	}
2865 
2866 	/*
2867 	 * scan backward for the read behind pages -- in memory
2868 	 *
2869 	 * Assume that if the page is not found an interrupt will not
2870 	 * create it.  Theoretically interrupts can only remove (busy)
2871 	 * pages, not create new associations.
2872 	 */
2873 	if (pindex > 0) {
2874 		if (rbehind > pindex) {
2875 			rbehind = pindex;
2876 			startpindex = 0;
2877 		} else {
2878 			startpindex = pindex - rbehind;
2879 		}
2880 
2881 		vm_object_hold(object);
2882 		for (tpindex = pindex; tpindex > startpindex; --tpindex) {
2883 			if (vm_page_lookup(object, tpindex - 1))
2884 				break;
2885 		}
2886 
2887 		i = 0;
2888 		while (tpindex < pindex) {
2889 			rtm = vm_page_alloc(object, tpindex, VM_ALLOC_SYSTEM |
2890 							     VM_ALLOC_NULL_OK);
2891 			if (rtm == NULL) {
2892 				for (j = 0; j < i; j++) {
2893 					vm_page_free(marray[j]);
2894 				}
2895 				vm_object_drop(object);
2896 				marray[0] = m;
2897 				*reqpage = 0;
2898 				return 1;
2899 			}
2900 			marray[i] = rtm;
2901 			++i;
2902 			++tpindex;
2903 		}
2904 		vm_object_drop(object);
2905 	} else {
2906 		i = 0;
2907 	}
2908 
2909 	/*
2910 	 * Assign requested page
2911 	 */
2912 	marray[i] = m;
2913 	*reqpage = i;
2914 	++i;
2915 
2916 	/*
2917 	 * Scan forwards for read-ahead pages
2918 	 */
2919 	tpindex = pindex + 1;
2920 	endpindex = tpindex + rahead;
2921 	if (endpindex > object->size)
2922 		endpindex = object->size;
2923 
2924 	vm_object_hold(object);
2925 	while (tpindex < endpindex) {
2926 		if (vm_page_lookup(object, tpindex))
2927 			break;
2928 		rtm = vm_page_alloc(object, tpindex, VM_ALLOC_SYSTEM |
2929 						     VM_ALLOC_NULL_OK);
2930 		if (rtm == NULL)
2931 			break;
2932 		marray[i] = rtm;
2933 		++i;
2934 		++tpindex;
2935 	}
2936 	vm_object_drop(object);
2937 
2938 	return (i);
2939 }
2940 
2941 #endif
2942 
2943 /*
2944  * vm_prefault() provides a quick way of clustering pagefaults into a
2945  * processes address space.  It is a "cousin" of pmap_object_init_pt,
2946  * except it runs at page fault time instead of mmap time.
2947  *
2948  * vm.fast_fault	Enables pre-faulting zero-fill pages
2949  *
2950  * vm.prefault_pages	Number of pages (1/2 negative, 1/2 positive) to
2951  *			prefault.  Scan stops in either direction when
2952  *			a page is found to already exist.
2953  *
2954  * This code used to be per-platform pmap_prefault().  It is now
2955  * machine-independent and enhanced to also pre-fault zero-fill pages
2956  * (see vm.fast_fault) as well as make them writable, which greatly
2957  * reduces the number of page faults programs incur.
2958  *
2959  * Application performance when pre-faulting zero-fill pages is heavily
2960  * dependent on the application.  Very tiny applications like /bin/echo
2961  * lose a little performance while applications of any appreciable size
2962  * gain performance.  Prefaulting multiple pages also reduces SMP
2963  * congestion and can improve SMP performance significantly.
2964  *
2965  * NOTE!  prot may allow writing but this only applies to the top level
2966  *	  object.  If we wind up mapping a page extracted from a backing
2967  *	  object we have to make sure it is read-only.
2968  *
2969  * NOTE!  The caller has already handled any COW operations on the
2970  *	  vm_map_entry via the normal fault code.  Do NOT call this
2971  *	  shortcut unless the normal fault code has run on this entry.
2972  *
2973  * The related map must be locked.
2974  * No other requirements.
2975  */
2976 __read_mostly static int vm_prefault_pages = 8;
2977 SYSCTL_INT(_vm, OID_AUTO, prefault_pages, CTLFLAG_RW, &vm_prefault_pages, 0,
2978 	   "Maximum number of pages to pre-fault");
2979 __read_mostly static int vm_fast_fault = 1;
2980 SYSCTL_INT(_vm, OID_AUTO, fast_fault, CTLFLAG_RW, &vm_fast_fault, 0,
2981 	   "Burst fault zero-fill regions");
2982 
2983 /*
2984  * Set PG_NOSYNC if the map entry indicates so, but only if the page
2985  * is not already dirty by other means.  This will prevent passive
2986  * filesystem syncing as well as 'sync' from writing out the page.
2987  */
2988 static void
2989 vm_set_nosync(vm_page_t m, vm_map_entry_t entry)
2990 {
2991 	if (entry->eflags & MAP_ENTRY_NOSYNC) {
2992 		if (m->dirty == 0)
2993 			vm_page_flag_set(m, PG_NOSYNC);
2994 	} else {
2995 		vm_page_flag_clear(m, PG_NOSYNC);
2996 	}
2997 }
2998 
2999 static void
3000 vm_prefault(pmap_t pmap, vm_offset_t addra, vm_map_entry_t entry, int prot,
3001 	    int fault_flags)
3002 {
3003 	vm_map_backing_t ba;	/* first ba */
3004 	struct lwp *lp;
3005 	vm_page_t m;
3006 	vm_offset_t addr;
3007 	vm_pindex_t index;
3008 	vm_pindex_t pindex;
3009 	vm_object_t object;
3010 	int pprot;
3011 	int i;
3012 	int noneg;
3013 	int nopos;
3014 	int maxpages;
3015 
3016 	/*
3017 	 * Get stable max count value, disabled if set to 0
3018 	 */
3019 	maxpages = vm_prefault_pages;
3020 	cpu_ccfence();
3021 	if (maxpages <= 0)
3022 		return;
3023 
3024 	/*
3025 	 * We do not currently prefault mappings that use virtual page
3026 	 * tables.  We do not prefault foreign pmaps.
3027 	 */
3028 	if (entry->maptype != VM_MAPTYPE_NORMAL)
3029 		return;
3030 	lp = curthread->td_lwp;
3031 	if (lp == NULL || (pmap != vmspace_pmap(lp->lwp_vmspace)))
3032 		return;
3033 
3034 	/*
3035 	 * Limit pre-fault count to 1024 pages.
3036 	 */
3037 	if (maxpages > 1024)
3038 		maxpages = 1024;
3039 
3040 	ba = &entry->ba;
3041 	object = entry->ba.object;
3042 	KKASSERT(object != NULL);
3043 
3044 	/*
3045 	 * NOTE: VM_FAULT_DIRTY allowed later so must hold object exclusively
3046 	 *	 now (or do something more complex XXX).
3047 	 */
3048 	vm_object_hold(object);
3049 
3050 	noneg = 0;
3051 	nopos = 0;
3052 	for (i = 0; i < maxpages; ++i) {
3053 		vm_object_t lobject;
3054 		vm_object_t nobject;
3055 		vm_map_backing_t last_ba;	/* last ba */
3056 		vm_map_backing_t next_ba;	/* last ba */
3057 		int allocated = 0;
3058 		int error;
3059 
3060 		/*
3061 		 * This can eat a lot of time on a heavily contended
3062 		 * machine so yield on the tick if needed.
3063 		 */
3064 		if ((i & 7) == 7)
3065 			lwkt_yield();
3066 
3067 		/*
3068 		 * Calculate the page to pre-fault, stopping the scan in
3069 		 * each direction separately if the limit is reached.
3070 		 */
3071 		if (i & 1) {
3072 			if (noneg)
3073 				continue;
3074 			addr = addra - ((i + 1) >> 1) * PAGE_SIZE;
3075 		} else {
3076 			if (nopos)
3077 				continue;
3078 			addr = addra + ((i + 2) >> 1) * PAGE_SIZE;
3079 		}
3080 		if (addr < entry->ba.start) {
3081 			noneg = 1;
3082 			if (noneg && nopos)
3083 				break;
3084 			continue;
3085 		}
3086 		if (addr >= entry->ba.end) {
3087 			nopos = 1;
3088 			if (noneg && nopos)
3089 				break;
3090 			continue;
3091 		}
3092 
3093 		/*
3094 		 * Skip pages already mapped, and stop scanning in that
3095 		 * direction.  When the scan terminates in both directions
3096 		 * we are done.
3097 		 */
3098 		if (pmap_prefault_ok(pmap, addr) == 0) {
3099 			if (i & 1)
3100 				noneg = 1;
3101 			else
3102 				nopos = 1;
3103 			if (noneg && nopos)
3104 				break;
3105 			continue;
3106 		}
3107 
3108 		/*
3109 		 * Follow the backing layers to obtain the page to be mapped
3110 		 * into the pmap.
3111 		 *
3112 		 * If we reach the terminal object without finding a page
3113 		 * and we determine it would be advantageous, then allocate
3114 		 * a zero-fill page for the base object.  The base object
3115 		 * is guaranteed to be OBJT_DEFAULT for this case.
3116 		 *
3117 		 * In order to not have to check the pager via *haspage*()
3118 		 * we stop if any non-default object is encountered.  e.g.
3119 		 * a vnode or swap object would stop the loop.
3120 		 */
3121 		index = ((addr - entry->ba.start) + entry->ba.offset) >>
3122 			PAGE_SHIFT;
3123 		last_ba = ba;
3124 		lobject = object;
3125 		pindex = index;
3126 		pprot = prot;
3127 
3128 		/*vm_object_hold(lobject); implied */
3129 
3130 		while ((m = vm_page_lookup_busy_try(lobject, pindex,
3131 						    TRUE, &error)) == NULL) {
3132 			if (lobject->type != OBJT_DEFAULT)
3133 				break;
3134 			if ((next_ba = last_ba->backing_ba) == NULL) {
3135 				if (vm_fast_fault == 0)
3136 					break;
3137 				if ((prot & VM_PROT_WRITE) == 0 ||
3138 				    vm_page_count_min(0)) {
3139 					break;
3140 				}
3141 
3142 				/*
3143 				 * NOTE: Allocated from base object
3144 				 */
3145 				m = vm_page_alloc(object, index,
3146 						  VM_ALLOC_NORMAL |
3147 						  VM_ALLOC_ZERO |
3148 						  VM_ALLOC_USE_GD |
3149 						  VM_ALLOC_NULL_OK);
3150 				if (m == NULL)
3151 					break;
3152 				allocated = 1;
3153 				pprot = prot;
3154 				/* lobject = object .. not needed */
3155 				break;
3156 			}
3157 			if (next_ba->offset & PAGE_MASK)
3158 				break;
3159 			nobject = next_ba->object;
3160 			vm_object_hold(nobject);
3161 			pindex -= last_ba->offset >> PAGE_SHIFT;
3162 			pindex += next_ba->offset >> PAGE_SHIFT;
3163 			if (last_ba != ba) {
3164 				vm_object_lock_swap();
3165 				vm_object_drop(lobject);
3166 			}
3167 			lobject = nobject;
3168 			last_ba = next_ba;
3169 			pprot &= ~VM_PROT_WRITE;
3170 		}
3171 
3172 		/*
3173 		 * NOTE: A non-NULL (m) will be associated with lobject if
3174 		 *	 it was found there, otherwise it is probably a
3175 		 *	 zero-fill page associated with the base object.
3176 		 *
3177 		 * Give-up if no page is available.
3178 		 */
3179 		if (m == NULL) {
3180 			if (last_ba != ba)
3181 				vm_object_drop(lobject);
3182 			break;
3183 		}
3184 
3185 		/*
3186 		 * The object must be marked dirty if we are mapping a
3187 		 * writable page.  Note that (m) does not have to be
3188 		 * entered into the object, so use lobject or object
3189 		 * as appropriate instead of m->object.
3190 		 *
3191 		 * Do this before we potentially drop the object.
3192 		 */
3193 		if (pprot & VM_PROT_WRITE) {
3194 			vm_object_set_writeable_dirty(
3195 				(allocated ? object : lobject));
3196 		}
3197 
3198 		/*
3199 		 * Do not conditionalize on PG_RAM.  If pages are present in
3200 		 * the VM system we assume optimal caching.  If caching is
3201 		 * not optimal the I/O gravy train will be restarted when we
3202 		 * hit an unavailable page.  We do not want to try to restart
3203 		 * the gravy train now because we really don't know how much
3204 		 * of the object has been cached.  The cost for restarting
3205 		 * the gravy train should be low (since accesses will likely
3206 		 * be I/O bound anyway).
3207 		 */
3208 		if (last_ba != ba)
3209 			vm_object_drop(lobject);
3210 
3211 		/*
3212 		 * Enter the page into the pmap if appropriate.  If we had
3213 		 * allocated the page we have to place it on a queue.  If not
3214 		 * we just have to make sure it isn't on the cache queue
3215 		 * (pages on the cache queue are not allowed to be mapped).
3216 		 *
3217 		 * When allocated is TRUE, m corresponds to object,
3218 		 * not lobject.
3219 		 */
3220 		if (allocated) {
3221 			/*
3222 			 * Page must be zerod.
3223 			 */
3224 			vm_page_zero_fill(m);
3225 			mycpu->gd_cnt.v_zfod++;
3226 			m->valid = VM_PAGE_BITS_ALL;
3227 
3228 			/*
3229 			 * Handle dirty page case
3230 			 */
3231 			if (pprot & VM_PROT_WRITE)
3232 				vm_set_nosync(m, entry);
3233 			pmap_enter(pmap, addr, m, pprot, 0, entry);
3234 #if 0
3235 			/* REMOVE ME, a burst counts as one fault */
3236 			mycpu->gd_cnt.v_vm_faults++;
3237 			if (curthread->td_lwp)
3238 				++curthread->td_lwp->lwp_ru.ru_minflt;
3239 #endif
3240 			vm_page_deactivate(m);
3241 			if (pprot & VM_PROT_WRITE) {
3242 				/*vm_object_set_writeable_dirty(object);*/
3243 				vm_set_nosync(m, entry);
3244 				if (fault_flags & VM_FAULT_DIRTY) {
3245 					vm_page_dirty(m);
3246 					/*XXX*/
3247 					swap_pager_unswapped(m);
3248 				}
3249 			}
3250 			vm_page_wakeup(m);
3251 		} else if (error) {
3252 			/* couldn't busy page, no wakeup */
3253 		} else if (
3254 		    ((m->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
3255 		    (m->flags & PG_FICTITIOUS) == 0) {
3256 			/*
3257 			 * A fully valid page not undergoing soft I/O can
3258 			 * be immediately entered into the pmap.
3259 			 *
3260 			 * When allocated is false, m corresponds to lobject.
3261 			 */
3262 			if ((m->queue - m->pc) == PQ_CACHE)
3263 				vm_page_deactivate(m);
3264 			if (pprot & VM_PROT_WRITE) {
3265 				/*vm_object_set_writeable_dirty(lobject);*/
3266 				vm_set_nosync(m, entry);
3267 				if (fault_flags & VM_FAULT_DIRTY) {
3268 					vm_page_dirty(m);
3269 					/*XXX*/
3270 					swap_pager_unswapped(m);
3271 				}
3272 			}
3273 			if (pprot & VM_PROT_WRITE)
3274 				vm_set_nosync(m, entry);
3275 			pmap_enter(pmap, addr, m, pprot, 0, entry);
3276 #if 0
3277 			/* REMOVE ME, a burst counts as one fault */
3278 			mycpu->gd_cnt.v_vm_faults++;
3279 			if (curthread->td_lwp)
3280 				++curthread->td_lwp->lwp_ru.ru_minflt;
3281 #endif
3282 			vm_page_wakeup(m);
3283 		} else {
3284 			vm_page_wakeup(m);
3285 		}
3286 	}
3287 	vm_object_drop(object);
3288 }
3289 
3290 /*
3291  * Object can be held shared
3292  */
3293 static void
3294 vm_prefault_quick(pmap_t pmap, vm_offset_t addra,
3295 		  vm_map_entry_t entry, int prot, int fault_flags)
3296 {
3297 	struct lwp *lp;
3298 	vm_page_t m;
3299 	vm_offset_t addr;
3300 	vm_pindex_t pindex;
3301 	vm_object_t object;
3302 	int i;
3303 	int noneg;
3304 	int nopos;
3305 	int maxpages;
3306 
3307 	/*
3308 	 * Get stable max count value, disabled if set to 0
3309 	 */
3310 	maxpages = vm_prefault_pages;
3311 	cpu_ccfence();
3312 	if (maxpages <= 0)
3313 		return;
3314 
3315 	/*
3316 	 * We do not currently prefault mappings that use virtual page
3317 	 * tables.  We do not prefault foreign pmaps.
3318 	 */
3319 	if (entry->maptype != VM_MAPTYPE_NORMAL)
3320 		return;
3321 	lp = curthread->td_lwp;
3322 	if (lp == NULL || (pmap != vmspace_pmap(lp->lwp_vmspace)))
3323 		return;
3324 	object = entry->ba.object;
3325 	if (entry->ba.backing_ba != NULL)
3326 		return;
3327 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
3328 
3329 	/*
3330 	 * Limit pre-fault count to 1024 pages.
3331 	 */
3332 	if (maxpages > 1024)
3333 		maxpages = 1024;
3334 
3335 	noneg = 0;
3336 	nopos = 0;
3337 	for (i = 0; i < maxpages; ++i) {
3338 		int error;
3339 
3340 		/*
3341 		 * Calculate the page to pre-fault, stopping the scan in
3342 		 * each direction separately if the limit is reached.
3343 		 */
3344 		if (i & 1) {
3345 			if (noneg)
3346 				continue;
3347 			addr = addra - ((i + 1) >> 1) * PAGE_SIZE;
3348 		} else {
3349 			if (nopos)
3350 				continue;
3351 			addr = addra + ((i + 2) >> 1) * PAGE_SIZE;
3352 		}
3353 		if (addr < entry->ba.start) {
3354 			noneg = 1;
3355 			if (noneg && nopos)
3356 				break;
3357 			continue;
3358 		}
3359 		if (addr >= entry->ba.end) {
3360 			nopos = 1;
3361 			if (noneg && nopos)
3362 				break;
3363 			continue;
3364 		}
3365 
3366 		/*
3367 		 * Follow the VM object chain to obtain the page to be mapped
3368 		 * into the pmap.  This version of the prefault code only
3369 		 * works with terminal objects.
3370 		 *
3371 		 * The page must already exist.  If we encounter a problem
3372 		 * we stop here.
3373 		 *
3374 		 * WARNING!  We cannot call swap_pager_unswapped() or insert
3375 		 *	     a new vm_page with a shared token.
3376 		 */
3377 		pindex = ((addr - entry->ba.start) + entry->ba.offset) >>
3378 			 PAGE_SHIFT;
3379 
3380 		/*
3381 		 * Skip pages already mapped, and stop scanning in that
3382 		 * direction.  When the scan terminates in both directions
3383 		 * we are done.
3384 		 */
3385 		if (pmap_prefault_ok(pmap, addr) == 0) {
3386 			if (i & 1)
3387 				noneg = 1;
3388 			else
3389 				nopos = 1;
3390 			if (noneg && nopos)
3391 				break;
3392 			continue;
3393 		}
3394 
3395 		/*
3396 		 * Shortcut the read-only mapping case using the far more
3397 		 * efficient vm_page_lookup_sbusy_try() function.  This
3398 		 * allows us to acquire the page soft-busied only which
3399 		 * is especially nice for concurrent execs of the same
3400 		 * program.
3401 		 *
3402 		 * The lookup function also validates page suitability
3403 		 * (all valid bits set, and not fictitious).
3404 		 *
3405 		 * If the page is in PQ_CACHE we have to fall-through
3406 		 * and hard-busy it so we can move it out of PQ_CACHE.
3407 		 */
3408 		if ((prot & VM_PROT_WRITE) == 0) {
3409 			m = vm_page_lookup_sbusy_try(object, pindex,
3410 						     0, PAGE_SIZE);
3411 			if (m == NULL)
3412 				break;
3413 			if ((m->queue - m->pc) != PQ_CACHE) {
3414 				pmap_enter(pmap, addr, m, prot, 0, entry);
3415 #if 0
3416 			/* REMOVE ME, a burst counts as one fault */
3417 				mycpu->gd_cnt.v_vm_faults++;
3418 				if (curthread->td_lwp)
3419 					++curthread->td_lwp->lwp_ru.ru_minflt;
3420 #endif
3421 				vm_page_sbusy_drop(m);
3422 				continue;
3423 			}
3424 			vm_page_sbusy_drop(m);
3425 		}
3426 
3427 		/*
3428 		 * Fallback to normal vm_page lookup code.  This code
3429 		 * hard-busies the page.  Not only that, but the page
3430 		 * can remain in that state for a significant period
3431 		 * time due to pmap_enter()'s overhead.
3432 		 */
3433 		m = vm_page_lookup_busy_try(object, pindex, TRUE, &error);
3434 		if (m == NULL || error)
3435 			break;
3436 
3437 		/*
3438 		 * Stop if the page cannot be trivially entered into the
3439 		 * pmap.
3440 		 */
3441 		if (((m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) ||
3442 		    (m->flags & PG_FICTITIOUS) ||
3443 		    ((m->flags & PG_SWAPPED) &&
3444 		     (prot & VM_PROT_WRITE) &&
3445 		     (fault_flags & VM_FAULT_DIRTY))) {
3446 			vm_page_wakeup(m);
3447 			break;
3448 		}
3449 
3450 		/*
3451 		 * Enter the page into the pmap.  The object might be held
3452 		 * shared so we can't do any (serious) modifying operation
3453 		 * on it.
3454 		 */
3455 		if ((m->queue - m->pc) == PQ_CACHE)
3456 			vm_page_deactivate(m);
3457 		if (prot & VM_PROT_WRITE) {
3458 			vm_object_set_writeable_dirty(m->object);
3459 			vm_set_nosync(m, entry);
3460 			if (fault_flags & VM_FAULT_DIRTY) {
3461 				vm_page_dirty(m);
3462 				/* can't happeen due to conditional above */
3463 				/* swap_pager_unswapped(m); */
3464 			}
3465 		}
3466 		pmap_enter(pmap, addr, m, prot, 0, entry);
3467 #if 0
3468 		/* REMOVE ME, a burst counts as one fault */
3469 		mycpu->gd_cnt.v_vm_faults++;
3470 		if (curthread->td_lwp)
3471 			++curthread->td_lwp->lwp_ru.ru_minflt;
3472 #endif
3473 		vm_page_wakeup(m);
3474 	}
3475 }
3476