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