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