xref: /xnu-8020.121.3/osfmk/vm/vm_compressor.c (revision fdd8201d7b966f0c3ea610489d29bd841d358941)
1 /*
2  * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 
29 #include <vm/vm_compressor.h>
30 
31 #if CONFIG_PHANTOM_CACHE
32 #include <vm/vm_phantom_cache.h>
33 #endif
34 
35 #include <vm/vm_map.h>
36 #include <vm/vm_pageout.h>
37 #include <vm/memory_object.h>
38 #include <vm/vm_compressor_algorithms.h>
39 #include <vm/vm_fault.h>
40 #include <vm/vm_protos.h>
41 #include <mach/mach_host.h>             /* for host_info() */
42 #if DEVELOPMENT || DEBUG
43 #include <kern/hvg_hypercall.h>
44 #endif
45 #include <kern/ledger.h>
46 #include <kern/policy_internal.h>
47 #include <kern/thread_group.h>
48 #include <san/kasan.h>
49 
50 #if defined(__x86_64__)
51 #include <i386/misc_protos.h>
52 #endif
53 #if defined(__arm64__)
54 #include <arm/machine_routines.h>
55 #endif
56 
57 #include <IOKit/IOHibernatePrivate.h>
58 
59 TUNABLE(uint32_t, c_seg_bufsize, "vm_compressor_segment_buffer_size", (1024 * 256));
60 uint32_t c_seg_max_pages, c_seg_off_limit, c_seg_allocsize, c_seg_slot_var_array_min_len;
61 
62 extern boolean_t vm_darkwake_mode;
63 extern zone_t vm_page_zone;
64 
65 #if DEVELOPMENT || DEBUG
66 /* sysctl defined in bsd/dev/arm64/sysctl.c */
67 int do_cseg_wedge_thread(void);
68 int do_cseg_unwedge_thread(void);
69 static event_t debug_cseg_wait_event = NULL;
70 #endif /* DEVELOPMENT || DEBUG */
71 
72 #if CONFIG_FREEZE
73 bool freezer_incore_cseg_acct = TRUE; /* Only count incore compressed memory for jetsams. */
74 void task_disown_frozen_csegs(task_t owner_task);
75 #endif /* CONFIG_FREEZE */
76 
77 #if POPCOUNT_THE_COMPRESSED_DATA
78 boolean_t popcount_c_segs = TRUE;
79 
80 static inline uint32_t
vmc_pop(uintptr_t ins,int sz)81 vmc_pop(uintptr_t ins, int sz)
82 {
83 	uint32_t rv = 0;
84 
85 	if (__probable(popcount_c_segs == FALSE)) {
86 		return 0xDEAD707C;
87 	}
88 
89 	while (sz >= 16) {
90 		uint32_t rv1, rv2;
91 		uint64_t *ins64 = (uint64_t *) ins;
92 		uint64_t *ins642 = (uint64_t *) (ins + 8);
93 		rv1 = __builtin_popcountll(*ins64);
94 		rv2 = __builtin_popcountll(*ins642);
95 		rv += rv1 + rv2;
96 		sz -= 16;
97 		ins += 16;
98 	}
99 
100 	while (sz >= 4) {
101 		uint32_t *ins32 = (uint32_t *) ins;
102 		rv += __builtin_popcount(*ins32);
103 		sz -= 4;
104 		ins += 4;
105 	}
106 
107 	while (sz > 0) {
108 		char *ins8 = (char *)ins;
109 		rv += __builtin_popcount(*ins8);
110 		sz--;
111 		ins++;
112 	}
113 	return rv;
114 }
115 #endif
116 
117 #if VALIDATE_C_SEGMENTS
118 boolean_t validate_c_segs = TRUE;
119 #endif
120 /*
121  * vm_compressor_mode has a heirarchy of control to set its value.
122  * boot-args are checked first, then device-tree, and finally
123  * the default value that is defined below. See vm_fault_init() for
124  * the boot-arg & device-tree code.
125  */
126 
127 #if !XNU_TARGET_OS_OSX
128 
129 #if CONFIG_FREEZE
130 int     vm_compressor_mode = VM_PAGER_FREEZER_DEFAULT;
131 struct  freezer_context freezer_context_global;
132 #else /* CONFIG_FREEZE */
133 int     vm_compressor_mode = VM_PAGER_NOT_CONFIGURED;
134 #endif /* CONFIG_FREEZE */
135 
136 #else /* !XNU_TARGET_OS_OSX */
137 int             vm_compressor_mode = VM_PAGER_COMPRESSOR_WITH_SWAP;
138 
139 #endif /* !XNU_TARGET_OS_OSX */
140 
141 TUNABLE(uint32_t, vm_compression_limit, "vm_compression_limit", 0);
142 int             vm_compressor_is_active = 0;
143 int             vm_compressor_available = 0;
144 
145 extern uint64_t vm_swap_get_max_configured_space(void);
146 extern void     vm_pageout_io_throttle(void);
147 
148 #if CHECKSUM_THE_DATA || CHECKSUM_THE_SWAP || CHECKSUM_THE_COMPRESSED_DATA
149 extern unsigned int hash_string(char *cp, int len);
150 static unsigned int vmc_hash(char *, int);
151 boolean_t checksum_c_segs = TRUE;
152 
153 unsigned int
vmc_hash(char * cp,int len)154 vmc_hash(char *cp, int len)
155 {
156 	if (__probable(checksum_c_segs == FALSE)) {
157 		return 0xDEAD7A37;
158 	}
159 	return hash_string(cp, len);
160 }
161 #endif
162 
163 #define UNPACK_C_SIZE(cs)       ((cs->c_size == (PAGE_SIZE-1)) ? PAGE_SIZE : cs->c_size)
164 #define PACK_C_SIZE(cs, size)   (cs->c_size = ((size == PAGE_SIZE) ? PAGE_SIZE - 1 : size))
165 
166 
167 struct c_sv_hash_entry {
168 	union {
169 		struct  {
170 			uint32_t        c_sv_he_ref;
171 			uint32_t        c_sv_he_data;
172 		} c_sv_he;
173 		uint64_t        c_sv_he_record;
174 	} c_sv_he_un;
175 };
176 
177 #define he_ref  c_sv_he_un.c_sv_he.c_sv_he_ref
178 #define he_data c_sv_he_un.c_sv_he.c_sv_he_data
179 #define he_record c_sv_he_un.c_sv_he_record
180 
181 #define C_SV_HASH_MAX_MISS      32
182 #define C_SV_HASH_SIZE          ((1 << 10))
183 #define C_SV_HASH_MASK          ((1 << 10) - 1)
184 #define C_SV_CSEG_ID            ((1 << 22) - 1)
185 
186 
187 union c_segu {
188 	c_segment_t     c_seg;
189 	uintptr_t       c_segno;
190 };
191 
192 #define C_SLOT_ASSERT_PACKABLE(ptr) \
193 	VM_ASSERT_POINTER_PACKABLE((vm_offset_t)(ptr), C_SLOT_PACKED_PTR);
194 
195 #define C_SLOT_PACK_PTR(ptr) \
196 	VM_PACK_POINTER((vm_offset_t)(ptr), C_SLOT_PACKED_PTR)
197 
198 #define C_SLOT_UNPACK_PTR(cslot) \
199 	(c_slot_mapping_t)VM_UNPACK_POINTER((cslot)->c_packed_ptr, C_SLOT_PACKED_PTR)
200 
201 /* for debugging purposes */
202 SECURITY_READ_ONLY_EARLY(vm_packing_params_t) c_slot_packing_params =
203     VM_PACKING_PARAMS(C_SLOT_PACKED_PTR);
204 
205 uint32_t        c_segment_count = 0;
206 uint32_t        c_segment_count_max = 0;
207 
208 uint64_t        c_generation_id = 0;
209 uint64_t        c_generation_id_flush_barrier;
210 
211 
212 #define         HIBERNATE_FLUSHING_SECS_TO_COMPLETE     120
213 
214 boolean_t       hibernate_no_swapspace = FALSE;
215 boolean_t       hibernate_flush_timed_out = FALSE;
216 clock_sec_t     hibernate_flushing_deadline = 0;
217 
218 
219 #if RECORD_THE_COMPRESSED_DATA
220 char    *c_compressed_record_sbuf;
221 char    *c_compressed_record_ebuf;
222 char    *c_compressed_record_cptr;
223 #endif
224 
225 
226 queue_head_t    c_age_list_head;
227 queue_head_t    c_swappedin_list_head;
228 queue_head_t    c_swapout_list_head;
229 queue_head_t    c_swapio_list_head;
230 queue_head_t    c_swappedout_list_head;
231 queue_head_t    c_swappedout_sparse_list_head;
232 queue_head_t    c_major_list_head;
233 queue_head_t    c_filling_list_head;
234 queue_head_t    c_bad_list_head;
235 
236 uint32_t        c_age_count = 0;
237 uint32_t        c_swappedin_count = 0;
238 uint32_t        c_swapout_count = 0;
239 uint32_t        c_swapio_count = 0;
240 uint32_t        c_swappedout_count = 0;
241 uint32_t        c_swappedout_sparse_count = 0;
242 uint32_t        c_major_count = 0;
243 uint32_t        c_filling_count = 0;
244 uint32_t        c_empty_count = 0;
245 uint32_t        c_bad_count = 0;
246 
247 
248 queue_head_t    c_minor_list_head;
249 uint32_t        c_minor_count = 0;
250 
251 int             c_overage_swapped_count = 0;
252 int             c_overage_swapped_limit = 0;
253 
254 int             c_seg_fixed_array_len;
255 union  c_segu   *c_segments;
256 vm_offset_t     c_buffers;
257 vm_size_t       c_buffers_size;
258 caddr_t         c_segments_next_page;
259 boolean_t       c_segments_busy;
260 uint32_t        c_segments_available;
261 uint32_t        c_segments_limit;
262 uint32_t        c_segments_nearing_limit;
263 
264 uint32_t        c_segment_svp_in_hash;
265 uint32_t        c_segment_svp_hash_succeeded;
266 uint32_t        c_segment_svp_hash_failed;
267 uint32_t        c_segment_svp_zero_compressions;
268 uint32_t        c_segment_svp_nonzero_compressions;
269 uint32_t        c_segment_svp_zero_decompressions;
270 uint32_t        c_segment_svp_nonzero_decompressions;
271 
272 uint32_t        c_segment_noncompressible_pages;
273 
274 uint32_t        c_segment_pages_compressed = 0; /* Tracks # of uncompressed pages fed into the compressor */
275 #if CONFIG_FREEZE
276 int32_t        c_segment_pages_compressed_incore = 0; /* Tracks # of uncompressed pages fed into the compressor that are in memory */
277 uint32_t        c_segments_incore_limit = 0; /* Tracks # of segments allowed to be in-core. Based on compressor pool size */
278 #endif /* CONFIG_FREEZE */
279 
280 uint32_t        c_segment_pages_compressed_limit;
281 uint32_t        c_segment_pages_compressed_nearing_limit;
282 uint32_t        c_free_segno_head = (uint32_t)-1;
283 
284 uint32_t        vm_compressor_minorcompact_threshold_divisor = 10;
285 uint32_t        vm_compressor_majorcompact_threshold_divisor = 10;
286 uint32_t        vm_compressor_unthrottle_threshold_divisor = 10;
287 uint32_t        vm_compressor_catchup_threshold_divisor = 10;
288 
289 uint32_t        vm_compressor_minorcompact_threshold_divisor_overridden = 0;
290 uint32_t        vm_compressor_majorcompact_threshold_divisor_overridden = 0;
291 uint32_t        vm_compressor_unthrottle_threshold_divisor_overridden = 0;
292 uint32_t        vm_compressor_catchup_threshold_divisor_overridden = 0;
293 
294 #define         C_SEGMENTS_PER_PAGE     (PAGE_SIZE / sizeof(union c_segu))
295 
296 LCK_GRP_DECLARE(vm_compressor_lck_grp, "vm_compressor");
297 LCK_RW_DECLARE(c_master_lock, &vm_compressor_lck_grp);
298 LCK_MTX_DECLARE(c_list_lock_storage, &vm_compressor_lck_grp);
299 
300 boolean_t       decompressions_blocked = FALSE;
301 
302 zone_t          compressor_segment_zone;
303 int             c_compressor_swap_trigger = 0;
304 
305 uint32_t        compressor_cpus;
306 char            *compressor_scratch_bufs;
307 char            *kdp_compressor_scratch_buf;
308 char            *kdp_compressor_decompressed_page;
309 addr64_t        kdp_compressor_decompressed_page_paddr;
310 ppnum_t         kdp_compressor_decompressed_page_ppnum;
311 
312 clock_sec_t     start_of_sample_period_sec = 0;
313 clock_nsec_t    start_of_sample_period_nsec = 0;
314 clock_sec_t     start_of_eval_period_sec = 0;
315 clock_nsec_t    start_of_eval_period_nsec = 0;
316 uint32_t        sample_period_decompression_count = 0;
317 uint32_t        sample_period_compression_count = 0;
318 uint32_t        last_eval_decompression_count = 0;
319 uint32_t        last_eval_compression_count = 0;
320 
321 #define         DECOMPRESSION_SAMPLE_MAX_AGE            (60 * 30)
322 
323 boolean_t       vm_swapout_ripe_segments = FALSE;
324 uint32_t        vm_ripe_target_age = (60 * 60 * 48);
325 
326 uint32_t        swapout_target_age = 0;
327 uint32_t        age_of_decompressions_during_sample_period[DECOMPRESSION_SAMPLE_MAX_AGE];
328 uint32_t        overage_decompressions_during_sample_period = 0;
329 
330 
331 void            do_fastwake_warmup(queue_head_t *, boolean_t);
332 boolean_t       fastwake_warmup = FALSE;
333 boolean_t       fastwake_recording_in_progress = FALSE;
334 clock_sec_t     dont_trim_until_ts = 0;
335 
336 uint64_t        c_segment_warmup_count;
337 uint64_t        first_c_segment_to_warm_generation_id = 0;
338 uint64_t        last_c_segment_to_warm_generation_id = 0;
339 boolean_t       hibernate_flushing = FALSE;
340 
341 int64_t         c_segment_input_bytes __attribute__((aligned(8))) = 0;
342 int64_t         c_segment_compressed_bytes __attribute__((aligned(8))) = 0;
343 int64_t         compressor_bytes_used __attribute__((aligned(8))) = 0;
344 
345 
346 struct c_sv_hash_entry c_segment_sv_hash_table[C_SV_HASH_SIZE]  __attribute__ ((aligned(8)));
347 
348 static boolean_t compressor_needs_to_swap(void);
349 static void vm_compressor_swap_trigger_thread(void);
350 static void vm_compressor_do_delayed_compactions(boolean_t);
351 static void vm_compressor_compact_and_swap(boolean_t);
352 static void vm_compressor_age_swapped_in_segments(boolean_t);
353 
354 struct vm_compressor_swapper_stats vmcs_stats;
355 
356 #if XNU_TARGET_OS_OSX
357 #if (__arm64__)
358 static void vm_compressor_process_major_segments(void);
359 #endif /* (__arm64__) */
360 static void vm_compressor_take_paging_space_action(void);
361 #endif /* XNU_TARGET_OS_OSX */
362 
363 void compute_swapout_target_age(void);
364 
365 boolean_t c_seg_major_compact(c_segment_t, c_segment_t);
366 boolean_t c_seg_major_compact_ok(c_segment_t, c_segment_t);
367 
368 int  c_seg_minor_compaction_and_unlock(c_segment_t, boolean_t);
369 int  c_seg_do_minor_compaction_and_unlock(c_segment_t, boolean_t, boolean_t, boolean_t);
370 void c_seg_try_minor_compaction_and_unlock(c_segment_t c_seg);
371 
372 void c_seg_move_to_sparse_list(c_segment_t);
373 void c_seg_insert_into_q(queue_head_t *, c_segment_t);
374 
375 uint64_t vm_available_memory(void);
376 uint64_t vm_compressor_pages_compressed(void);
377 uint32_t vm_compressor_pool_size(void);
378 
379 /*
380  * indicate the need to do a major compaction if
381  * the overall set of in-use compression segments
382  * becomes sparse... on systems that support pressure
383  * driven swapping, this will also cause swapouts to
384  * be initiated.
385  */
386 static inline boolean_t
vm_compressor_needs_to_major_compact()387 vm_compressor_needs_to_major_compact()
388 {
389 	uint32_t        incore_seg_count;
390 
391 	incore_seg_count = c_segment_count - c_swappedout_count - c_swappedout_sparse_count;
392 
393 	if ((c_segment_count >= (c_segments_nearing_limit / 8)) &&
394 	    ((incore_seg_count * c_seg_max_pages) - VM_PAGE_COMPRESSOR_COUNT) >
395 	    ((incore_seg_count / 8) * c_seg_max_pages)) {
396 		return 1;
397 	}
398 	return 0;
399 }
400 
401 
402 uint64_t
vm_available_memory(void)403 vm_available_memory(void)
404 {
405 	return ((uint64_t)AVAILABLE_NON_COMPRESSED_MEMORY) * PAGE_SIZE_64;
406 }
407 
408 
409 uint32_t
vm_compressor_pool_size(void)410 vm_compressor_pool_size(void)
411 {
412 	return VM_PAGE_COMPRESSOR_COUNT;
413 }
414 
415 uint64_t
vm_compressor_pages_compressed(void)416 vm_compressor_pages_compressed(void)
417 {
418 	return c_segment_pages_compressed * PAGE_SIZE_64;
419 }
420 
421 
422 boolean_t
vm_compressor_low_on_space(void)423 vm_compressor_low_on_space(void)
424 {
425 #if CONFIG_FREEZE
426 	uint64_t incore_seg_count;
427 	uint32_t incore_compressed_pages;
428 	if (freezer_incore_cseg_acct) {
429 		incore_seg_count = c_segment_count - c_swappedout_count - c_swappedout_sparse_count;
430 		incore_compressed_pages = c_segment_pages_compressed_incore;
431 	} else {
432 		incore_seg_count = c_segment_count;
433 		incore_compressed_pages = c_segment_pages_compressed;
434 	}
435 
436 	if ((incore_compressed_pages > c_segment_pages_compressed_nearing_limit) ||
437 	    (incore_seg_count > c_segments_nearing_limit)) {
438 		return TRUE;
439 	}
440 #else /* CONFIG_FREEZE */
441 	if ((c_segment_pages_compressed > c_segment_pages_compressed_nearing_limit) ||
442 	    (c_segment_count > c_segments_nearing_limit)) {
443 		return TRUE;
444 	}
445 #endif /* CONFIG_FREEZE */
446 	return FALSE;
447 }
448 
449 
450 boolean_t
vm_compressor_out_of_space(void)451 vm_compressor_out_of_space(void)
452 {
453 #if CONFIG_FREEZE
454 	uint64_t incore_seg_count;
455 	uint32_t incore_compressed_pages;
456 	if (freezer_incore_cseg_acct) {
457 		incore_seg_count = c_segment_count - c_swappedout_count - c_swappedout_sparse_count;
458 		incore_compressed_pages = c_segment_pages_compressed_incore;
459 	} else {
460 		incore_seg_count = c_segment_count;
461 		incore_compressed_pages = c_segment_pages_compressed;
462 	}
463 
464 	if ((incore_compressed_pages >= c_segment_pages_compressed_limit) ||
465 	    (incore_seg_count > c_segments_incore_limit)) {
466 		return TRUE;
467 	}
468 #else /* CONFIG_FREEZE */
469 	if ((c_segment_pages_compressed >= c_segment_pages_compressed_limit) ||
470 	    (c_segment_count >= c_segments_limit)) {
471 		return TRUE;
472 	}
473 #endif /* CONFIG_FREEZE */
474 	return FALSE;
475 }
476 
477 
478 int
vm_wants_task_throttled(task_t task)479 vm_wants_task_throttled(task_t task)
480 {
481 	ledger_amount_t compressed;
482 	if (task == kernel_task) {
483 		return 0;
484 	}
485 
486 	if (VM_CONFIG_SWAP_IS_ACTIVE) {
487 		if ((vm_compressor_low_on_space() || HARD_THROTTLE_LIMIT_REACHED())) {
488 			ledger_get_balance(task->ledger, task_ledgers.internal_compressed, &compressed);
489 			compressed >>= VM_MAP_PAGE_SHIFT(task->map);
490 			if ((unsigned int)compressed > (c_segment_pages_compressed / 4)) {
491 				return 1;
492 			}
493 		}
494 	}
495 	return 0;
496 }
497 
498 
499 #if DEVELOPMENT || DEBUG
500 /*
501  * On compressor/swap exhaustion, kill the largest process regardless of
502  * its chosen process policy.
503  */
504 TUNABLE(bool, kill_on_no_paging_space, "-kill_on_no_paging_space", false);
505 #endif /* DEVELOPMENT || DEBUG */
506 
507 #if XNU_TARGET_OS_OSX
508 
509 static uint32_t no_paging_space_action_in_progress = 0;
510 extern void memorystatus_send_low_swap_note(void);
511 
512 static void
vm_compressor_take_paging_space_action(void)513 vm_compressor_take_paging_space_action(void)
514 {
515 	if (no_paging_space_action_in_progress == 0) {
516 		if (OSCompareAndSwap(0, 1, (UInt32 *)&no_paging_space_action_in_progress)) {
517 			if (no_paging_space_action()) {
518 #if DEVELOPMENT || DEBUG
519 				if (kill_on_no_paging_space) {
520 					/*
521 					 * Since we are choosing to always kill a process, we don't need the
522 					 * "out of application memory" dialog box in this mode. And, hence we won't
523 					 * send the knote.
524 					 */
525 					no_paging_space_action_in_progress = 0;
526 					return;
527 				}
528 #endif /* DEVELOPMENT || DEBUG */
529 				memorystatus_send_low_swap_note();
530 			}
531 
532 			no_paging_space_action_in_progress = 0;
533 		}
534 	}
535 }
536 #endif /* XNU_TARGET_OS_OSX */
537 
538 
539 void
vm_decompressor_lock(void)540 vm_decompressor_lock(void)
541 {
542 	PAGE_REPLACEMENT_ALLOWED(TRUE);
543 
544 	decompressions_blocked = TRUE;
545 
546 	PAGE_REPLACEMENT_ALLOWED(FALSE);
547 }
548 
549 void
vm_decompressor_unlock(void)550 vm_decompressor_unlock(void)
551 {
552 	PAGE_REPLACEMENT_ALLOWED(TRUE);
553 
554 	decompressions_blocked = FALSE;
555 
556 	PAGE_REPLACEMENT_ALLOWED(FALSE);
557 
558 	thread_wakeup((event_t)&decompressions_blocked);
559 }
560 
561 static inline void
cslot_copy(c_slot_t cdst,c_slot_t csrc)562 cslot_copy(c_slot_t cdst, c_slot_t csrc)
563 {
564 #if CHECKSUM_THE_DATA
565 	cdst->c_hash_data = csrc->c_hash_data;
566 #endif
567 #if CHECKSUM_THE_COMPRESSED_DATA
568 	cdst->c_hash_compressed_data = csrc->c_hash_compressed_data;
569 #endif
570 #if POPCOUNT_THE_COMPRESSED_DATA
571 	cdst->c_pop_cdata = csrc->c_pop_cdata;
572 #endif
573 	cdst->c_size = csrc->c_size;
574 	cdst->c_packed_ptr = csrc->c_packed_ptr;
575 #if defined(__arm__) || defined(__arm64__)
576 	cdst->c_codec = csrc->c_codec;
577 #endif
578 #if __APPLE_WKDM_POPCNT_EXTENSIONS__
579 	cdst->c_inline_popcount = csrc->c_inline_popcount;
580 #endif
581 }
582 
583 #if XNU_TARGET_OS_OSX
584 #define VM_COMPRESSOR_MAX_POOL_SIZE (192UL << 30)
585 #else
586 #define VM_COMPRESSOR_MAX_POOL_SIZE (0)
587 #endif
588 
589 static vm_map_size_t compressor_size;
590 static SECURITY_READ_ONLY_LATE(struct kmem_range) compressor_range;
591 vm_map_t compressor_map;
592 uint64_t compressor_pool_max_size;
593 uint64_t compressor_pool_size;
594 uint32_t compressor_pool_multiplier;
595 
596 #if DEVELOPMENT || DEBUG
597 /*
598  * Compressor segments are write-protected in development/debug
599  * kernels to help debug memory corruption.
600  * In cases where performance is a concern, this can be disabled
601  * via the boot-arg "-disable_cseg_write_protection".
602  */
603 boolean_t write_protect_c_segs = TRUE;
604 int vm_compressor_test_seg_wp;
605 uint32_t vm_ktrace_enabled;
606 #endif /* DEVELOPMENT || DEBUG */
607 
608 #if (XNU_TARGET_OS_OSX && __arm64__)
609 
610 #include <IOKit/IOPlatformExpert.h>
611 #include <sys/random.h>
612 
613 static const char *csegbufsizeExperimentProperty = "_csegbufsz_experiment";
614 static thread_call_t csegbufsz_experiment_thread_call;
615 
616 extern boolean_t IOServiceWaitForMatchingResource(const char * property, uint64_t timeout);
617 static void
erase_csegbufsz_experiment_property(__unused void * param0,__unused void * param1)618 erase_csegbufsz_experiment_property(__unused void *param0, __unused void *param1)
619 {
620 	// Wait for NVRAM to be writable
621 	if (!IOServiceWaitForMatchingResource("IONVRAM", UINT64_MAX)) {
622 		printf("csegbufsz_experiment_property: Failed to wait for IONVRAM.");
623 	}
624 
625 	if (!PERemoveNVRAMProperty(csegbufsizeExperimentProperty)) {
626 		printf("csegbufsize_experiment_property: Failed to remove %s from NVRAM.", csegbufsizeExperimentProperty);
627 	}
628 	thread_call_free(csegbufsz_experiment_thread_call);
629 }
630 
631 static void
erase_csegbufsz_experiment_property_async()632 erase_csegbufsz_experiment_property_async()
633 {
634 	csegbufsz_experiment_thread_call = thread_call_allocate_with_priority(
635 		erase_csegbufsz_experiment_property,
636 		NULL,
637 		THREAD_CALL_PRIORITY_LOW
638 		);
639 	if (csegbufsz_experiment_thread_call == NULL) {
640 		printf("csegbufsize_experiment_property: Unable to allocate thread call.");
641 	} else {
642 		thread_call_enter(csegbufsz_experiment_thread_call);
643 	}
644 }
645 
646 static void
cleanup_csegbufsz_experiment(__unused void * arg0)647 cleanup_csegbufsz_experiment(__unused void *arg0)
648 {
649 	char nvram = 0;
650 	unsigned int len = sizeof(nvram);
651 	if (PEReadNVRAMProperty(csegbufsizeExperimentProperty, &nvram, &len)) {
652 		erase_csegbufsz_experiment_property_async();
653 	}
654 }
655 
656 STARTUP_ARG(EARLY_BOOT, STARTUP_RANK_FIRST, cleanup_csegbufsz_experiment, NULL);
657 #endif /* XNU_TARGET_OS_OSX && __arm64__ */
658 
659 __startup_func
660 static void
vm_compressor_set_size(void)661 vm_compressor_set_size(void)
662 {
663 	__assert_only struct c_slot_mapping tmp_slot_ptr;
664 	vm_size_t c_segments_arr_size = 0;
665 
666 	if (vm_compression_limit) {
667 		compressor_pool_size = ptoa_64(vm_compression_limit);
668 	}
669 
670 	compressor_pool_max_size = C_SEG_MAX_LIMIT;
671 	compressor_pool_max_size *= c_seg_bufsize;
672 
673 #if XNU_TARGET_OS_OSX
674 
675 	if (vm_compression_limit == 0) {
676 		if (max_mem <= (4ULL * 1024ULL * 1024ULL * 1024ULL)) {
677 			compressor_pool_size = 16ULL * max_mem;
678 		} else if (max_mem <= (8ULL * 1024ULL * 1024ULL * 1024ULL)) {
679 			compressor_pool_size = 8ULL * max_mem;
680 		} else if (max_mem <= (32ULL * 1024ULL * 1024ULL * 1024ULL)) {
681 			compressor_pool_size = 4ULL * max_mem;
682 		} else {
683 			compressor_pool_size = 2ULL * max_mem;
684 		}
685 	}
686 	/*
687 	 * Cap the compressor pool size to a max of 192G
688 	 */
689 	if (compressor_pool_size > VM_COMPRESSOR_MAX_POOL_SIZE) {
690 		compressor_pool_size = VM_COMPRESSOR_MAX_POOL_SIZE;
691 	}
692 	if (max_mem <= (8ULL * 1024ULL * 1024ULL * 1024ULL)) {
693 		compressor_pool_multiplier = 1;
694 	} else if (max_mem <= (32ULL * 1024ULL * 1024ULL * 1024ULL)) {
695 		compressor_pool_multiplier = 2;
696 	} else {
697 		compressor_pool_multiplier = 4;
698 	}
699 
700 #elif defined(__arm__)
701 
702 #define VM_RESERVE_SIZE                 (1024 * 1024 * 256)
703 #define MAX_COMPRESSOR_POOL_SIZE        (1024 * 1024 * 278)
704 
705 	if (compressor_pool_max_size > MAX_COMPRESSOR_POOL_SIZE) {
706 		compressor_pool_max_size = MAX_COMPRESSOR_POOL_SIZE;
707 	}
708 
709 	if (vm_compression_limit == 0) {
710 		compressor_pool_size = ((kernel_map->max_offset - kernel_map->min_offset) - kernel_map->size) - VM_RESERVE_SIZE;
711 	}
712 	compressor_pool_multiplier = 1;
713 
714 #elif defined(__arm64__) && defined(XNU_TARGET_OS_WATCH)
715 
716 	/*
717 	 * On M9 watches the compressor can become big and can lead to
718 	 * churn in workingset resulting in audio drops. Setting a cap
719 	 * on the compressor size favors reclaiming unused memory
720 	 * sitting in idle band via jetsams
721 	 */
722 
723 #define COMPRESSOR_CAP_PERCENTAGE        37ULL
724 
725 	if (compressor_pool_max_size > max_mem) {
726 		compressor_pool_max_size = max_mem;
727 	}
728 
729 	if (vm_compression_limit == 0) {
730 		compressor_pool_size = (max_mem * COMPRESSOR_CAP_PERCENTAGE) / 100ULL;
731 	}
732 	compressor_pool_multiplier = 1;
733 
734 #else
735 
736 	if (compressor_pool_max_size > max_mem) {
737 		compressor_pool_max_size = max_mem;
738 	}
739 
740 	if (vm_compression_limit == 0) {
741 		compressor_pool_size = max_mem;
742 	}
743 	compressor_pool_multiplier = 1;
744 #endif
745 	if (compressor_pool_size > compressor_pool_max_size) {
746 		compressor_pool_size = compressor_pool_max_size;
747 	}
748 
749 	c_seg_max_pages = (c_seg_bufsize / PAGE_SIZE);
750 	c_seg_slot_var_array_min_len = c_seg_max_pages;
751 
752 #if !defined(__x86_64__)
753 	c_seg_off_limit = (C_SEG_BYTES_TO_OFFSET((c_seg_bufsize - 512)));
754 	c_seg_allocsize = (c_seg_bufsize + PAGE_SIZE);
755 #else
756 	c_seg_off_limit = (C_SEG_BYTES_TO_OFFSET((c_seg_bufsize - 128)));
757 	c_seg_allocsize = c_seg_bufsize;
758 #endif /* !defined(__x86_64__) */
759 
760 	c_segments_limit = (uint32_t)(compressor_pool_size / (vm_size_t)(c_seg_allocsize));
761 	tmp_slot_ptr.s_cseg = c_segments_limit;
762 	/* Panic on internal configs*/
763 	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);
764 
765 	if (tmp_slot_ptr.s_cseg != c_segments_limit) {
766 		tmp_slot_ptr.s_cseg = -1;
767 		c_segments_limit = tmp_slot_ptr.s_cseg - 1; /*limited by segment idx bits in c_slot_mapping*/
768 		compressor_pool_size = (c_segments_limit * (vm_size_t)(c_seg_allocsize));
769 	}
770 
771 	c_segments_nearing_limit = (uint32_t)(((uint64_t)c_segments_limit * 98ULL) / 100ULL);
772 
773 	c_segment_pages_compressed_limit = (c_segments_limit * (c_seg_bufsize / PAGE_SIZE) * compressor_pool_multiplier);
774 
775 	if (c_segment_pages_compressed_limit < (uint32_t)(max_mem / PAGE_SIZE)) {
776 #if defined(XNU_TARGET_OS_WATCH)
777 		c_segment_pages_compressed_limit = (uint32_t)(max_mem / PAGE_SIZE);
778 #else
779 		if (!vm_compression_limit) {
780 			c_segment_pages_compressed_limit = (uint32_t)(max_mem / PAGE_SIZE);
781 		}
782 #endif
783 	}
784 
785 	c_segment_pages_compressed_nearing_limit = (uint32_t)(((uint64_t)c_segment_pages_compressed_limit * 98ULL) / 100ULL);
786 
787 #if CONFIG_FREEZE
788 	/*
789 	 * Our in-core limits are based on the size of the compressor pool.
790 	 * The c_segments_nearing_limit is also based on the compressor pool
791 	 * size and calculated above.
792 	 */
793 	c_segments_incore_limit = c_segments_limit;
794 
795 	if (freezer_incore_cseg_acct) {
796 		/*
797 		 * Add enough segments to track all frozen c_segs that can be stored in swap.
798 		 */
799 		c_segments_limit += (uint32_t)(vm_swap_get_max_configured_space() / (vm_size_t)(c_seg_allocsize));
800 		tmp_slot_ptr.s_cseg = c_segments_limit;
801 		/* Panic on internal configs*/
802 		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);
803 	}
804 #endif
805 	/*
806 	 * Submap needs space for:
807 	 * - c_segments
808 	 * - c_buffers
809 	 * - swap reclaimations -- c_seg_bufsize
810 	 */
811 	c_segments_arr_size = vm_map_round_page((sizeof(union c_segu) * c_segments_limit), VM_MAP_PAGE_MASK(kernel_map));
812 	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));
813 
814 	compressor_size = c_segments_arr_size + c_buffers_size + c_seg_bufsize;
815 
816 #if RECORD_THE_COMPRESSED_DATA
817 	c_compressed_record_sbuf_size = (vm_size_t)c_seg_allocsize + (PAGE_SIZE * 2);
818 	compressor_size += c_compressed_record_sbuf_size;
819 #endif /* RECORD_THE_COMPRESSED_DATA */
820 }
821 STARTUP(KMEM, STARTUP_RANK_FIRST, vm_compressor_set_size);
822 
823 KMEM_RANGE_REGISTER_DYNAMIC(compressor, &compressor_range, ^() {
824 	return compressor_size;
825 });
826 
827 void
vm_compressor_init(void)828 vm_compressor_init(void)
829 {
830 	thread_t        thread;
831 #if RECORD_THE_COMPRESSED_DATA
832 	vm_size_t       c_compressed_record_sbuf_size = 0;
833 #endif /* RECORD_THE_COMPRESSED_DATA */
834 
835 #if DEVELOPMENT || DEBUG || CONFIG_FREEZE
836 	char bootarg_name[32];
837 #endif /* DEVELOPMENT || DEBUG || CONFIG_FREEZE */
838 
839 #if DEVELOPMENT || DEBUG
840 	if (PE_parse_boot_argn("-disable_cseg_write_protection", bootarg_name, sizeof(bootarg_name))) {
841 		write_protect_c_segs = FALSE;
842 	}
843 	int vmcval = 1;
844 	PE_parse_boot_argn("vm_compressor_validation", &vmcval, sizeof(vmcval));
845 
846 	if (kern_feature_override(KF_COMPRSV_OVRD)) {
847 		vmcval = 0;
848 	}
849 	if (vmcval == 0) {
850 #if POPCOUNT_THE_COMPRESSED_DATA
851 		popcount_c_segs = FALSE;
852 #endif
853 #if CHECKSUM_THE_DATA || CHECKSUM_THE_COMPRESSED_DATA
854 		checksum_c_segs = FALSE;
855 #endif
856 #if VALIDATE_C_SEGMENTS
857 		validate_c_segs = FALSE;
858 #endif
859 		write_protect_c_segs = FALSE;
860 	}
861 #endif /* DEVELOPMENT || DEBUG */
862 
863 #if CONFIG_FREEZE
864 	if (PE_parse_boot_argn("-disable_freezer_cseg_acct", bootarg_name, sizeof(bootarg_name))) {
865 		freezer_incore_cseg_acct = FALSE;
866 	}
867 #endif /* CONFIG_FREEZE */
868 
869 	assert((C_SEGMENTS_PER_PAGE * sizeof(union c_segu)) == PAGE_SIZE);
870 
871 #if !XNU_TARGET_OS_OSX
872 	vm_compressor_minorcompact_threshold_divisor = 20;
873 	vm_compressor_majorcompact_threshold_divisor = 30;
874 	vm_compressor_unthrottle_threshold_divisor = 40;
875 	vm_compressor_catchup_threshold_divisor = 60;
876 #else /* !XNU_TARGET_OS_OSX */
877 	if (max_mem <= (3ULL * 1024ULL * 1024ULL * 1024ULL)) {
878 		vm_compressor_minorcompact_threshold_divisor = 11;
879 		vm_compressor_majorcompact_threshold_divisor = 13;
880 		vm_compressor_unthrottle_threshold_divisor = 20;
881 		vm_compressor_catchup_threshold_divisor = 35;
882 	} else {
883 		vm_compressor_minorcompact_threshold_divisor = 20;
884 		vm_compressor_majorcompact_threshold_divisor = 25;
885 		vm_compressor_unthrottle_threshold_divisor = 35;
886 		vm_compressor_catchup_threshold_divisor = 50;
887 	}
888 #endif /* !XNU_TARGET_OS_OSX */
889 
890 	queue_init(&c_bad_list_head);
891 	queue_init(&c_age_list_head);
892 	queue_init(&c_minor_list_head);
893 	queue_init(&c_major_list_head);
894 	queue_init(&c_filling_list_head);
895 	queue_init(&c_swapout_list_head);
896 	queue_init(&c_swapio_list_head);
897 	queue_init(&c_swappedin_list_head);
898 	queue_init(&c_swappedout_list_head);
899 	queue_init(&c_swappedout_sparse_list_head);
900 
901 	c_free_segno_head = -1;
902 	c_segments_available = 0;
903 
904 	compressor_map = kmem_suballoc(kernel_map, &compressor_range.min_address,
905 	    compressor_size, VM_MAP_CREATE_NEVER_FAULTS,
906 	    VM_FLAGS_FIXED_RANGE_SUBALLOC, KMS_NOFAIL | KMS_PERMANENT,
907 	    VM_KERN_MEMORY_COMPRESSOR).kmr_submap;
908 
909 	kmem_alloc(compressor_map, (vm_offset_t *)(&c_segments),
910 	    (sizeof(union c_segu) * c_segments_limit),
911 	    KMA_NOFAIL | KMA_KOBJECT | KMA_VAONLY | KMA_PERMANENT,
912 	    VM_KERN_MEMORY_COMPRESSOR);
913 	kmem_alloc(compressor_map, &c_buffers, c_buffers_size,
914 	    KMA_NOFAIL | KMA_COMPRESSOR | KMA_VAONLY | KMA_PERMANENT,
915 	    VM_KERN_MEMORY_COMPRESSOR);
916 
917 #if DEVELOPMENT || DEBUG
918 	hvg_hcall_set_coredump_data();
919 #endif
920 
921 	/*
922 	 * Pick a good size that will minimize fragmentation in zalloc
923 	 * by minimizing the fragmentation in a 16k run.
924 	 *
925 	 * c_seg_slot_var_array_min_len is larger on 4k systems than 16k ones,
926 	 * making the fragmentation in a 4k page terrible. Using 16k for all
927 	 * systems matches zalloc() and will minimize fragmentation.
928 	 */
929 	uint32_t c_segment_size = sizeof(struct c_segment) + (c_seg_slot_var_array_min_len * sizeof(struct c_slot));
930 	uint32_t cnt  = (16 << 10) / c_segment_size;
931 	uint32_t frag = (16 << 10) % c_segment_size;
932 
933 	c_seg_fixed_array_len = c_seg_slot_var_array_min_len;
934 
935 	while (cnt * sizeof(struct c_slot) < frag) {
936 		c_segment_size += sizeof(struct c_slot);
937 		c_seg_fixed_array_len++;
938 		frag -= cnt * sizeof(struct c_slot);
939 	}
940 
941 	compressor_segment_zone = zone_create("compressor_segment",
942 	    c_segment_size, ZC_PGZ_USE_GUARDS | ZC_NOENCRYPT | ZC_ZFREE_CLEARMEM);
943 
944 	c_segments_busy = FALSE;
945 
946 	c_segments_next_page = (caddr_t)c_segments;
947 	vm_compressor_algorithm_init();
948 
949 	{
950 		host_basic_info_data_t hinfo;
951 		mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
952 		size_t bufsize;
953 		char *buf;
954 
955 #define BSD_HOST 1
956 		host_info((host_t)BSD_HOST, HOST_BASIC_INFO, (host_info_t)&hinfo, &count);
957 
958 		compressor_cpus = hinfo.max_cpus;
959 
960 		bufsize = PAGE_SIZE;
961 		bufsize += compressor_cpus * vm_compressor_get_decode_scratch_size();
962 		/* For the KDP path */
963 		bufsize += vm_compressor_get_decode_scratch_size();
964 #if CONFIG_FREEZE
965 		bufsize += vm_compressor_get_encode_scratch_size();
966 #endif
967 #if RECORD_THE_COMPRESSED_DATA
968 		bufsize += c_compressed_record_sbuf_size;
969 #endif
970 
971 		kmem_alloc(kernel_map, (vm_offset_t *)&buf, bufsize,
972 		    KMA_DATA | KMA_NOFAIL | KMA_KOBJECT | KMA_PERMANENT,
973 		    VM_KERN_MEMORY_COMPRESSOR);
974 
975 		/*
976 		 * kdp_compressor_decompressed_page must be page aligned because we access
977 		 * it through the physical aperture by page number.
978 		 */
979 		kdp_compressor_decompressed_page = buf;
980 		kdp_compressor_decompressed_page_paddr = kvtophys((vm_offset_t)kdp_compressor_decompressed_page);
981 		kdp_compressor_decompressed_page_ppnum = (ppnum_t) atop(kdp_compressor_decompressed_page_paddr);
982 		buf += PAGE_SIZE;
983 		bufsize -= PAGE_SIZE;
984 
985 		compressor_scratch_bufs = buf;
986 		buf += compressor_cpus * vm_compressor_get_decode_scratch_size();
987 		bufsize -= compressor_cpus * vm_compressor_get_decode_scratch_size();
988 
989 		kdp_compressor_scratch_buf = buf;
990 		buf += vm_compressor_get_decode_scratch_size();
991 		bufsize -= vm_compressor_get_decode_scratch_size();
992 
993 #if CONFIG_FREEZE
994 		freezer_context_global.freezer_ctx_compressor_scratch_buf = buf;
995 		buf += vm_compressor_get_encode_scratch_size();
996 		bufsize -= vm_compressor_get_encode_scratch_size();
997 #endif
998 
999 #if RECORD_THE_COMPRESSED_DATA
1000 		c_compressed_record_sbuf = buf;
1001 		c_compressed_record_cptr = buf;
1002 		c_compressed_record_ebuf = c_compressed_record_sbuf + c_compressed_record_sbuf_size;
1003 		buf += c_compressed_record_sbuf_size;
1004 		bufsize -= c_compressed_record_sbuf_size;
1005 #endif
1006 		assert(bufsize == 0);
1007 	}
1008 
1009 	if (kernel_thread_start_priority((thread_continue_t)vm_compressor_swap_trigger_thread, NULL,
1010 	    BASEPRI_VM, &thread) != KERN_SUCCESS) {
1011 		panic("vm_compressor_swap_trigger_thread: create failed");
1012 	}
1013 	thread_deallocate(thread);
1014 
1015 	if (vm_pageout_internal_start() != KERN_SUCCESS) {
1016 		panic("vm_compressor_init: Failed to start the internal pageout thread.");
1017 	}
1018 	if (VM_CONFIG_SWAP_IS_PRESENT) {
1019 		vm_compressor_swap_init();
1020 	}
1021 
1022 	if (VM_CONFIG_COMPRESSOR_IS_ACTIVE) {
1023 		vm_compressor_is_active = 1;
1024 	}
1025 
1026 #if CONFIG_FREEZE
1027 	memorystatus_freeze_enabled = TRUE;
1028 #endif /* CONFIG_FREEZE */
1029 
1030 	vm_compressor_available = 1;
1031 
1032 	vm_page_reactivate_all_throttled();
1033 
1034 	bzero(&vmcs_stats, sizeof(struct vm_compressor_swapper_stats));
1035 }
1036 
1037 
1038 #if VALIDATE_C_SEGMENTS
1039 
1040 static void
c_seg_validate(c_segment_t c_seg,boolean_t must_be_compact)1041 c_seg_validate(c_segment_t c_seg, boolean_t must_be_compact)
1042 {
1043 	uint16_t        c_indx;
1044 	int32_t         bytes_used;
1045 	uint32_t        c_rounded_size;
1046 	uint32_t        c_size;
1047 	c_slot_t        cs;
1048 
1049 	if (__probable(validate_c_segs == FALSE)) {
1050 		return;
1051 	}
1052 	if (c_seg->c_firstemptyslot < c_seg->c_nextslot) {
1053 		c_indx = c_seg->c_firstemptyslot;
1054 		cs = C_SEG_SLOT_FROM_INDEX(c_seg, c_indx);
1055 
1056 		if (cs == NULL) {
1057 			panic("c_seg_validate:  no slot backing c_firstemptyslot");
1058 		}
1059 
1060 		if (cs->c_size) {
1061 			panic("c_seg_validate:  c_firstemptyslot has non-zero size (%d)", cs->c_size);
1062 		}
1063 	}
1064 	bytes_used = 0;
1065 
1066 	for (c_indx = 0; c_indx < c_seg->c_nextslot; c_indx++) {
1067 		cs = C_SEG_SLOT_FROM_INDEX(c_seg, c_indx);
1068 
1069 		c_size = UNPACK_C_SIZE(cs);
1070 
1071 		c_rounded_size = (c_size + C_SEG_OFFSET_ALIGNMENT_MASK) & ~C_SEG_OFFSET_ALIGNMENT_MASK;
1072 
1073 		bytes_used += c_rounded_size;
1074 
1075 #if CHECKSUM_THE_COMPRESSED_DATA
1076 		unsigned csvhash;
1077 		if (c_size && cs->c_hash_compressed_data != (csvhash = vmc_hash((char *)&c_seg->c_store.c_buffer[cs->c_offset], c_size))) {
1078 			addr64_t csvphys = kvtophys((vm_offset_t)&c_seg->c_store.c_buffer[cs->c_offset]);
1079 			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);
1080 		}
1081 #endif
1082 #if POPCOUNT_THE_COMPRESSED_DATA
1083 		unsigned csvpop;
1084 		if (c_size) {
1085 			uintptr_t csvaddr = (uintptr_t) &c_seg->c_store.c_buffer[cs->c_offset];
1086 			if (cs->c_pop_cdata != (csvpop = vmc_pop(csvaddr, c_size))) {
1087 				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);
1088 			}
1089 		}
1090 #endif
1091 	}
1092 
1093 	if (bytes_used != c_seg->c_bytes_used) {
1094 		panic("c_seg_validate: bytes_used mismatch - found %d, segment has %d", bytes_used, c_seg->c_bytes_used);
1095 	}
1096 
1097 	if (c_seg->c_bytes_used > C_SEG_OFFSET_TO_BYTES((int32_t)c_seg->c_nextoffset)) {
1098 		panic("c_seg_validate: c_bytes_used > c_nextoffset - c_nextoffset = %d,  c_bytes_used = %d",
1099 		    (int32_t)C_SEG_OFFSET_TO_BYTES((int32_t)c_seg->c_nextoffset), c_seg->c_bytes_used);
1100 	}
1101 
1102 	if (must_be_compact) {
1103 		if (c_seg->c_bytes_used != C_SEG_OFFSET_TO_BYTES((int32_t)c_seg->c_nextoffset)) {
1104 			panic("c_seg_validate: c_bytes_used doesn't match c_nextoffset - c_nextoffset = %d,  c_bytes_used = %d",
1105 			    (int32_t)C_SEG_OFFSET_TO_BYTES((int32_t)c_seg->c_nextoffset), c_seg->c_bytes_used);
1106 		}
1107 	}
1108 }
1109 
1110 #endif
1111 
1112 
1113 void
c_seg_need_delayed_compaction(c_segment_t c_seg,boolean_t c_list_lock_held)1114 c_seg_need_delayed_compaction(c_segment_t c_seg, boolean_t c_list_lock_held)
1115 {
1116 	boolean_t       clear_busy = FALSE;
1117 
1118 	if (c_list_lock_held == FALSE) {
1119 		if (!lck_mtx_try_lock_spin_always(c_list_lock)) {
1120 			C_SEG_BUSY(c_seg);
1121 
1122 			lck_mtx_unlock_always(&c_seg->c_lock);
1123 			lck_mtx_lock_spin_always(c_list_lock);
1124 			lck_mtx_lock_spin_always(&c_seg->c_lock);
1125 
1126 			clear_busy = TRUE;
1127 		}
1128 	}
1129 	assert(c_seg->c_state != C_IS_FILLING);
1130 
1131 	if (!c_seg->c_on_minorcompact_q && !(C_SEG_IS_ON_DISK_OR_SOQ(c_seg))) {
1132 		queue_enter(&c_minor_list_head, c_seg, c_segment_t, c_list);
1133 		c_seg->c_on_minorcompact_q = 1;
1134 		c_minor_count++;
1135 	}
1136 	if (c_list_lock_held == FALSE) {
1137 		lck_mtx_unlock_always(c_list_lock);
1138 	}
1139 
1140 	if (clear_busy == TRUE) {
1141 		C_SEG_WAKEUP_DONE(c_seg);
1142 	}
1143 }
1144 
1145 
1146 unsigned int c_seg_moved_to_sparse_list = 0;
1147 
1148 void
c_seg_move_to_sparse_list(c_segment_t c_seg)1149 c_seg_move_to_sparse_list(c_segment_t c_seg)
1150 {
1151 	boolean_t       clear_busy = FALSE;
1152 
1153 	if (!lck_mtx_try_lock_spin_always(c_list_lock)) {
1154 		C_SEG_BUSY(c_seg);
1155 
1156 		lck_mtx_unlock_always(&c_seg->c_lock);
1157 		lck_mtx_lock_spin_always(c_list_lock);
1158 		lck_mtx_lock_spin_always(&c_seg->c_lock);
1159 
1160 		clear_busy = TRUE;
1161 	}
1162 	c_seg_switch_state(c_seg, C_ON_SWAPPEDOUTSPARSE_Q, FALSE);
1163 
1164 	c_seg_moved_to_sparse_list++;
1165 
1166 	lck_mtx_unlock_always(c_list_lock);
1167 
1168 	if (clear_busy == TRUE) {
1169 		C_SEG_WAKEUP_DONE(c_seg);
1170 	}
1171 }
1172 
1173 
1174 void
c_seg_insert_into_q(queue_head_t * qhead,c_segment_t c_seg)1175 c_seg_insert_into_q(queue_head_t *qhead, c_segment_t c_seg)
1176 {
1177 	c_segment_t c_seg_next;
1178 
1179 	if (queue_empty(qhead)) {
1180 		queue_enter(qhead, c_seg, c_segment_t, c_age_list);
1181 	} else {
1182 		c_seg_next = (c_segment_t)queue_first(qhead);
1183 
1184 		while (TRUE) {
1185 			if (c_seg->c_generation_id < c_seg_next->c_generation_id) {
1186 				queue_insert_before(qhead, c_seg, c_seg_next, c_segment_t, c_age_list);
1187 				break;
1188 			}
1189 			c_seg_next = (c_segment_t) queue_next(&c_seg_next->c_age_list);
1190 
1191 			if (queue_end(qhead, (queue_entry_t) c_seg_next)) {
1192 				queue_enter(qhead, c_seg, c_segment_t, c_age_list);
1193 				break;
1194 			}
1195 		}
1196 	}
1197 }
1198 
1199 
1200 int try_minor_compaction_failed = 0;
1201 int try_minor_compaction_succeeded = 0;
1202 
1203 void
c_seg_try_minor_compaction_and_unlock(c_segment_t c_seg)1204 c_seg_try_minor_compaction_and_unlock(c_segment_t c_seg)
1205 {
1206 	assert(c_seg->c_on_minorcompact_q);
1207 	/*
1208 	 * c_seg is currently on the delayed minor compaction
1209 	 * queue and we have c_seg locked... if we can get the
1210 	 * c_list_lock w/o blocking (if we blocked we could deadlock
1211 	 * because the lock order is c_list_lock then c_seg's lock)
1212 	 * we'll pull it from the delayed list and free it directly
1213 	 */
1214 	if (!lck_mtx_try_lock_spin_always(c_list_lock)) {
1215 		/*
1216 		 * c_list_lock is held, we need to bail
1217 		 */
1218 		try_minor_compaction_failed++;
1219 
1220 		lck_mtx_unlock_always(&c_seg->c_lock);
1221 	} else {
1222 		try_minor_compaction_succeeded++;
1223 
1224 		C_SEG_BUSY(c_seg);
1225 		c_seg_do_minor_compaction_and_unlock(c_seg, TRUE, FALSE, FALSE);
1226 	}
1227 }
1228 
1229 
1230 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)1231 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)
1232 {
1233 	int     c_seg_freed;
1234 
1235 	assert(c_seg->c_busy);
1236 	assert(!C_SEG_IS_ON_DISK_OR_SOQ(c_seg));
1237 
1238 	/*
1239 	 * check for the case that can occur when we are not swapping
1240 	 * and this segment has been major compacted in the past
1241 	 * and moved to the majorcompact q to remove it from further
1242 	 * consideration... if the occupancy falls too low we need
1243 	 * to put it back on the age_q so that it will be considered
1244 	 * in the next major compaction sweep... if we don't do this
1245 	 * we will eventually run into the c_segments_limit
1246 	 */
1247 	if (c_seg->c_state == C_ON_MAJORCOMPACT_Q && C_SEG_SHOULD_MAJORCOMPACT_NOW(c_seg)) {
1248 		c_seg_switch_state(c_seg, C_ON_AGE_Q, FALSE);
1249 	}
1250 	if (!c_seg->c_on_minorcompact_q) {
1251 		if (clear_busy == TRUE) {
1252 			C_SEG_WAKEUP_DONE(c_seg);
1253 		}
1254 
1255 		lck_mtx_unlock_always(&c_seg->c_lock);
1256 
1257 		return 0;
1258 	}
1259 	queue_remove(&c_minor_list_head, c_seg, c_segment_t, c_list);
1260 	c_seg->c_on_minorcompact_q = 0;
1261 	c_minor_count--;
1262 
1263 	lck_mtx_unlock_always(c_list_lock);
1264 
1265 	if (disallow_page_replacement == TRUE) {
1266 		lck_mtx_unlock_always(&c_seg->c_lock);
1267 
1268 		PAGE_REPLACEMENT_DISALLOWED(TRUE);
1269 
1270 		lck_mtx_lock_spin_always(&c_seg->c_lock);
1271 	}
1272 	c_seg_freed = c_seg_minor_compaction_and_unlock(c_seg, clear_busy);
1273 
1274 	if (disallow_page_replacement == TRUE) {
1275 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
1276 	}
1277 
1278 	if (need_list_lock == TRUE) {
1279 		lck_mtx_lock_spin_always(c_list_lock);
1280 	}
1281 
1282 	return c_seg_freed;
1283 }
1284 
1285 void
kdp_compressor_busy_find_owner(event64_t wait_event,thread_waitinfo_t * waitinfo)1286 kdp_compressor_busy_find_owner(event64_t wait_event, thread_waitinfo_t *waitinfo)
1287 {
1288 	c_segment_t c_seg = (c_segment_t) wait_event;
1289 
1290 	waitinfo->owner = thread_tid(c_seg->c_busy_for_thread);
1291 	waitinfo->context = VM_KERNEL_UNSLIDE_OR_PERM(c_seg);
1292 }
1293 
1294 #if DEVELOPMENT || DEBUG
1295 int
do_cseg_wedge_thread(void)1296 do_cseg_wedge_thread(void)
1297 {
1298 	struct c_segment c_seg;
1299 	c_seg.c_busy_for_thread = current_thread();
1300 
1301 	debug_cseg_wait_event = (event_t) &c_seg;
1302 
1303 	thread_set_pending_block_hint(current_thread(), kThreadWaitCompressor);
1304 	assert_wait((event_t) (&c_seg), THREAD_INTERRUPTIBLE);
1305 
1306 	thread_block(THREAD_CONTINUE_NULL);
1307 
1308 	return 0;
1309 }
1310 
1311 int
do_cseg_unwedge_thread(void)1312 do_cseg_unwedge_thread(void)
1313 {
1314 	thread_wakeup(debug_cseg_wait_event);
1315 	debug_cseg_wait_event = NULL;
1316 
1317 	return 0;
1318 }
1319 #endif /* DEVELOPMENT || DEBUG */
1320 
1321 void
c_seg_wait_on_busy(c_segment_t c_seg)1322 c_seg_wait_on_busy(c_segment_t c_seg)
1323 {
1324 	c_seg->c_wanted = 1;
1325 
1326 	thread_set_pending_block_hint(current_thread(), kThreadWaitCompressor);
1327 	assert_wait((event_t) (c_seg), THREAD_UNINT);
1328 
1329 	lck_mtx_unlock_always(&c_seg->c_lock);
1330 	thread_block(THREAD_CONTINUE_NULL);
1331 }
1332 
1333 #if CONFIG_FREEZE
1334 /*
1335  * We don't have the task lock held while updating the task's
1336  * c_seg queues. We can do that because of the following restrictions:
1337  *
1338  * - SINGLE FREEZER CONTEXT:
1339  *   We 'insert' c_segs into the task list on the task_freeze path.
1340  *   There can only be one such freeze in progress and the task
1341  *   isn't disappearing because we have the VM map lock held throughout
1342  *   and we have a reference on the proc too.
1343  *
1344  * - SINGLE TASK DISOWN CONTEXT:
1345  *   We 'disown' c_segs of a task ONLY from the task_terminate context. So
1346  *   we don't need the task lock but we need the c_list_lock and the
1347  *   compressor master lock (shared). We also hold the individual
1348  *   c_seg locks (exclusive).
1349  *
1350  *   If we either:
1351  *   - can't get the c_seg lock on a try, then we start again because maybe
1352  *   the c_seg is part of a compaction and might get freed. So we can't trust
1353  *   that linkage and need to restart our queue traversal.
1354  *   - OR, we run into a busy c_seg (say being swapped in or free-ing) we
1355  *   drop all locks again and wait and restart our queue traversal.
1356  *
1357  * - The new_owner_task below is currently only the kernel or NULL.
1358  *
1359  */
1360 void
c_seg_update_task_owner(c_segment_t c_seg,task_t new_owner_task)1361 c_seg_update_task_owner(c_segment_t c_seg, task_t new_owner_task)
1362 {
1363 	task_t          owner_task = c_seg->c_task_owner;
1364 	uint64_t        uncompressed_bytes = ((c_seg->c_slots_used) * PAGE_SIZE_64);
1365 
1366 	LCK_MTX_ASSERT(c_list_lock, LCK_MTX_ASSERT_OWNED);
1367 	LCK_MTX_ASSERT(&c_seg->c_lock, LCK_MTX_ASSERT_OWNED);
1368 
1369 	if (owner_task) {
1370 		task_update_frozen_to_swap_acct(owner_task, uncompressed_bytes, DEBIT_FROM_SWAP);
1371 		queue_remove(&owner_task->task_frozen_cseg_q, c_seg,
1372 		    c_segment_t, c_task_list_next_cseg);
1373 	}
1374 
1375 	if (new_owner_task) {
1376 		queue_enter(&new_owner_task->task_frozen_cseg_q, c_seg,
1377 		    c_segment_t, c_task_list_next_cseg);
1378 		task_update_frozen_to_swap_acct(new_owner_task, uncompressed_bytes, CREDIT_TO_SWAP);
1379 	}
1380 
1381 	c_seg->c_task_owner = new_owner_task;
1382 }
1383 
1384 void
task_disown_frozen_csegs(task_t owner_task)1385 task_disown_frozen_csegs(task_t owner_task)
1386 {
1387 	c_segment_t c_seg = NULL, next_cseg = NULL;
1388 
1389 again:
1390 	PAGE_REPLACEMENT_DISALLOWED(TRUE);
1391 	lck_mtx_lock_spin_always(c_list_lock);
1392 
1393 	for (c_seg = (c_segment_t) queue_first(&owner_task->task_frozen_cseg_q);
1394 	    !queue_end(&owner_task->task_frozen_cseg_q, (queue_entry_t) c_seg);
1395 	    c_seg = next_cseg) {
1396 		next_cseg = (c_segment_t) queue_next(&c_seg->c_task_list_next_cseg);
1397 
1398 		if (!lck_mtx_try_lock_spin_always(&c_seg->c_lock)) {
1399 			lck_mtx_unlock(c_list_lock);
1400 			PAGE_REPLACEMENT_DISALLOWED(FALSE);
1401 			goto again;
1402 		}
1403 
1404 		if (c_seg->c_busy) {
1405 			lck_mtx_unlock(c_list_lock);
1406 			PAGE_REPLACEMENT_DISALLOWED(FALSE);
1407 
1408 			c_seg_wait_on_busy(c_seg);
1409 
1410 			goto again;
1411 		}
1412 		assert(c_seg->c_task_owner == owner_task);
1413 		c_seg_update_task_owner(c_seg, kernel_task);
1414 		lck_mtx_unlock_always(&c_seg->c_lock);
1415 	}
1416 
1417 	lck_mtx_unlock(c_list_lock);
1418 	PAGE_REPLACEMENT_DISALLOWED(FALSE);
1419 }
1420 #endif /* CONFIG_FREEZE */
1421 
1422 void
c_seg_switch_state(c_segment_t c_seg,int new_state,boolean_t insert_head)1423 c_seg_switch_state(c_segment_t c_seg, int new_state, boolean_t insert_head)
1424 {
1425 	int     old_state = c_seg->c_state;
1426 
1427 #if XNU_TARGET_OS_OSX
1428 #if     DEVELOPMENT || DEBUG
1429 	if (new_state != C_IS_FILLING) {
1430 		LCK_MTX_ASSERT(&c_seg->c_lock, LCK_MTX_ASSERT_OWNED);
1431 	}
1432 	LCK_MTX_ASSERT(c_list_lock, LCK_MTX_ASSERT_OWNED);
1433 #endif
1434 #endif /* XNU_TARGET_OS_OSX */
1435 	switch (old_state) {
1436 	case C_IS_EMPTY:
1437 		assert(new_state == C_IS_FILLING || new_state == C_IS_FREE);
1438 
1439 		c_empty_count--;
1440 		break;
1441 
1442 	case C_IS_FILLING:
1443 		assert(new_state == C_ON_AGE_Q || new_state == C_ON_SWAPOUT_Q);
1444 
1445 		queue_remove(&c_filling_list_head, c_seg, c_segment_t, c_age_list);
1446 		c_filling_count--;
1447 		break;
1448 
1449 	case C_ON_AGE_Q:
1450 		assert(new_state == C_ON_SWAPOUT_Q || new_state == C_ON_MAJORCOMPACT_Q ||
1451 		    new_state == C_IS_FREE);
1452 
1453 		queue_remove(&c_age_list_head, c_seg, c_segment_t, c_age_list);
1454 		c_age_count--;
1455 		break;
1456 
1457 	case C_ON_SWAPPEDIN_Q:
1458 		assert(new_state == C_ON_AGE_Q || new_state == C_IS_FREE);
1459 
1460 		queue_remove(&c_swappedin_list_head, c_seg, c_segment_t, c_age_list);
1461 		c_swappedin_count--;
1462 		break;
1463 
1464 	case C_ON_SWAPOUT_Q:
1465 		assert(new_state == C_ON_AGE_Q || new_state == C_IS_FREE || new_state == C_IS_EMPTY || new_state == C_ON_SWAPIO_Q);
1466 
1467 #if CONFIG_FREEZE
1468 		if (c_seg->c_task_owner && (new_state != C_ON_SWAPIO_Q)) {
1469 			c_seg_update_task_owner(c_seg, NULL);
1470 		}
1471 #endif /* CONFIG_FREEZE */
1472 
1473 		queue_remove(&c_swapout_list_head, c_seg, c_segment_t, c_age_list);
1474 		thread_wakeup((event_t)&compaction_swapper_running);
1475 		c_swapout_count--;
1476 		break;
1477 
1478 	case C_ON_SWAPIO_Q:
1479 		assert(new_state == C_ON_SWAPPEDOUT_Q || new_state == C_ON_SWAPPEDOUTSPARSE_Q || new_state == C_ON_AGE_Q);
1480 
1481 		queue_remove(&c_swapio_list_head, c_seg, c_segment_t, c_age_list);
1482 		c_swapio_count--;
1483 		break;
1484 
1485 	case C_ON_SWAPPEDOUT_Q:
1486 		assert(new_state == C_ON_SWAPPEDIN_Q || new_state == C_ON_AGE_Q ||
1487 		    new_state == C_ON_SWAPPEDOUTSPARSE_Q ||
1488 		    new_state == C_ON_BAD_Q || new_state == C_IS_EMPTY || new_state == C_IS_FREE);
1489 
1490 		queue_remove(&c_swappedout_list_head, c_seg, c_segment_t, c_age_list);
1491 		c_swappedout_count--;
1492 		break;
1493 
1494 	case C_ON_SWAPPEDOUTSPARSE_Q:
1495 		assert(new_state == C_ON_SWAPPEDIN_Q || new_state == C_ON_AGE_Q ||
1496 		    new_state == C_ON_BAD_Q || new_state == C_IS_EMPTY || new_state == C_IS_FREE);
1497 
1498 		queue_remove(&c_swappedout_sparse_list_head, c_seg, c_segment_t, c_age_list);
1499 		c_swappedout_sparse_count--;
1500 		break;
1501 
1502 	case C_ON_MAJORCOMPACT_Q:
1503 		assert(new_state == C_ON_AGE_Q || new_state == C_IS_FREE);
1504 
1505 		queue_remove(&c_major_list_head, c_seg, c_segment_t, c_age_list);
1506 		c_major_count--;
1507 		break;
1508 
1509 	case C_ON_BAD_Q:
1510 		assert(new_state == C_IS_FREE);
1511 
1512 		queue_remove(&c_bad_list_head, c_seg, c_segment_t, c_age_list);
1513 		c_bad_count--;
1514 		break;
1515 
1516 	default:
1517 		panic("c_seg %p has bad c_state = %d", c_seg, old_state);
1518 	}
1519 
1520 	switch (new_state) {
1521 	case C_IS_FREE:
1522 		assert(old_state != C_IS_FILLING);
1523 
1524 		break;
1525 
1526 	case C_IS_EMPTY:
1527 		assert(old_state == C_ON_SWAPOUT_Q || old_state == C_ON_SWAPPEDOUT_Q || old_state == C_ON_SWAPPEDOUTSPARSE_Q);
1528 
1529 		c_empty_count++;
1530 		break;
1531 
1532 	case C_IS_FILLING:
1533 		assert(old_state == C_IS_EMPTY);
1534 
1535 		queue_enter(&c_filling_list_head, c_seg, c_segment_t, c_age_list);
1536 		c_filling_count++;
1537 		break;
1538 
1539 	case C_ON_AGE_Q:
1540 		assert(old_state == C_IS_FILLING || old_state == C_ON_SWAPPEDIN_Q ||
1541 		    old_state == C_ON_SWAPOUT_Q || old_state == C_ON_SWAPIO_Q ||
1542 		    old_state == C_ON_MAJORCOMPACT_Q || old_state == C_ON_SWAPPEDOUT_Q || old_state == C_ON_SWAPPEDOUTSPARSE_Q);
1543 
1544 		if (old_state == C_IS_FILLING) {
1545 			queue_enter(&c_age_list_head, c_seg, c_segment_t, c_age_list);
1546 		} else {
1547 			if (!queue_empty(&c_age_list_head)) {
1548 				c_segment_t     c_first;
1549 
1550 				c_first = (c_segment_t)queue_first(&c_age_list_head);
1551 				c_seg->c_creation_ts = c_first->c_creation_ts;
1552 			}
1553 			queue_enter_first(&c_age_list_head, c_seg, c_segment_t, c_age_list);
1554 		}
1555 		c_age_count++;
1556 		break;
1557 
1558 	case C_ON_SWAPPEDIN_Q:
1559 		assert(old_state == C_ON_SWAPPEDOUT_Q || old_state == C_ON_SWAPPEDOUTSPARSE_Q);
1560 
1561 		if (insert_head == TRUE) {
1562 			queue_enter_first(&c_swappedin_list_head, c_seg, c_segment_t, c_age_list);
1563 		} else {
1564 			queue_enter(&c_swappedin_list_head, c_seg, c_segment_t, c_age_list);
1565 		}
1566 		c_swappedin_count++;
1567 		break;
1568 
1569 	case C_ON_SWAPOUT_Q:
1570 		assert(old_state == C_ON_AGE_Q || old_state == C_IS_FILLING);
1571 
1572 		if (insert_head == TRUE) {
1573 			queue_enter_first(&c_swapout_list_head, c_seg, c_segment_t, c_age_list);
1574 		} else {
1575 			queue_enter(&c_swapout_list_head, c_seg, c_segment_t, c_age_list);
1576 		}
1577 		c_swapout_count++;
1578 		break;
1579 
1580 	case C_ON_SWAPIO_Q:
1581 		assert(old_state == C_ON_SWAPOUT_Q);
1582 
1583 		if (insert_head == TRUE) {
1584 			queue_enter_first(&c_swapio_list_head, c_seg, c_segment_t, c_age_list);
1585 		} else {
1586 			queue_enter(&c_swapio_list_head, c_seg, c_segment_t, c_age_list);
1587 		}
1588 		c_swapio_count++;
1589 		break;
1590 
1591 	case C_ON_SWAPPEDOUT_Q:
1592 		assert(old_state == C_ON_SWAPIO_Q);
1593 
1594 		if (insert_head == TRUE) {
1595 			queue_enter_first(&c_swappedout_list_head, c_seg, c_segment_t, c_age_list);
1596 		} else {
1597 			queue_enter(&c_swappedout_list_head, c_seg, c_segment_t, c_age_list);
1598 		}
1599 		c_swappedout_count++;
1600 		break;
1601 
1602 	case C_ON_SWAPPEDOUTSPARSE_Q:
1603 		assert(old_state == C_ON_SWAPIO_Q || old_state == C_ON_SWAPPEDOUT_Q);
1604 
1605 		if (insert_head == TRUE) {
1606 			queue_enter_first(&c_swappedout_sparse_list_head, c_seg, c_segment_t, c_age_list);
1607 		} else {
1608 			queue_enter(&c_swappedout_sparse_list_head, c_seg, c_segment_t, c_age_list);
1609 		}
1610 
1611 		c_swappedout_sparse_count++;
1612 		break;
1613 
1614 	case C_ON_MAJORCOMPACT_Q:
1615 		assert(old_state == C_ON_AGE_Q);
1616 
1617 		if (insert_head == TRUE) {
1618 			queue_enter_first(&c_major_list_head, c_seg, c_segment_t, c_age_list);
1619 		} else {
1620 			queue_enter(&c_major_list_head, c_seg, c_segment_t, c_age_list);
1621 		}
1622 		c_major_count++;
1623 		break;
1624 
1625 	case C_ON_BAD_Q:
1626 		assert(old_state == C_ON_SWAPPEDOUT_Q || old_state == C_ON_SWAPPEDOUTSPARSE_Q);
1627 
1628 		if (insert_head == TRUE) {
1629 			queue_enter_first(&c_bad_list_head, c_seg, c_segment_t, c_age_list);
1630 		} else {
1631 			queue_enter(&c_bad_list_head, c_seg, c_segment_t, c_age_list);
1632 		}
1633 		c_bad_count++;
1634 		break;
1635 
1636 	default:
1637 		panic("c_seg %p requesting bad c_state = %d", c_seg, new_state);
1638 	}
1639 	c_seg->c_state = new_state;
1640 }
1641 
1642 
1643 
1644 void
c_seg_free(c_segment_t c_seg)1645 c_seg_free(c_segment_t c_seg)
1646 {
1647 	assert(c_seg->c_busy);
1648 
1649 	lck_mtx_unlock_always(&c_seg->c_lock);
1650 	lck_mtx_lock_spin_always(c_list_lock);
1651 	lck_mtx_lock_spin_always(&c_seg->c_lock);
1652 
1653 	c_seg_free_locked(c_seg);
1654 }
1655 
1656 
1657 void
c_seg_free_locked(c_segment_t c_seg)1658 c_seg_free_locked(c_segment_t c_seg)
1659 {
1660 	int             segno;
1661 	int             pages_populated = 0;
1662 	int32_t         *c_buffer = NULL;
1663 	uint64_t        c_swap_handle = 0;
1664 
1665 	assert(c_seg->c_busy);
1666 	assert(c_seg->c_slots_used == 0);
1667 	assert(!c_seg->c_on_minorcompact_q);
1668 	assert(!c_seg->c_busy_swapping);
1669 
1670 	if (c_seg->c_overage_swap == TRUE) {
1671 		c_overage_swapped_count--;
1672 		c_seg->c_overage_swap = FALSE;
1673 	}
1674 	if (!(C_SEG_IS_ONDISK(c_seg))) {
1675 		c_buffer = c_seg->c_store.c_buffer;
1676 	} else {
1677 		c_swap_handle = c_seg->c_store.c_swap_handle;
1678 	}
1679 
1680 	c_seg_switch_state(c_seg, C_IS_FREE, FALSE);
1681 
1682 	if (c_buffer) {
1683 		pages_populated = (round_page_32(C_SEG_OFFSET_TO_BYTES(c_seg->c_populated_offset))) / PAGE_SIZE;
1684 		c_seg->c_store.c_buffer = NULL;
1685 	} else {
1686 #if CONFIG_FREEZE
1687 		c_seg_update_task_owner(c_seg, NULL);
1688 #endif /* CONFIG_FREEZE */
1689 
1690 		c_seg->c_store.c_swap_handle = (uint64_t)-1;
1691 	}
1692 
1693 	lck_mtx_unlock_always(&c_seg->c_lock);
1694 
1695 	lck_mtx_unlock_always(c_list_lock);
1696 
1697 	if (c_buffer) {
1698 		if (pages_populated) {
1699 			kernel_memory_depopulate((vm_offset_t)c_buffer,
1700 			    ptoa(pages_populated), KMA_COMPRESSOR,
1701 			    VM_KERN_MEMORY_COMPRESSOR);
1702 		}
1703 	} else if (c_swap_handle) {
1704 		/*
1705 		 * Free swap space on disk.
1706 		 */
1707 		vm_swap_free(c_swap_handle);
1708 	}
1709 	lck_mtx_lock_spin_always(&c_seg->c_lock);
1710 	/*
1711 	 * c_seg must remain busy until
1712 	 * after the call to vm_swap_free
1713 	 */
1714 	C_SEG_WAKEUP_DONE(c_seg);
1715 	lck_mtx_unlock_always(&c_seg->c_lock);
1716 
1717 	segno = c_seg->c_mysegno;
1718 
1719 	lck_mtx_lock_spin_always(c_list_lock);
1720 	/*
1721 	 * because the c_buffer is now associated with the segno,
1722 	 * we can't put the segno back on the free list until
1723 	 * after we have depopulated the c_buffer range, or
1724 	 * we run the risk of depopulating a range that is
1725 	 * now being used in one of the compressor heads
1726 	 */
1727 	c_segments[segno].c_segno = c_free_segno_head;
1728 	c_free_segno_head = segno;
1729 	c_segment_count--;
1730 
1731 	lck_mtx_unlock_always(c_list_lock);
1732 
1733 	lck_mtx_destroy(&c_seg->c_lock, &vm_compressor_lck_grp);
1734 
1735 	if (c_seg->c_slot_var_array_len) {
1736 		kfree_data(c_seg->c_slot_var_array,
1737 		    sizeof(struct c_slot) * c_seg->c_slot_var_array_len);
1738 	}
1739 
1740 	zfree(compressor_segment_zone, c_seg);
1741 }
1742 
1743 #if DEVELOPMENT || DEBUG
1744 int c_seg_trim_page_count = 0;
1745 #endif
1746 
1747 void
c_seg_trim_tail(c_segment_t c_seg)1748 c_seg_trim_tail(c_segment_t c_seg)
1749 {
1750 	c_slot_t        cs;
1751 	uint32_t        c_size;
1752 	uint32_t        c_offset;
1753 	uint32_t        c_rounded_size;
1754 	uint16_t        current_nextslot;
1755 	uint32_t        current_populated_offset;
1756 
1757 	if (c_seg->c_bytes_used == 0) {
1758 		return;
1759 	}
1760 	current_nextslot = c_seg->c_nextslot;
1761 	current_populated_offset = c_seg->c_populated_offset;
1762 
1763 	while (c_seg->c_nextslot) {
1764 		cs = C_SEG_SLOT_FROM_INDEX(c_seg, (c_seg->c_nextslot - 1));
1765 
1766 		c_size = UNPACK_C_SIZE(cs);
1767 
1768 		if (c_size) {
1769 			if (current_nextslot != c_seg->c_nextslot) {
1770 				c_rounded_size = (c_size + C_SEG_OFFSET_ALIGNMENT_MASK) & ~C_SEG_OFFSET_ALIGNMENT_MASK;
1771 				c_offset = cs->c_offset + C_SEG_BYTES_TO_OFFSET(c_rounded_size);
1772 
1773 				c_seg->c_nextoffset = c_offset;
1774 				c_seg->c_populated_offset = (c_offset + (C_SEG_BYTES_TO_OFFSET(PAGE_SIZE) - 1)) &
1775 				    ~(C_SEG_BYTES_TO_OFFSET(PAGE_SIZE) - 1);
1776 
1777 				if (c_seg->c_firstemptyslot > c_seg->c_nextslot) {
1778 					c_seg->c_firstemptyslot = c_seg->c_nextslot;
1779 				}
1780 #if DEVELOPMENT || DEBUG
1781 				c_seg_trim_page_count += ((round_page_32(C_SEG_OFFSET_TO_BYTES(current_populated_offset)) -
1782 				    round_page_32(C_SEG_OFFSET_TO_BYTES(c_seg->c_populated_offset))) /
1783 				    PAGE_SIZE);
1784 #endif
1785 			}
1786 			break;
1787 		}
1788 		c_seg->c_nextslot--;
1789 	}
1790 	assert(c_seg->c_nextslot);
1791 }
1792 
1793 
1794 int
c_seg_minor_compaction_and_unlock(c_segment_t c_seg,boolean_t clear_busy)1795 c_seg_minor_compaction_and_unlock(c_segment_t c_seg, boolean_t clear_busy)
1796 {
1797 	c_slot_mapping_t slot_ptr;
1798 	uint32_t        c_offset = 0;
1799 	uint32_t        old_populated_offset;
1800 	uint32_t        c_rounded_size;
1801 	uint32_t        c_size;
1802 	uint16_t        c_indx = 0;
1803 	int             i;
1804 	c_slot_t        c_dst;
1805 	c_slot_t        c_src;
1806 
1807 	assert(c_seg->c_busy);
1808 
1809 #if VALIDATE_C_SEGMENTS
1810 	c_seg_validate(c_seg, FALSE);
1811 #endif
1812 	if (c_seg->c_bytes_used == 0) {
1813 		c_seg_free(c_seg);
1814 		return 1;
1815 	}
1816 	lck_mtx_unlock_always(&c_seg->c_lock);
1817 
1818 	if (c_seg->c_firstemptyslot >= c_seg->c_nextslot || C_SEG_UNUSED_BYTES(c_seg) < PAGE_SIZE) {
1819 		goto done;
1820 	}
1821 
1822 /* TODO: assert first emptyslot's c_size is actually 0 */
1823 
1824 #if DEVELOPMENT || DEBUG
1825 	C_SEG_MAKE_WRITEABLE(c_seg);
1826 #endif
1827 
1828 #if VALIDATE_C_SEGMENTS
1829 	c_seg->c_was_minor_compacted++;
1830 #endif
1831 	c_indx = c_seg->c_firstemptyslot;
1832 	c_dst = C_SEG_SLOT_FROM_INDEX(c_seg, c_indx);
1833 
1834 	old_populated_offset = c_seg->c_populated_offset;
1835 	c_offset = c_dst->c_offset;
1836 
1837 	for (i = c_indx + 1; i < c_seg->c_nextslot && c_offset < c_seg->c_nextoffset; i++) {
1838 		c_src = C_SEG_SLOT_FROM_INDEX(c_seg, i);
1839 
1840 		c_size = UNPACK_C_SIZE(c_src);
1841 
1842 		if (c_size == 0) {
1843 			continue;
1844 		}
1845 
1846 		c_rounded_size = (c_size + C_SEG_OFFSET_ALIGNMENT_MASK) & ~C_SEG_OFFSET_ALIGNMENT_MASK;
1847 /* N.B.: This memcpy may be an overlapping copy */
1848 		memcpy(&c_seg->c_store.c_buffer[c_offset], &c_seg->c_store.c_buffer[c_src->c_offset], c_rounded_size);
1849 
1850 		cslot_copy(c_dst, c_src);
1851 		c_dst->c_offset = c_offset;
1852 
1853 		slot_ptr = C_SLOT_UNPACK_PTR(c_dst);
1854 		slot_ptr->s_cindx = c_indx;
1855 
1856 		c_offset += C_SEG_BYTES_TO_OFFSET(c_rounded_size);
1857 		PACK_C_SIZE(c_src, 0);
1858 		c_indx++;
1859 
1860 		c_dst = C_SEG_SLOT_FROM_INDEX(c_seg, c_indx);
1861 	}
1862 	c_seg->c_firstemptyslot = c_indx;
1863 	c_seg->c_nextslot = c_indx;
1864 	c_seg->c_nextoffset = c_offset;
1865 	c_seg->c_populated_offset = (c_offset + (C_SEG_BYTES_TO_OFFSET(PAGE_SIZE) - 1)) & ~(C_SEG_BYTES_TO_OFFSET(PAGE_SIZE) - 1);
1866 	c_seg->c_bytes_unused = 0;
1867 
1868 #if VALIDATE_C_SEGMENTS
1869 	c_seg_validate(c_seg, TRUE);
1870 #endif
1871 	if (old_populated_offset > c_seg->c_populated_offset) {
1872 		uint32_t        gc_size;
1873 		int32_t         *gc_ptr;
1874 
1875 		gc_size = C_SEG_OFFSET_TO_BYTES(old_populated_offset - c_seg->c_populated_offset);
1876 		gc_ptr = &c_seg->c_store.c_buffer[c_seg->c_populated_offset];
1877 
1878 		kernel_memory_depopulate((vm_offset_t)gc_ptr, gc_size,
1879 		    KMA_COMPRESSOR, VM_KERN_MEMORY_COMPRESSOR);
1880 	}
1881 
1882 #if DEVELOPMENT || DEBUG
1883 	C_SEG_WRITE_PROTECT(c_seg);
1884 #endif
1885 
1886 done:
1887 	if (clear_busy == TRUE) {
1888 		lck_mtx_lock_spin_always(&c_seg->c_lock);
1889 		C_SEG_WAKEUP_DONE(c_seg);
1890 		lck_mtx_unlock_always(&c_seg->c_lock);
1891 	}
1892 	return 0;
1893 }
1894 
1895 
1896 static void
c_seg_alloc_nextslot(c_segment_t c_seg)1897 c_seg_alloc_nextslot(c_segment_t c_seg)
1898 {
1899 	struct c_slot   *old_slot_array = NULL;
1900 	struct c_slot   *new_slot_array = NULL;
1901 	int             newlen;
1902 	int             oldlen;
1903 
1904 	if (c_seg->c_nextslot < c_seg_fixed_array_len) {
1905 		return;
1906 	}
1907 
1908 	if ((c_seg->c_nextslot - c_seg_fixed_array_len) >= c_seg->c_slot_var_array_len) {
1909 		oldlen = c_seg->c_slot_var_array_len;
1910 		old_slot_array = c_seg->c_slot_var_array;
1911 
1912 		if (oldlen == 0) {
1913 			newlen = c_seg_slot_var_array_min_len;
1914 		} else {
1915 			newlen = oldlen * 2;
1916 		}
1917 
1918 		new_slot_array = kalloc_data(sizeof(struct c_slot) * newlen,
1919 		    Z_WAITOK);
1920 
1921 		lck_mtx_lock_spin_always(&c_seg->c_lock);
1922 
1923 		if (old_slot_array) {
1924 			memcpy(new_slot_array, old_slot_array,
1925 			    sizeof(struct c_slot) * oldlen);
1926 		}
1927 
1928 		c_seg->c_slot_var_array_len = newlen;
1929 		c_seg->c_slot_var_array = new_slot_array;
1930 
1931 		lck_mtx_unlock_always(&c_seg->c_lock);
1932 
1933 		kfree_data(old_slot_array, sizeof(struct c_slot) * oldlen);
1934 	}
1935 }
1936 
1937 
1938 #define C_SEG_MAJOR_COMPACT_STATS_MAX   (30)
1939 
1940 struct {
1941 	uint64_t asked_permission;
1942 	uint64_t compactions;
1943 	uint64_t moved_slots;
1944 	uint64_t moved_bytes;
1945 	uint64_t wasted_space_in_swapouts;
1946 	uint64_t count_of_swapouts;
1947 	uint64_t count_of_freed_segs;
1948 	uint64_t bailed_compactions;
1949 	uint64_t bytes_freed_rate_us;
1950 } c_seg_major_compact_stats[C_SEG_MAJOR_COMPACT_STATS_MAX];
1951 
1952 int c_seg_major_compact_stats_now = 0;
1953 
1954 
1955 #define C_MAJOR_COMPACTION_SIZE_APPROPRIATE     ((c_seg_bufsize * 90) / 100)
1956 
1957 
1958 boolean_t
c_seg_major_compact_ok(c_segment_t c_seg_dst,c_segment_t c_seg_src)1959 c_seg_major_compact_ok(
1960 	c_segment_t c_seg_dst,
1961 	c_segment_t c_seg_src)
1962 {
1963 	c_seg_major_compact_stats[c_seg_major_compact_stats_now].asked_permission++;
1964 
1965 	if (c_seg_src->c_bytes_used >= C_MAJOR_COMPACTION_SIZE_APPROPRIATE &&
1966 	    c_seg_dst->c_bytes_used >= C_MAJOR_COMPACTION_SIZE_APPROPRIATE) {
1967 		return FALSE;
1968 	}
1969 
1970 	if (c_seg_dst->c_nextoffset >= c_seg_off_limit || c_seg_dst->c_nextslot >= C_SLOT_MAX_INDEX) {
1971 		/*
1972 		 * destination segment is full... can't compact
1973 		 */
1974 		return FALSE;
1975 	}
1976 
1977 	return TRUE;
1978 }
1979 
1980 
1981 boolean_t
c_seg_major_compact(c_segment_t c_seg_dst,c_segment_t c_seg_src)1982 c_seg_major_compact(
1983 	c_segment_t c_seg_dst,
1984 	c_segment_t c_seg_src)
1985 {
1986 	c_slot_mapping_t slot_ptr;
1987 	uint32_t        c_rounded_size;
1988 	uint32_t        c_size;
1989 	uint16_t        dst_slot;
1990 	int             i;
1991 	c_slot_t        c_dst;
1992 	c_slot_t        c_src;
1993 	boolean_t       keep_compacting = TRUE;
1994 
1995 	/*
1996 	 * segments are not locked but they are both marked c_busy
1997 	 * which keeps c_decompress from working on them...
1998 	 * we can safely allocate new pages, move compressed data
1999 	 * from c_seg_src to c_seg_dst and update both c_segment's
2000 	 * state w/o holding the master lock
2001 	 */
2002 #if DEVELOPMENT || DEBUG
2003 	C_SEG_MAKE_WRITEABLE(c_seg_dst);
2004 #endif
2005 
2006 #if VALIDATE_C_SEGMENTS
2007 	c_seg_dst->c_was_major_compacted++;
2008 	c_seg_src->c_was_major_donor++;
2009 #endif
2010 	c_seg_major_compact_stats[c_seg_major_compact_stats_now].compactions++;
2011 
2012 	dst_slot = c_seg_dst->c_nextslot;
2013 
2014 	for (i = 0; i < c_seg_src->c_nextslot; i++) {
2015 		c_src = C_SEG_SLOT_FROM_INDEX(c_seg_src, i);
2016 
2017 		c_size = UNPACK_C_SIZE(c_src);
2018 
2019 		if (c_size == 0) {
2020 			/* BATCH: move what we have so far; */
2021 			continue;
2022 		}
2023 
2024 		if (C_SEG_OFFSET_TO_BYTES(c_seg_dst->c_populated_offset - c_seg_dst->c_nextoffset) < (unsigned) c_size) {
2025 			int     size_to_populate;
2026 
2027 			/* doesn't fit */
2028 			size_to_populate = c_seg_bufsize - C_SEG_OFFSET_TO_BYTES(c_seg_dst->c_populated_offset);
2029 
2030 			if (size_to_populate == 0) {
2031 				/* can't fit */
2032 				keep_compacting = FALSE;
2033 				break;
2034 			}
2035 			if (size_to_populate > C_SEG_MAX_POPULATE_SIZE) {
2036 				size_to_populate = C_SEG_MAX_POPULATE_SIZE;
2037 			}
2038 
2039 			kernel_memory_populate(
2040 				(vm_offset_t) &c_seg_dst->c_store.c_buffer[c_seg_dst->c_populated_offset],
2041 				size_to_populate,
2042 				KMA_NOFAIL | KMA_COMPRESSOR,
2043 				VM_KERN_MEMORY_COMPRESSOR);
2044 
2045 			c_seg_dst->c_populated_offset += C_SEG_BYTES_TO_OFFSET(size_to_populate);
2046 			assert(C_SEG_OFFSET_TO_BYTES(c_seg_dst->c_populated_offset) <= c_seg_bufsize);
2047 		}
2048 		c_seg_alloc_nextslot(c_seg_dst);
2049 
2050 		c_dst = C_SEG_SLOT_FROM_INDEX(c_seg_dst, c_seg_dst->c_nextslot);
2051 
2052 		memcpy(&c_seg_dst->c_store.c_buffer[c_seg_dst->c_nextoffset], &c_seg_src->c_store.c_buffer[c_src->c_offset], c_size);
2053 
2054 		c_rounded_size = (c_size + C_SEG_OFFSET_ALIGNMENT_MASK) & ~C_SEG_OFFSET_ALIGNMENT_MASK;
2055 
2056 		c_seg_major_compact_stats[c_seg_major_compact_stats_now].moved_slots++;
2057 		c_seg_major_compact_stats[c_seg_major_compact_stats_now].moved_bytes += c_size;
2058 
2059 		cslot_copy(c_dst, c_src);
2060 		c_dst->c_offset = c_seg_dst->c_nextoffset;
2061 
2062 		if (c_seg_dst->c_firstemptyslot == c_seg_dst->c_nextslot) {
2063 			c_seg_dst->c_firstemptyslot++;
2064 		}
2065 		c_seg_dst->c_slots_used++;
2066 		c_seg_dst->c_nextslot++;
2067 		c_seg_dst->c_bytes_used += c_rounded_size;
2068 		c_seg_dst->c_nextoffset += C_SEG_BYTES_TO_OFFSET(c_rounded_size);
2069 
2070 		PACK_C_SIZE(c_src, 0);
2071 
2072 		c_seg_src->c_bytes_used -= c_rounded_size;
2073 		c_seg_src->c_bytes_unused += c_rounded_size;
2074 		c_seg_src->c_firstemptyslot = 0;
2075 
2076 		assert(c_seg_src->c_slots_used);
2077 		c_seg_src->c_slots_used--;
2078 
2079 		if (!c_seg_src->c_swappedin) {
2080 			/* Pessimistically lose swappedin status when non-swappedin pages are added. */
2081 			c_seg_dst->c_swappedin = false;
2082 		}
2083 
2084 		if (c_seg_dst->c_nextoffset >= c_seg_off_limit || c_seg_dst->c_nextslot >= C_SLOT_MAX_INDEX) {
2085 			/* dest segment is now full */
2086 			keep_compacting = FALSE;
2087 			break;
2088 		}
2089 	}
2090 #if DEVELOPMENT || DEBUG
2091 	C_SEG_WRITE_PROTECT(c_seg_dst);
2092 #endif
2093 	if (dst_slot < c_seg_dst->c_nextslot) {
2094 		PAGE_REPLACEMENT_ALLOWED(TRUE);
2095 		/*
2096 		 * we've now locked out c_decompress from
2097 		 * converting the slot passed into it into
2098 		 * a c_segment_t which allows us to use
2099 		 * the backptr to change which c_segment and
2100 		 * index the slot points to
2101 		 */
2102 		while (dst_slot < c_seg_dst->c_nextslot) {
2103 			c_dst = C_SEG_SLOT_FROM_INDEX(c_seg_dst, dst_slot);
2104 
2105 			slot_ptr = C_SLOT_UNPACK_PTR(c_dst);
2106 			/* <csegno=0,indx=0> would mean "empty slot", so use csegno+1 */
2107 			slot_ptr->s_cseg = c_seg_dst->c_mysegno + 1;
2108 			slot_ptr->s_cindx = dst_slot++;
2109 		}
2110 		PAGE_REPLACEMENT_ALLOWED(FALSE);
2111 	}
2112 	return keep_compacting;
2113 }
2114 
2115 
2116 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)2117 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)
2118 {
2119 	uint64_t end_msecs;
2120 	uint64_t start_msecs;
2121 
2122 	end_msecs = (end_sec * 1000) + end_nsec / 1000000;
2123 	start_msecs = (start_sec * 1000) + start_nsec / 1000000;
2124 
2125 	return end_msecs - start_msecs;
2126 }
2127 
2128 
2129 
2130 uint32_t compressor_eval_period_in_msecs = 250;
2131 uint32_t compressor_sample_min_in_msecs = 500;
2132 uint32_t compressor_sample_max_in_msecs = 10000;
2133 uint32_t compressor_thrashing_threshold_per_10msecs = 50;
2134 uint32_t compressor_thrashing_min_per_10msecs = 20;
2135 
2136 /* When true, reset sample data next chance we get. */
2137 static boolean_t        compressor_need_sample_reset = FALSE;
2138 
2139 
2140 void
compute_swapout_target_age(void)2141 compute_swapout_target_age(void)
2142 {
2143 	clock_sec_t     cur_ts_sec;
2144 	clock_nsec_t    cur_ts_nsec;
2145 	uint32_t        min_operations_needed_in_this_sample;
2146 	uint64_t        elapsed_msecs_in_eval;
2147 	uint64_t        elapsed_msecs_in_sample;
2148 	boolean_t       need_eval_reset = FALSE;
2149 
2150 	clock_get_system_nanotime(&cur_ts_sec, &cur_ts_nsec);
2151 
2152 	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);
2153 
2154 	if (compressor_need_sample_reset ||
2155 	    elapsed_msecs_in_sample >= compressor_sample_max_in_msecs) {
2156 		compressor_need_sample_reset = TRUE;
2157 		need_eval_reset = TRUE;
2158 		goto done;
2159 	}
2160 	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);
2161 
2162 	if (elapsed_msecs_in_eval < compressor_eval_period_in_msecs) {
2163 		goto done;
2164 	}
2165 	need_eval_reset = TRUE;
2166 
2167 	KERNEL_DEBUG(0xe0400020 | DBG_FUNC_START, elapsed_msecs_in_eval, sample_period_compression_count, sample_period_decompression_count, 0, 0);
2168 
2169 	min_operations_needed_in_this_sample = (compressor_thrashing_min_per_10msecs * (uint32_t)elapsed_msecs_in_eval) / 10;
2170 
2171 	if ((sample_period_compression_count - last_eval_compression_count) < min_operations_needed_in_this_sample ||
2172 	    (sample_period_decompression_count - last_eval_decompression_count) < min_operations_needed_in_this_sample) {
2173 		KERNEL_DEBUG(0xe0400020 | DBG_FUNC_END, sample_period_compression_count - last_eval_compression_count,
2174 		    sample_period_decompression_count - last_eval_decompression_count, 0, 1, 0);
2175 
2176 		swapout_target_age = 0;
2177 
2178 		compressor_need_sample_reset = TRUE;
2179 		need_eval_reset = TRUE;
2180 		goto done;
2181 	}
2182 	last_eval_compression_count = sample_period_compression_count;
2183 	last_eval_decompression_count = sample_period_decompression_count;
2184 
2185 	if (elapsed_msecs_in_sample < compressor_sample_min_in_msecs) {
2186 		KERNEL_DEBUG(0xe0400020 | DBG_FUNC_END, swapout_target_age, 0, 0, 5, 0);
2187 		goto done;
2188 	}
2189 	if (sample_period_decompression_count > ((compressor_thrashing_threshold_per_10msecs * elapsed_msecs_in_sample) / 10)) {
2190 		uint64_t        running_total;
2191 		uint64_t        working_target;
2192 		uint64_t        aging_target;
2193 		uint32_t        oldest_age_of_csegs_sampled = 0;
2194 		uint64_t        working_set_approximation = 0;
2195 
2196 		swapout_target_age = 0;
2197 
2198 		working_target = (sample_period_decompression_count / 100) * 95;                /* 95 percent */
2199 		aging_target = (sample_period_decompression_count / 100) * 1;                   /* 1 percent */
2200 		running_total = 0;
2201 
2202 		for (oldest_age_of_csegs_sampled = 0; oldest_age_of_csegs_sampled < DECOMPRESSION_SAMPLE_MAX_AGE; oldest_age_of_csegs_sampled++) {
2203 			running_total += age_of_decompressions_during_sample_period[oldest_age_of_csegs_sampled];
2204 
2205 			working_set_approximation += oldest_age_of_csegs_sampled * age_of_decompressions_during_sample_period[oldest_age_of_csegs_sampled];
2206 
2207 			if (running_total >= working_target) {
2208 				break;
2209 			}
2210 		}
2211 		if (oldest_age_of_csegs_sampled < DECOMPRESSION_SAMPLE_MAX_AGE) {
2212 			working_set_approximation = (working_set_approximation * 1000) / elapsed_msecs_in_sample;
2213 
2214 			if (working_set_approximation < VM_PAGE_COMPRESSOR_COUNT) {
2215 				running_total = overage_decompressions_during_sample_period;
2216 
2217 				for (oldest_age_of_csegs_sampled = DECOMPRESSION_SAMPLE_MAX_AGE - 1; oldest_age_of_csegs_sampled; oldest_age_of_csegs_sampled--) {
2218 					running_total += age_of_decompressions_during_sample_period[oldest_age_of_csegs_sampled];
2219 
2220 					if (running_total >= aging_target) {
2221 						break;
2222 					}
2223 				}
2224 				swapout_target_age = (uint32_t)cur_ts_sec - oldest_age_of_csegs_sampled;
2225 
2226 				KERNEL_DEBUG(0xe0400020 | DBG_FUNC_END, swapout_target_age, working_set_approximation, VM_PAGE_COMPRESSOR_COUNT, 2, 0);
2227 			} else {
2228 				KERNEL_DEBUG(0xe0400020 | DBG_FUNC_END, working_set_approximation, VM_PAGE_COMPRESSOR_COUNT, 0, 3, 0);
2229 			}
2230 		} else {
2231 			KERNEL_DEBUG(0xe0400020 | DBG_FUNC_END, working_target, running_total, 0, 4, 0);
2232 		}
2233 
2234 		compressor_need_sample_reset = TRUE;
2235 		need_eval_reset = TRUE;
2236 	} else {
2237 		KERNEL_DEBUG(0xe0400020 | DBG_FUNC_END, sample_period_decompression_count, (compressor_thrashing_threshold_per_10msecs * elapsed_msecs_in_sample) / 10, 0, 6, 0);
2238 	}
2239 done:
2240 	if (compressor_need_sample_reset == TRUE) {
2241 		bzero(age_of_decompressions_during_sample_period, sizeof(age_of_decompressions_during_sample_period));
2242 		overage_decompressions_during_sample_period = 0;
2243 
2244 		start_of_sample_period_sec = cur_ts_sec;
2245 		start_of_sample_period_nsec = cur_ts_nsec;
2246 		sample_period_decompression_count = 0;
2247 		sample_period_compression_count = 0;
2248 		last_eval_decompression_count = 0;
2249 		last_eval_compression_count = 0;
2250 		compressor_need_sample_reset = FALSE;
2251 	}
2252 	if (need_eval_reset == TRUE) {
2253 		start_of_eval_period_sec = cur_ts_sec;
2254 		start_of_eval_period_nsec = cur_ts_nsec;
2255 	}
2256 }
2257 
2258 
2259 int             compaction_swapper_init_now = 0;
2260 int             compaction_swapper_running = 0;
2261 int             compaction_swapper_awakened = 0;
2262 int             compaction_swapper_abort = 0;
2263 
2264 
2265 #if CONFIG_JETSAM
2266 boolean_t       memorystatus_kill_on_VM_compressor_thrashing(boolean_t);
2267 boolean_t       memorystatus_kill_on_VM_compressor_space_shortage(boolean_t);
2268 boolean_t       memorystatus_kill_on_FC_thrashing(boolean_t);
2269 int             compressor_thrashing_induced_jetsam = 0;
2270 int             filecache_thrashing_induced_jetsam = 0;
2271 static boolean_t        vm_compressor_thrashing_detected = FALSE;
2272 #endif /* CONFIG_JETSAM */
2273 
2274 static bool
compressor_swapout_conditions_met(void)2275 compressor_swapout_conditions_met(void)
2276 {
2277 	bool should_swap = false;
2278 
2279 	if (COMPRESSOR_NEEDS_TO_SWAP()) {
2280 		should_swap = true;
2281 		vmcs_stats.compressor_swap_threshold_exceeded++;
2282 	}
2283 	if (VM_PAGE_Q_THROTTLED(&vm_pageout_queue_external) && vm_page_anonymous_count < (vm_page_inactive_count / 20)) {
2284 		should_swap = true;
2285 		vmcs_stats.external_q_throttled++;
2286 	}
2287 	if (vm_page_free_count < (vm_page_free_reserved - (COMPRESSOR_FREE_RESERVED_LIMIT * 2))) {
2288 		should_swap = true;
2289 		vmcs_stats.free_count_below_reserve++;
2290 	}
2291 	return should_swap;
2292 }
2293 
2294 static boolean_t
compressor_needs_to_swap(void)2295 compressor_needs_to_swap(void)
2296 {
2297 	boolean_t       should_swap = FALSE;
2298 
2299 	if (vm_swapout_ripe_segments == TRUE && c_overage_swapped_count < c_overage_swapped_limit) {
2300 		c_segment_t     c_seg;
2301 		clock_sec_t     now;
2302 		clock_sec_t     age;
2303 		clock_nsec_t    nsec;
2304 
2305 		clock_get_system_nanotime(&now, &nsec);
2306 		age = 0;
2307 
2308 		lck_mtx_lock_spin_always(c_list_lock);
2309 
2310 		if (!queue_empty(&c_age_list_head)) {
2311 			c_seg = (c_segment_t) queue_first(&c_age_list_head);
2312 
2313 			age = now - c_seg->c_creation_ts;
2314 		}
2315 		lck_mtx_unlock_always(c_list_lock);
2316 
2317 		if (age >= vm_ripe_target_age) {
2318 			should_swap = TRUE;
2319 			goto check_if_low_space;
2320 		}
2321 	}
2322 	if (VM_CONFIG_SWAP_IS_ACTIVE) {
2323 		should_swap =  compressor_swapout_conditions_met();
2324 		if (should_swap) {
2325 			goto check_if_low_space;
2326 		}
2327 	}
2328 
2329 #if (XNU_TARGET_OS_OSX && __arm64__)
2330 	/*
2331 	 * Thrashing detection disabled.
2332 	 */
2333 #else /* (XNU_TARGET_OS_OSX && __arm64__) */
2334 
2335 	compute_swapout_target_age();
2336 
2337 	if (swapout_target_age) {
2338 		c_segment_t     c_seg;
2339 
2340 		lck_mtx_lock_spin_always(c_list_lock);
2341 
2342 		if (!queue_empty(&c_age_list_head)) {
2343 			c_seg = (c_segment_t) queue_first(&c_age_list_head);
2344 
2345 			if (c_seg->c_creation_ts > swapout_target_age) {
2346 				swapout_target_age = 0;
2347 			}
2348 		}
2349 		lck_mtx_unlock_always(c_list_lock);
2350 	}
2351 #if CONFIG_PHANTOM_CACHE
2352 	if (vm_phantom_cache_check_pressure()) {
2353 		should_swap = TRUE;
2354 	}
2355 #endif
2356 	if (swapout_target_age) {
2357 		should_swap = TRUE;
2358 		vmcs_stats.thrashing_detected++;
2359 	}
2360 #endif /* (XNU_TARGET_OS_OSX && __arm64__) */
2361 
2362 check_if_low_space:
2363 
2364 #if CONFIG_JETSAM
2365 	if (should_swap || vm_compressor_low_on_space() == TRUE) {
2366 		if (vm_compressor_thrashing_detected == FALSE) {
2367 			vm_compressor_thrashing_detected = TRUE;
2368 
2369 			if (swapout_target_age) {
2370 				/* The compressor is thrashing. */
2371 				memorystatus_kill_on_VM_compressor_thrashing(TRUE /* async */);
2372 				compressor_thrashing_induced_jetsam++;
2373 			} else if (vm_compressor_low_on_space() == TRUE) {
2374 				/* The compressor is running low on space. */
2375 				memorystatus_kill_on_VM_compressor_space_shortage(TRUE /* async */);
2376 				compressor_thrashing_induced_jetsam++;
2377 			} else {
2378 				memorystatus_kill_on_FC_thrashing(TRUE /* async */);
2379 				filecache_thrashing_induced_jetsam++;
2380 			}
2381 		}
2382 		/*
2383 		 * let the jetsam take precedence over
2384 		 * any major compactions we might have
2385 		 * been able to do... otherwise we run
2386 		 * the risk of doing major compactions
2387 		 * on segments we're about to free up
2388 		 * due to the jetsam activity.
2389 		 */
2390 		should_swap = FALSE;
2391 	}
2392 
2393 #else /* CONFIG_JETSAM */
2394 	if (should_swap && vm_swap_low_on_space()) {
2395 		vm_compressor_take_paging_space_action();
2396 	}
2397 #endif /* CONFIG_JETSAM */
2398 
2399 	if (should_swap == FALSE) {
2400 		/*
2401 		 * vm_compressor_needs_to_major_compact returns true only if we're
2402 		 * about to run out of available compressor segments... in this
2403 		 * case, we absolutely need to run a major compaction even if
2404 		 * we've just kicked off a jetsam or we don't otherwise need to
2405 		 * swap... terminating objects releases
2406 		 * pages back to the uncompressed cache, but does not guarantee
2407 		 * that we will free up even a single compression segment
2408 		 */
2409 		should_swap = vm_compressor_needs_to_major_compact();
2410 		if (should_swap) {
2411 			vmcs_stats.fragmentation_detected++;
2412 		}
2413 	}
2414 
2415 	/*
2416 	 * returning TRUE when swap_supported == FALSE
2417 	 * will cause the major compaction engine to
2418 	 * run, but will not trigger any swapping...
2419 	 * segments that have been major compacted
2420 	 * will be moved to the majorcompact queue
2421 	 */
2422 	return should_swap;
2423 }
2424 
2425 #if CONFIG_JETSAM
2426 /*
2427  * This function is called from the jetsam thread after killing something to
2428  * mitigate thrashing.
2429  *
2430  * We need to restart our thrashing detection heuristics since memory pressure
2431  * has potentially changed significantly, and we don't want to detect on old
2432  * data from before the jetsam.
2433  */
2434 void
vm_thrashing_jetsam_done(void)2435 vm_thrashing_jetsam_done(void)
2436 {
2437 	vm_compressor_thrashing_detected = FALSE;
2438 
2439 	/* Were we compressor-thrashing or filecache-thrashing? */
2440 	if (swapout_target_age) {
2441 		swapout_target_age = 0;
2442 		compressor_need_sample_reset = TRUE;
2443 	}
2444 #if CONFIG_PHANTOM_CACHE
2445 	else {
2446 		vm_phantom_cache_restart_sample();
2447 	}
2448 #endif
2449 }
2450 #endif /* CONFIG_JETSAM */
2451 
2452 uint32_t vm_wake_compactor_swapper_calls = 0;
2453 uint32_t vm_run_compactor_already_running = 0;
2454 uint32_t vm_run_compactor_empty_minor_q = 0;
2455 uint32_t vm_run_compactor_did_compact = 0;
2456 uint32_t vm_run_compactor_waited = 0;
2457 
2458 void
vm_run_compactor(void)2459 vm_run_compactor(void)
2460 {
2461 	if (c_segment_count == 0) {
2462 		return;
2463 	}
2464 
2465 	lck_mtx_lock_spin_always(c_list_lock);
2466 
2467 	if (c_minor_count == 0) {
2468 		vm_run_compactor_empty_minor_q++;
2469 
2470 		lck_mtx_unlock_always(c_list_lock);
2471 		return;
2472 	}
2473 	if (compaction_swapper_running) {
2474 		if (vm_pageout_state.vm_restricted_to_single_processor == FALSE) {
2475 			vm_run_compactor_already_running++;
2476 
2477 			lck_mtx_unlock_always(c_list_lock);
2478 			return;
2479 		}
2480 		vm_run_compactor_waited++;
2481 
2482 		assert_wait((event_t)&compaction_swapper_running, THREAD_UNINT);
2483 
2484 		lck_mtx_unlock_always(c_list_lock);
2485 
2486 		thread_block(THREAD_CONTINUE_NULL);
2487 
2488 		return;
2489 	}
2490 	vm_run_compactor_did_compact++;
2491 
2492 	fastwake_warmup = FALSE;
2493 	compaction_swapper_running = 1;
2494 
2495 	vm_compressor_do_delayed_compactions(FALSE);
2496 
2497 	compaction_swapper_running = 0;
2498 
2499 	lck_mtx_unlock_always(c_list_lock);
2500 
2501 	thread_wakeup((event_t)&compaction_swapper_running);
2502 }
2503 
2504 
2505 void
vm_wake_compactor_swapper(void)2506 vm_wake_compactor_swapper(void)
2507 {
2508 	if (compaction_swapper_running || compaction_swapper_awakened || c_segment_count == 0) {
2509 		return;
2510 	}
2511 
2512 	if (c_minor_count || vm_compressor_needs_to_major_compact()) {
2513 		lck_mtx_lock_spin_always(c_list_lock);
2514 
2515 		fastwake_warmup = FALSE;
2516 
2517 		if (compaction_swapper_running == 0 && compaction_swapper_awakened == 0) {
2518 			vm_wake_compactor_swapper_calls++;
2519 
2520 			compaction_swapper_awakened = 1;
2521 			thread_wakeup((event_t)&c_compressor_swap_trigger);
2522 		}
2523 		lck_mtx_unlock_always(c_list_lock);
2524 	}
2525 }
2526 
2527 
2528 void
vm_consider_swapping()2529 vm_consider_swapping()
2530 {
2531 	c_segment_t     c_seg, c_seg_next;
2532 	clock_sec_t     now;
2533 	clock_nsec_t    nsec;
2534 
2535 	assert(VM_CONFIG_SWAP_IS_PRESENT);
2536 
2537 	lck_mtx_lock_spin_always(c_list_lock);
2538 
2539 	compaction_swapper_abort = 1;
2540 
2541 	while (compaction_swapper_running) {
2542 		assert_wait((event_t)&compaction_swapper_running, THREAD_UNINT);
2543 
2544 		lck_mtx_unlock_always(c_list_lock);
2545 
2546 		thread_block(THREAD_CONTINUE_NULL);
2547 
2548 		lck_mtx_lock_spin_always(c_list_lock);
2549 	}
2550 	compaction_swapper_abort = 0;
2551 	compaction_swapper_running = 1;
2552 
2553 	vm_swapout_ripe_segments = TRUE;
2554 
2555 	if (!queue_empty(&c_major_list_head)) {
2556 		clock_get_system_nanotime(&now, &nsec);
2557 
2558 		c_seg = (c_segment_t)queue_first(&c_major_list_head);
2559 
2560 		while (!queue_end(&c_major_list_head, (queue_entry_t)c_seg)) {
2561 			if (c_overage_swapped_count >= c_overage_swapped_limit) {
2562 				break;
2563 			}
2564 
2565 			c_seg_next = (c_segment_t) queue_next(&c_seg->c_age_list);
2566 
2567 			if ((now - c_seg->c_creation_ts) >= vm_ripe_target_age) {
2568 				lck_mtx_lock_spin_always(&c_seg->c_lock);
2569 
2570 				c_seg_switch_state(c_seg, C_ON_AGE_Q, FALSE);
2571 
2572 				lck_mtx_unlock_always(&c_seg->c_lock);
2573 			}
2574 			c_seg = c_seg_next;
2575 		}
2576 	}
2577 	vm_compressor_compact_and_swap(FALSE);
2578 
2579 	compaction_swapper_running = 0;
2580 
2581 	vm_swapout_ripe_segments = FALSE;
2582 
2583 	lck_mtx_unlock_always(c_list_lock);
2584 
2585 	thread_wakeup((event_t)&compaction_swapper_running);
2586 }
2587 
2588 
2589 void
vm_consider_waking_compactor_swapper(void)2590 vm_consider_waking_compactor_swapper(void)
2591 {
2592 	boolean_t       need_wakeup = FALSE;
2593 
2594 	if (c_segment_count == 0) {
2595 		return;
2596 	}
2597 
2598 	if (compaction_swapper_running || compaction_swapper_awakened) {
2599 		return;
2600 	}
2601 
2602 	if (!compaction_swapper_inited && !compaction_swapper_init_now) {
2603 		compaction_swapper_init_now = 1;
2604 		need_wakeup = TRUE;
2605 	}
2606 
2607 	if (c_minor_count && (COMPRESSOR_NEEDS_TO_MINOR_COMPACT())) {
2608 		need_wakeup = TRUE;
2609 	} else if (compressor_needs_to_swap()) {
2610 		need_wakeup = TRUE;
2611 	} else if (c_minor_count) {
2612 		uint64_t        total_bytes;
2613 
2614 		total_bytes = compressor_object->resident_page_count * PAGE_SIZE_64;
2615 
2616 		if ((total_bytes - compressor_bytes_used) > total_bytes / 10) {
2617 			need_wakeup = TRUE;
2618 		}
2619 	}
2620 	if (need_wakeup == TRUE) {
2621 		lck_mtx_lock_spin_always(c_list_lock);
2622 
2623 		fastwake_warmup = FALSE;
2624 
2625 		if (compaction_swapper_running == 0 && compaction_swapper_awakened == 0) {
2626 			memoryshot(VM_WAKEUP_COMPACTOR_SWAPPER, DBG_FUNC_NONE);
2627 
2628 			compaction_swapper_awakened = 1;
2629 			thread_wakeup((event_t)&c_compressor_swap_trigger);
2630 		}
2631 		lck_mtx_unlock_always(c_list_lock);
2632 	}
2633 }
2634 
2635 
2636 #define C_SWAPOUT_LIMIT                 4
2637 #define DELAYED_COMPACTIONS_PER_PASS    30
2638 
2639 void
vm_compressor_do_delayed_compactions(boolean_t flush_all)2640 vm_compressor_do_delayed_compactions(boolean_t flush_all)
2641 {
2642 	c_segment_t     c_seg;
2643 	int             number_compacted = 0;
2644 	boolean_t       needs_to_swap = FALSE;
2645 
2646 
2647 	VM_DEBUG_CONSTANT_EVENT(vm_compressor_do_delayed_compactions, VM_COMPRESSOR_DO_DELAYED_COMPACTIONS, DBG_FUNC_START, c_minor_count, flush_all, 0, 0);
2648 
2649 #if XNU_TARGET_OS_OSX
2650 	LCK_MTX_ASSERT(c_list_lock, LCK_MTX_ASSERT_OWNED);
2651 #endif /* XNU_TARGET_OS_OSX */
2652 
2653 	while (!queue_empty(&c_minor_list_head) && needs_to_swap == FALSE) {
2654 		c_seg = (c_segment_t)queue_first(&c_minor_list_head);
2655 
2656 		lck_mtx_lock_spin_always(&c_seg->c_lock);
2657 
2658 		if (c_seg->c_busy) {
2659 			lck_mtx_unlock_always(c_list_lock);
2660 			c_seg_wait_on_busy(c_seg);
2661 			lck_mtx_lock_spin_always(c_list_lock);
2662 
2663 			continue;
2664 		}
2665 		C_SEG_BUSY(c_seg);
2666 
2667 		c_seg_do_minor_compaction_and_unlock(c_seg, TRUE, FALSE, TRUE);
2668 
2669 		if (VM_CONFIG_SWAP_IS_ACTIVE && (number_compacted++ > DELAYED_COMPACTIONS_PER_PASS)) {
2670 			if ((flush_all == TRUE || compressor_needs_to_swap() == TRUE) && c_swapout_count < C_SWAPOUT_LIMIT) {
2671 				needs_to_swap = TRUE;
2672 			}
2673 
2674 			number_compacted = 0;
2675 		}
2676 		lck_mtx_lock_spin_always(c_list_lock);
2677 	}
2678 
2679 	VM_DEBUG_CONSTANT_EVENT(vm_compressor_do_delayed_compactions, VM_COMPRESSOR_DO_DELAYED_COMPACTIONS, DBG_FUNC_END, c_minor_count, number_compacted, needs_to_swap, 0);
2680 }
2681 
2682 
2683 #define C_SEGMENT_SWAPPEDIN_AGE_LIMIT   10
2684 
2685 static void
vm_compressor_age_swapped_in_segments(boolean_t flush_all)2686 vm_compressor_age_swapped_in_segments(boolean_t flush_all)
2687 {
2688 	c_segment_t     c_seg;
2689 	clock_sec_t     now;
2690 	clock_nsec_t    nsec;
2691 
2692 	clock_get_system_nanotime(&now, &nsec);
2693 
2694 	while (!queue_empty(&c_swappedin_list_head)) {
2695 		c_seg = (c_segment_t)queue_first(&c_swappedin_list_head);
2696 
2697 		if (flush_all == FALSE && (now - c_seg->c_swappedin_ts) < C_SEGMENT_SWAPPEDIN_AGE_LIMIT) {
2698 			break;
2699 		}
2700 
2701 		lck_mtx_lock_spin_always(&c_seg->c_lock);
2702 
2703 		c_seg_switch_state(c_seg, C_ON_AGE_Q, FALSE);
2704 		c_seg->c_agedin_ts = (uint32_t) now;
2705 
2706 		lck_mtx_unlock_always(&c_seg->c_lock);
2707 	}
2708 }
2709 
2710 
2711 extern  int     vm_num_swap_files;
2712 extern  int     vm_num_pinned_swap_files;
2713 extern  int     vm_swappin_enabled;
2714 
2715 extern  unsigned int    vm_swapfile_total_segs_used;
2716 extern  unsigned int    vm_swapfile_total_segs_alloced;
2717 
2718 
2719 void
vm_compressor_flush(void)2720 vm_compressor_flush(void)
2721 {
2722 	uint64_t        vm_swap_put_failures_at_start;
2723 	wait_result_t   wait_result = 0;
2724 	AbsoluteTime    startTime, endTime;
2725 	clock_sec_t     now_sec;
2726 	clock_nsec_t    now_nsec;
2727 	uint64_t        nsec;
2728 	c_segment_t     c_seg, c_seg_next;
2729 
2730 	HIBLOG("vm_compressor_flush - starting\n");
2731 
2732 	clock_get_uptime(&startTime);
2733 
2734 	lck_mtx_lock_spin_always(c_list_lock);
2735 
2736 	fastwake_warmup = FALSE;
2737 	compaction_swapper_abort = 1;
2738 
2739 	while (compaction_swapper_running) {
2740 		assert_wait((event_t)&compaction_swapper_running, THREAD_UNINT);
2741 
2742 		lck_mtx_unlock_always(c_list_lock);
2743 
2744 		thread_block(THREAD_CONTINUE_NULL);
2745 
2746 		lck_mtx_lock_spin_always(c_list_lock);
2747 	}
2748 	compaction_swapper_abort = 0;
2749 	compaction_swapper_running = 1;
2750 
2751 	hibernate_flushing = TRUE;
2752 	hibernate_no_swapspace = FALSE;
2753 	hibernate_flush_timed_out = FALSE;
2754 	c_generation_id_flush_barrier = c_generation_id + 1000;
2755 
2756 	clock_get_system_nanotime(&now_sec, &now_nsec);
2757 	hibernate_flushing_deadline = now_sec + HIBERNATE_FLUSHING_SECS_TO_COMPLETE;
2758 
2759 	vm_swap_put_failures_at_start = vm_swap_put_failures;
2760 
2761 	/*
2762 	 * We are about to hibernate and so we want all segments flushed to disk.
2763 	 * Segments that are on the major compaction queue won't be considered in
2764 	 * the vm_compressor_compact_and_swap() pass. So we need to bring them to
2765 	 * the ageQ for consideration.
2766 	 */
2767 	if (!queue_empty(&c_major_list_head)) {
2768 		c_seg = (c_segment_t)queue_first(&c_major_list_head);
2769 
2770 		while (!queue_end(&c_major_list_head, (queue_entry_t)c_seg)) {
2771 			c_seg_next = (c_segment_t) queue_next(&c_seg->c_age_list);
2772 			lck_mtx_lock_spin_always(&c_seg->c_lock);
2773 			c_seg_switch_state(c_seg, C_ON_AGE_Q, FALSE);
2774 			lck_mtx_unlock_always(&c_seg->c_lock);
2775 			c_seg = c_seg_next;
2776 		}
2777 	}
2778 	vm_compressor_compact_and_swap(TRUE);
2779 
2780 	while (!queue_empty(&c_swapout_list_head)) {
2781 		assert_wait_timeout((event_t) &compaction_swapper_running, THREAD_INTERRUPTIBLE, 5000, 1000 * NSEC_PER_USEC);
2782 
2783 		lck_mtx_unlock_always(c_list_lock);
2784 
2785 		wait_result = thread_block(THREAD_CONTINUE_NULL);
2786 
2787 		lck_mtx_lock_spin_always(c_list_lock);
2788 
2789 		if (wait_result == THREAD_TIMED_OUT) {
2790 			break;
2791 		}
2792 	}
2793 	hibernate_flushing = FALSE;
2794 	compaction_swapper_running = 0;
2795 
2796 	if (vm_swap_put_failures > vm_swap_put_failures_at_start) {
2797 		HIBLOG("vm_compressor_flush failed to clean %llu segments - vm_page_compressor_count(%d)\n",
2798 		    vm_swap_put_failures - vm_swap_put_failures_at_start, VM_PAGE_COMPRESSOR_COUNT);
2799 	}
2800 
2801 	lck_mtx_unlock_always(c_list_lock);
2802 
2803 	thread_wakeup((event_t)&compaction_swapper_running);
2804 
2805 	clock_get_uptime(&endTime);
2806 	SUB_ABSOLUTETIME(&endTime, &startTime);
2807 	absolutetime_to_nanoseconds(endTime, &nsec);
2808 
2809 	HIBLOG("vm_compressor_flush completed - took %qd msecs - vm_num_swap_files = %d, vm_num_pinned_swap_files = %d, vm_swappin_enabled = %d\n",
2810 	    nsec / 1000000ULL, vm_num_swap_files, vm_num_pinned_swap_files, vm_swappin_enabled);
2811 }
2812 
2813 
2814 int             compaction_swap_trigger_thread_awakened = 0;
2815 
2816 static void
vm_compressor_swap_trigger_thread(void)2817 vm_compressor_swap_trigger_thread(void)
2818 {
2819 	current_thread()->options |= TH_OPT_VMPRIV;
2820 
2821 	/*
2822 	 * compaction_swapper_init_now is set when the first call to
2823 	 * vm_consider_waking_compactor_swapper is made from
2824 	 * vm_pageout_scan... since this function is called upon
2825 	 * thread creation, we want to make sure to delay adjusting
2826 	 * the tuneables until we are awakened via vm_pageout_scan
2827 	 * so that we are at a point where the vm_swapfile_open will
2828 	 * be operating on the correct directory (in case the default
2829 	 * of using the VM volume is overridden by the dynamic_pager)
2830 	 */
2831 	if (compaction_swapper_init_now) {
2832 		vm_compaction_swapper_do_init();
2833 
2834 		if (vm_pageout_state.vm_restricted_to_single_processor == TRUE) {
2835 			thread_vm_bind_group_add();
2836 		}
2837 #if CONFIG_THREAD_GROUPS
2838 		thread_group_vm_add();
2839 #endif
2840 		thread_set_thread_name(current_thread(), "VM_cswap_trigger");
2841 		compaction_swapper_init_now = 0;
2842 	}
2843 	lck_mtx_lock_spin_always(c_list_lock);
2844 
2845 	compaction_swap_trigger_thread_awakened++;
2846 	compaction_swapper_awakened = 0;
2847 
2848 	if (compaction_swapper_running == 0) {
2849 		compaction_swapper_running = 1;
2850 
2851 		vm_compressor_compact_and_swap(FALSE);
2852 
2853 		compaction_swapper_running = 0;
2854 	}
2855 	assert_wait((event_t)&c_compressor_swap_trigger, THREAD_UNINT);
2856 
2857 	if (compaction_swapper_running == 0) {
2858 		thread_wakeup((event_t)&compaction_swapper_running);
2859 	}
2860 
2861 	lck_mtx_unlock_always(c_list_lock);
2862 
2863 	thread_block((thread_continue_t)vm_compressor_swap_trigger_thread);
2864 
2865 	/* NOTREACHED */
2866 }
2867 
2868 
2869 void
vm_compressor_record_warmup_start(void)2870 vm_compressor_record_warmup_start(void)
2871 {
2872 	c_segment_t     c_seg;
2873 
2874 	lck_mtx_lock_spin_always(c_list_lock);
2875 
2876 	if (first_c_segment_to_warm_generation_id == 0) {
2877 		if (!queue_empty(&c_age_list_head)) {
2878 			c_seg = (c_segment_t)queue_last(&c_age_list_head);
2879 
2880 			first_c_segment_to_warm_generation_id = c_seg->c_generation_id;
2881 		} else {
2882 			first_c_segment_to_warm_generation_id = 0;
2883 		}
2884 
2885 		fastwake_recording_in_progress = TRUE;
2886 	}
2887 	lck_mtx_unlock_always(c_list_lock);
2888 }
2889 
2890 
2891 void
vm_compressor_record_warmup_end(void)2892 vm_compressor_record_warmup_end(void)
2893 {
2894 	c_segment_t     c_seg;
2895 
2896 	lck_mtx_lock_spin_always(c_list_lock);
2897 
2898 	if (fastwake_recording_in_progress == TRUE) {
2899 		if (!queue_empty(&c_age_list_head)) {
2900 			c_seg = (c_segment_t)queue_last(&c_age_list_head);
2901 
2902 			last_c_segment_to_warm_generation_id = c_seg->c_generation_id;
2903 		} else {
2904 			last_c_segment_to_warm_generation_id = first_c_segment_to_warm_generation_id;
2905 		}
2906 
2907 		fastwake_recording_in_progress = FALSE;
2908 
2909 		HIBLOG("vm_compressor_record_warmup (%qd - %qd)\n", first_c_segment_to_warm_generation_id, last_c_segment_to_warm_generation_id);
2910 	}
2911 	lck_mtx_unlock_always(c_list_lock);
2912 }
2913 
2914 
2915 #define DELAY_TRIM_ON_WAKE_SECS         25
2916 
2917 void
vm_compressor_delay_trim(void)2918 vm_compressor_delay_trim(void)
2919 {
2920 	clock_sec_t     sec;
2921 	clock_nsec_t    nsec;
2922 
2923 	clock_get_system_nanotime(&sec, &nsec);
2924 	dont_trim_until_ts = sec + DELAY_TRIM_ON_WAKE_SECS;
2925 }
2926 
2927 
2928 void
vm_compressor_do_warmup(void)2929 vm_compressor_do_warmup(void)
2930 {
2931 	lck_mtx_lock_spin_always(c_list_lock);
2932 
2933 	if (first_c_segment_to_warm_generation_id == last_c_segment_to_warm_generation_id) {
2934 		first_c_segment_to_warm_generation_id = last_c_segment_to_warm_generation_id = 0;
2935 
2936 		lck_mtx_unlock_always(c_list_lock);
2937 		return;
2938 	}
2939 
2940 	if (compaction_swapper_running == 0 && compaction_swapper_awakened == 0) {
2941 		fastwake_warmup = TRUE;
2942 
2943 		compaction_swapper_awakened = 1;
2944 		thread_wakeup((event_t)&c_compressor_swap_trigger);
2945 	}
2946 	lck_mtx_unlock_always(c_list_lock);
2947 }
2948 
2949 void
do_fastwake_warmup_all(void)2950 do_fastwake_warmup_all(void)
2951 {
2952 	lck_mtx_lock_spin_always(c_list_lock);
2953 
2954 	if (queue_empty(&c_swappedout_list_head) && queue_empty(&c_swappedout_sparse_list_head)) {
2955 		lck_mtx_unlock_always(c_list_lock);
2956 		return;
2957 	}
2958 
2959 	fastwake_warmup = TRUE;
2960 
2961 	do_fastwake_warmup(&c_swappedout_list_head, TRUE);
2962 
2963 	do_fastwake_warmup(&c_swappedout_sparse_list_head, TRUE);
2964 
2965 	fastwake_warmup = FALSE;
2966 
2967 	lck_mtx_unlock_always(c_list_lock);
2968 }
2969 
2970 void
do_fastwake_warmup(queue_head_t * c_queue,boolean_t consider_all_cseg)2971 do_fastwake_warmup(queue_head_t *c_queue, boolean_t consider_all_cseg)
2972 {
2973 	c_segment_t     c_seg = NULL;
2974 	AbsoluteTime    startTime, endTime;
2975 	uint64_t        nsec;
2976 
2977 
2978 	HIBLOG("vm_compressor_fastwake_warmup (%qd - %qd) - starting\n", first_c_segment_to_warm_generation_id, last_c_segment_to_warm_generation_id);
2979 
2980 	clock_get_uptime(&startTime);
2981 
2982 	lck_mtx_unlock_always(c_list_lock);
2983 
2984 	proc_set_thread_policy(current_thread(),
2985 	    TASK_POLICY_INTERNAL, TASK_POLICY_IO, THROTTLE_LEVEL_COMPRESSOR_TIER2);
2986 
2987 	PAGE_REPLACEMENT_DISALLOWED(TRUE);
2988 
2989 	lck_mtx_lock_spin_always(c_list_lock);
2990 
2991 	while (!queue_empty(c_queue) && fastwake_warmup == TRUE) {
2992 		c_seg = (c_segment_t) queue_first(c_queue);
2993 
2994 		if (consider_all_cseg == FALSE) {
2995 			if (c_seg->c_generation_id < first_c_segment_to_warm_generation_id ||
2996 			    c_seg->c_generation_id > last_c_segment_to_warm_generation_id) {
2997 				break;
2998 			}
2999 
3000 			if (vm_page_free_count < (AVAILABLE_MEMORY / 4)) {
3001 				break;
3002 			}
3003 		}
3004 
3005 		lck_mtx_lock_spin_always(&c_seg->c_lock);
3006 		lck_mtx_unlock_always(c_list_lock);
3007 
3008 		if (c_seg->c_busy) {
3009 			PAGE_REPLACEMENT_DISALLOWED(FALSE);
3010 			c_seg_wait_on_busy(c_seg);
3011 			PAGE_REPLACEMENT_DISALLOWED(TRUE);
3012 		} else {
3013 			if (c_seg_swapin(c_seg, TRUE, FALSE) == 0) {
3014 				lck_mtx_unlock_always(&c_seg->c_lock);
3015 			}
3016 			c_segment_warmup_count++;
3017 
3018 			PAGE_REPLACEMENT_DISALLOWED(FALSE);
3019 			vm_pageout_io_throttle();
3020 			PAGE_REPLACEMENT_DISALLOWED(TRUE);
3021 		}
3022 		lck_mtx_lock_spin_always(c_list_lock);
3023 	}
3024 	lck_mtx_unlock_always(c_list_lock);
3025 
3026 	PAGE_REPLACEMENT_DISALLOWED(FALSE);
3027 
3028 	proc_set_thread_policy(current_thread(),
3029 	    TASK_POLICY_INTERNAL, TASK_POLICY_IO, THROTTLE_LEVEL_COMPRESSOR_TIER0);
3030 
3031 	clock_get_uptime(&endTime);
3032 	SUB_ABSOLUTETIME(&endTime, &startTime);
3033 	absolutetime_to_nanoseconds(endTime, &nsec);
3034 
3035 	HIBLOG("vm_compressor_fastwake_warmup completed - took %qd msecs\n", nsec / 1000000ULL);
3036 
3037 	lck_mtx_lock_spin_always(c_list_lock);
3038 
3039 	if (consider_all_cseg == FALSE) {
3040 		first_c_segment_to_warm_generation_id = last_c_segment_to_warm_generation_id = 0;
3041 	}
3042 }
3043 
3044 int min_csegs_per_major_compaction = DELAYED_COMPACTIONS_PER_PASS;
3045 extern bool     vm_swapout_thread_running;
3046 extern boolean_t        compressor_store_stop_compaction;
3047 
3048 void
vm_compressor_compact_and_swap(boolean_t flush_all)3049 vm_compressor_compact_and_swap(boolean_t flush_all)
3050 {
3051 	c_segment_t     c_seg, c_seg_next;
3052 	boolean_t       keep_compacting, switch_state;
3053 	clock_sec_t     now;
3054 	clock_nsec_t    nsec;
3055 	mach_timespec_t start_ts, end_ts;
3056 	unsigned int    number_considered, wanted_cseg_found, yield_after_considered_per_pass, number_yields;
3057 	uint64_t        bytes_to_free, bytes_freed, delta_usec;
3058 
3059 	VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_START, c_age_count, c_minor_count, c_major_count, vm_page_free_count);
3060 
3061 	if (fastwake_warmup == TRUE) {
3062 		uint64_t        starting_warmup_count;
3063 
3064 		starting_warmup_count = c_segment_warmup_count;
3065 
3066 		KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 11) | DBG_FUNC_START, c_segment_warmup_count,
3067 		    first_c_segment_to_warm_generation_id, last_c_segment_to_warm_generation_id, 0, 0);
3068 		do_fastwake_warmup(&c_swappedout_list_head, FALSE);
3069 		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);
3070 
3071 		fastwake_warmup = FALSE;
3072 	}
3073 
3074 #if (XNU_TARGET_OS_OSX && __arm64__)
3075 	/*
3076 	 * Re-considering major csegs showed benefits on all platforms by
3077 	 * significantly reducing fragmentation and getting back memory.
3078 	 * However, on smaller devices, eg watch, there was increased power
3079 	 * use for the additional compactions. And the turnover in csegs on
3080 	 * those smaller platforms is high enough in the decompression/free
3081 	 * path that we can skip reconsidering them here because we already
3082 	 * consider them for major compaction in those paths.
3083 	 */
3084 	vm_compressor_process_major_segments();
3085 #endif /* (XNU_TARGET_OS_OSX && __arm64__) */
3086 
3087 	/*
3088 	 * it's possible for the c_age_list_head to be empty if we
3089 	 * hit our limits for growing the compressor pool and we subsequently
3090 	 * hibernated... on the next hibernation we could see the queue as
3091 	 * empty and not proceeed even though we have a bunch of segments on
3092 	 * the swapped in queue that need to be dealt with.
3093 	 */
3094 	vm_compressor_do_delayed_compactions(flush_all);
3095 
3096 	vm_compressor_age_swapped_in_segments(flush_all);
3097 
3098 	/*
3099 	 * we only need to grab the timestamp once per
3100 	 * invocation of this function since the
3101 	 * timescale we're interested in is measured
3102 	 * in days
3103 	 */
3104 	clock_get_system_nanotime(&now, &nsec);
3105 
3106 	start_ts.tv_sec = (int) now;
3107 	start_ts.tv_nsec = nsec;
3108 	delta_usec = 0;
3109 	number_considered = 0;
3110 	wanted_cseg_found = 0;
3111 	number_yields = 0;
3112 	bytes_to_free = 0;
3113 	bytes_freed = 0;
3114 	yield_after_considered_per_pass = MAX(min_csegs_per_major_compaction, DELAYED_COMPACTIONS_PER_PASS);
3115 
3116 	while (!queue_empty(&c_age_list_head) && !compaction_swapper_abort && !compressor_store_stop_compaction) {
3117 		if (hibernate_flushing == TRUE) {
3118 			clock_sec_t     sec;
3119 
3120 			if (hibernate_should_abort()) {
3121 				HIBLOG("vm_compressor_flush - hibernate_should_abort returned TRUE\n");
3122 				break;
3123 			}
3124 			if (hibernate_no_swapspace == TRUE) {
3125 				HIBLOG("vm_compressor_flush - out of swap space\n");
3126 				break;
3127 			}
3128 			if (vm_swap_files_pinned() == FALSE) {
3129 				HIBLOG("vm_compressor_flush - unpinned swap files\n");
3130 				break;
3131 			}
3132 			if (hibernate_in_progress_with_pinned_swap == TRUE &&
3133 			    (vm_swapfile_total_segs_alloced == vm_swapfile_total_segs_used)) {
3134 				HIBLOG("vm_compressor_flush - out of pinned swap space\n");
3135 				break;
3136 			}
3137 			clock_get_system_nanotime(&sec, &nsec);
3138 
3139 			if (sec > hibernate_flushing_deadline) {
3140 				hibernate_flush_timed_out = TRUE;
3141 				HIBLOG("vm_compressor_flush - failed to finish before deadline\n");
3142 				break;
3143 			}
3144 		}
3145 		if (!vm_swap_out_of_space() && c_swapout_count >= C_SWAPOUT_LIMIT) {
3146 			assert_wait_timeout((event_t) &compaction_swapper_running, THREAD_INTERRUPTIBLE, 100, 1000 * NSEC_PER_USEC);
3147 
3148 			if (!vm_swapout_thread_running) {
3149 				thread_wakeup((event_t)&c_swapout_list_head);
3150 			}
3151 
3152 			lck_mtx_unlock_always(c_list_lock);
3153 
3154 			VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 1, c_swapout_count, 0, 0);
3155 
3156 			thread_block(THREAD_CONTINUE_NULL);
3157 
3158 			lck_mtx_lock_spin_always(c_list_lock);
3159 		}
3160 		/*
3161 		 * Minor compactions
3162 		 */
3163 		vm_compressor_do_delayed_compactions(flush_all);
3164 
3165 		vm_compressor_age_swapped_in_segments(flush_all);
3166 
3167 		if (!vm_swap_out_of_space() && c_swapout_count >= C_SWAPOUT_LIMIT) {
3168 			/*
3169 			 * we timed out on the above thread_block
3170 			 * let's loop around and try again
3171 			 * the timeout allows us to continue
3172 			 * to do minor compactions to make
3173 			 * more memory available
3174 			 */
3175 			VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 2, c_swapout_count, 0, 0);
3176 
3177 			continue;
3178 		}
3179 
3180 		/*
3181 		 * Swap out segments?
3182 		 */
3183 		if (flush_all == FALSE) {
3184 			boolean_t       needs_to_swap;
3185 
3186 			lck_mtx_unlock_always(c_list_lock);
3187 
3188 			needs_to_swap = compressor_needs_to_swap();
3189 
3190 			lck_mtx_lock_spin_always(c_list_lock);
3191 
3192 			VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 3, needs_to_swap, 0, 0);
3193 
3194 			if (needs_to_swap == FALSE) {
3195 				break;
3196 			}
3197 		}
3198 		if (queue_empty(&c_age_list_head)) {
3199 			VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 4, c_age_count, 0, 0);
3200 			break;
3201 		}
3202 		c_seg = (c_segment_t) queue_first(&c_age_list_head);
3203 
3204 		assert(c_seg->c_state == C_ON_AGE_Q);
3205 
3206 		if (flush_all == TRUE && c_seg->c_generation_id > c_generation_id_flush_barrier) {
3207 			VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 5, 0, 0, 0);
3208 			break;
3209 		}
3210 
3211 		lck_mtx_lock_spin_always(&c_seg->c_lock);
3212 
3213 		if (c_seg->c_busy) {
3214 			VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 6, (void*) VM_KERNEL_ADDRPERM(c_seg), 0, 0);
3215 
3216 			lck_mtx_unlock_always(c_list_lock);
3217 			c_seg_wait_on_busy(c_seg);
3218 			lck_mtx_lock_spin_always(c_list_lock);
3219 
3220 			continue;
3221 		}
3222 		C_SEG_BUSY(c_seg);
3223 
3224 		if (c_seg_do_minor_compaction_and_unlock(c_seg, FALSE, TRUE, TRUE)) {
3225 			/*
3226 			 * found an empty c_segment and freed it
3227 			 * so go grab the next guy in the queue
3228 			 */
3229 			VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 7, 0, 0, 0);
3230 			c_seg_major_compact_stats[c_seg_major_compact_stats_now].count_of_freed_segs++;
3231 			continue;
3232 		}
3233 		/*
3234 		 * Major compaction
3235 		 */
3236 		keep_compacting = TRUE;
3237 		switch_state = TRUE;
3238 
3239 		while (keep_compacting == TRUE) {
3240 			assert(c_seg->c_busy);
3241 
3242 			/* look for another segment to consolidate */
3243 
3244 			c_seg_next = (c_segment_t) queue_next(&c_seg->c_age_list);
3245 
3246 			if (queue_end(&c_age_list_head, (queue_entry_t)c_seg_next)) {
3247 				break;
3248 			}
3249 
3250 			assert(c_seg_next->c_state == C_ON_AGE_Q);
3251 
3252 			number_considered++;
3253 
3254 			if (c_seg_major_compact_ok(c_seg, c_seg_next) == FALSE) {
3255 				break;
3256 			}
3257 
3258 			lck_mtx_lock_spin_always(&c_seg_next->c_lock);
3259 
3260 			if (c_seg_next->c_busy) {
3261 				/*
3262 				 * We are going to block for our neighbor.
3263 				 * If our c_seg is wanted, we should unbusy
3264 				 * it because we don't know how long we might
3265 				 * have to block here.
3266 				 */
3267 				if (c_seg->c_wanted) {
3268 					lck_mtx_unlock_always(&c_seg_next->c_lock);
3269 					switch_state = FALSE;
3270 					c_seg_major_compact_stats[c_seg_major_compact_stats_now].bailed_compactions++;
3271 					wanted_cseg_found++;
3272 					break;
3273 				}
3274 
3275 				lck_mtx_unlock_always(c_list_lock);
3276 
3277 				VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 8, (void*) VM_KERNEL_ADDRPERM(c_seg_next), 0, 0);
3278 
3279 				c_seg_wait_on_busy(c_seg_next);
3280 				lck_mtx_lock_spin_always(c_list_lock);
3281 
3282 				continue;
3283 			}
3284 			/* grab that segment */
3285 			C_SEG_BUSY(c_seg_next);
3286 
3287 			bytes_to_free = C_SEG_OFFSET_TO_BYTES(c_seg_next->c_populated_offset);
3288 			if (c_seg_do_minor_compaction_and_unlock(c_seg_next, FALSE, TRUE, TRUE)) {
3289 				/*
3290 				 * found an empty c_segment and freed it
3291 				 * so we can't continue to use c_seg_next
3292 				 */
3293 				bytes_freed += bytes_to_free;
3294 				c_seg_major_compact_stats[c_seg_major_compact_stats_now].count_of_freed_segs++;
3295 				continue;
3296 			}
3297 
3298 			/* unlock the list ... */
3299 			lck_mtx_unlock_always(c_list_lock);
3300 
3301 			/* do the major compaction */
3302 
3303 			keep_compacting = c_seg_major_compact(c_seg, c_seg_next);
3304 
3305 			VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 9, keep_compacting, 0, 0);
3306 
3307 			PAGE_REPLACEMENT_DISALLOWED(TRUE);
3308 
3309 			lck_mtx_lock_spin_always(&c_seg_next->c_lock);
3310 			/*
3311 			 * run a minor compaction on the donor segment
3312 			 * since we pulled at least some of it's
3313 			 * data into our target...  if we've emptied
3314 			 * it, now is a good time to free it which
3315 			 * c_seg_minor_compaction_and_unlock also takes care of
3316 			 *
3317 			 * by passing TRUE, we ask for c_busy to be cleared
3318 			 * and c_wanted to be taken care of
3319 			 */
3320 			bytes_to_free = C_SEG_OFFSET_TO_BYTES(c_seg_next->c_populated_offset);
3321 			if (c_seg_minor_compaction_and_unlock(c_seg_next, TRUE)) {
3322 				bytes_freed += bytes_to_free;
3323 				c_seg_major_compact_stats[c_seg_major_compact_stats_now].count_of_freed_segs++;
3324 			} else {
3325 				bytes_to_free -= C_SEG_OFFSET_TO_BYTES(c_seg_next->c_populated_offset);
3326 				bytes_freed += bytes_to_free;
3327 			}
3328 
3329 			PAGE_REPLACEMENT_DISALLOWED(FALSE);
3330 
3331 			/* relock the list */
3332 			lck_mtx_lock_spin_always(c_list_lock);
3333 
3334 			if (c_seg->c_wanted) {
3335 				/*
3336 				 * Our c_seg is in demand. Let's
3337 				 * unbusy it and wakeup the waiters
3338 				 * instead of continuing the compaction
3339 				 * because we could be in this loop
3340 				 * for a while.
3341 				 */
3342 				switch_state = FALSE;
3343 				wanted_cseg_found++;
3344 				c_seg_major_compact_stats[c_seg_major_compact_stats_now].bailed_compactions++;
3345 				break;
3346 			}
3347 		} /* major compaction */
3348 
3349 		VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 10, number_considered, wanted_cseg_found, 0);
3350 
3351 		lck_mtx_lock_spin_always(&c_seg->c_lock);
3352 
3353 		assert(c_seg->c_busy);
3354 		assert(!c_seg->c_on_minorcompact_q);
3355 
3356 		if (switch_state) {
3357 			if (VM_CONFIG_SWAP_IS_ACTIVE) {
3358 				int new_state = C_ON_SWAPOUT_Q;
3359 
3360 #if (XNU_TARGET_OS_OSX && __arm64__)
3361 				if (flush_all == false && compressor_swapout_conditions_met() == false) {
3362 					new_state = C_ON_MAJORCOMPACT_Q;
3363 				}
3364 #endif /* (XNU_TARGET_OS_OSX && __arm64__) */
3365 
3366 				if (new_state == C_ON_SWAPOUT_Q) {
3367 					/*
3368 					 * This mode of putting a generic c_seg on the swapout list is
3369 					 * only supported when we have general swapping enabled
3370 					 */
3371 					clock_sec_t lnow;
3372 					clock_nsec_t lnsec;
3373 					clock_get_system_nanotime(&lnow, &lnsec);
3374 					if (c_seg->c_agedin_ts && (lnow - c_seg->c_agedin_ts) < 30) {
3375 						vmcs_stats.unripe_under_30s++;
3376 					} else if (c_seg->c_agedin_ts && (lnow - c_seg->c_agedin_ts) < 60) {
3377 						vmcs_stats.unripe_under_60s++;
3378 					} else if (c_seg->c_agedin_ts && (lnow - c_seg->c_agedin_ts) < 300) {
3379 						vmcs_stats.unripe_under_300s++;
3380 					}
3381 				}
3382 
3383 				c_seg_switch_state(c_seg, new_state, FALSE);
3384 			} else {
3385 				if ((vm_swapout_ripe_segments == TRUE && c_overage_swapped_count < c_overage_swapped_limit)) {
3386 					assert(VM_CONFIG_SWAP_IS_PRESENT);
3387 					/*
3388 					 * we are running compressor sweeps with swap-behind
3389 					 * make sure the c_seg has aged enough before swapping it
3390 					 * out...
3391 					 */
3392 					if ((now - c_seg->c_creation_ts) >= vm_ripe_target_age) {
3393 						c_seg->c_overage_swap = TRUE;
3394 						c_overage_swapped_count++;
3395 						c_seg_switch_state(c_seg, C_ON_SWAPOUT_Q, FALSE);
3396 					}
3397 				}
3398 			}
3399 			if (c_seg->c_state == C_ON_AGE_Q) {
3400 				/*
3401 				 * this c_seg didn't get moved to the swapout queue
3402 				 * so we need to move it out of the way...
3403 				 * we just did a major compaction on it so put it
3404 				 * on that queue
3405 				 */
3406 				c_seg_switch_state(c_seg, C_ON_MAJORCOMPACT_Q, FALSE);
3407 			} else {
3408 				c_seg_major_compact_stats[c_seg_major_compact_stats_now].wasted_space_in_swapouts += c_seg_bufsize - c_seg->c_bytes_used;
3409 				c_seg_major_compact_stats[c_seg_major_compact_stats_now].count_of_swapouts++;
3410 			}
3411 		}
3412 
3413 		C_SEG_WAKEUP_DONE(c_seg);
3414 
3415 		lck_mtx_unlock_always(&c_seg->c_lock);
3416 
3417 		if (c_swapout_count) {
3418 			/*
3419 			 * We don't pause/yield here because we will either
3420 			 * yield below or at the top of the loop with the
3421 			 * assert_wait_timeout.
3422 			 */
3423 			if (!vm_swapout_thread_running) {
3424 				thread_wakeup((event_t)&c_swapout_list_head);
3425 			}
3426 		}
3427 
3428 		if (number_considered >= yield_after_considered_per_pass) {
3429 			if (wanted_cseg_found) {
3430 				/*
3431 				 * We stopped major compactions on a c_seg
3432 				 * that is wanted. We don't know the priority
3433 				 * of the waiter unfortunately but we are at
3434 				 * a very high priority and so, just in case
3435 				 * the waiter is a critical system daemon or
3436 				 * UI thread, let's give up the CPU in case
3437 				 * the system is running a few CPU intensive
3438 				 * tasks.
3439 				 */
3440 				lck_mtx_unlock_always(c_list_lock);
3441 
3442 				mutex_pause(2); /* 100us yield */
3443 
3444 				number_yields++;
3445 
3446 				VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_NONE, 11, number_considered, number_yields, 0);
3447 
3448 				lck_mtx_lock_spin_always(c_list_lock);
3449 			}
3450 
3451 			number_considered = 0;
3452 			wanted_cseg_found = 0;
3453 		}
3454 	}
3455 	clock_get_system_nanotime(&now, &nsec);
3456 	end_ts.tv_sec = (int) now;
3457 	end_ts.tv_nsec = nsec;
3458 
3459 	SUB_MACH_TIMESPEC(&end_ts, &start_ts);
3460 
3461 	delta_usec = (end_ts.tv_sec * USEC_PER_SEC) + (end_ts.tv_nsec / NSEC_PER_USEC) - (number_yields * 100);
3462 
3463 	delta_usec = MAX(1, delta_usec); /* we could have 0 usec run if conditions weren't right */
3464 
3465 	c_seg_major_compact_stats[c_seg_major_compact_stats_now].bytes_freed_rate_us = (bytes_freed / delta_usec);
3466 
3467 	if ((c_seg_major_compact_stats_now + 1) == C_SEG_MAJOR_COMPACT_STATS_MAX) {
3468 		c_seg_major_compact_stats_now = 0;
3469 	} else {
3470 		c_seg_major_compact_stats_now++;
3471 	}
3472 
3473 	assert(c_seg_major_compact_stats_now < C_SEG_MAJOR_COMPACT_STATS_MAX);
3474 
3475 	VM_DEBUG_CONSTANT_EVENT(vm_compressor_compact_and_swap, VM_COMPRESSOR_COMPACT_AND_SWAP, DBG_FUNC_END, c_age_count, c_minor_count, c_major_count, vm_page_free_count);
3476 }
3477 
3478 
3479 static c_segment_t
c_seg_allocate(c_segment_t * current_chead)3480 c_seg_allocate(c_segment_t *current_chead)
3481 {
3482 	c_segment_t     c_seg;
3483 	int             min_needed;
3484 	int             size_to_populate;
3485 
3486 #if XNU_TARGET_OS_OSX
3487 	if (vm_compressor_low_on_space()) {
3488 		vm_compressor_take_paging_space_action();
3489 	}
3490 #endif /* XNU_TARGET_OS_OSX */
3491 
3492 	if ((c_seg = *current_chead) == NULL) {
3493 		uint32_t        c_segno;
3494 
3495 		lck_mtx_lock_spin_always(c_list_lock);
3496 
3497 		while (c_segments_busy == TRUE) {
3498 			assert_wait((event_t) (&c_segments_busy), THREAD_UNINT);
3499 
3500 			lck_mtx_unlock_always(c_list_lock);
3501 
3502 			thread_block(THREAD_CONTINUE_NULL);
3503 
3504 			lck_mtx_lock_spin_always(c_list_lock);
3505 		}
3506 		if (c_free_segno_head == (uint32_t)-1) {
3507 			uint32_t        c_segments_available_new;
3508 			uint32_t        compressed_pages;
3509 
3510 #if CONFIG_FREEZE
3511 			if (freezer_incore_cseg_acct) {
3512 				compressed_pages = c_segment_pages_compressed_incore;
3513 			} else {
3514 				compressed_pages = c_segment_pages_compressed;
3515 			}
3516 #else
3517 			compressed_pages = c_segment_pages_compressed;
3518 #endif /* CONFIG_FREEZE */
3519 
3520 			if (c_segments_available >= c_segments_limit || compressed_pages >= c_segment_pages_compressed_limit) {
3521 				lck_mtx_unlock_always(c_list_lock);
3522 
3523 				return NULL;
3524 			}
3525 			c_segments_busy = TRUE;
3526 			lck_mtx_unlock_always(c_list_lock);
3527 
3528 			kernel_memory_populate((vm_offset_t)c_segments_next_page,
3529 			    PAGE_SIZE, KMA_NOFAIL | KMA_KOBJECT,
3530 			    VM_KERN_MEMORY_COMPRESSOR);
3531 			c_segments_next_page += PAGE_SIZE;
3532 
3533 			c_segments_available_new = c_segments_available + C_SEGMENTS_PER_PAGE;
3534 
3535 			if (c_segments_available_new > c_segments_limit) {
3536 				c_segments_available_new = c_segments_limit;
3537 			}
3538 
3539 			for (c_segno = c_segments_available + 1; c_segno < c_segments_available_new; c_segno++) {
3540 				c_segments[c_segno - 1].c_segno = c_segno;
3541 			}
3542 
3543 			lck_mtx_lock_spin_always(c_list_lock);
3544 
3545 			c_segments[c_segno - 1].c_segno = c_free_segno_head;
3546 			c_free_segno_head = c_segments_available;
3547 			c_segments_available = c_segments_available_new;
3548 
3549 			c_segments_busy = FALSE;
3550 			thread_wakeup((event_t) (&c_segments_busy));
3551 		}
3552 		c_segno = c_free_segno_head;
3553 		assert(c_segno >= 0 && c_segno < c_segments_limit);
3554 
3555 		c_free_segno_head = (uint32_t)c_segments[c_segno].c_segno;
3556 
3557 		/*
3558 		 * do the rest of the bookkeeping now while we're still behind
3559 		 * the list lock and grab our generation id now into a local
3560 		 * so that we can install it once we have the c_seg allocated
3561 		 */
3562 		c_segment_count++;
3563 		if (c_segment_count > c_segment_count_max) {
3564 			c_segment_count_max = c_segment_count;
3565 		}
3566 
3567 		lck_mtx_unlock_always(c_list_lock);
3568 
3569 		c_seg = zalloc_flags(compressor_segment_zone, Z_WAITOK | Z_ZERO);
3570 
3571 		c_seg->c_store.c_buffer = (int32_t *)C_SEG_BUFFER_ADDRESS(c_segno);
3572 
3573 		lck_mtx_init(&c_seg->c_lock, &vm_compressor_lck_grp, LCK_ATTR_NULL);
3574 
3575 		c_seg->c_state = C_IS_EMPTY;
3576 		c_seg->c_firstemptyslot = C_SLOT_MAX_INDEX;
3577 		c_seg->c_mysegno = c_segno;
3578 
3579 		lck_mtx_lock_spin_always(c_list_lock);
3580 		c_empty_count++;
3581 		c_seg_switch_state(c_seg, C_IS_FILLING, FALSE);
3582 		c_segments[c_segno].c_seg = c_seg;
3583 		assert(c_segments[c_segno].c_segno > c_segments_available);
3584 		lck_mtx_unlock_always(c_list_lock);
3585 
3586 		*current_chead = c_seg;
3587 
3588 #if DEVELOPMENT || DEBUG
3589 		C_SEG_MAKE_WRITEABLE(c_seg);
3590 #endif
3591 	}
3592 	c_seg_alloc_nextslot(c_seg);
3593 
3594 	size_to_populate = c_seg_allocsize - C_SEG_OFFSET_TO_BYTES(c_seg->c_populated_offset);
3595 
3596 	if (size_to_populate) {
3597 		min_needed = PAGE_SIZE + (c_seg_allocsize - c_seg_bufsize);
3598 
3599 		if (C_SEG_OFFSET_TO_BYTES(c_seg->c_populated_offset - c_seg->c_nextoffset) < (unsigned) min_needed) {
3600 			if (size_to_populate > C_SEG_MAX_POPULATE_SIZE) {
3601 				size_to_populate = C_SEG_MAX_POPULATE_SIZE;
3602 			}
3603 
3604 			OSAddAtomic64(size_to_populate / PAGE_SIZE, &vm_pageout_vminfo.vm_compressor_pages_grabbed);
3605 
3606 			kernel_memory_populate(
3607 				(vm_offset_t) &c_seg->c_store.c_buffer[c_seg->c_populated_offset],
3608 				size_to_populate,
3609 				KMA_NOFAIL | KMA_COMPRESSOR,
3610 				VM_KERN_MEMORY_COMPRESSOR);
3611 		} else {
3612 			size_to_populate = 0;
3613 		}
3614 	}
3615 	PAGE_REPLACEMENT_DISALLOWED(TRUE);
3616 
3617 	lck_mtx_lock_spin_always(&c_seg->c_lock);
3618 
3619 	if (size_to_populate) {
3620 		c_seg->c_populated_offset += C_SEG_BYTES_TO_OFFSET(size_to_populate);
3621 	}
3622 
3623 	return c_seg;
3624 }
3625 
3626 #if DEVELOPMENT || DEBUG
3627 #if CONFIG_FREEZE
3628 extern boolean_t memorystatus_freeze_to_memory;
3629 #endif /* CONFIG_FREEZE */
3630 #endif /* DEVELOPMENT || DEBUG */
3631 
3632 static void
c_current_seg_filled(c_segment_t c_seg,c_segment_t * current_chead)3633 c_current_seg_filled(c_segment_t c_seg, c_segment_t *current_chead)
3634 {
3635 	uint32_t        unused_bytes;
3636 	uint32_t        offset_to_depopulate;
3637 	int             new_state = C_ON_AGE_Q;
3638 	clock_sec_t     sec;
3639 	clock_nsec_t    nsec;
3640 	boolean_t       head_insert = FALSE;
3641 
3642 	unused_bytes = trunc_page_32(C_SEG_OFFSET_TO_BYTES(c_seg->c_populated_offset - c_seg->c_nextoffset));
3643 
3644 	if (unused_bytes) {
3645 		offset_to_depopulate = C_SEG_BYTES_TO_OFFSET(round_page_32(C_SEG_OFFSET_TO_BYTES(c_seg->c_nextoffset)));
3646 
3647 		/*
3648 		 *  release the extra physical page(s) at the end of the segment
3649 		 */
3650 		lck_mtx_unlock_always(&c_seg->c_lock);
3651 
3652 		kernel_memory_depopulate(
3653 			(vm_offset_t) &c_seg->c_store.c_buffer[offset_to_depopulate],
3654 			unused_bytes,
3655 			KMA_COMPRESSOR,
3656 			VM_KERN_MEMORY_COMPRESSOR);
3657 
3658 		lck_mtx_lock_spin_always(&c_seg->c_lock);
3659 
3660 		c_seg->c_populated_offset = offset_to_depopulate;
3661 	}
3662 	assert(C_SEG_OFFSET_TO_BYTES(c_seg->c_populated_offset) <= c_seg_bufsize);
3663 
3664 #if DEVELOPMENT || DEBUG
3665 	{
3666 		boolean_t       c_seg_was_busy = FALSE;
3667 
3668 		if (!c_seg->c_busy) {
3669 			C_SEG_BUSY(c_seg);
3670 		} else {
3671 			c_seg_was_busy = TRUE;
3672 		}
3673 
3674 		lck_mtx_unlock_always(&c_seg->c_lock);
3675 
3676 		C_SEG_WRITE_PROTECT(c_seg);
3677 
3678 		lck_mtx_lock_spin_always(&c_seg->c_lock);
3679 
3680 		if (c_seg_was_busy == FALSE) {
3681 			C_SEG_WAKEUP_DONE(c_seg);
3682 		}
3683 	}
3684 #endif
3685 
3686 #if CONFIG_FREEZE
3687 	if (current_chead == (c_segment_t*) &(freezer_context_global.freezer_ctx_chead) &&
3688 	    VM_CONFIG_SWAP_IS_PRESENT &&
3689 	    VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
3690 #if DEVELOPMENT || DEBUG
3691 	    && !memorystatus_freeze_to_memory
3692 #endif /* DEVELOPMENT || DEBUG */
3693 	    ) {
3694 		new_state = C_ON_SWAPOUT_Q;
3695 	}
3696 #endif /* CONFIG_FREEZE */
3697 
3698 	if (vm_darkwake_mode == TRUE) {
3699 		new_state = C_ON_SWAPOUT_Q;
3700 		head_insert = TRUE;
3701 	}
3702 
3703 	clock_get_system_nanotime(&sec, &nsec);
3704 	c_seg->c_creation_ts = (uint32_t)sec;
3705 
3706 	lck_mtx_lock_spin_always(c_list_lock);
3707 
3708 	c_seg->c_generation_id = c_generation_id++;
3709 	c_seg_switch_state(c_seg, new_state, head_insert);
3710 
3711 #if CONFIG_FREEZE
3712 	if (c_seg->c_state == C_ON_SWAPOUT_Q) {
3713 		/*
3714 		 * darkwake and freezer can't co-exist together
3715 		 * We'll need to fix this accounting as a start.
3716 		 */
3717 		assert(vm_darkwake_mode == FALSE);
3718 		c_seg_update_task_owner(c_seg, freezer_context_global.freezer_ctx_task);
3719 		freezer_context_global.freezer_ctx_swapped_bytes += c_seg->c_bytes_used;
3720 	}
3721 #endif /* CONFIG_FREEZE */
3722 
3723 	if (c_seg->c_state == C_ON_AGE_Q && C_SEG_UNUSED_BYTES(c_seg) >= PAGE_SIZE) {
3724 #if CONFIG_FREEZE
3725 		assert(c_seg->c_task_owner == NULL);
3726 #endif /* CONFIG_FREEZE */
3727 		c_seg_need_delayed_compaction(c_seg, TRUE);
3728 	}
3729 
3730 	lck_mtx_unlock_always(c_list_lock);
3731 
3732 	if (c_seg->c_state == C_ON_SWAPOUT_Q) {
3733 		/*
3734 		 * Darkwake and Freeze configs always
3735 		 * wake up the swapout thread because
3736 		 * the compactor thread that normally handles
3737 		 * it may not be running as much in these
3738 		 * configs.
3739 		 */
3740 		thread_wakeup((event_t)&c_swapout_list_head);
3741 	}
3742 
3743 	*current_chead = NULL;
3744 }
3745 
3746 
3747 #if (XNU_TARGET_OS_OSX && __arm64__)
3748 static void
vm_compressor_process_major_segments(void)3749 vm_compressor_process_major_segments(void)
3750 {
3751 	c_segment_t c_seg = NULL, c_seg_next = NULL;
3752 	if (!queue_empty(&c_major_list_head)) {
3753 		c_seg = (c_segment_t)queue_first(&c_major_list_head);
3754 
3755 		while (!queue_end(&c_major_list_head, (queue_entry_t)c_seg)) {
3756 			c_seg_next = (c_segment_t) queue_next(&c_seg->c_age_list);
3757 			lck_mtx_lock_spin_always(&c_seg->c_lock);
3758 			c_seg_switch_state(c_seg, C_ON_AGE_Q, FALSE);
3759 			lck_mtx_unlock_always(&c_seg->c_lock);
3760 			c_seg = c_seg_next;
3761 		}
3762 	}
3763 }
3764 #endif /* (XNU_TARGET_OS_OSX && __arm64__) */
3765 
3766 /*
3767  * returns with c_seg locked
3768  */
3769 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)3770 c_seg_swapin_requeue(c_segment_t c_seg, boolean_t has_data, boolean_t minor_compact_ok, boolean_t age_on_swapin_q)
3771 {
3772 	clock_sec_t     sec;
3773 	clock_nsec_t    nsec;
3774 
3775 	clock_get_system_nanotime(&sec, &nsec);
3776 
3777 	lck_mtx_lock_spin_always(c_list_lock);
3778 	lck_mtx_lock_spin_always(&c_seg->c_lock);
3779 
3780 	assert(c_seg->c_busy_swapping);
3781 	assert(c_seg->c_busy);
3782 
3783 	c_seg->c_busy_swapping = 0;
3784 
3785 	if (c_seg->c_overage_swap == TRUE) {
3786 		c_overage_swapped_count--;
3787 		c_seg->c_overage_swap = FALSE;
3788 	}
3789 	if (has_data == TRUE) {
3790 		if (age_on_swapin_q == TRUE) {
3791 			c_seg_switch_state(c_seg, C_ON_SWAPPEDIN_Q, FALSE);
3792 		} else {
3793 			c_seg_switch_state(c_seg, C_ON_AGE_Q, FALSE);
3794 		}
3795 
3796 		if (minor_compact_ok == TRUE && !c_seg->c_on_minorcompact_q && C_SEG_UNUSED_BYTES(c_seg) >= PAGE_SIZE) {
3797 			c_seg_need_delayed_compaction(c_seg, TRUE);
3798 		}
3799 	} else {
3800 		c_seg->c_store.c_buffer = (int32_t*) NULL;
3801 		c_seg->c_populated_offset = C_SEG_BYTES_TO_OFFSET(0);
3802 
3803 		c_seg_switch_state(c_seg, C_ON_BAD_Q, FALSE);
3804 	}
3805 	c_seg->c_swappedin_ts = (uint32_t)sec;
3806 	c_seg->c_swappedin = true;
3807 
3808 	lck_mtx_unlock_always(c_list_lock);
3809 }
3810 
3811 
3812 
3813 /*
3814  * c_seg has to be locked and is returned locked if the c_seg isn't freed
3815  * PAGE_REPLACMENT_DISALLOWED has to be TRUE on entry and is returned TRUE
3816  * c_seg_swapin returns 1 if the c_seg was freed, 0 otherwise
3817  */
3818 
3819 int
c_seg_swapin(c_segment_t c_seg,boolean_t force_minor_compaction,boolean_t age_on_swapin_q)3820 c_seg_swapin(c_segment_t c_seg, boolean_t force_minor_compaction, boolean_t age_on_swapin_q)
3821 {
3822 	vm_offset_t     addr = 0;
3823 	uint32_t        io_size = 0;
3824 	uint64_t        f_offset;
3825 	thread_pri_floor_t token;
3826 
3827 	assert(C_SEG_IS_ONDISK(c_seg));
3828 
3829 #if !CHECKSUM_THE_SWAP
3830 	c_seg_trim_tail(c_seg);
3831 #endif
3832 	io_size = round_page_32(C_SEG_OFFSET_TO_BYTES(c_seg->c_populated_offset));
3833 	f_offset = c_seg->c_store.c_swap_handle;
3834 
3835 	C_SEG_BUSY(c_seg);
3836 	c_seg->c_busy_swapping = 1;
3837 
3838 	/*
3839 	 * This thread is likely going to block for I/O.
3840 	 * Make sure it is ready to run when the I/O completes because
3841 	 * it needs to clear the busy bit on the c_seg so that other
3842 	 * waiting threads can make progress too.
3843 	 */
3844 	token = thread_priority_floor_start();
3845 	lck_mtx_unlock_always(&c_seg->c_lock);
3846 
3847 	PAGE_REPLACEMENT_DISALLOWED(FALSE);
3848 
3849 	addr = (vm_offset_t)C_SEG_BUFFER_ADDRESS(c_seg->c_mysegno);
3850 	c_seg->c_store.c_buffer = (int32_t*) addr;
3851 
3852 	kernel_memory_populate(addr, io_size, KMA_NOFAIL | KMA_COMPRESSOR,
3853 	    VM_KERN_MEMORY_COMPRESSOR);
3854 
3855 	if (vm_swap_get(c_seg, f_offset, io_size) != KERN_SUCCESS) {
3856 		PAGE_REPLACEMENT_DISALLOWED(TRUE);
3857 
3858 		kernel_memory_depopulate(addr, io_size, KMA_COMPRESSOR,
3859 		    VM_KERN_MEMORY_COMPRESSOR);
3860 
3861 		c_seg_swapin_requeue(c_seg, FALSE, TRUE, age_on_swapin_q);
3862 	} else {
3863 #if ENCRYPTED_SWAP
3864 		vm_swap_decrypt(c_seg);
3865 #endif /* ENCRYPTED_SWAP */
3866 
3867 #if CHECKSUM_THE_SWAP
3868 		if (c_seg->cseg_swap_size != io_size) {
3869 			panic("swapin size doesn't match swapout size");
3870 		}
3871 
3872 		if (c_seg->cseg_hash != vmc_hash((char*) c_seg->c_store.c_buffer, (int)io_size)) {
3873 			panic("c_seg_swapin - Swap hash mismatch");
3874 		}
3875 #endif /* CHECKSUM_THE_SWAP */
3876 
3877 		PAGE_REPLACEMENT_DISALLOWED(TRUE);
3878 
3879 		c_seg_swapin_requeue(c_seg, TRUE, force_minor_compaction == TRUE ? FALSE : TRUE, age_on_swapin_q);
3880 
3881 #if CONFIG_FREEZE
3882 		/*
3883 		 * c_seg_swapin_requeue() returns with the c_seg lock held.
3884 		 */
3885 		if (!lck_mtx_try_lock_spin_always(c_list_lock)) {
3886 			assert(c_seg->c_busy);
3887 
3888 			lck_mtx_unlock_always(&c_seg->c_lock);
3889 			lck_mtx_lock_spin_always(c_list_lock);
3890 			lck_mtx_lock_spin_always(&c_seg->c_lock);
3891 		}
3892 
3893 		if (c_seg->c_task_owner) {
3894 			c_seg_update_task_owner(c_seg, NULL);
3895 		}
3896 
3897 		lck_mtx_unlock_always(c_list_lock);
3898 
3899 		OSAddAtomic(c_seg->c_slots_used, &c_segment_pages_compressed_incore);
3900 #endif /* CONFIG_FREEZE */
3901 
3902 		OSAddAtomic64(c_seg->c_bytes_used, &compressor_bytes_used);
3903 
3904 		if (force_minor_compaction == TRUE) {
3905 			if (c_seg_minor_compaction_and_unlock(c_seg, FALSE)) {
3906 				/*
3907 				 * c_seg was completely empty so it was freed,
3908 				 * so be careful not to reference it again
3909 				 *
3910 				 * Drop the boost so that the thread priority
3911 				 * is returned back to where it is supposed to be.
3912 				 */
3913 				thread_priority_floor_end(&token);
3914 				return 1;
3915 			}
3916 
3917 			lck_mtx_lock_spin_always(&c_seg->c_lock);
3918 		}
3919 	}
3920 	C_SEG_WAKEUP_DONE(c_seg);
3921 
3922 	/*
3923 	 * Drop the boost so that the thread priority
3924 	 * is returned back to where it is supposed to be.
3925 	 */
3926 	thread_priority_floor_end(&token);
3927 
3928 	return 0;
3929 }
3930 
3931 
3932 static void
c_segment_sv_hash_drop_ref(int hash_indx)3933 c_segment_sv_hash_drop_ref(int hash_indx)
3934 {
3935 	struct c_sv_hash_entry o_sv_he, n_sv_he;
3936 
3937 	while (1) {
3938 		o_sv_he.he_record = c_segment_sv_hash_table[hash_indx].he_record;
3939 
3940 		n_sv_he.he_ref = o_sv_he.he_ref - 1;
3941 		n_sv_he.he_data = o_sv_he.he_data;
3942 
3943 		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) {
3944 			if (n_sv_he.he_ref == 0) {
3945 				OSAddAtomic(-1, &c_segment_svp_in_hash);
3946 			}
3947 			break;
3948 		}
3949 	}
3950 }
3951 
3952 
3953 static int
c_segment_sv_hash_insert(uint32_t data)3954 c_segment_sv_hash_insert(uint32_t data)
3955 {
3956 	int             hash_sindx;
3957 	int             misses;
3958 	struct c_sv_hash_entry o_sv_he, n_sv_he;
3959 	boolean_t       got_ref = FALSE;
3960 
3961 	if (data == 0) {
3962 		OSAddAtomic(1, &c_segment_svp_zero_compressions);
3963 	} else {
3964 		OSAddAtomic(1, &c_segment_svp_nonzero_compressions);
3965 	}
3966 
3967 	hash_sindx = data & C_SV_HASH_MASK;
3968 
3969 	for (misses = 0; misses < C_SV_HASH_MAX_MISS; misses++) {
3970 		o_sv_he.he_record = c_segment_sv_hash_table[hash_sindx].he_record;
3971 
3972 		while (o_sv_he.he_data == data || o_sv_he.he_ref == 0) {
3973 			n_sv_he.he_ref = o_sv_he.he_ref + 1;
3974 			n_sv_he.he_data = data;
3975 
3976 			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) {
3977 				if (n_sv_he.he_ref == 1) {
3978 					OSAddAtomic(1, &c_segment_svp_in_hash);
3979 				}
3980 				got_ref = TRUE;
3981 				break;
3982 			}
3983 			o_sv_he.he_record = c_segment_sv_hash_table[hash_sindx].he_record;
3984 		}
3985 		if (got_ref == TRUE) {
3986 			break;
3987 		}
3988 		hash_sindx++;
3989 
3990 		if (hash_sindx == C_SV_HASH_SIZE) {
3991 			hash_sindx = 0;
3992 		}
3993 	}
3994 	if (got_ref == FALSE) {
3995 		return -1;
3996 	}
3997 
3998 	return hash_sindx;
3999 }
4000 
4001 
4002 #if RECORD_THE_COMPRESSED_DATA
4003 
4004 static void
c_compressed_record_data(char * src,int c_size)4005 c_compressed_record_data(char *src, int c_size)
4006 {
4007 	if ((c_compressed_record_cptr + c_size + 4) >= c_compressed_record_ebuf) {
4008 		panic("c_compressed_record_cptr >= c_compressed_record_ebuf");
4009 	}
4010 
4011 	*(int *)((void *)c_compressed_record_cptr) = c_size;
4012 
4013 	c_compressed_record_cptr += 4;
4014 
4015 	memcpy(c_compressed_record_cptr, src, c_size);
4016 	c_compressed_record_cptr += c_size;
4017 }
4018 #endif
4019 
4020 
4021 static int
c_compress_page(char * src,c_slot_mapping_t slot_ptr,c_segment_t * current_chead,char * scratch_buf)4022 c_compress_page(char *src, c_slot_mapping_t slot_ptr, c_segment_t *current_chead, char *scratch_buf)
4023 {
4024 	int             c_size = -1;
4025 	int             c_rounded_size = 0;
4026 	int             max_csize;
4027 	c_slot_t        cs;
4028 	c_segment_t     c_seg;
4029 
4030 	KERNEL_DEBUG(0xe0400000 | DBG_FUNC_START, *current_chead, 0, 0, 0, 0);
4031 retry:
4032 	if ((c_seg = c_seg_allocate(current_chead)) == NULL) {
4033 		return 1;
4034 	}
4035 	/*
4036 	 * returns with c_seg lock held
4037 	 * and PAGE_REPLACEMENT_DISALLOWED(TRUE)...
4038 	 * c_nextslot has been allocated and
4039 	 * c_store.c_buffer populated
4040 	 */
4041 	assert(c_seg->c_state == C_IS_FILLING);
4042 
4043 	cs = C_SEG_SLOT_FROM_INDEX(c_seg, c_seg->c_nextslot);
4044 
4045 	C_SLOT_ASSERT_PACKABLE(slot_ptr);
4046 	cs->c_packed_ptr = C_SLOT_PACK_PTR(slot_ptr);
4047 
4048 	cs->c_offset = c_seg->c_nextoffset;
4049 
4050 	max_csize = c_seg_bufsize - C_SEG_OFFSET_TO_BYTES((int32_t)cs->c_offset);
4051 
4052 	if (max_csize > PAGE_SIZE) {
4053 		max_csize = PAGE_SIZE;
4054 	}
4055 
4056 #if CHECKSUM_THE_DATA
4057 	cs->c_hash_data = vmc_hash(src, PAGE_SIZE);
4058 #endif
4059 	boolean_t incomp_copy = FALSE;
4060 	int max_csize_adj = (max_csize - 4);
4061 
4062 	if (vm_compressor_algorithm() != VM_COMPRESSOR_DEFAULT_CODEC) {
4063 #if defined(__arm__) || defined(__arm64__)
4064 		uint16_t ccodec = CINVALID;
4065 		uint32_t inline_popcount;
4066 		if (max_csize >= C_SEG_OFFSET_ALIGNMENT_BOUNDARY) {
4067 			c_size = metacompressor((const uint8_t *) src,
4068 			    (uint8_t *) &c_seg->c_store.c_buffer[cs->c_offset],
4069 			    max_csize_adj, &ccodec,
4070 			    scratch_buf, &incomp_copy, &inline_popcount);
4071 #if __APPLE_WKDM_POPCNT_EXTENSIONS__
4072 			cs->c_inline_popcount = inline_popcount;
4073 #else
4074 			assert(inline_popcount == C_SLOT_NO_POPCOUNT);
4075 #endif
4076 
4077 #if C_SEG_OFFSET_ALIGNMENT_BOUNDARY > 4
4078 			if (c_size > max_csize_adj) {
4079 				c_size = -1;
4080 			}
4081 #endif
4082 		} else {
4083 			c_size = -1;
4084 		}
4085 		assert(ccodec == CCWK || ccodec == CCLZ4);
4086 		cs->c_codec = ccodec;
4087 #endif
4088 	} else {
4089 #if defined(__arm__) || defined(__arm64__)
4090 		cs->c_codec = CCWK;
4091 #endif
4092 #if defined(__arm64__)
4093 		__unreachable_ok_push
4094 		if (PAGE_SIZE == 4096) {
4095 			c_size = WKdm_compress_4k((WK_word *)(uintptr_t)src, (WK_word *)(uintptr_t)&c_seg->c_store.c_buffer[cs->c_offset],
4096 			    (WK_word *)(uintptr_t)scratch_buf, max_csize_adj);
4097 		} else {
4098 			c_size = WKdm_compress_16k((WK_word *)(uintptr_t)src, (WK_word *)(uintptr_t)&c_seg->c_store.c_buffer[cs->c_offset],
4099 			    (WK_word *)(uintptr_t)scratch_buf, max_csize_adj);
4100 		}
4101 		__unreachable_ok_pop
4102 #else
4103 		c_size = WKdm_compress_new((const WK_word *)(uintptr_t)src, (WK_word *)(uintptr_t)&c_seg->c_store.c_buffer[cs->c_offset],
4104 		    (WK_word *)(uintptr_t)scratch_buf, max_csize_adj);
4105 #endif
4106 	}
4107 	assertf(((c_size <= max_csize_adj) && (c_size >= -1)),
4108 	    "c_size invalid (%d, %d), cur compressions: %d", c_size, max_csize_adj, c_segment_pages_compressed);
4109 
4110 	if (c_size == -1) {
4111 		if (max_csize < PAGE_SIZE) {
4112 			c_current_seg_filled(c_seg, current_chead);
4113 			assert(*current_chead == NULL);
4114 
4115 			lck_mtx_unlock_always(&c_seg->c_lock);
4116 			/* TODO: it may be worth requiring codecs to distinguish
4117 			 * between incompressible inputs and failures due to
4118 			 * budget exhaustion.
4119 			 */
4120 			PAGE_REPLACEMENT_DISALLOWED(FALSE);
4121 			goto retry;
4122 		}
4123 		c_size = PAGE_SIZE;
4124 
4125 		if (incomp_copy == FALSE) {
4126 			memcpy(&c_seg->c_store.c_buffer[cs->c_offset], src, c_size);
4127 		}
4128 
4129 		OSAddAtomic(1, &c_segment_noncompressible_pages);
4130 	} else if (c_size == 0) {
4131 		int             hash_index;
4132 
4133 		/*
4134 		 * special case - this is a page completely full of a single 32 bit value
4135 		 */
4136 		hash_index = c_segment_sv_hash_insert(*(uint32_t *)(uintptr_t)src);
4137 
4138 		if (hash_index != -1) {
4139 			slot_ptr->s_cindx = hash_index;
4140 			slot_ptr->s_cseg = C_SV_CSEG_ID;
4141 
4142 			OSAddAtomic(1, &c_segment_svp_hash_succeeded);
4143 #if RECORD_THE_COMPRESSED_DATA
4144 			c_compressed_record_data(src, 4);
4145 #endif
4146 			goto sv_compression;
4147 		}
4148 		c_size = 4;
4149 
4150 		memcpy(&c_seg->c_store.c_buffer[cs->c_offset], src, c_size);
4151 
4152 		OSAddAtomic(1, &c_segment_svp_hash_failed);
4153 	}
4154 
4155 #if RECORD_THE_COMPRESSED_DATA
4156 	c_compressed_record_data((char *)&c_seg->c_store.c_buffer[cs->c_offset], c_size);
4157 #endif
4158 #if CHECKSUM_THE_COMPRESSED_DATA
4159 	cs->c_hash_compressed_data = vmc_hash((char *)&c_seg->c_store.c_buffer[cs->c_offset], c_size);
4160 #endif
4161 #if POPCOUNT_THE_COMPRESSED_DATA
4162 	cs->c_pop_cdata = vmc_pop((uintptr_t) &c_seg->c_store.c_buffer[cs->c_offset], c_size);
4163 #endif
4164 	c_rounded_size = (c_size + C_SEG_OFFSET_ALIGNMENT_MASK) & ~C_SEG_OFFSET_ALIGNMENT_MASK;
4165 
4166 	PACK_C_SIZE(cs, c_size);
4167 	c_seg->c_bytes_used += c_rounded_size;
4168 	c_seg->c_nextoffset += C_SEG_BYTES_TO_OFFSET(c_rounded_size);
4169 	c_seg->c_slots_used++;
4170 
4171 	slot_ptr->s_cindx = c_seg->c_nextslot++;
4172 	/* <csegno=0,indx=0> would mean "empty slot", so use csegno+1 */
4173 	slot_ptr->s_cseg = c_seg->c_mysegno + 1;
4174 
4175 sv_compression:
4176 	if (c_seg->c_nextoffset >= c_seg_off_limit || c_seg->c_nextslot >= C_SLOT_MAX_INDEX) {
4177 		c_current_seg_filled(c_seg, current_chead);
4178 		assert(*current_chead == NULL);
4179 	}
4180 	lck_mtx_unlock_always(&c_seg->c_lock);
4181 
4182 	PAGE_REPLACEMENT_DISALLOWED(FALSE);
4183 
4184 #if RECORD_THE_COMPRESSED_DATA
4185 	if ((c_compressed_record_cptr - c_compressed_record_sbuf) >= c_seg_allocsize) {
4186 		c_compressed_record_write(c_compressed_record_sbuf, (int)(c_compressed_record_cptr - c_compressed_record_sbuf));
4187 		c_compressed_record_cptr = c_compressed_record_sbuf;
4188 	}
4189 #endif
4190 	if (c_size) {
4191 		OSAddAtomic64(c_size, &c_segment_compressed_bytes);
4192 		OSAddAtomic64(c_rounded_size, &compressor_bytes_used);
4193 	}
4194 	OSAddAtomic64(PAGE_SIZE, &c_segment_input_bytes);
4195 
4196 	OSAddAtomic(1, &c_segment_pages_compressed);
4197 #if CONFIG_FREEZE
4198 	OSAddAtomic(1, &c_segment_pages_compressed_incore);
4199 #endif /* CONFIG_FREEZE */
4200 	OSAddAtomic(1, &sample_period_compression_count);
4201 
4202 	KERNEL_DEBUG(0xe0400000 | DBG_FUNC_END, *current_chead, c_size, c_segment_input_bytes, c_segment_compressed_bytes, 0);
4203 
4204 	return 0;
4205 }
4206 
4207 static inline void
sv_decompress(int32_t * ddst,int32_t pattern)4208 sv_decompress(int32_t *ddst, int32_t pattern)
4209 {
4210 //	assert(__builtin_constant_p(PAGE_SIZE) != 0);
4211 #if defined(__x86_64__)
4212 	memset_word(ddst, pattern, PAGE_SIZE / sizeof(int32_t));
4213 #elif defined(__arm64__)
4214 	assert((PAGE_SIZE % 128) == 0);
4215 	if (pattern == 0) {
4216 		fill32_dczva((addr64_t)ddst, PAGE_SIZE);
4217 	} else {
4218 		fill32_nt((addr64_t)ddst, PAGE_SIZE, pattern);
4219 	}
4220 #else
4221 	size_t          i;
4222 
4223 	/* Unroll the pattern fill loop 4x to encourage the
4224 	 * compiler to emit NEON stores, cf.
4225 	 * <rdar://problem/25839866> Loop autovectorization
4226 	 * anomalies.
4227 	 */
4228 	/* * We use separate loops for each PAGE_SIZE
4229 	 * to allow the autovectorizer to engage, as PAGE_SIZE
4230 	 * may not be a constant.
4231 	 */
4232 
4233 	__unreachable_ok_push
4234 	if (PAGE_SIZE == 4096) {
4235 		for (i = 0; i < (4096U / sizeof(int32_t)); i += 4) {
4236 			*ddst++ = pattern;
4237 			*ddst++ = pattern;
4238 			*ddst++ = pattern;
4239 			*ddst++ = pattern;
4240 		}
4241 	} else {
4242 		assert(PAGE_SIZE == 16384);
4243 		for (i = 0; i < (int)(16384U / sizeof(int32_t)); i += 4) {
4244 			*ddst++ = pattern;
4245 			*ddst++ = pattern;
4246 			*ddst++ = pattern;
4247 			*ddst++ = pattern;
4248 		}
4249 	}
4250 	__unreachable_ok_pop
4251 #endif
4252 }
4253 
4254 static int
c_decompress_page(char * dst,volatile c_slot_mapping_t slot_ptr,int flags,int * zeroslot)4255 c_decompress_page(char *dst, volatile c_slot_mapping_t slot_ptr, int flags, int *zeroslot)
4256 {
4257 	c_slot_t        cs;
4258 	c_segment_t     c_seg;
4259 	uint32_t        c_segno;
4260 	uint16_t        c_indx;
4261 	int             c_rounded_size;
4262 	uint32_t        c_size;
4263 	int             retval = 0;
4264 	boolean_t       need_unlock = TRUE;
4265 	boolean_t       consider_defragmenting = FALSE;
4266 	boolean_t       kdp_mode = FALSE;
4267 
4268 	if (__improbable(flags & C_KDP)) {
4269 		if (not_in_kdp) {
4270 			panic("C_KDP passed to decompress page from outside of debugger context");
4271 		}
4272 
4273 		assert((flags & C_KEEP) == C_KEEP);
4274 		assert((flags & C_DONT_BLOCK) == C_DONT_BLOCK);
4275 
4276 		if ((flags & (C_DONT_BLOCK | C_KEEP)) != (C_DONT_BLOCK | C_KEEP)) {
4277 			return -2;
4278 		}
4279 
4280 		kdp_mode = TRUE;
4281 		*zeroslot = 0;
4282 	}
4283 
4284 ReTry:
4285 	if (__probable(!kdp_mode)) {
4286 		PAGE_REPLACEMENT_DISALLOWED(TRUE);
4287 	} else {
4288 		if (kdp_lck_rw_lock_is_acquired_exclusive(&c_master_lock)) {
4289 			return -2;
4290 		}
4291 	}
4292 
4293 #if HIBERNATION
4294 	/*
4295 	 * if hibernation is enabled, it indicates (via a call
4296 	 * to 'vm_decompressor_lock' that no further
4297 	 * decompressions are allowed once it reaches
4298 	 * the point of flushing all of the currently dirty
4299 	 * anonymous memory through the compressor and out
4300 	 * to disk... in this state we allow freeing of compressed
4301 	 * pages and must honor the C_DONT_BLOCK case
4302 	 */
4303 	if (__improbable(dst && decompressions_blocked == TRUE)) {
4304 		if (flags & C_DONT_BLOCK) {
4305 			if (__probable(!kdp_mode)) {
4306 				PAGE_REPLACEMENT_DISALLOWED(FALSE);
4307 			}
4308 
4309 			*zeroslot = 0;
4310 			return -2;
4311 		}
4312 		/*
4313 		 * it's safe to atomically assert and block behind the
4314 		 * lock held in shared mode because "decompressions_blocked" is
4315 		 * only set and cleared and the thread_wakeup done when the lock
4316 		 * is held exclusively
4317 		 */
4318 		assert_wait((event_t)&decompressions_blocked, THREAD_UNINT);
4319 
4320 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
4321 
4322 		thread_block(THREAD_CONTINUE_NULL);
4323 
4324 		goto ReTry;
4325 	}
4326 #endif
4327 	/* s_cseg is actually "segno+1" */
4328 	c_segno = slot_ptr->s_cseg - 1;
4329 
4330 	if (__improbable(c_segno >= c_segments_available)) {
4331 		panic("c_decompress_page: c_segno %d >= c_segments_available %d, slot_ptr(%p), slot_data(%x)",
4332 		    c_segno, c_segments_available, slot_ptr, *(int *)((void *)slot_ptr));
4333 	}
4334 
4335 	if (__improbable(c_segments[c_segno].c_segno < c_segments_available)) {
4336 		panic("c_decompress_page: c_segno %d is free, slot_ptr(%p), slot_data(%x)",
4337 		    c_segno, slot_ptr, *(int *)((void *)slot_ptr));
4338 	}
4339 
4340 	c_seg = c_segments[c_segno].c_seg;
4341 
4342 	if (__probable(!kdp_mode)) {
4343 		lck_mtx_lock_spin_always(&c_seg->c_lock);
4344 	} else {
4345 		if (kdp_lck_mtx_lock_spin_is_acquired(&c_seg->c_lock)) {
4346 			return -2;
4347 		}
4348 	}
4349 
4350 	assert(c_seg->c_state != C_IS_EMPTY && c_seg->c_state != C_IS_FREE);
4351 
4352 	if (dst == NULL && c_seg->c_busy_swapping) {
4353 		assert(c_seg->c_busy);
4354 
4355 		goto bypass_busy_check;
4356 	}
4357 	if (flags & C_DONT_BLOCK) {
4358 		if (c_seg->c_busy || (C_SEG_IS_ONDISK(c_seg) && dst)) {
4359 			*zeroslot = 0;
4360 
4361 			retval = -2;
4362 			goto done;
4363 		}
4364 	}
4365 	if (c_seg->c_busy) {
4366 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
4367 
4368 		c_seg_wait_on_busy(c_seg);
4369 
4370 		goto ReTry;
4371 	}
4372 bypass_busy_check:
4373 
4374 	c_indx = slot_ptr->s_cindx;
4375 
4376 	if (__improbable(c_indx >= c_seg->c_nextslot)) {
4377 		panic("c_decompress_page: c_indx %d >= c_nextslot %d, c_seg(%p), slot_ptr(%p), slot_data(%x)",
4378 		    c_indx, c_seg->c_nextslot, c_seg, slot_ptr, *(int *)((void *)slot_ptr));
4379 	}
4380 
4381 	cs = C_SEG_SLOT_FROM_INDEX(c_seg, c_indx);
4382 
4383 	c_size = UNPACK_C_SIZE(cs);
4384 
4385 	if (__improbable(c_size == 0)) {
4386 		panic("c_decompress_page: c_size == 0, c_seg(%p), slot_ptr(%p), slot_data(%x)",
4387 		    c_seg, slot_ptr, *(int *)((void *)slot_ptr));
4388 	}
4389 
4390 	c_rounded_size = (c_size + C_SEG_OFFSET_ALIGNMENT_MASK) & ~C_SEG_OFFSET_ALIGNMENT_MASK;
4391 
4392 	if (dst) {
4393 		uint32_t        age_of_cseg;
4394 		clock_sec_t     cur_ts_sec;
4395 		clock_nsec_t    cur_ts_nsec;
4396 
4397 		if (C_SEG_IS_ONDISK(c_seg)) {
4398 #if CONFIG_FREEZE
4399 			if (freezer_incore_cseg_acct) {
4400 				if ((c_seg->c_slots_used + c_segment_pages_compressed_incore) >= c_segment_pages_compressed_nearing_limit) {
4401 					PAGE_REPLACEMENT_DISALLOWED(FALSE);
4402 					lck_mtx_unlock_always(&c_seg->c_lock);
4403 
4404 					memorystatus_kill_on_VM_compressor_space_shortage(FALSE /* async */);
4405 
4406 					goto ReTry;
4407 				}
4408 
4409 				uint32_t incore_seg_count = c_segment_count - c_swappedout_count - c_swappedout_sparse_count;
4410 				if ((incore_seg_count + 1) >= c_segments_nearing_limit) {
4411 					PAGE_REPLACEMENT_DISALLOWED(FALSE);
4412 					lck_mtx_unlock_always(&c_seg->c_lock);
4413 
4414 					memorystatus_kill_on_VM_compressor_space_shortage(FALSE /* async */);
4415 
4416 					goto ReTry;
4417 				}
4418 			}
4419 #endif /* CONFIG_FREEZE */
4420 			assert(kdp_mode == FALSE);
4421 			retval = c_seg_swapin(c_seg, FALSE, TRUE);
4422 			assert(retval == 0);
4423 
4424 			retval = 1;
4425 		}
4426 		if (c_seg->c_state == C_ON_BAD_Q) {
4427 			assert(c_seg->c_store.c_buffer == NULL);
4428 			*zeroslot = 0;
4429 
4430 			retval = -1;
4431 			goto done;
4432 		}
4433 
4434 #if POPCOUNT_THE_COMPRESSED_DATA
4435 		unsigned csvpop;
4436 		uintptr_t csvaddr = (uintptr_t) &c_seg->c_store.c_buffer[cs->c_offset];
4437 		if (cs->c_pop_cdata != (csvpop = vmc_pop(csvaddr, c_size))) {
4438 			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);
4439 		}
4440 #endif
4441 
4442 #if CHECKSUM_THE_COMPRESSED_DATA
4443 		unsigned csvhash;
4444 		if (cs->c_hash_compressed_data != (csvhash = vmc_hash((char *)&c_seg->c_store.c_buffer[cs->c_offset], c_size))) {
4445 			panic("Compressed data doesn't match original %p %p %u %u %u", c_seg, cs, c_size, cs->c_hash_compressed_data, csvhash);
4446 		}
4447 #endif
4448 		if (c_rounded_size == PAGE_SIZE) {
4449 			/*
4450 			 * page wasn't compressible... just copy it out
4451 			 */
4452 			memcpy(dst, &c_seg->c_store.c_buffer[cs->c_offset], PAGE_SIZE);
4453 		} else if (c_size == 4) {
4454 			int32_t         data;
4455 			int32_t         *dptr;
4456 
4457 			/*
4458 			 * page was populated with a single value
4459 			 * that didn't fit into our fast hash
4460 			 * so we packed it in as a single non-compressed value
4461 			 * that we need to populate the page with
4462 			 */
4463 			dptr = (int32_t *)(uintptr_t)dst;
4464 			data = *(int32_t *)(&c_seg->c_store.c_buffer[cs->c_offset]);
4465 			sv_decompress(dptr, data);
4466 		} else {
4467 			uint32_t        my_cpu_no;
4468 			char            *scratch_buf;
4469 
4470 			if (__probable(!kdp_mode)) {
4471 				/*
4472 				 * we're behind the c_seg lock held in spin mode
4473 				 * which means pre-emption is disabled... therefore
4474 				 * the following sequence is atomic and safe
4475 				 */
4476 				my_cpu_no = cpu_number();
4477 
4478 				assert(my_cpu_no < compressor_cpus);
4479 
4480 				scratch_buf = &compressor_scratch_bufs[my_cpu_no * vm_compressor_get_decode_scratch_size()];
4481 			} else {
4482 				scratch_buf = kdp_compressor_scratch_buf;
4483 			}
4484 
4485 			if (vm_compressor_algorithm() != VM_COMPRESSOR_DEFAULT_CODEC) {
4486 #if defined(__arm__) || defined(__arm64__)
4487 				uint16_t c_codec = cs->c_codec;
4488 				uint32_t inline_popcount;
4489 				if (!metadecompressor((const uint8_t *) &c_seg->c_store.c_buffer[cs->c_offset],
4490 				    (uint8_t *)dst, c_size, c_codec, (void *)scratch_buf, &inline_popcount)) {
4491 					retval = -1;
4492 				} else {
4493 #if __APPLE_WKDM_POPCNT_EXTENSIONS__
4494 					if (inline_popcount != cs->c_inline_popcount) {
4495 						/*
4496 						 * The codec choice in compression and
4497 						 * decompression must agree, so there
4498 						 * should never be a disagreement in
4499 						 * whether an inline population count
4500 						 * was performed.
4501 						 */
4502 						assert(inline_popcount != C_SLOT_NO_POPCOUNT);
4503 						assert(cs->c_inline_popcount != C_SLOT_NO_POPCOUNT);
4504 						printf("decompression failure from physical region %llx+%05x: popcount mismatch (%d != %d)\n",
4505 						    (unsigned long long)kvtophys((uintptr_t)&c_seg->c_store.c_buffer[cs->c_offset]), c_size,
4506 						    inline_popcount,
4507 						    cs->c_inline_popcount);
4508 						retval = -1;
4509 					}
4510 #else
4511 					assert(inline_popcount == C_SLOT_NO_POPCOUNT);
4512 #endif /* __APPLE_WKDM_POPCNT_EXTENSIONS__ */
4513 				}
4514 #endif
4515 			} else {
4516 #if defined(__arm64__)
4517 				__unreachable_ok_push
4518 				if (PAGE_SIZE == 4096) {
4519 					WKdm_decompress_4k((WK_word *)(uintptr_t)&c_seg->c_store.c_buffer[cs->c_offset],
4520 					    (WK_word *)(uintptr_t)dst, (WK_word *)(uintptr_t)scratch_buf, c_size);
4521 				} else {
4522 					WKdm_decompress_16k((WK_word *)(uintptr_t)&c_seg->c_store.c_buffer[cs->c_offset],
4523 					    (WK_word *)(uintptr_t)dst, (WK_word *)(uintptr_t)scratch_buf, c_size);
4524 				}
4525 				__unreachable_ok_pop
4526 #else
4527 				WKdm_decompress_new((WK_word *)(uintptr_t)&c_seg->c_store.c_buffer[cs->c_offset],
4528 				    (WK_word *)(uintptr_t)dst, (WK_word *)(uintptr_t)scratch_buf, c_size);
4529 #endif
4530 			}
4531 		}
4532 
4533 #if CHECKSUM_THE_DATA
4534 		if (cs->c_hash_data != vmc_hash(dst, PAGE_SIZE)) {
4535 #if     defined(__arm__) || defined(__arm64__)
4536 			int32_t *dinput = &c_seg->c_store.c_buffer[cs->c_offset];
4537 			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));
4538 #else
4539 			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);
4540 #endif
4541 		}
4542 #endif
4543 		if (c_seg->c_swappedin_ts == 0 && !kdp_mode) {
4544 			clock_get_system_nanotime(&cur_ts_sec, &cur_ts_nsec);
4545 
4546 			age_of_cseg = (uint32_t)cur_ts_sec - c_seg->c_creation_ts;
4547 			if (age_of_cseg < DECOMPRESSION_SAMPLE_MAX_AGE) {
4548 				OSAddAtomic(1, &age_of_decompressions_during_sample_period[age_of_cseg]);
4549 			} else {
4550 				OSAddAtomic(1, &overage_decompressions_during_sample_period);
4551 			}
4552 
4553 			OSAddAtomic(1, &sample_period_decompression_count);
4554 		}
4555 	}
4556 #if CONFIG_FREEZE
4557 	else {
4558 		/*
4559 		 * We are freeing an uncompressed page from this c_seg and so balance the ledgers.
4560 		 */
4561 		if (C_SEG_IS_ONDISK(c_seg)) {
4562 			/*
4563 			 * The compression sweep feature will push out anonymous pages to disk
4564 			 * without going through the freezer path and so those c_segs, while
4565 			 * swapped out, won't have an owner.
4566 			 */
4567 			if (c_seg->c_task_owner) {
4568 				task_update_frozen_to_swap_acct(c_seg->c_task_owner, PAGE_SIZE_64, DEBIT_FROM_SWAP);
4569 			}
4570 
4571 			/*
4572 			 * We are freeing a page in swap without swapping it in. We bump the in-core
4573 			 * count here to simulate a swapin of a page so that we can accurately
4574 			 * decrement it below.
4575 			 */
4576 			OSAddAtomic(1, &c_segment_pages_compressed_incore);
4577 		}
4578 	}
4579 #endif /* CONFIG_FREEZE */
4580 
4581 	if (flags & C_KEEP) {
4582 		*zeroslot = 0;
4583 		goto done;
4584 	}
4585 	assert(kdp_mode == FALSE);
4586 
4587 	c_seg->c_bytes_unused += c_rounded_size;
4588 	c_seg->c_bytes_used -= c_rounded_size;
4589 
4590 	assert(c_seg->c_slots_used);
4591 	c_seg->c_slots_used--;
4592 	if (dst && c_seg->c_swappedin) {
4593 		task_t task = current_task();
4594 		if (task) {
4595 			ledger_credit(task->ledger, task_ledgers.swapins, PAGE_SIZE);
4596 		}
4597 	}
4598 
4599 	PACK_C_SIZE(cs, 0);
4600 
4601 	if (c_indx < c_seg->c_firstemptyslot) {
4602 		c_seg->c_firstemptyslot = c_indx;
4603 	}
4604 
4605 	OSAddAtomic(-1, &c_segment_pages_compressed);
4606 #if CONFIG_FREEZE
4607 	OSAddAtomic(-1, &c_segment_pages_compressed_incore);
4608 	assertf(c_segment_pages_compressed_incore >= 0, "-ve incore count %p 0x%x", c_seg, c_segment_pages_compressed_incore);
4609 #endif /* CONFIG_FREEZE */
4610 
4611 	if (c_seg->c_state != C_ON_BAD_Q && !(C_SEG_IS_ONDISK(c_seg))) {
4612 		/*
4613 		 * C_SEG_IS_ONDISK == TRUE can occur when we're doing a
4614 		 * free of a compressed page (i.e. dst == NULL)
4615 		 */
4616 		OSAddAtomic64(-c_rounded_size, &compressor_bytes_used);
4617 	}
4618 	if (c_seg->c_busy_swapping) {
4619 		/*
4620 		 * bypass case for c_busy_swapping...
4621 		 * let the swapin/swapout paths deal with putting
4622 		 * the c_seg on the minor compaction queue if needed
4623 		 */
4624 		assert(c_seg->c_busy);
4625 		goto done;
4626 	}
4627 	assert(!c_seg->c_busy);
4628 
4629 	if (c_seg->c_state != C_IS_FILLING) {
4630 		if (c_seg->c_bytes_used == 0) {
4631 			if (!(C_SEG_IS_ONDISK(c_seg))) {
4632 				int     pages_populated;
4633 
4634 				pages_populated = (round_page_32(C_SEG_OFFSET_TO_BYTES(c_seg->c_populated_offset))) / PAGE_SIZE;
4635 				c_seg->c_populated_offset = C_SEG_BYTES_TO_OFFSET(0);
4636 
4637 				if (pages_populated) {
4638 					assert(c_seg->c_state != C_ON_BAD_Q);
4639 					assert(c_seg->c_store.c_buffer != NULL);
4640 
4641 					C_SEG_BUSY(c_seg);
4642 					lck_mtx_unlock_always(&c_seg->c_lock);
4643 
4644 					kernel_memory_depopulate(
4645 						(vm_offset_t) c_seg->c_store.c_buffer,
4646 						ptoa(pages_populated),
4647 						KMA_COMPRESSOR, VM_KERN_MEMORY_COMPRESSOR);
4648 
4649 					lck_mtx_lock_spin_always(&c_seg->c_lock);
4650 					C_SEG_WAKEUP_DONE(c_seg);
4651 				}
4652 				if (!c_seg->c_on_minorcompact_q && c_seg->c_state != C_ON_SWAPOUT_Q && c_seg->c_state != C_ON_SWAPIO_Q) {
4653 					c_seg_need_delayed_compaction(c_seg, FALSE);
4654 				}
4655 			} else {
4656 				if (c_seg->c_state != C_ON_SWAPPEDOUTSPARSE_Q) {
4657 					c_seg_move_to_sparse_list(c_seg);
4658 					consider_defragmenting = TRUE;
4659 				}
4660 			}
4661 		} else if (c_seg->c_on_minorcompact_q) {
4662 			assert(c_seg->c_state != C_ON_BAD_Q);
4663 			assert(!C_SEG_IS_ON_DISK_OR_SOQ(c_seg));
4664 
4665 			if (C_SEG_SHOULD_MINORCOMPACT_NOW(c_seg)) {
4666 				c_seg_try_minor_compaction_and_unlock(c_seg);
4667 				need_unlock = FALSE;
4668 			}
4669 		} else if (!(C_SEG_IS_ONDISK(c_seg))) {
4670 			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 &&
4671 			    C_SEG_UNUSED_BYTES(c_seg) >= PAGE_SIZE) {
4672 				c_seg_need_delayed_compaction(c_seg, FALSE);
4673 			}
4674 		} else if (c_seg->c_state != C_ON_SWAPPEDOUTSPARSE_Q && C_SEG_ONDISK_IS_SPARSE(c_seg)) {
4675 			c_seg_move_to_sparse_list(c_seg);
4676 			consider_defragmenting = TRUE;
4677 		}
4678 	}
4679 done:
4680 	if (__improbable(kdp_mode)) {
4681 		return retval;
4682 	}
4683 
4684 	if (need_unlock == TRUE) {
4685 		lck_mtx_unlock_always(&c_seg->c_lock);
4686 	}
4687 
4688 	PAGE_REPLACEMENT_DISALLOWED(FALSE);
4689 
4690 	if (consider_defragmenting == TRUE) {
4691 		vm_swap_consider_defragmenting(VM_SWAP_FLAGS_NONE);
4692 	}
4693 
4694 #if !XNU_TARGET_OS_OSX
4695 	if ((c_minor_count && COMPRESSOR_NEEDS_TO_MINOR_COMPACT()) || vm_compressor_needs_to_major_compact()) {
4696 		vm_wake_compactor_swapper();
4697 	}
4698 #endif /* !XNU_TARGET_OS_OSX */
4699 
4700 	return retval;
4701 }
4702 
4703 
4704 int
vm_compressor_get(ppnum_t pn,int * slot,int flags)4705 vm_compressor_get(ppnum_t pn, int *slot, int flags)
4706 {
4707 	c_slot_mapping_t  slot_ptr;
4708 	char    *dst;
4709 	int     zeroslot = 1;
4710 	int     retval;
4711 
4712 	dst = pmap_map_compressor_page(pn);
4713 	slot_ptr = (c_slot_mapping_t)slot;
4714 
4715 	assert(dst != NULL);
4716 
4717 	if (slot_ptr->s_cseg == C_SV_CSEG_ID) {
4718 		int32_t         data;
4719 		int32_t         *dptr;
4720 
4721 		/*
4722 		 * page was populated with a single value
4723 		 * that found a home in our hash table
4724 		 * grab that value from the hash and populate the page
4725 		 * that we need to populate the page with
4726 		 */
4727 		dptr = (int32_t *)(uintptr_t)dst;
4728 		data = c_segment_sv_hash_table[slot_ptr->s_cindx].he_data;
4729 		sv_decompress(dptr, data);
4730 		if (!(flags & C_KEEP)) {
4731 			c_segment_sv_hash_drop_ref(slot_ptr->s_cindx);
4732 
4733 			OSAddAtomic(-1, &c_segment_pages_compressed);
4734 #if CONFIG_FREEZE
4735 			OSAddAtomic(-1, &c_segment_pages_compressed_incore);
4736 			assertf(c_segment_pages_compressed_incore >= 0, "-ve incore count 0x%x", c_segment_pages_compressed_incore);
4737 #endif /* CONFIG_FREEZE */
4738 			*slot = 0;
4739 		}
4740 		if (data) {
4741 			OSAddAtomic(1, &c_segment_svp_nonzero_decompressions);
4742 		} else {
4743 			OSAddAtomic(1, &c_segment_svp_zero_decompressions);
4744 		}
4745 
4746 		pmap_unmap_compressor_page(pn, dst);
4747 		return 0;
4748 	}
4749 
4750 	retval = c_decompress_page(dst, slot_ptr, flags, &zeroslot);
4751 
4752 	/*
4753 	 * zeroslot will be set to 0 by c_decompress_page if (flags & C_KEEP)
4754 	 * or (flags & C_DONT_BLOCK) and we found 'c_busy' or 'C_SEG_IS_ONDISK' to be TRUE
4755 	 */
4756 	if (zeroslot) {
4757 		*slot = 0;
4758 	}
4759 
4760 	pmap_unmap_compressor_page(pn, dst);
4761 
4762 	/*
4763 	 * returns 0 if we successfully decompressed a page from a segment already in memory
4764 	 * returns 1 if we had to first swap in the segment, before successfully decompressing the page
4765 	 * returns -1 if we encountered an error swapping in the segment - decompression failed
4766 	 * returns -2 if (flags & C_DONT_BLOCK) and we found 'c_busy' or 'C_SEG_IS_ONDISK' to be true
4767 	 */
4768 	return retval;
4769 }
4770 
4771 #if DEVELOPMENT || DEBUG
4772 
4773 void
vm_compressor_inject_error(int * slot)4774 vm_compressor_inject_error(int *slot)
4775 {
4776 	c_slot_mapping_t slot_ptr = (c_slot_mapping_t)slot;
4777 
4778 	/* No error detection for single-value compression. */
4779 	if (slot_ptr->s_cseg == C_SV_CSEG_ID) {
4780 		printf("%s(): cannot inject errors in SV-compressed pages\n", __func__ );
4781 		return;
4782 	}
4783 
4784 	/* s_cseg is actually "segno+1" */
4785 	const uint32_t c_segno = slot_ptr->s_cseg - 1;
4786 
4787 	assert(c_segno < c_segments_available);
4788 	assert(c_segments[c_segno].c_segno >= c_segments_available);
4789 
4790 	const c_segment_t c_seg = c_segments[c_segno].c_seg;
4791 
4792 	PAGE_REPLACEMENT_DISALLOWED(TRUE);
4793 
4794 	lck_mtx_lock_spin_always(&c_seg->c_lock);
4795 	assert(c_seg->c_state != C_IS_EMPTY && c_seg->c_state != C_IS_FREE);
4796 
4797 	const uint16_t c_indx = slot_ptr->s_cindx;
4798 	assert(c_indx < c_seg->c_nextslot);
4799 
4800 	/*
4801 	 * To safely make this segment temporarily writable, we need to mark
4802 	 * the segment busy, which allows us to release the segment lock.
4803 	 */
4804 	while (c_seg->c_busy) {
4805 		c_seg_wait_on_busy(c_seg);
4806 		lck_mtx_lock_spin_always(&c_seg->c_lock);
4807 	}
4808 	C_SEG_BUSY(c_seg);
4809 
4810 	bool already_writable = (c_seg->c_state == C_IS_FILLING);
4811 	if (!already_writable) {
4812 		/*
4813 		 * Protection update must be performed preemptibly, so temporarily drop
4814 		 * the lock. Having set c_busy will prevent most other concurrent
4815 		 * operations.
4816 		 */
4817 		lck_mtx_unlock_always(&c_seg->c_lock);
4818 		C_SEG_MAKE_WRITEABLE(c_seg);
4819 		lck_mtx_lock_spin_always(&c_seg->c_lock);
4820 	}
4821 
4822 	/*
4823 	 * Once we've released the lock following our c_state == C_IS_FILLING check,
4824 	 * c_current_seg_filled() can (re-)write-protect the segment. However, it
4825 	 * will transition from C_IS_FILLING before releasing the c_seg lock, so we
4826 	 * can detect this by re-checking after we've reobtained the lock.
4827 	 */
4828 	if (already_writable && c_seg->c_state != C_IS_FILLING) {
4829 		lck_mtx_unlock_always(&c_seg->c_lock);
4830 		C_SEG_MAKE_WRITEABLE(c_seg);
4831 		lck_mtx_lock_spin_always(&c_seg->c_lock);
4832 		already_writable = false;
4833 		/* Segment can't be freed while c_busy is set. */
4834 		assert(c_seg->c_state != C_IS_FILLING);
4835 	}
4836 
4837 	/*
4838 	 * Skip if the segment is on disk. This check can only be performed after
4839 	 * the final acquisition of the segment lock before we attempt to write to
4840 	 * the segment.
4841 	 */
4842 	if (!C_SEG_IS_ON_DISK_OR_SOQ(c_seg)) {
4843 		c_slot_t cs = C_SEG_SLOT_FROM_INDEX(c_seg, c_indx);
4844 		int32_t *data = &c_seg->c_store.c_buffer[cs->c_offset];
4845 		/* assume that the compressed data holds at least one int32_t */
4846 		assert(UNPACK_C_SIZE(cs) > sizeof(*data));
4847 		/*
4848 		 * This bit is known to be in the payload of a MISS packet resulting from
4849 		 * the pattern used in the test pattern from decompression_failure.c.
4850 		 * Flipping it should result in many corrupted bits in the test page.
4851 		 */
4852 		data[0] ^= 0x00000100;
4853 	}
4854 
4855 	if (!already_writable) {
4856 		lck_mtx_unlock_always(&c_seg->c_lock);
4857 		C_SEG_WRITE_PROTECT(c_seg);
4858 		lck_mtx_lock_spin_always(&c_seg->c_lock);
4859 	}
4860 
4861 	C_SEG_WAKEUP_DONE(c_seg);
4862 	lck_mtx_unlock_always(&c_seg->c_lock);
4863 
4864 	PAGE_REPLACEMENT_DISALLOWED(FALSE);
4865 }
4866 
4867 #endif /* DEVELOPMENT || DEBUG */
4868 
4869 int
vm_compressor_free(int * slot,int flags)4870 vm_compressor_free(int *slot, int flags)
4871 {
4872 	c_slot_mapping_t  slot_ptr;
4873 	int     zeroslot = 1;
4874 	int     retval;
4875 
4876 	assert(flags == 0 || flags == C_DONT_BLOCK);
4877 
4878 	slot_ptr = (c_slot_mapping_t)slot;
4879 
4880 	if (slot_ptr->s_cseg == C_SV_CSEG_ID) {
4881 		c_segment_sv_hash_drop_ref(slot_ptr->s_cindx);
4882 		OSAddAtomic(-1, &c_segment_pages_compressed);
4883 #if CONFIG_FREEZE
4884 		OSAddAtomic(-1, &c_segment_pages_compressed_incore);
4885 		assertf(c_segment_pages_compressed_incore >= 0, "-ve incore count 0x%x", c_segment_pages_compressed_incore);
4886 #endif /* CONFIG_FREEZE */
4887 
4888 		*slot = 0;
4889 		return 0;
4890 	}
4891 	retval = c_decompress_page(NULL, slot_ptr, flags, &zeroslot);
4892 	/*
4893 	 * returns 0 if we successfully freed the specified compressed page
4894 	 * returns -2 if (flags & C_DONT_BLOCK) and we found 'c_busy' set
4895 	 */
4896 
4897 	if (retval == 0) {
4898 		*slot = 0;
4899 	} else {
4900 		assert(retval == -2);
4901 	}
4902 
4903 	return retval;
4904 }
4905 
4906 
4907 int
vm_compressor_put(ppnum_t pn,int * slot,void ** current_chead,char * scratch_buf)4908 vm_compressor_put(ppnum_t pn, int *slot, void  **current_chead, char *scratch_buf)
4909 {
4910 	char    *src;
4911 	int     retval;
4912 
4913 	src = pmap_map_compressor_page(pn);
4914 	assert(src != NULL);
4915 
4916 	retval = c_compress_page(src, (c_slot_mapping_t)slot, (c_segment_t *)current_chead, scratch_buf);
4917 	pmap_unmap_compressor_page(pn, src);
4918 
4919 	return retval;
4920 }
4921 
4922 void
vm_compressor_transfer(int * dst_slot_p,int * src_slot_p)4923 vm_compressor_transfer(
4924 	int     *dst_slot_p,
4925 	int     *src_slot_p)
4926 {
4927 	c_slot_mapping_t        dst_slot, src_slot;
4928 	c_segment_t             c_seg;
4929 	uint16_t                c_indx;
4930 	c_slot_t                cs;
4931 
4932 	src_slot = (c_slot_mapping_t) src_slot_p;
4933 
4934 	if (src_slot->s_cseg == C_SV_CSEG_ID) {
4935 		*dst_slot_p = *src_slot_p;
4936 		*src_slot_p = 0;
4937 		return;
4938 	}
4939 	dst_slot = (c_slot_mapping_t) dst_slot_p;
4940 Retry:
4941 	PAGE_REPLACEMENT_DISALLOWED(TRUE);
4942 	/* get segment for src_slot */
4943 	c_seg = c_segments[src_slot->s_cseg - 1].c_seg;
4944 	/* lock segment */
4945 	lck_mtx_lock_spin_always(&c_seg->c_lock);
4946 	/* wait if it's busy */
4947 	if (c_seg->c_busy && !c_seg->c_busy_swapping) {
4948 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
4949 		c_seg_wait_on_busy(c_seg);
4950 		goto Retry;
4951 	}
4952 	/* find the c_slot */
4953 	c_indx = src_slot->s_cindx;
4954 	cs = C_SEG_SLOT_FROM_INDEX(c_seg, c_indx);
4955 	/* point the c_slot back to dst_slot instead of src_slot */
4956 	C_SLOT_ASSERT_PACKABLE(dst_slot);
4957 	cs->c_packed_ptr = C_SLOT_PACK_PTR(dst_slot);
4958 	/* transfer */
4959 	*dst_slot_p = *src_slot_p;
4960 	*src_slot_p = 0;
4961 	lck_mtx_unlock_always(&c_seg->c_lock);
4962 	PAGE_REPLACEMENT_DISALLOWED(FALSE);
4963 }
4964 
4965 #if defined(__arm64__)
4966 extern clock_sec_t             vm_swapfile_last_failed_to_create_ts;
4967 __attribute__((noreturn))
4968 void
vm_panic_hibernate_write_image_failed(int err)4969 vm_panic_hibernate_write_image_failed(int err)
4970 {
4971 	panic("hibernate_write_image encountered error 0x%x - %u, %u, %d, %d, %d, %d, %d, %d, %d, %d, %llu, %d, %d, %d\n",
4972 	    err,
4973 	    VM_PAGE_COMPRESSOR_COUNT, vm_page_wire_count,
4974 	    c_age_count, c_major_count, c_minor_count, c_swapout_count, c_swappedout_sparse_count,
4975 	    vm_num_swap_files, vm_num_pinned_swap_files, vm_swappin_enabled, vm_swap_put_failures,
4976 	    (vm_swapfile_last_failed_to_create_ts ? 1:0), hibernate_no_swapspace, hibernate_flush_timed_out);
4977 }
4978 #endif /*(__arm64__)*/
4979 
4980 #if CONFIG_FREEZE
4981 
4982 int     freezer_finished_filling = 0;
4983 
4984 void
vm_compressor_finished_filling(void ** current_chead)4985 vm_compressor_finished_filling(
4986 	void    **current_chead)
4987 {
4988 	c_segment_t     c_seg;
4989 
4990 	if ((c_seg = *(c_segment_t *)current_chead) == NULL) {
4991 		return;
4992 	}
4993 
4994 	assert(c_seg->c_state == C_IS_FILLING);
4995 
4996 	lck_mtx_lock_spin_always(&c_seg->c_lock);
4997 
4998 	c_current_seg_filled(c_seg, (c_segment_t *)current_chead);
4999 
5000 	lck_mtx_unlock_always(&c_seg->c_lock);
5001 
5002 	freezer_finished_filling++;
5003 }
5004 
5005 
5006 /*
5007  * This routine is used to transfer the compressed chunks from
5008  * the c_seg/cindx pointed to by slot_p into a new c_seg headed
5009  * by the current_chead and a new cindx within that c_seg.
5010  *
5011  * Currently, this routine is only used by the "freezer backed by
5012  * compressor with swap" mode to create a series of c_segs that
5013  * only contain compressed data belonging to one task. So, we
5014  * move a task's previously compressed data into a set of new
5015  * c_segs which will also hold the task's yet to be compressed data.
5016  */
5017 
5018 kern_return_t
vm_compressor_relocate(void ** current_chead,int * slot_p)5019 vm_compressor_relocate(
5020 	void            **current_chead,
5021 	int             *slot_p)
5022 {
5023 	c_slot_mapping_t        slot_ptr;
5024 	c_slot_mapping_t        src_slot;
5025 	uint32_t                c_rounded_size;
5026 	uint32_t                c_size;
5027 	uint16_t                dst_slot;
5028 	c_slot_t                c_dst;
5029 	c_slot_t                c_src;
5030 	uint16_t                c_indx;
5031 	c_segment_t             c_seg_dst = NULL;
5032 	c_segment_t             c_seg_src = NULL;
5033 	kern_return_t           kr = KERN_SUCCESS;
5034 
5035 
5036 	src_slot = (c_slot_mapping_t) slot_p;
5037 
5038 	if (src_slot->s_cseg == C_SV_CSEG_ID) {
5039 		/*
5040 		 * no need to relocate... this is a page full of a single
5041 		 * value which is hashed to a single entry not contained
5042 		 * in a c_segment_t
5043 		 */
5044 		return kr;
5045 	}
5046 
5047 Relookup_dst:
5048 	c_seg_dst = c_seg_allocate((c_segment_t *)current_chead);
5049 	/*
5050 	 * returns with c_seg lock held
5051 	 * and PAGE_REPLACEMENT_DISALLOWED(TRUE)...
5052 	 * c_nextslot has been allocated and
5053 	 * c_store.c_buffer populated
5054 	 */
5055 	if (c_seg_dst == NULL) {
5056 		/*
5057 		 * Out of compression segments?
5058 		 */
5059 		kr = KERN_RESOURCE_SHORTAGE;
5060 		goto out;
5061 	}
5062 
5063 	assert(c_seg_dst->c_busy == 0);
5064 
5065 	C_SEG_BUSY(c_seg_dst);
5066 
5067 	dst_slot = c_seg_dst->c_nextslot;
5068 
5069 	lck_mtx_unlock_always(&c_seg_dst->c_lock);
5070 
5071 Relookup_src:
5072 	c_seg_src = c_segments[src_slot->s_cseg - 1].c_seg;
5073 
5074 	assert(c_seg_dst != c_seg_src);
5075 
5076 	lck_mtx_lock_spin_always(&c_seg_src->c_lock);
5077 
5078 	if (C_SEG_IS_ON_DISK_OR_SOQ(c_seg_src) ||
5079 	    c_seg_src->c_state == C_IS_FILLING) {
5080 		/*
5081 		 * Skip this page if :-
5082 		 * a) the src c_seg is already on-disk (or on its way there)
5083 		 *    A "thaw" can mark a process as eligible for
5084 		 * another freeze cycle without bringing any of
5085 		 * its swapped out c_segs back from disk (because
5086 		 * that is done on-demand).
5087 		 *    Or, this page may be mapped elsewhere in the task's map,
5088 		 * and we may have marked it for swap already.
5089 		 *
5090 		 * b) Or, the src c_seg is being filled by the compressor
5091 		 * thread. We don't want the added latency of waiting for
5092 		 * this c_seg in the freeze path and so we skip it.
5093 		 */
5094 
5095 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
5096 
5097 		lck_mtx_unlock_always(&c_seg_src->c_lock);
5098 
5099 		c_seg_src = NULL;
5100 
5101 		goto out;
5102 	}
5103 
5104 	if (c_seg_src->c_busy) {
5105 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
5106 		c_seg_wait_on_busy(c_seg_src);
5107 
5108 		c_seg_src = NULL;
5109 
5110 		PAGE_REPLACEMENT_DISALLOWED(TRUE);
5111 
5112 		goto Relookup_src;
5113 	}
5114 
5115 	C_SEG_BUSY(c_seg_src);
5116 
5117 	lck_mtx_unlock_always(&c_seg_src->c_lock);
5118 
5119 	PAGE_REPLACEMENT_DISALLOWED(FALSE);
5120 
5121 	/* find the c_slot */
5122 	c_indx = src_slot->s_cindx;
5123 
5124 	c_src = C_SEG_SLOT_FROM_INDEX(c_seg_src, c_indx);
5125 
5126 	c_size = UNPACK_C_SIZE(c_src);
5127 
5128 	assert(c_size);
5129 
5130 	if (c_size > (uint32_t)(c_seg_bufsize - C_SEG_OFFSET_TO_BYTES((int32_t)c_seg_dst->c_nextoffset))) {
5131 		/*
5132 		 * This segment is full. We need a new one.
5133 		 */
5134 
5135 		PAGE_REPLACEMENT_DISALLOWED(TRUE);
5136 
5137 		lck_mtx_lock_spin_always(&c_seg_src->c_lock);
5138 		C_SEG_WAKEUP_DONE(c_seg_src);
5139 		lck_mtx_unlock_always(&c_seg_src->c_lock);
5140 
5141 		c_seg_src = NULL;
5142 
5143 		lck_mtx_lock_spin_always(&c_seg_dst->c_lock);
5144 
5145 		assert(c_seg_dst->c_busy);
5146 		assert(c_seg_dst->c_state == C_IS_FILLING);
5147 		assert(!c_seg_dst->c_on_minorcompact_q);
5148 
5149 		c_current_seg_filled(c_seg_dst, (c_segment_t *)current_chead);
5150 		assert(*current_chead == NULL);
5151 
5152 		C_SEG_WAKEUP_DONE(c_seg_dst);
5153 
5154 		lck_mtx_unlock_always(&c_seg_dst->c_lock);
5155 
5156 		c_seg_dst = NULL;
5157 
5158 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
5159 
5160 		goto Relookup_dst;
5161 	}
5162 
5163 	c_dst = C_SEG_SLOT_FROM_INDEX(c_seg_dst, c_seg_dst->c_nextslot);
5164 
5165 	memcpy(&c_seg_dst->c_store.c_buffer[c_seg_dst->c_nextoffset], &c_seg_src->c_store.c_buffer[c_src->c_offset], c_size);
5166 	/*
5167 	 * Is platform alignment actually necessary since wkdm aligns its output?
5168 	 */
5169 	c_rounded_size = (c_size + C_SEG_OFFSET_ALIGNMENT_MASK) & ~C_SEG_OFFSET_ALIGNMENT_MASK;
5170 
5171 	cslot_copy(c_dst, c_src);
5172 	c_dst->c_offset = c_seg_dst->c_nextoffset;
5173 
5174 	if (c_seg_dst->c_firstemptyslot == c_seg_dst->c_nextslot) {
5175 		c_seg_dst->c_firstemptyslot++;
5176 	}
5177 
5178 	c_seg_dst->c_slots_used++;
5179 	c_seg_dst->c_nextslot++;
5180 	c_seg_dst->c_bytes_used += c_rounded_size;
5181 	c_seg_dst->c_nextoffset += C_SEG_BYTES_TO_OFFSET(c_rounded_size);
5182 
5183 
5184 	PACK_C_SIZE(c_src, 0);
5185 
5186 	c_seg_src->c_bytes_used -= c_rounded_size;
5187 	c_seg_src->c_bytes_unused += c_rounded_size;
5188 
5189 	assert(c_seg_src->c_slots_used);
5190 	c_seg_src->c_slots_used--;
5191 
5192 	if (!c_seg_src->c_swappedin) {
5193 		/* Pessimistically lose swappedin status when non-swappedin pages are added. */
5194 		c_seg_dst->c_swappedin = false;
5195 	}
5196 
5197 	if (c_indx < c_seg_src->c_firstemptyslot) {
5198 		c_seg_src->c_firstemptyslot = c_indx;
5199 	}
5200 
5201 	c_dst = C_SEG_SLOT_FROM_INDEX(c_seg_dst, dst_slot);
5202 
5203 	PAGE_REPLACEMENT_ALLOWED(TRUE);
5204 	slot_ptr = C_SLOT_UNPACK_PTR(c_dst);
5205 	/* <csegno=0,indx=0> would mean "empty slot", so use csegno+1 */
5206 	slot_ptr->s_cseg = c_seg_dst->c_mysegno + 1;
5207 	slot_ptr->s_cindx = dst_slot;
5208 
5209 	PAGE_REPLACEMENT_ALLOWED(FALSE);
5210 
5211 out:
5212 	if (c_seg_src) {
5213 		lck_mtx_lock_spin_always(&c_seg_src->c_lock);
5214 
5215 		C_SEG_WAKEUP_DONE(c_seg_src);
5216 
5217 		if (c_seg_src->c_bytes_used == 0 && c_seg_src->c_state != C_IS_FILLING) {
5218 			if (!c_seg_src->c_on_minorcompact_q) {
5219 				c_seg_need_delayed_compaction(c_seg_src, FALSE);
5220 			}
5221 		}
5222 
5223 		lck_mtx_unlock_always(&c_seg_src->c_lock);
5224 	}
5225 
5226 	if (c_seg_dst) {
5227 		PAGE_REPLACEMENT_DISALLOWED(TRUE);
5228 
5229 		lck_mtx_lock_spin_always(&c_seg_dst->c_lock);
5230 
5231 		if (c_seg_dst->c_nextoffset >= c_seg_off_limit || c_seg_dst->c_nextslot >= C_SLOT_MAX_INDEX) {
5232 			/*
5233 			 * Nearing or exceeded maximum slot and offset capacity.
5234 			 */
5235 			assert(c_seg_dst->c_busy);
5236 			assert(c_seg_dst->c_state == C_IS_FILLING);
5237 			assert(!c_seg_dst->c_on_minorcompact_q);
5238 
5239 			c_current_seg_filled(c_seg_dst, (c_segment_t *)current_chead);
5240 			assert(*current_chead == NULL);
5241 		}
5242 
5243 		C_SEG_WAKEUP_DONE(c_seg_dst);
5244 
5245 		lck_mtx_unlock_always(&c_seg_dst->c_lock);
5246 
5247 		c_seg_dst = NULL;
5248 
5249 		PAGE_REPLACEMENT_DISALLOWED(FALSE);
5250 	}
5251 
5252 	return kr;
5253 }
5254 #endif /* CONFIG_FREEZE */
5255