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