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