xref: /xnu-11417.140.69/osfmk/vm/vm_compressor.c (revision 43a90889846e00bfb5cf1d255cdc0a701a1e05a4)
1 /*
2  * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 
29 #include <vm/vm_compressor_internal.h>
30 
31 #if CONFIG_PHANTOM_CACHE
32 #include <vm/vm_phantom_cache_internal.h>
33 #endif
34 
35 #include <vm/vm_map_xnu.h>
36 #include <vm/vm_pageout_xnu.h>
37 #include <vm/vm_map_internal.h>
38 #include <vm/memory_object.h>
39 #include <vm/vm_compressor_algorithms_internal.h>
40 #include <vm/vm_compressor_backing_store_internal.h>
41 #include <vm/vm_fault.h>
42 #include <vm/vm_protos.h>
43 #include <vm/vm_kern_xnu.h>
44 #include <vm/vm_compressor_pager_internal.h>
45 #include <vm/vm_iokit.h>
46 #include <vm/vm_far.h>
47 #include <mach/mach_host.h>             /* for host_info() */
48 #if DEVELOPMENT || DEBUG
49 #include <kern/hvg_hypercall.h>
50 #include <vm/vm_compressor_info.h>         /* for c_segment_info */
51 #endif
52 #include <kern/ledger.h>
53 #include <kern/policy_internal.h>
54 #include <kern/thread_group.h>
55 #include <san/kasan.h>
56 #include <sys/kern_memorystatus_xnu.h>
57 #include <os/atomic_private.h>
58 #include <os/log.h>
59 #include <pexpert/pexpert.h>
60 #include <pexpert/device_tree.h>
61 
62 #if defined(__x86_64__)
63 #include <i386/misc_protos.h>
64 #endif
65 #if defined(__arm64__)
66 #include <arm/machine_routines.h>
67 #endif
68 
69 #include <IOKit/IOHibernatePrivate.h>
70 
71 /*
72  * The segment buffer size is a tradeoff.
73  * A larger buffer leads to faster I/O throughput, better compression ratios
74  * (since fewer bytes are wasted at the end of the segment),
75  * and less overhead (both in time and space).
76  * However, a smaller buffer causes less swap when the system is overcommited
77  * b/c a higher percentage of the swapped-in segment is definitely accessed
78  * before it goes back out to storage.
79  *
80  * So on systems without swap, a larger segment is a clear win.
81  * On systems with swap, the choice is murkier. Empirically, we've
82  * found that a 64KB segment provides a better tradeoff both in terms of
83  * performance and swap writes than a 256KB segment on systems with fast SSDs
84  * and a HW compression block.
85  */
86 #define C_SEG_BUFSIZE_ARM_SWAP (1024 * 64)
87 #if XNU_TARGET_OS_OSX && defined(__arm64__)
88 #define C_SEG_BUFSIZE_DEFAULT C_SEG_BUFSIZE_ARM_SWAP
89 #else
90 #define C_SEG_BUFSIZE_DEFAULT (1024 * 256)
91 #endif /* TARGET_OS_OSX && defined(__arm64__) */
92 uint32_t c_seg_bufsize;
93 
94 uint32_t c_seg_max_pages; /* maximum number of pages the compressed data of a segment can take  */
95 uint32_t c_seg_off_limit; /* if we've reached this size while filling the segment, don't bother trying to fill anymore
96                            * because it's unlikely to succeed, in units of uint32_t, same as c_nextoffset */
97 uint32_t c_seg_allocsize, c_seg_slot_var_array_min_len;
98 
99 extern boolean_t vm_darkwake_mode;
100 extern zone_t vm_page_zone;
101 
102 #if DEVELOPMENT || DEBUG
103 /* sysctl defined in bsd/dev/arm64/sysctl.c */
104 static event_t debug_cseg_wait_event = NULL;
105 #endif /* DEVELOPMENT || DEBUG */
106 
107 #if CONFIG_FREEZE
108 bool freezer_incore_cseg_acct = TRUE; /* Only count incore compressed memory for jetsams. */
109 #endif /* CONFIG_FREEZE */
110 
111 #if POPCOUNT_THE_COMPRESSED_DATA
112 boolean_t popcount_c_segs = TRUE;
113 
114 static inline uint32_t
vmc_pop(uintptr_t ins,int sz)115 vmc_pop(uintptr_t ins, int sz)
116 {
117 	uint32_t rv = 0;
118 
119 	if (__probable(popcount_c_segs == FALSE)) {
120 		return 0xDEAD707C;
121 	}
122 
123 	while (sz >= 16) {
124 		uint32_t rv1, rv2;
125 		uint64_t *ins64 = (uint64_t *) ins;
126 		uint64_t *ins642 = (uint64_t *) (ins + 8);
127 		rv1 = __builtin_popcountll(*ins64);
128 		rv2 = __builtin_popcountll(*ins642);
129 		rv += rv1 + rv2;
130 		sz -= 16;
131 		ins += 16;
132 	}
133 
134 	while (sz >= 4) {
135 		uint32_t *ins32 = (uint32_t *) ins;
136 		rv += __builtin_popcount(*ins32);
137 		sz -= 4;
138 		ins += 4;
139 	}
140 
141 	while (sz > 0) {
142 		char *ins8 = (char *)ins;
143 		rv += __builtin_popcount(*ins8);
144 		sz--;
145 		ins++;
146 	}
147 	return rv;
148 }
149 #endif
150 
151 #if VALIDATE_C_SEGMENTS
152 boolean_t validate_c_segs = TRUE;
153 #endif
154 /*
155  * vm_compressor_mode has a hierarchy of control to set its value.
156  * boot-args are checked first, then device-tree, and finally
157  * the default value that is defined below. See vm_fault_init() for
158  * the boot-arg & device-tree code.
159  */
160 
161 #if !XNU_TARGET_OS_OSX
162 
163 #if CONFIG_FREEZE
164 int     vm_compressor_mode = VM_PAGER_FREEZER_DEFAULT;
165 struct  freezer_context freezer_context_global;
166 #else /* CONFIG_FREEZE */
167 int     vm_compressor_mode = VM_PAGER_NOT_CONFIGURED;
168 #endif /* CONFIG_FREEZE */
169 
170 #else /* !XNU_TARGET_OS_OSX */
171 int             vm_compressor_mode = VM_PAGER_COMPRESSOR_WITH_SWAP;
172 
173 #endif /* !XNU_TARGET_OS_OSX */
174 
175 TUNABLE(uint32_t, vm_compression_limit, "vm_compression_limit", 0);
176 int             vm_compressor_is_active = 0;
177 int             vm_compressor_available = 0;
178 
179 extern uint64_t vm_swap_get_max_configured_space(void);
180 extern void     vm_pageout_io_throttle(void);
181 
182 #if CHECKSUM_THE_DATA || CHECKSUM_THE_SWAP || CHECKSUM_THE_COMPRESSED_DATA
183 extern unsigned int hash_string(char *cp, int len);
184 static unsigned int vmc_hash(char *, int);
185 boolean_t checksum_c_segs = TRUE;
186 
187 unsigned int
vmc_hash(char * cp,int len)188 vmc_hash(char *cp, int len)
189 {
190 	unsigned int result;
191 	if (__probable(checksum_c_segs == FALSE)) {
192 		return 0xDEAD7A37;
193 	}
194 	vm_memtag_disable_checking();
195 	result = hash_string(cp, len);
196 	vm_memtag_enable_checking();
197 	return result;
198 }
199 #endif
200 
201 #define UNPACK_C_SIZE(cs)       ((cs->c_size == (PAGE_SIZE-1)) ? PAGE_SIZE : cs->c_size)
202 #define PACK_C_SIZE(cs, size)   (cs->c_size = ((size == PAGE_SIZE) ? PAGE_SIZE - 1 : size))
203 
204 
205 struct c_sv_hash_entry {
206 	union {
207 		struct  {
208 			uint32_t        c_sv_he_ref;
209 			uint32_t        c_sv_he_data;
210 		} c_sv_he;
211 		uint64_t        c_sv_he_record;
212 	} c_sv_he_un;
213 };
214 
215 #define he_ref  c_sv_he_un.c_sv_he.c_sv_he_ref
216 #define he_data c_sv_he_un.c_sv_he.c_sv_he_data
217 #define he_record c_sv_he_un.c_sv_he_record
218 
219 #define C_SV_HASH_MAX_MISS      32
220 #define C_SV_HASH_SIZE          ((1 << 10))
221 #define C_SV_HASH_MASK          ((1 << 10) - 1)
222 
223 #if CONFIG_TRACK_UNMODIFIED_ANON_PAGES
224 #define C_SV_CSEG_ID            ((1 << 21) - 1)
225 #else /* CONFIG_TRACK_UNMODIFIED_ANON_PAGES */
226 #define C_SV_CSEG_ID            ((1 << 22) - 1)
227 #endif /* CONFIG_TRACK_UNMODIFIED_ANON_PAGES */
228 
229 /* elements of c_segments array */
230 union c_segu {
231 	c_segment_t     c_seg;
232 	uintptr_t       c_segno;  /* index of the next element in the segments free-list, c_free_segno_head is the head */
233 };
234 
235 #define C_SLOT_ASSERT_PACKABLE(ptr) \
236 	VM_ASSERT_POINTER_PACKABLE((vm_offset_t)(ptr), C_SLOT_PACKED_PTR);
237 
238 #define C_SLOT_PACK_PTR(ptr) \
239 	VM_PACK_POINTER((vm_offset_t)(ptr), C_SLOT_PACKED_PTR)
240 
241 #define C_SLOT_UNPACK_PTR(cslot) \
242 	(c_slot_mapping_t)VM_UNPACK_POINTER((cslot)->c_packed_ptr, C_SLOT_PACKED_PTR)
243 
244 /* for debugging purposes */
245 SECURITY_READ_ONLY_EARLY(vm_packing_params_t) c_slot_packing_params =
246     VM_PACKING_PARAMS(C_SLOT_PACKED_PTR);
247 
248 uint32_t        c_segment_count = 0;       /* count all allocated c_segments in all queues */
249 uint32_t        c_segment_count_max = 0;   /* maximum c_segment_count has ever been */
250 
251 uint64_t        c_generation_id = 0;
252 uint64_t        c_generation_id_flush_barrier;
253 
254 boolean_t       hibernate_no_swapspace = FALSE;
255 boolean_t       hibernate_flush_timed_out = FALSE;
256 clock_sec_t     hibernate_flushing_deadline = 0;
257 
258 #if RECORD_THE_COMPRESSED_DATA
259 /* buffer used as an intermediate stage before writing to file */
260 char    *c_compressed_record_sbuf;  /* start */
261 char    *c_compressed_record_ebuf;  /* end */
262 char    *c_compressed_record_cptr;  /* next buffered write */
263 #endif
264 
265 /* the different queues a c_segment can be in via c_age_list */
266 queue_head_t    c_age_list_head;
267 queue_head_t    c_early_swappedin_list_head, c_regular_swappedin_list_head, c_late_swappedin_list_head;
268 queue_head_t    c_early_swapout_list_head, c_regular_swapout_list_head, c_late_swapout_list_head;
269 queue_head_t    c_swapio_list_head;
270 queue_head_t    c_swappedout_list_head;
271 queue_head_t    c_swappedout_sparse_list_head;
272 queue_head_t    c_major_list_head;
273 queue_head_t    c_filling_list_head;
274 queue_head_t    c_bad_list_head;
275 
276 /* count of each of the queues above */
277 uint32_t        c_age_count = 0;
278 uint32_t        c_early_swappedin_count = 0, c_regular_swappedin_count = 0, c_late_swappedin_count = 0;
279 uint32_t        c_early_swapout_count = 0, c_regular_swapout_count = 0, c_late_swapout_count = 0;
280 uint32_t        c_swapio_count = 0;
281 uint32_t        c_swappedout_count = 0;
282 uint32_t        c_swappedout_sparse_count = 0;
283 uint32_t        c_major_count = 0;
284 uint32_t        c_filling_count = 0;
285 uint32_t        c_empty_count = 0;
286 uint32_t        c_bad_count = 0;
287 
288 /* a c_segment can be in the minor-compact queue as well as one of the above ones, via c_list */
289 queue_head_t    c_minor_list_head;
290 uint32_t        c_minor_count = 0;
291 
292 int             c_overage_swapped_count = 0;
293 int             c_overage_swapped_limit = 0;
294 
295 int             c_seg_fixed_array_len;   /* number of slots in the c_segment inline slots array */
296 union  c_segu   *c_segments;             /* array of all c_segments, not all of it may be populated */
297 vm_offset_t     c_buffers;               /* starting address of all compressed data pointed to by c_segment.c_store.c_buffer */
298 vm_size_t       c_buffers_size;          /* total size allocated in c_buffers */
299 caddr_t         c_segments_next_page;    /* next page to populate for extending c_segments */
300 boolean_t       c_segments_busy;
301 uint32_t        c_segments_available;    /* how many segments are in populated memory (used or free), populated size of c_segments array */
302 uint32_t        c_segments_limit;        /* max size of c_segments array */
303 uint32_t        c_segments_nearing_limit;
304 
305 uint32_t        c_segment_svp_in_hash;
306 uint32_t        c_segment_svp_hash_succeeded;
307 uint32_t        c_segment_svp_hash_failed;
308 uint32_t        c_segment_svp_zero_compressions;
309 uint32_t        c_segment_svp_nonzero_compressions;
310 uint32_t        c_segment_svp_zero_decompressions;
311 uint32_t        c_segment_svp_nonzero_decompressions;
312 
313 uint32_t        c_segment_noncompressible_pages;
314 
315 uint32_t        c_segment_pages_compressed = 0; /* Tracks # of uncompressed pages fed into the compressor, including SV (single value) pages */
316 #if CONFIG_FREEZE
317 int32_t         c_segment_pages_compressed_incore = 0; /* Tracks # of uncompressed pages fed into the compressor that are in memory */
318 int32_t         c_segment_pages_compressed_incore_late_swapout = 0; /* Tracks # of uncompressed pages fed into the compressor that are in memory and tagged for swapout */
319 uint32_t        c_segments_incore_limit = 0; /* Tracks # of segments allowed to be in-core. Based on compressor pool size */
320 #endif /* CONFIG_FREEZE */
321 
322 uint32_t        c_segment_pages_compressed_limit;
323 uint32_t        c_segment_pages_compressed_nearing_limit;
324 uint32_t        c_free_segno_head = (uint32_t)-1;   /* head of free list of c_segment pointers in c_segments */
325 
326 uint32_t        vm_compressor_minorcompact_threshold_divisor = 10;
327 uint32_t        vm_compressor_majorcompact_threshold_divisor = 10;
328 uint32_t        vm_compressor_unthrottle_threshold_divisor = 10;
329 uint32_t        vm_compressor_catchup_threshold_divisor = 10;
330 
331 uint32_t        vm_compressor_minorcompact_threshold_divisor_overridden = 0;
332 uint32_t        vm_compressor_majorcompact_threshold_divisor_overridden = 0;
333 uint32_t        vm_compressor_unthrottle_threshold_divisor_overridden = 0;
334 uint32_t        vm_compressor_catchup_threshold_divisor_overridden = 0;
335 
336 #define         C_SEGMENTS_PER_PAGE     (PAGE_SIZE / sizeof(union c_segu))
337 
338 LCK_GRP_DECLARE(vm_compressor_lck_grp, "vm_compressor");
339 LCK_RW_DECLARE(c_master_lock, &vm_compressor_lck_grp);
340 LCK_MTX_DECLARE(c_list_lock_storage, &vm_compressor_lck_grp);
341 
342 boolean_t       decompressions_blocked = FALSE;
343 
344 zone_t          compressor_segment_zone;
345 int             c_compressor_swap_trigger = 0;
346 
347 uint32_t        compressor_cpus;
348 char            *compressor_scratch_bufs;
349 
350 struct vm_compressor_kdp_state vm_compressor_kdp_state;
351 
352 clock_sec_t     start_of_sample_period_sec = 0;
353 clock_nsec_t    start_of_sample_period_nsec = 0;
354 clock_sec_t     start_of_eval_period_sec = 0;
355 clock_nsec_t    start_of_eval_period_nsec = 0;
356 uint32_t        sample_period_decompression_count = 0;
357 uint32_t        sample_period_compression_count = 0;
358 uint32_t        last_eval_decompression_count = 0;
359 uint32_t        last_eval_compression_count = 0;
360 
361 #define         DECOMPRESSION_SAMPLE_MAX_AGE            (60 * 30)
362 
363 boolean_t       vm_swapout_ripe_segments = FALSE;
364 uint32_t        vm_ripe_target_age = (60 * 60 * 48);
365 
366 uint32_t        swapout_target_age = 0;
367 uint32_t        age_of_decompressions_during_sample_period[DECOMPRESSION_SAMPLE_MAX_AGE];
368 uint32_t        overage_decompressions_during_sample_period = 0;
369 
370 
371 void            do_fastwake_warmup(queue_head_t *, boolean_t);
372 boolean_t       fastwake_warmup = FALSE;
373 boolean_t       fastwake_recording_in_progress = FALSE;
374 uint64_t        dont_trim_until_ts = 0;
375 
376 uint64_t        c_segment_warmup_count;
377 uint64_t        first_c_segment_to_warm_generation_id = 0;
378 uint64_t        last_c_segment_to_warm_generation_id = 0;
379 boolean_t       hibernate_flushing = FALSE;
380 
381 _Atomic uint64_t c_segment_input_bytes = 0;
382 _Atomic uint64_t c_segment_compressed_bytes = 0;
383 _Atomic uint64_t compressor_bytes_used = 0;
384 
385 /* Keeps track of the most recent timestamp for when major compaction finished. */
386 mach_timespec_t major_compact_ts;
387 
388 struct c_sv_hash_entry c_segment_sv_hash_table[C_SV_HASH_SIZE]  __attribute__ ((aligned(8)));
389 
390 static void vm_compressor_swap_trigger_thread(void);
391 static void vm_compressor_do_delayed_compactions(boolean_t);
392 static void vm_compressor_compact_and_swap(boolean_t);
393 static void vm_compressor_process_regular_swapped_in_segments(boolean_t);
394 static void vm_compressor_process_special_swapped_in_segments_locked(void);
395 
396 struct vm_compressor_swapper_stats vmcs_stats;
397 
398 static void vm_compressor_process_major_segments(bool);
399 
400 void compute_swapout_target_age(void);
401 
402 boolean_t c_seg_major_compact(c_segment_t, c_segment_t);
403 boolean_t c_seg_major_compact_ok(c_segment_t, c_segment_t);
404 
405 int  c_seg_minor_compaction_and_unlock(c_segment_t, boolean_t);
406 int  c_seg_do_minor_compaction_and_unlock(c_segment_t, boolean_t, boolean_t, boolean_t);
407 void c_seg_try_minor_compaction_and_unlock(c_segment_t c_seg);
408 
409 void c_seg_move_to_sparse_list(c_segment_t);
410 void c_seg_insert_into_q(queue_head_t *, c_segment_t);
411 
412 uint64_t vm_available_memory(void);
413 
414 /*
415  * Get the address of a given entry in the c_segments array
416  */
417 static inline union c_segu *
c_segments_get(uint32_t segno)418 c_segments_get(uint32_t segno)
419 {
420 	return VM_FAR_ADD_PTR_UNBOUNDED(c_segments, segno);
421 }
422 
423 /*
424  * indicate the need to do a major compaction if
425  * the overall set of in-use compression segments
426  * becomes sparse... on systems that support pressure
427  * driven swapping, this will also cause swapouts to
428  * be initiated.
429  */
430 static bool
vm_compressor_needs_to_major_compact(void)431 vm_compressor_needs_to_major_compact(void)
432 {
433 	uint32_t        incore_seg_count;
434 
435 	incore_seg_count = c_segment_count - c_swappedout_count - c_swappedout_sparse_count;
436 
437 	/* second condition:
438 	 *   first term:
439 	 *   - (incore_seg_count * c_seg_max_pages) is the maximum number of pages that all resident segments can hold in their buffers
440 	 *   - VM_PAGE_COMPRESSOR_COUNT is the current size that is actually held by the buffers
441 	 *   -- subtracting these gives the amount of pages that is wasted as holes due to segments not being full
442 	 *   second term:
443 	 *   - 1/8 of the maximum size that can be held by this many segments
444 	 *   meaning of the comparison: is the ratio of wasted space greater than 1/8
445 	 * first condition:
446 	 *   compare number of segments being used vs the number of segments that can ever be allocated
447 	 *   if we don't have a lot of data in the compressor, then we don't need to bother caring about wasted space in holes
448 	 */
449 
450 	if ((c_segment_count >= (c_segments_nearing_limit / 8)) &&
451 	    ((incore_seg_count * c_seg_max_pages) - VM_PAGE_COMPRESSOR_COUNT) >
452 	    ((incore_seg_count / 8) * c_seg_max_pages)) {
453 		return true;
454 	}
455 	return false;
456 }
457 
458 uint32_t
vm_compressor_incore_fragmentation_wasted_pages(void)459 vm_compressor_incore_fragmentation_wasted_pages(void)
460 {
461 	/* return one of the components of the calculation in vm_compressor_needs_to_major_compact() */
462 	uint32_t incore_seg_count = c_segment_count - c_swappedout_count - c_swappedout_sparse_count;
463 	return (incore_seg_count * c_seg_max_pages) - VM_PAGE_COMPRESSOR_COUNT;
464 }
465 
466 TUNABLE_WRITEABLE(uint64_t, vm_compressor_minor_fragmentation_threshold_pct, "vm_compressor_minor_frag_threshold_pct", 10);
467 
468 static bool
vm_compressor_needs_to_minor_compact(void)469 vm_compressor_needs_to_minor_compact(void)
470 {
471 	uint32_t compactible_seg_count = os_atomic_load(&c_minor_count, relaxed);
472 	if (compactible_seg_count == 0) {
473 		return false;
474 	}
475 
476 	bool is_pressured = AVAILABLE_NON_COMPRESSED_MEMORY <
477 	    VM_PAGE_COMPRESSOR_COMPACT_THRESHOLD;
478 	if (!is_pressured) {
479 		return false;
480 	}
481 
482 	uint64_t bytes_used = os_atomic_load(&compressor_bytes_used, relaxed);
483 	uint64_t bytes_total = VM_PAGE_COMPRESSOR_COUNT * PAGE_SIZE_64;
484 	uint64_t bytes_frag = bytes_total - bytes_used;
485 	bool is_fragmented = bytes_frag >
486 	    bytes_total * vm_compressor_minor_fragmentation_threshold_pct / 100;
487 
488 	return is_fragmented;
489 }
490 
491 
492 uint64_t
vm_available_memory(void)493 vm_available_memory(void)
494 {
495 	return ((uint64_t)AVAILABLE_NON_COMPRESSED_MEMORY) * PAGE_SIZE_64;
496 }
497 
498 
499 uint32_t
vm_compressor_pool_size(void)500 vm_compressor_pool_size(void)
501 {
502 	return VM_PAGE_COMPRESSOR_COUNT;
503 }
504 
505 uint32_t
vm_compressor_fragmentation_level(void)506 vm_compressor_fragmentation_level(void)
507 {
508 	const uint32_t incore_seg_count = c_segment_count - c_swappedout_count - c_swappedout_sparse_count;
509 	if ((incore_seg_count == 0) || (c_seg_max_pages == 0)) {
510 		return 0;
511 	}
512 	return 100 - (vm_compressor_pool_size() * 100 / (incore_seg_count * c_seg_max_pages));
513 }
514 
515 uint32_t
vm_compression_ratio(void)516 vm_compression_ratio(void)
517 {
518 	if (vm_compressor_pool_size() == 0) {
519 		return UINT32_MAX;
520 	}
521 	return c_segment_pages_compressed / vm_compressor_pool_size();
522 }
523 
524 uint32_t
vm_compressor_pages_compressed(void)525 vm_compressor_pages_compressed(void)
526 {
527 #if CONFIG_FREEZE
528 	if (freezer_incore_cseg_acct) {
529 		return os_atomic_load(&c_segment_pages_compressed_incore, relaxed);
530 	}
531 #endif /* CONFIG_FREEZE */
532 	return os_atomic_load(&c_segment_pages_compressed, relaxed);
533 }
534 
535 bool
vm_compressor_compressed_pages_nearing_limit(void)536 vm_compressor_compressed_pages_nearing_limit(void)
537 {
538 	return vm_compressor_pages_compressed() > c_segment_pages_compressed_nearing_limit;
539 }
540 
541 static bool
vm_compressor_segments_nearing_limit(void)542 vm_compressor_segments_nearing_limit(void)
543 {
544 	uint64_t segments;
545 
546 #if CONFIG_FREEZE
547 	if (freezer_incore_cseg_acct) {
548 		if (os_sub_overflow(c_segment_count, c_swappedout_count, &segments)) {
549 			segments = 0;
550 		}
551 		if (os_sub_overflow(segments, c_swappedout_sparse_count, &segments)) {
552 			segments = 0;
553 		}
554 	} else {
555 		segments = os_atomic_load(&c_segment_count, relaxed);
556 	}
557 #else /* CONFIG_FREEZE */
558 	segments = c_segment_count;
559 #endif /* CONFIG_FREEZE */
560 
561 	return segments > c_segments_nearing_limit;
562 }
563 
564 bool
vm_compressor_low_on_space(void)565 vm_compressor_low_on_space(void)
566 {
567 	return vm_compressor_compressed_pages_nearing_limit() ||
568 	       vm_compressor_segments_nearing_limit();
569 }
570 
571 
572 bool
vm_compressor_out_of_space(void)573 vm_compressor_out_of_space(void)
574 {
575 #if CONFIG_FREEZE
576 	uint64_t incore_seg_count;
577 	uint32_t incore_compressed_pages;
578 	if (freezer_incore_cseg_acct) {
579 		if (os_sub_overflow(c_segment_count, c_swappedout_count, &incore_seg_count)) {
580 			incore_seg_count = 0;
581 		}
582 		if (os_sub_overflow(incore_seg_count, c_swappedout_sparse_count, &incore_seg_count)) {
583 			incore_seg_count = 0;
584 		}
585 		incore_compressed_pages = os_atomic_load(&c_segment_pages_compressed_incore, relaxed);
586 	} else {
587 		incore_seg_count = os_atomic_load(&c_segment_count, relaxed);
588 		incore_compressed_pages = os_atomic_load(&c_segment_pages_compressed_incore, relaxed);
589 	}
590 
591 	if ((incore_compressed_pages >= c_segment_pages_compressed_limit) ||
592 	    (incore_seg_count > c_segments_incore_limit)) {
593 		return true;
594 	}
595 #else /* CONFIG_FREEZE */
596 	if ((c_segment_pages_compressed >= c_segment_pages_compressed_limit) ||
597 	    (c_segment_count >= c_segments_limit)) {
598 		return true;
599 	}
600 #endif /* CONFIG_FREEZE */
601 	return FALSE;
602 }
603 
604 bool
vm_compressor_is_thrashing()605 vm_compressor_is_thrashing()
606 {
607 	compute_swapout_target_age();
608 
609 	if (swapout_target_age) {
610 		c_segment_t     c_seg;
611 
612 		lck_mtx_lock_spin_always(c_list_lock);
613 
614 		if (!queue_empty(&c_age_list_head)) {
615 			c_seg = (c_segment_t) queue_first(&c_age_list_head);
616 
617 			if (c_seg->c_creation_ts > swapout_target_age) {
618 				swapout_target_age = 0;
619 			}
620 		}
621 		lck_mtx_unlock_always(c_list_lock);
622 	}
623 
624 	return swapout_target_age != 0;
625 }
626 
627 
628 int
vm_wants_task_throttled(task_t task)629 vm_wants_task_throttled(task_t task)
630 {
631 	ledger_amount_t compressed;
632 	if (task == kernel_task) {
633 		return 0;
634 	}
635 
636 	if (VM_CONFIG_SWAP_IS_ACTIVE) {
637 		if ((vm_compressor_low_on_space() || HARD_THROTTLE_LIMIT_REACHED())) {
638 			ledger_get_balance(task->ledger, task_ledgers.internal_compressed, &compressed);
639 			compressed >>= VM_MAP_PAGE_SHIFT(task->map);
640 			if ((unsigned int)compressed > (c_segment_pages_compressed / 4)) {
641 				return 1;
642 			}
643 		}
644 	}
645 	return 0;
646 }
647 
648 #if CONFIG_JETSAM
649 bool            memorystatus_disable_swap(void);
650 #if CONFIG_PHANTOM_CACHE
651 extern bool memorystatus_phantom_cache_pressure;
652 #endif /* CONFIG_PHANTOM_CACHE */
653 int             compressor_thrashing_induced_jetsam = 0;
654 int             filecache_thrashing_induced_jetsam = 0;
655 static boolean_t        vm_compressor_thrashing_detected = FALSE;
656 #endif /* CONFIG_JETSAM */
657 
658 void
vm_decompressor_lock(void)659 vm_decompressor_lock(void)
660 {
661 	PAGE_REPLACEMENT_ALLOWED(TRUE);
662 
663 	decompressions_blocked = TRUE;
664 
665 	PAGE_REPLACEMENT_ALLOWED(FALSE);
666 }
667 
668 void
vm_decompressor_unlock(void)669 vm_decompressor_unlock(void)
670 {
671 	PAGE_REPLACEMENT_ALLOWED(TRUE);
672 
673 	decompressions_blocked = FALSE;
674 
675 	PAGE_REPLACEMENT_ALLOWED(FALSE);
676 
677 	thread_wakeup((event_t)&decompressions_blocked);
678 }
679 
680 static inline void
cslot_copy(c_slot_t cdst,c_slot_t csrc)681 cslot_copy(c_slot_t cdst, c_slot_t csrc)
682 {
683 #if CHECKSUM_THE_DATA
684 	cdst->c_hash_data = csrc->c_hash_data;
685 #endif
686 #if CHECKSUM_THE_COMPRESSED_DATA
687 	cdst->c_hash_compressed_data = csrc->c_hash_compressed_data;
688 #endif
689 #if POPCOUNT_THE_COMPRESSED_DATA
690 	cdst->c_pop_cdata = csrc->c_pop_cdata;
691 #endif
692 	cdst->c_size = csrc->c_size;
693 	cdst->c_packed_ptr = csrc->c_packed_ptr;
694 #if defined(__arm64__)
695 	cdst->c_codec = csrc->c_codec;
696 #endif
697 }
698 
699 #if XNU_TARGET_OS_OSX
700 #define VM_COMPRESSOR_MAX_POOL_SIZE (192UL << 30)
701 #else
702 #define VM_COMPRESSOR_MAX_POOL_SIZE (0)
703 #endif
704 
705 static vm_map_size_t compressor_size;
706 static SECURITY_READ_ONLY_LATE(struct mach_vm_range) compressor_range;
707 vm_map_t compressor_map;
708 uint64_t compressor_pool_max_size;
709 uint64_t compressor_pool_size;
710 uint32_t compressor_pool_multiplier;
711 
712 #if DEVELOPMENT || DEBUG
713 /*
714  * Compressor segments are write-protected in development/debug
715  * kernels to help debug memory corruption.
716  * In cases where performance is a concern, this can be disabled
717  * via the boot-arg "-disable_cseg_write_protection".
718  */
719 boolean_t write_protect_c_segs = TRUE;
720 int vm_compressor_test_seg_wp;
721 uint32_t vm_ktrace_enabled;
722 #endif /* DEVELOPMENT || DEBUG */
723 
724 #if (XNU_TARGET_OS_OSX && __arm64__)
725 
726 #include <IOKit/IOPlatformExpert.h>
727 #include <sys/random.h>
728 
729 static const char *csegbufsizeExperimentProperty = "_csegbufsz_experiment";
730 static thread_call_t csegbufsz_experiment_thread_call;
731 
732 extern boolean_t IOServiceWaitForMatchingResource(const char * property, uint64_t timeout);
733 static void
erase_csegbufsz_experiment_property(__unused void * param0,__unused void * param1)734 erase_csegbufsz_experiment_property(__unused void *param0, __unused void *param1)
735 {
736 	// Wait for NVRAM to be writable
737 	if (!IOServiceWaitForMatchingResource("IONVRAM", UINT64_MAX)) {
738 		printf("csegbufsz_experiment_property: Failed to wait for IONVRAM.");
739 	}
740 
741 	if (!PERemoveNVRAMProperty(csegbufsizeExperimentProperty)) {
742 		printf("csegbufsize_experiment_property: Failed to remove %s from NVRAM.", csegbufsizeExperimentProperty);
743 	}
744 	thread_call_free(csegbufsz_experiment_thread_call);
745 }
746 
747 static void
erase_csegbufsz_experiment_property_async()748 erase_csegbufsz_experiment_property_async()
749 {
750 	csegbufsz_experiment_thread_call = thread_call_allocate_with_priority(
751 		erase_csegbufsz_experiment_property,
752 		NULL,
753 		THREAD_CALL_PRIORITY_LOW
754 		);
755 	if (csegbufsz_experiment_thread_call == NULL) {
756 		printf("csegbufsize_experiment_property: Unable to allocate thread call.");
757 	} else {
758 		thread_call_enter(csegbufsz_experiment_thread_call);
759 	}
760 }
761 
762 static void
cleanup_csegbufsz_experiment(__unused void * arg0)763 cleanup_csegbufsz_experiment(__unused void *arg0)
764 {
765 	char nvram = 0;
766 	unsigned int len = sizeof(nvram);
767 	if (PEReadNVRAMProperty(csegbufsizeExperimentProperty, &nvram, &len)) {
768 		erase_csegbufsz_experiment_property_async();
769 	}
770 }
771 
772 STARTUP_ARG(EARLY_BOOT, STARTUP_RANK_FIRST, cleanup_csegbufsz_experiment, NULL);
773 #endif /* XNU_TARGET_OS_OSX && __arm64__ */
774 
775 #if CONFIG_JETSAM
776 extern unsigned int memorystatus_swap_all_apps;
777 #endif /* CONFIG_JETSAM */
778 
779 TUNABLE_DT(uint64_t, swap_vol_min_capacity, "/defaults", "kern.swap_min_capacity", "kern.swap_min_capacity", 0, TUNABLE_DT_NONE);
780 
781 static void
vm_compressor_set_size(void)782 vm_compressor_set_size(void)
783 {
784 	/*
785 	 * Note that this function may be called multiple times on systems with app swap
786 	 * because the value of vm_swap_get_max_configured_space() and memorystatus_swap_all_apps
787 	 * can change based the size of the swap volume. On these systems, we'll call
788 	 * this function once early in boot to reserve the maximum amount of VA required
789 	 * for the compressor submap and then one more time in vm_compressor_init after
790 	 * determining the swap volume size. We must not return a larger value the second
791 	 * time around.
792 	 */
793 	vm_size_t       c_segments_arr_size = 0;
794 	struct c_slot_mapping tmp_slot_ptr;
795 
796 	/* The segment size can be overwritten by a boot-arg */
797 	if (!PE_parse_boot_argn("vm_compressor_segment_buffer_size", &c_seg_bufsize, sizeof(c_seg_bufsize))) {
798 #if CONFIG_JETSAM
799 		if (memorystatus_swap_all_apps) {
800 			c_seg_bufsize = C_SEG_BUFSIZE_ARM_SWAP;
801 		} else {
802 			c_seg_bufsize = C_SEG_BUFSIZE_DEFAULT;
803 		}
804 #else
805 		c_seg_bufsize = C_SEG_BUFSIZE_DEFAULT;
806 #endif /* CONFIG_JETSAM */
807 	}
808 
809 	vm_compressor_swap_init_swap_file_limit();
810 	if (vm_compression_limit) {
811 		compressor_pool_size = ptoa_64(vm_compression_limit);
812 	}
813 
814 	compressor_pool_max_size = C_SEG_MAX_LIMIT;
815 	compressor_pool_max_size *= c_seg_bufsize;
816 
817 #if XNU_TARGET_OS_OSX
818 
819 	if (vm_compression_limit == 0) {
820 		if (max_mem <= (4ULL * 1024ULL * 1024ULL * 1024ULL)) {
821 			compressor_pool_size = 16ULL * max_mem;
822 		} else if (max_mem <= (8ULL * 1024ULL * 1024ULL * 1024ULL)) {
823 			compressor_pool_size = 8ULL * max_mem;
824 		} else if (max_mem <= (32ULL * 1024ULL * 1024ULL * 1024ULL)) {
825 			compressor_pool_size = 4ULL * max_mem;
826 		} else {
827 			compressor_pool_size = 2ULL * max_mem;
828 		}
829 	}
830 	/*
831 	 * Cap the compressor pool size to a max of 192G
832 	 */
833 	if (compressor_pool_size > VM_COMPRESSOR_MAX_POOL_SIZE) {
834 		compressor_pool_size = VM_COMPRESSOR_MAX_POOL_SIZE;
835 	}
836 	if (max_mem <= (8ULL * 1024ULL * 1024ULL * 1024ULL)) {
837 		compressor_pool_multiplier = 1;
838 	} else if (max_mem <= (32ULL * 1024ULL * 1024ULL * 1024ULL)) {
839 		compressor_pool_multiplier = 2;
840 	} else {
841 		compressor_pool_multiplier = 4;
842 	}
843 
844 #else
845 
846 	if (compressor_pool_max_size > max_mem) {
847 		compressor_pool_max_size = max_mem;
848 	}
849 
850 	if (vm_compression_limit == 0) {
851 		compressor_pool_size = max_mem;
852 	}
853 
854 #if XNU_TARGET_OS_WATCH
855 	compressor_pool_multiplier = 2;
856 #elif XNU_TARGET_OS_IOS
857 	if (max_mem <= (2ULL * 1024ULL * 1024ULL * 1024ULL)) {
858 		compressor_pool_multiplier = 2;
859 	} else {
860 		compressor_pool_multiplier = 1;
861 	}
862 #else
863 	compressor_pool_multiplier = 1;
864 #endif
865 
866 #endif
867 
868 	PE_parse_boot_argn("kern.compressor_pool_multiplier", &compressor_pool_multiplier, sizeof(compressor_pool_multiplier));
869 	if (compressor_pool_multiplier < 1) {
870 		compressor_pool_multiplier = 1;
871 	}
872 
873 	if (compressor_pool_size > compressor_pool_max_size) {
874 		compressor_pool_size = compressor_pool_max_size;
875 	}
876 
877 	c_seg_max_pages = (c_seg_bufsize / PAGE_SIZE);
878 	c_seg_slot_var_array_min_len = c_seg_max_pages;
879 
880 #if !defined(__x86_64__)
881 	c_seg_off_limit = (C_SEG_BYTES_TO_OFFSET((c_seg_bufsize - 512)));
882 	c_seg_allocsize = (c_seg_bufsize + PAGE_SIZE);
883 #else
884 	c_seg_off_limit = (C_SEG_BYTES_TO_OFFSET((c_seg_bufsize - 128)));
885 	c_seg_allocsize = c_seg_bufsize;
886 #endif /* !defined(__x86_64__) */
887 
888 	c_segments_limit = (uint32_t)(compressor_pool_size / (vm_size_t)(c_seg_allocsize));
889 	tmp_slot_ptr.s_cseg = c_segments_limit;
890 	/* Panic on internal configs*/
891 	assertf((tmp_slot_ptr.s_cseg == c_segments_limit), "vm_compressor_init: overflowed s_cseg field in c_slot_mapping with c_segno: %d", c_segments_limit);
892 
893 	if (tmp_slot_ptr.s_cseg != c_segments_limit) {
894 		tmp_slot_ptr.s_cseg = -1;
895 		c_segments_limit = tmp_slot_ptr.s_cseg - 1; /*limited by segment idx bits in c_slot_mapping*/
896 		compressor_pool_size = (c_segments_limit * (vm_size_t)(c_seg_allocsize));
897 	}
898 
899 	c_segments_nearing_limit = (uint32_t)(((uint64_t)c_segments_limit * 98ULL) / 100ULL);
900 
901 	/* an upper limit on how many input pages the compressor can hold */
902 	c_segment_pages_compressed_limit = (c_segments_limit * (c_seg_bufsize / PAGE_SIZE) * compressor_pool_multiplier);
903 
904 	if (c_segment_pages_compressed_limit < (uint32_t)(max_mem / PAGE_SIZE)) {
905 #if defined(XNU_TARGET_OS_WATCH)
906 		c_segment_pages_compressed_limit = (uint32_t)(max_mem / PAGE_SIZE);
907 #else
908 		if (!vm_compression_limit) {
909 			c_segment_pages_compressed_limit = (uint32_t)(max_mem / PAGE_SIZE);
910 		}
911 #endif
912 	}
913 
914 	c_segment_pages_compressed_nearing_limit = (uint32_t)(((uint64_t)c_segment_pages_compressed_limit * 98ULL) / 100ULL);
915 
916 #if CONFIG_FREEZE
917 	/*
918 	 * Our in-core limits are based on the size of the compressor pool.
919 	 * The c_segments_nearing_limit is also based on the compressor pool
920 	 * size and calculated above.
921 	 */
922 	c_segments_incore_limit = c_segments_limit;
923 
924 	if (freezer_incore_cseg_acct) {
925 		/*
926 		 * Add enough segments to track all frozen c_segs that can be stored in swap.
927 		 */
928 		c_segments_limit += (uint32_t)(vm_swap_get_max_configured_space() / (vm_size_t)(c_seg_allocsize));
929 		tmp_slot_ptr.s_cseg = c_segments_limit;
930 		/* Panic on internal configs*/
931 		assertf((tmp_slot_ptr.s_cseg == c_segments_limit), "vm_compressor_init: freezer reserve overflowed s_cseg field in c_slot_mapping with c_segno: %d", c_segments_limit);
932 	}
933 #endif
934 	/*
935 	 * Submap needs space for:
936 	 * - c_segments
937 	 * - c_buffers
938 	 * - swap reclaimations -- c_seg_bufsize
939 	 */
940 	c_segments_arr_size = vm_map_round_page((sizeof(union c_segu) * c_segments_limit), VM_MAP_PAGE_MASK(kernel_map));
941 	c_buffers_size = vm_map_round_page(((vm_size_t)c_seg_allocsize * (vm_size_t)c_segments_limit), VM_MAP_PAGE_MASK(kernel_map));
942 
943 	compressor_size = c_segments_arr_size + c_buffers_size + c_seg_bufsize;
944 
945 #if RECORD_THE_COMPRESSED_DATA
946 	c_compressed_record_sbuf_size = (vm_size_t)c_seg_allocsize + (PAGE_SIZE * 2);
947 	compressor_size += c_compressed_record_sbuf_size;
948 #endif /* RECORD_THE_COMPRESSED_DATA */
949 }
950 STARTUP(KMEM, STARTUP_RANK_FIRST, vm_compressor_set_size);
951 
952 KMEM_RANGE_REGISTER_DYNAMIC(compressor, &compressor_range, ^() {
953 	return compressor_size;
954 });
955 
956 bool
osenvironment_is_diagnostics(void)957 osenvironment_is_diagnostics(void)
958 {
959 	DTEntry chosen;
960 	const char *osenvironment;
961 	unsigned int size;
962 	if (kSuccess == SecureDTLookupEntry(0, "/chosen", &chosen)) {
963 		if (kSuccess == SecureDTGetProperty(chosen, "osenvironment", (void const **) &osenvironment, &size)) {
964 			return strcmp(osenvironment, "diagnostics") == 0;
965 		}
966 	}
967 	return false;
968 }
969 
970 void
vm_compressor_init(void)971 vm_compressor_init(void)
972 {
973 	thread_t        thread;
974 #if RECORD_THE_COMPRESSED_DATA
975 	vm_size_t       c_compressed_record_sbuf_size = 0;
976 #endif /* RECORD_THE_COMPRESSED_DATA */
977 
978 #if DEVELOPMENT || DEBUG || CONFIG_FREEZE
979 	char bootarg_name[32];
980 #endif /* DEVELOPMENT || DEBUG || CONFIG_FREEZE */
981 	__unused uint64_t early_boot_compressor_size = compressor_size;
982 
983 #if CONFIG_JETSAM
984 	if (memorystatus_swap_all_apps && osenvironment_is_diagnostics()) {
985 		printf("osenvironment == \"diagnostics\". Disabling app swap.\n");
986 		memorystatus_disable_swap();
987 	}
988 
989 	if (memorystatus_swap_all_apps) {
990 		/*
991 		 * App swap is disabled on devices with small NANDs.
992 		 * Now that we're no longer in early boot, we can get
993 		 * the NAND size and re-run vm_compressor_set_size.
994 		 */
995 		int error = vm_swap_vol_get_capacity(SWAP_VOLUME_NAME, &vm_swap_volume_capacity);
996 #if DEVELOPMENT || DEBUG
997 		if (error != 0) {
998 			panic("vm_compressor_init: Unable to get swap volume capacity. error=%d\n", error);
999 		}
1000 #else
1001 		if (error != 0) {
1002 			os_log_with_startup_serial(OS_LOG_DEFAULT, "vm_compressor_init: Unable to get swap volume capacity. error=%d\n", error);
1003 		}
1004 #endif /* DEVELOPMENT || DEBUG */
1005 		if (vm_swap_volume_capacity < swap_vol_min_capacity) {
1006 			memorystatus_disable_swap();
1007 		}
1008 		/*
1009 		 * Resize the compressor and swap now that we know the capacity
1010 		 * of the swap volume.
1011 		 */
1012 		vm_compressor_set_size();
1013 		/*
1014 		 * We reserved a chunk of VA early in boot for the compressor submap.
1015 		 * We can't allocate more than that.
1016 		 */
1017 		assert(compressor_size <= early_boot_compressor_size);
1018 	}
1019 #endif /* CONFIG_JETSAM */
1020 
1021 #if DEVELOPMENT || DEBUG
1022 	if (PE_parse_boot_argn("-disable_cseg_write_protection", bootarg_name, sizeof(bootarg_name))) {
1023 		write_protect_c_segs = FALSE;
1024 	}
1025 
1026 	int vmcval = 1;
1027 #if defined(XNU_TARGET_OS_WATCH)
1028 	vmcval = 0;
1029 #endif /* XNU_TARGET_OS_WATCH */
1030 	PE_parse_boot_argn("vm_compressor_validation", &vmcval, sizeof(vmcval));
1031 
1032 	if (kern_feature_override(KF_COMPRSV_OVRD)) {
1033 		vmcval = 0;
1034 	}
1035 
1036 	if (vmcval == 0) {
1037 #if POPCOUNT_THE_COMPRESSED_DATA
1038 		popcount_c_segs = FALSE;
1039 #endif
1040 #if CHECKSUM_THE_DATA || CHECKSUM_THE_COMPRESSED_DATA
1041 		checksum_c_segs = FALSE;
1042 #endif
1043 #if VALIDATE_C_SEGMENTS
1044 		validate_c_segs = FALSE;
1045 #endif
1046 		write_protect_c_segs = FALSE;
1047 	}
1048 #endif /* DEVELOPMENT || DEBUG */
1049 
1050 #if CONFIG_FREEZE
1051 	if (PE_parse_boot_argn("-disable_freezer_cseg_acct", bootarg_name, sizeof(bootarg_name))) {
1052 		freezer_incore_cseg_acct = FALSE;
1053 	}
1054 #endif /* CONFIG_FREEZE */
1055 
1056 	assert((C_SEGMENTS_PER_PAGE * sizeof(union c_segu)) == PAGE_SIZE);
1057 
1058 #if !XNU_TARGET_OS_OSX
1059 	vm_compressor_minorcompact_threshold_divisor = 20;
1060 	vm_compressor_majorcompact_threshold_divisor = 30;
1061 	vm_compressor_unthrottle_threshold_divisor = 40;
1062 	vm_compressor_catchup_threshold_divisor = 60;
1063 #else /* !XNU_TARGET_OS_OSX */
1064 	if (max_mem <= (3ULL * 1024ULL * 1024ULL * 1024ULL)) {
1065 		vm_compressor_minorcompact_threshold_divisor = 11;
1066 		vm_compressor_majorcompact_threshold_divisor = 13;
1067 		vm_compressor_unthrottle_threshold_divisor = 20;
1068 		vm_compressor_catchup_threshold_divisor = 35;
1069 	} else {
1070 		vm_compressor_minorcompact_threshold_divisor = 20;
1071 		vm_compressor_majorcompact_threshold_divisor = 25;
1072 		vm_compressor_unthrottle_threshold_divisor = 35;
1073 		vm_compressor_catchup_threshold_divisor = 50;
1074 	}
1075 #endif /* !XNU_TARGET_OS_OSX */
1076 
1077 	queue_init(&c_bad_list_head);
1078 	queue_init(&c_age_list_head);
1079 	queue_init(&c_minor_list_head);
1080 	queue_init(&c_major_list_head);
1081 	queue_init(&c_filling_list_head);
1082 	queue_init(&c_early_swapout_list_head);
1083 	queue_init(&c_regular_swapout_list_head);
1084 	queue_init(&c_late_swapout_list_head);
1085 	queue_init(&c_swapio_list_head);
1086 	queue_init(&c_early_swappedin_list_head);
1087 	queue_init(&c_regular_swappedin_list_head);
1088 	queue_init(&c_late_swappedin_list_head);
1089 	queue_init(&c_swappedout_list_head);
1090 	queue_init(&c_swappedout_sparse_list_head);
1091 
1092 	c_free_segno_head = -1;
1093 	c_segments_available = 0;
1094 
1095 	compressor_map = kmem_suballoc(kernel_map, &compressor_range.min_address,
1096 	    compressor_size, VM_MAP_CREATE_NEVER_FAULTS,
1097 	    VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE,
1098 	    KMS_NOFAIL | KMS_PERMANENT | KMS_NOSOFTLIMIT,
1099 	    VM_KERN_MEMORY_COMPRESSOR).kmr_submap;
1100 
1101 	kmem_alloc(compressor_map, (vm_offset_t *)(&c_segments),
1102 	    (sizeof(union c_segu) * c_segments_limit),
1103 	    KMA_NOFAIL | KMA_KOBJECT | KMA_VAONLY | KMA_PERMANENT | KMA_NOSOFTLIMIT,
1104 	    VM_KERN_MEMORY_COMPRESSOR);
1105 	kmem_alloc(compressor_map, &c_buffers, c_buffers_size,
1106 	    KMA_NOFAIL | KMA_COMPRESSOR | KMA_VAONLY | KMA_PERMANENT | KMA_NOSOFTLIMIT,
1107 	    VM_KERN_MEMORY_COMPRESSOR);
1108 
1109 #if DEVELOPMENT || DEBUG
1110 	if (hvg_is_hcall_available(HVG_HCALL_SET_COREDUMP_DATA)) {
1111 		hvg_hcall_set_coredump_data();
1112 	}
1113 #endif
1114 
1115 	/*
1116 	 * Pick a good size that will minimize fragmentation in zalloc
1117 	 * by minimizing the fragmentation in a 16k run.
1118 	 *
1119 	 * c_seg_slot_var_array_min_len is larger on 4k systems than 16k ones,
1120 	 * making the fragmentation in a 4k page terrible. Using 16k for all
1121 	 * systems matches zalloc() and will minimize fragmentation.
1122 	 */
1123 	uint32_t c_segment_size = sizeof(struct c_segment) + (c_seg_slot_var_array_min_len * sizeof(struct c_slot));
1124 	uint32_t cnt  = (16 << 10) / c_segment_size;
1125 	uint32_t frag = (16 << 10) % c_segment_size;
1126 
1127 	c_seg_fixed_array_len = c_seg_slot_var_array_min_len;
1128 
1129 	while (cnt * sizeof(struct c_slot) < frag) {
1130 		c_segment_size += sizeof(struct c_slot);
1131 		c_seg_fixed_array_len++;
1132 		frag -= cnt * sizeof(struct c_slot);
1133 	}
1134 
1135 	compressor_segment_zone = zone_create("compressor_segment",
1136 	    c_segment_size, ZC_PGZ_USE_GUARDS | ZC_NOENCRYPT | ZC_ZFREE_CLEARMEM);
1137 
1138 	c_segments_busy = FALSE;
1139 
1140 	c_segments_next_page = (caddr_t)c_segments;
1141 	vm_compressor_algorithm_init();
1142 
1143 	{
1144 		host_basic_info_data_t hinfo;
1145 		mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
1146 		size_t bufsize;
1147 		char *buf;
1148 
1149 #define BSD_HOST 1
1150 		host_info((host_t)BSD_HOST, HOST_BASIC_INFO, (host_info_t)&hinfo, &count);
1151 
1152 		compressor_cpus = hinfo.max_cpus;
1153 
1154 		/* allocate various scratch buffers at the same place */
1155 		bufsize = PAGE_SIZE;
1156 		bufsize += compressor_cpus * vm_compressor_get_decode_scratch_size();
1157 		/* For the panic path */
1158 		bufsize += vm_compressor_get_decode_scratch_size();
1159 #if CONFIG_FREEZE
1160 		bufsize += vm_compressor_get_encode_scratch_size();
1161 #endif
1162 #if RECORD_THE_COMPRESSED_DATA
1163 		bufsize += c_compressed_record_sbuf_size;
1164 #endif
1165 
1166 		kmem_alloc(kernel_map, (vm_offset_t *)&buf, bufsize,
1167 		    KMA_DATA | KMA_NOFAIL | KMA_KOBJECT | KMA_PERMANENT,
1168 		    VM_KERN_MEMORY_COMPRESSOR);
1169 
1170 		/*
1171 		 * vm_compressor_kdp_state.kc_decompressed_page must be page aligned because we access
1172 		 * it through the physical aperture by page number.
1173 		 */
1174 		vm_compressor_kdp_state.kc_panic_decompressed_page = buf;
1175 		vm_compressor_kdp_state.kc_panic_decompressed_page_paddr = kvtophys((vm_offset_t)vm_compressor_kdp_state.kc_panic_decompressed_page);
1176 		vm_compressor_kdp_state.kc_panic_decompressed_page_ppnum = (ppnum_t) atop(vm_compressor_kdp_state.kc_panic_decompressed_page_paddr);
1177 		buf += PAGE_SIZE;
1178 		bufsize -= PAGE_SIZE;
1179 
1180 		compressor_scratch_bufs = buf;
1181 		buf += compressor_cpus * vm_compressor_get_decode_scratch_size();
1182 		bufsize -= compressor_cpus * vm_compressor_get_decode_scratch_size();
1183 
1184 		vm_compressor_kdp_state.kc_panic_scratch_buf = buf;
1185 		buf += vm_compressor_get_decode_scratch_size();
1186 		bufsize -= vm_compressor_get_decode_scratch_size();
1187 
1188 		/* This is set up before each stackshot in vm_compressor_kdp_init */
1189 		vm_compressor_kdp_state.kc_scratch_bufs = NULL;
1190 
1191 #if CONFIG_FREEZE
1192 		freezer_context_global.freezer_ctx_compressor_scratch_buf = buf;
1193 		buf += vm_compressor_get_encode_scratch_size();
1194 		bufsize -= vm_compressor_get_encode_scratch_size();
1195 #endif
1196 
1197 #if RECORD_THE_COMPRESSED_DATA
1198 		c_compressed_record_sbuf = buf;
1199 		c_compressed_record_cptr = buf;
1200 		c_compressed_record_ebuf = c_compressed_record_sbuf + c_compressed_record_sbuf_size;
1201 		buf += c_compressed_record_sbuf_size;
1202 		bufsize -= c_compressed_record_sbuf_size;
1203 #endif
1204 		assert(bufsize == 0);
1205 	}
1206 
1207 	if (kernel_thread_start_priority((thread_continue_t)vm_compressor_swap_trigger_thread, NULL,
1208 	    BASEPRI_VM, &thread) != KERN_SUCCESS) {
1209 		panic("vm_compressor_swap_trigger_thread: create failed");
1210 	}
1211 	thread_deallocate(thread);
1212 
1213 	if (vm_pageout_internal_start() != KERN_SUCCESS) {
1214 		panic("vm_compressor_init: Failed to start the internal pageout thread.");
1215 	}
1216 	if (VM_CONFIG_SWAP_IS_PRESENT) {
1217 		vm_compressor_swap_init();
1218 	}
1219 
1220 	if (VM_CONFIG_COMPRESSOR_IS_ACTIVE) {
1221 		vm_compressor_is_active = 1;
1222 	}
1223 
1224 	vm_compressor_available = 1;
1225 
1226 	vm_page_reactivate_all_throttled();
1227 
1228 	bzero(&vmcs_stats, sizeof(struct vm_compressor_swapper_stats));
1229 }
1230 
1231 #define COMPRESSOR_KDP_BUFSIZE (\
1232 	(vm_compressor_get_decode_scratch_size() * compressor_cpus) + \
1233 	(PAGE_SIZE * compressor_cpus)) + \
1234 	(sizeof(*vm_compressor_kdp_state.kc_decompressed_pages_paddr) * compressor_cpus) + \
1235 	(sizeof(*vm_compressor_kdp_state.kc_decompressed_pages_ppnum) * compressor_cpus)
1236 
1237 
1238 /**
1239  * Initializes the VM compressor in preparation for a stackshot.
1240  * Stackshot mutex must be held.
1241  */
1242 kern_return_t
vm_compressor_kdp_init(void)1243 vm_compressor_kdp_init(void)
1244 {
1245 	char *buf;
1246 	kern_return_t err;
1247 	size_t bufsize;
1248 	size_t total_decode_size;
1249 
1250 #if DEVELOPMENT || DEBUG
1251 	extern lck_mtx_t stackshot_subsys_mutex;
1252 	lck_mtx_assert(&stackshot_subsys_mutex, LCK_MTX_ASSERT_OWNED);
1253 #endif /* DEVELOPMENT || DEBUG */
1254 
1255 	if (!vm_compressor_available) {
1256 		return KERN_SUCCESS;
1257 	}
1258 
1259 	bufsize = COMPRESSOR_KDP_BUFSIZE;
1260 
1261 	/* Allocate the per-cpu decompression pages. */
1262 	err = kmem_alloc(kernel_map, (vm_offset_t *)&buf, bufsize,
1263 	    KMA_DATA | KMA_NOFAIL | KMA_KOBJECT,
1264 	    VM_KERN_MEMORY_COMPRESSOR);
1265 
1266 	if (err != KERN_SUCCESS) {
1267 		return err;
1268 	}
1269 
1270 	assert(vm_compressor_kdp_state.kc_scratch_bufs == NULL);
1271 	vm_compressor_kdp_state.kc_scratch_bufs = buf;
1272 	total_decode_size = vm_compressor_get_decode_scratch_size() * compressor_cpus;
1273 	buf += total_decode_size;
1274 	bufsize -= total_decode_size;
1275 
1276 	/*
1277 	 * vm_compressor_kdp_state.kc_decompressed_page must be page aligned because we access
1278 	 * it through the physical aperture by page number.
1279 	 */
1280 	assert(vm_compressor_kdp_state.kc_decompressed_pages == NULL);
1281 	vm_compressor_kdp_state.kc_decompressed_pages = buf;
1282 	buf += PAGE_SIZE * compressor_cpus;
1283 	bufsize -= PAGE_SIZE * compressor_cpus;
1284 
1285 	/* Scary! This will be aligned, I promise :) */
1286 	assert(((vm_address_t) buf) % _Alignof(addr64_t) == 0);
1287 	assert(vm_compressor_kdp_state.kc_decompressed_pages_paddr == NULL);
1288 	vm_compressor_kdp_state.kc_decompressed_pages_paddr = (addr64_t*) (void*) buf;
1289 	buf += sizeof(*vm_compressor_kdp_state.kc_decompressed_pages_paddr) * compressor_cpus;
1290 	bufsize -= sizeof(*vm_compressor_kdp_state.kc_decompressed_pages_paddr) * compressor_cpus;
1291 
1292 	assert(((vm_address_t) buf) % _Alignof(ppnum_t) == 0);
1293 	assert(vm_compressor_kdp_state.kc_decompressed_pages_ppnum == NULL);
1294 	vm_compressor_kdp_state.kc_decompressed_pages_ppnum = (ppnum_t*) (void*) buf;
1295 	buf += sizeof(*vm_compressor_kdp_state.kc_decompressed_pages_ppnum) * compressor_cpus;
1296 	bufsize -= sizeof(*vm_compressor_kdp_state.kc_decompressed_pages_ppnum) * compressor_cpus;
1297 
1298 	assert(bufsize == 0);
1299 
1300 	for (size_t i = 0; i < compressor_cpus; i++) {
1301 		vm_offset_t offset = (vm_offset_t) &vm_compressor_kdp_state.kc_decompressed_pages[i * PAGE_SIZE];
1302 		vm_compressor_kdp_state.kc_decompressed_pages_paddr[i] = kvtophys(offset);
1303 		vm_compressor_kdp_state.kc_decompressed_pages_ppnum[i] = (ppnum_t) atop(vm_compressor_kdp_state.kc_decompressed_pages_paddr[i]);
1304 	}
1305 
1306 	return KERN_SUCCESS;
1307 }
1308 
1309 /*
1310  * Frees up compressor buffers used by stackshot.
1311  * Stackshot mutex must be held.
1312  */
1313 void
vm_compressor_kdp_teardown(void)1314 vm_compressor_kdp_teardown(void)
1315 {
1316 	extern lck_mtx_t stackshot_subsys_mutex;
1317 	LCK_MTX_ASSERT(&stackshot_subsys_mutex, LCK_MTX_ASSERT_OWNED);
1318 
1319 	if (vm_compressor_kdp_state.kc_scratch_bufs == NULL) {
1320 		return;
1321 	}
1322 
1323 	/* Deallocate the per-cpu decompression pages. */
1324 	kmem_free(kernel_map, (vm_offset_t) vm_compressor_kdp_state.kc_scratch_bufs, COMPRESSOR_KDP_BUFSIZE);
1325 
1326 	vm_compressor_kdp_state.kc_scratch_bufs = NULL;
1327 	vm_compressor_kdp_state.kc_decompressed_pages = NULL;
1328 	vm_compressor_kdp_state.kc_decompressed_pages_paddr = 0;
1329 	vm_compressor_kdp_state.kc_decompressed_pages_ppnum = 0;
1330 }
1331 
1332 static uint32_t
c_slot_extra_size(c_slot_t cs)1333 c_slot_extra_size(c_slot_t cs)
1334 {
1335 #pragma unused(cs)
1336 	return 0;
1337 }
1338 
1339 #if VALIDATE_C_SEGMENTS
1340 
1341 static void
c_seg_validate(c_segment_t c_seg,boolean_t must_be_compact)1342 c_seg_validate(c_segment_t c_seg, boolean_t must_be_compact)
1343 {
1344 	uint16_t        c_indx;
1345 	int32_t         bytes_used;
1346 	uint32_t        c_rounded_size;
1347 	uint32_t        c_size;
1348 	c_slot_t        cs;
1349 
1350 	if (__probable(validate_c_segs == FALSE)) {
1351 		return;
1352 	}
1353 	if (c_seg->c_firstemptyslot < c_seg->c_nextslot) {
1354 		c_indx = c_seg->c_firstemptyslot;
1355 		cs = C_SEG_SLOT_FROM_INDEX(c_seg, c_indx);
1356 
1357 		if (cs == NULL) {
1358 			panic("c_seg_validate:  no slot backing c_firstemptyslot");
1359 		}
1360 
1361 		if (cs->c_size) {
1362 			panic("c_seg_validate:  c_firstemptyslot has non-zero size (%d)", cs->c_size);
1363 		}
1364 	}
1365 	bytes_used = 0;
1366 
1367 	for (c_indx = 0; c_indx < c_seg->c_nextslot; c_indx++) {
1368 		cs = C_SEG_SLOT_FROM_INDEX(c_seg, c_indx);
1369 
1370 		c_size = UNPACK_C_SIZE(cs);
1371 
1372 		c_rounded_size = C_SEG_ROUND_TO_ALIGNMENT(c_size + c_slot_extra_size(cs));
1373 
1374 		bytes_used += c_rounded_size;
1375 
1376 #if CHECKSUM_THE_COMPRESSED_DATA
1377 		unsigned csvhash;
1378 		if (c_size && cs->c_hash_compressed_data != (csvhash = vmc_hash((char *)&c_seg->c_store.c_buffer[cs->c_offset], c_size))) {
1379 			addr64_t csvphys = kvtophys((vm_offset_t)&c_seg->c_store.c_buffer[cs->c_offset]);
1380 			panic("Compressed data doesn't match original %p phys: 0x%llx %d %p %d %d 0x%x 0x%x", c_seg, csvphys, cs->c_offset, cs, c_indx, c_size, cs->c_hash_compressed_data, csvhash);
1381 		}
1382 #endif
1383 #if POPCOUNT_THE_COMPRESSED_DATA
1384 		unsigned csvpop;
1385 		if (c_size) {
1386 			uintptr_t csvaddr = (uintptr_t) &c_seg->c_store.c_buffer[cs->c_offset];
1387 			if (cs->c_pop_cdata != (csvpop = vmc_pop(csvaddr, c_size))) {
1388 				panic("Compressed data popcount doesn't match original, bit distance: %d %p (phys: %p) %p %p 0x%llx 0x%x 0x%x 0x%x", (csvpop - cs->c_pop_cdata), (void *)csvaddr, (void *) kvtophys(csvaddr), c_seg, cs, (uint64_t)cs->c_offset, c_size, csvpop, cs->c_pop_cdata);
1389 			}
1390 		}
1391 #endif
1392 	}
1393 
1394 	if (bytes_used != c_seg->c_bytes_used) {
1395 		panic("c_seg_validate: bytes_used mismatch - found %d, segment has %d", bytes_used, c_seg->c_bytes_used);
1396 	}
1397 
1398 	if (c_seg->c_bytes_used > C_SEG_OFFSET_TO_BYTES((int32_t)c_seg->c_nextoffset)) {
1399 		panic("c_seg_validate: c_bytes_used > c_nextoffset - c_nextoffset = %d,  c_bytes_used = %d",
1400 		    (int32_t)C_SEG_OFFSET_TO_BYTES((int32_t)c_seg->c_nextoffset), c_seg->c_bytes_used);
1401 	}
1402 
1403 	if (must_be_compact) {
1404 		if (c_seg->c_bytes_used != C_SEG_OFFSET_TO_BYTES((int32_t)c_seg->c_nextoffset)) {
1405 			panic("c_seg_validate: c_bytes_used doesn't match c_nextoffset - c_nextoffset = %d,  c_bytes_used = %d",
1406 			    (int32_t)C_SEG_OFFSET_TO_BYTES((int32_t)c_seg->c_nextoffset), c_seg->c_bytes_used);
1407 		}
1408 	}
1409 }
1410 
1411 #endif
1412 
1413 
1414 void
c_seg_need_delayed_compaction(c_segment_t c_seg,boolean_t c_list_lock_held)1415 c_seg_need_delayed_compaction(c_segment_t c_seg, boolean_t c_list_lock_held)
1416 {
1417 	boolean_t       clear_busy = FALSE;
1418 
1419 	if (c_list_lock_held == FALSE) {
1420 		if (!lck_mtx_try_lock_spin_always(c_list_lock)) {
1421 			C_SEG_BUSY(c_seg);
1422 
1423 			lck_mtx_unlock_always(&c_seg->c_lock);
1424 			lck_mtx_lock_spin_always(c_list_lock);
1425 			lck_mtx_lock_spin_always(&c_seg->c_lock);
1426 
1427 			clear_busy = TRUE;
1428 		}
1429 	}
1430 	assert(c_seg->c_state != C_IS_FILLING);
1431 
1432 	if (!c_seg->c_on_minorcompact_q && !(C_SEG_IS_ON_DISK_OR_SOQ(c_seg)) && !c_seg->c_has_donated_pages) {
1433 		queue_enter(&c_minor_list_head, c_seg, c_segment_t, c_list);
1434 		c_seg->c_on_minorcompact_q = 1;
1435 		os_atomic_inc(&c_minor_count, relaxed);
1436 	}
1437 	if (c_list_lock_held == FALSE) {
1438 		lck_mtx_unlock_always(c_list_lock);
1439 	}
1440 
1441 	if (clear_busy == TRUE) {
1442 		C_SEG_WAKEUP_DONE(c_seg);
1443 	}
1444 }
1445 
1446 
1447 unsigned int c_seg_moved_to_sparse_list = 0;
1448 
1449 void
c_seg_move_to_sparse_list(c_segment_t c_seg)1450 c_seg_move_to_sparse_list(c_segment_t c_seg)
1451 {
1452 	boolean_t       clear_busy = FALSE;
1453 
1454 	if (!lck_mtx_try_lock_spin_always(c_list_lock)) {
1455 		C_SEG_BUSY(c_seg);
1456 
1457 		lck_mtx_unlock_always(&c_seg->c_lock);
1458 		lck_mtx_lock_spin_always(c_list_lock);
1459 		lck_mtx_lock_spin_always(&c_seg->c_lock);
1460 
1461 		clear_busy = TRUE;
1462 	}
1463 	c_seg_switch_state(c_seg, C_ON_SWAPPEDOUTSPARSE_Q, FALSE);
1464 
1465 	c_seg_moved_to_sparse_list++;
1466 
1467 	lck_mtx_unlock_always(c_list_lock);
1468 
1469 	if (clear_busy == TRUE) {
1470 		C_SEG_WAKEUP_DONE(c_seg);
1471 	}
1472 }
1473 
1474 
1475 
1476 
1477 int try_minor_compaction_failed = 0;
1478 int try_minor_compaction_succeeded = 0;
1479 
1480 void
c_seg_try_minor_compaction_and_unlock(c_segment_t c_seg)1481 c_seg_try_minor_compaction_and_unlock(c_segment_t c_seg)
1482 {
1483 	assert(c_seg->c_on_minorcompact_q);
1484 	/*
1485 	 * c_seg is currently on the delayed minor compaction
1486 	 * queue and we have c_seg locked... if we can get the
1487 	 * c_list_lock w/o blocking (if we blocked we could deadlock
1488 	 * because the lock order is c_list_lock then c_seg's lock)
1489 	 * we'll pull it from the delayed list and free it directly
1490 	 */
1491 	if (!lck_mtx_try_lock_spin_always(c_list_lock)) {
1492 		/*
1493 		 * c_list_lock is held, we need to bail
1494 		 */
1495 		try_minor_compaction_failed++;
1496 
1497 		lck_mtx_unlock_always(&c_seg->c_lock);
1498 	} else {
1499 		try_minor_compaction_succeeded++;
1500 
1501 		C_SEG_BUSY(c_seg);
1502 		c_seg_do_minor_compaction_and_unlock(c_seg, TRUE, FALSE, FALSE);
1503 	}
1504 }
1505 
1506 
1507 int
c_seg_do_minor_compaction_and_unlock(c_segment_t c_seg,boolean_t clear_busy,boolean_t need_list_lock,boolean_t disallow_page_replacement)1508 c_seg_do_minor_compaction_and_unlock(c_segment_t c_seg, boolean_t clear_busy, boolean_t need_list_lock, boolean_t disallow_page_replacement)
1509 {
1510 	int     c_seg_freed;
1511 
1512 	assert(c_seg->c_busy);
1513 	assert(!C_SEG_IS_ON_DISK_OR_SOQ(c_seg));
1514 
1515 	/*
1516 	 * check for the case that can occur when we are not swapping
1517 	 * and this segment has been major compacted in the past
1518 	 * and moved to the majorcompact q to remove it from further
1519 	 * consideration... if the occupancy falls too low we need
1520 	 * to put it back on the age_q so that it will be considered
1521 	 * in the next major compaction sweep... if we don't do this
1522 	 * we will eventually run into the c_segments_limit
1523 	 */
1524 	if (c_seg->c_state == C_ON_MAJORCOMPACT_Q && C_SEG_SHOULD_MAJORCOMPACT_NOW(c_seg)) {
1525 		c_seg_switch_state(c_seg, C_ON_AGE_Q, FALSE);
1526 	}
1527 	if (!c_seg->c_on_minorcompact_q) {
1528 		if (clear_busy == TRUE) {
1529 			C_SEG_WAKEUP_DONE(c_seg);
1530 		}
1531 
1532 		lck_mtx_unlock_always(&c_seg->c_lock);
1533 
1534 		return 0;
1535 	}
1536 	queue_remove(&c_minor_list_head, c_seg, c_segment_t, c_list);
1537 	c_seg->c_on_minorcompact_q = 0;
1538 	os_atomic_dec(&c_minor_count, relaxed);
1539 
1540 	lck_mtx_unlock_always(c_list_lock);
1541 
1542 	if (disallow_page_replacement == TRUE) {
1543 		lck_mtx_unlock_always(&c_seg->c_lock);
1544 
1545 		PAGE_REPLACEMENT_DISALLOWED(TRUE);
1546 
1547 		lck_mtx_lock_spin_always(&c_seg->c_lock);
1548 	}
1549 	c_seg_freed = c_seg_minor_compaction_and_unlock(c_seg, clear_busy);
1550 
1551 	if (disallow_page_replacement == TRUE) {
1552 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
1553 	}
1554 
1555 	if (need_list_lock == TRUE) {
1556 		lck_mtx_lock_spin_always(c_list_lock);
1557 	}
1558 
1559 	return c_seg_freed;
1560 }
1561 
1562 void
kdp_compressor_busy_find_owner(event64_t wait_event,thread_waitinfo_t * waitinfo)1563 kdp_compressor_busy_find_owner(event64_t wait_event, thread_waitinfo_t *waitinfo)
1564 {
1565 	c_segment_t c_seg = (c_segment_t) wait_event;
1566 
1567 	waitinfo->owner = thread_tid(c_seg->c_busy_for_thread);
1568 	waitinfo->context = VM_KERNEL_UNSLIDE_OR_PERM(c_seg);
1569 }
1570 
1571 #if DEVELOPMENT || DEBUG
1572 int
do_cseg_wedge_thread(void)1573 do_cseg_wedge_thread(void)
1574 {
1575 	struct c_segment c_seg;
1576 	c_seg.c_busy_for_thread = current_thread();
1577 
1578 	debug_cseg_wait_event = (event_t) &c_seg;
1579 
1580 	thread_set_pending_block_hint(current_thread(), kThreadWaitCompressor);
1581 	assert_wait((event_t) (&c_seg), THREAD_INTERRUPTIBLE);
1582 
1583 	thread_block(THREAD_CONTINUE_NULL);
1584 
1585 	return 0;
1586 }
1587 
1588 int
do_cseg_unwedge_thread(void)1589 do_cseg_unwedge_thread(void)
1590 {
1591 	thread_wakeup(debug_cseg_wait_event);
1592 	debug_cseg_wait_event = NULL;
1593 
1594 	return 0;
1595 }
1596 #endif /* DEVELOPMENT || DEBUG */
1597 
1598 void
c_seg_wait_on_busy(c_segment_t c_seg)1599 c_seg_wait_on_busy(c_segment_t c_seg)
1600 {
1601 	c_seg->c_wanted = 1;
1602 
1603 	thread_set_pending_block_hint(current_thread(), kThreadWaitCompressor);
1604 	assert_wait((event_t) (c_seg), THREAD_UNINT);
1605 
1606 	lck_mtx_unlock_always(&c_seg->c_lock);
1607 	thread_block(THREAD_CONTINUE_NULL);
1608 }
1609 
1610 #if CONFIG_FREEZE
1611 /*
1612  * We don't have the task lock held while updating the task's
1613  * c_seg queues. We can do that because of the following restrictions:
1614  *
1615  * - SINGLE FREEZER CONTEXT:
1616  *   We 'insert' c_segs into the task list on the task_freeze path.
1617  *   There can only be one such freeze in progress and the task
1618  *   isn't disappearing because we have the VM map lock held throughout
1619  *   and we have a reference on the proc too.
1620  *
1621  * - SINGLE TASK DISOWN CONTEXT:
1622  *   We 'disown' c_segs of a task ONLY from the task_terminate context. So
1623  *   we don't need the task lock but we need the c_list_lock and the
1624  *   compressor master lock (shared). We also hold the individual
1625  *   c_seg locks (exclusive).
1626  *
1627  *   If we either:
1628  *   - can't get the c_seg lock on a try, then we start again because maybe
1629  *   the c_seg is part of a compaction and might get freed. So we can't trust
1630  *   that linkage and need to restart our queue traversal.
1631  *   - OR, we run into a busy c_seg (say being swapped in or free-ing) we
1632  *   drop all locks again and wait and restart our queue traversal.
1633  *
1634  * - The new_owner_task below is currently only the kernel or NULL.
1635  *
1636  */
1637 void
c_seg_update_task_owner(c_segment_t c_seg,task_t new_owner_task)1638 c_seg_update_task_owner(c_segment_t c_seg, task_t new_owner_task)
1639 {
1640 	task_t          owner_task = c_seg->c_task_owner;
1641 	uint64_t        uncompressed_bytes = ((c_seg->c_slots_used) * PAGE_SIZE_64);
1642 
1643 	LCK_MTX_ASSERT(c_list_lock, LCK_MTX_ASSERT_OWNED);
1644 	LCK_MTX_ASSERT(&c_seg->c_lock, LCK_MTX_ASSERT_OWNED);
1645 
1646 	if (owner_task) {
1647 		task_update_frozen_to_swap_acct(owner_task, uncompressed_bytes, DEBIT_FROM_SWAP);
1648 		queue_remove(&owner_task->task_frozen_cseg_q, c_seg,
1649 		    c_segment_t, c_task_list_next_cseg);
1650 	}
1651 
1652 	if (new_owner_task) {
1653 		queue_enter(&new_owner_task->task_frozen_cseg_q, c_seg,
1654 		    c_segment_t, c_task_list_next_cseg);
1655 		task_update_frozen_to_swap_acct(new_owner_task, uncompressed_bytes, CREDIT_TO_SWAP);
1656 	}
1657 
1658 	c_seg->c_task_owner = new_owner_task;
1659 }
1660 
1661 void
task_disown_frozen_csegs(task_t owner_task)1662 task_disown_frozen_csegs(task_t owner_task)
1663 {
1664 	c_segment_t c_seg = NULL, next_cseg = NULL;
1665 
1666 again:
1667 	PAGE_REPLACEMENT_DISALLOWED(TRUE);
1668 	lck_mtx_lock_spin_always(c_list_lock);
1669 
1670 	for (c_seg = (c_segment_t) queue_first(&owner_task->task_frozen_cseg_q);
1671 	    !queue_end(&owner_task->task_frozen_cseg_q, (queue_entry_t) c_seg);
1672 	    c_seg = next_cseg) {
1673 		next_cseg = (c_segment_t) queue_next(&c_seg->c_task_list_next_cseg);
1674 
1675 		if (!lck_mtx_try_lock_spin_always(&c_seg->c_lock)) {
1676 			lck_mtx_unlock(c_list_lock);
1677 			PAGE_REPLACEMENT_DISALLOWED(FALSE);
1678 			goto again;
1679 		}
1680 
1681 		if (c_seg->c_busy) {
1682 			lck_mtx_unlock(c_list_lock);
1683 			PAGE_REPLACEMENT_DISALLOWED(FALSE);
1684 
1685 			c_seg_wait_on_busy(c_seg);
1686 
1687 			goto again;
1688 		}
1689 		assert(c_seg->c_task_owner == owner_task);
1690 		c_seg_update_task_owner(c_seg, kernel_task);
1691 		lck_mtx_unlock_always(&c_seg->c_lock);
1692 	}
1693 
1694 	lck_mtx_unlock(c_list_lock);
1695 	PAGE_REPLACEMENT_DISALLOWED(FALSE);
1696 }
1697 #endif /* CONFIG_FREEZE */
1698 
1699 void
c_seg_switch_state(c_segment_t c_seg,int new_state,boolean_t insert_head)1700 c_seg_switch_state(c_segment_t c_seg, int new_state, boolean_t insert_head)
1701 {
1702 	int     old_state = c_seg->c_state;
1703 	queue_head_t *donate_swapout_list_head, *donate_swappedin_list_head;
1704 	uint32_t     *donate_swapout_count, *donate_swappedin_count;
1705 
1706 	/*
1707 	 * On macOS the donate queue is swapped first ie the c_early_swapout queue.
1708 	 * On other swap-capable platforms, we want to swap those out last. So we
1709 	 * use the c_late_swapout queue.
1710 	 */
1711 #if XNU_TARGET_OS_OSX  /* tag:DONATE */
1712 #if (DEVELOPMENT || DEBUG)
1713 	if (new_state != C_IS_FILLING) {
1714 		LCK_MTX_ASSERT(&c_seg->c_lock, LCK_MTX_ASSERT_OWNED);
1715 	}
1716 	LCK_MTX_ASSERT(c_list_lock, LCK_MTX_ASSERT_OWNED);
1717 #endif /* DEVELOPMENT || DEBUG */
1718 
1719 	donate_swapout_list_head = &c_early_swapout_list_head;
1720 	donate_swapout_count = &c_early_swapout_count;
1721 	donate_swappedin_list_head = &c_early_swappedin_list_head;
1722 	donate_swappedin_count = &c_early_swappedin_count;
1723 #else /* XNU_TARGET_OS_OSX */
1724 	donate_swapout_list_head = &c_late_swapout_list_head;
1725 	donate_swapout_count = &c_late_swapout_count;
1726 	donate_swappedin_list_head = &c_late_swappedin_list_head;
1727 	donate_swappedin_count = &c_late_swappedin_count;
1728 #endif /* XNU_TARGET_OS_OSX */
1729 
1730 	switch (old_state) {
1731 	case C_IS_EMPTY:
1732 		assert(new_state == C_IS_FILLING || new_state == C_IS_FREE);
1733 
1734 		c_empty_count--;
1735 		break;
1736 
1737 	case C_IS_FILLING:
1738 		assert(new_state == C_ON_AGE_Q || new_state == C_ON_SWAPOUT_Q);
1739 
1740 		queue_remove(&c_filling_list_head, c_seg, c_segment_t, c_age_list);
1741 		c_filling_count--;
1742 		break;
1743 
1744 	case C_ON_AGE_Q:
1745 		assert(new_state == C_ON_SWAPOUT_Q || new_state == C_ON_MAJORCOMPACT_Q ||
1746 		    new_state == C_IS_FREE);
1747 
1748 		queue_remove(&c_age_list_head, c_seg, c_segment_t, c_age_list);
1749 		c_age_count--;
1750 		break;
1751 
1752 	case C_ON_SWAPPEDIN_Q:
1753 		if (c_seg->c_has_donated_pages) {
1754 			assert(new_state == C_ON_SWAPOUT_Q || new_state == C_IS_FREE);
1755 			queue_remove(donate_swappedin_list_head, c_seg, c_segment_t, c_age_list);
1756 			*donate_swappedin_count -= 1;
1757 		} else {
1758 			assert(new_state == C_ON_AGE_Q || new_state == C_IS_FREE);
1759 #if CONFIG_FREEZE
1760 			assert(c_seg->c_has_freezer_pages);
1761 			queue_remove(&c_early_swappedin_list_head, c_seg, c_segment_t, c_age_list);
1762 			c_early_swappedin_count--;
1763 #else /* CONFIG_FREEZE */
1764 			queue_remove(&c_regular_swappedin_list_head, c_seg, c_segment_t, c_age_list);
1765 			c_regular_swappedin_count--;
1766 #endif /* CONFIG_FREEZE */
1767 		}
1768 		break;
1769 
1770 	case C_ON_SWAPOUT_Q:
1771 		assert(new_state == C_ON_AGE_Q || new_state == C_IS_FREE || new_state == C_IS_EMPTY || new_state == C_ON_SWAPIO_Q);
1772 
1773 #if CONFIG_FREEZE
1774 		if (c_seg->c_has_freezer_pages) {
1775 			if (c_seg->c_task_owner && (new_state != C_ON_SWAPIO_Q)) {
1776 				c_seg_update_task_owner(c_seg, NULL);
1777 			}
1778 			queue_remove(&c_early_swapout_list_head, c_seg, c_segment_t, c_age_list);
1779 			c_early_swapout_count--;
1780 		} else
1781 #endif /* CONFIG_FREEZE */
1782 		{
1783 			if (c_seg->c_has_donated_pages) {
1784 				queue_remove(donate_swapout_list_head, c_seg, c_segment_t, c_age_list);
1785 				*donate_swapout_count -= 1;
1786 			} else {
1787 				queue_remove(&c_regular_swapout_list_head, c_seg, c_segment_t, c_age_list);
1788 				c_regular_swapout_count--;
1789 			}
1790 		}
1791 
1792 		if (new_state == C_ON_AGE_Q) {
1793 			c_seg->c_has_donated_pages = 0;
1794 		}
1795 		thread_wakeup((event_t)&compaction_swapper_running);
1796 		break;
1797 
1798 	case C_ON_SWAPIO_Q:
1799 #if CONFIG_FREEZE
1800 		if (c_seg->c_has_freezer_pages) {
1801 			assert(new_state == C_ON_SWAPPEDOUT_Q || new_state == C_ON_SWAPPEDOUTSPARSE_Q || new_state == C_ON_AGE_Q);
1802 		} else
1803 #endif /* CONFIG_FREEZE */
1804 		{
1805 			if (c_seg->c_has_donated_pages) {
1806 				assert(new_state == C_ON_SWAPPEDOUT_Q || new_state == C_ON_SWAPPEDOUTSPARSE_Q || new_state == C_ON_SWAPPEDIN_Q);
1807 			} else {
1808 				assert(new_state == C_ON_SWAPPEDOUT_Q || new_state == C_ON_SWAPPEDOUTSPARSE_Q || new_state == C_ON_AGE_Q);
1809 			}
1810 		}
1811 
1812 		queue_remove(&c_swapio_list_head, c_seg, c_segment_t, c_age_list);
1813 		c_swapio_count--;
1814 		break;
1815 
1816 	case C_ON_SWAPPEDOUT_Q:
1817 		assert(new_state == C_ON_SWAPPEDIN_Q || new_state == C_ON_AGE_Q ||
1818 		    new_state == C_ON_SWAPPEDOUTSPARSE_Q ||
1819 		    new_state == C_ON_BAD_Q || new_state == C_IS_EMPTY || new_state == C_IS_FREE);
1820 
1821 		queue_remove(&c_swappedout_list_head, c_seg, c_segment_t, c_age_list);
1822 		c_swappedout_count--;
1823 		break;
1824 
1825 	case C_ON_SWAPPEDOUTSPARSE_Q:
1826 		assert(new_state == C_ON_SWAPPEDIN_Q || new_state == C_ON_AGE_Q ||
1827 		    new_state == C_ON_BAD_Q || new_state == C_IS_EMPTY || new_state == C_IS_FREE);
1828 
1829 		queue_remove(&c_swappedout_sparse_list_head, c_seg, c_segment_t, c_age_list);
1830 		c_swappedout_sparse_count--;
1831 		break;
1832 
1833 	case C_ON_MAJORCOMPACT_Q:
1834 		assert(new_state == C_ON_AGE_Q || new_state == C_IS_FREE);
1835 
1836 		queue_remove(&c_major_list_head, c_seg, c_segment_t, c_age_list);
1837 		c_major_count--;
1838 		break;
1839 
1840 	case C_ON_BAD_Q:
1841 		assert(new_state == C_IS_FREE);
1842 
1843 		queue_remove(&c_bad_list_head, c_seg, c_segment_t, c_age_list);
1844 		c_bad_count--;
1845 		break;
1846 
1847 	default:
1848 		panic("c_seg %p has bad c_state = %d", c_seg, old_state);
1849 	}
1850 
1851 	switch (new_state) {
1852 	case C_IS_FREE:
1853 		assert(old_state != C_IS_FILLING);
1854 
1855 		break;
1856 
1857 	case C_IS_EMPTY:
1858 		assert(old_state == C_ON_SWAPOUT_Q || old_state == C_ON_SWAPPEDOUT_Q || old_state == C_ON_SWAPPEDOUTSPARSE_Q);
1859 
1860 		c_empty_count++;
1861 		break;
1862 
1863 	case C_IS_FILLING:
1864 		assert(old_state == C_IS_EMPTY);
1865 
1866 		queue_enter(&c_filling_list_head, c_seg, c_segment_t, c_age_list);
1867 		c_filling_count++;
1868 		break;
1869 
1870 	case C_ON_AGE_Q:
1871 		assert(old_state == C_IS_FILLING || old_state == C_ON_SWAPPEDIN_Q ||
1872 		    old_state == C_ON_SWAPOUT_Q || old_state == C_ON_SWAPIO_Q ||
1873 		    old_state == C_ON_MAJORCOMPACT_Q || old_state == C_ON_SWAPPEDOUT_Q || old_state == C_ON_SWAPPEDOUTSPARSE_Q);
1874 
1875 		assert(!c_seg->c_has_donated_pages);
1876 		if (old_state == C_IS_FILLING) {
1877 			queue_enter(&c_age_list_head, c_seg, c_segment_t, c_age_list);
1878 		} else {
1879 			if (!queue_empty(&c_age_list_head)) {
1880 				c_segment_t     c_first;
1881 
1882 				c_first = (c_segment_t)queue_first(&c_age_list_head);
1883 				c_seg->c_creation_ts = c_first->c_creation_ts;
1884 			}
1885 			queue_enter_first(&c_age_list_head, c_seg, c_segment_t, c_age_list);
1886 		}
1887 		c_age_count++;
1888 		break;
1889 
1890 	case C_ON_SWAPPEDIN_Q:
1891 	{
1892 		queue_head_t *list_head;
1893 
1894 		assert(old_state == C_ON_SWAPPEDOUT_Q || old_state == C_ON_SWAPPEDOUTSPARSE_Q || old_state == C_ON_SWAPIO_Q);
1895 		if (c_seg->c_has_donated_pages) {
1896 			/* Error in swapouts could happen while the c_seg is still on the swapio queue */
1897 			list_head = donate_swappedin_list_head;
1898 			*donate_swappedin_count += 1;
1899 		} else {
1900 #if CONFIG_FREEZE
1901 			assert(c_seg->c_has_freezer_pages);
1902 			list_head = &c_early_swappedin_list_head;
1903 			c_early_swappedin_count++;
1904 #else /* CONFIG_FREEZE */
1905 			list_head = &c_regular_swappedin_list_head;
1906 			c_regular_swappedin_count++;
1907 #endif /* CONFIG_FREEZE */
1908 		}
1909 
1910 		if (insert_head == TRUE) {
1911 			queue_enter_first(list_head, c_seg, c_segment_t, c_age_list);
1912 		} else {
1913 			queue_enter(list_head, c_seg, c_segment_t, c_age_list);
1914 		}
1915 		break;
1916 	}
1917 
1918 	case C_ON_SWAPOUT_Q:
1919 	{
1920 		queue_head_t *list_head;
1921 
1922 #if CONFIG_FREEZE
1923 		/*
1924 		 * A segment with both identities of frozen + donated pages
1925 		 * will be put on early swapout Q ie the frozen identity wins.
1926 		 * This is because when both identities are set, the donation bit
1927 		 * is added on after in the c_current_seg_filled path for accounting
1928 		 * purposes.
1929 		 */
1930 		if (c_seg->c_has_freezer_pages) {
1931 			assert(old_state == C_ON_AGE_Q || old_state == C_IS_FILLING);
1932 			list_head = &c_early_swapout_list_head;
1933 			c_early_swapout_count++;
1934 		} else
1935 #endif
1936 		{
1937 			if (c_seg->c_has_donated_pages) {
1938 				assert(old_state == C_ON_SWAPPEDIN_Q || old_state == C_IS_FILLING);
1939 				list_head = donate_swapout_list_head;
1940 				*donate_swapout_count += 1;
1941 			} else {
1942 				assert(old_state == C_ON_AGE_Q || old_state == C_IS_FILLING);
1943 				list_head = &c_regular_swapout_list_head;
1944 				c_regular_swapout_count++;
1945 			}
1946 		}
1947 
1948 		if (insert_head == TRUE) {
1949 			queue_enter_first(list_head, c_seg, c_segment_t, c_age_list);
1950 		} else {
1951 			queue_enter(list_head, c_seg, c_segment_t, c_age_list);
1952 		}
1953 		break;
1954 	}
1955 
1956 	case C_ON_SWAPIO_Q:
1957 		assert(old_state == C_ON_SWAPOUT_Q);
1958 
1959 		if (insert_head == TRUE) {
1960 			queue_enter_first(&c_swapio_list_head, c_seg, c_segment_t, c_age_list);
1961 		} else {
1962 			queue_enter(&c_swapio_list_head, c_seg, c_segment_t, c_age_list);
1963 		}
1964 		c_swapio_count++;
1965 		break;
1966 
1967 	case C_ON_SWAPPEDOUT_Q:
1968 		assert(old_state == C_ON_SWAPIO_Q);
1969 
1970 		if (insert_head == TRUE) {
1971 			queue_enter_first(&c_swappedout_list_head, c_seg, c_segment_t, c_age_list);
1972 		} else {
1973 			queue_enter(&c_swappedout_list_head, c_seg, c_segment_t, c_age_list);
1974 		}
1975 		c_swappedout_count++;
1976 		break;
1977 
1978 	case C_ON_SWAPPEDOUTSPARSE_Q:
1979 		assert(old_state == C_ON_SWAPIO_Q || old_state == C_ON_SWAPPEDOUT_Q);
1980 
1981 		if (insert_head == TRUE) {
1982 			queue_enter_first(&c_swappedout_sparse_list_head, c_seg, c_segment_t, c_age_list);
1983 		} else {
1984 			queue_enter(&c_swappedout_sparse_list_head, c_seg, c_segment_t, c_age_list);
1985 		}
1986 
1987 		c_swappedout_sparse_count++;
1988 		break;
1989 
1990 	case C_ON_MAJORCOMPACT_Q:
1991 		assert(old_state == C_ON_AGE_Q);
1992 		assert(!c_seg->c_has_donated_pages);
1993 
1994 		if (insert_head == TRUE) {
1995 			queue_enter_first(&c_major_list_head, c_seg, c_segment_t, c_age_list);
1996 		} else {
1997 			queue_enter(&c_major_list_head, c_seg, c_segment_t, c_age_list);
1998 		}
1999 		c_major_count++;
2000 		break;
2001 
2002 	case C_ON_BAD_Q:
2003 		assert(old_state == C_ON_SWAPPEDOUT_Q || old_state == C_ON_SWAPPEDOUTSPARSE_Q);
2004 
2005 		if (insert_head == TRUE) {
2006 			queue_enter_first(&c_bad_list_head, c_seg, c_segment_t, c_age_list);
2007 		} else {
2008 			queue_enter(&c_bad_list_head, c_seg, c_segment_t, c_age_list);
2009 		}
2010 		c_bad_count++;
2011 		break;
2012 
2013 	default:
2014 		panic("c_seg %p requesting bad c_state = %d", c_seg, new_state);
2015 	}
2016 	c_seg->c_state = new_state;
2017 }
2018 
2019 
2020 
2021 void
c_seg_free(c_segment_t c_seg)2022 c_seg_free(c_segment_t c_seg)
2023 {
2024 	assert(c_seg->c_busy);
2025 
2026 	lck_mtx_unlock_always(&c_seg->c_lock);
2027 	lck_mtx_lock_spin_always(c_list_lock);
2028 	lck_mtx_lock_spin_always(&c_seg->c_lock);
2029 
2030 	c_seg_free_locked(c_seg);
2031 }
2032 
2033 
2034 void
c_seg_free_locked(c_segment_t c_seg)2035 c_seg_free_locked(c_segment_t c_seg)
2036 {
2037 	int             segno;
2038 	int             pages_populated = 0;
2039 	int32_t         *c_buffer = NULL;
2040 	uint64_t        c_swap_handle = 0;
2041 
2042 	assert(c_seg->c_busy);
2043 	assert(c_seg->c_slots_used == 0);
2044 	assert(!c_seg->c_on_minorcompact_q);
2045 	assert(!c_seg->c_busy_swapping);
2046 
2047 	if (c_seg->c_overage_swap == TRUE) {
2048 		c_overage_swapped_count--;
2049 		c_seg->c_overage_swap = FALSE;
2050 	}
2051 	if (!(C_SEG_IS_ONDISK(c_seg))) {
2052 		c_buffer = c_seg->c_store.c_buffer;
2053 	} else {
2054 		c_swap_handle = c_seg->c_store.c_swap_handle;
2055 	}
2056 
2057 	c_seg_switch_state(c_seg, C_IS_FREE, FALSE);
2058 
2059 	if (c_buffer) {
2060 		pages_populated = (round_page_32(C_SEG_OFFSET_TO_BYTES(c_seg->c_populated_offset))) / PAGE_SIZE;
2061 		c_seg->c_store.c_buffer = NULL;
2062 	} else {
2063 #if CONFIG_FREEZE
2064 		c_seg_update_task_owner(c_seg, NULL);
2065 #endif /* CONFIG_FREEZE */
2066 
2067 		c_seg->c_store.c_swap_handle = (uint64_t)-1;
2068 	}
2069 
2070 	lck_mtx_unlock_always(&c_seg->c_lock);
2071 
2072 	lck_mtx_unlock_always(c_list_lock);
2073 
2074 	if (c_buffer) {
2075 		if (pages_populated) {
2076 			kernel_memory_depopulate((vm_offset_t)c_buffer,
2077 			    ptoa(pages_populated), KMA_COMPRESSOR,
2078 			    VM_KERN_MEMORY_COMPRESSOR);
2079 		}
2080 	} else if (c_swap_handle) {
2081 		/*
2082 		 * Free swap space on disk.
2083 		 */
2084 		vm_swap_free(c_swap_handle);
2085 	}
2086 	lck_mtx_lock_spin_always(&c_seg->c_lock);
2087 	/*
2088 	 * c_seg must remain busy until
2089 	 * after the call to vm_swap_free
2090 	 */
2091 	C_SEG_WAKEUP_DONE(c_seg);
2092 	lck_mtx_unlock_always(&c_seg->c_lock);
2093 
2094 	segno = c_seg->c_mysegno;
2095 
2096 	lck_mtx_lock_spin_always(c_list_lock);
2097 	/*
2098 	 * because the c_buffer is now associated with the segno,
2099 	 * we can't put the segno back on the free list until
2100 	 * after we have depopulated the c_buffer range, or
2101 	 * we run the risk of depopulating a range that is
2102 	 * now being used in one of the compressor heads
2103 	 */
2104 	c_segments_get(segno)->c_segno = c_free_segno_head;
2105 	c_free_segno_head = segno;
2106 	c_segment_count--;
2107 
2108 	lck_mtx_unlock_always(c_list_lock);
2109 
2110 	lck_mtx_destroy(&c_seg->c_lock, &vm_compressor_lck_grp);
2111 
2112 	if (c_seg->c_slot_var_array_len) {
2113 		kfree_type(struct c_slot, c_seg->c_slot_var_array_len,
2114 		    c_seg->c_slot_var_array);
2115 	}
2116 
2117 	zfree(compressor_segment_zone, c_seg);
2118 }
2119 
2120 #if DEVELOPMENT || DEBUG
2121 int c_seg_trim_page_count = 0;
2122 #endif
2123 
2124 void
c_seg_trim_tail(c_segment_t c_seg)2125 c_seg_trim_tail(c_segment_t c_seg)
2126 {
2127 	c_slot_t        cs;
2128 	uint32_t        c_size;
2129 	uint32_t        c_offset;
2130 	uint32_t        c_rounded_size;
2131 	uint16_t        current_nextslot;
2132 	uint32_t        current_populated_offset;
2133 
2134 	if (c_seg->c_bytes_used == 0) {
2135 		return;
2136 	}
2137 	current_nextslot = c_seg->c_nextslot;
2138 	current_populated_offset = c_seg->c_populated_offset;
2139 
2140 	while (c_seg->c_nextslot) {
2141 		cs = C_SEG_SLOT_FROM_INDEX(c_seg, (c_seg->c_nextslot - 1));
2142 
2143 		c_size = UNPACK_C_SIZE(cs);
2144 
2145 		if (c_size) {
2146 			if (current_nextslot != c_seg->c_nextslot) {
2147 				c_rounded_size = C_SEG_ROUND_TO_ALIGNMENT(c_size + c_slot_extra_size(cs));
2148 				c_offset = cs->c_offset + C_SEG_BYTES_TO_OFFSET(c_rounded_size);
2149 
2150 				c_seg->c_nextoffset = c_offset;
2151 				c_seg->c_populated_offset = (c_offset + (C_SEG_BYTES_TO_OFFSET(PAGE_SIZE) - 1)) &
2152 				    ~(C_SEG_BYTES_TO_OFFSET(PAGE_SIZE) - 1);
2153 
2154 				if (c_seg->c_firstemptyslot > c_seg->c_nextslot) {
2155 					c_seg->c_firstemptyslot = c_seg->c_nextslot;
2156 				}
2157 #if DEVELOPMENT || DEBUG
2158 				c_seg_trim_page_count += ((round_page_32(C_SEG_OFFSET_TO_BYTES(current_populated_offset)) -
2159 				    round_page_32(C_SEG_OFFSET_TO_BYTES(c_seg->c_populated_offset))) /
2160 				    PAGE_SIZE);
2161 #endif
2162 			}
2163 			break;
2164 		}
2165 		c_seg->c_nextslot--;
2166 	}
2167 	assert(c_seg->c_nextslot);
2168 }
2169 
2170 
2171 int
c_seg_minor_compaction_and_unlock(c_segment_t c_seg,boolean_t clear_busy)2172 c_seg_minor_compaction_and_unlock(c_segment_t c_seg, boolean_t clear_busy)
2173 {
2174 	c_slot_mapping_t slot_ptr;
2175 	uint32_t        c_offset = 0;
2176 	uint32_t        old_populated_offset;
2177 	uint32_t        c_rounded_size;
2178 	uint32_t        c_size;
2179 	uint16_t        c_indx = 0;
2180 	int             i;
2181 	c_slot_t        c_dst;
2182 	c_slot_t        c_src;
2183 
2184 	assert(c_seg->c_busy);
2185 
2186 #if VALIDATE_C_SEGMENTS
2187 	c_seg_validate(c_seg, FALSE);
2188 #endif
2189 	if (c_seg->c_bytes_used == 0) {
2190 		c_seg_free(c_seg);
2191 		return 1;
2192 	}
2193 	lck_mtx_unlock_always(&c_seg->c_lock);
2194 
2195 	if (c_seg->c_firstemptyslot >= c_seg->c_nextslot || C_SEG_UNUSED_BYTES(c_seg) < PAGE_SIZE) {
2196 		goto done;
2197 	}
2198 
2199 /* TODO: assert first emptyslot's c_size is actually 0 */
2200 
2201 #if DEVELOPMENT || DEBUG
2202 	C_SEG_MAKE_WRITEABLE(c_seg);
2203 #endif
2204 
2205 #if VALIDATE_C_SEGMENTS
2206 	c_seg->c_was_minor_compacted++;
2207 #endif
2208 	c_indx = c_seg->c_firstemptyslot;
2209 	c_dst = C_SEG_SLOT_FROM_INDEX(c_seg, c_indx);
2210 
2211 	old_populated_offset = c_seg->c_populated_offset;
2212 	c_offset = c_dst->c_offset;
2213 
2214 	for (i = c_indx + 1; i < c_seg->c_nextslot && c_offset < c_seg->c_nextoffset; i++) {
2215 		c_src = C_SEG_SLOT_FROM_INDEX(c_seg, i);
2216 
2217 		c_size = UNPACK_C_SIZE(c_src);
2218 
2219 		if (c_size == 0) {
2220 			continue;
2221 		}
2222 
2223 		c_rounded_size = C_SEG_ROUND_TO_ALIGNMENT(c_size + c_slot_extra_size(c_src));
2224 
2225 /* N.B.: This memcpy may be an overlapping copy */
2226 		memcpy(&c_seg->c_store.c_buffer[c_offset], &c_seg->c_store.c_buffer[c_src->c_offset], c_rounded_size);
2227 
2228 		cslot_copy(c_dst, c_src);
2229 		c_dst->c_offset = c_offset;
2230 
2231 		slot_ptr = C_SLOT_UNPACK_PTR(c_dst);
2232 		slot_ptr->s_cindx = c_indx;
2233 
2234 		c_offset += C_SEG_BYTES_TO_OFFSET(c_rounded_size);
2235 		PACK_C_SIZE(c_src, 0);
2236 		c_indx++;
2237 
2238 		c_dst = C_SEG_SLOT_FROM_INDEX(c_seg, c_indx);
2239 	}
2240 	c_seg->c_firstemptyslot = c_indx;
2241 	c_seg->c_nextslot = c_indx;
2242 	c_seg->c_nextoffset = c_offset;
2243 	c_seg->c_populated_offset = (c_offset + (C_SEG_BYTES_TO_OFFSET(PAGE_SIZE) - 1)) & ~(C_SEG_BYTES_TO_OFFSET(PAGE_SIZE) - 1);
2244 	c_seg->c_bytes_unused = 0;
2245 
2246 #if VALIDATE_C_SEGMENTS
2247 	c_seg_validate(c_seg, TRUE);
2248 #endif
2249 	if (old_populated_offset > c_seg->c_populated_offset) {
2250 		uint32_t        gc_size;
2251 		int32_t         *gc_ptr;
2252 
2253 		gc_size = C_SEG_OFFSET_TO_BYTES(old_populated_offset - c_seg->c_populated_offset);
2254 		gc_ptr = &c_seg->c_store.c_buffer[c_seg->c_populated_offset];
2255 
2256 		kernel_memory_depopulate((vm_offset_t)gc_ptr, gc_size,
2257 		    KMA_COMPRESSOR, VM_KERN_MEMORY_COMPRESSOR);
2258 	}
2259 
2260 #if DEVELOPMENT || DEBUG
2261 	C_SEG_WRITE_PROTECT(c_seg);
2262 #endif
2263 
2264 done:
2265 	if (clear_busy == TRUE) {
2266 		lck_mtx_lock_spin_always(&c_seg->c_lock);
2267 		C_SEG_WAKEUP_DONE(c_seg);
2268 		lck_mtx_unlock_always(&c_seg->c_lock);
2269 	}
2270 	return 0;
2271 }
2272 
2273 
2274 static void
c_seg_alloc_nextslot(c_segment_t c_seg)2275 c_seg_alloc_nextslot(c_segment_t c_seg)
2276 {
2277 	struct c_slot   *old_slot_array = NULL;
2278 	struct c_slot   *new_slot_array = NULL;
2279 	int             newlen;
2280 	int             oldlen;
2281 
2282 	if (c_seg->c_nextslot < c_seg_fixed_array_len) {
2283 		return;
2284 	}
2285 
2286 	if ((c_seg->c_nextslot - c_seg_fixed_array_len) >= c_seg->c_slot_var_array_len) {
2287 		oldlen = c_seg->c_slot_var_array_len;
2288 		old_slot_array = c_seg->c_slot_var_array;
2289 
2290 		if (oldlen == 0) {
2291 			newlen = c_seg_slot_var_array_min_len;
2292 		} else {
2293 			newlen = oldlen * 2;
2294 		}
2295 
2296 		new_slot_array = kalloc_type(struct c_slot, newlen, Z_WAITOK);
2297 
2298 		lck_mtx_lock_spin_always(&c_seg->c_lock);
2299 
2300 		if (old_slot_array) {
2301 			memcpy(new_slot_array, old_slot_array,
2302 			    sizeof(struct c_slot) * oldlen);
2303 		}
2304 
2305 		c_seg->c_slot_var_array_len = newlen;
2306 		c_seg->c_slot_var_array = new_slot_array;
2307 
2308 		lck_mtx_unlock_always(&c_seg->c_lock);
2309 
2310 		kfree_type(struct c_slot, oldlen, old_slot_array);
2311 	}
2312 }
2313 
2314 
2315 #define C_SEG_MAJOR_COMPACT_STATS_MAX   (30)
2316 
2317 struct {
2318 	uint64_t asked_permission;
2319 	uint64_t compactions;
2320 	uint64_t moved_slots;
2321 	uint64_t moved_bytes;
2322 	uint64_t wasted_space_in_swapouts;
2323 	uint64_t count_of_swapouts;
2324 	uint64_t count_of_freed_segs;
2325 	uint64_t bailed_compactions;
2326 	uint64_t bytes_freed_rate_us;
2327 } c_seg_major_compact_stats[C_SEG_MAJOR_COMPACT_STATS_MAX];
2328 
2329 int c_seg_major_compact_stats_now = 0;
2330 
2331 
2332 #define C_MAJOR_COMPACTION_SIZE_APPROPRIATE     ((c_seg_bufsize * 90) / 100)
2333 
2334 
2335 boolean_t
c_seg_major_compact_ok(c_segment_t c_seg_dst,c_segment_t c_seg_src)2336 c_seg_major_compact_ok(
2337 	c_segment_t c_seg_dst,
2338 	c_segment_t c_seg_src)
2339 {
2340 	c_seg_major_compact_stats[c_seg_major_compact_stats_now].asked_permission++;
2341 
2342 	if (c_seg_src->c_bytes_used >= C_MAJOR_COMPACTION_SIZE_APPROPRIATE &&
2343 	    c_seg_dst->c_bytes_used >= C_MAJOR_COMPACTION_SIZE_APPROPRIATE) {
2344 		return FALSE;
2345 	}
2346 
2347 	if (c_seg_dst->c_nextoffset >= c_seg_off_limit || c_seg_dst->c_nextslot >= C_SLOT_MAX_INDEX) {
2348 		/*
2349 		 * destination segment is full... can't compact
2350 		 */
2351 		return FALSE;
2352 	}
2353 
2354 	return TRUE;
2355 }
2356 
2357 /*
2358  * Move slots from src to dst
2359  * returns TRUE if we can continue compacting further to the same dst segment
2360  */
2361 boolean_t
c_seg_major_compact(c_segment_t c_seg_dst,c_segment_t c_seg_src)2362 c_seg_major_compact(
2363 	c_segment_t c_seg_dst,
2364 	c_segment_t c_seg_src)
2365 {
2366 	c_slot_mapping_t slot_ptr;
2367 	uint32_t        c_rounded_size;
2368 	uint32_t        c_size;
2369 	uint16_t        dst_slot;
2370 	int             i;
2371 	c_slot_t        c_dst;
2372 	c_slot_t        c_src;
2373 	boolean_t       keep_compacting = TRUE;
2374 
2375 	/*
2376 	 * segments are not locked but they are both marked c_busy
2377 	 * which keeps c_decompress from working on them...
2378 	 * we can safely allocate new pages, move compressed data
2379 	 * from c_seg_src to c_seg_dst and update both c_segment's
2380 	 * state w/o holding the master lock
2381 	 */
2382 #if DEVELOPMENT || DEBUG
2383 	C_SEG_MAKE_WRITEABLE(c_seg_dst);
2384 #endif
2385 
2386 #if VALIDATE_C_SEGMENTS
2387 	c_seg_dst->c_was_major_compacted++;
2388 	c_seg_src->c_was_major_donor++;
2389 #endif
2390 	assertf(c_seg_dst->c_has_donated_pages == c_seg_src->c_has_donated_pages, "Mismatched donation status Dst: %p, Src: %p\n", c_seg_dst, c_seg_src);
2391 	c_seg_major_compact_stats[c_seg_major_compact_stats_now].compactions++;
2392 
2393 	dst_slot = c_seg_dst->c_nextslot;
2394 
2395 	for (i = 0; i < c_seg_src->c_nextslot; i++) {
2396 		c_src = C_SEG_SLOT_FROM_INDEX(c_seg_src, i);
2397 
2398 		c_size = UNPACK_C_SIZE(c_src);
2399 
2400 		if (c_size == 0) {
2401 			/* BATCH: move what we have so far; */
2402 			continue;
2403 		}
2404 
2405 		int combined_size = c_size + c_slot_extra_size(c_src);
2406 
2407 		c_rounded_size = C_SEG_ROUND_TO_ALIGNMENT(combined_size);
2408 
2409 		int size_left = c_seg_bufsize - C_SEG_OFFSET_TO_BYTES(c_seg_dst->c_nextoffset);
2410 		/* we're going to increment c_nextoffset by c_rounded_size so it should not overflow the segment bufsize */
2411 		if (size_left < c_rounded_size) {
2412 			keep_compacting = FALSE;
2413 			break;
2414 		}
2415 
2416 		/* Do we have enough populated space left in dst? */
2417 		assertf(c_seg_dst->c_populated_offset >= c_seg_dst->c_nextoffset, "Unexpected segment offsets: %u,%u", c_seg_dst->c_populated_offset, c_seg_dst->c_nextoffset);
2418 		if (C_SEG_OFFSET_TO_BYTES(c_seg_dst->c_populated_offset - c_seg_dst->c_nextoffset) < (unsigned) combined_size) {
2419 			int     size_to_populate;
2420 
2421 			/* eagerly populate the entire segment in expectation to fill it */
2422 			assert(c_seg_bufsize >= C_SEG_OFFSET_TO_BYTES(c_seg_dst->c_populated_offset));
2423 			size_to_populate = c_seg_bufsize - C_SEG_OFFSET_TO_BYTES(c_seg_dst->c_populated_offset);
2424 
2425 			if (size_to_populate == 0) {
2426 				/* can't populate any more pages in this segment */
2427 				keep_compacting = FALSE;
2428 				break;
2429 			}
2430 			if (size_to_populate > C_SEG_MAX_POPULATE_SIZE) {
2431 				size_to_populate = C_SEG_MAX_POPULATE_SIZE;
2432 			}
2433 
2434 			kernel_memory_populate(
2435 				(vm_offset_t) &c_seg_dst->c_store.c_buffer[c_seg_dst->c_populated_offset],
2436 				size_to_populate,
2437 				KMA_NOFAIL | KMA_COMPRESSOR,
2438 				VM_KERN_MEMORY_COMPRESSOR);
2439 
2440 			c_seg_dst->c_populated_offset += C_SEG_BYTES_TO_OFFSET(size_to_populate);
2441 			assert(C_SEG_OFFSET_TO_BYTES(c_seg_dst->c_populated_offset) <= c_seg_bufsize);
2442 		}
2443 		c_seg_alloc_nextslot(c_seg_dst);
2444 
2445 		c_dst = C_SEG_SLOT_FROM_INDEX(c_seg_dst, c_seg_dst->c_nextslot);
2446 
2447 		/*
2448 		 * We don't want pages to get stolen by the contiguous memory allocator
2449 		 * when copying data from one segment to another.
2450 		 */
2451 		PAGE_REPLACEMENT_DISALLOWED(TRUE);
2452 		memcpy(&c_seg_dst->c_store.c_buffer[c_seg_dst->c_nextoffset], &c_seg_src->c_store.c_buffer[c_src->c_offset], combined_size);
2453 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
2454 
2455 		c_seg_major_compact_stats[c_seg_major_compact_stats_now].moved_slots++;
2456 		c_seg_major_compact_stats[c_seg_major_compact_stats_now].moved_bytes += combined_size;
2457 
2458 		cslot_copy(c_dst, c_src);
2459 		c_dst->c_offset = c_seg_dst->c_nextoffset;
2460 
2461 		if (c_seg_dst->c_firstemptyslot == c_seg_dst->c_nextslot) {
2462 			c_seg_dst->c_firstemptyslot++;
2463 		}
2464 		c_seg_dst->c_slots_used++;
2465 		c_seg_dst->c_nextslot++;
2466 		c_seg_dst->c_bytes_used += c_rounded_size;
2467 		c_seg_dst->c_nextoffset += C_SEG_BYTES_TO_OFFSET(c_rounded_size);
2468 
2469 		PACK_C_SIZE(c_src, 0);
2470 
2471 		c_seg_src->c_bytes_used -= c_rounded_size;
2472 		c_seg_src->c_bytes_unused += c_rounded_size;
2473 		c_seg_src->c_firstemptyslot = 0;
2474 
2475 		assert(c_seg_src->c_slots_used);
2476 		c_seg_src->c_slots_used--;
2477 
2478 		if (!c_seg_src->c_swappedin) {
2479 			/* Pessimistically lose swappedin status when non-swappedin pages are added. */
2480 			c_seg_dst->c_swappedin = false;
2481 		}
2482 
2483 		if (c_seg_dst->c_nextoffset >= c_seg_off_limit || c_seg_dst->c_nextslot >= C_SLOT_MAX_INDEX) {
2484 			/* dest segment is now full */
2485 			keep_compacting = FALSE;
2486 			break;
2487 		}
2488 	}
2489 #if DEVELOPMENT || DEBUG
2490 	C_SEG_WRITE_PROTECT(c_seg_dst);
2491 #endif
2492 	if (dst_slot < c_seg_dst->c_nextslot) {
2493 		PAGE_REPLACEMENT_ALLOWED(TRUE);
2494 		/*
2495 		 * we've now locked out c_decompress from
2496 		 * converting the slot passed into it into
2497 		 * a c_segment_t which allows us to use
2498 		 * the backptr to change which c_segment and
2499 		 * index the slot points to
2500 		 */
2501 		while (dst_slot < c_seg_dst->c_nextslot) {
2502 			c_dst = C_SEG_SLOT_FROM_INDEX(c_seg_dst, dst_slot);
2503 
2504 			slot_ptr = C_SLOT_UNPACK_PTR(c_dst);
2505 			/* <csegno=0,indx=0> would mean "empty slot", so use csegno+1 */
2506 			slot_ptr->s_cseg = c_seg_dst->c_mysegno + 1;
2507 			slot_ptr->s_cindx = dst_slot++;
2508 		}
2509 		PAGE_REPLACEMENT_ALLOWED(FALSE);
2510 	}
2511 	return keep_compacting;
2512 }
2513 
2514 
2515 uint64_t
vm_compressor_compute_elapsed_msecs(clock_sec_t end_sec,clock_nsec_t end_nsec,clock_sec_t start_sec,clock_nsec_t start_nsec)2516 vm_compressor_compute_elapsed_msecs(clock_sec_t end_sec, clock_nsec_t end_nsec, clock_sec_t start_sec, clock_nsec_t start_nsec)
2517 {
2518 	uint64_t end_msecs;
2519 	uint64_t start_msecs;
2520 
2521 	end_msecs = (end_sec * 1000) + end_nsec / 1000000;
2522 	start_msecs = (start_sec * 1000) + start_nsec / 1000000;
2523 
2524 	return end_msecs - start_msecs;
2525 }
2526 
2527 
2528 
2529 uint32_t compressor_eval_period_in_msecs = 250;
2530 uint32_t compressor_sample_min_in_msecs = 500;
2531 uint32_t compressor_sample_max_in_msecs = 10000;
2532 uint32_t compressor_thrashing_threshold_per_10msecs = 50;
2533 uint32_t compressor_thrashing_min_per_10msecs = 20;
2534 
2535 /* When true, reset sample data next chance we get. */
2536 static boolean_t        compressor_need_sample_reset = FALSE;
2537 
2538 
2539 void
compute_swapout_target_age(void)2540 compute_swapout_target_age(void)
2541 {
2542 	clock_sec_t     cur_ts_sec;
2543 	clock_nsec_t    cur_ts_nsec;
2544 	uint32_t        min_operations_needed_in_this_sample;
2545 	uint64_t        elapsed_msecs_in_eval;
2546 	uint64_t        elapsed_msecs_in_sample;
2547 	boolean_t       need_eval_reset = FALSE;
2548 
2549 	clock_get_system_nanotime(&cur_ts_sec, &cur_ts_nsec);
2550 
2551 	elapsed_msecs_in_sample = vm_compressor_compute_elapsed_msecs(cur_ts_sec, cur_ts_nsec, start_of_sample_period_sec, start_of_sample_period_nsec);
2552 
2553 	if (compressor_need_sample_reset ||
2554 	    elapsed_msecs_in_sample >= compressor_sample_max_in_msecs) {
2555 		compressor_need_sample_reset = TRUE;
2556 		need_eval_reset = TRUE;
2557 		goto done;
2558 	}
2559 	elapsed_msecs_in_eval = vm_compressor_compute_elapsed_msecs(cur_ts_sec, cur_ts_nsec, start_of_eval_period_sec, start_of_eval_period_nsec);
2560 
2561 	if (elapsed_msecs_in_eval < compressor_eval_period_in_msecs) {
2562 		goto done;
2563 	}
2564 	need_eval_reset = TRUE;
2565 
2566 	KERNEL_DEBUG(0xe0400020 | DBG_FUNC_START, elapsed_msecs_in_eval, sample_period_compression_count, sample_period_decompression_count, 0, 0);
2567 
2568 	min_operations_needed_in_this_sample = (compressor_thrashing_min_per_10msecs * (uint32_t)elapsed_msecs_in_eval) / 10;
2569 
2570 	if ((sample_period_compression_count - last_eval_compression_count) < min_operations_needed_in_this_sample ||
2571 	    (sample_period_decompression_count - last_eval_decompression_count) < min_operations_needed_in_this_sample) {
2572 		KERNEL_DEBUG(0xe0400020 | DBG_FUNC_END, sample_period_compression_count - last_eval_compression_count,
2573 		    sample_period_decompression_count - last_eval_decompression_count, 0, 1, 0);
2574 
2575 		swapout_target_age = 0;
2576 
2577 		compressor_need_sample_reset = TRUE;
2578 		need_eval_reset = TRUE;
2579 		goto done;
2580 	}
2581 	last_eval_compression_count = sample_period_compression_count;
2582 	last_eval_decompression_count = sample_period_decompression_count;
2583 
2584 	if (elapsed_msecs_in_sample < compressor_sample_min_in_msecs) {
2585 		KERNEL_DEBUG(0xe0400020 | DBG_FUNC_END, swapout_target_age, 0, 0, 5, 0);
2586 		goto done;
2587 	}
2588 	if (sample_period_decompression_count > ((compressor_thrashing_threshold_per_10msecs * elapsed_msecs_in_sample) / 10)) {
2589 		uint64_t        running_total;
2590 		uint64_t        working_target;
2591 		uint64_t        aging_target;
2592 		uint32_t        oldest_age_of_csegs_sampled = 0;
2593 		uint64_t        working_set_approximation = 0;
2594 
2595 		swapout_target_age = 0;
2596 
2597 		working_target = (sample_period_decompression_count / 100) * 95;                /* 95 percent */
2598 		aging_target = (sample_period_decompression_count / 100) * 1;                   /* 1 percent */
2599 		running_total = 0;
2600 
2601 		for (oldest_age_of_csegs_sampled = 0; oldest_age_of_csegs_sampled < DECOMPRESSION_SAMPLE_MAX_AGE; oldest_age_of_csegs_sampled++) {
2602 			running_total += age_of_decompressions_during_sample_period[oldest_age_of_csegs_sampled];
2603 
2604 			working_set_approximation += oldest_age_of_csegs_sampled * age_of_decompressions_during_sample_period[oldest_age_of_csegs_sampled];
2605 
2606 			if (running_total >= working_target) {
2607 				break;
2608 			}
2609 		}
2610 		if (oldest_age_of_csegs_sampled < DECOMPRESSION_SAMPLE_MAX_AGE) {
2611 			working_set_approximation = (working_set_approximation * 1000) / elapsed_msecs_in_sample;
2612 
2613 			if (working_set_approximation < VM_PAGE_COMPRESSOR_COUNT) {
2614 				running_total = overage_decompressions_during_sample_period;
2615 
2616 				for (oldest_age_of_csegs_sampled = DECOMPRESSION_SAMPLE_MAX_AGE - 1; oldest_age_of_csegs_sampled; oldest_age_of_csegs_sampled--) {
2617 					running_total += age_of_decompressions_during_sample_period[oldest_age_of_csegs_sampled];
2618 
2619 					if (running_total >= aging_target) {
2620 						break;
2621 					}
2622 				}
2623 				swapout_target_age = (uint32_t)cur_ts_sec - oldest_age_of_csegs_sampled;
2624 
2625 				KERNEL_DEBUG(0xe0400020 | DBG_FUNC_END, swapout_target_age, working_set_approximation, VM_PAGE_COMPRESSOR_COUNT, 2, 0);
2626 			} else {
2627 				KERNEL_DEBUG(0xe0400020 | DBG_FUNC_END, working_set_approximation, VM_PAGE_COMPRESSOR_COUNT, 0, 3, 0);
2628 			}
2629 		} else {
2630 			KERNEL_DEBUG(0xe0400020 | DBG_FUNC_END, working_target, running_total, 0, 4, 0);
2631 		}
2632 
2633 		compressor_need_sample_reset = TRUE;
2634 		need_eval_reset = TRUE;
2635 	} else {
2636 		KERNEL_DEBUG(0xe0400020 | DBG_FUNC_END, sample_period_decompression_count, (compressor_thrashing_threshold_per_10msecs * elapsed_msecs_in_sample) / 10, 0, 6, 0);
2637 	}
2638 done:
2639 	if (compressor_need_sample_reset == TRUE) {
2640 		bzero(age_of_decompressions_during_sample_period, sizeof(age_of_decompressions_during_sample_period));
2641 		overage_decompressions_during_sample_period = 0;
2642 
2643 		start_of_sample_period_sec = cur_ts_sec;
2644 		start_of_sample_period_nsec = cur_ts_nsec;
2645 		sample_period_decompression_count = 0;
2646 		sample_period_compression_count = 0;
2647 		last_eval_decompression_count = 0;
2648 		last_eval_compression_count = 0;
2649 		compressor_need_sample_reset = FALSE;
2650 	}
2651 	if (need_eval_reset == TRUE) {
2652 		start_of_eval_period_sec = cur_ts_sec;
2653 		start_of_eval_period_nsec = cur_ts_nsec;
2654 	}
2655 }
2656 
2657 
2658 int             compaction_swapper_init_now = 0;
2659 int             compaction_swapper_running = 0;
2660 int             compaction_swapper_awakened = 0;
2661 int             compaction_swapper_abort = 0;
2662 
2663 bool
vm_compressor_swapout_is_ripe()2664 vm_compressor_swapout_is_ripe()
2665 {
2666 	bool is_ripe = false;
2667 	if (vm_swapout_ripe_segments == TRUE && c_overage_swapped_count < c_overage_swapped_limit) {
2668 		c_segment_t     c_seg;
2669 		clock_sec_t     now;
2670 		clock_sec_t     age;
2671 		clock_nsec_t    nsec;
2672 
2673 		clock_get_system_nanotime(&now, &nsec);
2674 		age = 0;
2675 
2676 		lck_mtx_lock_spin_always(c_list_lock);
2677 
2678 		if (!queue_empty(&c_age_list_head)) {
2679 			c_seg = (c_segment_t) queue_first(&c_age_list_head);
2680 
2681 			age = now - c_seg->c_creation_ts;
2682 		}
2683 		lck_mtx_unlock_always(c_list_lock);
2684 
2685 		if (age >= vm_ripe_target_age) {
2686 			is_ripe = true;
2687 		}
2688 	}
2689 	return is_ripe;
2690 }
2691 
2692 static bool
compressor_swapout_conditions_met(void)2693 compressor_swapout_conditions_met(void)
2694 {
2695 	bool should_swap = false;
2696 	if (COMPRESSOR_NEEDS_TO_SWAP()) {
2697 		should_swap = true;
2698 		vmcs_stats.compressor_swap_threshold_exceeded++;
2699 	}
2700 	if (VM_PAGE_Q_THROTTLED(&vm_pageout_queue_external) && vm_page_anonymous_count < (vm_page_inactive_count / 20)) {
2701 		should_swap = true;
2702 		vmcs_stats.external_q_throttled++;
2703 	}
2704 	if (vm_page_free_count < (vm_page_free_reserved - (COMPRESSOR_FREE_RESERVED_LIMIT * 2))) {
2705 		should_swap = true;
2706 		vmcs_stats.free_count_below_reserve++;
2707 	}
2708 	return should_swap;
2709 }
2710 
2711 static bool
compressor_needs_to_swap()2712 compressor_needs_to_swap()
2713 {
2714 	bool should_swap = false;
2715 	if (vm_compressor_swapout_is_ripe()) {
2716 		should_swap = true;
2717 		goto check_if_low_space;
2718 	}
2719 
2720 	if (VM_CONFIG_SWAP_IS_ACTIVE) {
2721 		should_swap =  compressor_swapout_conditions_met();
2722 		if (should_swap) {
2723 			goto check_if_low_space;
2724 		}
2725 	}
2726 
2727 #if (XNU_TARGET_OS_OSX && __arm64__)
2728 	/*
2729 	 * Thrashing detection disabled.
2730 	 */
2731 #else /* (XNU_TARGET_OS_OSX && __arm64__) */
2732 
2733 	if (vm_compressor_is_thrashing()) {
2734 		should_swap = true;
2735 		vmcs_stats.thrashing_detected++;
2736 	}
2737 
2738 #if CONFIG_PHANTOM_CACHE
2739 	if (vm_phantom_cache_check_pressure()) {
2740 		os_atomic_store(&memorystatus_phantom_cache_pressure, true, release);
2741 		should_swap = true;
2742 	}
2743 #endif
2744 	if (swapout_target_age) {
2745 		should_swap = true;
2746 	}
2747 #endif /* (XNU_TARGET_OS_OSX && __arm64__) */
2748 
2749 check_if_low_space:
2750 
2751 #if CONFIG_JETSAM
2752 	if (should_swap || vm_compressor_low_on_space()) {
2753 		if (vm_compressor_thrashing_detected == FALSE) {
2754 			vm_compressor_thrashing_detected = TRUE;
2755 
2756 			if (swapout_target_age) {
2757 				compressor_thrashing_induced_jetsam++;
2758 			} else if (vm_compressor_low_on_space()) {
2759 				compressor_thrashing_induced_jetsam++;
2760 			} else {
2761 				filecache_thrashing_induced_jetsam++;
2762 			}
2763 			/*
2764 			 * Wake up the memorystatus thread so that it can return
2765 			 * the system to a healthy state (by killing processes).
2766 			 */
2767 			memorystatus_thread_wake();
2768 		}
2769 		/*
2770 		 * let the jetsam take precedence over
2771 		 * any major compactions we might have
2772 		 * been able to do... otherwise we run
2773 		 * the risk of doing major compactions
2774 		 * on segments we're about to free up
2775 		 * due to the jetsam activity.
2776 		 */
2777 		should_swap = false;
2778 		if (memorystatus_swap_all_apps && vm_swap_low_on_space()) {
2779 			memorystatus_respond_to_swap_exhaustion();
2780 		}
2781 	}
2782 #else /* CONFIG_JETSAM */
2783 	if (should_swap && vm_swap_low_on_space()) {
2784 		memorystatus_respond_to_swap_exhaustion();
2785 	}
2786 #endif /* CONFIG_JETSAM */
2787 
2788 	if (should_swap == false) {
2789 		/*
2790 		 * vm_compressor_needs_to_major_compact returns true only if we're
2791 		 * about to run out of available compressor segments... in this
2792 		 * case, we absolutely need to run a major compaction even if
2793 		 * we've just kicked off a jetsam or we don't otherwise need to
2794 		 * swap... terminating objects releases
2795 		 * pages back to the uncompressed cache, but does not guarantee
2796 		 * that we will free up even a single compression segment
2797 		 */
2798 		should_swap = vm_compressor_needs_to_major_compact();
2799 		if (should_swap) {
2800 			vmcs_stats.fragmentation_detected++;
2801 		}
2802 	}
2803 
2804 	/*
2805 	 * returning TRUE when swap_supported == FALSE
2806 	 * will cause the major compaction engine to
2807 	 * run, but will not trigger any swapping...
2808 	 * segments that have been major compacted
2809 	 * will be moved to the majorcompact queue
2810 	 */
2811 	return should_swap;
2812 }
2813 
2814 #if CONFIG_JETSAM
2815 /*
2816  * This function is called from the jetsam thread after killing something to
2817  * mitigate thrashing.
2818  *
2819  * We need to restart our thrashing detection heuristics since memory pressure
2820  * has potentially changed significantly, and we don't want to detect on old
2821  * data from before the jetsam.
2822  */
2823 void
vm_thrashing_jetsam_done(void)2824 vm_thrashing_jetsam_done(void)
2825 {
2826 	vm_compressor_thrashing_detected = FALSE;
2827 
2828 	/* Were we compressor-thrashing or filecache-thrashing? */
2829 	if (swapout_target_age) {
2830 		swapout_target_age = 0;
2831 		compressor_need_sample_reset = TRUE;
2832 	}
2833 #if CONFIG_PHANTOM_CACHE
2834 	else {
2835 		vm_phantom_cache_restart_sample();
2836 	}
2837 #endif
2838 }
2839 #endif /* CONFIG_JETSAM */
2840 
2841 uint32_t vm_wake_compactor_swapper_calls = 0;
2842 uint32_t vm_run_compactor_already_running = 0;
2843 uint32_t vm_run_compactor_empty_minor_q = 0;
2844 uint32_t vm_run_compactor_did_compact = 0;
2845 uint32_t vm_run_compactor_waited = 0;
2846 
2847 /* run minor compaction right now, if the compaction-swapper thread is not already running */
2848 void
vm_run_compactor(void)2849 vm_run_compactor(void)
2850 {
2851 	if (c_segment_count == 0) {
2852 		return;
2853 	}
2854 
2855 	if (os_atomic_load(&c_minor_count, relaxed) == 0) {
2856 		vm_run_compactor_empty_minor_q++;
2857 		return;
2858 	}
2859 
2860 	lck_mtx_lock_spin_always(c_list_lock);
2861 
2862 	if (compaction_swapper_running) {
2863 		if (vm_pageout_state.vm_restricted_to_single_processor == FALSE) {
2864 			vm_run_compactor_already_running++;
2865 
2866 			lck_mtx_unlock_always(c_list_lock);
2867 			return;
2868 		}
2869 		vm_run_compactor_waited++;
2870 
2871 		assert_wait((event_t)&compaction_swapper_running, THREAD_UNINT);
2872 
2873 		lck_mtx_unlock_always(c_list_lock);
2874 
2875 		thread_block(THREAD_CONTINUE_NULL);
2876 
2877 		return;
2878 	}
2879 	vm_run_compactor_did_compact++;
2880 
2881 	fastwake_warmup = FALSE;
2882 	compaction_swapper_running = 1;
2883 
2884 	vm_compressor_do_delayed_compactions(FALSE);
2885 
2886 	compaction_swapper_running = 0;
2887 
2888 	lck_mtx_unlock_always(c_list_lock);
2889 
2890 	thread_wakeup((event_t)&compaction_swapper_running);
2891 }
2892 
2893 
2894 void
vm_wake_compactor_swapper(void)2895 vm_wake_compactor_swapper(void)
2896 {
2897 	if (compaction_swapper_running || compaction_swapper_awakened || c_segment_count == 0) {
2898 		return;
2899 	}
2900 
2901 	if (os_atomic_load(&c_minor_count, relaxed) ||
2902 	    vm_compressor_needs_to_major_compact()) {
2903 		lck_mtx_lock_spin_always(c_list_lock);
2904 
2905 		fastwake_warmup = FALSE;
2906 
2907 		if (compaction_swapper_running == 0 && compaction_swapper_awakened == 0) {
2908 			vm_wake_compactor_swapper_calls++;
2909 
2910 			compaction_swapper_awakened = 1;
2911 			thread_wakeup((event_t)&c_compressor_swap_trigger);
2912 		}
2913 		lck_mtx_unlock_always(c_list_lock);
2914 	}
2915 }
2916 
2917 
2918 void
vm_consider_swapping()2919 vm_consider_swapping()
2920 {
2921 	assert(VM_CONFIG_SWAP_IS_PRESENT);
2922 
2923 	lck_mtx_lock_spin_always(c_list_lock);
2924 
2925 	compaction_swapper_abort = 1;
2926 
2927 	while (compaction_swapper_running) {
2928 		assert_wait((event_t)&compaction_swapper_running, THREAD_UNINT);
2929 
2930 		lck_mtx_unlock_always(c_list_lock);
2931 
2932 		thread_block(THREAD_CONTINUE_NULL);
2933 
2934 		lck_mtx_lock_spin_always(c_list_lock);
2935 	}
2936 	compaction_swapper_abort = 0;
2937 	compaction_swapper_running = 1;
2938 
2939 	vm_swapout_ripe_segments = TRUE;
2940 
2941 	vm_compressor_process_major_segments(vm_swapout_ripe_segments);
2942 
2943 	vm_compressor_compact_and_swap(FALSE);
2944 
2945 	compaction_swapper_running = 0;
2946 
2947 	vm_swapout_ripe_segments = FALSE;
2948 
2949 	lck_mtx_unlock_always(c_list_lock);
2950 
2951 	thread_wakeup((event_t)&compaction_swapper_running);
2952 }
2953 
2954 
2955 void
vm_consider_waking_compactor_swapper(void)2956 vm_consider_waking_compactor_swapper(void)
2957 {
2958 	bool need_wakeup = false;
2959 
2960 	if (c_segment_count == 0) {
2961 		return;
2962 	}
2963 
2964 	if (compaction_swapper_running || compaction_swapper_awakened) {
2965 		return;
2966 	}
2967 
2968 	if (!compaction_swapper_inited && !compaction_swapper_init_now) {
2969 		compaction_swapper_init_now = 1;
2970 		need_wakeup = true;
2971 	} else if (vm_compressor_needs_to_minor_compact() ||
2972 	    compressor_needs_to_swap()) {
2973 		need_wakeup = true;
2974 	}
2975 
2976 	if (need_wakeup) {
2977 		lck_mtx_lock_spin_always(c_list_lock);
2978 
2979 		fastwake_warmup = FALSE;
2980 
2981 		if (compaction_swapper_running == 0 && compaction_swapper_awakened == 0) {
2982 			memoryshot(DBG_VM_WAKEUP_COMPACTOR_SWAPPER, DBG_FUNC_NONE);
2983 
2984 			compaction_swapper_awakened = 1;
2985 			thread_wakeup((event_t)&c_compressor_swap_trigger);
2986 		}
2987 		lck_mtx_unlock_always(c_list_lock);
2988 	}
2989 }
2990 
2991 
2992 #define C_SWAPOUT_LIMIT                 4
2993 #define DELAYED_COMPACTIONS_PER_PASS    30
2994 
2995 /* process segments that are in the minor compaction queue */
2996 void
vm_compressor_do_delayed_compactions(boolean_t flush_all)2997 vm_compressor_do_delayed_compactions(boolean_t flush_all)
2998 {
2999 	c_segment_t     c_seg;
3000 	int             number_compacted = 0;
3001 	boolean_t       needs_to_swap = FALSE;
3002 	uint32_t        c_swapout_count = 0;
3003 
3004 
3005 	VM_DEBUG_CONSTANT_EVENT(vm_compressor_do_delayed_compactions, DBG_VM_COMPRESSOR_DELAYED_COMPACT, DBG_FUNC_START, c_minor_count, flush_all, 0, 0);
3006 
3007 #if XNU_TARGET_OS_OSX
3008 	LCK_MTX_ASSERT(c_list_lock, LCK_MTX_ASSERT_OWNED);
3009 #endif /* XNU_TARGET_OS_OSX */
3010 
3011 	while (!queue_empty(&c_minor_list_head) && needs_to_swap == FALSE) {
3012 		c_seg = (c_segment_t)queue_first(&c_minor_list_head);
3013 
3014 		lck_mtx_lock_spin_always(&c_seg->c_lock);
3015 
3016 		if (c_seg->c_busy) {
3017 			lck_mtx_unlock_always(c_list_lock);
3018 			c_seg_wait_on_busy(c_seg);
3019 			lck_mtx_lock_spin_always(c_list_lock);
3020 
3021 			continue;
3022 		}
3023 		C_SEG_BUSY(c_seg);
3024 
3025 		c_seg_do_minor_compaction_and_unlock(c_seg, TRUE, FALSE, TRUE);
3026 
3027 		c_swapout_count = c_early_swapout_count + c_regular_swapout_count + c_late_swapout_count;
3028 		if (VM_CONFIG_SWAP_IS_ACTIVE && (number_compacted++ > DELAYED_COMPACTIONS_PER_PASS)) {
3029 			if ((flush_all == TRUE || compressor_needs_to_swap()) && c_swapout_count < C_SWAPOUT_LIMIT) {
3030 				needs_to_swap = TRUE;
3031 			}
3032 
3033 			number_compacted = 0;
3034 		}
3035 		lck_mtx_lock_spin_always(c_list_lock);
3036 	}
3037 
3038 	VM_DEBUG_CONSTANT_EVENT(vm_compressor_do_delayed_compactions, DBG_VM_COMPRESSOR_DELAYED_COMPACT, DBG_FUNC_END, c_minor_count, number_compacted, needs_to_swap, 0);
3039 }
3040 
3041 int min_csegs_per_major_compaction = DELAYED_COMPACTIONS_PER_PASS;
3042 
3043 static bool
vm_compressor_major_compact_cseg(c_segment_t c_seg,uint32_t * c_seg_considered,bool * bail_wanted_cseg,uint64_t * total_bytes_freed)3044 vm_compressor_major_compact_cseg(c_segment_t c_seg, uint32_t* c_seg_considered, bool* bail_wanted_cseg, uint64_t* total_bytes_freed)
3045 {
3046 	/*
3047 	 * Major compaction
3048 	 */
3049 	bool keep_compacting = true, fully_compacted = true;
3050 	queue_head_t *list_head = NULL;
3051 	c_segment_t c_seg_next;
3052 	uint64_t        bytes_to_free = 0, bytes_freed = 0;
3053 	uint32_t        number_considered = 0;
3054 
3055 	if (c_seg->c_state == C_ON_AGE_Q) {
3056 		assert(!c_seg->c_has_donated_pages);
3057 		list_head = &c_age_list_head;
3058 	} else if (c_seg->c_state == C_ON_SWAPPEDIN_Q) {
3059 		assert(c_seg->c_has_donated_pages);
3060 		list_head = &c_late_swappedin_list_head;
3061 	}
3062 
3063 	while (keep_compacting == TRUE) {
3064 		assert(c_seg->c_busy);
3065 
3066 		/* look for another segment to consolidate */
3067 
3068 		c_seg_next = (c_segment_t) queue_next(&c_seg->c_age_list);
3069 
3070 		if (queue_end(list_head, (queue_entry_t)c_seg_next)) {
3071 			break;
3072 		}
3073 
3074 		assert(c_seg_next->c_state == c_seg->c_state);
3075 
3076 		number_considered++;
3077 
3078 		if (c_seg_major_compact_ok(c_seg, c_seg_next) == FALSE) {
3079 			break;
3080 		}
3081 
3082 		lck_mtx_lock_spin_always(&c_seg_next->c_lock);
3083 
3084 		if (c_seg_next->c_busy) {
3085 			/*
3086 			 * We are going to block for our neighbor.
3087 			 * If our c_seg is wanted, we should unbusy
3088 			 * it because we don't know how long we might
3089 			 * have to block here.
3090 			 */
3091 			if (c_seg->c_wanted) {
3092 				lck_mtx_unlock_always(&c_seg_next->c_lock);
3093 				fully_compacted = false;
3094 				c_seg_major_compact_stats[c_seg_major_compact_stats_now].bailed_compactions++;
3095 				*bail_wanted_cseg = true;
3096 				break;
3097 			}
3098 
3099 			lck_mtx_unlock_always(c_list_lock);
3100 
3101 			VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, DBG_VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 8, (void*) VM_KERNEL_ADDRPERM(c_seg_next), 0, 0);
3102 
3103 			c_seg_wait_on_busy(c_seg_next);
3104 			lck_mtx_lock_spin_always(c_list_lock);
3105 
3106 			continue;
3107 		}
3108 		/* grab that segment */
3109 		C_SEG_BUSY(c_seg_next);
3110 
3111 		bytes_to_free = C_SEG_OFFSET_TO_BYTES(c_seg_next->c_populated_offset);
3112 		if (c_seg_do_minor_compaction_and_unlock(c_seg_next, FALSE, TRUE, TRUE)) {
3113 			/*
3114 			 * found an empty c_segment and freed it
3115 			 * so we can't continue to use c_seg_next
3116 			 */
3117 			bytes_freed += bytes_to_free;
3118 			c_seg_major_compact_stats[c_seg_major_compact_stats_now].count_of_freed_segs++;
3119 			continue;
3120 		}
3121 
3122 		/* unlock the list ... */
3123 		lck_mtx_unlock_always(c_list_lock);
3124 
3125 		/* do the major compaction */
3126 
3127 		keep_compacting = c_seg_major_compact(c_seg, c_seg_next);
3128 
3129 		VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, DBG_VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 9, keep_compacting, 0, 0);
3130 
3131 		PAGE_REPLACEMENT_DISALLOWED(TRUE);
3132 
3133 		lck_mtx_lock_spin_always(&c_seg_next->c_lock);
3134 		/*
3135 		 * run a minor compaction on the donor segment
3136 		 * since we pulled at least some of it's
3137 		 * data into our target...  if we've emptied
3138 		 * it, now is a good time to free it which
3139 		 * c_seg_minor_compaction_and_unlock also takes care of
3140 		 *
3141 		 * by passing TRUE, we ask for c_busy to be cleared
3142 		 * and c_wanted to be taken care of
3143 		 */
3144 		bytes_to_free = C_SEG_OFFSET_TO_BYTES(c_seg_next->c_populated_offset);
3145 		if (c_seg_minor_compaction_and_unlock(c_seg_next, TRUE)) {
3146 			bytes_freed += bytes_to_free;
3147 			c_seg_major_compact_stats[c_seg_major_compact_stats_now].count_of_freed_segs++;
3148 		} else {
3149 			bytes_to_free -= C_SEG_OFFSET_TO_BYTES(c_seg_next->c_populated_offset);
3150 			bytes_freed += bytes_to_free;
3151 		}
3152 
3153 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
3154 
3155 		/* relock the list */
3156 		lck_mtx_lock_spin_always(c_list_lock);
3157 
3158 		if (c_seg->c_wanted) {
3159 			/*
3160 			 * Our c_seg is in demand. Let's
3161 			 * unbusy it and wakeup the waiters
3162 			 * instead of continuing the compaction
3163 			 * because we could be in this loop
3164 			 * for a while.
3165 			 */
3166 			fully_compacted = false;
3167 			*bail_wanted_cseg = true;
3168 			c_seg_major_compact_stats[c_seg_major_compact_stats_now].bailed_compactions++;
3169 			break;
3170 		}
3171 	} /* major compaction */
3172 
3173 	VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, DBG_VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 10, number_considered, *bail_wanted_cseg, 0);
3174 
3175 	*c_seg_considered += number_considered;
3176 	*total_bytes_freed += bytes_freed;
3177 
3178 	lck_mtx_lock_spin_always(&c_seg->c_lock);
3179 	return fully_compacted;
3180 }
3181 
3182 #define TIME_SUB(rsecs, secs, rfrac, frac, unit)                        \
3183 	MACRO_BEGIN                                                     \
3184 	if ((int)((rfrac) -= (frac)) < 0) {                             \
3185 	        (rfrac) += (unit);                                      \
3186 	        (rsecs) -= 1;                                           \
3187 	}                                                               \
3188 	(rsecs) -= (secs);                                              \
3189 	MACRO_END
3190 
3191 clock_nsec_t c_process_major_report_over_ms = 9; /* report if over 9 ms */
3192 int c_process_major_yield_after = 1000; /* yield after moving 1,000 segments */
3193 uint64_t c_process_major_reports = 0;
3194 clock_sec_t c_process_major_max_sec = 0;
3195 clock_nsec_t c_process_major_max_nsec = 0;
3196 uint32_t c_process_major_peak_segcount = 0;
3197 static void
vm_compressor_process_major_segments(bool ripe_age_only)3198 vm_compressor_process_major_segments(bool ripe_age_only)
3199 {
3200 	c_segment_t c_seg = NULL;
3201 	int count = 0, total = 0, breaks = 0;
3202 	clock_sec_t start_sec, end_sec;
3203 	clock_nsec_t start_nsec, end_nsec;
3204 	clock_nsec_t report_over_ns;
3205 
3206 	if (queue_empty(&c_major_list_head)) {
3207 		return;
3208 	}
3209 
3210 	// printf("%s: starting to move segments from MAJORQ to AGEQ\n", __FUNCTION__);
3211 	if (c_process_major_report_over_ms != 0) {
3212 		report_over_ns = c_process_major_report_over_ms * NSEC_PER_MSEC;
3213 	} else {
3214 		report_over_ns = (clock_nsec_t)-1;
3215 	}
3216 
3217 	if (ripe_age_only) {
3218 		if (c_overage_swapped_count >= c_overage_swapped_limit) {
3219 			/*
3220 			 * Return while we wait for the overage segments
3221 			 * in our queue to get pushed out first.
3222 			 */
3223 			return;
3224 		}
3225 	}
3226 
3227 	clock_get_system_nanotime(&start_sec, &start_nsec);
3228 	while (!queue_empty(&c_major_list_head)) {
3229 		if (!ripe_age_only) {
3230 			/*
3231 			 * Start from the end to preserve aging order. The newer
3232 			 * segments are at the tail and so need to be inserted in
3233 			 * the aging queue in this way so we have the older segments
3234 			 * at the end of the AGE_Q.
3235 			 */
3236 			c_seg = (c_segment_t)queue_last(&c_major_list_head);
3237 		} else {
3238 			c_seg = (c_segment_t)queue_first(&c_major_list_head);
3239 			if ((start_sec - c_seg->c_creation_ts) < vm_ripe_target_age) {
3240 				/*
3241 				 * We have found the first segment in our queue that is not ripe. Segments after it
3242 				 * will be the same. So let's bail here. Return with c_list_lock held.
3243 				 */
3244 				break;
3245 			}
3246 		}
3247 
3248 		lck_mtx_lock_spin_always(&c_seg->c_lock);
3249 		c_seg_switch_state(c_seg, C_ON_AGE_Q, FALSE);
3250 		lck_mtx_unlock_always(&c_seg->c_lock);
3251 
3252 		count++;
3253 		if (count == c_process_major_yield_after ||
3254 		    queue_empty(&c_major_list_head)) {
3255 			/* done or time to take a break */
3256 		} else {
3257 			/* keep going */
3258 			continue;
3259 		}
3260 
3261 		total += count;
3262 		clock_get_system_nanotime(&end_sec, &end_nsec);
3263 		TIME_SUB(end_sec, start_sec, end_nsec, start_nsec, NSEC_PER_SEC);
3264 		if (end_sec > c_process_major_max_sec) {
3265 			c_process_major_max_sec = end_sec;
3266 			c_process_major_max_nsec = end_nsec;
3267 		} else if (end_sec == c_process_major_max_sec &&
3268 		    end_nsec > c_process_major_max_nsec) {
3269 			c_process_major_max_nsec = end_nsec;
3270 		}
3271 		if (total > c_process_major_peak_segcount) {
3272 			c_process_major_peak_segcount = total;
3273 		}
3274 		if (end_sec > 0 ||
3275 		    end_nsec >= report_over_ns) {
3276 			/* we used more than expected */
3277 			c_process_major_reports++;
3278 			printf("%s: moved %d/%d segments from MAJORQ to AGEQ in %lu.%09u seconds and %d breaks\n",
3279 			    __FUNCTION__, count, total,
3280 			    end_sec, end_nsec, breaks);
3281 		}
3282 		if (queue_empty(&c_major_list_head)) {
3283 			/* done */
3284 			break;
3285 		}
3286 		/* take a break to allow someone else to grab the lock */
3287 		lck_mtx_unlock_always(c_list_lock);
3288 		mutex_pause(0); /* 10 microseconds */
3289 		lck_mtx_lock_spin_always(c_list_lock);
3290 		/* start again */
3291 		clock_get_system_nanotime(&start_sec, &start_nsec);
3292 		count = 0;
3293 		breaks++;
3294 	}
3295 }
3296 
3297 /*
3298  * macOS special swappable csegs -> early_swapin queue
3299  * non-macOS special swappable+non-freezer csegs -> late_swapin queue
3300  * Processing special csegs means minor compacting each cseg and then
3301  * major compacting it and putting them on the early or late
3302  * (depending on platform) swapout queue. tag:DONATE
3303  */
3304 static void
vm_compressor_process_special_swapped_in_segments_locked(void)3305 vm_compressor_process_special_swapped_in_segments_locked(void)
3306 {
3307 	c_segment_t c_seg = NULL;
3308 	bool            switch_state = true, bail_wanted_cseg = false;
3309 	unsigned int    number_considered = 0, yield_after_considered_per_pass = 0;
3310 	uint64_t        bytes_freed = 0;
3311 	queue_head_t    *special_swappedin_list_head;
3312 
3313 #if XNU_TARGET_OS_OSX
3314 	special_swappedin_list_head = &c_early_swappedin_list_head;
3315 #else /* XNU_TARGET_OS_OSX */
3316 	if (memorystatus_swap_all_apps) {
3317 		special_swappedin_list_head = &c_late_swappedin_list_head;
3318 	} else {
3319 		/* called on unsupported config*/
3320 		return;
3321 	}
3322 #endif /* XNU_TARGET_OS_OSX */
3323 
3324 	yield_after_considered_per_pass = MAX(min_csegs_per_major_compaction, DELAYED_COMPACTIONS_PER_PASS);
3325 	while (!queue_empty(special_swappedin_list_head)) {
3326 		c_seg = (c_segment_t)queue_first(special_swappedin_list_head);
3327 
3328 		lck_mtx_lock_spin_always(&c_seg->c_lock);
3329 
3330 		if (c_seg->c_busy) {
3331 			lck_mtx_unlock_always(c_list_lock);
3332 			c_seg_wait_on_busy(c_seg);
3333 			lck_mtx_lock_spin_always(c_list_lock);
3334 			continue;
3335 		}
3336 
3337 		C_SEG_BUSY(c_seg);
3338 		lck_mtx_unlock_always(&c_seg->c_lock);
3339 		lck_mtx_unlock_always(c_list_lock);
3340 
3341 		PAGE_REPLACEMENT_DISALLOWED(TRUE);
3342 
3343 		lck_mtx_lock_spin_always(&c_seg->c_lock);
3344 
3345 		if (c_seg_minor_compaction_and_unlock(c_seg, FALSE /*clear busy?*/)) {
3346 			/*
3347 			 * found an empty c_segment and freed it
3348 			 * so go grab the next guy in the queue
3349 			 */
3350 			PAGE_REPLACEMENT_DISALLOWED(FALSE);
3351 			lck_mtx_lock_spin_always(c_list_lock);
3352 			continue;
3353 		}
3354 
3355 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
3356 		lck_mtx_lock_spin_always(c_list_lock);
3357 
3358 		switch_state = vm_compressor_major_compact_cseg(c_seg, &number_considered, &bail_wanted_cseg, &bytes_freed);
3359 		assert(c_seg->c_busy);
3360 		assert(!c_seg->c_on_minorcompact_q);
3361 
3362 		if (switch_state) {
3363 			if (VM_CONFIG_SWAP_IS_ACTIVE || VM_CONFIG_FREEZER_SWAP_IS_ACTIVE) {
3364 				/*
3365 				 * Ordinarily we let swapped in segments age out + get
3366 				 * major compacted with the rest of the c_segs on the ageQ.
3367 				 * But the early donated c_segs, if well compacted, should be
3368 				 * kept ready to be swapped out if needed. These are typically
3369 				 * describing memory belonging to a leaky app (macOS) or a swap-
3370 				 * capable app (iPadOS) and for the latter we can keep these
3371 				 * around longer because we control the triggers in the memorystatus
3372 				 * subsystem
3373 				 */
3374 				c_seg_switch_state(c_seg, C_ON_SWAPOUT_Q, FALSE);
3375 			}
3376 		}
3377 
3378 		C_SEG_WAKEUP_DONE(c_seg);
3379 
3380 		lck_mtx_unlock_always(&c_seg->c_lock);
3381 
3382 		if (number_considered >= yield_after_considered_per_pass) {
3383 			if (bail_wanted_cseg) {
3384 				/*
3385 				 * We stopped major compactions on a c_seg
3386 				 * that is wanted. We don't know the priority
3387 				 * of the waiter unfortunately but we are at
3388 				 * a very high priority and so, just in case
3389 				 * the waiter is a critical system daemon or
3390 				 * UI thread, let's give up the CPU in case
3391 				 * the system is running a few CPU intensive
3392 				 * tasks.
3393 				 */
3394 				bail_wanted_cseg = false;
3395 				lck_mtx_unlock_always(c_list_lock);
3396 
3397 				mutex_pause(2); /* 100us yield */
3398 
3399 				lck_mtx_lock_spin_always(c_list_lock);
3400 			}
3401 
3402 			number_considered = 0;
3403 		}
3404 	}
3405 }
3406 
3407 void
vm_compressor_process_special_swapped_in_segments(void)3408 vm_compressor_process_special_swapped_in_segments(void)
3409 {
3410 	lck_mtx_lock_spin_always(c_list_lock);
3411 	vm_compressor_process_special_swapped_in_segments_locked();
3412 	lck_mtx_unlock_always(c_list_lock);
3413 }
3414 
3415 #define C_SEGMENT_SWAPPEDIN_AGE_LIMIT   10
3416 /*
3417  * Processing regular csegs means aging them.
3418  */
3419 static void
vm_compressor_process_regular_swapped_in_segments(boolean_t flush_all)3420 vm_compressor_process_regular_swapped_in_segments(boolean_t flush_all)
3421 {
3422 	c_segment_t     c_seg;
3423 	clock_sec_t     now;
3424 	clock_nsec_t    nsec;
3425 
3426 	clock_get_system_nanotime(&now, &nsec);
3427 
3428 	while (!queue_empty(&c_regular_swappedin_list_head)) {
3429 		c_seg = (c_segment_t)queue_first(&c_regular_swappedin_list_head);
3430 
3431 		if (flush_all == FALSE && (now - c_seg->c_swappedin_ts) < C_SEGMENT_SWAPPEDIN_AGE_LIMIT) {
3432 			break;
3433 		}
3434 
3435 		lck_mtx_lock_spin_always(&c_seg->c_lock);
3436 
3437 		c_seg_switch_state(c_seg, C_ON_AGE_Q, FALSE);
3438 		c_seg->c_agedin_ts = (uint32_t) now;
3439 
3440 		lck_mtx_unlock_always(&c_seg->c_lock);
3441 	}
3442 }
3443 
3444 
3445 extern  int     vm_num_swap_files;
3446 extern  int     vm_num_pinned_swap_files;
3447 extern  int     vm_swappin_enabled;
3448 
3449 extern  unsigned int    vm_swapfile_total_segs_used;
3450 extern  unsigned int    vm_swapfile_total_segs_alloced;
3451 
3452 
3453 void
vm_compressor_flush(void)3454 vm_compressor_flush(void)
3455 {
3456 	uint64_t        vm_swap_put_failures_at_start;
3457 	wait_result_t   wait_result = 0;
3458 	AbsoluteTime    startTime, endTime;
3459 	clock_sec_t     now_sec;
3460 	clock_nsec_t    now_nsec;
3461 	uint64_t        nsec;
3462 	c_segment_t     c_seg, c_seg_next;
3463 
3464 	HIBLOG("vm_compressor_flush - starting\n");
3465 
3466 	clock_get_uptime(&startTime);
3467 
3468 	lck_mtx_lock_spin_always(c_list_lock);
3469 
3470 	fastwake_warmup = FALSE;
3471 	compaction_swapper_abort = 1;
3472 
3473 	while (compaction_swapper_running) {
3474 		assert_wait((event_t)&compaction_swapper_running, THREAD_UNINT);
3475 
3476 		lck_mtx_unlock_always(c_list_lock);
3477 
3478 		thread_block(THREAD_CONTINUE_NULL);
3479 
3480 		lck_mtx_lock_spin_always(c_list_lock);
3481 	}
3482 	compaction_swapper_abort = 0;
3483 	compaction_swapper_running = 1;
3484 
3485 	hibernate_flushing = TRUE;
3486 	hibernate_no_swapspace = FALSE;
3487 	hibernate_flush_timed_out = FALSE;
3488 	c_generation_id_flush_barrier = c_generation_id + 1000;
3489 
3490 	clock_get_system_nanotime(&now_sec, &now_nsec);
3491 	hibernate_flushing_deadline = now_sec + HIBERNATE_FLUSHING_SECS_TO_COMPLETE;
3492 
3493 	vm_swap_put_failures_at_start = vm_swap_put_failures;
3494 
3495 	/*
3496 	 * We are about to hibernate and so we want all segments flushed to disk.
3497 	 * Segments that are on the major compaction queue won't be considered in
3498 	 * the vm_compressor_compact_and_swap() pass. So we need to bring them to
3499 	 * the ageQ for consideration.
3500 	 */
3501 	if (!queue_empty(&c_major_list_head)) {
3502 		c_seg = (c_segment_t)queue_first(&c_major_list_head);
3503 
3504 		while (!queue_end(&c_major_list_head, (queue_entry_t)c_seg)) {
3505 			c_seg_next = (c_segment_t) queue_next(&c_seg->c_age_list);
3506 			lck_mtx_lock_spin_always(&c_seg->c_lock);
3507 			c_seg_switch_state(c_seg, C_ON_AGE_Q, FALSE);
3508 			lck_mtx_unlock_always(&c_seg->c_lock);
3509 			c_seg = c_seg_next;
3510 		}
3511 	}
3512 	vm_compressor_compact_and_swap(TRUE);
3513 	/* need to wait here since the swap thread may also be running in parallel and handling segments */
3514 	while (!queue_empty(&c_early_swapout_list_head) || !queue_empty(&c_regular_swapout_list_head) || !queue_empty(&c_late_swapout_list_head)) {
3515 		assert_wait_timeout((event_t) &compaction_swapper_running, THREAD_INTERRUPTIBLE, 5000, 1000 * NSEC_PER_USEC);
3516 
3517 		lck_mtx_unlock_always(c_list_lock);
3518 
3519 		wait_result = thread_block(THREAD_CONTINUE_NULL);
3520 
3521 		lck_mtx_lock_spin_always(c_list_lock);
3522 
3523 		if (wait_result == THREAD_TIMED_OUT) {
3524 			break;
3525 		}
3526 	}
3527 	hibernate_flushing = FALSE;
3528 	compaction_swapper_running = 0;
3529 
3530 	if (vm_swap_put_failures > vm_swap_put_failures_at_start) {
3531 		HIBLOG("vm_compressor_flush failed to clean %llu segments - vm_page_compressor_count(%d)\n",
3532 		    vm_swap_put_failures - vm_swap_put_failures_at_start, VM_PAGE_COMPRESSOR_COUNT);
3533 	}
3534 
3535 	lck_mtx_unlock_always(c_list_lock);
3536 
3537 	thread_wakeup((event_t)&compaction_swapper_running);
3538 
3539 	clock_get_uptime(&endTime);
3540 	SUB_ABSOLUTETIME(&endTime, &startTime);
3541 	absolutetime_to_nanoseconds(endTime, &nsec);
3542 
3543 	HIBLOG("vm_compressor_flush completed - took %qd msecs - vm_num_swap_files = %d, vm_num_pinned_swap_files = %d, vm_swappin_enabled = %d\n",
3544 	    nsec / 1000000ULL, vm_num_swap_files, vm_num_pinned_swap_files, vm_swappin_enabled);
3545 }
3546 
3547 
3548 int             compaction_swap_trigger_thread_awakened = 0;
3549 
3550 static void
vm_compressor_swap_trigger_thread(void)3551 vm_compressor_swap_trigger_thread(void)
3552 {
3553 	current_thread()->options |= TH_OPT_VMPRIV;
3554 
3555 	/*
3556 	 * compaction_swapper_init_now is set when the first call to
3557 	 * vm_consider_waking_compactor_swapper is made from
3558 	 * vm_pageout_scan... since this function is called upon
3559 	 * thread creation, we want to make sure to delay adjusting
3560 	 * the tuneables until we are awakened via vm_pageout_scan
3561 	 * so that we are at a point where the vm_swapfile_open will
3562 	 * be operating on the correct directory (in case the default
3563 	 * of using the VM volume is overridden by the dynamic_pager)
3564 	 */
3565 	if (compaction_swapper_init_now) {
3566 		vm_compaction_swapper_do_init();
3567 
3568 		if (vm_pageout_state.vm_restricted_to_single_processor == TRUE) {
3569 			thread_vm_bind_group_add();
3570 		}
3571 #if CONFIG_THREAD_GROUPS
3572 		thread_group_vm_add();
3573 #endif
3574 		thread_set_thread_name(current_thread(), "VM_cswap_trigger");
3575 		compaction_swapper_init_now = 0;
3576 	}
3577 	lck_mtx_lock_spin_always(c_list_lock);
3578 
3579 	compaction_swap_trigger_thread_awakened++;
3580 	compaction_swapper_awakened = 0;
3581 
3582 	if (compaction_swapper_running == 0) {
3583 		compaction_swapper_running = 1;
3584 
3585 		vm_compressor_compact_and_swap(FALSE);
3586 
3587 		compaction_swapper_running = 0;
3588 	}
3589 	assert_wait((event_t)&c_compressor_swap_trigger, THREAD_UNINT);
3590 
3591 	if (compaction_swapper_running == 0) {
3592 		thread_wakeup((event_t)&compaction_swapper_running);
3593 	}
3594 
3595 	lck_mtx_unlock_always(c_list_lock);
3596 
3597 	thread_block((thread_continue_t)vm_compressor_swap_trigger_thread);
3598 
3599 	/* NOTREACHED */
3600 }
3601 
3602 
3603 void
vm_compressor_record_warmup_start(void)3604 vm_compressor_record_warmup_start(void)
3605 {
3606 	c_segment_t     c_seg;
3607 
3608 	lck_mtx_lock_spin_always(c_list_lock);
3609 
3610 	if (first_c_segment_to_warm_generation_id == 0) {
3611 		if (!queue_empty(&c_age_list_head)) {
3612 			c_seg = (c_segment_t)queue_last(&c_age_list_head);
3613 
3614 			first_c_segment_to_warm_generation_id = c_seg->c_generation_id;
3615 		} else {
3616 			first_c_segment_to_warm_generation_id = 0;
3617 		}
3618 
3619 		fastwake_recording_in_progress = TRUE;
3620 	}
3621 	lck_mtx_unlock_always(c_list_lock);
3622 }
3623 
3624 
3625 void
vm_compressor_record_warmup_end(void)3626 vm_compressor_record_warmup_end(void)
3627 {
3628 	c_segment_t     c_seg;
3629 
3630 	lck_mtx_lock_spin_always(c_list_lock);
3631 
3632 	if (fastwake_recording_in_progress == TRUE) {
3633 		if (!queue_empty(&c_age_list_head)) {
3634 			c_seg = (c_segment_t)queue_last(&c_age_list_head);
3635 
3636 			last_c_segment_to_warm_generation_id = c_seg->c_generation_id;
3637 		} else {
3638 			last_c_segment_to_warm_generation_id = first_c_segment_to_warm_generation_id;
3639 		}
3640 
3641 		fastwake_recording_in_progress = FALSE;
3642 
3643 		HIBLOG("vm_compressor_record_warmup (%qd - %qd)\n", first_c_segment_to_warm_generation_id, last_c_segment_to_warm_generation_id);
3644 	}
3645 	lck_mtx_unlock_always(c_list_lock);
3646 }
3647 
3648 
3649 #define DELAY_TRIM_ON_WAKE_NS (25 * NSEC_PER_SEC)
3650 
3651 void
vm_compressor_delay_trim(void)3652 vm_compressor_delay_trim(void)
3653 {
3654 	uint64_t now = mach_absolute_time();
3655 	uint64_t delay_abstime;
3656 	nanoseconds_to_absolutetime(DELAY_TRIM_ON_WAKE_NS, &delay_abstime);
3657 	dont_trim_until_ts = now + delay_abstime;
3658 }
3659 
3660 
3661 void
vm_compressor_do_warmup(void)3662 vm_compressor_do_warmup(void)
3663 {
3664 	lck_mtx_lock_spin_always(c_list_lock);
3665 
3666 	if (first_c_segment_to_warm_generation_id == last_c_segment_to_warm_generation_id) {
3667 		first_c_segment_to_warm_generation_id = last_c_segment_to_warm_generation_id = 0;
3668 
3669 		lck_mtx_unlock_always(c_list_lock);
3670 		return;
3671 	}
3672 
3673 	if (compaction_swapper_running == 0 && compaction_swapper_awakened == 0) {
3674 		fastwake_warmup = TRUE;
3675 
3676 		compaction_swapper_awakened = 1;
3677 		thread_wakeup((event_t)&c_compressor_swap_trigger);
3678 	}
3679 	lck_mtx_unlock_always(c_list_lock);
3680 }
3681 
3682 void
do_fastwake_warmup_all(void)3683 do_fastwake_warmup_all(void)
3684 {
3685 	lck_mtx_lock_spin_always(c_list_lock);
3686 
3687 	if (queue_empty(&c_swappedout_list_head) && queue_empty(&c_swappedout_sparse_list_head)) {
3688 		lck_mtx_unlock_always(c_list_lock);
3689 		return;
3690 	}
3691 
3692 	fastwake_warmup = TRUE;
3693 
3694 	do_fastwake_warmup(&c_swappedout_list_head, TRUE);
3695 
3696 	do_fastwake_warmup(&c_swappedout_sparse_list_head, TRUE);
3697 
3698 	fastwake_warmup = FALSE;
3699 
3700 	lck_mtx_unlock_always(c_list_lock);
3701 }
3702 
3703 void
do_fastwake_warmup(queue_head_t * c_queue,boolean_t consider_all_cseg)3704 do_fastwake_warmup(queue_head_t *c_queue, boolean_t consider_all_cseg)
3705 {
3706 	c_segment_t     c_seg = NULL;
3707 	AbsoluteTime    startTime, endTime;
3708 	uint64_t        nsec;
3709 
3710 
3711 	HIBLOG("vm_compressor_fastwake_warmup (%qd - %qd) - starting\n", first_c_segment_to_warm_generation_id, last_c_segment_to_warm_generation_id);
3712 
3713 	clock_get_uptime(&startTime);
3714 
3715 	lck_mtx_unlock_always(c_list_lock);
3716 
3717 	proc_set_thread_policy(current_thread(),
3718 	    TASK_POLICY_INTERNAL, TASK_POLICY_IO, THROTTLE_LEVEL_COMPRESSOR_TIER2);
3719 
3720 	PAGE_REPLACEMENT_DISALLOWED(TRUE);
3721 
3722 	lck_mtx_lock_spin_always(c_list_lock);
3723 
3724 	while (!queue_empty(c_queue) && fastwake_warmup == TRUE) {
3725 		c_seg = (c_segment_t) queue_first(c_queue);
3726 
3727 		if (consider_all_cseg == FALSE) {
3728 			if (c_seg->c_generation_id < first_c_segment_to_warm_generation_id ||
3729 			    c_seg->c_generation_id > last_c_segment_to_warm_generation_id) {
3730 				break;
3731 			}
3732 
3733 			if (vm_page_free_count < (AVAILABLE_MEMORY / 4)) {
3734 				break;
3735 			}
3736 		}
3737 
3738 		lck_mtx_lock_spin_always(&c_seg->c_lock);
3739 		lck_mtx_unlock_always(c_list_lock);
3740 
3741 		if (c_seg->c_busy) {
3742 			PAGE_REPLACEMENT_DISALLOWED(FALSE);
3743 			c_seg_wait_on_busy(c_seg);
3744 			PAGE_REPLACEMENT_DISALLOWED(TRUE);
3745 		} else {
3746 			if (c_seg_swapin(c_seg, TRUE, FALSE) == 0) {
3747 				lck_mtx_unlock_always(&c_seg->c_lock);
3748 			}
3749 			c_segment_warmup_count++;
3750 
3751 			PAGE_REPLACEMENT_DISALLOWED(FALSE);
3752 			vm_pageout_io_throttle();
3753 			PAGE_REPLACEMENT_DISALLOWED(TRUE);
3754 		}
3755 		lck_mtx_lock_spin_always(c_list_lock);
3756 	}
3757 	lck_mtx_unlock_always(c_list_lock);
3758 
3759 	PAGE_REPLACEMENT_DISALLOWED(FALSE);
3760 
3761 	proc_set_thread_policy(current_thread(),
3762 	    TASK_POLICY_INTERNAL, TASK_POLICY_IO, THROTTLE_LEVEL_COMPRESSOR_TIER0);
3763 
3764 	clock_get_uptime(&endTime);
3765 	SUB_ABSOLUTETIME(&endTime, &startTime);
3766 	absolutetime_to_nanoseconds(endTime, &nsec);
3767 
3768 	HIBLOG("vm_compressor_fastwake_warmup completed - took %qd msecs\n", nsec / 1000000ULL);
3769 
3770 	lck_mtx_lock_spin_always(c_list_lock);
3771 
3772 	if (consider_all_cseg == FALSE) {
3773 		first_c_segment_to_warm_generation_id = last_c_segment_to_warm_generation_id = 0;
3774 	}
3775 }
3776 
3777 extern bool     vm_swapout_thread_running;
3778 extern boolean_t        compressor_store_stop_compaction;
3779 
3780 void
vm_compressor_compact_and_swap(boolean_t flush_all)3781 vm_compressor_compact_and_swap(boolean_t flush_all)
3782 {
3783 	c_segment_t     c_seg;
3784 	bool            switch_state, bail_wanted_cseg = false;
3785 	clock_sec_t     now;
3786 	clock_nsec_t    nsec;
3787 	mach_timespec_t start_ts, end_ts;
3788 	unsigned int    number_considered, wanted_cseg_found, yield_after_considered_per_pass, number_yields;
3789 	uint64_t        bytes_freed, delta_usec;
3790 	uint32_t        c_swapout_count = 0;
3791 
3792 	VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, DBG_VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_START, c_age_count, c_minor_count, c_major_count, vm_page_free_count);
3793 
3794 	if (fastwake_warmup == TRUE) {
3795 		uint64_t        starting_warmup_count;
3796 
3797 		starting_warmup_count = c_segment_warmup_count;
3798 
3799 		KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 11) | DBG_FUNC_START, c_segment_warmup_count,
3800 		    first_c_segment_to_warm_generation_id, last_c_segment_to_warm_generation_id, 0, 0);
3801 		do_fastwake_warmup(&c_swappedout_list_head, FALSE);
3802 		KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 11) | DBG_FUNC_END, c_segment_warmup_count, c_segment_warmup_count - starting_warmup_count, 0, 0, 0);
3803 
3804 		fastwake_warmup = FALSE;
3805 	}
3806 
3807 #if (XNU_TARGET_OS_OSX && __arm64__)
3808 	/*
3809 	 * Re-considering major csegs showed benefits on all platforms by
3810 	 * significantly reducing fragmentation and getting back memory.
3811 	 * However, on smaller devices, eg watch, there was increased power
3812 	 * use for the additional compactions. And the turnover in csegs on
3813 	 * those smaller platforms is high enough in the decompression/free
3814 	 * path that we can skip reconsidering them here because we already
3815 	 * consider them for major compaction in those paths.
3816 	 */
3817 	vm_compressor_process_major_segments(false /*all segments and not just the ripe-aged ones*/);
3818 #endif /* (XNU_TARGET_OS_OSX && __arm64__) */
3819 
3820 	/*
3821 	 * it's possible for the c_age_list_head to be empty if we
3822 	 * hit our limits for growing the compressor pool and we subsequently
3823 	 * hibernated... on the next hibernation we could see the queue as
3824 	 * empty and not proceeed even though we have a bunch of segments on
3825 	 * the swapped in queue that need to be dealt with.
3826 	 */
3827 	vm_compressor_do_delayed_compactions(flush_all);
3828 	vm_compressor_process_special_swapped_in_segments_locked();
3829 	vm_compressor_process_regular_swapped_in_segments(flush_all);
3830 
3831 	/*
3832 	 * we only need to grab the timestamp once per
3833 	 * invocation of this function since the
3834 	 * timescale we're interested in is measured
3835 	 * in days
3836 	 */
3837 	clock_get_system_nanotime(&now, &nsec);
3838 
3839 	start_ts.tv_sec = (int) now;
3840 	start_ts.tv_nsec = nsec;
3841 	delta_usec = 0;
3842 	number_considered = 0;
3843 	wanted_cseg_found = 0;
3844 	number_yields = 0;
3845 	bytes_freed = 0;
3846 	yield_after_considered_per_pass = MAX(min_csegs_per_major_compaction, DELAYED_COMPACTIONS_PER_PASS);
3847 
3848 #if 0
3849 	/**
3850 	 * SW: Need to figure out how to properly rate limit this log because it is currently way too
3851 	 * noisy. rdar://99379414 (Figure out how to rate limit the fragmentation level logging)
3852 	 */
3853 	os_log(OS_LOG_DEFAULT, "memorystatus: before compaction fragmentation level %u\n", vm_compressor_fragmentation_level());
3854 #endif
3855 
3856 	while (!queue_empty(&c_age_list_head) && !compaction_swapper_abort && !compressor_store_stop_compaction) {
3857 		if (hibernate_flushing == TRUE) {
3858 			clock_sec_t     sec;
3859 
3860 			if (hibernate_should_abort()) {
3861 				HIBLOG("vm_compressor_flush - hibernate_should_abort returned TRUE\n");
3862 				break;
3863 			}
3864 			if (hibernate_no_swapspace == TRUE) {
3865 				HIBLOG("vm_compressor_flush - out of swap space\n");
3866 				break;
3867 			}
3868 			if (vm_swap_files_pinned() == FALSE) {
3869 				HIBLOG("vm_compressor_flush - unpinned swap files\n");
3870 				break;
3871 			}
3872 			if (hibernate_in_progress_with_pinned_swap == TRUE &&
3873 			    (vm_swapfile_total_segs_alloced == vm_swapfile_total_segs_used)) {
3874 				HIBLOG("vm_compressor_flush - out of pinned swap space\n");
3875 				break;
3876 			}
3877 			clock_get_system_nanotime(&sec, &nsec);
3878 
3879 			if (sec > hibernate_flushing_deadline) {
3880 				hibernate_flush_timed_out = TRUE;
3881 				HIBLOG("vm_compressor_flush - failed to finish before deadline\n");
3882 				break;
3883 			}
3884 		}
3885 
3886 		c_swapout_count = c_early_swapout_count + c_regular_swapout_count + c_late_swapout_count;
3887 		if (VM_CONFIG_SWAP_IS_ACTIVE && !vm_swap_out_of_space() && c_swapout_count >= C_SWAPOUT_LIMIT) {
3888 			assert_wait_timeout((event_t) &compaction_swapper_running, THREAD_INTERRUPTIBLE, 100, 1000 * NSEC_PER_USEC);
3889 
3890 			if (!vm_swapout_thread_running) {
3891 				thread_wakeup((event_t)&vm_swapout_thread);
3892 			}
3893 
3894 			lck_mtx_unlock_always(c_list_lock);
3895 
3896 			VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, DBG_VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 1, c_swapout_count, 0, 0);
3897 
3898 			thread_block(THREAD_CONTINUE_NULL);
3899 
3900 			lck_mtx_lock_spin_always(c_list_lock);
3901 		}
3902 		/*
3903 		 * Minor compactions
3904 		 */
3905 		vm_compressor_do_delayed_compactions(flush_all);
3906 
3907 		/*
3908 		 * vm_compressor_process_early_swapped_in_segments()
3909 		 * might be too aggressive. So OFF for now.
3910 		 */
3911 		vm_compressor_process_regular_swapped_in_segments(flush_all);
3912 
3913 		/* Recompute because we dropped the c_list_lock above*/
3914 		c_swapout_count = c_early_swapout_count + c_regular_swapout_count + c_late_swapout_count;
3915 		if (VM_CONFIG_SWAP_IS_ACTIVE && !vm_swap_out_of_space() && c_swapout_count >= C_SWAPOUT_LIMIT) {
3916 			/*
3917 			 * we timed out on the above thread_block
3918 			 * let's loop around and try again
3919 			 * the timeout allows us to continue
3920 			 * to do minor compactions to make
3921 			 * more memory available
3922 			 */
3923 			VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, DBG_VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 2, c_swapout_count, 0, 0);
3924 
3925 			continue;
3926 		}
3927 
3928 		/*
3929 		 * Swap out segments?
3930 		 */
3931 		if (flush_all == FALSE) {
3932 			bool needs_to_swap;
3933 
3934 			lck_mtx_unlock_always(c_list_lock);
3935 
3936 			needs_to_swap = compressor_needs_to_swap();
3937 
3938 			lck_mtx_lock_spin_always(c_list_lock);
3939 
3940 			VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, DBG_VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 3, needs_to_swap, 0, 0);
3941 
3942 			if (!needs_to_swap) {
3943 				break;
3944 			}
3945 		}
3946 		if (queue_empty(&c_age_list_head)) {
3947 			VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, DBG_VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 4, c_age_count, 0, 0);
3948 			break;
3949 		}
3950 		c_seg = (c_segment_t) queue_first(&c_age_list_head);
3951 
3952 		assert(c_seg->c_state == C_ON_AGE_Q);
3953 
3954 		if (flush_all == TRUE && c_seg->c_generation_id > c_generation_id_flush_barrier) {
3955 			VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, DBG_VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 5, 0, 0, 0);
3956 			break;
3957 		}
3958 
3959 		lck_mtx_lock_spin_always(&c_seg->c_lock);
3960 
3961 		if (c_seg->c_busy) {
3962 			VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, DBG_VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 6, (void*) VM_KERNEL_ADDRPERM(c_seg), 0, 0);
3963 
3964 			lck_mtx_unlock_always(c_list_lock);
3965 			c_seg_wait_on_busy(c_seg);
3966 			lck_mtx_lock_spin_always(c_list_lock);
3967 
3968 			continue;
3969 		}
3970 		C_SEG_BUSY(c_seg);
3971 
3972 		if (c_seg_do_minor_compaction_and_unlock(c_seg, FALSE, TRUE, TRUE)) {
3973 			/*
3974 			 * found an empty c_segment and freed it
3975 			 * so go grab the next guy in the queue
3976 			 */
3977 			VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, DBG_VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 7, 0, 0, 0);
3978 			c_seg_major_compact_stats[c_seg_major_compact_stats_now].count_of_freed_segs++;
3979 			continue;
3980 		}
3981 
3982 		switch_state = vm_compressor_major_compact_cseg(c_seg, &number_considered, &bail_wanted_cseg, &bytes_freed);
3983 		if (bail_wanted_cseg) {
3984 			wanted_cseg_found++;
3985 			bail_wanted_cseg = false;
3986 		}
3987 
3988 		assert(c_seg->c_busy);
3989 		assert(!c_seg->c_on_minorcompact_q);
3990 
3991 		if (switch_state) {
3992 			if (VM_CONFIG_SWAP_IS_ACTIVE) {
3993 				int new_state = C_ON_SWAPOUT_Q;
3994 #if (XNU_TARGET_OS_OSX && __arm64__)
3995 				if (flush_all == false && compressor_swapout_conditions_met() == false) {
3996 					new_state = C_ON_MAJORCOMPACT_Q;
3997 				}
3998 #endif /* (XNU_TARGET_OS_OSX && __arm64__) */
3999 
4000 				if (new_state == C_ON_SWAPOUT_Q) {
4001 					/*
4002 					 * This mode of putting a generic c_seg on the swapout list is
4003 					 * only supported when we have general swapping enabled
4004 					 */
4005 					clock_sec_t lnow;
4006 					clock_nsec_t lnsec;
4007 					clock_get_system_nanotime(&lnow, &lnsec);
4008 					if (c_seg->c_agedin_ts && (lnow - c_seg->c_agedin_ts) < 30) {
4009 						vmcs_stats.unripe_under_30s++;
4010 					} else if (c_seg->c_agedin_ts && (lnow - c_seg->c_agedin_ts) < 60) {
4011 						vmcs_stats.unripe_under_60s++;
4012 					} else if (c_seg->c_agedin_ts && (lnow - c_seg->c_agedin_ts) < 300) {
4013 						vmcs_stats.unripe_under_300s++;
4014 					}
4015 				}
4016 
4017 				c_seg_switch_state(c_seg, new_state, FALSE);
4018 			} else {
4019 				if ((vm_swapout_ripe_segments == TRUE && c_overage_swapped_count < c_overage_swapped_limit)) {
4020 					assert(VM_CONFIG_SWAP_IS_PRESENT);
4021 					/*
4022 					 * we are running compressor sweeps with swap-behind
4023 					 * make sure the c_seg has aged enough before swapping it
4024 					 * out...
4025 					 */
4026 					if ((now - c_seg->c_creation_ts) >= vm_ripe_target_age) {
4027 						c_seg->c_overage_swap = TRUE;
4028 						c_overage_swapped_count++;
4029 						c_seg_switch_state(c_seg, C_ON_SWAPOUT_Q, FALSE);
4030 					}
4031 				}
4032 			}
4033 			if (c_seg->c_state == C_ON_AGE_Q) {
4034 				/*
4035 				 * this c_seg didn't get moved to the swapout queue
4036 				 * so we need to move it out of the way...
4037 				 * we just did a major compaction on it so put it
4038 				 * on that queue
4039 				 */
4040 				c_seg_switch_state(c_seg, C_ON_MAJORCOMPACT_Q, FALSE);
4041 			} else {
4042 				c_seg_major_compact_stats[c_seg_major_compact_stats_now].wasted_space_in_swapouts += c_seg_bufsize - c_seg->c_bytes_used;
4043 				c_seg_major_compact_stats[c_seg_major_compact_stats_now].count_of_swapouts++;
4044 			}
4045 		}
4046 
4047 		C_SEG_WAKEUP_DONE(c_seg);
4048 
4049 		lck_mtx_unlock_always(&c_seg->c_lock);
4050 
4051 		/*
4052 		 * On systems _with_ general swap, regardless of jetsam, we wake up the swapout thread here.
4053 		 * On systems _without_ general swap, it's the responsibility of the memorystatus
4054 		 * subsystem to wake up the swapper.
4055 		 * TODO: When we have full jetsam support on a swap enabled system, we will need to revisit
4056 		 * this policy.
4057 		 */
4058 		if (VM_CONFIG_SWAP_IS_ACTIVE && c_swapout_count) {
4059 			/*
4060 			 * We don't pause/yield here because we will either
4061 			 * yield below or at the top of the loop with the
4062 			 * assert_wait_timeout.
4063 			 */
4064 			if (!vm_swapout_thread_running) {
4065 				thread_wakeup((event_t)&vm_swapout_thread);
4066 			}
4067 		}
4068 
4069 		if (number_considered >= yield_after_considered_per_pass) {
4070 			if (wanted_cseg_found) {
4071 				/*
4072 				 * We stopped major compactions on a c_seg
4073 				 * that is wanted. We don't know the priority
4074 				 * of the waiter unfortunately but we are at
4075 				 * a very high priority and so, just in case
4076 				 * the waiter is a critical system daemon or
4077 				 * UI thread, let's give up the CPU in case
4078 				 * the system is running a few CPU intensive
4079 				 * tasks.
4080 				 */
4081 				lck_mtx_unlock_always(c_list_lock);
4082 
4083 				mutex_pause(2); /* 100us yield */
4084 
4085 				number_yields++;
4086 
4087 				VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, DBG_VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 11, number_considered, number_yields, 0);
4088 
4089 				lck_mtx_lock_spin_always(c_list_lock);
4090 			}
4091 
4092 			number_considered = 0;
4093 			wanted_cseg_found = 0;
4094 		}
4095 	}
4096 	clock_get_system_nanotime(&now, &nsec);
4097 
4098 	end_ts = major_compact_ts = (mach_timespec_t){.tv_sec = (int)now, .tv_nsec = nsec};
4099 
4100 	SUB_MACH_TIMESPEC(&end_ts, &start_ts);
4101 
4102 	delta_usec = (end_ts.tv_sec * USEC_PER_SEC) + (end_ts.tv_nsec / NSEC_PER_USEC) - (number_yields * 100);
4103 
4104 	delta_usec = MAX(1, delta_usec); /* we could have 0 usec run if conditions weren't right */
4105 
4106 	c_seg_major_compact_stats[c_seg_major_compact_stats_now].bytes_freed_rate_us = (bytes_freed / delta_usec);
4107 
4108 	if ((c_seg_major_compact_stats_now + 1) == C_SEG_MAJOR_COMPACT_STATS_MAX) {
4109 		c_seg_major_compact_stats_now = 0;
4110 	} else {
4111 		c_seg_major_compact_stats_now++;
4112 	}
4113 
4114 	assert(c_seg_major_compact_stats_now < C_SEG_MAJOR_COMPACT_STATS_MAX);
4115 
4116 	VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, DBG_VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_END, c_age_count, c_minor_count, c_major_count, vm_page_free_count);
4117 }
4118 
4119 
4120 static c_segment_t
c_seg_allocate(c_segment_t * current_chead,bool * nearing_limits)4121 c_seg_allocate(c_segment_t *current_chead, bool *nearing_limits)
4122 {
4123 	c_segment_t     c_seg;
4124 	int             min_needed;
4125 	int             size_to_populate;
4126 	c_segment_t     *donate_queue_head;
4127 	uint32_t        compressed_pages;
4128 
4129 	*nearing_limits = false;
4130 
4131 	compressed_pages = vm_compressor_pages_compressed();
4132 
4133 	if (compressed_pages >= c_segment_pages_compressed_nearing_limit) {
4134 		*nearing_limits = true;
4135 	}
4136 	if (compressed_pages >= c_segment_pages_compressed_limit) {
4137 		/*
4138 		 * We've reached the compressed pages limit, don't return
4139 		 * a segment to compress into
4140 		 */
4141 		return NULL;
4142 	}
4143 
4144 	if ((c_seg = *current_chead) == NULL) {
4145 		uint32_t        c_segno;
4146 
4147 		lck_mtx_lock_spin_always(c_list_lock);
4148 
4149 		while (c_segments_busy == TRUE) {
4150 			assert_wait((event_t) (&c_segments_busy), THREAD_UNINT);
4151 
4152 			lck_mtx_unlock_always(c_list_lock);
4153 
4154 			thread_block(THREAD_CONTINUE_NULL);
4155 
4156 			lck_mtx_lock_spin_always(c_list_lock);
4157 		}
4158 		if (c_free_segno_head == (uint32_t)-1) {
4159 			uint32_t        c_segments_available_new;
4160 
4161 			/*
4162 			 * We may have dropped the c_list_lock, re-evaluate
4163 			 * the compressed pages count
4164 			 */
4165 			compressed_pages = vm_compressor_pages_compressed();
4166 
4167 			if (c_segments_available >= c_segments_nearing_limit ||
4168 			    compressed_pages >= c_segment_pages_compressed_nearing_limit) {
4169 				*nearing_limits = true;
4170 			}
4171 			if (c_segments_available >= c_segments_limit ||
4172 			    compressed_pages >= c_segment_pages_compressed_limit) {
4173 				lck_mtx_unlock_always(c_list_lock);
4174 
4175 				return NULL;
4176 			}
4177 			c_segments_busy = TRUE;
4178 			lck_mtx_unlock_always(c_list_lock);
4179 
4180 			/* pages for c_segments are never depopulated, c_segments_available never goes down */
4181 			kernel_memory_populate((vm_offset_t)c_segments_next_page,
4182 			    PAGE_SIZE, KMA_NOFAIL | KMA_KOBJECT,
4183 			    VM_KERN_MEMORY_COMPRESSOR);
4184 			c_segments_next_page += PAGE_SIZE;
4185 
4186 			c_segments_available_new = c_segments_available + C_SEGMENTS_PER_PAGE;
4187 
4188 			if (c_segments_available_new > c_segments_limit) {
4189 				c_segments_available_new = c_segments_limit;
4190 			}
4191 
4192 			/* add the just-added segments to the top of the free-list */
4193 			for (c_segno = c_segments_available + 1; c_segno < c_segments_available_new; c_segno++) {
4194 				c_segments_get(c_segno - 1)->c_segno = c_segno;  /* next free is the one after you */
4195 			}
4196 
4197 			lck_mtx_lock_spin_always(c_list_lock);
4198 
4199 			c_segments_get(c_segno - 1)->c_segno = c_free_segno_head; /* link to the rest of, existing freelist */
4200 			c_free_segno_head = c_segments_available; /* first one in the page that was just allocated */
4201 			c_segments_available = c_segments_available_new;
4202 
4203 			c_segments_busy = FALSE;
4204 			thread_wakeup((event_t) (&c_segments_busy));
4205 		}
4206 		c_segno = c_free_segno_head;
4207 		assert(c_segno >= 0 && c_segno < c_segments_limit);
4208 
4209 		c_free_segno_head = (uint32_t)c_segments_get(c_segno)->c_segno;
4210 
4211 		/*
4212 		 * do the rest of the bookkeeping now while we're still behind
4213 		 * the list lock and grab our generation id now into a local
4214 		 * so that we can install it once we have the c_seg allocated
4215 		 */
4216 		c_segment_count++;
4217 		if (c_segment_count > c_segment_count_max) {
4218 			c_segment_count_max = c_segment_count;
4219 		}
4220 
4221 		lck_mtx_unlock_always(c_list_lock);
4222 
4223 		c_seg = zalloc_flags(compressor_segment_zone, Z_WAITOK | Z_ZERO);
4224 
4225 		c_seg->c_store.c_buffer = (int32_t *)C_SEG_BUFFER_ADDRESS(c_segno);
4226 
4227 		lck_mtx_init(&c_seg->c_lock, &vm_compressor_lck_grp, LCK_ATTR_NULL);
4228 
4229 		c_seg->c_state = C_IS_EMPTY;
4230 		c_seg->c_firstemptyslot = C_SLOT_MAX_INDEX;
4231 		c_seg->c_mysegno = c_segno;
4232 
4233 		lck_mtx_lock_spin_always(c_list_lock);
4234 		c_empty_count++;  /* going to be immediately decremented in the next call */
4235 		c_seg_switch_state(c_seg, C_IS_FILLING, FALSE);
4236 		c_segments_get(c_segno)->c_seg = c_seg;
4237 		assert(c_segments_get(c_segno)->c_segno > c_segments_available);  /* we just assigned a pointer to it so this is an indication that it is occupied */
4238 		lck_mtx_unlock_always(c_list_lock);
4239 
4240 		for (int i = 0; i < vm_pageout_state.vm_compressor_thread_count; i++) {
4241 #if XNU_TARGET_OS_OSX /* tag:DONATE */
4242 			donate_queue_head = (c_segment_t*) &(pgo_iothread_internal_state[i].current_early_swapout_chead);
4243 #else /* XNU_TARGET_OS_OSX */
4244 			if (memorystatus_swap_all_apps) {
4245 				donate_queue_head = (c_segment_t*) &(pgo_iothread_internal_state[i].current_late_swapout_chead);
4246 			} else {
4247 				donate_queue_head = NULL;
4248 			}
4249 #endif /* XNU_TARGET_OS_OSX */
4250 
4251 			if (current_chead == donate_queue_head) {
4252 				c_seg->c_has_donated_pages = 1;
4253 				break;
4254 			}
4255 		}
4256 
4257 		*current_chead = c_seg;
4258 
4259 #if DEVELOPMENT || DEBUG
4260 		C_SEG_MAKE_WRITEABLE(c_seg);
4261 #endif
4262 	}
4263 	c_seg_alloc_nextslot(c_seg);
4264 
4265 	size_to_populate = c_seg_allocsize - C_SEG_OFFSET_TO_BYTES(c_seg->c_populated_offset);
4266 
4267 	if (size_to_populate) {
4268 		min_needed = PAGE_SIZE + (c_seg_allocsize - c_seg_bufsize);
4269 
4270 		if (C_SEG_OFFSET_TO_BYTES(c_seg->c_populated_offset - c_seg->c_nextoffset) < (unsigned) min_needed) {
4271 			if (size_to_populate > C_SEG_MAX_POPULATE_SIZE) {
4272 				size_to_populate = C_SEG_MAX_POPULATE_SIZE;
4273 			}
4274 
4275 			os_atomic_add(&vm_pageout_vminfo.vm_compressor_pages_grabbed, size_to_populate / PAGE_SIZE, relaxed);
4276 
4277 			kernel_memory_populate(
4278 				(vm_offset_t) &c_seg->c_store.c_buffer[c_seg->c_populated_offset],
4279 				size_to_populate,
4280 				KMA_NOFAIL | KMA_COMPRESSOR,
4281 				VM_KERN_MEMORY_COMPRESSOR);
4282 		} else {
4283 			size_to_populate = 0;
4284 		}
4285 	}
4286 	PAGE_REPLACEMENT_DISALLOWED(TRUE);
4287 
4288 	lck_mtx_lock_spin_always(&c_seg->c_lock);
4289 
4290 	if (size_to_populate) {
4291 		c_seg->c_populated_offset += C_SEG_BYTES_TO_OFFSET(size_to_populate);
4292 	}
4293 
4294 	return c_seg;
4295 }
4296 
4297 #if DEVELOPMENT || DEBUG
4298 #if CONFIG_FREEZE
4299 extern boolean_t memorystatus_freeze_to_memory;
4300 #endif /* CONFIG_FREEZE */
4301 #endif /* DEVELOPMENT || DEBUG */
4302 uint64_t c_seg_total_donated_bytes = 0; /* For testing/debugging only for now. Remove and add new counters for vm_stat.*/
4303 
4304 uint64_t c_seg_filled_no_contention = 0;
4305 uint64_t c_seg_filled_contention = 0;
4306 clock_sec_t c_seg_filled_contention_sec_max = 0;
4307 clock_nsec_t c_seg_filled_contention_nsec_max = 0;
4308 
4309 static void
c_current_seg_filled(c_segment_t c_seg,c_segment_t * current_chead)4310 c_current_seg_filled(c_segment_t c_seg, c_segment_t *current_chead)
4311 {
4312 	uint32_t        unused_bytes;
4313 	uint32_t        offset_to_depopulate;
4314 	int             new_state = C_ON_AGE_Q;
4315 	clock_sec_t     sec;
4316 	clock_nsec_t    nsec;
4317 	bool            head_insert = false, wakeup_swapout_thread = false;
4318 
4319 	unused_bytes = trunc_page_32(C_SEG_OFFSET_TO_BYTES(c_seg->c_populated_offset - c_seg->c_nextoffset));
4320 
4321 	if (unused_bytes) {
4322 		/* if this is a platform that need an extra page at the end of the segment when running compress
4323 		 * then now is the time to depopulate that extra page. it still takes virtual space but doesn't
4324 		 * actually waste memory */
4325 		offset_to_depopulate = C_SEG_BYTES_TO_OFFSET(round_page_32(C_SEG_OFFSET_TO_BYTES(c_seg->c_nextoffset)));
4326 
4327 		/* release the extra physical page(s) at the end of the segment  */
4328 		lck_mtx_unlock_always(&c_seg->c_lock);
4329 
4330 		kernel_memory_depopulate(
4331 			(vm_offset_t) &c_seg->c_store.c_buffer[offset_to_depopulate],
4332 			unused_bytes,
4333 			KMA_COMPRESSOR,
4334 			VM_KERN_MEMORY_COMPRESSOR);
4335 
4336 		lck_mtx_lock_spin_always(&c_seg->c_lock);
4337 
4338 		c_seg->c_populated_offset = offset_to_depopulate;
4339 	}
4340 	assert(C_SEG_OFFSET_TO_BYTES(c_seg->c_populated_offset) <= c_seg_bufsize);
4341 
4342 #if DEVELOPMENT || DEBUG
4343 	{
4344 		boolean_t       c_seg_was_busy = FALSE;
4345 
4346 		if (!c_seg->c_busy) {
4347 			C_SEG_BUSY(c_seg);
4348 		} else {
4349 			c_seg_was_busy = TRUE;
4350 		}
4351 
4352 		lck_mtx_unlock_always(&c_seg->c_lock);
4353 
4354 		C_SEG_WRITE_PROTECT(c_seg);
4355 
4356 		lck_mtx_lock_spin_always(&c_seg->c_lock);
4357 
4358 		if (c_seg_was_busy == FALSE) {
4359 			C_SEG_WAKEUP_DONE(c_seg);
4360 		}
4361 	}
4362 #endif
4363 
4364 #if CONFIG_FREEZE
4365 	if (current_chead == (c_segment_t*) &(freezer_context_global.freezer_ctx_chead) &&
4366 	    VM_CONFIG_SWAP_IS_PRESENT &&
4367 	    VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
4368 #if DEVELOPMENT || DEBUG
4369 	    && !memorystatus_freeze_to_memory
4370 #endif /* DEVELOPMENT || DEBUG */
4371 	    ) {
4372 		new_state = C_ON_SWAPOUT_Q;
4373 		wakeup_swapout_thread = true;
4374 	}
4375 #endif /* CONFIG_FREEZE */
4376 
4377 	if (vm_darkwake_mode == TRUE) {
4378 		new_state = C_ON_SWAPOUT_Q;
4379 		head_insert = true;
4380 		wakeup_swapout_thread = true;
4381 	} else {
4382 		c_segment_t *donate_queue_head;
4383 		for (int i = 0; i < vm_pageout_state.vm_compressor_thread_count; i++) {
4384 #if XNU_TARGET_OS_OSX  /* tag:DONATE */
4385 			donate_queue_head = (c_segment_t*) &(pgo_iothread_internal_state[i].current_early_swapout_chead);
4386 #else /* XNU_TARGET_OS_OSX */
4387 			donate_queue_head = (c_segment_t*) &(pgo_iothread_internal_state[i].current_late_swapout_chead);
4388 #endif /* XNU_TARGET_OS_OSX */
4389 			if (current_chead == donate_queue_head) {
4390 				/* This is the place where the "donating" task actually does the so-called donation
4391 				 * Instead of continueing to take place in memory in the compressor, the segment goes directly
4392 				 * to swap-out instead of going to AGE_Q */
4393 				assert(c_seg->c_has_donated_pages);
4394 				new_state = C_ON_SWAPOUT_Q;
4395 				c_seg_total_donated_bytes += c_seg->c_bytes_used;
4396 				break;
4397 			}
4398 		}
4399 	}
4400 
4401 	clock_get_system_nanotime(&sec, &nsec);
4402 	c_seg->c_creation_ts = (uint32_t)sec;
4403 
4404 	if (!lck_mtx_try_lock_spin_always(c_list_lock)) {
4405 		clock_sec_t     sec2;
4406 		clock_nsec_t    nsec2;
4407 
4408 		lck_mtx_lock_spin_always(c_list_lock);
4409 		clock_get_system_nanotime(&sec2, &nsec2);
4410 		TIME_SUB(sec2, sec, nsec2, nsec, NSEC_PER_SEC);
4411 		/* keep track of how much time we've waited for c_list_lock */
4412 		if (sec2 > c_seg_filled_contention_sec_max) {
4413 			c_seg_filled_contention_sec_max = sec2;
4414 			c_seg_filled_contention_nsec_max = nsec2;
4415 		} else if (sec2 == c_seg_filled_contention_sec_max && nsec2 > c_seg_filled_contention_nsec_max) {
4416 			c_seg_filled_contention_nsec_max = nsec2;
4417 		}
4418 		c_seg_filled_contention++;
4419 	} else {
4420 		c_seg_filled_no_contention++;
4421 	}
4422 
4423 #if CONFIG_FREEZE
4424 	if (current_chead == (c_segment_t*) &(freezer_context_global.freezer_ctx_chead)) {
4425 		if (freezer_context_global.freezer_ctx_task->donates_own_pages) {
4426 			assert(!c_seg->c_has_donated_pages);
4427 			c_seg->c_has_donated_pages = 1;
4428 			os_atomic_add(&c_segment_pages_compressed_incore_late_swapout, c_seg->c_slots_used, relaxed);
4429 		}
4430 		c_seg->c_has_freezer_pages = 1;
4431 	}
4432 #endif /* CONFIG_FREEZE */
4433 
4434 	c_seg->c_generation_id = c_generation_id++;
4435 	c_seg_switch_state(c_seg, new_state, head_insert);
4436 
4437 #if CONFIG_FREEZE
4438 	/*
4439 	 * Donated segments count as frozen to swap if we go through the freezer.
4440 	 * TODO: What we need is a new ledger and cseg state that can describe
4441 	 * a frozen cseg from a donated task so we can accurately decrement it on
4442 	 * swapins.
4443 	 */
4444 	if (current_chead == (c_segment_t*) &(freezer_context_global.freezer_ctx_chead) && (c_seg->c_state == C_ON_SWAPOUT_Q)) {
4445 		/*
4446 		 * darkwake and freezer can't co-exist together
4447 		 * We'll need to fix this accounting as a start.
4448 		 * And early donation c_segs are separate from frozen c_segs.
4449 		 */
4450 		assert(vm_darkwake_mode == FALSE);
4451 		c_seg_update_task_owner(c_seg, freezer_context_global.freezer_ctx_task);
4452 		freezer_context_global.freezer_ctx_swapped_bytes += c_seg->c_bytes_used;
4453 	}
4454 #endif /* CONFIG_FREEZE */
4455 
4456 	if (c_seg->c_state == C_ON_AGE_Q && C_SEG_UNUSED_BYTES(c_seg) >= PAGE_SIZE) {
4457 		/* this is possible if we decompressed a page from the segment before it ended filling */
4458 #if CONFIG_FREEZE
4459 		assert(c_seg->c_task_owner == NULL);
4460 #endif /* CONFIG_FREEZE */
4461 		c_seg_need_delayed_compaction(c_seg, TRUE);
4462 	}
4463 
4464 	lck_mtx_unlock_always(c_list_lock);
4465 
4466 	if (wakeup_swapout_thread) {
4467 		/*
4468 		 * Darkwake and Freeze configs always
4469 		 * wake up the swapout thread because
4470 		 * the compactor thread that normally handles
4471 		 * it may not be running as much in these
4472 		 * configs.
4473 		 */
4474 		thread_wakeup((event_t)&vm_swapout_thread);
4475 	}
4476 
4477 	*current_chead = NULL;
4478 }
4479 
4480 /*
4481  * returns with c_seg locked
4482  */
4483 void
c_seg_swapin_requeue(c_segment_t c_seg,boolean_t has_data,boolean_t minor_compact_ok,boolean_t age_on_swapin_q)4484 c_seg_swapin_requeue(c_segment_t c_seg, boolean_t has_data, boolean_t minor_compact_ok, boolean_t age_on_swapin_q)
4485 {
4486 	clock_sec_t     sec;
4487 	clock_nsec_t    nsec;
4488 
4489 	clock_get_system_nanotime(&sec, &nsec);
4490 
4491 	lck_mtx_lock_spin_always(c_list_lock);
4492 	lck_mtx_lock_spin_always(&c_seg->c_lock);
4493 
4494 	assert(c_seg->c_busy_swapping);
4495 	assert(c_seg->c_busy);
4496 
4497 	c_seg->c_busy_swapping = 0;
4498 
4499 	if (c_seg->c_overage_swap == TRUE) {
4500 		c_overage_swapped_count--;
4501 		c_seg->c_overage_swap = FALSE;
4502 	}
4503 	if (has_data == TRUE) {
4504 		if (age_on_swapin_q == TRUE || c_seg->c_has_donated_pages) {
4505 #if CONFIG_FREEZE
4506 			/*
4507 			 * If a segment has both identities, frozen and donated bits set, the donated
4508 			 * bit wins on the swapin path. This is because the segment is being swapped back
4509 			 * in and so is in demand and should be given more time to spend in memory before
4510 			 * being swapped back out under pressure.
4511 			 */
4512 			if (c_seg->c_has_donated_pages) {
4513 				c_seg->c_has_freezer_pages = 0;
4514 			}
4515 #endif /* CONFIG_FREEZE */
4516 			c_seg_switch_state(c_seg, C_ON_SWAPPEDIN_Q, FALSE);
4517 		} else {
4518 			c_seg_switch_state(c_seg, C_ON_AGE_Q, FALSE);
4519 		}
4520 
4521 		if (minor_compact_ok == TRUE && !c_seg->c_on_minorcompact_q && C_SEG_UNUSED_BYTES(c_seg) >= PAGE_SIZE) {
4522 			c_seg_need_delayed_compaction(c_seg, TRUE);
4523 		}
4524 	} else {
4525 		c_seg->c_store.c_buffer = (int32_t*) NULL;
4526 		c_seg->c_populated_offset = C_SEG_BYTES_TO_OFFSET(0);
4527 
4528 		c_seg_switch_state(c_seg, C_ON_BAD_Q, FALSE);
4529 	}
4530 	c_seg->c_swappedin_ts = (uint32_t)sec;
4531 	c_seg->c_swappedin = true;
4532 #if TRACK_C_SEGMENT_UTILIZATION
4533 	c_seg->c_decompressions_since_swapin = 0;
4534 #endif /* TRACK_C_SEGMENT_UTILIZATION */
4535 
4536 	lck_mtx_unlock_always(c_list_lock);
4537 }
4538 
4539 
4540 
4541 /*
4542  * c_seg has to be locked and is returned locked if the c_seg isn't freed
4543  * PAGE_REPLACMENT_DISALLOWED has to be TRUE on entry and is returned TRUE
4544  * c_seg_swapin returns 1 if the c_seg was freed, 0 otherwise
4545  */
4546 
4547 int
c_seg_swapin(c_segment_t c_seg,boolean_t force_minor_compaction,boolean_t age_on_swapin_q)4548 c_seg_swapin(c_segment_t c_seg, boolean_t force_minor_compaction, boolean_t age_on_swapin_q)
4549 {
4550 	vm_offset_t     addr = 0;
4551 	uint32_t        io_size = 0;
4552 	uint64_t        f_offset;
4553 	thread_pri_floor_t token;
4554 
4555 	assert(C_SEG_IS_ONDISK(c_seg));
4556 
4557 #if !CHECKSUM_THE_SWAP
4558 	c_seg_trim_tail(c_seg);
4559 #endif
4560 	io_size = round_page_32(C_SEG_OFFSET_TO_BYTES(c_seg->c_populated_offset));
4561 	f_offset = c_seg->c_store.c_swap_handle;
4562 
4563 	C_SEG_BUSY(c_seg);
4564 	c_seg->c_busy_swapping = 1;
4565 
4566 	/*
4567 	 * This thread is likely going to block for I/O.
4568 	 * Make sure it is ready to run when the I/O completes because
4569 	 * it needs to clear the busy bit on the c_seg so that other
4570 	 * waiting threads can make progress too.
4571 	 */
4572 	token = thread_priority_floor_start();
4573 	lck_mtx_unlock_always(&c_seg->c_lock);
4574 
4575 	PAGE_REPLACEMENT_DISALLOWED(FALSE);
4576 
4577 	addr = (vm_offset_t)C_SEG_BUFFER_ADDRESS(c_seg->c_mysegno);
4578 	c_seg->c_store.c_buffer = (int32_t*) addr;
4579 
4580 	kernel_memory_populate(addr, io_size, KMA_NOFAIL | KMA_COMPRESSOR,
4581 	    VM_KERN_MEMORY_COMPRESSOR);
4582 
4583 	if (vm_swap_get(c_seg, f_offset, io_size) != KERN_SUCCESS) {
4584 		PAGE_REPLACEMENT_DISALLOWED(TRUE);
4585 
4586 		kernel_memory_depopulate(addr, io_size, KMA_COMPRESSOR,
4587 		    VM_KERN_MEMORY_COMPRESSOR);
4588 
4589 		c_seg_swapin_requeue(c_seg, FALSE, TRUE, age_on_swapin_q);
4590 	} else {
4591 #if ENCRYPTED_SWAP
4592 		vm_swap_decrypt(c_seg, true);
4593 #endif /* ENCRYPTED_SWAP */
4594 
4595 #if CHECKSUM_THE_SWAP
4596 		if (c_seg->cseg_swap_size != io_size) {
4597 			panic("swapin size doesn't match swapout size");
4598 		}
4599 
4600 		if (c_seg->cseg_hash != vmc_hash((char*) c_seg->c_store.c_buffer, (int)io_size)) {
4601 			panic("c_seg_swapin - Swap hash mismatch");
4602 		}
4603 #endif /* CHECKSUM_THE_SWAP */
4604 
4605 		PAGE_REPLACEMENT_DISALLOWED(TRUE);
4606 
4607 		c_seg_swapin_requeue(c_seg, TRUE, force_minor_compaction == TRUE ? FALSE : TRUE, age_on_swapin_q);
4608 
4609 #if CONFIG_FREEZE
4610 		/*
4611 		 * c_seg_swapin_requeue() returns with the c_seg lock held.
4612 		 */
4613 		if (!lck_mtx_try_lock_spin_always(c_list_lock)) {
4614 			assert(c_seg->c_busy);
4615 
4616 			lck_mtx_unlock_always(&c_seg->c_lock);
4617 			lck_mtx_lock_spin_always(c_list_lock);
4618 			lck_mtx_lock_spin_always(&c_seg->c_lock);
4619 		}
4620 
4621 		if (c_seg->c_task_owner) {
4622 			c_seg_update_task_owner(c_seg, NULL);
4623 		}
4624 
4625 		lck_mtx_unlock_always(c_list_lock);
4626 
4627 		os_atomic_add(&c_segment_pages_compressed_incore, c_seg->c_slots_used, relaxed);
4628 		if (c_seg->c_has_donated_pages) {
4629 			os_atomic_add(&c_segment_pages_compressed_incore_late_swapout, c_seg->c_slots_used, relaxed);
4630 		}
4631 #endif /* CONFIG_FREEZE */
4632 
4633 		os_atomic_add(&compressor_bytes_used, c_seg->c_bytes_used, relaxed);
4634 
4635 		if (force_minor_compaction == TRUE) {
4636 			if (c_seg_minor_compaction_and_unlock(c_seg, FALSE)) {
4637 				/*
4638 				 * c_seg was completely empty so it was freed,
4639 				 * so be careful not to reference it again
4640 				 *
4641 				 * Drop the boost so that the thread priority
4642 				 * is returned back to where it is supposed to be.
4643 				 */
4644 				thread_priority_floor_end(&token);
4645 				return 1;
4646 			}
4647 
4648 			lck_mtx_lock_spin_always(&c_seg->c_lock);
4649 		}
4650 	}
4651 	C_SEG_WAKEUP_DONE(c_seg);
4652 
4653 	/*
4654 	 * Drop the boost so that the thread priority
4655 	 * is returned back to where it is supposed to be.
4656 	 */
4657 	thread_priority_floor_end(&token);
4658 
4659 	return 0;
4660 }
4661 
4662 /*
4663  * TODO: refactor the CAS loops in c_segment_sv_hash_drop_ref() and c_segment_sv_hash_instert()
4664  * to os_atomic_rmw_loop() [rdar://139546215]
4665  */
4666 
4667 static void
c_segment_sv_hash_drop_ref(int hash_indx)4668 c_segment_sv_hash_drop_ref(int hash_indx)
4669 {
4670 	struct c_sv_hash_entry o_sv_he, n_sv_he;
4671 
4672 	while (1) {
4673 		o_sv_he.he_record = c_segment_sv_hash_table[hash_indx].he_record;
4674 
4675 		n_sv_he.he_ref = o_sv_he.he_ref - 1;
4676 		n_sv_he.he_data = o_sv_he.he_data;
4677 
4678 		if (OSCompareAndSwap64((UInt64)o_sv_he.he_record, (UInt64)n_sv_he.he_record, (UInt64 *) &c_segment_sv_hash_table[hash_indx].he_record) == TRUE) {
4679 			if (n_sv_he.he_ref == 0) {
4680 				os_atomic_dec(&c_segment_svp_in_hash, relaxed);
4681 			}
4682 			break;
4683 		}
4684 	}
4685 }
4686 
4687 
4688 static int
c_segment_sv_hash_insert(uint32_t data)4689 c_segment_sv_hash_insert(uint32_t data)
4690 {
4691 	int             hash_sindx;
4692 	int             misses;
4693 	struct c_sv_hash_entry o_sv_he, n_sv_he;
4694 	boolean_t       got_ref = FALSE;
4695 
4696 	if (data == 0) {
4697 		os_atomic_inc(&c_segment_svp_zero_compressions, relaxed);
4698 	} else {
4699 		os_atomic_inc(&c_segment_svp_nonzero_compressions, relaxed);
4700 	}
4701 
4702 	hash_sindx = data & C_SV_HASH_MASK;
4703 
4704 	for (misses = 0; misses < C_SV_HASH_MAX_MISS; misses++) {
4705 		o_sv_he.he_record = c_segment_sv_hash_table[hash_sindx].he_record;
4706 
4707 		while (o_sv_he.he_data == data || o_sv_he.he_ref == 0) {
4708 			n_sv_he.he_ref = o_sv_he.he_ref + 1;
4709 			n_sv_he.he_data = data;
4710 
4711 			if (OSCompareAndSwap64((UInt64)o_sv_he.he_record, (UInt64)n_sv_he.he_record, (UInt64 *) &c_segment_sv_hash_table[hash_sindx].he_record) == TRUE) {
4712 				if (n_sv_he.he_ref == 1) {
4713 					os_atomic_inc(&c_segment_svp_in_hash, relaxed);
4714 				}
4715 				got_ref = TRUE;
4716 				break;
4717 			}
4718 			o_sv_he.he_record = c_segment_sv_hash_table[hash_sindx].he_record;
4719 		}
4720 		if (got_ref == TRUE) {
4721 			break;
4722 		}
4723 		hash_sindx++;
4724 
4725 		if (hash_sindx == C_SV_HASH_SIZE) {
4726 			hash_sindx = 0;
4727 		}
4728 	}
4729 	if (got_ref == FALSE) {
4730 		return -1;
4731 	}
4732 
4733 	return hash_sindx;
4734 }
4735 
4736 
4737 #if RECORD_THE_COMPRESSED_DATA
4738 
4739 static void
c_compressed_record_data(char * src,int c_size)4740 c_compressed_record_data(char *src, int c_size)
4741 {
4742 	if ((c_compressed_record_cptr + c_size + 4) >= c_compressed_record_ebuf) {
4743 		panic("c_compressed_record_cptr >= c_compressed_record_ebuf");
4744 	}
4745 
4746 	*(int *)((void *)c_compressed_record_cptr) = c_size;
4747 
4748 	c_compressed_record_cptr += 4;
4749 
4750 	memcpy(c_compressed_record_cptr, src, c_size);
4751 	c_compressed_record_cptr += c_size;
4752 }
4753 #endif
4754 
4755 
4756 /**
4757  * Do the actual compression of the given page
4758  * @param src [IN] address in the physical aperture of the page to compress.
4759  * @param slot_ptr [OUT] fill the slot-mapping of the c_seg+slot where the page ends up being stored
4760  * @param current_chead [IN-OUT] current filling c_seg. pointer comes from the current compression thread state
4761  *          On the very first call this is going to point to NULL and this function will fill that pointer with a new
4762  *          filling c_sec if the current filling c_seg doesn't have enough space, it will be replaced in this location
4763  *          with a new filling c_seg
4764  * @param scratch_buf [IN] pointer from the current thread state, used by the compression codec
4765  * @return KERN_RESOURCE_SHORTAGE if the compressor has been exhausted
4766  */
4767 static kern_return_t
c_compress_page(char * src,c_slot_mapping_t slot_ptr,c_segment_t * current_chead,char * scratch_buf,__unused vm_compressor_options_t flags)4768 c_compress_page(
4769 	char             *src,
4770 	c_slot_mapping_t slot_ptr,
4771 	c_segment_t      *current_chead,
4772 	char             *scratch_buf,
4773 	__unused vm_compressor_options_t flags)
4774 {
4775 	int              c_size = -1;
4776 	int              c_rounded_size = 0;
4777 	int              max_csize;
4778 	bool             nearing_limits;
4779 	c_slot_t         cs;
4780 	c_segment_t      c_seg;
4781 
4782 	KERNEL_DEBUG(0xe0400000 | DBG_FUNC_START, *current_chead, 0, 0, 0, 0);
4783 retry:  /* may need to retry if the currently filling c_seg will not have enough space */
4784 	c_seg = c_seg_allocate(current_chead, &nearing_limits);
4785 	if (c_seg == NULL) {
4786 		if (nearing_limits) {
4787 			memorystatus_respond_to_compressor_exhaustion();
4788 		}
4789 		return KERN_RESOURCE_SHORTAGE;
4790 	}
4791 
4792 	/*
4793 	 * returns with c_seg lock held
4794 	 * and PAGE_REPLACEMENT_DISALLOWED(TRUE)...
4795 	 * c_nextslot has been allocated and
4796 	 * c_store.c_buffer populated
4797 	 */
4798 	assert(c_seg->c_state == C_IS_FILLING);
4799 
4800 	cs = C_SEG_SLOT_FROM_INDEX(c_seg, c_seg->c_nextslot);
4801 
4802 	C_SLOT_ASSERT_PACKABLE(slot_ptr);
4803 	cs->c_packed_ptr = C_SLOT_PACK_PTR(slot_ptr);
4804 
4805 	cs->c_offset = c_seg->c_nextoffset;
4806 
4807 	unsigned int avail_space = c_seg_bufsize - C_SEG_OFFSET_TO_BYTES((int32_t)cs->c_offset);
4808 
4809 
4810 	max_csize = avail_space;
4811 	if (max_csize > PAGE_SIZE) {
4812 		max_csize = PAGE_SIZE;
4813 	}
4814 
4815 #if CHECKSUM_THE_DATA
4816 	cs->c_hash_data = vmc_hash(src, PAGE_SIZE);
4817 #endif
4818 	boolean_t incomp_copy = FALSE; /* codec indicates it already did copy an incompressible page */
4819 	int max_csize_adj = (max_csize - 4); /* how much size we have left in this c_seg to fill. */
4820 
4821 	if (vm_compressor_algorithm() != VM_COMPRESSOR_DEFAULT_CODEC) {
4822 #if defined(__arm64__)
4823 		uint16_t ccodec = CINVALID;
4824 		uint32_t inline_popcount;
4825 		if (max_csize >= C_SEG_OFFSET_ALIGNMENT_BOUNDARY) {
4826 			vm_memtag_disable_checking();
4827 			c_size = metacompressor((const uint8_t *) src,
4828 			    (uint8_t *) &c_seg->c_store.c_buffer[cs->c_offset],
4829 			    max_csize_adj, &ccodec,
4830 			    scratch_buf, &incomp_copy, &inline_popcount);
4831 			vm_memtag_enable_checking();
4832 			assert(inline_popcount == C_SLOT_NO_POPCOUNT);
4833 
4834 #if C_SEG_OFFSET_ALIGNMENT_BOUNDARY > 4
4835 			if (c_size > max_csize_adj) {
4836 				c_size = -1;
4837 			}
4838 #endif
4839 		} else {
4840 			c_size = -1;
4841 		}
4842 		assert(ccodec == CCWK || ccodec == CCLZ4);
4843 		cs->c_codec = ccodec;
4844 #endif
4845 	} else {
4846 #if defined(__arm64__)
4847 		vm_memtag_disable_checking();
4848 		cs->c_codec = CCWK;
4849 		__unreachable_ok_push
4850 		if (PAGE_SIZE == 4096) {
4851 			c_size = WKdm_compress_4k((WK_word *)(uintptr_t)src, (WK_word *)(uintptr_t)&c_seg->c_store.c_buffer[cs->c_offset],
4852 			    (WK_word *)(uintptr_t)scratch_buf, max_csize_adj);
4853 		} else {
4854 			c_size = WKdm_compress_16k((WK_word *)(uintptr_t)src, (WK_word *)(uintptr_t)&c_seg->c_store.c_buffer[cs->c_offset],
4855 			    (WK_word *)(uintptr_t)scratch_buf, max_csize_adj);
4856 		}
4857 		__unreachable_ok_pop
4858 		vm_memtag_enable_checking();
4859 #else
4860 		vm_memtag_disable_checking();
4861 		c_size = WKdm_compress_new((const WK_word *)(uintptr_t)src, (WK_word *)(uintptr_t)&c_seg->c_store.c_buffer[cs->c_offset],
4862 		    (WK_word *)(uintptr_t)scratch_buf, max_csize_adj);
4863 		vm_memtag_enable_checking();
4864 #endif
4865 	}
4866 	/* c_size is the size written by the codec, or 0 if it's uniform 32 bit value or (-1 if there was not enough space
4867 	 * or it was incompressible) */
4868 	assertf(((c_size <= max_csize_adj) && (c_size >= -1)),
4869 	    "c_size invalid (%d, %d), cur compressions: %d", c_size, max_csize_adj, c_segment_pages_compressed);
4870 
4871 	if (c_size == -1) {
4872 		if (max_csize < PAGE_SIZE) {
4873 			c_current_seg_filled(c_seg, current_chead);
4874 			assert(*current_chead == NULL);
4875 
4876 			lck_mtx_unlock_always(&c_seg->c_lock);
4877 			/* TODO: it may be worth requiring codecs to distinguish
4878 			 * between incompressible inputs and failures due to budget exhaustion.
4879 			 * right now this assumes that if the space we had is > PAGE_SIZE, then the codec failed due to incompressible input */
4880 
4881 			PAGE_REPLACEMENT_DISALLOWED(FALSE);
4882 			goto retry;  /* previous c_seg didn't have enought space, we finalized it and can try again with a fresh c_seg */
4883 		}
4884 		c_size = PAGE_SIZE; /* tag:WK-INCOMPRESSIBLE */
4885 
4886 		if (incomp_copy == FALSE) { /* codec did not copy the incompressible input */
4887 			vm_memtag_disable_checking();
4888 			memcpy(&c_seg->c_store.c_buffer[cs->c_offset], src, c_size);
4889 			vm_memtag_enable_checking();
4890 		}
4891 
4892 		os_atomic_inc(&c_segment_noncompressible_pages, relaxed);
4893 	} else if (c_size == 0) {
4894 		{
4895 			/*
4896 			 * Special case - this is a page completely full of a single 32 bit value.
4897 			 * We store some values directly in the c_slot_mapping, if not there, the
4898 			 * 4 byte value goes in the compressor segment.
4899 			 */
4900 			int hash_index = c_segment_sv_hash_insert(*(uint32_t *) (uintptr_t) src);
4901 
4902 			if (hash_index != -1) {
4903 				slot_ptr->s_cindx = hash_index;
4904 				slot_ptr->s_cseg = C_SV_CSEG_ID;
4905 #if CONFIG_TRACK_UNMODIFIED_ANON_PAGES
4906 				slot_ptr->s_uncompressed = 0;
4907 #endif /* CONFIG_TRACK_UNMODIFIED_ANON_PAGES */
4908 
4909 				os_atomic_inc(&c_segment_svp_hash_succeeded, relaxed);
4910 #if RECORD_THE_COMPRESSED_DATA
4911 				c_compressed_record_data(src, 4);
4912 #endif
4913 				/* we didn't write anything to c_buffer and didn't end up using the slot in the c_seg at all, so skip all
4914 				 * the book-keeping of the case that we did */
4915 				goto sv_compression;
4916 			}
4917 		}
4918 		os_atomic_inc(&c_segment_svp_hash_failed, relaxed);
4919 
4920 		c_size = 4;
4921 		vm_memtag_disable_checking();
4922 		memcpy(&c_seg->c_store.c_buffer[cs->c_offset], src, c_size);
4923 		vm_memtag_enable_checking();
4924 	}
4925 
4926 #if RECORD_THE_COMPRESSED_DATA
4927 	c_compressed_record_data((char *)&c_seg->c_store.c_buffer[cs->c_offset], c_size);
4928 #endif
4929 #if CHECKSUM_THE_COMPRESSED_DATA
4930 	cs->c_hash_compressed_data = vmc_hash((char *)&c_seg->c_store.c_buffer[cs->c_offset], c_size);
4931 #endif
4932 #if POPCOUNT_THE_COMPRESSED_DATA
4933 	cs->c_pop_cdata = vmc_pop((uintptr_t) &c_seg->c_store.c_buffer[cs->c_offset], c_size);
4934 #endif
4935 
4936 	PACK_C_SIZE(cs, c_size);
4937 
4938 	c_rounded_size = C_SEG_ROUND_TO_ALIGNMENT(c_size);
4939 
4940 	c_seg->c_bytes_used += c_rounded_size;
4941 	c_seg->c_nextoffset += C_SEG_BYTES_TO_OFFSET(c_rounded_size);
4942 	c_seg->c_slots_used++;
4943 
4944 #if CONFIG_FREEZE
4945 	/* TODO: should c_segment_pages_compressed be up here too? See 88598046 for details */
4946 	os_atomic_inc(&c_segment_pages_compressed_incore, relaxed);
4947 	if (c_seg->c_has_donated_pages) {
4948 		os_atomic_inc(&c_segment_pages_compressed_incore_late_swapout, relaxed);
4949 	}
4950 #endif /* CONFIG_FREEZE */
4951 
4952 	slot_ptr->s_cindx = c_seg->c_nextslot++;
4953 	/* <csegno=0,indx=0> would mean "empty slot", so use csegno+1, see other usages of s_cseg where it's decremented */
4954 	slot_ptr->s_cseg = c_seg->c_mysegno + 1;
4955 
4956 #if CONFIG_TRACK_UNMODIFIED_ANON_PAGES
4957 	slot_ptr->s_uncompressed = 0;
4958 #endif /* CONFIG_TRACK_UNMODIFIED_ANON_PAGES */
4959 
4960 sv_compression:
4961 	/* can we say this c_seg is full? */
4962 	if (c_seg->c_nextoffset >= c_seg_off_limit || c_seg->c_nextslot >= C_SLOT_MAX_INDEX) {
4963 		/* condition 1: segment buffer is almost full, don't bother trying to fill it further.
4964 		 * condition 2: we can't have any more slots in this c_segment even if we had buffer space */
4965 		c_current_seg_filled(c_seg, current_chead);
4966 		assert(*current_chead == NULL);
4967 	}
4968 
4969 	lck_mtx_unlock_always(&c_seg->c_lock);
4970 
4971 	PAGE_REPLACEMENT_DISALLOWED(FALSE);
4972 
4973 #if RECORD_THE_COMPRESSED_DATA
4974 	if ((c_compressed_record_cptr - c_compressed_record_sbuf) >= c_seg_allocsize) {
4975 		c_compressed_record_write(c_compressed_record_sbuf, (int)(c_compressed_record_cptr - c_compressed_record_sbuf));
4976 		c_compressed_record_cptr = c_compressed_record_sbuf;
4977 	}
4978 #endif
4979 	if (c_size) {
4980 		os_atomic_add(&c_segment_compressed_bytes, c_size, relaxed);
4981 		os_atomic_add(&compressor_bytes_used, c_rounded_size, relaxed);
4982 	}
4983 	os_atomic_add(&c_segment_input_bytes, PAGE_SIZE, relaxed);
4984 
4985 	os_atomic_inc(&c_segment_pages_compressed, relaxed);
4986 #if DEVELOPMENT || DEBUG
4987 	if (!compressor_running_perf_test) {
4988 		/*
4989 		 * The perf_compressor benchmark should not be able to trigger
4990 		 * compressor thrashing jetsams.
4991 		 */
4992 		os_atomic_inc(&sample_period_compression_count, relaxed);
4993 	}
4994 #else /* DEVELOPMENT || DEBUG */
4995 	os_atomic_inc(&sample_period_compression_count, relaxed);
4996 #endif /* DEVELOPMENT || DEBUG */
4997 
4998 	if (nearing_limits) {
4999 		memorystatus_respond_to_compressor_exhaustion();
5000 	}
5001 
5002 	KERNEL_DEBUG(0xe0400000 | DBG_FUNC_END, *current_chead, c_size, c_segment_input_bytes, c_segment_compressed_bytes, 0);
5003 
5004 	return KERN_SUCCESS;
5005 }
5006 
5007 static inline void
sv_decompress(int32_t * ddst,int32_t pattern)5008 sv_decompress(int32_t *ddst, int32_t pattern)
5009 {
5010 //	assert(__builtin_constant_p(PAGE_SIZE) != 0);
5011 #if defined(__x86_64__)
5012 	memset_word(ddst, pattern, PAGE_SIZE / sizeof(int32_t));
5013 #elif defined(__arm64__)
5014 	assert((PAGE_SIZE % 128) == 0);
5015 	if (pattern == 0) {
5016 		fill32_dczva((addr64_t)ddst, PAGE_SIZE);
5017 	} else {
5018 		fill32_nt((addr64_t)ddst, PAGE_SIZE, pattern);
5019 	}
5020 #else
5021 	size_t          i;
5022 
5023 	/* Unroll the pattern fill loop 4x to encourage the
5024 	 * compiler to emit NEON stores, cf.
5025 	 * <rdar://problem/25839866> Loop autovectorization
5026 	 * anomalies.
5027 	 */
5028 	/* * We use separate loops for each PAGE_SIZE
5029 	 * to allow the autovectorizer to engage, as PAGE_SIZE
5030 	 * may not be a constant.
5031 	 */
5032 
5033 	__unreachable_ok_push
5034 	if (PAGE_SIZE == 4096) {
5035 		for (i = 0; i < (4096U / sizeof(int32_t)); i += 4) {
5036 			*ddst++ = pattern;
5037 			*ddst++ = pattern;
5038 			*ddst++ = pattern;
5039 			*ddst++ = pattern;
5040 		}
5041 	} else {
5042 		assert(PAGE_SIZE == 16384);
5043 		for (i = 0; i < (int)(16384U / sizeof(int32_t)); i += 4) {
5044 			*ddst++ = pattern;
5045 			*ddst++ = pattern;
5046 			*ddst++ = pattern;
5047 			*ddst++ = pattern;
5048 		}
5049 	}
5050 	__unreachable_ok_pop
5051 #endif
5052 }
5053 
5054 static vm_decompress_result_t
c_decompress_page(char * dst,volatile c_slot_mapping_t slot_ptr,vm_compressor_options_t flags,int * zeroslot)5055 c_decompress_page(
5056 	char            *dst,
5057 	volatile c_slot_mapping_t slot_ptr,    /* why volatile? perhaps due to changes across hibernation */
5058 	vm_compressor_options_t flags,
5059 	int             *zeroslot)
5060 {
5061 	c_slot_t        cs;
5062 	c_segment_t     c_seg;
5063 	uint32_t        c_segno;
5064 	uint16_t        c_indx;
5065 	int             c_rounded_size;
5066 	uint32_t        c_size;
5067 	vm_decompress_result_t retval = 0;
5068 	boolean_t       need_unlock = TRUE;
5069 	boolean_t       consider_defragmenting = FALSE;
5070 	boolean_t       kdp_mode = FALSE;
5071 
5072 	if (__improbable(flags & C_KDP)) {
5073 		if (not_in_kdp) {
5074 			panic("C_KDP passed to decompress page from outside of debugger context");
5075 		}
5076 
5077 		assert((flags & C_KEEP) == C_KEEP);
5078 		assert((flags & C_DONT_BLOCK) == C_DONT_BLOCK);
5079 
5080 		if ((flags & (C_DONT_BLOCK | C_KEEP)) != (C_DONT_BLOCK | C_KEEP)) {
5081 			return DECOMPRESS_NEED_BLOCK;
5082 		}
5083 
5084 		kdp_mode = TRUE;
5085 		*zeroslot = 0;
5086 	}
5087 
5088 ReTry:
5089 	if (__probable(!kdp_mode)) {
5090 		PAGE_REPLACEMENT_DISALLOWED(TRUE);
5091 	} else {
5092 		if (kdp_lck_rw_lock_is_acquired_exclusive(&c_master_lock)) {
5093 			return DECOMPRESS_NEED_BLOCK;
5094 		}
5095 	}
5096 
5097 #if HIBERNATION
5098 	/*
5099 	 * if hibernation is enabled, it indicates (via a call
5100 	 * to 'vm_decompressor_lock' that no further
5101 	 * decompressions are allowed once it reaches
5102 	 * the point of flushing all of the currently dirty
5103 	 * anonymous memory through the compressor and out
5104 	 * to disk... in this state we allow freeing of compressed
5105 	 * pages and must honor the C_DONT_BLOCK case
5106 	 */
5107 	if (__improbable(dst && decompressions_blocked == TRUE)) {
5108 		if (flags & C_DONT_BLOCK) {
5109 			if (__probable(!kdp_mode)) {
5110 				PAGE_REPLACEMENT_DISALLOWED(FALSE);
5111 			}
5112 
5113 			*zeroslot = 0;
5114 			return -2;
5115 		}
5116 		/*
5117 		 * it's safe to atomically assert and block behind the
5118 		 * lock held in shared mode because "decompressions_blocked" is
5119 		 * only set and cleared and the thread_wakeup done when the lock
5120 		 * is held exclusively
5121 		 */
5122 		assert_wait((event_t)&decompressions_blocked, THREAD_UNINT);
5123 
5124 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
5125 
5126 		thread_block(THREAD_CONTINUE_NULL);
5127 
5128 		goto ReTry;
5129 	}
5130 #endif
5131 	/* s_cseg is actually "segno+1" */
5132 	c_segno = slot_ptr->s_cseg - 1;
5133 
5134 	if (__improbable(c_segno >= c_segments_available)) {
5135 		panic("c_decompress_page: c_segno %d >= c_segments_available %d, slot_ptr(%p), slot_data(%x)",
5136 		    c_segno, c_segments_available, slot_ptr, *(int *)((void *)slot_ptr));
5137 	}
5138 
5139 	if (__improbable(c_segments_get(c_segno)->c_segno < c_segments_available)) {
5140 		panic("c_decompress_page: c_segno %d is free, slot_ptr(%p), slot_data(%x)",
5141 		    c_segno, slot_ptr, *(int *)((void *)slot_ptr));
5142 	}
5143 
5144 	c_seg = c_segments_get(c_segno)->c_seg;
5145 
5146 	if (__probable(!kdp_mode)) {
5147 		lck_mtx_lock_spin_always(&c_seg->c_lock);
5148 	} else {
5149 		if (kdp_lck_mtx_lock_spin_is_acquired(&c_seg->c_lock)) {
5150 			return DECOMPRESS_NEED_BLOCK;
5151 		}
5152 	}
5153 
5154 	assert(c_seg->c_state != C_IS_EMPTY && c_seg->c_state != C_IS_FREE);
5155 
5156 	if (dst == NULL && c_seg->c_busy_swapping) {
5157 		assert(c_seg->c_busy);
5158 
5159 		goto bypass_busy_check;
5160 	}
5161 	if (flags & C_DONT_BLOCK) {
5162 		if (c_seg->c_busy || (C_SEG_IS_ONDISK(c_seg) && dst)) {
5163 			*zeroslot = 0;
5164 
5165 			retval = DECOMPRESS_NEED_BLOCK;
5166 			goto done;
5167 		}
5168 	}
5169 	if (c_seg->c_busy) {
5170 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
5171 
5172 		c_seg_wait_on_busy(c_seg);
5173 
5174 		goto ReTry;
5175 	}
5176 bypass_busy_check:
5177 
5178 	c_indx = slot_ptr->s_cindx;
5179 
5180 	if (__improbable(c_indx >= c_seg->c_nextslot)) {
5181 		panic("c_decompress_page: c_indx %d >= c_nextslot %d, c_seg(%p), slot_ptr(%p), slot_data(%x)",
5182 		    c_indx, c_seg->c_nextslot, c_seg, slot_ptr, *(int *)((void *)slot_ptr));
5183 	}
5184 
5185 	cs = C_SEG_SLOT_FROM_INDEX(c_seg, c_indx);
5186 
5187 	c_size = UNPACK_C_SIZE(cs);
5188 
5189 
5190 	if (__improbable(c_size == 0)) { /* sanity check it's not an empty slot */
5191 		panic("c_decompress_page: c_size == 0, c_seg(%p), slot_ptr(%p), slot_data(%x)",
5192 		    c_seg, slot_ptr, *(int *)((void *)slot_ptr));
5193 	}
5194 
5195 	c_rounded_size = C_SEG_ROUND_TO_ALIGNMENT(c_size + c_slot_extra_size(cs));
5196 	/* c_rounded_size should not change after this point so that it remains consistent on all branches */
5197 
5198 	if (dst) {  /* would be NULL if we don't want the page content, from free */
5199 		uint32_t        age_of_cseg;
5200 		clock_sec_t     cur_ts_sec;
5201 		clock_nsec_t    cur_ts_nsec;
5202 
5203 		if (C_SEG_IS_ONDISK(c_seg)) {
5204 #if CONFIG_FREEZE
5205 			if (freezer_incore_cseg_acct) {
5206 				if ((c_seg->c_slots_used + c_segment_pages_compressed_incore) >= c_segment_pages_compressed_nearing_limit) {
5207 					PAGE_REPLACEMENT_DISALLOWED(FALSE);
5208 					lck_mtx_unlock_always(&c_seg->c_lock);
5209 
5210 					memorystatus_kill_on_VM_compressor_space_shortage(FALSE /* async */);
5211 
5212 					goto ReTry;
5213 				}
5214 
5215 				uint32_t incore_seg_count = c_segment_count - c_swappedout_count - c_swappedout_sparse_count;
5216 				if ((incore_seg_count + 1) >= c_segments_nearing_limit) {
5217 					PAGE_REPLACEMENT_DISALLOWED(FALSE);
5218 					lck_mtx_unlock_always(&c_seg->c_lock);
5219 
5220 					memorystatus_kill_on_VM_compressor_space_shortage(FALSE /* async */);
5221 
5222 					goto ReTry;
5223 				}
5224 			}
5225 #endif /* CONFIG_FREEZE */
5226 			assert(kdp_mode == FALSE);
5227 			retval = c_seg_swapin(c_seg, FALSE, TRUE);
5228 			assert(retval == 0);
5229 
5230 			retval = DECOMPRESS_SUCCESS_SWAPPEDIN;
5231 		}
5232 		if (c_seg->c_state == C_ON_BAD_Q) {
5233 			assert(c_seg->c_store.c_buffer == NULL);
5234 			*zeroslot = 0;
5235 
5236 			retval = DECOMPRESS_FAILED_BAD_Q;
5237 			goto done;
5238 		}
5239 
5240 #if POPCOUNT_THE_COMPRESSED_DATA
5241 		unsigned csvpop;
5242 		uintptr_t csvaddr = (uintptr_t) &c_seg->c_store.c_buffer[cs->c_offset];
5243 		if (cs->c_pop_cdata != (csvpop = vmc_pop(csvaddr, c_size))) {
5244 			panic("Compressed data popcount doesn't match original, bit distance: %d %p (phys: %p) %p %p 0x%x 0x%x 0x%x 0x%x", (csvpop - cs->c_pop_cdata), (void *)csvaddr, (void *) kvtophys(csvaddr), c_seg, cs, cs->c_offset, c_size, csvpop, cs->c_pop_cdata);
5245 		}
5246 #endif
5247 
5248 #if CHECKSUM_THE_COMPRESSED_DATA
5249 		unsigned csvhash;
5250 		if (cs->c_hash_compressed_data != (csvhash = vmc_hash((char *)&c_seg->c_store.c_buffer[cs->c_offset], c_size))) {
5251 			panic("Compressed data doesn't match original %p %p %u %u %u", c_seg, cs, c_size, cs->c_hash_compressed_data, csvhash);
5252 		}
5253 #endif
5254 		if (c_size == PAGE_SIZE) { /* tag:WK-INCOMPRESSIBLE */
5255 			/* page wasn't compressible... just copy it out */
5256 			vm_memtag_disable_checking();
5257 			memcpy(dst, &c_seg->c_store.c_buffer[cs->c_offset], PAGE_SIZE);
5258 			vm_memtag_enable_checking();
5259 		} else if (c_size == 4) {
5260 			int32_t         data;
5261 			int32_t         *dptr;
5262 
5263 			/*
5264 			 * page was populated with a single value
5265 			 * that didn't fit into our fast hash
5266 			 * so we packed it in as a single non-compressed value
5267 			 * that we need to populate the page with
5268 			 */
5269 			dptr = (int32_t *)(uintptr_t)dst;
5270 			data = *(int32_t *)(&c_seg->c_store.c_buffer[cs->c_offset]);
5271 			vm_memtag_disable_checking();
5272 			sv_decompress(dptr, data);
5273 			vm_memtag_enable_checking();
5274 		} else {  /* normal segment decompress */
5275 			uint32_t        my_cpu_no;
5276 			char            *scratch_buf;
5277 
5278 			my_cpu_no = cpu_number();
5279 
5280 			assert(my_cpu_no < compressor_cpus);
5281 
5282 			if (__probable(!kdp_mode)) {
5283 				/*
5284 				 * we're behind the c_seg lock held in spin mode
5285 				 * which means pre-emption is disabled... therefore
5286 				 * the following sequence is atomic and safe
5287 				 */
5288 				scratch_buf = &compressor_scratch_bufs[my_cpu_no * vm_compressor_get_decode_scratch_size()];
5289 			} else if (flags & C_KDP_MULTICPU) {
5290 				assert(vm_compressor_kdp_state.kc_scratch_bufs != NULL);
5291 				scratch_buf = &vm_compressor_kdp_state.kc_scratch_bufs[my_cpu_no * vm_compressor_get_decode_scratch_size()];
5292 			} else {
5293 				scratch_buf = vm_compressor_kdp_state.kc_panic_scratch_buf;
5294 			}
5295 
5296 			if (vm_compressor_algorithm() != VM_COMPRESSOR_DEFAULT_CODEC) {
5297 #if defined(__arm64__)
5298 				uint16_t c_codec = cs->c_codec;
5299 				uint32_t inline_popcount;
5300 				vm_memtag_disable_checking();
5301 				if (!metadecompressor((const uint8_t *) &c_seg->c_store.c_buffer[cs->c_offset],
5302 				    (uint8_t *)dst, c_size, c_codec, (void *)scratch_buf, &inline_popcount)) {
5303 					vm_memtag_enable_checking();
5304 					retval = DECOMPRESS_FAILED_ALGO_ERROR;
5305 				} else {
5306 					vm_memtag_enable_checking();
5307 					assert(inline_popcount == C_SLOT_NO_POPCOUNT);
5308 				}
5309 #endif
5310 			} else {  /* algorithm == VM_COMPRESSOR_DEFAULT_CODEC */
5311 				vm_memtag_disable_checking();
5312 #if defined(__arm64__)
5313 				__unreachable_ok_push
5314 				if (PAGE_SIZE == 4096) {
5315 					WKdm_decompress_4k((WK_word *)(uintptr_t)&c_seg->c_store.c_buffer[cs->c_offset],
5316 					    (WK_word *)(uintptr_t)dst, (WK_word *)(uintptr_t)scratch_buf, c_size);
5317 				} else {
5318 					WKdm_decompress_16k((WK_word *)(uintptr_t)&c_seg->c_store.c_buffer[cs->c_offset],
5319 					    (WK_word *)(uintptr_t)dst, (WK_word *)(uintptr_t)scratch_buf, c_size);
5320 				}
5321 				__unreachable_ok_pop
5322 #else
5323 				WKdm_decompress_new((WK_word *)(uintptr_t)&c_seg->c_store.c_buffer[cs->c_offset],
5324 				    (WK_word *)(uintptr_t)dst, (WK_word *)(uintptr_t)scratch_buf, c_size);
5325 #endif
5326 				vm_memtag_enable_checking();
5327 			}
5328 		} /* normal segment decompress */
5329 
5330 #if CHECKSUM_THE_DATA
5331 		if (cs->c_hash_data != vmc_hash(dst, PAGE_SIZE)) {
5332 #if defined(__arm64__)
5333 			int32_t *dinput = &c_seg->c_store.c_buffer[cs->c_offset];
5334 			panic("decompressed data doesn't match original cs: %p, hash: 0x%x, offset: %d, c_size: %d, c_rounded_size: %d, codec: %d, header: 0x%x 0x%x 0x%x", cs, cs->c_hash_data, cs->c_offset, c_size, c_rounded_size, cs->c_codec, *dinput, *(dinput + 1), *(dinput + 2));
5335 #else /* defined(__arm64__) */
5336 			panic("decompressed data doesn't match original cs: %p, hash: %d, offset: 0x%x, c_size: %d", cs, cs->c_hash_data, cs->c_offset, c_size);
5337 #endif /* defined(__arm64__) */
5338 		}
5339 #endif /* CHECKSUM_THE_DATA */
5340 		if (c_seg->c_swappedin_ts == 0 && !kdp_mode) {
5341 			clock_get_system_nanotime(&cur_ts_sec, &cur_ts_nsec);
5342 
5343 			age_of_cseg = (uint32_t)cur_ts_sec - c_seg->c_creation_ts;
5344 			if (age_of_cseg < DECOMPRESSION_SAMPLE_MAX_AGE) {
5345 				os_atomic_inc(&age_of_decompressions_during_sample_period[age_of_cseg], relaxed);
5346 			} else {
5347 				os_atomic_inc(&overage_decompressions_during_sample_period, relaxed);
5348 			}
5349 
5350 			os_atomic_inc(&sample_period_decompression_count, relaxed);
5351 		}
5352 
5353 
5354 #if TRACK_C_SEGMENT_UTILIZATION
5355 		if (c_seg->c_swappedin) {
5356 			c_seg->c_decompressions_since_swapin++;
5357 		}
5358 #endif /* TRACK_C_SEGMENT_UTILIZATION */
5359 	} /* dst */
5360 	else {
5361 #if CONFIG_FREEZE
5362 		/*
5363 		 * We are freeing an uncompressed page from this c_seg and so balance the ledgers.
5364 		 */
5365 		if (C_SEG_IS_ONDISK(c_seg)) {
5366 			/*
5367 			 * The compression sweep feature will push out anonymous pages to disk
5368 			 * without going through the freezer path and so those c_segs, while
5369 			 * swapped out, won't have an owner.
5370 			 */
5371 			if (c_seg->c_task_owner) {
5372 				task_update_frozen_to_swap_acct(c_seg->c_task_owner, PAGE_SIZE_64, DEBIT_FROM_SWAP);
5373 			}
5374 
5375 			/*
5376 			 * We are freeing a page in swap without swapping it in. We bump the in-core
5377 			 * count here to simulate a swapin of a page so that we can accurately
5378 			 * decrement it below.
5379 			 */
5380 			os_atomic_inc(&c_segment_pages_compressed_incore, relaxed);
5381 			if (c_seg->c_has_donated_pages) {
5382 				os_atomic_inc(&c_segment_pages_compressed_incore_late_swapout, relaxed);
5383 			}
5384 		} else if (c_seg->c_state == C_ON_BAD_Q) {
5385 			assert(c_seg->c_store.c_buffer == NULL);
5386 			*zeroslot = 0;
5387 
5388 			retval = DECOMPRESS_FAILED_BAD_Q_FREEZE;
5389 			goto done; /* this is intended to avoid the decrement of c_segment_pages_compressed_incore below */
5390 		}
5391 #endif /* CONFIG_FREEZE */
5392 	}
5393 
5394 	if (flags & C_KEEP) {
5395 		*zeroslot = 0;
5396 		goto done;
5397 	}
5398 
5399 
5400 	/* now perform needed bookkeeping for the removal of the slot from the segment */
5401 	assert(kdp_mode == FALSE);
5402 
5403 	c_seg->c_bytes_unused += c_rounded_size;
5404 	c_seg->c_bytes_used -= c_rounded_size;
5405 
5406 	assert(c_seg->c_slots_used);
5407 	c_seg->c_slots_used--;
5408 	if (dst && c_seg->c_swappedin) {
5409 		task_t task = current_task();
5410 		if (task) {
5411 			ledger_credit(task->ledger, task_ledgers.swapins, PAGE_SIZE);
5412 		}
5413 	}
5414 
5415 	PACK_C_SIZE(cs, 0); /* mark slot as empty */
5416 
5417 	if (c_indx < c_seg->c_firstemptyslot) {
5418 		c_seg->c_firstemptyslot = c_indx;
5419 	}
5420 
5421 	os_atomic_dec(&c_segment_pages_compressed, relaxed);
5422 #if CONFIG_FREEZE
5423 	os_atomic_dec(&c_segment_pages_compressed_incore, relaxed);
5424 	assertf(c_segment_pages_compressed_incore >= 0, "-ve incore count %p 0x%x", c_seg, c_segment_pages_compressed_incore);
5425 	if (c_seg->c_has_donated_pages) {
5426 		os_atomic_dec(&c_segment_pages_compressed_incore_late_swapout, relaxed);
5427 		assertf(c_segment_pages_compressed_incore_late_swapout >= 0, "-ve lateswapout count %p 0x%x", c_seg, c_segment_pages_compressed_incore_late_swapout);
5428 	}
5429 #endif /* CONFIG_FREEZE */
5430 
5431 	if (c_seg->c_state != C_ON_BAD_Q && !(C_SEG_IS_ONDISK(c_seg))) {
5432 		/*
5433 		 * C_SEG_IS_ONDISK == TRUE can occur when we're doing a
5434 		 * free of a compressed page (i.e. dst == NULL)
5435 		 */
5436 		os_atomic_sub(&compressor_bytes_used, c_rounded_size, relaxed);
5437 	}
5438 	if (c_seg->c_busy_swapping) {
5439 		/*
5440 		 * bypass case for c_busy_swapping...
5441 		 * let the swapin/swapout paths deal with putting
5442 		 * the c_seg on the minor compaction queue if needed
5443 		 */
5444 		assert(c_seg->c_busy);
5445 		goto done;
5446 	}
5447 	assert(!c_seg->c_busy);
5448 
5449 	if (c_seg->c_state != C_IS_FILLING) {
5450 		/* did we just remove the last slot from the segment? */
5451 		if (c_seg->c_bytes_used == 0) {
5452 			if (!(C_SEG_IS_ONDISK(c_seg))) {
5453 				/* it was compressed resident in memory */
5454 				int     pages_populated;
5455 
5456 				pages_populated = (round_page_32(C_SEG_OFFSET_TO_BYTES(c_seg->c_populated_offset))) / PAGE_SIZE;
5457 				c_seg->c_populated_offset = C_SEG_BYTES_TO_OFFSET(0);
5458 
5459 				if (pages_populated) {
5460 					assert(c_seg->c_state != C_ON_BAD_Q);
5461 					assert(c_seg->c_store.c_buffer != NULL);
5462 
5463 					C_SEG_BUSY(c_seg);
5464 					lck_mtx_unlock_always(&c_seg->c_lock);
5465 
5466 					kernel_memory_depopulate(
5467 						(vm_offset_t) c_seg->c_store.c_buffer,
5468 						ptoa(pages_populated),
5469 						KMA_COMPRESSOR, VM_KERN_MEMORY_COMPRESSOR);
5470 
5471 					lck_mtx_lock_spin_always(&c_seg->c_lock);
5472 					C_SEG_WAKEUP_DONE(c_seg);
5473 				}
5474 				/* minor compaction will free it */
5475 				if (!c_seg->c_on_minorcompact_q && c_seg->c_state != C_ON_SWAPIO_Q) {
5476 					if (c_seg->c_state == C_ON_SWAPOUT_Q) {
5477 						/* If we're on the swapout q, we want to get out of it since there's no reason to swapout
5478 						 * anymore, so put on AGE Q in the meantime until minor compact */
5479 						bool clear_busy = false;
5480 						if (!lck_mtx_try_lock_spin_always(c_list_lock)) {
5481 							C_SEG_BUSY(c_seg);
5482 
5483 							lck_mtx_unlock_always(&c_seg->c_lock);
5484 							lck_mtx_lock_spin_always(c_list_lock);
5485 							lck_mtx_lock_spin_always(&c_seg->c_lock);
5486 							clear_busy = true;
5487 						}
5488 						c_seg_switch_state(c_seg, C_ON_AGE_Q, FALSE);
5489 						if (clear_busy) {
5490 							C_SEG_WAKEUP_DONE(c_seg);
5491 							clear_busy = false;
5492 						}
5493 						lck_mtx_unlock_always(c_list_lock);
5494 					}
5495 					c_seg_need_delayed_compaction(c_seg, FALSE);
5496 				}
5497 			} else { /* C_SEG_IS_ONDISK(c_seg) */
5498 				/* it's empty and on-disk, make sure it's marked as sparse */
5499 				if (c_seg->c_state != C_ON_SWAPPEDOUTSPARSE_Q) {
5500 					c_seg_move_to_sparse_list(c_seg);
5501 					consider_defragmenting = TRUE;
5502 				}
5503 			}
5504 		} else if (c_seg->c_on_minorcompact_q) {
5505 			assert(c_seg->c_state != C_ON_BAD_Q);
5506 			assert(!C_SEG_IS_ON_DISK_OR_SOQ(c_seg));
5507 
5508 			if (C_SEG_SHOULD_MINORCOMPACT_NOW(c_seg)) {
5509 				c_seg_try_minor_compaction_and_unlock(c_seg);
5510 				need_unlock = FALSE;
5511 			}
5512 		} else if (!(C_SEG_IS_ONDISK(c_seg))) {
5513 			if (c_seg->c_state != C_ON_BAD_Q && c_seg->c_state != C_ON_SWAPOUT_Q && c_seg->c_state != C_ON_SWAPIO_Q &&
5514 			    C_SEG_UNUSED_BYTES(c_seg) >= PAGE_SIZE) {
5515 				c_seg_need_delayed_compaction(c_seg, FALSE);
5516 			}
5517 		} else if (c_seg->c_state != C_ON_SWAPPEDOUTSPARSE_Q && C_SEG_ONDISK_IS_SPARSE(c_seg)) {
5518 			c_seg_move_to_sparse_list(c_seg);
5519 			consider_defragmenting = TRUE;
5520 		}
5521 	} /* c_state != C_IS_FILLING */
5522 done:
5523 	if (__improbable(kdp_mode)) {
5524 		return retval;
5525 	}
5526 
5527 	if (need_unlock == TRUE) {
5528 		lck_mtx_unlock_always(&c_seg->c_lock);
5529 	}
5530 
5531 	PAGE_REPLACEMENT_DISALLOWED(FALSE);
5532 
5533 	if (consider_defragmenting == TRUE) {
5534 		vm_swap_consider_defragmenting(VM_SWAP_FLAGS_NONE);
5535 	}
5536 
5537 #if !XNU_TARGET_OS_OSX
5538 	/*
5539 	 * Decompressions will generate fragmentation in the compressor pool
5540 	 * over time. Consider waking the compactor thread if any of the
5541 	 * fragmentation thresholds have been crossed as a result of this
5542 	 * decompression.
5543 	 */
5544 	vm_consider_waking_compactor_swapper();
5545 #endif /* !XNU_TARGET_OS_OSX */
5546 
5547 	return retval;
5548 }
5549 
5550 
5551 inline bool
vm_compressor_is_slot_compressed(int * slot)5552 vm_compressor_is_slot_compressed(int *slot)
5553 {
5554 #if !CONFIG_TRACK_UNMODIFIED_ANON_PAGES
5555 #pragma unused(slot)
5556 	return true;
5557 #else /* !CONFIG_TRACK_UNMODIFIED_ANON_PAGES*/
5558 	c_slot_mapping_t slot_ptr = (c_slot_mapping_t)slot;
5559 	return !slot_ptr->s_uncompressed;
5560 #endif /* !CONFIG_TRACK_UNMODIFIED_ANON_PAGES*/
5561 }
5562 
5563 vm_decompress_result_t
vm_compressor_get(ppnum_t pn,int * slot,vm_compressor_options_t flags)5564 vm_compressor_get(ppnum_t pn, int *slot, vm_compressor_options_t flags)
5565 {
5566 	c_slot_mapping_t  slot_ptr;
5567 	char    *dst;
5568 	int     zeroslot = 1;
5569 	vm_decompress_result_t retval;
5570 
5571 #if CONFIG_TRACK_UNMODIFIED_ANON_PAGES
5572 	if (flags & C_PAGE_UNMODIFIED) {
5573 		int iretval = vm_uncompressed_get(pn, slot, flags | C_KEEP);
5574 		if (iretval == 0) {
5575 			os_atomic_inc(&compressor_ro_uncompressed_get, relaxed);
5576 			return DECOMPRESS_SUCCESS;
5577 		}
5578 
5579 		return DECOMPRESS_FAILED_UNMODIFIED;
5580 	}
5581 #endif /* CONFIG_TRACK_UNMODIFIED_ANON_PAGES */
5582 
5583 	/* get address in physical aperture of this page for fill into */
5584 	dst = pmap_map_compressor_page(pn);
5585 	slot_ptr = (c_slot_mapping_t)slot;
5586 
5587 	assert(dst != NULL);
5588 
5589 	if (slot_ptr->s_cseg == C_SV_CSEG_ID) {
5590 		int32_t         data;
5591 		int32_t         *dptr;
5592 
5593 		/*
5594 		 * page was populated with a single value
5595 		 * that found a home in our hash table
5596 		 * grab that value from the hash and populate the page
5597 		 * that we need to populate the page with
5598 		 */
5599 		dptr = (int32_t *)(uintptr_t)dst;
5600 		data = c_segment_sv_hash_table[slot_ptr->s_cindx].he_data;
5601 		sv_decompress(dptr, data);
5602 
5603 		if (!(flags & C_KEEP)) {
5604 			c_segment_sv_hash_drop_ref(slot_ptr->s_cindx);
5605 
5606 			os_atomic_dec(&c_segment_pages_compressed, relaxed);
5607 			*slot = 0;
5608 		}
5609 		if (data) {
5610 			os_atomic_inc(&c_segment_svp_nonzero_decompressions, relaxed);
5611 		} else {
5612 			os_atomic_inc(&c_segment_svp_zero_decompressions, relaxed);
5613 		}
5614 
5615 		pmap_unmap_compressor_page(pn, dst);
5616 		return DECOMPRESS_SUCCESS;
5617 	}
5618 	retval = c_decompress_page(dst, slot_ptr, flags, &zeroslot);
5619 
5620 	/*
5621 	 * zeroslot will be set to 0 by c_decompress_page if (flags & C_KEEP)
5622 	 * or (flags & C_DONT_BLOCK) and we found 'c_busy' or 'C_SEG_IS_ONDISK' to be TRUE
5623 	 */
5624 	if (zeroslot) {
5625 		*slot = 0;
5626 	}
5627 
5628 	pmap_unmap_compressor_page(pn, dst);
5629 
5630 	/*
5631 	 * returns 0 if we successfully decompressed a page from a segment already in memory
5632 	 * returns 1 if we had to first swap in the segment, before successfully decompressing the page
5633 	 * returns -1 if we encountered an error swapping in the segment - decompression failed
5634 	 * returns -2 if (flags & C_DONT_BLOCK) and we found 'c_busy' or 'C_SEG_IS_ONDISK' to be true
5635 	 */
5636 	return retval;
5637 }
5638 
5639 vm_decompress_result_t
vm_compressor_free(int * slot,vm_compressor_options_t flags)5640 vm_compressor_free(int *slot, vm_compressor_options_t flags)
5641 {
5642 	bool slot_is_compressed = vm_compressor_is_slot_compressed(slot);
5643 
5644 	if (slot_is_compressed) {
5645 		c_slot_mapping_t  slot_ptr;
5646 		int     zeroslot = 1;
5647 		vm_decompress_result_t retval = DECOMPRESS_SUCCESS;
5648 
5649 		assert(flags == 0 || flags == C_DONT_BLOCK);
5650 
5651 		slot_ptr = (c_slot_mapping_t)slot;
5652 
5653 		if (slot_ptr->s_cseg == C_SV_CSEG_ID) {
5654 			c_segment_sv_hash_drop_ref(slot_ptr->s_cindx);
5655 			os_atomic_dec(&c_segment_pages_compressed, relaxed);
5656 
5657 			*slot = 0;
5658 			return 0;
5659 		}
5660 
5661 		retval = c_decompress_page(NULL, slot_ptr, flags, &zeroslot);
5662 		/*
5663 		 * returns 0 if we successfully freed the specified compressed page
5664 		 * returns -1 if we encountered an error swapping in the segment - decompression failed
5665 		 * returns -2 if (flags & C_DONT_BLOCK) and we found 'c_busy' set
5666 		 */
5667 
5668 		if (retval == DECOMPRESS_SUCCESS) {
5669 			*slot = 0;
5670 		}
5671 
5672 		return retval;
5673 	}
5674 #if CONFIG_TRACK_UNMODIFIED_ANON_PAGES
5675 	else {
5676 		if ((flags & C_PAGE_UNMODIFIED) == 0) {
5677 			/* moving from uncompressed state to compressed. Free it.*/
5678 			vm_uncompressed_free(slot, 0);
5679 			assert(*slot == 0);
5680 		}
5681 	}
5682 #endif /* CONFIG_TRACK_UNMODIFIED_ANON_PAGES */
5683 	return KERN_SUCCESS;
5684 }
5685 
5686 kern_return_t
vm_compressor_put(ppnum_t pn,int * slot,void ** current_chead,char * scratch_buf,vm_compressor_options_t flags)5687 vm_compressor_put(ppnum_t pn, int *slot, void  **current_chead, char *scratch_buf, vm_compressor_options_t flags)
5688 {
5689 	char *src;
5690 	kern_return_t kr;
5691 
5692 #if CONFIG_TRACK_UNMODIFIED_ANON_PAGES
5693 	if (flags & C_PAGE_UNMODIFIED) {
5694 		if (*slot) {
5695 			os_atomic_inc(&compressor_ro_uncompressed_skip_returned, relaxed);
5696 			return KERN_SUCCESS;
5697 		} else {
5698 			kr = vm_uncompressed_put(pn, slot);
5699 			if (kr == KERN_SUCCESS) {
5700 				os_atomic_inc(&compressor_ro_uncompressed_put, relaxed);
5701 				return kr;
5702 			}
5703 		}
5704 	}
5705 #endif /* CONFIG_TRACK_UNMODIFIED_ANON_PAGES */
5706 
5707 	/* get the address of the page in the physical apperture in the kernel task virtual memory */
5708 	src = pmap_map_compressor_page(pn);
5709 	assert(src != NULL);
5710 
5711 	kr = c_compress_page(src, (c_slot_mapping_t)slot, (c_segment_t *)current_chead, scratch_buf, flags);
5712 	pmap_unmap_compressor_page(pn, src);
5713 
5714 	return kr;
5715 }
5716 
5717 void
vm_compressor_transfer(int * dst_slot_p,int * src_slot_p)5718 vm_compressor_transfer(
5719 	int     *dst_slot_p,
5720 	int     *src_slot_p)
5721 {
5722 	c_slot_mapping_t        dst_slot, src_slot;
5723 	c_segment_t             c_seg;
5724 	uint16_t                c_indx;
5725 	c_slot_t                cs;
5726 
5727 	src_slot = (c_slot_mapping_t) src_slot_p;
5728 
5729 	if (src_slot->s_cseg == C_SV_CSEG_ID || !vm_compressor_is_slot_compressed(src_slot_p)) {
5730 		*dst_slot_p = *src_slot_p;
5731 		*src_slot_p = 0;
5732 		return;
5733 	}
5734 	dst_slot = (c_slot_mapping_t) dst_slot_p;
5735 Retry:
5736 	PAGE_REPLACEMENT_DISALLOWED(TRUE);
5737 	/* get segment for src_slot */
5738 	c_seg = c_segments_get(src_slot->s_cseg - 1)->c_seg;
5739 	/* lock segment */
5740 	lck_mtx_lock_spin_always(&c_seg->c_lock);
5741 	/* wait if it's busy */
5742 	if (c_seg->c_busy && !c_seg->c_busy_swapping) {
5743 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
5744 		c_seg_wait_on_busy(c_seg);
5745 		goto Retry;
5746 	}
5747 	/* find the c_slot */
5748 	c_indx = src_slot->s_cindx;
5749 	cs = C_SEG_SLOT_FROM_INDEX(c_seg, c_indx);
5750 	/* point the c_slot back to dst_slot instead of src_slot */
5751 	C_SLOT_ASSERT_PACKABLE(dst_slot);
5752 	cs->c_packed_ptr = C_SLOT_PACK_PTR(dst_slot);
5753 	/* transfer */
5754 	*dst_slot_p = *src_slot_p;
5755 	*src_slot_p = 0;
5756 	lck_mtx_unlock_always(&c_seg->c_lock);
5757 	PAGE_REPLACEMENT_DISALLOWED(FALSE);
5758 }
5759 
5760 #if defined(__arm64__)
5761 extern uint64_t vm_swapfile_last_failed_to_create_ts;
5762 __attribute__((noreturn))
5763 void
vm_panic_hibernate_write_image_failed(int err,uint64_t file_size_min,uint64_t file_size_max,uint64_t file_size)5764 vm_panic_hibernate_write_image_failed(
5765 	int err,
5766 	uint64_t file_size_min,
5767 	uint64_t file_size_max,
5768 	uint64_t file_size)
5769 {
5770 	panic("hibernate_write_image encountered error 0x%x - %u, %u, %d, %d, %d, %d, %d, %d, %d, %d, %llu, %d, %d, %d, %llu, %llu, %llu\n",
5771 	    err,
5772 	    VM_PAGE_COMPRESSOR_COUNT, vm_page_wire_count,
5773 	    c_age_count, c_major_count, c_minor_count, (c_early_swapout_count + c_regular_swapout_count + c_late_swapout_count), c_swappedout_sparse_count,
5774 	    vm_num_swap_files, vm_num_pinned_swap_files, vm_swappin_enabled, vm_swap_put_failures,
5775 	    (vm_swapfile_last_failed_to_create_ts ? 1:0), hibernate_no_swapspace, hibernate_flush_timed_out,
5776 	    file_size_min, file_size_max, file_size);
5777 }
5778 #endif /*(__arm64__)*/
5779 
5780 #if CONFIG_FREEZE
5781 
5782 int     freezer_finished_filling = 0;
5783 
5784 void
vm_compressor_finished_filling(void ** current_chead)5785 vm_compressor_finished_filling(
5786 	void    **current_chead)
5787 {
5788 	c_segment_t     c_seg;
5789 
5790 	if ((c_seg = *(c_segment_t *)current_chead) == NULL) {
5791 		return;
5792 	}
5793 
5794 	assert(c_seg->c_state == C_IS_FILLING);
5795 
5796 	lck_mtx_lock_spin_always(&c_seg->c_lock);
5797 
5798 	c_current_seg_filled(c_seg, (c_segment_t *)current_chead);
5799 
5800 	lck_mtx_unlock_always(&c_seg->c_lock);
5801 
5802 	freezer_finished_filling++;
5803 }
5804 
5805 
5806 /*
5807  * This routine is used to transfer the compressed chunks from
5808  * the c_seg/cindx pointed to by slot_p into a new c_seg headed
5809  * by the current_chead and a new cindx within that c_seg.
5810  *
5811  * Currently, this routine is only used by the "freezer backed by
5812  * compressor with swap" mode to create a series of c_segs that
5813  * only contain compressed data belonging to one task. So, we
5814  * move a task's previously compressed data into a set of new
5815  * c_segs which will also hold the task's yet to be compressed data.
5816  */
5817 
5818 kern_return_t
vm_compressor_relocate(void ** current_chead,int * slot_p)5819 vm_compressor_relocate(
5820 	void            **current_chead,
5821 	int             *slot_p)
5822 {
5823 	c_slot_mapping_t        slot_ptr;
5824 	c_slot_mapping_t        src_slot;
5825 	uint32_t                c_rounded_size;
5826 	uint32_t                c_size;
5827 	uint16_t                dst_slot;
5828 	c_slot_t                c_dst;
5829 	c_slot_t                c_src;
5830 	uint16_t                c_indx;
5831 	c_segment_t             c_seg_dst = NULL;
5832 	c_segment_t             c_seg_src = NULL;
5833 	kern_return_t           kr = KERN_SUCCESS;
5834 	bool                    nearing_limits;
5835 
5836 
5837 	src_slot = (c_slot_mapping_t) slot_p;
5838 
5839 	if (src_slot->s_cseg == C_SV_CSEG_ID) {
5840 		/*
5841 		 * no need to relocate... this is a page full of a single
5842 		 * value which is hashed to a single entry not contained
5843 		 * in a c_segment_t
5844 		 */
5845 		return kr;
5846 	}
5847 
5848 	if (vm_compressor_is_slot_compressed((int *)src_slot) == false) {
5849 		/*
5850 		 * Unmodified anonymous pages are sitting uncompressed on disk.
5851 		 * So don't pull them back in again.
5852 		 */
5853 		return kr;
5854 	}
5855 
5856 Relookup_dst:
5857 	c_seg_dst = c_seg_allocate((c_segment_t *)current_chead, &nearing_limits);
5858 	/*
5859 	 * returns with c_seg lock held
5860 	 * and PAGE_REPLACEMENT_DISALLOWED(TRUE)...
5861 	 * c_nextslot has been allocated and
5862 	 * c_store.c_buffer populated
5863 	 */
5864 	if (c_seg_dst == NULL) {
5865 		/*
5866 		 * Out of compression segments?
5867 		 */
5868 		if (nearing_limits) {
5869 			memorystatus_respond_to_compressor_exhaustion();
5870 		}
5871 		kr = KERN_RESOURCE_SHORTAGE;
5872 		goto out;
5873 	}
5874 
5875 	assert(c_seg_dst->c_busy == 0);
5876 
5877 	C_SEG_BUSY(c_seg_dst);
5878 
5879 	dst_slot = c_seg_dst->c_nextslot;
5880 
5881 	lck_mtx_unlock_always(&c_seg_dst->c_lock);
5882 	if (nearing_limits) {
5883 		memorystatus_respond_to_compressor_exhaustion();
5884 	}
5885 
5886 Relookup_src:
5887 	c_seg_src = c_segments_get(src_slot->s_cseg - 1)->c_seg;
5888 
5889 	assert(c_seg_dst != c_seg_src);
5890 
5891 	lck_mtx_lock_spin_always(&c_seg_src->c_lock);
5892 
5893 	if (C_SEG_IS_ON_DISK_OR_SOQ(c_seg_src) ||
5894 	    c_seg_src->c_state == C_IS_FILLING) {
5895 		/*
5896 		 * Skip this page if :-
5897 		 * a) the src c_seg is already on-disk (or on its way there)
5898 		 *    A "thaw" can mark a process as eligible for
5899 		 * another freeze cycle without bringing any of
5900 		 * its swapped out c_segs back from disk (because
5901 		 * that is done on-demand).
5902 		 *    Or, this page may be mapped elsewhere in the task's map,
5903 		 * and we may have marked it for swap already.
5904 		 *
5905 		 * b) Or, the src c_seg is being filled by the compressor
5906 		 * thread. We don't want the added latency of waiting for
5907 		 * this c_seg in the freeze path and so we skip it.
5908 		 */
5909 
5910 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
5911 
5912 		lck_mtx_unlock_always(&c_seg_src->c_lock);
5913 
5914 		c_seg_src = NULL;
5915 
5916 		goto out;
5917 	}
5918 
5919 	if (c_seg_src->c_busy) {
5920 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
5921 		c_seg_wait_on_busy(c_seg_src);
5922 
5923 		c_seg_src = NULL;
5924 
5925 		PAGE_REPLACEMENT_DISALLOWED(TRUE);
5926 
5927 		goto Relookup_src;
5928 	}
5929 
5930 	C_SEG_BUSY(c_seg_src);
5931 
5932 	lck_mtx_unlock_always(&c_seg_src->c_lock);
5933 
5934 	/* find the c_slot */
5935 	c_indx = src_slot->s_cindx;
5936 
5937 	c_src = C_SEG_SLOT_FROM_INDEX(c_seg_src, c_indx);
5938 
5939 	c_size = UNPACK_C_SIZE(c_src);
5940 
5941 	assert(c_size);
5942 	int combined_size = c_size + c_slot_extra_size(c_src);
5943 
5944 	if (combined_size > (uint32_t)(c_seg_bufsize - C_SEG_OFFSET_TO_BYTES((int32_t)c_seg_dst->c_nextoffset))) {
5945 		/*
5946 		 * This segment is full. We need a new one.
5947 		 */
5948 
5949 		lck_mtx_lock_spin_always(&c_seg_src->c_lock);
5950 		C_SEG_WAKEUP_DONE(c_seg_src);
5951 		lck_mtx_unlock_always(&c_seg_src->c_lock);
5952 
5953 		c_seg_src = NULL;
5954 
5955 		lck_mtx_lock_spin_always(&c_seg_dst->c_lock);
5956 
5957 		assert(c_seg_dst->c_busy);
5958 		assert(c_seg_dst->c_state == C_IS_FILLING);
5959 		assert(!c_seg_dst->c_on_minorcompact_q);
5960 
5961 		c_current_seg_filled(c_seg_dst, (c_segment_t *)current_chead);
5962 		assert(*current_chead == NULL);
5963 
5964 		C_SEG_WAKEUP_DONE(c_seg_dst);
5965 
5966 		lck_mtx_unlock_always(&c_seg_dst->c_lock);
5967 
5968 		c_seg_dst = NULL;
5969 
5970 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
5971 
5972 		goto Relookup_dst;
5973 	}
5974 
5975 	c_dst = C_SEG_SLOT_FROM_INDEX(c_seg_dst, c_seg_dst->c_nextslot);
5976 
5977 	memcpy(&c_seg_dst->c_store.c_buffer[c_seg_dst->c_nextoffset], &c_seg_src->c_store.c_buffer[c_src->c_offset], combined_size);
5978 	PAGE_REPLACEMENT_DISALLOWED(FALSE);
5979 	/*
5980 	 * Is platform alignment actually necessary since wkdm aligns its output?
5981 	 */
5982 	c_rounded_size = C_SEG_ROUND_TO_ALIGNMENT(combined_size);
5983 
5984 	cslot_copy(c_dst, c_src);
5985 	c_dst->c_offset = c_seg_dst->c_nextoffset;
5986 
5987 	if (c_seg_dst->c_firstemptyslot == c_seg_dst->c_nextslot) {
5988 		c_seg_dst->c_firstemptyslot++;
5989 	}
5990 
5991 	c_seg_dst->c_slots_used++;
5992 	c_seg_dst->c_nextslot++;
5993 	c_seg_dst->c_bytes_used += c_rounded_size;
5994 	c_seg_dst->c_nextoffset += C_SEG_BYTES_TO_OFFSET(c_rounded_size);
5995 
5996 
5997 	PACK_C_SIZE(c_src, 0);
5998 
5999 	c_seg_src->c_bytes_used -= c_rounded_size;
6000 	c_seg_src->c_bytes_unused += c_rounded_size;
6001 
6002 	assert(c_seg_src->c_slots_used);
6003 	c_seg_src->c_slots_used--;
6004 
6005 	if (!c_seg_src->c_swappedin) {
6006 		/* Pessimistically lose swappedin status when non-swappedin pages are added. */
6007 		c_seg_dst->c_swappedin = false;
6008 	}
6009 
6010 	if (c_indx < c_seg_src->c_firstemptyslot) {
6011 		c_seg_src->c_firstemptyslot = c_indx;
6012 	}
6013 
6014 	c_dst = C_SEG_SLOT_FROM_INDEX(c_seg_dst, dst_slot);
6015 
6016 	PAGE_REPLACEMENT_ALLOWED(TRUE);
6017 	slot_ptr = C_SLOT_UNPACK_PTR(c_dst);
6018 	/* <csegno=0,indx=0> would mean "empty slot", so use csegno+1 */
6019 	slot_ptr->s_cseg = c_seg_dst->c_mysegno + 1;
6020 	slot_ptr->s_cindx = dst_slot;
6021 
6022 	PAGE_REPLACEMENT_ALLOWED(FALSE);
6023 
6024 out:
6025 	if (c_seg_src) {
6026 		lck_mtx_lock_spin_always(&c_seg_src->c_lock);
6027 
6028 		C_SEG_WAKEUP_DONE(c_seg_src);
6029 
6030 		if (c_seg_src->c_bytes_used == 0 && c_seg_src->c_state != C_IS_FILLING) {
6031 			if (!c_seg_src->c_on_minorcompact_q) {
6032 				c_seg_need_delayed_compaction(c_seg_src, FALSE);
6033 			}
6034 		}
6035 
6036 		lck_mtx_unlock_always(&c_seg_src->c_lock);
6037 	}
6038 
6039 	if (c_seg_dst) {
6040 		PAGE_REPLACEMENT_DISALLOWED(TRUE);
6041 
6042 		lck_mtx_lock_spin_always(&c_seg_dst->c_lock);
6043 
6044 		if (c_seg_dst->c_nextoffset >= c_seg_off_limit || c_seg_dst->c_nextslot >= C_SLOT_MAX_INDEX) {
6045 			/*
6046 			 * Nearing or exceeded maximum slot and offset capacity.
6047 			 */
6048 			assert(c_seg_dst->c_busy);
6049 			assert(c_seg_dst->c_state == C_IS_FILLING);
6050 			assert(!c_seg_dst->c_on_minorcompact_q);
6051 
6052 			c_current_seg_filled(c_seg_dst, (c_segment_t *)current_chead);
6053 			assert(*current_chead == NULL);
6054 		}
6055 
6056 		C_SEG_WAKEUP_DONE(c_seg_dst);
6057 
6058 		lck_mtx_unlock_always(&c_seg_dst->c_lock);
6059 
6060 		c_seg_dst = NULL;
6061 
6062 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
6063 	}
6064 
6065 	return kr;
6066 }
6067 #endif /* CONFIG_FREEZE */
6068 
6069 #if DEVELOPMENT || DEBUG
6070 
6071 void
vm_compressor_inject_error(int * slot)6072 vm_compressor_inject_error(int *slot)
6073 {
6074 	c_slot_mapping_t slot_ptr = (c_slot_mapping_t)slot;
6075 
6076 	/* No error detection for single-value compression. */
6077 	if (slot_ptr->s_cseg == C_SV_CSEG_ID) {
6078 		printf("%s(): cannot inject errors in SV-compressed pages\n", __func__ );
6079 		return;
6080 	}
6081 
6082 	/* s_cseg is actually "segno+1" */
6083 	const uint32_t c_segno = slot_ptr->s_cseg - 1;
6084 
6085 	assert(c_segno < c_segments_available);
6086 	assert(c_segments_get(c_segno)->c_segno >= c_segments_available);
6087 
6088 	const c_segment_t c_seg = c_segments_get(c_segno)->c_seg;
6089 
6090 	PAGE_REPLACEMENT_DISALLOWED(TRUE);
6091 
6092 	lck_mtx_lock_spin_always(&c_seg->c_lock);
6093 	assert(c_seg->c_state != C_IS_EMPTY && c_seg->c_state != C_IS_FREE);
6094 
6095 	const uint16_t c_indx = slot_ptr->s_cindx;
6096 	assert(c_indx < c_seg->c_nextslot);
6097 
6098 	/*
6099 	 * To safely make this segment temporarily writable, we need to mark
6100 	 * the segment busy, which allows us to release the segment lock.
6101 	 */
6102 	while (c_seg->c_busy) {
6103 		c_seg_wait_on_busy(c_seg);
6104 		lck_mtx_lock_spin_always(&c_seg->c_lock);
6105 	}
6106 	C_SEG_BUSY(c_seg);
6107 
6108 	bool already_writable = (c_seg->c_state == C_IS_FILLING);
6109 	if (!already_writable) {
6110 		/*
6111 		 * Protection update must be performed preemptibly, so temporarily drop
6112 		 * the lock. Having set c_busy will prevent most other concurrent
6113 		 * operations.
6114 		 */
6115 		lck_mtx_unlock_always(&c_seg->c_lock);
6116 		C_SEG_MAKE_WRITEABLE(c_seg);
6117 		lck_mtx_lock_spin_always(&c_seg->c_lock);
6118 	}
6119 
6120 	/*
6121 	 * Once we've released the lock following our c_state == C_IS_FILLING check,
6122 	 * c_current_seg_filled() can (re-)write-protect the segment. However, it
6123 	 * will transition from C_IS_FILLING before releasing the c_seg lock, so we
6124 	 * can detect this by re-checking after we've reobtained the lock.
6125 	 */
6126 	if (already_writable && c_seg->c_state != C_IS_FILLING) {
6127 		lck_mtx_unlock_always(&c_seg->c_lock);
6128 		C_SEG_MAKE_WRITEABLE(c_seg);
6129 		lck_mtx_lock_spin_always(&c_seg->c_lock);
6130 		already_writable = false;
6131 		/* Segment can't be freed while c_busy is set. */
6132 		assert(c_seg->c_state != C_IS_FILLING);
6133 	}
6134 
6135 	/*
6136 	 * Skip if the segment is on disk. This check can only be performed after
6137 	 * the final acquisition of the segment lock before we attempt to write to
6138 	 * the segment.
6139 	 */
6140 	if (!C_SEG_IS_ON_DISK_OR_SOQ(c_seg)) {
6141 		c_slot_t cs = C_SEG_SLOT_FROM_INDEX(c_seg, c_indx);
6142 		int32_t *data = &c_seg->c_store.c_buffer[cs->c_offset];
6143 		/* assume that the compressed data holds at least one int32_t */
6144 		assert(UNPACK_C_SIZE(cs) > sizeof(*data));
6145 		/*
6146 		 * This bit is known to be in the payload of a MISS packet resulting from
6147 		 * the pattern used in the test pattern from decompression_failure.c.
6148 		 * Flipping it should result in many corrupted bits in the test page.
6149 		 */
6150 		data[0] ^= 0x00000100;
6151 	}
6152 
6153 	if (!already_writable) {
6154 		lck_mtx_unlock_always(&c_seg->c_lock);
6155 		C_SEG_WRITE_PROTECT(c_seg);
6156 		lck_mtx_lock_spin_always(&c_seg->c_lock);
6157 	}
6158 
6159 	C_SEG_WAKEUP_DONE(c_seg);
6160 	lck_mtx_unlock_always(&c_seg->c_lock);
6161 
6162 	PAGE_REPLACEMENT_DISALLOWED(FALSE);
6163 }
6164 
6165 /*
6166  * Serialize information about a specific segment
6167  * returns true if the segment was written or there's nothing to write for the segno
6168  *         false if there's not enough space
6169  * argument size input - the size of the input buffer, output - the size written, set to 0 on failure
6170  */
6171 kern_return_t
vm_compressor_serialize_segment_debug_info(int segno,char * buf,size_t * size,vm_c_serialize_add_data_t with_data)6172 vm_compressor_serialize_segment_debug_info(int segno, char *buf, size_t *size, vm_c_serialize_add_data_t with_data)
6173 {
6174 	size_t insize = *size;
6175 	size_t offset = 0;
6176 	*size = 0;
6177 	if (c_segments_get(segno)->c_segno < c_segments_available) {
6178 		/* This check means there's no pointer assigned here so it must be an index in the free list.
6179 		 * if this was an active c_segment, .c_seg would be assigned to, which is a pointer, interpreted as an int it
6180 		 * would be higher than c_segments_available. See also assert to this effect right after assigning to c_seg in
6181 		 * c_seg_allocate()
6182 		 */
6183 		return KERN_SUCCESS;
6184 	}
6185 	if (c_segments_get(segno)->c_segno == (uint32_t)-1) {
6186 		/* c_segno of the end of the free-list */
6187 		return KERN_SUCCESS;
6188 	}
6189 
6190 	const struct c_segment* c_seg = c_segments_get(segno)->c_seg;
6191 	if (c_seg->c_state == C_IS_FREE) {
6192 		return KERN_SUCCESS; /* nothing needs to be done */
6193 	}
6194 
6195 	int nslots = c_seg->c_nextslot;
6196 	/* do we have enough space for slots (without data)? */
6197 	if (sizeof(struct c_segment_info) + (nslots * sizeof(struct c_slot_info)) > insize) {
6198 		return KERN_NO_SPACE; /* not enough space, please call me again */
6199 	}
6200 
6201 	struct c_segment_info* csi = (struct c_segment_info*)buf;
6202 	offset += sizeof(struct c_segment_info);
6203 
6204 	csi->csi_mysegno = c_seg->c_mysegno;
6205 	csi->csi_creation_ts = c_seg->c_creation_ts;
6206 	csi->csi_swappedin_ts = c_seg->c_swappedin_ts;
6207 	csi->csi_bytes_unused = c_seg->c_bytes_unused;
6208 	csi->csi_bytes_used = c_seg->c_bytes_used;
6209 	csi->csi_populated_offset = c_seg->c_populated_offset;
6210 	csi->csi_state = c_seg->c_state;
6211 	csi->csi_swappedin = c_seg->c_swappedin;
6212 	csi->csi_on_minor_compact_q = c_seg->c_on_minorcompact_q;
6213 	csi->csi_has_donated_pages = c_seg->c_has_donated_pages;
6214 	csi->csi_slots_used = (uint16_t)c_seg->c_slots_used;
6215 	csi->csi_slot_var_array_len = c_seg->c_slot_var_array_len;
6216 	csi->csi_slots_len = (uint16_t)nslots;
6217 #if TRACK_C_SEGMENT_UTILIZATION
6218 	csi->csi_decompressions_since_swapin = c_seg->c_decompressions_since_swapin;
6219 #else
6220 	csi->csi_decompressions_since_swapin = 0;
6221 #endif /* TRACK_C_SEGMENT_UTILIZATION */
6222 	/* This entire data collection races with the compressor threads which can change any
6223 	 * of this data members, and specifically can drop the data buffer to swap
6224 	 * We don't take the segment lock since that would slow the iteration over the segments down
6225 	 * and hurt the "snapshot-ness" of the data. The race risk is acceptable since this is
6226 	 * used only for a tester in development. */
6227 
6228 	for (int si = 0; si < nslots; ++si) {
6229 		if (offset + sizeof(struct c_slot_info) > insize) {
6230 			return KERN_NO_SPACE;
6231 		}
6232 		/* see also c_seg_validate() for some of the details */
6233 		const struct c_slot* cs = C_SEG_SLOT_FROM_INDEX(c_seg, si);
6234 		struct c_slot_info* ssi = (struct c_slot_info*)(buf + offset);
6235 		offset += sizeof(struct c_slot_info);
6236 		ssi->csi_size = (uint16_t)UNPACK_C_SIZE(cs);
6237 #pragma unused(with_data)
6238 		ssi->csi_unused = 0;
6239 	}
6240 	*size = offset;
6241 	return KERN_SUCCESS;
6242 }
6243 
6244 #endif /* DEVELOPMENT || DEBUG */
6245 
6246 
6247 #if CONFIG_TRACK_UNMODIFIED_ANON_PAGES
6248 
6249 struct vnode;
6250 extern void vm_swapfile_open(const char *path, struct vnode **vp);
6251 extern int vm_swapfile_preallocate(struct vnode *vp, uint64_t *size, boolean_t *pin);
6252 
6253 struct vnode *uncompressed_vp0 = NULL;
6254 struct vnode *uncompressed_vp1 = NULL;
6255 uint32_t uncompressed_file0_free_pages = 0, uncompressed_file1_free_pages = 0;
6256 uint64_t uncompressed_file0_free_offset = 0, uncompressed_file1_free_offset = 0;
6257 
6258 uint64_t compressor_ro_uncompressed = 0;
6259 uint64_t compressor_ro_uncompressed_total_returned = 0;
6260 uint64_t compressor_ro_uncompressed_skip_returned = 0;
6261 uint64_t compressor_ro_uncompressed_get = 0;
6262 uint64_t compressor_ro_uncompressed_put = 0;
6263 uint64_t compressor_ro_uncompressed_swap_usage = 0;
6264 
6265 extern void vnode_put(struct vnode* vp);
6266 extern int vnode_getwithref(struct vnode* vp);
6267 extern int vm_swapfile_io(struct vnode *vp, uint64_t offset, uint64_t start, int npages, int flags, void *upl_ctx);
6268 
6269 #define MAX_OFFSET_PAGES        (255)
6270 uint64_t uncompressed_file0_space_bitmap[MAX_OFFSET_PAGES];
6271 uint64_t uncompressed_file1_space_bitmap[MAX_OFFSET_PAGES];
6272 
6273 #define UNCOMPRESSED_FILEIDX_OFFSET_MASK (((uint32_t)1<<31ull) - 1)
6274 #define UNCOMPRESSED_FILEIDX_SHIFT (29)
6275 #define UNCOMPRESSED_FILEIDX_MASK (3)
6276 #define UNCOMPRESSED_OFFSET_SHIFT (29)
6277 #define UNCOMPRESSED_OFFSET_MASK (7)
6278 
6279 static uint32_t
vm_uncompressed_extract_swap_file(int slot)6280 vm_uncompressed_extract_swap_file(int slot)
6281 {
6282 	uint32_t fileidx = (((uint32_t)slot & UNCOMPRESSED_FILEIDX_OFFSET_MASK) >> UNCOMPRESSED_FILEIDX_SHIFT) & UNCOMPRESSED_FILEIDX_MASK;
6283 	return fileidx;
6284 }
6285 
6286 static uint32_t
vm_uncompressed_extract_swap_offset(int slot)6287 vm_uncompressed_extract_swap_offset(int slot)
6288 {
6289 	return slot & (uint32_t)(~(UNCOMPRESSED_OFFSET_MASK << UNCOMPRESSED_OFFSET_SHIFT));
6290 }
6291 
6292 static void
vm_uncompressed_return_space_to_swap(int slot)6293 vm_uncompressed_return_space_to_swap(int slot)
6294 {
6295 	PAGE_REPLACEMENT_ALLOWED(TRUE);
6296 	uint32_t fileidx = vm_uncompressed_extract_swap_file(slot);
6297 	if (fileidx == 1) {
6298 		uint32_t free_offset = vm_uncompressed_extract_swap_offset(slot);
6299 		uint64_t pgidx = free_offset / PAGE_SIZE_64;
6300 		uint64_t chunkidx = pgidx / 64;
6301 		uint64_t chunkoffset = pgidx % 64;
6302 #if DEVELOPMENT || DEBUG
6303 		uint64_t vaddr = (uint64_t)&uncompressed_file0_space_bitmap[chunkidx];
6304 		uint64_t maxvaddr = (uint64_t)&uncompressed_file0_space_bitmap[MAX_OFFSET_PAGES];
6305 		assertf(vaddr < maxvaddr, "0x%llx 0x%llx", vaddr, maxvaddr);
6306 #endif /*DEVELOPMENT || DEBUG*/
6307 		assertf((uncompressed_file0_space_bitmap[chunkidx] & ((uint64_t)1 << chunkoffset)),
6308 		    "0x%x %llu %llu", slot, chunkidx, chunkoffset);
6309 		uncompressed_file0_space_bitmap[chunkidx] &= ~((uint64_t)1 << chunkoffset);
6310 		assertf(!(uncompressed_file0_space_bitmap[chunkidx] & ((uint64_t)1 << chunkoffset)),
6311 		    "0x%x %llu %llu", slot, chunkidx, chunkoffset);
6312 
6313 		uncompressed_file0_free_pages++;
6314 	} else {
6315 		uint32_t free_offset = vm_uncompressed_extract_swap_offset(slot);
6316 		uint64_t pgidx = free_offset / PAGE_SIZE_64;
6317 		uint64_t chunkidx = pgidx / 64;
6318 		uint64_t chunkoffset = pgidx % 64;
6319 		assertf((uncompressed_file1_space_bitmap[chunkidx] & ((uint64_t)1 << chunkoffset)),
6320 		    "%llu %llu", chunkidx, chunkoffset);
6321 		uncompressed_file1_space_bitmap[chunkidx] &= ~((uint64_t)1 << chunkoffset);
6322 
6323 		uncompressed_file1_free_pages++;
6324 	}
6325 	compressor_ro_uncompressed_swap_usage--;
6326 	PAGE_REPLACEMENT_ALLOWED(FALSE);
6327 }
6328 
6329 static int
vm_uncompressed_reserve_space_in_swap()6330 vm_uncompressed_reserve_space_in_swap()
6331 {
6332 	int slot = 0;
6333 	if (uncompressed_file0_free_pages == 0 && uncompressed_file1_free_pages == 0) {
6334 		return -1;
6335 	}
6336 
6337 	PAGE_REPLACEMENT_ALLOWED(TRUE);
6338 	if (uncompressed_file0_free_pages) {
6339 		uint64_t chunkidx = 0;
6340 		uint64_t chunkoffset = 0;
6341 		while (uncompressed_file0_space_bitmap[chunkidx] == 0xffffffffffffffff) {
6342 			chunkidx++;
6343 		}
6344 		while (uncompressed_file0_space_bitmap[chunkidx] & ((uint64_t)1 << chunkoffset)) {
6345 			chunkoffset++;
6346 		}
6347 
6348 		assertf((uncompressed_file0_space_bitmap[chunkidx] & ((uint64_t)1 << chunkoffset)) == 0,
6349 		    "%llu %llu", chunkidx, chunkoffset);
6350 #if DEVELOPMENT || DEBUG
6351 		uint64_t vaddr = (uint64_t)&uncompressed_file0_space_bitmap[chunkidx];
6352 		uint64_t maxvaddr = (uint64_t)&uncompressed_file0_space_bitmap[MAX_OFFSET_PAGES];
6353 		assertf(vaddr < maxvaddr, "0x%llx 0x%llx", vaddr, maxvaddr);
6354 #endif /*DEVELOPMENT || DEBUG*/
6355 		uncompressed_file0_space_bitmap[chunkidx] |= ((uint64_t)1 << chunkoffset);
6356 		uncompressed_file0_free_offset = ((chunkidx * 64) + chunkoffset) * PAGE_SIZE_64;
6357 		assertf((uncompressed_file0_space_bitmap[chunkidx] & ((uint64_t)1 << chunkoffset)),
6358 		    "%llu %llu", chunkidx, chunkoffset);
6359 
6360 		assert(uncompressed_file0_free_offset <= (1 << UNCOMPRESSED_OFFSET_SHIFT));
6361 		slot = (int)((1 << UNCOMPRESSED_FILEIDX_SHIFT) + uncompressed_file0_free_offset);
6362 		uncompressed_file0_free_pages--;
6363 	} else {
6364 		uint64_t chunkidx = 0;
6365 		uint64_t chunkoffset = 0;
6366 		while (uncompressed_file1_space_bitmap[chunkidx] == 0xFFFFFFFFFFFFFFFF) {
6367 			chunkidx++;
6368 		}
6369 		while (uncompressed_file1_space_bitmap[chunkidx] & ((uint64_t)1 << chunkoffset)) {
6370 			chunkoffset++;
6371 		}
6372 		assert((uncompressed_file1_space_bitmap[chunkidx] & ((uint64_t)1 << chunkoffset)) == 0);
6373 		uncompressed_file1_space_bitmap[chunkidx] |= ((uint64_t)1 << chunkoffset);
6374 		uncompressed_file1_free_offset = ((chunkidx * 64) + chunkoffset) * PAGE_SIZE_64;
6375 		slot = (int)((2 << UNCOMPRESSED_FILEIDX_SHIFT) + uncompressed_file1_free_offset);
6376 		uncompressed_file1_free_pages--;
6377 	}
6378 	compressor_ro_uncompressed_swap_usage++;
6379 	PAGE_REPLACEMENT_ALLOWED(FALSE);
6380 	return slot;
6381 }
6382 
6383 #define MAX_IO_REQ (16)
6384 struct _uncompressor_io_req {
6385 	uint64_t addr;
6386 	bool inuse;
6387 } uncompressor_io_req[MAX_IO_REQ];
6388 
6389 int
vm_uncompressed_put(ppnum_t pn,int * slot)6390 vm_uncompressed_put(ppnum_t pn, int *slot)
6391 {
6392 	int retval = 0;
6393 	struct vnode *uncompressed_vp = NULL;
6394 	uint64_t uncompress_offset = 0;
6395 
6396 again:
6397 	if (uncompressed_vp0 == NULL) {
6398 		PAGE_REPLACEMENT_ALLOWED(TRUE);
6399 		if (uncompressed_vp0 == NULL) {
6400 			uint64_t size = (MAX_OFFSET_PAGES * 1024 * 1024ULL);
6401 			vm_swapfile_open("/private/var/vm/uncompressedswap0", &uncompressed_vp0);
6402 			if (uncompressed_vp0 == NULL) {
6403 				PAGE_REPLACEMENT_ALLOWED(FALSE);
6404 				return KERN_NO_ACCESS;
6405 			}
6406 			vm_swapfile_preallocate(uncompressed_vp0, &size, NULL);
6407 			uncompressed_file0_free_pages = (uint32_t)atop(size);
6408 			bzero(uncompressed_file0_space_bitmap, sizeof(uint64_t) * MAX_OFFSET_PAGES);
6409 
6410 			int i = 0;
6411 			for (; i < MAX_IO_REQ; i++) {
6412 				kmem_alloc(kernel_map, (vm_offset_t*)&uncompressor_io_req[i].addr, PAGE_SIZE_64, KMA_NOFAIL | KMA_KOBJECT, VM_KERN_MEMORY_COMPRESSOR);
6413 				uncompressor_io_req[i].inuse = false;
6414 			}
6415 
6416 			vm_swapfile_open("/private/var/vm/uncompressedswap1", &uncompressed_vp1);
6417 			assert(uncompressed_vp1);
6418 			vm_swapfile_preallocate(uncompressed_vp1, &size, NULL);
6419 			uncompressed_file1_free_pages = (uint32_t)atop(size);
6420 			bzero(uncompressed_file1_space_bitmap, sizeof(uint64_t) * MAX_OFFSET_PAGES);
6421 			PAGE_REPLACEMENT_ALLOWED(FALSE);
6422 		} else {
6423 			PAGE_REPLACEMENT_ALLOWED(FALSE);
6424 			delay(100);
6425 			goto again;
6426 		}
6427 	}
6428 
6429 	int swapinfo = vm_uncompressed_reserve_space_in_swap();
6430 	if (swapinfo == -1) {
6431 		*slot = 0;
6432 		return KERN_RESOURCE_SHORTAGE;
6433 	}
6434 
6435 	if (vm_uncompressed_extract_swap_file(swapinfo) == 1) {
6436 		uncompressed_vp = uncompressed_vp0;
6437 	} else {
6438 		uncompressed_vp = uncompressed_vp1;
6439 	}
6440 	uncompress_offset = vm_uncompressed_extract_swap_offset(swapinfo);
6441 	if ((retval = vnode_getwithref(uncompressed_vp)) != 0) {
6442 		os_log_error_with_startup_serial(OS_LOG_DEFAULT, "vm_uncompressed_put: vnode_getwithref on swapfile failed with %d\n", retval);
6443 	} else {
6444 		int i = 0;
6445 retry:
6446 		PAGE_REPLACEMENT_ALLOWED(TRUE);
6447 		for (i = 0; i < MAX_IO_REQ; i++) {
6448 			if (uncompressor_io_req[i].inuse == false) {
6449 				uncompressor_io_req[i].inuse = true;
6450 				break;
6451 			}
6452 		}
6453 		if (i == MAX_IO_REQ) {
6454 			assert_wait((event_t)&uncompressor_io_req, THREAD_UNINT);
6455 			PAGE_REPLACEMENT_ALLOWED(FALSE);
6456 			thread_block(THREAD_CONTINUE_NULL);
6457 			goto retry;
6458 		}
6459 		PAGE_REPLACEMENT_ALLOWED(FALSE);
6460 		void *addr = pmap_map_compressor_page(pn);
6461 		memcpy((void*)uncompressor_io_req[i].addr, addr, PAGE_SIZE_64);
6462 		pmap_unmap_compressor_page(pn, addr);
6463 
6464 		retval = vm_swapfile_io(uncompressed_vp, uncompress_offset, (uint64_t)uncompressor_io_req[i].addr, 1, SWAP_WRITE, NULL);
6465 		if (retval) {
6466 			*slot = 0;
6467 		} else {
6468 			*slot = (int)swapinfo;
6469 			((c_slot_mapping_t)(slot))->s_uncompressed = 1;
6470 		}
6471 		vnode_put(uncompressed_vp);
6472 		PAGE_REPLACEMENT_ALLOWED(TRUE);
6473 		uncompressor_io_req[i].inuse = false;
6474 		thread_wakeup((event_t)&uncompressor_io_req);
6475 		PAGE_REPLACEMENT_ALLOWED(FALSE);
6476 	}
6477 	return retval;
6478 }
6479 
6480 int
vm_uncompressed_get(ppnum_t pn,int * slot,__unused vm_compressor_options_t flags)6481 vm_uncompressed_get(ppnum_t pn, int *slot, __unused vm_compressor_options_t flags)
6482 {
6483 	int retval = 0;
6484 	struct vnode *uncompressed_vp = NULL;
6485 	uint32_t fileidx = vm_uncompressed_extract_swap_file(*slot);
6486 	uint64_t uncompress_offset = vm_uncompressed_extract_swap_offset(*slot);
6487 
6488 	if (__improbable(flags & C_KDP)) {
6489 		return -2;
6490 	}
6491 
6492 	if (fileidx == 1) {
6493 		uncompressed_vp = uncompressed_vp0;
6494 	} else {
6495 		uncompressed_vp = uncompressed_vp1;
6496 	}
6497 
6498 	if ((retval = vnode_getwithref(uncompressed_vp)) != 0) {
6499 		os_log_error_with_startup_serial(OS_LOG_DEFAULT, "vm_uncompressed_put: vnode_getwithref on swapfile failed with %d\n", retval);
6500 	} else {
6501 		int i = 0;
6502 retry:
6503 		PAGE_REPLACEMENT_ALLOWED(TRUE);
6504 		for (i = 0; i < MAX_IO_REQ; i++) {
6505 			if (uncompressor_io_req[i].inuse == false) {
6506 				uncompressor_io_req[i].inuse = true;
6507 				break;
6508 			}
6509 		}
6510 		if (i == MAX_IO_REQ) {
6511 			assert_wait((event_t)&uncompressor_io_req, THREAD_UNINT);
6512 			PAGE_REPLACEMENT_ALLOWED(FALSE);
6513 			thread_block(THREAD_CONTINUE_NULL);
6514 			goto retry;
6515 		}
6516 		PAGE_REPLACEMENT_ALLOWED(FALSE);
6517 		retval = vm_swapfile_io(uncompressed_vp, uncompress_offset, (uint64_t)uncompressor_io_req[i].addr, 1, SWAP_READ, NULL);
6518 		vnode_put(uncompressed_vp);
6519 		void *addr = pmap_map_compressor_page(pn);
6520 		memcpy(addr, (void*)uncompressor_io_req[i].addr, PAGE_SIZE_64);
6521 		pmap_unmap_compressor_page(pn, addr);
6522 		PAGE_REPLACEMENT_ALLOWED(TRUE);
6523 		uncompressor_io_req[i].inuse = false;
6524 		thread_wakeup((event_t)&uncompressor_io_req);
6525 		PAGE_REPLACEMENT_ALLOWED(FALSE);
6526 	}
6527 	return retval;
6528 }
6529 
6530 int
vm_uncompressed_free(int * slot,__unused vm_compressor_options_t flags)6531 vm_uncompressed_free(int *slot, __unused vm_compressor_options_t flags)
6532 {
6533 	vm_uncompressed_return_space_to_swap(*slot);
6534 	*slot = 0;
6535 	return 0;
6536 }
6537 
6538 #endif /*CONFIG_TRACK_UNMODIFIED_ANON_PAGES*/
6539