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 (object == kernel_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(object != kernel_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->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->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 (VMP_ERROR_GET(m)) {
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->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 object == kernel_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(object != kernel_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
1728 /*
1729 * If the object is purgeable, its
1730 * owner's purgeable ledgers have been
1731 * updated in vm_page_insert() but the
1732 * page was also accounted for in a
1733 * "compressed purgeable" ledger, so
1734 * update that now.
1735 */
1736 if (((object->purgable !=
1737 VM_PURGABLE_DENY) ||
1738 object->vo_ledger_tag) &&
1739 (object->vo_owner !=
1740 NULL)) {
1741 /*
1742 * One less compressed
1743 * purgeable/tagged page.
1744 */
1745 vm_object_owner_compressed_update(
1746 object,
1747 -1);
1748 }
1749
1750 break;
1751 case KERN_MEMORY_FAILURE:
1752 m->vmp_unusual = TRUE;
1753 m->vmp_error = TRUE;
1754 m->vmp_absent = FALSE;
1755 break;
1756 case KERN_MEMORY_ERROR:
1757 assert(m->vmp_absent);
1758 break;
1759 default:
1760 panic("vm_fault_page(): unexpected "
1761 "error %d from "
1762 "vm_compressor_pager_get()\n",
1763 rc);
1764 }
1765 PAGE_WAKEUP_DONE(m);
1766
1767 rc = KERN_SUCCESS;
1768 goto data_requested;
1769 }
1770 my_fault_type = DBG_PAGEIN_FAULT;
1771
1772 if (m != VM_PAGE_NULL) {
1773 VM_PAGE_FREE(m);
1774 m = VM_PAGE_NULL;
1775 }
1776
1777 #if TRACEFAULTPAGE
1778 dbgTrace(0xBEEF0012, (unsigned int) object, (unsigned int) 0); /* (TEST/DEBUG) */
1779 #endif
1780
1781 /*
1782 * It's possible someone called vm_object_destroy while we weren't
1783 * holding the object lock. If that has happened, then bail out
1784 * here.
1785 */
1786
1787 pager = object->pager;
1788
1789 if (pager == MEMORY_OBJECT_NULL) {
1790 vm_fault_cleanup(object, first_m);
1791 thread_interrupt_level(interruptible_state);
1792 ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_OBJECT_NO_PAGER), 0 /* arg */);
1793 return VM_FAULT_MEMORY_ERROR;
1794 }
1795
1796 /*
1797 * We have an absent page in place for the faulting offset,
1798 * so we can release the object lock.
1799 */
1800
1801 if (object->object_is_shared_cache) {
1802 token = thread_priority_floor_start();
1803 /*
1804 * A non-native shared cache object might
1805 * be getting set up in parallel with this
1806 * fault and so we can't assume that this
1807 * check will be valid after we drop the
1808 * object lock below.
1809 */
1810 drop_floor = true;
1811 }
1812
1813 vm_object_unlock(object);
1814
1815 /*
1816 * If this object uses a copy_call strategy,
1817 * and we are interested in a copy of this object
1818 * (having gotten here only by following a
1819 * shadow chain), then tell the memory manager
1820 * via a flag added to the desired_access
1821 * parameter, so that it can detect a race
1822 * between our walking down the shadow chain
1823 * and its pushing pages up into a copy of
1824 * the object that it manages.
1825 */
1826 if (object->copy_strategy == MEMORY_OBJECT_COPY_CALL && object != first_object) {
1827 wants_copy_flag = VM_PROT_WANTS_COPY;
1828 } else {
1829 wants_copy_flag = VM_PROT_NONE;
1830 }
1831
1832 if (object->copy == first_object) {
1833 /*
1834 * if we issue the memory_object_data_request in
1835 * this state, we are subject to a deadlock with
1836 * the underlying filesystem if it is trying to
1837 * shrink the file resulting in a push of pages
1838 * into the copy object... that push will stall
1839 * on the placeholder page, and if the pushing thread
1840 * is holding a lock that is required on the pagein
1841 * path (such as a truncate lock), we'll deadlock...
1842 * to avoid this potential deadlock, we throw away
1843 * our placeholder page before calling memory_object_data_request
1844 * and force this thread to retry the vm_fault_page after
1845 * we have issued the I/O. the second time through this path
1846 * we will find the page already in the cache (presumably still
1847 * busy waiting for the I/O to complete) and then complete
1848 * the fault w/o having to go through memory_object_data_request again
1849 */
1850 assert(first_m != VM_PAGE_NULL);
1851 assert(VM_PAGE_OBJECT(first_m) == first_object);
1852
1853 vm_object_lock(first_object);
1854 VM_PAGE_FREE(first_m);
1855 vm_object_paging_end(first_object);
1856 vm_object_unlock(first_object);
1857
1858 first_m = VM_PAGE_NULL;
1859 force_fault_retry = TRUE;
1860
1861 vm_fault_page_forced_retry++;
1862 }
1863
1864 if (data_already_requested == TRUE) {
1865 orig_behavior = fault_info->behavior;
1866 orig_cluster_size = fault_info->cluster_size;
1867
1868 fault_info->behavior = VM_BEHAVIOR_RANDOM;
1869 fault_info->cluster_size = PAGE_SIZE;
1870 }
1871 /*
1872 * Call the memory manager to retrieve the data.
1873 */
1874 rc = memory_object_data_request(
1875 pager,
1876 vm_object_trunc_page(offset) + object->paging_offset,
1877 PAGE_SIZE,
1878 access_required | wants_copy_flag,
1879 (memory_object_fault_info_t)fault_info);
1880
1881 if (data_already_requested == TRUE) {
1882 fault_info->behavior = orig_behavior;
1883 fault_info->cluster_size = orig_cluster_size;
1884 } else {
1885 data_already_requested = TRUE;
1886 }
1887
1888 DTRACE_VM2(maj_fault, int, 1, (uint64_t *), NULL);
1889 #if TRACEFAULTPAGE
1890 dbgTrace(0xBEEF0013, (unsigned int) object, (unsigned int) rc); /* (TEST/DEBUG) */
1891 #endif
1892 vm_object_lock(object);
1893
1894 if (drop_floor && object->object_is_shared_cache) {
1895 thread_priority_floor_end(&token);
1896 drop_floor = false;
1897 }
1898
1899 data_requested:
1900 if (rc != KERN_SUCCESS) {
1901 vm_fault_cleanup(object, first_m);
1902 thread_interrupt_level(interruptible_state);
1903
1904 ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_NO_DATA), 0 /* arg */);
1905
1906 return (rc == MACH_SEND_INTERRUPTED) ?
1907 VM_FAULT_INTERRUPTED :
1908 VM_FAULT_MEMORY_ERROR;
1909 } else {
1910 clock_sec_t tv_sec;
1911 clock_usec_t tv_usec;
1912
1913 if (my_fault_type == DBG_PAGEIN_FAULT) {
1914 clock_get_system_microtime(&tv_sec, &tv_usec);
1915 current_thread()->t_page_creation_time = tv_sec;
1916 current_thread()->t_page_creation_count = 0;
1917 }
1918 }
1919 if ((interruptible != THREAD_UNINT) && (current_thread()->sched_flags & TH_SFLAG_ABORT)) {
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_FAULT_INTERRUPTED), 0 /* arg */);
1924 return VM_FAULT_INTERRUPTED;
1925 }
1926 if (force_fault_retry == TRUE) {
1927 vm_fault_cleanup(object, first_m);
1928 thread_interrupt_level(interruptible_state);
1929
1930 return VM_FAULT_RETRY;
1931 }
1932 if (m == VM_PAGE_NULL && object->phys_contiguous) {
1933 /*
1934 * No page here means that the object we
1935 * initially looked up was "physically
1936 * contiguous" (i.e. device memory). However,
1937 * with Virtual VRAM, the object might not
1938 * be backed by that device memory anymore,
1939 * so we're done here only if the object is
1940 * still "phys_contiguous".
1941 * Otherwise, if the object is no longer
1942 * "phys_contiguous", we need to retry the
1943 * page fault against the object's new backing
1944 * store (different memory object).
1945 */
1946 phys_contig_object:
1947 goto done;
1948 }
1949 /*
1950 * potentially a pagein fault
1951 * if we make it through the state checks
1952 * above, than we'll count it as such
1953 */
1954 my_fault = my_fault_type;
1955
1956 /*
1957 * Retry with same object/offset, since new data may
1958 * be in a different page (i.e., m is meaningless at
1959 * this point).
1960 */
1961 continue;
1962 }
1963 dont_look_for_page:
1964 /*
1965 * We get here if the object has no pager, or an existence map
1966 * exists and indicates the page isn't present on the pager
1967 * or we're unwiring a page. If a pager exists, but there
1968 * is no existence map, then the m->vmp_absent case above handles
1969 * the ZF case when the pager can't provide the page
1970 */
1971 #if TRACEFAULTPAGE
1972 dbgTrace(0xBEEF0014, (unsigned int) object, (unsigned int) m); /* (TEST/DEBUG) */
1973 #endif
1974 if (object == first_object) {
1975 first_m = m;
1976 } else {
1977 assert(m == VM_PAGE_NULL);
1978 }
1979
1980 next_object = object->shadow;
1981
1982 if (next_object == VM_OBJECT_NULL) {
1983 /*
1984 * we've hit the bottom of the shadown chain,
1985 * fill the page in the top object with zeros.
1986 */
1987 assert(!must_be_resident);
1988
1989 if (object != first_object) {
1990 vm_object_paging_end(object);
1991 vm_object_unlock(object);
1992
1993 object = first_object;
1994 offset = first_offset;
1995 vm_object_lock(object);
1996 }
1997 m = first_m;
1998 assert(VM_PAGE_OBJECT(m) == object);
1999 first_m = VM_PAGE_NULL;
2000
2001 /*
2002 * check for any conditions that prevent
2003 * us from creating a new zero-fill page
2004 * vm_fault_check will do all of the
2005 * fault cleanup in the case of an error condition
2006 * including resetting the thread_interrupt_level
2007 */
2008 error = vm_fault_check(object, m, first_m, interruptible_state, (type_of_fault == NULL) ? TRUE : FALSE);
2009
2010 if (error != VM_FAULT_SUCCESS) {
2011 return error;
2012 }
2013
2014 if (m == VM_PAGE_NULL) {
2015 m = vm_page_grab_options(grab_options);
2016
2017 if (m == VM_PAGE_NULL) {
2018 vm_fault_cleanup(object, VM_PAGE_NULL);
2019 thread_interrupt_level(interruptible_state);
2020
2021 return VM_FAULT_MEMORY_SHORTAGE;
2022 }
2023 vm_page_insert(m, object, vm_object_trunc_page(offset));
2024 }
2025 if (fault_info->mark_zf_absent && no_zero_fill == TRUE) {
2026 m->vmp_absent = TRUE;
2027 clear_absent_on_error = true;
2028 }
2029
2030 my_fault = vm_fault_zero_page(m, no_zero_fill);
2031
2032 break;
2033 } else {
2034 /*
2035 * Move on to the next object. Lock the next
2036 * object before unlocking the current one.
2037 */
2038 if ((object != first_object) || must_be_resident) {
2039 vm_object_paging_end(object);
2040 }
2041
2042 offset += object->vo_shadow_offset;
2043 fault_info->lo_offset += object->vo_shadow_offset;
2044 fault_info->hi_offset += object->vo_shadow_offset;
2045 access_required = VM_PROT_READ;
2046
2047 vm_object_lock(next_object);
2048 vm_object_unlock(object);
2049
2050 object = next_object;
2051 vm_object_paging_begin(object);
2052 }
2053 }
2054
2055 /*
2056 * PAGE HAS BEEN FOUND.
2057 *
2058 * This page (m) is:
2059 * busy, so that we can play with it;
2060 * not absent, so that nobody else will fill it;
2061 * possibly eligible for pageout;
2062 *
2063 * The top-level page (first_m) is:
2064 * VM_PAGE_NULL if the page was found in the
2065 * top-level object;
2066 * busy, not absent, and ineligible for pageout.
2067 *
2068 * The current object (object) is locked. A paging
2069 * reference is held for the current and top-level
2070 * objects.
2071 */
2072
2073 #if TRACEFAULTPAGE
2074 dbgTrace(0xBEEF0015, (unsigned int) object, (unsigned int) m); /* (TEST/DEBUG) */
2075 #endif
2076 #if EXTRA_ASSERTIONS
2077 assert(m->vmp_busy && !m->vmp_absent);
2078 assert((first_m == VM_PAGE_NULL) ||
2079 (first_m->vmp_busy && !first_m->vmp_absent &&
2080 !first_m->vmp_active && !first_m->vmp_inactive && !first_m->vmp_secluded));
2081 #endif /* EXTRA_ASSERTIONS */
2082
2083 /*
2084 * If the page is being written, but isn't
2085 * already owned by the top-level object,
2086 * we have to copy it into a new page owned
2087 * by the top-level object.
2088 */
2089 if (object != first_object) {
2090 #if TRACEFAULTPAGE
2091 dbgTrace(0xBEEF0016, (unsigned int) object, (unsigned int) fault_type); /* (TEST/DEBUG) */
2092 #endif
2093 if (fault_type & VM_PROT_WRITE) {
2094 vm_page_t copy_m;
2095
2096 /*
2097 * We only really need to copy if we
2098 * want to write it.
2099 */
2100 assert(!must_be_resident);
2101
2102 /*
2103 * If we try to collapse first_object at this
2104 * point, we may deadlock when we try to get
2105 * the lock on an intermediate object (since we
2106 * have the bottom object locked). We can't
2107 * unlock the bottom object, because the page
2108 * we found may move (by collapse) if we do.
2109 *
2110 * Instead, we first copy the page. Then, when
2111 * we have no more use for the bottom object,
2112 * we unlock it and try to collapse.
2113 *
2114 * Note that we copy the page even if we didn't
2115 * need to... that's the breaks.
2116 */
2117
2118 /*
2119 * Allocate a page for the copy
2120 */
2121 copy_m = vm_page_grab_options(grab_options);
2122
2123 if (copy_m == VM_PAGE_NULL) {
2124 RELEASE_PAGE(m);
2125
2126 vm_fault_cleanup(object, first_m);
2127 thread_interrupt_level(interruptible_state);
2128
2129 return VM_FAULT_MEMORY_SHORTAGE;
2130 }
2131
2132 vm_page_copy(m, copy_m);
2133
2134 /*
2135 * If another map is truly sharing this
2136 * page with us, we have to flush all
2137 * uses of the original page, since we
2138 * can't distinguish those which want the
2139 * original from those which need the
2140 * new copy.
2141 *
2142 * XXXO If we know that only one map has
2143 * access to this page, then we could
2144 * avoid the pmap_disconnect() call.
2145 */
2146 if (m->vmp_pmapped) {
2147 pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(m));
2148 }
2149
2150 if (m->vmp_clustered) {
2151 VM_PAGE_COUNT_AS_PAGEIN(m);
2152 VM_PAGE_CONSUME_CLUSTERED(m);
2153 }
2154 assert(!m->vmp_cleaning);
2155
2156 /*
2157 * We no longer need the old page or object.
2158 */
2159 RELEASE_PAGE(m);
2160
2161 /*
2162 * This check helps with marking the object as having a sequential pattern
2163 * Normally we'll miss doing this below because this fault is about COW to
2164 * the first_object i.e. bring page in from disk, push to object above but
2165 * don't update the file object's sequential pattern.
2166 */
2167 if (object->internal == FALSE) {
2168 vm_fault_is_sequential(object, offset, fault_info->behavior);
2169 }
2170
2171 vm_object_paging_end(object);
2172 vm_object_unlock(object);
2173
2174 my_fault = DBG_COW_FAULT;
2175 counter_inc(&vm_statistics_cow_faults);
2176 DTRACE_VM2(cow_fault, int, 1, (uint64_t *), NULL);
2177 counter_inc(¤t_task()->cow_faults);
2178
2179 object = first_object;
2180 offset = first_offset;
2181
2182 vm_object_lock(object);
2183 /*
2184 * get rid of the place holder
2185 * page that we soldered in earlier
2186 */
2187 VM_PAGE_FREE(first_m);
2188 first_m = VM_PAGE_NULL;
2189
2190 /*
2191 * and replace it with the
2192 * page we just copied into
2193 */
2194 assert(copy_m->vmp_busy);
2195 vm_page_insert(copy_m, object, vm_object_trunc_page(offset));
2196 SET_PAGE_DIRTY(copy_m, TRUE);
2197
2198 m = copy_m;
2199 /*
2200 * Now that we've gotten the copy out of the
2201 * way, let's try to collapse the top object.
2202 * But we have to play ugly games with
2203 * paging_in_progress to do that...
2204 */
2205 vm_object_paging_end(object);
2206 vm_object_collapse(object, vm_object_trunc_page(offset), TRUE);
2207 vm_object_paging_begin(object);
2208 } else {
2209 *protection &= (~VM_PROT_WRITE);
2210 }
2211 }
2212 /*
2213 * Now check whether the page needs to be pushed into the
2214 * copy object. The use of asymmetric copy on write for
2215 * shared temporary objects means that we may do two copies to
2216 * satisfy the fault; one above to get the page from a
2217 * shadowed object, and one here to push it into the copy.
2218 */
2219 try_failed_count = 0;
2220
2221 while ((copy_object = first_object->copy) != VM_OBJECT_NULL) {
2222 vm_object_offset_t copy_offset;
2223 vm_page_t copy_m;
2224
2225 #if TRACEFAULTPAGE
2226 dbgTrace(0xBEEF0017, (unsigned int) copy_object, (unsigned int) fault_type); /* (TEST/DEBUG) */
2227 #endif
2228 /*
2229 * If the page is being written, but hasn't been
2230 * copied to the copy-object, we have to copy it there.
2231 */
2232 if ((fault_type & VM_PROT_WRITE) == 0) {
2233 *protection &= ~VM_PROT_WRITE;
2234 break;
2235 }
2236
2237 /*
2238 * If the page was guaranteed to be resident,
2239 * we must have already performed the copy.
2240 */
2241 if (must_be_resident) {
2242 break;
2243 }
2244
2245 /*
2246 * Try to get the lock on the copy_object.
2247 */
2248 if (!vm_object_lock_try(copy_object)) {
2249 vm_object_unlock(object);
2250 try_failed_count++;
2251
2252 mutex_pause(try_failed_count); /* wait a bit */
2253 vm_object_lock(object);
2254
2255 continue;
2256 }
2257 try_failed_count = 0;
2258
2259 /*
2260 * Make another reference to the copy-object,
2261 * to keep it from disappearing during the
2262 * copy.
2263 */
2264 vm_object_reference_locked(copy_object);
2265
2266 /*
2267 * Does the page exist in the copy?
2268 */
2269 copy_offset = first_offset - copy_object->vo_shadow_offset;
2270 copy_offset = vm_object_trunc_page(copy_offset);
2271
2272 if (copy_object->vo_size <= copy_offset) {
2273 /*
2274 * Copy object doesn't cover this page -- do nothing.
2275 */
2276 ;
2277 } else if ((copy_m = vm_page_lookup(copy_object, copy_offset)) != VM_PAGE_NULL) {
2278 /*
2279 * Page currently exists in the copy object
2280 */
2281 if (copy_m->vmp_busy) {
2282 /*
2283 * If the page is being brought
2284 * in, wait for it and then retry.
2285 */
2286 RELEASE_PAGE(m);
2287
2288 /*
2289 * take an extra ref so object won't die
2290 */
2291 vm_object_reference_locked(copy_object);
2292 vm_object_unlock(copy_object);
2293 vm_fault_cleanup(object, first_m);
2294
2295 vm_object_lock(copy_object);
2296 assert(copy_object->ref_count > 0);
2297 vm_object_lock_assert_exclusive(copy_object);
2298 copy_object->ref_count--;
2299 assert(copy_object->ref_count > 0);
2300 copy_m = vm_page_lookup(copy_object, copy_offset);
2301
2302 if (copy_m != VM_PAGE_NULL && copy_m->vmp_busy) {
2303 PAGE_ASSERT_WAIT(copy_m, interruptible);
2304
2305 vm_object_unlock(copy_object);
2306 wait_result = thread_block(THREAD_CONTINUE_NULL);
2307 vm_object_deallocate(copy_object);
2308
2309 goto backoff;
2310 } else {
2311 vm_object_unlock(copy_object);
2312 vm_object_deallocate(copy_object);
2313 thread_interrupt_level(interruptible_state);
2314
2315 return VM_FAULT_RETRY;
2316 }
2317 }
2318 } else if (!PAGED_OUT(copy_object, copy_offset)) {
2319 /*
2320 * If PAGED_OUT is TRUE, then the page used to exist
2321 * in the copy-object, and has already been paged out.
2322 * We don't need to repeat this. If PAGED_OUT is
2323 * FALSE, then either we don't know (!pager_created,
2324 * for example) or it hasn't been paged out.
2325 * (VM_EXTERNAL_STATE_UNKNOWN||VM_EXTERNAL_STATE_ABSENT)
2326 * We must copy the page to the copy object.
2327 *
2328 * Allocate a page for the copy
2329 */
2330 copy_m = vm_page_alloc(copy_object, copy_offset);
2331
2332 if (copy_m == VM_PAGE_NULL) {
2333 RELEASE_PAGE(m);
2334
2335 vm_object_lock_assert_exclusive(copy_object);
2336 copy_object->ref_count--;
2337 assert(copy_object->ref_count > 0);
2338
2339 vm_object_unlock(copy_object);
2340 vm_fault_cleanup(object, first_m);
2341 thread_interrupt_level(interruptible_state);
2342
2343 return VM_FAULT_MEMORY_SHORTAGE;
2344 }
2345 /*
2346 * Must copy page into copy-object.
2347 */
2348 vm_page_copy(m, copy_m);
2349
2350 /*
2351 * If the old page was in use by any users
2352 * of the copy-object, it must be removed
2353 * from all pmaps. (We can't know which
2354 * pmaps use it.)
2355 */
2356 if (m->vmp_pmapped) {
2357 pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(m));
2358 }
2359
2360 if (m->vmp_clustered) {
2361 VM_PAGE_COUNT_AS_PAGEIN(m);
2362 VM_PAGE_CONSUME_CLUSTERED(m);
2363 }
2364 /*
2365 * If there's a pager, then immediately
2366 * page out this page, using the "initialize"
2367 * option. Else, we use the copy.
2368 */
2369 if ((!copy_object->pager_ready)
2370 || VM_COMPRESSOR_PAGER_STATE_GET(copy_object, copy_offset) == VM_EXTERNAL_STATE_ABSENT
2371 ) {
2372 vm_page_lockspin_queues();
2373 assert(!m->vmp_cleaning);
2374 vm_page_activate(copy_m);
2375 vm_page_unlock_queues();
2376
2377 SET_PAGE_DIRTY(copy_m, TRUE);
2378 PAGE_WAKEUP_DONE(copy_m);
2379 } else {
2380 assert(copy_m->vmp_busy == TRUE);
2381 assert(!m->vmp_cleaning);
2382
2383 /*
2384 * dirty is protected by the object lock
2385 */
2386 SET_PAGE_DIRTY(copy_m, TRUE);
2387
2388 /*
2389 * The page is already ready for pageout:
2390 * not on pageout queues and busy.
2391 * Unlock everything except the
2392 * copy_object itself.
2393 */
2394 vm_object_unlock(object);
2395
2396 /*
2397 * Write the page to the copy-object,
2398 * flushing it from the kernel.
2399 */
2400 vm_pageout_initialize_page(copy_m);
2401
2402 /*
2403 * Since the pageout may have
2404 * temporarily dropped the
2405 * copy_object's lock, we
2406 * check whether we'll have
2407 * to deallocate the hard way.
2408 */
2409 if ((copy_object->shadow != object) || (copy_object->ref_count == 1)) {
2410 vm_object_unlock(copy_object);
2411 vm_object_deallocate(copy_object);
2412 vm_object_lock(object);
2413
2414 continue;
2415 }
2416 /*
2417 * Pick back up the old object's
2418 * lock. [It is safe to do so,
2419 * since it must be deeper in the
2420 * object tree.]
2421 */
2422 vm_object_lock(object);
2423 }
2424
2425 /*
2426 * Because we're pushing a page upward
2427 * in the object tree, we must restart
2428 * any faults that are waiting here.
2429 * [Note that this is an expansion of
2430 * PAGE_WAKEUP that uses the THREAD_RESTART
2431 * wait result]. Can't turn off the page's
2432 * busy bit because we're not done with it.
2433 */
2434 if (m->vmp_wanted) {
2435 m->vmp_wanted = FALSE;
2436 thread_wakeup_with_result((event_t) m, THREAD_RESTART);
2437 }
2438 }
2439 /*
2440 * The reference count on copy_object must be
2441 * at least 2: one for our extra reference,
2442 * and at least one from the outside world
2443 * (we checked that when we last locked
2444 * copy_object).
2445 */
2446 vm_object_lock_assert_exclusive(copy_object);
2447 copy_object->ref_count--;
2448 assert(copy_object->ref_count > 0);
2449
2450 vm_object_unlock(copy_object);
2451
2452 break;
2453 }
2454
2455 done:
2456 *result_page = m;
2457 *top_page = first_m;
2458
2459 if (m != VM_PAGE_NULL) {
2460 assert(VM_PAGE_OBJECT(m) == object);
2461
2462 retval = VM_FAULT_SUCCESS;
2463
2464 if (my_fault == DBG_PAGEIN_FAULT) {
2465 VM_PAGE_COUNT_AS_PAGEIN(m);
2466
2467 if (object->internal) {
2468 my_fault = DBG_PAGEIND_FAULT;
2469 } else {
2470 my_fault = DBG_PAGEINV_FAULT;
2471 }
2472
2473 /*
2474 * evaluate access pattern and update state
2475 * vm_fault_deactivate_behind depends on the
2476 * state being up to date
2477 */
2478 vm_fault_is_sequential(object, offset, fault_info->behavior);
2479 vm_fault_deactivate_behind(object, offset, fault_info->behavior);
2480 } else if (type_of_fault == NULL && my_fault == DBG_CACHE_HIT_FAULT) {
2481 /*
2482 * we weren't called from vm_fault, so handle the
2483 * accounting here for hits in the cache
2484 */
2485 if (m->vmp_clustered) {
2486 VM_PAGE_COUNT_AS_PAGEIN(m);
2487 VM_PAGE_CONSUME_CLUSTERED(m);
2488 }
2489 vm_fault_is_sequential(object, offset, fault_info->behavior);
2490 vm_fault_deactivate_behind(object, offset, fault_info->behavior);
2491 } else if (my_fault == DBG_COMPRESSOR_FAULT || my_fault == DBG_COMPRESSOR_SWAPIN_FAULT) {
2492 VM_STAT_DECOMPRESSIONS();
2493 }
2494 if (type_of_fault) {
2495 *type_of_fault = my_fault;
2496 }
2497 } else {
2498 ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_SUCCESS_NO_PAGE), 0 /* arg */);
2499 retval = VM_FAULT_SUCCESS_NO_VM_PAGE;
2500 assert(first_m == VM_PAGE_NULL);
2501 assert(object == first_object);
2502 }
2503
2504 thread_interrupt_level(interruptible_state);
2505
2506 #if TRACEFAULTPAGE
2507 dbgTrace(0xBEEF001A, (unsigned int) VM_FAULT_SUCCESS, 0); /* (TEST/DEBUG) */
2508 #endif
2509 return retval;
2510
2511 backoff:
2512 thread_interrupt_level(interruptible_state);
2513
2514 if (wait_result == THREAD_INTERRUPTED) {
2515 ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_FAULT_INTERRUPTED), 0 /* arg */);
2516 return VM_FAULT_INTERRUPTED;
2517 }
2518 return VM_FAULT_RETRY;
2519
2520 #undef RELEASE_PAGE
2521 }
2522
2523 #if MACH_ASSERT && (XNU_PLATFORM_WatchOS || __x86_64__)
2524 #define PANIC_ON_CS_KILLED_DEFAULT true
2525 #else
2526 #define PANIC_ON_CS_KILLED_DEFAULT false
2527 #endif
2528 static TUNABLE(bool, panic_on_cs_killed, "panic_on_cs_killed",
2529 PANIC_ON_CS_KILLED_DEFAULT);
2530
2531 extern int proc_selfpid(void);
2532 extern char *proc_name_address(void *p);
2533 unsigned long cs_enter_tainted_rejected = 0;
2534 unsigned long cs_enter_tainted_accepted = 0;
2535
2536 /*
2537 * CODE SIGNING:
2538 * When soft faulting a page, we have to validate the page if:
2539 * 1. the page is being mapped in user space
2540 * 2. the page hasn't already been found to be "tainted"
2541 * 3. the page belongs to a code-signed object
2542 * 4. the page has not been validated yet or has been mapped for write.
2543 */
2544 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)2545 vm_fault_cs_need_validation(
2546 pmap_t pmap,
2547 vm_page_t page,
2548 vm_object_t page_obj,
2549 vm_map_size_t fault_page_size,
2550 vm_map_offset_t fault_phys_offset)
2551 {
2552 if (pmap == kernel_pmap) {
2553 /* 1 - not user space */
2554 return false;
2555 }
2556 if (!page_obj->code_signed) {
2557 /* 3 - page does not belong to a code-signed object */
2558 return false;
2559 }
2560 if (fault_page_size == PAGE_SIZE) {
2561 /* looking at the whole page */
2562 assertf(fault_phys_offset == 0,
2563 "fault_page_size 0x%llx fault_phys_offset 0x%llx\n",
2564 (uint64_t)fault_page_size,
2565 (uint64_t)fault_phys_offset);
2566 if (page->vmp_cs_tainted == VMP_CS_ALL_TRUE) {
2567 /* 2 - page is all tainted */
2568 return false;
2569 }
2570 if (page->vmp_cs_validated == VMP_CS_ALL_TRUE &&
2571 !page->vmp_wpmapped) {
2572 /* 4 - already fully validated and never mapped writable */
2573 return false;
2574 }
2575 } else {
2576 /* looking at a specific sub-page */
2577 if (VMP_CS_TAINTED(page, fault_page_size, fault_phys_offset)) {
2578 /* 2 - sub-page was already marked as tainted */
2579 return false;
2580 }
2581 if (VMP_CS_VALIDATED(page, fault_page_size, fault_phys_offset) &&
2582 !page->vmp_wpmapped) {
2583 /* 4 - already validated and never mapped writable */
2584 return false;
2585 }
2586 }
2587 /* page needs to be validated */
2588 return true;
2589 }
2590
2591
2592 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)2593 vm_fault_cs_page_immutable(
2594 vm_page_t m,
2595 vm_map_size_t fault_page_size,
2596 vm_map_offset_t fault_phys_offset,
2597 vm_prot_t prot __unused)
2598 {
2599 if (VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset)
2600 /*&& ((prot) & VM_PROT_EXECUTE)*/) {
2601 return true;
2602 }
2603 return false;
2604 }
2605
2606 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)2607 vm_fault_cs_page_nx(
2608 vm_page_t m,
2609 vm_map_size_t fault_page_size,
2610 vm_map_offset_t fault_phys_offset)
2611 {
2612 return VMP_CS_NX(m, fault_page_size, fault_phys_offset);
2613 }
2614
2615 /*
2616 * Check if the page being entered into the pmap violates code signing.
2617 */
2618 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)2619 vm_fault_cs_check_violation(
2620 bool cs_bypass,
2621 vm_object_t object,
2622 vm_page_t m,
2623 pmap_t pmap,
2624 vm_prot_t prot,
2625 vm_prot_t caller_prot,
2626 vm_map_size_t fault_page_size,
2627 vm_map_offset_t fault_phys_offset,
2628 vm_object_fault_info_t fault_info,
2629 bool map_is_switched,
2630 bool map_is_switch_protected,
2631 bool *cs_violation)
2632 {
2633 #if !CODE_SIGNING_MONITOR
2634 #pragma unused(caller_prot)
2635 #pragma unused(fault_info)
2636 #endif /* !CODE_SIGNING_MONITOR */
2637
2638 int cs_enforcement_enabled;
2639 if (!cs_bypass &&
2640 vm_fault_cs_need_validation(pmap, m, object,
2641 fault_page_size, fault_phys_offset)) {
2642 vm_object_lock_assert_exclusive(object);
2643
2644 if (VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset)) {
2645 vm_cs_revalidates++;
2646 }
2647
2648 /* VM map is locked, so 1 ref will remain on VM object -
2649 * so no harm if vm_page_validate_cs drops the object lock */
2650
2651 #if CODE_SIGNING_MONITOR
2652 if (fault_info->csm_associated &&
2653 csm_enabled() &&
2654 !VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset) &&
2655 !VMP_CS_TAINTED(m, fault_page_size, fault_phys_offset) &&
2656 !VMP_CS_NX(m, fault_page_size, fault_phys_offset) &&
2657 (prot & VM_PROT_EXECUTE) &&
2658 (caller_prot & VM_PROT_EXECUTE)) {
2659 /*
2660 * When we have a code signing monitor, the monitor will evaluate the code signature
2661 * for any executable page mapping. No need for the VM to also validate the page.
2662 * In the code signing monitor we trust :)
2663 */
2664 vm_cs_defer_to_csm++;
2665 } else {
2666 vm_cs_defer_to_csm_not++;
2667 vm_page_validate_cs(m, fault_page_size, fault_phys_offset);
2668 }
2669 #else /* CODE_SIGNING_MONITOR */
2670 vm_page_validate_cs(m, fault_page_size, fault_phys_offset);
2671 #endif /* CODE_SIGNING_MONITOR */
2672 }
2673
2674 /* If the map is switched, and is switch-protected, we must protect
2675 * some pages from being write-faulted: immutable pages because by
2676 * definition they may not be written, and executable pages because that
2677 * would provide a way to inject unsigned code.
2678 * If the page is immutable, we can simply return. However, we can't
2679 * immediately determine whether a page is executable anywhere. But,
2680 * we can disconnect it everywhere and remove the executable protection
2681 * from the current map. We do that below right before we do the
2682 * PMAP_ENTER.
2683 */
2684 if (pmap == kernel_pmap) {
2685 /* kernel fault: cs_enforcement does not apply */
2686 cs_enforcement_enabled = 0;
2687 } else {
2688 cs_enforcement_enabled = pmap_get_vm_map_cs_enforced(pmap);
2689 }
2690
2691 if (cs_enforcement_enabled && map_is_switched &&
2692 map_is_switch_protected &&
2693 vm_fault_cs_page_immutable(m, fault_page_size, fault_phys_offset, prot) &&
2694 (prot & VM_PROT_WRITE)) {
2695 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 */);
2696 return KERN_CODESIGN_ERROR;
2697 }
2698
2699 if (cs_enforcement_enabled &&
2700 vm_fault_cs_page_nx(m, fault_page_size, fault_phys_offset) &&
2701 (prot & VM_PROT_EXECUTE)) {
2702 if (cs_debug) {
2703 printf("page marked to be NX, not letting it be mapped EXEC\n");
2704 }
2705 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 */);
2706 return KERN_CODESIGN_ERROR;
2707 }
2708
2709 /* A page could be tainted, or pose a risk of being tainted later.
2710 * Check whether the receiving process wants it, and make it feel
2711 * the consequences (that hapens in cs_invalid_page()).
2712 * For CS Enforcement, two other conditions will
2713 * cause that page to be tainted as well:
2714 * - pmapping an unsigned page executable - this means unsigned code;
2715 * - writeable mapping of a validated page - the content of that page
2716 * can be changed without the kernel noticing, therefore unsigned
2717 * code can be created
2718 */
2719 if (cs_bypass) {
2720 /* code-signing is bypassed */
2721 *cs_violation = FALSE;
2722 } else if (VMP_CS_TAINTED(m, fault_page_size, fault_phys_offset)) {
2723 /* tainted page */
2724 *cs_violation = TRUE;
2725 } else if (!cs_enforcement_enabled) {
2726 /* no further code-signing enforcement */
2727 *cs_violation = FALSE;
2728 } else if (vm_fault_cs_page_immutable(m, fault_page_size, fault_phys_offset, prot) &&
2729 ((prot & VM_PROT_WRITE) ||
2730 m->vmp_wpmapped)) {
2731 /*
2732 * The page should be immutable, but is in danger of being
2733 * modified.
2734 * This is the case where we want policy from the code
2735 * directory - is the page immutable or not? For now we have
2736 * to assume that code pages will be immutable, data pages not.
2737 * We'll assume a page is a code page if it has a code directory
2738 * and we fault for execution.
2739 * That is good enough since if we faulted the code page for
2740 * writing in another map before, it is wpmapped; if we fault
2741 * it for writing in this map later it will also be faulted for
2742 * executing at the same time; and if we fault for writing in
2743 * another map later, we will disconnect it from this pmap so
2744 * we'll notice the change.
2745 */
2746 *cs_violation = TRUE;
2747 } else if (!VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset) &&
2748 (prot & VM_PROT_EXECUTE)
2749 #if CODE_SIGNING_MONITOR
2750 /*
2751 * Executable pages will be validated by the code signing monitor. If the
2752 * code signing monitor is turned off, then this is a code-signing violation.
2753 */
2754 && !csm_enabled()
2755 #endif /* CODE_SIGNING_MONITOR */
2756 ) {
2757 *cs_violation = TRUE;
2758 } else {
2759 *cs_violation = FALSE;
2760 }
2761 return KERN_SUCCESS;
2762 }
2763
2764 /*
2765 * Handles a code signing violation by either rejecting the page or forcing a disconnect.
2766 * @param must_disconnect This value will be set to true if the caller must disconnect
2767 * this page.
2768 * @return If this function does not return KERN_SUCCESS, the caller must abort the page fault.
2769 */
2770 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)2771 vm_fault_cs_handle_violation(
2772 vm_object_t object,
2773 vm_page_t m,
2774 pmap_t pmap,
2775 vm_prot_t prot,
2776 vm_map_offset_t vaddr,
2777 vm_map_size_t fault_page_size,
2778 vm_map_offset_t fault_phys_offset,
2779 bool map_is_switched,
2780 bool map_is_switch_protected,
2781 bool *must_disconnect)
2782 {
2783 #if !MACH_ASSERT
2784 #pragma unused(pmap)
2785 #pragma unused(map_is_switch_protected)
2786 #endif /* !MACH_ASSERT */
2787 /*
2788 * We will have a tainted page. Have to handle the special case
2789 * of a switched map now. If the map is not switched, standard
2790 * procedure applies - call cs_invalid_page().
2791 * If the map is switched, the real owner is invalid already.
2792 * There is no point in invalidating the switching process since
2793 * it will not be executing from the map. So we don't call
2794 * cs_invalid_page() in that case.
2795 */
2796 boolean_t reject_page, cs_killed;
2797 kern_return_t kr;
2798 if (map_is_switched) {
2799 assert(pmap == vm_map_pmap(current_thread()->map));
2800 assert(!(prot & VM_PROT_WRITE) || (map_is_switch_protected == FALSE));
2801 reject_page = FALSE;
2802 } else {
2803 if (cs_debug > 5) {
2804 printf("vm_fault: signed: %s validate: %s tainted: %s wpmapped: %s prot: 0x%x\n",
2805 object->code_signed ? "yes" : "no",
2806 VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset) ? "yes" : "no",
2807 VMP_CS_TAINTED(m, fault_page_size, fault_phys_offset) ? "yes" : "no",
2808 m->vmp_wpmapped ? "yes" : "no",
2809 (int)prot);
2810 }
2811 reject_page = cs_invalid_page((addr64_t) vaddr, &cs_killed);
2812 }
2813
2814 if (reject_page) {
2815 /* reject the invalid page: abort the page fault */
2816 int pid;
2817 const char *procname;
2818 task_t task;
2819 vm_object_t file_object, shadow;
2820 vm_object_offset_t file_offset;
2821 char *pathname, *filename;
2822 vm_size_t pathname_len, filename_len;
2823 boolean_t truncated_path;
2824 #define __PATH_MAX 1024
2825 struct timespec mtime, cs_mtime;
2826 int shadow_depth;
2827 os_reason_t codesigning_exit_reason = OS_REASON_NULL;
2828
2829 kr = KERN_CODESIGN_ERROR;
2830 cs_enter_tainted_rejected++;
2831
2832 /* get process name and pid */
2833 procname = "?";
2834 task = current_task();
2835 pid = proc_selfpid();
2836 if (get_bsdtask_info(task) != NULL) {
2837 procname = proc_name_address(get_bsdtask_info(task));
2838 }
2839
2840 /* get file's VM object */
2841 file_object = object;
2842 file_offset = m->vmp_offset;
2843 for (shadow = file_object->shadow,
2844 shadow_depth = 0;
2845 shadow != VM_OBJECT_NULL;
2846 shadow = file_object->shadow,
2847 shadow_depth++) {
2848 vm_object_lock_shared(shadow);
2849 if (file_object != object) {
2850 vm_object_unlock(file_object);
2851 }
2852 file_offset += file_object->vo_shadow_offset;
2853 file_object = shadow;
2854 }
2855
2856 mtime.tv_sec = 0;
2857 mtime.tv_nsec = 0;
2858 cs_mtime.tv_sec = 0;
2859 cs_mtime.tv_nsec = 0;
2860
2861 /* get file's pathname and/or filename */
2862 pathname = NULL;
2863 filename = NULL;
2864 pathname_len = 0;
2865 filename_len = 0;
2866 truncated_path = FALSE;
2867 /* no pager -> no file -> no pathname, use "<nil>" in that case */
2868 if (file_object->pager != NULL) {
2869 pathname = kalloc_data(__PATH_MAX * 2, Z_WAITOK);
2870 if (pathname) {
2871 pathname[0] = '\0';
2872 pathname_len = __PATH_MAX;
2873 filename = pathname + pathname_len;
2874 filename_len = __PATH_MAX;
2875
2876 if (vnode_pager_get_object_name(file_object->pager,
2877 pathname,
2878 pathname_len,
2879 filename,
2880 filename_len,
2881 &truncated_path) == KERN_SUCCESS) {
2882 /* safety first... */
2883 pathname[__PATH_MAX - 1] = '\0';
2884 filename[__PATH_MAX - 1] = '\0';
2885
2886 vnode_pager_get_object_mtime(file_object->pager,
2887 &mtime,
2888 &cs_mtime);
2889 } else {
2890 kfree_data(pathname, __PATH_MAX * 2);
2891 pathname = NULL;
2892 filename = NULL;
2893 pathname_len = 0;
2894 filename_len = 0;
2895 truncated_path = FALSE;
2896 }
2897 }
2898 }
2899 printf("CODE SIGNING: process %d[%s]: "
2900 "rejecting invalid page at address 0x%llx "
2901 "from offset 0x%llx in file \"%s%s%s\" "
2902 "(cs_mtime:%lu.%ld %s mtime:%lu.%ld) "
2903 "(signed:%d validated:%d tainted:%d nx:%d "
2904 "wpmapped:%d dirty:%d depth:%d)\n",
2905 pid, procname, (addr64_t) vaddr,
2906 file_offset,
2907 (pathname ? pathname : "<nil>"),
2908 (truncated_path ? "/.../" : ""),
2909 (truncated_path ? filename : ""),
2910 cs_mtime.tv_sec, cs_mtime.tv_nsec,
2911 ((cs_mtime.tv_sec == mtime.tv_sec &&
2912 cs_mtime.tv_nsec == mtime.tv_nsec)
2913 ? "=="
2914 : "!="),
2915 mtime.tv_sec, mtime.tv_nsec,
2916 object->code_signed,
2917 VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset),
2918 VMP_CS_TAINTED(m, fault_page_size, fault_phys_offset),
2919 VMP_CS_NX(m, fault_page_size, fault_phys_offset),
2920 m->vmp_wpmapped,
2921 m->vmp_dirty,
2922 shadow_depth);
2923
2924 /*
2925 * We currently only generate an exit reason if cs_invalid_page directly killed a process. If cs_invalid_page
2926 * did not kill the process (more the case on desktop), vm_fault_enter will not satisfy the fault and whether the
2927 * process dies is dependent on whether there is a signal handler registered for SIGSEGV and how that handler
2928 * will deal with the segmentation fault.
2929 */
2930 if (cs_killed) {
2931 KDBG(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2932 pid, OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_INVALID_PAGE);
2933
2934 codesigning_exit_reason = os_reason_create(OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_INVALID_PAGE);
2935 if (codesigning_exit_reason == NULL) {
2936 printf("vm_fault_enter: failed to allocate codesigning exit reason\n");
2937 } else {
2938 mach_vm_address_t data_addr = 0;
2939 struct codesigning_exit_reason_info *ceri = NULL;
2940 uint32_t reason_buffer_size_estimate = kcdata_estimate_required_buffer_size(1, sizeof(*ceri));
2941
2942 if (os_reason_alloc_buffer_noblock(codesigning_exit_reason, reason_buffer_size_estimate)) {
2943 printf("vm_fault_enter: failed to allocate buffer for codesigning exit reason\n");
2944 } else {
2945 if (KERN_SUCCESS == kcdata_get_memory_addr(&codesigning_exit_reason->osr_kcd_descriptor,
2946 EXIT_REASON_CODESIGNING_INFO, sizeof(*ceri), &data_addr)) {
2947 ceri = (struct codesigning_exit_reason_info *)data_addr;
2948 static_assert(__PATH_MAX == sizeof(ceri->ceri_pathname));
2949
2950 ceri->ceri_virt_addr = vaddr;
2951 ceri->ceri_file_offset = file_offset;
2952 if (pathname) {
2953 strncpy((char *)&ceri->ceri_pathname, pathname, sizeof(ceri->ceri_pathname));
2954 } else {
2955 ceri->ceri_pathname[0] = '\0';
2956 }
2957 if (filename) {
2958 strncpy((char *)&ceri->ceri_filename, filename, sizeof(ceri->ceri_filename));
2959 } else {
2960 ceri->ceri_filename[0] = '\0';
2961 }
2962 ceri->ceri_path_truncated = (truncated_path ? 1 : 0);
2963 ceri->ceri_codesig_modtime_secs = cs_mtime.tv_sec;
2964 ceri->ceri_codesig_modtime_nsecs = cs_mtime.tv_nsec;
2965 ceri->ceri_page_modtime_secs = mtime.tv_sec;
2966 ceri->ceri_page_modtime_nsecs = mtime.tv_nsec;
2967 ceri->ceri_object_codesigned = (object->code_signed);
2968 ceri->ceri_page_codesig_validated = VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset);
2969 ceri->ceri_page_codesig_tainted = VMP_CS_TAINTED(m, fault_page_size, fault_phys_offset);
2970 ceri->ceri_page_codesig_nx = VMP_CS_NX(m, fault_page_size, fault_phys_offset);
2971 ceri->ceri_page_wpmapped = (m->vmp_wpmapped);
2972 ceri->ceri_page_slid = 0;
2973 ceri->ceri_page_dirty = (m->vmp_dirty);
2974 ceri->ceri_page_shadow_depth = shadow_depth;
2975 } else {
2976 #if DEBUG || DEVELOPMENT
2977 panic("vm_fault_enter: failed to allocate kcdata for codesigning exit reason");
2978 #else
2979 printf("vm_fault_enter: failed to allocate kcdata for codesigning exit reason\n");
2980 #endif /* DEBUG || DEVELOPMENT */
2981 /* Free the buffer */
2982 os_reason_alloc_buffer_noblock(codesigning_exit_reason, 0);
2983 }
2984 }
2985 }
2986
2987 set_thread_exit_reason(current_thread(), codesigning_exit_reason, FALSE);
2988 }
2989 if (panic_on_cs_killed &&
2990 object->object_is_shared_cache) {
2991 char *tainted_contents;
2992 vm_map_offset_t src_vaddr;
2993 src_vaddr = (vm_map_offset_t) phystokv((pmap_paddr_t)VM_PAGE_GET_PHYS_PAGE(m) << PAGE_SHIFT);
2994 tainted_contents = kalloc_data(PAGE_SIZE, Z_WAITOK);
2995 bcopy((const char *)src_vaddr, tainted_contents, PAGE_SIZE);
2996 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);
2997 panic("CODE SIGNING: process %d[%s]: "
2998 "rejecting invalid page (phys#0x%x) at address 0x%llx "
2999 "from offset 0x%llx in file \"%s%s%s\" "
3000 "(cs_mtime:%lu.%ld %s mtime:%lu.%ld) "
3001 "(signed:%d validated:%d tainted:%d nx:%d"
3002 "wpmapped:%d dirty:%d depth:%d)\n",
3003 pid, procname,
3004 VM_PAGE_GET_PHYS_PAGE(m),
3005 (addr64_t) vaddr,
3006 file_offset,
3007 (pathname ? pathname : "<nil>"),
3008 (truncated_path ? "/.../" : ""),
3009 (truncated_path ? filename : ""),
3010 cs_mtime.tv_sec, cs_mtime.tv_nsec,
3011 ((cs_mtime.tv_sec == mtime.tv_sec &&
3012 cs_mtime.tv_nsec == mtime.tv_nsec)
3013 ? "=="
3014 : "!="),
3015 mtime.tv_sec, mtime.tv_nsec,
3016 object->code_signed,
3017 VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset),
3018 VMP_CS_TAINTED(m, fault_page_size, fault_phys_offset),
3019 VMP_CS_NX(m, fault_page_size, fault_phys_offset),
3020 m->vmp_wpmapped,
3021 m->vmp_dirty,
3022 shadow_depth);
3023 }
3024
3025 if (file_object != object) {
3026 vm_object_unlock(file_object);
3027 }
3028 if (pathname_len != 0) {
3029 kfree_data(pathname, __PATH_MAX * 2);
3030 pathname = NULL;
3031 filename = NULL;
3032 }
3033 } else {
3034 /* proceed with the invalid page */
3035 kr = KERN_SUCCESS;
3036 if (!VMP_CS_VALIDATED(m, fault_page_size, fault_phys_offset) &&
3037 !object->code_signed) {
3038 /*
3039 * This page has not been (fully) validated but
3040 * does not belong to a code-signed object
3041 * so it should not be forcefully considered
3042 * as tainted.
3043 * We're just concerned about it here because
3044 * we've been asked to "execute" it but that
3045 * does not mean that it should cause other
3046 * accesses to fail.
3047 * This happens when a debugger sets a
3048 * breakpoint and we then execute code in
3049 * that page. Marking the page as "tainted"
3050 * would cause any inspection tool ("leaks",
3051 * "vmmap", "CrashReporter", ...) to get killed
3052 * due to code-signing violation on that page,
3053 * even though they're just reading it and not
3054 * executing from it.
3055 */
3056 } else {
3057 /*
3058 * Page might have been tainted before or not;
3059 * now it definitively is. If the page wasn't
3060 * tainted, we must disconnect it from all
3061 * pmaps later, to force existing mappings
3062 * through that code path for re-consideration
3063 * of the validity of that page.
3064 */
3065 if (!VMP_CS_TAINTED(m, fault_page_size, fault_phys_offset)) {
3066 *must_disconnect = TRUE;
3067 VMP_CS_SET_TAINTED(m, fault_page_size, fault_phys_offset, TRUE);
3068 }
3069 }
3070 cs_enter_tainted_accepted++;
3071 }
3072 if (kr != KERN_SUCCESS) {
3073 if (cs_debug) {
3074 printf("CODESIGNING: vm_fault_enter(0x%llx): "
3075 "*** INVALID PAGE ***\n",
3076 (long long)vaddr);
3077 }
3078 #if !SECURE_KERNEL
3079 if (cs_enforcement_panic) {
3080 panic("CODESIGNING: panicking on invalid page");
3081 }
3082 #endif
3083 }
3084 return kr;
3085 }
3086
3087 /*
3088 * Check that the code signature is valid for the given page being inserted into
3089 * the pmap.
3090 *
3091 * @param must_disconnect This value will be set to true if the caller must disconnect
3092 * this page.
3093 * @return If this function does not return KERN_SUCCESS, the caller must abort the page fault.
3094 */
3095 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)3096 vm_fault_validate_cs(
3097 bool cs_bypass,
3098 vm_object_t object,
3099 vm_page_t m,
3100 pmap_t pmap,
3101 vm_map_offset_t vaddr,
3102 vm_prot_t prot,
3103 vm_prot_t caller_prot,
3104 vm_map_size_t fault_page_size,
3105 vm_map_offset_t fault_phys_offset,
3106 vm_object_fault_info_t fault_info,
3107 bool *must_disconnect)
3108 {
3109 bool map_is_switched, map_is_switch_protected, cs_violation;
3110 kern_return_t kr;
3111 /* Validate code signature if necessary. */
3112 map_is_switched = ((pmap != vm_map_pmap(current_task()->map)) &&
3113 (pmap == vm_map_pmap(current_thread()->map)));
3114 map_is_switch_protected = current_thread()->map->switch_protect;
3115 kr = vm_fault_cs_check_violation(cs_bypass, object, m, pmap,
3116 prot, caller_prot, fault_page_size, fault_phys_offset, fault_info,
3117 map_is_switched, map_is_switch_protected, &cs_violation);
3118 if (kr != KERN_SUCCESS) {
3119 return kr;
3120 }
3121 if (cs_violation) {
3122 kr = vm_fault_cs_handle_violation(object, m, pmap, prot, vaddr,
3123 fault_page_size, fault_phys_offset,
3124 map_is_switched, map_is_switch_protected, must_disconnect);
3125 }
3126 return kr;
3127 }
3128
3129 /*
3130 * Enqueue the page on the appropriate paging queue.
3131 */
3132 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)3133 vm_fault_enqueue_page(
3134 vm_object_t object,
3135 vm_page_t m,
3136 bool wired,
3137 bool change_wiring,
3138 vm_tag_t wire_tag,
3139 bool no_cache,
3140 int *type_of_fault,
3141 kern_return_t kr)
3142 {
3143 assert((m->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) || object != compressor_object);
3144 boolean_t page_queues_locked = FALSE;
3145 boolean_t previously_pmapped = m->vmp_pmapped;
3146 #define __VM_PAGE_LOCKSPIN_QUEUES_IF_NEEDED() \
3147 MACRO_BEGIN \
3148 if (! page_queues_locked) { \
3149 page_queues_locked = TRUE; \
3150 vm_page_lockspin_queues(); \
3151 } \
3152 MACRO_END
3153 #define __VM_PAGE_UNLOCK_QUEUES_IF_NEEDED() \
3154 MACRO_BEGIN \
3155 if (page_queues_locked) { \
3156 page_queues_locked = FALSE; \
3157 vm_page_unlock_queues(); \
3158 } \
3159 MACRO_END
3160
3161 vm_page_update_special_state(m);
3162 if (m->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) {
3163 /*
3164 * Compressor pages are neither wired
3165 * nor pageable and should never change.
3166 */
3167 assert(object == compressor_object);
3168 } else if (change_wiring) {
3169 __VM_PAGE_LOCKSPIN_QUEUES_IF_NEEDED();
3170
3171 if (wired) {
3172 if (kr == KERN_SUCCESS) {
3173 vm_page_wire(m, wire_tag, TRUE);
3174 }
3175 } else {
3176 vm_page_unwire(m, TRUE);
3177 }
3178 /* we keep the page queues lock, if we need it later */
3179 } else {
3180 if (object->internal == TRUE) {
3181 /*
3182 * don't allow anonymous pages on
3183 * the speculative queues
3184 */
3185 no_cache = FALSE;
3186 }
3187 if (kr != KERN_SUCCESS) {
3188 __VM_PAGE_LOCKSPIN_QUEUES_IF_NEEDED();
3189 vm_page_deactivate(m);
3190 /* we keep the page queues lock, if we need it later */
3191 } else if (((m->vmp_q_state == VM_PAGE_NOT_ON_Q) ||
3192 (m->vmp_q_state == VM_PAGE_ON_SPECULATIVE_Q) ||
3193 (m->vmp_q_state == VM_PAGE_ON_INACTIVE_CLEANED_Q) ||
3194 ((m->vmp_q_state != VM_PAGE_ON_THROTTLED_Q) && no_cache)) &&
3195 !VM_PAGE_WIRED(m)) {
3196 if (vm_page_local_q &&
3197 (*type_of_fault == DBG_COW_FAULT ||
3198 *type_of_fault == DBG_ZERO_FILL_FAULT)) {
3199 struct vpl *lq;
3200 uint32_t lid;
3201
3202 assert(m->vmp_q_state == VM_PAGE_NOT_ON_Q);
3203
3204 __VM_PAGE_UNLOCK_QUEUES_IF_NEEDED();
3205 vm_object_lock_assert_exclusive(object);
3206
3207 /*
3208 * we got a local queue to stuff this
3209 * new page on...
3210 * its safe to manipulate local and
3211 * local_id at this point since we're
3212 * behind an exclusive object lock and
3213 * the page is not on any global queue.
3214 *
3215 * we'll use the current cpu number to
3216 * select the queue note that we don't
3217 * need to disable preemption... we're
3218 * going to be behind the local queue's
3219 * lock to do the real work
3220 */
3221 lid = cpu_number();
3222
3223 lq = zpercpu_get_cpu(vm_page_local_q, lid);
3224
3225 VPL_LOCK(&lq->vpl_lock);
3226
3227 vm_page_check_pageable_safe(m);
3228 vm_page_queue_enter(&lq->vpl_queue, m, vmp_pageq);
3229 m->vmp_q_state = VM_PAGE_ON_ACTIVE_LOCAL_Q;
3230 m->vmp_local_id = lid;
3231 lq->vpl_count++;
3232
3233 if (object->internal) {
3234 lq->vpl_internal_count++;
3235 } else {
3236 lq->vpl_external_count++;
3237 }
3238
3239 VPL_UNLOCK(&lq->vpl_lock);
3240
3241 if (lq->vpl_count > vm_page_local_q_soft_limit) {
3242 /*
3243 * we're beyond the soft limit
3244 * for the local queue
3245 * vm_page_reactivate_local will
3246 * 'try' to take the global page
3247 * queue lock... if it can't
3248 * that's ok... we'll let the
3249 * queue continue to grow up
3250 * to the hard limit... at that
3251 * point we'll wait for the
3252 * lock... once we've got the
3253 * lock, we'll transfer all of
3254 * the pages from the local
3255 * queue to the global active
3256 * queue
3257 */
3258 vm_page_reactivate_local(lid, FALSE, FALSE);
3259 }
3260 } else {
3261 __VM_PAGE_LOCKSPIN_QUEUES_IF_NEEDED();
3262
3263 /*
3264 * test again now that we hold the
3265 * page queue lock
3266 */
3267 if (!VM_PAGE_WIRED(m)) {
3268 if (m->vmp_q_state == VM_PAGE_ON_INACTIVE_CLEANED_Q) {
3269 vm_page_queues_remove(m, FALSE);
3270
3271 VM_PAGEOUT_DEBUG(vm_pageout_cleaned_reactivated, 1);
3272 VM_PAGEOUT_DEBUG(vm_pageout_cleaned_fault_reactivated, 1);
3273 }
3274
3275 if (!VM_PAGE_ACTIVE_OR_INACTIVE(m) ||
3276 no_cache) {
3277 /*
3278 * If this is a no_cache mapping
3279 * and the page has never been
3280 * mapped before or was
3281 * previously a no_cache page,
3282 * then we want to leave pages
3283 * in the speculative state so
3284 * that they can be readily
3285 * recycled if free memory runs
3286 * low. Otherwise the page is
3287 * activated as normal.
3288 */
3289
3290 if (no_cache &&
3291 (!previously_pmapped ||
3292 m->vmp_no_cache)) {
3293 m->vmp_no_cache = TRUE;
3294
3295 if (m->vmp_q_state != VM_PAGE_ON_SPECULATIVE_Q) {
3296 vm_page_speculate(m, FALSE);
3297 }
3298 } else if (!VM_PAGE_ACTIVE_OR_INACTIVE(m)) {
3299 vm_page_activate(m);
3300 }
3301 }
3302 }
3303 /* we keep the page queues lock, if we need it later */
3304 }
3305 }
3306 }
3307 /* we're done with the page queues lock, if we ever took it */
3308 __VM_PAGE_UNLOCK_QUEUES_IF_NEEDED();
3309 }
3310
3311 /*
3312 * Sets the pmmpped, xpmapped, and wpmapped bits on the vm_page_t and updates accounting.
3313 * @return true if the page needs to be sync'ed via pmap_sync-page_data_physo
3314 * before being inserted into the pmap.
3315 */
3316 static bool
vm_fault_enter_set_mapped(vm_object_t object,vm_page_t m,vm_prot_t prot,vm_prot_t fault_type)3317 vm_fault_enter_set_mapped(
3318 vm_object_t object,
3319 vm_page_t m,
3320 vm_prot_t prot,
3321 vm_prot_t fault_type)
3322 {
3323 bool page_needs_sync = false;
3324 /*
3325 * NOTE: we may only hold the vm_object lock SHARED
3326 * at this point, so we need the phys_page lock to
3327 * properly serialize updating the pmapped and
3328 * xpmapped bits
3329 */
3330 if ((prot & VM_PROT_EXECUTE) && !m->vmp_xpmapped) {
3331 ppnum_t phys_page = VM_PAGE_GET_PHYS_PAGE(m);
3332
3333 pmap_lock_phys_page(phys_page);
3334 m->vmp_pmapped = TRUE;
3335
3336 if (!m->vmp_xpmapped) {
3337 m->vmp_xpmapped = TRUE;
3338
3339 pmap_unlock_phys_page(phys_page);
3340
3341 if (!object->internal) {
3342 OSAddAtomic(1, &vm_page_xpmapped_external_count);
3343 }
3344
3345 #if defined(__arm64__)
3346 page_needs_sync = true;
3347 #else
3348 if (object->internal &&
3349 object->pager != NULL) {
3350 /*
3351 * This page could have been
3352 * uncompressed by the
3353 * compressor pager and its
3354 * contents might be only in
3355 * the data cache.
3356 * Since it's being mapped for
3357 * "execute" for the fist time,
3358 * make sure the icache is in
3359 * sync.
3360 */
3361 assert(VM_CONFIG_COMPRESSOR_IS_PRESENT);
3362 page_needs_sync = true;
3363 }
3364 #endif
3365 } else {
3366 pmap_unlock_phys_page(phys_page);
3367 }
3368 } else {
3369 if (m->vmp_pmapped == FALSE) {
3370 ppnum_t phys_page = VM_PAGE_GET_PHYS_PAGE(m);
3371
3372 pmap_lock_phys_page(phys_page);
3373 m->vmp_pmapped = TRUE;
3374 pmap_unlock_phys_page(phys_page);
3375 }
3376 }
3377
3378 if (fault_type & VM_PROT_WRITE) {
3379 if (m->vmp_wpmapped == FALSE) {
3380 vm_object_lock_assert_exclusive(object);
3381 if (!object->internal && object->pager) {
3382 task_update_logical_writes(current_task(), PAGE_SIZE, TASK_WRITE_DEFERRED, vnode_pager_lookup_vnode(object->pager));
3383 }
3384 m->vmp_wpmapped = TRUE;
3385 }
3386 }
3387 return page_needs_sync;
3388 }
3389
3390 /*
3391 * Try to enter the given page into the pmap.
3392 * Will retry without execute permission if the code signing monitor is enabled and
3393 * we encounter a codesigning failure on a non-execute fault.
3394 */
3395 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)3396 vm_fault_attempt_pmap_enter(
3397 pmap_t pmap,
3398 vm_map_offset_t vaddr,
3399 vm_map_size_t fault_page_size,
3400 vm_map_offset_t fault_phys_offset,
3401 vm_page_t m,
3402 vm_prot_t *prot,
3403 vm_prot_t caller_prot,
3404 vm_prot_t fault_type,
3405 bool wired,
3406 int pmap_options)
3407 {
3408 #if !CODE_SIGNING_MONITOR
3409 #pragma unused(caller_prot)
3410 #endif /* !CODE_SIGNING_MONITOR */
3411
3412 kern_return_t kr;
3413 if (fault_page_size != PAGE_SIZE) {
3414 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);
3415 assertf((!(fault_phys_offset & FOURK_PAGE_MASK) &&
3416 fault_phys_offset < PAGE_SIZE),
3417 "0x%llx\n", (uint64_t)fault_phys_offset);
3418 } else {
3419 assertf(fault_phys_offset == 0,
3420 "0x%llx\n", (uint64_t)fault_phys_offset);
3421 }
3422
3423 PMAP_ENTER_OPTIONS(pmap, vaddr,
3424 fault_phys_offset,
3425 m, *prot, fault_type, 0,
3426 wired,
3427 pmap_options,
3428 kr);
3429
3430 #if CODE_SIGNING_MONITOR
3431 /*
3432 * Retry without execute permission if we encountered a codesigning
3433 * failure on a non-execute fault. This allows applications which
3434 * don't actually need to execute code to still map it for read access.
3435 */
3436 if ((kr == KERN_CODESIGN_ERROR) && csm_enabled() &&
3437 (*prot & VM_PROT_EXECUTE) && !(caller_prot & VM_PROT_EXECUTE)) {
3438 *prot &= ~VM_PROT_EXECUTE;
3439 PMAP_ENTER_OPTIONS(pmap, vaddr,
3440 fault_phys_offset,
3441 m, *prot, fault_type, 0,
3442 wired,
3443 pmap_options,
3444 kr);
3445 }
3446 #endif /* CODE_SIGNING_MONITOR */
3447
3448 return kr;
3449 }
3450
3451 /*
3452 * Enter the given page into the pmap.
3453 * The map must be locked shared.
3454 * The vm object must NOT be locked.
3455 *
3456 * @param need_retry if not null, avoid making a (potentially) blocking call into
3457 * the pmap layer. When such a call would be necessary, return true in this boolean instead.
3458 */
3459 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)3460 vm_fault_pmap_enter(
3461 pmap_t pmap,
3462 vm_map_offset_t vaddr,
3463 vm_map_size_t fault_page_size,
3464 vm_map_offset_t fault_phys_offset,
3465 vm_page_t m,
3466 vm_prot_t *prot,
3467 vm_prot_t caller_prot,
3468 vm_prot_t fault_type,
3469 bool wired,
3470 int pmap_options,
3471 boolean_t *need_retry)
3472 {
3473 kern_return_t kr;
3474 if (need_retry != NULL) {
3475 /*
3476 * Although we don't hold a lock on this object, we hold a lock
3477 * on the top object in the chain. To prevent a deadlock, we
3478 * can't allow the pmap layer to block.
3479 */
3480 pmap_options |= PMAP_OPTIONS_NOWAIT;
3481 }
3482 kr = vm_fault_attempt_pmap_enter(pmap, vaddr,
3483 fault_page_size, fault_phys_offset,
3484 m, prot, caller_prot, fault_type, wired, pmap_options);
3485 if (kr == KERN_RESOURCE_SHORTAGE) {
3486 if (need_retry) {
3487 /*
3488 * There's nothing we can do here since we hold the
3489 * lock on the top object in the chain. The caller
3490 * will need to deal with this by dropping that lock and retrying.
3491 */
3492 *need_retry = TRUE;
3493 vm_pmap_enter_retried++;
3494 }
3495 }
3496 return kr;
3497 }
3498
3499 /*
3500 * Enter the given page into the pmap.
3501 * The vm map must be locked shared.
3502 * The vm object must be locked exclusive, unless this is a soft fault.
3503 * For a soft fault, the object must be locked shared or exclusive.
3504 *
3505 * @param need_retry if not null, avoid making a (potentially) blocking call into
3506 * the pmap layer. When such a call would be necessary, return true in this boolean instead.
3507 */
3508 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)3509 vm_fault_pmap_enter_with_object_lock(
3510 vm_object_t object,
3511 pmap_t pmap,
3512 vm_map_offset_t vaddr,
3513 vm_map_size_t fault_page_size,
3514 vm_map_offset_t fault_phys_offset,
3515 vm_page_t m,
3516 vm_prot_t *prot,
3517 vm_prot_t caller_prot,
3518 vm_prot_t fault_type,
3519 bool wired,
3520 int pmap_options,
3521 boolean_t *need_retry)
3522 {
3523 kern_return_t kr;
3524 /*
3525 * Prevent a deadlock by not
3526 * holding the object lock if we need to wait for a page in
3527 * pmap_enter() - <rdar://problem/7138958>
3528 */
3529 kr = vm_fault_attempt_pmap_enter(pmap, vaddr,
3530 fault_page_size, fault_phys_offset,
3531 m, prot, caller_prot, fault_type, wired, pmap_options | PMAP_OPTIONS_NOWAIT);
3532 #if __x86_64__
3533 if (kr == KERN_INVALID_ARGUMENT &&
3534 pmap == PMAP_NULL &&
3535 wired) {
3536 /*
3537 * Wiring a page in a pmap-less VM map:
3538 * VMware's "vmmon" kernel extension does this
3539 * to grab pages.
3540 * Let it proceed even though the PMAP_ENTER() failed.
3541 */
3542 kr = KERN_SUCCESS;
3543 }
3544 #endif /* __x86_64__ */
3545
3546 if (kr == KERN_RESOURCE_SHORTAGE) {
3547 if (need_retry) {
3548 /*
3549 * this will be non-null in the case where we hold the lock
3550 * on the top-object in this chain... we can't just drop
3551 * the lock on the object we're inserting the page into
3552 * and recall the PMAP_ENTER since we can still cause
3553 * a deadlock if one of the critical paths tries to
3554 * acquire the lock on the top-object and we're blocked
3555 * in PMAP_ENTER waiting for memory... our only recourse
3556 * is to deal with it at a higher level where we can
3557 * drop both locks.
3558 */
3559 *need_retry = TRUE;
3560 ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_PMAP_ENTER_RESOURCE_SHORTAGE), 0 /* arg */);
3561 vm_pmap_enter_retried++;
3562 goto done;
3563 }
3564 /*
3565 * The nonblocking version of pmap_enter did not succeed.
3566 * and we don't need to drop other locks and retry
3567 * at the level above us, so
3568 * use the blocking version instead. Requires marking
3569 * the page busy and unlocking the object
3570 */
3571 boolean_t was_busy = m->vmp_busy;
3572
3573 vm_object_lock_assert_exclusive(object);
3574
3575 m->vmp_busy = TRUE;
3576 vm_object_unlock(object);
3577
3578 PMAP_ENTER_OPTIONS(pmap, vaddr,
3579 fault_phys_offset,
3580 m, *prot, fault_type,
3581 0, wired,
3582 pmap_options, kr);
3583
3584 assert(VM_PAGE_OBJECT(m) == object);
3585
3586 /* Take the object lock again. */
3587 vm_object_lock(object);
3588
3589 /* If the page was busy, someone else will wake it up.
3590 * Otherwise, we have to do it now. */
3591 assert(m->vmp_busy);
3592 if (!was_busy) {
3593 PAGE_WAKEUP_DONE(m);
3594 }
3595 vm_pmap_enter_blocked++;
3596 }
3597
3598 done:
3599 return kr;
3600 }
3601
3602 /*
3603 * Prepare to enter a page into the pmap by checking CS, protection bits,
3604 * and setting mapped bits on the page_t.
3605 * Does not modify the page's paging queue.
3606 *
3607 * page queue lock must NOT be held
3608 * m->vmp_object must be locked
3609 *
3610 * NOTE: m->vmp_object could be locked "shared" only if we are called
3611 * from vm_fault() as part of a soft fault.
3612 */
3613 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)3614 vm_fault_enter_prepare(
3615 vm_page_t m,
3616 pmap_t pmap,
3617 vm_map_offset_t vaddr,
3618 vm_prot_t *prot,
3619 vm_prot_t caller_prot,
3620 vm_map_size_t fault_page_size,
3621 vm_map_offset_t fault_phys_offset,
3622 boolean_t change_wiring,
3623 vm_prot_t fault_type,
3624 vm_object_fault_info_t fault_info,
3625 int *type_of_fault,
3626 bool *page_needs_data_sync)
3627 {
3628 kern_return_t kr;
3629 bool is_tainted = false;
3630 vm_object_t object;
3631 boolean_t cs_bypass = fault_info->cs_bypass;
3632
3633 object = VM_PAGE_OBJECT(m);
3634
3635 vm_object_lock_assert_held(object);
3636
3637 #if KASAN
3638 if (pmap == kernel_pmap) {
3639 kasan_notify_address(vaddr, PAGE_SIZE);
3640 }
3641 #endif
3642
3643 #if CODE_SIGNING_MONITOR
3644 if (csm_address_space_exempt(pmap) == KERN_SUCCESS) {
3645 cs_bypass = TRUE;
3646 }
3647 #endif
3648
3649 LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_NOTOWNED);
3650
3651 if (*type_of_fault == DBG_ZERO_FILL_FAULT) {
3652 vm_object_lock_assert_exclusive(object);
3653 } else if ((fault_type & VM_PROT_WRITE) == 0 &&
3654 !change_wiring &&
3655 (!m->vmp_wpmapped
3656 #if VM_OBJECT_ACCESS_TRACKING
3657 || object->access_tracking
3658 #endif /* VM_OBJECT_ACCESS_TRACKING */
3659 )) {
3660 /*
3661 * This is not a "write" fault, so we
3662 * might not have taken the object lock
3663 * exclusively and we might not be able
3664 * to update the "wpmapped" bit in
3665 * vm_fault_enter().
3666 * Let's just grant read access to
3667 * the page for now and we'll
3668 * soft-fault again if we need write
3669 * access later...
3670 */
3671
3672 /* This had better not be a JIT page. */
3673 if (!pmap_has_prot_policy(pmap, fault_info->pmap_options & PMAP_OPTIONS_TRANSLATED_ALLOW_EXECUTE, *prot)) {
3674 *prot &= ~VM_PROT_WRITE;
3675 } else {
3676 assert(cs_bypass);
3677 }
3678 }
3679 if (m->vmp_pmapped == FALSE) {
3680 if (m->vmp_clustered) {
3681 if (*type_of_fault == DBG_CACHE_HIT_FAULT) {
3682 /*
3683 * found it in the cache, but this
3684 * is the first fault-in of the page (m->vmp_pmapped == FALSE)
3685 * so it must have come in as part of
3686 * a cluster... account 1 pagein against it
3687 */
3688 if (object->internal) {
3689 *type_of_fault = DBG_PAGEIND_FAULT;
3690 } else {
3691 *type_of_fault = DBG_PAGEINV_FAULT;
3692 }
3693
3694 VM_PAGE_COUNT_AS_PAGEIN(m);
3695 }
3696 VM_PAGE_CONSUME_CLUSTERED(m);
3697 }
3698 }
3699
3700 if (*type_of_fault != DBG_COW_FAULT) {
3701 DTRACE_VM2(as_fault, int, 1, (uint64_t *), NULL);
3702
3703 if (pmap == kernel_pmap) {
3704 DTRACE_VM2(kernel_asflt, int, 1, (uint64_t *), NULL);
3705 }
3706 }
3707
3708 kr = vm_fault_validate_cs(cs_bypass, object, m, pmap, vaddr,
3709 *prot, caller_prot, fault_page_size, fault_phys_offset,
3710 fault_info, &is_tainted);
3711 if (kr == KERN_SUCCESS) {
3712 /*
3713 * We either have a good page, or a tainted page that has been accepted by the process.
3714 * In both cases the page will be entered into the pmap.
3715 */
3716 *page_needs_data_sync = vm_fault_enter_set_mapped(object, m, *prot, fault_type);
3717 if ((fault_type & VM_PROT_WRITE) && is_tainted) {
3718 /*
3719 * This page is tainted but we're inserting it anyways.
3720 * Since it's writeable, we need to disconnect it from other pmaps
3721 * now so those processes can take note.
3722 */
3723
3724 /*
3725 * We can only get here
3726 * because of the CSE logic
3727 */
3728 assert(pmap_get_vm_map_cs_enforced(pmap));
3729 pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(m));
3730 /*
3731 * If we are faulting for a write, we can clear
3732 * the execute bit - that will ensure the page is
3733 * checked again before being executable, which
3734 * protects against a map switch.
3735 * This only happens the first time the page
3736 * gets tainted, so we won't get stuck here
3737 * to make an already writeable page executable.
3738 */
3739 if (!cs_bypass) {
3740 assert(!pmap_has_prot_policy(pmap, fault_info->pmap_options & PMAP_OPTIONS_TRANSLATED_ALLOW_EXECUTE, *prot));
3741 *prot &= ~VM_PROT_EXECUTE;
3742 }
3743 }
3744 assert(VM_PAGE_OBJECT(m) == object);
3745
3746 #if VM_OBJECT_ACCESS_TRACKING
3747 if (object->access_tracking) {
3748 DTRACE_VM2(access_tracking, vm_map_offset_t, vaddr, int, fault_type);
3749 if (fault_type & VM_PROT_WRITE) {
3750 object->access_tracking_writes++;
3751 vm_object_access_tracking_writes++;
3752 } else {
3753 object->access_tracking_reads++;
3754 vm_object_access_tracking_reads++;
3755 }
3756 }
3757 #endif /* VM_OBJECT_ACCESS_TRACKING */
3758 }
3759
3760 return kr;
3761 }
3762
3763 /*
3764 * page queue lock must NOT be held
3765 * m->vmp_object must be locked
3766 *
3767 * NOTE: m->vmp_object could be locked "shared" only if we are called
3768 * from vm_fault() as part of a soft fault. If so, we must be
3769 * careful not to modify the VM object in any way that is not
3770 * legal under a shared lock...
3771 */
3772 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)3773 vm_fault_enter(
3774 vm_page_t m,
3775 pmap_t pmap,
3776 vm_map_offset_t vaddr,
3777 vm_map_size_t fault_page_size,
3778 vm_map_offset_t fault_phys_offset,
3779 vm_prot_t prot,
3780 vm_prot_t caller_prot,
3781 boolean_t wired,
3782 boolean_t change_wiring,
3783 vm_tag_t wire_tag,
3784 vm_object_fault_info_t fault_info,
3785 boolean_t *need_retry,
3786 int *type_of_fault)
3787 {
3788 kern_return_t kr;
3789 vm_object_t object;
3790 bool page_needs_data_sync;
3791 vm_prot_t fault_type;
3792 int pmap_options = fault_info->pmap_options;
3793
3794 if (VM_PAGE_GET_PHYS_PAGE(m) == vm_page_guard_addr) {
3795 assert(m->vmp_fictitious);
3796 return KERN_SUCCESS;
3797 }
3798
3799 fault_type = change_wiring ? VM_PROT_NONE : caller_prot;
3800
3801 assertf(VM_PAGE_OBJECT(m) != VM_OBJECT_NULL, "m=%p", m);
3802 kr = vm_fault_enter_prepare(m, pmap, vaddr, &prot, caller_prot,
3803 fault_page_size, fault_phys_offset, change_wiring, fault_type,
3804 fault_info, type_of_fault, &page_needs_data_sync);
3805 object = VM_PAGE_OBJECT(m);
3806
3807 vm_fault_enqueue_page(object, m, wired, change_wiring, wire_tag, fault_info->no_cache, type_of_fault, kr);
3808
3809 if (kr == KERN_SUCCESS) {
3810 if (page_needs_data_sync) {
3811 pmap_sync_page_data_phys(VM_PAGE_GET_PHYS_PAGE(m));
3812 }
3813
3814 if (fault_info->fi_xnu_user_debug && !object->code_signed) {
3815 pmap_options |= PMAP_OPTIONS_XNU_USER_DEBUG;
3816 }
3817 kr = vm_fault_pmap_enter_with_object_lock(object, pmap, vaddr,
3818 fault_page_size, fault_phys_offset, m,
3819 &prot, caller_prot, fault_type, wired, pmap_options, need_retry);
3820 }
3821
3822 return kr;
3823 }
3824
3825 void
vm_pre_fault(vm_map_offset_t vaddr,vm_prot_t prot)3826 vm_pre_fault(vm_map_offset_t vaddr, vm_prot_t prot)
3827 {
3828 if (pmap_find_phys(current_map()->pmap, vaddr) == 0) {
3829 vm_fault(current_map(), /* map */
3830 vaddr, /* vaddr */
3831 prot, /* fault_type */
3832 FALSE, /* change_wiring */
3833 VM_KERN_MEMORY_NONE, /* tag - not wiring */
3834 THREAD_UNINT, /* interruptible */
3835 NULL, /* caller_pmap */
3836 0 /* caller_pmap_addr */);
3837 }
3838 }
3839
3840
3841 /*
3842 * Routine: vm_fault
3843 * Purpose:
3844 * Handle page faults, including pseudo-faults
3845 * used to change the wiring status of pages.
3846 * Returns:
3847 * Explicit continuations have been removed.
3848 * Implementation:
3849 * vm_fault and vm_fault_page save mucho state
3850 * in the moral equivalent of a closure. The state
3851 * structure is allocated when first entering vm_fault
3852 * and deallocated when leaving vm_fault.
3853 */
3854
3855 extern uint64_t get_current_unique_pid(void);
3856
3857 unsigned long vm_fault_collapse_total = 0;
3858 unsigned long vm_fault_collapse_skipped = 0;
3859
3860
3861 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)3862 vm_fault_external(
3863 vm_map_t map,
3864 vm_map_offset_t vaddr,
3865 vm_prot_t fault_type,
3866 boolean_t change_wiring,
3867 int interruptible,
3868 pmap_t caller_pmap,
3869 vm_map_offset_t caller_pmap_addr)
3870 {
3871 return vm_fault_internal(map, vaddr, fault_type, change_wiring,
3872 change_wiring ? vm_tag_bt() : VM_KERN_MEMORY_NONE,
3873 interruptible, caller_pmap, caller_pmap_addr,
3874 NULL);
3875 }
3876
3877 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)3878 vm_fault(
3879 vm_map_t map,
3880 vm_map_offset_t vaddr,
3881 vm_prot_t fault_type,
3882 boolean_t change_wiring,
3883 vm_tag_t wire_tag, /* if wiring must pass tag != VM_KERN_MEMORY_NONE */
3884 int interruptible,
3885 pmap_t caller_pmap,
3886 vm_map_offset_t caller_pmap_addr)
3887 {
3888 return vm_fault_internal(map, vaddr, fault_type, change_wiring, wire_tag,
3889 interruptible, caller_pmap, caller_pmap_addr,
3890 NULL);
3891 }
3892
3893 static boolean_t
current_proc_is_privileged(void)3894 current_proc_is_privileged(void)
3895 {
3896 return csproc_get_platform_binary(current_proc());
3897 }
3898
3899 uint64_t vm_copied_on_read = 0;
3900
3901 /*
3902 * Cleanup after a vm_fault_enter.
3903 * At this point, the fault should either have failed (kr != KERN_SUCCESS)
3904 * or the page should be in the pmap and on the correct paging queue.
3905 *
3906 * Precondition:
3907 * map must be locked shared.
3908 * m_object must be locked.
3909 * If top_object != VM_OBJECT_NULL, it must be locked.
3910 * real_map must be locked.
3911 *
3912 * Postcondition:
3913 * map will be unlocked
3914 * m_object will be unlocked
3915 * top_object will be unlocked
3916 * If real_map != map, it will be unlocked
3917 */
3918 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)3919 vm_fault_complete(
3920 vm_map_t map,
3921 vm_map_t real_map,
3922 vm_object_t object,
3923 vm_object_t m_object,
3924 vm_page_t m,
3925 vm_map_offset_t offset,
3926 vm_map_offset_t trace_real_vaddr,
3927 vm_object_fault_info_t fault_info,
3928 vm_prot_t caller_prot,
3929 #if CONFIG_DTRACE
3930 vm_map_offset_t real_vaddr,
3931 #else
3932 __unused vm_map_offset_t real_vaddr,
3933 #endif /* CONFIG_DTRACE */
3934 int type_of_fault,
3935 boolean_t need_retry,
3936 kern_return_t kr,
3937 ppnum_t *physpage_p,
3938 vm_prot_t prot,
3939 vm_object_t top_object,
3940 boolean_t need_collapse,
3941 vm_map_offset_t cur_offset,
3942 vm_prot_t fault_type,
3943 vm_object_t *written_on_object,
3944 memory_object_t *written_on_pager,
3945 vm_object_offset_t *written_on_offset)
3946 {
3947 int event_code = 0;
3948 vm_map_lock_assert_shared(map);
3949 vm_object_lock_assert_held(m_object);
3950 if (top_object != VM_OBJECT_NULL) {
3951 vm_object_lock_assert_held(top_object);
3952 }
3953 vm_map_lock_assert_held(real_map);
3954
3955 if (m_object->internal) {
3956 event_code = (MACHDBG_CODE(DBG_MACH_WORKINGSET, VM_REAL_FAULT_ADDR_INTERNAL));
3957 } else if (m_object->object_is_shared_cache) {
3958 event_code = (MACHDBG_CODE(DBG_MACH_WORKINGSET, VM_REAL_FAULT_ADDR_SHAREDCACHE));
3959 } else {
3960 event_code = (MACHDBG_CODE(DBG_MACH_WORKINGSET, VM_REAL_FAULT_ADDR_EXTERNAL));
3961 }
3962 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());
3963 if (need_retry == FALSE) {
3964 KDBG_FILTERED(MACHDBG_CODE(DBG_MACH_WORKINGSET, VM_REAL_FAULT_FAST), get_current_unique_pid());
3965 }
3966 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);
3967 if (kr == KERN_SUCCESS &&
3968 physpage_p != NULL) {
3969 /* for vm_map_wire_and_extract() */
3970 *physpage_p = VM_PAGE_GET_PHYS_PAGE(m);
3971 if (prot & VM_PROT_WRITE) {
3972 vm_object_lock_assert_exclusive(m_object);
3973 m->vmp_dirty = TRUE;
3974 }
3975 }
3976
3977 if (top_object != VM_OBJECT_NULL) {
3978 /*
3979 * It's safe to drop the top object
3980 * now that we've done our
3981 * vm_fault_enter(). Any other fault
3982 * in progress for that virtual
3983 * address will either find our page
3984 * and translation or put in a new page
3985 * and translation.
3986 */
3987 vm_object_unlock(top_object);
3988 top_object = VM_OBJECT_NULL;
3989 }
3990
3991 if (need_collapse == TRUE) {
3992 vm_object_collapse(object, vm_object_trunc_page(offset), TRUE);
3993 }
3994
3995 if (need_retry == FALSE &&
3996 (type_of_fault == DBG_PAGEIND_FAULT || type_of_fault == DBG_PAGEINV_FAULT || type_of_fault == DBG_CACHE_HIT_FAULT)) {
3997 /*
3998 * evaluate access pattern and update state
3999 * vm_fault_deactivate_behind depends on the
4000 * state being up to date
4001 */
4002 vm_fault_is_sequential(m_object, cur_offset, fault_info->behavior);
4003
4004 vm_fault_deactivate_behind(m_object, cur_offset, fault_info->behavior);
4005 }
4006 /*
4007 * That's it, clean up and return.
4008 */
4009 if (m->vmp_busy) {
4010 vm_object_lock_assert_exclusive(m_object);
4011 PAGE_WAKEUP_DONE(m);
4012 }
4013
4014 if (need_retry == FALSE && !m_object->internal && (fault_type & VM_PROT_WRITE)) {
4015 vm_object_paging_begin(m_object);
4016
4017 assert(*written_on_object == VM_OBJECT_NULL);
4018 *written_on_object = m_object;
4019 *written_on_pager = m_object->pager;
4020 *written_on_offset = m_object->paging_offset + m->vmp_offset;
4021 }
4022 vm_object_unlock(object);
4023
4024 vm_map_unlock_read(map);
4025 if (real_map != map) {
4026 vm_map_unlock(real_map);
4027 }
4028 }
4029
4030 static inline int
vm_fault_type_for_tracing(boolean_t need_copy_on_read,int type_of_fault)4031 vm_fault_type_for_tracing(boolean_t need_copy_on_read, int type_of_fault)
4032 {
4033 if (need_copy_on_read && type_of_fault == DBG_COW_FAULT) {
4034 return DBG_COR_FAULT;
4035 }
4036 return type_of_fault;
4037 }
4038
4039 uint64_t vm_fault_resilient_media_initiate = 0;
4040 uint64_t vm_fault_resilient_media_retry = 0;
4041 uint64_t vm_fault_resilient_media_proceed = 0;
4042 uint64_t vm_fault_resilient_media_release = 0;
4043 uint64_t vm_fault_resilient_media_abort1 = 0;
4044 uint64_t vm_fault_resilient_media_abort2 = 0;
4045
4046 #if MACH_ASSERT
4047 int vm_fault_resilient_media_inject_error1_rate = 0;
4048 int vm_fault_resilient_media_inject_error1 = 0;
4049 int vm_fault_resilient_media_inject_error2_rate = 0;
4050 int vm_fault_resilient_media_inject_error2 = 0;
4051 int vm_fault_resilient_media_inject_error3_rate = 0;
4052 int vm_fault_resilient_media_inject_error3 = 0;
4053 #endif /* MACH_ASSERT */
4054
4055 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)4056 vm_fault_internal(
4057 vm_map_t map,
4058 vm_map_offset_t vaddr,
4059 vm_prot_t caller_prot,
4060 boolean_t change_wiring,
4061 vm_tag_t wire_tag, /* if wiring must pass tag != VM_KERN_MEMORY_NONE */
4062 int interruptible,
4063 pmap_t caller_pmap,
4064 vm_map_offset_t caller_pmap_addr,
4065 ppnum_t *physpage_p)
4066 {
4067 vm_map_version_t version; /* Map version for verificiation */
4068 boolean_t wired; /* Should mapping be wired down? */
4069 vm_object_t object; /* Top-level object */
4070 vm_object_offset_t offset; /* Top-level offset */
4071 vm_prot_t prot; /* Protection for mapping */
4072 vm_object_t old_copy_object; /* Saved copy object */
4073 vm_page_t result_page; /* Result of vm_fault_page */
4074 vm_page_t top_page; /* Placeholder page */
4075 kern_return_t kr;
4076
4077 vm_page_t m; /* Fast access to result_page */
4078 kern_return_t error_code;
4079 vm_object_t cur_object;
4080 vm_object_t m_object = NULL;
4081 vm_object_offset_t cur_offset;
4082 vm_page_t cur_m;
4083 vm_object_t new_object;
4084 int type_of_fault;
4085 pmap_t pmap;
4086 wait_interrupt_t interruptible_state;
4087 vm_map_t real_map = map;
4088 vm_map_t original_map = map;
4089 bool object_locks_dropped = FALSE;
4090 vm_prot_t fault_type;
4091 vm_prot_t original_fault_type;
4092 struct vm_object_fault_info fault_info = {};
4093 bool need_collapse = FALSE;
4094 boolean_t need_retry = FALSE;
4095 boolean_t *need_retry_ptr = NULL;
4096 uint8_t object_lock_type = 0;
4097 uint8_t cur_object_lock_type;
4098 vm_object_t top_object = VM_OBJECT_NULL;
4099 vm_object_t written_on_object = VM_OBJECT_NULL;
4100 memory_object_t written_on_pager = NULL;
4101 vm_object_offset_t written_on_offset = 0;
4102 int throttle_delay;
4103 int compressed_count_delta;
4104 uint8_t grab_options;
4105 bool need_copy;
4106 bool need_copy_on_read;
4107 vm_map_offset_t trace_vaddr;
4108 vm_map_offset_t trace_real_vaddr;
4109 vm_map_size_t fault_page_size;
4110 vm_map_size_t fault_page_mask;
4111 int fault_page_shift;
4112 vm_map_offset_t fault_phys_offset;
4113 vm_map_offset_t real_vaddr;
4114 bool resilient_media_retry = false;
4115 bool resilient_media_ref_transfer = false;
4116 vm_object_t resilient_media_object = VM_OBJECT_NULL;
4117 vm_object_offset_t resilient_media_offset = (vm_object_offset_t)-1;
4118 bool page_needs_data_sync = false;
4119 /*
4120 * Was the VM object contended when vm_map_lookup_and_lock_object locked it?
4121 * If so, the zero fill path will drop the lock
4122 * NB: Ideally we would always drop the lock rather than rely on
4123 * this heuristic, but vm_object_unlock currently takes > 30 cycles.
4124 */
4125 bool object_is_contended = false;
4126
4127 real_vaddr = vaddr;
4128 trace_real_vaddr = vaddr;
4129
4130 /*
4131 * Some (kernel) submaps are marked with "should never fault".
4132 *
4133 * We do this for two reasons:
4134 * - PGZ which is inside the zone map range can't go down the normal
4135 * lookup path (vm_map_lookup_entry() would panic).
4136 *
4137 * - we want for guard pages to not have to use fictitious pages at all
4138 * to prevent from ZFOD pages to be made.
4139 *
4140 * We also want capture the fault address easily so that the zone
4141 * allocator might present an enhanced panic log.
4142 */
4143 if (map->never_faults || (pgz_owned(vaddr) && map->pmap == kernel_pmap)) {
4144 assert(map->pmap == kernel_pmap);
4145 panic_fault_address = vaddr;
4146 return KERN_INVALID_ADDRESS;
4147 }
4148
4149 if (VM_MAP_PAGE_SIZE(original_map) < PAGE_SIZE) {
4150 fault_phys_offset = (vm_map_offset_t)-1;
4151 fault_page_size = VM_MAP_PAGE_SIZE(original_map);
4152 fault_page_mask = VM_MAP_PAGE_MASK(original_map);
4153 fault_page_shift = VM_MAP_PAGE_SHIFT(original_map);
4154 if (fault_page_size < PAGE_SIZE) {
4155 DEBUG4K_FAULT("map %p vaddr 0x%llx caller_prot 0x%x\n", map, (uint64_t)trace_real_vaddr, caller_prot);
4156 vaddr = vm_map_trunc_page(vaddr, fault_page_mask);
4157 }
4158 } else {
4159 fault_phys_offset = 0;
4160 fault_page_size = PAGE_SIZE;
4161 fault_page_mask = PAGE_MASK;
4162 fault_page_shift = PAGE_SHIFT;
4163 vaddr = vm_map_trunc_page(vaddr, PAGE_MASK);
4164 }
4165
4166 if (map == kernel_map) {
4167 trace_vaddr = VM_KERNEL_ADDRHIDE(vaddr);
4168 trace_real_vaddr = VM_KERNEL_ADDRHIDE(trace_real_vaddr);
4169 } else {
4170 trace_vaddr = vaddr;
4171 }
4172
4173 KDBG_RELEASE(
4174 (MACHDBG_CODE(DBG_MACH_VM, 2)) | DBG_FUNC_START,
4175 ((uint64_t)trace_vaddr >> 32),
4176 trace_vaddr,
4177 (map == kernel_map));
4178
4179 if (get_preemption_level() != 0) {
4180 KDBG_RELEASE(
4181 (MACHDBG_CODE(DBG_MACH_VM, 2)) | DBG_FUNC_END,
4182 ((uint64_t)trace_vaddr >> 32),
4183 trace_vaddr,
4184 KERN_FAILURE);
4185
4186 ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_NONZERO_PREEMPTION_LEVEL), 0 /* arg */);
4187 return KERN_FAILURE;
4188 }
4189
4190 thread_t cthread = current_thread();
4191 bool rtfault = (cthread->sched_mode == TH_MODE_REALTIME);
4192 uint64_t fstart = 0;
4193
4194 if (rtfault) {
4195 fstart = mach_continuous_time();
4196 }
4197
4198 interruptible_state = thread_interrupt_level(interruptible);
4199
4200 fault_type = (change_wiring ? VM_PROT_NONE : caller_prot);
4201
4202 counter_inc(&vm_statistics_faults);
4203 counter_inc(¤t_task()->faults);
4204 original_fault_type = fault_type;
4205
4206 need_copy = FALSE;
4207 if (fault_type & VM_PROT_WRITE) {
4208 need_copy = TRUE;
4209 }
4210
4211 if (need_copy || change_wiring) {
4212 object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4213 } else {
4214 object_lock_type = OBJECT_LOCK_SHARED;
4215 }
4216
4217 cur_object_lock_type = OBJECT_LOCK_SHARED;
4218
4219 if ((map == kernel_map) && (caller_prot & VM_PROT_WRITE)) {
4220 if (compressor_map) {
4221 if ((vaddr >= vm_map_min(compressor_map)) && (vaddr < vm_map_max(compressor_map))) {
4222 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));
4223 }
4224 }
4225 }
4226 RetryFault:
4227 assert(written_on_object == VM_OBJECT_NULL);
4228
4229 /*
4230 * assume we will hit a page in the cache
4231 * otherwise, explicitly override with
4232 * the real fault type once we determine it
4233 */
4234 type_of_fault = DBG_CACHE_HIT_FAULT;
4235
4236 /*
4237 * Find the backing store object and offset into
4238 * it to begin the search.
4239 */
4240 fault_type = original_fault_type;
4241 map = original_map;
4242 vm_map_lock_read(map);
4243
4244 if (resilient_media_retry) {
4245 /*
4246 * If we have to insert a fake zero-filled page to hide
4247 * a media failure to provide the real page, we need to
4248 * resolve any pending copy-on-write on this mapping.
4249 * VM_PROT_COPY tells vm_map_lookup_and_lock_object() to deal
4250 * with that even if this is not a "write" fault.
4251 */
4252 need_copy = TRUE;
4253 object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4254 vm_fault_resilient_media_retry++;
4255 }
4256
4257 kr = vm_map_lookup_and_lock_object(&map, vaddr,
4258 (fault_type | (need_copy ? VM_PROT_COPY : 0)),
4259 object_lock_type, &version,
4260 &object, &offset, &prot, &wired,
4261 &fault_info,
4262 &real_map,
4263 &object_is_contended);
4264
4265 if (kr != KERN_SUCCESS) {
4266 vm_map_unlock_read(map);
4267 /*
4268 * This can be seen in a crash report if indeed the
4269 * thread is crashing due to an invalid access in a non-existent
4270 * range.
4271 * Turning this OFF for now because it is noisy and not always fatal
4272 * eg prefaulting.
4273 *
4274 * if (kr == KERN_INVALID_ADDRESS) {
4275 * ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_ADDRESS_NOT_FOUND), 0);
4276 * }
4277 */
4278 goto done;
4279 }
4280
4281
4282 pmap = real_map->pmap;
4283 fault_info.interruptible = interruptible;
4284 fault_info.stealth = FALSE;
4285 fault_info.io_sync = FALSE;
4286 fault_info.mark_zf_absent = FALSE;
4287 fault_info.batch_pmap_op = FALSE;
4288
4289 if (resilient_media_retry) {
4290 /*
4291 * We're retrying this fault after having detected a media
4292 * failure from a "resilient_media" mapping.
4293 * Check that the mapping is still pointing at the object
4294 * that just failed to provide a page.
4295 */
4296 assert(resilient_media_object != VM_OBJECT_NULL);
4297 assert(resilient_media_offset != (vm_object_offset_t)-1);
4298 if ((object != VM_OBJECT_NULL &&
4299 object == resilient_media_object &&
4300 offset == resilient_media_offset &&
4301 fault_info.resilient_media)
4302 #if MACH_ASSERT
4303 && (vm_fault_resilient_media_inject_error1_rate == 0 ||
4304 (++vm_fault_resilient_media_inject_error1 % vm_fault_resilient_media_inject_error1_rate) != 0)
4305 #endif /* MACH_ASSERT */
4306 ) {
4307 /*
4308 * This mapping still points at the same object
4309 * and is still "resilient_media": proceed in
4310 * "recovery-from-media-failure" mode, where we'll
4311 * insert a zero-filled page in the top object.
4312 */
4313 // printf("RESILIENT_MEDIA %s:%d recovering for object %p offset 0x%llx\n", __FUNCTION__, __LINE__, object, offset);
4314 vm_fault_resilient_media_proceed++;
4315 } else {
4316 /* not recovering: reset state and retry fault */
4317 // 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);
4318 vm_object_unlock(object);
4319 if (real_map != map) {
4320 vm_map_unlock(real_map);
4321 }
4322 vm_map_unlock_read(map);
4323 /* release our extra reference on failed object */
4324 // printf("FBDP %s:%d resilient_media_object %p deallocate\n", __FUNCTION__, __LINE__, resilient_media_object);
4325 vm_object_lock_assert_notheld(resilient_media_object);
4326 vm_object_deallocate(resilient_media_object);
4327 resilient_media_object = VM_OBJECT_NULL;
4328 resilient_media_offset = (vm_object_offset_t)-1;
4329 resilient_media_retry = false;
4330 vm_fault_resilient_media_abort1++;
4331 goto RetryFault;
4332 }
4333 } else {
4334 assert(resilient_media_object == VM_OBJECT_NULL);
4335 resilient_media_offset = (vm_object_offset_t)-1;
4336 }
4337
4338 /*
4339 * If the page is wired, we must fault for the current protection
4340 * value, to avoid further faults.
4341 */
4342 if (wired) {
4343 fault_type = prot | VM_PROT_WRITE;
4344 }
4345 if (wired || need_copy) {
4346 /*
4347 * since we're treating this fault as a 'write'
4348 * we must hold the top object lock exclusively
4349 */
4350 if (object_lock_type == OBJECT_LOCK_SHARED) {
4351 object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4352
4353 if (vm_object_lock_upgrade(object) == FALSE) {
4354 /*
4355 * couldn't upgrade, so explictly
4356 * take the lock exclusively
4357 */
4358 vm_object_lock(object);
4359 }
4360 }
4361 }
4362
4363 #if VM_FAULT_CLASSIFY
4364 /*
4365 * Temporary data gathering code
4366 */
4367 vm_fault_classify(object, offset, fault_type);
4368 #endif
4369 /*
4370 * Fast fault code. The basic idea is to do as much as
4371 * possible while holding the map lock and object locks.
4372 * Busy pages are not used until the object lock has to
4373 * be dropped to do something (copy, zero fill, pmap enter).
4374 * Similarly, paging references aren't acquired until that
4375 * point, and object references aren't used.
4376 *
4377 * If we can figure out what to do
4378 * (zero fill, copy on write, pmap enter) while holding
4379 * the locks, then it gets done. Otherwise, we give up,
4380 * and use the original fault path (which doesn't hold
4381 * the map lock, and relies on busy pages).
4382 * The give up cases include:
4383 * - Have to talk to pager.
4384 * - Page is busy, absent or in error.
4385 * - Pager has locked out desired access.
4386 * - Fault needs to be restarted.
4387 * - Have to push page into copy object.
4388 *
4389 * The code is an infinite loop that moves one level down
4390 * the shadow chain each time. cur_object and cur_offset
4391 * refer to the current object being examined. object and offset
4392 * are the original object from the map. The loop is at the
4393 * top level if and only if object and cur_object are the same.
4394 *
4395 * Invariants: Map lock is held throughout. Lock is held on
4396 * original object and cur_object (if different) when
4397 * continuing or exiting loop.
4398 *
4399 */
4400
4401 #if defined(__arm64__)
4402 /*
4403 * Fail if reading an execute-only page in a
4404 * pmap that enforces execute-only protection.
4405 */
4406 if (fault_type == VM_PROT_READ &&
4407 (prot & VM_PROT_EXECUTE) &&
4408 !(prot & VM_PROT_READ) &&
4409 pmap_enforces_execute_only(pmap)) {
4410 vm_object_unlock(object);
4411 vm_map_unlock_read(map);
4412 if (real_map != map) {
4413 vm_map_unlock(real_map);
4414 }
4415 kr = KERN_PROTECTION_FAILURE;
4416 goto done;
4417 }
4418 #endif
4419
4420 fault_phys_offset = (vm_map_offset_t)offset - vm_map_trunc_page((vm_map_offset_t)offset, PAGE_MASK);
4421
4422 /*
4423 * If this page is to be inserted in a copy delay object
4424 * for writing, and if the object has a copy, then the
4425 * copy delay strategy is implemented in the slow fault page.
4426 */
4427 if (object->copy_strategy == MEMORY_OBJECT_COPY_DELAY &&
4428 object->copy != VM_OBJECT_NULL && (fault_type & VM_PROT_WRITE)) {
4429 goto handle_copy_delay;
4430 }
4431
4432 cur_object = object;
4433 cur_offset = offset;
4434
4435 grab_options = 0;
4436 #if CONFIG_SECLUDED_MEMORY
4437 if (object->can_grab_secluded) {
4438 grab_options |= VM_PAGE_GRAB_SECLUDED;
4439 }
4440 #endif /* CONFIG_SECLUDED_MEMORY */
4441
4442 while (TRUE) {
4443 if (!cur_object->pager_created &&
4444 cur_object->phys_contiguous) { /* superpage */
4445 break;
4446 }
4447
4448 if (cur_object->blocked_access) {
4449 /*
4450 * Access to this VM object has been blocked.
4451 * Let the slow path handle it.
4452 */
4453 break;
4454 }
4455
4456 m = vm_page_lookup(cur_object, vm_object_trunc_page(cur_offset));
4457 m_object = NULL;
4458
4459 if (m != VM_PAGE_NULL) {
4460 m_object = cur_object;
4461
4462 if (m->vmp_busy) {
4463 wait_result_t result;
4464
4465 /*
4466 * in order to do the PAGE_ASSERT_WAIT, we must
4467 * have object that 'm' belongs to locked exclusively
4468 */
4469 if (object != cur_object) {
4470 if (cur_object_lock_type == OBJECT_LOCK_SHARED) {
4471 cur_object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4472
4473 if (vm_object_lock_upgrade(cur_object) == FALSE) {
4474 /*
4475 * couldn't upgrade so go do a full retry
4476 * immediately since we can no longer be
4477 * certain about cur_object (since we
4478 * don't hold a reference on it)...
4479 * first drop the top object lock
4480 */
4481 vm_object_unlock(object);
4482
4483 vm_map_unlock_read(map);
4484 if (real_map != map) {
4485 vm_map_unlock(real_map);
4486 }
4487
4488 goto RetryFault;
4489 }
4490 }
4491 } else if (object_lock_type == OBJECT_LOCK_SHARED) {
4492 object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4493
4494 if (vm_object_lock_upgrade(object) == FALSE) {
4495 /*
4496 * couldn't upgrade, so explictly take the lock
4497 * exclusively and go relookup the page since we
4498 * will have dropped the object lock and
4499 * a different thread could have inserted
4500 * a page at this offset
4501 * no need for a full retry since we're
4502 * at the top level of the object chain
4503 */
4504 vm_object_lock(object);
4505
4506 continue;
4507 }
4508 }
4509 if ((m->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q) && m_object->internal) {
4510 /*
4511 * m->vmp_busy == TRUE and the object is locked exclusively
4512 * if m->pageout_queue == TRUE after we acquire the
4513 * queues lock, we are guaranteed that it is stable on
4514 * the pageout queue and therefore reclaimable
4515 *
4516 * NOTE: this is only true for the internal pageout queue
4517 * in the compressor world
4518 */
4519 assert(VM_CONFIG_COMPRESSOR_IS_PRESENT);
4520
4521 vm_page_lock_queues();
4522
4523 if (m->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q) {
4524 vm_pageout_throttle_up(m);
4525 vm_page_unlock_queues();
4526
4527 PAGE_WAKEUP_DONE(m);
4528 goto reclaimed_from_pageout;
4529 }
4530 vm_page_unlock_queues();
4531 }
4532 if (object != cur_object) {
4533 vm_object_unlock(object);
4534 }
4535
4536 vm_map_unlock_read(map);
4537 if (real_map != map) {
4538 vm_map_unlock(real_map);
4539 }
4540
4541 result = PAGE_ASSERT_WAIT(m, interruptible);
4542
4543 vm_object_unlock(cur_object);
4544
4545 if (result == THREAD_WAITING) {
4546 result = thread_block(THREAD_CONTINUE_NULL);
4547 }
4548 if (result == THREAD_AWAKENED || result == THREAD_RESTART) {
4549 goto RetryFault;
4550 }
4551
4552 ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_BUSYPAGE_WAIT_INTERRUPTED), 0 /* arg */);
4553 kr = KERN_ABORTED;
4554 goto done;
4555 }
4556 reclaimed_from_pageout:
4557 if (m->vmp_laundry) {
4558 if (object != cur_object) {
4559 if (cur_object_lock_type == OBJECT_LOCK_SHARED) {
4560 cur_object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4561
4562 vm_object_unlock(object);
4563 vm_object_unlock(cur_object);
4564
4565 vm_map_unlock_read(map);
4566 if (real_map != map) {
4567 vm_map_unlock(real_map);
4568 }
4569
4570 goto RetryFault;
4571 }
4572 } else if (object_lock_type == OBJECT_LOCK_SHARED) {
4573 object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4574
4575 if (vm_object_lock_upgrade(object) == FALSE) {
4576 /*
4577 * couldn't upgrade, so explictly take the lock
4578 * exclusively and go relookup the page since we
4579 * will have dropped the object lock and
4580 * a different thread could have inserted
4581 * a page at this offset
4582 * no need for a full retry since we're
4583 * at the top level of the object chain
4584 */
4585 vm_object_lock(object);
4586
4587 continue;
4588 }
4589 }
4590 vm_object_lock_assert_exclusive(VM_PAGE_OBJECT(m));
4591 vm_pageout_steal_laundry(m, FALSE);
4592 }
4593
4594
4595 if (VM_PAGE_GET_PHYS_PAGE(m) == vm_page_guard_addr) {
4596 /*
4597 * Guard page: let the slow path deal with it
4598 */
4599 break;
4600 }
4601 if (m->vmp_unusual && (VMP_ERROR_GET(m) || m->vmp_restart || m->vmp_private || m->vmp_absent)) {
4602 /*
4603 * Unusual case... let the slow path deal with it
4604 */
4605 break;
4606 }
4607 if (VM_OBJECT_PURGEABLE_FAULT_ERROR(m_object)) {
4608 if (object != cur_object) {
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 vm_object_unlock(cur_object);
4616 ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_PURGEABLE_FAULT_ERROR), 0 /* arg */);
4617 kr = KERN_MEMORY_ERROR;
4618 goto done;
4619 }
4620 assert(m_object == VM_PAGE_OBJECT(m));
4621
4622 if (vm_fault_cs_need_validation(map->pmap, m, m_object,
4623 PAGE_SIZE, 0) ||
4624 (physpage_p != NULL && (prot & VM_PROT_WRITE))) {
4625 upgrade_lock_and_retry:
4626 /*
4627 * We might need to validate this page
4628 * against its code signature, so we
4629 * want to hold the VM object exclusively.
4630 */
4631 if (object != cur_object) {
4632 if (cur_object_lock_type == OBJECT_LOCK_SHARED) {
4633 vm_object_unlock(object);
4634 vm_object_unlock(cur_object);
4635
4636 cur_object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4637
4638 vm_map_unlock_read(map);
4639 if (real_map != map) {
4640 vm_map_unlock(real_map);
4641 }
4642
4643 goto RetryFault;
4644 }
4645 } else if (object_lock_type == OBJECT_LOCK_SHARED) {
4646 object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4647
4648 if (vm_object_lock_upgrade(object) == FALSE) {
4649 /*
4650 * couldn't upgrade, so explictly take the lock
4651 * exclusively and go relookup the page since we
4652 * will have dropped the object lock and
4653 * a different thread could have inserted
4654 * a page at this offset
4655 * no need for a full retry since we're
4656 * at the top level of the object chain
4657 */
4658 vm_object_lock(object);
4659
4660 continue;
4661 }
4662 }
4663 }
4664 /*
4665 * Two cases of map in faults:
4666 * - At top level w/o copy object.
4667 * - Read fault anywhere.
4668 * --> must disallow write.
4669 */
4670
4671 if (object == cur_object && object->copy == VM_OBJECT_NULL) {
4672 goto FastPmapEnter;
4673 }
4674
4675 if (!need_copy &&
4676 !fault_info.no_copy_on_read &&
4677 cur_object != object &&
4678 !cur_object->internal &&
4679 !cur_object->pager_trusted &&
4680 vm_protect_privileged_from_untrusted &&
4681 !cur_object->code_signed &&
4682 current_proc_is_privileged()) {
4683 /*
4684 * We're faulting on a page in "object" and
4685 * went down the shadow chain to "cur_object"
4686 * to find out that "cur_object"'s pager
4687 * is not "trusted", i.e. we can not trust it
4688 * to always return the same contents.
4689 * Since the target is a "privileged" process,
4690 * let's treat this as a copy-on-read fault, as
4691 * if it was a copy-on-write fault.
4692 * Once "object" gets a copy of this page, it
4693 * won't have to rely on "cur_object" to
4694 * provide the contents again.
4695 *
4696 * This is done by setting "need_copy" and
4697 * retrying the fault from the top with the
4698 * appropriate locking.
4699 *
4700 * Special case: if the mapping is executable
4701 * and the untrusted object is code-signed and
4702 * the process is "cs_enforced", we do not
4703 * copy-on-read because that would break
4704 * code-signing enforcement expectations (an
4705 * executable page must belong to a code-signed
4706 * object) and we can rely on code-signing
4707 * to re-validate the page if it gets evicted
4708 * and paged back in.
4709 */
4710 // 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);
4711 vm_copied_on_read++;
4712 need_copy = TRUE;
4713
4714 vm_object_unlock(object);
4715 vm_object_unlock(cur_object);
4716 object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4717 vm_map_unlock_read(map);
4718 if (real_map != map) {
4719 vm_map_unlock(real_map);
4720 }
4721 goto RetryFault;
4722 }
4723
4724 if (!(fault_type & VM_PROT_WRITE) && !need_copy) {
4725 if (!pmap_has_prot_policy(pmap, fault_info.pmap_options & PMAP_OPTIONS_TRANSLATED_ALLOW_EXECUTE, prot)) {
4726 prot &= ~VM_PROT_WRITE;
4727 } else {
4728 /*
4729 * For a protection that the pmap cares
4730 * about, we must hand over the full
4731 * set of protections (so that the pmap
4732 * layer can apply any desired policy).
4733 * This means that cs_bypass must be
4734 * set, as this can force us to pass
4735 * RWX.
4736 */
4737 assert(fault_info.cs_bypass);
4738 }
4739
4740 if (object != cur_object) {
4741 /*
4742 * We still need to hold the top object
4743 * lock here to prevent a race between
4744 * a read fault (taking only "shared"
4745 * locks) and a write fault (taking
4746 * an "exclusive" lock on the top
4747 * object.
4748 * Otherwise, as soon as we release the
4749 * top lock, the write fault could
4750 * proceed and actually complete before
4751 * the read fault, and the copied page's
4752 * translation could then be overwritten
4753 * by the read fault's translation for
4754 * the original page.
4755 *
4756 * Let's just record what the top object
4757 * is and we'll release it later.
4758 */
4759 top_object = object;
4760
4761 /*
4762 * switch to the object that has the new page
4763 */
4764 object = cur_object;
4765 object_lock_type = cur_object_lock_type;
4766 }
4767 FastPmapEnter:
4768 assert(m_object == VM_PAGE_OBJECT(m));
4769
4770 /*
4771 * prepare for the pmap_enter...
4772 * object and map are both locked
4773 * m contains valid data
4774 * object == m->vmp_object
4775 * cur_object == NULL or it's been unlocked
4776 * no paging references on either object or cur_object
4777 */
4778 if (top_object != VM_OBJECT_NULL || object_lock_type != OBJECT_LOCK_EXCLUSIVE) {
4779 need_retry_ptr = &need_retry;
4780 } else {
4781 need_retry_ptr = NULL;
4782 }
4783
4784 if (fault_page_size < PAGE_SIZE) {
4785 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);
4786 assertf((!(fault_phys_offset & FOURK_PAGE_MASK) &&
4787 fault_phys_offset < PAGE_SIZE),
4788 "0x%llx\n", (uint64_t)fault_phys_offset);
4789 } else {
4790 assertf(fault_phys_offset == 0,
4791 "0x%llx\n", (uint64_t)fault_phys_offset);
4792 }
4793
4794 if (__improbable(rtfault &&
4795 !m->vmp_realtime &&
4796 vm_pageout_protect_realtime)) {
4797 vm_page_lock_queues();
4798 if (!m->vmp_realtime) {
4799 m->vmp_realtime = true;
4800 vm_page_realtime_count++;
4801 }
4802 vm_page_unlock_queues();
4803 }
4804 assertf(VM_PAGE_OBJECT(m) == m_object, "m=%p m_object=%p object=%p", m, m_object, object);
4805 assert(VM_PAGE_OBJECT(m) != VM_OBJECT_NULL);
4806 if (caller_pmap) {
4807 kr = vm_fault_enter(m,
4808 caller_pmap,
4809 caller_pmap_addr,
4810 fault_page_size,
4811 fault_phys_offset,
4812 prot,
4813 caller_prot,
4814 wired,
4815 change_wiring,
4816 wire_tag,
4817 &fault_info,
4818 need_retry_ptr,
4819 &type_of_fault);
4820 } else {
4821 kr = vm_fault_enter(m,
4822 pmap,
4823 vaddr,
4824 fault_page_size,
4825 fault_phys_offset,
4826 prot,
4827 caller_prot,
4828 wired,
4829 change_wiring,
4830 wire_tag,
4831 &fault_info,
4832 need_retry_ptr,
4833 &type_of_fault);
4834 }
4835
4836 vm_fault_complete(
4837 map,
4838 real_map,
4839 object,
4840 m_object,
4841 m,
4842 offset,
4843 trace_real_vaddr,
4844 &fault_info,
4845 caller_prot,
4846 real_vaddr,
4847 vm_fault_type_for_tracing(need_copy_on_read, type_of_fault),
4848 need_retry,
4849 kr,
4850 physpage_p,
4851 prot,
4852 top_object,
4853 need_collapse,
4854 cur_offset,
4855 fault_type,
4856 &written_on_object,
4857 &written_on_pager,
4858 &written_on_offset);
4859 top_object = VM_OBJECT_NULL;
4860 if (need_retry == TRUE) {
4861 /*
4862 * vm_fault_enter couldn't complete the PMAP_ENTER...
4863 * at this point we don't hold any locks so it's safe
4864 * to ask the pmap layer to expand the page table to
4865 * accommodate this mapping... once expanded, we'll
4866 * re-drive the fault which should result in vm_fault_enter
4867 * being able to successfully enter the mapping this time around
4868 */
4869 (void)pmap_enter_options(
4870 pmap, vaddr, 0, 0, 0, 0, 0,
4871 PMAP_OPTIONS_NOENTER, NULL);
4872
4873 need_retry = FALSE;
4874 goto RetryFault;
4875 }
4876 goto done;
4877 }
4878 /*
4879 * COPY ON WRITE FAULT
4880 */
4881 assert(object_lock_type == OBJECT_LOCK_EXCLUSIVE);
4882
4883 /*
4884 * If objects match, then
4885 * object->copy must not be NULL (else control
4886 * would be in previous code block), and we
4887 * have a potential push into the copy object
4888 * with which we can't cope with here.
4889 */
4890 if (cur_object == object) {
4891 /*
4892 * must take the slow path to
4893 * deal with the copy push
4894 */
4895 break;
4896 }
4897
4898 /*
4899 * This is now a shadow based copy on write
4900 * fault -- it requires a copy up the shadow
4901 * chain.
4902 */
4903 assert(m_object == VM_PAGE_OBJECT(m));
4904
4905 if ((cur_object_lock_type == OBJECT_LOCK_SHARED) &&
4906 vm_fault_cs_need_validation(NULL, m, m_object,
4907 PAGE_SIZE, 0)) {
4908 goto upgrade_lock_and_retry;
4909 }
4910
4911 #if MACH_ASSERT
4912 if (resilient_media_retry &&
4913 vm_fault_resilient_media_inject_error2_rate != 0 &&
4914 (++vm_fault_resilient_media_inject_error2 % vm_fault_resilient_media_inject_error2_rate) == 0) {
4915 /* inject an error */
4916 cur_m = m;
4917 m = VM_PAGE_NULL;
4918 m_object = VM_OBJECT_NULL;
4919 break;
4920 }
4921 #endif /* MACH_ASSERT */
4922 /*
4923 * Allocate a page in the original top level
4924 * object. Give up if allocate fails. Also
4925 * need to remember current page, as it's the
4926 * source of the copy.
4927 *
4928 * at this point we hold locks on both
4929 * object and cur_object... no need to take
4930 * paging refs or mark pages BUSY since
4931 * we don't drop either object lock until
4932 * the page has been copied and inserted
4933 */
4934 cur_m = m;
4935 m = vm_page_grab_options(grab_options);
4936 m_object = NULL;
4937
4938 if (m == VM_PAGE_NULL) {
4939 /*
4940 * no free page currently available...
4941 * must take the slow path
4942 */
4943 break;
4944 }
4945
4946 /*
4947 * Now do the copy. Mark the source page busy...
4948 *
4949 * NOTE: This code holds the map lock across
4950 * the page copy.
4951 */
4952 vm_page_copy(cur_m, m);
4953 vm_page_insert(m, object, vm_object_trunc_page(offset));
4954 if (VM_MAP_PAGE_MASK(map) != PAGE_MASK) {
4955 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);
4956 }
4957 m_object = object;
4958 SET_PAGE_DIRTY(m, FALSE);
4959
4960 /*
4961 * Now cope with the source page and object
4962 */
4963 if (object->ref_count > 1 && cur_m->vmp_pmapped) {
4964 pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(cur_m));
4965 } else if (VM_MAP_PAGE_SIZE(map) < PAGE_SIZE) {
4966 /*
4967 * We've copied the full 16K page but we're
4968 * about to call vm_fault_enter() only for
4969 * the 4K chunk we're faulting on. The other
4970 * three 4K chunks in that page could still
4971 * be pmapped in this pmap.
4972 * Since the VM object layer thinks that the
4973 * entire page has been dealt with and the
4974 * original page might no longer be needed,
4975 * it might collapse/bypass the original VM
4976 * object and free its pages, which would be
4977 * bad (and would trigger pmap_verify_free()
4978 * assertions) if the other 4K chunks are still
4979 * pmapped.
4980 */
4981 /*
4982 * XXX FBDP TODO4K: to be revisisted
4983 * Technically, we need to pmap_disconnect()
4984 * only the target pmap's mappings for the 4K
4985 * chunks of this 16K VM page. If other pmaps
4986 * have PTEs on these chunks, that means that
4987 * the associated VM map must have a reference
4988 * on the VM object, so no need to worry about
4989 * those.
4990 * pmap_protect() for each 4K chunk would be
4991 * better but we'd have to check which chunks
4992 * are actually mapped before and after this
4993 * one.
4994 * A full-blown pmap_disconnect() is easier
4995 * for now but not efficient.
4996 */
4997 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));
4998 pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(cur_m));
4999 }
5000
5001 if (cur_m->vmp_clustered) {
5002 VM_PAGE_COUNT_AS_PAGEIN(cur_m);
5003 VM_PAGE_CONSUME_CLUSTERED(cur_m);
5004 vm_fault_is_sequential(cur_object, cur_offset, fault_info.behavior);
5005 }
5006 need_collapse = TRUE;
5007
5008 if (!cur_object->internal &&
5009 cur_object->copy_strategy == MEMORY_OBJECT_COPY_DELAY) {
5010 /*
5011 * The object from which we've just
5012 * copied a page is most probably backed
5013 * by a vnode. We don't want to waste too
5014 * much time trying to collapse the VM objects
5015 * and create a bottleneck when several tasks
5016 * map the same file.
5017 */
5018 if (cur_object->copy == object) {
5019 /*
5020 * Shared mapping or no COW yet.
5021 * We can never collapse a copy
5022 * object into its backing object.
5023 */
5024 need_collapse = FALSE;
5025 } else if (cur_object->copy == object->shadow &&
5026 object->shadow->resident_page_count == 0) {
5027 /*
5028 * Shared mapping after a COW occurred.
5029 */
5030 need_collapse = FALSE;
5031 }
5032 }
5033 vm_object_unlock(cur_object);
5034
5035 if (need_collapse == FALSE) {
5036 vm_fault_collapse_skipped++;
5037 }
5038 vm_fault_collapse_total++;
5039
5040 type_of_fault = DBG_COW_FAULT;
5041 counter_inc(&vm_statistics_cow_faults);
5042 DTRACE_VM2(cow_fault, int, 1, (uint64_t *), NULL);
5043 counter_inc(¤t_task()->cow_faults);
5044
5045 goto FastPmapEnter;
5046 } else {
5047 /*
5048 * No page at cur_object, cur_offset... m == NULL
5049 */
5050 if (cur_object->pager_created) {
5051 vm_external_state_t compressor_external_state = VM_EXTERNAL_STATE_UNKNOWN;
5052
5053 if (MUST_ASK_PAGER(cur_object, cur_offset, compressor_external_state) == TRUE) {
5054 int my_fault_type;
5055 uint8_t c_flags = C_DONT_BLOCK;
5056 bool insert_cur_object = FALSE;
5057
5058 /*
5059 * May have to talk to a pager...
5060 * if so, take the slow path by
5061 * doing a 'break' from the while (TRUE) loop
5062 *
5063 * external_state will only be set to VM_EXTERNAL_STATE_EXISTS
5064 * if the compressor is active and the page exists there
5065 */
5066 if (compressor_external_state != VM_EXTERNAL_STATE_EXISTS) {
5067 break;
5068 }
5069
5070 if (map == kernel_map || real_map == kernel_map) {
5071 /*
5072 * can't call into the compressor with the kernel_map
5073 * lock held, since the compressor may try to operate
5074 * on the kernel map in order to return an empty c_segment
5075 */
5076 break;
5077 }
5078 if (object != cur_object) {
5079 if (fault_type & VM_PROT_WRITE) {
5080 c_flags |= C_KEEP;
5081 } else {
5082 insert_cur_object = TRUE;
5083 }
5084 }
5085 if (insert_cur_object == TRUE) {
5086 if (cur_object_lock_type == OBJECT_LOCK_SHARED) {
5087 cur_object_lock_type = OBJECT_LOCK_EXCLUSIVE;
5088
5089 if (vm_object_lock_upgrade(cur_object) == FALSE) {
5090 /*
5091 * couldn't upgrade so go do a full retry
5092 * immediately since we can no longer be
5093 * certain about cur_object (since we
5094 * don't hold a reference on it)...
5095 * first drop the top object lock
5096 */
5097 vm_object_unlock(object);
5098
5099 vm_map_unlock_read(map);
5100 if (real_map != map) {
5101 vm_map_unlock(real_map);
5102 }
5103
5104 goto RetryFault;
5105 }
5106 }
5107 } else if (object_lock_type == OBJECT_LOCK_SHARED) {
5108 object_lock_type = OBJECT_LOCK_EXCLUSIVE;
5109
5110 if (object != cur_object) {
5111 /*
5112 * we can't go for the upgrade on the top
5113 * lock since the upgrade may block waiting
5114 * for readers to drain... since we hold
5115 * cur_object locked at this point, waiting
5116 * for the readers to drain would represent
5117 * a lock order inversion since the lock order
5118 * for objects is the reference order in the
5119 * shadown chain
5120 */
5121 vm_object_unlock(object);
5122 vm_object_unlock(cur_object);
5123
5124 vm_map_unlock_read(map);
5125 if (real_map != map) {
5126 vm_map_unlock(real_map);
5127 }
5128
5129 goto RetryFault;
5130 }
5131 if (vm_object_lock_upgrade(object) == FALSE) {
5132 /*
5133 * couldn't upgrade, so explictly take the lock
5134 * exclusively and go relookup the page since we
5135 * will have dropped the object lock and
5136 * a different thread could have inserted
5137 * a page at this offset
5138 * no need for a full retry since we're
5139 * at the top level of the object chain
5140 */
5141 vm_object_lock(object);
5142
5143 continue;
5144 }
5145 }
5146 m = vm_page_grab_options(grab_options);
5147 m_object = NULL;
5148
5149 if (m == VM_PAGE_NULL) {
5150 /*
5151 * no free page currently available...
5152 * must take the slow path
5153 */
5154 break;
5155 }
5156
5157 /*
5158 * The object is and remains locked
5159 * so no need to take a
5160 * "paging_in_progress" reference.
5161 */
5162 bool shared_lock;
5163 if ((object == cur_object &&
5164 object_lock_type == OBJECT_LOCK_EXCLUSIVE) ||
5165 (object != cur_object &&
5166 cur_object_lock_type == OBJECT_LOCK_EXCLUSIVE)) {
5167 shared_lock = FALSE;
5168 } else {
5169 shared_lock = TRUE;
5170 }
5171
5172 kr = vm_compressor_pager_get(
5173 cur_object->pager,
5174 (vm_object_trunc_page(cur_offset)
5175 + cur_object->paging_offset),
5176 VM_PAGE_GET_PHYS_PAGE(m),
5177 &my_fault_type,
5178 c_flags,
5179 &compressed_count_delta);
5180
5181 vm_compressor_pager_count(
5182 cur_object->pager,
5183 compressed_count_delta,
5184 shared_lock,
5185 cur_object);
5186
5187 if (kr != KERN_SUCCESS) {
5188 vm_page_release(m, FALSE);
5189 m = VM_PAGE_NULL;
5190 }
5191 /*
5192 * If vm_compressor_pager_get() returns
5193 * KERN_MEMORY_FAILURE, then the
5194 * compressed data is permanently lost,
5195 * so return this error immediately.
5196 */
5197 if (kr == KERN_MEMORY_FAILURE) {
5198 if (object != cur_object) {
5199 vm_object_unlock(cur_object);
5200 }
5201 vm_object_unlock(object);
5202 vm_map_unlock_read(map);
5203 if (real_map != map) {
5204 vm_map_unlock(real_map);
5205 }
5206
5207 goto done;
5208 } else if (kr != KERN_SUCCESS) {
5209 break;
5210 }
5211 m->vmp_dirty = TRUE;
5212
5213 /*
5214 * If the object is purgeable, its
5215 * owner's purgeable ledgers will be
5216 * updated in vm_page_insert() but the
5217 * page was also accounted for in a
5218 * "compressed purgeable" ledger, so
5219 * update that now.
5220 */
5221 if (object != cur_object &&
5222 !insert_cur_object) {
5223 /*
5224 * We're not going to insert
5225 * the decompressed page into
5226 * the object it came from.
5227 *
5228 * We're dealing with a
5229 * copy-on-write fault on
5230 * "object".
5231 * We're going to decompress
5232 * the page directly into the
5233 * target "object" while
5234 * keepin the compressed
5235 * page for "cur_object", so
5236 * no ledger update in that
5237 * case.
5238 */
5239 } else if (((cur_object->purgable ==
5240 VM_PURGABLE_DENY) &&
5241 (!cur_object->vo_ledger_tag)) ||
5242 (cur_object->vo_owner ==
5243 NULL)) {
5244 /*
5245 * "cur_object" is not purgeable
5246 * and is not ledger-taged, or
5247 * there's no owner for it,
5248 * so no owner's ledgers to
5249 * update.
5250 */
5251 } else {
5252 /*
5253 * One less compressed
5254 * purgeable/tagged page for
5255 * cur_object's owner.
5256 */
5257 vm_object_owner_compressed_update(
5258 cur_object,
5259 -1);
5260 }
5261
5262 if (insert_cur_object) {
5263 vm_page_insert(m, cur_object, vm_object_trunc_page(cur_offset));
5264 m_object = cur_object;
5265 } else {
5266 vm_page_insert(m, object, vm_object_trunc_page(offset));
5267 m_object = object;
5268 }
5269
5270 if ((m_object->wimg_bits & VM_WIMG_MASK) != VM_WIMG_USE_DEFAULT) {
5271 /*
5272 * If the page is not cacheable,
5273 * we can't let its contents
5274 * linger in the data cache
5275 * after the decompression.
5276 */
5277 pmap_sync_page_attributes_phys(VM_PAGE_GET_PHYS_PAGE(m));
5278 }
5279
5280 type_of_fault = my_fault_type;
5281
5282 VM_STAT_DECOMPRESSIONS();
5283
5284 if (cur_object != object) {
5285 if (insert_cur_object) {
5286 top_object = object;
5287 /*
5288 * switch to the object that has the new page
5289 */
5290 object = cur_object;
5291 object_lock_type = cur_object_lock_type;
5292 } else {
5293 vm_object_unlock(cur_object);
5294 cur_object = object;
5295 }
5296 }
5297 goto FastPmapEnter;
5298 }
5299 /*
5300 * existence map present and indicates
5301 * that the pager doesn't have this page
5302 */
5303 }
5304 if (cur_object->shadow == VM_OBJECT_NULL ||
5305 resilient_media_retry) {
5306 /*
5307 * Zero fill fault. Page gets
5308 * inserted into the original object.
5309 */
5310 if (cur_object->shadow_severed ||
5311 VM_OBJECT_PURGEABLE_FAULT_ERROR(cur_object) ||
5312 cur_object == compressor_object ||
5313 cur_object == kernel_object) {
5314 if (object != cur_object) {
5315 vm_object_unlock(cur_object);
5316 }
5317 vm_object_unlock(object);
5318
5319 vm_map_unlock_read(map);
5320 if (real_map != map) {
5321 vm_map_unlock(real_map);
5322 }
5323 if (VM_OBJECT_PURGEABLE_FAULT_ERROR(cur_object)) {
5324 ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_PURGEABLE_FAULT_ERROR), 0 /* arg */);
5325 }
5326
5327 if (cur_object->shadow_severed) {
5328 ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_OBJECT_SHADOW_SEVERED), 0 /* arg */);
5329 }
5330
5331 kr = KERN_MEMORY_ERROR;
5332 goto done;
5333 }
5334 if (cur_object != object) {
5335 vm_object_unlock(cur_object);
5336
5337 cur_object = object;
5338 }
5339 if (object_lock_type == OBJECT_LOCK_SHARED) {
5340 object_lock_type = OBJECT_LOCK_EXCLUSIVE;
5341
5342 if (vm_object_lock_upgrade(object) == FALSE) {
5343 /*
5344 * couldn't upgrade so do a full retry on the fault
5345 * since we dropped the object lock which
5346 * could allow another thread to insert
5347 * a page at this offset
5348 */
5349 vm_map_unlock_read(map);
5350 if (real_map != map) {
5351 vm_map_unlock(real_map);
5352 }
5353
5354 goto RetryFault;
5355 }
5356 }
5357 if (!object->internal) {
5358 panic("%s:%d should not zero-fill page at offset 0x%llx in external object %p", __FUNCTION__, __LINE__, (uint64_t)offset, object);
5359 }
5360 #if MACH_ASSERT
5361 if (resilient_media_retry &&
5362 vm_fault_resilient_media_inject_error3_rate != 0 &&
5363 (++vm_fault_resilient_media_inject_error3 % vm_fault_resilient_media_inject_error3_rate) == 0) {
5364 /* inject an error */
5365 m_object = NULL;
5366 break;
5367 }
5368 #endif /* MACH_ASSERT */
5369 m = vm_page_alloc(object, vm_object_trunc_page(offset));
5370 m_object = NULL;
5371
5372 if (m == VM_PAGE_NULL) {
5373 /*
5374 * no free page currently available...
5375 * must take the slow path
5376 */
5377 break;
5378 }
5379 m_object = object;
5380
5381 if ((prot & VM_PROT_WRITE) &&
5382 !(fault_type & VM_PROT_WRITE) &&
5383 object->copy != VM_OBJECT_NULL) {
5384 /*
5385 * This is not a write fault and
5386 * we might have a copy-on-write
5387 * obligation to honor (copy object or
5388 * "needs_copy" map entry), so do not
5389 * give write access yet.
5390 * We'll need to catch the first write
5391 * to resolve the copy-on-write by
5392 * pushing this page to a copy object
5393 * or making a shadow object.
5394 */
5395 if (!pmap_has_prot_policy(pmap, fault_info.pmap_options & PMAP_OPTIONS_TRANSLATED_ALLOW_EXECUTE, prot)) {
5396 prot &= ~VM_PROT_WRITE;
5397 } else {
5398 assert(fault_info.cs_bypass);
5399 }
5400 }
5401
5402 /*
5403 * Zeroing the page and entering into it into the pmap
5404 * represents a significant amount of the zero fill fault handler's work.
5405 *
5406 * To improve fault scalability, we'll drop the object lock, if it appears contended,
5407 * now that we've inserted the page into the vm object.
5408 * Before dropping the lock, we need to check protection bits and set the
5409 * mapped bits on the page. Then we can mark the page busy, drop the lock,
5410 * zero it, and do the pmap enter. We'll need to reacquire the lock
5411 * to clear the busy bit and wake up any waiters.
5412 */
5413 vm_fault_cs_clear(m);
5414 m->vmp_pmapped = TRUE;
5415 if (map->no_zero_fill) {
5416 type_of_fault = DBG_NZF_PAGE_FAULT;
5417 } else {
5418 type_of_fault = DBG_ZERO_FILL_FAULT;
5419 }
5420 {
5421 pmap_t destination_pmap;
5422 vm_map_offset_t destination_pmap_vaddr;
5423 vm_prot_t enter_fault_type;
5424 if (caller_pmap) {
5425 destination_pmap = caller_pmap;
5426 destination_pmap_vaddr = caller_pmap_addr;
5427 } else {
5428 destination_pmap = pmap;
5429 destination_pmap_vaddr = vaddr;
5430 }
5431 if (change_wiring) {
5432 enter_fault_type = VM_PROT_NONE;
5433 } else {
5434 enter_fault_type = caller_prot;
5435 }
5436 assertf(VM_PAGE_OBJECT(m) == object, "m=%p object=%p", m, object);
5437 kr = vm_fault_enter_prepare(m,
5438 destination_pmap,
5439 destination_pmap_vaddr,
5440 &prot,
5441 caller_prot,
5442 fault_page_size,
5443 fault_phys_offset,
5444 change_wiring,
5445 enter_fault_type,
5446 &fault_info,
5447 &type_of_fault,
5448 &page_needs_data_sync);
5449 if (kr != KERN_SUCCESS) {
5450 goto zero_fill_cleanup;
5451 }
5452
5453 if (object_is_contended) {
5454 /*
5455 * At this point the page is in the vm object, but not on a paging queue.
5456 * Since it's accessible to another thread but its contents are invalid
5457 * (it hasn't been zeroed) mark it busy before dropping the object lock.
5458 */
5459 m->vmp_busy = TRUE;
5460 vm_object_unlock(object);
5461 }
5462 if (type_of_fault == DBG_ZERO_FILL_FAULT) {
5463 /*
5464 * Now zero fill page...
5465 * the page is probably going to
5466 * be written soon, so don't bother
5467 * to clear the modified bit
5468 *
5469 * NOTE: This code holds the map
5470 * lock across the zero fill.
5471 */
5472 vm_page_zero_fill(m);
5473 counter_inc(&vm_statistics_zero_fill_count);
5474 DTRACE_VM2(zfod, int, 1, (uint64_t *), NULL);
5475 }
5476 if (page_needs_data_sync) {
5477 pmap_sync_page_data_phys(VM_PAGE_GET_PHYS_PAGE(m));
5478 }
5479
5480 if (top_object != VM_OBJECT_NULL) {
5481 need_retry_ptr = &need_retry;
5482 } else {
5483 need_retry_ptr = NULL;
5484 }
5485 if (fault_info.fi_xnu_user_debug &&
5486 !object->code_signed) {
5487 fault_info.pmap_options |= PMAP_OPTIONS_XNU_USER_DEBUG;
5488 }
5489 if (object_is_contended) {
5490 kr = vm_fault_pmap_enter(destination_pmap, destination_pmap_vaddr,
5491 fault_page_size, fault_phys_offset,
5492 m, &prot, caller_prot, enter_fault_type, wired,
5493 fault_info.pmap_options, need_retry_ptr);
5494 vm_object_lock(object);
5495 } else {
5496 kr = vm_fault_pmap_enter_with_object_lock(object, destination_pmap, destination_pmap_vaddr,
5497 fault_page_size, fault_phys_offset,
5498 m, &prot, caller_prot, enter_fault_type, wired,
5499 fault_info.pmap_options, need_retry_ptr);
5500 }
5501 }
5502 zero_fill_cleanup:
5503 if (!VM_DYNAMIC_PAGING_ENABLED() &&
5504 (object->purgable == VM_PURGABLE_DENY ||
5505 object->purgable == VM_PURGABLE_NONVOLATILE ||
5506 object->purgable == VM_PURGABLE_VOLATILE)) {
5507 vm_page_lockspin_queues();
5508 if (!VM_DYNAMIC_PAGING_ENABLED()) {
5509 vm_fault_enqueue_throttled_locked(m);
5510 }
5511 vm_page_unlock_queues();
5512 }
5513 vm_fault_enqueue_page(object, m, wired, change_wiring, wire_tag, fault_info.no_cache, &type_of_fault, kr);
5514
5515 if (__improbable(rtfault &&
5516 !m->vmp_realtime &&
5517 vm_pageout_protect_realtime)) {
5518 vm_page_lock_queues();
5519 if (!m->vmp_realtime) {
5520 m->vmp_realtime = true;
5521 vm_page_realtime_count++;
5522 }
5523 vm_page_unlock_queues();
5524 }
5525 vm_fault_complete(
5526 map,
5527 real_map,
5528 object,
5529 m_object,
5530 m,
5531 offset,
5532 trace_real_vaddr,
5533 &fault_info,
5534 caller_prot,
5535 real_vaddr,
5536 type_of_fault,
5537 need_retry,
5538 kr,
5539 physpage_p,
5540 prot,
5541 top_object,
5542 need_collapse,
5543 cur_offset,
5544 fault_type,
5545 &written_on_object,
5546 &written_on_pager,
5547 &written_on_offset);
5548 top_object = VM_OBJECT_NULL;
5549 if (need_retry == TRUE) {
5550 /*
5551 * vm_fault_enter couldn't complete the PMAP_ENTER...
5552 * at this point we don't hold any locks so it's safe
5553 * to ask the pmap layer to expand the page table to
5554 * accommodate this mapping... once expanded, we'll
5555 * re-drive the fault which should result in vm_fault_enter
5556 * being able to successfully enter the mapping this time around
5557 */
5558 (void)pmap_enter_options(
5559 pmap, vaddr, 0, 0, 0, 0, 0,
5560 PMAP_OPTIONS_NOENTER, NULL);
5561
5562 need_retry = FALSE;
5563 goto RetryFault;
5564 }
5565 goto done;
5566 }
5567 /*
5568 * On to the next level in the shadow chain
5569 */
5570 cur_offset += cur_object->vo_shadow_offset;
5571 new_object = cur_object->shadow;
5572 fault_phys_offset = cur_offset - vm_object_trunc_page(cur_offset);
5573
5574 /*
5575 * take the new_object's lock with the indicated state
5576 */
5577 if (cur_object_lock_type == OBJECT_LOCK_SHARED) {
5578 vm_object_lock_shared(new_object);
5579 } else {
5580 vm_object_lock(new_object);
5581 }
5582
5583 if (cur_object != object) {
5584 vm_object_unlock(cur_object);
5585 }
5586
5587 cur_object = new_object;
5588
5589 continue;
5590 }
5591 }
5592 /*
5593 * Cleanup from fast fault failure. Drop any object
5594 * lock other than original and drop map lock.
5595 */
5596 if (object != cur_object) {
5597 vm_object_unlock(cur_object);
5598 }
5599
5600 /*
5601 * must own the object lock exclusively at this point
5602 */
5603 if (object_lock_type == OBJECT_LOCK_SHARED) {
5604 object_lock_type = OBJECT_LOCK_EXCLUSIVE;
5605
5606 if (vm_object_lock_upgrade(object) == FALSE) {
5607 /*
5608 * couldn't upgrade, so explictly
5609 * take the lock exclusively
5610 * no need to retry the fault at this
5611 * point since "vm_fault_page" will
5612 * completely re-evaluate the state
5613 */
5614 vm_object_lock(object);
5615 }
5616 }
5617
5618 handle_copy_delay:
5619 vm_map_unlock_read(map);
5620 if (real_map != map) {
5621 vm_map_unlock(real_map);
5622 }
5623
5624 if (__improbable(object == compressor_object ||
5625 object == kernel_object)) {
5626 /*
5627 * These objects are explicitly managed and populated by the
5628 * kernel. The virtual ranges backed by these objects should
5629 * either have wired pages or "holes" that are not supposed to
5630 * be accessed at all until they get explicitly populated.
5631 * We should never have to resolve a fault on a mapping backed
5632 * by one of these VM objects and providing a zero-filled page
5633 * would be wrong here, so let's fail the fault and let the
5634 * caller crash or recover.
5635 */
5636 vm_object_unlock(object);
5637 kr = KERN_MEMORY_ERROR;
5638 goto done;
5639 }
5640
5641 resilient_media_ref_transfer = false;
5642 if (resilient_media_retry) {
5643 /*
5644 * We could get here if we failed to get a free page
5645 * to zero-fill and had to take the slow path again.
5646 * Reset our "recovery-from-failed-media" state.
5647 */
5648 assert(resilient_media_object != VM_OBJECT_NULL);
5649 assert(resilient_media_offset != (vm_object_offset_t)-1);
5650 /* release our extra reference on failed object */
5651 // printf("FBDP %s:%d resilient_media_object %p deallocate\n", __FUNCTION__, __LINE__, resilient_media_object);
5652 if (object == resilient_media_object) {
5653 /*
5654 * We're holding "object"'s lock, so we can't release
5655 * our extra reference at this point.
5656 * We need an extra reference on "object" anyway
5657 * (see below), so let's just transfer this reference.
5658 */
5659 resilient_media_ref_transfer = true;
5660 } else {
5661 vm_object_lock_assert_notheld(resilient_media_object);
5662 vm_object_deallocate(resilient_media_object);
5663 }
5664 resilient_media_object = VM_OBJECT_NULL;
5665 resilient_media_offset = (vm_object_offset_t)-1;
5666 resilient_media_retry = false;
5667 vm_fault_resilient_media_abort2++;
5668 }
5669
5670 /*
5671 * Make a reference to this object to
5672 * prevent its disposal while we are messing with
5673 * it. Once we have the reference, the map is free
5674 * to be diddled. Since objects reference their
5675 * shadows (and copies), they will stay around as well.
5676 */
5677 if (resilient_media_ref_transfer) {
5678 /* we already have an extra reference on this object */
5679 resilient_media_ref_transfer = false;
5680 } else {
5681 vm_object_reference_locked(object);
5682 }
5683 vm_object_paging_begin(object);
5684
5685 set_thread_pagein_error(cthread, 0);
5686 error_code = 0;
5687
5688 result_page = VM_PAGE_NULL;
5689 kr = vm_fault_page(object, offset, fault_type,
5690 (change_wiring && !wired),
5691 FALSE, /* page not looked up */
5692 &prot, &result_page, &top_page,
5693 &type_of_fault,
5694 &error_code, map->no_zero_fill,
5695 &fault_info);
5696
5697 /*
5698 * if kr != VM_FAULT_SUCCESS, then the paging reference
5699 * has been dropped and the object unlocked... the ref_count
5700 * is still held
5701 *
5702 * if kr == VM_FAULT_SUCCESS, then the paging reference
5703 * is still held along with the ref_count on the original object
5704 *
5705 * the object is returned locked with a paging reference
5706 *
5707 * if top_page != NULL, then it's BUSY and the
5708 * object it belongs to has a paging reference
5709 * but is returned unlocked
5710 */
5711 if (kr != VM_FAULT_SUCCESS &&
5712 kr != VM_FAULT_SUCCESS_NO_VM_PAGE) {
5713 if (kr == VM_FAULT_MEMORY_ERROR &&
5714 fault_info.resilient_media) {
5715 assertf(object->internal, "object %p", object);
5716 /*
5717 * This fault failed but the mapping was
5718 * "media resilient", so we'll retry the fault in
5719 * recovery mode to get a zero-filled page in the
5720 * top object.
5721 * Keep the reference on the failing object so
5722 * that we can check that the mapping is still
5723 * pointing to it when we retry the fault.
5724 */
5725 // 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);
5726 assert(!resilient_media_retry); /* no double retry */
5727 assert(resilient_media_object == VM_OBJECT_NULL);
5728 assert(resilient_media_offset == (vm_object_offset_t)-1);
5729 resilient_media_retry = true;
5730 resilient_media_object = object;
5731 resilient_media_offset = offset;
5732 // printf("FBDP %s:%d resilient_media_object %p offset 0x%llx kept reference\n", __FUNCTION__, __LINE__, resilient_media_object, resilient_mmedia_offset);
5733 vm_fault_resilient_media_initiate++;
5734 goto RetryFault;
5735 } else {
5736 /*
5737 * we didn't succeed, lose the object reference
5738 * immediately.
5739 */
5740 vm_object_deallocate(object);
5741 object = VM_OBJECT_NULL; /* no longer valid */
5742 }
5743
5744 /*
5745 * See why we failed, and take corrective action.
5746 */
5747 switch (kr) {
5748 case VM_FAULT_MEMORY_SHORTAGE:
5749 if (vm_page_wait((change_wiring) ?
5750 THREAD_UNINT :
5751 THREAD_ABORTSAFE)) {
5752 goto RetryFault;
5753 }
5754 ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_FAULT_MEMORY_SHORTAGE), 0 /* arg */);
5755 OS_FALLTHROUGH;
5756 case VM_FAULT_INTERRUPTED:
5757 ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_FAULT_INTERRUPTED), 0 /* arg */);
5758 kr = KERN_ABORTED;
5759 goto done;
5760 case VM_FAULT_RETRY:
5761 goto RetryFault;
5762 case VM_FAULT_MEMORY_ERROR:
5763 if (error_code) {
5764 kr = error_code;
5765 } else {
5766 kr = KERN_MEMORY_ERROR;
5767 }
5768 goto done;
5769 default:
5770 panic("vm_fault: unexpected error 0x%x from "
5771 "vm_fault_page()\n", kr);
5772 }
5773 }
5774 m = result_page;
5775 m_object = NULL;
5776
5777 if (m != VM_PAGE_NULL) {
5778 m_object = VM_PAGE_OBJECT(m);
5779 assert((change_wiring && !wired) ?
5780 (top_page == VM_PAGE_NULL) :
5781 ((top_page == VM_PAGE_NULL) == (m_object == object)));
5782 }
5783
5784 /*
5785 * What to do with the resulting page from vm_fault_page
5786 * if it doesn't get entered into the physical map:
5787 */
5788 #define RELEASE_PAGE(m) \
5789 MACRO_BEGIN \
5790 PAGE_WAKEUP_DONE(m); \
5791 if ( !VM_PAGE_PAGEABLE(m)) { \
5792 vm_page_lockspin_queues(); \
5793 if ( !VM_PAGE_PAGEABLE(m)) \
5794 vm_page_activate(m); \
5795 vm_page_unlock_queues(); \
5796 } \
5797 MACRO_END
5798
5799
5800 object_locks_dropped = FALSE;
5801 /*
5802 * We must verify that the maps have not changed
5803 * since our last lookup. vm_map_verify() needs the
5804 * map lock (shared) but we are holding object locks.
5805 * So we do a try_lock() first and, if that fails, we
5806 * drop the object locks and go in for the map lock again.
5807 */
5808 if (!vm_map_try_lock_read(original_map)) {
5809 if (m != VM_PAGE_NULL) {
5810 old_copy_object = m_object->copy;
5811 vm_object_unlock(m_object);
5812 } else {
5813 old_copy_object = VM_OBJECT_NULL;
5814 vm_object_unlock(object);
5815 }
5816
5817 object_locks_dropped = TRUE;
5818
5819 vm_map_lock_read(original_map);
5820 }
5821
5822 if ((map != original_map) || !vm_map_verify(map, &version)) {
5823 if (object_locks_dropped == FALSE) {
5824 if (m != VM_PAGE_NULL) {
5825 old_copy_object = m_object->copy;
5826 vm_object_unlock(m_object);
5827 } else {
5828 old_copy_object = VM_OBJECT_NULL;
5829 vm_object_unlock(object);
5830 }
5831
5832 object_locks_dropped = TRUE;
5833 }
5834
5835 /*
5836 * no object locks are held at this point
5837 */
5838 vm_object_t retry_object;
5839 vm_object_offset_t retry_offset;
5840 vm_prot_t retry_prot;
5841
5842 /*
5843 * To avoid trying to write_lock the map while another
5844 * thread has it read_locked (in vm_map_pageable), we
5845 * do not try for write permission. If the page is
5846 * still writable, we will get write permission. If it
5847 * is not, or has been marked needs_copy, we enter the
5848 * mapping without write permission, and will merely
5849 * take another fault.
5850 */
5851 map = original_map;
5852
5853 kr = vm_map_lookup_and_lock_object(&map, vaddr,
5854 fault_type & ~VM_PROT_WRITE,
5855 OBJECT_LOCK_EXCLUSIVE, &version,
5856 &retry_object, &retry_offset, &retry_prot,
5857 &wired,
5858 &fault_info,
5859 &real_map,
5860 NULL);
5861 pmap = real_map->pmap;
5862
5863 if (kr != KERN_SUCCESS) {
5864 vm_map_unlock_read(map);
5865
5866 if (m != VM_PAGE_NULL) {
5867 assert(VM_PAGE_OBJECT(m) == m_object);
5868
5869 /*
5870 * retake the lock so that
5871 * we can drop the paging reference
5872 * in vm_fault_cleanup and do the
5873 * PAGE_WAKEUP_DONE in RELEASE_PAGE
5874 */
5875 vm_object_lock(m_object);
5876
5877 RELEASE_PAGE(m);
5878
5879 vm_fault_cleanup(m_object, top_page);
5880 } else {
5881 /*
5882 * retake the lock so that
5883 * we can drop the paging reference
5884 * in vm_fault_cleanup
5885 */
5886 vm_object_lock(object);
5887
5888 vm_fault_cleanup(object, top_page);
5889 }
5890 vm_object_deallocate(object);
5891
5892 if (kr == KERN_INVALID_ADDRESS) {
5893 ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_ADDRESS_NOT_FOUND), 0 /* arg */);
5894 }
5895 goto done;
5896 }
5897 vm_object_unlock(retry_object);
5898
5899 if ((retry_object != object) || (retry_offset != offset)) {
5900 vm_map_unlock_read(map);
5901 if (real_map != map) {
5902 vm_map_unlock(real_map);
5903 }
5904
5905 if (m != VM_PAGE_NULL) {
5906 assert(VM_PAGE_OBJECT(m) == m_object);
5907
5908 /*
5909 * retake the lock so that
5910 * we can drop the paging reference
5911 * in vm_fault_cleanup and do the
5912 * PAGE_WAKEUP_DONE in RELEASE_PAGE
5913 */
5914 vm_object_lock(m_object);
5915
5916 RELEASE_PAGE(m);
5917
5918 vm_fault_cleanup(m_object, top_page);
5919 } else {
5920 /*
5921 * retake the lock so that
5922 * we can drop the paging reference
5923 * in vm_fault_cleanup
5924 */
5925 vm_object_lock(object);
5926
5927 vm_fault_cleanup(object, top_page);
5928 }
5929 vm_object_deallocate(object);
5930
5931 goto RetryFault;
5932 }
5933 /*
5934 * Check whether the protection has changed or the object
5935 * has been copied while we left the map unlocked.
5936 */
5937 if (pmap_has_prot_policy(pmap, fault_info.pmap_options & PMAP_OPTIONS_TRANSLATED_ALLOW_EXECUTE, retry_prot)) {
5938 /* If the pmap layer cares, pass the full set. */
5939 prot = retry_prot;
5940 } else {
5941 prot &= retry_prot;
5942 }
5943 }
5944
5945 if (object_locks_dropped == TRUE) {
5946 if (m != VM_PAGE_NULL) {
5947 assertf(VM_PAGE_OBJECT(m) == m_object, "m=%p m_object=%p", m, m_object);
5948 assert(VM_PAGE_OBJECT(m) != VM_OBJECT_NULL);
5949 vm_object_lock(m_object);
5950
5951 if (m_object->copy != old_copy_object) {
5952 /*
5953 * The copy object changed while the top-level object
5954 * was unlocked, so take away write permission.
5955 */
5956 assert(!pmap_has_prot_policy(pmap, fault_info.pmap_options & PMAP_OPTIONS_TRANSLATED_ALLOW_EXECUTE, prot));
5957 prot &= ~VM_PROT_WRITE;
5958 }
5959 } else {
5960 vm_object_lock(object);
5961 }
5962
5963 object_locks_dropped = FALSE;
5964 }
5965
5966 if (!need_copy &&
5967 !fault_info.no_copy_on_read &&
5968 m != VM_PAGE_NULL &&
5969 VM_PAGE_OBJECT(m) != object &&
5970 !VM_PAGE_OBJECT(m)->pager_trusted &&
5971 vm_protect_privileged_from_untrusted &&
5972 !VM_PAGE_OBJECT(m)->code_signed &&
5973 current_proc_is_privileged()) {
5974 /*
5975 * We found the page we want in an "untrusted" VM object
5976 * down the shadow chain. Since the target is "privileged"
5977 * we want to perform a copy-on-read of that page, so that the
5978 * mapped object gets a stable copy and does not have to
5979 * rely on the "untrusted" object to provide the same
5980 * contents if the page gets reclaimed and has to be paged
5981 * in again later on.
5982 *
5983 * Special case: if the mapping is executable and the untrusted
5984 * object is code-signed and the process is "cs_enforced", we
5985 * do not copy-on-read because that would break code-signing
5986 * enforcement expectations (an executable page must belong
5987 * to a code-signed object) and we can rely on code-signing
5988 * to re-validate the page if it gets evicted and paged back in.
5989 */
5990 // 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);
5991 vm_copied_on_read++;
5992 need_copy_on_read = TRUE;
5993 need_copy = TRUE;
5994 } else {
5995 need_copy_on_read = FALSE;
5996 }
5997
5998 /*
5999 * If we want to wire down this page, but no longer have
6000 * adequate permissions, we must start all over.
6001 * If we decided to copy-on-read, we must also start all over.
6002 */
6003 if ((wired && (fault_type != (prot | VM_PROT_WRITE))) ||
6004 need_copy_on_read) {
6005 vm_map_unlock_read(map);
6006 if (real_map != map) {
6007 vm_map_unlock(real_map);
6008 }
6009
6010 if (m != VM_PAGE_NULL) {
6011 assert(VM_PAGE_OBJECT(m) == m_object);
6012
6013 RELEASE_PAGE(m);
6014
6015 vm_fault_cleanup(m_object, top_page);
6016 } else {
6017 vm_fault_cleanup(object, top_page);
6018 }
6019
6020 vm_object_deallocate(object);
6021
6022 goto RetryFault;
6023 }
6024 if (m != VM_PAGE_NULL) {
6025 /*
6026 * Put this page into the physical map.
6027 * We had to do the unlock above because pmap_enter
6028 * may cause other faults. The page may be on
6029 * the pageout queues. If the pageout daemon comes
6030 * across the page, it will remove it from the queues.
6031 */
6032 if (fault_page_size < PAGE_SIZE) {
6033 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);
6034 assertf((!(fault_phys_offset & FOURK_PAGE_MASK) &&
6035 fault_phys_offset < PAGE_SIZE),
6036 "0x%llx\n", (uint64_t)fault_phys_offset);
6037 } else {
6038 assertf(fault_phys_offset == 0,
6039 "0x%llx\n", (uint64_t)fault_phys_offset);
6040 }
6041 assertf(VM_PAGE_OBJECT(m) == m_object, "m=%p m_object=%p", m, m_object);
6042 assert(VM_PAGE_OBJECT(m) != VM_OBJECT_NULL);
6043 if (caller_pmap) {
6044 kr = vm_fault_enter(m,
6045 caller_pmap,
6046 caller_pmap_addr,
6047 fault_page_size,
6048 fault_phys_offset,
6049 prot,
6050 caller_prot,
6051 wired,
6052 change_wiring,
6053 wire_tag,
6054 &fault_info,
6055 NULL,
6056 &type_of_fault);
6057 } else {
6058 kr = vm_fault_enter(m,
6059 pmap,
6060 vaddr,
6061 fault_page_size,
6062 fault_phys_offset,
6063 prot,
6064 caller_prot,
6065 wired,
6066 change_wiring,
6067 wire_tag,
6068 &fault_info,
6069 NULL,
6070 &type_of_fault);
6071 }
6072 assert(VM_PAGE_OBJECT(m) == m_object);
6073
6074 {
6075 int event_code = 0;
6076
6077 if (m_object->internal) {
6078 event_code = (MACHDBG_CODE(DBG_MACH_WORKINGSET, VM_REAL_FAULT_ADDR_INTERNAL));
6079 } else if (m_object->object_is_shared_cache) {
6080 event_code = (MACHDBG_CODE(DBG_MACH_WORKINGSET, VM_REAL_FAULT_ADDR_SHAREDCACHE));
6081 } else {
6082 event_code = (MACHDBG_CODE(DBG_MACH_WORKINGSET, VM_REAL_FAULT_ADDR_EXTERNAL));
6083 }
6084
6085 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());
6086 KDBG_FILTERED(MACHDBG_CODE(DBG_MACH_WORKINGSET, VM_REAL_FAULT_SLOW), get_current_unique_pid());
6087
6088 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);
6089 }
6090 if (kr != KERN_SUCCESS) {
6091 /* abort this page fault */
6092 vm_map_unlock_read(map);
6093 if (real_map != map) {
6094 vm_map_unlock(real_map);
6095 }
6096 PAGE_WAKEUP_DONE(m);
6097 vm_fault_cleanup(m_object, top_page);
6098 vm_object_deallocate(object);
6099 goto done;
6100 }
6101 if (physpage_p != NULL) {
6102 /* for vm_map_wire_and_extract() */
6103 *physpage_p = VM_PAGE_GET_PHYS_PAGE(m);
6104 if (prot & VM_PROT_WRITE) {
6105 vm_object_lock_assert_exclusive(m_object);
6106 m->vmp_dirty = TRUE;
6107 }
6108 }
6109 } else {
6110 vm_map_entry_t entry;
6111 vm_map_offset_t laddr;
6112 vm_map_offset_t ldelta, hdelta;
6113
6114 /*
6115 * do a pmap block mapping from the physical address
6116 * in the object
6117 */
6118
6119 if (real_map != map) {
6120 vm_map_unlock(real_map);
6121 }
6122
6123 if (original_map != map) {
6124 vm_map_unlock_read(map);
6125 vm_map_lock_read(original_map);
6126 map = original_map;
6127 }
6128 real_map = map;
6129
6130 laddr = vaddr;
6131 hdelta = ldelta = (vm_map_offset_t)0xFFFFFFFFFFFFF000ULL;
6132
6133 while (vm_map_lookup_entry(map, laddr, &entry)) {
6134 if (ldelta > (laddr - entry->vme_start)) {
6135 ldelta = laddr - entry->vme_start;
6136 }
6137 if (hdelta > (entry->vme_end - laddr)) {
6138 hdelta = entry->vme_end - laddr;
6139 }
6140 if (entry->is_sub_map) {
6141 laddr = ((laddr - entry->vme_start)
6142 + VME_OFFSET(entry));
6143 vm_map_lock_read(VME_SUBMAP(entry));
6144
6145 if (map != real_map) {
6146 vm_map_unlock_read(map);
6147 }
6148 if (entry->use_pmap) {
6149 vm_map_unlock_read(real_map);
6150 real_map = VME_SUBMAP(entry);
6151 }
6152 map = VME_SUBMAP(entry);
6153 } else {
6154 break;
6155 }
6156 }
6157
6158 if (vm_map_lookup_entry(map, laddr, &entry) &&
6159 (!entry->is_sub_map) &&
6160 (object != VM_OBJECT_NULL) &&
6161 (VME_OBJECT(entry) == object)) {
6162 uint16_t superpage;
6163
6164 if (!object->pager_created &&
6165 object->phys_contiguous &&
6166 VME_OFFSET(entry) == 0 &&
6167 (entry->vme_end - entry->vme_start == object->vo_size) &&
6168 VM_MAP_PAGE_ALIGNED(entry->vme_start, (object->vo_size - 1))) {
6169 superpage = VM_MEM_SUPERPAGE;
6170 } else {
6171 superpage = 0;
6172 }
6173
6174 if (superpage && physpage_p) {
6175 /* for vm_map_wire_and_extract() */
6176 *physpage_p = (ppnum_t)
6177 ((((vm_map_offset_t)
6178 object->vo_shadow_offset)
6179 + VME_OFFSET(entry)
6180 + (laddr - entry->vme_start))
6181 >> PAGE_SHIFT);
6182 }
6183
6184 if (caller_pmap) {
6185 /*
6186 * Set up a block mapped area
6187 */
6188 assert((uint32_t)((ldelta + hdelta) >> fault_page_shift) == ((ldelta + hdelta) >> fault_page_shift));
6189 kr = pmap_map_block_addr(caller_pmap,
6190 (addr64_t)(caller_pmap_addr - ldelta),
6191 (pmap_paddr_t)(((vm_map_offset_t) (object->vo_shadow_offset)) +
6192 VME_OFFSET(entry) + (laddr - entry->vme_start) - ldelta),
6193 (uint32_t)((ldelta + hdelta) >> fault_page_shift), prot,
6194 (VM_WIMG_MASK & (int)object->wimg_bits) | superpage, 0);
6195
6196 if (kr != KERN_SUCCESS) {
6197 goto cleanup;
6198 }
6199 } else {
6200 /*
6201 * Set up a block mapped area
6202 */
6203 assert((uint32_t)((ldelta + hdelta) >> fault_page_shift) == ((ldelta + hdelta) >> fault_page_shift));
6204 kr = pmap_map_block_addr(real_map->pmap,
6205 (addr64_t)(vaddr - ldelta),
6206 (pmap_paddr_t)(((vm_map_offset_t)(object->vo_shadow_offset)) +
6207 VME_OFFSET(entry) + (laddr - entry->vme_start) - ldelta),
6208 (uint32_t)((ldelta + hdelta) >> fault_page_shift), prot,
6209 (VM_WIMG_MASK & (int)object->wimg_bits) | superpage, 0);
6210
6211 if (kr != KERN_SUCCESS) {
6212 goto cleanup;
6213 }
6214 }
6215 }
6216 }
6217
6218 /*
6219 * Success
6220 */
6221 kr = KERN_SUCCESS;
6222
6223 /*
6224 * TODO: could most of the done cases just use cleanup?
6225 */
6226 cleanup:
6227 /*
6228 * Unlock everything, and return
6229 */
6230 vm_map_unlock_read(map);
6231 if (real_map != map) {
6232 vm_map_unlock(real_map);
6233 }
6234
6235 if (m != VM_PAGE_NULL) {
6236 if (__improbable(rtfault &&
6237 !m->vmp_realtime &&
6238 vm_pageout_protect_realtime)) {
6239 vm_page_lock_queues();
6240 if (!m->vmp_realtime) {
6241 m->vmp_realtime = true;
6242 vm_page_realtime_count++;
6243 }
6244 vm_page_unlock_queues();
6245 }
6246 assert(VM_PAGE_OBJECT(m) == m_object);
6247
6248 if (!m_object->internal && (fault_type & VM_PROT_WRITE)) {
6249 vm_object_paging_begin(m_object);
6250
6251 assert(written_on_object == VM_OBJECT_NULL);
6252 written_on_object = m_object;
6253 written_on_pager = m_object->pager;
6254 written_on_offset = m_object->paging_offset + m->vmp_offset;
6255 }
6256 PAGE_WAKEUP_DONE(m);
6257
6258 vm_fault_cleanup(m_object, top_page);
6259 } else {
6260 vm_fault_cleanup(object, top_page);
6261 }
6262
6263 vm_object_deallocate(object);
6264
6265 #undef RELEASE_PAGE
6266
6267 done:
6268 thread_interrupt_level(interruptible_state);
6269
6270 if (resilient_media_object != VM_OBJECT_NULL) {
6271 assert(resilient_media_retry);
6272 assert(resilient_media_offset != (vm_object_offset_t)-1);
6273 /* release extra reference on failed object */
6274 // printf("FBDP %s:%d resilient_media_object %p deallocate\n", __FUNCTION__, __LINE__, resilient_media_object);
6275 vm_object_lock_assert_notheld(resilient_media_object);
6276 vm_object_deallocate(resilient_media_object);
6277 resilient_media_object = VM_OBJECT_NULL;
6278 resilient_media_offset = (vm_object_offset_t)-1;
6279 resilient_media_retry = false;
6280 vm_fault_resilient_media_release++;
6281 }
6282 assert(!resilient_media_retry);
6283
6284 /*
6285 * Only I/O throttle on faults which cause a pagein/swapin.
6286 */
6287 if ((type_of_fault == DBG_PAGEIND_FAULT) || (type_of_fault == DBG_PAGEINV_FAULT) || (type_of_fault == DBG_COMPRESSOR_SWAPIN_FAULT)) {
6288 throttle_lowpri_io(1);
6289 } else {
6290 if (kr == KERN_SUCCESS && type_of_fault != DBG_CACHE_HIT_FAULT && type_of_fault != DBG_GUARD_FAULT) {
6291 if ((throttle_delay = vm_page_throttled(TRUE))) {
6292 if (vm_debug_events) {
6293 if (type_of_fault == DBG_COMPRESSOR_FAULT) {
6294 VM_DEBUG_EVENT(vmf_compressordelay, VMF_COMPRESSORDELAY, DBG_FUNC_NONE, throttle_delay, 0, 0, 0);
6295 } else if (type_of_fault == DBG_COW_FAULT) {
6296 VM_DEBUG_EVENT(vmf_cowdelay, VMF_COWDELAY, DBG_FUNC_NONE, throttle_delay, 0, 0, 0);
6297 } else {
6298 VM_DEBUG_EVENT(vmf_zfdelay, VMF_ZFDELAY, DBG_FUNC_NONE, throttle_delay, 0, 0, 0);
6299 }
6300 }
6301 __VM_FAULT_THROTTLE_FOR_PAGEOUT_SCAN__(throttle_delay);
6302 }
6303 }
6304 }
6305
6306 if (written_on_object) {
6307 vnode_pager_dirtied(written_on_pager, written_on_offset, written_on_offset + PAGE_SIZE_64);
6308
6309 vm_object_lock(written_on_object);
6310 vm_object_paging_end(written_on_object);
6311 vm_object_unlock(written_on_object);
6312
6313 written_on_object = VM_OBJECT_NULL;
6314 }
6315
6316 if (rtfault) {
6317 vm_record_rtfault(cthread, fstart, trace_vaddr, type_of_fault);
6318 }
6319
6320 KDBG_RELEASE(
6321 (MACHDBG_CODE(DBG_MACH_VM, 2)) | DBG_FUNC_END,
6322 ((uint64_t)trace_vaddr >> 32),
6323 trace_vaddr,
6324 kr,
6325 vm_fault_type_for_tracing(need_copy_on_read, type_of_fault));
6326
6327 if (fault_page_size < PAGE_SIZE && kr != KERN_SUCCESS) {
6328 DEBUG4K_FAULT("map %p original %p vaddr 0x%llx -> 0x%x\n", map, original_map, (uint64_t)trace_real_vaddr, kr);
6329 }
6330
6331 return kr;
6332 }
6333
6334 /*
6335 * vm_fault_wire:
6336 *
6337 * Wire down a range of virtual addresses in a map.
6338 */
6339 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)6340 vm_fault_wire(
6341 vm_map_t map,
6342 vm_map_entry_t entry,
6343 vm_prot_t prot,
6344 vm_tag_t wire_tag,
6345 pmap_t pmap,
6346 vm_map_offset_t pmap_addr,
6347 ppnum_t *physpage_p)
6348 {
6349 vm_map_offset_t va;
6350 vm_map_offset_t end_addr = entry->vme_end;
6351 kern_return_t rc;
6352 vm_map_size_t effective_page_size;
6353
6354 assert(entry->in_transition);
6355
6356 if (!entry->is_sub_map &&
6357 VME_OBJECT(entry) != VM_OBJECT_NULL &&
6358 VME_OBJECT(entry)->phys_contiguous) {
6359 return KERN_SUCCESS;
6360 }
6361
6362 /*
6363 * Inform the physical mapping system that the
6364 * range of addresses may not fault, so that
6365 * page tables and such can be locked down as well.
6366 */
6367
6368 pmap_pageable(pmap, pmap_addr,
6369 pmap_addr + (end_addr - entry->vme_start), FALSE);
6370
6371 /*
6372 * We simulate a fault to get the page and enter it
6373 * in the physical map.
6374 */
6375
6376 effective_page_size = MIN(VM_MAP_PAGE_SIZE(map), PAGE_SIZE);
6377 for (va = entry->vme_start;
6378 va < end_addr;
6379 va += effective_page_size) {
6380 rc = vm_fault_wire_fast(map, va, prot, wire_tag, entry, pmap,
6381 pmap_addr + (va - entry->vme_start),
6382 physpage_p);
6383 if (rc != KERN_SUCCESS) {
6384 rc = vm_fault_internal(map, va, prot, TRUE, wire_tag,
6385 ((pmap == kernel_pmap)
6386 ? THREAD_UNINT
6387 : THREAD_ABORTSAFE),
6388 pmap,
6389 (pmap_addr +
6390 (va - entry->vme_start)),
6391 physpage_p);
6392 DTRACE_VM2(softlock, int, 1, (uint64_t *), NULL);
6393 }
6394
6395 if (rc != KERN_SUCCESS) {
6396 struct vm_map_entry tmp_entry = *entry;
6397
6398 /* unwire wired pages */
6399 tmp_entry.vme_end = va;
6400 vm_fault_unwire(map, &tmp_entry, FALSE,
6401 pmap, pmap_addr, tmp_entry.vme_end);
6402
6403 return rc;
6404 }
6405 }
6406 return KERN_SUCCESS;
6407 }
6408
6409 /*
6410 * vm_fault_unwire:
6411 *
6412 * Unwire a range of virtual addresses in a map.
6413 */
6414 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)6415 vm_fault_unwire(
6416 vm_map_t map,
6417 vm_map_entry_t entry,
6418 boolean_t deallocate,
6419 pmap_t pmap,
6420 vm_map_offset_t pmap_addr,
6421 vm_map_offset_t end_addr)
6422 {
6423 vm_map_offset_t va;
6424 vm_object_t object;
6425 struct vm_object_fault_info fault_info = {};
6426 unsigned int unwired_pages;
6427 vm_map_size_t effective_page_size;
6428
6429 object = (entry->is_sub_map) ? VM_OBJECT_NULL : VME_OBJECT(entry);
6430
6431 /*
6432 * If it's marked phys_contiguous, then vm_fault_wire() didn't actually
6433 * do anything since such memory is wired by default. So we don't have
6434 * anything to undo here.
6435 */
6436
6437 if (object != VM_OBJECT_NULL && object->phys_contiguous) {
6438 return;
6439 }
6440
6441 fault_info.interruptible = THREAD_UNINT;
6442 fault_info.behavior = entry->behavior;
6443 fault_info.user_tag = VME_ALIAS(entry);
6444 if (entry->iokit_acct ||
6445 (!entry->is_sub_map && !entry->use_pmap)) {
6446 fault_info.pmap_options |= PMAP_OPTIONS_ALT_ACCT;
6447 }
6448 fault_info.lo_offset = VME_OFFSET(entry);
6449 fault_info.hi_offset = (entry->vme_end - entry->vme_start) + VME_OFFSET(entry);
6450 fault_info.no_cache = entry->no_cache;
6451 fault_info.stealth = TRUE;
6452 if (entry->vme_xnu_user_debug) {
6453 /*
6454 * Modified code-signed executable region: wired pages must
6455 * have been copied, so they should be XNU_USER_DEBUG rather
6456 * than XNU_USER_EXEC.
6457 */
6458 fault_info.pmap_options |= PMAP_OPTIONS_XNU_USER_DEBUG;
6459 }
6460
6461 unwired_pages = 0;
6462
6463 /*
6464 * Since the pages are wired down, we must be able to
6465 * get their mappings from the physical map system.
6466 */
6467
6468 effective_page_size = MIN(VM_MAP_PAGE_SIZE(map), PAGE_SIZE);
6469 for (va = entry->vme_start;
6470 va < end_addr;
6471 va += effective_page_size) {
6472 if (object == VM_OBJECT_NULL) {
6473 if (pmap) {
6474 pmap_change_wiring(pmap,
6475 pmap_addr + (va - entry->vme_start), FALSE);
6476 }
6477 (void) vm_fault(map, va, VM_PROT_NONE,
6478 TRUE, VM_KERN_MEMORY_NONE, THREAD_UNINT, pmap, pmap_addr);
6479 } else {
6480 vm_prot_t prot;
6481 vm_page_t result_page;
6482 vm_page_t top_page;
6483 vm_object_t result_object;
6484 vm_fault_return_t result;
6485
6486 /* cap cluster size at maximum UPL size */
6487 upl_size_t cluster_size;
6488 if (os_sub_overflow(end_addr, va, &cluster_size)) {
6489 cluster_size = 0 - (upl_size_t)PAGE_SIZE;
6490 }
6491 fault_info.cluster_size = cluster_size;
6492
6493 do {
6494 prot = VM_PROT_NONE;
6495
6496 vm_object_lock(object);
6497 vm_object_paging_begin(object);
6498 result_page = VM_PAGE_NULL;
6499 result = vm_fault_page(
6500 object,
6501 (VME_OFFSET(entry) +
6502 (va - entry->vme_start)),
6503 VM_PROT_NONE, TRUE,
6504 FALSE, /* page not looked up */
6505 &prot, &result_page, &top_page,
6506 (int *)0,
6507 NULL, map->no_zero_fill,
6508 &fault_info);
6509 } while (result == VM_FAULT_RETRY);
6510
6511 /*
6512 * If this was a mapping to a file on a device that has been forcibly
6513 * unmounted, then we won't get a page back from vm_fault_page(). Just
6514 * move on to the next one in case the remaining pages are mapped from
6515 * different objects. During a forced unmount, the object is terminated
6516 * so the alive flag will be false if this happens. A forced unmount will
6517 * will occur when an external disk is unplugged before the user does an
6518 * eject, so we don't want to panic in that situation.
6519 */
6520
6521 if (result == VM_FAULT_MEMORY_ERROR) {
6522 if (!object->alive) {
6523 continue;
6524 }
6525 if (!object->internal && object->pager == NULL) {
6526 continue;
6527 }
6528 }
6529
6530 if (result == VM_FAULT_MEMORY_ERROR &&
6531 object == kernel_object) {
6532 /*
6533 * This must have been allocated with
6534 * KMA_KOBJECT and KMA_VAONLY and there's
6535 * no physical page at this offset.
6536 * We're done (no page to free).
6537 */
6538 assert(deallocate);
6539 continue;
6540 }
6541
6542 if (result != VM_FAULT_SUCCESS) {
6543 panic("vm_fault_unwire: failure");
6544 }
6545
6546 result_object = VM_PAGE_OBJECT(result_page);
6547
6548 if (deallocate) {
6549 assert(VM_PAGE_GET_PHYS_PAGE(result_page) !=
6550 vm_page_fictitious_addr);
6551 pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(result_page));
6552 if (VM_PAGE_WIRED(result_page)) {
6553 unwired_pages++;
6554 }
6555 VM_PAGE_FREE(result_page);
6556 } else {
6557 if ((pmap) && (VM_PAGE_GET_PHYS_PAGE(result_page) != vm_page_guard_addr)) {
6558 pmap_change_wiring(pmap,
6559 pmap_addr + (va - entry->vme_start), FALSE);
6560 }
6561
6562
6563 if (VM_PAGE_WIRED(result_page)) {
6564 vm_page_lockspin_queues();
6565 vm_page_unwire(result_page, TRUE);
6566 vm_page_unlock_queues();
6567 unwired_pages++;
6568 }
6569 if (entry->zero_wired_pages) {
6570 pmap_zero_page(VM_PAGE_GET_PHYS_PAGE(result_page));
6571 entry->zero_wired_pages = FALSE;
6572 }
6573
6574 PAGE_WAKEUP_DONE(result_page);
6575 }
6576 vm_fault_cleanup(result_object, top_page);
6577 }
6578 }
6579
6580 /*
6581 * Inform the physical mapping system that the range
6582 * of addresses may fault, so that page tables and
6583 * such may be unwired themselves.
6584 */
6585
6586 pmap_pageable(pmap, pmap_addr,
6587 pmap_addr + (end_addr - entry->vme_start), TRUE);
6588
6589 if (kernel_object == object) {
6590 /*
6591 * Would like to make user_tag in vm_object_fault_info
6592 * vm_tag_t (unsigned short) but user_tag derives its value from
6593 * VME_ALIAS(entry) at a few places and VME_ALIAS, in turn, casts
6594 * to an _unsigned int_ which is used by non-fault_info paths throughout the
6595 * code at many places.
6596 *
6597 * So, for now, an explicit truncation to unsigned short (vm_tag_t).
6598 */
6599 assertf((fault_info.user_tag & VME_ALIAS_MASK) == fault_info.user_tag,
6600 "VM Tag truncated from 0x%x to 0x%x\n", fault_info.user_tag, (fault_info.user_tag & VME_ALIAS_MASK));
6601 vm_tag_update_size((vm_tag_t) fault_info.user_tag, -ptoa_64(unwired_pages));
6602 }
6603 }
6604
6605 /*
6606 * vm_fault_wire_fast:
6607 *
6608 * Handle common case of a wire down page fault at the given address.
6609 * If successful, the page is inserted into the associated physical map.
6610 * The map entry is passed in to avoid the overhead of a map lookup.
6611 *
6612 * NOTE: the given address should be truncated to the
6613 * proper page address.
6614 *
6615 * KERN_SUCCESS is returned if the page fault is handled; otherwise,
6616 * a standard error specifying why the fault is fatal is returned.
6617 *
6618 * The map in question must be referenced, and remains so.
6619 * Caller has a read lock on the map.
6620 *
6621 * This is a stripped version of vm_fault() for wiring pages. Anything
6622 * other than the common case will return KERN_FAILURE, and the caller
6623 * is expected to call vm_fault().
6624 */
6625 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)6626 vm_fault_wire_fast(
6627 __unused vm_map_t map,
6628 vm_map_offset_t va,
6629 __unused vm_prot_t caller_prot,
6630 vm_tag_t wire_tag,
6631 vm_map_entry_t entry,
6632 pmap_t pmap,
6633 vm_map_offset_t pmap_addr,
6634 ppnum_t *physpage_p)
6635 {
6636 vm_object_t object;
6637 vm_object_offset_t offset;
6638 vm_page_t m;
6639 vm_prot_t prot;
6640 thread_t thread = current_thread();
6641 int type_of_fault;
6642 kern_return_t kr;
6643 vm_map_size_t fault_page_size;
6644 vm_map_offset_t fault_phys_offset;
6645 struct vm_object_fault_info fault_info = {};
6646
6647 counter_inc(&vm_statistics_faults);
6648
6649 if (thread != THREAD_NULL) {
6650 counter_inc(&get_threadtask(thread)->faults);
6651 }
6652
6653 /*
6654 * Recovery actions
6655 */
6656
6657 #undef RELEASE_PAGE
6658 #define RELEASE_PAGE(m) { \
6659 PAGE_WAKEUP_DONE(m); \
6660 vm_page_lockspin_queues(); \
6661 vm_page_unwire(m, TRUE); \
6662 vm_page_unlock_queues(); \
6663 }
6664
6665
6666 #undef UNLOCK_THINGS
6667 #define UNLOCK_THINGS { \
6668 vm_object_paging_end(object); \
6669 vm_object_unlock(object); \
6670 }
6671
6672 #undef UNLOCK_AND_DEALLOCATE
6673 #define UNLOCK_AND_DEALLOCATE { \
6674 UNLOCK_THINGS; \
6675 vm_object_deallocate(object); \
6676 }
6677 /*
6678 * Give up and have caller do things the hard way.
6679 */
6680
6681 #define GIVE_UP { \
6682 UNLOCK_AND_DEALLOCATE; \
6683 return(KERN_FAILURE); \
6684 }
6685
6686
6687 /*
6688 * If this entry is not directly to a vm_object, bail out.
6689 */
6690 if (entry->is_sub_map) {
6691 assert(physpage_p == NULL);
6692 return KERN_FAILURE;
6693 }
6694
6695 /*
6696 * Find the backing store object and offset into it.
6697 */
6698
6699 object = VME_OBJECT(entry);
6700 offset = (va - entry->vme_start) + VME_OFFSET(entry);
6701 prot = entry->protection;
6702
6703 /*
6704 * Make a reference to this object to prevent its
6705 * disposal while we are messing with it.
6706 */
6707
6708 vm_object_lock(object);
6709 vm_object_reference_locked(object);
6710 vm_object_paging_begin(object);
6711
6712 /*
6713 * INVARIANTS (through entire routine):
6714 *
6715 * 1) At all times, we must either have the object
6716 * lock or a busy page in some object to prevent
6717 * some other thread from trying to bring in
6718 * the same page.
6719 *
6720 * 2) Once we have a busy page, we must remove it from
6721 * the pageout queues, so that the pageout daemon
6722 * will not grab it away.
6723 *
6724 */
6725
6726 /*
6727 * Look for page in top-level object. If it's not there or
6728 * there's something going on, give up.
6729 */
6730 m = vm_page_lookup(object, vm_object_trunc_page(offset));
6731 if ((m == VM_PAGE_NULL) || (m->vmp_busy) ||
6732 (m->vmp_unusual && (VMP_ERROR_GET(m) || m->vmp_restart || m->vmp_absent))) {
6733 GIVE_UP;
6734 }
6735 if (m->vmp_fictitious &&
6736 VM_PAGE_GET_PHYS_PAGE(m) == vm_page_guard_addr) {
6737 /*
6738 * Guard pages are fictitious pages and are never
6739 * entered into a pmap, so let's say it's been wired...
6740 */
6741 kr = KERN_SUCCESS;
6742 goto done;
6743 }
6744
6745 /*
6746 * Wire the page down now. All bail outs beyond this
6747 * point must unwire the page.
6748 */
6749
6750 vm_page_lockspin_queues();
6751 vm_page_wire(m, wire_tag, TRUE);
6752 vm_page_unlock_queues();
6753
6754 /*
6755 * Mark page busy for other threads.
6756 */
6757 assert(!m->vmp_busy);
6758 m->vmp_busy = TRUE;
6759 assert(!m->vmp_absent);
6760
6761 /*
6762 * Give up if the page is being written and there's a copy object
6763 */
6764 if ((object->copy != VM_OBJECT_NULL) && (prot & VM_PROT_WRITE)) {
6765 RELEASE_PAGE(m);
6766 GIVE_UP;
6767 }
6768
6769 fault_info.user_tag = VME_ALIAS(entry);
6770 fault_info.pmap_options = 0;
6771 if (entry->iokit_acct ||
6772 (!entry->is_sub_map && !entry->use_pmap)) {
6773 fault_info.pmap_options |= PMAP_OPTIONS_ALT_ACCT;
6774 }
6775 if (entry->vme_xnu_user_debug) {
6776 /*
6777 * Modified code-signed executable region: wiring will
6778 * copy the pages, so they should be XNU_USER_DEBUG rather
6779 * than XNU_USER_EXEC.
6780 */
6781 fault_info.pmap_options |= PMAP_OPTIONS_XNU_USER_DEBUG;
6782 }
6783
6784 fault_page_size = MIN(VM_MAP_PAGE_SIZE(map), PAGE_SIZE);
6785 fault_phys_offset = offset - vm_object_trunc_page(offset);
6786
6787 /*
6788 * Put this page into the physical map.
6789 */
6790 type_of_fault = DBG_CACHE_HIT_FAULT;
6791 assertf(VM_PAGE_OBJECT(m) == object, "m=%p object=%p", m, object);
6792 assert(VM_PAGE_OBJECT(m) != VM_OBJECT_NULL);
6793 kr = vm_fault_enter(m,
6794 pmap,
6795 pmap_addr,
6796 fault_page_size,
6797 fault_phys_offset,
6798 prot,
6799 prot,
6800 TRUE, /* wired */
6801 FALSE, /* change_wiring */
6802 wire_tag,
6803 &fault_info,
6804 NULL,
6805 &type_of_fault);
6806 if (kr != KERN_SUCCESS) {
6807 RELEASE_PAGE(m);
6808 GIVE_UP;
6809 }
6810
6811 done:
6812 /*
6813 * Unlock everything, and return
6814 */
6815
6816 if (physpage_p) {
6817 /* for vm_map_wire_and_extract() */
6818 if (kr == KERN_SUCCESS) {
6819 assert(object == VM_PAGE_OBJECT(m));
6820 *physpage_p = VM_PAGE_GET_PHYS_PAGE(m);
6821 if (prot & VM_PROT_WRITE) {
6822 vm_object_lock_assert_exclusive(object);
6823 m->vmp_dirty = TRUE;
6824 }
6825 } else {
6826 *physpage_p = 0;
6827 }
6828 }
6829
6830 PAGE_WAKEUP_DONE(m);
6831 UNLOCK_AND_DEALLOCATE;
6832
6833 return kr;
6834 }
6835
6836 /*
6837 * Routine: vm_fault_copy_cleanup
6838 * Purpose:
6839 * Release a page used by vm_fault_copy.
6840 */
6841
6842 static void
vm_fault_copy_cleanup(vm_page_t page,vm_page_t top_page)6843 vm_fault_copy_cleanup(
6844 vm_page_t page,
6845 vm_page_t top_page)
6846 {
6847 vm_object_t object = VM_PAGE_OBJECT(page);
6848
6849 vm_object_lock(object);
6850 PAGE_WAKEUP_DONE(page);
6851 if (!VM_PAGE_PAGEABLE(page)) {
6852 vm_page_lockspin_queues();
6853 if (!VM_PAGE_PAGEABLE(page)) {
6854 vm_page_activate(page);
6855 }
6856 vm_page_unlock_queues();
6857 }
6858 vm_fault_cleanup(object, top_page);
6859 }
6860
6861 static void
vm_fault_copy_dst_cleanup(vm_page_t page)6862 vm_fault_copy_dst_cleanup(
6863 vm_page_t page)
6864 {
6865 vm_object_t object;
6866
6867 if (page != VM_PAGE_NULL) {
6868 object = VM_PAGE_OBJECT(page);
6869 vm_object_lock(object);
6870 vm_page_lockspin_queues();
6871 vm_page_unwire(page, TRUE);
6872 vm_page_unlock_queues();
6873 vm_object_paging_end(object);
6874 vm_object_unlock(object);
6875 }
6876 }
6877
6878 /*
6879 * Routine: vm_fault_copy
6880 *
6881 * Purpose:
6882 * Copy pages from one virtual memory object to another --
6883 * neither the source nor destination pages need be resident.
6884 *
6885 * Before actually copying a page, the version associated with
6886 * the destination address map wil be verified.
6887 *
6888 * In/out conditions:
6889 * The caller must hold a reference, but not a lock, to
6890 * each of the source and destination objects and to the
6891 * destination map.
6892 *
6893 * Results:
6894 * Returns KERN_SUCCESS if no errors were encountered in
6895 * reading or writing the data. Returns KERN_INTERRUPTED if
6896 * the operation was interrupted (only possible if the
6897 * "interruptible" argument is asserted). Other return values
6898 * indicate a permanent error in copying the data.
6899 *
6900 * The actual amount of data copied will be returned in the
6901 * "copy_size" argument. In the event that the destination map
6902 * verification failed, this amount may be less than the amount
6903 * requested.
6904 */
6905 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)6906 vm_fault_copy(
6907 vm_object_t src_object,
6908 vm_object_offset_t src_offset,
6909 vm_map_size_t *copy_size, /* INOUT */
6910 vm_object_t dst_object,
6911 vm_object_offset_t dst_offset,
6912 vm_map_t dst_map,
6913 vm_map_version_t *dst_version,
6914 int interruptible)
6915 {
6916 vm_page_t result_page;
6917
6918 vm_page_t src_page;
6919 vm_page_t src_top_page;
6920 vm_prot_t src_prot;
6921
6922 vm_page_t dst_page;
6923 vm_page_t dst_top_page;
6924 vm_prot_t dst_prot;
6925
6926 vm_map_size_t amount_left;
6927 vm_object_t old_copy_object;
6928 vm_object_t result_page_object = NULL;
6929 kern_return_t error = 0;
6930 vm_fault_return_t result;
6931
6932 vm_map_size_t part_size;
6933 struct vm_object_fault_info fault_info_src = {};
6934 struct vm_object_fault_info fault_info_dst = {};
6935
6936 /*
6937 * In order not to confuse the clustered pageins, align
6938 * the different offsets on a page boundary.
6939 */
6940
6941 #define RETURN(x) \
6942 MACRO_BEGIN \
6943 *copy_size -= amount_left; \
6944 MACRO_RETURN(x); \
6945 MACRO_END
6946
6947 amount_left = *copy_size;
6948
6949 fault_info_src.interruptible = interruptible;
6950 fault_info_src.behavior = VM_BEHAVIOR_SEQUENTIAL;
6951 fault_info_src.lo_offset = vm_object_trunc_page(src_offset);
6952 fault_info_src.hi_offset = fault_info_src.lo_offset + amount_left;
6953 fault_info_src.stealth = TRUE;
6954
6955 fault_info_dst.interruptible = interruptible;
6956 fault_info_dst.behavior = VM_BEHAVIOR_SEQUENTIAL;
6957 fault_info_dst.lo_offset = vm_object_trunc_page(dst_offset);
6958 fault_info_dst.hi_offset = fault_info_dst.lo_offset + amount_left;
6959 fault_info_dst.stealth = TRUE;
6960
6961 do { /* while (amount_left > 0) */
6962 /*
6963 * There may be a deadlock if both source and destination
6964 * pages are the same. To avoid this deadlock, the copy must
6965 * start by getting the destination page in order to apply
6966 * COW semantics if any.
6967 */
6968
6969 RetryDestinationFault:;
6970
6971 dst_prot = VM_PROT_WRITE | VM_PROT_READ;
6972
6973 vm_object_lock(dst_object);
6974 vm_object_paging_begin(dst_object);
6975
6976 /* cap cluster size at maximum UPL size */
6977 upl_size_t cluster_size;
6978 if (os_convert_overflow(amount_left, &cluster_size)) {
6979 cluster_size = 0 - (upl_size_t)PAGE_SIZE;
6980 }
6981 fault_info_dst.cluster_size = cluster_size;
6982
6983 dst_page = VM_PAGE_NULL;
6984 result = vm_fault_page(dst_object,
6985 vm_object_trunc_page(dst_offset),
6986 VM_PROT_WRITE | VM_PROT_READ,
6987 FALSE,
6988 FALSE, /* page not looked up */
6989 &dst_prot, &dst_page, &dst_top_page,
6990 (int *)0,
6991 &error,
6992 dst_map->no_zero_fill,
6993 &fault_info_dst);
6994 switch (result) {
6995 case VM_FAULT_SUCCESS:
6996 break;
6997 case VM_FAULT_RETRY:
6998 goto RetryDestinationFault;
6999 case VM_FAULT_MEMORY_SHORTAGE:
7000 if (vm_page_wait(interruptible)) {
7001 goto RetryDestinationFault;
7002 }
7003 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 */);
7004 OS_FALLTHROUGH;
7005 case VM_FAULT_INTERRUPTED:
7006 RETURN(MACH_SEND_INTERRUPTED);
7007 case VM_FAULT_SUCCESS_NO_VM_PAGE:
7008 /* success but no VM page: fail the copy */
7009 vm_object_paging_end(dst_object);
7010 vm_object_unlock(dst_object);
7011 OS_FALLTHROUGH;
7012 case VM_FAULT_MEMORY_ERROR:
7013 if (error) {
7014 return error;
7015 } else {
7016 return KERN_MEMORY_ERROR;
7017 }
7018 default:
7019 panic("vm_fault_copy: unexpected error 0x%x from "
7020 "vm_fault_page()\n", result);
7021 }
7022 assert((dst_prot & VM_PROT_WRITE) != VM_PROT_NONE);
7023
7024 assert(dst_object == VM_PAGE_OBJECT(dst_page));
7025 old_copy_object = dst_object->copy;
7026
7027 /*
7028 * There exists the possiblity that the source and
7029 * destination page are the same. But we can't
7030 * easily determine that now. If they are the
7031 * same, the call to vm_fault_page() for the
7032 * destination page will deadlock. To prevent this we
7033 * wire the page so we can drop busy without having
7034 * the page daemon steal the page. We clean up the
7035 * top page but keep the paging reference on the object
7036 * holding the dest page so it doesn't go away.
7037 */
7038
7039 vm_page_lockspin_queues();
7040 vm_page_wire(dst_page, VM_KERN_MEMORY_OSFMK, TRUE);
7041 vm_page_unlock_queues();
7042 PAGE_WAKEUP_DONE(dst_page);
7043 vm_object_unlock(dst_object);
7044
7045 if (dst_top_page != VM_PAGE_NULL) {
7046 vm_object_lock(dst_object);
7047 VM_PAGE_FREE(dst_top_page);
7048 vm_object_paging_end(dst_object);
7049 vm_object_unlock(dst_object);
7050 }
7051
7052 RetrySourceFault:;
7053
7054 if (src_object == VM_OBJECT_NULL) {
7055 /*
7056 * No source object. We will just
7057 * zero-fill the page in dst_object.
7058 */
7059 src_page = VM_PAGE_NULL;
7060 result_page = VM_PAGE_NULL;
7061 } else {
7062 vm_object_lock(src_object);
7063 src_page = vm_page_lookup(src_object,
7064 vm_object_trunc_page(src_offset));
7065 if (src_page == dst_page) {
7066 src_prot = dst_prot;
7067 result_page = VM_PAGE_NULL;
7068 } else {
7069 src_prot = VM_PROT_READ;
7070 vm_object_paging_begin(src_object);
7071
7072 /* cap cluster size at maximum UPL size */
7073 if (os_convert_overflow(amount_left, &cluster_size)) {
7074 cluster_size = 0 - (upl_size_t)PAGE_SIZE;
7075 }
7076 fault_info_src.cluster_size = cluster_size;
7077
7078 result_page = VM_PAGE_NULL;
7079 result = vm_fault_page(
7080 src_object,
7081 vm_object_trunc_page(src_offset),
7082 VM_PROT_READ, FALSE,
7083 FALSE, /* page not looked up */
7084 &src_prot,
7085 &result_page, &src_top_page,
7086 (int *)0, &error, FALSE,
7087 &fault_info_src);
7088
7089 switch (result) {
7090 case VM_FAULT_SUCCESS:
7091 break;
7092 case VM_FAULT_RETRY:
7093 goto RetrySourceFault;
7094 case VM_FAULT_MEMORY_SHORTAGE:
7095 if (vm_page_wait(interruptible)) {
7096 goto RetrySourceFault;
7097 }
7098 OS_FALLTHROUGH;
7099 case VM_FAULT_INTERRUPTED:
7100 vm_fault_copy_dst_cleanup(dst_page);
7101 RETURN(MACH_SEND_INTERRUPTED);
7102 case VM_FAULT_SUCCESS_NO_VM_PAGE:
7103 /* success but no VM page: fail */
7104 vm_object_paging_end(src_object);
7105 vm_object_unlock(src_object);
7106 OS_FALLTHROUGH;
7107 case VM_FAULT_MEMORY_ERROR:
7108 vm_fault_copy_dst_cleanup(dst_page);
7109 if (error) {
7110 return error;
7111 } else {
7112 return KERN_MEMORY_ERROR;
7113 }
7114 default:
7115 panic("vm_fault_copy(2): unexpected "
7116 "error 0x%x from "
7117 "vm_fault_page()\n", result);
7118 }
7119
7120 result_page_object = VM_PAGE_OBJECT(result_page);
7121 assert((src_top_page == VM_PAGE_NULL) ==
7122 (result_page_object == src_object));
7123 }
7124 assert((src_prot & VM_PROT_READ) != VM_PROT_NONE);
7125 vm_object_unlock(result_page_object);
7126 }
7127
7128 vm_map_lock_read(dst_map);
7129
7130 if (!vm_map_verify(dst_map, dst_version)) {
7131 vm_map_unlock_read(dst_map);
7132 if (result_page != VM_PAGE_NULL && src_page != dst_page) {
7133 vm_fault_copy_cleanup(result_page, src_top_page);
7134 }
7135 vm_fault_copy_dst_cleanup(dst_page);
7136 break;
7137 }
7138 assert(dst_object == VM_PAGE_OBJECT(dst_page));
7139
7140 vm_object_lock(dst_object);
7141
7142 if (dst_object->copy != old_copy_object) {
7143 vm_object_unlock(dst_object);
7144 vm_map_unlock_read(dst_map);
7145 if (result_page != VM_PAGE_NULL && src_page != dst_page) {
7146 vm_fault_copy_cleanup(result_page, src_top_page);
7147 }
7148 vm_fault_copy_dst_cleanup(dst_page);
7149 break;
7150 }
7151 vm_object_unlock(dst_object);
7152
7153 /*
7154 * Copy the page, and note that it is dirty
7155 * immediately.
7156 */
7157
7158 if (!page_aligned(src_offset) ||
7159 !page_aligned(dst_offset) ||
7160 !page_aligned(amount_left)) {
7161 vm_object_offset_t src_po,
7162 dst_po;
7163
7164 src_po = src_offset - vm_object_trunc_page(src_offset);
7165 dst_po = dst_offset - vm_object_trunc_page(dst_offset);
7166
7167 if (dst_po > src_po) {
7168 part_size = PAGE_SIZE - dst_po;
7169 } else {
7170 part_size = PAGE_SIZE - src_po;
7171 }
7172 if (part_size > (amount_left)) {
7173 part_size = amount_left;
7174 }
7175
7176 if (result_page == VM_PAGE_NULL) {
7177 assert((vm_offset_t) dst_po == dst_po);
7178 assert((vm_size_t) part_size == part_size);
7179 vm_page_part_zero_fill(dst_page,
7180 (vm_offset_t) dst_po,
7181 (vm_size_t) part_size);
7182 } else {
7183 assert((vm_offset_t) src_po == src_po);
7184 assert((vm_offset_t) dst_po == dst_po);
7185 assert((vm_size_t) part_size == part_size);
7186 vm_page_part_copy(result_page,
7187 (vm_offset_t) src_po,
7188 dst_page,
7189 (vm_offset_t) dst_po,
7190 (vm_size_t)part_size);
7191 if (!dst_page->vmp_dirty) {
7192 vm_object_lock(dst_object);
7193 SET_PAGE_DIRTY(dst_page, TRUE);
7194 vm_object_unlock(dst_object);
7195 }
7196 }
7197 } else {
7198 part_size = PAGE_SIZE;
7199
7200 if (result_page == VM_PAGE_NULL) {
7201 vm_page_zero_fill(dst_page);
7202 } else {
7203 vm_object_lock(result_page_object);
7204 vm_page_copy(result_page, dst_page);
7205 vm_object_unlock(result_page_object);
7206
7207 if (!dst_page->vmp_dirty) {
7208 vm_object_lock(dst_object);
7209 SET_PAGE_DIRTY(dst_page, TRUE);
7210 vm_object_unlock(dst_object);
7211 }
7212 }
7213 }
7214
7215 /*
7216 * Unlock everything, and return
7217 */
7218
7219 vm_map_unlock_read(dst_map);
7220
7221 if (result_page != VM_PAGE_NULL && src_page != dst_page) {
7222 vm_fault_copy_cleanup(result_page, src_top_page);
7223 }
7224 vm_fault_copy_dst_cleanup(dst_page);
7225
7226 amount_left -= part_size;
7227 src_offset += part_size;
7228 dst_offset += part_size;
7229 } while (amount_left > 0);
7230
7231 RETURN(KERN_SUCCESS);
7232 #undef RETURN
7233
7234 /*NOTREACHED*/
7235 }
7236
7237 #if VM_FAULT_CLASSIFY
7238 /*
7239 * Temporary statistics gathering support.
7240 */
7241
7242 /*
7243 * Statistics arrays:
7244 */
7245 #define VM_FAULT_TYPES_MAX 5
7246 #define VM_FAULT_LEVEL_MAX 8
7247
7248 int vm_fault_stats[VM_FAULT_TYPES_MAX][VM_FAULT_LEVEL_MAX];
7249
7250 #define VM_FAULT_TYPE_ZERO_FILL 0
7251 #define VM_FAULT_TYPE_MAP_IN 1
7252 #define VM_FAULT_TYPE_PAGER 2
7253 #define VM_FAULT_TYPE_COPY 3
7254 #define VM_FAULT_TYPE_OTHER 4
7255
7256
7257 void
vm_fault_classify(vm_object_t object,vm_object_offset_t offset,vm_prot_t fault_type)7258 vm_fault_classify(vm_object_t object,
7259 vm_object_offset_t offset,
7260 vm_prot_t fault_type)
7261 {
7262 int type, level = 0;
7263 vm_page_t m;
7264
7265 while (TRUE) {
7266 m = vm_page_lookup(object, offset);
7267 if (m != VM_PAGE_NULL) {
7268 if (m->vmp_busy || VMP_ERROR_GET(m) || m->vmp_restart || m->vmp_absent) {
7269 type = VM_FAULT_TYPE_OTHER;
7270 break;
7271 }
7272 if (((fault_type & VM_PROT_WRITE) == 0) ||
7273 ((level == 0) && object->copy == VM_OBJECT_NULL)) {
7274 type = VM_FAULT_TYPE_MAP_IN;
7275 break;
7276 }
7277 type = VM_FAULT_TYPE_COPY;
7278 break;
7279 } else {
7280 if (object->pager_created) {
7281 type = VM_FAULT_TYPE_PAGER;
7282 break;
7283 }
7284 if (object->shadow == VM_OBJECT_NULL) {
7285 type = VM_FAULT_TYPE_ZERO_FILL;
7286 break;
7287 }
7288
7289 offset += object->vo_shadow_offset;
7290 object = object->shadow;
7291 level++;
7292 continue;
7293 }
7294 }
7295
7296 if (level > VM_FAULT_LEVEL_MAX) {
7297 level = VM_FAULT_LEVEL_MAX;
7298 }
7299
7300 vm_fault_stats[type][level] += 1;
7301
7302 return;
7303 }
7304
7305 /* cleanup routine to call from debugger */
7306
7307 void
vm_fault_classify_init(void)7308 vm_fault_classify_init(void)
7309 {
7310 int type, level;
7311
7312 for (type = 0; type < VM_FAULT_TYPES_MAX; type++) {
7313 for (level = 0; level < VM_FAULT_LEVEL_MAX; level++) {
7314 vm_fault_stats[type][level] = 0;
7315 }
7316 }
7317
7318 return;
7319 }
7320 #endif /* VM_FAULT_CLASSIFY */
7321
7322 vm_offset_t
kdp_lightweight_fault(vm_map_t map,vm_offset_t cur_target_addr)7323 kdp_lightweight_fault(vm_map_t map, vm_offset_t cur_target_addr)
7324 {
7325 vm_map_entry_t entry;
7326 vm_object_t object;
7327 vm_offset_t object_offset;
7328 vm_page_t m;
7329 int compressor_external_state, compressed_count_delta;
7330 int compressor_flags = (C_DONT_BLOCK | C_KEEP | C_KDP);
7331 int my_fault_type = VM_PROT_READ;
7332 kern_return_t kr;
7333 int effective_page_mask, effective_page_size;
7334
7335 if (VM_MAP_PAGE_SHIFT(map) < PAGE_SHIFT) {
7336 effective_page_mask = VM_MAP_PAGE_MASK(map);
7337 effective_page_size = VM_MAP_PAGE_SIZE(map);
7338 } else {
7339 effective_page_mask = PAGE_MASK;
7340 effective_page_size = PAGE_SIZE;
7341 }
7342
7343 if (not_in_kdp) {
7344 panic("kdp_lightweight_fault called from outside of debugger context");
7345 }
7346
7347 assert(map != VM_MAP_NULL);
7348
7349 assert((cur_target_addr & effective_page_mask) == 0);
7350 if ((cur_target_addr & effective_page_mask) != 0) {
7351 return 0;
7352 }
7353
7354 if (kdp_lck_rw_lock_is_acquired_exclusive(&map->lock)) {
7355 return 0;
7356 }
7357
7358 if (!vm_map_lookup_entry(map, cur_target_addr, &entry)) {
7359 return 0;
7360 }
7361
7362 if (entry->is_sub_map) {
7363 return 0;
7364 }
7365
7366 object = VME_OBJECT(entry);
7367 if (object == VM_OBJECT_NULL) {
7368 return 0;
7369 }
7370
7371 object_offset = cur_target_addr - entry->vme_start + VME_OFFSET(entry);
7372
7373 while (TRUE) {
7374 if (kdp_lck_rw_lock_is_acquired_exclusive(&object->Lock)) {
7375 return 0;
7376 }
7377
7378 if (object->pager_created && (object->paging_in_progress ||
7379 object->activity_in_progress)) {
7380 return 0;
7381 }
7382
7383 m = kdp_vm_page_lookup(object, vm_object_trunc_page(object_offset));
7384
7385 if (m != VM_PAGE_NULL) {
7386 if ((object->wimg_bits & VM_WIMG_MASK) != VM_WIMG_DEFAULT) {
7387 return 0;
7388 }
7389
7390 if (m->vmp_laundry || m->vmp_busy || m->vmp_free_when_done || m->vmp_absent || VMP_ERROR_GET(m) || m->vmp_cleaning ||
7391 m->vmp_overwriting || m->vmp_restart || m->vmp_unusual) {
7392 return 0;
7393 }
7394
7395 assert(!m->vmp_private);
7396 if (m->vmp_private) {
7397 return 0;
7398 }
7399
7400 assert(!m->vmp_fictitious);
7401 if (m->vmp_fictitious) {
7402 return 0;
7403 }
7404
7405 assert(m->vmp_q_state != VM_PAGE_USED_BY_COMPRESSOR);
7406 if (m->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) {
7407 return 0;
7408 }
7409
7410 return ptoa(VM_PAGE_GET_PHYS_PAGE(m));
7411 }
7412
7413 compressor_external_state = VM_EXTERNAL_STATE_UNKNOWN;
7414
7415 if (object->pager_created && MUST_ASK_PAGER(object, object_offset, compressor_external_state)) {
7416 if (compressor_external_state == VM_EXTERNAL_STATE_EXISTS) {
7417 kr = vm_compressor_pager_get(object->pager,
7418 vm_object_trunc_page(object_offset + object->paging_offset),
7419 kdp_compressor_decompressed_page_ppnum, &my_fault_type,
7420 compressor_flags, &compressed_count_delta);
7421 if (kr == KERN_SUCCESS) {
7422 return kdp_compressor_decompressed_page_paddr;
7423 } else {
7424 return 0;
7425 }
7426 }
7427 }
7428
7429 if (object->shadow == VM_OBJECT_NULL) {
7430 return 0;
7431 }
7432
7433 object_offset += object->vo_shadow_offset;
7434 object = object->shadow;
7435 }
7436 }
7437
7438 /*
7439 * vm_page_validate_cs_fast():
7440 * Performs a few quick checks to determine if the page's code signature
7441 * really needs to be fully validated. It could:
7442 * 1. have been modified (i.e. automatically tainted),
7443 * 2. have already been validated,
7444 * 3. have already been found to be tainted,
7445 * 4. no longer have a backing store.
7446 * Returns FALSE if the page needs to be fully validated.
7447 */
7448 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)7449 vm_page_validate_cs_fast(
7450 vm_page_t page,
7451 vm_map_size_t fault_page_size,
7452 vm_map_offset_t fault_phys_offset)
7453 {
7454 vm_object_t object;
7455
7456 object = VM_PAGE_OBJECT(page);
7457 vm_object_lock_assert_held(object);
7458
7459 if (page->vmp_wpmapped &&
7460 !VMP_CS_TAINTED(page, fault_page_size, fault_phys_offset)) {
7461 /*
7462 * This page was mapped for "write" access sometime in the
7463 * past and could still be modifiable in the future.
7464 * Consider it tainted.
7465 * [ If the page was already found to be "tainted", no
7466 * need to re-validate. ]
7467 */
7468 vm_object_lock_assert_exclusive(object);
7469 VMP_CS_SET_VALIDATED(page, fault_page_size, fault_phys_offset, TRUE);
7470 VMP_CS_SET_TAINTED(page, fault_page_size, fault_phys_offset, TRUE);
7471 if (cs_debug) {
7472 printf("CODESIGNING: %s: "
7473 "page %p obj %p off 0x%llx "
7474 "was modified\n",
7475 __FUNCTION__,
7476 page, object, page->vmp_offset);
7477 }
7478 vm_cs_validated_dirtied++;
7479 }
7480
7481 if (VMP_CS_VALIDATED(page, fault_page_size, fault_phys_offset) ||
7482 VMP_CS_TAINTED(page, fault_page_size, fault_phys_offset)) {
7483 return TRUE;
7484 }
7485 vm_object_lock_assert_exclusive(object);
7486
7487 #if CHECK_CS_VALIDATION_BITMAP
7488 kern_return_t kr;
7489
7490 kr = vnode_pager_cs_check_validation_bitmap(
7491 object->pager,
7492 page->vmp_offset + object->paging_offset,
7493 CS_BITMAP_CHECK);
7494 if (kr == KERN_SUCCESS) {
7495 page->vmp_cs_validated = VMP_CS_ALL_TRUE;
7496 page->vmp_cs_tainted = VMP_CS_ALL_FALSE;
7497 vm_cs_bitmap_validated++;
7498 return TRUE;
7499 }
7500 #endif /* CHECK_CS_VALIDATION_BITMAP */
7501
7502 if (!object->alive || object->terminating || object->pager == NULL) {
7503 /*
7504 * The object is terminating and we don't have its pager
7505 * so we can't validate the data...
7506 */
7507 return TRUE;
7508 }
7509
7510 /* we need to really validate this page */
7511 vm_object_lock_assert_exclusive(object);
7512 return FALSE;
7513 }
7514
7515 void
vm_page_validate_cs_mapped_slow(vm_page_t page,const void * kaddr)7516 vm_page_validate_cs_mapped_slow(
7517 vm_page_t page,
7518 const void *kaddr)
7519 {
7520 vm_object_t object;
7521 memory_object_offset_t mo_offset;
7522 memory_object_t pager;
7523 struct vnode *vnode;
7524 int validated, tainted, nx;
7525
7526 assert(page->vmp_busy);
7527 object = VM_PAGE_OBJECT(page);
7528 vm_object_lock_assert_exclusive(object);
7529
7530 vm_cs_validates++;
7531
7532 /*
7533 * Since we get here to validate a page that was brought in by
7534 * the pager, we know that this pager is all setup and ready
7535 * by now.
7536 */
7537 assert(object->code_signed);
7538 assert(!object->internal);
7539 assert(object->pager != NULL);
7540 assert(object->pager_ready);
7541
7542 pager = object->pager;
7543 assert(object->paging_in_progress);
7544 vnode = vnode_pager_lookup_vnode(pager);
7545 mo_offset = page->vmp_offset + object->paging_offset;
7546
7547 /* verify the SHA1 hash for this page */
7548 validated = 0;
7549 tainted = 0;
7550 nx = 0;
7551 cs_validate_page(vnode,
7552 pager,
7553 mo_offset,
7554 (const void *)((const char *)kaddr),
7555 &validated,
7556 &tainted,
7557 &nx);
7558
7559 page->vmp_cs_validated |= validated;
7560 page->vmp_cs_tainted |= tainted;
7561 page->vmp_cs_nx |= nx;
7562
7563 #if CHECK_CS_VALIDATION_BITMAP
7564 if (page->vmp_cs_validated == VMP_CS_ALL_TRUE &&
7565 page->vmp_cs_tainted == VMP_CS_ALL_FALSE) {
7566 vnode_pager_cs_check_validation_bitmap(object->pager,
7567 mo_offset,
7568 CS_BITMAP_SET);
7569 }
7570 #endif /* CHECK_CS_VALIDATION_BITMAP */
7571 }
7572
7573 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)7574 vm_page_validate_cs_mapped(
7575 vm_page_t page,
7576 vm_map_size_t fault_page_size,
7577 vm_map_offset_t fault_phys_offset,
7578 const void *kaddr)
7579 {
7580 if (!vm_page_validate_cs_fast(page, fault_page_size, fault_phys_offset)) {
7581 vm_page_validate_cs_mapped_slow(page, kaddr);
7582 }
7583 }
7584
7585 static void
vm_page_map_and_validate_cs(vm_object_t object,vm_page_t page)7586 vm_page_map_and_validate_cs(
7587 vm_object_t object,
7588 vm_page_t page)
7589 {
7590 vm_object_offset_t offset;
7591 vm_map_offset_t koffset;
7592 vm_map_size_t ksize;
7593 vm_offset_t kaddr;
7594 kern_return_t kr;
7595 boolean_t busy_page;
7596 boolean_t need_unmap;
7597
7598 vm_object_lock_assert_exclusive(object);
7599
7600 assert(object->code_signed);
7601 offset = page->vmp_offset;
7602
7603 busy_page = page->vmp_busy;
7604 if (!busy_page) {
7605 /* keep page busy while we map (and unlock) the VM object */
7606 page->vmp_busy = TRUE;
7607 }
7608
7609 /*
7610 * Take a paging reference on the VM object
7611 * to protect it from collapse or bypass,
7612 * and keep it from disappearing too.
7613 */
7614 vm_object_paging_begin(object);
7615
7616 /* map the page in the kernel address space */
7617 ksize = PAGE_SIZE_64;
7618 koffset = 0;
7619 need_unmap = FALSE;
7620 kr = vm_paging_map_object(page,
7621 object,
7622 offset,
7623 VM_PROT_READ,
7624 FALSE, /* can't unlock object ! */
7625 &ksize,
7626 &koffset,
7627 &need_unmap);
7628 if (kr != KERN_SUCCESS) {
7629 panic("%s: could not map page: 0x%x", __FUNCTION__, kr);
7630 }
7631 kaddr = CAST_DOWN(vm_offset_t, koffset);
7632
7633 /* validate the mapped page */
7634 vm_page_validate_cs_mapped_slow(page, (const void *) kaddr);
7635
7636 assert(page->vmp_busy);
7637 assert(object == VM_PAGE_OBJECT(page));
7638 vm_object_lock_assert_exclusive(object);
7639
7640 if (!busy_page) {
7641 PAGE_WAKEUP_DONE(page);
7642 }
7643 if (need_unmap) {
7644 /* unmap the map from the kernel address space */
7645 vm_paging_unmap_object(object, koffset, koffset + ksize);
7646 koffset = 0;
7647 ksize = 0;
7648 kaddr = 0;
7649 }
7650 vm_object_paging_end(object);
7651 }
7652
7653 void
vm_page_validate_cs(vm_page_t page,vm_map_size_t fault_page_size,vm_map_offset_t fault_phys_offset)7654 vm_page_validate_cs(
7655 vm_page_t page,
7656 vm_map_size_t fault_page_size,
7657 vm_map_offset_t fault_phys_offset)
7658 {
7659 vm_object_t object;
7660
7661 object = VM_PAGE_OBJECT(page);
7662 vm_object_lock_assert_held(object);
7663
7664 if (vm_page_validate_cs_fast(page, fault_page_size, fault_phys_offset)) {
7665 return;
7666 }
7667 vm_page_map_and_validate_cs(object, page);
7668 }
7669
7670 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)7671 vm_page_validate_cs_mapped_chunk(
7672 vm_page_t page,
7673 const void *kaddr,
7674 vm_offset_t chunk_offset,
7675 vm_size_t chunk_size,
7676 boolean_t *validated_p,
7677 unsigned *tainted_p)
7678 {
7679 vm_object_t object;
7680 vm_object_offset_t offset, offset_in_page;
7681 memory_object_t pager;
7682 struct vnode *vnode;
7683 boolean_t validated;
7684 unsigned tainted;
7685
7686 *validated_p = FALSE;
7687 *tainted_p = 0;
7688
7689 assert(page->vmp_busy);
7690 object = VM_PAGE_OBJECT(page);
7691 vm_object_lock_assert_exclusive(object);
7692
7693 assert(object->code_signed);
7694 offset = page->vmp_offset;
7695
7696 if (!object->alive || object->terminating || object->pager == NULL) {
7697 /*
7698 * The object is terminating and we don't have its pager
7699 * so we can't validate the data...
7700 */
7701 return;
7702 }
7703 /*
7704 * Since we get here to validate a page that was brought in by
7705 * the pager, we know that this pager is all setup and ready
7706 * by now.
7707 */
7708 assert(!object->internal);
7709 assert(object->pager != NULL);
7710 assert(object->pager_ready);
7711
7712 pager = object->pager;
7713 assert(object->paging_in_progress);
7714 vnode = vnode_pager_lookup_vnode(pager);
7715
7716 /* verify the signature for this chunk */
7717 offset_in_page = chunk_offset;
7718 assert(offset_in_page < PAGE_SIZE);
7719
7720 tainted = 0;
7721 validated = cs_validate_range(vnode,
7722 pager,
7723 (object->paging_offset +
7724 offset +
7725 offset_in_page),
7726 (const void *)((const char *)kaddr
7727 + offset_in_page),
7728 chunk_size,
7729 &tainted);
7730 if (validated) {
7731 *validated_p = TRUE;
7732 }
7733 if (tainted) {
7734 *tainted_p = tainted;
7735 }
7736 }
7737
7738 static void
vm_rtfrecord_lock(void)7739 vm_rtfrecord_lock(void)
7740 {
7741 lck_spin_lock(&vm_rtfr_slock);
7742 }
7743
7744 static void
vm_rtfrecord_unlock(void)7745 vm_rtfrecord_unlock(void)
7746 {
7747 lck_spin_unlock(&vm_rtfr_slock);
7748 }
7749
7750 unsigned int
vmrtfaultinfo_bufsz(void)7751 vmrtfaultinfo_bufsz(void)
7752 {
7753 return vmrtf_num_records * sizeof(vm_rtfault_record_t);
7754 }
7755
7756 #include <kern/backtrace.h>
7757
7758 __attribute__((noinline))
7759 static void
vm_record_rtfault(thread_t cthread,uint64_t fstart,vm_map_offset_t fault_vaddr,int type_of_fault)7760 vm_record_rtfault(thread_t cthread, uint64_t fstart, vm_map_offset_t fault_vaddr, int type_of_fault)
7761 {
7762 uint64_t fend = mach_continuous_time();
7763
7764 uint64_t cfpc = 0;
7765 uint64_t ctid = cthread->thread_id;
7766 uint64_t cupid = get_current_unique_pid();
7767
7768 uintptr_t bpc = 0;
7769 errno_t btr = 0;
7770
7771 /*
7772 * Capture a single-frame backtrace. This extracts just the program
7773 * counter at the point of the fault, and should not use copyin to get
7774 * Rosetta save state.
7775 */
7776 struct backtrace_control ctl = {
7777 .btc_user_thread = cthread,
7778 .btc_user_copy = backtrace_user_copy_error,
7779 };
7780 unsigned int bfrs = backtrace_user(&bpc, 1U, &ctl, NULL);
7781 if ((btr == 0) && (bfrs > 0)) {
7782 cfpc = bpc;
7783 }
7784
7785 assert((fstart != 0) && fend >= fstart);
7786 vm_rtfrecord_lock();
7787 assert(vmrtfrs.vmrtfr_curi <= vmrtfrs.vmrtfr_maxi);
7788
7789 vmrtfrs.vmrtf_total++;
7790 vm_rtfault_record_t *cvmr = &vmrtfrs.vm_rtf_records[vmrtfrs.vmrtfr_curi++];
7791
7792 cvmr->rtfabstime = fstart;
7793 cvmr->rtfduration = fend - fstart;
7794 cvmr->rtfaddr = fault_vaddr;
7795 cvmr->rtfpc = cfpc;
7796 cvmr->rtftype = type_of_fault;
7797 cvmr->rtfupid = cupid;
7798 cvmr->rtftid = ctid;
7799
7800 if (vmrtfrs.vmrtfr_curi > vmrtfrs.vmrtfr_maxi) {
7801 vmrtfrs.vmrtfr_curi = 0;
7802 }
7803
7804 vm_rtfrecord_unlock();
7805 }
7806
7807 int
vmrtf_extract(uint64_t cupid,__unused boolean_t isroot,unsigned long vrecordsz,void * vrecords,unsigned long * vmrtfrv)7808 vmrtf_extract(uint64_t cupid, __unused boolean_t isroot, unsigned long vrecordsz, void *vrecords, unsigned long *vmrtfrv)
7809 {
7810 vm_rtfault_record_t *cvmrd = vrecords;
7811 size_t residue = vrecordsz;
7812 size_t numextracted = 0;
7813 boolean_t early_exit = FALSE;
7814
7815 vm_rtfrecord_lock();
7816
7817 for (int vmfi = 0; vmfi <= vmrtfrs.vmrtfr_maxi; vmfi++) {
7818 if (residue < sizeof(vm_rtfault_record_t)) {
7819 early_exit = TRUE;
7820 break;
7821 }
7822
7823 if (vmrtfrs.vm_rtf_records[vmfi].rtfupid != cupid) {
7824 #if DEVELOPMENT || DEBUG
7825 if (isroot == FALSE) {
7826 continue;
7827 }
7828 #else
7829 continue;
7830 #endif /* DEVDEBUG */
7831 }
7832
7833 *cvmrd = vmrtfrs.vm_rtf_records[vmfi];
7834 cvmrd++;
7835 residue -= sizeof(vm_rtfault_record_t);
7836 numextracted++;
7837 }
7838
7839 vm_rtfrecord_unlock();
7840
7841 *vmrtfrv = numextracted;
7842 return early_exit;
7843 }
7844
7845 /*
7846 * Only allow one diagnosis to be in flight at a time, to avoid
7847 * creating too much additional memory usage.
7848 */
7849 static volatile uint_t vmtc_diagnosing;
7850 unsigned int vmtc_total = 0;
7851
7852 /*
7853 * Type used to update telemetry for the diagnosis counts.
7854 */
7855 CA_EVENT(vmtc_telemetry,
7856 CA_INT, vmtc_num_byte, /* number of corrupt bytes found */
7857 CA_BOOL, vmtc_undiagnosed, /* undiagnosed because more than 1 at a time */
7858 CA_BOOL, vmtc_not_eligible, /* the page didn't qualify */
7859 CA_BOOL, vmtc_copyin_fail, /* unable to copy in the page */
7860 CA_BOOL, vmtc_not_found, /* no corruption found even though CS failed */
7861 CA_BOOL, vmtc_one_bit_flip, /* single bit flip */
7862 CA_BOOL, vmtc_testing); /* caused on purpose by testing */
7863
7864 #if DEVELOPMENT || DEBUG
7865 /*
7866 * Buffers used to compare before/after page contents.
7867 * Stashed to aid when debugging crashes.
7868 */
7869 static size_t vmtc_last_buffer_size = 0;
7870 static uint64_t *vmtc_last_before_buffer = NULL;
7871 static uint64_t *vmtc_last_after_buffer = NULL;
7872
7873 /*
7874 * Needed to record corruptions due to testing.
7875 */
7876 static uintptr_t corruption_test_va = 0;
7877 #endif /* DEVELOPMENT || DEBUG */
7878
7879 /*
7880 * Stash a copy of data from a possibly corrupt page.
7881 */
7882 static uint64_t *
vmtc_get_page_data(vm_map_offset_t code_addr,vm_page_t page)7883 vmtc_get_page_data(
7884 vm_map_offset_t code_addr,
7885 vm_page_t page)
7886 {
7887 uint64_t *buffer = NULL;
7888 addr64_t buffer_paddr;
7889 addr64_t page_paddr;
7890 extern void bcopy_phys(addr64_t from, addr64_t to, vm_size_t bytes);
7891 uint_t size = MIN(vm_map_page_size(current_map()), PAGE_SIZE);
7892
7893 /*
7894 * Need an aligned buffer to do a physical copy.
7895 */
7896 if (kernel_memory_allocate(kernel_map, (vm_offset_t *)&buffer,
7897 size, size - 1, KMA_KOBJECT, VM_KERN_MEMORY_DIAG) != KERN_SUCCESS) {
7898 return NULL;
7899 }
7900 buffer_paddr = kvtophys((vm_offset_t)buffer);
7901 page_paddr = ptoa(VM_PAGE_GET_PHYS_PAGE(page));
7902
7903 /* adjust the page start address if we need only 4K of a 16K page */
7904 if (size < PAGE_SIZE) {
7905 uint_t subpage_start = ((code_addr & (PAGE_SIZE - 1)) & ~(size - 1));
7906 page_paddr += subpage_start;
7907 }
7908
7909 bcopy_phys(page_paddr, buffer_paddr, size);
7910 return buffer;
7911 }
7912
7913 /*
7914 * Set things up so we can diagnose a potential text page corruption.
7915 */
7916 static uint64_t *
vmtc_text_page_diagnose_setup(vm_map_offset_t code_addr,vm_page_t page,CA_EVENT_TYPE (vmtc_telemetry)* event)7917 vmtc_text_page_diagnose_setup(
7918 vm_map_offset_t code_addr,
7919 vm_page_t page,
7920 CA_EVENT_TYPE(vmtc_telemetry) *event)
7921 {
7922 uint64_t *buffer = NULL;
7923
7924 /*
7925 * If another is being diagnosed, skip this one.
7926 */
7927 if (!OSCompareAndSwap(0, 1, &vmtc_diagnosing)) {
7928 event->vmtc_undiagnosed = true;
7929 return NULL;
7930 }
7931
7932 /*
7933 * Get the contents of the corrupt page.
7934 */
7935 buffer = vmtc_get_page_data(code_addr, page);
7936 if (buffer == NULL) {
7937 event->vmtc_copyin_fail = true;
7938 if (!OSCompareAndSwap(1, 0, &vmtc_diagnosing)) {
7939 panic("Bad compare and swap in setup!");
7940 }
7941 return NULL;
7942 }
7943 return buffer;
7944 }
7945
7946 /*
7947 * Diagnose the text page by comparing its contents with
7948 * the one we've previously saved.
7949 */
7950 static void
vmtc_text_page_diagnose(vm_map_offset_t code_addr,uint64_t * old_code_buffer,CA_EVENT_TYPE (vmtc_telemetry)* event)7951 vmtc_text_page_diagnose(
7952 vm_map_offset_t code_addr,
7953 uint64_t *old_code_buffer,
7954 CA_EVENT_TYPE(vmtc_telemetry) *event)
7955 {
7956 uint64_t *new_code_buffer;
7957 size_t size = MIN(vm_map_page_size(current_map()), PAGE_SIZE);
7958 uint_t count = (uint_t)size / sizeof(uint64_t);
7959 uint_t diff_count = 0;
7960 bool bit_flip = false;
7961 uint_t b;
7962 uint64_t *new;
7963 uint64_t *old;
7964
7965 new_code_buffer = kalloc_data(size, Z_WAITOK);
7966 assert(new_code_buffer != NULL);
7967 if (copyin((user_addr_t)vm_map_trunc_page(code_addr, size - 1), new_code_buffer, size) != 0) {
7968 /* copyin error, so undo things */
7969 event->vmtc_copyin_fail = true;
7970 goto done;
7971 }
7972
7973 new = new_code_buffer;
7974 old = old_code_buffer;
7975 for (; count-- > 0; ++new, ++old) {
7976 if (*new == *old) {
7977 continue;
7978 }
7979
7980 /*
7981 * On first diff, check for a single bit flip
7982 */
7983 if (diff_count == 0) {
7984 uint64_t x = (*new ^ *old);
7985 assert(x != 0);
7986 if ((x & (x - 1)) == 0) {
7987 bit_flip = true;
7988 ++diff_count;
7989 continue;
7990 }
7991 }
7992
7993 /*
7994 * count up the number of different bytes.
7995 */
7996 for (b = 0; b < sizeof(uint64_t); ++b) {
7997 char *n = (char *)new;
7998 char *o = (char *)old;
7999 if (n[b] != o[b]) {
8000 ++diff_count;
8001 }
8002 }
8003 }
8004
8005 if (diff_count > 1) {
8006 bit_flip = false;
8007 }
8008
8009 if (diff_count == 0) {
8010 event->vmtc_not_found = true;
8011 } else {
8012 event->vmtc_num_byte = diff_count;
8013 }
8014 if (bit_flip) {
8015 event->vmtc_one_bit_flip = true;
8016 }
8017
8018 done:
8019 /*
8020 * Free up the code copy buffers, but save the last
8021 * set on development / debug kernels in case they
8022 * can provide evidence for debugging memory stomps.
8023 */
8024 #if DEVELOPMENT || DEBUG
8025 if (vmtc_last_before_buffer != NULL) {
8026 kmem_free(kernel_map, (vm_offset_t)vmtc_last_before_buffer, vmtc_last_buffer_size);
8027 }
8028 if (vmtc_last_after_buffer != NULL) {
8029 kfree_data(vmtc_last_after_buffer, vmtc_last_buffer_size);
8030 }
8031 vmtc_last_before_buffer = old_code_buffer;
8032 vmtc_last_after_buffer = new_code_buffer;
8033 vmtc_last_buffer_size = size;
8034 #else /* DEVELOPMENT || DEBUG */
8035 kfree_data(new_code_buffer, size);
8036 kmem_free(kernel_map, (vm_offset_t)old_code_buffer, size);
8037 #endif /* DEVELOPMENT || DEBUG */
8038
8039 /*
8040 * We're finished, so clear the diagnosing flag.
8041 */
8042 if (!OSCompareAndSwap(1, 0, &vmtc_diagnosing)) {
8043 panic("Bad compare and swap in diagnose!");
8044 }
8045 }
8046
8047 /*
8048 * For the given map, virt address, find the object, offset, and page.
8049 * This has to lookup the map entry, verify protections, walk any shadow chains.
8050 * If found, returns with the object locked.
8051 */
8052 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)8053 vmtc_revalidate_lookup(
8054 vm_map_t map,
8055 vm_map_offset_t vaddr,
8056 vm_object_t *ret_object,
8057 vm_object_offset_t *ret_offset,
8058 vm_page_t *ret_page,
8059 vm_prot_t *ret_prot)
8060 {
8061 vm_object_t object;
8062 vm_object_offset_t offset;
8063 vm_page_t page;
8064 kern_return_t kr = KERN_SUCCESS;
8065 uint8_t object_lock_type = OBJECT_LOCK_EXCLUSIVE;
8066 vm_map_version_t version;
8067 boolean_t wired;
8068 struct vm_object_fault_info fault_info = {};
8069 vm_map_t real_map = NULL;
8070 vm_prot_t prot;
8071 vm_object_t shadow;
8072
8073 /*
8074 * Find the object/offset for the given location/map.
8075 * Note this returns with the object locked.
8076 */
8077 restart:
8078 vm_map_lock_read(map);
8079 object = VM_OBJECT_NULL; /* in case we come around the restart path */
8080 kr = vm_map_lookup_and_lock_object(&map, vaddr, VM_PROT_READ,
8081 object_lock_type, &version, &object, &offset, &prot, &wired,
8082 &fault_info, &real_map, NULL);
8083 vm_map_unlock_read(map);
8084 if (real_map != NULL && real_map != map) {
8085 vm_map_unlock(real_map);
8086 }
8087
8088 /*
8089 * If there's no page here, fail.
8090 */
8091 if (kr != KERN_SUCCESS || object == NULL) {
8092 kr = KERN_FAILURE;
8093 goto done;
8094 }
8095
8096 /*
8097 * Chase down any shadow chains to find the actual page.
8098 */
8099 for (;;) {
8100 /*
8101 * See if the page is on the current object.
8102 */
8103 page = vm_page_lookup(object, vm_object_trunc_page(offset));
8104 if (page != NULL) {
8105 /* restart the lookup */
8106 if (page->vmp_restart) {
8107 vm_object_unlock(object);
8108 goto restart;
8109 }
8110
8111 /*
8112 * If this page is busy, we need to wait for it.
8113 */
8114 if (page->vmp_busy) {
8115 PAGE_SLEEP(object, page, TRUE);
8116 vm_object_unlock(object);
8117 goto restart;
8118 }
8119 break;
8120 }
8121
8122 /*
8123 * If the object doesn't have the page and
8124 * has no shadow, then we can quit.
8125 */
8126 shadow = object->shadow;
8127 if (shadow == NULL) {
8128 kr = KERN_FAILURE;
8129 goto done;
8130 }
8131
8132 /*
8133 * Move to the next object
8134 */
8135 offset += object->vo_shadow_offset;
8136 vm_object_lock(shadow);
8137 vm_object_unlock(object);
8138 object = shadow;
8139 shadow = VM_OBJECT_NULL;
8140 }
8141 *ret_object = object;
8142 *ret_offset = vm_object_trunc_page(offset);
8143 *ret_page = page;
8144 *ret_prot = prot;
8145
8146 done:
8147 if (kr != KERN_SUCCESS && object != NULL) {
8148 vm_object_unlock(object);
8149 }
8150 return kr;
8151 }
8152
8153 /*
8154 * Check if a page is wired, needs extra locking.
8155 */
8156 static bool
is_page_wired(vm_page_t page)8157 is_page_wired(vm_page_t page)
8158 {
8159 bool result;
8160 vm_page_lock_queues();
8161 result = VM_PAGE_WIRED(page);
8162 vm_page_unlock_queues();
8163 return result;
8164 }
8165
8166 /*
8167 * A fatal process error has occurred in the given task.
8168 * Recheck the code signing of the text page at the given
8169 * address to check for a text page corruption.
8170 *
8171 * Returns KERN_FAILURE if a page was found to be corrupt
8172 * by failing to match its code signature. KERN_SUCCESS
8173 * means the page is either valid or we don't have the
8174 * information to say it's corrupt.
8175 */
8176 kern_return_t
revalidate_text_page(task_t task,vm_map_offset_t code_addr)8177 revalidate_text_page(task_t task, vm_map_offset_t code_addr)
8178 {
8179 kern_return_t kr;
8180 vm_map_t map;
8181 vm_object_t object = NULL;
8182 vm_object_offset_t offset;
8183 vm_page_t page = NULL;
8184 struct vnode *vnode;
8185 uint64_t *diagnose_buffer = NULL;
8186 CA_EVENT_TYPE(vmtc_telemetry) * event = NULL;
8187 ca_event_t ca_event = NULL;
8188 vm_prot_t prot;
8189
8190 map = task->map;
8191 if (task->map == NULL) {
8192 return KERN_SUCCESS;
8193 }
8194
8195 kr = vmtc_revalidate_lookup(map, code_addr, &object, &offset, &page, &prot);
8196 if (kr != KERN_SUCCESS) {
8197 goto done;
8198 }
8199
8200 /*
8201 * The page must be executable.
8202 */
8203 if (!(prot & VM_PROT_EXECUTE)) {
8204 goto done;
8205 }
8206
8207 /*
8208 * The object needs to have a pager.
8209 */
8210 if (object->pager == NULL) {
8211 goto done;
8212 }
8213
8214 /*
8215 * Needs to be a vnode backed page to have a signature.
8216 */
8217 vnode = vnode_pager_lookup_vnode(object->pager);
8218 if (vnode == NULL) {
8219 goto done;
8220 }
8221
8222 /*
8223 * Object checks to see if we should proceed.
8224 */
8225 if (!object->code_signed || /* no code signature to check */
8226 object->internal || /* internal objects aren't signed */
8227 object->terminating || /* the object and its pages are already going away */
8228 !object->pager_ready) { /* this should happen, but check shouldn't hurt */
8229 goto done;
8230 }
8231
8232
8233 /*
8234 * Check the code signature of the page in question.
8235 */
8236 vm_page_map_and_validate_cs(object, page);
8237
8238 /*
8239 * At this point:
8240 * vmp_cs_validated |= validated (set if a code signature exists)
8241 * vmp_cs_tainted |= tainted (set if code signature violation)
8242 * vmp_cs_nx |= nx; ??
8243 *
8244 * if vmp_pmapped then have to pmap_disconnect..
8245 * other flags to check on object or page?
8246 */
8247 if (page->vmp_cs_tainted != VMP_CS_ALL_FALSE) {
8248 #if DEBUG || DEVELOPMENT
8249 /*
8250 * On development builds, a boot-arg can be used to cause
8251 * a panic, instead of a quiet repair.
8252 */
8253 if (vmtc_panic_instead) {
8254 panic("Text page corruption detected: vm_page_t 0x%llx", (long long)(uintptr_t)page);
8255 }
8256 #endif /* DEBUG || DEVELOPMENT */
8257
8258 /*
8259 * We're going to invalidate this page. Grab a copy of it for comparison.
8260 */
8261 ca_event = CA_EVENT_ALLOCATE(vmtc_telemetry);
8262 event = ca_event->data;
8263 diagnose_buffer = vmtc_text_page_diagnose_setup(code_addr, page, event);
8264
8265 /*
8266 * Invalidate, i.e. toss, the corrupted page.
8267 */
8268 if (!page->vmp_cleaning &&
8269 !page->vmp_laundry &&
8270 !page->vmp_fictitious &&
8271 !page->vmp_precious &&
8272 !page->vmp_absent &&
8273 !VMP_ERROR_GET(page) &&
8274 !page->vmp_dirty &&
8275 !is_page_wired(page)) {
8276 if (page->vmp_pmapped) {
8277 int refmod = pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(page));
8278 if (refmod & VM_MEM_MODIFIED) {
8279 SET_PAGE_DIRTY(page, FALSE);
8280 }
8281 if (refmod & VM_MEM_REFERENCED) {
8282 page->vmp_reference = TRUE;
8283 }
8284 }
8285 /* If the page seems intentionally modified, don't trash it. */
8286 if (!page->vmp_dirty) {
8287 VM_PAGE_FREE(page);
8288 } else {
8289 event->vmtc_not_eligible = true;
8290 }
8291 } else {
8292 event->vmtc_not_eligible = true;
8293 }
8294 vm_object_unlock(object);
8295 object = VM_OBJECT_NULL;
8296
8297 /*
8298 * Now try to diagnose the type of failure by faulting
8299 * in a new copy and diff'ing it with what we saved.
8300 */
8301 if (diagnose_buffer != NULL) {
8302 vmtc_text_page_diagnose(code_addr, diagnose_buffer, event);
8303 }
8304 #if DEBUG || DEVELOPMENT
8305 if (corruption_test_va != 0) {
8306 corruption_test_va = 0;
8307 event->vmtc_testing = true;
8308 }
8309 #endif /* DEBUG || DEVELOPMENT */
8310 ktriage_record(thread_tid(current_thread()),
8311 KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_TEXT_CORRUPTION),
8312 0 /* arg */);
8313 CA_EVENT_SEND(ca_event);
8314 printf("Text page corruption detected for pid %d\n", proc_selfpid());
8315 ++vmtc_total;
8316 return KERN_FAILURE; /* failure means we definitely found a corrupt page */
8317 }
8318 done:
8319 if (object != NULL) {
8320 vm_object_unlock(object);
8321 }
8322 return KERN_SUCCESS;
8323 }
8324
8325 #if DEBUG || DEVELOPMENT
8326 /*
8327 * For implementing unit tests - ask the pmap to corrupt a text page.
8328 * We have to find the page, to get the physical address, then invoke
8329 * the pmap.
8330 */
8331 extern kern_return_t vm_corrupt_text_addr(uintptr_t);
8332
8333 kern_return_t
vm_corrupt_text_addr(uintptr_t va)8334 vm_corrupt_text_addr(uintptr_t va)
8335 {
8336 task_t task = current_task();
8337 vm_map_t map;
8338 kern_return_t kr = KERN_SUCCESS;
8339 vm_object_t object = VM_OBJECT_NULL;
8340 vm_object_offset_t offset;
8341 vm_page_t page = NULL;
8342 pmap_paddr_t pa;
8343 vm_prot_t prot;
8344
8345 map = task->map;
8346 if (task->map == NULL) {
8347 printf("corrupt_text_addr: no map\n");
8348 return KERN_FAILURE;
8349 }
8350
8351 kr = vmtc_revalidate_lookup(map, (vm_map_offset_t)va, &object, &offset, &page, &prot);
8352 if (kr != KERN_SUCCESS) {
8353 printf("corrupt_text_addr: page lookup failed\n");
8354 return kr;
8355 }
8356 if (!(prot & VM_PROT_EXECUTE)) {
8357 printf("corrupt_text_addr: page not executable\n");
8358 return KERN_FAILURE;
8359 }
8360
8361 /* get the physical address to use */
8362 pa = ptoa(VM_PAGE_GET_PHYS_PAGE(page)) + (va - vm_object_trunc_page(va));
8363
8364 /*
8365 * Check we have something we can work with.
8366 * Due to racing with pageout as we enter the sysctl,
8367 * it's theoretically possible to have the page disappear, just
8368 * before the lookup.
8369 *
8370 * That's highly likely to happen often. I've filed a radar 72857482
8371 * to bubble up the error here to the sysctl result and have the
8372 * test not FAIL in that case.
8373 */
8374 if (page->vmp_busy) {
8375 printf("corrupt_text_addr: vmp_busy\n");
8376 kr = KERN_FAILURE;
8377 }
8378 if (page->vmp_cleaning) {
8379 printf("corrupt_text_addr: vmp_cleaning\n");
8380 kr = KERN_FAILURE;
8381 }
8382 if (page->vmp_laundry) {
8383 printf("corrupt_text_addr: vmp_cleaning\n");
8384 kr = KERN_FAILURE;
8385 }
8386 if (page->vmp_fictitious) {
8387 printf("corrupt_text_addr: vmp_fictitious\n");
8388 kr = KERN_FAILURE;
8389 }
8390 if (page->vmp_precious) {
8391 printf("corrupt_text_addr: vmp_precious\n");
8392 kr = KERN_FAILURE;
8393 }
8394 if (page->vmp_absent) {
8395 printf("corrupt_text_addr: vmp_absent\n");
8396 kr = KERN_FAILURE;
8397 }
8398 if (VMP_ERROR_GET(page)) {
8399 printf("corrupt_text_addr: vmp_error\n");
8400 kr = KERN_FAILURE;
8401 }
8402 if (page->vmp_dirty) {
8403 printf("corrupt_text_addr: vmp_dirty\n");
8404 kr = KERN_FAILURE;
8405 }
8406 if (is_page_wired(page)) {
8407 printf("corrupt_text_addr: wired\n");
8408 kr = KERN_FAILURE;
8409 }
8410 if (!page->vmp_pmapped) {
8411 printf("corrupt_text_addr: !vmp_pmapped\n");
8412 kr = KERN_FAILURE;
8413 }
8414
8415 if (kr == KERN_SUCCESS) {
8416 printf("corrupt_text_addr: using physaddr 0x%llx\n", (long long)pa);
8417 kr = pmap_test_text_corruption(pa);
8418 if (kr != KERN_SUCCESS) {
8419 printf("corrupt_text_addr: pmap error %d\n", kr);
8420 } else {
8421 corruption_test_va = va;
8422 }
8423 } else {
8424 printf("corrupt_text_addr: object %p\n", object);
8425 printf("corrupt_text_addr: offset 0x%llx\n", (uint64_t)offset);
8426 printf("corrupt_text_addr: va 0x%llx\n", (uint64_t)va);
8427 printf("corrupt_text_addr: vm_object_trunc_page(va) 0x%llx\n", (uint64_t)vm_object_trunc_page(va));
8428 printf("corrupt_text_addr: vm_page_t %p\n", page);
8429 printf("corrupt_text_addr: ptoa(PHYS_PAGE) 0x%llx\n", (uint64_t)ptoa(VM_PAGE_GET_PHYS_PAGE(page)));
8430 printf("corrupt_text_addr: using physaddr 0x%llx\n", (uint64_t)pa);
8431 }
8432
8433 if (object != VM_OBJECT_NULL) {
8434 vm_object_unlock(object);
8435 }
8436 return kr;
8437 }
8438
8439 #endif /* DEBUG || DEVELOPMENT */
8440