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