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