xref: /xnu-11215.41.3/osfmk/vm/vm_fault.c (revision 33de042d024d46de5ff4e89f2471de6608e37fa4)
1 /*
2  * Copyright (c) 2000-2021 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  * @OSF_COPYRIGHT@
30  */
31 /*
32  * Mach Operating System
33  * Copyright (c) 1991,1990,1989,1988,1987 Carnegie Mellon University
34  * All Rights Reserved.
35  *
36  * Permission to use, copy, modify and distribute this software and its
37  * documentation is hereby granted, provided that both the copyright
38  * notice and this permission notice appear in all copies of the
39  * software, derivative works or modified versions, and any portions
40  * thereof, and that both notices appear in supporting documentation.
41  *
42  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
45  *
46  * Carnegie Mellon requests users of this software to return to
47  *
48  *  Software Distribution Coordinator  or  [email protected]
49  *  School of Computer Science
50  *  Carnegie Mellon University
51  *  Pittsburgh PA 15213-3890
52  *
53  * any improvements or extensions that they make and grant Carnegie Mellon
54  * the rights to redistribute these changes.
55  */
56 /*
57  */
58 /*
59  *	File:	vm_fault.c
60  *	Author:	Avadis Tevanian, Jr., Michael Wayne Young
61  *
62  *	Page fault handling module.
63  */
64 
65 #include <libkern/OSAtomic.h>
66 
67 #include <mach/mach_types.h>
68 #include <mach/kern_return.h>
69 #include <mach/message.h>       /* for error codes */
70 #include <mach/vm_param.h>
71 #include <mach/vm_behavior.h>
72 #include <mach/memory_object.h>
73 /* For memory_object_data_{request,unlock} */
74 #include <mach/sdt.h>
75 
76 #include <kern/kern_types.h>
77 #include <kern/host_statistics.h>
78 #include <kern/counter.h>
79 #include <kern/task.h>
80 #include <kern/thread.h>
81 #include <kern/sched_prim.h>
82 #include <kern/host.h>
83 #include <kern/mach_param.h>
84 #include <kern/macro_help.h>
85 #include <kern/zalloc_internal.h>
86 #include <kern/misc_protos.h>
87 #include <kern/policy_internal.h>
88 
89 #include <vm/vm_compressor_internal.h>
90 #include <vm/vm_compressor_pager_internal.h>
91 #include <vm/vm_fault_internal.h>
92 #include <vm/vm_map_internal.h>
93 #include <vm/vm_object_internal.h>
94 #include <vm/vm_page_internal.h>
95 #include <vm/vm_kern_xnu.h>
96 #include <vm/pmap.h>
97 #include <vm/vm_pageout_internal.h>
98 #include <vm/vm_protos_internal.h>
99 #include <vm/vm_external.h>
100 #include <vm/memory_object.h>
101 #include <vm/vm_purgeable_internal.h>   /* Needed by some vm_page.h macros */
102 #include <vm/vm_shared_region.h>
103 #include <vm/vm_page_internal.h>
104 
105 #include <sys/codesign.h>
106 #include <sys/code_signing.h>
107 #include <sys/kdebug.h>
108 #include <sys/kdebug_triage.h>
109 #include <sys/reason.h>
110 #include <sys/signalvar.h>
111 
112 #include <san/kasan.h>
113 #include <libkern/coreanalytics/coreanalytics.h>
114 
115 #define VM_FAULT_CLASSIFY       0
116 
117 #define TRACEFAULTPAGE 0 /* (TEST/DEBUG) */
118 
119 int vm_protect_privileged_from_untrusted = 1;
120 
121 /*
122  * Enforce a maximum number of concurrent PageIns per vm-object to prevent
123  * high-I/O-volume tasks from saturating storage and starving the rest of the
124  * system.
125  *
126  * TODO: This throttling mechanism may be more naturally done by the pager,
127  * filesystem, or storage layers, which will have better information about how
128  * much concurrency the backing store can reasonably support.
129  */
130 TUNABLE(uint16_t, vm_object_pagein_throttle, "vm_object_pagein_throttle", 16);
131 
132 /*
133  * We apply a hard throttle to the demand zero rate of tasks that we believe are running out of control which
134  * kicks in when swap space runs out.  64-bit programs have massive address spaces and can leak enormous amounts
135  * of memory if they're buggy and can run the system completely out of swap space.  If this happens, we
136  * impose a hard throttle on them to prevent them from taking the last bit of memory left.  This helps
137  * keep the UI active so that the user has a chance to kill the offending task before the system
138  * completely hangs.
139  *
140  * The hard throttle is only applied when the system is nearly completely out of swap space and is only applied
141  * to tasks that appear to be bloated.  When swap runs out, any task using more than vm_hard_throttle_threshold
142  * will be throttled.  The throttling is done by giving the thread that's trying to demand zero a page a
143  * delay of HARD_THROTTLE_DELAY microseconds before being allowed to try the page fault again.
144  */
145 
146 extern void throttle_lowpri_io(int);
147 
148 extern struct vnode *vnode_pager_lookup_vnode(memory_object_t);
149 
150 uint64_t vm_hard_throttle_threshold;
151 
152 #if DEBUG || DEVELOPMENT
153 static bool vmtc_panic_instead = false;
154 int panic_object_not_alive = 1;
155 #endif /* DEBUG || DEVELOPMENT */
156 
157 OS_ALWAYS_INLINE
158 boolean_t
NEED_TO_HARD_THROTTLE_THIS_TASK(void)159 NEED_TO_HARD_THROTTLE_THIS_TASK(void)
160 {
161 	return vm_wants_task_throttled(current_task()) ||
162 	       ((vm_page_free_count < vm_page_throttle_limit ||
163 	       HARD_THROTTLE_LIMIT_REACHED()) &&
164 	       proc_get_effective_thread_policy(current_thread(), TASK_POLICY_IO) >= THROTTLE_LEVEL_THROTTLED);
165 }
166 
167 
168 /*
169  * XXX: For now, vm faults cannot be recursively disabled. If the need for
170  * nested code that disables faults arises, the implementation can be modified
171  * to track a disabled-count.
172  */
173 
174 OS_ALWAYS_INLINE
175 void
vm_fault_disable(void)176 vm_fault_disable(void)
177 {
178 	thread_t t = current_thread();
179 	assert(!t->th_vm_faults_disabled);
180 	t->th_vm_faults_disabled = true;
181 	act_set_debug_assert();
182 }
183 
184 OS_ALWAYS_INLINE
185 void
vm_fault_enable(void)186 vm_fault_enable(void)
187 {
188 	thread_t t = current_thread();
189 	assert(t->th_vm_faults_disabled);
190 	t->th_vm_faults_disabled = false;
191 }
192 
193 OS_ALWAYS_INLINE
194 bool
vm_fault_get_disabled(void)195 vm_fault_get_disabled(void)
196 {
197 	thread_t t = current_thread();
198 	return t->th_vm_faults_disabled;
199 }
200 
201 #define HARD_THROTTLE_DELAY     10000   /* 10000 us == 10 ms */
202 #define SOFT_THROTTLE_DELAY     200     /* 200 us == .2 ms */
203 
204 #define VM_PAGE_CREATION_THROTTLE_PERIOD_SECS   6
205 #define VM_PAGE_CREATION_THROTTLE_RATE_PER_SEC  20000
206 
207 
208 #define VM_STAT_DECOMPRESSIONS()        \
209 MACRO_BEGIN                             \
210 	counter_inc(&vm_statistics_decompressions); \
211 	current_thread()->decompressions++; \
212 MACRO_END
213 
214 boolean_t current_thread_aborted(void);
215 
216 /* Forward declarations of internal routines. */
217 static kern_return_t vm_fault_wire_fast(
218 	vm_map_t        map,
219 	vm_map_offset_t va,
220 	vm_prot_t       prot,
221 	vm_tag_t        wire_tag,
222 	vm_map_entry_t  entry,
223 	pmap_t          pmap,
224 	vm_map_offset_t pmap_addr,
225 	ppnum_t         *physpage_p);
226 
227 static kern_return_t vm_fault_internal(
228 	vm_map_t               map,
229 	vm_map_offset_t        vaddr,
230 	vm_prot_t              caller_prot,
231 	boolean_t              change_wiring,
232 	vm_tag_t               wire_tag,
233 	pmap_t                 pmap,
234 	vm_map_offset_t        pmap_addr,
235 	ppnum_t                *physpage_p,
236 	vm_object_fault_info_t fault_info);
237 
238 static void vm_fault_copy_cleanup(
239 	vm_page_t       page,
240 	vm_page_t       top_page);
241 
242 static void vm_fault_copy_dst_cleanup(
243 	vm_page_t       page);
244 
245 #if     VM_FAULT_CLASSIFY
246 extern void vm_fault_classify(vm_object_t       object,
247     vm_object_offset_t    offset,
248     vm_prot_t             fault_type);
249 
250 extern void vm_fault_classify_init(void);
251 #endif
252 
253 unsigned long vm_pmap_enter_blocked = 0;
254 unsigned long vm_pmap_enter_retried = 0;
255 
256 unsigned long vm_cs_validates = 0;
257 unsigned long vm_cs_revalidates = 0;
258 unsigned long vm_cs_query_modified = 0;
259 unsigned long vm_cs_validated_dirtied = 0;
260 unsigned long vm_cs_bitmap_validated = 0;
261 
262 #if CODE_SIGNING_MONITOR
263 uint64_t vm_cs_defer_to_csm = 0;
264 uint64_t vm_cs_defer_to_csm_not = 0;
265 #endif /* CODE_SIGNING_MONITOR */
266 
267 void vm_pre_fault(vm_map_offset_t, vm_prot_t);
268 
269 struct vmrtfr {
270 	int vmrtfr_maxi;
271 	int vmrtfr_curi;
272 	int64_t vmrtf_total;
273 	vm_rtfault_record_t *vm_rtf_records;
274 } vmrtfrs;
275 #define VMRTF_DEFAULT_BUFSIZE (4096)
276 #define VMRTF_NUM_RECORDS_DEFAULT (VMRTF_DEFAULT_BUFSIZE / sizeof(vm_rtfault_record_t))
277 TUNABLE(int, vmrtf_num_records, "vm_rtfault_records", VMRTF_NUM_RECORDS_DEFAULT);
278 
279 static void vm_rtfrecord_lock(void);
280 static void vm_rtfrecord_unlock(void);
281 static void vm_record_rtfault(thread_t, uint64_t, vm_map_offset_t, int);
282 
283 extern lck_grp_t vm_page_lck_grp_bucket;
284 extern lck_attr_t vm_page_lck_attr;
285 LCK_SPIN_DECLARE_ATTR(vm_rtfr_slock, &vm_page_lck_grp_bucket, &vm_page_lck_attr);
286 
287 #if DEVELOPMENT || DEBUG
288 extern int madvise_free_debug;
289 extern int madvise_free_debug_sometimes;
290 #endif /* DEVELOPMENT || DEBUG */
291 
292 extern int vm_pageout_protect_realtime;
293 
294 #if CONFIG_FREEZE
295 #endif /* CONFIG_FREEZE */
296 
297 /*
298  *	Routine:	vm_fault_init
299  *	Purpose:
300  *		Initialize our private data structures.
301  */
302 __startup_func
303 void
vm_fault_init(void)304 vm_fault_init(void)
305 {
306 	int i, vm_compressor_temp;
307 	boolean_t need_default_val = TRUE;
308 	/*
309 	 * Choose a value for the hard throttle threshold based on the amount of ram.  The threshold is
310 	 * computed as a percentage of available memory, and the percentage used is scaled inversely with
311 	 * the amount of memory.  The percentage runs between 10% and 35%.  We use 35% for small memory systems
312 	 * and reduce the value down to 10% for very large memory configurations.  This helps give us a
313 	 * definition of a memory hog that makes more sense relative to the amount of ram in the machine.
314 	 * The formula here simply uses the number of gigabytes of ram to adjust the percentage.
315 	 */
316 
317 	vm_hard_throttle_threshold = sane_size * (35 - MIN((int)(sane_size / (1024 * 1024 * 1024)), 25)) / 100;
318 
319 	/*
320 	 * Configure compressed pager behavior. A boot arg takes precedence over a device tree entry.
321 	 */
322 
323 	if (PE_parse_boot_argn("vm_compressor", &vm_compressor_temp, sizeof(vm_compressor_temp))) {
324 		for (i = 0; i < VM_PAGER_MAX_MODES; i++) {
325 			if (((vm_compressor_temp & (1 << i)) == vm_compressor_temp)) {
326 				need_default_val = FALSE;
327 				vm_compressor_mode = vm_compressor_temp;
328 				break;
329 			}
330 		}
331 		if (need_default_val) {
332 			printf("Ignoring \"vm_compressor\" boot arg %d\n", vm_compressor_temp);
333 		}
334 	}
335 #if CONFIG_FREEZE
336 	if (need_default_val) {
337 		if (osenvironment_is_diagnostics()) {
338 			printf("osenvironment == \"diagnostics\". Setting \"vm_compressor_mode\" to in-core compressor only\n");
339 			vm_compressor_mode = VM_PAGER_COMPRESSOR_NO_SWAP;
340 			need_default_val = false;
341 		}
342 	}
343 #endif /* CONFIG_FREEZE */
344 	if (need_default_val) {
345 		/* If no boot arg or incorrect boot arg, try device tree. */
346 		PE_get_default("kern.vm_compressor", &vm_compressor_mode, sizeof(vm_compressor_mode));
347 	}
348 	printf("\"vm_compressor_mode\" is %d\n", vm_compressor_mode);
349 	vm_config_init();
350 
351 	PE_parse_boot_argn("vm_protect_privileged_from_untrusted",
352 	    &vm_protect_privileged_from_untrusted,
353 	    sizeof(vm_protect_privileged_from_untrusted));
354 
355 #if DEBUG || DEVELOPMENT
356 	(void)PE_parse_boot_argn("text_corruption_panic", &vmtc_panic_instead, sizeof(vmtc_panic_instead));
357 
358 	if (kern_feature_override(KF_MADVISE_FREE_DEBUG_OVRD)) {
359 		madvise_free_debug = 0;
360 		madvise_free_debug_sometimes = 0;
361 	}
362 
363 	PE_parse_boot_argn("panic_object_not_alive", &panic_object_not_alive, sizeof(panic_object_not_alive));
364 #endif /* DEBUG || DEVELOPMENT */
365 }
366 
367 __startup_func
368 static void
vm_rtfault_record_init(void)369 vm_rtfault_record_init(void)
370 {
371 	size_t size;
372 
373 	vmrtf_num_records = MAX(vmrtf_num_records, 1);
374 	size = vmrtf_num_records * sizeof(vm_rtfault_record_t);
375 	vmrtfrs.vm_rtf_records = zalloc_permanent_tag(size,
376 	    ZALIGN(vm_rtfault_record_t), VM_KERN_MEMORY_DIAG);
377 	vmrtfrs.vmrtfr_maxi = vmrtf_num_records - 1;
378 }
379 STARTUP(ZALLOC, STARTUP_RANK_MIDDLE, vm_rtfault_record_init);
380 
381 /*
382  *	Routine:	vm_fault_cleanup
383  *	Purpose:
384  *		Clean up the result of vm_fault_page.
385  *	Results:
386  *		The paging reference for "object" is released.
387  *		"object" is unlocked.
388  *		If "top_page" is not null,  "top_page" is
389  *		freed and the paging reference for the object
390  *		containing it is released.
391  *
392  *	In/out conditions:
393  *		"object" must be locked.
394  */
395 void
vm_fault_cleanup(vm_object_t object,vm_page_t top_page)396 vm_fault_cleanup(
397 	vm_object_t     object,
398 	vm_page_t       top_page)
399 {
400 	vm_object_paging_end(object);
401 	vm_object_unlock(object);
402 
403 	if (top_page != VM_PAGE_NULL) {
404 		object = VM_PAGE_OBJECT(top_page);
405 
406 		vm_object_lock(object);
407 		VM_PAGE_FREE(top_page);
408 		vm_object_paging_end(object);
409 		vm_object_unlock(object);
410 	}
411 }
412 
413 #define ALIGNED(x) (((x) & (PAGE_SIZE_64 - 1)) == 0)
414 
415 
416 boolean_t       vm_page_deactivate_behind = TRUE;
417 /*
418  * default sizes given VM_BEHAVIOR_DEFAULT reference behavior
419  */
420 #define VM_DEFAULT_DEACTIVATE_BEHIND_WINDOW     128
421 #define VM_DEFAULT_DEACTIVATE_BEHIND_CLUSTER    16              /* don't make this too big... */
422                                                                 /* we use it to size an array on the stack */
423 
424 int vm_default_behind = VM_DEFAULT_DEACTIVATE_BEHIND_WINDOW;
425 
426 #define MAX_SEQUENTIAL_RUN      (1024 * 1024 * 1024)
427 
428 /*
429  * vm_page_is_sequential
430  *
431  * Determine if sequential access is in progress
432  * in accordance with the behavior specified.
433  * Update state to indicate current access pattern.
434  *
435  * object must have at least the shared lock held
436  */
437 static
438 void
vm_fault_is_sequential(vm_object_t object,vm_object_offset_t offset,vm_behavior_t behavior)439 vm_fault_is_sequential(
440 	vm_object_t             object,
441 	vm_object_offset_t      offset,
442 	vm_behavior_t           behavior)
443 {
444 	vm_object_offset_t      last_alloc;
445 	int                     sequential;
446 	int                     orig_sequential;
447 
448 	last_alloc = object->last_alloc;
449 	sequential = object->sequential;
450 	orig_sequential = sequential;
451 
452 	offset = vm_object_trunc_page(offset);
453 	if (offset == last_alloc && behavior != VM_BEHAVIOR_RANDOM) {
454 		/* re-faulting in the same page: no change in behavior */
455 		return;
456 	}
457 
458 	switch (behavior) {
459 	case VM_BEHAVIOR_RANDOM:
460 		/*
461 		 * reset indicator of sequential behavior
462 		 */
463 		sequential = 0;
464 		break;
465 
466 	case VM_BEHAVIOR_SEQUENTIAL:
467 		if (offset && last_alloc == offset - PAGE_SIZE_64) {
468 			/*
469 			 * advance indicator of sequential behavior
470 			 */
471 			if (sequential < MAX_SEQUENTIAL_RUN) {
472 				sequential += PAGE_SIZE;
473 			}
474 		} else {
475 			/*
476 			 * reset indicator of sequential behavior
477 			 */
478 			sequential = 0;
479 		}
480 		break;
481 
482 	case VM_BEHAVIOR_RSEQNTL:
483 		if (last_alloc && last_alloc == offset + PAGE_SIZE_64) {
484 			/*
485 			 * advance indicator of sequential behavior
486 			 */
487 			if (sequential > -MAX_SEQUENTIAL_RUN) {
488 				sequential -= PAGE_SIZE;
489 			}
490 		} else {
491 			/*
492 			 * reset indicator of sequential behavior
493 			 */
494 			sequential = 0;
495 		}
496 		break;
497 
498 	case VM_BEHAVIOR_DEFAULT:
499 	default:
500 		if (offset && last_alloc == (offset - PAGE_SIZE_64)) {
501 			/*
502 			 * advance indicator of sequential behavior
503 			 */
504 			if (sequential < 0) {
505 				sequential = 0;
506 			}
507 			if (sequential < MAX_SEQUENTIAL_RUN) {
508 				sequential += PAGE_SIZE;
509 			}
510 		} else if (last_alloc && last_alloc == (offset + PAGE_SIZE_64)) {
511 			/*
512 			 * advance indicator of sequential behavior
513 			 */
514 			if (sequential > 0) {
515 				sequential = 0;
516 			}
517 			if (sequential > -MAX_SEQUENTIAL_RUN) {
518 				sequential -= PAGE_SIZE;
519 			}
520 		} else {
521 			/*
522 			 * reset indicator of sequential behavior
523 			 */
524 			sequential = 0;
525 		}
526 		break;
527 	}
528 	if (sequential != orig_sequential) {
529 		if (!OSCompareAndSwap(orig_sequential, sequential, (UInt32 *)&object->sequential)) {
530 			/*
531 			 * if someone else has already updated object->sequential
532 			 * don't bother trying to update it or object->last_alloc
533 			 */
534 			return;
535 		}
536 	}
537 	/*
538 	 * I'd like to do this with a OSCompareAndSwap64, but that
539 	 * doesn't exist for PPC...  however, it shouldn't matter
540 	 * that much... last_alloc is maintained so that we can determine
541 	 * if a sequential access pattern is taking place... if only
542 	 * one thread is banging on this object, no problem with the unprotected
543 	 * update... if 2 or more threads are banging away, we run the risk of
544 	 * someone seeing a mangled update... however, in the face of multiple
545 	 * accesses, no sequential access pattern can develop anyway, so we
546 	 * haven't lost any real info.
547 	 */
548 	object->last_alloc = offset;
549 }
550 
551 #if DEVELOPMENT || DEBUG
552 uint64_t vm_page_deactivate_behind_count = 0;
553 #endif /* DEVELOPMENT || DEBUG */
554 
555 /*
556  * vm_page_deactivate_behind
557  *
558  * Determine if sequential access is in progress
559  * in accordance with the behavior specified.  If
560  * so, compute a potential page to deactivate and
561  * deactivate it.
562  *
563  * object must be locked.
564  *
565  * return TRUE if we actually deactivate a page
566  */
567 static
568 boolean_t
vm_fault_deactivate_behind(vm_object_t object,vm_object_offset_t offset,vm_behavior_t behavior)569 vm_fault_deactivate_behind(
570 	vm_object_t             object,
571 	vm_object_offset_t      offset,
572 	vm_behavior_t           behavior)
573 {
574 	int             n;
575 	int             pages_in_run = 0;
576 	int             max_pages_in_run = 0;
577 	int             sequential_run;
578 	int             sequential_behavior = VM_BEHAVIOR_SEQUENTIAL;
579 	vm_object_offset_t      run_offset = 0;
580 	vm_object_offset_t      pg_offset = 0;
581 	vm_page_t       m;
582 	vm_page_t       page_run[VM_DEFAULT_DEACTIVATE_BEHIND_CLUSTER];
583 
584 	pages_in_run = 0;
585 #if TRACEFAULTPAGE
586 	dbgTrace(0xBEEF0018, (unsigned int) object, (unsigned int) vm_fault_deactivate_behind); /* (TEST/DEBUG) */
587 #endif
588 	if (is_kernel_object(object) || vm_page_deactivate_behind == FALSE || (vm_object_trunc_page(offset) != offset)) {
589 		/*
590 		 * Do not deactivate pages from the kernel object: they
591 		 * are not intended to become pageable.
592 		 * or we've disabled the deactivate behind mechanism
593 		 * or we are dealing with an offset that is not aligned to
594 		 * the system's PAGE_SIZE because in that case we will
595 		 * handle the deactivation on the aligned offset and, thus,
596 		 * the full PAGE_SIZE page once. This helps us avoid the redundant
597 		 * deactivates and the extra faults.
598 		 */
599 		return FALSE;
600 	}
601 	if ((sequential_run = object->sequential)) {
602 		if (sequential_run < 0) {
603 			sequential_behavior = VM_BEHAVIOR_RSEQNTL;
604 			sequential_run = 0 - sequential_run;
605 		} else {
606 			sequential_behavior = VM_BEHAVIOR_SEQUENTIAL;
607 		}
608 	}
609 	switch (behavior) {
610 	case VM_BEHAVIOR_RANDOM:
611 		break;
612 	case VM_BEHAVIOR_SEQUENTIAL:
613 		if (sequential_run >= (int)PAGE_SIZE) {
614 			run_offset = 0 - PAGE_SIZE_64;
615 			max_pages_in_run = 1;
616 		}
617 		break;
618 	case VM_BEHAVIOR_RSEQNTL:
619 		if (sequential_run >= (int)PAGE_SIZE) {
620 			run_offset = PAGE_SIZE_64;
621 			max_pages_in_run = 1;
622 		}
623 		break;
624 	case VM_BEHAVIOR_DEFAULT:
625 	default:
626 	{       vm_object_offset_t behind = vm_default_behind * PAGE_SIZE_64;
627 
628 		/*
629 		 * determine if the run of sequential accesss has been
630 		 * long enough on an object with default access behavior
631 		 * to consider it for deactivation
632 		 */
633 		if ((uint64_t)sequential_run >= behind && (sequential_run % (VM_DEFAULT_DEACTIVATE_BEHIND_CLUSTER * PAGE_SIZE)) == 0) {
634 			/*
635 			 * the comparisons between offset and behind are done
636 			 * in this kind of odd fashion in order to prevent wrap around
637 			 * at the end points
638 			 */
639 			if (sequential_behavior == VM_BEHAVIOR_SEQUENTIAL) {
640 				if (offset >= behind) {
641 					run_offset = 0 - behind;
642 					pg_offset = PAGE_SIZE_64;
643 					max_pages_in_run = VM_DEFAULT_DEACTIVATE_BEHIND_CLUSTER;
644 				}
645 			} else {
646 				if (offset < -behind) {
647 					run_offset = behind;
648 					pg_offset = 0 - PAGE_SIZE_64;
649 					max_pages_in_run = VM_DEFAULT_DEACTIVATE_BEHIND_CLUSTER;
650 				}
651 			}
652 		}
653 		break;}
654 	}
655 	for (n = 0; n < max_pages_in_run; n++) {
656 		m = vm_page_lookup(object, offset + run_offset + (n * pg_offset));
657 
658 		if (m && !m->vmp_laundry && !m->vmp_busy && !m->vmp_no_cache && (m->vmp_q_state != VM_PAGE_ON_THROTTLED_Q) && !m->vmp_fictitious && !m->vmp_absent) {
659 			page_run[pages_in_run++] = m;
660 
661 			/*
662 			 * by not passing in a pmap_flush_context we will forgo any TLB flushing, local or otherwise...
663 			 *
664 			 * a TLB flush isn't really needed here since at worst we'll miss the reference bit being
665 			 * updated in the PTE if a remote processor still has this mapping cached in its TLB when the
666 			 * new reference happens. If no futher references happen on the page after that remote TLB flushes
667 			 * we'll see a clean, non-referenced page when it eventually gets pulled out of the inactive queue
668 			 * by pageout_scan, which is just fine since the last reference would have happened quite far
669 			 * in the past (TLB caches don't hang around for very long), and of course could just as easily
670 			 * have happened before we did the deactivate_behind.
671 			 */
672 			pmap_clear_refmod_options(VM_PAGE_GET_PHYS_PAGE(m), VM_MEM_REFERENCED, PMAP_OPTIONS_NOFLUSH, (void *)NULL);
673 		}
674 	}
675 	if (pages_in_run) {
676 		vm_page_lockspin_queues();
677 
678 		for (n = 0; n < pages_in_run; n++) {
679 			m = page_run[n];
680 
681 			vm_page_deactivate_internal(m, FALSE);
682 
683 #if DEVELOPMENT || DEBUG
684 			vm_page_deactivate_behind_count++;
685 #endif /* DEVELOPMENT || DEBUG */
686 
687 #if TRACEFAULTPAGE
688 			dbgTrace(0xBEEF0019, (unsigned int) object, (unsigned int) m);  /* (TEST/DEBUG) */
689 #endif
690 		}
691 		vm_page_unlock_queues();
692 
693 		return TRUE;
694 	}
695 	return FALSE;
696 }
697 
698 
699 #if (DEVELOPMENT || DEBUG)
700 uint32_t        vm_page_creation_throttled_hard = 0;
701 uint32_t        vm_page_creation_throttled_soft = 0;
702 uint64_t        vm_page_creation_throttle_avoided = 0;
703 #endif /* DEVELOPMENT || DEBUG */
704 
705 static int
vm_page_throttled(boolean_t page_kept)706 vm_page_throttled(boolean_t page_kept)
707 {
708 	clock_sec_t     elapsed_sec;
709 	clock_sec_t     tv_sec;
710 	clock_usec_t    tv_usec;
711 	task_t          curtask = current_task_early();
712 
713 	thread_t thread = current_thread();
714 
715 	if (thread->options & TH_OPT_VMPRIV) {
716 		return 0;
717 	}
718 
719 	if (curtask && !curtask->active) {
720 		return 0;
721 	}
722 
723 	if (thread->t_page_creation_throttled) {
724 		thread->t_page_creation_throttled = 0;
725 
726 		if (page_kept == FALSE) {
727 			goto no_throttle;
728 		}
729 	}
730 	if (NEED_TO_HARD_THROTTLE_THIS_TASK()) {
731 #if (DEVELOPMENT || DEBUG)
732 		thread->t_page_creation_throttled_hard++;
733 		OSAddAtomic(1, &vm_page_creation_throttled_hard);
734 #endif /* DEVELOPMENT || DEBUG */
735 		return HARD_THROTTLE_DELAY;
736 	}
737 
738 	if ((vm_page_free_count < vm_page_throttle_limit || (VM_CONFIG_COMPRESSOR_IS_PRESENT && SWAPPER_NEEDS_TO_UNTHROTTLE())) &&
739 	    thread->t_page_creation_count > (VM_PAGE_CREATION_THROTTLE_PERIOD_SECS * VM_PAGE_CREATION_THROTTLE_RATE_PER_SEC)) {
740 		if (vm_page_free_wanted == 0 && vm_page_free_wanted_privileged == 0) {
741 #if (DEVELOPMENT || DEBUG)
742 			OSAddAtomic64(1, &vm_page_creation_throttle_avoided);
743 #endif
744 			goto no_throttle;
745 		}
746 		clock_get_system_microtime(&tv_sec, &tv_usec);
747 
748 		elapsed_sec = tv_sec - thread->t_page_creation_time;
749 
750 		if (elapsed_sec <= VM_PAGE_CREATION_THROTTLE_PERIOD_SECS ||
751 		    (thread->t_page_creation_count / elapsed_sec) >= VM_PAGE_CREATION_THROTTLE_RATE_PER_SEC) {
752 			if (elapsed_sec >= (3 * VM_PAGE_CREATION_THROTTLE_PERIOD_SECS)) {
753 				/*
754 				 * we'll reset our stats to give a well behaved app
755 				 * that was unlucky enough to accumulate a bunch of pages
756 				 * over a long period of time a chance to get out of
757 				 * the throttled state... we reset the counter and timestamp
758 				 * so that if it stays under the rate limit for the next second
759 				 * it will be back in our good graces... if it exceeds it, it
760 				 * will remain in the throttled state
761 				 */
762 				thread->t_page_creation_time = tv_sec;
763 				thread->t_page_creation_count = VM_PAGE_CREATION_THROTTLE_RATE_PER_SEC * (VM_PAGE_CREATION_THROTTLE_PERIOD_SECS - 1);
764 			}
765 			VM_PAGEOUT_DEBUG(vm_page_throttle_count, 1);
766 
767 			thread->t_page_creation_throttled = 1;
768 
769 			if (VM_CONFIG_COMPRESSOR_IS_PRESENT && HARD_THROTTLE_LIMIT_REACHED()) {
770 #if (DEVELOPMENT || DEBUG)
771 				thread->t_page_creation_throttled_hard++;
772 				OSAddAtomic(1, &vm_page_creation_throttled_hard);
773 #endif /* DEVELOPMENT || DEBUG */
774 				return HARD_THROTTLE_DELAY;
775 			} else {
776 #if (DEVELOPMENT || DEBUG)
777 				thread->t_page_creation_throttled_soft++;
778 				OSAddAtomic(1, &vm_page_creation_throttled_soft);
779 #endif /* DEVELOPMENT || DEBUG */
780 				return SOFT_THROTTLE_DELAY;
781 			}
782 		}
783 		thread->t_page_creation_time = tv_sec;
784 		thread->t_page_creation_count = 0;
785 	}
786 no_throttle:
787 	thread->t_page_creation_count++;
788 
789 	return 0;
790 }
791 
792 extern boolean_t vm_pageout_running;
793 static __attribute__((noinline, not_tail_called)) void
__VM_FAULT_THROTTLE_FOR_PAGEOUT_SCAN__(int throttle_delay)794 __VM_FAULT_THROTTLE_FOR_PAGEOUT_SCAN__(
795 	int throttle_delay)
796 {
797 	/* make sure vm_pageout_scan() gets to work while we're throttled */
798 	if (!vm_pageout_running) {
799 		thread_wakeup((event_t)&vm_page_free_wanted);
800 	}
801 	delay(throttle_delay);
802 }
803 
804 
805 /*
806  * check for various conditions that would
807  * prevent us from creating a ZF page...
808  * cleanup is based on being called from vm_fault_page
809  *
810  * object must be locked
811  * object == m->vmp_object
812  */
813 static vm_fault_return_t
vm_fault_check(vm_object_t object,vm_page_t m,vm_page_t first_m,wait_interrupt_t interruptible_state,boolean_t page_throttle)814 vm_fault_check(vm_object_t object, vm_page_t m, vm_page_t first_m, wait_interrupt_t interruptible_state, boolean_t page_throttle)
815 {
816 	int throttle_delay;
817 
818 	if (object->shadow_severed ||
819 	    VM_OBJECT_PURGEABLE_FAULT_ERROR(object)) {
820 		/*
821 		 * Either:
822 		 * 1. the shadow chain was severed,
823 		 * 2. the purgeable object is volatile or empty and is marked
824 		 *    to fault on access while volatile.
825 		 * Just have to return an error at this point
826 		 */
827 		if (m != VM_PAGE_NULL) {
828 			VM_PAGE_FREE(m);
829 		}
830 		vm_fault_cleanup(object, first_m);
831 
832 		thread_interrupt_level(interruptible_state);
833 
834 		if (VM_OBJECT_PURGEABLE_FAULT_ERROR(object)) {
835 			ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_PURGEABLE_FAULT_ERROR), 0 /* arg */);
836 		}
837 
838 		if (object->shadow_severed) {
839 			ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_OBJECT_SHADOW_SEVERED), 0 /* arg */);
840 		}
841 		return VM_FAULT_MEMORY_ERROR;
842 	}
843 	if (page_throttle == TRUE) {
844 		if ((throttle_delay = vm_page_throttled(FALSE))) {
845 			/*
846 			 * we're throttling zero-fills...
847 			 * treat this as if we couldn't grab a page
848 			 */
849 			if (m != VM_PAGE_NULL) {
850 				VM_PAGE_FREE(m);
851 			}
852 			vm_fault_cleanup(object, first_m);
853 
854 			VM_DEBUG_EVENT(vmf_check_zfdelay, DBG_VM_FAULT_CHECK_ZFDELAY, DBG_FUNC_NONE, throttle_delay, 0, 0, 0);
855 
856 			__VM_FAULT_THROTTLE_FOR_PAGEOUT_SCAN__(throttle_delay);
857 
858 			if (current_thread_aborted()) {
859 				thread_interrupt_level(interruptible_state);
860 				ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_FAULT_INTERRUPTED), 0 /* arg */);
861 				return VM_FAULT_INTERRUPTED;
862 			}
863 			thread_interrupt_level(interruptible_state);
864 
865 			return VM_FAULT_MEMORY_SHORTAGE;
866 		}
867 	}
868 	return VM_FAULT_SUCCESS;
869 }
870 
871 /*
872  * Clear the code signing bits on the given page_t
873  */
874 static void
vm_fault_cs_clear(vm_page_t m)875 vm_fault_cs_clear(vm_page_t m)
876 {
877 	m->vmp_cs_validated = VMP_CS_ALL_FALSE;
878 	m->vmp_cs_tainted = VMP_CS_ALL_FALSE;
879 	m->vmp_cs_nx = VMP_CS_ALL_FALSE;
880 }
881 
882 /*
883  * Enqueues the given page on the throttled queue.
884  * The caller must hold the vm_page_queue_lock and it will be held on return.
885  */
886 static void
vm_fault_enqueue_throttled_locked(vm_page_t m)887 vm_fault_enqueue_throttled_locked(vm_page_t m)
888 {
889 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
890 	assert(!VM_PAGE_WIRED(m));
891 
892 	/*
893 	 * can't be on the pageout queue since we don't
894 	 * have a pager to try and clean to
895 	 */
896 	vm_page_queues_remove(m, TRUE);
897 	vm_page_check_pageable_safe(m);
898 	vm_page_queue_enter(&vm_page_queue_throttled, m, vmp_pageq);
899 	m->vmp_q_state = VM_PAGE_ON_THROTTLED_Q;
900 	vm_page_throttled_count++;
901 }
902 
903 /*
904  * do the work to zero fill a page and
905  * inject it into the correct paging queue
906  *
907  * m->vmp_object must be locked
908  * page queue lock must NOT be held
909  */
910 static int
vm_fault_zero_page(vm_page_t m,boolean_t no_zero_fill)911 vm_fault_zero_page(vm_page_t m, boolean_t no_zero_fill)
912 {
913 	int my_fault = DBG_ZERO_FILL_FAULT;
914 	vm_object_t     object;
915 
916 	object = VM_PAGE_OBJECT(m);
917 
918 	/*
919 	 * This is is a zero-fill page fault...
920 	 *
921 	 * Checking the page lock is a waste of
922 	 * time;  this page was absent, so
923 	 * it can't be page locked by a pager.
924 	 *
925 	 * we also consider it undefined
926 	 * with respect to instruction
927 	 * execution.  i.e. it is the responsibility
928 	 * of higher layers to call for an instruction
929 	 * sync after changing the contents and before
930 	 * sending a program into this area.  We
931 	 * choose this approach for performance
932 	 */
933 	vm_fault_cs_clear(m);
934 	m->vmp_pmapped = TRUE;
935 
936 	if (no_zero_fill == TRUE) {
937 		my_fault = DBG_NZF_PAGE_FAULT;
938 
939 		if (m->vmp_absent && m->vmp_busy) {
940 			return my_fault;
941 		}
942 	} else {
943 		vm_page_zero_fill(m);
944 
945 		counter_inc(&vm_statistics_zero_fill_count);
946 		DTRACE_VM2(zfod, int, 1, (uint64_t *), NULL);
947 	}
948 	assert(!m->vmp_laundry);
949 	assert(!is_kernel_object(object));
950 	//assert(m->vmp_pageq.next == 0 && m->vmp_pageq.prev == 0);
951 	if (!VM_DYNAMIC_PAGING_ENABLED() &&
952 	    (object->purgable == VM_PURGABLE_DENY ||
953 	    object->purgable == VM_PURGABLE_NONVOLATILE ||
954 	    object->purgable == VM_PURGABLE_VOLATILE)) {
955 		vm_page_lockspin_queues();
956 		if (!VM_DYNAMIC_PAGING_ENABLED()) {
957 			vm_fault_enqueue_throttled_locked(m);
958 		}
959 		vm_page_unlock_queues();
960 	}
961 	return my_fault;
962 }
963 
964 
965 /*
966  *	Routine:	vm_fault_page
967  *	Purpose:
968  *		Find the resident page for the virtual memory
969  *		specified by the given virtual memory object
970  *		and offset.
971  *	Additional arguments:
972  *		The required permissions for the page is given
973  *		in "fault_type".  Desired permissions are included
974  *		in "protection".
975  *		fault_info is passed along to determine pagein cluster
976  *		limits... it contains the expected reference pattern,
977  *		cluster size if available, etc...
978  *
979  *		If the desired page is known to be resident (for
980  *		example, because it was previously wired down), asserting
981  *		the "unwiring" parameter will speed the search.
982  *
983  *		If the operation can be interrupted (by thread_abort
984  *		or thread_terminate), then the "interruptible"
985  *		parameter should be asserted.
986  *
987  *	Results:
988  *		The page containing the proper data is returned
989  *		in "result_page".
990  *
991  *	In/out conditions:
992  *		The source object must be locked and referenced,
993  *		and must donate one paging reference.  The reference
994  *		is not affected.  The paging reference and lock are
995  *		consumed.
996  *
997  *		If the call succeeds, the object in which "result_page"
998  *		resides is left locked and holding a paging reference.
999  *		If this is not the original object, a busy page in the
1000  *		original object is returned in "top_page", to prevent other
1001  *		callers from pursuing this same data, along with a paging
1002  *		reference for the original object.  The "top_page" should
1003  *		be destroyed when this guarantee is no longer required.
1004  *		The "result_page" is also left busy.  It is not removed
1005  *		from the pageout queues.
1006  *	Special Case:
1007  *		A return value of VM_FAULT_SUCCESS_NO_PAGE means that the
1008  *		fault succeeded but there's no VM page (i.e. the VM object
1009  *              does not actually hold VM pages, but device memory or
1010  *		large pages).  The object is still locked and we still hold a
1011  *		paging_in_progress reference.
1012  */
1013 unsigned int vm_fault_page_blocked_access = 0;
1014 unsigned int vm_fault_page_forced_retry = 0;
1015 
1016 vm_fault_return_t
vm_fault_page(vm_object_t first_object,vm_object_offset_t first_offset,vm_prot_t fault_type,boolean_t must_be_resident,boolean_t caller_lookup,vm_prot_t * protection,vm_page_t * result_page,vm_page_t * top_page,int * type_of_fault,kern_return_t * error_code,boolean_t no_zero_fill,vm_object_fault_info_t fault_info)1017 vm_fault_page(
1018 	/* Arguments: */
1019 	vm_object_t     first_object,   /* Object to begin search */
1020 	vm_object_offset_t first_offset,        /* Offset into object */
1021 	vm_prot_t       fault_type,     /* What access is requested */
1022 	boolean_t       must_be_resident,/* Must page be resident? */
1023 	boolean_t       caller_lookup,  /* caller looked up page */
1024 	/* Modifies in place: */
1025 	vm_prot_t       *protection,    /* Protection for mapping */
1026 	vm_page_t       *result_page,   /* Page found, if successful */
1027 	/* Returns: */
1028 	vm_page_t       *top_page,      /* Page in top object, if
1029                                          * not result_page.  */
1030 	int             *type_of_fault, /* if non-null, fill in with type of fault
1031                                          * COW, zero-fill, etc... returned in trace point */
1032 	/* More arguments: */
1033 	kern_return_t   *error_code,    /* code if page is in error */
1034 	boolean_t       no_zero_fill,   /* don't zero fill absent pages */
1035 	vm_object_fault_info_t fault_info)
1036 {
1037 	vm_page_t               m;
1038 	vm_object_t             object;
1039 	vm_object_offset_t      offset;
1040 	vm_page_t               first_m;
1041 	vm_object_t             next_object;
1042 	vm_object_t             copy_object;
1043 	boolean_t               look_for_page;
1044 	boolean_t               force_fault_retry = FALSE;
1045 	vm_prot_t               access_required = fault_type;
1046 	vm_prot_t               wants_copy_flag;
1047 	kern_return_t           wait_result;
1048 	wait_interrupt_t        interruptible_state;
1049 	boolean_t               data_already_requested = FALSE;
1050 	vm_behavior_t           orig_behavior;
1051 	vm_size_t               orig_cluster_size;
1052 	vm_fault_return_t       error;
1053 	int                     my_fault;
1054 	uint32_t                try_failed_count;
1055 	wait_interrupt_t        interruptible; /* how may fault be interrupted? */
1056 	int                     external_state = VM_EXTERNAL_STATE_UNKNOWN;
1057 	memory_object_t         pager;
1058 	vm_fault_return_t       retval;
1059 	int                     grab_options;
1060 	bool                    clear_absent_on_error = false;
1061 
1062 /*
1063  * MUST_ASK_PAGER() evaluates to TRUE if the page specified by object/offset is
1064  * marked as paged out in the compressor pager or the pager doesn't exist.
1065  * Note also that if the pager for an internal object
1066  * has not been created, the pager is not invoked regardless of the value
1067  * of MUST_ASK_PAGER().
1068  *
1069  * PAGED_OUT() evaluates to TRUE if the page specified by the object/offset
1070  * is marked as paged out in the compressor pager.
1071  * PAGED_OUT() is used to determine if a page has already been pushed
1072  * into a copy object in order to avoid a redundant page out operation.
1073  */
1074 #define MUST_ASK_PAGER(o, f, s)                                 \
1075 	((s = vm_object_compressor_pager_state_get((o), (f))) != VM_EXTERNAL_STATE_ABSENT)
1076 
1077 #define PAGED_OUT(o, f) \
1078 	(vm_object_compressor_pager_state_get((o), (f)) == VM_EXTERNAL_STATE_EXISTS)
1079 
1080 /*
1081  *	Recovery actions
1082  */
1083 #define RELEASE_PAGE(m)                                 \
1084 	MACRO_BEGIN                                     \
1085 	vm_page_wakeup_done(VM_PAGE_OBJECT(m), m);                            \
1086 	if ( !VM_PAGE_PAGEABLE(m)) {                    \
1087 	        vm_page_lockspin_queues();              \
1088 	        if (clear_absent_on_error && m->vmp_absent) {\
1089 	                vm_page_zero_fill(m);           \
1090 	                counter_inc(&vm_statistics_zero_fill_count);\
1091 	                DTRACE_VM2(zfod, int, 1, (uint64_t *), NULL);\
1092 	                m->vmp_absent = false;          \
1093 	        }                                       \
1094 	        if ( !VM_PAGE_PAGEABLE(m)) {            \
1095 	                if (VM_CONFIG_COMPRESSOR_IS_ACTIVE)     \
1096 	                        vm_page_deactivate(m);          \
1097 	                else                                    \
1098 	                        vm_page_activate(m);            \
1099 	        }                                               \
1100 	        vm_page_unlock_queues();                        \
1101 	}                                                       \
1102 	clear_absent_on_error = false;                  \
1103 	MACRO_END
1104 
1105 #if TRACEFAULTPAGE
1106 	dbgTrace(0xBEEF0002, (unsigned int) first_object, (unsigned int) first_offset); /* (TEST/DEBUG) */
1107 #endif
1108 
1109 	interruptible = fault_info->interruptible;
1110 	interruptible_state = thread_interrupt_level(interruptible);
1111 
1112 	/*
1113 	 *	INVARIANTS (through entire routine):
1114 	 *
1115 	 *	1)	At all times, we must either have the object
1116 	 *		lock or a busy page in some object to prevent
1117 	 *		some other thread from trying to bring in
1118 	 *		the same page.
1119 	 *
1120 	 *		Note that we cannot hold any locks during the
1121 	 *		pager access or when waiting for memory, so
1122 	 *		we use a busy page then.
1123 	 *
1124 	 *	2)	To prevent another thread from racing us down the
1125 	 *		shadow chain and entering a new page in the top
1126 	 *		object before we do, we must keep a busy page in
1127 	 *		the top object while following the shadow chain.
1128 	 *
1129 	 *	3)	We must increment paging_in_progress on any object
1130 	 *		for which we have a busy page before dropping
1131 	 *		the object lock
1132 	 *
1133 	 *	4)	We leave busy pages on the pageout queues.
1134 	 *		If the pageout daemon comes across a busy page,
1135 	 *		it will remove the page from the pageout queues.
1136 	 */
1137 
1138 	object = first_object;
1139 	offset = first_offset;
1140 	first_m = VM_PAGE_NULL;
1141 	access_required = fault_type;
1142 
1143 	/*
1144 	 * default type of fault
1145 	 */
1146 	my_fault = DBG_CACHE_HIT_FAULT;
1147 	thread_pri_floor_t token;
1148 	bool    drop_floor = false;
1149 
1150 	while (TRUE) {
1151 #if TRACEFAULTPAGE
1152 		dbgTrace(0xBEEF0003, (unsigned int) 0, (unsigned int) 0);       /* (TEST/DEBUG) */
1153 #endif
1154 
1155 		grab_options = 0;
1156 #if CONFIG_SECLUDED_MEMORY
1157 		if (object->can_grab_secluded) {
1158 			grab_options |= VM_PAGE_GRAB_SECLUDED;
1159 		}
1160 #endif /* CONFIG_SECLUDED_MEMORY */
1161 
1162 		if (!object->alive) {
1163 			/*
1164 			 * object is no longer valid
1165 			 * clean up and return error
1166 			 */
1167 #if DEVELOPMENT || DEBUG
1168 			printf("FBDP rdar://93769854 %s:%d object %p internal %d pager %p (%s) copy %p shadow %p alive %d terminating %d named %d ref %d shadow_severed %d\n", __FUNCTION__, __LINE__, object, object->internal, object->pager, object->pager ? object->pager->mo_pager_ops->memory_object_pager_name : "?", object->vo_copy, object->shadow, object->alive, object->terminating, object->named, object->ref_count, object->shadow_severed);
1169 			if (panic_object_not_alive) {
1170 				panic("FBDP rdar://93769854 %s:%d object %p internal %d pager %p (%s) copy %p shadow %p alive %d terminating %d named %d ref %d shadow_severed %d\n", __FUNCTION__, __LINE__, object, object->internal, object->pager, object->pager ? object->pager->mo_pager_ops->memory_object_pager_name : "?", object->vo_copy, object->shadow, object->alive, object->terminating, object->named, object->ref_count, object->shadow_severed);
1171 			}
1172 #endif /* DEVELOPMENT || DEBUG */
1173 			vm_fault_cleanup(object, first_m);
1174 			thread_interrupt_level(interruptible_state);
1175 
1176 			ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_OBJECT_NOT_ALIVE), 0 /* arg */);
1177 			return VM_FAULT_MEMORY_ERROR;
1178 		}
1179 
1180 		if (!object->pager_created && object->phys_contiguous) {
1181 			/*
1182 			 * A physically-contiguous object without a pager:
1183 			 * must be a "large page" object.  We do not deal
1184 			 * with VM pages for this object.
1185 			 */
1186 			caller_lookup = FALSE;
1187 			m = VM_PAGE_NULL;
1188 			goto phys_contig_object;
1189 		}
1190 
1191 		if (object->blocked_access) {
1192 			/*
1193 			 * Access to this VM object has been blocked.
1194 			 * Replace our "paging_in_progress" reference with
1195 			 * a "activity_in_progress" reference and wait for
1196 			 * access to be unblocked.
1197 			 */
1198 			caller_lookup = FALSE; /* no longer valid after sleep */
1199 			vm_object_activity_begin(object);
1200 			vm_object_paging_end(object);
1201 			while (object->blocked_access) {
1202 				vm_object_sleep(object,
1203 				    VM_OBJECT_EVENT_UNBLOCKED,
1204 				    THREAD_UNINT, LCK_SLEEP_EXCLUSIVE);
1205 			}
1206 			vm_fault_page_blocked_access++;
1207 			vm_object_paging_begin(object);
1208 			vm_object_activity_end(object);
1209 		}
1210 
1211 		/*
1212 		 * See whether the page at 'offset' is resident
1213 		 */
1214 		if (caller_lookup == TRUE) {
1215 			/*
1216 			 * The caller has already looked up the page
1217 			 * and gave us the result in "result_page".
1218 			 * We can use this for the first lookup but
1219 			 * it loses its validity as soon as we unlock
1220 			 * the object.
1221 			 */
1222 			m = *result_page;
1223 			caller_lookup = FALSE; /* no longer valid after that */
1224 		} else {
1225 			m = vm_page_lookup(object, vm_object_trunc_page(offset));
1226 		}
1227 #if TRACEFAULTPAGE
1228 		dbgTrace(0xBEEF0004, (unsigned int) m, (unsigned int) object);  /* (TEST/DEBUG) */
1229 #endif
1230 		if (m != VM_PAGE_NULL) {
1231 			if (m->vmp_busy) {
1232 				/*
1233 				 * The page is being brought in,
1234 				 * wait for it and then retry.
1235 				 */
1236 #if TRACEFAULTPAGE
1237 				dbgTrace(0xBEEF0005, (unsigned int) m, (unsigned int) 0);       /* (TEST/DEBUG) */
1238 #endif
1239 				wait_result = vm_page_sleep(object, m, interruptible, LCK_SLEEP_DEFAULT);
1240 
1241 				if (wait_result != THREAD_AWAKENED) {
1242 					vm_fault_cleanup(object, first_m);
1243 					thread_interrupt_level(interruptible_state);
1244 
1245 					if (wait_result == THREAD_RESTART) {
1246 						return VM_FAULT_RETRY;
1247 					} else {
1248 						ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_BUSYPAGE_WAIT_INTERRUPTED), 0 /* arg */);
1249 						return VM_FAULT_INTERRUPTED;
1250 					}
1251 				}
1252 				continue;
1253 			}
1254 			if (m->vmp_laundry) {
1255 				m->vmp_free_when_done = FALSE;
1256 
1257 				if (!m->vmp_cleaning) {
1258 					vm_pageout_steal_laundry(m, FALSE);
1259 				}
1260 			}
1261 			vm_object_lock_assert_exclusive(VM_PAGE_OBJECT(m));
1262 			if (VM_PAGE_GET_PHYS_PAGE(m) == vm_page_guard_addr) {
1263 				/*
1264 				 * Guard page: off limits !
1265 				 */
1266 				if (fault_type == VM_PROT_NONE) {
1267 					/*
1268 					 * The fault is not requesting any
1269 					 * access to the guard page, so it must
1270 					 * be just to wire or unwire it.
1271 					 * Let's pretend it succeeded...
1272 					 */
1273 					m->vmp_busy = TRUE;
1274 					*result_page = m;
1275 					assert(first_m == VM_PAGE_NULL);
1276 					*top_page = first_m;
1277 					if (type_of_fault) {
1278 						*type_of_fault = DBG_GUARD_FAULT;
1279 					}
1280 					thread_interrupt_level(interruptible_state);
1281 					return VM_FAULT_SUCCESS;
1282 				} else {
1283 					/*
1284 					 * The fault requests access to the
1285 					 * guard page: let's deny that !
1286 					 */
1287 					vm_fault_cleanup(object, first_m);
1288 					thread_interrupt_level(interruptible_state);
1289 					ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_GUARDPAGE_FAULT), 0 /* arg */);
1290 					return VM_FAULT_MEMORY_ERROR;
1291 				}
1292 			}
1293 
1294 
1295 			if (m->vmp_error) {
1296 				/*
1297 				 * The page is in error, give up now.
1298 				 */
1299 #if TRACEFAULTPAGE
1300 				dbgTrace(0xBEEF0006, (unsigned int) m, (unsigned int) error_code);      /* (TEST/DEBUG) */
1301 #endif
1302 				if (error_code) {
1303 					*error_code = KERN_MEMORY_ERROR;
1304 				}
1305 				VM_PAGE_FREE(m);
1306 
1307 				vm_fault_cleanup(object, first_m);
1308 				thread_interrupt_level(interruptible_state);
1309 
1310 				ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_PAGE_HAS_ERROR), 0 /* arg */);
1311 				return VM_FAULT_MEMORY_ERROR;
1312 			}
1313 			if (m->vmp_restart) {
1314 				/*
1315 				 * The pager wants us to restart
1316 				 * at the top of the chain,
1317 				 * typically because it has moved the
1318 				 * page to another pager, then do so.
1319 				 */
1320 #if TRACEFAULTPAGE
1321 				dbgTrace(0xBEEF0007, (unsigned int) m, (unsigned int) 0);       /* (TEST/DEBUG) */
1322 #endif
1323 				VM_PAGE_FREE(m);
1324 
1325 				vm_fault_cleanup(object, first_m);
1326 				thread_interrupt_level(interruptible_state);
1327 
1328 				ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_PAGE_HAS_RESTART), 0 /* arg */);
1329 				return VM_FAULT_RETRY;
1330 			}
1331 			if (m->vmp_absent) {
1332 				/*
1333 				 * The page isn't busy, but is absent,
1334 				 * therefore it's deemed "unavailable".
1335 				 *
1336 				 * Remove the non-existent page (unless it's
1337 				 * in the top object) and move on down to the
1338 				 * next object (if there is one).
1339 				 */
1340 #if TRACEFAULTPAGE
1341 				dbgTrace(0xBEEF0008, (unsigned int) m, (unsigned int) object->shadow);  /* (TEST/DEBUG) */
1342 #endif
1343 				next_object = object->shadow;
1344 
1345 				if (next_object == VM_OBJECT_NULL) {
1346 					/*
1347 					 * Absent page at bottom of shadow
1348 					 * chain; zero fill the page we left
1349 					 * busy in the first object, and free
1350 					 * the absent page.
1351 					 */
1352 					assert(!must_be_resident);
1353 
1354 					/*
1355 					 * check for any conditions that prevent
1356 					 * us from creating a new zero-fill page
1357 					 * vm_fault_check will do all of the
1358 					 * fault cleanup in the case of an error condition
1359 					 * including resetting the thread_interrupt_level
1360 					 */
1361 					error = vm_fault_check(object, m, first_m, interruptible_state, (type_of_fault == NULL) ? TRUE : FALSE);
1362 
1363 					if (error != VM_FAULT_SUCCESS) {
1364 						return error;
1365 					}
1366 
1367 					if (object != first_object) {
1368 						/*
1369 						 * free the absent page we just found
1370 						 */
1371 						VM_PAGE_FREE(m);
1372 
1373 						/*
1374 						 * drop reference and lock on current object
1375 						 */
1376 						vm_object_paging_end(object);
1377 						vm_object_unlock(object);
1378 
1379 						/*
1380 						 * grab the original page we
1381 						 * 'soldered' in place and
1382 						 * retake lock on 'first_object'
1383 						 */
1384 						m = first_m;
1385 						first_m = VM_PAGE_NULL;
1386 
1387 						object = first_object;
1388 						offset = first_offset;
1389 
1390 						vm_object_lock(object);
1391 					} else {
1392 						/*
1393 						 * we're going to use the absent page we just found
1394 						 * so convert it to a 'busy' page
1395 						 */
1396 						m->vmp_absent = FALSE;
1397 						m->vmp_busy = TRUE;
1398 					}
1399 					if (fault_info->mark_zf_absent && no_zero_fill == TRUE) {
1400 						m->vmp_absent = TRUE;
1401 						clear_absent_on_error = true;
1402 					}
1403 					/*
1404 					 * zero-fill the page and put it on
1405 					 * the correct paging queue
1406 					 */
1407 					my_fault = vm_fault_zero_page(m, no_zero_fill);
1408 
1409 					break;
1410 				} else {
1411 					if (must_be_resident) {
1412 						vm_object_paging_end(object);
1413 					} else if (object != first_object) {
1414 						vm_object_paging_end(object);
1415 						VM_PAGE_FREE(m);
1416 					} else {
1417 						first_m = m;
1418 						m->vmp_absent = FALSE;
1419 						m->vmp_busy = TRUE;
1420 
1421 						vm_page_lockspin_queues();
1422 						vm_page_queues_remove(m, FALSE);
1423 						vm_page_unlock_queues();
1424 					}
1425 
1426 					offset += object->vo_shadow_offset;
1427 					fault_info->lo_offset += object->vo_shadow_offset;
1428 					fault_info->hi_offset += object->vo_shadow_offset;
1429 					access_required = VM_PROT_READ;
1430 
1431 					vm_object_lock(next_object);
1432 					vm_object_unlock(object);
1433 					object = next_object;
1434 					vm_object_paging_begin(object);
1435 
1436 					/*
1437 					 * reset to default type of fault
1438 					 */
1439 					my_fault = DBG_CACHE_HIT_FAULT;
1440 
1441 					continue;
1442 				}
1443 			}
1444 			if ((m->vmp_cleaning)
1445 			    && ((object != first_object) || (object->vo_copy != VM_OBJECT_NULL))
1446 			    && (fault_type & VM_PROT_WRITE)) {
1447 				/*
1448 				 * This is a copy-on-write fault that will
1449 				 * cause us to revoke access to this page, but
1450 				 * this page is in the process of being cleaned
1451 				 * in a clustered pageout. We must wait until
1452 				 * the cleaning operation completes before
1453 				 * revoking access to the original page,
1454 				 * otherwise we might attempt to remove a
1455 				 * wired mapping.
1456 				 */
1457 #if TRACEFAULTPAGE
1458 				dbgTrace(0xBEEF0009, (unsigned int) m, (unsigned int) offset);  /* (TEST/DEBUG) */
1459 #endif
1460 				/*
1461 				 * take an extra ref so that object won't die
1462 				 */
1463 				vm_object_reference_locked(object);
1464 
1465 				vm_fault_cleanup(object, first_m);
1466 
1467 				vm_object_lock(object);
1468 				assert(object->ref_count > 0);
1469 
1470 				m = vm_page_lookup(object, vm_object_trunc_page(offset));
1471 
1472 				if (m != VM_PAGE_NULL && m->vmp_cleaning) {
1473 					wait_result = vm_page_sleep(object, m, interruptible, LCK_SLEEP_UNLOCK);
1474 					vm_object_deallocate(object);
1475 					goto backoff;
1476 				} else {
1477 					vm_object_unlock(object);
1478 
1479 					vm_object_deallocate(object);
1480 					thread_interrupt_level(interruptible_state);
1481 
1482 					return VM_FAULT_RETRY;
1483 				}
1484 			}
1485 			if (type_of_fault == NULL && (m->vmp_q_state == VM_PAGE_ON_SPECULATIVE_Q) &&
1486 			    !(fault_info != NULL && fault_info->stealth)) {
1487 				/*
1488 				 * If we were passed a non-NULL pointer for
1489 				 * "type_of_fault", than we came from
1490 				 * vm_fault... we'll let it deal with
1491 				 * this condition, since it
1492 				 * needs to see m->vmp_speculative to correctly
1493 				 * account the pageins, otherwise...
1494 				 * take it off the speculative queue, we'll
1495 				 * let the caller of vm_fault_page deal
1496 				 * with getting it onto the correct queue
1497 				 *
1498 				 * If the caller specified in fault_info that
1499 				 * it wants a "stealth" fault, we also leave
1500 				 * the page in the speculative queue.
1501 				 */
1502 				vm_page_lockspin_queues();
1503 				if (m->vmp_q_state == VM_PAGE_ON_SPECULATIVE_Q) {
1504 					vm_page_queues_remove(m, FALSE);
1505 				}
1506 				vm_page_unlock_queues();
1507 			}
1508 			assert(object == VM_PAGE_OBJECT(m));
1509 
1510 			if (object->code_signed) {
1511 				/*
1512 				 * CODE SIGNING:
1513 				 * We just paged in a page from a signed
1514 				 * memory object but we don't need to
1515 				 * validate it now.  We'll validate it if
1516 				 * when it gets mapped into a user address
1517 				 * space for the first time or when the page
1518 				 * gets copied to another object as a result
1519 				 * of a copy-on-write.
1520 				 */
1521 			}
1522 
1523 			/*
1524 			 * We mark the page busy and leave it on
1525 			 * the pageout queues.  If the pageout
1526 			 * deamon comes across it, then it will
1527 			 * remove the page from the queue, but not the object
1528 			 */
1529 #if TRACEFAULTPAGE
1530 			dbgTrace(0xBEEF000B, (unsigned int) m, (unsigned int) 0);       /* (TEST/DEBUG) */
1531 #endif
1532 			assert(!m->vmp_busy);
1533 			assert(!m->vmp_absent);
1534 
1535 			m->vmp_busy = TRUE;
1536 			break;
1537 		}
1538 
1539 		/*
1540 		 * we get here when there is no page present in the object at
1541 		 * the offset we're interested in... we'll allocate a page
1542 		 * at this point if the pager associated with
1543 		 * this object can provide the data or we're the top object...
1544 		 * object is locked;  m == NULL
1545 		 */
1546 
1547 		if (must_be_resident) {
1548 			if (fault_type == VM_PROT_NONE &&
1549 			    is_kernel_object(object)) {
1550 				/*
1551 				 * We've been called from vm_fault_unwire()
1552 				 * while removing a map entry that was allocated
1553 				 * with KMA_KOBJECT and KMA_VAONLY.  This page
1554 				 * is not present and there's nothing more to
1555 				 * do here (nothing to unwire).
1556 				 */
1557 				vm_fault_cleanup(object, first_m);
1558 				thread_interrupt_level(interruptible_state);
1559 
1560 				return VM_FAULT_MEMORY_ERROR;
1561 			}
1562 
1563 			goto dont_look_for_page;
1564 		}
1565 
1566 		/* Don't expect to fault pages into the kernel object. */
1567 		assert(!is_kernel_object(object));
1568 
1569 		look_for_page = (object->pager_created && (MUST_ASK_PAGER(object, offset, external_state) == TRUE));
1570 
1571 #if TRACEFAULTPAGE
1572 		dbgTrace(0xBEEF000C, (unsigned int) look_for_page, (unsigned int) object);      /* (TEST/DEBUG) */
1573 #endif
1574 		if (!look_for_page && object == first_object && !object->phys_contiguous) {
1575 			/*
1576 			 * Allocate a new page for this object/offset pair as a placeholder
1577 			 */
1578 			m = vm_page_grab_options(grab_options);
1579 #if TRACEFAULTPAGE
1580 			dbgTrace(0xBEEF000D, (unsigned int) m, (unsigned int) object);  /* (TEST/DEBUG) */
1581 #endif
1582 			if (m == VM_PAGE_NULL) {
1583 				vm_fault_cleanup(object, first_m);
1584 				thread_interrupt_level(interruptible_state);
1585 
1586 				return VM_FAULT_MEMORY_SHORTAGE;
1587 			}
1588 
1589 			if (fault_info && fault_info->batch_pmap_op == TRUE) {
1590 				vm_page_insert_internal(m, object,
1591 				    vm_object_trunc_page(offset),
1592 				    VM_KERN_MEMORY_NONE, FALSE, TRUE, TRUE, FALSE, NULL);
1593 			} else {
1594 				vm_page_insert(m, object, vm_object_trunc_page(offset));
1595 			}
1596 		}
1597 		if (look_for_page) {
1598 			kern_return_t   rc;
1599 			int             my_fault_type;
1600 
1601 			/*
1602 			 *	If the memory manager is not ready, we
1603 			 *	cannot make requests.
1604 			 */
1605 			if (!object->pager_ready) {
1606 #if TRACEFAULTPAGE
1607 				dbgTrace(0xBEEF000E, (unsigned int) 0, (unsigned int) 0);       /* (TEST/DEBUG) */
1608 #endif
1609 				if (m != VM_PAGE_NULL) {
1610 					VM_PAGE_FREE(m);
1611 				}
1612 
1613 				/*
1614 				 * take an extra ref so object won't die
1615 				 */
1616 				vm_object_reference_locked(object);
1617 				vm_fault_cleanup(object, first_m);
1618 
1619 				vm_object_lock(object);
1620 				assert(object->ref_count > 0);
1621 
1622 				if (!object->pager_ready) {
1623 					wait_result = vm_object_sleep(object, VM_OBJECT_EVENT_PAGER_READY, interruptible, LCK_SLEEP_UNLOCK);
1624 					vm_object_deallocate(object);
1625 
1626 					goto backoff;
1627 				} else {
1628 					vm_object_unlock(object);
1629 					vm_object_deallocate(object);
1630 					thread_interrupt_level(interruptible_state);
1631 
1632 					return VM_FAULT_RETRY;
1633 				}
1634 			}
1635 			if (!object->internal && !object->phys_contiguous && object->paging_in_progress > vm_object_pagein_throttle) {
1636 				/*
1637 				 * If there are too many outstanding page
1638 				 * requests pending on this external object, we
1639 				 * wait for them to be resolved now.
1640 				 */
1641 #if TRACEFAULTPAGE
1642 				dbgTrace(0xBEEF0010, (unsigned int) m, (unsigned int) 0);       /* (TEST/DEBUG) */
1643 #endif
1644 				if (m != VM_PAGE_NULL) {
1645 					VM_PAGE_FREE(m);
1646 				}
1647 				/*
1648 				 * take an extra ref so object won't die
1649 				 */
1650 				vm_object_reference_locked(object);
1651 
1652 				vm_fault_cleanup(object, first_m);
1653 
1654 				vm_object_lock(object);
1655 				assert(object->ref_count > 0);
1656 
1657 				if (object->paging_in_progress >= vm_object_pagein_throttle) {
1658 					wait_result = vm_object_paging_throttle_wait(object, interruptible);
1659 					vm_object_unlock(object);
1660 					vm_object_deallocate(object);
1661 					goto backoff;
1662 				} else {
1663 					vm_object_unlock(object);
1664 					vm_object_deallocate(object);
1665 					thread_interrupt_level(interruptible_state);
1666 
1667 					return VM_FAULT_RETRY;
1668 				}
1669 			}
1670 			if (object->internal) {
1671 				int compressed_count_delta;
1672 
1673 				assert(VM_CONFIG_COMPRESSOR_IS_PRESENT);
1674 
1675 				if (m == VM_PAGE_NULL) {
1676 					/*
1677 					 * Allocate a new page for this object/offset pair as a placeholder
1678 					 */
1679 					m = vm_page_grab_options(grab_options);
1680 #if TRACEFAULTPAGE
1681 					dbgTrace(0xBEEF000D, (unsigned int) m, (unsigned int) object);  /* (TEST/DEBUG) */
1682 #endif
1683 					if (m == VM_PAGE_NULL) {
1684 						vm_fault_cleanup(object, first_m);
1685 						thread_interrupt_level(interruptible_state);
1686 
1687 						return VM_FAULT_MEMORY_SHORTAGE;
1688 					}
1689 
1690 					m->vmp_absent = TRUE;
1691 					if (fault_info && fault_info->batch_pmap_op == TRUE) {
1692 						vm_page_insert_internal(m, object, vm_object_trunc_page(offset), VM_KERN_MEMORY_NONE, FALSE, TRUE, TRUE, FALSE, NULL);
1693 					} else {
1694 						vm_page_insert(m, object, vm_object_trunc_page(offset));
1695 					}
1696 				}
1697 				assert(m->vmp_busy);
1698 
1699 				m->vmp_absent = TRUE;
1700 				pager = object->pager;
1701 
1702 				assert(object->paging_in_progress > 0);
1703 				vm_object_unlock(object);
1704 
1705 				rc = vm_compressor_pager_get(
1706 					pager,
1707 					offset + object->paging_offset,
1708 					VM_PAGE_GET_PHYS_PAGE(m),
1709 					&my_fault_type,
1710 					0,
1711 					&compressed_count_delta);
1712 
1713 				if (type_of_fault == NULL) {
1714 					int     throttle_delay;
1715 
1716 					/*
1717 					 * we weren't called from vm_fault, so we
1718 					 * need to apply page creation throttling
1719 					 * do it before we re-acquire any locks
1720 					 */
1721 					if (my_fault_type == DBG_COMPRESSOR_FAULT) {
1722 						if ((throttle_delay = vm_page_throttled(TRUE))) {
1723 							VM_DEBUG_EVENT(vmf_compressordelay, DBG_VM_FAULT_COMPRESSORDELAY, DBG_FUNC_NONE, throttle_delay, 0, 1, 0);
1724 							__VM_FAULT_THROTTLE_FOR_PAGEOUT_SCAN__(throttle_delay);
1725 						}
1726 					}
1727 				}
1728 				vm_object_lock(object);
1729 				assert(object->paging_in_progress > 0);
1730 
1731 				vm_compressor_pager_count(
1732 					pager,
1733 					compressed_count_delta,
1734 					FALSE, /* shared_lock */
1735 					object);
1736 
1737 				switch (rc) {
1738 				case KERN_SUCCESS:
1739 					m->vmp_absent = FALSE;
1740 					m->vmp_dirty = TRUE;
1741 					if ((object->wimg_bits &
1742 					    VM_WIMG_MASK) !=
1743 					    VM_WIMG_USE_DEFAULT) {
1744 						/*
1745 						 * If the page is not cacheable,
1746 						 * we can't let its contents
1747 						 * linger in the data cache
1748 						 * after the decompression.
1749 						 */
1750 						pmap_sync_page_attributes_phys(
1751 							VM_PAGE_GET_PHYS_PAGE(m));
1752 					} else {
1753 						m->vmp_written_by_kernel = TRUE;
1754 					}
1755 #if CONFIG_TRACK_UNMODIFIED_ANON_PAGES
1756 					if ((fault_type & VM_PROT_WRITE) == 0) {
1757 						vm_object_lock_assert_exclusive(object);
1758 						vm_page_lockspin_queues();
1759 						m->vmp_unmodified_ro = true;
1760 						vm_page_unlock_queues();
1761 						os_atomic_inc(&compressor_ro_uncompressed, relaxed);
1762 						*protection &= ~VM_PROT_WRITE;
1763 					}
1764 #endif /* CONFIG_TRACK_UNMODIFIED_ANON_PAGES */
1765 
1766 					/*
1767 					 * If the object is purgeable, its
1768 					 * owner's purgeable ledgers have been
1769 					 * updated in vm_page_insert() but the
1770 					 * page was also accounted for in a
1771 					 * "compressed purgeable" ledger, so
1772 					 * update that now.
1773 					 */
1774 					if (((object->purgable !=
1775 					    VM_PURGABLE_DENY) ||
1776 					    object->vo_ledger_tag) &&
1777 					    (object->vo_owner !=
1778 					    NULL)) {
1779 						/*
1780 						 * One less compressed
1781 						 * purgeable/tagged page.
1782 						 */
1783 						if (compressed_count_delta) {
1784 							vm_object_owner_compressed_update(
1785 								object,
1786 								-1);
1787 						}
1788 					}
1789 
1790 					break;
1791 				case KERN_MEMORY_FAILURE:
1792 					m->vmp_unusual = TRUE;
1793 					m->vmp_error = TRUE;
1794 					m->vmp_absent = FALSE;
1795 					break;
1796 				case KERN_MEMORY_ERROR:
1797 					assert(m->vmp_absent);
1798 					break;
1799 				default:
1800 					panic("vm_fault_page(): unexpected "
1801 					    "error %d from "
1802 					    "vm_compressor_pager_get()\n",
1803 					    rc);
1804 				}
1805 				vm_page_wakeup_done(object, m);
1806 
1807 				rc = KERN_SUCCESS;
1808 				goto data_requested;
1809 			}
1810 			my_fault_type = DBG_PAGEIN_FAULT;
1811 
1812 			if (m != VM_PAGE_NULL) {
1813 				VM_PAGE_FREE(m);
1814 				m = VM_PAGE_NULL;
1815 			}
1816 
1817 #if TRACEFAULTPAGE
1818 			dbgTrace(0xBEEF0012, (unsigned int) object, (unsigned int) 0);  /* (TEST/DEBUG) */
1819 #endif
1820 
1821 			/*
1822 			 * It's possible someone called vm_object_destroy while we weren't
1823 			 * holding the object lock.  If that has happened, then bail out
1824 			 * here.
1825 			 */
1826 
1827 			pager = object->pager;
1828 
1829 			if (pager == MEMORY_OBJECT_NULL) {
1830 				vm_fault_cleanup(object, first_m);
1831 				thread_interrupt_level(interruptible_state);
1832 
1833 				static const enum vm_subsys_error_codes object_destroy_errors[VM_OBJECT_DESTROY_MAX + 1] = {
1834 					[VM_OBJECT_DESTROY_UNKNOWN_REASON] = KDBG_TRIAGE_VM_OBJECT_NO_PAGER,
1835 					[VM_OBJECT_DESTROY_UNMOUNT] = KDBG_TRIAGE_VM_OBJECT_NO_PAGER_UNMOUNT,
1836 					[VM_OBJECT_DESTROY_FORCED_UNMOUNT] = KDBG_TRIAGE_VM_OBJECT_NO_PAGER_FORCED_UNMOUNT,
1837 					[VM_OBJECT_DESTROY_UNGRAFT] = KDBG_TRIAGE_VM_OBJECT_NO_PAGER_UNGRAFT,
1838 					[VM_OBJECT_DESTROY_PAGER] = KDBG_TRIAGE_VM_OBJECT_NO_PAGER_DEALLOC_PAGER,
1839 					[VM_OBJECT_DESTROY_RECLAIM] = KDBG_TRIAGE_VM_OBJECT_NO_PAGER_RECLAIM,
1840 				};
1841 				enum vm_subsys_error_codes kdbg_code = object_destroy_errors[(vm_object_destroy_reason_t)object->no_pager_reason];
1842 				ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, kdbg_code), 0 /* arg */);
1843 				return VM_FAULT_MEMORY_ERROR;
1844 			}
1845 
1846 			/*
1847 			 * We have an absent page in place for the faulting offset,
1848 			 * so we can release the object lock.
1849 			 */
1850 
1851 			if (object->object_is_shared_cache) {
1852 				token = thread_priority_floor_start();
1853 				/*
1854 				 * A non-native shared cache object might
1855 				 * be getting set up in parallel with this
1856 				 * fault and so we can't assume that this
1857 				 * check will be valid after we drop the
1858 				 * object lock below.
1859 				 */
1860 				drop_floor = true;
1861 			}
1862 
1863 			vm_object_unlock(object);
1864 
1865 			/*
1866 			 * If this object uses a copy_call strategy,
1867 			 * and we are interested in a copy of this object
1868 			 * (having gotten here only by following a
1869 			 * shadow chain), then tell the memory manager
1870 			 * via a flag added to the desired_access
1871 			 * parameter, so that it can detect a race
1872 			 * between our walking down the shadow chain
1873 			 * and its pushing pages up into a copy of
1874 			 * the object that it manages.
1875 			 */
1876 			if (object->copy_strategy == MEMORY_OBJECT_COPY_CALL && object != first_object) {
1877 				wants_copy_flag = VM_PROT_WANTS_COPY;
1878 			} else {
1879 				wants_copy_flag = VM_PROT_NONE;
1880 			}
1881 
1882 			if (object->vo_copy == first_object) {
1883 				/*
1884 				 * if we issue the memory_object_data_request in
1885 				 * this state, we are subject to a deadlock with
1886 				 * the underlying filesystem if it is trying to
1887 				 * shrink the file resulting in a push of pages
1888 				 * into the copy object...  that push will stall
1889 				 * on the placeholder page, and if the pushing thread
1890 				 * is holding a lock that is required on the pagein
1891 				 * path (such as a truncate lock), we'll deadlock...
1892 				 * to avoid this potential deadlock, we throw away
1893 				 * our placeholder page before calling memory_object_data_request
1894 				 * and force this thread to retry the vm_fault_page after
1895 				 * we have issued the I/O.  the second time through this path
1896 				 * we will find the page already in the cache (presumably still
1897 				 * busy waiting for the I/O to complete) and then complete
1898 				 * the fault w/o having to go through memory_object_data_request again
1899 				 */
1900 				assert(first_m != VM_PAGE_NULL);
1901 				assert(VM_PAGE_OBJECT(first_m) == first_object);
1902 
1903 				vm_object_lock(first_object);
1904 				VM_PAGE_FREE(first_m);
1905 				vm_object_paging_end(first_object);
1906 				vm_object_unlock(first_object);
1907 
1908 				first_m = VM_PAGE_NULL;
1909 				force_fault_retry = TRUE;
1910 
1911 				vm_fault_page_forced_retry++;
1912 			}
1913 
1914 			if (data_already_requested == TRUE) {
1915 				orig_behavior = fault_info->behavior;
1916 				orig_cluster_size = fault_info->cluster_size;
1917 
1918 				fault_info->behavior = VM_BEHAVIOR_RANDOM;
1919 				fault_info->cluster_size = PAGE_SIZE;
1920 			}
1921 			/*
1922 			 * Call the memory manager to retrieve the data.
1923 			 */
1924 			rc = memory_object_data_request(
1925 				pager,
1926 				vm_object_trunc_page(offset) + object->paging_offset,
1927 				PAGE_SIZE,
1928 				access_required | wants_copy_flag,
1929 				(memory_object_fault_info_t)fault_info);
1930 
1931 			if (data_already_requested == TRUE) {
1932 				fault_info->behavior = orig_behavior;
1933 				fault_info->cluster_size = orig_cluster_size;
1934 			} else {
1935 				data_already_requested = TRUE;
1936 			}
1937 
1938 			DTRACE_VM2(maj_fault, int, 1, (uint64_t *), NULL);
1939 #if TRACEFAULTPAGE
1940 			dbgTrace(0xBEEF0013, (unsigned int) object, (unsigned int) rc); /* (TEST/DEBUG) */
1941 #endif
1942 			vm_object_lock(object);
1943 
1944 			if (drop_floor && object->object_is_shared_cache) {
1945 				thread_priority_floor_end(&token);
1946 				drop_floor = false;
1947 			}
1948 
1949 data_requested:
1950 			if (rc != KERN_SUCCESS) {
1951 				vm_fault_cleanup(object, first_m);
1952 				thread_interrupt_level(interruptible_state);
1953 
1954 				ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_NO_DATA), 0 /* arg */);
1955 
1956 				return (rc == MACH_SEND_INTERRUPTED) ?
1957 				       VM_FAULT_INTERRUPTED :
1958 				       VM_FAULT_MEMORY_ERROR;
1959 			} else {
1960 				clock_sec_t     tv_sec;
1961 				clock_usec_t    tv_usec;
1962 
1963 				if (my_fault_type == DBG_PAGEIN_FAULT) {
1964 					clock_get_system_microtime(&tv_sec, &tv_usec);
1965 					current_thread()->t_page_creation_time = tv_sec;
1966 					current_thread()->t_page_creation_count = 0;
1967 				}
1968 			}
1969 			if ((interruptible != THREAD_UNINT) && (current_thread()->sched_flags & TH_SFLAG_ABORT)) {
1970 				vm_fault_cleanup(object, first_m);
1971 				thread_interrupt_level(interruptible_state);
1972 
1973 				ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_FAULT_INTERRUPTED), 0 /* arg */);
1974 				return VM_FAULT_INTERRUPTED;
1975 			}
1976 			if (force_fault_retry == TRUE) {
1977 				vm_fault_cleanup(object, first_m);
1978 				thread_interrupt_level(interruptible_state);
1979 
1980 				return VM_FAULT_RETRY;
1981 			}
1982 			if (m == VM_PAGE_NULL && object->phys_contiguous) {
1983 				/*
1984 				 * No page here means that the object we
1985 				 * initially looked up was "physically
1986 				 * contiguous" (i.e. device memory).  However,
1987 				 * with Virtual VRAM, the object might not
1988 				 * be backed by that device memory anymore,
1989 				 * so we're done here only if the object is
1990 				 * still "phys_contiguous".
1991 				 * Otherwise, if the object is no longer
1992 				 * "phys_contiguous", we need to retry the
1993 				 * page fault against the object's new backing
1994 				 * store (different memory object).
1995 				 */
1996 phys_contig_object:
1997 				assert(object->copy_strategy == MEMORY_OBJECT_COPY_NONE);
1998 				assert(object == first_object);
1999 				goto done;
2000 			}
2001 			/*
2002 			 * potentially a pagein fault
2003 			 * if we make it through the state checks
2004 			 * above, than we'll count it as such
2005 			 */
2006 			my_fault = my_fault_type;
2007 
2008 			/*
2009 			 * Retry with same object/offset, since new data may
2010 			 * be in a different page (i.e., m is meaningless at
2011 			 * this point).
2012 			 */
2013 			continue;
2014 		}
2015 dont_look_for_page:
2016 		/*
2017 		 * We get here if the object has no pager, or an existence map
2018 		 * exists and indicates the page isn't present on the pager
2019 		 * or we're unwiring a page.  If a pager exists, but there
2020 		 * is no existence map, then the m->vmp_absent case above handles
2021 		 * the ZF case when the pager can't provide the page
2022 		 */
2023 #if TRACEFAULTPAGE
2024 		dbgTrace(0xBEEF0014, (unsigned int) object, (unsigned int) m);  /* (TEST/DEBUG) */
2025 #endif
2026 		if (object == first_object) {
2027 			first_m = m;
2028 		} else {
2029 			assert(m == VM_PAGE_NULL);
2030 		}
2031 
2032 		next_object = object->shadow;
2033 
2034 		if (next_object == VM_OBJECT_NULL) {
2035 			/*
2036 			 * we've hit the bottom of the shadown chain,
2037 			 * fill the page in the top object with zeros.
2038 			 */
2039 			assert(!must_be_resident);
2040 
2041 			if (object != first_object) {
2042 				vm_object_paging_end(object);
2043 				vm_object_unlock(object);
2044 
2045 				object = first_object;
2046 				offset = first_offset;
2047 				vm_object_lock(object);
2048 			}
2049 			m = first_m;
2050 			assert(VM_PAGE_OBJECT(m) == object);
2051 			first_m = VM_PAGE_NULL;
2052 
2053 			/*
2054 			 * check for any conditions that prevent
2055 			 * us from creating a new zero-fill page
2056 			 * vm_fault_check will do all of the
2057 			 * fault cleanup in the case of an error condition
2058 			 * including resetting the thread_interrupt_level
2059 			 */
2060 			error = vm_fault_check(object, m, first_m, interruptible_state, (type_of_fault == NULL) ? TRUE : FALSE);
2061 
2062 			if (error != VM_FAULT_SUCCESS) {
2063 				return error;
2064 			}
2065 
2066 			if (m == VM_PAGE_NULL) {
2067 				m = vm_page_grab_options(grab_options);
2068 
2069 				if (m == VM_PAGE_NULL) {
2070 					vm_fault_cleanup(object, VM_PAGE_NULL);
2071 					thread_interrupt_level(interruptible_state);
2072 
2073 					return VM_FAULT_MEMORY_SHORTAGE;
2074 				}
2075 				vm_page_insert(m, object, vm_object_trunc_page(offset));
2076 			}
2077 			if (fault_info->mark_zf_absent && no_zero_fill == TRUE) {
2078 				m->vmp_absent = TRUE;
2079 				clear_absent_on_error = true;
2080 			}
2081 
2082 			my_fault = vm_fault_zero_page(m, no_zero_fill);
2083 
2084 			break;
2085 		} else {
2086 			/*
2087 			 * Move on to the next object.  Lock the next
2088 			 * object before unlocking the current one.
2089 			 */
2090 			if ((object != first_object) || must_be_resident) {
2091 				vm_object_paging_end(object);
2092 			}
2093 
2094 			offset += object->vo_shadow_offset;
2095 			fault_info->lo_offset += object->vo_shadow_offset;
2096 			fault_info->hi_offset += object->vo_shadow_offset;
2097 			access_required = VM_PROT_READ;
2098 
2099 			vm_object_lock(next_object);
2100 			vm_object_unlock(object);
2101 
2102 			object = next_object;
2103 			vm_object_paging_begin(object);
2104 		}
2105 	}
2106 
2107 	/*
2108 	 *	PAGE HAS BEEN FOUND.
2109 	 *
2110 	 *	This page (m) is:
2111 	 *		busy, so that we can play with it;
2112 	 *		not absent, so that nobody else will fill it;
2113 	 *		possibly eligible for pageout;
2114 	 *
2115 	 *	The top-level page (first_m) is:
2116 	 *		VM_PAGE_NULL if the page was found in the
2117 	 *		 top-level object;
2118 	 *		busy, not absent, and ineligible for pageout.
2119 	 *
2120 	 *	The current object (object) is locked.  A paging
2121 	 *	reference is held for the current and top-level
2122 	 *	objects.
2123 	 */
2124 
2125 #if TRACEFAULTPAGE
2126 	dbgTrace(0xBEEF0015, (unsigned int) object, (unsigned int) m);  /* (TEST/DEBUG) */
2127 #endif
2128 #if     EXTRA_ASSERTIONS
2129 	assert(m->vmp_busy && !m->vmp_absent);
2130 	assert((first_m == VM_PAGE_NULL) ||
2131 	    (first_m->vmp_busy && !first_m->vmp_absent &&
2132 	    !first_m->vmp_active && !first_m->vmp_inactive && !first_m->vmp_secluded));
2133 #endif  /* EXTRA_ASSERTIONS */
2134 
2135 	/*
2136 	 * If the page is being written, but isn't
2137 	 * already owned by the top-level object,
2138 	 * we have to copy it into a new page owned
2139 	 * by the top-level object.
2140 	 */
2141 	if (object != first_object) {
2142 #if TRACEFAULTPAGE
2143 		dbgTrace(0xBEEF0016, (unsigned int) object, (unsigned int) fault_type); /* (TEST/DEBUG) */
2144 #endif
2145 		if (fault_type & VM_PROT_WRITE) {
2146 			vm_page_t copy_m;
2147 
2148 			/*
2149 			 * We only really need to copy if we
2150 			 * want to write it.
2151 			 */
2152 			assert(!must_be_resident);
2153 
2154 			/*
2155 			 * If we try to collapse first_object at this
2156 			 * point, we may deadlock when we try to get
2157 			 * the lock on an intermediate object (since we
2158 			 * have the bottom object locked).  We can't
2159 			 * unlock the bottom object, because the page
2160 			 * we found may move (by collapse) if we do.
2161 			 *
2162 			 * Instead, we first copy the page.  Then, when
2163 			 * we have no more use for the bottom object,
2164 			 * we unlock it and try to collapse.
2165 			 *
2166 			 * Note that we copy the page even if we didn't
2167 			 * need to... that's the breaks.
2168 			 */
2169 
2170 			/*
2171 			 * Allocate a page for the copy
2172 			 */
2173 			copy_m = vm_page_grab_options(grab_options);
2174 
2175 			if (copy_m == VM_PAGE_NULL) {
2176 				RELEASE_PAGE(m);
2177 
2178 				vm_fault_cleanup(object, first_m);
2179 				thread_interrupt_level(interruptible_state);
2180 
2181 				return VM_FAULT_MEMORY_SHORTAGE;
2182 			}
2183 
2184 			vm_page_copy(m, copy_m);
2185 
2186 			/*
2187 			 * If another map is truly sharing this
2188 			 * page with us, we have to flush all
2189 			 * uses of the original page, since we
2190 			 * can't distinguish those which want the
2191 			 * original from those which need the
2192 			 * new copy.
2193 			 *
2194 			 * XXXO If we know that only one map has
2195 			 * access to this page, then we could
2196 			 * avoid the pmap_disconnect() call.
2197 			 */
2198 			if (m->vmp_pmapped) {
2199 				pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(m));
2200 			}
2201 
2202 			if (m->vmp_clustered) {
2203 				VM_PAGE_COUNT_AS_PAGEIN(m);
2204 				VM_PAGE_CONSUME_CLUSTERED(m);
2205 			}
2206 			assert(!m->vmp_cleaning);
2207 
2208 			/*
2209 			 * We no longer need the old page or object.
2210 			 */
2211 			RELEASE_PAGE(m);
2212 
2213 			/*
2214 			 * This check helps with marking the object as having a sequential pattern
2215 			 * Normally we'll miss doing this below because this fault is about COW to
2216 			 * the first_object i.e. bring page in from disk, push to object above but
2217 			 * don't update the file object's sequential pattern.
2218 			 */
2219 			if (object->internal == FALSE) {
2220 				vm_fault_is_sequential(object, offset, fault_info->behavior);
2221 			}
2222 
2223 			vm_object_paging_end(object);
2224 			vm_object_unlock(object);
2225 
2226 			my_fault = DBG_COW_FAULT;
2227 			counter_inc(&vm_statistics_cow_faults);
2228 			DTRACE_VM2(cow_fault, int, 1, (uint64_t *), NULL);
2229 			counter_inc(&current_task()->cow_faults);
2230 
2231 			object = first_object;
2232 			offset = first_offset;
2233 
2234 			vm_object_lock(object);
2235 			/*
2236 			 * get rid of the place holder
2237 			 * page that we soldered in earlier
2238 			 */
2239 			VM_PAGE_FREE(first_m);
2240 			first_m = VM_PAGE_NULL;
2241 
2242 			/*
2243 			 * and replace it with the
2244 			 * page we just copied into
2245 			 */
2246 			assert(copy_m->vmp_busy);
2247 			vm_page_insert(copy_m, object, vm_object_trunc_page(offset));
2248 			SET_PAGE_DIRTY(copy_m, TRUE);
2249 
2250 			m = copy_m;
2251 			/*
2252 			 * Now that we've gotten the copy out of the
2253 			 * way, let's try to collapse the top object.
2254 			 * But we have to play ugly games with
2255 			 * paging_in_progress to do that...
2256 			 */
2257 			vm_object_paging_end(object);
2258 			vm_object_collapse(object, vm_object_trunc_page(offset), TRUE);
2259 			vm_object_paging_begin(object);
2260 		} else {
2261 			*protection &= (~VM_PROT_WRITE);
2262 		}
2263 	}
2264 	/*
2265 	 * Now check whether the page needs to be pushed into the
2266 	 * copy object.  The use of asymmetric copy on write for
2267 	 * shared temporary objects means that we may do two copies to
2268 	 * satisfy the fault; one above to get the page from a
2269 	 * shadowed object, and one here to push it into the copy.
2270 	 */
2271 	try_failed_count = 0;
2272 
2273 	while ((copy_object = first_object->vo_copy) != VM_OBJECT_NULL) {
2274 		vm_object_offset_t      copy_offset;
2275 		vm_page_t               copy_m;
2276 
2277 #if TRACEFAULTPAGE
2278 		dbgTrace(0xBEEF0017, (unsigned int) copy_object, (unsigned int) fault_type);    /* (TEST/DEBUG) */
2279 #endif
2280 		/*
2281 		 * If the page is being written, but hasn't been
2282 		 * copied to the copy-object, we have to copy it there.
2283 		 */
2284 		if ((fault_type & VM_PROT_WRITE) == 0) {
2285 			*protection &= ~VM_PROT_WRITE;
2286 			break;
2287 		}
2288 
2289 		/*
2290 		 * If the page was guaranteed to be resident,
2291 		 * we must have already performed the copy.
2292 		 */
2293 		if (must_be_resident) {
2294 			break;
2295 		}
2296 
2297 		/*
2298 		 * Try to get the lock on the copy_object.
2299 		 */
2300 		if (!vm_object_lock_try(copy_object)) {
2301 			vm_object_unlock(object);
2302 			try_failed_count++;
2303 
2304 			mutex_pause(try_failed_count);  /* wait a bit */
2305 			vm_object_lock(object);
2306 
2307 			continue;
2308 		}
2309 		try_failed_count = 0;
2310 
2311 		/*
2312 		 * Make another reference to the copy-object,
2313 		 * to keep it from disappearing during the
2314 		 * copy.
2315 		 */
2316 		vm_object_reference_locked(copy_object);
2317 
2318 		/*
2319 		 * Does the page exist in the copy?
2320 		 */
2321 		copy_offset = first_offset - copy_object->vo_shadow_offset;
2322 		copy_offset = vm_object_trunc_page(copy_offset);
2323 
2324 		if (copy_object->vo_size <= copy_offset) {
2325 			/*
2326 			 * Copy object doesn't cover this page -- do nothing.
2327 			 */
2328 			;
2329 		} else if ((copy_m = vm_page_lookup(copy_object, copy_offset)) != VM_PAGE_NULL) {
2330 			/*
2331 			 * Page currently exists in the copy object
2332 			 */
2333 			if (copy_m->vmp_busy) {
2334 				/*
2335 				 * If the page is being brought
2336 				 * in, wait for it and then retry.
2337 				 */
2338 				RELEASE_PAGE(m);
2339 
2340 				/*
2341 				 * take an extra ref so object won't die
2342 				 */
2343 				vm_object_reference_locked(copy_object);
2344 				vm_object_unlock(copy_object);
2345 				vm_fault_cleanup(object, first_m);
2346 
2347 				vm_object_lock(copy_object);
2348 				assert(copy_object->ref_count > 0);
2349 				vm_object_lock_assert_exclusive(copy_object);
2350 				copy_object->ref_count--;
2351 				assert(copy_object->ref_count > 0);
2352 				copy_m = vm_page_lookup(copy_object, copy_offset);
2353 
2354 				if (copy_m != VM_PAGE_NULL && copy_m->vmp_busy) {
2355 					wait_result = vm_page_sleep(copy_object, copy_m, interruptible, LCK_SLEEP_UNLOCK);
2356 					vm_object_deallocate(copy_object);
2357 
2358 					goto backoff;
2359 				} else {
2360 					vm_object_unlock(copy_object);
2361 					vm_object_deallocate(copy_object);
2362 					thread_interrupt_level(interruptible_state);
2363 
2364 					return VM_FAULT_RETRY;
2365 				}
2366 			}
2367 		} else if (!PAGED_OUT(copy_object, copy_offset)) {
2368 			/*
2369 			 * If PAGED_OUT is TRUE, then the page used to exist
2370 			 * in the copy-object, and has already been paged out.
2371 			 * We don't need to repeat this. If PAGED_OUT is
2372 			 * FALSE, then either we don't know (!pager_created,
2373 			 * for example) or it hasn't been paged out.
2374 			 * (VM_EXTERNAL_STATE_UNKNOWN||VM_EXTERNAL_STATE_ABSENT)
2375 			 * We must copy the page to the copy object.
2376 			 *
2377 			 * Allocate a page for the copy
2378 			 */
2379 			copy_m = vm_page_alloc(copy_object, copy_offset);
2380 
2381 			if (copy_m == VM_PAGE_NULL) {
2382 				RELEASE_PAGE(m);
2383 
2384 				vm_object_lock_assert_exclusive(copy_object);
2385 				copy_object->ref_count--;
2386 				assert(copy_object->ref_count > 0);
2387 
2388 				vm_object_unlock(copy_object);
2389 				vm_fault_cleanup(object, first_m);
2390 				thread_interrupt_level(interruptible_state);
2391 
2392 				return VM_FAULT_MEMORY_SHORTAGE;
2393 			}
2394 			/*
2395 			 * Must copy page into copy-object.
2396 			 */
2397 			vm_page_copy(m, copy_m);
2398 
2399 			/*
2400 			 * If the old page was in use by any users
2401 			 * of the copy-object, it must be removed
2402 			 * from all pmaps.  (We can't know which
2403 			 * pmaps use it.)
2404 			 */
2405 			if (m->vmp_pmapped) {
2406 				pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(m));
2407 			}
2408 
2409 			if (m->vmp_clustered) {
2410 				VM_PAGE_COUNT_AS_PAGEIN(m);
2411 				VM_PAGE_CONSUME_CLUSTERED(m);
2412 			}
2413 			/*
2414 			 * If there's a pager, then immediately
2415 			 * page out this page, using the "initialize"
2416 			 * option.  Else, we use the copy.
2417 			 */
2418 			if ((!copy_object->pager_ready)
2419 			    || vm_object_compressor_pager_state_get(copy_object, copy_offset) == VM_EXTERNAL_STATE_ABSENT
2420 			    ) {
2421 				vm_page_lockspin_queues();
2422 				assert(!m->vmp_cleaning);
2423 				vm_page_activate(copy_m);
2424 				vm_page_unlock_queues();
2425 
2426 				SET_PAGE_DIRTY(copy_m, TRUE);
2427 				vm_page_wakeup_done(copy_object, copy_m);
2428 			} else {
2429 				assert(copy_m->vmp_busy == TRUE);
2430 				assert(!m->vmp_cleaning);
2431 
2432 				/*
2433 				 * dirty is protected by the object lock
2434 				 */
2435 				SET_PAGE_DIRTY(copy_m, TRUE);
2436 
2437 				/*
2438 				 * The page is already ready for pageout:
2439 				 * not on pageout queues and busy.
2440 				 * Unlock everything except the
2441 				 * copy_object itself.
2442 				 */
2443 				vm_object_unlock(object);
2444 
2445 				/*
2446 				 * Write the page to the copy-object,
2447 				 * flushing it from the kernel.
2448 				 */
2449 				vm_pageout_initialize_page(copy_m);
2450 
2451 				/*
2452 				 * Since the pageout may have
2453 				 * temporarily dropped the
2454 				 * copy_object's lock, we
2455 				 * check whether we'll have
2456 				 * to deallocate the hard way.
2457 				 */
2458 				if ((copy_object->shadow != object) || (copy_object->ref_count == 1)) {
2459 					vm_object_unlock(copy_object);
2460 					vm_object_deallocate(copy_object);
2461 					vm_object_lock(object);
2462 
2463 					continue;
2464 				}
2465 				/*
2466 				 * Pick back up the old object's
2467 				 * lock.  [It is safe to do so,
2468 				 * since it must be deeper in the
2469 				 * object tree.]
2470 				 */
2471 				vm_object_lock(object);
2472 			}
2473 
2474 			/*
2475 			 * Because we're pushing a page upward
2476 			 * in the object tree, we must restart
2477 			 * any faults that are waiting here.
2478 			 * [Note that this is an expansion of
2479 			 * vm_page_wakeup() that uses the THREAD_RESTART
2480 			 * wait result].  Can't turn off the page's
2481 			 * busy bit because we're not done with it.
2482 			 */
2483 			if (m->vmp_wanted) {
2484 				m->vmp_wanted = FALSE;
2485 				thread_wakeup_with_result((event_t) m, THREAD_RESTART);
2486 			}
2487 		}
2488 		/*
2489 		 * The reference count on copy_object must be
2490 		 * at least 2: one for our extra reference,
2491 		 * and at least one from the outside world
2492 		 * (we checked that when we last locked
2493 		 * copy_object).
2494 		 */
2495 		vm_object_lock_assert_exclusive(copy_object);
2496 		copy_object->ref_count--;
2497 		assert(copy_object->ref_count > 0);
2498 
2499 		vm_object_unlock(copy_object);
2500 
2501 		break;
2502 	}
2503 
2504 done:
2505 	*result_page = m;
2506 	*top_page = first_m;
2507 
2508 	if (m != VM_PAGE_NULL) {
2509 		assert(VM_PAGE_OBJECT(m) == object);
2510 
2511 		retval = VM_FAULT_SUCCESS;
2512 
2513 		if (my_fault == DBG_PAGEIN_FAULT) {
2514 			VM_PAGE_COUNT_AS_PAGEIN(m);
2515 
2516 			if (object->internal) {
2517 				my_fault = DBG_PAGEIND_FAULT;
2518 			} else {
2519 				my_fault = DBG_PAGEINV_FAULT;
2520 			}
2521 
2522 			/*
2523 			 * evaluate access pattern and update state
2524 			 * vm_fault_deactivate_behind depends on the
2525 			 * state being up to date
2526 			 */
2527 			vm_fault_is_sequential(object, offset, fault_info->behavior);
2528 			vm_fault_deactivate_behind(object, offset, fault_info->behavior);
2529 		} else if (type_of_fault == NULL && my_fault == DBG_CACHE_HIT_FAULT) {
2530 			/*
2531 			 * we weren't called from vm_fault, so handle the
2532 			 * accounting here for hits in the cache
2533 			 */
2534 			if (m->vmp_clustered) {
2535 				VM_PAGE_COUNT_AS_PAGEIN(m);
2536 				VM_PAGE_CONSUME_CLUSTERED(m);
2537 			}
2538 			vm_fault_is_sequential(object, offset, fault_info->behavior);
2539 			vm_fault_deactivate_behind(object, offset, fault_info->behavior);
2540 		} else if (my_fault == DBG_COMPRESSOR_FAULT || my_fault == DBG_COMPRESSOR_SWAPIN_FAULT) {
2541 			VM_STAT_DECOMPRESSIONS();
2542 		}
2543 		if (type_of_fault) {
2544 			*type_of_fault = my_fault;
2545 		}
2546 	} else {
2547 		ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_SUCCESS_NO_PAGE), 0 /* arg */);
2548 		retval = VM_FAULT_SUCCESS_NO_VM_PAGE;
2549 		assert(first_m == VM_PAGE_NULL);
2550 		assert(object == first_object);
2551 	}
2552 
2553 	thread_interrupt_level(interruptible_state);
2554 
2555 #if TRACEFAULTPAGE
2556 	dbgTrace(0xBEEF001A, (unsigned int) VM_FAULT_SUCCESS, 0);       /* (TEST/DEBUG) */
2557 #endif
2558 	return retval;
2559 
2560 backoff:
2561 	thread_interrupt_level(interruptible_state);
2562 
2563 	if (wait_result == THREAD_INTERRUPTED) {
2564 		ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_FAULT_INTERRUPTED), 0 /* arg */);
2565 		return VM_FAULT_INTERRUPTED;
2566 	}
2567 	return VM_FAULT_RETRY;
2568 
2569 #undef  RELEASE_PAGE
2570 }
2571 
2572 #if MACH_ASSERT && (XNU_PLATFORM_WatchOS || __x86_64__)
2573 #define PANIC_ON_CS_KILLED_DEFAULT true
2574 #else
2575 #define PANIC_ON_CS_KILLED_DEFAULT false
2576 #endif
2577 static TUNABLE(bool, panic_on_cs_killed, "panic_on_cs_killed",
2578     PANIC_ON_CS_KILLED_DEFAULT);
2579 
2580 extern int proc_selfpid(void);
2581 extern char *proc_name_address(struct proc *p);
2582 extern const char *proc_best_name(struct proc *);
2583 unsigned long cs_enter_tainted_rejected = 0;
2584 unsigned long cs_enter_tainted_accepted = 0;
2585 
2586 /*
2587  * CODE SIGNING:
2588  * When soft faulting a page, we have to validate the page if:
2589  * 1. the page is being mapped in user space
2590  * 2. the page hasn't already been found to be "tainted"
2591  * 3. the page belongs to a code-signed object
2592  * 4. the page has not been validated yet or has been mapped for write.
2593  */
2594 static bool
vm_fault_cs_need_validation(pmap_t pmap,vm_page_t page,vm_object_t page_obj,vm_map_size_t fault_page_size,vm_map_offset_t fault_phys_offset)2595 vm_fault_cs_need_validation(
2596 	pmap_t pmap,
2597 	vm_page_t page,
2598 	vm_object_t page_obj,
2599 	vm_map_size_t fault_page_size,
2600 	vm_map_offset_t fault_phys_offset)
2601 {
2602 	if (pmap == kernel_pmap) {
2603 		/* 1 - not user space */
2604 		return false;
2605 	}
2606 	if (!page_obj->code_signed) {
2607 		/* 3 - page does not belong to a code-signed object */
2608 		return false;
2609 	}
2610 	if (fault_page_size == PAGE_SIZE) {
2611 		/* looking at the whole page */
2612 		assertf(fault_phys_offset == 0,
2613 		    "fault_page_size 0x%llx fault_phys_offset 0x%llx\n",
2614 		    (uint64_t)fault_page_size,
2615 		    (uint64_t)fault_phys_offset);
2616 		if (page->vmp_cs_tainted == VMP_CS_ALL_TRUE) {
2617 			/* 2 - page is all tainted */
2618 			return false;
2619 		}
2620 		if (page->vmp_cs_validated == VMP_CS_ALL_TRUE &&
2621 		    !page->vmp_wpmapped) {
2622 			/* 4 - already fully validated and never mapped writable */
2623 			return false;
2624 		}
2625 	} else {
2626 		/* looking at a specific sub-page */
2627 		if (VMP_CS_TAINTED(page, fault_page_size, fault_phys_offset)) {
2628 			/* 2 - sub-page was already marked as tainted */
2629 			return false;
2630 		}
2631 		if (VMP_CS_VALIDATED(page, fault_page_size, fault_phys_offset) &&
2632 		    !page->vmp_wpmapped) {
2633 			/* 4 - already validated and never mapped writable */
2634 			return false;
2635 		}
2636 	}
2637 	/* page needs to be validated */
2638 	return true;
2639 }
2640 
2641 
2642 static bool
vm_fault_cs_page_immutable(vm_page_t m,vm_map_size_t fault_page_size,vm_map_offset_t fault_phys_offset,vm_prot_t prot __unused)2643 vm_fault_cs_page_immutable(
2644 	vm_page_t m,
2645 	vm_map_size_t fault_page_size,
2646 	vm_map_offset_t fault_phys_offset,
2647 	vm_prot_t prot __unused)
2648 {
2649 	if (VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset)
2650 	    /*&& ((prot) & VM_PROT_EXECUTE)*/) {
2651 		return true;
2652 	}
2653 	return false;
2654 }
2655 
2656 static bool
vm_fault_cs_page_nx(vm_page_t m,vm_map_size_t fault_page_size,vm_map_offset_t fault_phys_offset)2657 vm_fault_cs_page_nx(
2658 	vm_page_t m,
2659 	vm_map_size_t fault_page_size,
2660 	vm_map_offset_t fault_phys_offset)
2661 {
2662 	return VMP_CS_NX(m, fault_page_size, fault_phys_offset);
2663 }
2664 
2665 /*
2666  * Check if the page being entered into the pmap violates code signing.
2667  */
2668 static kern_return_t
vm_fault_cs_check_violation(bool cs_bypass,vm_object_t object,vm_page_t m,pmap_t pmap,vm_prot_t prot,vm_prot_t caller_prot,vm_map_size_t fault_page_size,vm_map_offset_t fault_phys_offset,vm_object_fault_info_t fault_info,bool map_is_switched,bool map_is_switch_protected,bool * cs_violation)2669 vm_fault_cs_check_violation(
2670 	bool cs_bypass,
2671 	vm_object_t object,
2672 	vm_page_t m,
2673 	pmap_t pmap,
2674 	vm_prot_t prot,
2675 	vm_prot_t caller_prot,
2676 	vm_map_size_t fault_page_size,
2677 	vm_map_offset_t fault_phys_offset,
2678 	vm_object_fault_info_t fault_info,
2679 	bool map_is_switched,
2680 	bool map_is_switch_protected,
2681 	bool *cs_violation)
2682 {
2683 #if !CODE_SIGNING_MONITOR
2684 #pragma unused(caller_prot)
2685 #pragma unused(fault_info)
2686 #endif /* !CODE_SIGNING_MONITOR */
2687 
2688 	int             cs_enforcement_enabled;
2689 	if (!cs_bypass &&
2690 	    vm_fault_cs_need_validation(pmap, m, object,
2691 	    fault_page_size, fault_phys_offset)) {
2692 		vm_object_lock_assert_exclusive(object);
2693 
2694 		if (VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset)) {
2695 			vm_cs_revalidates++;
2696 		}
2697 
2698 		/* VM map is locked, so 1 ref will remain on VM object -
2699 		 * so no harm if vm_page_validate_cs drops the object lock */
2700 
2701 #if CODE_SIGNING_MONITOR
2702 		if (fault_info->csm_associated &&
2703 		    csm_enabled() &&
2704 		    !VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset) &&
2705 		    !VMP_CS_TAINTED(m, fault_page_size, fault_phys_offset) &&
2706 		    !VMP_CS_NX(m, fault_page_size, fault_phys_offset) &&
2707 		    (prot & VM_PROT_EXECUTE) &&
2708 		    (caller_prot & VM_PROT_EXECUTE)) {
2709 			/*
2710 			 * When we have a code signing monitor, the monitor will evaluate the code signature
2711 			 * for any executable page mapping. No need for the VM to also validate the page.
2712 			 * In the code signing monitor we trust :)
2713 			 */
2714 			vm_cs_defer_to_csm++;
2715 		} else {
2716 			vm_cs_defer_to_csm_not++;
2717 			vm_page_validate_cs(m, fault_page_size, fault_phys_offset);
2718 		}
2719 #else /* CODE_SIGNING_MONITOR */
2720 		vm_page_validate_cs(m, fault_page_size, fault_phys_offset);
2721 #endif /* CODE_SIGNING_MONITOR */
2722 	}
2723 
2724 	/* If the map is switched, and is switch-protected, we must protect
2725 	 * some pages from being write-faulted: immutable pages because by
2726 	 * definition they may not be written, and executable pages because that
2727 	 * would provide a way to inject unsigned code.
2728 	 * If the page is immutable, we can simply return. However, we can't
2729 	 * immediately determine whether a page is executable anywhere. But,
2730 	 * we can disconnect it everywhere and remove the executable protection
2731 	 * from the current map. We do that below right before we do the
2732 	 * PMAP_ENTER.
2733 	 */
2734 	if (pmap == kernel_pmap) {
2735 		/* kernel fault: cs_enforcement does not apply */
2736 		cs_enforcement_enabled = 0;
2737 	} else {
2738 		cs_enforcement_enabled = pmap_get_vm_map_cs_enforced(pmap);
2739 	}
2740 
2741 	if (cs_enforcement_enabled && map_is_switched &&
2742 	    map_is_switch_protected &&
2743 	    vm_fault_cs_page_immutable(m, fault_page_size, fault_phys_offset, prot) &&
2744 	    (prot & VM_PROT_WRITE)) {
2745 		ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_FAILED_IMMUTABLE_PAGE_WRITE), 0 /* arg */);
2746 		return KERN_CODESIGN_ERROR;
2747 	}
2748 
2749 	if (cs_enforcement_enabled &&
2750 	    vm_fault_cs_page_nx(m, fault_page_size, fault_phys_offset) &&
2751 	    (prot & VM_PROT_EXECUTE)) {
2752 		if (cs_debug) {
2753 			printf("page marked to be NX, not letting it be mapped EXEC\n");
2754 		}
2755 		ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_FAILED_NX_PAGE_EXEC_MAPPING), 0 /* arg */);
2756 		return KERN_CODESIGN_ERROR;
2757 	}
2758 
2759 	/* A page could be tainted, or pose a risk of being tainted later.
2760 	 * Check whether the receiving process wants it, and make it feel
2761 	 * the consequences (that hapens in cs_invalid_page()).
2762 	 * For CS Enforcement, two other conditions will
2763 	 * cause that page to be tainted as well:
2764 	 * - pmapping an unsigned page executable - this means unsigned code;
2765 	 * - writeable mapping of a validated page - the content of that page
2766 	 *   can be changed without the kernel noticing, therefore unsigned
2767 	 *   code can be created
2768 	 */
2769 	if (cs_bypass) {
2770 		/* code-signing is bypassed */
2771 		*cs_violation = FALSE;
2772 	} else if (VMP_CS_TAINTED(m, fault_page_size, fault_phys_offset)) {
2773 		/* tainted page */
2774 		*cs_violation = TRUE;
2775 	} else if (!cs_enforcement_enabled) {
2776 		/* no further code-signing enforcement */
2777 		*cs_violation = FALSE;
2778 	} else if (vm_fault_cs_page_immutable(m, fault_page_size, fault_phys_offset, prot) &&
2779 	    ((prot & VM_PROT_WRITE) ||
2780 	    m->vmp_wpmapped)) {
2781 		/*
2782 		 * The page should be immutable, but is in danger of being
2783 		 * modified.
2784 		 * This is the case where we want policy from the code
2785 		 * directory - is the page immutable or not? For now we have
2786 		 * to assume that code pages will be immutable, data pages not.
2787 		 * We'll assume a page is a code page if it has a code directory
2788 		 * and we fault for execution.
2789 		 * That is good enough since if we faulted the code page for
2790 		 * writing in another map before, it is wpmapped; if we fault
2791 		 * it for writing in this map later it will also be faulted for
2792 		 * executing at the same time; and if we fault for writing in
2793 		 * another map later, we will disconnect it from this pmap so
2794 		 * we'll notice the change.
2795 		 */
2796 		*cs_violation = TRUE;
2797 	} else if (!VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset) &&
2798 	    (prot & VM_PROT_EXECUTE)
2799 #if CODE_SIGNING_MONITOR
2800 	    /*
2801 	     * Executable pages will be validated by the code signing monitor. If the
2802 	     * code signing monitor is turned off, then this is a code-signing violation.
2803 	     */
2804 	    && !csm_enabled()
2805 #endif /* CODE_SIGNING_MONITOR */
2806 	    ) {
2807 		*cs_violation = TRUE;
2808 	} else {
2809 		*cs_violation = FALSE;
2810 	}
2811 	return KERN_SUCCESS;
2812 }
2813 
2814 /*
2815  * Handles a code signing violation by either rejecting the page or forcing a disconnect.
2816  * @param must_disconnect This value will be set to true if the caller must disconnect
2817  * this page.
2818  * @return If this function does not return KERN_SUCCESS, the caller must abort the page fault.
2819  */
2820 static kern_return_t
vm_fault_cs_handle_violation(vm_object_t object,vm_page_t m,pmap_t pmap,vm_prot_t prot,vm_map_offset_t vaddr,vm_map_size_t fault_page_size,vm_map_offset_t fault_phys_offset,bool map_is_switched,bool map_is_switch_protected,bool * must_disconnect)2821 vm_fault_cs_handle_violation(
2822 	vm_object_t object,
2823 	vm_page_t m,
2824 	pmap_t pmap,
2825 	vm_prot_t prot,
2826 	vm_map_offset_t vaddr,
2827 	vm_map_size_t fault_page_size,
2828 	vm_map_offset_t fault_phys_offset,
2829 	bool map_is_switched,
2830 	bool map_is_switch_protected,
2831 	bool *must_disconnect)
2832 {
2833 #if !MACH_ASSERT
2834 #pragma unused(pmap)
2835 #pragma unused(map_is_switch_protected)
2836 #endif /* !MACH_ASSERT */
2837 	/*
2838 	 * We will have a tainted page. Have to handle the special case
2839 	 * of a switched map now. If the map is not switched, standard
2840 	 * procedure applies - call cs_invalid_page().
2841 	 * If the map is switched, the real owner is invalid already.
2842 	 * There is no point in invalidating the switching process since
2843 	 * it will not be executing from the map. So we don't call
2844 	 * cs_invalid_page() in that case.
2845 	 */
2846 	boolean_t reject_page, cs_killed;
2847 	kern_return_t kr;
2848 	if (map_is_switched) {
2849 		assert(pmap == vm_map_pmap(current_thread()->map));
2850 		assert(!(prot & VM_PROT_WRITE) || (map_is_switch_protected == FALSE));
2851 		reject_page = FALSE;
2852 	} else {
2853 		if (cs_debug > 5) {
2854 			printf("vm_fault: signed: %s validate: %s tainted: %s wpmapped: %s prot: 0x%x\n",
2855 			    object->code_signed ? "yes" : "no",
2856 			    VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset) ? "yes" : "no",
2857 			    VMP_CS_TAINTED(m, fault_page_size, fault_phys_offset) ? "yes" : "no",
2858 			    m->vmp_wpmapped ? "yes" : "no",
2859 			    (int)prot);
2860 		}
2861 		reject_page = cs_invalid_page((addr64_t) vaddr, &cs_killed);
2862 	}
2863 
2864 	if (reject_page) {
2865 		/* reject the invalid page: abort the page fault */
2866 		int                     pid;
2867 		const char              *procname;
2868 		task_t                  task;
2869 		vm_object_t             file_object, shadow;
2870 		vm_object_offset_t      file_offset;
2871 		char                    *pathname, *filename;
2872 		vm_size_t               pathname_len, filename_len;
2873 		boolean_t               truncated_path;
2874 #define __PATH_MAX 1024
2875 		struct timespec         mtime, cs_mtime;
2876 		int                     shadow_depth;
2877 		os_reason_t             codesigning_exit_reason = OS_REASON_NULL;
2878 
2879 		kr = KERN_CODESIGN_ERROR;
2880 		cs_enter_tainted_rejected++;
2881 
2882 		/* get process name and pid */
2883 		procname = "?";
2884 		task = current_task();
2885 		pid = proc_selfpid();
2886 		if (get_bsdtask_info(task) != NULL) {
2887 			procname = proc_name_address(get_bsdtask_info(task));
2888 		}
2889 
2890 		/* get file's VM object */
2891 		file_object = object;
2892 		file_offset = m->vmp_offset;
2893 		for (shadow = file_object->shadow,
2894 		    shadow_depth = 0;
2895 		    shadow != VM_OBJECT_NULL;
2896 		    shadow = file_object->shadow,
2897 		    shadow_depth++) {
2898 			vm_object_lock_shared(shadow);
2899 			if (file_object != object) {
2900 				vm_object_unlock(file_object);
2901 			}
2902 			file_offset += file_object->vo_shadow_offset;
2903 			file_object = shadow;
2904 		}
2905 
2906 		mtime.tv_sec = 0;
2907 		mtime.tv_nsec = 0;
2908 		cs_mtime.tv_sec = 0;
2909 		cs_mtime.tv_nsec = 0;
2910 
2911 		/* get file's pathname and/or filename */
2912 		pathname = NULL;
2913 		filename = NULL;
2914 		pathname_len = 0;
2915 		filename_len = 0;
2916 		truncated_path = FALSE;
2917 		/* no pager -> no file -> no pathname, use "<nil>" in that case */
2918 		if (file_object->pager != NULL) {
2919 			pathname = kalloc_data(__PATH_MAX * 2, Z_WAITOK);
2920 			if (pathname) {
2921 				pathname[0] = '\0';
2922 				pathname_len = __PATH_MAX;
2923 				filename = pathname + pathname_len;
2924 				filename_len = __PATH_MAX;
2925 
2926 				if (vnode_pager_get_object_name(file_object->pager,
2927 				    pathname,
2928 				    pathname_len,
2929 				    filename,
2930 				    filename_len,
2931 				    &truncated_path) == KERN_SUCCESS) {
2932 					/* safety first... */
2933 					pathname[__PATH_MAX - 1] = '\0';
2934 					filename[__PATH_MAX - 1] = '\0';
2935 
2936 					vnode_pager_get_object_mtime(file_object->pager,
2937 					    &mtime,
2938 					    &cs_mtime);
2939 				} else {
2940 					kfree_data(pathname, __PATH_MAX * 2);
2941 					pathname = NULL;
2942 					filename = NULL;
2943 					pathname_len = 0;
2944 					filename_len = 0;
2945 					truncated_path = FALSE;
2946 				}
2947 			}
2948 		}
2949 		printf("CODE SIGNING: process %d[%s]: "
2950 		    "rejecting invalid page at address 0x%llx "
2951 		    "from offset 0x%llx in file \"%s%s%s\" "
2952 		    "(cs_mtime:%lu.%ld %s mtime:%lu.%ld) "
2953 		    "(signed:%d validated:%d tainted:%d nx:%d "
2954 		    "wpmapped:%d dirty:%d depth:%d)\n",
2955 		    pid, procname, (addr64_t) vaddr,
2956 		    file_offset,
2957 		    (pathname ? pathname : "<nil>"),
2958 		    (truncated_path ? "/.../" : ""),
2959 		    (truncated_path ? filename : ""),
2960 		    cs_mtime.tv_sec, cs_mtime.tv_nsec,
2961 		    ((cs_mtime.tv_sec == mtime.tv_sec &&
2962 		    cs_mtime.tv_nsec == mtime.tv_nsec)
2963 		    ? "=="
2964 		    : "!="),
2965 		    mtime.tv_sec, mtime.tv_nsec,
2966 		    object->code_signed,
2967 		    VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset),
2968 		    VMP_CS_TAINTED(m, fault_page_size, fault_phys_offset),
2969 		    VMP_CS_NX(m, fault_page_size, fault_phys_offset),
2970 		    m->vmp_wpmapped,
2971 		    m->vmp_dirty,
2972 		    shadow_depth);
2973 
2974 		/*
2975 		 * We currently only generate an exit reason if cs_invalid_page directly killed a process. If cs_invalid_page
2976 		 * did not kill the process (more the case on desktop), vm_fault_enter will not satisfy the fault and whether the
2977 		 * process dies is dependent on whether there is a signal handler registered for SIGSEGV and how that handler
2978 		 * will deal with the segmentation fault.
2979 		 */
2980 		if (cs_killed) {
2981 			KDBG(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2982 			    pid, OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_INVALID_PAGE);
2983 
2984 			codesigning_exit_reason = os_reason_create(OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_INVALID_PAGE);
2985 			if (codesigning_exit_reason == NULL) {
2986 				printf("vm_fault_enter: failed to allocate codesigning exit reason\n");
2987 			} else {
2988 				mach_vm_address_t data_addr = 0;
2989 				struct codesigning_exit_reason_info *ceri = NULL;
2990 				uint32_t reason_buffer_size_estimate = kcdata_estimate_required_buffer_size(1, sizeof(*ceri));
2991 
2992 				if (os_reason_alloc_buffer_noblock(codesigning_exit_reason, reason_buffer_size_estimate)) {
2993 					printf("vm_fault_enter: failed to allocate buffer for codesigning exit reason\n");
2994 				} else {
2995 					if (KERN_SUCCESS == kcdata_get_memory_addr(&codesigning_exit_reason->osr_kcd_descriptor,
2996 					    EXIT_REASON_CODESIGNING_INFO, sizeof(*ceri), &data_addr)) {
2997 						ceri = (struct codesigning_exit_reason_info *)data_addr;
2998 						static_assert(__PATH_MAX == sizeof(ceri->ceri_pathname));
2999 
3000 						ceri->ceri_virt_addr = vaddr;
3001 						ceri->ceri_file_offset = file_offset;
3002 						if (pathname) {
3003 							strncpy((char *)&ceri->ceri_pathname, pathname, sizeof(ceri->ceri_pathname));
3004 						} else {
3005 							ceri->ceri_pathname[0] = '\0';
3006 						}
3007 						if (filename) {
3008 							strncpy((char *)&ceri->ceri_filename, filename, sizeof(ceri->ceri_filename));
3009 						} else {
3010 							ceri->ceri_filename[0] = '\0';
3011 						}
3012 						ceri->ceri_path_truncated = (truncated_path ? 1 : 0);
3013 						ceri->ceri_codesig_modtime_secs = cs_mtime.tv_sec;
3014 						ceri->ceri_codesig_modtime_nsecs = cs_mtime.tv_nsec;
3015 						ceri->ceri_page_modtime_secs = mtime.tv_sec;
3016 						ceri->ceri_page_modtime_nsecs = mtime.tv_nsec;
3017 						ceri->ceri_object_codesigned = (object->code_signed);
3018 						ceri->ceri_page_codesig_validated = VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset);
3019 						ceri->ceri_page_codesig_tainted = VMP_CS_TAINTED(m, fault_page_size, fault_phys_offset);
3020 						ceri->ceri_page_codesig_nx = VMP_CS_NX(m, fault_page_size, fault_phys_offset);
3021 						ceri->ceri_page_wpmapped = (m->vmp_wpmapped);
3022 						ceri->ceri_page_slid = 0;
3023 						ceri->ceri_page_dirty = (m->vmp_dirty);
3024 						ceri->ceri_page_shadow_depth = shadow_depth;
3025 					} else {
3026 #if DEBUG || DEVELOPMENT
3027 						panic("vm_fault_enter: failed to allocate kcdata for codesigning exit reason");
3028 #else
3029 						printf("vm_fault_enter: failed to allocate kcdata for codesigning exit reason\n");
3030 #endif /* DEBUG || DEVELOPMENT */
3031 						/* Free the buffer */
3032 						os_reason_alloc_buffer_noblock(codesigning_exit_reason, 0);
3033 					}
3034 				}
3035 			}
3036 
3037 			set_thread_exit_reason(current_thread(), codesigning_exit_reason, FALSE);
3038 		}
3039 		if (panic_on_cs_killed &&
3040 		    object->object_is_shared_cache) {
3041 			char *tainted_contents;
3042 			vm_map_offset_t src_vaddr;
3043 			src_vaddr = (vm_map_offset_t) phystokv((pmap_paddr_t)VM_PAGE_GET_PHYS_PAGE(m) << PAGE_SHIFT);
3044 			tainted_contents = kalloc_data(PAGE_SIZE, Z_WAITOK);
3045 			bcopy((const char *)src_vaddr, tainted_contents, PAGE_SIZE);
3046 			printf("CODE SIGNING: tainted page %p phys 0x%x phystokv 0x%llx copied to %p\n", m, VM_PAGE_GET_PHYS_PAGE(m), (uint64_t)src_vaddr, tainted_contents);
3047 			panic("CODE SIGNING: process %d[%s]: "
3048 			    "rejecting invalid page (phys#0x%x) at address 0x%llx "
3049 			    "from offset 0x%llx in file \"%s%s%s\" "
3050 			    "(cs_mtime:%lu.%ld %s mtime:%lu.%ld) "
3051 			    "(signed:%d validated:%d tainted:%d nx:%d"
3052 			    "wpmapped:%d dirty:%d depth:%d)\n",
3053 			    pid, procname,
3054 			    VM_PAGE_GET_PHYS_PAGE(m),
3055 			    (addr64_t) vaddr,
3056 			    file_offset,
3057 			    (pathname ? pathname : "<nil>"),
3058 			    (truncated_path ? "/.../" : ""),
3059 			    (truncated_path ? filename : ""),
3060 			    cs_mtime.tv_sec, cs_mtime.tv_nsec,
3061 			    ((cs_mtime.tv_sec == mtime.tv_sec &&
3062 			    cs_mtime.tv_nsec == mtime.tv_nsec)
3063 			    ? "=="
3064 			    : "!="),
3065 			    mtime.tv_sec, mtime.tv_nsec,
3066 			    object->code_signed,
3067 			    VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset),
3068 			    VMP_CS_TAINTED(m, fault_page_size, fault_phys_offset),
3069 			    VMP_CS_NX(m, fault_page_size, fault_phys_offset),
3070 			    m->vmp_wpmapped,
3071 			    m->vmp_dirty,
3072 			    shadow_depth);
3073 		}
3074 
3075 		if (file_object != object) {
3076 			vm_object_unlock(file_object);
3077 		}
3078 		if (pathname_len != 0) {
3079 			kfree_data(pathname, __PATH_MAX * 2);
3080 			pathname = NULL;
3081 			filename = NULL;
3082 		}
3083 	} else {
3084 		/* proceed with the invalid page */
3085 		kr = KERN_SUCCESS;
3086 		if (!VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset) &&
3087 		    !object->code_signed) {
3088 			/*
3089 			 * This page has not been (fully) validated but
3090 			 * does not belong to a code-signed object
3091 			 * so it should not be forcefully considered
3092 			 * as tainted.
3093 			 * We're just concerned about it here because
3094 			 * we've been asked to "execute" it but that
3095 			 * does not mean that it should cause other
3096 			 * accesses to fail.
3097 			 * This happens when a debugger sets a
3098 			 * breakpoint and we then execute code in
3099 			 * that page.  Marking the page as "tainted"
3100 			 * would cause any inspection tool ("leaks",
3101 			 * "vmmap", "CrashReporter", ...) to get killed
3102 			 * due to code-signing violation on that page,
3103 			 * even though they're just reading it and not
3104 			 * executing from it.
3105 			 */
3106 		} else {
3107 			/*
3108 			 * Page might have been tainted before or not;
3109 			 * now it definitively is. If the page wasn't
3110 			 * tainted, we must disconnect it from all
3111 			 * pmaps later, to force existing mappings
3112 			 * through that code path for re-consideration
3113 			 * of the validity of that page.
3114 			 */
3115 			if (!VMP_CS_TAINTED(m, fault_page_size, fault_phys_offset)) {
3116 				*must_disconnect = TRUE;
3117 				VMP_CS_SET_TAINTED(m, fault_page_size, fault_phys_offset, TRUE);
3118 			}
3119 		}
3120 		cs_enter_tainted_accepted++;
3121 	}
3122 	if (kr != KERN_SUCCESS) {
3123 		if (cs_debug) {
3124 			printf("CODESIGNING: vm_fault_enter(0x%llx): "
3125 			    "*** INVALID PAGE ***\n",
3126 			    (long long)vaddr);
3127 		}
3128 #if !SECURE_KERNEL
3129 		if (cs_enforcement_panic) {
3130 			panic("CODESIGNING: panicking on invalid page");
3131 		}
3132 #endif
3133 	}
3134 	return kr;
3135 }
3136 
3137 /*
3138  * Check that the code signature is valid for the given page being inserted into
3139  * the pmap.
3140  *
3141  * @param must_disconnect This value will be set to true if the caller must disconnect
3142  * this page.
3143  * @return If this function does not return KERN_SUCCESS, the caller must abort the page fault.
3144  */
3145 static kern_return_t
vm_fault_validate_cs(bool cs_bypass,vm_object_t object,vm_page_t m,pmap_t pmap,vm_map_offset_t vaddr,vm_prot_t prot,vm_prot_t caller_prot,vm_map_size_t fault_page_size,vm_map_offset_t fault_phys_offset,vm_object_fault_info_t fault_info,bool * must_disconnect)3146 vm_fault_validate_cs(
3147 	bool cs_bypass,
3148 	vm_object_t object,
3149 	vm_page_t m,
3150 	pmap_t pmap,
3151 	vm_map_offset_t vaddr,
3152 	vm_prot_t prot,
3153 	vm_prot_t caller_prot,
3154 	vm_map_size_t fault_page_size,
3155 	vm_map_offset_t fault_phys_offset,
3156 	vm_object_fault_info_t fault_info,
3157 	bool *must_disconnect)
3158 {
3159 	bool map_is_switched, map_is_switch_protected, cs_violation;
3160 	kern_return_t kr;
3161 	/* Validate code signature if necessary. */
3162 	map_is_switched = ((pmap != vm_map_pmap(current_task()->map)) &&
3163 	    (pmap == vm_map_pmap(current_thread()->map)));
3164 	map_is_switch_protected = current_thread()->map->switch_protect;
3165 	kr = vm_fault_cs_check_violation(cs_bypass, object, m, pmap,
3166 	    prot, caller_prot, fault_page_size, fault_phys_offset, fault_info,
3167 	    map_is_switched, map_is_switch_protected, &cs_violation);
3168 	if (kr != KERN_SUCCESS) {
3169 		return kr;
3170 	}
3171 	if (cs_violation) {
3172 		kr = vm_fault_cs_handle_violation(object, m, pmap, prot, vaddr,
3173 		    fault_page_size, fault_phys_offset,
3174 		    map_is_switched, map_is_switch_protected, must_disconnect);
3175 	}
3176 	return kr;
3177 }
3178 
3179 /*
3180  * Enqueue the page on the appropriate paging queue.
3181  */
3182 static void
vm_fault_enqueue_page(vm_object_t object,vm_page_t m,bool wired,bool change_wiring,vm_tag_t wire_tag,bool no_cache,int * type_of_fault,kern_return_t kr)3183 vm_fault_enqueue_page(
3184 	vm_object_t object,
3185 	vm_page_t m,
3186 	bool wired,
3187 	bool change_wiring,
3188 	vm_tag_t wire_tag,
3189 	bool no_cache,
3190 	int *type_of_fault,
3191 	kern_return_t kr)
3192 {
3193 	assert((m->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) || object != compressor_object);
3194 	boolean_t       page_queues_locked = FALSE;
3195 	boolean_t       previously_pmapped = m->vmp_pmapped;
3196 #define __VM_PAGE_LOCKSPIN_QUEUES_IF_NEEDED()   \
3197 MACRO_BEGIN                                     \
3198 	if (! page_queues_locked) {             \
3199 	        page_queues_locked = TRUE;      \
3200 	        vm_page_lockspin_queues();      \
3201 	}                                       \
3202 MACRO_END
3203 #define __VM_PAGE_UNLOCK_QUEUES_IF_NEEDED()     \
3204 MACRO_BEGIN                                     \
3205 	if (page_queues_locked) {               \
3206 	        page_queues_locked = FALSE;     \
3207 	        vm_page_unlock_queues();        \
3208 	}                                       \
3209 MACRO_END
3210 
3211 	vm_page_update_special_state(m);
3212 	if (m->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) {
3213 		/*
3214 		 * Compressor pages are neither wired
3215 		 * nor pageable and should never change.
3216 		 */
3217 		assert(object == compressor_object);
3218 	} else if (change_wiring) {
3219 		__VM_PAGE_LOCKSPIN_QUEUES_IF_NEEDED();
3220 
3221 		if (wired) {
3222 			if (kr == KERN_SUCCESS) {
3223 				vm_page_wire(m, wire_tag, TRUE);
3224 			}
3225 		} else {
3226 			vm_page_unwire(m, TRUE);
3227 		}
3228 		/* we keep the page queues lock, if we need it later */
3229 	} else {
3230 		if (object->internal == TRUE) {
3231 			/*
3232 			 * don't allow anonymous pages on
3233 			 * the speculative queues
3234 			 */
3235 			no_cache = FALSE;
3236 		}
3237 		if (kr != KERN_SUCCESS) {
3238 			__VM_PAGE_LOCKSPIN_QUEUES_IF_NEEDED();
3239 			vm_page_deactivate(m);
3240 			/* we keep the page queues lock, if we need it later */
3241 		} else if (((m->vmp_q_state == VM_PAGE_NOT_ON_Q) ||
3242 		    (m->vmp_q_state == VM_PAGE_ON_SPECULATIVE_Q) ||
3243 		    (m->vmp_q_state == VM_PAGE_ON_INACTIVE_CLEANED_Q) ||
3244 		    ((m->vmp_q_state != VM_PAGE_ON_THROTTLED_Q) && no_cache)) &&
3245 		    !VM_PAGE_WIRED(m)) {
3246 			if (vm_page_local_q &&
3247 			    (*type_of_fault == DBG_COW_FAULT ||
3248 			    *type_of_fault == DBG_ZERO_FILL_FAULT)) {
3249 				struct vpl      *lq;
3250 				uint32_t        lid;
3251 
3252 				assert(m->vmp_q_state == VM_PAGE_NOT_ON_Q);
3253 
3254 				__VM_PAGE_UNLOCK_QUEUES_IF_NEEDED();
3255 				vm_object_lock_assert_exclusive(object);
3256 
3257 				/*
3258 				 * we got a local queue to stuff this
3259 				 * new page on...
3260 				 * its safe to manipulate local and
3261 				 * local_id at this point since we're
3262 				 * behind an exclusive object lock and
3263 				 * the page is not on any global queue.
3264 				 *
3265 				 * we'll use the current cpu number to
3266 				 * select the queue note that we don't
3267 				 * need to disable preemption... we're
3268 				 * going to be behind the local queue's
3269 				 * lock to do the real work
3270 				 */
3271 				lid = cpu_number();
3272 
3273 				lq = zpercpu_get_cpu(vm_page_local_q, lid);
3274 
3275 				VPL_LOCK(&lq->vpl_lock);
3276 
3277 				vm_page_check_pageable_safe(m);
3278 				vm_page_queue_enter(&lq->vpl_queue, m, vmp_pageq);
3279 				m->vmp_q_state = VM_PAGE_ON_ACTIVE_LOCAL_Q;
3280 				m->vmp_local_id = lid;
3281 				lq->vpl_count++;
3282 
3283 				if (object->internal) {
3284 					lq->vpl_internal_count++;
3285 				} else {
3286 					lq->vpl_external_count++;
3287 				}
3288 
3289 				VPL_UNLOCK(&lq->vpl_lock);
3290 
3291 				if (lq->vpl_count > vm_page_local_q_soft_limit) {
3292 					/*
3293 					 * we're beyond the soft limit
3294 					 * for the local queue
3295 					 * vm_page_reactivate_local will
3296 					 * 'try' to take the global page
3297 					 * queue lock... if it can't
3298 					 * that's ok... we'll let the
3299 					 * queue continue to grow up
3300 					 * to the hard limit... at that
3301 					 * point we'll wait for the
3302 					 * lock... once we've got the
3303 					 * lock, we'll transfer all of
3304 					 * the pages from the local
3305 					 * queue to the global active
3306 					 * queue
3307 					 */
3308 					vm_page_reactivate_local(lid, FALSE, FALSE);
3309 				}
3310 			} else {
3311 				__VM_PAGE_LOCKSPIN_QUEUES_IF_NEEDED();
3312 
3313 				/*
3314 				 * test again now that we hold the
3315 				 * page queue lock
3316 				 */
3317 				if (!VM_PAGE_WIRED(m)) {
3318 					if (m->vmp_q_state == VM_PAGE_ON_INACTIVE_CLEANED_Q) {
3319 						vm_page_queues_remove(m, FALSE);
3320 
3321 						VM_PAGEOUT_DEBUG(vm_pageout_cleaned_reactivated, 1);
3322 						VM_PAGEOUT_DEBUG(vm_pageout_cleaned_fault_reactivated, 1);
3323 					}
3324 
3325 					if (!VM_PAGE_ACTIVE_OR_INACTIVE(m) ||
3326 					    no_cache) {
3327 						/*
3328 						 * If this is a no_cache mapping
3329 						 * and the page has never been
3330 						 * mapped before or was
3331 						 * previously a no_cache page,
3332 						 * then we want to leave pages
3333 						 * in the speculative state so
3334 						 * that they can be readily
3335 						 * recycled if free memory runs
3336 						 * low.  Otherwise the page is
3337 						 * activated as normal.
3338 						 */
3339 
3340 						if (no_cache &&
3341 						    (!previously_pmapped ||
3342 						    m->vmp_no_cache)) {
3343 							m->vmp_no_cache = TRUE;
3344 
3345 							if (m->vmp_q_state != VM_PAGE_ON_SPECULATIVE_Q) {
3346 								vm_page_speculate(m, FALSE);
3347 							}
3348 						} else if (!VM_PAGE_ACTIVE_OR_INACTIVE(m)) {
3349 							vm_page_activate(m);
3350 						}
3351 					}
3352 				}
3353 				/* we keep the page queues lock, if we need it later */
3354 			}
3355 		}
3356 	}
3357 	/* we're done with the page queues lock, if we ever took it */
3358 	__VM_PAGE_UNLOCK_QUEUES_IF_NEEDED();
3359 }
3360 
3361 /*
3362  * Sets the pmmpped, xpmapped, and wpmapped bits on the vm_page_t and updates accounting.
3363  * @return true if the page needs to be sync'ed via pmap_sync-page_data_physo
3364  * before being inserted into the pmap.
3365  */
3366 static bool
vm_fault_enter_set_mapped(vm_object_t object,vm_page_t m,vm_prot_t prot,vm_prot_t fault_type)3367 vm_fault_enter_set_mapped(
3368 	vm_object_t object,
3369 	vm_page_t m,
3370 	vm_prot_t prot,
3371 	vm_prot_t fault_type)
3372 {
3373 	bool page_needs_sync = false;
3374 	/*
3375 	 * NOTE: we may only hold the vm_object lock SHARED
3376 	 * at this point, so we need the phys_page lock to
3377 	 * properly serialize updating the pmapped and
3378 	 * xpmapped bits
3379 	 */
3380 	if ((prot & VM_PROT_EXECUTE) && !m->vmp_xpmapped) {
3381 		ppnum_t phys_page = VM_PAGE_GET_PHYS_PAGE(m);
3382 
3383 		pmap_lock_phys_page(phys_page);
3384 		m->vmp_pmapped = TRUE;
3385 
3386 		if (!m->vmp_xpmapped) {
3387 			m->vmp_xpmapped = TRUE;
3388 
3389 			pmap_unlock_phys_page(phys_page);
3390 
3391 			if (!object->internal) {
3392 				OSAddAtomic(1, &vm_page_xpmapped_external_count);
3393 			}
3394 
3395 #if defined(__arm64__)
3396 			page_needs_sync = true;
3397 #else
3398 			if (object->internal &&
3399 			    object->pager != NULL) {
3400 				/*
3401 				 * This page could have been
3402 				 * uncompressed by the
3403 				 * compressor pager and its
3404 				 * contents might be only in
3405 				 * the data cache.
3406 				 * Since it's being mapped for
3407 				 * "execute" for the fist time,
3408 				 * make sure the icache is in
3409 				 * sync.
3410 				 */
3411 				assert(VM_CONFIG_COMPRESSOR_IS_PRESENT);
3412 				page_needs_sync = true;
3413 			}
3414 #endif
3415 		} else {
3416 			pmap_unlock_phys_page(phys_page);
3417 		}
3418 	} else {
3419 		if (m->vmp_pmapped == FALSE) {
3420 			ppnum_t phys_page = VM_PAGE_GET_PHYS_PAGE(m);
3421 
3422 			pmap_lock_phys_page(phys_page);
3423 			m->vmp_pmapped = TRUE;
3424 			pmap_unlock_phys_page(phys_page);
3425 		}
3426 	}
3427 
3428 	if (fault_type & VM_PROT_WRITE) {
3429 		if (m->vmp_wpmapped == FALSE) {
3430 			vm_object_lock_assert_exclusive(object);
3431 			if (!object->internal && object->pager) {
3432 				task_update_logical_writes(current_task(), PAGE_SIZE, TASK_WRITE_DEFERRED, vnode_pager_lookup_vnode(object->pager));
3433 			}
3434 			m->vmp_wpmapped = TRUE;
3435 		}
3436 	}
3437 	return page_needs_sync;
3438 }
3439 
3440 /*
3441  * wrapper for pmap_enter_options()
3442  */
3443 static kern_return_t
pmap_enter_options_check(pmap_t pmap,vm_map_address_t virtual_address,vm_map_offset_t fault_phys_offset,vm_page_t page,vm_prot_t protection,vm_prot_t fault_type,unsigned int flags,boolean_t wired,unsigned int options)3444 pmap_enter_options_check(
3445 	pmap_t           pmap,
3446 	vm_map_address_t virtual_address,
3447 	vm_map_offset_t  fault_phys_offset,
3448 	vm_page_t        page,
3449 	vm_prot_t        protection,
3450 	vm_prot_t        fault_type,
3451 	unsigned int     flags,
3452 	boolean_t        wired,
3453 	unsigned int     options)
3454 {
3455 	int             extra_options = 0;
3456 	vm_object_t     obj;
3457 
3458 	if (page->vmp_error) {
3459 		return KERN_MEMORY_FAILURE;
3460 	}
3461 	obj = VM_PAGE_OBJECT(page);
3462 	if (obj->internal) {
3463 		extra_options |= PMAP_OPTIONS_INTERNAL;
3464 	}
3465 	if (page->vmp_reusable || obj->all_reusable) {
3466 		extra_options |= PMAP_OPTIONS_REUSABLE;
3467 	}
3468 	return pmap_enter_options_addr(pmap,
3469 	           virtual_address,
3470 	           (pmap_paddr_t)ptoa(VM_PAGE_GET_PHYS_PAGE(page)) + fault_phys_offset,
3471 	           protection,
3472 	           fault_type,
3473 	           flags,
3474 	           wired,
3475 	           options | extra_options,
3476 	           NULL,
3477 	           PMAP_MAPPING_TYPE_INFER);
3478 }
3479 
3480 /*
3481  * Try to enter the given page into the pmap.
3482  * Will retry without execute permission if the code signing monitor is enabled and
3483  * we encounter a codesigning failure on a non-execute fault.
3484  */
3485 static kern_return_t
vm_fault_attempt_pmap_enter(pmap_t pmap,vm_map_offset_t vaddr,vm_map_size_t fault_page_size,vm_map_offset_t fault_phys_offset,vm_page_t m,vm_prot_t * prot,vm_prot_t caller_prot,vm_prot_t fault_type,bool wired,int pmap_options)3486 vm_fault_attempt_pmap_enter(
3487 	pmap_t pmap,
3488 	vm_map_offset_t vaddr,
3489 	vm_map_size_t fault_page_size,
3490 	vm_map_offset_t fault_phys_offset,
3491 	vm_page_t m,
3492 	vm_prot_t *prot,
3493 	vm_prot_t caller_prot,
3494 	vm_prot_t fault_type,
3495 	bool wired,
3496 	int pmap_options)
3497 {
3498 #if !CODE_SIGNING_MONITOR
3499 #pragma unused(caller_prot)
3500 #endif /* !CODE_SIGNING_MONITOR */
3501 
3502 	kern_return_t kr;
3503 	if (fault_page_size != PAGE_SIZE) {
3504 		DEBUG4K_FAULT("pmap %p va 0x%llx pa 0x%llx (0x%llx+0x%llx) prot 0x%x fault_type 0x%x\n", pmap, (uint64_t)vaddr, (uint64_t)((((pmap_paddr_t)VM_PAGE_GET_PHYS_PAGE(m)) << PAGE_SHIFT) + fault_phys_offset), (uint64_t)(((pmap_paddr_t)VM_PAGE_GET_PHYS_PAGE(m)) << PAGE_SHIFT), (uint64_t)fault_phys_offset, *prot, fault_type);
3505 		assertf((!(fault_phys_offset & FOURK_PAGE_MASK) &&
3506 		    fault_phys_offset < PAGE_SIZE),
3507 		    "0x%llx\n", (uint64_t)fault_phys_offset);
3508 	} else {
3509 		assertf(fault_phys_offset == 0,
3510 		    "0x%llx\n", (uint64_t)fault_phys_offset);
3511 	}
3512 
3513 	kr = pmap_enter_options_check(pmap, vaddr,
3514 	    fault_phys_offset,
3515 	    m, *prot, fault_type, 0,
3516 	    wired,
3517 	    pmap_options);
3518 
3519 #if CODE_SIGNING_MONITOR
3520 	/*
3521 	 * Retry without execute permission if we encountered a codesigning
3522 	 * failure on a non-execute fault.  This allows applications which
3523 	 * don't actually need to execute code to still map it for read access.
3524 	 */
3525 	if (kr == KERN_CODESIGN_ERROR &&
3526 	    csm_enabled() &&
3527 	    (*prot & VM_PROT_EXECUTE) &&
3528 	    !(caller_prot & VM_PROT_EXECUTE)) {
3529 		*prot &= ~VM_PROT_EXECUTE;
3530 		kr = pmap_enter_options_check(pmap, vaddr,
3531 		    fault_phys_offset,
3532 		    m, *prot, fault_type, 0,
3533 		    wired,
3534 		    pmap_options);
3535 	}
3536 #endif /* CODE_SIGNING_MONITOR */
3537 
3538 	return kr;
3539 }
3540 
3541 /*
3542  * Enter the given page into the pmap.
3543  * The map must be locked shared.
3544  * The vm object must NOT be locked.
3545  *
3546  * @param need_retry if not null, avoid making a (potentially) blocking call into
3547  * the pmap layer. When such a call would be necessary, return true in this boolean instead.
3548  */
3549 static kern_return_t
vm_fault_pmap_enter(pmap_t pmap,vm_map_offset_t vaddr,vm_map_size_t fault_page_size,vm_map_offset_t fault_phys_offset,vm_page_t m,vm_prot_t * prot,vm_prot_t caller_prot,vm_prot_t fault_type,bool wired,int pmap_options,boolean_t * need_retry)3550 vm_fault_pmap_enter(
3551 	pmap_t pmap,
3552 	vm_map_offset_t vaddr,
3553 	vm_map_size_t fault_page_size,
3554 	vm_map_offset_t fault_phys_offset,
3555 	vm_page_t m,
3556 	vm_prot_t *prot,
3557 	vm_prot_t caller_prot,
3558 	vm_prot_t fault_type,
3559 	bool wired,
3560 	int pmap_options,
3561 	boolean_t *need_retry)
3562 {
3563 	kern_return_t kr;
3564 	if (need_retry != NULL) {
3565 		/*
3566 		 * Although we don't hold a lock on this object, we hold a lock
3567 		 * on the top object in the chain. To prevent a deadlock, we
3568 		 * can't allow the pmap layer to block.
3569 		 */
3570 		pmap_options |= PMAP_OPTIONS_NOWAIT;
3571 	}
3572 	kr = vm_fault_attempt_pmap_enter(pmap, vaddr,
3573 	    fault_page_size, fault_phys_offset,
3574 	    m, prot, caller_prot, fault_type, wired, pmap_options);
3575 	if (kr == KERN_RESOURCE_SHORTAGE) {
3576 		if (need_retry) {
3577 			/*
3578 			 * There's nothing we can do here since we hold the
3579 			 * lock on the top object in the chain. The caller
3580 			 * will need to deal with this by dropping that lock and retrying.
3581 			 */
3582 			*need_retry = TRUE;
3583 			vm_pmap_enter_retried++;
3584 		}
3585 	}
3586 	return kr;
3587 }
3588 
3589 /*
3590  * Enter the given page into the pmap.
3591  * The vm map must be locked shared.
3592  * The vm object must be locked exclusive, unless this is a soft fault.
3593  * For a soft fault, the object must be locked shared or exclusive.
3594  *
3595  * @param need_retry if not null, avoid making a (potentially) blocking call into
3596  * the pmap layer. When such a call would be necessary, return true in this boolean instead.
3597  */
3598 static kern_return_t
vm_fault_pmap_enter_with_object_lock(vm_object_t object,pmap_t pmap,vm_map_offset_t vaddr,vm_map_size_t fault_page_size,vm_map_offset_t fault_phys_offset,vm_page_t m,vm_prot_t * prot,vm_prot_t caller_prot,vm_prot_t fault_type,bool wired,int pmap_options,boolean_t * need_retry,uint8_t * object_lock_type)3599 vm_fault_pmap_enter_with_object_lock(
3600 	vm_object_t object,
3601 	pmap_t pmap,
3602 	vm_map_offset_t vaddr,
3603 	vm_map_size_t fault_page_size,
3604 	vm_map_offset_t fault_phys_offset,
3605 	vm_page_t m,
3606 	vm_prot_t *prot,
3607 	vm_prot_t caller_prot,
3608 	vm_prot_t fault_type,
3609 	bool wired,
3610 	int pmap_options,
3611 	boolean_t *need_retry,
3612 	uint8_t *object_lock_type)
3613 {
3614 	kern_return_t kr;
3615 	/*
3616 	 * Prevent a deadlock by not
3617 	 * holding the object lock if we need to wait for a page in
3618 	 * pmap_enter() - <rdar://problem/7138958>
3619 	 */
3620 	kr = vm_fault_attempt_pmap_enter(pmap, vaddr,
3621 	    fault_page_size, fault_phys_offset,
3622 	    m, prot, caller_prot, fault_type, wired, pmap_options | PMAP_OPTIONS_NOWAIT);
3623 #if __x86_64__
3624 	if (kr == KERN_INVALID_ARGUMENT &&
3625 	    pmap == PMAP_NULL &&
3626 	    wired) {
3627 		/*
3628 		 * Wiring a page in a pmap-less VM map:
3629 		 * VMware's "vmmon" kernel extension does this
3630 		 * to grab pages.
3631 		 * Let it proceed even though the PMAP_ENTER() failed.
3632 		 */
3633 		kr = KERN_SUCCESS;
3634 	}
3635 #endif /* __x86_64__ */
3636 
3637 	if (kr == KERN_RESOURCE_SHORTAGE) {
3638 		if (need_retry) {
3639 			/*
3640 			 * this will be non-null in the case where we hold the lock
3641 			 * on the top-object in this chain... we can't just drop
3642 			 * the lock on the object we're inserting the page into
3643 			 * and recall the PMAP_ENTER since we can still cause
3644 			 * a deadlock if one of the critical paths tries to
3645 			 * acquire the lock on the top-object and we're blocked
3646 			 * in PMAP_ENTER waiting for memory... our only recourse
3647 			 * is to deal with it at a higher level where we can
3648 			 * drop both locks.
3649 			 */
3650 			*need_retry = TRUE;
3651 			vm_pmap_enter_retried++;
3652 			goto done;
3653 		}
3654 		/*
3655 		 * The nonblocking version of pmap_enter did not succeed.
3656 		 * and we don't need to drop other locks and retry
3657 		 * at the level above us, so
3658 		 * use the blocking version instead. Requires marking
3659 		 * the page busy and unlocking the object
3660 		 */
3661 		boolean_t was_busy = m->vmp_busy;
3662 
3663 		vm_object_lock_assert_exclusive(object);
3664 
3665 		m->vmp_busy = TRUE;
3666 		vm_object_unlock(object);
3667 
3668 		kr = pmap_enter_options_check(pmap, vaddr,
3669 		    fault_phys_offset,
3670 		    m, *prot, fault_type,
3671 		    0, wired,
3672 		    pmap_options);
3673 
3674 		assert(VM_PAGE_OBJECT(m) == object);
3675 
3676 		/* Take the object lock again. */
3677 		vm_object_lock(object);
3678 
3679 		/* If the page was busy, someone else will wake it up.
3680 		 * Otherwise, we have to do it now. */
3681 		assert(m->vmp_busy);
3682 		if (!was_busy) {
3683 			vm_page_wakeup_done(object, m);
3684 		}
3685 		vm_pmap_enter_blocked++;
3686 	}
3687 
3688 #if CONFIG_TRACK_UNMODIFIED_ANON_PAGES
3689 	if ((*prot & VM_PROT_WRITE) && m->vmp_unmodified_ro) {
3690 		if (*object_lock_type == OBJECT_LOCK_SHARED) {
3691 			boolean_t was_busy = m->vmp_busy;
3692 			m->vmp_busy = TRUE;
3693 
3694 			*object_lock_type = OBJECT_LOCK_EXCLUSIVE;
3695 
3696 			if (vm_object_lock_upgrade(object) == FALSE) {
3697 				vm_object_lock(object);
3698 			}
3699 
3700 			if (!was_busy) {
3701 				vm_page_wakeup_done(object, m);
3702 			}
3703 		}
3704 		vm_object_lock_assert_exclusive(object);
3705 		vm_page_lockspin_queues();
3706 		m->vmp_unmodified_ro = false;
3707 		vm_page_unlock_queues();
3708 		os_atomic_dec(&compressor_ro_uncompressed, relaxed);
3709 
3710 		vm_object_compressor_pager_state_clr(VM_PAGE_OBJECT(m), m->vmp_offset);
3711 	}
3712 #else /* CONFIG_TRACK_UNMODIFIED_ANON_PAGES */
3713 #pragma unused(object_lock_type)
3714 #endif /* CONFIG_TRACK_UNMODIFIED_ANON_PAGES */
3715 
3716 done:
3717 	return kr;
3718 }
3719 
3720 /*
3721  * Prepare to enter a page into the pmap by checking CS, protection bits,
3722  * and setting mapped bits on the page_t.
3723  * Does not modify the page's paging queue.
3724  *
3725  * page queue lock must NOT be held
3726  * m->vmp_object must be locked
3727  *
3728  * NOTE: m->vmp_object could be locked "shared" only if we are called
3729  * from vm_fault() as part of a soft fault.
3730  */
3731 static kern_return_t
vm_fault_enter_prepare(vm_page_t m,pmap_t pmap,vm_map_offset_t vaddr,vm_prot_t * prot,vm_prot_t caller_prot,vm_map_size_t fault_page_size,vm_map_offset_t fault_phys_offset,boolean_t change_wiring,vm_prot_t fault_type,vm_object_fault_info_t fault_info,int * type_of_fault,bool * page_needs_data_sync)3732 vm_fault_enter_prepare(
3733 	vm_page_t m,
3734 	pmap_t pmap,
3735 	vm_map_offset_t vaddr,
3736 	vm_prot_t *prot,
3737 	vm_prot_t caller_prot,
3738 	vm_map_size_t fault_page_size,
3739 	vm_map_offset_t fault_phys_offset,
3740 	boolean_t change_wiring,
3741 	vm_prot_t fault_type,
3742 	vm_object_fault_info_t fault_info,
3743 	int *type_of_fault,
3744 	bool *page_needs_data_sync)
3745 {
3746 	kern_return_t   kr;
3747 	bool            is_tainted = false;
3748 	vm_object_t     object;
3749 	boolean_t       cs_bypass = fault_info->cs_bypass;
3750 
3751 	object = VM_PAGE_OBJECT(m);
3752 
3753 	vm_object_lock_assert_held(object);
3754 
3755 #if KASAN
3756 	if (pmap == kernel_pmap) {
3757 		kasan_notify_address(vaddr, PAGE_SIZE);
3758 	}
3759 #endif
3760 
3761 #if CODE_SIGNING_MONITOR
3762 	if (csm_address_space_exempt(pmap) == KERN_SUCCESS) {
3763 		cs_bypass = TRUE;
3764 	}
3765 #endif
3766 
3767 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_NOTOWNED);
3768 
3769 	if (*type_of_fault == DBG_ZERO_FILL_FAULT) {
3770 		vm_object_lock_assert_exclusive(object);
3771 	} else if ((fault_type & VM_PROT_WRITE) == 0 &&
3772 	    !change_wiring &&
3773 	    (!m->vmp_wpmapped
3774 #if VM_OBJECT_ACCESS_TRACKING
3775 	    || object->access_tracking
3776 #endif /* VM_OBJECT_ACCESS_TRACKING */
3777 	    )) {
3778 		/*
3779 		 * This is not a "write" fault, so we
3780 		 * might not have taken the object lock
3781 		 * exclusively and we might not be able
3782 		 * to update the "wpmapped" bit in
3783 		 * vm_fault_enter().
3784 		 * Let's just grant read access to
3785 		 * the page for now and we'll
3786 		 * soft-fault again if we need write
3787 		 * access later...
3788 		 */
3789 
3790 		/* This had better not be a JIT page. */
3791 		if (pmap_has_prot_policy(pmap, fault_info->pmap_options & PMAP_OPTIONS_TRANSLATED_ALLOW_EXECUTE, *prot)) {
3792 			/*
3793 			 * This pmap enforces extra constraints for this set of
3794 			 * protections, so we can't modify them.
3795 			 */
3796 			if (!cs_bypass) {
3797 				panic("%s: pmap %p vaddr 0x%llx prot 0x%x options 0x%x !cs_bypass",
3798 				    __FUNCTION__, pmap, (uint64_t)vaddr,
3799 				    *prot, fault_info->pmap_options);
3800 			}
3801 		} else {
3802 			*prot &= ~VM_PROT_WRITE;
3803 		}
3804 	}
3805 	if (m->vmp_pmapped == FALSE) {
3806 		if (m->vmp_clustered) {
3807 			if (*type_of_fault == DBG_CACHE_HIT_FAULT) {
3808 				/*
3809 				 * found it in the cache, but this
3810 				 * is the first fault-in of the page (m->vmp_pmapped == FALSE)
3811 				 * so it must have come in as part of
3812 				 * a cluster... account 1 pagein against it
3813 				 */
3814 				if (object->internal) {
3815 					*type_of_fault = DBG_PAGEIND_FAULT;
3816 				} else {
3817 					*type_of_fault = DBG_PAGEINV_FAULT;
3818 				}
3819 
3820 				VM_PAGE_COUNT_AS_PAGEIN(m);
3821 			}
3822 			VM_PAGE_CONSUME_CLUSTERED(m);
3823 		}
3824 	}
3825 
3826 	if (*type_of_fault != DBG_COW_FAULT) {
3827 		DTRACE_VM2(as_fault, int, 1, (uint64_t *), NULL);
3828 
3829 		if (pmap == kernel_pmap) {
3830 			DTRACE_VM2(kernel_asflt, int, 1, (uint64_t *), NULL);
3831 		}
3832 	}
3833 
3834 	kr = vm_fault_validate_cs(cs_bypass, object, m, pmap, vaddr,
3835 	    *prot, caller_prot, fault_page_size, fault_phys_offset,
3836 	    fault_info, &is_tainted);
3837 	if (kr == KERN_SUCCESS) {
3838 		/*
3839 		 * We either have a good page, or a tainted page that has been accepted by the process.
3840 		 * In both cases the page will be entered into the pmap.
3841 		 */
3842 		*page_needs_data_sync = vm_fault_enter_set_mapped(object, m, *prot, fault_type);
3843 		if ((fault_type & VM_PROT_WRITE) && is_tainted) {
3844 			/*
3845 			 * This page is tainted but we're inserting it anyways.
3846 			 * Since it's writeable, we need to disconnect it from other pmaps
3847 			 * now so those processes can take note.
3848 			 */
3849 
3850 			/*
3851 			 * We can only get here
3852 			 * because of the CSE logic
3853 			 */
3854 			assert(pmap_get_vm_map_cs_enforced(pmap));
3855 			pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(m));
3856 			/*
3857 			 * If we are faulting for a write, we can clear
3858 			 * the execute bit - that will ensure the page is
3859 			 * checked again before being executable, which
3860 			 * protects against a map switch.
3861 			 * This only happens the first time the page
3862 			 * gets tainted, so we won't get stuck here
3863 			 * to make an already writeable page executable.
3864 			 */
3865 			if (!cs_bypass) {
3866 				if (pmap_has_prot_policy(pmap, fault_info->pmap_options & PMAP_OPTIONS_TRANSLATED_ALLOW_EXECUTE, *prot)) {
3867 					/*
3868 					 * This pmap enforces extra constraints
3869 					 * for this set of protections, so we
3870 					 * can't change the protections.
3871 					 */
3872 					panic("%s: pmap %p vaddr 0x%llx prot 0x%x options 0x%x",
3873 					    __FUNCTION__, pmap,
3874 					    (uint64_t)vaddr, *prot,
3875 					    fault_info->pmap_options);
3876 				}
3877 				*prot &= ~VM_PROT_EXECUTE;
3878 			}
3879 		}
3880 		assert(VM_PAGE_OBJECT(m) == object);
3881 
3882 #if VM_OBJECT_ACCESS_TRACKING
3883 		if (object->access_tracking) {
3884 			DTRACE_VM2(access_tracking, vm_map_offset_t, vaddr, int, fault_type);
3885 			if (fault_type & VM_PROT_WRITE) {
3886 				object->access_tracking_writes++;
3887 				vm_object_access_tracking_writes++;
3888 			} else {
3889 				object->access_tracking_reads++;
3890 				vm_object_access_tracking_reads++;
3891 			}
3892 		}
3893 #endif /* VM_OBJECT_ACCESS_TRACKING */
3894 	}
3895 
3896 	return kr;
3897 }
3898 
3899 /*
3900  * page queue lock must NOT be held
3901  * m->vmp_object must be locked
3902  *
3903  * NOTE: m->vmp_object could be locked "shared" only if we are called
3904  * from vm_fault() as part of a soft fault.  If so, we must be
3905  * careful not to modify the VM object in any way that is not
3906  * legal under a shared lock...
3907  */
3908 kern_return_t
vm_fault_enter(vm_page_t m,pmap_t pmap,vm_map_offset_t vaddr,vm_map_size_t fault_page_size,vm_map_offset_t fault_phys_offset,vm_prot_t prot,vm_prot_t caller_prot,boolean_t wired,boolean_t change_wiring,vm_tag_t wire_tag,vm_object_fault_info_t fault_info,boolean_t * need_retry,int * type_of_fault,uint8_t * object_lock_type)3909 vm_fault_enter(
3910 	vm_page_t m,
3911 	pmap_t pmap,
3912 	vm_map_offset_t vaddr,
3913 	vm_map_size_t fault_page_size,
3914 	vm_map_offset_t fault_phys_offset,
3915 	vm_prot_t prot,
3916 	vm_prot_t caller_prot,
3917 	boolean_t wired,
3918 	boolean_t change_wiring,
3919 	vm_tag_t  wire_tag,
3920 	vm_object_fault_info_t fault_info,
3921 	boolean_t *need_retry,
3922 	int *type_of_fault,
3923 	uint8_t *object_lock_type)
3924 {
3925 	kern_return_t   kr;
3926 	vm_object_t     object;
3927 	bool            page_needs_data_sync;
3928 	vm_prot_t       fault_type;
3929 	int             pmap_options = fault_info->pmap_options;
3930 
3931 	if (VM_PAGE_GET_PHYS_PAGE(m) == vm_page_guard_addr) {
3932 		assert(m->vmp_fictitious);
3933 		return KERN_SUCCESS;
3934 	}
3935 
3936 	fault_type = change_wiring ? VM_PROT_NONE : caller_prot;
3937 
3938 	assertf(VM_PAGE_OBJECT(m) != VM_OBJECT_NULL, "m=%p", m);
3939 	kr = vm_fault_enter_prepare(m, pmap, vaddr, &prot, caller_prot,
3940 	    fault_page_size, fault_phys_offset, change_wiring, fault_type,
3941 	    fault_info, type_of_fault, &page_needs_data_sync);
3942 	object = VM_PAGE_OBJECT(m);
3943 
3944 	vm_fault_enqueue_page(object, m, wired, change_wiring, wire_tag, fault_info->no_cache, type_of_fault, kr);
3945 
3946 	if (kr == KERN_SUCCESS) {
3947 		if (page_needs_data_sync) {
3948 			pmap_sync_page_data_phys(VM_PAGE_GET_PHYS_PAGE(m));
3949 		}
3950 
3951 		if (fault_info->fi_xnu_user_debug && !object->code_signed) {
3952 			pmap_options |= PMAP_OPTIONS_XNU_USER_DEBUG;
3953 		}
3954 
3955 
3956 		kr = vm_fault_pmap_enter_with_object_lock(object, pmap, vaddr,
3957 		    fault_page_size, fault_phys_offset, m,
3958 		    &prot, caller_prot, fault_type, wired, pmap_options, need_retry, object_lock_type);
3959 	}
3960 
3961 	return kr;
3962 }
3963 
3964 void
vm_pre_fault(vm_map_offset_t vaddr,vm_prot_t prot)3965 vm_pre_fault(vm_map_offset_t vaddr, vm_prot_t prot)
3966 {
3967 	if (pmap_find_phys(current_map()->pmap, vaddr) == 0) {
3968 		vm_fault(current_map(),      /* map */
3969 		    vaddr,                   /* vaddr */
3970 		    prot,                    /* fault_type */
3971 		    FALSE,                   /* change_wiring */
3972 		    VM_KERN_MEMORY_NONE,     /* tag - not wiring */
3973 		    THREAD_UNINT,            /* interruptible */
3974 		    NULL,                    /* caller_pmap */
3975 		    0 /* caller_pmap_addr */);
3976 	}
3977 }
3978 
3979 
3980 /*
3981  *	Routine:	vm_fault
3982  *	Purpose:
3983  *		Handle page faults, including pseudo-faults
3984  *		used to change the wiring status of pages.
3985  *	Returns:
3986  *		Explicit continuations have been removed.
3987  *	Implementation:
3988  *		vm_fault and vm_fault_page save mucho state
3989  *		in the moral equivalent of a closure.  The state
3990  *		structure is allocated when first entering vm_fault
3991  *		and deallocated when leaving vm_fault.
3992  */
3993 
3994 extern uint64_t get_current_unique_pid(void);
3995 
3996 unsigned long vm_fault_collapse_total = 0;
3997 unsigned long vm_fault_collapse_skipped = 0;
3998 
3999 
4000 kern_return_t
vm_fault_external(vm_map_t map,vm_map_offset_t vaddr,vm_prot_t fault_type,boolean_t change_wiring,int interruptible,pmap_t caller_pmap,vm_map_offset_t caller_pmap_addr)4001 vm_fault_external(
4002 	vm_map_t        map,
4003 	vm_map_offset_t vaddr,
4004 	vm_prot_t       fault_type,
4005 	boolean_t       change_wiring,
4006 	int             interruptible,
4007 	pmap_t          caller_pmap,
4008 	vm_map_offset_t caller_pmap_addr)
4009 {
4010 	struct vm_object_fault_info fault_info = {
4011 		.interruptible = interruptible
4012 	};
4013 	return vm_fault_internal(map, vaddr, fault_type, change_wiring,
4014 	           change_wiring ? vm_tag_bt() : VM_KERN_MEMORY_NONE,
4015 	           caller_pmap, caller_pmap_addr,
4016 	           NULL, &fault_info);
4017 }
4018 
4019 kern_return_t
vm_fault(vm_map_t map,vm_map_offset_t vaddr,vm_prot_t fault_type,boolean_t change_wiring,vm_tag_t wire_tag,int interruptible,pmap_t caller_pmap,vm_map_offset_t caller_pmap_addr)4020 vm_fault(
4021 	vm_map_t        map,
4022 	vm_map_offset_t vaddr,
4023 	vm_prot_t       fault_type,
4024 	boolean_t       change_wiring,
4025 	vm_tag_t        wire_tag,               /* if wiring must pass tag != VM_KERN_MEMORY_NONE */
4026 	int             interruptible,
4027 	pmap_t          caller_pmap,
4028 	vm_map_offset_t caller_pmap_addr)
4029 {
4030 	struct vm_object_fault_info fault_info = {
4031 		.interruptible = interruptible
4032 	};
4033 	return vm_fault_internal(map, vaddr, fault_type, change_wiring, wire_tag,
4034 	           caller_pmap, caller_pmap_addr,
4035 	           NULL, &fault_info);
4036 }
4037 
4038 static boolean_t
current_proc_is_privileged(void)4039 current_proc_is_privileged(void)
4040 {
4041 	return csproc_get_platform_binary(current_proc());
4042 }
4043 
4044 uint64_t vm_copied_on_read = 0;
4045 
4046 /*
4047  * Cleanup after a vm_fault_enter.
4048  * At this point, the fault should either have failed (kr != KERN_SUCCESS)
4049  * or the page should be in the pmap and on the correct paging queue.
4050  *
4051  * Precondition:
4052  * map must be locked shared.
4053  * m_object must be locked.
4054  * If top_object != VM_OBJECT_NULL, it must be locked.
4055  * real_map must be locked.
4056  *
4057  * Postcondition:
4058  * map will be unlocked
4059  * m_object will be unlocked
4060  * top_object will be unlocked
4061  * If real_map != map, it will be unlocked
4062  */
4063 static void
vm_fault_complete(vm_map_t map,vm_map_t real_map,vm_object_t object,vm_object_t m_object,vm_page_t m,vm_map_offset_t offset,vm_map_offset_t trace_real_vaddr,vm_object_fault_info_t fault_info,vm_prot_t caller_prot,vm_map_offset_t real_vaddr,int type_of_fault,boolean_t need_retry,kern_return_t kr,ppnum_t * physpage_p,vm_prot_t prot,vm_object_t top_object,boolean_t need_collapse,vm_map_offset_t cur_offset,vm_prot_t fault_type,vm_object_t * written_on_object,memory_object_t * written_on_pager,vm_object_offset_t * written_on_offset)4064 vm_fault_complete(
4065 	vm_map_t map,
4066 	vm_map_t real_map,
4067 	vm_object_t object,
4068 	vm_object_t m_object,
4069 	vm_page_t m,
4070 	vm_map_offset_t offset,
4071 	vm_map_offset_t trace_real_vaddr,
4072 	vm_object_fault_info_t fault_info,
4073 	vm_prot_t caller_prot,
4074 #if CONFIG_DTRACE
4075 	vm_map_offset_t real_vaddr,
4076 #else
4077 	__unused vm_map_offset_t real_vaddr,
4078 #endif /* CONFIG_DTRACE */
4079 	int type_of_fault,
4080 	boolean_t need_retry,
4081 	kern_return_t kr,
4082 	ppnum_t *physpage_p,
4083 	vm_prot_t prot,
4084 	vm_object_t top_object,
4085 	boolean_t need_collapse,
4086 	vm_map_offset_t cur_offset,
4087 	vm_prot_t fault_type,
4088 	vm_object_t *written_on_object,
4089 	memory_object_t *written_on_pager,
4090 	vm_object_offset_t *written_on_offset)
4091 {
4092 	int     event_code = 0;
4093 	vm_map_lock_assert_shared(map);
4094 	vm_object_lock_assert_held(m_object);
4095 	if (top_object != VM_OBJECT_NULL) {
4096 		vm_object_lock_assert_held(top_object);
4097 	}
4098 	vm_map_lock_assert_held(real_map);
4099 
4100 	if (m_object->internal) {
4101 		event_code = (MACHDBG_CODE(DBG_MACH_WORKINGSET, VM_REAL_FAULT_ADDR_INTERNAL));
4102 	} else if (m_object->object_is_shared_cache) {
4103 		event_code = (MACHDBG_CODE(DBG_MACH_WORKINGSET, VM_REAL_FAULT_ADDR_SHAREDCACHE));
4104 	} else {
4105 		event_code = (MACHDBG_CODE(DBG_MACH_WORKINGSET, VM_REAL_FAULT_ADDR_EXTERNAL));
4106 	}
4107 	KDBG_RELEASE(event_code | DBG_FUNC_NONE, trace_real_vaddr, (fault_info->user_tag << 16) | (caller_prot << 8) | type_of_fault, m->vmp_offset, get_current_unique_pid());
4108 	if (need_retry == FALSE) {
4109 		KDBG_FILTERED(MACHDBG_CODE(DBG_MACH_WORKINGSET, VM_REAL_FAULT_FAST), get_current_unique_pid());
4110 	}
4111 	DTRACE_VM6(real_fault, vm_map_offset_t, real_vaddr, vm_map_offset_t, m->vmp_offset, int, event_code, int, caller_prot, int, type_of_fault, int, fault_info->user_tag);
4112 	if (kr == KERN_SUCCESS &&
4113 	    physpage_p != NULL) {
4114 		/* for vm_map_wire_and_extract() */
4115 		*physpage_p = VM_PAGE_GET_PHYS_PAGE(m);
4116 		if (prot & VM_PROT_WRITE) {
4117 			vm_object_lock_assert_exclusive(m_object);
4118 			m->vmp_dirty = TRUE;
4119 		}
4120 	}
4121 
4122 	if (top_object != VM_OBJECT_NULL) {
4123 		/*
4124 		 * It's safe to drop the top object
4125 		 * now that we've done our
4126 		 * vm_fault_enter().  Any other fault
4127 		 * in progress for that virtual
4128 		 * address will either find our page
4129 		 * and translation or put in a new page
4130 		 * and translation.
4131 		 */
4132 		vm_object_unlock(top_object);
4133 		top_object = VM_OBJECT_NULL;
4134 	}
4135 
4136 	if (need_collapse == TRUE) {
4137 		vm_object_collapse(object, vm_object_trunc_page(offset), TRUE);
4138 	}
4139 
4140 	if (need_retry == FALSE &&
4141 	    (type_of_fault == DBG_PAGEIND_FAULT || type_of_fault == DBG_PAGEINV_FAULT || type_of_fault == DBG_CACHE_HIT_FAULT)) {
4142 		/*
4143 		 * evaluate access pattern and update state
4144 		 * vm_fault_deactivate_behind depends on the
4145 		 * state being up to date
4146 		 */
4147 		vm_fault_is_sequential(m_object, cur_offset, fault_info->behavior);
4148 
4149 		vm_fault_deactivate_behind(m_object, cur_offset, fault_info->behavior);
4150 	}
4151 	/*
4152 	 * That's it, clean up and return.
4153 	 */
4154 	if (m->vmp_busy) {
4155 		vm_object_lock_assert_exclusive(m_object);
4156 		vm_page_wakeup_done(m_object, m);
4157 	}
4158 
4159 	if (need_retry == FALSE && !m_object->internal && (fault_type & VM_PROT_WRITE)) {
4160 		vm_object_paging_begin(m_object);
4161 
4162 		assert(*written_on_object == VM_OBJECT_NULL);
4163 		*written_on_object = m_object;
4164 		*written_on_pager = m_object->pager;
4165 		*written_on_offset = m_object->paging_offset + m->vmp_offset;
4166 	}
4167 	vm_object_unlock(object);
4168 
4169 	vm_map_unlock_read(map);
4170 	if (real_map != map) {
4171 		vm_map_unlock(real_map);
4172 	}
4173 }
4174 
4175 static inline int
vm_fault_type_for_tracing(boolean_t need_copy_on_read,int type_of_fault)4176 vm_fault_type_for_tracing(boolean_t need_copy_on_read, int type_of_fault)
4177 {
4178 	if (need_copy_on_read && type_of_fault == DBG_COW_FAULT) {
4179 		return DBG_COR_FAULT;
4180 	}
4181 	return type_of_fault;
4182 }
4183 
4184 uint64_t vm_fault_resilient_media_initiate = 0;
4185 uint64_t vm_fault_resilient_media_retry = 0;
4186 uint64_t vm_fault_resilient_media_proceed = 0;
4187 uint64_t vm_fault_resilient_media_release = 0;
4188 uint64_t vm_fault_resilient_media_abort1 = 0;
4189 uint64_t vm_fault_resilient_media_abort2 = 0;
4190 
4191 #if MACH_ASSERT
4192 int vm_fault_resilient_media_inject_error1_rate = 0;
4193 int vm_fault_resilient_media_inject_error1 = 0;
4194 int vm_fault_resilient_media_inject_error2_rate = 0;
4195 int vm_fault_resilient_media_inject_error2 = 0;
4196 int vm_fault_resilient_media_inject_error3_rate = 0;
4197 int vm_fault_resilient_media_inject_error3 = 0;
4198 #endif /* MACH_ASSERT */
4199 
4200 kern_return_t
vm_fault_internal(vm_map_t map,vm_map_offset_t vaddr,vm_prot_t caller_prot,boolean_t change_wiring,vm_tag_t wire_tag,pmap_t caller_pmap,vm_map_offset_t caller_pmap_addr,ppnum_t * physpage_p,vm_object_fault_info_t fault_info)4201 vm_fault_internal(
4202 	vm_map_t               map,
4203 	vm_map_offset_t        vaddr,
4204 	vm_prot_t              caller_prot,
4205 	boolean_t              change_wiring,
4206 	vm_tag_t               wire_tag,               /* if wiring must pass tag != VM_KERN_MEMORY_NONE */
4207 	pmap_t                 caller_pmap,
4208 	vm_map_offset_t        caller_pmap_addr,
4209 	ppnum_t                *physpage_p,
4210 	vm_object_fault_info_t fault_info)
4211 {
4212 	vm_map_version_t        version;        /* Map version for verificiation */
4213 	boolean_t               wired;          /* Should mapping be wired down? */
4214 	vm_object_t             object;         /* Top-level object */
4215 	vm_object_offset_t      offset;         /* Top-level offset */
4216 	vm_prot_t               prot;           /* Protection for mapping */
4217 	vm_object_t             old_copy_object; /* Saved copy object */
4218 	uint32_t                old_copy_version;
4219 	vm_page_t               result_page;    /* Result of vm_fault_page */
4220 	vm_page_t               top_page;       /* Placeholder page */
4221 	kern_return_t           kr;
4222 
4223 	vm_page_t               m;      /* Fast access to result_page */
4224 	kern_return_t           error_code;
4225 	vm_object_t             cur_object;
4226 	vm_object_t             m_object = NULL;
4227 	vm_object_offset_t      cur_offset;
4228 	vm_page_t               cur_m;
4229 	vm_object_t             new_object;
4230 	int                     type_of_fault;
4231 	pmap_t                  pmap;
4232 	wait_interrupt_t        interruptible_state;
4233 	vm_map_t                real_map = map;
4234 	vm_map_t                original_map = map;
4235 	bool                    object_locks_dropped = FALSE;
4236 	vm_prot_t               fault_type;
4237 	vm_prot_t               original_fault_type;
4238 	bool                    need_collapse = FALSE;
4239 	boolean_t               need_retry = FALSE;
4240 	boolean_t               *need_retry_ptr = NULL;
4241 	uint8_t                 object_lock_type = 0;
4242 	uint8_t                 cur_object_lock_type;
4243 	vm_object_t             top_object = VM_OBJECT_NULL;
4244 	vm_object_t             written_on_object = VM_OBJECT_NULL;
4245 	memory_object_t         written_on_pager = NULL;
4246 	vm_object_offset_t      written_on_offset = 0;
4247 	int                     throttle_delay;
4248 	int                     compressed_count_delta;
4249 	uint8_t                 grab_options;
4250 	bool                    need_copy;
4251 	bool                    need_copy_on_read;
4252 	vm_map_offset_t         trace_vaddr;
4253 	vm_map_offset_t         trace_real_vaddr;
4254 	vm_map_size_t           fault_page_size;
4255 	vm_map_size_t           fault_page_mask;
4256 	int                     fault_page_shift;
4257 	vm_map_offset_t         fault_phys_offset;
4258 	vm_map_offset_t         real_vaddr;
4259 	bool                    resilient_media_retry = false;
4260 	bool                    resilient_media_ref_transfer = false;
4261 	vm_object_t             resilient_media_object = VM_OBJECT_NULL;
4262 	vm_object_offset_t      resilient_media_offset = (vm_object_offset_t)-1;
4263 	bool                    page_needs_data_sync = false;
4264 	/*
4265 	 * Was the VM object contended when vm_map_lookup_and_lock_object locked it?
4266 	 * If so, the zero fill path will drop the lock
4267 	 * NB: Ideally we would always drop the lock rather than rely on
4268 	 * this heuristic, but vm_object_unlock currently takes > 30 cycles.
4269 	 */
4270 	bool                    object_is_contended = false;
4271 
4272 
4273 	real_vaddr = vaddr;
4274 	trace_real_vaddr = vaddr;
4275 
4276 	/*
4277 	 * Some (kernel) submaps are marked with "should never fault".
4278 	 *
4279 	 * We do this for two reasons:
4280 	 * - PGZ which is inside the zone map range can't go down the normal
4281 	 *   lookup path (vm_map_lookup_entry() would panic).
4282 	 *
4283 	 * - we want for guard pages to not have to use fictitious pages at all
4284 	 *   to prevent from ZFOD pages to be made.
4285 	 *
4286 	 * We also want capture the fault address easily so that the zone
4287 	 * allocator might present an enhanced panic log.
4288 	 */
4289 	if (map->never_faults || (pgz_owned(vaddr) && map->pmap == kernel_pmap)) {
4290 		assert(map->pmap == kernel_pmap);
4291 		return KERN_INVALID_ADDRESS;
4292 	}
4293 
4294 	if (VM_MAP_PAGE_SIZE(original_map) < PAGE_SIZE) {
4295 		fault_phys_offset = (vm_map_offset_t)-1;
4296 		fault_page_size = VM_MAP_PAGE_SIZE(original_map);
4297 		fault_page_mask = VM_MAP_PAGE_MASK(original_map);
4298 		fault_page_shift = VM_MAP_PAGE_SHIFT(original_map);
4299 		if (fault_page_size < PAGE_SIZE) {
4300 			DEBUG4K_FAULT("map %p vaddr 0x%llx caller_prot 0x%x\n", map, (uint64_t)trace_real_vaddr, caller_prot);
4301 			vaddr = vm_map_trunc_page(vaddr, fault_page_mask);
4302 		}
4303 	} else {
4304 		fault_phys_offset = 0;
4305 		fault_page_size = PAGE_SIZE;
4306 		fault_page_mask = PAGE_MASK;
4307 		fault_page_shift = PAGE_SHIFT;
4308 		vaddr = vm_map_trunc_page(vaddr, PAGE_MASK);
4309 	}
4310 
4311 	if (map == kernel_map) {
4312 		trace_vaddr = VM_KERNEL_ADDRHIDE(vaddr);
4313 		trace_real_vaddr = VM_KERNEL_ADDRHIDE(trace_real_vaddr);
4314 	} else {
4315 		trace_vaddr = vaddr;
4316 	}
4317 
4318 	KDBG_RELEASE(
4319 		(VMDBG_CODE(DBG_VM_FAULT_INTERNAL)) | DBG_FUNC_START,
4320 		((uint64_t)trace_vaddr >> 32),
4321 		trace_vaddr,
4322 		(map == kernel_map));
4323 
4324 	if (get_preemption_level() != 0) {
4325 		KDBG_RELEASE(
4326 			(VMDBG_CODE(DBG_VM_FAULT_INTERNAL)) | DBG_FUNC_END,
4327 			((uint64_t)trace_vaddr >> 32),
4328 			trace_vaddr,
4329 			KERN_FAILURE);
4330 
4331 		ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_NONZERO_PREEMPTION_LEVEL), 0 /* arg */);
4332 		return KERN_FAILURE;
4333 	}
4334 
4335 	thread_t cthread = current_thread();
4336 
4337 	if (cthread->th_vm_faults_disabled) {
4338 		KDBG_RELEASE(
4339 			(MACHDBG_CODE(DBG_MACH_VM, 2)) | DBG_FUNC_END,
4340 			((uint64_t)trace_vaddr >> 32),
4341 			trace_vaddr,
4342 			KERN_FAILURE);
4343 		ktriage_record(thread_tid(cthread),
4344 		    KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM,
4345 		    KDBG_TRIAGE_RESERVED,
4346 		    KDBG_TRIAGE_VM_FAULTS_DISABLED),
4347 		    0 /* arg */);
4348 		return KERN_FAILURE;
4349 	}
4350 
4351 	bool     rtfault = (cthread->sched_mode == TH_MODE_REALTIME);
4352 	uint64_t fstart = 0;
4353 
4354 	if (rtfault) {
4355 		fstart = mach_continuous_time();
4356 	}
4357 
4358 	interruptible_state = thread_interrupt_level(fault_info->interruptible);
4359 
4360 	fault_type = (change_wiring ? VM_PROT_NONE : caller_prot);
4361 
4362 	counter_inc(&vm_statistics_faults);
4363 	counter_inc(&current_task()->faults);
4364 	original_fault_type = fault_type;
4365 
4366 	need_copy = FALSE;
4367 	if (fault_type & VM_PROT_WRITE) {
4368 		need_copy = TRUE;
4369 	}
4370 
4371 	if (need_copy || change_wiring) {
4372 		object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4373 	} else {
4374 		object_lock_type = OBJECT_LOCK_SHARED;
4375 	}
4376 
4377 	cur_object_lock_type = OBJECT_LOCK_SHARED;
4378 
4379 	if ((map == kernel_map) && (caller_prot & VM_PROT_WRITE)) {
4380 		if (compressor_map) {
4381 			if ((vaddr >= vm_map_min(compressor_map)) && (vaddr < vm_map_max(compressor_map))) {
4382 				panic("Write fault on compressor map, va: %p type: %u bounds: %p->%p", (void *) vaddr, caller_prot, (void *) vm_map_min(compressor_map), (void *) vm_map_max(compressor_map));
4383 			}
4384 		}
4385 	}
4386 RetryFault:
4387 	assert(written_on_object == VM_OBJECT_NULL);
4388 
4389 	/*
4390 	 * assume we will hit a page in the cache
4391 	 * otherwise, explicitly override with
4392 	 * the real fault type once we determine it
4393 	 */
4394 	type_of_fault = DBG_CACHE_HIT_FAULT;
4395 
4396 	/*
4397 	 *	Find the backing store object and offset into
4398 	 *	it to begin the search.
4399 	 */
4400 	fault_type = original_fault_type;
4401 	map = original_map;
4402 	vm_map_lock_read(map);
4403 
4404 	if (resilient_media_retry) {
4405 		/*
4406 		 * If we have to insert a fake zero-filled page to hide
4407 		 * a media failure to provide the real page, we need to
4408 		 * resolve any pending copy-on-write on this mapping.
4409 		 * VM_PROT_COPY tells vm_map_lookup_and_lock_object() to deal
4410 		 * with that even if this is not a "write" fault.
4411 		 */
4412 		need_copy = TRUE;
4413 		object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4414 		vm_fault_resilient_media_retry++;
4415 	}
4416 
4417 	kr = vm_map_lookup_and_lock_object(&map, vaddr,
4418 	    (fault_type | (need_copy ? VM_PROT_COPY : 0)),
4419 	    object_lock_type, &version,
4420 	    &object, &offset, &prot, &wired,
4421 	    fault_info,
4422 	    &real_map,
4423 	    &object_is_contended);
4424 	object_is_contended = false; /* avoid unsafe optimization */
4425 
4426 	if (kr != KERN_SUCCESS) {
4427 		vm_map_unlock_read(map);
4428 		/*
4429 		 * This can be seen in a crash report if indeed the
4430 		 * thread is crashing due to an invalid access in a non-existent
4431 		 * range.
4432 		 * Turning this OFF for now because it is noisy and not always fatal
4433 		 * eg prefaulting.
4434 		 *
4435 		 * if (kr == KERN_INVALID_ADDRESS) {
4436 		 *	ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_ADDRESS_NOT_FOUND), 0);
4437 		 * }
4438 		 */
4439 		goto done;
4440 	}
4441 
4442 
4443 	pmap = real_map->pmap;
4444 	fault_info->stealth = FALSE;
4445 	fault_info->io_sync = FALSE;
4446 	fault_info->mark_zf_absent = FALSE;
4447 	fault_info->batch_pmap_op = FALSE;
4448 
4449 	if (resilient_media_retry) {
4450 		/*
4451 		 * We're retrying this fault after having detected a media
4452 		 * failure from a "resilient_media" mapping.
4453 		 * Check that the mapping is still pointing at the object
4454 		 * that just failed to provide a page.
4455 		 */
4456 		assert(resilient_media_object != VM_OBJECT_NULL);
4457 		assert(resilient_media_offset != (vm_object_offset_t)-1);
4458 		if ((object != VM_OBJECT_NULL &&
4459 		    object == resilient_media_object &&
4460 		    offset == resilient_media_offset &&
4461 		    fault_info->resilient_media)
4462 #if MACH_ASSERT
4463 		    && (vm_fault_resilient_media_inject_error1_rate == 0 ||
4464 		    (++vm_fault_resilient_media_inject_error1 % vm_fault_resilient_media_inject_error1_rate) != 0)
4465 #endif /* MACH_ASSERT */
4466 		    ) {
4467 			/*
4468 			 * This mapping still points at the same object
4469 			 * and is still "resilient_media": proceed in
4470 			 * "recovery-from-media-failure" mode, where we'll
4471 			 * insert a zero-filled page in the top object.
4472 			 */
4473 //                     printf("RESILIENT_MEDIA %s:%d recovering for object %p offset 0x%llx\n", __FUNCTION__, __LINE__, object, offset);
4474 			vm_fault_resilient_media_proceed++;
4475 		} else {
4476 			/* not recovering: reset state and retry fault */
4477 //                     printf("RESILIENT_MEDIA %s:%d no recovery resilient %d object %p/%p offset 0x%llx/0x%llx\n", __FUNCTION__, __LINE__, fault_info->resilient_media, object, resilient_media_object, offset, resilient_media_offset);
4478 			vm_object_unlock(object);
4479 			if (real_map != map) {
4480 				vm_map_unlock(real_map);
4481 			}
4482 			vm_map_unlock_read(map);
4483 			/* release our extra reference on failed object */
4484 //                     printf("FBDP %s:%d resilient_media_object %p deallocate\n", __FUNCTION__, __LINE__, resilient_media_object);
4485 			vm_object_deallocate(resilient_media_object);
4486 			resilient_media_object = VM_OBJECT_NULL;
4487 			resilient_media_offset = (vm_object_offset_t)-1;
4488 			resilient_media_retry = false;
4489 			vm_fault_resilient_media_abort1++;
4490 			goto RetryFault;
4491 		}
4492 	} else {
4493 		assert(resilient_media_object == VM_OBJECT_NULL);
4494 		resilient_media_offset = (vm_object_offset_t)-1;
4495 	}
4496 
4497 	/*
4498 	 * If the page is wired, we must fault for the current protection
4499 	 * value, to avoid further faults.
4500 	 */
4501 	if (wired) {
4502 		fault_type = prot | VM_PROT_WRITE;
4503 	}
4504 	if (wired || need_copy) {
4505 		/*
4506 		 * since we're treating this fault as a 'write'
4507 		 * we must hold the top object lock exclusively
4508 		 */
4509 		if (object_lock_type == OBJECT_LOCK_SHARED) {
4510 			object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4511 
4512 			if (vm_object_lock_upgrade(object) == FALSE) {
4513 				/*
4514 				 * couldn't upgrade, so explictly
4515 				 * take the lock exclusively
4516 				 */
4517 				vm_object_lock(object);
4518 			}
4519 		}
4520 	}
4521 
4522 #if     VM_FAULT_CLASSIFY
4523 	/*
4524 	 *	Temporary data gathering code
4525 	 */
4526 	vm_fault_classify(object, offset, fault_type);
4527 #endif
4528 	/*
4529 	 *	Fast fault code.  The basic idea is to do as much as
4530 	 *	possible while holding the map lock and object locks.
4531 	 *      Busy pages are not used until the object lock has to
4532 	 *	be dropped to do something (copy, zero fill, pmap enter).
4533 	 *	Similarly, paging references aren't acquired until that
4534 	 *	point, and object references aren't used.
4535 	 *
4536 	 *	If we can figure out what to do
4537 	 *	(zero fill, copy on write, pmap enter) while holding
4538 	 *	the locks, then it gets done.  Otherwise, we give up,
4539 	 *	and use the original fault path (which doesn't hold
4540 	 *	the map lock, and relies on busy pages).
4541 	 *	The give up cases include:
4542 	 *              - Have to talk to pager.
4543 	 *		- Page is busy, absent or in error.
4544 	 *		- Pager has locked out desired access.
4545 	 *		- Fault needs to be restarted.
4546 	 *		- Have to push page into copy object.
4547 	 *
4548 	 *	The code is an infinite loop that moves one level down
4549 	 *	the shadow chain each time.  cur_object and cur_offset
4550 	 *      refer to the current object being examined. object and offset
4551 	 *	are the original object from the map.  The loop is at the
4552 	 *	top level if and only if object and cur_object are the same.
4553 	 *
4554 	 *	Invariants:  Map lock is held throughout.  Lock is held on
4555 	 *		original object and cur_object (if different) when
4556 	 *		continuing or exiting loop.
4557 	 *
4558 	 */
4559 
4560 #if defined(__arm64__)
4561 	/*
4562 	 * Fail if reading an execute-only page in a
4563 	 * pmap that enforces execute-only protection.
4564 	 */
4565 	if (fault_type == VM_PROT_READ &&
4566 	    (prot & VM_PROT_EXECUTE) &&
4567 	    !(prot & VM_PROT_READ) &&
4568 	    pmap_enforces_execute_only(pmap)) {
4569 		vm_object_unlock(object);
4570 		vm_map_unlock_read(map);
4571 		if (real_map != map) {
4572 			vm_map_unlock(real_map);
4573 		}
4574 		kr = KERN_PROTECTION_FAILURE;
4575 		goto done;
4576 	}
4577 #endif
4578 
4579 	fault_phys_offset = (vm_map_offset_t)offset - vm_map_trunc_page((vm_map_offset_t)offset, PAGE_MASK);
4580 
4581 	/*
4582 	 * If this page is to be inserted in a copy delay object
4583 	 * for writing, and if the object has a copy, then the
4584 	 * copy delay strategy is implemented in the slow fault page.
4585 	 */
4586 	if ((object->copy_strategy == MEMORY_OBJECT_COPY_DELAY ||
4587 	    object->copy_strategy == MEMORY_OBJECT_COPY_DELAY_FORK) &&
4588 	    object->vo_copy != VM_OBJECT_NULL && (fault_type & VM_PROT_WRITE)) {
4589 		goto handle_copy_delay;
4590 	}
4591 
4592 	cur_object = object;
4593 	cur_offset = offset;
4594 
4595 	grab_options = 0;
4596 #if CONFIG_SECLUDED_MEMORY
4597 	if (object->can_grab_secluded) {
4598 		grab_options |= VM_PAGE_GRAB_SECLUDED;
4599 	}
4600 #endif /* CONFIG_SECLUDED_MEMORY */
4601 
4602 	while (TRUE) {
4603 		if (!cur_object->pager_created &&
4604 		    cur_object->phys_contiguous) { /* superpage */
4605 			break;
4606 		}
4607 
4608 		if (cur_object->blocked_access) {
4609 			/*
4610 			 * Access to this VM object has been blocked.
4611 			 * Let the slow path handle it.
4612 			 */
4613 			break;
4614 		}
4615 
4616 		m = vm_page_lookup(cur_object, vm_object_trunc_page(cur_offset));
4617 		m_object = NULL;
4618 
4619 		if (m != VM_PAGE_NULL) {
4620 			m_object = cur_object;
4621 
4622 			if (m->vmp_busy) {
4623 				wait_result_t   result;
4624 
4625 				/*
4626 				 * in order to vm_page_sleep(), we must
4627 				 * have object that 'm' belongs to locked exclusively
4628 				 */
4629 				if (object != cur_object) {
4630 					if (cur_object_lock_type == OBJECT_LOCK_SHARED) {
4631 						cur_object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4632 
4633 						if (vm_object_lock_upgrade(cur_object) == FALSE) {
4634 							/*
4635 							 * couldn't upgrade so go do a full retry
4636 							 * immediately since we can no longer be
4637 							 * certain about cur_object (since we
4638 							 * don't hold a reference on it)...
4639 							 * first drop the top object lock
4640 							 */
4641 							vm_object_unlock(object);
4642 
4643 							vm_map_unlock_read(map);
4644 							if (real_map != map) {
4645 								vm_map_unlock(real_map);
4646 							}
4647 
4648 							goto RetryFault;
4649 						}
4650 					}
4651 				} else if (object_lock_type == OBJECT_LOCK_SHARED) {
4652 					object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4653 
4654 					if (vm_object_lock_upgrade(object) == FALSE) {
4655 						/*
4656 						 * couldn't upgrade, so explictly take the lock
4657 						 * exclusively and go relookup the page since we
4658 						 * will have dropped the object lock and
4659 						 * a different thread could have inserted
4660 						 * a page at this offset
4661 						 * no need for a full retry since we're
4662 						 * at the top level of the object chain
4663 						 */
4664 						vm_object_lock(object);
4665 
4666 						continue;
4667 					}
4668 				}
4669 				if ((m->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q) && m_object->internal) {
4670 					/*
4671 					 * m->vmp_busy == TRUE and the object is locked exclusively
4672 					 * if m->pageout_queue == TRUE after we acquire the
4673 					 * queues lock, we are guaranteed that it is stable on
4674 					 * the pageout queue and therefore reclaimable
4675 					 *
4676 					 * NOTE: this is only true for the internal pageout queue
4677 					 * in the compressor world
4678 					 */
4679 					assert(VM_CONFIG_COMPRESSOR_IS_PRESENT);
4680 
4681 					vm_page_lock_queues();
4682 
4683 					if (m->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q) {
4684 						vm_pageout_throttle_up(m);
4685 						vm_page_unlock_queues();
4686 
4687 						vm_page_wakeup_done(m_object, m);
4688 						goto reclaimed_from_pageout;
4689 					}
4690 					vm_page_unlock_queues();
4691 				}
4692 				if (object != cur_object) {
4693 					vm_object_unlock(object);
4694 				}
4695 
4696 				vm_map_unlock_read(map);
4697 				if (real_map != map) {
4698 					vm_map_unlock(real_map);
4699 				}
4700 
4701 				result = vm_page_sleep(cur_object, m, fault_info->interruptible, LCK_SLEEP_UNLOCK);
4702 				if (result == THREAD_AWAKENED || result == THREAD_RESTART) {
4703 					goto RetryFault;
4704 				}
4705 
4706 				ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_BUSYPAGE_WAIT_INTERRUPTED), 0 /* arg */);
4707 				kr = KERN_ABORTED;
4708 				goto done;
4709 			}
4710 reclaimed_from_pageout:
4711 			if (m->vmp_laundry) {
4712 				if (object != cur_object) {
4713 					if (cur_object_lock_type == OBJECT_LOCK_SHARED) {
4714 						cur_object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4715 
4716 						vm_object_unlock(object);
4717 						vm_object_unlock(cur_object);
4718 
4719 						vm_map_unlock_read(map);
4720 						if (real_map != map) {
4721 							vm_map_unlock(real_map);
4722 						}
4723 
4724 						goto RetryFault;
4725 					}
4726 				} else if (object_lock_type == OBJECT_LOCK_SHARED) {
4727 					object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4728 
4729 					if (vm_object_lock_upgrade(object) == FALSE) {
4730 						/*
4731 						 * couldn't upgrade, so explictly take the lock
4732 						 * exclusively and go relookup the page since we
4733 						 * will have dropped the object lock and
4734 						 * a different thread could have inserted
4735 						 * a page at this offset
4736 						 * no need for a full retry since we're
4737 						 * at the top level of the object chain
4738 						 */
4739 						vm_object_lock(object);
4740 
4741 						continue;
4742 					}
4743 				}
4744 				vm_object_lock_assert_exclusive(VM_PAGE_OBJECT(m));
4745 				vm_pageout_steal_laundry(m, FALSE);
4746 			}
4747 
4748 
4749 			if (VM_PAGE_GET_PHYS_PAGE(m) == vm_page_guard_addr) {
4750 				/*
4751 				 * Guard page: let the slow path deal with it
4752 				 */
4753 				break;
4754 			}
4755 			if (m->vmp_unusual && (m->vmp_error || m->vmp_restart || m->vmp_private || m->vmp_absent)) {
4756 				/*
4757 				 * Unusual case... let the slow path deal with it
4758 				 */
4759 				break;
4760 			}
4761 			if (VM_OBJECT_PURGEABLE_FAULT_ERROR(m_object)) {
4762 				if (object != cur_object) {
4763 					vm_object_unlock(object);
4764 				}
4765 				vm_map_unlock_read(map);
4766 				if (real_map != map) {
4767 					vm_map_unlock(real_map);
4768 				}
4769 				vm_object_unlock(cur_object);
4770 				ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_PURGEABLE_FAULT_ERROR), 0 /* arg */);
4771 				kr = KERN_MEMORY_ERROR;
4772 				goto done;
4773 			}
4774 			assert(m_object == VM_PAGE_OBJECT(m));
4775 
4776 			if (vm_fault_cs_need_validation(map->pmap, m, m_object,
4777 			    PAGE_SIZE, 0) ||
4778 			    (physpage_p != NULL && (prot & VM_PROT_WRITE))) {
4779 upgrade_lock_and_retry:
4780 				/*
4781 				 * We might need to validate this page
4782 				 * against its code signature, so we
4783 				 * want to hold the VM object exclusively.
4784 				 */
4785 				if (object != cur_object) {
4786 					if (cur_object_lock_type == OBJECT_LOCK_SHARED) {
4787 						vm_object_unlock(object);
4788 						vm_object_unlock(cur_object);
4789 
4790 						cur_object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4791 
4792 						vm_map_unlock_read(map);
4793 						if (real_map != map) {
4794 							vm_map_unlock(real_map);
4795 						}
4796 
4797 						goto RetryFault;
4798 					}
4799 				} else if (object_lock_type == OBJECT_LOCK_SHARED) {
4800 					object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4801 
4802 					if (vm_object_lock_upgrade(object) == FALSE) {
4803 						/*
4804 						 * couldn't upgrade, so explictly take the lock
4805 						 * exclusively and go relookup the page since we
4806 						 * will have dropped the object lock and
4807 						 * a different thread could have inserted
4808 						 * a page at this offset
4809 						 * no need for a full retry since we're
4810 						 * at the top level of the object chain
4811 						 */
4812 						vm_object_lock(object);
4813 
4814 						continue;
4815 					}
4816 				}
4817 			}
4818 			/*
4819 			 *	Two cases of map in faults:
4820 			 *	    - At top level w/o copy object.
4821 			 *	    - Read fault anywhere.
4822 			 *		--> must disallow write.
4823 			 */
4824 
4825 			if (object == cur_object && object->vo_copy == VM_OBJECT_NULL) {
4826 #if CONFIG_TRACK_UNMODIFIED_ANON_PAGES
4827 				if ((fault_type & VM_PROT_WRITE) && m->vmp_unmodified_ro) {
4828 					assert(cur_object == VM_PAGE_OBJECT(m));
4829 					assert(cur_object->internal);
4830 					vm_object_lock_assert_exclusive(cur_object);
4831 					vm_page_lockspin_queues();
4832 					m->vmp_unmodified_ro = false;
4833 					vm_page_unlock_queues();
4834 					os_atomic_dec(&compressor_ro_uncompressed, relaxed);
4835 					vm_object_compressor_pager_state_clr(cur_object, m->vmp_offset);
4836 				}
4837 #endif /* CONFIG_TRACK_UNMODIFIED_ANON_PAGES */
4838 				goto FastPmapEnter;
4839 			}
4840 
4841 			if (!need_copy &&
4842 			    !fault_info->no_copy_on_read &&
4843 			    cur_object != object &&
4844 			    !cur_object->internal &&
4845 			    !cur_object->pager_trusted &&
4846 			    vm_protect_privileged_from_untrusted &&
4847 			    !cur_object->code_signed &&
4848 			    current_proc_is_privileged()) {
4849 				/*
4850 				 * We're faulting on a page in "object" and
4851 				 * went down the shadow chain to "cur_object"
4852 				 * to find out that "cur_object"'s pager
4853 				 * is not "trusted", i.e. we can not trust it
4854 				 * to always return the same contents.
4855 				 * Since the target is a "privileged" process,
4856 				 * let's treat this as a copy-on-read fault, as
4857 				 * if it was a copy-on-write fault.
4858 				 * Once "object" gets a copy of this page, it
4859 				 * won't have to rely on "cur_object" to
4860 				 * provide the contents again.
4861 				 *
4862 				 * This is done by setting "need_copy" and
4863 				 * retrying the fault from the top with the
4864 				 * appropriate locking.
4865 				 *
4866 				 * Special case: if the mapping is executable
4867 				 * and the untrusted object is code-signed and
4868 				 * the process is "cs_enforced", we do not
4869 				 * copy-on-read because that would break
4870 				 * code-signing enforcement expectations (an
4871 				 * executable page must belong to a code-signed
4872 				 * object) and we can rely on code-signing
4873 				 * to re-validate the page if it gets evicted
4874 				 * and paged back in.
4875 				 */
4876 //				printf("COPY-ON-READ %s:%d map %p va 0x%llx page %p object %p offset 0x%llx UNTRUSTED: need copy-on-read!\n", __FUNCTION__, __LINE__, map, (uint64_t)vaddr, m, VM_PAGE_OBJECT(m), m->vmp_offset);
4877 				vm_copied_on_read++;
4878 				need_copy = TRUE;
4879 
4880 				vm_object_unlock(object);
4881 				vm_object_unlock(cur_object);
4882 				object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4883 				vm_map_unlock_read(map);
4884 				if (real_map != map) {
4885 					vm_map_unlock(real_map);
4886 				}
4887 				goto RetryFault;
4888 			}
4889 
4890 			if (!(fault_type & VM_PROT_WRITE) && !need_copy) {
4891 				if (pmap_has_prot_policy(pmap, fault_info->pmap_options & PMAP_OPTIONS_TRANSLATED_ALLOW_EXECUTE, prot)) {
4892 					/*
4893 					 * For a protection that the pmap cares
4894 					 * about, we must hand over the full
4895 					 * set of protections (so that the pmap
4896 					 * layer can apply any desired policy).
4897 					 * This means that cs_bypass must be
4898 					 * set, as this can force us to pass
4899 					 * RWX.
4900 					 */
4901 					if (!fault_info->cs_bypass) {
4902 						panic("%s: pmap %p vaddr 0x%llx prot 0x%x options 0x%x",
4903 						    __FUNCTION__, pmap,
4904 						    (uint64_t)vaddr, prot,
4905 						    fault_info->pmap_options);
4906 					}
4907 				} else {
4908 					prot &= ~VM_PROT_WRITE;
4909 				}
4910 
4911 				if (object != cur_object) {
4912 					/*
4913 					 * We still need to hold the top object
4914 					 * lock here to prevent a race between
4915 					 * a read fault (taking only "shared"
4916 					 * locks) and a write fault (taking
4917 					 * an "exclusive" lock on the top
4918 					 * object.
4919 					 * Otherwise, as soon as we release the
4920 					 * top lock, the write fault could
4921 					 * proceed and actually complete before
4922 					 * the read fault, and the copied page's
4923 					 * translation could then be overwritten
4924 					 * by the read fault's translation for
4925 					 * the original page.
4926 					 *
4927 					 * Let's just record what the top object
4928 					 * is and we'll release it later.
4929 					 */
4930 					top_object = object;
4931 
4932 					/*
4933 					 * switch to the object that has the new page
4934 					 */
4935 					object = cur_object;
4936 					object_lock_type = cur_object_lock_type;
4937 				}
4938 FastPmapEnter:
4939 				assert(m_object == VM_PAGE_OBJECT(m));
4940 
4941 				/*
4942 				 * prepare for the pmap_enter...
4943 				 * object and map are both locked
4944 				 * m contains valid data
4945 				 * object == m->vmp_object
4946 				 * cur_object == NULL or it's been unlocked
4947 				 * no paging references on either object or cur_object
4948 				 */
4949 				if (top_object != VM_OBJECT_NULL || object_lock_type != OBJECT_LOCK_EXCLUSIVE) {
4950 					need_retry_ptr = &need_retry;
4951 				} else {
4952 					need_retry_ptr = NULL;
4953 				}
4954 
4955 				if (fault_page_size < PAGE_SIZE) {
4956 					DEBUG4K_FAULT("map %p original %p pmap %p va 0x%llx caller pmap %p va 0x%llx pa 0x%llx (0x%llx+0x%llx) prot 0x%x caller_prot 0x%x\n", map, original_map, pmap, (uint64_t)vaddr, caller_pmap, (uint64_t)caller_pmap_addr, (uint64_t)((((pmap_paddr_t)VM_PAGE_GET_PHYS_PAGE(m)) << PAGE_SHIFT) + fault_phys_offset), (uint64_t)(((pmap_paddr_t)VM_PAGE_GET_PHYS_PAGE(m)) << PAGE_SHIFT), (uint64_t)fault_phys_offset, prot, caller_prot);
4957 					assertf((!(fault_phys_offset & FOURK_PAGE_MASK) &&
4958 					    fault_phys_offset < PAGE_SIZE),
4959 					    "0x%llx\n", (uint64_t)fault_phys_offset);
4960 				} else {
4961 					assertf(fault_phys_offset == 0,
4962 					    "0x%llx\n", (uint64_t)fault_phys_offset);
4963 				}
4964 
4965 				if (__improbable(rtfault &&
4966 				    !m->vmp_realtime &&
4967 				    vm_pageout_protect_realtime)) {
4968 					vm_page_lock_queues();
4969 					if (!m->vmp_realtime) {
4970 						m->vmp_realtime = true;
4971 						vm_page_realtime_count++;
4972 					}
4973 					vm_page_unlock_queues();
4974 				}
4975 				assertf(VM_PAGE_OBJECT(m) == m_object, "m=%p m_object=%p object=%p", m, m_object, object);
4976 				assert(VM_PAGE_OBJECT(m) != VM_OBJECT_NULL);
4977 				if (caller_pmap) {
4978 					kr = vm_fault_enter(m,
4979 					    caller_pmap,
4980 					    caller_pmap_addr,
4981 					    fault_page_size,
4982 					    fault_phys_offset,
4983 					    prot,
4984 					    caller_prot,
4985 					    wired,
4986 					    change_wiring,
4987 					    wire_tag,
4988 					    fault_info,
4989 					    need_retry_ptr,
4990 					    &type_of_fault,
4991 					    &object_lock_type);
4992 				} else {
4993 					kr = vm_fault_enter(m,
4994 					    pmap,
4995 					    vaddr,
4996 					    fault_page_size,
4997 					    fault_phys_offset,
4998 					    prot,
4999 					    caller_prot,
5000 					    wired,
5001 					    change_wiring,
5002 					    wire_tag,
5003 					    fault_info,
5004 					    need_retry_ptr,
5005 					    &type_of_fault,
5006 					    &object_lock_type);
5007 				}
5008 
5009 				vm_fault_complete(
5010 					map,
5011 					real_map,
5012 					object,
5013 					m_object,
5014 					m,
5015 					offset,
5016 					trace_real_vaddr,
5017 					fault_info,
5018 					caller_prot,
5019 					real_vaddr,
5020 					vm_fault_type_for_tracing(need_copy_on_read, type_of_fault),
5021 					need_retry,
5022 					kr,
5023 					physpage_p,
5024 					prot,
5025 					top_object,
5026 					need_collapse,
5027 					cur_offset,
5028 					fault_type,
5029 					&written_on_object,
5030 					&written_on_pager,
5031 					&written_on_offset);
5032 				top_object = VM_OBJECT_NULL;
5033 				if (need_retry == TRUE) {
5034 					/*
5035 					 * vm_fault_enter couldn't complete the PMAP_ENTER...
5036 					 * at this point we don't hold any locks so it's safe
5037 					 * to ask the pmap layer to expand the page table to
5038 					 * accommodate this mapping... once expanded, we'll
5039 					 * re-drive the fault which should result in vm_fault_enter
5040 					 * being able to successfully enter the mapping this time around
5041 					 */
5042 					(void)pmap_enter_options(
5043 						pmap, vaddr, 0, 0, 0, 0, 0,
5044 						PMAP_OPTIONS_NOENTER, NULL, PMAP_MAPPING_TYPE_INFER);
5045 
5046 					need_retry = FALSE;
5047 					goto RetryFault;
5048 				}
5049 				goto done;
5050 			}
5051 			/*
5052 			 * COPY ON WRITE FAULT
5053 			 */
5054 			assert(object_lock_type == OBJECT_LOCK_EXCLUSIVE);
5055 
5056 			/*
5057 			 * If objects match, then
5058 			 * object->vo_copy must not be NULL (else control
5059 			 * would be in previous code block), and we
5060 			 * have a potential push into the copy object
5061 			 * with which we can't cope with here.
5062 			 */
5063 			if (cur_object == object) {
5064 				/*
5065 				 * must take the slow path to
5066 				 * deal with the copy push
5067 				 */
5068 				break;
5069 			}
5070 
5071 			/*
5072 			 * This is now a shadow based copy on write
5073 			 * fault -- it requires a copy up the shadow
5074 			 * chain.
5075 			 */
5076 			assert(m_object == VM_PAGE_OBJECT(m));
5077 
5078 			if ((cur_object_lock_type == OBJECT_LOCK_SHARED) &&
5079 			    vm_fault_cs_need_validation(NULL, m, m_object,
5080 			    PAGE_SIZE, 0)) {
5081 				goto upgrade_lock_and_retry;
5082 			}
5083 
5084 #if MACH_ASSERT
5085 			if (resilient_media_retry &&
5086 			    vm_fault_resilient_media_inject_error2_rate != 0 &&
5087 			    (++vm_fault_resilient_media_inject_error2 % vm_fault_resilient_media_inject_error2_rate) == 0) {
5088 				/* inject an error */
5089 				cur_m = m;
5090 				m = VM_PAGE_NULL;
5091 				m_object = VM_OBJECT_NULL;
5092 				break;
5093 			}
5094 #endif /* MACH_ASSERT */
5095 			/*
5096 			 * Allocate a page in the original top level
5097 			 * object. Give up if allocate fails.  Also
5098 			 * need to remember current page, as it's the
5099 			 * source of the copy.
5100 			 *
5101 			 * at this point we hold locks on both
5102 			 * object and cur_object... no need to take
5103 			 * paging refs or mark pages BUSY since
5104 			 * we don't drop either object lock until
5105 			 * the page has been copied and inserted
5106 			 */
5107 			cur_m = m;
5108 			m = vm_page_grab_options(grab_options);
5109 			m_object = NULL;
5110 
5111 			if (m == VM_PAGE_NULL) {
5112 				/*
5113 				 * no free page currently available...
5114 				 * must take the slow path
5115 				 */
5116 				break;
5117 			}
5118 
5119 			/*
5120 			 * Now do the copy.  Mark the source page busy...
5121 			 *
5122 			 *	NOTE: This code holds the map lock across
5123 			 *	the page copy.
5124 			 */
5125 			vm_page_copy(cur_m, m);
5126 			vm_page_insert(m, object, vm_object_trunc_page(offset));
5127 			if (VM_MAP_PAGE_MASK(map) != PAGE_MASK) {
5128 				DEBUG4K_FAULT("map %p vaddr 0x%llx page %p [%p 0x%llx] copied to %p [%p 0x%llx]\n", map, (uint64_t)vaddr, cur_m, VM_PAGE_OBJECT(cur_m), cur_m->vmp_offset, m, VM_PAGE_OBJECT(m), m->vmp_offset);
5129 			}
5130 			m_object = object;
5131 			SET_PAGE_DIRTY(m, FALSE);
5132 
5133 			/*
5134 			 * Now cope with the source page and object
5135 			 */
5136 			if (object->ref_count > 1 && cur_m->vmp_pmapped) {
5137 				pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(cur_m));
5138 			} else if (VM_MAP_PAGE_SIZE(map) < PAGE_SIZE) {
5139 				/*
5140 				 * We've copied the full 16K page but we're
5141 				 * about to call vm_fault_enter() only for
5142 				 * the 4K chunk we're faulting on.  The other
5143 				 * three 4K chunks in that page could still
5144 				 * be pmapped in this pmap.
5145 				 * Since the VM object layer thinks that the
5146 				 * entire page has been dealt with and the
5147 				 * original page might no longer be needed,
5148 				 * it might collapse/bypass the original VM
5149 				 * object and free its pages, which would be
5150 				 * bad (and would trigger pmap_verify_free()
5151 				 * assertions) if the other 4K chunks are still
5152 				 * pmapped.
5153 				 */
5154 				/*
5155 				 * XXX FBDP TODO4K: to be revisisted
5156 				 * Technically, we need to pmap_disconnect()
5157 				 * only the target pmap's mappings for the 4K
5158 				 * chunks of this 16K VM page.  If other pmaps
5159 				 * have PTEs on these chunks, that means that
5160 				 * the associated VM map must have a reference
5161 				 * on the VM object, so no need to worry about
5162 				 * those.
5163 				 * pmap_protect() for each 4K chunk would be
5164 				 * better but we'd have to check which chunks
5165 				 * are actually mapped before and after this
5166 				 * one.
5167 				 * A full-blown pmap_disconnect() is easier
5168 				 * for now but not efficient.
5169 				 */
5170 				DEBUG4K_FAULT("pmap_disconnect() page %p object %p offset 0x%llx phys 0x%x\n", cur_m, VM_PAGE_OBJECT(cur_m), cur_m->vmp_offset, VM_PAGE_GET_PHYS_PAGE(cur_m));
5171 				pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(cur_m));
5172 			}
5173 
5174 			if (cur_m->vmp_clustered) {
5175 				VM_PAGE_COUNT_AS_PAGEIN(cur_m);
5176 				VM_PAGE_CONSUME_CLUSTERED(cur_m);
5177 				vm_fault_is_sequential(cur_object, cur_offset, fault_info->behavior);
5178 			}
5179 			need_collapse = TRUE;
5180 
5181 			if (!cur_object->internal &&
5182 			    cur_object->copy_strategy == MEMORY_OBJECT_COPY_DELAY) {
5183 				/*
5184 				 * The object from which we've just
5185 				 * copied a page is most probably backed
5186 				 * by a vnode.  We don't want to waste too
5187 				 * much time trying to collapse the VM objects
5188 				 * and create a bottleneck when several tasks
5189 				 * map the same file.
5190 				 */
5191 				if (cur_object->vo_copy == object) {
5192 					/*
5193 					 * Shared mapping or no COW yet.
5194 					 * We can never collapse a copy
5195 					 * object into its backing object.
5196 					 */
5197 					need_collapse = FALSE;
5198 				} else if (cur_object->vo_copy == object->shadow &&
5199 				    object->shadow->resident_page_count == 0) {
5200 					/*
5201 					 * Shared mapping after a COW occurred.
5202 					 */
5203 					need_collapse = FALSE;
5204 				}
5205 			}
5206 			vm_object_unlock(cur_object);
5207 
5208 			if (need_collapse == FALSE) {
5209 				vm_fault_collapse_skipped++;
5210 			}
5211 			vm_fault_collapse_total++;
5212 
5213 			type_of_fault = DBG_COW_FAULT;
5214 			counter_inc(&vm_statistics_cow_faults);
5215 			DTRACE_VM2(cow_fault, int, 1, (uint64_t *), NULL);
5216 			counter_inc(&current_task()->cow_faults);
5217 
5218 			goto FastPmapEnter;
5219 		} else {
5220 			/*
5221 			 * No page at cur_object, cur_offset... m == NULL
5222 			 */
5223 			if (cur_object->pager_created) {
5224 				vm_external_state_t compressor_external_state = VM_EXTERNAL_STATE_UNKNOWN;
5225 
5226 				if (MUST_ASK_PAGER(cur_object, cur_offset, compressor_external_state) == TRUE) {
5227 					int             my_fault_type;
5228 					vm_compressor_options_t         c_flags = C_DONT_BLOCK;
5229 					bool            insert_cur_object = FALSE;
5230 
5231 					/*
5232 					 * May have to talk to a pager...
5233 					 * if so, take the slow path by
5234 					 * doing a 'break' from the while (TRUE) loop
5235 					 *
5236 					 * external_state will only be set to VM_EXTERNAL_STATE_EXISTS
5237 					 * if the compressor is active and the page exists there
5238 					 */
5239 					if (compressor_external_state != VM_EXTERNAL_STATE_EXISTS) {
5240 						break;
5241 					}
5242 
5243 					if (map == kernel_map || real_map == kernel_map) {
5244 						/*
5245 						 * can't call into the compressor with the kernel_map
5246 						 * lock held, since the compressor may try to operate
5247 						 * on the kernel map in order to return an empty c_segment
5248 						 */
5249 						break;
5250 					}
5251 					if (object != cur_object) {
5252 						if (fault_type & VM_PROT_WRITE) {
5253 							c_flags |= C_KEEP;
5254 						} else {
5255 							insert_cur_object = TRUE;
5256 						}
5257 					}
5258 					if (insert_cur_object == TRUE) {
5259 						if (cur_object_lock_type == OBJECT_LOCK_SHARED) {
5260 							cur_object_lock_type = OBJECT_LOCK_EXCLUSIVE;
5261 
5262 							if (vm_object_lock_upgrade(cur_object) == FALSE) {
5263 								/*
5264 								 * couldn't upgrade so go do a full retry
5265 								 * immediately since we can no longer be
5266 								 * certain about cur_object (since we
5267 								 * don't hold a reference on it)...
5268 								 * first drop the top object lock
5269 								 */
5270 								vm_object_unlock(object);
5271 
5272 								vm_map_unlock_read(map);
5273 								if (real_map != map) {
5274 									vm_map_unlock(real_map);
5275 								}
5276 
5277 								goto RetryFault;
5278 							}
5279 						}
5280 					} else if (object_lock_type == OBJECT_LOCK_SHARED) {
5281 						object_lock_type = OBJECT_LOCK_EXCLUSIVE;
5282 
5283 						if (object != cur_object) {
5284 							/*
5285 							 * we can't go for the upgrade on the top
5286 							 * lock since the upgrade may block waiting
5287 							 * for readers to drain... since we hold
5288 							 * cur_object locked at this point, waiting
5289 							 * for the readers to drain would represent
5290 							 * a lock order inversion since the lock order
5291 							 * for objects is the reference order in the
5292 							 * shadown chain
5293 							 */
5294 							vm_object_unlock(object);
5295 							vm_object_unlock(cur_object);
5296 
5297 							vm_map_unlock_read(map);
5298 							if (real_map != map) {
5299 								vm_map_unlock(real_map);
5300 							}
5301 
5302 							goto RetryFault;
5303 						}
5304 						if (vm_object_lock_upgrade(object) == FALSE) {
5305 							/*
5306 							 * couldn't upgrade, so explictly take the lock
5307 							 * exclusively and go relookup the page since we
5308 							 * will have dropped the object lock and
5309 							 * a different thread could have inserted
5310 							 * a page at this offset
5311 							 * no need for a full retry since we're
5312 							 * at the top level of the object chain
5313 							 */
5314 							vm_object_lock(object);
5315 
5316 							continue;
5317 						}
5318 					}
5319 					m = vm_page_grab_options(grab_options);
5320 					m_object = NULL;
5321 
5322 					if (m == VM_PAGE_NULL) {
5323 						/*
5324 						 * no free page currently available...
5325 						 * must take the slow path
5326 						 */
5327 						break;
5328 					}
5329 
5330 					/*
5331 					 * The object is and remains locked
5332 					 * so no need to take a
5333 					 * "paging_in_progress" reference.
5334 					 */
5335 					bool      shared_lock;
5336 					if ((object == cur_object &&
5337 					    object_lock_type == OBJECT_LOCK_EXCLUSIVE) ||
5338 					    (object != cur_object &&
5339 					    cur_object_lock_type == OBJECT_LOCK_EXCLUSIVE)) {
5340 						shared_lock = FALSE;
5341 					} else {
5342 						shared_lock = TRUE;
5343 					}
5344 
5345 					kr = vm_compressor_pager_get(
5346 						cur_object->pager,
5347 						(vm_object_trunc_page(cur_offset)
5348 						+ cur_object->paging_offset),
5349 						VM_PAGE_GET_PHYS_PAGE(m),
5350 						&my_fault_type,
5351 						c_flags,
5352 						&compressed_count_delta);
5353 
5354 					vm_compressor_pager_count(
5355 						cur_object->pager,
5356 						compressed_count_delta,
5357 						shared_lock,
5358 						cur_object);
5359 
5360 					if (kr != KERN_SUCCESS) {
5361 						vm_page_release(m, FALSE);
5362 						m = VM_PAGE_NULL;
5363 					}
5364 					/*
5365 					 * If vm_compressor_pager_get() returns
5366 					 * KERN_MEMORY_FAILURE, then the
5367 					 * compressed data is permanently lost,
5368 					 * so return this error immediately.
5369 					 */
5370 					if (kr == KERN_MEMORY_FAILURE) {
5371 						if (object != cur_object) {
5372 							vm_object_unlock(cur_object);
5373 						}
5374 						vm_object_unlock(object);
5375 						vm_map_unlock_read(map);
5376 						if (real_map != map) {
5377 							vm_map_unlock(real_map);
5378 						}
5379 
5380 						goto done;
5381 					} else if (kr != KERN_SUCCESS) {
5382 						break;
5383 					}
5384 					m->vmp_dirty = TRUE;
5385 #if CONFIG_TRACK_UNMODIFIED_ANON_PAGES
5386 					if ((fault_type & VM_PROT_WRITE) == 0) {
5387 						prot &= ~VM_PROT_WRITE;
5388 						/*
5389 						 * The page, m, has yet to be inserted
5390 						 * into an object. So we are fine with
5391 						 * the object/cur_object lock being held
5392 						 * shared.
5393 						 */
5394 						vm_page_lockspin_queues();
5395 						m->vmp_unmodified_ro = true;
5396 						vm_page_unlock_queues();
5397 						os_atomic_inc(&compressor_ro_uncompressed, relaxed);
5398 					}
5399 #endif /* CONFIG_TRACK_UNMODIFIED_ANON_PAGES */
5400 
5401 					/*
5402 					 * If the object is purgeable, its
5403 					 * owner's purgeable ledgers will be
5404 					 * updated in vm_page_insert() but the
5405 					 * page was also accounted for in a
5406 					 * "compressed purgeable" ledger, so
5407 					 * update that now.
5408 					 */
5409 					if (object != cur_object &&
5410 					    !insert_cur_object) {
5411 						/*
5412 						 * We're not going to insert
5413 						 * the decompressed page into
5414 						 * the object it came from.
5415 						 *
5416 						 * We're dealing with a
5417 						 * copy-on-write fault on
5418 						 * "object".
5419 						 * We're going to decompress
5420 						 * the page directly into the
5421 						 * target "object" while
5422 						 * keepin the compressed
5423 						 * page for "cur_object", so
5424 						 * no ledger update in that
5425 						 * case.
5426 						 */
5427 					} else if (((cur_object->purgable ==
5428 					    VM_PURGABLE_DENY) &&
5429 					    (!cur_object->vo_ledger_tag)) ||
5430 					    (cur_object->vo_owner ==
5431 					    NULL)) {
5432 						/*
5433 						 * "cur_object" is not purgeable
5434 						 * and is not ledger-taged, or
5435 						 * there's no owner for it,
5436 						 * so no owner's ledgers to
5437 						 * update.
5438 						 */
5439 					} else {
5440 						/*
5441 						 * One less compressed
5442 						 * purgeable/tagged page for
5443 						 * cur_object's owner.
5444 						 */
5445 						if (compressed_count_delta) {
5446 							vm_object_owner_compressed_update(
5447 								cur_object,
5448 								-1);
5449 						}
5450 					}
5451 
5452 					if (insert_cur_object) {
5453 						vm_page_insert(m, cur_object, vm_object_trunc_page(cur_offset));
5454 						m_object = cur_object;
5455 					} else {
5456 						vm_page_insert(m, object, vm_object_trunc_page(offset));
5457 						m_object = object;
5458 					}
5459 
5460 					if ((m_object->wimg_bits & VM_WIMG_MASK) != VM_WIMG_USE_DEFAULT) {
5461 						/*
5462 						 * If the page is not cacheable,
5463 						 * we can't let its contents
5464 						 * linger in the data cache
5465 						 * after the decompression.
5466 						 */
5467 						pmap_sync_page_attributes_phys(VM_PAGE_GET_PHYS_PAGE(m));
5468 					}
5469 
5470 					type_of_fault = my_fault_type;
5471 
5472 					VM_STAT_DECOMPRESSIONS();
5473 
5474 					if (cur_object != object) {
5475 						if (insert_cur_object) {
5476 							top_object = object;
5477 							/*
5478 							 * switch to the object that has the new page
5479 							 */
5480 							object = cur_object;
5481 							object_lock_type = cur_object_lock_type;
5482 						} else {
5483 							vm_object_unlock(cur_object);
5484 							cur_object = object;
5485 						}
5486 					}
5487 					goto FastPmapEnter;
5488 				}
5489 				/*
5490 				 * existence map present and indicates
5491 				 * that the pager doesn't have this page
5492 				 */
5493 			}
5494 			if (cur_object->shadow == VM_OBJECT_NULL ||
5495 			    resilient_media_retry) {
5496 				/*
5497 				 * Zero fill fault.  Page gets
5498 				 * inserted into the original object.
5499 				 */
5500 				if (cur_object->shadow_severed ||
5501 				    VM_OBJECT_PURGEABLE_FAULT_ERROR(cur_object) ||
5502 				    cur_object == compressor_object ||
5503 				    is_kernel_object(cur_object)) {
5504 					if (object != cur_object) {
5505 						vm_object_unlock(cur_object);
5506 					}
5507 					vm_object_unlock(object);
5508 
5509 					vm_map_unlock_read(map);
5510 					if (real_map != map) {
5511 						vm_map_unlock(real_map);
5512 					}
5513 					if (VM_OBJECT_PURGEABLE_FAULT_ERROR(cur_object)) {
5514 						ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_PURGEABLE_FAULT_ERROR), 0 /* arg */);
5515 					}
5516 
5517 					if (cur_object->shadow_severed) {
5518 						ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_OBJECT_SHADOW_SEVERED), 0 /* arg */);
5519 					}
5520 
5521 					kr = KERN_MEMORY_ERROR;
5522 					goto done;
5523 				}
5524 				if (cur_object != object) {
5525 					vm_object_unlock(cur_object);
5526 
5527 					cur_object = object;
5528 				}
5529 				if (object_lock_type == OBJECT_LOCK_SHARED) {
5530 					object_lock_type = OBJECT_LOCK_EXCLUSIVE;
5531 
5532 					if (vm_object_lock_upgrade(object) == FALSE) {
5533 						/*
5534 						 * couldn't upgrade so do a full retry on the fault
5535 						 * since we dropped the object lock which
5536 						 * could allow another thread to insert
5537 						 * a page at this offset
5538 						 */
5539 						vm_map_unlock_read(map);
5540 						if (real_map != map) {
5541 							vm_map_unlock(real_map);
5542 						}
5543 
5544 						goto RetryFault;
5545 					}
5546 				}
5547 				if (!object->internal) {
5548 					panic("%s:%d should not zero-fill page at offset 0x%llx in external object %p", __FUNCTION__, __LINE__, (uint64_t)offset, object);
5549 				}
5550 #if MACH_ASSERT
5551 				if (resilient_media_retry &&
5552 				    vm_fault_resilient_media_inject_error3_rate != 0 &&
5553 				    (++vm_fault_resilient_media_inject_error3 % vm_fault_resilient_media_inject_error3_rate) == 0) {
5554 					/* inject an error */
5555 					m_object = NULL;
5556 					break;
5557 				}
5558 #endif /* MACH_ASSERT */
5559 				m = vm_page_alloc(object, vm_object_trunc_page(offset));
5560 				m_object = NULL;
5561 
5562 				if (m == VM_PAGE_NULL) {
5563 					/*
5564 					 * no free page currently available...
5565 					 * must take the slow path
5566 					 */
5567 					break;
5568 				}
5569 				m_object = object;
5570 
5571 				if ((prot & VM_PROT_WRITE) &&
5572 				    !(fault_type & VM_PROT_WRITE) &&
5573 				    object->vo_copy != VM_OBJECT_NULL) {
5574 					/*
5575 					 * This is not a write fault and
5576 					 * we might have a copy-on-write
5577 					 * obligation to honor (copy object or
5578 					 * "needs_copy" map entry), so do not
5579 					 * give write access yet.
5580 					 * We'll need to catch the first write
5581 					 * to resolve the copy-on-write by
5582 					 * pushing this page to a copy object
5583 					 * or making a shadow object.
5584 					 */
5585 					if (pmap_has_prot_policy(pmap, fault_info->pmap_options & PMAP_OPTIONS_TRANSLATED_ALLOW_EXECUTE, prot)) {
5586 						/*
5587 						 * This pmap enforces extra
5588 						 * constraints for this set of
5589 						 * protections, so we can't
5590 						 * change the protections.
5591 						 * We would expect code-signing
5592 						 * to be bypassed in this case.
5593 						 */
5594 						if (!fault_info->cs_bypass) {
5595 							panic("%s: pmap %p vaddr 0x%llx prot 0x%x options 0x%x",
5596 							    __FUNCTION__,
5597 							    pmap,
5598 							    (uint64_t)vaddr,
5599 							    prot,
5600 							    fault_info->pmap_options);
5601 						}
5602 					} else {
5603 						prot &= ~VM_PROT_WRITE;
5604 					}
5605 				}
5606 				assertf(!((fault_type & VM_PROT_WRITE) && object->vo_copy),
5607 				    "map %p va 0x%llx wrong path for write fault (fault_type 0x%x) on object %p with copy %p\n",
5608 				    map, (uint64_t)vaddr, fault_type, object, object->vo_copy);
5609 
5610 				vm_object_t saved_copy_object;
5611 				uint32_t saved_copy_version;
5612 				saved_copy_object = object->vo_copy;
5613 				saved_copy_version = object->vo_copy_version;
5614 
5615 				/*
5616 				 * Zeroing the page and entering into it into the pmap
5617 				 * represents a significant amount of the zero fill fault handler's work.
5618 				 *
5619 				 * To improve fault scalability, we'll drop the object lock, if it appears contended,
5620 				 * now that we've inserted the page into the vm object.
5621 				 * Before dropping the lock, we need to check protection bits and set the
5622 				 * mapped bits on the page. Then we can mark the page busy, drop the lock,
5623 				 * zero it, and do the pmap enter. We'll need to reacquire the lock
5624 				 * to clear the busy bit and wake up any waiters.
5625 				 */
5626 				vm_fault_cs_clear(m);
5627 				m->vmp_pmapped = TRUE;
5628 				if (map->no_zero_fill) {
5629 					type_of_fault = DBG_NZF_PAGE_FAULT;
5630 				} else {
5631 					type_of_fault = DBG_ZERO_FILL_FAULT;
5632 				}
5633 				{
5634 					pmap_t destination_pmap;
5635 					vm_map_offset_t destination_pmap_vaddr;
5636 					vm_prot_t enter_fault_type;
5637 					if (caller_pmap) {
5638 						destination_pmap = caller_pmap;
5639 						destination_pmap_vaddr = caller_pmap_addr;
5640 					} else {
5641 						destination_pmap = pmap;
5642 						destination_pmap_vaddr = vaddr;
5643 					}
5644 					if (change_wiring) {
5645 						enter_fault_type = VM_PROT_NONE;
5646 					} else {
5647 						enter_fault_type = caller_prot;
5648 					}
5649 					assertf(VM_PAGE_OBJECT(m) == object, "m=%p object=%p", m, object);
5650 					kr = vm_fault_enter_prepare(m,
5651 					    destination_pmap,
5652 					    destination_pmap_vaddr,
5653 					    &prot,
5654 					    caller_prot,
5655 					    fault_page_size,
5656 					    fault_phys_offset,
5657 					    change_wiring,
5658 					    enter_fault_type,
5659 					    fault_info,
5660 					    &type_of_fault,
5661 					    &page_needs_data_sync);
5662 					if (kr != KERN_SUCCESS) {
5663 						goto zero_fill_cleanup;
5664 					}
5665 
5666 					if (object_is_contended) {
5667 						/*
5668 						 * At this point the page is in the vm object, but not on a paging queue.
5669 						 * Since it's accessible to another thread but its contents are invalid
5670 						 * (it hasn't been zeroed) mark it busy before dropping the object lock.
5671 						 */
5672 						m->vmp_busy = TRUE;
5673 						vm_object_paging_begin(object); /* keep object alive */
5674 						vm_object_unlock(object);
5675 					}
5676 					if (type_of_fault == DBG_ZERO_FILL_FAULT) {
5677 						/*
5678 						 * Now zero fill page...
5679 						 * the page is probably going to
5680 						 * be written soon, so don't bother
5681 						 * to clear the modified bit
5682 						 *
5683 						 *   NOTE: This code holds the map
5684 						 *   lock across the zero fill.
5685 						 */
5686 						vm_page_zero_fill(m);
5687 						counter_inc(&vm_statistics_zero_fill_count);
5688 						DTRACE_VM2(zfod, int, 1, (uint64_t *), NULL);
5689 					}
5690 
5691 					if (object_is_contended) {
5692 						/*
5693 						 * It's not safe to do the pmap_enter() without holding
5694 						 * the object lock because its "vo_copy" could change.
5695 						 */
5696 						object_is_contended = false; /* get out of that code path */
5697 
5698 						vm_object_lock(object);
5699 						vm_object_paging_end(object);
5700 						if (object->vo_copy != saved_copy_object ||
5701 						    object->vo_copy_version != saved_copy_version) {
5702 							/*
5703 							 * The COPY_DELAY copy-on-write situation for
5704 							 * this VM object has changed while it was
5705 							 * unlocked, so do not grant write access to
5706 							 * this page.
5707 							 * The write access will fault again and we'll
5708 							 * resolve the copy-on-write then.
5709 							 */
5710 							if (pmap_has_prot_policy(pmap,
5711 							    fault_info->pmap_options & PMAP_OPTIONS_TRANSLATED_ALLOW_EXECUTE,
5712 							    prot)) {
5713 								/* we should not do CoW on pmap_has_prot_policy mappings */
5714 								panic("%s: map %p va 0x%llx obj %p,%u saved %p,%u: unexpected CoW",
5715 								    __FUNCTION__,
5716 								    map, (uint64_t)vaddr,
5717 								    object, object->vo_copy_version,
5718 								    saved_copy_object, saved_copy_version);
5719 							} else {
5720 								/* the pmap layer is OK with changing the PTE's prot */
5721 								prot &= ~VM_PROT_WRITE;
5722 							}
5723 						}
5724 					}
5725 
5726 					if (page_needs_data_sync) {
5727 						pmap_sync_page_data_phys(VM_PAGE_GET_PHYS_PAGE(m));
5728 					}
5729 
5730 					if (top_object != VM_OBJECT_NULL) {
5731 						need_retry_ptr = &need_retry;
5732 					} else {
5733 						need_retry_ptr = NULL;
5734 					}
5735 					if (fault_info->fi_xnu_user_debug &&
5736 					    !object->code_signed) {
5737 						fault_info->pmap_options |= PMAP_OPTIONS_XNU_USER_DEBUG;
5738 					}
5739 					if (object_is_contended) {
5740 						panic("object_is_contended");
5741 						kr = vm_fault_pmap_enter(destination_pmap, destination_pmap_vaddr,
5742 						    fault_page_size, fault_phys_offset,
5743 						    m, &prot, caller_prot, enter_fault_type, wired,
5744 						    fault_info->pmap_options, need_retry_ptr);
5745 						vm_object_lock(object);
5746 						assertf(!((prot & VM_PROT_WRITE) && object->vo_copy),
5747 						    "prot 0x%x object %p copy %p\n",
5748 						    prot, object, object->vo_copy);
5749 					} else {
5750 						kr = vm_fault_pmap_enter_with_object_lock(object, destination_pmap, destination_pmap_vaddr,
5751 						    fault_page_size, fault_phys_offset,
5752 						    m, &prot, caller_prot, enter_fault_type, wired,
5753 						    fault_info->pmap_options, need_retry_ptr, &object_lock_type);
5754 					}
5755 				}
5756 zero_fill_cleanup:
5757 				if (!VM_DYNAMIC_PAGING_ENABLED() &&
5758 				    (object->purgable == VM_PURGABLE_DENY ||
5759 				    object->purgable == VM_PURGABLE_NONVOLATILE ||
5760 				    object->purgable == VM_PURGABLE_VOLATILE)) {
5761 					vm_page_lockspin_queues();
5762 					if (!VM_DYNAMIC_PAGING_ENABLED()) {
5763 						vm_fault_enqueue_throttled_locked(m);
5764 					}
5765 					vm_page_unlock_queues();
5766 				}
5767 				vm_fault_enqueue_page(object, m, wired, change_wiring, wire_tag, fault_info->no_cache, &type_of_fault, kr);
5768 
5769 				if (__improbable(rtfault &&
5770 				    !m->vmp_realtime &&
5771 				    vm_pageout_protect_realtime)) {
5772 					vm_page_lock_queues();
5773 					if (!m->vmp_realtime) {
5774 						m->vmp_realtime = true;
5775 						vm_page_realtime_count++;
5776 					}
5777 					vm_page_unlock_queues();
5778 				}
5779 				vm_fault_complete(
5780 					map,
5781 					real_map,
5782 					object,
5783 					m_object,
5784 					m,
5785 					offset,
5786 					trace_real_vaddr,
5787 					fault_info,
5788 					caller_prot,
5789 					real_vaddr,
5790 					type_of_fault,
5791 					need_retry,
5792 					kr,
5793 					physpage_p,
5794 					prot,
5795 					top_object,
5796 					need_collapse,
5797 					cur_offset,
5798 					fault_type,
5799 					&written_on_object,
5800 					&written_on_pager,
5801 					&written_on_offset);
5802 				top_object = VM_OBJECT_NULL;
5803 				if (need_retry == TRUE) {
5804 					/*
5805 					 * vm_fault_enter couldn't complete the PMAP_ENTER...
5806 					 * at this point we don't hold any locks so it's safe
5807 					 * to ask the pmap layer to expand the page table to
5808 					 * accommodate this mapping... once expanded, we'll
5809 					 * re-drive the fault which should result in vm_fault_enter
5810 					 * being able to successfully enter the mapping this time around
5811 					 */
5812 					(void)pmap_enter_options(
5813 						pmap, vaddr, 0, 0, 0, 0, 0,
5814 						PMAP_OPTIONS_NOENTER, NULL, PMAP_MAPPING_TYPE_INFER);
5815 
5816 					need_retry = FALSE;
5817 					goto RetryFault;
5818 				}
5819 				goto done;
5820 			}
5821 			/*
5822 			 * On to the next level in the shadow chain
5823 			 */
5824 			cur_offset += cur_object->vo_shadow_offset;
5825 			new_object = cur_object->shadow;
5826 			fault_phys_offset = cur_offset - vm_object_trunc_page(cur_offset);
5827 
5828 			/*
5829 			 * take the new_object's lock with the indicated state
5830 			 */
5831 			if (cur_object_lock_type == OBJECT_LOCK_SHARED) {
5832 				vm_object_lock_shared(new_object);
5833 			} else {
5834 				vm_object_lock(new_object);
5835 			}
5836 
5837 			if (cur_object != object) {
5838 				vm_object_unlock(cur_object);
5839 			}
5840 
5841 			cur_object = new_object;
5842 
5843 			continue;
5844 		}
5845 	}
5846 	/*
5847 	 * Cleanup from fast fault failure.  Drop any object
5848 	 * lock other than original and drop map lock.
5849 	 */
5850 	if (object != cur_object) {
5851 		vm_object_unlock(cur_object);
5852 	}
5853 
5854 	/*
5855 	 * must own the object lock exclusively at this point
5856 	 */
5857 	if (object_lock_type == OBJECT_LOCK_SHARED) {
5858 		object_lock_type = OBJECT_LOCK_EXCLUSIVE;
5859 
5860 		if (vm_object_lock_upgrade(object) == FALSE) {
5861 			/*
5862 			 * couldn't upgrade, so explictly
5863 			 * take the lock exclusively
5864 			 * no need to retry the fault at this
5865 			 * point since "vm_fault_page" will
5866 			 * completely re-evaluate the state
5867 			 */
5868 			vm_object_lock(object);
5869 		}
5870 	}
5871 
5872 handle_copy_delay:
5873 	vm_map_unlock_read(map);
5874 	if (real_map != map) {
5875 		vm_map_unlock(real_map);
5876 	}
5877 
5878 	if (__improbable(object == compressor_object ||
5879 	    is_kernel_object(object))) {
5880 		/*
5881 		 * These objects are explicitly managed and populated by the
5882 		 * kernel.  The virtual ranges backed by these objects should
5883 		 * either have wired pages or "holes" that are not supposed to
5884 		 * be accessed at all until they get explicitly populated.
5885 		 * We should never have to resolve a fault on a mapping backed
5886 		 * by one of these VM objects and providing a zero-filled page
5887 		 * would be wrong here, so let's fail the fault and let the
5888 		 * caller crash or recover.
5889 		 */
5890 		vm_object_unlock(object);
5891 		kr = KERN_MEMORY_ERROR;
5892 		goto done;
5893 	}
5894 
5895 	resilient_media_ref_transfer = false;
5896 	if (resilient_media_retry) {
5897 		/*
5898 		 * We could get here if we failed to get a free page
5899 		 * to zero-fill and had to take the slow path again.
5900 		 * Reset our "recovery-from-failed-media" state.
5901 		 */
5902 		assert(resilient_media_object != VM_OBJECT_NULL);
5903 		assert(resilient_media_offset != (vm_object_offset_t)-1);
5904 		/* release our extra reference on failed object */
5905 //             printf("FBDP %s:%d resilient_media_object %p deallocate\n", __FUNCTION__, __LINE__, resilient_media_object);
5906 		if (object == resilient_media_object) {
5907 			/*
5908 			 * We're holding "object"'s lock, so we can't release
5909 			 * our extra reference at this point.
5910 			 * We need an extra reference on "object" anyway
5911 			 * (see below), so let's just transfer this reference.
5912 			 */
5913 			resilient_media_ref_transfer = true;
5914 		} else {
5915 			vm_object_deallocate(resilient_media_object);
5916 		}
5917 		resilient_media_object = VM_OBJECT_NULL;
5918 		resilient_media_offset = (vm_object_offset_t)-1;
5919 		resilient_media_retry = false;
5920 		vm_fault_resilient_media_abort2++;
5921 	}
5922 
5923 	/*
5924 	 * Make a reference to this object to
5925 	 * prevent its disposal while we are messing with
5926 	 * it.  Once we have the reference, the map is free
5927 	 * to be diddled.  Since objects reference their
5928 	 * shadows (and copies), they will stay around as well.
5929 	 */
5930 	if (resilient_media_ref_transfer) {
5931 		/* we already have an extra reference on this object */
5932 		resilient_media_ref_transfer = false;
5933 	} else {
5934 		vm_object_reference_locked(object);
5935 	}
5936 	vm_object_paging_begin(object);
5937 
5938 	set_thread_pagein_error(cthread, 0);
5939 	error_code = 0;
5940 
5941 	result_page = VM_PAGE_NULL;
5942 	kr = vm_fault_page(object, offset, fault_type,
5943 	    (change_wiring && !wired),
5944 	    FALSE,                /* page not looked up */
5945 	    &prot, &result_page, &top_page,
5946 	    &type_of_fault,
5947 	    &error_code, map->no_zero_fill,
5948 	    fault_info);
5949 
5950 	/*
5951 	 * if kr != VM_FAULT_SUCCESS, then the paging reference
5952 	 * has been dropped and the object unlocked... the ref_count
5953 	 * is still held
5954 	 *
5955 	 * if kr == VM_FAULT_SUCCESS, then the paging reference
5956 	 * is still held along with the ref_count on the original object
5957 	 *
5958 	 *	the object is returned locked with a paging reference
5959 	 *
5960 	 *	if top_page != NULL, then it's BUSY and the
5961 	 *	object it belongs to has a paging reference
5962 	 *	but is returned unlocked
5963 	 */
5964 	if (kr != VM_FAULT_SUCCESS &&
5965 	    kr != VM_FAULT_SUCCESS_NO_VM_PAGE) {
5966 		if (kr == VM_FAULT_MEMORY_ERROR &&
5967 		    fault_info->resilient_media) {
5968 			assertf(object->internal, "object %p", object);
5969 			/*
5970 			 * This fault failed but the mapping was
5971 			 * "media resilient", so we'll retry the fault in
5972 			 * recovery mode to get a zero-filled page in the
5973 			 * top object.
5974 			 * Keep the reference on the failing object so
5975 			 * that we can check that the mapping is still
5976 			 * pointing to it when we retry the fault.
5977 			 */
5978 //                     printf("RESILIENT_MEDIA %s:%d: object %p offset 0x%llx recover from media error 0x%x kr 0x%x top_page %p result_page %p\n", __FUNCTION__, __LINE__, object, offset, error_code, kr, top_page, result_page);
5979 			assert(!resilient_media_retry); /* no double retry */
5980 			assert(resilient_media_object == VM_OBJECT_NULL);
5981 			assert(resilient_media_offset == (vm_object_offset_t)-1);
5982 			resilient_media_retry = true;
5983 			resilient_media_object = object;
5984 			resilient_media_offset = offset;
5985 //                     printf("FBDP %s:%d resilient_media_object %p offset 0x%llx kept reference\n", __FUNCTION__, __LINE__, resilient_media_object, resilient_mmedia_offset);
5986 			vm_fault_resilient_media_initiate++;
5987 			goto RetryFault;
5988 		} else {
5989 			/*
5990 			 * we didn't succeed, lose the object reference
5991 			 * immediately.
5992 			 */
5993 			vm_object_deallocate(object);
5994 			object = VM_OBJECT_NULL; /* no longer valid */
5995 		}
5996 
5997 		/*
5998 		 * See why we failed, and take corrective action.
5999 		 */
6000 		switch (kr) {
6001 		case VM_FAULT_MEMORY_SHORTAGE:
6002 			if (vm_page_wait((change_wiring) ?
6003 			    THREAD_UNINT :
6004 			    THREAD_ABORTSAFE)) {
6005 				goto RetryFault;
6006 			}
6007 			ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_FAULT_MEMORY_SHORTAGE), 0 /* arg */);
6008 			OS_FALLTHROUGH;
6009 		case VM_FAULT_INTERRUPTED:
6010 			ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_FAULT_INTERRUPTED), 0 /* arg */);
6011 			kr = KERN_ABORTED;
6012 			goto done;
6013 		case VM_FAULT_RETRY:
6014 			goto RetryFault;
6015 		case VM_FAULT_MEMORY_ERROR:
6016 			if (error_code) {
6017 				kr = error_code;
6018 			} else {
6019 				kr = KERN_MEMORY_ERROR;
6020 			}
6021 			goto done;
6022 		default:
6023 			panic("vm_fault: unexpected error 0x%x from "
6024 			    "vm_fault_page()\n", kr);
6025 		}
6026 	}
6027 	m = result_page;
6028 	m_object = NULL;
6029 
6030 	if (m != VM_PAGE_NULL) {
6031 		m_object = VM_PAGE_OBJECT(m);
6032 		assert((change_wiring && !wired) ?
6033 		    (top_page == VM_PAGE_NULL) :
6034 		    ((top_page == VM_PAGE_NULL) == (m_object == object)));
6035 	}
6036 
6037 	/*
6038 	 * What to do with the resulting page from vm_fault_page
6039 	 * if it doesn't get entered into the physical map:
6040 	 */
6041 #define RELEASE_PAGE(m)                                 \
6042 	MACRO_BEGIN                                     \
6043 	vm_page_wakeup_done(VM_PAGE_OBJECT(m), m);                            \
6044 	if ( !VM_PAGE_PAGEABLE(m)) {                    \
6045 	        vm_page_lockspin_queues();              \
6046 	        if ( !VM_PAGE_PAGEABLE(m))              \
6047 	                vm_page_activate(m);            \
6048 	        vm_page_unlock_queues();                \
6049 	}                                               \
6050 	MACRO_END
6051 
6052 
6053 	object_locks_dropped = FALSE;
6054 	/*
6055 	 * We must verify that the maps have not changed
6056 	 * since our last lookup. vm_map_verify() needs the
6057 	 * map lock (shared) but we are holding object locks.
6058 	 * So we do a try_lock() first and, if that fails, we
6059 	 * drop the object locks and go in for the map lock again.
6060 	 */
6061 	if (m != VM_PAGE_NULL) {
6062 		old_copy_object = m_object->vo_copy;
6063 		old_copy_version = m_object->vo_copy_version;
6064 	} else {
6065 		old_copy_object = VM_OBJECT_NULL;
6066 		old_copy_version = 0;
6067 	}
6068 	if (!vm_map_try_lock_read(original_map)) {
6069 		if (m != VM_PAGE_NULL) {
6070 			vm_object_unlock(m_object);
6071 		} else {
6072 			vm_object_unlock(object);
6073 		}
6074 
6075 		object_locks_dropped = TRUE;
6076 
6077 		vm_map_lock_read(original_map);
6078 	}
6079 
6080 	if ((map != original_map) || !vm_map_verify(map, &version)) {
6081 		if (object_locks_dropped == FALSE) {
6082 			if (m != VM_PAGE_NULL) {
6083 				vm_object_unlock(m_object);
6084 			} else {
6085 				vm_object_unlock(object);
6086 			}
6087 
6088 			object_locks_dropped = TRUE;
6089 		}
6090 
6091 		/*
6092 		 * no object locks are held at this point
6093 		 */
6094 		vm_object_t             retry_object;
6095 		vm_object_offset_t      retry_offset;
6096 		vm_prot_t               retry_prot;
6097 
6098 		/*
6099 		 * To avoid trying to write_lock the map while another
6100 		 * thread has it read_locked (in vm_map_pageable), we
6101 		 * do not try for write permission.  If the page is
6102 		 * still writable, we will get write permission.  If it
6103 		 * is not, or has been marked needs_copy, we enter the
6104 		 * mapping without write permission, and will merely
6105 		 * take another fault.
6106 		 */
6107 		map = original_map;
6108 
6109 		kr = vm_map_lookup_and_lock_object(&map, vaddr,
6110 		    fault_type & ~VM_PROT_WRITE,
6111 		    OBJECT_LOCK_EXCLUSIVE, &version,
6112 		    &retry_object, &retry_offset, &retry_prot,
6113 		    &wired,
6114 		    fault_info,
6115 		    &real_map,
6116 		    NULL);
6117 		pmap = real_map->pmap;
6118 
6119 		if (kr != KERN_SUCCESS) {
6120 			vm_map_unlock_read(map);
6121 
6122 			if (m != VM_PAGE_NULL) {
6123 				assert(VM_PAGE_OBJECT(m) == m_object);
6124 
6125 				/*
6126 				 * retake the lock so that
6127 				 * we can drop the paging reference
6128 				 * in vm_fault_cleanup and do the
6129 				 * vm_page_wakeup_done() in RELEASE_PAGE
6130 				 */
6131 				vm_object_lock(m_object);
6132 
6133 				RELEASE_PAGE(m);
6134 
6135 				vm_fault_cleanup(m_object, top_page);
6136 			} else {
6137 				/*
6138 				 * retake the lock so that
6139 				 * we can drop the paging reference
6140 				 * in vm_fault_cleanup
6141 				 */
6142 				vm_object_lock(object);
6143 
6144 				vm_fault_cleanup(object, top_page);
6145 			}
6146 			vm_object_deallocate(object);
6147 
6148 			if (kr == KERN_INVALID_ADDRESS) {
6149 				ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_ADDRESS_NOT_FOUND), 0 /* arg */);
6150 			}
6151 			goto done;
6152 		}
6153 		vm_object_unlock(retry_object);
6154 
6155 		if ((retry_object != object) || (retry_offset != offset)) {
6156 			vm_map_unlock_read(map);
6157 			if (real_map != map) {
6158 				vm_map_unlock(real_map);
6159 			}
6160 
6161 			if (m != VM_PAGE_NULL) {
6162 				assert(VM_PAGE_OBJECT(m) == m_object);
6163 
6164 				/*
6165 				 * retake the lock so that
6166 				 * we can drop the paging reference
6167 				 * in vm_fault_cleanup and do the
6168 				 * vm_page_wakeup_done() in RELEASE_PAGE
6169 				 */
6170 				vm_object_lock(m_object);
6171 
6172 				RELEASE_PAGE(m);
6173 
6174 				vm_fault_cleanup(m_object, top_page);
6175 			} else {
6176 				/*
6177 				 * retake the lock so that
6178 				 * we can drop the paging reference
6179 				 * in vm_fault_cleanup
6180 				 */
6181 				vm_object_lock(object);
6182 
6183 				vm_fault_cleanup(object, top_page);
6184 			}
6185 			vm_object_deallocate(object);
6186 
6187 			goto RetryFault;
6188 		}
6189 		/*
6190 		 * Check whether the protection has changed or the object
6191 		 * has been copied while we left the map unlocked.
6192 		 */
6193 		if (pmap_has_prot_policy(pmap, fault_info->pmap_options & PMAP_OPTIONS_TRANSLATED_ALLOW_EXECUTE, retry_prot)) {
6194 			/* If the pmap layer cares, pass the full set. */
6195 			prot = retry_prot;
6196 		} else {
6197 			prot &= retry_prot;
6198 		}
6199 	}
6200 
6201 	if (object_locks_dropped == TRUE) {
6202 		if (m != VM_PAGE_NULL) {
6203 			assertf(VM_PAGE_OBJECT(m) == m_object, "m=%p m_object=%p", m, m_object);
6204 			assert(VM_PAGE_OBJECT(m) != VM_OBJECT_NULL);
6205 			vm_object_lock(m_object);
6206 		} else {
6207 			vm_object_lock(object);
6208 		}
6209 
6210 		object_locks_dropped = FALSE;
6211 	}
6212 
6213 	if ((prot & VM_PROT_WRITE) &&
6214 	    m != VM_PAGE_NULL &&
6215 	    (m_object->vo_copy != old_copy_object ||
6216 	    m_object->vo_copy_version != old_copy_version)) {
6217 		/*
6218 		 * The copy object changed while the top-level object
6219 		 * was unlocked, so take away write permission.
6220 		 */
6221 		if (pmap_has_prot_policy(pmap, fault_info->pmap_options & PMAP_OPTIONS_TRANSLATED_ALLOW_EXECUTE, prot)) {
6222 			/*
6223 			 * This pmap enforces extra constraints for this set
6224 			 * of protections, so we can't change the protections.
6225 			 * This mapping should have been setup to avoid
6226 			 * copy-on-write since that requires removing write
6227 			 * access.
6228 			 */
6229 			panic("%s: pmap %p vaddr 0x%llx prot 0x%x options 0x%x m%p obj %p copyobj %p",
6230 			    __FUNCTION__, pmap, (uint64_t)vaddr, prot,
6231 			    fault_info->pmap_options,
6232 			    m, m_object, m_object->vo_copy);
6233 		}
6234 		prot &= ~VM_PROT_WRITE;
6235 	}
6236 
6237 	if (!need_copy &&
6238 	    !fault_info->no_copy_on_read &&
6239 	    m != VM_PAGE_NULL &&
6240 	    VM_PAGE_OBJECT(m) != object &&
6241 	    !VM_PAGE_OBJECT(m)->pager_trusted &&
6242 	    vm_protect_privileged_from_untrusted &&
6243 	    !VM_PAGE_OBJECT(m)->code_signed &&
6244 	    current_proc_is_privileged()) {
6245 		/*
6246 		 * We found the page we want in an "untrusted" VM object
6247 		 * down the shadow chain.  Since the target is "privileged"
6248 		 * we want to perform a copy-on-read of that page, so that the
6249 		 * mapped object gets a stable copy and does not have to
6250 		 * rely on the "untrusted" object to provide the same
6251 		 * contents if the page gets reclaimed and has to be paged
6252 		 * in again later on.
6253 		 *
6254 		 * Special case: if the mapping is executable and the untrusted
6255 		 * object is code-signed and the process is "cs_enforced", we
6256 		 * do not copy-on-read because that would break code-signing
6257 		 * enforcement expectations (an executable page must belong
6258 		 * to a code-signed object) and we can rely on code-signing
6259 		 * to re-validate the page if it gets evicted and paged back in.
6260 		 */
6261 //		printf("COPY-ON-READ %s:%d map %p vaddr 0x%llx obj %p offset 0x%llx found page %p (obj %p offset 0x%llx) UNTRUSTED -> need copy-on-read\n", __FUNCTION__, __LINE__, map, (uint64_t)vaddr, object, offset, m, VM_PAGE_OBJECT(m), m->vmp_offset);
6262 		vm_copied_on_read++;
6263 		need_copy_on_read = TRUE;
6264 		need_copy = TRUE;
6265 	} else {
6266 		need_copy_on_read = FALSE;
6267 	}
6268 
6269 	/*
6270 	 * If we want to wire down this page, but no longer have
6271 	 * adequate permissions, we must start all over.
6272 	 * If we decided to copy-on-read, we must also start all over.
6273 	 */
6274 	if ((wired && (fault_type != (prot | VM_PROT_WRITE))) ||
6275 	    need_copy_on_read) {
6276 		vm_map_unlock_read(map);
6277 		if (real_map != map) {
6278 			vm_map_unlock(real_map);
6279 		}
6280 
6281 		if (m != VM_PAGE_NULL) {
6282 			assert(VM_PAGE_OBJECT(m) == m_object);
6283 
6284 			RELEASE_PAGE(m);
6285 
6286 			vm_fault_cleanup(m_object, top_page);
6287 		} else {
6288 			vm_fault_cleanup(object, top_page);
6289 		}
6290 
6291 		vm_object_deallocate(object);
6292 
6293 		goto RetryFault;
6294 	}
6295 	if (m != VM_PAGE_NULL) {
6296 		/*
6297 		 * Put this page into the physical map.
6298 		 * We had to do the unlock above because pmap_enter
6299 		 * may cause other faults.  The page may be on
6300 		 * the pageout queues.  If the pageout daemon comes
6301 		 * across the page, it will remove it from the queues.
6302 		 */
6303 		if (fault_page_size < PAGE_SIZE) {
6304 			DEBUG4K_FAULT("map %p original %p pmap %p va 0x%llx pa 0x%llx(0x%llx+0x%llx) prot 0x%x caller_prot 0x%x\n", map, original_map, pmap, (uint64_t)vaddr, (uint64_t)((((pmap_paddr_t)VM_PAGE_GET_PHYS_PAGE(m)) << PAGE_SHIFT) + fault_phys_offset), (uint64_t)(((pmap_paddr_t)VM_PAGE_GET_PHYS_PAGE(m)) << PAGE_SHIFT), (uint64_t)fault_phys_offset, prot, caller_prot);
6305 			assertf((!(fault_phys_offset & FOURK_PAGE_MASK) &&
6306 			    fault_phys_offset < PAGE_SIZE),
6307 			    "0x%llx\n", (uint64_t)fault_phys_offset);
6308 		} else {
6309 			assertf(fault_phys_offset == 0,
6310 			    "0x%llx\n", (uint64_t)fault_phys_offset);
6311 		}
6312 		assertf(VM_PAGE_OBJECT(m) == m_object, "m=%p m_object=%p", m, m_object);
6313 		assert(VM_PAGE_OBJECT(m) != VM_OBJECT_NULL);
6314 		if (caller_pmap) {
6315 			kr = vm_fault_enter(m,
6316 			    caller_pmap,
6317 			    caller_pmap_addr,
6318 			    fault_page_size,
6319 			    fault_phys_offset,
6320 			    prot,
6321 			    caller_prot,
6322 			    wired,
6323 			    change_wiring,
6324 			    wire_tag,
6325 			    fault_info,
6326 			    NULL,
6327 			    &type_of_fault,
6328 			    &object_lock_type);
6329 		} else {
6330 			kr = vm_fault_enter(m,
6331 			    pmap,
6332 			    vaddr,
6333 			    fault_page_size,
6334 			    fault_phys_offset,
6335 			    prot,
6336 			    caller_prot,
6337 			    wired,
6338 			    change_wiring,
6339 			    wire_tag,
6340 			    fault_info,
6341 			    NULL,
6342 			    &type_of_fault,
6343 			    &object_lock_type);
6344 		}
6345 		assert(VM_PAGE_OBJECT(m) == m_object);
6346 
6347 		{
6348 			int     event_code = 0;
6349 
6350 			if (m_object->internal) {
6351 				event_code = (MACHDBG_CODE(DBG_MACH_WORKINGSET, VM_REAL_FAULT_ADDR_INTERNAL));
6352 			} else if (m_object->object_is_shared_cache) {
6353 				event_code = (MACHDBG_CODE(DBG_MACH_WORKINGSET, VM_REAL_FAULT_ADDR_SHAREDCACHE));
6354 			} else {
6355 				event_code = (MACHDBG_CODE(DBG_MACH_WORKINGSET, VM_REAL_FAULT_ADDR_EXTERNAL));
6356 			}
6357 
6358 			KDBG_RELEASE(event_code | DBG_FUNC_NONE, trace_real_vaddr, (fault_info->user_tag << 16) | (caller_prot << 8) | vm_fault_type_for_tracing(need_copy_on_read, type_of_fault), m->vmp_offset, get_current_unique_pid());
6359 			KDBG_FILTERED(MACHDBG_CODE(DBG_MACH_WORKINGSET, VM_REAL_FAULT_SLOW), get_current_unique_pid());
6360 
6361 			DTRACE_VM6(real_fault, vm_map_offset_t, real_vaddr, vm_map_offset_t, m->vmp_offset, int, event_code, int, caller_prot, int, type_of_fault, int, fault_info->user_tag);
6362 		}
6363 		if (kr != KERN_SUCCESS) {
6364 			/* abort this page fault */
6365 			vm_map_unlock_read(map);
6366 			if (real_map != map) {
6367 				vm_map_unlock(real_map);
6368 			}
6369 			vm_page_wakeup_done(m_object, m);
6370 			vm_fault_cleanup(m_object, top_page);
6371 			vm_object_deallocate(object);
6372 			goto done;
6373 		}
6374 		if (physpage_p != NULL) {
6375 			/* for vm_map_wire_and_extract() */
6376 			*physpage_p = VM_PAGE_GET_PHYS_PAGE(m);
6377 			if (prot & VM_PROT_WRITE) {
6378 				vm_object_lock_assert_exclusive(m_object);
6379 				m->vmp_dirty = TRUE;
6380 			}
6381 		}
6382 	} else {
6383 		vm_map_entry_t          entry;
6384 		vm_map_offset_t         laddr;
6385 		vm_map_offset_t         ldelta, hdelta;
6386 
6387 		/*
6388 		 * do a pmap block mapping from the physical address
6389 		 * in the object
6390 		 */
6391 
6392 		if (real_map != map) {
6393 			vm_map_unlock(real_map);
6394 		}
6395 
6396 		if (original_map != map) {
6397 			vm_map_unlock_read(map);
6398 			vm_map_lock_read(original_map);
6399 			map = original_map;
6400 		}
6401 		real_map = map;
6402 
6403 		laddr = vaddr;
6404 		hdelta = ldelta = (vm_map_offset_t)0xFFFFFFFFFFFFF000ULL;
6405 
6406 		while (vm_map_lookup_entry(map, laddr, &entry)) {
6407 			if (ldelta > (laddr - entry->vme_start)) {
6408 				ldelta = laddr - entry->vme_start;
6409 			}
6410 			if (hdelta > (entry->vme_end - laddr)) {
6411 				hdelta = entry->vme_end - laddr;
6412 			}
6413 			if (entry->is_sub_map) {
6414 				laddr = ((laddr - entry->vme_start)
6415 				    + VME_OFFSET(entry));
6416 				vm_map_lock_read(VME_SUBMAP(entry));
6417 
6418 				if (map != real_map) {
6419 					vm_map_unlock_read(map);
6420 				}
6421 				if (entry->use_pmap) {
6422 					vm_map_unlock_read(real_map);
6423 					real_map = VME_SUBMAP(entry);
6424 				}
6425 				map = VME_SUBMAP(entry);
6426 			} else {
6427 				break;
6428 			}
6429 		}
6430 
6431 		if (vm_map_lookup_entry(map, laddr, &entry) &&
6432 		    (!entry->is_sub_map) &&
6433 		    (object != VM_OBJECT_NULL) &&
6434 		    (VME_OBJECT(entry) == object)) {
6435 			uint16_t superpage;
6436 
6437 			if (!object->pager_created &&
6438 			    object->phys_contiguous &&
6439 			    VME_OFFSET(entry) == 0 &&
6440 			    (entry->vme_end - entry->vme_start == object->vo_size) &&
6441 			    VM_MAP_PAGE_ALIGNED(entry->vme_start, (object->vo_size - 1))) {
6442 				superpage = VM_MEM_SUPERPAGE;
6443 			} else {
6444 				superpage = 0;
6445 			}
6446 
6447 			if (superpage && physpage_p) {
6448 				/* for vm_map_wire_and_extract() */
6449 				*physpage_p = (ppnum_t)
6450 				    ((((vm_map_offset_t)
6451 				    object->vo_shadow_offset)
6452 				    + VME_OFFSET(entry)
6453 				    + (laddr - entry->vme_start))
6454 				    >> PAGE_SHIFT);
6455 			}
6456 
6457 			if (caller_pmap) {
6458 				/*
6459 				 * Set up a block mapped area
6460 				 */
6461 				assert((uint32_t)((ldelta + hdelta) >> fault_page_shift) == ((ldelta + hdelta) >> fault_page_shift));
6462 				kr = pmap_map_block_addr(caller_pmap,
6463 				    (addr64_t)(caller_pmap_addr - ldelta),
6464 				    (pmap_paddr_t)(((vm_map_offset_t) (object->vo_shadow_offset)) +
6465 				    VME_OFFSET(entry) + (laddr - entry->vme_start) - ldelta),
6466 				    (uint32_t)((ldelta + hdelta) >> fault_page_shift), prot,
6467 				    (VM_WIMG_MASK & (int)object->wimg_bits) | superpage, 0);
6468 
6469 				if (kr != KERN_SUCCESS) {
6470 					goto cleanup;
6471 				}
6472 			} else {
6473 				/*
6474 				 * Set up a block mapped area
6475 				 */
6476 				assert((uint32_t)((ldelta + hdelta) >> fault_page_shift) == ((ldelta + hdelta) >> fault_page_shift));
6477 				kr = pmap_map_block_addr(real_map->pmap,
6478 				    (addr64_t)(vaddr - ldelta),
6479 				    (pmap_paddr_t)(((vm_map_offset_t)(object->vo_shadow_offset)) +
6480 				    VME_OFFSET(entry) + (laddr - entry->vme_start) - ldelta),
6481 				    (uint32_t)((ldelta + hdelta) >> fault_page_shift), prot,
6482 				    (VM_WIMG_MASK & (int)object->wimg_bits) | superpage, 0);
6483 
6484 				if (kr != KERN_SUCCESS) {
6485 					goto cleanup;
6486 				}
6487 			}
6488 		}
6489 	}
6490 
6491 	/*
6492 	 * Success
6493 	 */
6494 	kr = KERN_SUCCESS;
6495 
6496 	/*
6497 	 * TODO: could most of the done cases just use cleanup?
6498 	 */
6499 cleanup:
6500 	/*
6501 	 * Unlock everything, and return
6502 	 */
6503 	vm_map_unlock_read(map);
6504 	if (real_map != map) {
6505 		vm_map_unlock(real_map);
6506 	}
6507 
6508 	if (m != VM_PAGE_NULL) {
6509 		if (__improbable(rtfault &&
6510 		    !m->vmp_realtime &&
6511 		    vm_pageout_protect_realtime)) {
6512 			vm_page_lock_queues();
6513 			if (!m->vmp_realtime) {
6514 				m->vmp_realtime = true;
6515 				vm_page_realtime_count++;
6516 			}
6517 			vm_page_unlock_queues();
6518 		}
6519 		assert(VM_PAGE_OBJECT(m) == m_object);
6520 
6521 		if (!m_object->internal && (fault_type & VM_PROT_WRITE)) {
6522 			vm_object_paging_begin(m_object);
6523 
6524 			assert(written_on_object == VM_OBJECT_NULL);
6525 			written_on_object = m_object;
6526 			written_on_pager = m_object->pager;
6527 			written_on_offset = m_object->paging_offset + m->vmp_offset;
6528 		}
6529 		vm_page_wakeup_done(m_object, m);
6530 
6531 		vm_fault_cleanup(m_object, top_page);
6532 	} else {
6533 		vm_fault_cleanup(object, top_page);
6534 	}
6535 
6536 	vm_object_deallocate(object);
6537 
6538 #undef  RELEASE_PAGE
6539 
6540 done:
6541 	thread_interrupt_level(interruptible_state);
6542 
6543 	if (resilient_media_object != VM_OBJECT_NULL) {
6544 		assert(resilient_media_retry);
6545 		assert(resilient_media_offset != (vm_object_offset_t)-1);
6546 		/* release extra reference on failed object */
6547 //             printf("FBDP %s:%d resilient_media_object %p deallocate\n", __FUNCTION__, __LINE__, resilient_media_object);
6548 		vm_object_deallocate(resilient_media_object);
6549 		resilient_media_object = VM_OBJECT_NULL;
6550 		resilient_media_offset = (vm_object_offset_t)-1;
6551 		resilient_media_retry = false;
6552 		vm_fault_resilient_media_release++;
6553 	}
6554 	assert(!resilient_media_retry);
6555 
6556 	/*
6557 	 * Only I/O throttle on faults which cause a pagein/swapin.
6558 	 */
6559 	if ((type_of_fault == DBG_PAGEIND_FAULT) || (type_of_fault == DBG_PAGEINV_FAULT) || (type_of_fault == DBG_COMPRESSOR_SWAPIN_FAULT)) {
6560 		throttle_lowpri_io(1);
6561 	} else {
6562 		if (kr == KERN_SUCCESS && type_of_fault != DBG_CACHE_HIT_FAULT && type_of_fault != DBG_GUARD_FAULT) {
6563 			if ((throttle_delay = vm_page_throttled(TRUE))) {
6564 				if (vm_debug_events) {
6565 					if (type_of_fault == DBG_COMPRESSOR_FAULT) {
6566 						VM_DEBUG_EVENT(vmf_compressordelay, DBG_VM_FAULT_COMPRESSORDELAY, DBG_FUNC_NONE, throttle_delay, 0, 0, 0);
6567 					} else if (type_of_fault == DBG_COW_FAULT) {
6568 						VM_DEBUG_EVENT(vmf_cowdelay, DBG_VM_FAULT_COWDELAY, DBG_FUNC_NONE, throttle_delay, 0, 0, 0);
6569 					} else {
6570 						VM_DEBUG_EVENT(vmf_zfdelay, DBG_VM_FAULT_ZFDELAY, DBG_FUNC_NONE, throttle_delay, 0, 0, 0);
6571 					}
6572 				}
6573 				__VM_FAULT_THROTTLE_FOR_PAGEOUT_SCAN__(throttle_delay);
6574 			}
6575 		}
6576 	}
6577 
6578 	if (written_on_object) {
6579 		vnode_pager_dirtied(written_on_pager, written_on_offset, written_on_offset + PAGE_SIZE_64);
6580 
6581 		vm_object_lock(written_on_object);
6582 		vm_object_paging_end(written_on_object);
6583 		vm_object_unlock(written_on_object);
6584 
6585 		written_on_object = VM_OBJECT_NULL;
6586 	}
6587 
6588 	if (rtfault) {
6589 		vm_record_rtfault(cthread, fstart, trace_vaddr, type_of_fault);
6590 	}
6591 
6592 	KDBG_RELEASE(
6593 		(VMDBG_CODE(DBG_VM_FAULT_INTERNAL)) | DBG_FUNC_END,
6594 		((uint64_t)trace_vaddr >> 32),
6595 		trace_vaddr,
6596 		kr,
6597 		vm_fault_type_for_tracing(need_copy_on_read, type_of_fault));
6598 
6599 	if (fault_page_size < PAGE_SIZE && kr != KERN_SUCCESS) {
6600 		DEBUG4K_FAULT("map %p original %p vaddr 0x%llx -> 0x%x\n", map, original_map, (uint64_t)trace_real_vaddr, kr);
6601 	}
6602 
6603 	return kr;
6604 }
6605 
6606 /*
6607  *	vm_fault_wire:
6608  *
6609  *	Wire down a range of virtual addresses in a map.
6610  */
6611 kern_return_t
vm_fault_wire(vm_map_t map,vm_map_entry_t entry,vm_prot_t prot,vm_tag_t wire_tag,pmap_t pmap,vm_map_offset_t pmap_addr,ppnum_t * physpage_p)6612 vm_fault_wire(
6613 	vm_map_t        map,
6614 	vm_map_entry_t  entry,
6615 	vm_prot_t       prot,
6616 	vm_tag_t        wire_tag,
6617 	pmap_t          pmap,
6618 	vm_map_offset_t pmap_addr,
6619 	ppnum_t         *physpage_p)
6620 {
6621 	vm_map_offset_t va;
6622 	vm_map_offset_t end_addr = entry->vme_end;
6623 	kern_return_t   rc;
6624 	vm_map_size_t   effective_page_size;
6625 
6626 	assert(entry->in_transition);
6627 
6628 	if (!entry->is_sub_map &&
6629 	    VME_OBJECT(entry) != VM_OBJECT_NULL &&
6630 	    VME_OBJECT(entry)->phys_contiguous) {
6631 		return KERN_SUCCESS;
6632 	}
6633 
6634 	/*
6635 	 *	Inform the physical mapping system that the
6636 	 *	range of addresses may not fault, so that
6637 	 *	page tables and such can be locked down as well.
6638 	 */
6639 
6640 	pmap_pageable(pmap, pmap_addr,
6641 	    pmap_addr + (end_addr - entry->vme_start), FALSE);
6642 
6643 	/*
6644 	 *	We simulate a fault to get the page and enter it
6645 	 *	in the physical map.
6646 	 */
6647 
6648 	effective_page_size = MIN(VM_MAP_PAGE_SIZE(map), PAGE_SIZE);
6649 	for (va = entry->vme_start;
6650 	    va < end_addr;
6651 	    va += effective_page_size) {
6652 		rc = vm_fault_wire_fast(map, va, prot, wire_tag, entry, pmap,
6653 		    pmap_addr + (va - entry->vme_start),
6654 		    physpage_p);
6655 		if (rc != KERN_SUCCESS) {
6656 			struct vm_object_fault_info fault_info = {
6657 				.interruptible = (pmap == kernel_pmap) ? THREAD_UNINT : THREAD_ABORTSAFE,
6658 				.behavior = VM_BEHAVIOR_SEQUENTIAL,
6659 			};
6660 			if (os_sub_overflow(end_addr, va, &fault_info.cluster_size)) {
6661 				fault_info.cluster_size = UPL_SIZE_MAX;
6662 			}
6663 			rc = vm_fault_internal(map, va, prot, TRUE, wire_tag,
6664 			    pmap,
6665 			    (pmap_addr +
6666 			    (va - entry->vme_start)),
6667 			    physpage_p,
6668 			    &fault_info);
6669 			DTRACE_VM2(softlock, int, 1, (uint64_t *), NULL);
6670 		}
6671 
6672 		if (rc != KERN_SUCCESS) {
6673 			struct vm_map_entry     tmp_entry = *entry;
6674 
6675 			/* unwire wired pages */
6676 			tmp_entry.vme_end = va;
6677 			vm_fault_unwire(map, &tmp_entry, FALSE,
6678 			    pmap, pmap_addr, tmp_entry.vme_end);
6679 
6680 			return rc;
6681 		}
6682 	}
6683 	return KERN_SUCCESS;
6684 }
6685 
6686 /*
6687  *	vm_fault_unwire:
6688  *
6689  *	Unwire a range of virtual addresses in a map.
6690  */
6691 void
vm_fault_unwire(vm_map_t map,vm_map_entry_t entry,boolean_t deallocate,pmap_t pmap,vm_map_offset_t pmap_addr,vm_map_offset_t end_addr)6692 vm_fault_unwire(
6693 	vm_map_t        map,
6694 	vm_map_entry_t  entry,
6695 	boolean_t       deallocate,
6696 	pmap_t          pmap,
6697 	vm_map_offset_t pmap_addr,
6698 	vm_map_offset_t end_addr)
6699 {
6700 	vm_map_offset_t va;
6701 	vm_object_t     object;
6702 	struct vm_object_fault_info fault_info = {};
6703 	unsigned int    unwired_pages;
6704 	vm_map_size_t   effective_page_size;
6705 
6706 	object = (entry->is_sub_map) ? VM_OBJECT_NULL : VME_OBJECT(entry);
6707 
6708 	/*
6709 	 * If it's marked phys_contiguous, then vm_fault_wire() didn't actually
6710 	 * do anything since such memory is wired by default.  So we don't have
6711 	 * anything to undo here.
6712 	 */
6713 
6714 	if (object != VM_OBJECT_NULL && object->phys_contiguous) {
6715 		return;
6716 	}
6717 
6718 	fault_info.interruptible = THREAD_UNINT;
6719 	fault_info.behavior = entry->behavior;
6720 	fault_info.user_tag = VME_ALIAS(entry);
6721 	if (entry->iokit_acct ||
6722 	    (!entry->is_sub_map && !entry->use_pmap)) {
6723 		fault_info.pmap_options |= PMAP_OPTIONS_ALT_ACCT;
6724 	}
6725 	fault_info.lo_offset = VME_OFFSET(entry);
6726 	fault_info.hi_offset = (entry->vme_end - entry->vme_start) + VME_OFFSET(entry);
6727 	fault_info.no_cache = entry->no_cache;
6728 	fault_info.stealth = TRUE;
6729 	if (entry->vme_xnu_user_debug) {
6730 		/*
6731 		 * Modified code-signed executable region: wired pages must
6732 		 * have been copied, so they should be XNU_USER_DEBUG rather
6733 		 * than XNU_USER_EXEC.
6734 		 */
6735 		fault_info.pmap_options |= PMAP_OPTIONS_XNU_USER_DEBUG;
6736 	}
6737 
6738 	unwired_pages = 0;
6739 
6740 	/*
6741 	 *	Since the pages are wired down, we must be able to
6742 	 *	get their mappings from the physical map system.
6743 	 */
6744 
6745 	effective_page_size = MIN(VM_MAP_PAGE_SIZE(map), PAGE_SIZE);
6746 	for (va = entry->vme_start;
6747 	    va < end_addr;
6748 	    va += effective_page_size) {
6749 		if (object == VM_OBJECT_NULL) {
6750 			if (pmap) {
6751 				pmap_change_wiring(pmap,
6752 				    pmap_addr + (va - entry->vme_start), FALSE);
6753 			}
6754 			(void) vm_fault(map, va, VM_PROT_NONE,
6755 			    TRUE, VM_KERN_MEMORY_NONE, THREAD_UNINT, pmap, pmap_addr);
6756 		} else {
6757 			vm_prot_t       prot;
6758 			vm_page_t       result_page;
6759 			vm_page_t       top_page;
6760 			vm_object_t     result_object;
6761 			vm_fault_return_t result;
6762 
6763 			/* cap cluster size at maximum UPL size */
6764 			upl_size_t cluster_size;
6765 			if (os_sub_overflow(end_addr, va, &cluster_size)) {
6766 				cluster_size = UPL_SIZE_MAX;
6767 			}
6768 			fault_info.cluster_size = cluster_size;
6769 
6770 			do {
6771 				prot = VM_PROT_NONE;
6772 
6773 				vm_object_lock(object);
6774 				vm_object_paging_begin(object);
6775 				result_page = VM_PAGE_NULL;
6776 				result = vm_fault_page(
6777 					object,
6778 					(VME_OFFSET(entry) +
6779 					(va - entry->vme_start)),
6780 					VM_PROT_NONE, TRUE,
6781 					FALSE, /* page not looked up */
6782 					&prot, &result_page, &top_page,
6783 					(int *)0,
6784 					NULL, map->no_zero_fill,
6785 					&fault_info);
6786 			} while (result == VM_FAULT_RETRY);
6787 
6788 			/*
6789 			 * If this was a mapping to a file on a device that has been forcibly
6790 			 * unmounted, then we won't get a page back from vm_fault_page().  Just
6791 			 * move on to the next one in case the remaining pages are mapped from
6792 			 * different objects.  During a forced unmount, the object is terminated
6793 			 * so the alive flag will be false if this happens.  A forced unmount will
6794 			 * will occur when an external disk is unplugged before the user does an
6795 			 * eject, so we don't want to panic in that situation.
6796 			 */
6797 
6798 			if (result == VM_FAULT_MEMORY_ERROR) {
6799 				if (!object->alive) {
6800 					continue;
6801 				}
6802 				if (!object->internal && object->pager == NULL) {
6803 					continue;
6804 				}
6805 			}
6806 
6807 			if (result == VM_FAULT_MEMORY_ERROR &&
6808 			    is_kernel_object(object)) {
6809 				/*
6810 				 * This must have been allocated with
6811 				 * KMA_KOBJECT and KMA_VAONLY and there's
6812 				 * no physical page at this offset.
6813 				 * We're done (no page to free).
6814 				 */
6815 				assert(deallocate);
6816 				continue;
6817 			}
6818 
6819 			if (result != VM_FAULT_SUCCESS) {
6820 				panic("vm_fault_unwire: failure");
6821 			}
6822 
6823 			result_object = VM_PAGE_OBJECT(result_page);
6824 
6825 			if (deallocate) {
6826 				assert(VM_PAGE_GET_PHYS_PAGE(result_page) !=
6827 				    vm_page_fictitious_addr);
6828 				pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(result_page));
6829 				if (VM_PAGE_WIRED(result_page)) {
6830 					unwired_pages++;
6831 				}
6832 				VM_PAGE_FREE(result_page);
6833 			} else {
6834 				if ((pmap) && (VM_PAGE_GET_PHYS_PAGE(result_page) != vm_page_guard_addr)) {
6835 					pmap_change_wiring(pmap,
6836 					    pmap_addr + (va - entry->vme_start), FALSE);
6837 				}
6838 
6839 
6840 				if (VM_PAGE_WIRED(result_page)) {
6841 					vm_page_lockspin_queues();
6842 					vm_page_unwire(result_page, TRUE);
6843 					vm_page_unlock_queues();
6844 					unwired_pages++;
6845 				}
6846 				if (entry->zero_wired_pages) {
6847 					pmap_zero_page(VM_PAGE_GET_PHYS_PAGE(result_page));
6848 					entry->zero_wired_pages = FALSE;
6849 				}
6850 
6851 				vm_page_wakeup_done(result_object, result_page);
6852 			}
6853 			vm_fault_cleanup(result_object, top_page);
6854 		}
6855 	}
6856 
6857 	/*
6858 	 *	Inform the physical mapping system that the range
6859 	 *	of addresses may fault, so that page tables and
6860 	 *	such may be unwired themselves.
6861 	 */
6862 
6863 	pmap_pageable(pmap, pmap_addr,
6864 	    pmap_addr + (end_addr - entry->vme_start), TRUE);
6865 
6866 	if (is_kernel_object(object)) {
6867 		/*
6868 		 * Would like to make user_tag in vm_object_fault_info
6869 		 * vm_tag_t (unsigned short) but user_tag derives its value from
6870 		 * VME_ALIAS(entry) at a few places and VME_ALIAS, in turn, casts
6871 		 * to an _unsigned int_ which is used by non-fault_info paths throughout the
6872 		 * code at many places.
6873 		 *
6874 		 * So, for now, an explicit truncation to unsigned short (vm_tag_t).
6875 		 */
6876 		assertf((fault_info.user_tag & VME_ALIAS_MASK) == fault_info.user_tag,
6877 		    "VM Tag truncated from 0x%x to 0x%x\n", fault_info.user_tag, (fault_info.user_tag & VME_ALIAS_MASK));
6878 		vm_tag_update_size((vm_tag_t) fault_info.user_tag, -ptoa_64(unwired_pages), NULL);
6879 	}
6880 }
6881 
6882 /*
6883  *	vm_fault_wire_fast:
6884  *
6885  *	Handle common case of a wire down page fault at the given address.
6886  *	If successful, the page is inserted into the associated physical map.
6887  *	The map entry is passed in to avoid the overhead of a map lookup.
6888  *
6889  *	NOTE: the given address should be truncated to the
6890  *	proper page address.
6891  *
6892  *	KERN_SUCCESS is returned if the page fault is handled; otherwise,
6893  *	a standard error specifying why the fault is fatal is returned.
6894  *
6895  *	The map in question must be referenced, and remains so.
6896  *	Caller has a read lock on the map.
6897  *
6898  *	This is a stripped version of vm_fault() for wiring pages.  Anything
6899  *	other than the common case will return KERN_FAILURE, and the caller
6900  *	is expected to call vm_fault().
6901  */
6902 static kern_return_t
vm_fault_wire_fast(__unused vm_map_t map,vm_map_offset_t va,__unused vm_prot_t caller_prot,vm_tag_t wire_tag,vm_map_entry_t entry,pmap_t pmap,vm_map_offset_t pmap_addr,ppnum_t * physpage_p)6903 vm_fault_wire_fast(
6904 	__unused vm_map_t       map,
6905 	vm_map_offset_t va,
6906 	__unused vm_prot_t       caller_prot,
6907 	vm_tag_t        wire_tag,
6908 	vm_map_entry_t  entry,
6909 	pmap_t          pmap,
6910 	vm_map_offset_t pmap_addr,
6911 	ppnum_t         *physpage_p)
6912 {
6913 	vm_object_t             object;
6914 	vm_object_offset_t      offset;
6915 	vm_page_t               m;
6916 	vm_prot_t               prot;
6917 	thread_t                thread = current_thread();
6918 	int                     type_of_fault;
6919 	kern_return_t           kr;
6920 	vm_map_size_t           fault_page_size;
6921 	vm_map_offset_t         fault_phys_offset;
6922 	struct vm_object_fault_info fault_info = {};
6923 	uint8_t                 object_lock_type = 0;
6924 
6925 	counter_inc(&vm_statistics_faults);
6926 
6927 	if (thread != THREAD_NULL) {
6928 		counter_inc(&get_threadtask(thread)->faults);
6929 	}
6930 
6931 /*
6932  *	Recovery actions
6933  */
6934 
6935 #undef  RELEASE_PAGE
6936 #define RELEASE_PAGE(m) {                               \
6937 	vm_page_wakeup_done(VM_PAGE_OBJECT(m), m);                            \
6938 	vm_page_lockspin_queues();                      \
6939 	vm_page_unwire(m, TRUE);                        \
6940 	vm_page_unlock_queues();                        \
6941 }
6942 
6943 
6944 #undef  UNLOCK_THINGS
6945 #define UNLOCK_THINGS   {                               \
6946 	vm_object_paging_end(object);                      \
6947 	vm_object_unlock(object);                          \
6948 }
6949 
6950 #undef  UNLOCK_AND_DEALLOCATE
6951 #define UNLOCK_AND_DEALLOCATE   {                       \
6952 	UNLOCK_THINGS;                                  \
6953 	vm_object_deallocate(object);                   \
6954 }
6955 /*
6956  *	Give up and have caller do things the hard way.
6957  */
6958 
6959 #define GIVE_UP {                                       \
6960 	UNLOCK_AND_DEALLOCATE;                          \
6961 	return(KERN_FAILURE);                           \
6962 }
6963 
6964 
6965 	/*
6966 	 *	If this entry is not directly to a vm_object, bail out.
6967 	 */
6968 	if (entry->is_sub_map) {
6969 		assert(physpage_p == NULL);
6970 		return KERN_FAILURE;
6971 	}
6972 
6973 	/*
6974 	 *	Find the backing store object and offset into it.
6975 	 */
6976 
6977 	object = VME_OBJECT(entry);
6978 	offset = (va - entry->vme_start) + VME_OFFSET(entry);
6979 	prot = entry->protection;
6980 
6981 	/*
6982 	 *	Make a reference to this object to prevent its
6983 	 *	disposal while we are messing with it.
6984 	 */
6985 
6986 	object_lock_type = OBJECT_LOCK_EXCLUSIVE;
6987 	vm_object_lock(object);
6988 	vm_object_reference_locked(object);
6989 	vm_object_paging_begin(object);
6990 
6991 	/*
6992 	 *	INVARIANTS (through entire routine):
6993 	 *
6994 	 *	1)	At all times, we must either have the object
6995 	 *		lock or a busy page in some object to prevent
6996 	 *		some other thread from trying to bring in
6997 	 *		the same page.
6998 	 *
6999 	 *	2)	Once we have a busy page, we must remove it from
7000 	 *		the pageout queues, so that the pageout daemon
7001 	 *		will not grab it away.
7002 	 *
7003 	 */
7004 
7005 	/*
7006 	 *	Look for page in top-level object.  If it's not there or
7007 	 *	there's something going on, give up.
7008 	 */
7009 	m = vm_page_lookup(object, vm_object_trunc_page(offset));
7010 	if ((m == VM_PAGE_NULL) || (m->vmp_busy) ||
7011 	    (m->vmp_unusual && (m->vmp_error || m->vmp_restart || m->vmp_absent))) {
7012 		GIVE_UP;
7013 	}
7014 	if (m->vmp_fictitious &&
7015 	    VM_PAGE_GET_PHYS_PAGE(m) == vm_page_guard_addr) {
7016 		/*
7017 		 * Guard pages are fictitious pages and are never
7018 		 * entered into a pmap, so let's say it's been wired...
7019 		 */
7020 		kr = KERN_SUCCESS;
7021 		goto done;
7022 	}
7023 
7024 	/*
7025 	 *	Wire the page down now.  All bail outs beyond this
7026 	 *	point must unwire the page.
7027 	 */
7028 
7029 	vm_page_lockspin_queues();
7030 	vm_page_wire(m, wire_tag, TRUE);
7031 	vm_page_unlock_queues();
7032 
7033 	/*
7034 	 *	Mark page busy for other threads.
7035 	 */
7036 	assert(!m->vmp_busy);
7037 	m->vmp_busy = TRUE;
7038 	assert(!m->vmp_absent);
7039 
7040 	/*
7041 	 *	Give up if the page is being written and there's a copy object
7042 	 */
7043 	if ((object->vo_copy != VM_OBJECT_NULL) && (prot & VM_PROT_WRITE)) {
7044 		RELEASE_PAGE(m);
7045 		GIVE_UP;
7046 	}
7047 
7048 	fault_info.user_tag = VME_ALIAS(entry);
7049 	fault_info.pmap_options = 0;
7050 	if (entry->iokit_acct ||
7051 	    (!entry->is_sub_map && !entry->use_pmap)) {
7052 		fault_info.pmap_options |= PMAP_OPTIONS_ALT_ACCT;
7053 	}
7054 	if (entry->vme_xnu_user_debug) {
7055 		/*
7056 		 * Modified code-signed executable region: wiring will
7057 		 * copy the pages, so they should be XNU_USER_DEBUG rather
7058 		 * than XNU_USER_EXEC.
7059 		 */
7060 		fault_info.pmap_options |= PMAP_OPTIONS_XNU_USER_DEBUG;
7061 	}
7062 
7063 	if (entry->translated_allow_execute) {
7064 		fault_info.pmap_options |= PMAP_OPTIONS_TRANSLATED_ALLOW_EXECUTE;
7065 	}
7066 
7067 	fault_page_size = MIN(VM_MAP_PAGE_SIZE(map), PAGE_SIZE);
7068 	fault_phys_offset = offset - vm_object_trunc_page(offset);
7069 
7070 	/*
7071 	 *	Put this page into the physical map.
7072 	 */
7073 	type_of_fault = DBG_CACHE_HIT_FAULT;
7074 	assert3p(VM_PAGE_OBJECT(m), ==, object);
7075 	kr = vm_fault_enter(m,
7076 	    pmap,
7077 	    pmap_addr,
7078 	    fault_page_size,
7079 	    fault_phys_offset,
7080 	    prot,
7081 	    prot,
7082 	    TRUE,                  /* wired */
7083 	    FALSE,                 /* change_wiring */
7084 	    wire_tag,
7085 	    &fault_info,
7086 	    NULL,
7087 	    &type_of_fault,
7088 	    &object_lock_type); /* Exclusive lock mode. Will remain unchanged.*/
7089 	if (kr != KERN_SUCCESS) {
7090 		RELEASE_PAGE(m);
7091 		GIVE_UP;
7092 	}
7093 
7094 
7095 done:
7096 	/*
7097 	 *	Unlock everything, and return
7098 	 */
7099 
7100 	if (physpage_p) {
7101 		/* for vm_map_wire_and_extract() */
7102 		if (kr == KERN_SUCCESS) {
7103 			assert3p(object, ==, VM_PAGE_OBJECT(m));
7104 			*physpage_p = VM_PAGE_GET_PHYS_PAGE(m);
7105 			if (prot & VM_PROT_WRITE) {
7106 				vm_object_lock_assert_exclusive(object);
7107 				m->vmp_dirty = TRUE;
7108 			}
7109 		} else {
7110 			*physpage_p = 0;
7111 		}
7112 	}
7113 
7114 	if (m->vmp_busy) {
7115 		vm_page_wakeup_done(object, m);
7116 	}
7117 
7118 	UNLOCK_AND_DEALLOCATE;
7119 
7120 	return kr;
7121 }
7122 
7123 /*
7124  *	Routine:	vm_fault_copy_cleanup
7125  *	Purpose:
7126  *		Release a page used by vm_fault_copy.
7127  */
7128 
7129 static void
vm_fault_copy_cleanup(vm_page_t page,vm_page_t top_page)7130 vm_fault_copy_cleanup(
7131 	vm_page_t       page,
7132 	vm_page_t       top_page)
7133 {
7134 	vm_object_t     object = VM_PAGE_OBJECT(page);
7135 
7136 	vm_object_lock(object);
7137 	vm_page_wakeup_done(object, page);
7138 	if (!VM_PAGE_PAGEABLE(page)) {
7139 		vm_page_lockspin_queues();
7140 		if (!VM_PAGE_PAGEABLE(page)) {
7141 			vm_page_activate(page);
7142 		}
7143 		vm_page_unlock_queues();
7144 	}
7145 	vm_fault_cleanup(object, top_page);
7146 }
7147 
7148 static void
vm_fault_copy_dst_cleanup(vm_page_t page)7149 vm_fault_copy_dst_cleanup(
7150 	vm_page_t       page)
7151 {
7152 	vm_object_t     object;
7153 
7154 	if (page != VM_PAGE_NULL) {
7155 		object = VM_PAGE_OBJECT(page);
7156 		vm_object_lock(object);
7157 		vm_page_lockspin_queues();
7158 		vm_page_unwire(page, TRUE);
7159 		vm_page_unlock_queues();
7160 		vm_object_paging_end(object);
7161 		vm_object_unlock(object);
7162 	}
7163 }
7164 
7165 /*
7166  *	Routine:	vm_fault_copy
7167  *
7168  *	Purpose:
7169  *		Copy pages from one virtual memory object to another --
7170  *		neither the source nor destination pages need be resident.
7171  *
7172  *		Before actually copying a page, the version associated with
7173  *		the destination address map wil be verified.
7174  *
7175  *	In/out conditions:
7176  *		The caller must hold a reference, but not a lock, to
7177  *		each of the source and destination objects and to the
7178  *		destination map.
7179  *
7180  *	Results:
7181  *		Returns KERN_SUCCESS if no errors were encountered in
7182  *		reading or writing the data.  Returns KERN_INTERRUPTED if
7183  *		the operation was interrupted (only possible if the
7184  *		"interruptible" argument is asserted).  Other return values
7185  *		indicate a permanent error in copying the data.
7186  *
7187  *		The actual amount of data copied will be returned in the
7188  *		"copy_size" argument.  In the event that the destination map
7189  *		verification failed, this amount may be less than the amount
7190  *		requested.
7191  */
7192 kern_return_t
vm_fault_copy(vm_object_t src_object,vm_object_offset_t src_offset,vm_map_size_t * copy_size,vm_object_t dst_object,vm_object_offset_t dst_offset,vm_map_t dst_map,vm_map_version_t * dst_version,int interruptible)7193 vm_fault_copy(
7194 	vm_object_t             src_object,
7195 	vm_object_offset_t      src_offset,
7196 	vm_map_size_t           *copy_size,             /* INOUT */
7197 	vm_object_t             dst_object,
7198 	vm_object_offset_t      dst_offset,
7199 	vm_map_t                dst_map,
7200 	vm_map_version_t         *dst_version,
7201 	int                     interruptible)
7202 {
7203 	vm_page_t               result_page;
7204 
7205 	vm_page_t               src_page;
7206 	vm_page_t               src_top_page;
7207 	vm_prot_t               src_prot;
7208 
7209 	vm_page_t               dst_page;
7210 	vm_page_t               dst_top_page;
7211 	vm_prot_t               dst_prot;
7212 
7213 	vm_map_size_t           amount_left;
7214 	vm_object_t             old_copy_object;
7215 	uint32_t                old_copy_version;
7216 	vm_object_t             result_page_object = NULL;
7217 	kern_return_t           error = 0;
7218 	vm_fault_return_t       result;
7219 
7220 	vm_map_size_t           part_size;
7221 	struct vm_object_fault_info fault_info_src = {};
7222 	struct vm_object_fault_info fault_info_dst = {};
7223 
7224 	/*
7225 	 * In order not to confuse the clustered pageins, align
7226 	 * the different offsets on a page boundary.
7227 	 */
7228 
7229 #define RETURN(x)                                       \
7230 	MACRO_BEGIN                                     \
7231 	*copy_size -= amount_left;                      \
7232 	MACRO_RETURN(x);                                \
7233 	MACRO_END
7234 
7235 	amount_left = *copy_size;
7236 
7237 	fault_info_src.interruptible = interruptible;
7238 	fault_info_src.behavior = VM_BEHAVIOR_SEQUENTIAL;
7239 	fault_info_src.lo_offset = vm_object_trunc_page(src_offset);
7240 	fault_info_src.hi_offset = fault_info_src.lo_offset + amount_left;
7241 	fault_info_src.stealth = TRUE;
7242 
7243 	fault_info_dst.interruptible = interruptible;
7244 	fault_info_dst.behavior = VM_BEHAVIOR_SEQUENTIAL;
7245 	fault_info_dst.lo_offset = vm_object_trunc_page(dst_offset);
7246 	fault_info_dst.hi_offset = fault_info_dst.lo_offset + amount_left;
7247 	fault_info_dst.stealth = TRUE;
7248 
7249 	do { /* while (amount_left > 0) */
7250 		/*
7251 		 * There may be a deadlock if both source and destination
7252 		 * pages are the same. To avoid this deadlock, the copy must
7253 		 * start by getting the destination page in order to apply
7254 		 * COW semantics if any.
7255 		 */
7256 
7257 RetryDestinationFault:;
7258 
7259 		dst_prot = VM_PROT_WRITE | VM_PROT_READ;
7260 
7261 		vm_object_lock(dst_object);
7262 		vm_object_paging_begin(dst_object);
7263 
7264 		/* cap cluster size at maximum UPL size */
7265 		upl_size_t cluster_size;
7266 		if (os_convert_overflow(amount_left, &cluster_size)) {
7267 			cluster_size = 0 - (upl_size_t)PAGE_SIZE;
7268 		}
7269 		fault_info_dst.cluster_size = cluster_size;
7270 
7271 		dst_page = VM_PAGE_NULL;
7272 		result = vm_fault_page(dst_object,
7273 		    vm_object_trunc_page(dst_offset),
7274 		    VM_PROT_WRITE | VM_PROT_READ,
7275 		    FALSE,
7276 		    FALSE,                    /* page not looked up */
7277 		    &dst_prot, &dst_page, &dst_top_page,
7278 		    (int *)0,
7279 		    &error,
7280 		    dst_map->no_zero_fill,
7281 		    &fault_info_dst);
7282 		switch (result) {
7283 		case VM_FAULT_SUCCESS:
7284 			break;
7285 		case VM_FAULT_RETRY:
7286 			goto RetryDestinationFault;
7287 		case VM_FAULT_MEMORY_SHORTAGE:
7288 			if (vm_page_wait(interruptible)) {
7289 				goto RetryDestinationFault;
7290 			}
7291 			ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_FAULT_COPY_MEMORY_SHORTAGE), 0 /* arg */);
7292 			OS_FALLTHROUGH;
7293 		case VM_FAULT_INTERRUPTED:
7294 			RETURN(MACH_SEND_INTERRUPTED);
7295 		case VM_FAULT_SUCCESS_NO_VM_PAGE:
7296 			/* success but no VM page: fail the copy */
7297 			vm_object_paging_end(dst_object);
7298 			vm_object_unlock(dst_object);
7299 			OS_FALLTHROUGH;
7300 		case VM_FAULT_MEMORY_ERROR:
7301 			if (error) {
7302 				return error;
7303 			} else {
7304 				return KERN_MEMORY_ERROR;
7305 			}
7306 		default:
7307 			panic("vm_fault_copy: unexpected error 0x%x from "
7308 			    "vm_fault_page()\n", result);
7309 		}
7310 		assert((dst_prot & VM_PROT_WRITE) != VM_PROT_NONE);
7311 
7312 		assert(dst_object == VM_PAGE_OBJECT(dst_page));
7313 		old_copy_object = dst_object->vo_copy;
7314 		old_copy_version = dst_object->vo_copy_version;
7315 
7316 		/*
7317 		 * There exists the possiblity that the source and
7318 		 * destination page are the same.  But we can't
7319 		 * easily determine that now.  If they are the
7320 		 * same, the call to vm_fault_page() for the
7321 		 * destination page will deadlock.  To prevent this we
7322 		 * wire the page so we can drop busy without having
7323 		 * the page daemon steal the page.  We clean up the
7324 		 * top page  but keep the paging reference on the object
7325 		 * holding the dest page so it doesn't go away.
7326 		 */
7327 
7328 		vm_page_lockspin_queues();
7329 		vm_page_wire(dst_page, VM_KERN_MEMORY_OSFMK, TRUE);
7330 		vm_page_unlock_queues();
7331 		vm_page_wakeup_done(dst_object, dst_page);
7332 		vm_object_unlock(dst_object);
7333 
7334 		if (dst_top_page != VM_PAGE_NULL) {
7335 			vm_object_lock(dst_object);
7336 			VM_PAGE_FREE(dst_top_page);
7337 			vm_object_paging_end(dst_object);
7338 			vm_object_unlock(dst_object);
7339 		}
7340 
7341 RetrySourceFault:;
7342 
7343 		if (src_object == VM_OBJECT_NULL) {
7344 			/*
7345 			 *	No source object.  We will just
7346 			 *	zero-fill the page in dst_object.
7347 			 */
7348 			src_page = VM_PAGE_NULL;
7349 			result_page = VM_PAGE_NULL;
7350 		} else {
7351 			vm_object_lock(src_object);
7352 			src_page = vm_page_lookup(src_object,
7353 			    vm_object_trunc_page(src_offset));
7354 			if (src_page == dst_page) {
7355 				src_prot = dst_prot;
7356 				result_page = VM_PAGE_NULL;
7357 			} else {
7358 				src_prot = VM_PROT_READ;
7359 				vm_object_paging_begin(src_object);
7360 
7361 				/* cap cluster size at maximum UPL size */
7362 				if (os_convert_overflow(amount_left, &cluster_size)) {
7363 					cluster_size = 0 - (upl_size_t)PAGE_SIZE;
7364 				}
7365 				fault_info_src.cluster_size = cluster_size;
7366 
7367 				result_page = VM_PAGE_NULL;
7368 				result = vm_fault_page(
7369 					src_object,
7370 					vm_object_trunc_page(src_offset),
7371 					VM_PROT_READ, FALSE,
7372 					FALSE, /* page not looked up */
7373 					&src_prot,
7374 					&result_page, &src_top_page,
7375 					(int *)0, &error, FALSE,
7376 					&fault_info_src);
7377 
7378 				switch (result) {
7379 				case VM_FAULT_SUCCESS:
7380 					break;
7381 				case VM_FAULT_RETRY:
7382 					goto RetrySourceFault;
7383 				case VM_FAULT_MEMORY_SHORTAGE:
7384 					if (vm_page_wait(interruptible)) {
7385 						goto RetrySourceFault;
7386 					}
7387 					OS_FALLTHROUGH;
7388 				case VM_FAULT_INTERRUPTED:
7389 					vm_fault_copy_dst_cleanup(dst_page);
7390 					RETURN(MACH_SEND_INTERRUPTED);
7391 				case VM_FAULT_SUCCESS_NO_VM_PAGE:
7392 					/* success but no VM page: fail */
7393 					vm_object_paging_end(src_object);
7394 					vm_object_unlock(src_object);
7395 					OS_FALLTHROUGH;
7396 				case VM_FAULT_MEMORY_ERROR:
7397 					vm_fault_copy_dst_cleanup(dst_page);
7398 					if (error) {
7399 						return error;
7400 					} else {
7401 						return KERN_MEMORY_ERROR;
7402 					}
7403 				default:
7404 					panic("vm_fault_copy(2): unexpected "
7405 					    "error 0x%x from "
7406 					    "vm_fault_page()\n", result);
7407 				}
7408 
7409 				result_page_object = VM_PAGE_OBJECT(result_page);
7410 				assert((src_top_page == VM_PAGE_NULL) ==
7411 				    (result_page_object == src_object));
7412 			}
7413 			assert((src_prot & VM_PROT_READ) != VM_PROT_NONE);
7414 			vm_object_unlock(result_page_object);
7415 		}
7416 
7417 		vm_map_lock_read(dst_map);
7418 
7419 		if (!vm_map_verify(dst_map, dst_version)) {
7420 			vm_map_unlock_read(dst_map);
7421 			if (result_page != VM_PAGE_NULL && src_page != dst_page) {
7422 				vm_fault_copy_cleanup(result_page, src_top_page);
7423 			}
7424 			vm_fault_copy_dst_cleanup(dst_page);
7425 			break;
7426 		}
7427 		assert(dst_object == VM_PAGE_OBJECT(dst_page));
7428 
7429 		vm_object_lock(dst_object);
7430 
7431 		if ((dst_object->vo_copy != old_copy_object ||
7432 		    dst_object->vo_copy_version != old_copy_version)) {
7433 			vm_object_unlock(dst_object);
7434 			vm_map_unlock_read(dst_map);
7435 			if (result_page != VM_PAGE_NULL && src_page != dst_page) {
7436 				vm_fault_copy_cleanup(result_page, src_top_page);
7437 			}
7438 			vm_fault_copy_dst_cleanup(dst_page);
7439 			break;
7440 		}
7441 		vm_object_unlock(dst_object);
7442 
7443 		/*
7444 		 *	Copy the page, and note that it is dirty
7445 		 *	immediately.
7446 		 */
7447 
7448 		if (!page_aligned(src_offset) ||
7449 		    !page_aligned(dst_offset) ||
7450 		    !page_aligned(amount_left)) {
7451 			vm_object_offset_t      src_po,
7452 			    dst_po;
7453 
7454 			src_po = src_offset - vm_object_trunc_page(src_offset);
7455 			dst_po = dst_offset - vm_object_trunc_page(dst_offset);
7456 
7457 			if (dst_po > src_po) {
7458 				part_size = PAGE_SIZE - dst_po;
7459 			} else {
7460 				part_size = PAGE_SIZE - src_po;
7461 			}
7462 			if (part_size > (amount_left)) {
7463 				part_size = amount_left;
7464 			}
7465 
7466 			if (result_page == VM_PAGE_NULL) {
7467 				assert((vm_offset_t) dst_po == dst_po);
7468 				assert((vm_size_t) part_size == part_size);
7469 				vm_page_part_zero_fill(dst_page,
7470 				    (vm_offset_t) dst_po,
7471 				    (vm_size_t) part_size);
7472 			} else {
7473 				assert((vm_offset_t) src_po == src_po);
7474 				assert((vm_offset_t) dst_po == dst_po);
7475 				assert((vm_size_t) part_size == part_size);
7476 				vm_page_part_copy(result_page,
7477 				    (vm_offset_t) src_po,
7478 				    dst_page,
7479 				    (vm_offset_t) dst_po,
7480 				    (vm_size_t)part_size);
7481 				if (!dst_page->vmp_dirty) {
7482 					vm_object_lock(dst_object);
7483 					SET_PAGE_DIRTY(dst_page, TRUE);
7484 					vm_object_unlock(dst_object);
7485 				}
7486 			}
7487 		} else {
7488 			part_size = PAGE_SIZE;
7489 
7490 			if (result_page == VM_PAGE_NULL) {
7491 				vm_page_zero_fill(dst_page);
7492 			} else {
7493 				vm_object_lock(result_page_object);
7494 				vm_page_copy(result_page, dst_page);
7495 				vm_object_unlock(result_page_object);
7496 
7497 				if (!dst_page->vmp_dirty) {
7498 					vm_object_lock(dst_object);
7499 					SET_PAGE_DIRTY(dst_page, TRUE);
7500 					vm_object_unlock(dst_object);
7501 				}
7502 			}
7503 		}
7504 
7505 		/*
7506 		 *	Unlock everything, and return
7507 		 */
7508 
7509 		vm_map_unlock_read(dst_map);
7510 
7511 		if (result_page != VM_PAGE_NULL && src_page != dst_page) {
7512 			vm_fault_copy_cleanup(result_page, src_top_page);
7513 		}
7514 		vm_fault_copy_dst_cleanup(dst_page);
7515 
7516 		amount_left -= part_size;
7517 		src_offset += part_size;
7518 		dst_offset += part_size;
7519 	} while (amount_left > 0);
7520 
7521 	RETURN(KERN_SUCCESS);
7522 #undef  RETURN
7523 
7524 	/*NOTREACHED*/
7525 }
7526 
7527 #if     VM_FAULT_CLASSIFY
7528 /*
7529  *	Temporary statistics gathering support.
7530  */
7531 
7532 /*
7533  *	Statistics arrays:
7534  */
7535 #define VM_FAULT_TYPES_MAX      5
7536 #define VM_FAULT_LEVEL_MAX      8
7537 
7538 int     vm_fault_stats[VM_FAULT_TYPES_MAX][VM_FAULT_LEVEL_MAX];
7539 
7540 #define VM_FAULT_TYPE_ZERO_FILL 0
7541 #define VM_FAULT_TYPE_MAP_IN    1
7542 #define VM_FAULT_TYPE_PAGER     2
7543 #define VM_FAULT_TYPE_COPY      3
7544 #define VM_FAULT_TYPE_OTHER     4
7545 
7546 
7547 void
vm_fault_classify(vm_object_t object,vm_object_offset_t offset,vm_prot_t fault_type)7548 vm_fault_classify(vm_object_t           object,
7549     vm_object_offset_t    offset,
7550     vm_prot_t             fault_type)
7551 {
7552 	int             type, level = 0;
7553 	vm_page_t       m;
7554 
7555 	while (TRUE) {
7556 		m = vm_page_lookup(object, offset);
7557 		if (m != VM_PAGE_NULL) {
7558 			if (m->vmp_busy || m->vmp_error || m->vmp_restart || m->vmp_absent) {
7559 				type = VM_FAULT_TYPE_OTHER;
7560 				break;
7561 			}
7562 			if (((fault_type & VM_PROT_WRITE) == 0) ||
7563 			    ((level == 0) && object->vo_copy == VM_OBJECT_NULL)) {
7564 				type = VM_FAULT_TYPE_MAP_IN;
7565 				break;
7566 			}
7567 			type = VM_FAULT_TYPE_COPY;
7568 			break;
7569 		} else {
7570 			if (object->pager_created) {
7571 				type = VM_FAULT_TYPE_PAGER;
7572 				break;
7573 			}
7574 			if (object->shadow == VM_OBJECT_NULL) {
7575 				type = VM_FAULT_TYPE_ZERO_FILL;
7576 				break;
7577 			}
7578 
7579 			offset += object->vo_shadow_offset;
7580 			object = object->shadow;
7581 			level++;
7582 			continue;
7583 		}
7584 	}
7585 
7586 	if (level > VM_FAULT_LEVEL_MAX) {
7587 		level = VM_FAULT_LEVEL_MAX;
7588 	}
7589 
7590 	vm_fault_stats[type][level] += 1;
7591 
7592 	return;
7593 }
7594 
7595 /* cleanup routine to call from debugger */
7596 
7597 void
vm_fault_classify_init(void)7598 vm_fault_classify_init(void)
7599 {
7600 	int type, level;
7601 
7602 	for (type = 0; type < VM_FAULT_TYPES_MAX; type++) {
7603 		for (level = 0; level < VM_FAULT_LEVEL_MAX; level++) {
7604 			vm_fault_stats[type][level] = 0;
7605 		}
7606 	}
7607 
7608 	return;
7609 }
7610 #endif  /* VM_FAULT_CLASSIFY */
7611 
7612 vm_offset_t
kdp_lightweight_fault(vm_map_t map,vm_offset_t cur_target_addr,bool multi_cpu)7613 kdp_lightweight_fault(vm_map_t map, vm_offset_t cur_target_addr, bool multi_cpu)
7614 {
7615 	vm_map_entry_t  entry;
7616 	vm_object_t     object;
7617 	vm_offset_t     object_offset;
7618 	vm_page_t       m;
7619 	int             compressor_external_state, compressed_count_delta;
7620 	vm_compressor_options_t             compressor_flags = (C_DONT_BLOCK | C_KEEP | C_KDP);
7621 	int             my_fault_type = VM_PROT_READ;
7622 	kern_return_t   kr;
7623 	int effective_page_mask, effective_page_size;
7624 	int             my_cpu_no = cpu_number();
7625 	ppnum_t         decomp_ppnum;
7626 	addr64_t        decomp_paddr;
7627 
7628 	if (multi_cpu) {
7629 		compressor_flags |= C_KDP_MULTICPU;
7630 	}
7631 
7632 	if (VM_MAP_PAGE_SHIFT(map) < PAGE_SHIFT) {
7633 		effective_page_mask = VM_MAP_PAGE_MASK(map);
7634 		effective_page_size = VM_MAP_PAGE_SIZE(map);
7635 	} else {
7636 		effective_page_mask = PAGE_MASK;
7637 		effective_page_size = PAGE_SIZE;
7638 	}
7639 
7640 	if (not_in_kdp) {
7641 		panic("kdp_lightweight_fault called from outside of debugger context");
7642 	}
7643 
7644 	assert(map != VM_MAP_NULL);
7645 
7646 	assert((cur_target_addr & effective_page_mask) == 0);
7647 	if ((cur_target_addr & effective_page_mask) != 0) {
7648 		return 0;
7649 	}
7650 
7651 	if (kdp_lck_rw_lock_is_acquired_exclusive(&map->lock)) {
7652 		return 0;
7653 	}
7654 
7655 	if (!vm_map_lookup_entry(map, cur_target_addr, &entry)) {
7656 		return 0;
7657 	}
7658 
7659 	if (entry->is_sub_map) {
7660 		return 0;
7661 	}
7662 
7663 	object = VME_OBJECT(entry);
7664 	if (object == VM_OBJECT_NULL) {
7665 		return 0;
7666 	}
7667 
7668 	object_offset = cur_target_addr - entry->vme_start + VME_OFFSET(entry);
7669 
7670 	while (TRUE) {
7671 		if (kdp_lck_rw_lock_is_acquired_exclusive(&object->Lock)) {
7672 			return 0;
7673 		}
7674 
7675 		if (object->pager_created && (object->paging_in_progress ||
7676 		    object->activity_in_progress)) {
7677 			return 0;
7678 		}
7679 
7680 		m = kdp_vm_page_lookup(object, vm_object_trunc_page(object_offset));
7681 
7682 		if (m != VM_PAGE_NULL) {
7683 			if ((object->wimg_bits & VM_WIMG_MASK) != VM_WIMG_DEFAULT) {
7684 				return 0;
7685 			}
7686 
7687 			if (m->vmp_laundry || m->vmp_busy || m->vmp_free_when_done || m->vmp_absent || VMP_ERROR_GET(m) || m->vmp_cleaning ||
7688 			    m->vmp_overwriting || m->vmp_restart || m->vmp_unusual) {
7689 				return 0;
7690 			}
7691 
7692 			assert(!m->vmp_private);
7693 			if (m->vmp_private) {
7694 				return 0;
7695 			}
7696 
7697 			assert(!m->vmp_fictitious);
7698 			if (m->vmp_fictitious) {
7699 				return 0;
7700 			}
7701 
7702 			assert(m->vmp_q_state != VM_PAGE_USED_BY_COMPRESSOR);
7703 			if (m->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) {
7704 				return 0;
7705 			}
7706 
7707 			return ptoa(VM_PAGE_GET_PHYS_PAGE(m));
7708 		}
7709 
7710 		compressor_external_state = VM_EXTERNAL_STATE_UNKNOWN;
7711 
7712 		if (multi_cpu) {
7713 			assert(vm_compressor_kdp_state.kc_decompressed_pages_ppnum != NULL);
7714 			assert(vm_compressor_kdp_state.kc_decompressed_pages_paddr != NULL);
7715 			decomp_ppnum = vm_compressor_kdp_state.kc_decompressed_pages_ppnum[my_cpu_no];
7716 			decomp_paddr = vm_compressor_kdp_state.kc_decompressed_pages_paddr[my_cpu_no];
7717 		} else {
7718 			decomp_ppnum = vm_compressor_kdp_state.kc_panic_decompressed_page_ppnum;
7719 			decomp_paddr = vm_compressor_kdp_state.kc_panic_decompressed_page_paddr;
7720 		}
7721 
7722 		if (object->pager_created && MUST_ASK_PAGER(object, object_offset, compressor_external_state)) {
7723 			if (compressor_external_state == VM_EXTERNAL_STATE_EXISTS) {
7724 				kr = vm_compressor_pager_get(object->pager,
7725 				    vm_object_trunc_page(object_offset + object->paging_offset),
7726 				    decomp_ppnum, &my_fault_type,
7727 				    compressor_flags, &compressed_count_delta);
7728 				if (kr == KERN_SUCCESS) {
7729 					return decomp_paddr;
7730 				} else {
7731 					return 0;
7732 				}
7733 			}
7734 		}
7735 
7736 		if (object->shadow == VM_OBJECT_NULL) {
7737 			return 0;
7738 		}
7739 
7740 		object_offset += object->vo_shadow_offset;
7741 		object = object->shadow;
7742 	}
7743 }
7744 
7745 /*
7746  * vm_page_validate_cs_fast():
7747  * Performs a few quick checks to determine if the page's code signature
7748  * really needs to be fully validated.  It could:
7749  *	1. have been modified (i.e. automatically tainted),
7750  *	2. have already been validated,
7751  *	3. have already been found to be tainted,
7752  *	4. no longer have a backing store.
7753  * Returns FALSE if the page needs to be fully validated.
7754  */
7755 static boolean_t
vm_page_validate_cs_fast(vm_page_t page,vm_map_size_t fault_page_size,vm_map_offset_t fault_phys_offset)7756 vm_page_validate_cs_fast(
7757 	vm_page_t       page,
7758 	vm_map_size_t   fault_page_size,
7759 	vm_map_offset_t fault_phys_offset)
7760 {
7761 	vm_object_t     object;
7762 
7763 	object = VM_PAGE_OBJECT(page);
7764 	vm_object_lock_assert_held(object);
7765 
7766 	if (page->vmp_wpmapped &&
7767 	    !VMP_CS_TAINTED(page, fault_page_size, fault_phys_offset)) {
7768 		/*
7769 		 * This page was mapped for "write" access sometime in the
7770 		 * past and could still be modifiable in the future.
7771 		 * Consider it tainted.
7772 		 * [ If the page was already found to be "tainted", no
7773 		 * need to re-validate. ]
7774 		 */
7775 		vm_object_lock_assert_exclusive(object);
7776 		VMP_CS_SET_VALIDATED(page, fault_page_size, fault_phys_offset, TRUE);
7777 		VMP_CS_SET_TAINTED(page, fault_page_size, fault_phys_offset, TRUE);
7778 		if (cs_debug) {
7779 			printf("CODESIGNING: %s: "
7780 			    "page %p obj %p off 0x%llx "
7781 			    "was modified\n",
7782 			    __FUNCTION__,
7783 			    page, object, page->vmp_offset);
7784 		}
7785 		vm_cs_validated_dirtied++;
7786 	}
7787 
7788 	if (VMP_CS_VALIDATED(page, fault_page_size, fault_phys_offset) ||
7789 	    VMP_CS_TAINTED(page, fault_page_size, fault_phys_offset)) {
7790 		return TRUE;
7791 	}
7792 	vm_object_lock_assert_exclusive(object);
7793 
7794 #if CHECK_CS_VALIDATION_BITMAP
7795 	kern_return_t kr;
7796 
7797 	kr = vnode_pager_cs_check_validation_bitmap(
7798 		object->pager,
7799 		page->vmp_offset + object->paging_offset,
7800 		CS_BITMAP_CHECK);
7801 	if (kr == KERN_SUCCESS) {
7802 		page->vmp_cs_validated = VMP_CS_ALL_TRUE;
7803 		page->vmp_cs_tainted = VMP_CS_ALL_FALSE;
7804 		vm_cs_bitmap_validated++;
7805 		return TRUE;
7806 	}
7807 #endif /* CHECK_CS_VALIDATION_BITMAP */
7808 
7809 	if (!object->alive || object->terminating || object->pager == NULL) {
7810 		/*
7811 		 * The object is terminating and we don't have its pager
7812 		 * so we can't validate the data...
7813 		 */
7814 		return TRUE;
7815 	}
7816 
7817 	/* we need to really validate this page */
7818 	vm_object_lock_assert_exclusive(object);
7819 	return FALSE;
7820 }
7821 
7822 void
vm_page_validate_cs_mapped_slow(vm_page_t page,const void * kaddr)7823 vm_page_validate_cs_mapped_slow(
7824 	vm_page_t       page,
7825 	const void      *kaddr)
7826 {
7827 	vm_object_t             object;
7828 	memory_object_offset_t  mo_offset;
7829 	memory_object_t         pager;
7830 	struct vnode            *vnode;
7831 	int                     validated, tainted, nx;
7832 
7833 	assert(page->vmp_busy);
7834 	object = VM_PAGE_OBJECT(page);
7835 	vm_object_lock_assert_exclusive(object);
7836 
7837 	vm_cs_validates++;
7838 
7839 	/*
7840 	 * Since we get here to validate a page that was brought in by
7841 	 * the pager, we know that this pager is all setup and ready
7842 	 * by now.
7843 	 */
7844 	assert(object->code_signed);
7845 	assert(!object->internal);
7846 	assert(object->pager != NULL);
7847 	assert(object->pager_ready);
7848 
7849 	pager = object->pager;
7850 	assert(object->paging_in_progress);
7851 	vnode = vnode_pager_lookup_vnode(pager);
7852 	mo_offset = page->vmp_offset + object->paging_offset;
7853 
7854 	/* verify the SHA1 hash for this page */
7855 	validated = 0;
7856 	tainted = 0;
7857 	nx = 0;
7858 	cs_validate_page(vnode,
7859 	    pager,
7860 	    mo_offset,
7861 	    (const void *)((const char *)kaddr),
7862 	    &validated,
7863 	    &tainted,
7864 	    &nx);
7865 
7866 	page->vmp_cs_validated |= validated;
7867 	page->vmp_cs_tainted |= tainted;
7868 	page->vmp_cs_nx |= nx;
7869 
7870 #if CHECK_CS_VALIDATION_BITMAP
7871 	if (page->vmp_cs_validated == VMP_CS_ALL_TRUE &&
7872 	    page->vmp_cs_tainted == VMP_CS_ALL_FALSE) {
7873 		vnode_pager_cs_check_validation_bitmap(object->pager,
7874 		    mo_offset,
7875 		    CS_BITMAP_SET);
7876 	}
7877 #endif /* CHECK_CS_VALIDATION_BITMAP */
7878 }
7879 
7880 void
vm_page_validate_cs_mapped(vm_page_t page,vm_map_size_t fault_page_size,vm_map_offset_t fault_phys_offset,const void * kaddr)7881 vm_page_validate_cs_mapped(
7882 	vm_page_t       page,
7883 	vm_map_size_t   fault_page_size,
7884 	vm_map_offset_t fault_phys_offset,
7885 	const void      *kaddr)
7886 {
7887 	if (!vm_page_validate_cs_fast(page, fault_page_size, fault_phys_offset)) {
7888 		vm_page_validate_cs_mapped_slow(page, kaddr);
7889 	}
7890 }
7891 
7892 static void
vm_page_map_and_validate_cs(vm_object_t object,vm_page_t page)7893 vm_page_map_and_validate_cs(
7894 	vm_object_t     object,
7895 	vm_page_t       page)
7896 {
7897 	vm_object_offset_t      offset;
7898 	vm_map_offset_t         koffset;
7899 	vm_map_size_t           ksize;
7900 	vm_offset_t             kaddr;
7901 	kern_return_t           kr;
7902 	boolean_t               busy_page;
7903 	boolean_t               need_unmap;
7904 
7905 	vm_object_lock_assert_exclusive(object);
7906 
7907 	assert(object->code_signed);
7908 	offset = page->vmp_offset;
7909 
7910 	busy_page = page->vmp_busy;
7911 	if (!busy_page) {
7912 		/* keep page busy while we map (and unlock) the VM object */
7913 		page->vmp_busy = TRUE;
7914 	}
7915 
7916 	/*
7917 	 * Take a paging reference on the VM object
7918 	 * to protect it from collapse or bypass,
7919 	 * and keep it from disappearing too.
7920 	 */
7921 	vm_object_paging_begin(object);
7922 
7923 	/* map the page in the kernel address space */
7924 	ksize = PAGE_SIZE_64;
7925 	koffset = 0;
7926 	need_unmap = FALSE;
7927 	kr = vm_paging_map_object(page,
7928 	    object,
7929 	    offset,
7930 	    VM_PROT_READ,
7931 	    FALSE,                       /* can't unlock object ! */
7932 	    &ksize,
7933 	    &koffset,
7934 	    &need_unmap);
7935 	if (kr != KERN_SUCCESS) {
7936 		panic("%s: could not map page: 0x%x", __FUNCTION__, kr);
7937 	}
7938 	kaddr = CAST_DOWN(vm_offset_t, koffset);
7939 
7940 	/* validate the mapped page */
7941 	vm_page_validate_cs_mapped_slow(page, (const void *) kaddr);
7942 
7943 	assert(page->vmp_busy);
7944 	assert(object == VM_PAGE_OBJECT(page));
7945 	vm_object_lock_assert_exclusive(object);
7946 
7947 	if (!busy_page) {
7948 		vm_page_wakeup_done(object, page);
7949 	}
7950 	if (need_unmap) {
7951 		/* unmap the map from the kernel address space */
7952 		vm_paging_unmap_object(object, koffset, koffset + ksize);
7953 		koffset = 0;
7954 		ksize = 0;
7955 		kaddr = 0;
7956 	}
7957 	vm_object_paging_end(object);
7958 }
7959 
7960 void
vm_page_validate_cs(vm_page_t page,vm_map_size_t fault_page_size,vm_map_offset_t fault_phys_offset)7961 vm_page_validate_cs(
7962 	vm_page_t       page,
7963 	vm_map_size_t   fault_page_size,
7964 	vm_map_offset_t fault_phys_offset)
7965 {
7966 	vm_object_t             object;
7967 
7968 	object = VM_PAGE_OBJECT(page);
7969 	vm_object_lock_assert_held(object);
7970 
7971 	if (vm_page_validate_cs_fast(page, fault_page_size, fault_phys_offset)) {
7972 		return;
7973 	}
7974 	vm_page_map_and_validate_cs(object, page);
7975 }
7976 
7977 void
vm_page_validate_cs_mapped_chunk(vm_page_t page,const void * kaddr,vm_offset_t chunk_offset,vm_size_t chunk_size,boolean_t * validated_p,unsigned * tainted_p)7978 vm_page_validate_cs_mapped_chunk(
7979 	vm_page_t       page,
7980 	const void      *kaddr,
7981 	vm_offset_t     chunk_offset,
7982 	vm_size_t       chunk_size,
7983 	boolean_t       *validated_p,
7984 	unsigned        *tainted_p)
7985 {
7986 	vm_object_t             object;
7987 	vm_object_offset_t      offset, offset_in_page;
7988 	memory_object_t         pager;
7989 	struct vnode            *vnode;
7990 	boolean_t               validated;
7991 	unsigned                tainted;
7992 
7993 	*validated_p = FALSE;
7994 	*tainted_p = 0;
7995 
7996 	assert(page->vmp_busy);
7997 	object = VM_PAGE_OBJECT(page);
7998 	vm_object_lock_assert_exclusive(object);
7999 
8000 	assert(object->code_signed);
8001 	offset = page->vmp_offset;
8002 
8003 	if (!object->alive || object->terminating || object->pager == NULL) {
8004 		/*
8005 		 * The object is terminating and we don't have its pager
8006 		 * so we can't validate the data...
8007 		 */
8008 		return;
8009 	}
8010 	/*
8011 	 * Since we get here to validate a page that was brought in by
8012 	 * the pager, we know that this pager is all setup and ready
8013 	 * by now.
8014 	 */
8015 	assert(!object->internal);
8016 	assert(object->pager != NULL);
8017 	assert(object->pager_ready);
8018 
8019 	pager = object->pager;
8020 	assert(object->paging_in_progress);
8021 	vnode = vnode_pager_lookup_vnode(pager);
8022 
8023 	/* verify the signature for this chunk */
8024 	offset_in_page = chunk_offset;
8025 	assert(offset_in_page < PAGE_SIZE);
8026 
8027 	tainted = 0;
8028 	validated = cs_validate_range(vnode,
8029 	    pager,
8030 	    (object->paging_offset +
8031 	    offset +
8032 	    offset_in_page),
8033 	    (const void *)((const char *)kaddr
8034 	    + offset_in_page),
8035 	    chunk_size,
8036 	    &tainted);
8037 	if (validated) {
8038 		*validated_p = TRUE;
8039 	}
8040 	if (tainted) {
8041 		*tainted_p = tainted;
8042 	}
8043 }
8044 
8045 static void
vm_rtfrecord_lock(void)8046 vm_rtfrecord_lock(void)
8047 {
8048 	lck_spin_lock(&vm_rtfr_slock);
8049 }
8050 
8051 static void
vm_rtfrecord_unlock(void)8052 vm_rtfrecord_unlock(void)
8053 {
8054 	lck_spin_unlock(&vm_rtfr_slock);
8055 }
8056 
8057 unsigned int
vmrtfaultinfo_bufsz(void)8058 vmrtfaultinfo_bufsz(void)
8059 {
8060 	return vmrtf_num_records * sizeof(vm_rtfault_record_t);
8061 }
8062 
8063 #include <kern/backtrace.h>
8064 
8065 __attribute__((noinline))
8066 static void
vm_record_rtfault(thread_t cthread,uint64_t fstart,vm_map_offset_t fault_vaddr,int type_of_fault)8067 vm_record_rtfault(thread_t cthread, uint64_t fstart, vm_map_offset_t fault_vaddr, int type_of_fault)
8068 {
8069 	uint64_t fend = mach_continuous_time();
8070 
8071 	uint64_t cfpc = 0;
8072 	uint64_t ctid = cthread->thread_id;
8073 	uint64_t cupid = get_current_unique_pid();
8074 
8075 	uintptr_t bpc = 0;
8076 	errno_t btr = 0;
8077 
8078 	/*
8079 	 * Capture a single-frame backtrace.  This extracts just the program
8080 	 * counter at the point of the fault, and should not use copyin to get
8081 	 * Rosetta save state.
8082 	 */
8083 	struct backtrace_control ctl = {
8084 		.btc_user_thread = cthread,
8085 		.btc_user_copy = backtrace_user_copy_error,
8086 	};
8087 	unsigned int bfrs = backtrace_user(&bpc, 1U, &ctl, NULL);
8088 	if ((btr == 0) && (bfrs > 0)) {
8089 		cfpc = bpc;
8090 	}
8091 
8092 	assert((fstart != 0) && fend >= fstart);
8093 	vm_rtfrecord_lock();
8094 	assert(vmrtfrs.vmrtfr_curi <= vmrtfrs.vmrtfr_maxi);
8095 
8096 	vmrtfrs.vmrtf_total++;
8097 	vm_rtfault_record_t *cvmr = &vmrtfrs.vm_rtf_records[vmrtfrs.vmrtfr_curi++];
8098 
8099 	cvmr->rtfabstime = fstart;
8100 	cvmr->rtfduration = fend - fstart;
8101 	cvmr->rtfaddr = fault_vaddr;
8102 	cvmr->rtfpc = cfpc;
8103 	cvmr->rtftype = type_of_fault;
8104 	cvmr->rtfupid = cupid;
8105 	cvmr->rtftid = ctid;
8106 
8107 	if (vmrtfrs.vmrtfr_curi > vmrtfrs.vmrtfr_maxi) {
8108 		vmrtfrs.vmrtfr_curi = 0;
8109 	}
8110 
8111 	vm_rtfrecord_unlock();
8112 }
8113 
8114 int
vmrtf_extract(uint64_t cupid,__unused boolean_t isroot,unsigned long vrecordsz,void * vrecords,unsigned long * vmrtfrv)8115 vmrtf_extract(uint64_t cupid, __unused boolean_t isroot, unsigned long vrecordsz, void *vrecords, unsigned long *vmrtfrv)
8116 {
8117 	vm_rtfault_record_t *cvmrd = vrecords;
8118 	size_t residue = vrecordsz;
8119 	size_t numextracted = 0;
8120 	boolean_t early_exit = FALSE;
8121 
8122 	vm_rtfrecord_lock();
8123 
8124 	for (int vmfi = 0; vmfi <= vmrtfrs.vmrtfr_maxi; vmfi++) {
8125 		if (residue < sizeof(vm_rtfault_record_t)) {
8126 			early_exit = TRUE;
8127 			break;
8128 		}
8129 
8130 		if (vmrtfrs.vm_rtf_records[vmfi].rtfupid != cupid) {
8131 #if     DEVELOPMENT || DEBUG
8132 			if (isroot == FALSE) {
8133 				continue;
8134 			}
8135 #else
8136 			continue;
8137 #endif /* DEVDEBUG */
8138 		}
8139 
8140 		*cvmrd = vmrtfrs.vm_rtf_records[vmfi];
8141 		cvmrd++;
8142 		residue -= sizeof(vm_rtfault_record_t);
8143 		numextracted++;
8144 	}
8145 
8146 	vm_rtfrecord_unlock();
8147 
8148 	*vmrtfrv = numextracted;
8149 	return early_exit;
8150 }
8151 
8152 /*
8153  * Only allow one diagnosis to be in flight at a time, to avoid
8154  * creating too much additional memory usage.
8155  */
8156 static volatile uint_t vmtc_diagnosing;
8157 unsigned int vmtc_total = 0;
8158 
8159 /*
8160  * Type used to update telemetry for the diagnosis counts.
8161  */
8162 CA_EVENT(vmtc_telemetry,
8163     CA_INT, vmtc_num_byte,            /* number of corrupt bytes found */
8164     CA_BOOL, vmtc_undiagnosed,        /* undiagnosed because more than 1 at a time */
8165     CA_BOOL, vmtc_not_eligible,       /* the page didn't qualify */
8166     CA_BOOL, vmtc_copyin_fail,        /* unable to copy in the page */
8167     CA_BOOL, vmtc_not_found,          /* no corruption found even though CS failed */
8168     CA_BOOL, vmtc_one_bit_flip,       /* single bit flip */
8169     CA_BOOL, vmtc_testing);           /* caused on purpose by testing */
8170 
8171 #if DEVELOPMENT || DEBUG
8172 /*
8173  * Buffers used to compare before/after page contents.
8174  * Stashed to aid when debugging crashes.
8175  */
8176 static size_t vmtc_last_buffer_size = 0;
8177 static uint64_t *vmtc_last_before_buffer = NULL;
8178 static uint64_t *vmtc_last_after_buffer = NULL;
8179 
8180 /*
8181  * Needed to record corruptions due to testing.
8182  */
8183 static uintptr_t corruption_test_va = 0;
8184 #endif /* DEVELOPMENT || DEBUG */
8185 
8186 /*
8187  * Stash a copy of data from a possibly corrupt page.
8188  */
8189 static uint64_t *
vmtc_get_page_data(vm_map_offset_t code_addr,vm_page_t page)8190 vmtc_get_page_data(
8191 	vm_map_offset_t code_addr,
8192 	vm_page_t       page)
8193 {
8194 	uint64_t        *buffer = NULL;
8195 	addr64_t        buffer_paddr;
8196 	addr64_t        page_paddr;
8197 	extern void     bcopy_phys(addr64_t from, addr64_t to, vm_size_t bytes);
8198 	uint_t          size = MIN(vm_map_page_size(current_map()), PAGE_SIZE);
8199 
8200 	/*
8201 	 * Need an aligned buffer to do a physical copy.
8202 	 */
8203 	if (kernel_memory_allocate(kernel_map, (vm_offset_t *)&buffer,
8204 	    size, size - 1, KMA_KOBJECT, VM_KERN_MEMORY_DIAG) != KERN_SUCCESS) {
8205 		return NULL;
8206 	}
8207 	buffer_paddr = kvtophys((vm_offset_t)buffer);
8208 	page_paddr = ptoa(VM_PAGE_GET_PHYS_PAGE(page));
8209 
8210 	/* adjust the page start address if we need only 4K of a 16K page */
8211 	if (size < PAGE_SIZE) {
8212 		uint_t subpage_start = ((code_addr & (PAGE_SIZE - 1)) & ~(size - 1));
8213 		page_paddr += subpage_start;
8214 	}
8215 
8216 	bcopy_phys(page_paddr, buffer_paddr, size);
8217 	return buffer;
8218 }
8219 
8220 /*
8221  * Set things up so we can diagnose a potential text page corruption.
8222  */
8223 static uint64_t *
vmtc_text_page_diagnose_setup(vm_map_offset_t code_addr,vm_page_t page,CA_EVENT_TYPE (vmtc_telemetry)* event)8224 vmtc_text_page_diagnose_setup(
8225 	vm_map_offset_t code_addr,
8226 	vm_page_t       page,
8227 	CA_EVENT_TYPE(vmtc_telemetry) *event)
8228 {
8229 	uint64_t        *buffer = NULL;
8230 
8231 	/*
8232 	 * If another is being diagnosed, skip this one.
8233 	 */
8234 	if (!OSCompareAndSwap(0, 1, &vmtc_diagnosing)) {
8235 		event->vmtc_undiagnosed = true;
8236 		return NULL;
8237 	}
8238 
8239 	/*
8240 	 * Get the contents of the corrupt page.
8241 	 */
8242 	buffer = vmtc_get_page_data(code_addr, page);
8243 	if (buffer == NULL) {
8244 		event->vmtc_copyin_fail = true;
8245 		if (!OSCompareAndSwap(1, 0, &vmtc_diagnosing)) {
8246 			panic("Bad compare and swap in setup!");
8247 		}
8248 		return NULL;
8249 	}
8250 	return buffer;
8251 }
8252 
8253 /*
8254  * Diagnose the text page by comparing its contents with
8255  * the one we've previously saved.
8256  */
8257 static void
vmtc_text_page_diagnose(vm_map_offset_t code_addr,uint64_t * old_code_buffer,CA_EVENT_TYPE (vmtc_telemetry)* event)8258 vmtc_text_page_diagnose(
8259 	vm_map_offset_t code_addr,
8260 	uint64_t        *old_code_buffer,
8261 	CA_EVENT_TYPE(vmtc_telemetry) *event)
8262 {
8263 	uint64_t        *new_code_buffer;
8264 	size_t          size = MIN(vm_map_page_size(current_map()), PAGE_SIZE);
8265 	uint_t          count = (uint_t)size / sizeof(uint64_t);
8266 	uint_t          diff_count = 0;
8267 	bool            bit_flip = false;
8268 	uint_t          b;
8269 	uint64_t        *new;
8270 	uint64_t        *old;
8271 
8272 	new_code_buffer = kalloc_data(size, Z_WAITOK);
8273 	assert(new_code_buffer != NULL);
8274 	if (copyin((user_addr_t)vm_map_trunc_page(code_addr, size - 1), new_code_buffer, size) != 0) {
8275 		/* copyin error, so undo things */
8276 		event->vmtc_copyin_fail = true;
8277 		goto done;
8278 	}
8279 
8280 	new = new_code_buffer;
8281 	old = old_code_buffer;
8282 	for (; count-- > 0; ++new, ++old) {
8283 		if (*new == *old) {
8284 			continue;
8285 		}
8286 
8287 		/*
8288 		 * On first diff, check for a single bit flip
8289 		 */
8290 		if (diff_count == 0) {
8291 			uint64_t x = (*new ^ *old);
8292 			assert(x != 0);
8293 			if ((x & (x - 1)) == 0) {
8294 				bit_flip = true;
8295 				++diff_count;
8296 				continue;
8297 			}
8298 		}
8299 
8300 		/*
8301 		 * count up the number of different bytes.
8302 		 */
8303 		for (b = 0; b < sizeof(uint64_t); ++b) {
8304 			char *n = (char *)new;
8305 			char *o = (char *)old;
8306 			if (n[b] != o[b]) {
8307 				++diff_count;
8308 			}
8309 		}
8310 	}
8311 
8312 	if (diff_count > 1) {
8313 		bit_flip = false;
8314 	}
8315 
8316 	if (diff_count == 0) {
8317 		event->vmtc_not_found = true;
8318 	} else {
8319 		event->vmtc_num_byte = diff_count;
8320 	}
8321 	if (bit_flip) {
8322 		event->vmtc_one_bit_flip = true;
8323 	}
8324 
8325 done:
8326 	/*
8327 	 * Free up the code copy buffers, but save the last
8328 	 * set on development / debug kernels in case they
8329 	 * can provide evidence for debugging memory stomps.
8330 	 */
8331 #if DEVELOPMENT || DEBUG
8332 	if (vmtc_last_before_buffer != NULL) {
8333 		kmem_free(kernel_map, (vm_offset_t)vmtc_last_before_buffer, vmtc_last_buffer_size);
8334 	}
8335 	if (vmtc_last_after_buffer != NULL) {
8336 		kfree_data(vmtc_last_after_buffer, vmtc_last_buffer_size);
8337 	}
8338 	vmtc_last_before_buffer = old_code_buffer;
8339 	vmtc_last_after_buffer = new_code_buffer;
8340 	vmtc_last_buffer_size = size;
8341 #else /* DEVELOPMENT || DEBUG */
8342 	kfree_data(new_code_buffer, size);
8343 	kmem_free(kernel_map, (vm_offset_t)old_code_buffer, size);
8344 #endif /* DEVELOPMENT || DEBUG */
8345 
8346 	/*
8347 	 * We're finished, so clear the diagnosing flag.
8348 	 */
8349 	if (!OSCompareAndSwap(1, 0, &vmtc_diagnosing)) {
8350 		panic("Bad compare and swap in diagnose!");
8351 	}
8352 }
8353 
8354 /*
8355  * For the given map, virt address, find the object, offset, and page.
8356  * This has to lookup the map entry, verify protections, walk any shadow chains.
8357  * If found, returns with the object locked.
8358  */
8359 static kern_return_t
vmtc_revalidate_lookup(vm_map_t map,vm_map_offset_t vaddr,vm_object_t * ret_object,vm_object_offset_t * ret_offset,vm_page_t * ret_page,vm_prot_t * ret_prot)8360 vmtc_revalidate_lookup(
8361 	vm_map_t               map,
8362 	vm_map_offset_t        vaddr,
8363 	vm_object_t            *ret_object,
8364 	vm_object_offset_t     *ret_offset,
8365 	vm_page_t              *ret_page,
8366 	vm_prot_t              *ret_prot)
8367 {
8368 	vm_object_t            object;
8369 	vm_object_offset_t     offset;
8370 	vm_page_t              page;
8371 	kern_return_t          kr = KERN_SUCCESS;
8372 	uint8_t                object_lock_type = OBJECT_LOCK_EXCLUSIVE;
8373 	vm_map_version_t       version;
8374 	boolean_t              wired;
8375 	struct vm_object_fault_info fault_info = {
8376 		.interruptible = THREAD_UNINT
8377 	};
8378 	vm_map_t               real_map = NULL;
8379 	vm_prot_t              prot;
8380 	vm_object_t            shadow;
8381 
8382 	/*
8383 	 * Find the object/offset for the given location/map.
8384 	 * Note this returns with the object locked.
8385 	 */
8386 restart:
8387 	vm_map_lock_read(map);
8388 	object = VM_OBJECT_NULL;        /* in case we come around the restart path */
8389 	kr = vm_map_lookup_and_lock_object(&map, vaddr, VM_PROT_READ,
8390 	    object_lock_type, &version, &object, &offset, &prot, &wired,
8391 	    &fault_info, &real_map, NULL);
8392 	vm_map_unlock_read(map);
8393 	if (real_map != NULL && real_map != map) {
8394 		vm_map_unlock(real_map);
8395 	}
8396 
8397 	/*
8398 	 * If there's no page here, fail.
8399 	 */
8400 	if (kr != KERN_SUCCESS || object == NULL) {
8401 		kr = KERN_FAILURE;
8402 		goto done;
8403 	}
8404 
8405 	/*
8406 	 * Chase down any shadow chains to find the actual page.
8407 	 */
8408 	for (;;) {
8409 		/*
8410 		 * See if the page is on the current object.
8411 		 */
8412 		page = vm_page_lookup(object, vm_object_trunc_page(offset));
8413 		if (page != NULL) {
8414 			/* restart the lookup */
8415 			if (page->vmp_restart) {
8416 				vm_object_unlock(object);
8417 				goto restart;
8418 			}
8419 
8420 			/*
8421 			 * If this page is busy, we need to wait for it.
8422 			 */
8423 			if (page->vmp_busy) {
8424 				vm_page_sleep(object, page, THREAD_INTERRUPTIBLE, LCK_SLEEP_UNLOCK);
8425 				goto restart;
8426 			}
8427 			break;
8428 		}
8429 
8430 		/*
8431 		 * If the object doesn't have the page and
8432 		 * has no shadow, then we can quit.
8433 		 */
8434 		shadow = object->shadow;
8435 		if (shadow == NULL) {
8436 			kr = KERN_FAILURE;
8437 			goto done;
8438 		}
8439 
8440 		/*
8441 		 * Move to the next object
8442 		 */
8443 		offset += object->vo_shadow_offset;
8444 		vm_object_lock(shadow);
8445 		vm_object_unlock(object);
8446 		object = shadow;
8447 		shadow = VM_OBJECT_NULL;
8448 	}
8449 	*ret_object = object;
8450 	*ret_offset = vm_object_trunc_page(offset);
8451 	*ret_page = page;
8452 	*ret_prot = prot;
8453 
8454 done:
8455 	if (kr != KERN_SUCCESS && object != NULL) {
8456 		vm_object_unlock(object);
8457 	}
8458 	return kr;
8459 }
8460 
8461 /*
8462  * Check if a page is wired, needs extra locking.
8463  */
8464 static bool
is_page_wired(vm_page_t page)8465 is_page_wired(vm_page_t page)
8466 {
8467 	bool result;
8468 	vm_page_lock_queues();
8469 	result = VM_PAGE_WIRED(page);
8470 	vm_page_unlock_queues();
8471 	return result;
8472 }
8473 
8474 /*
8475  * A fatal process error has occurred in the given task.
8476  * Recheck the code signing of the text page at the given
8477  * address to check for a text page corruption.
8478  *
8479  * Returns KERN_FAILURE if a page was found to be corrupt
8480  * by failing to match its code signature. KERN_SUCCESS
8481  * means the page is either valid or we don't have the
8482  * information to say it's corrupt.
8483  */
8484 kern_return_t
revalidate_text_page(task_t task,vm_map_offset_t code_addr)8485 revalidate_text_page(task_t task, vm_map_offset_t code_addr)
8486 {
8487 	kern_return_t          kr;
8488 	vm_map_t               map;
8489 	vm_object_t            object = NULL;
8490 	vm_object_offset_t     offset;
8491 	vm_page_t              page = NULL;
8492 	struct vnode           *vnode;
8493 	uint64_t               *diagnose_buffer = NULL;
8494 	CA_EVENT_TYPE(vmtc_telemetry) * event = NULL;
8495 	ca_event_t             ca_event = NULL;
8496 	vm_prot_t              prot;
8497 
8498 	map = task->map;
8499 	if (task->map == NULL) {
8500 		return KERN_SUCCESS;
8501 	}
8502 
8503 	kr = vmtc_revalidate_lookup(map, code_addr, &object, &offset, &page, &prot);
8504 	if (kr != KERN_SUCCESS) {
8505 		goto done;
8506 	}
8507 
8508 	/*
8509 	 * The page must be executable.
8510 	 */
8511 	if (!(prot & VM_PROT_EXECUTE)) {
8512 		goto done;
8513 	}
8514 
8515 	/*
8516 	 * The object needs to have a pager.
8517 	 */
8518 	if (object->pager == NULL) {
8519 		goto done;
8520 	}
8521 
8522 	/*
8523 	 * Needs to be a vnode backed page to have a signature.
8524 	 */
8525 	vnode = vnode_pager_lookup_vnode(object->pager);
8526 	if (vnode == NULL) {
8527 		goto done;
8528 	}
8529 
8530 	/*
8531 	 * Object checks to see if we should proceed.
8532 	 */
8533 	if (!object->code_signed ||     /* no code signature to check */
8534 	    object->internal ||         /* internal objects aren't signed */
8535 	    object->terminating ||      /* the object and its pages are already going away */
8536 	    !object->pager_ready) {     /* this should happen, but check shouldn't hurt */
8537 		goto done;
8538 	}
8539 
8540 
8541 	/*
8542 	 * Check the code signature of the page in question.
8543 	 */
8544 	vm_page_map_and_validate_cs(object, page);
8545 
8546 	/*
8547 	 * At this point:
8548 	 * vmp_cs_validated |= validated (set if a code signature exists)
8549 	 * vmp_cs_tainted |= tainted (set if code signature violation)
8550 	 * vmp_cs_nx |= nx;  ??
8551 	 *
8552 	 * if vmp_pmapped then have to pmap_disconnect..
8553 	 * other flags to check on object or page?
8554 	 */
8555 	if (page->vmp_cs_tainted != VMP_CS_ALL_FALSE) {
8556 #if DEBUG || DEVELOPMENT
8557 		/*
8558 		 * On development builds, a boot-arg can be used to cause
8559 		 * a panic, instead of a quiet repair.
8560 		 */
8561 		if (vmtc_panic_instead) {
8562 			panic("Text page corruption detected: vm_page_t 0x%llx", (long long)(uintptr_t)page);
8563 		}
8564 #endif /* DEBUG || DEVELOPMENT */
8565 
8566 		/*
8567 		 * We're going to invalidate this page. Grab a copy of it for comparison.
8568 		 */
8569 		ca_event = CA_EVENT_ALLOCATE(vmtc_telemetry);
8570 		event = ca_event->data;
8571 		diagnose_buffer = vmtc_text_page_diagnose_setup(code_addr, page, event);
8572 
8573 		/*
8574 		 * Invalidate, i.e. toss, the corrupted page.
8575 		 */
8576 		if (!page->vmp_cleaning &&
8577 		    !page->vmp_laundry &&
8578 		    !page->vmp_fictitious &&
8579 		    !page->vmp_precious &&
8580 		    !page->vmp_absent &&
8581 		    !VMP_ERROR_GET(page) &&
8582 		    !page->vmp_dirty &&
8583 		    !is_page_wired(page)) {
8584 			if (page->vmp_pmapped) {
8585 				int refmod = pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(page));
8586 				if (refmod & VM_MEM_MODIFIED) {
8587 					SET_PAGE_DIRTY(page, FALSE);
8588 				}
8589 				if (refmod & VM_MEM_REFERENCED) {
8590 					page->vmp_reference = TRUE;
8591 				}
8592 			}
8593 			/* If the page seems intentionally modified, don't trash it. */
8594 			if (!page->vmp_dirty) {
8595 				VM_PAGE_FREE(page);
8596 			} else {
8597 				event->vmtc_not_eligible = true;
8598 			}
8599 		} else {
8600 			event->vmtc_not_eligible = true;
8601 		}
8602 		vm_object_unlock(object);
8603 		object = VM_OBJECT_NULL;
8604 
8605 		/*
8606 		 * Now try to diagnose the type of failure by faulting
8607 		 * in a new copy and diff'ing it with what we saved.
8608 		 */
8609 		if (diagnose_buffer != NULL) {
8610 			vmtc_text_page_diagnose(code_addr, diagnose_buffer, event);
8611 		}
8612 #if DEBUG || DEVELOPMENT
8613 		if (corruption_test_va != 0) {
8614 			corruption_test_va = 0;
8615 			event->vmtc_testing = true;
8616 		}
8617 #endif /* DEBUG || DEVELOPMENT */
8618 		ktriage_record(thread_tid(current_thread()),
8619 		    KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_TEXT_CORRUPTION),
8620 		    0 /* arg */);
8621 		CA_EVENT_SEND(ca_event);
8622 		printf("Text page corruption detected for pid %d\n", proc_selfpid());
8623 		++vmtc_total;
8624 		return KERN_FAILURE; /* failure means we definitely found a corrupt page */
8625 	}
8626 done:
8627 	if (object != NULL) {
8628 		vm_object_unlock(object);
8629 	}
8630 	return KERN_SUCCESS;
8631 }
8632 
8633 #if DEBUG || DEVELOPMENT
8634 /*
8635  * For implementing unit tests - ask the pmap to corrupt a text page.
8636  * We have to find the page, to get the physical address, then invoke
8637  * the pmap.
8638  */
8639 extern kern_return_t vm_corrupt_text_addr(uintptr_t);
8640 
8641 kern_return_t
vm_corrupt_text_addr(uintptr_t va)8642 vm_corrupt_text_addr(uintptr_t va)
8643 {
8644 	task_t                 task = current_task();
8645 	vm_map_t               map;
8646 	kern_return_t          kr = KERN_SUCCESS;
8647 	vm_object_t            object = VM_OBJECT_NULL;
8648 	vm_object_offset_t     offset;
8649 	vm_page_t              page = NULL;
8650 	pmap_paddr_t           pa;
8651 	vm_prot_t              prot;
8652 
8653 	map = task->map;
8654 	if (task->map == NULL) {
8655 		printf("corrupt_text_addr: no map\n");
8656 		return KERN_FAILURE;
8657 	}
8658 
8659 	kr = vmtc_revalidate_lookup(map, (vm_map_offset_t)va, &object, &offset, &page, &prot);
8660 	if (kr != KERN_SUCCESS) {
8661 		printf("corrupt_text_addr: page lookup failed\n");
8662 		return kr;
8663 	}
8664 	if (!(prot & VM_PROT_EXECUTE)) {
8665 		printf("corrupt_text_addr: page not executable\n");
8666 		return KERN_FAILURE;
8667 	}
8668 
8669 	/* get the physical address to use */
8670 	pa = ptoa(VM_PAGE_GET_PHYS_PAGE(page)) + (va - vm_object_trunc_page(va));
8671 
8672 	/*
8673 	 * Check we have something we can work with.
8674 	 * Due to racing with pageout as we enter the sysctl,
8675 	 * it's theoretically possible to have the page disappear, just
8676 	 * before the lookup.
8677 	 *
8678 	 * That's highly likely to happen often. I've filed a radar 72857482
8679 	 * to bubble up the error here to the sysctl result and have the
8680 	 * test not FAIL in that case.
8681 	 */
8682 	if (page->vmp_busy) {
8683 		printf("corrupt_text_addr: vmp_busy\n");
8684 		kr = KERN_FAILURE;
8685 	}
8686 	if (page->vmp_cleaning) {
8687 		printf("corrupt_text_addr: vmp_cleaning\n");
8688 		kr = KERN_FAILURE;
8689 	}
8690 	if (page->vmp_laundry) {
8691 		printf("corrupt_text_addr: vmp_cleaning\n");
8692 		kr = KERN_FAILURE;
8693 	}
8694 	if (page->vmp_fictitious) {
8695 		printf("corrupt_text_addr: vmp_fictitious\n");
8696 		kr = KERN_FAILURE;
8697 	}
8698 	if (page->vmp_precious) {
8699 		printf("corrupt_text_addr: vmp_precious\n");
8700 		kr = KERN_FAILURE;
8701 	}
8702 	if (page->vmp_absent) {
8703 		printf("corrupt_text_addr: vmp_absent\n");
8704 		kr = KERN_FAILURE;
8705 	}
8706 	if (VMP_ERROR_GET(page)) {
8707 		printf("corrupt_text_addr: vmp_error\n");
8708 		kr = KERN_FAILURE;
8709 	}
8710 	if (page->vmp_dirty) {
8711 		printf("corrupt_text_addr: vmp_dirty\n");
8712 		kr = KERN_FAILURE;
8713 	}
8714 	if (is_page_wired(page)) {
8715 		printf("corrupt_text_addr: wired\n");
8716 		kr = KERN_FAILURE;
8717 	}
8718 	if (!page->vmp_pmapped) {
8719 		printf("corrupt_text_addr: !vmp_pmapped\n");
8720 		kr = KERN_FAILURE;
8721 	}
8722 
8723 	if (kr == KERN_SUCCESS) {
8724 		printf("corrupt_text_addr: using physaddr 0x%llx\n", (long long)pa);
8725 		kr = pmap_test_text_corruption(pa);
8726 		if (kr != KERN_SUCCESS) {
8727 			printf("corrupt_text_addr: pmap error %d\n", kr);
8728 		} else {
8729 			corruption_test_va = va;
8730 		}
8731 	} else {
8732 		printf("corrupt_text_addr: object %p\n", object);
8733 		printf("corrupt_text_addr: offset 0x%llx\n", (uint64_t)offset);
8734 		printf("corrupt_text_addr: va 0x%llx\n", (uint64_t)va);
8735 		printf("corrupt_text_addr: vm_object_trunc_page(va) 0x%llx\n", (uint64_t)vm_object_trunc_page(va));
8736 		printf("corrupt_text_addr: vm_page_t %p\n", page);
8737 		printf("corrupt_text_addr: ptoa(PHYS_PAGE) 0x%llx\n", (uint64_t)ptoa(VM_PAGE_GET_PHYS_PAGE(page)));
8738 		printf("corrupt_text_addr: using physaddr 0x%llx\n", (uint64_t)pa);
8739 	}
8740 
8741 	if (object != VM_OBJECT_NULL) {
8742 		vm_object_unlock(object);
8743 	}
8744 	return kr;
8745 }
8746 
8747 #endif /* DEBUG || DEVELOPMENT */
8748