1 /*
2 * Copyright (c) 2000-2020 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/vm_object.c
60 * Author: Avadis Tevanian, Jr., Michael Wayne Young
61 *
62 * Virtual memory object module.
63 */
64
65 #include <debug.h>
66
67 #include <mach/mach_types.h>
68 #include <mach/memory_object.h>
69 #include <mach/vm_param.h>
70
71 #include <mach/sdt.h>
72
73 #include <ipc/ipc_types.h>
74 #include <ipc/ipc_port.h>
75
76 #include <kern/kern_types.h>
77 #include <kern/assert.h>
78 #include <kern/queue.h>
79 #include <kern/kalloc.h>
80 #include <kern/zalloc.h>
81 #include <kern/host.h>
82 #include <kern/host_statistics.h>
83 #include <kern/processor.h>
84 #include <kern/misc_protos.h>
85 #include <kern/policy_internal.h>
86
87 #include <sys/kdebug.h>
88 #include <sys/kdebug_triage.h>
89
90 #include <vm/memory_object_internal.h>
91 #include <vm/vm_compressor_pager_internal.h>
92 #include <vm/vm_fault_internal.h>
93 #include <vm/vm_map.h>
94 #include <vm/vm_object_internal.h>
95 #include <vm/vm_page_internal.h>
96 #include <vm/vm_pageout_internal.h>
97 #include <vm/vm_protos_internal.h>
98 #include <vm/vm_purgeable_internal.h>
99 #include <vm/vm_ubc.h>
100 #include <vm/vm_compressor_xnu.h>
101 #include <os/hash.h>
102
103 #if CONFIG_PHANTOM_CACHE
104 #include <vm/vm_phantom_cache_internal.h>
105 #endif
106
107 #if VM_OBJECT_ACCESS_TRACKING
108 uint64_t vm_object_access_tracking_reads = 0;
109 uint64_t vm_object_access_tracking_writes = 0;
110 #endif /* VM_OBJECT_ACCESS_TRACKING */
111
112 boolean_t vm_object_collapse_compressor_allowed = TRUE;
113
114 struct vm_counters vm_counters;
115
116 os_refgrp_decl(, vm_object_refgrp, "vm_object", NULL);
117
118 #if DEVELOPMENT || DEBUG
119 extern struct memory_object_pager_ops shared_region_pager_ops;
120 extern unsigned int shared_region_pagers_resident_count;
121 extern unsigned int shared_region_pagers_resident_peak;
122 #endif /* DEVELOPMENT || DEBUG */
123
124 #if VM_OBJECT_TRACKING
125 btlog_t vm_object_tracking_btlog;
126
127 void
vm_object_tracking_init(void)128 vm_object_tracking_init(void)
129 {
130 int vm_object_tracking;
131
132 vm_object_tracking = 1;
133 PE_parse_boot_argn("vm_object_tracking", &vm_object_tracking,
134 sizeof(vm_object_tracking));
135
136 if (vm_object_tracking) {
137 vm_object_tracking_btlog = btlog_create(BTLOG_HASH,
138 VM_OBJECT_TRACKING_NUM_RECORDS);
139 assert(vm_object_tracking_btlog);
140 }
141 }
142 #endif /* VM_OBJECT_TRACKING */
143
144 /*
145 * Virtual memory objects maintain the actual data
146 * associated with allocated virtual memory. A given
147 * page of memory exists within exactly one object.
148 *
149 * An object is only deallocated when all "references"
150 * are given up.
151 *
152 * Associated with each object is a list of all resident
153 * memory pages belonging to that object; this list is
154 * maintained by the "vm_page" module, but locked by the object's
155 * lock.
156 *
157 * Each object also records the memory object reference
158 * that is used by the kernel to request and write
159 * back data (the memory object, field "pager"), etc...
160 *
161 * Virtual memory objects are allocated to provide
162 * zero-filled memory (vm_allocate) or map a user-defined
163 * memory object into a virtual address space (vm_map).
164 *
165 * Virtual memory objects that refer to a user-defined
166 * memory object are called "permanent", because all changes
167 * made in virtual memory are reflected back to the
168 * memory manager, which may then store it permanently.
169 * Other virtual memory objects are called "temporary",
170 * meaning that changes need be written back only when
171 * necessary to reclaim pages, and that storage associated
172 * with the object can be discarded once it is no longer
173 * mapped.
174 *
175 * A permanent memory object may be mapped into more
176 * than one virtual address space. Moreover, two threads
177 * may attempt to make the first mapping of a memory
178 * object concurrently. Only one thread is allowed to
179 * complete this mapping; all others wait for the
180 * "pager_initialized" field is asserted, indicating
181 * that the first thread has initialized all of the
182 * necessary fields in the virtual memory object structure.
183 *
184 * The kernel relies on a *default memory manager* to
185 * provide backing storage for the zero-filled virtual
186 * memory objects. The pager memory objects associated
187 * with these temporary virtual memory objects are only
188 * requested from the default memory manager when it
189 * becomes necessary. Virtual memory objects
190 * that depend on the default memory manager are called
191 * "internal". The "pager_created" field is provided to
192 * indicate whether these ports have ever been allocated.
193 *
194 * The kernel may also create virtual memory objects to
195 * hold changed pages after a copy-on-write operation.
196 * In this case, the virtual memory object (and its
197 * backing storage -- its memory object) only contain
198 * those pages that have been changed. The "shadow"
199 * field refers to the virtual memory object that contains
200 * the remainder of the contents. The "shadow_offset"
201 * field indicates where in the "shadow" these contents begin.
202 * The "copy" field refers to a virtual memory object
203 * to which changed pages must be copied before changing
204 * this object, in order to implement another form
205 * of copy-on-write optimization.
206 *
207 * The virtual memory object structure also records
208 * the attributes associated with its memory object.
209 * The "pager_ready", "can_persist" and "copy_strategy"
210 * fields represent those attributes. The "cached_list"
211 * field is used in the implementation of the persistence
212 * attribute.
213 *
214 * ZZZ Continue this comment.
215 */
216
217 /* Forward declarations for internal functions. */
218 static kern_return_t vm_object_terminate(
219 vm_object_t object);
220
221 static void vm_object_do_collapse(
222 vm_object_t object,
223 vm_object_t backing_object);
224
225 static void vm_object_do_bypass(
226 vm_object_t object,
227 vm_object_t backing_object);
228
229 static void vm_object_release_pager(
230 memory_object_t pager);
231
232 SECURITY_READ_ONLY_LATE(zone_t) vm_object_zone; /* vm backing store zone */
233
234 /*
235 * Wired-down kernel memory belongs to this memory object (kernel_object)
236 * by default to avoid wasting data structures.
237 */
238 static struct vm_object kernel_object_store VM_PAGE_PACKED_ALIGNED;
239 const vm_object_t kernel_object_default = &kernel_object_store;
240
241 static struct vm_object compressor_object_store VM_PAGE_PACKED_ALIGNED;
242 const vm_object_t compressor_object = &compressor_object_store;
243
244 /*
245 * This object holds all pages that have been retired due to errors like ECC.
246 * The system should never use the page or look at its contents. The offset
247 * in this object is the same as the page's physical address.
248 */
249 static struct vm_object retired_pages_object_store VM_PAGE_PACKED_ALIGNED;
250 const vm_object_t retired_pages_object = &retired_pages_object_store;
251
252
253 static struct vm_object exclaves_object_store VM_PAGE_PACKED_ALIGNED;
254 const vm_object_t exclaves_object = &exclaves_object_store;
255
256
257 /*
258 * Virtual memory objects are initialized from
259 * a template (see vm_object_allocate).
260 *
261 * When adding a new field to the virtual memory
262 * object structure, be sure to add initialization
263 * (see _vm_object_allocate()).
264 */
265 static const struct vm_object vm_object_template = {
266 .memq.prev = 0,
267 .memq.next = 0,
268 /*
269 * The lock will be initialized for each allocated object in
270 * _vm_object_allocate(), so we don't need to initialize it in
271 * the vm_object_template.
272 */
273 .vo_size = 0,
274 .memq_hint = VM_PAGE_NULL,
275 /*
276 * The ref count will be initialized for each allocated object in
277 * _vm_object_allocate(), so we don't need to initialize it in the
278 * vm_object_template.
279 */
280 .resident_page_count = 0,
281 .wired_page_count = 0,
282 .reusable_page_count = 0,
283 .vo_copy = VM_OBJECT_NULL,
284 .vo_copy_version = 0,
285 .vo_inherit_copy_none = false,
286 .shadow = VM_OBJECT_NULL,
287 .vo_shadow_offset = (vm_object_offset_t) 0,
288 .pager = MEMORY_OBJECT_NULL,
289 .paging_offset = 0,
290 .pager_control = MEMORY_OBJECT_CONTROL_NULL,
291 .copy_strategy = MEMORY_OBJECT_COPY_SYMMETRIC,
292 .paging_in_progress = 0,
293 .vo_size_delta = 0,
294 .activity_in_progress = 0,
295
296 /* Begin bitfields */
297 .all_wanted = 0, /* all bits FALSE */
298 .pager_created = FALSE,
299 .pager_initialized = FALSE,
300 .pager_ready = FALSE,
301 .pager_trusted = FALSE,
302 .can_persist = FALSE,
303 .internal = TRUE,
304 .private = FALSE,
305 .pageout = FALSE,
306 .alive = TRUE,
307 .purgable = VM_PURGABLE_DENY,
308 .purgeable_when_ripe = FALSE,
309 .purgeable_only_by_kernel = FALSE,
310 .shadowed = FALSE,
311 .true_share = FALSE,
312 .terminating = FALSE,
313 .named = FALSE,
314 .shadow_severed = FALSE,
315 .phys_contiguous = FALSE,
316 .nophyscache = FALSE,
317 /* End bitfields */
318
319 .cached_list.prev = NULL,
320 .cached_list.next = NULL,
321
322 .last_alloc = (vm_object_offset_t) 0,
323 .sequential = (vm_object_offset_t) 0,
324 .pages_created = 0,
325 .pages_used = 0,
326 .scan_collisions = 0,
327 #if CONFIG_PHANTOM_CACHE
328 .phantom_object_id = 0,
329 #endif
330 .cow_hint = ~(vm_offset_t)0,
331
332 /* cache bitfields */
333 .wimg_bits = VM_WIMG_USE_DEFAULT,
334 .set_cache_attr = FALSE,
335 .object_is_shared_cache = FALSE,
336 .code_signed = FALSE,
337 .transposed = FALSE,
338 .mapping_in_progress = FALSE,
339 .phantom_isssd = FALSE,
340 .volatile_empty = FALSE,
341 .volatile_fault = FALSE,
342 .all_reusable = FALSE,
343 .blocked_access = FALSE,
344 .vo_ledger_tag = VM_LEDGER_TAG_NONE,
345 .vo_no_footprint = FALSE,
346 #if CONFIG_IOSCHED || UPL_DEBUG
347 .uplq.prev = NULL,
348 .uplq.next = NULL,
349 #endif /* UPL_DEBUG */
350 #ifdef VM_PIP_DEBUG
351 .pip_holders = {0},
352 #endif /* VM_PIP_DEBUG */
353
354 .objq.next = NULL,
355 .objq.prev = NULL,
356 .task_objq.next = NULL,
357 .task_objq.prev = NULL,
358
359 .purgeable_queue_type = PURGEABLE_Q_TYPE_MAX,
360 .purgeable_queue_group = 0,
361
362 .wire_tag = VM_KERN_MEMORY_NONE,
363 #if !VM_TAG_ACTIVE_UPDATE
364 .wired_objq.next = NULL,
365 .wired_objq.prev = NULL,
366 #endif /* ! VM_TAG_ACTIVE_UPDATE */
367
368 .io_tracking = FALSE,
369
370 #if CONFIG_SECLUDED_MEMORY
371 .eligible_for_secluded = FALSE,
372 .can_grab_secluded = FALSE,
373 #else /* CONFIG_SECLUDED_MEMORY */
374 .__object3_unused_bits = 0,
375 #endif /* CONFIG_SECLUDED_MEMORY */
376
377 .for_realtime = false,
378 .no_pager_reason = VM_OBJECT_DESTROY_UNKNOWN_REASON,
379
380 #if VM_OBJECT_ACCESS_TRACKING
381 .access_tracking = FALSE,
382 .access_tracking_reads = 0,
383 .access_tracking_writes = 0,
384 #endif /* VM_OBJECT_ACCESS_TRACKING */
385
386 #if DEBUG
387 .purgeable_owner_bt = {0},
388 .vo_purgeable_volatilizer = NULL,
389 .purgeable_volatilizer_bt = {0},
390 #endif /* DEBUG */
391 };
392
393 LCK_GRP_DECLARE(vm_object_lck_grp, "vm_object");
394 LCK_GRP_DECLARE(vm_object_cache_lck_grp, "vm_object_cache");
395 LCK_ATTR_DECLARE(vm_object_lck_attr, 0, 0);
396 LCK_ATTR_DECLARE(kernel_object_lck_attr, 0, LCK_ATTR_DEBUG);
397 LCK_ATTR_DECLARE(compressor_object_lck_attr, 0, LCK_ATTR_DEBUG);
398
399 unsigned int vm_page_purged_wired = 0;
400 unsigned int vm_page_purged_busy = 0;
401 unsigned int vm_page_purged_others = 0;
402
403 static queue_head_t vm_object_cached_list;
404 static uint32_t vm_object_cache_pages_freed = 0;
405 static uint32_t vm_object_cache_pages_moved = 0;
406 static uint32_t vm_object_cache_pages_skipped = 0;
407 static uint32_t vm_object_cache_adds = 0;
408 static uint32_t vm_object_cached_count = 0;
409 static LCK_MTX_DECLARE_ATTR(vm_object_cached_lock_data,
410 &vm_object_cache_lck_grp, &vm_object_lck_attr);
411
412 static uint32_t vm_object_page_grab_failed = 0;
413 static uint32_t vm_object_page_grab_skipped = 0;
414 static uint32_t vm_object_page_grab_returned = 0;
415 static uint32_t vm_object_page_grab_pmapped = 0;
416 static uint32_t vm_object_page_grab_reactivations = 0;
417
418 #define vm_object_cache_lock_spin() \
419 lck_mtx_lock_spin(&vm_object_cached_lock_data)
420 #define vm_object_cache_unlock() \
421 lck_mtx_unlock(&vm_object_cached_lock_data)
422
423 static void vm_object_cache_remove_locked(vm_object_t);
424
425
426 static void vm_object_reap(vm_object_t object);
427 static void vm_object_reap_async(vm_object_t object);
428 static void vm_object_reaper_thread(void);
429
430 static LCK_MTX_DECLARE_ATTR(vm_object_reaper_lock_data,
431 &vm_object_lck_grp, &vm_object_lck_attr);
432
433 static queue_head_t vm_object_reaper_queue; /* protected by vm_object_reaper_lock() */
434 unsigned int vm_object_reap_count = 0;
435 unsigned int vm_object_reap_count_async = 0;
436
437
438 #define vm_object_reaper_lock() \
439 lck_mtx_lock(&vm_object_reaper_lock_data)
440 #define vm_object_reaper_lock_spin() \
441 lck_mtx_lock_spin(&vm_object_reaper_lock_data)
442 #define vm_object_reaper_unlock() \
443 lck_mtx_unlock(&vm_object_reaper_lock_data)
444
445 #if CONFIG_IOSCHED
446 /* I/O Re-prioritization request list */
447 struct mpsc_daemon_queue io_reprioritize_q;
448
449 ZONE_DEFINE_TYPE(io_reprioritize_req_zone, "io_reprioritize_req",
450 struct io_reprioritize_req, ZC_NONE);
451
452 /* I/O re-prioritization MPSC callback */
453 static void io_reprioritize(mpsc_queue_chain_t elm, mpsc_daemon_queue_t dq);
454
455 void vm_page_request_reprioritize(vm_object_t, uint64_t, uint32_t, int);
456 void vm_page_handle_prio_inversion(vm_object_t, vm_page_t);
457 void vm_decmp_upl_reprioritize(upl_t, int);
458 #endif
459
460 void
vm_object_set_size(vm_object_t object,vm_object_size_t outer_size,vm_object_size_t inner_size)461 vm_object_set_size(
462 vm_object_t object,
463 vm_object_size_t outer_size,
464 vm_object_size_t inner_size)
465 {
466 object->vo_size = vm_object_round_page(outer_size);
467 #if KASAN
468 assert(object->vo_size - inner_size <= USHRT_MAX);
469 object->vo_size_delta = (unsigned short)(object->vo_size - inner_size);
470 #else
471 (void)inner_size;
472 #endif
473 }
474
475
476 /*
477 * vm_object_allocate:
478 *
479 * Returns a new object with the given size.
480 */
481
482 __private_extern__ void
_vm_object_allocate(vm_object_size_t size,vm_object_t object)483 _vm_object_allocate(
484 vm_object_size_t size,
485 vm_object_t object)
486 {
487 *object = vm_object_template;
488 vm_page_queue_init(&object->memq);
489 #if UPL_DEBUG || CONFIG_IOSCHED
490 queue_init(&object->uplq);
491 #endif
492 vm_object_lock_init(object);
493 vm_object_set_size(object, size, size);
494
495 os_ref_init_raw(&object->ref_count, &vm_object_refgrp);
496
497 #if VM_OBJECT_TRACKING_OP_CREATED
498 if (vm_object_tracking_btlog) {
499 btlog_record(vm_object_tracking_btlog, object,
500 VM_OBJECT_TRACKING_OP_CREATED,
501 btref_get(__builtin_frame_address(0), 0));
502 }
503 #endif /* VM_OBJECT_TRACKING_OP_CREATED */
504 }
505
506 __private_extern__ vm_object_t
vm_object_allocate(vm_object_size_t size)507 vm_object_allocate(
508 vm_object_size_t size)
509 {
510 vm_object_t object;
511
512 object = zalloc_flags(vm_object_zone, Z_WAITOK | Z_NOFAIL);
513 _vm_object_allocate(size, object);
514
515 return object;
516 }
517
518 TUNABLE(bool, workaround_41447923, "workaround_41447923", false);
519
520 /*
521 * vm_object_bootstrap:
522 *
523 * Initialize the VM objects module.
524 */
525 __startup_func
526 void
vm_object_bootstrap(void)527 vm_object_bootstrap(void)
528 {
529 vm_size_t vm_object_size;
530
531 assert(sizeof(mo_ipc_object_bits_t) == sizeof(ipc_object_bits_t));
532
533 vm_object_size = (sizeof(struct vm_object) + (VM_PAGE_PACKED_PTR_ALIGNMENT - 1)) &
534 ~(VM_PAGE_PACKED_PTR_ALIGNMENT - 1);
535
536 vm_object_zone = zone_create("vm objects", vm_object_size,
537 ZC_NOENCRYPT | ZC_ALIGNMENT_REQUIRED | ZC_VM);
538
539 queue_init(&vm_object_cached_list);
540
541 queue_init(&vm_object_reaper_queue);
542
543 /*
544 * Initialize the "kernel object"
545 */
546
547 /*
548 * Note that in the following size specifications, we need to add 1 because
549 * VM_MAX_KERNEL_ADDRESS (vm_last_addr) is a maximum address, not a size.
550 */
551 _vm_object_allocate(VM_MAX_KERNEL_ADDRESS + 1, kernel_object_default);
552 _vm_object_allocate(VM_MAX_KERNEL_ADDRESS + 1, compressor_object);
553 kernel_object_default->copy_strategy = MEMORY_OBJECT_COPY_NONE;
554 compressor_object->copy_strategy = MEMORY_OBJECT_COPY_NONE;
555 kernel_object_default->no_tag_update = TRUE;
556
557 /*
558 * The object to hold retired VM pages.
559 */
560 _vm_object_allocate(VM_MAX_KERNEL_ADDRESS + 1, retired_pages_object);
561 retired_pages_object->copy_strategy = MEMORY_OBJECT_COPY_NONE;
562
563
564 /**
565 * The object to hold pages owned by exclaves.
566 */
567 _vm_object_allocate(VM_MAX_KERNEL_ADDRESS + 1, exclaves_object);
568 exclaves_object->copy_strategy = MEMORY_OBJECT_COPY_NONE;
569 }
570
571 #if CONFIG_IOSCHED
572 void
vm_io_reprioritize_init(void)573 vm_io_reprioritize_init(void)
574 {
575 kern_return_t result;
576
577 result = mpsc_daemon_queue_init_with_thread(&io_reprioritize_q, io_reprioritize, BASEPRI_KERNEL,
578 "VM_io_reprioritize_thread", MPSC_DAEMON_INIT_NONE);
579 if (result != KERN_SUCCESS) {
580 panic("Unable to start I/O reprioritization thread (%d)", result);
581 }
582 }
583 #endif
584
585 void
vm_object_reaper_init(void)586 vm_object_reaper_init(void)
587 {
588 kern_return_t kr;
589 thread_t thread;
590
591 kr = kernel_thread_start_priority(
592 (thread_continue_t) vm_object_reaper_thread,
593 NULL,
594 BASEPRI_VM,
595 &thread);
596 if (kr != KERN_SUCCESS) {
597 panic("failed to launch vm_object_reaper_thread kr=0x%x", kr);
598 }
599 thread_set_thread_name(thread, "VM_object_reaper_thread");
600 thread_deallocate(thread);
601 }
602
603
604 /*
605 * vm_object_deallocate:
606 *
607 * Release a reference to the specified object,
608 * gained either through a vm_object_allocate
609 * or a vm_object_reference call. When all references
610 * are gone, storage associated with this object
611 * may be relinquished.
612 *
613 * No object may be locked.
614 */
615 unsigned long vm_object_deallocate_shared_successes = 0;
616 unsigned long vm_object_deallocate_shared_failures = 0;
617 unsigned long vm_object_deallocate_shared_swap_failures = 0;
618
619 __private_extern__ void
vm_object_deallocate(vm_object_t object)620 vm_object_deallocate(
621 vm_object_t object)
622 {
623 vm_object_t shadow = VM_OBJECT_NULL;
624
625 // if(object)dbgLog(object, object->ref_count, object->can_persist, 3); /* (TEST/DEBUG) */
626 // else dbgLog(object, 0, 0, 3); /* (TEST/DEBUG) */
627
628 if (object == VM_OBJECT_NULL) {
629 return;
630 }
631
632 if (is_kernel_object(object) || object == compressor_object || object == retired_pages_object) {
633 vm_object_lock_shared(object);
634
635 if (os_ref_get_count_raw(&object->ref_count) == 1) {
636 if (is_kernel_object(object)) {
637 panic("vm_object_deallocate: losing a kernel_object");
638 } else if (object == retired_pages_object) {
639 panic("vm_object_deallocate: losing retired_pages_object");
640 } else {
641 panic("vm_object_deallocate: losing compressor_object");
642 }
643 }
644
645 os_ref_release_live_raw(&object->ref_count, &vm_object_refgrp);
646
647 vm_object_unlock(object);
648 return;
649 }
650
651 if (os_ref_get_count_raw(&object->ref_count) == 2 &&
652 object->named) {
653 /*
654 * This "named" object's reference count is about to
655 * drop from 2 to 1:
656 * we'll need to call memory_object_last_unmap().
657 */
658 } else if (os_ref_get_count_raw(&object->ref_count) == 2 &&
659 object->internal &&
660 object->shadow != VM_OBJECT_NULL) {
661 /*
662 * This internal object's reference count is about to
663 * drop from 2 to 1 and it has a shadow object:
664 * we'll want to try and collapse this object with its
665 * shadow.
666 */
667 } else if (os_ref_get_count_raw(&object->ref_count) >= 2) {
668 UInt32 original_ref_count;
669 volatile UInt32 *ref_count_p;
670 Boolean atomic_swap;
671
672 /*
673 * The object currently looks like it is not being
674 * kept alive solely by the reference we're about to release.
675 * Let's try and release our reference without taking
676 * all the locks we would need if we had to terminate the
677 * object (cache lock + exclusive object lock).
678 * Lock the object "shared" to make sure we don't race with
679 * anyone holding it "exclusive".
680 */
681 vm_object_lock_shared(object);
682 ref_count_p = (volatile UInt32 *) &object->ref_count;
683 original_ref_count = os_ref_get_count_raw(&object->ref_count);
684 /*
685 * Test again as "ref_count" could have changed.
686 * "named" shouldn't change.
687 */
688 if (original_ref_count == 2 &&
689 object->named) {
690 /* need to take slow path for m_o_last_unmap() */
691 atomic_swap = FALSE;
692 } else if (original_ref_count == 2 &&
693 object->internal &&
694 object->shadow != VM_OBJECT_NULL) {
695 /* need to take slow path for vm_object_collapse() */
696 atomic_swap = FALSE;
697 } else if (original_ref_count < 2) {
698 /* need to take slow path for vm_object_terminate() */
699 atomic_swap = FALSE;
700 } else {
701 /* try an atomic update with the shared lock */
702 atomic_swap = OSCompareAndSwap(
703 original_ref_count,
704 original_ref_count - 1,
705 (UInt32 *) &object->ref_count);
706 if (atomic_swap == FALSE) {
707 vm_object_deallocate_shared_swap_failures++;
708 /* fall back to the slow path... */
709 }
710 }
711
712 vm_object_unlock(object);
713
714 if (atomic_swap) {
715 /*
716 * ref_count was updated atomically !
717 */
718 vm_object_deallocate_shared_successes++;
719 return;
720 }
721
722 /*
723 * Someone else updated the ref_count at the same
724 * time and we lost the race. Fall back to the usual
725 * slow but safe path...
726 */
727 vm_object_deallocate_shared_failures++;
728 }
729
730 while (object != VM_OBJECT_NULL) {
731 vm_object_lock(object);
732
733 assert(os_ref_get_count_raw(&object->ref_count) > 0);
734
735 /*
736 * If the object has a named reference, and only
737 * that reference would remain, inform the pager
738 * about the last "mapping" reference going away.
739 */
740 if ((os_ref_get_count_raw(&object->ref_count) == 2) && (object->named)) {
741 memory_object_t pager = object->pager;
742
743 /* Notify the Pager that there are no */
744 /* more mappers for this object */
745
746 if (pager != MEMORY_OBJECT_NULL) {
747 vm_object_mapping_wait(object, THREAD_UNINT);
748 /* object might have lost its pager while waiting */
749 pager = object->pager;
750 if (object->ref_count == 2 &&
751 object->named &&
752 pager != MEMORY_OBJECT_NULL) {
753 vm_object_mapping_begin(object);
754 vm_object_unlock(object);
755
756 memory_object_last_unmap(pager);
757
758 vm_object_lock(object);
759 vm_object_mapping_end(object);
760 }
761 }
762 assert(os_ref_get_count_raw(&object->ref_count) > 0);
763 }
764
765 /*
766 * Lose the reference. If other references
767 * remain, then we are done, unless we need
768 * to retry a cache trim.
769 * If it is the last reference, then keep it
770 * until any pending initialization is completed.
771 */
772
773 /* if the object is terminating, it cannot go into */
774 /* the cache and we obviously should not call */
775 /* terminate again. */
776
777 if ((os_ref_get_count_raw(&object->ref_count) > 1) ||
778 object->terminating) {
779 vm_object_lock_assert_exclusive(object);
780 os_ref_release_live_locked_raw(&object->ref_count,
781 &vm_object_refgrp);
782
783 if (os_ref_get_count_raw(&object->ref_count) == 1 &&
784 object->shadow != VM_OBJECT_NULL) {
785 /*
786 * There's only one reference left on this
787 * VM object. We can't tell if it's a valid
788 * one (from a mapping for example) or if this
789 * object is just part of a possibly stale and
790 * useless shadow chain.
791 * We would like to try and collapse it into
792 * its parent, but we don't have any pointers
793 * back to this parent object.
794 * But we can try and collapse this object with
795 * its own shadows, in case these are useless
796 * too...
797 * We can't bypass this object though, since we
798 * don't know if this last reference on it is
799 * meaningful or not.
800 */
801 vm_object_collapse(object, 0, FALSE);
802 }
803 vm_object_unlock(object);
804 return;
805 }
806
807 /*
808 * We have to wait for initialization
809 * before destroying or caching the object.
810 */
811
812 if (object->pager_created && !object->pager_initialized) {
813 assert(!object->can_persist);
814 vm_object_sleep(object,
815 VM_OBJECT_EVENT_PAGER_INIT,
816 THREAD_UNINT,
817 LCK_SLEEP_UNLOCK);
818 continue;
819 }
820
821 /*
822 * Terminate this object. If it had a shadow,
823 * then deallocate it; otherwise, if we need
824 * to retry a cache trim, do so now; otherwise,
825 * we are done. "pageout" objects have a shadow,
826 * but maintain a "paging reference" rather than
827 * a normal reference.
828 */
829 shadow = object->pageout?VM_OBJECT_NULL:object->shadow;
830
831 if (vm_object_terminate(object) != KERN_SUCCESS) {
832 return;
833 }
834 if (shadow != VM_OBJECT_NULL) {
835 object = shadow;
836 continue;
837 }
838 return;
839 }
840 }
841
842
843
844 vm_page_t
vm_object_page_grab(vm_object_t object)845 vm_object_page_grab(
846 vm_object_t object)
847 {
848 vm_page_t p, next_p;
849 int p_limit = 0;
850 int p_skipped = 0;
851
852 vm_object_lock_assert_exclusive(object);
853
854 next_p = (vm_page_t)vm_page_queue_first(&object->memq);
855 p_limit = MIN(50, object->resident_page_count);
856
857 while (!vm_page_queue_end(&object->memq, (vm_page_queue_entry_t)next_p) && --p_limit > 0) {
858 p = next_p;
859 next_p = (vm_page_t)vm_page_queue_next(&next_p->vmp_listq);
860
861 if (VM_PAGE_WIRED(p) || p->vmp_busy || p->vmp_cleaning ||
862 p->vmp_laundry || vm_page_is_fictitious(p)) {
863 goto move_page_in_obj;
864 }
865
866 if (p->vmp_pmapped || p->vmp_dirty || p->vmp_precious) {
867 vm_page_lockspin_queues();
868
869 if (p->vmp_pmapped) {
870 int refmod_state;
871
872 vm_object_page_grab_pmapped++;
873
874 if (p->vmp_reference == FALSE || p->vmp_dirty == FALSE) {
875 refmod_state = pmap_get_refmod(VM_PAGE_GET_PHYS_PAGE(p));
876
877 if (refmod_state & VM_MEM_REFERENCED) {
878 p->vmp_reference = TRUE;
879 }
880 if (refmod_state & VM_MEM_MODIFIED) {
881 SET_PAGE_DIRTY(p, FALSE);
882 }
883 }
884 if (p->vmp_dirty == FALSE && p->vmp_precious == FALSE) {
885 vm_page_lockconvert_queues();
886 refmod_state = pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(p));
887
888 if (refmod_state & VM_MEM_REFERENCED) {
889 p->vmp_reference = TRUE;
890 }
891 if (refmod_state & VM_MEM_MODIFIED) {
892 SET_PAGE_DIRTY(p, FALSE);
893 }
894
895 if (p->vmp_dirty == FALSE) {
896 goto take_page;
897 }
898 }
899 }
900 if ((p->vmp_q_state != VM_PAGE_ON_ACTIVE_Q) && p->vmp_reference == TRUE) {
901 vm_page_activate(p);
902
903 counter_inc(&vm_statistics_reactivations);
904 vm_object_page_grab_reactivations++;
905 }
906 vm_page_unlock_queues();
907 move_page_in_obj:
908 vm_page_queue_remove(&object->memq, p, vmp_listq);
909 vm_page_queue_enter(&object->memq, p, vmp_listq);
910
911 p_skipped++;
912 continue;
913 }
914 vm_page_lockspin_queues();
915 take_page:
916 vm_page_free_prepare_queues(p);
917 vm_object_page_grab_returned++;
918 vm_object_page_grab_skipped += p_skipped;
919
920 vm_page_unlock_queues();
921
922 vm_page_free_prepare_object(p, TRUE);
923
924 return p;
925 }
926 vm_object_page_grab_skipped += p_skipped;
927 vm_object_page_grab_failed++;
928
929 return NULL;
930 }
931
932
933
934 #define EVICT_PREPARE_LIMIT 64
935 #define EVICT_AGE 10
936
937 static clock_sec_t vm_object_cache_aging_ts = 0;
938
939 static void
vm_object_cache_remove_locked(vm_object_t object)940 vm_object_cache_remove_locked(
941 vm_object_t object)
942 {
943 assert(object->purgable == VM_PURGABLE_DENY);
944
945 queue_remove(&vm_object_cached_list, object, vm_object_t, cached_list);
946 object->cached_list.next = NULL;
947 object->cached_list.prev = NULL;
948
949 vm_object_cached_count--;
950 }
951
952 void
vm_object_cache_remove(vm_object_t object)953 vm_object_cache_remove(
954 vm_object_t object)
955 {
956 vm_object_cache_lock_spin();
957
958 if (object->cached_list.next &&
959 object->cached_list.prev) {
960 vm_object_cache_remove_locked(object);
961 }
962
963 vm_object_cache_unlock();
964 }
965
966 void
vm_object_cache_add(vm_object_t object)967 vm_object_cache_add(
968 vm_object_t object)
969 {
970 clock_sec_t sec;
971 clock_nsec_t nsec;
972
973 assert(object->purgable == VM_PURGABLE_DENY);
974
975 if (object->resident_page_count == 0) {
976 return;
977 }
978 if (object->vo_ledger_tag) {
979 /*
980 * We can't add an "owned" object to the cache because
981 * the "vo_owner" and "vo_cache_ts" fields are part of the
982 * same "union" and can't be used at the same time.
983 */
984 return;
985 }
986 clock_get_system_nanotime(&sec, &nsec);
987
988 vm_object_cache_lock_spin();
989
990 if (object->cached_list.next == NULL &&
991 object->cached_list.prev == NULL) {
992 queue_enter(&vm_object_cached_list, object, vm_object_t, cached_list);
993 object->vo_cache_ts = sec + EVICT_AGE;
994 object->vo_cache_pages_to_scan = object->resident_page_count;
995
996 vm_object_cached_count++;
997 vm_object_cache_adds++;
998 }
999 vm_object_cache_unlock();
1000 }
1001
1002 int
vm_object_cache_evict(int num_to_evict,int max_objects_to_examine)1003 vm_object_cache_evict(
1004 int num_to_evict,
1005 int max_objects_to_examine)
1006 {
1007 vm_object_t object = VM_OBJECT_NULL;
1008 vm_object_t next_obj = VM_OBJECT_NULL;
1009 vm_page_t local_free_q = VM_PAGE_NULL;
1010 vm_page_t p;
1011 vm_page_t next_p;
1012 int object_cnt = 0;
1013 vm_page_t ep_array[EVICT_PREPARE_LIMIT];
1014 int ep_count;
1015 int ep_limit;
1016 int ep_index;
1017 int ep_freed = 0;
1018 int ep_moved = 0;
1019 uint32_t ep_skipped = 0;
1020 clock_sec_t sec;
1021 clock_nsec_t nsec;
1022
1023 KDBG_DEBUG(0x13001ec | DBG_FUNC_START);
1024 /*
1025 * do a couple of quick checks to see if it's
1026 * worthwhile grabbing the lock
1027 */
1028 if (queue_empty(&vm_object_cached_list)) {
1029 KDBG_DEBUG(0x13001ec | DBG_FUNC_END);
1030 return 0;
1031 }
1032 clock_get_system_nanotime(&sec, &nsec);
1033
1034 /*
1035 * the object on the head of the queue has not
1036 * yet sufficiently aged
1037 */
1038 if (sec < vm_object_cache_aging_ts) {
1039 KDBG_DEBUG(0x13001ec | DBG_FUNC_END);
1040 return 0;
1041 }
1042 /*
1043 * don't need the queue lock to find
1044 * and lock an object on the cached list
1045 */
1046 vm_page_unlock_queues();
1047
1048 vm_object_cache_lock_spin();
1049
1050 for (;;) { /* loop for as long as we have objects to process */
1051 next_obj = (vm_object_t)queue_first(&vm_object_cached_list);
1052
1053 /* loop to find the next target in the cache_list */
1054 while (!queue_end(&vm_object_cached_list, (queue_entry_t)next_obj) && object_cnt++ < max_objects_to_examine) {
1055 object = next_obj;
1056 next_obj = (vm_object_t)queue_next(&next_obj->cached_list);
1057
1058 assert(object->purgable == VM_PURGABLE_DENY);
1059
1060 if (sec < object->vo_cache_ts) { // reached the point in the queue beyond the time we started
1061 KDBG_DEBUG(0x130020c, object, object->resident_page_count, object->vo_cache_ts, sec);
1062
1063 vm_object_cache_aging_ts = object->vo_cache_ts;
1064 object = VM_OBJECT_NULL; /* this will cause to break away from the outer loop */
1065 break;
1066 }
1067 if (!vm_object_lock_try_scan(object)) {
1068 /*
1069 * just skip over this guy for now... if we find
1070 * an object to steal pages from, we'll revist in a bit...
1071 * hopefully, the lock will have cleared
1072 */
1073 KDBG_DEBUG(0x13001f8, object, object->resident_page_count);
1074
1075 object = VM_OBJECT_NULL;
1076 continue;
1077 }
1078 if (vm_page_queue_empty(&object->memq) || object->vo_cache_pages_to_scan == 0) {
1079 /*
1080 * this case really shouldn't happen, but it's not fatal
1081 * so deal with it... if we don't remove the object from
1082 * the list, we'll never move past it.
1083 */
1084 KDBG_DEBUG(0x13001fc, object, object->resident_page_count, ep_freed, ep_moved);
1085
1086 vm_object_cache_remove_locked(object);
1087 vm_object_unlock(object);
1088 object = VM_OBJECT_NULL;
1089 continue;
1090 }
1091 /*
1092 * we have a locked object with pages...
1093 * time to start harvesting
1094 */
1095 break;
1096 }
1097 vm_object_cache_unlock();
1098
1099 if (object == VM_OBJECT_NULL) {
1100 break;
1101 }
1102
1103 /*
1104 * object is locked at this point and
1105 * has resident pages
1106 */
1107 next_p = (vm_page_t)vm_page_queue_first(&object->memq);
1108
1109 /*
1110 * break the page scan into 2 pieces to minimize the time spent
1111 * behind the page queue lock...
1112 * the list of pages on these unused objects is likely to be cold
1113 * w/r to the cpu cache which increases the time to scan the list
1114 * tenfold... and we may have a 'run' of pages we can't utilize that
1115 * needs to be skipped over...
1116 */
1117 if ((ep_limit = num_to_evict - (ep_freed + ep_moved)) > EVICT_PREPARE_LIMIT) {
1118 ep_limit = EVICT_PREPARE_LIMIT;
1119 }
1120 ep_count = 0;
1121
1122 while (!vm_page_queue_end(&object->memq, (vm_page_queue_entry_t)next_p) && object->vo_cache_pages_to_scan && ep_count < ep_limit) {
1123 p = next_p;
1124 next_p = (vm_page_t)vm_page_queue_next(&next_p->vmp_listq);
1125
1126 object->vo_cache_pages_to_scan--;
1127
1128 if (VM_PAGE_WIRED(p) || p->vmp_busy || p->vmp_cleaning || p->vmp_laundry) {
1129 vm_page_queue_remove(&object->memq, p, vmp_listq);
1130 vm_page_queue_enter(&object->memq, p, vmp_listq);
1131
1132 ep_skipped++;
1133 continue;
1134 }
1135 if (p->vmp_wpmapped || p->vmp_dirty || p->vmp_precious) {
1136 vm_page_queue_remove(&object->memq, p, vmp_listq);
1137 vm_page_queue_enter(&object->memq, p, vmp_listq);
1138
1139 pmap_clear_reference(VM_PAGE_GET_PHYS_PAGE(p));
1140 }
1141 ep_array[ep_count++] = p;
1142 }
1143 KDBG_DEBUG(0x13001f4 | DBG_FUNC_START, object, object->resident_page_count, ep_freed, ep_moved);
1144
1145 vm_page_lockspin_queues();
1146
1147 for (ep_index = 0; ep_index < ep_count; ep_index++) {
1148 p = ep_array[ep_index];
1149
1150 if (p->vmp_wpmapped || p->vmp_dirty || p->vmp_precious) {
1151 p->vmp_reference = FALSE;
1152 p->vmp_no_cache = FALSE;
1153
1154 /*
1155 * we've already filtered out pages that are in the laundry
1156 * so if we get here, this page can't be on the pageout queue
1157 */
1158 vm_page_queues_remove(p, FALSE);
1159 vm_page_enqueue_inactive(p, TRUE);
1160
1161 ep_moved++;
1162 } else {
1163 #if CONFIG_PHANTOM_CACHE
1164 vm_phantom_cache_add_ghost(p);
1165 #endif
1166 vm_page_free_prepare_queues(p);
1167
1168 assert(p->vmp_pageq.next == 0 && p->vmp_pageq.prev == 0);
1169 /*
1170 * Add this page to our list of reclaimed pages,
1171 * to be freed later.
1172 */
1173 p->vmp_snext = local_free_q;
1174 local_free_q = p;
1175
1176 ep_freed++;
1177 }
1178 }
1179 vm_page_unlock_queues();
1180
1181 KDBG_DEBUG(0x13001f4 | DBG_FUNC_END, object, object->resident_page_count, ep_freed, ep_moved);
1182
1183 if (local_free_q) {
1184 vm_page_free_list(local_free_q, TRUE);
1185 local_free_q = VM_PAGE_NULL;
1186 }
1187 if (object->vo_cache_pages_to_scan == 0) {
1188 KDBG_DEBUG(0x1300208, object, object->resident_page_count, ep_freed, ep_moved);
1189
1190 vm_object_cache_remove(object);
1191
1192 KDBG_DEBUG(0x13001fc, object, object->resident_page_count, ep_freed, ep_moved);
1193 }
1194 /*
1195 * done with this object
1196 */
1197 vm_object_unlock(object);
1198 object = VM_OBJECT_NULL;
1199
1200 /*
1201 * at this point, we are not holding any locks
1202 */
1203 if ((ep_freed + ep_moved) >= num_to_evict) {
1204 /*
1205 * we've reached our target for the
1206 * number of pages to evict
1207 */
1208 break;
1209 }
1210 vm_object_cache_lock_spin();
1211 }
1212 /*
1213 * put the page queues lock back to the caller's
1214 * idea of it
1215 */
1216 vm_page_lock_queues();
1217
1218 vm_object_cache_pages_freed += ep_freed;
1219 vm_object_cache_pages_moved += ep_moved;
1220 vm_object_cache_pages_skipped += ep_skipped;
1221
1222 KDBG_DEBUG(0x13001ec | DBG_FUNC_END, ep_freed);
1223 return ep_freed;
1224 }
1225
1226 /*
1227 * Routine: vm_object_terminate
1228 * Purpose:
1229 * Free all resources associated with a vm_object.
1230 * In/out conditions:
1231 * Upon entry, the object must be locked,
1232 * and the object must have exactly one reference.
1233 *
1234 * The shadow object reference is left alone.
1235 *
1236 * The object must be unlocked if its found that pages
1237 * must be flushed to a backing object. If someone
1238 * manages to map the object while it is being flushed
1239 * the object is returned unlocked and unchanged. Otherwise,
1240 * upon exit, the cache will be unlocked, and the
1241 * object will cease to exist.
1242 */
1243 static kern_return_t
vm_object_terminate(vm_object_t object)1244 vm_object_terminate(
1245 vm_object_t object)
1246 {
1247 vm_object_t shadow_object;
1248
1249 vm_object_lock_assert_exclusive(object);
1250
1251 if (!object->pageout && (!object->internal && object->can_persist) &&
1252 (object->pager != NULL || object->shadow_severed)) {
1253 /*
1254 * Clear pager_trusted bit so that the pages get yanked
1255 * out of the object instead of cleaned in place. This
1256 * prevents a deadlock in XMM and makes more sense anyway.
1257 */
1258 VM_OBJECT_SET_PAGER_TRUSTED(object, FALSE);
1259
1260 vm_object_reap_pages(object, REAP_TERMINATE);
1261 }
1262 /*
1263 * Make sure the object isn't already being terminated
1264 */
1265 if (object->terminating) {
1266 vm_object_lock_assert_exclusive(object);
1267 os_ref_release_live_locked_raw(&object->ref_count, &vm_object_refgrp);
1268 vm_object_unlock(object);
1269 return KERN_FAILURE;
1270 }
1271
1272 /*
1273 * Did somebody get a reference to the object while we were
1274 * cleaning it?
1275 */
1276 if (os_ref_get_count_raw(&object->ref_count) != 1) {
1277 vm_object_lock_assert_exclusive(object);
1278 os_ref_release_live_locked_raw(&object->ref_count, &vm_object_refgrp);
1279 vm_object_unlock(object);
1280 return KERN_FAILURE;
1281 }
1282
1283 /*
1284 * Make sure no one can look us up now.
1285 */
1286
1287 VM_OBJECT_SET_TERMINATING(object, TRUE);
1288 VM_OBJECT_SET_ALIVE(object, FALSE);
1289
1290 if (!object->internal &&
1291 object->cached_list.next &&
1292 object->cached_list.prev) {
1293 vm_object_cache_remove(object);
1294 }
1295
1296 /*
1297 * Detach the object from its shadow if we are the shadow's
1298 * copy. The reference we hold on the shadow must be dropped
1299 * by our caller.
1300 */
1301 if (((shadow_object = object->shadow) != VM_OBJECT_NULL) &&
1302 !(object->pageout)) {
1303 vm_object_lock(shadow_object);
1304 if (shadow_object->vo_copy == object) {
1305 VM_OBJECT_COPY_SET(shadow_object, VM_OBJECT_NULL);
1306 }
1307 vm_object_unlock(shadow_object);
1308 }
1309
1310 if (object->paging_in_progress != 0 ||
1311 object->activity_in_progress != 0) {
1312 /*
1313 * There are still some paging_in_progress references
1314 * on this object, meaning that there are some paging
1315 * or other I/O operations in progress for this VM object.
1316 * Such operations take some paging_in_progress references
1317 * up front to ensure that the object doesn't go away, but
1318 * they may also need to acquire a reference on the VM object,
1319 * to map it in kernel space, for example. That means that
1320 * they may end up releasing the last reference on the VM
1321 * object, triggering its termination, while still holding
1322 * paging_in_progress references. Waiting for these
1323 * pending paging_in_progress references to go away here would
1324 * deadlock.
1325 *
1326 * To avoid deadlocking, we'll let the vm_object_reaper_thread
1327 * complete the VM object termination if it still holds
1328 * paging_in_progress references at this point.
1329 *
1330 * No new paging_in_progress should appear now that the
1331 * VM object is "terminating" and not "alive".
1332 */
1333 vm_object_reap_async(object);
1334 vm_object_unlock(object);
1335 /*
1336 * Return KERN_FAILURE to let the caller know that we
1337 * haven't completed the termination and it can't drop this
1338 * object's reference on its shadow object yet.
1339 * The reaper thread will take care of that once it has
1340 * completed this object's termination.
1341 */
1342 return KERN_FAILURE;
1343 }
1344 /*
1345 * complete the VM object termination
1346 */
1347 vm_object_reap(object);
1348 object = VM_OBJECT_NULL;
1349
1350 /*
1351 * the object lock was released by vm_object_reap()
1352 *
1353 * KERN_SUCCESS means that this object has been terminated
1354 * and no longer needs its shadow object but still holds a
1355 * reference on it.
1356 * The caller is responsible for dropping that reference.
1357 * We can't call vm_object_deallocate() here because that
1358 * would create a recursion.
1359 */
1360 return KERN_SUCCESS;
1361 }
1362
1363
1364 /*
1365 * vm_object_reap():
1366 *
1367 * Complete the termination of a VM object after it's been marked
1368 * as "terminating" and "!alive" by vm_object_terminate().
1369 *
1370 * The VM object must be locked by caller.
1371 * The lock will be released on return and the VM object is no longer valid.
1372 */
1373
1374 void
vm_object_reap(vm_object_t object)1375 vm_object_reap(
1376 vm_object_t object)
1377 {
1378 memory_object_t pager;
1379 os_ref_count_t ref_count;
1380
1381 vm_object_lock_assert_exclusive(object);
1382 assert(object->paging_in_progress == 0);
1383 assert(object->activity_in_progress == 0);
1384
1385 vm_object_reap_count++;
1386
1387 /*
1388 * Disown this purgeable object to cleanup its owner's purgeable
1389 * ledgers. We need to do this before disconnecting the object
1390 * from its pager, to properly account for compressed pages.
1391 */
1392 if (/* object->internal && */
1393 (object->purgable != VM_PURGABLE_DENY ||
1394 object->vo_ledger_tag)) {
1395 int ledger_flags;
1396 kern_return_t kr;
1397
1398 ledger_flags = 0;
1399 assert(!object->alive);
1400 assert(object->terminating);
1401 kr = vm_object_ownership_change(object,
1402 VM_LEDGER_TAG_NONE,
1403 NULL, /* no owner */
1404 ledger_flags,
1405 FALSE); /* task_objq not locked */
1406 assert(kr == KERN_SUCCESS);
1407 assert(object->vo_owner == NULL);
1408 }
1409
1410 #if DEVELOPMENT || DEBUG
1411 if (object->object_is_shared_cache &&
1412 object->pager != NULL &&
1413 object->pager->mo_pager_ops == &shared_region_pager_ops) {
1414 OSAddAtomic(-object->resident_page_count, &shared_region_pagers_resident_count);
1415 }
1416 #endif /* DEVELOPMENT || DEBUG */
1417
1418 pager = object->pager;
1419 object->pager = MEMORY_OBJECT_NULL;
1420
1421 if (pager != MEMORY_OBJECT_NULL) {
1422 memory_object_control_disable(&object->pager_control);
1423 }
1424
1425 ref_count = os_ref_release_locked_raw(&object->ref_count,
1426 &vm_object_refgrp);
1427 if (__improbable(ref_count != 0)) {
1428 panic("Attempting to deallocate vm_object with outstanding refs: %u",
1429 ref_count);
1430 }
1431
1432 /*
1433 * remove from purgeable queue if it's on
1434 */
1435 if (object->internal) {
1436 assert(VM_OBJECT_OWNER(object) == TASK_NULL);
1437
1438 VM_OBJECT_UNWIRED(object);
1439
1440 if (object->purgable == VM_PURGABLE_DENY) {
1441 /* not purgeable: nothing to do */
1442 } else if (object->purgable == VM_PURGABLE_VOLATILE) {
1443 purgeable_q_t queue;
1444
1445 queue = vm_purgeable_object_remove(object);
1446 assert(queue);
1447
1448 if (object->purgeable_when_ripe) {
1449 /*
1450 * Must take page lock for this -
1451 * using it to protect token queue
1452 */
1453 vm_page_lock_queues();
1454 vm_purgeable_token_delete_first(queue);
1455
1456 assert(queue->debug_count_objects >= 0);
1457 vm_page_unlock_queues();
1458 }
1459
1460 /*
1461 * Update "vm_page_purgeable_count" in bulk and mark
1462 * object as VM_PURGABLE_EMPTY to avoid updating
1463 * "vm_page_purgeable_count" again in vm_page_remove()
1464 * when reaping the pages.
1465 */
1466 unsigned int delta;
1467 assert(object->resident_page_count >=
1468 object->wired_page_count);
1469 delta = (object->resident_page_count -
1470 object->wired_page_count);
1471 if (delta != 0) {
1472 assert(vm_page_purgeable_count >= delta);
1473 OSAddAtomic(-delta,
1474 (SInt32 *)&vm_page_purgeable_count);
1475 }
1476 if (object->wired_page_count != 0) {
1477 assert(vm_page_purgeable_wired_count >=
1478 object->wired_page_count);
1479 OSAddAtomic(-object->wired_page_count,
1480 (SInt32 *)&vm_page_purgeable_wired_count);
1481 }
1482 VM_OBJECT_SET_PURGABLE(object, VM_PURGABLE_EMPTY);
1483 } else if (object->purgable == VM_PURGABLE_NONVOLATILE ||
1484 object->purgable == VM_PURGABLE_EMPTY) {
1485 /* remove from nonvolatile queue */
1486 vm_purgeable_nonvolatile_dequeue(object);
1487 } else {
1488 panic("object %p in unexpected purgeable state 0x%x",
1489 object, object->purgable);
1490 }
1491 if (object->transposed &&
1492 object->cached_list.next != NULL &&
1493 object->cached_list.prev == NULL) {
1494 /*
1495 * object->cached_list.next "points" to the
1496 * object that was transposed with this object.
1497 */
1498 } else {
1499 assert(object->cached_list.next == NULL);
1500 }
1501 assert(object->cached_list.prev == NULL);
1502 }
1503
1504 if (object->pageout) {
1505 /*
1506 * free all remaining pages tabled on
1507 * this object
1508 * clean up it's shadow
1509 */
1510 assert(object->shadow != VM_OBJECT_NULL);
1511
1512 vm_pageout_object_terminate(object);
1513 } else if (object->resident_page_count) {
1514 /*
1515 * free all remaining pages tabled on
1516 * this object
1517 */
1518 vm_object_reap_pages(object, REAP_REAP);
1519 }
1520 assert(vm_page_queue_empty(&object->memq));
1521 assert(object->paging_in_progress == 0);
1522 assert(object->activity_in_progress == 0);
1523 assert(os_ref_get_count_raw(&object->ref_count) == 0);
1524
1525 /*
1526 * If the pager has not already been released by
1527 * vm_object_destroy, we need to terminate it and
1528 * release our reference to it here.
1529 */
1530 if (pager != MEMORY_OBJECT_NULL) {
1531 vm_object_unlock(object);
1532 vm_object_release_pager(pager);
1533 vm_object_lock(object);
1534 }
1535
1536 /* kick off anyone waiting on terminating */
1537 VM_OBJECT_SET_TERMINATING(object, FALSE);
1538 vm_object_paging_begin(object);
1539 vm_object_paging_end(object);
1540 vm_object_unlock(object);
1541
1542 object->shadow = VM_OBJECT_NULL;
1543
1544 #if VM_OBJECT_TRACKING
1545 if (vm_object_tracking_btlog) {
1546 btlog_erase(vm_object_tracking_btlog, object);
1547 }
1548 #endif /* VM_OBJECT_TRACKING */
1549
1550 vm_object_lock_destroy(object);
1551 /*
1552 * Free the space for the object.
1553 */
1554 zfree(vm_object_zone, object);
1555 object = VM_OBJECT_NULL;
1556 }
1557
1558
1559 unsigned int vm_max_batch = 256;
1560
1561 #define V_O_R_MAX_BATCH 128
1562
1563 #define BATCH_LIMIT(max) (vm_max_batch >= max ? max : vm_max_batch)
1564
1565 static inline vm_page_t
vm_object_reap_freelist(vm_page_t local_free_q,bool do_disconnect,bool set_cache_attr)1566 vm_object_reap_freelist(vm_page_t local_free_q, bool do_disconnect, bool set_cache_attr)
1567 {
1568 vm_page_t page;
1569 if (local_free_q) {
1570 if (do_disconnect) {
1571 vm_page_list_foreach(page, local_free_q) {
1572 if (page->vmp_pmapped) {
1573 pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(page));
1574 }
1575 }
1576 }
1577
1578 if (set_cache_attr) {
1579 const unified_page_list_t pmap_batch_list = {
1580 .page_slist = local_free_q,
1581 .type = UNIFIED_PAGE_LIST_TYPE_VM_PAGE_LIST,
1582 };
1583 pmap_batch_set_cache_attributes(&pmap_batch_list, 0);
1584 }
1585 vm_page_free_list(local_free_q, TRUE);
1586 }
1587 return VM_PAGE_NULL;
1588 }
1589
1590 void
vm_object_reap_pages(vm_object_t object,int reap_type)1591 vm_object_reap_pages(
1592 vm_object_t object,
1593 int reap_type)
1594 {
1595 vm_page_t p;
1596 vm_page_t next;
1597 vm_page_t local_free_q = VM_PAGE_NULL;
1598 int loop_count;
1599 bool disconnect_on_release;
1600 bool set_cache_attr_needed;
1601 pmap_flush_context pmap_flush_context_storage;
1602
1603 if (reap_type == REAP_DATA_FLUSH) {
1604 /*
1605 * We need to disconnect pages from all pmaps before
1606 * releasing them to the free list
1607 */
1608 disconnect_on_release = true;
1609 } else {
1610 /*
1611 * Either the caller has already disconnected the pages
1612 * from all pmaps, or we disconnect them here as we add
1613 * them to out local list of pages to be released.
1614 * No need to re-disconnect them when we release the pages
1615 * to the free list.
1616 */
1617 disconnect_on_release = false;
1618 }
1619
1620 restart_after_sleep:
1621 set_cache_attr_needed = false;
1622 if (object->set_cache_attr) {
1623 /**
1624 * If the cache attributes need to be reset for the pages to
1625 * be freed, we clear object->set_cache_attr here so that
1626 * our call to vm_page_free_list (which will ultimately call
1627 * vm_page_remove() on each page) won't try to reset the
1628 * cache attributes on each page individually. Depending on
1629 * the architecture, it may be much faster for us to call
1630 * pmap_batch_set_cache_attributes() instead. Note that
1631 * this function must restore object->set_cache_attr in any
1632 * case where it is required to drop the object lock, e.g.
1633 * to wait for a busy page.
1634 */
1635 object->set_cache_attr = FALSE;
1636 set_cache_attr_needed = true;
1637 }
1638
1639 if (vm_page_queue_empty(&object->memq)) {
1640 return;
1641 }
1642 loop_count = BATCH_LIMIT(V_O_R_MAX_BATCH);
1643
1644 if (reap_type == REAP_PURGEABLE) {
1645 pmap_flush_context_init(&pmap_flush_context_storage);
1646 }
1647
1648 vm_page_lock_queues();
1649
1650 next = (vm_page_t)vm_page_queue_first(&object->memq);
1651
1652 while (!vm_page_queue_end(&object->memq, (vm_page_queue_entry_t)next)) {
1653 p = next;
1654 next = (vm_page_t)vm_page_queue_next(&next->vmp_listq);
1655
1656 if (--loop_count == 0) {
1657 vm_page_unlock_queues();
1658
1659 if (local_free_q) {
1660 if (reap_type == REAP_PURGEABLE) {
1661 pmap_flush(&pmap_flush_context_storage);
1662 pmap_flush_context_init(&pmap_flush_context_storage);
1663 }
1664 /*
1665 * Free the pages we reclaimed so far
1666 * and take a little break to avoid
1667 * hogging the page queue lock too long
1668 */
1669 local_free_q = vm_object_reap_freelist(local_free_q,
1670 disconnect_on_release, set_cache_attr_needed);
1671 } else {
1672 mutex_pause(0);
1673 }
1674
1675 loop_count = BATCH_LIMIT(V_O_R_MAX_BATCH);
1676
1677 vm_page_lock_queues();
1678 }
1679 if (reap_type == REAP_DATA_FLUSH || reap_type == REAP_TERMINATE) {
1680 if (p->vmp_busy || p->vmp_cleaning) {
1681 vm_page_unlock_queues();
1682 /*
1683 * free the pages reclaimed so far
1684 */
1685 local_free_q = vm_object_reap_freelist(local_free_q,
1686 disconnect_on_release, set_cache_attr_needed);
1687
1688 if (set_cache_attr_needed) {
1689 object->set_cache_attr = TRUE;
1690 }
1691 vm_page_sleep(object, p, THREAD_UNINT, LCK_SLEEP_DEFAULT);
1692
1693 goto restart_after_sleep;
1694 }
1695 if (p->vmp_laundry) {
1696 vm_pageout_steal_laundry(p, TRUE);
1697 }
1698 }
1699 switch (reap_type) {
1700 case REAP_DATA_FLUSH:
1701 if (VM_PAGE_WIRED(p)) {
1702 /*
1703 * this is an odd case... perhaps we should
1704 * zero-fill this page since we're conceptually
1705 * tossing its data at this point, but leaving
1706 * it on the object to honor the 'wire' contract
1707 */
1708 continue;
1709 }
1710 break;
1711
1712 case REAP_PURGEABLE:
1713 if (VM_PAGE_WIRED(p)) {
1714 /*
1715 * can't purge a wired page
1716 */
1717 vm_page_purged_wired++;
1718 continue;
1719 }
1720 if (p->vmp_laundry && !p->vmp_busy && !p->vmp_cleaning) {
1721 vm_pageout_steal_laundry(p, TRUE);
1722 }
1723
1724 if (p->vmp_cleaning || p->vmp_laundry || p->vmp_absent) {
1725 /*
1726 * page is being acted upon,
1727 * so don't mess with it
1728 */
1729 vm_page_purged_others++;
1730 continue;
1731 }
1732 if (p->vmp_busy) {
1733 /*
1734 * We can't reclaim a busy page but we can
1735 * make it more likely to be paged (it's not wired) to make
1736 * sure that it gets considered by
1737 * vm_pageout_scan() later.
1738 */
1739 if (VM_PAGE_PAGEABLE(p)) {
1740 vm_page_deactivate(p);
1741 }
1742 vm_page_purged_busy++;
1743 continue;
1744 }
1745
1746 assert(!is_kernel_object(VM_PAGE_OBJECT(p)));
1747
1748 /*
1749 * we can discard this page...
1750 */
1751 if (p->vmp_pmapped == TRUE) {
1752 /*
1753 * unmap the page
1754 */
1755 pmap_disconnect_options(VM_PAGE_GET_PHYS_PAGE(p), PMAP_OPTIONS_NOFLUSH | PMAP_OPTIONS_NOREFMOD, (void *)&pmap_flush_context_storage);
1756 }
1757 vm_page_purged_count++;
1758
1759 break;
1760
1761 case REAP_TERMINATE:
1762 if (p->vmp_absent || vm_page_is_private(p)) {
1763 /*
1764 * For private pages, VM_PAGE_FREE just
1765 * leaves the page structure around for
1766 * its owner to clean up. For absent
1767 * pages, the structure is returned to
1768 * the appropriate pool.
1769 */
1770 break;
1771 }
1772 if (vm_page_is_fictitious(p)) {
1773 assert(vm_page_is_guard(p));
1774 break;
1775 }
1776 if (!p->vmp_dirty && p->vmp_wpmapped) {
1777 p->vmp_dirty = pmap_is_modified(VM_PAGE_GET_PHYS_PAGE(p));
1778 }
1779
1780 if ((p->vmp_dirty || p->vmp_precious) && !VMP_ERROR_GET(p) && object->alive) {
1781 assert(!object->internal);
1782
1783 p->vmp_free_when_done = TRUE;
1784
1785 if (!p->vmp_laundry) {
1786 vm_page_queues_remove(p, TRUE);
1787 /*
1788 * flush page... page will be freed
1789 * upon completion of I/O
1790 */
1791 vm_pageout_cluster(p);
1792 }
1793 vm_page_unlock_queues();
1794 /*
1795 * free the pages reclaimed so far
1796 */
1797 local_free_q = vm_object_reap_freelist(local_free_q,
1798 disconnect_on_release, set_cache_attr_needed);
1799
1800 if (set_cache_attr_needed) {
1801 object->set_cache_attr = TRUE;
1802 }
1803 vm_object_paging_wait(object, THREAD_UNINT);
1804
1805 goto restart_after_sleep;
1806 }
1807 break;
1808
1809 case REAP_REAP:
1810 break;
1811 }
1812 vm_page_free_prepare_queues(p);
1813 assert(p->vmp_pageq.next == 0 && p->vmp_pageq.prev == 0);
1814 /*
1815 * Add this page to our list of reclaimed pages,
1816 * to be freed later.
1817 */
1818 p->vmp_snext = local_free_q;
1819 local_free_q = p;
1820 }
1821 vm_page_unlock_queues();
1822
1823 /*
1824 * Free the remaining reclaimed pages
1825 */
1826 if (reap_type == REAP_PURGEABLE) {
1827 pmap_flush(&pmap_flush_context_storage);
1828 }
1829
1830 vm_object_reap_freelist(local_free_q,
1831 disconnect_on_release, set_cache_attr_needed);
1832 if (set_cache_attr_needed) {
1833 object->set_cache_attr = TRUE;
1834 }
1835 }
1836
1837
1838 void
vm_object_reap_async(vm_object_t object)1839 vm_object_reap_async(
1840 vm_object_t object)
1841 {
1842 vm_object_lock_assert_exclusive(object);
1843
1844 vm_object_reaper_lock_spin();
1845
1846 vm_object_reap_count_async++;
1847
1848 /* enqueue the VM object... */
1849 queue_enter(&vm_object_reaper_queue, object,
1850 vm_object_t, cached_list);
1851
1852 vm_object_reaper_unlock();
1853
1854 /* ... and wake up the reaper thread */
1855 thread_wakeup((event_t) &vm_object_reaper_queue);
1856 }
1857
1858
1859 void
vm_object_reaper_thread(void)1860 vm_object_reaper_thread(void)
1861 {
1862 vm_object_t object, shadow_object;
1863
1864 vm_object_reaper_lock_spin();
1865
1866 while (!queue_empty(&vm_object_reaper_queue)) {
1867 queue_remove_first(&vm_object_reaper_queue,
1868 object,
1869 vm_object_t,
1870 cached_list);
1871
1872 vm_object_reaper_unlock();
1873 vm_object_lock(object);
1874
1875 assert(object->terminating);
1876 assert(!object->alive);
1877
1878 /*
1879 * The pageout daemon might be playing with our pages.
1880 * Now that the object is dead, it won't touch any more
1881 * pages, but some pages might already be on their way out.
1882 * Hence, we wait until the active paging activities have
1883 * ceased before we break the association with the pager
1884 * itself.
1885 */
1886 vm_object_paging_wait(object, THREAD_UNINT);
1887
1888 shadow_object =
1889 object->pageout ? VM_OBJECT_NULL : object->shadow;
1890
1891 vm_object_reap(object);
1892 /* cache is unlocked and object is no longer valid */
1893 object = VM_OBJECT_NULL;
1894
1895 if (shadow_object != VM_OBJECT_NULL) {
1896 /*
1897 * Drop the reference "object" was holding on
1898 * its shadow object.
1899 */
1900 vm_object_deallocate(shadow_object);
1901 shadow_object = VM_OBJECT_NULL;
1902 }
1903 vm_object_reaper_lock_spin();
1904 }
1905
1906 /* wait for more work... */
1907 assert_wait((event_t) &vm_object_reaper_queue, THREAD_UNINT);
1908
1909 vm_object_reaper_unlock();
1910
1911 thread_block((thread_continue_t) vm_object_reaper_thread);
1912 /*NOTREACHED*/
1913 }
1914
1915 /*
1916 * Routine: vm_object_release_pager
1917 * Purpose: Terminate the pager and, upon completion,
1918 * release our last reference to it.
1919 */
1920 static void
vm_object_release_pager(memory_object_t pager)1921 vm_object_release_pager(
1922 memory_object_t pager)
1923 {
1924 /*
1925 * Terminate the pager.
1926 */
1927
1928 (void) memory_object_terminate(pager);
1929
1930 /*
1931 * Release reference to pager.
1932 */
1933 memory_object_deallocate(pager);
1934 }
1935
1936 /*
1937 * Routine: vm_object_destroy
1938 * Purpose:
1939 * Shut down a VM object, despite the
1940 * presence of address map (or other) references
1941 * to the vm_object.
1942 */
1943 #if FBDP_DEBUG_OBJECT_NO_PAGER
1944 extern uint32_t system_inshutdown;
1945 int fbdp_no_panic = 1;
1946 #endif /* FBDP_DEBUG_OBJECT_NO_PAGER */
1947 kern_return_t
vm_object_destroy(vm_object_t object,vm_object_destroy_reason_t reason)1948 vm_object_destroy(
1949 vm_object_t object,
1950 vm_object_destroy_reason_t reason)
1951 {
1952 memory_object_t old_pager;
1953
1954 if (object == VM_OBJECT_NULL) {
1955 return KERN_SUCCESS;
1956 }
1957
1958 /*
1959 * Remove the pager association immediately.
1960 *
1961 * This will prevent the memory manager from further
1962 * meddling. [If it wanted to flush data or make
1963 * other changes, it should have done so before performing
1964 * the destroy call.]
1965 */
1966
1967 vm_object_lock(object);
1968
1969 #if FBDP_DEBUG_OBJECT_NO_PAGER
1970 static bool fbdp_no_panic_retrieved = false;
1971 if (!fbdp_no_panic_retrieved) {
1972 PE_parse_boot_argn("fbdp_no_panic4", &fbdp_no_panic, sizeof(fbdp_no_panic));
1973 fbdp_no_panic_retrieved = true;
1974 }
1975
1976 bool forced_unmount = false;
1977 if (object->named &&
1978 os_ref_get_count_raw(&object->ref_count) > 2 &&
1979 object->pager != NULL &&
1980 vnode_pager_get_forced_unmount(object->pager, &forced_unmount) == KERN_SUCCESS &&
1981 forced_unmount == false) {
1982 if (!fbdp_no_panic) {
1983 panic("FBDP rdar://99829401 object %p refs %d pager %p (no forced unmount)\n", object, os_ref_get_count_raw(&object->ref_count), object->pager);
1984 }
1985 DTRACE_VM3(vm_object_destroy_no_forced_unmount,
1986 vm_object_t, object,
1987 int, os_ref_get_count_raw(&object->ref_count),
1988 memory_object_t, object->pager);
1989 }
1990
1991 if (object->fbdp_tracked) {
1992 if (os_ref_get_count_raw(&object->ref_count) > 2 && !system_inshutdown) {
1993 if (!fbdp_no_panic) {
1994 panic("FBDP/4 rdar://99829401 object %p refs %d pager %p (tracked)\n", object, os_ref_get_count_raw(&object->ref_count), object->pager);
1995 }
1996 }
1997 VM_OBJECT_SET_FBDP_TRACKED(object, false);
1998 }
1999 #endif /* FBDP_DEBUG_OBJECT_NO_PAGER */
2000
2001 VM_OBJECT_SET_NO_PAGER_REASON(object, reason);
2002
2003 VM_OBJECT_SET_CAN_PERSIST(object, FALSE);
2004 VM_OBJECT_SET_NAMED(object, FALSE);
2005 #if 00
2006 VM_OBJECT_SET_ALIVE(object, FALSE);
2007 #endif /* 00 */
2008
2009 #if DEVELOPMENT || DEBUG
2010 if (object->object_is_shared_cache &&
2011 object->pager != NULL &&
2012 object->pager->mo_pager_ops == &shared_region_pager_ops) {
2013 OSAddAtomic(-object->resident_page_count, &shared_region_pagers_resident_count);
2014 }
2015 #endif /* DEVELOPMENT || DEBUG */
2016
2017 old_pager = object->pager;
2018 object->pager = MEMORY_OBJECT_NULL;
2019 if (old_pager != MEMORY_OBJECT_NULL) {
2020 memory_object_control_disable(&object->pager_control);
2021 }
2022
2023 /*
2024 * Wait for the existing paging activity (that got
2025 * through before we nulled out the pager) to subside.
2026 */
2027
2028 vm_object_paging_wait(object, THREAD_UNINT);
2029 vm_object_unlock(object);
2030
2031 /*
2032 * Terminate the object now.
2033 */
2034 if (old_pager != MEMORY_OBJECT_NULL) {
2035 vm_object_release_pager(old_pager);
2036
2037 /*
2038 * JMM - Release the caller's reference. This assumes the
2039 * caller had a reference to release, which is a big (but
2040 * currently valid) assumption if this is driven from the
2041 * vnode pager (it is holding a named reference when making
2042 * this call)..
2043 */
2044 vm_object_deallocate(object);
2045 }
2046 return KERN_SUCCESS;
2047 }
2048
2049 /*
2050 * The "chunk" macros are used by routines below when looking for pages to deactivate. These
2051 * exist because of the need to handle shadow chains. When deactivating pages, we only
2052 * want to deactive the ones at the top most level in the object chain. In order to do
2053 * this efficiently, the specified address range is divided up into "chunks" and we use
2054 * a bit map to keep track of which pages have already been processed as we descend down
2055 * the shadow chain. These chunk macros hide the details of the bit map implementation
2056 * as much as we can.
2057 *
2058 * For convenience, we use a 64-bit data type as the bit map, and therefore a chunk is
2059 * set to 64 pages. The bit map is indexed from the low-order end, so that the lowest
2060 * order bit represents page 0 in the current range and highest order bit represents
2061 * page 63.
2062 *
2063 * For further convenience, we also use negative logic for the page state in the bit map.
2064 * The bit is set to 1 to indicate it has not yet been seen, and to 0 to indicate it has
2065 * been processed. This way we can simply test the 64-bit long word to see if it's zero
2066 * to easily tell if the whole range has been processed. Therefore, the bit map starts
2067 * out with all the bits set. The macros below hide all these details from the caller.
2068 */
2069
2070 #define PAGES_IN_A_CHUNK 64 /* The number of pages in the chunk must */
2071 /* be the same as the number of bits in */
2072 /* the chunk_state_t type. We use 64 */
2073 /* just for convenience. */
2074
2075 #define CHUNK_SIZE (PAGES_IN_A_CHUNK * PAGE_SIZE_64) /* Size of a chunk in bytes */
2076
2077 typedef uint64_t chunk_state_t;
2078
2079 /*
2080 * The bit map uses negative logic, so we start out with all 64 bits set to indicate
2081 * that no pages have been processed yet. Also, if len is less than the full CHUNK_SIZE,
2082 * then we mark pages beyond the len as having been "processed" so that we don't waste time
2083 * looking at pages in that range. This can save us from unnecessarily chasing down the
2084 * shadow chain.
2085 */
2086
2087 #define CHUNK_INIT(c, len) \
2088 MACRO_BEGIN \
2089 uint64_t p; \
2090 \
2091 (c) = 0xffffffffffffffffLL; \
2092 \
2093 for (p = (len) / PAGE_SIZE_64; p < PAGES_IN_A_CHUNK; p++) \
2094 MARK_PAGE_HANDLED(c, p); \
2095 MACRO_END
2096
2097
2098 /*
2099 * Return true if all pages in the chunk have not yet been processed.
2100 */
2101
2102 #define CHUNK_NOT_COMPLETE(c) ((c) != 0)
2103
2104 /*
2105 * Return true if the page at offset 'p' in the bit map has already been handled
2106 * while processing a higher level object in the shadow chain.
2107 */
2108
2109 #define PAGE_ALREADY_HANDLED(c, p) (((c) & (1ULL << (p))) == 0)
2110
2111 /*
2112 * Mark the page at offset 'p' in the bit map as having been processed.
2113 */
2114
2115 #define MARK_PAGE_HANDLED(c, p) \
2116 MACRO_BEGIN \
2117 (c) = (c) & ~(1ULL << (p)); \
2118 MACRO_END
2119
2120
2121 /*
2122 * Return true if the page at the given offset has been paged out. Object is
2123 * locked upon entry and returned locked.
2124 *
2125 * NB: It is the callers responsibility to ensure that the offset in question
2126 * is not in the process of being paged in/out (i.e. not busy or no backing
2127 * page)
2128 */
2129 static bool
page_is_paged_out(vm_object_t object,vm_object_offset_t offset)2130 page_is_paged_out(
2131 vm_object_t object,
2132 vm_object_offset_t offset)
2133 {
2134 if (object->internal &&
2135 object->alive &&
2136 !object->terminating &&
2137 object->pager_ready) {
2138 if (vm_object_compressor_pager_state_get(object, offset)
2139 == VM_EXTERNAL_STATE_EXISTS) {
2140 return true;
2141 }
2142 }
2143 return false;
2144 }
2145
2146
2147
2148 /*
2149 * madvise_free_debug
2150 *
2151 * To help debug madvise(MADV_FREE*) mis-usage, this triggers a
2152 * zero-fill as soon as a page is affected by a madvise(MADV_FREE*), to
2153 * simulate the loss of the page's contents as if the page had been
2154 * reclaimed and then re-faulted.
2155 */
2156 #if DEVELOPMENT || DEBUG
2157 int madvise_free_debug = 0;
2158 int madvise_free_debug_sometimes = 1;
2159 #else /* DEBUG */
2160 int madvise_free_debug = 0;
2161 int madvise_free_debug_sometimes = 0;
2162 #endif /* DEBUG */
2163 int madvise_free_counter = 0;
2164
2165 __options_decl(deactivate_flags_t, uint32_t, {
2166 DEACTIVATE_KILL = 0x1,
2167 DEACTIVATE_REUSABLE = 0x2,
2168 DEACTIVATE_ALL_REUSABLE = 0x4,
2169 DEACTIVATE_CLEAR_REFMOD = 0x8,
2170 DEACTIVATE_KILL_NO_WRITE = 0x10
2171 });
2172
2173 /*
2174 * Deactivate the pages in the specified object and range. If kill_page is set, also discard any
2175 * page modified state from the pmap. Update the chunk_state as we go along. The caller must specify
2176 * a size that is less than or equal to the CHUNK_SIZE.
2177 */
2178
2179 static void
deactivate_pages_in_object(vm_object_t object,vm_object_offset_t offset,vm_object_size_t size,deactivate_flags_t flags,chunk_state_t * chunk_state,pmap_flush_context * pfc,struct pmap * pmap,vm_map_offset_t pmap_offset)2180 deactivate_pages_in_object(
2181 vm_object_t object,
2182 vm_object_offset_t offset,
2183 vm_object_size_t size,
2184 deactivate_flags_t flags,
2185 chunk_state_t *chunk_state,
2186 pmap_flush_context *pfc,
2187 struct pmap *pmap,
2188 vm_map_offset_t pmap_offset)
2189 {
2190 vm_page_t m;
2191 int p;
2192 struct vm_page_delayed_work dw_array;
2193 struct vm_page_delayed_work *dwp, *dwp_start;
2194 bool dwp_finish_ctx = TRUE;
2195 int dw_count;
2196 int dw_limit;
2197 unsigned int reusable = 0;
2198
2199 /*
2200 * Examine each page in the chunk. The variable 'p' is the page number relative to the start of the
2201 * chunk. Since this routine is called once for each level in the shadow chain, the chunk_state may
2202 * have pages marked as having been processed already. We stop the loop early if we find we've handled
2203 * all the pages in the chunk.
2204 */
2205
2206 dwp_start = dwp = NULL;
2207 dw_count = 0;
2208 dw_limit = DELAYED_WORK_LIMIT(DEFAULT_DELAYED_WORK_LIMIT);
2209 dwp_start = vm_page_delayed_work_get_ctx();
2210 if (dwp_start == NULL) {
2211 dwp_start = &dw_array;
2212 dw_limit = 1;
2213 dwp_finish_ctx = FALSE;
2214 }
2215
2216 dwp = dwp_start;
2217
2218 for (p = 0; size && CHUNK_NOT_COMPLETE(*chunk_state); p++, size -= PAGE_SIZE_64, offset += PAGE_SIZE_64, pmap_offset += PAGE_SIZE_64) {
2219 /*
2220 * If this offset has already been found and handled in a higher level object, then don't
2221 * do anything with it in the current shadow object.
2222 */
2223
2224 if (PAGE_ALREADY_HANDLED(*chunk_state, p)) {
2225 continue;
2226 }
2227
2228 /*
2229 * See if the page at this offset is around. First check to see if the page is resident,
2230 * then if not, check the existence map or with the pager.
2231 */
2232
2233 if ((m = vm_page_lookup(object, offset)) != VM_PAGE_NULL) {
2234 /*
2235 * We found a page we were looking for. Mark it as "handled" now in the chunk_state
2236 * so that we won't bother looking for a page at this offset again if there are more
2237 * shadow objects. Then deactivate the page.
2238 */
2239
2240 MARK_PAGE_HANDLED(*chunk_state, p);
2241
2242 if ((!VM_PAGE_WIRED(m)) && (!vm_page_is_private(m)) && (!m->vmp_gobbled) && (!m->vmp_busy) &&
2243 (!m->vmp_laundry) && (!m->vmp_cleaning) && !(m->vmp_free_when_done)) {
2244 int clear_refmod_mask;
2245 int pmap_options;
2246 dwp->dw_mask = 0;
2247
2248 pmap_options = 0;
2249 clear_refmod_mask = VM_MEM_REFERENCED;
2250 dwp->dw_mask |= DW_clear_reference;
2251
2252 if ((flags & DEACTIVATE_KILL) && (object->internal)) {
2253 if (!(flags & DEACTIVATE_KILL_NO_WRITE) &&
2254 (madvise_free_debug ||
2255 (madvise_free_debug_sometimes &&
2256 madvise_free_counter++ & 0x1))) {
2257 /*
2258 * zero-fill the page (or every
2259 * other page) now to simulate
2260 * it being reclaimed and
2261 * re-faulted.
2262 */
2263 #if CONFIG_TRACK_UNMODIFIED_ANON_PAGES
2264 if (!m->vmp_unmodified_ro) {
2265 #else /* CONFIG_TRACK_UNMODIFIED_ANON_PAGES */
2266 if (true) {
2267 #endif /* CONFIG_TRACK_UNMODIFIED_ANON_PAGES */
2268 pmap_zero_page(VM_PAGE_GET_PHYS_PAGE(m));
2269 }
2270 }
2271 m->vmp_precious = FALSE;
2272 m->vmp_dirty = FALSE;
2273
2274 clear_refmod_mask |= VM_MEM_MODIFIED;
2275 if (m->vmp_q_state == VM_PAGE_ON_THROTTLED_Q) {
2276 /*
2277 * This page is now clean and
2278 * reclaimable. Move it out
2279 * of the throttled queue, so
2280 * that vm_pageout_scan() can
2281 * find it.
2282 */
2283 dwp->dw_mask |= DW_move_page;
2284 }
2285
2286 #if 0
2287 #if CONFIG_TRACK_UNMODIFIED_ANON_PAGES
2288 /*
2289 * COMMENT BLOCK ON WHY THIS SHOULDN'T BE DONE.
2290 *
2291 * Since we are about to do a vm_object_compressor_pager_state_clr
2292 * below for this page, which drops any existing compressor
2293 * storage of this page (eg side-effect of a CoW operation or
2294 * a collapse operation), it is tempting to think that we should
2295 * treat this page as if it was just decompressed (during which
2296 * we also drop existing compressor storage) and so start its life
2297 * out with vmp_unmodified_ro set to FALSE.
2298 *
2299 * However, we can't do that here because we could swing around
2300 * and re-access this page in a read-only fault.
2301 * Clearing this bit means we'll try to zero it up above
2302 * and fail.
2303 *
2304 * Note that clearing the bit is unnecessary regardless because
2305 * dirty state has been cleared. During the next soft fault, the
2306 * right state will be restored and things will progress just fine.
2307 */
2308 if (m->vmp_unmodified_ro == true) {
2309 /* Need object and pageq locks for bit manipulation*/
2310 m->vmp_unmodified_ro = false;
2311 os_atomic_dec(&compressor_ro_uncompressed);
2312 }
2313 #endif /* CONFIG_TRACK_UNMODIFIED_ANON_PAGES */
2314 #endif /* 0 */
2315 vm_object_compressor_pager_state_clr(object, offset);
2316
2317 if ((flags & DEACTIVATE_REUSABLE) && !m->vmp_reusable) {
2318 assert(!(flags & DEACTIVATE_ALL_REUSABLE));
2319 assert(!object->all_reusable);
2320 m->vmp_reusable = TRUE;
2321 object->reusable_page_count++;
2322 assert(object->resident_page_count >= object->reusable_page_count);
2323 reusable++;
2324 /*
2325 * Tell pmap this page is now
2326 * "reusable" (to update pmap
2327 * stats for all mappings).
2328 */
2329 pmap_options |= PMAP_OPTIONS_SET_REUSABLE;
2330 }
2331 }
2332 if (flags & DEACTIVATE_CLEAR_REFMOD) {
2333 /*
2334 * The caller didn't clear the refmod bits in advance.
2335 * Clear them for this page now.
2336 */
2337 pmap_options |= PMAP_OPTIONS_NOFLUSH;
2338 pmap_clear_refmod_options(VM_PAGE_GET_PHYS_PAGE(m),
2339 clear_refmod_mask,
2340 pmap_options,
2341 (void *)pfc);
2342 }
2343
2344 if ((m->vmp_q_state != VM_PAGE_ON_THROTTLED_Q) &&
2345 !(flags & (DEACTIVATE_REUSABLE | DEACTIVATE_ALL_REUSABLE))) {
2346 dwp->dw_mask |= DW_move_page;
2347 }
2348
2349 if (dwp->dw_mask) {
2350 VM_PAGE_ADD_DELAYED_WORK(dwp, m,
2351 dw_count);
2352 }
2353
2354 if (dw_count >= dw_limit) {
2355 if (reusable) {
2356 OSAddAtomic(reusable,
2357 &vm_page_stats_reusable.reusable_count);
2358 vm_page_stats_reusable.reusable += reusable;
2359 reusable = 0;
2360 }
2361 vm_page_do_delayed_work(object, VM_KERN_MEMORY_NONE, dwp_start, dw_count);
2362
2363 dwp = dwp_start;
2364 dw_count = 0;
2365 }
2366 }
2367 } else {
2368 /*
2369 * The page at this offset isn't memory resident, check to see if it's
2370 * been paged out. If so, mark it as handled so we don't bother looking
2371 * for it in the shadow chain.
2372 */
2373
2374 if (page_is_paged_out(object, offset)) {
2375 MARK_PAGE_HANDLED(*chunk_state, p);
2376
2377 /*
2378 * If we're killing a non-resident page, then clear the page in the existence
2379 * map so we don't bother paging it back in if it's touched again in the future.
2380 */
2381
2382 if ((flags & DEACTIVATE_KILL) && (object->internal)) {
2383 vm_object_compressor_pager_state_clr(object, offset);
2384
2385 if (pmap != PMAP_NULL) {
2386 /*
2387 * Tell pmap that this page
2388 * is no longer mapped, to
2389 * adjust the footprint ledger
2390 * because this page is no
2391 * longer compressed.
2392 */
2393 pmap_remove_options(
2394 pmap,
2395 pmap_offset,
2396 (pmap_offset +
2397 PAGE_SIZE),
2398 PMAP_OPTIONS_REMOVE);
2399 }
2400 }
2401 }
2402 }
2403 }
2404
2405 if (reusable) {
2406 OSAddAtomic(reusable, &vm_page_stats_reusable.reusable_count);
2407 vm_page_stats_reusable.reusable += reusable;
2408 reusable = 0;
2409 }
2410
2411 if (dw_count) {
2412 vm_page_do_delayed_work(object, VM_KERN_MEMORY_NONE, dwp_start, dw_count);
2413 dwp = dwp_start;
2414 dw_count = 0;
2415 }
2416
2417 if (dwp_start && dwp_finish_ctx) {
2418 vm_page_delayed_work_finish_ctx(dwp_start);
2419 dwp_start = dwp = NULL;
2420 }
2421 }
2422
2423
2424 /*
2425 * Deactive a "chunk" of the given range of the object starting at offset. A "chunk"
2426 * will always be less than or equal to the given size. The total range is divided up
2427 * into chunks for efficiency and performance related to the locks and handling the shadow
2428 * chain. This routine returns how much of the given "size" it actually processed. It's
2429 * up to the caler to loop and keep calling this routine until the entire range they want
2430 * to process has been done.
2431 * Iff clear_refmod is true, pmap_clear_refmod_options is called for each physical page in this range.
2432 */
2433
2434 static vm_object_size_t
2435 deactivate_a_chunk(
2436 vm_object_t orig_object,
2437 vm_object_offset_t offset,
2438 vm_object_size_t size,
2439 deactivate_flags_t flags,
2440 pmap_flush_context *pfc,
2441 struct pmap *pmap,
2442 vm_map_offset_t pmap_offset)
2443 {
2444 vm_object_t object;
2445 vm_object_t tmp_object;
2446 vm_object_size_t length;
2447 chunk_state_t chunk_state;
2448
2449
2450 /*
2451 * Get set to do a chunk. We'll do up to CHUNK_SIZE, but no more than the
2452 * remaining size the caller asked for.
2453 */
2454
2455 length = MIN(size, CHUNK_SIZE);
2456
2457 /*
2458 * The chunk_state keeps track of which pages we've already processed if there's
2459 * a shadow chain on this object. At this point, we haven't done anything with this
2460 * range of pages yet, so initialize the state to indicate no pages processed yet.
2461 */
2462
2463 CHUNK_INIT(chunk_state, length);
2464 object = orig_object;
2465
2466 /*
2467 * Start at the top level object and iterate around the loop once for each object
2468 * in the shadow chain. We stop processing early if we've already found all the pages
2469 * in the range. Otherwise we stop when we run out of shadow objects.
2470 */
2471
2472 while (object && CHUNK_NOT_COMPLETE(chunk_state)) {
2473 vm_object_paging_begin(object);
2474
2475 deactivate_pages_in_object(object, offset, length, flags, &chunk_state, pfc, pmap, pmap_offset);
2476
2477 vm_object_paging_end(object);
2478
2479 /*
2480 * We've finished with this object, see if there's a shadow object. If
2481 * there is, update the offset and lock the new object. We also turn off
2482 * kill_page at this point since we only kill pages in the top most object.
2483 */
2484
2485 tmp_object = object->shadow;
2486
2487 if (tmp_object) {
2488 assert(!(flags & DEACTIVATE_KILL) || (flags & DEACTIVATE_CLEAR_REFMOD));
2489 flags &= ~(DEACTIVATE_KILL | DEACTIVATE_REUSABLE | DEACTIVATE_ALL_REUSABLE);
2490 offset += object->vo_shadow_offset;
2491 vm_object_lock(tmp_object);
2492 }
2493
2494 if (object != orig_object) {
2495 vm_object_unlock(object);
2496 }
2497
2498 object = tmp_object;
2499 }
2500
2501 if (object && object != orig_object) {
2502 vm_object_unlock(object);
2503 }
2504
2505 return length;
2506 }
2507
2508
2509
2510 /*
2511 * Move any resident pages in the specified range to the inactive queue. If kill_page is set,
2512 * we also clear the modified status of the page and "forget" any changes that have been made
2513 * to the page.
2514 */
2515
2516 __private_extern__ void
2517 vm_object_deactivate_pages(
2518 vm_object_t object,
2519 vm_object_offset_t offset,
2520 vm_object_size_t size,
2521 boolean_t kill_page,
2522 boolean_t reusable_page,
2523 boolean_t kill_no_write,
2524 struct pmap *pmap,
2525 vm_map_offset_t pmap_offset)
2526 {
2527 vm_object_size_t length;
2528 boolean_t all_reusable;
2529 pmap_flush_context pmap_flush_context_storage;
2530 unsigned int pmap_clear_refmod_mask = VM_MEM_REFERENCED;
2531 unsigned int pmap_clear_refmod_options = 0;
2532 deactivate_flags_t flags = DEACTIVATE_CLEAR_REFMOD;
2533 bool refmod_cleared = false;
2534 if (kill_page) {
2535 flags |= DEACTIVATE_KILL;
2536 }
2537 if (reusable_page) {
2538 flags |= DEACTIVATE_REUSABLE;
2539 }
2540 if (kill_no_write) {
2541 flags |= DEACTIVATE_KILL_NO_WRITE;
2542 }
2543
2544 /*
2545 * We break the range up into chunks and do one chunk at a time. This is for
2546 * efficiency and performance while handling the shadow chains and the locks.
2547 * The deactivate_a_chunk() function returns how much of the range it processed.
2548 * We keep calling this routine until the given size is exhausted.
2549 */
2550
2551
2552 all_reusable = FALSE;
2553 #if 11
2554 /*
2555 * For the sake of accurate "reusable" pmap stats, we need
2556 * to tell pmap about each page that is no longer "reusable",
2557 * so we can't do the "all_reusable" optimization.
2558 *
2559 * If we do go with the all_reusable optimization, we can't
2560 * return if size is 0 since we could have "all_reusable == TRUE"
2561 * In this case, we save the overhead of doing the pmap_flush_context
2562 * work.
2563 */
2564 if (size == 0) {
2565 return;
2566 }
2567 #else
2568 if (reusable_page &&
2569 object->internal &&
2570 object->vo_size != 0 &&
2571 object->vo_size == size &&
2572 object->reusable_page_count == 0) {
2573 all_reusable = TRUE;
2574 reusable_page = FALSE;
2575 flags |= DEACTIVATE_ALL_REUSABLE;
2576 }
2577 #endif
2578
2579 if ((reusable_page || all_reusable) && object->all_reusable) {
2580 /* This means MADV_FREE_REUSABLE has been called twice, which
2581 * is probably illegal. */
2582 return;
2583 }
2584
2585
2586 pmap_flush_context_init(&pmap_flush_context_storage);
2587
2588 /*
2589 * If we're deactivating multiple pages, try to perform one bulk pmap operation.
2590 * We can't do this if we're killing pages and there's a shadow chain as
2591 * we don't yet know which pages are in the top object (pages in shadow copies aren't
2592 * safe to kill).
2593 * And we can only do this on hardware that supports it.
2594 */
2595 if (size > PAGE_SIZE && (!kill_page || !object->shadow)) {
2596 if (kill_page && object->internal) {
2597 pmap_clear_refmod_mask |= VM_MEM_MODIFIED;
2598 }
2599 if (reusable_page) {
2600 pmap_clear_refmod_options |= PMAP_OPTIONS_SET_REUSABLE;
2601 }
2602
2603 refmod_cleared = pmap_clear_refmod_range_options(pmap, pmap_offset, pmap_offset + size, pmap_clear_refmod_mask, pmap_clear_refmod_options);
2604 if (refmod_cleared) {
2605 // We were able to clear all the refmod bits. So deactivate_a_chunk doesn't need to do it.
2606 flags &= ~DEACTIVATE_CLEAR_REFMOD;
2607 }
2608 }
2609
2610 while (size) {
2611 length = deactivate_a_chunk(object, offset, size, flags,
2612 &pmap_flush_context_storage, pmap, pmap_offset);
2613
2614 size -= length;
2615 offset += length;
2616 pmap_offset += length;
2617 }
2618 pmap_flush(&pmap_flush_context_storage);
2619
2620 if (all_reusable) {
2621 if (!object->all_reusable) {
2622 unsigned int reusable;
2623
2624 object->all_reusable = TRUE;
2625 assert(object->reusable_page_count == 0);
2626 /* update global stats */
2627 reusable = object->resident_page_count;
2628 OSAddAtomic(reusable,
2629 &vm_page_stats_reusable.reusable_count);
2630 vm_page_stats_reusable.reusable += reusable;
2631 vm_page_stats_reusable.all_reusable_calls++;
2632 }
2633 } else if (reusable_page) {
2634 vm_page_stats_reusable.partial_reusable_calls++;
2635 }
2636 }
2637
2638 void
2639 vm_object_reuse_pages(
2640 vm_object_t object,
2641 vm_object_offset_t start_offset,
2642 vm_object_offset_t end_offset,
2643 boolean_t allow_partial_reuse)
2644 {
2645 vm_object_offset_t cur_offset;
2646 vm_page_t m;
2647 unsigned int reused, reusable;
2648
2649 #define VM_OBJECT_REUSE_PAGE(object, m, reused) \
2650 MACRO_BEGIN \
2651 if ((m) != VM_PAGE_NULL && \
2652 (m)->vmp_reusable) { \
2653 assert((object)->reusable_page_count <= \
2654 (object)->resident_page_count); \
2655 assert((object)->reusable_page_count > 0); \
2656 (object)->reusable_page_count--; \
2657 (m)->vmp_reusable = FALSE; \
2658 (reused)++; \
2659 /* \
2660 * Tell pmap that this page is no longer \
2661 * "reusable", to update the "reusable" stats \
2662 * for all the pmaps that have mapped this \
2663 * page. \
2664 */ \
2665 pmap_clear_refmod_options(VM_PAGE_GET_PHYS_PAGE((m)), \
2666 0, /* refmod */ \
2667 (PMAP_OPTIONS_CLEAR_REUSABLE \
2668 | PMAP_OPTIONS_NOFLUSH), \
2669 NULL); \
2670 } \
2671 MACRO_END
2672
2673 reused = 0;
2674 reusable = 0;
2675
2676 vm_object_lock_assert_exclusive(object);
2677
2678 if (object->all_reusable) {
2679 panic("object %p all_reusable: can't update pmap stats",
2680 object);
2681 assert(object->reusable_page_count == 0);
2682 object->all_reusable = FALSE;
2683 if (end_offset - start_offset == object->vo_size ||
2684 !allow_partial_reuse) {
2685 vm_page_stats_reusable.all_reuse_calls++;
2686 reused = object->resident_page_count;
2687 } else {
2688 vm_page_stats_reusable.partial_reuse_calls++;
2689 vm_page_queue_iterate(&object->memq, m, vmp_listq) {
2690 if (m->vmp_offset < start_offset ||
2691 m->vmp_offset >= end_offset) {
2692 m->vmp_reusable = TRUE;
2693 object->reusable_page_count++;
2694 assert(object->resident_page_count >= object->reusable_page_count);
2695 continue;
2696 } else {
2697 assert(!m->vmp_reusable);
2698 reused++;
2699 }
2700 }
2701 }
2702 } else if (object->resident_page_count >
2703 ((end_offset - start_offset) >> PAGE_SHIFT)) {
2704 vm_page_stats_reusable.partial_reuse_calls++;
2705 for (cur_offset = start_offset;
2706 cur_offset < end_offset;
2707 cur_offset += PAGE_SIZE_64) {
2708 if (object->reusable_page_count == 0) {
2709 break;
2710 }
2711 m = vm_page_lookup(object, cur_offset);
2712 VM_OBJECT_REUSE_PAGE(object, m, reused);
2713 }
2714 } else {
2715 vm_page_stats_reusable.partial_reuse_calls++;
2716 vm_page_queue_iterate(&object->memq, m, vmp_listq) {
2717 if (object->reusable_page_count == 0) {
2718 break;
2719 }
2720 if (m->vmp_offset < start_offset ||
2721 m->vmp_offset >= end_offset) {
2722 continue;
2723 }
2724 VM_OBJECT_REUSE_PAGE(object, m, reused);
2725 }
2726 }
2727
2728 /* update global stats */
2729 OSAddAtomic(reusable - reused, &vm_page_stats_reusable.reusable_count);
2730 vm_page_stats_reusable.reused += reused;
2731 vm_page_stats_reusable.reusable += reusable;
2732 }
2733
2734 /*
2735 * This function determines if the zero operation can be run on the
2736 * object. The checks on the entry have already been performed by
2737 * vm_map_zero_entry_preflight.
2738 */
2739 static kern_return_t
2740 vm_object_zero_preflight(
2741 vm_object_t object,
2742 vm_object_offset_t start,
2743 vm_object_offset_t end)
2744 {
2745 /*
2746 * Zeroing is further restricted to anonymous memory.
2747 */
2748 if (!object->internal) {
2749 return KERN_PROTECTION_FAILURE;
2750 }
2751
2752 /*
2753 * Zeroing for copy on write isn't yet supported
2754 */
2755 if (object->shadow != NULL ||
2756 object->vo_copy != NULL) {
2757 return KERN_NO_ACCESS;
2758 }
2759
2760 /*
2761 * Ensure the that bounds makes sense wrt the object
2762 */
2763 if (end - start > object->vo_size) {
2764 return KERN_INVALID_ADDRESS;
2765 }
2766
2767 if (object->terminating || !object->alive) {
2768 return KERN_ABORTED;
2769 }
2770
2771 return KERN_SUCCESS;
2772 }
2773
2774 static void
2775 vm_object_zero_page(vm_page_t m)
2776 {
2777 if (m != VM_PAGE_NULL) {
2778 ppnum_t phy_page_num = VM_PAGE_GET_PHYS_PAGE(m);
2779
2780 /*
2781 * Skip fictitious guard pages
2782 */
2783 if (vm_page_is_fictitious(m)) {
2784 assert(vm_page_is_guard(m));
2785 return;
2786 }
2787 pmap_zero_page(phy_page_num);
2788 }
2789 }
2790
2791 /*
2792 * This function iterates the range of pages specified in the object and
2793 * discards the ones that are compressed and zeroes the ones that are wired.
2794 * This function may drop the object lock while waiting for a page that is
2795 * busy and will restart the operation for the specific offset.
2796 */
2797 kern_return_t
2798 vm_object_zero(
2799 vm_object_t object,
2800 vm_object_offset_t cur_offset,
2801 vm_object_offset_t end_offset)
2802 {
2803 kern_return_t ret;
2804
2805 vm_object_lock_assert_exclusive(object);
2806 ret = vm_object_zero_preflight(object, cur_offset, end_offset);
2807 if (ret != KERN_SUCCESS) {
2808 return ret;
2809 }
2810
2811 while (cur_offset < end_offset) {
2812 vm_page_t m = vm_page_lookup(object, cur_offset);
2813
2814 if (m != VM_PAGE_NULL && m->vmp_busy) {
2815 vm_page_sleep(object, m, THREAD_UNINT, LCK_SLEEP_DEFAULT);
2816 /* Object lock was dropped -- reverify validity */
2817 ret = vm_object_zero_preflight(object, cur_offset, end_offset);
2818 if (ret != KERN_SUCCESS) {
2819 return ret;
2820 }
2821 continue;
2822 }
2823
2824 /*
2825 * If the compressor has the page then just discard it instead
2826 * of faulting it in and zeroing it else zero the page if it exists. If
2827 * we dropped the object lock during the lookup retry the lookup for the
2828 * cur_offset.
2829 */
2830 if (page_is_paged_out(object, cur_offset)) {
2831 vm_object_compressor_pager_state_clr(object, cur_offset);
2832 } else {
2833 vm_object_zero_page(m);
2834 }
2835 cur_offset += PAGE_SIZE_64;
2836 /*
2837 * TODO: May need a vm_object_lock_yield_shared in this loop if it takes
2838 * too long, as holding the object lock for too long can stall pageout
2839 * scan (or other users of the object)
2840 */
2841 }
2842
2843 return KERN_SUCCESS;
2844 }
2845
2846 /*
2847 * Routine: vm_object_pmap_protect
2848 *
2849 * Purpose:
2850 * Reduces the permission for all physical
2851 * pages in the specified object range.
2852 *
2853 * If removing write permission only, it is
2854 * sufficient to protect only the pages in
2855 * the top-level object; only those pages may
2856 * have write permission.
2857 *
2858 * If removing all access, we must follow the
2859 * shadow chain from the top-level object to
2860 * remove access to all pages in shadowed objects.
2861 *
2862 * The object must *not* be locked. The object must
2863 * be internal.
2864 *
2865 * If pmap is not NULL, this routine assumes that
2866 * the only mappings for the pages are in that
2867 * pmap.
2868 */
2869
2870 __private_extern__ void
2871 vm_object_pmap_protect(
2872 vm_object_t object,
2873 vm_object_offset_t offset,
2874 vm_object_size_t size,
2875 pmap_t pmap,
2876 vm_map_size_t pmap_page_size,
2877 vm_map_offset_t pmap_start,
2878 vm_prot_t prot)
2879 {
2880 vm_object_pmap_protect_options(object, offset, size, pmap,
2881 pmap_page_size,
2882 pmap_start, prot, 0);
2883 }
2884
2885 __private_extern__ void
2886 vm_object_pmap_protect_options(
2887 vm_object_t object,
2888 vm_object_offset_t offset,
2889 vm_object_size_t size,
2890 pmap_t pmap,
2891 vm_map_size_t pmap_page_size,
2892 vm_map_offset_t pmap_start,
2893 vm_prot_t prot,
2894 int options)
2895 {
2896 pmap_flush_context pmap_flush_context_storage;
2897 boolean_t delayed_pmap_flush = FALSE;
2898 vm_object_offset_t offset_in_object;
2899 vm_object_size_t size_in_object;
2900
2901 if (object == VM_OBJECT_NULL) {
2902 return;
2903 }
2904 if (pmap_page_size > PAGE_SIZE) {
2905 /* for 16K map on 4K device... */
2906 pmap_page_size = PAGE_SIZE;
2907 }
2908 /*
2909 * If we decide to work on the object itself, extend the range to
2910 * cover a full number of native pages.
2911 */
2912 size_in_object = vm_object_round_page(offset + size) - vm_object_trunc_page(offset);
2913 offset_in_object = vm_object_trunc_page(offset);
2914 /*
2915 * If we decide to work on the pmap, use the exact range specified,
2916 * so no rounding/truncating offset and size. They should already
2917 * be aligned to pmap_page_size.
2918 */
2919 assertf(!(offset & (pmap_page_size - 1)) && !(size & (pmap_page_size - 1)),
2920 "offset 0x%llx size 0x%llx pmap_page_size 0x%llx",
2921 offset, size, (uint64_t)pmap_page_size);
2922
2923 vm_object_lock(object);
2924
2925 if (object->phys_contiguous) {
2926 if (pmap != NULL) {
2927 vm_object_unlock(object);
2928 pmap_protect_options(pmap,
2929 pmap_start,
2930 pmap_start + size,
2931 prot,
2932 options & ~PMAP_OPTIONS_NOFLUSH,
2933 NULL);
2934 } else {
2935 vm_object_offset_t phys_start, phys_end, phys_addr;
2936
2937 phys_start = object->vo_shadow_offset + offset_in_object;
2938 phys_end = phys_start + size_in_object;
2939 assert(phys_start <= phys_end);
2940 assert(phys_end <= object->vo_shadow_offset + object->vo_size);
2941 vm_object_unlock(object);
2942
2943 pmap_flush_context_init(&pmap_flush_context_storage);
2944 delayed_pmap_flush = FALSE;
2945
2946 for (phys_addr = phys_start;
2947 phys_addr < phys_end;
2948 phys_addr += PAGE_SIZE_64) {
2949 pmap_page_protect_options(
2950 (ppnum_t) (phys_addr >> PAGE_SHIFT),
2951 prot,
2952 options | PMAP_OPTIONS_NOFLUSH,
2953 (void *)&pmap_flush_context_storage);
2954 delayed_pmap_flush = TRUE;
2955 }
2956 if (delayed_pmap_flush == TRUE) {
2957 pmap_flush(&pmap_flush_context_storage);
2958 }
2959 }
2960 return;
2961 }
2962
2963 assert(object->internal);
2964
2965 while (TRUE) {
2966 if (ptoa_64(object->resident_page_count) > size_in_object / 2 && pmap != PMAP_NULL) {
2967 vm_object_unlock(object);
2968 if (pmap_page_size < PAGE_SIZE) {
2969 DEBUG4K_PMAP("pmap %p start 0x%llx end 0x%llx prot 0x%x: pmap_protect()\n", pmap, (uint64_t)pmap_start, pmap_start + size, prot);
2970 }
2971 pmap_protect_options(pmap, pmap_start, pmap_start + size, prot,
2972 options & ~PMAP_OPTIONS_NOFLUSH, NULL);
2973 return;
2974 }
2975
2976 if (pmap_page_size < PAGE_SIZE) {
2977 DEBUG4K_PMAP("pmap %p start 0x%llx end 0x%llx prot 0x%x: offset 0x%llx size 0x%llx object %p offset 0x%llx size 0x%llx\n", pmap, (uint64_t)pmap_start, pmap_start + size, prot, offset, size, object, offset_in_object, size_in_object);
2978 }
2979
2980 pmap_flush_context_init(&pmap_flush_context_storage);
2981 delayed_pmap_flush = FALSE;
2982
2983 /*
2984 * if we are doing large ranges with respect to resident
2985 * page count then we should interate over pages otherwise
2986 * inverse page look-up will be faster
2987 */
2988 if (ptoa_64(object->resident_page_count / 4) < size_in_object) {
2989 vm_page_t p;
2990 vm_object_offset_t end;
2991
2992 end = offset_in_object + size_in_object;
2993
2994 vm_page_queue_iterate(&object->memq, p, vmp_listq) {
2995 if (!vm_page_is_fictitious(p) &&
2996 (offset_in_object <= p->vmp_offset) &&
2997 (p->vmp_offset < end)) {
2998 vm_map_offset_t start;
2999
3000 /*
3001 * XXX FBDP 4K: intentionally using "offset" here instead
3002 * of "offset_in_object", since "start" is a pmap address.
3003 */
3004 start = pmap_start + p->vmp_offset - offset;
3005
3006 if (pmap != PMAP_NULL) {
3007 vm_map_offset_t curr;
3008 for (curr = start;
3009 curr < start + PAGE_SIZE_64;
3010 curr += pmap_page_size) {
3011 if (curr < pmap_start) {
3012 continue;
3013 }
3014 if (curr >= pmap_start + size) {
3015 break;
3016 }
3017 pmap_protect_options(
3018 pmap,
3019 curr,
3020 curr + pmap_page_size,
3021 prot,
3022 options | PMAP_OPTIONS_NOFLUSH,
3023 &pmap_flush_context_storage);
3024 }
3025 } else {
3026 pmap_page_protect_options(
3027 VM_PAGE_GET_PHYS_PAGE(p),
3028 prot,
3029 options | PMAP_OPTIONS_NOFLUSH,
3030 &pmap_flush_context_storage);
3031 }
3032 delayed_pmap_flush = TRUE;
3033 }
3034 }
3035 } else {
3036 vm_page_t p;
3037 vm_object_offset_t end;
3038 vm_object_offset_t target_off;
3039
3040 end = offset_in_object + size_in_object;
3041
3042 for (target_off = offset_in_object;
3043 target_off < end; target_off += PAGE_SIZE) {
3044 p = vm_page_lookup(object, target_off);
3045
3046 if (p != VM_PAGE_NULL) {
3047 vm_object_offset_t start;
3048
3049 /*
3050 * XXX FBDP 4K: intentionally using "offset" here instead
3051 * of "offset_in_object", since "start" is a pmap address.
3052 */
3053 start = pmap_start + (p->vmp_offset - offset);
3054
3055 if (pmap != PMAP_NULL) {
3056 vm_map_offset_t curr;
3057 for (curr = start;
3058 curr < start + PAGE_SIZE;
3059 curr += pmap_page_size) {
3060 if (curr < pmap_start) {
3061 continue;
3062 }
3063 if (curr >= pmap_start + size) {
3064 break;
3065 }
3066 pmap_protect_options(
3067 pmap,
3068 curr,
3069 curr + pmap_page_size,
3070 prot,
3071 options | PMAP_OPTIONS_NOFLUSH,
3072 &pmap_flush_context_storage);
3073 }
3074 } else {
3075 pmap_page_protect_options(
3076 VM_PAGE_GET_PHYS_PAGE(p),
3077 prot,
3078 options | PMAP_OPTIONS_NOFLUSH,
3079 &pmap_flush_context_storage);
3080 }
3081 delayed_pmap_flush = TRUE;
3082 }
3083 }
3084 }
3085 if (delayed_pmap_flush == TRUE) {
3086 pmap_flush(&pmap_flush_context_storage);
3087 }
3088
3089 if (prot == VM_PROT_NONE) {
3090 /*
3091 * Must follow shadow chain to remove access
3092 * to pages in shadowed objects.
3093 */
3094 vm_object_t next_object;
3095
3096 next_object = object->shadow;
3097 if (next_object != VM_OBJECT_NULL) {
3098 offset_in_object += object->vo_shadow_offset;
3099 offset += object->vo_shadow_offset;
3100 vm_object_lock(next_object);
3101 vm_object_unlock(object);
3102 object = next_object;
3103 } else {
3104 /*
3105 * End of chain - we are done.
3106 */
3107 break;
3108 }
3109 } else {
3110 /*
3111 * Pages in shadowed objects may never have
3112 * write permission - we may stop here.
3113 */
3114 break;
3115 }
3116 }
3117
3118 vm_object_unlock(object);
3119 }
3120
3121 uint32_t vm_page_busy_absent_skipped = 0;
3122
3123 /*
3124 * Routine: vm_object_copy_slowly
3125 *
3126 * Description:
3127 * Copy the specified range of the source
3128 * virtual memory object without using
3129 * protection-based optimizations (such
3130 * as copy-on-write). The pages in the
3131 * region are actually copied.
3132 *
3133 * In/out conditions:
3134 * The caller must hold a reference and a lock
3135 * for the source virtual memory object. The source
3136 * object will be returned *unlocked*.
3137 *
3138 * Results:
3139 * If the copy is completed successfully, KERN_SUCCESS is
3140 * returned. If the caller asserted the interruptible
3141 * argument, and an interruption occurred while waiting
3142 * for a user-generated event, MACH_SEND_INTERRUPTED is
3143 * returned. Other values may be returned to indicate
3144 * hard errors during the copy operation.
3145 *
3146 * A new virtual memory object is returned in a
3147 * parameter (_result_object). The contents of this
3148 * new object, starting at a zero offset, are a copy
3149 * of the source memory region. In the event of
3150 * an error, this parameter will contain the value
3151 * VM_OBJECT_NULL.
3152 */
3153 __private_extern__ kern_return_t
3154 vm_object_copy_slowly(
3155 vm_object_t src_object,
3156 vm_object_offset_t src_offset,
3157 vm_object_size_t size,
3158 boolean_t interruptible,
3159 vm_object_t *_result_object) /* OUT */
3160 {
3161 vm_object_t new_object;
3162 vm_object_offset_t new_offset;
3163
3164 struct vm_object_fault_info fault_info = {};
3165
3166 if (size == 0) {
3167 vm_object_unlock(src_object);
3168 *_result_object = VM_OBJECT_NULL;
3169 return KERN_INVALID_ARGUMENT;
3170 }
3171
3172 /*
3173 * Prevent destruction of the source object while we copy.
3174 */
3175
3176 vm_object_reference_locked(src_object);
3177 vm_object_unlock(src_object);
3178
3179 /*
3180 * Create a new object to hold the copied pages.
3181 * A few notes:
3182 * We fill the new object starting at offset 0,
3183 * regardless of the input offset.
3184 * We don't bother to lock the new object within
3185 * this routine, since we have the only reference.
3186 */
3187
3188 size = vm_object_round_page(src_offset + size) - vm_object_trunc_page(src_offset);
3189 src_offset = vm_object_trunc_page(src_offset);
3190 new_object = vm_object_allocate(size);
3191 new_offset = 0;
3192 if (src_object->copy_strategy == MEMORY_OBJECT_COPY_NONE &&
3193 src_object->vo_inherit_copy_none) {
3194 new_object->copy_strategy = MEMORY_OBJECT_COPY_NONE;
3195 new_object->vo_inherit_copy_none = true;
3196 }
3197
3198
3199 assert(size == trunc_page_64(size)); /* Will the loop terminate? */
3200
3201 fault_info.interruptible = interruptible;
3202 fault_info.behavior = VM_BEHAVIOR_SEQUENTIAL;
3203 fault_info.lo_offset = src_offset;
3204 fault_info.hi_offset = src_offset + size;
3205 fault_info.stealth = TRUE;
3206
3207 for (;
3208 size != 0;
3209 src_offset += PAGE_SIZE_64,
3210 new_offset += PAGE_SIZE_64, size -= PAGE_SIZE_64
3211 ) {
3212 vm_page_t new_page;
3213 vm_fault_return_t result;
3214
3215 vm_object_lock(new_object);
3216
3217 while ((new_page = vm_page_alloc(new_object, new_offset))
3218 == VM_PAGE_NULL) {
3219 vm_object_unlock(new_object);
3220
3221 if (!vm_page_wait(interruptible)) {
3222 vm_object_deallocate(new_object);
3223 vm_object_deallocate(src_object);
3224 *_result_object = VM_OBJECT_NULL;
3225 return MACH_SEND_INTERRUPTED;
3226 }
3227 vm_object_lock(new_object);
3228 }
3229 vm_object_unlock(new_object);
3230
3231 do {
3232 vm_prot_t prot = VM_PROT_READ;
3233 vm_page_t _result_page;
3234 vm_page_t top_page;
3235 vm_page_t result_page;
3236 kern_return_t error_code;
3237 vm_object_t result_page_object;
3238
3239
3240 vm_object_lock(src_object);
3241
3242 if (src_object->internal &&
3243 src_object->shadow == VM_OBJECT_NULL &&
3244 (src_object->pager == NULL ||
3245 (vm_object_compressor_pager_state_get(src_object,
3246 src_offset) ==
3247 VM_EXTERNAL_STATE_ABSENT))) {
3248 boolean_t can_skip_page;
3249
3250 _result_page = vm_page_lookup(src_object,
3251 src_offset);
3252 if (_result_page == VM_PAGE_NULL) {
3253 /*
3254 * This page is neither resident nor
3255 * compressed and there's no shadow
3256 * object below "src_object", so this
3257 * page is really missing.
3258 * There's no need to zero-fill it just
3259 * to copy it: let's leave it missing
3260 * in "new_object" and get zero-filled
3261 * on demand.
3262 */
3263 can_skip_page = TRUE;
3264 } else if (workaround_41447923 &&
3265 src_object->pager == NULL &&
3266 _result_page != VM_PAGE_NULL &&
3267 _result_page->vmp_busy &&
3268 _result_page->vmp_absent &&
3269 src_object->purgable == VM_PURGABLE_DENY &&
3270 !src_object->blocked_access) {
3271 /*
3272 * This page is "busy" and "absent"
3273 * but not because we're waiting for
3274 * it to be decompressed. It must
3275 * be because it's a "no zero fill"
3276 * page that is currently not
3277 * accessible until it gets overwritten
3278 * by a device driver.
3279 * Since its initial state would have
3280 * been "zero-filled", let's leave the
3281 * copy page missing and get zero-filled
3282 * on demand.
3283 */
3284 assert(src_object->internal);
3285 assert(src_object->shadow == NULL);
3286 assert(src_object->pager == NULL);
3287 can_skip_page = TRUE;
3288 vm_page_busy_absent_skipped++;
3289 } else {
3290 can_skip_page = FALSE;
3291 }
3292 if (can_skip_page) {
3293 vm_object_unlock(src_object);
3294 /* free the unused "new_page"... */
3295 vm_object_lock(new_object);
3296 VM_PAGE_FREE(new_page);
3297 new_page = VM_PAGE_NULL;
3298 vm_object_unlock(new_object);
3299 /* ...and go to next page in "src_object" */
3300 result = VM_FAULT_SUCCESS;
3301 break;
3302 }
3303 }
3304
3305 vm_object_paging_begin(src_object);
3306
3307 /* cap size at maximum UPL size */
3308 upl_size_t cluster_size;
3309 if (os_convert_overflow(size, &cluster_size)) {
3310 cluster_size = 0 - (upl_size_t)PAGE_SIZE;
3311 }
3312 fault_info.cluster_size = cluster_size;
3313
3314 _result_page = VM_PAGE_NULL;
3315 result = vm_fault_page(src_object, src_offset,
3316 VM_PROT_READ, FALSE,
3317 FALSE, /* page not looked up */
3318 &prot, &_result_page, &top_page,
3319 (int *)0,
3320 &error_code, FALSE, &fault_info);
3321
3322 switch (result) {
3323 case VM_FAULT_SUCCESS:
3324 result_page = _result_page;
3325 result_page_object = VM_PAGE_OBJECT(result_page);
3326
3327 /*
3328 * Copy the page to the new object.
3329 *
3330 * POLICY DECISION:
3331 * If result_page is clean,
3332 * we could steal it instead
3333 * of copying.
3334 */
3335 vm_page_copy(result_page, new_page);
3336
3337 vm_object_unlock(result_page_object);
3338
3339 /*
3340 * Let go of both pages (make them
3341 * not busy, perform wakeup, activate).
3342 */
3343 vm_object_lock(new_object);
3344 SET_PAGE_DIRTY(new_page, FALSE);
3345 vm_page_wakeup_done(new_object, new_page);
3346 vm_object_unlock(new_object);
3347
3348 vm_object_lock(result_page_object);
3349 vm_page_wakeup_done(result_page_object, result_page);
3350
3351 vm_page_lockspin_queues();
3352 if ((result_page->vmp_q_state == VM_PAGE_ON_SPECULATIVE_Q) ||
3353 (result_page->vmp_q_state == VM_PAGE_NOT_ON_Q)) {
3354 vm_page_activate(result_page);
3355 }
3356 vm_page_activate(new_page);
3357 vm_page_unlock_queues();
3358
3359 /*
3360 * Release paging references and
3361 * top-level placeholder page, if any.
3362 */
3363
3364 vm_fault_cleanup(result_page_object,
3365 top_page);
3366
3367 break;
3368
3369 case VM_FAULT_RETRY:
3370 break;
3371
3372 case VM_FAULT_MEMORY_SHORTAGE:
3373 if (vm_page_wait(interruptible)) {
3374 break;
3375 }
3376 ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_FAULT_OBJCOPYSLOWLY_MEMORY_SHORTAGE), 0 /* arg */);
3377 OS_FALLTHROUGH;
3378
3379 case VM_FAULT_INTERRUPTED:
3380 vm_object_lock(new_object);
3381 VM_PAGE_FREE(new_page);
3382 vm_object_unlock(new_object);
3383
3384 vm_object_deallocate(new_object);
3385 vm_object_deallocate(src_object);
3386 *_result_object = VM_OBJECT_NULL;
3387 return MACH_SEND_INTERRUPTED;
3388
3389 case VM_FAULT_SUCCESS_NO_VM_PAGE:
3390 /* success but no VM page: fail */
3391 vm_object_paging_end(src_object);
3392 vm_object_unlock(src_object);
3393 OS_FALLTHROUGH;
3394 case VM_FAULT_MEMORY_ERROR:
3395 /*
3396 * A policy choice:
3397 * (a) ignore pages that we can't
3398 * copy
3399 * (b) return the null object if
3400 * any page fails [chosen]
3401 */
3402
3403 vm_object_lock(new_object);
3404 VM_PAGE_FREE(new_page);
3405 vm_object_unlock(new_object);
3406
3407 vm_object_deallocate(new_object);
3408 vm_object_deallocate(src_object);
3409 *_result_object = VM_OBJECT_NULL;
3410 return error_code ? error_code:
3411 KERN_MEMORY_ERROR;
3412
3413 default:
3414 panic("vm_object_copy_slowly: unexpected error"
3415 " 0x%x from vm_fault_page()\n", result);
3416 }
3417 } while (result != VM_FAULT_SUCCESS);
3418 }
3419
3420 /*
3421 * Lose the extra reference, and return our object.
3422 */
3423 vm_object_deallocate(src_object);
3424 *_result_object = new_object;
3425 return KERN_SUCCESS;
3426 }
3427
3428 /*
3429 * Routine: vm_object_copy_quickly
3430 *
3431 * Purpose:
3432 * Copy the specified range of the source virtual
3433 * memory object, if it can be done without waiting
3434 * for user-generated events.
3435 *
3436 * Results:
3437 * If the copy is successful, the copy is returned in
3438 * the arguments; otherwise, the arguments are not
3439 * affected.
3440 *
3441 * In/out conditions:
3442 * The object should be unlocked on entry and exit.
3443 */
3444
3445 /*ARGSUSED*/
3446 __private_extern__ boolean_t
3447 vm_object_copy_quickly(
3448 vm_object_t object, /* IN */
3449 __unused vm_object_offset_t offset, /* IN */
3450 __unused vm_object_size_t size, /* IN */
3451 boolean_t *_src_needs_copy, /* OUT */
3452 boolean_t *_dst_needs_copy) /* OUT */
3453 {
3454 memory_object_copy_strategy_t copy_strategy;
3455
3456 if (object == VM_OBJECT_NULL) {
3457 *_src_needs_copy = FALSE;
3458 *_dst_needs_copy = FALSE;
3459 return TRUE;
3460 }
3461
3462 vm_object_lock(object);
3463
3464 copy_strategy = object->copy_strategy;
3465
3466 switch (copy_strategy) {
3467 case MEMORY_OBJECT_COPY_SYMMETRIC:
3468
3469 /*
3470 * Symmetric copy strategy.
3471 * Make another reference to the object.
3472 * Leave object/offset unchanged.
3473 */
3474
3475 vm_object_reference_locked(object);
3476 VM_OBJECT_SET_SHADOWED(object, TRUE);
3477 vm_object_unlock(object);
3478
3479 /*
3480 * Both source and destination must make
3481 * shadows, and the source must be made
3482 * read-only if not already.
3483 */
3484
3485 *_src_needs_copy = TRUE;
3486 *_dst_needs_copy = TRUE;
3487
3488 break;
3489
3490 case MEMORY_OBJECT_COPY_DELAY:
3491 vm_object_unlock(object);
3492 return FALSE;
3493
3494 default:
3495 vm_object_unlock(object);
3496 return FALSE;
3497 }
3498 return TRUE;
3499 }
3500
3501 static uint32_t copy_delayed_lock_collisions;
3502 static uint32_t copy_delayed_max_collisions;
3503 static uint32_t copy_delayed_lock_contention;
3504 static uint32_t copy_delayed_protect_iterate;
3505
3506 unsigned int vm_object_copy_delayed_paging_wait_disable = 0;
3507 /*
3508 * Routine: vm_object_copy_delayed [internal]
3509 *
3510 * Description:
3511 * Copy the specified virtual memory object, using
3512 * the asymmetric copy-on-write algorithm.
3513 *
3514 * In/out conditions:
3515 * The src_object must be locked on entry. It will be unlocked
3516 * on exit - so the caller must also hold a reference to it.
3517 *
3518 * This routine will not block waiting for user-generated
3519 * events. It is not interruptible.
3520 */
3521 __private_extern__ vm_object_t
3522 vm_object_copy_delayed(
3523 vm_object_t src_object,
3524 vm_object_offset_t src_offset,
3525 vm_object_size_t size,
3526 boolean_t src_object_shared)
3527 {
3528 vm_object_t new_copy = VM_OBJECT_NULL;
3529 vm_object_t old_copy;
3530 vm_page_t p;
3531 vm_object_size_t copy_size = src_offset + size;
3532 pmap_flush_context pmap_flush_context_storage;
3533 boolean_t delayed_pmap_flush = FALSE;
3534
3535
3536 uint32_t collisions = 0;
3537 /*
3538 * The user-level memory manager wants to see all of the changes
3539 * to this object, but it has promised not to make any changes on
3540 * its own.
3541 *
3542 * Perform an asymmetric copy-on-write, as follows:
3543 * Create a new object, called a "copy object" to hold
3544 * pages modified by the new mapping (i.e., the copy,
3545 * not the original mapping).
3546 * Record the original object as the backing object for
3547 * the copy object. If the original mapping does not
3548 * change a page, it may be used read-only by the copy.
3549 * Record the copy object in the original object.
3550 * When the original mapping causes a page to be modified,
3551 * it must be copied to a new page that is "pushed" to
3552 * the copy object.
3553 * Mark the new mapping (the copy object) copy-on-write.
3554 * This makes the copy object itself read-only, allowing
3555 * it to be reused if the original mapping makes no
3556 * changes, and simplifying the synchronization required
3557 * in the "push" operation described above.
3558 *
3559 * The copy-on-write is said to be assymetric because the original
3560 * object is *not* marked copy-on-write. A copied page is pushed
3561 * to the copy object, regardless which party attempted to modify
3562 * the page.
3563 *
3564 * Repeated asymmetric copy operations may be done. If the
3565 * original object has not been changed since the last copy, its
3566 * copy object can be reused. Otherwise, a new copy object can be
3567 * inserted between the original object and its previous copy
3568 * object. Since any copy object is read-only, this cannot affect
3569 * affect the contents of the previous copy object.
3570 *
3571 * Note that a copy object is higher in the object tree than the
3572 * original object; therefore, use of the copy object recorded in
3573 * the original object must be done carefully, to avoid deadlock.
3574 */
3575
3576 copy_size = vm_object_round_page(copy_size);
3577 Retry:
3578 if (!vm_object_copy_delayed_paging_wait_disable) {
3579 /*
3580 * Wait for paging in progress.
3581 */
3582 if (!src_object->true_share &&
3583 (src_object->paging_in_progress != 0 ||
3584 src_object->activity_in_progress != 0)) {
3585 if (src_object_shared == TRUE) {
3586 vm_object_unlock(src_object);
3587 vm_object_lock(src_object);
3588 src_object_shared = FALSE;
3589 goto Retry;
3590 }
3591 vm_object_paging_wait(src_object, THREAD_UNINT);
3592 }
3593 }
3594
3595 /*
3596 * See whether we can reuse the result of a previous
3597 * copy operation.
3598 */
3599
3600 old_copy = src_object->vo_copy;
3601 if (old_copy != VM_OBJECT_NULL) {
3602 int lock_granted;
3603
3604 /*
3605 * Try to get the locks (out of order)
3606 */
3607 if (src_object_shared == TRUE) {
3608 lock_granted = vm_object_lock_try_shared(old_copy);
3609 } else {
3610 lock_granted = vm_object_lock_try(old_copy);
3611 }
3612
3613 if (!lock_granted) {
3614 vm_object_unlock(src_object);
3615
3616 if (collisions++ == 0) {
3617 copy_delayed_lock_contention++;
3618 }
3619 mutex_pause(collisions);
3620
3621 /* Heisenberg Rules */
3622 copy_delayed_lock_collisions++;
3623
3624 if (collisions > copy_delayed_max_collisions) {
3625 copy_delayed_max_collisions = collisions;
3626 }
3627
3628 if (src_object_shared == TRUE) {
3629 vm_object_lock_shared(src_object);
3630 } else {
3631 vm_object_lock(src_object);
3632 }
3633
3634 goto Retry;
3635 }
3636
3637 /*
3638 * Determine whether the old copy object has
3639 * been modified.
3640 */
3641
3642 if (old_copy->resident_page_count == 0 &&
3643 !old_copy->pager_created) {
3644 /*
3645 * It has not been modified.
3646 *
3647 * Return another reference to
3648 * the existing copy-object if
3649 * we can safely grow it (if
3650 * needed).
3651 */
3652
3653 if (old_copy->vo_size < copy_size) {
3654 if (src_object_shared == TRUE) {
3655 vm_object_unlock(old_copy);
3656 vm_object_unlock(src_object);
3657
3658 vm_object_lock(src_object);
3659 src_object_shared = FALSE;
3660 goto Retry;
3661 }
3662 /*
3663 * We can't perform a delayed copy if any of the
3664 * pages in the extended range are wired (because
3665 * we can't safely take write permission away from
3666 * wired pages). If the pages aren't wired, then
3667 * go ahead and protect them.
3668 */
3669 copy_delayed_protect_iterate++;
3670
3671 pmap_flush_context_init(&pmap_flush_context_storage);
3672 delayed_pmap_flush = FALSE;
3673
3674 vm_page_queue_iterate(&src_object->memq, p, vmp_listq) {
3675 if (!vm_page_is_fictitious(p) &&
3676 p->vmp_offset >= old_copy->vo_size &&
3677 p->vmp_offset < copy_size) {
3678 if (VM_PAGE_WIRED(p)) {
3679 vm_object_unlock(old_copy);
3680 vm_object_unlock(src_object);
3681
3682 if (new_copy != VM_OBJECT_NULL) {
3683 vm_object_unlock(new_copy);
3684 vm_object_deallocate(new_copy);
3685 }
3686 if (delayed_pmap_flush == TRUE) {
3687 pmap_flush(&pmap_flush_context_storage);
3688 }
3689
3690 return VM_OBJECT_NULL;
3691 } else {
3692 pmap_page_protect_options(VM_PAGE_GET_PHYS_PAGE(p),
3693 (p->vmp_xpmapped ? (VM_PROT_READ | VM_PROT_EXECUTE) : VM_PROT_READ),
3694 PMAP_OPTIONS_NOFLUSH, (void *)&pmap_flush_context_storage);
3695 delayed_pmap_flush = TRUE;
3696 }
3697 }
3698 }
3699 if (delayed_pmap_flush == TRUE) {
3700 pmap_flush(&pmap_flush_context_storage);
3701 }
3702
3703 assertf(page_aligned(copy_size),
3704 "object %p size 0x%llx",
3705 old_copy, (uint64_t)copy_size);
3706 old_copy->vo_size = copy_size;
3707
3708 /*
3709 * src_object's "vo_copy" object now covers
3710 * a larger portion of src_object.
3711 * Increment src_object's "vo_copy_version"
3712 * to make any racing vm_fault() on
3713 * "src_object" re-check if it needs to honor
3714 * any new copy-on-write obligation.
3715 */
3716 src_object->vo_copy_version++;
3717 }
3718 if (src_object_shared == TRUE) {
3719 vm_object_reference_shared(old_copy);
3720 } else {
3721 vm_object_reference_locked(old_copy);
3722 }
3723 vm_object_unlock(old_copy);
3724 vm_object_unlock(src_object);
3725
3726 if (new_copy != VM_OBJECT_NULL) {
3727 vm_object_unlock(new_copy);
3728 vm_object_deallocate(new_copy);
3729 }
3730 return old_copy;
3731 }
3732
3733
3734
3735 /*
3736 * Adjust the size argument so that the newly-created
3737 * copy object will be large enough to back either the
3738 * old copy object or the new mapping.
3739 */
3740 if (old_copy->vo_size > copy_size) {
3741 copy_size = old_copy->vo_size;
3742 }
3743
3744 if (new_copy == VM_OBJECT_NULL) {
3745 vm_object_unlock(old_copy);
3746 vm_object_unlock(src_object);
3747 new_copy = vm_object_allocate(copy_size);
3748 vm_object_lock(src_object);
3749 vm_object_lock(new_copy);
3750
3751 src_object_shared = FALSE;
3752 goto Retry;
3753 }
3754 assertf(page_aligned(copy_size),
3755 "object %p size 0x%llx",
3756 new_copy, (uint64_t)copy_size);
3757 new_copy->vo_size = copy_size;
3758
3759 /*
3760 * The copy-object is always made large enough to
3761 * completely shadow the original object, since
3762 * it may have several users who want to shadow
3763 * the original object at different points.
3764 */
3765
3766 assert((old_copy->shadow == src_object) &&
3767 (old_copy->vo_shadow_offset == (vm_object_offset_t) 0));
3768 } else if (new_copy == VM_OBJECT_NULL) {
3769 vm_object_unlock(src_object);
3770 new_copy = vm_object_allocate(copy_size);
3771 vm_object_lock(src_object);
3772 vm_object_lock(new_copy);
3773
3774 src_object_shared = FALSE;
3775 goto Retry;
3776 }
3777
3778 /*
3779 * We now have the src object locked, and the new copy object
3780 * allocated and locked (and potentially the old copy locked).
3781 * Before we go any further, make sure we can still perform
3782 * a delayed copy, as the situation may have changed.
3783 *
3784 * Specifically, we can't perform a delayed copy if any of the
3785 * pages in the range are wired (because we can't safely take
3786 * write permission away from wired pages). If the pages aren't
3787 * wired, then go ahead and protect them.
3788 */
3789 copy_delayed_protect_iterate++;
3790
3791 pmap_flush_context_init(&pmap_flush_context_storage);
3792 delayed_pmap_flush = FALSE;
3793
3794 vm_page_queue_iterate(&src_object->memq, p, vmp_listq) {
3795 if (!vm_page_is_fictitious(p) && p->vmp_offset < copy_size) {
3796 if (VM_PAGE_WIRED(p)) {
3797 if (old_copy) {
3798 vm_object_unlock(old_copy);
3799 }
3800 vm_object_unlock(src_object);
3801 vm_object_unlock(new_copy);
3802 vm_object_deallocate(new_copy);
3803
3804 if (delayed_pmap_flush == TRUE) {
3805 pmap_flush(&pmap_flush_context_storage);
3806 }
3807
3808 return VM_OBJECT_NULL;
3809 } else {
3810 pmap_page_protect_options(VM_PAGE_GET_PHYS_PAGE(p),
3811 (p->vmp_xpmapped ? (VM_PROT_READ | VM_PROT_EXECUTE) : VM_PROT_READ),
3812 PMAP_OPTIONS_NOFLUSH, (void *)&pmap_flush_context_storage);
3813 delayed_pmap_flush = TRUE;
3814 }
3815 }
3816 }
3817 if (delayed_pmap_flush == TRUE) {
3818 pmap_flush(&pmap_flush_context_storage);
3819 }
3820
3821 if (old_copy != VM_OBJECT_NULL) {
3822 /*
3823 * Make the old copy-object shadow the new one.
3824 * It will receive no more pages from the original
3825 * object.
3826 */
3827
3828 /* remove ref. from old_copy */
3829 vm_object_lock_assert_exclusive(src_object);
3830 os_ref_release_live_locked_raw(&src_object->ref_count,
3831 &vm_object_refgrp);
3832 vm_object_lock_assert_exclusive(old_copy);
3833 old_copy->shadow = new_copy;
3834 vm_object_lock_assert_exclusive(new_copy);
3835 assert(os_ref_get_count_raw(&new_copy->ref_count) > 0);
3836 /* for old_copy->shadow ref. */
3837 os_ref_retain_locked_raw(&new_copy->ref_count, &vm_object_refgrp);
3838
3839 vm_object_unlock(old_copy); /* done with old_copy */
3840 }
3841
3842 /*
3843 * Point the new copy at the existing object.
3844 */
3845 vm_object_lock_assert_exclusive(new_copy);
3846 new_copy->shadow = src_object;
3847 new_copy->vo_shadow_offset = 0;
3848 VM_OBJECT_SET_SHADOWED(new_copy, TRUE); /* caller must set needs_copy */
3849
3850 vm_object_lock_assert_exclusive(src_object);
3851 vm_object_reference_locked(src_object);
3852 VM_OBJECT_COPY_SET(src_object, new_copy);
3853 vm_object_unlock(src_object);
3854 vm_object_unlock(new_copy);
3855
3856 return new_copy;
3857 }
3858
3859 /*
3860 * Routine: vm_object_copy_strategically
3861 *
3862 * Purpose:
3863 * Perform a copy according to the source object's
3864 * declared strategy. This operation may block,
3865 * and may be interrupted.
3866 */
3867 __private_extern__ kern_return_t
3868 vm_object_copy_strategically(
3869 vm_object_t src_object,
3870 vm_object_offset_t src_offset,
3871 vm_object_size_t size,
3872 bool forking,
3873 vm_object_t *dst_object, /* OUT */
3874 vm_object_offset_t *dst_offset, /* OUT */
3875 boolean_t *dst_needs_copy) /* OUT */
3876 {
3877 boolean_t result;
3878 boolean_t interruptible = THREAD_ABORTSAFE; /* XXX */
3879 boolean_t object_lock_shared = FALSE;
3880 memory_object_copy_strategy_t copy_strategy;
3881
3882 assert(src_object != VM_OBJECT_NULL);
3883
3884 copy_strategy = src_object->copy_strategy;
3885
3886 if (copy_strategy == MEMORY_OBJECT_COPY_DELAY) {
3887 vm_object_lock_shared(src_object);
3888 object_lock_shared = TRUE;
3889 } else {
3890 vm_object_lock(src_object);
3891 }
3892
3893 /*
3894 * The copy strategy is only valid if the memory manager
3895 * is "ready". Internal objects are always ready.
3896 */
3897
3898 while (!src_object->internal && !src_object->pager_ready) {
3899 wait_result_t wait_result;
3900
3901 if (object_lock_shared == TRUE) {
3902 vm_object_unlock(src_object);
3903 vm_object_lock(src_object);
3904 object_lock_shared = FALSE;
3905 continue;
3906 }
3907 wait_result = vm_object_sleep( src_object,
3908 VM_OBJECT_EVENT_PAGER_READY,
3909 interruptible, LCK_SLEEP_EXCLUSIVE);
3910 if (wait_result != THREAD_AWAKENED) {
3911 vm_object_unlock(src_object);
3912 *dst_object = VM_OBJECT_NULL;
3913 *dst_offset = 0;
3914 *dst_needs_copy = FALSE;
3915 return MACH_SEND_INTERRUPTED;
3916 }
3917 }
3918
3919 /*
3920 * Use the appropriate copy strategy.
3921 */
3922
3923 if (copy_strategy == MEMORY_OBJECT_COPY_DELAY_FORK) {
3924 if (forking) {
3925 copy_strategy = MEMORY_OBJECT_COPY_DELAY;
3926 } else {
3927 copy_strategy = MEMORY_OBJECT_COPY_NONE;
3928 if (object_lock_shared) {
3929 vm_object_unlock(src_object);
3930 vm_object_lock(src_object);
3931 object_lock_shared = FALSE;
3932 }
3933 }
3934 }
3935
3936 switch (copy_strategy) {
3937 case MEMORY_OBJECT_COPY_DELAY:
3938 *dst_object = vm_object_copy_delayed(src_object,
3939 src_offset, size, object_lock_shared);
3940 if (*dst_object != VM_OBJECT_NULL) {
3941 *dst_offset = src_offset;
3942 *dst_needs_copy = TRUE;
3943 result = KERN_SUCCESS;
3944 break;
3945 }
3946 vm_object_lock(src_object);
3947 OS_FALLTHROUGH; /* fall thru when delayed copy not allowed */
3948
3949 case MEMORY_OBJECT_COPY_NONE:
3950 result = vm_object_copy_slowly(src_object,
3951 src_offset, size,
3952 interruptible,
3953 dst_object);
3954 if (result == KERN_SUCCESS) {
3955 *dst_offset = src_offset - vm_object_trunc_page(src_offset);
3956 *dst_needs_copy = FALSE;
3957 }
3958 break;
3959
3960 case MEMORY_OBJECT_COPY_SYMMETRIC:
3961 vm_object_unlock(src_object);
3962 result = KERN_MEMORY_RESTART_COPY;
3963 break;
3964
3965 default:
3966 panic("copy_strategically: bad strategy %d for object %p",
3967 copy_strategy, src_object);
3968 result = KERN_INVALID_ARGUMENT;
3969 }
3970 return result;
3971 }
3972
3973 /*
3974 * vm_object_shadow:
3975 *
3976 * Create a new object which is backed by the
3977 * specified existing object range. The source
3978 * object reference is deallocated.
3979 *
3980 * The new object and offset into that object
3981 * are returned in the source parameters.
3982 */
3983 boolean_t vm_object_shadow_check = TRUE;
3984 uint64_t vm_object_shadow_forced = 0;
3985 uint64_t vm_object_shadow_skipped = 0;
3986
3987 __private_extern__ boolean_t
3988 vm_object_shadow(
3989 vm_object_t *object, /* IN/OUT */
3990 vm_object_offset_t *offset, /* IN/OUT */
3991 vm_object_size_t length,
3992 boolean_t always_shadow)
3993 {
3994 vm_object_t source;
3995 vm_object_t result;
3996
3997 source = *object;
3998 assert(source != VM_OBJECT_NULL);
3999 if (source == VM_OBJECT_NULL) {
4000 return FALSE;
4001 }
4002
4003 assert(source->copy_strategy == MEMORY_OBJECT_COPY_SYMMETRIC);
4004
4005 /*
4006 * Determine if we really need a shadow.
4007 *
4008 * If the source object is larger than what we are trying
4009 * to create, then force the shadow creation even if the
4010 * ref count is 1. This will allow us to [potentially]
4011 * collapse the underlying object away in the future
4012 * (freeing up the extra data it might contain and that
4013 * we don't need).
4014 */
4015
4016 assert(source->copy_strategy != MEMORY_OBJECT_COPY_NONE); /* Purgeable objects shouldn't have shadow objects. */
4017
4018 /*
4019 * The following optimization does not work in the context of submaps
4020 * (the shared region, in particular).
4021 * This object might have only 1 reference (in the submap) but that
4022 * submap can itself be mapped multiple times, so the object is
4023 * actually indirectly referenced more than once...
4024 * The caller can specify to "always_shadow" to bypass the optimization.
4025 */
4026 if (vm_object_shadow_check &&
4027 source->vo_size == length &&
4028 os_ref_get_count_raw(&source->ref_count) == 1) {
4029 if (always_shadow) {
4030 vm_object_shadow_forced++;
4031 } else {
4032 /*
4033 * Lock the object and check again.
4034 * We also check to see if there's
4035 * a shadow or copy object involved.
4036 * We can't do that earlier because
4037 * without the object locked, there
4038 * could be a collapse and the chain
4039 * gets modified leaving us with an
4040 * invalid pointer.
4041 */
4042 vm_object_lock(source);
4043 if (source->vo_size == length &&
4044 os_ref_get_count_raw(&source->ref_count) == 1 &&
4045 (source->shadow == VM_OBJECT_NULL ||
4046 source->shadow->vo_copy == VM_OBJECT_NULL)) {
4047 VM_OBJECT_SET_SHADOWED(source, FALSE);
4048 vm_object_unlock(source);
4049 vm_object_shadow_skipped++;
4050 return FALSE;
4051 }
4052 /* things changed while we were locking "source"... */
4053 vm_object_unlock(source);
4054 }
4055 }
4056
4057 /*
4058 * *offset is the map entry's offset into the VM object and
4059 * is aligned to the map's page size.
4060 * VM objects need to be aligned to the system's page size.
4061 * Record the necessary adjustment and re-align the offset so
4062 * that result->vo_shadow_offset is properly page-aligned.
4063 */
4064 vm_object_offset_t offset_adjustment;
4065 offset_adjustment = *offset - vm_object_trunc_page(*offset);
4066 length = vm_object_round_page(length + offset_adjustment);
4067 *offset = vm_object_trunc_page(*offset);
4068
4069 /*
4070 * Allocate a new object with the given length
4071 */
4072
4073 if ((result = vm_object_allocate(length)) == VM_OBJECT_NULL) {
4074 panic("vm_object_shadow: no object for shadowing");
4075 }
4076
4077 /*
4078 * The new object shadows the source object, adding
4079 * a reference to it. Our caller changes his reference
4080 * to point to the new object, removing a reference to
4081 * the source object. Net result: no change of reference
4082 * count.
4083 */
4084 result->shadow = source;
4085
4086 /*
4087 * Store the offset into the source object,
4088 * and fix up the offset into the new object.
4089 */
4090
4091 result->vo_shadow_offset = *offset;
4092 assertf(page_aligned(result->vo_shadow_offset),
4093 "result %p shadow offset 0x%llx",
4094 result, result->vo_shadow_offset);
4095
4096 /*
4097 * Return the new things
4098 */
4099
4100 *offset = 0;
4101 if (offset_adjustment) {
4102 /*
4103 * Make the map entry point to the equivalent offset
4104 * in the new object.
4105 */
4106 DEBUG4K_COPY("adjusting offset @ %p from 0x%llx to 0x%llx for object %p length: 0x%llx\n", offset, *offset, *offset + offset_adjustment, result, length);
4107 *offset += offset_adjustment;
4108 }
4109 *object = result;
4110 return TRUE;
4111 }
4112
4113 /*
4114 * The relationship between vm_object structures and
4115 * the memory_object requires careful synchronization.
4116 *
4117 * All associations are created by memory_object_create_named
4118 * for external pagers and vm_object_compressor_pager_create for internal
4119 * objects as follows:
4120 *
4121 * pager: the memory_object itself, supplied by
4122 * the user requesting a mapping (or the kernel,
4123 * when initializing internal objects); the
4124 * kernel simulates holding send rights by keeping
4125 * a port reference;
4126 *
4127 * pager_request:
4128 * the memory object control port,
4129 * created by the kernel; the kernel holds
4130 * receive (and ownership) rights to this
4131 * port, but no other references.
4132 *
4133 * When initialization is complete, the "initialized" field
4134 * is asserted. Other mappings using a particular memory object,
4135 * and any references to the vm_object gained through the
4136 * port association must wait for this initialization to occur.
4137 *
4138 * In order to allow the memory manager to set attributes before
4139 * requests (notably virtual copy operations, but also data or
4140 * unlock requests) are made, a "ready" attribute is made available.
4141 * Only the memory manager may affect the value of this attribute.
4142 * Its value does not affect critical kernel functions, such as
4143 * internal object initialization or destruction. [Furthermore,
4144 * memory objects created by the kernel are assumed to be ready
4145 * immediately; the default memory manager need not explicitly
4146 * set the "ready" attribute.]
4147 *
4148 * [Both the "initialized" and "ready" attribute wait conditions
4149 * use the "pager" field as the wait event.]
4150 *
4151 * The port associations can be broken down by any of the
4152 * following routines:
4153 * vm_object_terminate:
4154 * No references to the vm_object remain, and
4155 * the object cannot (or will not) be cached.
4156 * This is the normal case, and is done even
4157 * though one of the other cases has already been
4158 * done.
4159 * memory_object_destroy:
4160 * The memory manager has requested that the
4161 * kernel relinquish references to the memory
4162 * object. [The memory manager may not want to
4163 * destroy the memory object, but may wish to
4164 * refuse or tear down existing memory mappings.]
4165 *
4166 * Each routine that breaks an association must break all of
4167 * them at once. At some later time, that routine must clear
4168 * the pager field and release the memory object references.
4169 * [Furthermore, each routine must cope with the simultaneous
4170 * or previous operations of the others.]
4171 *
4172 * Because the pager field may be cleared spontaneously, it
4173 * cannot be used to determine whether a memory object has
4174 * ever been associated with a particular vm_object. [This
4175 * knowledge is important to the shadow object mechanism.]
4176 * For this reason, an additional "created" attribute is
4177 * provided.
4178 *
4179 * During various paging operations, the pager reference found in the
4180 * vm_object must be valid. To prevent this from being released,
4181 * (other than being removed, i.e., made null), routines may use
4182 * the vm_object_paging_begin/end routines [actually, macros].
4183 * The implementation uses the "paging_in_progress" and "wanted" fields.
4184 * [Operations that alter the validity of the pager values include the
4185 * termination routines and vm_object_collapse.]
4186 */
4187
4188
4189 /*
4190 * Routine: vm_object_memory_object_associate
4191 * Purpose:
4192 * Associate a VM object to the given pager.
4193 * If a VM object is not provided, create one.
4194 * Initialize the pager.
4195 */
4196 vm_object_t
4197 vm_object_memory_object_associate(
4198 memory_object_t pager,
4199 vm_object_t object,
4200 vm_object_size_t size,
4201 boolean_t named)
4202 {
4203 memory_object_control_t control;
4204
4205 assert(pager != MEMORY_OBJECT_NULL);
4206
4207 if (object != VM_OBJECT_NULL) {
4208 vm_object_lock(object);
4209 assert(object->internal);
4210 assert(object->pager_created);
4211 assert(!object->pager_initialized);
4212 assert(!object->pager_ready);
4213 assert(object->pager_trusted);
4214 } else {
4215 object = vm_object_allocate(size);
4216 assert(object != VM_OBJECT_NULL);
4217 vm_object_lock(object);
4218 VM_OBJECT_SET_INTERNAL(object, FALSE);
4219 VM_OBJECT_SET_PAGER_TRUSTED(object, FALSE);
4220 /* copy strategy invalid until set by memory manager */
4221 object->copy_strategy = MEMORY_OBJECT_COPY_INVALID;
4222 }
4223
4224 /*
4225 * Allocate request port.
4226 */
4227
4228 control = memory_object_control_allocate(object);
4229 assert(control != MEMORY_OBJECT_CONTROL_NULL);
4230
4231 assert(!object->pager_ready);
4232 assert(!object->pager_initialized);
4233 assert(object->pager == NULL);
4234 assert(object->pager_control == NULL);
4235
4236 /*
4237 * Copy the reference we were given.
4238 */
4239
4240 memory_object_reference(pager);
4241 VM_OBJECT_SET_PAGER_CREATED(object, TRUE);
4242 object->pager = pager;
4243 object->pager_control = control;
4244 VM_OBJECT_SET_PAGER_READY(object, FALSE);
4245
4246 vm_object_unlock(object);
4247
4248 /*
4249 * Let the pager know we're using it.
4250 */
4251
4252 (void) memory_object_init(pager,
4253 object->pager_control,
4254 PAGE_SIZE);
4255
4256 vm_object_lock(object);
4257 if (named) {
4258 VM_OBJECT_SET_NAMED(object, TRUE);
4259 }
4260 if (object->internal) {
4261 VM_OBJECT_SET_PAGER_READY(object, TRUE);
4262 vm_object_wakeup(object, VM_OBJECT_EVENT_PAGER_READY);
4263 }
4264
4265 VM_OBJECT_SET_PAGER_INITIALIZED(object, TRUE);
4266 vm_object_wakeup(object, VM_OBJECT_EVENT_PAGER_INIT);
4267
4268 vm_object_unlock(object);
4269
4270 return object;
4271 }
4272
4273 /*
4274 * Routine: vm_object_compressor_pager_create
4275 * Purpose:
4276 * Create a memory object for an internal object.
4277 * In/out conditions:
4278 * The object is locked on entry and exit;
4279 * it may be unlocked within this call.
4280 * Limitations:
4281 * Only one thread may be performing a
4282 * vm_object_compressor_pager_create on an object at
4283 * a time. Presumably, only the pageout
4284 * daemon will be using this routine.
4285 */
4286
4287 void
4288 vm_object_compressor_pager_create(
4289 vm_object_t object)
4290 {
4291 memory_object_t pager;
4292 vm_object_t pager_object = VM_OBJECT_NULL;
4293
4294 assert(!is_kernel_object(object));
4295
4296 /*
4297 * Prevent collapse or termination by holding a paging reference
4298 */
4299
4300 vm_object_paging_begin(object);
4301 if (object->pager_created) {
4302 /*
4303 * Someone else got to it first...
4304 * wait for them to finish initializing the ports
4305 */
4306 while (!object->pager_initialized) {
4307 vm_object_sleep(object,
4308 VM_OBJECT_EVENT_PAGER_INIT,
4309 THREAD_UNINT, LCK_SLEEP_EXCLUSIVE);
4310 }
4311 vm_object_paging_end(object);
4312 return;
4313 }
4314
4315 if ((uint32_t) (object->vo_size / PAGE_SIZE) !=
4316 (object->vo_size / PAGE_SIZE)) {
4317 #if DEVELOPMENT || DEBUG
4318 printf("vm_object_compressor_pager_create(%p): "
4319 "object size 0x%llx >= 0x%llx\n",
4320 object,
4321 (uint64_t) object->vo_size,
4322 0x0FFFFFFFFULL * PAGE_SIZE);
4323 #endif /* DEVELOPMENT || DEBUG */
4324 vm_object_paging_end(object);
4325 return;
4326 }
4327
4328
4329 /*
4330 * Indicate that a memory object has been assigned
4331 * before dropping the lock, to prevent a race.
4332 */
4333
4334 VM_OBJECT_SET_PAGER_CREATED(object, TRUE);
4335 VM_OBJECT_SET_PAGER_TRUSTED(object, TRUE);
4336 object->paging_offset = 0;
4337
4338 vm_object_unlock(object);
4339
4340 /*
4341 * Create the [internal] pager, and associate it with this object.
4342 *
4343 * We make the association here so that vm_object_enter()
4344 * can look up the object to complete initializing it. No
4345 * user will ever map this object.
4346 */
4347 {
4348 /* create our new memory object */
4349 assert((uint32_t) (object->vo_size / PAGE_SIZE) ==
4350 (object->vo_size / PAGE_SIZE));
4351 (void) compressor_memory_object_create(
4352 (memory_object_size_t) object->vo_size,
4353 &pager);
4354 if (pager == NULL) {
4355 panic("vm_object_compressor_pager_create(): "
4356 "no pager for object %p size 0x%llx\n",
4357 object, (uint64_t) object->vo_size);
4358 }
4359 }
4360
4361 /*
4362 * A reference was returned by
4363 * memory_object_create(), and it is
4364 * copied by vm_object_memory_object_associate().
4365 */
4366
4367 pager_object = vm_object_memory_object_associate(pager,
4368 object,
4369 object->vo_size,
4370 FALSE);
4371 if (pager_object != object) {
4372 panic("vm_object_compressor_pager_create: mismatch (pager: %p, pager_object: %p, orig_object: %p, orig_object size: 0x%llx)", pager, pager_object, object, (uint64_t) object->vo_size);
4373 }
4374
4375 /*
4376 * Drop the reference we were passed.
4377 */
4378 memory_object_deallocate(pager);
4379
4380 vm_object_lock(object);
4381
4382 /*
4383 * Release the paging reference
4384 */
4385 vm_object_paging_end(object);
4386 }
4387
4388 vm_external_state_t
4389 vm_object_compressor_pager_state_get(
4390 vm_object_t object,
4391 vm_object_offset_t offset)
4392 {
4393 if (__probable(not_in_kdp)) {
4394 vm_object_lock_assert_held(object);
4395 }
4396 if (object->internal &&
4397 object->pager != NULL &&
4398 !object->terminating &&
4399 object->alive) {
4400 return vm_compressor_pager_state_get(object->pager,
4401 offset + object->paging_offset);
4402 } else {
4403 return VM_EXTERNAL_STATE_UNKNOWN;
4404 }
4405 }
4406
4407 void
4408 vm_object_compressor_pager_state_clr(
4409 vm_object_t object,
4410 vm_object_offset_t offset)
4411 {
4412 unsigned int num_pages_cleared;
4413 vm_object_lock_assert_exclusive(object);
4414 if (object->internal &&
4415 object->pager != NULL &&
4416 !object->terminating &&
4417 object->alive) {
4418 num_pages_cleared = vm_compressor_pager_state_clr(object->pager,
4419 offset + object->paging_offset);
4420 if (num_pages_cleared) {
4421 vm_compressor_pager_count(object->pager,
4422 -num_pages_cleared,
4423 FALSE, /* shared */
4424 object);
4425 }
4426 if (num_pages_cleared &&
4427 (object->purgable != VM_PURGABLE_DENY || object->vo_ledger_tag)) {
4428 /* less compressed purgeable/tagged pages */
4429 assert3u(num_pages_cleared, ==, 1);
4430 vm_object_owner_compressed_update(object, -num_pages_cleared);
4431 }
4432 }
4433 }
4434
4435 /*
4436 * Global variables for vm_object_collapse():
4437 *
4438 * Counts for normal collapses and bypasses.
4439 * Debugging variables, to watch or disable collapse.
4440 */
4441 static long object_collapses = 0;
4442 static long object_bypasses = 0;
4443
4444 static boolean_t vm_object_collapse_allowed = TRUE;
4445 static boolean_t vm_object_bypass_allowed = TRUE;
4446
4447 void vm_object_do_collapse_compressor(vm_object_t object,
4448 vm_object_t backing_object);
4449 void
4450 vm_object_do_collapse_compressor(
4451 vm_object_t object,
4452 vm_object_t backing_object)
4453 {
4454 vm_object_offset_t new_offset, backing_offset;
4455 vm_object_size_t size;
4456
4457 vm_counters.do_collapse_compressor++;
4458
4459 vm_object_lock_assert_exclusive(object);
4460 vm_object_lock_assert_exclusive(backing_object);
4461
4462 size = object->vo_size;
4463
4464 /*
4465 * Move all compressed pages from backing_object
4466 * to the parent.
4467 */
4468
4469 for (backing_offset = object->vo_shadow_offset;
4470 backing_offset < object->vo_shadow_offset + object->vo_size;
4471 backing_offset += PAGE_SIZE) {
4472 memory_object_offset_t backing_pager_offset;
4473
4474 /* find the next compressed page at or after this offset */
4475 backing_pager_offset = (backing_offset +
4476 backing_object->paging_offset);
4477 backing_pager_offset = vm_compressor_pager_next_compressed(
4478 backing_object->pager,
4479 backing_pager_offset);
4480 if (backing_pager_offset == (memory_object_offset_t) -1) {
4481 /* no more compressed pages */
4482 break;
4483 }
4484 backing_offset = (backing_pager_offset -
4485 backing_object->paging_offset);
4486
4487 new_offset = backing_offset - object->vo_shadow_offset;
4488
4489 if (new_offset >= object->vo_size) {
4490 /* we're out of the scope of "object": done */
4491 break;
4492 }
4493
4494 if ((vm_page_lookup(object, new_offset) != VM_PAGE_NULL) ||
4495 (vm_compressor_pager_state_get(object->pager,
4496 (new_offset +
4497 object->paging_offset)) ==
4498 VM_EXTERNAL_STATE_EXISTS)) {
4499 /*
4500 * This page already exists in object, resident or
4501 * compressed.
4502 * We don't need this compressed page in backing_object
4503 * and it will be reclaimed when we release
4504 * backing_object.
4505 */
4506 continue;
4507 }
4508
4509 /*
4510 * backing_object has this page in the VM compressor and
4511 * we need to transfer it to object.
4512 */
4513 vm_counters.do_collapse_compressor_pages++;
4514 vm_compressor_pager_transfer(
4515 /* destination: */
4516 object->pager,
4517 (new_offset + object->paging_offset),
4518 /* source: */
4519 backing_object->pager,
4520 (backing_offset + backing_object->paging_offset));
4521 }
4522 }
4523
4524 /*
4525 * Routine: vm_object_do_collapse
4526 * Purpose:
4527 * Collapse an object with the object backing it.
4528 * Pages in the backing object are moved into the
4529 * parent, and the backing object is deallocated.
4530 * Conditions:
4531 * Both objects and the cache are locked; the page
4532 * queues are unlocked.
4533 *
4534 */
4535 static void
4536 vm_object_do_collapse(
4537 vm_object_t object,
4538 vm_object_t backing_object)
4539 {
4540 vm_page_t p, pp;
4541 vm_object_offset_t new_offset, backing_offset;
4542 vm_object_size_t size;
4543
4544 vm_object_lock_assert_exclusive(object);
4545 vm_object_lock_assert_exclusive(backing_object);
4546
4547 assert(object->purgable == VM_PURGABLE_DENY);
4548 assert(backing_object->purgable == VM_PURGABLE_DENY);
4549
4550 backing_offset = object->vo_shadow_offset;
4551 size = object->vo_size;
4552
4553 /*
4554 * Move all in-memory pages from backing_object
4555 * to the parent. Pages that have been paged out
4556 * will be overwritten by any of the parent's
4557 * pages that shadow them.
4558 */
4559
4560 while (!vm_page_queue_empty(&backing_object->memq)) {
4561 p = (vm_page_t) vm_page_queue_first(&backing_object->memq);
4562
4563 new_offset = (p->vmp_offset - backing_offset);
4564
4565 assert(!p->vmp_busy || p->vmp_absent);
4566
4567 /*
4568 * If the parent has a page here, or if
4569 * this page falls outside the parent,
4570 * dispose of it.
4571 *
4572 * Otherwise, move it as planned.
4573 */
4574
4575 if (p->vmp_offset < backing_offset || new_offset >= size) {
4576 VM_PAGE_FREE(p);
4577 } else {
4578 pp = vm_page_lookup(object, new_offset);
4579 if (pp == VM_PAGE_NULL) {
4580 if (vm_object_compressor_pager_state_get(object,
4581 new_offset)
4582 == VM_EXTERNAL_STATE_EXISTS) {
4583 /*
4584 * Parent object has this page
4585 * in the VM compressor.
4586 * Throw away the backing
4587 * object's page.
4588 */
4589 VM_PAGE_FREE(p);
4590 } else {
4591 /*
4592 * Parent now has no page.
4593 * Move the backing object's page
4594 * up.
4595 */
4596 vm_page_rename(p, object, new_offset);
4597 }
4598 } else {
4599 assert(!pp->vmp_absent);
4600
4601 /*
4602 * Parent object has a real page.
4603 * Throw away the backing object's
4604 * page.
4605 */
4606 VM_PAGE_FREE(p);
4607 }
4608 }
4609 }
4610
4611 if (vm_object_collapse_compressor_allowed &&
4612 object->pager != MEMORY_OBJECT_NULL &&
4613 backing_object->pager != MEMORY_OBJECT_NULL) {
4614 /* move compressed pages from backing_object to object */
4615 vm_object_do_collapse_compressor(object, backing_object);
4616 } else if (backing_object->pager != MEMORY_OBJECT_NULL) {
4617 assert((!object->pager_created &&
4618 (object->pager == MEMORY_OBJECT_NULL)) ||
4619 (!backing_object->pager_created &&
4620 (backing_object->pager == MEMORY_OBJECT_NULL)));
4621 /*
4622 * Move the pager from backing_object to object.
4623 *
4624 * XXX We're only using part of the paging space
4625 * for keeps now... we ought to discard the
4626 * unused portion.
4627 */
4628
4629 assert(!object->paging_in_progress);
4630 assert(!object->activity_in_progress);
4631 assert(!object->pager_created);
4632 assert(object->pager == NULL);
4633 object->pager = backing_object->pager;
4634
4635 VM_OBJECT_SET_PAGER_CREATED(object, backing_object->pager_created);
4636 object->pager_control = backing_object->pager_control;
4637 VM_OBJECT_SET_PAGER_READY(object, backing_object->pager_ready);
4638 VM_OBJECT_SET_PAGER_INITIALIZED(object, backing_object->pager_initialized);
4639 object->paging_offset =
4640 backing_object->paging_offset + backing_offset;
4641 if (object->pager_control != MEMORY_OBJECT_CONTROL_NULL) {
4642 memory_object_control_collapse(&object->pager_control,
4643 object);
4644 }
4645 /* the backing_object has lost its pager: reset all fields */
4646 VM_OBJECT_SET_PAGER_CREATED(backing_object, FALSE);
4647 backing_object->pager_control = NULL;
4648 VM_OBJECT_SET_PAGER_READY(backing_object, FALSE);
4649 backing_object->paging_offset = 0;
4650 backing_object->pager = NULL;
4651 }
4652 /*
4653 * Object now shadows whatever backing_object did.
4654 * Note that the reference to backing_object->shadow
4655 * moves from within backing_object to within object.
4656 */
4657
4658 assert(!object->phys_contiguous);
4659 assert(!backing_object->phys_contiguous);
4660 object->shadow = backing_object->shadow;
4661 if (object->shadow) {
4662 assertf(page_aligned(object->vo_shadow_offset),
4663 "object %p shadow_offset 0x%llx",
4664 object, object->vo_shadow_offset);
4665 assertf(page_aligned(backing_object->vo_shadow_offset),
4666 "backing_object %p shadow_offset 0x%llx",
4667 backing_object, backing_object->vo_shadow_offset);
4668 object->vo_shadow_offset += backing_object->vo_shadow_offset;
4669 /* "backing_object" gave its shadow to "object" */
4670 backing_object->shadow = VM_OBJECT_NULL;
4671 backing_object->vo_shadow_offset = 0;
4672 } else {
4673 /* no shadow, therefore no shadow offset... */
4674 object->vo_shadow_offset = 0;
4675 }
4676 assert((object->shadow == VM_OBJECT_NULL) ||
4677 (object->shadow->vo_copy != backing_object));
4678
4679 /*
4680 * Discard backing_object.
4681 *
4682 * Since the backing object has no pages, no
4683 * pager left, and no object references within it,
4684 * all that is necessary is to dispose of it.
4685 */
4686 object_collapses++;
4687
4688 assert(os_ref_get_count_raw(&backing_object->ref_count) == 1);
4689 assert(backing_object->resident_page_count == 0);
4690 assert(backing_object->paging_in_progress == 0);
4691 assert(backing_object->activity_in_progress == 0);
4692 assert(backing_object->shadow == VM_OBJECT_NULL);
4693 assert(backing_object->vo_shadow_offset == 0);
4694
4695 if (backing_object->pager != MEMORY_OBJECT_NULL) {
4696 /* ... unless it has a pager; need to terminate pager too */
4697 vm_counters.do_collapse_terminate++;
4698 if (vm_object_terminate(backing_object) != KERN_SUCCESS) {
4699 vm_counters.do_collapse_terminate_failure++;
4700 }
4701 return;
4702 }
4703
4704 assert(backing_object->pager == NULL);
4705
4706 VM_OBJECT_SET_ALIVE(backing_object, FALSE);
4707 vm_object_unlock(backing_object);
4708
4709 #if VM_OBJECT_TRACKING
4710 if (vm_object_tracking_btlog) {
4711 btlog_erase(vm_object_tracking_btlog, backing_object);
4712 }
4713 #endif /* VM_OBJECT_TRACKING */
4714
4715 vm_object_lock_destroy(backing_object);
4716
4717 zfree(vm_object_zone, backing_object);
4718 }
4719
4720 static void
4721 vm_object_do_bypass(
4722 vm_object_t object,
4723 vm_object_t backing_object)
4724 {
4725 /*
4726 * Make the parent shadow the next object
4727 * in the chain.
4728 */
4729
4730 vm_object_lock_assert_exclusive(object);
4731 vm_object_lock_assert_exclusive(backing_object);
4732
4733 vm_object_reference(backing_object->shadow);
4734
4735 assert(!object->phys_contiguous);
4736 assert(!backing_object->phys_contiguous);
4737 object->shadow = backing_object->shadow;
4738 if (object->shadow) {
4739 assertf(page_aligned(object->vo_shadow_offset),
4740 "object %p shadow_offset 0x%llx",
4741 object, object->vo_shadow_offset);
4742 assertf(page_aligned(backing_object->vo_shadow_offset),
4743 "backing_object %p shadow_offset 0x%llx",
4744 backing_object, backing_object->vo_shadow_offset);
4745 object->vo_shadow_offset += backing_object->vo_shadow_offset;
4746 } else {
4747 /* no shadow, therefore no shadow offset... */
4748 object->vo_shadow_offset = 0;
4749 }
4750
4751 /*
4752 * Backing object might have had a copy pointer
4753 * to us. If it did, clear it.
4754 */
4755 if (backing_object->vo_copy == object) {
4756 VM_OBJECT_COPY_SET(backing_object, VM_OBJECT_NULL);
4757 }
4758
4759 /*
4760 * Drop the reference count on backing_object.
4761 #if TASK_SWAPPER
4762 * Since its ref_count was at least 2, it
4763 * will not vanish; so we don't need to call
4764 * vm_object_deallocate.
4765 * [with a caveat for "named" objects]
4766 *
4767 * The res_count on the backing object is
4768 * conditionally decremented. It's possible
4769 * (via vm_pageout_scan) to get here with
4770 * a "swapped" object, which has a 0 res_count,
4771 * in which case, the backing object res_count
4772 * is already down by one.
4773 #else
4774 * Don't call vm_object_deallocate unless
4775 * ref_count drops to zero.
4776 *
4777 * The ref_count can drop to zero here if the
4778 * backing object could be bypassed but not
4779 * collapsed, such as when the backing object
4780 * is temporary and cachable.
4781 #endif
4782 */
4783 if (os_ref_get_count_raw(&backing_object->ref_count) > 2 ||
4784 (!backing_object->named &&
4785 os_ref_get_count_raw(&backing_object->ref_count) > 1)) {
4786 vm_object_lock_assert_exclusive(backing_object);
4787 os_ref_release_live_locked_raw(&backing_object->ref_count,
4788 &vm_object_refgrp);
4789 vm_object_unlock(backing_object);
4790 } else {
4791 /*
4792 * Drop locks so that we can deallocate
4793 * the backing object.
4794 */
4795
4796 /*
4797 * vm_object_collapse (the caller of this function) is
4798 * now called from contexts that may not guarantee that a
4799 * valid reference is held on the object... w/o a valid
4800 * reference, it is unsafe and unwise (you will definitely
4801 * regret it) to unlock the object and then retake the lock
4802 * since the object may be terminated and recycled in between.
4803 * The "activity_in_progress" reference will keep the object
4804 * 'stable'.
4805 */
4806 vm_object_activity_begin(object);
4807 vm_object_unlock(object);
4808
4809 vm_object_unlock(backing_object);
4810 vm_object_deallocate(backing_object);
4811
4812 /*
4813 * Relock object. We don't have to reverify
4814 * its state since vm_object_collapse will
4815 * do that for us as it starts at the
4816 * top of its loop.
4817 */
4818
4819 vm_object_lock(object);
4820 vm_object_activity_end(object);
4821 }
4822
4823 object_bypasses++;
4824 }
4825
4826
4827 /*
4828 * vm_object_collapse:
4829 *
4830 * Perform an object collapse or an object bypass if appropriate.
4831 * The real work of collapsing and bypassing is performed in
4832 * the routines vm_object_do_collapse and vm_object_do_bypass.
4833 *
4834 * Requires that the object be locked and the page queues be unlocked.
4835 *
4836 */
4837 static unsigned long vm_object_collapse_calls = 0;
4838 static unsigned long vm_object_collapse_objects = 0;
4839 static unsigned long vm_object_collapse_do_collapse = 0;
4840 static unsigned long vm_object_collapse_do_bypass = 0;
4841
4842 __private_extern__ void
4843 vm_object_collapse(
4844 vm_object_t object,
4845 vm_object_offset_t hint_offset,
4846 boolean_t can_bypass)
4847 {
4848 vm_object_t backing_object;
4849 vm_object_size_t object_vcount, object_rcount;
4850 vm_object_t original_object;
4851 int object_lock_type;
4852 int backing_object_lock_type;
4853
4854 vm_object_collapse_calls++;
4855
4856 assertf(page_aligned(hint_offset), "hint_offset 0x%llx", hint_offset);
4857
4858 if (!vm_object_collapse_allowed &&
4859 !(can_bypass && vm_object_bypass_allowed)) {
4860 return;
4861 }
4862
4863 if (object == VM_OBJECT_NULL) {
4864 return;
4865 }
4866
4867 original_object = object;
4868
4869 /*
4870 * The top object was locked "exclusive" by the caller.
4871 * In the first pass, to determine if we can collapse the shadow chain,
4872 * take a "shared" lock on the shadow objects. If we can collapse,
4873 * we'll have to go down the chain again with exclusive locks.
4874 */
4875 object_lock_type = OBJECT_LOCK_EXCLUSIVE;
4876 backing_object_lock_type = OBJECT_LOCK_SHARED;
4877
4878 retry:
4879 object = original_object;
4880 vm_object_lock_assert_exclusive(object);
4881
4882 while (TRUE) {
4883 vm_object_collapse_objects++;
4884 /*
4885 * Verify that the conditions are right for either
4886 * collapse or bypass:
4887 */
4888
4889 /*
4890 * There is a backing object, and
4891 */
4892
4893 backing_object = object->shadow;
4894 if (backing_object == VM_OBJECT_NULL) {
4895 if (object != original_object) {
4896 vm_object_unlock(object);
4897 }
4898 return;
4899 }
4900 if (backing_object_lock_type == OBJECT_LOCK_SHARED) {
4901 vm_object_lock_shared(backing_object);
4902 } else {
4903 vm_object_lock(backing_object);
4904 }
4905
4906 /*
4907 * No pages in the object are currently
4908 * being paged out, and
4909 */
4910 if (object->paging_in_progress != 0 ||
4911 object->activity_in_progress != 0) {
4912 /* try and collapse the rest of the shadow chain */
4913 if (object != original_object) {
4914 vm_object_unlock(object);
4915 }
4916 object = backing_object;
4917 object_lock_type = backing_object_lock_type;
4918 continue;
4919 }
4920
4921 /*
4922 * ...
4923 * The backing object is not read_only,
4924 * and no pages in the backing object are
4925 * currently being paged out.
4926 * The backing object is internal.
4927 *
4928 */
4929
4930 if (!backing_object->internal ||
4931 backing_object->paging_in_progress != 0 ||
4932 backing_object->activity_in_progress != 0) {
4933 /* try and collapse the rest of the shadow chain */
4934 if (object != original_object) {
4935 vm_object_unlock(object);
4936 }
4937 object = backing_object;
4938 object_lock_type = backing_object_lock_type;
4939 continue;
4940 }
4941
4942 /*
4943 * Purgeable objects are not supposed to engage in
4944 * copy-on-write activities, so should not have
4945 * any shadow objects or be a shadow object to another
4946 * object.
4947 * Collapsing a purgeable object would require some
4948 * updates to the purgeable compressed ledgers.
4949 */
4950 if (object->purgable != VM_PURGABLE_DENY ||
4951 backing_object->purgable != VM_PURGABLE_DENY) {
4952 panic("vm_object_collapse() attempting to collapse "
4953 "purgeable object: %p(%d) %p(%d)\n",
4954 object, object->purgable,
4955 backing_object, backing_object->purgable);
4956 /* try and collapse the rest of the shadow chain */
4957 if (object != original_object) {
4958 vm_object_unlock(object);
4959 }
4960 object = backing_object;
4961 object_lock_type = backing_object_lock_type;
4962 continue;
4963 }
4964
4965 /*
4966 * The backing object can't be a copy-object:
4967 * the shadow_offset for the copy-object must stay
4968 * as 0. Furthermore (for the 'we have all the
4969 * pages' case), if we bypass backing_object and
4970 * just shadow the next object in the chain, old
4971 * pages from that object would then have to be copied
4972 * BOTH into the (former) backing_object and into the
4973 * parent object.
4974 */
4975 if (backing_object->shadow != VM_OBJECT_NULL &&
4976 backing_object->shadow->vo_copy == backing_object) {
4977 /* try and collapse the rest of the shadow chain */
4978 if (object != original_object) {
4979 vm_object_unlock(object);
4980 }
4981 object = backing_object;
4982 object_lock_type = backing_object_lock_type;
4983 continue;
4984 }
4985
4986 /*
4987 * We can now try to either collapse the backing
4988 * object (if the parent is the only reference to
4989 * it) or (perhaps) remove the parent's reference
4990 * to it.
4991 *
4992 * If there is exactly one reference to the backing
4993 * object, we may be able to collapse it into the
4994 * parent.
4995 *
4996 * As long as one of the objects is still not known
4997 * to the pager, we can collapse them.
4998 */
4999 if (os_ref_get_count_raw(&backing_object->ref_count) == 1 &&
5000 (vm_object_collapse_compressor_allowed ||
5001 !object->pager_created
5002 || (!backing_object->pager_created)
5003 ) && vm_object_collapse_allowed) {
5004 /*
5005 * We need the exclusive lock on the VM objects.
5006 */
5007 if (backing_object_lock_type != OBJECT_LOCK_EXCLUSIVE) {
5008 /*
5009 * We have an object and its shadow locked
5010 * "shared". We can't just upgrade the locks
5011 * to "exclusive", as some other thread might
5012 * also have these objects locked "shared" and
5013 * attempt to upgrade one or the other to
5014 * "exclusive". The upgrades would block
5015 * forever waiting for the other "shared" locks
5016 * to get released.
5017 * So we have to release the locks and go
5018 * down the shadow chain again (since it could
5019 * have changed) with "exclusive" locking.
5020 */
5021 vm_object_unlock(backing_object);
5022 if (object != original_object) {
5023 vm_object_unlock(object);
5024 }
5025 object_lock_type = OBJECT_LOCK_EXCLUSIVE;
5026 backing_object_lock_type = OBJECT_LOCK_EXCLUSIVE;
5027 goto retry;
5028 }
5029
5030 /*
5031 * Collapse the object with its backing
5032 * object, and try again with the object's
5033 * new backing object.
5034 */
5035
5036 vm_object_do_collapse(object, backing_object);
5037 vm_object_collapse_do_collapse++;
5038 continue;
5039 }
5040
5041 /*
5042 * Collapsing the backing object was not possible
5043 * or permitted, so let's try bypassing it.
5044 */
5045
5046 if (!(can_bypass && vm_object_bypass_allowed)) {
5047 /* try and collapse the rest of the shadow chain */
5048 if (object != original_object) {
5049 vm_object_unlock(object);
5050 }
5051 object = backing_object;
5052 object_lock_type = backing_object_lock_type;
5053 continue;
5054 }
5055
5056
5057 /*
5058 * If the object doesn't have all its pages present,
5059 * we have to make sure no pages in the backing object
5060 * "show through" before bypassing it.
5061 */
5062 object_vcount = object->vo_size >> PAGE_SHIFT;
5063 object_rcount = (vm_object_size_t)object->resident_page_count;
5064
5065 if (object_rcount != object_vcount) {
5066 vm_object_offset_t offset;
5067 vm_object_offset_t backing_offset;
5068 vm_object_size_t backing_rcount, backing_vcount;
5069
5070 /*
5071 * If the backing object has a pager but no pagemap,
5072 * then we cannot bypass it, because we don't know
5073 * what pages it has.
5074 */
5075 if (backing_object->pager_created) {
5076 /* try and collapse the rest of the shadow chain */
5077 if (object != original_object) {
5078 vm_object_unlock(object);
5079 }
5080 object = backing_object;
5081 object_lock_type = backing_object_lock_type;
5082 continue;
5083 }
5084
5085 /*
5086 * If the object has a pager but no pagemap,
5087 * then we cannot bypass it, because we don't know
5088 * what pages it has.
5089 */
5090 if (object->pager_created) {
5091 /* try and collapse the rest of the shadow chain */
5092 if (object != original_object) {
5093 vm_object_unlock(object);
5094 }
5095 object = backing_object;
5096 object_lock_type = backing_object_lock_type;
5097 continue;
5098 }
5099
5100 backing_offset = object->vo_shadow_offset;
5101 backing_vcount = backing_object->vo_size >> PAGE_SHIFT;
5102 backing_rcount = (vm_object_size_t)backing_object->resident_page_count;
5103 assert(backing_vcount >= object_vcount);
5104
5105 if (backing_rcount > (backing_vcount - object_vcount) &&
5106 backing_rcount - (backing_vcount - object_vcount) > object_rcount) {
5107 /*
5108 * we have enough pages in the backing object to guarantee that
5109 * at least 1 of them must be 'uncovered' by a resident page
5110 * in the object we're evaluating, so move on and
5111 * try to collapse the rest of the shadow chain
5112 */
5113 if (object != original_object) {
5114 vm_object_unlock(object);
5115 }
5116 object = backing_object;
5117 object_lock_type = backing_object_lock_type;
5118 continue;
5119 }
5120
5121 /*
5122 * If all of the pages in the backing object are
5123 * shadowed by the parent object, the parent
5124 * object no longer has to shadow the backing
5125 * object; it can shadow the next one in the
5126 * chain.
5127 *
5128 * If the backing object has existence info,
5129 * we must check examine its existence info
5130 * as well.
5131 *
5132 */
5133
5134 #define EXISTS_IN_OBJECT(obj, off, rc) \
5135 ((vm_object_compressor_pager_state_get((obj), (off)) \
5136 == VM_EXTERNAL_STATE_EXISTS) || \
5137 ((rc) && vm_page_lookup((obj), (off)) != VM_PAGE_NULL && (rc)--))
5138
5139 /*
5140 * Check the hint location first
5141 * (since it is often the quickest way out of here).
5142 */
5143 if (object->cow_hint != ~(vm_offset_t)0) {
5144 hint_offset = (vm_object_offset_t)object->cow_hint;
5145 } else {
5146 hint_offset = (hint_offset > 8 * PAGE_SIZE_64) ?
5147 (hint_offset - 8 * PAGE_SIZE_64) : 0;
5148 }
5149
5150 if (EXISTS_IN_OBJECT(backing_object, hint_offset +
5151 backing_offset, backing_rcount) &&
5152 !EXISTS_IN_OBJECT(object, hint_offset, object_rcount)) {
5153 /* dependency right at the hint */
5154 object->cow_hint = (vm_offset_t) hint_offset; /* atomic */
5155 /* try and collapse the rest of the shadow chain */
5156 if (object != original_object) {
5157 vm_object_unlock(object);
5158 }
5159 object = backing_object;
5160 object_lock_type = backing_object_lock_type;
5161 continue;
5162 }
5163
5164 /*
5165 * If the object's window onto the backing_object
5166 * is large compared to the number of resident
5167 * pages in the backing object, it makes sense to
5168 * walk the backing_object's resident pages first.
5169 *
5170 * NOTE: Pages may be in both the existence map and/or
5171 * resident, so if we don't find a dependency while
5172 * walking the backing object's resident page list
5173 * directly, and there is an existence map, we'll have
5174 * to run the offset based 2nd pass. Because we may
5175 * have to run both passes, we need to be careful
5176 * not to decrement 'rcount' in the 1st pass
5177 */
5178 if (backing_rcount && backing_rcount < (object_vcount / 8)) {
5179 vm_object_size_t rc = object_rcount;
5180 vm_page_t p;
5181
5182 backing_rcount = backing_object->resident_page_count;
5183 p = (vm_page_t)vm_page_queue_first(&backing_object->memq);
5184 do {
5185 offset = (p->vmp_offset - backing_offset);
5186
5187 if (offset < object->vo_size &&
5188 offset != hint_offset &&
5189 !EXISTS_IN_OBJECT(object, offset, rc)) {
5190 /* found a dependency */
5191 object->cow_hint = (vm_offset_t) offset; /* atomic */
5192
5193 break;
5194 }
5195 p = (vm_page_t) vm_page_queue_next(&p->vmp_listq);
5196 } while (--backing_rcount);
5197 if (backing_rcount != 0) {
5198 /* try and collapse the rest of the shadow chain */
5199 if (object != original_object) {
5200 vm_object_unlock(object);
5201 }
5202 object = backing_object;
5203 object_lock_type = backing_object_lock_type;
5204 continue;
5205 }
5206 }
5207
5208 /*
5209 * Walk through the offsets looking for pages in the
5210 * backing object that show through to the object.
5211 */
5212 if (backing_rcount) {
5213 offset = hint_offset;
5214
5215 while ((offset =
5216 (offset + PAGE_SIZE_64 < object->vo_size) ?
5217 (offset + PAGE_SIZE_64) : 0) != hint_offset) {
5218 if (EXISTS_IN_OBJECT(backing_object, offset +
5219 backing_offset, backing_rcount) &&
5220 !EXISTS_IN_OBJECT(object, offset, object_rcount)) {
5221 /* found a dependency */
5222 object->cow_hint = (vm_offset_t) offset; /* atomic */
5223 break;
5224 }
5225 }
5226 if (offset != hint_offset) {
5227 /* try and collapse the rest of the shadow chain */
5228 if (object != original_object) {
5229 vm_object_unlock(object);
5230 }
5231 object = backing_object;
5232 object_lock_type = backing_object_lock_type;
5233 continue;
5234 }
5235 }
5236 }
5237
5238 /*
5239 * We need "exclusive" locks on the 2 VM objects.
5240 */
5241 if (backing_object_lock_type != OBJECT_LOCK_EXCLUSIVE) {
5242 vm_object_unlock(backing_object);
5243 if (object != original_object) {
5244 vm_object_unlock(object);
5245 }
5246 object_lock_type = OBJECT_LOCK_EXCLUSIVE;
5247 backing_object_lock_type = OBJECT_LOCK_EXCLUSIVE;
5248 goto retry;
5249 }
5250
5251 /* reset the offset hint for any objects deeper in the chain */
5252 object->cow_hint = (vm_offset_t)0;
5253
5254 /*
5255 * All interesting pages in the backing object
5256 * already live in the parent or its pager.
5257 * Thus we can bypass the backing object.
5258 */
5259
5260 vm_object_do_bypass(object, backing_object);
5261 vm_object_collapse_do_bypass++;
5262
5263 /*
5264 * Try again with this object's new backing object.
5265 */
5266
5267 continue;
5268 }
5269
5270 /* NOT REACHED */
5271 /*
5272 * if (object != original_object) {
5273 * vm_object_unlock(object);
5274 * }
5275 */
5276 }
5277
5278 /*
5279 * Routine: vm_object_page_remove: [internal]
5280 * Purpose:
5281 * Removes all physical pages in the specified
5282 * object range from the object's list of pages.
5283 *
5284 * In/out conditions:
5285 * The object must be locked.
5286 * The object must not have paging_in_progress, usually
5287 * guaranteed by not having a pager.
5288 */
5289 unsigned int vm_object_page_remove_lookup = 0;
5290 unsigned int vm_object_page_remove_iterate = 0;
5291
5292 __private_extern__ void
5293 vm_object_page_remove(
5294 vm_object_t object,
5295 vm_object_offset_t start,
5296 vm_object_offset_t end)
5297 {
5298 vm_page_t p, next;
5299
5300 /*
5301 * One and two page removals are most popular.
5302 * The factor of 16 here is somewhat arbitrary.
5303 * It balances vm_object_lookup vs iteration.
5304 */
5305
5306 if (atop_64(end - start) < (unsigned)object->resident_page_count / 16) {
5307 vm_object_page_remove_lookup++;
5308
5309 for (; start < end; start += PAGE_SIZE_64) {
5310 p = vm_page_lookup(object, start);
5311 if (p != VM_PAGE_NULL) {
5312 assert(!p->vmp_cleaning && !p->vmp_laundry);
5313 if (!vm_page_is_fictitious(p) && p->vmp_pmapped) {
5314 pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(p));
5315 }
5316 VM_PAGE_FREE(p);
5317 }
5318 }
5319 } else {
5320 vm_object_page_remove_iterate++;
5321
5322 p = (vm_page_t) vm_page_queue_first(&object->memq);
5323 while (!vm_page_queue_end(&object->memq, (vm_page_queue_entry_t) p)) {
5324 next = (vm_page_t) vm_page_queue_next(&p->vmp_listq);
5325 if ((start <= p->vmp_offset) && (p->vmp_offset < end)) {
5326 assert(!p->vmp_cleaning && !p->vmp_laundry);
5327 if (!vm_page_is_fictitious(p) && p->vmp_pmapped) {
5328 pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(p));
5329 }
5330 VM_PAGE_FREE(p);
5331 }
5332 p = next;
5333 }
5334 }
5335 }
5336
5337
5338 /*
5339 * Routine: vm_object_coalesce
5340 * Function: Coalesces two objects backing up adjoining
5341 * regions of memory into a single object.
5342 *
5343 * returns TRUE if objects were combined.
5344 *
5345 * NOTE: Only works at the moment if the second object is NULL -
5346 * if it's not, which object do we lock first?
5347 *
5348 * Parameters:
5349 * prev_object First object to coalesce
5350 * prev_offset Offset into prev_object
5351 * next_object Second object into coalesce
5352 * next_offset Offset into next_object
5353 *
5354 * prev_size Size of reference to prev_object
5355 * next_size Size of reference to next_object
5356 *
5357 * Conditions:
5358 * The object(s) must *not* be locked. The map must be locked
5359 * to preserve the reference to the object(s).
5360 */
5361 static int vm_object_coalesce_count = 0;
5362
5363 __private_extern__ boolean_t
5364 vm_object_coalesce(
5365 vm_object_t prev_object,
5366 vm_object_t next_object,
5367 vm_object_offset_t prev_offset,
5368 __unused vm_object_offset_t next_offset,
5369 vm_object_size_t prev_size,
5370 vm_object_size_t next_size)
5371 {
5372 vm_object_size_t newsize;
5373
5374 #ifdef lint
5375 next_offset++;
5376 #endif /* lint */
5377
5378 if (next_object != VM_OBJECT_NULL) {
5379 return FALSE;
5380 }
5381
5382 if (prev_object == VM_OBJECT_NULL) {
5383 return TRUE;
5384 }
5385
5386 vm_object_lock(prev_object);
5387
5388 /*
5389 * Try to collapse the object first
5390 */
5391 vm_object_collapse(prev_object, prev_offset, TRUE);
5392
5393 /*
5394 * Can't coalesce if pages not mapped to
5395 * prev_entry may be in use any way:
5396 * . more than one reference
5397 * . paged out
5398 * . shadows another object
5399 * . has a copy elsewhere
5400 * . is purgeable
5401 * . paging references (pages might be in page-list)
5402 */
5403
5404 if ((os_ref_get_count_raw(&prev_object->ref_count) > 1) ||
5405 prev_object->pager_created ||
5406 prev_object->phys_contiguous ||
5407 (prev_object->shadow != VM_OBJECT_NULL) ||
5408 (prev_object->vo_copy != VM_OBJECT_NULL) ||
5409 (prev_object->true_share != FALSE) ||
5410 (prev_object->purgable != VM_PURGABLE_DENY) ||
5411 (prev_object->paging_in_progress != 0) ||
5412 (prev_object->activity_in_progress != 0)) {
5413 vm_object_unlock(prev_object);
5414 return FALSE;
5415 }
5416 /* newsize = prev_offset + prev_size + next_size; */
5417 if (__improbable(os_add3_overflow(prev_offset, prev_size, next_size,
5418 &newsize))) {
5419 vm_object_unlock(prev_object);
5420 return FALSE;
5421 }
5422
5423 vm_object_coalesce_count++;
5424
5425 /*
5426 * Remove any pages that may still be in the object from
5427 * a previous deallocation.
5428 */
5429 vm_object_page_remove(prev_object,
5430 prev_offset + prev_size,
5431 prev_offset + prev_size + next_size);
5432
5433 /*
5434 * Extend the object if necessary.
5435 */
5436 if (newsize > prev_object->vo_size) {
5437 assertf(page_aligned(newsize),
5438 "object %p size 0x%llx",
5439 prev_object, (uint64_t)newsize);
5440 prev_object->vo_size = newsize;
5441 }
5442
5443 vm_object_unlock(prev_object);
5444 return TRUE;
5445 }
5446
5447 kern_return_t
5448 vm_object_populate_with_private(
5449 vm_object_t object,
5450 vm_object_offset_t offset,
5451 ppnum_t phys_page,
5452 vm_size_t size)
5453 {
5454 ppnum_t base_page;
5455 vm_object_offset_t base_offset;
5456
5457
5458 if (!object->private) {
5459 return KERN_FAILURE;
5460 }
5461
5462 base_page = phys_page;
5463
5464 vm_object_lock(object);
5465
5466 if (!object->phys_contiguous) {
5467 vm_page_t m;
5468
5469 if ((base_offset = trunc_page_64(offset)) != offset) {
5470 vm_object_unlock(object);
5471 return KERN_FAILURE;
5472 }
5473 base_offset += object->paging_offset;
5474
5475 while (size) {
5476 m = vm_page_lookup(object, base_offset);
5477
5478 if (m != VM_PAGE_NULL) {
5479 ppnum_t m_phys_page = VM_PAGE_GET_PHYS_PAGE(m);
5480
5481 if (m_phys_page == vm_page_guard_addr) {
5482 /* nothing to do */
5483 } else if (m_phys_page == vm_page_fictitious_addr) {
5484 vm_page_lockspin_queues();
5485 vm_page_make_private(m, base_page);
5486 vm_page_unlock_queues();
5487 } else if (m_phys_page != base_page) {
5488 if (!vm_page_is_private(m)) {
5489 /*
5490 * we'd leak a real page... that can't be right
5491 */
5492 panic("vm_object_populate_with_private - %p not private", m);
5493 }
5494 if (m->vmp_pmapped) {
5495 /*
5496 * pmap call to clear old mapping
5497 */
5498 pmap_disconnect(m_phys_page);
5499 }
5500 VM_PAGE_SET_PHYS_PAGE(m, base_page);
5501 }
5502 } else {
5503 m = vm_page_create_private(base_page);
5504
5505 m->vmp_unusual = TRUE;
5506 m->vmp_busy = FALSE;
5507
5508 vm_page_insert(m, object, base_offset);
5509 }
5510 base_page++; /* Go to the next physical page */
5511 base_offset += PAGE_SIZE;
5512 size -= PAGE_SIZE;
5513 }
5514 } else {
5515 /* NOTE: we should check the original settings here */
5516 /* if we have a size > zero a pmap call should be made */
5517 /* to disable the range */
5518
5519 /* pmap_? */
5520
5521 /* shadows on contiguous memory are not allowed */
5522 /* we therefore can use the offset field */
5523 object->vo_shadow_offset = (vm_object_offset_t)phys_page << PAGE_SHIFT;
5524 assertf(page_aligned(size),
5525 "object %p size 0x%llx",
5526 object, (uint64_t)size);
5527 object->vo_size = size;
5528 }
5529 vm_object_unlock(object);
5530
5531 return KERN_SUCCESS;
5532 }
5533
5534
5535 kern_return_t
5536 memory_object_create_named(
5537 memory_object_t pager,
5538 memory_object_offset_t size,
5539 memory_object_control_t *control)
5540 {
5541 vm_object_t object;
5542
5543 *control = MEMORY_OBJECT_CONTROL_NULL;
5544 if (pager == MEMORY_OBJECT_NULL) {
5545 return KERN_INVALID_ARGUMENT;
5546 }
5547
5548 object = vm_object_memory_object_associate(pager,
5549 VM_OBJECT_NULL,
5550 size,
5551 TRUE);
5552 if (object == VM_OBJECT_NULL) {
5553 return KERN_INVALID_OBJECT;
5554 }
5555
5556 /* wait for object (if any) to be ready */
5557 if (object != VM_OBJECT_NULL) {
5558 vm_object_lock(object);
5559 VM_OBJECT_SET_NAMED(object, TRUE);
5560 while (!object->pager_ready) {
5561 vm_object_sleep(object,
5562 VM_OBJECT_EVENT_PAGER_READY,
5563 THREAD_UNINT, LCK_SLEEP_EXCLUSIVE);
5564 }
5565 *control = object->pager_control;
5566 vm_object_unlock(object);
5567 }
5568 return KERN_SUCCESS;
5569 }
5570
5571
5572 __private_extern__ kern_return_t
5573 vm_object_lock_request(
5574 vm_object_t object,
5575 vm_object_offset_t offset,
5576 vm_object_size_t size,
5577 memory_object_return_t should_return,
5578 int flags,
5579 vm_prot_t prot)
5580 {
5581 __unused boolean_t should_flush;
5582
5583 should_flush = flags & MEMORY_OBJECT_DATA_FLUSH;
5584
5585 /*
5586 * Check for bogus arguments.
5587 */
5588 if (object == VM_OBJECT_NULL) {
5589 return KERN_INVALID_ARGUMENT;
5590 }
5591
5592 if ((prot & ~VM_PROT_ALL) != 0 && prot != VM_PROT_NO_CHANGE) {
5593 return KERN_INVALID_ARGUMENT;
5594 }
5595
5596 /*
5597 * XXX TODO4K
5598 * extend range for conservative operations (copy-on-write, sync, ...)
5599 * truncate range for destructive operations (purge, ...)
5600 */
5601 size = vm_object_round_page(offset + size) - vm_object_trunc_page(offset);
5602 offset = vm_object_trunc_page(offset);
5603
5604 /*
5605 * Lock the object, and acquire a paging reference to
5606 * prevent the memory_object reference from being released.
5607 */
5608 vm_object_lock(object);
5609 vm_object_paging_begin(object);
5610
5611 (void)vm_object_update(object,
5612 offset, size, NULL, NULL, should_return, flags, prot);
5613
5614 vm_object_paging_end(object);
5615 vm_object_unlock(object);
5616
5617 return KERN_SUCCESS;
5618 }
5619
5620 /*
5621 * Empty a purgeable object by grabbing the physical pages assigned to it and
5622 * putting them on the free queue without writing them to backing store, etc.
5623 * When the pages are next touched they will be demand zero-fill pages. We
5624 * skip pages which are busy, being paged in/out, wired, etc. We do _not_
5625 * skip referenced/dirty pages, pages on the active queue, etc. We're more
5626 * than happy to grab these since this is a purgeable object. We mark the
5627 * object as "empty" after reaping its pages.
5628 *
5629 * On entry the object must be locked and it must be
5630 * purgeable with no delayed copies pending.
5631 */
5632 uint64_t
5633 vm_object_purge(vm_object_t object, int flags)
5634 {
5635 unsigned int object_page_count = 0, pgcount = 0;
5636 uint64_t total_purged_pgcount = 0;
5637 boolean_t skipped_object = FALSE;
5638
5639 vm_object_lock_assert_exclusive(object);
5640
5641 if (object->purgable == VM_PURGABLE_DENY) {
5642 return 0;
5643 }
5644
5645 assert(object->vo_copy == VM_OBJECT_NULL);
5646 assert(object->copy_strategy == MEMORY_OBJECT_COPY_NONE);
5647
5648 /*
5649 * We need to set the object's state to VM_PURGABLE_EMPTY *before*
5650 * reaping its pages. We update vm_page_purgeable_count in bulk
5651 * and we don't want vm_page_remove() to update it again for each
5652 * page we reap later.
5653 *
5654 * For the purgeable ledgers, pages from VOLATILE and EMPTY objects
5655 * are all accounted for in the "volatile" ledgers, so this does not
5656 * make any difference.
5657 * If we transitioned directly from NONVOLATILE to EMPTY,
5658 * vm_page_purgeable_count must have been updated when the object
5659 * was dequeued from its volatile queue and the purgeable ledgers
5660 * must have also been updated accordingly at that time (in
5661 * vm_object_purgable_control()).
5662 */
5663 if (object->purgable == VM_PURGABLE_VOLATILE) {
5664 unsigned int delta;
5665 assert(object->resident_page_count >=
5666 object->wired_page_count);
5667 delta = (object->resident_page_count -
5668 object->wired_page_count);
5669 if (delta != 0) {
5670 assert(vm_page_purgeable_count >=
5671 delta);
5672 OSAddAtomic(-delta,
5673 (SInt32 *)&vm_page_purgeable_count);
5674 }
5675 if (object->wired_page_count != 0) {
5676 assert(vm_page_purgeable_wired_count >=
5677 object->wired_page_count);
5678 OSAddAtomic(-object->wired_page_count,
5679 (SInt32 *)&vm_page_purgeable_wired_count);
5680 }
5681 VM_OBJECT_SET_PURGABLE(object, VM_PURGABLE_EMPTY);
5682 }
5683 assert(object->purgable == VM_PURGABLE_EMPTY);
5684
5685 object_page_count = object->resident_page_count;
5686
5687 vm_object_reap_pages(object, REAP_PURGEABLE);
5688
5689 if (object->resident_page_count >= object_page_count) {
5690 total_purged_pgcount = 0;
5691 } else {
5692 total_purged_pgcount = object_page_count - object->resident_page_count;
5693 }
5694
5695 if (object->pager != NULL) {
5696 assert(VM_CONFIG_COMPRESSOR_IS_PRESENT);
5697
5698 if (object->activity_in_progress == 0 &&
5699 object->paging_in_progress == 0) {
5700 /*
5701 * Also reap any memory coming from this object
5702 * in the VM compressor.
5703 *
5704 * There are no operations in progress on the VM object
5705 * and no operation can start while we're holding the
5706 * VM object lock, so it's safe to reap the compressed
5707 * pages and update the page counts.
5708 */
5709 pgcount = vm_compressor_pager_get_count(object->pager);
5710 if (pgcount) {
5711 pgcount = vm_compressor_pager_reap_pages(object->pager, flags);
5712 vm_compressor_pager_count(object->pager,
5713 -pgcount,
5714 FALSE, /* shared */
5715 object);
5716 vm_object_owner_compressed_update(object,
5717 -pgcount);
5718 }
5719 if (!(flags & C_DONT_BLOCK)) {
5720 assert(vm_compressor_pager_get_count(object->pager)
5721 == 0);
5722 }
5723 } else {
5724 /*
5725 * There's some kind of paging activity in progress
5726 * for this object, which could result in a page
5727 * being compressed or decompressed, possibly while
5728 * the VM object is not locked, so it could race
5729 * with us.
5730 *
5731 * We can't really synchronize this without possibly
5732 * causing a deadlock when the compressor needs to
5733 * allocate or free memory while compressing or
5734 * decompressing a page from a purgeable object
5735 * mapped in the kernel_map...
5736 *
5737 * So let's not attempt to purge the compressor
5738 * pager if there's any kind of operation in
5739 * progress on the VM object.
5740 */
5741 skipped_object = TRUE;
5742 }
5743 }
5744
5745 vm_object_lock_assert_exclusive(object);
5746
5747 total_purged_pgcount += pgcount;
5748
5749 KDBG_RELEASE(VMDBG_CODE(DBG_VM_PURGEABLE_OBJECT_PURGE_ONE) | DBG_FUNC_NONE,
5750 VM_KERNEL_UNSLIDE_OR_PERM(object), /* purged object */
5751 object_page_count,
5752 total_purged_pgcount,
5753 skipped_object);
5754
5755 return total_purged_pgcount;
5756 }
5757
5758
5759 /*
5760 * vm_object_purgeable_control() allows the caller to control and investigate the
5761 * state of a purgeable object. A purgeable object is created via a call to
5762 * vm_allocate() with VM_FLAGS_PURGABLE specified. A purgeable object will
5763 * never be coalesced with any other object -- even other purgeable objects --
5764 * and will thus always remain a distinct object. A purgeable object has
5765 * special semantics when its reference count is exactly 1. If its reference
5766 * count is greater than 1, then a purgeable object will behave like a normal
5767 * object and attempts to use this interface will result in an error return
5768 * of KERN_INVALID_ARGUMENT.
5769 *
5770 * A purgeable object may be put into a "volatile" state which will make the
5771 * object's pages elligable for being reclaimed without paging to backing
5772 * store if the system runs low on memory. If the pages in a volatile
5773 * purgeable object are reclaimed, the purgeable object is said to have been
5774 * "emptied." When a purgeable object is emptied the system will reclaim as
5775 * many pages from the object as it can in a convenient manner (pages already
5776 * en route to backing store or busy for other reasons are left as is). When
5777 * a purgeable object is made volatile, its pages will generally be reclaimed
5778 * before other pages in the application's working set. This semantic is
5779 * generally used by applications which can recreate the data in the object
5780 * faster than it can be paged in. One such example might be media assets
5781 * which can be reread from a much faster RAID volume.
5782 *
5783 * A purgeable object may be designated as "non-volatile" which means it will
5784 * behave like all other objects in the system with pages being written to and
5785 * read from backing store as needed to satisfy system memory needs. If the
5786 * object was emptied before the object was made non-volatile, that fact will
5787 * be returned as the old state of the purgeable object (see
5788 * VM_PURGABLE_SET_STATE below). In this case, any pages of the object which
5789 * were reclaimed as part of emptying the object will be refaulted in as
5790 * zero-fill on demand. It is up to the application to note that an object
5791 * was emptied and recreate the objects contents if necessary. When a
5792 * purgeable object is made non-volatile, its pages will generally not be paged
5793 * out to backing store in the immediate future. A purgeable object may also
5794 * be manually emptied.
5795 *
5796 * Finally, the current state (non-volatile, volatile, volatile & empty) of a
5797 * volatile purgeable object may be queried at any time. This information may
5798 * be used as a control input to let the application know when the system is
5799 * experiencing memory pressure and is reclaiming memory.
5800 *
5801 * The specified address may be any address within the purgeable object. If
5802 * the specified address does not represent any object in the target task's
5803 * virtual address space, then KERN_INVALID_ADDRESS will be returned. If the
5804 * object containing the specified address is not a purgeable object, then
5805 * KERN_INVALID_ARGUMENT will be returned. Otherwise, KERN_SUCCESS will be
5806 * returned.
5807 *
5808 * The control parameter may be any one of VM_PURGABLE_SET_STATE or
5809 * VM_PURGABLE_GET_STATE. For VM_PURGABLE_SET_STATE, the in/out parameter
5810 * state is used to set the new state of the purgeable object and return its
5811 * old state. For VM_PURGABLE_GET_STATE, the current state of the purgeable
5812 * object is returned in the parameter state.
5813 *
5814 * The in/out parameter state may be one of VM_PURGABLE_NONVOLATILE,
5815 * VM_PURGABLE_VOLATILE or VM_PURGABLE_EMPTY. These, respectively, represent
5816 * the non-volatile, volatile and volatile/empty states described above.
5817 * Setting the state of a purgeable object to VM_PURGABLE_EMPTY will
5818 * immediately reclaim as many pages in the object as can be conveniently
5819 * collected (some may have already been written to backing store or be
5820 * otherwise busy).
5821 *
5822 * The process of making a purgeable object non-volatile and determining its
5823 * previous state is atomic. Thus, if a purgeable object is made
5824 * VM_PURGABLE_NONVOLATILE and the old state is returned as
5825 * VM_PURGABLE_VOLATILE, then the purgeable object's previous contents are
5826 * completely intact and will remain so until the object is made volatile
5827 * again. If the old state is returned as VM_PURGABLE_EMPTY then the object
5828 * was reclaimed while it was in a volatile state and its previous contents
5829 * have been lost.
5830 */
5831 /*
5832 * The object must be locked.
5833 */
5834 kern_return_t
5835 vm_object_purgable_control(
5836 vm_object_t object,
5837 vm_purgable_t control,
5838 int *state)
5839 {
5840 int old_state;
5841 int new_state;
5842
5843 if (object == VM_OBJECT_NULL) {
5844 /*
5845 * Object must already be present or it can't be purgeable.
5846 */
5847 return KERN_INVALID_ARGUMENT;
5848 }
5849
5850 vm_object_lock_assert_exclusive(object);
5851
5852 /*
5853 * Get current state of the purgeable object.
5854 */
5855 old_state = object->purgable;
5856 if (old_state == VM_PURGABLE_DENY) {
5857 return KERN_INVALID_ARGUMENT;
5858 }
5859
5860 /* purgeable cant have delayed copies - now or in the future */
5861 assert(object->vo_copy == VM_OBJECT_NULL);
5862 assert(object->copy_strategy == MEMORY_OBJECT_COPY_NONE);
5863
5864 /*
5865 * Execute the desired operation.
5866 */
5867 if (control == VM_PURGABLE_GET_STATE) {
5868 *state = old_state;
5869 return KERN_SUCCESS;
5870 }
5871
5872 if (control == VM_PURGABLE_SET_STATE &&
5873 object->purgeable_only_by_kernel) {
5874 return KERN_PROTECTION_FAILURE;
5875 }
5876
5877 if (control != VM_PURGABLE_SET_STATE &&
5878 control != VM_PURGABLE_SET_STATE_FROM_KERNEL) {
5879 return KERN_INVALID_ARGUMENT;
5880 }
5881
5882 if ((*state) & VM_PURGABLE_DEBUG_EMPTY) {
5883 object->volatile_empty = TRUE;
5884 }
5885 if ((*state) & VM_PURGABLE_DEBUG_FAULT) {
5886 object->volatile_fault = TRUE;
5887 }
5888
5889 new_state = *state & VM_PURGABLE_STATE_MASK;
5890 if (new_state == VM_PURGABLE_VOLATILE) {
5891 if (old_state == VM_PURGABLE_EMPTY) {
5892 /* what's been emptied must stay empty */
5893 new_state = VM_PURGABLE_EMPTY;
5894 }
5895 if (object->volatile_empty) {
5896 /* debugging mode: go straight to empty */
5897 new_state = VM_PURGABLE_EMPTY;
5898 }
5899 }
5900
5901 switch (new_state) {
5902 case VM_PURGABLE_DENY:
5903 /*
5904 * Attempting to convert purgeable memory to non-purgeable:
5905 * not allowed.
5906 */
5907 return KERN_INVALID_ARGUMENT;
5908 case VM_PURGABLE_NONVOLATILE:
5909 VM_OBJECT_SET_PURGABLE(object, new_state);
5910
5911 if (old_state == VM_PURGABLE_VOLATILE) {
5912 unsigned int delta;
5913
5914 assert(object->resident_page_count >=
5915 object->wired_page_count);
5916 delta = (object->resident_page_count -
5917 object->wired_page_count);
5918
5919 assert(vm_page_purgeable_count >= delta);
5920
5921 if (delta != 0) {
5922 OSAddAtomic(-delta,
5923 (SInt32 *)&vm_page_purgeable_count);
5924 }
5925 if (object->wired_page_count != 0) {
5926 assert(vm_page_purgeable_wired_count >=
5927 object->wired_page_count);
5928 OSAddAtomic(-object->wired_page_count,
5929 (SInt32 *)&vm_page_purgeable_wired_count);
5930 }
5931
5932 vm_page_lock_queues();
5933
5934 /* object should be on a queue */
5935 assert(object->objq.next != NULL &&
5936 object->objq.prev != NULL);
5937 purgeable_q_t queue;
5938
5939 /*
5940 * Move object from its volatile queue to the
5941 * non-volatile queue...
5942 */
5943 queue = vm_purgeable_object_remove(object);
5944 assert(queue);
5945
5946 if (object->purgeable_when_ripe) {
5947 vm_purgeable_token_delete_last(queue);
5948 }
5949 assert(queue->debug_count_objects >= 0);
5950
5951 vm_page_unlock_queues();
5952 }
5953 if (old_state == VM_PURGABLE_VOLATILE ||
5954 old_state == VM_PURGABLE_EMPTY) {
5955 /*
5956 * Transfer the object's pages from the volatile to
5957 * non-volatile ledgers.
5958 */
5959 vm_purgeable_accounting(object, VM_PURGABLE_VOLATILE);
5960 }
5961
5962 break;
5963
5964 case VM_PURGABLE_VOLATILE:
5965 if (object->volatile_fault) {
5966 vm_page_t p;
5967 int refmod;
5968
5969 vm_page_queue_iterate(&object->memq, p, vmp_listq) {
5970 if (p->vmp_busy ||
5971 VM_PAGE_WIRED(p) ||
5972 vm_page_is_fictitious(p)) {
5973 continue;
5974 }
5975 refmod = pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(p));
5976 if ((refmod & VM_MEM_MODIFIED) &&
5977 !p->vmp_dirty) {
5978 SET_PAGE_DIRTY(p, FALSE);
5979 }
5980 }
5981 }
5982
5983 assert(old_state != VM_PURGABLE_EMPTY);
5984
5985 purgeable_q_t queue;
5986
5987 /* find the correct queue */
5988 if ((*state & VM_PURGABLE_ORDERING_MASK) == VM_PURGABLE_ORDERING_OBSOLETE) {
5989 queue = &purgeable_queues[PURGEABLE_Q_TYPE_OBSOLETE];
5990 } else {
5991 if ((*state & VM_PURGABLE_BEHAVIOR_MASK) == VM_PURGABLE_BEHAVIOR_FIFO) {
5992 queue = &purgeable_queues[PURGEABLE_Q_TYPE_FIFO];
5993 } else {
5994 queue = &purgeable_queues[PURGEABLE_Q_TYPE_LIFO];
5995 }
5996 }
5997
5998 if (old_state == VM_PURGABLE_NONVOLATILE ||
5999 old_state == VM_PURGABLE_EMPTY) {
6000 unsigned int delta;
6001
6002 if ((*state & VM_PURGABLE_NO_AGING_MASK) ==
6003 VM_PURGABLE_NO_AGING) {
6004 VM_OBJECT_SET_PURGEABLE_WHEN_RIPE(object, FALSE);
6005 } else {
6006 VM_OBJECT_SET_PURGEABLE_WHEN_RIPE(object, TRUE);
6007 }
6008
6009 if (object->purgeable_when_ripe) {
6010 kern_return_t result;
6011
6012 /* try to add token... this can fail */
6013 vm_page_lock_queues();
6014
6015 result = vm_purgeable_token_add(queue);
6016 if (result != KERN_SUCCESS) {
6017 vm_page_unlock_queues();
6018 return result;
6019 }
6020 vm_page_unlock_queues();
6021 }
6022
6023 assert(object->resident_page_count >=
6024 object->wired_page_count);
6025 delta = (object->resident_page_count -
6026 object->wired_page_count);
6027
6028 if (delta != 0) {
6029 OSAddAtomic(delta,
6030 &vm_page_purgeable_count);
6031 }
6032 if (object->wired_page_count != 0) {
6033 OSAddAtomic(object->wired_page_count,
6034 &vm_page_purgeable_wired_count);
6035 }
6036
6037 VM_OBJECT_SET_PURGABLE(object, new_state);
6038
6039 /* object should be on "non-volatile" queue */
6040 assert(object->objq.next != NULL);
6041 assert(object->objq.prev != NULL);
6042 } else if (old_state == VM_PURGABLE_VOLATILE) {
6043 purgeable_q_t old_queue;
6044 boolean_t purgeable_when_ripe;
6045
6046 /*
6047 * if reassigning priorities / purgeable groups, we don't change the
6048 * token queue. So moving priorities will not make pages stay around longer.
6049 * Reasoning is that the algorithm gives most priority to the most important
6050 * object. If a new token is added, the most important object' priority is boosted.
6051 * This biases the system already for purgeable queues that move a lot.
6052 * It doesn't seem more biasing is neccessary in this case, where no new object is added.
6053 */
6054 assert(object->objq.next != NULL && object->objq.prev != NULL); /* object should be on a queue */
6055
6056 old_queue = vm_purgeable_object_remove(object);
6057 assert(old_queue);
6058
6059 if ((*state & VM_PURGABLE_NO_AGING_MASK) ==
6060 VM_PURGABLE_NO_AGING) {
6061 purgeable_when_ripe = FALSE;
6062 } else {
6063 purgeable_when_ripe = TRUE;
6064 }
6065
6066 if (old_queue != queue ||
6067 (purgeable_when_ripe !=
6068 object->purgeable_when_ripe)) {
6069 kern_return_t result;
6070
6071 /* Changing queue. Have to move token. */
6072 vm_page_lock_queues();
6073 if (object->purgeable_when_ripe) {
6074 vm_purgeable_token_delete_last(old_queue);
6075 }
6076 VM_OBJECT_SET_PURGEABLE_WHEN_RIPE(object, purgeable_when_ripe);
6077 if (object->purgeable_when_ripe) {
6078 result = vm_purgeable_token_add(queue);
6079 assert(result == KERN_SUCCESS); /* this should never fail since we just freed a token */
6080 }
6081 vm_page_unlock_queues();
6082 }
6083 }
6084 ;
6085 vm_purgeable_object_add(object, queue, (*state & VM_VOLATILE_GROUP_MASK) >> VM_VOLATILE_GROUP_SHIFT );
6086 if (old_state == VM_PURGABLE_NONVOLATILE) {
6087 vm_purgeable_accounting(object,
6088 VM_PURGABLE_NONVOLATILE);
6089 }
6090
6091 assert(queue->debug_count_objects >= 0);
6092
6093 break;
6094
6095
6096 case VM_PURGABLE_EMPTY:
6097 if (object->volatile_fault) {
6098 vm_page_t p;
6099 int refmod;
6100
6101 vm_page_queue_iterate(&object->memq, p, vmp_listq) {
6102 if (p->vmp_busy ||
6103 VM_PAGE_WIRED(p) ||
6104 vm_page_is_fictitious(p)) {
6105 continue;
6106 }
6107 refmod = pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(p));
6108 if ((refmod & VM_MEM_MODIFIED) &&
6109 !p->vmp_dirty) {
6110 SET_PAGE_DIRTY(p, FALSE);
6111 }
6112 }
6113 }
6114
6115 if (old_state == VM_PURGABLE_VOLATILE) {
6116 purgeable_q_t old_queue;
6117
6118 /* object should be on a queue */
6119 assert(object->objq.next != NULL &&
6120 object->objq.prev != NULL);
6121
6122 old_queue = vm_purgeable_object_remove(object);
6123 assert(old_queue);
6124 if (object->purgeable_when_ripe) {
6125 vm_page_lock_queues();
6126 vm_purgeable_token_delete_first(old_queue);
6127 vm_page_unlock_queues();
6128 }
6129 }
6130
6131 if (old_state == VM_PURGABLE_NONVOLATILE) {
6132 /*
6133 * This object's pages were previously accounted as
6134 * "non-volatile" and now need to be accounted as
6135 * "volatile".
6136 */
6137 vm_purgeable_accounting(object,
6138 VM_PURGABLE_NONVOLATILE);
6139 /*
6140 * Set to VM_PURGABLE_EMPTY because the pages are no
6141 * longer accounted in the "non-volatile" ledger
6142 * and are also not accounted for in
6143 * "vm_page_purgeable_count".
6144 */
6145 VM_OBJECT_SET_PURGABLE(object, VM_PURGABLE_EMPTY);
6146 }
6147
6148 (void) vm_object_purge(object, 0);
6149 assert(object->purgable == VM_PURGABLE_EMPTY);
6150
6151 break;
6152 }
6153
6154 *state = old_state;
6155
6156 vm_object_lock_assert_exclusive(object);
6157
6158 return KERN_SUCCESS;
6159 }
6160
6161 kern_return_t
6162 vm_object_get_page_counts(
6163 vm_object_t object,
6164 vm_object_offset_t offset,
6165 vm_object_size_t size,
6166 unsigned int *resident_page_count,
6167 unsigned int *dirty_page_count)
6168 {
6169 kern_return_t kr = KERN_SUCCESS;
6170 boolean_t count_dirty_pages = FALSE;
6171 vm_page_t p = VM_PAGE_NULL;
6172 unsigned int local_resident_count = 0;
6173 unsigned int local_dirty_count = 0;
6174 vm_object_offset_t cur_offset = 0;
6175 vm_object_offset_t end_offset = 0;
6176
6177 if (object == VM_OBJECT_NULL) {
6178 return KERN_INVALID_ARGUMENT;
6179 }
6180
6181
6182 cur_offset = offset;
6183
6184 end_offset = offset + size;
6185
6186 vm_object_lock_assert_exclusive(object);
6187
6188 if (dirty_page_count != NULL) {
6189 count_dirty_pages = TRUE;
6190 }
6191
6192 if (resident_page_count != NULL && count_dirty_pages == FALSE) {
6193 /*
6194 * Fast path when:
6195 * - we only want the resident page count, and,
6196 * - the entire object is exactly covered by the request.
6197 */
6198 if (offset == 0 && (object->vo_size == size)) {
6199 *resident_page_count = object->resident_page_count;
6200 goto out;
6201 }
6202 }
6203
6204 if (object->resident_page_count <= (size >> PAGE_SHIFT)) {
6205 vm_page_queue_iterate(&object->memq, p, vmp_listq) {
6206 if (p->vmp_offset >= cur_offset && p->vmp_offset < end_offset) {
6207 local_resident_count++;
6208
6209 if (count_dirty_pages) {
6210 if (p->vmp_dirty || (p->vmp_wpmapped && pmap_is_modified(VM_PAGE_GET_PHYS_PAGE(p)))) {
6211 local_dirty_count++;
6212 }
6213 }
6214 }
6215 }
6216 } else {
6217 for (cur_offset = offset; cur_offset < end_offset; cur_offset += PAGE_SIZE_64) {
6218 p = vm_page_lookup(object, cur_offset);
6219
6220 if (p != VM_PAGE_NULL) {
6221 local_resident_count++;
6222
6223 if (count_dirty_pages) {
6224 if (p->vmp_dirty || (p->vmp_wpmapped && pmap_is_modified(VM_PAGE_GET_PHYS_PAGE(p)))) {
6225 local_dirty_count++;
6226 }
6227 }
6228 }
6229 }
6230 }
6231
6232 if (resident_page_count != NULL) {
6233 *resident_page_count = local_resident_count;
6234 }
6235
6236 if (dirty_page_count != NULL) {
6237 *dirty_page_count = local_dirty_count;
6238 }
6239
6240 out:
6241 return kr;
6242 }
6243
6244
6245 /*
6246 * vm_object_reference:
6247 *
6248 * Gets another reference to the given object.
6249 */
6250 #ifdef vm_object_reference
6251 #undef vm_object_reference
6252 #endif
6253 __private_extern__ void
6254 vm_object_reference(
6255 vm_object_t object)
6256 {
6257 if (object == VM_OBJECT_NULL) {
6258 return;
6259 }
6260
6261 vm_object_lock(object);
6262 vm_object_reference_locked(object);
6263 vm_object_unlock(object);
6264 }
6265
6266 /*
6267 * vm_object_transpose
6268 *
6269 * This routine takes two VM objects of the same size and exchanges
6270 * their backing store.
6271 * The objects should be "quiesced" via a UPL operation with UPL_SET_IO_WIRE
6272 * and UPL_BLOCK_ACCESS if they are referenced anywhere.
6273 *
6274 * The VM objects must not be locked by caller.
6275 */
6276 unsigned int vm_object_transpose_count = 0;
6277 kern_return_t
6278 vm_object_transpose(
6279 vm_object_t object1,
6280 vm_object_t object2,
6281 vm_object_size_t transpose_size)
6282 {
6283 vm_object_t tmp_object;
6284 kern_return_t retval;
6285 boolean_t object1_locked, object2_locked;
6286 vm_page_t page;
6287 vm_object_offset_t page_offset;
6288
6289 tmp_object = VM_OBJECT_NULL;
6290 object1_locked = FALSE; object2_locked = FALSE;
6291
6292 if (object1 == object2 ||
6293 object1 == VM_OBJECT_NULL ||
6294 object2 == VM_OBJECT_NULL) {
6295 /*
6296 * If the 2 VM objects are the same, there's
6297 * no point in exchanging their backing store.
6298 */
6299 retval = KERN_INVALID_VALUE;
6300 goto done;
6301 }
6302
6303 /*
6304 * Since we need to lock both objects at the same time,
6305 * make sure we always lock them in the same order to
6306 * avoid deadlocks.
6307 */
6308 if (object1 > object2) {
6309 tmp_object = object1;
6310 object1 = object2;
6311 object2 = tmp_object;
6312 }
6313
6314 /*
6315 * Allocate a temporary VM object to hold object1's contents
6316 * while we copy object2 to object1.
6317 */
6318 tmp_object = vm_object_allocate(transpose_size);
6319 vm_object_lock(tmp_object);
6320 VM_OBJECT_SET_CAN_PERSIST(tmp_object, FALSE);
6321
6322
6323 /*
6324 * Grab control of the 1st VM object.
6325 */
6326 vm_object_lock(object1);
6327 object1_locked = TRUE;
6328 if (!object1->alive || object1->terminating ||
6329 object1->vo_copy || object1->shadow || object1->shadowed ||
6330 object1->purgable != VM_PURGABLE_DENY) {
6331 /*
6332 * We don't deal with copy or shadow objects (yet).
6333 */
6334 retval = KERN_INVALID_VALUE;
6335 goto done;
6336 }
6337 /*
6338 * We're about to mess with the object's backing store and
6339 * taking a "paging_in_progress" reference wouldn't be enough
6340 * to prevent any paging activity on this object, so the caller should
6341 * have "quiesced" the objects beforehand, via a UPL operation with
6342 * UPL_SET_IO_WIRE (to make sure all the pages are there and wired)
6343 * and UPL_BLOCK_ACCESS (to mark the pages "busy").
6344 *
6345 * Wait for any paging operation to complete (but only paging, not
6346 * other kind of activities not linked to the pager). After we're
6347 * statisfied that there's no more paging in progress, we keep the
6348 * object locked, to guarantee that no one tries to access its pager.
6349 */
6350 vm_object_paging_only_wait(object1, THREAD_UNINT);
6351
6352 /*
6353 * Same as above for the 2nd object...
6354 */
6355 vm_object_lock(object2);
6356 object2_locked = TRUE;
6357 if (!object2->alive || object2->terminating ||
6358 object2->vo_copy || object2->shadow || object2->shadowed ||
6359 object2->purgable != VM_PURGABLE_DENY) {
6360 retval = KERN_INVALID_VALUE;
6361 goto done;
6362 }
6363 vm_object_paging_only_wait(object2, THREAD_UNINT);
6364
6365
6366 if (object1->vo_size != object2->vo_size ||
6367 object1->vo_size != transpose_size) {
6368 /*
6369 * If the 2 objects don't have the same size, we can't
6370 * exchange their backing stores or one would overflow.
6371 * If their size doesn't match the caller's
6372 * "transpose_size", we can't do it either because the
6373 * transpose operation will affect the entire span of
6374 * the objects.
6375 */
6376 retval = KERN_INVALID_VALUE;
6377 goto done;
6378 }
6379
6380
6381 /*
6382 * Transpose the lists of resident pages.
6383 * This also updates the resident_page_count and the memq_hint.
6384 */
6385 if (object1->phys_contiguous || vm_page_queue_empty(&object1->memq)) {
6386 /*
6387 * No pages in object1, just transfer pages
6388 * from object2 to object1. No need to go through
6389 * an intermediate object.
6390 */
6391 while (!vm_page_queue_empty(&object2->memq)) {
6392 page = (vm_page_t) vm_page_queue_first(&object2->memq);
6393 vm_page_rename(page, object1, page->vmp_offset);
6394 }
6395 assert(vm_page_queue_empty(&object2->memq));
6396 } else if (object2->phys_contiguous || vm_page_queue_empty(&object2->memq)) {
6397 /*
6398 * No pages in object2, just transfer pages
6399 * from object1 to object2. No need to go through
6400 * an intermediate object.
6401 */
6402 while (!vm_page_queue_empty(&object1->memq)) {
6403 page = (vm_page_t) vm_page_queue_first(&object1->memq);
6404 vm_page_rename(page, object2, page->vmp_offset);
6405 }
6406 assert(vm_page_queue_empty(&object1->memq));
6407 } else {
6408 /* transfer object1's pages to tmp_object */
6409 while (!vm_page_queue_empty(&object1->memq)) {
6410 page = (vm_page_t) vm_page_queue_first(&object1->memq);
6411 page_offset = page->vmp_offset;
6412 vm_page_remove(page, TRUE);
6413 page->vmp_offset = page_offset;
6414 vm_page_queue_enter(&tmp_object->memq, page, vmp_listq);
6415 }
6416 assert(vm_page_queue_empty(&object1->memq));
6417 /* transfer object2's pages to object1 */
6418 while (!vm_page_queue_empty(&object2->memq)) {
6419 page = (vm_page_t) vm_page_queue_first(&object2->memq);
6420 vm_page_rename(page, object1, page->vmp_offset);
6421 }
6422 assert(vm_page_queue_empty(&object2->memq));
6423 /* transfer tmp_object's pages to object2 */
6424 while (!vm_page_queue_empty(&tmp_object->memq)) {
6425 page = (vm_page_t) vm_page_queue_first(&tmp_object->memq);
6426 vm_page_queue_remove(&tmp_object->memq, page, vmp_listq);
6427 vm_page_insert(page, object2, page->vmp_offset);
6428 }
6429 assert(vm_page_queue_empty(&tmp_object->memq));
6430 }
6431
6432 #define __TRANSPOSE_FIELD(field) \
6433 MACRO_BEGIN \
6434 tmp_object->field = object1->field; \
6435 object1->field = object2->field; \
6436 object2->field = tmp_object->field; \
6437 MACRO_END
6438
6439 /* "Lock" refers to the object not its contents */
6440 /* "size" should be identical */
6441 assert(object1->vo_size == object2->vo_size);
6442 /* "memq_hint" was updated above when transposing pages */
6443 /* "ref_count" refers to the object not its contents */
6444 assert(os_ref_get_count_raw(&object1->ref_count) >= 1);
6445 assert(os_ref_get_count_raw(&object2->ref_count) >= 1);
6446 /* "resident_page_count" was updated above when transposing pages */
6447 /* "wired_page_count" was updated above when transposing pages */
6448 #if !VM_TAG_ACTIVE_UPDATE
6449 /* "wired_objq" was dealt with along with "wired_page_count" */
6450 #endif /* ! VM_TAG_ACTIVE_UPDATE */
6451 /* "reusable_page_count" was updated above when transposing pages */
6452 /* there should be no "copy" */
6453 assert(!object1->vo_copy);
6454 assert(!object2->vo_copy);
6455 /* there should be no "shadow" */
6456 assert(!object1->shadow);
6457 assert(!object2->shadow);
6458 __TRANSPOSE_FIELD(vo_shadow_offset); /* used by phys_contiguous objects */
6459 __TRANSPOSE_FIELD(pager);
6460 __TRANSPOSE_FIELD(paging_offset);
6461 __TRANSPOSE_FIELD(pager_control);
6462 /* update the memory_objects' pointers back to the VM objects */
6463 if (object1->pager_control != MEMORY_OBJECT_CONTROL_NULL) {
6464 memory_object_control_collapse(&object1->pager_control,
6465 object1);
6466 }
6467 if (object2->pager_control != MEMORY_OBJECT_CONTROL_NULL) {
6468 memory_object_control_collapse(&object2->pager_control,
6469 object2);
6470 }
6471 __TRANSPOSE_FIELD(copy_strategy);
6472 /* "paging_in_progress" refers to the object not its contents */
6473 assert(!object1->paging_in_progress);
6474 assert(!object2->paging_in_progress);
6475 assert(object1->activity_in_progress);
6476 assert(object2->activity_in_progress);
6477 /* "all_wanted" refers to the object not its contents */
6478 __TRANSPOSE_FIELD(pager_created);
6479 __TRANSPOSE_FIELD(pager_initialized);
6480 __TRANSPOSE_FIELD(pager_ready);
6481 __TRANSPOSE_FIELD(pager_trusted);
6482 __TRANSPOSE_FIELD(can_persist);
6483 __TRANSPOSE_FIELD(internal);
6484 __TRANSPOSE_FIELD(private);
6485 __TRANSPOSE_FIELD(pageout);
6486 /* "alive" should be set */
6487 assert(object1->alive);
6488 assert(object2->alive);
6489 /* "purgeable" should be non-purgeable */
6490 assert(object1->purgable == VM_PURGABLE_DENY);
6491 assert(object2->purgable == VM_PURGABLE_DENY);
6492 /* "shadowed" refers to the the object not its contents */
6493 __TRANSPOSE_FIELD(purgeable_when_ripe);
6494 __TRANSPOSE_FIELD(true_share);
6495 /* "terminating" should not be set */
6496 assert(!object1->terminating);
6497 assert(!object2->terminating);
6498 /* transfer "named" reference if needed */
6499 if (object1->named && !object2->named) {
6500 os_ref_release_live_locked_raw(&object1->ref_count, &vm_object_refgrp);
6501 os_ref_retain_locked_raw(&object2->ref_count, &vm_object_refgrp);
6502 } else if (!object1->named && object2->named) {
6503 os_ref_retain_locked_raw(&object1->ref_count, &vm_object_refgrp);
6504 os_ref_release_live_locked_raw(&object2->ref_count, &vm_object_refgrp);
6505 }
6506 __TRANSPOSE_FIELD(named);
6507 /* "shadow_severed" refers to the object not its contents */
6508 __TRANSPOSE_FIELD(phys_contiguous);
6509 __TRANSPOSE_FIELD(nophyscache);
6510 __TRANSPOSE_FIELD(no_pager_reason);
6511 /* "cached_list.next" points to transposed object */
6512 object1->cached_list.next = (queue_entry_t) object2;
6513 object2->cached_list.next = (queue_entry_t) object1;
6514 /* "cached_list.prev" should be NULL */
6515 assert(object1->cached_list.prev == NULL);
6516 assert(object2->cached_list.prev == NULL);
6517 __TRANSPOSE_FIELD(last_alloc);
6518 __TRANSPOSE_FIELD(sequential);
6519 __TRANSPOSE_FIELD(pages_created);
6520 __TRANSPOSE_FIELD(pages_used);
6521 __TRANSPOSE_FIELD(scan_collisions);
6522 __TRANSPOSE_FIELD(cow_hint);
6523 __TRANSPOSE_FIELD(wimg_bits);
6524 __TRANSPOSE_FIELD(set_cache_attr);
6525 __TRANSPOSE_FIELD(code_signed);
6526 object1->transposed = TRUE;
6527 object2->transposed = TRUE;
6528 __TRANSPOSE_FIELD(mapping_in_progress);
6529 __TRANSPOSE_FIELD(volatile_empty);
6530 __TRANSPOSE_FIELD(volatile_fault);
6531 __TRANSPOSE_FIELD(all_reusable);
6532 assert(object1->blocked_access);
6533 assert(object2->blocked_access);
6534 __TRANSPOSE_FIELD(set_cache_attr);
6535 assert(!object1->object_is_shared_cache);
6536 assert(!object2->object_is_shared_cache);
6537 /* ignore purgeable_queue_type and purgeable_queue_group */
6538 assert(!object1->io_tracking);
6539 assert(!object2->io_tracking);
6540 #if VM_OBJECT_ACCESS_TRACKING
6541 assert(!object1->access_tracking);
6542 assert(!object2->access_tracking);
6543 #endif /* VM_OBJECT_ACCESS_TRACKING */
6544 __TRANSPOSE_FIELD(no_tag_update);
6545 #if CONFIG_SECLUDED_MEMORY
6546 assert(!object1->eligible_for_secluded);
6547 assert(!object2->eligible_for_secluded);
6548 assert(!object1->can_grab_secluded);
6549 assert(!object2->can_grab_secluded);
6550 #else /* CONFIG_SECLUDED_MEMORY */
6551 assert(object1->__object3_unused_bits == 0);
6552 assert(object2->__object3_unused_bits == 0);
6553 #endif /* CONFIG_SECLUDED_MEMORY */
6554 #if UPL_DEBUG
6555 /* "uplq" refers to the object not its contents (see upl_transpose()) */
6556 #endif
6557 assert((object1->purgable == VM_PURGABLE_DENY) || (object1->objq.next == NULL));
6558 assert((object1->purgable == VM_PURGABLE_DENY) || (object1->objq.prev == NULL));
6559 assert((object2->purgable == VM_PURGABLE_DENY) || (object2->objq.next == NULL));
6560 assert((object2->purgable == VM_PURGABLE_DENY) || (object2->objq.prev == NULL));
6561
6562 #undef __TRANSPOSE_FIELD
6563
6564 retval = KERN_SUCCESS;
6565
6566 done:
6567 /*
6568 * Cleanup.
6569 */
6570 if (tmp_object != VM_OBJECT_NULL) {
6571 vm_object_unlock(tmp_object);
6572 /*
6573 * Re-initialize the temporary object to avoid
6574 * deallocating a real pager.
6575 */
6576 _vm_object_allocate(transpose_size, tmp_object);
6577 vm_object_deallocate(tmp_object);
6578 tmp_object = VM_OBJECT_NULL;
6579 }
6580
6581 if (object1_locked) {
6582 vm_object_unlock(object1);
6583 object1_locked = FALSE;
6584 }
6585 if (object2_locked) {
6586 vm_object_unlock(object2);
6587 object2_locked = FALSE;
6588 }
6589
6590 vm_object_transpose_count++;
6591
6592 return retval;
6593 }
6594
6595
6596 /*
6597 * vm_object_cluster_size
6598 *
6599 * Determine how big a cluster we should issue an I/O for...
6600 *
6601 * Inputs: *start == offset of page needed
6602 * *length == maximum cluster pager can handle
6603 * Outputs: *start == beginning offset of cluster
6604 * *length == length of cluster to try
6605 *
6606 * The original *start will be encompassed by the cluster
6607 *
6608 */
6609 extern int speculative_reads_disabled;
6610
6611 /*
6612 * Try to always keep these values an even multiple of PAGE_SIZE. We use these values
6613 * to derive min_ph_bytes and max_ph_bytes (IMP: bytes not # of pages) and expect those values to
6614 * always be page-aligned. The derivation could involve operations (e.g. division)
6615 * that could give us non-page-size aligned values if we start out with values that
6616 * are odd multiples of PAGE_SIZE.
6617 */
6618 #if !XNU_TARGET_OS_OSX
6619 unsigned int preheat_max_bytes = (1024 * 512);
6620 #else /* !XNU_TARGET_OS_OSX */
6621 unsigned int preheat_max_bytes = MAX_UPL_TRANSFER_BYTES;
6622 #endif /* !XNU_TARGET_OS_OSX */
6623 unsigned int preheat_min_bytes = (1024 * 32);
6624
6625
6626 __private_extern__ void
6627 vm_object_cluster_size(vm_object_t object, vm_object_offset_t *start,
6628 vm_size_t *length, vm_object_fault_info_t fault_info, uint32_t *io_streaming)
6629 {
6630 vm_size_t pre_heat_size;
6631 vm_size_t tail_size;
6632 vm_size_t head_size;
6633 vm_size_t max_length;
6634 vm_size_t cluster_size;
6635 vm_object_offset_t object_size;
6636 vm_object_offset_t orig_start;
6637 vm_object_offset_t target_start;
6638 vm_object_offset_t offset;
6639 vm_behavior_t behavior;
6640 boolean_t look_behind = TRUE;
6641 boolean_t look_ahead = TRUE;
6642 boolean_t isSSD = FALSE;
6643 uint32_t throttle_limit;
6644 int sequential_run;
6645 int sequential_behavior = VM_BEHAVIOR_SEQUENTIAL;
6646 vm_size_t max_ph_size;
6647 vm_size_t min_ph_size;
6648
6649 assert( !(*length & PAGE_MASK));
6650 assert( !(*start & PAGE_MASK_64));
6651
6652 /*
6653 * remember maxiumum length of run requested
6654 */
6655 max_length = *length;
6656 /*
6657 * we'll always return a cluster size of at least
6658 * 1 page, since the original fault must always
6659 * be processed
6660 */
6661 *length = PAGE_SIZE;
6662 *io_streaming = 0;
6663
6664 if (speculative_reads_disabled || fault_info == NULL) {
6665 /*
6666 * no cluster... just fault the page in
6667 */
6668 return;
6669 }
6670 orig_start = *start;
6671 target_start = orig_start;
6672 cluster_size = round_page(fault_info->cluster_size);
6673 behavior = fault_info->behavior;
6674
6675 vm_object_lock(object);
6676
6677 if (object->pager == MEMORY_OBJECT_NULL) {
6678 goto out; /* pager is gone for this object, nothing more to do */
6679 }
6680 vnode_pager_get_isSSD(object->pager, &isSSD);
6681
6682 min_ph_size = round_page(preheat_min_bytes);
6683 max_ph_size = round_page(preheat_max_bytes);
6684
6685 #if XNU_TARGET_OS_OSX
6686 /*
6687 * If we're paging from an SSD, we cut the minimum cluster size in half
6688 * and reduce the maximum size by a factor of 8. We do this because the
6689 * latency to issue an I/O is a couple of orders of magnitude smaller than
6690 * on spinning media, so being overly aggressive on the cluster size (to
6691 * try and reduce cumulative seek penalties) isn't a good trade off over
6692 * the increased memory pressure caused by the larger speculative I/Os.
6693 * However, the latency isn't 0, so a small amount of clustering is still
6694 * a win.
6695 *
6696 * If an explicit cluster size has already been provided, then we're
6697 * receiving a strong hint that the entire range will be needed (e.g.
6698 * wiring, willneed). In these cases, we want to maximize the I/O size
6699 * to minimize the number of I/Os issued.
6700 */
6701 if (isSSD && cluster_size <= PAGE_SIZE) {
6702 min_ph_size /= 2;
6703 max_ph_size /= 8;
6704
6705 if (min_ph_size & PAGE_MASK_64) {
6706 min_ph_size = trunc_page(min_ph_size);
6707 }
6708
6709 if (max_ph_size & PAGE_MASK_64) {
6710 max_ph_size = trunc_page(max_ph_size);
6711 }
6712 }
6713 #endif /* XNU_TARGET_OS_OSX */
6714
6715 if (min_ph_size < PAGE_SIZE) {
6716 min_ph_size = PAGE_SIZE;
6717 }
6718
6719 if (max_ph_size < PAGE_SIZE) {
6720 max_ph_size = PAGE_SIZE;
6721 } else if (max_ph_size > MAX_UPL_TRANSFER_BYTES) {
6722 max_ph_size = MAX_UPL_TRANSFER_BYTES;
6723 }
6724
6725 if (max_length > max_ph_size) {
6726 max_length = max_ph_size;
6727 }
6728
6729 if (max_length <= PAGE_SIZE) {
6730 goto out;
6731 }
6732
6733 if (object->internal) {
6734 object_size = object->vo_size;
6735 } else {
6736 vnode_pager_get_object_size(object->pager, &object_size);
6737 }
6738
6739 object_size = round_page_64(object_size);
6740
6741 if (orig_start >= object_size) {
6742 /*
6743 * fault occurred beyond the EOF...
6744 * we need to punt w/o changing the
6745 * starting offset
6746 */
6747 goto out;
6748 }
6749 if (object->pages_used > object->pages_created) {
6750 /*
6751 * must have wrapped our 32 bit counters
6752 * so reset
6753 */
6754 object->pages_used = object->pages_created = 0;
6755 }
6756 if ((sequential_run = object->sequential)) {
6757 if (sequential_run < 0) {
6758 sequential_behavior = VM_BEHAVIOR_RSEQNTL;
6759 sequential_run = 0 - sequential_run;
6760 } else {
6761 sequential_behavior = VM_BEHAVIOR_SEQUENTIAL;
6762 }
6763 }
6764 switch (behavior) {
6765 default:
6766 behavior = VM_BEHAVIOR_DEFAULT;
6767 OS_FALLTHROUGH;
6768
6769 case VM_BEHAVIOR_DEFAULT:
6770 if (object->internal && fault_info->user_tag == VM_MEMORY_STACK) {
6771 goto out;
6772 }
6773
6774 if (sequential_run >= (3 * PAGE_SIZE)) {
6775 pre_heat_size = sequential_run + PAGE_SIZE;
6776
6777 if (sequential_behavior == VM_BEHAVIOR_SEQUENTIAL) {
6778 look_behind = FALSE;
6779 } else {
6780 look_ahead = FALSE;
6781 }
6782
6783 *io_streaming = 1;
6784 } else {
6785 if (object->pages_created < (20 * (min_ph_size >> PAGE_SHIFT))) {
6786 /*
6787 * prime the pump
6788 */
6789 pre_heat_size = min_ph_size;
6790 } else {
6791 /*
6792 * Linear growth in PH size: The maximum size is max_length...
6793 * this cacluation will result in a size that is neither a
6794 * power of 2 nor a multiple of PAGE_SIZE... so round
6795 * it up to the nearest PAGE_SIZE boundary
6796 */
6797 pre_heat_size = (max_length * (uint64_t)object->pages_used) / object->pages_created;
6798
6799 if (pre_heat_size < min_ph_size) {
6800 pre_heat_size = min_ph_size;
6801 } else {
6802 pre_heat_size = round_page(pre_heat_size);
6803 }
6804 }
6805 }
6806 break;
6807
6808 case VM_BEHAVIOR_RANDOM:
6809 if ((pre_heat_size = cluster_size) <= PAGE_SIZE) {
6810 goto out;
6811 }
6812 break;
6813
6814 case VM_BEHAVIOR_SEQUENTIAL:
6815 if ((pre_heat_size = cluster_size) == 0) {
6816 pre_heat_size = sequential_run + PAGE_SIZE;
6817 }
6818 look_behind = FALSE;
6819 *io_streaming = 1;
6820
6821 break;
6822
6823 case VM_BEHAVIOR_RSEQNTL:
6824 if ((pre_heat_size = cluster_size) == 0) {
6825 pre_heat_size = sequential_run + PAGE_SIZE;
6826 }
6827 look_ahead = FALSE;
6828 *io_streaming = 1;
6829
6830 break;
6831 }
6832 throttle_limit = (uint32_t) max_length;
6833 assert(throttle_limit == max_length);
6834
6835 if (vnode_pager_get_throttle_io_limit(object->pager, &throttle_limit) == KERN_SUCCESS) {
6836 if (max_length > throttle_limit) {
6837 max_length = throttle_limit;
6838 }
6839 }
6840 if (pre_heat_size > max_length) {
6841 pre_heat_size = max_length;
6842 }
6843
6844 if (behavior == VM_BEHAVIOR_DEFAULT && (pre_heat_size > min_ph_size)) {
6845 unsigned int consider_free = vm_page_free_count + vm_page_cleaned_count;
6846
6847 if (consider_free < vm_page_throttle_limit) {
6848 pre_heat_size = trunc_page(pre_heat_size / 16);
6849 } else if (consider_free < vm_page_free_target) {
6850 pre_heat_size = trunc_page(pre_heat_size / 4);
6851 }
6852
6853 if (pre_heat_size < min_ph_size) {
6854 pre_heat_size = min_ph_size;
6855 }
6856 }
6857 if (look_ahead == TRUE) {
6858 if (look_behind == TRUE) {
6859 /*
6860 * if we get here its due to a random access...
6861 * so we want to center the original fault address
6862 * within the cluster we will issue... make sure
6863 * to calculate 'head_size' as a multiple of PAGE_SIZE...
6864 * 'pre_heat_size' is a multiple of PAGE_SIZE but not
6865 * necessarily an even number of pages so we need to truncate
6866 * the result to a PAGE_SIZE boundary
6867 */
6868 head_size = trunc_page(pre_heat_size / 2);
6869
6870 if (target_start > head_size) {
6871 target_start -= head_size;
6872 } else {
6873 target_start = 0;
6874 }
6875
6876 /*
6877 * 'target_start' at this point represents the beginning offset
6878 * of the cluster we are considering... 'orig_start' will be in
6879 * the center of this cluster if we didn't have to clip the start
6880 * due to running into the start of the file
6881 */
6882 }
6883 if ((target_start + pre_heat_size) > object_size) {
6884 pre_heat_size = (vm_size_t)(round_page_64(object_size - target_start));
6885 }
6886 /*
6887 * at this point caclulate the number of pages beyond the original fault
6888 * address that we want to consider... this is guaranteed not to extend beyond
6889 * the current EOF...
6890 */
6891 assert((vm_size_t)(orig_start - target_start) == (orig_start - target_start));
6892 tail_size = pre_heat_size - (vm_size_t)(orig_start - target_start) - PAGE_SIZE;
6893 } else {
6894 if (pre_heat_size > target_start) {
6895 /*
6896 * since pre_heat_size is always smaller then 2^32,
6897 * if it is larger then target_start (a 64 bit value)
6898 * it is safe to clip target_start to 32 bits
6899 */
6900 pre_heat_size = (vm_size_t) target_start;
6901 }
6902 tail_size = 0;
6903 }
6904 assert( !(target_start & PAGE_MASK_64));
6905 assert( !(pre_heat_size & PAGE_MASK_64));
6906
6907 if (pre_heat_size <= PAGE_SIZE) {
6908 goto out;
6909 }
6910
6911 if (look_behind == TRUE) {
6912 /*
6913 * take a look at the pages before the original
6914 * faulting offset... recalculate this in case
6915 * we had to clip 'pre_heat_size' above to keep
6916 * from running past the EOF.
6917 */
6918 head_size = pre_heat_size - tail_size - PAGE_SIZE;
6919
6920 for (offset = orig_start - PAGE_SIZE_64; head_size; offset -= PAGE_SIZE_64, head_size -= PAGE_SIZE) {
6921 /*
6922 * don't poke below the lowest offset
6923 */
6924 if (offset < fault_info->lo_offset) {
6925 break;
6926 }
6927 /*
6928 * for external objects or internal objects w/o a pager,
6929 * vm_object_compressor_pager_state_get will return VM_EXTERNAL_STATE_UNKNOWN
6930 */
6931 if (vm_object_compressor_pager_state_get(object, offset) == VM_EXTERNAL_STATE_ABSENT) {
6932 break;
6933 }
6934 if (vm_page_lookup(object, offset) != VM_PAGE_NULL) {
6935 /*
6936 * don't bridge resident pages
6937 */
6938 break;
6939 }
6940 *start = offset;
6941 *length += PAGE_SIZE;
6942 }
6943 }
6944 if (look_ahead == TRUE) {
6945 for (offset = orig_start + PAGE_SIZE_64; tail_size; offset += PAGE_SIZE_64, tail_size -= PAGE_SIZE) {
6946 /*
6947 * don't poke above the highest offset
6948 */
6949 if (offset >= fault_info->hi_offset) {
6950 break;
6951 }
6952 assert(offset < object_size);
6953
6954 /*
6955 * for external objects or internal objects w/o a pager,
6956 * vm_object_compressor_pager_state_get will return VM_EXTERNAL_STATE_UNKNOWN
6957 */
6958 if (vm_object_compressor_pager_state_get(object, offset) == VM_EXTERNAL_STATE_ABSENT) {
6959 break;
6960 }
6961 if (vm_page_lookup(object, offset) != VM_PAGE_NULL) {
6962 /*
6963 * don't bridge resident pages
6964 */
6965 break;
6966 }
6967 *length += PAGE_SIZE;
6968 }
6969 }
6970 out:
6971 if (*length > max_length) {
6972 *length = max_length;
6973 }
6974
6975 vm_object_unlock(object);
6976
6977 DTRACE_VM1(clustersize, vm_size_t, *length);
6978 }
6979
6980
6981 /*
6982 * Allow manipulation of individual page state. This is actually part of
6983 * the UPL regimen but takes place on the VM object rather than on a UPL
6984 */
6985
6986 kern_return_t
6987 vm_object_page_op(
6988 vm_object_t object,
6989 vm_object_offset_t offset,
6990 int ops,
6991 ppnum_t *phys_entry,
6992 int *flags)
6993 {
6994 vm_page_t dst_page;
6995
6996 vm_object_lock(object);
6997
6998 if (ops & UPL_POP_PHYSICAL) {
6999 if (object->phys_contiguous) {
7000 if (phys_entry) {
7001 *phys_entry = (ppnum_t)
7002 (object->vo_shadow_offset >> PAGE_SHIFT);
7003 }
7004 vm_object_unlock(object);
7005 return KERN_SUCCESS;
7006 } else {
7007 vm_object_unlock(object);
7008 return KERN_INVALID_OBJECT;
7009 }
7010 }
7011 if (object->phys_contiguous) {
7012 vm_object_unlock(object);
7013 return KERN_INVALID_OBJECT;
7014 }
7015
7016 while (TRUE) {
7017 if ((dst_page = vm_page_lookup(object, offset)) == VM_PAGE_NULL) {
7018 vm_object_unlock(object);
7019 return KERN_FAILURE;
7020 }
7021
7022 /* Sync up on getting the busy bit */
7023 if ((dst_page->vmp_busy || dst_page->vmp_cleaning) &&
7024 (((ops & UPL_POP_SET) &&
7025 (ops & UPL_POP_BUSY)) || (ops & UPL_POP_DUMP))) {
7026 /* someone else is playing with the page, we will */
7027 /* have to wait */
7028 vm_page_sleep(object, dst_page, THREAD_UNINT, LCK_SLEEP_DEFAULT);
7029 continue;
7030 }
7031
7032 if (ops & UPL_POP_DUMP) {
7033 if (dst_page->vmp_pmapped == TRUE) {
7034 pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(dst_page));
7035 }
7036
7037 VM_PAGE_FREE(dst_page);
7038 break;
7039 }
7040
7041 if (flags) {
7042 *flags = 0;
7043
7044 /* Get the condition of flags before requested ops */
7045 /* are undertaken */
7046
7047 if (dst_page->vmp_dirty) {
7048 *flags |= UPL_POP_DIRTY;
7049 }
7050 if (dst_page->vmp_free_when_done) {
7051 *flags |= UPL_POP_PAGEOUT;
7052 }
7053 if (dst_page->vmp_precious) {
7054 *flags |= UPL_POP_PRECIOUS;
7055 }
7056 if (dst_page->vmp_absent) {
7057 *flags |= UPL_POP_ABSENT;
7058 }
7059 if (dst_page->vmp_busy) {
7060 *flags |= UPL_POP_BUSY;
7061 }
7062 }
7063
7064 /* The caller should have made a call either contingent with */
7065 /* or prior to this call to set UPL_POP_BUSY */
7066 if (ops & UPL_POP_SET) {
7067 /* The protection granted with this assert will */
7068 /* not be complete. If the caller violates the */
7069 /* convention and attempts to change page state */
7070 /* without first setting busy we may not see it */
7071 /* because the page may already be busy. However */
7072 /* if such violations occur we will assert sooner */
7073 /* or later. */
7074 assert(dst_page->vmp_busy || (ops & UPL_POP_BUSY));
7075 if (ops & UPL_POP_DIRTY) {
7076 SET_PAGE_DIRTY(dst_page, FALSE);
7077 }
7078 if (ops & UPL_POP_PAGEOUT) {
7079 dst_page->vmp_free_when_done = TRUE;
7080 }
7081 if (ops & UPL_POP_PRECIOUS) {
7082 dst_page->vmp_precious = TRUE;
7083 }
7084 if (ops & UPL_POP_ABSENT) {
7085 dst_page->vmp_absent = TRUE;
7086 }
7087 if (ops & UPL_POP_BUSY) {
7088 dst_page->vmp_busy = TRUE;
7089 }
7090 }
7091
7092 if (ops & UPL_POP_CLR) {
7093 assert(dst_page->vmp_busy);
7094 if (ops & UPL_POP_DIRTY) {
7095 dst_page->vmp_dirty = FALSE;
7096 }
7097 if (ops & UPL_POP_PAGEOUT) {
7098 dst_page->vmp_free_when_done = FALSE;
7099 }
7100 if (ops & UPL_POP_PRECIOUS) {
7101 dst_page->vmp_precious = FALSE;
7102 }
7103 if (ops & UPL_POP_ABSENT) {
7104 dst_page->vmp_absent = FALSE;
7105 }
7106 if (ops & UPL_POP_BUSY) {
7107 dst_page->vmp_busy = FALSE;
7108 vm_page_wakeup(object, dst_page);
7109 }
7110 }
7111 if (phys_entry) {
7112 /*
7113 * The physical page number will remain valid
7114 * only if the page is kept busy.
7115 */
7116 assert(dst_page->vmp_busy);
7117 *phys_entry = VM_PAGE_GET_PHYS_PAGE(dst_page);
7118 }
7119
7120 break;
7121 }
7122
7123 vm_object_unlock(object);
7124 return KERN_SUCCESS;
7125 }
7126
7127 /*
7128 * vm_object_range_op offers performance enhancement over
7129 * vm_object_page_op for page_op functions which do not require page
7130 * level state to be returned from the call. Page_op was created to provide
7131 * a low-cost alternative to page manipulation via UPLs when only a single
7132 * page was involved. The range_op call establishes the ability in the _op
7133 * family of functions to work on multiple pages where the lack of page level
7134 * state handling allows the caller to avoid the overhead of the upl structures.
7135 */
7136
7137 kern_return_t
7138 vm_object_range_op(
7139 vm_object_t object,
7140 vm_object_offset_t offset_beg,
7141 vm_object_offset_t offset_end,
7142 int ops,
7143 uint32_t *range)
7144 {
7145 vm_object_offset_t offset;
7146 vm_page_t dst_page;
7147
7148 if (object->resident_page_count == 0) {
7149 if (range) {
7150 if (ops & UPL_ROP_PRESENT) {
7151 *range = 0;
7152 } else {
7153 *range = (uint32_t) (offset_end - offset_beg);
7154 assert(*range == (offset_end - offset_beg));
7155 }
7156 }
7157 return KERN_SUCCESS;
7158 }
7159 vm_object_lock(object);
7160
7161 if (object->phys_contiguous) {
7162 vm_object_unlock(object);
7163 return KERN_INVALID_OBJECT;
7164 }
7165
7166 offset = offset_beg & ~PAGE_MASK_64;
7167
7168 while (offset < offset_end) {
7169 dst_page = vm_page_lookup(object, offset);
7170 if (dst_page != VM_PAGE_NULL) {
7171 if (ops & UPL_ROP_DUMP) {
7172 if (dst_page->vmp_busy || dst_page->vmp_cleaning) {
7173 /*
7174 * someone else is playing with the
7175 * page, we will have to wait
7176 */
7177 vm_page_sleep(object, dst_page, THREAD_UNINT, LCK_SLEEP_DEFAULT);
7178 /*
7179 * need to relook the page up since it's
7180 * state may have changed while we slept
7181 * it might even belong to a different object
7182 * at this point
7183 */
7184 continue;
7185 }
7186 if (dst_page->vmp_laundry) {
7187 vm_pageout_steal_laundry(dst_page, FALSE);
7188 }
7189
7190 if (dst_page->vmp_pmapped == TRUE) {
7191 pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(dst_page));
7192 }
7193
7194 VM_PAGE_FREE(dst_page);
7195 } else if ((ops & UPL_ROP_ABSENT)
7196 && (!dst_page->vmp_absent || dst_page->vmp_busy)) {
7197 break;
7198 }
7199 } else if (ops & UPL_ROP_PRESENT) {
7200 break;
7201 }
7202
7203 offset += PAGE_SIZE;
7204 }
7205 vm_object_unlock(object);
7206
7207 if (range) {
7208 if (offset > offset_end) {
7209 offset = offset_end;
7210 }
7211 if (offset > offset_beg) {
7212 *range = (uint32_t) (offset - offset_beg);
7213 assert(*range == (offset - offset_beg));
7214 } else {
7215 *range = 0;
7216 }
7217 }
7218 return KERN_SUCCESS;
7219 }
7220
7221 /*
7222 * Used to point a pager directly to a range of memory (when the pager may be associated
7223 * with a non-device vnode). Takes a virtual address, an offset, and a size. We currently
7224 * expect that the virtual address will denote the start of a range that is physically contiguous.
7225 */
7226 kern_return_t
7227 pager_map_to_phys_contiguous(
7228 memory_object_control_t object,
7229 memory_object_offset_t offset,
7230 addr64_t base_vaddr,
7231 vm_size_t size)
7232 {
7233 ppnum_t page_num;
7234 boolean_t clobbered_private;
7235 kern_return_t retval;
7236 vm_object_t pager_object;
7237
7238 page_num = pmap_find_phys(kernel_pmap, base_vaddr);
7239
7240 if (!page_num) {
7241 retval = KERN_FAILURE;
7242 goto out;
7243 }
7244
7245 pager_object = memory_object_control_to_vm_object(object);
7246
7247 if (!pager_object) {
7248 retval = KERN_FAILURE;
7249 goto out;
7250 }
7251
7252 clobbered_private = pager_object->private;
7253 if (pager_object->private != TRUE) {
7254 vm_object_lock(pager_object);
7255 VM_OBJECT_SET_PRIVATE(pager_object, TRUE);
7256 vm_object_unlock(pager_object);
7257 }
7258 retval = vm_object_populate_with_private(pager_object, offset, page_num, size);
7259
7260 if (retval != KERN_SUCCESS) {
7261 if (pager_object->private != clobbered_private) {
7262 vm_object_lock(pager_object);
7263 VM_OBJECT_SET_PRIVATE(pager_object, clobbered_private);
7264 vm_object_unlock(pager_object);
7265 }
7266 }
7267
7268 out:
7269 return retval;
7270 }
7271
7272 uint32_t scan_object_collision = 0;
7273
7274 void
7275 vm_object_lock(vm_object_t object)
7276 {
7277 if (object == vm_pageout_scan_wants_object) {
7278 scan_object_collision++;
7279 mutex_pause(2);
7280 }
7281 DTRACE_VM(vm_object_lock_w);
7282 lck_rw_lock_exclusive(&object->Lock);
7283 }
7284
7285 boolean_t
7286 vm_object_lock_avoid(vm_object_t object)
7287 {
7288 if (object == vm_pageout_scan_wants_object) {
7289 scan_object_collision++;
7290 return TRUE;
7291 }
7292 return FALSE;
7293 }
7294
7295 boolean_t
7296 _vm_object_lock_try(vm_object_t object)
7297 {
7298 boolean_t retval;
7299
7300 retval = lck_rw_try_lock_exclusive(&object->Lock);
7301 #if DEVELOPMENT || DEBUG
7302 if (retval == TRUE) {
7303 DTRACE_VM(vm_object_lock_w);
7304 }
7305 #endif
7306 return retval;
7307 }
7308
7309 boolean_t
7310 vm_object_lock_try(vm_object_t object)
7311 {
7312 /*
7313 * Called from hibernate path so check before blocking.
7314 */
7315 if (vm_object_lock_avoid(object) && ml_get_interrupts_enabled() && get_preemption_level() == 0) {
7316 mutex_pause(2);
7317 }
7318 return _vm_object_lock_try(object);
7319 }
7320
7321 /*
7322 * Lock the object exclusive.
7323 *
7324 * Returns true iff the thread had to spin or block before
7325 * acquiring the lock.
7326 */
7327 bool
7328 vm_object_lock_check_contended(vm_object_t object)
7329 {
7330 if (object == vm_pageout_scan_wants_object) {
7331 scan_object_collision++;
7332 mutex_pause(2);
7333 }
7334 DTRACE_VM(vm_object_lock_w);
7335 return lck_rw_lock_exclusive_check_contended(&object->Lock);
7336 }
7337
7338 void
7339 vm_object_lock_shared(vm_object_t object)
7340 {
7341 if (vm_object_lock_avoid(object)) {
7342 mutex_pause(2);
7343 }
7344 DTRACE_VM(vm_object_lock_r);
7345 lck_rw_lock_shared(&object->Lock);
7346 }
7347
7348 boolean_t
7349 vm_object_lock_yield_shared(vm_object_t object)
7350 {
7351 boolean_t retval = FALSE, force_yield = FALSE;
7352
7353 vm_object_lock_assert_shared(object);
7354
7355 force_yield = vm_object_lock_avoid(object);
7356
7357 retval = lck_rw_lock_yield_shared(&object->Lock, force_yield);
7358 if (retval) {
7359 DTRACE_VM(vm_object_lock_yield);
7360 }
7361
7362 return retval;
7363 }
7364
7365 boolean_t
7366 vm_object_lock_try_shared(vm_object_t object)
7367 {
7368 boolean_t retval;
7369
7370 if (vm_object_lock_avoid(object)) {
7371 mutex_pause(2);
7372 }
7373 retval = lck_rw_try_lock_shared(&object->Lock);
7374 if (retval) {
7375 DTRACE_VM(vm_object_lock_r);
7376 }
7377 return retval;
7378 }
7379
7380 boolean_t
7381 vm_object_lock_upgrade(vm_object_t object)
7382 {
7383 boolean_t retval;
7384
7385 retval = lck_rw_lock_shared_to_exclusive(&object->Lock);
7386 #if DEVELOPMENT || DEBUG
7387 if (retval == TRUE) {
7388 DTRACE_VM(vm_object_lock_w);
7389 }
7390 #endif
7391 return retval;
7392 }
7393
7394 void
7395 vm_object_unlock(vm_object_t object)
7396 {
7397 #if DEVELOPMENT || DEBUG
7398 DTRACE_VM(vm_object_unlock);
7399 #endif
7400 lck_rw_done(&object->Lock);
7401 }
7402
7403
7404 unsigned int vm_object_change_wimg_mode_count = 0;
7405
7406 /*
7407 * The object must be locked
7408 */
7409 void
7410 vm_object_change_wimg_mode(vm_object_t object, unsigned int wimg_mode)
7411 {
7412 vm_object_lock_assert_exclusive(object);
7413
7414 vm_object_paging_only_wait(object, THREAD_UNINT);
7415
7416
7417 const unified_page_list_t pmap_batch_list = {
7418 .pageq = &object->memq,
7419 .type = UNIFIED_PAGE_LIST_TYPE_VM_PAGE_OBJ_Q,
7420 };
7421 pmap_batch_set_cache_attributes(&pmap_batch_list, wimg_mode);
7422 object->set_cache_attr = !HAS_DEFAULT_CACHEABILITY(wimg_mode);
7423
7424 object->wimg_bits = wimg_mode;
7425
7426 vm_object_change_wimg_mode_count++;
7427 }
7428
7429 #if CONFIG_FREEZE
7430
7431 extern struct freezer_context freezer_context_global;
7432
7433 /*
7434 * This routine does the "relocation" of previously
7435 * compressed pages belonging to this object that are
7436 * residing in a number of compressed segments into
7437 * a set of compressed segments dedicated to hold
7438 * compressed pages belonging to this object.
7439 */
7440
7441 extern AbsoluteTime c_freezer_last_yield_ts;
7442
7443 #define MAX_FREE_BATCH 32
7444 #define FREEZER_DUTY_CYCLE_ON_MS 5
7445 #define FREEZER_DUTY_CYCLE_OFF_MS 5
7446
7447 static int c_freezer_should_yield(void);
7448
7449
7450 static int
7451 c_freezer_should_yield()
7452 {
7453 AbsoluteTime cur_time;
7454 uint64_t nsecs;
7455
7456 assert(c_freezer_last_yield_ts);
7457 clock_get_uptime(&cur_time);
7458
7459 SUB_ABSOLUTETIME(&cur_time, &c_freezer_last_yield_ts);
7460 absolutetime_to_nanoseconds(cur_time, &nsecs);
7461
7462 if (nsecs > 1000 * 1000 * FREEZER_DUTY_CYCLE_ON_MS) {
7463 return 1;
7464 }
7465 return 0;
7466 }
7467
7468
7469 void
7470 vm_object_compressed_freezer_done()
7471 {
7472 vm_compressor_finished_filling( &(freezer_context_global.freezer_ctx_chead));
7473 }
7474
7475
7476 uint32_t
7477 vm_object_compressed_freezer_pageout(
7478 vm_object_t object, uint32_t dirty_budget)
7479 {
7480 vm_page_t p;
7481 vm_page_t local_freeq = NULL;
7482 int local_freed = 0;
7483 kern_return_t retval = KERN_SUCCESS;
7484 int obj_resident_page_count_snapshot = 0;
7485 uint32_t paged_out_count = 0;
7486
7487 assert(object != VM_OBJECT_NULL);
7488 assert(object->internal);
7489
7490 vm_object_lock(object);
7491
7492 if (!object->pager_initialized || object->pager == MEMORY_OBJECT_NULL) {
7493 if (!object->pager_initialized) {
7494 vm_object_collapse(object, (vm_object_offset_t) 0, TRUE);
7495
7496 if (!object->pager_initialized) {
7497 vm_object_compressor_pager_create(object);
7498 }
7499 }
7500
7501 if (!object->pager_initialized || object->pager == MEMORY_OBJECT_NULL) {
7502 vm_object_unlock(object);
7503 return paged_out_count;
7504 }
7505 }
7506
7507 /*
7508 * We could be freezing a shared internal object that might
7509 * be part of some other thread's current VM operations.
7510 * We skip it if there's a paging-in-progress or activity-in-progress
7511 * because we could be here a long time with the map lock held.
7512 *
7513 * Note: We are holding the map locked while we wait.
7514 * This is fine in the freezer path because the task
7515 * is suspended and so this latency is acceptable.
7516 */
7517 if (object->paging_in_progress || object->activity_in_progress) {
7518 vm_object_unlock(object);
7519 return paged_out_count;
7520 }
7521
7522 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE) {
7523 vm_object_offset_t curr_offset = 0;
7524
7525 /*
7526 * Go through the object and make sure that any
7527 * previously compressed pages are relocated into
7528 * a compressed segment associated with our "freezer_chead".
7529 */
7530 while (curr_offset < object->vo_size) {
7531 curr_offset = vm_compressor_pager_next_compressed(object->pager, curr_offset);
7532
7533 if (curr_offset == (vm_object_offset_t) -1) {
7534 break;
7535 }
7536
7537 retval = vm_compressor_pager_relocate(object->pager, curr_offset, &(freezer_context_global.freezer_ctx_chead));
7538
7539 if (retval != KERN_SUCCESS) {
7540 break;
7541 }
7542
7543 curr_offset += PAGE_SIZE_64;
7544 }
7545 }
7546
7547 /*
7548 * We can't hold the object lock while heading down into the compressed pager
7549 * layer because we might need the kernel map lock down there to allocate new
7550 * compressor data structures. And if this same object is mapped in the kernel
7551 * and there's a fault on it, then that thread will want the object lock while
7552 * holding the kernel map lock.
7553 *
7554 * Since we are going to drop/grab the object lock repeatedly, we must make sure
7555 * we won't be stuck in an infinite loop if the same page(s) keep getting
7556 * decompressed. So we grab a snapshot of the number of pages in the object and
7557 * we won't process any more than that number of pages.
7558 */
7559
7560 obj_resident_page_count_snapshot = object->resident_page_count;
7561
7562 vm_object_activity_begin(object);
7563
7564 while ((obj_resident_page_count_snapshot--) && !vm_page_queue_empty(&object->memq) && paged_out_count < dirty_budget) {
7565 p = (vm_page_t)vm_page_queue_first(&object->memq);
7566
7567 KDBG_DEBUG(0xe0430004 | DBG_FUNC_START, object, local_freed);
7568
7569 vm_page_lockspin_queues();
7570
7571 if (p->vmp_cleaning || vm_page_is_fictitious(p) ||
7572 p->vmp_busy || p->vmp_absent || p->vmp_unusual ||
7573 VMP_ERROR_GET(p) || VM_PAGE_WIRED(p)) {
7574 vm_page_unlock_queues();
7575
7576 KDBG_DEBUG(0xe0430004 | DBG_FUNC_END, object, local_freed, 1);
7577
7578 vm_page_queue_remove(&object->memq, p, vmp_listq);
7579 vm_page_queue_enter(&object->memq, p, vmp_listq);
7580
7581 continue;
7582 }
7583
7584 if (p->vmp_pmapped == TRUE) {
7585 int refmod_state, pmap_flags;
7586
7587 if (p->vmp_dirty || p->vmp_precious) {
7588 pmap_flags = PMAP_OPTIONS_COMPRESSOR;
7589 } else {
7590 pmap_flags = PMAP_OPTIONS_COMPRESSOR_IFF_MODIFIED;
7591 }
7592
7593 vm_page_lockconvert_queues();
7594 refmod_state = pmap_disconnect_options(VM_PAGE_GET_PHYS_PAGE(p), pmap_flags, NULL);
7595 if (refmod_state & VM_MEM_MODIFIED) {
7596 SET_PAGE_DIRTY(p, FALSE);
7597 }
7598 }
7599
7600 if (p->vmp_dirty == FALSE && p->vmp_precious == FALSE) {
7601 /*
7602 * Clean and non-precious page.
7603 */
7604 vm_page_unlock_queues();
7605 VM_PAGE_FREE(p);
7606
7607 KDBG_DEBUG(0xe0430004 | DBG_FUNC_END, object, local_freed, 2);
7608 continue;
7609 }
7610
7611 if (p->vmp_laundry) {
7612 vm_pageout_steal_laundry(p, TRUE);
7613 }
7614
7615 vm_page_queues_remove(p, TRUE);
7616
7617 vm_page_unlock_queues();
7618
7619
7620 /*
7621 * In case the compressor fails to compress this page, we need it at
7622 * the back of the object memq so that we don't keep trying to process it.
7623 * Make the move here while we have the object lock held.
7624 */
7625
7626 vm_page_queue_remove(&object->memq, p, vmp_listq);
7627 vm_page_queue_enter(&object->memq, p, vmp_listq);
7628
7629 /*
7630 * Grab an activity_in_progress here for vm_pageout_compress_page() to consume.
7631 *
7632 * Mark the page busy so no one messes with it while we have the object lock dropped.
7633 */
7634 p->vmp_busy = TRUE;
7635
7636 vm_object_activity_begin(object);
7637
7638 vm_object_unlock(object);
7639
7640 if (vm_pageout_compress_page(&(freezer_context_global.freezer_ctx_chead),
7641 (freezer_context_global.freezer_ctx_compressor_scratch_buf),
7642 p) == KERN_SUCCESS) {
7643 /*
7644 * page has already been un-tabled from the object via 'vm_page_remove'
7645 */
7646 p->vmp_snext = local_freeq;
7647 local_freeq = p;
7648 local_freed++;
7649 paged_out_count++;
7650
7651 if (local_freed >= MAX_FREE_BATCH) {
7652 OSAddAtomic64(local_freed, &vm_pageout_vminfo.vm_pageout_compressions);
7653
7654 vm_page_free_list(local_freeq, TRUE);
7655
7656 local_freeq = NULL;
7657 local_freed = 0;
7658 }
7659 freezer_context_global.freezer_ctx_uncompressed_pages++;
7660 }
7661 KDBG_DEBUG(0xe0430004 | DBG_FUNC_END, object, local_freed);
7662
7663 if (local_freed == 0 && c_freezer_should_yield()) {
7664 thread_yield_internal(FREEZER_DUTY_CYCLE_OFF_MS);
7665 clock_get_uptime(&c_freezer_last_yield_ts);
7666 }
7667
7668 vm_object_lock(object);
7669 }
7670
7671 if (local_freeq) {
7672 OSAddAtomic64(local_freed, &vm_pageout_vminfo.vm_pageout_compressions);
7673
7674 vm_page_free_list(local_freeq, TRUE);
7675
7676 local_freeq = NULL;
7677 local_freed = 0;
7678 }
7679
7680 vm_object_activity_end(object);
7681
7682 vm_object_unlock(object);
7683
7684 if (c_freezer_should_yield()) {
7685 thread_yield_internal(FREEZER_DUTY_CYCLE_OFF_MS);
7686 clock_get_uptime(&c_freezer_last_yield_ts);
7687 }
7688 return paged_out_count;
7689 }
7690
7691 #endif /* CONFIG_FREEZE */
7692
7693
7694 void
7695 vm_object_pageout(
7696 vm_object_t object)
7697 {
7698 vm_page_t p, next;
7699 struct vm_pageout_queue *iq;
7700
7701 if (!VM_CONFIG_COMPRESSOR_IS_PRESENT) {
7702 return;
7703 }
7704
7705 iq = &vm_pageout_queue_internal;
7706
7707 assert(object != VM_OBJECT_NULL );
7708
7709 vm_object_lock(object);
7710
7711 if (!object->internal ||
7712 object->terminating ||
7713 !object->alive) {
7714 vm_object_unlock(object);
7715 return;
7716 }
7717
7718 if (!object->pager_initialized || object->pager == MEMORY_OBJECT_NULL) {
7719 if (!object->pager_initialized) {
7720 vm_object_collapse(object, (vm_object_offset_t) 0, TRUE);
7721
7722 if (!object->pager_initialized) {
7723 vm_object_compressor_pager_create(object);
7724 }
7725 }
7726
7727 if (!object->pager_initialized || object->pager == MEMORY_OBJECT_NULL) {
7728 vm_object_unlock(object);
7729 return;
7730 }
7731 }
7732
7733 ReScan:
7734 next = (vm_page_t)vm_page_queue_first(&object->memq);
7735
7736 while (!vm_page_queue_end(&object->memq, (vm_page_queue_entry_t)next)) {
7737 p = next;
7738 next = (vm_page_t)vm_page_queue_next(&next->vmp_listq);
7739
7740 assert(p->vmp_q_state != VM_PAGE_ON_FREE_Q);
7741
7742 if ((p->vmp_q_state == VM_PAGE_ON_THROTTLED_Q) ||
7743 p->vmp_cleaning ||
7744 p->vmp_laundry ||
7745 p->vmp_busy ||
7746 p->vmp_absent ||
7747 VMP_ERROR_GET(p) ||
7748 vm_page_is_fictitious(p) ||
7749 VM_PAGE_WIRED(p)) {
7750 /*
7751 * Page is already being cleaned or can't be cleaned.
7752 */
7753 continue;
7754 }
7755 if (vm_compressor_low_on_space()) {
7756 break;
7757 }
7758
7759 /* Throw to the pageout queue */
7760
7761 vm_page_lockspin_queues();
7762
7763 if (VM_PAGE_Q_THROTTLED(iq)) {
7764 iq->pgo_draining = TRUE;
7765
7766 assert_wait((event_t) (&iq->pgo_laundry + 1),
7767 THREAD_INTERRUPTIBLE);
7768 vm_page_unlock_queues();
7769 vm_object_unlock(object);
7770
7771 thread_block(THREAD_CONTINUE_NULL);
7772
7773 vm_object_lock(object);
7774 goto ReScan;
7775 }
7776
7777 assert(!vm_page_is_fictitious(p));
7778 assert(!p->vmp_busy);
7779 assert(!p->vmp_absent);
7780 assert(!p->vmp_unusual);
7781 assert(!VMP_ERROR_GET(p)); /* XXX there's a window here where we could have an ECC error! */
7782 assert(!VM_PAGE_WIRED(p));
7783 assert(!p->vmp_cleaning);
7784
7785 if (p->vmp_pmapped == TRUE) {
7786 int refmod_state;
7787 int pmap_options;
7788
7789 /*
7790 * Tell pmap the page should be accounted
7791 * for as "compressed" if it's been modified.
7792 */
7793 pmap_options =
7794 PMAP_OPTIONS_COMPRESSOR_IFF_MODIFIED;
7795 if (p->vmp_dirty || p->vmp_precious) {
7796 /*
7797 * We already know it's been modified,
7798 * so tell pmap to account for it
7799 * as "compressed".
7800 */
7801 pmap_options = PMAP_OPTIONS_COMPRESSOR;
7802 }
7803 vm_page_lockconvert_queues();
7804 refmod_state = pmap_disconnect_options(VM_PAGE_GET_PHYS_PAGE(p),
7805 pmap_options,
7806 NULL);
7807 if (refmod_state & VM_MEM_MODIFIED) {
7808 SET_PAGE_DIRTY(p, FALSE);
7809 }
7810 }
7811
7812 if (!p->vmp_dirty && !p->vmp_precious) {
7813 vm_page_unlock_queues();
7814 VM_PAGE_FREE(p);
7815 continue;
7816 }
7817 vm_page_queues_remove(p, TRUE);
7818
7819 vm_pageout_cluster(p);
7820
7821 vm_page_unlock_queues();
7822 }
7823 vm_object_unlock(object);
7824 }
7825
7826
7827 #if CONFIG_IOSCHED
7828
7829 void
7830 vm_page_request_reprioritize(vm_object_t o, uint64_t blkno, uint32_t len, int prio)
7831 {
7832 io_reprioritize_req_t req;
7833 struct vnode *devvp = NULL;
7834
7835 if (vnode_pager_get_object_devvp(o->pager, (uintptr_t *)&devvp) != KERN_SUCCESS) {
7836 return;
7837 }
7838
7839 /*
7840 * Create the request for I/O reprioritization.
7841 * We use the noblock variant of zalloc because we're holding the object
7842 * lock here and we could cause a deadlock in low memory conditions.
7843 */
7844 req = (io_reprioritize_req_t)zalloc_noblock(io_reprioritize_req_zone);
7845 if (req == NULL) {
7846 return;
7847 }
7848 req->blkno = blkno;
7849 req->len = len;
7850 req->priority = prio;
7851 req->devvp = devvp;
7852
7853 /* Insert request into the reprioritization list */
7854 mpsc_daemon_enqueue(&io_reprioritize_q, &req->iorr_elm, MPSC_QUEUE_DISABLE_PREEMPTION);
7855
7856 return;
7857 }
7858
7859 void
7860 vm_decmp_upl_reprioritize(upl_t upl, int prio)
7861 {
7862 int offset;
7863 vm_object_t object;
7864 io_reprioritize_req_t req;
7865 struct vnode *devvp = NULL;
7866 uint64_t blkno;
7867 uint32_t len;
7868 upl_t io_upl;
7869 uint64_t *io_upl_reprio_info;
7870 int io_upl_size;
7871
7872 if ((upl->flags & UPL_TRACKED_BY_OBJECT) == 0 || (upl->flags & UPL_EXPEDITE_SUPPORTED) == 0) {
7873 return;
7874 }
7875
7876 /*
7877 * We dont want to perform any allocations with the upl lock held since that might
7878 * result in a deadlock. If the system is low on memory, the pageout thread would
7879 * try to pageout stuff and might wait on this lock. If we are waiting for the memory to
7880 * be freed up by the pageout thread, it would be a deadlock.
7881 */
7882
7883
7884 /* First step is just to get the size of the upl to find out how big the reprio info is */
7885 if (!upl_try_lock(upl)) {
7886 return;
7887 }
7888
7889 if (upl->decmp_io_upl == NULL) {
7890 /* The real I/O upl was destroyed by the time we came in here. Nothing to do. */
7891 upl_unlock(upl);
7892 return;
7893 }
7894
7895 io_upl = upl->decmp_io_upl;
7896 assert((io_upl->flags & UPL_DECMP_REAL_IO) != 0);
7897 assertf(page_aligned(io_upl->u_offset) && page_aligned(io_upl->u_size),
7898 "upl %p offset 0x%llx size 0x%x\n",
7899 io_upl, io_upl->u_offset, io_upl->u_size);
7900 io_upl_size = io_upl->u_size;
7901 upl_unlock(upl);
7902
7903 /* Now perform the allocation */
7904 io_upl_reprio_info = kalloc_data(sizeof(uint64_t) * atop(io_upl_size), Z_WAITOK);
7905 if (io_upl_reprio_info == NULL) {
7906 return;
7907 }
7908
7909 /* Now again take the lock, recheck the state and grab out the required info */
7910 if (!upl_try_lock(upl)) {
7911 goto out;
7912 }
7913
7914 if (upl->decmp_io_upl == NULL || upl->decmp_io_upl != io_upl) {
7915 /* The real I/O upl was destroyed by the time we came in here. Nothing to do. */
7916 upl_unlock(upl);
7917 goto out;
7918 }
7919 memcpy(io_upl_reprio_info, io_upl->upl_reprio_info,
7920 sizeof(uint64_t) * atop(io_upl_size));
7921
7922 /* Get the VM object for this UPL */
7923 if (io_upl->flags & UPL_SHADOWED) {
7924 object = io_upl->map_object->shadow;
7925 } else {
7926 object = io_upl->map_object;
7927 }
7928
7929 /* Get the dev vnode ptr for this object */
7930 if (!object || !object->pager ||
7931 vnode_pager_get_object_devvp(object->pager, (uintptr_t *)&devvp) != KERN_SUCCESS) {
7932 upl_unlock(upl);
7933 goto out;
7934 }
7935
7936 upl_unlock(upl);
7937
7938 /* Now we have all the information needed to do the expedite */
7939
7940 offset = 0;
7941 while (offset < io_upl_size) {
7942 blkno = io_upl_reprio_info[atop(offset)] & UPL_REPRIO_INFO_MASK;
7943 len = (io_upl_reprio_info[atop(offset)] >> UPL_REPRIO_INFO_SHIFT) & UPL_REPRIO_INFO_MASK;
7944
7945 /*
7946 * This implementation may cause some spurious expedites due to the
7947 * fact that we dont cleanup the blkno & len from the upl_reprio_info
7948 * even after the I/O is complete.
7949 */
7950
7951 if (blkno != 0 && len != 0) {
7952 /* Create the request for I/O reprioritization */
7953 req = zalloc_flags(io_reprioritize_req_zone,
7954 Z_WAITOK | Z_NOFAIL);
7955 req->blkno = blkno;
7956 req->len = len;
7957 req->priority = prio;
7958 req->devvp = devvp;
7959
7960 /* Insert request into the reprioritization list */
7961 mpsc_daemon_enqueue(&io_reprioritize_q, &req->iorr_elm, MPSC_QUEUE_DISABLE_PREEMPTION);
7962
7963 offset += len;
7964 } else {
7965 offset += PAGE_SIZE;
7966 }
7967 }
7968
7969 out:
7970 kfree_data(io_upl_reprio_info, sizeof(uint64_t) * atop(io_upl_size));
7971 }
7972
7973 void
7974 vm_page_handle_prio_inversion(vm_object_t o, vm_page_t m)
7975 {
7976 upl_t upl;
7977 upl_page_info_t *pl;
7978 unsigned int i, num_pages;
7979 int cur_tier;
7980
7981 cur_tier = proc_get_effective_thread_policy(current_thread(), TASK_POLICY_IO);
7982
7983 /*
7984 * Scan through all UPLs associated with the object to find the
7985 * UPL containing the contended page.
7986 */
7987 queue_iterate(&o->uplq, upl, upl_t, uplq) {
7988 if (((upl->flags & UPL_EXPEDITE_SUPPORTED) == 0) || upl->upl_priority <= cur_tier) {
7989 continue;
7990 }
7991 pl = UPL_GET_INTERNAL_PAGE_LIST(upl);
7992 assertf(page_aligned(upl->u_offset) && page_aligned(upl->u_size),
7993 "upl %p offset 0x%llx size 0x%x\n",
7994 upl, upl->u_offset, upl->u_size);
7995 num_pages = (upl->u_size / PAGE_SIZE);
7996
7997 /*
7998 * For each page in the UPL page list, see if it matches the contended
7999 * page and was issued as a low prio I/O.
8000 */
8001 for (i = 0; i < num_pages; i++) {
8002 if (UPL_PAGE_PRESENT(pl, i) && VM_PAGE_GET_PHYS_PAGE(m) == pl[i].phys_addr) {
8003 if ((upl->flags & UPL_DECMP_REQ) && upl->decmp_io_upl) {
8004 KDBG((VMDBG_CODE(DBG_VM_PAGE_EXPEDITE)) | DBG_FUNC_NONE, VM_KERNEL_UNSLIDE_OR_PERM(upl->upl_creator), VM_KERNEL_UNSLIDE_OR_PERM(m),
8005 VM_KERNEL_UNSLIDE_OR_PERM(upl), upl->upl_priority);
8006 vm_decmp_upl_reprioritize(upl, cur_tier);
8007 break;
8008 }
8009 KDBG((VMDBG_CODE(DBG_VM_PAGE_EXPEDITE)) | DBG_FUNC_NONE, VM_KERNEL_UNSLIDE_OR_PERM(upl->upl_creator), VM_KERNEL_UNSLIDE_OR_PERM(m),
8010 upl->upl_reprio_info[i], upl->upl_priority);
8011 if (UPL_REPRIO_INFO_BLKNO(upl, i) != 0 && UPL_REPRIO_INFO_LEN(upl, i) != 0) {
8012 vm_page_request_reprioritize(o, UPL_REPRIO_INFO_BLKNO(upl, i), UPL_REPRIO_INFO_LEN(upl, i), cur_tier);
8013 }
8014 break;
8015 }
8016 }
8017 /* Check if we found any hits */
8018 if (i != num_pages) {
8019 break;
8020 }
8021 }
8022
8023 return;
8024 }
8025
8026 void
8027 kdp_vm_object_sleep_find_owner(
8028 event64_t wait_event,
8029 block_hint_t wait_type,
8030 thread_waitinfo_t *waitinfo)
8031 {
8032 assert(wait_type >= kThreadWaitPagerInit && wait_type <= kThreadWaitPageInThrottle);
8033 vm_object_wait_reason_t wait_reason = wait_type - kThreadWaitPagerInit;
8034 vm_object_t object = (vm_object_t)((uintptr_t)wait_event - wait_reason);
8035 waitinfo->context = VM_KERNEL_ADDRPERM(object);
8036 /*
8037 * There is currently no non-trivial way to ascertain the thread(s)
8038 * currently operating on this object.
8039 */
8040 waitinfo->owner = 0;
8041 }
8042
8043
8044 wait_result_t
8045 vm_object_sleep(
8046 vm_object_t object,
8047 vm_object_wait_reason_t reason,
8048 wait_interrupt_t interruptible,
8049 lck_sleep_action_t action)
8050 {
8051 wait_result_t wr;
8052 block_hint_t block_hint;
8053 event_t wait_event;
8054
8055 vm_object_lock_assert_exclusive(object);
8056 assert(reason >= 0 && reason <= VM_OBJECT_EVENT_MAX);
8057 switch (reason) {
8058 case VM_OBJECT_EVENT_PAGER_INIT:
8059 block_hint = kThreadWaitPagerInit;
8060 break;
8061 case VM_OBJECT_EVENT_PAGER_READY:
8062 block_hint = kThreadWaitPagerReady;
8063 break;
8064 case VM_OBJECT_EVENT_PAGING_IN_PROGRESS:
8065 block_hint = kThreadWaitPagingActivity;
8066 break;
8067 case VM_OBJECT_EVENT_MAPPING_IN_PROGRESS:
8068 block_hint = kThreadWaitMappingInProgress;
8069 break;
8070 case VM_OBJECT_EVENT_UNBLOCKED:
8071 block_hint = kThreadWaitMemoryBlocked;
8072 break;
8073 case VM_OBJECT_EVENT_PAGING_ONLY_IN_PROGRESS:
8074 block_hint = kThreadWaitPagingInProgress;
8075 break;
8076 case VM_OBJECT_EVENT_PAGEIN_THROTTLE:
8077 block_hint = kThreadWaitPageInThrottle;
8078 break;
8079 default:
8080 panic("Unexpected wait reason %u", reason);
8081 }
8082 thread_set_pending_block_hint(current_thread(), block_hint);
8083
8084 KDBG_FILTERED(VMDBG_CODE(DBG_VM_OBJECT_SLEEP) | DBG_FUNC_START, VM_KERNEL_ADDRHIDE(object), reason);
8085
8086 vm_object_set_wanted(object, reason);
8087 wait_event = (event_t)((uintptr_t)object + (uintptr_t)reason);
8088 wr = lck_rw_sleep(&object->Lock, LCK_SLEEP_PROMOTED_PRI | action, wait_event, interruptible);
8089
8090 KDBG_FILTERED(VMDBG_CODE(DBG_VM_OBJECT_SLEEP) | DBG_FUNC_END, VM_KERNEL_ADDRHIDE(object), reason, wr);
8091 return wr;
8092 }
8093
8094
8095 wait_result_t
8096 vm_object_paging_wait(vm_object_t object, wait_interrupt_t interruptible)
8097 {
8098 wait_result_t wr = THREAD_NOT_WAITING;
8099 vm_object_lock_assert_exclusive(object);
8100 while (object->paging_in_progress != 0 ||
8101 object->activity_in_progress != 0) {
8102 wr = vm_object_sleep((object),
8103 VM_OBJECT_EVENT_PAGING_IN_PROGRESS,
8104 interruptible,
8105 LCK_SLEEP_EXCLUSIVE);
8106 if (wr != THREAD_AWAKENED) {
8107 break;
8108 }
8109 }
8110 return wr;
8111 }
8112
8113 wait_result_t
8114 vm_object_paging_only_wait(vm_object_t object, wait_interrupt_t interruptible)
8115 {
8116 wait_result_t wr = THREAD_NOT_WAITING;
8117 vm_object_lock_assert_exclusive(object);
8118 while (object->paging_in_progress != 0) {
8119 wr = vm_object_sleep(object,
8120 VM_OBJECT_EVENT_PAGING_ONLY_IN_PROGRESS,
8121 interruptible,
8122 LCK_SLEEP_EXCLUSIVE);
8123 if (wr != THREAD_AWAKENED) {
8124 break;
8125 }
8126 }
8127 return wr;
8128 }
8129
8130 wait_result_t
8131 vm_object_paging_throttle_wait(vm_object_t object, wait_interrupt_t interruptible)
8132 {
8133 wait_result_t wr = THREAD_NOT_WAITING;
8134 vm_object_lock_assert_exclusive(object);
8135 /*
8136 * TODO: consider raising the throttle limit specifically for
8137 * shared-cache objects, which are expected to be highly contended.
8138 * (rdar://127899888)
8139 */
8140 while (object->paging_in_progress >= vm_object_pagein_throttle) {
8141 wr = vm_object_sleep(object,
8142 VM_OBJECT_EVENT_PAGEIN_THROTTLE,
8143 interruptible,
8144 LCK_SLEEP_EXCLUSIVE);
8145 if (wr != THREAD_AWAKENED) {
8146 break;
8147 }
8148 }
8149 return wr;
8150 }
8151
8152 wait_result_t
8153 vm_object_mapping_wait(vm_object_t object, wait_interrupt_t interruptible)
8154 {
8155 wait_result_t wr = THREAD_NOT_WAITING;
8156 vm_object_lock_assert_exclusive(object);
8157 while (object->mapping_in_progress) {
8158 wr = vm_object_sleep(object,
8159 VM_OBJECT_EVENT_MAPPING_IN_PROGRESS,
8160 interruptible,
8161 LCK_SLEEP_EXCLUSIVE);
8162 if (wr != THREAD_AWAKENED) {
8163 break;
8164 }
8165 }
8166 return wr;
8167 }
8168
8169 void
8170 vm_object_wakeup(
8171 vm_object_t object,
8172 vm_object_wait_reason_t reason)
8173 {
8174 vm_object_lock_assert_exclusive(object);
8175 assert(reason >= 0 && reason <= VM_OBJECT_EVENT_MAX);
8176
8177 if (vm_object_wanted(object, reason)) {
8178 thread_wakeup((event_t)((uintptr_t)object + (uintptr_t)reason));
8179 }
8180 object->all_wanted &= ~(1 << reason);
8181 }
8182
8183
8184 void
8185 kdp_vm_page_sleep_find_owner(event64_t wait_event, thread_waitinfo_t *waitinfo)
8186 {
8187 vm_page_t m = (vm_page_t)wait_event;
8188 waitinfo->context = VM_KERNEL_ADDRPERM(m);
8189 /*
8190 * There is not currently a non-trivial way to identify the thread
8191 * holding a page busy.
8192 */
8193 waitinfo->owner = 0;
8194 }
8195
8196 #if PAGE_SLEEP_WITH_INHERITOR
8197 static wait_result_t vm_page_sleep_with_inheritor(lck_rw_t *lck, lck_sleep_action_t lck_sleep_action, event_t event, wait_interrupt_t interruptible);
8198 #endif /* PAGE_SLEEP_WITH_INHERITOR */
8199
8200 wait_result_t
8201 vm_page_sleep(vm_object_t object, vm_page_t m, wait_interrupt_t interruptible, lck_sleep_action_t action)
8202 {
8203 wait_result_t ret;
8204
8205 KDBG_FILTERED((VMDBG_CODE(DBG_VM_PAGE_SLEEP)) | DBG_FUNC_START, VM_KERNEL_ADDRHIDE(object), m->vmp_offset, VM_KERNEL_ADDRHIDE(m));
8206 #if CONFIG_IOSCHED
8207 if (object->io_tracking && ((m->vmp_busy == TRUE) || (m->vmp_cleaning == TRUE) || VM_PAGE_WIRED(m))) {
8208 /*
8209 * Indicates page is busy due to an I/O. Issue a reprioritize request if necessary.
8210 */
8211 vm_page_handle_prio_inversion(object, m);
8212 }
8213 #endif /* CONFIG_IOSCHED */
8214 m->vmp_wanted = TRUE;
8215 thread_set_pending_block_hint(current_thread(), kThreadWaitPageBusy);
8216 #if PAGE_SLEEP_WITH_INHERITOR
8217 ret = vm_page_sleep_with_inheritor(&object->Lock, action, (event_t)m, interruptible);
8218 #else
8219 ret = lck_rw_sleep(&object->Lock, LCK_SLEEP_PROMOTED_PRI | action, (event_t)m, interruptible);
8220 #endif
8221 KDBG_FILTERED((VMDBG_CODE(DBG_VM_PAGE_SLEEP)) | DBG_FUNC_END, VM_KERNEL_ADDRHIDE(object), m->vmp_offset, VM_KERNEL_ADDRHIDE(m));
8222 return ret;
8223 }
8224
8225 void
8226 vm_page_wakeup(vm_object_t object, vm_page_t m)
8227 {
8228 assert(m);
8229 /*
8230 * The page may have been freed from its object before this wakeup is issued
8231 */
8232 if (object != VM_OBJECT_NULL) {
8233 vm_object_lock_assert_exclusive(object);
8234 }
8235
8236 if (m->vmp_wanted) {
8237 KDBG(VMDBG_CODE(DBG_VM_PAGE_WAKEUP) | DBG_FUNC_NONE,
8238 VM_KERNEL_ADDRHIDE(object), m->vmp_offset,
8239 VM_KERNEL_ADDRHIDE(m));
8240 m->vmp_wanted = false;
8241 thread_wakeup((event_t)m);
8242 }
8243 }
8244
8245 void
8246 vm_page_wakeup_done(__assert_only vm_object_t object, vm_page_t m)
8247 {
8248 assert(object);
8249 assert(m->vmp_busy);
8250 vm_object_lock_assert_exclusive(object);
8251
8252 KDBG(VMDBG_CODE(DBG_VM_PAGE_WAKEUP_DONE) | DBG_FUNC_NONE,
8253 VM_KERNEL_ADDRHIDE(object), m->vmp_offset,
8254 VM_KERNEL_ADDRHIDE(m), m->vmp_wanted);
8255 m->vmp_busy = false;
8256 vm_page_wakeup(object, m);
8257 }
8258
8259 #if PAGE_SLEEP_WITH_INHERITOR
8260 static bool page_worker_unregister_worker(event_t event, thread_t expect_th, page_worker_token_t *token);
8261 #endif /* PAGE_SLEEP_WITH_INHERITOR */
8262
8263 /* This function duplicates all of what vm_page_wakeup_done() does and adds the option
8264 * that we're being called from vm_fault_page() in a page that is possibly boosted due to being an inheritor*/
8265 void
8266 vm_page_wakeup_done_with_inheritor(vm_object_t object __unused, vm_page_t m, page_worker_token_t *token __unused)
8267 {
8268 #if PAGE_SLEEP_WITH_INHERITOR
8269 assert(object);
8270 assert(m->vmp_busy);
8271 vm_object_lock_assert_exclusive(object);
8272
8273 bool had_inheritor = page_worker_unregister_worker((event_t)m, current_thread(), token);
8274
8275 KDBG(VMDBG_CODE(DBG_VM_PAGE_WAKEUP_DONE) | DBG_FUNC_NONE,
8276 VM_KERNEL_ADDRHIDE(object), VM_KERNEL_ADDRHIDE(m),
8277 m->vmp_wanted, had_inheritor);
8278 m->vmp_busy = FALSE;
8279
8280 if (m->vmp_wanted) {
8281 m->vmp_wanted = FALSE;
8282 if (had_inheritor) {
8283 wakeup_all_with_inheritor((event_t)m, THREAD_AWAKENED);
8284 } else {
8285 thread_wakeup((event_t)m);
8286 }
8287 }
8288 #else /* PAGE_SLEEP_WITH_INHERITOR */
8289 vm_page_wakeup_done(object, m);
8290 #endif /* PAGE_SLEEP_WITH_INHERITOR */
8291 }
8292
8293 #if PAGE_SLEEP_WITH_INHERITOR
8294
8295 /*
8296 * vm_page_sleep_with_inheritor:
8297 * The goal of this functionality is to prevent priority inversion that can occur when a low-priority
8298 * thread is stuck in the compressor and a higher priority thread waits for the same page.
8299 * Just before vm_fault_page() calls into the compressor it calls page_worker_register_worker()
8300 * this registers the calling thread as the "page worker" of this page.
8301 * When another thread then tries to vm_page_sleep() on that page, (wait for it to un-busy) the worker is found and
8302 * instead of a plain thread_block() (in lck_rw_sleep()) we do lck_rw_sleep_with_inheritor() and give the registered
8303 * worker thread as the inheritor of the priority boost.
8304 * The worker thread might have started its work on a low priority, and when a waiter was added, it got boost.
8305 * When the worker is done getting the page it calls vm_page_wakeup_done_with_inheritor() instead of
8306 * vm_page_wakeup_done() this unregisters the thread, clears the page busy bit (so that now other threads can
8307 * use this page), and wakes up any waiters waiting for that page with wakeup_all_with_inheritor(), which
8308 * removes the priority boost.
8309 *
8310 * The worker registration is done in a simple single entry per bucket hash table. A hash collision may occur
8311 * if two faulting pages end up in the same entry. In this case, the registration of the second one is going to
8312 * fail and the only repercussions of this is that it would not get the possible boost if anyone is going to wait
8313 * on it. This implementation was selected over a full hash-table to keep it simple and fast.
8314 */
8315
8316 struct page_worker {
8317 lck_ticket_t pw_entry_lock;
8318 event_t pw_owner_event;
8319 thread_t pw_current_worker;
8320 };
8321
8322 SECURITY_READ_ONLY_LATE(uint32_t) page_worker_table_size = 0;
8323 SECURITY_READ_ONLY_LATE(static struct page_worker *)page_worker_table = NULL;
8324 SCALABLE_COUNTER_DEFINE(page_worker_hash_collisions);
8325 SCALABLE_COUNTER_DEFINE(page_worker_inheritor_sleeps);
8326
8327 LCK_GRP_DECLARE(page_worker_table_lock_grp, "page_worker_table_locks");
8328
8329 #define page_worker_entry_unlock(entry) \
8330 lck_ticket_unlock(&entry->pw_entry_lock);
8331
8332 #define PAGE_WORKER_TABLE_BUCKETS (256)
8333
8334 void
8335 page_worker_init(void)
8336 {
8337 page_worker_table_size = PAGE_WORKER_TABLE_BUCKETS;
8338 #if DEVELOPMENT || DEBUG
8339 PE_parse_boot_argn("page_worker_table_size", &page_worker_table_size, sizeof(page_worker_table_size));
8340 #endif /* DEVELOPMENT || DEBUG */
8341 /* This checks that the size is a positive power of 2, needed for the hash function */
8342 assert(page_worker_table_size > 0 && !(page_worker_table_size & (page_worker_table_size - 1)));
8343
8344 page_worker_table = zalloc_permanent(page_worker_table_size * sizeof(struct page_worker), ZALIGN_PTR);
8345 if (page_worker_table == NULL) {
8346 panic("Page events hash table memory allocation failed!");
8347 }
8348 for (uint32_t i = 0; i < page_worker_table_size; ++i) {
8349 struct page_worker* we = &(page_worker_table[i]);
8350 lck_ticket_init(&we->pw_entry_lock, &page_worker_table_lock_grp);
8351 }
8352 }
8353
8354 static struct page_worker *
8355 page_worker_lock_table_entry(event_t event)
8356 {
8357 if (page_worker_table == NULL) {
8358 return NULL;
8359 }
8360 uint32_t hash = os_hash_kernel_pointer((void *)event);
8361 uint32_t index = hash & (page_worker_table_size - 1);
8362
8363 struct page_worker *entry = &page_worker_table[index];
8364
8365 lck_ticket_lock(&entry->pw_entry_lock, &page_worker_table_lock_grp);
8366 return entry;
8367 }
8368
8369 /* returns a locked entry if found or added, otherwise returns NULL */
8370 static struct page_worker *
8371 page_worker_lookup(event_t event, bool try_add_missing)
8372 {
8373 assert(event != NULL);
8374 struct page_worker *entry = page_worker_lock_table_entry(event);
8375 if (entry == NULL) {
8376 /* table not initialized */
8377 return NULL;
8378 }
8379 if (entry->pw_owner_event == event) {
8380 /* found existing entry and it belongs to this event */
8381 return entry;
8382 }
8383
8384 if (try_add_missing) {
8385 if (entry->pw_owner_event == NULL) {
8386 /* found empty entry, take over it */
8387 entry->pw_owner_event = event;
8388 return entry;
8389 }
8390 /* didn't find the event, need to add it, but can't because it's occupied */
8391 counter_inc(&page_worker_hash_collisions);
8392 }
8393 page_worker_entry_unlock(entry);
8394 return NULL;
8395 }
8396
8397 /* returns true if current_thread() was successfully registered as worker */
8398 void
8399 page_worker_register_worker(event_t event __unused, page_worker_token_t *out_token)
8400 {
8401 out_token->pwt_did_register_inheritor = false;
8402 out_token->pwt_floor_token.thread = THREAD_NULL;
8403
8404 struct page_worker* entry = page_worker_lookup(event, TRUE);
8405 if (entry == NULL) {
8406 /* failed registration due to a hash collision */
8407 out_token->pwt_floor_token = thread_priority_floor_start();
8408 return;
8409 }
8410 entry->pw_current_worker = current_thread();
8411 /* no need to take the thread reference because this is going to get cleared in the same call of vm_page_fault() */
8412 page_worker_entry_unlock(entry);
8413 out_token->pwt_did_register_inheritor = true;
8414 }
8415
8416 static bool
8417 page_worker_unregister_worker(event_t event, thread_t expect_th __unused, page_worker_token_t *token)
8418 {
8419 struct page_worker *entry = page_worker_lookup(event, FALSE);
8420 if (entry == NULL) {
8421 assert(!token->pwt_did_register_inheritor);
8422 /* did we do thread_priority_floor_start() ? */
8423 if (token->pwt_floor_token.thread != THREAD_NULL) {
8424 thread_priority_floor_end(&token->pwt_floor_token);
8425 }
8426 return false;
8427 }
8428 assert(token->pwt_did_register_inheritor);
8429 assert(token->pwt_floor_token.thread == THREAD_NULL); /* we shouldn't have done thread_priority_floor_start() */
8430 assert(entry->pw_owner_event != 0);
8431 assert(entry->pw_current_worker == expect_th);
8432 entry->pw_owner_event = 0;
8433 entry->pw_current_worker = THREAD_NULL;
8434 page_worker_entry_unlock(entry); /* was locked in page_worker_lookup() */
8435 return true;
8436 }
8437
8438 static wait_result_t
8439 vm_page_sleep_with_inheritor(lck_rw_t *lck, lck_sleep_action_t action, event_t event, wait_interrupt_t interruptible)
8440 {
8441 struct page_worker *entry = page_worker_lookup(event, FALSE);
8442 thread_t inheritor = THREAD_NULL;
8443 if (entry != NULL) {
8444 inheritor = entry->pw_current_worker;
8445 page_worker_entry_unlock(entry);
8446 }
8447
8448 wait_result_t ret;
8449 if (inheritor == THREAD_NULL) {
8450 /* no worker was found */
8451 ret = lck_rw_sleep(lck, LCK_SLEEP_PROMOTED_PRI | action, event, interruptible);
8452 } else {
8453 counter_inc(&page_worker_inheritor_sleeps);
8454 ret = lck_rw_sleep_with_inheritor(lck, action, event, inheritor, interruptible, TIMEOUT_WAIT_FOREVER);
8455 }
8456
8457 return ret;
8458 }
8459 #endif /* PAGE_SLEEP_WITH_INHERITOR */
8460
8461 static void
8462 io_reprioritize(mpsc_queue_chain_t elm, __assert_only mpsc_daemon_queue_t dq)
8463 {
8464 assert3p(dq, ==, &io_reprioritize_q);
8465 io_reprioritize_req_t req = mpsc_queue_element(elm, struct io_reprioritize_req, iorr_elm);
8466 vnode_pager_issue_reprioritize_io(req->devvp, req->blkno, req->len, req->priority);
8467 zfree(io_reprioritize_req_zone, req);
8468 }
8469
8470 #endif /* CONFIG_IOSCHED */
8471
8472 #if VM_OBJECT_ACCESS_TRACKING
8473 void
8474 vm_object_access_tracking(
8475 vm_object_t object,
8476 int *access_tracking_p,
8477 uint32_t *access_tracking_reads_p,
8478 uint32_t *access_tracking_writes_p)
8479 {
8480 int access_tracking;
8481
8482 access_tracking = !!*access_tracking_p;
8483
8484 vm_object_lock(object);
8485 *access_tracking_p = object->access_tracking;
8486 if (access_tracking_reads_p) {
8487 *access_tracking_reads_p = object->access_tracking_reads;
8488 }
8489 if (access_tracking_writes_p) {
8490 *access_tracking_writes_p = object->access_tracking_writes;
8491 }
8492 object->access_tracking = access_tracking;
8493 object->access_tracking_reads = 0;
8494 object->access_tracking_writes = 0;
8495 vm_object_unlock(object);
8496
8497 if (access_tracking) {
8498 vm_object_pmap_protect_options(object,
8499 0,
8500 object->vo_size,
8501 PMAP_NULL,
8502 PAGE_SIZE,
8503 0,
8504 VM_PROT_NONE,
8505 0);
8506 }
8507 }
8508 #endif /* VM_OBJECT_ACCESS_TRACKING */
8509
8510 void
8511 vm_object_ledger_tag_ledgers(
8512 vm_object_t object,
8513 int *ledger_idx_volatile,
8514 int *ledger_idx_nonvolatile,
8515 int *ledger_idx_volatile_compressed,
8516 int *ledger_idx_nonvolatile_compressed,
8517 int *ledger_idx_composite,
8518 int *ledger_idx_external_wired,
8519 boolean_t *do_footprint)
8520 {
8521 assert(object->shadow == VM_OBJECT_NULL);
8522
8523 *ledger_idx_volatile = -1;
8524 *ledger_idx_nonvolatile = -1;
8525 *ledger_idx_volatile_compressed = -1;
8526 *ledger_idx_nonvolatile_compressed = -1;
8527 *ledger_idx_composite = -1;
8528 *ledger_idx_external_wired = -1;
8529 *do_footprint = !object->vo_no_footprint;
8530
8531 if (!object->internal) {
8532 switch (object->vo_ledger_tag) {
8533 case VM_LEDGER_TAG_DEFAULT:
8534 if (*do_footprint) {
8535 *ledger_idx_external_wired = task_ledgers.tagged_footprint;
8536 } else {
8537 *ledger_idx_external_wired = task_ledgers.tagged_nofootprint;
8538 }
8539 break;
8540 case VM_LEDGER_TAG_NETWORK:
8541 *do_footprint = FALSE;
8542 *ledger_idx_external_wired = task_ledgers.network_nonvolatile;
8543 break;
8544 case VM_LEDGER_TAG_MEDIA:
8545 if (*do_footprint) {
8546 *ledger_idx_external_wired = task_ledgers.media_footprint;
8547 } else {
8548 *ledger_idx_external_wired = task_ledgers.media_nofootprint;
8549 }
8550 break;
8551 case VM_LEDGER_TAG_GRAPHICS:
8552 if (*do_footprint) {
8553 *ledger_idx_external_wired = task_ledgers.graphics_footprint;
8554 } else {
8555 *ledger_idx_external_wired = task_ledgers.graphics_nofootprint;
8556 }
8557 break;
8558 case VM_LEDGER_TAG_NEURAL:
8559 *ledger_idx_composite = task_ledgers.neural_nofootprint_total;
8560 if (*do_footprint) {
8561 *ledger_idx_external_wired = task_ledgers.neural_footprint;
8562 } else {
8563 *ledger_idx_external_wired = task_ledgers.neural_nofootprint;
8564 }
8565 break;
8566 case VM_LEDGER_TAG_NONE:
8567 default:
8568 panic("%s: external object %p has unsupported ledger_tag %d",
8569 __FUNCTION__, object, object->vo_ledger_tag);
8570 }
8571 return;
8572 }
8573
8574 assert(object->internal);
8575 switch (object->vo_ledger_tag) {
8576 case VM_LEDGER_TAG_NONE:
8577 /*
8578 * Regular purgeable memory:
8579 * counts in footprint only when nonvolatile.
8580 */
8581 *do_footprint = TRUE;
8582 assert(object->purgable != VM_PURGABLE_DENY);
8583 *ledger_idx_volatile = task_ledgers.purgeable_volatile;
8584 *ledger_idx_nonvolatile = task_ledgers.purgeable_nonvolatile;
8585 *ledger_idx_volatile_compressed = task_ledgers.purgeable_volatile_compressed;
8586 *ledger_idx_nonvolatile_compressed = task_ledgers.purgeable_nonvolatile_compressed;
8587 break;
8588 case VM_LEDGER_TAG_DEFAULT:
8589 /*
8590 * "default" tagged memory:
8591 * counts in footprint only when nonvolatile and not marked
8592 * as "no_footprint".
8593 */
8594 *ledger_idx_volatile = task_ledgers.tagged_nofootprint;
8595 *ledger_idx_volatile_compressed = task_ledgers.tagged_nofootprint_compressed;
8596 if (*do_footprint) {
8597 *ledger_idx_nonvolatile = task_ledgers.tagged_footprint;
8598 *ledger_idx_nonvolatile_compressed = task_ledgers.tagged_footprint_compressed;
8599 } else {
8600 *ledger_idx_nonvolatile = task_ledgers.tagged_nofootprint;
8601 *ledger_idx_nonvolatile_compressed = task_ledgers.tagged_nofootprint_compressed;
8602 }
8603 break;
8604 case VM_LEDGER_TAG_NETWORK:
8605 /*
8606 * "network" tagged memory:
8607 * never counts in footprint.
8608 */
8609 *do_footprint = FALSE;
8610 *ledger_idx_volatile = task_ledgers.network_volatile;
8611 *ledger_idx_volatile_compressed = task_ledgers.network_volatile_compressed;
8612 *ledger_idx_nonvolatile = task_ledgers.network_nonvolatile;
8613 *ledger_idx_nonvolatile_compressed = task_ledgers.network_nonvolatile_compressed;
8614 break;
8615 case VM_LEDGER_TAG_MEDIA:
8616 /*
8617 * "media" tagged memory:
8618 * counts in footprint only when nonvolatile and not marked
8619 * as "no footprint".
8620 */
8621 *ledger_idx_volatile = task_ledgers.media_nofootprint;
8622 *ledger_idx_volatile_compressed = task_ledgers.media_nofootprint_compressed;
8623 if (*do_footprint) {
8624 *ledger_idx_nonvolatile = task_ledgers.media_footprint;
8625 *ledger_idx_nonvolatile_compressed = task_ledgers.media_footprint_compressed;
8626 } else {
8627 *ledger_idx_nonvolatile = task_ledgers.media_nofootprint;
8628 *ledger_idx_nonvolatile_compressed = task_ledgers.media_nofootprint_compressed;
8629 }
8630 break;
8631 case VM_LEDGER_TAG_GRAPHICS:
8632 /*
8633 * "graphics" tagged memory:
8634 * counts in footprint only when nonvolatile and not marked
8635 * as "no footprint".
8636 */
8637 *ledger_idx_volatile = task_ledgers.graphics_nofootprint;
8638 *ledger_idx_volatile_compressed = task_ledgers.graphics_nofootprint_compressed;
8639 if (*do_footprint) {
8640 *ledger_idx_nonvolatile = task_ledgers.graphics_footprint;
8641 *ledger_idx_nonvolatile_compressed = task_ledgers.graphics_footprint_compressed;
8642 } else {
8643 *ledger_idx_nonvolatile = task_ledgers.graphics_nofootprint;
8644 *ledger_idx_nonvolatile_compressed = task_ledgers.graphics_nofootprint_compressed;
8645 }
8646 break;
8647 case VM_LEDGER_TAG_NEURAL:
8648 /*
8649 * "neural" tagged memory:
8650 * counts in footprint only when nonvolatile and not marked
8651 * as "no footprint".
8652 */
8653 *ledger_idx_composite = task_ledgers.neural_nofootprint_total;
8654 *ledger_idx_volatile = task_ledgers.neural_nofootprint;
8655 *ledger_idx_volatile_compressed = task_ledgers.neural_nofootprint_compressed;
8656 if (*do_footprint) {
8657 *ledger_idx_nonvolatile = task_ledgers.neural_footprint;
8658 *ledger_idx_nonvolatile_compressed = task_ledgers.neural_footprint_compressed;
8659 } else {
8660 *ledger_idx_nonvolatile = task_ledgers.neural_nofootprint;
8661 *ledger_idx_nonvolatile_compressed = task_ledgers.neural_nofootprint_compressed;
8662 }
8663 break;
8664 default:
8665 panic("%s: object %p has unsupported ledger_tag %d",
8666 __FUNCTION__, object, object->vo_ledger_tag);
8667 }
8668 }
8669
8670 kern_return_t
8671 vm_object_ownership_change(
8672 vm_object_t object,
8673 int new_ledger_tag,
8674 task_t new_owner,
8675 int new_ledger_flags,
8676 boolean_t old_task_objq_locked)
8677 {
8678 int old_ledger_tag;
8679 task_t old_owner;
8680 int resident_count, wired_count;
8681 unsigned int compressed_count;
8682 int ledger_idx_volatile;
8683 int ledger_idx_nonvolatile;
8684 int ledger_idx_volatile_compressed;
8685 int ledger_idx_nonvolatile_compressed;
8686 int ledger_idx;
8687 int ledger_idx_compressed;
8688 int ledger_idx_composite;
8689 int ledger_idx_external_wired;
8690 boolean_t do_footprint, old_no_footprint, new_no_footprint;
8691 boolean_t new_task_objq_locked;
8692
8693 vm_object_lock_assert_exclusive(object);
8694
8695 if (new_owner != VM_OBJECT_OWNER_DISOWNED &&
8696 new_owner != TASK_NULL) {
8697 if (new_ledger_tag == VM_LEDGER_TAG_NONE &&
8698 object->purgable == VM_PURGABLE_DENY) {
8699 /* non-purgeable memory must have a valid non-zero ledger tag */
8700 return KERN_INVALID_ARGUMENT;
8701 }
8702 if (!object->internal
8703 && !memory_object_is_vnode_pager(object->pager)) {
8704 /* non-file-backed "external" objects can't be owned */
8705 return KERN_INVALID_ARGUMENT;
8706 }
8707 }
8708 if (new_owner == VM_OBJECT_OWNER_UNCHANGED) {
8709 /* leave owner unchanged */
8710 new_owner = VM_OBJECT_OWNER(object);
8711 }
8712 if (new_ledger_tag == VM_LEDGER_TAG_UNCHANGED) {
8713 /* leave ledger_tag unchanged */
8714 new_ledger_tag = object->vo_ledger_tag;
8715 }
8716 if (new_ledger_tag < 0 ||
8717 new_ledger_tag > VM_LEDGER_TAG_MAX) {
8718 return KERN_INVALID_ARGUMENT;
8719 }
8720 if (new_ledger_flags & ~VM_LEDGER_FLAGS_ALL) {
8721 return KERN_INVALID_ARGUMENT;
8722 }
8723 if (object->internal &&
8724 object->vo_ledger_tag == VM_LEDGER_TAG_NONE &&
8725 object->purgable == VM_PURGABLE_DENY) {
8726 /*
8727 * This VM object is neither ledger-tagged nor purgeable.
8728 * We can convert it to "ledger tag" ownership iff it
8729 * has not been used at all yet (no resident pages and
8730 * no pager) and it's going to be assigned to a valid task.
8731 */
8732 if (object->resident_page_count != 0 ||
8733 object->pager != NULL ||
8734 object->pager_created ||
8735 os_ref_get_count_raw(&object->ref_count) != 1 ||
8736 object->vo_owner != TASK_NULL ||
8737 object->copy_strategy != MEMORY_OBJECT_COPY_NONE ||
8738 new_owner == TASK_NULL) {
8739 return KERN_FAILURE;
8740 }
8741 }
8742
8743 if (new_ledger_flags & VM_LEDGER_FLAG_NO_FOOTPRINT) {
8744 new_no_footprint = TRUE;
8745 } else {
8746 new_no_footprint = FALSE;
8747 }
8748 #if __arm64__
8749 if (!new_no_footprint &&
8750 object->purgable != VM_PURGABLE_DENY &&
8751 new_owner != TASK_NULL &&
8752 new_owner != VM_OBJECT_OWNER_DISOWNED &&
8753 new_owner->task_legacy_footprint) {
8754 /*
8755 * This task has been granted "legacy footprint" and should
8756 * not be charged for its IOKit purgeable memory. Since we
8757 * might now change the accounting of such memory to the
8758 * "graphics" ledger, for example, give it the "no footprint"
8759 * option.
8760 */
8761 new_no_footprint = TRUE;
8762 }
8763 #endif /* __arm64__ */
8764 assert(object->copy_strategy != MEMORY_OBJECT_COPY_SYMMETRIC);
8765 assert(object->shadow == VM_OBJECT_NULL);
8766 if (object->internal) {
8767 assert(object->copy_strategy == MEMORY_OBJECT_COPY_NONE);
8768 assert(object->vo_copy == VM_OBJECT_NULL);
8769 }
8770
8771 old_ledger_tag = object->vo_ledger_tag;
8772 old_no_footprint = object->vo_no_footprint;
8773 old_owner = VM_OBJECT_OWNER(object);
8774
8775 if (__improbable(vm_debug_events)) {
8776 DTRACE_VM8(object_ownership_change,
8777 vm_object_t, object,
8778 task_t, old_owner,
8779 int, old_ledger_tag,
8780 int, old_no_footprint,
8781 task_t, new_owner,
8782 int, new_ledger_tag,
8783 int, new_no_footprint,
8784 int, VM_OBJECT_ID(object));
8785 }
8786
8787 resident_count = object->resident_page_count - object->wired_page_count;
8788 wired_count = object->wired_page_count;
8789 if (object->internal) {
8790 compressed_count = vm_compressor_pager_get_count(object->pager);
8791 } else {
8792 compressed_count = 0;
8793 }
8794
8795 /*
8796 * Deal with the old owner and/or ledger tag, if needed.
8797 */
8798 if (old_owner != TASK_NULL &&
8799 ((old_owner != new_owner) /* new owner ... */
8800 || /* ... or ... */
8801 (old_no_footprint != new_no_footprint) /* new "no_footprint" */
8802 || /* ... or ... */
8803 old_ledger_tag != new_ledger_tag)) { /* ... new ledger */
8804 /*
8805 * Take this object off of the old owner's ledgers.
8806 */
8807 vm_object_ledger_tag_ledgers(object,
8808 &ledger_idx_volatile,
8809 &ledger_idx_nonvolatile,
8810 &ledger_idx_volatile_compressed,
8811 &ledger_idx_nonvolatile_compressed,
8812 &ledger_idx_composite,
8813 &ledger_idx_external_wired,
8814 &do_footprint);
8815 if (object->internal) {
8816 if (object->purgable == VM_PURGABLE_VOLATILE ||
8817 object->purgable == VM_PURGABLE_EMPTY) {
8818 ledger_idx = ledger_idx_volatile;
8819 ledger_idx_compressed = ledger_idx_volatile_compressed;
8820 } else {
8821 ledger_idx = ledger_idx_nonvolatile;
8822 ledger_idx_compressed = ledger_idx_nonvolatile_compressed;
8823 }
8824 if (resident_count) {
8825 /*
8826 * Adjust the appropriate old owners's ledgers by the
8827 * number of resident pages.
8828 */
8829 ledger_debit(old_owner->ledger,
8830 ledger_idx,
8831 ptoa_64(resident_count));
8832 /* adjust old owner's footprint */
8833 if (object->purgable != VM_PURGABLE_VOLATILE &&
8834 object->purgable != VM_PURGABLE_EMPTY) {
8835 if (do_footprint) {
8836 ledger_debit(old_owner->ledger,
8837 task_ledgers.phys_footprint,
8838 ptoa_64(resident_count));
8839 } else if (ledger_idx_composite != -1) {
8840 ledger_debit(old_owner->ledger,
8841 ledger_idx_composite,
8842 ptoa_64(resident_count));
8843 }
8844 }
8845 }
8846 if (wired_count) {
8847 /* wired pages are always nonvolatile */
8848 ledger_debit(old_owner->ledger,
8849 ledger_idx_nonvolatile,
8850 ptoa_64(wired_count));
8851 if (do_footprint) {
8852 ledger_debit(old_owner->ledger,
8853 task_ledgers.phys_footprint,
8854 ptoa_64(wired_count));
8855 } else if (ledger_idx_composite != -1) {
8856 ledger_debit(old_owner->ledger,
8857 ledger_idx_composite,
8858 ptoa_64(wired_count));
8859 }
8860 }
8861 if (compressed_count) {
8862 /*
8863 * Adjust the appropriate old owner's ledgers
8864 * by the number of compressed pages.
8865 */
8866 ledger_debit(old_owner->ledger,
8867 ledger_idx_compressed,
8868 ptoa_64(compressed_count));
8869 if (object->purgable != VM_PURGABLE_VOLATILE &&
8870 object->purgable != VM_PURGABLE_EMPTY) {
8871 if (do_footprint) {
8872 ledger_debit(old_owner->ledger,
8873 task_ledgers.phys_footprint,
8874 ptoa_64(compressed_count));
8875 } else if (ledger_idx_composite != -1) {
8876 ledger_debit(old_owner->ledger,
8877 ledger_idx_composite,
8878 ptoa_64(compressed_count));
8879 }
8880 }
8881 }
8882 } else {
8883 /* external but owned object: count wired pages */
8884 if (wired_count) {
8885 ledger_debit(old_owner->ledger,
8886 ledger_idx_external_wired,
8887 ptoa_64(wired_count));
8888 if (do_footprint) {
8889 ledger_debit(old_owner->ledger,
8890 task_ledgers.phys_footprint,
8891 ptoa_64(wired_count));
8892 } else if (ledger_idx_composite != -1) {
8893 ledger_debit(old_owner->ledger,
8894 ledger_idx_composite,
8895 ptoa_64(wired_count));
8896 }
8897 }
8898 }
8899 if (old_owner != new_owner) {
8900 /* remove object from old_owner's list of owned objects */
8901 DTRACE_VM2(object_owner_remove,
8902 vm_object_t, object,
8903 task_t, old_owner);
8904 if (!old_task_objq_locked) {
8905 task_objq_lock(old_owner);
8906 }
8907 old_owner->task_owned_objects--;
8908 queue_remove(&old_owner->task_objq, object,
8909 vm_object_t, task_objq);
8910 switch (object->purgable) {
8911 case VM_PURGABLE_NONVOLATILE:
8912 case VM_PURGABLE_EMPTY:
8913 vm_purgeable_nonvolatile_owner_update(old_owner,
8914 -1);
8915 break;
8916 case VM_PURGABLE_VOLATILE:
8917 vm_purgeable_volatile_owner_update(old_owner,
8918 -1);
8919 break;
8920 default:
8921 break;
8922 }
8923 if (!old_task_objq_locked) {
8924 task_objq_unlock(old_owner);
8925 }
8926 }
8927 }
8928
8929 /*
8930 * Switch to new ledger tag and/or owner.
8931 */
8932
8933 new_task_objq_locked = FALSE;
8934 if (new_owner != old_owner &&
8935 new_owner != TASK_NULL &&
8936 new_owner != VM_OBJECT_OWNER_DISOWNED) {
8937 /*
8938 * If the new owner is not accepting new objects ("disowning"),
8939 * the object becomes "disowned" and will be added to
8940 * the kernel's task_objq.
8941 *
8942 * Check first without locking, to avoid blocking while the
8943 * task is disowning its objects.
8944 */
8945 if (new_owner->task_objects_disowning) {
8946 new_owner = VM_OBJECT_OWNER_DISOWNED;
8947 } else {
8948 task_objq_lock(new_owner);
8949 /* check again now that we have the lock */
8950 if (new_owner->task_objects_disowning) {
8951 new_owner = VM_OBJECT_OWNER_DISOWNED;
8952 task_objq_unlock(new_owner);
8953 } else {
8954 new_task_objq_locked = TRUE;
8955 }
8956 }
8957 }
8958
8959 object->vo_ledger_tag = new_ledger_tag;
8960 object->vo_owner = new_owner;
8961 object->vo_no_footprint = new_no_footprint;
8962
8963 if (new_owner == VM_OBJECT_OWNER_DISOWNED) {
8964 /*
8965 * Disowned objects are added to the kernel's task_objq but
8966 * are marked as owned by "VM_OBJECT_OWNER_DISOWNED" to
8967 * differentiate them from objects intentionally owned by
8968 * the kernel.
8969 */
8970 assert(old_owner != kernel_task);
8971 new_owner = kernel_task;
8972 assert(!new_task_objq_locked);
8973 task_objq_lock(new_owner);
8974 new_task_objq_locked = TRUE;
8975 }
8976
8977 /*
8978 * Deal with the new owner and/or ledger tag, if needed.
8979 */
8980 if (new_owner != TASK_NULL &&
8981 ((new_owner != old_owner) /* new owner ... */
8982 || /* ... or ... */
8983 (new_no_footprint != old_no_footprint) /* ... new "no_footprint" */
8984 || /* ... or ... */
8985 new_ledger_tag != old_ledger_tag)) { /* ... new ledger */
8986 /*
8987 * Add this object to the new owner's ledgers.
8988 */
8989 vm_object_ledger_tag_ledgers(object,
8990 &ledger_idx_volatile,
8991 &ledger_idx_nonvolatile,
8992 &ledger_idx_volatile_compressed,
8993 &ledger_idx_nonvolatile_compressed,
8994 &ledger_idx_composite,
8995 &ledger_idx_external_wired,
8996 &do_footprint);
8997 if (object->internal) {
8998 if (object->purgable == VM_PURGABLE_VOLATILE ||
8999 object->purgable == VM_PURGABLE_EMPTY) {
9000 ledger_idx = ledger_idx_volatile;
9001 ledger_idx_compressed = ledger_idx_volatile_compressed;
9002 } else {
9003 ledger_idx = ledger_idx_nonvolatile;
9004 ledger_idx_compressed = ledger_idx_nonvolatile_compressed;
9005 }
9006 if (resident_count) {
9007 /*
9008 * Adjust the appropriate new owners's ledgers by the
9009 * number of resident pages.
9010 */
9011 ledger_credit(new_owner->ledger,
9012 ledger_idx,
9013 ptoa_64(resident_count));
9014 /* adjust new owner's footprint */
9015 if (object->purgable != VM_PURGABLE_VOLATILE &&
9016 object->purgable != VM_PURGABLE_EMPTY) {
9017 if (do_footprint) {
9018 ledger_credit(new_owner->ledger,
9019 task_ledgers.phys_footprint,
9020 ptoa_64(resident_count));
9021 } else if (ledger_idx_composite != -1) {
9022 ledger_credit(new_owner->ledger,
9023 ledger_idx_composite,
9024 ptoa_64(resident_count));
9025 }
9026 }
9027 }
9028 if (wired_count) {
9029 /* wired pages are always nonvolatile */
9030 ledger_credit(new_owner->ledger,
9031 ledger_idx_nonvolatile,
9032 ptoa_64(wired_count));
9033 if (do_footprint) {
9034 ledger_credit(new_owner->ledger,
9035 task_ledgers.phys_footprint,
9036 ptoa_64(wired_count));
9037 } else if (ledger_idx_composite != -1) {
9038 ledger_credit(new_owner->ledger,
9039 ledger_idx_composite,
9040 ptoa_64(wired_count));
9041 }
9042 }
9043 if (compressed_count) {
9044 /*
9045 * Adjust the new owner's ledgers by the number of
9046 * compressed pages.
9047 */
9048 ledger_credit(new_owner->ledger,
9049 ledger_idx_compressed,
9050 ptoa_64(compressed_count));
9051 if (object->purgable != VM_PURGABLE_VOLATILE &&
9052 object->purgable != VM_PURGABLE_EMPTY) {
9053 if (do_footprint) {
9054 ledger_credit(new_owner->ledger,
9055 task_ledgers.phys_footprint,
9056 ptoa_64(compressed_count));
9057 } else if (ledger_idx_composite != -1) {
9058 ledger_credit(new_owner->ledger,
9059 ledger_idx_composite,
9060 ptoa_64(compressed_count));
9061 }
9062 }
9063 }
9064 } else {
9065 /* external but owned object: count wired pages */
9066 if (wired_count) {
9067 ledger_credit(new_owner->ledger,
9068 ledger_idx_external_wired,
9069 ptoa_64(wired_count));
9070 if (do_footprint) {
9071 ledger_credit(new_owner->ledger,
9072 task_ledgers.phys_footprint,
9073 ptoa_64(wired_count));
9074 } else if (ledger_idx_composite != -1) {
9075 ledger_credit(new_owner->ledger,
9076 ledger_idx_composite,
9077 ptoa_64(wired_count));
9078 }
9079 }
9080 }
9081 if (new_owner != old_owner) {
9082 /* add object to new_owner's list of owned objects */
9083 DTRACE_VM2(object_owner_add,
9084 vm_object_t, object,
9085 task_t, new_owner);
9086 assert(new_task_objq_locked);
9087 new_owner->task_owned_objects++;
9088 queue_enter(&new_owner->task_objq, object,
9089 vm_object_t, task_objq);
9090 switch (object->purgable) {
9091 case VM_PURGABLE_NONVOLATILE:
9092 case VM_PURGABLE_EMPTY:
9093 vm_purgeable_nonvolatile_owner_update(new_owner,
9094 +1);
9095 break;
9096 case VM_PURGABLE_VOLATILE:
9097 vm_purgeable_volatile_owner_update(new_owner,
9098 +1);
9099 break;
9100 default:
9101 break;
9102 }
9103 }
9104 }
9105
9106 if (new_task_objq_locked) {
9107 task_objq_unlock(new_owner);
9108 }
9109
9110 return KERN_SUCCESS;
9111 }
9112
9113 void
9114 vm_owned_objects_disown(
9115 task_t task)
9116 {
9117 vm_object_t next_object;
9118 vm_object_t object;
9119 int collisions;
9120 kern_return_t kr;
9121
9122 if (task == NULL) {
9123 return;
9124 }
9125
9126 collisions = 0;
9127
9128 again:
9129 if (task->task_objects_disowned) {
9130 /* task has already disowned its owned objects */
9131 assert(task->task_volatile_objects == 0);
9132 assert(task->task_nonvolatile_objects == 0);
9133 assert(task->task_owned_objects == 0);
9134 return;
9135 }
9136
9137 task_objq_lock(task);
9138
9139 task->task_objects_disowning = TRUE;
9140
9141 for (object = (vm_object_t) queue_first(&task->task_objq);
9142 !queue_end(&task->task_objq, (queue_entry_t) object);
9143 object = next_object) {
9144 if (task->task_nonvolatile_objects == 0 &&
9145 task->task_volatile_objects == 0 &&
9146 task->task_owned_objects == 0) {
9147 /* no more objects owned by "task" */
9148 break;
9149 }
9150
9151 next_object = (vm_object_t) queue_next(&object->task_objq);
9152
9153 #if DEBUG
9154 assert(object->vo_purgeable_volatilizer == NULL);
9155 #endif /* DEBUG */
9156 assert(object->vo_owner == task);
9157 if (!vm_object_lock_try(object)) {
9158 task_objq_unlock(task);
9159 mutex_pause(collisions++);
9160 goto again;
9161 }
9162 /* transfer ownership to the kernel */
9163 assert(VM_OBJECT_OWNER(object) != kernel_task);
9164 kr = vm_object_ownership_change(
9165 object,
9166 object->vo_ledger_tag, /* unchanged */
9167 VM_OBJECT_OWNER_DISOWNED, /* new owner */
9168 0, /* new_ledger_flags */
9169 TRUE); /* old_owner->task_objq locked */
9170 assert(kr == KERN_SUCCESS);
9171 assert(object->vo_owner == VM_OBJECT_OWNER_DISOWNED);
9172 vm_object_unlock(object);
9173 }
9174
9175 if (__improbable(task->task_owned_objects != 0)) {
9176 panic("%s(%p): volatile=%d nonvolatile=%d owned=%d q=%p q_first=%p q_last=%p",
9177 __FUNCTION__,
9178 task,
9179 task->task_volatile_objects,
9180 task->task_nonvolatile_objects,
9181 task->task_owned_objects,
9182 &task->task_objq,
9183 queue_first(&task->task_objq),
9184 queue_last(&task->task_objq));
9185 }
9186
9187 /* there shouldn't be any objects owned by task now */
9188 assert(task->task_volatile_objects == 0);
9189 assert(task->task_nonvolatile_objects == 0);
9190 assert(task->task_owned_objects == 0);
9191 assert(task->task_objects_disowning);
9192
9193 /* and we don't need to try and disown again */
9194 task->task_objects_disowned = TRUE;
9195
9196 task_objq_unlock(task);
9197 }
9198
9199 void
9200 vm_object_wired_page_update_ledgers(
9201 vm_object_t object,
9202 int64_t wired_delta)
9203 {
9204 task_t owner;
9205
9206 vm_object_lock_assert_exclusive(object);
9207 if (wired_delta == 0) {
9208 /* no change in number of wired pages */
9209 return;
9210 }
9211 if (object->internal) {
9212 /* no extra accounting needed for internal objects */
9213 return;
9214 }
9215 if (!object->vo_ledger_tag) {
9216 /* external object but not owned: no extra accounting */
9217 return;
9218 }
9219
9220 /*
9221 * For an explicitly-owned external VM object, account for
9222 * wired pages in one of the owner's ledgers.
9223 */
9224 owner = VM_OBJECT_OWNER(object);
9225 if (owner) {
9226 int ledger_idx_volatile;
9227 int ledger_idx_nonvolatile;
9228 int ledger_idx_volatile_compressed;
9229 int ledger_idx_nonvolatile_compressed;
9230 int ledger_idx_composite;
9231 int ledger_idx_external_wired;
9232 boolean_t do_footprint;
9233
9234 /* ask which ledgers need an update */
9235 vm_object_ledger_tag_ledgers(object,
9236 &ledger_idx_volatile,
9237 &ledger_idx_nonvolatile,
9238 &ledger_idx_volatile_compressed,
9239 &ledger_idx_nonvolatile_compressed,
9240 &ledger_idx_composite,
9241 &ledger_idx_external_wired,
9242 &do_footprint);
9243 if (wired_delta > 0) {
9244 /* more external wired bytes */
9245 ledger_credit(owner->ledger,
9246 ledger_idx_external_wired,
9247 ptoa(wired_delta));
9248 if (do_footprint) {
9249 /* more footprint */
9250 ledger_credit(owner->ledger,
9251 task_ledgers.phys_footprint,
9252 ptoa(wired_delta));
9253 } else if (ledger_idx_composite != -1) {
9254 ledger_credit(owner->ledger,
9255 ledger_idx_composite,
9256 ptoa(wired_delta));
9257 }
9258 } else {
9259 /* less external wired bytes */
9260 ledger_debit(owner->ledger,
9261 ledger_idx_external_wired,
9262 ptoa(-wired_delta));
9263 if (do_footprint) {
9264 /* more footprint */
9265 ledger_debit(owner->ledger,
9266 task_ledgers.phys_footprint,
9267 ptoa(-wired_delta));
9268 } else if (ledger_idx_composite != -1) {
9269 ledger_debit(owner->ledger,
9270 ledger_idx_composite,
9271 ptoa(-wired_delta));
9272 }
9273 }
9274 }
9275 }
9276