xref: /netbsd-src/sys/uvm/uvm_fault.c (revision 4817a0b0b8fe9612e8ebe21a9bf2d97b95038a97)
1 /*	$NetBSD: uvm_fault.c,v 1.178 2010/12/20 00:25:47 matt Exp $	*/
2 
3 /*
4  *
5  * Copyright (c) 1997 Charles D. Cranor and Washington University.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
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 the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by Charles D. Cranor and
19  *      Washington University.
20  * 4. The name of the author may not be used to endorse or promote products
21  *    derived from this software without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  *
34  * from: Id: uvm_fault.c,v 1.1.2.23 1998/02/06 05:29:05 chs Exp
35  */
36 
37 /*
38  * uvm_fault.c: fault handler
39  */
40 
41 #include <sys/cdefs.h>
42 __KERNEL_RCSID(0, "$NetBSD: uvm_fault.c,v 1.178 2010/12/20 00:25:47 matt Exp $");
43 
44 #include "opt_uvmhist.h"
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/kernel.h>
49 #include <sys/proc.h>
50 #include <sys/malloc.h>
51 #include <sys/mman.h>
52 
53 #include <uvm/uvm.h>
54 
55 /*
56  *
57  * a word on page faults:
58  *
59  * types of page faults we handle:
60  *
61  * CASE 1: upper layer faults                   CASE 2: lower layer faults
62  *
63  *    CASE 1A         CASE 1B                  CASE 2A        CASE 2B
64  *    read/write1     write>1                  read/write   +-cow_write/zero
65  *         |             |                         |        |
66  *      +--|--+       +--|--+     +-----+       +  |  +     | +-----+
67  * amap |  V  |       |  ---------> new |          |        | |  ^  |
68  *      +-----+       +-----+     +-----+       +  |  +     | +--|--+
69  *                                                 |        |    |
70  *      +-----+       +-----+                   +--|--+     | +--|--+
71  * uobj | d/c |       | d/c |                   |  V  |     +----+  |
72  *      +-----+       +-----+                   +-----+       +-----+
73  *
74  * d/c = don't care
75  *
76  *   case [0]: layerless fault
77  *	no amap or uobj is present.   this is an error.
78  *
79  *   case [1]: upper layer fault [anon active]
80  *     1A: [read] or [write with anon->an_ref == 1]
81  *		I/O takes place in upper level anon and uobj is not touched.
82  *     1B: [write with anon->an_ref > 1]
83  *		new anon is alloc'd and data is copied off ["COW"]
84  *
85  *   case [2]: lower layer fault [uobj]
86  *     2A: [read on non-NULL uobj] or [write to non-copy_on_write area]
87  *		I/O takes place directly in object.
88  *     2B: [write to copy_on_write] or [read on NULL uobj]
89  *		data is "promoted" from uobj to a new anon.
90  *		if uobj is null, then we zero fill.
91  *
92  * we follow the standard UVM locking protocol ordering:
93  *
94  * MAPS => AMAP => UOBJ => ANON => PAGE QUEUES (PQ)
95  * we hold a PG_BUSY page if we unlock for I/O
96  *
97  *
98  * the code is structured as follows:
99  *
100  *     - init the "IN" params in the ufi structure
101  *   ReFault: (ERESTART returned to the loop in uvm_fault_internal)
102  *     - do lookups [locks maps], check protection, handle needs_copy
103  *     - check for case 0 fault (error)
104  *     - establish "range" of fault
105  *     - if we have an amap lock it and extract the anons
106  *     - if sequential advice deactivate pages behind us
107  *     - at the same time check pmap for unmapped areas and anon for pages
108  *	 that we could map in (and do map it if found)
109  *     - check object for resident pages that we could map in
110  *     - if (case 2) goto Case2
111  *     - >>> handle case 1
112  *           - ensure source anon is resident in RAM
113  *           - if case 1B alloc new anon and copy from source
114  *           - map the correct page in
115  *   Case2:
116  *     - >>> handle case 2
117  *           - ensure source page is resident (if uobj)
118  *           - if case 2B alloc new anon and copy from source (could be zero
119  *		fill if uobj == NULL)
120  *           - map the correct page in
121  *     - done!
122  *
123  * note on paging:
124  *   if we have to do I/O we place a PG_BUSY page in the correct object,
125  * unlock everything, and do the I/O.   when I/O is done we must reverify
126  * the state of the world before assuming that our data structures are
127  * valid.   [because mappings could change while the map is unlocked]
128  *
129  *  alternative 1: unbusy the page in question and restart the page fault
130  *    from the top (ReFault).   this is easy but does not take advantage
131  *    of the information that we already have from our previous lookup,
132  *    although it is possible that the "hints" in the vm_map will help here.
133  *
134  * alternative 2: the system already keeps track of a "version" number of
135  *    a map.   [i.e. every time you write-lock a map (e.g. to change a
136  *    mapping) you bump the version number up by one...]   so, we can save
137  *    the version number of the map before we release the lock and start I/O.
138  *    then when I/O is done we can relock and check the version numbers
139  *    to see if anything changed.    this might save us some over 1 because
140  *    we don't have to unbusy the page and may be less compares(?).
141  *
142  * alternative 3: put in backpointers or a way to "hold" part of a map
143  *    in place while I/O is in progress.   this could be complex to
144  *    implement (especially with structures like amap that can be referenced
145  *    by multiple map entries, and figuring out what should wait could be
146  *    complex as well...).
147  *
148  * we use alternative 2.  given that we are multi-threaded now we may want
149  * to reconsider the choice.
150  */
151 
152 /*
153  * local data structures
154  */
155 
156 struct uvm_advice {
157 	int advice;
158 	int nback;
159 	int nforw;
160 };
161 
162 /*
163  * page range array:
164  * note: index in array must match "advice" value
165  * XXX: borrowed numbers from freebsd.   do they work well for us?
166  */
167 
168 static const struct uvm_advice uvmadvice[] = {
169 	{ MADV_NORMAL, 3, 4 },
170 	{ MADV_RANDOM, 0, 0 },
171 	{ MADV_SEQUENTIAL, 8, 7},
172 };
173 
174 #define UVM_MAXRANGE 16	/* must be MAX() of nback+nforw+1 */
175 
176 /*
177  * private prototypes
178  */
179 
180 /*
181  * inline functions
182  */
183 
184 /*
185  * uvmfault_anonflush: try and deactivate pages in specified anons
186  *
187  * => does not have to deactivate page if it is busy
188  */
189 
190 static inline void
191 uvmfault_anonflush(struct vm_anon **anons, int n)
192 {
193 	int lcv;
194 	struct vm_page *pg;
195 
196 	for (lcv = 0; lcv < n; lcv++) {
197 		if (anons[lcv] == NULL)
198 			continue;
199 		mutex_enter(&anons[lcv]->an_lock);
200 		pg = anons[lcv]->an_page;
201 		if (pg && (pg->flags & PG_BUSY) == 0) {
202 			mutex_enter(&uvm_pageqlock);
203 			if (pg->wire_count == 0) {
204 				uvm_pagedeactivate(pg);
205 			}
206 			mutex_exit(&uvm_pageqlock);
207 		}
208 		mutex_exit(&anons[lcv]->an_lock);
209 	}
210 }
211 
212 /*
213  * normal functions
214  */
215 
216 /*
217  * uvmfault_amapcopy: clear "needs_copy" in a map.
218  *
219  * => called with VM data structures unlocked (usually, see below)
220  * => we get a write lock on the maps and clear needs_copy for a VA
221  * => if we are out of RAM we sleep (waiting for more)
222  */
223 
224 static void
225 uvmfault_amapcopy(struct uvm_faultinfo *ufi)
226 {
227 	for (;;) {
228 
229 		/*
230 		 * no mapping?  give up.
231 		 */
232 
233 		if (uvmfault_lookup(ufi, true) == false)
234 			return;
235 
236 		/*
237 		 * copy if needed.
238 		 */
239 
240 		if (UVM_ET_ISNEEDSCOPY(ufi->entry))
241 			amap_copy(ufi->map, ufi->entry, AMAP_COPY_NOWAIT,
242 				ufi->orig_rvaddr, ufi->orig_rvaddr + 1);
243 
244 		/*
245 		 * didn't work?  must be out of RAM.   unlock and sleep.
246 		 */
247 
248 		if (UVM_ET_ISNEEDSCOPY(ufi->entry)) {
249 			uvmfault_unlockmaps(ufi, true);
250 			uvm_wait("fltamapcopy");
251 			continue;
252 		}
253 
254 		/*
255 		 * got it!   unlock and return.
256 		 */
257 
258 		uvmfault_unlockmaps(ufi, true);
259 		return;
260 	}
261 	/*NOTREACHED*/
262 }
263 
264 /*
265  * uvmfault_anonget: get data in an anon into a non-busy, non-released
266  * page in that anon.
267  *
268  * => maps, amap, and anon locked by caller.
269  * => if we fail (result != 0) we unlock everything.
270  * => if we are successful, we return with everything still locked.
271  * => we don't move the page on the queues [gets moved later]
272  * => if we allocate a new page [we_own], it gets put on the queues.
273  *    either way, the result is that the page is on the queues at return time
274  * => for pages which are on loan from a uvm_object (and thus are not
275  *    owned by the anon): if successful, we return with the owning object
276  *    locked.   the caller must unlock this object when it unlocks everything
277  *    else.
278  */
279 
280 int
281 uvmfault_anonget(struct uvm_faultinfo *ufi, struct vm_amap *amap,
282     struct vm_anon *anon)
283 {
284 	bool we_own;	/* we own anon's page? */
285 	bool locked;	/* did we relock? */
286 	struct vm_page *pg;
287 	int error;
288 	UVMHIST_FUNC("uvmfault_anonget"); UVMHIST_CALLED(maphist);
289 
290 	KASSERT(mutex_owned(&anon->an_lock));
291 
292 	error = 0;
293 	uvmexp.fltanget++;
294         /* bump rusage counters */
295 	if (anon->an_page)
296 		curlwp->l_ru.ru_minflt++;
297 	else
298 		curlwp->l_ru.ru_majflt++;
299 
300 	/*
301 	 * loop until we get it, or fail.
302 	 */
303 
304 	for (;;) {
305 		we_own = false;		/* true if we set PG_BUSY on a page */
306 		pg = anon->an_page;
307 
308 		/*
309 		 * if there is a resident page and it is loaned, then anon
310 		 * may not own it.   call out to uvm_anon_lockpage() to ensure
311 		 * the real owner of the page has been identified and locked.
312 		 */
313 
314 		if (pg && pg->loan_count)
315 			pg = uvm_anon_lockloanpg(anon);
316 
317 		/*
318 		 * page there?   make sure it is not busy/released.
319 		 */
320 
321 		if (pg) {
322 
323 			/*
324 			 * at this point, if the page has a uobject [meaning
325 			 * we have it on loan], then that uobject is locked
326 			 * by us!   if the page is busy, we drop all the
327 			 * locks (including uobject) and try again.
328 			 */
329 
330 			if ((pg->flags & PG_BUSY) == 0) {
331 				UVMHIST_LOG(maphist, "<- OK",0,0,0,0);
332 				return (0);
333 			}
334 			pg->flags |= PG_WANTED;
335 			uvmexp.fltpgwait++;
336 
337 			/*
338 			 * the last unlock must be an atomic unlock+wait on
339 			 * the owner of page
340 			 */
341 
342 			if (pg->uobject) {	/* owner is uobject ? */
343 				uvmfault_unlockall(ufi, amap, NULL, anon);
344 				UVMHIST_LOG(maphist, " unlock+wait on uobj",0,
345 				    0,0,0);
346 				UVM_UNLOCK_AND_WAIT(pg,
347 				    &pg->uobject->vmobjlock,
348 				    false, "anonget1",0);
349 			} else {
350 				/* anon owns page */
351 				uvmfault_unlockall(ufi, amap, NULL, NULL);
352 				UVMHIST_LOG(maphist, " unlock+wait on anon",0,
353 				    0,0,0);
354 				UVM_UNLOCK_AND_WAIT(pg,&anon->an_lock,0,
355 				    "anonget2",0);
356 			}
357 		} else {
358 #if defined(VMSWAP)
359 
360 			/*
361 			 * no page, we must try and bring it in.
362 			 */
363 
364 			pg = uvm_pagealloc(NULL, 0, anon, 0);
365 			if (pg == NULL) {		/* out of RAM.  */
366 				uvmfault_unlockall(ufi, amap, NULL, anon);
367 				uvmexp.fltnoram++;
368 				UVMHIST_LOG(maphist, "  noram -- UVM_WAIT",0,
369 				    0,0,0);
370 				if (!uvm_reclaimable()) {
371 					return ENOMEM;
372 				}
373 				uvm_wait("flt_noram1");
374 			} else {
375 				/* we set the PG_BUSY bit */
376 				we_own = true;
377 				uvmfault_unlockall(ufi, amap, NULL, anon);
378 
379 				/*
380 				 * we are passing a PG_BUSY+PG_FAKE+PG_CLEAN
381 				 * page into the uvm_swap_get function with
382 				 * all data structures unlocked.  note that
383 				 * it is ok to read an_swslot here because
384 				 * we hold PG_BUSY on the page.
385 				 */
386 				uvmexp.pageins++;
387 				error = uvm_swap_get(pg, anon->an_swslot,
388 				    PGO_SYNCIO);
389 
390 				/*
391 				 * we clean up after the i/o below in the
392 				 * "we_own" case
393 				 */
394 			}
395 #else /* defined(VMSWAP) */
396 			panic("%s: no page", __func__);
397 #endif /* defined(VMSWAP) */
398 		}
399 
400 		/*
401 		 * now relock and try again
402 		 */
403 
404 		locked = uvmfault_relock(ufi);
405 		if (locked && amap != NULL) {
406 			amap_lock(amap);
407 		}
408 		if (locked || we_own)
409 			mutex_enter(&anon->an_lock);
410 
411 		/*
412 		 * if we own the page (i.e. we set PG_BUSY), then we need
413 		 * to clean up after the I/O. there are three cases to
414 		 * consider:
415 		 *   [1] page released during I/O: free anon and ReFault.
416 		 *   [2] I/O not OK.   free the page and cause the fault
417 		 *       to fail.
418 		 *   [3] I/O OK!   activate the page and sync with the
419 		 *       non-we_own case (i.e. drop anon lock if not locked).
420 		 */
421 
422 		if (we_own) {
423 #if defined(VMSWAP)
424 			if (pg->flags & PG_WANTED) {
425 				wakeup(pg);
426 			}
427 			if (error) {
428 
429 				/*
430 				 * remove the swap slot from the anon
431 				 * and mark the anon as having no real slot.
432 				 * don't free the swap slot, thus preventing
433 				 * it from being used again.
434 				 */
435 
436 				if (anon->an_swslot > 0)
437 					uvm_swap_markbad(anon->an_swslot, 1);
438 				anon->an_swslot = SWSLOT_BAD;
439 
440 				if ((pg->flags & PG_RELEASED) != 0)
441 					goto released;
442 
443 				/*
444 				 * note: page was never !PG_BUSY, so it
445 				 * can't be mapped and thus no need to
446 				 * pmap_page_protect it...
447 				 */
448 
449 				mutex_enter(&uvm_pageqlock);
450 				uvm_pagefree(pg);
451 				mutex_exit(&uvm_pageqlock);
452 
453 				if (locked)
454 					uvmfault_unlockall(ufi, amap, NULL,
455 					    anon);
456 				else
457 					mutex_exit(&anon->an_lock);
458 				UVMHIST_LOG(maphist, "<- ERROR", 0,0,0,0);
459 				return error;
460 			}
461 
462 			if ((pg->flags & PG_RELEASED) != 0) {
463 released:
464 				KASSERT(anon->an_ref == 0);
465 
466 				/*
467 				 * released while we unlocked amap.
468 				 */
469 
470 				if (locked)
471 					uvmfault_unlockall(ufi, amap, NULL,
472 					    NULL);
473 
474 				uvm_anon_release(anon);
475 
476 				if (error) {
477 					UVMHIST_LOG(maphist,
478 					    "<- ERROR/RELEASED", 0,0,0,0);
479 					return error;
480 				}
481 
482 				UVMHIST_LOG(maphist, "<- RELEASED", 0,0,0,0);
483 				return ERESTART;
484 			}
485 
486 			/*
487 			 * we've successfully read the page, activate it.
488 			 */
489 
490 			mutex_enter(&uvm_pageqlock);
491 			uvm_pageactivate(pg);
492 			mutex_exit(&uvm_pageqlock);
493 			pg->flags &= ~(PG_WANTED|PG_BUSY|PG_FAKE);
494 			UVM_PAGE_OWN(pg, NULL);
495 			if (!locked)
496 				mutex_exit(&anon->an_lock);
497 #else /* defined(VMSWAP) */
498 			panic("%s: we_own", __func__);
499 #endif /* defined(VMSWAP) */
500 		}
501 
502 		/*
503 		 * we were not able to relock.   restart fault.
504 		 */
505 
506 		if (!locked) {
507 			UVMHIST_LOG(maphist, "<- REFAULT", 0,0,0,0);
508 			return (ERESTART);
509 		}
510 
511 		/*
512 		 * verify no one has touched the amap and moved the anon on us.
513 		 */
514 
515 		if (ufi != NULL &&
516 		    amap_lookup(&ufi->entry->aref,
517 				ufi->orig_rvaddr - ufi->entry->start) != anon) {
518 
519 			uvmfault_unlockall(ufi, amap, NULL, anon);
520 			UVMHIST_LOG(maphist, "<- REFAULT", 0,0,0,0);
521 			return (ERESTART);
522 		}
523 
524 		/*
525 		 * try it again!
526 		 */
527 
528 		uvmexp.fltanretry++;
529 		continue;
530 	}
531 	/*NOTREACHED*/
532 }
533 
534 /*
535  * uvmfault_promote: promote data to a new anon.  used for 1B and 2B.
536  *
537  *	1. allocate an anon and a page.
538  *	2. fill its contents.
539  *	3. put it into amap.
540  *
541  * => if we fail (result != 0) we unlock everything.
542  * => on success, return a new locked anon via 'nanon'.
543  *    (*nanon)->an_page will be a resident, locked, dirty page.
544  */
545 
546 static int
547 uvmfault_promote(struct uvm_faultinfo *ufi,
548     struct vm_anon *oanon,
549     struct vm_page *uobjpage,
550     struct vm_anon **nanon, /* OUT: allocated anon */
551     struct vm_anon **spare)
552 {
553 	struct vm_amap *amap = ufi->entry->aref.ar_amap;
554 	struct uvm_object *uobj;
555 	struct vm_anon *anon;
556 	struct vm_page *pg;
557 	struct vm_page *opg;
558 	int error;
559 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
560 
561 	if (oanon) {
562 		/* anon COW */
563 		opg = oanon->an_page;
564 		KASSERT(opg != NULL);
565 		KASSERT(opg->uobject == NULL || opg->loan_count > 0);
566 	} else if (uobjpage != PGO_DONTCARE) {
567 		/* object-backed COW */
568 		opg = uobjpage;
569 	} else {
570 		/* ZFOD */
571 		opg = NULL;
572 	}
573 	if (opg != NULL) {
574 		uobj = opg->uobject;
575 	} else {
576 		uobj = NULL;
577 	}
578 
579 	KASSERT(amap != NULL);
580 	KASSERT(uobjpage != NULL);
581 	KASSERT(uobjpage == PGO_DONTCARE || (uobjpage->flags & PG_BUSY) != 0);
582 	KASSERT(mutex_owned(&amap->am_l));
583 	KASSERT(oanon == NULL || mutex_owned(&oanon->an_lock));
584 	KASSERT(uobj == NULL || mutex_owned(&uobj->vmobjlock));
585 #if 0
586 	KASSERT(*spare == NULL || !mutex_owned(&(*spare)->an_lock));
587 #endif
588 
589 	if (*spare != NULL) {
590 		anon = *spare;
591 		*spare = NULL;
592 		mutex_enter(&anon->an_lock);
593 	} else if (ufi->map != kernel_map) {
594 		anon = uvm_analloc();
595 	} else {
596 		UVMHIST_LOG(maphist, "kernel_map, unlock and retry", 0,0,0,0);
597 
598 		/*
599 		 * we can't allocate anons with kernel_map locked.
600 		 */
601 
602 		uvm_page_unbusy(&uobjpage, 1);
603 		uvmfault_unlockall(ufi, amap, uobj, oanon);
604 
605 		*spare = uvm_analloc();
606 		if (*spare == NULL) {
607 			goto nomem;
608 		}
609 		mutex_exit(&(*spare)->an_lock);
610 		error = ERESTART;
611 		goto done;
612 	}
613 	if (anon) {
614 
615 		/*
616 		 * The new anon is locked.
617 		 *
618 		 * if opg == NULL, we want a zero'd, dirty page,
619 		 * so have uvm_pagealloc() do that for us.
620 		 */
621 
622 		pg = uvm_pagealloc(NULL, 0, anon,
623 		    (opg == NULL) ? UVM_PGA_ZERO : 0);
624 	} else {
625 		pg = NULL;
626 	}
627 
628 	/*
629 	 * out of memory resources?
630 	 */
631 
632 	if (pg == NULL) {
633 		/* save anon for the next try. */
634 		if (anon != NULL) {
635 			mutex_exit(&anon->an_lock);
636 			*spare = anon;
637 		}
638 
639 		/* unlock and fail ... */
640 		uvm_page_unbusy(&uobjpage, 1);
641 		uvmfault_unlockall(ufi, amap, uobj, oanon);
642 nomem:
643 		if (!uvm_reclaimable()) {
644 			UVMHIST_LOG(maphist, "out of VM", 0,0,0,0);
645 			uvmexp.fltnoanon++;
646 			error = ENOMEM;
647 			goto done;
648 		}
649 
650 		UVMHIST_LOG(maphist, "out of RAM, waiting for more", 0,0,0,0);
651 		uvmexp.fltnoram++;
652 		uvm_wait("flt_noram5");
653 		error = ERESTART;
654 		goto done;
655 	}
656 
657 	/* copy page [pg now dirty] */
658 	if (opg) {
659 		uvm_pagecopy(opg, pg);
660 	}
661 
662 	amap_add(&ufi->entry->aref, ufi->orig_rvaddr - ufi->entry->start, anon,
663 	    oanon != NULL);
664 
665 	*nanon = anon;
666 	error = 0;
667 done:
668 	return error;
669 }
670 
671 
672 /*
673  *   F A U L T   -   m a i n   e n t r y   p o i n t
674  */
675 
676 /*
677  * uvm_fault: page fault handler
678  *
679  * => called from MD code to resolve a page fault
680  * => VM data structures usually should be unlocked.   however, it is
681  *	possible to call here with the main map locked if the caller
682  *	gets a write lock, sets it recusive, and then calls us (c.f.
683  *	uvm_map_pageable).   this should be avoided because it keeps
684  *	the map locked off during I/O.
685  * => MUST NEVER BE CALLED IN INTERRUPT CONTEXT
686  */
687 
688 #define MASK(entry)     (UVM_ET_ISCOPYONWRITE(entry) ? \
689 			 ~VM_PROT_WRITE : VM_PROT_ALL)
690 
691 /* fault_flag values passed from uvm_fault_wire to uvm_fault_internal */
692 #define UVM_FAULT_WIRE		(1 << 0)
693 #define UVM_FAULT_MAXPROT	(1 << 1)
694 
695 struct uvm_faultctx {
696 	vm_prot_t access_type;
697 	vm_prot_t enter_prot;
698 	vaddr_t startva;
699 	int npages;
700 	int centeridx;
701 	struct vm_anon *anon_spare;
702 	bool wire_mapping;
703 	bool narrow;
704 	bool wire_paging;
705 	bool cow_now;
706 	bool promote;
707 };
708 
709 static inline int	uvm_fault_check(
710 			    struct uvm_faultinfo *, struct uvm_faultctx *,
711 			    struct vm_anon ***, bool);
712 
713 static int		uvm_fault_upper(
714 			    struct uvm_faultinfo *, struct uvm_faultctx *,
715 			    struct vm_anon **);
716 static inline int	uvm_fault_upper_lookup(
717 			    struct uvm_faultinfo *, const struct uvm_faultctx *,
718 			    struct vm_anon **, struct vm_page **);
719 static inline void	uvm_fault_upper_neighbor(
720 			    struct uvm_faultinfo *, const struct uvm_faultctx *,
721 			    vaddr_t, struct vm_page *, bool);
722 static inline int	uvm_fault_upper_loan(
723 			    struct uvm_faultinfo *, struct uvm_faultctx *,
724 			    struct vm_anon *, struct uvm_object **);
725 static inline int	uvm_fault_upper_promote(
726 			    struct uvm_faultinfo *, struct uvm_faultctx *,
727 			    struct uvm_object *, struct vm_anon *);
728 static inline int	uvm_fault_upper_direct(
729 			    struct uvm_faultinfo *, struct uvm_faultctx *,
730 			    struct uvm_object *, struct vm_anon *);
731 static int		uvm_fault_upper_enter(
732 			    struct uvm_faultinfo *, const struct uvm_faultctx *,
733 			    struct uvm_object *, struct vm_anon *,
734 			    struct vm_page *, struct vm_anon *);
735 static inline void	uvm_fault_upper_done(
736 			    struct uvm_faultinfo *, const struct uvm_faultctx *,
737 			    struct vm_anon *, struct vm_page *);
738 
739 static int		uvm_fault_lower(
740 			    struct uvm_faultinfo *, struct uvm_faultctx *,
741 			    struct vm_page **);
742 static inline void	uvm_fault_lower_lookup(
743 			    struct uvm_faultinfo *, const struct uvm_faultctx *,
744 			    struct vm_page **);
745 static inline void	uvm_fault_lower_neighbor(
746 			    struct uvm_faultinfo *, const struct uvm_faultctx *,
747 			    vaddr_t, struct vm_page *, bool);
748 static inline int	uvm_fault_lower_io(
749 			    struct uvm_faultinfo *, const struct uvm_faultctx *,
750 			    struct uvm_object **, struct vm_page **);
751 static inline int	uvm_fault_lower_direct(
752 			    struct uvm_faultinfo *, struct uvm_faultctx *,
753 			    struct uvm_object *, struct vm_page *);
754 static inline int	uvm_fault_lower_direct_loan(
755 			    struct uvm_faultinfo *, struct uvm_faultctx *,
756 			    struct uvm_object *, struct vm_page **,
757 			    struct vm_page **);
758 static inline int	uvm_fault_lower_promote(
759 			    struct uvm_faultinfo *, struct uvm_faultctx *,
760 			    struct uvm_object *, struct vm_page *);
761 static int		uvm_fault_lower_enter(
762 			    struct uvm_faultinfo *, const struct uvm_faultctx *,
763 			    struct uvm_object *,
764 			    struct vm_anon *, struct vm_page *,
765 			    struct vm_page *);
766 static inline void	uvm_fault_lower_done(
767 			    struct uvm_faultinfo *, const struct uvm_faultctx *,
768 			    struct uvm_object *, struct vm_page *);
769 
770 int
771 uvm_fault_internal(struct vm_map *orig_map, vaddr_t vaddr,
772     vm_prot_t access_type, int fault_flag)
773 {
774 	struct uvm_faultinfo ufi;
775 	struct uvm_faultctx flt = {
776 		.access_type = access_type,
777 
778 		/* don't look for neighborhood * pages on "wire" fault */
779 		.narrow = (fault_flag & UVM_FAULT_WIRE) != 0,
780 
781 		/* "wire" fault causes wiring of both mapping and paging */
782 		.wire_mapping = (fault_flag & UVM_FAULT_WIRE) != 0,
783 		.wire_paging = (fault_flag & UVM_FAULT_WIRE) != 0,
784 	};
785 	const bool maxprot = (fault_flag & UVM_FAULT_MAXPROT) != 0;
786 	struct vm_anon *anons_store[UVM_MAXRANGE], **anons;
787 	struct vm_page *pages_store[UVM_MAXRANGE], **pages;
788 	int error;
789 	UVMHIST_FUNC("uvm_fault"); UVMHIST_CALLED(maphist);
790 
791 	UVMHIST_LOG(maphist, "(map=0x%x, vaddr=0x%x, at=%d, ff=%d)",
792 	      orig_map, vaddr, access_type, fault_flag);
793 
794 	curcpu()->ci_data.cpu_nfault++;
795 
796 	/*
797 	 * init the IN parameters in the ufi
798 	 */
799 
800 	ufi.orig_map = orig_map;
801 	ufi.orig_rvaddr = trunc_page(vaddr);
802 	ufi.orig_size = PAGE_SIZE;	/* can't get any smaller than this */
803 
804 	error = ERESTART;
805 	while (error == ERESTART) {
806 		anons = anons_store;
807 		pages = pages_store;
808 
809 		error = uvm_fault_check(&ufi, &flt, &anons, maxprot);
810 		if (error != 0)
811 			continue;
812 
813 		error = uvm_fault_upper_lookup(&ufi, &flt, anons, pages);
814 		if (error != 0)
815 			continue;
816 
817 		if (pages[flt.centeridx] == PGO_DONTCARE)
818 			error = uvm_fault_upper(&ufi, &flt, anons);
819 		else {
820 			struct uvm_object * const uobj =
821 			    ufi.entry->object.uvm_obj;
822 
823 			if (uobj && uobj->pgops->pgo_fault != NULL) {
824 				/*
825 				 * invoke "special" fault routine.
826 				 */
827 				mutex_enter(&uobj->vmobjlock);
828 				/* locked: maps(read), amap(if there), uobj */
829 				error = uobj->pgops->pgo_fault(&ufi,
830 				    flt.startva, pages, flt.npages,
831 				    flt.centeridx, flt.access_type,
832 				    PGO_LOCKED|PGO_SYNCIO);
833 
834 				/*
835 				 * locked: nothing, pgo_fault has unlocked
836 				 * everything
837 				 */
838 
839 				/*
840 				 * object fault routine responsible for
841 				 * pmap_update().
842 				 */
843 			} else {
844 				error = uvm_fault_lower(&ufi, &flt, pages);
845 			}
846 		}
847 	}
848 
849 	if (flt.anon_spare != NULL) {
850 		flt.anon_spare->an_ref--;
851 		uvm_anfree(flt.anon_spare);
852 	}
853 	return error;
854 }
855 
856 /*
857  * uvm_fault_check: check prot, handle needs-copy, etc.
858  *
859  *	1. lookup entry.
860  *	2. check protection.
861  *	3. adjust fault condition (mainly for simulated fault).
862  *	4. handle needs-copy (lazy amap copy).
863  *	5. establish range of interest for neighbor fault (aka pre-fault).
864  *	6. look up anons (if amap exists).
865  *	7. flush pages (if MADV_SEQUENTIAL)
866  *
867  * => called with nothing locked.
868  * => if we fail (result != 0) we unlock everything.
869  * => initialize/adjust many members of flt.
870  */
871 
872 static int
873 uvm_fault_check(
874 	struct uvm_faultinfo *ufi, struct uvm_faultctx *flt,
875 	struct vm_anon ***ranons, bool maxprot)
876 {
877 	struct vm_amap *amap;
878 	struct uvm_object *uobj;
879 	vm_prot_t check_prot;
880 	int nback, nforw;
881 	UVMHIST_FUNC("uvm_fault_check"); UVMHIST_CALLED(maphist);
882 
883 	/*
884 	 * lookup and lock the maps
885 	 */
886 
887 	if (uvmfault_lookup(ufi, false) == false) {
888 		UVMHIST_LOG(maphist, "<- no mapping @ 0x%x", ufi->orig_rvaddr,
889 		    0,0,0);
890 		return EFAULT;
891 	}
892 	/* locked: maps(read) */
893 
894 #ifdef DIAGNOSTIC
895 	if ((ufi->map->flags & VM_MAP_PAGEABLE) == 0) {
896 		printf("Page fault on non-pageable map:\n");
897 		printf("ufi->map = %p\n", ufi->map);
898 		printf("ufi->orig_map = %p\n", ufi->orig_map);
899 		printf("ufi->orig_rvaddr = 0x%lx\n", (u_long) ufi->orig_rvaddr);
900 		panic("uvm_fault: (ufi->map->flags & VM_MAP_PAGEABLE) == 0");
901 	}
902 #endif
903 
904 	/*
905 	 * check protection
906 	 */
907 
908 	check_prot = maxprot ?
909 	    ufi->entry->max_protection : ufi->entry->protection;
910 	if ((check_prot & flt->access_type) != flt->access_type) {
911 		UVMHIST_LOG(maphist,
912 		    "<- protection failure (prot=0x%x, access=0x%x)",
913 		    ufi->entry->protection, flt->access_type, 0, 0);
914 		uvmfault_unlockmaps(ufi, false);
915 		return EACCES;
916 	}
917 
918 	/*
919 	 * "enter_prot" is the protection we want to enter the page in at.
920 	 * for certain pages (e.g. copy-on-write pages) this protection can
921 	 * be more strict than ufi->entry->protection.  "wired" means either
922 	 * the entry is wired or we are fault-wiring the pg.
923 	 */
924 
925 	flt->enter_prot = ufi->entry->protection;
926 	if (VM_MAPENT_ISWIRED(ufi->entry))
927 		flt->wire_mapping = true;
928 
929 	if (flt->wire_mapping) {
930 		flt->access_type = flt->enter_prot; /* full access for wired */
931 		flt->cow_now = (check_prot & VM_PROT_WRITE) != 0;
932 	} else {
933 		flt->cow_now = (flt->access_type & VM_PROT_WRITE) != 0;
934 	}
935 
936 	flt->promote = false;
937 
938 	/*
939 	 * handle "needs_copy" case.   if we need to copy the amap we will
940 	 * have to drop our readlock and relock it with a write lock.  (we
941 	 * need a write lock to change anything in a map entry [e.g.
942 	 * needs_copy]).
943 	 */
944 
945 	if (UVM_ET_ISNEEDSCOPY(ufi->entry)) {
946 		if (flt->cow_now || (ufi->entry->object.uvm_obj == NULL)) {
947 			KASSERT(!maxprot);
948 			/* need to clear */
949 			UVMHIST_LOG(maphist,
950 			    "  need to clear needs_copy and refault",0,0,0,0);
951 			uvmfault_unlockmaps(ufi, false);
952 			uvmfault_amapcopy(ufi);
953 			uvmexp.fltamcopy++;
954 			return ERESTART;
955 
956 		} else {
957 
958 			/*
959 			 * ensure that we pmap_enter page R/O since
960 			 * needs_copy is still true
961 			 */
962 
963 			flt->enter_prot &= ~VM_PROT_WRITE;
964 		}
965 	}
966 
967 	/*
968 	 * identify the players
969 	 */
970 
971 	amap = ufi->entry->aref.ar_amap;	/* upper layer */
972 	uobj = ufi->entry->object.uvm_obj;	/* lower layer */
973 
974 	/*
975 	 * check for a case 0 fault.  if nothing backing the entry then
976 	 * error now.
977 	 */
978 
979 	if (amap == NULL && uobj == NULL) {
980 		uvmfault_unlockmaps(ufi, false);
981 		UVMHIST_LOG(maphist,"<- no backing store, no overlay",0,0,0,0);
982 		return EFAULT;
983 	}
984 
985 	/*
986 	 * establish range of interest based on advice from mapper
987 	 * and then clip to fit map entry.   note that we only want
988 	 * to do this the first time through the fault.   if we
989 	 * ReFault we will disable this by setting "narrow" to true.
990 	 */
991 
992 	if (flt->narrow == false) {
993 
994 		/* wide fault (!narrow) */
995 		KASSERT(uvmadvice[ufi->entry->advice].advice ==
996 			 ufi->entry->advice);
997 		nback = MIN(uvmadvice[ufi->entry->advice].nback,
998 		    (ufi->orig_rvaddr - ufi->entry->start) >> PAGE_SHIFT);
999 		flt->startva = ufi->orig_rvaddr - (nback << PAGE_SHIFT);
1000 		/*
1001 		 * note: "-1" because we don't want to count the
1002 		 * faulting page as forw
1003 		 */
1004 		nforw = MIN(uvmadvice[ufi->entry->advice].nforw,
1005 			    ((ufi->entry->end - ufi->orig_rvaddr) >>
1006 			     PAGE_SHIFT) - 1);
1007 		flt->npages = nback + nforw + 1;
1008 		flt->centeridx = nback;
1009 
1010 		flt->narrow = true;	/* ensure only once per-fault */
1011 
1012 	} else {
1013 
1014 		/* narrow fault! */
1015 		nback = nforw = 0;
1016 		flt->startva = ufi->orig_rvaddr;
1017 		flt->npages = 1;
1018 		flt->centeridx = 0;
1019 
1020 	}
1021 	/* offset from entry's start to pgs' start */
1022 	const voff_t eoff = flt->startva - ufi->entry->start;
1023 
1024 	/* locked: maps(read) */
1025 	UVMHIST_LOG(maphist, "  narrow=%d, back=%d, forw=%d, startva=0x%x",
1026 		    flt->narrow, nback, nforw, flt->startva);
1027 	UVMHIST_LOG(maphist, "  entry=0x%x, amap=0x%x, obj=0x%x", ufi->entry,
1028 		    amap, uobj, 0);
1029 
1030 	/*
1031 	 * if we've got an amap, lock it and extract current anons.
1032 	 */
1033 
1034 	if (amap) {
1035 		amap_lock(amap);
1036 		amap_lookups(&ufi->entry->aref, eoff, *ranons, flt->npages);
1037 	} else {
1038 		*ranons = NULL;	/* to be safe */
1039 	}
1040 
1041 	/* locked: maps(read), amap(if there) */
1042 	KASSERT(amap == NULL || mutex_owned(&amap->am_l));
1043 
1044 	/*
1045 	 * for MADV_SEQUENTIAL mappings we want to deactivate the back pages
1046 	 * now and then forget about them (for the rest of the fault).
1047 	 */
1048 
1049 	if (ufi->entry->advice == MADV_SEQUENTIAL && nback != 0) {
1050 
1051 		UVMHIST_LOG(maphist, "  MADV_SEQUENTIAL: flushing backpages",
1052 		    0,0,0,0);
1053 		/* flush back-page anons? */
1054 		if (amap)
1055 			uvmfault_anonflush(*ranons, nback);
1056 
1057 		/* flush object? */
1058 		if (uobj) {
1059 			voff_t uoff;
1060 
1061 			uoff = ufi->entry->offset + eoff;
1062 			mutex_enter(&uobj->vmobjlock);
1063 			(void) (uobj->pgops->pgo_put)(uobj, uoff, uoff +
1064 				    (nback << PAGE_SHIFT), PGO_DEACTIVATE);
1065 		}
1066 
1067 		/* now forget about the backpages */
1068 		if (amap)
1069 			*ranons += nback;
1070 		flt->startva += (nback << PAGE_SHIFT);
1071 		flt->npages -= nback;
1072 		flt->centeridx = 0;
1073 	}
1074 	/*
1075 	 * => startva is fixed
1076 	 * => npages is fixed
1077 	 */
1078 	KASSERT(flt->startva <= ufi->orig_rvaddr);
1079 	KASSERT(ufi->orig_rvaddr + ufi->orig_size <=
1080 	    flt->startva + (flt->npages << PAGE_SHIFT));
1081 	return 0;
1082 }
1083 
1084 /*
1085  * uvm_fault_upper_lookup: look up existing h/w mapping and amap.
1086  *
1087  * iterate range of interest:
1088  *	1. check if h/w mapping exists.  if yes, we don't care
1089  *	2. check if anon exists.  if not, page is lower.
1090  *	3. if anon exists, enter h/w mapping for neighbors.
1091  *
1092  * => called with amap locked (if exists).
1093  */
1094 
1095 static int
1096 uvm_fault_upper_lookup(
1097 	struct uvm_faultinfo *ufi, const struct uvm_faultctx *flt,
1098 	struct vm_anon **anons, struct vm_page **pages)
1099 {
1100 	struct vm_amap *amap = ufi->entry->aref.ar_amap;
1101 	int lcv;
1102 	vaddr_t currva;
1103 	bool shadowed;
1104 	UVMHIST_FUNC("uvm_fault_upper_lookup"); UVMHIST_CALLED(maphist);
1105 
1106 	/* locked: maps(read), amap(if there) */
1107 	KASSERT(amap == NULL || mutex_owned(&amap->am_l));
1108 
1109 	/*
1110 	 * map in the backpages and frontpages we found in the amap in hopes
1111 	 * of preventing future faults.    we also init the pages[] array as
1112 	 * we go.
1113 	 */
1114 
1115 	currva = flt->startva;
1116 	shadowed = false;
1117 	for (lcv = 0; lcv < flt->npages; lcv++, currva += PAGE_SIZE) {
1118 		/*
1119 		 * don't play with VAs that are already mapped
1120 		 * (except for center)
1121 		 */
1122 		if (lcv != flt->centeridx &&
1123 		    pmap_extract(ufi->orig_map->pmap, currva, NULL)) {
1124 			pages[lcv] = PGO_DONTCARE;
1125 			continue;
1126 		}
1127 
1128 		/*
1129 		 * unmapped or center page.   check if any anon at this level.
1130 		 */
1131 		if (amap == NULL || anons[lcv] == NULL) {
1132 			pages[lcv] = NULL;
1133 			continue;
1134 		}
1135 
1136 		/*
1137 		 * check for present page and map if possible.   re-activate it.
1138 		 */
1139 
1140 		pages[lcv] = PGO_DONTCARE;
1141 		if (lcv == flt->centeridx) {	/* save center for later! */
1142 			shadowed = true;
1143 		} else {
1144 			struct vm_anon *anon = anons[lcv];
1145 
1146 			mutex_enter(&anon->an_lock);
1147 			struct vm_page *pg = anon->an_page;
1148 
1149 			/* ignore loaned and busy pages */
1150 			if (pg != NULL && pg->loan_count == 0 &&
1151 			    (pg->flags & PG_BUSY) == 0)
1152 				uvm_fault_upper_neighbor(ufi, flt, currva,
1153 				    pg, anon->an_ref > 1);
1154 			mutex_exit(&anon->an_lock);
1155 		}
1156 	}
1157 
1158 	/* locked: maps(read), amap(if there) */
1159 	KASSERT(amap == NULL || mutex_owned(&amap->am_l));
1160 	/* (shadowed == true) if there is an anon at the faulting address */
1161 	UVMHIST_LOG(maphist, "  shadowed=%d, will_get=%d", shadowed,
1162 	    (ufi->entry->object.uvm_obj && shadowed != false),0,0);
1163 
1164 	/*
1165 	 * note that if we are really short of RAM we could sleep in the above
1166 	 * call to pmap_enter with everything locked.   bad?
1167 	 *
1168 	 * XXX Actually, that is bad; pmap_enter() should just fail in that
1169 	 * XXX case.  --thorpej
1170 	 */
1171 
1172 	return 0;
1173 }
1174 
1175 /*
1176  * uvm_fault_upper_neighbor: enter single lower neighbor page.
1177  *
1178  * => called with amap and anon locked.
1179  */
1180 
1181 static void
1182 uvm_fault_upper_neighbor(
1183 	struct uvm_faultinfo *ufi, const struct uvm_faultctx *flt,
1184 	vaddr_t currva, struct vm_page *pg, bool readonly)
1185 {
1186 	UVMHIST_FUNC("uvm_fault_upper_neighbor"); UVMHIST_CALLED(maphist);
1187 
1188 	/* locked: amap, anon */
1189 
1190 	mutex_enter(&uvm_pageqlock);
1191 	uvm_pageenqueue(pg);
1192 	mutex_exit(&uvm_pageqlock);
1193 	UVMHIST_LOG(maphist,
1194 	    "  MAPPING: n anon: pm=0x%x, va=0x%x, pg=0x%x",
1195 	    ufi->orig_map->pmap, currva, pg, 0);
1196 	uvmexp.fltnamap++;
1197 
1198 	/*
1199 	 * Since this page isn't the page that's actually faulting,
1200 	 * ignore pmap_enter() failures; it's not critical that we
1201 	 * enter these right now.
1202 	 */
1203 
1204 	(void) pmap_enter(ufi->orig_map->pmap, currva,
1205 	    VM_PAGE_TO_PHYS(pg),
1206 	    readonly ? (flt->enter_prot & ~VM_PROT_WRITE) :
1207 	    flt->enter_prot,
1208 	    PMAP_CANFAIL | (flt->wire_mapping ? PMAP_WIRED : 0));
1209 
1210 	pmap_update(ufi->orig_map->pmap);
1211 }
1212 
1213 /*
1214  * uvm_fault_upper: handle upper fault.
1215  *
1216  *	1. acquire anon lock.
1217  *	2. get anon.  let uvmfault_anonget do the dirty work.
1218  *	3. handle loan.
1219  *	4. dispatch direct or promote handlers.
1220  */
1221 
1222 static int
1223 uvm_fault_upper(
1224 	struct uvm_faultinfo *ufi, struct uvm_faultctx *flt,
1225 	struct vm_anon **anons)
1226 {
1227 	struct vm_amap * const amap = ufi->entry->aref.ar_amap;
1228 	struct vm_anon * const anon = anons[flt->centeridx];
1229 	struct uvm_object *uobj;
1230 	int error;
1231 	UVMHIST_FUNC("uvm_fault_upper"); UVMHIST_CALLED(maphist);
1232 
1233 	/* locked: maps(read), amap */
1234 	KASSERT(mutex_owned(&amap->am_l));
1235 
1236 	/*
1237 	 * handle case 1: fault on an anon in our amap
1238 	 */
1239 
1240 	UVMHIST_LOG(maphist, "  case 1 fault: anon=0x%x", anon, 0,0,0);
1241 	mutex_enter(&anon->an_lock);
1242 
1243 	/* locked: maps(read), amap, anon */
1244 	KASSERT(mutex_owned(&amap->am_l));
1245 	KASSERT(mutex_owned(&anon->an_lock));
1246 
1247 	/*
1248 	 * no matter if we have case 1A or case 1B we are going to need to
1249 	 * have the anon's memory resident.   ensure that now.
1250 	 */
1251 
1252 	/*
1253 	 * let uvmfault_anonget do the dirty work.
1254 	 * if it fails (!OK) it will unlock everything for us.
1255 	 * if it succeeds, locks are still valid and locked.
1256 	 * also, if it is OK, then the anon's page is on the queues.
1257 	 * if the page is on loan from a uvm_object, then anonget will
1258 	 * lock that object for us if it does not fail.
1259 	 */
1260 
1261 	error = uvmfault_anonget(ufi, amap, anon);
1262 	switch (error) {
1263 	case 0:
1264 		break;
1265 
1266 	case ERESTART:
1267 		return ERESTART;
1268 
1269 	case EAGAIN:
1270 		kpause("fltagain1", false, hz/2, NULL);
1271 		return ERESTART;
1272 
1273 	default:
1274 		return error;
1275 	}
1276 
1277 	/*
1278 	 * uobj is non null if the page is on loan from an object (i.e. uobj)
1279 	 */
1280 
1281 	uobj = anon->an_page->uobject;	/* locked by anonget if !NULL */
1282 
1283 	/* locked: maps(read), amap, anon, uobj(if one) */
1284 	KASSERT(mutex_owned(&amap->am_l));
1285 	KASSERT(mutex_owned(&anon->an_lock));
1286 	KASSERT(uobj == NULL || mutex_owned(&uobj->vmobjlock));
1287 
1288 	/*
1289 	 * special handling for loaned pages
1290 	 */
1291 
1292 	if (anon->an_page->loan_count) {
1293 		error = uvm_fault_upper_loan(ufi, flt, anon, &uobj);
1294 		if (error != 0)
1295 			return error;
1296 	}
1297 
1298 	/*
1299 	 * if we are case 1B then we will need to allocate a new blank
1300 	 * anon to transfer the data into.   note that we have a lock
1301 	 * on anon, so no one can busy or release the page until we are done.
1302 	 * also note that the ref count can't drop to zero here because
1303 	 * it is > 1 and we are only dropping one ref.
1304 	 *
1305 	 * in the (hopefully very rare) case that we are out of RAM we
1306 	 * will unlock, wait for more RAM, and refault.
1307 	 *
1308 	 * if we are out of anon VM we kill the process (XXX: could wait?).
1309 	 */
1310 
1311 	if (flt->cow_now && anon->an_ref > 1) {
1312 		flt->promote = true;
1313 		error = uvm_fault_upper_promote(ufi, flt, uobj, anon);
1314 	} else {
1315 		error = uvm_fault_upper_direct(ufi, flt, uobj, anon);
1316 	}
1317 	return error;
1318 }
1319 
1320 /*
1321  * uvm_fault_upper_loan: handle loaned upper page.
1322  *
1323  *	1. if not cow'ing now, simply adjust flt->enter_prot.
1324  *	2. if cow'ing now, and if ref count is 1, break loan.
1325  */
1326 
1327 static int
1328 uvm_fault_upper_loan(
1329 	struct uvm_faultinfo *ufi, struct uvm_faultctx *flt,
1330 	struct vm_anon *anon, struct uvm_object **ruobj)
1331 {
1332 	struct vm_amap * const amap = ufi->entry->aref.ar_amap;
1333 	int error = 0;
1334 	UVMHIST_FUNC("uvm_fault_upper_loan"); UVMHIST_CALLED(maphist);
1335 
1336 	if (!flt->cow_now) {
1337 
1338 		/*
1339 		 * for read faults on loaned pages we just cap the
1340 		 * protection at read-only.
1341 		 */
1342 
1343 		flt->enter_prot = flt->enter_prot & ~VM_PROT_WRITE;
1344 
1345 	} else {
1346 		/*
1347 		 * note that we can't allow writes into a loaned page!
1348 		 *
1349 		 * if we have a write fault on a loaned page in an
1350 		 * anon then we need to look at the anon's ref count.
1351 		 * if it is greater than one then we are going to do
1352 		 * a normal copy-on-write fault into a new anon (this
1353 		 * is not a problem).  however, if the reference count
1354 		 * is one (a case where we would normally allow a
1355 		 * write directly to the page) then we need to kill
1356 		 * the loan before we continue.
1357 		 */
1358 
1359 		/* >1 case is already ok */
1360 		if (anon->an_ref == 1) {
1361 			error = uvm_loanbreak_anon(anon, *ruobj);
1362 			if (error != 0) {
1363 				uvmfault_unlockall(ufi, amap, *ruobj, anon);
1364 				uvm_wait("flt_noram2");
1365 				return ERESTART;
1366 			}
1367 			/* if we were a loan reciever uobj is gone */
1368 			if (*ruobj)
1369 				*ruobj = NULL;
1370 		}
1371 	}
1372 	return error;
1373 }
1374 
1375 /*
1376  * uvm_fault_upper_promote: promote upper page.
1377  *
1378  *	1. call uvmfault_promote.
1379  *	2. enqueue page.
1380  *	3. deref.
1381  *	4. pass page to uvm_fault_upper_enter.
1382  */
1383 
1384 static int
1385 uvm_fault_upper_promote(
1386 	struct uvm_faultinfo *ufi, struct uvm_faultctx *flt,
1387 	struct uvm_object *uobj, struct vm_anon *anon)
1388 {
1389 	struct vm_anon * const oanon = anon;
1390 	struct vm_page *pg;
1391 	int error;
1392 	UVMHIST_FUNC("uvm_fault_upper_promote"); UVMHIST_CALLED(maphist);
1393 
1394 	UVMHIST_LOG(maphist, "  case 1B: COW fault",0,0,0,0);
1395 	uvmexp.flt_acow++;
1396 
1397 	error = uvmfault_promote(ufi, oanon, PGO_DONTCARE, &anon,
1398 	    &flt->anon_spare);
1399 	switch (error) {
1400 	case 0:
1401 		break;
1402 	case ERESTART:
1403 		return ERESTART;
1404 	default:
1405 		return error;
1406 	}
1407 
1408 	pg = anon->an_page;
1409 	mutex_enter(&uvm_pageqlock);
1410 	uvm_pageactivate(pg);
1411 	mutex_exit(&uvm_pageqlock);
1412 	pg->flags &= ~(PG_BUSY|PG_FAKE);
1413 	UVM_PAGE_OWN(pg, NULL);
1414 
1415 	/* deref: can not drop to zero here by defn! */
1416 	oanon->an_ref--;
1417 
1418 	/*
1419 	 * note: oanon is still locked, as is the new anon.  we
1420 	 * need to check for this later when we unlock oanon; if
1421 	 * oanon != anon, we'll have to unlock anon, too.
1422 	 */
1423 
1424 	return uvm_fault_upper_enter(ufi, flt, uobj, anon, pg, oanon);
1425 }
1426 
1427 /*
1428  * uvm_fault_upper_direct: handle direct fault.
1429  */
1430 
1431 static int
1432 uvm_fault_upper_direct(
1433 	struct uvm_faultinfo *ufi, struct uvm_faultctx *flt,
1434 	struct uvm_object *uobj, struct vm_anon *anon)
1435 {
1436 	struct vm_anon * const oanon = anon;
1437 	struct vm_page *pg;
1438 	UVMHIST_FUNC("uvm_fault_upper_direct"); UVMHIST_CALLED(maphist);
1439 
1440 	uvmexp.flt_anon++;
1441 	pg = anon->an_page;
1442 	if (anon->an_ref > 1)     /* disallow writes to ref > 1 anons */
1443 		flt->enter_prot = flt->enter_prot & ~VM_PROT_WRITE;
1444 
1445 	return uvm_fault_upper_enter(ufi, flt, uobj, anon, pg, oanon);
1446 }
1447 
1448 /*
1449  * uvm_fault_upper_enter: enter h/w mapping of upper page.
1450  */
1451 
1452 static int
1453 uvm_fault_upper_enter(
1454 	struct uvm_faultinfo *ufi, const struct uvm_faultctx *flt,
1455 	struct uvm_object *uobj, struct vm_anon *anon, struct vm_page *pg,
1456 	struct vm_anon *oanon)
1457 {
1458 	struct vm_amap * const amap = ufi->entry->aref.ar_amap;
1459 	UVMHIST_FUNC("uvm_fault_upper_enter"); UVMHIST_CALLED(maphist);
1460 
1461 	/* locked: maps(read), amap, oanon, anon(if different from oanon) */
1462 	KASSERT(mutex_owned(&amap->am_l));
1463 	KASSERT(mutex_owned(&anon->an_lock));
1464 	KASSERT(mutex_owned(&oanon->an_lock));
1465 
1466 	/*
1467 	 * now map the page in.
1468 	 */
1469 
1470 	UVMHIST_LOG(maphist,
1471 	    "  MAPPING: anon: pm=0x%x, va=0x%x, pg=0x%x, promote=%d",
1472 	    ufi->orig_map->pmap, ufi->orig_rvaddr, pg, flt->promote);
1473 	if (pmap_enter(ufi->orig_map->pmap, ufi->orig_rvaddr,
1474 	    VM_PAGE_TO_PHYS(pg),
1475 	    flt->enter_prot, flt->access_type | PMAP_CANFAIL |
1476 	    (flt->wire_mapping ? PMAP_WIRED : 0)) != 0) {
1477 
1478 		/*
1479 		 * No need to undo what we did; we can simply think of
1480 		 * this as the pmap throwing away the mapping information.
1481 		 *
1482 		 * We do, however, have to go through the ReFault path,
1483 		 * as the map may change while we're asleep.
1484 		 */
1485 
1486 		if (anon != oanon)
1487 			mutex_exit(&anon->an_lock);
1488 		uvmfault_unlockall(ufi, amap, uobj, oanon);
1489 		if (!uvm_reclaimable()) {
1490 			UVMHIST_LOG(maphist,
1491 			    "<- failed.  out of VM",0,0,0,0);
1492 			/* XXX instrumentation */
1493 			return ENOMEM;
1494 		}
1495 		/* XXX instrumentation */
1496 		uvm_wait("flt_pmfail1");
1497 		return ERESTART;
1498 	}
1499 
1500 	uvm_fault_upper_done(ufi, flt, anon, pg);
1501 
1502 	/*
1503 	 * done case 1!  finish up by unlocking everything and returning success
1504 	 */
1505 
1506 	if (anon != oanon) {
1507 		mutex_exit(&anon->an_lock);
1508 	}
1509 	pmap_update(ufi->orig_map->pmap);
1510 	uvmfault_unlockall(ufi, amap, uobj, oanon);
1511 	return 0;
1512 }
1513 
1514 /*
1515  * uvm_fault_upper_done: queue upper center page.
1516  */
1517 
1518 static void
1519 uvm_fault_upper_done(
1520 	struct uvm_faultinfo *ufi, const struct uvm_faultctx *flt,
1521 	struct vm_anon *anon, struct vm_page *pg)
1522 {
1523 	const bool wire_paging = flt->wire_paging;
1524 
1525 	UVMHIST_FUNC("uvm_fault_upper_done"); UVMHIST_CALLED(maphist);
1526 
1527 	/*
1528 	 * ... update the page queues.
1529 	 */
1530 
1531 	mutex_enter(&uvm_pageqlock);
1532 	if (wire_paging) {
1533 		uvm_pagewire(pg);
1534 
1535 		/*
1536 		 * since the now-wired page cannot be paged out,
1537 		 * release its swap resources for others to use.
1538 		 * since an anon with no swap cannot be PG_CLEAN,
1539 		 * clear its clean flag now.
1540 		 */
1541 
1542 		pg->flags &= ~(PG_CLEAN);
1543 
1544 	} else {
1545 		uvm_pageactivate(pg);
1546 	}
1547 	mutex_exit(&uvm_pageqlock);
1548 
1549 	if (wire_paging) {
1550 		uvm_anon_dropswap(anon);
1551 	}
1552 }
1553 
1554 /*
1555  * uvm_fault_lower: handle lower fault.
1556  *
1557  *	1. check uobj
1558  *	1.1. if null, ZFOD.
1559  *	1.2. if not null, look up unnmapped neighbor pages.
1560  *	2. for center page, check if promote.
1561  *	2.1. ZFOD always needs promotion.
1562  *	2.2. other uobjs, when entry is marked COW (usually MAP_PRIVATE vnode).
1563  *	3. if uobj is not ZFOD and page is not found, do i/o.
1564  *	4. dispatch either direct / promote fault.
1565  */
1566 
1567 static int
1568 uvm_fault_lower(
1569 	struct uvm_faultinfo *ufi, struct uvm_faultctx *flt,
1570 	struct vm_page **pages)
1571 {
1572 #ifdef DIAGNOSTIC
1573 	struct vm_amap *amap = ufi->entry->aref.ar_amap;
1574 #endif
1575 	struct uvm_object *uobj = ufi->entry->object.uvm_obj;
1576 	struct vm_page *uobjpage;
1577 	int error;
1578 	UVMHIST_FUNC("uvm_fault_lower"); UVMHIST_CALLED(maphist);
1579 
1580 	/* locked: maps(read), amap(if there), uobj(if !null) */
1581 
1582 	/*
1583 	 * now, if the desired page is not shadowed by the amap and we have
1584 	 * a backing object that does not have a special fault routine, then
1585 	 * we ask (with pgo_get) the object for resident pages that we care
1586 	 * about and attempt to map them in.  we do not let pgo_get block
1587 	 * (PGO_LOCKED).
1588 	 */
1589 
1590 	if (uobj == NULL) {
1591 		/* zero fill; don't care neighbor pages */
1592 		uobjpage = NULL;
1593 	} else {
1594 		uvm_fault_lower_lookup(ufi, flt, pages);
1595 		uobjpage = pages[flt->centeridx];
1596 	}
1597 
1598 	/*
1599 	 * note that at this point we are done with any front or back pages.
1600 	 * we are now going to focus on the center page (i.e. the one we've
1601 	 * faulted on).  if we have faulted on the upper (anon) layer
1602 	 * [i.e. case 1], then the anon we want is anons[centeridx] (we have
1603 	 * not touched it yet).  if we have faulted on the bottom (uobj)
1604 	 * layer [i.e. case 2] and the page was both present and available,
1605 	 * then we've got a pointer to it as "uobjpage" and we've already
1606 	 * made it BUSY.
1607 	 */
1608 
1609 	/*
1610 	 * locked:
1611 	 * maps(read), amap(if there), uobj(if !null), uobjpage(if !null)
1612 	 */
1613 	KASSERT(amap == NULL || mutex_owned(&amap->am_l));
1614 	KASSERT(uobj == NULL || mutex_owned(&uobj->vmobjlock));
1615 	KASSERT(uobjpage == NULL || (uobjpage->flags & PG_BUSY) != 0);
1616 
1617 	/*
1618 	 * note that uobjpage can not be PGO_DONTCARE at this point.  we now
1619 	 * set uobjpage to PGO_DONTCARE if we are doing a zero fill.  if we
1620 	 * have a backing object, check and see if we are going to promote
1621 	 * the data up to an anon during the fault.
1622 	 */
1623 
1624 	if (uobj == NULL) {
1625 		uobjpage = PGO_DONTCARE;
1626 		flt->promote = true;		/* always need anon here */
1627 	} else {
1628 		KASSERT(uobjpage != PGO_DONTCARE);
1629 		flt->promote = flt->cow_now && UVM_ET_ISCOPYONWRITE(ufi->entry);
1630 	}
1631 	UVMHIST_LOG(maphist, "  case 2 fault: promote=%d, zfill=%d",
1632 	    flt->promote, (uobj == NULL), 0,0);
1633 
1634 	/*
1635 	 * if uobjpage is not null then we do not need to do I/O to get the
1636 	 * uobjpage.
1637 	 *
1638 	 * if uobjpage is null, then we need to unlock and ask the pager to
1639 	 * get the data for us.   once we have the data, we need to reverify
1640 	 * the state the world.   we are currently not holding any resources.
1641 	 */
1642 
1643 	if (uobjpage) {
1644 		/* update rusage counters */
1645 		curlwp->l_ru.ru_minflt++;
1646 	} else {
1647 		error = uvm_fault_lower_io(ufi, flt, &uobj, &uobjpage);
1648 		if (error != 0)
1649 			return error;
1650 	}
1651 
1652 	/*
1653 	 * locked:
1654 	 * maps(read), amap(if !null), uobj(if !null), uobjpage(if uobj)
1655 	 */
1656 	KASSERT(amap == NULL || mutex_owned(&amap->am_l));
1657 	KASSERT(uobj == NULL || mutex_owned(&uobj->vmobjlock));
1658 	KASSERT(uobj == NULL || (uobjpage->flags & PG_BUSY) != 0);
1659 
1660 	/*
1661 	 * notes:
1662 	 *  - at this point uobjpage can not be NULL
1663 	 *  - at this point uobjpage can not be PG_RELEASED (since we checked
1664 	 *  for it above)
1665 	 *  - at this point uobjpage could be PG_WANTED (handle later)
1666 	 */
1667 
1668 	KASSERT(uobjpage != NULL);
1669 	KASSERT(uobj == NULL || uobj == uobjpage->uobject);
1670 	KASSERT(uobj == NULL || !UVM_OBJ_IS_CLEAN(uobjpage->uobject) ||
1671 	    (uobjpage->flags & PG_CLEAN) != 0);
1672 
1673 	if (!flt->promote) {
1674 		error = uvm_fault_lower_direct(ufi, flt, uobj, uobjpage);
1675 	} else {
1676 		error = uvm_fault_lower_promote(ufi, flt, uobj, uobjpage);
1677 	}
1678 	return error;
1679 }
1680 
1681 /*
1682  * uvm_fault_lower_lookup: look up on-memory uobj pages.
1683  *
1684  *	1. get on-memory pages.
1685  *	2. if failed, give up (get only center page later).
1686  *	3. if succeeded, enter h/w mapping of neighbor pages.
1687  */
1688 
1689 static void
1690 uvm_fault_lower_lookup(
1691 	struct uvm_faultinfo *ufi, const struct uvm_faultctx *flt,
1692 	struct vm_page **pages)
1693 {
1694 	struct uvm_object *uobj = ufi->entry->object.uvm_obj;
1695 	int lcv, gotpages;
1696 	vaddr_t currva;
1697 	UVMHIST_FUNC("uvm_fault_lower_lookup"); UVMHIST_CALLED(maphist);
1698 
1699 	mutex_enter(&uobj->vmobjlock);
1700 	/* locked: maps(read), amap(if there), uobj */
1701 	/*
1702 	 * the following call to pgo_get does _not_ change locking state
1703 	 */
1704 
1705 	uvmexp.fltlget++;
1706 	gotpages = flt->npages;
1707 	(void) uobj->pgops->pgo_get(uobj,
1708 	    ufi->entry->offset + flt->startva - ufi->entry->start,
1709 	    pages, &gotpages, flt->centeridx,
1710 	    flt->access_type & MASK(ufi->entry), ufi->entry->advice, PGO_LOCKED);
1711 
1712 	/*
1713 	 * check for pages to map, if we got any
1714 	 */
1715 
1716 	if (gotpages == 0) {
1717 		pages[flt->centeridx] = NULL;
1718 		return;
1719 	}
1720 
1721 	currva = flt->startva;
1722 	for (lcv = 0; lcv < flt->npages; lcv++, currva += PAGE_SIZE) {
1723 		struct vm_page *curpg;
1724 
1725 		curpg = pages[lcv];
1726 		if (curpg == NULL || curpg == PGO_DONTCARE) {
1727 			continue;
1728 		}
1729 		KASSERT(curpg->uobject == uobj);
1730 
1731 		/*
1732 		 * if center page is resident and not PG_BUSY|PG_RELEASED
1733 		 * then pgo_get made it PG_BUSY for us and gave us a handle
1734 		 * to it.
1735 		 */
1736 
1737 		if (lcv == flt->centeridx) {
1738 			UVMHIST_LOG(maphist, "  got uobjpage "
1739 			    "(0x%x) with locked get",
1740 			    curpg, 0,0,0);
1741 		} else {
1742 			bool readonly = (curpg->flags & PG_RDONLY)
1743 			    || (curpg->loan_count > 0)
1744 			    || UVM_OBJ_NEEDS_WRITEFAULT(curpg->uobject);
1745 
1746 			uvm_fault_lower_neighbor(ufi, flt,
1747 			    currva, curpg, readonly);
1748 		}
1749 	}
1750 	pmap_update(ufi->orig_map->pmap);
1751 }
1752 
1753 /*
1754  * uvm_fault_lower_neighbor: enter h/w mapping of lower neighbor page.
1755  */
1756 
1757 static void
1758 uvm_fault_lower_neighbor(
1759 	struct uvm_faultinfo *ufi, const struct uvm_faultctx *flt,
1760 	vaddr_t currva, struct vm_page *pg, bool readonly)
1761 {
1762 	UVMHIST_FUNC("uvm_fault_lower_neighor"); UVMHIST_CALLED(maphist);
1763 
1764 	/* locked: maps(read), amap(if there), uobj */
1765 
1766 	/*
1767 	 * calling pgo_get with PGO_LOCKED returns us pages which
1768 	 * are neither busy nor released, so we don't need to check
1769 	 * for this.  we can just directly enter the pages.
1770 	 */
1771 
1772 	mutex_enter(&uvm_pageqlock);
1773 	uvm_pageenqueue(pg);
1774 	mutex_exit(&uvm_pageqlock);
1775 	UVMHIST_LOG(maphist,
1776 	    "  MAPPING: n obj: pm=0x%x, va=0x%x, pg=0x%x",
1777 	    ufi->orig_map->pmap, currva, pg, 0);
1778 	uvmexp.fltnomap++;
1779 
1780 	/*
1781 	 * Since this page isn't the page that's actually faulting,
1782 	 * ignore pmap_enter() failures; it's not critical that we
1783 	 * enter these right now.
1784 	 * NOTE: page can't be PG_WANTED or PG_RELEASED because we've
1785 	 * held the lock the whole time we've had the handle.
1786 	 */
1787 	KASSERT((pg->flags & PG_PAGEOUT) == 0);
1788 	KASSERT((pg->flags & PG_RELEASED) == 0);
1789 	KASSERT((pg->flags & PG_WANTED) == 0);
1790 	KASSERT(!UVM_OBJ_IS_CLEAN(pg->uobject) ||
1791 	    (pg->flags & PG_CLEAN) != 0);
1792 	pg->flags &= ~(PG_BUSY);
1793 	UVM_PAGE_OWN(pg, NULL);
1794 
1795 	(void) pmap_enter(ufi->orig_map->pmap, currva,
1796 	    VM_PAGE_TO_PHYS(pg),
1797 	    readonly ? (flt->enter_prot & ~VM_PROT_WRITE) :
1798 	    flt->enter_prot & MASK(ufi->entry),
1799 	    PMAP_CANFAIL | (flt->wire_mapping ? PMAP_WIRED : 0));
1800 }
1801 
1802 /*
1803  * uvm_fault_lower_io: get lower page from backing store.
1804  *
1805  *	1. unlock everything, because i/o will block.
1806  *	2. call pgo_get.
1807  *	3. if failed, recover.
1808  *	4. if succeeded, relock everything and verify things.
1809  */
1810 
1811 static int
1812 uvm_fault_lower_io(
1813 	struct uvm_faultinfo *ufi, const struct uvm_faultctx *flt,
1814 	struct uvm_object **ruobj, struct vm_page **ruobjpage)
1815 {
1816 	struct vm_amap * const amap = ufi->entry->aref.ar_amap;
1817 	struct uvm_object *uobj = *ruobj;
1818 	struct vm_page *pg;
1819 	bool locked;
1820 	int gotpages;
1821 	int error;
1822 	voff_t uoff;
1823 	UVMHIST_FUNC("uvm_fault_lower_io"); UVMHIST_CALLED(maphist);
1824 
1825 	/* update rusage counters */
1826 	curlwp->l_ru.ru_majflt++;
1827 
1828 	/* locked: maps(read), amap(if there), uobj */
1829 	uvmfault_unlockall(ufi, amap, NULL, NULL);
1830 	/* locked: uobj */
1831 
1832 	uvmexp.fltget++;
1833 	gotpages = 1;
1834 	pg = NULL;
1835 	uoff = (ufi->orig_rvaddr - ufi->entry->start) + ufi->entry->offset;
1836 	error = uobj->pgops->pgo_get(uobj, uoff, &pg, &gotpages,
1837 	    0, flt->access_type & MASK(ufi->entry), ufi->entry->advice,
1838 	    PGO_SYNCIO);
1839 	/* locked: pg(if no error) */
1840 
1841 	/*
1842 	 * recover from I/O
1843 	 */
1844 
1845 	if (error) {
1846 		if (error == EAGAIN) {
1847 			UVMHIST_LOG(maphist,
1848 			    "  pgo_get says TRY AGAIN!",0,0,0,0);
1849 			kpause("fltagain2", false, hz/2, NULL);
1850 			return ERESTART;
1851 		}
1852 
1853 #if 0
1854 		KASSERT(error != ERESTART);
1855 #else
1856 		/* XXXUEBS don't re-fault? */
1857 		if (error == ERESTART)
1858 			error = EIO;
1859 #endif
1860 
1861 		UVMHIST_LOG(maphist, "<- pgo_get failed (code %d)",
1862 		    error, 0,0,0);
1863 		return error;
1864 	}
1865 
1866 	/* locked: pg */
1867 
1868 	KASSERT((pg->flags & PG_BUSY) != 0);
1869 
1870 	mutex_enter(&uvm_pageqlock);
1871 	uvm_pageactivate(pg);
1872 	mutex_exit(&uvm_pageqlock);
1873 
1874 	/*
1875 	 * re-verify the state of the world by first trying to relock
1876 	 * the maps.  always relock the object.
1877 	 */
1878 
1879 	locked = uvmfault_relock(ufi);
1880 	if (locked && amap)
1881 		amap_lock(amap);
1882 
1883 	/* might be changed */
1884 	uobj = pg->uobject;
1885 
1886 	mutex_enter(&uobj->vmobjlock);
1887 
1888 	/* locked(locked): maps(read), amap(if !null), uobj, pg */
1889 	/* locked(!locked): uobj, pg */
1890 
1891 	/*
1892 	 * verify that the page has not be released and re-verify
1893 	 * that amap slot is still free.   if there is a problem,
1894 	 * we unlock and clean up.
1895 	 */
1896 
1897 	if ((pg->flags & PG_RELEASED) != 0 ||
1898 	    (locked && amap && amap_lookup(&ufi->entry->aref,
1899 	      ufi->orig_rvaddr - ufi->entry->start))) {
1900 		if (locked)
1901 			uvmfault_unlockall(ufi, amap, NULL, NULL);
1902 		locked = false;
1903 	}
1904 
1905 	/*
1906 	 * didn't get the lock?   release the page and retry.
1907 	 */
1908 
1909 	if (locked == false) {
1910 		UVMHIST_LOG(maphist,
1911 		    "  wasn't able to relock after fault: retry",
1912 		    0,0,0,0);
1913 		if (pg->flags & PG_WANTED) {
1914 			wakeup(pg);
1915 		}
1916 		if (pg->flags & PG_RELEASED) {
1917 			uvmexp.fltpgrele++;
1918 			uvm_pagefree(pg);
1919 			mutex_exit(&uobj->vmobjlock);
1920 			return ERESTART;
1921 		}
1922 		pg->flags &= ~(PG_BUSY|PG_WANTED);
1923 		UVM_PAGE_OWN(pg, NULL);
1924 		mutex_exit(&uobj->vmobjlock);
1925 		return ERESTART;
1926 	}
1927 
1928 	/*
1929 	 * we have the data in pg which is busy and
1930 	 * not released.  we are holding object lock (so the page
1931 	 * can't be released on us).
1932 	 */
1933 
1934 	/* locked: maps(read), amap(if !null), uobj, pg */
1935 
1936 	*ruobj = uobj;
1937 	*ruobjpage = pg;
1938 	return 0;
1939 }
1940 
1941 /*
1942  * uvm_fault_lower_direct: fault lower center page
1943  *
1944  *	1. adjust flt->enter_prot.
1945  *	2. if page is loaned, resolve.
1946  */
1947 
1948 int
1949 uvm_fault_lower_direct(
1950 	struct uvm_faultinfo *ufi, struct uvm_faultctx *flt,
1951 	struct uvm_object *uobj, struct vm_page *uobjpage)
1952 {
1953 	struct vm_page *pg;
1954 	UVMHIST_FUNC("uvm_fault_lower_direct"); UVMHIST_CALLED(maphist);
1955 
1956 	/*
1957 	 * we are not promoting.   if the mapping is COW ensure that we
1958 	 * don't give more access than we should (e.g. when doing a read
1959 	 * fault on a COPYONWRITE mapping we want to map the COW page in
1960 	 * R/O even though the entry protection could be R/W).
1961 	 *
1962 	 * set "pg" to the page we want to map in (uobjpage, usually)
1963 	 */
1964 
1965 	uvmexp.flt_obj++;
1966 	if (UVM_ET_ISCOPYONWRITE(ufi->entry) ||
1967 	    UVM_OBJ_NEEDS_WRITEFAULT(uobjpage->uobject))
1968 		flt->enter_prot &= ~VM_PROT_WRITE;
1969 	pg = uobjpage;		/* map in the actual object */
1970 
1971 	KASSERT(uobjpage != PGO_DONTCARE);
1972 
1973 	/*
1974 	 * we are faulting directly on the page.   be careful
1975 	 * about writing to loaned pages...
1976 	 */
1977 
1978 	if (uobjpage->loan_count) {
1979 		uvm_fault_lower_direct_loan(ufi, flt, uobj, &pg, &uobjpage);
1980 	}
1981 	KASSERT(pg == uobjpage);
1982 
1983 	return uvm_fault_lower_enter(ufi, flt, uobj, NULL, pg, uobjpage);
1984 }
1985 
1986 /*
1987  * uvm_fault_lower_direct_loan: resolve loaned page.
1988  *
1989  *	1. if not cow'ing, adjust flt->enter_prot.
1990  *	2. if cow'ing, break loan.
1991  */
1992 
1993 static int
1994 uvm_fault_lower_direct_loan(
1995 	struct uvm_faultinfo *ufi, struct uvm_faultctx *flt,
1996 	struct uvm_object *uobj, struct vm_page **rpg,
1997 	struct vm_page **ruobjpage)
1998 {
1999 	struct vm_amap * const amap = ufi->entry->aref.ar_amap;
2000 	struct vm_page *pg;
2001 	struct vm_page *uobjpage = *ruobjpage;
2002 	UVMHIST_FUNC("uvm_fault_lower_direct_loan"); UVMHIST_CALLED(maphist);
2003 
2004 	if (!flt->cow_now) {
2005 		/* read fault: cap the protection at readonly */
2006 		/* cap! */
2007 		flt->enter_prot = flt->enter_prot & ~VM_PROT_WRITE;
2008 	} else {
2009 		/* write fault: must break the loan here */
2010 
2011 		pg = uvm_loanbreak(uobjpage);
2012 		if (pg == NULL) {
2013 
2014 			/*
2015 			 * drop ownership of page, it can't be released
2016 			 */
2017 
2018 			if (uobjpage->flags & PG_WANTED)
2019 				wakeup(uobjpage);
2020 			uobjpage->flags &= ~(PG_BUSY|PG_WANTED);
2021 			UVM_PAGE_OWN(uobjpage, NULL);
2022 
2023 			uvmfault_unlockall(ufi, amap, uobj, NULL);
2024 			UVMHIST_LOG(maphist,
2025 			  "  out of RAM breaking loan, waiting",
2026 			  0,0,0,0);
2027 			uvmexp.fltnoram++;
2028 			uvm_wait("flt_noram4");
2029 			return ERESTART;
2030 		}
2031 		*rpg = pg;
2032 		*ruobjpage = pg;
2033 	}
2034 	return 0;
2035 }
2036 
2037 /*
2038  * uvm_fault_lower_promote: promote lower page.
2039  *
2040  *	1. call uvmfault_promote.
2041  *	2. fill in data.
2042  *	3. if not ZFOD, dispose old page.
2043  */
2044 
2045 int
2046 uvm_fault_lower_promote(
2047 	struct uvm_faultinfo *ufi, struct uvm_faultctx *flt,
2048 	struct uvm_object *uobj, struct vm_page *uobjpage)
2049 {
2050 	struct vm_amap * const amap = ufi->entry->aref.ar_amap;
2051 	struct vm_anon *anon;
2052 	struct vm_page *pg;
2053 	int error;
2054 	UVMHIST_FUNC("uvm_fault_lower_promote"); UVMHIST_CALLED(maphist);
2055 
2056 	/*
2057 	 * if we are going to promote the data to an anon we
2058 	 * allocate a blank anon here and plug it into our amap.
2059 	 */
2060 #if DIAGNOSTIC
2061 	if (amap == NULL)
2062 		panic("uvm_fault: want to promote data, but no anon");
2063 #endif
2064 	error = uvmfault_promote(ufi, NULL, uobjpage,
2065 	    &anon, &flt->anon_spare);
2066 	switch (error) {
2067 	case 0:
2068 		break;
2069 	case ERESTART:
2070 		return ERESTART;
2071 	default:
2072 		return error;
2073 	}
2074 
2075 	pg = anon->an_page;
2076 
2077 	/*
2078 	 * fill in the data
2079 	 */
2080 
2081 	if (uobjpage != PGO_DONTCARE) {
2082 		uvmexp.flt_prcopy++;
2083 
2084 		/*
2085 		 * promote to shared amap?  make sure all sharing
2086 		 * procs see it
2087 		 */
2088 
2089 		if ((amap_flags(amap) & AMAP_SHARED) != 0) {
2090 			pmap_page_protect(uobjpage, VM_PROT_NONE);
2091 			/*
2092 			 * XXX: PAGE MIGHT BE WIRED!
2093 			 */
2094 		}
2095 
2096 		/*
2097 		 * dispose of uobjpage.  it can't be PG_RELEASED
2098 		 * since we still hold the object lock.
2099 		 * drop handle to uobj as well.
2100 		 */
2101 
2102 		if (uobjpage->flags & PG_WANTED)
2103 			/* still have the obj lock */
2104 			wakeup(uobjpage);
2105 		uobjpage->flags &= ~(PG_BUSY|PG_WANTED);
2106 		UVM_PAGE_OWN(uobjpage, NULL);
2107 		mutex_exit(&uobj->vmobjlock);
2108 		uobj = NULL;
2109 
2110 		UVMHIST_LOG(maphist,
2111 		    "  promote uobjpage 0x%x to anon/page 0x%x/0x%x",
2112 		    uobjpage, anon, pg, 0);
2113 
2114 	} else {
2115 		uvmexp.flt_przero++;
2116 
2117 		/*
2118 		 * Page is zero'd and marked dirty by
2119 		 * uvmfault_promote().
2120 		 */
2121 
2122 		UVMHIST_LOG(maphist,"  zero fill anon/page 0x%x/0%x",
2123 		    anon, pg, 0, 0);
2124 	}
2125 
2126 	return uvm_fault_lower_enter(ufi, flt, uobj, anon, pg, uobjpage);
2127 }
2128 
2129 /*
2130  * uvm_fault_lower_enter: enter h/w mapping of lower page.
2131  */
2132 
2133 int
2134 uvm_fault_lower_enter(
2135 	struct uvm_faultinfo *ufi, const struct uvm_faultctx *flt,
2136 	struct uvm_object *uobj,
2137 	struct vm_anon *anon, struct vm_page *pg, struct vm_page *uobjpage)
2138 {
2139 	struct vm_amap * const amap = ufi->entry->aref.ar_amap;
2140 	int error;
2141 	UVMHIST_FUNC("uvm_fault_lower_enter"); UVMHIST_CALLED(maphist);
2142 
2143 	/*
2144 	 * locked:
2145 	 * maps(read), amap(if !null), uobj(if !null), uobjpage(if uobj),
2146 	 *   anon(if !null), pg(if anon)
2147 	 *
2148 	 * note: pg is either the uobjpage or the new page in the new anon
2149 	 */
2150 	KASSERT(amap == NULL || mutex_owned(&amap->am_l));
2151 	KASSERT(uobj == NULL || mutex_owned(&uobj->vmobjlock));
2152 	KASSERT(uobj == NULL || (uobjpage->flags & PG_BUSY) != 0);
2153 	KASSERT(anon == NULL || mutex_owned(&anon->an_lock));
2154 	KASSERT((pg->flags & PG_BUSY) != 0);
2155 
2156 	/*
2157 	 * all resources are present.   we can now map it in and free our
2158 	 * resources.
2159 	 */
2160 
2161 	UVMHIST_LOG(maphist,
2162 	    "  MAPPING: case2: pm=0x%x, va=0x%x, pg=0x%x, promote=%d",
2163 	    ufi->orig_map->pmap, ufi->orig_rvaddr, pg, flt->promote);
2164 	KASSERT((flt->access_type & VM_PROT_WRITE) == 0 ||
2165 		(pg->flags & PG_RDONLY) == 0);
2166 	if (pmap_enter(ufi->orig_map->pmap, ufi->orig_rvaddr,
2167 	    VM_PAGE_TO_PHYS(pg),
2168 	    (pg->flags & PG_RDONLY) != 0 ?
2169 	    flt->enter_prot & ~VM_PROT_WRITE : flt->enter_prot,
2170 	    flt->access_type | PMAP_CANFAIL |
2171 	    (flt->wire_mapping ? PMAP_WIRED : 0)) != 0) {
2172 
2173 		/*
2174 		 * No need to undo what we did; we can simply think of
2175 		 * this as the pmap throwing away the mapping information.
2176 		 *
2177 		 * We do, however, have to go through the ReFault path,
2178 		 * as the map may change while we're asleep.
2179 		 */
2180 
2181 		if (pg->flags & PG_WANTED)
2182 			wakeup(pg);
2183 
2184 		/*
2185 		 * note that pg can't be PG_RELEASED since we did not drop
2186 		 * the object lock since the last time we checked.
2187 		 */
2188 		KASSERT((pg->flags & PG_RELEASED) == 0);
2189 
2190 		pg->flags &= ~(PG_BUSY|PG_FAKE|PG_WANTED);
2191 		UVM_PAGE_OWN(pg, NULL);
2192 
2193 		uvmfault_unlockall(ufi, amap, uobj, anon);
2194 		if (!uvm_reclaimable()) {
2195 			UVMHIST_LOG(maphist,
2196 			    "<- failed.  out of VM",0,0,0,0);
2197 			/* XXX instrumentation */
2198 			error = ENOMEM;
2199 			return error;
2200 		}
2201 		/* XXX instrumentation */
2202 		uvm_wait("flt_pmfail2");
2203 		return ERESTART;
2204 	}
2205 
2206 	uvm_fault_lower_done(ufi, flt, uobj, pg);
2207 
2208 	/*
2209 	 * note that pg can't be PG_RELEASED since we did not drop the object
2210 	 * lock since the last time we checked.
2211 	 */
2212 	KASSERT((pg->flags & PG_RELEASED) == 0);
2213 	if (pg->flags & PG_WANTED)
2214 		wakeup(pg);
2215 	pg->flags &= ~(PG_BUSY|PG_FAKE|PG_WANTED);
2216 	UVM_PAGE_OWN(pg, NULL);
2217 
2218 	pmap_update(ufi->orig_map->pmap);
2219 	uvmfault_unlockall(ufi, amap, uobj, anon);
2220 
2221 	UVMHIST_LOG(maphist, "<- done (SUCCESS!)",0,0,0,0);
2222 	return 0;
2223 }
2224 
2225 /*
2226  * uvm_fault_lower_done: queue lower center page.
2227  */
2228 
2229 void
2230 uvm_fault_lower_done(
2231 	struct uvm_faultinfo *ufi, const struct uvm_faultctx *flt,
2232 	struct uvm_object *uobj, struct vm_page *pg)
2233 {
2234 	bool dropswap = false;
2235 
2236 	UVMHIST_FUNC("uvm_fault_lower_done"); UVMHIST_CALLED(maphist);
2237 
2238 	mutex_enter(&uvm_pageqlock);
2239 	if (flt->wire_paging) {
2240 		uvm_pagewire(pg);
2241 		if (pg->pqflags & PQ_AOBJ) {
2242 
2243 			/*
2244 			 * since the now-wired page cannot be paged out,
2245 			 * release its swap resources for others to use.
2246 			 * since an aobj page with no swap cannot be PG_CLEAN,
2247 			 * clear its clean flag now.
2248 			 */
2249 
2250 			KASSERT(uobj != NULL);
2251 			pg->flags &= ~(PG_CLEAN);
2252 			dropswap = true;
2253 		}
2254 	} else {
2255 		uvm_pageactivate(pg);
2256 	}
2257 	mutex_exit(&uvm_pageqlock);
2258 
2259 	if (dropswap) {
2260 		uao_dropswap(uobj, pg->offset >> PAGE_SHIFT);
2261 	}
2262 }
2263 
2264 
2265 /*
2266  * uvm_fault_wire: wire down a range of virtual addresses in a map.
2267  *
2268  * => map may be read-locked by caller, but MUST NOT be write-locked.
2269  * => if map is read-locked, any operations which may cause map to
2270  *	be write-locked in uvm_fault() must be taken care of by
2271  *	the caller.  See uvm_map_pageable().
2272  */
2273 
2274 int
2275 uvm_fault_wire(struct vm_map *map, vaddr_t start, vaddr_t end,
2276     vm_prot_t access_type, int maxprot)
2277 {
2278 	vaddr_t va;
2279 	int error;
2280 
2281 	/*
2282 	 * now fault it in a page at a time.   if the fault fails then we have
2283 	 * to undo what we have done.   note that in uvm_fault VM_PROT_NONE
2284 	 * is replaced with the max protection if fault_type is VM_FAULT_WIRE.
2285 	 */
2286 
2287 	/*
2288 	 * XXX work around overflowing a vaddr_t.  this prevents us from
2289 	 * wiring the last page in the address space, though.
2290 	 */
2291 	if (start > end) {
2292 		return EFAULT;
2293 	}
2294 
2295 	for (va = start; va < end; va += PAGE_SIZE) {
2296 		error = uvm_fault_internal(map, va, access_type,
2297 		    (maxprot ? UVM_FAULT_MAXPROT : 0) | UVM_FAULT_WIRE);
2298 		if (error) {
2299 			if (va != start) {
2300 				uvm_fault_unwire(map, start, va);
2301 			}
2302 			return error;
2303 		}
2304 	}
2305 	return 0;
2306 }
2307 
2308 /*
2309  * uvm_fault_unwire(): unwire range of virtual space.
2310  */
2311 
2312 void
2313 uvm_fault_unwire(struct vm_map *map, vaddr_t start, vaddr_t end)
2314 {
2315 	vm_map_lock_read(map);
2316 	uvm_fault_unwire_locked(map, start, end);
2317 	vm_map_unlock_read(map);
2318 }
2319 
2320 /*
2321  * uvm_fault_unwire_locked(): the guts of uvm_fault_unwire().
2322  *
2323  * => map must be at least read-locked.
2324  */
2325 
2326 void
2327 uvm_fault_unwire_locked(struct vm_map *map, vaddr_t start, vaddr_t end)
2328 {
2329 	struct vm_map_entry *entry;
2330 	pmap_t pmap = vm_map_pmap(map);
2331 	vaddr_t va;
2332 	paddr_t pa;
2333 	struct vm_page *pg;
2334 
2335 	KASSERT((map->flags & VM_MAP_INTRSAFE) == 0);
2336 
2337 	/*
2338 	 * we assume that the area we are unwiring has actually been wired
2339 	 * in the first place.   this means that we should be able to extract
2340 	 * the PAs from the pmap.   we also lock out the page daemon so that
2341 	 * we can call uvm_pageunwire.
2342 	 */
2343 
2344 	mutex_enter(&uvm_pageqlock);
2345 
2346 	/*
2347 	 * find the beginning map entry for the region.
2348 	 */
2349 
2350 	KASSERT(start >= vm_map_min(map) && end <= vm_map_max(map));
2351 	if (uvm_map_lookup_entry(map, start, &entry) == false)
2352 		panic("uvm_fault_unwire_locked: address not in map");
2353 
2354 	for (va = start; va < end; va += PAGE_SIZE) {
2355 		if (pmap_extract(pmap, va, &pa) == false)
2356 			continue;
2357 
2358 		/*
2359 		 * find the map entry for the current address.
2360 		 */
2361 
2362 		KASSERT(va >= entry->start);
2363 		while (va >= entry->end) {
2364 			KASSERT(entry->next != &map->header &&
2365 				entry->next->start <= entry->end);
2366 			entry = entry->next;
2367 		}
2368 
2369 		/*
2370 		 * if the entry is no longer wired, tell the pmap.
2371 		 */
2372 
2373 		if (VM_MAPENT_ISWIRED(entry) == 0)
2374 			pmap_unwire(pmap, va);
2375 
2376 		pg = PHYS_TO_VM_PAGE(pa);
2377 		if (pg)
2378 			uvm_pageunwire(pg);
2379 	}
2380 
2381 	mutex_exit(&uvm_pageqlock);
2382 }
2383