xref: /openbsd/sys/uvm/uvm_fault.c (revision 891d7ab6)
1 /*	$OpenBSD: uvm_fault.c,v 1.62 2011/07/03 18:34:14 oga Exp $	*/
2 /*	$NetBSD: uvm_fault.c,v 1.51 2000/08/06 00:22:53 thorpej Exp $	*/
3 
4 /*
5  *
6  * Copyright (c) 1997 Charles D. Cranor and Washington University.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *      This product includes software developed by Charles D. Cranor and
20  *      Washington University.
21  * 4. The name of the author may not be used to endorse or promote products
22  *    derived from this software without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  *
35  * from: Id: uvm_fault.c,v 1.1.2.23 1998/02/06 05:29:05 chs Exp
36  */
37 
38 /*
39  * uvm_fault.c: fault handler
40  */
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/proc.h>
46 #include <sys/malloc.h>
47 #include <sys/mman.h>
48 #include <sys/user.h>
49 
50 #include <uvm/uvm.h>
51 
52 /*
53  *
54  * a word on page faults:
55  *
56  * types of page faults we handle:
57  *
58  * CASE 1: upper layer faults                   CASE 2: lower layer faults
59  *
60  *    CASE 1A         CASE 1B                  CASE 2A        CASE 2B
61  *    read/write1     write>1                  read/write   +-cow_write/zero
62  *         |             |                         |        |
63  *      +--|--+       +--|--+     +-----+       +  |  +     | +-----+
64  * amap |  V  |       |  ----------->new|          |        | |  ^  |
65  *      +-----+       +-----+     +-----+       +  |  +     | +--|--+
66  *                                                 |        |    |
67  *      +-----+       +-----+                   +--|--+     | +--|--+
68  * uobj | d/c |       | d/c |                   |  V  |     +----|  |
69  *      +-----+       +-----+                   +-----+       +-----+
70  *
71  * d/c = don't care
72  *
73  *   case [0]: layerless fault
74  *	no amap or uobj is present.   this is an error.
75  *
76  *   case [1]: upper layer fault [anon active]
77  *     1A: [read] or [write with anon->an_ref == 1]
78  *		I/O takes place in top level anon and uobj is not touched.
79  *     1B: [write with anon->an_ref > 1]
80  *		new anon is alloc'd and data is copied off ["COW"]
81  *
82  *   case [2]: lower layer fault [uobj]
83  *     2A: [read on non-NULL uobj] or [write to non-copy_on_write area]
84  *		I/O takes place directly in object.
85  *     2B: [write to copy_on_write] or [read on NULL uobj]
86  *		data is "promoted" from uobj to a new anon.
87  *		if uobj is null, then we zero fill.
88  *
89  * we follow the standard UVM locking protocol ordering:
90  *
91  * MAPS => AMAP => UOBJ => ANON => PAGE QUEUES (PQ)
92  * we hold a PG_BUSY page if we unlock for I/O
93  *
94  *
95  * the code is structured as follows:
96  *
97  *     - init the "IN" params in the ufi structure
98  *   ReFault:
99  *     - do lookups [locks maps], check protection, handle needs_copy
100  *     - check for case 0 fault (error)
101  *     - establish "range" of fault
102  *     - if we have an amap lock it and extract the anons
103  *     - if sequential advice deactivate pages behind us
104  *     - at the same time check pmap for unmapped areas and anon for pages
105  *	 that we could map in (and do map it if found)
106  *     - check object for resident pages that we could map in
107  *     - if (case 2) goto Case2
108  *     - >>> handle case 1
109  *           - ensure source anon is resident in RAM
110  *           - if case 1B alloc new anon and copy from source
111  *           - map the correct page in
112  *   Case2:
113  *     - >>> handle case 2
114  *           - ensure source page is resident (if uobj)
115  *           - if case 2B alloc new anon and copy from source (could be zero
116  *		fill if uobj == NULL)
117  *           - map the correct page in
118  *     - done!
119  *
120  * note on paging:
121  *   if we have to do I/O we place a PG_BUSY page in the correct object,
122  * unlock everything, and do the I/O.   when I/O is done we must reverify
123  * the state of the world before assuming that our data structures are
124  * valid.   [because mappings could change while the map is unlocked]
125  *
126  *  alternative 1: unbusy the page in question and restart the page fault
127  *    from the top (ReFault).   this is easy but does not take advantage
128  *    of the information that we already have from our previous lookup,
129  *    although it is possible that the "hints" in the vm_map will help here.
130  *
131  * alternative 2: the system already keeps track of a "version" number of
132  *    a map.   [i.e. every time you write-lock a map (e.g. to change a
133  *    mapping) you bump the version number up by one...]   so, we can save
134  *    the version number of the map before we release the lock and start I/O.
135  *    then when I/O is done we can relock and check the version numbers
136  *    to see if anything changed.    this might save us some over 1 because
137  *    we don't have to unbusy the page and may be less compares(?).
138  *
139  * alternative 3: put in backpointers or a way to "hold" part of a map
140  *    in place while I/O is in progress.   this could be complex to
141  *    implement (especially with structures like amap that can be referenced
142  *    by multiple map entries, and figuring out what should wait could be
143  *    complex as well...).
144  *
145  * given that we are not currently multiprocessor or multithreaded we might
146  * as well choose alternative 2 now.   maybe alternative 3 would be useful
147  * in the future.    XXX keep in mind for future consideration//rechecking.
148  */
149 
150 /*
151  * local data structures
152  */
153 
154 struct uvm_advice {
155 	int advice;
156 	int nback;
157 	int nforw;
158 };
159 
160 /*
161  * page range array:
162  * note: index in array must match "advice" value
163  * XXX: borrowed numbers from freebsd.   do they work well for us?
164  */
165 
166 static struct uvm_advice uvmadvice[] = {
167 	{ MADV_NORMAL, 3, 4 },
168 	{ MADV_RANDOM, 0, 0 },
169 	{ MADV_SEQUENTIAL, 8, 7},
170 };
171 
172 #define UVM_MAXRANGE 16	/* must be max() of nback+nforw+1 */
173 
174 /*
175  * private prototypes
176  */
177 
178 static void uvmfault_amapcopy(struct uvm_faultinfo *);
179 static __inline void uvmfault_anonflush(struct vm_anon **, int);
180 void	uvmfault_unlockmaps(struct uvm_faultinfo *, boolean_t);
181 
182 /*
183  * inline functions
184  */
185 
186 /*
187  * uvmfault_anonflush: try and deactivate pages in specified anons
188  *
189  * => does not have to deactivate page if it is busy
190  */
191 
192 static __inline void
193 uvmfault_anonflush(struct vm_anon **anons, int n)
194 {
195 	int lcv;
196 	struct vm_page *pg;
197 
198 	for (lcv = 0 ; lcv < n ; lcv++) {
199 		if (anons[lcv] == NULL)
200 			continue;
201 		simple_lock(&anons[lcv]->an_lock);
202 		pg = anons[lcv]->an_page;
203 		if (pg && (pg->pg_flags & PG_BUSY) == 0 && pg->loan_count == 0) {
204 			uvm_lock_pageq();
205 			if (pg->wire_count == 0) {
206 #ifdef UBC
207 				pmap_clear_reference(pg);
208 #else
209 				pmap_page_protect(pg, VM_PROT_NONE);
210 #endif
211 				uvm_pagedeactivate(pg);
212 			}
213 			uvm_unlock_pageq();
214 		}
215 		simple_unlock(&anons[lcv]->an_lock);
216 	}
217 }
218 
219 /*
220  * normal functions
221  */
222 
223 /*
224  * uvmfault_amapcopy: clear "needs_copy" in a map.
225  *
226  * => called with VM data structures unlocked (usually, see below)
227  * => we get a write lock on the maps and clear needs_copy for a VA
228  * => if we are out of RAM we sleep (waiting for more)
229  */
230 
231 static void
232 uvmfault_amapcopy(struct uvm_faultinfo *ufi)
233 {
234 
235 	/*
236 	 * while we haven't done the job
237 	 */
238 
239 	while (1) {
240 
241 		/*
242 		 * no mapping?  give up.
243 		 */
244 
245 		if (uvmfault_lookup(ufi, TRUE) == FALSE)
246 			return;
247 
248 		/*
249 		 * copy if needed.
250 		 */
251 
252 		if (UVM_ET_ISNEEDSCOPY(ufi->entry))
253 			amap_copy(ufi->map, ufi->entry, M_NOWAIT, TRUE,
254 				ufi->orig_rvaddr, ufi->orig_rvaddr + 1);
255 
256 		/*
257 		 * didn't work?  must be out of RAM.   unlock and sleep.
258 		 */
259 
260 		if (UVM_ET_ISNEEDSCOPY(ufi->entry)) {
261 			uvmfault_unlockmaps(ufi, TRUE);
262 			uvm_wait("fltamapcopy");
263 			continue;
264 		}
265 
266 		/*
267 		 * got it!   unlock and return.
268 		 */
269 
270 		uvmfault_unlockmaps(ufi, TRUE);
271 		return;
272 	}
273 	/*NOTREACHED*/
274 }
275 
276 /*
277  * uvmfault_anonget: get data in an anon into a non-busy, non-released
278  * page in that anon.
279  *
280  * => maps, amap, and anon locked by caller.
281  * => if we fail (result != VM_PAGER_OK) we unlock everything.
282  * => if we are successful, we return with everything still locked.
283  * => we don't move the page on the queues [gets moved later]
284  * => if we allocate a new page [we_own], it gets put on the queues.
285  *    either way, the result is that the page is on the queues at return time
286  * => for pages which are on loan from a uvm_object (and thus are not
287  *    owned by the anon): if successful, we return with the owning object
288  *    locked.   the caller must unlock this object when it unlocks everything
289  *    else.
290  */
291 
292 int
293 uvmfault_anonget(struct uvm_faultinfo *ufi, struct vm_amap *amap,
294     struct vm_anon *anon)
295 {
296 	boolean_t we_own;	/* we own anon's page? */
297 	boolean_t locked;	/* did we relock? */
298 	struct vm_page *pg;
299 	int result;
300 
301 	result = 0;		/* XXX shut up gcc */
302 	uvmexp.fltanget++;
303         /* bump rusage counters */
304 	if (anon->an_page)
305 		curproc->p_addr->u_stats.p_ru.ru_minflt++;
306 	else
307 		curproc->p_addr->u_stats.p_ru.ru_majflt++;
308 
309 	/*
310 	 * loop until we get it, or fail.
311 	 */
312 
313 	while (1) {
314 
315 		we_own = FALSE;		/* TRUE if we set PG_BUSY on a page */
316 		pg = anon->an_page;
317 
318 		/*
319 		 * if there is a resident page and it is loaned, then anon
320 		 * may not own it.   call out to uvm_anon_lockpage() to ensure
321 		 * the real owner of the page has been identified and locked.
322 		 */
323 
324 		if (pg && pg->loan_count)
325 			pg = uvm_anon_lockloanpg(anon);
326 
327 		/*
328 		 * page there?   make sure it is not busy/released.
329 		 */
330 
331 		if (pg) {
332 
333 			/*
334 			 * at this point, if the page has a uobject [meaning
335 			 * we have it on loan], then that uobject is locked
336 			 * by us!   if the page is busy, we drop all the
337 			 * locks (including uobject) and try again.
338 			 */
339 
340 			if ((pg->pg_flags & (PG_BUSY|PG_RELEASED)) == 0) {
341 				return (VM_PAGER_OK);
342 			}
343 			atomic_setbits_int(&pg->pg_flags, PG_WANTED);
344 			uvmexp.fltpgwait++;
345 
346 			/*
347 			 * the last unlock must be an atomic unlock+wait on
348 			 * the owner of page
349 			 */
350 			if (pg->uobject) {	/* owner is uobject ? */
351 				uvmfault_unlockall(ufi, amap, NULL, anon);
352 				UVM_UNLOCK_AND_WAIT(pg,
353 				    &pg->uobject->vmobjlock,
354 				    FALSE, "anonget1",0);
355 			} else {
356 				/* anon owns page */
357 				uvmfault_unlockall(ufi, amap, NULL, NULL);
358 				UVM_UNLOCK_AND_WAIT(pg,&anon->an_lock,0,
359 				    "anonget2",0);
360 			}
361 			/* ready to relock and try again */
362 
363 		} else {
364 
365 			/*
366 			 * no page, we must try and bring it in.
367 			 */
368 			pg = uvm_pagealloc(NULL, 0, anon, 0);
369 
370 			if (pg == NULL) {		/* out of RAM.  */
371 
372 				uvmfault_unlockall(ufi, amap, NULL, anon);
373 				uvmexp.fltnoram++;
374 				uvm_wait("flt_noram1");
375 				/* ready to relock and try again */
376 
377 			} else {
378 
379 				/* we set the PG_BUSY bit */
380 				we_own = TRUE;
381 				uvmfault_unlockall(ufi, amap, NULL, anon);
382 
383 				/*
384 				 * we are passing a PG_BUSY+PG_FAKE+PG_CLEAN
385 				 * page into the uvm_swap_get function with
386 				 * all data structures unlocked.  note that
387 				 * it is ok to read an_swslot here because
388 				 * we hold PG_BUSY on the page.
389 				 */
390 				uvmexp.pageins++;
391 				result = uvm_swap_get(pg, anon->an_swslot,
392 				    PGO_SYNCIO);
393 
394 				/*
395 				 * we clean up after the i/o below in the
396 				 * "we_own" case
397 				 */
398 				/* ready to relock and try again */
399 			}
400 		}
401 
402 		/*
403 		 * now relock and try again
404 		 */
405 
406 		locked = uvmfault_relock(ufi);
407 		if (locked || we_own)
408 			simple_lock(&anon->an_lock);
409 
410 		/*
411 		 * if we own the page (i.e. we set PG_BUSY), then we need
412 		 * to clean up after the I/O. there are three cases to
413 		 * consider:
414 		 *   [1] page released during I/O: free anon and ReFault.
415 		 *   [2] I/O not OK.   free the page and cause the fault
416 		 *       to fail.
417 		 *   [3] I/O OK!   activate the page and sync with the
418 		 *       non-we_own case (i.e. drop anon lock if not locked).
419 		 */
420 
421 		if (we_own) {
422 
423 			if (pg->pg_flags & PG_WANTED) {
424 				/* still holding object lock */
425 				wakeup(pg);
426 			}
427 			/* un-busy! */
428 			atomic_clearbits_int(&pg->pg_flags,
429 			    PG_WANTED|PG_BUSY|PG_FAKE);
430 			UVM_PAGE_OWN(pg, NULL);
431 
432 			/*
433 			 * if we were RELEASED during I/O, then our anon is
434 			 * no longer part of an amap.   we need to free the
435 			 * anon and try again.
436 			 */
437 			if (pg->pg_flags & PG_RELEASED) {
438 				pmap_page_protect(pg, VM_PROT_NONE);
439 				simple_unlock(&anon->an_lock);
440 				uvm_anfree(anon);	/* frees page for us */
441 				if (locked)
442 					uvmfault_unlockall(ufi, amap, NULL,
443 							   NULL);
444 				uvmexp.fltpgrele++;
445 				return (VM_PAGER_REFAULT);	/* refault! */
446 			}
447 
448 			if (result != VM_PAGER_OK) {
449 				KASSERT(result != VM_PAGER_PEND);
450 
451 				/* remove page from anon */
452 				anon->an_page = NULL;
453 
454 				/*
455 				 * remove the swap slot from the anon
456 				 * and mark the anon as having no real slot.
457 				 * don't free the swap slot, thus preventing
458 				 * it from being used again.
459 				 */
460 				uvm_swap_markbad(anon->an_swslot, 1);
461 				anon->an_swslot = SWSLOT_BAD;
462 
463 				/*
464 				 * note: page was never !PG_BUSY, so it
465 				 * can't be mapped and thus no need to
466 				 * pmap_page_protect it...
467 				 */
468 				uvm_lock_pageq();
469 				uvm_pagefree(pg);
470 				uvm_unlock_pageq();
471 
472 				if (locked)
473 					uvmfault_unlockall(ufi, amap, NULL,
474 					    anon);
475 				else
476 					simple_unlock(&anon->an_lock);
477 				return (VM_PAGER_ERROR);
478 			}
479 
480 			/*
481 			 * must be OK, clear modify (already PG_CLEAN)
482 			 * and activate
483 			 */
484 			pmap_clear_modify(pg);
485 			uvm_lock_pageq();
486 			uvm_pageactivate(pg);
487 			uvm_unlock_pageq();
488 			if (!locked)
489 				simple_unlock(&anon->an_lock);
490 		}
491 
492 		/*
493 		 * we were not able to relock.   restart fault.
494 		 */
495 
496 		if (!locked)
497 			return (VM_PAGER_REFAULT);
498 
499 		/*
500 		 * verify no one has touched the amap and moved the anon on us.
501 		 */
502 
503 		if (ufi != NULL &&
504 		    amap_lookup(&ufi->entry->aref,
505 				ufi->orig_rvaddr - ufi->entry->start) != anon) {
506 
507 			uvmfault_unlockall(ufi, amap, NULL, anon);
508 			return (VM_PAGER_REFAULT);
509 		}
510 
511 		/*
512 		 * try it again!
513 		 */
514 
515 		uvmexp.fltanretry++;
516 		continue;
517 
518 	} /* while (1) */
519 
520 	/*NOTREACHED*/
521 }
522 
523 /*
524  *   F A U L T   -   m a i n   e n t r y   p o i n t
525  */
526 
527 /*
528  * uvm_fault: page fault handler
529  *
530  * => called from MD code to resolve a page fault
531  * => VM data structures usually should be unlocked.   however, it is
532  *	possible to call here with the main map locked if the caller
533  *	gets a write lock, sets it recursive, and then calls us (c.f.
534  *	uvm_map_pageable).   this should be avoided because it keeps
535  *	the map locked off during I/O.
536  */
537 
538 #define MASK(entry)     (UVM_ET_ISCOPYONWRITE(entry) ? \
539 			 ~VM_PROT_WRITE : VM_PROT_ALL)
540 
541 int
542 uvm_fault(vm_map_t orig_map, vaddr_t vaddr, vm_fault_t fault_type,
543     vm_prot_t access_type)
544 {
545 	struct uvm_faultinfo ufi;
546 	vm_prot_t enter_prot;
547 	boolean_t wired, narrow, promote, locked, shadowed;
548 	int npages, nback, nforw, centeridx, result, lcv, gotpages;
549 	vaddr_t startva, currva;
550 	voff_t uoff;
551 	paddr_t pa;
552 	struct vm_amap *amap;
553 	struct uvm_object *uobj;
554 	struct vm_anon *anons_store[UVM_MAXRANGE], **anons, *anon, *oanon;
555 	struct vm_page *pages[UVM_MAXRANGE], *pg, *uobjpage;
556 
557 	anon = NULL;
558 	pg = NULL;
559 
560 	uvmexp.faults++;	/* XXX: locking? */
561 
562 	/*
563 	 * init the IN parameters in the ufi
564 	 */
565 
566 	ufi.orig_map = orig_map;
567 	ufi.orig_rvaddr = trunc_page(vaddr);
568 	ufi.orig_size = PAGE_SIZE;	/* can't get any smaller than this */
569 	if (fault_type == VM_FAULT_WIRE)
570 		narrow = TRUE;		/* don't look for neighborhood
571 					 * pages on wire */
572 	else
573 		narrow = FALSE;		/* normal fault */
574 
575 	/*
576 	 * "goto ReFault" means restart the page fault from ground zero.
577 	 */
578 ReFault:
579 
580 	/*
581 	 * lookup and lock the maps
582 	 */
583 
584 	if (uvmfault_lookup(&ufi, FALSE) == FALSE) {
585 		return (EFAULT);
586 	}
587 	/* locked: maps(read) */
588 
589 #ifdef DIAGNOSTIC
590 	if ((ufi.map->flags & VM_MAP_PAGEABLE) == 0)
591 		panic("uvm_fault: fault on non-pageable map (%p, 0x%lx)",
592 		    ufi.map, vaddr);
593 #endif
594 
595 	/*
596 	 * check protection
597 	 */
598 
599 	if ((ufi.entry->protection & access_type) != access_type) {
600 		uvmfault_unlockmaps(&ufi, FALSE);
601 		return (EACCES);
602 	}
603 
604 	/*
605 	 * "enter_prot" is the protection we want to enter the page in at.
606 	 * for certain pages (e.g. copy-on-write pages) this protection can
607 	 * be more strict than ufi.entry->protection.  "wired" means either
608 	 * the entry is wired or we are fault-wiring the pg.
609 	 */
610 
611 	enter_prot = ufi.entry->protection;
612 	wired = VM_MAPENT_ISWIRED(ufi.entry) || (fault_type == VM_FAULT_WIRE);
613 	if (wired)
614 		access_type = enter_prot; /* full access for wired */
615 
616 	/*
617 	 * handle "needs_copy" case.   if we need to copy the amap we will
618 	 * have to drop our readlock and relock it with a write lock.  (we
619 	 * need a write lock to change anything in a map entry [e.g.
620 	 * needs_copy]).
621 	 */
622 
623 	if (UVM_ET_ISNEEDSCOPY(ufi.entry)) {
624 		if ((access_type & VM_PROT_WRITE) ||
625 		    (ufi.entry->object.uvm_obj == NULL)) {
626 			/* need to clear */
627 			uvmfault_unlockmaps(&ufi, FALSE);
628 			uvmfault_amapcopy(&ufi);
629 			uvmexp.fltamcopy++;
630 			goto ReFault;
631 
632 		} else {
633 
634 			/*
635 			 * ensure that we pmap_enter page R/O since
636 			 * needs_copy is still true
637 			 */
638 			enter_prot &= ~VM_PROT_WRITE;
639 
640 		}
641 	}
642 
643 	/*
644 	 * identify the players
645 	 */
646 
647 	amap = ufi.entry->aref.ar_amap;		/* top layer */
648 	uobj = ufi.entry->object.uvm_obj;	/* bottom layer */
649 
650 	/*
651 	 * check for a case 0 fault.  if nothing backing the entry then
652 	 * error now.
653 	 */
654 
655 	if (amap == NULL && uobj == NULL) {
656 		uvmfault_unlockmaps(&ufi, FALSE);
657 		return (EFAULT);
658 	}
659 
660 	/*
661 	 * establish range of interest based on advice from mapper
662 	 * and then clip to fit map entry.   note that we only want
663 	 * to do this the first time through the fault.   if we
664 	 * ReFault we will disable this by setting "narrow" to true.
665 	 */
666 
667 	if (narrow == FALSE) {
668 
669 		/* wide fault (!narrow) */
670 		KASSERT(uvmadvice[ufi.entry->advice].advice ==
671 			 ufi.entry->advice);
672 		nback = min(uvmadvice[ufi.entry->advice].nback,
673 			    (ufi.orig_rvaddr - ufi.entry->start) >> PAGE_SHIFT);
674 		startva = ufi.orig_rvaddr - (nback << PAGE_SHIFT);
675 		nforw = min(uvmadvice[ufi.entry->advice].nforw,
676 			    ((ufi.entry->end - ufi.orig_rvaddr) >>
677 			     PAGE_SHIFT) - 1);
678 		/*
679 		 * note: "-1" because we don't want to count the
680 		 * faulting page as forw
681 		 */
682 		npages = nback + nforw + 1;
683 		centeridx = nback;
684 
685 		narrow = TRUE;	/* ensure only once per-fault */
686 
687 	} else {
688 
689 		/* narrow fault! */
690 		nback = nforw = 0;
691 		startva = ufi.orig_rvaddr;
692 		npages = 1;
693 		centeridx = 0;
694 
695 	}
696 
697 	/* locked: maps(read) */
698 
699 	/*
700 	 * if we've got an amap, lock it and extract current anons.
701 	 */
702 
703 	if (amap) {
704 		anons = anons_store;
705 		amap_lookups(&ufi.entry->aref, startva - ufi.entry->start,
706 		    anons, npages);
707 	} else {
708 		anons = NULL;	/* to be safe */
709 	}
710 
711 	/* locked: maps(read), amap(if there) */
712 
713 	/*
714 	 * for MADV_SEQUENTIAL mappings we want to deactivate the back pages
715 	 * now and then forget about them (for the rest of the fault).
716 	 */
717 
718 	if (ufi.entry->advice == MADV_SEQUENTIAL && nback != 0) {
719 
720 		/* flush back-page anons? */
721 		if (amap)
722 			uvmfault_anonflush(anons, nback);
723 
724 		/* flush object? */
725 		if (uobj) {
726 			uoff = (startva - ufi.entry->start) + ufi.entry->offset;
727 			simple_lock(&uobj->vmobjlock);
728 			(void) uobj->pgops->pgo_flush(uobj, uoff, uoff +
729 				    (nback << PAGE_SHIFT), PGO_DEACTIVATE);
730 			simple_unlock(&uobj->vmobjlock);
731 		}
732 
733 		/* now forget about the backpages */
734 		if (amap)
735 			anons += nback;
736 		startva += (nback << PAGE_SHIFT);
737 		npages -= nback;
738 		centeridx = 0;
739 	}
740 
741 	/* locked: maps(read), amap(if there) */
742 
743 	/*
744 	 * map in the backpages and frontpages we found in the amap in hopes
745 	 * of preventing future faults.    we also init the pages[] array as
746 	 * we go.
747 	 */
748 
749 	currva = startva;
750 	shadowed = FALSE;
751 	for (lcv = 0 ; lcv < npages ; lcv++, currva += PAGE_SIZE) {
752 
753 		/*
754 		 * dont play with VAs that are already mapped
755 		 * except for center)
756 		 */
757 		if (lcv != centeridx &&
758 		    pmap_extract(ufi.orig_map->pmap, currva, &pa)) {
759 			pages[lcv] = PGO_DONTCARE;
760 			continue;
761 		}
762 
763 		/*
764 		 * unmapped or center page.   check if any anon at this level.
765 		 */
766 		if (amap == NULL || anons[lcv] == NULL) {
767 			pages[lcv] = NULL;
768 			continue;
769 		}
770 
771 		/*
772 		 * check for present page and map if possible.   re-activate it.
773 		 */
774 
775 		pages[lcv] = PGO_DONTCARE;
776 		if (lcv == centeridx) {		/* save center for later! */
777 			shadowed = TRUE;
778 			continue;
779 		}
780 		anon = anons[lcv];
781 		simple_lock(&anon->an_lock);
782 		/* ignore loaned pages */
783 		if (anon->an_page && anon->an_page->loan_count == 0 &&
784 		    (anon->an_page->pg_flags & (PG_RELEASED|PG_BUSY)) == 0) {
785 			uvm_lock_pageq();
786 			uvm_pageactivate(anon->an_page);	/* reactivate */
787 			uvm_unlock_pageq();
788 			uvmexp.fltnamap++;
789 
790 			/*
791 			 * Since this isn't the page that's actually faulting,
792 			 * ignore pmap_enter() failures; it's not critical
793 			 * that we enter these right now.
794 			 */
795 
796 			(void) pmap_enter(ufi.orig_map->pmap, currva,
797 			    VM_PAGE_TO_PHYS(anon->an_page),
798 			    (anon->an_ref > 1) ? (enter_prot & ~VM_PROT_WRITE) :
799 			    enter_prot,
800 			    PMAP_CANFAIL |
801 			     (VM_MAPENT_ISWIRED(ufi.entry) ? PMAP_WIRED : 0));
802 		}
803 		simple_unlock(&anon->an_lock);
804 		pmap_update(ufi.orig_map->pmap);
805 	}
806 
807 	/* locked: maps(read), amap(if there) */
808 	/* (shadowed == TRUE) if there is an anon at the faulting address */
809 
810 	/*
811 	 * note that if we are really short of RAM we could sleep in the above
812 	 * call to pmap_enter with everything locked.   bad?
813 	 *
814 	 * XXX Actually, that is bad; pmap_enter() should just fail in that
815 	 * XXX case.  --thorpej
816 	 */
817 
818 	/*
819 	 * if the desired page is not shadowed by the amap and we have a
820 	 * backing object, then we check to see if the backing object would
821 	 * prefer to handle the fault itself (rather than letting us do it
822 	 * with the usual pgo_get hook).  the backing object signals this by
823 	 * providing a pgo_fault routine.
824 	 */
825 
826 	if (uobj && shadowed == FALSE && uobj->pgops->pgo_fault != NULL) {
827 		simple_lock(&uobj->vmobjlock);
828 
829 		/* locked: maps(read), amap (if there), uobj */
830 		result = uobj->pgops->pgo_fault(&ufi, startva, pages, npages,
831 				    centeridx, fault_type, access_type,
832 				    PGO_LOCKED);
833 
834 		/* locked: nothing, pgo_fault has unlocked everything */
835 
836 		if (result == VM_PAGER_OK)
837 			return (0);		/* pgo_fault did pmap enter */
838 		else if (result == VM_PAGER_REFAULT)
839 			goto ReFault;		/* try again! */
840 		else
841 			return (EACCES);
842 	}
843 
844 	/*
845 	 * now, if the desired page is not shadowed by the amap and we have
846 	 * a backing object that does not have a special fault routine, then
847 	 * we ask (with pgo_get) the object for resident pages that we care
848 	 * about and attempt to map them in.  we do not let pgo_get block
849 	 * (PGO_LOCKED).
850 	 *
851 	 * ("get" has the option of doing a pmap_enter for us)
852 	 */
853 
854 	if (uobj && shadowed == FALSE) {
855 		simple_lock(&uobj->vmobjlock);
856 
857 		/* locked (!shadowed): maps(read), amap (if there), uobj */
858 		/*
859 		 * the following call to pgo_get does _not_ change locking state
860 		 */
861 
862 		uvmexp.fltlget++;
863 		gotpages = npages;
864 		(void) uobj->pgops->pgo_get(uobj, ufi.entry->offset +
865 				(startva - ufi.entry->start),
866 				pages, &gotpages, centeridx,
867 				access_type & MASK(ufi.entry),
868 				ufi.entry->advice, PGO_LOCKED);
869 
870 		/*
871 		 * check for pages to map, if we got any
872 		 */
873 
874 		uobjpage = NULL;
875 
876 		if (gotpages) {
877 			currva = startva;
878 			for (lcv = 0 ; lcv < npages ;
879 			    lcv++, currva += PAGE_SIZE) {
880 
881 				if (pages[lcv] == NULL ||
882 				    pages[lcv] == PGO_DONTCARE)
883 					continue;
884 
885 				KASSERT((pages[lcv]->pg_flags & PG_RELEASED) == 0);
886 
887 				/*
888 				 * if center page is resident and not
889 				 * PG_BUSY, then pgo_get made it PG_BUSY
890 				 * for us and gave us a handle to it.
891 				 * remember this page as "uobjpage."
892 				 * (for later use).
893 				 */
894 
895 				if (lcv == centeridx) {
896 					uobjpage = pages[lcv];
897 					continue;
898 				}
899 
900 				/*
901 				 * note: calling pgo_get with locked data
902 				 * structures returns us pages which are
903 				 * neither busy nor released, so we don't
904 				 * need to check for this.   we can just
905 				 * directly enter the page (after moving it
906 				 * to the head of the active queue [useful?]).
907 				 */
908 
909 				uvm_lock_pageq();
910 				uvm_pageactivate(pages[lcv]);	/* reactivate */
911 				uvm_unlock_pageq();
912 				uvmexp.fltnomap++;
913 
914 				/*
915 				 * Since this page isn't the page that's
916 				 * actually fauling, ignore pmap_enter()
917 				 * failures; it's not critical that we
918 				 * enter these right now.
919 				 */
920 
921 				(void) pmap_enter(ufi.orig_map->pmap, currva,
922 				    VM_PAGE_TO_PHYS(pages[lcv]),
923 				    enter_prot & MASK(ufi.entry),
924 				    PMAP_CANFAIL |
925 				     (wired ? PMAP_WIRED : 0));
926 
927 				/*
928 				 * NOTE: page can't be PG_WANTED because
929 				 * we've held the lock the whole time
930 				 * we've had the handle.
931 				 */
932 
933 				atomic_clearbits_int(&pages[lcv]->pg_flags,
934 				    PG_BUSY);
935 				UVM_PAGE_OWN(pages[lcv], NULL);
936 			}	/* for "lcv" loop */
937 			pmap_update(ufi.orig_map->pmap);
938 		}   /* "gotpages" != 0 */
939 		/* note: object still _locked_ */
940 	} else {
941 		uobjpage = NULL;
942 	}
943 
944 	/* locked (shadowed): maps(read), amap */
945 	/* locked (!shadowed): maps(read), amap(if there),
946 		 uobj(if !null), uobjpage(if !null) */
947 
948 	/*
949 	 * note that at this point we are done with any front or back pages.
950 	 * we are now going to focus on the center page (i.e. the one we've
951 	 * faulted on).  if we have faulted on the top (anon) layer
952 	 * [i.e. case 1], then the anon we want is anons[centeridx] (we have
953 	 * not touched it yet).  if we have faulted on the bottom (uobj)
954 	 * layer [i.e. case 2] and the page was both present and available,
955 	 * then we've got a pointer to it as "uobjpage" and we've already
956 	 * made it BUSY.
957 	 */
958 
959 	/*
960 	 * there are four possible cases we must address: 1A, 1B, 2A, and 2B
961 	 */
962 
963 	/*
964 	 * redirect case 2: if we are not shadowed, go to case 2.
965 	 */
966 
967 	if (shadowed == FALSE)
968 		goto Case2;
969 
970 	/* locked: maps(read), amap */
971 
972 	/*
973 	 * handle case 1: fault on an anon in our amap
974 	 */
975 
976 	anon = anons[centeridx];
977 	simple_lock(&anon->an_lock);
978 
979 	/* locked: maps(read), amap, anon */
980 
981 	/*
982 	 * no matter if we have case 1A or case 1B we are going to need to
983 	 * have the anon's memory resident.   ensure that now.
984 	 */
985 
986 	/*
987 	 * let uvmfault_anonget do the dirty work.
988 	 * if it fails (!OK) it will unlock everything for us.
989 	 * if it succeeds, locks are still valid and locked.
990 	 * also, if it is OK, then the anon's page is on the queues.
991 	 * if the page is on loan from a uvm_object, then anonget will
992 	 * lock that object for us if it does not fail.
993 	 */
994 
995 	result = uvmfault_anonget(&ufi, amap, anon);
996 	switch (result) {
997 	case VM_PAGER_OK:
998 		break;
999 
1000 	case VM_PAGER_REFAULT:
1001 		goto ReFault;
1002 
1003 	case VM_PAGER_ERROR:
1004 		/*
1005 		 * An error occured while trying to bring in the
1006 		 * page -- this is the only error we return right
1007 		 * now.
1008 		 */
1009 		return (EACCES);	/* XXX */
1010 
1011 	default:
1012 #ifdef DIAGNOSTIC
1013 		panic("uvm_fault: uvmfault_anonget -> %d", result);
1014 #else
1015 		return (EACCES);
1016 #endif
1017 	}
1018 
1019 	/*
1020 	 * uobj is non null if the page is on loan from an object (i.e. uobj)
1021 	 */
1022 
1023 	uobj = anon->an_page->uobject;	/* locked by anonget if !NULL */
1024 
1025 	/* locked: maps(read), amap, anon, uobj(if one) */
1026 
1027 	/*
1028 	 * special handling for loaned pages
1029 	 */
1030 
1031 	if (anon->an_page->loan_count) {
1032 
1033 		if ((access_type & VM_PROT_WRITE) == 0) {
1034 
1035 			/*
1036 			 * for read faults on loaned pages we just cap the
1037 			 * protection at read-only.
1038 			 */
1039 
1040 			enter_prot = enter_prot & ~VM_PROT_WRITE;
1041 
1042 		} else {
1043 			/*
1044 			 * note that we can't allow writes into a loaned page!
1045 			 *
1046 			 * if we have a write fault on a loaned page in an
1047 			 * anon then we need to look at the anon's ref count.
1048 			 * if it is greater than one then we are going to do
1049 			 * a normal copy-on-write fault into a new anon (this
1050 			 * is not a problem).  however, if the reference count
1051 			 * is one (a case where we would normally allow a
1052 			 * write directly to the page) then we need to kill
1053 			 * the loan before we continue.
1054 			 */
1055 
1056 			/* >1 case is already ok */
1057 			if (anon->an_ref == 1) {
1058 
1059 				/* get new un-owned replacement page */
1060 				pg = uvm_pagealloc(NULL, 0, NULL, 0);
1061 				if (pg == NULL) {
1062 					uvmfault_unlockall(&ufi, amap, uobj,
1063 					    anon);
1064 					uvm_wait("flt_noram2");
1065 					goto ReFault;
1066 				}
1067 
1068 				/*
1069 				 * copy data, kill loan, and drop uobj lock
1070 				 * (if any)
1071 				 */
1072 				/* copy old -> new */
1073 				uvm_pagecopy(anon->an_page, pg);
1074 
1075 				/* force reload */
1076 				pmap_page_protect(anon->an_page,
1077 						  VM_PROT_NONE);
1078 				uvm_lock_pageq();	  /* KILL loan */
1079 				if (uobj)
1080 					/* if we were loaning */
1081 					anon->an_page->loan_count--;
1082 				anon->an_page->uanon = NULL;
1083 				/* in case we owned */
1084 				atomic_clearbits_int(
1085 				    &anon->an_page->pg_flags, PQ_ANON);
1086 				uvm_pageactivate(pg);
1087 				uvm_unlock_pageq();
1088 				if (uobj) {
1089 					simple_unlock(&uobj->vmobjlock);
1090 					uobj = NULL;
1091 				}
1092 
1093 				/* install new page in anon */
1094 				anon->an_page = pg;
1095 				pg->uanon = anon;
1096 				atomic_setbits_int(&pg->pg_flags, PQ_ANON);
1097 				atomic_clearbits_int(&pg->pg_flags,
1098 				    PG_BUSY|PG_FAKE);
1099 				UVM_PAGE_OWN(pg, NULL);
1100 
1101 				/* done! */
1102 			}     /* ref == 1 */
1103 		}       /* write fault */
1104 	}         /* loan count */
1105 
1106 	/*
1107 	 * if we are case 1B then we will need to allocate a new blank
1108 	 * anon to transfer the data into.   note that we have a lock
1109 	 * on anon, so no one can busy or release the page until we are done.
1110 	 * also note that the ref count can't drop to zero here because
1111 	 * it is > 1 and we are only dropping one ref.
1112 	 *
1113 	 * in the (hopefully very rare) case that we are out of RAM we
1114 	 * will unlock, wait for more RAM, and refault.
1115 	 *
1116 	 * if we are out of anon VM we kill the process (XXX: could wait?).
1117 	 */
1118 
1119 	if ((access_type & VM_PROT_WRITE) != 0 && anon->an_ref > 1) {
1120 		uvmexp.flt_acow++;
1121 		oanon = anon;		/* oanon = old, locked anon */
1122 		anon = uvm_analloc();
1123 		if (anon) {
1124 			pg = uvm_pagealloc(NULL, 0, anon, 0);
1125 		}
1126 
1127 		/* check for out of RAM */
1128 		if (anon == NULL || pg == NULL) {
1129 			if (anon)
1130 				uvm_anfree(anon);
1131 			uvmfault_unlockall(&ufi, amap, uobj, oanon);
1132 			KASSERT(uvmexp.swpgonly <= uvmexp.swpages);
1133 			if (anon == NULL || uvmexp.swpgonly == uvmexp.swpages) {
1134 				uvmexp.fltnoanon++;
1135 				return (ENOMEM);
1136 			}
1137 
1138 			uvmexp.fltnoram++;
1139 			uvm_wait("flt_noram3");	/* out of RAM, wait for more */
1140 			goto ReFault;
1141 		}
1142 
1143 		/* got all resources, replace anon with nanon */
1144 
1145 		uvm_pagecopy(oanon->an_page, pg);	/* pg now !PG_CLEAN */
1146 		/* un-busy! new page */
1147 		atomic_clearbits_int(&pg->pg_flags, PG_BUSY|PG_FAKE);
1148 		UVM_PAGE_OWN(pg, NULL);
1149 		amap_add(&ufi.entry->aref, ufi.orig_rvaddr - ufi.entry->start,
1150 		    anon, 1);
1151 
1152 		/* deref: can not drop to zero here by defn! */
1153 		oanon->an_ref--;
1154 
1155 		/*
1156 		 * note: oanon still locked.   anon is _not_ locked, but we
1157 		 * have the sole references to in from amap which _is_ locked.
1158 		 * thus, no one can get at it until we are done with it.
1159 		 */
1160 
1161 	} else {
1162 
1163 		uvmexp.flt_anon++;
1164 		oanon = anon;		/* old, locked anon is same as anon */
1165 		pg = anon->an_page;
1166 		if (anon->an_ref > 1)     /* disallow writes to ref > 1 anons */
1167 			enter_prot = enter_prot & ~VM_PROT_WRITE;
1168 
1169 	}
1170 
1171 	/* locked: maps(read), amap, oanon */
1172 
1173 	/*
1174 	 * now map the page in ...
1175 	 * XXX: old fault unlocks object before pmap_enter.  this seems
1176 	 * suspect since some other thread could blast the page out from
1177 	 * under us between the unlock and the pmap_enter.
1178 	 */
1179 
1180 	if (pmap_enter(ufi.orig_map->pmap, ufi.orig_rvaddr, VM_PAGE_TO_PHYS(pg),
1181 	    enter_prot, access_type | PMAP_CANFAIL | (wired ? PMAP_WIRED : 0))
1182 	    != 0) {
1183 		/*
1184 		 * No need to undo what we did; we can simply think of
1185 		 * this as the pmap throwing away the mapping information.
1186 		 *
1187 		 * We do, however, have to go through the ReFault path,
1188 		 * as the map may change while we're asleep.
1189 		 */
1190 		uvmfault_unlockall(&ufi, amap, uobj, oanon);
1191 		KASSERT(uvmexp.swpgonly <= uvmexp.swpages);
1192 		if (uvmexp.swpgonly == uvmexp.swpages) {
1193 			/* XXX instrumentation */
1194 			return (ENOMEM);
1195 		}
1196 		/* XXX instrumentation */
1197 		uvm_wait("flt_pmfail1");
1198 		goto ReFault;
1199 	}
1200 
1201 	/*
1202 	 * ... update the page queues.
1203 	 */
1204 
1205 	uvm_lock_pageq();
1206 
1207 	if (fault_type == VM_FAULT_WIRE) {
1208 		uvm_pagewire(pg);
1209 
1210 		/*
1211 		 * since the now-wired page cannot be paged out,
1212 		 * release its swap resources for others to use.
1213 		 * since an anon with no swap cannot be PG_CLEAN,
1214 		 * clear its clean flag now.
1215 		 */
1216 		atomic_clearbits_int(&pg->pg_flags, PG_CLEAN);
1217 		uvm_anon_dropswap(anon);
1218 	} else {
1219 		/* activate it */
1220 		uvm_pageactivate(pg);
1221 	}
1222 
1223 	uvm_unlock_pageq();
1224 
1225 	/*
1226 	 * done case 1!  finish up by unlocking everything and returning success
1227 	 */
1228 
1229 	uvmfault_unlockall(&ufi, amap, uobj, oanon);
1230 	pmap_update(ufi.orig_map->pmap);
1231 	return (0);
1232 
1233 
1234 Case2:
1235 	/*
1236 	 * handle case 2: faulting on backing object or zero fill
1237 	 */
1238 
1239 	/*
1240 	 * locked:
1241 	 * maps(read), amap(if there), uobj(if !null), uobjpage(if !null)
1242 	 */
1243 
1244 	/*
1245 	 * note that uobjpage can not be PGO_DONTCARE at this point.  we now
1246 	 * set uobjpage to PGO_DONTCARE if we are doing a zero fill.  if we
1247 	 * have a backing object, check and see if we are going to promote
1248 	 * the data up to an anon during the fault.
1249 	 */
1250 
1251 	if (uobj == NULL) {
1252 		uobjpage = PGO_DONTCARE;
1253 		promote = TRUE;		/* always need anon here */
1254 	} else {
1255 		KASSERT(uobjpage != PGO_DONTCARE);
1256 		promote = (access_type & VM_PROT_WRITE) &&
1257 		     UVM_ET_ISCOPYONWRITE(ufi.entry);
1258 	}
1259 
1260 	/*
1261 	 * if uobjpage is not null then we do not need to do I/O to get the
1262 	 * uobjpage.
1263 	 *
1264 	 * if uobjpage is null, then we need to unlock and ask the pager to
1265 	 * get the data for us.   once we have the data, we need to reverify
1266 	 * the state the world.   we are currently not holding any resources.
1267 	 */
1268 
1269 	if (uobjpage) {
1270 		/* update rusage counters */
1271 		curproc->p_addr->u_stats.p_ru.ru_minflt++;
1272 	} else {
1273 		/* update rusage counters */
1274 		curproc->p_addr->u_stats.p_ru.ru_majflt++;
1275 
1276 		/* locked: maps(read), amap(if there), uobj */
1277 		uvmfault_unlockall(&ufi, amap, NULL, NULL);
1278 		/* locked: uobj */
1279 
1280 		uvmexp.fltget++;
1281 		gotpages = 1;
1282 		uoff = (ufi.orig_rvaddr - ufi.entry->start) + ufi.entry->offset;
1283 		result = uobj->pgops->pgo_get(uobj, uoff, &uobjpage, &gotpages,
1284 		    0, access_type & MASK(ufi.entry), ufi.entry->advice,
1285 		    PGO_SYNCIO);
1286 
1287 		/* locked: uobjpage(if result OK) */
1288 
1289 		/*
1290 		 * recover from I/O
1291 		 */
1292 
1293 		if (result != VM_PAGER_OK) {
1294 			KASSERT(result != VM_PAGER_PEND);
1295 
1296 			if (result == VM_PAGER_AGAIN) {
1297 				tsleep((caddr_t)&lbolt, PVM, "fltagain2", 0);
1298 				goto ReFault;
1299 			}
1300 
1301 			return (EACCES); /* XXX i/o error */
1302 		}
1303 
1304 		/* locked: uobjpage */
1305 
1306 		/*
1307 		 * re-verify the state of the world by first trying to relock
1308 		 * the maps.  always relock the object.
1309 		 */
1310 
1311 		locked = uvmfault_relock(&ufi);
1312 		simple_lock(&uobj->vmobjlock);
1313 
1314 		/* locked(locked): maps(read), amap(if !null), uobj, uobjpage */
1315 		/* locked(!locked): uobj, uobjpage */
1316 
1317 		/*
1318 		 * Re-verify that amap slot is still free. if there is
1319 		 * a problem, we unlock and clean up.
1320 		 */
1321 
1322 		if (locked && amap && amap_lookup(&ufi.entry->aref,
1323 		      ufi.orig_rvaddr - ufi.entry->start)) {
1324 			if (locked)
1325 				uvmfault_unlockall(&ufi, amap, NULL, NULL);
1326 			locked = FALSE;
1327 		}
1328 
1329 		/*
1330 		 * didn't get the lock?   release the page and retry.
1331 		 */
1332 
1333 		if (locked == FALSE) {
1334 			if (uobjpage->pg_flags & PG_WANTED)
1335 				/* still holding object lock */
1336 				wakeup(uobjpage);
1337 
1338 			uvm_lock_pageq();
1339 			/* make sure it is in queues */
1340 			uvm_pageactivate(uobjpage);
1341 
1342 			uvm_unlock_pageq();
1343 			atomic_clearbits_int(&uobjpage->pg_flags,
1344 			    PG_BUSY|PG_WANTED);
1345 			UVM_PAGE_OWN(uobjpage, NULL);
1346 			simple_unlock(&uobj->vmobjlock);
1347 			goto ReFault;
1348 
1349 		}
1350 
1351 		/*
1352 		 * we have the data in uobjpage which is PG_BUSY and we are
1353 		 * holding object lock.
1354 		 */
1355 
1356 		/* locked: maps(read), amap(if !null), uobj, uobjpage */
1357 	}
1358 
1359 	/*
1360 	 * locked:
1361 	 * maps(read), amap(if !null), uobj(if !null), uobjpage(if uobj)
1362 	 */
1363 
1364 	/*
1365 	 * notes:
1366 	 *  - at this point uobjpage can not be NULL
1367 	 *  - at this point uobjpage could be PG_WANTED (handle later)
1368 	 */
1369 
1370 	if (promote == FALSE) {
1371 
1372 		/*
1373 		 * we are not promoting.   if the mapping is COW ensure that we
1374 		 * don't give more access than we should (e.g. when doing a read
1375 		 * fault on a COPYONWRITE mapping we want to map the COW page in
1376 		 * R/O even though the entry protection could be R/W).
1377 		 *
1378 		 * set "pg" to the page we want to map in (uobjpage, usually)
1379 		 */
1380 
1381 		uvmexp.flt_obj++;
1382 		if (UVM_ET_ISCOPYONWRITE(ufi.entry))
1383 			enter_prot &= ~VM_PROT_WRITE;
1384 		pg = uobjpage;		/* map in the actual object */
1385 
1386 		/* assert(uobjpage != PGO_DONTCARE) */
1387 
1388 		/*
1389 		 * we are faulting directly on the page.   be careful
1390 		 * about writing to loaned pages...
1391 		 */
1392 		if (uobjpage->loan_count) {
1393 
1394 			if ((access_type & VM_PROT_WRITE) == 0) {
1395 				/* read fault: cap the protection at readonly */
1396 				/* cap! */
1397 				enter_prot = enter_prot & ~VM_PROT_WRITE;
1398 			} else {
1399 				/* write fault: must break the loan here */
1400 
1401 				/* alloc new un-owned page */
1402 				pg = uvm_pagealloc(NULL, 0, NULL, 0);
1403 
1404 				if (pg == NULL) {
1405 					/*
1406 					 * drop ownership of page, it can't
1407 					 * be released
1408 					 */
1409 					if (uobjpage->pg_flags & PG_WANTED)
1410 						wakeup(uobjpage);
1411 					atomic_clearbits_int(
1412 					    &uobjpage->pg_flags,
1413 					    PG_BUSY|PG_WANTED);
1414 					UVM_PAGE_OWN(uobjpage, NULL);
1415 
1416 					uvm_lock_pageq();
1417 					/* activate: we will need it later */
1418 					uvm_pageactivate(uobjpage);
1419 
1420 					uvm_unlock_pageq();
1421 					uvmfault_unlockall(&ufi, amap, uobj,
1422 					  NULL);
1423 					uvmexp.fltnoram++;
1424 					uvm_wait("flt_noram4");
1425 					goto ReFault;
1426 				}
1427 
1428 				/*
1429 				 * copy the data from the old page to the new
1430 				 * one and clear the fake/clean flags on the
1431 				 * new page (keep it busy).  force a reload
1432 				 * of the old page by clearing it from all
1433 				 * pmaps.  then lock the page queues to
1434 				 * rename the pages.
1435 				 */
1436 				uvm_pagecopy(uobjpage, pg);	/* old -> new */
1437 				atomic_clearbits_int(&pg->pg_flags,
1438 				    PG_FAKE|PG_CLEAN);
1439 				pmap_page_protect(uobjpage, VM_PROT_NONE);
1440 				if (uobjpage->pg_flags & PG_WANTED)
1441 					wakeup(uobjpage);
1442 				/* uobj still locked */
1443 				atomic_clearbits_int(&uobjpage->pg_flags,
1444 				    PG_BUSY|PG_WANTED);
1445 				UVM_PAGE_OWN(uobjpage, NULL);
1446 
1447 				uvm_lock_pageq();
1448 				uoff = uobjpage->offset;
1449 				/* remove old page */
1450 				uvm_pagerealloc(uobjpage, NULL, 0);
1451 
1452 				/*
1453 				 * at this point we have absolutely no
1454 				 * control over uobjpage
1455 				 */
1456 				/* install new page */
1457 				uvm_pagerealloc(pg, uobj, uoff);
1458 				uvm_unlock_pageq();
1459 
1460 				/*
1461 				 * done!  loan is broken and "pg" is
1462 				 * PG_BUSY.   it can now replace uobjpage.
1463 				 */
1464 
1465 				uobjpage = pg;
1466 
1467 			}		/* write fault case */
1468 		}		/* if loan_count */
1469 
1470 	} else {
1471 
1472 		/*
1473 		 * if we are going to promote the data to an anon we
1474 		 * allocate a blank anon here and plug it into our amap.
1475 		 */
1476 #ifdef DIAGNOSTIC
1477 		if (amap == NULL)
1478 			panic("uvm_fault: want to promote data, but no anon");
1479 #endif
1480 
1481 		anon = uvm_analloc();
1482 		if (anon) {
1483 			/*
1484 			 * In `Fill in data...' below, if
1485 			 * uobjpage == PGO_DONTCARE, we want
1486 			 * a zero'd, dirty page, so have
1487 			 * uvm_pagealloc() do that for us.
1488 			 */
1489 			pg = uvm_pagealloc(NULL, 0, anon,
1490 			    (uobjpage == PGO_DONTCARE) ? UVM_PGA_ZERO : 0);
1491 		}
1492 
1493 		/*
1494 		 * out of memory resources?
1495 		 */
1496 		if (anon == NULL || pg == NULL) {
1497 
1498 			/*
1499 			 * arg!  must unbusy our page and fail or sleep.
1500 			 */
1501 			if (uobjpage != PGO_DONTCARE) {
1502 				if (uobjpage->pg_flags & PG_WANTED)
1503 					/* still holding object lock */
1504 					wakeup(uobjpage);
1505 
1506 				uvm_lock_pageq();
1507 				uvm_pageactivate(uobjpage);
1508 				uvm_unlock_pageq();
1509 				atomic_clearbits_int(&uobjpage->pg_flags,
1510 				    PG_BUSY|PG_WANTED);
1511 				UVM_PAGE_OWN(uobjpage, NULL);
1512 			}
1513 
1514 			/* unlock and fail ... */
1515 			uvmfault_unlockall(&ufi, amap, uobj, NULL);
1516 			KASSERT(uvmexp.swpgonly <= uvmexp.swpages);
1517 			if (anon == NULL || uvmexp.swpgonly == uvmexp.swpages) {
1518 				uvmexp.fltnoanon++;
1519 				return (ENOMEM);
1520 			}
1521 
1522 			uvm_anfree(anon);
1523 			uvmexp.fltnoram++;
1524 			uvm_wait("flt_noram5");
1525 			goto ReFault;
1526 		}
1527 
1528 		/*
1529 		 * fill in the data
1530 		 */
1531 
1532 		if (uobjpage != PGO_DONTCARE) {
1533 			uvmexp.flt_prcopy++;
1534 			/* copy page [pg now dirty] */
1535 			uvm_pagecopy(uobjpage, pg);
1536 
1537 			/*
1538 			 * promote to shared amap?  make sure all sharing
1539 			 * procs see it
1540 			 */
1541 			if ((amap_flags(amap) & AMAP_SHARED) != 0) {
1542 				pmap_page_protect(uobjpage, VM_PROT_NONE);
1543 			}
1544 
1545 			/*
1546 			 * dispose of uobjpage. drop handle to uobj as well.
1547 			 */
1548 
1549 			if (uobjpage->pg_flags & PG_WANTED)
1550 				/* still have the obj lock */
1551 				wakeup(uobjpage);
1552 			atomic_clearbits_int(&uobjpage->pg_flags,
1553 			    PG_BUSY|PG_WANTED);
1554 			UVM_PAGE_OWN(uobjpage, NULL);
1555 			uvm_lock_pageq();
1556 			uvm_pageactivate(uobjpage);
1557 			uvm_unlock_pageq();
1558 			simple_unlock(&uobj->vmobjlock);
1559 			uobj = NULL;
1560 		} else {
1561 			uvmexp.flt_przero++;
1562 			/*
1563 			 * Page is zero'd and marked dirty by uvm_pagealloc()
1564 			 * above.
1565 			 */
1566 		}
1567 
1568 		amap_add(&ufi.entry->aref, ufi.orig_rvaddr - ufi.entry->start,
1569 		    anon, 0);
1570 	}
1571 
1572 	/*
1573 	 * locked:
1574 	 * maps(read), amap(if !null), uobj(if !null), uobjpage(if uobj)
1575 	 *
1576 	 * note: pg is either the uobjpage or the new page in the new anon
1577 	 */
1578 
1579 	/*
1580 	 * all resources are present.   we can now map it in and free our
1581 	 * resources.
1582 	 */
1583 
1584 	if (pmap_enter(ufi.orig_map->pmap, ufi.orig_rvaddr, VM_PAGE_TO_PHYS(pg),
1585 	    enter_prot, access_type | PMAP_CANFAIL | (wired ? PMAP_WIRED : 0))
1586 	    != 0) {
1587 
1588 		/*
1589 		 * No need to undo what we did; we can simply think of
1590 		 * this as the pmap throwing away the mapping information.
1591 		 *
1592 		 * We do, however, have to go through the ReFault path,
1593 		 * as the map may change while we're asleep.
1594 		 */
1595 
1596 		if (pg->pg_flags & PG_WANTED)
1597 			wakeup(pg);		/* lock still held */
1598 
1599 		atomic_clearbits_int(&pg->pg_flags, PG_BUSY|PG_FAKE|PG_WANTED);
1600 		UVM_PAGE_OWN(pg, NULL);
1601 		uvmfault_unlockall(&ufi, amap, uobj, NULL);
1602 		KASSERT(uvmexp.swpgonly <= uvmexp.swpages);
1603 		if (uvmexp.swpgonly == uvmexp.swpages) {
1604 			/* XXX instrumentation */
1605 			return (ENOMEM);
1606 		}
1607 		/* XXX instrumentation */
1608 		uvm_wait("flt_pmfail2");
1609 		goto ReFault;
1610 	}
1611 
1612 	uvm_lock_pageq();
1613 
1614 	if (fault_type == VM_FAULT_WIRE) {
1615 		uvm_pagewire(pg);
1616 		if (pg->pg_flags & PQ_AOBJ) {
1617 
1618 			/*
1619 			 * since the now-wired page cannot be paged out,
1620 			 * release its swap resources for others to use.
1621 			 * since an aobj page with no swap cannot be PG_CLEAN,
1622 			 * clear its clean flag now.
1623 			 */
1624 			atomic_clearbits_int(&pg->pg_flags, PG_CLEAN);
1625 			uao_dropswap(uobj, pg->offset >> PAGE_SHIFT);
1626 		}
1627 	} else {
1628 		/* activate it */
1629 		uvm_pageactivate(pg);
1630 	}
1631 	uvm_unlock_pageq();
1632 
1633 	if (pg->pg_flags & PG_WANTED)
1634 		wakeup(pg);		/* lock still held */
1635 
1636 	atomic_clearbits_int(&pg->pg_flags, PG_BUSY|PG_FAKE|PG_WANTED);
1637 	UVM_PAGE_OWN(pg, NULL);
1638 	uvmfault_unlockall(&ufi, amap, uobj, NULL);
1639 	pmap_update(ufi.orig_map->pmap);
1640 
1641 	return (0);
1642 }
1643 
1644 
1645 /*
1646  * uvm_fault_wire: wire down a range of virtual addresses in a map.
1647  *
1648  * => map may be read-locked by caller, but MUST NOT be write-locked.
1649  * => if map is read-locked, any operations which may cause map to
1650  *	be write-locked in uvm_fault() must be taken care of by
1651  *	the caller.  See uvm_map_pageable().
1652  */
1653 
1654 int
1655 uvm_fault_wire(vm_map_t map, vaddr_t start, vaddr_t end, vm_prot_t access_type)
1656 {
1657 	vaddr_t va;
1658 	pmap_t  pmap;
1659 	int rv;
1660 
1661 	pmap = vm_map_pmap(map);
1662 
1663 	/*
1664 	 * now fault it in a page at a time.   if the fault fails then we have
1665 	 * to undo what we have done.   note that in uvm_fault VM_PROT_NONE
1666 	 * is replaced with the max protection if fault_type is VM_FAULT_WIRE.
1667 	 */
1668 
1669 	for (va = start ; va < end ; va += PAGE_SIZE) {
1670 		rv = uvm_fault(map, va, VM_FAULT_WIRE, access_type);
1671 		if (rv) {
1672 			if (va != start) {
1673 				uvm_fault_unwire(map, start, va);
1674 			}
1675 			return (rv);
1676 		}
1677 	}
1678 
1679 	return (0);
1680 }
1681 
1682 /*
1683  * uvm_fault_unwire(): unwire range of virtual space.
1684  */
1685 
1686 void
1687 uvm_fault_unwire(vm_map_t map, vaddr_t start, vaddr_t end)
1688 {
1689 
1690 	vm_map_lock_read(map);
1691 	uvm_fault_unwire_locked(map, start, end);
1692 	vm_map_unlock_read(map);
1693 }
1694 
1695 /*
1696  * uvm_fault_unwire_locked(): the guts of uvm_fault_unwire().
1697  *
1698  * => map must be at least read-locked.
1699  */
1700 
1701 void
1702 uvm_fault_unwire_locked(vm_map_t map, vaddr_t start, vaddr_t end)
1703 {
1704 	vm_map_entry_t entry;
1705 	pmap_t pmap = vm_map_pmap(map);
1706 	vaddr_t va;
1707 	paddr_t pa;
1708 	struct vm_page *pg;
1709 
1710 	KASSERT((map->flags & VM_MAP_INTRSAFE) == 0);
1711 
1712 	/*
1713 	 * we assume that the area we are unwiring has actually been wired
1714 	 * in the first place.   this means that we should be able to extract
1715 	 * the PAs from the pmap.   we also lock out the page daemon so that
1716 	 * we can call uvm_pageunwire.
1717 	 */
1718 
1719 	uvm_lock_pageq();
1720 
1721 	/*
1722 	 * find the beginning map entry for the region.
1723 	 */
1724 	KASSERT(start >= vm_map_min(map) && end <= vm_map_max(map));
1725 	if (uvm_map_lookup_entry(map, start, &entry) == FALSE)
1726 		panic("uvm_fault_unwire_locked: address not in map");
1727 
1728 	for (va = start; va < end ; va += PAGE_SIZE) {
1729 		if (pmap_extract(pmap, va, &pa) == FALSE)
1730 			continue;
1731 
1732 		/*
1733 		 * find the map entry for the current address.
1734 		 */
1735 		KASSERT(va >= entry->start);
1736 		while (va >= entry->end) {
1737 			KASSERT(entry->next != &map->header &&
1738 				entry->next->start <= entry->end);
1739 			entry = entry->next;
1740 		}
1741 
1742 		/*
1743 		 * if the entry is no longer wired, tell the pmap.
1744 		 */
1745 		if (VM_MAPENT_ISWIRED(entry) == 0)
1746 			pmap_unwire(pmap, va);
1747 
1748 		pg = PHYS_TO_VM_PAGE(pa);
1749 		if (pg)
1750 			uvm_pageunwire(pg);
1751 	}
1752 
1753 	uvm_unlock_pageq();
1754 }
1755 
1756 /*
1757  * uvmfault_unlockmaps: unlock the maps
1758  */
1759 void
1760 uvmfault_unlockmaps(struct uvm_faultinfo *ufi, boolean_t write_locked)
1761 {
1762 	/*
1763 	 * ufi can be NULL when this isn't really a fault,
1764 	 * but merely paging in anon data.
1765 	 */
1766 
1767 	if (ufi == NULL) {
1768 		return;
1769 	}
1770 
1771 	if (write_locked) {
1772 		vm_map_unlock(ufi->map);
1773 	} else {
1774 		vm_map_unlock_read(ufi->map);
1775 	}
1776 }
1777 
1778 /*
1779  * uvmfault_unlockall: unlock everything passed in.
1780  *
1781  * => maps must be read-locked (not write-locked).
1782  */
1783 void
1784 uvmfault_unlockall(struct uvm_faultinfo *ufi, struct vm_amap *amap,
1785     struct uvm_object *uobj, struct vm_anon *anon)
1786 {
1787 
1788 	if (anon)
1789 		simple_unlock(&anon->an_lock);
1790 	if (uobj)
1791 		simple_unlock(&uobj->vmobjlock);
1792 	uvmfault_unlockmaps(ufi, FALSE);
1793 }
1794 
1795 /*
1796  * uvmfault_lookup: lookup a virtual address in a map
1797  *
1798  * => caller must provide a uvm_faultinfo structure with the IN
1799  *	params properly filled in
1800  * => we will lookup the map entry (handling submaps) as we go
1801  * => if the lookup is a success we will return with the maps locked
1802  * => if "write_lock" is TRUE, we write_lock the map, otherwise we only
1803  *	get a read lock.
1804  * => note that submaps can only appear in the kernel and they are
1805  *	required to use the same virtual addresses as the map they
1806  *	are referenced by (thus address translation between the main
1807  *	map and the submap is unnecessary).
1808  */
1809 
1810 boolean_t
1811 uvmfault_lookup(struct uvm_faultinfo *ufi, boolean_t write_lock)
1812 {
1813 	vm_map_t tmpmap;
1814 
1815 	/*
1816 	 * init ufi values for lookup.
1817 	 */
1818 
1819 	ufi->map = ufi->orig_map;
1820 	ufi->size = ufi->orig_size;
1821 
1822 	/*
1823 	 * keep going down levels until we are done.   note that there can
1824 	 * only be two levels so we won't loop very long.
1825 	 */
1826 
1827 	while (1) {
1828 
1829 		/*
1830 		 * lock map
1831 		 */
1832 		if (write_lock) {
1833 			vm_map_lock(ufi->map);
1834 		} else {
1835 			vm_map_lock_read(ufi->map);
1836 		}
1837 
1838 		/*
1839 		 * lookup
1840 		 */
1841 		if (!uvm_map_lookup_entry(ufi->map, ufi->orig_rvaddr,
1842 								&ufi->entry)) {
1843 			uvmfault_unlockmaps(ufi, write_lock);
1844 			return(FALSE);
1845 		}
1846 
1847 		/*
1848 		 * reduce size if necessary
1849 		 */
1850 		if (ufi->entry->end - ufi->orig_rvaddr < ufi->size)
1851 			ufi->size = ufi->entry->end - ufi->orig_rvaddr;
1852 
1853 		/*
1854 		 * submap?    replace map with the submap and lookup again.
1855 		 * note: VAs in submaps must match VAs in main map.
1856 		 */
1857 		if (UVM_ET_ISSUBMAP(ufi->entry)) {
1858 			tmpmap = ufi->entry->object.sub_map;
1859 			uvmfault_unlockmaps(ufi, write_lock);
1860 			ufi->map = tmpmap;
1861 			continue;
1862 		}
1863 
1864 		/*
1865 		 * got it!
1866 		 */
1867 
1868 		ufi->mapv = ufi->map->timestamp;
1869 		return(TRUE);
1870 
1871 	}	/* while loop */
1872 
1873 	/*NOTREACHED*/
1874 }
1875 
1876 /*
1877  * uvmfault_relock: attempt to relock the same version of the map
1878  *
1879  * => fault data structures should be unlocked before calling.
1880  * => if a success (TRUE) maps will be locked after call.
1881  */
1882 boolean_t
1883 uvmfault_relock(struct uvm_faultinfo *ufi)
1884 {
1885 	/*
1886 	 * ufi can be NULL when this isn't really a fault,
1887 	 * but merely paging in anon data.
1888 	 */
1889 
1890 	if (ufi == NULL) {
1891 		return TRUE;
1892 	}
1893 
1894 	uvmexp.fltrelck++;
1895 
1896 	/*
1897 	 * relock map.   fail if version mismatch (in which case nothing
1898 	 * gets locked).
1899 	 */
1900 
1901 	vm_map_lock_read(ufi->map);
1902 	if (ufi->mapv != ufi->map->timestamp) {
1903 		vm_map_unlock_read(ufi->map);
1904 		return(FALSE);
1905 	}
1906 
1907 	uvmexp.fltrelckok++;
1908 	return(TRUE);		/* got it! */
1909 }
1910