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