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