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