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