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