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