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