xref: /xnu-8792.41.9/bsd/kern/kern_memorystatus_policy.c (revision 5c2921b07a2480ab43ec66f5b9e41cb872bc554f) !
1 /*
2  * Copyright (c) 2006-2021 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 
30 #include <kern/task.h>
31 #include <libkern/libkern.h>
32 #include <machine/atomic.h>
33 #include <mach/coalition.h>
34 #include <os/log.h>
35 #include <sys/coalition.h>
36 #include <sys/proc.h>
37 #include <sys/proc_internal.h>
38 #include <sys/kdebug.h>
39 #include <sys/kern_memorystatus.h>
40 #include <vm/vm_protos.h>
41 
42 #include "kern_memorystatus_internal.h"
43 
44 /*
45  * All memory pressure policy decisions should live here, and there should be
46  * as little mechanism as possible. This file prioritizes readability.
47  */
48 
49 #pragma mark Policy Function Declarations
50 
51 #if CONFIG_JETSAM
52 static bool memorystatus_check_aggressive_jetsam_needed(int *jld_idle_kills);
53 #endif /* CONFIG_JETSAM */
54 
55 #pragma mark Memorystatus Health Check
56 
57 /*
58  * Each subsystem that relies on the memorystatus thread
59  * for resource exhaustion should put a health check in this section.
60  * The memorystatus thread runs all of the health checks
61  * to determine if the system is healthy. If the system is unhealthy
62  * it picks an action based on the system health status. See the
63  * Memorystatus Thread Actions section below.
64  */
65 
66 extern bool vm_compressor_needs_to_swap(bool wake_memorystatus_thread);
67 extern boolean_t vm_compressor_low_on_space(void);
68 extern bool vm_compressor_compressed_pages_nearing_limit(void);
69 extern bool vm_compressor_is_thrashing(void);
70 extern bool vm_compressor_swapout_is_ripe(void);
71 
72 static void
memorystatus_health_check(memorystatus_system_health_t * status)73 memorystatus_health_check(memorystatus_system_health_t *status)
74 {
75 	memset(status, 0, sizeof(memorystatus_system_health_t));
76 #if CONFIG_JETSAM
77 	status->msh_available_pages_below_pressure = memorystatus_avail_pages_below_pressure();
78 	status->msh_available_pages_below_critical = memorystatus_avail_pages_below_critical();
79 	status->msh_compressor_is_low_on_space = (vm_compressor_low_on_space() == TRUE);
80 	status->msh_compressed_pages_nearing_limit = vm_compressor_compressed_pages_nearing_limit();
81 	status->msh_swapout_is_ripe = vm_compressor_swapout_is_ripe();
82 	if (!status->msh_swapout_is_ripe) {
83 		status->msh_compressor_is_thrashing = !memorystatus_swap_all_apps && vm_compressor_is_thrashing();
84 #if CONFIG_PHANTOM_CACHE
85 		status->msh_phantom_cache_pressure = os_atomic_load(&memorystatus_phantom_cache_pressure, acquire);
86 #else
87 		status->msh_phantom_cache_pressure = false;
88 #endif /* CONFIG_PHANTOM_CACHE */
89 	} else {
90 		status->msh_compressor_is_thrashing = false;
91 		status->msh_phantom_cache_pressure = false;
92 	}
93 	if (!memorystatus_swap_all_apps &&
94 	    (status->msh_swapout_is_ripe || status->msh_phantom_cache_pressure) &&
95 	    !(status->msh_compressor_is_thrashing && status->msh_compressor_is_low_on_space)) {
96 		status->msh_filecache_is_thrashing = true;
97 	}
98 	if (os_atomic_load(&memorystatus_compressor_space_shortage, relaxed)) {
99 		status->msh_compressor_is_low_on_space = true;
100 	}
101 	status->msh_swappable_compressor_segments_over_limit = memorystatus_swap_over_trigger(100);
102 	status->msh_swapin_queue_over_limit = memorystatus_swapin_over_trigger();
103 	status->msh_swap_low_on_space = vm_swap_low_on_space();
104 	status->msh_swap_out_of_space = vm_swap_out_of_space();
105 #endif /* CONFIG_JETSAM */
106 	status->msh_zone_map_is_exhausted = os_atomic_load(&memorystatus_zone_map_is_exhausted, relaxed);
107 }
108 
109 bool
memorystatus_is_system_healthy(const memorystatus_system_health_t * status)110 memorystatus_is_system_healthy(const memorystatus_system_health_t *status)
111 {
112 #if CONFIG_JETSAM
113 	return !(status->msh_available_pages_below_critical
114 	       || status->msh_compressor_is_low_on_space
115 	       || status->msh_compressor_is_thrashing
116 	       || status->msh_filecache_is_thrashing
117 	       || status->msh_zone_map_is_exhausted);
118 #else /* CONFIG_JETSAM */
119 	return !status->msh_zone_map_is_exhausted;
120 #endif /* CONFIG_JETSAM */
121 }
122 
123 
124 #pragma mark Memorystatus Thread Actions
125 
126 /*
127  * This section picks the appropriate memorystatus_action & deploys it.
128  */
129 
130 /*
131  * Inspects the state of various resources in the system to see if
132  * the system is healthy. If the system is not healthy, picks a
133  * memorystatus_action_t to recover the system.
134  *
135  * Every time the memorystatus thread wakes up it calls into here
136  * to pick an action. It will continue performing memorystatus actions until this
137  * function returns MEMORYSTATUS_KILL_NONE. At that point the thread will block.
138  */
139 memorystatus_action_t
memorystatus_pick_action(struct jetsam_thread_state * jetsam_thread,uint32_t * kill_cause,bool highwater_remaining,bool suspended_swappable_apps_remaining,bool swappable_apps_remaining,int * jld_idle_kills)140 memorystatus_pick_action(struct jetsam_thread_state *jetsam_thread,
141     uint32_t *kill_cause,
142     bool highwater_remaining,
143     bool suspended_swappable_apps_remaining,
144     bool swappable_apps_remaining,
145     int *jld_idle_kills)
146 {
147 	memorystatus_system_health_t status;
148 	memorystatus_health_check(&status);
149 	memorystatus_log_system_health(&status);
150 	bool is_system_healthy = memorystatus_is_system_healthy(&status);
151 
152 #if CONFIG_JETSAM
153 	if (status.msh_available_pages_below_pressure || !is_system_healthy) {
154 		/*
155 		 * If swap is enabled, first check if we're running low or are out of swap space.
156 		 */
157 		if (memorystatus_swap_all_apps && jetsam_kill_on_low_swap) {
158 			if (swappable_apps_remaining && status.msh_swap_out_of_space) {
159 				*kill_cause = kMemorystatusKilledLowSwap;
160 				return MEMORYSTATUS_KILL_SWAPPABLE;
161 			} else if (suspended_swappable_apps_remaining && status.msh_swap_low_on_space) {
162 				*kill_cause = kMemorystatusKilledLowSwap;
163 				return MEMORYSTATUS_KILL_SUSPENDED_SWAPPABLE;
164 			}
165 		}
166 
167 		/*
168 		 * We're below the pressure level or the system is unhealthy,
169 		 * regardless of the system health let's check if we should be swapping
170 		 * and if there are high watermark kills left to do.
171 		 */
172 		if (memorystatus_swap_all_apps) {
173 			if (status.msh_swappable_compressor_segments_over_limit && !vm_swapout_thread_running && !os_atomic_load(&vm_swapout_wake_pending, relaxed)) {
174 				/*
175 				 * TODO: The swapper will keep running until it has drained the entire early swapout queue.
176 				 * That might be overly aggressive & we should look into tuning it.
177 				 * See rdar://84102304.
178 				 */
179 				return MEMORYSTATUS_WAKE_SWAPPER;
180 			} else if (status.msh_swapin_queue_over_limit) {
181 				return MEMORYSTATUS_PROCESS_SWAPIN_QUEUE;
182 			} else if (status.msh_swappable_compressor_segments_over_limit) {
183 				os_log_with_startup_serial(OS_LOG_DEFAULT, "memorystatus: Skipping swap wakeup because the swap thread is already running. vm_swapout_thread_running=%d, vm_swapout_wake_pending=%d\n", vm_swapout_thread_running, os_atomic_load(&vm_swapout_wake_pending, relaxed));
184 			}
185 		}
186 
187 		if (highwater_remaining) {
188 			*kill_cause = kMemorystatusKilledHiwat;
189 			os_log_with_startup_serial(OS_LOG_DEFAULT, "memorystatus: Looking for highwatermark kills.\n");
190 			return MEMORYSTATUS_KILL_HIWATER;
191 		}
192 	}
193 
194 	if (is_system_healthy) {
195 		*kill_cause = 0;
196 		return MEMORYSTATUS_KILL_NONE;
197 	}
198 
199 	/*
200 	 * At this point the system is unhealthy and there are no
201 	 * more highwatermark processes to kill.
202 	 */
203 
204 	if (!jetsam_thread->limit_to_low_bands) {
205 		if (memorystatus_check_aggressive_jetsam_needed(jld_idle_kills)) {
206 			os_log_with_startup_serial(OS_LOG_DEFAULT, "memorystatus: Starting aggressive jetsam.\n");
207 			*kill_cause = kMemorystatusKilledProcThrashing;
208 			return MEMORYSTATUS_KILL_AGGRESSIVE;
209 		}
210 	}
211 	/*
212 	 * The system is unhealthy and we either don't need aggressive jetsam
213 	 * or are not allowed to deploy it.
214 	 * Kill in priority order. We'll use LRU within every band except the
215 	 * FG (which will be sorted by coalition role).
216 	 */
217 	*kill_cause = memorystatus_pick_kill_cause(&status);
218 	return MEMORYSTATUS_KILL_TOP_PROCESS;
219 #else /* CONFIG_JETSAM */
220 	(void) jetsam_thread;
221 	(void) jld_idle_kills;
222 	(void) suspended_swappable_apps_remaining;
223 	(void) swappable_apps_remaining;
224 	/*
225 	 * Without CONFIG_JETSAM, we only kill if the system is unhealthy.
226 	 * There is no aggressive jetsam and no
227 	 * early highwatermark killing.
228 	 */
229 	if (is_system_healthy) {
230 		*kill_cause = 0;
231 		return MEMORYSTATUS_KILL_NONE;
232 	}
233 	if (highwater_remaining) {
234 		*kill_cause = kMemorystatusKilledHiwat;
235 		return MEMORYSTATUS_KILL_HIWATER;
236 	} else {
237 		*kill_cause = memorystatus_pick_kill_cause(&status);
238 		return MEMORYSTATUS_KILL_TOP_PROCESS;
239 	}
240 #endif /* CONFIG_JETSAM */
241 }
242 
243 #pragma mark Aggressive Jetsam
244 /*
245  * This section defines when we deploy aggressive jetsam.
246  * Aggressive jetsam kills everything up to the jld_priority_band_max band.
247  */
248 
249 #if CONFIG_JETSAM
250 
251 static bool
252 memorystatus_aggressive_jetsam_needed_sysproc_aging(__unused int jld_eval_aggressive_count, __unused int *jld_idle_kills, __unused int jld_idle_kill_candidates, int *total_candidates);
253 
254 /*
255  * kJetsamHighRelaunchCandidatesThreshold defines the percentage of candidates
256  * in the idle & deferred bands that need to be bad candidates in order to trigger
257  * aggressive jetsam.
258  */
259 #define kJetsamHighRelaunchCandidatesThreshold  (100)
260 
261 /* kJetsamMinCandidatesThreshold defines the minimum number of candidates in the
262  * idle/deferred bands to trigger aggressive jetsam. This value basically decides
263  * how much memory the system is ready to hold in the lower bands without triggering
264  * aggressive jetsam. This number should ideally be tuned based on the memory config
265  * of the device.
266  */
267 #define kJetsamMinCandidatesThreshold           (5)
268 
269 static bool
memorystatus_check_aggressive_jetsam_needed(int * jld_idle_kills)270 memorystatus_check_aggressive_jetsam_needed(int *jld_idle_kills)
271 {
272 	bool aggressive_jetsam_needed = false;
273 	int total_candidates = 0;
274 	/*
275 	 * The aggressive jetsam logic looks at the number of times it has been in the
276 	 * aggressive loop to determine the max priority band it should kill upto. The
277 	 * static variables below are used to track that property.
278 	 *
279 	 * To reset those values, the implementation checks if it has been
280 	 * memorystatus_jld_eval_period_msecs since the parameters were reset.
281 	 */
282 
283 	if (memorystatus_jld_enabled == FALSE) {
284 		/* If aggressive jetsam is disabled, nothing to do here */
285 		return FALSE;
286 	}
287 
288 	/* Get current timestamp (msecs only) */
289 	struct timeval  jld_now_tstamp = {0, 0};
290 	uint64_t        jld_now_msecs = 0;
291 	microuptime(&jld_now_tstamp);
292 	jld_now_msecs = (jld_now_tstamp.tv_sec * 1000);
293 
294 	/*
295 	 * Look at the number of candidates in the idle and deferred band and
296 	 * how many out of them are marked as high relaunch probability.
297 	 */
298 	aggressive_jetsam_needed = memorystatus_aggressive_jetsam_needed_sysproc_aging(jld_eval_aggressive_count,
299 	    jld_idle_kills, jld_idle_kill_candidates, &total_candidates);
300 
301 	/*
302 	 * Check if its been really long since the aggressive jetsam evaluation
303 	 * parameters have been refreshed. This logic also resets the jld_eval_aggressive_count
304 	 * counter to make sure we reset the aggressive jetsam severity.
305 	 */
306 	boolean_t param_reval = false;
307 
308 	if ((total_candidates == 0) ||
309 	    (jld_now_msecs > (jld_timestamp_msecs + memorystatus_jld_eval_period_msecs))) {
310 		jld_timestamp_msecs      = jld_now_msecs;
311 		jld_idle_kill_candidates = total_candidates;
312 		*jld_idle_kills          = 0;
313 		jld_eval_aggressive_count = 0;
314 		jld_priority_band_max   = JETSAM_PRIORITY_UI_SUPPORT;
315 		param_reval = true;
316 	}
317 
318 	/*
319 	 * It is also possible that the system is down to a very small number of processes in the candidate
320 	 * bands. In that case, the decisions made by the memorystatus_aggressive_jetsam_needed_* routines
321 	 * would not be useful. In that case, do not trigger aggressive jetsam.
322 	 */
323 	if (total_candidates < kJetsamMinCandidatesThreshold) {
324 #if DEVELOPMENT || DEBUG
325 		printf("memorystatus: aggressive: [FAILED] Low Candidate Count (current: %d, threshold: %d)\n", total_candidates, kJetsamMinCandidatesThreshold);
326 #endif /* DEVELOPMENT || DEBUG */
327 		aggressive_jetsam_needed = false;
328 	}
329 	return aggressive_jetsam_needed;
330 }
331 
332 static bool
memorystatus_aggressive_jetsam_needed_sysproc_aging(__unused int eval_aggressive_count,__unused int * idle_kills,__unused int idle_kill_candidates,int * total_candidates)333 memorystatus_aggressive_jetsam_needed_sysproc_aging(__unused int eval_aggressive_count, __unused int *idle_kills, __unused int idle_kill_candidates, int *total_candidates)
334 {
335 	bool aggressive_jetsam_needed = false;
336 
337 	/*
338 	 * For the kJetsamAgingPolicySysProcsReclaimedFirst aging policy, we maintain the jetsam
339 	 * relaunch behavior for all daemons. Also, daemons and apps are aged in deferred bands on
340 	 * every dirty->clean transition. For this aging policy, the best way to determine if
341 	 * aggressive jetsam is needed, is to see if the kill candidates are mostly bad candidates.
342 	 * If yes, then we need to go to higher bands to reclaim memory.
343 	 */
344 	proc_list_lock();
345 	/* Get total candidate counts for idle and idle deferred bands */
346 	*total_candidates = memstat_bucket[JETSAM_PRIORITY_IDLE].count + memstat_bucket[system_procs_aging_band].count;
347 	/* Get counts of bad kill candidates in idle and idle deferred bands */
348 	int bad_candidates = memstat_bucket[JETSAM_PRIORITY_IDLE].relaunch_high_count + memstat_bucket[system_procs_aging_band].relaunch_high_count;
349 
350 	proc_list_unlock();
351 
352 	/* Check if the number of bad candidates is greater than kJetsamHighRelaunchCandidatesThreshold % */
353 	aggressive_jetsam_needed = (((bad_candidates * 100) / *total_candidates) >= kJetsamHighRelaunchCandidatesThreshold);
354 
355 	/*
356 	 * Since the new aging policy bases the aggressive jetsam trigger on percentage of
357 	 * bad candidates, it is prone to being overly aggressive. In order to mitigate that,
358 	 * make sure the system is really under memory pressure before triggering aggressive
359 	 * jetsam.
360 	 */
361 	if (memorystatus_available_pages > memorystatus_sysproc_aging_aggr_pages) {
362 		aggressive_jetsam_needed = false;
363 	}
364 
365 #if DEVELOPMENT || DEBUG
366 	printf("memorystatus: aggressive%d: [%s] Bad Candidate Threshold Check (total: %d, bad: %d, threshold: %d %%); Memory Pressure Check (available_pgs: %llu, threshold_pgs: %llu)\n",
367 	    eval_aggressive_count, aggressive_jetsam_needed ? "PASSED" : "FAILED", *total_candidates, bad_candidates,
368 	    kJetsamHighRelaunchCandidatesThreshold, (uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES, (uint64_t)memorystatus_sysproc_aging_aggr_pages);
369 #endif /* DEVELOPMENT || DEBUG */
370 	return aggressive_jetsam_needed;
371 }
372 
373 #endif /* CONFIG_JETSAM */
374 
375 #pragma mark Freezer
376 #if CONFIG_FREEZE
377 /*
378  * Freezer policies
379  */
380 
381 /*
382  * These functions determine what is eligible for the freezer
383  * and the order that we consider freezing them
384  */
385 
386 /*
387  * Checks if the given process is eligible for the freezer.
388  * Processes can only be frozen if this returns true.
389  */
390 bool
memorystatus_is_process_eligible_for_freeze(proc_t p)391 memorystatus_is_process_eligible_for_freeze(proc_t p)
392 {
393 	/*
394 	 * Called with proc_list_lock held.
395 	 */
396 
397 	LCK_MTX_ASSERT(&proc_list_mlock, LCK_MTX_ASSERT_OWNED);
398 
399 	bool should_freeze = false;
400 	uint32_t state = 0, pages = 0;
401 	bool first_consideration = true;
402 	task_t task;
403 
404 	state = p->p_memstat_state;
405 
406 	if (state & (P_MEMSTAT_TERMINATED | P_MEMSTAT_LOCKED | P_MEMSTAT_FREEZE_DISABLED | P_MEMSTAT_FREEZE_IGNORE)) {
407 		if (state & P_MEMSTAT_FREEZE_DISABLED) {
408 			p->p_memstat_freeze_skip_reason = kMemorystatusFreezeSkipReasonDisabled;
409 		}
410 		goto out;
411 	}
412 
413 	task = proc_task(p);
414 
415 	if (isSysProc(p)) {
416 		/*
417 		 * Daemon:- We consider freezing it if:
418 		 * - it belongs to a coalition and the leader is frozen, and,
419 		 * - its role in the coalition is XPC service.
420 		 *
421 		 * We skip memory size requirements in this case.
422 		 */
423 		int task_role_in_coalition = 0;
424 		proc_t leader_proc = memorystatus_get_coalition_leader_and_role(p, &task_role_in_coalition);
425 		if (leader_proc == PROC_NULL || leader_proc == p) {
426 			/*
427 			 * Jetsam coalition is leaderless or the leader is not an app.
428 			 * Either way, don't freeze this proc.
429 			 */
430 			goto out;
431 		}
432 
433 		/* Leader must be frozen */
434 		if (!(leader_proc->p_memstat_state & P_MEMSTAT_FROZEN)) {
435 			goto out;
436 		}
437 		/* Only freeze XPC services */
438 		if (task_role_in_coalition == COALITION_TASKROLE_XPC) {
439 			should_freeze = true;
440 		}
441 
442 		goto out;
443 	} else {
444 		/*
445 		 * Application. Only freeze if it's suspended.
446 		 */
447 		if (!(state & P_MEMSTAT_SUSPENDED)) {
448 			goto out;
449 		}
450 	}
451 
452 	/*
453 	 * We're interested in tracking what percentage of
454 	 * eligible apps actually get frozen.
455 	 * To avoid skewing the metrics towards processes which
456 	 * are considered more frequently, we only track failures once
457 	 * per process.
458 	 */
459 	first_consideration = !(state & P_MEMSTAT_FREEZE_CONSIDERED);
460 
461 	if (first_consideration) {
462 		memorystatus_freezer_stats.mfs_process_considered_count++;
463 		p->p_memstat_state |= P_MEMSTAT_FREEZE_CONSIDERED;
464 	}
465 
466 	/* Only freeze applications meeting our minimum resident page criteria */
467 	memorystatus_get_task_page_counts(proc_task(p), &pages, NULL, NULL);
468 	if (pages < memorystatus_freeze_pages_min) {
469 		if (first_consideration) {
470 			memorystatus_freezer_stats.mfs_error_below_min_pages_count++;
471 		}
472 		p->p_memstat_freeze_skip_reason = kMemorystatusFreezeSkipReasonBelowMinPages;
473 		goto out;
474 	}
475 
476 	/* Don't freeze processes that are already exiting on core. It may have started exiting
477 	 * after we chose it for freeze, but before we obtained the proc_list_lock.
478 	 * NB: This is only possible if we're coming in from memorystatus_freeze_process_sync.
479 	 * memorystatus_freeze_top_process holds the proc_list_lock while it traverses the bands.
480 	 */
481 	if (proc_list_exited(p)) {
482 		if (first_consideration) {
483 			memorystatus_freezer_stats.mfs_error_other_count++;
484 		}
485 		p->p_memstat_freeze_skip_reason = kMemorystatusFreezeSkipReasonOther;
486 		goto out;
487 	}
488 
489 	if (!memorystatus_freezer_use_ordered_list) {
490 		/*
491 		 * We're not using the ordered list so we need to check
492 		 * that dasd recommended the process. Note that the ordered list
493 		 * algorithm only considers processes on the list in the first place
494 		 * so there's no need to double check here.
495 		 */
496 		if (!memorystatus_freeze_process_is_recommended(p)) {
497 			if (first_consideration) {
498 				memorystatus_freezer_stats.mfs_error_low_probability_of_use_count++;
499 			}
500 			p->p_memstat_freeze_skip_reason = kMemorystatusFreezeSkipReasonLowProbOfUse;
501 			goto out;
502 		}
503 	}
504 
505 	if (!(state & P_MEMSTAT_FROZEN) && p->p_memstat_effectivepriority > memorystatus_freeze_max_candidate_band) {
506 		/*
507 		 * Proc has been elevated by something else.
508 		 * Don't freeze it.
509 		 */
510 		if (first_consideration) {
511 			memorystatus_freezer_stats.mfs_error_elevated_count++;
512 		}
513 		p->p_memstat_freeze_skip_reason = kMemorystatusFreezeSkipReasonElevated;
514 		goto out;
515 	}
516 
517 	should_freeze = true;
518 out:
519 	if (should_freeze && !(state & P_MEMSTAT_FROZEN)) {
520 		/*
521 		 * Reset the skip reason. If it's killed before we manage to actually freeze it
522 		 * we failed to consider it early enough.
523 		 */
524 		p->p_memstat_freeze_skip_reason = kMemorystatusFreezeSkipReasonNone;
525 		if (!first_consideration) {
526 			/*
527 			 * We're freezing this for the first time and we previously considered it ineligible.
528 			 * Bump the considered count so that we track this as 1 failure
529 			 * and 1 success.
530 			 */
531 			memorystatus_freezer_stats.mfs_process_considered_count++;
532 		}
533 	}
534 	return should_freeze;
535 }
536 
537 bool
memorystatus_freeze_proc_is_refreeze_eligible(proc_t p)538 memorystatus_freeze_proc_is_refreeze_eligible(proc_t p)
539 {
540 	return (p->p_memstat_state & P_MEMSTAT_REFREEZE_ELIGIBLE) != 0;
541 }
542 
543 
544 static proc_t
memorystatus_freeze_pick_refreeze_process(proc_t last_p)545 memorystatus_freeze_pick_refreeze_process(proc_t last_p)
546 {
547 	proc_t p = PROC_NULL, next_p = PROC_NULL;
548 	unsigned int band = (unsigned int) memorystatus_freeze_jetsam_band;
549 	if (last_p == PROC_NULL) {
550 		next_p = memorystatus_get_first_proc_locked(&band, FALSE);
551 	} else {
552 		next_p = memorystatus_get_next_proc_locked(&band, last_p, FALSE);
553 	}
554 	while (next_p) {
555 		p = next_p;
556 		next_p = memorystatus_get_next_proc_locked(&band, p, FALSE);
557 		if ((p->p_memstat_state & P_MEMSTAT_FROZEN) && !memorystatus_freeze_proc_is_refreeze_eligible(p)) {
558 			/* Process is already frozen & hasn't been thawed. */
559 			continue;
560 		}
561 		/*
562 		 * Has to have been frozen once before.
563 		 */
564 		if (!(p->p_memstat_state & P_MEMSTAT_FROZEN)) {
565 			continue;
566 		}
567 
568 		/*
569 		 * Not currently being looked at for something.
570 		 */
571 		if (p->p_memstat_state & P_MEMSTAT_LOCKED) {
572 			continue;
573 		}
574 		/*
575 		 * Found it
576 		 */
577 		break;
578 	}
579 	return p;
580 }
581 
582 proc_t
memorystatus_freeze_pick_process(struct memorystatus_freeze_list_iterator * iterator)583 memorystatus_freeze_pick_process(struct memorystatus_freeze_list_iterator *iterator)
584 {
585 	proc_t p = PROC_NULL, next_p = PROC_NULL;
586 	unsigned int band = JETSAM_PRIORITY_IDLE;
587 
588 	LCK_MTX_ASSERT(&proc_list_mlock, LCK_MTX_ASSERT_OWNED);
589 	/*
590 	 * If the freezer is full, only consider refreezes.
591 	 */
592 	if (iterator->refreeze_only || memorystatus_frozen_count >= memorystatus_frozen_processes_max) {
593 		if (!iterator->refreeze_only) {
594 			/*
595 			 * The first time the iterator starts to return refreeze
596 			 * candidates, we need to reset the last pointer b/c it's pointing into the wrong band.
597 			 */
598 			iterator->last_p = PROC_NULL;
599 			iterator->refreeze_only = true;
600 		}
601 		iterator->last_p = memorystatus_freeze_pick_refreeze_process(iterator->last_p);
602 		return iterator->last_p;
603 	}
604 
605 	/*
606 	 * Search for the next freezer candidate.
607 	 */
608 	if (memorystatus_freezer_use_ordered_list) {
609 		next_p = memorystatus_freezer_candidate_list_get_proc(
610 			&memorystatus_global_freeze_list,
611 			(iterator->global_freeze_list_index)++,
612 			&memorystatus_freezer_stats.mfs_freeze_pid_mismatches);
613 	} else if (iterator->last_p == PROC_NULL) {
614 		next_p = memorystatus_get_first_proc_locked(&band, FALSE);
615 	} else {
616 		next_p = memorystatus_get_next_proc_locked(&band, iterator->last_p, FALSE);
617 	}
618 	while (next_p) {
619 		p = next_p;
620 		if (memorystatus_is_process_eligible_for_freeze(p)) {
621 			iterator->last_p = p;
622 			return iterator->last_p;
623 		} else {
624 			if (memorystatus_freezer_use_ordered_list) {
625 				next_p = memorystatus_freezer_candidate_list_get_proc(
626 					&memorystatus_global_freeze_list,
627 					(iterator->global_freeze_list_index)++,
628 					&memorystatus_freezer_stats.mfs_freeze_pid_mismatches);
629 			} else {
630 				next_p = memorystatus_get_next_proc_locked(&band, p, FALSE);
631 			}
632 		}
633 	}
634 
635 	/*
636 	 * Failed to find a new freezer candidate.
637 	 * Try to re-freeze.
638 	 */
639 	if (memorystatus_refreeze_eligible_count >= MIN_THAW_REFREEZE_THRESHOLD) {
640 		assert(!iterator->refreeze_only);
641 		iterator->refreeze_only = true;
642 		iterator->last_p = memorystatus_freeze_pick_refreeze_process(PROC_NULL);
643 		return iterator->last_p;
644 	}
645 	return PROC_NULL;
646 }
647 
648 /*
649  * memorystatus_pages_update calls this function whenever the number
650  * of available pages changes. It wakes the freezer thread iff the function returns
651  * true. The freezer thread will try to freeze (or refreeze) up to 1 process
652  * before blocking again.
653  *
654  * Note the freezer thread is also woken up by memorystatus_on_inactivity.
655  */
656 
657 bool
memorystatus_freeze_thread_should_run()658 memorystatus_freeze_thread_should_run()
659 {
660 	/*
661 	 * No freezer_mutex held here...see why near call-site
662 	 * within memorystatus_pages_update().
663 	 */
664 
665 	if (memorystatus_freeze_enabled == FALSE) {
666 		return false;
667 	}
668 
669 	if (memorystatus_available_pages > memorystatus_freeze_threshold) {
670 		return false;
671 	}
672 
673 	memorystatus_freezer_stats.mfs_below_threshold_count++;
674 
675 	if ((memorystatus_frozen_count >= memorystatus_frozen_processes_max)) {
676 		/*
677 		 * Consider this as a skip even if we wake up to refreeze because
678 		 * we won't freeze any new procs.
679 		 */
680 		memorystatus_freezer_stats.mfs_skipped_full_count++;
681 		if (memorystatus_refreeze_eligible_count < MIN_THAW_REFREEZE_THRESHOLD) {
682 			return false;
683 		}
684 	}
685 
686 	if (memorystatus_frozen_shared_mb_max && (memorystatus_frozen_shared_mb >= memorystatus_frozen_shared_mb_max)) {
687 		memorystatus_freezer_stats.mfs_skipped_shared_mb_high_count++;
688 		return false;
689 	}
690 
691 	uint64_t curr_time = mach_absolute_time();
692 
693 	if (curr_time < memorystatus_freezer_thread_next_run_ts) {
694 		return false;
695 	}
696 
697 	return true;
698 }
699 
700 size_t
memorystatus_pick_freeze_count_for_wakeup()701 memorystatus_pick_freeze_count_for_wakeup()
702 {
703 	size_t num_to_freeze = 0;
704 	if (!memorystatus_swap_all_apps) {
705 		num_to_freeze = 1;
706 	} else {
707 		/*
708 		 * When app swap is enabled, we want the freezer thread to aggressively freeze
709 		 * all candidates so we clear out space for the fg working set.
710 		 * But we still cap it to the current size of the candidate bands to avoid
711 		 * consuming excessive CPU if there's a lot of churn in the candidate band.
712 		 */
713 		proc_list_lock();
714 		for (unsigned int band = JETSAM_PRIORITY_IDLE; band <= memorystatus_freeze_max_candidate_band; band++) {
715 			num_to_freeze += memstat_bucket[band].count;
716 		}
717 		proc_list_unlock();
718 	}
719 
720 	return num_to_freeze;
721 }
722 
723 #endif /* CONFIG_FREEZE */
724