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