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