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