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